@assistant-ui/react-statewire 0.1.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/AssistantTransportThread.d.ts +4 -4
- package/dist/AssistantTransportThread.d.ts.map +1 -1
- package/dist/AssistantTransportThread.js +65 -45
- package/dist/AssistantTransportThread.js.map +1 -1
- package/dist/StatewireThread.d.ts +122 -10
- package/dist/StatewireThread.d.ts.map +1 -1
- package/dist/StatewireThread.js +90 -38
- package/dist/StatewireThread.js.map +1 -1
- package/dist/host.d.ts +0 -1
- package/dist/host.d.ts.map +1 -1
- package/dist/host.js +20 -12
- package/dist/host.js.map +1 -1
- package/dist/index.d.ts +21 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/inputRequests.d.ts +14 -0
- package/dist/inputRequests.d.ts.map +1 -0
- package/dist/inputRequests.js +35 -0
- package/dist/inputRequests.js.map +1 -0
- package/dist/runCommands.d.ts +22 -0
- package/dist/runCommands.d.ts.map +1 -0
- package/dist/runCommands.js +105 -0
- package/dist/runCommands.js.map +1 -0
- package/dist/types.d.ts +114 -17
- package/dist/types.d.ts.map +1 -1
- package/package.json +4 -4
- package/src/AssistantTransportThread.ts +120 -50
- package/src/StatewireThread.test.tsx +587 -61
- package/src/StatewireThread.ts +310 -47
- package/src/__tests__/testHelpers.tsx +1 -1
- package/src/athena.e2e.test.tsx +34 -25
- package/src/host.ts +23 -11
- package/src/index.ts +20 -4
- package/src/inputRequests.ts +57 -0
- package/src/legacy-diff.test.tsx +32 -8
- package/src/runCommands.ts +146 -0
- package/src/transport.test.tsx +581 -57
- package/src/types.ts +133 -19
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { AssistantTransportCommand, AssistantTransportOptions, InputRequestState } from "./types.js";
|
|
2
2
|
import { ResourceElement } from "@assistant-ui/tap";
|
|
3
3
|
import { ClientOutput } from "@assistant-ui/store";
|
|
4
|
-
import { AppendMessage } from "@assistant-ui/core";
|
|
5
4
|
//#region src/AssistantTransportThread.d.ts
|
|
6
5
|
declare const symbolAssistantTransportExtras: unique symbol;
|
|
7
6
|
type AssistantTransportExtras = {
|
|
@@ -9,10 +8,11 @@ type AssistantTransportExtras = {
|
|
|
9
8
|
sendCommand: (command: AssistantTransportCommand) => void;
|
|
10
9
|
reconnect: () => void;
|
|
11
10
|
state: unknown;
|
|
11
|
+
/** The host's parked input requests; absent when the converter does not project them. */
|
|
12
|
+
inputRequests?: readonly InputRequestState[];
|
|
12
13
|
};
|
|
13
14
|
declare const asAssistantTransportExtras: (extras: unknown) => AssistantTransportExtras;
|
|
14
|
-
declare const convertAppendMessageToCommand: (message: AppendMessage) => AddMessageCommand | null;
|
|
15
15
|
declare const AssistantTransportThread: <T>(options: AssistantTransportOptions<T>) => ResourceElement<ClientOutput<"thread">>;
|
|
16
16
|
//#endregion
|
|
17
|
-
export { AssistantTransportExtras, AssistantTransportThread, asAssistantTransportExtras,
|
|
17
|
+
export { AssistantTransportExtras, AssistantTransportThread, asAssistantTransportExtras, symbolAssistantTransportExtras };
|
|
18
18
|
//# sourceMappingURL=AssistantTransportThread.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AssistantTransportThread.d.ts","names":[],"sources":["../src/AssistantTransportThread.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"AssistantTransportThread.d.ts","names":[],"sources":["../src/AssistantTransportThread.ts"],"mappings":";;;;cA2Da;KAID;GACT;EACD,cAAc,SAAS;EACvB;EACA;;EAEA,yBAAyB;;cAGd,6BACX,oBACC;cA4VU,2BAA4B,GACvC,SAAS,0BAA0B,OAClC,gBAAgB"}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { AssistantTransportHost } from "./host.js";
|
|
2
|
+
import { createRunQueueAdapter, resolveReloadCommand, toWireMessage } from "./runCommands.js";
|
|
3
|
+
import { resolveToolApprovalInput, resolveToolResultInput } from "./inputRequests.js";
|
|
2
4
|
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "@assistant-ui/tap/react-shim";
|
|
3
5
|
import { resource, useResource } from "@assistant-ui/tap";
|
|
4
6
|
import { ExternalThread } from "@assistant-ui/react";
|
|
@@ -15,29 +17,6 @@ const asAssistantTransportExtras = (extras) => {
|
|
|
15
17
|
if (typeof extras !== "object" || extras == null || !(symbolAssistantTransportExtras in extras)) throw new Error("This method can only be called when you are using AssistantTransportThread or StatewireThread");
|
|
16
18
|
return extras;
|
|
17
19
|
};
|
|
18
|
-
const convertAppendMessageToCommand = (message) => {
|
|
19
|
-
if (message.role !== "user") throw new Error("Only user messages are supported");
|
|
20
|
-
const parts = [];
|
|
21
|
-
const content = [...message.content, ...message.attachments?.flatMap((a) => a.content) ?? []];
|
|
22
|
-
for (const contentPart of content) if (contentPart.type === "text") parts.push({
|
|
23
|
-
type: "text",
|
|
24
|
-
text: contentPart.text
|
|
25
|
-
});
|
|
26
|
-
else if (contentPart.type === "image") parts.push({
|
|
27
|
-
type: "image",
|
|
28
|
-
image: contentPart.image
|
|
29
|
-
});
|
|
30
|
-
if (parts.length === 0) return null;
|
|
31
|
-
return {
|
|
32
|
-
type: "add-message",
|
|
33
|
-
message: {
|
|
34
|
-
role: "user",
|
|
35
|
-
parts
|
|
36
|
-
},
|
|
37
|
-
parentId: message.parentId,
|
|
38
|
-
sourceId: message.sourceId
|
|
39
|
-
};
|
|
40
|
-
};
|
|
41
20
|
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))));
|
|
42
21
|
const useAssistantTransportThread = (options) => {
|
|
43
22
|
const clientRef = useAssistantClientRef();
|
|
@@ -87,7 +66,8 @@ const useAssistantTransportThread = (options) => {
|
|
|
87
66
|
onResult: (command_0) => {
|
|
88
67
|
const messages = convertedRef.current.messages;
|
|
89
68
|
if (!messagesContainToolCall(messages, command_0.toolCallId)) return;
|
|
90
|
-
|
|
69
|
+
const requests = convertedRef.current.inputRequests;
|
|
70
|
+
dispatch((requests && resolveToolResultInput(requests, command_0)) ?? command_0);
|
|
91
71
|
},
|
|
92
72
|
onStatusesChange: (statuses) => {
|
|
93
73
|
setToolStatuses(statuses.size === 0 ? EMPTY_TOOL_STATUSES : Object.fromEntries(statuses));
|
|
@@ -103,51 +83,77 @@ const useAssistantTransportThread = (options) => {
|
|
|
103
83
|
useEffect(() => () => {
|
|
104
84
|
toolInvocations.reset();
|
|
105
85
|
}, [toolInvocations]);
|
|
86
|
+
const inputRequests = converted.inputRequests;
|
|
87
|
+
const [inputSeam] = useState(() => ({ present: inputRequests !== void 0 }));
|
|
88
|
+
if (inputSeam.present !== (inputRequests !== void 0)) throw new Error("statewire: the converter's inputRequests projection must be stable — it was " + (inputSeam.present ? "defined" : "undefined") + " on first convert and changed since");
|
|
106
89
|
const extras = useMemo(() => ({
|
|
107
90
|
[symbolAssistantTransportExtras]: true,
|
|
108
91
|
sendCommand: dispatch,
|
|
109
92
|
reconnect: connection.reconnect,
|
|
110
|
-
state: agentState
|
|
93
|
+
state: agentState,
|
|
94
|
+
...inputRequests !== void 0 && { inputRequests }
|
|
111
95
|
}), [
|
|
112
96
|
dispatch,
|
|
113
97
|
connection.reconnect,
|
|
114
|
-
agentState
|
|
98
|
+
agentState,
|
|
99
|
+
inputRequests
|
|
115
100
|
]);
|
|
116
101
|
const handleAppend = (message) => {
|
|
117
102
|
const startRun = message.startRun ?? message.role === "user";
|
|
118
|
-
const command_1 =
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
if (!command_1) return;
|
|
122
|
-
dispatch(command_1, { schedule: startRun });
|
|
103
|
+
const command_1 = {
|
|
104
|
+
type: "run/steer",
|
|
105
|
+
message: toWireMessage(message, crypto.randomUUID())
|
|
123
106
|
};
|
|
107
|
+
commands.setParentId(message.parentId).catch(() => {});
|
|
108
|
+
const send = () => dispatch(command_1, { schedule: startRun });
|
|
124
109
|
if (startRun) toolInvocations.abort().then(send);
|
|
125
110
|
else send();
|
|
126
111
|
};
|
|
112
|
+
const handleEdit = (message_0) => {
|
|
113
|
+
if (message_0.sourceId == null) throw new Error("statewire: run/edit requires a sourceId");
|
|
114
|
+
const command_2 = {
|
|
115
|
+
type: "run/edit",
|
|
116
|
+
message: toWireMessage(message_0, crypto.randomUUID()),
|
|
117
|
+
sourceId: message_0.sourceId
|
|
118
|
+
};
|
|
119
|
+
toolInvocations.abort().then(() => dispatch(command_2));
|
|
120
|
+
};
|
|
127
121
|
const handleCancel = () => {
|
|
128
122
|
toolInvocations.abort();
|
|
129
123
|
commands.cancel().catch(() => {});
|
|
130
124
|
};
|
|
131
125
|
const driverRef = useRef(void 0);
|
|
132
126
|
driverRef.current = {
|
|
133
|
-
run: (
|
|
134
|
-
...
|
|
127
|
+
run: (message_1) => handleAppend({
|
|
128
|
+
...message_1,
|
|
135
129
|
parentId: convertedRef.current.messages.at(-1)?.id ?? null
|
|
136
130
|
}),
|
|
137
131
|
cancel: handleCancel
|
|
138
132
|
};
|
|
133
|
+
const queueProjection = converted.queue;
|
|
134
|
+
const steerProjection = converted.steerQueue;
|
|
135
|
+
if (steerProjection !== void 0 && queueProjection === void 0) throw new Error("statewire: the converter's steerQueue projection requires the queue projection");
|
|
136
|
+
if (queueProjection !== void 0 && options.capabilities?.queue) throw new Error("statewire: the converter's queue projection excludes capabilities.queue");
|
|
137
|
+
const [queueSeam] = useState(() => ({ present: queueProjection !== void 0 }));
|
|
138
|
+
if (queueSeam.present !== (queueProjection !== void 0)) throw new Error("statewire: the converter's queue projection must be stable — it was " + (queueSeam.present ? "defined" : "undefined") + " on first convert and changed since");
|
|
139
|
+
const serverQueue = useMemo(() => queueProjection ? createRunQueueAdapter(queueProjection, steerProjection, dispatch) : void 0, [
|
|
140
|
+
queueProjection,
|
|
141
|
+
steerProjection,
|
|
142
|
+
dispatch
|
|
143
|
+
]);
|
|
139
144
|
const enableQueue = options.capabilities?.queue === true;
|
|
140
145
|
const queueRef = useRef(null);
|
|
141
146
|
if (enableQueue && !queueRef.current) queueRef.current = createMessageQueue({
|
|
142
|
-
run: (
|
|
147
|
+
run: (message_2, opts_0) => driverRef.current.run(message_2, opts_0),
|
|
143
148
|
cancel: () => driverRef.current.cancel()
|
|
144
149
|
});
|
|
145
150
|
else if (!enableQueue && queueRef.current) {
|
|
146
|
-
queueRef.current.
|
|
151
|
+
queueRef.current.clear();
|
|
147
152
|
queueRef.current = null;
|
|
148
153
|
}
|
|
149
154
|
const messageQueue = queueRef.current;
|
|
150
155
|
const queueItems = useSyncExternalStore(messageQueue?.subscribe ?? subscribeNoop, () => messageQueue?.adapter.items ?? EMPTY_QUEUE_ITEMS, () => EMPTY_QUEUE_ITEMS);
|
|
156
|
+
const steerQueueItems = useSyncExternalStore(messageQueue?.subscribe ?? subscribeNoop, () => messageQueue?.adapter.steerItems ?? EMPTY_QUEUE_ITEMS, () => EMPTY_QUEUE_ITEMS);
|
|
151
157
|
const busy = isSending || converted.isRunning || Object.keys(toolStatuses).length > 0;
|
|
152
158
|
const wasBusyRef = useRef(false);
|
|
153
159
|
useEffect(() => {
|
|
@@ -164,23 +170,36 @@ const useAssistantTransportThread = (options) => {
|
|
|
164
170
|
extras,
|
|
165
171
|
attachmentAdapter: options.adapters?.attachments,
|
|
166
172
|
onNew: handleAppend,
|
|
167
|
-
...messageQueue && { queue: {
|
|
173
|
+
...serverQueue ? { queue: serverQueue } : messageQueue && { queue: {
|
|
168
174
|
...messageQueue.adapter,
|
|
169
|
-
items: queueItems
|
|
175
|
+
items: queueItems,
|
|
176
|
+
steerItems: steerQueueItems
|
|
170
177
|
} },
|
|
171
|
-
...options.capabilities?.edit && { onEdit:
|
|
178
|
+
...options.capabilities?.edit && { onEdit: handleEdit },
|
|
172
179
|
onReload: (parentId) => {
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
180
|
+
const command_3 = resolveReloadCommand(convertedRef.current.messages, parentId);
|
|
181
|
+
toolInvocations.abort().then(() => dispatch(command_3));
|
|
182
|
+
},
|
|
183
|
+
onCancel: () => {
|
|
184
|
+
messageQueue?.clear();
|
|
185
|
+
handleCancel();
|
|
176
186
|
},
|
|
177
|
-
onCancel: handleCancel,
|
|
178
187
|
onResume: () => {
|
|
188
|
+
if (options.capabilities?.continue) {
|
|
189
|
+
dispatch({ type: "run/continue" });
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
179
192
|
if (!options.resumeApi) throw new Error("Must pass resumeApi to options to resume runs");
|
|
180
193
|
commands.resume().catch(() => {});
|
|
181
194
|
},
|
|
182
195
|
onAddToolResult: (toolOptions) => {
|
|
183
|
-
const
|
|
196
|
+
const requests_0 = convertedRef.current.inputRequests;
|
|
197
|
+
const inputCommand = requests_0 && resolveToolResultInput(requests_0, toolOptions);
|
|
198
|
+
if (inputCommand) {
|
|
199
|
+
dispatch(inputCommand);
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
const command_4 = {
|
|
184
203
|
type: "add-tool-result",
|
|
185
204
|
toolCallId: toolOptions.toolCallId,
|
|
186
205
|
result: toolOptions.result,
|
|
@@ -189,8 +208,9 @@ const useAssistantTransportThread = (options) => {
|
|
|
189
208
|
...toolOptions.artifact && { artifact: toolOptions.artifact },
|
|
190
209
|
...toolOptions.modelContent !== void 0 && { modelContent: toolOptions.modelContent }
|
|
191
210
|
};
|
|
192
|
-
dispatch(
|
|
211
|
+
dispatch(command_4);
|
|
193
212
|
},
|
|
213
|
+
...inputRequests !== void 0 && { onRespondToToolApproval: (options_0) => dispatch(resolveToolApprovalInput(convertedRef.current.inputRequests, options_0)) },
|
|
194
214
|
onResumeToolCall: ({ toolCallId, payload }) => {
|
|
195
215
|
if (!toolInvocations.resume(toolCallId, payload)) throw new Error(`Tool call ${toolCallId} is not waiting for resume.`);
|
|
196
216
|
},
|
|
@@ -209,6 +229,6 @@ const useAssistantTransportThread = (options) => {
|
|
|
209
229
|
const AssistantTransportThread = (options) => resource(useAssistantTransportThread)(options);
|
|
210
230
|
forwardTransformScopes(useAssistantTransportThread, ExternalThread(void 0).hook);
|
|
211
231
|
//#endregion
|
|
212
|
-
export { AssistantTransportThread, asAssistantTransportExtras,
|
|
232
|
+
export { AssistantTransportThread, asAssistantTransportExtras, symbolAssistantTransportExtras };
|
|
213
233
|
|
|
214
234
|
//# sourceMappingURL=AssistantTransportThread.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AssistantTransportThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","useSyncExternalStore","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","createMessageQueue","AddToolResultOptions","AppendMessage","MessageQueueController","MessageQueueDriver","ResumeToolCallOptions","ThreadMessage","ToolExecutionStatus","ToolInvocationTracker","ReadonlyJSONObject","useStatewire","AssistantTransportHost","AssistantTransportHostCommands","AssistantTransportHostState","HostQueueCell","HostRunContext","SendOptions","AddMessageCommand","AddToolResultCommand","AssistantTransportCommand","AssistantTransportOptions","UserMessagePart","EMPTY_TOOL_STATUSES","Record","EMPTY_QUEUE_ITEMS","subscribeNoop","symbolAssistantTransportExtras","Symbol","AssistantTransportExtras","sendCommand","command","reconnect","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","connection","transport","agent","agentState","isSending","isReplaying","queue","dispatch","opts","send","catch","toolStatuses","setToolStatuses","converter","converted","pendingCommands","convertedRef","toolInvocations","tools","onResult","onStatusesChange","statuses","size","Object","fromEntries","setState","isRunning","isLoading","reset","handleAppend","startRun","setParentId","schedule","abort","then","handleCancel","cancel","driverRef","run","at","id","enableQueue","capabilities","queueRef","adapter","clear","messageQueue","queueItems","subscribe","items","busy","keys","wasBusyRef","notifyBusy","notifyIdle","attachmentAdapter","adapters","onNew","edit","onEdit","onReload","reload","onCancel","onResume","resumeApi","resume","onAddToolResult","toolOptions","result","toolName","isError","artifact","modelContent","onResumeToolCall","payload","onLoadExternalState","imported","importState","AssistantTransportThread","T","hook"],"sources":["../src/AssistantTransportThread.ts"],"sourcesContent":["import {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} 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 { createMessageQueue } from \"@assistant-ui/core\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n MessageQueueController,\n MessageQueueDriver,\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> = {};\nconst EMPTY_QUEUE_ITEMS: MessageQueueController[\"adapter\"][\"items\"] = [];\nconst subscribeNoop = () => () => {};\n\nexport const symbolAssistantTransportExtras = Symbol(\n \"assistant-transport-extras\",\n);\n\nexport type AssistantTransportExtras = {\n [symbolAssistantTransportExtras]: true;\n sendCommand: (command: AssistantTransportCommand) => void;\n reconnect: () => 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 or StatewireThread\",\n );\n\n return extras as AssistantTransportExtras;\n};\n\nexport const 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, connection } = 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 const dispatch = useCallback(\n (command: AssistantTransportCommand, opts?: SendOptions) => {\n void commands.send(command, opts).catch(() => {});\n },\n [commands],\n );\n\n const [toolStatuses, setToolStatuses] =\n useState<Record<string, ToolExecutionStatus>>(EMPTY_TOOL_STATUSES);\n\n const { converter } = options;\n const converted = useMemo(\n () =>\n converter(agentState, {\n pendingCommands: [...queue.inTransit, ...queue.queued],\n isSending,\n toolStatuses,\n }),\n [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 reconnect: connection.reconnect,\n state: agentState,\n }),\n [dispatch, connection.reconnect, 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 const handleCancel = () => {\n void toolInvocations.abort();\n void commands.cancel().catch(() => {});\n };\n\n const driverRef = useRef<{\n run: MessageQueueDriver[\"run\"];\n cancel: () => void;\n }>(undefined as never);\n driverRef.current = {\n // the queued message was stamped with the head at enqueue time; restamp so\n // it appends to the thread the finished run left behind\n run: (message) =>\n handleAppend({\n ...message,\n parentId: convertedRef.current.messages.at(-1)?.id ?? null,\n }),\n cancel: handleCancel,\n };\n\n const enableQueue = options.capabilities?.queue === true;\n const queueRef = useRef<MessageQueueController | null>(null);\n if (enableQueue && !queueRef.current) {\n queueRef.current = createMessageQueue({\n run: (message, opts) => driverRef.current.run(message, opts),\n cancel: () => driverRef.current.cancel(),\n });\n } else if (!enableQueue && queueRef.current) {\n queueRef.current.adapter.clear(\"cancel-run\");\n queueRef.current = null;\n }\n const messageQueue = queueRef.current;\n\n // fresh view per snapshot: the controller mutates adapter.items in place,\n // which a stable prop identity would hide from the thread resource\n const queueItems = useSyncExternalStore(\n messageQueue?.subscribe ?? subscribeNoop,\n () => messageQueue?.adapter.items ?? EMPTY_QUEUE_ITEMS,\n () => EMPTY_QUEUE_ITEMS,\n );\n\n // settled edge: the queue only advances once the host run loop has fully\n // released (isSending), the converted state agrees, and no client tool from\n // the finished run is still executing\n const busy =\n isSending || converted.isRunning || Object.keys(toolStatuses).length > 0;\n const wasBusyRef = useRef(false);\n useEffect(() => {\n if (wasBusyRef.current === busy) return;\n wasBusyRef.current = busy;\n if (busy) messageQueue?.notifyBusy();\n else messageQueue?.notifyIdle();\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 ...(messageQueue && {\n queue: { ...messageQueue.adapter, items: queueItems },\n }),\n ...(options.capabilities?.edit && { onEdit: handleAppend }),\n onReload: (parentId: string | null) => {\n void toolInvocations.abort().then(() => {\n void commands.reload(parentId).catch(() => {});\n });\n },\n onCancel: handleCancel,\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":";;;;;;;;;AA8CA,MAAMoC,sBAA2D,CAAC;AAClE,MAAME,oBAAgE,CAAA;AACtE,MAAMC,4BAA4B,CAAC;AAEnC,MAAaC,iCAAiCC,OAC5C,4BACF;AASA,MAAaM,8BACXC,WAC6B;CAC7B,IACE,OAAOA,WAAW,YAClBA,UAAU,QACV,EAAER,kCAAkCQ,SAEpC,M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GAAIH,YAAYI,YAAY,EAAEA,UAAUJ,YAAYI,SAAS;IAC7D,GAAIJ,YAAYK,iBAAiB1F,KAAAA,KAAa,EAC5C0F,cAAcL,YAAYK,aAC5B;GACF;GAEAjE,SAASpD,SAAO;EAClB;EACAsH,mBAAmB,EAAE9F,YAAY+F,cAAqC;GACpE,IAAI,CAACzD,gBAAgBgD,OAAOtF,YAAY+F,OAAO,GAC7C,MAAM,IAAIlH,MAAM,aAAamB,WAAU,4BAA6B;EACxE;EACAgG,sBAAsBC,aAAsB;GAC1C,SAAcC,YAAYD,QAAQ,CAAC,CAAClE,YAAY,CAAC,CAAC;GAElDM,aAAa5B,UAAUJ,QAAQ6B,UAAU+D,UAAU;IACjD7D,iBAAiB,CAAC,GAAGT,MAAMR,WAAW,GAAGQ,MAAMT,MAAM;IACrDO;IACAO,cAAchE;GAChB,CAAC;GACDsE,gBAAgBW,MAAM;GACtBhB,gBAAgBjE,mBAAmB;EACrC;CACF,CAAC,CACH;AACF;AAEA,MAAamI,4BACX9F,YAEAnE,SAASkE,2BAA2B,CAAC,CACnCC,OACF;AAGF9D,uBACE6D,6BACA/D,eAAe8D,KAAAA,CAAkB,CAAC,CAACkG,IACrC"}
|
|
1
|
+
{"version":3,"file":"AssistantTransportThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","useSyncExternalStore","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","createMessageQueue","AddToolResultOptions","AppendMessage","MessageQueueController","MessageQueueDriver","RespondToToolApprovalOptions","ResumeToolCallOptions","ThreadMessage","ToolExecutionStatus","ToolInvocationTracker","ReadonlyJSONObject","useStatewire","AssistantTransportHost","AssistantTransportHostCommands","AssistantTransportHostState","HostQueueCell","HostRunContext","SendOptions","createRunQueueAdapter","resolveReloadCommand","toWireMessage","resolveToolApprovalInput","resolveToolResultInput","AddToolResultCommand","AssistantTransportCommand","AssistantTransportOptions","InputRequestState","EMPTY_TOOL_STATUSES","Record","EMPTY_QUEUE_ITEMS","subscribeNoop","symbolAssistantTransportExtras","Symbol","AssistantTransportExtras","sendCommand","command","reconnect","state","inputRequests","asAssistantTransportExtras","extras","Error","messagesContainToolCall","messages","toolCallId","some","message","content","part","type","undefined","useAssistantTransportThread","options","clientRef","getRunContext","aui","current","parent","threadId","threadListItem","getState","remoteId","modelContext","getModelContext","queueCell","queued","inTransit","commands","connection","transport","agent","agentState","isSending","isReplaying","queue","dispatch","opts","send","catch","toolStatuses","setToolStatuses","converter","converted","pendingCommands","convertedRef","toolInvocations","tools","onResult","requests","onStatusesChange","statuses","size","Object","fromEntries","setState","isRunning","isLoading","reset","inputSeam","present","handleAppend","startRun","role","crypto","randomUUID","setParentId","parentId","schedule","abort","then","handleEdit","sourceId","handleCancel","cancel","driverRef","run","at","id","queueProjection","steerProjection","steerQueue","capabilities","queueSeam","serverQueue","enableQueue","queueRef","clear","messageQueue","queueItems","subscribe","adapter","items","steerQueueItems","steerItems","busy","keys","length","wasBusyRef","notifyBusy","notifyIdle","attachmentAdapter","adapters","attachments","onNew","edit","onEdit","onReload","onCancel","onResume","continue","resumeApi","resume","onAddToolResult","toolOptions","inputCommand","result","toolName","isError","artifact","modelContent","onRespondToToolApproval","onResumeToolCall","payload","onLoadExternalState","imported","importState","AssistantTransportThread","T","hook"],"sources":["../src/AssistantTransportThread.ts"],"sourcesContent":["import {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} 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 { createMessageQueue } from \"@assistant-ui/core\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n MessageQueueController,\n MessageQueueDriver,\n RespondToToolApprovalOptions,\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 {\n createRunQueueAdapter,\n resolveReloadCommand,\n toWireMessage,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\nimport type {\n AddToolResultCommand,\n AssistantTransportCommand,\n AssistantTransportOptions,\n InputRequestState,\n} from \"./types\";\n\nconst EMPTY_TOOL_STATUSES: Record<string, ToolExecutionStatus> = {};\nconst EMPTY_QUEUE_ITEMS: MessageQueueController[\"adapter\"][\"items\"] = [];\nconst subscribeNoop = () => () => {};\n\nexport const symbolAssistantTransportExtras = Symbol(\n \"assistant-transport-extras\",\n);\n\nexport type AssistantTransportExtras = {\n [symbolAssistantTransportExtras]: true;\n sendCommand: (command: AssistantTransportCommand) => void;\n reconnect: () => void;\n state: unknown;\n /** The host's parked input requests; absent when the converter does not project them. */\n inputRequests?: readonly InputRequestState[];\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 or StatewireThread\",\n );\n\n return extras as AssistantTransportExtras;\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, connection } = 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 const dispatch = useCallback(\n (command: AssistantTransportCommand, opts?: SendOptions) => {\n void commands.send(command, opts).catch(() => {});\n },\n [commands],\n );\n\n const [toolStatuses, setToolStatuses] =\n useState<Record<string, ToolExecutionStatus>>(EMPTY_TOOL_STATUSES);\n\n const { converter } = options;\n const converted = useMemo(\n () =>\n converter(agentState, {\n pendingCommands: [...queue.inTransit, ...queue.queued],\n isSending,\n toolStatuses,\n }),\n [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 const requests = convertedRef.current.inputRequests;\n dispatch(\n (requests && resolveToolResultInput(requests, command)) ??\n command,\n );\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 inputRequests = converted.inputRequests;\n const [inputSeam] = useState(() => ({\n present: inputRequests !== undefined,\n }));\n if (inputSeam.present !== (inputRequests !== undefined))\n throw new Error(\n \"statewire: the converter's inputRequests projection must be stable — it was \" +\n (inputSeam.present ? \"defined\" : \"undefined\") +\n \" on first convert and changed since\",\n );\n\n const extras = useMemo(\n (): AssistantTransportExtras => ({\n [symbolAssistantTransportExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state: agentState,\n ...(inputRequests !== undefined && { inputRequests }),\n }),\n [dispatch, connection.reconnect, agentState, inputRequests],\n );\n\n const handleAppend = (message: AppendMessage) => {\n const startRun = message.startRun ?? message.role === \"user\";\n const command: AssistantTransportCommand = {\n type: \"run/steer\",\n message: toWireMessage(message, crypto.randomUUID()),\n };\n void commands.setParentId(message.parentId).catch(() => {});\n\n const send = () => dispatch(command, { schedule: startRun });\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 const handleEdit = (message: AppendMessage) => {\n if (message.sourceId == null)\n throw new Error(\"statewire: run/edit requires a sourceId\");\n const command: AssistantTransportCommand = {\n type: \"run/edit\",\n message: toWireMessage(message, crypto.randomUUID()),\n sourceId: message.sourceId,\n };\n void toolInvocations.abort().then(() => dispatch(command));\n };\n\n const handleCancel = () => {\n void toolInvocations.abort();\n void commands.cancel().catch(() => {});\n };\n\n const driverRef = useRef<{\n run: MessageQueueDriver[\"run\"];\n cancel: () => void;\n }>(undefined as never);\n driverRef.current = {\n // the queued message was stamped with the head at enqueue time; restamp so\n // it appends to the thread the finished run left behind\n run: (message) =>\n handleAppend({\n ...message,\n parentId: convertedRef.current.messages.at(-1)?.id ?? null,\n }),\n cancel: handleCancel,\n };\n\n const queueProjection = converted.queue;\n const steerProjection = converted.steerQueue;\n if (steerProjection !== undefined && queueProjection === undefined)\n throw new Error(\n \"statewire: the converter's steerQueue projection requires the queue projection\",\n );\n if (queueProjection !== undefined && options.capabilities?.queue)\n throw new Error(\n \"statewire: the converter's queue projection excludes capabilities.queue\",\n );\n const [queueSeam] = useState(() => ({\n present: queueProjection !== undefined,\n }));\n if (queueSeam.present !== (queueProjection !== undefined))\n throw new Error(\n \"statewire: the converter's queue projection must be stable — it was \" +\n (queueSeam.present ? \"defined\" : \"undefined\") +\n \" on first convert and changed since\",\n );\n const serverQueue = useMemo(\n () =>\n queueProjection\n ? createRunQueueAdapter(queueProjection, steerProjection, dispatch)\n : undefined,\n [queueProjection, steerProjection, dispatch],\n );\n\n const enableQueue = options.capabilities?.queue === true;\n const queueRef = useRef<MessageQueueController | null>(null);\n if (enableQueue && !queueRef.current) {\n queueRef.current = createMessageQueue({\n run: (message, opts) => driverRef.current.run(message, opts),\n cancel: () => driverRef.current.cancel(),\n });\n } else if (!enableQueue && queueRef.current) {\n queueRef.current.clear();\n queueRef.current = null;\n }\n const messageQueue = queueRef.current;\n\n // fresh view per snapshot: the controller mutates adapter.items in place,\n // which a stable prop identity would hide from the thread resource\n const queueItems = useSyncExternalStore(\n messageQueue?.subscribe ?? subscribeNoop,\n () => messageQueue?.adapter.items ?? EMPTY_QUEUE_ITEMS,\n () => EMPTY_QUEUE_ITEMS,\n );\n const steerQueueItems = useSyncExternalStore(\n messageQueue?.subscribe ?? subscribeNoop,\n () => messageQueue?.adapter.steerItems ?? EMPTY_QUEUE_ITEMS,\n () => EMPTY_QUEUE_ITEMS,\n );\n\n // settled edge: the queue only advances once the host run loop has fully\n // released (isSending), the converted state agrees, and no client tool from\n // the finished run is still executing\n const busy =\n isSending || converted.isRunning || Object.keys(toolStatuses).length > 0;\n const wasBusyRef = useRef(false);\n useEffect(() => {\n if (wasBusyRef.current === busy) return;\n wasBusyRef.current = busy;\n if (busy) messageQueue?.notifyBusy();\n else messageQueue?.notifyIdle();\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 ...(serverQueue\n ? { queue: serverQueue }\n : messageQueue && {\n queue: {\n ...messageQueue.adapter,\n items: queueItems,\n steerItems: steerQueueItems,\n },\n }),\n ...(options.capabilities?.edit && { onEdit: handleEdit }),\n onReload: (parentId: string | null) => {\n const command = resolveReloadCommand(\n convertedRef.current.messages,\n parentId,\n );\n void toolInvocations.abort().then(() => dispatch(command));\n },\n onCancel: () => {\n // user cancel drops pending lanes; a steer interrupt (driver.cancel) keeps them\n messageQueue?.clear();\n handleCancel();\n },\n onResume: () => {\n if (options.capabilities?.continue) {\n dispatch({ type: \"run/continue\" });\n return;\n }\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 requests = convertedRef.current.inputRequests;\n const inputCommand =\n requests && resolveToolResultInput(requests, toolOptions);\n if (inputCommand) {\n dispatch(inputCommand);\n return;\n }\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 ...(inputRequests !== undefined && {\n onRespondToToolApproval: (options: RespondToToolApprovalOptions) =>\n dispatch(\n resolveToolApprovalInput(\n convertedRef.current.inputRequests!,\n options,\n ),\n ),\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":";;;;;;;;;;;AAuDA,MAAMyC,sBAA2D,CAAC;AAClE,MAAME,oBAAgE,CAAA;AACtE,MAAMC,4BAA4B,CAAC;AAEnC,MAAaC,iCAAiCC,OAC5C,4BACF;AAWA,MAAaO,8BACXC,WAC6B;CAC7B,IACE,OAAOA,WAAW,YAClBA,UAAU,QACV,EAAET,kCAAkCS,SAEpC,MAAM,IAAIC,MACR,+FACF;CAEF,OAAOD;AACT;AAEA,MAAME,2BACJC,UACAC,eAEAD,SAASE,MAAMC,YACbA,QAAQC,QAAQF,MACbG,SACCA,KAAKC,SAAS,gBACbD,KAAKJ,eAAeA,cAClBI,KAAKL,aAAaO,KAAAA,KACjBR,wBAAwBM,KAAKL,UAAUC,UAAU,EACzD,CACF;AAEF,MAAMO,+BACJC,YAC2B;CAC3B,MAAMC,YAAYvD,sBAAsB;CACxC,MAAM,CAACwD,iBAAiBhE,qBAAqC;EAC3D,MAAMiE,MAAMF,UAAUG,WAAWH,UAAUI;EAE3C,IAAIC,WAA0B;EAC9B,IAAI;GACFA,WAAWH,IAAII,eAAe,CAAC,CAACC,SAAS,CAAC,CAACC,YAAY;EACzD,QAAQ,CAAC;EACT,OAAO;GACLC,cAAcP,IAAIO,aAAa,CAAC,CAACC,gBA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MAAa2I,4BACXlH,YAEA5D,SAAS2D,2BAA2B,CAAC,CACnCC,OACF;AAGFvD,uBACEsD,6BACAxD,eAAeuD,KAAAA,CAAkB,CAAC,CAACsH,IACrC"}
|
|
@@ -8,34 +8,135 @@ import { ReadonlyJSONValue } from "assistant-stream/utils";
|
|
|
8
8
|
declare const StatewireThread: <T>(options: StatewireThread.Options<T>) => ResourceElement<ClientOutput<"thread">>;
|
|
9
9
|
declare namespace StatewireThread {
|
|
10
10
|
type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;
|
|
11
|
+
type TextPart = {
|
|
12
|
+
readonly type: "text";
|
|
13
|
+
readonly text: string;
|
|
14
|
+
};
|
|
15
|
+
type FilePart = {
|
|
16
|
+
readonly type: "file";
|
|
17
|
+
readonly mediaType: string;
|
|
18
|
+
readonly url: string;
|
|
19
|
+
readonly filename?: string;
|
|
20
|
+
};
|
|
21
|
+
type UserMessage = {
|
|
22
|
+
readonly id: string;
|
|
23
|
+
readonly role: "user";
|
|
24
|
+
readonly parts: readonly (TextPart | FilePart)[];
|
|
25
|
+
readonly metadata?: Record<string, unknown>;
|
|
26
|
+
};
|
|
27
|
+
/** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */
|
|
28
|
+
type Placement = {
|
|
29
|
+
readonly insertAfter?: string | null;
|
|
30
|
+
readonly insertBefore?: string | null;
|
|
31
|
+
};
|
|
32
|
+
type RunEnqueueCommand = {
|
|
33
|
+
readonly type: "run/enqueue";
|
|
34
|
+
} & ({
|
|
35
|
+
readonly message: UserMessage;
|
|
36
|
+
} | {
|
|
37
|
+
readonly messageId: string;
|
|
38
|
+
}) & Placement;
|
|
39
|
+
type RunSteerCommand = {
|
|
40
|
+
readonly type: "run/steer";
|
|
41
|
+
} & ({
|
|
42
|
+
readonly message: UserMessage;
|
|
43
|
+
} | {
|
|
44
|
+
readonly messageId: string;
|
|
45
|
+
}) & Placement;
|
|
46
|
+
type RunDequeueCommand = {
|
|
47
|
+
readonly type: "run/dequeue";
|
|
48
|
+
readonly messageId: string;
|
|
49
|
+
};
|
|
50
|
+
type RunEditCommand = {
|
|
51
|
+
readonly type: "run/edit";
|
|
52
|
+
readonly message: UserMessage;
|
|
53
|
+
readonly sourceId: string;
|
|
54
|
+
};
|
|
55
|
+
type RunContinueCommand = {
|
|
56
|
+
readonly type: "run/continue";
|
|
57
|
+
};
|
|
58
|
+
type ToolCallInputRequest = {
|
|
59
|
+
readonly type: "tool-call";
|
|
60
|
+
readonly id: string;
|
|
61
|
+
readonly toolCallId: string;
|
|
62
|
+
};
|
|
63
|
+
type ToolApprovalInputRequest = {
|
|
64
|
+
readonly type: "tool-approval";
|
|
65
|
+
readonly id: string;
|
|
66
|
+
readonly toolCallId: string;
|
|
67
|
+
};
|
|
68
|
+
type CustomInputRequest = {
|
|
69
|
+
readonly type: string;
|
|
70
|
+
readonly id: string;
|
|
71
|
+
readonly [key: string]: ReadonlyJSONValue | undefined;
|
|
72
|
+
};
|
|
73
|
+
/** A host request parking the run until answered; open union for custom types. */
|
|
74
|
+
type InputRequest = ToolCallInputRequest | ToolApprovalInputRequest | CustomInputRequest;
|
|
75
|
+
type ToolCallInputResponse = {
|
|
76
|
+
readonly output: ReadonlyJSONValue;
|
|
77
|
+
/** Default false; when true, `output` carries the error payload. */
|
|
78
|
+
readonly isError?: boolean;
|
|
79
|
+
readonly artifact?: ReadonlyJSONValue;
|
|
80
|
+
};
|
|
81
|
+
type ToolApprovalInputResponse = {
|
|
82
|
+
readonly decision: "approve" | "reject" | "edit" | "respond";
|
|
83
|
+
readonly editedArgs?: ReadonlyJSONValue;
|
|
84
|
+
readonly message?: string;
|
|
85
|
+
};
|
|
86
|
+
type InputResponse = ReadonlyJSONValue;
|
|
87
|
+
type RunInputCommand = {
|
|
88
|
+
readonly type: "run/input";
|
|
89
|
+
readonly requestId: string;
|
|
90
|
+
readonly response: InputResponse;
|
|
91
|
+
};
|
|
92
|
+
/** An input request projected out of the host state with its response echo. */
|
|
93
|
+
type InputRequestState = InputRequest & {
|
|
94
|
+
readonly response: InputResponse | null;
|
|
95
|
+
};
|
|
96
|
+
type RunReloadCommand = {
|
|
97
|
+
readonly type: "run/reload";
|
|
98
|
+
readonly sourceId: string;
|
|
99
|
+
};
|
|
100
|
+
type RunCommand = RunEnqueueCommand | RunSteerCommand | RunDequeueCommand | RunEditCommand | RunContinueCommand | RunReloadCommand | RunInputCommand;
|
|
101
|
+
type Command = AssistantTransportCommand | RunCommand;
|
|
102
|
+
/** A queued message projected out of the host state, wire shape. */
|
|
11
103
|
type QueueItem = {
|
|
12
104
|
readonly id: string;
|
|
13
|
-
readonly
|
|
105
|
+
readonly parts: readonly (TextPart | FilePart)[];
|
|
14
106
|
};
|
|
15
107
|
type State = {
|
|
16
108
|
readonly messages: readonly ThreadMessage[];
|
|
17
109
|
readonly state?: ReadonlyJSONValue;
|
|
18
110
|
readonly isRunning: boolean;
|
|
19
111
|
/**
|
|
20
|
-
*
|
|
21
|
-
* (even empty) turns on the queue capability: sends
|
|
22
|
-
* `
|
|
23
|
-
* Presence must be stable across conversions.
|
|
112
|
+
* The host's regular queue lane projected out of the state. Returning it
|
|
113
|
+
* (even empty) turns on the queue capability: sends become `run/enqueue`
|
|
114
|
+
* / `run/steer` commands and item controls send the `run/*` queue
|
|
115
|
+
* commands. Presence must be stable across conversions.
|
|
24
116
|
*/
|
|
25
117
|
readonly queue?: readonly QueueItem[];
|
|
118
|
+
/** The host's steer lane; requires `queue`. Absent means empty. */
|
|
119
|
+
readonly steerQueue?: readonly QueueItem[];
|
|
120
|
+
/**
|
|
121
|
+
* The host's parked input requests projected out of the state. Returning
|
|
122
|
+
* it (even empty) routes tool results and approvals with a matching
|
|
123
|
+
* pending request through `run/input`. Presence must be stable across
|
|
124
|
+
* conversions.
|
|
125
|
+
*/
|
|
126
|
+
readonly inputRequests?: readonly InputRequestState[];
|
|
26
127
|
};
|
|
27
128
|
type ConnectionMetadata = {
|
|
28
|
-
pendingCommands:
|
|
129
|
+
pendingCommands: Command[];
|
|
29
130
|
isSending: boolean;
|
|
30
131
|
/** Statewire connection status; local transports are always `live`. */
|
|
31
132
|
connection: StatewireClient.ConnectionState;
|
|
32
133
|
};
|
|
33
134
|
type StateConverter<T> = (state: T, connectionMetadata: ConnectionMetadata) => State;
|
|
34
135
|
/**
|
|
35
|
-
* Payload of the built-in `
|
|
136
|
+
* Payload of the built-in `run/stop` command. `reason` is the one well-known
|
|
36
137
|
* field; apps extend it with their own JSON-serializable fields.
|
|
37
138
|
*/
|
|
38
|
-
type
|
|
139
|
+
type StopPayload = {
|
|
39
140
|
readonly reason?: string | undefined;
|
|
40
141
|
readonly [key: string]: ReadonlyJSONValue | undefined;
|
|
41
142
|
};
|
|
@@ -49,11 +150,22 @@ declare namespace StatewireThread {
|
|
|
49
150
|
* on connect and whenever it changes. Requires a remote transport.
|
|
50
151
|
*/
|
|
51
152
|
contextSync?: "command-send" | undefined;
|
|
52
|
-
/** Supplies the `
|
|
53
|
-
|
|
153
|
+
/** Supplies the `run/stop` command's payload; omitted, stop sends no payload. */
|
|
154
|
+
stopPayload?: (() => StopPayload) | undefined;
|
|
155
|
+
/**
|
|
156
|
+
* Offered each pending command when a remote transport's session is
|
|
157
|
+
* evicted; return "replay" to re-enqueue it under the rotated client id.
|
|
158
|
+
* A callback set on the transport options is consulted first; this one
|
|
159
|
+
* runs for commands it declined.
|
|
160
|
+
*/
|
|
161
|
+
onCommandSessionLost?: ((command: StatewireClient.SessionLostCommand) => "replay" | void) | undefined;
|
|
54
162
|
onError?: ((error: Error) => void) | undefined;
|
|
55
163
|
capabilities?: {
|
|
56
164
|
edit?: boolean | undefined;
|
|
165
|
+
/** The host supports `run/continue` (a continue affordance on aborted runs). */
|
|
166
|
+
continue?: boolean | undefined;
|
|
167
|
+
/** The host supports `run/reload` (regenerating an assistant message). */
|
|
168
|
+
reload?: boolean | undefined;
|
|
57
169
|
} | undefined;
|
|
58
170
|
adapters?: {
|
|
59
171
|
attachments?: AttachmentAdapter | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;;cA4Ua,kBAAmB,GAC9B,SAAS,gBAAgB,QAAQ,OAChC,gBAAgB;kBAGF;OACH,UAAU,KAAK,gBAAgB,UAAU;OAEzC;aACD;aACA;;OAGC;aACD;aACA;aACA;aACA;;OAGC;aACD;aACA;aACA,iBAAiB,WAAW;aAC5B,WAAW;;;OAIV;aACD;aACA;;OAGC;aACD;;aACK,SAAS;;aAA2B;OAClD;OAEU;aACD;;aACK,SAAS;;aAA2B;OAClD;OAEU;aACD;aACA;;OAGC;aACD;aACA,SAAS;aACT;;OAGC;aACD;;OAGC;aACD;aACA;aACA;;OAGC;aACD;aACA;aACA;;OAGC;aACD;aACA;cACC,cAAc;;;OAId,eACR,uBACA,2BACA;OAEQ;aACD,QAAQ;;aAER;aACA,WAAW;;OAGV;aACD;aACA,aAAa;aACb;;OAGC,gBAAgB;OAEhB;aACD;aACA;aACA,UAAU;;;OAIT,oBAAoB;aACrB,UAAU;;OAGT;aACD;aACA;;OAGC,aACR,oBACA,kBACA,oBACA,iBACA,qBACA,mBACA;OAEQ,UAAU,4BAA4B;;OAGtC;aACD;aACA,iBAAiB,WAAW;;OAG3B;aACD,mBAAmB;aACnB,QAAQ;aACR;;;;;;;aAOA,iBAAiB;;aAEjB,sBAAsB;;;;;;;aAOtB,yBAAyB;;OAGxB;IACV,iBAAiB;IACjB;;IAEA,YAAY,gBAAgB;;OAGlB,eAAe,MACzB,OAAO,GACP,oBAAoB,uBACjB;;;;;OAMO;aACD;cACC,cAAc;;OAGd,QAAQ;IAClB,WAAW,UAAU;IACrB,cAAc;IACd,WAAW,eAAe;;;;;;IAM1B;;IAEA,qBAAqB;;;;;;;IAOrB,yBACM,SAAS,gBAAgB;IAE/B,YAAY,OAAO;IACnB;MAEM;;MAEA;;MAEA;;IAGN;MAEM,cAAc"}
|