@assistant-ui/react-statewire 0.0.1

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.
package/src/host.ts ADDED
@@ -0,0 +1,413 @@
1
+ import { useEffect, useRef, useState } from "react";
2
+ import { resource } from "@assistant-ui/tap";
3
+ import type { ResourceElement } from "@assistant-ui/tap";
4
+ import { createRequestHeaders } from "@assistant-ui/core";
5
+ import type { ModelContext } from "@assistant-ui/core";
6
+ import {
7
+ AssistantTransportDecoder,
8
+ DataStreamDecoder,
9
+ toToolsJSONSchema,
10
+ } from "assistant-stream";
11
+ import type { AssistantTransportStateOperation } from "assistant-stream";
12
+ import { asAsyncIterableStream } from "assistant-stream/utils";
13
+ import { applyOps } from "statewire";
14
+ import type { Statewire } from "statewire";
15
+ import {
16
+ CommandExecution,
17
+ useStatewireCommands,
18
+ useStatewireEmit,
19
+ useStatewireState,
20
+ } from "statewire/server";
21
+ import type { StatewireServer } from "statewire/server";
22
+ import { createReplayBoundaryStream } from "./replayBoundaryStream";
23
+ import { translateStateOp } from "./stateOps";
24
+ import type {
25
+ AssistantTransportCommand,
26
+ AssistantTransportOptions,
27
+ SendCommandsRequestBody,
28
+ } from "./types";
29
+
30
+ export type SendOptions = {
31
+ schedule?: boolean;
32
+ };
33
+
34
+ export type HostRunContext = {
35
+ modelContext: ModelContext;
36
+ threadId: string | null;
37
+ };
38
+
39
+ export type HostQueue = {
40
+ queued: AssistantTransportCommand[];
41
+ inTransit: AssistantTransportCommand[];
42
+ };
43
+
44
+ // Statewire state sanitizes values on apply; command objects must keep their
45
+ // identity for converter-side caches, so the host publishes them through this
46
+ // cell and bumps queueVersion in state to signal the change.
47
+ export type HostQueueCell = { current: HostQueue };
48
+
49
+ export type HostOptions = AssistantTransportOptions<unknown> & {
50
+ getRunContext: () => HostRunContext;
51
+ queueCell: HostQueueCell;
52
+ };
53
+
54
+ export type AssistantTransportHostState = {
55
+ agent: unknown;
56
+ queueVersion: number;
57
+ isSending: boolean;
58
+ isReplaying: boolean;
59
+ };
60
+
61
+ export type AssistantTransportHostCommands = {
62
+ send(command: AssistantTransportCommand, opts?: SendOptions): void;
63
+ setParentId(parentId: string | null): void;
64
+ cancel(): void;
65
+ resume(): void;
66
+ reload(parentId: string | null): void;
67
+ importState(state: unknown): void;
68
+ };
69
+
70
+ type QueueEntry = {
71
+ command: AssistantTransportCommand;
72
+ execution: StatewireServer.ExecutionResolvers;
73
+ };
74
+
75
+ type EntryQueue = {
76
+ queued: QueueEntry[];
77
+ inTransit: QueueEntry[];
78
+ };
79
+
80
+ const commandsOf = (entries: QueueEntry[]) => entries.map((e) => e.command);
81
+
82
+ const createHostLoop = (
83
+ getOptions: () => HostOptions,
84
+ ctl: StatewireServer.StateCtl,
85
+ ) => {
86
+ let agent = getOptions().initialState as unknown;
87
+ let queue: EntryQueue = { queued: [], inTransit: [] };
88
+ let activeEntries: QueueEntry[] = [];
89
+ let parentId: string | null | undefined;
90
+ let resumeRequested = false;
91
+ let followUpRequested = false;
92
+ let isReplaying = false;
93
+ let disposed = false;
94
+ let abortController: AbortController | null = null;
95
+
96
+ const setReplaying = (value: boolean) => {
97
+ if (isReplaying === value) return;
98
+ isReplaying = value;
99
+ ctl.apply([{ op: "replace", path: ["isReplaying"], value }]);
100
+ };
101
+
102
+ const setSending = (value: boolean) => {
103
+ ctl.apply([{ op: "replace", path: ["isSending"], value }]);
104
+ };
105
+
106
+ const replaceAgent = (next: unknown) => {
107
+ agent = next;
108
+ ctl.apply([{ op: "replace", path: ["agent"], value: next }]);
109
+ };
110
+
111
+ const updateState = (updater: (state: unknown) => unknown) => {
112
+ replaceAgent(updater(agent));
113
+ };
114
+
115
+ // A chunk commits atomically — an op error must not leak a partial chunk.
116
+ // Ops mirror one-by-one under ["agent"] so untouched slices keep identity.
117
+ const applyChunkOps = (
118
+ operations: readonly AssistantTransportStateOperation[],
119
+ ) => {
120
+ let next = agent;
121
+ const translated: Statewire.Op[] = [];
122
+ for (const operation of operations) {
123
+ const op = translateStateOp(next, operation);
124
+ next = applyOps(next, [op]).state;
125
+ translated.push({ ...op, path: ["agent", ...op.path] });
126
+ }
127
+ agent = next;
128
+ ctl.apply(translated);
129
+ };
130
+
131
+ let queueVersion = 0;
132
+ const setQueue = (next: EntryQueue) => {
133
+ queue = next;
134
+ getOptions().queueCell.current = {
135
+ queued: commandsOf(next.queued),
136
+ inTransit: commandsOf(next.inTransit),
137
+ };
138
+ ctl.apply([
139
+ { op: "replace", path: ["queueVersion"], value: ++queueVersion },
140
+ ]);
141
+ };
142
+
143
+ const takeQueuedIntoTransit = (): QueueEntry[] => {
144
+ const { queued, inTransit } = queue;
145
+ if (queued.length === 0) return [];
146
+ setQueue({ queued: [], inTransit: [...inTransit, ...queued] });
147
+ return queued;
148
+ };
149
+
150
+ const drainQueue = (): EntryQueue => {
151
+ const drained = queue;
152
+ setQueue({ queued: [], inTransit: [] });
153
+ return drained;
154
+ };
155
+
156
+ const buildRequestBody = async (
157
+ o: HostOptions,
158
+ commands: AssistantTransportCommand[],
159
+ ) => {
160
+ const runParentId = parentId;
161
+ parentId = undefined;
162
+ const bodyValue = typeof o.body === "function" ? await o.body() : o.body;
163
+ const { modelContext, threadId } = o.getRunContext();
164
+
165
+ const requestBody: Record<string, unknown> = {
166
+ commands,
167
+ state: agent,
168
+ system: modelContext.system,
169
+ tools: modelContext.tools
170
+ ? toToolsJSONSchema(modelContext.tools)
171
+ : undefined,
172
+ threadId,
173
+ ...(runParentId !== undefined && { parentId: runParentId }),
174
+ callSettings: modelContext.callSettings,
175
+ config: modelContext.config,
176
+ // deprecated top-level spread, kept for legacy parity
177
+ ...modelContext.callSettings,
178
+ ...modelContext.config,
179
+ ...(bodyValue ?? {}),
180
+ };
181
+
182
+ if (!o.prepareSendCommandsRequest) return requestBody;
183
+ return o.prepareSendCommandsRequest(requestBody as SendCommandsRequestBody);
184
+ };
185
+
186
+ const run = async (signal: AbortSignal) => {
187
+ const o = getOptions();
188
+ const isResume = resumeRequested;
189
+ resumeRequested = false;
190
+ setReplaying(false);
191
+ activeEntries = isResume ? [] : takeQueuedIntoTransit();
192
+ if (activeEntries.length === 0 && !isResume) return;
193
+
194
+ const headers = await createRequestHeaders(o.headers);
195
+ const requestBody = await buildRequestBody(o, commandsOf(activeEntries));
196
+
197
+ const response = await fetch(isResume ? o.resumeApi! : o.api, {
198
+ method: "POST",
199
+ headers,
200
+ body: JSON.stringify(requestBody),
201
+ signal,
202
+ });
203
+
204
+ o.onResponse?.(response);
205
+
206
+ if (!response.ok) {
207
+ throw new Error(`Status ${response.status}: ${await response.text()}`);
208
+ }
209
+ if (!response.body) {
210
+ throw new Error("Response body is null");
211
+ }
212
+
213
+ const body = await createReplayBoundaryStream(response, setReplaying);
214
+ const decoder =
215
+ (o.protocol ?? "data-stream") === "assistant-transport"
216
+ ? new AssistantTransportDecoder()
217
+ : new DataStreamDecoder();
218
+
219
+ let streamError: string | undefined;
220
+ let delivered = false;
221
+
222
+ const markDelivered = () => {
223
+ for (const entry of activeEntries) entry.execution.ack();
224
+ setQueue({ ...queue, inTransit: [] });
225
+ delivered = true;
226
+ };
227
+
228
+ const chunks = body.pipeThrough(decoder);
229
+ for await (const chunk of asAsyncIterableStream(chunks)) {
230
+ if (chunk.type === "error") {
231
+ streamError = chunk.error;
232
+ continue;
233
+ }
234
+ if (chunk.type !== "update-state" || chunk.operations.length === 0)
235
+ continue;
236
+
237
+ applyChunkOps(chunk.operations);
238
+
239
+ // only after the chunk committed — a failing first chunk must leave
240
+ // the commands in transit for onError (legacy parity)
241
+ if (!delivered) markDelivered();
242
+ }
243
+
244
+ if (streamError) {
245
+ throw new Error(streamError);
246
+ }
247
+
248
+ if (!delivered) markDelivered();
249
+
250
+ // commands that coalesced into a resume run must not starve
251
+ if (isResume && queue.queued.length > 0) followUpRequested = true;
252
+ };
253
+
254
+ const resolveActive = () => {
255
+ for (const entry of activeEntries.splice(0)) entry.execution.resolve();
256
+ };
257
+
258
+ const settleCancelled = () => {
259
+ setReplaying(false);
260
+ const { queued, inTransit } = drainQueue();
261
+ resolveActive();
262
+ for (const entry of [...inTransit, ...queued]) entry.execution.resolve();
263
+ getOptions().onCancel?.({
264
+ commands: commandsOf([...inTransit, ...queued]),
265
+ updateState,
266
+ });
267
+ };
268
+
269
+ const settleFailed = async (error: Error) => {
270
+ setReplaying(false);
271
+ const { queued, inTransit } = drainQueue();
272
+ for (const entry of inTransit) entry.execution.reject(error);
273
+ resolveActive();
274
+ try {
275
+ await getOptions().onError?.(error, {
276
+ commands: commandsOf(inTransit),
277
+ updateState,
278
+ });
279
+ } finally {
280
+ getOptions().onCancel?.({
281
+ commands: commandsOf(queued),
282
+ updateState,
283
+ error,
284
+ });
285
+ for (const entry of queued) entry.execution.resolve();
286
+ }
287
+ };
288
+
289
+ const startRun = () => {
290
+ followUpRequested = false;
291
+ const ac = new AbortController();
292
+ abortController = ac;
293
+ setSending(true);
294
+
295
+ // macrotask: every command admitted this turn coalesces into the take
296
+ setTimeout(async () => {
297
+ try {
298
+ await run(ac.signal);
299
+ resolveActive();
300
+ } catch (error) {
301
+ followUpRequested = false;
302
+ // disposed means unmounted mid-run: the abort is ours, no callbacks
303
+ if (!disposed) {
304
+ if (ac.signal.aborted) settleCancelled();
305
+ else await settleFailed(error as Error);
306
+ }
307
+ } finally {
308
+ if (disposed) {
309
+ abortController = null;
310
+ } else {
311
+ getOptions().onFinish?.();
312
+ if (followUpRequested) {
313
+ startRun();
314
+ } else {
315
+ abortController = null;
316
+ setSending(false);
317
+ }
318
+ }
319
+ }
320
+ }, 0);
321
+ };
322
+
323
+ const schedule = () => {
324
+ if (abortController) {
325
+ followUpRequested = true;
326
+ return;
327
+ }
328
+ startRun();
329
+ };
330
+
331
+ const handlers = {
332
+ send: (command: AssistantTransportCommand, opts?: SendOptions) => {
333
+ const [execution, resolvers] = CommandExecution.withResolvers();
334
+ setQueue({
335
+ queued: [...queue.queued, { command, execution: resolvers }],
336
+ inTransit: queue.inTransit,
337
+ });
338
+ if (opts?.schedule !== false) schedule();
339
+ return execution;
340
+ },
341
+ setParentId: (id: string | null) => {
342
+ parentId = id;
343
+ },
344
+ cancel: () => {
345
+ resumeRequested = false;
346
+ followUpRequested = false;
347
+ abortController?.abort();
348
+ },
349
+ resume: () => {
350
+ if (!getOptions().resumeApi)
351
+ throw new Error("Must pass resumeApi to options to resume runs");
352
+
353
+ resumeRequested = true;
354
+ schedule();
355
+ },
356
+ reload: (id: string | null) => {
357
+ parentId = id;
358
+ schedule();
359
+ },
360
+ importState: replaceAgent,
361
+ };
362
+
363
+ return {
364
+ handlers,
365
+ // Strict-mode effects run setup → cleanup → setup on the same instance;
366
+ // arm undoes the cleanup's dispose.
367
+ arm: () => {
368
+ disposed = false;
369
+ },
370
+ dispose: () => {
371
+ disposed = true;
372
+ followUpRequested = false;
373
+ abortController?.abort();
374
+ },
375
+ };
376
+ };
377
+
378
+ const useAssistantTransportHost = (
379
+ options: HostOptions,
380
+ ): StatewireServer.Transport<AssistantTransportHostState> => {
381
+ const latestOptions = useRef(options);
382
+ latestOptions.current = options;
383
+
384
+ const [state, ctl] = useStatewireState<AssistantTransportHostState>(() => ({
385
+ agent: options.initialState,
386
+ queueVersion: 0,
387
+ isSending: false,
388
+ isReplaying: false,
389
+ }));
390
+ const emit = useStatewireEmit();
391
+
392
+ const [loop] = useState(() =>
393
+ createHostLoop(() => latestOptions.current, ctl),
394
+ );
395
+
396
+ useEffect(() => {
397
+ loop.arm();
398
+ return loop.dispose;
399
+ }, [loop]);
400
+
401
+ const commands = useStatewireCommands(loop.handlers);
402
+
403
+ return { state, commands, emit };
404
+ };
405
+
406
+ export const AssistantTransportHost = resource(useAssistantTransportHost) as (
407
+ options: HostOptions,
408
+ ) => ResourceElement<
409
+ StatewireServer.Transport<
410
+ AssistantTransportHostState,
411
+ AssistantTransportHostCommands
412
+ >
413
+ >;
package/src/index.ts ADDED
@@ -0,0 +1,23 @@
1
+ export { AssistantTransportThread } from "./AssistantTransportThread";
2
+ export {
3
+ useAssistantTransportSendCommand,
4
+ useAssistantTransportState,
5
+ } from "./hooks";
6
+ export { REPLAY_CONTENT_LENGTH_HEADER } from "./replayBoundaryStream";
7
+ export type {
8
+ AssistantTransportOptions,
9
+ AssistantTransportCommand,
10
+ AssistantTransportProtocol,
11
+ AssistantTransportState,
12
+ AssistantTransportConnectionMetadata,
13
+ AssistantTransportStateConverter,
14
+ AddMessageCommand,
15
+ AddToolResultCommand,
16
+ SendCommandsRequestBody,
17
+ UserMessage,
18
+ AssistantMessage,
19
+ UserMessagePart,
20
+ TextPart,
21
+ ImagePart,
22
+ HeadersValue,
23
+ } from "./types";