@muse-code/sdk 1.3.0 → 1.4.4

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.
@@ -0,0 +1,81 @@
1
+ /**
2
+ * The typed failure of `MuseClient.spawn` when the host is lost before the
3
+ * SS1.4 handshake completes (#49791).
4
+ *
5
+ * Without it the rejection is whatever the transport saw first — `write
6
+ * EPIPE` on the first frame, or `connection reached EOF` — while the evidence
7
+ * that explains it (Node's spawn error, or the SS2.11 exit row with its
8
+ * bounded stderr tail) sits unread on the child the facade already owns.
9
+ * Spec 14990 Scenario 4 attaches that evidence to every process-exit error;
10
+ * this module is the handshake-failure arm of that rule.
11
+ */
12
+ /** How many tail lines the message quotes; `stderrTail` carries them all. */
13
+ const MESSAGE_TAIL_LINES = 5;
14
+ /**
15
+ * `MuseClient.spawn` lost its host before the handshake completed.
16
+ *
17
+ * Typed rather than a bare `Error` because the two arms of `failure` name
18
+ * STATES an embedder branches on (retry after fixing the path, versus act on
19
+ * an SS2.11 retry posture). The transport error that first surfaced the loss
20
+ * rides as `cause`, so nothing the old rejection carried is dropped.
21
+ */
22
+ export class MuseHostStartError extends Error {
23
+ failure;
24
+ /**
25
+ * The SDK's bounded stderr tail when the host was lost, one accessor
26
+ * regardless of arm: empty when no process ran, and the only place the
27
+ * evidence lives when the row is `cleanShutdown` (SS2.11 keeps no tail on
28
+ * the clean row; a logger wants the lines either way).
29
+ */
30
+ stderrTail;
31
+ constructor(failure, stderrTail, cause) {
32
+ super(describeHostStartFailure(failure, stderrTail), { cause });
33
+ this.name = "MuseHostStartError";
34
+ this.failure = failure;
35
+ this.stderrTail = stderrTail;
36
+ }
37
+ }
38
+ function describeHostStartFailure(failure, tail) {
39
+ if (failure.kind === "spawnFailed") {
40
+ return `muse host could not be spawned: ${failure.error.message}`;
41
+ }
42
+ const exit = failure.exit;
43
+ const how = exit.kind === "cleanShutdown"
44
+ ? "exit code 0"
45
+ : exit.kind === "crash"
46
+ ? exit.exitSignal !== null
47
+ ? `signal ${exit.exitSignal}`
48
+ : `exit code ${String(exit.exitCode)}`
49
+ : `exit code ${String(exit.exitCode)}${"retry" in exit ? `, retry: ${exit.retry}` : ""}`;
50
+ const quoted = tail.slice(-MESSAGE_TAIL_LINES);
51
+ const evidence = tail.length === 0
52
+ ? "stderr tail: (empty)"
53
+ : `stderr tail${quoted.length < tail.length ? ` (last ${quoted.length} of ${tail.length} lines)` : ""}:\n ${quoted.join("\n ")}`;
54
+ const when = failure.answeredInitialize
55
+ ? "after answering initialize, before the handshake completed"
56
+ : "before answering initialize";
57
+ return `muse host exited ${when}: ${exit.kind} (${how}); ${evidence}`;
58
+ }
59
+ /**
60
+ * Read a lost host's evidence into the typed error. "Lost" is decided by
61
+ * whether the host ANSWERED — whether a response frame came back — never by
62
+ * how it ended: the caller keeps an answer's own error (`MspError`, or a
63
+ * `ProtocolError` carrying the refused frame) and routes only frameless
64
+ * failures here, where the row says how the unanswering host ended.
65
+ *
66
+ * Call only after the handshake's `close()` has settled: the close ladder
67
+ * ends at the child's observed exit (or at its spawn failure), so
68
+ * `child.exit` is already settled here and this never waits on a live host.
69
+ */
70
+ export async function hostStartFailure(child, cause, answeredInitialize) {
71
+ let exit;
72
+ try {
73
+ exit = await child.exit;
74
+ }
75
+ catch (spawnError) {
76
+ // `exit` rejects only with the ChildProcess 'error' payload: Node's own
77
+ // spawn errno (`code` ENOENT, EACCES, …). No other producer reaches it.
78
+ return new MuseHostStartError({ kind: "spawnFailed", error: spawnError }, child.stderrTail, cause);
79
+ }
80
+ return new MuseHostStartError({ kind: "hostExited", exit, answeredInitialize }, child.stderrTail, cause);
81
+ }
@@ -277,6 +277,7 @@ export class Session {
277
277
  case "view/gap":
278
278
  case "turn/retracted": // the turn still reaches its own terminal
279
279
  case "turn/retryScheduled": // non-terminal by contract (SS4.5.1)
280
+ case "turn/foregroundCompleted": // non-terminal by contract (SS4.5.12)
280
281
  case "approval/resolved":
281
282
  case "userInput/requested":
282
283
  case "userInput/settled":
@@ -18,7 +18,15 @@ import { MspError } from "../connection/connection.js";
18
18
  * the guard chain in `#params` is hand-listed — so a regenerated member fails
19
19
  * the BUILD here until it is forwarded.
20
20
  */
21
- const TURN_START_FORWARDED = ["input", "displayText", "ifBusy", "reasoningEffort"];
21
+ const TURN_START_FORWARDED = [
22
+ "input",
23
+ "displayText",
24
+ "ifBusy",
25
+ "reasoningEffort",
26
+ // No "tokenBudget" (#45454): experimental-gated, and this SDK serves the
27
+ // stable surface only.
28
+ "workspaceRoots",
29
+ ];
22
30
  /**
23
31
  * An `MspError` as the pending set reads it (SS4.13's settlement test).
24
32
  *
@@ -163,6 +171,9 @@ export class TurnSubmitter {
163
171
  params.ifBusy = options.ifBusy;
164
172
  if (options.reasoningEffort != null)
165
173
  params.reasoningEffort = options.reasoningEffort;
174
+ // No tokenBudget forward (#45454): experimental-gated, stable SDK omits it.
175
+ if (options.workspaceRoots != null)
176
+ params.workspaceRoots = options.workspaceRoots;
166
177
  return params;
167
178
  }
168
179
  }
@@ -13,7 +13,7 @@
13
13
  * (tdd SS1.4.1) — additive-optional evolution means an older SDK keeps
14
14
  * working against a newer host.
15
15
  */
16
- export declare const EXPECTED_SCHEMA_FINGERPRINT = "sha256:7469c9e352e67def4a59df7e439984d7194fa351e1c8b7abb34060fd977ced81";
16
+ export declare const EXPECTED_SCHEMA_FINGERPRINT = "sha256:7c94f153c41659cb3f1bd3c3e04438be254644cb2a97d65d48edc7449b74858a";
17
17
  /**
18
18
  * What a build-time mismatch MEANS, in the words a human needs at 2am.
19
19
  *
@@ -13,7 +13,7 @@
13
13
  * (tdd SS1.4.1) — additive-optional evolution means an older SDK keeps
14
14
  * working against a newer host.
15
15
  */
16
- export const EXPECTED_SCHEMA_FINGERPRINT = "sha256:7469c9e352e67def4a59df7e439984d7194fa351e1c8b7abb34060fd977ced81";
16
+ export const EXPECTED_SCHEMA_FINGERPRINT = "sha256:7c94f153c41659cb3f1bd3c3e04438be254644cb2a97d65d48edc7449b74858a";
17
17
  /**
18
18
  * What a build-time mismatch MEANS, in the words a human needs at 2am.
19
19
  *
@@ -13,7 +13,8 @@
13
13
  * are neither an item nor a state family:
14
14
  *
15
15
  * - the TURN LIFECYCLE — `turn/started`, `turn/completed`, `turn/retracted`,
16
- * `turn/unqueued`, and the non-terminal `turn/retryScheduled`;
16
+ * `turn/unqueued`, and the non-terminal `turn/retryScheduled` and
17
+ * `turn/foregroundCompleted`;
17
18
  * - the APPROVAL and USER-INPUT view events as fold INPUTS — the pending
18
19
  * sets and their first durable terminal. The decision flow (choosing and
19
20
  * sending a resolution) is the facade's, not the fold's;
@@ -26,7 +27,7 @@
26
27
  * unrecognized `TurnTerminal` is kept verbatim, and a second resolution never
27
28
  * displaces the first durable one.
28
29
  */
29
- import type { ApprovalRequestParams, ApprovalResolvedParams, ApprovalUpdatedParams, Item, ItemCompletedParams, ItemDeltaParams, ItemStartedParams, ItemUpdatedParams, MspNotification, SessionApprovalModeChangedParams, SessionBranchChangedParams, SessionContextUsageParams, SessionGoalChangedParams, SessionModelChangedParams, SessionModelRouteUnservedParams, SessionNameChangedParams, SessionReasoningEffortChangedParams, SessionTodoListChangedParams, SessionTokenUsageParams, TurnCompletedParams, TurnError, TurnRetractedParams, TurnRetryScheduledParams, TurnStartedParams, TurnTerminal, TurnUnqueuedParams, UserInputRequestParams, UserInputSettledParams, ViewGapParams } from "../msp.js";
30
+ import type { ApprovalRequestParams, ApprovalResolvedParams, ApprovalUpdatedParams, Item, ItemCompletedParams, ItemDeltaParams, ItemStartedParams, ItemUpdatedParams, MspNotification, SessionApprovalModeChangedParams, SessionBranchChangedParams, SessionContextUsageParams, SessionGoalChangedParams, SessionModelChangedParams, SessionModelRouteUnservedParams, SessionNameChangedParams, SessionReasoningEffortChangedParams, SessionTodoListChangedParams, SessionTokenUsageParams, TurnCompletedParams, TurnError, TurnForegroundCompletedParams, TurnRetractedParams, TurnRetryScheduledParams, TurnStartedParams, TurnTerminal, TurnUnqueuedParams, UserInputRequestParams, UserInputSettledParams, ViewGapParams } from "../msp.js";
30
31
  import type { DeltaApplyOutcome, ItemApplyOutcome, TerminalUnknownItemAnnotation } from "./item-store.js";
31
32
  import type { StateApplyOutcome, StateValue } from "./state-store.js";
32
33
  /** The session-state families, each keyed in the store by its method name. */
@@ -50,6 +51,9 @@ export type ViewEvent = {
50
51
  } | {
51
52
  readonly method: "turn/completed";
52
53
  readonly params: TurnCompletedParams;
54
+ } | {
55
+ readonly method: "turn/foregroundCompleted";
56
+ readonly params: TurnForegroundCompletedParams;
53
57
  } | {
54
58
  readonly method: "turn/retracted";
55
59
  readonly params: TurnRetractedParams;
@@ -142,6 +146,14 @@ export type ViewEvent = {
142
146
  * before this fold exists. (The `view/gap` exclusion D-24021-1 recorded
143
147
  * was removed by spec 14990 T032 when the marker became the `ViewEvent`
144
148
  * arm above.)
149
+ * - `session/started` and `session/closed` (#33065's enrollment) are SS2.6
150
+ * control-plane lifecycle broadcasts, not view events — they carry no
151
+ * foldable view envelope (no `sourceRange`; `closed`'s `viewCursor` is a
152
+ * final session head, not view state), and a fold over session-view state
153
+ * has nothing to apply. Today a lifecycle frame keeps the pre-enrollment
154
+ * runtime answer (`ignoredUnrecognizedMethod`, pinned by the session-fold
155
+ * test); #33102 owns consciously surfacing the pair, the same sanctioned
156
+ * initial-drop shape D-24021-1 used for `view/gap` before T032 flipped it.
145
157
  * - `session/viewHealthChanged` (#32557, ADR 32557) is a COMMAND-PLANE
146
158
  * health push, not a view-fold event: it reports that the live view
147
159
  * stream stopped, so it carries no cursor and folds into no transcript
@@ -159,7 +171,8 @@ export type ViewEvent = {
159
171
  */
160
172
  type AssertNever<T extends never> = T;
161
173
  type LiveHostStateProjection = "skill/changed" | "usage/changed" | "session/statusChanged" | "session/listChanged";
162
- type NonFoldNotification = "initialized" | "session/viewHealthChanged" | LiveHostStateProjection;
174
+ type SessionLifecycleBroadcast = "session/started" | "session/closed";
175
+ type NonFoldNotification = "initialized" | "userInput/engaged" | "session/viewHealthChanged" | SessionLifecycleBroadcast | LiveHostStateProjection;
163
176
  type UnfoldedViewNotification = Exclude<MspNotification, NonFoldNotification | ViewEvent["method"]>;
164
177
  export type EveryViewNotificationIsFolded = AssertNever<UnfoldedViewNotification>;
165
178
  /**
@@ -171,11 +184,11 @@ export type EveryViewNotificationIsFolded = AssertNever<UnfoldedViewNotification
171
184
  type StaleViewArm = Exclude<ViewEvent["method"], MspNotification>;
172
185
  export type NoStaleViewArm = AssertNever<StaleViewArm>;
173
186
  /**
174
- * The same reverse pin for the hand-typed exclusion literal above:
187
+ * The same reverse pin for the hand-typed exclusion literals above:
175
188
  * `Exclude` silently ignores excluder members outside the union, so a
176
- * retired or renamed `initialized` would otherwise compile clean as dead
177
- * vocabulary (the PR #23087 rule, applied to this file's only other
178
- * hand-typed method set).
189
+ * retired or renamed `initialized` — or a lifecycle name that leaves the
190
+ * union — would otherwise compile clean as dead vocabulary (the PR #23087
191
+ * rule, applied to this file's only other hand-typed method set).
179
192
  */
180
193
  type StaleExclusion = Exclude<NonFoldNotification, MspNotification>;
181
194
  export type NoStaleExclusion = AssertNever<StaleExclusion>;
@@ -205,7 +218,7 @@ export type SessionStateMethod = ViewEvent["method"] & `session/${string}`;
205
218
  * and could never match exhaustively. A future arm that starts dropping
206
219
  * widens this deliberately (PR #23087 review round).
207
220
  */
208
- export type StaleDroppableMethod = "turn/started" | "turn/completed" | "turn/retryScheduled" | "approval/requested" | "approval/updated" | "userInput/requested";
221
+ export type StaleDroppableMethod = "turn/started" | "turn/completed" | "turn/foregroundCompleted" | "turn/retryScheduled" | "approval/requested" | "approval/updated" | "userInput/requested";
209
222
  /**
210
223
  * The `NoStaleViewArm` sibling for the union above: these are hand-typed
211
224
  * literals, so without this pin a typo'd or later-retired member compiles
@@ -228,6 +241,12 @@ export interface TurnEntry {
228
241
  readonly error?: TurnError;
229
242
  /** The latest scheduled model retry; non-terminal (tdd SS4.5.1, D-026). */
230
243
  readonly retryScheduled?: TurnRetryScheduledParams;
244
+ /**
245
+ * The latest foreground-completed notice; non-terminal (tdd SS4.5.12).
246
+ * Tells a renderer the answer is done while `blockingAgents` hold the
247
+ * turn; clears on the turn's terminal.
248
+ */
249
+ readonly foregroundCompleted?: TurnForegroundCompletedParams;
231
250
  }
232
251
  /** An approval awaiting its first durable terminal. */
233
252
  export interface PendingApproval {
@@ -13,7 +13,8 @@
13
13
  * are neither an item nor a state family:
14
14
  *
15
15
  * - the TURN LIFECYCLE — `turn/started`, `turn/completed`, `turn/retracted`,
16
- * `turn/unqueued`, and the non-terminal `turn/retryScheduled`;
16
+ * `turn/unqueued`, and the non-terminal `turn/retryScheduled` and
17
+ * `turn/foregroundCompleted`;
17
18
  * - the APPROVAL and USER-INPUT view events as fold INPUTS — the pending
18
19
  * sets and their first durable terminal. The decision flow (choosing and
19
20
  * sending a resolution) is the facade's, not the fold's;
@@ -162,6 +163,8 @@ export class SessionFold {
162
163
  return this.#turnUnqueued(typed.params);
163
164
  case "turn/retryScheduled":
164
165
  return this.#turnRetryScheduled(typed.params);
166
+ case "turn/foregroundCompleted":
167
+ return this.#turnForegroundCompleted(typed.params);
165
168
  case "approval/requested":
166
169
  return this.#approvalRequested(typed.params);
167
170
  case "approval/updated":
@@ -265,6 +268,9 @@ export class SessionFold {
265
268
  // turn's next event — which a completion is (tdd SS4.5.1). Leaving it set
266
269
  // makes a renderer show the countdown on a finished turn.
267
270
  turn.retryScheduled = undefined;
271
+ // Same for the foreground hint: a finished turn is not background-waiting
272
+ // (tdd SS4.5.12).
273
+ turn.foregroundCompleted = undefined;
268
274
  this.#clearActive(params.turnId);
269
275
  return { kind: "turn", turnId: params.turnId, state: turn.state };
270
276
  }
@@ -304,6 +310,18 @@ export class SessionFold {
304
310
  turn.retryScheduled = params;
305
311
  return { kind: "turn", turnId: params.turnId, state: turn.state };
306
312
  }
313
+ #turnForegroundCompleted(params) {
314
+ // Non-terminal by contract: it never resolves a turn-wait (tdd SS4.5.12).
315
+ const turn = this.#turnFor(params.turnId);
316
+ // …but it is still a turn frame, so it takes the same redelivery guard
317
+ // as the retry hint: a replayed page must not re-plant the
318
+ // background-wait hint on a turn that already left `running`.
319
+ if (turn.state !== "running") {
320
+ return { kind: "ignoredStaleFrame", method: "turn/foregroundCompleted", id: params.turnId };
321
+ }
322
+ turn.foregroundCompleted = params;
323
+ return { kind: "turn", turnId: params.turnId, state: turn.state };
324
+ }
307
325
  #turnFor(turnId) {
308
326
  const held = this.#turns.get(turnId);
309
327
  if (held !== undefined)
@@ -324,6 +342,9 @@ export class SessionFold {
324
342
  ...(turn.terminal !== undefined ? { terminal: turn.terminal } : {}),
325
343
  ...(turn.error !== undefined ? { error: turn.error } : {}),
326
344
  ...(turn.retryScheduled !== undefined ? { retryScheduled: turn.retryScheduled } : {}),
345
+ ...(turn.foregroundCompleted !== undefined
346
+ ? { foregroundCompleted: turn.foregroundCompleted }
347
+ : {}),
327
348
  };
328
349
  }
329
350
  // ---- the delivery-plane marker ------------------------------------------
@@ -54,6 +54,8 @@ export { MuseForeignSessionError, MuseGapFillError, MuseSessionDiscardedError, }
54
54
  export type { GapFillFailureReason } from "./errors.js";
55
55
  export type { GapFillFailureHandler } from "./facade/gap-fill.js";
56
56
  export { MuseHostDiedError, readSessionDurability } from "./facade/host-death.js";
57
+ export { MuseHostStartError } from "./facade/host-start.js";
58
+ export type { HostStartFailure } from "./facade/host-start.js";
57
59
  export type { AbnormalExit, HostDeathDischarge, HostDeathNotification, SessionDurabilityProfile, TransportEof, } from "./facade/host-death.js";
58
60
  export { Session } from "./facade/session.js";
59
61
  export type { PendingCommandView, SessionApplyOutcome, SessionApplyRefusal, SessionFoldView, SessionGapBuffered, SessionGapOverlap, SessionOpening, SessionOptions, } from "./facade/session.js";
package/dist/src/index.js CHANGED
@@ -46,6 +46,11 @@ export { MuseForeignSessionError, MuseGapFillError, MuseSessionDiscardedError, }
46
46
  // with no consumer, and a barrel export would freeze them into `@muse-code/sdk`'s
47
47
  // contract the moment #211 adopts the package.
48
48
  export { MuseHostDiedError, readSessionDurability } from "./facade/host-death.js";
49
+ // The #49791 handshake-failure arm of Scenario 4: `MuseClient.spawn`'s typed
50
+ // rejection when the host is lost before the handshake completes. The
51
+ // reader `hostStartFailure` stays OFF the barrel (Constitution XI): it is
52
+ // `spawn`'s internal with no consumer.
53
+ export { MuseHostStartError } from "./facade/host-start.js";
49
54
  export { Session } from "./facade/session.js";
50
55
  // `Turn` (the narrow consumer view), not `TurnHandle`: the concrete class's
51
56
  // Session-fed mutators would let an embedder fabricate a terminal (INV-006).