@assistant-ui/react-statewire 0.16.0 → 0.16.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -166,6 +166,8 @@ declare namespace StatewireThread {
|
|
|
166
166
|
export type RunState = {
|
|
167
167
|
/** The run's identity — client-minted, adopted by the host at run creation; persists through steers, input-required, and error/stop, retiring only when the queue drains and the run completes. */
|
|
168
168
|
readonly runId: string | null;
|
|
169
|
+
/** Counts the entry's dispatches; a `run/stop` carrying a stale epoch rejects. */
|
|
170
|
+
readonly epoch?: number;
|
|
169
171
|
readonly status: RunStatus;
|
|
170
172
|
readonly queue: readonly RunsQueueEntry[];
|
|
171
173
|
readonly steerQueue: readonly RunsQueueEntry[];
|
|
@@ -197,6 +199,8 @@ declare namespace StatewireThread {
|
|
|
197
199
|
export type Runs = {
|
|
198
200
|
/** The live run's id — non-null whenever a run entry is live (running, input-required, error/stop); the target for `run/*` sends. */
|
|
199
201
|
readonly runId: string | null;
|
|
202
|
+
/** Counts the entry's dispatches; rides `run/stop` so a replayed stop cannot end a later leg. */
|
|
203
|
+
readonly epoch?: number;
|
|
200
204
|
readonly queue: readonly RunsQueueEntry[];
|
|
201
205
|
readonly steerQueue: readonly RunsQueueEntry[];
|
|
202
206
|
/** The dispatch record — the unapplied batch handed to the run, cleared at applied. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;cAwCa;cAEA,oBAAqB,oBAAkB,gBAAgB;
|
|
1
|
+
{"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;cAwCa;cAEA,oBAAqB,oBAAkB,gBAAgB;cA+RvD,kBAAmB,GAC9B,SAAS,gBAAgB,QAAQ,OAChC,gBAAgB;kBAGF;OACV,eAAe,UAAU,eAAe,UAAU;cAE3C,UAAU,KAAK,gBAAgB,UAAU;cAEz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AiB;IACjB;;IAEA,YAAY,gBAAgB;;IAE5B,MAAM;;;cAII;aACD,mBAAmB;aACnB,QAAQ;;cAGP,eAAe,MACzB,OAAO,GACP,oBAAoB,uBACjB;;;;;cAMO;aACD;cACC,cAAc;;cAGd,QAAQ;IAClB,WAAW,UAAU;;IAErB,cAAc;IACd,WAAW,eAAe;;IAE1B,aACI,gBAAgB,WACd,GACA,mBAAmB;;IAIzB,cAAc,gBAAgB,YAAY,YAAY;;;;;;IAMtD;;IAEA,qBAAqB;;IAErB,oBAEM,QAAQ,UAAU,cAChB,mBAAmB,2BAErB;MAAO,OAAO,YAAY;;;IAIhC,kBACM,OAAO,YAAY,IAAI;MAAO,SAAS,UAAU;;;IAGvD,uBACM,YAAY,gBAAgB;IAElC,YAAY,OAAO;IACnB;MAEM;;MAEA;;MAEA;;IAGN;MAEM,cAAc;MACd,SAAS;MACT,WAAW;;;;;;YAOT;cACE;MACR,YAAY,gBAAgB;MAC5B,UAAU,gBAAgB;MAC1B,YAAY,gBAAgB;MAC5B,SAAS,gBAAgB;MACzB,aAAa,gBAAgB;MAC7B,WAAW,gBAAgB;MAC3B,UAAU,gBAAgB"}
|
package/dist/StatewireThread.js
CHANGED
|
@@ -93,6 +93,7 @@ const useStatewireThread = (options) => {
|
|
|
93
93
|
status: entries === void 0 ? "loading" : entry?.status ?? "ready",
|
|
94
94
|
runs: entry === void 0 ? RESTING_RUNS : {
|
|
95
95
|
runId: entry.runId,
|
|
96
|
+
...entry.epoch !== void 0 && { epoch: entry.epoch },
|
|
96
97
|
queue: entry.queue,
|
|
97
98
|
steerQueue: entry.steerQueue,
|
|
98
99
|
...entry.dispatching !== void 0 && { dispatching: entry.dispatching },
|
|
@@ -182,7 +183,8 @@ const useStatewireThread = (options) => {
|
|
|
182
183
|
if (payload !== void 0 && (typeof payload !== "object" || payload === null || Array.isArray(payload))) throw new Error("statewire: stopPayload must return a plain object");
|
|
183
184
|
commands["run/stop"]({
|
|
184
185
|
...payload,
|
|
185
|
-
runId: runs.runId
|
|
186
|
+
runId: runs.runId,
|
|
187
|
+
...runs.epoch !== void 0 && { epoch: runs.epoch }
|
|
186
188
|
}).catch((error_0) => {
|
|
187
189
|
latest.current.onError?.(error_0);
|
|
188
190
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","Assistant","forwardTransformScopes","useAssistantClientRef","ClientOutput","AddToolResultOptions","AppendMessage","AttachmentAdapter","FeedbackAdapter","ModelContext","RespondToToolApprovalOptions","SpeechSynthesisAdapter","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","StatewireClient","createRunQueueAdapter","resolveEditCommand","resolveReloadCommand","sendFields","toWireMessage","resolveToolApprovalInput","resolveToolResultInput","runsOptimistic","AnyCommands","Record","args","symbolStatewireExtras","Symbol","asStatewireExtras","extras","StatewireThread","Extras","Error","NO_INPUT_REQUESTS","InputRequestState","RESTING_RUNS","Runs","runId","queue","steerQueue","ambientContextOf","context","system","undefined","tools","callSettings","config","useStatewireThread","options","Options","latest","current","pending","setPending","Command","retire","command","prev","includes","filter","c","state","commands","connection","setContext","isBusy","transport","initialState","optimistic","draft","ctx","materialize","onCommandChange","update","status","params","onStateChange","onConnectionChange","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","subscribe","dispatch","settled","type","catch","error","onError","threadRef","dispatchSend","message","sourceId","text","content","flatMap","part","join","setText","composer","next","runs","ThreadStatus","entries","RunState","entry","dispatching","stopping","nextDispatch","inputRequests","converter","metadata","ConnectionMetadata","pendingCommands","isSending","length","converted","State","messages","liveRunId","sendCommand","reconnect","handleAppend","crypto","randomUUID","handleReload","parentId","handleEdit","thread","isRunning","attachmentAdapter","adapters","attachments","speechAdapter","speech","feedbackAdapter","feedback","onNew","capabilities","edit","onEdit","continue","onResume","reload","onReload","onAddToolResult","toolOptions","onRespondToToolApproval","approval","onCancel","payload","stopPayload","Array","isArray","T","UserCommands","Commands","Transport","TextPart","FilePart","mediaType","url","filename","UserMessage","id","role","parts","Placement","insertAfter","insertBefore","RunEnqueueCommand","runAnchorMessageId","messageId","RunSteerCommand","RunDequeueCommand","RunEditCommand","RunContinueCommand","ToolCallInputRequest","toolCallId","ToolApprovalInputRequest","CustomInputRequest","InputRequest","InputResponse","RunInputCommand","requestId","response","meta","RunReloadCommand","RunCommand","RunQueueItem","RunStatus","RunsQueueEntry","RunsInputOutcome","request","RunsDispatch","trigger","rollbackTo","rootMeta","inputOutcomes","RunsStopping","reason","RunsError","MaterializeEffects","append","rollback","to","RunsState","Exclude","ConnectionState","StateConverter","connectionMetadata","StopPayload","Optimistic","Materialize","NonNullable","CommandUpdate","changes","Changes","Connection","runEnqueue","runSteer","runDequeue","runEdit","runContinue","runReload","runInput","hook"],"sources":["../src/StatewireThread.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { resource, useResource } from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/core/store\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/core/store\";\nimport type { Assistant } from \"@assistant-ui/core\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n AttachmentAdapter,\n FeedbackAdapter,\n ModelContext,\n RespondToToolApprovalOptions,\n SpeechSynthesisAdapter,\n ThreadMessage,\n} from \"@assistant-ui/core\";\nimport { toToolsJSONSchema } from \"assistant-stream\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { useStatewire } from \"statewire\";\nimport type { Statewire, StatewireClient } from \"statewire\";\nimport {\n createRunQueueAdapter,\n resolveEditCommand,\n resolveReloadCommand,\n sendFields,\n toWireMessage,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\nimport { runsOptimistic } from \"./runsOptimistic\";\n\ntype AnyCommands = Record<string, (...args: any[]) => unknown>;\n\nexport const symbolStatewireExtras = Symbol(\"statewire-extras\");\n\nexport const asStatewireExtras = (extras: unknown): StatewireThread.Extras => {\n if (\n typeof extras !== \"object\" ||\n extras == null ||\n !(symbolStatewireExtras in extras)\n )\n throw new Error(\n \"This method can only be called when you are using StatewireThread\",\n );\n\n return extras as StatewireThread.Extras;\n};\n\nconst NO_INPUT_REQUESTS: readonly StatewireThread.InputRequestState[] = [];\n\nconst RESTING_RUNS: StatewireThread.Runs = {\n runId: null,\n queue: [],\n steerQueue: [],\n};\n\nconst ambientContextOf = (context: ModelContext): Record<string, unknown> => ({\n ...(context.system !== undefined && { system: context.system }),\n ...(context.tools !== undefined && {\n tools: toToolsJSONSchema(context.tools),\n }),\n ...(context.callSettings !== undefined && {\n callSettings: context.callSettings,\n }),\n ...(context.config !== undefined && { config: context.config }),\n});\n\nconst useStatewireThread = (\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 { state, commands, connection, setContext, isBusy } = useStatewire<\n unknown,\n AnyCommands\n >({\n transport: options.transport,\n initialState: options.initialState,\n optimistic: (draft, command, ctx) => {\n runsOptimistic(draft, command, ctx);\n latest.current.optimistic?.(draft, command, ctx);\n },\n materialize: (draft: {}) => latest.current.materialize?.(draft),\n onCommandChange: (update, ctx) => {\n if (update.status === \"applied\" || update.status === \"settled\")\n retire(update.params[0]);\n latest.current.onCommandChange?.(update, ctx);\n },\n onStateChange: (state, ctx) => latest.current.onStateChange?.(state, ctx),\n onConnectionChange: (connection) =>\n latest.current.onConnectionChange?.(connection),\n });\n\n const clientRef = useAssistantClientRef();\n const setContextRef = useRef(setContext);\n setContextRef.current = setContext;\n const [syncState] = useState(() => ({ lastSent: undefined as unknown }));\n const { contextSync } = options;\n useEffect(() => {\n if (contextSync === undefined) return;\n const modelContext = (clientRef.current ?? clientRef.parent).modelContext();\n const send = () => {\n const value = ambientContextOf(modelContext.getModelContext());\n const key = JSON.stringify(value);\n if (key === syncState.lastSent) return;\n syncState.lastSent = key;\n setContextRef.current(value);\n };\n send();\n if (!modelContext.subscribe) {\n throw new Error(\n \"statewire: contextSync requires a subscribable model context\",\n );\n }\n return modelContext.subscribe(send);\n }, [contextSync, clientRef, syncState]);\n\n const dispatch = useCallback(\n (command: StatewireThread.Command) => {\n setPending((prev) => [...prev, command]);\n const settled = commands[command.type]!(command);\n settled.catch((error: Error) => {\n retire(command);\n latest.current.onError?.(error);\n });\n return settled;\n },\n [commands, retire],\n );\n\n const threadRef = useRef<ClientOutput<\"thread\"> | null>(null);\n const dispatchSend = useCallback(\n (command: StatewireThread.Command, message: AppendMessage) => {\n if (message.sourceId != null) return void dispatch(command);\n const text = message.content\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\");\n void dispatch(command).catch(() => {\n // Rejected send: put the text back unless the user typed since.\n // ExternalThread's setText is live-ref-backed and takes an updater.\n const setText = threadRef.current!.composer().setText as (\n next: string | ((prev: string) => string),\n ) => void;\n setText((prev) => (prev === \"\" ? text : prev));\n });\n },\n [dispatch],\n );\n\n const { status, runs } = useMemo((): {\n status: StatewireThread.ThreadStatus;\n runs: StatewireThread.Runs;\n } => {\n const entries = (\n state as { runs?: readonly StatewireThread.RunState[] } | undefined\n )?.runs;\n const entry = entries?.[0];\n return {\n status: entries === undefined ? \"loading\" : (entry?.status ?? \"ready\"),\n runs:\n entry === undefined\n ? RESTING_RUNS\n : {\n runId: entry.runId,\n queue: entry.queue,\n steerQueue: entry.steerQueue,\n ...(entry.dispatching !== undefined && {\n dispatching: entry.dispatching,\n }),\n ...(entry.stopping !== undefined && { stopping: entry.stopping }),\n ...(entry.nextDispatch !== undefined && {\n nextDispatch: entry.nextDispatch,\n }),\n ...(entry.inputRequests !== undefined && {\n inputRequests: entry.inputRequests,\n }),\n ...(entry.error !== undefined && { error: entry.error }),\n },\n };\n }, [state]);\n\n const { converter } = options;\n const metadata = useMemo(\n (): StatewireThread.ConnectionMetadata => ({\n pendingCommands: [...pending],\n isSending: pending.length > 0,\n connection,\n runs,\n }),\n [pending, connection, runs],\n );\n const converted = useMemo(\n (): StatewireThread.State => converter(state, metadata),\n [converter, state, metadata],\n );\n // Dispatch limbo is a materialize concern: the fold makes the record\n // concrete in state before conversion.\n const messages = converted.messages;\n const liveRunId = runs.runId;\n\n const queue = useMemo(\n () =>\n createRunQueueAdapter(\n messages,\n liveRunId,\n runs.queue,\n runs.steerQueue,\n dispatch,\n dispatchSend,\n ),\n [messages, liveRunId, runs, dispatch, dispatchSend],\n );\n\n const inputRequests = runs.inputRequests ?? NO_INPUT_REQUESTS;\n\n const extras = useMemo(\n (): StatewireThread.Extras => ({\n [symbolStatewireExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state,\n status,\n isBusy,\n inputRequests,\n runs,\n }),\n [\n dispatch,\n connection.reconnect,\n state,\n status,\n isBusy,\n inputRequests,\n runs,\n ],\n );\n\n const handleAppend = (message: AppendMessage) => {\n dispatchSend(\n message.sourceId != null\n ? resolveEditCommand(messages, message, liveRunId)\n : {\n type: \"run/steer\",\n ...sendFields(\n messages,\n liveRunId,\n toWireMessage(message, crypto.randomUUID()),\n ),\n },\n message,\n );\n };\n\n const handleReload = (parentId: string | null) => {\n dispatch(resolveReloadCommand(messages, parentId, liveRunId));\n };\n\n const handleEdit = (message: AppendMessage) => {\n dispatch(resolveEditCommand(messages, message, liveRunId));\n };\n\n const thread = useResource(\n ExternalThread({\n messages: messages as readonly ExternalThreadMessage[],\n isRunning: status === \"running\",\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n speechAdapter: options.adapters?.speech,\n feedbackAdapter: options.adapters?.feedback,\n onNew: handleAppend,\n queue,\n ...(options.capabilities?.edit && { onEdit: handleEdit }),\n ...(options.capabilities?.continue && {\n onResume: () =>\n dispatch({\n type: \"run/continue\",\n ...(liveRunId !== null && { runId: liveRunId }),\n }),\n }),\n ...(options.capabilities?.reload && { onReload: handleReload }),\n onAddToolResult: (toolOptions: AddToolResultOptions) =>\n dispatch(resolveToolResultInput(inputRequests, toolOptions, liveRunId)),\n onRespondToToolApproval: (approval: RespondToToolApprovalOptions) =>\n dispatch(resolveToolApprovalInput(inputRequests, approval, liveRunId)),\n onCancel: () => {\n const payload = latest.current.stopPayload?.();\n if (\n payload !== undefined &&\n (typeof payload !== \"object\" ||\n payload === null ||\n Array.isArray(payload))\n )\n throw new Error(\"statewire: stopPayload must return a plain object\");\n void commands[\"run/stop\"]!({ ...payload, runId: runs.runId }).catch(\n (error: Error) => {\n latest.current.onError?.(error);\n },\n );\n },\n }),\n );\n threadRef.current = thread;\n return thread;\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 type UserCommands = Assistant.Commands[keyof Assistant.Commands];\n\n export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;\n\n export type Extras = {\n [symbolStatewireExtras]: true;\n sendCommand: (command: Command) => void;\n reconnect: () => void;\n state: unknown;\n status: ThreadStatus;\n /** Negation of the server's broadcast idle level (a transport without idle is always busy). */\n isBusy: boolean;\n inputRequests: readonly InputRequestState[];\n runs: Runs;\n };\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 /** The run this command targets — the live run's id, or a fresh client-minted uuid on run-creating sends. */\n readonly runId: string;\n } & (\n | {\n readonly message: UserMessage;\n /** Run anchor: the message the new content grows after, null asserting an empty thread. Present on run-creating sends; absent when targeting the live run. */\n readonly runAnchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunSteerCommand = {\n readonly type: \"run/steer\";\n /** The run this command targets — the live run's id, or a fresh client-minted uuid on run-creating sends. */\n readonly runId: string;\n } & (\n | {\n readonly message: UserMessage;\n /** Run anchor: the message the new content grows after, null asserting an empty thread. Present on run-creating sends; absent when targeting the live run. */\n readonly runAnchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunDequeueCommand = {\n readonly type: \"run/dequeue\";\n readonly runId: string;\n readonly messageId: string;\n };\n\n export type RunEditCommand = {\n readonly type: \"run/edit\";\n /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */\n readonly runId: string;\n readonly message: UserMessage;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly runAnchorMessageId: string | null;\n };\n\n export type RunContinueCommand = {\n readonly type: \"run/continue\";\n readonly runId?: string;\n };\n\n export type ToolCallInputRequest = {\n readonly type: \"tool-call\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type ToolApprovalInputRequest = {\n readonly type: \"tool-approval\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type CustomInputRequest = {\n readonly type: string;\n readonly id: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A host request parking the run until answered; open union for custom types. */\n export type InputRequest =\n | ToolCallInputRequest\n | ToolApprovalInputRequest\n | CustomInputRequest;\n\n export type InputResponse = ReadonlyJSONValue;\n\n export type RunInputCommand = {\n readonly type: \"run/input\";\n readonly runId?: string;\n readonly requestId: string;\n readonly response: InputResponse;\n };\n\n /** An input request projected out of the host state; a present `response` key marks the entry answered. */\n export type InputRequestState = InputRequest & {\n readonly response?: InputResponse;\n /** The answer's `run/input` meta; absent when the answer carried none. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n export type RunReloadCommand = {\n readonly type: \"run/reload\";\n /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */\n readonly runId: string;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly runAnchorMessageId: string | null;\n };\n\n export type RunCommand =\n | RunEnqueueCommand\n | RunSteerCommand\n | RunDequeueCommand\n | RunEditCommand\n | RunContinueCommand\n | RunReloadCommand\n | RunInputCommand;\n\n export type Command = RunCommand | UserCommands;\n\n /** A queued message projected out of the host state, wire shape. */\n export type RunQueueItem = {\n readonly id: string;\n readonly parts: readonly (TextPart | FilePart)[];\n };\n\n /** Run subsystem status replicated by the host. */\n export type RunStatus = \"running\" | \"stopped\" | \"error\" | \"input-required\";\n\n /** The thread's status, derived from the state: `\"loading\"` while the runs mount is absent, `\"ready\"` while resting, otherwise the run's status. */\n export type ThreadStatus = \"loading\" | \"ready\" | RunStatus;\n\n /** A queue-lane entry as replicated: the user message plus host-stamped `meta`. */\n export type RunsQueueEntry = UserMessage & {\n /** Host-stamped opaque per-entry metadata. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n /** An input outcome riding a dispatch record: the request with its response (null = abandoned) and `run/input` meta. */\n export type RunsInputOutcome = {\n readonly request: InputRequest;\n readonly response: InputResponse | null;\n readonly meta: ReadonlyJSONValue | null;\n };\n\n /** The dispatch record — the unapplied batch handed to the run; absent between applied and the next dispatch or take. */\n export type RunsDispatch = {\n readonly trigger:\n | \"message-send\"\n | \"message-edit\"\n | \"message-reload\"\n | \"input-resume\"\n | \"error-continue\"\n | \"stop-continue\"\n | \"steer\";\n readonly messages: readonly RunsQueueEntry[];\n /** Present on rewind dispatches: truncate the thread at this id first; null names the root. */\n readonly rollbackTo?: string | null;\n /** The run-starting op's meta; present only when carried. */\n readonly rootMeta?: ReadonlyJSONValue;\n /** Present when input outcomes ride the dispatch; visible until applied. */\n readonly inputOutcomes?: readonly RunsInputOutcome[];\n };\n\n /** The stopping window: present while a stop of the live run is underway; `\"message-edit\"` / `\"message-reload\"` pair with `nextDispatch`. */\n export type RunsStopping = {\n readonly reason: \"stop\" | \"message-edit\" | \"message-reload\";\n };\n\n /** The replicated run error — set on an unhandled failure, cleared by the next user-initiated run. */\n export type RunsError = {\n readonly message: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A replicated run entry — one element of the mount's `runs` array. */\n export type RunState = {\n /** The run's identity — client-minted, adopted by the host at run creation; persists through steers, input-required, and error/stop, retiring only when the queue drains and the run completes. */\n readonly runId: string | null;\n readonly status: RunStatus;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */\n readonly dispatching?: RunsDispatch;\n readonly stopping?: RunsStopping;\n /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */\n readonly nextDispatch?: RunsDispatch;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n /** Set only by an unhandled throw; cleared by the next user-initiated run. */\n readonly error?: RunsError;\n };\n\n /** App-shaped effects `runsMaterialize` applies for the dispatch record. */\n export type MaterializeEffects = {\n /** Append one dispatched message to the app's committed message state. */\n append: (message: RunsQueueEntry) => void;\n /** Truncate to the rolled-back view first (null names the root); required for hosts that dispatch edits/reloads. */\n rollback?: (to: string | null) => void;\n };\n\n /** The runs mount as replicated: the run entries plus the top-level status projection. */\n export type RunsState = {\n /** Projection of `runs[0]?.status ?? \"ready\"`. */\n readonly status: Exclude<ThreadStatus, \"loading\">;\n /** At most one entry; empty while resting. */\n readonly runs: readonly RunState[];\n };\n\n /** The run subsystem's typed read — `runs[0]` of the state with unsettled commands folded in, resting defaults while no entry is live. */\n export type Runs = {\n /** The live run's id — non-null whenever a run entry is live (running, input-required, error/stop); the target for `run/*` sends. */\n readonly runId: string | null;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */\n readonly dispatching?: RunsDispatch;\n readonly stopping?: RunsStopping;\n /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */\n readonly nextDispatch?: RunsDispatch;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n /** Set only by an unhandled throw; cleared by the next user-initiated run. */\n readonly error?: RunsError;\n };\n\n export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `live`. */\n connection: StatewireClient.ConnectionState;\n /** The typed runs read. */\n runs: Runs;\n };\n\n /** Converter output: app-owned keys only — the lib projects the run mounts itself. */\n export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n /**\n * Payload of the built-in `run/stop` command. `reason` is the one well-known\n * field; apps extend it with their own JSON-serializable fields.\n */\n export type StopPayload = {\n readonly reason?: string | undefined;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n export type Options<T> = {\n transport: Transport<T>;\n /** The pre-attach state, replaced by the attach snapshot. `runs: []` projects ready (interactive from the first render); an absent runs mount projects loading until attach. */\n initialState: T;\n converter: StateConverter<T>;\n /** Folds app-owned keys for an unsettled command into the draft; runs after the lib's run-dialect reducer. */\n optimistic?:\n | StatewireClient.Optimistic<\n T,\n Record<string, (...args: any[]) => unknown>\n >\n | undefined;\n /** Makes dispatch records concrete in the draft (runs after the optimistic folds); without it, dispatch limbo stays out of `messages`. */\n materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;\n /**\n * \"command-send\" mirrors the client's ambient model context (system,\n * tools, callSettings, config) to the server over the command channel —\n * on connect and whenever it changes. Requires a remote transport.\n */\n contextSync?: \"command-send\" | undefined;\n /** Supplies the `run/stop` command's payload; omitted, stop sends no payload. */\n stopPayload?: (() => StopPayload) | undefined;\n /** Observes each command's lifecycle (queued, posted, applied, settled); runs after the built-in pending-command retirement. */\n onCommandChange?:\n | ((\n update: Statewire.CommandUpdate<\n Record<string, (...args: any[]) => unknown>\n >,\n ctx: { state: NonNullable<T> },\n ) => void)\n | undefined;\n /** Observes the transport state: fires with the attach snapshot, then once per change. */\n onStateChange?:\n | ((state: NonNullable<T>, ctx: { changes: Statewire.Changes }) => void)\n | undefined;\n /** Observes connection status transitions, starting with the initial status. */\n onConnectionChange?:\n | ((connection: StatewireClient.Connection) => void)\n | undefined;\n onError?: ((error: Error) => void) | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n /** The host supports `run/continue` (a continue affordance on aborted runs). */\n continue?: boolean | undefined;\n /** The host supports `run/reload` (regenerating an assistant message). */\n reload?: boolean | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n speech?: SpeechSynthesisAdapter | undefined;\n feedback?: FeedbackAdapter | undefined;\n }\n | undefined;\n };\n}\n\ndeclare module \"@assistant-ui/core\" {\n namespace Assistant {\n interface Commands {\n runEnqueue: StatewireThread.RunEnqueueCommand;\n runSteer: StatewireThread.RunSteerCommand;\n runDequeue: StatewireThread.RunDequeueCommand;\n runEdit: StatewireThread.RunEditCommand;\n runContinue: StatewireThread.RunContinueCommand;\n runReload: StatewireThread.RunReloadCommand;\n runInput: StatewireThread.RunInputCommand;\n }\n }\n}\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useStatewireThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;;;AAwCA,MAAasC,wBAAwBC,OAAO,k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,QAAQ4F,UAAUK;EACnCC,OAAOf;EACP7F;EACA,GAAIU,QAAQmG,cAAcC,QAAQ,EAAEC,QAAQb,WAAW;EACvD,GAAIxF,QAAQmG,cAAcG,YAAY,EACpCC,gBACE3D,SAAS;GACPE,MAAM;GACN,GAAIkC,cAAc,QAAQ,EAAE3F,OAAO2F,UAAU;EAC/C,CAAC,EACL;EACA,GAAIhF,QAAQmG,cAAcK,UAAU,EAAEC,UAAUnB,aAAa;EAC7DoB,kBAAkBC,gBAChB/D,SAASvE,uBAAuBiG,eAAeqC,aAAa3B,SAAS,CAAC;EACxE4B,0BAA0BC,aACxBjE,SAASxE,yBAAyBkG,eAAeuC,UAAU7B,SAAS,CAAC;EACvE8B,gBAAgB;GACd,MAAMC,UAAU7G,OAAOC,QAAQ6G,cAAc;GAC7C,IACED,YAAYpH,KAAAA,MACX,OAAOoH,YAAY,YAClBA,YAAY,QACZE,MAAMC,QAAQH,OAAO,IAEvB,MAAM,IAAI/H,MAAM,mDAAmD;GACrE,SAAc,WAAW,CAAE;IAAE,GAAG+H;IAAS1H,OAAOyE,KAAKzE;GAAM,CAAC,CAAC,CAAC0D,OAC3DC,YAAiB;IAChB9C,OAAOC,QAAQ8C,UAAUD,OAAK;GAChC,CACF;EACF;CACF,CAAC,CACH;CACAE,UAAU/C,UAAUsF;CACpB,OAAOA;AACT;AAEA,MAAa3G,mBACXkB,YAEAvD,SAASsD,kBAAkB,CAAC,CAACC,OAAuC;AA0WtEjD,uBACEgD,oBACAnD,eAAe+C,KAAAA,CAAkB,CAAC,CAACgM,IACrC"}
|
|
1
|
+
{"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","Assistant","forwardTransformScopes","useAssistantClientRef","ClientOutput","AddToolResultOptions","AppendMessage","AttachmentAdapter","FeedbackAdapter","ModelContext","RespondToToolApprovalOptions","SpeechSynthesisAdapter","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","StatewireClient","createRunQueueAdapter","resolveEditCommand","resolveReloadCommand","sendFields","toWireMessage","resolveToolApprovalInput","resolveToolResultInput","runsOptimistic","AnyCommands","Record","args","symbolStatewireExtras","Symbol","asStatewireExtras","extras","StatewireThread","Extras","Error","NO_INPUT_REQUESTS","InputRequestState","RESTING_RUNS","Runs","runId","queue","steerQueue","ambientContextOf","context","system","undefined","tools","callSettings","config","useStatewireThread","options","Options","latest","current","pending","setPending","Command","retire","command","prev","includes","filter","c","state","commands","connection","setContext","isBusy","transport","initialState","optimistic","draft","ctx","materialize","onCommandChange","update","status","params","onStateChange","onConnectionChange","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","subscribe","dispatch","settled","type","catch","error","onError","threadRef","dispatchSend","message","sourceId","text","content","flatMap","part","join","setText","composer","next","runs","ThreadStatus","entries","RunState","entry","epoch","dispatching","stopping","nextDispatch","inputRequests","converter","metadata","ConnectionMetadata","pendingCommands","isSending","length","converted","State","messages","liveRunId","sendCommand","reconnect","handleAppend","crypto","randomUUID","handleReload","parentId","handleEdit","thread","isRunning","attachmentAdapter","adapters","attachments","speechAdapter","speech","feedbackAdapter","feedback","onNew","capabilities","edit","onEdit","continue","onResume","reload","onReload","onAddToolResult","toolOptions","onRespondToToolApproval","approval","onCancel","payload","stopPayload","Array","isArray","T","UserCommands","Commands","Transport","TextPart","FilePart","mediaType","url","filename","UserMessage","id","role","parts","Placement","insertAfter","insertBefore","RunEnqueueCommand","runAnchorMessageId","messageId","RunSteerCommand","RunDequeueCommand","RunEditCommand","RunContinueCommand","ToolCallInputRequest","toolCallId","ToolApprovalInputRequest","CustomInputRequest","InputRequest","InputResponse","RunInputCommand","requestId","response","meta","RunReloadCommand","RunCommand","RunQueueItem","RunStatus","RunsQueueEntry","RunsInputOutcome","request","RunsDispatch","trigger","rollbackTo","rootMeta","inputOutcomes","RunsStopping","reason","RunsError","MaterializeEffects","append","rollback","to","RunsState","Exclude","ConnectionState","StateConverter","connectionMetadata","StopPayload","Optimistic","Materialize","NonNullable","CommandUpdate","changes","Changes","Connection","runEnqueue","runSteer","runDequeue","runEdit","runContinue","runReload","runInput","hook"],"sources":["../src/StatewireThread.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { resource, useResource } from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/core/store\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/core/store\";\nimport type { Assistant } from \"@assistant-ui/core\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n AttachmentAdapter,\n FeedbackAdapter,\n ModelContext,\n RespondToToolApprovalOptions,\n SpeechSynthesisAdapter,\n ThreadMessage,\n} from \"@assistant-ui/core\";\nimport { toToolsJSONSchema } from \"assistant-stream\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { useStatewire } from \"statewire\";\nimport type { Statewire, StatewireClient } from \"statewire\";\nimport {\n createRunQueueAdapter,\n resolveEditCommand,\n resolveReloadCommand,\n sendFields,\n toWireMessage,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\nimport { runsOptimistic } from \"./runsOptimistic\";\n\ntype AnyCommands = Record<string, (...args: any[]) => unknown>;\n\nexport const symbolStatewireExtras = Symbol(\"statewire-extras\");\n\nexport const asStatewireExtras = (extras: unknown): StatewireThread.Extras => {\n if (\n typeof extras !== \"object\" ||\n extras == null ||\n !(symbolStatewireExtras in extras)\n )\n throw new Error(\n \"This method can only be called when you are using StatewireThread\",\n );\n\n return extras as StatewireThread.Extras;\n};\n\nconst NO_INPUT_REQUESTS: readonly StatewireThread.InputRequestState[] = [];\n\nconst RESTING_RUNS: StatewireThread.Runs = {\n runId: null,\n queue: [],\n steerQueue: [],\n};\n\nconst ambientContextOf = (context: ModelContext): Record<string, unknown> => ({\n ...(context.system !== undefined && { system: context.system }),\n ...(context.tools !== undefined && {\n tools: toToolsJSONSchema(context.tools),\n }),\n ...(context.callSettings !== undefined && {\n callSettings: context.callSettings,\n }),\n ...(context.config !== undefined && { config: context.config }),\n});\n\nconst useStatewireThread = (\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 { state, commands, connection, setContext, isBusy } = useStatewire<\n unknown,\n AnyCommands\n >({\n transport: options.transport,\n initialState: options.initialState,\n optimistic: (draft, command, ctx) => {\n runsOptimistic(draft, command, ctx);\n latest.current.optimistic?.(draft, command, ctx);\n },\n materialize: (draft: {}) => latest.current.materialize?.(draft),\n onCommandChange: (update, ctx) => {\n if (update.status === \"applied\" || update.status === \"settled\")\n retire(update.params[0]);\n latest.current.onCommandChange?.(update, ctx);\n },\n onStateChange: (state, ctx) => latest.current.onStateChange?.(state, ctx),\n onConnectionChange: (connection) =>\n latest.current.onConnectionChange?.(connection),\n });\n\n const clientRef = useAssistantClientRef();\n const setContextRef = useRef(setContext);\n setContextRef.current = setContext;\n const [syncState] = useState(() => ({ lastSent: undefined as unknown }));\n const { contextSync } = options;\n useEffect(() => {\n if (contextSync === undefined) return;\n const modelContext = (clientRef.current ?? clientRef.parent).modelContext();\n const send = () => {\n const value = ambientContextOf(modelContext.getModelContext());\n const key = JSON.stringify(value);\n if (key === syncState.lastSent) return;\n syncState.lastSent = key;\n setContextRef.current(value);\n };\n send();\n if (!modelContext.subscribe) {\n throw new Error(\n \"statewire: contextSync requires a subscribable model context\",\n );\n }\n return modelContext.subscribe(send);\n }, [contextSync, clientRef, syncState]);\n\n const dispatch = useCallback(\n (command: StatewireThread.Command) => {\n setPending((prev) => [...prev, command]);\n const settled = commands[command.type]!(command);\n settled.catch((error: Error) => {\n retire(command);\n latest.current.onError?.(error);\n });\n return settled;\n },\n [commands, retire],\n );\n\n const threadRef = useRef<ClientOutput<\"thread\"> | null>(null);\n const dispatchSend = useCallback(\n (command: StatewireThread.Command, message: AppendMessage) => {\n if (message.sourceId != null) return void dispatch(command);\n const text = message.content\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\");\n void dispatch(command).catch(() => {\n // Rejected send: put the text back unless the user typed since.\n // ExternalThread's setText is live-ref-backed and takes an updater.\n const setText = threadRef.current!.composer().setText as (\n next: string | ((prev: string) => string),\n ) => void;\n setText((prev) => (prev === \"\" ? text : prev));\n });\n },\n [dispatch],\n );\n\n const { status, runs } = useMemo((): {\n status: StatewireThread.ThreadStatus;\n runs: StatewireThread.Runs;\n } => {\n const entries = (\n state as { runs?: readonly StatewireThread.RunState[] } | undefined\n )?.runs;\n const entry = entries?.[0];\n return {\n status: entries === undefined ? \"loading\" : (entry?.status ?? \"ready\"),\n runs:\n entry === undefined\n ? RESTING_RUNS\n : {\n runId: entry.runId,\n ...(entry.epoch !== undefined && { epoch: entry.epoch }),\n queue: entry.queue,\n steerQueue: entry.steerQueue,\n ...(entry.dispatching !== undefined && {\n dispatching: entry.dispatching,\n }),\n ...(entry.stopping !== undefined && { stopping: entry.stopping }),\n ...(entry.nextDispatch !== undefined && {\n nextDispatch: entry.nextDispatch,\n }),\n ...(entry.inputRequests !== undefined && {\n inputRequests: entry.inputRequests,\n }),\n ...(entry.error !== undefined && { error: entry.error }),\n },\n };\n }, [state]);\n\n const { converter } = options;\n const metadata = useMemo(\n (): StatewireThread.ConnectionMetadata => ({\n pendingCommands: [...pending],\n isSending: pending.length > 0,\n connection,\n runs,\n }),\n [pending, connection, runs],\n );\n const converted = useMemo(\n (): StatewireThread.State => converter(state, metadata),\n [converter, state, metadata],\n );\n // Dispatch limbo is a materialize concern: the fold makes the record\n // concrete in state before conversion.\n const messages = converted.messages;\n const liveRunId = runs.runId;\n\n const queue = useMemo(\n () =>\n createRunQueueAdapter(\n messages,\n liveRunId,\n runs.queue,\n runs.steerQueue,\n dispatch,\n dispatchSend,\n ),\n [messages, liveRunId, runs, dispatch, dispatchSend],\n );\n\n const inputRequests = runs.inputRequests ?? NO_INPUT_REQUESTS;\n\n const extras = useMemo(\n (): StatewireThread.Extras => ({\n [symbolStatewireExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state,\n status,\n isBusy,\n inputRequests,\n runs,\n }),\n [\n dispatch,\n connection.reconnect,\n state,\n status,\n isBusy,\n inputRequests,\n runs,\n ],\n );\n\n const handleAppend = (message: AppendMessage) => {\n dispatchSend(\n message.sourceId != null\n ? resolveEditCommand(messages, message, liveRunId)\n : {\n type: \"run/steer\",\n ...sendFields(\n messages,\n liveRunId,\n toWireMessage(message, crypto.randomUUID()),\n ),\n },\n message,\n );\n };\n\n const handleReload = (parentId: string | null) => {\n dispatch(resolveReloadCommand(messages, parentId, liveRunId));\n };\n\n const handleEdit = (message: AppendMessage) => {\n dispatch(resolveEditCommand(messages, message, liveRunId));\n };\n\n const thread = useResource(\n ExternalThread({\n messages: messages as readonly ExternalThreadMessage[],\n isRunning: status === \"running\",\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n speechAdapter: options.adapters?.speech,\n feedbackAdapter: options.adapters?.feedback,\n onNew: handleAppend,\n queue,\n ...(options.capabilities?.edit && { onEdit: handleEdit }),\n ...(options.capabilities?.continue && {\n onResume: () =>\n dispatch({\n type: \"run/continue\",\n ...(liveRunId !== null && { runId: liveRunId }),\n }),\n }),\n ...(options.capabilities?.reload && { onReload: handleReload }),\n onAddToolResult: (toolOptions: AddToolResultOptions) =>\n dispatch(resolveToolResultInput(inputRequests, toolOptions, liveRunId)),\n onRespondToToolApproval: (approval: RespondToToolApprovalOptions) =>\n dispatch(resolveToolApprovalInput(inputRequests, approval, liveRunId)),\n onCancel: () => {\n const payload = latest.current.stopPayload?.();\n if (\n payload !== undefined &&\n (typeof payload !== \"object\" ||\n payload === null ||\n Array.isArray(payload))\n )\n throw new Error(\"statewire: stopPayload must return a plain object\");\n void commands[\"run/stop\"]!({\n ...payload,\n runId: runs.runId,\n ...(runs.epoch !== undefined && { epoch: runs.epoch }),\n }).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n },\n }),\n );\n threadRef.current = thread;\n return thread;\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 type UserCommands = Assistant.Commands[keyof Assistant.Commands];\n\n export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;\n\n export type Extras = {\n [symbolStatewireExtras]: true;\n sendCommand: (command: Command) => void;\n reconnect: () => void;\n state: unknown;\n status: ThreadStatus;\n /** Negation of the server's broadcast idle level (a transport without idle is always busy). */\n isBusy: boolean;\n inputRequests: readonly InputRequestState[];\n runs: Runs;\n };\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 /** The run this command targets — the live run's id, or a fresh client-minted uuid on run-creating sends. */\n readonly runId: string;\n } & (\n | {\n readonly message: UserMessage;\n /** Run anchor: the message the new content grows after, null asserting an empty thread. Present on run-creating sends; absent when targeting the live run. */\n readonly runAnchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunSteerCommand = {\n readonly type: \"run/steer\";\n /** The run this command targets — the live run's id, or a fresh client-minted uuid on run-creating sends. */\n readonly runId: string;\n } & (\n | {\n readonly message: UserMessage;\n /** Run anchor: the message the new content grows after, null asserting an empty thread. Present on run-creating sends; absent when targeting the live run. */\n readonly runAnchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunDequeueCommand = {\n readonly type: \"run/dequeue\";\n readonly runId: string;\n readonly messageId: string;\n };\n\n export type RunEditCommand = {\n readonly type: \"run/edit\";\n /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */\n readonly runId: string;\n readonly message: UserMessage;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly runAnchorMessageId: string | null;\n };\n\n export type RunContinueCommand = {\n readonly type: \"run/continue\";\n readonly runId?: string;\n };\n\n export type ToolCallInputRequest = {\n readonly type: \"tool-call\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type ToolApprovalInputRequest = {\n readonly type: \"tool-approval\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type CustomInputRequest = {\n readonly type: string;\n readonly id: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A host request parking the run until answered; open union for custom types. */\n export type InputRequest =\n | ToolCallInputRequest\n | ToolApprovalInputRequest\n | CustomInputRequest;\n\n export type InputResponse = ReadonlyJSONValue;\n\n export type RunInputCommand = {\n readonly type: \"run/input\";\n readonly runId?: string;\n readonly requestId: string;\n readonly response: InputResponse;\n };\n\n /** An input request projected out of the host state; a present `response` key marks the entry answered. */\n export type InputRequestState = InputRequest & {\n readonly response?: InputResponse;\n /** The answer's `run/input` meta; absent when the answer carried none. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n export type RunReloadCommand = {\n readonly type: \"run/reload\";\n /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */\n readonly runId: string;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly runAnchorMessageId: string | null;\n };\n\n export type RunCommand =\n | RunEnqueueCommand\n | RunSteerCommand\n | RunDequeueCommand\n | RunEditCommand\n | RunContinueCommand\n | RunReloadCommand\n | RunInputCommand;\n\n export type Command = RunCommand | UserCommands;\n\n /** A queued message projected out of the host state, wire shape. */\n export type RunQueueItem = {\n readonly id: string;\n readonly parts: readonly (TextPart | FilePart)[];\n };\n\n /** Run subsystem status replicated by the host. */\n export type RunStatus = \"running\" | \"stopped\" | \"error\" | \"input-required\";\n\n /** The thread's status, derived from the state: `\"loading\"` while the runs mount is absent, `\"ready\"` while resting, otherwise the run's status. */\n export type ThreadStatus = \"loading\" | \"ready\" | RunStatus;\n\n /** A queue-lane entry as replicated: the user message plus host-stamped `meta`. */\n export type RunsQueueEntry = UserMessage & {\n /** Host-stamped opaque per-entry metadata. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n /** An input outcome riding a dispatch record: the request with its response (null = abandoned) and `run/input` meta. */\n export type RunsInputOutcome = {\n readonly request: InputRequest;\n readonly response: InputResponse | null;\n readonly meta: ReadonlyJSONValue | null;\n };\n\n /** The dispatch record — the unapplied batch handed to the run; absent between applied and the next dispatch or take. */\n export type RunsDispatch = {\n readonly trigger:\n | \"message-send\"\n | \"message-edit\"\n | \"message-reload\"\n | \"input-resume\"\n | \"error-continue\"\n | \"stop-continue\"\n | \"steer\";\n readonly messages: readonly RunsQueueEntry[];\n /** Present on rewind dispatches: truncate the thread at this id first; null names the root. */\n readonly rollbackTo?: string | null;\n /** The run-starting op's meta; present only when carried. */\n readonly rootMeta?: ReadonlyJSONValue;\n /** Present when input outcomes ride the dispatch; visible until applied. */\n readonly inputOutcomes?: readonly RunsInputOutcome[];\n };\n\n /** The stopping window: present while a stop of the live run is underway; `\"message-edit\"` / `\"message-reload\"` pair with `nextDispatch`. */\n export type RunsStopping = {\n readonly reason: \"stop\" | \"message-edit\" | \"message-reload\";\n };\n\n /** The replicated run error — set on an unhandled failure, cleared by the next user-initiated run. */\n export type RunsError = {\n readonly message: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A replicated run entry — one element of the mount's `runs` array. */\n export type RunState = {\n /** The run's identity — client-minted, adopted by the host at run creation; persists through steers, input-required, and error/stop, retiring only when the queue drains and the run completes. */\n readonly runId: string | null;\n /** Counts the entry's dispatches; a `run/stop` carrying a stale epoch rejects. */\n readonly epoch?: number;\n readonly status: RunStatus;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */\n readonly dispatching?: RunsDispatch;\n readonly stopping?: RunsStopping;\n /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */\n readonly nextDispatch?: RunsDispatch;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n /** Set only by an unhandled throw; cleared by the next user-initiated run. */\n readonly error?: RunsError;\n };\n\n /** App-shaped effects `runsMaterialize` applies for the dispatch record. */\n export type MaterializeEffects = {\n /** Append one dispatched message to the app's committed message state. */\n append: (message: RunsQueueEntry) => void;\n /** Truncate to the rolled-back view first (null names the root); required for hosts that dispatch edits/reloads. */\n rollback?: (to: string | null) => void;\n };\n\n /** The runs mount as replicated: the run entries plus the top-level status projection. */\n export type RunsState = {\n /** Projection of `runs[0]?.status ?? \"ready\"`. */\n readonly status: Exclude<ThreadStatus, \"loading\">;\n /** At most one entry; empty while resting. */\n readonly runs: readonly RunState[];\n };\n\n /** The run subsystem's typed read — `runs[0]` of the state with unsettled commands folded in, resting defaults while no entry is live. */\n export type Runs = {\n /** The live run's id — non-null whenever a run entry is live (running, input-required, error/stop); the target for `run/*` sends. */\n readonly runId: string | null;\n /** Counts the entry's dispatches; rides `run/stop` so a replayed stop cannot end a later leg. */\n readonly epoch?: number;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */\n readonly dispatching?: RunsDispatch;\n readonly stopping?: RunsStopping;\n /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */\n readonly nextDispatch?: RunsDispatch;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n /** Set only by an unhandled throw; cleared by the next user-initiated run. */\n readonly error?: RunsError;\n };\n\n export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `live`. */\n connection: StatewireClient.ConnectionState;\n /** The typed runs read. */\n runs: Runs;\n };\n\n /** Converter output: app-owned keys only — the lib projects the run mounts itself. */\n export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n /**\n * Payload of the built-in `run/stop` command. `reason` is the one well-known\n * field; apps extend it with their own JSON-serializable fields.\n */\n export type StopPayload = {\n readonly reason?: string | undefined;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n export type Options<T> = {\n transport: Transport<T>;\n /** The pre-attach state, replaced by the attach snapshot. `runs: []` projects ready (interactive from the first render); an absent runs mount projects loading until attach. */\n initialState: T;\n converter: StateConverter<T>;\n /** Folds app-owned keys for an unsettled command into the draft; runs after the lib's run-dialect reducer. */\n optimistic?:\n | StatewireClient.Optimistic<\n T,\n Record<string, (...args: any[]) => unknown>\n >\n | undefined;\n /** Makes dispatch records concrete in the draft (runs after the optimistic folds); without it, dispatch limbo stays out of `messages`. */\n materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;\n /**\n * \"command-send\" mirrors the client's ambient model context (system,\n * tools, callSettings, config) to the server over the command channel —\n * on connect and whenever it changes. Requires a remote transport.\n */\n contextSync?: \"command-send\" | undefined;\n /** Supplies the `run/stop` command's payload; omitted, stop sends no payload. */\n stopPayload?: (() => StopPayload) | undefined;\n /** Observes each command's lifecycle (queued, posted, applied, settled); runs after the built-in pending-command retirement. */\n onCommandChange?:\n | ((\n update: Statewire.CommandUpdate<\n Record<string, (...args: any[]) => unknown>\n >,\n ctx: { state: NonNullable<T> },\n ) => void)\n | undefined;\n /** Observes the transport state: fires with the attach snapshot, then once per change. */\n onStateChange?:\n | ((state: NonNullable<T>, ctx: { changes: Statewire.Changes }) => void)\n | undefined;\n /** Observes connection status transitions, starting with the initial status. */\n onConnectionChange?:\n | ((connection: StatewireClient.Connection) => void)\n | undefined;\n onError?: ((error: Error) => void) | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n /** The host supports `run/continue` (a continue affordance on aborted runs). */\n continue?: boolean | undefined;\n /** The host supports `run/reload` (regenerating an assistant message). */\n reload?: boolean | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n speech?: SpeechSynthesisAdapter | undefined;\n feedback?: FeedbackAdapter | undefined;\n }\n | undefined;\n };\n}\n\ndeclare module \"@assistant-ui/core\" {\n namespace Assistant {\n interface Commands {\n runEnqueue: StatewireThread.RunEnqueueCommand;\n runSteer: StatewireThread.RunSteerCommand;\n runDequeue: StatewireThread.RunDequeueCommand;\n runEdit: StatewireThread.RunEditCommand;\n runContinue: StatewireThread.RunContinueCommand;\n runReload: StatewireThread.RunReloadCommand;\n runInput: StatewireThread.RunInputCommand;\n }\n }\n}\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useStatewireThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;;;AAwCA,MAAasC,wBAAwBC,OAAO,kBAAkB;AAE9D,MAAaC,qBAAqBC,WAA4C;CAC5E,IACE,OAAOA,WAAW,YAClBA,UAAU,QACV,EAAEH,yBAAyBG,SAE3B,MAAM,IAAIG,MACR,mEACF;CAEF,OAAOH;AACT;AAEA,MAAMI,oBAAkE,CAAA;AAExE,MAAME,eAAqC;CACzCE,OAAO;CACPC,OAAO,CAAA;CACPC,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E,MAAM;GACN,GAAImC,cAAc,QAAQ,EAAE5F,OAAO4F,UAAU;EAC/C,CAAC,EACL;EACA,GAAIjF,QAAQoG,cAAcK,UAAU,EAAEC,UAAUnB,aAAa;EAC7DoB,kBAAkBC,gBAChBhE,SAASvE,uBAAuBkG,eAAeqC,aAAa3B,SAAS,CAAC;EACxE4B,0BAA0BC,aACxBlE,SAASxE,yBAAyBmG,eAAeuC,UAAU7B,SAAS,CAAC;EACvE8B,gBAAgB;GACd,MAAMC,UAAU9G,OAAOC,QAAQ8G,cAAc;GAC7C,IACED,YAAYrH,KAAAA,MACX,OAAOqH,YAAY,YAClBA,YAAY,QACZE,MAAMC,QAAQH,OAAO,IAEvB,MAAM,IAAIhI,MAAM,mDAAmD;GACrE,SAAc,WAAW,CAAE;IACzB,GAAGgI;IACH3H,OAAOyE,KAAKzE;IACZ,GAAIyE,KAAKK,UAAUxE,KAAAA,KAAa,EAAEwE,OAAOL,KAAKK,MAAM;GACtD,CAAC,CAAC,CAACpB,OAAOC,YAAiB;IACzB9C,OAAOC,QAAQ8C,UAAUD,OAAK;GAChC,CAAC;EACH;CACF,CAAC,CACH;CACAE,UAAU/C,UAAUuF;CACpB,OAAOA;AACT;AAEA,MAAa5G,mBACXkB,YAEAvD,SAASsD,kBAAkB,CAAC,CAACC,OAAuC;AA8WtEjD,uBACEgD,oBACAnD,eAAe+C,KAAAA,CAAkB,CAAC,CAACiM,IACrC"}
|
package/package.json
CHANGED
package/src/StatewireThread.ts
CHANGED
|
@@ -182,6 +182,7 @@ const useStatewireThread = (
|
|
|
182
182
|
? RESTING_RUNS
|
|
183
183
|
: {
|
|
184
184
|
runId: entry.runId,
|
|
185
|
+
...(entry.epoch !== undefined && { epoch: entry.epoch }),
|
|
185
186
|
queue: entry.queue,
|
|
186
187
|
steerQueue: entry.steerQueue,
|
|
187
188
|
...(entry.dispatching !== undefined && {
|
|
@@ -312,11 +313,13 @@ const useStatewireThread = (
|
|
|
312
313
|
Array.isArray(payload))
|
|
313
314
|
)
|
|
314
315
|
throw new Error("statewire: stopPayload must return a plain object");
|
|
315
|
-
void commands["run/stop"]!({
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
},
|
|
319
|
-
)
|
|
316
|
+
void commands["run/stop"]!({
|
|
317
|
+
...payload,
|
|
318
|
+
runId: runs.runId,
|
|
319
|
+
...(runs.epoch !== undefined && { epoch: runs.epoch }),
|
|
320
|
+
}).catch((error: Error) => {
|
|
321
|
+
latest.current.onError?.(error);
|
|
322
|
+
});
|
|
320
323
|
},
|
|
321
324
|
}),
|
|
322
325
|
);
|
|
@@ -539,6 +542,8 @@ export namespace StatewireThread {
|
|
|
539
542
|
export type RunState = {
|
|
540
543
|
/** The run's identity — client-minted, adopted by the host at run creation; persists through steers, input-required, and error/stop, retiring only when the queue drains and the run completes. */
|
|
541
544
|
readonly runId: string | null;
|
|
545
|
+
/** Counts the entry's dispatches; a `run/stop` carrying a stale epoch rejects. */
|
|
546
|
+
readonly epoch?: number;
|
|
542
547
|
readonly status: RunStatus;
|
|
543
548
|
readonly queue: readonly RunsQueueEntry[];
|
|
544
549
|
readonly steerQueue: readonly RunsQueueEntry[];
|
|
@@ -573,6 +578,8 @@ export namespace StatewireThread {
|
|
|
573
578
|
export type Runs = {
|
|
574
579
|
/** The live run's id — non-null whenever a run entry is live (running, input-required, error/stop); the target for `run/*` sends. */
|
|
575
580
|
readonly runId: string | null;
|
|
581
|
+
/** Counts the entry's dispatches; rides `run/stop` so a replayed stop cannot end a later leg. */
|
|
582
|
+
readonly epoch?: number;
|
|
576
583
|
readonly queue: readonly RunsQueueEntry[];
|
|
577
584
|
readonly steerQueue: readonly RunsQueueEntry[];
|
|
578
585
|
/** The dispatch record — the unapplied batch handed to the run, cleared at applied. */
|