@assistant-ui/react-statewire 0.0.1 → 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 +15 -16
- 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
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { useCallback, useMemo, useRef, useState } from "react";
|
|
2
|
+
import { resource, useResource } from "@assistant-ui/tap";
|
|
3
|
+
import type { ResourceElement } from "@assistant-ui/tap";
|
|
4
|
+
import { ExternalThread } from "@assistant-ui/react";
|
|
5
|
+
import type { ExternalThreadMessage } from "@assistant-ui/react";
|
|
6
|
+
import { forwardTransformScopes } from "@assistant-ui/store";
|
|
7
|
+
import type { ClientOutput } from "@assistant-ui/store";
|
|
8
|
+
import type {
|
|
9
|
+
AppendMessage,
|
|
10
|
+
AttachmentAdapter,
|
|
11
|
+
ThreadMessage,
|
|
12
|
+
} from "@assistant-ui/core";
|
|
13
|
+
import type { ReadonlyJSONValue } from "assistant-stream/utils";
|
|
14
|
+
import { useStatewire } from "statewire";
|
|
15
|
+
import type { Statewire } from "statewire";
|
|
16
|
+
import {
|
|
17
|
+
convertAppendMessageToCommand,
|
|
18
|
+
symbolAssistantTransportExtras,
|
|
19
|
+
} from "./AssistantTransportThread";
|
|
20
|
+
import type { AssistantTransportExtras } from "./AssistantTransportThread";
|
|
21
|
+
import type { AssistantTransportCommand } from "./types";
|
|
22
|
+
|
|
23
|
+
type AnyCommands = Record<string, (...args: any[]) => unknown>;
|
|
24
|
+
|
|
25
|
+
const EMPTY_CONVERTED: StatewireThread.State = {
|
|
26
|
+
messages: [],
|
|
27
|
+
isRunning: false,
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
const useStatewireThread = (
|
|
31
|
+
options: StatewireThread.Options<any>,
|
|
32
|
+
): ClientOutput<"thread"> => {
|
|
33
|
+
const latest = useRef(options);
|
|
34
|
+
latest.current = options;
|
|
35
|
+
|
|
36
|
+
const [pending, setPending] = useState<readonly AssistantTransportCommand[]>(
|
|
37
|
+
[],
|
|
38
|
+
);
|
|
39
|
+
const [retire] = useState(
|
|
40
|
+
() => (command: unknown) =>
|
|
41
|
+
setPending((prev) =>
|
|
42
|
+
prev.includes(command as AssistantTransportCommand)
|
|
43
|
+
? prev.filter((c) => c !== command)
|
|
44
|
+
: prev,
|
|
45
|
+
),
|
|
46
|
+
);
|
|
47
|
+
|
|
48
|
+
const { state, commands } = useStatewire<unknown, AnyCommands>({
|
|
49
|
+
transport: options.transport,
|
|
50
|
+
onCommandChange: (update) => {
|
|
51
|
+
if (update.status === "acked" || update.status === "settled")
|
|
52
|
+
retire(update.params[0]);
|
|
53
|
+
},
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
const dispatch = useCallback(
|
|
57
|
+
(command: AssistantTransportCommand) => {
|
|
58
|
+
setPending((prev) => [...prev, command]);
|
|
59
|
+
void commands[command.type]!(command).catch((error: Error) => {
|
|
60
|
+
retire(command);
|
|
61
|
+
latest.current.onError?.(error);
|
|
62
|
+
});
|
|
63
|
+
},
|
|
64
|
+
[commands, retire],
|
|
65
|
+
);
|
|
66
|
+
|
|
67
|
+
const { converter } = options;
|
|
68
|
+
const metadata = useMemo(
|
|
69
|
+
(): StatewireThread.ConnectionMetadata => ({
|
|
70
|
+
pendingCommands: [...pending],
|
|
71
|
+
isSending: pending.length > 0,
|
|
72
|
+
}),
|
|
73
|
+
[pending],
|
|
74
|
+
);
|
|
75
|
+
const converted = useMemo(
|
|
76
|
+
() => (state === undefined ? EMPTY_CONVERTED : converter(state, metadata)),
|
|
77
|
+
[converter, state, metadata],
|
|
78
|
+
);
|
|
79
|
+
|
|
80
|
+
const extras = useMemo(
|
|
81
|
+
(): AssistantTransportExtras => ({
|
|
82
|
+
[symbolAssistantTransportExtras]: true,
|
|
83
|
+
sendCommand: dispatch,
|
|
84
|
+
state,
|
|
85
|
+
}),
|
|
86
|
+
[dispatch, state],
|
|
87
|
+
);
|
|
88
|
+
|
|
89
|
+
const handleAppend = (message: AppendMessage) => {
|
|
90
|
+
const command = convertAppendMessageToCommand(message);
|
|
91
|
+
if (!command) return;
|
|
92
|
+
dispatch(command);
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
return useResource(
|
|
96
|
+
ExternalThread({
|
|
97
|
+
messages: converted.messages as readonly ExternalThreadMessage[],
|
|
98
|
+
isRunning: converted.isRunning,
|
|
99
|
+
isLoading: state === undefined,
|
|
100
|
+
state: converted.state,
|
|
101
|
+
extras,
|
|
102
|
+
attachmentAdapter: options.adapters?.attachments,
|
|
103
|
+
onNew: handleAppend,
|
|
104
|
+
...(options.capabilities?.edit && { onEdit: handleAppend }),
|
|
105
|
+
onCancel: () => {
|
|
106
|
+
void commands["cancel"]!().catch((error: Error) => {
|
|
107
|
+
latest.current.onError?.(error);
|
|
108
|
+
});
|
|
109
|
+
},
|
|
110
|
+
}),
|
|
111
|
+
);
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
export const StatewireThread = <T>(
|
|
115
|
+
options: StatewireThread.Options<T>,
|
|
116
|
+
): ResourceElement<ClientOutput<"thread">> =>
|
|
117
|
+
resource(useStatewireThread)(options as StatewireThread.Options<any>);
|
|
118
|
+
|
|
119
|
+
export namespace StatewireThread {
|
|
120
|
+
export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;
|
|
121
|
+
|
|
122
|
+
export type State = {
|
|
123
|
+
readonly messages: readonly ThreadMessage[];
|
|
124
|
+
readonly state?: ReadonlyJSONValue;
|
|
125
|
+
readonly isRunning: boolean;
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
export type ConnectionMetadata = {
|
|
129
|
+
pendingCommands: AssistantTransportCommand[];
|
|
130
|
+
isSending: boolean;
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
export type StateConverter<T> = (
|
|
134
|
+
state: T,
|
|
135
|
+
connectionMetadata: ConnectionMetadata,
|
|
136
|
+
) => State;
|
|
137
|
+
|
|
138
|
+
export type Options<T> = {
|
|
139
|
+
transport: Transport<T>;
|
|
140
|
+
converter: StateConverter<T>;
|
|
141
|
+
onError?: ((error: Error) => void) | undefined;
|
|
142
|
+
capabilities?:
|
|
143
|
+
| {
|
|
144
|
+
edit?: boolean | undefined;
|
|
145
|
+
}
|
|
146
|
+
| undefined;
|
|
147
|
+
adapters?:
|
|
148
|
+
| {
|
|
149
|
+
attachments?: AttachmentAdapter | undefined;
|
|
150
|
+
}
|
|
151
|
+
| undefined;
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// Scope transforms are keyed by the underlying hook, not the resource wrapper.
|
|
156
|
+
forwardTransformScopes(
|
|
157
|
+
useStatewireThread,
|
|
158
|
+
ExternalThread(undefined as never).hook,
|
|
159
|
+
);
|
package/src/host.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { useEffect, useRef, useState } from "react";
|
|
2
2
|
import { resource } from "@assistant-ui/tap";
|
|
3
|
-
import type { ResourceElement } from "@assistant-ui/tap";
|
|
4
3
|
import { createRequestHeaders } from "@assistant-ui/core";
|
|
5
4
|
import type { ModelContext } from "@assistant-ui/core";
|
|
6
5
|
import {
|
|
@@ -10,15 +9,14 @@ import {
|
|
|
10
9
|
} from "assistant-stream";
|
|
11
10
|
import type { AssistantTransportStateOperation } from "assistant-stream";
|
|
12
11
|
import { asAsyncIterableStream } from "assistant-stream/utils";
|
|
13
|
-
import { applyOps } from "statewire";
|
|
14
12
|
import type { Statewire } from "statewire";
|
|
15
13
|
import {
|
|
16
14
|
CommandExecution,
|
|
17
15
|
useStatewireCommands,
|
|
18
16
|
useStatewireEmit,
|
|
19
17
|
useStatewireState,
|
|
20
|
-
} from "statewire/
|
|
21
|
-
import type {
|
|
18
|
+
} from "statewire/host";
|
|
19
|
+
import type { StatewireHost } from "statewire/host";
|
|
22
20
|
import { createReplayBoundaryStream } from "./replayBoundaryStream";
|
|
23
21
|
import { translateStateOp } from "./stateOps";
|
|
24
22
|
import type {
|
|
@@ -69,7 +67,7 @@ export type AssistantTransportHostCommands = {
|
|
|
69
67
|
|
|
70
68
|
type QueueEntry = {
|
|
71
69
|
command: AssistantTransportCommand;
|
|
72
|
-
execution:
|
|
70
|
+
execution: StatewireHost.ExecutionResolvers;
|
|
73
71
|
};
|
|
74
72
|
|
|
75
73
|
type EntryQueue = {
|
|
@@ -79,23 +77,49 @@ type EntryQueue = {
|
|
|
79
77
|
|
|
80
78
|
const commandsOf = (entries: QueueEntry[]) => entries.map((e) => e.command);
|
|
81
79
|
|
|
82
|
-
|
|
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 = (
|
|
83
93
|
getOptions: () => HostOptions,
|
|
84
|
-
ctl:
|
|
94
|
+
ctl: StatewireHost.StateCtl,
|
|
95
|
+
getAgent: () => unknown,
|
|
85
96
|
) => {
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
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]);
|
|
95
119
|
|
|
96
120
|
const setReplaying = (value: boolean) => {
|
|
97
|
-
if (isReplaying === value) return;
|
|
98
|
-
isReplaying = value;
|
|
121
|
+
if (s.isReplaying === value) return;
|
|
122
|
+
s.isReplaying = value;
|
|
99
123
|
ctl.apply([{ op: "replace", path: ["isReplaying"], value }]);
|
|
100
124
|
};
|
|
101
125
|
|
|
@@ -104,51 +128,44 @@ const createHostLoop = (
|
|
|
104
128
|
};
|
|
105
129
|
|
|
106
130
|
const replaceAgent = (next: unknown) => {
|
|
107
|
-
agent = next;
|
|
108
131
|
ctl.apply([{ op: "replace", path: ["agent"], value: next }]);
|
|
109
132
|
};
|
|
110
133
|
|
|
111
134
|
const updateState = (updater: (state: unknown) => unknown) => {
|
|
112
|
-
replaceAgent(updater(
|
|
135
|
+
replaceAgent(updater(getAgent()));
|
|
113
136
|
};
|
|
114
137
|
|
|
115
|
-
//
|
|
116
|
-
// Ops mirror one-by-one under ["agent"] so untouched slices keep identity.
|
|
138
|
+
// Ops commit one-by-one — an op error leaves the chunk's prefix applied.
|
|
117
139
|
const applyChunkOps = (
|
|
118
140
|
operations: readonly AssistantTransportStateOperation[],
|
|
119
141
|
) => {
|
|
120
|
-
let next = agent;
|
|
121
|
-
const translated: Statewire.Op[] = [];
|
|
122
142
|
for (const operation of operations) {
|
|
123
|
-
const op = translateStateOp(
|
|
124
|
-
|
|
125
|
-
|
|
143
|
+
const op = translateStateOp(getAgent(), operation);
|
|
144
|
+
if (op === undefined) continue;
|
|
145
|
+
ctl.apply([{ ...op, path: ["agent", ...op.path] }]);
|
|
126
146
|
}
|
|
127
|
-
agent = next;
|
|
128
|
-
ctl.apply(translated);
|
|
129
147
|
};
|
|
130
148
|
|
|
131
|
-
let queueVersion = 0;
|
|
132
149
|
const setQueue = (next: EntryQueue) => {
|
|
133
|
-
queue = next;
|
|
150
|
+
s.queue = next;
|
|
134
151
|
getOptions().queueCell.current = {
|
|
135
152
|
queued: commandsOf(next.queued),
|
|
136
153
|
inTransit: commandsOf(next.inTransit),
|
|
137
154
|
};
|
|
138
155
|
ctl.apply([
|
|
139
|
-
{ op: "replace", path: ["queueVersion"], value: ++queueVersion },
|
|
156
|
+
{ op: "replace", path: ["queueVersion"], value: ++s.queueVersion },
|
|
140
157
|
]);
|
|
141
158
|
};
|
|
142
159
|
|
|
143
160
|
const takeQueuedIntoTransit = (): QueueEntry[] => {
|
|
144
|
-
const { queued, inTransit } = queue;
|
|
161
|
+
const { queued, inTransit } = s.queue;
|
|
145
162
|
if (queued.length === 0) return [];
|
|
146
163
|
setQueue({ queued: [], inTransit: [...inTransit, ...queued] });
|
|
147
164
|
return queued;
|
|
148
165
|
};
|
|
149
166
|
|
|
150
167
|
const drainQueue = (): EntryQueue => {
|
|
151
|
-
const drained = queue;
|
|
168
|
+
const drained = s.queue;
|
|
152
169
|
setQueue({ queued: [], inTransit: [] });
|
|
153
170
|
return drained;
|
|
154
171
|
};
|
|
@@ -156,15 +173,14 @@ const createHostLoop = (
|
|
|
156
173
|
const buildRequestBody = async (
|
|
157
174
|
o: HostOptions,
|
|
158
175
|
commands: AssistantTransportCommand[],
|
|
176
|
+
runParentId: string | null | undefined,
|
|
159
177
|
) => {
|
|
160
|
-
const runParentId = parentId;
|
|
161
|
-
parentId = undefined;
|
|
162
178
|
const bodyValue = typeof o.body === "function" ? await o.body() : o.body;
|
|
163
179
|
const { modelContext, threadId } = o.getRunContext();
|
|
164
180
|
|
|
165
181
|
const requestBody: Record<string, unknown> = {
|
|
166
182
|
commands,
|
|
167
|
-
state:
|
|
183
|
+
state: getAgent(),
|
|
168
184
|
system: modelContext.system,
|
|
169
185
|
tools: modelContext.tools
|
|
170
186
|
? toToolsJSONSchema(modelContext.tools)
|
|
@@ -185,14 +201,35 @@ const createHostLoop = (
|
|
|
185
201
|
|
|
186
202
|
const run = async (signal: AbortSignal) => {
|
|
187
203
|
const o = getOptions();
|
|
188
|
-
const isResume = resumeRequested;
|
|
189
|
-
resumeRequested = false;
|
|
204
|
+
const isResume = s.resumeRequested;
|
|
205
|
+
s.resumeRequested = false;
|
|
190
206
|
setReplaying(false);
|
|
191
|
-
activeEntries = isResume ? [] : takeQueuedIntoTransit();
|
|
192
|
-
if (activeEntries.length === 0 && !isResume)
|
|
207
|
+
s.activeEntries = isResume ? [] : takeQueuedIntoTransit();
|
|
208
|
+
if (s.activeEntries.length === 0 && !isResume && s.parentId === undefined)
|
|
209
|
+
return;
|
|
210
|
+
|
|
211
|
+
const runParentId = s.parentId;
|
|
212
|
+
s.parentId = undefined;
|
|
213
|
+
try {
|
|
214
|
+
await runRequest(o, isResume, runParentId, signal);
|
|
215
|
+
} catch (error) {
|
|
216
|
+
if (!signal.aborted && s.parentId === undefined) s.parentId = runParentId;
|
|
217
|
+
throw error;
|
|
218
|
+
}
|
|
219
|
+
};
|
|
193
220
|
|
|
221
|
+
const runRequest = async (
|
|
222
|
+
o: HostOptions,
|
|
223
|
+
isResume: boolean,
|
|
224
|
+
runParentId: string | null | undefined,
|
|
225
|
+
signal: AbortSignal,
|
|
226
|
+
) => {
|
|
194
227
|
const headers = await createRequestHeaders(o.headers);
|
|
195
|
-
const requestBody = await buildRequestBody(
|
|
228
|
+
const requestBody = await buildRequestBody(
|
|
229
|
+
o,
|
|
230
|
+
commandsOf(s.activeEntries),
|
|
231
|
+
runParentId,
|
|
232
|
+
);
|
|
196
233
|
|
|
197
234
|
const response = await fetch(isResume ? o.resumeApi! : o.api, {
|
|
198
235
|
method: "POST",
|
|
@@ -211,17 +248,18 @@ const createHostLoop = (
|
|
|
211
248
|
}
|
|
212
249
|
|
|
213
250
|
const body = await createReplayBoundaryStream(response, setReplaying);
|
|
251
|
+
const strict = !isResume;
|
|
214
252
|
const decoder =
|
|
215
253
|
(o.protocol ?? "data-stream") === "assistant-transport"
|
|
216
|
-
? new AssistantTransportDecoder()
|
|
217
|
-
: new DataStreamDecoder();
|
|
254
|
+
? new AssistantTransportDecoder({ strict })
|
|
255
|
+
: new DataStreamDecoder({ strict });
|
|
218
256
|
|
|
219
257
|
let streamError: string | undefined;
|
|
220
258
|
let delivered = false;
|
|
221
259
|
|
|
222
260
|
const markDelivered = () => {
|
|
223
|
-
for (const entry of activeEntries) entry.execution.ack();
|
|
224
|
-
setQueue({ ...queue, inTransit: [] });
|
|
261
|
+
for (const entry of s.activeEntries) entry.execution.ack();
|
|
262
|
+
setQueue({ ...s.queue, inTransit: [] });
|
|
225
263
|
delivered = true;
|
|
226
264
|
};
|
|
227
265
|
|
|
@@ -248,11 +286,11 @@ const createHostLoop = (
|
|
|
248
286
|
if (!delivered) markDelivered();
|
|
249
287
|
|
|
250
288
|
// commands that coalesced into a resume run must not starve
|
|
251
|
-
if (isResume && queue.queued.length > 0) followUpRequested = true;
|
|
289
|
+
if (isResume && s.queue.queued.length > 0) s.followUpRequested = true;
|
|
252
290
|
};
|
|
253
291
|
|
|
254
292
|
const resolveActive = () => {
|
|
255
|
-
for (const entry of activeEntries.splice(0)) entry.execution.resolve();
|
|
293
|
+
for (const entry of s.activeEntries.splice(0)) entry.execution.resolve();
|
|
256
294
|
};
|
|
257
295
|
|
|
258
296
|
const settleCancelled = () => {
|
|
@@ -287,9 +325,9 @@ const createHostLoop = (
|
|
|
287
325
|
};
|
|
288
326
|
|
|
289
327
|
const startRun = () => {
|
|
290
|
-
followUpRequested = false;
|
|
328
|
+
s.followUpRequested = false;
|
|
291
329
|
const ac = new AbortController();
|
|
292
|
-
abortController = ac;
|
|
330
|
+
s.abortController = ac;
|
|
293
331
|
setSending(true);
|
|
294
332
|
|
|
295
333
|
// macrotask: every command admitted this turn coalesces into the take
|
|
@@ -298,21 +336,21 @@ const createHostLoop = (
|
|
|
298
336
|
await run(ac.signal);
|
|
299
337
|
resolveActive();
|
|
300
338
|
} catch (error) {
|
|
301
|
-
followUpRequested = false;
|
|
339
|
+
s.followUpRequested = false;
|
|
302
340
|
// disposed means unmounted mid-run: the abort is ours, no callbacks
|
|
303
|
-
if (!disposed) {
|
|
341
|
+
if (!s.disposed) {
|
|
304
342
|
if (ac.signal.aborted) settleCancelled();
|
|
305
343
|
else await settleFailed(error as Error);
|
|
306
344
|
}
|
|
307
345
|
} finally {
|
|
308
|
-
if (disposed) {
|
|
309
|
-
abortController = null;
|
|
346
|
+
if (s.disposed) {
|
|
347
|
+
s.abortController = null;
|
|
310
348
|
} else {
|
|
311
349
|
getOptions().onFinish?.();
|
|
312
|
-
if (followUpRequested) {
|
|
350
|
+
if (s.followUpRequested) {
|
|
313
351
|
startRun();
|
|
314
352
|
} else {
|
|
315
|
-
abortController = null;
|
|
353
|
+
s.abortController = null;
|
|
316
354
|
setSending(false);
|
|
317
355
|
}
|
|
318
356
|
}
|
|
@@ -321,63 +359,49 @@ const createHostLoop = (
|
|
|
321
359
|
};
|
|
322
360
|
|
|
323
361
|
const schedule = () => {
|
|
324
|
-
if (abortController) {
|
|
325
|
-
followUpRequested = true;
|
|
362
|
+
if (s.abortController) {
|
|
363
|
+
s.followUpRequested = true;
|
|
326
364
|
return;
|
|
327
365
|
}
|
|
328
366
|
startRun();
|
|
329
367
|
};
|
|
330
368
|
|
|
331
|
-
|
|
369
|
+
return {
|
|
332
370
|
send: (command: AssistantTransportCommand, opts?: SendOptions) => {
|
|
333
371
|
const [execution, resolvers] = CommandExecution.withResolvers();
|
|
334
372
|
setQueue({
|
|
335
|
-
queued: [...queue.queued, { command, execution: resolvers }],
|
|
336
|
-
inTransit: queue.inTransit,
|
|
373
|
+
queued: [...s.queue.queued, { command, execution: resolvers }],
|
|
374
|
+
inTransit: s.queue.inTransit,
|
|
337
375
|
});
|
|
338
376
|
if (opts?.schedule !== false) schedule();
|
|
339
377
|
return execution;
|
|
340
378
|
},
|
|
341
379
|
setParentId: (id: string | null) => {
|
|
342
|
-
parentId = id;
|
|
380
|
+
s.parentId = id;
|
|
343
381
|
},
|
|
344
382
|
cancel: () => {
|
|
345
|
-
resumeRequested = false;
|
|
346
|
-
followUpRequested = false;
|
|
347
|
-
abortController?.abort();
|
|
383
|
+
s.resumeRequested = false;
|
|
384
|
+
s.followUpRequested = false;
|
|
385
|
+
s.abortController?.abort();
|
|
348
386
|
},
|
|
349
387
|
resume: () => {
|
|
350
388
|
if (!getOptions().resumeApi)
|
|
351
389
|
throw new Error("Must pass resumeApi to options to resume runs");
|
|
352
390
|
|
|
353
|
-
resumeRequested = true;
|
|
391
|
+
s.resumeRequested = true;
|
|
354
392
|
schedule();
|
|
355
393
|
},
|
|
356
394
|
reload: (id: string | null) => {
|
|
357
|
-
parentId = id;
|
|
395
|
+
s.parentId = id;
|
|
358
396
|
schedule();
|
|
359
397
|
},
|
|
360
398
|
importState: replaceAgent,
|
|
361
399
|
};
|
|
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
400
|
};
|
|
377
401
|
|
|
378
402
|
const useAssistantTransportHost = (
|
|
379
403
|
options: HostOptions,
|
|
380
|
-
):
|
|
404
|
+
): Statewire<AssistantTransportHostState, AssistantTransportHostCommands> => {
|
|
381
405
|
const latestOptions = useRef(options);
|
|
382
406
|
latestOptions.current = options;
|
|
383
407
|
|
|
@@ -389,25 +413,15 @@ const useAssistantTransportHost = (
|
|
|
389
413
|
}));
|
|
390
414
|
const emit = useStatewireEmit();
|
|
391
415
|
|
|
392
|
-
const
|
|
393
|
-
|
|
416
|
+
const handlers = useHostLoop(
|
|
417
|
+
() => latestOptions.current,
|
|
418
|
+
ctl,
|
|
419
|
+
() => ctl.snapshot().agent,
|
|
394
420
|
);
|
|
395
421
|
|
|
396
|
-
|
|
397
|
-
loop.arm();
|
|
398
|
-
return loop.dispose;
|
|
399
|
-
}, [loop]);
|
|
400
|
-
|
|
401
|
-
const commands = useStatewireCommands(loop.handlers);
|
|
422
|
+
const commands = useStatewireCommands(handlers);
|
|
402
423
|
|
|
403
424
|
return { state, commands, emit };
|
|
404
425
|
};
|
|
405
426
|
|
|
406
|
-
export const AssistantTransportHost = resource(useAssistantTransportHost)
|
|
407
|
-
options: HostOptions,
|
|
408
|
-
) => ResourceElement<
|
|
409
|
-
StatewireServer.Transport<
|
|
410
|
-
AssistantTransportHostState,
|
|
411
|
-
AssistantTransportHostCommands
|
|
412
|
-
>
|
|
413
|
-
>;
|
|
427
|
+
export const AssistantTransportHost = resource(useAssistantTransportHost);
|
package/src/index.ts
CHANGED
|
@@ -1,23 +1,27 @@
|
|
|
1
|
-
|
|
1
|
+
import type * as types from "./types";
|
|
2
|
+
import { AssistantTransportThread } from "./AssistantTransportThread";
|
|
3
|
+
|
|
4
|
+
export { AssistantTransportThread };
|
|
5
|
+
export { StatewireThread } from "./StatewireThread";
|
|
2
6
|
export {
|
|
3
7
|
useAssistantTransportSendCommand,
|
|
4
8
|
useAssistantTransportState,
|
|
5
9
|
} from "./hooks";
|
|
6
|
-
|
|
7
|
-
export
|
|
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
|
-
}
|
|
10
|
+
|
|
11
|
+
export namespace AssistantTransportThread {
|
|
12
|
+
export type Options<T> = types.AssistantTransportOptions<T>;
|
|
13
|
+
export type Command = types.AssistantTransportCommand;
|
|
14
|
+
export type Protocol = types.AssistantTransportProtocol;
|
|
15
|
+
export type State = types.AssistantTransportState;
|
|
16
|
+
export type ConnectionMetadata = types.AssistantTransportConnectionMetadata;
|
|
17
|
+
export type StateConverter<T> = types.AssistantTransportStateConverter<T>;
|
|
18
|
+
export type AddMessageCommand = types.AddMessageCommand;
|
|
19
|
+
export type AddToolResultCommand = types.AddToolResultCommand;
|
|
20
|
+
export type SendCommandsRequestBody = types.SendCommandsRequestBody;
|
|
21
|
+
export type UserMessage = types.UserMessage;
|
|
22
|
+
export type AssistantMessage = types.AssistantMessage;
|
|
23
|
+
export type UserMessagePart = types.UserMessagePart;
|
|
24
|
+
export type TextPart = types.TextPart;
|
|
25
|
+
export type ImagePart = types.ImagePart;
|
|
26
|
+
export type HeadersValue = types.HeadersValue;
|
|
27
|
+
}
|
|
@@ -6,8 +6,14 @@ const parseReplayContentLength = (headers: Headers): number => {
|
|
|
6
6
|
const raw = headers.get(REPLAY_CONTENT_LENGTH_HEADER);
|
|
7
7
|
if (raw == null) return 0;
|
|
8
8
|
|
|
9
|
-
const
|
|
10
|
-
|
|
9
|
+
const trimmed = raw.trim();
|
|
10
|
+
const boundary = Number(trimmed);
|
|
11
|
+
if (!/^\d+$/.test(trimmed) || !Number.isSafeInteger(boundary)) {
|
|
12
|
+
throw new Error(
|
|
13
|
+
`statewire: invalid ${REPLAY_CONTENT_LENGTH_HEADER} header "${raw}"`,
|
|
14
|
+
);
|
|
15
|
+
}
|
|
16
|
+
return boundary;
|
|
11
17
|
};
|
|
12
18
|
|
|
13
19
|
// Gates replay bytes until isReplaying:true renders, then releases live bytes after isReplaying:false renders.
|