@assistant-ui/react-statewire 0.4.3 → 0.4.4

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/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","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,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SAAS;IACP/D,QAAQ,CACN,GAAG+C,EAAEZ,MAAMnC,QACX;KAAEc;KAASc,WAAW;MAAEL,KAAK,KAAKA;MAAKC;MAASC;KAAO;IAAE,CAAC;IAE5DxB,WAAW8C,EAAEZ,MAAMlC;GACrB,CAAC;GACD,IAAIc,MAAMpB,aAAa,OAAOA,SAAS;GACvC,OAAOgI;EACT;EACA3G,cAAc+G,OAAsB;GAClChF,EAAE9B,WAAW8G;EACf;EACA7G,cAAc;GACZ6B,EAAEV,kBAAkB;GACpBU,EAAET,oBAAoB;GACtBS,EAAEP,iBAAiBS,MAAM;EAC3B;EACA9B,cAAc;GACZ,IAAI,CAACwB,WAAW,CAAC,CAAC+C,WAChB,MAAM,IAAIO,MAAM,+CAA+C;GAEjElD,EAAEV,kBAAkB;GACpB1C,SAAS;EACX;EACAyB,aAAaoC;CACf;AACF;AAEA,MAAMwE,6BACJC,YAC2E;CAC3E,MAAMC,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"}
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","AssistantTransportThread","SendOptions","schedule","HostRunContext","modelContext","threadId","HostQueue","queued","Command","inTransit","HostQueueCell","current","HostOptions","Options","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","SendCommandsRequestBody","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 { AssistantTransportThread } from \"./AssistantTransportThread\";\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: AssistantTransportThread.Command[];\n inTransit: AssistantTransportThread.Command[];\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 = AssistantTransportThread.Options<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: AssistantTransportThread.Command, 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: AssistantTransportThread.Command;\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: AssistantTransportThread.Command[],\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(\n requestBody as AssistantTransportThread.SendCommandsRequestBody,\n );\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: AssistantTransportThread.Command,\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":";;;;;;;;;AA6EA,MAAMyD,cAAcC,YAA0BA,QAAQC,KAAKC,MAAMA,EAAEnB,OAAO;AAc1E,MAAM4B,eACJC,YACAC,KACAE,aACG;CACH,MAAM,CAACC,KAAKxE,gBACQ;EAChB4D,OAAO;GAAErC,QAAQ,CAAA;GAAIE,WAAW,CAAA;EAAG;EACnCoC,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,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Ac;GACZ,IAAI,CAACwB,WAAW,CAAC,CAACgD,WAChB,MAAM,IAAIO,MAAM,+CAA+C;GAEjEnD,EAAEV,kBAAkB;GACpB5C,SAAS;EACX;EACA2B,aAAaoC;CACf;AACF;AAEA,MAAMyE,6BACJC,YAC2E;CAC3E,MAAMC,gBAAgB7J,OAAO4J,OAAO;CACpCC,cAAcjI,UAAUgI;CAExB,MAAM,CAAC7G,OAAOuB,OAAOzD,yBAAsD;EACzEqB,OAAO0H,QAAQE;EACf3H,cAAc;EACdC,WAAW;EACXC,aAAa;CACf,EAAE;CACF,MAAM0H,OAAOnJ,iBAAiB;CAE9B,MAAMoJ,WAAW5F,kBACTyF,cAAcjI,SACpB0C,WACMA,IAAI2F,SAAS,CAAC,CAAC/H,KACvB;CAIA,OAAO;EAAEa;EAAOiD,UAFCrF,qBAAqBqJ,QAEtBhE;EAAU+D;CAAK;AACjC;AAEA,MAAaG,yBAAyBhK,SAASyJ,yBAAyB"}
package/dist/index.d.ts CHANGED
@@ -1,39 +1,4 @@
1
- import { AssistantTransportCommand, AssistantTransportConnectionMetadata, AssistantTransportOptions, AssistantTransportProtocol, AssistantTransportState, AssistantTransportStateConverter, CustomInputRequest, FilePart, HeadersValue, InputRequest, InputRequestState, InputResponse, RunCommand, RunContinueCommand, RunDequeueCommand, RunEditCommand, RunEnqueueCommand, RunInputCommand, RunPlacement, RunQueueItem, RunReloadCommand, RunSteerCommand, RunUserMessage, SendCommandsRequestBody, TextPart, ToolApprovalInputRequest, ToolApprovalInputResponse, ToolCallInputRequest, ToolCallInputResponse } from "./types.js";
2
1
  import { AssistantTransportThread } from "./AssistantTransportThread.js";
3
2
  import { StatewireThread } from "./StatewireThread.js";
4
3
  import { useAssistantTransportSendCommand, useAssistantTransportState } from "./hooks.js";
