@assistant-ui/react-statewire 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/AssistantTransportThread.d.ts +3 -2
- package/dist/AssistantTransportThread.d.ts.map +1 -1
- package/dist/AssistantTransportThread.js +57 -8
- package/dist/AssistantTransportThread.js.map +1 -1
- package/dist/StatewireThread.d.ts +86 -2
- package/dist/StatewireThread.d.ts.map +1 -1
- package/dist/StatewireThread.js +140 -9
- package/dist/StatewireThread.js.map +1 -1
- package/dist/host.d.ts +2 -1
- package/dist/host.d.ts.map +1 -1
- package/dist/host.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/types.d.ts +17 -6
- package/dist/types.d.ts.map +1 -1
- package/package.json +4 -4
- package/src/AssistantTransportThread.ts +93 -12
- package/src/StatewireThread.test.tsx +511 -13
- package/src/StatewireThread.ts +306 -14
- package/src/__tests__/testHelpers.tsx +1 -1
- package/src/athena.e2e.test.tsx +17 -17
- package/src/host.ts +1 -6
- package/src/index.ts +2 -2
- package/src/legacy-diff.test.tsx +25 -8
- package/src/transport.test.tsx +155 -16
- package/src/types.ts +17 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","AppendMessage","AttachmentAdapter","ModelContext","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","convertAppendMessageToCommand","symbolAssistantTransportExtras","AssistantTransportExtras","AssistantTransportCommand","AnyCommands","Record","args","ambientContextOf","context","system","undefined","tools","Parameters","callSettings","config","useStatewireThread","options","StatewireThread","Options","latest","current","pending","setPending","retire","command","prev","includes","filter","c","state","transportState","commands","setContext","transport","onCommandChange","update","status","params","attached","initialState","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","catch","error","Error","onError","subscribe","dispatch","type","converter","metadata","ConnectionMetadata","pendingCommands","isSending","length","converted","extras","sendCommand","handleAppend","message","messages","isRunning","isLoading","attachmentAdapter","adapters","attachments","onNew","capabilities","edit","onEdit","onCancel","T","Transport","State","StateConverter","connectionMetadata","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 ModelContext,\n ThreadMessage,\n} from \"@assistant-ui/core\";\nimport { toToolsJSONSchema } from \"assistant-stream\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { useStatewire } from \"statewire\";\nimport type { Statewire } 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 // cast: core >=0.3.5 widens tool generics beyond assistant-stream's Tool\n tools: toToolsJSONSchema(\n context.tools as unknown as Parameters<typeof toToolsJSONSchema>[0],\n ),\n }),\n ...(context.callSettings !== undefined && {\n callSettings: context.callSettings,\n }),\n ...(context.config !== undefined && { config: context.config }),\n});\n\nconst useStatewireThread = (\n options: StatewireThread.Options<any>,\n): ClientOutput<\"thread\"> => {\n const latest = useRef(options);\n latest.current = options;\n\n const [pending, setPending] = useState<readonly AssistantTransportCommand[]>(\n [],\n );\n const [retire] = useState(\n () => (command: unknown) =>\n setPending((prev) =>\n prev.includes(command as AssistantTransportCommand)\n ? prev.filter((c) => c !== command)\n : prev,\n ),\n );\n\n const {\n state: transportState,\n commands,\n setContext,\n } = useStatewire<unknown, AnyCommands>({\n transport: options.transport,\n onCommandChange: (update) => {\n if (update.status === \"acked\" || update.status === \"settled\")\n retire(update.params[0]);\n },\n });\n const attached = transportState !== undefined;\n const state = attached ? transportState : options.initialState;\n\n const clientRef = useAssistantClientRef();\n const setContextRef = useRef(setContext);\n setContextRef.current = setContext;\n const [syncState] = useState(() => ({ lastSent: undefined as unknown }));\n const { contextSync } = options;\n useEffect(() => {\n if (contextSync === undefined) return;\n const modelContext = (clientRef.current ?? clientRef.parent).modelContext();\n const send = () => {\n const value = ambientContextOf(modelContext.getModelContext());\n const key = JSON.stringify(value);\n if (key === syncState.lastSent) return;\n syncState.lastSent = key;\n void setContextRef.current(value).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n };\n send();\n if (!modelContext.subscribe) {\n throw new Error(\n \"statewire: contextSync requires a subscribable model context\",\n );\n }\n return modelContext.subscribe(send);\n }, [contextSync, clientRef, syncState]);\n\n const dispatch = useCallback(\n (command: AssistantTransportCommand) => {\n setPending((prev) => [...prev, command]);\n void commands[command.type]!(command).catch((error: Error) => {\n retire(command);\n latest.current.onError?.(error);\n });\n },\n [commands, retire],\n );\n\n const { converter } = options;\n const metadata = useMemo(\n (): StatewireThread.ConnectionMetadata => ({\n pendingCommands: [...pending],\n isSending: pending.length > 0,\n }),\n [pending],\n );\n const converted = useMemo(\n () => converter(state, metadata),\n [converter, state, metadata],\n );\n\n const extras = useMemo(\n (): AssistantTransportExtras => ({\n [symbolAssistantTransportExtras]: true,\n sendCommand: dispatch,\n state,\n }),\n [dispatch, state],\n );\n\n const handleAppend = (message: AppendMessage) => {\n const command = convertAppendMessageToCommand(message);\n if (!command) return;\n dispatch(command);\n };\n\n return useResource(\n ExternalThread({\n messages: converted.messages as readonly ExternalThreadMessage[],\n isRunning: converted.isRunning,\n isLoading: !attached,\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n onNew: handleAppend,\n ...(options.capabilities?.edit && { onEdit: handleAppend }),\n onCancel: () => {\n void commands[\"cancel\"]!().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 State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n readonly isRunning: boolean;\n };\n\n export type ConnectionMetadata = {\n pendingCommands: AssistantTransportCommand[];\n isSending: boolean;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\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 onError?: ((error: Error) => void) | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n }\n | undefined;\n };\n}\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useStatewireThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;AA6BA,MAAM4B,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWC,KAAAA,KAAa,EAAED,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQG,UAAUD,KAAAA,KAAa,EAEjCC,OAAOf,kBACLY,QAAQG,KACV,EACF;CACA,GAAIH,QAAQK,iBAAiBH,KAAAA,K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AAiB;IACjDnC,OAAOC,QAAQoC,UAAUF,OAAK;GAChC,CAAC;EACH;CACF,CAAC,CACH;AACF;AAEA,MAAarC,mBACXD,YAEAhC,SAAS+B,kBAAkB,CAAC,CAACC,OAAuC;AA8CtE3B,uBACE0B,oBACA5B,eAAeuB,KAAAA,CAAkB,CAAC,CAAC6E,IACrC"}
|
|
1
|
+
{"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","AppendMessage","AttachmentAdapter","ExternalThreadQueueAdapter","ModelContext","QueuePlacement","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","StatewireClient","convertAppendMessageToCommand","symbolAssistantTransportExtras","AssistantTransportExtras","AssistantTransportCommand","AnyCommands","Record","args","ambientContextOf","context","system","undefined","tools","callSettings","config","toWireMessage","message","id","StatewireThread","UserMessage","role","Error","files","FilePart","texts","source","content","attachments","flatMap","a","part","type","push","text","mediaType","url","image","mimeType","data","filename","parts","TextPart","length","const","join","toQueueItemState","item","QueueItem","prompt","map","placementFields","placement","insertAfter","insertBefore","withSessionLostFallback","transport","Transport","latest","current","Options","transportOptions","rest","transportLevel","onCommandSessionLost","command","SessionLostCommand","useStatewireThread","options","pending","setPending","Command","retire","prev","includes","filter","c","state","transportState","commands","connection","setContext","onCommandChange","update","status","params","attached","initialState","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","catch","error","onError","subscribe","dispatch","converter","metadata","ConnectionMetadata","pendingCommands","isSending","converted","queueItems","queue","steerQueueItems","steerQueue","queueSeam","present","laneOf","queueItemId","some","items","steerItems","enqueue","crypto","randomUUID","steer","move","lane","fields","messageId","edit","wireMessage","remove","extras","sendCommand","reconnect","handleAppend","handleEdit","sourceId","messages","isRunning","isLoading","attachmentAdapter","adapters","onNew","capabilities","onEdit","continue","onResume","onCancel","payload","cancelPayload","Array","isArray","T","Placement","RunEnqueueCommand","RunSteerCommand","RunDequeueCommand","RunEditCommand","RunContinueCommand","RunCommand","State","ConnectionState","StateConverter","connectionMetadata","CancelPayload","reason","hook"],"sources":["../src/StatewireThread.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { resource, useResource } from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/react\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/react\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport type {\n AppendMessage,\n AttachmentAdapter,\n ExternalThreadQueueAdapter,\n ModelContext,\n QueuePlacement,\n ThreadMessage,\n} from \"@assistant-ui/core\";\nimport { toToolsJSONSchema } from \"assistant-stream\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { useStatewire } from \"statewire\";\nimport type { Statewire, StatewireClient } from \"statewire\";\nimport {\n convertAppendMessageToCommand,\n symbolAssistantTransportExtras,\n} from \"./AssistantTransportThread\";\nimport type { AssistantTransportExtras } from \"./AssistantTransportThread\";\nimport type { AssistantTransportCommand } from \"./types\";\n\ntype AnyCommands = Record<string, (...args: any[]) => unknown>;\n\nconst ambientContextOf = (context: ModelContext): Record<string, unknown> => ({\n ...(context.system !== undefined && { system: context.system }),\n ...(context.tools !== undefined && {\n tools: toToolsJSONSchema(context.tools),\n }),\n ...(context.callSettings !== undefined && {\n callSettings: context.callSettings,\n }),\n ...(context.config !== undefined && { config: context.config }),\n});\n\nconst toWireMessage = (\n message: AppendMessage,\n id: string,\n): StatewireThread.UserMessage => {\n if (message.role !== \"user\")\n throw new Error(\"statewire: only user messages are supported\");\n const files: StatewireThread.FilePart[] = [];\n const texts: string[] = [];\n const source = [\n ...message.content,\n ...(message.attachments?.flatMap((a) => a.content) ?? []),\n ];\n for (const part of source) {\n if (part.type === \"text\") {\n texts.push(part.text);\n } else if (part.type === \"image\") {\n files.push({ type: \"file\", mediaType: \"image/*\", url: part.image });\n } else if (part.type === \"file\") {\n files.push({\n type: \"file\",\n mediaType: part.mimeType,\n url: part.data,\n ...(part.filename !== undefined && { filename: part.filename }),\n });\n } else {\n throw new Error(`statewire: unsupported message part \"${part.type}\"`);\n }\n }\n // default-safe against host capabilities: files first, one merged text part\n const parts: (StatewireThread.TextPart | StatewireThread.FilePart)[] = [\n ...files,\n ...(texts.length > 0\n ? [{ type: \"text\" as const, text: texts.join(\"\\n\\n\") }]\n : []),\n ];\n if (parts.length === 0)\n throw new Error(\"statewire: cannot send an empty message\");\n return { id, role: \"user\", parts };\n};\n\nconst toQueueItemState = (item: StatewireThread.QueueItem) => ({\n id: item.id,\n prompt: item.parts\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\"),\n parts: item.parts.map((part) =>\n part.type === \"text\"\n ? part\n : {\n type: \"file\" as const,\n data: part.url,\n mimeType: part.mediaType,\n ...(part.filename !== undefined && { filename: part.filename }),\n },\n ),\n});\n\nconst placementFields = (placement: QueuePlacement) => ({\n ...(placement.insertAfter !== undefined && {\n insertAfter: placement.insertAfter,\n }),\n ...(placement.insertBefore !== undefined && {\n insertBefore: placement.insertBefore,\n }),\n});\n\nconst withSessionLostFallback = (\n transport: StatewireThread.Transport<any>,\n latest: { current: StatewireThread.Options<any> },\n): StatewireThread.Transport<any> => {\n const [transportOptions, ...rest] = transport.args as [\n Record<string, unknown>,\n ...unknown[],\n ];\n if (\n rest.length > 0 ||\n typeof transportOptions !== \"object\" ||\n transportOptions === null\n ) {\n throw new Error(\n \"statewire: onCommandSessionLost requires a transport element that takes a single options object\",\n );\n }\n const transportLevel = transportOptions.onCommandSessionLost as\n | ((command: StatewireClient.SessionLostCommand) => \"replay\" | void)\n | undefined;\n return {\n ...transport,\n args: [\n {\n ...transportOptions,\n onCommandSessionLost: (\n command: StatewireClient.SessionLostCommand,\n ): \"replay\" | void =>\n transportLevel?.(command) ??\n latest.current.onCommandSessionLost?.(command),\n },\n ],\n };\n};\n\nconst useStatewireThread = (\n options: StatewireThread.Options<any>,\n): ClientOutput<\"thread\"> => {\n const latest = useRef(options);\n latest.current = options;\n\n const [pending, setPending] = useState<readonly StatewireThread.Command[]>(\n [],\n );\n const [retire] = useState(\n () => (command: unknown) =>\n setPending((prev) =>\n prev.includes(command as StatewireThread.Command)\n ? prev.filter((c) => c !== command)\n : prev,\n ),\n );\n\n const {\n state: transportState,\n commands,\n connection,\n setContext,\n } = useStatewire<unknown, AnyCommands>({\n transport:\n options.onCommandSessionLost === undefined\n ? options.transport\n : withSessionLostFallback(options.transport, latest),\n onCommandChange: (update) => {\n if (update.status === \"acked\" || update.status === \"settled\")\n retire(update.params[0]);\n },\n });\n const attached = transportState !== undefined;\n const state = attached ? transportState : options.initialState;\n\n const clientRef = useAssistantClientRef();\n const setContextRef = useRef(setContext);\n setContextRef.current = setContext;\n const [syncState] = useState(() => ({ lastSent: undefined as unknown }));\n const { contextSync } = options;\n useEffect(() => {\n if (contextSync === undefined) return;\n const modelContext = (clientRef.current ?? clientRef.parent).modelContext();\n const send = () => {\n const value = ambientContextOf(modelContext.getModelContext());\n const key = JSON.stringify(value);\n if (key === syncState.lastSent) return;\n syncState.lastSent = key;\n void setContextRef.current(value).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n };\n send();\n if (!modelContext.subscribe) {\n throw new Error(\n \"statewire: contextSync requires a subscribable model context\",\n );\n }\n return modelContext.subscribe(send);\n }, [contextSync, clientRef, syncState]);\n\n const dispatch = useCallback(\n (command: StatewireThread.Command) => {\n setPending((prev) => [...prev, command]);\n void commands[command.type]!(command).catch((error: Error) => {\n retire(command);\n latest.current.onError?.(error);\n });\n },\n [commands, retire],\n );\n\n const { converter } = options;\n const metadata = useMemo(\n (): StatewireThread.ConnectionMetadata => ({\n pendingCommands: [...pending],\n isSending: pending.length > 0,\n connection,\n }),\n [pending, connection],\n );\n const converted = useMemo(\n () => converter(state, metadata),\n [converter, state, metadata],\n );\n const queueItems = converted.queue;\n const steerQueueItems = converted.steerQueue;\n if (steerQueueItems !== undefined && queueItems === undefined)\n throw new Error(\n \"statewire: the converter's steerQueue projection requires the queue projection\",\n );\n const [queueSeam] = useState(() => ({\n present: queueItems !== undefined,\n }));\n if (queueSeam.present !== (queueItems !== undefined))\n throw new Error(\n \"statewire: the converter's queue projection must be stable — it was \" +\n (queueSeam.present ? \"defined\" : \"undefined\") +\n \" on first convert and changed since\",\n );\n\n const queue = useMemo((): ExternalThreadQueueAdapter | undefined => {\n if (!queueItems) return undefined;\n const laneOf = (queueItemId: string): \"queue\" | \"steer\" => {\n if (steerQueueItems?.some((item) => item.id === queueItemId))\n return \"steer\";\n if (queueItems.some((item) => item.id === queueItemId)) return \"queue\";\n throw new Error(`statewire: unknown queue item \"${queueItemId}\"`);\n };\n return {\n items: queueItems.map(toQueueItemState),\n steerItems: (steerQueueItems ?? []).map(toQueueItemState),\n enqueue: (message) =>\n dispatch({\n type: \"run/enqueue\",\n message: toWireMessage(message, crypto.randomUUID()),\n }),\n steer: (message) =>\n dispatch({\n type: \"run/steer\",\n message: toWireMessage(message, crypto.randomUUID()),\n }),\n move: (queueItemId, placement) => {\n const lane = placement.lane ?? laneOf(queueItemId);\n const fields = {\n messageId: queueItemId,\n ...placementFields(placement),\n };\n dispatch(\n lane === \"steer\"\n ? { type: \"run/steer\", ...fields }\n : { type: \"run/enqueue\", ...fields },\n );\n },\n edit: (queueItemId, message) => {\n const wireMessage = toWireMessage(message, queueItemId);\n dispatch(\n laneOf(queueItemId) === \"steer\"\n ? { type: \"run/steer\", message: wireMessage }\n : { type: \"run/enqueue\", message: wireMessage },\n );\n },\n remove: (queueItemId) =>\n dispatch({ type: \"run/dequeue\", messageId: queueItemId }),\n };\n }, [queueItems, steerQueueItems, dispatch]);\n\n const extras = useMemo(\n (): AssistantTransportExtras => ({\n [symbolAssistantTransportExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state,\n }),\n [dispatch, connection.reconnect, state],\n );\n\n const handleAppend = (message: AppendMessage) => {\n const command = convertAppendMessageToCommand(message);\n if (!command) return;\n dispatch(command);\n };\n\n const handleEdit = (message: AppendMessage) => {\n if (!queueItems) return handleAppend(message);\n if (message.sourceId == null)\n throw new Error(\"statewire: run/edit requires a sourceId\");\n dispatch({\n type: \"run/edit\",\n message: toWireMessage(message, crypto.randomUUID()),\n sourceId: message.sourceId,\n });\n };\n\n return useResource(\n ExternalThread({\n messages: converted.messages as readonly ExternalThreadMessage[],\n isRunning: converted.isRunning,\n isLoading: !attached,\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n onNew: handleAppend,\n ...(queue && { queue }),\n ...(options.capabilities?.edit && { onEdit: handleEdit }),\n ...(options.capabilities?.continue && {\n onResume: () => dispatch({ type: \"run/continue\" }),\n }),\n onCancel: () => {\n const payload = latest.current.cancelPayload?.();\n if (\n payload !== undefined &&\n (typeof payload !== \"object\" ||\n payload === null ||\n Array.isArray(payload))\n )\n throw new Error(\n \"statewire: cancelPayload must return a plain object\",\n );\n void commands[\"run/cancel\"]!(\n ...(payload === undefined ? [] : [payload]),\n ).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n },\n }),\n );\n};\n\nexport const StatewireThread = <T>(\n options: StatewireThread.Options<T>,\n): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useStatewireThread)(options as StatewireThread.Options<any>);\n\nexport namespace StatewireThread {\n export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;\n\n export type TextPart = {\n readonly type: \"text\";\n readonly text: string;\n };\n\n export type FilePart = {\n readonly type: \"file\";\n readonly mediaType: string;\n readonly url: string;\n readonly filename?: string;\n };\n\n export type UserMessage = {\n readonly id: string;\n readonly role: \"user\";\n readonly parts: readonly (TextPart | FilePart)[];\n readonly metadata?: Record<string, unknown>;\n };\n\n /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */\n export type Placement = {\n readonly insertAfter?: string | null;\n readonly insertBefore?: string | null;\n };\n\n export type RunEnqueueCommand = {\n readonly type: \"run/enqueue\";\n } & ({ readonly message: UserMessage } | { readonly messageId: string }) &\n Placement;\n\n export type RunSteerCommand = {\n readonly type: \"run/steer\";\n } & ({ readonly message: UserMessage } | { readonly messageId: string }) &\n Placement;\n\n export type RunDequeueCommand = {\n readonly type: \"run/dequeue\";\n readonly messageId: string;\n };\n\n export type RunEditCommand = {\n readonly type: \"run/edit\";\n readonly message: UserMessage;\n readonly sourceId: string;\n };\n\n export type RunContinueCommand = {\n readonly type: \"run/continue\";\n };\n\n export type RunCommand =\n | RunEnqueueCommand\n | RunSteerCommand\n | RunDequeueCommand\n | RunEditCommand\n | RunContinueCommand;\n\n export type Command = AssistantTransportCommand | RunCommand;\n\n /** A queued message projected out of the host state, wire shape. */\n export type QueueItem = {\n readonly id: string;\n readonly parts: readonly (TextPart | FilePart)[];\n };\n\n export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n readonly isRunning: boolean;\n /**\n * The host's regular queue lane projected out of the state. Returning it\n * (even empty) turns on the queue capability: sends become `run/enqueue`\n * / `run/steer` commands and item controls send the `run/*` queue\n * commands. Presence must be stable across conversions.\n */\n readonly queue?: readonly QueueItem[];\n /** The host's steer lane; requires `queue`. Absent means empty. */\n readonly steerQueue?: readonly QueueItem[];\n };\n\n export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `live`. */\n connection: StatewireClient.ConnectionState;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n /**\n * Payload of the built-in `run/cancel` command. `reason` is the one well-known\n * field; apps extend it with their own JSON-serializable fields.\n */\n export type CancelPayload = {\n readonly reason?: string | undefined;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n export type Options<T> = {\n transport: Transport<T>;\n initialState: T;\n converter: StateConverter<T>;\n /**\n * \"command-send\" mirrors the client's ambient model context (system,\n * tools, callSettings, config) to the server over the command channel —\n * on connect and whenever it changes. Requires a remote transport.\n */\n contextSync?: \"command-send\" | undefined;\n /** Supplies the `run/cancel` command's payload; omitted, cancel sends no payload. */\n cancelPayload?: (() => CancelPayload) | undefined;\n /**\n * Offered each pending command when a remote transport's session is\n * evicted; return \"replay\" to re-enqueue it under the rotated client id.\n * A callback set on the transport options is consulted first; this one\n * runs for commands it declined.\n */\n onCommandSessionLost?:\n | ((command: StatewireClient.SessionLostCommand) => \"replay\" | void)\n | undefined;\n onError?: ((error: Error) => void) | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n /** The host supports `run/continue` (a continue affordance on aborted runs). */\n continue?: boolean | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n }\n | undefined;\n };\n}\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useStatewireThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;AA+BA,MAAM+B,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWC,KAAAA,KAAa,EAAED,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQG,UAAUD,KAAAA,KAAa,EACjCC,OAAOhB,kBAAkBa,QAAQG,KAAK,EACxC;CACA,GAAIH,QAAQI,iBAAiBF,KAAAA,KAAa,EACxCE,cAAcJ,QAAQI,aACxB;CACA,GAAIJ,QAAQK,WAAWH,KAAAA,KAAa,EAAEG,QAAQL,QAAQK,OAAO;AAC/D;AAEA,MAAMC,iBACJC,SACAC,OACgC;CAChC,IAAID,QAAQI,SAAS,QACnB,MAAM,IAAIC,MAAM,6CAA6C;CAC/D,MAAMC,QAAoC,CAAA;CAC1C,MAAME,QAAkB,CAAA;CACxB,MAAMC,SAAS,CACb,GAAGT,QAAQU,SACX,GAAIV,QAAQW,aAAaC,SAASC,MAAMA,EAAEH,OAAO,KAAK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AAM,IAAIjI,MACR,qDACF;GACF,SAAc,aAAa,CACzB,GAAIiI,YAAY3I,KAAAA,IAAY,CAAA,IAAK,CAAC2I,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"}
|
package/dist/host.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { AssistantTransportCommand, AssistantTransportOptions } from "./types.js";
|
|
2
2
|
import { ModelContext } from "@assistant-ui/core";
|
|
3
|
+
import { Statewire } from "statewire";
|
|
3
4
|
//#region src/host.d.ts
|
|
4
5
|
type SendOptions = {
|
|
5
6
|
schedule?: boolean;
|
|
@@ -33,7 +34,7 @@ type AssistantTransportHostCommands = {
|
|
|
33
34
|
reload(parentId: string | null): void;
|
|
34
35
|
importState(state: unknown): void;
|
|
35
36
|
};
|
|
36
|
-
declare const AssistantTransportHost: import("@assistant-ui/tap").Resource<Statewire<AssistantTransportHostState, AssistantTransportHostCommands>, [options: HostOptions]>;
|
|
37
|
+
declare const AssistantTransportHost: import("@assistant-ui/tap").Resource<Statewire<AssistantTransportHostState, AssistantTransportHostCommands, any>, [options: HostOptions]>;
|
|
37
38
|
//#endregion
|
|
38
39
|
export { AssistantTransportHost, AssistantTransportHostCommands, AssistantTransportHostState, HostOptions, HostQueue, HostQueueCell, HostRunContext, SendOptions };
|
|
39
40
|
//# sourceMappingURL=host.d.ts.map
|
package/dist/host.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"host.d.ts","names":[],"sources":["../src/host.ts"],"mappings":"
|
|
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"}
|
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","Parameters","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 ? // cast: core >=0.3.5 widens tool generics beyond assistant-stream's Tool\n toToolsJSONSchema(\n modelContext.tools as unknown as Parameters<\n typeof toToolsJSONSchema\n >[0],\n )\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;EACVX,iBAAiB;EACjBC,mBAAmB;EACnBxB,aAAa;EACbyB,UAAU;EACVC,iBAAiB;EACjB5B,cAAc;CAChB,EACF;CAEArC,gBAAgB;EACdwE,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,EAAEjC,gBAAgBqC,OAAO;EAC7BJ,EAAEjC,cAAcqC;EAChBP,IAAIQ,MAAM,CAAC;GAAEC,IAAI;GAAWC,MAAM,CAAC,aAAa;GAAGH;EAAM,CAAC,CAAC;CAC7D;CAEA,MAAMI,cAAcJ,YAAmB;EACrCP,IAAIQ,MAAM,CAAC;GAAEC,IAAI;GAAWC,MAAM,CAAC,WAAW;GAAGH,OAAAA;EAAM,CAAC,CAAC;CAC3D;CAEA,MAAMK,gBAAgBC,SAAkB;EACtCb,IAAIQ,MAAM,CAAC;GAAEC,IAAI;GAAWC,MAAM,CAAC,OAAO;GAAGH,OAAOM;EAAK,CAAC,CAAC;CAC7D;CAEA,MAAMC,eAAeC,YAAyC;EAC5DH,aAAaG,QAAQb,SAAS,CAAC,CAAC;CAClC;CAGA,MAAMc,iBACJC,eACG;EACH,KAAK,MAAMC,aAAaD,YAAY;GAClC,MAAMR,KAAK5D,iBAAiBqD,SAAS,GAAGgB,SAAS;GACjD,IA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oB;GACtB;EACF;EACAoF,SAAS;CACX;CAEA,OAAO;EACL1G,OAAOC,SAAoCC,SAAuB;GAChE,MAAM,CAACS,WAAWmG,aAAa3I,iBAAiB4I,cAAc;GAC9DhE,SAAS;IACP5D,QAAQ,CAAC,GAAG4C,EAAEZ,MAAMhC,QAAQ;KAAEc;KAASU,WAAWmG;IAAU,CAAC;IAC7D1H,WAAW2C,EAAEZ,MAAM/B;GACrB,CAAC;GACD,IAAIc,MAAMpB,aAAa,OAAOA,SAAS;GACvC,OAAO6B;EACT;EACAR,cAAc6G,OAAsB;GAClCjF,EAAE3B,WAAW4G;EACf;EACA3G,cAAc;GACZ0B,EAAEV,kBAAkB;GACpBU,EAAET,oBAAoB;GACtBS,EAAEP,iBAAiBS,MAAM;EAC3B;EACA3B,cAAc;GACZ,IAAI,CAACqB,WAAW,CAAC,CAACiD,WAChB,MAAM,IAAIO,MAAM,+CAA+C;GAEjEpD,EAAEV,kBAAkB;GACpBvC,SAAS;EACX;EACAyB,SAASyG,SAAsB;GAC7BjF,EAAE3B,WAAW4G;GACblI,SAAS;EACX;EACA0B,aAAagC;CACf;AACF;AAEA,MAAMyE,6BACJC,YAC2E;CAC3E,MAAMC,gBAAgB3J,OAAO0J,OAAO;CACpCC,cAAc7H,UAAU4H;CAExB,MAAM,CAACzG,OAAOmB,OAAOtD,yBAAsD;EACzEqB,OAAOuH,QAAQE;EACfxH,cAAc;EACdC,WAAW;EACXC,aAAa;CACf,EAAE;CACF,MAAMuH,OAAOhJ,iBAAiB;CAU9B,OAAO;EAAEoC;EAAO6C,UAFClF,qBANAsD,kBACTyF,cAAc7H,SACpBsC,WACMA,IAAI2F,SAAS,CAAC,CAAC5H,KAGe2H,CAEtBhE;EAAU+D;CAAK;AACjC;AAEA,MAAaG,yBAAyB9J,SAASuJ,yBAAyB"}
|
|
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;EACVX,iBAAiB;EACjBC,mBAAmB;EACnBxB,aAAa;EACbyB,UAAU;EACVC,iBAAiB;EACjB5B,cAAc;CAChB,EACF;CAEArC,gBAAgB;EACdwE,EAAER,WAAW;EACb,aAAa;GACXQ,EAAER,WAAW;GACbQ,EAAET,oBAAoB;GACtBS,EAA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C,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"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { AssistantMessage, AssistantTransportCommand, AssistantTransportConnectionMetadata, AssistantTransportOptions, AssistantTransportProtocol, AssistantTransportState, AssistantTransportStateConverter, HeadersValue, ImagePart, MessageAddCommand, SendCommandsRequestBody, TextPart, ToolResultAddCommand, 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,8 +10,8 @@ declare namespace AssistantTransportThread {
|
|
|
10
10
|
type State = AssistantTransportState;
|
|
11
11
|
type ConnectionMetadata = AssistantTransportConnectionMetadata;
|
|
12
12
|
type StateConverter<T> = AssistantTransportStateConverter<T>;
|
|
13
|
-
type
|
|
14
|
-
type
|
|
13
|
+
type MessageAddCommand = MessageAddCommand;
|
|
14
|
+
type ToolResultAddCommand = ToolResultAddCommand;
|
|
15
15
|
type SendCommandsRequestBody = SendCommandsRequestBody;
|
|
16
16
|
type UserMessage = UserMessage;
|
|
17
17
|
type AssistantMessage = AssistantMessage;
|
package/dist/types.d.ts
CHANGED
|
@@ -22,14 +22,20 @@ type AssistantMessage = {
|
|
|
22
22
|
readonly role: "assistant";
|
|
23
23
|
readonly parts: readonly TextPart[];
|
|
24
24
|
};
|
|
25
|
-
type
|
|
26
|
-
readonly type: "add
|
|
25
|
+
type MessageAddCommand = {
|
|
26
|
+
readonly type: "message/add";
|
|
27
27
|
readonly message: UserMessage | AssistantMessage;
|
|
28
28
|
readonly parentId: string | null;
|
|
29
29
|
readonly sourceId: string | null;
|
|
30
|
+
/**
|
|
31
|
+
* How the host handles the message while a run is active: `"queue"`
|
|
32
|
+
* appends to the queue, `"steer"` moves it to the front and interrupts
|
|
33
|
+
* the run. Absent, the host decides. Ignored when the host is idle.
|
|
34
|
+
*/
|
|
35
|
+
readonly behavior?: "queue" | "steer";
|
|
30
36
|
};
|
|
31
|
-
type
|
|
32
|
-
readonly type: "
|
|
37
|
+
type ToolResultAddCommand = {
|
|
38
|
+
readonly type: "tool-result/add";
|
|
33
39
|
readonly toolCallId: string;
|
|
34
40
|
readonly toolName: string;
|
|
35
41
|
readonly result: ReadonlyJSONValue;
|
|
@@ -37,7 +43,7 @@ type AddToolResultCommand = {
|
|
|
37
43
|
readonly artifact?: ReadonlyJSONValue;
|
|
38
44
|
readonly modelContent?: readonly ToolModelContentPart[];
|
|
39
45
|
};
|
|
40
|
-
type AssistantTransportCommand =
|
|
46
|
+
type AssistantTransportCommand = MessageAddCommand | ToolResultAddCommand | UserCommands;
|
|
41
47
|
type AssistantTransportState = {
|
|
42
48
|
readonly messages: readonly ThreadMessage[];
|
|
43
49
|
readonly state?: ReadonlyJSONValue;
|
|
@@ -89,11 +95,16 @@ type AssistantTransportOptions<T> = {
|
|
|
89
95
|
}) => void) | undefined;
|
|
90
96
|
capabilities?: {
|
|
91
97
|
edit?: boolean | undefined;
|
|
98
|
+
/**
|
|
99
|
+
* Buffer messages sent during a run in an in-memory queue and dispatch
|
|
100
|
+
* them once the run settles. Steering interrupts the active run.
|
|
101
|
+
*/
|
|
102
|
+
queue?: boolean | undefined;
|
|
92
103
|
} | undefined;
|
|
93
104
|
adapters?: {
|
|
94
105
|
attachments?: AttachmentAdapter | undefined;
|
|
95
106
|
} | undefined;
|
|
96
107
|
};
|
|
97
108
|
//#endregion
|
|
98
|
-
export {
|
|
109
|
+
export { AssistantMessage, AssistantTransportCommand, AssistantTransportConnectionMetadata, AssistantTransportOptions, AssistantTransportProtocol, AssistantTransportState, AssistantTransportStateConverter, HeadersValue, ImagePart, MessageAddCommand, SendCommandsRequestBody, TextPart, ToolResultAddCommand, UserCommands, UserExternalState, UserMessage, UserMessagePart };
|
|
99
110
|
//# sourceMappingURL=types.d.ts.map
|
package/dist/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","names":[],"sources":["../src/types.ts"],"mappings":";;;;;KAWY,eAAe,UAAU,eAAe,UAAU;KAClD,0BAA0B,UAAU,8BAC5C,0BACA,UAAU,oBAAoB,UAAU;KAEhC;WACD;WACA;;KAGC;WACD;WACA;;KAGC,kBAAkB,WAAW;KAE7B;WACD;WACA,gBAAgB;;KAGf;WACD;WACA,gBAAgB;;KAGf;WACD;WACA,SAAS,cAAc;WACvB;WACA;;KAGC;WACD;WACA;WACA;WACA,QAAQ;WACR;WACA,WAAW;WACX,wBAAwB;;KAGvB,4BACR,oBACA,uBACA;KAEQ;WACD,mBAAmB;WACnB,QAAQ;WACR;;KAGC;EACV,iBAAiB;EACjB;EACA,cAAc,eAAe;;KAGnB,iCAAiC,MAC3C,OAAO,GACP,oBAAoB,yCACjB;KAEO,eAAe,yBAAyB;KAExC;KAEA;EACV,UAAU;EACV;EACA;EACA,OAAO;EACP,cAAc;EACd,QAAQ;EACR;EACA;GACC;;KAGS,0BAA0B;EACpC,cAAc;EACd,WAAW,iCAAiC;EAC5C;EACA;EACA,WAAW;EACX,SAAS,sBAAsB,QAAQ;EACvC,uBAAuB;;EAEvB,+BAEM,MAAM,4BACH,0BAA0B,QAAQ;EAE3C,eAAe,UAAU;EACzB;EACA,YAEM,OAAO,OACP;IACE,UAAU;IACV,cAAc,UAAU,OAAO,MAAM;eAE7B;;;;;EAMhB,aACM;IACA,UAAU;IACV,cAAc,UAAU,OAAO,MAAM;IACrC,QAAQ;;EAGd;IAEM;;EAGN;IAEM,cAAc"}
|
|
1
|
+
{"version":3,"file":"types.d.ts","names":[],"sources":["../src/types.ts"],"mappings":";;;;;KAWY,eAAe,UAAU,eAAe,UAAU;KAClD,0BAA0B,UAAU,8BAC5C,0BACA,UAAU,oBAAoB,UAAU;KAEhC;WACD;WACA;;KAGC;WACD;WACA;;KAGC,kBAAkB,WAAW;KAE7B;WACD;WACA,gBAAgB;;KAGf;WACD;WACA,gBAAgB;;KAGf;WACD;WACA,SAAS,cAAc;WACvB;WACA;;;;;;WAMA;;KAGC;WACD;WACA;WACA;WACA,QAAQ;WACR;WACA,WAAW;WACX,wBAAwB;;KAGvB,4BACR,oBACA,uBACA;KAEQ;WACD,mBAAmB;WACnB,QAAQ;WACR;;KAGC;EACV,iBAAiB;EACjB;EACA,cAAc,eAAe;;KAGnB,iCAAiC,MAC3C,OAAO,GACP,oBAAoB,yCACjB;KAEO,eAAe,yBAAyB;KAExC;KAEA;EACV,UAAU;EACV;EACA;EACA,OAAO;EACP,cAAc;EACd,QAAQ;EACR;EACA;GACC;;KAGS,0BAA0B;EACpC,cAAc;EACd,WAAW,iCAAiC;EAC5C;EACA;EACA,WAAW;EACX,SAAS,sBAAsB,QAAQ;EACvC,uBAAuB;;EAEvB,+BAEM,MAAM,4BACH,0BAA0B,QAAQ;EAE3C,eAAe,UAAU;EACzB;EACA,YAEM,OAAO,OACP;IACE,UAAU;IACV,cAAc,UAAU,OAAO,MAAM;eAE7B;;;;;EAMhB,aACM;IACA,UAAU;IACV,cAAc,UAAU,OAAO,MAAM;IACrC,QAAQ;;EAGd;IAEM;;;;;IAKA;;EAGN;IAEM,cAAc"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@assistant-ui/react-statewire",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "assistant-ui thread binding for statewire backends",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -30,14 +30,14 @@
|
|
|
30
30
|
"test": "vitest run"
|
|
31
31
|
},
|
|
32
32
|
"dependencies": {
|
|
33
|
-
"@assistant-ui/core": "^0.3.
|
|
33
|
+
"@assistant-ui/core": "^0.3.7",
|
|
34
34
|
"@assistant-ui/store": "^0.3.0",
|
|
35
35
|
"@assistant-ui/tap": "^0.9.7",
|
|
36
36
|
"assistant-stream": "^0.3.33",
|
|
37
|
-
"statewire": "^0.0.
|
|
37
|
+
"statewire": "^0.0.5"
|
|
38
38
|
},
|
|
39
39
|
"peerDependencies": {
|
|
40
|
-
"@assistant-ui/react": ">=0.
|
|
40
|
+
"@assistant-ui/react": ">=0.15.6",
|
|
41
41
|
"react": "^18 || ^19"
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
@@ -1,4 +1,11 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
useCallback,
|
|
3
|
+
useEffect,
|
|
4
|
+
useMemo,
|
|
5
|
+
useRef,
|
|
6
|
+
useState,
|
|
7
|
+
useSyncExternalStore,
|
|
8
|
+
} from "react";
|
|
2
9
|
import { resource, useResource } from "@assistant-ui/tap";
|
|
3
10
|
import type { ResourceElement } from "@assistant-ui/tap";
|
|
4
11
|
import { ExternalThread } from "@assistant-ui/react";
|
|
@@ -8,9 +15,12 @@ import {
|
|
|
8
15
|
useAssistantClientRef,
|
|
9
16
|
} from "@assistant-ui/store";
|
|
10
17
|
import type { ClientOutput } from "@assistant-ui/store";
|
|
18
|
+
import { createMessageQueue } from "@assistant-ui/core";
|
|
11
19
|
import type {
|
|
12
20
|
AddToolResultOptions,
|
|
13
21
|
AppendMessage,
|
|
22
|
+
MessageQueueController,
|
|
23
|
+
MessageQueueDriver,
|
|
14
24
|
ResumeToolCallOptions,
|
|
15
25
|
ThreadMessage,
|
|
16
26
|
ToolExecutionStatus,
|
|
@@ -27,14 +37,16 @@ import type {
|
|
|
27
37
|
SendOptions,
|
|
28
38
|
} from "./host";
|
|
29
39
|
import type {
|
|
30
|
-
|
|
31
|
-
|
|
40
|
+
MessageAddCommand,
|
|
41
|
+
ToolResultAddCommand,
|
|
32
42
|
AssistantTransportCommand,
|
|
33
43
|
AssistantTransportOptions,
|
|
34
44
|
UserMessagePart,
|
|
35
45
|
} from "./types";
|
|
36
46
|
|
|
37
47
|
const EMPTY_TOOL_STATUSES: Record<string, ToolExecutionStatus> = {};
|
|
48
|
+
const EMPTY_QUEUE_ITEMS: MessageQueueController["adapter"]["items"] = [];
|
|
49
|
+
const subscribeNoop = () => () => {};
|
|
38
50
|
|
|
39
51
|
export const symbolAssistantTransportExtras = Symbol(
|
|
40
52
|
"assistant-transport-extras",
|
|
@@ -43,6 +55,7 @@ export const symbolAssistantTransportExtras = Symbol(
|
|
|
43
55
|
export type AssistantTransportExtras = {
|
|
44
56
|
[symbolAssistantTransportExtras]: true;
|
|
45
57
|
sendCommand: (command: AssistantTransportCommand) => void;
|
|
58
|
+
reconnect: () => void;
|
|
46
59
|
state: unknown;
|
|
47
60
|
};
|
|
48
61
|
|
|
@@ -63,7 +76,7 @@ export const asAssistantTransportExtras = (
|
|
|
63
76
|
|
|
64
77
|
export const convertAppendMessageToCommand = (
|
|
65
78
|
message: AppendMessage,
|
|
66
|
-
):
|
|
79
|
+
): MessageAddCommand | null => {
|
|
67
80
|
if (message.role !== "user")
|
|
68
81
|
throw new Error("Only user messages are supported");
|
|
69
82
|
|
|
@@ -83,7 +96,7 @@ export const convertAppendMessageToCommand = (
|
|
|
83
96
|
if (parts.length === 0) return null;
|
|
84
97
|
|
|
85
98
|
return {
|
|
86
|
-
type: "add
|
|
99
|
+
type: "message/add",
|
|
87
100
|
message: {
|
|
88
101
|
role: "user",
|
|
89
102
|
parts,
|
|
@@ -127,7 +140,7 @@ const useAssistantTransportThread = (
|
|
|
127
140
|
const [queueCell] = useState(
|
|
128
141
|
(): HostQueueCell => ({ current: { queued: [], inTransit: [] } }),
|
|
129
142
|
);
|
|
130
|
-
const { state, commands } = useStatewire<
|
|
143
|
+
const { state, commands, connection } = useStatewire<
|
|
131
144
|
AssistantTransportHostState,
|
|
132
145
|
AssistantTransportHostCommands
|
|
133
146
|
>({
|
|
@@ -171,7 +184,7 @@ const useAssistantTransportThread = (
|
|
|
171
184
|
const messages = convertedRef.current
|
|
172
185
|
.messages as readonly ThreadMessage[];
|
|
173
186
|
if (!messagesContainToolCall(messages, command.toolCallId)) return;
|
|
174
|
-
dispatch(command);
|
|
187
|
+
dispatch({ ...command, type: "tool-result/add" });
|
|
175
188
|
},
|
|
176
189
|
onStatusesChange: (statuses) => {
|
|
177
190
|
setToolStatuses(
|
|
@@ -202,9 +215,10 @@ const useAssistantTransportThread = (
|
|
|
202
215
|
(): AssistantTransportExtras => ({
|
|
203
216
|
[symbolAssistantTransportExtras]: true,
|
|
204
217
|
sendCommand: dispatch,
|
|
218
|
+
reconnect: connection.reconnect,
|
|
205
219
|
state: agentState,
|
|
206
220
|
}),
|
|
207
|
-
[dispatch, agentState],
|
|
221
|
+
[dispatch, connection.reconnect, agentState],
|
|
208
222
|
);
|
|
209
223
|
|
|
210
224
|
const handleAppend = (message: AppendMessage) => {
|
|
@@ -224,6 +238,65 @@ const useAssistantTransportThread = (
|
|
|
224
238
|
}
|
|
225
239
|
};
|
|
226
240
|
|
|
241
|
+
const handleCancel = () => {
|
|
242
|
+
void toolInvocations.abort();
|
|
243
|
+
void commands.cancel().catch(() => {});
|
|
244
|
+
};
|
|
245
|
+
|
|
246
|
+
const driverRef = useRef<{
|
|
247
|
+
run: MessageQueueDriver["run"];
|
|
248
|
+
cancel: () => void;
|
|
249
|
+
}>(undefined as never);
|
|
250
|
+
driverRef.current = {
|
|
251
|
+
// the queued message was stamped with the head at enqueue time; restamp so
|
|
252
|
+
// it appends to the thread the finished run left behind
|
|
253
|
+
run: (message) =>
|
|
254
|
+
handleAppend({
|
|
255
|
+
...message,
|
|
256
|
+
parentId: convertedRef.current.messages.at(-1)?.id ?? null,
|
|
257
|
+
}),
|
|
258
|
+
cancel: handleCancel,
|
|
259
|
+
};
|
|
260
|
+
|
|
261
|
+
const enableQueue = options.capabilities?.queue === true;
|
|
262
|
+
const queueRef = useRef<MessageQueueController | null>(null);
|
|
263
|
+
if (enableQueue && !queueRef.current) {
|
|
264
|
+
queueRef.current = createMessageQueue({
|
|
265
|
+
run: (message, opts) => driverRef.current.run(message, opts),
|
|
266
|
+
cancel: () => driverRef.current.cancel(),
|
|
267
|
+
});
|
|
268
|
+
} else if (!enableQueue && queueRef.current) {
|
|
269
|
+
queueRef.current.clear();
|
|
270
|
+
queueRef.current = null;
|
|
271
|
+
}
|
|
272
|
+
const messageQueue = queueRef.current;
|
|
273
|
+
|
|
274
|
+
// fresh view per snapshot: the controller mutates adapter.items in place,
|
|
275
|
+
// which a stable prop identity would hide from the thread resource
|
|
276
|
+
const queueItems = useSyncExternalStore(
|
|
277
|
+
messageQueue?.subscribe ?? subscribeNoop,
|
|
278
|
+
() => messageQueue?.adapter.items ?? EMPTY_QUEUE_ITEMS,
|
|
279
|
+
() => EMPTY_QUEUE_ITEMS,
|
|
280
|
+
);
|
|
281
|
+
const steerQueueItems = useSyncExternalStore(
|
|
282
|
+
messageQueue?.subscribe ?? subscribeNoop,
|
|
283
|
+
() => messageQueue?.adapter.steerItems ?? EMPTY_QUEUE_ITEMS,
|
|
284
|
+
() => EMPTY_QUEUE_ITEMS,
|
|
285
|
+
);
|
|
286
|
+
|
|
287
|
+
// settled edge: the queue only advances once the host run loop has fully
|
|
288
|
+
// released (isSending), the converted state agrees, and no client tool from
|
|
289
|
+
// the finished run is still executing
|
|
290
|
+
const busy =
|
|
291
|
+
isSending || converted.isRunning || Object.keys(toolStatuses).length > 0;
|
|
292
|
+
const wasBusyRef = useRef(false);
|
|
293
|
+
useEffect(() => {
|
|
294
|
+
if (wasBusyRef.current === busy) return;
|
|
295
|
+
wasBusyRef.current = busy;
|
|
296
|
+
if (busy) messageQueue?.notifyBusy();
|
|
297
|
+
else messageQueue?.notifyIdle();
|
|
298
|
+
});
|
|
299
|
+
|
|
227
300
|
return useResource(
|
|
228
301
|
ExternalThread({
|
|
229
302
|
messages: converted.messages as readonly ExternalThreadMessage[],
|
|
@@ -233,6 +306,13 @@ const useAssistantTransportThread = (
|
|
|
233
306
|
extras,
|
|
234
307
|
attachmentAdapter: options.adapters?.attachments,
|
|
235
308
|
onNew: handleAppend,
|
|
309
|
+
...(messageQueue && {
|
|
310
|
+
queue: {
|
|
311
|
+
...messageQueue.adapter,
|
|
312
|
+
items: queueItems,
|
|
313
|
+
steerItems: steerQueueItems,
|
|
314
|
+
},
|
|
315
|
+
}),
|
|
236
316
|
...(options.capabilities?.edit && { onEdit: handleAppend }),
|
|
237
317
|
onReload: (parentId: string | null) => {
|
|
238
318
|
void toolInvocations.abort().then(() => {
|
|
@@ -240,8 +320,9 @@ const useAssistantTransportThread = (
|
|
|
240
320
|
});
|
|
241
321
|
},
|
|
242
322
|
onCancel: () => {
|
|
243
|
-
|
|
244
|
-
|
|
323
|
+
// user cancel drops pending lanes; a steer interrupt (driver.cancel) keeps them
|
|
324
|
+
messageQueue?.clear();
|
|
325
|
+
handleCancel();
|
|
245
326
|
},
|
|
246
327
|
onResume: () => {
|
|
247
328
|
if (!options.resumeApi)
|
|
@@ -249,8 +330,8 @@ const useAssistantTransportThread = (
|
|
|
249
330
|
void commands.resume().catch(() => {});
|
|
250
331
|
},
|
|
251
332
|
onAddToolResult: (toolOptions: AddToolResultOptions) => {
|
|
252
|
-
const command:
|
|
253
|
-
type: "
|
|
333
|
+
const command: ToolResultAddCommand = {
|
|
334
|
+
type: "tool-result/add",
|
|
254
335
|
toolCallId: toolOptions.toolCallId,
|
|
255
336
|
result: toolOptions.result as ReadonlyJSONObject,
|
|
256
337
|
toolName: toolOptions.toolName,
|