@assistant-ui/react-statewire 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","AppendMessage","AttachmentAdapter","ExternalThreadQueueAdapter","ModelContext","QueuePlacement","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","StatewireClient","convertAppendMessageToCommand","symbolAssistantTransportExtras","AssistantTransportExtras","AssistantTransportCommand","AnyCommands","Record","args","ambientContextOf","context","system","undefined","tools","callSettings","config","toWireMessage","message","id","StatewireThread","UserMessage","role","Error","files","FilePart","texts","source","content","attachments","flatMap","a","part","type","push","text","mediaType","url","image","mimeType","data","filename","parts","TextPart","length","const","join","toQueueItemState","item","QueueItem","prompt","map","placementFields","placement","insertAfter","insertBefore","withSessionLostFallback","transport","Transport","latest","current","Options","transportOptions","rest","transportLevel","onCommandSessionLost","command","SessionLostCommand","useStatewireThread","options","pending","setPending","Command","retire","prev","includes","filter","c","state","transportState","commands","connection","setContext","onCommandChange","update","status","params","attached","initialState","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","catch","error","onError","subscribe","dispatch","converter","metadata","ConnectionMetadata","pendingCommands","isSending","converted","queueItems","queue","steerQueueItems","steerQueue","queueSeam","present","laneOf","queueItemId","some","items","steerItems","enqueue","crypto","randomUUID","steer","move","lane","fields","messageId","edit","wireMessage","remove","extras","sendCommand","reconnect","handleAppend","handleEdit","sourceId","messages","isRunning","isLoading","attachmentAdapter","adapters","onNew","capabilities","onEdit","continue","onResume","onCancel","payload","cancelPayload","Array","isArray","T","Placement","RunEnqueueCommand","RunSteerCommand","RunDequeueCommand","RunEditCommand","RunContinueCommand","RunCommand","State","ConnectionState","StateConverter","connectionMetadata","CancelPayload","reason","hook"],"sources":["../src/StatewireThread.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { resource, useResource } from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/react\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/react\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport type {\n AppendMessage,\n AttachmentAdapter,\n ExternalThreadQueueAdapter,\n ModelContext,\n QueuePlacement,\n ThreadMessage,\n} from \"@assistant-ui/core\";\nimport { toToolsJSONSchema } from \"assistant-stream\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { useStatewire } from \"statewire\";\nimport type { Statewire, StatewireClient } from \"statewire\";\nimport {\n convertAppendMessageToCommand,\n symbolAssistantTransportExtras,\n} from \"./AssistantTransportThread\";\nimport type { AssistantTransportExtras } from \"./AssistantTransportThread\";\nimport type { AssistantTransportCommand } from \"./types\";\n\ntype AnyCommands = Record<string, (...args: any[]) => unknown>;\n\nconst ambientContextOf = (context: ModelContext): Record<string, unknown> => ({\n ...(context.system !== undefined && { system: context.system }),\n ...(context.tools !== undefined && {\n tools: toToolsJSONSchema(context.tools),\n }),\n ...(context.callSettings !== undefined && {\n callSettings: context.callSettings,\n }),\n ...(context.config !== undefined && { config: context.config }),\n});\n\nconst toWireMessage = (\n message: AppendMessage,\n id: string,\n): StatewireThread.UserMessage => {\n if (message.role !== \"user\")\n throw new Error(\"statewire: only user messages are supported\");\n const files: StatewireThread.FilePart[] = [];\n const texts: string[] = [];\n const source = [\n ...message.content,\n ...(message.attachments?.flatMap((a) => a.content) ?? []),\n ];\n for (const part of source) {\n if (part.type === \"text\") {\n texts.push(part.text);\n } else if (part.type === \"image\") {\n files.push({ type: \"file\", mediaType: \"image/*\", url: part.image });\n } else if (part.type === \"file\") {\n files.push({\n type: \"file\",\n mediaType: part.mimeType,\n url: part.data,\n ...(part.filename !== undefined && { filename: part.filename }),\n });\n } else {\n throw new Error(`statewire: unsupported message part \"${part.type}\"`);\n }\n }\n // default-safe against host capabilities: files first, one merged text part\n const parts: (StatewireThread.TextPart | StatewireThread.FilePart)[] = [\n ...files,\n ...(texts.length > 0\n ? [{ type: \"text\" as const, text: texts.join(\"\\n\\n\") }]\n : []),\n ];\n if (parts.length === 0)\n throw new Error(\"statewire: cannot send an empty message\");\n return { id, role: \"user\", parts };\n};\n\nconst toQueueItemState = (item: StatewireThread.QueueItem) => ({\n id: item.id,\n prompt: item.parts\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\"),\n parts: item.parts.map((part) =>\n part.type === \"text\"\n ? part\n : {\n type: \"file\" as const,\n data: part.url,\n mimeType: part.mediaType,\n ...(part.filename !== undefined && { filename: part.filename }),\n },\n ),\n});\n\nconst placementFields = (placement: QueuePlacement) => ({\n ...(placement.insertAfter !== undefined && {\n insertAfter: placement.insertAfter,\n }),\n ...(placement.insertBefore !== undefined && {\n insertBefore: placement.insertBefore,\n }),\n});\n\nconst withSessionLostFallback = (\n transport: StatewireThread.Transport<any>,\n latest: { current: StatewireThread.Options<any> },\n): StatewireThread.Transport<any> => {\n const [transportOptions, ...rest] = transport.args as [\n Record<string, unknown>,\n ...unknown[],\n ];\n if (\n rest.length > 0 ||\n typeof transportOptions !== \"object\" ||\n transportOptions === null\n ) {\n throw new Error(\n \"statewire: onCommandSessionLost requires a transport element that takes a single options object\",\n );\n }\n const transportLevel = transportOptions.onCommandSessionLost as\n | ((command: StatewireClient.SessionLostCommand) => \"replay\" | void)\n | undefined;\n return {\n ...transport,\n args: [\n {\n ...transportOptions,\n onCommandSessionLost: (\n command: StatewireClient.SessionLostCommand,\n ): \"replay\" | void =>\n transportLevel?.(command) ??\n latest.current.onCommandSessionLost?.(command),\n },\n ],\n };\n};\n\nconst useStatewireThread = (\n options: StatewireThread.Options<any>,\n): ClientOutput<\"thread\"> => {\n const latest = useRef(options);\n latest.current = options;\n\n const [pending, setPending] = useState<readonly StatewireThread.Command[]>(\n [],\n );\n const [retire] = useState(\n () => (command: unknown) =>\n setPending((prev) =>\n prev.includes(command as StatewireThread.Command)\n ? prev.filter((c) => c !== command)\n : prev,\n ),\n );\n\n const {\n state: transportState,\n commands,\n connection,\n setContext,\n } = useStatewire<unknown, AnyCommands>({\n transport:\n options.onCommandSessionLost === undefined\n ? options.transport\n : withSessionLostFallback(options.transport, latest),\n onCommandChange: (update) => {\n if (update.status === \"acked\" || update.status === \"settled\")\n retire(update.params[0]);\n },\n });\n const attached = transportState !== undefined;\n const state = attached ? transportState : options.initialState;\n\n const clientRef = useAssistantClientRef();\n const setContextRef = useRef(setContext);\n setContextRef.current = setContext;\n const [syncState] = useState(() => ({ lastSent: undefined as unknown }));\n const { contextSync } = options;\n useEffect(() => {\n if (contextSync === undefined) return;\n const modelContext = (clientRef.current ?? clientRef.parent).modelContext();\n const send = () => {\n const value = ambientContextOf(modelContext.getModelContext());\n const key = JSON.stringify(value);\n if (key === syncState.lastSent) return;\n syncState.lastSent = key;\n void setContextRef.current(value).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n };\n send();\n if (!modelContext.subscribe) {\n throw new Error(\n \"statewire: contextSync requires a subscribable model context\",\n );\n }\n return modelContext.subscribe(send);\n }, [contextSync, clientRef, syncState]);\n\n const dispatch = useCallback(\n (command: StatewireThread.Command) => {\n setPending((prev) => [...prev, command]);\n void commands[command.type]!(command).catch((error: Error) => {\n retire(command);\n latest.current.onError?.(error);\n });\n },\n [commands, retire],\n );\n\n const { converter } = options;\n const metadata = useMemo(\n (): StatewireThread.ConnectionMetadata => ({\n pendingCommands: [...pending],\n isSending: pending.length > 0,\n connection,\n }),\n [pending, connection],\n );\n const converted = useMemo(\n () => converter(state, metadata),\n [converter, state, metadata],\n );\n const queueItems = converted.queue;\n const steerQueueItems = converted.steerQueue;\n if (steerQueueItems !== undefined && queueItems === undefined)\n throw new Error(\n \"statewire: the converter's steerQueue projection requires the queue projection\",\n );\n const [queueSeam] = useState(() => ({\n present: queueItems !== undefined,\n }));\n if (queueSeam.present !== (queueItems !== undefined))\n throw new Error(\n \"statewire: the converter's queue projection must be stable — it was \" +\n (queueSeam.present ? \"defined\" : \"undefined\") +\n \" on first convert and changed since\",\n );\n\n const queue = useMemo((): ExternalThreadQueueAdapter | undefined => {\n if (!queueItems) return undefined;\n const laneOf = (queueItemId: string): \"queue\" | \"steer\" => {\n if (steerQueueItems?.some((item) => item.id === queueItemId))\n return \"steer\";\n if (queueItems.some((item) => item.id === queueItemId)) return \"queue\";\n throw new Error(`statewire: unknown queue item \"${queueItemId}\"`);\n };\n return {\n items: queueItems.map(toQueueItemState),\n steerItems: (steerQueueItems ?? []).map(toQueueItemState),\n enqueue: (message) =>\n dispatch({\n type: \"run/enqueue\",\n message: toWireMessage(message, crypto.randomUUID()),\n }),\n steer: (message) =>\n dispatch({\n type: \"run/steer\",\n message: toWireMessage(message, crypto.randomUUID()),\n }),\n move: (queueItemId, placement) => {\n const lane = placement.lane ?? laneOf(queueItemId);\n const fields = {\n messageId: queueItemId,\n ...placementFields(placement),\n };\n dispatch(\n lane === \"steer\"\n ? { type: \"run/steer\", ...fields }\n : { type: \"run/enqueue\", ...fields },\n );\n },\n edit: (queueItemId, message) => {\n const wireMessage = toWireMessage(message, queueItemId);\n dispatch(\n laneOf(queueItemId) === \"steer\"\n ? { type: \"run/steer\", message: wireMessage }\n : { type: \"run/enqueue\", message: wireMessage },\n );\n },\n remove: (queueItemId) =>\n dispatch({ type: \"run/dequeue\", messageId: queueItemId }),\n };\n }, [queueItems, steerQueueItems, dispatch]);\n\n const extras = useMemo(\n (): AssistantTransportExtras => ({\n [symbolAssistantTransportExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state,\n }),\n [dispatch, connection.reconnect, state],\n );\n\n const handleAppend = (message: AppendMessage) => {\n const command = convertAppendMessageToCommand(message);\n if (!command) return;\n dispatch(command);\n };\n\n const handleEdit = (message: AppendMessage) => {\n if (!queueItems) return handleAppend(message);\n if (message.sourceId == null)\n throw new Error(\"statewire: run/edit requires a sourceId\");\n dispatch({\n type: \"run/edit\",\n message: toWireMessage(message, crypto.randomUUID()),\n sourceId: message.sourceId,\n });\n };\n\n return useResource(\n ExternalThread({\n messages: converted.messages as readonly ExternalThreadMessage[],\n isRunning: converted.isRunning,\n isLoading: !attached,\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n onNew: handleAppend,\n ...(queue && { queue }),\n ...(options.capabilities?.edit && { onEdit: handleEdit }),\n ...(options.capabilities?.continue && {\n onResume: () => dispatch({ type: \"run/continue\" }),\n }),\n onCancel: () => {\n const payload = latest.current.cancelPayload?.();\n if (\n payload !== undefined &&\n (typeof payload !== \"object\" ||\n payload === null ||\n Array.isArray(payload))\n )\n throw new Error(\n \"statewire: cancelPayload must return a plain object\",\n );\n void commands[\"run/cancel\"]!(\n ...(payload === undefined ? [] : [payload]),\n ).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n },\n }),\n );\n};\n\nexport const StatewireThread = <T>(\n options: StatewireThread.Options<T>,\n): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useStatewireThread)(options as StatewireThread.Options<any>);\n\nexport namespace StatewireThread {\n export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;\n\n export type TextPart = {\n readonly type: \"text\";\n readonly text: string;\n };\n\n export type FilePart = {\n readonly type: \"file\";\n readonly mediaType: string;\n readonly url: string;\n readonly filename?: string;\n };\n\n export type UserMessage = {\n readonly id: string;\n readonly role: \"user\";\n readonly parts: readonly (TextPart | FilePart)[];\n readonly metadata?: Record<string, unknown>;\n };\n\n /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */\n export type Placement = {\n readonly insertAfter?: string | null;\n readonly insertBefore?: string | null;\n };\n\n export type RunEnqueueCommand = {\n readonly type: \"run/enqueue\";\n } & ({ readonly message: UserMessage } | { readonly messageId: string }) &\n Placement;\n\n export type RunSteerCommand = {\n readonly type: \"run/steer\";\n } & ({ readonly message: UserMessage } | { readonly messageId: string }) &\n Placement;\n\n export type RunDequeueCommand = {\n readonly type: \"run/dequeue\";\n readonly messageId: string;\n };\n\n export type RunEditCommand = {\n readonly type: \"run/edit\";\n readonly message: UserMessage;\n readonly sourceId: string;\n };\n\n export type RunContinueCommand = {\n readonly type: \"run/continue\";\n };\n\n export type RunCommand =\n | RunEnqueueCommand\n | RunSteerCommand\n | RunDequeueCommand\n | RunEditCommand\n | RunContinueCommand;\n\n export type Command = AssistantTransportCommand | RunCommand;\n\n /** A queued message projected out of the host state, wire shape. */\n export type QueueItem = {\n readonly id: string;\n readonly parts: readonly (TextPart | FilePart)[];\n };\n\n export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n readonly isRunning: boolean;\n /**\n * The host's regular queue lane projected out of the state. Returning it\n * (even empty) turns on the queue capability: sends become `run/enqueue`\n * / `run/steer` commands and item controls send the `run/*` queue\n * commands. Presence must be stable across conversions.\n */\n readonly queue?: readonly QueueItem[];\n /** The host's steer lane; requires `queue`. Absent means empty. */\n readonly steerQueue?: readonly QueueItem[];\n };\n\n export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `live`. */\n connection: StatewireClient.ConnectionState;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n /**\n * Payload of the built-in `run/cancel` command. `reason` is the one well-known\n * field; apps extend it with their own JSON-serializable fields.\n */\n export type CancelPayload = {\n readonly reason?: string | undefined;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n export type Options<T> = {\n transport: Transport<T>;\n initialState: T;\n converter: StateConverter<T>;\n /**\n * \"command-send\" mirrors the client's ambient model context (system,\n * tools, callSettings, config) to the server over the command channel —\n * on connect and whenever it changes. Requires a remote transport.\n */\n contextSync?: \"command-send\" | undefined;\n /** Supplies the `run/cancel` command's payload; omitted, cancel sends no payload. */\n cancelPayload?: (() => CancelPayload) | undefined;\n /**\n * Offered each pending command when a remote transport's session is\n * evicted; return \"replay\" to re-enqueue it under the rotated client id.\n * A callback set on the transport options is consulted first; this one\n * runs for commands it declined.\n */\n onCommandSessionLost?:\n | ((command: StatewireClient.SessionLostCommand) => \"replay\" | void)\n | undefined;\n onError?: ((error: Error) => void) | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n /** The host supports `run/continue` (a continue affordance on aborted runs). */\n continue?: boolean | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n }\n | undefined;\n };\n}\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useStatewireThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;AA+BA,MAAM+B,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWC,KAAAA,KAAa,EAAED,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQG,UAAUD,KAAAA,KAAa,EACjCC,OAAOhB,kBAAkBa,QAAQG,KAAK,EACxC;CACA,GAAIH,QAAQI,iBAAiBF,KAAAA,KAAa,EACxCE,cAAcJ,QAAQI,aACxB;CACA,GAAIJ,QAAQK,WAAWH,KAAAA,KAAa,EAAEG,QAAQL,QAAQK,OAAO;AAC/D;AAEA,MAAMC,iBACJC,SACAC,OACgC;CAChC,IAAID,QAAQI,SAAS,QACnB,MAAM,IAAIC,MAAM,6CAA6C;CAC/D,MAAMC,QAAoC,CAAA;CAC1C,MAAME,QAAkB,CAAA;CACxB,MAAMC,SAAS,CACb,GAAGT,QAAQU,SACX,GAAIV,QAAQW,aAAaC,SAASC,MAAMA,EAAEH,OAAO,KAAK,CAAA,CAAG;CAE3D,KAAK,MAAMI,QAAQL,QACjB,IAAIK,KAAKC,SAAS,QAChBP,MAAMQ,KAAKF,KAAKG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,OAAO,CAC3C,CAAC,CAAClD,OAAOC,YAAiB;IACxB5C,OAAOC,QAAQ4C,UAAUD,OAAK;GAChC,CAAC;EACH;CACF,CAAC,CACH;AACF;AAEA,MAAanF,mBACXiD,YAEArF,SAASoF,kBAAkB,CAAC,CAACC,OAAuC;AAgJtEhF,uBACE+E,oBACAjF,eAAe0B,KAAAA,CAAkB,CAAC,CAAC6J,IACrC"}
1
+ {"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","AddToolResultOptions","AppendMessage","AttachmentAdapter","ExternalThreadQueueAdapter","ModelContext","RespondToToolApprovalOptions","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","StatewireClient","symbolAssistantTransportExtras","AssistantTransportExtras","createRunQueueAdapter","resolveReloadCommand","toWireMessage","resolveToolApprovalInput","resolveToolResultInput","AddMessageCommand","AssistantTransportCommand","UserMessagePart","AnyCommands","Record","args","ambientContextOf","context","system","undefined","tools","callSettings","config","convertAppendMessageToCommand","message","role","Error","parts","content","attachments","flatMap","a","contentPart","type","push","text","image","length","parentId","sourceId","withSessionLostFallback","transport","StatewireThread","Transport","latest","current","Options","transportOptions","rest","transportLevel","onCommandSessionLost","command","SessionLostCommand","useStatewireThread","options","pending","setPending","Command","retire","prev","includes","filter","c","state","transportState","commands","connection","setContext","onCommandChange","update","status","params","attached","initialState","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","catch","error","onError","subscribe","dispatch","converter","metadata","ConnectionMetadata","pendingCommands","isSending","converted","queueItems","queue","steerQueueItems","steerQueue","queueSeam","present","inputRequests","inputSeam","extras","sendCommand","reconnect","handleAppend","handleReload","messages","handleEdit","crypto","randomUUID","isRunning","isLoading","attachmentAdapter","adapters","onNew","capabilities","edit","onEdit","continue","onResume","reload","onReload","onAddToolResult","toolOptions","inputCommand","toolCallId","toolName","result","isError","artifact","modelContent","onRespondToToolApproval","approval","onCancel","payload","stopPayload","Array","isArray","T","TextPart","FilePart","mediaType","url","filename","UserMessage","id","Placement","insertAfter","insertBefore","RunEnqueueCommand","messageId","RunSteerCommand","RunDequeueCommand","RunEditCommand","RunContinueCommand","ToolCallInputRequest","ToolApprovalInputRequest","CustomInputRequest","InputRequest","ToolCallInputResponse","output","ToolApprovalInputResponse","decision","editedArgs","InputResponse","RunInputCommand","requestId","response","InputRequestState","RunReloadCommand","RunCommand","QueueItem","State","ConnectionState","StateConverter","connectionMetadata","StopPayload","reason","hook"],"sources":["../src/StatewireThread.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { resource, useResource } from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/react\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/react\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n AttachmentAdapter,\n ExternalThreadQueueAdapter,\n ModelContext,\n RespondToToolApprovalOptions,\n ThreadMessage,\n} from \"@assistant-ui/core\";\nimport { toToolsJSONSchema } from \"assistant-stream\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { useStatewire } from \"statewire\";\nimport type { Statewire, StatewireClient } from \"statewire\";\nimport { symbolAssistantTransportExtras } from \"./AssistantTransportThread\";\nimport type { AssistantTransportExtras } from \"./AssistantTransportThread\";\nimport {\n createRunQueueAdapter,\n resolveReloadCommand,\n toWireMessage,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\nimport type {\n AddMessageCommand,\n AssistantTransportCommand,\n UserMessagePart,\n} from \"./types\";\n\ntype AnyCommands = Record<string, (...args: any[]) => unknown>;\n\nconst ambientContextOf = (context: ModelContext): Record<string, unknown> => ({\n ...(context.system !== undefined && { system: context.system }),\n ...(context.tools !== undefined && {\n tools: toToolsJSONSchema(context.tools),\n }),\n ...(context.callSettings !== undefined && {\n callSettings: context.callSettings,\n }),\n ...(context.config !== undefined && { config: context.config }),\n});\n\nconst convertAppendMessageToCommand = (\n message: AppendMessage,\n): AddMessageCommand | null => {\n if (message.role !== \"user\")\n throw new Error(\"Only user messages are supported\");\n\n const parts: UserMessagePart[] = [];\n const content = [\n ...message.content,\n ...(message.attachments?.flatMap((a) => a.content) ?? []),\n ];\n for (const contentPart of content) {\n if (contentPart.type === \"text\") {\n parts.push({ type: \"text\", text: contentPart.text });\n } else if (contentPart.type === \"image\") {\n parts.push({ type: \"image\", image: contentPart.image });\n }\n }\n\n if (parts.length === 0) return null;\n\n return {\n type: \"add-message\",\n message: {\n role: \"user\",\n parts,\n },\n parentId: message.parentId,\n sourceId: message.sourceId,\n };\n};\n\nconst withSessionLostFallback = (\n transport: StatewireThread.Transport<any>,\n latest: { current: StatewireThread.Options<any> },\n): StatewireThread.Transport<any> => {\n const [transportOptions, ...rest] = transport.args as [\n Record<string, unknown>,\n ...unknown[],\n ];\n if (\n rest.length > 0 ||\n typeof transportOptions !== \"object\" ||\n transportOptions === null\n ) {\n throw new Error(\n \"statewire: onCommandSessionLost requires a transport element that takes a single options object\",\n );\n }\n const transportLevel = transportOptions.onCommandSessionLost as\n | ((command: StatewireClient.SessionLostCommand) => \"replay\" | void)\n | undefined;\n return {\n ...transport,\n args: [\n {\n ...transportOptions,\n onCommandSessionLost: (\n command: StatewireClient.SessionLostCommand,\n ): \"replay\" | void =>\n transportLevel?.(command) ??\n latest.current.onCommandSessionLost?.(command),\n },\n ],\n };\n};\n\nconst useStatewireThread = (\n options: StatewireThread.Options<any>,\n): ClientOutput<\"thread\"> => {\n const latest = useRef(options);\n latest.current = options;\n\n const [pending, setPending] = useState<readonly StatewireThread.Command[]>(\n [],\n );\n const [retire] = useState(\n () => (command: unknown) =>\n setPending((prev) =>\n prev.includes(command as StatewireThread.Command)\n ? prev.filter((c) => c !== command)\n : prev,\n ),\n );\n\n const {\n state: transportState,\n commands,\n connection,\n setContext,\n } = useStatewire<unknown, AnyCommands>({\n transport:\n options.onCommandSessionLost === undefined\n ? options.transport\n : withSessionLostFallback(options.transport, latest),\n onCommandChange: (update) => {\n if (update.status === \"acked\" || update.status === \"settled\")\n retire(update.params[0]);\n },\n });\n const attached = transportState !== undefined;\n const state = attached ? transportState : options.initialState;\n\n const clientRef = useAssistantClientRef();\n const setContextRef = useRef(setContext);\n setContextRef.current = setContext;\n const [syncState] = useState(() => ({ lastSent: undefined as unknown }));\n const { contextSync } = options;\n useEffect(() => {\n if (contextSync === undefined) return;\n const modelContext = (clientRef.current ?? clientRef.parent).modelContext();\n const send = () => {\n const value = ambientContextOf(modelContext.getModelContext());\n const key = JSON.stringify(value);\n if (key === syncState.lastSent) return;\n syncState.lastSent = key;\n void setContextRef.current(value).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n };\n send();\n if (!modelContext.subscribe) {\n throw new Error(\n \"statewire: contextSync requires a subscribable model context\",\n );\n }\n return modelContext.subscribe(send);\n }, [contextSync, clientRef, syncState]);\n\n const dispatch = useCallback(\n (command: StatewireThread.Command) => {\n setPending((prev) => [...prev, command]);\n void commands[command.type]!(command).catch((error: Error) => {\n retire(command);\n latest.current.onError?.(error);\n });\n },\n [commands, retire],\n );\n\n const { converter } = options;\n const metadata = useMemo(\n (): StatewireThread.ConnectionMetadata => ({\n pendingCommands: [...pending],\n isSending: pending.length > 0,\n connection,\n }),\n [pending, connection],\n );\n const converted = useMemo(\n () => converter(state, metadata),\n [converter, state, metadata],\n );\n const queueItems = converted.queue;\n const steerQueueItems = converted.steerQueue;\n if (steerQueueItems !== undefined && queueItems === undefined)\n throw new Error(\n \"statewire: the converter's steerQueue projection requires the queue projection\",\n );\n const [queueSeam] = useState(() => ({\n present: queueItems !== undefined,\n }));\n if (queueSeam.present !== (queueItems !== undefined))\n throw new Error(\n \"statewire: the converter's queue projection must be stable — it was \" +\n (queueSeam.present ? \"defined\" : \"undefined\") +\n \" on first convert and changed since\",\n );\n\n const queue = useMemo(\n (): ExternalThreadQueueAdapter | undefined =>\n queueItems\n ? createRunQueueAdapter(queueItems, steerQueueItems, dispatch)\n : undefined,\n [queueItems, steerQueueItems, dispatch],\n );\n\n const inputRequests = converted.inputRequests;\n const [inputSeam] = useState(() => ({\n present: inputRequests !== undefined,\n }));\n if (inputSeam.present !== (inputRequests !== undefined))\n throw new Error(\n \"statewire: the converter's inputRequests projection must be stable — it was \" +\n (inputSeam.present ? \"defined\" : \"undefined\") +\n \" on first convert and changed since\",\n );\n\n const extras = useMemo(\n (): AssistantTransportExtras => ({\n [symbolAssistantTransportExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state,\n ...(inputRequests !== undefined && { inputRequests }),\n }),\n [dispatch, connection.reconnect, state, inputRequests],\n );\n\n const handleAppend = (message: AppendMessage) => {\n const command = convertAppendMessageToCommand(message);\n if (!command) return;\n dispatch(command);\n };\n\n const handleReload = (parentId: string | null) => {\n dispatch(resolveReloadCommand(converted.messages, parentId));\n };\n\n const handleEdit = (message: AppendMessage) => {\n if (!queueItems) return handleAppend(message);\n if (message.sourceId == null)\n throw new Error(\"statewire: run/edit requires a sourceId\");\n dispatch({\n type: \"run/edit\",\n message: toWireMessage(message, crypto.randomUUID()),\n sourceId: message.sourceId,\n });\n };\n\n return useResource(\n ExternalThread({\n messages: converted.messages as readonly ExternalThreadMessage[],\n isRunning: converted.isRunning,\n isLoading: !attached,\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n onNew: handleAppend,\n ...(queue && { queue }),\n ...(options.capabilities?.edit && { onEdit: handleEdit }),\n ...(options.capabilities?.continue && {\n onResume: () => dispatch({ type: \"run/continue\" }),\n }),\n ...(options.capabilities?.reload && { onReload: handleReload }),\n ...(inputRequests !== undefined && {\n onAddToolResult: (toolOptions: AddToolResultOptions) => {\n const inputCommand = resolveToolResultInput(\n inputRequests,\n toolOptions,\n );\n dispatch(\n inputCommand ?? {\n type: \"add-tool-result\",\n toolCallId: toolOptions.toolCallId,\n toolName: toolOptions.toolName,\n result: toolOptions.result,\n isError: toolOptions.isError,\n ...(toolOptions.artifact !== undefined && {\n artifact: toolOptions.artifact,\n }),\n ...(toolOptions.modelContent !== undefined && {\n modelContent: toolOptions.modelContent,\n }),\n },\n );\n },\n onRespondToToolApproval: (approval: RespondToToolApprovalOptions) =>\n dispatch(resolveToolApprovalInput(inputRequests, approval)),\n }),\n onCancel: () => {\n const payload = latest.current.stopPayload?.();\n if (\n payload !== undefined &&\n (typeof payload !== \"object\" ||\n payload === null ||\n Array.isArray(payload))\n )\n throw new Error(\"statewire: stopPayload must return a plain object\");\n void commands[\"run/stop\"]!(\n ...(payload === undefined ? [] : [payload]),\n ).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n },\n }),\n );\n};\n\nexport const StatewireThread = <T>(\n options: StatewireThread.Options<T>,\n): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useStatewireThread)(options as StatewireThread.Options<any>);\n\nexport namespace StatewireThread {\n export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;\n\n export type TextPart = {\n readonly type: \"text\";\n readonly text: string;\n };\n\n export type FilePart = {\n readonly type: \"file\";\n readonly mediaType: string;\n readonly url: string;\n readonly filename?: string;\n };\n\n export type UserMessage = {\n readonly id: string;\n readonly role: \"user\";\n readonly parts: readonly (TextPart | FilePart)[];\n readonly metadata?: Record<string, unknown>;\n };\n\n /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */\n export type Placement = {\n readonly insertAfter?: string | null;\n readonly insertBefore?: string | null;\n };\n\n export type RunEnqueueCommand = {\n readonly type: \"run/enqueue\";\n } & ({ readonly message: UserMessage } | { readonly messageId: string }) &\n Placement;\n\n export type RunSteerCommand = {\n readonly type: \"run/steer\";\n } & ({ readonly message: UserMessage } | { readonly messageId: string }) &\n Placement;\n\n export type RunDequeueCommand = {\n readonly type: \"run/dequeue\";\n readonly messageId: string;\n };\n\n export type RunEditCommand = {\n readonly type: \"run/edit\";\n readonly message: UserMessage;\n readonly sourceId: string;\n };\n\n export type RunContinueCommand = {\n readonly type: \"run/continue\";\n };\n\n export type ToolCallInputRequest = {\n readonly type: \"tool-call\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type ToolApprovalInputRequest = {\n readonly type: \"tool-approval\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type CustomInputRequest = {\n readonly type: string;\n readonly id: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A host request parking the run until answered; open union for custom types. */\n export type InputRequest =\n | ToolCallInputRequest\n | ToolApprovalInputRequest\n | CustomInputRequest;\n\n export type ToolCallInputResponse = {\n readonly output: ReadonlyJSONValue;\n /** Default false; when true, `output` carries the error payload. */\n readonly isError?: boolean;\n readonly artifact?: ReadonlyJSONValue;\n };\n\n export type ToolApprovalInputResponse = {\n readonly decision: \"approve\" | \"reject\" | \"edit\" | \"respond\";\n readonly editedArgs?: ReadonlyJSONValue;\n readonly message?: string;\n };\n\n export type InputResponse = ReadonlyJSONValue;\n\n export type RunInputCommand = {\n readonly type: \"run/input\";\n readonly requestId: string;\n readonly response: InputResponse;\n };\n\n /** An input request projected out of the host state with its response echo. */\n export type InputRequestState = InputRequest & {\n readonly response: InputResponse | null;\n };\n\n export type RunReloadCommand = {\n readonly type: \"run/reload\";\n readonly sourceId: string;\n };\n\n export type RunCommand =\n | RunEnqueueCommand\n | RunSteerCommand\n | RunDequeueCommand\n | RunEditCommand\n | RunContinueCommand\n | RunReloadCommand\n | RunInputCommand;\n\n export type Command = AssistantTransportCommand | RunCommand;\n\n /** A queued message projected out of the host state, wire shape. */\n export type QueueItem = {\n readonly id: string;\n readonly parts: readonly (TextPart | FilePart)[];\n };\n\n export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n readonly isRunning: boolean;\n /**\n * The host's regular queue lane projected out of the state. Returning it\n * (even empty) turns on the queue capability: sends become `run/enqueue`\n * / `run/steer` commands and item controls send the `run/*` queue\n * commands. Presence must be stable across conversions.\n */\n readonly queue?: readonly QueueItem[];\n /** The host's steer lane; requires `queue`. Absent means empty. */\n readonly steerQueue?: readonly QueueItem[];\n /**\n * The host's parked input requests projected out of the state. Returning\n * it (even empty) routes tool results and approvals with a matching\n * pending request through `run/input`. Presence must be stable across\n * conversions.\n */\n readonly inputRequests?: readonly InputRequestState[];\n };\n\n export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `live`. */\n connection: StatewireClient.ConnectionState;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n /**\n * Payload of the built-in `run/stop` command. `reason` is the one well-known\n * field; apps extend it with their own JSON-serializable fields.\n */\n export type StopPayload = {\n readonly reason?: string | undefined;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n export type Options<T> = {\n transport: Transport<T>;\n initialState: T;\n converter: StateConverter<T>;\n /**\n * \"command-send\" mirrors the client's ambient model context (system,\n * tools, callSettings, config) to the server over the command channel —\n * on connect and whenever it changes. Requires a remote transport.\n */\n contextSync?: \"command-send\" | undefined;\n /** Supplies the `run/stop` command's payload; omitted, stop sends no payload. */\n stopPayload?: (() => StopPayload) | undefined;\n /**\n * Offered each pending command when a remote transport's session is\n * evicted; return \"replay\" to re-enqueue it under the rotated client id.\n * A callback set on the transport options is consulted first; this one\n * runs for commands it declined.\n */\n onCommandSessionLost?:\n | ((command: StatewireClient.SessionLostCommand) => \"replay\" | void)\n | undefined;\n onError?: ((error: Error) => void) | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n /** The host supports `run/continue` (a continue affordance on aborted runs). */\n continue?: boolean | undefined;\n /** The host supports `run/reload` (regenerating an assistant message). */\n reload?: boolean | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n }\n | undefined;\n };\n}\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useStatewireThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;;;AA0CA,MAAMsC,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWC,KAAAA,KAAa,EAAED,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQG,UAAUD,KAAAA,KAAa,EACjCC,OAAOtB,kBAAkBmB,QAAQG,KAAK,EACxC;CACA,GAAIH,QAAQI,iBAAiBF,KAAAA,KAAa,EACxCE,cAAcJ,QAAQI,aACxB;CACA,GAAIJ,QAAQK,WAAWH,KAAAA,KAAa,EAAEG,QAAQL,QAAQK,OAAO;AAC/D;AAEA,MAAMC,iCACJC,YAC6B;CAC7B,IAAIA,QAAQC,SAAS,QACnB,MAAM,IAAIC,MAAM,kCAAkC;CAEpD,MAAMC,QAA2B,CAAA;CACjC,MAAMC,UAAU,CACd,GAAGJ,QAAQI,SACX,GAAIJ,QAAQK,aAAaC,SAASC,MAAMA,EAAEH,OAAO,KAAK,CAAA,CAAG;CAE3D,KAAK,MAAMI,eAAeJ,SACxB,IAAII,YAAYC,SAAS,QACvBN,MAAMO,KAAK;EAAED,MAAM;EAAQE,MAAMH,YAAYG;CAAK,CAAC;MAC9C,IAAIH,YAAYC,SAAS,SAC9BN,MAAMO,KAAK;EAAED,MAAM;EAASG,OAAOJ,YAAYI;CAAM,CAAC;CAI1D,IAAIT,MAAMU,WAAW,GAAG,OAAO;CAE/B,OAAO;EACLJ,MAAM;EACNT,SAAS;GACPC,MAAM;GACNE;EACF;EACAW,UAAUd,QAAQc;EAClBC,UAAUf,QAAQe;CACpB;AACF;AAEA,MAAMC,2BACJC,WACAG,WACmC;CACnC,MAAM,CAACG,kBAAkB,GAAGC,QAAQP,UAAU1B;CAI9C,IACEiC,KAAKX,SAAS,KACd,OAAOU,qBAAqB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@@ -31,7 +31,6 @@ type AssistantTransportHostCommands = {
31
31
  setParentId(parentId: string | null): void;
32
32
  cancel(): void;
33
33
  resume(): void;
34
- reload(parentId: string | null): void;
35
34
  importState(state: unknown): void;
36
35
  };