5
- //#region src/index.d.ts
6
- declare namespace AssistantTransportThread {
7
- type Options<T> = AssistantTransportOptions<T>;
8
- type Command = AssistantTransportCommand;
9
- type Protocol = AssistantTransportProtocol;
10
- type State = AssistantTransportState;
11
- type ConnectionMetadata = AssistantTransportConnectionMetadata;
12
- type StateConverter<T> = AssistantTransportStateConverter<T>;
13
- type RunCommand = RunCommand;
14
- type RunEnqueueCommand = RunEnqueueCommand;
15
- type RunSteerCommand = RunSteerCommand;
16
- type RunDequeueCommand = RunDequeueCommand;
17
- type RunEditCommand = RunEditCommand;
18
- type RunContinueCommand = RunContinueCommand;
19
- type RunReloadCommand = RunReloadCommand;
20
- type RunInputCommand = RunInputCommand;
21
- type InputRequest = InputRequest;
22
- type ToolCallInputRequest = ToolCallInputRequest;
23
- type ToolApprovalInputRequest = ToolApprovalInputRequest;
24
- type CustomInputRequest = CustomInputRequest;
25
- type InputRequestState = InputRequestState;
26
- type InputResponse = InputResponse;
27
- type ToolCallInputResponse = ToolCallInputResponse;
28
- type ToolApprovalInputResponse = ToolApprovalInputResponse;
29
- type RunUserMessage = RunUserMessage;
30
- type RunQueueItem = RunQueueItem;
31
- type RunPlacement = RunPlacement;
32
- type SendCommandsRequestBody = SendCommandsRequestBody;
33
- type TextPart = TextPart;
34
- type FilePart = FilePart;
35
- type HeadersValue = HeadersValue;
36
- }
37
- //#endregion
38
- export { AssistantTransportThread, StatewireThread, useAssistantTransportSendCommand, useAssistantTransportState };
39
- //# sourceMappingURL=index.d.ts.map
4
+ export { AssistantTransportThread, StatewireThread, useAssistantTransportSendCommand, useAssistantTransportState };
@@ -1,14 +1,14 @@
1
- import { InputRequestState, RunInputCommand } from "./types.js";
1
+ import { AssistantTransportThread } from "./AssistantTransportThread.js";
2
2
  import { RespondToToolApprovalOptions } from "@assistant-ui/core";
3
3
  import { ReadonlyJSONValue } from "assistant-stream/utils";
4
4
  //#region src/inputRequests.d.ts
5
- declare const resolveToolResultInput: (inputRequests: readonly InputRequestState[], options: {
5
+ declare const resolveToolResultInput: (inputRequests: readonly AssistantTransportThread.InputRequestState[], options: {
6
6
  toolCallId: string;
7
7
  result: ReadonlyJSONValue;
8
8
  isError: boolean;
9
9
  artifact?: ReadonlyJSONValue | undefined;
10
- }) => RunInputCommand;
11
- declare const resolveToolApprovalInput: (inputRequests: readonly InputRequestState[], options: RespondToToolApprovalOptions) => RunInputCommand;
10
+ }) => AssistantTransportThread.RunInputCommand;
11
+ declare const resolveToolApprovalInput: (inputRequests: readonly AssistantTransportThread.InputRequestState[], options: RespondToToolApprovalOptions) => AssistantTransportThread.RunInputCommand;
12
12
  //#endregion
13
13
  export { resolveToolApprovalInput, resolveToolResultInput };
14
14
  //# sourceMappingURL=inputRequests.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"inputRequests.d.ts","names":[],"sources":["../src/inputRequests.ts"],"mappings":";;;;cAWa,yBACX,wBAAwB,qBACxB;EACE;EACA,QAAQ;EACR;EACA,WAAW;MAEZ;cAoBU,2BACX,wBAAwB,qBACxB,SAAS,iCACR"}
