@assistant-ui/react-statewire 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"AssistantTransportThread.d.ts","names":[],"sources":["../src/AssistantTransportThread.ts"],"mappings":";;;;cA2Da;KAID;GACT;EACD,cAAc,SAAS;EACvB;EACA;;EAEA,yBAAyB;;cAGd,6BACX,oBACC;cA4VU,2BAA4B,GACvC,SAAS,0BAA0B,OAClC,gBAAgB"}
1
+ {"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,5 +1,5 @@
1
1
  import { AssistantTransportHost } from "./host.js";
2
- import { createRunQueueAdapter, resolveReloadCommand, toWireMessage } from "./runCommands.js";
2
+ import { createRunQueueAdapter, resolveReloadCommand, toWireMessage, viewedLeafId } from "./runCommands.js";
3
3
  import { resolveToolApprovalInput, resolveToolResultInput } from "./inputRequests.js";
4
4
  import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "@assistant-ui/tap/react-shim";
5
5
  import { resource, useResource } from "@assistant-ui/tap";
@@ -66,8 +66,7 @@ const useAssistantTransportThread = (options) => {
66
66
  onResult: (command_0) => {
67
67
  const messages = convertedRef.current.messages;
68
68
  if (!messagesContainToolCall(messages, command_0.toolCallId)) return;
69
- const requests = convertedRef.current.inputRequests;
70
- dispatch((requests && resolveToolResultInput(requests, command_0)) ?? command_0);
69
+ dispatch(resolveToolResultInput(convertedRef.current.inputRequests ?? [], command_0));
71
70
  },
72
71
  onStatusesChange: (statuses) => {
73
72
  setToolStatuses(statuses.size === 0 ? EMPTY_TOOL_STATUSES : Object.fromEntries(statuses));
@@ -102,7 +101,8 @@ const useAssistantTransportThread = (options) => {
102
101
  const startRun = message.startRun ?? message.role === "user";
103
102
  const command_1 = {
104
103
  type: "run/steer",
105
- message: toWireMessage(message, crypto.randomUUID())
104
+ message: toWireMessage(message, crypto.randomUUID()),
105
+ anchorMessageId: viewedLeafId(convertedRef.current.messages)
106
106
  };
107
107
  commands.setParentId(message.parentId).catch(() => {});
108
108
  const send = () => dispatch(command_1, { schedule: startRun });
@@ -136,7 +136,8 @@ const useAssistantTransportThread = (options) => {
136
136
  if (queueProjection !== void 0 && options.capabilities?.queue) throw new Error("statewire: the converter's queue projection excludes capabilities.queue");
137
137
  const [queueSeam] = useState(() => ({ present: queueProjection !== void 0 }));
138
138
  if (queueSeam.present !== (queueProjection !== void 0)) throw new Error("statewire: the converter's queue projection must be stable — it was " + (queueSeam.present ? "defined" : "undefined") + " on first convert and changed since");
139
- const serverQueue = useMemo(() => queueProjection ? createRunQueueAdapter(queueProjection, steerProjection, dispatch) : void 0, [
139
+ const serverQueue = useMemo(() => queueProjection ? createRunQueueAdapter(converted.messages, queueProjection, steerProjection, dispatch) : void 0, [
140
+ converted.messages,
140
141
  queueProjection,
141
142
  steerProjection,
142
143
  dispatch
@@ -192,25 +193,10 @@ const useAssistantTransportThread = (options) => {
192
193
  if (!options.resumeApi) throw new Error("Must pass resumeApi to options to resume runs");
193
194
  commands.resume().catch(() => {});
194
195
  },
195
- onAddToolResult: (toolOptions) => {
196
- const requests_0 = convertedRef.current.inputRequests;
197
- const inputCommand = requests_0 && resolveToolResultInput(requests_0, toolOptions);
198
- if (inputCommand) {
199
- dispatch(inputCommand);
200
- return;
201
- }
202
- const command_4 = {
203
- type: "add-tool-result",
204
- toolCallId: toolOptions.toolCallId,
205
- result: toolOptions.result,
206
- toolName: toolOptions.toolName,
207
- isError: toolOptions.isError,
208
- ...toolOptions.artifact && { artifact: toolOptions.artifact },
209
- ...toolOptions.modelContent !== void 0 && { modelContent: toolOptions.modelContent }
210
- };
211
- dispatch(command_4);
196
+ ...inputRequests !== void 0 && {
197
+ onAddToolResult: (toolOptions) => dispatch(resolveToolResultInput(convertedRef.current.inputRequests, toolOptions)),
198
+ onRespondToToolApproval: (options_0) => dispatch(resolveToolApprovalInput(convertedRef.current.inputRequests, options_0))
212
199
  },
213
- ...inputRequests !== void 0 && { onRespondToToolApproval: (options_0) => dispatch(resolveToolApprovalInput(convertedRef.current.inputRequests, options_0)) },
214
200
  onResumeToolCall: ({ toolCallId, payload }) => {
215
201
  if (!toolInvocations.resume(toolCallId, payload)) throw new Error(`Tool call ${toolCallId} is not waiting for resume.`);
216
202
  },
@@ -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","RespondToToolApprovalOptions","ResumeToolCallOptions","ThreadMessage","ToolExecutionStatus","ToolInvocationTracker","ReadonlyJSONObject","useStatewire","AssistantTransportHost","AssistantTransportHostCommands","AssistantTransportHostState","HostQueueCell","HostRunContext","SendOptions","createRunQueueAdapter","resolveReloadCommand","toWireMessage","resolveToolApprovalInput","resolveToolResultInput","AddToolResultCommand","AssistantTransportCommand","AssistantTransportOptions","InputRequestState","EMPTY_TOOL_STATUSES","Record","EMPTY_QUEUE_ITEMS","subscribeNoop","symbolAssistantTransportExtras","Symbol","AssistantTransportExtras","sendCommand","command","reconnect","state","inputRequests","asAssistantTransportExtras","extras","Error","messagesContainToolCall","messages","toolCallId","some","message","content","part","type","undefined","useAssistantTransportThread","options","clientRef","getRunContext","aui","current","parent","threadId","threadListItem","getState","remoteId","modelContext","getModelContext","queueCell","queued","inTransit","commands","connection","transport","agent","agentState","isSending","isReplaying","queue","dispatch","opts","send","catch","toolStatuses","setToolStatuses","converter","converted","pendingCommands","convertedRef","toolInvocations","tools","onResult","requests","onStatusesChange","statuses","size","Object","fromEntries","setState","isRunning","isLoading","reset","inputSeam","present","handleAppend","startRun","role","crypto","randomUUID","setParentId","parentId","schedule","abort","then","handleEdit","sourceId","handleCancel","cancel","driverRef","run","at","id","queueProjection","steerProjection","steerQueue","capabilities","queueSeam","serverQueue","enableQueue","queueRef","clear","messageQueue","queueItems","subscribe","adapter","items","steerQueueItems","steerItems","busy","keys","length","wasBusyRef","notifyBusy","notifyIdle","attachmentAdapter","adapters","attachments","onNew","edit","onEdit","onReload","onCancel","onResume","continue","resumeApi","resume","onAddToolResult","toolOptions","inputCommand","result","toolName","isError","artifact","modelContent","onRespondToToolApproval","onResumeToolCall","payload","onLoadExternalState","imported","importState","AssistantTransportThread","T","hook"],"sources":["../src/AssistantTransportThread.ts"],"sourcesContent":["import {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport { resource, useResource } from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/react\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/react\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport { createMessageQueue } from \"@assistant-ui/core\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n MessageQueueController,\n MessageQueueDriver,\n RespondToToolApprovalOptions,\n ResumeToolCallOptions,\n ThreadMessage,\n ToolExecutionStatus,\n} from \"@assistant-ui/core\";\nimport { ToolInvocationTracker } from \"@assistant-ui/core/internal\";\nimport type { ReadonlyJSONObject } from \"assistant-stream/utils\";\nimport { useStatewire } from \"statewire\";\nimport { AssistantTransportHost } from \"./host\";\nimport type {\n AssistantTransportHostCommands,\n AssistantTransportHostState,\n HostQueueCell,\n HostRunContext,\n SendOptions,\n} from \"./host\";\nimport {\n createRunQueueAdapter,\n resolveReloadCommand,\n toWireMessage,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\nimport type {\n AddToolResultCommand,\n AssistantTransportCommand,\n AssistantTransportOptions,\n InputRequestState,\n} from \"./types\";\n\nconst EMPTY_TOOL_STATUSES: Record<string, ToolExecutionStatus> = {};\nconst EMPTY_QUEUE_ITEMS: MessageQueueController[\"adapter\"][\"items\"] = [];\nconst subscribeNoop = () => () => {};\n\nexport const symbolAssistantTransportExtras = Symbol(\n \"assistant-transport-extras\",\n);\n\nexport type AssistantTransportExtras = {\n [symbolAssistantTransportExtras]: true;\n sendCommand: (command: AssistantTransportCommand) => void;\n reconnect: () => void;\n state: unknown;\n /** The host's parked input requests; absent when the converter does not project them. */\n inputRequests?: readonly InputRequestState[];\n};\n\nexport const asAssistantTransportExtras = (\n extras: unknown,\n): AssistantTransportExtras => {\n if (\n typeof extras !== \"object\" ||\n extras == null ||\n !(symbolAssistantTransportExtras in extras)\n )\n throw new Error(\n \"This method can only be called when you are using AssistantTransportThread or StatewireThread\",\n );\n\n return extras as AssistantTransportExtras;\n};\n\nconst messagesContainToolCall = (\n messages: readonly ThreadMessage[],\n toolCallId: string,\n): boolean =>\n messages.some((message) =>\n message.content.some(\n (part) =>\n part.type === \"tool-call\" &&\n (part.toolCallId === toolCallId ||\n (part.messages !== undefined &&\n messagesContainToolCall(part.messages, toolCallId))),\n ),\n );\n\nconst useAssistantTransportThread = (\n options: AssistantTransportOptions<any>,\n): ClientOutput<\"thread\"> => {\n const clientRef = useAssistantClientRef();\n const [getRunContext] = useState(() => (): HostRunContext => {\n const aui = clientRef.current ?? clientRef.parent;\n // legacy parity: a threadListItem throw must not kill the run\n let threadId: string | null = null;\n try {\n threadId = aui.threadListItem().getState().remoteId ?? null;\n } catch {}\n return {\n modelContext: aui.modelContext().getModelContext(),\n threadId,\n };\n });\n\n const [queueCell] = useState(\n (): HostQueueCell => ({ current: { queued: [], inTransit: [] } }),\n );\n const { state, commands, connection } = useStatewire<\n AssistantTransportHostState,\n AssistantTransportHostCommands\n >({\n transport: AssistantTransportHost({ ...options, getRunContext, queueCell }),\n });\n const { agent: agentState, isSending, isReplaying } = state;\n const queue = queueCell.current;\n\n const dispatch = useCallback(\n (command: AssistantTransportCommand, opts?: SendOptions) => {\n void commands.send(command, opts).catch(() => {});\n },\n [commands],\n );\n\n const [toolStatuses, setToolStatuses] =\n useState<Record<string, ToolExecutionStatus>>(EMPTY_TOOL_STATUSES);\n\n const { converter } = options;\n const converted = useMemo(\n () =>\n converter(agentState, {\n pendingCommands: [...queue.inTransit, ...queue.queued],\n isSending,\n toolStatuses,\n }),\n [converter, agentState, queue, isSending, toolStatuses],\n );\n const convertedRef = useRef(converted);\n convertedRef.current = converted;\n\n const [toolInvocations] = useState(\n () =>\n new ToolInvocationTracker(\n () => {\n const aui = clientRef.current ?? clientRef.parent;\n return aui.modelContext().getModelContext().tools;\n },\n {\n onResult: (command) => {\n const messages = convertedRef.current\n .messages as readonly ThreadMessage[];\n if (!messagesContainToolCall(messages, command.toolCallId)) return;\n const requests = convertedRef.current.inputRequests;\n dispatch(\n (requests && resolveToolResultInput(requests, command)) ??\n command,\n );\n },\n onStatusesChange: (statuses) => {\n setToolStatuses(\n statuses.size === 0\n ? EMPTY_TOOL_STATUSES\n : Object.fromEntries(statuses),\n );\n },\n },\n ),\n );\n // dep-less by design: setState dedups identical snapshots internally\n useEffect(() => {\n toolInvocations.setState({\n messages: converted.messages as readonly ThreadMessage[],\n isRunning: converted.isRunning,\n isLoading: isReplaying,\n });\n });\n useEffect(\n () => () => {\n toolInvocations.reset();\n },\n [toolInvocations],\n );\n\n const inputRequests = converted.inputRequests;\n const [inputSeam] = useState(() => ({\n present: inputRequests !== undefined,\n }));\n if (inputSeam.present !== (inputRequests !== undefined))\n throw new Error(\n \"statewire: the converter's inputRequests projection must be stable — it was \" +\n (inputSeam.present ? \"defined\" : \"undefined\") +\n \" on first convert and changed since\",\n );\n\n const extras = useMemo(\n (): AssistantTransportExtras => ({\n [symbolAssistantTransportExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state: agentState,\n ...(inputRequests !== undefined && { inputRequests }),\n }),\n [dispatch, connection.reconnect, agentState, inputRequests],\n );\n\n const handleAppend = (message: AppendMessage) => {\n const startRun = message.startRun ?? message.role === \"user\";\n const command: AssistantTransportCommand = {\n type: \"run/steer\",\n message: toWireMessage(message, crypto.randomUUID()),\n };\n void commands.setParentId(message.parentId).catch(() => {});\n\n const send = () => dispatch(command, { schedule: startRun });\n if (startRun) {\n // abort in-flight tool executions so their late results cannot race the new turn\n void toolInvocations.abort().then(send);\n } else {\n send();\n }\n };\n\n const handleEdit = (message: AppendMessage) => {\n if (message.sourceId == null)\n throw new Error(\"statewire: run/edit requires a sourceId\");\n const command: AssistantTransportCommand = {\n type: \"run/edit\",\n message: toWireMessage(message, crypto.randomUUID()),\n sourceId: message.sourceId,\n };\n void toolInvocations.abort().then(() => dispatch(command));\n };\n\n const handleCancel = () => {\n void toolInvocations.abort();\n void commands.cancel().catch(() => {});\n };\n\n const driverRef = useRef<{\n run: MessageQueueDriver[\"run\"];\n cancel: () => void;\n }>(undefined as never);\n driverRef.current = {\n // the queued message was stamped with the head at enqueue time; restamp so\n // it appends to the thread the finished run left behind\n run: (message) =>\n handleAppend({\n ...message,\n parentId: convertedRef.current.messages.at(-1)?.id ?? null,\n }),\n cancel: handleCancel,\n };\n\n const queueProjection = converted.queue;\n const steerProjection = converted.steerQueue;\n if (steerProjection !== undefined && queueProjection === undefined)\n throw new Error(\n \"statewire: the converter's steerQueue projection requires the queue projection\",\n );\n if (queueProjection !== undefined && options.capabilities?.queue)\n throw new Error(\n \"statewire: the converter's queue projection excludes capabilities.queue\",\n );\n const [queueSeam] = useState(() => ({\n present: queueProjection !== undefined,\n }));\n if (queueSeam.present !== (queueProjection !== undefined))\n throw new Error(\n \"statewire: the converter's queue projection must be stable — it was \" +\n (queueSeam.present ? \"defined\" : \"undefined\") +\n \" on first convert and changed since\",\n );\n const serverQueue = useMemo(\n () =>\n queueProjection\n ? createRunQueueAdapter(queueProjection, steerProjection, dispatch)\n : undefined,\n [queueProjection, steerProjection, dispatch],\n );\n\n const enableQueue = options.capabilities?.queue === true;\n const queueRef = useRef<MessageQueueController | null>(null);\n if (enableQueue && !queueRef.current) {\n queueRef.current = createMessageQueue({\n run: (message, opts) => driverRef.current.run(message, opts),\n cancel: () => driverRef.current.cancel(),\n });\n } else if (!enableQueue && queueRef.current) {\n queueRef.current.clear();\n queueRef.current = null;\n }\n const messageQueue = queueRef.current;\n\n // fresh view per snapshot: the controller mutates adapter.items in place,\n // which a stable prop identity would hide from the thread resource\n const queueItems = useSyncExternalStore(\n messageQueue?.subscribe ?? subscribeNoop,\n () => messageQueue?.adapter.items ?? EMPTY_QUEUE_ITEMS,\n () => EMPTY_QUEUE_ITEMS,\n );\n const steerQueueItems = useSyncExternalStore(\n messageQueue?.subscribe ?? subscribeNoop,\n () => messageQueue?.adapter.steerItems ?? EMPTY_QUEUE_ITEMS,\n () => EMPTY_QUEUE_ITEMS,\n );\n\n // settled edge: the queue only advances once the host run loop has fully\n // released (isSending), the converted state agrees, and no client tool from\n // the finished run is still executing\n const busy =\n isSending || converted.isRunning || Object.keys(toolStatuses).length > 0;\n const wasBusyRef = useRef(false);\n useEffect(() => {\n if (wasBusyRef.current === busy) return;\n wasBusyRef.current = busy;\n if (busy) messageQueue?.notifyBusy();\n else messageQueue?.notifyIdle();\n });\n\n return useResource(\n ExternalThread({\n messages: converted.messages as readonly ExternalThreadMessage[],\n isRunning: converted.isRunning,\n isLoading: isReplaying,\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n onNew: handleAppend,\n ...(serverQueue\n ? { queue: serverQueue }\n : messageQueue && {\n queue: {\n ...messageQueue.adapter,\n items: queueItems,\n steerItems: steerQueueItems,\n },\n }),\n ...(options.capabilities?.edit && { onEdit: handleEdit }),\n onReload: (parentId: string | null) => {\n const command = resolveReloadCommand(\n convertedRef.current.messages,\n parentId,\n );\n void toolInvocations.abort().then(() => dispatch(command));\n },\n onCancel: () => {\n // user cancel drops pending lanes; a steer interrupt (driver.cancel) keeps them\n messageQueue?.clear();\n handleCancel();\n },\n onResume: () => {\n if (options.capabilities?.continue) {\n dispatch({ type: \"run/continue\" });\n return;\n }\n if (!options.resumeApi)\n throw new Error(\"Must pass resumeApi to options to resume runs\");\n void commands.resume().catch(() => {});\n },\n onAddToolResult: (toolOptions: AddToolResultOptions) => {\n const requests = convertedRef.current.inputRequests;\n const inputCommand =\n requests && resolveToolResultInput(requests, toolOptions);\n if (inputCommand) {\n dispatch(inputCommand);\n return;\n }\n const command: AddToolResultCommand = {\n type: \"add-tool-result\",\n toolCallId: toolOptions.toolCallId,\n result: toolOptions.result as ReadonlyJSONObject,\n toolName: toolOptions.toolName,\n isError: toolOptions.isError,\n ...(toolOptions.artifact && { artifact: toolOptions.artifact }),\n ...(toolOptions.modelContent !== undefined && {\n modelContent: toolOptions.modelContent,\n }),\n };\n\n dispatch(command);\n },\n ...(inputRequests !== undefined && {\n onRespondToToolApproval: (options: RespondToToolApprovalOptions) =>\n dispatch(\n resolveToolApprovalInput(\n convertedRef.current.inputRequests!,\n options,\n ),\n ),\n }),\n onResumeToolCall: ({ toolCallId, payload }: ResumeToolCallOptions) => {\n if (!toolInvocations.resume(toolCallId, payload))\n throw new Error(`Tool call ${toolCallId} is not waiting for resume.`);\n },\n onLoadExternalState: (imported: unknown) => {\n void commands.importState(imported).catch(() => {});\n // reset() aborts tools before React re-renders — gate their late results against the imported state\n convertedRef.current = options.converter(imported, {\n pendingCommands: [...queue.inTransit, ...queue.queued],\n isSending,\n toolStatuses: EMPTY_TOOL_STATUSES,\n });\n toolInvocations.reset();\n setToolStatuses(EMPTY_TOOL_STATUSES);\n },\n }),\n );\n};\n\nexport const AssistantTransportThread = <T>(\n options: AssistantTransportOptions<T>,\n): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useAssistantTransportThread)(\n options as AssistantTransportOptions<any>,\n );\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useAssistantTransportThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;;;;AAuDA,MAAMyC,sBAA2D,CAAC;AAClE,MAAME,oBAAgE,CAAA;AACtE,MAAMC,4BAA4B,CAAC;AAEnC,MAAaC,iCAAiCC,OAC5C,4BACF;AAWA,MAAaO,8BACXC,WAC6B;CAC7B,IACE,OAAOA,WAAW,YAClBA,UAAU,QACV,EAAET,kCAAkCS,SAEpC,MAAM,IAAIC,MACR,+FACF;CAEF,OAAOD;AACT;AAEA,MAAME,2BACJC,UACAC,eAEAD,SAASE,MAAMC,YACbA,QAAQC,QAAQF,MACbG,SACCA,KAAKC,SAAS,gBACbD,KAAKJ,eAAeA,cAClBI,KAAKL,aAAaO,KAAAA,KACjBR,wBAAwBM,KAAKL,UAAUC,UAAU,EACzD,CACF;AAEF,MAAMO,+BACJC,YAC2B;CAC3B,MAAMC,YAAYvD,sBAAsB;CACxC,MAAM,CAACwD,iBAAiBhE,qBAAqC;EAC3D,MAAMiE,MAAMF,UAAUG,WAAWH,UAAUI;EAE3C,IAAIC,WAA0B;EAC9B,IAAI;GACFA,WAAWH,IAAII,eAAe,CAAC,CAACC,SAAS,CAAC,CAACC,YAAY;EACzD,QAAQ,CAAC;EACT,OAAO;GACLC,cAAcP,IAAIO,aAAa,CAAC,CAACC,gBAAgB;GACjDL;EACF;CACF,CAAC;CAED,MAAM,CAACM,aAAa1E,gBACI,EAAEkE,SAAS;EAAES,QAAQ,CAAA;EAAIC,WAAW,CAAA;CAAG,EAAE,EACjE;CACA,MAAM,EAAE7B,OAAO8B,UAAUC,eAAezD,aAGtC,EACA0D,WAAWzD,uBAAuB;EAAE,GAAGwC;EAASE;EAAeU;CAAU,CAAC,EAC5E,CAAC;CACD,MAAM,EAAEM,OAAOC,YAAYC,WAAWC,gBAAgBpC;CACtD,MAAMqC,QAAQV,UAAUR;CAExB,MAAMmB,WAAWzF,aACdiD,SAAoCyC,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vH,YAAgC;IACpCc,MAAM;IACNL,YAAY6G,YAAY7G;IACxB+G,QAAQF,YAAYE;IACpBC,UAAUH,YAAYG;IACtBC,SAASJ,YAAYI;IACrB,GAAIJ,YAAYK,YAAY,EAAEA,UAAUL,YAAYK,SAAS;IAC7D,GAAIL,YAAYM,iBAAiB7G,KAAAA,KAAa,EAC5C6G,cAAcN,YAAYM,aAC5B;GACF;GAEApF,SAASxC,SAAO;EAClB;EACA,GAAIG,kBAAkBY,KAAAA,KAAa,EACjC8G,0BAA0B5G,cACxBuB,SACEtD,yBACE+D,aAAa5B,QAAQlB,eACrBc,SACF,CACF,EACJ;EACA6G,mBAAmB,EAAErH,YAAYsH,cAAqC;GACpE,IAAI,CAAC7E,gBAAgBkE,OAAO3G,YAAYsH,OAAO,GAC7C,MAAM,IAAIzH,MAAM,aAAaG,WAAU,4BAA6B;EACxE;EACAuH,sBAAsBC,aAAsB;GAC1C,SAAcC,YAAYD,QAAQ,CAAC,CAACtF,YAAY,CAAC,CAAC;GAElDM,aAAa5B,UAAUJ,QAAQ6B,UAAUmF,UAAU;IACjDjF,iBAAiB,CAAC,GAAGT,MAAMR,WAAW,GAAGQ,MAAMT,MAAM;IACrDO;IACAO,cAAcpD;GAChB,CAAC;GACD0D,gBAAgBY,MAAM;GACtBjB,gBAAgBrD,mBAAmB;EACrC;CACF,CAAC,CACH;AACF;AAEA,MAAa2I,4BACXlH,YAEA5D,SAAS2D,2BAA2B,CAAC,CACnCC,OACF;AAGFvD,uBACEsD,6BACAxD,eAAeuD,KAAAA,CAAkB,CAAC,CAACsH,IACrC"}
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,cAAcP,IAAIO,aAAa,CAAC,CAACC,gBAAgB;GACjDL;EACF;CACF,CAAC;CAED,MAAM,CAACM,aAAazE,gBACI,EAAEiE,SAAS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1E,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;
@@ -96,6 +100,8 @@ declare namespace StatewireThread {
96
100
  type RunReloadCommand = {
97
101
  readonly type: "run/reload";
98
102
  readonly sourceId: string;
103
+ /** Client-generated id of the regenerated assistant message. */
104
+ readonly messageId: string;
99
105
  };
100
106
  type RunCommand = RunEnqueueCommand | RunSteerCommand | RunDequeueCommand | RunEditCommand | RunContinueCommand | RunReloadCommand | RunInputCommand;
101
107
  type Command = AssistantTransportCommand | RunCommand;
@@ -1 +1 @@
1
- {"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;;cA4Ua,kBAAmB,GAC9B,SAAS,gBAAgB,QAAQ,OAChC,gBAAgB;kBAGF;OACH,UAAU,KAAK,gBAAgB,UAAU;OAEzC;aACD;aACA;;OAGC;aACD;aACA;aACA;aACA;;OAGC;aACD;aACA;aACA,iBAAiB,WAAW;aAC5B,WAAW;;;OAIV;aACD;aACA;;OAGC;aACD;;aACK,SAAS;;aAA2B;OAClD;OAEU;aACD;;aACK,SAAS;;aAA2B;OAClD;OAEU;aACD;aACA;;OAGC;aACD;aACA,SAAS;aACT;;OAGC;aACD;;OAGC;aACD;aACA;aACA;;OAGC;aACD;aACA;aACA;;OAGC;aACD;aACA;cACC,cAAc;;;OAId,eACR,uBACA,2BACA;OAEQ;aACD,QAAQ;;aAER;aACA,WAAW;;OAGV;aACD;aACA,aAAa;aACb;;OAGC,gBAAgB;OAEhB;aACD;aACA;aACA,UAAU;;;OAIT,oBAAoB;aACrB,UAAU;;OAGT;aACD;aACA;;OAGC,aACR,oBACA,kBACA,oBACA,iBACA,qBACA,mBACA;OAEQ,UAAU,4BAA4B;;OAGtC;aACD;aACA,iBAAiB,WAAW;;OAG3B;aACD,mBAAmB;aACnB,QAAQ;aACR;;;;;;;aAOA,iBAAiB;;aAEjB,sBAAsB;;;;;;;aAOtB,yBAAyB;;OAGxB;IACV,iBAAiB;IACjB;;IAEA,YAAY,gBAAgB;;OAGlB,eAAe,MACzB,OAAO,GACP,oBAAoB,uBACjB;;;;;OAMO;aACD;cACC,cAAc;;OAGd,QAAQ;IAClB,WAAW,UAAU;IACrB,cAAc;IACd,WAAW,eAAe;;;;;;IAM1B;;IAEA,qBAAqB;;;;;;;IAOrB,yBACM,SAAS,gBAAgB;IAE/B,YAAY,OAAO;IACnB;MAEM;;MAEA;;MAEA;;IAGN;MAEM,cAAc"}
1
+ {"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,4 @@
1
- import { createRunQueueAdapter, resolveReloadCommand, toWireMessage } from "./runCommands.js";
1
+ import { createRunQueueAdapter, resolveReloadCommand, toWireMessage, viewedLeafId } from "./runCommands.js";
2
2
  import { resolveToolApprovalInput, resolveToolResultInput } from "./inputRequests.js";
3
3
  import { symbolAssistantTransportExtras } from "./AssistantTransportThread.js";
4
4
  import { useCallback, useEffect, useMemo, useRef, useState } from "@assistant-ui/tap/react-shim";
@@ -14,29 +14,6 @@ const ambientContextOf = (context) => ({
14
14
  ...context.callSettings !== void 0 && { callSettings: context.callSettings },
15
15
  ...context.config !== void 0 && { config: context.config }
16
16
  });
17
- const convertAppendMessageToCommand = (message) => {
18
- if (message.role !== "user") throw new Error("Only user messages are supported");
19
- const parts = [];
20
- const content = [...message.content, ...message.attachments?.flatMap((a) => a.content) ?? []];
21
- for (const contentPart of content) if (contentPart.type === "text") parts.push({
22
- type: "text",
23
- text: contentPart.text
24
- });
25
- else if (contentPart.type === "image") parts.push({
26
- type: "image",
27
- image: contentPart.image
28
- });
29
- if (parts.length === 0) return null;
30
- return {
31
- type: "add-message",
32
- message: {
33
- role: "user",
34
- parts
35
- },
36
- parentId: message.parentId,
37
- sourceId: message.sourceId
38
- };
39
- };
40
17
  const withSessionLostFallback = (transport, latest) => {
41
18
  const [transportOptions, ...rest] = transport.args;
42
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");
@@ -110,7 +87,8 @@ const useStatewireThread = (options) => {
110
87
  if (steerQueueItems !== void 0 && queueItems === void 0) throw new Error("statewire: the converter's steerQueue projection requires the queue projection");
111
88
  const [queueSeam] = useState(() => ({ present: queueItems !== void 0 }));
112
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");
113
- const queue = useMemo(() => queueItems ? createRunQueueAdapter(queueItems, steerQueueItems, dispatch) : void 0, [
90
+ const queue = useMemo(() => queueItems ? createRunQueueAdapter(converted.messages, queueItems, steerQueueItems, dispatch) : void 0, [
91
+ converted.messages,
114
92
  queueItems,
115
93
  steerQueueItems,
116
94
  dispatch
@@ -131,15 +109,16 @@ const useStatewireThread = (options) => {
131
109
  inputRequests
132
110
  ]);
133
111
  const handleAppend = (message) => {
134
- const command_1 = convertAppendMessageToCommand(message);
135
- if (!command_1) return;
136
- dispatch(command_1);
112
+ dispatch({
113
+ type: "run/steer",
114
+ message: toWireMessage(message, crypto.randomUUID()),
115
+ anchorMessageId: viewedLeafId(converted.messages)
116
+ });
137
117
  };
138
118
  const handleReload = (parentId) => {
139
119
  dispatch(resolveReloadCommand(converted.messages, parentId));
140
120
  };
141
121
  const handleEdit = (message_0) => {
142
- if (!queueItems) return handleAppend(message_0);
143
122
  if (message_0.sourceId == null) throw new Error("statewire: run/edit requires a sourceId");
144
123
  dispatch({
145
124
  type: "run/edit",
@@ -160,18 +139,7 @@ const useStatewireThread = (options) => {
160
139
  ...options.capabilities?.continue && { onResume: () => dispatch({ type: "run/continue" }) },
161
140
  ...options.capabilities?.reload && { onReload: handleReload },
162
141
  ...inputRequests !== void 0 && {
163
- onAddToolResult: (toolOptions) => {
164
- const inputCommand = resolveToolResultInput(inputRequests, toolOptions);
165
- dispatch(inputCommand ?? {
166
- type: "add-tool-result",
167
- toolCallId: toolOptions.toolCallId,
168
- toolName: toolOptions.toolName,
169
- result: toolOptions.result,
170
- isError: toolOptions.isError,
171
- ...toolOptions.artifact !== void 0 && { artifact: toolOptions.artifact },
172
- ...toolOptions.modelContent !== void 0 && { modelContent: toolOptions.modelContent }
173
- });
174
- },
142
+ onAddToolResult: (toolOptions) => dispatch(resolveToolResultInput(inputRequests, toolOptions)),
175
143
  onRespondToToolApproval: (approval) => dispatch(resolveToolApprovalInput(inputRequests, approval))
176
144
  },
177
145
  onCancel: () => {
@@ -1 +1 @@
1
- {"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","AddToolResultOptions","AppendMessage","AttachmentAdapter","ExternalThreadQueueAdapter","ModelContext","RespondToToolApprovalOptions","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","StatewireClient","symbolAssistantTransportExtras","AssistantTransportExtras","createRunQueueAdapter","resolveReloadCommand","toWireMessage","resolveToolApprovalInput","resolveToolResultInput","AddMessageCommand","AssistantTransportCommand","UserMessagePart","AnyCommands","Record","args","ambientContextOf","context","system","undefined","tools","callSettings","config","convertAppendMessageToCommand","message","role","Error","parts","content","attachments","flatMap","a","contentPart","type","push","text","image","length","parentId","sourceId","withSessionLostFallback","transport","StatewireThread","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","inputRequests","inputSeam","extras","sendCommand","reconnect","handleAppend","handleReload","messages","handleEdit","crypto","randomUUID","isRunning","isLoading","attachmentAdapter","adapters","onNew","capabilities","edit","onEdit","continue","onResume","reload","onReload","onAddToolResult","toolOptions","inputCommand","toolCallId","toolName","result","isError","artifact","modelContent","onRespondToToolApproval","approval","onCancel","payload","stopPayload","Array","isArray","T","TextPart","FilePart","mediaType","url","filename","UserMessage","id","Placement","insertAfter","insertBefore","RunEnqueueCommand","messageId","RunSteerCommand","RunDequeueCommand","RunEditCommand","RunContinueCommand","ToolCallInputRequest","ToolApprovalInputRequest","CustomInputRequest","InputRequest","ToolCallInputResponse","output","ToolApprovalInputResponse","decision","editedArgs","InputResponse","RunInputCommand","requestId","response","InputRequestState","RunReloadCommand","RunCommand","QueueItem","State","ConnectionState","StateConverter","connectionMetadata","StopPayload","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 AddToolResultOptions,\n AppendMessage,\n AttachmentAdapter,\n ExternalThreadQueueAdapter,\n ModelContext,\n RespondToToolApprovalOptions,\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 { symbolAssistantTransportExtras } from \"./AssistantTransportThread\";\nimport type { AssistantTransportExtras } from \"./AssistantTransportThread\";\nimport {\n createRunQueueAdapter,\n resolveReloadCommand,\n toWireMessage,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\nimport type {\n AddMessageCommand,\n AssistantTransportCommand,\n UserMessagePart,\n} 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 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 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(\n (): ExternalThreadQueueAdapter | undefined =>\n queueItems\n ? createRunQueueAdapter(queueItems, steerQueueItems, dispatch)\n : undefined,\n [queueItems, steerQueueItems, dispatch],\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,\n ...(inputRequests !== undefined && { inputRequests }),\n }),\n [dispatch, connection.reconnect, state, inputRequests],\n );\n\n const handleAppend = (message: AppendMessage) => {\n const command = convertAppendMessageToCommand(message);\n if (!command) return;\n dispatch(command);\n };\n\n const handleReload = (parentId: string | null) => {\n dispatch(resolveReloadCommand(converted.messages, parentId));\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 ...(options.capabilities?.reload && { onReload: handleReload }),\n ...(inputRequests !== undefined && {\n onAddToolResult: (toolOptions: AddToolResultOptions) => {\n const inputCommand = resolveToolResultInput(\n inputRequests,\n toolOptions,\n );\n dispatch(\n inputCommand ?? {\n type: \"add-tool-result\",\n toolCallId: toolOptions.toolCallId,\n toolName: toolOptions.toolName,\n result: toolOptions.result,\n isError: toolOptions.isError,\n ...(toolOptions.artifact !== undefined && {\n artifact: toolOptions.artifact,\n }),\n ...(toolOptions.modelContent !== undefined && {\n modelContent: toolOptions.modelContent,\n }),\n },\n );\n },\n onRespondToToolApproval: (approval: RespondToToolApprovalOptions) =>\n dispatch(resolveToolApprovalInput(inputRequests, approval)),\n }),\n onCancel: () => {\n const payload = latest.current.stopPayload?.();\n if (\n payload !== undefined &&\n (typeof payload !== \"object\" ||\n payload === null ||\n Array.isArray(payload))\n )\n throw new Error(\"statewire: stopPayload must return a plain object\");\n void commands[\"run/stop\"]!(\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 ToolCallInputRequest = {\n readonly type: \"tool-call\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type ToolApprovalInputRequest = {\n readonly type: \"tool-approval\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type CustomInputRequest = {\n readonly type: string;\n readonly id: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A host request parking the run until answered; open union for custom types. */\n export type InputRequest =\n | ToolCallInputRequest\n | ToolApprovalInputRequest\n | CustomInputRequest;\n\n export type ToolCallInputResponse = {\n readonly output: ReadonlyJSONValue;\n /** Default false; when true, `output` carries the error payload. */\n readonly isError?: boolean;\n readonly artifact?: ReadonlyJSONValue;\n };\n\n export type ToolApprovalInputResponse = {\n readonly decision: \"approve\" | \"reject\" | \"edit\" | \"respond\";\n readonly editedArgs?: ReadonlyJSONValue;\n readonly message?: string;\n };\n\n export type InputResponse = ReadonlyJSONValue;\n\n export type RunInputCommand = {\n readonly type: \"run/input\";\n readonly requestId: string;\n readonly response: InputResponse;\n };\n\n /** An input request projected out of the host state with its response echo. */\n export type InputRequestState = InputRequest & {\n readonly response: InputResponse | null;\n };\n\n export type RunReloadCommand = {\n readonly type: \"run/reload\";\n readonly sourceId: string;\n };\n\n export type RunCommand =\n | RunEnqueueCommand\n | RunSteerCommand\n | RunDequeueCommand\n | RunEditCommand\n | RunContinueCommand\n | RunReloadCommand\n | RunInputCommand;\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 * The host's parked input requests projected out of the state. Returning\n * it (even empty) routes tool results and approvals with a matching\n * pending request through `run/input`. Presence must be stable across\n * conversions.\n */\n readonly inputRequests?: readonly InputRequestState[];\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/stop` command. `reason` is the one well-known\n * field; apps extend it with their own JSON-serializable fields.\n */\n export type StopPayload = {\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/stop` command's payload; omitted, stop sends no payload. */\n stopPayload?: (() => StopPayload) | 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 /** The host supports `run/reload` (regenerating an assistant message). */\n reload?: 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":";;;;;;;;;;AA0CA,MAAMsC,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWC,KAAAA,KAAa,EAAED,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQG,UAAUD,KAAAA,KAAa,EACjCC,OAAOtB,kBAAkBmB,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,iCACJC,YAC6B;CAC7B,IAAIA,QAAQC,SAAS,QACnB,MAAM,IAAIC,MAAM,kCAAkC;CAEpD,MAAMC,QAA2B,CAAA;CACjC,MAAMC,UAAU,CACd,GAAGJ,QAAQI,SACX,GAAIJ,QAAQK,aAAaC,SAASC,MAAMA,EAAEH,OAAO,KAAK,CAAA,CAAG;CAE3D,KAAK,MAAMI,eAAeJ,SACxB,IAAII,YAAYC,SAAS,QACvBN,MAAMO,KAAK;EAAED,MAAM;EAAQE,MAAMH,YAAYG;CAAK,CAAC;MAC9C,IAAIH,YAAYC,SAAS,SAC9BN,MAAMO,KAAK;EAAED,MAAM;EAASG,OAAOJ,YAAYI;CAAM,CAAC;CAI1D,IAAIT,MAAMU,WAAW,GAAG,OAAO;CAE/B,OAAO;EACLJ,MAAM;EACNT,SAAS;GACPC,MAAM;GACNE;EACF;EACAW,UAAUd,QAAQc;EAClBC,UAAUf,QAAQe;CACpB;AACF;AAEA,MAAMC,2BACJC,WACAG,WACmC;CACnC,MAAM,CAAC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BACEiE,oBACAnE,eAAeiC,KAAAA,CAAkB,CAAC,CAACoK,IACrC"}
1
+ {"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","AddToolResultOptions","AppendMessage","AttachmentAdapter","ExternalThreadQueueAdapter","ModelContext","RespondToToolApprovalOptions","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","StatewireClient","symbolAssistantTransportExtras","AssistantTransportExtras","createRunQueueAdapter","resolveReloadCommand","toWireMessage","viewedLeafId","resolveToolApprovalInput","resolveToolResultInput","AssistantTransportCommand","AnyCommands","Record","args","ambientContextOf","context","system","undefined","tools","callSettings","config","withSessionLostFallback","transport","StatewireThread","Transport","latest","current","Options","transportOptions","rest","length","Error","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","type","converter","metadata","ConnectionMetadata","pendingCommands","isSending","converted","queueItems","queue","steerQueueItems","steerQueue","queueSeam","present","messages","inputRequests","inputSeam","extras","sendCommand","reconnect","handleAppend","message","crypto","randomUUID","anchorMessageId","handleReload","parentId","handleEdit","sourceId","isRunning","isLoading","attachmentAdapter","adapters","attachments","onNew","capabilities","edit","onEdit","continue","onResume","reload","onReload","onAddToolResult","toolOptions","onRespondToToolApproval","approval","onCancel","payload","stopPayload","Array","isArray","T","TextPart","text","FilePart","mediaType","url","filename","UserMessage","id","role","parts","Placement","insertAfter","insertBefore","RunEnqueueCommand","messageId","RunSteerCommand","RunDequeueCommand","RunEditCommand","RunContinueCommand","ToolCallInputRequest","toolCallId","ToolApprovalInputRequest","CustomInputRequest","InputRequest","ToolCallInputResponse","output","isError","artifact","ToolApprovalInputResponse","decision","editedArgs","InputResponse","RunInputCommand","requestId","response","InputRequestState","RunReloadCommand","RunCommand","QueueItem","State","ConnectionState","StateConverter","connectionMetadata","StopPayload","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 AddToolResultOptions,\n AppendMessage,\n AttachmentAdapter,\n ExternalThreadQueueAdapter,\n ModelContext,\n RespondToToolApprovalOptions,\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 { symbolAssistantTransportExtras } from \"./AssistantTransportThread\";\nimport type { AssistantTransportExtras } from \"./AssistantTransportThread\";\nimport {\n createRunQueueAdapter,\n resolveReloadCommand,\n toWireMessage,\n viewedLeafId,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\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 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(\n (): ExternalThreadQueueAdapter | undefined =>\n queueItems\n ? createRunQueueAdapter(\n converted.messages,\n queueItems,\n steerQueueItems,\n dispatch,\n )\n : undefined,\n [converted.messages, queueItems, steerQueueItems, dispatch],\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,\n ...(inputRequests !== undefined && { inputRequests }),\n }),\n [dispatch, connection.reconnect, state, inputRequests],\n );\n\n const handleAppend = (message: AppendMessage) => {\n dispatch({\n type: \"run/steer\",\n message: toWireMessage(message, crypto.randomUUID()),\n anchorMessageId: viewedLeafId(converted.messages),\n });\n };\n\n const handleReload = (parentId: string | null) => {\n dispatch(resolveReloadCommand(converted.messages, parentId));\n };\n\n const handleEdit = (message: AppendMessage) => {\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 ...(options.capabilities?.reload && { onReload: handleReload }),\n ...(inputRequests !== undefined && {\n onAddToolResult: (toolOptions: AddToolResultOptions) =>\n dispatch(resolveToolResultInput(inputRequests, toolOptions)),\n onRespondToToolApproval: (approval: RespondToToolApprovalOptions) =>\n dispatch(resolveToolApprovalInput(inputRequests, approval)),\n }),\n onCancel: () => {\n const payload = latest.current.stopPayload?.();\n if (\n payload !== undefined &&\n (typeof payload !== \"object\" ||\n payload === null ||\n Array.isArray(payload))\n )\n throw new Error(\"statewire: stopPayload must return a plain object\");\n void commands[\"run/stop\"]!(\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 } & (\n | {\n readonly message: UserMessage;\n /** 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. */\n readonly anchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunSteerCommand = {\n readonly type: \"run/steer\";\n } & (\n | {\n readonly message: UserMessage;\n /** 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. */\n readonly anchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\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 ToolCallInputRequest = {\n readonly type: \"tool-call\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type ToolApprovalInputRequest = {\n readonly type: \"tool-approval\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type CustomInputRequest = {\n readonly type: string;\n readonly id: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A host request parking the run until answered; open union for custom types. */\n export type InputRequest =\n | ToolCallInputRequest\n | ToolApprovalInputRequest\n | CustomInputRequest;\n\n export type ToolCallInputResponse = {\n readonly output: ReadonlyJSONValue;\n /** Default false; when true, `output` carries the error payload. */\n readonly isError?: boolean;\n readonly artifact?: ReadonlyJSONValue;\n };\n\n export type ToolApprovalInputResponse = {\n readonly decision: \"approve\" | \"reject\" | \"edit\" | \"respond\";\n readonly editedArgs?: ReadonlyJSONValue;\n readonly message?: string;\n };\n\n export type InputResponse = ReadonlyJSONValue;\n\n export type RunInputCommand = {\n readonly type: \"run/input\";\n readonly requestId: string;\n readonly response: InputResponse;\n };\n\n /** An input request projected out of the host state with its response echo. */\n export type InputRequestState = InputRequest & {\n readonly response: InputResponse | null;\n };\n\n export type RunReloadCommand = {\n readonly type: \"run/reload\";\n readonly sourceId: string;\n /** Client-generated id of the regenerated assistant message. */\n readonly messageId: string;\n };\n\n export type RunCommand =\n | RunEnqueueCommand\n | RunSteerCommand\n | RunDequeueCommand\n | RunEditCommand\n | RunContinueCommand\n | RunReloadCommand\n | RunInputCommand;\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 * The host's parked input requests projected out of the state. Returning\n * it (even empty) routes tool results and approvals with a matching\n * pending request through `run/input`. Presence must be stable across\n * conversions.\n */\n readonly inputRequests?: readonly InputRequestState[];\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/stop` command. `reason` is the one well-known\n * field; apps extend it with their own JSON-serializable fields.\n */\n export type StopPayload = {\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/stop` command's payload; omitted, stop sends no payload. */\n stopPayload?: (() => StopPayload) | 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 /** The host supports `run/reload` (regenerating an assistant message). */\n reload?: 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":";;;;;;;;;;AAuCA,MAAMqC,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWC,KAAAA,KAAa,EAAED,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQG,UAAUD,KAAAA,KAAa,EACjCC,OAAOrB,kBAAkBkB,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,2BACJC,WACAG,WACmC;CACnC,MAAM,CAACG,kBAAkB,GAAGC,QAAQP,UAAUT;CAI9C,IACEgB,KAAKC,SAAS,KACd,OAAOF,qBAAqB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;EACP,GAAIX,SAAS,EAAEA,MAAM;EACrB,GAAI9C,QAAQwE,cAAcC,QAAQ,EAAEC,QAAQV,WAAW;EACvD,GAAIhE,QAAQwE,cAAcG,YAAY,EACpCC,gBAAgBvC,SAAS,EAAEC,MAAM,eAAe,CAAC,EACnD;EACA,GAAItC,QAAQwE,cAAcK,UAAU,EAAEC,UAAUhB,aAAa;EAC7D,GAAIV,kBAAkBxE,KAAAA,KAAa;GACjCmG,kBAAkBC,gBAChB3C,SAASjE,uBAAuBgF,eAAe4B,WAAW,CAAC;GAC7DC,0BAA0BC,aACxB7C,SAASlE,yBAAyBiF,eAAe8B,QAAQ,CAAC;EAC9D;EACAC,gBAAgB;GACd,MAAMC,UAAUhG,OAAOC,QAAQgG,cAAc;GAC7C,IACED,YAAYxG,KAAAA,MACX,OAAOwG,YAAY,YAClBA,YAAY,QACZE,MAAMC,QAAQH,OAAO,IAEvB,MAAM,IAAI1F,MAAM,mDAAmD;GACrE,SAAc,WAAW,CACvB,GAAI0F,YAAYxG,KAAAA,IAAY,CAAA,IAAK,CAACwG,OAAO,CAC3C,CAAC,CAACnD,OAAOC,YAAiB;IACxB9C,OAAOC,QAAQ8C,UAAUD,OAAK;GAChC,CAAC;EACH;CACF,CAAC,CACH;AACF;AAEA,MAAahD,mBACXc,YAEAvD,SAASsD,kBAAkB,CAAC,CAACC,OAAuC;AAkOtElD,uBACEiD,oBACAnD,eAAegC,KAAAA,CAAkB,CAAC,CAAC0J,IACrC"}
package/dist/host.d.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  import { AssistantTransportCommand, AssistantTransportOptions } from "./types.js";
2
2
  import { ModelContext } from "@assistant-ui/core";
3
- import { Statewire } from "statewire";
4
3
  //#region src/host.d.ts
5
4
  type SendOptions = {
6
5
  schedule?: boolean;
@@ -33,7 +32,7 @@ type AssistantTransportHostCommands = {
33
32
  resume(): void;
34
33
  importState(state: unknown): void;
35
34
  };
36
- declare const AssistantTransportHost: import("@assistant-ui/tap").Resource<Statewire<AssistantTransportHostState, AssistantTransportHostCommands, any>, [options: HostOptions]>;
35
+ declare const AssistantTransportHost: import("@assistant-ui/tap").Resource<Statewire<AssistantTransportHostState, AssistantTransportHostCommands>, [options: HostOptions]>;
37
36
  //#endregion
38
37
  export { AssistantTransportHost, AssistantTransportHostCommands, AssistantTransportHostState, HostOptions, HostQueue, HostQueueCell, HostRunContext, SendOptions };
39
38
  //# sourceMappingURL=host.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"host.d.ts","names":[],"sources":["../src/host.ts"],"mappings":";;;;KA0BY;EACV;;KAGU;EACV,cAAc;EACd;;KAGU;EACV,QAAQ;EACR,WAAW;;KAMD;EAAkB,SAAS;;KAE3B,cAAc;EACxB,qBAAqB;EACrB,WAAW;;KAGD;EACV;EACA;EACA;EACA;;KAGU;EACV,KAAK,SAAS,2BAA2B,OAAO;EAChD,YAAY;EACZ;EACA;EACA,YAAY;;cAwXD,oDAAsB,SAAA,UAAA,6BAAA,uCAAA,SAAA"}
1
+ {"version":3,"file":"host.d.ts","names":[],"sources":["../src/host.ts"],"mappings":";;;KA0BY;EACV;;KAGU;EACV,cAAc;EACd;;KAGU;EACV,QAAQ;EACR,WAAW;;KAMD;EAAkB,SAAS;;KAE3B,cAAc;EACxB,qBAAqB;EACrB,WAAW;;KAGD;EACV;EACA;EACA;EACA;;KAGU;EACV,KAAK,SAAS,2BAA2B,OAAO;EAChD,YAAY;EACZ;EACA;EACA,YAAY;;cAwXD,oDAAsB,SAAA,UAAA,6BAAA,kCAAA,SAAA"}
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { AddMessageCommand, AddToolResultCommand, AssistantMessage, AssistantTransportCommand, AssistantTransportConnectionMetadata, AssistantTransportOptions, AssistantTransportProtocol, AssistantTransportState, AssistantTransportStateConverter, CustomInputRequest, FilePart, HeadersValue, ImagePart, InputRequest, InputRequestState, InputResponse, RunCommand, RunContinueCommand, RunDequeueCommand, RunEditCommand, RunEnqueueCommand, RunInputCommand, RunPlacement, RunQueueItem, RunReloadCommand, RunSteerCommand, RunUserMessage, SendCommandsRequestBody, TextPart, ToolApprovalInputRequest, ToolApprovalInputResponse, ToolCallInputRequest, ToolCallInputResponse, UserMessage, UserMessagePart } from "./types.js";
1
+ import { AssistantTransportCommand, AssistantTransportConnectionMetadata, AssistantTransportOptions, AssistantTransportProtocol, AssistantTransportState, AssistantTransportStateConverter, CustomInputRequest, FilePart, HeadersValue, InputRequest, InputRequestState, InputResponse, RunCommand, RunContinueCommand, RunDequeueCommand, RunEditCommand, RunEnqueueCommand, RunInputCommand, RunPlacement, RunQueueItem, RunReloadCommand, RunSteerCommand, RunUserMessage, SendCommandsRequestBody, TextPart, ToolApprovalInputRequest, ToolApprovalInputResponse, ToolCallInputRequest, ToolCallInputResponse } from "./types.js";
2
2
  import { AssistantTransportThread } from "./AssistantTransportThread.js";
3
3
  import { StatewireThread } from "./StatewireThread.js";
4
4
  import { useAssistantTransportSendCommand, useAssistantTransportState } from "./hooks.js";
@@ -10,8 +10,6 @@ declare namespace AssistantTransportThread {
10
10
  type State = AssistantTransportState;
11
11
  type ConnectionMetadata = AssistantTransportConnectionMetadata;
12
12
  type StateConverter<T> = AssistantTransportStateConverter<T>;
13
- type AddMessageCommand = AddMessageCommand;
14
- type AddToolResultCommand = AddToolResultCommand;
15
13
  type RunCommand = RunCommand;
16
14
  type RunEnqueueCommand = RunEnqueueCommand;
17
15
  type RunSteerCommand = RunSteerCommand;
@@ -32,12 +30,8 @@ declare namespace AssistantTransportThread {
32
30
  type RunQueueItem = RunQueueItem;
33
31
  type RunPlacement = RunPlacement;
34
32
  type SendCommandsRequestBody = SendCommandsRequestBody;
35
- type UserMessage = UserMessage;
36
- type AssistantMessage = AssistantMessage;
37
- type UserMessagePart = UserMessagePart;
38
33
  type TextPart = TextPart;
39
34
  type FilePart = FilePart;
40
- type ImagePart = ImagePart;
41
35
  type HeadersValue = HeadersValue;
42
36
  }
43
37
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;kBAUiB;OACH,QAAQ,KAAK,0BAAgC;OAC7C,UAAU;OACV,WAAW;OACX,QAAQ;OACR,qBAAqB;OACrB,eAAe,KAAK,iCAAuC;OAC3D,oBAAoB;OACpB,uBAAuB;OACvB,aAAa;OACb,oBAAoB;OACpB,kBAAkB;OAClB,oBAAoB;OACpB,iBAAiB;OACjB,qBAAqB;OACrB,mBAAmB;OACnB,kBAAkB;OAClB,eAAe;OACf,uBAAuB;OACvB,2BAA2B;OAC3B,qBAAqB;OACrB,oBAAoB;OACpB,gBAAgB;OAChB,wBAAwB;OACxB,4BAA4B;OAC5B,iBAAiB;OACjB,eAAe;OACf,eAAe;OACf,0BAA0B;OAC1B,cAAc;OACd,mBAAmB;OACnB,kBAAkB;OAClB,WAAW;OACX,WAAW;OACX,YAAY;OACZ,eAAe"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;kBAUiB;OACH,QAAQ,KAAK,0BAAgC;OAC7C,UAAU;OACV,WAAW;OACX,QAAQ;OACR,qBAAqB;OACrB,eAAe,KAAK,iCAAuC;OAC3D,aAAa;OACb,oBAAoB;OACpB,kBAAkB;OAClB,oBAAoB;OACpB,iBAAiB;OACjB,qBAAqB;OACrB,mBAAmB;OACnB,kBAAkB;OAClB,eAAe;OACf,uBAAuB;OACvB,2BAA2B;OAC3B,qBAAqB;OACrB,oBAAoB;OACpB,gBAAgB;OAChB,wBAAwB;OACxB,4BAA4B;OAC5B,iBAAiB;OACjB,eAAe;OACf,eAAe;OACf,0BAA0B;OAC1B,WAAW;OACX,WAAW;OACX,eAAe"}
@@ -7,7 +7,7 @@ declare const resolveToolResultInput: (inputRequests: readonly InputRequestState
7
7
  result: ReadonlyJSONValue;
8
8
  isError: boolean;
9
9
  artifact?: ReadonlyJSONValue | undefined;
10
- }) => RunInputCommand | undefined;
10
+ }) => RunInputCommand;
11
11
  declare const resolveToolApprovalInput: (inputRequests: readonly InputRequestState[], options: RespondToToolApprovalOptions) => RunInputCommand;
12
12
  //#endregion
13
13
  export { resolveToolApprovalInput, resolveToolResultInput };
@@ -1 +1 @@
1
- {"version":3,"file":"inputRequests.d.ts","names":[],"sources":["../src/inputRequests.ts"],"mappings":";;;;cAWa,yBACX,wBAAwB,qBACxB;EACE;EACA,QAAQ;EACR;EACA,WAAW;MAEZ;cAiBU,2BACX,wBAAwB,qBACxB,SAAS,iCACR"}
1
+ {"version":3,"file":"inputRequests.d.ts","names":[],"sources":["../src/inputRequests.ts"],"mappings":";;;;cAWa,yBACX,wBAAwB,qBACxB;EACE;EACA,QAAQ;EACR;EACA,WAAW;MAEZ;cAoBU,2BACX,wBAAwB,qBACxB,SAAS,iCACR"}
@@ -4,7 +4,7 @@ const assertUnanswered = (request) => {
4
4
  };
5
5
  const resolveToolResultInput = (inputRequests, options) => {
6
6
  const request = inputRequests.find((r) => r.type === "tool-call" && r.toolCallId === options.toolCallId);
7
- if (request === void 0) return void 0;
7
+ if (request === void 0) throw new Error(`statewire: no tool-call input request for tool call "${options.toolCallId}"`);
8
8
  assertUnanswered(request);
9
9
  return {
10
10
  type: "run/input",
@@ -1 +1 @@
1
- {"version":3,"file":"inputRequests.js","names":["RespondToToolApprovalOptions","ReadonlyJSONValue","InputRequestState","RunInputCommand","assertUnanswered","request","response","Error","id","resolveToolResultInput","inputRequests","options","toolCallId","result","isError","artifact","find","r","type","undefined","requestId","output","resolveToolApprovalInput","approvalId","decision","approved","reason","message"],"sources":["../src/inputRequests.ts"],"sourcesContent":["import type { RespondToToolApprovalOptions } from \"@assistant-ui/core\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport type { InputRequestState, RunInputCommand } from \"./types\";\n\nconst assertUnanswered = (request: InputRequestState) => {\n if (request.response !== null)\n throw new Error(\n `statewire: input request \"${request.id}\" is already answered`,\n );\n};\n\nexport const resolveToolResultInput = (\n inputRequests: readonly InputRequestState[],\n options: {\n toolCallId: string;\n result: ReadonlyJSONValue;\n isError: boolean;\n artifact?: ReadonlyJSONValue | undefined;\n },\n): RunInputCommand | undefined => {\n const request = inputRequests.find(\n (r) => r.type === \"tool-call\" && r.toolCallId === options.toolCallId,\n );\n if (request === undefined) return undefined;\n assertUnanswered(request);\n return {\n type: \"run/input\",\n requestId: request.id,\n response: {\n output: options.result,\n ...(options.isError && { isError: true }),\n ...(options.artifact !== undefined && { artifact: options.artifact }),\n },\n };\n};\n\nexport const resolveToolApprovalInput = (\n inputRequests: readonly InputRequestState[],\n options: RespondToToolApprovalOptions,\n): RunInputCommand => {\n const request = inputRequests.find(\n (r) => r.type === \"tool-approval\" && r.id === options.approvalId,\n );\n if (request === undefined)\n throw new Error(\n `statewire: no tool-approval input request \"${options.approvalId}\"`,\n );\n assertUnanswered(request);\n return {\n type: \"run/input\",\n requestId: request.id,\n response: {\n decision: options.approved ? \"approve\" : \"reject\",\n ...(options.reason !== undefined && { message: options.reason }),\n },\n };\n};\n"],"mappings":";AAIA,MAAMI,oBAAoBC,YAA+B;CACvD,IAAIA,QAAQC,aAAa,MACvB,MAAM,IAAIC,MACR,6BAA6BF,QAAQG,GAAE,sBACzC;AACJ;AAEA,MAAaC,0BACXC,eACAC,YAMgC;CAChC,MAAMN,UAAUK,cAAcM,MAC3BC,MAAMA,EAAEC,SAAS,eAAeD,EAAEL,eAAeD,QAAQC,UAC5D;CACA,IAAIP,YAAYc,KAAAA,GAAW,OAAOA,KAAAA;CAClCf,iBAAiBC,OAAO;CACxB,OAAO;EACLa,MAAM;EACNE,WAAWf,QAAQG;EACnBF,UAAU;GACRe,QAAQV,QAAQE;GAChB,GAAIF,QAAQG,WAAW,EAAEA,SAAS,KAAK;GACvC,GAAIH,QAAQI,aAAaI,KAAAA,KAAa,EAAEJ,UAAUJ,QAAQI,SAAS;EACrE;CACF;AACF;AAEA,MAAaO,4BACXZ,eACAC,YACoB;CACpB,MAAMN,UAAUK,cAAcM,MAC3BC,MAAMA,EAAEC,SAAS,mBAAmBD,EAAET,OAAOG,QAAQY,UACxD;CACA,IAAIlB,YAAYc,KAAAA,GACd,MAAM,IAAIZ,MACR,8CAA8CI,QAAQY,WAAU,EAClE;CACFnB,iBAAiBC,OAAO;CACxB,OAAO;EACLa,MAAM;EACNE,WAAWf,QAAQG;EACnBF,UAAU;GACRkB,UAAUb,QAAQc,WAAW,YAAY;GACzC,GAAId,QAAQe,WAAWP,KAAAA,KAAa,EAAEQ,SAAShB,QAAQe,OAAO;EAChE;CACF;AACF"}
1
+ {"version":3,"file":"inputRequests.js","names":["RespondToToolApprovalOptions","ReadonlyJSONValue","InputRequestState","RunInputCommand","assertUnanswered","request","response","Error","id","resolveToolResultInput","inputRequests","options","toolCallId","result","isError","artifact","find","r","type","undefined","requestId","output","resolveToolApprovalInput","approvalId","decision","approved","reason","message"],"sources":["../src/inputRequests.ts"],"sourcesContent":["import type { RespondToToolApprovalOptions } from \"@assistant-ui/core\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport type { InputRequestState, RunInputCommand } from \"./types\";\n\nconst assertUnanswered = (request: InputRequestState) => {\n if (request.response !== null)\n throw new Error(\n `statewire: input request \"${request.id}\" is already answered`,\n );\n};\n\nexport const resolveToolResultInput = (\n inputRequests: readonly InputRequestState[],\n options: {\n toolCallId: string;\n result: ReadonlyJSONValue;\n isError: boolean;\n artifact?: ReadonlyJSONValue | undefined;\n },\n): RunInputCommand => {\n const request = inputRequests.find(\n (r) => r.type === \"tool-call\" && r.toolCallId === options.toolCallId,\n );\n if (request === undefined)\n throw new Error(\n `statewire: no tool-call input request for tool call \"${options.toolCallId}\"`,\n );\n assertUnanswered(request);\n return {\n type: \"run/input\",\n requestId: request.id,\n response: {\n output: options.result,\n ...(options.isError && { isError: true }),\n ...(options.artifact !== undefined && { artifact: options.artifact }),\n },\n };\n};\n\nexport const resolveToolApprovalInput = (\n inputRequests: readonly InputRequestState[],\n options: RespondToToolApprovalOptions,\n): RunInputCommand => {\n const request = inputRequests.find(\n (r) => r.type === \"tool-approval\" && r.id === options.approvalId,\n );\n if (request === undefined)\n throw new Error(\n `statewire: no tool-approval input request \"${options.approvalId}\"`,\n );\n assertUnanswered(request);\n return {\n type: \"run/input\",\n requestId: request.id,\n response: {\n decision: options.approved ? \"approve\" : \"reject\",\n ...(options.reason !== undefined && { message: options.reason }),\n },\n };\n};\n"],"mappings":";AAIA,MAAMI,oBAAoBC,YAA+B;CACvD,IAAIA,QAAQC,aAAa,MACvB,MAAM,IAAIC,MACR,6BAA6BF,QAAQG,GAAE,sBACzC;AACJ;AAEA,MAAaC,0BACXC,eACAC,YAMoB;CACpB,MAAMN,UAAUK,cAAcM,MAC3BC,MAAMA,EAAEC,SAAS,eAAeD,EAAEL,eAAeD,QAAQC,UAC5D;CACA,IAAIP,YAAYc,KAAAA,GACd,MAAM,IAAIZ,MACR,wDAAwDI,QAAQC,WAAU,EAC5E;CACFR,iBAAiBC,OAAO;CACxB,OAAO;EACLa,MAAM;EACNE,WAAWf,QAAQG;EACnBF,UAAU;GACRe,QAAQV,QAAQE;GAChB,GAAIF,QAAQG,WAAW,EAAEA,SAAS,KAAK;GACvC,GAAIH,QAAQI,aAAaI,KAAAA,KAAa,EAAEJ,UAAUJ,QAAQI,SAAS;EACrE;CACF;AACF;AAEA,MAAaO,4BACXZ,eACAC,YACoB;CACpB,MAAMN,UAAUK,cAAcM,MAC3BC,MAAMA,EAAEC,SAAS,mBAAmBD,EAAET,OAAOG,QAAQY,UACxD;CACA,IAAIlB,YAAYc,KAAAA,GACd,MAAM,IAAIZ,MACR,8CAA8CI,QAAQY,WAAU,EAClE;CACFnB,iBAAiBC,OAAO;CACxB,OAAO;EACLa,MAAM;EACNE,WAAWf,QAAQG;EACnBF,UAAU;GACRkB,UAAUb,QAAQc,WAAW,YAAY;GACzC,GAAId,QAAQe,WAAWP,KAAAA,KAAa,EAAEQ,SAAShB,QAAQe,OAAO;EAChE;CACF;AACF"}
@@ -12,11 +12,16 @@ declare const toQueueItemState: (item: RunQueueItem) => {
12
12
  mimeType: string;
13
13
  })[];
14
14
  };
15
- declare const createRunQueueAdapter: (queueItems: readonly RunQueueItem[], steerQueueItems: readonly RunQueueItem[] | undefined, dispatch: (command: RunCommand) => void) => ExternalThreadQueueAdapter;
15
+ declare const viewedLeafId: (messages: readonly {
16
+ id: string;
17
+ }[]) => string | null;
18
+ declare const createRunQueueAdapter: (messages: readonly {
19
+ id: string;
20
+ }[], queueItems: readonly RunQueueItem[], steerQueueItems: readonly RunQueueItem[] | undefined, dispatch: (command: RunCommand) => void) => ExternalThreadQueueAdapter;
16
21
  declare const resolveReloadCommand: (messages: readonly {
17
22
  id: string;
18
23
  role: string;
19
24
  }[], parentId: string | null) => RunReloadCommand;
20
25
  //#endregion
21
- export { createRunQueueAdapter, resolveReloadCommand, toQueueItemState, toWireMessage };
26
+ export { createRunQueueAdapter, resolveReloadCommand, toQueueItemState, toWireMessage, viewedLeafId };
22
27
  //# sourceMappingURL=runCommands.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"runCommands.d.ts","names":[],"sources":["../src/runCommands.ts"],"mappings":";;;cAca,gBACX,SAAS,eACT,eACC;cAqCU,mBAAoB,MAAM;;;UAAA;;;;;;;cA0B1B,wBACX,qBAAqB,gBACrB,0BAA0B,4BAC1B,WAAW,SAAS,wBACnB;cA6CU,uBACX;EAAqB;EAAY;KACjC,4BACC"}
1
+ {"version":3,"file":"runCommands.d.ts","names":[],"sources":["../src/runCommands.ts"],"mappings":";;;cAca,gBACX,SAAS,eACT,eACC;cAqCU,mBAAoB,MAAM;;;UAAA;;;;;;;cA0B1B,eACX;EAAqB;;cAGV,wBACX;EAAqB;KACrB,qBAAqB,gBACrB,0BAA0B,4BAC1B,WAAW,SAAS,wBACnB;cA+CU,uBACX;EAAqB;EAAY;KACjC,4BACC"}