37
36
  declare const AssistantTransportHost: import("@assistant-ui/tap").Resource<Statewire<AssistantTransportHostState, AssistantTransportHostCommands, any>, [options: HostOptions]>;
@@ -1 +1 @@
1
- {"version":3,"file":"host.d.ts","names":[],"sources":["../src/host.ts"],"mappings":";;;;KA2BY;EACV;;KAGU;EACV,cAAc;EACd;;KAGU;EACV,QAAQ;EACR,WAAW;;KAMD;EAAkB,SAAS;;KAE3B,cAAc;EACxB,qBAAqB;EACrB,WAAW;;KAGD;EACV;EACA;EACA;EACA;;KAGU;EACV,KAAK,SAAS,2BAA2B,OAAO;EAChD,YAAY;EACZ;EACA;EACA,OAAO;EACP,YAAY;;cA0WD,oDAAsB,SAAA,UAAA,6BAAA,uCAAA,SAAA"}
1
+ {"version":3,"file":"host.d.ts","names":[],"sources":["../src/host.ts"],"mappings":";;;;KA0BY;EACV;;KAGU;EACV,cAAc;EACd;;KAGU;EACV,QAAQ;EACR,WAAW;;KAMD;EAAkB,SAAS;;KAE3B,cAAc;EACxB,qBAAqB;EACrB,WAAW;;KAGD;EACV;EACA;EACA;EACA;;KAGU;EACV,KAAK,SAAS,2BAA2B,OAAO;EAChD,YAAY;EACZ;EACA;EACA,YAAY;;cAwXD,oDAAsB,SAAA,UAAA,6BAAA,uCAAA,SAAA"}
package/dist/host.js CHANGED
@@ -5,7 +5,7 @@ import { resource } from "@assistant-ui/tap";
5
5
  import { createRequestHeaders } from "@assistant-ui/core";
