@assistant-ui/react-statewire 0.2.0 → 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.
@@ -1,7 +1,6 @@
1
- import { AssistantTransportCommand, AssistantTransportOptions, MessageAddCommand } from "./types.js";
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) => MessageAddCommand | null;
15
15
  declare const AssistantTransportThread: <T>(options: AssistantTransportOptions<T>) => ResourceElement<ClientOutput<"thread">>;
16
16
  //#endregion
17
- export { AssistantTransportExtras, AssistantTransportThread, asAssistantTransportExtras, convertAppendMessageToCommand, symbolAssistantTransportExtras };
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":";;;;;cAkDa;KAID;GACT;EACD,cAAc,SAAS;EACvB;EACA;;cAGW,6BACX,oBACC;cAaU,gCACX,SAAS,kBACR;cA+RU,2BAA4B,GACvC,SAAS,0BAA0B,OAClC,gBAAgB"}
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: "message/add",
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,10 +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
- dispatch({
91
- ...command_0,
92
- type: "tool-result/add"
93
- });
69
+ const requests = convertedRef.current.inputRequests;
70
+ dispatch((requests && resolveToolResultInput(requests, command_0)) ?? command_0);
94
71
  },
95
72
  onStatusesChange: (statuses) => {
96
73
  setToolStatuses(statuses.size === 0 ? EMPTY_TOOL_STATUSES : Object.fromEntries(statuses));
@@ -106,43 +83,68 @@ const useAssistantTransportThread = (options) => {
106
83
  useEffect(() => () => {
107
84
  toolInvocations.reset();
108
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");
109
89
  const extras = useMemo(() => ({
110
90
  [symbolAssistantTransportExtras]: true,
111
91
  sendCommand: dispatch,
112
92
  reconnect: connection.reconnect,
113
- state: agentState
93
+ state: agentState,
94
+ ...inputRequests !== void 0 && { inputRequests }
114
95
  }), [
115
96
  dispatch,
116
97
  connection.reconnect,
117
- agentState
98
+ agentState,
99
+ inputRequests
118
100
  ]);
119
101
  const handleAppend = (message) => {
120
102
  const startRun = message.startRun ?? message.role === "user";
121
- const command_1 = convertAppendMessageToCommand(message);
122
- commands.setParentId(message.parentId).catch(() => {});
123
- const send = () => {
124
- if (!command_1) return;
125
- dispatch(command_1, { schedule: startRun });
103
+ const command_1 = {
104
+ type: "run/steer",
105
+ message: toWireMessage(message, crypto.randomUUID())
126
106
  };
107
+ commands.setParentId(message.parentId).catch(() => {});
108
+ const send = () => dispatch(command_1, { schedule: startRun });
127
109
  if (startRun) toolInvocations.abort().then(send);
128
110
  else send();
129
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
+ };
130
121
  const handleCancel = () => {
131
122
  toolInvocations.abort();
132
123
  commands.cancel().catch(() => {});
133
124
  };
134
125
  const driverRef = useRef(void 0);
135
126
  driverRef.current = {
136
- run: (message_0) => handleAppend({
137
- ...message_0,
127
+ run: (message_1) => handleAppend({
128
+ ...message_1,
138
129
  parentId: convertedRef.current.messages.at(-1)?.id ?? null
139
130
  }),
140
131
  cancel: handleCancel
141
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
+ ]);
142
144
  const enableQueue = options.capabilities?.queue === true;
143
145
  const queueRef = useRef(null);
144
146
  if (enableQueue && !queueRef.current) queueRef.current = createMessageQueue({
145
- run: (message_1, opts_0) => driverRef.current.run(message_1, opts_0),
147
+ run: (message_2, opts_0) => driverRef.current.run(message_2, opts_0),
146
148
  cancel: () => driverRef.current.cancel()
147
149
  });
148
150
  else if (!enableQueue && queueRef.current) {
@@ -168,28 +170,37 @@ const useAssistantTransportThread = (options) => {
168
170
  extras,
169
171
  attachmentAdapter: options.adapters?.attachments,
170
172
  onNew: handleAppend,
171
- ...messageQueue && { queue: {
173
+ ...serverQueue ? { queue: serverQueue } : messageQueue && { queue: {
172
174
  ...messageQueue.adapter,
173
175
  items: queueItems,
174
176
  steerItems: steerQueueItems
175
177
  } },
176
- ...options.capabilities?.edit && { onEdit: handleAppend },
178
+ ...options.capabilities?.edit && { onEdit: handleEdit },
177
179
  onReload: (parentId) => {
178
- toolInvocations.abort().then(() => {
179
- commands.reload(parentId).catch(() => {});
180
- });
180
+ const command_3 = resolveReloadCommand(convertedRef.current.messages, parentId);
181
+ toolInvocations.abort().then(() => dispatch(command_3));
181
182
  },
182
183
  onCancel: () => {
183
184
  messageQueue?.clear();
184
185
  handleCancel();
185
186
  },
186
187
  onResume: () => {
188
+ if (options.capabilities?.continue) {
189
+ dispatch({ type: "run/continue" });
190
+ return;
191
+ }
187
192
  if (!options.resumeApi) throw new Error("Must pass resumeApi to options to resume runs");
188
193
  commands.resume().catch(() => {});
189
194
  },
190
195
  onAddToolResult: (toolOptions) => {
191
- const command_2 = {
192
- type: "tool-result/add",
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 = {
203
+ type: "add-tool-result",
193
204
  toolCallId: toolOptions.toolCallId,
194
205
  result: toolOptions.result,
195
206
  toolName: toolOptions.toolName,
@@ -197,8 +208,9 @@ const useAssistantTransportThread = (options) => {
197
208
  ...toolOptions.artifact && { artifact: toolOptions.artifact },
198
209
  ...toolOptions.modelContent !== void 0 && { modelContent: toolOptions.modelContent }
199
210
  };
200
- dispatch(command_2);
211
+ dispatch(command_4);
201
212
  },
213
+ ...inputRequests !== void 0 && { onRespondToToolApproval: (options_0) => dispatch(resolveToolApprovalInput(convertedRef.current.inputRequests, options_0)) },
202
214
  onResumeToolCall: ({ toolCallId, payload }) => {
203
215
  if (!toolInvocations.resume(toolCallId, payload)) throw new Error(`Tool call ${toolCallId} is not waiting for resume.`);
204
216
  },
@@ -217,6 +229,6 @@ const useAssistantTransportThread = (options) => {
217
229
  const AssistantTransportThread = (options) => resource(useAssistantTransportThread)(options);
218
230
  forwardTransformScopes(useAssistantTransportThread, ExternalThread(void 0).hook);
219
231
  //#endregion
220
- export { AssistantTransportThread, asAssistantTransportExtras, convertAppendMessageToCommand, symbolAssistantTransportExtras };
232
+ export { AssistantTransportThread, asAssistantTransportExtras, symbolAssistantTransportExtras };
221
233
 
222
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","MessageAddCommand","ToolResultAddCommand","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","clear","messageQueue","queueItems","subscribe","adapter","items","steerQueueItems","steerItems","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 MessageAddCommand,\n ToolResultAddCommand,\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): MessageAddCommand | 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: \"message/add\",\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, type: \"tool-result/add\" });\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.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 ...(messageQueue && {\n queue: {\n ...messageQueue.adapter,\n items: queueItems,\n steerItems: steerQueueItems,\n },\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: () => {\n // user cancel drops pending lanes; a steer interrupt (driver.cancel) keeps them\n messageQueue?.clear();\n handleCancel();\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: ToolResultAddCommand = {\n type: \"tool-result/add\",\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,MAAM,IAAIC,MACR,+FACF;CAEF,OAAOD;AACT;AAEA,MAAaE,iCACXC,YAC6B;CAC7B,IAAIA,QAAQC,SAAS,QACnB,MAAM,IAAIH,MAAM,kCAAkC;CAEpD,MAAMI,QAA2B,CAAA;CACjC,MAAMC,UAAU,CACd,GAAGH,QAAQG,SACX,GAAIH,QAAQI,aAAaC,SAASC,MAAMA,EAAEH,OAAO,KAAK,CAAA,CAAG;CAE3D,KAAK,MAAMI,eAAeJ,SACxB,IAAII,YAAYC,SAAS,QACvBN,MAAMO,KAAK;EAAED,MAAM;EAAQE,MAAMH,YAAYG;CAAK,CAAC;MAC9C,IAAIH,YAAYC,SAAS,SAC9BN,MAAMO,KAAK;EAAED,MAAM;EAASG,OAAOJ,YAAYI;CAAM,CAAC;CAI1D,IAAIT,MAAMU,WAAW,GAAG,OAAO;CAE/B,OAAO;EACLJ,MAAM;EACNR,SAAS;GACPC,MAAM;GACNC;EACF;EACAW,UAAUb,QAAQa;EAClBC,UAAUd,QAAQc;CACpB;AACF;AAEA,MAAMC,2BACJC,UACAC,eAEAD,SAASE,MAAMlB,YACbA,QAAQG,QAAQe,MACbC,SACCA,KAAKX,SAAS,gBACbW,KAAKF,eAAeA,cAClBE,KAAKH,aAAaI,KAAAA,KACjBL,wBAAwBI,KAAKH,UAAUC,UAAU,EACzD,CACF;AAEF,MAAMI,+BACJC,YAC2B;CAC3B,MAAMC,YAAY9D,sBAAsB;CACxC,MAAM,CAAC+D,iBAAiBvE,qBAAqC;EAC3D,MAA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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,QAAQ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AAErH,YAAYsH,cAAqC;GACpE,IAAI,CAAC7E,gBAAgBkE,OAAO3G,YAAYsH,OAAO,GAC7C,MAAM,IAAIzH,MAAM,aAAaG,WAAU,4BAA6B;EACxE;EACAuH,sBAAsBC,aAAsB;GAC1C,SAAcC,YAAYD,QAAQ,CAAC,CAACtF,YAAY,CAAC,CAAC;GAElDM,aAAa5B,UAAUJ,QAAQ6B,UAAUmF,UAAU;IACjDjF,iBAAiB,CAAC,GAAGT,MAAMR,WAAW,GAAGQ,MAAMT,MAAM;IACrDO;IACAO,cAAcpD;GAChB,CAAC;GACD0D,gBAAgBY,MAAM;GACtBjB,gBAAgBrD,mBAAmB;EACrC;CACF,CAAC,CACH;AACF;AAEA,MAAa2I,4BACXlH,YAEA5D,SAAS2D,2BAA2B,CAAC,CACnCC,OACF;AAGFvD,uBACEsD,6BACAxD,eAAeuD,KAAAA,CAAkB,CAAC,CAACsH,IACrC"}
@@ -55,7 +55,49 @@ declare namespace StatewireThread {
55
55
  type RunContinueCommand = {
56
56
  readonly type: "run/continue";
57
57
  };
58
- type RunCommand = RunEnqueueCommand | RunSteerCommand | RunDequeueCommand | RunEditCommand | RunContinueCommand;
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;
59
101
  type Command = AssistantTransportCommand | RunCommand;
60
102
  /** A queued message projected out of the host state, wire shape. */
61
103
  type QueueItem = {
@@ -75,6 +117,13 @@ declare namespace StatewireThread {
75
117
  readonly queue?: readonly QueueItem[];
76
118
  /** The host's steer lane; requires `queue`. Absent means empty. */
77
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[];
78
127
  };
79
128
  type ConnectionMetadata = {
80
129
  pendingCommands: Command[];
@@ -84,10 +133,10 @@ declare namespace StatewireThread {
84
133
  };
85
134
  type StateConverter<T> = (state: T, connectionMetadata: ConnectionMetadata) => State;
86
135
  /**
87
- * Payload of the built-in `run/cancel` command. `reason` is the one well-known
136
+ * Payload of the built-in `run/stop` command. `reason` is the one well-known
88
137
  * field; apps extend it with their own JSON-serializable fields.
89
138
  */
90
- type CancelPayload = {
139
+ type StopPayload = {
91
140
  readonly reason?: string | undefined;
92
141
  readonly [key: string]: ReadonlyJSONValue | undefined;
93
142
  };
@@ -101,8 +150,8 @@ declare namespace StatewireThread {
101
150
  * on connect and whenever it changes. Requires a remote transport.
102
151
  */
103
152
  contextSync?: "command-send" | undefined;
104
- /** Supplies the `run/cancel` command's payload; omitted, cancel sends no payload. */
105
- cancelPayload?: (() => CancelPayload) | undefined;
153
+ /** Supplies the `run/stop` command's payload; omitted, stop sends no payload. */
154
+ stopPayload?: (() => StopPayload) | undefined;
106
155
  /**
107
156
  * Offered each pending command when a remote transport's session is
108
157
  * evicted; return "replay" to re-enqueue it under the rotated client id.
@@ -115,6 +164,8 @@ declare namespace StatewireThread {
115
164
  edit?: boolean | undefined;
116
165
  /** The host supports `run/continue` (a continue affordance on aborted runs). */
117
166
  continue?: boolean | undefined;
167
+ /** The host supports `run/reload` (regenerating an assistant message). */
168
+ reload?: boolean | undefined;
118
169
  } | undefined;
119
170
  adapters?: {
120
171
  attachments?: AttachmentAdapter | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;;cAiWa,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,aACR,oBACA,kBACA,oBACA,iBACA;OAEQ,UAAU,4BAA4B;;OAGtC;aACD;aACA,iBAAiB,WAAW;;OAG3B;aACD,mBAAmB;aACnB,QAAQ;aACR;;;;;;;aAOA,iBAAiB;;aAEjB,sBAAsB;;OAGrB;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,uBAAuB;;;;;;;IAOvB,yBACM,SAAS,gBAAgB;IAE/B,YAAY,OAAO;IACnB;MAEM;;MAEA;;IAGN;MAEM,cAAc"}
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"}
@@ -1,4 +1,6 @@
1
- import { convertAppendMessageToCommand, symbolAssistantTransportExtras } from "./AssistantTransportThread.js";
1
+ import { createRunQueueAdapter, resolveReloadCommand, toWireMessage } from "./runCommands.js";
2
+ import { resolveToolApprovalInput, resolveToolResultInput } from "./inputRequests.js";
3
+ import { symbolAssistantTransportExtras } from "./AssistantTransportThread.js";
2
4
  import { useCallback, useEffect, useMemo, useRef, useState } from "@assistant-ui/tap/react-shim";
3
5
  import { resource, useResource } from "@assistant-ui/tap";
4
6
  import { ExternalThread } from "@assistant-ui/react";
@@ -12,49 +14,29 @@ const ambientContextOf = (context) => ({
12
14
  ...context.callSettings !== void 0 && { callSettings: context.callSettings },
13
15
  ...context.config !== void 0 && { config: context.config }
14
16
  });
15
- const toWireMessage = (message, id) => {
16
- if (message.role !== "user") throw new Error("statewire: only user messages are supported");
17
- const files = [];
18
- const texts = [];
19
- const source = [...message.content, ...message.attachments?.flatMap((a) => a.content) ?? []];
20
- for (const part of source) if (part.type === "text") texts.push(part.text);
21
- else if (part.type === "image") files.push({
22
- type: "file",
23
- mediaType: "image/*",
24
- url: part.image
17
+ const convertAppendMessageToCommand = (message) => {
18
+ if (message.role !== "user") throw new Error("Only user messages are supported");
19
+ const parts = [];
20
+ const content = [...message.content, ...message.attachments?.flatMap((a) => a.content) ?? []];
21
+ for (const contentPart of content) if (contentPart.type === "text") parts.push({
22
+ type: "text",
23
+ text: contentPart.text
25
24
  });
26
- else if (part.type === "file") files.push({
27
- type: "file",
28
- mediaType: part.mimeType,
29
- url: part.data,
30
- ...part.filename !== void 0 && { filename: part.filename }
25
+ else if (contentPart.type === "image") parts.push({
26
+ type: "image",
27
+ image: contentPart.image
31
28
  });
32
- else throw new Error(`statewire: unsupported message part "${part.type}"`);
33
- const parts = [...files, ...texts.length > 0 ? [{
34
- type: "text",
35
- text: texts.join("\n\n")
36
- }] : []];
37
- if (parts.length === 0) throw new Error("statewire: cannot send an empty message");
29
+ if (parts.length === 0) return null;
38
30
  return {
39
- id,
40
- role: "user",
41
- parts
31
+ type: "add-message",
32
+ message: {
33
+ role: "user",
34
+ parts
35
+ },
36
+ parentId: message.parentId,
37
+ sourceId: message.sourceId
42
38
  };
43
39
  };
44
- const toQueueItemState = (item) => ({
45
- id: item.id,
46
- prompt: item.parts.flatMap((part) => part.type === "text" ? [part.text] : []).join("\n\n"),
47
- parts: item.parts.map((part) => part.type === "text" ? part : {
48
- type: "file",
49
- data: part.url,
50
- mimeType: part.mediaType,
51
- ...part.filename !== void 0 && { filename: part.filename }
52
- })
53
- });
54
- const placementFields = (placement) => ({
55
- ...placement.insertAfter !== void 0 && { insertAfter: placement.insertAfter },
56
- ...placement.insertBefore !== void 0 && { insertBefore: placement.insertBefore }
57
- });
58
40
  const withSessionLostFallback = (transport, latest) => {
59
41
  const [transportOptions, ...rest] = transport.args;
60
42
  if (rest.length > 0 || typeof transportOptions !== "object" || transportOptions === null) throw new Error("statewire: onCommandSessionLost requires a transport element that takes a single options object");
@@ -128,80 +110,41 @@ const useStatewireThread = (options) => {
128
110
  if (steerQueueItems !== void 0 && queueItems === void 0) throw new Error("statewire: the converter's steerQueue projection requires the queue projection");
129
111
  const [queueSeam] = useState(() => ({ present: queueItems !== void 0 }));
130
112
  if (queueSeam.present !== (queueItems !== 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");
131
- const queue = useMemo(() => {
132
- if (!queueItems) return void 0;
133
- const laneOf = (queueItemId) => {
134
- if (steerQueueItems?.some((item) => item.id === queueItemId)) return "steer";
135
- if (queueItems.some((item_0) => item_0.id === queueItemId)) return "queue";
136
- throw new Error(`statewire: unknown queue item "${queueItemId}"`);
137
- };
138
- return {
139
- items: queueItems.map(toQueueItemState),
140
- steerItems: (steerQueueItems ?? []).map(toQueueItemState),
141
- enqueue: (message) => dispatch({
142
- type: "run/enqueue",
143
- message: toWireMessage(message, crypto.randomUUID())
144
- }),
145
- steer: (message_0) => dispatch({
146
- type: "run/steer",
147
- message: toWireMessage(message_0, crypto.randomUUID())
148
- }),
149
- move: (queueItemId_0, placement) => {
150
- const lane = placement.lane ?? laneOf(queueItemId_0);
151
- const fields = {
152
- messageId: queueItemId_0,
153
- ...placementFields(placement)
154
- };
155
- dispatch(lane === "steer" ? {
156
- type: "run/steer",
157
- ...fields
158
- } : {
159
- type: "run/enqueue",
160
- ...fields
161
- });
162
- },
163
- edit: (queueItemId_1, message_1) => {
164
- const wireMessage = toWireMessage(message_1, queueItemId_1);
165
- dispatch(laneOf(queueItemId_1) === "steer" ? {
166
- type: "run/steer",
167
- message: wireMessage
168
- } : {
169
- type: "run/enqueue",
170
- message: wireMessage
171
- });
172
- },
173
- remove: (queueItemId_2) => dispatch({
174
- type: "run/dequeue",
175
- messageId: queueItemId_2
176
- })
177
- };
178
- }, [
113
+ const queue = useMemo(() => queueItems ? createRunQueueAdapter(queueItems, steerQueueItems, dispatch) : void 0, [
179
114
  queueItems,
180
115
  steerQueueItems,
181
116
  dispatch
182
117
  ]);
118
+ const inputRequests = converted.inputRequests;
119
+ const [inputSeam] = useState(() => ({ present: inputRequests !== void 0 }));
120
+ 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");
183
121
  const extras = useMemo(() => ({
184
122
  [symbolAssistantTransportExtras]: true,
185
123
  sendCommand: dispatch,
186
124
  reconnect: connection.reconnect,
187
- state
125
+ state,
126
+ ...inputRequests !== void 0 && { inputRequests }
188
127
  }), [
189
128
  dispatch,
190
129
  connection.reconnect,
191
- state
130
+ state,
131
+ inputRequests
192
132
  ]);
193
- const handleAppend = (message_2) => {
194
- const command_1 = convertAppendMessageToCommand(message_2);
133
+ const handleAppend = (message) => {
134
+ const command_1 = convertAppendMessageToCommand(message);
195
135
  if (!command_1) return;
196
136
  dispatch(command_1);
197
137
  };
198
- const handleEdit = (message_3) => {
199
- if (!queueItems) return handleAppend(message_3);
200
- if (message_3.sourceId == null) throw new Error("statewire: run/edit requires a sourceId");
138
+ const handleReload = (parentId) => {
139
+ dispatch(resolveReloadCommand(converted.messages, parentId));
140
+ };
141
+ const handleEdit = (message_0) => {
142
+ if (!queueItems) return handleAppend(message_0);
143
+ if (message_0.sourceId == null) throw new Error("statewire: run/edit requires a sourceId");
201
144
  dispatch({
202
145
  type: "run/edit",
203
- message: toWireMessage(message_3, crypto.randomUUID()),
204
- sourceId: message_3.sourceId
146
+ message: toWireMessage(message_0, crypto.randomUUID()),
147
+ sourceId: message_0.sourceId
205
148
  });
206
149
  };
207
150
  return useResource(ExternalThread({
@@ -215,10 +158,26 @@ const useStatewireThread = (options) => {
215
158
  ...queue && { queue },
216
159
  ...options.capabilities?.edit && { onEdit: handleEdit },
217
160
  ...options.capabilities?.continue && { onResume: () => dispatch({ type: "run/continue" }) },
161
+ ...options.capabilities?.reload && { onReload: handleReload },
162
+ ...inputRequests !== void 0 && {
163
+ onAddToolResult: (toolOptions) => {
164
+ const inputCommand = resolveToolResultInput(inputRequests, toolOptions);
165
+ dispatch(inputCommand ?? {
166
+ type: "add-tool-result",
167
+ toolCallId: toolOptions.toolCallId,
168
+ toolName: toolOptions.toolName,
169
+ result: toolOptions.result,
170
+ isError: toolOptions.isError,
171
+ ...toolOptions.artifact !== void 0 && { artifact: toolOptions.artifact },
172
+ ...toolOptions.modelContent !== void 0 && { modelContent: toolOptions.modelContent }
173
+ });
174
+ },
175
+ onRespondToToolApproval: (approval) => dispatch(resolveToolApprovalInput(inputRequests, approval))
176
+ },
218
177
  onCancel: () => {
219
- const payload = latest.current.cancelPayload?.();
220
- if (payload !== void 0 && (typeof payload !== "object" || payload === null || Array.isArray(payload))) throw new Error("statewire: cancelPayload must return a plain object");
221
- commands["run/cancel"](...payload === void 0 ? [] : [payload]).catch((error_1) => {
178
+ const payload = latest.current.stopPayload?.();
179
+ if (payload !== void 0 && (typeof payload !== "object" || payload === null || Array.isArray(payload))) throw new Error("statewire: stopPayload must return a plain object");
180
+ commands["run/stop"](...payload === void 0 ? [] : [payload]).catch((error_1) => {
222
181
  latest.current.onError?.(error_1);
223
182
  });
224
183
  }