@assistant-ui/react-statewire 0.1.1 → 0.2.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,4 +1,4 @@
1
- import { AddMessageCommand, AssistantTransportCommand, AssistantTransportOptions } from "./types.js";
1
+ import { AssistantTransportCommand, AssistantTransportOptions, MessageAddCommand } from "./types.js";
2
2
  import { ResourceElement } from "@assistant-ui/tap";
3
3
  import { ClientOutput } from "@assistant-ui/store";
4
4
  import { AppendMessage } from "@assistant-ui/core";
@@ -11,7 +11,7 @@ type AssistantTransportExtras = {
11
11
  state: unknown;
12
12
  };
13
13
  declare const asAssistantTransportExtras: (extras: unknown) => AssistantTransportExtras;
14
- declare const convertAppendMessageToCommand: (message: AppendMessage) => AddMessageCommand | null;
14
+ declare const convertAppendMessageToCommand: (message: AppendMessage) => MessageAddCommand | null;
15
15
  declare const AssistantTransportThread: <T>(options: AssistantTransportOptions<T>) => ResourceElement<ClientOutput<"thread">>;
16
16
  //#endregion
17
17
  export { AssistantTransportExtras, AssistantTransportThread, asAssistantTransportExtras, convertAppendMessageToCommand, symbolAssistantTransportExtras };
@@ -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;cAkRU,2BAA4B,GACvC,SAAS,0BAA0B,OAClC,gBAAgB"}
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"}
@@ -29,7 +29,7 @@ const convertAppendMessageToCommand = (message) => {
29
29
  });
30
30
  if (parts.length === 0) return null;
