@assistant-ui/react-statewire 0.9.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/AssistantTransportThread.d.ts +4 -0
- package/dist/AssistantTransportThread.d.ts.map +1 -1
- package/dist/AssistantTransportThread.js +40 -15
- package/dist/AssistantTransportThread.js.map +1 -1
- package/dist/StatewireThread.d.ts +1 -1
- package/dist/StatewireThread.d.ts.map +1 -1
- package/dist/StatewireThread.js +3 -16
- package/dist/StatewireThread.js.map +1 -1
- package/dist/runCommands.d.ts +2 -4
- package/dist/runCommands.d.ts.map +1 -1
- package/dist/runCommands.js +1 -14
- package/dist/runCommands.js.map +1 -1
- package/package.json +1 -1
- package/src/AssistantTransportThread.ts +59 -23
- package/src/StatewireThread.runs.test.tsx +40 -21
- package/src/StatewireThread.ts +4 -23
- package/src/runCommands.ts +0 -22
- package/src/transport.test.tsx +157 -0
|
@@ -166,6 +166,10 @@ declare namespace AssistantTransportThread {
|
|
|
166
166
|
initialState: T;
|
|
167
167
|
converter: StateConverter<T>;
|
|
168
168
|
optimistic?: Optimistic<T> | undefined;
|
|
169
|
+
/** Folds the lib's run-dialect optimistic reducer before `optimistic`: `true` reads the run mounts off the state root; a selector picks a nested mount. */
|
|
170
|
+
runs?: true | ((state: T) => unknown) | undefined;
|
|
171
|
+
/** Makes dispatch records concrete in the draft (runs after the optimistic folds); without it, dispatch limbo stays out of `messages`. */
|
|
172
|
+
materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;
|
|
169
173
|
api: string;
|
|
170
174
|
resumeApi?: string | undefined;
|
|
171
175
|
protocol?: Protocol | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AssistantTransportThread.d.ts","names":[],"sources":["../src/AssistantTransportThread.ts"],"mappings":";;;;;;;;
|
|
1
|
+
{"version":3,"file":"AssistantTransportThread.d.ts","names":[],"sources":["../src/AssistantTransportThread.ts"],"mappings":";;;;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,gBAAgB,YAAY,YAAY;IACtD;IACA;IACA,WAAW;IACX,SAAS,sBAAsB,QAAQ;IACvC,uBAAuB;;IAEvB,+BAEM,MAAM,4BACH,0BAA0B,QAAQ;IAE3C,eAAe,UAAU;IACzB;IACA,YAEM,OAAO,OACP;MACE,UAAU;MACV,cAAc,UAAU,OAAO,MAAM;iBAE7B;;;;;IAMhB,aACM;MACA,UAAU;MACV,cAAc,UAAU,OAAO,MAAM;MACrC,QAAQ;;IAGd;MAEM;;;;;;MAMA;;MAEA;;IAGN;MAEM,cAAc"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { AssistantTransportHost } from "./host.js";
|
|
2
2
|
import { createRunQueueAdapter, resolveEditCommand, resolveReloadCommand, toWireMessage, viewedLeafId } from "./runCommands.js";
|
|
3
|
+
import { runsOptimistic } from "./runsOptimistic.js";
|
|
3
4
|
import { resolveToolApprovalInput, resolveToolResultInput } from "./inputRequests.js";
|
|
4
5
|
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "@assistant-ui/tap/react-shim";
|
|
5
6
|
import { resource, useResource } from "@assistant-ui/tap";
|
|
@@ -70,23 +71,47 @@ const useAssistantTransportThread = (options) => {
|
|
|
70
71
|
return ctx;
|
|
71
72
|
};
|
|
72
73
|
});
|
|
73
|
-
const { converter, optimistic } = options;
|
|
74
|
-
const
|
|
75
|
-
|
|
74
|
+
const { converter, optimistic, runs: runsOption, materialize } = options;
|
|
75
|
+
const [runsSeam] = useState(() => runsOption !== void 0);
|
|
76
|
+
if (runsSeam !== (runsOption !== void 0)) throw new Error("statewire: the runs option must be stable — it was " + (runsSeam ? "set" : "unset") + " on first render and changed since");
|
|
77
|
+
const [materializeSeam] = useState(() => materialize !== void 0);
|
|
78
|
+
if (materializeSeam !== (materialize !== void 0)) throw new Error("statewire: the materialize option must be stable — it was " + (materializeSeam ? "set" : "unset") + " on first render and changed since");
|
|
79
|
+
const project = useCallback((state_0) => {
|
|
80
|
+
const fold = runsOption !== void 0 ? (draft, command_1, ctx_0) => {
|
|
81
|
+
runsOptimistic(runsOption === true ? draft : runsOption(draft), {
|
|
82
|
+
method: command_1.type,
|
|
83
|
+
params: [command_1]
|
|
84
|
+
}, ctx_0);
|
|
85
|
+
optimistic?.(draft, command_1, ctx_0);
|
|
86
|
+
} : optimistic;
|
|
87
|
+
let next = fold ? foldOptimistic(state_0, [...queue.inTransit, ...queue.queued], fold, ctxOf) : state_0;
|
|
88
|
+
if (materialize) try {
|
|
89
|
+
next = applyOptimistic(next, (draft_0) => materialize(draft_0));
|
|
90
|
+
} catch (error) {
|
|
91
|
+
console.error("statewire: materialize threw; publishing without its update", error);
|
|
92
|
+
}
|
|
93
|
+
return next;
|
|
94
|
+
}, [
|
|
95
|
+
runsOption,
|
|
76
96
|
optimistic,
|
|
77
|
-
|
|
97
|
+
materialize,
|
|
78
98
|
queue,
|
|
79
99
|
ctxOf
|
|
80
100
|
]);
|
|
101
|
+
const converted = useMemo(() => converter(project(agentState)), [
|
|
102
|
+
converter,
|
|
103
|
+
project,
|
|
104
|
+
agentState
|
|
105
|
+
]);
|
|
81
106
|
const convertedRef = useRef(converted);
|
|
82
107
|
convertedRef.current = converted;
|
|
83
108
|
const [toolInvocations] = useState(() => new ToolInvocationTracker(() => {
|
|
84
109
|
return (clientRef.current ?? clientRef.parent).modelContext().getModelContext().tools;
|
|
85
110
|
}, {
|
|
86
|
-
onResult: (
|
|
111
|
+
onResult: (command_2) => {
|
|
87
112
|
const messages = convertedRef.current.messages;
|
|
88
|
-
if (!messagesContainToolCall(messages,
|
|
89
|
-
dispatch(resolveToolResultInput(convertedRef.current.inputRequests ?? [],
|
|
113
|
+
if (!messagesContainToolCall(messages, command_2.toolCallId)) return;
|
|
114
|
+
dispatch(resolveToolResultInput(convertedRef.current.inputRequests ?? [], command_2));
|
|
90
115
|
},
|
|
91
116
|
onStatusesChange: (statuses) => {
|
|
92
117
|
setToolStatuses(statuses.size === 0 ? EMPTY_TOOL_STATUSES : Object.fromEntries(statuses));
|
|
@@ -118,19 +143,19 @@ const useAssistantTransportThread = (options) => {
|
|
|
118
143
|
inputRequests
|
|
119
144
|
]);
|
|
120
145
|
const handleEdit = (message) => {
|
|
121
|
-
const
|
|
122
|
-
toolInvocations.abort().then(() => dispatch(
|
|
146
|
+
const command_3 = resolveEditCommand(convertedRef.current.messages, message);
|
|
147
|
+
toolInvocations.abort().then(() => dispatch(command_3));
|
|
123
148
|
};
|
|
124
149
|
const handleAppend = (message_0) => {
|
|
125
150
|
if (message_0.sourceId != null) return handleEdit(message_0);
|
|
126
151
|
const startRun = message_0.startRun ?? message_0.role === "user";
|
|
127
|
-
const
|
|
152
|
+
const command_4 = {
|
|
128
153
|
type: "run/steer",
|
|
129
154
|
message: toWireMessage(message_0, crypto.randomUUID()),
|
|
130
155
|
anchorMessageId: viewedLeafId(convertedRef.current.messages)
|
|
131
156
|
};
|
|
132
157
|
commands.setParentId(message_0.parentId).catch(() => {});
|
|
133
|
-
const send = () => dispatch(
|
|
158
|
+
const send = () => dispatch(command_4, { schedule: startRun });
|
|
134
159
|
if (startRun) toolInvocations.abort().then(send);
|
|
135
160
|
else send();
|
|
136
161
|
};
|
|
@@ -152,7 +177,7 @@ const useAssistantTransportThread = (options) => {
|
|
|
152
177
|
if (queueProjection !== void 0 && options.capabilities?.queue) throw new Error("statewire: the converter's queue projection excludes capabilities.queue");
|
|
153
178
|
const [queueSeam] = useState(() => ({ present: queueProjection !== void 0 }));
|
|
154
179
|
if (queueSeam.present !== (queueProjection !== void 0)) throw new Error("statewire: the converter's queue projection must be stable — it was " + (queueSeam.present ? "defined" : "undefined") + " on first convert and changed since");
|
|
155
|
-
const serverQueue = useMemo(() => queueProjection ? createRunQueueAdapter(converted.messages, queueProjection, steerProjection, dispatch, (
|
|
180
|
+
const serverQueue = useMemo(() => queueProjection ? createRunQueueAdapter(converted.messages, queueProjection, steerProjection, dispatch, (command_5) => dispatch(command_5)) : void 0, [
|
|
156
181
|
converted.messages,
|
|
157
182
|
queueProjection,
|
|
158
183
|
steerProjection,
|
|
@@ -194,8 +219,8 @@ const useAssistantTransportThread = (options) => {
|
|
|
194
219
|
} },
|
|
195
220
|
...options.capabilities?.edit && { onEdit: handleEdit },
|
|
196
221
|
onReload: (parentId) => {
|
|
197
|
-
const
|
|
198
|
-
toolInvocations.abort().then(() => dispatch(
|
|
222
|
+
const command_6 = resolveReloadCommand(convertedRef.current.messages, parentId);
|
|
223
|
+
toolInvocations.abort().then(() => dispatch(command_6));
|
|
199
224
|
},
|
|
200
225
|
onCancel: () => {
|
|
201
226
|
messageQueue?.clear();
|
|
@@ -218,7 +243,7 @@ const useAssistantTransportThread = (options) => {
|
|
|
218
243
|
},
|
|
219
244
|
onLoadExternalState: (imported) => {
|
|
220
245
|
commands.importState(imported).catch(() => {});
|
|
221
|
-
convertedRef.current = converter(
|
|
246
|
+
convertedRef.current = converter(project(imported));
|
|
222
247
|
toolInvocations.reset();
|
|
223
248
|
setToolStatuses(EMPTY_TOOL_STATUSES);
|
|
224
249
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AssistantTransportThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","useSyncExternalStore","resource","useResource","ResourceElement","ExternalThread","Assistant","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","createMessageQueue","AddToolResultOptions","AppendMessage","AttachmentAdapter","LanguageModelConfig","LanguageModelV1CallSettings","MessageQueueController","MessageQueueDriver","RespondToToolApprovalOptions","ResumeToolCallOptions","ThreadMessage","ToolExecutionStatus","ReadonlyJSONValue","ToolInvocationTracker","applyOptimistic","useStatewire","StatewireClient","StatewireThread","AssistantTransportHost","AssistantTransportHostCommands","AssistantTransportHostState","HostQueueCell","HostRunContext","SendOptions","createRunQueueAdapter","resolveEditCommand","resolveReloadCommand","toWireMessage","viewedLeafId","resolveToolApprovalInput","resolveToolResultInput","EMPTY_TOOL_STATUSES","Record","EMPTY_QUEUE_ITEMS","subscribeNoop","symbolAssistantTransportExtras","Symbol","AssistantTransportExtras","sendCommand","command","AssistantTransportThread","Command","reconnect","state","inputRequests","InputRequestState","runs","Runs","asAssistantTransportExtras","extras","Error","foldOptimistic","commands","optimistic","Optimistic","ctxOf","OptimisticContext","next","draft","error","console","type","messagesContainToolCall","messages","toolCallId","some","message","content","part","undefined","useAssistantTransportThread","options","Options","clientRef","getRunContext","aui","current","parent","threadId","threadListItem","getState","remoteId","modelContext","getModelContext","queueCell","queued","inTransit","connection","transport","agent","agentState","isSending","isReplaying","queue","dispatch","opts","send","catch","toolStatuses","setToolStatuses","ctxs","WeakMap","seq","ctx","get","ts","Date","now","set","converter","converted","convertedRef","toolInvocations","tools","onResult","onStatusesChange","statuses","size","Object","fromEntries","setState","isRunning","isLoading","reset","inputSeam","present","handleEdit","abort","then","handleAppend","sourceId","startRun","role","crypto","randomUUID","anchorMessageId","setParentId","parentId","schedule","handleCancel","cancel","driverRef","run","at","id","queueProjection","steerProjection","steerQueue","capabilities","queueSeam","serverQueue","enableQueue","queueRef","clear","messageQueue","queueItems","subscribe","adapter","items","steerQueueItems","steerItems","busy","keys","length","wasBusyRef","notifyBusy","notifyIdle","attachmentAdapter","adapters","attachments","onNew","edit","onEdit","onReload","onCancel","onResume","continue","resumeApi","resume","onAddToolResult","toolOptions","onRespondToToolApproval","onResumeToolCall","payload","onLoadExternalState","imported","importState","T","UserCommands","Commands","TextPart","text","FilePart","mediaType","url","filename","RunUserMessage","parts","metadata","RunPlacement","insertAfter","insertBefore","RunEnqueueCommand","messageId","RunSteerCommand","RunDequeueCommand","RunEditCommand","rollbackTo","RunContinueCommand","ToolCallInputRequest","ToolApprovalInputRequest","CustomInputRequest","key","InputRequest","ToolCallInputResponse","output","isError","artifact","ToolApprovalInputResponse","decision","editedArgs","InputResponse","RunInputCommand","requestId","response","RunReloadCommand","RunCommand","RunQueueItem","State","StateConverter","HeadersValue","Headers","Protocol","SendCommandsRequestBody","system","callSettings","config","initialState","api","protocol","headers","Promise","body","prepareSendCommandsRequest","onResponse","Response","onFinish","onError","params","updateState","updater","hook"],"sources":["../src/AssistantTransportThread.ts"],"sourcesContent":["import {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport { resource, useResource } from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/react\";\nimport type { Assistant, ExternalThreadMessage } from \"@assistant-ui/react\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport { createMessageQueue } from \"@assistant-ui/core\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n AttachmentAdapter,\n LanguageModelConfig,\n LanguageModelV1CallSettings,\n MessageQueueController,\n MessageQueueDriver,\n RespondToToolApprovalOptions,\n ResumeToolCallOptions,\n ThreadMessage,\n ToolExecutionStatus,\n} from \"@assistant-ui/core\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { ToolInvocationTracker } from \"@assistant-ui/core/internal\";\nimport { applyOptimistic, useStatewire } from \"statewire\";\nimport type { StatewireClient } from \"statewire\";\nimport type { StatewireThread } from \"./StatewireThread\";\nimport { AssistantTransportHost } from \"./host\";\nimport type {\n AssistantTransportHostCommands,\n AssistantTransportHostState,\n HostQueueCell,\n HostRunContext,\n SendOptions,\n} from \"./host\";\nimport {\n createRunQueueAdapter,\n resolveEditCommand,\n resolveReloadCommand,\n toWireMessage,\n viewedLeafId,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\n\nconst EMPTY_TOOL_STATUSES: Record<string, ToolExecutionStatus> = {};\nconst EMPTY_QUEUE_ITEMS: MessageQueueController[\"adapter\"][\"items\"] = [];\nconst subscribeNoop = () => () => {};\n\nexport const symbolAssistantTransportExtras = Symbol(\n \"assistant-transport-extras\",\n);\n\nexport type AssistantTransportExtras = {\n [symbolAssistantTransportExtras]: true;\n sendCommand: (command: AssistantTransportThread.Command) => void;\n reconnect: () => void;\n state: unknown;\n /** The host's parked input requests; absent when the converter does not project them. */\n inputRequests?: readonly AssistantTransportThread.InputRequestState[];\n /** The typed runs read; present iff StatewireThread runs with the `runs` option. */\n runs?: StatewireThread.Runs;\n};\n\nexport const asAssistantTransportExtras = (\n extras: unknown,\n): AssistantTransportExtras => {\n if (\n typeof extras !== \"object\" ||\n extras == null ||\n !(symbolAssistantTransportExtras in extras)\n )\n throw new Error(\n \"This method can only be called when you are using AssistantTransportThread or StatewireThread\",\n );\n\n return extras as AssistantTransportExtras;\n};\n\nconst foldOptimistic = (\n state: unknown,\n commands: readonly AssistantTransportThread.Command[],\n optimistic: AssistantTransportThread.Optimistic<unknown>,\n ctxOf: (command: object) => StatewireClient.OptimisticContext,\n): unknown => {\n let next = state;\n for (const command of commands) {\n try {\n next = applyOptimistic(next, (draft) =>\n optimistic(draft, command, ctxOf(command)),\n );\n } catch (error) {\n console.error(\n `statewire: optimistic reducer threw for \"${command.type}\"; dropping its optimistic update`,\n error,\n );\n }\n }\n return next;\n};\n\nconst messagesContainToolCall = (\n messages: readonly ThreadMessage[],\n toolCallId: string,\n): boolean =>\n messages.some((message) =>\n message.content.some(\n (part) =>\n part.type === \"tool-call\" &&\n (part.toolCallId === toolCallId ||\n (part.messages !== undefined &&\n messagesContainToolCall(part.messages, toolCallId))),\n ),\n );\n\nconst useAssistantTransportThread = (\n options: AssistantTransportThread.Options<any>,\n): ClientOutput<\"thread\"> => {\n const clientRef = useAssistantClientRef();\n const [getRunContext] = useState(() => (): HostRunContext => {\n const aui = clientRef.current ?? clientRef.parent;\n // legacy parity: a threadListItem throw must not kill the run\n let threadId: string | null = null;\n try {\n threadId = aui.threadListItem().getState().remoteId ?? null;\n } catch {}\n return {\n modelContext: aui.modelContext().getModelContext(),\n threadId,\n };\n });\n\n const [queueCell] = useState(\n (): HostQueueCell => ({ current: { queued: [], inTransit: [] } }),\n );\n const { state, commands, connection } = useStatewire<\n AssistantTransportHostState,\n AssistantTransportHostCommands\n >({\n transport: AssistantTransportHost({ ...options, getRunContext, queueCell }),\n });\n const { agent: agentState, isSending, isReplaying } = state;\n const queue = queueCell.current;\n\n const dispatch = useCallback(\n (command: AssistantTransportThread.Command, opts?: SendOptions) => {\n void commands.send(command, opts).catch(() => {});\n },\n [commands],\n );\n\n const [toolStatuses, setToolStatuses] =\n useState<Record<string, ToolExecutionStatus>>(EMPTY_TOOL_STATUSES);\n\n const [ctxOf] = useState(() => {\n const ctxs = new WeakMap<object, StatewireClient.OptimisticContext>();\n let seq = 0;\n return (command: object): StatewireClient.OptimisticContext => {\n let ctx = ctxs.get(command);\n if (ctx === undefined) {\n ctx = { ts: Date.now(), seq: ++seq };\n ctxs.set(command, ctx);\n }\n return ctx;\n };\n });\n\n const { converter, optimistic } = options;\n const converted = useMemo(\n () =>\n converter(\n optimistic\n ? foldOptimistic(\n agentState,\n [...queue.inTransit, ...queue.queued],\n optimistic,\n ctxOf,\n )\n : agentState,\n ),\n [converter, optimistic, agentState, queue, ctxOf],\n );\n const convertedRef = useRef(converted);\n convertedRef.current = converted;\n\n const [toolInvocations] = useState(\n () =>\n new ToolInvocationTracker(\n () => {\n const aui = clientRef.current ?? clientRef.parent;\n return aui.modelContext().getModelContext().tools;\n },\n {\n onResult: (command) => {\n const messages = convertedRef.current\n .messages as readonly ThreadMessage[];\n if (!messagesContainToolCall(messages, command.toolCallId)) return;\n dispatch(\n resolveToolResultInput(\n convertedRef.current.inputRequests ?? [],\n command,\n ),\n );\n },\n onStatusesChange: (statuses) => {\n setToolStatuses(\n statuses.size === 0\n ? EMPTY_TOOL_STATUSES\n : Object.fromEntries(statuses),\n );\n },\n },\n ),\n );\n // dep-less by design: setState dedups identical snapshots internally\n useEffect(() => {\n toolInvocations.setState({\n messages: converted.messages as readonly ThreadMessage[],\n isRunning: converted.isRunning,\n isLoading: isReplaying,\n });\n });\n useEffect(\n () => () => {\n toolInvocations.reset();\n },\n [toolInvocations],\n );\n\n const inputRequests = converted.inputRequests;\n const [inputSeam] = useState(() => ({\n present: inputRequests !== undefined,\n }));\n if (inputSeam.present !== (inputRequests !== undefined))\n throw new Error(\n \"statewire: the converter's inputRequests projection must be stable — it was \" +\n (inputSeam.present ? \"defined\" : \"undefined\") +\n \" on first convert and changed since\",\n );\n\n const extras = useMemo(\n (): AssistantTransportExtras => ({\n [symbolAssistantTransportExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state: agentState,\n ...(inputRequests !== undefined && { inputRequests }),\n }),\n [dispatch, connection.reconnect, agentState, inputRequests],\n );\n\n const handleEdit = (message: AppendMessage) => {\n const command = resolveEditCommand(convertedRef.current.messages, message);\n void toolInvocations.abort().then(() => dispatch(command));\n };\n\n const handleAppend = (message: AppendMessage) => {\n if (message.sourceId != null) return handleEdit(message);\n const startRun = message.startRun ?? message.role === \"user\";\n const command: AssistantTransportThread.Command = {\n type: \"run/steer\",\n message: toWireMessage(message, crypto.randomUUID()),\n anchorMessageId: viewedLeafId(convertedRef.current.messages),\n };\n void commands.setParentId(message.parentId).catch(() => {});\n\n const send = () => dispatch(command, { schedule: startRun });\n if (startRun) {\n // abort in-flight tool executions so their late results cannot race the new turn\n void toolInvocations.abort().then(send);\n } else {\n send();\n }\n };\n\n const handleCancel = () => {\n void toolInvocations.abort();\n void commands.cancel().catch(() => {});\n };\n\n const driverRef = useRef<{\n run: MessageQueueDriver[\"run\"];\n cancel: () => void;\n }>(undefined as never);\n driverRef.current = {\n // the queued message was stamped with the head at enqueue time; restamp so\n // it appends to the thread the finished run left behind\n run: (message) =>\n handleAppend({\n ...message,\n parentId: convertedRef.current.messages.at(-1)?.id ?? null,\n }),\n cancel: handleCancel,\n };\n\n const queueProjection = converted.queue;\n const steerProjection = converted.steerQueue;\n if (steerProjection !== undefined && queueProjection === undefined)\n throw new Error(\n \"statewire: the converter's steerQueue projection requires the queue projection\",\n );\n if (queueProjection !== undefined && options.capabilities?.queue)\n throw new Error(\n \"statewire: the converter's queue projection excludes capabilities.queue\",\n );\n const [queueSeam] = useState(() => ({\n present: queueProjection !== undefined,\n }));\n if (queueSeam.present !== (queueProjection !== undefined))\n throw new Error(\n \"statewire: the converter's queue projection must be stable — it was \" +\n (queueSeam.present ? \"defined\" : \"undefined\") +\n \" on first convert and changed since\",\n );\n const serverQueue = useMemo(\n () =>\n queueProjection\n ? createRunQueueAdapter(\n converted.messages,\n queueProjection,\n steerProjection,\n dispatch,\n (command) => dispatch(command),\n )\n : undefined,\n [converted.messages, queueProjection, steerProjection, dispatch],\n );\n\n const enableQueue = options.capabilities?.queue === true;\n const queueRef = useRef<MessageQueueController | null>(null);\n if (enableQueue && !queueRef.current) {\n queueRef.current = createMessageQueue({\n run: (message, opts) => driverRef.current.run(message, opts),\n cancel: () => driverRef.current.cancel(),\n });\n } else if (!enableQueue && queueRef.current) {\n queueRef.current.clear();\n queueRef.current = null;\n }\n const messageQueue = queueRef.current;\n\n // fresh view per snapshot: the controller mutates adapter.items in place,\n // which a stable prop identity would hide from the thread resource\n const queueItems = useSyncExternalStore(\n messageQueue?.subscribe ?? subscribeNoop,\n () => messageQueue?.adapter.items ?? EMPTY_QUEUE_ITEMS,\n () => EMPTY_QUEUE_ITEMS,\n );\n const steerQueueItems = useSyncExternalStore(\n messageQueue?.subscribe ?? subscribeNoop,\n () => messageQueue?.adapter.steerItems ?? EMPTY_QUEUE_ITEMS,\n () => EMPTY_QUEUE_ITEMS,\n );\n\n // settled edge: the queue only advances once the host run loop has fully\n // released (isSending), the converted state agrees, and no client tool from\n // the finished run is still executing\n const busy =\n isSending || converted.isRunning || Object.keys(toolStatuses).length > 0;\n const wasBusyRef = useRef(false);\n useEffect(() => {\n if (wasBusyRef.current === busy) return;\n wasBusyRef.current = busy;\n if (busy) messageQueue?.notifyBusy();\n else messageQueue?.notifyIdle();\n });\n\n return useResource(\n ExternalThread({\n messages: converted.messages as readonly ExternalThreadMessage[],\n isRunning: converted.isRunning,\n isLoading: isReplaying,\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n onNew: handleAppend,\n ...(serverQueue\n ? { queue: serverQueue }\n : messageQueue && {\n queue: {\n ...messageQueue.adapter,\n items: queueItems,\n steerItems: steerQueueItems,\n },\n }),\n ...(options.capabilities?.edit && { onEdit: handleEdit }),\n onReload: (parentId: string | null) => {\n const command = resolveReloadCommand(\n convertedRef.current.messages,\n parentId,\n );\n void toolInvocations.abort().then(() => dispatch(command));\n },\n onCancel: () => {\n // user cancel drops pending lanes; a steer interrupt (driver.cancel) keeps them\n messageQueue?.clear();\n handleCancel();\n },\n onResume: () => {\n if (options.capabilities?.continue) {\n dispatch({ type: \"run/continue\" });\n return;\n }\n if (!options.resumeApi)\n throw new Error(\"Must pass resumeApi to options to resume runs\");\n void commands.resume().catch(() => {});\n },\n ...(inputRequests !== undefined && {\n onAddToolResult: (toolOptions: AddToolResultOptions) =>\n dispatch(\n resolveToolResultInput(\n convertedRef.current.inputRequests!,\n toolOptions,\n ),\n ),\n onRespondToToolApproval: (options: RespondToToolApprovalOptions) =>\n dispatch(\n resolveToolApprovalInput(\n convertedRef.current.inputRequests!,\n options,\n ),\n ),\n }),\n onResumeToolCall: ({ toolCallId, payload }: ResumeToolCallOptions) => {\n if (!toolInvocations.resume(toolCallId, payload))\n throw new Error(`Tool call ${toolCallId} is not waiting for resume.`);\n },\n onLoadExternalState: (imported: unknown) => {\n void commands.importState(imported).catch(() => {});\n // reset() aborts tools before React re-renders — gate their late results against the imported state\n convertedRef.current = converter(\n optimistic\n ? foldOptimistic(\n imported,\n [...queue.inTransit, ...queue.queued],\n optimistic,\n ctxOf,\n )\n : imported,\n );\n toolInvocations.reset();\n setToolStatuses(EMPTY_TOOL_STATUSES);\n },\n }),\n );\n};\n\nexport const AssistantTransportThread = <T>(\n options: AssistantTransportThread.Options<T>,\n): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useAssistantTransportThread)(\n options as AssistantTransportThread.Options<any>,\n );\n\nexport namespace AssistantTransportThread {\n type UserCommands = Assistant.Commands[keyof Assistant.Commands];\n\n export type TextPart = {\n readonly type: \"text\";\n readonly text: string;\n };\n\n export type FilePart = {\n readonly type: \"file\";\n readonly mediaType: string;\n readonly url: string;\n readonly filename?: string;\n };\n\n export type RunUserMessage = {\n readonly id: string;\n readonly role: \"user\";\n readonly parts: readonly (TextPart | FilePart)[];\n readonly metadata?: Record<string, unknown>;\n };\n\n /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */\n export type RunPlacement = {\n readonly insertAfter?: string | null;\n readonly insertBefore?: string | null;\n };\n\n export type RunEnqueueCommand = {\n readonly type: \"run/enqueue\";\n } & (\n | {\n readonly message: RunUserMessage;\n /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */\n readonly anchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n RunPlacement;\n\n export type RunSteerCommand = {\n readonly type: \"run/steer\";\n } & (\n | {\n readonly message: RunUserMessage;\n /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */\n readonly anchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n RunPlacement;\n\n export type RunDequeueCommand = {\n readonly type: \"run/dequeue\";\n readonly messageId: string;\n };\n\n export type RunEditCommand = {\n readonly type: \"run/edit\";\n readonly message: RunUserMessage;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly rollbackTo: string | null;\n };\n\n export type RunContinueCommand = {\n readonly type: \"run/continue\";\n };\n\n export type ToolCallInputRequest = {\n readonly type: \"tool-call\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type ToolApprovalInputRequest = {\n readonly type: \"tool-approval\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type CustomInputRequest = {\n readonly type: string;\n readonly id: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A host request parking the run until answered; open union for custom types. */\n export type InputRequest =\n | ToolCallInputRequest\n | ToolApprovalInputRequest\n | CustomInputRequest;\n\n export type ToolCallInputResponse = {\n readonly output: ReadonlyJSONValue;\n /** Default false; when true, `output` carries the error payload. */\n readonly isError?: boolean;\n readonly artifact?: ReadonlyJSONValue;\n };\n\n export type ToolApprovalInputResponse = {\n readonly decision: \"approve\" | \"reject\" | \"edit\" | \"respond\";\n readonly editedArgs?: ReadonlyJSONValue;\n readonly message?: string;\n };\n\n export type InputResponse = ReadonlyJSONValue;\n\n export type RunInputCommand = {\n readonly type: \"run/input\";\n readonly requestId: string;\n readonly response: InputResponse;\n };\n\n /** An input request projected out of the host state with its response echo. */\n export type InputRequestState = InputRequest & {\n readonly response: InputResponse | null;\n };\n\n export type RunReloadCommand = {\n readonly type: \"run/reload\";\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly rollbackTo: string | null;\n };\n\n export type RunCommand =\n | RunEnqueueCommand\n | RunSteerCommand\n | RunDequeueCommand\n | RunEditCommand\n | RunContinueCommand\n | RunReloadCommand\n | RunInputCommand;\n\n export type Command = RunCommand | UserCommands;\n\n /** A queued message projected out of the host state, wire shape. */\n export type RunQueueItem = {\n readonly id: string;\n readonly parts: readonly (TextPart | FilePart)[];\n };\n\n export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n readonly isRunning: boolean;\n /**\n * The host's regular queue lane projected out of the state. Returning it\n * (even empty) turns on the server-side queue: sends become `run/enqueue`\n * / `run/steer` commands and item controls send the `run/*` queue\n * commands. Presence must be stable across conversions and excludes the\n * client-local `capabilities.queue` buffer.\n */\n readonly queue?: readonly RunQueueItem[];\n /** The host's steer lane; requires `queue`. Absent means empty. */\n readonly steerQueue?: readonly RunQueueItem[];\n /**\n * The host's parked input requests projected out of the state. Returning it\n * (even empty) routes tool results and approvals with a matching pending\n * request through `run/input`. Presence must be stable across conversions.\n */\n readonly inputRequests?: readonly AssistantTransportThread.InputRequestState[];\n };\n\n export type StateConverter<T> = (state: T) => State;\n\n /** Folds an unsettled command into a draft of the client state; called once per pending command, in send order, re-run on every state change. A throwing fold logs and drops that command's update. */\n export type Optimistic<T> = (\n draft: T,\n command: Command,\n ctx: StatewireClient.OptimisticContext,\n ) => void;\n\n export type HeadersValue = Record<string, string> | Headers;\n\n export type Protocol = \"data-stream\" | \"assistant-transport\";\n\n export type SendCommandsRequestBody = {\n commands: Command[];\n state: unknown;\n system: string | undefined;\n tools: Record<string, unknown> | undefined;\n callSettings: LanguageModelV1CallSettings | undefined;\n config: LanguageModelConfig | undefined;\n threadId: string | null;\n parentId?: string | null;\n [key: string]: unknown;\n };\n\n export type Options<T> = {\n initialState: T;\n converter: StateConverter<T>;\n optimistic?: Optimistic<T> | undefined;\n api: string;\n resumeApi?: string | undefined;\n protocol?: Protocol | undefined;\n headers: HeadersValue | (() => Promise<HeadersValue>);\n body?: object | (() => Promise<object | undefined>) | undefined;\n /** Transform the fully assembled request body before it is sent. */\n prepareSendCommandsRequest?:\n | ((\n body: SendCommandsRequestBody,\n ) => Record<string, unknown> | Promise<Record<string, unknown>>)\n | undefined;\n onResponse?: ((response: Response) => void) | undefined;\n onFinish?: (() => void) | undefined;\n onError?:\n | ((\n error: Error,\n params: {\n commands: Command[];\n updateState: (updater: (state: T) => T) => void;\n },\n ) => void | Promise<void>)\n | undefined;\n /**\n * Called when commands are cancelled. After an error, queued commands are\n * cancelled once `onError` settles; `error` then carries the cause.\n */\n onCancel?:\n | ((params: {\n commands: Command[];\n updateState: (updater: (state: T) => T) => void;\n error?: Error;\n }) => void)\n | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n /**\n * Buffer messages sent during a run in an in-memory queue and dispatch\n * them once the run settles. Steering interrupts the active run.\n * Mutually exclusive with the converter's `queue` projection.\n */\n queue?: boolean | undefined;\n /** The host supports `run/continue` (a continue affordance on aborted runs). */\n continue?: boolean | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n }\n | undefined;\n };\n}\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useAssistantTransportThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;;;;AAwDA,MAAM8C,sBAA2D,CAAC;AAClE,MAAME,oBAAgE,CAAA;AACtE,MAAMC,4BAA4B,CAAC;AAEnC,MAAaC,iCAAiCC,OAC5C,4BACF;AAaA,MAAaY,8BACXC,WAC6B;CAC7B,IACE,OAAOA,WAAW,YAClBA,UAAU,QACV,EAAEd,kCAAkCc,SAEpC,MAAM,IAAIC,MACR,+FACF;CAEF,OAAOD;AACT;AAEA,MAAME,kBACJR,OACAS,UACAC,YACAE,UACY;CACZ,IAAIE,OAAOd;CACX,KAAK,MAAMJ,WAAWa,UACpB,IAAI;EACFK,OAAO3C,gBAAgB2C,OAAOC,UAC5BL,WAAWK,OAAOnB,SAASgB,MAAMhB,OAAO,CAAC,CAC3C;CACF,SAASoB,OAAO;EACdC,QAAQD,MACN,4CAA4CpB,QAAQsB,KAAI,oCACxDF,KACF;CACF;CAEF,OAAOF;AACT;AAEA,MAAMK,2BACJC,UACAC,eAEAD,SAASE,MAAMC,YACbA,QAAQC,QAAQF,MACbG,SACCA,KAAKP,SAAS,gBACbO,KAAKJ,eAAeA,cAClBI,KAAKL,aAAaM,KAAAA,KACjBP,wBAAwBM,KAAKL,UAAUC,UAAU,EACzD,CACF;AAEF,MAAMM,+BACJC,YAC2B;CAC3B,MAAME,YAAY3E,sBAAsB;CACxC,MAAM,CAAC4E,iBAAiBrF,qBAAqC;EAC3D,MAAMsF,MAAMF,UAAUG,WAAWH,UAAUI;EAE3C,IAAIC,WAA0B;EAC9B,IAAI;GACFA,WAAWH,IAAII,eAAe,CAAC,CAACC,SAAS,CAAC,CAACC,YAAY;EACzD,QAAQ,CAAC;EACT,OAAO;GACLC,cAAcP,IAAIO,aAAa,CAAC,CAACC,gBAAgB;GACjDL;EACF;CACF,CAAC;CA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PF1E,uBACEyE,6BACA5E,eAAe2E,KAAAA,CAAkB,CAAC,CAACsL,IACrC"}
|
|
1
|
+
{"version":3,"file":"AssistantTransportThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","useSyncExternalStore","resource","useResource","ResourceElement","ExternalThread","Assistant","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","createMessageQueue","AddToolResultOptions","AppendMessage","AttachmentAdapter","LanguageModelConfig","LanguageModelV1CallSettings","MessageQueueController","MessageQueueDriver","RespondToToolApprovalOptions","ResumeToolCallOptions","ThreadMessage","ToolExecutionStatus","ReadonlyJSONValue","ToolInvocationTracker","applyOptimistic","useStatewire","StatewireClient","StatewireThread","AssistantTransportHost","AssistantTransportHostCommands","AssistantTransportHostState","HostQueueCell","HostRunContext","SendOptions","createRunQueueAdapter","resolveEditCommand","resolveReloadCommand","toWireMessage","viewedLeafId","runsOptimistic","resolveToolApprovalInput","resolveToolResultInput","EMPTY_TOOL_STATUSES","Record","EMPTY_QUEUE_ITEMS","subscribeNoop","symbolAssistantTransportExtras","Symbol","AssistantTransportExtras","sendCommand","command","AssistantTransportThread","Command","reconnect","state","inputRequests","InputRequestState","runs","Runs","asAssistantTransportExtras","extras","Error","foldOptimistic","commands","optimistic","Optimistic","ctxOf","OptimisticContext","next","draft","error","console","type","messagesContainToolCall","messages","toolCallId","some","message","content","part","undefined","useAssistantTransportThread","options","Options","clientRef","getRunContext","aui","current","parent","threadId","threadListItem","getState","remoteId","modelContext","getModelContext","queueCell","queued","inTransit","connection","transport","agent","agentState","isSending","isReplaying","queue","dispatch","opts","send","catch","toolStatuses","setToolStatuses","ctxs","WeakMap","seq","ctx","get","ts","Date","now","set","converter","runsOption","materialize","runsSeam","materializeSeam","project","fold","method","params","converted","convertedRef","toolInvocations","tools","onResult","onStatusesChange","statuses","size","Object","fromEntries","setState","isRunning","isLoading","reset","inputSeam","present","handleEdit","abort","then","handleAppend","sourceId","startRun","role","crypto","randomUUID","anchorMessageId","setParentId","parentId","schedule","handleCancel","cancel","driverRef","run","at","id","queueProjection","steerProjection","steerQueue","capabilities","queueSeam","serverQueue","enableQueue","queueRef","clear","messageQueue","queueItems","subscribe","adapter","items","steerQueueItems","steerItems","busy","keys","length","wasBusyRef","notifyBusy","notifyIdle","attachmentAdapter","adapters","attachments","onNew","edit","onEdit","onReload","onCancel","onResume","continue","resumeApi","resume","onAddToolResult","toolOptions","onRespondToToolApproval","onResumeToolCall","payload","onLoadExternalState","imported","importState","T","UserCommands","Commands","TextPart","text","FilePart","mediaType","url","filename","RunUserMessage","parts","metadata","RunPlacement","insertAfter","insertBefore","RunEnqueueCommand","messageId","RunSteerCommand","RunDequeueCommand","RunEditCommand","rollbackTo","RunContinueCommand","ToolCallInputRequest","ToolApprovalInputRequest","CustomInputRequest","key","InputRequest","ToolCallInputResponse","output","isError","artifact","ToolApprovalInputResponse","decision","editedArgs","InputResponse","RunInputCommand","requestId","response","RunReloadCommand","RunCommand","RunQueueItem","State","StateConverter","HeadersValue","Headers","Protocol","SendCommandsRequestBody","system","callSettings","config","initialState","Materialize","NonNullable","api","protocol","headers","Promise","body","prepareSendCommandsRequest","onResponse","Response","onFinish","onError","updateState","updater","hook"],"sources":["../src/AssistantTransportThread.ts"],"sourcesContent":["import {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport { resource, useResource } from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/react\";\nimport type { Assistant, ExternalThreadMessage } from \"@assistant-ui/react\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport { createMessageQueue } from \"@assistant-ui/core\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n AttachmentAdapter,\n LanguageModelConfig,\n LanguageModelV1CallSettings,\n MessageQueueController,\n MessageQueueDriver,\n RespondToToolApprovalOptions,\n ResumeToolCallOptions,\n ThreadMessage,\n ToolExecutionStatus,\n} from \"@assistant-ui/core\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { ToolInvocationTracker } from \"@assistant-ui/core/internal\";\nimport { applyOptimistic, useStatewire } from \"statewire\";\nimport type { StatewireClient } from \"statewire\";\nimport type { StatewireThread } from \"./StatewireThread\";\nimport { AssistantTransportHost } from \"./host\";\nimport type {\n AssistantTransportHostCommands,\n AssistantTransportHostState,\n HostQueueCell,\n HostRunContext,\n SendOptions,\n} from \"./host\";\nimport {\n createRunQueueAdapter,\n resolveEditCommand,\n resolveReloadCommand,\n toWireMessage,\n viewedLeafId,\n} from \"./runCommands\";\nimport { runsOptimistic } from \"./runsOptimistic\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\n\nconst EMPTY_TOOL_STATUSES: Record<string, ToolExecutionStatus> = {};\nconst EMPTY_QUEUE_ITEMS: MessageQueueController[\"adapter\"][\"items\"] = [];\nconst subscribeNoop = () => () => {};\n\nexport const symbolAssistantTransportExtras = Symbol(\n \"assistant-transport-extras\",\n);\n\nexport type AssistantTransportExtras = {\n [symbolAssistantTransportExtras]: true;\n sendCommand: (command: AssistantTransportThread.Command) => void;\n reconnect: () => void;\n state: unknown;\n /** The host's parked input requests; absent when the converter does not project them. */\n inputRequests?: readonly AssistantTransportThread.InputRequestState[];\n /** The typed runs read; present iff StatewireThread runs with the `runs` option. */\n runs?: StatewireThread.Runs;\n};\n\nexport const asAssistantTransportExtras = (\n extras: unknown,\n): AssistantTransportExtras => {\n if (\n typeof extras !== \"object\" ||\n extras == null ||\n !(symbolAssistantTransportExtras in extras)\n )\n throw new Error(\n \"This method can only be called when you are using AssistantTransportThread or StatewireThread\",\n );\n\n return extras as AssistantTransportExtras;\n};\n\nconst foldOptimistic = (\n state: unknown,\n commands: readonly AssistantTransportThread.Command[],\n optimistic: AssistantTransportThread.Optimistic<unknown>,\n ctxOf: (command: object) => StatewireClient.OptimisticContext,\n): unknown => {\n let next = state;\n for (const command of commands) {\n try {\n next = applyOptimistic(next, (draft) =>\n optimistic(draft, command, ctxOf(command)),\n );\n } catch (error) {\n console.error(\n `statewire: optimistic reducer threw for \"${command.type}\"; dropping its optimistic update`,\n error,\n );\n }\n }\n return next;\n};\n\nconst messagesContainToolCall = (\n messages: readonly ThreadMessage[],\n toolCallId: string,\n): boolean =>\n messages.some((message) =>\n message.content.some(\n (part) =>\n part.type === \"tool-call\" &&\n (part.toolCallId === toolCallId ||\n (part.messages !== undefined &&\n messagesContainToolCall(part.messages, toolCallId))),\n ),\n );\n\nconst useAssistantTransportThread = (\n options: AssistantTransportThread.Options<any>,\n): ClientOutput<\"thread\"> => {\n const clientRef = useAssistantClientRef();\n const [getRunContext] = useState(() => (): HostRunContext => {\n const aui = clientRef.current ?? clientRef.parent;\n // legacy parity: a threadListItem throw must not kill the run\n let threadId: string | null = null;\n try {\n threadId = aui.threadListItem().getState().remoteId ?? null;\n } catch {}\n return {\n modelContext: aui.modelContext().getModelContext(),\n threadId,\n };\n });\n\n const [queueCell] = useState(\n (): HostQueueCell => ({ current: { queued: [], inTransit: [] } }),\n );\n const { state, commands, connection } = useStatewire<\n AssistantTransportHostState,\n AssistantTransportHostCommands\n >({\n transport: AssistantTransportHost({ ...options, getRunContext, queueCell }),\n });\n const { agent: agentState, isSending, isReplaying } = state;\n const queue = queueCell.current;\n\n const dispatch = useCallback(\n (command: AssistantTransportThread.Command, opts?: SendOptions) => {\n void commands.send(command, opts).catch(() => {});\n },\n [commands],\n );\n\n const [toolStatuses, setToolStatuses] =\n useState<Record<string, ToolExecutionStatus>>(EMPTY_TOOL_STATUSES);\n\n const [ctxOf] = useState(() => {\n const ctxs = new WeakMap<object, StatewireClient.OptimisticContext>();\n let seq = 0;\n return (command: object): StatewireClient.OptimisticContext => {\n let ctx = ctxs.get(command);\n if (ctx === undefined) {\n ctx = { ts: Date.now(), seq: ++seq };\n ctxs.set(command, ctx);\n }\n return ctx;\n };\n });\n\n const { converter, optimistic, runs: runsOption, materialize } = options;\n const [runsSeam] = useState(() => runsOption !== undefined);\n if (runsSeam !== (runsOption !== undefined))\n throw new Error(\n \"statewire: the runs option must be stable — it was \" +\n (runsSeam ? \"set\" : \"unset\") +\n \" on first render and changed since\",\n );\n const [materializeSeam] = useState(() => materialize !== undefined);\n if (materializeSeam !== (materialize !== undefined))\n throw new Error(\n \"statewire: the materialize option must be stable — it was \" +\n (materializeSeam ? \"set\" : \"unset\") +\n \" on first render and changed since\",\n );\n\n const project = useCallback(\n (state: unknown): unknown => {\n const fold: AssistantTransportThread.Optimistic<unknown> | undefined =\n runsOption !== undefined\n ? (draft, command, ctx) => {\n runsOptimistic(\n runsOption === true ? draft : runsOption(draft as never),\n { method: command.type, params: [command] },\n ctx,\n );\n optimistic?.(draft, command, ctx);\n }\n : optimistic;\n let next = fold\n ? foldOptimistic(\n state,\n [...queue.inTransit, ...queue.queued],\n fold,\n ctxOf,\n )\n : state;\n if (materialize) {\n try {\n next = applyOptimistic(next, (draft) => materialize(draft as never));\n } catch (error) {\n console.error(\n \"statewire: materialize threw; publishing without its update\",\n error,\n );\n }\n }\n return next;\n },\n [runsOption, optimistic, materialize, queue, ctxOf],\n );\n const converted = useMemo(\n () => converter(project(agentState)),\n [converter, project, agentState],\n );\n const convertedRef = useRef(converted);\n convertedRef.current = converted;\n\n const [toolInvocations] = useState(\n () =>\n new ToolInvocationTracker(\n () => {\n const aui = clientRef.current ?? clientRef.parent;\n return aui.modelContext().getModelContext().tools;\n },\n {\n onResult: (command) => {\n const messages = convertedRef.current\n .messages as readonly ThreadMessage[];\n if (!messagesContainToolCall(messages, command.toolCallId)) return;\n dispatch(\n resolveToolResultInput(\n convertedRef.current.inputRequests ?? [],\n command,\n ),\n );\n },\n onStatusesChange: (statuses) => {\n setToolStatuses(\n statuses.size === 0\n ? EMPTY_TOOL_STATUSES\n : Object.fromEntries(statuses),\n );\n },\n },\n ),\n );\n // dep-less by design: setState dedups identical snapshots internally\n useEffect(() => {\n toolInvocations.setState({\n messages: converted.messages as readonly ThreadMessage[],\n isRunning: converted.isRunning,\n isLoading: isReplaying,\n });\n });\n useEffect(\n () => () => {\n toolInvocations.reset();\n },\n [toolInvocations],\n );\n\n const inputRequests = converted.inputRequests;\n const [inputSeam] = useState(() => ({\n present: inputRequests !== undefined,\n }));\n if (inputSeam.present !== (inputRequests !== undefined))\n throw new Error(\n \"statewire: the converter's inputRequests projection must be stable — it was \" +\n (inputSeam.present ? \"defined\" : \"undefined\") +\n \" on first convert and changed since\",\n );\n\n const extras = useMemo(\n (): AssistantTransportExtras => ({\n [symbolAssistantTransportExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state: agentState,\n ...(inputRequests !== undefined && { inputRequests }),\n }),\n [dispatch, connection.reconnect, agentState, inputRequests],\n );\n\n const handleEdit = (message: AppendMessage) => {\n const command = resolveEditCommand(convertedRef.current.messages, message);\n void toolInvocations.abort().then(() => dispatch(command));\n };\n\n const handleAppend = (message: AppendMessage) => {\n if (message.sourceId != null) return handleEdit(message);\n const startRun = message.startRun ?? message.role === \"user\";\n const command: AssistantTransportThread.Command = {\n type: \"run/steer\",\n message: toWireMessage(message, crypto.randomUUID()),\n anchorMessageId: viewedLeafId(convertedRef.current.messages),\n };\n void commands.setParentId(message.parentId).catch(() => {});\n\n const send = () => dispatch(command, { schedule: startRun });\n if (startRun) {\n // abort in-flight tool executions so their late results cannot race the new turn\n void toolInvocations.abort().then(send);\n } else {\n send();\n }\n };\n\n const handleCancel = () => {\n void toolInvocations.abort();\n void commands.cancel().catch(() => {});\n };\n\n const driverRef = useRef<{\n run: MessageQueueDriver[\"run\"];\n cancel: () => void;\n }>(undefined as never);\n driverRef.current = {\n // the queued message was stamped with the head at enqueue time; restamp so\n // it appends to the thread the finished run left behind\n run: (message) =>\n handleAppend({\n ...message,\n parentId: convertedRef.current.messages.at(-1)?.id ?? null,\n }),\n cancel: handleCancel,\n };\n\n const queueProjection = converted.queue;\n const steerProjection = converted.steerQueue;\n if (steerProjection !== undefined && queueProjection === undefined)\n throw new Error(\n \"statewire: the converter's steerQueue projection requires the queue projection\",\n );\n if (queueProjection !== undefined && options.capabilities?.queue)\n throw new Error(\n \"statewire: the converter's queue projection excludes capabilities.queue\",\n );\n const [queueSeam] = useState(() => ({\n present: queueProjection !== undefined,\n }));\n if (queueSeam.present !== (queueProjection !== undefined))\n throw new Error(\n \"statewire: the converter's queue projection must be stable — it was \" +\n (queueSeam.present ? \"defined\" : \"undefined\") +\n \" on first convert and changed since\",\n );\n const serverQueue = useMemo(\n () =>\n queueProjection\n ? createRunQueueAdapter(\n converted.messages,\n queueProjection,\n steerProjection,\n dispatch,\n (command) => dispatch(command),\n )\n : undefined,\n [converted.messages, queueProjection, steerProjection, dispatch],\n );\n\n const enableQueue = options.capabilities?.queue === true;\n const queueRef = useRef<MessageQueueController | null>(null);\n if (enableQueue && !queueRef.current) {\n queueRef.current = createMessageQueue({\n run: (message, opts) => driverRef.current.run(message, opts),\n cancel: () => driverRef.current.cancel(),\n });\n } else if (!enableQueue && queueRef.current) {\n queueRef.current.clear();\n queueRef.current = null;\n }\n const messageQueue = queueRef.current;\n\n // fresh view per snapshot: the controller mutates adapter.items in place,\n // which a stable prop identity would hide from the thread resource\n const queueItems = useSyncExternalStore(\n messageQueue?.subscribe ?? subscribeNoop,\n () => messageQueue?.adapter.items ?? EMPTY_QUEUE_ITEMS,\n () => EMPTY_QUEUE_ITEMS,\n );\n const steerQueueItems = useSyncExternalStore(\n messageQueue?.subscribe ?? subscribeNoop,\n () => messageQueue?.adapter.steerItems ?? EMPTY_QUEUE_ITEMS,\n () => EMPTY_QUEUE_ITEMS,\n );\n\n // settled edge: the queue only advances once the host run loop has fully\n // released (isSending), the converted state agrees, and no client tool from\n // the finished run is still executing\n const busy =\n isSending || converted.isRunning || Object.keys(toolStatuses).length > 0;\n const wasBusyRef = useRef(false);\n useEffect(() => {\n if (wasBusyRef.current === busy) return;\n wasBusyRef.current = busy;\n if (busy) messageQueue?.notifyBusy();\n else messageQueue?.notifyIdle();\n });\n\n return useResource(\n ExternalThread({\n messages: converted.messages as readonly ExternalThreadMessage[],\n isRunning: converted.isRunning,\n isLoading: isReplaying,\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n onNew: handleAppend,\n ...(serverQueue\n ? { queue: serverQueue }\n : messageQueue && {\n queue: {\n ...messageQueue.adapter,\n items: queueItems,\n steerItems: steerQueueItems,\n },\n }),\n ...(options.capabilities?.edit && { onEdit: handleEdit }),\n onReload: (parentId: string | null) => {\n const command = resolveReloadCommand(\n convertedRef.current.messages,\n parentId,\n );\n void toolInvocations.abort().then(() => dispatch(command));\n },\n onCancel: () => {\n // user cancel drops pending lanes; a steer interrupt (driver.cancel) keeps them\n messageQueue?.clear();\n handleCancel();\n },\n onResume: () => {\n if (options.capabilities?.continue) {\n dispatch({ type: \"run/continue\" });\n return;\n }\n if (!options.resumeApi)\n throw new Error(\"Must pass resumeApi to options to resume runs\");\n void commands.resume().catch(() => {});\n },\n ...(inputRequests !== undefined && {\n onAddToolResult: (toolOptions: AddToolResultOptions) =>\n dispatch(\n resolveToolResultInput(\n convertedRef.current.inputRequests!,\n toolOptions,\n ),\n ),\n onRespondToToolApproval: (options: RespondToToolApprovalOptions) =>\n dispatch(\n resolveToolApprovalInput(\n convertedRef.current.inputRequests!,\n options,\n ),\n ),\n }),\n onResumeToolCall: ({ toolCallId, payload }: ResumeToolCallOptions) => {\n if (!toolInvocations.resume(toolCallId, payload))\n throw new Error(`Tool call ${toolCallId} is not waiting for resume.`);\n },\n onLoadExternalState: (imported: unknown) => {\n void commands.importState(imported).catch(() => {});\n // reset() aborts tools before React re-renders — gate their late results against the imported state\n convertedRef.current = converter(project(imported));\n toolInvocations.reset();\n setToolStatuses(EMPTY_TOOL_STATUSES);\n },\n }),\n );\n};\n\nexport const AssistantTransportThread = <T>(\n options: AssistantTransportThread.Options<T>,\n): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useAssistantTransportThread)(\n options as AssistantTransportThread.Options<any>,\n );\n\nexport namespace AssistantTransportThread {\n type UserCommands = Assistant.Commands[keyof Assistant.Commands];\n\n export type TextPart = {\n readonly type: \"text\";\n readonly text: string;\n };\n\n export type FilePart = {\n readonly type: \"file\";\n readonly mediaType: string;\n readonly url: string;\n readonly filename?: string;\n };\n\n export type RunUserMessage = {\n readonly id: string;\n readonly role: \"user\";\n readonly parts: readonly (TextPart | FilePart)[];\n readonly metadata?: Record<string, unknown>;\n };\n\n /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */\n export type RunPlacement = {\n readonly insertAfter?: string | null;\n readonly insertBefore?: string | null;\n };\n\n export type RunEnqueueCommand = {\n readonly type: \"run/enqueue\";\n } & (\n | {\n readonly message: RunUserMessage;\n /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */\n readonly anchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n RunPlacement;\n\n export type RunSteerCommand = {\n readonly type: \"run/steer\";\n } & (\n | {\n readonly message: RunUserMessage;\n /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */\n readonly anchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n RunPlacement;\n\n export type RunDequeueCommand = {\n readonly type: \"run/dequeue\";\n readonly messageId: string;\n };\n\n export type RunEditCommand = {\n readonly type: \"run/edit\";\n readonly message: RunUserMessage;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly rollbackTo: string | null;\n };\n\n export type RunContinueCommand = {\n readonly type: \"run/continue\";\n };\n\n export type ToolCallInputRequest = {\n readonly type: \"tool-call\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type ToolApprovalInputRequest = {\n readonly type: \"tool-approval\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type CustomInputRequest = {\n readonly type: string;\n readonly id: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A host request parking the run until answered; open union for custom types. */\n export type InputRequest =\n | ToolCallInputRequest\n | ToolApprovalInputRequest\n | CustomInputRequest;\n\n export type ToolCallInputResponse = {\n readonly output: ReadonlyJSONValue;\n /** Default false; when true, `output` carries the error payload. */\n readonly isError?: boolean;\n readonly artifact?: ReadonlyJSONValue;\n };\n\n export type ToolApprovalInputResponse = {\n readonly decision: \"approve\" | \"reject\" | \"edit\" | \"respond\";\n readonly editedArgs?: ReadonlyJSONValue;\n readonly message?: string;\n };\n\n export type InputResponse = ReadonlyJSONValue;\n\n export type RunInputCommand = {\n readonly type: \"run/input\";\n readonly requestId: string;\n readonly response: InputResponse;\n };\n\n /** An input request projected out of the host state with its response echo. */\n export type InputRequestState = InputRequest & {\n readonly response: InputResponse | null;\n };\n\n export type RunReloadCommand = {\n readonly type: \"run/reload\";\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly rollbackTo: string | null;\n };\n\n export type RunCommand =\n | RunEnqueueCommand\n | RunSteerCommand\n | RunDequeueCommand\n | RunEditCommand\n | RunContinueCommand\n | RunReloadCommand\n | RunInputCommand;\n\n export type Command = RunCommand | UserCommands;\n\n /** A queued message projected out of the host state, wire shape. */\n export type RunQueueItem = {\n readonly id: string;\n readonly parts: readonly (TextPart | FilePart)[];\n };\n\n export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n readonly isRunning: boolean;\n /**\n * The host's regular queue lane projected out of the state. Returning it\n * (even empty) turns on the server-side queue: sends become `run/enqueue`\n * / `run/steer` commands and item controls send the `run/*` queue\n * commands. Presence must be stable across conversions and excludes the\n * client-local `capabilities.queue` buffer.\n */\n readonly queue?: readonly RunQueueItem[];\n /** The host's steer lane; requires `queue`. Absent means empty. */\n readonly steerQueue?: readonly RunQueueItem[];\n /**\n * The host's parked input requests projected out of the state. Returning it\n * (even empty) routes tool results and approvals with a matching pending\n * request through `run/input`. Presence must be stable across conversions.\n */\n readonly inputRequests?: readonly AssistantTransportThread.InputRequestState[];\n };\n\n export type StateConverter<T> = (state: T) => State;\n\n /** Folds an unsettled command into a draft of the client state; called once per pending command, in send order, re-run on every state change. A throwing fold logs and drops that command's update. */\n export type Optimistic<T> = (\n draft: T,\n command: Command,\n ctx: StatewireClient.OptimisticContext,\n ) => void;\n\n export type HeadersValue = Record<string, string> | Headers;\n\n export type Protocol = \"data-stream\" | \"assistant-transport\";\n\n export type SendCommandsRequestBody = {\n commands: Command[];\n state: unknown;\n system: string | undefined;\n tools: Record<string, unknown> | undefined;\n callSettings: LanguageModelV1CallSettings | undefined;\n config: LanguageModelConfig | undefined;\n threadId: string | null;\n parentId?: string | null;\n [key: string]: unknown;\n };\n\n export type Options<T> = {\n initialState: T;\n converter: StateConverter<T>;\n optimistic?: Optimistic<T> | undefined;\n /** Folds the lib's run-dialect optimistic reducer before `optimistic`: `true` reads the run mounts off the state root; a selector picks a nested mount. */\n runs?: true | ((state: T) => unknown) | undefined;\n /** Makes dispatch records concrete in the draft (runs after the optimistic folds); without it, dispatch limbo stays out of `messages`. */\n materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;\n api: string;\n resumeApi?: string | undefined;\n protocol?: Protocol | undefined;\n headers: HeadersValue | (() => Promise<HeadersValue>);\n body?: object | (() => Promise<object | undefined>) | undefined;\n /** Transform the fully assembled request body before it is sent. */\n prepareSendCommandsRequest?:\n | ((\n body: SendCommandsRequestBody,\n ) => Record<string, unknown> | Promise<Record<string, unknown>>)\n | undefined;\n onResponse?: ((response: Response) => void) | undefined;\n onFinish?: (() => void) | undefined;\n onError?:\n | ((\n error: Error,\n params: {\n commands: Command[];\n updateState: (updater: (state: T) => T) => void;\n },\n ) => void | Promise<void>)\n | undefined;\n /**\n * Called when commands are cancelled. After an error, queued commands are\n * cancelled once `onError` settles; `error` then carries the cause.\n */\n onCancel?:\n | ((params: {\n commands: Command[];\n updateState: (updater: (state: T) => T) => void;\n error?: Error;\n }) => void)\n | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n /**\n * Buffer messages sent during a run in an in-memory queue and dispatch\n * them once the run settles. Steering interrupts the active run.\n * Mutually exclusive with the converter's `queue` projection.\n */\n queue?: boolean | undefined;\n /** The host supports `run/continue` (a continue affordance on aborted runs). */\n continue?: boolean | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n }\n | undefined;\n };\n}\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useAssistantTransportThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;;;;;AAyDA,MAAM+C,sBAA2D,CAAC;AAClE,MAAME,oBAAgE,CAAA;AACtE,MAAMC,4BAA4B,CAAC;AAEnC,MAAaC,iCAAiCC,OAC5C,4BACF;AAaA,MAAaY,8BACXC,WAC6B;CAC7B,IACE,OAAOA,WAAW,YAClBA,UAAU,QACV,EAAEd,kCAAkCc,SAEpC,MAAM,IAAIC,MACR,+FACF;CAEF,OAAOD;AACT;AAEA,MAAME,kBACJR,OACAS,UACAC,YACAE,UACY;CACZ,IAAIE,OAAOd;CACX,KAAK,MAAMJ,WAAWa,UACpB,IAAI;EACFK,OAAO5C,gBAAgB4C,OAAOC,UAC5BL,WAAWK,OAAOnB,SAASgB,MAAMhB,OAAO,CAAC,CAC3C;CACF,SAASoB,OAAO;EACdC,QAAQD,MACN,4CAA4CpB,QAAQsB,KAAI,oCACxDF,KACF;CACF;CAEF,OAAOF;AACT;AAEA,MAAMK,2BACJC,UACAC,eAEAD,SAASE,MAAMC,YACbA,QAAQC,QAAQF,MACbG,SACCA,KAAKP,SAAS,gBACbO,KAAKJ,eAAeA,cAClBI,KAAKL,aAAaM,KAAAA,KACjBP,wBAAwBM,KAAKL,UAAUC,UAAU,EACzD,CACF;AAEF,MAAMM,+BACJC,YAC2B;CAC3B,MAAME,YAAY5E,sBAAsB;CACxC,MAAM,CAAC6E,iBAAi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vD+C,WAAWpC,aAA4B;GACrC,MAAM1G,YAAUd,qBACd8F,aAAa3C,QAAQb,UACrBkF,QACF;GACA,gBAAqBV,MAAM,CAAC,CAACC,WAAW1C,SAASvD,SAAO,CAAC;EAC3D;EACA+I,gBAAgB;GAEdpB,cAAcD,MAAM;GACpBd,aAAa;EACf;EACAoC,gBAAgB;GACd,IAAIhH,QAAQqF,cAAc4B,UAAU;IAClC1F,SAAS,EAAEjC,MAAM,eAAe,CAAC;IACjC;GACF;GACA,IAAI,CAACU,QAAQkH,WACX,MAAM,IAAIvI,MAAM,+CAA+C;GACjE,SAAcwI,OAAO,CAAC,CAACzF,YAAY,CAAC,CAAC;EACvC;EACA,GAAIrD,kBAAkByB,KAAAA,KAAa;GACjCsH,kBAAkBC,gBAChB9F,SACEhE,uBACEyF,aAAa3C,QAAQhC,eACrBgJ,WACF,CACF;GACFC,0BAA0BtH,cACxBuB,SACEjE,yBACE0F,aAAa3C,QAAQhC,eACrB2B,SACF,CACF;EACJ;EACAuH,mBAAmB,EAAE9H,YAAY+H,cAAqC;GACpE,IAAI,CAACvE,gBAAgBkE,OAAO1H,YAAY+H,OAAO,GAC7C,MAAM,IAAI7I,MAAM,aAAac,WAAU,4BAA6B;EACxE;EACAgI,sBAAsBC,aAAsB;GAC1C,SAAcC,YAAYD,QAAQ,CAAC,CAAChG,YAAY,CAAC,CAAC;GAElDsB,aAAa3C,UAAUiC,UAAUK,QAAQ+E,QAAQ,CAAC;GAClDzE,gBAAgBW,MAAM;GACtBhC,gBAAgBpE,mBAAmB;EACrC;CACF,CAAC,CACH;AACF;AAEA,MAAaS,4BACX+B,YAEAjF,SAASgF,2BAA2B,CAAC,CACnCC,OACF;AA+PF3E,uBACE0E,6BACA7E,eAAe4E,KAAAA,CAAkB,CAAC,CAAC+L,IACrC"}
|
|
@@ -274,7 +274,7 @@ declare namespace StatewireThread {
|
|
|
274
274
|
converter: RunsStateConverter<T>;
|
|
275
275
|
/** Folds app-owned keys for an unsettled command into the draft; runs after the lib's run-dialect reducer. */
|
|
276
276
|
optimistic?: StatewireClient.Optimistic<T, Record<string, (...args: any[]) => unknown>> | undefined;
|
|
277
|
-
/** Makes dispatch records concrete in the draft (runs after the optimistic folds);
|
|
277
|
+
/** Makes dispatch records concrete in the draft (runs after the optimistic folds); without it, dispatch limbo stays out of `messages`. */
|
|
278
278
|
materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;
|
|
279
279
|
};
|
|
280
280
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;;cAgXa;GACV,GACC,SAAS,gBAAgB,YAAY,KACpC,gBAAgB;GAClB,GACC,SAAS,gBAAgB,QAAQ,KAChC,gBAAgB;;kBAIJ;OACH,UAAU,KAAK,gBAAgB,UAAU;OAEzC;aACD;aACA;;OAGC;aACD;aACA;aACA;aACA;;OAGC;aACD;aACA;aACA,iBAAiB,WAAW;aAC5B,WAAW;;;OAIV;aACD;aACA;;OAGC;aACD;;aAGI,SAAS;;aAET;;aAEA;OAEb;OAEU;aACD;;aAGI,SAAS;;aAET;;aAEA;OAEb;OAEU;aACD;aACA;;OAGC;aACD;aACA,SAAS;aACT;;aAEA;;OAGC;aACD;;OAGC;aACD;aACA;aACA;;OAGC;aACD;aACA;aACA;;OAGC;aACD;aACA;cACC,cAAc;;;OAId,eACR,uBACA,2BACA;OAEQ;aACD,QAAQ;;aAER;aACA,WAAW;;OAGV;aACD;aACA,aAAa;aACb;;OAGC,gBAAgB;OAEhB;aACD;aACA;aACA,UAAU;;;OAIT,oBAAoB;aACrB,UAAU;;OAGT;aACD;aACA;;aAEA;;OAGC,aACR,oBACA,kBACA,oBACA,iBACA,qBACA,mBACA;OAEQ,UAAU,yBAAyB,UAAU;;OAG7C;aACD;aACA,iBAAiB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,gBAAgB,YAAY,YAAY;;;;YAK9C;cACE;MACR,YAAY,gBAAgB;MAC5B,UAAU,gBAAgB;MAC1B,YAAY,gBAAgB;MAC5B,SAAS,gBAAgB;MACzB,aAAa,gBAAgB;MAC7B,WAAW,gBAAgB;MAC3B,UAAU,gBAAgB"}
|
package/dist/StatewireThread.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { createRunQueueAdapter, resolveEditCommand, resolveReloadCommand,
|
|
1
|
+
import { createRunQueueAdapter, resolveEditCommand, resolveReloadCommand, toWireMessage, viewedLeafId } from "./runCommands.js";
|
|
2
|
+
import { runsOptimistic } from "./runsOptimistic.js";
|
|
2
3
|
import { resolveToolApprovalInput, resolveToolResultInput } from "./inputRequests.js";
|
|
3
4
|
import { symbolAssistantTransportExtras } from "./AssistantTransportThread.js";
|
|
4
|
-
import { runsOptimistic } from "./runsOptimistic.js";
|
|
5
5
|
import { useCallback, useEffect, useMemo, useRef, useState } from "@assistant-ui/tap/react-shim";
|
|
6
6
|
import { resource, useResource } from "@assistant-ui/tap";
|
|
7
7
|
import { ExternalThread } from "@assistant-ui/react";
|
|
@@ -123,20 +123,7 @@ const useStatewireThread = (options) => {
|
|
|
123
123
|
state_0,
|
|
124
124
|
metadata
|
|
125
125
|
]);
|
|
126
|
-
const messages =
|
|
127
|
-
const record = runs?.dispatching ?? null;
|
|
128
|
-
if (record === null || materializeSeam) return converted.messages;
|
|
129
|
-
let base = converted.messages;
|
|
130
|
-
if ("rollbackTo" in record) base = record.rollbackTo == null ? [] : base.slice(0, base.findIndex((m) => m.id === record.rollbackTo) + 1);
|
|
131
|
-
const known = new Set(base.map((m_0) => m_0.id));
|
|
132
|
-
const pending_0 = record.messages.filter((e) => !known.has(e.id));
|
|
133
|
-
if (pending_0.length === 0) return base;
|
|
134
|
-
return [...base, ...pending_0.map(toDispatchingMessage)];
|
|
135
|
-
}, [
|
|
136
|
-
converted.messages,
|
|
137
|
-
runs,
|
|
138
|
-
materializeSeam
|
|
139
|
-
]);
|
|
126
|
+
const messages = converted.messages;
|
|
140
127
|
const queueItems = runs !== void 0 ? runs.queue : converted.queue;
|
|
141
128
|
const steerQueueItems = runs !== void 0 ? runs.steerQueue : converted.steerQueue;
|
|
142
129
|
if (steerQueueItems !== void 0 && queueItems === void 0) throw new Error("statewire: the converter's steerQueue projection requires the queue projection");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","AddToolResultOptions","AppendMessage","AttachmentAdapter","ExternalThreadQueueAdapter","FeedbackAdapter","ModelContext","RespondToToolApprovalOptions","SpeechSynthesisAdapter","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","StatewireClient","symbolAssistantTransportExtras","AssistantTransportExtras","AssistantTransportThread","createRunQueueAdapter","resolveEditCommand","resolveReloadCommand","toDispatchingMessage","toWireMessage","viewedLeafId","resolveToolApprovalInput","resolveToolResultInput","runsOptimistic","AnyCommands","Record","args","AnyOptions","StatewireThread","Options","RunsOptions","READY_RUNS","Runs","status","runId","queue","steerQueue","dispatching","error","ambientContextOf","context","system","undefined","tools","callSettings","config","useStatewireThread","options","latest","current","pending","setPending","Command","retire","command","prev","includes","filter","c","runsOption","runs","runsSeam","Error","materializeOption","materialize","materializeSeam","state","transportState","commands","connection","setContext","transport","optimistic","draft","ctx","runsOpt","onCommandChange","update","params","onStateChange","onConnectionChange","attached","initialState","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","catch","onError","subscribe","dispatch","settled","type","threadRef","dispatchSend","message","sourceId","text","content","flatMap","part","join","setText","composer","next","mount","RunsState","entry","inputRequests","converter","metadata","ConnectionMetadata","pendingCommands","isSending","length","converted","State","messages","record","base","rollbackTo","slice","findIndex","m","id","known","Set","map","e","has","queueItems","steerQueueItems","queueSeam","present","inputSeam","extras","sendCommand","reconnect","handleAppend","crypto","randomUUID","anchorMessageId","handleReload","parentId","handleEdit","thread","isRunning","isLoading","attachmentAdapter","adapters","attachments","speechAdapter","speech","feedbackAdapter","feedback","onNew","capabilities","edit","onEdit","continue","onResume","reload","onReload","onAddToolResult","toolOptions","onRespondToToolApproval","approval","onCancel","payload","stopPayload","Array","isArray","T","Transport","TextPart","FilePart","mediaType","url","filename","UserMessage","role","parts","Placement","insertAfter","insertBefore","RunEnqueueCommand","messageId","RunSteerCommand","RunDequeueCommand","RunEditCommand","RunContinueCommand","ToolCallInputRequest","toolCallId","ToolApprovalInputRequest","CustomInputRequest","InputRequest","ToolCallInputResponse","output","isError","artifact","ToolApprovalInputResponse","decision","editedArgs","InputResponse","RunInputCommand","requestId","response","InputRequestState","RunReloadCommand","RunCommand","QueueItem","RunStatus","RunsQueueEntry","meta","RunsInputOutcome","request","RunsDispatch","trigger","inputOutcomes","RunsError","RunState","Exclude","MaterializeEffects","append","rollback","to","ConnectionState","StateConverter","connectionMetadata","RunsConverterState","RunsStateConverter","StopPayload","reason","CommandUpdate","NonNullable","changes","Changes","Connection","Omit","Optimistic","Materialize","Assistant","Commands","runEnqueue","runSteer","runDequeue","runEdit","runContinue","runReload","runInput","hook"],"sources":["../src/StatewireThread.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { resource, useResource } from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/react\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/react\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n AttachmentAdapter,\n ExternalThreadQueueAdapter,\n FeedbackAdapter,\n ModelContext,\n RespondToToolApprovalOptions,\n SpeechSynthesisAdapter,\n ThreadMessage,\n} from \"@assistant-ui/core\";\nimport { toToolsJSONSchema } from \"assistant-stream\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { useStatewire } from \"statewire\";\nimport type { Statewire, StatewireClient } from \"statewire\";\nimport { symbolAssistantTransportExtras } from \"./AssistantTransportThread\";\nimport type {\n AssistantTransportExtras,\n AssistantTransportThread,\n} from \"./AssistantTransportThread\";\nimport {\n createRunQueueAdapter,\n resolveEditCommand,\n resolveReloadCommand,\n toDispatchingMessage,\n toWireMessage,\n viewedLeafId,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\nimport { runsOptimistic } from \"./runsOptimistic\";\n\ntype AnyCommands = Record<string, (...args: any[]) => unknown>;\n\ntype AnyOptions =\n | StatewireThread.Options<any>\n | StatewireThread.RunsOptions<any>;\n\nconst READY_RUNS: StatewireThread.Runs = {\n status: \"ready\",\n runId: null,\n queue: [],\n steerQueue: [],\n dispatching: null,\n error: null,\n};\n\nconst ambientContextOf = (context: ModelContext): Record<string, unknown> => ({\n ...(context.system !== undefined && { system: context.system }),\n ...(context.tools !== undefined && {\n tools: toToolsJSONSchema(context.tools),\n }),\n ...(context.callSettings !== undefined && {\n callSettings: context.callSettings,\n }),\n ...(context.config !== undefined && { config: context.config }),\n});\n\nconst useStatewireThread = (options: AnyOptions): ClientOutput<\"thread\"> => {\n const latest = useRef(options);\n latest.current = options;\n\n const [pending, setPending] = useState<readonly StatewireThread.Command[]>(\n [],\n );\n const [retire] = useState(\n () => (command: unknown) =>\n setPending((prev) =>\n prev.includes(command as StatewireThread.Command)\n ? prev.filter((c) => c !== command)\n : prev,\n ),\n );\n\n const runsOption = options.runs;\n const [runsSeam] = useState(() => runsOption !== undefined);\n if (runsSeam !== (runsOption !== undefined))\n throw new Error(\n \"statewire: the runs option must be stable — it was \" +\n (runsSeam ? \"set\" : \"unset\") +\n \" on first render and changed since\",\n );\n\n const materializeOption = (options as StatewireThread.RunsOptions<unknown>)\n .materialize;\n const [materializeSeam] = useState(() => materializeOption !== undefined);\n if (materializeSeam !== (materializeOption !== undefined))\n throw new Error(\n \"statewire: the materialize option must be stable — it was \" +\n (materializeSeam ? \"set\" : \"unset\") +\n \" on first render and changed since\",\n );\n\n const {\n state: transportState,\n commands,\n connection,\n setContext,\n } = useStatewire<unknown, AnyCommands>({\n transport: options.transport,\n ...(runsSeam && {\n optimistic: (draft, command, ctx) => {\n const runsOpt = latest.current.runs!;\n runsOptimistic(runsOpt === true ? draft : runsOpt(draft), command, ctx);\n (latest.current as StatewireThread.RunsOptions<unknown>).optimistic?.(\n draft,\n command,\n ctx,\n );\n },\n }),\n ...(materializeSeam && {\n materialize: (draft: {}) =>\n (latest.current as StatewireThread.RunsOptions<unknown>).materialize!(\n draft,\n ),\n }),\n onCommandChange: (update, ctx) => {\n if (update.status === \"acked\" || update.status === \"settled\")\n retire(update.params[0]);\n latest.current.onCommandChange?.(update, ctx);\n },\n onStateChange: (state, ctx) => latest.current.onStateChange?.(state, ctx),\n onConnectionChange: (connection) =>\n latest.current.onConnectionChange?.(connection),\n });\n const attached = transportState !== undefined;\n const state = attached ? transportState : options.initialState;\n\n const clientRef = useAssistantClientRef();\n const setContextRef = useRef(setContext);\n setContextRef.current = setContext;\n const [syncState] = useState(() => ({ lastSent: undefined as unknown }));\n const { contextSync } = options;\n useEffect(() => {\n if (contextSync === undefined) return;\n const modelContext = (clientRef.current ?? clientRef.parent).modelContext();\n const send = () => {\n const value = ambientContextOf(modelContext.getModelContext());\n const key = JSON.stringify(value);\n if (key === syncState.lastSent) return;\n syncState.lastSent = key;\n void setContextRef.current(value).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n };\n send();\n if (!modelContext.subscribe) {\n throw new Error(\n \"statewire: contextSync requires a subscribable model context\",\n );\n }\n return modelContext.subscribe(send);\n }, [contextSync, clientRef, syncState]);\n\n const dispatch = useCallback(\n (command: StatewireThread.Command) => {\n setPending((prev) => [...prev, command]);\n const settled = commands[command.type]!(command);\n settled.catch((error: Error) => {\n retire(command);\n latest.current.onError?.(error);\n });\n return settled;\n },\n [commands, retire],\n );\n\n const threadRef = useRef<ClientOutput<\"thread\"> | null>(null);\n const dispatchSend = useCallback(\n (command: StatewireThread.Command, message: AppendMessage) => {\n if (message.sourceId != null) return void dispatch(command);\n const text = message.content\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\");\n void dispatch(command).catch(() => {\n // Rejected send: put the text back unless the user typed since.\n // ExternalThread's setText is live-ref-backed and takes an updater.\n const setText = threadRef.current!.composer().setText as (\n next: string | ((prev: string) => string),\n ) => void;\n setText((prev) => (prev === \"\" ? text : prev));\n });\n },\n [dispatch],\n );\n\n const runs = useMemo((): StatewireThread.Runs | undefined => {\n if (runsOption === undefined) return undefined;\n const mount = (runsOption === true ? state : runsOption(state)) as\n | StatewireThread.RunsState\n | undefined;\n const entry = mount?.runs?.[0];\n return entry === undefined\n ? READY_RUNS\n : {\n status: entry.status,\n runId: entry.runId,\n queue: entry.queue,\n steerQueue: entry.steerQueue,\n dispatching: entry.dispatching,\n ...(entry.inputRequests !== undefined && {\n inputRequests: entry.inputRequests,\n }),\n error: entry.error,\n };\n }, [runsOption, state]);\n\n const { converter } = options;\n const metadata = useMemo(\n (): StatewireThread.ConnectionMetadata => ({\n pendingCommands: [...pending],\n isSending: pending.length > 0,\n connection,\n ...(runs !== undefined && { runs }),\n }),\n [pending, connection, runs],\n );\n const converted = useMemo(\n () =>\n converter(\n state,\n metadata as StatewireThread.ConnectionMetadata & {\n runs: StatewireThread.Runs;\n },\n ) as StatewireThread.State,\n [converter, state, metadata],\n );\n // Dispatch limbo renders as in-flight messages; ids already converted win.\n // A rollbackTo key truncates to the rolled-back view first (null = root).\n // A materialize option owns this projection state-side; no post-convert merge.\n const messages = useMemo((): StatewireThread.State[\"messages\"] => {\n const record = runs?.dispatching ?? null;\n if (record === null || materializeSeam) return converted.messages;\n let base = converted.messages;\n if (\"rollbackTo\" in record) {\n base =\n record.rollbackTo == null\n ? []\n : base.slice(\n 0,\n base.findIndex((m) => m.id === record.rollbackTo) + 1,\n );\n }\n const known = new Set(base.map((m) => m.id));\n const pending = record.messages.filter((e) => !known.has(e.id));\n if (pending.length === 0) return base;\n return [...base, ...pending.map(toDispatchingMessage)];\n }, [converted.messages, runs, materializeSeam]);\n const queueItems = runs !== undefined ? runs.queue : converted.queue;\n const steerQueueItems =\n runs !== undefined ? runs.steerQueue : converted.steerQueue;\n if (steerQueueItems !== undefined && queueItems === undefined)\n throw new Error(\n \"statewire: the converter's steerQueue projection requires the queue projection\",\n );\n const [queueSeam] = useState(() => ({\n present: queueItems !== undefined,\n }));\n if (queueSeam.present !== (queueItems !== undefined))\n throw new Error(\n \"statewire: the converter's queue projection must be stable — it was \" +\n (queueSeam.present ? \"defined\" : \"undefined\") +\n \" on first convert and changed since\",\n );\n\n const queue = useMemo(\n (): ExternalThreadQueueAdapter | undefined =>\n queueItems\n ? createRunQueueAdapter(\n messages,\n queueItems,\n steerQueueItems,\n dispatch,\n dispatchSend,\n )\n : undefined,\n [messages, queueItems, steerQueueItems, dispatch, dispatchSend],\n );\n\n const inputRequests =\n runs !== undefined ? (runs.inputRequests ?? []) : converted.inputRequests;\n const [inputSeam] = useState(() => ({\n present: inputRequests !== undefined,\n }));\n if (inputSeam.present !== (inputRequests !== undefined))\n throw new Error(\n \"statewire: the converter's inputRequests projection must be stable — it was \" +\n (inputSeam.present ? \"defined\" : \"undefined\") +\n \" on first convert and changed since\",\n );\n\n const extras = useMemo(\n (): AssistantTransportExtras => ({\n [symbolAssistantTransportExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state,\n ...(inputRequests !== undefined && { inputRequests }),\n ...(runs !== undefined && { runs }),\n }),\n [dispatch, connection.reconnect, state, inputRequests, runs],\n );\n\n const handleAppend = (message: AppendMessage) => {\n dispatchSend(\n message.sourceId != null\n ? resolveEditCommand(messages, message)\n : {\n type: \"run/steer\",\n message: toWireMessage(message, crypto.randomUUID()),\n anchorMessageId: viewedLeafId(messages),\n },\n message,\n );\n };\n\n const handleReload = (parentId: string | null) => {\n dispatch(resolveReloadCommand(messages, parentId));\n };\n\n const handleEdit = (message: AppendMessage) => {\n dispatch(resolveEditCommand(messages, message));\n };\n\n const thread = useResource(\n ExternalThread({\n messages: messages as readonly ExternalThreadMessage[],\n isRunning:\n runs !== undefined ? runs.status === \"running\" : converted.isRunning,\n isLoading: !attached,\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n speechAdapter: options.adapters?.speech,\n feedbackAdapter: options.adapters?.feedback,\n onNew: handleAppend,\n ...(queue && { queue }),\n ...(options.capabilities?.edit && { onEdit: handleEdit }),\n ...(options.capabilities?.continue && {\n onResume: () => dispatch({ type: \"run/continue\" }),\n }),\n ...(options.capabilities?.reload && { onReload: handleReload }),\n ...(inputRequests !== undefined && {\n onAddToolResult: (toolOptions: AddToolResultOptions) =>\n dispatch(resolveToolResultInput(inputRequests, toolOptions)),\n onRespondToToolApproval: (approval: RespondToToolApprovalOptions) =>\n dispatch(resolveToolApprovalInput(inputRequests, approval)),\n }),\n onCancel: () => {\n const payload = latest.current.stopPayload?.();\n if (\n payload !== undefined &&\n (typeof payload !== \"object\" ||\n payload === null ||\n Array.isArray(payload))\n )\n throw new Error(\"statewire: stopPayload must return a plain object\");\n const runId = runs !== undefined ? runs.runId : converted.runId;\n const args =\n runId === undefined\n ? payload === undefined\n ? []\n : [payload]\n : [{ ...payload, runId }];\n void commands[\"run/stop\"]!(...args).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n },\n }),\n );\n threadRef.current = thread;\n return thread;\n};\n\nexport const StatewireThread: {\n <T>(\n options: StatewireThread.RunsOptions<T>,\n ): ResourceElement<ClientOutput<\"thread\">>;\n <T>(\n options: StatewireThread.Options<T>,\n ): ResourceElement<ClientOutput<\"thread\">>;\n} = (options: AnyOptions): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useStatewireThread)(options);\n\nexport namespace StatewireThread {\n export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;\n\n export type TextPart = {\n readonly type: \"text\";\n readonly text: string;\n };\n\n export type FilePart = {\n readonly type: \"file\";\n readonly mediaType: string;\n readonly url: string;\n readonly filename?: string;\n };\n\n export type UserMessage = {\n readonly id: string;\n readonly role: \"user\";\n readonly parts: readonly (TextPart | FilePart)[];\n readonly metadata?: Record<string, unknown>;\n };\n\n /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */\n export type Placement = {\n readonly insertAfter?: string | null;\n readonly insertBefore?: string | null;\n };\n\n export type RunEnqueueCommand = {\n readonly type: \"run/enqueue\";\n } & (\n | {\n readonly message: UserMessage;\n /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */\n readonly anchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunSteerCommand = {\n readonly type: \"run/steer\";\n } & (\n | {\n readonly message: UserMessage;\n /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */\n readonly anchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunDequeueCommand = {\n readonly type: \"run/dequeue\";\n readonly messageId: string;\n };\n\n export type RunEditCommand = {\n readonly type: \"run/edit\";\n readonly message: UserMessage;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly rollbackTo: string | null;\n };\n\n export type RunContinueCommand = {\n readonly type: \"run/continue\";\n };\n\n export type ToolCallInputRequest = {\n readonly type: \"tool-call\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type ToolApprovalInputRequest = {\n readonly type: \"tool-approval\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type CustomInputRequest = {\n readonly type: string;\n readonly id: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A host request parking the run until answered; open union for custom types. */\n export type InputRequest =\n | ToolCallInputRequest\n | ToolApprovalInputRequest\n | CustomInputRequest;\n\n export type ToolCallInputResponse = {\n readonly output: ReadonlyJSONValue;\n /** Default false; when true, `output` carries the error payload. */\n readonly isError?: boolean;\n readonly artifact?: ReadonlyJSONValue;\n };\n\n export type ToolApprovalInputResponse = {\n readonly decision: \"approve\" | \"reject\" | \"edit\" | \"respond\";\n readonly editedArgs?: ReadonlyJSONValue;\n readonly message?: string;\n };\n\n export type InputResponse = ReadonlyJSONValue;\n\n export type RunInputCommand = {\n readonly type: \"run/input\";\n readonly requestId: string;\n readonly response: InputResponse;\n };\n\n /** An input request projected out of the host state with its response echo. */\n export type InputRequestState = InputRequest & {\n readonly response: InputResponse | null;\n };\n\n export type RunReloadCommand = {\n readonly type: \"run/reload\";\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly rollbackTo: string | null;\n };\n\n export type RunCommand =\n | RunEnqueueCommand\n | RunSteerCommand\n | RunDequeueCommand\n | RunEditCommand\n | RunContinueCommand\n | RunReloadCommand\n | RunInputCommand;\n\n export type Command = AssistantTransportThread.Command | RunCommand;\n\n /** A queued message projected out of the host state, wire shape. */\n export type QueueItem = {\n readonly id: string;\n readonly parts: readonly (TextPart | FilePart)[];\n };\n\n export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n readonly isRunning: boolean;\n /** The live run's id projected out of the host state; stamped onto `run/stop`. */\n readonly runId?: string | null;\n /**\n * The host's regular queue lane projected out of the state. Returning it\n * (even empty) turns on the queue capability: sends become `run/enqueue`\n * / `run/steer` commands and item controls send the `run/*` queue\n * commands. Presence must be stable across conversions.\n */\n readonly queue?: readonly QueueItem[];\n /** The host's steer lane; requires `queue`. Absent means empty. */\n readonly steerQueue?: readonly QueueItem[];\n /**\n * The host's parked input requests projected out of the state. Returning\n * it (even empty) routes tool results and approvals with a matching\n * pending request through `run/input`. Presence must be stable across\n * conversions.\n */\n readonly inputRequests?: readonly InputRequestState[];\n };\n\n /** Run subsystem status replicated by the host. */\n export type RunStatus =\n | \"ready\"\n | \"running\"\n | \"stopped\"\n | \"error\"\n | \"input-required\";\n\n /** A queue-lane entry as replicated: the user message plus host-stamped `meta`. */\n export type RunsQueueEntry = UserMessage & {\n /** Host-stamped opaque per-entry metadata. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n /** An input outcome riding a dispatch record: the request with its response (null = abandoned) and `run/input` meta. */\n export type RunsInputOutcome = {\n readonly request: InputRequest;\n readonly response: InputResponse | null;\n readonly meta: ReadonlyJSONValue | null;\n };\n\n /** The dispatch record — the unacked batch handed to the run; null between the ack and the next dispatch or take. */\n export type RunsDispatch = {\n readonly trigger:\n | \"message-send\"\n | \"message-edit\"\n | \"message-reload\"\n | \"input-resume\"\n | \"error-continue\"\n | \"stop-continue\"\n | \"steer\";\n readonly messages: readonly RunsQueueEntry[];\n /** Present on rewind dispatches: truncate the thread at this id first; null names the root. */\n readonly rollbackTo?: string | null;\n /** Present when input outcomes ride the dispatch; visible until the ack. */\n readonly inputOutcomes?: readonly RunsInputOutcome[];\n };\n\n /** The replicated run error — set on an unhandled failure, cleared by the next user-initiated run. */\n export type RunsError = {\n readonly message: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A replicated run entry — one element of the mount's `runs` array. */\n export type RunState = {\n /** The run's identity — minted at dispatch, persists through input-required, null in error/stop. */\n readonly runId: string | null;\n readonly status: Exclude<RunStatus, \"ready\">;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unacked batch handed to the run, cleared at the ack. */\n readonly dispatching: RunsDispatch | null;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n readonly error: RunsError | null;\n };\n\n /** App-shaped effects `runsMaterialize` applies for the dispatch record. */\n export type MaterializeEffects = {\n /** Append one dispatched message to the app's committed message state. */\n append: (message: RunsQueueEntry) => void;\n /** Truncate to the rolled-back view first (null names the root); required for hosts that dispatch edits/reloads. */\n rollback?: (to: string | null) => void;\n };\n\n /** The runs mount as replicated: the run entries plus the top-level status projection. */\n export type RunsState = {\n /** Projection of `runs[0]?.status ?? \"ready\"`. */\n readonly status: RunStatus;\n /** At most one entry; empty while resting. */\n readonly runs: readonly RunState[];\n };\n\n /** The run subsystem's typed read — `runs[0]` of the selected mount with unsettled commands folded in, ready defaults while resting. */\n export type Runs = {\n readonly status: RunStatus;\n /** The live run's id — non-null in running and input-required; stamped onto `run/stop`. */\n readonly runId: string | null;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unacked batch handed to the run, cleared at the ack. */\n readonly dispatching: RunsDispatch | null;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n readonly error: RunsError | null;\n };\n\n export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `live`. */\n connection: StatewireClient.ConnectionState;\n /** The typed runs read; present iff the `runs` option is set. */\n runs?: Runs;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n /** Converter output in runs mode: app-owned keys only — the lib projects the run mounts itself. */\n export type RunsConverterState = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n };\n\n export type RunsStateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata & { runs: Runs },\n ) => RunsConverterState;\n\n /**\n * Payload of the built-in `run/stop` command. `reason` is the one well-known\n * field; apps extend it with their own JSON-serializable fields.\n */\n export type StopPayload = {\n readonly reason?: string | undefined;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n export type Options<T> = {\n transport: Transport<T>;\n initialState: T;\n converter: StateConverter<T>;\n runs?: undefined;\n /**\n * \"command-send\" mirrors the client's ambient model context (system,\n * tools, callSettings, config) to the server over the command channel —\n * on connect and whenever it changes. Requires a remote transport.\n */\n contextSync?: \"command-send\" | undefined;\n /** Supplies the `run/stop` command's payload; omitted, stop sends no payload. */\n stopPayload?: (() => StopPayload) | undefined;\n /** Observes each command's lifecycle (queued, posted, acked, settled); runs after the built-in pending-command retirement. */\n onCommandChange?:\n | ((\n update: Statewire.CommandUpdate<\n Record<string, (...args: any[]) => unknown>\n >,\n ctx: { state: NonNullable<T> },\n ) => void)\n | undefined;\n /** Observes the transport state: fires with the attach snapshot, then once per change. */\n onStateChange?:\n | ((state: NonNullable<T>, ctx: { changes: Statewire.Changes }) => void)\n | undefined;\n /** Observes connection status transitions, starting with the initial status. */\n onConnectionChange?:\n | ((connection: StatewireClient.Connection) => void)\n | undefined;\n onError?: ((error: Error) => void) | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n /** The host supports `run/continue` (a continue affordance on aborted runs). */\n continue?: boolean | undefined;\n /** The host supports `run/reload` (regenerating an assistant message). */\n reload?: boolean | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n speech?: SpeechSynthesisAdapter | undefined;\n feedback?: FeedbackAdapter | undefined;\n }\n | undefined;\n };\n\n /** Options with the runs read enabled: the lib types the run mounts and the converter returns app-owned keys only. */\n export type RunsOptions<T> = Omit<Options<T>, \"converter\" | \"runs\"> & {\n /** `true` reads the run mounts off the state root; a selector picks a nested mount. */\n runs: true | ((state: T) => unknown);\n converter: RunsStateConverter<T>;\n /** Folds app-owned keys for an unsettled command into the draft; runs after the lib's run-dialect reducer. */\n optimistic?:\n | StatewireClient.Optimistic<\n T,\n Record<string, (...args: any[]) => unknown>\n >\n | undefined;\n /** Makes dispatch records concrete in the draft (runs after the optimistic folds); when set, the lib stops projecting dispatch limbo into `messages` itself. */\n materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;\n };\n}\n\ndeclare module \"@assistant-ui/react\" {\n namespace Assistant {\n interface Commands {\n runEnqueue: StatewireThread.RunEnqueueCommand;\n runSteer: StatewireThread.RunSteerCommand;\n runDequeue: StatewireThread.RunDequeueCommand;\n runEdit: StatewireThread.RunEditCommand;\n runContinue: StatewireThread.RunContinueCommand;\n runReload: StatewireThread.RunReloadCommand;\n runInput: StatewireThread.RunInputCommand;\n }\n }\n}\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useStatewireThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;;;;AAkDA,MAAM8C,aAAmC;CACvCE,QAAQ;CACRC,OAAO;CACPC,OAAO,CAAA;CACPC,YAAY,CAAA;CACZC,aAAa;CACbC,OAAO;AACT;AAEA,MAAMC,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWC,KAAAA,KAAa,EAAED,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQG,UAAUD,KAAAA,KAAa,EACjCC,OAAOpC,kBAAkBiC,QAAQG,KAAK,EACxC;CACA,GAAIH,QAAQI,iBAAiBF,KAAAA,KAAa,EACxCE,cAAcJ,QAAQI,aACxB;CACA,GAAIJ,QAAQK,WAAWH,KAAAA,KAAa,EAAEG,QAAQL,QAAQK,OAAO;AAC/D;AAEA,MAAMC,sBAAsBC,YAAgD;CAC1E,MAAMC,SAAS5D,OAAO2D,OAAO;CAC7BC,OAAOC,UAAUF;CAEjB,MAAM,CAACG,SAASC,cAAc9D,SAC5B,CAAA,CACF;CACA,MAAM,CAACgE,UAAUhE,gBACRiE,YACLH,YAAYI,SACVA,KAAKC,SAASF,OAAkC,IAC5CC,KAAKE,QAAQC,MAAMA,MAAMJ,OAAO,IAChCC,IACN,CACJ;CAEA,MAAMI,aAAaZ,QAAQa;CAC3B,MAAM,CAACC,YAAYxE,eAAesE,eAAejB,KAAAA,CAAS;CAC1D,IAAImB,cAAcF,eAAejB,KAAAA,IAC/B,MAAM,IAAIoB,MACR,yDACGD,WAAW,QAAQ,WACpB,oCACJ;CAEF,MAAME,oBAAqBhB,QACxBiB;CACH,MAAM,CAACC,mBAAmB5E,eAAe0E,sBAAsBrB,KAAAA,CAA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AY,QACZE,MAAMC,QAAQH,OAAO,IAEvB,MAAM,IAAInH,MAAM,mDAAmD;GACrE,MAAM5B,QAAQ0B,SAASlB,KAAAA,IAAYkB,KAAK1B,QAAQ0F,UAAU1F;GAC1D,MAAMR,OACJQ,UAAUQ,KAAAA,IACNuI,YAAYvI,KAAAA,IACV,CAAA,IACA,CAACuI,OAAO,IACV,CAAC;IAAE,GAAGA;IAAS/I;GAAM,CAAC;GAC5B,SAAc,WAAW,CAAE,GAAGR,IAAI,CAAC,CAACsE,OAAO1D,YAAiB;IAC1DU,OAAOC,QAAQgD,UAAU3D,OAAK;GAChC,CAAC;EACH;CACF,CAAC,CACH;CACAgE,UAAUrD,UAAUyG;CACpB,OAAOA;AACT;AAEA,MAAa9H,mBAORmB,YACHzD,SAASwD,kBAAkB,CAAC,CAACC,OAAO;AAoXtCpD,uBACEmD,oBACArD,eAAeiD,KAAAA,CAAkB,CAAC,CAACyN,IACrC"}
|
|
1
|
+
{"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","AddToolResultOptions","AppendMessage","AttachmentAdapter","ExternalThreadQueueAdapter","FeedbackAdapter","ModelContext","RespondToToolApprovalOptions","SpeechSynthesisAdapter","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","StatewireClient","symbolAssistantTransportExtras","AssistantTransportExtras","AssistantTransportThread","createRunQueueAdapter","resolveEditCommand","resolveReloadCommand","toWireMessage","viewedLeafId","resolveToolApprovalInput","resolveToolResultInput","runsOptimistic","AnyCommands","Record","args","AnyOptions","StatewireThread","Options","RunsOptions","READY_RUNS","Runs","status","runId","queue","steerQueue","dispatching","error","ambientContextOf","context","system","undefined","tools","callSettings","config","useStatewireThread","options","latest","current","pending","setPending","Command","retire","command","prev","includes","filter","c","runsOption","runs","runsSeam","Error","materializeOption","materialize","materializeSeam","state","transportState","commands","connection","setContext","transport","optimistic","draft","ctx","runsOpt","onCommandChange","update","params","onStateChange","onConnectionChange","attached","initialState","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","catch","onError","subscribe","dispatch","settled","type","threadRef","dispatchSend","message","sourceId","text","content","flatMap","part","join","setText","composer","next","mount","RunsState","entry","inputRequests","converter","metadata","ConnectionMetadata","pendingCommands","isSending","length","converted","State","messages","queueItems","steerQueueItems","queueSeam","present","inputSeam","extras","sendCommand","reconnect","handleAppend","crypto","randomUUID","anchorMessageId","handleReload","parentId","handleEdit","thread","isRunning","isLoading","attachmentAdapter","adapters","attachments","speechAdapter","speech","feedbackAdapter","feedback","onNew","capabilities","edit","onEdit","continue","onResume","reload","onReload","onAddToolResult","toolOptions","onRespondToToolApproval","approval","onCancel","payload","stopPayload","Array","isArray","T","Transport","TextPart","FilePart","mediaType","url","filename","UserMessage","id","role","parts","Placement","insertAfter","insertBefore","RunEnqueueCommand","messageId","RunSteerCommand","RunDequeueCommand","RunEditCommand","rollbackTo","RunContinueCommand","ToolCallInputRequest","toolCallId","ToolApprovalInputRequest","CustomInputRequest","InputRequest","ToolCallInputResponse","output","isError","artifact","ToolApprovalInputResponse","decision","editedArgs","InputResponse","RunInputCommand","requestId","response","InputRequestState","RunReloadCommand","RunCommand","QueueItem","RunStatus","RunsQueueEntry","meta","RunsInputOutcome","request","RunsDispatch","trigger","inputOutcomes","RunsError","RunState","Exclude","MaterializeEffects","append","rollback","to","ConnectionState","StateConverter","connectionMetadata","RunsConverterState","RunsStateConverter","StopPayload","reason","CommandUpdate","NonNullable","changes","Changes","Connection","Omit","Optimistic","Materialize","Assistant","Commands","runEnqueue","runSteer","runDequeue","runEdit","runContinue","runReload","runInput","hook"],"sources":["../src/StatewireThread.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { resource, useResource } from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/react\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/react\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n AttachmentAdapter,\n ExternalThreadQueueAdapter,\n FeedbackAdapter,\n ModelContext,\n RespondToToolApprovalOptions,\n SpeechSynthesisAdapter,\n ThreadMessage,\n} from \"@assistant-ui/core\";\nimport { toToolsJSONSchema } from \"assistant-stream\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { useStatewire } from \"statewire\";\nimport type { Statewire, StatewireClient } from \"statewire\";\nimport { symbolAssistantTransportExtras } from \"./AssistantTransportThread\";\nimport type {\n AssistantTransportExtras,\n AssistantTransportThread,\n} from \"./AssistantTransportThread\";\nimport {\n createRunQueueAdapter,\n resolveEditCommand,\n resolveReloadCommand,\n toWireMessage,\n viewedLeafId,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\nimport { runsOptimistic } from \"./runsOptimistic\";\n\ntype AnyCommands = Record<string, (...args: any[]) => unknown>;\n\ntype AnyOptions =\n | StatewireThread.Options<any>\n | StatewireThread.RunsOptions<any>;\n\nconst READY_RUNS: StatewireThread.Runs = {\n status: \"ready\",\n runId: null,\n queue: [],\n steerQueue: [],\n dispatching: null,\n error: null,\n};\n\nconst ambientContextOf = (context: ModelContext): Record<string, unknown> => ({\n ...(context.system !== undefined && { system: context.system }),\n ...(context.tools !== undefined && {\n tools: toToolsJSONSchema(context.tools),\n }),\n ...(context.callSettings !== undefined && {\n callSettings: context.callSettings,\n }),\n ...(context.config !== undefined && { config: context.config }),\n});\n\nconst useStatewireThread = (options: AnyOptions): ClientOutput<\"thread\"> => {\n const latest = useRef(options);\n latest.current = options;\n\n const [pending, setPending] = useState<readonly StatewireThread.Command[]>(\n [],\n );\n const [retire] = useState(\n () => (command: unknown) =>\n setPending((prev) =>\n prev.includes(command as StatewireThread.Command)\n ? prev.filter((c) => c !== command)\n : prev,\n ),\n );\n\n const runsOption = options.runs;\n const [runsSeam] = useState(() => runsOption !== undefined);\n if (runsSeam !== (runsOption !== undefined))\n throw new Error(\n \"statewire: the runs option must be stable — it was \" +\n (runsSeam ? \"set\" : \"unset\") +\n \" on first render and changed since\",\n );\n\n const materializeOption = (options as StatewireThread.RunsOptions<unknown>)\n .materialize;\n const [materializeSeam] = useState(() => materializeOption !== undefined);\n if (materializeSeam !== (materializeOption !== undefined))\n throw new Error(\n \"statewire: the materialize option must be stable — it was \" +\n (materializeSeam ? \"set\" : \"unset\") +\n \" on first render and changed since\",\n );\n\n const {\n state: transportState,\n commands,\n connection,\n setContext,\n } = useStatewire<unknown, AnyCommands>({\n transport: options.transport,\n ...(runsSeam && {\n optimistic: (draft, command, ctx) => {\n const runsOpt = latest.current.runs!;\n runsOptimistic(runsOpt === true ? draft : runsOpt(draft), command, ctx);\n (latest.current as StatewireThread.RunsOptions<unknown>).optimistic?.(\n draft,\n command,\n ctx,\n );\n },\n }),\n ...(materializeSeam && {\n materialize: (draft: {}) =>\n (latest.current as StatewireThread.RunsOptions<unknown>).materialize!(\n draft,\n ),\n }),\n onCommandChange: (update, ctx) => {\n if (update.status === \"acked\" || update.status === \"settled\")\n retire(update.params[0]);\n latest.current.onCommandChange?.(update, ctx);\n },\n onStateChange: (state, ctx) => latest.current.onStateChange?.(state, ctx),\n onConnectionChange: (connection) =>\n latest.current.onConnectionChange?.(connection),\n });\n const attached = transportState !== undefined;\n const state = attached ? transportState : options.initialState;\n\n const clientRef = useAssistantClientRef();\n const setContextRef = useRef(setContext);\n setContextRef.current = setContext;\n const [syncState] = useState(() => ({ lastSent: undefined as unknown }));\n const { contextSync } = options;\n useEffect(() => {\n if (contextSync === undefined) return;\n const modelContext = (clientRef.current ?? clientRef.parent).modelContext();\n const send = () => {\n const value = ambientContextOf(modelContext.getModelContext());\n const key = JSON.stringify(value);\n if (key === syncState.lastSent) return;\n syncState.lastSent = key;\n void setContextRef.current(value).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n };\n send();\n if (!modelContext.subscribe) {\n throw new Error(\n \"statewire: contextSync requires a subscribable model context\",\n );\n }\n return modelContext.subscribe(send);\n }, [contextSync, clientRef, syncState]);\n\n const dispatch = useCallback(\n (command: StatewireThread.Command) => {\n setPending((prev) => [...prev, command]);\n const settled = commands[command.type]!(command);\n settled.catch((error: Error) => {\n retire(command);\n latest.current.onError?.(error);\n });\n return settled;\n },\n [commands, retire],\n );\n\n const threadRef = useRef<ClientOutput<\"thread\"> | null>(null);\n const dispatchSend = useCallback(\n (command: StatewireThread.Command, message: AppendMessage) => {\n if (message.sourceId != null) return void dispatch(command);\n const text = message.content\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\");\n void dispatch(command).catch(() => {\n // Rejected send: put the text back unless the user typed since.\n // ExternalThread's setText is live-ref-backed and takes an updater.\n const setText = threadRef.current!.composer().setText as (\n next: string | ((prev: string) => string),\n ) => void;\n setText((prev) => (prev === \"\" ? text : prev));\n });\n },\n [dispatch],\n );\n\n const runs = useMemo((): StatewireThread.Runs | undefined => {\n if (runsOption === undefined) return undefined;\n const mount = (runsOption === true ? state : runsOption(state)) as\n | StatewireThread.RunsState\n | undefined;\n const entry = mount?.runs?.[0];\n return entry === undefined\n ? READY_RUNS\n : {\n status: entry.status,\n runId: entry.runId,\n queue: entry.queue,\n steerQueue: entry.steerQueue,\n dispatching: entry.dispatching,\n ...(entry.inputRequests !== undefined && {\n inputRequests: entry.inputRequests,\n }),\n error: entry.error,\n };\n }, [runsOption, state]);\n\n const { converter } = options;\n const metadata = useMemo(\n (): StatewireThread.ConnectionMetadata => ({\n pendingCommands: [...pending],\n isSending: pending.length > 0,\n connection,\n ...(runs !== undefined && { runs }),\n }),\n [pending, connection, runs],\n );\n const converted = useMemo(\n () =>\n converter(\n state,\n metadata as StatewireThread.ConnectionMetadata & {\n runs: StatewireThread.Runs;\n },\n ) as StatewireThread.State,\n [converter, state, metadata],\n );\n // Dispatch limbo is a materialize concern: the fold makes the record\n // concrete in state before conversion.\n const messages = converted.messages;\n const queueItems = runs !== undefined ? runs.queue : converted.queue;\n const steerQueueItems =\n runs !== undefined ? runs.steerQueue : converted.steerQueue;\n if (steerQueueItems !== undefined && queueItems === undefined)\n throw new Error(\n \"statewire: the converter's steerQueue projection requires the queue projection\",\n );\n const [queueSeam] = useState(() => ({\n present: queueItems !== undefined,\n }));\n if (queueSeam.present !== (queueItems !== undefined))\n throw new Error(\n \"statewire: the converter's queue projection must be stable — it was \" +\n (queueSeam.present ? \"defined\" : \"undefined\") +\n \" on first convert and changed since\",\n );\n\n const queue = useMemo(\n (): ExternalThreadQueueAdapter | undefined =>\n queueItems\n ? createRunQueueAdapter(\n messages,\n queueItems,\n steerQueueItems,\n dispatch,\n dispatchSend,\n )\n : undefined,\n [messages, queueItems, steerQueueItems, dispatch, dispatchSend],\n );\n\n const inputRequests =\n runs !== undefined ? (runs.inputRequests ?? []) : converted.inputRequests;\n const [inputSeam] = useState(() => ({\n present: inputRequests !== undefined,\n }));\n if (inputSeam.present !== (inputRequests !== undefined))\n throw new Error(\n \"statewire: the converter's inputRequests projection must be stable — it was \" +\n (inputSeam.present ? \"defined\" : \"undefined\") +\n \" on first convert and changed since\",\n );\n\n const extras = useMemo(\n (): AssistantTransportExtras => ({\n [symbolAssistantTransportExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state,\n ...(inputRequests !== undefined && { inputRequests }),\n ...(runs !== undefined && { runs }),\n }),\n [dispatch, connection.reconnect, state, inputRequests, runs],\n );\n\n const handleAppend = (message: AppendMessage) => {\n dispatchSend(\n message.sourceId != null\n ? resolveEditCommand(messages, message)\n : {\n type: \"run/steer\",\n message: toWireMessage(message, crypto.randomUUID()),\n anchorMessageId: viewedLeafId(messages),\n },\n message,\n );\n };\n\n const handleReload = (parentId: string | null) => {\n dispatch(resolveReloadCommand(messages, parentId));\n };\n\n const handleEdit = (message: AppendMessage) => {\n dispatch(resolveEditCommand(messages, message));\n };\n\n const thread = useResource(\n ExternalThread({\n messages: messages as readonly ExternalThreadMessage[],\n isRunning:\n runs !== undefined ? runs.status === \"running\" : converted.isRunning,\n isLoading: !attached,\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n speechAdapter: options.adapters?.speech,\n feedbackAdapter: options.adapters?.feedback,\n onNew: handleAppend,\n ...(queue && { queue }),\n ...(options.capabilities?.edit && { onEdit: handleEdit }),\n ...(options.capabilities?.continue && {\n onResume: () => dispatch({ type: \"run/continue\" }),\n }),\n ...(options.capabilities?.reload && { onReload: handleReload }),\n ...(inputRequests !== undefined && {\n onAddToolResult: (toolOptions: AddToolResultOptions) =>\n dispatch(resolveToolResultInput(inputRequests, toolOptions)),\n onRespondToToolApproval: (approval: RespondToToolApprovalOptions) =>\n dispatch(resolveToolApprovalInput(inputRequests, approval)),\n }),\n onCancel: () => {\n const payload = latest.current.stopPayload?.();\n if (\n payload !== undefined &&\n (typeof payload !== \"object\" ||\n payload === null ||\n Array.isArray(payload))\n )\n throw new Error(\"statewire: stopPayload must return a plain object\");\n const runId = runs !== undefined ? runs.runId : converted.runId;\n const args =\n runId === undefined\n ? payload === undefined\n ? []\n : [payload]\n : [{ ...payload, runId }];\n void commands[\"run/stop\"]!(...args).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n },\n }),\n );\n threadRef.current = thread;\n return thread;\n};\n\nexport const StatewireThread: {\n <T>(\n options: StatewireThread.RunsOptions<T>,\n ): ResourceElement<ClientOutput<\"thread\">>;\n <T>(\n options: StatewireThread.Options<T>,\n ): ResourceElement<ClientOutput<\"thread\">>;\n} = (options: AnyOptions): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useStatewireThread)(options);\n\nexport namespace StatewireThread {\n export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;\n\n export type TextPart = {\n readonly type: \"text\";\n readonly text: string;\n };\n\n export type FilePart = {\n readonly type: \"file\";\n readonly mediaType: string;\n readonly url: string;\n readonly filename?: string;\n };\n\n export type UserMessage = {\n readonly id: string;\n readonly role: \"user\";\n readonly parts: readonly (TextPart | FilePart)[];\n readonly metadata?: Record<string, unknown>;\n };\n\n /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */\n export type Placement = {\n readonly insertAfter?: string | null;\n readonly insertBefore?: string | null;\n };\n\n export type RunEnqueueCommand = {\n readonly type: \"run/enqueue\";\n } & (\n | {\n readonly message: UserMessage;\n /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */\n readonly anchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunSteerCommand = {\n readonly type: \"run/steer\";\n } & (\n | {\n readonly message: UserMessage;\n /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */\n readonly anchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunDequeueCommand = {\n readonly type: \"run/dequeue\";\n readonly messageId: string;\n };\n\n export type RunEditCommand = {\n readonly type: \"run/edit\";\n readonly message: UserMessage;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly rollbackTo: string | null;\n };\n\n export type RunContinueCommand = {\n readonly type: \"run/continue\";\n };\n\n export type ToolCallInputRequest = {\n readonly type: \"tool-call\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type ToolApprovalInputRequest = {\n readonly type: \"tool-approval\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type CustomInputRequest = {\n readonly type: string;\n readonly id: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A host request parking the run until answered; open union for custom types. */\n export type InputRequest =\n | ToolCallInputRequest\n | ToolApprovalInputRequest\n | CustomInputRequest;\n\n export type ToolCallInputResponse = {\n readonly output: ReadonlyJSONValue;\n /** Default false; when true, `output` carries the error payload. */\n readonly isError?: boolean;\n readonly artifact?: ReadonlyJSONValue;\n };\n\n export type ToolApprovalInputResponse = {\n readonly decision: \"approve\" | \"reject\" | \"edit\" | \"respond\";\n readonly editedArgs?: ReadonlyJSONValue;\n readonly message?: string;\n };\n\n export type InputResponse = ReadonlyJSONValue;\n\n export type RunInputCommand = {\n readonly type: \"run/input\";\n readonly requestId: string;\n readonly response: InputResponse;\n };\n\n /** An input request projected out of the host state with its response echo. */\n export type InputRequestState = InputRequest & {\n readonly response: InputResponse | null;\n };\n\n export type RunReloadCommand = {\n readonly type: \"run/reload\";\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly rollbackTo: string | null;\n };\n\n export type RunCommand =\n | RunEnqueueCommand\n | RunSteerCommand\n | RunDequeueCommand\n | RunEditCommand\n | RunContinueCommand\n | RunReloadCommand\n | RunInputCommand;\n\n export type Command = AssistantTransportThread.Command | RunCommand;\n\n /** A queued message projected out of the host state, wire shape. */\n export type QueueItem = {\n readonly id: string;\n readonly parts: readonly (TextPart | FilePart)[];\n };\n\n export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n readonly isRunning: boolean;\n /** The live run's id projected out of the host state; stamped onto `run/stop`. */\n readonly runId?: string | null;\n /**\n * The host's regular queue lane projected out of the state. Returning it\n * (even empty) turns on the queue capability: sends become `run/enqueue`\n * / `run/steer` commands and item controls send the `run/*` queue\n * commands. Presence must be stable across conversions.\n */\n readonly queue?: readonly QueueItem[];\n /** The host's steer lane; requires `queue`. Absent means empty. */\n readonly steerQueue?: readonly QueueItem[];\n /**\n * The host's parked input requests projected out of the state. Returning\n * it (even empty) routes tool results and approvals with a matching\n * pending request through `run/input`. Presence must be stable across\n * conversions.\n */\n readonly inputRequests?: readonly InputRequestState[];\n };\n\n /** Run subsystem status replicated by the host. */\n export type RunStatus =\n | \"ready\"\n | \"running\"\n | \"stopped\"\n | \"error\"\n | \"input-required\";\n\n /** A queue-lane entry as replicated: the user message plus host-stamped `meta`. */\n export type RunsQueueEntry = UserMessage & {\n /** Host-stamped opaque per-entry metadata. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n /** An input outcome riding a dispatch record: the request with its response (null = abandoned) and `run/input` meta. */\n export type RunsInputOutcome = {\n readonly request: InputRequest;\n readonly response: InputResponse | null;\n readonly meta: ReadonlyJSONValue | null;\n };\n\n /** The dispatch record — the unacked batch handed to the run; null between the ack and the next dispatch or take. */\n export type RunsDispatch = {\n readonly trigger:\n | \"message-send\"\n | \"message-edit\"\n | \"message-reload\"\n | \"input-resume\"\n | \"error-continue\"\n | \"stop-continue\"\n | \"steer\";\n readonly messages: readonly RunsQueueEntry[];\n /** Present on rewind dispatches: truncate the thread at this id first; null names the root. */\n readonly rollbackTo?: string | null;\n /** Present when input outcomes ride the dispatch; visible until the ack. */\n readonly inputOutcomes?: readonly RunsInputOutcome[];\n };\n\n /** The replicated run error — set on an unhandled failure, cleared by the next user-initiated run. */\n export type RunsError = {\n readonly message: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A replicated run entry — one element of the mount's `runs` array. */\n export type RunState = {\n /** The run's identity — minted at dispatch, persists through input-required, null in error/stop. */\n readonly runId: string | null;\n readonly status: Exclude<RunStatus, \"ready\">;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unacked batch handed to the run, cleared at the ack. */\n readonly dispatching: RunsDispatch | null;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n readonly error: RunsError | null;\n };\n\n /** App-shaped effects `runsMaterialize` applies for the dispatch record. */\n export type MaterializeEffects = {\n /** Append one dispatched message to the app's committed message state. */\n append: (message: RunsQueueEntry) => void;\n /** Truncate to the rolled-back view first (null names the root); required for hosts that dispatch edits/reloads. */\n rollback?: (to: string | null) => void;\n };\n\n /** The runs mount as replicated: the run entries plus the top-level status projection. */\n export type RunsState = {\n /** Projection of `runs[0]?.status ?? \"ready\"`. */\n readonly status: RunStatus;\n /** At most one entry; empty while resting. */\n readonly runs: readonly RunState[];\n };\n\n /** The run subsystem's typed read — `runs[0]` of the selected mount with unsettled commands folded in, ready defaults while resting. */\n export type Runs = {\n readonly status: RunStatus;\n /** The live run's id — non-null in running and input-required; stamped onto `run/stop`. */\n readonly runId: string | null;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unacked batch handed to the run, cleared at the ack. */\n readonly dispatching: RunsDispatch | null;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n readonly error: RunsError | null;\n };\n\n export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `live`. */\n connection: StatewireClient.ConnectionState;\n /** The typed runs read; present iff the `runs` option is set. */\n runs?: Runs;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n /** Converter output in runs mode: app-owned keys only — the lib projects the run mounts itself. */\n export type RunsConverterState = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n };\n\n export type RunsStateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata & { runs: Runs },\n ) => RunsConverterState;\n\n /**\n * Payload of the built-in `run/stop` command. `reason` is the one well-known\n * field; apps extend it with their own JSON-serializable fields.\n */\n export type StopPayload = {\n readonly reason?: string | undefined;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n export type Options<T> = {\n transport: Transport<T>;\n initialState: T;\n converter: StateConverter<T>;\n runs?: undefined;\n /**\n * \"command-send\" mirrors the client's ambient model context (system,\n * tools, callSettings, config) to the server over the command channel —\n * on connect and whenever it changes. Requires a remote transport.\n */\n contextSync?: \"command-send\" | undefined;\n /** Supplies the `run/stop` command's payload; omitted, stop sends no payload. */\n stopPayload?: (() => StopPayload) | undefined;\n /** Observes each command's lifecycle (queued, posted, acked, settled); runs after the built-in pending-command retirement. */\n onCommandChange?:\n | ((\n update: Statewire.CommandUpdate<\n Record<string, (...args: any[]) => unknown>\n >,\n ctx: { state: NonNullable<T> },\n ) => void)\n | undefined;\n /** Observes the transport state: fires with the attach snapshot, then once per change. */\n onStateChange?:\n | ((state: NonNullable<T>, ctx: { changes: Statewire.Changes }) => void)\n | undefined;\n /** Observes connection status transitions, starting with the initial status. */\n onConnectionChange?:\n | ((connection: StatewireClient.Connection) => void)\n | undefined;\n onError?: ((error: Error) => void) | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n /** The host supports `run/continue` (a continue affordance on aborted runs). */\n continue?: boolean | undefined;\n /** The host supports `run/reload` (regenerating an assistant message). */\n reload?: boolean | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n speech?: SpeechSynthesisAdapter | undefined;\n feedback?: FeedbackAdapter | undefined;\n }\n | undefined;\n };\n\n /** Options with the runs read enabled: the lib types the run mounts and the converter returns app-owned keys only. */\n export type RunsOptions<T> = Omit<Options<T>, \"converter\" | \"runs\"> & {\n /** `true` reads the run mounts off the state root; a selector picks a nested mount. */\n runs: true | ((state: T) => unknown);\n converter: RunsStateConverter<T>;\n /** Folds app-owned keys for an unsettled command into the draft; runs after the lib's run-dialect reducer. */\n optimistic?:\n | StatewireClient.Optimistic<\n T,\n Record<string, (...args: any[]) => unknown>\n >\n | undefined;\n /** Makes dispatch records concrete in the draft (runs after the optimistic folds); without it, dispatch limbo stays out of `messages`. */\n materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;\n };\n}\n\ndeclare module \"@assistant-ui/react\" {\n namespace Assistant {\n interface Commands {\n runEnqueue: StatewireThread.RunEnqueueCommand;\n runSteer: StatewireThread.RunSteerCommand;\n runDequeue: StatewireThread.RunDequeueCommand;\n runEdit: StatewireThread.RunEditCommand;\n runContinue: StatewireThread.RunContinueCommand;\n runReload: StatewireThread.RunReloadCommand;\n runInput: StatewireThread.RunInputCommand;\n }\n }\n}\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useStatewireThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;;;;AAiDA,MAAM6C,aAAmC;CACvCE,QAAQ;CACRC,OAAO;CACPC,OAAO,CAAA;CACPC,YAAY,CAAA;CACZC,aAAa;CACbC,OAAO;AACT;AAEA,MAAMC,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWC,KAAAA,KAAa,EAAED,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQG,UAAUD,KAAAA,KAAa,EACjCC,OAAOnC,kBAAkBgC,QAAQG,KAAK,EACxC;CACA,GAAIH,QAAQI,iBAAiBF,KAAAA,KAAa,EACxCE,cAAcJ,QAAQI,aACxB;CACA,GAAIJ,QAAQK,WAAWH,KAAAA,KAAa,EAAEG,QAAQL,QAAQK,OAAO;AAC/D;AAEA,MAAMC,sBAAsBC,YAAgD;CAC1E,MAAMC,SAAS3D,OAAO0D,OAAO;CAC7BC,OAAOC,UAAUF;CAEjB,MAAM,CAACG,SAASC,cAAc7D,SAC5B,CAAA,CACF;CACA,MAAM,CAAC+D,UAAU/D,gBACRgE,YACLH,YAAYI,SACVA,KAAKC,SAASF,OAAkC,IAC5CC,KAAKE,QAAQC,MAAMA,MAAMJ,OAAO,IAChCC,IACN,CACJ;CAEA,MAAMI,aAAaZ,QAAQa;CAC3B,MAAM,CAACC,YAAYvE,eAAeqE,eAAejB,KAAAA,CAAS;CAC1D,IAAImB,cAAcF,eAAejB,KAAAA,IAC/B,MAAM,IAAIoB,MACR,yDACGD,WAAW,QAAQ,WACpB,oCACJ;CAEF,MAAME,oBAAqBhB,QACxBiB;CACH,MAAM,CAACC,mBAAmB3E,eAAeyE,sBAAsBrB,KAAAA,CAAS;CACxE,IAAIuB,qBAAqBF,sBAAsBrB,KAAAA,IAC7C,MAAM,IAAIoB,MACR,gEACGG,kBAAkB,QAA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GAAIpG,SAAS,EAAEA,MAAM;EACrB,GAAIY,QAAQ0G,cAAcC,QAAQ,EAAEC,QAAQd,WAAW;EACvD,GAAI9F,QAAQ0G,cAAcG,YAAY,EACpCC,gBAAgB1D,SAAS,EAAEE,MAAM,eAAe,CAAC,EACnD;EACA,GAAItD,QAAQ0G,cAAcK,UAAU,EAAEC,UAAUpB,aAAa;EAC7D,GAAItB,kBAAkB3E,KAAAA,KAAa;GACjCsH,kBAAkBC,gBAChB9D,SAAS7E,uBAAuB+F,eAAe4C,WAAW,CAAC;GAC7DC,0BAA0BC,aACxBhE,SAAS9E,yBAAyBgG,eAAe8C,QAAQ,CAAC;EAC9D;EACAC,gBAAgB;GACd,MAAMC,UAAUrH,OAAOC,QAAQqH,cAAc;GAC7C,IACED,YAAY3H,KAAAA,MACX,OAAO2H,YAAY,YAClBA,YAAY,QACZE,MAAMC,QAAQH,OAAO,IAEvB,MAAM,IAAIvG,MAAM,mDAAmD;GACrE,MAAM5B,QAAQ0B,SAASlB,KAAAA,IAAYkB,KAAK1B,QAAQ0F,UAAU1F;GAC1D,MAAMR,OACJQ,UAAUQ,KAAAA,IACN2H,YAAY3H,KAAAA,IACV,CAAA,IACA,CAAC2H,OAAO,IACV,CAAC;IAAE,GAAGA;IAASnI;GAAM,CAAC;GAC5B,SAAc,WAAW,CAAE,GAAGR,IAAI,CAAC,CAACsE,OAAO1D,YAAiB;IAC1DU,OAAOC,QAAQgD,UAAU3D,OAAK;GAChC,CAAC;EACH;CACF,CAAC,CACH;CACAgE,UAAUrD,UAAU6F;CACpB,OAAOA;AACT;AAEA,MAAalH,mBAORmB,YACHxD,SAASuD,kBAAkB,CAAC,CAACC,OAAO;AAoXtCnD,uBACEkD,oBACApD,eAAegD,KAAAA,CAAkB,CAAC,CAAC+M,IACrC"}
|
package/dist/runCommands.d.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import { StatewireThread } from "./StatewireThread.js";
|
|
2
1
|
import { AssistantTransportThread } from "./AssistantTransportThread.js";
|
|
3
|
-
import { AppendMessage, ExternalThreadQueueAdapter
|
|
2
|
+
import { AppendMessage, ExternalThreadQueueAdapter } from "@assistant-ui/core";
|
|
4
3
|
//#region src/runCommands.d.ts
|
|
5
4
|
declare const toWireMessage: (message: AppendMessage, id: string) => AssistantTransportThread.RunUserMessage;
|
|
6
5
|
declare const toQueueItemState: (item: AssistantTransportThread.RunQueueItem) => {
|
|
@@ -13,7 +12,6 @@ declare const toQueueItemState: (item: AssistantTransportThread.RunQueueItem) =>
|
|
|
13
12
|
mimeType: string;
|
|
14
13
|
})[];
|
|
15
14
|
};
|
|
16
|
-
declare const toDispatchingMessage: (item: StatewireThread.RunsQueueEntry) => ThreadMessage;
|
|
17
15
|
declare const viewedLeafId: (messages: readonly {
|
|
18
16
|
id: string;
|
|
19
17
|
}[]) => string | null;
|
|
@@ -28,5 +26,5 @@ declare const resolveReloadCommand: (messages: readonly {
|
|
|
28
26
|
role: string;
|
|
29
27
|
}[], parentId: string | null) => AssistantTransportThread.RunReloadCommand;
|
|
30
28
|
//#endregion
|
|
31
|
-
export { createRunQueueAdapter, resolveEditCommand, resolveReloadCommand,
|
|
29
|
+
export { createRunQueueAdapter, resolveEditCommand, resolveReloadCommand, toQueueItemState, toWireMessage, viewedLeafId };
|
|
32
30
|
//# sourceMappingURL=runCommands.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runCommands.d.ts","names":[],"sources":["../src/runCommands.ts"],"mappings":"
|
|
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,qBACX;EAAqB;KACrB,SAAS,kBACR,yBAAyB;cAgBf,wBACX;EAAqB;KACrB,qBAAqB,yBAAyB,gBAC9C,0BAA0B,yBAAyB,4BACnD,WAAW,SAAS,yBAAyB,qBAC7C,eACE,SAAS,yBAAyB,YAClC,SAAS,2BAEV;cAmDU,uBACX;EAAqB;EAAY;KACjC,4BACC,yBAAyB"}
|
package/dist/runCommands.js
CHANGED
|
@@ -38,19 +38,6 @@ const toQueueItemState = (item) => ({
|
|
|
38
38
|
...part.filename !== void 0 && { filename: part.filename }
|
|
39
39
|
})
|
|
40
40
|
});
|
|
41
|
-
const toDispatchingMessage = (item) => ({
|
|
42
|
-
id: item.id,
|
|
43
|
-
role: "user",
|
|
44
|
-
createdAt: /* @__PURE__ */ new Date(),
|
|
45
|
-
content: item.parts.map((part) => part.type === "text" ? part : {
|
|
46
|
-
type: "file",
|
|
47
|
-
data: part.url,
|
|
48
|
-
mimeType: part.mediaType,
|
|
49
|
-
...part.filename !== void 0 && { filename: part.filename }
|
|
50
|
-
}),
|
|
51
|
-
attachments: [],
|
|
52
|
-
metadata: { custom: {} }
|
|
53
|
-
});
|
|
54
41
|
const placementFields = (placement) => ({
|
|
55
42
|
...placement.insertAfter !== void 0 && { insertAfter: placement.insertAfter },
|
|
56
43
|
...placement.insertBefore !== void 0 && { insertBefore: placement.insertBefore }
|
|
@@ -134,6 +121,6 @@ const resolveReloadCommand = (messages, parentId) => {
|
|
|
134
121
|
};
|
|
135
122
|
};
|
|
136
123
|
//#endregion
|
|
137
|
-
export { createRunQueueAdapter, resolveEditCommand, resolveReloadCommand,
|
|
124
|
+
export { createRunQueueAdapter, resolveEditCommand, resolveReloadCommand, toQueueItemState, toWireMessage, viewedLeafId };
|
|
138
125
|
|
|
139
126
|
//# sourceMappingURL=runCommands.js.map
|
package/dist/runCommands.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runCommands.js","names":["AppendMessage","ExternalThreadQueueAdapter","QueuePlacement","ThreadMessage","AssistantTransportThread","StatewireThread","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","toDispatchingMessage","RunsQueueEntry","createdAt","Date","metadata","custom","placementFields","placement","insertAfter","insertBefore","viewedLeafId","messages","at","resolveEditCommand","RunEditCommand","sourceId","index","findIndex","m","crypto","randomUUID","rollbackTo","createRunQueueAdapter","queueItems","steerQueueItems","dispatch","command","RunCommand","dispatchSend","laneOf","queueItemId","some","sendCommand","lane","fields","anchorMessageId","items","steerItems","enqueue","steer","move","messageId","edit","wireMessage","remove","resolveReloadCommand","parentId","RunReloadCommand","target"],"sources":["../src/runCommands.ts"],"sourcesContent":["import type {\n AppendMessage,\n ExternalThreadQueueAdapter,\n QueuePlacement,\n ThreadMessage,\n} from \"@assistant-ui/core\";\nimport type { AssistantTransportThread } from \"./AssistantTransportThread\";\nimport type { StatewireThread } from \"./StatewireThread\";\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\nexport const toDispatchingMessage = (\n item: StatewireThread.RunsQueueEntry,\n): ThreadMessage => ({\n id: item.id,\n role: \"user\",\n createdAt: new Date(),\n content: 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 attachments: [],\n metadata: { custom: {} },\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 resolveEditCommand = (\n messages: readonly { id: string }[],\n message: AppendMessage,\n): AssistantTransportThread.RunEditCommand => {\n if (message.sourceId == null)\n throw new Error(\"statewire: run/edit requires a sourceId\");\n const index = messages.findIndex((m) => m.id === message.sourceId);\n if (index === -1)\n throw new Error(\n `statewire: run/edit source \"${message.sourceId}\" is unknown`,\n );\n return {\n type: \"run/edit\",\n message: toWireMessage(message, crypto.randomUUID()),\n sourceId: message.sourceId,\n rollbackTo: messages[index - 1]?.id ?? null,\n };\n};\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 dispatchSend: (\n command: AssistantTransportThread.RunCommand,\n message: AppendMessage,\n ) => 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 // edit-composer sends carry a sourceId; they bypass the lanes into run/edit\n const sendCommand = (\n lane: \"queue\" | \"steer\",\n message: AppendMessage,\n ): AssistantTransportThread.RunCommand => {\n if (message.sourceId != null) return resolveEditCommand(messages, message);\n const fields = {\n message: toWireMessage(message, crypto.randomUUID()),\n anchorMessageId: viewedLeafId(messages),\n };\n return lane === \"steer\"\n ? { type: \"run/steer\", ...fields }\n : { type: \"run/enqueue\", ...fields };\n };\n return {\n items: queueItems.map(toQueueItemState),\n steerItems: (steerQueueItems ?? []).map(toQueueItemState),\n enqueue: (message) => dispatchSend(sendCommand(\"queue\", message), message),\n steer: (message) => dispatchSend(sendCommand(\"steer\", message), message),\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, rollbackTo: parentId };\n};\n"],"mappings":";AASA,MAAaM,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,aAAaC,SAASC,MAAMA,EAAEH,OAAO,KAAK,CAAA,CAAG;CAE3D,KAAK,MAAMI,QAAQL,QACjB,IAAIK,KAAKC,SAAS,QAChBP,MAAMQ,KAAKF,KAAKG,IAAI;MACf,IAAIH,KAAKC,SAAS,SACvBT,MAAMU,KAAK;EAAED,MAAM;EAAQG,WAAW;EAAWC,KAAKL,KAAKM;CAAM,CAAC;MAC7D,IAAIN,KAAKC,SAAS,QACvBT,MAAMU,KAAK;EACTD,MAAM;EACNG,WAAWJ,KAAKO;EAChBF,KAAKL,KAAKQ;EACV,GAAIR,KAAKS,aAAaC,KAAAA,KAAa,EAAED,UAAUT,KAAKS,SAAS;CAC/D,CAAC;MAED,MAAM,IAAIlB,MAAM,wCAAwCS,KAAKC,KAAI,EAAG;CAIxE,MAAMU,QAGA,CACJ,GAAGnB,OACH,GAAIE,MAAMmB,SAAS,IACf,CAAC;EAAEZ,MAAM;EAAiBE,MAAMT,MAAMqB,KAAK,MAAM;CAAE,CAAC,IACpD,CAAA,CAAG;CAET,IAAIJ,MAAME,WAAW,GACnB,MAAM,IAAItB,MAAM,yCAAyC;CAC3D,OAAO;EAAEH;EAAIE,MAAM;EAAQqB;CAAM;AACnC;AAEA,MAAaK,oBACXC,UACI;CACJ7B,IAAI6B,KAAK7B;CACT+B,QAAQF,KAAKN,MACVb,SAASE,SAAUA,KAAKC,SAAS,SAAS,CAACD,KAAKG,IAAI,IAAI,CAAA,CAAG,CAAC,CAC5DY,KAAK,MAAM;CACdJ,OAAOM,KAAKN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,SAAS6E;GAAY,CAClD;EACF;EACAC,SAASd,gBACPL,SAAS;GAAE7C,MAAM;GAAe6D,WAAWX;EAAY,CAAC;CAC5D;AACF;AAEA,MAAae,wBACXlC,UACAmC,aAC8C;CAC9C,MAAM9B,QACJ8B,aAAa,OACT,IACAnC,SAASM,WAAWnD,YAAYA,QAAQC,OAAO+E,QAAQ,IAAI;CACjE,IAAIA,aAAa,QAAQ9B,UAAU,GACjC,MAAM,IAAI9C,MAAM,iCAAiC4E,SAAQ,aAAc;CACzE,MAAME,SAASrC,SAASK;CACxB,IAAIgC,WAAW3D,KAAAA,KAAa2D,OAAO/E,SAAS,aAC1C,MAAM,IAAIC,MACR,mEACF;CACF,OAAO;EAAEU,MAAM;EAAcmC,UAAUiC,OAAOjF;EAAIsD,YAAYyB;CAAS;AACzE"}
|
|
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","resolveEditCommand","RunEditCommand","sourceId","index","findIndex","m","crypto","randomUUID","rollbackTo","createRunQueueAdapter","queueItems","steerQueueItems","dispatch","command","RunCommand","dispatchSend","laneOf","queueItemId","some","sendCommand","lane","fields","anchorMessageId","items","steerItems","enqueue","steer","move","messageId","edit","wireMessage","remove","resolveReloadCommand","parentId","RunReloadCommand","target"],"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 resolveEditCommand = (\n messages: readonly { id: string }[],\n message: AppendMessage,\n): AssistantTransportThread.RunEditCommand => {\n if (message.sourceId == null)\n throw new Error(\"statewire: run/edit requires a sourceId\");\n const index = messages.findIndex((m) => m.id === message.sourceId);\n if (index === -1)\n throw new Error(\n `statewire: run/edit source \"${message.sourceId}\" is unknown`,\n );\n return {\n type: \"run/edit\",\n message: toWireMessage(message, crypto.randomUUID()),\n sourceId: message.sourceId,\n rollbackTo: messages[index - 1]?.id ?? null,\n };\n};\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 dispatchSend: (\n command: AssistantTransportThread.RunCommand,\n message: AppendMessage,\n ) => 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 // edit-composer sends carry a sourceId; they bypass the lanes into run/edit\n const sendCommand = (\n lane: \"queue\" | \"steer\",\n message: AppendMessage,\n ): AssistantTransportThread.RunCommand => {\n if (message.sourceId != null) return resolveEditCommand(messages, message);\n const fields = {\n message: toWireMessage(message, crypto.randomUUID()),\n anchorMessageId: viewedLeafId(messages),\n };\n return lane === \"steer\"\n ? { type: \"run/steer\", ...fields }\n : { type: \"run/enqueue\", ...fields };\n };\n return {\n items: queueItems.map(toQueueItemState),\n steerItems: (steerQueueItems ?? []).map(toQueueItemState),\n enqueue: (message) => dispatchSend(sendCommand(\"queue\", message), message),\n steer: (message) => dispatchSend(sendCommand(\"steer\", message), message),\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, rollbackTo: parentId };\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,aAAaC,SAASC,MAAMA,EAAEH,OAAO,KAAK,CAAA,CAAG;CAE3D,KAAK,MAAMI,QAAQL,QACjB,IAAIK,KAAKC,SAAS,QAChBP,MAAMQ,KAAKF,KAAKG,IAAI;MACf,IAAIH,KAAKC,SAAS,SACvBT,MAAMU,KAAK;EAAED,MAAM;EAAQG,WAAW;EAAWC,KAAKL,KAAKM;CAAM,CAAC;MAC7D,IAAIN,KAAKC,SAAS,QACvBT,MAAMU,KAAK;EACTD,MAAM;EACNG,WAAWJ,KAAKO;EAChBF,KAAKL,KAAKQ;EACV,GAAIR,KAAKS,aAAaC,KAAAA,KAAa,EAAED,UAAUT,KAAKS,SAAS;CAC/D,CAAC;MAED,MAAM,IAAIlB,MAAM,wCAAwCS,KAAKC,KAAI,EAAG;CAIxE,MAAMU,QAGA,CACJ,GAAGnB,OACH,GAAIE,MAAMmB,SAAS,IACf,CAAC;EAAEZ,MAAM;EAAiBE,MAAMT,MAAMqB,KAAK,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E;GAAY,CAClD;EACF;EACAC,SAASd,gBACPL,SAAS;GAAEvC,MAAM;GAAeuD,WAAWX;EAAY,CAAC;CAC5D;AACF;AAEA,MAAae,wBACXlC,UACAmC,aAC8C;CAC9C,MAAM9B,QACJ8B,aAAa,OACT,IACAnC,SAASM,WAAW7C,YAAYA,QAAQC,OAAOyE,QAAQ,IAAI;CACjE,IAAIA,aAAa,QAAQ9B,UAAU,GACjC,MAAM,IAAIxC,MAAM,iCAAiCsE,SAAQ,aAAc;CACzE,MAAME,SAASrC,SAASK;CACxB,IAAIgC,WAAWrD,KAAAA,KAAaqD,OAAOzE,SAAS,aAC1C,MAAM,IAAIC,MACR,mEACF;CACF,OAAO;EAAEU,MAAM;EAAc6B,UAAUiC,OAAO3E;EAAIgD,YAAYyB;CAAS;AACzE"}
|
package/package.json
CHANGED
|
@@ -49,6 +49,7 @@ import {
|
|
|
49
49
|
toWireMessage,
|
|
50
50
|
viewedLeafId,
|
|
51
51
|
} from "./runCommands";
|
|
52
|
+
import { runsOptimistic } from "./runsOptimistic";
|
|
52
53
|
import {
|
|
53
54
|
resolveToolApprovalInput,
|
|
54
55
|
resolveToolResultInput,
|
|
@@ -176,20 +177,60 @@ const useAssistantTransportThread = (
|
|
|
176
177
|
};
|
|
177
178
|
});
|
|
178
179
|
|
|
179
|
-
const { converter, optimistic } = options;
|
|
180
|
+
const { converter, optimistic, runs: runsOption, materialize } = options;
|
|
181
|
+
const [runsSeam] = useState(() => runsOption !== undefined);
|
|
182
|
+
if (runsSeam !== (runsOption !== undefined))
|
|
183
|
+
throw new Error(
|
|
184
|
+
"statewire: the runs option must be stable — it was " +
|
|
185
|
+
(runsSeam ? "set" : "unset") +
|
|
186
|
+
" on first render and changed since",
|
|
187
|
+
);
|
|
188
|
+
const [materializeSeam] = useState(() => materialize !== undefined);
|
|
189
|
+
if (materializeSeam !== (materialize !== undefined))
|
|
190
|
+
throw new Error(
|
|
191
|
+
"statewire: the materialize option must be stable — it was " +
|
|
192
|
+
(materializeSeam ? "set" : "unset") +
|
|
193
|
+
" on first render and changed since",
|
|
194
|
+
);
|
|
195
|
+
|
|
196
|
+
const project = useCallback(
|
|
197
|
+
(state: unknown): unknown => {
|
|
198
|
+
const fold: AssistantTransportThread.Optimistic<unknown> | undefined =
|
|
199
|
+
runsOption !== undefined
|
|
200
|
+
? (draft, command, ctx) => {
|
|
201
|
+
runsOptimistic(
|
|
202
|
+
runsOption === true ? draft : runsOption(draft as never),
|
|
203
|
+
{ method: command.type, params: [command] },
|
|
204
|
+
ctx,
|
|
205
|
+
);
|
|
206
|
+
optimistic?.(draft, command, ctx);
|
|
207
|
+
}
|
|
208
|
+
: optimistic;
|
|
209
|
+
let next = fold
|
|
210
|
+
? foldOptimistic(
|
|
211
|
+
state,
|
|
212
|
+
[...queue.inTransit, ...queue.queued],
|
|
213
|
+
fold,
|
|
214
|
+
ctxOf,
|
|
215
|
+
)
|
|
216
|
+
: state;
|
|
217
|
+
if (materialize) {
|
|
218
|
+
try {
|
|
219
|
+
next = applyOptimistic(next, (draft) => materialize(draft as never));
|
|
220
|
+
} catch (error) {
|
|
221
|
+
console.error(
|
|
222
|
+
"statewire: materialize threw; publishing without its update",
|
|
223
|
+
error,
|
|
224
|
+
);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
return next;
|
|
228
|
+
},
|
|
229
|
+
[runsOption, optimistic, materialize, queue, ctxOf],
|
|
230
|
+
);
|
|
180
231
|
const converted = useMemo(
|
|
181
|
-
() =>
|
|
182
|
-
|
|
183
|
-
optimistic
|
|
184
|
-
? foldOptimistic(
|
|
185
|
-
agentState,
|
|
186
|
-
[...queue.inTransit, ...queue.queued],
|
|
187
|
-
optimistic,
|
|
188
|
-
ctxOf,
|
|
189
|
-
)
|
|
190
|
-
: agentState,
|
|
191
|
-
),
|
|
192
|
-
[converter, optimistic, agentState, queue, ctxOf],
|
|
232
|
+
() => converter(project(agentState)),
|
|
233
|
+
[converter, project, agentState],
|
|
193
234
|
);
|
|
194
235
|
const convertedRef = useRef(converted);
|
|
195
236
|
convertedRef.current = converted;
|
|
@@ -439,16 +480,7 @@ const useAssistantTransportThread = (
|
|
|
439
480
|
onLoadExternalState: (imported: unknown) => {
|
|
440
481
|
void commands.importState(imported).catch(() => {});
|
|
441
482
|
// reset() aborts tools before React re-renders — gate their late results against the imported state
|
|
442
|
-
convertedRef.current = converter(
|
|
443
|
-
optimistic
|
|
444
|
-
? foldOptimistic(
|
|
445
|
-
imported,
|
|
446
|
-
[...queue.inTransit, ...queue.queued],
|
|
447
|
-
optimistic,
|
|
448
|
-
ctxOf,
|
|
449
|
-
)
|
|
450
|
-
: imported,
|
|
451
|
-
);
|
|
483
|
+
convertedRef.current = converter(project(imported));
|
|
452
484
|
toolInvocations.reset();
|
|
453
485
|
setToolStatuses(EMPTY_TOOL_STATUSES);
|
|
454
486
|
},
|
|
@@ -657,6 +689,10 @@ export namespace AssistantTransportThread {
|
|
|
657
689
|
initialState: T;
|
|
658
690
|
converter: StateConverter<T>;
|
|
659
691
|
optimistic?: Optimistic<T> | undefined;
|
|
692
|
+
/** Folds the lib's run-dialect optimistic reducer before `optimistic`: `true` reads the run mounts off the state root; a selector picks a nested mount. */
|
|
693
|
+
runs?: true | ((state: T) => unknown) | undefined;
|
|
694
|
+
/** Makes dispatch records concrete in the draft (runs after the optimistic folds); without it, dispatch limbo stays out of `messages`. */
|
|
695
|
+
materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;
|
|
660
696
|
api: string;
|
|
661
697
|
resumeApi?: string | undefined;
|
|
662
698
|
protocol?: Protocol | undefined;
|
|
@@ -67,6 +67,23 @@ const withRun = (
|
|
|
67
67
|
],
|
|
68
68
|
});
|
|
69
69
|
|
|
70
|
+
const rollbackMaterialize = (draft: RunsServerState): void =>
|
|
71
|
+
runsMaterialize(draft, {
|
|
72
|
+
append: (m) =>
|
|
73
|
+
draft.messages.push({
|
|
74
|
+
id: m.id,
|
|
75
|
+
role: m.role,
|
|
76
|
+
text: m.parts.map((p) => (p.type === "text" ? p.text : "")).join(""),
|
|
77
|
+
}),
|
|
78
|
+
rollback: (to) => {
|
|
79
|
+
if (to === null) {
|
|
80
|
+
draft.messages = [];
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
draft.messages.splice(draft.messages.findIndex((m) => m.id === to) + 1);
|
|
84
|
+
},
|
|
85
|
+
});
|
|
86
|
+
|
|
70
87
|
const converter: StatewireThread.RunsStateConverter<RunsServerState> = (
|
|
71
88
|
state,
|
|
72
89
|
) => ({
|
|
@@ -323,7 +340,7 @@ describe("StatewireThread runs mode", () => {
|
|
|
323
340
|
);
|
|
324
341
|
});
|
|
325
342
|
|
|
326
|
-
it("
|
|
343
|
+
it("keeps dispatch limbo out of messages when no materialize option is set", async () => {
|
|
327
344
|
const server = createServer({
|
|
328
345
|
messages: [{ id: "m1", role: "user", text: "hi" }],
|
|
329
346
|
...withRun({
|
|
@@ -332,7 +349,6 @@ describe("StatewireThread runs mode", () => {
|
|
|
332
349
|
dispatching: {
|
|
333
350
|
trigger: "message-send",
|
|
334
351
|
messages: [
|
|
335
|
-
{ id: "m1", role: "user", parts: [{ type: "text", text: "hi" }] },
|
|
336
352
|
{ id: "d1", role: "user", parts: [{ type: "text", text: "go" }] },
|
|
337
353
|
],
|
|
338
354
|
},
|
|
@@ -340,25 +356,16 @@ describe("StatewireThread runs mode", () => {
|
|
|
340
356
|
});
|
|
341
357
|
const { aui, runs } = mountThread({ transport: server.transport });
|
|
342
358
|
|
|
343
|
-
await waitFor(() => expect(runs().dispatching?.messages).toHaveLength(
|
|
344
|
-
const messages = aui().thread().getState().messages;
|
|
345
|
-
expect(messages.map((m) => m.id)).toEqual(["m1", "d1"]);
|
|
346
|
-
expect(messages[1]!.role).toBe("user");
|
|
347
|
-
|
|
348
|
-
act(() => {
|
|
349
|
-
server.cell.state!.messages.push({ id: "d1", role: "user", text: "go" });
|
|
350
|
-
server.cell.state!.runs[0]!.dispatching = null;
|
|
351
|
-
});
|
|
352
|
-
await waitFor(() => expect(runs().dispatching).toBeNull());
|
|
359
|
+
await waitFor(() => expect(runs().dispatching?.messages).toHaveLength(1));
|
|
353
360
|
expect(
|
|
354
361
|
aui()
|
|
355
362
|
.thread()
|
|
356
363
|
.getState()
|
|
357
364
|
.messages.map((m) => m.id),
|
|
358
|
-
).toEqual(["m1"
|
|
365
|
+
).toEqual(["m1"]);
|
|
359
366
|
});
|
|
360
367
|
|
|
361
|
-
it("
|
|
368
|
+
it("projects the dispatch record through the materialize fold", async () => {
|
|
362
369
|
const server = createServer({
|
|
363
370
|
messages: [{ id: "m1", role: "user", text: "hi" }],
|
|
364
371
|
...withRun({
|
|
@@ -390,7 +397,7 @@ describe("StatewireThread runs mode", () => {
|
|
|
390
397
|
await waitFor(() => expect(runs().dispatching?.messages).toHaveLength(1));
|
|
391
398
|
const messages = aui().thread().getState().messages;
|
|
392
399
|
expect(messages.map((m) => m.id)).toEqual(["m1", "d1"]);
|
|
393
|
-
// Epoch createdAt proves d1 came through the converter
|
|
400
|
+
// Epoch createdAt proves d1 came through the converter (state-side fold).
|
|
394
401
|
expect(messages[1]!.createdAt.getTime()).toBe(0);
|
|
395
402
|
|
|
396
403
|
act(() => {
|
|
@@ -406,7 +413,7 @@ describe("StatewireThread runs mode", () => {
|
|
|
406
413
|
).toEqual(["m1", "d1"]);
|
|
407
414
|
});
|
|
408
415
|
|
|
409
|
-
it("renders the edit replacement in branch position
|
|
416
|
+
it("renders the edit replacement in branch position through the materialize fold", async () => {
|
|
410
417
|
const server = createServer({
|
|
411
418
|
messages: [
|
|
412
419
|
{ id: "u1", role: "user", text: "one" },
|
|
@@ -430,7 +437,10 @@ describe("StatewireThread runs mode", () => {
|
|
|
430
437
|
},
|
|
431
438
|
}),
|
|
432
439
|
});
|
|
433
|
-
const { aui, runs } = mountThread({
|
|
440
|
+
const { aui, runs } = mountThread({
|
|
441
|
+
transport: server.transport,
|
|
442
|
+
materialize: rollbackMaterialize,
|
|
443
|
+
});
|
|
434
444
|
|
|
435
445
|
await waitFor(() => expect(runs().status).toBe("running"));
|
|
436
446
|
expect(
|
|
@@ -441,7 +451,7 @@ describe("StatewireThread runs mode", () => {
|
|
|
441
451
|
).toEqual(["u1", "a1", "u2b"]);
|
|
442
452
|
});
|
|
443
453
|
|
|
444
|
-
it("renders the rolled-back view for a reload dispatch", async () => {
|
|
454
|
+
it("renders the rolled-back view for a reload dispatch through the materialize fold", async () => {
|
|
445
455
|
const server = createServer({
|
|
446
456
|
messages: [
|
|
447
457
|
{ id: "u1", role: "user", text: "one" },
|
|
@@ -457,7 +467,10 @@ describe("StatewireThread runs mode", () => {
|
|
|
457
467
|
},
|
|
458
468
|
}),
|
|
459
469
|
});
|
|
460
|
-
const { aui, runs } = mountThread({
|
|
470
|
+
const { aui, runs } = mountThread({
|
|
471
|
+
transport: server.transport,
|
|
472
|
+
materialize: rollbackMaterialize,
|
|
473
|
+
});
|
|
461
474
|
|
|
462
475
|
await waitFor(() => expect(runs().status).toBe("running"));
|
|
463
476
|
expect(
|
|
@@ -490,7 +503,10 @@ describe("StatewireThread runs mode", () => {
|
|
|
490
503
|
},
|
|
491
504
|
}),
|
|
492
505
|
});
|
|
493
|
-
const { aui, runs } = mountThread({
|
|
506
|
+
const { aui, runs } = mountThread({
|
|
507
|
+
transport: server.transport,
|
|
508
|
+
materialize: rollbackMaterialize,
|
|
509
|
+
});
|
|
494
510
|
|
|
495
511
|
await waitFor(() => expect(runs().status).toBe("running"));
|
|
496
512
|
expect(
|
|
@@ -530,7 +546,10 @@ describe("StatewireThread runs mode", () => {
|
|
|
530
546
|
|
|
531
547
|
it("flips the run optimistically for a dispatching send", async () => {
|
|
532
548
|
const server = createRemoteServer();
|
|
533
|
-
const { aui, runs } = mountThread({
|
|
549
|
+
const { aui, runs } = mountThread({
|
|
550
|
+
transport: server.transport,
|
|
551
|
+
materialize: rollbackMaterialize,
|
|
552
|
+
});
|
|
534
553
|
|
|
535
554
|
await waitFor(() =>
|
|
536
555
|
expect(aui().thread().getState().isLoading).toBe(false),
|
package/src/StatewireThread.ts
CHANGED
|
@@ -32,7 +32,6 @@ import {
|
|
|
32
32
|
createRunQueueAdapter,
|
|
33
33
|
resolveEditCommand,
|
|
34
34
|
resolveReloadCommand,
|
|
35
|
-
toDispatchingMessage,
|
|
36
35
|
toWireMessage,
|
|
37
36
|
viewedLeafId,
|
|
38
37
|
} from "./runCommands";
|
|
@@ -238,27 +237,9 @@ const useStatewireThread = (options: AnyOptions): ClientOutput<"thread"> => {
|
|
|
238
237
|
) as StatewireThread.State,
|
|
239
238
|
[converter, state, metadata],
|
|
240
239
|
);
|
|
241
|
-
// Dispatch limbo
|
|
242
|
-
//
|
|
243
|
-
|
|
244
|
-
const messages = useMemo((): StatewireThread.State["messages"] => {
|
|
245
|
-
const record = runs?.dispatching ?? null;
|
|
246
|
-
if (record === null || materializeSeam) return converted.messages;
|
|
247
|
-
let base = converted.messages;
|
|
248
|
-
if ("rollbackTo" in record) {
|
|
249
|
-
base =
|
|
250
|
-
record.rollbackTo == null
|
|
251
|
-
? []
|
|
252
|
-
: base.slice(
|
|
253
|
-
0,
|
|
254
|
-
base.findIndex((m) => m.id === record.rollbackTo) + 1,
|
|
255
|
-
);
|
|
256
|
-
}
|
|
257
|
-
const known = new Set(base.map((m) => m.id));
|
|
258
|
-
const pending = record.messages.filter((e) => !known.has(e.id));
|
|
259
|
-
if (pending.length === 0) return base;
|
|
260
|
-
return [...base, ...pending.map(toDispatchingMessage)];
|
|
261
|
-
}, [converted.messages, runs, materializeSeam]);
|
|
240
|
+
// Dispatch limbo is a materialize concern: the fold makes the record
|
|
241
|
+
// concrete in state before conversion.
|
|
242
|
+
const messages = converted.messages;
|
|
262
243
|
const queueItems = runs !== undefined ? runs.queue : converted.queue;
|
|
263
244
|
const steerQueueItems =
|
|
264
245
|
runs !== undefined ? runs.steerQueue : converted.steerQueue;
|
|
@@ -745,7 +726,7 @@ export namespace StatewireThread {
|
|
|
745
726
|
Record<string, (...args: any[]) => unknown>
|
|
746
727
|
>
|
|
747
728
|
| undefined;
|
|
748
|
-
/** Makes dispatch records concrete in the draft (runs after the optimistic folds);
|
|
729
|
+
/** Makes dispatch records concrete in the draft (runs after the optimistic folds); without it, dispatch limbo stays out of `messages`. */
|
|
749
730
|
materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;
|
|
750
731
|
};
|
|
751
732
|
}
|
package/src/runCommands.ts
CHANGED
|
@@ -2,10 +2,8 @@ import type {
|
|
|
2
2
|
AppendMessage,
|
|
3
3
|
ExternalThreadQueueAdapter,
|
|
4
4
|
QueuePlacement,
|
|
5
|
-
ThreadMessage,
|
|
6
5
|
} from "@assistant-ui/core";
|
|
7
6
|
import type { AssistantTransportThread } from "./AssistantTransportThread";
|
|
8
|
-
import type { StatewireThread } from "./StatewireThread";
|
|
9
7
|
|
|
10
8
|
export const toWireMessage = (
|
|
11
9
|
message: AppendMessage,
|
|
@@ -69,26 +67,6 @@ export const toQueueItemState = (
|
|
|
69
67
|
),
|
|
70
68
|
});
|
|
71
69
|
|
|
72
|
-
export const toDispatchingMessage = (
|
|
73
|
-
item: StatewireThread.RunsQueueEntry,
|
|
74
|
-
): ThreadMessage => ({
|
|
75
|
-
id: item.id,
|
|
76
|
-
role: "user",
|
|
77
|
-
createdAt: new Date(),
|
|
78
|
-
content: item.parts.map((part) =>
|
|
79
|
-
part.type === "text"
|
|
80
|
-
? part
|
|
81
|
-
: {
|
|
82
|
-
type: "file" as const,
|
|
83
|
-
data: part.url,
|
|
84
|
-
mimeType: part.mediaType,
|
|
85
|
-
...(part.filename !== undefined && { filename: part.filename }),
|
|
86
|
-
},
|
|
87
|
-
),
|
|
88
|
-
attachments: [],
|
|
89
|
-
metadata: { custom: {} },
|
|
90
|
-
});
|
|
91
|
-
|
|
92
70
|
const placementFields = (placement: QueuePlacement) => ({
|
|
93
71
|
...(placement.insertAfter !== undefined && {
|
|
94
72
|
insertAfter: placement.insertAfter,
|
package/src/transport.test.tsx
CHANGED
|
@@ -20,6 +20,7 @@ import {
|
|
|
20
20
|
useAssistantTransportSendCommand,
|
|
21
21
|
useAssistantTransportState,
|
|
22
22
|
} from "./hooks";
|
|
23
|
+
import { runsMaterialize } from "./runsMaterialize";
|
|
23
24
|
|
|
24
25
|
import {
|
|
25
26
|
INITIAL_STATE,
|
|
@@ -34,6 +35,7 @@ import {
|
|
|
34
35
|
sseEvent,
|
|
35
36
|
threadTexts,
|
|
36
37
|
toolCallConverter,
|
|
38
|
+
toThreadMessage,
|
|
37
39
|
} from "./__tests__/testHelpers";
|
|
38
40
|
import type { StreamResponse, TestState } from "./__tests__/testHelpers";
|
|
39
41
|
|
|
@@ -2757,3 +2759,158 @@ describe("input requests", () => {
|
|
|
2757
2759
|
unmount();
|
|
2758
2760
|
});
|
|
2759
2761
|
});
|
|
2762
|
+
|
|
2763
|
+
describe("runs fold and materialize", () => {
|
|
2764
|
+
type RunsTestState = TestState & {
|
|
2765
|
+
status: "ready" | "running";
|
|
2766
|
+
runs: {
|
|
2767
|
+
runId: string | null;
|
|
2768
|
+
status: string;
|
|
2769
|
+
queue: { id: string }[];
|
|
2770
|
+
steerQueue: { id: string }[];
|
|
2771
|
+
dispatching: {
|
|
2772
|
+
trigger: string;
|
|
2773
|
+
messages: {
|
|
2774
|
+
id: string;
|
|
2775
|
+
role: "user";
|
|
2776
|
+
parts: { type: "text"; text: string }[];
|
|
2777
|
+
}[];
|
|
2778
|
+
rollbackTo?: string | null;
|
|
2779
|
+
} | null;
|
|
2780
|
+
error: null;
|
|
2781
|
+
}[];
|
|
2782
|
+
};
|
|
2783
|
+
|
|
2784
|
+
const runsConverter: AssistantTransportThread.StateConverter<
|
|
2785
|
+
RunsTestState
|
|
2786
|
+
> = (state) => ({
|
|
2787
|
+
messages: state.messages.map(toThreadMessage),
|
|
2788
|
+
isRunning: state.status === "running",
|
|
2789
|
+
});
|
|
2790
|
+
|
|
2791
|
+
const materialize = (draft: RunsTestState): void =>
|
|
2792
|
+
runsMaterialize(draft, {
|
|
2793
|
+
append: (m) =>
|
|
2794
|
+
draft.messages.push({
|
|
2795
|
+
id: m.id,
|
|
2796
|
+
role: m.role,
|
|
2797
|
+
text: m.parts.map((p) => (p.type === "text" ? p.text : "")).join(""),
|
|
2798
|
+
}),
|
|
2799
|
+
rollback: (to) => {
|
|
2800
|
+
if (to === null) {
|
|
2801
|
+
draft.messages = [];
|
|
2802
|
+
return;
|
|
2803
|
+
}
|
|
2804
|
+
draft.messages.splice(draft.messages.findIndex((m) => m.id === to) + 1);
|
|
2805
|
+
},
|
|
2806
|
+
});
|
|
2807
|
+
|
|
2808
|
+
const mountRuns = (init?: Partial<RunsTestState>) => {
|
|
2809
|
+
const captured: { aui?: ReturnType<typeof useAui> } = {};
|
|
2810
|
+
const Capture: FC = () => {
|
|
2811
|
+
captured.aui = useAui();
|
|
2812
|
+
return null;
|
|
2813
|
+
};
|
|
2814
|
+
const App: FC = () => {
|
|
2815
|
+
const aui = useAui({
|
|
2816
|
+
thread: AssistantTransportThread<RunsTestState>({
|
|
2817
|
+
initialState: { messages: [], status: "ready", runs: [], ...init },
|
|
2818
|
+
api: "https://example.com/api",
|
|
2819
|
+
headers: {},
|
|
2820
|
+
converter: runsConverter,
|
|
2821
|
+
runs: true,
|
|
2822
|
+
materialize,
|
|
2823
|
+
capabilities: { edit: true },
|
|
2824
|
+
protocol: "assistant-transport",
|
|
2825
|
+
}),
|
|
2826
|
+
});
|
|
2827
|
+
return (
|
|
2828
|
+
<AuiProvider value={aui}>
|
|
2829
|
+
<Capture />
|
|
2830
|
+
</AuiProvider>
|
|
2831
|
+
);
|
|
2832
|
+
};
|
|
2833
|
+
render(<App />);
|
|
2834
|
+
return { aui: () => captured.aui! };
|
|
2835
|
+
};
|
|
2836
|
+
|
|
2837
|
+
it("projects a pending send through the runs fold and materialize", async () => {
|
|
2838
|
+
const fetchMock = installFetch();
|
|
2839
|
+
let server!: StreamResponse;
|
|
2840
|
+
fetchMock.setHandler(() => {
|
|
2841
|
+
server = createStreamResponse();
|
|
2842
|
+
return server.response;
|
|
2843
|
+
});
|
|
2844
|
+
|
|
2845
|
+
const { aui } = mountRuns();
|
|
2846
|
+
aui().thread().append("go");
|
|
2847
|
+
await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
|
|
2848
|
+
|
|
2849
|
+
// The lib fold predicts the dispatch record; materialize renders it. One copy.
|
|
2850
|
+
expect(threadTexts(aui)).toEqual(["go"]);
|
|
2851
|
+
expect(aui().thread().getState().isRunning).toBe(true);
|
|
2852
|
+
|
|
2853
|
+
const sent = fetchMock.requests[0]!.body.commands[0] as {
|
|
2854
|
+
message: { id: string };
|
|
2855
|
+
};
|
|
2856
|
+
server.emit({
|
|
2857
|
+
type: "update-state",
|
|
2858
|
+
operations: [
|
|
2859
|
+
{
|
|
2860
|
+
type: "set",
|
|
2861
|
+
path: [],
|
|
2862
|
+
value: {
|
|
2863
|
+
messages: [],
|
|
2864
|
+
status: "running",
|
|
2865
|
+
runs: [
|
|
2866
|
+
{
|
|
2867
|
+
runId: "run-1",
|
|
2868
|
+
status: "running",
|
|
2869
|
+
queue: [],
|
|
2870
|
+
steerQueue: [],
|
|
2871
|
+
dispatching: {
|
|
2872
|
+
trigger: "message-send",
|
|
2873
|
+
messages: [
|
|
2874
|
+
{
|
|
2875
|
+
id: sent.message.id,
|
|
2876
|
+
role: "user",
|
|
2877
|
+
parts: [{ type: "text", text: "go" }],
|
|
2878
|
+
},
|
|
2879
|
+
],
|
|
2880
|
+
},
|
|
2881
|
+
error: null,
|
|
2882
|
+
},
|
|
2883
|
+
],
|
|
2884
|
+
},
|
|
2885
|
+
},
|
|
2886
|
+
],
|
|
2887
|
+
});
|
|
2888
|
+
|
|
2889
|
+
// Canonical echo retires the overlay in the same publish: still one copy.
|
|
2890
|
+
await waitFor(() => expect(threadTexts(aui)).toEqual(["go"]));
|
|
2891
|
+
});
|
|
2892
|
+
|
|
2893
|
+
it("rewinds through the materialize fold for a pending edit", async () => {
|
|
2894
|
+
const fetchMock = installFetch();
|
|
2895
|
+
fetchMock.setHandler(() => createStreamResponse().response);
|
|
2896
|
+
|
|
2897
|
+
const { aui } = mountRuns({
|
|
2898
|
+
messages: [
|
|
2899
|
+
{ id: "u1", role: "user", text: "one" },
|
|
2900
|
+
{ id: "a1", role: "assistant", text: "re one" },
|
|
2901
|
+
],
|
|
2902
|
+
});
|
|
2903
|
+
sendCommand(aui, {
|
|
2904
|
+
type: "run/edit",
|
|
2905
|
+
message: {
|
|
2906
|
+
id: "u1b",
|
|
2907
|
+
role: "user",
|
|
2908
|
+
parts: [{ type: "text", text: "one'" }],
|
|
2909
|
+
},
|
|
2910
|
+
sourceId: "u1",
|
|
2911
|
+
rollbackTo: null,
|
|
2912
|
+
});
|
|
2913
|
+
|
|
2914
|
+
await waitFor(() => expect(threadTexts(aui)).toEqual(["one'"]));
|
|
2915
|
+
});
|
|
2916
|
+
});
|