@muse-code/sdk 1.4.14 → 1.4.20

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.
@@ -3,8 +3,10 @@
3
3
  * tasks.md T030).
4
4
  *
5
5
  * A handle owns two things: the SS3.1.4 turn-wait, and the async iterators
6
- * that ride the fold for this turn. It authors no wire traffic and holds no
7
- * durable state — `Session` feeds it folded events and it fans them out.
6
+ * that ride the fold for this turn. It holds no durable state — `Session`
7
+ * feeds it folded events and it fans them out. Its control verbs
8
+ * (`cancel`/`interrupt`/`steer`/`unqueue`, FR-79106-1) author wire traffic
9
+ * only through the `TurnControls` its `Session` hands it.
8
10
  *
9
11
  * INV-006 governs the wait: the SDK never locally times out, fails, or
10
12
  * completes a turn. Every settlement below traces to a server-authored fact,
@@ -40,7 +42,7 @@ export function isLaunchFailure(outcome) {
40
42
  * buffer over before reporting an end or a failure, so a consumer never loses
41
43
  * events it was already owed.
42
44
  */
43
- class PushStream {
45
+ export class PushStream {
44
46
  #buffer = [];
45
47
  #onFinished;
46
48
  /**
@@ -120,6 +122,7 @@ class PushStream {
120
122
  export class TurnHandle {
121
123
  turnId;
122
124
  #replayItems;
125
+ #controls;
123
126
  #itemStreams = new Set();
124
127
  #deltaStreams = new Set();
125
128
  #completed;
@@ -134,9 +137,10 @@ export class TurnHandle {
134
137
  * rendered as finished, which is the invented completion INV-006 forbids.
135
138
  */
136
139
  #failure;
137
- constructor(turnId, replayItems) {
140
+ constructor(turnId, replayItems, controls) {
138
141
  this.turnId = turnId;
139
142
  this.#replayItems = replayItems;
143
+ this.#controls = controls;
140
144
  this.#completed = new Promise((resolve, reject) => {
141
145
  this.#settle = resolve;
142
146
  this.#fail = reject;
@@ -194,6 +198,18 @@ export class TurnHandle {
194
198
  this.#admit(stream, this.#deltaStreams);
195
199
  return stream;
196
200
  }
201
+ cancel() {
202
+ return this.#controls.cancel(this.turnId);
203
+ }
204
+ interrupt(options = {}) {
205
+ return this.#controls.interrupt(this.turnId, options);
206
+ }
207
+ steer(options) {
208
+ return this.#controls.steer(this.turnId, options);
209
+ }
210
+ unqueue() {
211
+ return this.#controls.unqueue(this.turnId);
212
+ }
197
213
  /**
198
214
  * Register a fresh stream, or finish it the way this turn already finished.
199
215
  * The failure branch comes FIRST: a turn that failed is not a turn that
@@ -1,21 +1,23 @@
1
1
  /**
2
- * `turn/start` submission and same-`commandId` replay (spec 14990 FR-018 /
3
- * T030 obligations (a) and (d); tdd SS3.1.1, SS3.2, SS4.13).
2
+ * `turn/start` and `turn/steer` submission and same-`commandId` replay (spec
3
+ * 14990 FR-018 / T030 obligations (a) and (d), FR-79106-1; tdd SS3.1.1,
4
+ * SS3.2, SS3.3, SS4.13).
4
5
  *
5
6
  * Split out of `session.ts` for the same reason `approval.ts` was: this is a
6
7
  * wire-shaping and idempotency concern, not a fold concern, and `Session` was
7
8
  * already the package's largest module.
8
9
  *
9
10
  * It holds the ONE piece of state `PendingCommandSet` deliberately cannot: the
10
- * `turn/start` params per `commandId`. The set stores the COMPOSER input and is
11
- * wire-blind by design (INV-001), so a replay — which must re-send the SAME
12
- * logical command, byte for byte, to be the sanctioned retry rather than a
13
- * double execution — needs the params to live on this side of that boundary.
11
+ * submitted method and params per `commandId`. The set stores the COMPOSER
12
+ * input and is wire-blind by design (INV-001), so a replay — which must re-send
13
+ * the SAME logical command, byte for byte, to be the sanctioned retry rather
14
+ * than a double execution — needs the params to live on this side of that
15
+ * boundary.
14
16
  */
15
17
  import type { Connection } from "../connection/connection.js";
16
18
  import type { PendingCommandSet } from "../pending/pending-command-set.js";
17
19
  import type { CommandErrorResponse, PendingCommandAck, PendingRetirement, ReplayAnswer } from "../pending/pending-command-set.js";
18
- import type { TurnStartParams } from "../msp.js";
20
+ import type { TurnStartParams, TurnSteerParams, TurnSteerResult } from "../msp.js";
19
21
  /**
20
22
  * What `Session.sendUserTurn` sends, COMPOSED from the generated params rather
21
23
  * than restated (INV-001).
@@ -32,6 +34,16 @@ export type SendUserTurnOptions<I> = Readonly<Omit<TurnStartParams, "commandId"
32
34
  */
33
35
  readonly composerInput?: I;
34
36
  };
37
+ /**
38
+ * What a turn handle's `steer` sends (`turn/steer`, tdd SS3.3), composed from
39
+ * the generated params. `expectedTurnId` is the handle's own turn, and
40
+ * `commandId`/`sessionId` are excluded for the same reasons as on
41
+ * {@link SendUserTurnOptions}.
42
+ */
43
+ export type SteerTurnOptions<I> = Readonly<Omit<TurnSteerParams, "commandId" | "sessionId" | "expectedTurnId">> & {
44
+ /** What to hand back to the composer if this steer is ever retired (SS4.13). */
45
+ readonly composerInput?: I;
46
+ };
35
47
  /**
36
48
  * An `MspError` as the pending set reads it (SS4.13's settlement test).
37
49
  *
@@ -45,18 +57,17 @@ export declare class TurnSubmitter<I> {
45
57
  constructor(sessionId: string, connection: Connection | undefined, pending: PendingCommandSet<I>);
46
58
  get wired(): boolean;
47
59
  requireConnection(verb: string): Connection;
60
+ /** Submit a `turn/start` through the SS4.13 path (`#submitRecorded`). */
61
+ submit(options: SendUserTurnOptions<I>, anchorAfterItemId: string | null): Promise<PendingCommandAck>;
48
62
  /**
49
- * Record the optimistic SS4.13 entry, then send `turn/start`.
50
- *
51
- * The ORDER is the point. An entry created only on the ack is invisible for
52
- * exactly the window it exists to cover — between the user pressing enter and
53
- * the host answering — and `anchorAfterItemId` is fixed here, at submission
54
- * time, because SS4.13's insertion point may never be relocated by events
55
- * that fold in afterwards.
63
+ * Steer `turnId` (`turn/steer`, tdd SS3.3) through the same SS4.13 path as
64
+ * `submit`: SS4.13's entry exists "from the moment it submits `turn/start`
65
+ * (or `turn/steer`)", and the steer's `userMessage` echoes its `commandId`,
66
+ * so materialization, rejection and reconnect replay all ride the set.
56
67
  */
57
- submit(options: SendUserTurnOptions<I>, anchorAfterItemId: string | null): Promise<PendingCommandAck>;
68
+ steer(turnId: string, options: SteerTurnOptions<I>, anchorAfterItemId: string | null): Promise<TurnSteerResult>;
58
69
  /**
59
- * Re-send one remembered `turn/start` under its ORIGINAL `commandId`
70
+ * Re-send one remembered submission under its ORIGINAL `commandId`
60
71
  * (SS3.1.1 — always safe, and the only re-send that is not a double
61
72
  * execution).
62
73
  *
@@ -1,16 +1,18 @@
1
1
  /**
2
- * `turn/start` submission and same-`commandId` replay (spec 14990 FR-018 /
3
- * T030 obligations (a) and (d); tdd SS3.1.1, SS3.2, SS4.13).
2
+ * `turn/start` and `turn/steer` submission and same-`commandId` replay (spec
3
+ * 14990 FR-018 / T030 obligations (a) and (d), FR-79106-1; tdd SS3.1.1,
4
+ * SS3.2, SS3.3, SS4.13).
4
5
  *
5
6
  * Split out of `session.ts` for the same reason `approval.ts` was: this is a
6
7
  * wire-shaping and idempotency concern, not a fold concern, and `Session` was
7
8
  * already the package's largest module.
8
9
  *
9
10
  * It holds the ONE piece of state `PendingCommandSet` deliberately cannot: the
10
- * `turn/start` params per `commandId`. The set stores the COMPOSER input and is
11
- * wire-blind by design (INV-001), so a replay — which must re-send the SAME
12
- * logical command, byte for byte, to be the sanctioned retry rather than a
13
- * double execution — needs the params to live on this side of that boundary.
11
+ * submitted method and params per `commandId`. The set stores the COMPOSER
12
+ * input and is wire-blind by design (INV-001), so a replay — which must re-send
13
+ * the SAME logical command, byte for byte, to be the sanctioned retry rather
14
+ * than a double execution — needs the params to live on this side of that
15
+ * boundary.
14
16
  */
15
17
  import { MspError } from "../connection/connection.js";
16
18
  /**
@@ -29,6 +31,14 @@ const TURN_START_FORWARDED = [
29
31
  // v1 stable member, forwarded like any other.
30
32
  "userShell",
31
33
  ];
34
+ /** Every `turn/steer` member forwarded; a regenerated member fails the build. */
35
+ const TURN_STEER_FORWARDED = ["input", "reasoningEffort"];
36
+ /**
37
+ * A steer's ack carries no disposition, but it IS the steered admission SS4.13
38
+ * names: the input is pending on the running turn's steer queue, so the entry
39
+ * holds like a `turn/start` acked `"steered"` (the acked-steer join arm).
40
+ */
41
+ const STEERED = "steered";
32
42
  /**
33
43
  * An `MspError` as the pending set reads it (SS4.13's settlement test).
34
44
  *
@@ -69,8 +79,38 @@ export class TurnSubmitter {
69
79
  }
70
80
  return connection;
71
81
  }
82
+ /** Submit a `turn/start` through the SS4.13 path (`#submitRecorded`). */
83
+ async submit(options, anchorAfterItemId) {
84
+ const connection = this.requireConnection("sendUserTurn");
85
+ // Delegated, not re-implemented: the connection owns the single mint, so
86
+ // INV-013's single-minter property survives this verb needing the id early.
87
+ const commandId = connection.mintCommandId();
88
+ const params = this.#params(commandId, options);
89
+ const sent = await this.#submitRecorded(connection, commandId, { method: "turn/start", params }, options.composerInput, anchorAfterItemId);
90
+ return sent.ack;
91
+ }
72
92
  /**
73
- * Record the optimistic SS4.13 entry, then send `turn/start`.
93
+ * Steer `turnId` (`turn/steer`, tdd SS3.3) through the same SS4.13 path as
94
+ * `submit`: SS4.13's entry exists "from the moment it submits `turn/start`
95
+ * (or `turn/steer`)", and the steer's `userMessage` echoes its `commandId`,
96
+ * so materialization, rejection and reconnect replay all ride the set.
97
+ */
98
+ async steer(turnId, options, anchorAfterItemId) {
99
+ const connection = this.requireConnection("steer");
100
+ const commandId = connection.mintCommandId();
101
+ const params = {
102
+ commandId,
103
+ expectedTurnId: turnId,
104
+ input: options.input,
105
+ sessionId: this.#sessionId,
106
+ };
107
+ if (options.reasoningEffort != null)
108
+ params.reasoningEffort = options.reasoningEffort;
109
+ const sent = await this.#submitRecorded(connection, commandId, { method: "turn/steer", params }, options.composerInput, anchorAfterItemId);
110
+ return sent.result;
111
+ }
112
+ /**
113
+ * Record the optimistic SS4.13 entry, then send.
74
114
  *
75
115
  * The ORDER is the point. An entry created only on the ack is invisible for
76
116
  * exactly the window it exists to cover — between the user pressing enter and
@@ -78,23 +118,19 @@ export class TurnSubmitter {
78
118
  * time, because SS4.13's insertion point may never be relocated by events
79
119
  * that fold in afterwards.
80
120
  */
81
- async submit(options, anchorAfterItemId) {
82
- const connection = this.requireConnection("sendUserTurn");
83
- // Delegated, not re-implemented: the connection owns the single mint, so
84
- // INV-013's single-minter property survives this verb needing the id early.
85
- const commandId = connection.mintCommandId();
86
- const params = this.#params(commandId, options);
121
+ async #submitRecorded(connection, commandId, remembered, input, anchorAfterItemId) {
122
+ const displayText = remembered.method === "turn/start" ? remembered.params.displayText : undefined;
87
123
  this.#pending.submitted({
88
124
  anchorAfterItemId,
89
125
  commandId,
90
- input: options.composerInput,
91
- ...(params.displayText === undefined ? {} : { displayText: params.displayText }),
126
+ input,
127
+ ...(displayText === undefined ? {} : { displayText }),
92
128
  });
93
- this.#memory.set(commandId, params);
129
+ this.#memory.set(commandId, remembered);
94
130
  try {
95
- const ack = await this.#send(connection, params, commandId);
96
- this.#pending.acked(commandId, ack);
97
- return ack;
131
+ const sent = await this.#send(connection, remembered, commandId);
132
+ this.#pending.acked(commandId, sent.ack);
133
+ return sent;
98
134
  }
99
135
  catch (error) {
100
136
  const response = commandErrorResponse(error);
@@ -111,7 +147,7 @@ export class TurnSubmitter {
111
147
  }
112
148
  }
113
149
  /**
114
- * Re-send one remembered `turn/start` under its ORIGINAL `commandId`
150
+ * Re-send one remembered submission under its ORIGINAL `commandId`
115
151
  * (SS3.1.1 — always safe, and the only re-send that is not a double
116
152
  * execution).
117
153
  *
@@ -120,12 +156,12 @@ export class TurnSubmitter {
120
156
  * transport/protocol one, which proves nothing about the intake.
121
157
  */
122
158
  async replay(commandId) {
123
- const params = this.#memory.get(commandId);
124
- if (params === undefined)
159
+ const remembered = this.#memory.get(commandId);
160
+ if (remembered === undefined)
125
161
  return undefined;
126
- const connection = this.requireConnection("turn/start replay");
162
+ const connection = this.requireConnection(`${remembered.method} replay`);
127
163
  try {
128
- return { ack: await this.#send(connection, params, commandId), kind: "ack" };
164
+ return { ack: (await this.#send(connection, remembered, commandId)).ack, kind: "ack" };
129
165
  }
130
166
  catch (error) {
131
167
  const response = commandErrorResponse(error);
@@ -148,12 +184,16 @@ export class TurnSubmitter {
148
184
  for (const retirement of retirements)
149
185
  this.#memory.delete(retirement.commandId);
150
186
  }
151
- async #send(connection, params, commandId) {
152
- const raw = await connection.command("turn/start", params, { commandId });
153
- const result = raw;
187
+ async #send(connection, remembered, commandId) {
188
+ const result = await connection.command(remembered.method, remembered.params, { commandId });
154
189
  // `turnId` comes from the ACK and never from the `commandId`: SS3.2 makes
155
190
  // the ack authoritative, and a queued submit's turn may already exist.
156
- return { disposition: result.disposition, turnId: result.turnId };
191
+ if (remembered.method === "turn/steer") {
192
+ const steered = result;
193
+ return { ack: { disposition: STEERED, turnId: steered.turnId }, result };
194
+ }
195
+ const started = result;
196
+ return { ack: { disposition: started.disposition, turnId: started.turnId }, result };
157
197
  }
158
198
  /**
159
199
  * OPTIONAL MEANS OMITTED, NEVER `null` (tdd SS1.2), and the guards are LOOSE
@@ -1,26 +1,12 @@
1
- /**
2
- * The schema-bundle staleness anchor (spec 14990 FR-006).
3
- *
4
- * `EXPECTED_SCHEMA_FINGERPRINT` pins the stable protocol-schema fingerprint
5
- * this SDK was written against. Two consumers:
6
- *
7
- * - Build time: a test asserts this equals `schema/msp/stable/manifest.json`,
8
- * so a schema advance that forgets the SDK reds the SDK lane instead of
9
- * shipping a silently-stale facade. This is the same manifest-pin pattern
10
- * the #210 transcripts use.
11
- * - Runtime: the connection machine compares `InitializeResult.schema
12
- * .fingerprint` against this pin. A mismatch is a WARNING, never an error
13
- * (tdd SS1.4.1) — additive-optional evolution means an older SDK keeps
14
- * working against a newer host.
15
- */
16
- export declare const EXPECTED_SCHEMA_FINGERPRINT = "sha256:c94c3d1f2f51e6424074b9ec43eac3eedcf532d3dcd77351ec1383a87d3049c6";
1
+ export declare const EXPECTED_SCHEMA_FINGERPRINT: string;
17
2
  /**
18
3
  * What a build-time mismatch MEANS, in the words a human needs at 2am.
19
4
  *
20
5
  * A mismatch is the normal, expected consequence of the protocol schema
21
6
  * advancing — it is NOT evidence that the SDK is broken. The remedy is to
22
- * re-pin and adapt whatever actually changed. Several lanes have burned time
23
- * reading a red fingerprint as an SDK defect, so the message says it plainly.
7
+ * rebuild and adapt whatever actually changed. Several lanes have burned
8
+ * time reading a red fingerprint as an SDK defect, so the message says it
9
+ * plainly.
24
10
  */
25
11
  export declare function fingerprintMismatchMessage(pinned: string, actual: string): string;
26
12
  /** The runtime arm (tdd SS1.4.1): advisory only, never a connection failure. */
@@ -1,37 +1,47 @@
1
1
  /**
2
2
  * The schema-bundle staleness anchor (spec 14990 FR-006).
3
3
  *
4
- * `EXPECTED_SCHEMA_FINGERPRINT` pins the stable protocol-schema fingerprint
5
- * this SDK was written against. Two consumers:
4
+ * `EXPECTED_SCHEMA_FINGERPRINT` is the stable protocol-schema fingerprint
5
+ * this SDK was built against. It derives at build: the `prebuild` step
6
+ * (`node scripts/msp-fingerprint.mjs --stamp`) computes it from the
7
+ * committed schema bytes and stamps the generated module this file imports
8
+ * (ADR 77546 D4). No literal is committed here — a schema advance moves
9
+ * the value at the next build, and two PRs that change different schema
10
+ * regions never conflict on this file.
6
11
  *
7
- * - Build time: a test asserts this equals `schema/msp/stable/manifest.json`,
8
- * so a schema advance that forgets the SDK reds the SDK lane instead of
9
- * shipping a silently-stale facade. This is the same manifest-pin pattern
10
- * the #210 transcripts use.
12
+ * Two consumers:
13
+ *
14
+ * - Build time: the receipt-pins gate proves this file carries the
15
+ * derivation hook and no committed copy, and the sdk-ts suite proves
16
+ * the stamped value equals the port's derivation over the live schema
17
+ * bytes — so a schema advance that the build somehow misses reds
18
+ * instead of shipping a silently-stale facade.
11
19
  * - Runtime: the connection machine compares `InitializeResult.schema
12
- * .fingerprint` against this pin. A mismatch is a WARNING, never an error
13
- * (tdd SS1.4.1) — additive-optional evolution means an older SDK keeps
14
- * working against a newer host.
20
+ * .fingerprint` against this value. A mismatch is a WARNING, never an
21
+ * error (tdd SS1.4.1) — additive-optional evolution means an older SDK
22
+ * keeps working against a newer host.
15
23
  */
16
- export const EXPECTED_SCHEMA_FINGERPRINT = "sha256:c94c3d1f2f51e6424074b9ec43eac3eedcf532d3dcd77351ec1383a87d3049c6";
24
+ import { STAMPED_SCHEMA_FINGERPRINT } from "./fingerprint.stamped.js";
25
+ export const EXPECTED_SCHEMA_FINGERPRINT = STAMPED_SCHEMA_FINGERPRINT;
17
26
  /**
18
27
  * What a build-time mismatch MEANS, in the words a human needs at 2am.
19
28
  *
20
29
  * A mismatch is the normal, expected consequence of the protocol schema
21
30
  * advancing — it is NOT evidence that the SDK is broken. The remedy is to
22
- * re-pin and adapt whatever actually changed. Several lanes have burned time
23
- * reading a red fingerprint as an SDK defect, so the message says it plainly.
31
+ * rebuild and adapt whatever actually changed. Several lanes have burned
32
+ * time reading a red fingerprint as an SDK defect, so the message says it
33
+ * plainly.
24
34
  */
25
35
  export function fingerprintMismatchMessage(pinned, actual) {
26
36
  return [
27
- "MSP schema fingerprint moved: re-pin after a schema advance.",
28
- ` pinned by @muse-code/sdk: ${pinned}`,
29
- ` schema/msp/stable/manifest.json: ${actual}`,
37
+ "MSP schema fingerprint moved: rebuild after a schema advance.",
38
+ ` built by @muse-code/sdk: ${pinned}`,
39
+ ` derived stable schema fingerprint: ${actual}`,
30
40
  "",
31
41
  "This does NOT mean the SDK is broken. The stable schema bundle advanced",
32
- "(a #206 enrollment or renderer change). Fix it by running",
33
- "scripts/regen-msp-pins.sh, which re-pins EXPECTED_SCHEMA_FINGERPRINT and",
34
- "every other derived copy from the committed stable manifest, then adapt",
42
+ "(a #206 enrollment or renderer change). Fix it by rebuilding",
43
+ "(`npm run build` re-stamps EXPECTED_SCHEMA_FINGERPRINT from the",
44
+ "committed schema bytes), then adapt",
35
45
  "the facade to whatever the advance actually changed. Never hand-edit",
36
46
  "schema/msp/** to match the SDK.",
37
47
  ].join("\n");
@@ -48,7 +58,7 @@ export function checkServedFingerprint(served, pinned = EXPECTED_SCHEMA_FINGERPR
48
58
  pinned,
49
59
  served,
50
60
  message: `host schema fingerprint ${served} differs from the fingerprint this ` +
51
- `SDK pins (${pinned}); proceeding under additive-optional evolution ` +
52
- `(SS1.5.4). Re-pin after a schema advance.`,
61
+ `SDK was built against (${pinned}); proceeding under additive-optional ` +
62
+ `evolution (SS1.5.4). Rebuild after a schema advance.`,
53
63
  };
54
64
  }
@@ -0,0 +1 @@
1
+ export declare const STAMPED_SCHEMA_FINGERPRINT = "sha256:283b1b125dcc9172928fb5d6711a92a353796d030a7c186988ed527a13cf07f0";
@@ -0,0 +1,6 @@
1
+ // GENERATED by `node scripts/msp-fingerprint.mjs --stamp` (runs on every
2
+ // `npm run build` / `npm run check`). Do not edit: the value derives from
3
+ // schema/msp/stable/msp.schema.json through the port in
4
+ // scripts/msp-fingerprint.mjs. A schema advance moves this value at the
5
+ // next build; the file itself is gitignored and never committed.
6
+ export const STAMPED_SCHEMA_FINGERPRINT = "sha256:283b1b125dcc9172928fb5d6711a92a353796d030a7c186988ed527a13cf07f0";
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The one fold extension hook (FR-97527-3): a neutral, method-name-keyed
3
+ * registration consulted for BOTH connection-level state and the
4
+ * per-session fold.
5
+ *
6
+ * An extension runs INSIDE the single apply path — never a second pump —
7
+ * so gap buffering, twin-claiming and resume behave exactly as today. The
8
+ * hook names no experimental feature: it matches on the method string, and
9
+ * the extension keeps its own state in its own instance.
10
+ *
11
+ * A throw never escapes: both loops catch an extension's throw and report
12
+ * it to that extension's `onError` (the `ApprovalFailure` "reported, not
13
+ * thrown" rule — the call site is a notification pump with nothing to
14
+ * catch it). Without an `onError` the failure is swallowed, deliberately:
15
+ * one bad add-on must not drop every session. An `onError` that itself
16
+ * throws is swallowed too, for the same reason the approval observer's is.
17
+ */
18
+ export interface FoldExtension {
19
+ /** The exact notification method this extension handles. */
20
+ readonly method: string;
21
+ /**
22
+ * Fold one frame's params. Called in registration order with the other
23
+ * extensions for the same method, before the fold's own arm for that
24
+ * method runs.
25
+ */
26
+ apply(params: unknown): void;
27
+ /** Receives this extension's throws; absent means swallow. */
28
+ readonly onError?: (error: unknown) => void;
29
+ }
30
+ /**
31
+ * Run every extension registered for `method`, in registration order.
32
+ *
33
+ * The ONE call-and-report loop both planes share (fold + client `#route`),
34
+ * so guard and reporting changes land once. Objects only — a frame without
35
+ * usable params has nothing to fold. A throw is reported to that
36
+ * extension's `onError` (absent means swallow); an `onError` that itself
37
+ * throws is swallowed too. Returns how many extensions fired.
38
+ */
39
+ export declare function fireExtensions(extensions: readonly FoldExtension[], method: string, params: unknown): number;
@@ -0,0 +1,49 @@
1
+ /**
2
+ * The one fold extension hook (FR-97527-3): a neutral, method-name-keyed
3
+ * registration consulted for BOTH connection-level state and the
4
+ * per-session fold.
5
+ *
6
+ * An extension runs INSIDE the single apply path — never a second pump —
7
+ * so gap buffering, twin-claiming and resume behave exactly as today. The
8
+ * hook names no experimental feature: it matches on the method string, and
9
+ * the extension keeps its own state in its own instance.
10
+ *
11
+ * A throw never escapes: both loops catch an extension's throw and report
12
+ * it to that extension's `onError` (the `ApprovalFailure` "reported, not
13
+ * thrown" rule — the call site is a notification pump with nothing to
14
+ * catch it). Without an `onError` the failure is swallowed, deliberately:
15
+ * one bad add-on must not drop every session. An `onError` that itself
16
+ * throws is swallowed too, for the same reason the approval observer's is.
17
+ */
18
+ /**
19
+ * Run every extension registered for `method`, in registration order.
20
+ *
21
+ * The ONE call-and-report loop both planes share (fold + client `#route`),
22
+ * so guard and reporting changes land once. Objects only — a frame without
23
+ * usable params has nothing to fold. A throw is reported to that
24
+ * extension's `onError` (absent means swallow); an `onError` that itself
25
+ * throws is swallowed too. Returns how many extensions fired.
26
+ */
27
+ export function fireExtensions(extensions, method, params) {
28
+ if (params === null || typeof params !== "object" || Array.isArray(params))
29
+ return 0;
30
+ let fired = 0;
31
+ for (const extension of extensions) {
32
+ if (extension.method !== method)
33
+ continue;
34
+ fired += 1;
35
+ try {
36
+ extension.apply(params);
37
+ }
38
+ catch (error) {
39
+ try {
40
+ extension.onError?.(error);
41
+ }
42
+ catch {
43
+ // The failure observer threw. Swallowed, deliberately — same rule
44
+ // as the approval observer: there is no one left to tell.
45
+ }
46
+ }
47
+ }
48
+ return fired;
49
+ }
@@ -14,7 +14,8 @@
14
14
  *
15
15
  * - the TURN LIFECYCLE — `turn/started`, `turn/completed`, `turn/retracted`,
16
16
  * `turn/unqueued`, and the non-terminal `turn/retryScheduled`,
17
- * `turn/modelRetryScheduled`, and `turn/foregroundCompleted`;
17
+ * `turn/modelRetryScheduled`, `turn/modelAttemptStarted`, and
18
+ * `turn/foregroundCompleted`;
18
19
  * - the APPROVAL and USER-INPUT view events as fold INPUTS — the pending
19
20
  * sets and their first durable terminal. The decision flow (choosing and
20
21
  * sending a resolution) is the facade's, not the fold's;
@@ -27,7 +28,8 @@
27
28
  * unrecognized `TurnTerminal` is kept verbatim, and a second resolution never
28
29
  * displaces the first durable one.
29
30
  */
30
- import type { ApprovalRequestParams, ApprovalResolvedParams, ApprovalUpdatedParams, Item, ItemCompletedParams, ItemDeltaParams, ItemStartedParams, ItemUpdatedParams, MonitorInboxItemAdmittedParams, MonitorInboxItemDrainedParams, MonitorInboxItemVoidedParams, MspNotification, SessionApprovalModeChangedParams, SessionBranchChangedParams, SessionContextUsageParams, SessionGoalChangedParams, SessionModelChangedParams, SessionModelRouteUnservedParams, SessionNameChangedParams, SessionReasoningEffortChangedParams, SessionTodoListChangedParams, SessionTokenUsageParams, TurnCompletedParams, TurnError, TurnForegroundCompletedParams, TurnModelRetryScheduledParams, TurnRetractedParams, TurnRetryScheduledParams, TurnStartedParams, TurnTerminal, TurnUnqueuedParams, UserInputRequestParams, UserInputSettledParams, ViewGapParams } from "../msp.js";
31
+ import type { ApprovalRequestParams, ApprovalResolvedParams, ApprovalUpdatedParams, Item, ItemCompletedParams, ItemDeltaParams, ItemStartedParams, ItemUpdatedParams, MonitorInboxItemAdmittedParams, MonitorInboxItemDrainedParams, MonitorInboxItemVoidedParams, MspNotification, SessionApprovalModeChangedParams, SessionBranchChangedParams, SessionContextUsageParams, SessionGoalChangedParams, SessionModelChangedParams, SessionModelRouteUnservedParams, SessionNameChangedParams, SessionReasoningEffortChangedParams, SessionTodoListChangedParams, SessionTokenUsageParams, TurnCompletedParams, TurnError, TurnForegroundCompletedParams, TurnModelAttemptStartedParams, TurnModelRetryScheduledParams, TurnRetractedParams, TurnRetryScheduledParams, TurnStartedParams, TurnTerminal, TurnUnqueuedParams, UserInputRequestParams, UserInputSettledParams, ViewGapParams } from "../msp.js";
32
+ import type { FoldExtension } from "./extension.js";
31
33
  import type { DeltaApplyOutcome, ItemApplyOutcome, TerminalUnknownItemAnnotation } from "./item-store.js";
32
34
  import type { StateApplyOutcome, StateValue } from "./state-store.js";
33
35
  /** The session-state families, each keyed in the store by its method name. */
@@ -63,6 +65,9 @@ export type ViewEvent = {
63
65
  } | {
64
66
  readonly method: "turn/modelRetryScheduled";
65
67
  readonly params: TurnModelRetryScheduledParams;
68
+ } | {
69
+ readonly method: "turn/modelAttemptStarted";
70
+ readonly params: TurnModelAttemptStartedParams;
66
71
  } | {
67
72
  readonly method: "turn/unqueued";
68
73
  readonly params: TurnUnqueuedParams;
@@ -195,7 +200,7 @@ export type ViewEvent = {
195
200
  type AssertNever<T extends never> = T;
196
201
  type LiveHostStateProjection = "skill/changed" | "usage/changed" | "session/statusChanged" | "session/listChanged" | "plugin/changed" | "plugin/marketplaceChanged" | "computerUseSetup/changed";
197
202
  type SessionLifecycleBroadcast = "session/started" | "session/closed";
198
- type NonFoldNotification = "initialized" | "userInput/engaged" | "session/viewHealthChanged" | "session/leaveCompleted" | "recap/completed" | SessionLifecycleBroadcast | LiveHostStateProjection;
203
+ type NonFoldNotification = "initialized" | "userInput/engaged" | "session/viewHealthChanged" | "session/leaveCompleted" | "recap/completed" | "model/completed" | SessionLifecycleBroadcast | LiveHostStateProjection;
199
204
  type UnfoldedViewNotification = Exclude<MspNotification, NonFoldNotification | ViewEvent["method"]>;
200
205
  export type EveryViewNotificationIsFolded = AssertNever<UnfoldedViewNotification>;
201
206
  /**
@@ -241,7 +246,7 @@ export type SessionStateMethod = ViewEvent["method"] & `session/${string}`;
241
246
  * and could never match exhaustively. A future arm that starts dropping
242
247
  * widens this deliberately (PR #23087 review round).
243
248
  */
244
- export type StaleDroppableMethod = "turn/started" | "turn/completed" | "turn/retracted" | "turn/foregroundCompleted" | "turn/retryScheduled" | "turn/modelRetryScheduled" | "approval/requested" | "approval/updated" | "userInput/requested" | "view/gap";
249
+ export type StaleDroppableMethod = "turn/started" | "turn/completed" | "turn/retracted" | "turn/foregroundCompleted" | "turn/retryScheduled" | "turn/modelRetryScheduled" | "turn/modelAttemptStarted" | "approval/requested" | "approval/updated" | "userInput/requested" | "view/gap";
245
250
  /**
246
251
  * The `NoStaleViewArm` sibling for the union above: these are hand-typed
247
252
  * literals, so without this pin a typo'd or later-retired member compiles
@@ -271,6 +276,13 @@ export interface TurnEntry {
271
276
  * its delay. Clears on the turn's terminal.
272
277
  */
273
278
  readonly modelRetryScheduled?: TurnModelRetryScheduledParams;
279
+ /**
280
+ * The latest model attempt start (tdd SS4.5.1, ADR 68644 D1), recorded
281
+ * before the provider dials; non-terminal. It stays set through tool runs
282
+ * and retry backoffs until the turn's terminal, so it is not a live
283
+ * "model is working" flag.
284
+ */
285
+ readonly modelAttemptStarted?: TurnModelAttemptStartedParams;
274
286
  /**
275
287
  * The latest foreground-completed notice; non-terminal (tdd SS4.5.12).
276
288
  * Tells a renderer the answer is done while `blockingAgents` hold the
@@ -384,6 +396,15 @@ export type FoldOutcome = {
384
396
  } | {
385
397
  readonly kind: "ignoredUnrecognizedMethod";
386
398
  readonly method: string;
399
+ }
400
+ /**
401
+ * An otherwise-unrecognized method a registered extension handled
402
+ * (FR-97527-3). Ids only, like its ignored twin: the extension keeps
403
+ * its own state in its own instance, so nothing here needs sealing.
404
+ */
405
+ | {
406
+ readonly kind: "extension";
407
+ readonly method: string;
387
408
  } | {
388
409
  /**
389
410
  * A frame that carried no `params`. The generated `Notification`
@@ -401,13 +422,16 @@ export type FoldOutcome = {
401
422
  /**
402
423
  * A recognized frame the fold deliberately dropped, leaving state
403
424
  * unchanged: a `turn/started`, `turn/retryScheduled`,
404
- * `turn/modelRetryScheduled` or `turn/foregroundCompleted` for a turn
425
+ * `turn/modelRetryScheduled`, `turn/modelAttemptStarted` or
426
+ * `turn/foregroundCompleted` for a turn
405
427
  * that already left `running`; a `turn/completed` for a `retracted` or
406
428
  * `unqueued` turn; a declined `turn/retracted` for a turn the fold has
407
429
  * not seen; an `approval/updated` for an approval it never saw
408
430
  * requested (or whose entry a resolution already deleted); or a
409
431
  * redelivered `approval/requested` / `userInput/requested` for an
410
432
  * approval/prompt that already has its durable terminal; or a
433
+ * `userInput/requested` for a turn already known to have left
434
+ * `running`; or a
411
435
  * `view/gap` whose `next` an earlier frame already named while the
412
436
  * hole is open (`id` is that `next`, #62032). Truthful by
413
437
  * contract: a "pending" kind here would make a renderer show an entry
@@ -490,6 +514,7 @@ export interface FoldSessionState {
490
514
  */
491
515
  export declare class SessionFold {
492
516
  #private;
517
+ constructor(extensions?: readonly FoldExtension[]);
493
518
  /** Items, snapshot-only: the mutators are `apply()`'s, not the consumer's. */
494
519
  get items(): FoldItems;
495
520
  /**