@muse-code/sdk 1.4.2 → 1.4.6

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.
@@ -35,10 +35,12 @@
35
35
  * chain close that gap — add a member upstream and the BUILD fails here until
36
36
  * it is forwarded (or explicitly allow-listed as unforwardable).
37
37
  */
38
- import { spawnMspConnection } from "../connection/spawn.js";
39
- import { MuseSessionDiscardedError } from "../errors.js";
38
+ import { initializeAnswered, spawnMspConnection } from "../connection/spawn.js";
39
+ import { MuseSessionDiscardedError, PermissionProfileNotApplied } from "../errors.js";
40
40
  import { DiscardedSessions } from "./discarded.js";
41
41
  import { isAbnormalHostDeath, readSessionDurability } from "./host-death.js";
42
+ import { MspError, ProtocolError } from "../connection/connection.js";
43
+ import { hostStartFailure } from "./host-start.js";
42
44
  import { Session } from "./session.js";
43
45
  /**
44
46
  * Every `StartParams` member `startSession` forwards. `config` is temporarily
@@ -52,12 +54,29 @@ const START_FORWARDED = [
52
54
  "workspaceRoot",
53
55
  "workspaceRoots",
54
56
  "modelId",
57
+ "permissionProfile",
55
58
  ];
56
59
  /**
57
60
  * Every `ResumeParams` member `resumeSession` forwards. `config` has the same
58
61
  * temporary capability-check boundary as the start facade above.
59
62
  */
60
63
  const RESUME_FORWARDED = ["sessionId", "cursor", "excludeItems", "history"];
64
+ /**
65
+ * The committed profile id a session snapshot claims, or null when the
66
+ * snapshot is silent (the stable bundle strips the member; absent and null
67
+ * both mean unknown, never applied). Structural on purpose: the stable
68
+ * `Session` type carries no `permissionState`, and an unknown wire shape
69
+ * must read as unknown rather than throw.
70
+ */
71
+ function committedProfileId(snapshot) {
72
+ if (typeof snapshot !== "object" || snapshot === null)
73
+ return null;
74
+ const state = snapshot.permissionState;
75
+ if (typeof state !== "object" || state === null)
76
+ return null;
77
+ const id = state.profileId;
78
+ return typeof id === "string" ? id : null;
79
+ }
61
80
  /**
62
81
  * Your entry point to the SDK.
63
82
  *
@@ -72,6 +91,15 @@ export class MuseClient {
72
91
  #discarded;
73
92
  /** Sessions this client opened, so one death notification reaches them all. */
74
93
  #sessions = new Set();
94
+ /**
95
+ * Frames naming a session this client has not registered YET, held only
96
+ * while a `session/start`/`session/resume` is in flight (#49790): the host
97
+ * flushes the resume replay BEFORE the result, and the promise awaiting that
98
+ * result resumes only after the whole chunk has been routed. `#route` holds,
99
+ * `#openSession` drains, `#open` clears when the last open settles.
100
+ */
101
+ #held = new Map();
102
+ #opening = 0;
75
103
  /** The spawned host, when `spawn` built this client. */
76
104
  #child;
77
105
  #initializeResult;