1
+ {"version":3,"file":"inputRequests.d.ts","names":[],"sources":["../src/inputRequests.ts"],"mappings":";;;;cAaa,yBACX,wBAAwB,yBAAyB,qBACjD;EACE;EACA,QAAQ;EACR;EACA,WAAW;MAEZ,yBAAyB;cAoBf,2BACX,wBAAwB,yBAAyB,qBACjD,SAAS,iCACR,yBAAyB"}
@@ -1 +1 @@
1
- {"version":3,"file":"inputRequests.js","names":["RespondToToolApprovalOptions","ReadonlyJSONValue","InputRequestState","RunInputCommand","assertUnanswered","request","response","Error","id","resolveToolResultInput","inputRequests","options","toolCallId","result","isError","artifact","find","r","type","undefined","requestId","output","resolveToolApprovalInput","approvalId","decision","approved","reason","message"],"sources":["../src/inputRequests.ts"],"sourcesContent":["import type { RespondToToolApprovalOptions } from \"@assistant-ui/core\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport type { InputRequestState, RunInputCommand } from \"./types\";\n\nconst assertUnanswered = (request: InputRequestState) => {\n if (request.response !== null)\n throw new Error(\n `statewire: input request \"${request.id}\" is already answered`,\n );\n};\n\nexport const resolveToolResultInput = (\n inputRequests: readonly InputRequestState[],\n options: {\n toolCallId: string;\n result: ReadonlyJSONValue;\n isError: boolean;\n artifact?: ReadonlyJSONValue | undefined;\n },\n): RunInputCommand => {\n const request = inputRequests.find(\n (r) => r.type === \"tool-call\" && r.toolCallId === options.toolCallId,\n );\n if (request === undefined)\n throw new Error(\n `statewire: no tool-call input request for tool call \"${options.toolCallId}\"`,\n );\n assertUnanswered(request);\n return {\n type: \"run/input\",\n requestId: request.id,\n response: {\n output: options.result,\n ...(options.isError && { isError: true }),\n ...(options.artifact !== undefined && { artifact: options.artifact }),\n },\n };\n};\n\nexport const resolveToolApprovalInput = (\n inputRequests: readonly InputRequestState[],\n options: RespondToToolApprovalOptions,\n): RunInputCommand => {\n const request = inputRequests.find(\n (r) => r.type === \"tool-approval\" && r.id === options.approvalId,\n );\n if (request === undefined)\n throw new Error(\n `statewire: no tool-approval input request \"${options.approvalId}\"`,\n );\n assertUnanswered(request);\n return {\n type: \"run/input\",\n requestId: request.id,\n response: {\n decision: options.approved ? \"approve\" : \"reject\",\n ...(options.reason !== undefined && { message: options.reason }),\n },\n };\n};\n"],"mappings":";AAIA,MAAMI,oBAAoBC,YAA+B;CACvD,IAAIA,QAAQC,aAAa,MACvB,MAAM,IAAIC,MACR,6BAA6BF,QAAQG,GAAE,sBACzC;AACJ;AAEA,MAAaC,0BACXC,eACAC,YAMoB;CACpB,MAAMN,UAAUK,cAAcM,MAC3BC,MAAMA,EAAEC,SAAS,eAAeD,EAAEL,eAAeD,QAAQC,UAC5D;CACA,IAAIP,YAAYc,KAAAA,GACd,MAAM,IAAIZ,MACR,wDAAwDI,QAAQC,WAAU,EAC5E;CACFR,iBAAiBC,OAAO;CACxB,OAAO;EACLa,MAAM;EACNE,WAAWf,QAAQG;EACnBF,UAAU;GACRe,QAAQV,QAAQE;GAChB,GAAIF,QAAQG,WAAW,EAAEA,SAAS,KAAK;GACvC,GAAIH,QAAQI,aAAaI,KAAAA,KAAa,EAAEJ,UAAUJ,QAAQI,SAAS;EACrE;CACF;AACF;AAEA,MAAaO,4BACXZ,eACAC,YACoB;CACpB,MAAMN,UAAUK,cAAcM,MAC3BC,MAAMA,EAAEC,SAAS,mBAAmBD,EAAET,OAAOG,QAAQY,UACxD;CACA,IAAIlB,YAAYc,KAAAA,GACd,MAAM,IAAIZ,MACR,8CAA8CI,QAAQY,WAAU,EAClE;CACFnB,iBAAiBC,OAAO;CACxB,OAAO;EACLa,MAAM;EACNE,WAAWf,QAAQG;EACnBF,UAAU;GACRkB,UAAUb,QAAQc,WAAW,YAAY;GACzC,GAAId,QAAQe,WAAWP,KAAAA,KAAa,EAAEQ,SAAShB,QAAQe,OAAO;EAChE;CACF;AACF"}
1
+ {"version":3,"file":"inputRequests.js","names":["RespondToToolApprovalOptions","ReadonlyJSONValue","AssistantTransportThread","assertUnanswered","request","InputRequestState","response","Error","id","resolveToolResultInput","inputRequests","options","toolCallId","result","isError","artifact","RunInputCommand","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 { AssistantTransportThread } from \"./AssistantTransportThread\";\n\nconst assertUnanswered = (\n request: AssistantTransportThread.InputRequestState,\n) => {\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 AssistantTransportThread.InputRequestState[],\n options: {\n toolCallId: string;\n result: ReadonlyJSONValue;\n isError: boolean;\n artifact?: ReadonlyJSONValue | undefined;\n },\n): AssistantTransportThread.RunInputCommand => {\n const request = inputRequests.find(\n (r) => r.type === \"tool-call\" && r.toolCallId === options.toolCallId,\n );\n if (request === undefined)\n throw new Error(\n `statewire: no tool-call input request for tool call \"${options.toolCallId}\"`,\n );\n assertUnanswered(request);\n return {\n type: \"run/input\",\n requestId: request.id,\n response: {\n output: options.result,\n ...(options.isError && { isError: true }),\n ...(options.artifact !== undefined && { artifact: options.artifact }),\n },\n };\n};\n\nexport const resolveToolApprovalInput = (\n inputRequests: readonly AssistantTransportThread.InputRequestState[],\n options: RespondToToolApprovalOptions,\n): AssistantTransportThread.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,MAAMG,oBACJC,YACG;CACH,IAAIA,QAAQE,aAAa,MACvB,MAAM,IAAIC,MACR,6BAA6BH,QAAQI,GAAE,sBACzC;AACJ;AAEA,MAAaC,0BACXC,eACAC,YAM6C;CAC7C,MAAMP,UAAUM,cAAcO,MAC3BC,MAAMA,EAAEC,SAAS,eAAeD,EAAEN,eAAeD,QAAQC,UAC5D;CACA,IAAIR,YAAYgB,KAAAA,GACd,MAAM,IAAIb,MACR,wDAAwDI,QAAQC,WAAU,EAC5E;CACFT,iBAAiBC,OAAO;CACxB,OAAO;EACLe,MAAM;EACNE,WAAWjB,QAAQI;EACnBF,UAAU;GACRgB,QAAQX,QAAQE;GAChB,GAAIF,QAAQG,WAAW,EAAEA,SAAS,KAAK;GACvC,GAAIH,QAAQI,aAAaK,KAAAA,KAAa,EAAEL,UAAUJ,QAAQI,SAAS;EACrE;CACF;AACF;AAEA,MAAaQ,4BACXb,eACAC,YAC6C;CAC7C,MAAMP,UAAUM,cAAcO,MAC3BC,MAAMA,EAAEC,SAAS,mBAAmBD,EAAEV,OAAOG,QAAQa,UACxD;CACA,IAAIpB,YAAYgB,KAAAA,GACd,MAAM,IAAIb,MACR,8CAA8CI,QAAQa,WAAU,EAClE;CACFrB,iBAAiBC,OAAO;CACxB,OAAO;EACLe,MAAM;EACNE,WAAWjB,QAAQI;EACnBF,UAAU;GACRmB,UAAUd,QAAQe,WAAW,YAAY;GACzC,GAAIf,QAAQgB,WAAWP,KAAAA,KAAa,EAAEQ,SAASjB,QAAQgB,OAAO;EAChE;CACF;AACF"}
@@ -1,11 +1,11 @@
1
- import { RunCommand, RunQueueItem, RunReloadCommand, RunUserMessage, TextPart } from "./types.js";
1
+ import { AssistantTransportThread } from "./AssistantTransportThread.js";
2
2
  import { AppendMessage, ExternalThreadQueueAdapter } from "@assistant-ui/core";
3
3
  //#region src/runCommands.d.ts
4
- declare const toWireMessage: (message: AppendMessage, id: string) => RunUserMessage;
5
- declare const toQueueItemState: (item: RunQueueItem) => {
4
+ declare const toWireMessage: (message: AppendMessage, id: string) => AssistantTransportThread.RunUserMessage;
5
+ declare const toQueueItemState: (item: AssistantTransportThread.RunQueueItem) => {
6
6
  id: string;
7
7
  prompt: string;
8
- parts: (TextPart | {
8
+ parts: (AssistantTransportThread.TextPart | {
9
9
  filename?: string;
10
10
  type: "file";
11
11
  data: string;
@@ -17,11 +17,11 @@ declare const viewedLeafId: (messages: readonly {
17
17
  }[]) => string | null;
18
18
  declare const createRunQueueAdapter: (messages: readonly {
19
19
  id: string;
20
- }[], queueItems: readonly RunQueueItem[], steerQueueItems: readonly RunQueueItem[] | undefined, dispatch: (command: RunCommand) => void) => ExternalThreadQueueAdapter;
20
+ }[], queueItems: readonly AssistantTransportThread.RunQueueItem[], steerQueueItems: readonly AssistantTransportThread.RunQueueItem[] | undefined, dispatch: (command: AssistantTransportThread.RunCommand) => void) => ExternalThreadQueueAdapter;
21
21
  declare const resolveReloadCommand: (messages: readonly {
22
22
  id: string;
23
23
  role: string;
24
- }[], parentId: string | null) => RunReloadCommand;
24
+ }[], parentId: string | null) => AssistantTransportThread.RunReloadCommand;
25
25
  //#endregion
26
26
  export { createRunQueueAdapter, resolveReloadCommand, toQueueItemState, toWireMessage, viewedLeafId };
27
27
  //# sourceMappingURL=runCommands.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"runCommands.d.ts","names":[],"sources":["../src/runCommands.ts"],"mappings":";;;cAca,gBACX,SAAS,eACT,eACC;cAqCU,mBAAoB,MAAM;;;UAAA;;;;;;;cA0B1B,eACX;EAAqB;;cAGV,wBACX;EAAqB;KACrB,qBAAqB,gBACrB,0BAA0B,4BAC1B,WAAW,SAAS,wBACnB;cA+CU,uBACX;EAAqB;EAAY;KACjC,4BACC"}
1
+ {"version":3,"file":"runCommands.d.ts","names":[],"sources":["../src/runCommands.ts"],"mappings":";;;cAOa,gBACX,SAAS,eACT,eACC,yBAAyB;cAwCf,mBACX,MAAM,yBAAyB;;;UAAA,yBAAA;;;;;;;cA2BpB,eACX;EAAqB;;cAGV,wBACX;EAAqB;KACrB,qBAAqB,yBAAyB,gBAC9C,0BAA0B,yBAAyB,4BACnD,WAAW,SAAS,yBAAyB,wBAC5C;cA+CU,uBACX;EAAqB;EAAY;KACjC,4BACC,yBAAyB"}
@@ -1 +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","viewedLeafId","messages","at","createRunQueueAdapter","queueItems","steerQueueItems","dispatch","command","laneOf","queueItemId","some","items","steerItems","enqueue","crypto","randomUUID","anchorMessageId","steer","move","lane","fields","messageId","edit","wireMessage","remove","resolveReloadCommand","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 viewedLeafId = (\n messages: readonly { id: string }[],\n): string | null => messages.at(-1)?.id ?? null;\n\nexport const createRunQueueAdapter = (\n messages: readonly { id: string }[],\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 anchorMessageId: viewedLeafId(messages),\n }),\n steer: (message) =>\n dispatch({\n type: \"run/steer\",\n message: toWireMessage(message, crypto.randomUUID()),\n anchorMessageId: viewedLeafId(messages),\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,aAA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,SAASyD;GAAY,CAClD;EACF;EACAC,SAASf,gBACPH,SAAS;GAAE5B,MAAM;GAAe2C,WAAWZ;EAAY,CAAC;CAC5D;AACF;AAEA,MAAagB,wBACXxB,UACAyB,aACqB;CACrB,MAAMC,QACJD,aAAa,OACT,IACAzB,SAAS2B,WAAW9D,YAAYA,QAAQC,OAAO2D,QAAQ,IAAI;CACjE,IAAIA,aAAa,QAAQC,UAAU,GACjC,MAAM,IAAI1D,MAAM,iCAAiCyD,SAAQ,aAAc;CACzE,MAAMG,SAAS5B,SAAS0B;CACxB,IAAIE,WAAW1C,KAAAA,KAAa0C,OAAO7D,SAAS,aAC1C,MAAM,IAAIC,MACR,mEACF;CACF,OAAO;EAAES,MAAM;EAAcoD,UAAUD,OAAO9D;CAAG;AACnD"}
1
+ {"version":3,"file":"runCommands.js","names":["AppendMessage","ExternalThreadQueueAdapter","QueuePlacement","AssistantTransportThread","toWireMessage","message","id","RunUserMessage","role","Error","files","FilePart","texts","source","content","attachments","flatMap","a","part","type","push","text","mediaType","url","image","mimeType","data","filename","undefined","parts","TextPart","length","const","join","toQueueItemState","item","RunQueueItem","prompt","map","placementFields","placement","insertAfter","insertBefore","viewedLeafId","messages","at","createRunQueueAdapter","queueItems","steerQueueItems","dispatch","command","RunCommand","laneOf","queueItemId","some","items","steerItems","enqueue","crypto","randomUUID","anchorMessageId","steer","move","lane","fields","messageId","edit","wireMessage","remove","resolveReloadCommand","parentId","RunReloadCommand","index","findIndex","target","sourceId"],"sources":["../src/runCommands.ts"],"sourcesContent":["import type {\n AppendMessage,\n ExternalThreadQueueAdapter,\n QueuePlacement,\n} from \"@assistant-ui/core\";\nimport type { AssistantTransportThread } from \"./AssistantTransportThread\";\n\nexport const toWireMessage = (\n message: AppendMessage,\n id: string,\n): AssistantTransportThread.RunUserMessage => {\n if (message.role !== \"user\")\n throw new Error(\"statewire: only user messages are supported\");\n const files: AssistantTransportThread.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: (\n | AssistantTransportThread.TextPart\n | AssistantTransportThread.FilePart\n )[] = [\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 = (\n item: AssistantTransportThread.RunQueueItem,\n) => ({\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 viewedLeafId = (\n messages: readonly { id: string }[],\n): string | null => messages.at(-1)?.id ?? null;\n\nexport const createRunQueueAdapter = (\n messages: readonly { id: string }[],\n queueItems: readonly AssistantTransportThread.RunQueueItem[],\n steerQueueItems: readonly AssistantTransportThread.RunQueueItem[] | undefined,\n dispatch: (command: AssistantTransportThread.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 anchorMessageId: viewedLeafId(messages),\n }),\n steer: (message) =>\n dispatch({\n type: \"run/steer\",\n message: toWireMessage(message, crypto.randomUUID()),\n anchorMessageId: viewedLeafId(messages),\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): AssistantTransportThread.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":";AAOA,MAAaI,iBACXC,SACAC,OAC4C;CAC5C,IAAID,QAAQG,SAAS,QACnB,MAAM,IAAIC,MAAM,6CAA6C;CAC/D,MAAMC,QAA6C,CAAA;CACnD,MAAME,QAAkB,CAAA;CACxB,MAAMC,SAAS,CACb,GAAGR,QAAQS,SACX,GAAIT,QAAQU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GAAY,CAClD;EACF;EACAC,SAASf,gBACPJ,SAAS;GAAE9B,MAAM;GAAe8C,WAAWZ;EAAY,CAAC;CAC5D;AACF;AAEA,MAAagB,wBACXzB,UACA0B,aAC8C;CAC9C,MAAME,QACJF,aAAa,OACT,IACA1B,SAAS6B,WAAWpE,YAAYA,QAAQC,OAAOgE,QAAQ,IAAI;CACjE,IAAIA,aAAa,QAAQE,UAAU,GACjC,MAAM,IAAI/D,MAAM,iCAAiC6D,SAAQ,aAAc;CACzE,MAAMI,SAAS9B,SAAS4B;CACxB,IAAIE,WAAW9C,KAAAA,KAAa8C,OAAOlE,SAAS,aAC1C,MAAM,IAAIC,MACR,mEACF;CACF,OAAO;EAAEU,MAAM;EAAcwD,UAAUD,OAAOpE;CAAG;AACnD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@assistant-ui/react-statewire",
3
- "version": "0.4.3",
3
+ "version": "0.4.4",
4
4
  "description": "assistant-ui thread binding for statewire backends",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -9,7 +9,7 @@ import {
9
9
  import { resource, useResource } from "@assistant-ui/tap";
10
10
  import type { ResourceElement } from "@assistant-ui/tap";
11
11
  import { ExternalThread } from "@assistant-ui/react";
12
- import type { ExternalThreadMessage } from "@assistant-ui/react";
12
+ import type { Assistant, ExternalThreadMessage } from "@assistant-ui/react";
13
13
  import {
14
14
  forwardTransformScopes,
15
15
  useAssistantClientRef,
@@ -19,6 +19,9 @@ import { createMessageQueue } from "@assistant-ui/core";
19
19
  import type {
20
20
  AddToolResultOptions,
21
21
  AppendMessage,
22
+ AttachmentAdapter,
23
+ LanguageModelConfig,
24
+ LanguageModelV1CallSettings,
22
25
  MessageQueueController,
23
26
  MessageQueueDriver,
24
27
  RespondToToolApprovalOptions,
@@ -26,6 +29,7 @@ import type {
26
29
  ThreadMessage,
27
30
  ToolExecutionStatus,
28
31
  } from "@assistant-ui/core";
32
+ import type { ReadonlyJSONValue } from "assistant-stream/utils";
29
33
  import { ToolInvocationTracker } from "@assistant-ui/core/internal";
30
34
  import { useStatewire } from "statewire";
31
35
  import { AssistantTransportHost } from "./host";
@@ -46,11 +50,6 @@ import {
46
50
  resolveToolApprovalInput,
47
51
  resolveToolResultInput,
48
52
  } from "./inputRequests";
49
- import type {
50
- AssistantTransportCommand,
51
- AssistantTransportOptions,
52
- InputRequestState,
53
- } from "./types";
54
53
 
55
54
  const EMPTY_TOOL_STATUSES: Record<string, ToolExecutionStatus> = {};
56
55
  const EMPTY_QUEUE_ITEMS: MessageQueueController["adapter"]["items"] = [];
@@ -62,11 +61,11 @@ export const symbolAssistantTransportExtras = Symbol(
62
61
 
63
62
  export type AssistantTransportExtras = {
64
63
  [symbolAssistantTransportExtras]: true;
65
- sendCommand: (command: AssistantTransportCommand) => void;
64
+ sendCommand: (command: AssistantTransportThread.Command) => void;
66
65
  reconnect: () => void;
67
66
  state: unknown;
68
67
  /** The host's parked input requests; absent when the converter does not project them. */
69
- inputRequests?: readonly InputRequestState[];
68
+ inputRequests?: readonly AssistantTransportThread.InputRequestState[];
70
69
  };
71
70
 
72
71
  export const asAssistantTransportExtras = (
@@ -99,7 +98,7 @@ const messagesContainToolCall = (
99
98
  );
100
99
 
101
100
  const useAssistantTransportThread = (
102
- options: AssistantTransportOptions<any>,
101
+ options: AssistantTransportThread.Options<any>,
103
102
  ): ClientOutput<"thread"> => {
104
103
  const clientRef = useAssistantClientRef();
105
104
  const [getRunContext] = useState(() => (): HostRunContext => {
@@ -128,7 +127,7 @@ const useAssistantTransportThread = (
128
127
  const queue = queueCell.current;
129
128
 
130
129
  const dispatch = useCallback(
131
- (command: AssistantTransportCommand, opts?: SendOptions) => {
130
+ (command: AssistantTransportThread.Command, opts?: SendOptions) => {
132
131
  void commands.send(command, opts).catch(() => {});
133
132
  },
134
133
  [commands],
@@ -218,7 +217,7 @@ const useAssistantTransportThread = (
218
217
 
219
218
  const handleAppend = (message: AppendMessage) => {
220
219
  const startRun = message.startRun ?? message.role === "user";
221
- const command: AssistantTransportCommand = {
220
+ const command: AssistantTransportThread.Command = {
222
221
  type: "run/steer",
223
222
  message: toWireMessage(message, crypto.randomUUID()),
224
223
  anchorMessageId: viewedLeafId(convertedRef.current.messages),
@@ -237,7 +236,7 @@ const useAssistantTransportThread = (
237
236
  const handleEdit = (message: AppendMessage) => {
238
237
  if (message.sourceId == null)
239
238
  throw new Error("statewire: run/edit requires a sourceId");
240
- const command: AssistantTransportCommand = {
239
+ const command: AssistantTransportThread.Command = {
241
240
  type: "run/edit",
242
241
  message: toWireMessage(message, crypto.randomUUID()),
243
242
  sourceId: message.sourceId,
@@ -412,12 +411,257 @@ const useAssistantTransportThread = (
412
411
  };
413
412
 
414
413
  export const AssistantTransportThread = <T>(
415
- options: AssistantTransportOptions<T>,
414
+ options: AssistantTransportThread.Options<T>,
416
415
  ): ResourceElement<ClientOutput<"thread">> =>
417
416
  resource(useAssistantTransportThread)(
418
- options as AssistantTransportOptions<any>,
417
+ options as AssistantTransportThread.Options<any>,
419
418
  );
420
419
 
420
+ export namespace AssistantTransportThread {
421
+ type UserCommands = Assistant.Commands[keyof Assistant.Commands];
422
+
423
+ export type TextPart = {
424
+ readonly type: "text";
425
+ readonly text: string;
426
+ };
427
+
428
+ export type FilePart = {
429
+ readonly type: "file";
430
+ readonly mediaType: string;
431
+ readonly url: string;
432
+ readonly filename?: string;
433
+ };
434
+
435
+ export type RunUserMessage = {
436
+ readonly id: string;
437
+ readonly role: "user";
438
+ readonly parts: readonly (TextPart | FilePart)[];
439
+ readonly metadata?: Record<string, unknown>;
440
+ };
441
+
442
+ /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */
443
+ export type RunPlacement = {
444
+ readonly insertAfter?: string | null;
445
+ readonly insertBefore?: string | null;
446
+ };
447
+
448
+ export type RunEnqueueCommand = {
449
+ readonly type: "run/enqueue";
450
+ } & (
451
+ | {
452
+ readonly message: RunUserMessage;
453
+ /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */
454
+ readonly anchorMessageId?: string | null;
455
+ }
456
+ | { readonly messageId: string }
457
+ ) &
458
+ RunPlacement;
459
+
460
+ export type RunSteerCommand = {
461
+ readonly type: "run/steer";
462
+ } & (
463
+ | {
464
+ readonly message: RunUserMessage;
465
+ /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */
466
+ readonly anchorMessageId?: string | null;
467
+ }
468
+ | { readonly messageId: string }
469
+ ) &
470
+ RunPlacement;
471
+
472
+ export type RunDequeueCommand = {
473
+ readonly type: "run/dequeue";
474
+ readonly messageId: string;
475
+ };
476
+
477
+ export type RunEditCommand = {
478
+ readonly type: "run/edit";
479
+ readonly message: RunUserMessage;
480
+ readonly sourceId: string;
481
+ };
482
+
483
+ export type RunContinueCommand = {
484
+ readonly type: "run/continue";
485
+ };
486
+
487
+ export type ToolCallInputRequest = {
488
+ readonly type: "tool-call";
489
+ readonly id: string;
490
+ readonly toolCallId: string;
491
+ };
492
+
493
+ export type ToolApprovalInputRequest = {
494
+ readonly type: "tool-approval";
495
+ readonly id: string;
496
+ readonly toolCallId: string;
497
+ };
498
+
499
+ export type CustomInputRequest = {
500
+ readonly type: string;
501
+ readonly id: string;
502
+ readonly [key: string]: ReadonlyJSONValue | undefined;
503
+ };
504
+
505
+ /** A host request parking the run until answered; open union for custom types. */
506
+ export type InputRequest =
507
+ | ToolCallInputRequest
508
+ | ToolApprovalInputRequest
509
+ | CustomInputRequest;
510
+
511
+ export type ToolCallInputResponse = {
512
+ readonly output: ReadonlyJSONValue;
513
+ /** Default false; when true, `output` carries the error payload. */
514
+ readonly isError?: boolean;
515
+ readonly artifact?: ReadonlyJSONValue;
516
+ };
517
+
518
+ export type ToolApprovalInputResponse = {
519
+ readonly decision: "approve" | "reject" | "edit" | "respond";
520
+ readonly editedArgs?: ReadonlyJSONValue;
521
+ readonly message?: string;
522
+ };
523
+
524
+ export type InputResponse = ReadonlyJSONValue;
525
+
526
+ export type RunInputCommand = {
527
+ readonly type: "run/input";
528
+ readonly requestId: string;
529
+ readonly response: InputResponse;
530
+ };
531
+
532
+ /** An input request projected out of the host state with its response echo. */
533
+ export type InputRequestState = InputRequest & {
534
+ readonly response: InputResponse | null;
535
+ };
536
+
537
+ export type RunReloadCommand = {
538
+ readonly type: "run/reload";
539
+ readonly sourceId: string;
540
+ };
541
+
542
+ export type RunCommand =
543
+ | RunEnqueueCommand
544
+ | RunSteerCommand
545
+ | RunDequeueCommand
546
+ | RunEditCommand
547
+ | RunContinueCommand
548
+ | RunReloadCommand
549
+ | RunInputCommand;
550
+
551
+ export type Command = RunCommand | UserCommands;
552
+
553
+ /** A queued message projected out of the host state, wire shape. */
554
+ export type RunQueueItem = {
555
+ readonly id: string;
556
+ readonly parts: readonly (TextPart | FilePart)[];
557
+ };
558
+
559
+ export type State = {
560
+ readonly messages: readonly ThreadMessage[];
561
+ readonly state?: ReadonlyJSONValue;
562
+ readonly isRunning: boolean;
563
+ /**
564
+ * The host's regular queue lane projected out of the state. Returning it
565
+ * (even empty) turns on the server-side queue: sends become `run/enqueue`
566
+ * / `run/steer` commands and item controls send the `run/*` queue
567
+ * commands. Presence must be stable across conversions and excludes the
568
+ * client-local `capabilities.queue` buffer.
569
+ */
570
+ readonly queue?: readonly RunQueueItem[];
571
+ /** The host's steer lane; requires `queue`. Absent means empty. */
572
+ readonly steerQueue?: readonly RunQueueItem[];
573
+ /**
574
+ * The host's parked input requests projected out of the state. Returning it
575
+ * (even empty) routes tool results and approvals with a matching pending
576
+ * request through `run/input`. Presence must be stable across conversions.
577
+ */
578
+ readonly inputRequests?: readonly AssistantTransportThread.InputRequestState[];
579
+ };
580
+
581
+ export type ConnectionMetadata = {
582
+ pendingCommands: Command[];
583
+ isSending: boolean;
584
+ toolStatuses: Record<string, ToolExecutionStatus>;
585
+ };
586
+
587
+ export type StateConverter<T> = (
588
+ state: T,
589
+ connectionMetadata: ConnectionMetadata,
590
+ ) => State;
591
+
592
+ export type HeadersValue = Record<string, string> | Headers;
593
+
594
+ export type Protocol = "data-stream" | "assistant-transport";
595
+
596
+ export type SendCommandsRequestBody = {
597
+ commands: Command[];
598
+ state: unknown;
599
+ system: string | undefined;
600
+ tools: Record<string, unknown> | undefined;
601
+ callSettings: LanguageModelV1CallSettings | undefined;
602
+ config: LanguageModelConfig | undefined;
603
+ threadId: string | null;
604
+ parentId?: string | null;
605
+ [key: string]: unknown;
606
+ };
607
+
608
+ export type Options<T> = {
609
+ initialState: T;
610
+ converter: StateConverter<T>;
611
+ api: string;
612
+ resumeApi?: string | undefined;
613
+ protocol?: Protocol | undefined;
614
+ headers: HeadersValue | (() => Promise<HeadersValue>);
615
+ body?: object | (() => Promise<object | undefined>) | undefined;
616
+ /** Transform the fully assembled request body before it is sent. */
617
+ prepareSendCommandsRequest?:
618
+ | ((
619
+ body: SendCommandsRequestBody,
620
+ ) => Record<string, unknown> | Promise<Record<string, unknown>>)
621
+ | undefined;
622
+ onResponse?: ((response: Response) => void) | undefined;
623
+ onFinish?: (() => void) | undefined;
624
+ onError?:
625
+ | ((
626
+ error: Error,
627
+ params: {
628
+ commands: Command[];
629
+ updateState: (updater: (state: T) => T) => void;
630
+ },
631
+ ) => void | Promise<void>)
632
+ | undefined;
633
+ /**
634
+ * Called when commands are cancelled. After an error, queued commands are
635
+ * cancelled once `onError` settles; `error` then carries the cause.
636
+ */
637
+ onCancel?:
638
+ | ((params: {
639
+ commands: Command[];
640
+ updateState: (updater: (state: T) => T) => void;
641
+ error?: Error;
642
+ }) => void)
643
+ | undefined;
644
+ capabilities?:
645
+ | {
646
+ edit?: boolean | undefined;
647
+ /**
648
+ * Buffer messages sent during a run in an in-memory queue and dispatch
649
+ * them once the run settles. Steering interrupts the active run.
650
+ * Mutually exclusive with the converter's `queue` projection.
651
+ */
652
+ queue?: boolean | undefined;
653
+ /** The host supports `run/continue` (a continue affordance on aborted runs). */
654
+ continue?: boolean | undefined;
655
+ }
656
+ | undefined;
657
+ adapters?:
658
+ | {
659
+ attachments?: AttachmentAdapter | undefined;
660
+ }
661
+ | undefined;
662
+ };
663
+ }
664
+
421
665
  // Scope transforms are keyed by the underlying hook, not the resource wrapper.
422
666
  forwardTransformScopes(
423
667
  useAssistantTransportThread,