6
6
  import { AssistantTransportDecoder, DataStreamDecoder, toToolsJSONSchema } from "assistant-stream";
7
7
  import { asAsyncIterableStream } from "assistant-stream/utils";
8
- import { CommandExecution, useStatewireCommands, useStatewireEmit, useStatewireState } from "statewire/host";
8
+ import { useStatewireCommands, useStatewireEmit, useStatewireState } from "statewire/host";
9
9
  //#region src/host.ts
10
10
  const commandsOf = (entries) => entries.map((e) => e.command);
11
11
  const useHostLoop = (getOptions, ctl, getAgent) => {
@@ -213,8 +213,10 @@ const useHostLoop = (getOptions, ctl, getAgent) => {
213
213
  resolveActive();
214
214
  } catch (error_1) {
215
215
  s.followUpRequested = false;
216
- if (!s.disposed) if (ac.signal.aborted) settleCancelled();
217
- else await settleFailed(error_1);
216
+ if (!s.disposed) {
217
+ if (ac.signal.aborted) settleCancelled();
218
+ else await settleFailed(error_1);
219
+ }
218
220
  } finally {
219
221
  if (s.disposed) s.abortController = null;
220
222
  else {
@@ -236,17 +238,26 @@ const useHostLoop = (getOptions, ctl, getAgent) => {
236
238
  startRun();
237
239
  };
238
240
  return {
239
- send: (command, opts) => {
240
- const [execution, resolvers] = CommandExecution.withResolvers();
241
+ send: function(command, opts) {
242
+ let resolve;
243
+ let reject;
244
+ const promise = new Promise((res, rej) => {
245
+ resolve = res;
246
+ reject = rej;
247
+ });
241
248
  setQueue({
242
249
  queued: [...s.queue.queued, {
243
250
  command,
244
- execution: resolvers
251
+ execution: {
252
+ ack: this.ack,
253
+ resolve,
254
+ reject
255
+ }
245
256
  }],
246
257
  inTransit: s.queue.inTransit
247
258
  });
248
259
  if (opts?.schedule !== false) schedule();
249
- return execution;
260
+ return promise;
250
261
  },
251
262
  setParentId: (id) => {
252
263
  s.parentId = id;
@@ -261,10 +272,6 @@ const useHostLoop = (getOptions, ctl, getAgent) => {
261
272
  s.resumeRequested = true;
262
273
  schedule();
263
274
  },
264
- reload: (id_0) => {
265
- s.parentId = id_0;
266
- schedule();
267
- },
268
275
  importState: replaceAgent
269
276
  };
270
277
  };
@@ -278,9 +285,10 @@ const useAssistantTransportHost = (options) => {
278
285
  isReplaying: false
279
286
  }));
280
287
  const emit = useStatewireEmit();
288
+ const handlers = useHostLoop(() => latestOptions.current, ctl, () => ctl.snapshot().agent);
281
289
  return {
282
290
  state,
283
- commands: useStatewireCommands(useHostLoop(() => latestOptions.current, ctl, () => ctl.snapshot().agent)),
291
+ commands: useStatewireCommands(handlers),
284
292
  emit
285
293
  };
286
294
  };
package/dist/host.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"host.js","names":["useEffect","useRef","useState","resource","createRequestHeaders","ModelContext","AssistantTransportDecoder","DataStreamDecoder","toToolsJSONSchema","AssistantTransportStateOperation","asAsyncIterableStream","Statewire","CommandExecution","useStatewireCommands","useStatewireEmit","useStatewireState","StatewireHost","createReplayBoundaryStream","translateStateOp","AssistantTransportCommand","AssistantTransportOptions","SendCommandsRequestBody","SendOptions","schedule","HostRunContext","modelContext","threadId","HostQueue","queued","inTransit","HostQueueCell","current","HostOptions","getRunContext","queueCell","AssistantTransportHostState","agent","queueVersion","isSending","isReplaying","AssistantTransportHostCommands","send","command","opts","setParentId","parentId","cancel","resume","reload","importState","state","QueueEntry","execution","ExecutionResolvers","EntryQueue","commandsOf","entries","map","e","LoopState","queue","activeEntries","resumeRequested","followUpRequested","disposed","abortController","AbortController","useHostLoop","getOptions","ctl","StateCtl","getAgent","s","undefined","abort","setReplaying","value","apply","op","path","setSending","replaceAgent","next","updateState","updater","applyChunkOps","operations","operation","setQueue","takeQueuedIntoTransit","length","drainQueue","drained","buildRequestBody","o","commands","runParentId","bodyValue","body","requestBody","Record","system","tools","callSettings","config","prepareSendCommandsRequest","run","signal","AbortSignal","isResume","runRequest","error","aborted","headers","response","fetch","resumeApi","api","method","JSON","stringify","onResponse","ok","Error","status","text","strict","decoder","protocol","streamError","delivered","markDelivered","entry","ack","chunks","pipeThrough","chunk","type","resolveActive","splice","resolve","settleCancelled","onCancel","settleFailed","reject","onError","startRun","ac","setTimeout","onFinish","resolvers","withResolvers","id","useAssistantTransportHost","options","latestOptions","initialState","emit","handlers","snapshot","AssistantTransportHost"],"sources":["../src/host.ts"],"sourcesContent":["import { useEffect, useRef, useState } from \"react\";\nimport { resource } from \"@assistant-ui/tap\";\nimport { createRequestHeaders } from \"@assistant-ui/core\";\nimport type { ModelContext } from \"@assistant-ui/core\";\nimport {\n AssistantTransportDecoder,\n DataStreamDecoder,\n toToolsJSONSchema,\n} from \"assistant-stream\";\nimport type { AssistantTransportStateOperation } from \"assistant-stream\";\nimport { asAsyncIterableStream } from \"assistant-stream/utils\";\nimport type { Statewire } from \"statewire\";\nimport {\n CommandExecution,\n useStatewireCommands,\n useStatewireEmit,\n useStatewireState,\n} from \"statewire/host\";\nimport type { StatewireHost } from \"statewire/host\";\nimport { createReplayBoundaryStream } from \"./replayBoundaryStream\";\nimport { translateStateOp } from \"./stateOps\";\nimport type {\n AssistantTransportCommand,\n AssistantTransportOptions,\n SendCommandsRequestBody,\n} from \"./types\";\n\nexport type SendOptions = {\n schedule?: boolean;\n};\n\nexport type HostRunContext = {\n modelContext: ModelContext;\n threadId: string | null;\n};\n\nexport type HostQueue = {\n queued: AssistantTransportCommand[];\n inTransit: AssistantTransportCommand[];\n};\n\n// Statewire state sanitizes values on apply; command objects must keep their\n// identity for converter-side caches, so the host publishes them through this\n// cell and bumps queueVersion in state to signal the change.\nexport type HostQueueCell = { current: HostQueue };\n\nexport type HostOptions = AssistantTransportOptions<unknown> & {\n getRunContext: () => HostRunContext;\n queueCell: HostQueueCell;\n};\n\nexport type AssistantTransportHostState = {\n agent: unknown;\n queueVersion: number;\n isSending: boolean;\n isReplaying: boolean;\n};\n\nexport type AssistantTransportHostCommands = {\n send(command: AssistantTransportCommand, opts?: SendOptions): void;\n setParentId(parentId: string | null): void;\n cancel(): void;\n resume(): void;\n reload(parentId: string | null): void;\n importState(state: unknown): void;\n};\n\ntype QueueEntry = {\n command: AssistantTransportCommand;\n execution: StatewireHost.ExecutionResolvers;\n};\n\ntype EntryQueue = {\n queued: QueueEntry[];\n inTransit: QueueEntry[];\n};\n\nconst commandsOf = (entries: QueueEntry[]) => entries.map((e) => e.command);\n\ntype LoopState = {\n queue: EntryQueue;\n activeEntries: QueueEntry[];\n parentId: string | null | undefined;\n resumeRequested: boolean;\n followUpRequested: boolean;\n isReplaying: boolean;\n disposed: boolean;\n abortController: AbortController | null;\n queueVersion: number;\n};\n\nconst useHostLoop = (\n getOptions: () => HostOptions,\n ctl: StatewireHost.StateCtl,\n getAgent: () => unknown,\n) => {\n const [s] = useState(\n (): LoopState => ({\n queue: { queued: [], inTransit: [] },\n activeEntries: [],\n parentId: undefined,\n resumeRequested: false,\n followUpRequested: false,\n isReplaying: false,\n disposed: false,\n abortController: null,\n queueVersion: 0,\n }),\n );\n\n useEffect(() => {\n s.disposed = false;\n return () => {\n s.disposed = true;\n s.followUpRequested = false;\n s.abortController?.abort();\n };\n }, [s]);\n\n const setReplaying = (value: boolean) => {\n if (s.isReplaying === value) return;\n s.isReplaying = value;\n ctl.apply([{ op: \"replace\", path: [\"isReplaying\"], value }]);\n };\n\n const setSending = (value: boolean) => {\n ctl.apply([{ op: \"replace\", path: [\"isSending\"], value }]);\n };\n\n const replaceAgent = (next: unknown) => {\n ctl.apply([{ op: \"replace\", path: [\"agent\"], value: next }]);\n };\n\n const updateState = (updater: (state: unknown) => unknown) => {\n replaceAgent(updater(getAgent()));\n };\n\n // Ops commit one-by-one — an op error leaves the chunk's prefix applied.\n const applyChunkOps = (\n operations: readonly AssistantTransportStateOperation[],\n ) => {\n for (const operation of operations) {\n const op = translateStateOp(getAgent(), operation);\n if (op === undefined) continue;\n ctl.apply([{ ...op, path: [\"agent\", ...op.path] }]);\n }\n };\n\n const setQueue = (next: EntryQueue) => {\n s.queue = next;\n getOptions().queueCell.current = {\n queued: commandsOf(next.queued),\n inTransit: commandsOf(next.inTransit),\n };\n ctl.apply([\n { op: \"replace\", path: [\"queueVersion\"], value: ++s.queueVersion },\n ]);\n };\n\n const takeQueuedIntoTransit = (): QueueEntry[] => {\n const { queued, inTransit } = s.queue;\n if (queued.length === 0) return [];\n setQueue({ queued: [], inTransit: [...inTransit, ...queued] });\n return queued;\n };\n\n const drainQueue = (): EntryQueue => {\n const drained = s.queue;\n setQueue({ queued: [], inTransit: [] });\n return drained;\n };\n\n const buildRequestBody = async (\n o: HostOptions,\n commands: AssistantTransportCommand[],\n runParentId: string | null | undefined,\n ) => {\n const bodyValue = typeof o.body === \"function\" ? await o.body() : o.body;\n const { modelContext, threadId } = o.getRunContext();\n\n const requestBody: Record<string, unknown> = {\n commands,\n state: getAgent(),\n system: modelContext.system,\n tools: modelContext.tools\n ? toToolsJSONSchema(modelContext.tools)\n : undefined,\n threadId,\n ...(runParentId !== undefined && { parentId: runParentId }),\n callSettings: modelContext.callSettings,\n config: modelContext.config,\n // deprecated top-level spread, kept for legacy parity\n ...modelContext.callSettings,\n ...modelContext.config,\n ...(bodyValue ?? {}),\n };\n\n if (!o.prepareSendCommandsRequest) return requestBody;\n return o.prepareSendCommandsRequest(requestBody as SendCommandsRequestBody);\n };\n\n const run = async (signal: AbortSignal) => {\n const o = getOptions();\n const isResume = s.resumeRequested;\n s.resumeRequested = false;\n setReplaying(false);\n s.activeEntries = isResume ? [] : takeQueuedIntoTransit();\n if (s.activeEntries.length === 0 && !isResume && s.parentId === undefined)\n return;\n\n const runParentId = s.parentId;\n s.parentId = undefined;\n try {\n await runRequest(o, isResume, runParentId, signal);\n } catch (error) {\n if (!signal.aborted && s.parentId === undefined) s.parentId = runParentId;\n throw error;\n }\n };\n\n const runRequest = async (\n o: HostOptions,\n isResume: boolean,\n runParentId: string | null | undefined,\n signal: AbortSignal,\n ) => {\n const headers = await createRequestHeaders(o.headers);\n const requestBody = await buildRequestBody(\n o,\n commandsOf(s.activeEntries),\n runParentId,\n );\n\n const response = await fetch(isResume ? o.resumeApi! : o.api, {\n method: \"POST\",\n headers,\n body: JSON.stringify(requestBody),\n signal,\n });\n\n o.onResponse?.(response);\n\n if (!response.ok) {\n throw new Error(`Status ${response.status}: ${await response.text()}`);\n }\n if (!response.body) {\n throw new Error(\"Response body is null\");\n }\n\n const body = await createReplayBoundaryStream(response, setReplaying);\n const strict = !isResume;\n const decoder =\n (o.protocol ?? \"data-stream\") === \"assistant-transport\"\n ? new AssistantTransportDecoder({ strict })\n : new DataStreamDecoder({ strict });\n\n let streamError: string | undefined;\n let delivered = false;\n\n const markDelivered = () => {\n for (const entry of s.activeEntries) entry.execution.ack();\n setQueue({ ...s.queue, inTransit: [] });\n delivered = true;\n };\n\n const chunks = body.pipeThrough(decoder);\n for await (const chunk of asAsyncIterableStream(chunks)) {\n if (chunk.type === \"error\") {\n streamError = chunk.error;\n continue;\n }\n if (chunk.type !== \"update-state\" || chunk.operations.length === 0)\n continue;\n\n applyChunkOps(chunk.operations);\n\n // only after the chunk committed — a failing first chunk must leave\n // the commands in transit for onError (legacy parity)\n if (!delivered) markDelivered();\n }\n\n if (streamError) {\n throw new Error(streamError);\n }\n\n if (!delivered) markDelivered();\n\n // commands that coalesced into a resume run must not starve\n if (isResume && s.queue.queued.length > 0) s.followUpRequested = true;\n };\n\n const resolveActive = () => {\n for (const entry of s.activeEntries.splice(0)) entry.execution.resolve();\n };\n\n const settleCancelled = () => {\n setReplaying(false);\n const { queued, inTransit } = drainQueue();\n resolveActive();\n for (const entry of [...inTransit, ...queued]) entry.execution.resolve();\n getOptions().onCancel?.({\n commands: commandsOf([...inTransit, ...queued]),\n updateState,\n });\n };\n\n const settleFailed = async (error: Error) => {\n setReplaying(false);\n const { queued, inTransit } = drainQueue();\n for (const entry of inTransit) entry.execution.reject(error);\n resolveActive();\n try {\n await getOptions().onError?.(error, {\n commands: commandsOf(inTransit),\n updateState,\n });\n } finally {\n getOptions().onCancel?.({\n commands: commandsOf(queued),\n updateState,\n error,\n });\n for (const entry of queued) entry.execution.resolve();\n }\n };\n\n const startRun = () => {\n s.followUpRequested = false;\n const ac = new AbortController();\n s.abortController = ac;\n setSending(true);\n\n // macrotask: every command admitted this turn coalesces into the take\n setTimeout(async () => {\n try {\n await run(ac.signal);\n resolveActive();\n } catch (error) {\n s.followUpRequested = false;\n // disposed means unmounted mid-run: the abort is ours, no callbacks\n if (!s.disposed) {\n if (ac.signal.aborted) settleCancelled();\n else await settleFailed(error as Error);\n }\n } finally {\n if (s.disposed) {\n s.abortController = null;\n } else {\n getOptions().onFinish?.();\n if (s.followUpRequested) {\n startRun();\n } else {\n s.abortController = null;\n setSending(false);\n }\n }\n }\n }, 0);\n };\n\n const schedule = () => {\n if (s.abortController) {\n s.followUpRequested = true;\n return;\n }\n startRun();\n };\n\n return {\n send: (command: AssistantTransportCommand, opts?: SendOptions) => {\n const [execution, resolvers] = CommandExecution.withResolvers();\n setQueue({\n queued: [...s.queue.queued, { command, execution: resolvers }],\n inTransit: s.queue.inTransit,\n });\n if (opts?.schedule !== false) schedule();\n return execution;\n },\n setParentId: (id: string | null) => {\n s.parentId = id;\n },\n cancel: () => {\n s.resumeRequested = false;\n s.followUpRequested = false;\n s.abortController?.abort();\n },\n resume: () => {\n if (!getOptions().resumeApi)\n throw new Error(\"Must pass resumeApi to options to resume runs\");\n\n s.resumeRequested = true;\n schedule();\n },\n reload: (id: string | null) => {\n s.parentId = id;\n schedule();\n },\n importState: replaceAgent,\n };\n};\n\nconst useAssistantTransportHost = (\n options: HostOptions,\n): Statewire<AssistantTransportHostState, AssistantTransportHostCommands> => {\n const latestOptions = useRef(options);\n latestOptions.current = options;\n\n const [state, ctl] = useStatewireState<AssistantTransportHostState>(() => ({\n agent: options.initialState,\n queueVersion: 0,\n isSending: false,\n isReplaying: false,\n }));\n const emit = useStatewireEmit();\n\n const handlers = useHostLoop(\n () => latestOptions.current,\n ctl,\n () => ctl.snapshot().agent,\n );\n\n const commands = useStatewireCommands(handlers);\n\n return { state, commands, emit };\n};\n\nexport const AssistantTransportHost = resource(useAssistantTransportHost);\n"],"mappings":";;;;;;;;;AA6EA,MAAMuD,cAAcC,YAA0BA,QAAQC,KAAKC,MAAMA,EAAEhB,OAAO;AAc1E,MAAMyB,eACJC,YACAC,KACAE,aACG;CACH,MAAM,CAACC,KAAKtE,gBACQ;EAChB0D,OAAO;GAAEhC,QAAQ,CAAA;GAAIC,WAAW,CAAA;EAAG;EACnCgC,eAAe,CAAA;EACfhB,UAAU4B,KAAAA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B;EACT;EACAR,cAAc4G,OAAsB;GAClChF,EAAE3B,WAAW2G;EACf;EACA1G,cAAc;GACZ0B,EAAEV,kBAAkB;GACpBU,EAAET,oBAAoB;GACtBS,EAAEP,iBAAiBS,MAAM;EAC3B;EACA3B,cAAc;GACZ,IAAI,CAACqB,WAAW,CAAC,CAACgD,WAChB,MAAM,IAAIO,MAAM,+CAA+C;GAEjEnD,EAAEV,kBAAkB;GACpBvC,SAAS;EACX;EACAyB,SAASwG,SAAsB;GAC7BhF,EAAE3B,WAAW2G;GACbjI,SAAS;EACX;EACA0B,aAAagC;CACf;AACF;AAEA,MAAMwE,6BACJC,YAC2E;CAC3E,MAAMC,gBAAgB1J,OAAOyJ,OAAO;CACpCC,cAAc5H,UAAU2H;CAExB,MAAM,CAACxG,OAAOmB,OAAOtD,yBAAsD;EACzEqB,OAAOsH,QAAQE;EACfvH,cAAc;EACdC,WAAW;EACXC,aAAa;CACf,EAAE;CACF,MAAMsH,OAAO/I,iBAAiB;CAU9B,OAAO;EAAEoC;EAAO6C,UAFClF,qBANAsD,kBACTwF,cAAc5H,SACpBsC,WACMA,IAAI0F,SAAS,CAAC,CAAC3H,KAGe0H,CAEtB/D;EAAU8D;CAAK;AACjC;AAEA,MAAaG,yBAAyB7J,SAASsJ,yBAAyB"}
1
+ {"version":3,"file":"host.js","names":["useEffect","useRef","useState","resource","createRequestHeaders","ModelContext","AssistantTransportDecoder","DataStreamDecoder","toToolsJSONSchema","AssistantTransportStateOperation","asAsyncIterableStream","Statewire","useStatewireCommands","useStatewireEmit","useStatewireState","StatewireHost","createReplayBoundaryStream","translateStateOp","AssistantTransportCommand","AssistantTransportOptions","SendCommandsRequestBody","SendOptions","schedule","HostRunContext","modelContext","threadId","HostQueue","queued","inTransit","HostQueueCell","current","HostOptions","getRunContext","queueCell","AssistantTransportHostState","agent","queueVersion","isSending","isReplaying","AssistantTransportHostCommands","send","command","opts","setParentId","parentId","cancel","resume","importState","state","EntrySettlement","ack","resolve","reject","error","QueueEntry","execution","EntryQueue","commandsOf","entries","map","e","LoopState","queue","activeEntries","resumeRequested","followUpRequested","disposed","abortController","AbortController","useHostLoop","getOptions","ctl","StateCtl","getAgent","s","undefined","abort","setReplaying","value","apply","op","path","setSending","replaceAgent","next","updateState","updater","applyChunkOps","operations","operation","setQueue","takeQueuedIntoTransit","length","drainQueue","drained","buildRequestBody","o","commands","runParentId","bodyValue","body","requestBody","Record","system","tools","callSettings","config","prepareSendCommandsRequest","run","signal","AbortSignal","isResume","runRequest","aborted","headers","response","fetch","resumeApi","api","method","JSON","stringify","onResponse","ok","Error","status","text","strict","decoder","protocol","streamError","delivered","markDelivered","entry","chunks","pipeThrough","chunk","type","resolveActive","splice","settleCancelled","onCancel","settleFailed","onError","startRun","ac","setTimeout","onFinish","this","Ctx","promise","Promise","res","rej","id","useAssistantTransportHost","options","latestOptions","initialState","emit","handlers","snapshot","AssistantTransportHost"],"sources":["../src/host.ts"],"sourcesContent":["import { useEffect, useRef, useState } from \"react\";\nimport { resource } from \"@assistant-ui/tap\";\nimport { createRequestHeaders } from \"@assistant-ui/core\";\nimport type { ModelContext } from \"@assistant-ui/core\";\nimport {\n AssistantTransportDecoder,\n DataStreamDecoder,\n toToolsJSONSchema,\n} from \"assistant-stream\";\nimport type { AssistantTransportStateOperation } from \"assistant-stream\";\nimport { asAsyncIterableStream } from \"assistant-stream/utils\";\nimport type { Statewire } from \"statewire\";\nimport {\n useStatewireCommands,\n useStatewireEmit,\n useStatewireState,\n} from \"statewire/host\";\nimport type { StatewireHost } from \"statewire/host\";\nimport { createReplayBoundaryStream } from \"./replayBoundaryStream\";\nimport { translateStateOp } from \"./stateOps\";\nimport type {\n AssistantTransportCommand,\n AssistantTransportOptions,\n SendCommandsRequestBody,\n} from \"./types\";\n\nexport type SendOptions = {\n schedule?: boolean;\n};\n\nexport type HostRunContext = {\n modelContext: ModelContext;\n threadId: string | null;\n};\n\nexport type HostQueue = {\n queued: AssistantTransportCommand[];\n inTransit: AssistantTransportCommand[];\n};\n\n// Statewire state sanitizes values on apply; command objects must keep their\n// identity for converter-side caches, so the host publishes them through this\n// cell and bumps queueVersion in state to signal the change.\nexport type HostQueueCell = { current: HostQueue };\n\nexport type HostOptions = AssistantTransportOptions<unknown> & {\n getRunContext: () => HostRunContext;\n queueCell: HostQueueCell;\n};\n\nexport type AssistantTransportHostState = {\n agent: unknown;\n queueVersion: number;\n isSending: boolean;\n isReplaying: boolean;\n};\n\nexport type AssistantTransportHostCommands = {\n send(command: AssistantTransportCommand, opts?: SendOptions): void;\n setParentId(parentId: string | null): void;\n cancel(): void;\n resume(): void;\n importState(state: unknown): void;\n};\n\ntype EntrySettlement = {\n ack: () => void;\n resolve: () => void;\n reject: (error: unknown) => void;\n};\n\ntype QueueEntry = {\n command: AssistantTransportCommand;\n execution: EntrySettlement;\n};\n\ntype EntryQueue = {\n queued: QueueEntry[];\n inTransit: QueueEntry[];\n};\n\nconst commandsOf = (entries: QueueEntry[]) => entries.map((e) => e.command);\n\ntype LoopState = {\n queue: EntryQueue;\n activeEntries: QueueEntry[];\n parentId: string | null | undefined;\n resumeRequested: boolean;\n followUpRequested: boolean;\n isReplaying: boolean;\n disposed: boolean;\n abortController: AbortController | null;\n queueVersion: number;\n};\n\nconst useHostLoop = (\n getOptions: () => HostOptions,\n ctl: StatewireHost.StateCtl,\n getAgent: () => unknown,\n) => {\n const [s] = useState(\n (): LoopState => ({\n queue: { queued: [], inTransit: [] },\n activeEntries: [],\n parentId: undefined,\n resumeRequested: false,\n followUpRequested: false,\n isReplaying: false,\n disposed: false,\n abortController: null,\n queueVersion: 0,\n }),\n );\n\n useEffect(() => {\n s.disposed = false;\n return () => {\n s.disposed = true;\n s.followUpRequested = false;\n s.abortController?.abort();\n };\n }, [s]);\n\n const setReplaying = (value: boolean) => {\n if (s.isReplaying === value) return;\n s.isReplaying = value;\n ctl.apply([{ op: \"replace\", path: [\"isReplaying\"], value }]);\n };\n\n const setSending = (value: boolean) => {\n ctl.apply([{ op: \"replace\", path: [\"isSending\"], value }]);\n };\n\n const replaceAgent = (next: unknown) => {\n ctl.apply([{ op: \"replace\", path: [\"agent\"], value: next }]);\n };\n\n const updateState = (updater: (state: unknown) => unknown) => {\n replaceAgent(updater(getAgent()));\n };\n\n // Ops commit one-by-one — an op error leaves the chunk's prefix applied.\n const applyChunkOps = (\n operations: readonly AssistantTransportStateOperation[],\n ) => {\n for (const operation of operations) {\n const op = translateStateOp(getAgent(), operation);\n if (op === undefined) continue;\n ctl.apply([{ ...op, path: [\"agent\", ...op.path] }]);\n }\n };\n\n const setQueue = (next: EntryQueue) => {\n s.queue = next;\n getOptions().queueCell.current = {\n queued: commandsOf(next.queued),\n inTransit: commandsOf(next.inTransit),\n };\n ctl.apply([\n { op: \"replace\", path: [\"queueVersion\"], value: ++s.queueVersion },\n ]);\n };\n\n const takeQueuedIntoTransit = (): QueueEntry[] => {\n const { queued, inTransit } = s.queue;\n if (queued.length === 0) return [];\n setQueue({ queued: [], inTransit: [...inTransit, ...queued] });\n return queued;\n };\n\n const drainQueue = (): EntryQueue => {\n const drained = s.queue;\n setQueue({ queued: [], inTransit: [] });\n return drained;\n };\n\n const buildRequestBody = async (\n o: HostOptions,\n commands: AssistantTransportCommand[],\n runParentId: string | null | undefined,\n ) => {\n const bodyValue = typeof o.body === \"function\" ? await o.body() : o.body;\n const { modelContext, threadId } = o.getRunContext();\n\n const requestBody: Record<string, unknown> = {\n commands,\n state: getAgent(),\n system: modelContext.system,\n tools: modelContext.tools\n ? toToolsJSONSchema(modelContext.tools)\n : undefined,\n threadId,\n ...(runParentId !== undefined && { parentId: runParentId }),\n callSettings: modelContext.callSettings,\n config: modelContext.config,\n // deprecated top-level spread, kept for legacy parity\n ...modelContext.callSettings,\n ...modelContext.config,\n ...(bodyValue ?? {}),\n };\n\n if (!o.prepareSendCommandsRequest) return requestBody;\n return o.prepareSendCommandsRequest(requestBody as SendCommandsRequestBody);\n };\n\n const run = async (signal: AbortSignal) => {\n const o = getOptions();\n const isResume = s.resumeRequested;\n s.resumeRequested = false;\n setReplaying(false);\n s.activeEntries = isResume ? [] : takeQueuedIntoTransit();\n if (s.activeEntries.length === 0 && !isResume && s.parentId === undefined)\n return;\n\n const runParentId = s.parentId;\n s.parentId = undefined;\n try {\n await runRequest(o, isResume, runParentId, signal);\n } catch (error) {\n if (!signal.aborted && s.parentId === undefined) s.parentId = runParentId;\n throw error;\n }\n };\n\n const runRequest = async (\n o: HostOptions,\n isResume: boolean,\n runParentId: string | null | undefined,\n signal: AbortSignal,\n ) => {\n const headers = await createRequestHeaders(o.headers);\n const requestBody = await buildRequestBody(\n o,\n commandsOf(s.activeEntries),\n runParentId,\n );\n\n const response = await fetch(isResume ? o.resumeApi! : o.api, {\n method: \"POST\",\n headers,\n body: JSON.stringify(requestBody),\n signal,\n });\n\n o.onResponse?.(response);\n\n if (!response.ok) {\n throw new Error(`Status ${response.status}: ${await response.text()}`);\n }\n if (!response.body) {\n throw new Error(\"Response body is null\");\n }\n\n const body = await createReplayBoundaryStream(response, setReplaying);\n const strict = !isResume;\n const decoder =\n (o.protocol ?? \"data-stream\") === \"assistant-transport\"\n ? new AssistantTransportDecoder({ strict })\n : new DataStreamDecoder({ strict });\n\n let streamError: string | undefined;\n let delivered = false;\n\n const markDelivered = () => {\n for (const entry of s.activeEntries) entry.execution.ack();\n setQueue({ ...s.queue, inTransit: [] });\n delivered = true;\n };\n\n const chunks = body.pipeThrough(decoder);\n for await (const chunk of asAsyncIterableStream(chunks)) {\n if (chunk.type === \"error\") {\n streamError = chunk.error;\n continue;\n }\n if (chunk.type !== \"update-state\" || chunk.operations.length === 0)\n continue;\n\n applyChunkOps(chunk.operations);\n\n // only after the chunk committed — a failing first chunk must leave\n // the commands in transit for onError (legacy parity)\n if (!delivered) markDelivered();\n }\n\n if (streamError) {\n throw new Error(streamError);\n }\n\n if (!delivered) markDelivered();\n\n // commands that coalesced into a resume run must not starve\n if (isResume && s.queue.queued.length > 0) s.followUpRequested = true;\n };\n\n const resolveActive = () => {\n for (const entry of s.activeEntries.splice(0)) entry.execution.resolve();\n };\n\n const settleCancelled = () => {\n setReplaying(false);\n const { queued, inTransit } = drainQueue();\n resolveActive();\n for (const entry of [...inTransit, ...queued]) entry.execution.resolve();\n getOptions().onCancel?.({\n commands: commandsOf([...inTransit, ...queued]),\n updateState,\n });\n };\n\n const settleFailed = async (error: Error) => {\n setReplaying(false);\n const { queued, inTransit } = drainQueue();\n for (const entry of inTransit) entry.execution.reject(error);\n resolveActive();\n try {\n await getOptions().onError?.(error, {\n commands: commandsOf(inTransit),\n updateState,\n });\n } finally {\n getOptions().onCancel?.({\n commands: commandsOf(queued),\n updateState,\n error,\n });\n for (const entry of queued) entry.execution.resolve();\n }\n };\n\n const startRun = () => {\n s.followUpRequested = false;\n const ac = new AbortController();\n s.abortController = ac;\n setSending(true);\n\n // macrotask: every command admitted this turn coalesces into the take\n setTimeout(async () => {\n try {\n await run(ac.signal);\n resolveActive();\n } catch (error) {\n s.followUpRequested = false;\n // disposed means unmounted mid-run: the abort is ours, no callbacks\n if (!s.disposed) {\n if (ac.signal.aborted) settleCancelled();\n else await settleFailed(error as Error);\n }\n } finally {\n if (s.disposed) {\n s.abortController = null;\n } else {\n getOptions().onFinish?.();\n if (s.followUpRequested) {\n startRun();\n } else {\n s.abortController = null;\n setSending(false);\n }\n }\n }\n }, 0);\n };\n\n const schedule = () => {\n if (s.abortController) {\n s.followUpRequested = true;\n return;\n }\n startRun();\n };\n\n return {\n send: function (\n this: StatewireHost.Ctx,\n command: AssistantTransportCommand,\n opts?: SendOptions,\n ) {\n let resolve!: () => void;\n let reject!: (error: unknown) => void;\n const promise = new Promise<void>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n setQueue({\n queued: [\n ...s.queue.queued,\n { command, execution: { ack: this.ack, resolve, reject } },\n ],\n inTransit: s.queue.inTransit,\n });\n if (opts?.schedule !== false) schedule();\n return promise;\n },\n setParentId: (id: string | null) => {\n s.parentId = id;\n },\n cancel: () => {\n s.resumeRequested = false;\n s.followUpRequested = false;\n s.abortController?.abort();\n },\n resume: () => {\n if (!getOptions().resumeApi)\n throw new Error(\"Must pass resumeApi to options to resume runs\");\n\n s.resumeRequested = true;\n schedule();\n },\n importState: replaceAgent,\n };\n};\n\nconst useAssistantTransportHost = (\n options: HostOptions,\n): Statewire<AssistantTransportHostState, AssistantTransportHostCommands> => {\n const latestOptions = useRef(options);\n latestOptions.current = options;\n\n const [state, ctl] = useStatewireState<AssistantTransportHostState>(() => ({\n agent: options.initialState,\n queueVersion: 0,\n isSending: false,\n isReplaying: false,\n }));\n const emit = useStatewireEmit();\n\n const handlers = useHostLoop(\n () => latestOptions.current,\n ctl,\n () => ctl.snapshot().agent,\n );\n\n const commands = useStatewireCommands(handlers);\n\n return { state, commands, emit };\n};\n\nexport const AssistantTransportHost = resource(useAssistantTransportHost);\n"],"mappings":";;;;;;;;;AAiFA,MAAMyD,cAAcC,YAA0BA,QAAQC,KAAKC,MAAMA,EAAEnB,OAAO;AAc1E,MAAM4B,eACJC,YACAC,KACAE,aACG;CACH,MAAM,CAACC,KAAKxE,gBACQ;EAChB4D,OAAO;GAAEnC,QAAQ,CAAA;GAAIC,WAAW,CAAA;EAAG;EACnCmC,eAAe,CAAA;EACfnB,UAAU+B,KAAAA;EACVX,iBAAiB;EACjBC,mBAAmB;EACnB3B,aAAa;EACb4B,UAAU;EACVC,iBAAiB;EACjB/B,cAAc;CAChB,EACF;CAEApC,gBAAgB;EACd0E,EAAER,WAAW;EACb,aAAa;GACXQ,EAAER,WAAW;GACbQ,EAAET,oBAAoB;GACtBS,EAAEP,iBAAiBS,MAAM;EAC3B;CACF,GAAG,CAACF,CAAC,CAAC;CAEN,MAAMG,gBAAgBC,UAAmB;EACvC,IAAIJ,EAAEpC,gBAAgBwC,OAAO;EAC7BJ,EAAEpC,cAAcwC;EAChBP,IAAIQ,MAAM,CAAC;GAAEC,IAAI;GAAWC,MAAM,CAAC,aAAa;GAAGH;EAAM,CAAC,CAAC;CAC7D;C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gBAAgB5J,OAAO2J,OAAO;CACpCC,cAAc/H,UAAU8H;CAExB,MAAM,CAAC5G,OAAOuB,OAAOzD,yBAAsD;EACzEqB,OAAOyH,QAAQE;EACf1H,cAAc;EACdC,WAAW;EACXC,aAAa;CACf,EAAE;CACF,MAAMyH,OAAOlJ,iBAAiB;CAE9B,MAAMmJ,WAAW3F,kBACTwF,cAAc/H,SACpByC,WACMA,IAAI0F,SAAS,CAAC,CAAC9H,KACvB;CAIA,OAAO;EAAEa;EAAOiD,UAFCrF,qBAAqBoJ,QAEtB/D;EAAU8D;CAAK;AACjC;AAEA,MAAaG,yBAAyB/J,SAASwJ,yBAAyB"}
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { AssistantMessage, AssistantTransportCommand, AssistantTransportConnectionMetadata, AssistantTransportOptions, AssistantTransportProtocol, AssistantTransportState, AssistantTransportStateConverter, HeadersValue, ImagePart, MessageAddCommand, SendCommandsRequestBody, TextPart, ToolResultAddCommand, UserMessage, UserMessagePart } from "./types.js";
1
+ import { AddMessageCommand, AddToolResultCommand, AssistantMessage, AssistantTransportCommand, AssistantTransportConnectionMetadata, AssistantTransportOptions, AssistantTransportProtocol, AssistantTransportState, AssistantTransportStateConverter, CustomInputRequest, FilePart, HeadersValue, ImagePart, InputRequest, InputRequestState, InputResponse, RunCommand, RunContinueCommand, RunDequeueCommand, RunEditCommand, RunEnqueueCommand, RunInputCommand, RunPlacement, RunQueueItem, RunReloadCommand, RunSteerCommand, RunUserMessage, SendCommandsRequestBody, TextPart, ToolApprovalInputRequest, ToolApprovalInputResponse, ToolCallInputRequest, ToolCallInputResponse, UserMessage, UserMessagePart } from "./types.js";
2
2
  import { AssistantTransportThread } from "./AssistantTransportThread.js";
