@assistant-ui/react-statewire 0.11.2 → 0.13.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.
Files changed (39) hide show
  1. package/dist/AssistantTransportThread.d.ts +19 -6
  2. package/dist/AssistantTransportThread.d.ts.map +1 -1
  3. package/dist/AssistantTransportThread.js +22 -15
  4. package/dist/AssistantTransportThread.js.map +1 -1
  5. package/dist/StatewireThread.d.ts +27 -15
  6. package/dist/StatewireThread.d.ts.map +1 -1
  7. package/dist/StatewireThread.js +37 -37
  8. package/dist/StatewireThread.js.map +1 -1
  9. package/dist/hooks.d.ts +3 -1
  10. package/dist/hooks.d.ts.map +1 -1
  11. package/dist/hooks.js +11 -2
  12. package/dist/hooks.js.map +1 -1
  13. package/dist/index.d.ts +2 -2
  14. package/dist/index.js +2 -2
  15. package/dist/inputRequests.d.ts +2 -2
  16. package/dist/inputRequests.d.ts.map +1 -1
  17. package/dist/inputRequests.js +4 -2
  18. package/dist/inputRequests.js.map +1 -1
  19. package/dist/runCommands.d.ts +15 -4
  20. package/dist/runCommands.d.ts.map +1 -1
  21. package/dist/runCommands.js +27 -11
  22. package/dist/runCommands.js.map +1 -1
  23. package/dist/runsOptimistic.d.ts.map +1 -1
  24. package/dist/runsOptimistic.js +6 -6
  25. package/dist/runsOptimistic.js.map +1 -1
  26. package/package.json +1 -1
  27. package/src/AssistantTransportThread.ts +53 -16
  28. package/src/StatewireThread.runs.test.tsx +69 -55
  29. package/src/StatewireThread.test.tsx +40 -53
  30. package/src/StatewireThread.ts +89 -78
  31. package/src/athena.e2e.test.tsx +4 -2
  32. package/src/hooks.ts +11 -0
  33. package/src/index.ts +1 -0
  34. package/src/inputRequests.ts +4 -0
  35. package/src/legacy-diff.test.tsx +2 -1
  36. package/src/runCommands.ts +48 -10
  37. package/src/runsOptimistic.test.ts +64 -26
  38. package/src/runsOptimistic.ts +10 -7
  39. package/src/transport.test.tsx +46 -9
