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