@assistant-ui/react-statewire 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/dist/AssistantTransportThread.d.ts +15 -0
- package/dist/AssistantTransportThread.d.ts.map +1 -0
- package/dist/AssistantTransportThread.js +172 -0
- package/dist/AssistantTransportThread.js.map +1 -0
- package/dist/hooks.d.ts +8 -0
- package/dist/hooks.d.ts.map +1 -0
- package/dist/hooks.js +26 -0
- package/dist/hooks.js.map +1 -0
- package/dist/host.d.ts +41 -0
- package/dist/host.d.ts.map +1 -0
- package/dist/host.js +294 -0
- package/dist/host.js.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +4 -0
- package/dist/replayBoundaryStream.d.ts +6 -0
- package/dist/replayBoundaryStream.d.ts.map +1 -0
- package/dist/replayBoundaryStream.js +47 -0
- package/dist/replayBoundaryStream.js.map +1 -0
- package/dist/stateOps.d.ts +10 -0
- package/dist/stateOps.d.ts.map +1 -0
- package/dist/stateOps.js +106 -0
- package/dist/stateOps.js.map +1 -0
- package/dist/types.d.ts +99 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +0 -0
- package/package.json +54 -0
- package/src/AssistantTransportThread.ts +295 -0
- package/src/__tests__/testHelpers.tsx +243 -0
- package/src/athena.e2e.test.tsx +628 -0
- package/src/hooks.ts +28 -0
- package/src/host.ts +413 -0
- package/src/index.ts +23 -0
- package/src/legacy-diff.test.tsx +581 -0
- package/src/replayBoundaryStream.ts +65 -0
- package/src/stateOps.test.ts +125 -0
- package/src/stateOps.ts +122 -0
- package/src/transport.test.tsx +1858 -0
- package/src/types.ts +140 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 AgentbaseAI Inc.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { AssistantTransportCommand, AssistantTransportOptions } from "./types.js";
|
|
2
|
+
import { ResourceElement } from "@assistant-ui/tap";
|
|
3
|
+
import { ClientOutput } from "@assistant-ui/store";
|
|
4
|
+
//#region src/AssistantTransportThread.d.ts
|
|
5
|
+
declare const symbolAssistantTransportExtras: unique symbol;
|
|
6
|
+
type AssistantTransportExtras = {
|
|
7
|
+
[symbolAssistantTransportExtras]: true;
|
|
8
|
+
sendCommand: (command: AssistantTransportCommand) => void;
|
|
9
|
+
state: unknown;
|
|
10
|
+
};
|
|
11
|
+
declare const asAssistantTransportExtras: (extras: unknown) => AssistantTransportExtras;
|
|
12
|
+
declare const AssistantTransportThread: <T>(options: AssistantTransportOptions<T>) => ResourceElement<ClientOutput<"thread">>;
|
|
13
|
+
//#endregion
|
|
14
|
+
export { AssistantTransportExtras, AssistantTransportThread, asAssistantTransportExtras, symbolAssistantTransportExtras };
|
|
15
|
+
//# sourceMappingURL=AssistantTransportThread.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"AssistantTransportThread.d.ts","names":[],"sources":["../src/AssistantTransportThread.ts"],"mappings":";;;;cAsCa;KAID;GACT;EACD,cAAc,SAAS;EACvB;;cAGW,6BACX,oBACC;cAyOU,2BAA4B,GACvC,SAAS,0BAA0B,OAClC,gBAAgB"}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { AssistantTransportHost } from "./host.js";
|
|
2
|
+
import { useEffect, useMemo, useRef, useState } from "@assistant-ui/tap/react-shim";
|
|
3
|
+
import { resource, useResource } from "@assistant-ui/tap";
|
|
4
|
+
import { ExternalThread } from "@assistant-ui/react";
|
|
5
|
+
import { forwardTransformScopes, useAssistantClientRef } from "@assistant-ui/store";
|
|
6
|
+
import { ToolInvocationTracker } from "@assistant-ui/core/internal";
|
|
7
|
+
import { useStatewire } from "statewire";
|
|
8
|
+
//#region src/AssistantTransportThread.ts
|
|
9
|
+
const EMPTY_TOOL_STATUSES = {};
|
|
10
|
+
const symbolAssistantTransportExtras = Symbol("assistant-transport-extras");
|
|
11
|
+
const asAssistantTransportExtras = (extras) => {
|
|
12
|
+
if (typeof extras !== "object" || extras == null || !(symbolAssistantTransportExtras in extras)) throw new Error("This method can only be called when you are using AssistantTransportThread");
|
|
13
|
+
return extras;
|
|
14
|
+
};
|
|
15
|
+
const convertAppendMessageToCommand = (message) => {
|
|
16
|
+
if (message.role !== "user") throw new Error("Only user messages are supported");
|
|
17
|
+
const parts = [];
|
|
18
|
+
const content = [...message.content, ...message.attachments?.flatMap((a) => a.content) ?? []];
|
|
19
|
+
for (const contentPart of content) if (contentPart.type === "text") parts.push({
|
|
20
|
+
type: "text",
|
|
21
|
+
text: contentPart.text
|
|
22
|
+
});
|
|
23
|
+
else if (contentPart.type === "image") parts.push({
|
|
24
|
+
type: "image",
|
|
25
|
+
image: contentPart.image
|
|
26
|
+
});
|
|
27
|
+
if (parts.length === 0) return null;
|
|
28
|
+
return {
|
|
29
|
+
type: "add-message",
|
|
30
|
+
message: {
|
|
31
|
+
role: "user",
|
|
32
|
+
parts
|
|
33
|
+
},
|
|
34
|
+
parentId: message.parentId,
|
|
35
|
+
sourceId: message.sourceId
|
|
36
|
+
};
|
|
37
|
+
};
|
|
38
|
+
const messagesContainToolCall = (messages, toolCallId) => messages.some((message) => message.content.some((part) => part.type === "tool-call" && (part.toolCallId === toolCallId || part.messages !== void 0 && messagesContainToolCall(part.messages, toolCallId))));
|
|
39
|
+
const useAssistantTransportThread = (options) => {
|
|
40
|
+
const clientRef = useAssistantClientRef();
|
|
41
|
+
const [getRunContext] = useState(() => () => {
|
|
42
|
+
const aui = clientRef.current ?? clientRef.parent;
|
|
43
|
+
let threadId = null;
|
|
44
|
+
try {
|
|
45
|
+
threadId = aui.threadListItem().getState().remoteId ?? null;
|
|
46
|
+
} catch {}
|
|
47
|
+
return {
|
|
48
|
+
modelContext: aui.modelContext().getModelContext(),
|
|
49
|
+
threadId
|
|
50
|
+
};
|
|
51
|
+
});
|
|
52
|
+
const [queueCell] = useState(() => ({ current: {
|
|
53
|
+
queued: [],
|
|
54
|
+
inTransit: []
|
|
55
|
+
} }));
|
|
56
|
+
const { state, commands } = useStatewire({ transport: AssistantTransportHost({
|
|
57
|
+
...options,
|
|
58
|
+
getRunContext,
|
|
59
|
+
queueCell
|
|
60
|
+
}) });
|
|
61
|
+
const { agent: agentState, isSending, isReplaying } = state;
|
|
62
|
+
const queue = queueCell.current;
|
|
63
|
+
const dispatch = (command, opts) => {
|
|
64
|
+
commands.send(command, opts).catch(() => {});
|
|
65
|
+
};
|
|
66
|
+
const [toolStatuses, setToolStatuses] = useState(EMPTY_TOOL_STATUSES);
|
|
67
|
+
const converted = useMemo(() => options.converter(agentState, {
|
|
68
|
+
pendingCommands: [...queue.inTransit, ...queue.queued],
|
|
69
|
+
isSending,
|
|
70
|
+
toolStatuses
|
|
71
|
+
}), [
|
|
72
|
+
options.converter,
|
|
73
|
+
agentState,
|
|
74
|
+
queue,
|
|
75
|
+
isSending,
|
|
76
|
+
toolStatuses
|
|
77
|
+
]);
|
|
78
|
+
const convertedRef = useRef(converted);
|
|
79
|
+
convertedRef.current = converted;
|
|
80
|
+
const [toolInvocations] = useState(() => new ToolInvocationTracker(() => {
|
|
81
|
+
return (clientRef.current ?? clientRef.parent).modelContext().getModelContext().tools;
|
|
82
|
+
}, {
|
|
83
|
+
onResult: (command_0) => {
|
|
84
|
+
const messages = convertedRef.current.messages;
|
|
85
|
+
if (!messagesContainToolCall(messages, command_0.toolCallId)) return;
|
|
86
|
+
dispatch(command_0);
|
|
87
|
+
},
|
|
88
|
+
onStatusesChange: (statuses) => {
|
|
89
|
+
setToolStatuses(statuses.size === 0 ? EMPTY_TOOL_STATUSES : Object.fromEntries(statuses));
|
|
90
|
+
}
|
|
91
|
+
}));
|
|
92
|
+
useEffect(() => {
|
|
93
|
+
toolInvocations.setState({
|
|
94
|
+
messages: converted.messages,
|
|
95
|
+
isRunning: converted.isRunning,
|
|
96
|
+
isLoading: isReplaying
|
|
97
|
+
});
|
|
98
|
+
});
|
|
99
|
+
useEffect(() => () => {
|
|
100
|
+
toolInvocations.reset();
|
|
101
|
+
}, [toolInvocations]);
|
|
102
|
+
const extras = useMemo(() => ({
|
|
103
|
+
[symbolAssistantTransportExtras]: true,
|
|
104
|
+
sendCommand: dispatch,
|
|
105
|
+
state: agentState
|
|
106
|
+
}), [commands, agentState]);
|
|
107
|
+
const handleAppend = (message) => {
|
|
108
|
+
const startRun = message.startRun ?? message.role === "user";
|
|
109
|
+
const command_1 = convertAppendMessageToCommand(message);
|
|
110
|
+
commands.setParentId(message.parentId).catch(() => {});
|
|
111
|
+
const send = () => {
|
|
112
|
+
if (!command_1) return;
|
|
113
|
+
dispatch(command_1, { schedule: startRun });
|
|
114
|
+
};
|
|
115
|
+
if (startRun) toolInvocations.abort().then(send);
|
|
116
|
+
else send();
|
|
117
|
+
};
|
|
118
|
+
return useResource(ExternalThread({
|
|
119
|
+
messages: converted.messages,
|
|
120
|
+
isRunning: converted.isRunning,
|
|
121
|
+
isLoading: isReplaying,
|
|
122
|
+
state: converted.state,
|
|
123
|
+
extras,
|
|
124
|
+
attachmentAdapter: options.adapters?.attachments,
|
|
125
|
+
onNew: handleAppend,
|
|
126
|
+
...options.capabilities?.edit && { onEdit: handleAppend },
|
|
127
|
+
...queue.queued.length > 0 && { onReload: (parentId) => {
|
|
128
|
+
toolInvocations.abort().then(() => {
|
|
129
|
+
commands.reload(parentId).catch(() => {});
|
|
130
|
+
});
|
|
131
|
+
} },
|
|
132
|
+
onCancel: () => {
|
|
133
|
+
toolInvocations.abort();
|
|
134
|
+
commands.cancel().catch(() => {});
|
|
135
|
+
},
|
|
136
|
+
onResume: () => {
|
|
137
|
+
if (!options.resumeApi) throw new Error("Must pass resumeApi to options to resume runs");
|
|
138
|
+
commands.resume().catch(() => {});
|
|
139
|
+
},
|
|
140
|
+
onAddToolResult: (toolOptions) => {
|
|
141
|
+
const command_2 = {
|
|
142
|
+
type: "add-tool-result",
|
|
143
|
+
toolCallId: toolOptions.toolCallId,
|
|
144
|
+
result: toolOptions.result,
|
|
145
|
+
toolName: toolOptions.toolName,
|
|
146
|
+
isError: toolOptions.isError,
|
|
147
|
+
...toolOptions.artifact && { artifact: toolOptions.artifact },
|
|
148
|
+
...toolOptions.modelContent !== void 0 && { modelContent: toolOptions.modelContent }
|
|
149
|
+
};
|
|
150
|
+
dispatch(command_2);
|
|
151
|
+
},
|
|
152
|
+
onResumeToolCall: ({ toolCallId, payload }) => {
|
|
153
|
+
if (!toolInvocations.resume(toolCallId, payload)) throw new Error(`Tool call ${toolCallId} is not waiting for resume.`);
|
|
154
|
+
},
|
|
155
|
+
onLoadExternalState: (imported) => {
|
|
156
|
+
commands.importState(imported).catch(() => {});
|
|
157
|
+
convertedRef.current = options.converter(imported, {
|
|
158
|
+
pendingCommands: [...queue.inTransit, ...queue.queued],
|
|
159
|
+
isSending,
|
|
160
|
+
toolStatuses: EMPTY_TOOL_STATUSES
|
|
161
|
+
});
|
|
162
|
+
toolInvocations.reset();
|
|
163
|
+
setToolStatuses(EMPTY_TOOL_STATUSES);
|
|
164
|
+
}
|
|
165
|
+
}));
|
|
166
|
+
};
|
|
167
|
+
const AssistantTransportThread = (options) => resource(useAssistantTransportThread)(options);
|
|
168
|
+
forwardTransformScopes(useAssistantTransportThread, ExternalThread(void 0).hook);
|
|
169
|
+
//#endregion
|
|
170
|
+
export { AssistantTransportThread, asAssistantTransportExtras, symbolAssistantTransportExtras };
|
|
171
|
+
|
|
172
|
+
//# sourceMappingURL=AssistantTransportThread.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"AssistantTransportThread.js","names":["useEffect","useMemo","useRef","useState","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","AddToolResultOptions","AppendMessage","ResumeToolCallOptions","ThreadMessage","ToolExecutionStatus","ToolInvocationTracker","ReadonlyJSONObject","useStatewire","AssistantTransportHost","AssistantTransportHostCommands","AssistantTransportHostState","HostQueueCell","HostRunContext","SendOptions","AddMessageCommand","AddToolResultCommand","AssistantTransportCommand","AssistantTransportOptions","UserMessagePart","EMPTY_TOOL_STATUSES","Record","symbolAssistantTransportExtras","Symbol","AssistantTransportExtras","sendCommand","command","state","asAssistantTransportExtras","extras","Error","convertAppendMessageToCommand","message","role","parts","content","attachments","flatMap","a","contentPart","type","push","text","image","length","parentId","sourceId","messagesContainToolCall","messages","toolCallId","some","part","undefined","useAssistantTransportThread","options","clientRef","getRunContext","aui","current","parent","threadId","threadListItem","getState","remoteId","modelContext","getModelContext","queueCell","queued","inTransit","commands","transport","agent","agentState","isSending","isReplaying","queue","dispatch","opts","send","catch","toolStatuses","setToolStatuses","converted","converter","pendingCommands","convertedRef","toolInvocations","tools","onResult","onStatusesChange","statuses","size","Object","fromEntries","setState","isRunning","isLoading","reset","handleAppend","startRun","setParentId","schedule","abort","then","attachmentAdapter","adapters","onNew","capabilities","edit","onEdit","onReload","reload","onCancel","cancel","onResume","resumeApi","resume","onAddToolResult","toolOptions","result","toolName","isError","artifact","modelContent","onResumeToolCall","payload","onLoadExternalState","imported","importState","AssistantTransportThread","T","hook"],"sources":["../src/AssistantTransportThread.ts"],"sourcesContent":["import { useEffect, useMemo, useRef, useState } from \"react\";\nimport { resource, useResource } from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/react\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/react\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n ResumeToolCallOptions,\n ThreadMessage,\n ToolExecutionStatus,\n} from \"@assistant-ui/core\";\nimport { ToolInvocationTracker } from \"@assistant-ui/core/internal\";\nimport type { ReadonlyJSONObject } from \"assistant-stream/utils\";\nimport { useStatewire } from \"statewire\";\nimport { AssistantTransportHost } from \"./host\";\nimport type {\n AssistantTransportHostCommands,\n AssistantTransportHostState,\n HostQueueCell,\n HostRunContext,\n SendOptions,\n} from \"./host\";\nimport type {\n AddMessageCommand,\n AddToolResultCommand,\n AssistantTransportCommand,\n AssistantTransportOptions,\n UserMessagePart,\n} from \"./types\";\n\nconst EMPTY_TOOL_STATUSES: Record<string, ToolExecutionStatus> = {};\n\nexport const symbolAssistantTransportExtras = Symbol(\n \"assistant-transport-extras\",\n);\n\nexport type AssistantTransportExtras = {\n [symbolAssistantTransportExtras]: true;\n sendCommand: (command: AssistantTransportCommand) => void;\n state: unknown;\n};\n\nexport const asAssistantTransportExtras = (\n extras: unknown,\n): AssistantTransportExtras => {\n if (\n typeof extras !== \"object\" ||\n extras == null ||\n !(symbolAssistantTransportExtras in extras)\n )\n throw new Error(\n \"This method can only be called when you are using AssistantTransportThread\",\n );\n\n return extras as AssistantTransportExtras;\n};\n\nconst convertAppendMessageToCommand = (\n message: AppendMessage,\n): AddMessageCommand | null => {\n if (message.role !== \"user\")\n throw new Error(\"Only user messages are supported\");\n\n const parts: UserMessagePart[] = [];\n const content = [\n ...message.content,\n ...(message.attachments?.flatMap((a) => a.content) ?? []),\n ];\n for (const contentPart of content) {\n if (contentPart.type === \"text\") {\n parts.push({ type: \"text\", text: contentPart.text });\n } else if (contentPart.type === \"image\") {\n parts.push({ type: \"image\", image: contentPart.image });\n }\n }\n\n if (parts.length === 0) return null;\n\n return {\n type: \"add-message\",\n message: {\n role: \"user\",\n parts,\n },\n parentId: message.parentId,\n sourceId: message.sourceId,\n };\n};\n\nconst messagesContainToolCall = (\n messages: readonly ThreadMessage[],\n toolCallId: string,\n): boolean =>\n messages.some((message) =>\n message.content.some(\n (part) =>\n part.type === \"tool-call\" &&\n (part.toolCallId === toolCallId ||\n (part.messages !== undefined &&\n messagesContainToolCall(part.messages, toolCallId))),\n ),\n );\n\nconst useAssistantTransportThread = (\n options: AssistantTransportOptions<any>,\n): ClientOutput<\"thread\"> => {\n const clientRef = useAssistantClientRef();\n const [getRunContext] = useState(() => (): HostRunContext => {\n const aui = clientRef.current ?? clientRef.parent;\n // legacy parity: a threadListItem throw must not kill the run\n let threadId: string | null = null;\n try {\n threadId = aui.threadListItem().getState().remoteId ?? null;\n } catch {}\n return {\n modelContext: aui.modelContext().getModelContext(),\n threadId,\n };\n });\n\n const [queueCell] = useState(\n (): HostQueueCell => ({ current: { queued: [], inTransit: [] } }),\n );\n const { state, commands } = useStatewire<\n AssistantTransportHostState,\n AssistantTransportHostCommands\n >({\n transport: AssistantTransportHost({ ...options, getRunContext, queueCell }),\n });\n const { agent: agentState, isSending, isReplaying } = state;\n const queue = queueCell.current;\n\n // the commands proxy is identity-stable across renders\n const dispatch = (command: AssistantTransportCommand, opts?: SendOptions) => {\n void commands.send(command, opts).catch(() => {});\n };\n\n const [toolStatuses, setToolStatuses] =\n useState<Record<string, ToolExecutionStatus>>(EMPTY_TOOL_STATUSES);\n\n const converted = useMemo(\n () =>\n options.converter(agentState, {\n pendingCommands: [...queue.inTransit, ...queue.queued],\n isSending,\n toolStatuses,\n }),\n [options.converter, agentState, queue, isSending, toolStatuses],\n );\n const convertedRef = useRef(converted);\n convertedRef.current = converted;\n\n const [toolInvocations] = useState(\n () =>\n new ToolInvocationTracker(\n () => {\n const aui = clientRef.current ?? clientRef.parent;\n return aui.modelContext().getModelContext().tools;\n },\n {\n onResult: (command) => {\n const messages = convertedRef.current\n .messages as readonly ThreadMessage[];\n if (!messagesContainToolCall(messages, command.toolCallId)) return;\n dispatch(command);\n },\n onStatusesChange: (statuses) => {\n setToolStatuses(\n statuses.size === 0\n ? EMPTY_TOOL_STATUSES\n : Object.fromEntries(statuses),\n );\n },\n },\n ),\n );\n // dep-less by design: setState dedups identical snapshots internally\n useEffect(() => {\n toolInvocations.setState({\n messages: converted.messages as readonly ThreadMessage[],\n isRunning: converted.isRunning,\n isLoading: isReplaying,\n });\n });\n useEffect(\n () => () => {\n toolInvocations.reset();\n },\n [toolInvocations],\n );\n\n const extras = useMemo(\n (): AssistantTransportExtras => ({\n [symbolAssistantTransportExtras]: true,\n sendCommand: dispatch,\n state: agentState,\n }),\n [commands, agentState],\n );\n\n const handleAppend = (message: AppendMessage) => {\n const startRun = message.startRun ?? message.role === \"user\";\n const command = convertAppendMessageToCommand(message);\n void commands.setParentId(message.parentId).catch(() => {});\n\n const send = () => {\n if (!command) return;\n dispatch(command, { schedule: startRun });\n };\n if (startRun) {\n // abort in-flight tool executions so their late results cannot race the new turn\n void toolInvocations.abort().then(send);\n } else {\n send();\n }\n };\n\n return useResource(\n ExternalThread({\n messages: converted.messages as readonly ExternalThreadMessage[],\n isRunning: converted.isRunning,\n isLoading: isReplaying,\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n onNew: handleAppend,\n ...(options.capabilities?.edit && { onEdit: handleAppend }),\n ...(queue.queued.length > 0 && {\n onReload: (parentId: string | null) => {\n void toolInvocations.abort().then(() => {\n void commands.reload(parentId).catch(() => {});\n });\n },\n }),\n onCancel: () => {\n void toolInvocations.abort();\n void commands.cancel().catch(() => {});\n },\n onResume: () => {\n if (!options.resumeApi)\n throw new Error(\"Must pass resumeApi to options to resume runs\");\n void commands.resume().catch(() => {});\n },\n onAddToolResult: (toolOptions: AddToolResultOptions) => {\n const command: AddToolResultCommand = {\n type: \"add-tool-result\",\n toolCallId: toolOptions.toolCallId,\n result: toolOptions.result as ReadonlyJSONObject,\n toolName: toolOptions.toolName,\n isError: toolOptions.isError,\n ...(toolOptions.artifact && { artifact: toolOptions.artifact }),\n ...(toolOptions.modelContent !== undefined && {\n modelContent: toolOptions.modelContent,\n }),\n };\n\n dispatch(command);\n },\n onResumeToolCall: ({ toolCallId, payload }: ResumeToolCallOptions) => {\n if (!toolInvocations.resume(toolCallId, payload))\n throw new Error(`Tool call ${toolCallId} is not waiting for resume.`);\n },\n onLoadExternalState: (imported: unknown) => {\n void commands.importState(imported).catch(() => {});\n // reset() aborts tools before React re-renders — gate their late results against the imported state\n convertedRef.current = options.converter(imported, {\n pendingCommands: [...queue.inTransit, ...queue.queued],\n isSending,\n toolStatuses: EMPTY_TOOL_STATUSES,\n });\n toolInvocations.reset();\n setToolStatuses(EMPTY_TOOL_STATUSES);\n },\n }),\n );\n};\n\nexport const AssistantTransportThread = <T>(\n options: AssistantTransportOptions<T>,\n): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useAssistantTransportThread)(\n options as AssistantTransportOptions<any>,\n );\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useAssistantTransportThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;AAoCA,MAAM+B,sBAA2D,CAAC;AAElE,MAAaE,iCAAiCC,OAC5C,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AC,CAACrC,YAAY,CAAC,CAAC;EACvC;EACAsC,kBAAkBC,gBAAsC;GACtD,MAAM5F,YAAgC;IACpCc,MAAM;IACNS,YAAYqE,YAAYrE;IACxBsE,QAAQD,YAAYC;IACpBC,UAAUF,YAAYE;IACtBC,SAASH,YAAYG;IACrB,GAAIH,YAAYI,YAAY,EAAEA,UAAUJ,YAAYI,SAAS;IAC7D,GAAIJ,YAAYK,iBAAiBvE,KAAAA,KAAa,EAC5CuE,cAAcL,YAAYK,aAC5B;GACF;GAEA/C,SAASlD,SAAO;EAClB;EACAkG,mBAAmB,EAAE3E,YAAY4E,cAAqC;GACpE,IAAI,CAACvC,gBAAgB8B,OAAOnE,YAAY4E,OAAO,GAC7C,MAAM,IAAI/F,MAAM,aAAamB,WAAU,4BAA6B;EACxE;EACA6E,sBAAsBC,aAAsB;GAC1C,SAAcC,YAAYD,QAAQ,CAAC,CAAChD,YAAY,CAAC,CAAC;GAElDM,aAAa3B,UAAUJ,QAAQ6B,UAAU4C,UAAU;IACjD3C,iBAAiB,CAAC,GAAGT,MAAMP,WAAW,GAAGO,MAAMR,MAAM;IACrDM;IACAO,cAAc5D;GAChB,CAAC;GACDkE,gBAAgBW,MAAM;GACtBhB,gBAAgB7D,mBAAmB;EACrC;CACF,CAAC,CACH;AACF;AAEA,MAAa6G,4BACX3E,YAEA7D,SAAS4D,2BAA2B,CAAC,CACnCC,OACF;AAGFxD,uBACEuD,6BACAzD,eAAewD,KAAAA,CAAkB,CAAC,CAAC+E,IACrC"}
|
package/dist/hooks.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { AssistantTransportCommand, UserExternalState } from "./types.js";
|
|
2
|
+
//#region src/hooks.d.ts
|
|
3
|
+
declare const useAssistantTransportSendCommand: () => (command: AssistantTransportCommand) => void;
|
|
4
|
+
declare function useAssistantTransportState(): UserExternalState;
|
|
5
|
+
declare function useAssistantTransportState<T>(selector: (state: UserExternalState) => T): T;
|
|
6
|
+
//#endregion
|
|
7
|
+
export { useAssistantTransportSendCommand, useAssistantTransportState };
|
|
8
|
+
//# sourceMappingURL=hooks.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hooks.d.ts","names":[],"sources":["../src/hooks.ts"],"mappings":";;cAMa,yCAGH,SAAS;iBAMH,8BAA8B;iBAC9B,2BAA2B,GACzC,WAAW,OAAO,sBAAsB,IACvC"}
|
package/dist/hooks.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { asAssistantTransportExtras } from "./AssistantTransportThread.js";
|
|
3
|
+
import { useAui, useAuiState } from "@assistant-ui/store";
|
|
4
|
+
import { c } from "@assistant-ui/tap/react-shim/compiler-runtime";
|
|
5
|
+
//#region src/hooks.ts
|
|
6
|
+
const useAssistantTransportSendCommand = () => {
|
|
7
|
+
const $ = c(2);
|
|
8
|
+
const aui = useAui();
|
|
9
|
+
let t0;
|
|
10
|
+
if ($[0] !== aui) {
|
|
11
|
+
t0 = (command) => {
|
|
12
|
+
const extras = aui.thread().getState().extras;
|
|
13
|
+
asAssistantTransportExtras(extras).sendCommand(command);
|
|
14
|
+
};
|
|
15
|
+
$[0] = aui;
|
|
16
|
+
$[1] = t0;
|
|
17
|
+
} else t0 = $[1];
|
|
18
|
+
return t0;
|
|
19
|
+
};
|
|
20
|
+
function useAssistantTransportState(selector = (t) => t) {
|
|
21
|
+
return useAuiState((s) => selector(asAssistantTransportExtras(s.thread.extras).state));
|
|
22
|
+
}
|
|
23
|
+
//#endregion
|
|
24
|
+
export { useAssistantTransportSendCommand, useAssistantTransportState };
|
|
25
|
+
|
|
26
|
+
//# sourceMappingURL=hooks.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hooks.js","names":["c","_c","useAui","useAuiState","asAssistantTransportExtras","AssistantTransportCommand","UserExternalState","useAssistantTransportSendCommand","$","aui","t0","command","extras","thread","getState","sendCommand","useAssistantTransportState","selector","state","T","t","s"],"sources":["../src/hooks.ts"],"sourcesContent":["\"use client\";\n\nimport { useAui, useAuiState } from \"@assistant-ui/store\";\nimport { asAssistantTransportExtras } from \"./AssistantTransportThread\";\nimport type { AssistantTransportCommand, UserExternalState } from \"./types\";\n\nexport const useAssistantTransportSendCommand = () => {\n const aui = useAui();\n\n return (command: AssistantTransportCommand) => {\n const extras = aui.thread().getState().extras;\n asAssistantTransportExtras(extras).sendCommand(command);\n };\n};\n\nexport function useAssistantTransportState(): UserExternalState;\nexport function useAssistantTransportState<T>(\n selector: (state: UserExternalState) => T,\n): T;\nexport function useAssistantTransportState<T>(\n selector: (state: UserExternalState) => T = (t) => t as T,\n): T | UserExternalState {\n return useAuiState((s) =>\n selector(\n asAssistantTransportExtras(s.thread.extras).state as UserExternalState,\n ),\n );\n}\n"],"mappings":";;;;;AAMA,MAAaO,yCAAmC;CAAA,MAAAC,IAAAP,EAAA,CAAA;CAC9C,MAAAQ,MAAYP,OAAO;CAAE,IAAAQ;CAAA,IAAAF,EAAA,OAAAC,KAAA;EAEdC,MAAAC,YAAA;GACL,MAAAC,SAAeH,IAAGI,OAAQ,CAAC,CAAAC,SAAU,CAAC,CAAAF;GACtCR,2BAA2BQ,MAAM,CAAC,CAAAG,YAAaJ,OAAO;EAAC;EACxDH,EAAA,KAAAC;EAAAD,EAAA,KAAAE;CAAA,OAAAA,KAAAF,EAAA;CAAA,OAHME;AAGN;AAOH,SAAgBM,2BACdC,YAA6CG,MAAMA,GAC5B;CACvB,OAAOjB,aAAakB,MAClBJ,SACEb,2BAA2BiB,EAAER,OAAOD,MAAM,CAAC,CAACM,KAC9C,CACF;AACF"}
|
package/dist/host.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { AssistantTransportCommand, AssistantTransportOptions } from "./types.js";
|
|
2
|
+
import { ResourceElement } from "@assistant-ui/tap";
|
|
3
|
+
import { ModelContext } from "@assistant-ui/core";
|
|
4
|
+
import { StatewireServer } from "statewire/server";
|
|
5
|
+
//#region src/host.d.ts
|
|
6
|
+
type SendOptions = {
|
|
7
|
+
schedule?: boolean;
|
|
8
|
+
};
|
|
9
|
+
type HostRunContext = {
|
|
10
|
+
modelContext: ModelContext;
|
|
11
|
+
threadId: string | null;
|
|
12
|
+
};
|
|
13
|
+
type HostQueue = {
|
|
14
|
+
queued: AssistantTransportCommand[];
|
|
15
|
+
inTransit: AssistantTransportCommand[];
|
|
16
|
+
};
|
|
17
|
+
type HostQueueCell = {
|
|
18
|
+
current: HostQueue;
|
|
19
|
+
};
|
|
20
|
+
type HostOptions = AssistantTransportOptions<unknown> & {
|
|
21
|
+
getRunContext: () => HostRunContext;
|
|
22
|
+
queueCell: HostQueueCell;
|
|
23
|
+
};
|
|
24
|
+
type AssistantTransportHostState = {
|
|
25
|
+
agent: unknown;
|
|
26
|
+
queueVersion: number;
|
|
27
|
+
isSending: boolean;
|
|
28
|
+
isReplaying: boolean;
|
|
29
|
+
};
|
|
30
|
+
type AssistantTransportHostCommands = {
|
|
31
|
+
send(command: AssistantTransportCommand, opts?: SendOptions): void;
|
|
32
|
+
setParentId(parentId: string | null): void;
|
|
33
|
+
cancel(): void;
|
|
34
|
+
resume(): void;
|
|
35
|
+
reload(parentId: string | null): void;
|
|
36
|
+
importState(state: unknown): void;
|
|
37
|
+
};
|
|
38
|
+
declare const AssistantTransportHost: (options: HostOptions) => ResourceElement<StatewireServer.Transport<AssistantTransportHostState, AssistantTransportHostCommands>>;
|
|
39
|
+
//#endregion
|
|
40
|
+
export { AssistantTransportHost, AssistantTransportHostCommands, AssistantTransportHostState, HostOptions, HostQueue, HostQueueCell, HostRunContext, SendOptions };
|
|
41
|
+
//# sourceMappingURL=host.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"host.d.ts","names":[],"sources":["../src/host.ts"],"mappings":";;;;;KA6BY;EACV;;KAGU;EACV,cAAc;EACd;;KAGU;EACV,QAAQ;EACR,WAAW;;KAMD;EAAkB,SAAS;;KAE3B,cAAc;EACxB,qBAAqB;EACrB,WAAW;;KAGD;EACV;EACA;EACA;EACA;;KAGU;EACV,KAAK,SAAS,2BAA2B,OAAO;EAChD,YAAY;EACZ;EACA;EACA,OAAO;EACP,YAAY;;cAmVD,yBACX,SAAS,gBACN,gBACH,gBAAgB,UACd,6BACA"}
|
package/dist/host.js
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
import { createReplayBoundaryStream } from "./replayBoundaryStream.js";
|
|
2
|
+
import { translateStateOp } from "./stateOps.js";
|
|
3
|
+
import { useEffect, useRef, useState } from "@assistant-ui/tap/react-shim";
|
|
4
|
+
import { resource } from "@assistant-ui/tap";
|
|
5
|
+
import { applyOps } from "statewire";
|
|
6
|
+
import { createRequestHeaders } from "@assistant-ui/core";
|
|
7
|
+
import { AssistantTransportDecoder, DataStreamDecoder, toToolsJSONSchema } from "assistant-stream";
|
|
8
|
+
import { asAsyncIterableStream } from "assistant-stream/utils";
|
|
9
|
+
import { CommandExecution, useStatewireCommands, useStatewireEmit, useStatewireState } from "statewire/server";
|
|
10
|
+
//#region src/host.ts
|
|
11
|
+
const commandsOf = (entries) => entries.map((e) => e.command);
|
|
12
|
+
const createHostLoop = (getOptions, ctl) => {
|
|
13
|
+
let agent = getOptions().initialState;
|
|
14
|
+
let queue = {
|
|
15
|
+
queued: [],
|
|
16
|
+
inTransit: []
|
|
17
|
+
};
|
|
18
|
+
let activeEntries = [];
|
|
19
|
+
let parentId;
|
|
20
|
+
let resumeRequested = false;
|
|
21
|
+
let followUpRequested = false;
|
|
22
|
+
let isReplaying = false;
|
|
23
|
+
let disposed = false;
|
|
24
|
+
let abortController = null;
|
|
25
|
+
const setReplaying = (value) => {
|
|
26
|
+
if (isReplaying === value) return;
|
|
27
|
+
isReplaying = value;
|
|
28
|
+
ctl.apply([{
|
|
29
|
+
op: "replace",
|
|
30
|
+
path: ["isReplaying"],
|
|
31
|
+
value
|
|
32
|
+
}]);
|
|
33
|
+
};
|
|
34
|
+
const setSending = (value) => {
|
|
35
|
+
ctl.apply([{
|
|
36
|
+
op: "replace",
|
|
37
|
+
path: ["isSending"],
|
|
38
|
+
value
|
|
39
|
+
}]);
|
|
40
|
+
};
|
|
41
|
+
const replaceAgent = (next) => {
|
|
42
|
+
agent = next;
|
|
43
|
+
ctl.apply([{
|
|
44
|
+
op: "replace",
|
|
45
|
+
path: ["agent"],
|
|
46
|
+
value: next
|
|
47
|
+
}]);
|
|
48
|
+
};
|
|
49
|
+
const updateState = (updater) => {
|
|
50
|
+
replaceAgent(updater(agent));
|
|
51
|
+
};
|
|
52
|
+
const applyChunkOps = (operations) => {
|
|
53
|
+
let next = agent;
|
|
54
|
+
const translated = [];
|
|
55
|
+
for (const operation of operations) {
|
|
56
|
+
const op = translateStateOp(next, operation);
|
|
57
|
+
next = applyOps(next, [op]).state;
|
|
58
|
+
translated.push({
|
|
59
|
+
...op,
|
|
60
|
+
path: ["agent", ...op.path]
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
agent = next;
|
|
64
|
+
ctl.apply(translated);
|
|
65
|
+
};
|
|
66
|
+
let queueVersion = 0;
|
|
67
|
+
const setQueue = (next) => {
|
|
68
|
+
queue = next;
|
|
69
|
+
getOptions().queueCell.current = {
|
|
70
|
+
queued: commandsOf(next.queued),
|
|
71
|
+
inTransit: commandsOf(next.inTransit)
|
|
72
|
+
};
|
|
73
|
+
ctl.apply([{
|
|
74
|
+
op: "replace",
|
|
75
|
+
path: ["queueVersion"],
|
|
76
|
+
value: ++queueVersion
|
|
77
|
+
}]);
|
|
78
|
+
};
|
|
79
|
+
const takeQueuedIntoTransit = () => {
|
|
80
|
+
const { queued, inTransit } = queue;
|
|
81
|
+
if (queued.length === 0) return [];
|
|
82
|
+
setQueue({
|
|
83
|
+
queued: [],
|
|
84
|
+
inTransit: [...inTransit, ...queued]
|
|
85
|
+
});
|
|
86
|
+
return queued;
|
|
87
|
+
};
|
|
88
|
+
const drainQueue = () => {
|
|
89
|
+
const drained = queue;
|
|
90
|
+
setQueue({
|
|
91
|
+
queued: [],
|
|
92
|
+
inTransit: []
|
|
93
|
+
});
|
|
94
|
+
return drained;
|
|
95
|
+
};
|
|
96
|
+
const buildRequestBody = async (o, commands) => {
|
|
97
|
+
const runParentId = parentId;
|
|
98
|
+
parentId = void 0;
|
|
99
|
+
const bodyValue = typeof o.body === "function" ? await o.body() : o.body;
|
|
100
|
+
const { modelContext, threadId } = o.getRunContext();
|
|
101
|
+
const requestBody = {
|
|
102
|
+
commands,
|
|
103
|
+
state: agent,
|
|
104
|
+
system: modelContext.system,
|
|
105
|
+
tools: modelContext.tools ? toToolsJSONSchema(modelContext.tools) : void 0,
|
|
106
|
+
threadId,
|
|
107
|
+
...runParentId !== void 0 && { parentId: runParentId },
|
|
108
|
+
callSettings: modelContext.callSettings,
|
|
109
|
+
config: modelContext.config,
|
|
110
|
+
...modelContext.callSettings,
|
|
111
|
+
...modelContext.config,
|
|
112
|
+
...bodyValue ?? {}
|
|
113
|
+
};
|
|
114
|
+
if (!o.prepareSendCommandsRequest) return requestBody;
|
|
115
|
+
return o.prepareSendCommandsRequest(requestBody);
|
|
116
|
+
};
|
|
117
|
+
const run = async (signal) => {
|
|
118
|
+
const o = getOptions();
|
|
119
|
+
const isResume = resumeRequested;
|
|
120
|
+
resumeRequested = false;
|
|
121
|
+
setReplaying(false);
|
|
122
|
+
activeEntries = isResume ? [] : takeQueuedIntoTransit();
|
|
123
|
+
if (activeEntries.length === 0 && !isResume) return;
|
|
124
|
+
const headers = await createRequestHeaders(o.headers);
|
|
125
|
+
const requestBody = await buildRequestBody(o, commandsOf(activeEntries));
|
|
126
|
+
const response = await fetch(isResume ? o.resumeApi : o.api, {
|
|
127
|
+
method: "POST",
|
|
128
|
+
headers,
|
|
129
|
+
body: JSON.stringify(requestBody),
|
|
130
|
+
signal
|
|
131
|
+
});
|
|
132
|
+
o.onResponse?.(response);
|
|
133
|
+
if (!response.ok) throw new Error(`Status ${response.status}: ${await response.text()}`);
|
|
134
|
+
if (!response.body) throw new Error("Response body is null");
|
|
135
|
+
const body = await createReplayBoundaryStream(response, setReplaying);
|
|
136
|
+
const decoder = (o.protocol ?? "data-stream") === "assistant-transport" ? new AssistantTransportDecoder() : new DataStreamDecoder();
|
|
137
|
+
let streamError;
|
|
138
|
+
let delivered = false;
|
|
139
|
+
const markDelivered = () => {
|
|
140
|
+
for (const entry of activeEntries) entry.execution.ack();
|
|
141
|
+
setQueue({
|
|
142
|
+
...queue,
|
|
143
|
+
inTransit: []
|
|
144
|
+
});
|
|
145
|
+
delivered = true;
|
|
146
|
+
};
|
|
147
|
+
const chunks = body.pipeThrough(decoder);
|
|
148
|
+
for await (const chunk of asAsyncIterableStream(chunks)) {
|
|
149
|
+
if (chunk.type === "error") {
|
|
150
|
+
streamError = chunk.error;
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
if (chunk.type !== "update-state" || chunk.operations.length === 0) continue;
|
|
154
|
+
applyChunkOps(chunk.operations);
|
|
155
|
+
if (!delivered) markDelivered();
|
|
156
|
+
}
|
|
157
|
+
if (streamError) throw new Error(streamError);
|
|
158
|
+
if (!delivered) markDelivered();
|
|
159
|
+
if (isResume && queue.queued.length > 0) followUpRequested = true;
|
|
160
|
+
};
|
|
161
|
+
const resolveActive = () => {
|
|
162
|
+
for (const entry of activeEntries.splice(0)) entry.execution.resolve();
|
|
163
|
+
};
|
|
164
|
+
const settleCancelled = () => {
|
|
165
|
+
setReplaying(false);
|
|
166
|
+
const { queued, inTransit } = drainQueue();
|
|
167
|
+
resolveActive();
|
|
168
|
+
for (const entry of [...inTransit, ...queued]) entry.execution.resolve();
|
|
169
|
+
getOptions().onCancel?.({
|
|
170
|
+
commands: commandsOf([...inTransit, ...queued]),
|
|
171
|
+
updateState
|
|
172
|
+
});
|
|
173
|
+
};
|
|
174
|
+
const settleFailed = async (error) => {
|
|
175
|
+
setReplaying(false);
|
|
176
|
+
const { queued, inTransit } = drainQueue();
|
|
177
|
+
for (const entry of inTransit) entry.execution.reject(error);
|
|
178
|
+
resolveActive();
|
|
179
|
+
try {
|
|
180
|
+
await getOptions().onError?.(error, {
|
|
181
|
+
commands: commandsOf(inTransit),
|
|
182
|
+
updateState
|
|
183
|
+
});
|
|
184
|
+
} finally {
|
|
185
|
+
getOptions().onCancel?.({
|
|
186
|
+
commands: commandsOf(queued),
|
|
187
|
+
updateState,
|
|
188
|
+
error
|
|
189
|
+
});
|
|
190
|
+
for (const entry of queued) entry.execution.resolve();
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
const startRun = () => {
|
|
194
|
+
followUpRequested = false;
|
|
195
|
+
const ac = new AbortController();
|
|
196
|
+
abortController = ac;
|
|
197
|
+
setSending(true);
|
|
198
|
+
setTimeout(async () => {
|
|
199
|
+
try {
|
|
200
|
+
await run(ac.signal);
|
|
201
|
+
resolveActive();
|
|
202
|
+
} catch (error) {
|
|
203
|
+
followUpRequested = false;
|
|
204
|
+
if (!disposed) if (ac.signal.aborted) settleCancelled();
|
|
205
|
+
else await settleFailed(error);
|
|
206
|
+
} finally {
|
|
207
|
+
if (disposed) abortController = null;
|
|
208
|
+
else {
|
|
209
|
+
getOptions().onFinish?.();
|
|
210
|
+
if (followUpRequested) startRun();
|
|
211
|
+
else {
|
|
212
|
+
abortController = null;
|
|
213
|
+
setSending(false);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
}, 0);
|
|
218
|
+
};
|
|
219
|
+
const schedule = () => {
|
|
220
|
+
if (abortController) {
|
|
221
|
+
followUpRequested = true;
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
startRun();
|
|
225
|
+
};
|
|
226
|
+
return {
|
|
227
|
+
handlers: {
|
|
228
|
+
send: (command, opts) => {
|
|
229
|
+
const [execution, resolvers] = CommandExecution.withResolvers();
|
|
230
|
+
setQueue({
|
|
231
|
+
queued: [...queue.queued, {
|
|
232
|
+
command,
|
|
233
|
+
execution: resolvers
|
|
234
|
+
}],
|
|
235
|
+
inTransit: queue.inTransit
|
|
236
|
+
});
|
|
237
|
+
if (opts?.schedule !== false) schedule();
|
|
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
|
|
258
|
+
},
|
|
259
|
+
arm: () => {
|
|
260
|
+
disposed = false;
|
|
261
|
+
},
|
|
262
|
+
dispose: () => {
|
|
263
|
+
disposed = true;
|
|
264
|
+
followUpRequested = false;
|
|
265
|
+
abortController?.abort();
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
};
|
|
269
|
+
const useAssistantTransportHost = (options) => {
|
|
270
|
+
const latestOptions = useRef(options);
|
|
271
|
+
latestOptions.current = options;
|
|
272
|
+
const [state, ctl] = useStatewireState(() => ({
|
|
273
|
+
agent: options.initialState,
|
|
274
|
+
queueVersion: 0,
|
|
275
|
+
isSending: false,
|
|
276
|
+
isReplaying: false
|
|
277
|
+
}));
|
|
278
|
+
const emit = useStatewireEmit();
|
|
279
|
+
const [loop] = useState(() => createHostLoop(() => latestOptions.current, ctl));
|
|
280
|
+
useEffect(() => {
|
|
281
|
+
loop.arm();
|
|
282
|
+
return loop.dispose;
|
|
283
|
+
}, [loop]);
|
|
284
|
+
return {
|
|
285
|
+
state,
|
|
286
|
+
commands: useStatewireCommands(loop.handlers),
|
|
287
|
+
emit
|
|
288
|
+
};
|
|
289
|
+
};
|
|
290
|
+
const AssistantTransportHost = resource(useAssistantTransportHost);
|
|
291
|
+
//#endregion
|
|
292
|
+
export { AssistantTransportHost };
|
|
293
|
+
|
|
294
|
+
//# sourceMappingURL=host.js.map
|