@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,51 @@
1
+ /**
2
+ * Typed errors shared by the stores and the facade.
3
+ *
4
+ * They live here rather than in `facade/` because the stores throw them too,
5
+ * and a store importing from the facade would invert the layering. Typed
6
+ * rather than bare `Error` because each names a STATE an embedder must branch
7
+ * on; the only alternative is matching message text, which silently turns
8
+ * those strings into the package's contract.
9
+ */
10
+ /**
11
+ * The session was discarded after an ephemeral host's abnormal death, and the
12
+ * operation attempted would either resurrect it or replay against a new host
13
+ * (tdd SS2.13.3b, SS3.1.3).
14
+ */
15
+ export class MuseSessionDiscardedError extends Error {
16
+ constructor(message) {
17
+ super(message);
18
+ this.name = "MuseSessionDiscardedError";
19
+ }
20
+ }
21
+ /** An event whose `sessionId` names a different session than the one folding it. */
22
+ export class MuseForeignSessionError extends Error {
23
+ constructor(message) {
24
+ super(message);
25
+ this.name = "MuseForeignSessionError";
26
+ }
27
+ }
28
+ /**
29
+ * A gap the client could not fill (spec 14990 FR-020, tdd SS4.8).
30
+ *
31
+ * REPORTED to `Session.onGapError`, never thrown: the fill is driven from a
32
+ * notification, so a throw would escape into the consumer's pump with nothing
33
+ * to catch it. Typed rather than a bare `Error` because the hole it names is a
34
+ * STATE a consumer must branch on — the fold stays not-current until a later
35
+ * recovery, and `(after, next)` names exactly what is missing. Reporting it is
36
+ * what makes the hole loud instead of silent, which is the half of FR-020 the
37
+ * fill itself cannot deliver.
38
+ */
39
+ export class MuseGapFillError extends Error {
40
+ reason;
41
+ /** The gap's own bounds, verbatim and opaque (tdd SS4.1). */
42
+ after;
43
+ next;
44
+ constructor(reason, after, next, cause) {
45
+ super(`view/gap (${after}, ${next}) could not be filled: ${reason}`, { cause });
46
+ this.name = "MuseGapFillError";
47
+ this.reason = reason;
48
+ this.after = after;
49
+ this.next = next;
50
+ }
51
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * The FR-019 approval round trip: inbound `approval/requested` → the consumer's
3
+ * handler → outbound `approval/decide` (spec 14990 T031, tdd SS5.4).
4
+ *
5
+ * Split out of `session.ts` rather than added to it: the router owns a handler,
6
+ * a per-stage latch, and a decision-shaping guard chain that have nothing to do
7
+ * with folding a view, and `Session` was already the package's largest module.
8
+ *
9
+ * SHAPE NOTE, established from the bundle rather than assumed. `approval/request`
10
+ * as a SERVER REQUEST is not enrolled — the schema carries `approval/requested`
11
+ * as a NOTIFICATION only — so the round trip is notification-in /
12
+ * command-out, which is exactly the pair FR-019 names. The server-request form
13
+ * would be a #206 enrollment request (INV-001), never a local interface.
14
+ */
15
+ import type { Connection } from "../connection/connection.js";
16
+ import type { ApprovalDecideParams, ApprovalRequestParams } from "@muse-code/msp";
17
+ /**
18
+ * What an approval handler answers with: a choice the SERVER offered, and
19
+ * optional feedback. Composed from the generated decide params, so "the client
20
+ * picks a `choiceId`" stays one fact rather than two that can drift.
21
+ *
22
+ * D-006 is select-never-create, and this TYPE cannot enforce it — `choiceId` is
23
+ * a `string` on the wire — so the router checks the answer against the
24
+ * request's own `availableChoices` before the frame is built.
25
+ */
26
+ export type ApprovalDecisionInput = Readonly<Pick<ApprovalDecideParams, "choiceId" | "feedback">>;
27
+ /** FR-019: the consumer's decision callback. May be sync or async. */
28
+ export type ApprovalHandler = (request: ApprovalRequestParams) => ApprovalDecisionInput | Promise<ApprovalDecisionInput>;
29
+ /**
30
+ * Why one approval round trip did not complete.
31
+ *
32
+ * REPORTED, not thrown: the trip is driven from a notification, so a throw
33
+ * would escape into the consumer's pump with nothing to catch it — the same
34
+ * hazard `Session.apply` already refuses a malformed frame for. Each arm names
35
+ * a DIFFERENT owner (the consumer's handler, the consumer's choice, the host),
36
+ * because the repair differs.
37
+ */
38
+ export type ApprovalFailure = {
39
+ readonly kind: "unofferedChoice";
40
+ readonly approvalId: string;
41
+ readonly choiceId: string;
42
+ readonly availableChoiceIds: readonly string[];
43
+ } | {
44
+ readonly kind: "handlerThrew";
45
+ readonly approvalId: string;
46
+ readonly error: unknown;
47
+ } | {
48
+ readonly kind: "submitFailed";
49
+ readonly approvalId: string;
50
+ readonly error: unknown;
51
+ };
52
+ /** Receives each `ApprovalFailure`; the failure's `kind` names what went wrong and whose repair it is. */
53
+ export type ApprovalFailureHandler = (failure: ApprovalFailure) => void;
54
+ export declare class ApprovalRouter {
55
+ #private;
56
+ constructor(sessionId: string, connection: Connection | undefined);
57
+ /**
58
+ * Register the decision callback (FR-019).
59
+ *
60
+ * REPLACES any previous handler rather than adding to a list: two handlers
61
+ * would race to decide one approval and only one decision can win, so the
62
+ * loser's would be silently discarded.
63
+ */
64
+ onApproval(handler: ApprovalHandler): void;
65
+ /** Observe round trips that did not complete. See {@link ApprovalFailure}. */
66
+ onApprovalError(handler: ApprovalFailureHandler): void;
67
+ /**
68
+ * An `approval/requested` folded. Returns the decision round trip to await,
69
+ * or `undefined` when this client authors nothing for it.
70
+ *
71
+ * No handler at all is the supported default posture, NOT a degraded one
72
+ * (D-008): the client runs under the server's own default-deny, and this SDK
73
+ * parks nothing — no queued decision, no synthesized denial, no local hold.
74
+ */
75
+ requested(params: ApprovalRequestParams): Promise<void> | undefined;
76
+ }
@@ -0,0 +1,165 @@
1
+ /**
2
+ * The FR-019 approval round trip: inbound `approval/requested` → the consumer's
3
+ * handler → outbound `approval/decide` (spec 14990 T031, tdd SS5.4).
4
+ *
5
+ * Split out of `session.ts` rather than added to it: the router owns a handler,
6
+ * a per-stage latch, and a decision-shaping guard chain that have nothing to do
7
+ * with folding a view, and `Session` was already the package's largest module.
8
+ *
9
+ * SHAPE NOTE, established from the bundle rather than assumed. `approval/request`
10
+ * as a SERVER REQUEST is not enrolled — the schema carries `approval/requested`
11
+ * as a NOTIFICATION only — so the round trip is notification-in /
12
+ * command-out, which is exactly the pair FR-019 names. The server-request form
13
+ * would be a #206 enrollment request (INV-001), never a local interface.
14
+ */
15
+ /**
16
+ * Every `DecideParams` member the guard chain below forwards. Composition alone
17
+ * does not stop drift — the chain is hand-listed — so a regenerated member
18
+ * fails the BUILD here until it is forwarded, exactly as `MuseClient`'s two
19
+ * chains do.
20
+ */
21
+ const DECIDE_FORWARDED = [
22
+ "approvalId",
23
+ "choiceId",
24
+ "requirementId",
25
+ "sessionId",
26
+ "feedback",
27
+ ];
28
+ export class ApprovalRouter {
29
+ #sessionId;
30
+ #connection;
31
+ #handler;
32
+ #onFailure;
33
+ /**
34
+ * Approval STAGES already decided, keyed by `approvalId` + `requirementId`.
35
+ *
36
+ * Not `approvalId` alone: `requirementId` is SS5.4's multi-stage race guard,
37
+ * so a stage-2 request must get its own decision or the approval pends
38
+ * forever. Not per-request either: a redelivered `approval/requested` for the
39
+ * SAME stage must author no second decide, or a two-stage approval races
40
+ * itself. The key is kept on FAILURE too — a genuinely advancing stage brings
41
+ * a new `requirementId` and therefore a new key, so "ask the consumer once
42
+ * per stage" holds absolutely.
43
+ */
44
+ #decidedStages = new Set();
45
+ constructor(sessionId, connection) {
46
+ this.#sessionId = sessionId;
47
+ this.#connection = connection;
48
+ }
49
+ /**
50
+ * Register the decision callback (FR-019).
51
+ *
52
+ * REPLACES any previous handler rather than adding to a list: two handlers
53
+ * would race to decide one approval and only one decision can win, so the
54
+ * loser's would be silently discarded.
55
+ */
56
+ onApproval(handler) {
57
+ this.#handler = handler;
58
+ }
59
+ /** Observe round trips that did not complete. See {@link ApprovalFailure}. */
60
+ onApprovalError(handler) {
61
+ this.#onFailure = handler;
62
+ }
63
+ /**
64
+ * An `approval/requested` folded. Returns the decision round trip to await,
65
+ * or `undefined` when this client authors nothing for it.
66
+ *
67
+ * No handler at all is the supported default posture, NOT a degraded one
68
+ * (D-008): the client runs under the server's own default-deny, and this SDK
69
+ * parks nothing — no queued decision, no synthesized denial, no local hold.
70
+ */
71
+ requested(params) {
72
+ const handler = this.#handler;
73
+ if (handler === undefined)
74
+ return undefined;
75
+ const stage = ApprovalRouter.#stageKey(params);
76
+ if (this.#decidedStages.has(stage))
77
+ return undefined;
78
+ // Latched BEFORE the first await: a redelivery folded on the very next
79
+ // frame must find the stage already claimed, and an `await` boundary here
80
+ // would let both pass the check.
81
+ this.#decidedStages.add(stage);
82
+ return this.#decide(params, handler);
83
+ }
84
+ static #stageKey(params) {
85
+ const requirement = params.currentRequirementId;
86
+ return `${params.approvalId} ${requirement.approvalId}:${String(requirement.sourceIndex)}`;
87
+ }
88
+ async #decide(params, handler) {
89
+ const connection = this.#connection;
90
+ // Checked BEFORE the handler runs: asking a consumer to decide and then
91
+ // dropping the answer is worse than not asking, and on a fold-only session
92
+ // that is all this could do.
93
+ if (connection === undefined) {
94
+ // A plain `Error`: constructing fold-only and then registering a decide
95
+ // handler is API misuse, not the foreign-frame STATE
96
+ // `MuseForeignSessionError` names — a typed class here would send an
97
+ // embedder's routing-bug branch chasing a session mismatch that never
98
+ // happened.
99
+ this.#report({
100
+ approvalId: params.approvalId,
101
+ error: new Error("approval/decide needs a connection; this Session was constructed fold-only"),
102
+ kind: "submitFailed",
103
+ });
104
+ return;
105
+ }
106
+ let decision;
107
+ try {
108
+ decision = await handler(params);
109
+ }
110
+ catch (error) {
111
+ this.#report({ approvalId: params.approvalId, error, kind: "handlerThrew" });
112
+ return;
113
+ }
114
+ const availableChoiceIds = params.availableChoices.map((choice) => choice.choiceId);
115
+ if (!availableChoiceIds.includes(decision.choiceId)) {
116
+ // D-006 select-never-create, enforced on THIS side of the transport. An
117
+ // invented choice bounces -32052 a round trip later, by which time the
118
+ // stage may have advanced — so the diagnosis a consumer would actually
119
+ // see is a stale-requirement error about a frame it should never have
120
+ // sent.
121
+ this.#report({
122
+ approvalId: params.approvalId,
123
+ availableChoiceIds,
124
+ choiceId: decision.choiceId,
125
+ kind: "unofferedChoice",
126
+ });
127
+ return;
128
+ }
129
+ const decideParams = {
130
+ approvalId: params.approvalId,
131
+ choiceId: decision.choiceId,
132
+ // Echoed from the request, never remembered: SS5.4 makes a stale value a
133
+ // -32053, and the request in hand is the only current statement of it.
134
+ requirementId: params.currentRequirementId,
135
+ sessionId: this.#sessionId,
136
+ };
137
+ // Loose guard, and omitted rather than nulled (SS1.2): `feedback` is valid
138
+ // only on choices with `acceptsFeedback`, so an explicit null forwarded by
139
+ // a plain-JS caller would be rejected by the host.
140
+ if (decision.feedback != null)
141
+ decideParams.feedback = decision.feedback;
142
+ try {
143
+ // No explicit `commandId`: unlike `sendUserTurn`, nothing here needs the
144
+ // id before the ack, so `Connection.command()` mints and stamps it — and
145
+ // its own SS3.1.1 retry then reuses that id for free.
146
+ await connection.command("approval/decide", decideParams);
147
+ }
148
+ catch (error) {
149
+ this.#report({ approvalId: params.approvalId, error, kind: "submitFailed" });
150
+ }
151
+ }
152
+ #report(failure) {
153
+ try {
154
+ this.#onFailure?.(failure);
155
+ }
156
+ catch {
157
+ // The consumer's failure OBSERVER threw. Swallowed, deliberately: a
158
+ // rejection escaping here rides `SessionApplyOutcome.io`, whose contract
159
+ // is "IT NEVER REJECTS" — and since most consumers never await `io`, it
160
+ // would surface as an unhandled rejection that kills the embedder, the
161
+ // exact failure that contract exists to prevent. The failure itself was
162
+ // already handed to the observer; there is no one left to tell.
163
+ }
164
+ }
165
+ }
@@ -0,0 +1,153 @@
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 type { Connection } from "../connection/connection.js";
39
+ import type { ExitClassification, SpawnedMspConnection } from "../connection/spawn.js";
40
+ import type { SessionDurabilityProfile } from "./host-death.js";
41
+ import { Session } from "./session.js";
42
+ import type { InitializeParams, InitializeResult, SessionResumeParams, SessionStartParams } from "@muse-code/msp";
43
+ /**
44
+ * Caller-facing options for `session/start` (tdd SS2.5.1).
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.
49
+ */
50
+ export type StartSessionOptions = Readonly<Omit<SessionStartParams, "commandId" | "config">>;
51
+ /** Caller-facing options for `session/resume` (tdd SS2.5.2). */
52
+ export type ResumeSessionOptions = Readonly<Omit<SessionResumeParams, "commandId">>;
53
+ /**
54
+ * Options for building a `MuseClient` around a connection you already own.
55
+ * `MuseClient.spawn` fills these in for you; supply them yourself only when
56
+ * you compose the client with your own transport and handshake.
57
+ */
58
+ export interface MuseClientOptions {
59
+ /**
60
+ * The handshake's `sessionDurability`, read through `readSessionDurability`.
61
+ *
62
+ * REQUIRED, for the same reason `SessionOptions.durability` is: it decides
63
+ * what happens to every in-flight item and command when the host dies
64
+ * (SS2.13.3b), and a default would let a caller skip reading the handshake
65
+ * and silently inherit the wrong obligation. `MuseClient.spawn` supplies it.
66
+ */
67
+ readonly durability: SessionDurabilityProfile;
68
+ /**
69
+ * The owned host, set by `MuseClient.spawn`. A client built around a
70
+ * connection somebody else owns has none, and says so by omitting it — which
71
+ * is why `close()` falls back to closing just the connection.
72
+ */
73
+ readonly host?: SpawnedMspConnection;
74
+ }
75
+ /** What `MuseClient.spawn` needs: FR-018's `{ museBin, args?, env? }`, plus the handshake. */
76
+ export interface MuseClientSpawnOptions {
77
+ readonly museBin: string;
78
+ readonly args?: readonly string[];
79
+ readonly cwd?: string;
80
+ /** REPLACES the child's environment (PATH included) — spread `process.env` to extend it. */
81
+ readonly env?: NodeJS.ProcessEnv;
82
+ /** Client identification, forwarded verbatim into `initialize` (SS1.4). */
83
+ readonly clientInfo: InitializeParams["clientInfo"];
84
+ /** Capability posture; absent means all defaults. */
85
+ readonly capabilities?: InitializeParams["capabilities"];
86
+ /** Raw stderr chunks, drained from process birth and never parsed (INV-010). */
87
+ readonly onStderr?: (chunk: string) => void;
88
+ /** See `MuseServeChildOptions.shutdownTimeoutMs`. */
89
+ readonly shutdownTimeoutMs?: number;
90
+ }
91
+ /**
92
+ * Your entry point to the SDK.
93
+ *
94
+ * Spawn a host with `MuseClient.spawn`, then open conversations with
95
+ * `startSession` or `resumeSession`. The client owns the connection: it
96
+ * routes every server event to the session it belongs to and reports a host
97
+ * death to all of them. Call `close` to shut the host down cleanly.
98
+ */
99
+ export declare class MuseClient {
100
+ #private;
101
+ constructor(connection: Connection, options: MuseClientOptions);
102
+ /**
103
+ * Spawn an owned host, run the SS1.4 handshake, and hand back a client whose
104
+ * durability profile came from that handshake (FR-018).
105
+ *
106
+ * The profile is READ rather than asked of the caller, which is the whole
107
+ * reason this factory exists beside the bare constructor: SS2.13.1 makes the
108
+ * absent/unrecognized distinction load-bearing, and a caller re-deriving it
109
+ * by hand is a caller that can get it wrong.
110
+ */
111
+ static spawn(options: MuseClientSpawnOptions): Promise<MuseClient>;
112
+ /**
113
+ * The handshake result, when this client was built by `spawn`.
114
+ *
115
+ * A plain `Error`, not a typed one: reading this off a client that was not
116
+ * built by `spawn` is API misuse, not a protocol STATE an embedder branches
117
+ * on — a typed class here would send the SS2.13.3b recovery path chasing a
118
+ * host death that never happened.
119
+ */
120
+ get initializeResult(): InitializeResult;
121
+ /** The host's SS2.11 exit row, when this client was built by `spawn`. */
122
+ get exit(): Promise<ExitClassification>;
123
+ /** The durability profile every session this client opens inherits. */
124
+ get durability(): SessionDurabilityProfile;
125
+ /** Open a new root session (tdd SS2.5.1). */
126
+ startSession(options?: StartSessionOptions): Promise<Session>;
127
+ /**
128
+ * Load an existing session and subscribe this connection to its view
129
+ * (tdd SS2.5.2).
130
+ *
131
+ * WITHHELD after an ephemeral host death (SS2.13.3b clause 2, "do not attempt
132
+ * to reattach"), and refused on THIS side of the transport: a reattach
133
+ * attempt that reaches the wire has already violated the clause, whatever the
134
+ * server answers.
135
+ */
136
+ resumeSession(options: ResumeSessionOptions): Promise<Session>;
137
+ /**
138
+ * Shut the host down in an orderly way (SS2.1.2); the shutdown this causes
139
+ * is not reported to your sessions as a host death.
140
+ *
141
+ * The EOF this close produces is NOT a death, which is what `#closing`
142
+ * records.
143
+ *
144
+ * `#closing` covers only the EOF; it must not swallow the EXIT ROW. When the
145
+ * host ignores stdin EOF, `#child.close()` escalates to SIGTERM/SIGKILL and
146
+ * the exit classifies as a crash — an abnormal death under SS2.13.3b no
147
+ * matter who started the close, and one no transport event will ever report
148
+ * here because `#closing` already claimed the EOF. So the classification the
149
+ * close itself returns is forwarded to every session: `hostExited` answers
150
+ * `notADeath` for `cleanShutdown`, keeping the orderly arm inert.
151
+ */
152
+ close(): Promise<void>;
153
+ }