@assistant-ui/react-statewire 0.0.2 → 0.0.3
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/AssistantTransportThread.d.ts +4 -2
- package/dist/AssistantTransportThread.d.ts.map +1 -1
- package/dist/AssistantTransportThread.js +11 -10
- package/dist/AssistantTransportThread.js.map +1 -1
- package/dist/StatewireThread.d.ts +35 -0
- package/dist/StatewireThread.d.ts.map +1 -0
- package/dist/StatewireThread.js +71 -0
- package/dist/StatewireThread.js.map +1 -0
- package/dist/host.d.ts +2 -3
- package/dist/host.d.ts.map +1 -1
- package/dist/host.js +120 -123
- package/dist/host.js.map +1 -1
- package/dist/index.d.ts +22 -2
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2 -2
- package/dist/replayBoundaryStream.d.ts.map +1 -1
- package/dist/replayBoundaryStream.js +4 -2
- package/dist/replayBoundaryStream.js.map +1 -1
- package/dist/stateOps.d.ts +2 -2
- package/dist/stateOps.d.ts.map +1 -1
- package/dist/stateOps.js +24 -16
- package/dist/stateOps.js.map +1 -1
- package/package.json +11 -12
- package/src/AssistantTransportThread.ts +18 -17
- package/src/StatewireThread.test.tsx +262 -0
- package/src/StatewireThread.ts +159 -0
- package/src/host.ts +112 -98
- package/src/index.ts +23 -19
- package/src/replayBoundaryStream.ts +8 -2
- package/src/stateOps.test.ts +53 -13
- package/src/stateOps.ts +23 -19
- package/src/transport.test.tsx +146 -6
- package/LICENSE +0 -21
package/dist/host.js
CHANGED
|
@@ -2,44 +2,52 @@ import { createReplayBoundaryStream } from "./replayBoundaryStream.js";
|
|
|
2
2
|
import { translateStateOp } from "./stateOps.js";
|
|
3
3
|
import { useEffect, useRef, useState } from "@assistant-ui/tap/react-shim";
|
|
4
4
|
import { resource } from "@assistant-ui/tap";
|
|
5
|
-
import { applyOps } from "statewire";
|
|
6
5
|
import { createRequestHeaders } from "@assistant-ui/core";
|
|
7
6
|
import { AssistantTransportDecoder, DataStreamDecoder, toToolsJSONSchema } from "assistant-stream";
|
|
8
7
|
import { asAsyncIterableStream } from "assistant-stream/utils";
|
|
9
|
-
import { CommandExecution, useStatewireCommands, useStatewireEmit, useStatewireState } from "statewire/
|
|
8
|
+
import { CommandExecution, useStatewireCommands, useStatewireEmit, useStatewireState } from "statewire/host";
|
|
10
9
|
//#region src/host.ts
|
|
11
10
|
const commandsOf = (entries) => entries.map((e) => e.command);
|
|
12
|
-
const
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
11
|
+
const useHostLoop = (getOptions, ctl, getAgent) => {
|
|
12
|
+
const [s] = useState(() => ({
|
|
13
|
+
queue: {
|
|
14
|
+
queued: [],
|
|
15
|
+
inTransit: []
|
|
16
|
+
},
|
|
17
|
+
activeEntries: [],
|
|
18
|
+
parentId: void 0,
|
|
19
|
+
resumeRequested: false,
|
|
20
|
+
followUpRequested: false,
|
|
21
|
+
isReplaying: false,
|
|
22
|
+
disposed: false,
|
|
23
|
+
abortController: null,
|
|
24
|
+
queueVersion: 0
|
|
25
|
+
}));
|
|
26
|
+
useEffect(() => {
|
|
27
|
+
s.disposed = false;
|
|
28
|
+
return () => {
|
|
29
|
+
s.disposed = true;
|
|
30
|
+
s.followUpRequested = false;
|
|
31
|
+
s.abortController?.abort();
|
|
32
|
+
};
|
|
33
|
+
}, [s]);
|
|
25
34
|
const setReplaying = (value) => {
|
|
26
|
-
if (isReplaying === value) return;
|
|
27
|
-
isReplaying = value;
|
|
35
|
+
if (s.isReplaying === value) return;
|
|
36
|
+
s.isReplaying = value;
|
|
28
37
|
ctl.apply([{
|
|
29
38
|
op: "replace",
|
|
30
39
|
path: ["isReplaying"],
|
|
31
40
|
value
|
|
32
41
|
}]);
|
|
33
42
|
};
|
|
34
|
-
const setSending = (
|
|
43
|
+
const setSending = (value_0) => {
|
|
35
44
|
ctl.apply([{
|
|
36
45
|
op: "replace",
|
|
37
46
|
path: ["isSending"],
|
|
38
|
-
value
|
|
47
|
+
value: value_0
|
|
39
48
|
}]);
|
|
40
49
|
};
|
|
41
50
|
const replaceAgent = (next) => {
|
|
42
|
-
agent = next;
|
|
43
51
|
ctl.apply([{
|
|
44
52
|
op: "replace",
|
|
45
53
|
path: ["agent"],
|
|
@@ -47,37 +55,32 @@ const createHostLoop = (getOptions, ctl) => {
|
|
|
47
55
|
}]);
|
|
48
56
|
};
|
|
49
57
|
const updateState = (updater) => {
|
|
50
|
-
replaceAgent(updater(
|
|
58
|
+
replaceAgent(updater(getAgent()));
|
|
51
59
|
};
|
|
52
60
|
const applyChunkOps = (operations) => {
|
|
53
|
-
let next = agent;
|
|
54
|
-
const translated = [];
|
|
55
61
|
for (const operation of operations) {
|
|
56
|
-
const op = translateStateOp(
|
|
57
|
-
|
|
58
|
-
|
|
62
|
+
const op = translateStateOp(getAgent(), operation);
|
|
63
|
+
if (op === void 0) continue;
|
|
64
|
+
ctl.apply([{
|
|
59
65
|
...op,
|
|
60
66
|
path: ["agent", ...op.path]
|
|
61
|
-
});
|
|
67
|
+
}]);
|
|
62
68
|
}
|
|
63
|
-
agent = next;
|
|
64
|
-
ctl.apply(translated);
|
|
65
69
|
};
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
queue = next;
|
|
70
|
+
const setQueue = (next_0) => {
|
|
71
|
+
s.queue = next_0;
|
|
69
72
|
getOptions().queueCell.current = {
|
|
70
|
-
queued: commandsOf(
|
|
71
|
-
inTransit: commandsOf(
|
|
73
|
+
queued: commandsOf(next_0.queued),
|
|
74
|
+
inTransit: commandsOf(next_0.inTransit)
|
|
72
75
|
};
|
|
73
76
|
ctl.apply([{
|
|
74
77
|
op: "replace",
|
|
75
78
|
path: ["queueVersion"],
|
|
76
|
-
value: ++queueVersion
|
|
79
|
+
value: ++s.queueVersion
|
|
77
80
|
}]);
|
|
78
81
|
};
|
|
79
82
|
const takeQueuedIntoTransit = () => {
|
|
80
|
-
const { queued, inTransit } = queue;
|
|
83
|
+
const { queued, inTransit } = s.queue;
|
|
81
84
|
if (queued.length === 0) return [];
|
|
82
85
|
setQueue({
|
|
83
86
|
queued: [],
|
|
@@ -86,21 +89,19 @@ const createHostLoop = (getOptions, ctl) => {
|
|
|
86
89
|
return queued;
|
|
87
90
|
};
|
|
88
91
|
const drainQueue = () => {
|
|
89
|
-
const drained = queue;
|
|
92
|
+
const drained = s.queue;
|
|
90
93
|
setQueue({
|
|
91
94
|
queued: [],
|
|
92
95
|
inTransit: []
|
|
93
96
|
});
|
|
94
97
|
return drained;
|
|
95
98
|
};
|
|
96
|
-
const buildRequestBody = async (o, commands) => {
|
|
97
|
-
const runParentId = parentId;
|
|
98
|
-
parentId = void 0;
|
|
99
|
+
const buildRequestBody = async (o, commands, runParentId) => {
|
|
99
100
|
const bodyValue = typeof o.body === "function" ? await o.body() : o.body;
|
|
100
101
|
const { modelContext, threadId } = o.getRunContext();
|
|
101
102
|
const requestBody = {
|
|
102
103
|
commands,
|
|
103
|
-
state:
|
|
104
|
+
state: getAgent(),
|
|
104
105
|
system: modelContext.system,
|
|
105
106
|
tools: modelContext.tools ? toToolsJSONSchema(modelContext.tools) : void 0,
|
|
106
107
|
threadId,
|
|
@@ -115,31 +116,42 @@ const createHostLoop = (getOptions, ctl) => {
|
|
|
115
116
|
return o.prepareSendCommandsRequest(requestBody);
|
|
116
117
|
};
|
|
117
118
|
const run = async (signal) => {
|
|
118
|
-
const
|
|
119
|
-
const isResume = resumeRequested;
|
|
120
|
-
resumeRequested = false;
|
|
119
|
+
const o_0 = getOptions();
|
|
120
|
+
const isResume = s.resumeRequested;
|
|
121
|
+
s.resumeRequested = false;
|
|
121
122
|
setReplaying(false);
|
|
122
|
-
activeEntries = isResume ? [] : takeQueuedIntoTransit();
|
|
123
|
-
if (activeEntries.length === 0 && !isResume) return;
|
|
124
|
-
const
|
|
125
|
-
|
|
126
|
-
|
|
123
|
+
s.activeEntries = isResume ? [] : takeQueuedIntoTransit();
|
|
124
|
+
if (s.activeEntries.length === 0 && !isResume && s.parentId === void 0) return;
|
|
125
|
+
const runParentId_0 = s.parentId;
|
|
126
|
+
s.parentId = void 0;
|
|
127
|
+
try {
|
|
128
|
+
await runRequest(o_0, isResume, runParentId_0, signal);
|
|
129
|
+
} catch (error) {
|
|
130
|
+
if (!signal.aborted && s.parentId === void 0) s.parentId = runParentId_0;
|
|
131
|
+
throw error;
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
const runRequest = async (o_1, isResume_0, runParentId_1, signal_0) => {
|
|
135
|
+
const headers = await createRequestHeaders(o_1.headers);
|
|
136
|
+
const requestBody_0 = await buildRequestBody(o_1, commandsOf(s.activeEntries), runParentId_1);
|
|
137
|
+
const response = await fetch(isResume_0 ? o_1.resumeApi : o_1.api, {
|
|
127
138
|
method: "POST",
|
|
128
139
|
headers,
|
|
129
|
-
body: JSON.stringify(
|
|
130
|
-
signal
|
|
140
|
+
body: JSON.stringify(requestBody_0),
|
|
141
|
+
signal: signal_0
|
|
131
142
|
});
|
|
132
|
-
|
|
143
|
+
o_1.onResponse?.(response);
|
|
133
144
|
if (!response.ok) throw new Error(`Status ${response.status}: ${await response.text()}`);
|
|
134
145
|
if (!response.body) throw new Error("Response body is null");
|
|
135
146
|
const body = await createReplayBoundaryStream(response, setReplaying);
|
|
136
|
-
const
|
|
147
|
+
const strict = !isResume_0;
|
|
148
|
+
const decoder = (o_1.protocol ?? "data-stream") === "assistant-transport" ? new AssistantTransportDecoder({ strict }) : new DataStreamDecoder({ strict });
|
|
137
149
|
let streamError;
|
|
138
150
|
let delivered = false;
|
|
139
151
|
const markDelivered = () => {
|
|
140
|
-
for (const entry of activeEntries) entry.execution.ack();
|
|
152
|
+
for (const entry of s.activeEntries) entry.execution.ack();
|
|
141
153
|
setQueue({
|
|
142
|
-
...queue,
|
|
154
|
+
...s.queue,
|
|
143
155
|
inTransit: []
|
|
144
156
|
});
|
|
145
157
|
delivered = true;
|
|
@@ -156,60 +168,60 @@ const createHostLoop = (getOptions, ctl) => {
|
|
|
156
168
|
}
|
|
157
169
|
if (streamError) throw new Error(streamError);
|
|
158
170
|
if (!delivered) markDelivered();
|
|
159
|
-
if (
|
|
171
|
+
if (isResume_0 && s.queue.queued.length > 0) s.followUpRequested = true;
|
|
160
172
|
};
|
|
161
173
|
const resolveActive = () => {
|
|
162
|
-
for (const
|
|
174
|
+
for (const entry_0 of s.activeEntries.splice(0)) entry_0.execution.resolve();
|
|
163
175
|
};
|
|
164
176
|
const settleCancelled = () => {
|
|
165
177
|
setReplaying(false);
|
|
166
|
-
const { queued, inTransit } = drainQueue();
|
|
178
|
+
const { queued: queued_0, inTransit: inTransit_0 } = drainQueue();
|
|
167
179
|
resolveActive();
|
|
168
|
-
for (const
|
|
180
|
+
for (const entry_1 of [...inTransit_0, ...queued_0]) entry_1.execution.resolve();
|
|
169
181
|
getOptions().onCancel?.({
|
|
170
|
-
commands: commandsOf([...
|
|
182
|
+
commands: commandsOf([...inTransit_0, ...queued_0]),
|
|
171
183
|
updateState
|
|
172
184
|
});
|
|
173
185
|
};
|
|
174
|
-
const settleFailed = async (
|
|
186
|
+
const settleFailed = async (error_0) => {
|
|
175
187
|
setReplaying(false);
|
|
176
|
-
const { queued, inTransit } = drainQueue();
|
|
177
|
-
for (const
|
|
188
|
+
const { queued: queued_1, inTransit: inTransit_1 } = drainQueue();
|
|
189
|
+
for (const entry_2 of inTransit_1) entry_2.execution.reject(error_0);
|
|
178
190
|
resolveActive();
|
|
179
191
|
try {
|
|
180
|
-
await getOptions().onError?.(
|
|
181
|
-
commands: commandsOf(
|
|
192
|
+
await getOptions().onError?.(error_0, {
|
|
193
|
+
commands: commandsOf(inTransit_1),
|
|
182
194
|
updateState
|
|
183
195
|
});
|
|
184
196
|
} finally {
|
|
185
197
|
getOptions().onCancel?.({
|
|
186
|
-
commands: commandsOf(
|
|
198
|
+
commands: commandsOf(queued_1),
|
|
187
199
|
updateState,
|
|
188
|
-
error
|
|
200
|
+
error: error_0
|
|
189
201
|
});
|
|
190
|
-
for (const entry of
|
|
202
|
+
for (const entry of queued_1) entry.execution.resolve();
|
|
191
203
|
}
|
|
192
204
|
};
|
|
193
205
|
const startRun = () => {
|
|
194
|
-
followUpRequested = false;
|
|
206
|
+
s.followUpRequested = false;
|
|
195
207
|
const ac = new AbortController();
|
|
196
|
-
abortController = ac;
|
|
208
|
+
s.abortController = ac;
|
|
197
209
|
setSending(true);
|
|
198
210
|
setTimeout(async () => {
|
|
199
211
|
try {
|
|
200
212
|
await run(ac.signal);
|
|
201
213
|
resolveActive();
|
|
202
|
-
} catch (
|
|
203
|
-
followUpRequested = false;
|
|
204
|
-
if (!disposed) if (ac.signal.aborted) settleCancelled();
|
|
205
|
-
else await settleFailed(
|
|
214
|
+
} catch (error_1) {
|
|
215
|
+
s.followUpRequested = false;
|
|
216
|
+
if (!s.disposed) if (ac.signal.aborted) settleCancelled();
|
|
217
|
+
else await settleFailed(error_1);
|
|
206
218
|
} finally {
|
|
207
|
-
if (disposed) abortController = null;
|
|
219
|
+
if (s.disposed) s.abortController = null;
|
|
208
220
|
else {
|
|
209
221
|
getOptions().onFinish?.();
|
|
210
|
-
if (followUpRequested) startRun();
|
|
222
|
+
if (s.followUpRequested) startRun();
|
|
211
223
|
else {
|
|
212
|
-
abortController = null;
|
|
224
|
+
s.abortController = null;
|
|
213
225
|
setSending(false);
|
|
214
226
|
}
|
|
215
227
|
}
|
|
@@ -217,53 +229,43 @@ const createHostLoop = (getOptions, ctl) => {
|
|
|
217
229
|
}, 0);
|
|
218
230
|
};
|
|
219
231
|
const schedule = () => {
|
|
220
|
-
if (abortController) {
|
|
221
|
-
followUpRequested = true;
|
|
232
|
+
if (s.abortController) {
|
|
233
|
+
s.followUpRequested = true;
|
|
222
234
|
return;
|
|
223
235
|
}
|
|
224
236
|
startRun();
|
|
225
237
|
};
|
|
226
238
|
return {
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
return execution;
|
|
239
|
-
},
|
|
240
|
-
setParentId: (id) => {
|
|
241
|
-
parentId = id;
|
|
242
|
-
},
|
|
243
|
-
cancel: () => {
|
|
244
|
-
resumeRequested = false;
|
|
245
|
-
followUpRequested = false;
|
|
246
|
-
abortController?.abort();
|
|
247
|
-
},
|
|
248
|
-
resume: () => {
|
|
249
|
-
if (!getOptions().resumeApi) throw new Error("Must pass resumeApi to options to resume runs");
|
|
250
|
-
resumeRequested = true;
|
|
251
|
-
schedule();
|
|
252
|
-
},
|
|
253
|
-
reload: (id) => {
|
|
254
|
-
parentId = id;
|
|
255
|
-
schedule();
|
|
256
|
-
},
|
|
257
|
-
importState: replaceAgent
|
|
239
|
+
send: (command, opts) => {
|
|
240
|
+
const [execution, resolvers] = CommandExecution.withResolvers();
|
|
241
|
+
setQueue({
|
|
242
|
+
queued: [...s.queue.queued, {
|
|
243
|
+
command,
|
|
244
|
+
execution: resolvers
|
|
245
|
+
}],
|
|
246
|
+
inTransit: s.queue.inTransit
|
|
247
|
+
});
|
|
248
|
+
if (opts?.schedule !== false) schedule();
|
|
249
|
+
return execution;
|
|
258
250
|
},
|
|
259
|
-
|
|
260
|
-
|
|
251
|
+
setParentId: (id) => {
|
|
252
|
+
s.parentId = id;
|
|
261
253
|
},
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
followUpRequested = false;
|
|
265
|
-
abortController?.abort();
|
|
266
|
-
}
|
|
254
|
+
cancel: () => {
|
|
255
|
+
s.resumeRequested = false;
|
|
256
|
+
s.followUpRequested = false;
|
|
257
|
+
s.abortController?.abort();
|
|
258
|
+
},
|
|
259
|
+
resume: () => {
|
|
260
|
+
if (!getOptions().resumeApi) throw new Error("Must pass resumeApi to options to resume runs");
|
|
261
|
+
s.resumeRequested = true;
|
|
262
|
+
schedule();
|
|
263
|
+
},
|
|
264
|
+
reload: (id_0) => {
|
|
265
|
+
s.parentId = id_0;
|
|
266
|
+
schedule();
|
|
267
|
+
},
|
|
268
|
+
importState: replaceAgent
|
|
267
269
|
};
|
|
268
270
|
};
|
|
269
271
|
const useAssistantTransportHost = (options) => {
|
|
@@ -276,14 +278,9 @@ const useAssistantTransportHost = (options) => {
|
|
|
276
278
|
isReplaying: false
|
|
277
279
|
}));
|
|
278
280
|
const emit = useStatewireEmit();
|
|
279
|
-
const [loop] = useState(() => createHostLoop(() => latestOptions.current, ctl));
|
|
280
|
-
useEffect(() => {
|
|
281
|
-
loop.arm();
|
|
282
|
-
return loop.dispose;
|
|
283
|
-
}, [loop]);
|
|
284
281
|
return {
|
|
285
282
|
state,
|
|
286
|
-
commands: useStatewireCommands(
|
|
283
|
+
commands: useStatewireCommands(useHostLoop(() => latestOptions.current, ctl, () => ctl.snapshot().agent)),
|
|
287
284
|
emit
|
|
288
285
|
};
|
|
289
286
|
};
|
package/dist/host.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"host.js","names":["useEffect","useRef","useState","resource","ResourceElement","createRequestHeaders","ModelContext","AssistantTransportDecoder","DataStreamDecoder","toToolsJSONSchema","AssistantTransportStateOperation","asAsyncIterableStream","applyOps","Statewire","CommandExecution","useStatewireCommands","useStatewireEmit","useStatewireState","StatewireServer","createReplayBoundaryStream","translateStateOp","AssistantTransportCommand","AssistantTransportOptions","SendCommandsRequestBody","SendOptions","schedule","HostRunContext","modelContext","threadId","HostQueue","queued","inTransit","HostQueueCell","current","HostOptions","getRunContext","queueCell","AssistantTransportHostState","agent","queueVersion","isSending","isReplaying","AssistantTransportHostCommands","send","command","opts","setParentId","parentId","cancel","resume","reload","importState","state","QueueEntry","execution","ExecutionResolvers","EntryQueue","commandsOf","entries","map","e","createHostLoop","getOptions","ctl","StateCtl","initialState","queue","activeEntries","resumeRequested","followUpRequested","disposed","abortController","AbortController","setReplaying","value","apply","op","path","setSending","replaceAgent","next","updateState","updater","applyChunkOps","operations","translated","Op","operation","push","setQueue","takeQueuedIntoTransit","length","drainQueue","drained","buildRequestBody","o","commands","runParentId","undefined","bodyValue","body","requestBody","Record","system","tools","callSettings","config","prepareSendCommandsRequest","run","signal","AbortSignal","isResume","headers","response","fetch","resumeApi","api","method","JSON","stringify","onResponse","ok","Error","status","text","decoder","protocol","streamError","delivered","markDelivered","entry","ack","chunks","pipeThrough","chunk","type","error","resolveActive","splice","resolve","settleCancelled","onCancel","settleFailed","reject","onError","startRun","ac","setTimeout","aborted","onFinish","handlers","resolvers","withResolvers","id","abort","arm","dispose","useAssistantTransportHost","options","Transport","latestOptions","emit","loop","AssistantTransportHost"],"sources":["../src/host.ts"],"sourcesContent":["import { useEffect, useRef, useState } from \"react\";\nimport { resource } from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { createRequestHeaders } from \"@assistant-ui/core\";\nimport type { ModelContext } from \"@assistant-ui/core\";\nimport {\n AssistantTransportDecoder,\n DataStreamDecoder,\n toToolsJSONSchema,\n} from \"assistant-stream\";\nimport type { AssistantTransportStateOperation } from \"assistant-stream\";\nimport { asAsyncIterableStream } from \"assistant-stream/utils\";\nimport { applyOps } from \"statewire\";\nimport type { Statewire } from \"statewire\";\nimport {\n CommandExecution,\n useStatewireCommands,\n useStatewireEmit,\n useStatewireState,\n} from \"statewire/server\";\nimport type { StatewireServer } from \"statewire/server\";\nimport { createReplayBoundaryStream } from \"./replayBoundaryStream\";\nimport { translateStateOp } from \"./stateOps\";\nimport type {\n AssistantTransportCommand,\n AssistantTransportOptions,\n SendCommandsRequestBody,\n} from \"./types\";\n\nexport type SendOptions = {\n schedule?: boolean;\n};\n\nexport type HostRunContext = {\n modelContext: ModelContext;\n threadId: string | null;\n};\n\nexport type HostQueue = {\n queued: AssistantTransportCommand[];\n inTransit: AssistantTransportCommand[];\n};\n\n// Statewire state sanitizes values on apply; command objects must keep their\n// identity for converter-side caches, so the host publishes them through this\n// cell and bumps queueVersion in state to signal the change.\nexport type HostQueueCell = { current: HostQueue };\n\nexport type HostOptions = AssistantTransportOptions<unknown> & {\n getRunContext: () => HostRunContext;\n queueCell: HostQueueCell;\n};\n\nexport type AssistantTransportHostState = {\n agent: unknown;\n queueVersion: number;\n isSending: boolean;\n isReplaying: boolean;\n};\n\nexport type AssistantTransportHostCommands = {\n send(command: AssistantTransportCommand, opts?: SendOptions): void;\n setParentId(parentId: string | null): void;\n cancel(): void;\n resume(): void;\n reload(parentId: string | null): void;\n importState(state: unknown): void;\n};\n\ntype QueueEntry = {\n command: AssistantTransportCommand;\n execution: StatewireServer.ExecutionResolvers;\n};\n\ntype EntryQueue = {\n queued: QueueEntry[];\n inTransit: QueueEntry[];\n};\n\nconst commandsOf = (entries: QueueEntry[]) => entries.map((e) => e.command);\n\nconst createHostLoop = (\n getOptions: () => HostOptions,\n ctl: StatewireServer.StateCtl,\n) => {\n let agent = getOptions().initialState as unknown;\n let queue: EntryQueue = { queued: [], inTransit: [] };\n let activeEntries: QueueEntry[] = [];\n let parentId: string | null | undefined;\n let resumeRequested = false;\n let followUpRequested = false;\n let isReplaying = false;\n let disposed = false;\n let abortController: AbortController | null = null;\n\n const setReplaying = (value: boolean) => {\n if (isReplaying === value) return;\n isReplaying = value;\n ctl.apply([{ op: \"replace\", path: [\"isReplaying\"], value }]);\n };\n\n const setSending = (value: boolean) => {\n ctl.apply([{ op: \"replace\", path: [\"isSending\"], value }]);\n };\n\n const replaceAgent = (next: unknown) => {\n agent = next;\n ctl.apply([{ op: \"replace\", path: [\"agent\"], value: next }]);\n };\n\n const updateState = (updater: (state: unknown) => unknown) => {\n replaceAgent(updater(agent));\n };\n\n // A chunk commits atomically — an op error must not leak a partial chunk.\n // Ops mirror one-by-one under [\"agent\"] so untouched slices keep identity.\n const applyChunkOps = (\n operations: readonly AssistantTransportStateOperation[],\n ) => {\n let next = agent;\n const translated: Statewire.Op[] = [];\n for (const operation of operations) {\n const op = translateStateOp(next, operation);\n next = applyOps(next, [op]).state;\n translated.push({ ...op, path: [\"agent\", ...op.path] });\n }\n agent = next;\n ctl.apply(translated);\n };\n\n let queueVersion = 0;\n const setQueue = (next: EntryQueue) => {\n queue = next;\n getOptions().queueCell.current = {\n queued: commandsOf(next.queued),\n inTransit: commandsOf(next.inTransit),\n };\n ctl.apply([\n { op: \"replace\", path: [\"queueVersion\"], value: ++queueVersion },\n ]);\n };\n\n const takeQueuedIntoTransit = (): QueueEntry[] => {\n const { queued, inTransit } = queue;\n if (queued.length === 0) return [];\n setQueue({ queued: [], inTransit: [...inTransit, ...queued] });\n return queued;\n };\n\n const drainQueue = (): EntryQueue => {\n const drained = queue;\n setQueue({ queued: [], inTransit: [] });\n return drained;\n };\n\n const buildRequestBody = async (\n o: HostOptions,\n commands: AssistantTransportCommand[],\n ) => {\n const runParentId = parentId;\n parentId = undefined;\n const bodyValue = typeof o.body === \"function\" ? await o.body() : o.body;\n const { modelContext, threadId } = o.getRunContext();\n\n const requestBody: Record<string, unknown> = {\n commands,\n state: agent,\n system: modelContext.system,\n tools: modelContext.tools\n ? toToolsJSONSchema(modelContext.tools)\n : undefined,\n threadId,\n ...(runParentId !== undefined && { parentId: runParentId }),\n callSettings: modelContext.callSettings,\n config: modelContext.config,\n // deprecated top-level spread, kept for legacy parity\n ...modelContext.callSettings,\n ...modelContext.config,\n ...(bodyValue ?? {}),\n };\n\n if (!o.prepareSendCommandsRequest) return requestBody;\n return o.prepareSendCommandsRequest(requestBody as SendCommandsRequestBody);\n };\n\n const run = async (signal: AbortSignal) => {\n const o = getOptions();\n const isResume = resumeRequested;\n resumeRequested = false;\n setReplaying(false);\n activeEntries = isResume ? [] : takeQueuedIntoTransit();\n if (activeEntries.length === 0 && !isResume) return;\n\n const headers = await createRequestHeaders(o.headers);\n const requestBody = await buildRequestBody(o, commandsOf(activeEntries));\n\n const response = await fetch(isResume ? o.resumeApi! : o.api, {\n method: \"POST\",\n headers,\n body: JSON.stringify(requestBody),\n signal,\n });\n\n o.onResponse?.(response);\n\n if (!response.ok) {\n throw new Error(`Status ${response.status}: ${await response.text()}`);\n }\n if (!response.body) {\n throw new Error(\"Response body is null\");\n }\n\n const body = await createReplayBoundaryStream(response, setReplaying);\n const decoder =\n (o.protocol ?? \"data-stream\") === \"assistant-transport\"\n ? new AssistantTransportDecoder()\n : new DataStreamDecoder();\n\n let streamError: string | undefined;\n let delivered = false;\n\n const markDelivered = () => {\n for (const entry of activeEntries) entry.execution.ack();\n setQueue({ ...queue, inTransit: [] });\n delivered = true;\n };\n\n const chunks = body.pipeThrough(decoder);\n for await (const chunk of asAsyncIterableStream(chunks)) {\n if (chunk.type === \"error\") {\n streamError = chunk.error;\n continue;\n }\n if (chunk.type !== \"update-state\" || chunk.operations.length === 0)\n continue;\n\n applyChunkOps(chunk.operations);\n\n // only after the chunk committed — a failing first chunk must leave\n // the commands in transit for onError (legacy parity)\n if (!delivered) markDelivered();\n }\n\n if (streamError) {\n throw new Error(streamError);\n }\n\n if (!delivered) markDelivered();\n\n // commands that coalesced into a resume run must not starve\n if (isResume && queue.queued.length > 0) followUpRequested = true;\n };\n\n const resolveActive = () => {\n for (const entry of activeEntries.splice(0)) entry.execution.resolve();\n };\n\n const settleCancelled = () => {\n setReplaying(false);\n const { queued, inTransit } = drainQueue();\n resolveActive();\n for (const entry of [...inTransit, ...queued]) entry.execution.resolve();\n getOptions().onCancel?.({\n commands: commandsOf([...inTransit, ...queued]),\n updateState,\n });\n };\n\n const settleFailed = async (error: Error) => {\n setReplaying(false);\n const { queued, inTransit } = drainQueue();\n for (const entry of inTransit) entry.execution.reject(error);\n resolveActive();\n try {\n await getOptions().onError?.(error, {\n commands: commandsOf(inTransit),\n updateState,\n });\n } finally {\n getOptions().onCancel?.({\n commands: commandsOf(queued),\n updateState,\n error,\n });\n for (const entry of queued) entry.execution.resolve();\n }\n };\n\n const startRun = () => {\n followUpRequested = false;\n const ac = new AbortController();\n abortController = ac;\n setSending(true);\n\n // macrotask: every command admitted this turn coalesces into the take\n setTimeout(async () => {\n try {\n await run(ac.signal);\n resolveActive();\n } catch (error) {\n followUpRequested = false;\n // disposed means unmounted mid-run: the abort is ours, no callbacks\n if (!disposed) {\n if (ac.signal.aborted) settleCancelled();\n else await settleFailed(error as Error);\n }\n } finally {\n if (disposed) {\n abortController = null;\n } else {\n getOptions().onFinish?.();\n if (followUpRequested) {\n startRun();\n } else {\n abortController = null;\n setSending(false);\n }\n }\n }\n }, 0);\n };\n\n const schedule = () => {\n if (abortController) {\n followUpRequested = true;\n return;\n }\n startRun();\n };\n\n const handlers = {\n send: (command: AssistantTransportCommand, opts?: SendOptions) => {\n const [execution, resolvers] = CommandExecution.withResolvers();\n setQueue({\n queued: [...queue.queued, { command, execution: resolvers }],\n inTransit: queue.inTransit,\n });\n if (opts?.schedule !== false) schedule();\n return execution;\n },\n setParentId: (id: string | null) => {\n parentId = id;\n },\n cancel: () => {\n resumeRequested = false;\n followUpRequested = false;\n abortController?.abort();\n },\n resume: () => {\n if (!getOptions().resumeApi)\n throw new Error(\"Must pass resumeApi to options to resume runs\");\n\n resumeRequested = true;\n schedule();\n },\n reload: (id: string | null) => {\n parentId = id;\n schedule();\n },\n importState: replaceAgent,\n };\n\n return {\n handlers,\n // Strict-mode effects run setup → cleanup → setup on the same instance;\n // arm undoes the cleanup's dispose.\n arm: () => {\n disposed = false;\n },\n dispose: () => {\n disposed = true;\n followUpRequested = false;\n abortController?.abort();\n },\n };\n};\n\nconst useAssistantTransportHost = (\n options: HostOptions,\n): StatewireServer.Transport<AssistantTransportHostState> => {\n const latestOptions = useRef(options);\n latestOptions.current = options;\n\n const [state, ctl] = useStatewireState<AssistantTransportHostState>(() => ({\n agent: options.initialState,\n queueVersion: 0,\n isSending: false,\n isReplaying: false,\n }));\n const emit = useStatewireEmit();\n\n const [loop] = useState(() =>\n createHostLoop(() => latestOptions.current, ctl),\n );\n\n useEffect(() => {\n loop.arm();\n return loop.dispose;\n }, [loop]);\n\n const commands = useStatewireCommands(loop.handlers);\n\n return { state, commands, emit };\n};\n\nexport const AssistantTransportHost = resource(useAssistantTransportHost) as (\n options: HostOptions,\n) => ResourceElement<\n StatewireServer.Transport<\n AssistantTransportHostState,\n AssistantTransportHostCommands\n >\n>;\n"],"mappings":";;;;;;;;;;AA+EA,MAAMyD,cAAcC,YAA0BA,QAAQC,KAAKC,MAAMA,EAAEhB,OAAO;AAE1E,MAAMiB,kBACJC,YACAC,QACG;CACH,IAAIzB,QAAQwB,WAAW,CAAC,CAACG;CACzB,IAAIC,QAAoB;EAAEpC,QAAQ,CAAA;EAAIC,WAAW,CAAA;CAAG;CACpD,IAAIoC,gBAA8B,CAAA;CAClC,IAAIpB;CACJ,IAAIqB,kBAAkB;CACtB,IAAIC,oBAAoB;CACxB,IAAI5B,cAAc;CAClB,IAAI6B,WAAW;CACf,IAAIC,kBAA0C;CAE9C,MAAME,gBAAgBC,UAAmB;EACvC,IAAIjC,gBAAgBiC,OAAO;EAC3BjC,cAAciC;EACdX,IAAIY,MAAM,CAAC;GAAEC,IAAI;GAAWC,MAAM,CAAC,aAAa;GAAGH;EAAM,CAAC,CAAC;CAC7D;CAEA,MAAMI,cAAcJ,UAAmB;EACrCX,IAAIY,MAAM,CAAC;GAAEC,IAAI;GAAWC,MAAM,CAAC,WAAW;GAAGH;EAAM,CAAC,CAAC;CAC3D;CAEA,MAAMK,gBAAgBC,SAAkB;EACtC1C,QAAQ0C;EACRjB,IAAIY,MAAM,CAAC;GAAEC,IAAI;GAAWC,MAAM,CAAC,OAAO;GAAGH,OAAOM;EAAK,CAAC,CAAC;CAC7D;CAEA,MAAMC,eAAeC,YAAyC;EAC5DH,aAAaG,QAAQ5C,KAAK,CAAC;CAC7B;CAIA,MAAM6C,iBACJC,eACG;EACH,IAAIJ,OAAO1C;EACX,MAAM+C,aAA6B,CAAA;EACnC,KAAK,MAAME,aAAaH,YAAY;GAClC,MAAMR,KAAKxD,iBAAiB4D,MAAMO,SAAS;GAC3CP,OAAOpE,SAAS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,kBAAkB;IAClB3C,SAAS;GACX;GACAyB,SAASuG,OAAsB;IAC7B1G,WAAW0G;IACXhI,SAAS;GACX;GACA0B,aAAa4B;EAIbuE;EAGAK,WAAW;GACTrF,WAAW;EACb;EACAsF,eAAe;GACbtF,WAAW;GACXD,oBAAoB;GACpBE,iBAAiBmF,MAAM;EACzB;CACF;AACF;AAEA,MAAMG,6BACJC,YAC2D;CAC3D,MAAME,gBAAgB/J,OAAO6J,OAAO;CACpCE,cAAc/H,UAAU6H;CAExB,MAAM,CAAC1G,OAAOW,OAAO9C,yBAAsD;EACzEqB,OAAOwH,QAAQ7F;EACf1B,cAAc;EACdC,WAAW;EACXC,aAAa;CACf,EAAE;CACF,MAAMwH,OAAOjJ,iBAAiB;CAE9B,MAAM,CAACkJ,QAAQhK,eACb2D,qBAAqBmG,cAAc/H,SAAS8B,GAAG,CACjD;CAEA/D,gBAAgB;EACdkK,KAAKP,IAAI;EACT,OAAOO,KAAKN;CACd,GAAG,CAACM,IAAI,CAAC;CAIT,OAAO;EAAE9G;EAAO4C,UAFCjF,qBAAqBmJ,KAAKZ,QAE3BtD;EAAUiE;CAAK;AACjC;AAEA,MAAaE,yBAAyBhK,SAAS0J,yBAAyB"}
|
|
1
|
+
{"version":3,"file":"host.js","names":["useEffect","useRef","useState","resource","createRequestHeaders","ModelContext","AssistantTransportDecoder","DataStreamDecoder","toToolsJSONSchema","AssistantTransportStateOperation","asAsyncIterableStream","Statewire","CommandExecution","useStatewireCommands","useStatewireEmit","useStatewireState","StatewireHost","createReplayBoundaryStream","translateStateOp","AssistantTransportCommand","AssistantTransportOptions","SendCommandsRequestBody","SendOptions","schedule","HostRunContext","modelContext","threadId","HostQueue","queued","inTransit","HostQueueCell","current","HostOptions","getRunContext","queueCell","AssistantTransportHostState","agent","queueVersion","isSending","isReplaying","AssistantTransportHostCommands","send","command","opts","setParentId","parentId","cancel","resume","reload","importState","state","QueueEntry","execution","ExecutionResolvers","EntryQueue","commandsOf","entries","map","e","LoopState","queue","activeEntries","resumeRequested","followUpRequested","disposed","abortController","AbortController","useHostLoop","getOptions","ctl","StateCtl","getAgent","s","undefined","abort","setReplaying","value","apply","op","path","setSending","replaceAgent","next","updateState","updater","applyChunkOps","operations","operation","setQueue","takeQueuedIntoTransit","length","drainQueue","drained","buildRequestBody","o","commands","runParentId","bodyValue","body","requestBody","Record","system","tools","callSettings","config","prepareSendCommandsRequest","run","signal","AbortSignal","isResume","runRequest","error","aborted","headers","response","fetch","resumeApi","api","method","JSON","stringify","onResponse","ok","Error","status","text","strict","decoder","protocol","streamError","delivered","markDelivered","entry","ack","chunks","pipeThrough","chunk","type","resolveActive","splice","resolve","settleCancelled","onCancel","settleFailed","reject","onError","startRun","ac","setTimeout","onFinish","resolvers","withResolvers","id","useAssistantTransportHost","options","latestOptions","initialState","emit","handlers","snapshot","AssistantTransportHost"],"sources":["../src/host.ts"],"sourcesContent":["import { useEffect, useRef, useState } from \"react\";\nimport { resource } from \"@assistant-ui/tap\";\nimport { createRequestHeaders } from \"@assistant-ui/core\";\nimport type { ModelContext } from \"@assistant-ui/core\";\nimport {\n AssistantTransportDecoder,\n DataStreamDecoder,\n toToolsJSONSchema,\n} from \"assistant-stream\";\nimport type { AssistantTransportStateOperation } from \"assistant-stream\";\nimport { asAsyncIterableStream } from \"assistant-stream/utils\";\nimport type { Statewire } from \"statewire\";\nimport {\n CommandExecution,\n useStatewireCommands,\n useStatewireEmit,\n useStatewireState,\n} from \"statewire/host\";\nimport type { StatewireHost } from \"statewire/host\";\nimport { createReplayBoundaryStream } from \"./replayBoundaryStream\";\nimport { translateStateOp } from \"./stateOps\";\nimport type {\n AssistantTransportCommand,\n AssistantTransportOptions,\n SendCommandsRequestBody,\n} from \"./types\";\n\nexport type SendOptions = {\n schedule?: boolean;\n};\n\nexport type HostRunContext = {\n modelContext: ModelContext;\n threadId: string | null;\n};\n\nexport type HostQueue = {\n queued: AssistantTransportCommand[];\n inTransit: AssistantTransportCommand[];\n};\n\n// Statewire state sanitizes values on apply; command objects must keep their\n// identity for converter-side caches, so the host publishes them through this\n// cell and bumps queueVersion in state to signal the change.\nexport type HostQueueCell = { current: HostQueue };\n\nexport type HostOptions = AssistantTransportOptions<unknown> & {\n getRunContext: () => HostRunContext;\n queueCell: HostQueueCell;\n};\n\nexport type AssistantTransportHostState = {\n agent: unknown;\n queueVersion: number;\n isSending: boolean;\n isReplaying: boolean;\n};\n\nexport type AssistantTransportHostCommands = {\n send(command: AssistantTransportCommand, opts?: SendOptions): void;\n setParentId(parentId: string | null): void;\n cancel(): void;\n resume(): void;\n reload(parentId: string | null): void;\n importState(state: unknown): void;\n};\n\ntype QueueEntry = {\n command: AssistantTransportCommand;\n execution: StatewireHost.ExecutionResolvers;\n};\n\ntype EntryQueue = {\n queued: QueueEntry[];\n inTransit: QueueEntry[];\n};\n\nconst commandsOf = (entries: QueueEntry[]) => entries.map((e) => e.command);\n\ntype LoopState = {\n queue: EntryQueue;\n activeEntries: QueueEntry[];\n parentId: string | null | undefined;\n resumeRequested: boolean;\n followUpRequested: boolean;\n isReplaying: boolean;\n disposed: boolean;\n abortController: AbortController | null;\n queueVersion: number;\n};\n\nconst useHostLoop = (\n getOptions: () => HostOptions,\n ctl: StatewireHost.StateCtl,\n getAgent: () => unknown,\n) => {\n const [s] = useState(\n (): LoopState => ({\n queue: { queued: [], inTransit: [] },\n activeEntries: [],\n parentId: undefined,\n resumeRequested: false,\n followUpRequested: false,\n isReplaying: false,\n disposed: false,\n abortController: null,\n queueVersion: 0,\n }),\n );\n\n useEffect(() => {\n s.disposed = false;\n return () => {\n s.disposed = true;\n s.followUpRequested = false;\n s.abortController?.abort();\n };\n }, [s]);\n\n const setReplaying = (value: boolean) => {\n if (s.isReplaying === value) return;\n s.isReplaying = value;\n ctl.apply([{ op: \"replace\", path: [\"isReplaying\"], value }]);\n };\n\n const setSending = (value: boolean) => {\n ctl.apply([{ op: \"replace\", path: [\"isSending\"], value }]);\n };\n\n const replaceAgent = (next: unknown) => {\n ctl.apply([{ op: \"replace\", path: [\"agent\"], value: next }]);\n };\n\n const updateState = (updater: (state: unknown) => unknown) => {\n replaceAgent(updater(getAgent()));\n };\n\n // Ops commit one-by-one — an op error leaves the chunk's prefix applied.\n const applyChunkOps = (\n operations: readonly AssistantTransportStateOperation[],\n ) => {\n for (const operation of operations) {\n const op = translateStateOp(getAgent(), operation);\n if (op === undefined) continue;\n ctl.apply([{ ...op, path: [\"agent\", ...op.path] }]);\n }\n };\n\n const setQueue = (next: EntryQueue) => {\n s.queue = next;\n getOptions().queueCell.current = {\n queued: commandsOf(next.queued),\n inTransit: commandsOf(next.inTransit),\n };\n ctl.apply([\n { op: \"replace\", path: [\"queueVersion\"], value: ++s.queueVersion },\n ]);\n };\n\n const takeQueuedIntoTransit = (): QueueEntry[] => {\n const { queued, inTransit } = s.queue;\n if (queued.length === 0) return [];\n setQueue({ queued: [], inTransit: [...inTransit, ...queued] });\n return queued;\n };\n\n const drainQueue = (): EntryQueue => {\n const drained = s.queue;\n setQueue({ queued: [], inTransit: [] });\n return drained;\n };\n\n const buildRequestBody = async (\n o: HostOptions,\n commands: AssistantTransportCommand[],\n runParentId: string | null | undefined,\n ) => {\n const bodyValue = typeof o.body === \"function\" ? await o.body() : o.body;\n const { modelContext, threadId } = o.getRunContext();\n\n const requestBody: Record<string, unknown> = {\n commands,\n state: getAgent(),\n system: modelContext.system,\n tools: modelContext.tools\n ? toToolsJSONSchema(modelContext.tools)\n : undefined,\n threadId,\n ...(runParentId !== undefined && { parentId: runParentId }),\n callSettings: modelContext.callSettings,\n config: modelContext.config,\n // deprecated top-level spread, kept for legacy parity\n ...modelContext.callSettings,\n ...modelContext.config,\n ...(bodyValue ?? {}),\n };\n\n if (!o.prepareSendCommandsRequest) return requestBody;\n return o.prepareSendCommandsRequest(requestBody as SendCommandsRequestBody);\n };\n\n const run = async (signal: AbortSignal) => {\n const o = getOptions();\n const isResume = s.resumeRequested;\n s.resumeRequested = false;\n setReplaying(false);\n s.activeEntries = isResume ? [] : takeQueuedIntoTransit();\n if (s.activeEntries.length === 0 && !isResume && s.parentId === undefined)\n return;\n\n const runParentId = s.parentId;\n s.parentId = undefined;\n try {\n await runRequest(o, isResume, runParentId, signal);\n } catch (error) {\n if (!signal.aborted && s.parentId === undefined) s.parentId = runParentId;\n throw error;\n }\n };\n\n const runRequest = async (\n o: HostOptions,\n isResume: boolean,\n runParentId: string | null | undefined,\n signal: AbortSignal,\n ) => {\n const headers = await createRequestHeaders(o.headers);\n const requestBody = await buildRequestBody(\n o,\n commandsOf(s.activeEntries),\n runParentId,\n );\n\n const response = await fetch(isResume ? o.resumeApi! : o.api, {\n method: \"POST\",\n headers,\n body: JSON.stringify(requestBody),\n signal,\n });\n\n o.onResponse?.(response);\n\n if (!response.ok) {\n throw new Error(`Status ${response.status}: ${await response.text()}`);\n }\n if (!response.body) {\n throw new Error(\"Response body is null\");\n }\n\n const body = await createReplayBoundaryStream(response, setReplaying);\n const strict = !isResume;\n const decoder =\n (o.protocol ?? \"data-stream\") === \"assistant-transport\"\n ? new AssistantTransportDecoder({ strict })\n : new DataStreamDecoder({ strict });\n\n let streamError: string | undefined;\n let delivered = false;\n\n const markDelivered = () => {\n for (const entry of s.activeEntries) entry.execution.ack();\n setQueue({ ...s.queue, inTransit: [] });\n delivered = true;\n };\n\n const chunks = body.pipeThrough(decoder);\n for await (const chunk of asAsyncIterableStream(chunks)) {\n if (chunk.type === \"error\") {\n streamError = chunk.error;\n continue;\n }\n if (chunk.type !== \"update-state\" || chunk.operations.length === 0)\n continue;\n\n applyChunkOps(chunk.operations);\n\n // only after the chunk committed — a failing first chunk must leave\n // the commands in transit for onError (legacy parity)\n if (!delivered) markDelivered();\n }\n\n if (streamError) {\n throw new Error(streamError);\n }\n\n if (!delivered) markDelivered();\n\n // commands that coalesced into a resume run must not starve\n if (isResume && s.queue.queued.length > 0) s.followUpRequested = true;\n };\n\n const resolveActive = () => {\n for (const entry of s.activeEntries.splice(0)) entry.execution.resolve();\n };\n\n const settleCancelled = () => {\n setReplaying(false);\n const { queued, inTransit } = drainQueue();\n resolveActive();\n for (const entry of [...inTransit, ...queued]) entry.execution.resolve();\n getOptions().onCancel?.({\n commands: commandsOf([...inTransit, ...queued]),\n updateState,\n });\n };\n\n const settleFailed = async (error: Error) => {\n setReplaying(false);\n const { queued, inTransit } = drainQueue();\n for (const entry of inTransit) entry.execution.reject(error);\n resolveActive();\n try {\n await getOptions().onError?.(error, {\n commands: commandsOf(inTransit),\n updateState,\n });\n } finally {\n getOptions().onCancel?.({\n commands: commandsOf(queued),\n updateState,\n error,\n });\n for (const entry of queued) entry.execution.resolve();\n }\n };\n\n const startRun = () => {\n s.followUpRequested = false;\n const ac = new AbortController();\n s.abortController = ac;\n setSending(true);\n\n // macrotask: every command admitted this turn coalesces into the take\n setTimeout(async () => {\n try {\n await run(ac.signal);\n resolveActive();\n } catch (error) {\n s.followUpRequested = false;\n // disposed means unmounted mid-run: the abort is ours, no callbacks\n if (!s.disposed) {\n if (ac.signal.aborted) settleCancelled();\n else await settleFailed(error as Error);\n }\n } finally {\n if (s.disposed) {\n s.abortController = null;\n } else {\n getOptions().onFinish?.();\n if (s.followUpRequested) {\n startRun();\n } else {\n s.abortController = null;\n setSending(false);\n }\n }\n }\n }, 0);\n };\n\n const schedule = () => {\n if (s.abortController) {\n s.followUpRequested = true;\n return;\n }\n startRun();\n };\n\n return {\n send: (command: AssistantTransportCommand, opts?: SendOptions) => {\n const [execution, resolvers] = CommandExecution.withResolvers();\n setQueue({\n queued: [...s.queue.queued, { command, execution: resolvers }],\n inTransit: s.queue.inTransit,\n });\n if (opts?.schedule !== false) schedule();\n return execution;\n },\n setParentId: (id: string | null) => {\n s.parentId = id;\n },\n cancel: () => {\n s.resumeRequested = false;\n s.followUpRequested = false;\n s.abortController?.abort();\n },\n resume: () => {\n if (!getOptions().resumeApi)\n throw new Error(\"Must pass resumeApi to options to resume runs\");\n\n s.resumeRequested = true;\n schedule();\n },\n reload: (id: string | null) => {\n s.parentId = id;\n schedule();\n },\n importState: replaceAgent,\n };\n};\n\nconst useAssistantTransportHost = (\n options: HostOptions,\n): Statewire<AssistantTransportHostState, AssistantTransportHostCommands> => {\n const latestOptions = useRef(options);\n latestOptions.current = options;\n\n const [state, ctl] = useStatewireState<AssistantTransportHostState>(() => ({\n agent: options.initialState,\n queueVersion: 0,\n isSending: false,\n isReplaying: false,\n }));\n const emit = useStatewireEmit();\n\n const handlers = useHostLoop(\n () => latestOptions.current,\n ctl,\n () => ctl.snapshot().agent,\n );\n\n const commands = useStatewireCommands(handlers);\n\n return { state, commands, emit };\n};\n\nexport const AssistantTransportHost = resource(useAssistantTransportHost);\n"],"mappings":";;;;;;;;;AA6EA,MAAMuD,cAAcC,YAA0BA,QAAQC,KAAKC,MAAMA,EAAEhB,OAAO;AAc1E,MAAMyB,eACJC,YACAC,KACAE,aACG;CACH,MAAM,CAACC,KAAKtE,gBACQ;EAChB0D,OAAO;GAAEhC,QAAQ,CAAA;GAAIC,WAAW,CAAA;EAAG;EACnCgC,eAAe,CAAA;EACfhB,UAAU4B,KAAAA;EACVX,iBAAiB;EACjBC,mBAAmB;EACnBxB,aAAa;EACbyB,UAAU;EACVC,iBAAiB;EACjB5B,cAAc;CAChB,EACF;CAEArC,gBAAgB;EACdwE,EAAER,WAAW;EACb,aAAa;GACXQ,EAAER,WAAW;GACbQ,EAAET,oBAAoB;GACtBS,EAAEP,iBAAiBS,MAAM;EAC3B;CACF,GAAG,CAACF,CAAC,CAAC;CAEN,MAAMG,gBAAgBC,UAAmB;EACvC,IAAIJ,EAAEjC,gBAAgBqC,OAAO;EAC7BJ,EAAEjC,cAAcqC;EAChBP,IAAIQ,MAAM,CAAC;GAAEC,IAAI;GAAWC,MAAM,CAAC,aAAa;GAAGH;EAAM,CAAC,CAAC;CAC7D;CAEA,MAAMI,cAAcJ,YAAmB;EACrCP,IAAIQ,MAAM,CAAC;GAAEC,IAAI;GAAWC,MAAM,CAAC,WAAW;GAAGH,OAAAA;EAAM,CAAC,C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AAa;CACf,EAAE;CACF,MAAMsH,OAAO/I,iBAAiB;CAU9B,OAAO;EAAEoC;EAAO6C,UAFClF,qBANAsD,kBACTwF,cAAc5H,SACpBsC,WACMA,IAAI0F,SAAS,CAAC,CAAC3H,KAGe0H,CAEtB/D;EAAU8D;CAAK;AACjC;AAEA,MAAaG,yBAAyB7J,SAASsJ,yBAAyB"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,25 @@
|
|
|
1
1
|
import { AddMessageCommand, AddToolResultCommand, AssistantMessage, AssistantTransportCommand, AssistantTransportConnectionMetadata, AssistantTransportOptions, AssistantTransportProtocol, AssistantTransportState, AssistantTransportStateConverter, HeadersValue, ImagePart, SendCommandsRequestBody, TextPart, UserMessage, UserMessagePart } from "./types.js";
|
|
2
2
|
import { AssistantTransportThread } from "./AssistantTransportThread.js";
|
|
3
|
+
import { StatewireThread } from "./StatewireThread.js";
|
|
3
4
|
import { useAssistantTransportSendCommand, useAssistantTransportState } from "./hooks.js";
|
|
4
|
-
|
|
5
|
-
|
|
5
|
+
//#region src/index.d.ts
|
|
6
|
+
declare namespace AssistantTransportThread {
|
|
7
|
+
type Options<T> = AssistantTransportOptions<T>;
|
|
8
|
+
type Command = AssistantTransportCommand;
|
|
9
|
+
type Protocol = AssistantTransportProtocol;
|
|
10
|
+
type State = AssistantTransportState;
|
|
11
|
+
type ConnectionMetadata = AssistantTransportConnectionMetadata;
|
|
12
|
+
type StateConverter<T> = AssistantTransportStateConverter<T>;
|
|
13
|
+
type AddMessageCommand = AddMessageCommand;
|
|
14
|
+
type AddToolResultCommand = AddToolResultCommand;
|
|
15
|
+
type SendCommandsRequestBody = SendCommandsRequestBody;
|
|
16
|
+
type UserMessage = UserMessage;
|
|
17
|
+
type AssistantMessage = AssistantMessage;
|
|
18
|
+
type UserMessagePart = UserMessagePart;
|
|
19
|
+
type TextPart = TextPart;
|
|
20
|
+
type ImagePart = ImagePart;
|
|
21
|
+
type HeadersValue = HeadersValue;
|
|
22
|
+
}
|
|
23
|
+
//#endregion
|
|
24
|
+
export { AssistantTransportThread, StatewireThread, useAssistantTransportSendCommand, useAssistantTransportState };
|
|
25
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;kBAUiB;OACH,QAAQ,KAAK,0BAAgC;OAC7C,UAAU;OACV,WAAW;OACX,QAAQ;OACR,qBAAqB;OACrB,eAAe,KAAK,iCAAuC;OAC3D,oBAAoB;OACpB,uBAAuB;OACvB,0BAA0B;OAC1B,cAAc;OACd,mBAAmB;OACnB,kBAAkB;OAClB,WAAW;OACX,YAAY;OACZ,eAAe"}
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { REPLAY_CONTENT_LENGTH_HEADER } from "./replayBoundaryStream.js";
|
|
2
1
|
import { AssistantTransportThread } from "./AssistantTransportThread.js";
|
|
2
|
+
import { StatewireThread } from "./StatewireThread.js";
|
|
3
3
|
import { useAssistantTransportSendCommand, useAssistantTransportState } from "./hooks.js";
|
|
4
|
-
export { AssistantTransportThread,
|
|
4
|
+
export { AssistantTransportThread, StatewireThread, useAssistantTransportSendCommand, useAssistantTransportState };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"replayBoundaryStream.d.ts","names":[],"sources":["../src/replayBoundaryStream.ts"],"mappings":";cAAa;
|
|
1
|
+
{"version":3,"file":"replayBoundaryStream.d.ts","names":[],"sources":["../src/replayBoundaryStream.ts"],"mappings":";cAAa;cAmBA,6BACX,UAAU,UACV,eAAe,4BACd,QAAQ,eAAe,WAAW"}
|
|
@@ -4,8 +4,10 @@ const waitForRender = () => new Promise((r) => setTimeout(r, 0));
|
|
|
4
4
|
const parseReplayContentLength = (headers) => {
|
|
5
5
|
const raw = headers.get(REPLAY_CONTENT_LENGTH_HEADER);
|
|
6
6
|
if (raw == null) return 0;
|
|
7
|
-
const
|
|
8
|
-
|
|
7
|
+
const trimmed = raw.trim();
|
|
8
|
+
const boundary = Number(trimmed);
|
|
9
|
+
if (!/^\d+$/.test(trimmed) || !Number.isSafeInteger(boundary)) throw new Error(`statewire: invalid ${REPLAY_CONTENT_LENGTH_HEADER} header "${raw}"`);
|
|
10
|
+
return boundary;
|
|
9
11
|
};
|
|
10
12
|
const createReplayBoundaryStream = async (response, setReplaying) => {
|
|
11
13
|
const body = response.body;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"replayBoundaryStream.js","names":["REPLAY_CONTENT_LENGTH_HEADER","waitForRender","Promise","r","setTimeout","parseReplayContentLength","headers","Headers","raw","get","boundary","Number","isSafeInteger","createReplayBoundaryStream","response","Response","setReplaying","value","ReadableStream","Uint8Array","ArrayBuffer","body","remaining","finishReplay","transformer","Transformer","cancel","transform","chunk","controller","enqueue","replayPart","subarray","byteLength","flush","pipeThrough","TransformStream"],"sources":["../src/replayBoundaryStream.ts"],"sourcesContent":["export const REPLAY_CONTENT_LENGTH_HEADER = \"Aui-Replay-Content-Length\";\n\nconst waitForRender = () => new Promise<void>((r) => setTimeout(r, 0));\n\nconst parseReplayContentLength = (headers: Headers): number => {\n const raw = headers.get(REPLAY_CONTENT_LENGTH_HEADER);\n if (raw == null) return 0;\n\n const boundary = Number(
|
|
1
|
+
{"version":3,"file":"replayBoundaryStream.js","names":["REPLAY_CONTENT_LENGTH_HEADER","waitForRender","Promise","r","setTimeout","parseReplayContentLength","headers","Headers","raw","get","trimmed","trim","boundary","Number","test","isSafeInteger","Error","createReplayBoundaryStream","response","Response","setReplaying","value","ReadableStream","Uint8Array","ArrayBuffer","body","remaining","finishReplay","transformer","Transformer","cancel","transform","chunk","controller","enqueue","replayPart","subarray","byteLength","flush","pipeThrough","TransformStream"],"sources":["../src/replayBoundaryStream.ts"],"sourcesContent":["export const REPLAY_CONTENT_LENGTH_HEADER = \"Aui-Replay-Content-Length\";\n\nconst waitForRender = () => new Promise<void>((r) => setTimeout(r, 0));\n\nconst parseReplayContentLength = (headers: Headers): number => {\n const raw = headers.get(REPLAY_CONTENT_LENGTH_HEADER);\n if (raw == null) return 0;\n\n const trimmed = raw.trim();\n const boundary = Number(trimmed);\n if (!/^\\d+$/.test(trimmed) || !Number.isSafeInteger(boundary)) {\n throw new Error(\n `statewire: invalid ${REPLAY_CONTENT_LENGTH_HEADER} header \"${raw}\"`,\n );\n }\n return boundary;\n};\n\n// Gates replay bytes until isReplaying:true renders, then releases live bytes after isReplaying:false renders.\nexport const createReplayBoundaryStream = async (\n response: Response,\n setReplaying: (value: boolean) => void,\n): Promise<ReadableStream<Uint8Array<ArrayBuffer>>> => {\n const body = response.body!;\n let remaining = parseReplayContentLength(response.headers);\n\n if (remaining <= 0) {\n return body;\n }\n\n setReplaying(true);\n await waitForRender();\n\n // Let replay bytes drain before rendering live mode, then render live mode before releasing live bytes.\n const finishReplay = async () => {\n remaining = 0;\n await waitForRender();\n setReplaying(false);\n await waitForRender();\n };\n\n // TS's Transformer type predates the spec's cancel hook.\n const transformer: Transformer<\n Uint8Array<ArrayBuffer>,\n Uint8Array<ArrayBuffer>\n > & { cancel: () => void } = {\n async transform(chunk, controller) {\n if (remaining === 0) {\n controller.enqueue(chunk);\n return;\n }\n const replayPart = chunk.subarray(0, remaining);\n remaining -= replayPart.byteLength;\n controller.enqueue(replayPart);\n if (remaining > 0) return;\n await finishReplay();\n if (replayPart.byteLength < chunk.byteLength) {\n controller.enqueue(chunk.subarray(replayPart.byteLength));\n }\n },\n async flush() {\n if (remaining > 0) await finishReplay();\n },\n cancel() {\n if (remaining > 0) setReplaying(false);\n remaining = 0;\n },\n };\n\n return body.pipeThrough(new TransformStream(transformer));\n};\n"],"mappings":";AAAA,MAAaA,+BAA+B;AAE5C,MAAMC,sBAAsB,IAAIC,SAAeC,MAAMC,WAAWD,GAAG,CAAC,CAAC;AAErE,MAAME,4BAA4BC,YAA6B;CAC7D,MAAME,MAAMF,QAAQG,IAAIT,4BAA4B;CACpD,IAAIQ,OAAO,MAAM,OAAO;CAExB,MAAME,UAAUF,IAAIG,KAAK;CACzB,MAAMC,WAAWC,OAAOH,OAAO;CAC/B,IAAI,CAAC,QAAQI,KAAKJ,OAAO,KAAK,CAACG,OAAOE,cAAcH,QAAQ,GAC1D,MAAM,IAAII,MACR,sBAAsBhB,6BAA4B,WAAYQ,IAAG,EACnE;CAEF,OAAOI;AACT;AAGA,MAAaK,6BAA6B,OACxCC,UACAE,iBACqD;CACrD,MAAMK,OAAOP,SAASO;CACtB,IAAIC,YAAYrB,yBAAyBa,SAASZ,OAAO;CAEzD,IAAIoB,aAAa,GACf,OAAOD;CAGTL,aAAa,IAAI;CACjB,MAAMnB,cAAc;CAGpB,MAAM0B,eAAe,YAAY;EAC/BD,YAAY;EACZ,MAAMzB,cAAc;EACpBmB,aAAa,KAAK;EAClB,MAAMnB,cAAc;CACtB;CA8BA,OAAOwB,KAAKc,YAAY,IAAIC,gBAAgBZ;EAvB1C,MAAMG,UAAUC,OAAOC,YAAY;GACjC,IAAIP,cAAc,GAAG;IACnBO,WAAWC,QAAQF,KAAK;IACxB;GACF;GACA,MAAMG,aAAaH,MAAMI,SAAS,GAAGV,SAAS;GAC9CA,aAAaS,WAAWE;GACxBJ,WAAWC,QAAQC,UAAU;GAC7B,IAAIT,YAAY,GAAG;GACnB,MAAMC,aAAa;GACnB,IAAIQ,WAAWE,aAAaL,MAAMK,YAChCJ,WAAWC,QAAQF,MAAMI,SAASD,WAAWE,UAAU,CAAC;EAE5D;EACA,MAAMC,QAAQ;GACZ,IAAIZ,YAAY,GAAG,MAAMC,aAAa;EACxC;EACAG,SAAS;GACP,IAAIJ,YAAY,GAAGN,aAAa,KAAK;GACrCM,YAAY;EACd;CAG0CE,CAAW,CAAC;AAC1D"}
|
package/dist/stateOps.d.ts
CHANGED
|
@@ -2,9 +2,9 @@ import { Statewire } from "statewire";
|
|
|
2
2
|
import { AssistantTransportStateOperation } from "assistant-stream";
|
|
3
3
|
//#region src/stateOps.d.ts
|
|
4
4
|
type TranslatedOp = Extract<Statewire.Op, {
|
|
5
|
-
op: "replace" | "add"
|
|
5
|
+
op: "replace" | "add";
|
|
6
6
|
}>;
|
|
7
|
-
declare const translateStateOp: (root: unknown, op: AssistantTransportStateOperation) => TranslatedOp;
|
|
7
|
+
declare const translateStateOp: (root: unknown, op: AssistantTransportStateOperation) => TranslatedOp | undefined;
|
|
8
8
|
//#endregion
|
|
9
9
|
export { TranslatedOp, translateStateOp };
|
|
10
10
|
//# sourceMappingURL=stateOps.d.ts.map
|
package/dist/stateOps.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stateOps.d.ts","names":[],"sources":["../src/stateOps.ts"],"mappings":";;;KAGY,eAAe,
|
|
1
|
+
{"version":3,"file":"stateOps.d.ts","names":[],"sources":["../src/stateOps.ts"],"mappings":";;;KAGY,eAAe,QAAQ,UAAU;EAAM;;cA8BtC,mBACX,eACA,IAAI,qCACH"}
|