@assistant-ui/react-statewire 0.13.0 → 0.15.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 (57) hide show
  1. package/dist/StatewireThread.d.ts +86 -105
  2. package/dist/StatewireThread.d.ts.map +1 -1
  3. package/dist/StatewireThread.js +36 -51
  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 +1 -1
  14. package/dist/inputRequests.js.map +1 -1
  15. package/dist/runCommands.d.ts +8 -24
  16. package/dist/runCommands.d.ts.map +1 -1
  17. package/dist/runCommands.js +3 -3
  18. package/dist/runCommands.js.map +1 -1
  19. package/dist/runsOptimistic.d.ts.map +1 -1
  20. package/dist/runsOptimistic.js +30 -13
  21. package/dist/runsOptimistic.js.map +1 -1
  22. package/package.json +4 -5
  23. package/src/StatewireThread.runs.test.tsx +65 -33
  24. package/src/StatewireThread.test.tsx +228 -426
  25. package/src/StatewireThread.ts +133 -224
  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 +7 -9
  30. package/src/runCommands.ts +17 -23
  31. package/src/runsMaterialize.test.ts +7 -8
  32. package/src/runsOptimistic.test.ts +86 -19
  33. package/src/runsOptimistic.ts +49 -19
  34. package/dist/AssistantTransportThread.d.ts +0 -227
  35. package/dist/AssistantTransportThread.d.ts.map +0 -1
  36. package/dist/AssistantTransportThread.js +0 -264
  37. package/dist/AssistantTransportThread.js.map +0 -1
  38. package/dist/host.d.ts +0 -38
  39. package/dist/host.d.ts.map +0 -1
  40. package/dist/host.js +0 -299
  41. package/dist/host.js.map +0 -1
  42. package/dist/replayBoundaryStream.d.ts +0 -6
  43. package/dist/replayBoundaryStream.d.ts.map +0 -1
  44. package/dist/replayBoundaryStream.js +0 -49
  45. package/dist/replayBoundaryStream.js.map +0 -1
  46. package/dist/stateOps.d.ts +0 -10
  47. package/dist/stateOps.d.ts.map +0 -1
  48. package/dist/stateOps.js +0 -114
  49. package/dist/stateOps.js.map +0 -1
  50. package/src/AssistantTransportThread.ts +0 -791
  51. package/src/athena.e2e.test.tsx +0 -654
  52. package/src/host.ts +0 -437
  53. package/src/legacy-diff.test.tsx +0 -628
  54. package/src/replayBoundaryStream.ts +0 -71
  55. package/src/stateOps.test.ts +0 -165
  56. package/src/stateOps.ts +0 -126
  57. package/src/transport.test.tsx +0 -3001
@@ -1,38 +1,46 @@
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";
37
45
  /** The run this command targets — the live run's id, or a fresh client-minted uuid on run-creating sends. */
38
46
  readonly runId: string;
@@ -43,7 +51,7 @@ declare namespace StatewireThread {
43
51
  } | {
44
52
  readonly messageId: string;
45
53
  }) & Placement;
