@assistant-ui/react-statewire 0.2.0 → 0.4.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":";;;;cA0Da;KAID;GACT;EACD,cAAc,SAAS;EACvB;EACA;;EAEA,yBAAyB;;cAGd,6BACX,oBACC;cAoVU,2BAA4B,GACvC,SAAS,0BAA0B,OAClC,gBAAgB"}
@@ -1,4 +1,6 @@
1
1
  import { AssistantTransportHost } from "./host.js";
2
+ import { createRunQueueAdapter, resolveReloadCommand, toWireMessage, viewedLeafId } 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,7 @@ 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
+ dispatch(resolveToolResultInput(convertedRef.current.inputRequests ?? [], command_0));
94
70
  },
95
71
  onStatusesChange: (statuses) => {
96
72
  setToolStatuses(statuses.size === 0 ? EMPTY_TOOL_STATUSES : Object.fromEntries(statuses));
@@ -106,43 +82,70 @@ const useAssistantTransportThread = (options) => {
106
82
  useEffect(() => () => {
107
83
  toolInvocations.reset();
108
84
  }, [toolInvocations]);
85
+ const inputRequests = converted.inputRequests;
86
+ const [inputSeam] = useState(() => ({ present: inputRequests !== void 0 }));
87
+ 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
88
  const extras = useMemo(() => ({
110
89
  [symbolAssistantTransportExtras]: true,
111
90
  sendCommand: dispatch,
112
91
  reconnect: connection.reconnect,
113
- state: agentState
92
+ state: agentState,
93
+ ...inputRequests !== void 0 && { inputRequests }
114
94
  }), [
115
95
  dispatch,
116
96
  connection.reconnect,
117
- agentState
97
+ agentState,
98
+ inputRequests
118
99
  ]);
119
100
  const handleAppend = (message) => {
120
101
  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 });
102
+ const command_1 = {
103
+ type: "run/steer",
104
+ message: toWireMessage(message, crypto.randomUUID()),
105
+ anchorMessageId: viewedLeafId(convertedRef.current.messages)
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(converted.messages, queueProjection, steerProjection, dispatch) : void 0, [
140
+ converted.messages,
141
+ queueProjection,
142
+ steerProjection,
143
+ dispatch
144
+ ]);
142
145
  const enableQueue = options.capabilities?.queue === true;
143
146
  const queueRef = useRef(null);
144
147
  if (enableQueue && !queueRef.current) queueRef.current = createMessageQueue({
145
- run: (message_1, opts_0) => driverRef.current.run(message_1, opts_0),
148
+ run: (message_2, opts_0) => driverRef.current.run(message_2, opts_0),
146
149
  cancel: () => driverRef.current.cancel()
147
150
  });
148
151
  else if (!enableQueue && queueRef.current) {
@@ -168,36 +171,31 @@ const useAssistantTransportThread = (options) => {
168
171
  extras,
169
172
  attachmentAdapter: options.adapters?.attachments,
170
173
  onNew: handleAppend,
171
- ...messageQueue && { queue: {
174
+ ...serverQueue ? { queue: serverQueue } : messageQueue && { queue: {
172
175
  ...messageQueue.adapter,
173
176
  items: queueItems,
174
177
  steerItems: steerQueueItems
175
178
  } },
176
- ...options.capabilities?.edit && { onEdit: handleAppend },
179
+ ...options.capabilities?.edit && { onEdit: handleEdit },
177
180
  onReload: (parentId) => {
178
- toolInvocations.abort().then(() => {
179
- commands.reload(parentId).catch(() => {});
180
- });
181
+ const command_3 = resolveReloadCommand(convertedRef.current.messages, parentId);
182
+ toolInvocations.abort().then(() => dispatch(command_3));
181
183
  },
182
184
  onCancel: () => {
183
185
  messageQueue?.clear();
184
186
  handleCancel();
185
187
  },
186
188
  onResume: () => {
189
+ if (options.capabilities?.continue) {
190
+ dispatch({ type: "run/continue" });
191
+ return;
192
+ }
187
193
  if (!options.resumeApi) throw new Error("Must pass resumeApi to options to resume runs");
188
194
  commands.resume().catch(() => {});
189
195
  },
190
- onAddToolResult: (toolOptions) => {
191
- const command_2 = {
192
- type: "tool-result/add",
193
- toolCallId: toolOptions.toolCallId,
194
- result: toolOptions.result,
195
- toolName: toolOptions.toolName,
196
- isError: toolOptions.isError,
197
- ...toolOptions.artifact && { artifact: toolOptions.artifact },
198
- ...toolOptions.modelContent !== void 0 && { modelContent: toolOptions.modelContent }
199
- };
200
- dispatch(command_2);
196
+ ...inputRequests !== void 0 && {
197
+ onAddToolResult: (toolOptions) => dispatch(resolveToolResultInput(convertedRef.current.inputRequests, toolOptions)),
198
+ onRespondToToolApproval: (options_0) => dispatch(resolveToolApprovalInput(convertedRef.current.inputRequests, options_0))
201
199
  },
202
200
  onResumeToolCall: ({ toolCallId, payload }) => {
203
201
  if (!toolInvocations.resume(toolCallId, payload)) throw new Error(`Tool call ${toolCallId} is not waiting for resume.`);
@@ -217,6 +215,6 @@ const useAssistantTransportThread = (options) => {
217
215
  const AssistantTransportThread = (options) => resource(useAssistantTransportThread)(options);
218
216
  forwardTransformScopes(useAssistantTransportThread, ExternalThread(void 0).hook);
219
217
  //#endregion
220
- export { AssistantTransportThread, asAssistantTransportExtras, convertAppendMessageToCommand, symbolAssistantTransportExtras };
218
+ export { AssistantTransportThread, asAssistantTransportExtras, symbolAssistantTransportExtras };
221
219
 
222
220
  //# 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;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EACAsD,gBAAgB;GAEdnB,cAAcD,MAAM;GACpBT,aAAa;EACf;EACA8B,gBAAgB;GACd,IAAI,CAACjF,QAAQkF,WACX,MAAM,IAAI1G,MAAM,+CAA+C;GACjE,SAAc2G,OAAO,CAAC,CAACzD,YAAY,CAAC,CAAC;EACvC;EACA0D,kBAAkBC,gBAAsC;GACtD,MAAMlH,YAAgC;IACpCe,MAAM;IACNS,YAAY0F,YAAY1F;IACxB2F,QAAQD,YAAYC;IACpBC,UAAUF,YAAYE;IACtBC,SAASH,YAAYG;IACrB,GAAIH,YAAYI,YAAY,EAAEA,UAAUJ,YAAYI,SAAS;IAC7D,GAAIJ,YAAYK,iBAAiB5F,KAAAA,KAAa,EAC5C4F,cAAcL,YAAYK,aAC5B;GACF;GAEAnE,SAASpD,SAAO;EAClB;EACAwH,mBAAmB,EAAEhG,YAAYiG,cAAqC;GACpE,IAAI,CAAC3D,gBAAgBkD,OAAOxF,YAAYiG,OAAO,GAC7C,MAAM,IAAIpH,MAAM,aAAamB,WAAU,4BAA6B;EACxE;EACAkG,sBAAsBC,aAAsB;GAC1C,SAAcC,YAAYD,QAAQ,CAAC,CAACpE,YAAY,CAAC,CAAC;GAElDM,aAAa5B,UAAUJ,QAAQ6B,UAAUiE,UAAU;IACjD/D,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,MAAaqI,4BACXhG,YAEAnE,SAASkE,2BAA2B,CAAC,CACnCC,OACF;AAGF9D,uBACE6D,6BACA/D,eAAe8D,KAAAA,CAAkB,CAAC,CAACoG,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","useStatewire","AssistantTransportHost","AssistantTransportHostCommands","AssistantTransportHostState","HostQueueCell","HostRunContext","SendOptions","createRunQueueAdapter","resolveReloadCommand","toWireMessage","viewedLeafId","resolveToolApprovalInput","resolveToolResultInput","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","onStatusesChange","statuses","size","Object","fromEntries","setState","isRunning","isLoading","reset","inputSeam","present","handleAppend","startRun","role","crypto","randomUUID","anchorMessageId","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","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 { 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 viewedLeafId,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\nimport type {\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 dispatch(\n resolveToolResultInput(\n convertedRef.current.inputRequests ?? [],\n command,\n ),\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 anchorMessageId: viewedLeafId(convertedRef.current.messages),\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(\n converted.messages,\n queueProjection,\n steerProjection,\n dispatch,\n )\n : undefined,\n [converted.messages, 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 ...(inputRequests !== undefined && {\n onAddToolResult: (toolOptions: AddToolResultOptions) =>\n dispatch(\n resolveToolResultInput(\n convertedRef.current.inputRequests!,\n toolOptions,\n ),\n ),\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":";;;;;;;;;;;AAsDA,MAAMwC,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,YAAYtD,sBAAsB;CACxC,MAAM,CAACuD,iBAAiB/D,qBAAqC;EAC3D,MAAMgE,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,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H,gBAAgB;GAEdpB,cAAcD,MAAM;GACpBd,aAAa;EACf;EACAoC,gBAAgB;GACd,IAAIhG,QAAQqE,cAAc4B,UAAU;IAClC1E,SAAS,EAAE1B,MAAM,eAAe,CAAC;IACjC;GACF;GACA,IAAI,CAACG,QAAQkG,WACX,MAAM,IAAI7G,MAAM,+CAA+C;GACjE,SAAc8G,OAAO,CAAC,CAACzE,YAAY,CAAC,CAAC;EACvC;EACA,GAAIxC,kBAAkBY,KAAAA,KAAa;GACjCsG,kBAAkBC,gBAChB9E,SACEpD,uBACE6D,aAAa5B,QAAQlB,eACrBmH,WACF,CACF;GACFC,0BAA0BtG,cACxBuB,SACErD,yBACE8D,aAAa5B,QAAQlB,eACrBc,SACF,CACF;EACJ;EACAuG,mBAAmB,EAAE/G,YAAYgH,cAAqC;GACpE,IAAI,CAACvE,gBAAgBkE,OAAO3G,YAAYgH,OAAO,GAC7C,MAAM,IAAInH,MAAM,aAAaG,WAAU,4BAA6B;EACxE;EACAiH,sBAAsBC,aAAsB;GAC1C,SAAcC,YAAYD,QAAQ,CAAC,CAAChF,YAAY,CAAC,CAAC;GAElDM,aAAa5B,UAAUJ,QAAQ6B,UAAU6E,UAAU;IACjD3E,iBAAiB,CAAC,GAAGT,MAAMR,WAAW,GAAGQ,MAAMT,MAAM;IACrDO;IACAO,cAAcpD;GAChB,CAAC;GACD0D,gBAAgBW,MAAM;GACtBhB,gBAAgBrD,mBAAmB;EACrC;CACF,CAAC,CACH;AACF;AAEA,MAAaqI,4BACX5G,YAEA3D,SAAS0D,2BAA2B,CAAC,CACnCC,OACF;AAGFtD,uBACEqD,6BACAvD,eAAesD,KAAAA,CAAkB,CAAC,CAACgH,IACrC"}
@@ -33,6 +33,8 @@ declare namespace StatewireThread {
33
33
  readonly type: "run/enqueue";
34
34
  } & ({
35
35
  readonly message: UserMessage;
36
+ /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */
37
+ readonly anchorMessageId?: string | null;
36
38
  } | {
37
39
  readonly messageId: string;
38
40
  }) & Placement;
@@ -40,6 +42,8 @@ declare namespace StatewireThread {
40
42
  readonly type: "run/steer";
41
43
  } & ({
42
44
  readonly message: UserMessage;
45
+ /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */
46
+ readonly anchorMessageId?: string | null;
43
47
  } | {
44
48
  readonly messageId: string;
45
49
  }) & Placement;
@@ -55,7 +59,51 @@ declare namespace StatewireThread {
55
59
  type RunContinueCommand = {
56
60
  readonly type: "run/continue";
57
61
  };
58
- type RunCommand = RunEnqueueCommand | RunSteerCommand | RunDequeueCommand | RunEditCommand | RunContinueCommand;
62
+ type ToolCallInputRequest = {
63
+ readonly type: "tool-call";
64
+ readonly id: string;
65
+ readonly toolCallId: string;
66
+ };
67
+ type ToolApprovalInputRequest = {
68
+ readonly type: "tool-approval";
69
+ readonly id: string;
70
+ readonly toolCallId: string;
71
+ };
72
+ type CustomInputRequest = {
73
+ readonly type: string;
74
+ readonly id: string;
75
+ readonly [key: string]: ReadonlyJSONValue | undefined;
76
+ };
77
+ /** A host request parking the run until answered; open union for custom types. */
78
+ type InputRequest = ToolCallInputRequest | ToolApprovalInputRequest | CustomInputRequest;
79
+ type ToolCallInputResponse = {
80
+ readonly output: ReadonlyJSONValue;
81
+ /** Default false; when true, `output` carries the error payload. */
82
+ readonly isError?: boolean;
83
+ readonly artifact?: ReadonlyJSONValue;
84
+ };
85
+ type ToolApprovalInputResponse = {
86
+ readonly decision: "approve" | "reject" | "edit" | "respond";
87
+ readonly editedArgs?: ReadonlyJSONValue;
88
+ readonly message?: string;
89
+ };
90
+ type InputResponse = ReadonlyJSONValue;
91
+ type RunInputCommand = {
92
+ readonly type: "run/input";
93
+ readonly requestId: string;
94
+ readonly response: InputResponse;
95
+ };
96
+ /** An input request projected out of the host state with its response echo. */
97
+ type InputRequestState = InputRequest & {
98
+ readonly response: InputResponse | null;
99
+ };
100
+ type RunReloadCommand = {
101
+ readonly type: "run/reload";
102
+ readonly sourceId: string;
103
+ /** Client-generated id of the regenerated assistant message. */
104
+ readonly messageId: string;
105
+ };
106
+ type RunCommand = RunEnqueueCommand | RunSteerCommand | RunDequeueCommand | RunEditCommand | RunContinueCommand | RunReloadCommand | RunInputCommand;
59
107
  type Command = AssistantTransportCommand | RunCommand;
60
108
  /** A queued message projected out of the host state, wire shape. */
61
109
  type QueueItem = {
@@ -75,6 +123,13 @@ declare namespace StatewireThread {
75
123
  readonly queue?: readonly QueueItem[];
76
124
  /** The host's steer lane; requires `queue`. Absent means empty. */
77
125
  readonly steerQueue?: readonly QueueItem[];
126
+ /**
127
+ * The host's parked input requests projected out of the state. Returning
128
+ * it (even empty) routes tool results and approvals with a matching
129
+ * pending request through `run/input`. Presence must be stable across
130
+ * conversions.
131
+ */
132
+ readonly inputRequests?: readonly InputRequestState[];
78
133
  };
79
134
  type ConnectionMetadata = {
80
135
  pendingCommands: Command[];
@@ -84,10 +139,10 @@ declare namespace StatewireThread {
84
139
  };
85
140
  type StateConverter<T> = (state: T, connectionMetadata: ConnectionMetadata) => State;
86
141
  /**
87
- * Payload of the built-in `run/cancel` command. `reason` is the one well-known
142
+ * Payload of the built-in `run/stop` command. `reason` is the one well-known
88
143
  * field; apps extend it with their own JSON-serializable fields.
89
144
  */
90
- type CancelPayload = {
145
+ type StopPayload = {
91
146
  readonly reason?: string | undefined;
92
147
  readonly [key: string]: ReadonlyJSONValue | undefined;
93
148
  };
@@ -101,8 +156,8 @@ declare namespace StatewireThread {
101
156
  * on connect and whenever it changes. Requires a remote transport.
102
157
  */
103
158
  contextSync?: "command-send" | undefined;
104
- /** Supplies the `run/cancel` command's payload; omitted, cancel sends no payload. */
105
- cancelPayload?: (() => CancelPayload) | undefined;
159
+ /** Supplies the `run/stop` command's payload; omitted, stop sends no payload. */
160
+ stopPayload?: (() => StopPayload) | undefined;
106
161
  /**
107
162
  * Offered each pending command when a remote transport's session is
108
163
  * evicted; return "replay" to re-enqueue it under the rotated client id.
@@ -115,6 +170,8 @@ declare namespace StatewireThread {
115
170
  edit?: boolean | undefined;
116
171
  /** The host supports `run/continue` (a continue affordance on aborted runs). */
117
172
  continue?: boolean | undefined;
173
+ /** The host supports `run/reload` (regenerating an assistant message). */
174
+ reload?: boolean | undefined;
118
175
  } | undefined;
119
176
  adapters?: {
120
177
  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":";;;;;;;cA4Ra,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;;aAGI,SAAS;;aAET;;aAEA;OAEb;OAEU;aACD;;aAGI,SAAS;;aAET;;aAEA;OAEb;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;;aAEA;;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, viewedLeafId } 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,6 @@ 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
25
- });
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 }
31
- });
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");
38
- return {
39
- id,
40
- role: "user",
41
- parts
42
- };
43
- };
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
17
  const withSessionLostFallback = (transport, latest) => {
59
18
  const [transportOptions, ...rest] = transport.args;
60
19
  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 +87,43 @@ const useStatewireThread = (options) => {
128
87
  if (steerQueueItems !== void 0 && queueItems === void 0) throw new Error("statewire: the converter's steerQueue projection requires the queue projection");
129
88
  const [queueSeam] = useState(() => ({ present: queueItems !== void 0 }));
130
89
  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
- }, [
90
+ const queue = useMemo(() => queueItems ? createRunQueueAdapter(converted.messages, queueItems, steerQueueItems, dispatch) : void 0, [
91
+ converted.messages,
179
92
  queueItems,
180
93
  steerQueueItems,
181
94
  dispatch
182
95
  ]);
96
+ const inputRequests = converted.inputRequests;
97
+ const [inputSeam] = useState(() => ({ present: inputRequests !== void 0 }));
98
+ 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
99
  const extras = useMemo(() => ({
184
100
  [symbolAssistantTransportExtras]: true,
185
101
  sendCommand: dispatch,
186
102
  reconnect: connection.reconnect,
187
- state
103
+ state,
104
+ ...inputRequests !== void 0 && { inputRequests }
188
105
  }), [
189
106
  dispatch,
190
107
  connection.reconnect,
191
- state
108
+ state,
109
+ inputRequests
192
110
  ]);
193
- const handleAppend = (message_2) => {
194
- const command_1 = convertAppendMessageToCommand(message_2);
195
- if (!command_1) return;
196
- dispatch(command_1);
111
+ const handleAppend = (message) => {
112
+ dispatch({
113
+ type: "run/steer",
114
+ message: toWireMessage(message, crypto.randomUUID()),
115
+ anchorMessageId: viewedLeafId(converted.messages)
116
+ });
117
+ };
118
+ const handleReload = (parentId) => {
119
+ dispatch(resolveReloadCommand(converted.messages, parentId));
197
120
  };
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");
121
+ const handleEdit = (message_0) => {
122
+ if (message_0.sourceId == null) throw new Error("statewire: run/edit requires a sourceId");
201
123
  dispatch({
202
124
  type: "run/edit",
203
- message: toWireMessage(message_3, crypto.randomUUID()),
204
- sourceId: message_3.sourceId
125
+ message: toWireMessage(message_0, crypto.randomUUID()),
126
+ sourceId: message_0.sourceId
205
127
  });
206
128
  };
207
129
  return useResource(ExternalThread({
@@ -215,10 +137,15 @@ const useStatewireThread = (options) => {
215
137
  ...queue && { queue },
216
138
  ...options.capabilities?.edit && { onEdit: handleEdit },
217
139
  ...options.capabilities?.continue && { onResume: () => dispatch({ type: "run/continue" }) },
140
+ ...options.capabilities?.reload && { onReload: handleReload },
141
+ ...inputRequests !== void 0 && {
142
+ onAddToolResult: (toolOptions) => dispatch(resolveToolResultInput(inputRequests, toolOptions)),
143
+ onRespondToToolApproval: (approval) => dispatch(resolveToolApprovalInput(inputRequests, approval))
144
+ },
218
145
  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) => {
146
+ const payload = latest.current.stopPayload?.();
147
+ if (payload !== void 0 && (typeof payload !== "object" || payload === null || Array.isArray(payload))) throw new Error("statewire: stopPayload must return a plain object");
148
+ commands["run/stop"](...payload === void 0 ? [] : [payload]).catch((error_1) => {
222
149
  latest.current.onError?.(error_1);
223
150
  });
224
151
  }