@@ -113,16 +141,29 @@ export class MuseClient {
113
141
  * session: `Session.apply` already tolerates unknown methods, but only the
114
142
  * frames that name a `sessionId` have an owner to route to. A frame naming
115
143
  * an UNKNOWN session is dropped for the same reason — routing it anywhere
116
- * would trip the foreign-frame throw on a session it does not belong to.
144
+ * would trip the foreign-frame throw on a session it does not belong to —
145
+ * UNLESS an open is in flight, when it may be that open's own session named
146
+ * by the server before the awaiting promise has run (#49790): then it is
147
+ * held for `#openSession` to fold, or for `#open` to clear.
117
148
  */
118
149
  #route(notification) {
119
150
  const named = notification.params?.sessionId;
120
151
  if (typeof named !== "string")
121
152
  return;
153
+ let delivered = false;
122
154
  for (const session of this.#sessions) {
123
- if (session.sessionId === named)
155
+ if (session.sessionId === named) {
124
156
  session.apply(notification);
157
+ delivered = true;
158
+ }
125
159
  }
160
+ if (delivered || this.#opening === 0)
161
+ return;
162
+ const held = this.#held.get(named);
163
+ if (held === undefined)
164
+ this.#held.set(named, [notification]);
165
+ else
166
+ held.push(notification);
126
167
  }
127
168
  /**
128
169
  * Spawn an owned host, run the SS1.4 handshake, and hand back a client whose
@@ -132,6 +173,15 @@ export class MuseClient {
132
173
  * reason this factory exists beside the bare constructor: SS2.13.1 makes the
133
174
  * absent/unrecognized distinction load-bearing, and a caller re-deriving it
134
175
  * by hand is a caller that can get it wrong.
176
+ *
177
+ * Rejects with {@link MuseHostStartError} when the host is lost before the
178
+ * handshake completes (the binary could not be spawned, or the process
179
+ * ended first — exit code or signal plus the bounded stderr tail;
180
+ * `answeredInitialize` says whether it died after a usable answer). A host
181
+ * that answers with a reply the SDK refuses keeps its own error: an
182
+ * `MspError` for an SS1.6 refusal, or a `ProtocolError` (with the whole
183
+ * refused frame on `line`) for a reply the SDK cannot use, such as one with
184
+ * no schema fingerprint.
135
185
  */
136
186
  static async spawn(options) {
137
187
  const handshake = spawnMspConnection({
@@ -154,7 +204,23 @@ export class MuseClient {
154
204
  catch (error) {
155
205
  // A failed handshake must not leak the process it already spawned.
156
206
  await handshake.close().catch(() => undefined);
157
- throw error;
207
+ // A host that ANSWERED `initialize` is not a lost host, however it ends
208
+ // once we close it: its answer is the actionable error. "Answered" is
209
+ // evidence that a response frame came back — an SS1.6 `MspError`, or a
210
+ // `ProtocolError` carrying the frame the SDK refused (a malformed or
211
+ // version-skewed reply) — never the error's class alone (#49912).
212
+ // Decided before the exit is read, so our own close ladder can never
213
+ // dress an answer up as a death.
214
+ const answered = error instanceof MspError || (error instanceof ProtocolError && error.line !== undefined);
215
+ if (answered)
216
+ throw error;
217
+ // No refused frame: the host was lost — before answering, or after a
218
+ // usable answer while we sent `initialized` (the error then says so).
219
+ // close() ended at its observed exit (or its spawn failure), so the
220
+ // evidence is settled: the typed error carries the spawn error or the
221
+ // SS2.11 row plus the stderr tail instead of the transport's first
222
+ // symptom (#49791, #49912).
223
+ throw await hostStartFailure(handshake.child, error, handshake[initializeAnswered]());
158
224
  }
159
225
  return new MuseClient(spawned.connection, {
160
226
  durability: readSessionDurability(spawned.initializeResult),
@@ -203,15 +269,58 @@ export class MuseClient {
203
269
  params.workspaceRoots = options.workspaceRoots;
204
270
  if (options.modelId != null)
205
271
  params.modelId = options.modelId;
206
- const raw = await this.#connection.command("session/start", params);
207
- const result = raw;
272
+ // The initial permission-profile selection, forwarded verbatim like the
273
+ // other start members (undefined stays omitted).
274
+ if (options.permissionProfile != null)
275
+ params.permissionProfile = options.permissionProfile;
276
+ // TEST-42624-10: a caller that requires its selection proves it, never
277
+ // assuming the host default. The flag without the member is API misuse
278
+ // (plain Error, like the other misuse guards here), raised pre-wire.
279
+ const required = options.requirePermissionProfile === true;
280
+ if (required && options.permissionProfile == null) {
281
+ throw new Error("requirePermissionProfile needs permissionProfile: require the selection you pass");
282
+ }
208
283
  // Keyed by the id the SERVER named, never the one the caller asked for:
209
284
  // `sessionId` is a REQUEST on start, and a session keyed by a hopeful id
210
285
  // would reject every one of its own events as foreign.
211
- return this.#openSession(result.session.sessionId, {
212
- result,
286
+ const session = await this.#open("session/start", params, (raw) => ({
287
+ result: raw,
213
288
  verb: "session/start",
289
+ }));
290
+ if (!required)
291
+ return session;
292
+ return this.#proveSelection(session, options.permissionProfile);
293
+ }
294
+ /**
295
+ * Prove a required start selection (TEST-42624-10): the start result's own
296
+ * `session.permissionState` first (absent = unknown, never applied); else a
297
+ * point-in-time `session/read`, which never subscribes. Only `profileId ==
298
+ * requested` proceeds; anything else throws `PermissionProfileNotApplied`
299
+ * BEFORE any turn is sent. The refused session is dropped from the client
300
+ * (no orphan keeps folding for an id the caller can never reach — the SDK
301
+ * has no set/close-by-id verb); the error's `sessionId` is the caller's
302
+ * handle to resume via `sessionId` or start again. A failed read-back
303
+ * propagates: the client still never proceeds on the default.
304
+ */
305
+ async #proveSelection(session, requested) {
306
+ const opening = session.opening;
307
+ const started = opening !== undefined && opening.verb === "session/start"
308
+ ? committedProfileId(opening.result.session)
309
+ : null;
310
+ if (started !== null) {
311
+ if (started === requested)
312
+ return session;
313
+ this.#sessions.delete(session);
314
+ throw new PermissionProfileNotApplied(requested, started, session.sessionId);
315
+ }
316
+ const read = await this.#connection.command("session/read", {
317
+ sessionId: session.sessionId,
214
318
  });
319
+ const served = committedProfileId(read["session"]);
320
+ if (served === requested)
321
+ return session;
322
+ this.#sessions.delete(session);
323
+ throw new PermissionProfileNotApplied(requested, served, session.sessionId);
215
324
  }
216
325
  /**
217
326
  * Load an existing session and subscribe this connection to its view
@@ -231,12 +340,10 @@ export class MuseClient {
231
340
  params.excludeItems = options.excludeItems;
232
341
  if (options.history != null)
233
342
  params.history = options.history;
234
- const raw = await this.#connection.command("session/resume", params);
235
- const result = raw;
236
- return this.#openSession(result.session.sessionId, {
237
- result,
343
+ return this.#open("session/resume", params, (raw) => ({
344
+ result: raw,
238
345
  verb: "session/resume",
239
- });
346
+ }));
240
347
  }
241
348
  /**
242
349
  * Shut the host down in an orderly way (SS2.1.2); the shutdown this causes
@@ -265,6 +372,25 @@ export class MuseClient {
265
372
  }
266
373
  await this.#connection.close();
267
374
  }
375
+ /**
376
+ * The window `#route` holds unknown-session frames for: from the request to
377
+ * the Session's registration. Counted, not flagged, so two concurrent opens
378
+ * keep it open until the LAST settles; cleared on settle so a frame that
379
+ * named no session this client opened is held no longer than the open it
380
+ * rode in with (#49790).
381
+ */
382
+ async #open(verb, params, opening) {
383
+ this.#opening += 1;
384
+ try {
385
+ const opened = opening(await this.#connection.command(verb, params));
386
+ return this.#openSession(opened.result.session.sessionId, opened);
387
+ }
388
+ finally {
389
+ this.#opening -= 1;
390
+ if (this.#opening === 0)
391
+ this.#held.clear();
392
+ }
393
+ }
268
394
  #openSession(sessionId, opening) {
269
395
  const session = new Session({
270
396
  connection: this.#connection,
@@ -274,6 +400,15 @@ export class MuseClient {
274
400
  sessionId,
275
401
  });
276
402
  this.#sessions.add(session);
403
+ // The frames that named this session while its verb was in flight fold
404
+ // NOW, in arrival order — synchronously, so nothing the pump routes next
405
+ // can overtake them.
406
+ const held = this.#held.get(sessionId);
407
+ if (held !== undefined) {
408
+ this.#held.delete(sessionId);
409
+ for (const frame of held)
410
+ session.apply(frame);
411
+ }
277
412
  return session;
278
413
  }
279
414
  #assertReattachAllowed(sessionId) {
@@ -208,9 +208,13 @@ export class GapFiller {
208
208
  return;
209
209
  const result = await this.#page(connection, this.#cursor);
210
210
  let reached = false;
211
+ // The last cursor this page served, skipped events included — where a
212
+ // walk toward an extended target resumes after an end-of-view page.
213
+ let lastServed;
211
214
  for (const event of result.events) {
212
215
  this.#requireOwnSession(event, after, target);
213
216
  const cursor = event.params.viewCursor;
217
+ lastServed = cursor;
214
218
  // An EARLIER fill already served — and applied — this durable event.
215
219
  // A later walk may legally page through the same range, and re-applying
216
220
  // it here is the same double fold the discard exists to prevent (PR
@@ -243,8 +247,17 @@ export class GapFiller {
243
247
  // The server's own end of the view. `next` names a LIVE cursor and
244
248
  // `view/page` serves durable-sourced events only (tdd SS4.7.3), so a
245
249
  // hole whose tail was ephemeral ends here and never at `target`.
246
- if (result.nextCursor === null)
250
+ //
251
+ // The cursor still advances to the last event served (#50252, the Rust
252
+ // SDK's INV-002 rule from #49869): if a `view/gap` extended the target
253
+ // while this page was in flight, `#walk` comes back here toward the new
254
+ // one, and re-asking from where this walk started would re-serve — and
255
+ // fold a second time — every event this page just delivered.
256
+ if (result.nextCursor === null) {
257
+ if (lastServed !== undefined)
258
+ this.#cursor = lastServed;
247
259
  return;
260
+ }
248
261
  // PROGRESS is the only bound on this walk, and it has to be, because a
249
262
  // legitimate fill is unbounded in length: an attempt cap would silently
250
263
  // truncate one. A page that carries no event, repeats the cursor it was
@@ -0,0 +1,62 @@
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
+ import type { ExitClassification, MuseServeChild } from "../connection/spawn.js";
13
+ /**
14
+ * How the host was lost. Two arms because the repair differs: `spawnFailed`
15
+ * means no process ever ran (`error` is Node's own spawn error — `code`
16
+ * `ENOENT`, `EACCES`, … — so fix the path or its permissions); `hostExited`
17
+ * means a process ran and ended before the handshake completed, and `exit` is
18
+ * its SS2.11 row — any row, the clean one included: a host that wrote its
19
+ * complaint to stderr and exited 0 before its first frame is still a lost
20
+ * host, and the row says only how it ended. `answeredInitialize` says whether
21
+ * it got as far as a usable `initialize` answer before dying (then the loss
22
+ * came while the SDK was completing the handshake, not at startup).
23
+ */
24
+ export type HostStartFailure = {
25
+ readonly kind: "spawnFailed";
26
+ readonly error: NodeJS.ErrnoException;
27
+ } | {
28
+ readonly kind: "hostExited";
29
+ readonly exit: ExitClassification;
30
+ readonly answeredInitialize: boolean;
31
+ };
32
+ /**
33
+ * `MuseClient.spawn` lost its host before the handshake completed.
34
+ *
35
+ * Typed rather than a bare `Error` because the two arms of `failure` name
36
+ * STATES an embedder branches on (retry after fixing the path, versus act on
37
+ * an SS2.11 retry posture). The transport error that first surfaced the loss
38
+ * rides as `cause`, so nothing the old rejection carried is dropped.
39
+ */
40
+ export declare class MuseHostStartError extends Error {
41
+ readonly failure: HostStartFailure;
42
+ /**
43
+ * The SDK's bounded stderr tail when the host was lost, one accessor
44
+ * regardless of arm: empty when no process ran, and the only place the
45
+ * evidence lives when the row is `cleanShutdown` (SS2.11 keeps no tail on
46
+ * the clean row; a logger wants the lines either way).
47
+ */
48
+ readonly stderrTail: readonly string[];
49
+ constructor(failure: HostStartFailure, stderrTail: readonly string[], cause: unknown);
50
+ }
51
+ /**
52
+ * Read a lost host's evidence into the typed error. "Lost" is decided by
53
+ * whether the host ANSWERED — whether a response frame came back — never by
54
+ * how it ended: the caller keeps an answer's own error (`MspError`, or a
55
+ * `ProtocolError` carrying the refused frame) and routes only frameless
56
+ * failures here, where the row says how the unanswering host ended.
57
+ *
58
+ * Call only after the handshake's `close()` has settled: the close ladder
59
+ * ends at the child's observed exit (or at its spawn failure), so
60
+ * `child.exit` is already settled here and this never waits on a live host.
61
+ */
62
+ export declare function hostStartFailure(child: MuseServeChild, cause: unknown, answeredInitialize: boolean): Promise<MuseHostStartError>;
@@ -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":
@@ -23,7 +23,11 @@ const TURN_START_FORWARDED = [
23
23
  "displayText",
24
24
  "ifBusy",
25
25
  "reasoningEffort",
26
+ // No "tokenBudget" (#45454): experimental-gated, and this SDK serves the
27
+ // stable surface only.
26
28
  "workspaceRoots",
29
+ // v1 stable member, forwarded like any other.
30
+ "userShell",
27
31
  ];
28
32
  /**
29
33
  * An `MspError` as the pending set reads it (SS4.13's settlement test).
@@ -169,8 +173,11 @@ export class TurnSubmitter {
169
173
  params.ifBusy = options.ifBusy;
170
174
  if (options.reasoningEffort != null)
171
175
  params.reasoningEffort = options.reasoningEffort;
176
+ // No tokenBudget forward (#45454): experimental-gated, stable SDK omits it.
172
177
  if (options.workspaceRoots != null)
173
178
  params.workspaceRoots = options.workspaceRoots;
179
+ if (options.userShell != null)
180
+ params.userShell = options.userShell;
174
181
  return params;
175
182
  }
176
183
  }
@@ -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:61afea3112e0906e9dc3a536144278a74cb4b36fc6e20901a91d4432ba3568e2";
16
+ export declare const EXPECTED_SCHEMA_FINGERPRINT = "sha256:eae467ab60cb9a5d5af4de616830f065e59375c987fd59269c8cc33ed2a1137f";
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:61afea3112e0906e9dc3a536144278a74cb4b36fc6e20901a91d4432ba3568e2";
16
+ export const EXPECTED_SCHEMA_FINGERPRINT = "sha256:eae467ab60cb9a5d5af4de616830f065e59375c987fd59269c8cc33ed2a1137f";
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;
@@ -166,9 +170,9 @@ export type ViewEvent = {
166
170
  * client's notification callback rather than this fold.
167
171
  */
168
172
  type AssertNever<T extends never> = T;
169
- type LiveHostStateProjection = "skill/changed" | "usage/changed" | "session/statusChanged" | "session/listChanged";
173
+ type LiveHostStateProjection = "skill/changed" | "usage/changed" | "session/statusChanged" | "session/listChanged" | "plugin/changed" | "plugin/marketplaceChanged" | "computerUseSetup/changed";
170
174
  type SessionLifecycleBroadcast = "session/started" | "session/closed";
171
- type NonFoldNotification = "initialized" | "session/viewHealthChanged" | "session/deleteCompleted" | SessionLifecycleBroadcast | LiveHostStateProjection;
175
+ type NonFoldNotification = "initialized" | "userInput/engaged" | "session/viewHealthChanged" | "recap/completed" | SessionLifecycleBroadcast | LiveHostStateProjection;
172
176
  type UnfoldedViewNotification = Exclude<MspNotification, NonFoldNotification | ViewEvent["method"]>;
173
177
  export type EveryViewNotificationIsFolded = AssertNever<UnfoldedViewNotification>;
174
178
  /**
@@ -214,7 +218,7 @@ export type SessionStateMethod = ViewEvent["method"] & `session/${string}`;
214
218
  * and could never match exhaustively. A future arm that starts dropping
215
219
  * widens this deliberately (PR #23087 review round).
216
220
  */
217
- 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";
218
222
  /**
219
223
  * The `NoStaleViewArm` sibling for the union above: these are hand-typed
220
224
  * literals, so without this pin a typo'd or later-retired member compiles
@@ -237,6 +241,12 @@ export interface TurnEntry {
237
241
  readonly error?: TurnError;
238
242
  /** The latest scheduled model retry; non-terminal (tdd SS4.5.1, D-026). */
239
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;
240
250
  }
241
251
  /** An approval awaiting its first durable terminal. */
242
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
  }
@@ -272,8 +278,11 @@ export class SessionFold {
272
278
  const turn = this.#turnFor(params.turnId);
273
279
  turn.commandId = params.commandId;
274
280
  // A retract is NOT a `TurnTerminal`; leaving `terminal` unset is the whole
275
- // point (INV-006). The retracted user message re-arrives via `item/updated`
276
- // with `retracted: true`, which the item half folds.
281
+ // point (INV-006). On accepted, the retracted user message re-arrives via
282
+ // `item/updated` with `retracted: true`, which the item half folds
283
+ // (a declined outcome also lands here for now: the entry reads retracted
284
+ // and the later turn/completed arrives as a stale frame, so its terminal
285
+ // is dropped too - a known gap in this fold, behavior unchanged).
277
286
  turn.state = "retracted";
278
287
  this.#clearActive(params.turnId);
279
288
  return { kind: "turn", turnId: params.turnId, state: turn.state };
@@ -304,6 +313,18 @@ export class SessionFold {
304
313
  turn.retryScheduled = params;
305
314
  return { kind: "turn", turnId: params.turnId, state: turn.state };
306
315
  }
316
+ #turnForegroundCompleted(params) {
317
+ // Non-terminal by contract: it never resolves a turn-wait (tdd SS4.5.12).
318
+ const turn = this.#turnFor(params.turnId);
319
+ // …but it is still a turn frame, so it takes the same redelivery guard
320
+ // as the retry hint: a replayed page must not re-plant the
321
+ // background-wait hint on a turn that already left `running`.
322
+ if (turn.state !== "running") {
323
+ return { kind: "ignoredStaleFrame", method: "turn/foregroundCompleted", id: params.turnId };
324
+ }
325
+ turn.foregroundCompleted = params;
326
+ return { kind: "turn", turnId: params.turnId, state: turn.state };
327
+ }
307
328
  #turnFor(turnId) {
308
329
  const held = this.#turns.get(turnId);
309
330
  if (held !== undefined)
@@ -324,6 +345,9 @@ export class SessionFold {
324
345
  ...(turn.terminal !== undefined ? { terminal: turn.terminal } : {}),
325
346
  ...(turn.error !== undefined ? { error: turn.error } : {}),
326
347
  ...(turn.retryScheduled !== undefined ? { retryScheduled: turn.retryScheduled } : {}),
348
+ ...(turn.foregroundCompleted !== undefined
349
+ ? { foregroundCompleted: turn.foregroundCompleted }
350
+ : {}),
327
351
  };
328
352
  }
329
353
  // ---- the delivery-plane marker ------------------------------------------
@@ -50,10 +50,12 @@ export { MuseClient } from "./facade/client.js";
50
50
  export type { MuseClientOptions, MuseClientSpawnOptions, ResumeSessionOptions, StartSessionOptions, } from "./facade/client.js";
51
51
  export type { ExitClassification, MuseServeChildOptions, ProcessExit, SpawnMspConnectionOptions, } from "./connection/spawn.js";
52
52
  export { DiscardedSessions } from "./facade/discarded.js";
53
- export { MuseForeignSessionError, MuseGapFillError, MuseSessionDiscardedError, } from "./errors.js";
53
+ export { MuseForeignSessionError, MuseGapFillError, MuseSessionDiscardedError, PermissionProfileNotApplied, } from "./errors.js";
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
@@ -40,12 +40,17 @@ export { MuseClient } from "./facade/client.js";
40
40
  // none — the cross-client sharing knob was declined (Constitution XI; see the
41
41
  // constructor note in `facade/client.ts`).
42
42
  export { DiscardedSessions } from "./facade/discarded.js";
43
- export { MuseForeignSessionError, MuseGapFillError, MuseSessionDiscardedError, } from "./errors.js";
43
+ export { MuseForeignSessionError, MuseGapFillError, MuseSessionDiscardedError, PermissionProfileNotApplied, } from "./errors.js";
44
44
  // Trimmed deliberately (Constitution XI): `isAbnormalHostDeath`,
45
45
  // `isItemInProgress`, and `survivesHostDeath` are `Session`'s own internals
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).