@assistant-ui/react-statewire 0.30.0 → 0.31.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -1
- package/dist/StatewireThread.d.ts.map +1 -1
- package/dist/StatewireThread.js +75 -35
- package/dist/StatewireThread.js.map +1 -1
- package/dist/localStorage.d.ts +7 -7
- package/dist/localStorage.d.ts.map +1 -1
- package/dist/localStorage.js +86 -37
- package/dist/localStorage.js.map +1 -1
- package/dist/runCommands.d.ts +6 -3
- package/dist/runCommands.d.ts.map +1 -1
- package/dist/runCommands.js +9 -2
- package/dist/runCommands.js.map +1 -1
- package/package.json +2 -2
- package/src/StatewireThread.drafts.test.tsx +6 -2
- package/src/StatewireThread.test.tsx +127 -0
- package/src/StatewireThread.ts +59 -15
- package/src/localStorage.test.ts +101 -27
- package/src/localStorage.ts +41 -19
- package/src/runCommands.test.ts +44 -1
- package/src/runCommands.ts +13 -3
package/README.md
CHANGED
|
@@ -21,7 +21,7 @@ const thread = StatewireThread<ServerState>({
|
|
|
21
21
|
initialState: { messages: [], status: "ready", runs: [] },
|
|
22
22
|
converter,
|
|
23
23
|
capabilities: { edit: true, reload: true },
|
|
24
|
-
storage: { composer: LocalStorageComposerDrafts({ threadId }) },
|
|
24
|
+
storage: { composer: LocalStorageComposerDrafts({ threadId, principal }) },
|
|
25
25
|
});
|
|
26
26
|
const config = AuiConfig({ thread });
|
|
27
27
|
return (
|
|
@@ -31,6 +31,8 @@ return (
|
|
|
31
31
|
);
|
|
32
32
|
```
|
|
33
33
|
|
|
34
|
+
Pass a stable authenticated `principal`; remount the thread/session when the account changes. Legacy unscoped drafts and sessions remain quarantined.
|
|
35
|
+
|
|
34
36
|
## Docs
|
|
35
37
|
|
|
36
38
|
- Get started: https://github.com/assistant-ui/harness-sdk/blob/main/apps/docs/app/docs/get-started/statewire/page.mdx
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;cA2Da;cAEA,oBAAqB,oBAAkB,gBAAgB;
|
|
1
|
+
{"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;cA2Da;cAEA,oBAAqB,oBAAkB,gBAAgB;cA8jBvD,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,iBA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EA;;;;;;;;IASN;MAEM,WAAW,gBAAgB;MAC3B,UAAU,gBAAgB,gBAAgB;;IAGhD;MAEM,cAAc;MACd,SAAS;MACT,WAAW;;;;;;YAOT;cACE;MACR,YAAY,gBAAgB;MAC5B,UAAU,gBAAgB;MAC1B,YAAY,gBAAgB;MAC5B,SAAS,gBAAgB;MACzB,aAAa,gBAAgB;MAC7B,WAAW,gBAAgB;MAC3B,UAAU,gBAAgB;MAC1B,qBAAqB,gBAAgB"}
|
package/dist/StatewireThread.js
CHANGED
|
@@ -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
|
-
|
|
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
|
|
100
|
-
|
|
101
|
-
const
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
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
|
-
}, [
|
|
122
|
+
}, [
|
|
123
|
+
commands,
|
|
124
|
+
retire,
|
|
125
|
+
heldByContext
|
|
126
|
+
]);
|
|
108
127
|
const threadRef = useRef(null);
|
|
109
|
-
const dispatchSend = useCallback((
|
|
110
|
-
if (message.sourceId != null) return void dispatch(
|
|
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(
|
|
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
|
|
143
|
-
return
|
|
144
|
-
...
|
|
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
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
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
|
|
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(
|
|
234
|
-
} catch (
|
|
261
|
+
dispatch(command_6).then(release, release);
|
|
262
|
+
} catch (error_2) {
|
|
235
263
|
release();
|
|
236
|
-
throw
|
|
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
|
|
272
|
-
|
|
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: (approval) => {
|
|
310
|
+
const { inputRequests: inputRequests_1, runId: runId_2, dispatch: dispatch_2 } = live.current;
|
|
311
|
+
return 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,25 @@ const useStatewireThread = (options) => {
|
|
|
281
321
|
feedbackAdapter: options.adapters?.feedback,
|
|
282
322
|
onNew: handleAppend,
|
|
283
323
|
queue,
|
|
284
|
-
...options.capabilities?.edit && { onEdit:
|
|
324
|
+
...options.capabilities?.edit && { onEdit: messageHandlers.onEdit },
|
|
285
325
|
...options.capabilities?.continue && { onResume: () => dispatch({
|
|
286
326
|
type: "run/continue",
|
|
287
327
|
...liveRunId !== null && { runId: liveRunId }
|
|
288
328
|
}) },
|
|
289
329
|
...options.capabilities?.reload && { onReload: handleReload },
|
|
290
330
|
...options.capabilities?.unstable_switchBranch && { branches },
|
|
291
|
-
onAddToolResult:
|
|
292
|
-
onRespondToToolApproval:
|
|
331
|
+
onAddToolResult: messageHandlers.onAddToolResult,
|
|
332
|
+
onRespondToToolApproval: messageHandlers.onRespondToToolApproval,
|
|
293
333
|
onCancel: () => {
|
|
294
334
|
const payload = latest.current.stopPayload?.();
|
|
295
335
|
if (payload !== void 0 && (typeof payload !== "object" || payload === null || Array.isArray(payload))) throw new Error("statewire: stopPayload must return a plain object");
|
|
296
|
-
const
|
|
336
|
+
const runId_3 = runs.runId;
|
|
297
337
|
commands["run/stop"]({
|
|
298
338
|
...payload,
|
|
299
|
-
runId:
|
|
339
|
+
runId: runId_3,
|
|
300
340
|
...runs.epoch !== void 0 && { epoch: runs.epoch }
|
|
301
|
-
}).then((retracted_0) => popRetracted(retracted_0,
|
|
302
|
-
latest.current.onError?.(
|
|
341
|
+
}).then((retracted_0) => popRetracted(retracted_0, runId_3)).catch((error_3) => {
|
|
342
|
+
latest.current.onError?.(error_3);
|
|
303
343
|
});
|
|
304
344
|
}
|
|
305
345
|
}));
|
|
@@ -318,8 +358,8 @@ const useStatewireThread = (options) => {
|
|
|
318
358
|
name: attachment.name,
|
|
319
359
|
...attachment.contentType !== void 0 && { contentType: attachment.contentType },
|
|
320
360
|
content: attachment.content
|
|
321
|
-
}).catch((
|
|
322
|
-
latest.current.onError?.(
|
|
361
|
+
}).catch((error_4) => {
|
|
362
|
+
latest.current.onError?.(error_4);
|
|
323
363
|
});
|
|
324
364
|
}, [composerStorage]);
|
|
325
365
|
const { text: draftText, attachments: composerAttachments } = thread.getState().composer;
|
|
@@ -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,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,eACrBH,WAAWI,SAAS,YACpB,YACA;AAER,MAAMC,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWb,KAAAA,KAAa,EAAEa,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQE,UAAUd,KAAAA,KAAa,EACjCc,OAAO/D,kBAAkB6D,QAAQE,KAAK,EACxC;CACA,GAAIF,QAAQG,iBAAiBf,KAAAA,KAAa,EACxCe,cAAcH,QAAQG,aACxB;CACA,GAAIH,QAAQI,WAAWhB,KAAAA,KAAa,EAAEgB,QAAQJ,QAAQI,OAAO;AAC/D;AAEA,MAAMC,sBACJC,YAC2B;CAC3B,MAAME,SAAS5F,OA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AM4L,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: (approval: RespondToToolApprovalOptions) => {\n const { inputRequests, runId, dispatch } = live.current;\n return 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: () =>\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: 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,q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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/localStorage.d.ts
CHANGED
|
@@ -2,9 +2,9 @@ import { StatewireThread } from "./StatewireThread.js";
|
|
|
2
2
|
import { StatewireClient } from "statewire";
|
|
3
3
|
import { KeyValueSessionStorage } from "statewire/storage";
|
|
4
4
|
//#region src/localStorage.d.ts
|
|
5
|
-
/** Composer draft storage on localStorage, keyed per thread; stale drafts are swept on mount. */
|
|
5
|
+
/** Composer draft storage on localStorage, keyed per principal and thread; stale drafts are swept on mount. */
|
|
6
6
|
declare const LocalStorageComposerDrafts: import("@assistant-ui/tap").Resource<StatewireThread.ComposerStorage, [LocalStorageComposerDrafts.Options]>;
|
|
7
|
-
/** Session storage on localStorage, keyed per
|
|
7
|
+
/** Session storage on localStorage, keyed per principal and thread; sharers serialize through a per-key Web Lock. */
|
|
8
8
|
declare const LocalStorageSession: import("@assistant-ui/tap").Resource<StatewireClient.SessionStorage, [LocalStorageSession.Options]>;
|
|
9
9
|
declare namespace LocalStorageSession {
|
|
10
10
|
type Options = {
|
|
@@ -15,19 +15,19 @@ declare namespace LocalStorageSession {
|
|
|
15
15
|
migrate?: StatewireClient.SessionStorage["migrate"];
|
|
16
16
|
/** The thread whose session this storage holds. */
|
|
17
17
|
threadId: string;
|
|
18
|
-
/**
|
|
19
|
-
|
|
18
|
+
/** The account whose commands this storage holds. */
|
|
19
|
+
principal: string;
|
|
20
20
|
};
|
|
21
21
|
}
|
|
22
22
|
declare namespace LocalStorageComposerDrafts {
|
|
23
23
|
type Options = {
|
|
24
24
|
/** The thread whose draft this storage holds. */
|
|
25
25
|
threadId: string;
|
|
26
|
-
/**
|
|
27
|
-
|
|
26
|
+
/** The account whose draft this storage holds. */
|
|
27
|
+
principal: string;
|
|
28
28
|
/** Draft lifetime in milliseconds, enforced by the mount sweep. Default 7 days. */
|
|
29
29
|
ttl?: number | undefined;
|
|
30
|
-
/** Newest drafts kept across
|
|
30
|
+
/** Newest drafts kept across the principal's threads, enforced by the mount sweep. Default 50. */
|
|
31
31
|
max?: number | undefined;
|
|
32
32
|
};
|
|
33
33
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"localStorage.d.ts","names":[],"sources":["../src/localStorage.ts"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"localStorage.d.ts","names":[],"sources":["../src/localStorage.ts"],"mappings":";;;;;cA8Ka,wDAA0B,SAAA,gBAAA,kBAAA,2BAAA;;cA8F1B,iDAAmB,SAAA,gBAAA,iBAAA,oBAAA;kBAEf;OACH;IACV,WAAW,uBAAuB;IAClC,YAAY,uBAAuB;IACnC,UAAU,uBAAuB;;IAEjC,UAAU,gBAAgB;;IAE1B;;IAEA;;;kBAIa;OACH;;IAEV;;IAEA;;IAEA;;IAEA"}
|