@assistant-ui/react-statewire 0.30.0 → 0.32.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 (41) hide show
  1. package/README.md +7 -5
  2. package/dist/StatewireThread.d.ts +341 -343
  3. package/dist/StatewireThread.d.ts.map +1 -1
  4. package/dist/StatewireThread.js +82 -41
  5. package/dist/StatewireThread.js.map +1 -1
  6. package/dist/hooks.d.ts +7 -9
  7. package/dist/hooks.d.ts.map +1 -1
  8. package/dist/hooks.js +1 -2
  9. package/dist/hooks.js.map +1 -1
  10. package/dist/index.d.ts +4 -4
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/inputRequests.d.ts +9 -12
  13. package/dist/inputRequests.d.ts.map +1 -1
  14. package/dist/inputRequests.js +1 -2
  15. package/dist/localStorage.d.ts +29 -32
  16. package/dist/localStorage.d.ts.map +1 -1
  17. package/dist/localStorage.js +54 -21
  18. package/dist/localStorage.js.map +1 -1
  19. package/dist/runCommands.d.ts +34 -34
  20. package/dist/runCommands.d.ts.map +1 -1
  21. package/dist/runCommands.js +10 -4
  22. package/dist/runCommands.js.map +1 -1
  23. package/dist/runsMaterialize.d.ts +2 -5
  24. package/dist/runsMaterialize.d.ts.map +1 -1
  25. package/dist/runsMaterialize.js +1 -2
  26. package/dist/runsOptimistic.d.ts +2 -5
  27. package/dist/runsOptimistic.d.ts.map +1 -1
  28. package/dist/runsOptimistic.js +2 -3
  29. package/dist/runsOptimistic.js.map +1 -1
  30. package/package.json +16 -14
  31. package/src/StatewireThread.drafts.test.tsx +6 -2
  32. package/src/StatewireThread.failed.test.tsx +1 -1
  33. package/src/StatewireThread.runs.test.tsx +1 -1
  34. package/src/StatewireThread.test.tsx +127 -0
  35. package/src/StatewireThread.ts +63 -18
  36. package/src/localStorage.test.ts +108 -29
  37. package/src/localStorage.ts +62 -20
  38. package/src/runCommands.test.ts +44 -1
  39. package/src/runCommands.ts +13 -3
  40. package/src/runsOptimistic.test.ts +1 -1
  41. package/src/runsOptimistic.ts +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;cA2Da;cAEA,oBAAqB,oBAAkB,gBAAgB;cAkhBvD,kBAAmB,GAC9B,SAAS,gBAAgB,QAAQ,OAChC,gBAAgB;kBAGF;OACV,eAAe,UAAU,eAAe,UAAU;cAE3C,UAAU,KAAK,gBAAgB,UAAU;;cAGzC;aACD;aACA,sBAAsB;;;cAIrB;IACV,QAAQ;IACR,MAAM,OAAO;IACb;;cAGU;KACT;;IAED,cAAc,SAAS,YAAY;IACnC;IACA,YAAY,gBAAgB;;IAE5B,WAAW,mBAAmB;;IAE9B,SACE,kBACA,gBACA,+BACG;;IAEL;IACA,QAAQ;;IAER;IACA,wBAAwB;IACxB,MAAM;;IAEN,cAAc;;IAEd,gBAAgB;;IAEhB,YAAY;;cAGF;aACD;aACA;;cAGC;aACD;aACA;aACA;aACA;;cAGC;aACD;aACA;aACA,iBAAiB,WAAW;aAC5B,WAAW;;;cAIV;aACD;aACA;;OAGN,eAAe;aACT,MAAM;;aAEN;;aAGI,SAAS;;aAET;;aAEA;OAEb;cAEU,oBAAoB;cAEpB,kBAAkB;cAElB;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,gBAAgB;cAEhB;aACD;aACA;aACA;aACA,UAAU;;;cAIT,oBAAoB;aACrB,WAAW;;aAEX,OAAO;;;cAIN;aACD;aACA;;cAGC;aACD;aACA;;cAGC;aACD;;aAEA;aACA;;aAEA;;cAGC,aACR,oBACA,kBACA,oBACA,iBACA,qBACA,mBACA;cAEQ,UAAU,aAAa;;cAGvB;aACD;aACA,iBAAiB,WAAW;aAC5B,WAAW;;;cAIV;;c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@assistant-ui/store";
8
8
  import { toToolsJSONSchema } from "assistant-stream";
9
9
  import { DEFAULT_PROTOCOL, useStatewire } from "statewire";
10
- //#region src/StatewireThread.ts
10
+ // src/StatewireThread.ts
11
11
  const NO_DOCUMENTS = /* @__PURE__ */ new Map();
12
12
  const noopSubscribe = () => () => {};
13
13
  const symbolStatewireExtras = Symbol("statewire-extras");
