@assistant-ui/react-statewire 0.11.1 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -12,6 +12,8 @@ type AssistantTransportExtras = {
12
12
  sendCommand: (command: AssistantTransportThread.Command) => void;
13
13
  reconnect: () => void;
14
14
  state: unknown;
15
+ /** The thread status; present iff StatewireThread. */
16
+ status?: StatewireThread.ThreadStatus;
15
17
  /** The host's parked input requests; absent when the converter does not project them. */
16
18
  inputRequests?: readonly AssistantTransportThread.InputRequestState[];
17
19
  /** The typed runs read; present iff StatewireThread runs with the `runs` option. */
@@ -1 +1 @@
1
- {"version":3,"file":"AssistantTransportThread.d.ts","names":[],"sources":["../src/AssistantTransportThread.ts"],"mappings":";;;;;;;;cA6Da;KAID;GACT;EACD,cAAc,SAAS,yBAAyB;EAChD;EACA;;EAEA,yBAAyB,yBAAyB;;EAElD,OAAO,gBAAgB;;cAGZ,6BACX,oBACC;cA4ZU,2BAA4B,GACvC,SAAS,yBAAyB,QAAQ,OACzC,gBAAgB;kBAKF;OACV,eAAe,UAAU,eAAe,UAAU;cAE3C;aACD;aACA;;cAGC;aACD;aACA;aACA;aACA;;cAGC;aACD;aACA;aACA,iBAAiB,WAAW;aAC5B,WAAW;;;cAIV;aACD;aACA;;cAGC;aACD;;aAGI,SAAS;;aAET;;aAEA;OAEb;cAEU;aACD;;aAGI,SAAS;;aAET;;aAEA;OAEb;cAEU;aACD;aACA;;cAGC;aACD;aACA,SAAS;aACT;;aAEA;;cAGC;aACD;;cAGC;aACD;aACA;aACA;;cAGC;aACD;aACA;aACA;;cAGC;aACD;aACA;cACC,cAAc;;;cAId,eACR,uBACA,2BACA;cAEQ;aACD,QAAQ;;aAER;aACA,WAAW;;cAGV;aACD;aACA,aAAa;aACb;;cAGC,gBAAgB;cAEhB;aACD;aACA;aACA,UAAU;;;cAIT,oBAAoB;aACrB,UAAU;;cAGT;aACD;aACA;;aAEA;;cAGC,aACR,oBACA,kBACA,oBACA,iBACA,qBACA,mBACA;cAEQ,UAAU,aAAa;;cAGvB;aACD;aACA,iBAAiB,WAAW;;cAG3B;aACD,mBAAmB;aACnB,QAAQ;aACR;;;;;;;;aAQA,iBAAiB;;aAEjB,sBAAsB;;;;;;aAMtB,yBAAyB,yBAAyB;;cAGjD,eAAe,MAAM,OAAO,MAAM;;cAGlC,WAAW,MACrB,OAAO,GACP,SAAS,SACT,KAAK,gBAAgB;cAGX,eAAe,yBAAyB;cAExC;cAEA;IACV,UAAU;IACV;IACA;IACA,OAAO;IACP,cAAc;IACd,QAAQ;IACR;IACA;KACC;;cAGS,QAAQ;IAClB,cAAc;IACd,WAAW,eAAe;IAC1B,aAAa,WAAW;;IAExB,gBAAgB,OAAO;;IAEvB,cAAc,gBAAgB,YAAY,YAAY;IACtD;IACA;IACA,WAAW;IACX,SAAS,sBAAsB,QAAQ;IACvC,uBAAuB;;IAEvB,+BAEM,MAAM,4BACH,0BAA0B,QAAQ;IAE3C,eAAe,UAAU;IACzB;IACA,YAEM,OAAO,OACP;MACE,UAAU;MACV,cAAc,UAAU,OAAO,MAAM;iBAE7B;;;;;IAMhB,aACM;MACA,UAAU;MACV,cAAc,UAAU,OAAO,MAAM;MACrC,QAAQ;;IAGd;MAEM;;;;;;MAMA;;MAEA;;IAGN;MAEM,cAAc"}
1
+ {"version":3,"file":"AssistantTransportThread.d.ts","names":[],"sources":["../src/AssistantTransportThread.ts"],"mappings":";;;;;;;;cA6Da;KAID;GACT;EACD,cAAc,SAAS,yBAAyB;EAChD;EACA;;EAEA,SAAS,gBAAgB;;EAEzB,yBAAyB,yBAAyB;;EAElD,OAAO,gBAAgB;;cAGZ,6BACX,oBACC;cA4ZU,2BAA4B,GACvC,SAAS,yBAAyB,QAAQ,OACzC,gBAAgB;kBAKF;OACV,eAAe,UAAU,eAAe,UAAU;cAE3C;aACD;aACA;;cAGC;aACD;aACA;aACA;aACA;;cAGC;aACD;aACA;aACA,iBAAiB,WAAW;a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MAEM;;;;;;MAMA;;MAEA;;IAGN;MAEM,cAAc"}
@@ -1 +1 @@
1
- {"version":3,"file":"AssistantTransportThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","useSyncExternalStore","resource","useResource","ResourceElement","ExternalThread","Assistant","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","createMessageQueue","AddToolResultOptions","AppendMessage","AttachmentAdapter","LanguageModelConfig","LanguageModelV1CallSettings","MessageQueueController","MessageQueueDriver","RespondToToolApprovalOptions","ResumeToolCallOptions","ThreadMessage","ToolExecutionStatus","ReadonlyJSONValue","ToolInvocationTracker","applyOptimistic","useStatewire","StatewireClient","StatewireThread","AssistantTransportHost","AssistantTransportHostCommands","AssistantTransportHostState","HostQueueCell","HostRunContext","SendOptions","createRunQueueAdapter","resolveEditCommand","resolveReloadCommand","toWireMessage","viewedLeafId","runsOptimistic","resolveToolApprovalInput","resolveToolResultInput","EMPTY_TOOL_STATUSES","Record","EMPTY_QUEUE_ITEMS","subscribeNoop","symbolAssistantTransportExtras","Symbol","AssistantTransportExtras","sendCommand","command","AssistantTransportThread","Command","reconnect","state","inputRequests","InputRequestState","runs","Runs","asAssistantTransportExtras","extras","Error","foldOptimistic","commands","optimistic","Optimistic","ctxOf","OptimisticContext","next","draft","error","console","type","messagesContainToolCall","messages","toolCallId","some","message","content","part","undefined","useAssistantTransportThread","options","Options","clientRef","getRunContext","aui","current","parent","threadId","threadListItem","getState","remoteId","modelContext","getModelContext","queueCell","queued","inTransit","connection","transport","agent","agentState","isSending","isReplaying","queue","dispatch","opts","send","catch","toolStatuses","setToolStatuses","ctxs","WeakMap","seq","ctx","get","ts","Date","now","set","converter","runsOption","materialize","runsSeam","materializeSeam","project","fold","method","params","converted","convertedRef","toolInvocations","tools","onResult","onStatusesChange","statuses","size","Object","fromEntries","setState","isRunning","isLoading","reset","inputSeam","present","handleEdit","abort","then","handleAppend","sourceId","startRun","role","crypto","randomUUID","anchorMessageId","setParentId","parentId","schedule","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","T","UserCommands","Commands","TextPart","text","FilePart","mediaType","url","filename","RunUserMessage","parts","metadata","RunPlacement","insertAfter","insertBefore","RunEnqueueCommand","messageId","RunSteerCommand","RunDequeueCommand","RunEditCommand","rollbackTo","RunContinueCommand","ToolCallInputRequest","ToolApprovalInputRequest","CustomInputRequest","key","InputRequest","ToolCallInputResponse","output","isError","artifact","ToolApprovalInputResponse","decision","editedArgs","InputResponse","RunInputCommand","requestId","response","RunReloadCommand","RunCommand","RunQueueItem","State","StateConverter","HeadersValue","Headers","Protocol","SendCommandsRequestBody","system","callSettings","config","initialState","Materialize","NonNullable","api","protocol","headers","Promise","body","prepareSendCommandsRequest","onResponse","Response","onFinish","onError","updateState","updater","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 { Assistant, 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 AttachmentAdapter,\n LanguageModelConfig,\n LanguageModelV1CallSettings,\n MessageQueueController,\n MessageQueueDriver,\n RespondToToolApprovalOptions,\n ResumeToolCallOptions,\n ThreadMessage,\n ToolExecutionStatus,\n} from \"@assistant-ui/core\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { ToolInvocationTracker } from \"@assistant-ui/core/internal\";\nimport { applyOptimistic, useStatewire } from \"statewire\";\nimport type { StatewireClient } from \"statewire\";\nimport type { StatewireThread } from \"./StatewireThread\";\nimport { AssistantTransportHost } from \"./host\";\nimport type {\n AssistantTransportHostCommands,\n AssistantTransportHostState,\n HostQueueCell,\n HostRunContext,\n SendOptions,\n} from \"./host\";\nimport {\n createRunQueueAdapter,\n resolveEditCommand,\n resolveReloadCommand,\n toWireMessage,\n viewedLeafId,\n} from \"./runCommands\";\nimport { runsOptimistic } from \"./runsOptimistic\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\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: AssistantTransportThread.Command) => 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 AssistantTransportThread.InputRequestState[];\n /** The typed runs read; present iff StatewireThread runs with the `runs` option. */\n runs?: StatewireThread.Runs;\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 foldOptimistic = (\n state: unknown,\n commands: readonly AssistantTransportThread.Command[],\n optimistic: AssistantTransportThread.Optimistic<unknown>,\n ctxOf: (command: object) => StatewireClient.OptimisticContext,\n): unknown => {\n let next = state;\n for (const command of commands) {\n try {\n next = applyOptimistic(next, (draft) =>\n optimistic(draft, command, ctxOf(command)),\n );\n } catch (error) {\n console.error(\n `statewire: optimistic reducer threw for \"${command.type}\"; dropping its optimistic update`,\n error,\n );\n }\n }\n return next;\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: AssistantTransportThread.Options<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: AssistantTransportThread.Command, 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 [ctxOf] = useState(() => {\n const ctxs = new WeakMap<object, StatewireClient.OptimisticContext>();\n let seq = 0;\n return (command: object): StatewireClient.OptimisticContext => {\n let ctx = ctxs.get(command);\n if (ctx === undefined) {\n ctx = { ts: Date.now(), seq: ++seq };\n ctxs.set(command, ctx);\n }\n return ctx;\n };\n });\n\n const { converter, optimistic, runs: runsOption, materialize } = options;\n const [runsSeam] = useState(() => runsOption !== undefined);\n if (runsSeam !== (runsOption !== undefined))\n throw new Error(\n \"statewire: the runs option must be stable — it was \" +\n (runsSeam ? \"set\" : \"unset\") +\n \" on first render and changed since\",\n );\n const [materializeSeam] = useState(() => materialize !== undefined);\n if (materializeSeam !== (materialize !== undefined))\n throw new Error(\n \"statewire: the materialize option must be stable — it was \" +\n (materializeSeam ? \"set\" : \"unset\") +\n \" on first render and changed since\",\n );\n\n const project = useCallback(\n (state: unknown): unknown => {\n const fold: AssistantTransportThread.Optimistic<unknown> | undefined =\n runsOption !== undefined\n ? (draft, command, ctx) => {\n runsOptimistic(\n runsOption === true ? draft : runsOption(draft as never),\n { method: command.type, params: [command] },\n ctx,\n );\n optimistic?.(draft, command, ctx);\n }\n : optimistic;\n let next = fold\n ? foldOptimistic(\n state,\n [...queue.inTransit, ...queue.queued],\n fold,\n ctxOf,\n )\n : state;\n if (materialize) {\n try {\n next = applyOptimistic(next, (draft) => materialize(draft as never));\n } catch (error) {\n console.error(\n \"statewire: materialize threw; publishing without its update\",\n error,\n );\n }\n }\n return next;\n },\n [runsOption, optimistic, materialize, queue, ctxOf],\n );\n const converted = useMemo(\n () => converter(project(agentState)),\n [converter, project, agentState],\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 handleEdit = (message: AppendMessage) => {\n const command = resolveEditCommand(convertedRef.current.messages, message);\n void toolInvocations.abort().then(() => dispatch(command));\n };\n\n const handleAppend = (message: AppendMessage) => {\n if (message.sourceId != null) return handleEdit(message);\n const startRun = message.startRun ?? message.role === \"user\";\n const command: AssistantTransportThread.Command = {\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 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 (command) => dispatch(command),\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 = converter(project(imported));\n toolInvocations.reset();\n setToolStatuses(EMPTY_TOOL_STATUSES);\n },\n }),\n );\n};\n\nexport const AssistantTransportThread = <T>(\n options: AssistantTransportThread.Options<T>,\n): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useAssistantTransportThread)(\n options as AssistantTransportThread.Options<any>,\n );\n\nexport namespace AssistantTransportThread {\n type UserCommands = Assistant.Commands[keyof Assistant.Commands];\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 RunUserMessage = {\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 RunPlacement = {\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: RunUserMessage;\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 RunPlacement;\n\n export type RunSteerCommand = {\n readonly type: \"run/steer\";\n } & (\n | {\n readonly message: RunUserMessage;\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 RunPlacement;\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: RunUserMessage;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly rollbackTo: string | null;\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 /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly rollbackTo: string | null;\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 = RunCommand | UserCommands;\n\n /** A queued message projected out of the host state, wire shape. */\n export type RunQueueItem = {\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 server-side queue: sends become `run/enqueue`\n * / `run/steer` commands and item controls send the `run/*` queue\n * commands. Presence must be stable across conversions and excludes the\n * client-local `capabilities.queue` buffer.\n */\n readonly queue?: readonly RunQueueItem[];\n /** The host's steer lane; requires `queue`. Absent means empty. */\n readonly steerQueue?: readonly RunQueueItem[];\n /**\n * The host's parked input requests projected out of the state. Returning it\n * (even empty) routes tool results and approvals with a matching pending\n * request through `run/input`. Presence must be stable across conversions.\n */\n readonly inputRequests?: readonly AssistantTransportThread.InputRequestState[];\n };\n\n export type StateConverter<T> = (state: T) => State;\n\n /** Folds an unsettled command into a draft of the client state; called once per pending command, in send order, re-run on every state change. A throwing fold logs and drops that command's update. */\n export type Optimistic<T> = (\n draft: T,\n command: Command,\n ctx: StatewireClient.OptimisticContext,\n ) => void;\n\n export type HeadersValue = Record<string, string> | Headers;\n\n export type Protocol = \"data-stream\" | \"assistant-transport\";\n\n export type SendCommandsRequestBody = {\n commands: Command[];\n state: unknown;\n system: string | undefined;\n tools: Record<string, unknown> | undefined;\n callSettings: LanguageModelV1CallSettings | undefined;\n config: LanguageModelConfig | undefined;\n threadId: string | null;\n parentId?: string | null;\n [key: string]: unknown;\n };\n\n export type Options<T> = {\n initialState: T;\n converter: StateConverter<T>;\n optimistic?: Optimistic<T> | undefined;\n /** Folds the lib's run-dialect optimistic reducer before `optimistic`: `true` reads the run mounts off the state root; a selector picks a nested mount. */\n runs?: true | ((state: T) => unknown) | undefined;\n /** Makes dispatch records concrete in the draft (runs after the optimistic folds); without it, dispatch limbo stays out of `messages`. */\n materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;\n api: string;\n resumeApi?: string | undefined;\n protocol?: Protocol | undefined;\n headers: HeadersValue | (() => Promise<HeadersValue>);\n body?: object | (() => Promise<object | undefined>) | undefined;\n /** Transform the fully assembled request body before it is sent. */\n prepareSendCommandsRequest?:\n | ((\n body: SendCommandsRequestBody,\n ) => Record<string, unknown> | Promise<Record<string, unknown>>)\n | undefined;\n onResponse?: ((response: Response) => void) | undefined;\n onFinish?: (() => void) | undefined;\n onError?:\n | ((\n error: Error,\n params: {\n commands: Command[];\n updateState: (updater: (state: T) => T) => void;\n },\n ) => void | Promise<void>)\n | undefined;\n /**\n * Called when commands are cancelled. After an error, queued commands are\n * cancelled once `onError` settles; `error` then carries the cause.\n */\n onCancel?:\n | ((params: {\n commands: Command[];\n updateState: (updater: (state: T) => T) => void;\n error?: Error;\n }) => void)\n | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n /**\n * Buffer messages sent during a run in an in-memory queue and dispatch\n * them once the run settles. Steering interrupts the active run.\n * Mutually exclusive with the converter's `queue` projection.\n */\n queue?: boolean | undefined;\n /** The host supports `run/continue` (a continue affordance on aborted runs). */\n continue?: boolean | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n }\n | undefined;\n };\n}\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useAssistantTransportThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;;;;;AAyDA,MAAM+C,sBAA2D,CAAC;AAClE,MAAME,oBAAgE,CAAA;AACtE,MAAMC,4BAA4B,CAAC;AAEnC,MAAaC,iCAAiCC,OAC5C,4BACF;AAaA,MAAaY,8BACXC,WAC6B;CAC7B,IACE,OAAOA,WAAW,YAClBA,UAAU,QACV,EAAEd,kCAAkCc,SAEpC,MAAM,IAAIC,MACR,+FACF;CAEF,OAAOD;AACT;AAEA,MAAME,kBACJR,OACAS,UACAC,YACAE,UACY;CACZ,IAAIE,OAAOd;CACX,KAAK,MAAMJ,WAAWa,UACpB,IAAI;EACFK,OAAO5C,gBAAgB4C,OAAOC,UAC5BL,WAAWK,OAAOnB,SAASgB,MAAMhB,OAAO,CAAC,CAC3C;CACF,SAASoB,OAAO;EACdC,QAAQD,MACN,4CAA4CpB,QAAQsB,KAAI,oCACxDF,KACF;CACF;CAEF,OAAOF;AACT;AAEA,MAAMK,2BACJC,UACAC,eAEAD,SAASE,MAAMC,YACbA,QAAQC,QAAQF,MACbG,SACCA,KAAKP,SAAS,gBACbO,KAAKJ,eAAeA,cAClBI,KAAKL,aAAaM,KAAAA,KACjBP,wBAAwBM,KAAKL,UAAUC,UAAU,EACzD,CACF;AAEF,MAAMM,+BACJC,YAC2B;CAC3B,MAAME,YAAY5E,sBAAsB;CACxC,MAAM,CAAC6E,iBAAiBtF,qBAAqC;E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aAA4B;GACrC,MAAM1G,YAAUd,qBACd8F,aAAa3C,QAAQb,UACrBkF,QACF;GACA,gBAAqBV,MAAM,CAAC,CAACC,WAAW1C,SAASvD,SAAO,CAAC;EAC3D;EACA+I,gBAAgB;GAEdpB,cAAcD,MAAM;GACpBd,aAAa;EACf;EACAoC,gBAAgB;GACd,IAAIhH,QAAQqF,cAAc4B,UAAU;IAClC1F,SAAS,EAAEjC,MAAM,eAAe,CAAC;IACjC;GACF;GACA,IAAI,CAACU,QAAQkH,WACX,MAAM,IAAIvI,MAAM,+CAA+C;GACjE,SAAcwI,OAAO,CAAC,CAACzF,YAAY,CAAC,CAAC;EACvC;EACA,GAAIrD,kBAAkByB,KAAAA,KAAa;GACjCsH,kBAAkBC,gBAChB9F,SACEhE,uBACEyF,aAAa3C,QAAQhC,eACrBgJ,WACF,CACF;GACFC,0BAA0BtH,cACxBuB,SACEjE,yBACE0F,aAAa3C,QAAQhC,eACrB2B,SACF,CACF;EACJ;EACAuH,mBAAmB,EAAE9H,YAAY+H,cAAqC;GACpE,IAAI,CAACvE,gBAAgBkE,OAAO1H,YAAY+H,OAAO,GAC7C,MAAM,IAAI7I,MAAM,aAAac,WAAU,4BAA6B;EACxE;EACAgI,sBAAsBC,aAAsB;GAC1C,SAAcC,YAAYD,QAAQ,CAAC,CAAChG,YAAY,CAAC,CAAC;GAElDsB,aAAa3C,UAAUiC,UAAUK,QAAQ+E,QAAQ,CAAC;GAClDzE,gBAAgBW,MAAM;GACtBhC,gBAAgBpE,mBAAmB;EACrC;CACF,CAAC,CACH;AACF;AAEA,MAAaS,4BACX+B,YAEAjF,SAASgF,2BAA2B,CAAC,CACnCC,OACF;AA+PF3E,uBACE0E,6BACA7E,eAAe4E,KAAAA,CAAkB,CAAC,CAAC+L,IACrC"}
1
+ {"version":3,"file":"AssistantTransportThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","useSyncExternalStore","resource","useResource","ResourceElement","ExternalThread","Assistant","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","createMessageQueue","AddToolResultOptions","AppendMessage","AttachmentAdapter","LanguageModelConfig","LanguageModelV1CallSettings","MessageQueueController","MessageQueueDriver","RespondToToolApprovalOptions","ResumeToolCallOptions","ThreadMessage","ToolExecutionStatus","ReadonlyJSONValue","ToolInvocationTracker","applyOptimistic","useStatewire","StatewireClient","StatewireThread","AssistantTransportHost","AssistantTransportHostCommands","AssistantTransportHostState","HostQueueCell","HostRunContext","SendOptions","createRunQueueAdapter","resolveEditCommand","resolveReloadCommand","toWireMessage","viewedLeafId","runsOptimistic","resolveToolApprovalInput","resolveToolResultInput","EMPTY_TOOL_STATUSES","Record","EMPTY_QUEUE_ITEMS","subscribeNoop","symbolAssistantTransportExtras","Symbol","AssistantTransportExtras","sendCommand","command","AssistantTransportThread","Command","reconnect","state","status","ThreadStatus","inputRequests","InputRequestState","runs","Runs","asAssistantTransportExtras","extras","Error","foldOptimistic","commands","optimistic","Optimistic","ctxOf","OptimisticContext","next","draft","error","console","type","messagesContainToolCall","messages","toolCallId","some","message","content","part","undefined","useAssistantTransportThread","options","Options","clientRef","getRunContext","aui","current","parent","threadId","threadListItem","getState","remoteId","modelContext","getModelContext","queueCell","queued","inTransit","connection","transport","agent","agentState","isSending","isReplaying","queue","dispatch","opts","send","catch","toolStatuses","setToolStatuses","ctxs","WeakMap","seq","ctx","get","ts","Date","now","set","converter","runsOption","materialize","runsSeam","materializeSeam","project","fold","method","params","converted","convertedRef","toolInvocations","tools","onResult","onStatusesChange","statuses","size","Object","fromEntries","setState","isRunning","isLoading","reset","inputSeam","present","handleEdit","abort","then","handleAppend","sourceId","startRun","role","crypto","randomUUID","anchorMessageId","setParentId","parentId","schedule","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","T","UserCommands","Commands","TextPart","text","FilePart","mediaType","url","filename","RunUserMessage","parts","metadata","RunPlacement","insertAfter","insertBefore","RunEnqueueCommand","messageId","RunSteerCommand","RunDequeueCommand","RunEditCommand","rollbackTo","RunContinueCommand","ToolCallInputRequest","ToolApprovalInputRequest","CustomInputRequest","key","InputRequest","ToolCallInputResponse","output","isError","artifact","ToolApprovalInputResponse","decision","editedArgs","InputResponse","RunInputCommand","requestId","response","RunReloadCommand","RunCommand","RunQueueItem","State","StateConverter","HeadersValue","Headers","Protocol","SendCommandsRequestBody","system","callSettings","config","initialState","Materialize","NonNullable","api","protocol","headers","Promise","body","prepareSendCommandsRequest","onResponse","Response","onFinish","onError","updateState","updater","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 { Assistant, 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 AttachmentAdapter,\n LanguageModelConfig,\n LanguageModelV1CallSettings,\n MessageQueueController,\n MessageQueueDriver,\n RespondToToolApprovalOptions,\n ResumeToolCallOptions,\n ThreadMessage,\n ToolExecutionStatus,\n} from \"@assistant-ui/core\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { ToolInvocationTracker } from \"@assistant-ui/core/internal\";\nimport { applyOptimistic, useStatewire } from \"statewire\";\nimport type { StatewireClient } from \"statewire\";\nimport type { StatewireThread } from \"./StatewireThread\";\nimport { AssistantTransportHost } from \"./host\";\nimport type {\n AssistantTransportHostCommands,\n AssistantTransportHostState,\n HostQueueCell,\n HostRunContext,\n SendOptions,\n} from \"./host\";\nimport {\n createRunQueueAdapter,\n resolveEditCommand,\n resolveReloadCommand,\n toWireMessage,\n viewedLeafId,\n} from \"./runCommands\";\nimport { runsOptimistic } from \"./runsOptimistic\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\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: AssistantTransportThread.Command) => void;\n reconnect: () => void;\n state: unknown;\n /** The thread status; present iff StatewireThread. */\n status?: StatewireThread.ThreadStatus;\n /** The host's parked input requests; absent when the converter does not project them. */\n inputRequests?: readonly AssistantTransportThread.InputRequestState[];\n /** The typed runs read; present iff StatewireThread runs with the `runs` option. */\n runs?: StatewireThread.Runs;\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 foldOptimistic = (\n state: unknown,\n commands: readonly AssistantTransportThread.Command[],\n optimistic: AssistantTransportThread.Optimistic<unknown>,\n ctxOf: (command: object) => StatewireClient.OptimisticContext,\n): unknown => {\n let next = state;\n for (const command of commands) {\n try {\n next = applyOptimistic(next, (draft) =>\n optimistic(draft, command, ctxOf(command)),\n );\n } catch (error) {\n console.error(\n `statewire: optimistic reducer threw for \"${command.type}\"; dropping its optimistic update`,\n error,\n );\n }\n }\n return next;\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: AssistantTransportThread.Options<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: AssistantTransportThread.Command, 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 [ctxOf] = useState(() => {\n const ctxs = new WeakMap<object, StatewireClient.OptimisticContext>();\n let seq = 0;\n return (command: object): StatewireClient.OptimisticContext => {\n let ctx = ctxs.get(command);\n if (ctx === undefined) {\n ctx = { ts: Date.now(), seq: ++seq };\n ctxs.set(command, ctx);\n }\n return ctx;\n };\n });\n\n const { converter, optimistic, runs: runsOption, materialize } = options;\n const [runsSeam] = useState(() => runsOption !== undefined);\n if (runsSeam !== (runsOption !== undefined))\n throw new Error(\n \"statewire: the runs option must be stable — it was \" +\n (runsSeam ? \"set\" : \"unset\") +\n \" on first render and changed since\",\n );\n const [materializeSeam] = useState(() => materialize !== undefined);\n if (materializeSeam !== (materialize !== undefined))\n throw new Error(\n \"statewire: the materialize option must be stable — it was \" +\n (materializeSeam ? \"set\" : \"unset\") +\n \" on first render and changed since\",\n );\n\n const project = useCallback(\n (state: unknown): unknown => {\n const fold: AssistantTransportThread.Optimistic<unknown> | undefined =\n runsOption !== undefined\n ? (draft, command, ctx) => {\n runsOptimistic(\n runsOption === true ? draft : runsOption(draft as never),\n { method: command.type, params: [command] },\n ctx,\n );\n optimistic?.(draft, command, ctx);\n }\n : optimistic;\n let next = fold\n ? foldOptimistic(\n state,\n [...queue.inTransit, ...queue.queued],\n fold,\n ctxOf,\n )\n : state;\n if (materialize) {\n try {\n next = applyOptimistic(next, (draft) => materialize(draft as never));\n } catch (error) {\n console.error(\n \"statewire: materialize threw; publishing without its update\",\n error,\n );\n }\n }\n return next;\n },\n [runsOption, optimistic, materialize, queue, ctxOf],\n );\n const converted = useMemo(\n () => converter(project(agentState)),\n [converter, project, agentState],\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 handleEdit = (message: AppendMessage) => {\n const command = resolveEditCommand(convertedRef.current.messages, message);\n void toolInvocations.abort().then(() => dispatch(command));\n };\n\n const handleAppend = (message: AppendMessage) => {\n if (message.sourceId != null) return handleEdit(message);\n const startRun = message.startRun ?? message.role === \"user\";\n const command: AssistantTransportThread.Command = {\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 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 (command) => dispatch(command),\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 = converter(project(imported));\n toolInvocations.reset();\n setToolStatuses(EMPTY_TOOL_STATUSES);\n },\n }),\n );\n};\n\nexport const AssistantTransportThread = <T>(\n options: AssistantTransportThread.Options<T>,\n): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useAssistantTransportThread)(\n options as AssistantTransportThread.Options<any>,\n );\n\nexport namespace AssistantTransportThread {\n type UserCommands = Assistant.Commands[keyof Assistant.Commands];\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 RunUserMessage = {\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 RunPlacement = {\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: RunUserMessage;\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 RunPlacement;\n\n export type RunSteerCommand = {\n readonly type: \"run/steer\";\n } & (\n | {\n readonly message: RunUserMessage;\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 RunPlacement;\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: RunUserMessage;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly rollbackTo: string | null;\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 /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly rollbackTo: string | null;\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 = RunCommand | UserCommands;\n\n /** A queued message projected out of the host state, wire shape. */\n export type RunQueueItem = {\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 server-side queue: sends become `run/enqueue`\n * / `run/steer` commands and item controls send the `run/*` queue\n * commands. Presence must be stable across conversions and excludes the\n * client-local `capabilities.queue` buffer.\n */\n readonly queue?: readonly RunQueueItem[];\n /** The host's steer lane; requires `queue`. Absent means empty. */\n readonly steerQueue?: readonly RunQueueItem[];\n /**\n * The host's parked input requests projected out of the state. Returning it\n * (even empty) routes tool results and approvals with a matching pending\n * request through `run/input`. Presence must be stable across conversions.\n */\n readonly inputRequests?: readonly AssistantTransportThread.InputRequestState[];\n };\n\n export type StateConverter<T> = (state: T) => State;\n\n /** Folds an unsettled command into a draft of the client state; called once per pending command, in send order, re-run on every state change. A throwing fold logs and drops that command's update. */\n export type Optimistic<T> = (\n draft: T,\n command: Command,\n ctx: StatewireClient.OptimisticContext,\n ) => void;\n\n export type HeadersValue = Record<string, string> | Headers;\n\n export type Protocol = \"data-stream\" | \"assistant-transport\";\n\n export type SendCommandsRequestBody = {\n commands: Command[];\n state: unknown;\n system: string | undefined;\n tools: Record<string, unknown> | undefined;\n callSettings: LanguageModelV1CallSettings | undefined;\n config: LanguageModelConfig | undefined;\n threadId: string | null;\n parentId?: string | null;\n [key: string]: unknown;\n };\n\n export type Options<T> = {\n initialState: T;\n converter: StateConverter<T>;\n optimistic?: Optimistic<T> | undefined;\n /** Folds the lib's run-dialect optimistic reducer before `optimistic`: `true` reads the run mounts off the state root; a selector picks a nested mount. */\n runs?: true | ((state: T) => unknown) | undefined;\n /** Makes dispatch records concrete in the draft (runs after the optimistic folds); without it, dispatch limbo stays out of `messages`. */\n materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;\n api: string;\n resumeApi?: string | undefined;\n protocol?: Protocol | undefined;\n headers: HeadersValue | (() => Promise<HeadersValue>);\n body?: object | (() => Promise<object | undefined>) | undefined;\n /** Transform the fully assembled request body before it is sent. */\n prepareSendCommandsRequest?:\n | ((\n body: SendCommandsRequestBody,\n ) => Record<string, unknown> | Promise<Record<string, unknown>>)\n | undefined;\n onResponse?: ((response: Response) => void) | undefined;\n onFinish?: (() => void) | undefined;\n onError?:\n | ((\n error: Error,\n params: {\n commands: Command[];\n updateState: (updater: (state: T) => T) => void;\n },\n ) => void | Promise<void>)\n | undefined;\n /**\n * Called when commands are cancelled. After an error, queued commands are\n * cancelled once `onError` settles; `error` then carries the cause.\n */\n onCancel?:\n | ((params: {\n commands: Command[];\n updateState: (updater: (state: T) => T) => void;\n error?: Error;\n }) => void)\n | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n /**\n * Buffer messages sent during a run in an in-memory queue and dispatch\n * them once the run settles. Steering interrupts the active run.\n * Mutually exclusive with the converter's `queue` projection.\n */\n queue?: boolean | undefined;\n /** The host supports `run/continue` (a continue affordance on aborted runs). */\n continue?: boolean | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n }\n | undefined;\n };\n}\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useAssistantTransportThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;;;;;AAyDA,MAAM+C,sBAA2D,CAAC;AAClE,MAAME,oBAAgE,CAAA;AACtE,MAAMC,4BAA4B,CAAC;AAEnC,MAAaC,iCAAiCC,OAC5C,4BACF;AAeA,MAAac,8BACXC,WAC6B;CAC7B,IACE,OAAOA,WAAW,YAClBA,UAAU,QACV,EAAEhB,kCAAkCgB,SAEpC,MAAM,IAAIC,MACR,+FACF;CAEF,OAAOD;AACT;AAEA,MAAME,kBACJV,OACAW,UACAC,YACAE,UACY;CACZ,IAAIE,OAAOhB;CACX,KAAK,MAAMJ,WAAWe,UACpB,IAAI;EACFK,OAAO9C,gBAAgB8C,OAAOC,UAC5BL,WAAWK,OAAOrB,SAASkB,MAAMlB,OAAO,CAAC,CAC3C;CACF,SAASsB,OAAO;EACdC,QAAQD,MACN,4CAA4CtB,QAAQwB,KAAI,oCACxDF,KACF;CACF;CAEF,OAAOF;AACT;AAEA,MAAMK,2BACJC,UACAC,eAEAD,SAASE,MAAMC,YACbA,QAAQC,QAAQF,MACbG,SACCA,KAAKP,SAAS,gBACbO,KAAKJ,eAAeA,cAClBI,KAAKL,aAAaM,KAAAA,KACjBP,wBAAwBM,KAAKL,UAAUC,UAAU,EACzD,CACF;AAEF,MAAMM,+BACJC,YAC2B;CAC3B,MAAME,YAAY9E,sBAAsB;CACxC,MAAM,CAAC+E,iBAAiBxF,qBAAqC;EAC3D,MAAMyF,MAAMF,UAAUG,WAAWH,UAAUI;EAE3C,IAAIC,WAA0B;EAC9B,IAAI;GACFA,WAAWH,IAAII,eAAe,CAAC,CAACC,SAAS,C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CAAC;EAC3D;EACAiJ,gBAAgB;GAEdpB,cAAcD,MAAM;GACpBd,aAAa;EACf;EACAoC,gBAAgB;GACd,IAAIhH,QAAQqF,cAAc4B,UAAU;IAClC1F,SAAS,EAAEjC,MAAM,eAAe,CAAC;IACjC;GACF;GACA,IAAI,CAACU,QAAQkH,WACX,MAAM,IAAIvI,MAAM,+CAA+C;GACjE,SAAcwI,OAAO,CAAC,CAACzF,YAAY,CAAC,CAAC;EACvC;EACA,GAAIrD,kBAAkByB,KAAAA,KAAa;GACjCsH,kBAAkBC,gBAChB9F,SACElE,uBACE2F,aAAa3C,QAAQhC,eACrBgJ,WACF,CACF;GACFC,0BAA0BtH,cACxBuB,SACEnE,yBACE4F,aAAa3C,QAAQhC,eACrB2B,SACF,CACF;EACJ;EACAuH,mBAAmB,EAAE9H,YAAY+H,cAAqC;GACpE,IAAI,CAACvE,gBAAgBkE,OAAO1H,YAAY+H,OAAO,GAC7C,MAAM,IAAI7I,MAAM,aAAac,WAAU,4BAA6B;EACxE;EACAgI,sBAAsBC,aAAsB;GAC1C,SAAcC,YAAYD,QAAQ,CAAC,CAAChG,YAAY,CAAC,CAAC;GAElDsB,aAAa3C,UAAUiC,UAAUK,QAAQ+E,QAAQ,CAAC;GAClDzE,gBAAgBW,MAAM;GACtBhC,gBAAgBtE,mBAAmB;EACrC;CACF,CAAC,CACH;AACF;AAEA,MAAaS,4BACXiC,YAEAnF,SAASkF,2BAA2B,CAAC,CACnCC,OACF;AA+PF7E,uBACE4E,6BACA/E,eAAe8E,KAAAA,CAAkB,CAAC,CAAC+L,IACrC"}
@@ -139,7 +139,9 @@ declare namespace StatewireThread {
139
139
  readonly inputRequests?: readonly InputRequestState[];
140
140
  };
141
141
  /** Run subsystem status replicated by the host. */
142
- type RunStatus = "ready" | "running" | "stopped" | "error" | "input-required";
142
+ type RunStatus = "running" | "stopped" | "error" | "input-required";
143
+ /** The thread's status: `"loading"` while awaiting the attach snapshot, `"ready"` while resting, otherwise the run's status. */
144
+ type ThreadStatus = "loading" | "ready" | RunStatus;
143
145
  /** A queue-lane entry as replicated: the user message plus host-stamped `meta`. */
144
146
  type RunsQueueEntry = UserMessage & {
145
147
  /** Host-stamped opaque per-entry metadata. */
@@ -169,7 +171,7 @@ declare namespace StatewireThread {
169
171
  type RunState = {
170
172
  /** The run's identity — minted at dispatch, persists through input-required, null in error/stop. */
171
173
  readonly runId: string | null;
172
- readonly status: Exclude<RunStatus, "ready">;
174
+ readonly status: RunStatus;
173
175
  readonly queue: readonly RunsQueueEntry[];
174
176
  readonly steerQueue: readonly RunsQueueEntry[];
175
177
  /** The dispatch record — the unacked batch handed to the run, cleared at the ack. */
@@ -188,13 +190,13 @@ declare namespace StatewireThread {
188
190
  /** The runs mount as replicated: the run entries plus the top-level status projection. */
189
191
  type RunsState = {
190
192
  /** Projection of `runs[0]?.status ?? "ready"`. */
191
- readonly status: RunStatus;
193
+ readonly status: Exclude<ThreadStatus, "loading">;
192
194
  /** At most one entry; empty while resting. */
193
195
  readonly runs: readonly RunState[];
194
196
  };
195
- /** The run subsystem's typed read — `runs[0]` of the selected mount with unsettled commands folded in, ready defaults while resting. */
197
+ /** The run subsystem's typed read — `runs[0]` of the selected mount with unsettled commands folded in, ready defaults while resting, loading defaults while awaiting the attach snapshot. */
196
198
  type Runs = {
197
- readonly status: RunStatus;
199
+ readonly status: ThreadStatus;
198
200
  /** The live run's id — non-null in running and input-required; stamped onto `run/stop`. */
199
201
  readonly runId: string | null;
200
202
  readonly queue: readonly RunsQueueEntry[];
@@ -1 +1 @@
1
- {"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;;cA6Xa;GACV,GACC,SAAS,gBAAgB,YAAY,KACpC,gBAAgB;GAClB,GACC,SAAS,gBAAgB,QAAQ,KAChC,gBAAgB;;kBAIJ;OACH,UAAU,KAAK,gBAAgB,UAAU;OAEzC;aACD;aACA;;OAGC;aACD;aACA;aACA;aACA;;OAGC;aACD;aACA;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B;;IAErB,oBAEM,QAAQ,UAAU,cAChB,mBAAmB,2BAErB;MAAO,OAAO,YAAY;;;IAIhC,kBACM,OAAO,YAAY,IAAI;MAAO,SAAS,UAAU;;;IAGvD,uBACM,YAAY,gBAAgB;IAElC,YAAY,OAAO;IACnB;MAEM;;MAEA;;MAEA;;IAGN;MAEM,cAAc;MACd,SAAS;MACT,WAAW;;;;OAMP,YAAY,KAAK,KAAK,QAAQ;;IAExC,eAAe,OAAO;IACtB,WAAW,mBAAmB;;IAE9B,aACI,gBAAgB,WACd,GACA,mBAAmB;;IAIzB,cAAc,gBAAgB,YAAY,YAAY;;;;YAK9C;cACE;MACR,YAAY,gBAAgB;MAC5B,UAAU,gBAAgB;MAC1B,YAAY,gBAAgB;MAC5B,SAAS,gBAAgB;MACzB,aAAa,gBAAgB;MAC7B,WAAW,gBAAgB;MAC3B,UAAU,gBAAgB"}
@@ -21,6 +21,14 @@ const READY_RUNS = {
21
21
  dispatching: null,
22
22
  error: null
23
23
  };
24
+ const LOADING_RUNS = {
25
+ status: "loading",
26
+ runId: null,
27
+ queue: [],
28
+ steerQueue: [],
29
+ dispatching: null,
30
+ error: null
31
+ };
24
32
  const ambientContextOf = (context) => ({
25
33
  ...context.system !== void 0 && { system: context.system },
26
34
  ...context.tools !== void 0 && { tools: toToolsJSONSchema(context.tools) },
@@ -99,7 +107,7 @@ const useStatewireThread = (options) => {
99
107
  }, [dispatch]);
100
108
  const runs = useMemo(() => {
101
109
  if (runsOption === void 0) return void 0;
102
- if (state_0 === void 0) return READY_RUNS;
110
+ if (state_0 === void 0) return LOADING_RUNS;
103
111
  const entry = (runsOption === true ? state_0 : runsOption(state_0))?.runs?.[0];
104
112
  return entry === void 0 ? READY_RUNS : {
105
113
  status: entry.status,
@@ -145,17 +153,20 @@ const useStatewireThread = (options) => {
145
153
  const [inputSeam] = useState(() => ({ present: void 0 }));
146
154
  if (state_0 !== void 0 && inputSeam.present === void 0) inputSeam.present = inputRequests !== void 0;
147
155
  if (inputSeam.present !== void 0 && inputSeam.present !== (inputRequests !== void 0)) throw new Error("statewire: the converter's inputRequests projection must be stable — it was " + (inputSeam.present ? "defined" : "undefined") + " on first convert and changed since");
156
+ const status = runs !== void 0 ? runs.status : state_0 === void 0 ? "loading" : "ready";
148
157
  const extras = useMemo(() => ({
149
158
  [symbolAssistantTransportExtras]: true,
150
159
  sendCommand: dispatch,
151
160
  reconnect: connection_0.reconnect,
152
161
  state: state_0,
162
+ status,
153
163
  ...inputRequests !== void 0 && { inputRequests },
154
164
  ...runs !== void 0 && { runs }
155
165
  }), [
156
166
  dispatch,
157
167
  connection_0.reconnect,
158
168
  state_0,
169
+ status,
159
170
  inputRequests,
160
171
  runs
161
172
  ]);
@@ -175,7 +186,6 @@ const useStatewireThread = (options) => {
175
186
  const thread = useResource(ExternalThread({
176
187
  messages,
177
188
  isRunning: runs !== void 0 ? runs.status === "running" : converted.isRunning,
178
- isLoading: state_0 === void 0,
179
189
  state: converted.state,
180
190
  extras,
181
191
  attachmentAdapter: options.adapters?.attachments,
@@ -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","FeedbackAdapter","ModelContext","RespondToToolApprovalOptions","SpeechSynthesisAdapter","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","StatewireClient","symbolAssistantTransportExtras","AssistantTransportExtras","AssistantTransportThread","createRunQueueAdapter","resolveEditCommand","resolveReloadCommand","toWireMessage","viewedLeafId","resolveToolApprovalInput","resolveToolResultInput","runsOptimistic","AnyCommands","Record","args","AnyOptions","StatewireThread","Options","RunsOptions","LOADING_STATE","State","messages","isRunning","READY_RUNS","Runs","status","runId","queue","steerQueue","dispatching","error","ambientContextOf","context","system","undefined","tools","callSettings","config","useStatewireThread","options","latest","current","pending","setPending","Command","retire","command","prev","includes","filter","c","runsOption","runs","runsSeam","Error","materializeOption","materialize","materializeSeam","state","commands","connection","setContext","transport","initialState","optimistic","draft","ctx","runsOpt","onCommandChange","update","params","onStateChange","onConnectionChange","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","catch","onError","subscribe","dispatch","settled","type","threadRef","dispatchSend","message","sourceId","text","content","flatMap","part","join","setText","composer","next","mount","RunsState","entry","inputRequests","converter","metadata","ConnectionMetadata","pendingCommands","isSending","length","converted","queueItems","steerQueueItems","queueSeam","present","inputSeam","extras","sendCommand","reconnect","handleAppend","crypto","randomUUID","anchorMessageId","handleReload","parentId","handleEdit","thread","isLoading","attachmentAdapter","adapters","attachments","speechAdapter","speech","feedbackAdapter","feedback","onNew","capabilities","edit","onEdit","continue","onResume","reload","onReload","onAddToolResult","toolOptions","onRespondToToolApproval","approval","onCancel","payload","stopPayload","Array","isArray","T","Transport","TextPart","FilePart","mediaType","url","filename","UserMessage","id","role","parts","Placement","insertAfter","insertBefore","RunEnqueueCommand","messageId","RunSteerCommand","RunDequeueCommand","RunEditCommand","rollbackTo","RunContinueCommand","ToolCallInputRequest","toolCallId","ToolApprovalInputRequest","CustomInputRequest","InputRequest","ToolCallInputResponse","output","isError","artifact","ToolApprovalInputResponse","decision","editedArgs","InputResponse","RunInputCommand","requestId","response","InputRequestState","RunReloadCommand","RunCommand","QueueItem","RunStatus","RunsQueueEntry","meta","RunsInputOutcome","request","RunsDispatch","trigger","inputOutcomes","RunsError","RunState","Exclude","MaterializeEffects","append","rollback","to","ConnectionState","StateConverter","connectionMetadata","RunsConverterState","RunsStateConverter","StopPayload","reason","CommandUpdate","NonNullable","changes","Changes","Connection","Omit","Optimistic","Materialize","Assistant","Commands","runEnqueue","runSteer","runDequeue","runEdit","runContinue","runReload","runInput","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 FeedbackAdapter,\n ModelContext,\n RespondToToolApprovalOptions,\n SpeechSynthesisAdapter,\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 {\n AssistantTransportExtras,\n AssistantTransportThread,\n} from \"./AssistantTransportThread\";\nimport {\n createRunQueueAdapter,\n resolveEditCommand,\n resolveReloadCommand,\n toWireMessage,\n viewedLeafId,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\nimport { runsOptimistic } from \"./runsOptimistic\";\n\ntype AnyCommands = Record<string, (...args: any[]) => unknown>;\n\ntype AnyOptions =\n | StatewireThread.Options<any>\n | StatewireThread.RunsOptions<any>;\n\nconst LOADING_STATE: StatewireThread.State = { messages: [], isRunning: false };\n\nconst READY_RUNS: StatewireThread.Runs = {\n status: \"ready\",\n runId: null,\n queue: [],\n steerQueue: [],\n dispatching: null,\n error: null,\n};\n\nconst ambientContextOf = (context: ModelContext): Record<string, unknown> => ({\n ...(context.system !== undefined && { system: context.system }),\n ...(context.tools !== undefined && {\n tools: toToolsJSONSchema(context.tools),\n }),\n ...(context.callSettings !== undefined && {\n callSettings: context.callSettings,\n }),\n ...(context.config !== undefined && { config: context.config }),\n});\n\nconst useStatewireThread = (options: AnyOptions): 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 runsOption = options.runs;\n const [runsSeam] = useState(() => runsOption !== undefined);\n if (runsSeam !== (runsOption !== undefined))\n throw new Error(\n \"statewire: the runs option must be stable — it was \" +\n (runsSeam ? \"set\" : \"unset\") +\n \" on first render and changed since\",\n );\n\n const materializeOption = (options as StatewireThread.RunsOptions<unknown>)\n .materialize;\n const [materializeSeam] = useState(() => materializeOption !== undefined);\n if (materializeSeam !== (materializeOption !== undefined))\n throw new Error(\n \"statewire: the materialize option must be stable — it was \" +\n (materializeSeam ? \"set\" : \"unset\") +\n \" on first render and changed since\",\n );\n\n const { state, commands, connection, setContext } = useStatewire<\n unknown,\n AnyCommands\n >({\n transport: options.transport,\n initialState: options.initialState,\n ...(runsSeam && {\n optimistic: (draft, command, ctx) => {\n const runsOpt = latest.current.runs!;\n runsOptimistic(runsOpt === true ? draft : runsOpt(draft), command, ctx);\n (latest.current as StatewireThread.RunsOptions<unknown>).optimistic?.(\n draft,\n command,\n ctx,\n );\n },\n }),\n ...(materializeSeam && {\n materialize: (draft: {}) =>\n (latest.current as StatewireThread.RunsOptions<unknown>).materialize!(\n draft,\n ),\n }),\n onCommandChange: (update, ctx) => {\n if (update.status === \"acked\" || update.status === \"settled\")\n retire(update.params[0]);\n latest.current.onCommandChange?.(update, ctx);\n },\n onStateChange: (state, ctx) => latest.current.onStateChange?.(state, ctx),\n onConnectionChange: (connection) =>\n latest.current.onConnectionChange?.(connection),\n });\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 const settled = commands[command.type]!(command);\n settled.catch((error: Error) => {\n retire(command);\n latest.current.onError?.(error);\n });\n return settled;\n },\n [commands, retire],\n );\n\n const threadRef = useRef<ClientOutput<\"thread\"> | null>(null);\n const dispatchSend = useCallback(\n (command: StatewireThread.Command, message: AppendMessage) => {\n if (message.sourceId != null) return void dispatch(command);\n const text = message.content\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\");\n void dispatch(command).catch(() => {\n // Rejected send: put the text back unless the user typed since.\n // ExternalThread's setText is live-ref-backed and takes an updater.\n const setText = threadRef.current!.composer().setText as (\n next: string | ((prev: string) => string),\n ) => void;\n setText((prev) => (prev === \"\" ? text : prev));\n });\n },\n [dispatch],\n );\n\n const runs = useMemo((): StatewireThread.Runs | undefined => {\n if (runsOption === undefined) return undefined;\n if (state === undefined) return READY_RUNS;\n const mount = (runsOption === true ? state : runsOption(state)) as\n | StatewireThread.RunsState\n | undefined;\n const entry = mount?.runs?.[0];\n return entry === undefined\n ? READY_RUNS\n : {\n status: entry.status,\n runId: entry.runId,\n queue: entry.queue,\n steerQueue: entry.steerQueue,\n dispatching: entry.dispatching,\n ...(entry.inputRequests !== undefined && {\n inputRequests: entry.inputRequests,\n }),\n error: entry.error,\n };\n }, [runsOption, state]);\n\n const { converter } = options;\n const metadata = useMemo(\n (): StatewireThread.ConnectionMetadata => ({\n pendingCommands: [...pending],\n isSending: pending.length > 0,\n connection,\n ...(runs !== undefined && { runs }),\n }),\n [pending, connection, runs],\n );\n const converted = useMemo(\n (): StatewireThread.State =>\n state === undefined\n ? LOADING_STATE\n : (converter(\n state,\n metadata as StatewireThread.ConnectionMetadata & {\n runs: StatewireThread.Runs;\n },\n ) as StatewireThread.State),\n [converter, state, metadata],\n );\n // Dispatch limbo is a materialize concern: the fold makes the record\n // concrete in state before conversion.\n const messages = converted.messages;\n const queueItems = runs !== undefined ? runs.queue : converted.queue;\n const steerQueueItems =\n runs !== undefined ? runs.steerQueue : 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 // Seams anchor at the first real convert; the loading placeholder projects nothing.\n const [queueSeam] = useState(() => ({\n present: undefined as boolean | undefined,\n }));\n if (state !== undefined && queueSeam.present === undefined)\n queueSeam.present = queueItems !== undefined;\n if (\n queueSeam.present !== undefined &&\n queueSeam.present !== (queueItems !== undefined)\n )\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 messages,\n queueItems,\n steerQueueItems,\n dispatch,\n dispatchSend,\n )\n : undefined,\n [messages, queueItems, steerQueueItems, dispatch, dispatchSend],\n );\n\n const inputRequests =\n runs !== undefined ? (runs.inputRequests ?? []) : converted.inputRequests;\n const [inputSeam] = useState(() => ({\n present: undefined as boolean | undefined,\n }));\n if (state !== undefined && inputSeam.present === undefined)\n inputSeam.present = inputRequests !== undefined;\n if (\n inputSeam.present !== undefined &&\n inputSeam.present !== (inputRequests !== undefined)\n )\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 ...(runs !== undefined && { runs }),\n }),\n [dispatch, connection.reconnect, state, inputRequests, runs],\n );\n\n const handleAppend = (message: AppendMessage) => {\n dispatchSend(\n message.sourceId != null\n ? resolveEditCommand(messages, message)\n : {\n type: \"run/steer\",\n message: toWireMessage(message, crypto.randomUUID()),\n anchorMessageId: viewedLeafId(messages),\n },\n message,\n );\n };\n\n const handleReload = (parentId: string | null) => {\n dispatch(resolveReloadCommand(messages, parentId));\n };\n\n const handleEdit = (message: AppendMessage) => {\n dispatch(resolveEditCommand(messages, message));\n };\n\n const thread = useResource(\n ExternalThread({\n messages: messages as readonly ExternalThreadMessage[],\n isRunning:\n runs !== undefined ? runs.status === \"running\" : converted.isRunning,\n isLoading: state === undefined,\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n speechAdapter: options.adapters?.speech,\n feedbackAdapter: options.adapters?.feedback,\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 const runId = runs !== undefined ? runs.runId : converted.runId;\n const args =\n runId === undefined\n ? payload === undefined\n ? []\n : [payload]\n : [{ ...payload, runId }];\n void commands[\"run/stop\"]!(...args).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n },\n }),\n );\n threadRef.current = thread;\n return thread;\n};\n\nexport const StatewireThread: {\n <T>(\n options: StatewireThread.RunsOptions<T>,\n ): ResourceElement<ClientOutput<\"thread\">>;\n <T>(\n options: StatewireThread.Options<T>,\n ): ResourceElement<ClientOutput<\"thread\">>;\n} = (options: AnyOptions): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useStatewireThread)(options);\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 /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly rollbackTo: string | null;\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 /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly rollbackTo: string | null;\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 = AssistantTransportThread.Command | 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 /** The live run's id projected out of the host state; stamped onto `run/stop`. */\n readonly runId?: string | null;\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 /** Run subsystem status replicated by the host. */\n export type RunStatus =\n | \"ready\"\n | \"running\"\n | \"stopped\"\n | \"error\"\n | \"input-required\";\n\n /** A queue-lane entry as replicated: the user message plus host-stamped `meta`. */\n export type RunsQueueEntry = UserMessage & {\n /** Host-stamped opaque per-entry metadata. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n /** An input outcome riding a dispatch record: the request with its response (null = abandoned) and `run/input` meta. */\n export type RunsInputOutcome = {\n readonly request: InputRequest;\n readonly response: InputResponse | null;\n readonly meta: ReadonlyJSONValue | null;\n };\n\n /** The dispatch record — the unacked batch handed to the run; null between the ack and the next dispatch or take. */\n export type RunsDispatch = {\n readonly trigger:\n | \"message-send\"\n | \"message-edit\"\n | \"message-reload\"\n | \"input-resume\"\n | \"error-continue\"\n | \"stop-continue\"\n | \"steer\";\n readonly messages: readonly RunsQueueEntry[];\n /** Present on rewind dispatches: truncate the thread at this id first; null names the root. */\n readonly rollbackTo?: string | null;\n /** Present when input outcomes ride the dispatch; visible until the ack. */\n readonly inputOutcomes?: readonly RunsInputOutcome[];\n };\n\n /** The replicated run error — set on an unhandled failure, cleared by the next user-initiated run. */\n export type RunsError = {\n readonly message: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A replicated run entry — one element of the mount's `runs` array. */\n export type RunState = {\n /** The run's identity — minted at dispatch, persists through input-required, null in error/stop. */\n readonly runId: string | null;\n readonly status: Exclude<RunStatus, \"ready\">;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unacked batch handed to the run, cleared at the ack. */\n readonly dispatching: RunsDispatch | null;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n readonly error: RunsError | null;\n };\n\n /** App-shaped effects `runsMaterialize` applies for the dispatch record. */\n export type MaterializeEffects = {\n /** Append one dispatched message to the app's committed message state. */\n append: (message: RunsQueueEntry) => void;\n /** Truncate to the rolled-back view first (null names the root); required for hosts that dispatch edits/reloads. */\n rollback?: (to: string | null) => void;\n };\n\n /** The runs mount as replicated: the run entries plus the top-level status projection. */\n export type RunsState = {\n /** Projection of `runs[0]?.status ?? \"ready\"`. */\n readonly status: RunStatus;\n /** At most one entry; empty while resting. */\n readonly runs: readonly RunState[];\n };\n\n /** The run subsystem's typed read — `runs[0]` of the selected mount with unsettled commands folded in, ready defaults while resting. */\n export type Runs = {\n readonly status: RunStatus;\n /** The live run's id — non-null in running and input-required; stamped onto `run/stop`. */\n readonly runId: string | null;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unacked batch handed to the run, cleared at the ack. */\n readonly dispatching: RunsDispatch | null;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n readonly error: RunsError | null;\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 /** The typed runs read; present iff the `runs` option is set. */\n runs?: Runs;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n /** Converter output in runs mode: app-owned keys only — the lib projects the run mounts itself. */\n export type RunsConverterState = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n };\n\n export type RunsStateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata & { runs: Runs },\n ) => RunsConverterState;\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 /** Preloads the thread: published and interactive from the first render, replaced by the attach snapshot. Omitted, the thread stays loading until attach. */\n initialState?: T | undefined;\n converter: StateConverter<T>;\n runs?: undefined;\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 /** Observes each command's lifecycle (queued, posted, acked, settled); runs after the built-in pending-command retirement. */\n onCommandChange?:\n | ((\n update: Statewire.CommandUpdate<\n Record<string, (...args: any[]) => unknown>\n >,\n ctx: { state: NonNullable<T> },\n ) => void)\n | undefined;\n /** Observes the transport state: fires with the attach snapshot, then once per change. */\n onStateChange?:\n | ((state: NonNullable<T>, ctx: { changes: Statewire.Changes }) => void)\n | undefined;\n /** Observes connection status transitions, starting with the initial status. */\n onConnectionChange?:\n | ((connection: StatewireClient.Connection) => 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 speech?: SpeechSynthesisAdapter | undefined;\n feedback?: FeedbackAdapter | undefined;\n }\n | undefined;\n };\n\n /** Options with the runs read enabled: the lib types the run mounts and the converter returns app-owned keys only. */\n export type RunsOptions<T> = Omit<Options<T>, \"converter\" | \"runs\"> & {\n /** `true` reads the run mounts off the state root; a selector picks a nested mount. */\n runs: true | ((state: T) => unknown);\n converter: RunsStateConverter<T>;\n /** Folds app-owned keys for an unsettled command into the draft; runs after the lib's run-dialect reducer. */\n optimistic?:\n | StatewireClient.Optimistic<\n T,\n Record<string, (...args: any[]) => unknown>\n >\n | undefined;\n /** Makes dispatch records concrete in the draft (runs after the optimistic folds); without it, dispatch limbo stays out of `messages`. */\n materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;\n };\n}\n\ndeclare module \"@assistant-ui/react\" {\n namespace Assistant {\n interface Commands {\n runEnqueue: StatewireThread.RunEnqueueCommand;\n runSteer: StatewireThread.RunSteerCommand;\n runDequeue: StatewireThread.RunDequeueCommand;\n runEdit: StatewireThread.RunEditCommand;\n runContinue: StatewireThread.RunContinueCommand;\n runReload: StatewireThread.RunReloadCommand;\n runInput: StatewireThread.RunInputCommand;\n }\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":";;;;;;;;;;;AAiDA,MAAM6C,gBAAuC;CAAEE,UAAU,CAAA;CAAIC,WAAW;AAAM;AAE9E,MAAMC,aAAmC;CACvCE,QAAQ;CACRC,OAAO;CACPC,OAAO,CAAA;CACPC,YAAY,CAAA;CACZC,aAAa;CACbC,OAAO;AACT;AAEA,MAAMC,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWC,KAAAA,KAAa,EAAED,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQG,UAAUD,KAAAA,KAAa,EACjCC,OAAOvC,kBAAkBoC,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,sBAAsBC,YAAgD;CAC1E,MAAMC,SAAS/D,OAAO8D,OAAO;CAC7BC,OAAOC,UAAUF;CAEjB,MAAM,CAACG,SAASC,cAAcjE,SAC5B,CAAA,CACF;CACA,MAAM,CAACmE,UAAUnE,gBACRoE,YACLH,Y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AA,MACX,OAAOsH,YAAY,YAClBA,YAAY,QACZE,MAAMC,QAAQH,OAAO,IAEvB,MAAM,IAAIlG,MAAM,mDAAmD;GACrE,MAAM5B,QAAQ0B,SAASlB,KAAAA,IAAYkB,KAAK1B,QAAQwF,UAAUxF;GAC1D,MAAMZ,OACJY,UAAUQ,KAAAA,IACNsH,YAAYtH,KAAAA,IACV,CAAA,IACA,CAACsH,OAAO,IACV,CAAC;IAAE,GAAGA;IAAS9H;GAAM,CAAC;GAC5B,SAAc,WAAW,CAAE,GAAGZ,IAAI,CAAC,CAACwE,OAAOxD,YAAiB;IAC1DU,OAAOC,QAAQ8C,UAAUzD,OAAK;GAChC,CAAC;EACH;CACF,CAAC,CACH;CACA8D,UAAUnD,UAAUyF;CACpB,OAAOA;AACT;AAEA,MAAalH,mBAORuB,YACH5D,SAAS2D,kBAAkB,CAAC,CAACC,OAAO;AAqXtCvD,uBACEsD,oBACAxD,eAAeoD,KAAAA,CAAkB,CAAC,CAAC0M,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","FeedbackAdapter","ModelContext","RespondToToolApprovalOptions","SpeechSynthesisAdapter","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","StatewireClient","symbolAssistantTransportExtras","AssistantTransportExtras","AssistantTransportThread","createRunQueueAdapter","resolveEditCommand","resolveReloadCommand","toWireMessage","viewedLeafId","resolveToolApprovalInput","resolveToolResultInput","runsOptimistic","AnyCommands","Record","args","AnyOptions","StatewireThread","Options","RunsOptions","LOADING_STATE","State","messages","isRunning","READY_RUNS","Runs","status","runId","queue","steerQueue","dispatching","error","LOADING_RUNS","ambientContextOf","context","system","undefined","tools","callSettings","config","useStatewireThread","options","latest","current","pending","setPending","Command","retire","command","prev","includes","filter","c","runsOption","runs","runsSeam","Error","materializeOption","materialize","materializeSeam","state","commands","connection","setContext","transport","initialState","optimistic","draft","ctx","runsOpt","onCommandChange","update","params","onStateChange","onConnectionChange","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","catch","onError","subscribe","dispatch","settled","type","threadRef","dispatchSend","message","sourceId","text","content","flatMap","part","join","setText","composer","next","mount","RunsState","entry","inputRequests","converter","metadata","ConnectionMetadata","pendingCommands","isSending","length","converted","queueItems","steerQueueItems","queueSeam","present","inputSeam","ThreadStatus","extras","sendCommand","reconnect","handleAppend","crypto","randomUUID","anchorMessageId","handleReload","parentId","handleEdit","thread","attachmentAdapter","adapters","attachments","speechAdapter","speech","feedbackAdapter","feedback","onNew","capabilities","edit","onEdit","continue","onResume","reload","onReload","onAddToolResult","toolOptions","onRespondToToolApproval","approval","onCancel","payload","stopPayload","Array","isArray","T","Transport","TextPart","FilePart","mediaType","url","filename","UserMessage","id","role","parts","Placement","insertAfter","insertBefore","RunEnqueueCommand","messageId","RunSteerCommand","RunDequeueCommand","RunEditCommand","rollbackTo","RunContinueCommand","ToolCallInputRequest","toolCallId","ToolApprovalInputRequest","CustomInputRequest","InputRequest","ToolCallInputResponse","output","isError","artifact","ToolApprovalInputResponse","decision","editedArgs","InputResponse","RunInputCommand","requestId","response","InputRequestState","RunReloadCommand","RunCommand","QueueItem","RunStatus","RunsQueueEntry","meta","RunsInputOutcome","request","RunsDispatch","trigger","inputOutcomes","RunsError","RunState","MaterializeEffects","append","rollback","to","Exclude","ConnectionState","StateConverter","connectionMetadata","RunsConverterState","RunsStateConverter","StopPayload","reason","CommandUpdate","NonNullable","changes","Changes","Connection","Omit","Optimistic","Materialize","Assistant","Commands","runEnqueue","runSteer","runDequeue","runEdit","runContinue","runReload","runInput","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 FeedbackAdapter,\n ModelContext,\n RespondToToolApprovalOptions,\n SpeechSynthesisAdapter,\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 {\n AssistantTransportExtras,\n AssistantTransportThread,\n} from \"./AssistantTransportThread\";\nimport {\n createRunQueueAdapter,\n resolveEditCommand,\n resolveReloadCommand,\n toWireMessage,\n viewedLeafId,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\nimport { runsOptimistic } from \"./runsOptimistic\";\n\ntype AnyCommands = Record<string, (...args: any[]) => unknown>;\n\ntype AnyOptions =\n | StatewireThread.Options<any>\n | StatewireThread.RunsOptions<any>;\n\nconst LOADING_STATE: StatewireThread.State = { messages: [], isRunning: false };\n\nconst READY_RUNS: StatewireThread.Runs = {\n status: \"ready\",\n runId: null,\n queue: [],\n steerQueue: [],\n dispatching: null,\n error: null,\n};\n\nconst LOADING_RUNS: StatewireThread.Runs = {\n status: \"loading\",\n runId: null,\n queue: [],\n steerQueue: [],\n dispatching: null,\n error: null,\n};\n\nconst ambientContextOf = (context: ModelContext): Record<string, unknown> => ({\n ...(context.system !== undefined && { system: context.system }),\n ...(context.tools !== undefined && {\n tools: toToolsJSONSchema(context.tools),\n }),\n ...(context.callSettings !== undefined && {\n callSettings: context.callSettings,\n }),\n ...(context.config !== undefined && { config: context.config }),\n});\n\nconst useStatewireThread = (options: AnyOptions): 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 runsOption = options.runs;\n const [runsSeam] = useState(() => runsOption !== undefined);\n if (runsSeam !== (runsOption !== undefined))\n throw new Error(\n \"statewire: the runs option must be stable — it was \" +\n (runsSeam ? \"set\" : \"unset\") +\n \" on first render and changed since\",\n );\n\n const materializeOption = (options as StatewireThread.RunsOptions<unknown>)\n .materialize;\n const [materializeSeam] = useState(() => materializeOption !== undefined);\n if (materializeSeam !== (materializeOption !== undefined))\n throw new Error(\n \"statewire: the materialize option must be stable — it was \" +\n (materializeSeam ? \"set\" : \"unset\") +\n \" on first render and changed since\",\n );\n\n const { state, commands, connection, setContext } = useStatewire<\n unknown,\n AnyCommands\n >({\n transport: options.transport,\n initialState: options.initialState,\n ...(runsSeam && {\n optimistic: (draft, command, ctx) => {\n const runsOpt = latest.current.runs!;\n runsOptimistic(runsOpt === true ? draft : runsOpt(draft), command, ctx);\n (latest.current as StatewireThread.RunsOptions<unknown>).optimistic?.(\n draft,\n command,\n ctx,\n );\n },\n }),\n ...(materializeSeam && {\n materialize: (draft: {}) =>\n (latest.current as StatewireThread.RunsOptions<unknown>).materialize!(\n draft,\n ),\n }),\n onCommandChange: (update, ctx) => {\n if (update.status === \"acked\" || update.status === \"settled\")\n retire(update.params[0]);\n latest.current.onCommandChange?.(update, ctx);\n },\n onStateChange: (state, ctx) => latest.current.onStateChange?.(state, ctx),\n onConnectionChange: (connection) =>\n latest.current.onConnectionChange?.(connection),\n });\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 const settled = commands[command.type]!(command);\n settled.catch((error: Error) => {\n retire(command);\n latest.current.onError?.(error);\n });\n return settled;\n },\n [commands, retire],\n );\n\n const threadRef = useRef<ClientOutput<\"thread\"> | null>(null);\n const dispatchSend = useCallback(\n (command: StatewireThread.Command, message: AppendMessage) => {\n if (message.sourceId != null) return void dispatch(command);\n const text = message.content\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\");\n void dispatch(command).catch(() => {\n // Rejected send: put the text back unless the user typed since.\n // ExternalThread's setText is live-ref-backed and takes an updater.\n const setText = threadRef.current!.composer().setText as (\n next: string | ((prev: string) => string),\n ) => void;\n setText((prev) => (prev === \"\" ? text : prev));\n });\n },\n [dispatch],\n );\n\n const runs = useMemo((): StatewireThread.Runs | undefined => {\n if (runsOption === undefined) return undefined;\n if (state === undefined) return LOADING_RUNS;\n const mount = (runsOption === true ? state : runsOption(state)) as\n | StatewireThread.RunsState\n | undefined;\n const entry = mount?.runs?.[0];\n return entry === undefined\n ? READY_RUNS\n : {\n status: entry.status,\n runId: entry.runId,\n queue: entry.queue,\n steerQueue: entry.steerQueue,\n dispatching: entry.dispatching,\n ...(entry.inputRequests !== undefined && {\n inputRequests: entry.inputRequests,\n }),\n error: entry.error,\n };\n }, [runsOption, state]);\n\n const { converter } = options;\n const metadata = useMemo(\n (): StatewireThread.ConnectionMetadata => ({\n pendingCommands: [...pending],\n isSending: pending.length > 0,\n connection,\n ...(runs !== undefined && { runs }),\n }),\n [pending, connection, runs],\n );\n const converted = useMemo(\n (): StatewireThread.State =>\n state === undefined\n ? LOADING_STATE\n : (converter(\n state,\n metadata as StatewireThread.ConnectionMetadata & {\n runs: StatewireThread.Runs;\n },\n ) as StatewireThread.State),\n [converter, state, metadata],\n );\n // Dispatch limbo is a materialize concern: the fold makes the record\n // concrete in state before conversion.\n const messages = converted.messages;\n const queueItems = runs !== undefined ? runs.queue : converted.queue;\n const steerQueueItems =\n runs !== undefined ? runs.steerQueue : 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 // Seams anchor at the first real convert; the loading placeholder projects nothing.\n const [queueSeam] = useState(() => ({\n present: undefined as boolean | undefined,\n }));\n if (state !== undefined && queueSeam.present === undefined)\n queueSeam.present = queueItems !== undefined;\n if (\n queueSeam.present !== undefined &&\n queueSeam.present !== (queueItems !== undefined)\n )\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 messages,\n queueItems,\n steerQueueItems,\n dispatch,\n dispatchSend,\n )\n : undefined,\n [messages, queueItems, steerQueueItems, dispatch, dispatchSend],\n );\n\n const inputRequests =\n runs !== undefined ? (runs.inputRequests ?? []) : converted.inputRequests;\n const [inputSeam] = useState(() => ({\n present: undefined as boolean | undefined,\n }));\n if (state !== undefined && inputSeam.present === undefined)\n inputSeam.present = inputRequests !== undefined;\n if (\n inputSeam.present !== undefined &&\n inputSeam.present !== (inputRequests !== undefined)\n )\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 status: StatewireThread.ThreadStatus =\n runs !== undefined\n ? runs.status\n : state === undefined\n ? \"loading\"\n : \"ready\";\n\n const extras = useMemo(\n (): AssistantTransportExtras => ({\n [symbolAssistantTransportExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state,\n status,\n ...(inputRequests !== undefined && { inputRequests }),\n ...(runs !== undefined && { runs }),\n }),\n [dispatch, connection.reconnect, state, status, inputRequests, runs],\n );\n\n const handleAppend = (message: AppendMessage) => {\n dispatchSend(\n message.sourceId != null\n ? resolveEditCommand(messages, message)\n : {\n type: \"run/steer\",\n message: toWireMessage(message, crypto.randomUUID()),\n anchorMessageId: viewedLeafId(messages),\n },\n message,\n );\n };\n\n const handleReload = (parentId: string | null) => {\n dispatch(resolveReloadCommand(messages, parentId));\n };\n\n const handleEdit = (message: AppendMessage) => {\n dispatch(resolveEditCommand(messages, message));\n };\n\n const thread = useResource(\n ExternalThread({\n messages: messages as readonly ExternalThreadMessage[],\n isRunning:\n runs !== undefined ? runs.status === \"running\" : converted.isRunning,\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n speechAdapter: options.adapters?.speech,\n feedbackAdapter: options.adapters?.feedback,\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 const runId = runs !== undefined ? runs.runId : converted.runId;\n const args =\n runId === undefined\n ? payload === undefined\n ? []\n : [payload]\n : [{ ...payload, runId }];\n void commands[\"run/stop\"]!(...args).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n },\n }),\n );\n threadRef.current = thread;\n return thread;\n};\n\nexport const StatewireThread: {\n <T>(\n options: StatewireThread.RunsOptions<T>,\n ): ResourceElement<ClientOutput<\"thread\">>;\n <T>(\n options: StatewireThread.Options<T>,\n ): ResourceElement<ClientOutput<\"thread\">>;\n} = (options: AnyOptions): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useStatewireThread)(options);\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 /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly rollbackTo: string | null;\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 /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly rollbackTo: string | null;\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 = AssistantTransportThread.Command | 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 /** The live run's id projected out of the host state; stamped onto `run/stop`. */\n readonly runId?: string | null;\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 /** Run subsystem status replicated by the host. */\n export type RunStatus = \"running\" | \"stopped\" | \"error\" | \"input-required\";\n\n /** The thread's status: `\"loading\"` while awaiting the attach snapshot, `\"ready\"` while resting, otherwise the run's status. */\n export type ThreadStatus = \"loading\" | \"ready\" | RunStatus;\n\n /** A queue-lane entry as replicated: the user message plus host-stamped `meta`. */\n export type RunsQueueEntry = UserMessage & {\n /** Host-stamped opaque per-entry metadata. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n /** An input outcome riding a dispatch record: the request with its response (null = abandoned) and `run/input` meta. */\n export type RunsInputOutcome = {\n readonly request: InputRequest;\n readonly response: InputResponse | null;\n readonly meta: ReadonlyJSONValue | null;\n };\n\n /** The dispatch record — the unacked batch handed to the run; null between the ack and the next dispatch or take. */\n export type RunsDispatch = {\n readonly trigger:\n | \"message-send\"\n | \"message-edit\"\n | \"message-reload\"\n | \"input-resume\"\n | \"error-continue\"\n | \"stop-continue\"\n | \"steer\";\n readonly messages: readonly RunsQueueEntry[];\n /** Present on rewind dispatches: truncate the thread at this id first; null names the root. */\n readonly rollbackTo?: string | null;\n /** Present when input outcomes ride the dispatch; visible until the ack. */\n readonly inputOutcomes?: readonly RunsInputOutcome[];\n };\n\n /** The replicated run error — set on an unhandled failure, cleared by the next user-initiated run. */\n export type RunsError = {\n readonly message: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A replicated run entry — one element of the mount's `runs` array. */\n export type RunState = {\n /** The run's identity — minted at dispatch, persists through input-required, null in error/stop. */\n readonly runId: string | null;\n readonly status: RunStatus;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unacked batch handed to the run, cleared at the ack. */\n readonly dispatching: RunsDispatch | null;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n readonly error: RunsError | null;\n };\n\n /** App-shaped effects `runsMaterialize` applies for the dispatch record. */\n export type MaterializeEffects = {\n /** Append one dispatched message to the app's committed message state. */\n append: (message: RunsQueueEntry) => void;\n /** Truncate to the rolled-back view first (null names the root); required for hosts that dispatch edits/reloads. */\n rollback?: (to: string | null) => void;\n };\n\n /** The runs mount as replicated: the run entries plus the top-level status projection. */\n export type RunsState = {\n /** Projection of `runs[0]?.status ?? \"ready\"`. */\n readonly status: Exclude<ThreadStatus, \"loading\">;\n /** At most one entry; empty while resting. */\n readonly runs: readonly RunState[];\n };\n\n /** The run subsystem's typed read — `runs[0]` of the selected mount with unsettled commands folded in, ready defaults while resting, loading defaults while awaiting the attach snapshot. */\n export type Runs = {\n readonly status: ThreadStatus;\n /** The live run's id — non-null in running and input-required; stamped onto `run/stop`. */\n readonly runId: string | null;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unacked batch handed to the run, cleared at the ack. */\n readonly dispatching: RunsDispatch | null;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n readonly error: RunsError | null;\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 /** The typed runs read; present iff the `runs` option is set. */\n runs?: Runs;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n /** Converter output in runs mode: app-owned keys only — the lib projects the run mounts itself. */\n export type RunsConverterState = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n };\n\n export type RunsStateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata & { runs: Runs },\n ) => RunsConverterState;\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 /** Preloads the thread: published and interactive from the first render, replaced by the attach snapshot. Omitted, the thread stays loading until attach. */\n initialState?: T | undefined;\n converter: StateConverter<T>;\n runs?: undefined;\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 /** Observes each command's lifecycle (queued, posted, acked, settled); runs after the built-in pending-command retirement. */\n onCommandChange?:\n | ((\n update: Statewire.CommandUpdate<\n Record<string, (...args: any[]) => unknown>\n >,\n ctx: { state: NonNullable<T> },\n ) => void)\n | undefined;\n /** Observes the transport state: fires with the attach snapshot, then once per change. */\n onStateChange?:\n | ((state: NonNullable<T>, ctx: { changes: Statewire.Changes }) => void)\n | undefined;\n /** Observes connection status transitions, starting with the initial status. */\n onConnectionChange?:\n | ((connection: StatewireClient.Connection) => 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 speech?: SpeechSynthesisAdapter | undefined;\n feedback?: FeedbackAdapter | undefined;\n }\n | undefined;\n };\n\n /** Options with the runs read enabled: the lib types the run mounts and the converter returns app-owned keys only. */\n export type RunsOptions<T> = Omit<Options<T>, \"converter\" | \"runs\"> & {\n /** `true` reads the run mounts off the state root; a selector picks a nested mount. */\n runs: true | ((state: T) => unknown);\n converter: RunsStateConverter<T>;\n /** Folds app-owned keys for an unsettled command into the draft; runs after the lib's run-dialect reducer. */\n optimistic?:\n | StatewireClient.Optimistic<\n T,\n Record<string, (...args: any[]) => unknown>\n >\n | undefined;\n /** Makes dispatch records concrete in the draft (runs after the optimistic folds); without it, dispatch limbo stays out of `messages`. */\n materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;\n };\n}\n\ndeclare module \"@assistant-ui/react\" {\n namespace Assistant {\n interface Commands {\n runEnqueue: StatewireThread.RunEnqueueCommand;\n runSteer: StatewireThread.RunSteerCommand;\n runDequeue: StatewireThread.RunDequeueCommand;\n runEdit: StatewireThread.RunEditCommand;\n runContinue: StatewireThread.RunContinueCommand;\n runReload: StatewireThread.RunReloadCommand;\n runInput: StatewireThread.RunInputCommand;\n }\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":";;;;;;;;;;;AAiDA,MAAM6C,gBAAuC;CAAEE,UAAU,CAAA;CAAIC,WAAW;AAAM;AAE9E,MAAMC,aAAmC;CACvCE,QAAQ;CACRC,OAAO;CACPC,OAAO,CAAA;CACPC,YAAY,CAAA;CACZC,aAAa;CACbC,OAAO;AACT;AAEA,MAAMC,eAAqC;CACzCN,QAAQ;CACRC,OAAO;CACPC,OAAO,CAAA;CACPC,YAAY,CAAA;CACZC,aAAa;CACbC,OAAO;AACT;AAEA,MAAME,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWC,KAAAA,KAAa,EAAED,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQG,UAAUD,KAAAA,KAAa,EACjC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cC,QAAQ,EAAEC,QAAQZ,WAAW;EACvD,GAAI3F,QAAQqG,cAAcG,YAAY,EACpCC,gBAAgBvD,SAAS,EAAEE,MAAM,eAAe,CAAC,EACnD;EACA,GAAIpD,QAAQqG,cAAcK,UAAU,EAAEC,UAAUlB,aAAa;EAC7D,GAAIrB,kBAAkBzE,KAAAA,KAAa;GACjCiH,kBAAkBC,gBAChB3D,SAAShF,uBAAuBkG,eAAeyC,WAAW,CAAC;GAC7DC,0BAA0BC,aACxB7D,SAASjF,yBAAyBmG,eAAe2C,QAAQ,CAAC;EAC9D;EACAC,gBAAgB;GACd,MAAMC,UAAUhH,OAAOC,QAAQgH,cAAc;GAC7C,IACED,YAAYtH,KAAAA,MACX,OAAOsH,YAAY,YAClBA,YAAY,QACZE,MAAMC,QAAQH,OAAO,IAEvB,MAAM,IAAIlG,MAAM,mDAAmD;GACrE,MAAM7B,QAAQ2B,SAASlB,KAAAA,IAAYkB,KAAK3B,QAAQyF,UAAUzF;GAC1D,MAAMZ,OACJY,UAAUS,KAAAA,IACNsH,YAAYtH,KAAAA,IACV,CAAA,IACA,CAACsH,OAAO,IACV,CAAC;IAAE,GAAGA;IAAS/H;GAAM,CAAC;GAC5B,SAAc,WAAW,CAAE,GAAGZ,IAAI,CAAC,CAACyE,OAAOzD,YAAiB;IAC1DW,OAAOC,QAAQ8C,UAAU1D,OAAK;GAChC,CAAC;EACH;CACF,CAAC,CACH;CACA+D,UAAUnD,UAAU0F;CACpB,OAAOA;AACT;AAEA,MAAapH,mBAORwB,YACH7D,SAAS4D,kBAAkB,CAAC,CAACC,OAAO;AAmXtCxD,uBACEuD,oBACAzD,eAAeqD,KAAAA,CAAkB,CAAC,CAAC0M,IACrC"}
package/dist/hooks.d.ts CHANGED
@@ -4,10 +4,12 @@ import { Assistant } from "@assistant-ui/react";
4
4
  //#region src/hooks.d.ts
5
5
  type UserExternalState = keyof Assistant.ExternalState extends never ? Record<string, unknown> : Assistant.ExternalState[keyof Assistant.ExternalState];
6
6
  declare const useAssistantTransportSendCommand: () => (command: AssistantTransportThread.Command) => void;
7
+ /** The thread status; requires StatewireThread. */
8
+ declare const useStatewireThreadStatus: () => StatewireThread.ThreadStatus;
7
9
  /** The typed runs read; requires StatewireThread with the `runs` option. */
8
10
  declare const useStatewireRuns: () => StatewireThread.Runs;
9
11
  declare function useAssistantTransportState(): UserExternalState;
10
12
  declare function useAssistantTransportState<T>(selector: (state: UserExternalState) => T): T;
11
13
  //#endregion
12
- export { useAssistantTransportSendCommand, useAssistantTransportState, useStatewireRuns };
14
+ export { useAssistantTransportSendCommand, useAssistantTransportState, useStatewireRuns, useStatewireThreadStatus };
13
15
  //# sourceMappingURL=hooks.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"hooks.d.ts","names":[],"sources":["../src/hooks.ts"],"mappings":";;;;KAQK,0BAA0B,UAAU,8BACrC,0BACA,UAAU,oBAAoB,UAAU;cAE/B,yCAGH,SAAS,yBAAyB;;cAO/B,wBAAuB,gBAAgB;iBAUpC,8BAA8B;iBAC9B,2BAA2B,GACzC,WAAW,OAAO,sBAAsB,IACvC"}
1
+ {"version":3,"file":"hooks.d.ts","names":[],"sources":["../src/hooks.ts"],"mappings":";;;;KAQK,0BAA0B,UAAU,8BACrC,0BACA,UAAU,oBAAoB,UAAU;cAE/B,yCAGH,SAAS,yBAAyB;;cAO/B,gCAA+B,gBAAgB;;cAW/C,wBAAuB,gBAAgB;iBAUpC,8BAA8B;iBAC9B,2BAA2B,GACzC,WAAW,OAAO,sBAAsB,IACvC"}
package/dist/hooks.js CHANGED
@@ -17,19 +17,28 @@ const useAssistantTransportSendCommand = () => {
17
17
  } else t0 = $[1];
18
18
  return t0;
19
19
  };
20
+ /** The thread status; requires StatewireThread. */
21
+ const useStatewireThreadStatus = () => {
22
+ return useAuiState(_temp);
23
+ };
20
24
  /** The typed runs read; requires StatewireThread with the `runs` option. */
21
25
  const useStatewireRuns = () => {
22
- return useAuiState(_temp);
26
+ return useAuiState(_temp2);
23
27
  };
24
28
  function useAssistantTransportState(selector = (t) => t) {
25
29
  return useAuiState((s) => selector(asAssistantTransportExtras(s.thread.extras).state));
26
30
  }
27
31
  function _temp(s) {
32
+ const { status } = asAssistantTransportExtras(s.thread.extras);
33
+ if (status === void 0) throw new Error("statewire: useStatewireThreadStatus requires StatewireThread");
34
+ return status;
35
+ }
36
+ function _temp2(s) {
28
37
  const { runs } = asAssistantTransportExtras(s.thread.extras);
29
38
  if (runs === void 0) throw new Error("statewire: useStatewireRuns requires StatewireThread with the runs option enabled");
30
39
  return runs;
31
40
  }
32
41
  //#endregion
33
- export { useAssistantTransportSendCommand, useAssistantTransportState, useStatewireRuns };
42
+ export { useAssistantTransportSendCommand, useAssistantTransportState, useStatewireRuns, useStatewireThreadStatus };
34
43
 
35
44
  //# sourceMappingURL=hooks.js.map
package/dist/hooks.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"hooks.js","names":["c","_c","useAui","useAuiState","asAssistantTransportExtras","Assistant","AssistantTransportThread","StatewireThread","UserExternalState","ExternalState","Record","useAssistantTransportSendCommand","$","aui","t0","command","extras","thread","getState","sendCommand","useStatewireRuns","_temp","useAssistantTransportState","selector","state","T","t","s","runs","undefined","Error"],"sources":["../src/hooks.ts"],"sourcesContent":["\"use client\";\n\nimport { useAui, useAuiState } from \"@assistant-ui/store\";\nimport { asAssistantTransportExtras } from \"./AssistantTransportThread\";\nimport type { Assistant } from \"@assistant-ui/react\";\nimport type { AssistantTransportThread } from \"./AssistantTransportThread\";\nimport type { StatewireThread } from \"./StatewireThread\";\n\ntype UserExternalState = keyof Assistant.ExternalState extends never\n ? Record<string, unknown>\n : Assistant.ExternalState[keyof Assistant.ExternalState];\n\nexport const useAssistantTransportSendCommand = () => {\n const aui = useAui();\n\n return (command: AssistantTransportThread.Command) => {\n const extras = aui.thread().getState().extras;\n asAssistantTransportExtras(extras).sendCommand(command);\n };\n};\n\n/** The typed runs read; requires StatewireThread with the `runs` option. */\nexport const useStatewireRuns = (): StatewireThread.Runs =>\n useAuiState((s) => {\n const { runs } = asAssistantTransportExtras(s.thread.extras);\n if (runs === undefined)\n throw new Error(\n \"statewire: useStatewireRuns requires StatewireThread with the runs option enabled\",\n );\n return runs;\n });\n\nexport function useAssistantTransportState(): UserExternalState;\nexport function useAssistantTransportState<T>(\n selector: (state: UserExternalState) => T,\n): T;\nexport function useAssistantTransportState<T>(\n selector: (state: UserExternalState) => T = (t) => t as T,\n): T | UserExternalState {\n return useAuiState((s) =>\n selector(\n asAssistantTransportExtras(s.thread.extras).state as UserExternalState,\n ),\n );\n}\n"],"mappings":";;;;;AAYA,MAAaW,yCAAmC;CAAA,MAAAC,IAAAX,EAAA,CAAA;CAC9C,MAAAY,MAAYX,OAAO;CAAE,IAAAY;CAAA,IAAAF,EAAA,OAAAC,KAAA;EAEdC,MAAAC,YAAA;GACL,MAAAC,SAAeH,IAAGI,OAAQ,CAAC,CAAAC,SAAU,CAAC,CAAAF;GACtCZ,2BAA2BY,MAAM,CAAC,CAAAG,YAAaJ,OAAO;EAAC;EACxDH,EAAA,KAAAC;EAAAD,EAAA,KAAAE;CAAA,OAAAA,KAAAF,EAAA;CAAA,OAHME;AAGN;;AAIH,MAAaM,yBAAmB;CAAA,OAC9BjB,YAAYkB,KAOX;AAAC;AAMJ,SAAgBC,2BACdC,YAA6CG,MAAMA,GAC5B;CACvB,OAAOvB,aAAawB,MAClBJ,SACEnB,2BAA2BuB,EAAEV,OAAOD,MAAM,CAAC,CAACQ,KAC9C,CACF;AACF;AAtBgC,SAAAH,MAAAM,GAAA;CAE5B,MAAA,EAAAC,SAAiBxB,2BAA2BuB,EAACV,OAAOD,MAAO;CAC3D,IAAIY,SAASC,KAAAA,GACX,MAAM,IAAIC,MACR,mFACF;CAAE,OACGF;AAAI"}
1
+ {"version":3,"file":"hooks.js","names":["c","_c","useAui","useAuiState","asAssistantTransportExtras","Assistant","AssistantTransportThread","StatewireThread","UserExternalState","ExternalState","Record","useAssistantTransportSendCommand","$","aui","t0","command","extras","thread","getState","sendCommand","useStatewireThreadStatus","_temp","useStatewireRuns","_temp2","useAssistantTransportState","selector","state","T","t","s","status","undefined","Error","runs"],"sources":["../src/hooks.ts"],"sourcesContent":["\"use client\";\n\nimport { useAui, useAuiState } from \"@assistant-ui/store\";\nimport { asAssistantTransportExtras } from \"./AssistantTransportThread\";\nimport type { Assistant } from \"@assistant-ui/react\";\nimport type { AssistantTransportThread } from \"./AssistantTransportThread\";\nimport type { StatewireThread } from \"./StatewireThread\";\n\ntype UserExternalState = keyof Assistant.ExternalState extends never\n ? Record<string, unknown>\n : Assistant.ExternalState[keyof Assistant.ExternalState];\n\nexport const useAssistantTransportSendCommand = () => {\n const aui = useAui();\n\n return (command: AssistantTransportThread.Command) => {\n const extras = aui.thread().getState().extras;\n asAssistantTransportExtras(extras).sendCommand(command);\n };\n};\n\n/** The thread status; requires StatewireThread. */\nexport const useStatewireThreadStatus = (): StatewireThread.ThreadStatus =>\n useAuiState((s) => {\n const { status } = asAssistantTransportExtras(s.thread.extras);\n if (status === undefined)\n throw new Error(\n \"statewire: useStatewireThreadStatus requires StatewireThread\",\n );\n return status;\n });\n\n/** The typed runs read; requires StatewireThread with the `runs` option. */\nexport const useStatewireRuns = (): StatewireThread.Runs =>\n useAuiState((s) => {\n const { runs } = asAssistantTransportExtras(s.thread.extras);\n if (runs === undefined)\n throw new Error(\n \"statewire: useStatewireRuns requires StatewireThread with the runs option enabled\",\n );\n return runs;\n });\n\nexport function useAssistantTransportState(): UserExternalState;\nexport function useAssistantTransportState<T>(\n selector: (state: UserExternalState) => T,\n): T;\nexport function useAssistantTransportState<T>(\n selector: (state: UserExternalState) => T = (t) => t as T,\n): T | UserExternalState {\n return useAuiState((s) =>\n selector(\n asAssistantTransportExtras(s.thread.extras).state as UserExternalState,\n ),\n );\n}\n"],"mappings":";;;;;AAYA,MAAaW,yCAAmC;CAAA,MAAAC,IAAAX,EAAA,CAAA;CAC9C,MAAAY,MAAYX,OAAO;CAAE,IAAAY;CAAA,IAAAF,EAAA,OAAAC,KAAA;EAEdC,MAAAC,YAAA;GACL,MAAAC,SAAeH,IAAGI,OAAQ,CAAC,CAAAC,SAAU,CAAC,CAAAF;GACtCZ,2BAA2BY,MAAM,CAAC,CAAAG,YAAaJ,OAAO;EAAC;EACxDH,EAAA,KAAAC;EAAAD,EAAA,KAAAE;CAAA,OAAAA,KAAAF,EAAA;CAAA,OAHME;AAGN;;AAIH,MAAaM,iCAA2B;CAAA,OACtCjB,YAAYkB,KAOX;AAAC;;AAGJ,MAAaC,yBAAmB;CAAA,OAC9BnB,YAAYoB,MAOX;AAAC;AAMJ,SAAgBC,2BACdC,YAA6CG,MAAMA,GAC5B;CACvB,OAAOzB,aAAa0B,MAClBJ,SACErB,2BAA2ByB,EAAEZ,OAAOD,MAAM,CAAC,CAACU,KAC9C,CACF;AACF;AAjCwC,SAAAL,MAAAQ,GAAA;CAEpC,MAAA,EAAAC,WAAmB1B,2BAA2ByB,EAACZ,OAAOD,MAAO;CAC7D,IAAIc,WAAWC,KAAAA,GACb,MAAM,IAAIC,MACR,8DACF;CAAE,OACGF;AAAM;AAIe,SAAAP,OAAAM,GAAA;CAE5B,MAAA,EAAAI,SAAiB7B,2BAA2ByB,EAACZ,OAAOD,MAAO;CAC3D,IAAIiB,SAASF,KAAAA,GACX,MAAM,IAAIC,MACR,mFACF;CAAE,OACGC;AAAI"}
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { StatewireThread } from "./StatewireThread.js";
2
2
  import { AssistantTransportThread } from "./AssistantTransportThread.js";
3
- import { useAssistantTransportSendCommand, useAssistantTransportState, useStatewireRuns } from "./hooks.js";
3
+ import { useAssistantTransportSendCommand, useAssistantTransportState, useStatewireRuns, useStatewireThreadStatus } from "./hooks.js";
4
4
  import { runsMaterialize } from "./runsMaterialize.js";
5
- export { AssistantTransportThread, StatewireThread, runsMaterialize, useAssistantTransportSendCommand, useAssistantTransportState, useStatewireRuns };
5
+ export { AssistantTransportThread, StatewireThread, runsMaterialize, useAssistantTransportSendCommand, useAssistantTransportState, useStatewireRuns, useStatewireThreadStatus };