@@ -12,6 +12,8 @@ type AssistantTransportExtras = {
12
12
  sendCommand: (command: AssistantTransportThread.Command) => void;
13
13
  reconnect: () => void;
14
14
  state: unknown;
15
+ /** The thread status; present iff StatewireThread. */
16
+ status?: StatewireThread.ThreadStatus;
15
17
  /** The host's parked input requests; absent when the converter does not project them. */
16
18
  inputRequests?: readonly AssistantTransportThread.InputRequestState[];
17
19
  /** The typed runs read; present iff StatewireThread runs with the `runs` option. */
@@ -44,35 +46,43 @@ declare namespace AssistantTransportThread {
44
46
  };
45
47
  export type RunEnqueueCommand = {
46
48
  readonly type: "run/enqueue";
49
+ /** The run this command targets — the live run's id, or a fresh client-minted uuid on run-creating sends. */
50
+ readonly runId: string;
47
51
  } & ({
48
52
  readonly message: RunUserMessage;
49
- /** 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. */
50
- readonly anchorMessageId?: string | null;
53
+ /** Run anchor: the message the new content grows after, null asserting an empty thread. Present on run-creating sends; absent when targeting the live run. */
54
+ readonly runAnchorMessageId?: string | null;
51
55
  } | {
52
56
  readonly messageId: string;
53
57
  }) & RunPlacement;
54
58
  export type RunSteerCommand = {
55
59
  readonly type: "run/steer";
60
+ /** The run this command targets — the live run's id, or a fresh client-minted uuid on run-creating sends. */
61
+ readonly runId: string;
56
62
  } & ({
57
63
  readonly message: RunUserMessage;
58
- /** 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. */
59
- readonly anchorMessageId?: string | null;
64
+ /** Run anchor: the message the new content grows after, null asserting an empty thread. Present on run-creating sends; absent when targeting the live run. */
65
+ readonly runAnchorMessageId?: string | null;
60
66
  } | {
61
67
  readonly messageId: string;
62
68
  }) & RunPlacement;
63
69
  export type RunDequeueCommand = {
64
70
  readonly type: "run/dequeue";
71
+ readonly runId: string;
65
72
  readonly messageId: string;
66
73
  };
67
74
  export type RunEditCommand = {
68
75
  readonly type: "run/edit";
76
+ /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */
77
+ readonly runId: string;
69
78
  readonly message: RunUserMessage;
70
79
  readonly sourceId: string;
71
80
  /** Asserts `sourceId`'s parent — the rewind target; null names the root. */
72
- readonly rollbackTo: string | null;
81
+ readonly runAnchorMessageId: string | null;
73
82
  };
74
83
  export type RunContinueCommand = {
75
84
  readonly type: "run/continue";
85
+ readonly runId?: string;
76
86
  };
77
87
  export type ToolCallInputRequest = {
78
88
  readonly type: "tool-call";
@@ -105,6 +115,7 @@ declare namespace AssistantTransportThread {
105
115
  export type InputResponse = ReadonlyJSONValue;
106
116
  export type RunInputCommand = {
107
117
  readonly type: "run/input";
118
+ readonly runId?: string;
108
119
  readonly requestId: string;
109
120
  readonly response: InputResponse;
110
121
  };
@@ -114,9 +125,11 @@ declare namespace AssistantTransportThread {
114
125
  };
115
126
  export type RunReloadCommand = {
116
127
  readonly type: "run/reload";
128
+ /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */
129
+ readonly runId: string;
117
130
  readonly sourceId: string;
118
131
  /** Asserts `sourceId`'s parent — the rewind target; null names the root. */
119
- readonly rollbackTo: string | null;
132
+ readonly runAnchorMessageId: string | null;
120
133
  };
121
134
  export type RunCommand = RunEnqueueCommand | RunSteerCommand | RunDequeueCommand | RunEditCommand | RunContinueCommand | RunReloadCommand | RunInputCommand;
122
135
  export type Command = RunCommand | UserCommands;
@@ -1 +1 @@
1
- {"version":3,"file":"AssistantTransportThread.d.ts","names":[],"sources":["../src/AssistantTransportThread.ts"],"mappings":";;;;;;;;cA6Da;KAID;GACT;EACD,cAAc,SAAS,yBAAyB;EAChD;EACA;;EAEA,yBAAyB,yBAAyB;;EAElD,OAAO,gBAAgB;;cAGZ,6BACX,oBACC;cA4ZU,2BAA4B,GACvC,SAAS,yBAAyB,QAAQ,OACzC,gBAAgB;kBAKF;OACV,eAAe,UAAU,eAAe,UAAU;cAE3C;aACD;aACA;;cAGC;aACD;aACA;aACA;aACA;;cAGC;aACD;aACA;aACA,iBAAiB,WAAW;aAC5B,WAAW;;;cA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;;MAEA;;IAGN;MAEM,cAAc"}
1
+ {"version":3,"file":"AssistantTransportThread.d.ts","names":[],"sources":["../src/AssistantTransportThread.ts"],"mappings":";;;;;;;;cA6Da;KAID;GACT;EACD,cAAc,SAAS,yBAAyB;EAChD;EACA;;EAEA,SAAS,gBAAgB;;EAEzB,yBAAyB,yBAAyB;;EAElD,OAAO,gBAAgB;;cAGZ,6BACX,oBACC;cAobU,2BAA4B,GACvC,SAAS,yBAAyB,QAAQ,OACzC,gBAAgB;kBAKF;OACV,eAAe,UAAU,eAAe,UAAU;cAE3C;aACD;aACA;;cAGC;aACD;aACA;aACA;aACA;;cAGC;aACD;aACA;aACA,iBAAiB,WAAW;aAC5B,WAAW;;;cAIV;aACD;aACA;;cAGC;aACD;;aAEA;;aAGI,SAAS;;aAET;;aAEA;OAEb;cAEU;aACD;;aAEA;;aAGI,SAAS;;aAET;;aAEA;OAEb;cAEU;aACD;aACA;aACA;;cAGC;aACD;;aAEA;aACA,SAAS;aACT;;aAEA;;cAGC;aACD;aACA;;cAGC;aACD;aACA;aACA;;cAGC;aACD;aACA;aACA;;cAGC;aACD;aACA;cACC,cAAc;;;cAId,eACR,uBACA,2BACA;cAEQ;aACD,QAAQ;;aAER;aACA,WAAW;;cAGV;aACD;aACA,aAAa;aACb;;cAGC,gBAAgB;cAEhB;aACD;aACA;aACA;aACA,UAAU;;;cAIT,oBAAoB;aACrB,UAAU;;cAGT;aACD;;aAEA;aACA;;aAEA;;cAGC,aACR,oBACA,kBACA,oBACA,iBACA,qBACA,mBACA;cAEQ,UAAU,aAAa;;cAGvB;aACD;aACA,iBAAiB,WAAW;;cAG3B;aACD,mBAAmB;aACnB,QAAQ;aACR;;;;;;;;aAQA,iBAAiB;;aAEjB,sBAAsB;;;;;;aAMtB,yBAAyB,yBAAyB;;cAGjD,eAAe,MAAM,OAAO,MAAM;;cAGlC,WAAW,MACrB,OAAO,GACP,SAAS,SACT,KAAK,gBAAgB;cAGX,eAAe,yBAAyB;cAExC;cAEA;IACV,UAAU;IACV;IACA;IACA,OAAO;IACP,cAAc;IACd,QAAQ;IACR;IACA;KACC;;cAGS,QAAQ;IAClB,cAAc;IACd,WAAW,eAAe;IAC1B,aAAa,WAAW;;IAExB,gBAAgB,OAAO;;IAEvB,cAAc,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,5 @@
1
1
  import { AssistantTransportHost } from "./host.js";
2
- import { createRunQueueAdapter, resolveEditCommand, resolveReloadCommand, toWireMessage, viewedLeafId } from "./runCommands.js";
2
+ import { createRunQueueAdapter, resolveEditCommand, resolveReloadCommand, sendFields, toWireMessage } from "./runCommands.js";
3
3
  import { runsOptimistic } from "./runsOptimistic.js";
4
4
  import { resolveToolApprovalInput, resolveToolResultInput } from "./inputRequests.js";
5
5
  import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "@assistant-ui/tap/react-shim";
@@ -98,20 +98,23 @@ const useAssistantTransportThread = (options) => {
98
98
  queue,
99
99
  ctxOf
100
100
  ]);
101
- const converted = useMemo(() => converter(project(agentState)), [
102
- converter,
103
- project,
104
- agentState
105
- ]);
101
+ const projected = useMemo(() => project(agentState), [project, agentState]);
102
+ const converted = useMemo(() => converter(projected), [converter, projected]);
106
103
  const convertedRef = useRef(converted);
107
104
  convertedRef.current = converted;
105
+ const liveRunId = useMemo(() => {
106
+ if (runsOption === void 0) return null;
107
+ return (runsOption === true ? projected : runsOption(projected))?.runs?.[0]?.runId ?? null;
108
+ }, [runsOption, projected]);
109
+ const liveRunIdRef = useRef(liveRunId);
110
+ liveRunIdRef.current = liveRunId;
108
111
  const [toolInvocations] = useState(() => new ToolInvocationTracker(() => {
109
112
  return (clientRef.current ?? clientRef.parent).modelContext().getModelContext().tools;
110
113
  }, {
111
114
  onResult: (command_2) => {
112
115
  const messages = convertedRef.current.messages;
113
116
  if (!messagesContainToolCall(messages, command_2.toolCallId)) return;
114
- dispatch(resolveToolResultInput(convertedRef.current.inputRequests ?? [], command_2));
117
+ dispatch(resolveToolResultInput(convertedRef.current.inputRequests ?? [], command_2, liveRunIdRef.current));
115
118
  },
116
119
  onStatusesChange: (statuses) => {
117
120
  setToolStatuses(statuses.size === 0 ? EMPTY_TOOL_STATUSES : Object.fromEntries(statuses));
@@ -143,7 +146,7 @@ const useAssistantTransportThread = (options) => {
143
146
  inputRequests
144
147
  ]);
145
148
  const handleEdit = (message) => {
146
- const command_3 = resolveEditCommand(convertedRef.current.messages, message);
149
+ const command_3 = resolveEditCommand(convertedRef.current.messages, message, liveRunIdRef.current);
147
150
  toolInvocations.abort().then(() => dispatch(command_3));
148
151
  };
149
152
  const handleAppend = (message_0) => {
@@ -151,8 +154,7 @@ const useAssistantTransportThread = (options) => {
151
154
  const startRun = message_0.startRun ?? message_0.role === "user";
152
155
  const command_4 = {
153
156
  type: "run/steer",
154
- message: toWireMessage(message_0, crypto.randomUUID()),
155
- anchorMessageId: viewedLeafId(convertedRef.current.messages)
157
+ ...sendFields(convertedRef.current.messages, liveRunIdRef.current, toWireMessage(message_0, crypto.randomUUID()))
156
158
  };
157
159
  commands.setParentId(message_0.parentId).catch(() => {});
158
160
  const send = () => dispatch(command_4, { schedule: startRun });
@@ -177,8 +179,9 @@ const useAssistantTransportThread = (options) => {
177
179
  if (queueProjection !== void 0 && options.capabilities?.queue) throw new Error("statewire: the converter's queue projection excludes capabilities.queue");
178
180
  const [queueSeam] = useState(() => ({ present: queueProjection !== void 0 }));
179
181
  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");
180
- const serverQueue = useMemo(() => queueProjection ? createRunQueueAdapter(converted.messages, queueProjection, steerProjection, dispatch, (command_5) => dispatch(command_5)) : void 0, [
182
+ const serverQueue = useMemo(() => queueProjection ? createRunQueueAdapter(converted.messages, liveRunId, queueProjection, steerProjection, dispatch, (command_5) => dispatch(command_5)) : void 0, [
181
183
  converted.messages,
184
+ liveRunId,
182
185
  queueProjection,
183
186
  steerProjection,
184
187
  dispatch
@@ -219,7 +222,7 @@ const useAssistantTransportThread = (options) => {
219
222
  } },
220
223
  ...options.capabilities?.edit && { onEdit: handleEdit },
221
224
  onReload: (parentId) => {
222
- const command_6 = resolveReloadCommand(convertedRef.current.messages, parentId);
225
+ const command_6 = resolveReloadCommand(convertedRef.current.messages, parentId, liveRunIdRef.current);
223
226
  toolInvocations.abort().then(() => dispatch(command_6));
224
227
  },
225
228
  onCancel: () => {
@@ -228,15 +231,19 @@ const useAssistantTransportThread = (options) => {
228
231
  },
229
232
  onResume: () => {
230
233
  if (options.capabilities?.continue) {
231
- dispatch({ type: "run/continue" });
234
+ const runId = liveRunIdRef.current;
235
+ dispatch({
236
+ type: "run/continue",
237
+ ...runId !== null && { runId }
238
+ });
232
239
  return;
233
240
  }
234
241
  if (!options.resumeApi) throw new Error("Must pass resumeApi to options to resume runs");
235
242
  commands.resume().catch(() => {});
236
243
  },
237
244
  ...inputRequests !== void 0 && {
238
- onAddToolResult: (toolOptions) => dispatch(resolveToolResultInput(convertedRef.current.inputRequests, toolOptions)),
239
- onRespondToToolApproval: (options_0) => dispatch(resolveToolApprovalInput(convertedRef.current.inputRequests, options_0))
245
+ onAddToolResult: (toolOptions) => dispatch(resolveToolResultInput(convertedRef.current.inputRequests, toolOptions, liveRunIdRef.current)),
246
+ onRespondToToolApproval: (options_0) => dispatch(resolveToolApprovalInput(convertedRef.current.inputRequests, options_0, liveRunIdRef.current))
240
247
  },
241
248
  onResumeToolCall: ({ toolCallId, payload }) => {
242
249
  if (!toolInvocations.resume(toolCallId, payload)) throw new Error(`Tool call ${toolCallId} is not waiting for resume.`);
@@ -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","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,MAA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QqF,cAAcuB,QAAQ,EAAEC,QAAQ9C,WAAW;EACvD+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"}
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","sendFields","toWireMessage","runsOptimistic","resolveToolApprovalInput","resolveToolResultInput","EMPTY_TOOL_STATUSES","Record","EMPTY_QUEUE_ITEMS","subscribeNoop","symbolAssistantTransportExtras","Symbol","AssistantTransportExtras","sendCommand","command","AssistantTransportThread","Command","reconnect","state","status","ThreadStatus","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","projected","converted","convertedRef","liveRunId","mount","runId","liveRunIdRef","toolInvocations","tools","onResult","onStatusesChange","statuses","size","Object","fromEntries","setState","isRunning","isLoading","reset","inputSeam","present","handleEdit","abort","then","handleAppend","sourceId","startRun","role","crypto","randomUUID","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","runAnchorMessageId","messageId","RunSteerCommand","RunDequeueCommand","RunEditCommand","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 sendFields,\n toWireMessage,\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 thread status; present iff StatewireThread. */\n status?: StatewireThread.ThreadStatus;\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 projected = useMemo(() => project(agentState), [project, agentState]);\n const converted = useMemo(() => converter(projected), [converter, projected]);\n const convertedRef = useRef(converted);\n convertedRef.current = converted;\n\n const liveRunId = useMemo((): string | null => {\n if (runsOption === undefined) return null;\n const mount = (\n runsOption === true ? projected : runsOption(projected as never)\n ) as { runs?: readonly { runId: string | null }[] } | undefined;\n return mount?.runs?.[0]?.runId ?? null;\n }, [runsOption, projected]);\n const liveRunIdRef = useRef(liveRunId);\n liveRunIdRef.current = liveRunId;\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 liveRunIdRef.current,\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(\n convertedRef.current.messages,\n message,\n liveRunIdRef.current,\n );\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 ...sendFields(\n convertedRef.current.messages,\n liveRunIdRef.current,\n toWireMessage(message, crypto.randomUUID()),\n ),\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 liveRunId,\n queueProjection,\n steerProjection,\n dispatch,\n (command) => dispatch(command),\n )\n : undefined,\n [converted.messages, liveRunId, 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 liveRunIdRef.current,\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 const runId = liveRunIdRef.current;\n dispatch({\n type: \"run/continue\",\n ...(runId !== null && { runId }),\n });\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 liveRunIdRef.current,\n ),\n ),\n onRespondToToolApproval: (options: RespondToToolApprovalOptions) =>\n dispatch(\n resolveToolApprovalInput(\n convertedRef.current.inputRequests!,\n options,\n liveRunIdRef.current,\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 /** The run this command targets — the live run's id, or a fresh client-minted uuid on run-creating sends. */\n readonly runId: string;\n } & (\n | {\n readonly message: RunUserMessage;\n /** Run anchor: the message the new content grows after, null asserting an empty thread. Present on run-creating sends; absent when targeting the live run. */\n readonly runAnchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n RunPlacement;\n\n export type RunSteerCommand = {\n readonly type: \"run/steer\";\n /** The run this command targets — the live run's id, or a fresh client-minted uuid on run-creating sends. */\n readonly runId: string;\n } & (\n | {\n readonly message: RunUserMessage;\n /** Run anchor: the message the new content grows after, null asserting an empty thread. Present on run-creating sends; absent when targeting the live run. */\n readonly runAnchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n RunPlacement;\n\n export type RunDequeueCommand = {\n readonly type: \"run/dequeue\";\n readonly runId: string;\n readonly messageId: string;\n };\n\n export type RunEditCommand = {\n readonly type: \"run/edit\";\n /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */\n readonly runId: string;\n readonly message: RunUserMessage;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly runAnchorMessageId: string | null;\n };\n\n export type RunContinueCommand = {\n readonly type: \"run/continue\";\n readonly runId?: string;\n };\n\n export type ToolCallInputRequest = {\n readonly type: \"tool-call\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type ToolApprovalInputRequest = {\n readonly type: \"tool-approval\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type CustomInputRequest = {\n readonly type: string;\n readonly id: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A host request parking the run until answered; open union for custom types. */\n export type InputRequest =\n | ToolCallInputRequest\n | ToolApprovalInputRequest\n | CustomInputRequest;\n\n export type 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 runId?: string;\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 /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */\n readonly runId: string;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly runAnchorMessageId: string | null;\n };\n\n export type RunCommand =\n | RunEnqueueCommand\n | RunSteerCommand\n | RunDequeueCommand\n | RunEditCommand\n | RunContinueCommand\n | RunReloadCommand\n | RunInputCommand;\n\n export type Command = RunCommand | UserCommands;\n\n /** A queued message projected out of the host state, wire shape. */\n export type RunQueueItem = {\n readonly id: string;\n readonly parts: readonly (TextPart | FilePart)[];\n };\n\n 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;AAeA,MAAac,8BACXC,WAC6B;CAC7B,IACE,OAAOA,WAAW,YAClBA,UAAU,QACV,EAAEhB,kCAAkCgB,SAEpC,MAAM,IAAIC,MACR,+FACF;C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IAClC,MAAMjE,QAAQC,aAAahD;IAC3BkB,SAAS;KACPjC,MAAM;KACN,GAAI8D,UAAU,QAAQ,EAAEA,MAAM;IAChC,CAAC;IACD;GACF;GACA,IAAI,CAACpD,QAAQsH,WACX,MAAM,IAAI3I,MAAM,+CAA+C;GACjE,SAAc4I,OAAO,CAAC,CAAC7F,YAAY,CAAC,CAAC;EACvC;EACA,GAAIrD,kBAAkByB,KAAAA,KAAa;GACjC0H,kBAAkBC,gBAChBlG,SACElE,uBACE4F,aAAa5C,QAAQhC,eACrBoJ,aACApE,aAAahD,OACf,CACF;GACFqH,0BAA0B1H,cACxBuB,SACEnE,yBACE6F,aAAa5C,QAAQhC,eACrB2B,WACAqD,aAAahD,OACf,CACF;EACJ;EACAsH,mBAAmB,EAAElI,YAAYmI,cAAqC;GACpE,IAAI,CAACtE,gBAAgBiE,OAAO9H,YAAYmI,OAAO,GAC7C,MAAM,IAAIjJ,MAAM,aAAac,WAAU,4BAA6B;EACxE;EACAoI,sBAAsBC,aAAsB;GAC1C,SAAcC,YAAYD,QAAQ,CAAC,CAACpG,YAAY,CAAC,CAAC;GAElDuB,aAAa5C,UAAUiC,UAAUK,QAAQmF,QAAQ,CAAC;GAClDxE,gBAAgBW,MAAM;GACtBrC,gBAAgBtE,mBAAmB;EACrC;CACF,CAAC,CACH;AACF;AAEA,MAAaS,4BACXiC,YAEAnF,SAASkF,2BAA2B,CAAC,CACnCC,OACF;AA0QF7E,uBACE4E,6BACA/E,eAAe8E,KAAAA,CAAkB,CAAC,CAACmM,IACrC"}
@@ -34,35 +34,43 @@ declare namespace StatewireThread {
34
34
  };
35
35
  type RunEnqueueCommand = {
36
36
  readonly type: "run/enqueue";
37
+ /** The run this command targets — the live run's id, or a fresh client-minted uuid on run-creating sends. */
38
+ readonly runId: string;
37
39
  } & ({
38
40
  readonly message: UserMessage;
39
- /** 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. */
40
- readonly anchorMessageId?: string | null;
41
+ /** Run anchor: the message the new content grows after, null asserting an empty thread. Present on run-creating sends; absent when targeting the live run. */
42
+ readonly runAnchorMessageId?: string | null;
41
43
  } | {
42
44
  readonly messageId: string;
43
45
  }) & Placement;
44
46
  type RunSteerCommand = {
45
47
  readonly type: "run/steer";
48
+ /** The run this command targets — the live run's id, or a fresh client-minted uuid on run-creating sends. */
49
+ readonly runId: string;
46
50
  } & ({
47
51
  readonly message: UserMessage;
48
- /** 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. */
49
- readonly anchorMessageId?: string | null;
52
+ /** Run anchor: the message the new content grows after, null asserting an empty thread. Present on run-creating sends; absent when targeting the live run. */
53
+ readonly runAnchorMessageId?: string | null;
50
54
  } | {
51
55
  readonly messageId: string;
52
56
  }) & Placement;
53
57
  type RunDequeueCommand = {
54
58
  readonly type: "run/dequeue";
59
+ readonly runId: string;
55
60
  readonly messageId: string;
56
61
  };
57
62
  type RunEditCommand = {
58
63
  readonly type: "run/edit";
64
+ /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */
65
+ readonly runId: string;
59
66
  readonly message: UserMessage;
60
67
  readonly sourceId: string;
61
68
  /** Asserts `sourceId`'s parent — the rewind target; null names the root. */
62
- readonly rollbackTo: string | null;
69
+ readonly runAnchorMessageId: string | null;
63
70
  };
64
71
  type RunContinueCommand = {
65
72
  readonly type: "run/continue";
73
+ readonly runId?: string;
66
74
  };
67
75
  type ToolCallInputRequest = {
68
76
  readonly type: "tool-call";
@@ -95,6 +103,7 @@ declare namespace StatewireThread {
95
103
  type InputResponse = ReadonlyJSONValue;
96
104
  type RunInputCommand = {
97
105
  readonly type: "run/input";
106
+ readonly runId?: string;
98
107
  readonly requestId: string;
99
108
  readonly response: InputResponse;
100
109
  };
@@ -104,9 +113,11 @@ declare namespace StatewireThread {
104
113
  };
105
114
  type RunReloadCommand = {
106
115
  readonly type: "run/reload";
116
+ /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */
117
+ readonly runId: string;
107
118
  readonly sourceId: string;
108
119
  /** Asserts `sourceId`'s parent — the rewind target; null names the root. */
109
- readonly rollbackTo: string | null;
120
+ readonly runAnchorMessageId: string | null;
110
121
  };
111
122
  type RunCommand = RunEnqueueCommand | RunSteerCommand | RunDequeueCommand | RunEditCommand | RunContinueCommand | RunReloadCommand | RunInputCommand;
112
123
  type Command = AssistantTransportThread.Command | RunCommand;
@@ -139,7 +150,9 @@ declare namespace StatewireThread {
139
150
  readonly inputRequests?: readonly InputRequestState[];
140
151
  };
141
152
  /** Run subsystem status replicated by the host. */
142
- type RunStatus = "ready" | "running" | "stopped" | "error" | "input-required";
153
+ type RunStatus = "running" | "stopped" | "error" | "input-required";
154
+ /** The thread's status, derived from the state: `"loading"` while the runs mount is absent, `"ready"` while resting, otherwise the run's status. */
155
+ type ThreadStatus = "loading" | "ready" | RunStatus;
143
156
  /** A queue-lane entry as replicated: the user message plus host-stamped `meta`. */
144
157
  type RunsQueueEntry = UserMessage & {
145
158
  /** Host-stamped opaque per-entry metadata. */
@@ -167,9 +180,9 @@ declare namespace StatewireThread {
167
180
  };
168
181
  /** A replicated run entry — one element of the mount's `runs` array. */
169
182
  type RunState = {
170
- /** The run's identity — minted at dispatch, persists through input-required, null in error/stop. */
183
+ /** The run's identity — client-minted, adopted by the host at run creation; persists through steers, input-required, and error/stop, retiring only when the queue drains and the run completes. */
171
184
  readonly runId: string | null;
172
- readonly status: Exclude<RunStatus, "ready">;
185
+ readonly status: RunStatus;
173
186
  readonly queue: readonly RunsQueueEntry[];
174
187
  readonly steerQueue: readonly RunsQueueEntry[];
175
188
  /** The dispatch record — the unacked batch handed to the run, cleared at the ack. */
@@ -188,14 +201,13 @@ declare namespace StatewireThread {
188
201
  /** The runs mount as replicated: the run entries plus the top-level status projection. */
189
202
  type RunsState = {
190
203
  /** Projection of `runs[0]?.status ?? "ready"`. */
191
- readonly status: RunStatus;
204
+ readonly status: Exclude<ThreadStatus, "loading">;
192
205
  /** At most one entry; empty while resting. */
193
206
  readonly runs: readonly RunState[];
194
207
  };
195
- /** The run subsystem's typed read — `runs[0]` of the selected mount with unsettled commands folded in, ready defaults while resting. */
208
+ /** The run subsystem's typed read — `runs[0]` of the selected mount with unsettled commands folded in, resting defaults while no entry is live. */
196
209
  type Runs = {
197
- readonly status: RunStatus;
198
- /** The live run's id — non-null in running and input-required; stamped onto `run/stop`. */
210
+ /** The live run's id — non-null whenever a run entry is live (running, input-required, error/stop); the target for `run/*` sends. */
199
211
  readonly runId: string | null;
200
212
  readonly queue: readonly RunsQueueEntry[];
201
213
  readonly steerQueue: readonly RunsQueueEntry[];
@@ -232,8 +244,8 @@ declare namespace StatewireThread {
232
244
  };
233
245
  type Options<T> = {
234
246
  transport: Transport<T>;
235
- /** Preloads the thread: published and interactive from the first render, replaced by the attach snapshot. Omitted, the thread stays loading until attach. */
236
- initialState?: T | undefined;
247
+ /** The pre-attach state, replaced by the attach snapshot. With runs, `runs: []` projects ready (interactive from the first render); an absent runs mount projects loading until attach. */
248
+ initialState: T;
237
249
  converter: StateConverter<T>;
238
250
  runs?: undefined;
239
251
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;;cA6Xa;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;;OAG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O,OAAO,YAAY;;;IAIhC,kBACM,OAAO,YAAY,IAAI;MAAO,SAAS,UAAU;;;IAGvD,uBACM,YAAY,gBAAgB;IAElC,YAAY,OAAO;IACnB;MAEM;;MAEA;;MAEA;;IAGN;MAEM,cAAc;MACd,SAAS;MACT,WAAW;;;;OAMP,YAAY,KAAK,KAAK,QAAQ;;IAExC,eAAe,OAAO;IACtB,WAAW,mBAAmB;;IAE9B,aACI,gBAAgB,WACd,GACA,mBAAmB;;IAIzB,cAAc,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"}
1
+ {"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;;cAgYa;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;;aAEA;;aAGI,SAAS;;aAET;;aAEA;OAEb;OAEU;aACD;;aAEA;;aAGI,SAAS;;aAET;;aAEA;OAEb;OAEU;aACD;aACA;aACA;;OAGC;aACD;;aAEA;aACA,SAAS;aACT;;aAEA;;OAGC;aACD;aACA;;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;aACA,UAAU;;;OAIT,oBAAoB;aACrB,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