@assistant-ui/react-statewire 0.12.0 → 0.14.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 (56) hide show
  1. package/dist/StatewireThread.d.ts +83 -108
  2. package/dist/StatewireThread.d.ts.map +1 -1
  3. package/dist/StatewireThread.js +54 -79
  4. package/dist/StatewireThread.js.map +1 -1
  5. package/dist/hooks.d.ts +6 -9
  6. package/dist/hooks.d.ts.map +1 -1
  7. package/dist/hooks.js +9 -20
  8. package/dist/hooks.js.map +1 -1
  9. package/dist/index.d.ts +2 -3
  10. package/dist/index.js +2 -3
  11. package/dist/inputRequests.d.ts +4 -4
  12. package/dist/inputRequests.d.ts.map +1 -1
  13. package/dist/inputRequests.js +4 -2
  14. package/dist/inputRequests.js.map +1 -1
  15. package/dist/runCommands.d.ts +14 -19
  16. package/dist/runCommands.d.ts.map +1 -1
  17. package/dist/runCommands.js +29 -13
  18. package/dist/runCommands.js.map +1 -1
  19. package/dist/runsOptimistic.d.ts.map +1 -1
  20. package/dist/runsOptimistic.js +9 -8
  21. package/dist/runsOptimistic.js.map +1 -1
  22. package/package.json +4 -5
  23. package/src/StatewireThread.runs.test.tsx +67 -54
  24. package/src/StatewireThread.test.tsx +239 -431
  25. package/src/StatewireThread.ts +151 -266
  26. package/src/__tests__/testHelpers.tsx +6 -226
  27. package/src/hooks.ts +11 -32
  28. package/src/index.ts +2 -4
  29. package/src/inputRequests.ts +10 -8
  30. package/src/runCommands.ts +63 -31
  31. package/src/runsOptimistic.test.ts +64 -26
  32. package/src/runsOptimistic.ts +14 -9
  33. package/dist/AssistantTransportThread.d.ts +0 -216
  34. package/dist/AssistantTransportThread.d.ts.map +0 -1
  35. package/dist/AssistantTransportThread.js +0 -257
  36. package/dist/AssistantTransportThread.js.map +0 -1
  37. package/dist/host.d.ts +0 -38
  38. package/dist/host.d.ts.map +0 -1
  39. package/dist/host.js +0 -299
  40. package/dist/host.js.map +0 -1
  41. package/dist/replayBoundaryStream.d.ts +0 -6
  42. package/dist/replayBoundaryStream.d.ts.map +0 -1
  43. package/dist/replayBoundaryStream.js +0 -49
  44. package/dist/replayBoundaryStream.js.map +0 -1
  45. package/dist/stateOps.d.ts +0 -10
  46. package/dist/stateOps.d.ts.map +0 -1
  47. package/dist/stateOps.js +0 -114
  48. package/dist/stateOps.js.map +0 -1
  49. package/src/AssistantTransportThread.ts +0 -756
  50. package/src/athena.e2e.test.tsx +0 -652
  51. package/src/host.ts +0 -437
  52. package/src/legacy-diff.test.tsx +0 -627
  53. package/src/replayBoundaryStream.ts +0 -71
  54. package/src/stateOps.test.ts +0 -165
  55. package/src/stateOps.ts +0 -126
  56. package/src/transport.test.tsx +0 -2964
@@ -1,8 +1,9 @@
1
1
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2
2
  import { resource, useResource } from "@assistant-ui/tap";
3
3
  import type { ResourceElement } from "@assistant-ui/tap";
