@assistant-ui/react-statewire 0.13.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 (54) hide show
  1. package/dist/StatewireThread.d.ts +62 -97
  2. package/dist/StatewireThread.d.ts.map +1 -1
  3. package/dist/StatewireThread.js +31 -46
  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.map +1 -1
  14. package/dist/runCommands.d.ts +8 -24
  15. package/dist/runCommands.d.ts.map +1 -1
  16. package/dist/runCommands.js +3 -3
  17. package/dist/runCommands.js.map +1 -1
  18. package/dist/runsOptimistic.d.ts.map +1 -1
  19. package/dist/runsOptimistic.js +3 -2
  20. package/dist/runsOptimistic.js.map +1 -1
  21. package/package.json +4 -5
  22. package/src/StatewireThread.runs.test.tsx +10 -15
  23. package/src/StatewireThread.test.tsx +227 -405
  24. package/src/StatewireThread.ts +98 -210
  25. package/src/__tests__/testHelpers.tsx +6 -226
  26. package/src/hooks.ts +11 -32
  27. package/src/index.ts +2 -4
  28. package/src/inputRequests.ts +6 -8
  29. package/src/runCommands.ts +17 -23
  30. package/src/runsOptimistic.ts +5 -3
  31. package/dist/AssistantTransportThread.d.ts +0 -227
  32. package/dist/AssistantTransportThread.d.ts.map +0 -1
  33. package/dist/AssistantTransportThread.js +0 -264
  34. package/dist/AssistantTransportThread.js.map +0 -1
  35. package/dist/host.d.ts +0 -38
  36. package/dist/host.d.ts.map +0 -1
  37. package/dist/host.js +0 -299
  38. package/dist/host.js.map +0 -1
  39. package/dist/replayBoundaryStream.d.ts +0 -6
  40. package/dist/replayBoundaryStream.d.ts.map +0 -1
  41. package/dist/replayBoundaryStream.js +0 -49
  42. package/dist/replayBoundaryStream.js.map +0 -1
  43. package/dist/stateOps.d.ts +0 -10
  44. package/dist/stateOps.d.ts.map +0 -1
  45. package/dist/stateOps.js +0 -114
  46. package/dist/stateOps.js.map +0 -1
  47. package/src/AssistantTransportThread.ts +0 -791
  48. package/src/athena.e2e.test.tsx +0 -654
  49. package/src/host.ts +0 -437
  50. package/src/legacy-diff.test.tsx +0 -628
  51. package/src/replayBoundaryStream.ts +0 -71
  52. package/src/stateOps.test.ts +0 -165
  53. package/src/stateOps.ts +0 -126
  54. package/src/transport.test.tsx +0 -3001