31
31
  return {
32
- type: "add-message",
32
+ type: "message/add",
33
33
  message: {
34
34
  role: "user",
35
35
  parts
@@ -87,7 +87,10 @@ const useAssistantTransportThread = (options) => {
87
87
  onResult: (command_0) => {
88
88
  const messages = convertedRef.current.messages;
89
89
  if (!messagesContainToolCall(messages, command_0.toolCallId)) return;
90
- dispatch(command_0);
90
+ dispatch({
91
+ ...command_0,
92
+ type: "tool-result/add"
93
+ });
91
94
  },
92
95
  onStatusesChange: (statuses) => {
93
96
  setToolStatuses(statuses.size === 0 ? EMPTY_TOOL_STATUSES : Object.fromEntries(statuses));
@@ -143,11 +146,12 @@ const useAssistantTransportThread = (options) => {
143
146
  cancel: () => driverRef.current.cancel()
144
147
  });
145
148
  else if (!enableQueue && queueRef.current) {
146
- queueRef.current.adapter.clear("cancel-run");
149
+ queueRef.current.clear();
147
150
  queueRef.current = null;
148
151
  }
149
152
  const messageQueue = queueRef.current;
150
153
  const queueItems = useSyncExternalStore(messageQueue?.subscribe ?? subscribeNoop, () => messageQueue?.adapter.items ?? EMPTY_QUEUE_ITEMS, () => EMPTY_QUEUE_ITEMS);
154
+ const steerQueueItems = useSyncExternalStore(messageQueue?.subscribe ?? subscribeNoop, () => messageQueue?.adapter.steerItems ?? EMPTY_QUEUE_ITEMS, () => EMPTY_QUEUE_ITEMS);
151
155
  const busy = isSending || converted.isRunning || Object.keys(toolStatuses).length > 0;
152
156
  const wasBusyRef = useRef(false);
153
157
  useEffect(() => {
@@ -166,7 +170,8 @@ const useAssistantTransportThread = (options) => {
166
170
  onNew: handleAppend,
167
171
  ...messageQueue && { queue: {
168
172
  ...messageQueue.adapter,
169
- items: queueItems
173
+ items: queueItems,
174
+ steerItems: steerQueueItems
170
175
  } },
171
176
  ...options.capabilities?.edit && { onEdit: handleAppend },
172
177
  onReload: (parentId) => {
@@ -174,14 +179,17 @@ const useAssistantTransportThread = (options) => {
174
179
  commands.reload(parentId).catch(() => {});
175
180
  });
176
181
  },
177
- onCancel: handleCancel,
182
+ onCancel: () => {
183
+ messageQueue?.clear();
184
+ handleCancel();
185
+ },
178
186
  onResume: () => {
179
187
  if (!options.resumeApi) throw new Error("Must pass resumeApi to options to resume runs");
180
188
  commands.resume().catch(() => {});
181
189
  },
182
190
  onAddToolResult: (toolOptions) => {
183
191
  const command_2 = {
184
- type: "add-tool-result",
192
+ type: "tool-result/add",
185
193
  toolCallId: toolOptions.toolCallId,
186
194
  result: toolOptions.result,
187
195
  toolName: toolOptions.toolName,
@@ -1 +1 @@
1
- {"version":3,"file":"AssistantTransportThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","useSyncExternalStore","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","createMessageQueue","AddToolResultOptions","AppendMessage","MessageQueueController","MessageQueueDriver","ResumeToolCallOptions","ThreadMessage","ToolExecutionStatus","ToolInvocationTracker","ReadonlyJSONObject","useStatewire","AssistantTransportHost","AssistantTransportHostCommands","AssistantTransportHostState","HostQueueCell","HostRunContext","SendOptions","AddMessageCommand","AddToolResultCommand","AssistantTransportCommand","AssistantTransportOptions","UserMessagePart","EMPTY_TOOL_STATUSES","Record","EMPTY_QUEUE_ITEMS","subscribeNoop","symbolAssistantTransportExtras","Symbol","AssistantTransportExtras","sendCommand","command","reconnect","state","asAssistantTransportExtras","extras","Error","convertAppendMessageToCommand","message","role","parts","content","attachments","flatMap","a","contentPart","type","push","text","image","length","parentId","sourceId","messagesContainToolCall","messages","toolCallId","some","part","undefined","useAssistantTransportThread","options","clientRef","getRunContext","aui","current","parent","threadId","threadListItem","getState","remoteId","modelContext","getModelContext","queueCell","queued","inTransit","commands","connection","transport","agent","agentState","isSending","isReplaying","queue","dispatch","opts","send","catch","toolStatuses","setToolStatuses","converter","converted","pendingCommands","convertedRef","toolInvocations","tools","onResult","onStatusesChange","statuses","size","Object","fromEntries","setState","isRunning","isLoading","reset","handleAppend","startRun","setParentId","schedule","abort","then","handleCancel","cancel","driverRef","run","at","id","enableQueue","capabilities","queueRef","adapter","clear","messageQueue","queueItems","subscribe","items","busy","keys","wasBusyRef","notifyBusy","notifyIdle","attachmentAdapter","adapters","onNew","edit","onEdit","onReload","reload","onCancel","onResume","resumeApi","resume","onAddToolResult","toolOptions","result","toolName","isError","artifact","modelContent","onResumeToolCall","payload","onLoadExternalState","imported","importState","AssistantTransportThread","T","hook"],"sources":["../src/AssistantTransportThread.ts"],"sourcesContent":["import {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport { resource, useResource } from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/react\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/react\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport { createMessageQueue } from \"@assistant-ui/core\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n MessageQueueController,\n MessageQueueDriver,\n ResumeToolCallOptions,\n ThreadMessage,\n ToolExecutionStatus,\n} from \"@assistant-ui/core\";\nimport { ToolInvocationTracker } from \"@assistant-ui/core/internal\";\nimport type { ReadonlyJSONObject } from \"assistant-stream/utils\";\nimport { useStatewire } from \"statewire\";\nimport { AssistantTransportHost } from \"./host\";\nimport type {\n AssistantTransportHostCommands,\n AssistantTransportHostState,\n HostQueueCell,\n HostRunContext,\n SendOptions,\n} from \"./host\";\nimport type {\n AddMessageCommand,\n AddToolResultCommand,\n AssistantTransportCommand,\n AssistantTransportOptions,\n UserMessagePart,\n} from \"./types\";\n\nconst EMPTY_TOOL_STATUSES: Record<string, ToolExecutionStatus> = {};\nconst EMPTY_QUEUE_ITEMS: MessageQueueController[\"adapter\"][\"items\"] = [];\nconst subscribeNoop = () => () => {};\n\nexport const symbolAssistantTransportExtras = Symbol(\n \"assistant-transport-extras\",\n);\n\nexport type AssistantTransportExtras = {\n [symbolAssistantTransportExtras]: true;\n sendCommand: (command: AssistantTransportCommand) => void;\n reconnect: () => void;\n state: unknown;\n};\n\nexport const asAssistantTransportExtras = (\n extras: unknown,\n): AssistantTransportExtras => {\n if (\n typeof extras !== \"object\" ||\n extras == null ||\n !(symbolAssistantTransportExtras in extras)\n )\n throw new Error(\n \"This method can only be called when you are using AssistantTransportThread or StatewireThread\",\n );\n\n return extras as AssistantTransportExtras;\n};\n\nexport const convertAppendMessageToCommand = (\n message: AppendMessage,\n): AddMessageCommand | null => {\n if (message.role !== \"user\")\n throw new Error(\"Only user messages are supported\");\n\n const parts: UserMessagePart[] = [];\n const content = [\n ...message.content,\n ...(message.attachments?.flatMap((a) => a.content) ?? []),\n ];\n for (const contentPart of content) {\n if (contentPart.type === \"text\") {\n parts.push({ type: \"text\", text: contentPart.text });\n } else if (contentPart.type === \"image\") {\n parts.push({ type: \"image\", image: contentPart.image });\n }\n }\n\n if (parts.length === 0) return null;\n\n return {\n type: \"add-message\",\n message: {\n role: \"user\",\n parts,\n },\n parentId: message.parentId,\n sourceId: message.sourceId,\n };\n};\n\nconst messagesContainToolCall = (\n messages: readonly ThreadMessage[],\n toolCallId: string,\n): boolean =>\n messages.some((message) =>\n message.content.some(\n (part) =>\n part.type === \"tool-call\" &&\n (part.toolCallId === toolCallId ||\n (part.messages !== undefined &&\n messagesContainToolCall(part.messages, toolCallId))),\n ),\n );\n\nconst useAssistantTransportThread = (\n options: AssistantTransportOptions<any>,\n): ClientOutput<\"thread\"> => {\n const clientRef = useAssistantClientRef();\n const [getRunContext] = useState(() => (): HostRunContext => {\n const aui = clientRef.current ?? clientRef.parent;\n // legacy parity: a threadListItem throw must not kill the run\n let threadId: string | null = null;\n try {\n threadId = aui.threadListItem().getState().remoteId ?? null;\n } catch {}\n return {\n modelContext: aui.modelContext().getModelContext(),\n threadId,\n };\n });\n\n const [queueCell] = useState(\n (): HostQueueCell => ({ current: { queued: [], inTransit: [] } }),\n );\n const { state, commands, connection } = useStatewire<\n AssistantTransportHostState,\n AssistantTransportHostCommands\n >({\n transport: AssistantTransportHost({ ...options, getRunContext, queueCell }),\n });\n const { agent: agentState, isSending, isReplaying } = state;\n const queue = queueCell.current;\n\n const dispatch = useCallback(\n (command: AssistantTransportCommand, opts?: SendOptions) => {\n void commands.send(command, opts).catch(() => {});\n },\n [commands],\n );\n\n const [toolStatuses, setToolStatuses] =\n useState<Record<string, ToolExecutionStatus>>(EMPTY_TOOL_STATUSES);\n\n const { converter } = options;\n const converted = useMemo(\n () =>\n converter(agentState, {\n pendingCommands: [...queue.inTransit, ...queue.queued],\n isSending,\n toolStatuses,\n }),\n [converter, agentState, queue, isSending, toolStatuses],\n );\n const convertedRef = useRef(converted);\n convertedRef.current = converted;\n\n const [toolInvocations] = useState(\n () =>\n new ToolInvocationTracker(\n () => {\n const aui = clientRef.current ?? clientRef.parent;\n return aui.modelContext().getModelContext().tools;\n },\n {\n onResult: (command) => {\n const messages = convertedRef.current\n .messages as readonly ThreadMessage[];\n if (!messagesContainToolCall(messages, command.toolCallId)) return;\n dispatch(command);\n },\n onStatusesChange: (statuses) => {\n setToolStatuses(\n statuses.size === 0\n ? EMPTY_TOOL_STATUSES\n : Object.fromEntries(statuses),\n );\n },\n },\n ),\n );\n // dep-less by design: setState dedups identical snapshots internally\n useEffect(() => {\n toolInvocations.setState({\n messages: converted.messages as readonly ThreadMessage[],\n isRunning: converted.isRunning,\n isLoading: isReplaying,\n });\n });\n useEffect(\n () => () => {\n toolInvocations.reset();\n },\n [toolInvocations],\n );\n\n const extras = useMemo(\n (): AssistantTransportExtras => ({\n [symbolAssistantTransportExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state: agentState,\n }),\n [dispatch, connection.reconnect, agentState],\n );\n\n const handleAppend = (message: AppendMessage) => {\n const startRun = message.startRun ?? message.role === \"user\";\n const command = convertAppendMessageToCommand(message);\n void commands.setParentId(message.parentId).catch(() => {});\n\n const send = () => {\n if (!command) return;\n dispatch(command, { schedule: startRun });\n };\n if (startRun) {\n // abort in-flight tool executions so their late results cannot race the new turn\n void toolInvocations.abort().then(send);\n } else {\n send();\n }\n };\n\n const handleCancel = () => {\n void toolInvocations.abort();\n void commands.cancel().catch(() => {});\n };\n\n const driverRef = useRef<{\n run: MessageQueueDriver[\"run\"];\n cancel: () => void;\n }>(undefined as never);\n driverRef.current = {\n // the queued message was stamped with the head at enqueue time; restamp so\n // it appends to the thread the finished run left behind\n run: (message) =>\n handleAppend({\n ...message,\n parentId: convertedRef.current.messages.at(-1)?.id ?? null,\n }),\n cancel: handleCancel,\n };\n\n const enableQueue = options.capabilities?.queue === true;\n const queueRef = useRef<MessageQueueController | null>(null);\n if (enableQueue && !queueRef.current) {\n queueRef.current = createMessageQueue({\n run: (message, opts) => driverRef.current.run(message, opts),\n cancel: () => driverRef.current.cancel(),\n });\n } else if (!enableQueue && queueRef.current) {\n queueRef.current.adapter.clear(\"cancel-run\");\n queueRef.current = null;\n }\n const messageQueue = queueRef.current;\n\n // fresh view per snapshot: the controller mutates adapter.items in place,\n // which a stable prop identity would hide from the thread resource\n const queueItems = useSyncExternalStore(\n messageQueue?.subscribe ?? subscribeNoop,\n () => messageQueue?.adapter.items ?? EMPTY_QUEUE_ITEMS,\n () => EMPTY_QUEUE_ITEMS,\n );\n\n // settled edge: the queue only advances once the host run loop has fully\n // released (isSending), the converted state agrees, and no client tool from\n // the finished run is still executing\n const busy =\n isSending || converted.isRunning || Object.keys(toolStatuses).length > 0;\n const wasBusyRef = useRef(false);\n useEffect(() => {\n if (wasBusyRef.current === busy) return;\n wasBusyRef.current = busy;\n if (busy) messageQueue?.notifyBusy();\n else messageQueue?.notifyIdle();\n });\n\n return useResource(\n ExternalThread({\n messages: converted.messages as readonly ExternalThreadMessage[],\n isRunning: converted.isRunning,\n isLoading: isReplaying,\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n onNew: handleAppend,\n ...(messageQueue && {\n queue: { ...messageQueue.adapter, items: queueItems },\n }),\n ...(options.capabilities?.edit && { onEdit: handleAppend }),\n onReload: (parentId: string | null) => {\n void toolInvocations.abort().then(() => {\n void commands.reload(parentId).catch(() => {});\n });\n },\n onCancel: handleCancel,\n onResume: () => {\n if (!options.resumeApi)\n throw new Error(\"Must pass resumeApi to options to resume runs\");\n void commands.resume().catch(() => {});\n },\n onAddToolResult: (toolOptions: AddToolResultOptions) => {\n const command: AddToolResultCommand = {\n type: \"add-tool-result\",\n toolCallId: toolOptions.toolCallId,\n result: toolOptions.result as ReadonlyJSONObject,\n toolName: toolOptions.toolName,\n isError: toolOptions.isError,\n ...(toolOptions.artifact && { artifact: toolOptions.artifact }),\n ...(toolOptions.modelContent !== undefined && {\n modelContent: toolOptions.modelContent,\n }),\n };\n\n dispatch(command);\n },\n onResumeToolCall: ({ toolCallId, payload }: ResumeToolCallOptions) => {\n if (!toolInvocations.resume(toolCallId, payload))\n throw new Error(`Tool call ${toolCallId} is not waiting for resume.`);\n },\n onLoadExternalState: (imported: unknown) => {\n void commands.importState(imported).catch(() => {});\n // reset() aborts tools before React re-renders — gate their late results against the imported state\n convertedRef.current = options.converter(imported, {\n pendingCommands: [...queue.inTransit, ...queue.queued],\n isSending,\n toolStatuses: EMPTY_TOOL_STATUSES,\n });\n toolInvocations.reset();\n setToolStatuses(EMPTY_TOOL_STATUSES);\n },\n }),\n );\n};\n\nexport const AssistantTransportThread = <T>(\n options: AssistantTransportOptions<T>,\n): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useAssistantTransportThread)(\n options as AssistantTransportOptions<any>,\n );\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useAssistantTransportThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;;AA8CA,MAAMoC,sBAA2D,CAAC;AAClE,MAAME,oBAAgE,CAAA;AACtE,MAAMC,4BAA4B,CAAC;AAEnC,MAAaC,iCAAiCC,OAC5C,4BACF;AASA,MAAaM,8BACXC,WAC6B;CAC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F,QAAQD,YAAYC;IACpBC,UAAUF,YAAYE;IACtBC,SAASH,YAAYG;IACrB,GAAIH,YAAYI,YAAY,EAAEA,UAAUJ,YAAYI,SAAS;IAC7D,GAAIJ,YAAYK,iBAAiB1F,KAAAA,KAAa,EAC5C0F,cAAcL,YAAYK,aAC5B;GACF;GAEAjE,SAASpD,SAAO;EAClB;EACAsH,mBAAmB,EAAE9F,YAAY+F,cAAqC;GACpE,IAAI,CAACzD,gBAAgBgD,OAAOtF,YAAY+F,OAAO,GAC7C,MAAM,IAAIlH,MAAM,aAAamB,WAAU,4BAA6B;EACxE;EACAgG,sBAAsBC,aAAsB;GAC1C,SAAcC,YAAYD,QAAQ,CAAC,CAAClE,YAAY,CAAC,CAAC;GAElDM,aAAa5B,UAAUJ,QAAQ6B,UAAU+D,UAAU;IACjD7D,iBAAiB,CAAC,GAAGT,MAAMR,WAAW,GAAGQ,MAAMT,MAAM;IACrDO;IACAO,cAAchE;GAChB,CAAC;GACDsE,gBAAgBW,MAAM;GACtBhB,gBAAgBjE,mBAAmB;EACrC;CACF,CAAC,CACH;AACF;AAEA,MAAamI,4BACX9F,YAEAnE,SAASkE,2BAA2B,CAAC,CACnCC,OACF;AAGF9D,uBACE6D,6BACA/D,eAAe8D,KAAAA,CAAkB,CAAC,CAACkG,IACrC"}
1
+ {"version":3,"file":"AssistantTransportThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","useSyncExternalStore","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","createMessageQueue","AddToolResultOptions","AppendMessage","MessageQueueController","MessageQueueDriver","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,MAA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IpH,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"}
@@ -8,31 +8,83 @@ import { ReadonlyJSONValue } from "assistant-stream/utils";
8
8
  declare const StatewireThread: <T>(options: StatewireThread.Options<T>) => ResourceElement<ClientOutput<"thread">>;
9
9
  declare namespace StatewireThread {
10
10
  type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;
11
+ type TextPart = {
12
+ readonly type: "text";
13
+ readonly text: string;
14
+ };
15
+ type FilePart = {
16
+ readonly type: "file";
17
+ readonly mediaType: string;
18
+ readonly url: string;
19
+ readonly filename?: string;
20
+ };
21
+ type UserMessage = {
22
+ readonly id: string;
23
+ readonly role: "user";
24
+ readonly parts: readonly (TextPart | FilePart)[];
25
+ readonly metadata?: Record<string, unknown>;
26
+ };
27
+ /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */
28
+ type Placement = {
29
+ readonly insertAfter?: string | null;
30
+ readonly insertBefore?: string | null;
31
+ };
32
+ type RunEnqueueCommand = {
33
+ readonly type: "run/enqueue";
34
+ } & ({
35
+ readonly message: UserMessage;
36
+ } | {
37
+ readonly messageId: string;
38
+ }) & Placement;
39
+ type RunSteerCommand = {
40
+ readonly type: "run/steer";
41
+ } & ({
42
+ readonly message: UserMessage;
43
+ } | {
44
+ readonly messageId: string;
45
+ }) & Placement;
46
+ type RunDequeueCommand = {
47
+ readonly type: "run/dequeue";
48
+ readonly messageId: string;
49
+ };
50
+ type RunEditCommand = {
51
+ readonly type: "run/edit";
52
+ readonly message: UserMessage;
53
+ readonly sourceId: string;
54
+ };
55
+ type RunContinueCommand = {
56
+ readonly type: "run/continue";
57
+ };
58
+ type RunCommand = RunEnqueueCommand | RunSteerCommand | RunDequeueCommand | RunEditCommand | RunContinueCommand;
59
+ type Command = AssistantTransportCommand | RunCommand;
60
+ /** A queued message projected out of the host state, wire shape. */
11
61
  type QueueItem = {
12
62
  readonly id: string;
13
- readonly prompt: string;
63
+ readonly parts: readonly (TextPart | FilePart)[];
14
64
  };
15
65
  type State = {
16
66
  readonly messages: readonly ThreadMessage[];
17
67
  readonly state?: ReadonlyJSONValue;
18
68
  readonly isRunning: boolean;
19
69
  /**
20
- * Server-owned message queue projected out of the state. Returning it
21
- * (even empty) turns on the queue capability: sends during a run become
22
- * `enqueue-message` commands and item controls send the queue commands.
23
- * Presence must be stable across conversions.
70
+ * The host's regular queue lane projected out of the state. Returning it
71
+ * (even empty) turns on the queue capability: sends become `run/enqueue`
72
+ * / `run/steer` commands and item controls send the `run/*` queue
73
+ * commands. Presence must be stable across conversions.
24
74
  */
25
75
  readonly queue?: readonly QueueItem[];
76
+ /** The host's steer lane; requires `queue`. Absent means empty. */
77
+ readonly steerQueue?: readonly QueueItem[];
26
78
  };
27
79
  type ConnectionMetadata = {
28
- pendingCommands: AssistantTransportCommand[];
80
+ pendingCommands: Command[];
29
81
  isSending: boolean;
30
82
  /** Statewire connection status; local transports are always `live`. */
31
83
  connection: StatewireClient.ConnectionState;
32
84
  };
33
85
  type StateConverter<T> = (state: T, connectionMetadata: ConnectionMetadata) => State;
34
86
  /**
35
- * Payload of the built-in `cancel` command. `reason` is the one well-known
87
+ * Payload of the built-in `run/cancel` command. `reason` is the one well-known
36
88
  * field; apps extend it with their own JSON-serializable fields.
37
89
  */
38
90
  type CancelPayload = {
@@ -49,11 +101,20 @@ declare namespace StatewireThread {
49
101
  * on connect and whenever it changes. Requires a remote transport.
50
102
  */
51
103
  contextSync?: "command-send" | undefined;
52
- /** Supplies the `cancel` command's payload; omitted, cancel sends no payload. */
104
+ /** Supplies the `run/cancel` command's payload; omitted, cancel sends no payload. */
53
105
  cancelPayload?: (() => CancelPayload) | undefined;
106
+ /**
107
+ * Offered each pending command when a remote transport's session is
108
+ * evicted; return "replay" to re-enqueue it under the rotated client id.
109
+ * A callback set on the transport options is consulted first; this one
110
+ * runs for commands it declined.
111
+ */
112
+ onCommandSessionLost?: ((command: StatewireClient.SessionLostCommand) => "replay" | void) | undefined;
54
113
  onError?: ((error: Error) => void) | undefined;
55
114
  capabilities?: {
56
115
  edit?: boolean | undefined;
116
+ /** The host supports `run/continue` (a continue affordance on aborted runs). */
117
+ continue?: boolean | undefined;
57
118
  } | undefined;
58
119
  adapters?: {
59
120
  attachments?: AttachmentAdapter | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;;cAgNa,kBAAmB,GAC9B,SAAS,gBAAgB,QAAQ,OAChC,gBAAgB;kBAGF;OACH,UAAU,KAAK,gBAAgB,UAAU;OAEzC;aACD;aACA;;OAGC;aACD,mBAAmB;aACnB,QAAQ;aACR;;;;;;;aAOA,iBAAiB;;OAGhB;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;IACvB,YAAY,OAAO;IACnB;MAEM;;IAGN;MAEM,cAAc"}
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"}
@@ -12,13 +12,68 @@ const ambientContextOf = (context) => ({
12
12
  ...context.callSettings !== void 0 && { callSettings: context.callSettings },
13
13
  ...context.config !== void 0 && { config: context.config }
14
14
  });
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
+ const withSessionLostFallback = (transport, latest) => {
59
+ const [transportOptions, ...rest] = transport.args;
60
+ if (rest.length > 0 || typeof transportOptions !== "object" || transportOptions === null) throw new Error("statewire: onCommandSessionLost requires a transport element that takes a single options object");
61
+ const transportLevel = transportOptions.onCommandSessionLost;
62
+ return {
63
+ ...transport,
64
+ args: [{
65
+ ...transportOptions,
66
+ onCommandSessionLost: (command) => transportLevel?.(command) ?? latest.current.onCommandSessionLost?.(command)
67
+ }]
68
+ };
69
+ };
15
70
  const useStatewireThread = (options) => {
16
71
  const latest = useRef(options);
17
72
  latest.current = options;
18
73
  const [pending, setPending] = useState([]);
19
74
  const [retire] = useState(() => (command) => setPending((prev) => prev.includes(command) ? prev.filter((c) => c !== command) : prev));
20
75
  const { state: transportState, commands, connection, setContext } = useStatewire({
21
- transport: options.transport,
76
+ transport: options.onCommandSessionLost === void 0 ? options.transport : withSessionLostFallback(options.transport, latest),
22
77
  onCommandChange: (update) => {
23
78
  if (update.status === "acked" || update.status === "settled") retire(update.params[0]);
24
79
  }
@@ -68,35 +123,63 @@ const useStatewireThread = (options) => {
68
123
  state,
69
124
  metadata
70
125
  ]);
71
- const convertedRef = useRef(converted);
72
- convertedRef.current = converted;
73
126
  const queueItems = converted.queue;
127
+ const steerQueueItems = converted.steerQueue;
128
+ if (steerQueueItems !== void 0 && queueItems === void 0) throw new Error("statewire: the converter's steerQueue projection requires the queue projection");
74
129
  const [queueSeam] = useState(() => ({ present: queueItems !== void 0 }));
75
130
  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");
76
- const queue = useMemo(() => queueItems && {
77
- items: queueItems,
78
- enqueue: (message, { steer }) => {
79
- const command_1 = convertAppendMessageToCommand(message);
80
- if (!command_1) return;
81
- dispatch(convertedRef.current.isRunning ? {
82
- ...command_1,
83
- type: "enqueue-message",
84
- steer
85
- } : command_1);
86
- },
87
- steer: (queueItemId) => dispatch({
88
- type: "steer-queue-item",
89
- queueItemId
90
- }),
91
- remove: (queueItemId_0) => dispatch({
92
- type: "remove-queue-item",
93
- queueItemId: queueItemId_0
94
- }),
95
- clear: (reason) => dispatch({
96
- type: "clear-queue",
97
- reason
98
- })
99
- }, [queueItems, dispatch]);
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
+ }, [
179
+ queueItems,
180
+ steerQueueItems,
181
+ dispatch
182
+ ]);
100
183
  const extras = useMemo(() => ({
101
184
  [symbolAssistantTransportExtras]: true,
102
185
  sendCommand: dispatch,
@@ -107,10 +190,19 @@ const useStatewireThread = (options) => {
107
190
  connection.reconnect,
108
191
  state
109
192
  ]);
110
- const handleAppend = (message_0) => {
111
- const command_2 = convertAppendMessageToCommand(message_0);
112
- if (!command_2) return;
113
- dispatch(command_2);
193
+ const handleAppend = (message_2) => {
194
+ const command_1 = convertAppendMessageToCommand(message_2);
195
+ if (!command_1) return;
196
+ dispatch(command_1);
197
+ };
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");
201
+ dispatch({
202
+ type: "run/edit",
203
+ message: toWireMessage(message_3, crypto.randomUUID()),
204
+ sourceId: message_3.sourceId
205
+ });
114
206
  };
115
207
  return useResource(ExternalThread({
116
208
  messages: converted.messages,
@@ -121,11 +213,12 @@ const useStatewireThread = (options) => {
121
213
  attachmentAdapter: options.adapters?.attachments,
122
214
  onNew: handleAppend,
123
215
  ...queue && { queue },
124
- ...options.capabilities?.edit && { onEdit: handleAppend },
216
+ ...options.capabilities?.edit && { onEdit: handleEdit },
217
+ ...options.capabilities?.continue && { onResume: () => dispatch({ type: "run/continue" }) },
125
218
  onCancel: () => {
126
219
  const payload = latest.current.cancelPayload?.();
127
220
  if (payload !== void 0 && (typeof payload !== "object" || payload === null || Array.isArray(payload))) throw new Error("statewire: cancelPayload must return a plain object");
128
- commands["cancel"](...payload === void 0 ? [] : [payload]).catch((error_1) => {
221
+ commands["run/cancel"](...payload === void 0 ? [] : [payload]).catch((error_1) => {
129
222
  latest.current.onError?.(error_1);
130
223
  });
131
224
  }
@@ -1 +1 @@
1
- {"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","AppendMessage","AttachmentAdapter","ExternalThreadQueueAdapter","ModelContext","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","StatewireClient","convertAppendMessageToCommand","symbolAssistantTransportExtras","AssistantTransportExtras","AssistantTransportCommand","AnyCommands","Record","args","ambientContextOf","context","system","undefined","tools","callSettings","config","useStatewireThread","options","StatewireThread","Options","latest","current","pending","setPending","retire","command","prev","includes","filter","c","state","transportState","commands","connection","setContext","transport","onCommandChange","update","status","params","attached","initialState","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","catch","error","Error","onError","subscribe","dispatch","type","converter","metadata","ConnectionMetadata","pendingCommands","isSending","length","converted","convertedRef","queueItems","queue","queueSeam","present","items","enqueue","message","steer","isRunning","queueItemId","remove","clear","reason","extras","sendCommand","reconnect","handleAppend","messages","isLoading","attachmentAdapter","adapters","attachments","onNew","capabilities","edit","onEdit","onCancel","payload","cancelPayload","Array","isArray","T","Transport","QueueItem","id","prompt","State","ConnectionState","StateConverter","connectionMetadata","CancelPayload","hook"],"sources":["../src/StatewireThread.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { resource, useResource } from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/react\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/react\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport type {\n AppendMessage,\n AttachmentAdapter,\n ExternalThreadQueueAdapter,\n ModelContext,\n ThreadMessage,\n} from \"@assistant-ui/core\";\nimport { toToolsJSONSchema } from \"assistant-stream\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { useStatewire } from \"statewire\";\nimport type { Statewire, StatewireClient } from \"statewire\";\nimport {\n convertAppendMessageToCommand,\n symbolAssistantTransportExtras,\n} from \"./AssistantTransportThread\";\nimport type { AssistantTransportExtras } from \"./AssistantTransportThread\";\nimport type { AssistantTransportCommand } from \"./types\";\n\ntype AnyCommands = Record<string, (...args: any[]) => unknown>;\n\nconst ambientContextOf = (context: ModelContext): Record<string, unknown> => ({\n ...(context.system !== undefined && { system: context.system }),\n ...(context.tools !== undefined && {\n tools: toToolsJSONSchema(context.tools),\n }),\n ...(context.callSettings !== undefined && {\n callSettings: context.callSettings,\n }),\n ...(context.config !== undefined && { config: context.config }),\n});\n\nconst useStatewireThread = (\n options: StatewireThread.Options<any>,\n): ClientOutput<\"thread\"> => {\n const latest = useRef(options);\n latest.current = options;\n\n const [pending, setPending] = useState<readonly AssistantTransportCommand[]>(\n [],\n );\n const [retire] = useState(\n () => (command: unknown) =>\n setPending((prev) =>\n prev.includes(command as AssistantTransportCommand)\n ? prev.filter((c) => c !== command)\n : prev,\n ),\n );\n\n const {\n state: transportState,\n commands,\n connection,\n setContext,\n } = useStatewire<unknown, AnyCommands>({\n transport: options.transport,\n onCommandChange: (update) => {\n if (update.status === \"acked\" || update.status === \"settled\")\n retire(update.params[0]);\n },\n });\n const attached = transportState !== undefined;\n const state = attached ? transportState : options.initialState;\n\n const clientRef = useAssistantClientRef();\n const setContextRef = useRef(setContext);\n setContextRef.current = setContext;\n const [syncState] = useState(() => ({ lastSent: undefined as unknown }));\n const { contextSync } = options;\n useEffect(() => {\n if (contextSync === undefined) return;\n const modelContext = (clientRef.current ?? clientRef.parent).modelContext();\n const send = () => {\n const value = ambientContextOf(modelContext.getModelContext());\n const key = JSON.stringify(value);\n if (key === syncState.lastSent) return;\n syncState.lastSent = key;\n void setContextRef.current(value).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n };\n send();\n if (!modelContext.subscribe) {\n throw new Error(\n \"statewire: contextSync requires a subscribable model context\",\n );\n }\n return modelContext.subscribe(send);\n }, [contextSync, clientRef, syncState]);\n\n const dispatch = useCallback(\n (command: AssistantTransportCommand) => {\n setPending((prev) => [...prev, command]);\n void commands[command.type]!(command).catch((error: Error) => {\n retire(command);\n latest.current.onError?.(error);\n });\n },\n [commands, retire],\n );\n\n const { converter } = options;\n const metadata = useMemo(\n (): StatewireThread.ConnectionMetadata => ({\n pendingCommands: [...pending],\n isSending: pending.length > 0,\n connection,\n }),\n [pending, connection],\n );\n const converted = useMemo(\n () => converter(state, metadata),\n [converter, state, metadata],\n );\n const convertedRef = useRef(converted);\n convertedRef.current = converted;\n\n const queueItems = converted.queue;\n const [queueSeam] = useState(() => ({\n present: queueItems !== undefined,\n }));\n if (queueSeam.present !== (queueItems !== 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\n const queue = useMemo(\n (): ExternalThreadQueueAdapter | undefined =>\n queueItems && {\n items: queueItems,\n enqueue: (message, { steer }) => {\n const command = convertAppendMessageToCommand(message);\n if (!command) return;\n dispatch(\n convertedRef.current.isRunning\n ? { ...command, type: \"enqueue-message\", steer }\n : command,\n );\n },\n steer: (queueItemId) =>\n dispatch({ type: \"steer-queue-item\", queueItemId }),\n remove: (queueItemId) =>\n dispatch({ type: \"remove-queue-item\", queueItemId }),\n clear: (reason) => dispatch({ type: \"clear-queue\", reason }),\n },\n [queueItems, dispatch],\n );\n\n const extras = useMemo(\n (): AssistantTransportExtras => ({\n [symbolAssistantTransportExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state,\n }),\n [dispatch, connection.reconnect, state],\n );\n\n const handleAppend = (message: AppendMessage) => {\n const command = convertAppendMessageToCommand(message);\n if (!command) return;\n dispatch(command);\n };\n\n return useResource(\n ExternalThread({\n messages: converted.messages as readonly ExternalThreadMessage[],\n isRunning: converted.isRunning,\n isLoading: !attached,\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n onNew: handleAppend,\n ...(queue && { queue }),\n ...(options.capabilities?.edit && { onEdit: handleAppend }),\n onCancel: () => {\n const payload = latest.current.cancelPayload?.();\n if (\n payload !== undefined &&\n (typeof payload !== \"object\" ||\n payload === null ||\n Array.isArray(payload))\n )\n throw new Error(\n \"statewire: cancelPayload must return a plain object\",\n );\n void commands[\"cancel\"]!(\n ...(payload === undefined ? [] : [payload]),\n ).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n },\n }),\n );\n};\n\nexport const StatewireThread = <T>(\n options: StatewireThread.Options<T>,\n): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useStatewireThread)(options as StatewireThread.Options<any>);\n\nexport namespace StatewireThread {\n export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;\n\n export type QueueItem = {\n readonly id: string;\n readonly prompt: string;\n };\n\n export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n readonly isRunning: boolean;\n /**\n * Server-owned message queue projected out of the state. Returning it\n * (even empty) turns on the queue capability: sends during a run become\n * `enqueue-message` commands and item controls send the queue commands.\n * Presence must be stable across conversions.\n */\n readonly queue?: readonly QueueItem[];\n };\n\n export type ConnectionMetadata = {\n pendingCommands: AssistantTransportCommand[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `live`. */\n connection: StatewireClient.ConnectionState;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n /**\n * Payload of the built-in `cancel` command. `reason` is the one well-known\n * field; apps extend it with their own JSON-serializable fields.\n */\n export type CancelPayload = {\n readonly reason?: string | undefined;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n export type Options<T> = {\n transport: Transport<T>;\n initialState: T;\n converter: StateConverter<T>;\n /**\n * \"command-send\" mirrors the client's ambient model context (system,\n * tools, callSettings, config) to the server over the command channel —\n * on connect and whenever it changes. Requires a remote transport.\n */\n contextSync?: \"command-send\" | undefined;\n /** Supplies the `cancel` command's payload; omitted, cancel sends no payload. */\n cancelPayload?: (() => CancelPayload) | undefined;\n onError?: ((error: Error) => void) | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n }\n | undefined;\n };\n}\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useStatewireThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;AA8BA,MAAM8B,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWC,KAAAA,KAAa,EAAED,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQG,UAAUD,KAAAA,KAAa,EACjCC,OAAOhB,kBAAkBa,QAAQG,KAAK,EACxC;CACA,GAAIH,QAAQI,iBAAiBF,KAAAA,KAAa,EACxCE,cAAcJ,QAAQI,aACxB;CACA,GAAIJ,QAAQK,WAAWH,KAAAA,KAAa,EAAEG,QAAQL,QAAQK,OAAO;AAC/D;AAEA,MAAMC,sBACJC,YAC2B;CAC3B,MAAMG,SAAStC,OAAOmC,OAAO;CAC7BG,OAAOC,UAAUJ;CAEjB,MAAM,CAACK,SAASC,cAAcxC,SAC5B,CAAA,CACF;CACA,MAAM,CAACyC,UAAUzC,gBACR0C,YACLF,YAAYG,SACVA,KAAKC,SAASF,O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yB,WAAWpD,WAAWoD;EACtBvD;CACF,IACA;EAAC8B;EAAU3B,WAAWoD;EAAWvD;CAAK,CACxC;CAEA,MAAMwD,gBAAgBV,cAA2B;EAC/C,MAAMnD,YAAUvB,8BAA8B0E,SAAO;EACrD,IAAI,CAACnD,WAAS;EACdmC,SAASnC,SAAO;CAClB;CAEA,OAAOxC,YACLE,eAAe;EACboG,UAAUnB,UAAUmB;EACpBT,WAAWV,UAAUU;EACrBU,WAAW,CAAChD;EACZV,OAAOsC,UAAUtC;EACjBqD;EACAM,mBAAmBxE,QAAQyE,UAAUC;EACrCC,OAAON;EACP,GAAIf,SAAS,EAAEA,MAAM;EACrB,GAAItD,QAAQ4E,cAAcC,QAAQ,EAAEC,QAAQT,aAAa;EACzDU,gBAAgB;GACd,MAAMC,UAAU7E,OAAOC,QAAQ6E,gBAAgB;GAC/C,IACED,YAAYrF,KAAAA,MACX,OAAOqF,YAAY,YAClBA,YAAY,QACZE,MAAMC,QAAQH,OAAO,IAEvB,MAAM,IAAIxC,MACR,qDACF;GACF,SAAc,SAAS,CACrB,GAAIwC,YAAYrF,KAAAA,IAAY,CAAA,IAAK,CAACqF,OAAO,CAC3C,CAAC,CAAC1C,OAAOC,YAAiB;IACxBpC,OAAOC,QAAQqC,UAAUF,OAAK;GAChC,CAAC;EACH;CACF,CAAC,CACH;AACF;AAEA,MAAatC,mBACXD,YAEAjC,SAASgC,kBAAkB,CAAC,CAACC,OAAuC;AAuEtE5B,uBACE2B,oBACA7B,eAAeyB,KAAAA,CAAkB,CAAC,CAACmG,IACrC"}
1
+ {"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","AppendMessage","AttachmentAdapter","ExternalThreadQueueAdapter","ModelContext","QueuePlacement","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","StatewireClient","convertAppendMessageToCommand","symbolAssistantTransportExtras","AssistantTransportExtras","AssistantTransportCommand","AnyCommands","Record","args","ambientContextOf","context","system","undefined","tools","callSettings","config","toWireMessage","message","id","StatewireThread","UserMessage","role","Error","files","FilePart","texts","source","content","attachments","flatMap","a","part","type","push","text","mediaType","url","image","mimeType","data","filename","parts","TextPart","length","const","join","toQueueItemState","item","QueueItem","prompt","map","placementFields","placement","insertAfter","insertBefore","withSessionLostFallback","transport","Transport","latest","current","Options","transportOptions","rest","transportLevel","onCommandSessionLost","command","SessionLostCommand","useStatewireThread","options","pending","setPending","Command","retire","prev","includes","filter","c","state","transportState","commands","connection","setContext","onCommandChange","update","status","params","attached","initialState","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","catch","error","onError","subscribe","dispatch","converter","metadata","ConnectionMetadata","pendingCommands","isSending","converted","queueItems","queue","steerQueueItems","steerQueue","queueSeam","present","laneOf","queueItemId","some","items","steerItems","enqueue","crypto","randomUUID","steer","move","lane","fields","messageId","edit","wireMessage","remove","extras","sendCommand","reconnect","handleAppend","handleEdit","sourceId","messages","isRunning","isLoading","attachmentAdapter","adapters","onNew","capabilities","onEdit","continue","onResume","onCancel","payload","cancelPayload","Array","isArray","T","Placement","RunEnqueueCommand","RunSteerCommand","RunDequeueCommand","RunEditCommand","RunContinueCommand","RunCommand","State","ConnectionState","StateConverter","connectionMetadata","CancelPayload","reason","hook"],"sources":["../src/StatewireThread.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { resource, useResource } from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/react\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/react\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport type {\n AppendMessage,\n AttachmentAdapter,\n ExternalThreadQueueAdapter,\n ModelContext,\n QueuePlacement,\n ThreadMessage,\n} from \"@assistant-ui/core\";\nimport { toToolsJSONSchema } from \"assistant-stream\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { useStatewire } from \"statewire\";\nimport type { Statewire, StatewireClient } from \"statewire\";\nimport {\n convertAppendMessageToCommand,\n symbolAssistantTransportExtras,\n} from \"./AssistantTransportThread\";\nimport type { AssistantTransportExtras } from \"./AssistantTransportThread\";\nimport type { AssistantTransportCommand } from \"./types\";\n\ntype AnyCommands = Record<string, (...args: any[]) => unknown>;\n\nconst ambientContextOf = (context: ModelContext): Record<string, unknown> => ({\n ...(context.system !== undefined && { system: context.system }),\n ...(context.tools !== undefined && {\n tools: toToolsJSONSchema(context.tools),\n }),\n ...(context.callSettings !== undefined && {\n callSettings: context.callSettings,\n }),\n ...(context.config !== undefined && { config: context.config }),\n});\n\nconst toWireMessage = (\n message: AppendMessage,\n id: string,\n): StatewireThread.UserMessage => {\n if (message.role !== \"user\")\n throw new Error(\"statewire: only user messages are supported\");\n const files: StatewireThread.FilePart[] = [];\n const texts: string[] = [];\n const source = [\n ...message.content,\n ...(message.attachments?.flatMap((a) => a.content) ?? []),\n ];\n for (const part of source) {\n if (part.type === \"text\") {\n texts.push(part.text);\n } else if (part.type === \"image\") {\n files.push({ type: \"file\", mediaType: \"image/*\", url: part.image });\n } else if (part.type === \"file\") {\n files.push({\n type: \"file\",\n mediaType: part.mimeType,\n url: part.data,\n ...(part.filename !== undefined && { filename: part.filename }),\n });\n } else {\n throw new Error(`statewire: unsupported message part \"${part.type}\"`);\n }\n }\n // default-safe against host capabilities: files first, one merged text part\n const parts: (StatewireThread.TextPart | StatewireThread.FilePart)[] = [\n ...files,\n ...(texts.length > 0\n ? [{ type: \"text\" as const, text: texts.join(\"\\n\\n\") }]\n : []),\n ];\n if (parts.length === 0)\n throw new Error(\"statewire: cannot send an empty message\");\n return { id, role: \"user\", parts };\n};\n\nconst toQueueItemState = (item: StatewireThread.QueueItem) => ({\n id: item.id,\n prompt: item.parts\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\"),\n parts: item.parts.map((part) =>\n part.type === \"text\"\n ? part\n : {\n type: \"file\" as const,\n data: part.url,\n mimeType: part.mediaType,\n ...(part.filename !== undefined && { filename: part.filename }),\n },\n ),\n});\n\nconst placementFields = (placement: QueuePlacement) => ({\n ...(placement.insertAfter !== undefined && {\n insertAfter: placement.insertAfter,\n }),\n ...(placement.insertBefore !== undefined && {\n insertBefore: placement.insertBefore,\n }),\n});\n\nconst withSessionLostFallback = (\n transport: StatewireThread.Transport<any>,\n latest: { current: StatewireThread.Options<any> },\n): StatewireThread.Transport<any> => {\n const [transportOptions, ...rest] = transport.args as [\n Record<string, unknown>,\n ...unknown[],\n ];\n if (\n rest.length > 0 ||\n typeof transportOptions !== \"object\" ||\n transportOptions === null\n ) {\n throw new Error(\n \"statewire: onCommandSessionLost requires a transport element that takes a single options object\",\n );\n }\n const transportLevel = transportOptions.onCommandSessionLost as\n | ((command: StatewireClient.SessionLostCommand) => \"replay\" | void)\n | undefined;\n return {\n ...transport,\n args: [\n {\n ...transportOptions,\n onCommandSessionLost: (\n command: StatewireClient.SessionLostCommand,\n ): \"replay\" | void =>\n transportLevel?.(command) ??\n latest.current.onCommandSessionLost?.(command),\n },\n ],\n };\n};\n\nconst useStatewireThread = (\n options: StatewireThread.Options<any>,\n): ClientOutput<\"thread\"> => {\n const latest = useRef(options);\n latest.current = options;\n\n const [pending, setPending] = useState<readonly StatewireThread.Command[]>(\n [],\n );\n const [retire] = useState(\n () => (command: unknown) =>\n setPending((prev) =>\n prev.includes(command as StatewireThread.Command)\n ? prev.filter((c) => c !== command)\n : prev,\n ),\n );\n\n const {\n state: transportState,\n commands,\n connection,\n setContext,\n } = useStatewire<unknown, AnyCommands>({\n transport:\n options.onCommandSessionLost === undefined\n ? options.transport\n : withSessionLostFallback(options.transport, latest),\n onCommandChange: (update) => {\n if (update.status === \"acked\" || update.status === \"settled\")\n retire(update.params[0]);\n },\n });\n const attached = transportState !== undefined;\n const state = attached ? transportState : options.initialState;\n\n const clientRef = useAssistantClientRef();\n const setContextRef = useRef(setContext);\n setContextRef.current = setContext;\n const [syncState] = useState(() => ({ lastSent: undefined as unknown }));\n const { contextSync } = options;\n useEffect(() => {\n if (contextSync === undefined) return;\n const modelContext = (clientRef.current ?? clientRef.parent).modelContext();\n const send = () => {\n const value = ambientContextOf(modelContext.getModelContext());\n const key = JSON.stringify(value);\n if (key === syncState.lastSent) return;\n syncState.lastSent = key;\n void setContextRef.current(value).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n };\n send();\n if (!modelContext.subscribe) {\n throw new Error(\n \"statewire: contextSync requires a subscribable model context\",\n );\n }\n return modelContext.subscribe(send);\n }, [contextSync, clientRef, syncState]);\n\n const dispatch = useCallback(\n (command: StatewireThread.Command) => {\n setPending((prev) => [...prev, command]);\n void commands[command.type]!(command).catch((error: Error) => {\n retire(command);\n latest.current.onError?.(error);\n });\n },\n [commands, retire],\n );\n\n const { converter } = options;\n const metadata = useMemo(\n (): StatewireThread.ConnectionMetadata => ({\n pendingCommands: [...pending],\n isSending: pending.length > 0,\n connection,\n }),\n [pending, connection],\n );\n const converted = useMemo(\n () => converter(state, metadata),\n [converter, state, metadata],\n );\n const queueItems = converted.queue;\n const steerQueueItems = converted.steerQueue;\n if (steerQueueItems !== undefined && queueItems === undefined)\n throw new Error(\n \"statewire: the converter's steerQueue projection requires the queue projection\",\n );\n const [queueSeam] = useState(() => ({\n present: queueItems !== undefined,\n }));\n if (queueSeam.present !== (queueItems !== 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\n const queue = useMemo((): ExternalThreadQueueAdapter | undefined => {\n if (!queueItems) return undefined;\n const laneOf = (queueItemId: string): \"queue\" | \"steer\" => {\n if (steerQueueItems?.some((item) => item.id === queueItemId))\n return \"steer\";\n if (queueItems.some((item) => item.id === queueItemId)) return \"queue\";\n throw new Error(`statewire: unknown queue item \"${queueItemId}\"`);\n };\n return {\n items: queueItems.map(toQueueItemState),\n steerItems: (steerQueueItems ?? []).map(toQueueItemState),\n enqueue: (message) =>\n dispatch({\n type: \"run/enqueue\",\n message: toWireMessage(message, crypto.randomUUID()),\n }),\n steer: (message) =>\n dispatch({\n type: \"run/steer\",\n message: toWireMessage(message, crypto.randomUUID()),\n }),\n move: (queueItemId, placement) => {\n const lane = placement.lane ?? laneOf(queueItemId);\n const fields = {\n messageId: queueItemId,\n ...placementFields(placement),\n };\n dispatch(\n lane === \"steer\"\n ? { type: \"run/steer\", ...fields }\n : { type: \"run/enqueue\", ...fields },\n );\n },\n edit: (queueItemId, message) => {\n const wireMessage = toWireMessage(message, queueItemId);\n dispatch(\n laneOf(queueItemId) === \"steer\"\n ? { type: \"run/steer\", message: wireMessage }\n : { type: \"run/enqueue\", message: wireMessage },\n );\n },\n remove: (queueItemId) =>\n dispatch({ type: \"run/dequeue\", messageId: queueItemId }),\n };\n }, [queueItems, steerQueueItems, dispatch]);\n\n const extras = useMemo(\n (): AssistantTransportExtras => ({\n [symbolAssistantTransportExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state,\n }),\n [dispatch, connection.reconnect, state],\n );\n\n const handleAppend = (message: AppendMessage) => {\n const command = convertAppendMessageToCommand(message);\n if (!command) return;\n dispatch(command);\n };\n\n const handleEdit = (message: AppendMessage) => {\n if (!queueItems) return handleAppend(message);\n if (message.sourceId == null)\n throw new Error(\"statewire: run/edit requires a sourceId\");\n dispatch({\n type: \"run/edit\",\n message: toWireMessage(message, crypto.randomUUID()),\n sourceId: message.sourceId,\n });\n };\n\n return useResource(\n ExternalThread({\n messages: converted.messages as readonly ExternalThreadMessage[],\n isRunning: converted.isRunning,\n isLoading: !attached,\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n onNew: handleAppend,\n ...(queue && { queue }),\n ...(options.capabilities?.edit && { onEdit: handleEdit }),\n ...(options.capabilities?.continue && {\n onResume: () => dispatch({ type: \"run/continue\" }),\n }),\n onCancel: () => {\n const payload = latest.current.cancelPayload?.();\n if (\n payload !== undefined &&\n (typeof payload !== \"object\" ||\n payload === null ||\n Array.isArray(payload))\n )\n throw new Error(\n \"statewire: cancelPayload must return a plain object\",\n );\n void commands[\"run/cancel\"]!(\n ...(payload === undefined ? [] : [payload]),\n ).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n },\n }),\n );\n};\n\nexport const StatewireThread = <T>(\n options: StatewireThread.Options<T>,\n): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useStatewireThread)(options as StatewireThread.Options<any>);\n\nexport namespace StatewireThread {\n export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;\n\n export type TextPart = {\n readonly type: \"text\";\n readonly text: string;\n };\n\n export type FilePart = {\n readonly type: \"file\";\n readonly mediaType: string;\n readonly url: string;\n readonly filename?: string;\n };\n\n export type UserMessage = {\n readonly id: string;\n readonly role: \"user\";\n readonly parts: readonly (TextPart | FilePart)[];\n readonly metadata?: Record<string, unknown>;\n };\n\n /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */\n export type Placement = {\n readonly insertAfter?: string | null;\n readonly insertBefore?: string | null;\n };\n\n export type RunEnqueueCommand = {\n readonly type: \"run/enqueue\";\n } & ({ readonly message: UserMessage } | { readonly messageId: string }) &\n Placement;\n\n export type RunSteerCommand = {\n readonly type: \"run/steer\";\n } & ({ readonly message: UserMessage } | { readonly messageId: string }) &\n Placement;\n\n export type RunDequeueCommand = {\n readonly type: \"run/dequeue\";\n readonly messageId: string;\n };\n\n export type RunEditCommand = {\n readonly type: \"run/edit\";\n readonly message: UserMessage;\n readonly sourceId: string;\n };\n\n export type RunContinueCommand = {\n readonly type: \"run/continue\";\n };\n\n export type RunCommand =\n | RunEnqueueCommand\n | RunSteerCommand\n | RunDequeueCommand\n | RunEditCommand\n | RunContinueCommand;\n\n export type Command = AssistantTransportCommand | RunCommand;\n\n /** A queued message projected out of the host state, wire shape. */\n export type QueueItem = {\n readonly id: string;\n readonly parts: readonly (TextPart | FilePart)[];\n };\n\n export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n readonly isRunning: boolean;\n /**\n * The host's regular queue lane projected out of the state. Returning it\n * (even empty) turns on the queue capability: sends become `run/enqueue`\n * / `run/steer` commands and item controls send the `run/*` queue\n * commands. Presence must be stable across conversions.\n */\n readonly queue?: readonly QueueItem[];\n /** The host's steer lane; requires `queue`. Absent means empty. */\n readonly steerQueue?: readonly QueueItem[];\n };\n\n export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `live`. */\n connection: StatewireClient.ConnectionState;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n /**\n * Payload of the built-in `run/cancel` command. `reason` is the one well-known\n * field; apps extend it with their own JSON-serializable fields.\n */\n export type CancelPayload = {\n readonly reason?: string | undefined;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n export type Options<T> = {\n transport: Transport<T>;\n initialState: T;\n converter: StateConverter<T>;\n /**\n * \"command-send\" mirrors the client's ambient model context (system,\n * tools, callSettings, config) to the server over the command channel —\n * on connect and whenever it changes. Requires a remote transport.\n */\n contextSync?: \"command-send\" | undefined;\n /** Supplies the `run/cancel` command's payload; omitted, cancel sends no payload. */\n cancelPayload?: (() => CancelPayload) | undefined;\n /**\n * Offered each pending command when a remote transport's session is\n * evicted; return \"replay\" to re-enqueue it under the rotated client id.\n * A callback set on the transport options is consulted first; this one\n * runs for commands it declined.\n */\n onCommandSessionLost?:\n | ((command: StatewireClient.SessionLostCommand) => \"replay\" | void)\n | undefined;\n onError?: ((error: Error) => void) | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n /** The host supports `run/continue` (a continue affordance on aborted runs). */\n continue?: boolean | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n }\n | undefined;\n };\n}\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useStatewireThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;AA+BA,MAAM+B,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWC,KAAAA,KAAa,EAAED,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQG,UAAUD,KAAAA,KAAa,EACjCC,OAAOhB,kBAAkBa,QAAQG,KAAK,EACxC;CACA,GAAIH,QAAQI,iBAAiBF,KAAAA,KAAa,EACxCE,cAAcJ,QAAQI,aACxB;CACA,GAAIJ,QAAQK,WAAWH,KAAAA,KAAa,EAAEG,QAAQL,QAAQK,OAAO;AAC/D;AAEA,MAAMC,iBACJC,SACAC,OACgC;CAChC,IAAID,QAAQI,SAAS,QACnB,MAAM,IAAIC,MAAM,6CAA6C;CAC/D,MAAMC,QAAoC,CAAA;CAC1C,MAAME,QAAkB,CAAA;CACxB,MAAMC,SAAS,CACb,GAAGT,QAAQU,SACX,GAAIV,QAAQW,aAAaC,SAASC,MAAMA,EAAEH,OAAO,KAAK,CAAA,CAAG;CAE3D,KAAK,MAAMI,QAAQL,QACjB,IAAIK,KAAKC,SAAS,QAChBP,MAAMQ,KAAKF,KAAKG,IAAI;MACf,IAAIH,KAAKC,SAAS,SACvBT,MAAMU,KAAK;EAAED,MAAM;EAAQG,WAAW;EAAWC,KAAKL,KAAKM;CAAM,CAAC;MAC7D,IAAIN,KAAKC,SAAS,QACvBT,MAAMU,KAAK;EACTD,MAAM;EACNG,WAAWJ,KAAKO;EAChBF,KAAKL,KAAKQ;EACV,GAAIR,KAAKS,aAAa5B,KAAAA,KAAa,EAAE4B,UAAUT,KAAKS,SAAS;CAC/D,CAAC;MAED,MAAM,IAAIlB,MAAM,wCAAwCS,KAAKC,KAAI,EAAG;CAIxE,MAAMS,QAAiE,CACrE,GAAGlB,O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