4
- import { ExternalThread } from "@assistant-ui/react";
5
- import type { ExternalThreadMessage } from "@assistant-ui/react";
4
+ import { ExternalThread } from "@assistant-ui/core/store";
5
+ import type { ExternalThreadMessage } from "@assistant-ui/core/store";
6
+ import type { Assistant } from "@assistant-ui/core";
6
7
  import {
7
8
  forwardTransformScopes,
8
9
  useAssistantClientRef,
@@ -12,7 +13,6 @@ import type {
12
13
  AddToolResultOptions,
13
14
  AppendMessage,
14
15
  AttachmentAdapter,
15
- ExternalThreadQueueAdapter,
16
16
  FeedbackAdapter,
17
17
  ModelContext,
18
18
  RespondToToolApprovalOptions,
@@ -23,17 +23,12 @@ import { toToolsJSONSchema } from "assistant-stream";
23
23
  import type { ReadonlyJSONValue } from "assistant-stream/utils";
24
24
  import { useStatewire } from "statewire";
25
25
  import type { Statewire, StatewireClient } from "statewire";
26
- import { symbolAssistantTransportExtras } from "./AssistantTransportThread";
27
- import type {
28
- AssistantTransportExtras,
29
- AssistantTransportThread,
30
- } from "./AssistantTransportThread";
31
26
  import {
32
27
  createRunQueueAdapter,
33
28
  resolveEditCommand,
34
29
  resolveReloadCommand,
30
+ sendFields,
35
31
  toWireMessage,
36
- viewedLeafId,
37
32
  } from "./runCommands";
38
33
  import {
39
34
  resolveToolApprovalInput,
@@ -43,23 +38,24 @@ import { runsOptimistic } from "./runsOptimistic";
43
38
 
44
39
  type AnyCommands = Record<string, (...args: any[]) => unknown>;
45
40
 
46
- type AnyOptions =
47
- | StatewireThread.Options<any>
48
- | StatewireThread.RunsOptions<any>;
41
+ export const symbolStatewireExtras = Symbol("statewire-extras");
49
42
 
50
- const LOADING_STATE: StatewireThread.State = { messages: [], isRunning: false };
43
+ export const asStatewireExtras = (extras: unknown): StatewireThread.Extras => {
44
+ if (
45
+ typeof extras !== "object" ||
46
+ extras == null ||
47
+ !(symbolStatewireExtras in extras)
48
+ )
49
+ throw new Error(
50
+ "This method can only be called when you are using StatewireThread",
51
+ );
51
52
 
52
- const READY_RUNS: StatewireThread.Runs = {
53
- status: "ready",
54
- runId: null,
55
- queue: [],
56
- steerQueue: [],
57
- dispatching: null,
58
- error: null,
53
+ return extras as StatewireThread.Extras;
59
54
  };
60
55
 
61
- const LOADING_RUNS: StatewireThread.Runs = {
62
- status: "loading",
56
+ const NO_INPUT_REQUESTS: readonly StatewireThread.InputRequestState[] = [];
57
+
58
+ const RESTING_RUNS: StatewireThread.Runs = {
63
59
  runId: null,
64
60
  queue: [],
65
61
  steerQueue: [],
@@ -78,7 +74,9 @@ const ambientContextOf = (context: ModelContext): Record<string, unknown> => ({
78
74
  ...(context.config !== undefined && { config: context.config }),
79
75
  });
80
76
 
81
- const useStatewireThread = (options: AnyOptions): ClientOutput<"thread"> => {
77
+ const useStatewireThread = (
78
+ options: StatewireThread.Options<any>,
79
+ ): ClientOutput<"thread"> => {
82
80
  const latest = useRef(options);
83
81
  latest.current = options;
84
82
 
@@ -94,48 +92,17 @@ const useStatewireThread = (options: AnyOptions): ClientOutput<"thread"> => {
94
92
  ),
95
93
  );
96
94
 
97
- const runsOption = options.runs;
98
- const [runsSeam] = useState(() => runsOption !== undefined);
99
- if (runsSeam !== (runsOption !== undefined))
100
- throw new Error(
101
- "statewire: the runs option must be stable — it was " +
102
- (runsSeam ? "set" : "unset") +
103
- " on first render and changed since",
104
- );
105
-
106
- const materializeOption = (options as StatewireThread.RunsOptions<unknown>)
107
- .materialize;
108
- const [materializeSeam] = useState(() => materializeOption !== undefined);
109
- if (materializeSeam !== (materializeOption !== undefined))
110
- throw new Error(
111
- "statewire: the materialize option must be stable — it was " +
112
- (materializeSeam ? "set" : "unset") +
113
- " on first render and changed since",
114
- );
115
-
116
95
  const { state, commands, connection, setContext } = useStatewire<
117
96
  unknown,
118
97
  AnyCommands
119
98
  >({
120
99
  transport: options.transport,
121
100
  initialState: options.initialState,
122
- ...(runsSeam && {
123
- optimistic: (draft, command, ctx) => {
124
- const runsOpt = latest.current.runs!;
125
- runsOptimistic(runsOpt === true ? draft : runsOpt(draft), command, ctx);
126
- (latest.current as StatewireThread.RunsOptions<unknown>).optimistic?.(
127
- draft,
128
- command,
129
- ctx,
130
- );
131
- },
132
- }),
133
- ...(materializeSeam && {
134
- materialize: (draft: {}) =>
135
- (latest.current as StatewireThread.RunsOptions<unknown>).materialize!(
136
- draft,
137
- ),
138
- }),
101
+ optimistic: (draft, command, ctx) => {
102
+ runsOptimistic(draft, command, ctx);
103
+ latest.current.optimistic?.(draft, command, ctx);
104
+ },
105
+ materialize: (draft: {}) => latest.current.materialize?.(draft),
139
106
  onCommandChange: (update, ctx) => {
140
107
  if (update.status === "acked" || update.status === "settled")
141
108
  retire(update.params[0]);
@@ -204,27 +171,31 @@ const useStatewireThread = (options: AnyOptions): ClientOutput<"thread"> => {
204
171
  [dispatch],
205
172
  );
206
173
 
207
- const runs = useMemo((): StatewireThread.Runs | undefined => {
208
- if (runsOption === undefined) return undefined;
209
- if (state === undefined) return LOADING_RUNS;
210
- const mount = (runsOption === true ? state : runsOption(state)) as
211
- | StatewireThread.RunsState
212
- | undefined;
213
- const entry = mount?.runs?.[0];
214
- return entry === undefined
215
- ? READY_RUNS
216
- : {
217
- status: entry.status,
218
- runId: entry.runId,
219
- queue: entry.queue,
220
- steerQueue: entry.steerQueue,
221
- dispatching: entry.dispatching,
222
- ...(entry.inputRequests !== undefined && {
223
- inputRequests: entry.inputRequests,
224
- }),
225
- error: entry.error,
226
- };
227
- }, [runsOption, state]);
174
+ const { status, runs } = useMemo((): {
175
+ status: StatewireThread.ThreadStatus;
176
+ runs: StatewireThread.Runs;
177
+ } => {
178
+ const entries = (
179
+ state as { runs?: readonly StatewireThread.RunState[] } | undefined
180
+ )?.runs;
181
+ const entry = entries?.[0];
182
+ return {
183
+ status: entries === undefined ? "loading" : (entry?.status ?? "ready"),
184
+ runs:
185
+ entry === undefined
186
+ ? RESTING_RUNS
187
+ : {
188
+ runId: entry.runId,
189
+ queue: entry.queue,
190
+ steerQueue: entry.steerQueue,
191
+ dispatching: entry.dispatching,
192
+ ...(entry.inputRequests !== undefined && {
193
+ inputRequests: entry.inputRequests,
194
+ }),
195
+ error: entry.error,
196
+ },
197
+ };
198
+ }, [state]);
228
199
 
229
200
  const { converter } = options;
230
201
  const metadata = useMemo(
@@ -232,95 +203,43 @@ const useStatewireThread = (options: AnyOptions): ClientOutput<"thread"> => {
232
203
  pendingCommands: [...pending],
233
204
  isSending: pending.length > 0,
234
205
  connection,
235
- ...(runs !== undefined && { runs }),
206
+ runs,
236
207
  }),
237
208
  [pending, connection, runs],
238
209
  );
239
210
  const converted = useMemo(
240
- (): StatewireThread.State =>
241
- state === undefined
242
- ? LOADING_STATE
243
- : (converter(
244
- state,
245
- metadata as StatewireThread.ConnectionMetadata & {
246
- runs: StatewireThread.Runs;
247
- },
248
- ) as StatewireThread.State),
211
+ (): StatewireThread.State => converter(state, metadata),
249
212
  [converter, state, metadata],
250
213
  );
251
214
  // Dispatch limbo is a materialize concern: the fold makes the record
252
215
  // concrete in state before conversion.
253
216
  const messages = converted.messages;
254
- const queueItems = runs !== undefined ? runs.queue : converted.queue;
255
- const steerQueueItems =
256
- runs !== undefined ? runs.steerQueue : converted.steerQueue;
257
- if (steerQueueItems !== undefined && queueItems === undefined)
258
- throw new Error(
259
- "statewire: the converter's steerQueue projection requires the queue projection",
260
- );
261
- // Seams anchor at the first real convert; the loading placeholder projects nothing.
262
- const [queueSeam] = useState(() => ({
263
- present: undefined as boolean | undefined,
264
- }));
265
- if (state !== undefined && queueSeam.present === undefined)
266
- queueSeam.present = queueItems !== undefined;
267
- if (
268
- queueSeam.present !== undefined &&
269
- queueSeam.present !== (queueItems !== undefined)
270
- )
271
- throw new Error(
272
- "statewire: the converter's queue projection must be stable — it was " +
273
- (queueSeam.present ? "defined" : "undefined") +
274
- " on first convert and changed since",
275
- );
217
+ const liveRunId = runs.runId;
276
218
 
277
219
  const queue = useMemo(
278
- (): ExternalThreadQueueAdapter | undefined =>
279
- queueItems
280
- ? createRunQueueAdapter(
281
- messages,
282
- queueItems,
283
- steerQueueItems,
284
- dispatch,
285
- dispatchSend,
286
- )
287
- : undefined,
288
- [messages, queueItems, steerQueueItems, dispatch, dispatchSend],
220
+ () =>
221
+ createRunQueueAdapter(
222
+ messages,
223
+ liveRunId,
224
+ runs.queue,
225
+ runs.steerQueue,
226
+ dispatch,
227
+ dispatchSend,
228
+ ),
229
+ [messages, liveRunId, runs, dispatch, dispatchSend],
289
230
  );
290
231
 
291
- const inputRequests =
292
- runs !== undefined ? (runs.inputRequests ?? []) : converted.inputRequests;
293
- const [inputSeam] = useState(() => ({
294
- present: undefined as boolean | undefined,
295
- }));
296
- if (state !== undefined && inputSeam.present === undefined)
297
- inputSeam.present = inputRequests !== undefined;
298
- if (
299
- inputSeam.present !== undefined &&
300
- inputSeam.present !== (inputRequests !== undefined)
301
- )
302
- throw new Error(
303
- "statewire: the converter's inputRequests projection must be stable — it was " +
304
- (inputSeam.present ? "defined" : "undefined") +
305
- " on first convert and changed since",
306
- );
307
-
308
- const status: StatewireThread.ThreadStatus =
309
- runs !== undefined
310
- ? runs.status
311
- : state === undefined
312
- ? "loading"
313
- : "ready";
232
+ const inputRequests = runs.inputRequests ?? NO_INPUT_REQUESTS;
314
233
 
315
234
  const extras = useMemo(
316
- (): AssistantTransportExtras => ({
317
- [symbolAssistantTransportExtras]: true,
235
+ (): StatewireThread.Extras => ({
236
+ [symbolStatewireExtras]: true,
318
237
  sendCommand: dispatch,
319
238
  reconnect: connection.reconnect,
320
239
  state,
321
240
  status,
322
- ...(inputRequests !== undefined && { inputRequests }),
323
- ...(runs !== undefined && { runs }),
241
+ inputRequests,
242
+ runs,
324
243
  }),
325
244
  [dispatch, connection.reconnect, state, status, inputRequests, runs],
326
245
  );
@@ -328,47 +247,51 @@ const useStatewireThread = (options: AnyOptions): ClientOutput<"thread"> => {
328
247
  const handleAppend = (message: AppendMessage) => {
329
248
  dispatchSend(
330
249
  message.sourceId != null
331
- ? resolveEditCommand(messages, message)
250
+ ? resolveEditCommand(messages, message, liveRunId)
332
251
  : {
333
252
  type: "run/steer",
334
- message: toWireMessage(message, crypto.randomUUID()),
335
- anchorMessageId: viewedLeafId(messages),
253
+ ...sendFields(
254
+ messages,
255
+ liveRunId,
256
+ toWireMessage(message, crypto.randomUUID()),
257
+ ),
336
258
  },
337
259
  message,
338
260
  );
339
261
  };
340
262
 
341
263
  const handleReload = (parentId: string | null) => {
342
- dispatch(resolveReloadCommand(messages, parentId));
264
+ dispatch(resolveReloadCommand(messages, parentId, liveRunId));
343
265
  };
344
266
 
345
267
  const handleEdit = (message: AppendMessage) => {
346
- dispatch(resolveEditCommand(messages, message));
268
+ dispatch(resolveEditCommand(messages, message, liveRunId));
347
269
  };
348
270
 
349
271
  const thread = useResource(
350
272
  ExternalThread({
351
273
  messages: messages as readonly ExternalThreadMessage[],
352
- isRunning:
353
- runs !== undefined ? runs.status === "running" : converted.isRunning,
274
+ isRunning: status === "running",
354
275
  state: converted.state,
355
276
  extras,
356
277
  attachmentAdapter: options.adapters?.attachments,
357
278
  speechAdapter: options.adapters?.speech,
358
279
  feedbackAdapter: options.adapters?.feedback,
359
280
  onNew: handleAppend,
360
- ...(queue && { queue }),
281
+ queue,
361
282
  ...(options.capabilities?.edit && { onEdit: handleEdit }),
362
283
  ...(options.capabilities?.continue && {
363
- onResume: () => dispatch({ type: "run/continue" }),
284
+ onResume: () =>
285
+ dispatch({
286
+ type: "run/continue",
287
+ ...(liveRunId !== null && { runId: liveRunId }),
288
+ }),
364
289
  }),
365
290
  ...(options.capabilities?.reload && { onReload: handleReload }),
366
- ...(inputRequests !== undefined && {
367
- onAddToolResult: (toolOptions: AddToolResultOptions) =>
368
- dispatch(resolveToolResultInput(inputRequests, toolOptions)),
369
- onRespondToToolApproval: (approval: RespondToToolApprovalOptions) =>
370
- dispatch(resolveToolApprovalInput(inputRequests, approval)),
371
- }),
291
+ onAddToolResult: (toolOptions: AddToolResultOptions) =>
292
+ dispatch(resolveToolResultInput(inputRequests, toolOptions, liveRunId)),
293
+ onRespondToToolApproval: (approval: RespondToToolApprovalOptions) =>
294
+ dispatch(resolveToolApprovalInput(inputRequests, approval, liveRunId)),
372
295
  onCancel: () => {
373
296
  const payload = latest.current.stopPayload?.();
374
297
  if (
@@ -378,16 +301,11 @@ const useStatewireThread = (options: AnyOptions): ClientOutput<"thread"> => {
378
301
  Array.isArray(payload))
379
302
  )
380
303
  throw new Error("statewire: stopPayload must return a plain object");
381
- const runId = runs !== undefined ? runs.runId : converted.runId;
382
- const args =
383
- runId === undefined
384
- ? payload === undefined
385
- ? []
386
- : [payload]
387
- : [{ ...payload, runId }];
388
- void commands["run/stop"]!(...args).catch((error: Error) => {
389
- latest.current.onError?.(error);
390
- });
304
+ void commands["run/stop"]!({ ...payload, runId: runs.runId }).catch(
305
+ (error: Error) => {
306
+ latest.current.onError?.(error);
307
+ },
308
+ );
391
309
  },
392
310
  }),
393
311
  );
@@ -395,19 +313,26 @@ const useStatewireThread = (options: AnyOptions): ClientOutput<"thread"> => {
395
313
  return thread;
396
314
  };
397
315
 
398
- export const StatewireThread: {
399
- <T>(
400
- options: StatewireThread.RunsOptions<T>,
401
- ): ResourceElement<ClientOutput<"thread">>;
402
- <T>(
403
- options: StatewireThread.Options<T>,
404
- ): ResourceElement<ClientOutput<"thread">>;
405
- } = (options: AnyOptions): ResourceElement<ClientOutput<"thread">> =>
406
- resource(useStatewireThread)(options);
316
+ export const StatewireThread = <T>(
317
+ options: StatewireThread.Options<T>,
318
+ ): ResourceElement<ClientOutput<"thread">> =>
319
+ resource(useStatewireThread)(options as StatewireThread.Options<any>);
407
320
 
408
321
  export namespace StatewireThread {
322
+ type UserCommands = Assistant.Commands[keyof Assistant.Commands];
323
+
409
324
  export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;
410
325
 
326
+ export type Extras = {
327
+ [symbolStatewireExtras]: true;
328
+ sendCommand: (command: Command) => void;
329
+ reconnect: () => void;
330
+ state: unknown;
331
+ status: ThreadStatus;
332
+ inputRequests: readonly InputRequestState[];
333
+ runs: Runs;
334
+ };
335
+
411
336
  export type TextPart = {
412
337
  readonly type: "text";
413
338
  readonly text: string;
@@ -435,11 +360,13 @@ export namespace StatewireThread {
435
360
 
436
361
  export type RunEnqueueCommand = {
437
362
  readonly type: "run/enqueue";
363
+ /** The run this command targets — the live run's id, or a fresh client-minted uuid on run-creating sends. */
364
+ readonly runId: string;
438
365
  } & (
439
366
  | {
440
367
  readonly message: UserMessage;
441
- /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */
442
- readonly anchorMessageId?: string | null;
368
+ /** Run anchor: the message the new content grows after, null asserting an empty thread. Present on run-creating sends; absent when targeting the live run. */
369
+ readonly runAnchorMessageId?: string | null;
443
370
  }
444
371
  | { readonly messageId: string }
445
372
  ) &
@@ -447,11 +374,13 @@ export namespace StatewireThread {
447
374
 
448
375
  export type RunSteerCommand = {
449
376
  readonly type: "run/steer";
377
+ /** The run this command targets — the live run's id, or a fresh client-minted uuid on run-creating sends. */
378
+ readonly runId: string;
450
379
  } & (
451
380
  | {
452
381
  readonly message: UserMessage;
453
- /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */
454
- readonly anchorMessageId?: string | null;
382
+ /** Run anchor: the message the new content grows after, null asserting an empty thread. Present on run-creating sends; absent when targeting the live run. */
383
+ readonly runAnchorMessageId?: string | null;
455
384
  }
456
385
  | { readonly messageId: string }
457
386
  ) &
@@ -459,19 +388,23 @@ export namespace StatewireThread {
459
388
 
460
389
  export type RunDequeueCommand = {
461
390
  readonly type: "run/dequeue";
391
+ readonly runId: string;
462
392
  readonly messageId: string;
463
393
  };
464
394
 
465
395
  export type RunEditCommand = {
466
396
  readonly type: "run/edit";
397
+ /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */
398
+ readonly runId: string;
467
399
  readonly message: UserMessage;
468
400
  readonly sourceId: string;
469
401
  /** Asserts `sourceId`'s parent — the rewind target; null names the root. */
470
- readonly rollbackTo: string | null;
402
+ readonly runAnchorMessageId: string | null;
471
403
  };
472
404
 
473
405
  export type RunContinueCommand = {
474
406
  readonly type: "run/continue";
407
+ readonly runId?: string;
475
408
  };
476
409
 
477
410
  export type ToolCallInputRequest = {
@@ -498,23 +431,11 @@ export namespace StatewireThread {
498
431
  | ToolApprovalInputRequest
499
432
  | CustomInputRequest;
500
433
 
501
- export type ToolCallInputResponse = {
502
- readonly output: ReadonlyJSONValue;
503
- /** Default false; when true, `output` carries the error payload. */
504
- readonly isError?: boolean;
505
- readonly artifact?: ReadonlyJSONValue;
506
- };
507
-
508
- export type ToolApprovalInputResponse = {
509
- readonly decision: "approve" | "reject" | "edit" | "respond";
510
- readonly editedArgs?: ReadonlyJSONValue;
511
- readonly message?: string;
512
- };
513
-
514
434
  export type InputResponse = ReadonlyJSONValue;
515
435
 
516
436
  export type RunInputCommand = {
517
437
  readonly type: "run/input";
438
+ readonly runId?: string;
518
439
  readonly requestId: string;
519
440
  readonly response: InputResponse;
520
441
  };
@@ -526,9 +447,11 @@ export namespace StatewireThread {
526
447
 
527
448
  export type RunReloadCommand = {
528
449
  readonly type: "run/reload";
450
+ /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */
451
+ readonly runId: string;
529
452
  readonly sourceId: string;
530
453
  /** Asserts `sourceId`'s parent — the rewind target; null names the root. */
531
- readonly rollbackTo: string | null;
454
+ readonly runAnchorMessageId: string | null;
532
455
  };
533
456
 
534
457
  export type RunCommand =
@@ -540,42 +463,18 @@ export namespace StatewireThread {
540
463
  | RunReloadCommand
541
464
  | RunInputCommand;
542
465
 
543
- export type Command = AssistantTransportThread.Command | RunCommand;
466
+ export type Command = RunCommand | UserCommands;
544
467
 
545
468
  /** A queued message projected out of the host state, wire shape. */
546
- export type QueueItem = {
469
+ export type RunQueueItem = {
547
470
  readonly id: string;
548
471
  readonly parts: readonly (TextPart | FilePart)[];
549
472
  };
550
473
 
551
- export type State = {
552
- readonly messages: readonly ThreadMessage[];
553
- readonly state?: ReadonlyJSONValue;
554
- readonly isRunning: boolean;
555
- /** The live run's id projected out of the host state; stamped onto `run/stop`. */
556
- readonly runId?: string | null;
557
- /**
558
- * The host's regular queue lane projected out of the state. Returning it
559
- * (even empty) turns on the queue capability: sends become `run/enqueue`
560
- * / `run/steer` commands and item controls send the `run/*` queue
561
- * commands. Presence must be stable across conversions.
562
- */
563
- readonly queue?: readonly QueueItem[];
564
- /** The host's steer lane; requires `queue`. Absent means empty. */
565
- readonly steerQueue?: readonly QueueItem[];
566
- /**
567
- * The host's parked input requests projected out of the state. Returning
568
- * it (even empty) routes tool results and approvals with a matching
569
- * pending request through `run/input`. Presence must be stable across
570
- * conversions.
571
- */
572
- readonly inputRequests?: readonly InputRequestState[];
573
- };
574
-
575
474
  /** Run subsystem status replicated by the host. */
576
475
  export type RunStatus = "running" | "stopped" | "error" | "input-required";
577
476
 
578
- /** The thread's status: `"loading"` while awaiting the attach snapshot, `"ready"` while resting, otherwise the run's status. */
477
+ /** The thread's status, derived from the state: `"loading"` while the runs mount is absent, `"ready"` while resting, otherwise the run's status. */
579
478
  export type ThreadStatus = "loading" | "ready" | RunStatus;
580
479
 
581
480
  /** A queue-lane entry as replicated: the user message plus host-stamped `meta`. */
@@ -616,7 +515,7 @@ export namespace StatewireThread {
616
515
 
617
516
  /** A replicated run entry — one element of the mount's `runs` array. */
618
517
  export type RunState = {
619
- /** The run's identity — minted at dispatch, persists through input-required, null in error/stop. */
518
+ /** The run's identity — client-minted, adopted by the host at run creation; persists through steers, input-required, and error/stop, retiring only when the queue drains and the run completes. */
620
519
  readonly runId: string | null;
621
520
  readonly status: RunStatus;
622
521
  readonly queue: readonly RunsQueueEntry[];
@@ -644,10 +543,9 @@ export namespace StatewireThread {
644
543
  readonly runs: readonly RunState[];
645
544
  };
646
545
 
647
- /** The run subsystem's typed read — `runs[0]` of the selected mount with unsettled commands folded in, ready defaults while resting, loading defaults while awaiting the attach snapshot. */
546
+ /** The run subsystem's typed read — `runs[0]` of the state with unsettled commands folded in, resting defaults while no entry is live. */
648
547
  export type Runs = {
649
- readonly status: ThreadStatus;
650
- /** The live run's id — non-null in running and input-required; stamped onto `run/stop`. */
548
+ /** The live run's id — non-null whenever a run entry is live (running, input-required, error/stop); the target for `run/*` sends. */
651
549
  readonly runId: string | null;
652
550
  readonly queue: readonly RunsQueueEntry[];
653
551
  readonly steerQueue: readonly RunsQueueEntry[];
@@ -663,25 +561,20 @@ export namespace StatewireThread {
663
561
  isSending: boolean;
664
562
  /** Statewire connection status; local transports are always `live`. */
665
563
  connection: StatewireClient.ConnectionState;
666
- /** The typed runs read; present iff the `runs` option is set. */
667
- runs?: Runs;
564
+ /** The typed runs read. */
565
+ runs: Runs;
668
566
  };
669
567
 
670
- export type StateConverter<T> = (
671
- state: T,
672
- connectionMetadata: ConnectionMetadata,
673
- ) => State;
674
-
675
- /** Converter output in runs mode: app-owned keys only — the lib projects the run mounts itself. */
676
- export type RunsConverterState = {
568
+ /** Converter output: app-owned keys only — the lib projects the run mounts itself. */
569
+ export type State = {
677
570
  readonly messages: readonly ThreadMessage[];
678
571
  readonly state?: ReadonlyJSONValue;
679
572
  };
680
573
 
681
- export type RunsStateConverter<T> = (
574
+ export type StateConverter<T> = (
682
575
  state: T,
683
- connectionMetadata: ConnectionMetadata & { runs: Runs },
684
- ) => RunsConverterState;
576
+ connectionMetadata: ConnectionMetadata,
577
+ ) => State;
685
578
 
686
579
  /**
687
580
  * Payload of the built-in `run/stop` command. `reason` is the one well-known
@@ -694,10 +587,18 @@ export namespace StatewireThread {
694
587
 
695
588
  export type Options<T> = {
696
589
  transport: Transport<T>;
697
- /** Preloads the thread: published and interactive from the first render, replaced by the attach snapshot. Omitted, the thread stays loading until attach. */
698
- initialState?: T | undefined;
590
+ /** The pre-attach state, replaced by the attach snapshot. `runs: []` projects ready (interactive from the first render); an absent runs mount projects loading until attach. */
591
+ initialState: T;
699
592
  converter: StateConverter<T>;
700
- runs?: undefined;
593
+ /** Folds app-owned keys for an unsettled command into the draft; runs after the lib's run-dialect reducer. */
594
+ optimistic?:
595
+ | StatewireClient.Optimistic<
596
+ T,
597
+ Record<string, (...args: any[]) => unknown>
598
+ >
599
+ | undefined;
600
+ /** Makes dispatch records concrete in the draft (runs after the optimistic folds); without it, dispatch limbo stays out of `messages`. */
601
+ materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;
701
602
  /**
702
603
  * "command-send" mirrors the client's ambient model context (system,
703
604
  * tools, callSettings, config) to the server over the command channel —
@@ -741,25 +642,9 @@ export namespace StatewireThread {
741
642
  }
742
643
  | undefined;
743
644
  };
744
-
745
- /** Options with the runs read enabled: the lib types the run mounts and the converter returns app-owned keys only. */
746
- export type RunsOptions<T> = Omit<Options<T>, "converter" | "runs"> & {
747
- /** `true` reads the run mounts off the state root; a selector picks a nested mount. */
748
- runs: true | ((state: T) => unknown);
749
- converter: RunsStateConverter<T>;
750
- /** Folds app-owned keys for an unsettled command into the draft; runs after the lib's run-dialect reducer. */
751
- optimistic?:
752
- | StatewireClient.Optimistic<
753
- T,
754
- Record<string, (...args: any[]) => unknown>
755
- >
756
- | undefined;
757
- /** Makes dispatch records concrete in the draft (runs after the optimistic folds); without it, dispatch limbo stays out of `messages`. */
758
- materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;
759
- };
760
645
  }
761
646
 
762
- declare module "@assistant-ui/react" {
647
+ declare module "@assistant-ui/core" {
763
648
  namespace Assistant {
764
649
  interface Commands {
765
650
  runEnqueue: StatewireThread.RunEnqueueCommand;