46
- type RunSteerCommand = {
54
+ export type RunSteerCommand = {
47
55
  readonly type: "run/steer";
48
56
  /** The run this command targets — the live run's id, or a fresh client-minted uuid on run-creating sends. */
49
57
  readonly runId: string;
@@ -54,12 +62,12 @@ declare namespace StatewireThread {
54
62
  } | {
55
63
  readonly messageId: string;
56
64
  }) & Placement;
57
- type RunDequeueCommand = {
65
+ export type RunDequeueCommand = {
58
66
  readonly type: "run/dequeue";
59
67
  readonly runId: string;
60
68
  readonly messageId: string;
61
69
  };
62
- type RunEditCommand = {
70
+ export type RunEditCommand = {
63
71
  readonly type: "run/edit";
64
72
  /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */
65
73
  readonly runId: string;
@@ -68,50 +76,41 @@ declare namespace StatewireThread {
68
76
  /** Asserts `sourceId`'s parent — the rewind target; null names the root. */
69
77
  readonly runAnchorMessageId: string | null;
70
78
  };
71
- type RunContinueCommand = {
79
+ export type RunContinueCommand = {
72
80
  readonly type: "run/continue";
73
81
  readonly runId?: string;
74
82
  };
75
- type ToolCallInputRequest = {
83
+ export type ToolCallInputRequest = {
76
84
  readonly type: "tool-call";
77
85
  readonly id: string;
78
86
  readonly toolCallId: string;
79
87
  };
80
- type ToolApprovalInputRequest = {
88
+ export type ToolApprovalInputRequest = {
81
89
  readonly type: "tool-approval";
82
90
  readonly id: string;
83
91
  readonly toolCallId: string;
84
92
  };
85
- type CustomInputRequest = {
93
+ export type CustomInputRequest = {
86
94
  readonly type: string;
87
95
  readonly id: string;
88
96
  readonly [key: string]: ReadonlyJSONValue | undefined;
89
97
  };
90
98
  /** A host request parking the run until answered; open union for custom types. */
91
- type InputRequest = ToolCallInputRequest | ToolApprovalInputRequest | CustomInputRequest;
92
- type ToolCallInputResponse = {
93
- readonly output: ReadonlyJSONValue;
94
- /** Default false; when true, `output` carries the error payload. */
95
- readonly isError?: boolean;
96
- readonly artifact?: ReadonlyJSONValue;
97
- };
98
- type ToolApprovalInputResponse = {
99
- readonly decision: "approve" | "reject" | "edit" | "respond";
100
- readonly editedArgs?: ReadonlyJSONValue;
101
- readonly message?: string;
102
- };
103
- type InputResponse = ReadonlyJSONValue;
104
- type RunInputCommand = {
99
+ export type InputRequest = ToolCallInputRequest | ToolApprovalInputRequest | CustomInputRequest;
100
+ export type InputResponse = ReadonlyJSONValue;
101
+ export type RunInputCommand = {
105
102
  readonly type: "run/input";
106
103
  readonly runId?: string;
107
104
  readonly requestId: string;
108
105
  readonly response: InputResponse;
109
106
  };
110
- /** An input request projected out of the host state with its response echo. */
111
- type InputRequestState = InputRequest & {
112
- readonly response: InputResponse | null;
107
+ /** An input request projected out of the host state; a present `response` key marks the entry answered. */
108
+ export type InputRequestState = InputRequest & {
109
+ readonly response?: InputResponse;
110
+ /** The answer's `run/input` meta; absent when the answer carried none. */
111
+ readonly meta?: ReadonlyJSONValue;
113
112
  };
114
- type RunReloadCommand = {
113
+ export type RunReloadCommand = {
115
114
  readonly type: "run/reload";
116
115
  /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */
117
116
  readonly runId: string;
@@ -119,135 +118,126 @@ declare namespace StatewireThread {
119
118
  /** Asserts `sourceId`'s parent — the rewind target; null names the root. */
120
119
  readonly runAnchorMessageId: string | null;
121
120
  };
122
- type RunCommand = RunEnqueueCommand | RunSteerCommand | RunDequeueCommand | RunEditCommand | RunContinueCommand | RunReloadCommand | RunInputCommand;
123
- type Command = AssistantTransportThread.Command | RunCommand;
121
+ export type RunCommand = RunEnqueueCommand | RunSteerCommand | RunDequeueCommand | RunEditCommand | RunContinueCommand | RunReloadCommand | RunInputCommand;
122
+ export type Command = RunCommand | UserCommands;
124
123
  /** A queued message projected out of the host state, wire shape. */
125
- type QueueItem = {
124
+ export type RunQueueItem = {
126
125
  readonly id: string;
127
126
  readonly parts: readonly (TextPart | FilePart)[];
128
127
  };
129
- type State = {
130
- readonly messages: readonly ThreadMessage[];
131
- readonly state?: ReadonlyJSONValue;
132
- readonly isRunning: boolean;
133
- /** The live run's id projected out of the host state; stamped onto `run/stop`. */
134
- readonly runId?: string | null;
135
- /**
136
- * The host's regular queue lane projected out of the state. Returning it
137
- * (even empty) turns on the queue capability: sends become `run/enqueue`
138
- * / `run/steer` commands and item controls send the `run/*` queue
139
- * commands. Presence must be stable across conversions.
140
- */
141
- readonly queue?: readonly QueueItem[];
142
- /** The host's steer lane; requires `queue`. Absent means empty. */
143
- readonly steerQueue?: readonly QueueItem[];
144
- /**
145
- * The host's parked input requests projected out of the state. Returning
146
- * it (even empty) routes tool results and approvals with a matching
147
- * pending request through `run/input`. Presence must be stable across
148
- * conversions.
149
- */
150
- readonly inputRequests?: readonly InputRequestState[];
151
- };
152
128
  /** Run subsystem status replicated by the host. */
153
- type RunStatus = "running" | "stopped" | "error" | "input-required";
129
+ export type RunStatus = "running" | "stopped" | "error" | "input-required";
154
130
  /** The thread's status, derived from the state: `"loading"` while the runs mount is absent, `"ready"` while resting, otherwise the run's status. */
155
- type ThreadStatus = "loading" | "ready" | RunStatus;
131
+ export type ThreadStatus = "loading" | "ready" | RunStatus;
156
132
  /** A queue-lane entry as replicated: the user message plus host-stamped `meta`. */
157
- type RunsQueueEntry = UserMessage & {
133
+ export type RunsQueueEntry = UserMessage & {
158
134
  /** Host-stamped opaque per-entry metadata. */
159
135
  readonly meta?: ReadonlyJSONValue;
160
136
  };
161
137
  /** An input outcome riding a dispatch record: the request with its response (null = abandoned) and `run/input` meta. */
162
- type RunsInputOutcome = {
138
+ export type RunsInputOutcome = {
163
139
  readonly request: InputRequest;
164
140
  readonly response: InputResponse | null;
165
141
  readonly meta: ReadonlyJSONValue | null;
166
142
  };
167
- /** The dispatch record — the unacked batch handed to the run; null between the ack and the next dispatch or take. */
168
- type RunsDispatch = {
169
- readonly trigger: "message-send" | "message-edit" | "message-reload" | "input-resume" | "error-continue" | "stop-continue" | "steer";
143
+ /** The dispatch record — the unacked batch handed to the run; absent between the ack and the next dispatch or take. */
144
+ export type RunsDispatch = {
145
+ readonly trigger: "send-message" | "edit-message" | "reload-message" | "input-resume" | "error-continue" | "stop-continue" | "steer";
170
146
  readonly messages: readonly RunsQueueEntry[];
171
147
  /** Present on rewind dispatches: truncate the thread at this id first; null names the root. */
172
148
  readonly rollbackTo?: string | null;
149
+ /** The run-starting op's meta; present only when carried. */
150
+ readonly rootMeta?: ReadonlyJSONValue;
173
151
  /** Present when input outcomes ride the dispatch; visible until the ack. */
174
152
  readonly inputOutcomes?: readonly RunsInputOutcome[];
175
153
  };
154
+ /** The stopping window: present while a stop of the live run is underway; `"edit-message"` / `"reload-message"` pair with `nextDispatch`. */
155
+ export type RunsStopping = {
156
+ readonly reason: "stop" | "edit-message" | "reload-message";
157
+ };
176
158
  /** The replicated run error — set on an unhandled failure, cleared by the next user-initiated run. */
177
- type RunsError = {
159
+ export type RunsError = {
178
160
  readonly message: string;
179
161
  readonly [key: string]: ReadonlyJSONValue | undefined;
180
162
  };
181
163
  /** A replicated run entry — one element of the mount's `runs` array. */
182
- type RunState = {
164
+ export type RunState = {
183
165
  /** 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. */
184
166
  readonly runId: string | null;
185
167
  readonly status: RunStatus;
186
168
  readonly queue: readonly RunsQueueEntry[];
187
169
  readonly steerQueue: readonly RunsQueueEntry[];
188
170
  /** The dispatch record — the unacked batch handed to the run, cleared at the ack. */
189
- readonly dispatching: RunsDispatch | null;
171
+ readonly dispatching?: RunsDispatch;
172
+ readonly stopping?: RunsStopping;
173
+ /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */
174
+ readonly nextDispatch?: RunsDispatch;
190
175
  /** The parked pending set; present only in input-required. */
191
176
  readonly inputRequests?: readonly InputRequestState[];
192
- readonly error: RunsError | null;
177
+ /** Set only by an unhandled throw; cleared by the next user-initiated run. */
178
+ readonly error?: RunsError;
193
179
  };
194
180
  /** App-shaped effects `runsMaterialize` applies for the dispatch record. */
195
- type MaterializeEffects = {
181
+ export type MaterializeEffects = {
196
182
  /** Append one dispatched message to the app's committed message state. */
197
183
  append: (message: RunsQueueEntry) => void;
198
184
  /** Truncate to the rolled-back view first (null names the root); required for hosts that dispatch edits/reloads. */
199
185
  rollback?: (to: string | null) => void;
200
186
  };
201
187
  /** The runs mount as replicated: the run entries plus the top-level status projection. */
202
- type RunsState = {
188
+ export type RunsState = {
203
189
  /** Projection of `runs[0]?.status ?? "ready"`. */
204
190
  readonly status: Exclude<ThreadStatus, "loading">;
205
191
  /** At most one entry; empty while resting. */
206
192
  readonly runs: readonly RunState[];
207
193
  };
208
- /** The run subsystem's typed read — `runs[0]` of the selected mount with unsettled commands folded in, resting defaults while no entry is live. */
209
- type Runs = {
194
+ /** The run subsystem's typed read — `runs[0]` of the state with unsettled commands folded in, resting defaults while no entry is live. */
195
+ export type Runs = {
210
196
  /** The live run's id — non-null whenever a run entry is live (running, input-required, error/stop); the target for `run/*` sends. */
211
197
  readonly runId: string | null;
212
198
  readonly queue: readonly RunsQueueEntry[];
213
199
  readonly steerQueue: readonly RunsQueueEntry[];
214
200
  /** The dispatch record — the unacked batch handed to the run, cleared at the ack. */
215
- readonly dispatching: RunsDispatch | null;
201
+ readonly dispatching?: RunsDispatch;
202
+ readonly stopping?: RunsStopping;
203
+ /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */
204
+ readonly nextDispatch?: RunsDispatch;
216
205
  /** The parked pending set; present only in input-required. */
217
206
  readonly inputRequests?: readonly InputRequestState[];
218
- readonly error: RunsError | null;
207
+ /** Set only by an unhandled throw; cleared by the next user-initiated run. */
208
+ readonly error?: RunsError;
219
209
  };
220
- type ConnectionMetadata = {
210
+ export type ConnectionMetadata = {
221
211
  pendingCommands: Command[];
222
212
  isSending: boolean;
223
213
  /** Statewire connection status; local transports are always `live`. */
224
214
  connection: StatewireClient.ConnectionState;
225
- /** The typed runs read; present iff the `runs` option is set. */
226
- runs?: Runs;
215
+ /** The typed runs read. */
216
+ runs: Runs;
227
217
  };
228
- type StateConverter<T> = (state: T, connectionMetadata: ConnectionMetadata) => State;
229
- /** Converter output in runs mode: app-owned keys only — the lib projects the run mounts itself. */
230
- type RunsConverterState = {
218
+ /** Converter output: app-owned keys only — the lib projects the run mounts itself. */
219
+ export type State = {
231
220
  readonly messages: readonly ThreadMessage[];
232
221
  readonly state?: ReadonlyJSONValue;
233
222
  };
234
- type RunsStateConverter<T> = (state: T, connectionMetadata: ConnectionMetadata & {
235
- runs: Runs;
236
- }) => RunsConverterState;
223
+ export type StateConverter<T> = (state: T, connectionMetadata: ConnectionMetadata) => State;
237
224
  /**
238
225
  * Payload of the built-in `run/stop` command. `reason` is the one well-known
239
226
  * field; apps extend it with their own JSON-serializable fields.
240
227
  */
241
- type StopPayload = {
228
+ export type StopPayload = {
242
229
  readonly reason?: string | undefined;
243
230
  readonly [key: string]: ReadonlyJSONValue | undefined;
244
231
  };
245
- type Options<T> = {
232
+ export type Options<T> = {
246
233
  transport: Transport<T>;
247
- /** The pre-attach state, replaced by the attach snapshot. With runs, `runs: []` projects ready (interactive from the first render); an absent runs mount projects loading until attach. */
234
+ /** 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. */
248
235
  initialState: T;
249
236
  converter: StateConverter<T>;
250
- runs?: undefined;
237
+ /** Folds app-owned keys for an unsettled command into the draft; runs after the lib's run-dialect reducer. */
238
+ optimistic?: StatewireClient.Optimistic<T, Record<string, (...args: any[]) => unknown>> | undefined;
239
+ /** Makes dispatch records concrete in the draft (runs after the optimistic folds); without it, dispatch limbo stays out of `messages`. */
240
+ materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;
251
241
  /**
252
242
  * "command-send" mirrors the client's ambient model context (system,
253
243
  * tools, callSettings, config) to the server over the command channel —
@@ -280,18 +270,9 @@ declare namespace StatewireThread {
280
270
  feedback?: FeedbackAdapter | undefined;
281
271
  } | undefined;
282
272
  };
283
- /** Options with the runs read enabled: the lib types the run mounts and the converter returns app-owned keys only. */
284
- type RunsOptions<T> = Omit<Options<T>, "converter" | "runs"> & {
285
- /** `true` reads the run mounts off the state root; a selector picks a nested mount. */
286
- runs: true | ((state: T) => unknown);
287
- converter: RunsStateConverter<T>;
288
- /** Folds app-owned keys for an unsettled command into the draft; runs after the lib's run-dialect reducer. */
289
- optimistic?: StatewireClient.Optimistic<T, Record<string, (...args: any[]) => unknown>> | undefined;
290
- /** Makes dispatch records concrete in the draft (runs after the optimistic folds); without it, dispatch limbo stays out of `messages`. */
291
- materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;
292
- };
273
+ export {};
293
274
  }
294
- declare module "@assistant-ui/react" {
275
+ declare module "@assistant-ui/core" {
295
276
  namespace Assistant {
296
277
  interface Commands {
297
278
  runEnqueue: StatewireThread.RunEnqueueCommand;
@@ -305,5 +286,5 @@ declare module "@assistant-ui/react" {
305
286
  }
306
287
  }
307
288
  //#endregion
308
- export { StatewireThread };
289
+ export { StatewireThread, asStatewireExtras, symbolStatewireExtras };
309
290
  //# sourceMappingURL=StatewireThread.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;;cAgYa;GACV,GACC,SAAS,gBAAgB,YAAY,KACpC,gBAAgB;GAClB,GACC,SAAS,gBAAgB,QAAQ,KAChC,gBAAgB;;kBAIJ;OACH,UAAU,KAAK,gBAAgB,UAAU;OAEzC;aACD;aACA;;OAGC;aACD;aACA;aACA;aACA;;OAGC;aACD;aACA;aACA,iBAAiB,WAAW;aAC5B,WAAW;;;OAIV;aACD;aACA;;OAGC;aACD;;aAEA;;aAGI,SAAS;;aAET;;aAEA;OAEb;OAEU;aACD;;aAEA;;aAGI,SAAS;;aAET;;aAEA;OAEb;OAEU;aACD;aACA;aACA;;OAGC;aACD;;aAEA;aACA,SAAS;aACT;;aAEA;;OAGC;aACD;aACA;;OAGC;aACD;aACA;aACA;;OAGC;aACD;aACA;aACA;;OAGC;aACD;aACA;cACC,cAAc;;;OAId,eACR,uBACA,2BACA;OAEQ;aACD,QAAQ;;aAER;aACA,WAAW;;OAGV;aACD;aACA,aAAa;aACb;;OAGC,gBAAgB;OAEhB;aACD;aACA;aACA;aACA,UAAU;;;OAIT,oBAAoB;aACrB,UAAU;;OAGT;aACD;;aAEA;aACA;;aAEA;;OAGC,aACR,oBACA,kBACA,oBACA,iBACA,qBACA,mBACA;OAEQ,UAAU,yBAAyB,UAAU;;OAG7C;aACD;aACA,iBAAiB,WAAW;;OAG3B;aACD,mBAAmB;aACnB,QAAQ;aACR;;aAEA;;;;;;;aAOA,iBAAiB;;aAEjB,sBAAsB;;;;;;;aAOtB,yBAAyB;;;OAIxB;;OAGA,qCAAqC;;OAGrC,iBAAiB;;aAElB,OAAO;;;OAIN;aACD,SAAS;aACT,UAAU;aACV,MAAM;;;OAIL;aACD;aAQA,mBAAmB;;aAEnB;;aAEA,yBAAyB;;;OAIxB;aACD;cACC,cAAc;;;OAId;;aAED;aACA,QAAQ;aACR,gBAAgB;aAChB,qBAAqB;;aAErB,aAAa;;aAEb,yBAAyB;aACzB,OAAO;;;OAIN;;IAEV,SAAS,SAAS;;IAElB,YAAY;;;OAIF;;aAED,QAAQ,QAAQ;;aAEhB,eAAe;;;OAId;;aAED;aACA,gBAAgB;aAChB,qBAAqB;;aAErB,aAAa;;aAEb,yBAAyB;aACzB,OAAO;;OAGN;IACV,iBAAiB;IACjB;;IAEA,YAAY,gBAAgB;;IAE5B,OAAO;;OAGG,eAAe,MACzB,OAAO,GACP,oBAAoB,uBACjB;;OAGO;aACD,mBAAmB;aACnB,QAAQ;;OAGP,mBAAmB,MAC7B,OAAO,GACP,oBAAoB;IAAuB,MAAM;QAC9C;;;;;OAMO;aACD;cACC,cAAc;;OAGd,QAAQ;IAClB,WAAW,UAAU;;IAErB,cAAc;IACd,WAAW,eAAe;IAC1B;;;;;;IAMA;;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;;;;OAMP,YAAY,KAAK,KAAK,QAAQ;;IAExC,eAAe,OAAO;IACtB,WAAW,mBAAmB;;IAE9B,aACI,gBAAgB,WACd,GACA,mBAAmB;;IAIzB,cAAc,gBAAgB,YAAY,YAAY;;;;YAK9C;cACE;MACR,YAAY,gBAAgB;MAC5B,UAAU,gBAAgB;MAC1B,YAAY,gBAAgB;MAC5B,SAAS,gBAAgB;MACzB,aAAa,gBAAgB;MAC7B,WAAW,gBAAgB;MAC3B,UAAU,gBAAgB"}
1
+ {"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;cAwCa;cAEA,oBAAqB,oBAAkB,gBAAgB;cAqRvD,kBAAmB,GAC9B,SAAS,gBAAgB,QAAQ,OAChC,gBAAgB;kBAGF;OACV,eAAe,UAAU,eAAe,UAAU;cAE3C,UAAU,KAAK,gBAAgB,UAAU;cAEzC;KACT;IACD,cAAc,SAAS;IACvB;IACA;IACA,QAAQ;IACR,wBAAwB;IACxB,MAAM;;cAGI;aACD;aACA;;cAGC;aACD;aACA;aACA;aACA;;cAGC;aACD;aACA;aACA,iBAAiB,WAAW;aAC5B,WAAW;;;cAIV;aACD;aACA;;cAGC;aACD;;aAEA;;aAGI,SAAS;;aAET;;aAEA;OAEb;cAEU;aACD;;aAEA;;aAGI,SAAS;;aAET;;aAEA;OAEb;cAEU;aACD;aACA;aACA;;cAGC;aACD;;aAEA;aACA,SAAS;aACT;;aAEA;;cAGC;aACD;aACA;;cAGC;aACD;aACA;aACA;;cAGC;aACD;aACA;aACA;;cAGC;aACD;aACA;cACC,cAAc;;;cAId,eACR,uBACA,2BACA;cAEQ,gBAAgB;cAEhB;aACD;aACA;aACA;aACA,UAAU;;;cAIT,oBAAoB;aACrB,WAAW;;aAEX,OAAO;;cAGN;aACD;;aAEA;aACA;;aAEA;;cAGC,aACR,oBACA,kBACA,oBACA,iBACA,qBACA,mBACA;cAEQ,UAAU,aAAa;;cAGvB;aACD;aACA,iBAAiB,WAAW;;;cAI3B;;cAGA,qCAAqC;;cAGrC,iBAAiB;;aAElB,OAAO;;;cAIN;aACD,SAAS;aACT,UAAU;aACV,MAAM;;;cAIL;aACD;aAQA,mBAAmB;;aAEnB;;aAEA,WAAW;;aAEX,yBAAyB;;;cAIxB;aACD;;;cAIC;aACD;cACC,cAAc;;;cAId;;aAED;aACA,QAAQ;aACR,gBAAgB;aAChB,qBAAqB;;aAErB,cAAc;aACd,WAAW;;aAEX,eAAe;;aAEf,yBAAyB;;aAEzB,QAAQ;;;cAIP;;IAEV,SAAS,SAAS;;IAElB,YAAY;;;cAIF;;aAED,QAAQ,QAAQ;;aAEhB,eAAe;;;cAId;;aAED;aACA,gBAAgB;aAChB,qBAAqB;;aAErB,cAAc;aACd,WAAW;;aAEX,eAAe;;aAEf,yBAAyB;;aAEzB,QAAQ;;cAGP;IACV,iBAAiB;IACjB;;IAEA,YAAY,gBAAgB;;IAE5B,MAAM;;;cAII;aACD,mBAAmB;aACnB,QAAQ;;cAGP,eAAe,MACzB,OAAO,GACP,oBAAoB,uBACjB;;;;;cAMO;aACD;cACC,cAAc;;cAGd,QAAQ;IAClB,WAAW,UAAU;;IAErB,cAAc;IACd,WAAW,eAAe;;IAE1B,aACI,gBAAgB,WACd,GACA,mBAAmB;;IAIzB,cAAc,gBAAgB,YAAY,YAAY;;;;;;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,20 +1,23 @@
1
1
  import { createRunQueueAdapter, resolveEditCommand, resolveReloadCommand, sendFields, toWireMessage } from "./runCommands.js";
2
- import { runsOptimistic } from "./runsOptimistic.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
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
+ };
16
+ const NO_INPUT_REQUESTS = [];
12
17
  const RESTING_RUNS = {
13
18
  runId: null,
14
19
  queue: [],
15
- steerQueue: [],
16
- dispatching: null,
17
- error: null
20
+ steerQueue: []
18
21
  };
19
22
  const ambientContextOf = (context) => ({
20
23
  ...context.system !== void 0 && { system: context.system },
@@ -27,21 +30,14 @@ const useStatewireThread = (options) => {
27
30
  latest.current = options;
28
31
  const [pending, setPending] = useState([]);
29
32
  const [retire] = useState(() => (command) => setPending((prev) => prev.includes(command) ? prev.filter((c) => c !== command) : prev));
30
- const runsOption = options.runs;
31
- const [runsSeam] = useState(() => runsOption !== void 0);
32
- 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");
33
- const materializeOption = options.materialize;
34
- const [materializeSeam] = useState(() => materializeOption !== void 0);
35
- 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");
36
33
  const { state: state_0, commands, connection: connection_0, setContext } = useStatewire({
37
34
  transport: options.transport,
38
35
  initialState: options.initialState,
39
- ...runsSeam && { optimistic: (draft, command_0, ctx) => {
40
- const runsOpt = latest.current.runs;
41
- runsOptimistic(runsOpt === true ? draft : runsOpt(draft), command_0, ctx);
36
+ optimistic: (draft, command_0, ctx) => {
37
+ runsOptimistic(draft, command_0, ctx);
42
38
  latest.current.optimistic?.(draft, command_0, ctx);
43
- } },
44
- ...materializeSeam && { materialize: (draft_0) => latest.current.materialize(draft_0) },
39
+ },
40
+ materialize: (draft_0) => latest.current.materialize?.(draft_0),
45
41
  onCommandChange: (update, ctx_0) => {
46
42
  if (update.status === "acked" || update.status === "settled") retire(update.params[0]);
47
43
  latest.current.onCommandChange?.(update, ctx_0);
@@ -93,8 +89,7 @@ const useStatewireThread = (options) => {
93
89
  });
94
90
  }, [dispatch]);
95
91
  const { status, runs } = useMemo(() => {
96
- if (runsOption === void 0) return { status: "ready" };
97
- const entries = (runsOption === true ? state_0 : runsOption(state_0))?.runs;
92
+ const entries = state_0?.runs;
98
93
  const entry = entries?.[0];
99
94
  return {
100
95
  status: entries === void 0 ? "loading" : entry?.status ?? "ready",
@@ -102,18 +97,20 @@ const useStatewireThread = (options) => {
102
97
  runId: entry.runId,
103
98
  queue: entry.queue,
104
99
  steerQueue: entry.steerQueue,
105
- dispatching: entry.dispatching,
100
+ ...entry.dispatching !== void 0 && { dispatching: entry.dispatching },
101
+ ...entry.stopping !== void 0 && { stopping: entry.stopping },
102
+ ...entry.nextDispatch !== void 0 && { nextDispatch: entry.nextDispatch },
106
103
  ...entry.inputRequests !== void 0 && { inputRequests: entry.inputRequests },
107
- error: entry.error
104
+ ...entry.error !== void 0 && { error: entry.error }
108
105
  }
109
106
  };
110
- }, [runsOption, state_0]);
107
+ }, [state_0]);
111
108
  const { converter } = options;
112
109
  const metadata = useMemo(() => ({
113
110
  pendingCommands: [...pending],
114
111
  isSending: pending.length > 0,
115
112
  connection: connection_0,
116
- ...runs !== void 0 && { runs }
113
+ runs
117
114
  }), [
118
115
  pending,
119
116
  connection_0,
@@ -125,31 +122,23 @@ const useStatewireThread = (options) => {
125
122
  metadata
126
123
  ]);
127
124
  const messages = converted.messages;
128
- const liveRunId = runs !== void 0 ? runs.runId : converted.runId ?? null;
129
- const queueItems = runs !== void 0 ? runs.queue : converted.queue;
130
- const steerQueueItems = runs !== void 0 ? runs.steerQueue : converted.steerQueue;
131
- if (steerQueueItems !== void 0 && queueItems === void 0) throw new Error("statewire: the converter's steerQueue projection requires the queue projection");
132
- const [queueSeam] = useState(() => ({ present: queueItems !== void 0 }));
133
- if (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");
134
- const queue = useMemo(() => queueItems ? createRunQueueAdapter(messages, liveRunId, queueItems, steerQueueItems, dispatch, dispatchSend) : void 0, [
125
+ const liveRunId = runs.runId;
126
+ const queue = useMemo(() => createRunQueueAdapter(messages, liveRunId, runs.queue, runs.steerQueue, dispatch, dispatchSend), [
135
127
  messages,
136
128
  liveRunId,
137
- queueItems,
138
- steerQueueItems,
129
+ runs,
139
130
  dispatch,
140
131
  dispatchSend
141
132
  ]);
142
- const inputRequests = runs !== void 0 ? runs.inputRequests ?? [] : converted.inputRequests;
143
- const [inputSeam] = useState(() => ({ present: inputRequests !== void 0 }));
144
- if (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");
133
+ const inputRequests = runs.inputRequests ?? NO_INPUT_REQUESTS;
145
134
  const extras = useMemo(() => ({
146
- [symbolAssistantTransportExtras]: true,
135
+ [symbolStatewireExtras]: true,
147
136
  sendCommand: dispatch,
148
137
  reconnect: connection_0.reconnect,
149
138
  state: state_0,
150
139
  status,
151
- ...inputRequests !== void 0 && { inputRequests },
152
- ...runs !== void 0 && { runs }
140
+ inputRequests,
141
+ runs
153
142
  }), [
154
143
  dispatch,
155
144
  connection_0.reconnect,
@@ -172,33 +161,29 @@ const useStatewireThread = (options) => {
172
161
  };
173
162
  const thread = useResource(ExternalThread({
174
163
  messages,
175
- isRunning: runs !== void 0 ? status === "running" : converted.isRunning,
164
+ isRunning: status === "running",
176
165
  state: converted.state,
177
166
  extras,
178
167
  attachmentAdapter: options.adapters?.attachments,
179
168
  speechAdapter: options.adapters?.speech,
180
169
  feedbackAdapter: options.adapters?.feedback,
181
170
  onNew: handleAppend,
182
- ...queue && { queue },
171
+ queue,
183
172
  ...options.capabilities?.edit && { onEdit: handleEdit },
184
173
  ...options.capabilities?.continue && { onResume: () => dispatch({
185
174
  type: "run/continue",
186
175
  ...liveRunId !== null && { runId: liveRunId }
187
176
  }) },
188
177
  ...options.capabilities?.reload && { onReload: handleReload },
189
- ...inputRequests !== void 0 && {
190
- onAddToolResult: (toolOptions) => dispatch(resolveToolResultInput(inputRequests, toolOptions, liveRunId)),
191
- onRespondToToolApproval: (approval) => dispatch(resolveToolApprovalInput(inputRequests, approval, liveRunId))
192
- },
178
+ onAddToolResult: (toolOptions) => dispatch(resolveToolResultInput(inputRequests, toolOptions, liveRunId)),
179
+ onRespondToToolApproval: (approval) => dispatch(resolveToolApprovalInput(inputRequests, approval, liveRunId)),
193
180
  onCancel: () => {
194
181
  const payload = latest.current.stopPayload?.();
195
182
  if (payload !== void 0 && (typeof payload !== "object" || payload === null || Array.isArray(payload))) throw new Error("statewire: stopPayload must return a plain object");
196
- const runId = runs !== void 0 ? runs.runId : converted.runId;
197
- const args = runId === void 0 ? payload === void 0 ? [] : [payload] : [{
183
+ commands["run/stop"]({
198
184
  ...payload,
199
- runId
200
- }];
201
- commands["run/stop"](...args).catch((error_1) => {
185
+ runId: runs.runId
186
+ }).catch((error_1) => {
202
187
  latest.current.onError?.(error_1);
203
188
  });
204
189
  }
@@ -209,6 +194,6 @@ const useStatewireThread = (options) => {
209
194
  const StatewireThread = (options) => resource(useStatewireThread)(options);
210
195
  forwardTransformScopes(useStatewireThread, ExternalThread(void 0).hook);
211
196
  //#endregion
212
- export { StatewireThread };
197
+ export { StatewireThread, asStatewireExtras, symbolStatewireExtras };
213
198
 
214
199
  //# sourceMappingURL=StatewireThread.js.map