3
3
  import { StatewireThread } from "./StatewireThread.js";
4
4
  import { useAssistantTransportSendCommand, useAssistantTransportState } from "./hooks.js";
@@ -10,13 +10,33 @@ declare namespace AssistantTransportThread {
10
10
  type State = AssistantTransportState;
11
11
  type ConnectionMetadata = AssistantTransportConnectionMetadata;
12
12
  type StateConverter<T> = AssistantTransportStateConverter<T>;
13
- type MessageAddCommand = MessageAddCommand;
14
- type ToolResultAddCommand = ToolResultAddCommand;
13
+ type AddMessageCommand = AddMessageCommand;
14
+ type AddToolResultCommand = AddToolResultCommand;
15
+ type RunCommand = RunCommand;
16
+ type RunEnqueueCommand = RunEnqueueCommand;
17
+ type RunSteerCommand = RunSteerCommand;
18
+ type RunDequeueCommand = RunDequeueCommand;
19
+ type RunEditCommand = RunEditCommand;
20
+ type RunContinueCommand = RunContinueCommand;
21
+ type RunReloadCommand = RunReloadCommand;
22
+ type RunInputCommand = RunInputCommand;
23
+ type InputRequest = InputRequest;
24
+ type ToolCallInputRequest = ToolCallInputRequest;
25
+ type ToolApprovalInputRequest = ToolApprovalInputRequest;
26
+ type CustomInputRequest = CustomInputRequest;
27
+ type InputRequestState = InputRequestState;
28
+ type InputResponse = InputResponse;
29
+ type ToolCallInputResponse = ToolCallInputResponse;
30
+ type ToolApprovalInputResponse = ToolApprovalInputResponse;
31
+ type RunUserMessage = RunUserMessage;
32
+ type RunQueueItem = RunQueueItem;
33
+ type RunPlacement = RunPlacement;
15
34
  type SendCommandsRequestBody = SendCommandsRequestBody;
16
35
  type UserMessage = UserMessage;
17
36
  type AssistantMessage = AssistantMessage;
18
37
  type UserMessagePart = UserMessagePart;
19
38
  type TextPart = TextPart;
39
+ type FilePart = FilePart;
20
40
  type ImagePart = ImagePart;
21
41
  type HeadersValue = HeadersValue;
22
42
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;kBAUiB;OACH,QAAQ,KAAK,0BAAgC;OAC7C,UAAU;OACV,WAAW;OACX,QAAQ;OACR,qBAAqB;OACrB,eAAe,KAAK,iCAAuC;OAC3D,oBAAoB;OACpB,uBAAuB;OACvB,0BAA0B;OAC1B,cAAc;OACd,mBAAmB;OACnB,kBAAkB;OAClB,WAAW;OACX,YAAY;OACZ,eAAe"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;kBAUiB;OACH,QAAQ,KAAK,0BAAgC;OAC7C,UAAU;OACV,WAAW;OACX,QAAQ;OACR,qBAAqB;OACrB,eAAe,KAAK,iCAAuC;OAC3D,oBAAoB;OACpB,uBAAuB;OACvB,aAAa;OACb,oBAAoB;OACpB,kBAAkB;OAClB,oBAAoB;OACpB,iBAAiB;OACjB,qBAAqB;OACrB,mBAAmB;OACnB,kBAAkB;OAClB,eAAe;OACf,uBAAuB;OACvB,2BAA2B;OAC3B,qBAAqB;OACrB,oBAAoB;OACpB,gBAAgB;OAChB,wBAAwB;OACxB,4BAA4B;OAC5B,iBAAiB;OACjB,eAAe;OACf,eAAe;OACf,0BAA0B;OAC1B,cAAc;OACd,mBAAmB;OACnB,kBAAkB;OAClB,WAAW;OACX,WAAW;OACX,YAAY;OACZ,eAAe"}
@@ -0,0 +1,14 @@
1
+ import { InputRequestState, RunInputCommand } from "./types.js";
2
+ import { RespondToToolApprovalOptions } from "@assistant-ui/core";
3
+ import { ReadonlyJSONValue } from "assistant-stream/utils";
4
+ //#region src/inputRequests.d.ts
5
+ declare const resolveToolResultInput: (inputRequests: readonly InputRequestState[], options: {
6
+ toolCallId: string;
7
+ result: ReadonlyJSONValue;
8
+ isError: boolean;
9
+ artifact?: ReadonlyJSONValue | undefined;
10
+ }) => RunInputCommand | undefined;
11
+ declare const resolveToolApprovalInput: (inputRequests: readonly InputRequestState[], options: RespondToToolApprovalOptions) => RunInputCommand;
12
+ //#endregion
13
+ export { resolveToolApprovalInput, resolveToolResultInput };
14
+ //# sourceMappingURL=inputRequests.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"inputRequests.d.ts","names":[],"sources":["../src/inputRequests.ts"],"mappings":";;;;cAWa,yBACX,wBAAwB,qBACxB;EACE;EACA,QAAQ;EACR;EACA,WAAW;MAEZ;cAiBU,2BACX,wBAAwB,qBACxB,SAAS,iCACR"}
@@ -0,0 +1,35 @@
1
+ //#region src/inputRequests.ts
2
+ const assertUnanswered = (request) => {
3
+ if (request.response !== null) throw new Error(`statewire: input request "${request.id}" is already answered`);
4
+ };
5
+ const resolveToolResultInput = (inputRequests, options) => {
6
+ const request = inputRequests.find((r) => r.type === "tool-call" && r.toolCallId === options.toolCallId);
7
+ if (request === void 0) return void 0;
8
+ assertUnanswered(request);
9
+ return {
10
+ type: "run/input",
11
+ requestId: request.id,
12
+ response: {
13
+ output: options.result,
14
+ ...options.isError && { isError: true },
15
+ ...options.artifact !== void 0 && { artifact: options.artifact }
16
+ }
17
+ };
18
+ };
19
+ const resolveToolApprovalInput = (inputRequests, options) => {
20
+ const request = inputRequests.find((r) => r.type === "tool-approval" && r.id === options.approvalId);
21
+ if (request === void 0) throw new Error(`statewire: no tool-approval input request "${options.approvalId}"`);
22
+ assertUnanswered(request);
23
+ return {
24
+ type: "run/input",
25
+ requestId: request.id,
26
+ response: {
27
+ decision: options.approved ? "approve" : "reject",
28
+ ...options.reason !== void 0 && { message: options.reason }
29
+ }
30
+ };
31
+ };
32
+ //#endregion
33
+ export { resolveToolApprovalInput, resolveToolResultInput };
34
+
35
+ //# sourceMappingURL=inputRequests.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"inputRequests.js","names":["RespondToToolApprovalOptions","ReadonlyJSONValue","InputRequestState","RunInputCommand","assertUnanswered","request","response","Error","id","resolveToolResultInput","inputRequests","options","toolCallId","result","isError","artifact","find","r","type","undefined","requestId","output","resolveToolApprovalInput","approvalId","decision","approved","reason","message"],"sources":["../src/inputRequests.ts"],"sourcesContent":["import type { RespondToToolApprovalOptions } from \"@assistant-ui/core\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport type { InputRequestState, RunInputCommand } from \"./types\";\n\nconst assertUnanswered = (request: InputRequestState) => {\n if (request.response !== null)\n throw new Error(\n `statewire: input request \"${request.id}\" is already answered`,\n );\n};\n\nexport const resolveToolResultInput = (\n inputRequests: readonly InputRequestState[],\n options: {\n toolCallId: string;\n result: ReadonlyJSONValue;\n isError: boolean;\n artifact?: ReadonlyJSONValue | undefined;\n },\n): RunInputCommand | undefined => {\n const request = inputRequests.find(\n (r) => r.type === \"tool-call\" && r.toolCallId === options.toolCallId,\n );\n if (request === undefined) return undefined;\n assertUnanswered(request);\n return {\n type: \"run/input\",\n requestId: request.id,\n response: {\n output: options.result,\n ...(options.isError && { isError: true }),\n ...(options.artifact !== undefined && { artifact: options.artifact }),\n },\n };\n};\n\nexport const resolveToolApprovalInput = (\n inputRequests: readonly InputRequestState[],\n options: RespondToToolApprovalOptions,\n): RunInputCommand => {\n const request = inputRequests.find(\n (r) => r.type === \"tool-approval\" && r.id === options.approvalId,\n );\n if (request === undefined)\n throw new Error(\n `statewire: no tool-approval input request \"${options.approvalId}\"`,\n );\n assertUnanswered(request);\n return {\n type: \"run/input\",\n requestId: request.id,\n response: {\n decision: options.approved ? \"approve\" : \"reject\",\n ...(options.reason !== undefined && { message: options.reason }),\n },\n };\n};\n"],"mappings":";AAIA,MAAMI,oBAAoBC,YAA+B;CACvD,IAAIA,QAAQC,aAAa,MACvB,MAAM,IAAIC,MACR,6BAA6BF,QAAQG,GAAE,sBACzC;AACJ;AAEA,MAAaC,0BACXC,eACAC,YAMgC;CAChC,MAAMN,UAAUK,cAAcM,MAC3BC,MAAMA,EAAEC,SAAS,eAAeD,EAAEL,eAAeD,QAAQC,UAC5D;CACA,IAAIP,YAAYc,KAAAA,GAAW,OAAOA,KAAAA;CAClCf,iBAAiBC,OAAO;CACxB,OAAO;EACLa,MAAM;EACNE,WAAWf,QAAQG;EACnBF,UAAU;GACRe,QAAQV,QAAQE;GAChB,GAAIF,QAAQG,WAAW,EAAEA,SAAS,KAAK;GACvC,GAAIH,QAAQI,aAAaI,KAAAA,KAAa,EAAEJ,UAAUJ,QAAQI,SAAS;EACrE;CACF;AACF;AAEA,MAAaO,4BACXZ,eACAC,YACoB;CACpB,MAAMN,UAAUK,cAAcM,MAC3BC,MAAMA,EAAEC,SAAS,mBAAmBD,EAAET,OAAOG,QAAQY,UACxD;CACA,IAAIlB,YAAYc,KAAAA,GACd,MAAM,IAAIZ,MACR,8CAA8CI,QAAQY,WAAU,EAClE;CACFnB,iBAAiBC,OAAO;CACxB,OAAO;EACLa,MAAM;EACNE,WAAWf,QAAQG;EACnBF,UAAU;GACRkB,UAAUb,QAAQc,WAAW,YAAY;GACzC,GAAId,QAAQe,WAAWP,KAAAA,KAAa,EAAEQ,SAAShB,QAAQe,OAAO;EAChE;CACF;AACF"}
@@ -0,0 +1,22 @@
1
+ import { RunCommand, RunQueueItem, RunReloadCommand, RunUserMessage, TextPart } from "./types.js";
2
+ import { AppendMessage, ExternalThreadQueueAdapter } from "@assistant-ui/core";
3
+ //#region src/runCommands.d.ts
4
+ declare const toWireMessage: (message: AppendMessage, id: string) => RunUserMessage;
5
+ declare const toQueueItemState: (item: RunQueueItem) => {
6
+ id: string;
7
+ prompt: string;
8
+ parts: (TextPart | {
9
+ filename?: string;
10
+ type: "file";
11
+ data: string;
12
+ mimeType: string;
13
+ })[];
14
+ };
15
+ declare const createRunQueueAdapter: (queueItems: readonly RunQueueItem[], steerQueueItems: readonly RunQueueItem[] | undefined, dispatch: (command: RunCommand) => void) => ExternalThreadQueueAdapter;
16
+ declare const resolveReloadCommand: (messages: readonly {
17
+ id: string;
18
+ role: string;
19
+ }[], parentId: string | null) => RunReloadCommand;
20
+ //#endregion
21
+ export { createRunQueueAdapter, resolveReloadCommand, toQueueItemState, toWireMessage };
22
+ //# sourceMappingURL=runCommands.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runCommands.d.ts","names":[],"sources":["../src/runCommands.ts"],"mappings":";;;cAca,gBACX,SAAS,eACT,eACC;cAqCU,mBAAoB,MAAM;;;UAAA;;;;;;;cA0B1B,wBACX,qBAAqB,gBACrB,0BAA0B,4BAC1B,WAAW,SAAS,wBACnB;cA6CU,uBACX;EAAqB;EAAY;KACjC,4BACC"}
@@ -0,0 +1,105 @@
1
+ //#region src/runCommands.ts
2
+ const toWireMessage = (message, id) => {
3
+ if (message.role !== "user") throw new Error("statewire: only user messages are supported");
4
+ const files = [];
5
+ const texts = [];
6
+ const source = [...message.content, ...message.attachments?.flatMap((a) => a.content) ?? []];
7
+ for (const part of source) if (part.type === "text") texts.push(part.text);
8
+ else if (part.type === "image") files.push({
9
+ type: "file",
10
+ mediaType: "image/*",
11
+ url: part.image
12
+ });
13
+ else if (part.type === "file") files.push({
14
+ type: "file",
15
+ mediaType: part.mimeType,
16
+ url: part.data,
17
+ ...part.filename !== void 0 && { filename: part.filename }
18
+ });
19
+ else throw new Error(`statewire: unsupported message part "${part.type}"`);
20
+ const parts = [...files, ...texts.length > 0 ? [{
21
+ type: "text",
22
+ text: texts.join("\n\n")
23
+ }] : []];
24
+ if (parts.length === 0) throw new Error("statewire: cannot send an empty message");
25
+ return {
26
+ id,
27
+ role: "user",
28
+ parts
29
+ };
30
+ };
31
+ const toQueueItemState = (item) => ({
32
+ id: item.id,
33
+ prompt: item.parts.flatMap((part) => part.type === "text" ? [part.text] : []).join("\n\n"),
34
+ parts: item.parts.map((part) => part.type === "text" ? part : {
35
+ type: "file",
36
+ data: part.url,
37
+ mimeType: part.mediaType,
38
+ ...part.filename !== void 0 && { filename: part.filename }
39
+ })
40
+ });
41
+ const placementFields = (placement) => ({
42
+ ...placement.insertAfter !== void 0 && { insertAfter: placement.insertAfter },
43
+ ...placement.insertBefore !== void 0 && { insertBefore: placement.insertBefore }
44
+ });
45
+ const createRunQueueAdapter = (queueItems, steerQueueItems, dispatch) => {
46
+ const laneOf = (queueItemId) => {
47
+ if (steerQueueItems?.some((item) => item.id === queueItemId)) return "steer";
48
+ if (queueItems.some((item) => item.id === queueItemId)) return "queue";
49
+ throw new Error(`statewire: unknown queue item "${queueItemId}"`);
50
+ };
51
+ return {
52
+ items: queueItems.map(toQueueItemState),
53
+ steerItems: (steerQueueItems ?? []).map(toQueueItemState),
54
+ enqueue: (message) => dispatch({
55
+ type: "run/enqueue",
56
+ message: toWireMessage(message, crypto.randomUUID())
57
+ }),
58
+ steer: (message) => dispatch({
59
+ type: "run/steer",
60
+ message: toWireMessage(message, crypto.randomUUID())
61
+ }),
62
+ move: (queueItemId, placement) => {
63
+ const lane = placement.lane ?? laneOf(queueItemId);
64
+ const fields = {
65
+ messageId: queueItemId,
66
+ ...placementFields(placement)
67
+ };
68
+ dispatch(lane === "steer" ? {
69
+ type: "run/steer",
70
+ ...fields
71
+ } : {
72
+ type: "run/enqueue",
73
+ ...fields
74
+ });
75
+ },
76
+ edit: (queueItemId, message) => {
77
+ const wireMessage = toWireMessage(message, queueItemId);
78
+ dispatch(laneOf(queueItemId) === "steer" ? {
79
+ type: "run/steer",
80
+ message: wireMessage
81
+ } : {
82
+ type: "run/enqueue",
83
+ message: wireMessage
84
+ });
85
+ },
86
+ remove: (queueItemId) => dispatch({
87
+ type: "run/dequeue",
88
+ messageId: queueItemId
89
+ })
90
+ };
91
+ };
92
+ const resolveReloadCommand = (messages, parentId) => {
93
+ const index = parentId === null ? 0 : messages.findIndex((message) => message.id === parentId) + 1;
94
+ if (parentId !== null && index === 0) throw new Error(`statewire: run/reload parent "${parentId}" is unknown`);
95
+ const target = messages[index];
96
+ if (target === void 0 || target.role !== "assistant") throw new Error("statewire: run/reload requires an assistant message to regenerate");
97
+ return {
98
+ type: "run/reload",
99
+ sourceId: target.id
100
+ };
101
+ };
102
+ //#endregion
103
+ export { createRunQueueAdapter, resolveReloadCommand, toQueueItemState, toWireMessage };
104
+
105
+ //# sourceMappingURL=runCommands.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runCommands.js","names":["AppendMessage","ExternalThreadQueueAdapter","QueuePlacement","FilePart","RunCommand","RunQueueItem","RunReloadCommand","RunUserMessage","TextPart","toWireMessage","message","id","role","Error","files","texts","source","content","attachments","flatMap","a","part","type","push","text","mediaType","url","image","mimeType","data","filename","undefined","parts","length","const","join","toQueueItemState","item","prompt","map","placementFields","placement","insertAfter","insertBefore","createRunQueueAdapter","queueItems","steerQueueItems","dispatch","command","laneOf","queueItemId","some","items","steerItems","enqueue","crypto","randomUUID","steer","move","lane","fields","messageId","edit","wireMessage","remove","resolveReloadCommand","messages","parentId","index","findIndex","target","sourceId"],"sources":["../src/runCommands.ts"],"sourcesContent":["import type {\n AppendMessage,\n ExternalThreadQueueAdapter,\n QueuePlacement,\n} from \"@assistant-ui/core\";\nimport type {\n FilePart,\n RunCommand,\n RunQueueItem,\n RunReloadCommand,\n RunUserMessage,\n TextPart,\n} from \"./types\";\n\nexport const toWireMessage = (\n message: AppendMessage,\n id: string,\n): RunUserMessage => {\n if (message.role !== \"user\")\n throw new Error(\"statewire: only user messages are supported\");\n const files: FilePart[] = [];\n const texts: string[] = [];\n const source = [\n ...message.content,\n ...(message.attachments?.flatMap((a) => a.content) ?? []),\n ];\n for (const part of source) {\n if (part.type === \"text\") {\n texts.push(part.text);\n } else if (part.type === \"image\") {\n files.push({ type: \"file\", mediaType: \"image/*\", url: part.image });\n } else if (part.type === \"file\") {\n files.push({\n type: \"file\",\n mediaType: part.mimeType,\n url: part.data,\n ...(part.filename !== undefined && { filename: part.filename }),\n });\n } else {\n throw new Error(`statewire: unsupported message part \"${part.type}\"`);\n }\n }\n // default-safe against host capabilities: files first, one merged text part\n const parts: (TextPart | FilePart)[] = [\n ...files,\n ...(texts.length > 0\n ? [{ type: \"text\" as const, text: texts.join(\"\\n\\n\") }]\n : []),\n ];\n if (parts.length === 0)\n throw new Error(\"statewire: cannot send an empty message\");\n return { id, role: \"user\", parts };\n};\n\nexport const toQueueItemState = (item: RunQueueItem) => ({\n id: item.id,\n prompt: item.parts\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\"),\n parts: item.parts.map((part) =>\n part.type === \"text\"\n ? part\n : {\n type: \"file\" as const,\n data: part.url,\n mimeType: part.mediaType,\n ...(part.filename !== undefined && { filename: part.filename }),\n },\n ),\n});\n\nconst placementFields = (placement: QueuePlacement) => ({\n ...(placement.insertAfter !== undefined && {\n insertAfter: placement.insertAfter,\n }),\n ...(placement.insertBefore !== undefined && {\n insertBefore: placement.insertBefore,\n }),\n});\n\nexport const createRunQueueAdapter = (\n queueItems: readonly RunQueueItem[],\n steerQueueItems: readonly RunQueueItem[] | undefined,\n dispatch: (command: RunCommand) => void,\n): ExternalThreadQueueAdapter => {\n const laneOf = (queueItemId: string): \"queue\" | \"steer\" => {\n if (steerQueueItems?.some((item) => item.id === queueItemId))\n return \"steer\";\n if (queueItems.some((item) => item.id === queueItemId)) return \"queue\";\n throw new Error(`statewire: unknown queue item \"${queueItemId}\"`);\n };\n return {\n items: queueItems.map(toQueueItemState),\n steerItems: (steerQueueItems ?? []).map(toQueueItemState),\n enqueue: (message) =>\n dispatch({\n type: \"run/enqueue\",\n message: toWireMessage(message, crypto.randomUUID()),\n }),\n steer: (message) =>\n dispatch({\n type: \"run/steer\",\n message: toWireMessage(message, crypto.randomUUID()),\n }),\n move: (queueItemId, placement) => {\n const lane = placement.lane ?? laneOf(queueItemId);\n const fields = {\n messageId: queueItemId,\n ...placementFields(placement),\n };\n dispatch(\n lane === \"steer\"\n ? { type: \"run/steer\", ...fields }\n : { type: \"run/enqueue\", ...fields },\n );\n },\n edit: (queueItemId, message) => {\n const wireMessage = toWireMessage(message, queueItemId);\n dispatch(\n laneOf(queueItemId) === \"steer\"\n ? { type: \"run/steer\", message: wireMessage }\n : { type: \"run/enqueue\", message: wireMessage },\n );\n },\n remove: (queueItemId) =>\n dispatch({ type: \"run/dequeue\", messageId: queueItemId }),\n };\n};\n\nexport const resolveReloadCommand = (\n messages: readonly { id: string; role: string }[],\n parentId: string | null,\n): RunReloadCommand => {\n const index =\n parentId === null\n ? 0\n : messages.findIndex((message) => message.id === parentId) + 1;\n if (parentId !== null && index === 0)\n throw new Error(`statewire: run/reload parent \"${parentId}\" is unknown`);\n const target = messages[index];\n if (target === undefined || target.role !== \"assistant\")\n throw new Error(\n \"statewire: run/reload requires an assistant message to regenerate\",\n );\n return { type: \"run/reload\", sourceId: target.id };\n};\n"],"mappings":";AAcA,MAAaS,iBACXC,SACAC,OACmB;CACnB,IAAID,QAAQE,SAAS,QACnB,MAAM,IAAIC,MAAM,6CAA6C;CAC/D,MAAMC,QAAoB,CAAA;CAC1B,MAAMC,QAAkB,CAAA;CACxB,MAAMC,SAAS,CACb,GAAGN,QAAQO,SACX,GAAIP,QAAQQ,aAAaC,SAASC,MAAMA,EAAEH,OAAO,KAAK,CAAA,CAAG;CAE3D,KAAK,MAAMI,QAAQL,QACjB,IAAIK,KAAKC,SAAS,QAChBP,MAAMQ,KAAKF,KAAKG,IAAI;MACf,IAAIH,KAAKC,SAAS,SACvBR,MAAMS,KAAK;EAAED,MAAM;EAAQG,WAAW;EAAWC,KAAKL,KAAKM;CAAM,CAAC;MAC7D,IAAIN,KAAKC,SAAS,QACvBR,MAAMS,KAAK;EACTD,MAAM;EACNG,WAAWJ,KAAKO;EAChBF,KAAKL,KAAKQ;EACV,GAAIR,KAAKS,aAAaC,KAAAA,KAAa,EAAED,UAAUT,KAAKS,SAAS;CAC/D,CAAC;MAED,MAAM,IAAIjB,MAAM,wCAAwCQ,KAAKC,KAAI,EAAG;CAIxE,MAAMU,QAAiC,CACrC,GAAGlB,OACH,GAAIC,MAAMkB,SAAS,IACf,CAAC;EAAEX,MAAM;EAAiBE,MAAMT,MAAMoB,KAAK,MAAM;CAAE,CAAC,IACpD,CAAA,CAAG;CAET,IAAIH,MAAMC,WAAW,GACnB,MAAM,IAAIpB,MAAM,yCAAyC;CAC3D,OAAO;EAAEF;EAAIC,MAAM;EAAQoB;CAAM;AACnC;AAEA,MAAaI,oBAAoBC,UAAwB;CACvD1B,IAAI0B,KAAK1B;CACT2B,QAAQD,KAAKL,MACVb,SAASE,SAAUA,KAAKC,SAAS,SAAS,CAACD,KAAKG,IAAI,IAAI,CAAA,CAAG,CAAC,CAC5DW,KAAK,MAAM;CACdH,OAAOK,KAAK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