@@ -75,6 +75,7 @@ const useStatewireThread = (options) => {
75
75
  const clientRef = useAssistantClientRef();
76
76
  const contextRef = useRef(setContext);
77
77
  contextRef.current = setContext;
78
+ const contextFailure = useRef(void 0);
78
79
  const { contextSync } = options;
79
80
  const contextProtocol = options.protocol ?? DEFAULT_PROTOCOL;
80
81
  useEffect(() => {
@@ -85,7 +86,15 @@ const useStatewireThread = (options) => {
85
86
  const value = ambientContextOf(modelContext.getModelContext());
86
87
  const key = JSON.stringify(value);
87
88
  if (key === lastSent) return;
88
- contextRef.current(contextProtocol, value);
89
+ try {
90
+ contextRef.current(contextProtocol, value);
91
+ } catch (error_0) {
92
+ contextFailure.current = error_0;
93
+ lastSent = void 0;
94
+ latest.current.onError?.(error_0);
95
+ return;
96
+ }
97
+ contextFailure.current = void 0;
89
98
  lastSent = key;
90
99
  };
91
100
  if (!modelContext.subscribe) throw new Error("statewire: contextSync requires a subscribable model context");
@@ -96,20 +105,30 @@ const useStatewireThread = (options) => {
96
105
  contextProtocol,
97
106
  clientRef
98
107
  ]);
99
- const dispatch = useCallback((command_2) => {
100
- setPending((prev_0) => [...prev_0, command_2]);
101
- const settled = commands[command_2.type](command_2);
102
- settled.catch((error_0) => {
103
- retire(command_2);
104
- latest.current.onError?.(error_0);
108
+ const [heldByContext] = useState(() => (command_2) => contextFailure.current !== void 0 && (command_2.type === "run/enqueue" || command_2.type === "run/steer" || command_2.type === "run/edit") ? new Error("statewire: the model context was rejected", { cause: contextFailure.current }) : void 0);
109
+ const dispatch = useCallback((command_3) => {
110
+ const held = heldByContext(command_3);
111
+ if (held !== void 0) {
112
+ latest.current.onError?.(held);
113
+ return Promise.reject(held);
114
+ }
115
+ setPending((prev_0) => [...prev_0, command_3]);
116
+ const settled = commands[command_3.type](command_3);
117
+ settled.catch((error_1) => {
118
+ retire(command_3);
119
+ latest.current.onError?.(error_1);
105
120
  });
106
121
  return settled;
107
- }, [commands, retire]);
122
+ }, [
123
+ commands,
124
+ retire,
125
+ heldByContext
126
+ ]);
108
127
  const threadRef = useRef(null);
109
- const dispatchSend = useCallback((command_3, message) => {
110
- if (message.sourceId != null) return void dispatch(command_3);
128
+ const dispatchSend = useCallback((command_4, message) => {
129
+ if (message.sourceId != null) return void dispatch(command_4);
111
130
  const text = message.content.flatMap((part) => part.type === "text" ? [part.text] : []).join("\n\n");
112
- dispatch(command_3).catch(() => {
131
+ dispatch(command_4).catch(() => {
113
132
  const setText = threadRef.current.composer().setText;
114
133
  setText((prev_1) => prev_1 === "" ? text : prev_1);
115
134
  });
@@ -139,9 +158,9 @@ const useStatewireThread = (options) => {
139
158
  const entries = state_1?.runs;
140
159
  const entry_1 = entries?.[0];
141
160
  const failedEntries = failed.flatMap((failure) => {
142
- const command_4 = failedRunCommand(failure);
143
- return command_4 === void 0 ? [] : [{
144
- ...command_4.message,
161
+ const command_5 = failedRunCommand(failure);
162
+ return command_5 === void 0 ? [] : [{
163
+ ...command_5.message,
145
164
  sendFailure: failure.failure
146
165
  }];
147
166
  });
@@ -193,15 +212,22 @@ const useStatewireThread = (options) => {
193
212
  ]);
194
213
  const messages_0 = converted.messages;
195
214
  const liveRunId = runs.runId;
196
- const queue = useMemo(() => createRunQueueAdapter(messages_0, liveRunId, runs.queue, runs.steerQueue, dispatch, dispatchSend), [
197
- messages_0,
198
- liveRunId,
199
- runs,
215
+ const inputRequests = runs.inputRequests ?? NO_INPUT_REQUESTS;
216
+ const pass = {
217
+ messages: messages_0,
218
+ runId: liveRunId,
219
+ inputRequests,
220
+ dispatch
221
+ };
222
+ const live = useRef(pass);
223
+ live.current = pass;
224
+ const queue = useMemo(() => createRunQueueAdapter(() => live.current, runs.queue, runs.steerQueue, dispatch, dispatchSend), [
225
+ runs.queue,
226
+ runs.steerQueue,
200
227
  dispatch,
201
228
  dispatchSend
202
229
  ]);
203
230
  const branches = useMemo(() => createBranchCommandAdapter(messages_0, dispatch), [messages_0, dispatch]);
204
- const inputRequests = runs.inputRequests ?? NO_INPUT_REQUESTS;
205
231
  const extras = useMemo(() => {
206
232
  const takeFailed = (messageId) => {
207
233
  const entry_2 = failed.find((f) => failedRunCommand(f)?.message.id === messageId);
@@ -223,17 +249,19 @@ const useStatewireThread = (options) => {
223
249
  retryFailed: (messageId_0) => {
224
250
  if (retrying.current.has(messageId_0)) return;
225
251
  const entry_3 = takeFailed(messageId_0);
226
- const command_5 = retryCommand(messages_0, liveRunId, failedRunCommand(entry_3));
252
+ const command_6 = retryCommand(messages_0, liveRunId, failedRunCommand(entry_3));
253
+ const held_0 = heldByContext(command_6);
254
+ if (held_0 !== void 0) throw held_0;
227
255
  retrying.current.add(messageId_0);
228
256
  const release = () => {
229
257
  retrying.current.delete(messageId_0);
230
258
  };
231
259
  try {
232
260
  discardFailed(entry_3);
233
- dispatch(command_5).then(release, release);
234
- } catch (error_1) {
261
+ dispatch(command_6).then(release, release);
262
+ } catch (error_2) {
235
263
  release();
236
- throw error_1;
264
+ throw error_2;
237
265
  }
238
266
  },
239
267
  discardFailed: (messageId_1) => discardFailed(takeFailed(messageId_1)),
@@ -245,6 +273,7 @@ const useStatewireThread = (options) => {
245
273
  };
246
274
  }, [
247
275
  dispatch,
276
+ heldByContext,
248
277
  connection_0,
249
278
  documents,
250
279
  invoke,
@@ -268,9 +297,20 @@ const useStatewireThread = (options) => {
268
297
  const handleReload = (parentId) => {
269
298
  dispatch(resolveReloadCommand(messages_0, parentId, liveRunId));
270
299
  };
271
- const handleEdit = (message_1) => {
272
- dispatch(resolveEditCommand(messages_0, message_1, liveRunId));
273
- };
300
+ const [messageHandlers] = useState(() => ({
301
+ onEdit: (message_1) => {
302
+ const { messages: messages_1, runId: runId_0, dispatch: dispatch_0 } = live.current;
303
+ dispatch_0(resolveEditCommand(messages_1, message_1, runId_0));
304
+ },
305
+ onAddToolResult: (toolOptions) => {
306
+ const { inputRequests: inputRequests_0, runId: runId_1, dispatch: dispatch_1 } = live.current;
307
+ return dispatch_1(resolveToolResultInput(inputRequests_0, toolOptions, runId_1));
308
+ },
309
+ onRespondToToolApproval: async (approval) => {
310
+ const { inputRequests: inputRequests_1, runId: runId_2, dispatch: dispatch_2 } = live.current;
311
+ await dispatch_2(resolveToolApprovalInput(inputRequests_1, approval, runId_2));
312
+ }
313
+ }));
274
314
  const thread = useResource(ExternalThread({
275
315
  messages: messages_0,
276
316
  isRunning: status === "running",
@@ -281,25 +321,27 @@ const useStatewireThread = (options) => {
281
321
  feedbackAdapter: options.adapters?.feedback,
282
322
  onNew: handleAppend,
283
323
  queue,
284
- ...options.capabilities?.edit && { onEdit: handleEdit },
285
- ...options.capabilities?.continue && { onResume: () => dispatch({
286
- type: "run/continue",
287
- ...liveRunId !== null && { runId: liveRunId }
288
- }) },
324
+ ...options.capabilities?.edit && { onEdit: messageHandlers.onEdit },
325
+ ...options.capabilities?.continue && { onResume: async () => {
326
+ await dispatch({
327
+ type: "run/continue",
328
+ ...liveRunId !== null && { runId: liveRunId }
329
+ });
330
+ } },
289
331
  ...options.capabilities?.reload && { onReload: handleReload },
290
332
  ...options.capabilities?.unstable_switchBranch && { branches },
291
- onAddToolResult: (toolOptions) => dispatch(resolveToolResultInput(inputRequests, toolOptions, liveRunId)),
292
- onRespondToToolApproval: (approval) => dispatch(resolveToolApprovalInput(inputRequests, approval, liveRunId)),
333
+ onAddToolResult: messageHandlers.onAddToolResult,
334
+ onRespondToToolApproval: messageHandlers.onRespondToToolApproval,
293
335
  onCancel: () => {
294
336
  const payload = latest.current.stopPayload?.();
295
337
  if (payload !== void 0 && (typeof payload !== "object" || payload === null || Array.isArray(payload))) throw new Error("statewire: stopPayload must return a plain object");
296
- const runId_0 = runs.runId;
338
+ const runId_3 = runs.runId;
297
339
  commands["run/stop"]({
298
340
  ...payload,
299
- runId: runId_0,
341
+ runId: runId_3,
300
342
  ...runs.epoch !== void 0 && { epoch: runs.epoch }
301
- }).then((retracted_0) => popRetracted(retracted_0, runId_0)).catch((error_2) => {
302
- latest.current.onError?.(error_2);
343
+ }).then((retracted_0) => popRetracted(retracted_0, runId_3)).catch((error_3) => {
344
+ latest.current.onError?.(error_3);
303
345
  });
304
346
  }
305
347
  }));
@@ -318,8 +360,8 @@ const useStatewireThread = (options) => {
318
360
  name: attachment.name,
319
361
  ...attachment.contentType !== void 0 && { contentType: attachment.contentType },
320
362
  content: attachment.content
321
- }).catch((error_3) => {
322
- latest.current.onError?.(error_3);
363
+ }).catch((error_4) => {
364
+ latest.current.onError?.(error_4);
323
365
  });
324
366
  }, [composerStorage]);
325
367
  const { text: draftText, attachments: composerAttachments } = thread.getState().composer;
@@ -348,7 +390,6 @@ const useStatewireThread = (options) => {
348
390
  };
349
391
  const StatewireThread = (options) => resource(useStatewireThread)(options);
350
392
  forwardTransformScopes(useStatewireThread, ExternalThread(void 0).hook);
351
- //#endregion
352
393
  export { StatewireThread, asStatewireExtras, symbolStatewireExtras };
353
394
 
354
395
  //# sourceMappingURL=StatewireThread.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","useSyncExternalStore","resource","useResource","useResources","withKey","ResourceElement","ExternalThread","ExternalThreadMessage","Assistant","forwardTransformScopes","useAssistantClientRef","ClientOutput","AddToolResultOptions","AppendMessage","AttachmentAdapter","CompleteAttachment","FeedbackAdapter","ModelContext","RespondToToolApprovalOptions","SpeechSynthesisAdapter","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","DEFAULT_PROTOCOL","useStatewire","Statewire","StatewireClient","StatewireDocuments","createBranchCommandAdapter","createRunQueueAdapter","resolveEditCommand","retryCommand","resolveReloadCommand","sendFields","toWireMessage","resolveToolApprovalInput","resolveToolResultInput","runsOptimistic","AnyCommands","Record","args","NO_DOCUMENTS","ReadonlyMap","Document","Map","noopSubscribe","symbolStatewireExtras","Symbol","asStatewireExtras","extras","StatewireThread","Extras","Error","NO_INPUT_REQUESTS","InputRequestState","RESTING_RUNS","Runs","runId","queue","steerQueue","failed","failedRunCommand","entry","FailedCommand","RunEnqueueCommand","RunSteerCommand","RunEditCommand","message","UserMessage","command","undefined","params","ReturnType","presentStatus","status","ThreadStatus","connection","ConnectionState","reason","cause","code","ambientContextOf","context","system","tools","callSettings","config","useStatewireThread","options","Options","latest","current","retrying","Set","pending","setPending","Command","retire","prev","includes","filter","c","state","commands","documents","invoke","setContext","isBusy","discardFailed","transport","onError","error","storage","initialState","protocol","optimistic","draft","ctx","materialize","onCommandChange","update","onStateChange","onConnectionChange","failureCovered","messages","id","some","m","discarded","WeakSet","has","add","clientRef","contextRef","contextSync","contextProtocol","modelContext","parent","lastSent","send","value","getModelContext","key","JSON","stringify","subscribe","dispatch","settled","type","catch","threadRef","dispatchSend","sourceId","text","content","flatMap","part","join","setText","composer","next","popRetracted","retracted","Promise","Array","isArray","length","composerApi","getState","texts","item","RunsQueueEntry","messageId","push","parts","Boolean","runs","entries","RunState","failedEntries","failure","RunsFailedEntry","sendFailure","epoch","stopReason","dispatching","stopping","nextDispatch","inputRequests","converter","mounted","list","metadata","ConnectionMetadata","pendingCommands","isSending","converted","State","liveRunId","branches","takeFailed","find","f","sendCommand","reconnect","retryFailed","release","delete","then","popFailed","p","handleAppend","crypto","randomUUID","handleReload","parentId","handleEdit","thread","isRunning","attachmentAdapter","adapters","attachments","speechAdapter","speech","feedbackAdapter","feedback","onNew","capabilities","edit","onEdit","continue","onResume","reload","onReload","unstable_switchBranch","onAddToolResult","toolOptions","onRespondToToolApproval","approval","onCancel","payload","stopPayload","composerStorage","read","isEmpty","attachment","addAttachment","name","contentType","draftText","composerAttachments","draftAttachments","map","file","_file","record","draftSync","writingFor","isBaseline","clear","write","T","UserCommands","Commands","Transport","ComposerDraft","ComposerStorage","Source","method","TextPart","FilePart","mediaType","url","filename","role","Placement","insertAfter","insertBefore","RunSendCommand","TType","runAnchorMessageId","RunDequeueCommand","RunContinueCommand","ToolCallInputRequest","toolCallId","ToolApprovalInputRequest","CustomInputRequest","InputRequest","InputResponse","RunInputCommand","requestId","response","meta","BranchMetadata","siblings","SwitchBranchCommand","branchId","RunReloadCommand","RunCommand","RunQueueItem","RunStatus","SendFailure","RunsInputOutcome","request","RunsDispatch","trigger","rollbackTo","rootMeta","inputOutcomes","RunsStopping","RunsError","MaterializeEffects","append","rollback","to","RunsState","StateConverter","connectionMetadata","StopPayload","Optimistic","Materialize","NonNullable","CommandUpdate","changes","Changes","Connection","session","SessionStorage","runEnqueue","runSteer","runDequeue","runEdit","runContinue","runReload","runInput","messageSwitchBranch","hook"],"sources":["../src/StatewireThread.ts"],"sourcesContent":["import {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport {\n resource,\n useResource,\n useResources,\n withKey,\n} from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/core/store\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/core/store\";\nimport type { Assistant } from \"@assistant-ui/core\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n AttachmentAdapter,\n CompleteAttachment,\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 { DEFAULT_PROTOCOL, useStatewire } from \"statewire\";\nimport type { Statewire, StatewireClient, StatewireDocuments } from \"statewire\";\nimport {\n createBranchCommandAdapter,\n createRunQueueAdapter,\n resolveEditCommand,\n retryCommand,\n resolveReloadCommand,\n sendFields,\n toWireMessage,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\nimport { runsOptimistic } from \"./runsOptimistic\";\n\ntype AnyCommands = Record<string, (...args: any[]) => unknown>;\n\nconst NO_DOCUMENTS: ReadonlyMap<number, StatewireDocuments.Document> =\n new Map();\nconst noopSubscribe = () => () => {};\n\nexport const symbolStatewireExtras = Symbol(\"statewire-extras\");\n\nexport const asStatewireExtras = (extras: unknown): StatewireThread.Extras => {\n if (\n typeof extras !== \"object\" ||\n extras == null ||\n !(symbolStatewireExtras in extras)\n )\n throw new Error(\n \"This method can only be called when you are using StatewireThread\",\n );\n\n return extras as StatewireThread.Extras;\n};\n\nconst NO_INPUT_REQUESTS: readonly StatewireThread.InputRequestState[] = [];\n\nconst RESTING_RUNS: StatewireThread.Runs = {\n runId: null,\n queue: [],\n steerQueue: [],\n failed: [],\n};\n\n/** The failed run sends the thread can project: enqueue/steer/edit invocations carrying a message. */\nconst failedRunCommand = (\n entry: StatewireClient.FailedCommand,\n):\n | ((\n | StatewireThread.RunEnqueueCommand\n | StatewireThread.RunSteerCommand\n | StatewireThread.RunEditCommand\n ) & { message: StatewireThread.UserMessage })\n | undefined => {\n if (\n entry.command !== \"run/enqueue\" &&\n entry.command !== \"run/steer\" &&\n entry.command !== \"run/edit\"\n )\n return undefined;\n const command = entry.params[0] as\n | { message?: StatewireThread.UserMessage }\n | undefined;\n if (command?.message === undefined) return undefined;\n return command as ReturnType<typeof failedRunCommand>;\n};\n\n// Derived presentation while the connection can't vouch for progress:\n// live-claiming \"running\" reads as evicted/disconnected; facts pass through.\nconst presentStatus = (\n status: StatewireThread.ThreadStatus,\n connection: StatewireClient.ConnectionState,\n): StatewireThread.ThreadStatus =>\n status !== \"running\" ||\n connection.status === \"connected\" ||\n (connection.status === \"standby\" && connection.reason === \"idle\")\n ? status\n : connection.status === \"retrying\" &&\n connection.cause === \"reconnect\" &&\n connection.code === \"evicted\"\n ? \"evicted\"\n : \"disconnected\";\n\nconst ambientContextOf = (context: ModelContext): Record<string, unknown> => ({\n ...(context.system !== undefined && { system: context.system }),\n ...(context.tools !== undefined && {\n tools: toToolsJSONSchema(context.tools),\n }),\n ...(context.callSettings !== undefined && {\n callSettings: context.callSettings,\n }),\n ...(context.config !== undefined && { config: context.config }),\n});\n\nconst useStatewireThread = (\n options: StatewireThread.Options<any>,\n): ClientOutput<\"thread\"> => {\n const latest = useRef(options);\n latest.current = options;\n const retrying = useRef(new Set<string>());\n\n const [pending, setPending] = useState<readonly StatewireThread.Command[]>(\n [],\n );\n const [retire] = useState(\n () => (command: unknown) =>\n setPending((prev) =>\n prev.includes(command as StatewireThread.Command)\n ? prev.filter((c) => c !== command)\n : prev,\n ),\n );\n\n const {\n state,\n commands,\n connection,\n documents,\n invoke,\n setContext,\n isBusy,\n failed,\n discardFailed,\n } = useStatewire<unknown, AnyCommands>({\n transport: options.transport,\n onError: (error) => latest.current.onError?.(error),\n storage: options.storage,\n initialState: options.initialState,\n ...(options.protocol !== undefined && { protocol: options.protocol }),\n optimistic: (draft, command, ctx) => {\n runsOptimistic(draft, command, ctx);\n latest.current.optimistic?.(draft, command, ctx);\n },\n materialize: (draft: {}) => latest.current.materialize?.(draft),\n onCommandChange: (update, ctx) => {\n if (update.status === \"applied\" || update.status === \"settled\")\n retire(update.params[0]);\n latest.current.onCommandChange?.(update, ctx);\n },\n onStateChange: (state, ctx) => latest.current.onStateChange?.(state, ctx),\n onConnectionChange: (connection) =>\n latest.current.onConnectionChange?.(connection),\n failureCovered: (state, entry) => {\n const command = failedRunCommand(entry);\n if (command === undefined) return false;\n const messages = (state as { messages?: readonly { id: string }[] })\n .messages;\n return messages?.some((m) => m.id === command.message.id) ?? false;\n },\n });\n\n const discarded = useRef(new WeakSet<StatewireClient.FailedCommand>());\n // Effects can replay before the updated failed lane reaches the binding.\n useEffect(() => {\n for (const entry of failed) {\n if (\n failedRunCommand(entry) === undefined &&\n !discarded.current.has(entry)\n ) {\n discarded.current.add(entry);\n discardFailed(entry);\n }\n }\n }, [failed, discardFailed]);\n\n const clientRef = useAssistantClientRef();\n const contextRef = useRef(setContext);\n contextRef.current = setContext;\n const { contextSync } = options;\n const contextProtocol = options.protocol ?? DEFAULT_PROTOCOL;\n useEffect(() => {\n if (contextSync === undefined) return;\n const modelContext = (clientRef.current ?? clientRef.parent).modelContext();\n let lastSent: string | undefined;\n const send = () => {\n const value = ambientContextOf(modelContext.getModelContext());\n const key = JSON.stringify(value);\n if (key === lastSent) return;\n contextRef.current(contextProtocol, value);\n lastSent = key;\n };\n if (!modelContext.subscribe)\n throw new Error(\n \"statewire: contextSync requires a subscribable model context\",\n );\n send();\n return modelContext.subscribe(send);\n }, [contextSync, contextProtocol, clientRef]);\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 // The stop verdict carries the run's retracted items; the stopping client\n // dequeues them into an empty composer. Other clients see them queued.\n const popRetracted = async (\n retracted: unknown,\n runId: string | null,\n ): Promise<void> => {\n if (!Array.isArray(retracted) || retracted.length === 0 || runId === null)\n return;\n const composerApi = threadRef.current!.composer();\n if (composerApi.getState().text !== \"\") return;\n const texts: string[] = [];\n for (const item of retracted as StatewireThread.RunsQueueEntry[]) {\n try {\n await dispatch({ type: \"run/dequeue\", runId, messageId: item.id });\n } catch {\n continue; // rejected dequeue: the item stays queued\n }\n texts.push(\n item.parts\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\"),\n );\n }\n if (texts.length === 0) return;\n const setText = composerApi.setText as (\n next: string | ((prev: string) => string),\n ) => void;\n setText((prev) => [prev, ...texts].filter(Boolean).join(\"\\n\\n\"));\n };\n\n const { status, runs } = useMemo((): {\n status: StatewireThread.ThreadStatus;\n runs: StatewireThread.Runs;\n } => {\n const entries = (\n state as { runs?: readonly StatewireThread.RunState[] } | undefined\n )?.runs;\n const entry = entries?.[0];\n const failedEntries = failed.flatMap(\n (failure): StatewireThread.RunsFailedEntry[] => {\n const command = failedRunCommand(failure);\n return command === undefined\n ? []\n : [{ ...command.message, sendFailure: failure.failure }];\n },\n );\n return {\n status: presentStatus(\n entries === undefined ? \"loading\" : (entry?.status ?? \"ready\"),\n connection,\n ),\n runs:\n entry === undefined && failedEntries.length === 0\n ? RESTING_RUNS\n : {\n ...(entry === undefined\n ? RESTING_RUNS\n : {\n runId: entry.runId,\n ...(entry.epoch !== undefined && { epoch: entry.epoch }),\n ...(entry.stopReason !== undefined && {\n stopReason: entry.stopReason,\n }),\n queue: entry.queue,\n steerQueue: entry.steerQueue,\n ...(entry.dispatching !== undefined && {\n dispatching: entry.dispatching,\n }),\n ...(entry.stopping !== undefined && {\n stopping: entry.stopping,\n }),\n ...(entry.nextDispatch !== undefined && {\n nextDispatch: entry.nextDispatch,\n }),\n ...(entry.inputRequests !== undefined && {\n inputRequests: entry.inputRequests,\n }),\n ...(entry.error !== undefined && { error: entry.error }),\n }),\n failed: failedEntries,\n },\n };\n }, [state, connection, failed]);\n\n const { converter } = options;\n const mounted = useSyncExternalStore(\n documents?.subscribe ?? noopSubscribe,\n () => documents?.list() ?? NO_DOCUMENTS,\n () => documents?.list() ?? NO_DOCUMENTS,\n );\n const metadata = useMemo(\n (): StatewireThread.ConnectionMetadata => ({\n pendingCommands: [...pending],\n isSending: pending.length > 0,\n connection,\n runs,\n documents,\n mounted,\n invoke,\n }),\n [pending, connection, runs, documents, mounted, invoke],\n );\n const converted = useMemo(\n (): StatewireThread.State => converter(state, metadata),\n [converter, state, metadata],\n );\n // Dispatch limbo is a materialize concern: the fold makes the record\n // concrete in state before conversion.\n const messages = converted.messages;\n const liveRunId = runs.runId;\n\n const queue = useMemo(\n () =>\n createRunQueueAdapter(\n messages,\n liveRunId,\n runs.queue,\n runs.steerQueue,\n dispatch,\n dispatchSend,\n ),\n [messages, liveRunId, runs, dispatch, dispatchSend],\n );\n\n const branches = useMemo(\n () => createBranchCommandAdapter(messages, dispatch),\n [messages, dispatch],\n );\n\n const inputRequests = runs.inputRequests ?? NO_INPUT_REQUESTS;\n\n const extras = useMemo((): StatewireThread.Extras => {\n const takeFailed = (messageId: string): StatewireClient.FailedCommand => {\n const entry = failed.find(\n (f) => failedRunCommand(f)?.message.id === messageId,\n );\n if (entry === undefined)\n throw new Error(`statewire: unknown failed entry \"${messageId}\"`);\n return entry;\n };\n return {\n [symbolStatewireExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n connection,\n documents,\n invoke,\n state: converted.state === undefined ? state : converted.state,\n status,\n isBusy,\n inputRequests,\n runs,\n retryFailed: (messageId) => {\n if (retrying.current.has(messageId)) return;\n const entry = takeFailed(messageId);\n const command = retryCommand(\n messages,\n liveRunId,\n failedRunCommand(entry)!,\n );\n retrying.current.add(messageId);\n const release = () => {\n retrying.current.delete(messageId);\n };\n try {\n discardFailed(entry);\n void dispatch(command).then(release, release);\n } catch (error) {\n release();\n throw error;\n }\n },\n discardFailed: (messageId) => discardFailed(takeFailed(messageId)),\n popFailed: (messageId) => {\n const entry = takeFailed(messageId);\n discardFailed(entry);\n return failedRunCommand(entry)!\n .message.parts.flatMap((p) => (p.type === \"text\" ? [p.text] : []))\n .join(\"\\n\\n\");\n },\n };\n }, [\n dispatch,\n connection,\n documents,\n invoke,\n state,\n converted.state,\n status,\n isBusy,\n inputRequests,\n runs,\n failed,\n discardFailed,\n messages,\n liveRunId,\n ]);\n\n const handleAppend = (message: AppendMessage) => {\n dispatchSend(\n message.sourceId != null\n ? resolveEditCommand(messages, message, liveRunId)\n : {\n type: \"run/steer\",\n ...sendFields(\n messages,\n liveRunId,\n toWireMessage(message, crypto.randomUUID()),\n ),\n },\n message,\n );\n };\n\n const handleReload = (parentId: string | null) => {\n dispatch(resolveReloadCommand(messages, parentId, liveRunId));\n };\n\n const handleEdit = (message: AppendMessage) => {\n dispatch(resolveEditCommand(messages, message, liveRunId));\n };\n\n const thread = useResource(\n ExternalThread({\n messages: messages as readonly ExternalThreadMessage[],\n isRunning: status === \"running\",\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n speechAdapter: options.adapters?.speech,\n feedbackAdapter: options.adapters?.feedback,\n onNew: handleAppend,\n queue,\n ...(options.capabilities?.edit && { onEdit: handleEdit }),\n ...(options.capabilities?.continue && {\n onResume: () =>\n dispatch({\n type: \"run/continue\",\n ...(liveRunId !== null && { runId: liveRunId }),\n }),\n }),\n ...(options.capabilities?.reload && { onReload: handleReload }),\n ...(options.capabilities?.unstable_switchBranch && { branches }),\n onAddToolResult: (toolOptions: AddToolResultOptions) =>\n dispatch(resolveToolResultInput(inputRequests, toolOptions, liveRunId)),\n onRespondToToolApproval: (approval: RespondToToolApprovalOptions) =>\n dispatch(resolveToolApprovalInput(inputRequests, approval, liveRunId)),\n onCancel: () => {\n const payload = latest.current.stopPayload?.();\n if (\n payload !== undefined &&\n (typeof payload !== \"object\" ||\n payload === null ||\n Array.isArray(payload))\n )\n throw new Error(\"statewire: stopPayload must return a plain object\");\n const runId = runs.runId;\n void commands[\"run/stop\"]!({\n ...payload,\n runId,\n ...(runs.epoch !== undefined && { epoch: runs.epoch }),\n })\n .then((retracted) => popRetracted(retracted, runId))\n .catch((error: Error) => {\n latest.current.onError?.(error);\n });\n },\n }),\n );\n threadRef.current = thread;\n\n const composerStorage = useResources(\n options.storage?.composer !== undefined\n ? [withKey(\"composer\", options.storage.composer)]\n : [],\n )[0];\n\n useEffect(() => {\n const storage = composerStorage;\n if (storage === undefined) return;\n const composer = threadRef.current!.composer();\n const draft = storage.read();\n if (draft === undefined || !composer.getState().isEmpty) return;\n composer.setText(draft.text);\n for (const attachment of draft.attachments) {\n composer\n .addAttachment({\n id: attachment.id,\n type: attachment.type,\n name: attachment.name,\n ...(attachment.contentType !== undefined && {\n contentType: attachment.contentType,\n }),\n content: attachment.content,\n })\n .catch((error: Error) => {\n latest.current.onError?.(error);\n });\n }\n }, [composerStorage]);\n\n const { text: draftText, attachments: composerAttachments } =\n thread.getState().composer;\n const draftAttachments = useMemo(\n () =>\n composerAttachments\n .filter(\n (attachment): attachment is CompleteAttachment =>\n attachment.status.type === \"complete\",\n )\n .map(({ file: _file, ...record }) => record),\n [composerAttachments],\n );\n const [draftSync] = useState(() => ({ writingFor: undefined as unknown }));\n useEffect(() => {\n const storage = composerStorage;\n if (storage === undefined) return;\n // First run per storage is the baseline, not a change: never clear the\n // stored draft the restore effect is about to load.\n const isBaseline = draftSync.writingFor !== storage;\n draftSync.writingFor = storage;\n if (draftText === \"\" && draftAttachments.length === 0) {\n if (!isBaseline) storage.clear();\n return;\n }\n storage.write({ text: draftText, attachments: draftAttachments });\n }, [draftSync, composerStorage, draftText, draftAttachments]);\n\n return thread;\n};\n\nexport const StatewireThread = <T>(\n options: StatewireThread.Options<T>,\n): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useStatewireThread)(options as StatewireThread.Options<any>);\n\nexport namespace StatewireThread {\n type UserCommands = Assistant.Commands[keyof Assistant.Commands];\n\n export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;\n\n /** A composer draft as persisted: the text plus the completed attachments. */\n export type ComposerDraft = {\n readonly text: string;\n readonly attachments: readonly CompleteAttachment[];\n };\n\n /** Composer draft storage seam; `write` must persist synchronously in the caller's flow. */\n export type ComposerStorage = {\n read(): ComposerDraft | undefined;\n write(draft: ComposerDraft): void;\n clear(): void;\n };\n\n export type Extras = {\n [symbolStatewireExtras]: true;\n /** Dispatches the command; the promise settles with the accepted command's result payload, rejecting with `StatewireSendError` otherwise. */\n sendCommand: (command: Command) => Promise<unknown>;\n reconnect: () => void;\n connection: StatewireClient.ConnectionState;\n /** The mounted documents, or `undefined` on a transport without documents. */\n documents: StatewireDocuments.Source | undefined;\n /** Sends a statement on a negotiated protocol lane. */\n invoke: (\n protocol: string,\n method: string,\n params: readonly unknown[],\n ) => Promise<unknown>;\n /** The converter's `state` when it returns one, else the replicated state. */\n state: unknown;\n status: ThreadStatus;\n /** Negation of the server's broadcast idle level (a transport without idle is always busy). */\n isBusy: boolean;\n inputRequests: readonly InputRequestState[];\n runs: Runs;\n /** Re-dispatches the failed entry against the current thread and removes it; keyed by the entry's message id. */\n retryFailed: (messageId: string) => void;\n /** Removes the failed entry; keyed by the entry's message id. */\n discardFailed: (messageId: string) => void;\n /** Removes the failed entry and returns its text for the composer; keyed by the entry's message id. */\n popFailed: (messageId: string) => string;\n };\n\n export type TextPart = {\n readonly type: \"text\";\n readonly text: string;\n };\n\n export type FilePart = {\n readonly type: \"file\";\n readonly mediaType: string;\n readonly url: string;\n readonly filename?: string;\n };\n\n export type UserMessage = {\n readonly id: string;\n readonly role: \"user\";\n readonly parts: readonly (TextPart | FilePart)[];\n readonly metadata?: Record<string, unknown>;\n };\n\n /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */\n export type Placement = {\n readonly insertAfter?: string | null;\n readonly insertBefore?: string | null;\n };\n\n type RunSendCommand<TType extends \"run/enqueue\" | \"run/steer\"> = {\n readonly type: TType;\n /** The run this command targets — the live run's id, or a fresh client-minted uuid on run-creating sends. */\n readonly runId: string;\n } & (\n | {\n readonly message: UserMessage;\n /** Run anchor: the message the new content grows after, null asserting an empty thread. Present on run-creating sends; absent when targeting the live run. */\n readonly runAnchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunEnqueueCommand = RunSendCommand<\"run/enqueue\">;\n\n export type RunSteerCommand = RunSendCommand<\"run/steer\">;\n\n export type RunDequeueCommand = {\n readonly type: \"run/dequeue\";\n readonly runId: string;\n readonly messageId: string;\n };\n\n export type RunEditCommand = {\n readonly type: \"run/edit\";\n /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */\n readonly runId: string;\n readonly message: UserMessage;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly runAnchorMessageId: string | null;\n };\n\n export type RunContinueCommand = {\n readonly type: \"run/continue\";\n readonly runId?: string;\n };\n\n export type ToolCallInputRequest = {\n readonly type: \"tool-call\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type ToolApprovalInputRequest = {\n readonly type: \"tool-approval\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type CustomInputRequest = {\n readonly type: string;\n readonly id: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A host request parking the run until answered; open union for custom types. */\n export type InputRequest =\n | ToolCallInputRequest\n | ToolApprovalInputRequest\n | CustomInputRequest;\n\n export type InputResponse = ReadonlyJSONValue;\n\n export type RunInputCommand = {\n readonly type: \"run/input\";\n readonly runId?: string;\n readonly requestId: string;\n readonly response: InputResponse;\n };\n\n /** An input request projected out of the host state; a present `response` key marks the entry answered. */\n export type InputRequestState = InputRequest & {\n readonly response?: InputResponse;\n /** The answer's `run/input` meta; absent when the answer carried none. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n /** Per-message branch metadata read from `metadata.custom.branch`: the message's own branch id and the fan-out's branch ids in creation order (own id included). */\n export type BranchMetadata = {\n readonly id: number;\n readonly siblings: readonly number[];\n };\n\n export type SwitchBranchCommand = {\n readonly type: \"message/switch-branch\";\n readonly branchId: number;\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 readonly metadata?: Record<string, unknown>;\n };\n\n /** Run subsystem status replicated by the host. */\n export type RunStatus = \"running\" | \"stopped\" | \"error\" | \"input-required\";\n\n /** The thread's status: `\"loading\"` while the runs mount is absent, `\"ready\"` while resting, otherwise the run's status; `\"evicted\"` and `\"disconnected\"` are client-derived from the connection, never replicated. */\n export type ThreadStatus =\n | \"loading\"\n | \"ready\"\n | \"evicted\"\n | \"disconnected\"\n | RunStatus;\n\n /** A queue-lane entry as replicated: the user message plus host-stamped `meta`. */\n export type RunsQueueEntry = UserMessage & {\n /** Host-stamped opaque per-entry metadata. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n /** A failed run send projected out of the retained lane: the entry shape plus its send failure. */\n export type RunsFailedEntry = RunsQueueEntry & {\n readonly sendFailure: StatewireClient.SendFailure;\n };\n\n /** An input outcome riding a dispatch record: the request with its response (null = abandoned) and `run/input` meta. */\n export type RunsInputOutcome = {\n readonly request: InputRequest;\n readonly response: InputResponse | null;\n readonly meta: ReadonlyJSONValue | null;\n };\n\n /** The dispatch record — the unapplied batch handed to the run; absent between applied and the next dispatch or take. */\n export type RunsDispatch = {\n readonly trigger:\n | \"message-send\"\n | \"message-edit\"\n | \"message-reload\"\n | \"input-resume\"\n | \"error-continue\"\n | \"stop-continue\"\n | \"steer\";\n readonly messages: readonly RunsQueueEntry[];\n /** Present on rewind dispatches: truncate the thread at this id first; null names the root. */\n readonly rollbackTo?: string | null;\n /** The run-starting op's meta; present only when carried. */\n readonly rootMeta?: ReadonlyJSONValue;\n /** Present when input outcomes ride the dispatch; visible until applied. */\n readonly inputOutcomes?: readonly RunsInputOutcome[];\n };\n\n /** The stopping window: present while a stop of the live run is underway; `\"message-edit\"` / `\"message-reload\"` pair with `nextDispatch`. */\n export type RunsStopping = {\n readonly reason: \"stop\" | \"message-edit\" | \"message-reload\";\n };\n\n /** The replicated run error — set on an unhandled failure, cleared by the next user-initiated run. */\n export type RunsError = {\n readonly message: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A replicated run entry — one element of the mount's `runs` array. */\n export type RunState = {\n /** The run's identity — client-minted, adopted by the host at run creation; persists through steers, input-required, and error/stop, retiring only when the queue drains and the run completes. */\n readonly runId: string | null;\n /** Counts the entry's dispatches; a `run/stop` carrying a stale epoch rejects. */\n readonly epoch?: number;\n /** The reason carried by `run/stop`; persists through error/stop, cleared at the next dispatch. */\n readonly stopReason?: string | null;\n readonly status: RunStatus;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */\n readonly dispatching?: RunsDispatch;\n readonly stopping?: RunsStopping;\n /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */\n readonly nextDispatch?: RunsDispatch;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n /** Set only by an unhandled throw; cleared by the next user-initiated run. */\n readonly error?: RunsError;\n };\n\n /** App-shaped effects `runsMaterialize` applies for the dispatch record. */\n export type MaterializeEffects = {\n /** Append one dispatched message to the app's committed message state. */\n append: (message: RunsQueueEntry) => void;\n /** Truncate to the rolled-back view first (null names the root); required for hosts that dispatch edits/reloads. */\n rollback?: (to: string | null) => void;\n };\n\n /** The runs mount as replicated: the run entries plus the top-level status projection. */\n export type RunsState = {\n /** Projection of `runs[0]?.status ?? \"ready\"`. */\n readonly status: \"ready\" | 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 state with unsettled commands folded in, resting defaults while no entry is live. */\n export type Runs = {\n /** The live run's id — non-null whenever a run entry is live (running, input-required, error/stop); the target for `run/*` sends. */\n readonly runId: string | null;\n /** Counts the entry's dispatches; rides `run/stop` so a replayed stop cannot end a later leg. */\n readonly epoch?: number;\n /** The reason carried by `run/stop`; persists through error/stop, cleared at the next dispatch. */\n readonly stopReason?: string | null;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */\n readonly dispatching?: RunsDispatch;\n readonly stopping?: RunsStopping;\n /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */\n readonly nextDispatch?: RunsDispatch;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n /** Set only by an unhandled throw; cleared by the next user-initiated run. */\n readonly error?: RunsError;\n /** Run sends retained after a non-accepted settle; retry, discard, or pop via the thread extras. */\n readonly failed: readonly RunsFailedEntry[];\n };\n\n export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `connected`. */\n connection: StatewireClient.ConnectionState;\n /** The typed runs read. */\n runs: Runs;\n documents: StatewireDocuments.Source | undefined;\n /** The mounted documents as of this pass; a new map whenever one changes. */\n mounted: ReadonlyMap<number, StatewireDocuments.Document>;\n invoke: (\n protocol: string,\n method: string,\n params: readonly unknown[],\n ) => Promise<unknown>;\n };\n\n /** Converter output: app-owned keys only — the lib projects the run mounts itself; `state` replaces the replicated state on the extras and thread. */\n export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n /**\n * Payload of the built-in `run/stop` command. `reason` is the one well-known\n * field; apps extend it with their own JSON-serializable fields.\n */\n export type StopPayload = {\n readonly reason?: string | undefined;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n export type Options<T> = {\n transport: Transport<T>;\n /** The pre-attach state, replaced by the attach snapshot. `runs: []` projects ready (interactive from the first render); an absent runs mount projects loading until attach. */\n initialState: T;\n /** Application protocol for optimistic commands; must match the transport's protocol. */\n protocol?: string | undefined;\n converter: StateConverter<T>;\n /** Folds app-owned keys for an unsettled command into the draft; runs after the lib's run-dialect reducer. */\n optimistic?:\n | StatewireClient.Optimistic<\n T,\n Record<string, (...args: any[]) => unknown>\n >\n | undefined;\n /** Makes dispatch records concrete in the draft (runs after the optimistic folds); without it, dispatch limbo stays out of `messages`. */\n materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;\n /**\n * \"command-send\" mirrors the client's ambient model context (system,\n * tools, callSettings, config) to native protocol context, restored on\n * each attachment and updated whenever it changes.\n */\n contextSync?: \"command-send\" | undefined;\n /** Supplies the `run/stop` command's payload; omitted, stop sends no payload. */\n stopPayload?: (() => StopPayload) | undefined;\n /** Observes each command's lifecycle (queued, posted, applied, settled); runs after the built-in pending-command retirement. */\n onCommandChange?:\n | ((\n update: Statewire.CommandUpdate<\n Record<string, (...args: any[]) => unknown>\n >,\n ctx: { state: NonNullable<T> },\n ) => void)\n | undefined;\n /** Observes the transport state: fires with the attach snapshot, then once per change. */\n onStateChange?:\n | ((state: NonNullable<T>, ctx: { changes: Statewire.Changes }) => void)\n | undefined;\n /** Observes connection status transitions, starting with the initial status. */\n onConnectionChange?:\n | ((connection: StatewireClient.Connection) => void)\n | undefined;\n onError?: ((error: Error) => void) | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n /** The host supports `run/continue` (a continue affordance on aborted runs). */\n continue?: boolean | undefined;\n /** The host supports `run/reload` (regenerating an assistant message). */\n reload?: boolean | undefined;\n /** The host supports `message/switch-branch` (thread-global branch switching driven by `metadata.custom.branch`). */\n unstable_switchBranch?: boolean | undefined;\n }\n | undefined;\n /**\n * Durable drafts: the mounted composer storage restores on mount, mirrors\n * every change, and clears when the draft is consumed. The session storage\n * holds this thread's lane identity and its un-durable commands, which\n * resend under their original seqs on the next mount.\n */\n storage?:\n | {\n composer?: ResourceElement<ComposerStorage> | undefined;\n session?: ResourceElement<StatewireClient.SessionStorage> | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n speech?: SpeechSynthesisAdapter | undefined;\n feedback?: FeedbackAdapter | undefined;\n }\n | undefined;\n };\n}\n\ndeclare module \"@assistant-ui/core\" {\n namespace Assistant {\n interface Commands {\n runEnqueue: StatewireThread.RunEnqueueCommand;\n runSteer: StatewireThread.RunSteerCommand;\n runDequeue: StatewireThread.RunDequeueCommand;\n runEdit: StatewireThread.RunEditCommand;\n runContinue: StatewireThread.RunContinueCommand;\n runReload: StatewireThread.RunReloadCommand;\n runInput: StatewireThread.RunInputCommand;\n messageSwitchBranch: StatewireThread.SwitchBranchCommand;\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":";;;;;;;;;;AAuDA,MAAM8C,+BACJ,IAAIG,IAAI;AACV,MAAMC,4BAA4B,CAAC;AAEnC,MAAaC,wBAAwBC,OAAO,kBAAkB;AAE9D,MAAaC,qBAAqBC,WAA4C;CAC5E,IACE,OAAOA,WAAW,YAClBA,UAAU,QACV,EAAEH,yBAAyBG,SAE3B,MAAM,IAAIG,MACR,mEACF;CAEF,OAAOH;AACT;AAEA,MAAMI,oBAAkE,CAAA;AAExE,MAAME,eAAqC;CACzCE,OAAO;CACPC,OAAO,CAAA;CACPC,YAAY,CAAA;CACZC,QAAQ,CAAA;AACV;;AAGA,MAAMC,oBACJC,UAOe;CACf,IACEA,MAAMO,YAAY,iBAClBP,MAAMO,YAAY,eAClBP,MAAMO,YAAY,YAElB,OAAOC,KAAAA;CACT,MAAMD,UAAUP,MAAMS,OAAO;CAG7B,IAAIF,SAASF,YAA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BAAgBlL,KAAAA,KAAa,EAC1CkL,aAAaH,WAAWG,YAC1B;GACA9F,SAAS2F,WAAW3F;EACtB,CAAC,CAAC,CACDL,OAAOtC,YAAiB;GACvBrB,OAAOC,QAAQmB,UAAUC,OAAK;EAChC,CAAC;CAEP,GAAG,CAACmI,eAAe,CAAC;CAEpB,MAAM,EAAEzF,MAAMgG,WAAW5B,aAAa6B,wBACpCjC,OAAOjD,SAAS,CAAC,CAACT;CACpB,MAAM4F,mBAAmB9P,cAErB6P,oBACGtJ,QACEiJ,iBACCA,aAAW3K,OAAO0E,SAAS,UAC/B,CAAC,CACAwG,KAAK,EAAEC,MAAMC,OAAO,GAAGC,aAAaA,MAAM,GAC/C,CAACL,mBAAmB,CACtB;CACA,MAAM,CAACM,aAAajQ,gBAAgB,EAAEkQ,YAAY3L,KAAAA,EAAqB,EAAE;CACzE1E,gBAAgB;EACd,MAAMoH,YAAUkI;EAChB,IAAIlI,cAAY1C,KAAAA,GAAW;EAG3B,MAAM4L,aAAaF,UAAUC,eAAejJ;EAC5CgJ,UAAUC,aAAajJ;EACvB,IAAIyI,cAAc,MAAME,iBAAiBrF,WAAW,GAAG;GACrD,IAAI,CAAC4F,YAAYlJ,UAAQmJ,MAAM;GAC/B;EACF;EACAnJ,UAAQoJ,MAAM;GAAE3G,MAAMgG;GAAW5B,aAAa8B;EAAiB,CAAC;CAClE,GAAG;EAACK;EAAWd;EAAiBO;EAAWE;CAAgB,CAAC;CAE5D,OAAOlC;AACT;AAEA,MAAavK,mBACXsC,YAEAvF,SAASsF,kBAAkB,CAAC,CAACC,OAAuC;AAubtE/E,uBACE8E,oBACAjF,eAAegE,KAAAA,CAAkB,CAAC,CAAC0Q,IACrC"}
1
+ {"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","useSyncExternalStore","resource","useResource","useResources","withKey","ResourceElement","ExternalThread","ExternalThreadMessage","Assistant","forwardTransformScopes","useAssistantClientRef","ClientOutput","AddToolResultOptions","AppendMessage","AttachmentAdapter","CompleteAttachment","FeedbackAdapter","ModelContext","RespondToToolApprovalOptions","SpeechSynthesisAdapter","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","DEFAULT_PROTOCOL","useStatewire","Statewire","StatewireClient","StatewireDocuments","createBranchCommandAdapter","createRunQueueAdapter","resolveEditCommand","retryCommand","resolveReloadCommand","sendFields","toWireMessage","resolveToolApprovalInput","resolveToolResultInput","runsOptimistic","AnyCommands","Record","args","NO_DOCUMENTS","ReadonlyMap","Document","Map","noopSubscribe","symbolStatewireExtras","Symbol","asStatewireExtras","extras","StatewireThread","Extras","Error","NO_INPUT_REQUESTS","InputRequestState","RESTING_RUNS","Runs","runId","queue","steerQueue","failed","failedRunCommand","entry","FailedCommand","RunEnqueueCommand","RunSteerCommand","RunEditCommand","message","UserMessage","command","undefined","params","ReturnType","presentStatus","status","ThreadStatus","connection","ConnectionState","reason","cause","code","ambientContextOf","context","system","tools","callSettings","config","useStatewireThread","options","Options","latest","current","retrying","Set","pending","setPending","Command","retire","prev","includes","filter","c","state","commands","documents","invoke","setContext","isBusy","discardFailed","transport","onError","error","storage","initialState","protocol","optimistic","draft","ctx","materialize","onCommandChange","update","onStateChange","onConnectionChange","failureCovered","messages","id","some","m","discarded","WeakSet","has","add","clientRef","contextRef","contextFailure","contextSync","contextProtocol","modelContext","parent","lastSent","send","value","getModelContext","key","JSON","stringify","subscribe","heldByContext","type","dispatch","held","Promise","reject","settled","catch","threadRef","dispatchSend","sourceId","text","content","flatMap","part","join","setText","composer","next","popRetracted","retracted","Array","isArray","length","composerApi","getState","texts","item","RunsQueueEntry","messageId","push","parts","Boolean","runs","entries","RunState","failedEntries","failure","RunsFailedEntry","sendFailure","epoch","stopReason","dispatching","stopping","nextDispatch","inputRequests","converter","mounted","list","metadata","ConnectionMetadata","pendingCommands","isSending","converted","State","liveRunId","pass","live","branches","takeFailed","find","f","sendCommand","reconnect","retryFailed","release","delete","then","popFailed","p","handleAppend","crypto","randomUUID","handleReload","parentId","messageHandlers","onEdit","onAddToolResult","toolOptions","onRespondToToolApproval","approval","thread","isRunning","attachmentAdapter","adapters","attachments","speechAdapter","speech","feedbackAdapter","feedback","onNew","capabilities","edit","continue","onResume","reload","onReload","unstable_switchBranch","onCancel","payload","stopPayload","composerStorage","read","isEmpty","attachment","addAttachment","name","contentType","draftText","composerAttachments","draftAttachments","map","file","_file","record","draftSync","writingFor","isBaseline","clear","write","T","UserCommands","Commands","Transport","ComposerDraft","ComposerStorage","Source","method","TextPart","FilePart","mediaType","url","filename","role","Placement","insertAfter","insertBefore","RunSendCommand","TType","runAnchorMessageId","RunDequeueCommand","RunContinueCommand","ToolCallInputRequest","toolCallId","ToolApprovalInputRequest","CustomInputRequest","InputRequest","InputResponse","RunInputCommand","requestId","response","meta","BranchMetadata","siblings","SwitchBranchCommand","branchId","RunReloadCommand","RunCommand","RunQueueItem","RunStatus","SendFailure","RunsInputOutcome","request","RunsDispatch","trigger","rollbackTo","rootMeta","inputOutcomes","RunsStopping","RunsError","MaterializeEffects","append","rollback","to","RunsState","StateConverter","connectionMetadata","StopPayload","Optimistic","Materialize","NonNullable","CommandUpdate","changes","Changes","Connection","session","SessionStorage","runEnqueue","runSteer","runDequeue","runEdit","runContinue","runReload","runInput","messageSwitchBranch","hook"],"sources":["../src/StatewireThread.ts"],"sourcesContent":["import {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport {\n resource,\n useResource,\n useResources,\n withKey,\n} from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/core/store\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/core/store\";\nimport type { Assistant } from \"@assistant-ui/core\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n AttachmentAdapter,\n CompleteAttachment,\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 { DEFAULT_PROTOCOL, useStatewire } from \"statewire\";\nimport type { Statewire, StatewireClient, StatewireDocuments } from \"statewire\";\nimport {\n createBranchCommandAdapter,\n createRunQueueAdapter,\n resolveEditCommand,\n retryCommand,\n resolveReloadCommand,\n sendFields,\n toWireMessage,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\nimport { runsOptimistic } from \"./runsOptimistic\";\n\ntype AnyCommands = Record<string, (...args: any[]) => unknown>;\n\nconst NO_DOCUMENTS: ReadonlyMap<number, StatewireDocuments.Document> =\n new Map();\nconst noopSubscribe = () => () => {};\n\nexport const symbolStatewireExtras = Symbol(\"statewire-extras\");\n\nexport const asStatewireExtras = (extras: unknown): StatewireThread.Extras => {\n if (\n typeof extras !== \"object\" ||\n extras == null ||\n !(symbolStatewireExtras in extras)\n )\n throw new Error(\n \"This method can only be called when you are using StatewireThread\",\n );\n\n return extras as StatewireThread.Extras;\n};\n\nconst NO_INPUT_REQUESTS: readonly StatewireThread.InputRequestState[] = [];\n\nconst RESTING_RUNS: StatewireThread.Runs = {\n runId: null,\n queue: [],\n steerQueue: [],\n failed: [],\n};\n\n/** The failed run sends the thread can project: enqueue/steer/edit invocations carrying a message. */\nconst failedRunCommand = (\n entry: StatewireClient.FailedCommand,\n):\n | ((\n | StatewireThread.RunEnqueueCommand\n | StatewireThread.RunSteerCommand\n | StatewireThread.RunEditCommand\n ) & { message: StatewireThread.UserMessage })\n | undefined => {\n if (\n entry.command !== \"run/enqueue\" &&\n entry.command !== \"run/steer\" &&\n entry.command !== \"run/edit\"\n )\n return undefined;\n const command = entry.params[0] as\n | { message?: StatewireThread.UserMessage }\n | undefined;\n if (command?.message === undefined) return undefined;\n return command as ReturnType<typeof failedRunCommand>;\n};\n\n// Derived presentation while the connection can't vouch for progress:\n// live-claiming \"running\" reads as evicted/disconnected; facts pass through.\nconst presentStatus = (\n status: StatewireThread.ThreadStatus,\n connection: StatewireClient.ConnectionState,\n): StatewireThread.ThreadStatus =>\n status !== \"running\" ||\n connection.status === \"connected\" ||\n (connection.status === \"standby\" && connection.reason === \"idle\")\n ? status\n : connection.status === \"retrying\" &&\n connection.cause === \"reconnect\" &&\n connection.code === \"evicted\"\n ? \"evicted\"\n : \"disconnected\";\n\nconst ambientContextOf = (context: ModelContext): Record<string, unknown> => ({\n ...(context.system !== undefined && { system: context.system }),\n ...(context.tools !== undefined && {\n tools: toToolsJSONSchema(context.tools),\n }),\n ...(context.callSettings !== undefined && {\n callSettings: context.callSettings,\n }),\n ...(context.config !== undefined && { config: context.config }),\n});\n\nconst useStatewireThread = (\n options: StatewireThread.Options<any>,\n): ClientOutput<\"thread\"> => {\n const latest = useRef(options);\n latest.current = options;\n const retrying = useRef(new Set<string>());\n\n const [pending, setPending] = useState<readonly StatewireThread.Command[]>(\n [],\n );\n const [retire] = useState(\n () => (command: unknown) =>\n setPending((prev) =>\n prev.includes(command as StatewireThread.Command)\n ? prev.filter((c) => c !== command)\n : prev,\n ),\n );\n\n const {\n state,\n commands,\n connection,\n documents,\n invoke,\n setContext,\n isBusy,\n failed,\n discardFailed,\n } = useStatewire<unknown, AnyCommands>({\n transport: options.transport,\n onError: (error) => latest.current.onError?.(error),\n storage: options.storage,\n initialState: options.initialState,\n ...(options.protocol !== undefined && { protocol: options.protocol }),\n optimistic: (draft, command, ctx) => {\n runsOptimistic(draft, command, ctx);\n latest.current.optimistic?.(draft, command, ctx);\n },\n materialize: (draft: {}) => latest.current.materialize?.(draft),\n onCommandChange: (update, ctx) => {\n if (update.status === \"applied\" || update.status === \"settled\")\n retire(update.params[0]);\n latest.current.onCommandChange?.(update, ctx);\n },\n onStateChange: (state, ctx) => latest.current.onStateChange?.(state, ctx),\n onConnectionChange: (connection) =>\n latest.current.onConnectionChange?.(connection),\n failureCovered: (state, entry) => {\n const command = failedRunCommand(entry);\n if (command === undefined) return false;\n const messages = (state as { messages?: readonly { id: string }[] })\n .messages;\n return messages?.some((m) => m.id === command.message.id) ?? false;\n },\n });\n\n const discarded = useRef(new WeakSet<StatewireClient.FailedCommand>());\n // Effects can replay before the updated failed lane reaches the binding.\n useEffect(() => {\n for (const entry of failed) {\n if (\n failedRunCommand(entry) === undefined &&\n !discarded.current.has(entry)\n ) {\n discarded.current.add(entry);\n discardFailed(entry);\n }\n }\n }, [failed, discardFailed]);\n\n const clientRef = useAssistantClientRef();\n const contextRef = useRef(setContext);\n contextRef.current = setContext;\n const contextFailure = useRef<Error | undefined>(undefined);\n const { contextSync } = options;\n const contextProtocol = options.protocol ?? DEFAULT_PROTOCOL;\n useEffect(() => {\n if (contextSync === undefined) return;\n const modelContext = (clientRef.current ?? clientRef.parent).modelContext();\n let lastSent: string | undefined;\n const send = () => {\n const value = ambientContextOf(modelContext.getModelContext());\n const key = JSON.stringify(value);\n if (key === lastSent) return;\n try {\n contextRef.current(contextProtocol, value);\n } catch (error) {\n contextFailure.current = error as Error;\n lastSent = undefined;\n latest.current.onError?.(error as Error);\n return;\n }\n contextFailure.current = undefined;\n lastSent = key;\n };\n if (!modelContext.subscribe)\n throw new Error(\n \"statewire: contextSync requires a subscribable model context\",\n );\n send();\n return modelContext.subscribe(send);\n }, [contextSync, contextProtocol, clientRef]);\n\n const [heldByContext] = useState(\n () =>\n (command: StatewireThread.Command): Error | undefined =>\n contextFailure.current !== undefined &&\n (command.type === \"run/enqueue\" ||\n command.type === \"run/steer\" ||\n command.type === \"run/edit\")\n ? new Error(\"statewire: the model context was rejected\", {\n cause: contextFailure.current,\n })\n : undefined,\n );\n\n const dispatch = useCallback(\n (command: StatewireThread.Command) => {\n const held = heldByContext(command);\n if (held !== undefined) {\n latest.current.onError?.(held);\n return Promise.reject(held);\n }\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, heldByContext],\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 // The stop verdict carries the run's retracted items; the stopping client\n // dequeues them into an empty composer. Other clients see them queued.\n const popRetracted = async (\n retracted: unknown,\n runId: string | null,\n ): Promise<void> => {\n if (!Array.isArray(retracted) || retracted.length === 0 || runId === null)\n return;\n const composerApi = threadRef.current!.composer();\n if (composerApi.getState().text !== \"\") return;\n const texts: string[] = [];\n for (const item of retracted as StatewireThread.RunsQueueEntry[]) {\n try {\n await dispatch({ type: \"run/dequeue\", runId, messageId: item.id });\n } catch {\n continue; // rejected dequeue: the item stays queued\n }\n texts.push(\n item.parts\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\"),\n );\n }\n if (texts.length === 0) return;\n const setText = composerApi.setText as (\n next: string | ((prev: string) => string),\n ) => void;\n setText((prev) => [prev, ...texts].filter(Boolean).join(\"\\n\\n\"));\n };\n\n const { status, runs } = useMemo((): {\n status: StatewireThread.ThreadStatus;\n runs: StatewireThread.Runs;\n } => {\n const entries = (\n state as { runs?: readonly StatewireThread.RunState[] } | undefined\n )?.runs;\n const entry = entries?.[0];\n const failedEntries = failed.flatMap(\n (failure): StatewireThread.RunsFailedEntry[] => {\n const command = failedRunCommand(failure);\n return command === undefined\n ? []\n : [{ ...command.message, sendFailure: failure.failure }];\n },\n );\n return {\n status: presentStatus(\n entries === undefined ? \"loading\" : (entry?.status ?? \"ready\"),\n connection,\n ),\n runs:\n entry === undefined && failedEntries.length === 0\n ? RESTING_RUNS\n : {\n ...(entry === undefined\n ? RESTING_RUNS\n : {\n runId: entry.runId,\n ...(entry.epoch !== undefined && { epoch: entry.epoch }),\n ...(entry.stopReason !== undefined && {\n stopReason: entry.stopReason,\n }),\n queue: entry.queue,\n steerQueue: entry.steerQueue,\n ...(entry.dispatching !== undefined && {\n dispatching: entry.dispatching,\n }),\n ...(entry.stopping !== undefined && {\n stopping: entry.stopping,\n }),\n ...(entry.nextDispatch !== undefined && {\n nextDispatch: entry.nextDispatch,\n }),\n ...(entry.inputRequests !== undefined && {\n inputRequests: entry.inputRequests,\n }),\n ...(entry.error !== undefined && { error: entry.error }),\n }),\n failed: failedEntries,\n },\n };\n }, [state, connection, failed]);\n\n const { converter } = options;\n const mounted = useSyncExternalStore(\n documents?.subscribe ?? noopSubscribe,\n () => documents?.list() ?? NO_DOCUMENTS,\n () => documents?.list() ?? NO_DOCUMENTS,\n );\n const metadata = useMemo(\n (): StatewireThread.ConnectionMetadata => ({\n pendingCommands: [...pending],\n isSending: pending.length > 0,\n connection,\n runs,\n documents,\n mounted,\n invoke,\n }),\n [pending, connection, runs, documents, mounted, invoke],\n );\n const converted = useMemo(\n (): StatewireThread.State => converter(state, metadata),\n [converter, state, metadata],\n );\n // Dispatch limbo is a materialize concern: the fold makes the record\n // concrete in state before conversion.\n const messages = converted.messages;\n const liveRunId = runs.runId;\n\n // ExternalThread rebuilds every message's state when `queue` or a message\n // handler changes identity, so these read the latest pass instead of closing over it.\n const inputRequests = runs.inputRequests ?? NO_INPUT_REQUESTS;\n const pass = { messages, runId: liveRunId, inputRequests, dispatch };\n const live = useRef(pass);\n live.current = pass;\n const queue = useMemo(\n () =>\n createRunQueueAdapter(\n () => live.current,\n runs.queue,\n runs.steerQueue,\n dispatch,\n dispatchSend,\n ),\n [runs.queue, runs.steerQueue, dispatch, dispatchSend],\n );\n\n const branches = useMemo(\n () => createBranchCommandAdapter(messages, dispatch),\n [messages, dispatch],\n );\n\n const extras = useMemo((): StatewireThread.Extras => {\n const takeFailed = (messageId: string): StatewireClient.FailedCommand => {\n const entry = failed.find(\n (f) => failedRunCommand(f)?.message.id === messageId,\n );\n if (entry === undefined)\n throw new Error(`statewire: unknown failed entry \"${messageId}\"`);\n return entry;\n };\n return {\n [symbolStatewireExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n connection,\n documents,\n invoke,\n state: converted.state === undefined ? state : converted.state,\n status,\n isBusy,\n inputRequests,\n runs,\n retryFailed: (messageId) => {\n if (retrying.current.has(messageId)) return;\n const entry = takeFailed(messageId);\n const command = retryCommand(\n messages,\n liveRunId,\n failedRunCommand(entry)!,\n );\n const held = heldByContext(command);\n if (held !== undefined) throw held;\n retrying.current.add(messageId);\n const release = () => {\n retrying.current.delete(messageId);\n };\n try {\n discardFailed(entry);\n void dispatch(command).then(release, release);\n } catch (error) {\n release();\n throw error;\n }\n },\n discardFailed: (messageId) => discardFailed(takeFailed(messageId)),\n popFailed: (messageId) => {\n const entry = takeFailed(messageId);\n discardFailed(entry);\n return failedRunCommand(entry)!\n .message.parts.flatMap((p) => (p.type === \"text\" ? [p.text] : []))\n .join(\"\\n\\n\");\n },\n };\n }, [\n dispatch,\n heldByContext,\n connection,\n documents,\n invoke,\n state,\n converted.state,\n status,\n isBusy,\n inputRequests,\n runs,\n failed,\n discardFailed,\n messages,\n liveRunId,\n ]);\n\n const handleAppend = (message: AppendMessage) => {\n dispatchSend(\n message.sourceId != null\n ? resolveEditCommand(messages, message, liveRunId)\n : {\n type: \"run/steer\",\n ...sendFields(\n messages,\n liveRunId,\n toWireMessage(message, crypto.randomUUID()),\n ),\n },\n message,\n );\n };\n\n const handleReload = (parentId: string | null) => {\n dispatch(resolveReloadCommand(messages, parentId, liveRunId));\n };\n\n const [messageHandlers] = useState(() => ({\n onEdit: (message: AppendMessage) => {\n const { messages, runId, dispatch } = live.current;\n dispatch(resolveEditCommand(messages, message, runId));\n },\n onAddToolResult: (toolOptions: AddToolResultOptions) => {\n const { inputRequests, runId, dispatch } = live.current;\n return dispatch(\n resolveToolResultInput(inputRequests, toolOptions, runId),\n );\n },\n onRespondToToolApproval: async (approval: RespondToToolApprovalOptions) => {\n const { inputRequests, runId, dispatch } = live.current;\n await dispatch(resolveToolApprovalInput(inputRequests, approval, runId));\n },\n }));\n\n const thread = useResource(\n ExternalThread({\n messages: messages as readonly ExternalThreadMessage[],\n isRunning: status === \"running\",\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n speechAdapter: options.adapters?.speech,\n feedbackAdapter: options.adapters?.feedback,\n onNew: handleAppend,\n queue,\n ...(options.capabilities?.edit && { onEdit: messageHandlers.onEdit }),\n ...(options.capabilities?.continue && {\n onResume: async () => {\n await dispatch({\n type: \"run/continue\",\n ...(liveRunId !== null && { runId: liveRunId }),\n });\n },\n }),\n ...(options.capabilities?.reload && { onReload: handleReload }),\n ...(options.capabilities?.unstable_switchBranch && { branches }),\n onAddToolResult: messageHandlers.onAddToolResult,\n onRespondToToolApproval: messageHandlers.onRespondToToolApproval,\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.runId;\n void commands[\"run/stop\"]!({\n ...payload,\n runId,\n ...(runs.epoch !== undefined && { epoch: runs.epoch }),\n })\n .then((retracted) => popRetracted(retracted, runId))\n .catch((error: Error) => {\n latest.current.onError?.(error);\n });\n },\n }),\n );\n threadRef.current = thread;\n\n const composerStorage = useResources(\n options.storage?.composer !== undefined\n ? [withKey(\"composer\", options.storage.composer)]\n : [],\n )[0];\n\n useEffect(() => {\n const storage = composerStorage;\n if (storage === undefined) return;\n const composer = threadRef.current!.composer();\n const draft = storage.read();\n if (draft === undefined || !composer.getState().isEmpty) return;\n composer.setText(draft.text);\n for (const attachment of draft.attachments) {\n composer\n .addAttachment({\n id: attachment.id,\n type: attachment.type,\n name: attachment.name,\n ...(attachment.contentType !== undefined && {\n contentType: attachment.contentType,\n }),\n content: attachment.content,\n })\n .catch((error: Error) => {\n latest.current.onError?.(error);\n });\n }\n }, [composerStorage]);\n\n const { text: draftText, attachments: composerAttachments } =\n thread.getState().composer;\n const draftAttachments = useMemo(\n () =>\n composerAttachments\n .filter(\n (attachment): attachment is CompleteAttachment =>\n attachment.status.type === \"complete\",\n )\n .map(({ file: _file, ...record }) => record),\n [composerAttachments],\n );\n const [draftSync] = useState(() => ({ writingFor: undefined as unknown }));\n useEffect(() => {\n const storage = composerStorage;\n if (storage === undefined) return;\n // First run per storage is the baseline, not a change: never clear the\n // stored draft the restore effect is about to load.\n const isBaseline = draftSync.writingFor !== storage;\n draftSync.writingFor = storage;\n if (draftText === \"\" && draftAttachments.length === 0) {\n if (!isBaseline) storage.clear();\n return;\n }\n storage.write({ text: draftText, attachments: draftAttachments });\n }, [draftSync, composerStorage, draftText, draftAttachments]);\n\n return thread;\n};\n\nexport const StatewireThread = <T>(\n options: StatewireThread.Options<T>,\n): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useStatewireThread)(options as StatewireThread.Options<any>);\n\nexport namespace StatewireThread {\n type UserCommands = Assistant.Commands[keyof Assistant.Commands];\n\n export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;\n\n /** A composer draft as persisted: the text plus the completed attachments. */\n export type ComposerDraft = {\n readonly text: string;\n readonly attachments: readonly CompleteAttachment[];\n };\n\n /** Composer draft storage seam; `write` must persist synchronously in the caller's flow. */\n export type ComposerStorage = {\n read(): ComposerDraft | undefined;\n write(draft: ComposerDraft): void;\n clear(): void;\n };\n\n export type Extras = {\n [symbolStatewireExtras]: true;\n /** Dispatches the command; the promise settles with the accepted command's result payload, rejecting with `StatewireSendError` otherwise. */\n sendCommand: (command: Command) => Promise<unknown>;\n reconnect: () => void;\n connection: StatewireClient.ConnectionState;\n /** The mounted documents, or `undefined` on a transport without documents. */\n documents: StatewireDocuments.Source | undefined;\n /** Sends a statement on a negotiated protocol lane. */\n invoke: (\n protocol: string,\n method: string,\n params: readonly unknown[],\n ) => Promise<unknown>;\n /** The converter's `state` when it returns one, else the replicated state. */\n state: unknown;\n status: ThreadStatus;\n /** Negation of the server's broadcast idle level (a transport without idle is always busy). */\n isBusy: boolean;\n inputRequests: readonly InputRequestState[];\n runs: Runs;\n /** Re-dispatches the failed entry against the current thread and removes it; keyed by the entry's message id. */\n retryFailed: (messageId: string) => void;\n /** Removes the failed entry; keyed by the entry's message id. */\n discardFailed: (messageId: string) => void;\n /** Removes the failed entry and returns its text for the composer; keyed by the entry's message id. */\n popFailed: (messageId: string) => string;\n };\n\n export type TextPart = {\n readonly type: \"text\";\n readonly text: string;\n };\n\n export type FilePart = {\n readonly type: \"file\";\n readonly mediaType: string;\n readonly url: string;\n readonly filename?: string;\n };\n\n export type UserMessage = {\n readonly id: string;\n readonly role: \"user\";\n readonly parts: readonly (TextPart | FilePart)[];\n readonly metadata?: Record<string, unknown>;\n };\n\n /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */\n export type Placement = {\n readonly insertAfter?: string | null;\n readonly insertBefore?: string | null;\n };\n\n type RunSendCommand<TType extends \"run/enqueue\" | \"run/steer\"> = {\n readonly type: TType;\n /** The run this command targets — the live run's id, or a fresh client-minted uuid on run-creating sends. */\n readonly runId: string;\n } & (\n | {\n readonly message: UserMessage;\n /** Run anchor: the message the new content grows after, null asserting an empty thread. Present on run-creating sends; absent when targeting the live run. */\n readonly runAnchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunEnqueueCommand = RunSendCommand<\"run/enqueue\">;\n\n export type RunSteerCommand = RunSendCommand<\"run/steer\">;\n\n export type RunDequeueCommand = {\n readonly type: \"run/dequeue\";\n readonly runId: string;\n readonly messageId: string;\n };\n\n export type RunEditCommand = {\n readonly type: \"run/edit\";\n /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */\n readonly runId: string;\n readonly message: UserMessage;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly runAnchorMessageId: string | null;\n };\n\n export type RunContinueCommand = {\n readonly type: \"run/continue\";\n readonly runId?: string;\n };\n\n export type ToolCallInputRequest = {\n readonly type: \"tool-call\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type ToolApprovalInputRequest = {\n readonly type: \"tool-approval\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type CustomInputRequest = {\n readonly type: string;\n readonly id: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A host request parking the run until answered; open union for custom types. */\n export type InputRequest =\n | ToolCallInputRequest\n | ToolApprovalInputRequest\n | CustomInputRequest;\n\n export type InputResponse = ReadonlyJSONValue;\n\n export type RunInputCommand = {\n readonly type: \"run/input\";\n readonly runId?: string;\n readonly requestId: string;\n readonly response: InputResponse;\n };\n\n /** An input request projected out of the host state; a present `response` key marks the entry answered. */\n export type InputRequestState = InputRequest & {\n readonly response?: InputResponse;\n /** The answer's `run/input` meta; absent when the answer carried none. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n /** Per-message branch metadata read from `metadata.custom.branch`: the message's own branch id and the fan-out's branch ids in creation order (own id included). */\n export type BranchMetadata = {\n readonly id: number;\n readonly siblings: readonly number[];\n };\n\n export type SwitchBranchCommand = {\n readonly type: \"message/switch-branch\";\n readonly branchId: number;\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 readonly metadata?: Record<string, unknown>;\n };\n\n /** Run subsystem status replicated by the host. */\n export type RunStatus = \"running\" | \"stopped\" | \"error\" | \"input-required\";\n\n /** The thread's status: `\"loading\"` while the runs mount is absent, `\"ready\"` while resting, otherwise the run's status; `\"evicted\"` and `\"disconnected\"` are client-derived from the connection, never replicated. */\n export type ThreadStatus =\n | \"loading\"\n | \"ready\"\n | \"evicted\"\n | \"disconnected\"\n | RunStatus;\n\n /** A queue-lane entry as replicated: the user message plus host-stamped `meta`. */\n export type RunsQueueEntry = UserMessage & {\n /** Host-stamped opaque per-entry metadata. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n /** A failed run send projected out of the retained lane: the entry shape plus its send failure. */\n export type RunsFailedEntry = RunsQueueEntry & {\n readonly sendFailure: StatewireClient.SendFailure;\n };\n\n /** An input outcome riding a dispatch record: the request with its response (null = abandoned) and `run/input` meta. */\n export type RunsInputOutcome = {\n readonly request: InputRequest;\n readonly response: InputResponse | null;\n readonly meta: ReadonlyJSONValue | null;\n };\n\n /** The dispatch record — the unapplied batch handed to the run; absent between applied and the next dispatch or take. */\n export type RunsDispatch = {\n readonly trigger:\n | \"message-send\"\n | \"message-edit\"\n | \"message-reload\"\n | \"input-resume\"\n | \"error-continue\"\n | \"stop-continue\"\n | \"steer\";\n readonly messages: readonly RunsQueueEntry[];\n /** Present on rewind dispatches: truncate the thread at this id first; null names the root. */\n readonly rollbackTo?: string | null;\n /** The run-starting op's meta; present only when carried. */\n readonly rootMeta?: ReadonlyJSONValue;\n /** Present when input outcomes ride the dispatch; visible until applied. */\n readonly inputOutcomes?: readonly RunsInputOutcome[];\n };\n\n /** The stopping window: present while a stop of the live run is underway; `\"message-edit\"` / `\"message-reload\"` pair with `nextDispatch`. */\n export type RunsStopping = {\n readonly reason: \"stop\" | \"message-edit\" | \"message-reload\";\n };\n\n /** The replicated run error — set on an unhandled failure, cleared by the next user-initiated run. */\n export type RunsError = {\n readonly message: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A replicated run entry — one element of the mount's `runs` array. */\n export type RunState = {\n /** The run's identity — client-minted, adopted by the host at run creation; persists through steers, input-required, and error/stop, retiring only when the queue drains and the run completes. */\n readonly runId: string | null;\n /** Counts the entry's dispatches; a `run/stop` carrying a stale epoch rejects. */\n readonly epoch?: number;\n /** The reason carried by `run/stop`; persists through error/stop, cleared at the next dispatch. */\n readonly stopReason?: string | null;\n readonly status: RunStatus;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */\n readonly dispatching?: RunsDispatch;\n readonly stopping?: RunsStopping;\n /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */\n readonly nextDispatch?: RunsDispatch;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n /** Set only by an unhandled throw; cleared by the next user-initiated run. */\n readonly error?: RunsError;\n };\n\n /** App-shaped effects `runsMaterialize` applies for the dispatch record. */\n export type MaterializeEffects = {\n /** Append one dispatched message to the app's committed message state. */\n append: (message: RunsQueueEntry) => void;\n /** Truncate to the rolled-back view first (null names the root); required for hosts that dispatch edits/reloads. */\n rollback?: (to: string | null) => void;\n };\n\n /** The runs mount as replicated: the run entries plus the top-level status projection. */\n export type RunsState = {\n /** Projection of `runs[0]?.status ?? \"ready\"`. */\n readonly status: \"ready\" | 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 state with unsettled commands folded in, resting defaults while no entry is live. */\n export type Runs = {\n /** The live run's id — non-null whenever a run entry is live (running, input-required, error/stop); the target for `run/*` sends. */\n readonly runId: string | null;\n /** Counts the entry's dispatches; rides `run/stop` so a replayed stop cannot end a later leg. */\n readonly epoch?: number;\n /** The reason carried by `run/stop`; persists through error/stop, cleared at the next dispatch. */\n readonly stopReason?: string | null;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */\n readonly dispatching?: RunsDispatch;\n readonly stopping?: RunsStopping;\n /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */\n readonly nextDispatch?: RunsDispatch;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n /** Set only by an unhandled throw; cleared by the next user-initiated run. */\n readonly error?: RunsError;\n /** Run sends retained after a non-accepted settle; retry, discard, or pop via the thread extras. */\n readonly failed: readonly RunsFailedEntry[];\n };\n\n export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `connected`. */\n connection: StatewireClient.ConnectionState;\n /** The typed runs read. */\n runs: Runs;\n documents: StatewireDocuments.Source | undefined;\n /** The mounted documents as of this pass; a new map whenever one changes. */\n mounted: ReadonlyMap<number, StatewireDocuments.Document>;\n invoke: (\n protocol: string,\n method: string,\n params: readonly unknown[],\n ) => Promise<unknown>;\n };\n\n /** Converter output: app-owned keys only — the lib projects the run mounts itself; `state` replaces the replicated state on the extras and thread. */\n export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n /**\n * Payload of the built-in `run/stop` command. `reason` is the one well-known\n * field; apps extend it with their own JSON-serializable fields.\n */\n export type StopPayload = {\n readonly reason?: string | undefined;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n export type Options<T> = {\n transport: Transport<T>;\n /** The pre-attach state, replaced by the attach snapshot. `runs: []` projects ready (interactive from the first render); an absent runs mount projects loading until attach. */\n initialState: T;\n /** Application protocol for optimistic commands; must match the transport's protocol. */\n protocol?: string | undefined;\n converter: StateConverter<T>;\n /** Folds app-owned keys for an unsettled command into the draft; runs after the lib's run-dialect reducer. */\n optimistic?:\n | StatewireClient.Optimistic<\n T,\n Record<string, (...args: any[]) => unknown>\n >\n | undefined;\n /** Makes dispatch records concrete in the draft (runs after the optimistic folds); without it, dispatch limbo stays out of `messages`. */\n materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;\n /**\n * \"command-send\" mirrors the client's ambient model context (system,\n * tools, callSettings, config) to native protocol context, restored on\n * each attachment and updated whenever it changes.\n */\n contextSync?: \"command-send\" | undefined;\n /** Supplies the `run/stop` command's payload; omitted, stop sends no payload. */\n stopPayload?: (() => StopPayload) | undefined;\n /** Observes each command's lifecycle (queued, posted, applied, settled); runs after the built-in pending-command retirement. */\n onCommandChange?:\n | ((\n update: Statewire.CommandUpdate<\n Record<string, (...args: any[]) => unknown>\n >,\n ctx: { state: NonNullable<T> },\n ) => void)\n | undefined;\n /** Observes the transport state: fires with the attach snapshot, then once per change. */\n onStateChange?:\n | ((state: NonNullable<T>, ctx: { changes: Statewire.Changes }) => void)\n | undefined;\n /** Observes connection status transitions, starting with the initial status. */\n onConnectionChange?:\n | ((connection: StatewireClient.Connection) => void)\n | undefined;\n onError?: ((error: Error) => void) | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n /** The host supports `run/continue` (a continue affordance on aborted runs). */\n continue?: boolean | undefined;\n /** The host supports `run/reload` (regenerating an assistant message). */\n reload?: boolean | undefined;\n /** The host supports `message/switch-branch` (thread-global branch switching driven by `metadata.custom.branch`). */\n unstable_switchBranch?: boolean | undefined;\n }\n | undefined;\n /**\n * Durable drafts: the mounted composer storage restores on mount, mirrors\n * every change, and clears when the draft is consumed. The session storage\n * holds this thread's lane identity and its un-durable commands, which\n * resend under their original seqs on the next mount.\n */\n storage?:\n | {\n composer?: ResourceElement<ComposerStorage> | undefined;\n session?: ResourceElement<StatewireClient.SessionStorage> | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n speech?: SpeechSynthesisAdapter | undefined;\n feedback?: FeedbackAdapter | undefined;\n }\n | undefined;\n };\n}\n\ndeclare module \"@assistant-ui/core\" {\n namespace Assistant {\n interface Commands {\n runEnqueue: StatewireThread.RunEnqueueCommand;\n runSteer: StatewireThread.RunSteerCommand;\n runDequeue: StatewireThread.RunDequeueCommand;\n runEdit: StatewireThread.RunEditCommand;\n runContinue: StatewireThread.RunContinueCommand;\n runReload: StatewireThread.RunReloadCommand;\n runInput: StatewireThread.RunInputCommand;\n messageSwitchBranch: StatewireThread.SwitchBranchCommand;\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":";;;;;;;;;;AAuDA,MAAM8C,+BACJ,IAAIG,IAAI;AACV,MAAMC,4BAA4B,CAAC;AAEnC,MAAaC,wBAAwBC,OAAO,kBAAkB;AAE9D,MAAaC,qBAAqBC,WAA4C;CAC5E,IACE,OAAOA,WAAW,YAClBA,UAAU,QACV,EAAEH,yBAAyBG,SAE3B,MAAM,IAAIG,MACR,mEACF;CAEF,OAAOH;AACT;AAEA,MAAMI,oBAAkE,CAAA;AAExE,MAAME,eAAqC;CACzCE,OAAO;CACPC,OAAO,CAAA;CACPC,YAAY,CAAA;CACZC,QAAQ,CAAA;AACV;;AAGA,MAAMC,oBACJC,UAOe;CACf,IACEA,MAAMO,YAAY,iBAClBP,MAAMO,YAAY,eAClBP,MAAMO,YAAY,YAElB,OAAOC,KAAAA;CACT,MAAMD,UAAUP,MAAMS,OAAO;CAG7B,IAAIF,SAASF,YAAYG,KAAAA,GAAW,OAAOA,KAAAA;CAC3C,OAAOD;AACT;AAIA,MAAMI,iBACJC,QACAE,eAEAF,WAAW,aACXE,WAAWF,WAAW,eACrBE,WAAWF,WAAW,aAAaE,WAAWE,WAAW,SACtDJ,SACAE,WAAWF,WAAW,cACpBE,WAAWG,UAAU,eACr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AEpB,MAAM,EAAE1F,MAAMiG,WAAWvB,aAAawB,wBACpC5B,OAAOxD,SAAS,CAAC,CAACR;CACpB,MAAM6F,mBAAmBpQ,cAErBmQ,oBACG5J,QACEuJ,iBACCA,aAAWjL,OAAO0E,SAAS,UAC/B,CAAC,CACA8G,KAAK,EAAEC,MAAMC,OAAO,GAAGC,aAAaA,MAAM,GAC/C,CAACL,mBAAmB,CACtB;CACA,MAAM,CAACM,aAAavQ,gBAAgB,EAAEwQ,YAAYjM,KAAAA,EAAqB,EAAE;CACzE1E,gBAAgB;EACd,MAAMoH,YAAUwI;EAChB,IAAIxI,cAAY1C,KAAAA,GAAW;EAG3B,MAAMkM,aAAaF,UAAUC,eAAevJ;EAC5CsJ,UAAUC,aAAavJ;EACvB,IAAI+I,cAAc,MAAME,iBAAiBvF,WAAW,GAAG;GACrD,IAAI,CAAC8F,YAAYxJ,UAAQyJ,MAAM;GAC/B;EACF;EACAzJ,UAAQ0J,MAAM;GAAE5G,MAAMiG;GAAWvB,aAAayB;EAAiB,CAAC;CAClE,GAAG;EAACK;EAAWd;EAAiBO;EAAWE;CAAgB,CAAC;CAE5D,OAAO7B;AACT;AAEA,MAAalL,mBACXsC,YAEAvF,SAASsF,kBAAkB,CAAC,CAACC,OAAuC;AAubtE/E,uBACE8E,oBACAjF,eAAegE,KAAAA,CAAkB,CAAC,CAACgR,IACrC"}
package/dist/hooks.d.ts CHANGED
@@ -1,12 +1,10 @@
1
- import { StatewireThread } from "./StatewireThread.js";
2
- import { Assistant } from "@assistant-ui/core";
3
- //#region src/hooks.d.ts
1
+ import type { Assistant } from "@assistant-ui/core";
2
+ import type { StatewireThread } from "./StatewireThread.js";
4
3
  type UserExternalState = keyof Assistant.ExternalState extends never ? Record<string, unknown> : Assistant.ExternalState[keyof Assistant.ExternalState];
5
- declare const useStatewireSendCommand: () => (command: StatewireThread.Command) => Promise<unknown>;
4
+ export declare const useStatewireSendCommand: () => (command: StatewireThread.Command) => Promise<unknown>;
6
5
  /** The typed runs read. */
7
- declare const useStatewireRuns: () => StatewireThread.Runs;
8
- declare function useStatewireState(): UserExternalState;
9
- declare function useStatewireState<T>(selector: (state: UserExternalState) => T): T;
10
- //#endregion
11
- export { useStatewireRuns, useStatewireSendCommand, useStatewireState };
6
+ export declare const useStatewireRuns: () => StatewireThread.Runs;
7
+ export declare function useStatewireState(): UserExternalState;
8
+ export declare function useStatewireState<T>(selector: (state: UserExternalState) => T): T;
9
+ export {};
12
10
  //# sourceMappingURL=hooks.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"hooks.d.ts","names":[],"sources":["../src/hooks.ts"],"mappings":";;;KAOK,0BAA0B,UAAU,8BACrC,0BACA,UAAU,oBAAoB,UAAU;cAE/B,gCAGH,SAAS,gBAAgB,YAAO;;cAK7B,wBAAuB,gBAAgB;iBAGpC,qBAAqB;iBACrB,kBAAkB,GAChC,WAAW,OAAO,sBAAsB,IACvC"}
1
+ {"version":3,"file":"hooks.d.ts","sourceRoot":"","sources":["../src/hooks.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,KAAK,EAAE,eAAe,EAAE,6BAA0B;AAEzD,KAAK,iBAAiB,GAAG,MAAM,SAAS,CAAC,aAAa,SAAS,KAAK,GAChE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GACvB,SAAS,CAAC,aAAa,CAAC,MAAM,SAAS,CAAC,aAAa,CAAC,CAAC;AAE3D,eAAO,MAAM,uBAAuB,SAG1B,SAAS,eAAe,CAAC,OAAO,qBAEzC,CAAC;AAEF,2BAA2B;AAC3B,eAAO,MAAM,gBAAgB,QAAO,eAAe,CAAC,IACS,CAAC;AAE9D,wBAAgB,iBAAiB,IAAI,iBAAiB,CAAC;AACvD,wBAAgB,iBAAiB,CAAC,CAAC,EACjC,QAAQ,EAAE,CAAC,KAAK,EAAE,iBAAiB,KAAK,CAAC,GACxC,CAAC,CAAC"}
package/dist/hooks.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import { asStatewireExtras } from "./StatewireThread.js";
3
3
  import { useAui, useAuiState } from "@assistant-ui/store";
4
4
  import { c } from "@assistant-ui/tap/react-shim/compiler-runtime";
5
- //#region src/hooks.ts
5
+ // src/hooks.ts
6
6
  const useStatewireSendCommand = () => {
7
7
  const $ = c(2);
8
8
  const aui = useAui();
@@ -24,7 +24,6 @@ function useStatewireState(selector = (t) => t) {
24
24
  function _temp(s) {
25
25
  return asStatewireExtras(s.thread.extras).runs;
26
26
  }
27
- //#endregion
28
27
  export { useStatewireRuns, useStatewireSendCommand, useStatewireState };
29
28
 
30
29
  //# sourceMappingURL=hooks.js.map
package/dist/hooks.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"hooks.js","names":["c","_c","useAui","useAuiState","asStatewireExtras","Assistant","StatewireThread","UserExternalState","ExternalState","Record","useStatewireSendCommand","$","aui","t0","command","thread","getState","extras","sendCommand","useStatewireRuns","_temp","useStatewireState","selector","state","T","t","s","runs"],"sources":["../src/hooks.ts"],"sourcesContent":["\"use client\";\n\nimport { useAui, useAuiState } from \"@assistant-ui/store\";\nimport { asStatewireExtras } from \"./StatewireThread\";\nimport type { Assistant } from \"@assistant-ui/core\";\nimport type { StatewireThread } from \"./StatewireThread\";\n\ntype UserExternalState = keyof Assistant.ExternalState extends never\n ? Record<string, unknown>\n : Assistant.ExternalState[keyof Assistant.ExternalState];\n\nexport const useStatewireSendCommand = () => {\n const aui = useAui();\n\n return (command: StatewireThread.Command) =>\n asStatewireExtras(aui.thread().getState().extras).sendCommand(command);\n};\n\n/** The typed runs read. */\nexport const useStatewireRuns = (): StatewireThread.Runs =>\n useAuiState((s) => asStatewireExtras(s.thread.extras).runs);\n\nexport function useStatewireState(): UserExternalState;\nexport function useStatewireState<T>(\n selector: (state: UserExternalState) => T,\n): T;\nexport function useStatewireState<T>(\n selector: (state: UserExternalState) => T = (t) => t as T,\n): T | UserExternalState {\n return useAuiState((s) =>\n selector(asStatewireExtras(s.thread.extras).state as UserExternalState),\n );\n}\n"],"mappings":";;;;;AAWA,MAAaU,gCAA0B;CAAA,MAAAC,IAAAV,EAAA,CAAA;CACrC,MAAAW,MAAYV,OAAO;CAAE,IAAAW;CAAA,IAAAF,EAAA,OAAAC,KAAA;EAEdC,MAAAC,YACLV,kBAAkBQ,IAAGG,OAAQ,CAAC,CAAAC,SAAU,CAAC,CAAAC,MAAO,CAAC,CAAAC,YAAaJ,OAAO;EAACH,EAAA,KAAAC;EAAAD,EAAA,KAAAE;CAAA,OAAAA,KAAAF,EAAA;CAAA,OADjEE;AACiE;;AAI1E,MAAaM,yBAAmB;CAAA,OAC9BhB,YAAYiB,KAA8C;AAAC;AAM7D,SAAgBC,kBACdC,YAA6CG,MAAMA,GAC5B;CACvB,OAAOtB,aAAauB,MAClBJ,SAASlB,kBAAkBsB,EAAEX,OAAOE,MAAM,CAAC,CAACM,KAA0B,CACxE;AACF;AAbgC,SAAAH,MAAAM,GAAA;CAAA,OACXtB,kBAAkBsB,EAACX,OAAOE,MAAO,CAAC,CAAAU;AAAK"}
1
+ {"version":3,"file":"hooks.js","names":["c","_c","useAui","useAuiState","asStatewireExtras","Assistant","StatewireThread","UserExternalState","ExternalState","Record","useStatewireSendCommand","$","aui","t0","command","thread","getState","extras","sendCommand","useStatewireRuns","_temp","useStatewireState","selector","state","T","t","s","runs","_c"],"sources":["../src/hooks.ts"],"sourcesContent":["\"use client\";\n\nimport { useAui, useAuiState } from \"@assistant-ui/store\";\nimport { asStatewireExtras } from \"./StatewireThread\";\nimport type { Assistant } from \"@assistant-ui/core\";\nimport type { StatewireThread } from \"./StatewireThread\";\n\ntype UserExternalState = keyof Assistant.ExternalState extends never\n ? Record<string, unknown>\n : Assistant.ExternalState[keyof Assistant.ExternalState];\n\nexport const useStatewireSendCommand = () => {\n const aui = useAui();\n\n return (command: StatewireThread.Command) =>\n asStatewireExtras(aui.thread().getState().extras).sendCommand(command);\n};\n\n/** The typed runs read. */\nexport const useStatewireRuns = (): StatewireThread.Runs =>\n useAuiState((s) => asStatewireExtras(s.thread.extras).runs);\n\nexport function useStatewireState(): UserExternalState;\nexport function useStatewireState<T>(\n selector: (state: UserExternalState) => T,\n): T;\nexport function useStatewireState<T>(\n selector: (state: UserExternalState) => T = (t) => t as T,\n): T | UserExternalState {\n return useAuiState((s) =>\n selector(asStatewireExtras(s.thread.extras).state as UserExternalState),\n );\n}\n"],"mappings":";;;;;AAWA,MAAaU,gCAA0B;CAAA,MAAAC,IAAAV,EAAA,CAAA;CACrC,MAAAW,MAAYV,OAAO;CAAE,IAAAW;CAAA,IAAAF,EAAA,OAAAC,KAAA;EAEdC,MAAAC,YACLV,kBAAkBQ,IAAGG,OAAQ,CAAC,CAAAC,SAAU,CAAC,CAAAC,MAAO,CAAC,CAAAC,YAAaJ,OAAO;EAACH,EAAA,KAAAC;EAAAD,EAAA,KAAAE;CAAA,OAAAA,KAAAF,EAAA;CAAA,OADjEE;AACiE;;AAI1E,MAAaM,yBAAmB;CAAA,OAC9BhB,YAAYiB,KAA8C;AAAC;AAM7D,SAAgBC,kBACdC,YAA6CG,MAAMA,GAC5B;CACvB,OAAOtB,aAAauB,MAClBJ,SAASlB,kBAAkBsB,EAAEX,OAAOE,MAAM,CAAC,CAACM,KAA0B,CACxE;AACF;AAbgC,SAAAH,MAAAM,GAAA;CAAA,OACXtB,kBAAkBsB,EAACX,OAAOE,MAAO,CAAC,CAAAU;AAAK"}
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { StatewireThread } from "./StatewireThread.js";
2
- import { useStatewireRuns, useStatewireSendCommand, useStatewireState } from "./hooks.js";
3
- import { runsMaterialize } from "./runsMaterialize.js";
4
- export { StatewireThread, runsMaterialize, useStatewireRuns, useStatewireSendCommand, useStatewireState };
1
+ export { StatewireThread } from "./StatewireThread.js";
2
+ export { runsMaterialize } from "./runsMaterialize.js";
3
+ export { useStatewireSendCommand, useStatewireState, useStatewireRuns, } from "./hooks.js";
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,6BAA0B;AACpD,OAAO,EAAE,eAAe,EAAE,6BAA0B;AACpD,OAAO,EACL,uBAAuB,EACvB,iBAAiB,EACjB,gBAAgB,GACjB,mBAAgB"}