@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,160 +1,145 @@
1
- import { AssistantTransportThread } from "./AssistantTransportThread.js";
2
1
  import { ResourceElement } from "@assistant-ui/tap";
3
2
  import { ClientOutput } from "@assistant-ui/store";
4
- import { AttachmentAdapter, FeedbackAdapter, SpeechSynthesisAdapter, ThreadMessage } from "@assistant-ui/core";
5
3
  import { Statewire, StatewireClient } from "statewire";
4
+ import { Assistant, AttachmentAdapter, FeedbackAdapter, SpeechSynthesisAdapter, ThreadMessage } from "@assistant-ui/core";
6
5
  import { ReadonlyJSONValue } from "assistant-stream/utils";
7
6
  //#region src/StatewireThread.d.ts
8
- declare const StatewireThread: {
9
- <T>(options: StatewireThread.RunsOptions<T>): ResourceElement<ClientOutput<"thread">>;
10
- <T>(options: StatewireThread.Options<T>): ResourceElement<ClientOutput<"thread">>;
11
- };
7
+ declare const symbolStatewireExtras: unique symbol;
8
+ declare const asStatewireExtras: (extras: unknown) => StatewireThread.Extras;
9
+ declare const StatewireThread: <T>(options: StatewireThread.Options<T>) => ResourceElement<ClientOutput<"thread">>;
12
10
  declare namespace StatewireThread {
13
- type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;
14
- type TextPart = {
11
+ type UserCommands = Assistant.Commands[keyof Assistant.Commands];
12
+ export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;
13
+ export type Extras = {
14
+ [symbolStatewireExtras]: true;
15
+ sendCommand: (command: Command) => void;
16
+ reconnect: () => void;
17
+ state: unknown;
18
+ status: ThreadStatus;
19
+ inputRequests: readonly InputRequestState[];
20
+ runs: Runs;
21
+ };
22
+ export type TextPart = {
15
23
  readonly type: "text";
16
24
  readonly text: string;
17
25
  };
18
- type FilePart = {
26
+ export type FilePart = {
19
27
  readonly type: "file";
20
28
  readonly mediaType: string;
21
29
  readonly url: string;
22
30
  readonly filename?: string;
23
31
  };
24
- type UserMessage = {
32
+ export type UserMessage = {
25
33
  readonly id: string;
26
34
  readonly role: "user";
27
35
  readonly parts: readonly (TextPart | FilePart)[];
28
36
  readonly metadata?: Record<string, unknown>;
29
37
  };
30
38
  /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */
31
- type Placement = {
39
+ export type Placement = {
32
40
  readonly insertAfter?: string | null;
33
41
  readonly insertBefore?: string | null;
34
42
  };
35
- type RunEnqueueCommand = {
43
+ export type RunEnqueueCommand = {
36
44
  readonly type: "run/enqueue";
45
+ /** The run this command targets — the live run's id, or a fresh client-minted uuid on run-creating sends. */
46
+ readonly runId: string;
37
47
  } & ({
38
48
  readonly message: UserMessage;
39
- /** 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. */
40
- readonly anchorMessageId?: string | null;
49
+ /** 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. */
50
+ readonly runAnchorMessageId?: string | null;
41
51
  } | {
42
52
  readonly messageId: string;
43
53
  }) & Placement;
44
- type RunSteerCommand = {
54
+ export type RunSteerCommand = {
45
55
  readonly type: "run/steer";
56
+ /** The run this command targets — the live run's id, or a fresh client-minted uuid on run-creating sends. */
57
+ readonly runId: string;
46
58
  } & ({
47
59
  readonly message: UserMessage;
48
- /** 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. */
49
- readonly anchorMessageId?: string | null;
60
+ /** 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. */
61
+ readonly runAnchorMessageId?: string | null;
50
62
  } | {
51
63
  readonly messageId: string;
52
64
  }) & Placement;
53
- type RunDequeueCommand = {
65
+ export type RunDequeueCommand = {
54
66
  readonly type: "run/dequeue";
67
+ readonly runId: string;
55
68
  readonly messageId: string;
56
69
  };
57
- type RunEditCommand = {
70
+ export type RunEditCommand = {
58
71
  readonly type: "run/edit";
72
+ /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */
73
+ readonly runId: string;
59
74
  readonly message: UserMessage;
60
75
  readonly sourceId: string;
61
76
  /** Asserts `sourceId`'s parent — the rewind target; null names the root. */
62
- readonly rollbackTo: string | null;
77
+ readonly runAnchorMessageId: string | null;
63
78
  };
64
- type RunContinueCommand = {
79
+ export type RunContinueCommand = {
65
80
  readonly type: "run/continue";
81
+ readonly runId?: string;
66
82
  };
67
- type ToolCallInputRequest = {
83
+ export type ToolCallInputRequest = {
68
84
  readonly type: "tool-call";
69
85
  readonly id: string;
70
86
  readonly toolCallId: string;
71
87
  };
72
- type ToolApprovalInputRequest = {
88
+ export type ToolApprovalInputRequest = {
73
89
  readonly type: "tool-approval";
74
90
  readonly id: string;
75
91
  readonly toolCallId: string;
76
92
  };
77
- type CustomInputRequest = {
93
+ export type CustomInputRequest = {
78
94
  readonly type: string;
79
95
  readonly id: string;
80
96
  readonly [key: string]: ReadonlyJSONValue | undefined;
81
97
  };
82
98
  /** A host request parking the run until answered; open union for custom types. */
83
- type InputRequest = ToolCallInputRequest | ToolApprovalInputRequest | CustomInputRequest;
84
- type ToolCallInputResponse = {
85
- readonly output: ReadonlyJSONValue;
86
- /** Default false; when true, `output` carries the error payload. */
87
- readonly isError?: boolean;
88
- readonly artifact?: ReadonlyJSONValue;
89
- };
90
- type ToolApprovalInputResponse = {
91
- readonly decision: "approve" | "reject" | "edit" | "respond";
92
- readonly editedArgs?: ReadonlyJSONValue;
93
- readonly message?: string;
94
- };
95
- type InputResponse = ReadonlyJSONValue;
96
- type RunInputCommand = {
99
+ export type InputRequest = ToolCallInputRequest | ToolApprovalInputRequest | CustomInputRequest;
100
+ export type InputResponse = ReadonlyJSONValue;
101
+ export type RunInputCommand = {
97
102
  readonly type: "run/input";
103
+ readonly runId?: string;
98
104
  readonly requestId: string;
99
105
  readonly response: InputResponse;
100
106
  };
101
107
  /** An input request projected out of the host state with its response echo. */
102
- type InputRequestState = InputRequest & {
108
+ export type InputRequestState = InputRequest & {
103
109
  readonly response: InputResponse | null;
104
110
  };
105
- type RunReloadCommand = {
111
+ export type RunReloadCommand = {
106
112
  readonly type: "run/reload";
113
+ /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */
114
+ readonly runId: string;
107
115
  readonly sourceId: string;
108
116
  /** Asserts `sourceId`'s parent — the rewind target; null names the root. */
109
- readonly rollbackTo: string | null;
117
+ readonly runAnchorMessageId: string | null;
110
118
  };
111
- type RunCommand = RunEnqueueCommand | RunSteerCommand | RunDequeueCommand | RunEditCommand | RunContinueCommand | RunReloadCommand | RunInputCommand;
112
- type Command = AssistantTransportThread.Command | RunCommand;
119
+ export type RunCommand = RunEnqueueCommand | RunSteerCommand | RunDequeueCommand | RunEditCommand | RunContinueCommand | RunReloadCommand | RunInputCommand;
120
+ export type Command = RunCommand | UserCommands;
113
121
  /** A queued message projected out of the host state, wire shape. */
114
- type QueueItem = {
122
+ export type RunQueueItem = {
115
123
  readonly id: string;
116
124
  readonly parts: readonly (TextPart | FilePart)[];
117
125
  };
118
- type State = {
119
- readonly messages: readonly ThreadMessage[];
120
- readonly state?: ReadonlyJSONValue;
121
- readonly isRunning: boolean;
122
- /** The live run's id projected out of the host state; stamped onto `run/stop`. */
123
- readonly runId?: string | null;
124
- /**
125
- * The host's regular queue lane projected out of the state. Returning it
126
- * (even empty) turns on the queue capability: sends become `run/enqueue`
127
- * / `run/steer` commands and item controls send the `run/*` queue
128
- * commands. Presence must be stable across conversions.
129
- */
130
- readonly queue?: readonly QueueItem[];
131
- /** The host's steer lane; requires `queue`. Absent means empty. */
132
- readonly steerQueue?: readonly QueueItem[];
133
- /**
134
- * The host's parked input requests projected out of the state. Returning
135
- * it (even empty) routes tool results and approvals with a matching
136
- * pending request through `run/input`. Presence must be stable across
137
- * conversions.
138
- */
139
- readonly inputRequests?: readonly InputRequestState[];
140
- };
141
126
  /** Run subsystem status replicated by the host. */
142
- type RunStatus = "running" | "stopped" | "error" | "input-required";
143
- /** The thread's status: `"loading"` while awaiting the attach snapshot, `"ready"` while resting, otherwise the run's status. */
144
- type ThreadStatus = "loading" | "ready" | RunStatus;
127
+ export type RunStatus = "running" | "stopped" | "error" | "input-required";
128
+ /** The thread's status, derived from the state: `"loading"` while the runs mount is absent, `"ready"` while resting, otherwise the run's status. */
129
+ export type ThreadStatus = "loading" | "ready" | RunStatus;
145
130
  /** A queue-lane entry as replicated: the user message plus host-stamped `meta`. */
146
- type RunsQueueEntry = UserMessage & {
131
+ export type RunsQueueEntry = UserMessage & {
147
132
  /** Host-stamped opaque per-entry metadata. */
148
133
  readonly meta?: ReadonlyJSONValue;
149
134
  };
150
135
  /** An input outcome riding a dispatch record: the request with its response (null = abandoned) and `run/input` meta. */
151
- type RunsInputOutcome = {
136
+ export type RunsInputOutcome = {
152
137
  readonly request: InputRequest;
153
138
  readonly response: InputResponse | null;
154
139
  readonly meta: ReadonlyJSONValue | null;
155
140
  };
156
141
  /** The dispatch record — the unacked batch handed to the run; null between the ack and the next dispatch or take. */
157
- type RunsDispatch = {
142
+ export type RunsDispatch = {
158
143
  readonly trigger: "message-send" | "message-edit" | "message-reload" | "input-resume" | "error-continue" | "stop-continue" | "steer";
159
144
  readonly messages: readonly RunsQueueEntry[];
160
145
  /** Present on rewind dispatches: truncate the thread at this id first; null names the root. */
@@ -163,13 +148,13 @@ declare namespace StatewireThread {
163
148
  readonly inputOutcomes?: readonly RunsInputOutcome[];
164
149
  };
165
150
  /** The replicated run error — set on an unhandled failure, cleared by the next user-initiated run. */
166
- type RunsError = {
151
+ export type RunsError = {
167
152
  readonly message: string;
168
153
  readonly [key: string]: ReadonlyJSONValue | undefined;
169
154
  };
170
155
  /** A replicated run entry — one element of the mount's `runs` array. */
171
- type RunState = {
172
- /** The run's identity — minted at dispatch, persists through input-required, null in error/stop. */
156
+ export type RunState = {
157
+ /** 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. */
173
158
  readonly runId: string | null;
174
159
  readonly status: RunStatus;
175
160
  readonly queue: readonly RunsQueueEntry[];
@@ -181,23 +166,22 @@ declare namespace StatewireThread {
181
166
  readonly error: RunsError | null;
182
167
  };
183
168
  /** App-shaped effects `runsMaterialize` applies for the dispatch record. */
184
- type MaterializeEffects = {
169
+ export type MaterializeEffects = {
185
170
  /** Append one dispatched message to the app's committed message state. */
186
171
  append: (message: RunsQueueEntry) => void;
187
172
  /** Truncate to the rolled-back view first (null names the root); required for hosts that dispatch edits/reloads. */
188
173
  rollback?: (to: string | null) => void;
189
174
  };
190
175
  /** The runs mount as replicated: the run entries plus the top-level status projection. */
191
- type RunsState = {
176
+ export type RunsState = {
192
177
  /** Projection of `runs[0]?.status ?? "ready"`. */
193
178
  readonly status: Exclude<ThreadStatus, "loading">;
194
179
  /** At most one entry; empty while resting. */
195
180
  readonly runs: readonly RunState[];
196
181
  };
197
- /** 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. */
198
- type Runs = {
199
- readonly status: ThreadStatus;
200
- /** The live run's id — non-null in running and input-required; stamped onto `run/stop`. */
182
+ /** The run subsystem's typed read — `runs[0]` of the state with unsettled commands folded in, resting defaults while no entry is live. */
183
+ export type Runs = {
184
+ /** The live run's id — non-null whenever a run entry is live (running, input-required, error/stop); the target for `run/*` sends. */
201
185
  readonly runId: string | null;
202
186
  readonly queue: readonly RunsQueueEntry[];
203
187
  readonly steerQueue: readonly RunsQueueEntry[];
@@ -207,37 +191,37 @@ declare namespace StatewireThread {
207
191
  readonly inputRequests?: readonly InputRequestState[];
208
192
  readonly error: RunsError | null;
209
193
  };
210
- type ConnectionMetadata = {
194
+ export type ConnectionMetadata = {
211
195
  pendingCommands: Command[];
212
196
  isSending: boolean;
213
197
  /** Statewire connection status; local transports are always `live`. */
214
198
  connection: StatewireClient.ConnectionState;
215
- /** The typed runs read; present iff the `runs` option is set. */
216
- runs?: Runs;
199
+ /** The typed runs read. */
200
+ runs: Runs;
217
201
  };
218
- type StateConverter<T> = (state: T, connectionMetadata: ConnectionMetadata) => State;
219
- /** Converter output in runs mode: app-owned keys only — the lib projects the run mounts itself. */
220
- type RunsConverterState = {
202
+ /** Converter output: app-owned keys only — the lib projects the run mounts itself. */
203
+ export type State = {
221
204
  readonly messages: readonly ThreadMessage[];
222
205
  readonly state?: ReadonlyJSONValue;
223
206
  };
224
- type RunsStateConverter<T> = (state: T, connectionMetadata: ConnectionMetadata & {
225
- runs: Runs;
226
- }) => RunsConverterState;
207
+ export type StateConverter<T> = (state: T, connectionMetadata: ConnectionMetadata) => State;
227
208
  /**
228
209
  * Payload of the built-in `run/stop` command. `reason` is the one well-known
229
210
  * field; apps extend it with their own JSON-serializable fields.
230
211
  */
231
- type StopPayload = {
212
+ export type StopPayload = {
232
213
  readonly reason?: string | undefined;
233
214
  readonly [key: string]: ReadonlyJSONValue | undefined;
234
215
  };
235
- type Options<T> = {
216
+ export type Options<T> = {
236
217
  transport: Transport<T>;
237
- /** Preloads the thread: published and interactive from the first render, replaced by the attach snapshot. Omitted, the thread stays loading until attach. */
238
- initialState?: T | undefined;
218
+ /** 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. */
219
+ initialState: T;
239
220
  converter: StateConverter<T>;
240
- runs?: undefined;
221
+ /** Folds app-owned keys for an unsettled command into the draft; runs after the lib's run-dialect reducer. */
222
+ optimistic?: StatewireClient.Optimistic<T, Record<string, (...args: any[]) => unknown>> | undefined;
223
+ /** Makes dispatch records concrete in the draft (runs after the optimistic folds); without it, dispatch limbo stays out of `messages`. */
224
+ materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;
241
225
  /**
242
226
  * "command-send" mirrors the client's ambient model context (system,
243
227
  * tools, callSettings, config) to the server over the command channel —
@@ -270,18 +254,9 @@ declare namespace StatewireThread {
270
254
  feedback?: FeedbackAdapter | undefined;
271
255
  } | undefined;
272
256
  };
273
- /** Options with the runs read enabled: the lib types the run mounts and the converter returns app-owned keys only. */
274
- type RunsOptions<T> = Omit<Options<T>, "converter" | "runs"> & {
275
- /** `true` reads the run mounts off the state root; a selector picks a nested mount. */
276
- runs: true | ((state: T) => unknown);
277
- converter: RunsStateConverter<T>;
278
- /** Folds app-owned keys for an unsettled command into the draft; runs after the lib's run-dialect reducer. */
279
- optimistic?: StatewireClient.Optimistic<T, Record<string, (...args: any[]) => unknown>> | undefined;
280
- /** Makes dispatch records concrete in the draft (runs after the optimistic folds); without it, dispatch limbo stays out of `messages`. */
281
- materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;
282
- };
257
+ export {};
283
258
  }
284
- declare module "@assistant-ui/react" {
259
+ declare module "@assistant-ui/core" {
285
260
  namespace Assistant {
286
261
  interface Commands {
287
262
  runEnqueue: StatewireThread.RunEnqueueCommand;
@@ -295,5 +270,5 @@ declare module "@assistant-ui/react" {
295
270
  }
296
271
  }
297
272
  //#endregion
298
- export { StatewireThread };
273
+ export { StatewireThread, asStatewireExtras, symbolStatewireExtras };
299
274
  //# sourceMappingURL=StatewireThread.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;;cA6Ya;GACV,GACC,SAAS,gBAAgB,YAAY,KACpC,gBAAgB;GAClB,GACC,SAAS,gBAAgB,QAAQ,KAChC,gBAAgB;;kBAIJ;OACH,UAAU,KAAK,gBAAgB,UAAU;OAEzC;aACD;a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;;;;IAMtD;;IAEA,qBAAqB;;IAErB,oBAEM,QAAQ,UAAU,cAChB,mBAAmB,2BAErB;MAAO,OAAO,YAAY;;;IAIhC,kBACM,OAAO,YAAY,IAAI;MAAO,SAAS,UAAU;;;IAGvD,uBACM,YAAY,gBAAgB;IAElC,YAAY,OAAO;IACnB;MAEM;;MAEA;;MAEA;;IAGN;MAEM,cAAc;MACd,SAAS;MACT,WAAW;;;;;;YAOT;cACE;MACR,YAAY,gBAAgB;MAC5B,UAAU,gBAAgB;MAC1B,YAAY,gBAAgB;MAC5B,SAAS,gBAAgB;MACzB,aAAa,gBAAgB;MAC7B,WAAW,gBAAgB;MAC3B,UAAU,gBAAgB"}
@@ -1,28 +1,20 @@
1
- import { createRunQueueAdapter, resolveEditCommand, resolveReloadCommand, toWireMessage, viewedLeafId } from "./runCommands.js";
2
- import { runsOptimistic } from "./runsOptimistic.js";
1
+ import { createRunQueueAdapter, resolveEditCommand, resolveReloadCommand, sendFields, toWireMessage } from "./runCommands.js";
3
2
  import { resolveToolApprovalInput, resolveToolResultInput } from "./inputRequests.js";
4
- import { symbolAssistantTransportExtras } from "./AssistantTransportThread.js";
3
+ import { runsOptimistic } from "./runsOptimistic.js";
5
4
  import { useCallback, useEffect, useMemo, useRef, useState } from "@assistant-ui/tap/react-shim";
6
5
  import { resource, useResource } from "@assistant-ui/tap";
7
- import { ExternalThread } from "@assistant-ui/react";
6
+ import { ExternalThread } from "@assistant-ui/core/store";
8
7
  import { forwardTransformScopes, useAssistantClientRef } from "@assistant-ui/store";
9
- import { useStatewire } from "statewire";
10
8
  import { toToolsJSONSchema } from "assistant-stream";
9
+ import { useStatewire } from "statewire";
11
10
  //#region src/StatewireThread.ts
12
- const LOADING_STATE = {
13
- messages: [],
14
- isRunning: false
11
+ const symbolStatewireExtras = Symbol("statewire-extras");
12
+ const asStatewireExtras = (extras) => {
13
+ if (typeof extras !== "object" || extras == null || !(symbolStatewireExtras in extras)) throw new Error("This method can only be called when you are using StatewireThread");
14
+ return extras;
15
15
  };
16
- const READY_RUNS = {
17
- status: "ready",
18
- runId: null,
19
- queue: [],
20
- steerQueue: [],
21
- dispatching: null,
22
- error: null
23
- };
24
- const LOADING_RUNS = {
25
- status: "loading",
16
+ const NO_INPUT_REQUESTS = [];
17
+ const RESTING_RUNS = {
26
18
  runId: null,
27
19
  queue: [],
28
20
  steerQueue: [],
@@ -40,21 +32,14 @@ const useStatewireThread = (options) => {
40
32
  latest.current = options;
41
33
  const [pending, setPending] = useState([]);
42
34
  const [retire] = useState(() => (command) => setPending((prev) => prev.includes(command) ? prev.filter((c) => c !== command) : prev));
43
- const runsOption = options.runs;
44
- const [runsSeam] = useState(() => runsOption !== void 0);
45
- if (runsSeam !== (runsOption !== void 0)) throw new Error("statewire: the runs option must be stable — it was " + (runsSeam ? "set" : "unset") + " on first render and changed since");
46
- const materializeOption = options.materialize;
47
- const [materializeSeam] = useState(() => materializeOption !== void 0);
48
- if (materializeSeam !== (materializeOption !== void 0)) throw new Error("statewire: the materialize option must be stable — it was " + (materializeSeam ? "set" : "unset") + " on first render and changed since");
49
35
  const { state: state_0, commands, connection: connection_0, setContext } = useStatewire({
50
36
  transport: options.transport,
51
37
  initialState: options.initialState,
52
- ...runsSeam && { optimistic: (draft, command_0, ctx) => {
53
- const runsOpt = latest.current.runs;
54
- runsOptimistic(runsOpt === true ? draft : runsOpt(draft), command_0, ctx);
38
+ optimistic: (draft, command_0, ctx) => {
39
+ runsOptimistic(draft, command_0, ctx);
55
40
  latest.current.optimistic?.(draft, command_0, ctx);
56
- } },
57
- ...materializeSeam && { materialize: (draft_0) => latest.current.materialize(draft_0) },
41
+ },
42
+ materialize: (draft_0) => latest.current.materialize?.(draft_0),
58
43
  onCommandChange: (update, ctx_0) => {
59
44
  if (update.status === "acked" || update.status === "settled") retire(update.params[0]);
60
45
  latest.current.onCommandChange?.(update, ctx_0);
@@ -105,63 +90,55 @@ const useStatewireThread = (options) => {
105
90
  setText((prev_1) => prev_1 === "" ? text : prev_1);
106
91
  });
107
92
  }, [dispatch]);
108
- const runs = useMemo(() => {
109
- if (runsOption === void 0) return void 0;
110
- if (state_0 === void 0) return LOADING_RUNS;
111
- const entry = (runsOption === true ? state_0 : runsOption(state_0))?.runs?.[0];
112
- return entry === void 0 ? READY_RUNS : {
113
- status: entry.status,
114
- runId: entry.runId,
115
- queue: entry.queue,
116
- steerQueue: entry.steerQueue,
117
- dispatching: entry.dispatching,
118
- ...entry.inputRequests !== void 0 && { inputRequests: entry.inputRequests },
119
- error: entry.error
93
+ const { status, runs } = useMemo(() => {
94
+ const entries = state_0?.runs;
95
+ const entry = entries?.[0];
96
+ return {
97
+ status: entries === void 0 ? "loading" : entry?.status ?? "ready",
98
+ runs: entry === void 0 ? RESTING_RUNS : {
99
+ runId: entry.runId,
100
+ queue: entry.queue,
101
+ steerQueue: entry.steerQueue,
102
+ dispatching: entry.dispatching,
103
+ ...entry.inputRequests !== void 0 && { inputRequests: entry.inputRequests },
104
+ error: entry.error
105
+ }
120
106
  };
121
- }, [runsOption, state_0]);
107
+ }, [state_0]);
122
108
  const { converter } = options;
123
109
  const metadata = useMemo(() => ({
124
110
  pendingCommands: [...pending],
125
111
  isSending: pending.length > 0,
126
112
  connection: connection_0,
127
- ...runs !== void 0 && { runs }
113
+ runs
128
114
  }), [
129
115
  pending,
130
116
  connection_0,
131
117
  runs
132
118
  ]);
133
- const converted = useMemo(() => state_0 === void 0 ? LOADING_STATE : converter(state_0, metadata), [
119
+ const converted = useMemo(() => converter(state_0, metadata), [
134
120
  converter,
135
121
  state_0,
136
122
  metadata
137
123
  ]);
138
124
  const messages = converted.messages;
139
- const queueItems = runs !== void 0 ? runs.queue : converted.queue;
140
- const steerQueueItems = runs !== void 0 ? runs.steerQueue : converted.steerQueue;
141
- if (steerQueueItems !== void 0 && queueItems === void 0) throw new Error("statewire: the converter's steerQueue projection requires the queue projection");
142
- const [queueSeam] = useState(() => ({ present: void 0 }));
143
- if (state_0 !== void 0 && queueSeam.present === void 0) queueSeam.present = queueItems !== void 0;
144
- if (queueSeam.present !== void 0 && queueSeam.present !== (queueItems !== void 0)) throw new Error("statewire: the converter's queue projection must be stable — it was " + (queueSeam.present ? "defined" : "undefined") + " on first convert and changed since");
145
- const queue = useMemo(() => queueItems ? createRunQueueAdapter(messages, queueItems, steerQueueItems, dispatch, dispatchSend) : void 0, [
125
+ const liveRunId = runs.runId;
126
+ const queue = useMemo(() => createRunQueueAdapter(messages, liveRunId, runs.queue, runs.steerQueue, dispatch, dispatchSend), [
146
127
  messages,
147
- queueItems,
148
- steerQueueItems,
128
+ liveRunId,
129
+ runs,
149
130
  dispatch,
150
131
  dispatchSend
151
132
  ]);
152
- const inputRequests = runs !== void 0 ? runs.inputRequests ?? [] : converted.inputRequests;
153
- const [inputSeam] = useState(() => ({ present: void 0 }));
154
- if (state_0 !== void 0 && inputSeam.present === void 0) inputSeam.present = inputRequests !== void 0;
155
- if (inputSeam.present !== void 0 && inputSeam.present !== (inputRequests !== void 0)) throw new Error("statewire: the converter's inputRequests projection must be stable — it was " + (inputSeam.present ? "defined" : "undefined") + " on first convert and changed since");
156
- const status = runs !== void 0 ? runs.status : state_0 === void 0 ? "loading" : "ready";
133
+ const inputRequests = runs.inputRequests ?? NO_INPUT_REQUESTS;
157
134
  const extras = useMemo(() => ({
158
- [symbolAssistantTransportExtras]: true,
135
+ [symbolStatewireExtras]: true,
159
136
  sendCommand: dispatch,
160
137
  reconnect: connection_0.reconnect,
161
138
  state: state_0,
162
139
  status,
163
- ...inputRequests !== void 0 && { inputRequests },
164
- ...runs !== void 0 && { runs }
140
+ inputRequests,
141
+ runs
165
142
  }), [
166
143
  dispatch,
167
144
  connection_0.reconnect,
@@ -171,44 +148,42 @@ const useStatewireThread = (options) => {
171
148
  runs
172
149
  ]);
173
150
  const handleAppend = (message_0) => {
174
- dispatchSend(message_0.sourceId != null ? resolveEditCommand(messages, message_0) : {
151
+ dispatchSend(message_0.sourceId != null ? resolveEditCommand(messages, message_0, liveRunId) : {
175
152
  type: "run/steer",
176
- message: toWireMessage(message_0, crypto.randomUUID()),
177
- anchorMessageId: viewedLeafId(messages)
153
+ ...sendFields(messages, liveRunId, toWireMessage(message_0, crypto.randomUUID()))
178
154
  }, message_0);
179
155
  };
180
156
  const handleReload = (parentId) => {
181
- dispatch(resolveReloadCommand(messages, parentId));
157
+ dispatch(resolveReloadCommand(messages, parentId, liveRunId));
182
158
  };
183
159
  const handleEdit = (message_1) => {
184
- dispatch(resolveEditCommand(messages, message_1));
160
+ dispatch(resolveEditCommand(messages, message_1, liveRunId));
185
161
  };
186
162
  const thread = useResource(ExternalThread({
187
163
  messages,
188
- isRunning: runs !== void 0 ? runs.status === "running" : converted.isRunning,
164
+ isRunning: status === "running",
189
165
  state: converted.state,
190
166
  extras,
191
167
  attachmentAdapter: options.adapters?.attachments,
192
168
  speechAdapter: options.adapters?.speech,
193
169
  feedbackAdapter: options.adapters?.feedback,
194
170
  onNew: handleAppend,
195
- ...queue && { queue },
171
+ queue,
196
172
  ...options.capabilities?.edit && { onEdit: handleEdit },
197
- ...options.capabilities?.continue && { onResume: () => dispatch({ type: "run/continue" }) },
173
+ ...options.capabilities?.continue && { onResume: () => dispatch({
174
+ type: "run/continue",
175
+ ...liveRunId !== null && { runId: liveRunId }
176
+ }) },
198
177
  ...options.capabilities?.reload && { onReload: handleReload },
199
- ...inputRequests !== void 0 && {
200
- onAddToolResult: (toolOptions) => dispatch(resolveToolResultInput(inputRequests, toolOptions)),
201
- onRespondToToolApproval: (approval) => dispatch(resolveToolApprovalInput(inputRequests, approval))
202
- },
178
+ onAddToolResult: (toolOptions) => dispatch(resolveToolResultInput(inputRequests, toolOptions, liveRunId)),
179
+ onRespondToToolApproval: (approval) => dispatch(resolveToolApprovalInput(inputRequests, approval, liveRunId)),
203
180
  onCancel: () => {
204
181
  const payload = latest.current.stopPayload?.();
205
182
  if (payload !== void 0 && (typeof payload !== "object" || payload === null || Array.isArray(payload))) throw new Error("statewire: stopPayload must return a plain object");
206
- const runId = runs !== void 0 ? runs.runId : converted.runId;
207
- const args = runId === void 0 ? payload === void 0 ? [] : [payload] : [{
183
+ commands["run/stop"]({
208
184
  ...payload,
209
- runId
210
- }];
211
- commands["run/stop"](...args).catch((error_1) => {
185
+ runId: runs.runId
186
+ }).catch((error_1) => {
212
187
  latest.current.onError?.(error_1);
213
188
  });
214
189
  }
@@ -219,6 +194,6 @@ const useStatewireThread = (options) => {
219
194
  const StatewireThread = (options) => resource(useStatewireThread)(options);
220
195
  forwardTransformScopes(useStatewireThread, ExternalThread(void 0).hook);
221
196
  //#endregion
222
- export { StatewireThread };
197
+ export { StatewireThread, asStatewireExtras, symbolStatewireExtras };
223
198
 
224
199
  //# sourceMappingURL=StatewireThread.js.map