@@ -1,791 +0,0 @@
1
- import {
2
- useCallback,
3
- useEffect,
4
- useMemo,
5
- useRef,
6
- useState,
7
- useSyncExternalStore,
8
- } from "react";
9
- import { resource, useResource } from "@assistant-ui/tap";
10
- import type { ResourceElement } from "@assistant-ui/tap";
11
- import { ExternalThread } from "@assistant-ui/react";
12
- import type { Assistant, ExternalThreadMessage } from "@assistant-ui/react";
13
- import {
14
- forwardTransformScopes,
15
- useAssistantClientRef,
16
- } from "@assistant-ui/store";
17
- import type { ClientOutput } from "@assistant-ui/store";
18
- import { createMessageQueue } from "@assistant-ui/core";
19
- import type {
20
- AddToolResultOptions,
21
- AppendMessage,
22
- AttachmentAdapter,
23
- LanguageModelConfig,
24
- LanguageModelV1CallSettings,
25
- MessageQueueController,
26
- MessageQueueDriver,
27
- RespondToToolApprovalOptions,
28
- ResumeToolCallOptions,
29
- ThreadMessage,
30
- ToolExecutionStatus,
31
- } from "@assistant-ui/core";
32
- import type { ReadonlyJSONValue } from "assistant-stream/utils";
33
- import { ToolInvocationTracker } from "@assistant-ui/core/internal";
34
- import { applyOptimistic, useStatewire } from "statewire";
35
- import type { StatewireClient } from "statewire";
36
- import type { StatewireThread } from "./StatewireThread";
37
- import { AssistantTransportHost } from "./host";
38
- import type {
39
- AssistantTransportHostCommands,
40
- AssistantTransportHostState,
41
- HostQueueCell,
42
- HostRunContext,
43
- SendOptions,
44
- } from "./host";
45
- import {
46
- createRunQueueAdapter,
47
- resolveEditCommand,
48
- resolveReloadCommand,
49
- sendFields,
50
- toWireMessage,
51
- } from "./runCommands";
52
- import { runsOptimistic } from "./runsOptimistic";
53
- import {
54
- resolveToolApprovalInput,
55
- resolveToolResultInput,
56
- } from "./inputRequests";
57
-
58
- const EMPTY_TOOL_STATUSES: Record<string, ToolExecutionStatus> = {};
59
- const EMPTY_QUEUE_ITEMS: MessageQueueController["adapter"]["items"] = [];
60
- const subscribeNoop = () => () => {};
61
-
62
- export const symbolAssistantTransportExtras = Symbol(
63
- "assistant-transport-extras",
64
- );
65
-
66
- export type AssistantTransportExtras = {
67
- [symbolAssistantTransportExtras]: true;
68
- sendCommand: (command: AssistantTransportThread.Command) => void;
69
- reconnect: () => void;
70
- state: unknown;
71
- /** The thread status; present iff StatewireThread. */
72
- status?: StatewireThread.ThreadStatus;
73
- /** The host's parked input requests; absent when the converter does not project them. */
74
- inputRequests?: readonly AssistantTransportThread.InputRequestState[];
75
- /** The typed runs read; present iff StatewireThread runs with the `runs` option. */
76
- runs?: StatewireThread.Runs;
77
- };
78
-
79
- export const asAssistantTransportExtras = (
80
- extras: unknown,
81
- ): AssistantTransportExtras => {
82
- if (
83
- typeof extras !== "object" ||
84
- extras == null ||
85
- !(symbolAssistantTransportExtras in extras)
86
- )
87
- throw new Error(
88
- "This method can only be called when you are using AssistantTransportThread or StatewireThread",
89
- );
90
-
91
- return extras as AssistantTransportExtras;
92
- };
93
-
94
- const foldOptimistic = (
95
- state: unknown,
96
- commands: readonly AssistantTransportThread.Command[],
97
- optimistic: AssistantTransportThread.Optimistic<unknown>,
98
- ctxOf: (command: object) => StatewireClient.OptimisticContext,
99
- ): unknown => {
100
- let next = state;
101
- for (const command of commands) {
102
- try {
103
- next = applyOptimistic(next, (draft) =>
104
- optimistic(draft, command, ctxOf(command)),
105
- );
106
- } catch (error) {
107
- console.error(
108
- `statewire: optimistic reducer threw for "${command.type}"; dropping its optimistic update`,
109
- error,
110
- );
111
- }
112
- }
113
- return next;
114
- };
115
-
116
- const messagesContainToolCall = (
117
- messages: readonly ThreadMessage[],
118
- toolCallId: string,
119
- ): boolean =>
120
- messages.some((message) =>
121
- message.content.some(
122
- (part) =>
123
- part.type === "tool-call" &&
124
- (part.toolCallId === toolCallId ||
125
- (part.messages !== undefined &&
126
- messagesContainToolCall(part.messages, toolCallId))),
127
- ),
128
- );
129
-
130
- const useAssistantTransportThread = (
131
- options: AssistantTransportThread.Options<any>,
132
- ): ClientOutput<"thread"> => {
133
- const clientRef = useAssistantClientRef();
134
- const [getRunContext] = useState(() => (): HostRunContext => {
135
- const aui = clientRef.current ?? clientRef.parent;
136
- // legacy parity: a threadListItem throw must not kill the run
137
- let threadId: string | null = null;
138
- try {
139
- threadId = aui.threadListItem().getState().remoteId ?? null;
140
- } catch {}
141
- return {
142
- modelContext: aui.modelContext().getModelContext(),
143
- threadId,
144
- };
145
- });
146
-
147
- const [queueCell] = useState(
148
- (): HostQueueCell => ({ current: { queued: [], inTransit: [] } }),
149
- );
150
- const { state, commands, connection } = useStatewire<
151
- AssistantTransportHostState,
152
- AssistantTransportHostCommands
153
- >({
154
- transport: AssistantTransportHost({ ...options, getRunContext, queueCell }),
155
- });
156
- const { agent: agentState, isSending, isReplaying } = state;
157
- const queue = queueCell.current;
158
-
159
- const dispatch = useCallback(
160
- (command: AssistantTransportThread.Command, opts?: SendOptions) => {
161
- void commands.send(command, opts).catch(() => {});
162
- },
163
- [commands],
164
- );
165
-
166
- const [toolStatuses, setToolStatuses] =
167
- useState<Record<string, ToolExecutionStatus>>(EMPTY_TOOL_STATUSES);
168
-
169
- const [ctxOf] = useState(() => {
170
- const ctxs = new WeakMap<object, StatewireClient.OptimisticContext>();
171
- let seq = 0;
172
- return (command: object): StatewireClient.OptimisticContext => {
173
- let ctx = ctxs.get(command);
174
- if (ctx === undefined) {
175
- ctx = { ts: Date.now(), seq: ++seq };
176
- ctxs.set(command, ctx);
177
- }
178
- return ctx;
179
- };
180
- });
181
-
182
- const { converter, optimistic, runs: runsOption, materialize } = options;
183
- const [runsSeam] = useState(() => runsOption !== undefined);
184
- if (runsSeam !== (runsOption !== undefined))
185
- throw new Error(
186
- "statewire: the runs option must be stable — it was " +
187
- (runsSeam ? "set" : "unset") +
188
- " on first render and changed since",
189
- );
190
- const [materializeSeam] = useState(() => materialize !== undefined);
191
- if (materializeSeam !== (materialize !== undefined))
192
- throw new Error(
193
- "statewire: the materialize option must be stable — it was " +
194
- (materializeSeam ? "set" : "unset") +
195
- " on first render and changed since",
196
- );
197
-
198
- const project = useCallback(
199
- (state: unknown): unknown => {
200
- const fold: AssistantTransportThread.Optimistic<unknown> | undefined =
201
- runsOption !== undefined
202
- ? (draft, command, ctx) => {
203
- runsOptimistic(
204
- runsOption === true ? draft : runsOption(draft as never),
205
- { method: command.type, params: [command] },
206
- ctx,
207
- );
208
- optimistic?.(draft, command, ctx);
209
- }
210
- : optimistic;
211
- let next = fold
212
- ? foldOptimistic(
213
- state,
214
- [...queue.inTransit, ...queue.queued],
215
- fold,
216
- ctxOf,
217
- )
218
- : state;
219
- if (materialize) {
220
- try {
221
- next = applyOptimistic(next, (draft) => materialize(draft as never));
222
- } catch (error) {
223
- console.error(
224
- "statewire: materialize threw; publishing without its update",
225
- error,
226
- );
227
- }
228
- }
229
- return next;
230
- },
231
- [runsOption, optimistic, materialize, queue, ctxOf],
232
- );
233
- const projected = useMemo(() => project(agentState), [project, agentState]);
234
- const converted = useMemo(() => converter(projected), [converter, projected]);
235
- const convertedRef = useRef(converted);
236
- convertedRef.current = converted;
237
-
238
- const liveRunId = useMemo((): string | null => {
239
- if (runsOption === undefined) return null;
240
- const mount = (
241
- runsOption === true ? projected : runsOption(projected as never)
242
- ) as { runs?: readonly { runId: string | null }[] } | undefined;
243
- return mount?.runs?.[0]?.runId ?? null;
244
- }, [runsOption, projected]);
245
- const liveRunIdRef = useRef(liveRunId);
246
- liveRunIdRef.current = liveRunId;
247
-
248
- const [toolInvocations] = useState(
249
- () =>
250
- new ToolInvocationTracker(
251
- () => {
252
- const aui = clientRef.current ?? clientRef.parent;
253
- return aui.modelContext().getModelContext().tools;
254
- },
255
- {
256
- onResult: (command) => {
257
- const messages = convertedRef.current
258
- .messages as readonly ThreadMessage[];
259
- if (!messagesContainToolCall(messages, command.toolCallId)) return;
260
- dispatch(
261
- resolveToolResultInput(
262
- convertedRef.current.inputRequests ?? [],
263
- command,
264
- liveRunIdRef.current,
265
- ),
266
- );
267
- },
268
- onStatusesChange: (statuses) => {
269
- setToolStatuses(
270
- statuses.size === 0
271
- ? EMPTY_TOOL_STATUSES
272
- : Object.fromEntries(statuses),
273
- );
274
- },
275
- },
276
- ),
277
- );
278
- // dep-less by design: setState dedups identical snapshots internally
279
- useEffect(() => {
280
- toolInvocations.setState({
281
- messages: converted.messages as readonly ThreadMessage[],
282
- isRunning: converted.isRunning,
283
- isLoading: isReplaying,
284
- });
285
- });
286
- useEffect(
287
- () => () => {
288
- toolInvocations.reset();
289
- },
290
- [toolInvocations],
291
- );
292
-
293
- const inputRequests = converted.inputRequests;
294
- const [inputSeam] = useState(() => ({
295
- present: inputRequests !== undefined,
296
- }));
297
- if (inputSeam.present !== (inputRequests !== undefined))
298
- throw new Error(
299
- "statewire: the converter's inputRequests projection must be stable — it was " +
300
- (inputSeam.present ? "defined" : "undefined") +
301
- " on first convert and changed since",
302
- );
303
-
304
- const extras = useMemo(
305
- (): AssistantTransportExtras => ({
306
- [symbolAssistantTransportExtras]: true,
307
- sendCommand: dispatch,
308
- reconnect: connection.reconnect,
309
- state: agentState,
310
- ...(inputRequests !== undefined && { inputRequests }),
311
- }),
312
- [dispatch, connection.reconnect, agentState, inputRequests],
313
- );
314
-
315
- const handleEdit = (message: AppendMessage) => {
316
- const command = resolveEditCommand(
317
- convertedRef.current.messages,
318
- message,
319
- liveRunIdRef.current,
320
- );
321
- void toolInvocations.abort().then(() => dispatch(command));
322
- };
323
-
324
- const handleAppend = (message: AppendMessage) => {
325
- if (message.sourceId != null) return handleEdit(message);
326
- const startRun = message.startRun ?? message.role === "user";
327
- const command: AssistantTransportThread.Command = {
328
- type: "run/steer",
329
- ...sendFields(
330
- convertedRef.current.messages,
331
- liveRunIdRef.current,
332
- toWireMessage(message, crypto.randomUUID()),
333
- ),
334
- };
335
- void commands.setParentId(message.parentId).catch(() => {});
336
-
337
- const send = () => dispatch(command, { schedule: startRun });
338
- if (startRun) {
339
- // abort in-flight tool executions so their late results cannot race the new turn
340
- void toolInvocations.abort().then(send);
341
- } else {
342
- send();
343
- }
344
- };
345
-
346
- const handleCancel = () => {
347
- void toolInvocations.abort();
348
- void commands.cancel().catch(() => {});
349
- };
350
-
351
- const driverRef = useRef<{
352
- run: MessageQueueDriver["run"];
353
- cancel: () => void;
354
- }>(undefined as never);
355
- driverRef.current = {
356
- // the queued message was stamped with the head at enqueue time; restamp so
357
- // it appends to the thread the finished run left behind
358
- run: (message) =>
359
- handleAppend({
360
- ...message,
361
- parentId: convertedRef.current.messages.at(-1)?.id ?? null,
362
- }),
363
- cancel: handleCancel,
364
- };
365
-
366
- const queueProjection = converted.queue;
367
- const steerProjection = converted.steerQueue;
368
- if (steerProjection !== undefined && queueProjection === undefined)
369
- throw new Error(
370
- "statewire: the converter's steerQueue projection requires the queue projection",
371
- );
372
- if (queueProjection !== undefined && options.capabilities?.queue)
373
- throw new Error(
374
- "statewire: the converter's queue projection excludes capabilities.queue",
375
- );
376
- const [queueSeam] = useState(() => ({
377
- present: queueProjection !== undefined,
378
- }));
379
- if (queueSeam.present !== (queueProjection !== undefined))
380
- throw new Error(
381
- "statewire: the converter's queue projection must be stable — it was " +
382
- (queueSeam.present ? "defined" : "undefined") +
383
- " on first convert and changed since",
384
- );
385
- const serverQueue = useMemo(
386
- () =>
387
- queueProjection
388
- ? createRunQueueAdapter(
389
- converted.messages,
390
- liveRunId,
391
- queueProjection,
392
- steerProjection,
393
- dispatch,
394
- (command) => dispatch(command),
395
- )
396
- : undefined,
397
- [converted.messages, liveRunId, queueProjection, steerProjection, dispatch],
398
- );
399
-
400
- const enableQueue = options.capabilities?.queue === true;
401
- const queueRef = useRef<MessageQueueController | null>(null);
402
- if (enableQueue && !queueRef.current) {
403
- queueRef.current = createMessageQueue({
404
- run: (message, opts) => driverRef.current.run(message, opts),
405
- cancel: () => driverRef.current.cancel(),
406
- });
407
- } else if (!enableQueue && queueRef.current) {
408
- queueRef.current.clear();
409
- queueRef.current = null;
410
- }
411
- const messageQueue = queueRef.current;
412
-
413
- // fresh view per snapshot: the controller mutates adapter.items in place,
414
- // which a stable prop identity would hide from the thread resource
415
- const queueItems = useSyncExternalStore(
416
- messageQueue?.subscribe ?? subscribeNoop,
417
- () => messageQueue?.adapter.items ?? EMPTY_QUEUE_ITEMS,
418
- () => EMPTY_QUEUE_ITEMS,
419
- );
420
- const steerQueueItems = useSyncExternalStore(
421
- messageQueue?.subscribe ?? subscribeNoop,
422
- () => messageQueue?.adapter.steerItems ?? EMPTY_QUEUE_ITEMS,
423
- () => EMPTY_QUEUE_ITEMS,
424
- );
425
-
426
- // settled edge: the queue only advances once the host run loop has fully
427
- // released (isSending), the converted state agrees, and no client tool from
428
- // the finished run is still executing
429
- const busy =
430
- isSending || converted.isRunning || Object.keys(toolStatuses).length > 0;
431
- const wasBusyRef = useRef(false);
432
- useEffect(() => {
433
- if (wasBusyRef.current === busy) return;
434
- wasBusyRef.current = busy;
435
- if (busy) messageQueue?.notifyBusy();
436
- else messageQueue?.notifyIdle();
437
- });
438
-
439
- return useResource(
440
- ExternalThread({
441
- messages: converted.messages as readonly ExternalThreadMessage[],
442
- isRunning: converted.isRunning,
443
- isLoading: isReplaying,
444
- state: converted.state,
445
- extras,
446
- attachmentAdapter: options.adapters?.attachments,
447
- onNew: handleAppend,
448
- ...(serverQueue
449
- ? { queue: serverQueue }
450
- : messageQueue && {
451
- queue: {
452
- ...messageQueue.adapter,
453
- items: queueItems,
454
- steerItems: steerQueueItems,
455
- },
456
- }),
457
- ...(options.capabilities?.edit && { onEdit: handleEdit }),
458
- onReload: (parentId: string | null) => {
459
- const command = resolveReloadCommand(
460
- convertedRef.current.messages,
461
- parentId,
462
- liveRunIdRef.current,
463
- );
464
- void toolInvocations.abort().then(() => dispatch(command));
465
- },
466
- onCancel: () => {
467
- // user cancel drops pending lanes; a steer interrupt (driver.cancel) keeps them
468
- messageQueue?.clear();
469
- handleCancel();
470
- },
471
- onResume: () => {
472
- if (options.capabilities?.continue) {
473
- const runId = liveRunIdRef.current;
474
- dispatch({
475
- type: "run/continue",
476
- ...(runId !== null && { runId }),
477
- });
478
- return;
479
- }
480
- if (!options.resumeApi)
481
- throw new Error("Must pass resumeApi to options to resume runs");
482
- void commands.resume().catch(() => {});
483
- },
484
- ...(inputRequests !== undefined && {
485
- onAddToolResult: (toolOptions: AddToolResultOptions) =>
486
- dispatch(
487
- resolveToolResultInput(
488
- convertedRef.current.inputRequests!,
489
- toolOptions,
490
- liveRunIdRef.current,
491
- ),
492
- ),
493
- onRespondToToolApproval: (options: RespondToToolApprovalOptions) =>
494
- dispatch(
495
- resolveToolApprovalInput(
496
- convertedRef.current.inputRequests!,
497
- options,
498
- liveRunIdRef.current,
499
- ),
500
- ),
501
- }),
502
- onResumeToolCall: ({ toolCallId, payload }: ResumeToolCallOptions) => {
503
- if (!toolInvocations.resume(toolCallId, payload))
504
- throw new Error(`Tool call ${toolCallId} is not waiting for resume.`);
505
- },
506
- onLoadExternalState: (imported: unknown) => {
507
- void commands.importState(imported).catch(() => {});
508
- // reset() aborts tools before React re-renders — gate their late results against the imported state
509
- convertedRef.current = converter(project(imported));
510
- toolInvocations.reset();
511
- setToolStatuses(EMPTY_TOOL_STATUSES);
512
- },
513
- }),
514
- );
515
- };
516
-
517
- export const AssistantTransportThread = <T>(
518
- options: AssistantTransportThread.Options<T>,
519
- ): ResourceElement<ClientOutput<"thread">> =>
520
- resource(useAssistantTransportThread)(
521
- options as AssistantTransportThread.Options<any>,
522
- );
523
-
524
- export namespace AssistantTransportThread {
525
- type UserCommands = Assistant.Commands[keyof Assistant.Commands];
526
-
527
- export type TextPart = {
528
- readonly type: "text";
529
- readonly text: string;
530
- };
531
-
532
- export type FilePart = {
533
- readonly type: "file";
534
- readonly mediaType: string;
535
- readonly url: string;
536
- readonly filename?: string;
537
- };
538
-
539
- export type RunUserMessage = {
540
- readonly id: string;
541
- readonly role: "user";
542
- readonly parts: readonly (TextPart | FilePart)[];
543
- readonly metadata?: Record<string, unknown>;
544
- };
545
-
546
- /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */
547
- export type RunPlacement = {
548
- readonly insertAfter?: string | null;
549
- readonly insertBefore?: string | null;
550
- };
551
-
552
- export type RunEnqueueCommand = {
553
- readonly type: "run/enqueue";
554
- /** The run this command targets — the live run's id, or a fresh client-minted uuid on run-creating sends. */
555
- readonly runId: string;
556
- } & (
557
- | {
558
- readonly message: RunUserMessage;
559
- /** 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. */
560
- readonly runAnchorMessageId?: string | null;
561
- }
562
- | { readonly messageId: string }
563
- ) &
564
- RunPlacement;
565
-
566
- export type RunSteerCommand = {
567
- readonly type: "run/steer";
568
- /** The run this command targets — the live run's id, or a fresh client-minted uuid on run-creating sends. */
569
- readonly runId: string;
570
- } & (
571
- | {
572
- readonly message: RunUserMessage;
573
- /** 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. */
574
- readonly runAnchorMessageId?: string | null;
575
- }
576
- | { readonly messageId: string }
577
- ) &
578
- RunPlacement;
579
-
580
- export type RunDequeueCommand = {
581
- readonly type: "run/dequeue";
582
- readonly runId: string;
583
- readonly messageId: string;
584
- };
585
-
586
- export type RunEditCommand = {
587
- readonly type: "run/edit";
588
- /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */
589
- readonly runId: string;
590
- readonly message: RunUserMessage;
591
- readonly sourceId: string;
592
- /** Asserts `sourceId`'s parent — the rewind target; null names the root. */
593
- readonly runAnchorMessageId: string | null;
594
- };
595
-
596
- export type RunContinueCommand = {
597
- readonly type: "run/continue";
598
- readonly runId?: string;
599
- };
600
-
601
- export type ToolCallInputRequest = {
602
- readonly type: "tool-call";
603
- readonly id: string;
604
- readonly toolCallId: string;
605
- };
606
-
607
- export type ToolApprovalInputRequest = {
608
- readonly type: "tool-approval";
609
- readonly id: string;
610
- readonly toolCallId: string;
611
- };
612
-
613
- export type CustomInputRequest = {
614
- readonly type: string;
615
- readonly id: string;
616
- readonly [key: string]: ReadonlyJSONValue | undefined;
617
- };
618
-
619
- /** A host request parking the run until answered; open union for custom types. */
620
- export type InputRequest =
621
- | ToolCallInputRequest
622
- | ToolApprovalInputRequest
623
- | CustomInputRequest;
624
-
625
- export type ToolCallInputResponse = {
626
- readonly output: ReadonlyJSONValue;
627
- /** Default false; when true, `output` carries the error payload. */
628
- readonly isError?: boolean;
629
- readonly artifact?: ReadonlyJSONValue;
630
- };
631
-
632
- export type ToolApprovalInputResponse = {
633
- readonly decision: "approve" | "reject" | "edit" | "respond";
634
- readonly editedArgs?: ReadonlyJSONValue;
635
- readonly message?: string;
636
- };
637
-
638
- export type InputResponse = ReadonlyJSONValue;
639
-
640
- export type RunInputCommand = {
641
- readonly type: "run/input";
642
- readonly runId?: string;
643
- readonly requestId: string;
644
- readonly response: InputResponse;
645
- };
646
-
647
- /** An input request projected out of the host state with its response echo. */
648
- export type InputRequestState = InputRequest & {
649
- readonly response: InputResponse | null;
650
- };
651
-
652
- export type RunReloadCommand = {
653
- readonly type: "run/reload";
654
- /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */
655
- readonly runId: string;
656
- readonly sourceId: string;
657
- /** Asserts `sourceId`'s parent — the rewind target; null names the root. */
658
- readonly runAnchorMessageId: string | null;
659
- };
660
-
661
- export type RunCommand =
662
- | RunEnqueueCommand
663
- | RunSteerCommand
664
- | RunDequeueCommand
665
- | RunEditCommand
666
- | RunContinueCommand
667
- | RunReloadCommand
668
- | RunInputCommand;
669
-
670
- export type Command = RunCommand | UserCommands;
671
-
672
- /** A queued message projected out of the host state, wire shape. */
673
- export type RunQueueItem = {
674
- readonly id: string;
675
- readonly parts: readonly (TextPart | FilePart)[];
676
- };
677
-
678
- export type State = {
679
- readonly messages: readonly ThreadMessage[];
680
- readonly state?: ReadonlyJSONValue;
681
- readonly isRunning: boolean;
682
- /**
683
- * The host's regular queue lane projected out of the state. Returning it
684
- * (even empty) turns on the server-side queue: sends become `run/enqueue`
685
- * / `run/steer` commands and item controls send the `run/*` queue
686
- * commands. Presence must be stable across conversions and excludes the
687
- * client-local `capabilities.queue` buffer.
688
- */
689
- readonly queue?: readonly RunQueueItem[];
690
- /** The host's steer lane; requires `queue`. Absent means empty. */
691
- readonly steerQueue?: readonly RunQueueItem[];
692
- /**
693
- * The host's parked input requests projected out of the state. Returning it
694
- * (even empty) routes tool results and approvals with a matching pending
695
- * request through `run/input`. Presence must be stable across conversions.
696
- */
697
- readonly inputRequests?: readonly AssistantTransportThread.InputRequestState[];
698
- };
699
-
700
- export type StateConverter<T> = (state: T) => State;
701
-
702
- /** Folds an unsettled command into a draft of the client state; called once per pending command, in send order, re-run on every state change. A throwing fold logs and drops that command's update. */
703
- export type Optimistic<T> = (
704
- draft: T,
705
- command: Command,
706
- ctx: StatewireClient.OptimisticContext,
707
- ) => void;
708
-
709
- export type HeadersValue = Record<string, string> | Headers;
710
-
711
- export type Protocol = "data-stream" | "assistant-transport";
712
-
713
- export type SendCommandsRequestBody = {
714
- commands: Command[];
715
- state: unknown;
716
- system: string | undefined;
717
- tools: Record<string, unknown> | undefined;
718
- callSettings: LanguageModelV1CallSettings | undefined;
719
- config: LanguageModelConfig | undefined;
720
- threadId: string | null;
721
- parentId?: string | null;
722
- [key: string]: unknown;
723
- };
724
-
725
- export type Options<T> = {
726
- initialState: T;
727
- converter: StateConverter<T>;
728
- optimistic?: Optimistic<T> | undefined;
729
- /** Folds the lib's run-dialect optimistic reducer before `optimistic`: `true` reads the run mounts off the state root; a selector picks a nested mount. */
730
- runs?: true | ((state: T) => unknown) | undefined;
731
- /** Makes dispatch records concrete in the draft (runs after the optimistic folds); without it, dispatch limbo stays out of `messages`. */
732
- materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;
733
- api: string;
734
- resumeApi?: string | undefined;
735
- protocol?: Protocol | undefined;
736
- headers: HeadersValue | (() => Promise<HeadersValue>);
737
- body?: object | (() => Promise<object | undefined>) | undefined;
738
- /** Transform the fully assembled request body before it is sent. */
739
- prepareSendCommandsRequest?:
740
- | ((
741
- body: SendCommandsRequestBody,
742
- ) => Record<string, unknown> | Promise<Record<string, unknown>>)
743
- | undefined;
744
- onResponse?: ((response: Response) => void) | undefined;
745
- onFinish?: (() => void) | undefined;
746
- onError?:
747
- | ((
748
- error: Error,
749
- params: {
750
- commands: Command[];
751
- updateState: (updater: (state: T) => T) => void;
752
- },
753
- ) => void | Promise<void>)
754
- | undefined;
755
- /**
756
- * Called when commands are cancelled. After an error, queued commands are
757
- * cancelled once `onError` settles; `error` then carries the cause.
758
- */
759
- onCancel?:
760
- | ((params: {
761
- commands: Command[];
762
- updateState: (updater: (state: T) => T) => void;
763
- error?: Error;
764
- }) => void)
765
- | undefined;
766
- capabilities?:
767
- | {
768
- edit?: boolean | undefined;
769
- /**
770
- * Buffer messages sent during a run in an in-memory queue and dispatch
771
- * them once the run settles. Steering interrupts the active run.
772
- * Mutually exclusive with the converter's `queue` projection.
773
- */
774
- queue?: boolean | undefined;
775
- /** The host supports `run/continue` (a continue affordance on aborted runs). */
776
- continue?: boolean | undefined;
777
- }
778
- | undefined;
779
- adapters?:
780
- | {
781
- attachments?: AttachmentAdapter | undefined;
782
- }
783
- | undefined;
784
- };
785
- }
786
-
787
- // Scope transforms are keyed by the underlying hook, not the resource wrapper.
788
- forwardTransformScopes(
789
- useAssistantTransportThread,
790
- ExternalThread(undefined as never).hook,
791
- );