@assistant-ui/react-statewire 0.30.0 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +7 -5
  2. package/dist/StatewireThread.d.ts +341 -343
  3. package/dist/StatewireThread.d.ts.map +1 -1
  4. package/dist/StatewireThread.js +82 -41
  5. package/dist/StatewireThread.js.map +1 -1
  6. package/dist/hooks.d.ts +7 -9
  7. package/dist/hooks.d.ts.map +1 -1
  8. package/dist/hooks.js +1 -2
  9. package/dist/hooks.js.map +1 -1
  10. package/dist/index.d.ts +4 -4
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/inputRequests.d.ts +9 -12
  13. package/dist/inputRequests.d.ts.map +1 -1
  14. package/dist/inputRequests.js +1 -2
  15. package/dist/localStorage.d.ts +29 -32
  16. package/dist/localStorage.d.ts.map +1 -1
  17. package/dist/localStorage.js +54 -21
  18. package/dist/localStorage.js.map +1 -1
  19. package/dist/runCommands.d.ts +34 -34
  20. package/dist/runCommands.d.ts.map +1 -1
  21. package/dist/runCommands.js +10 -4
  22. package/dist/runCommands.js.map +1 -1
  23. package/dist/runsMaterialize.d.ts +2 -5
  24. package/dist/runsMaterialize.d.ts.map +1 -1
  25. package/dist/runsMaterialize.js +1 -2
  26. package/dist/runsOptimistic.d.ts +2 -5
  27. package/dist/runsOptimistic.d.ts.map +1 -1
  28. package/dist/runsOptimistic.js +2 -3
  29. package/dist/runsOptimistic.js.map +1 -1
  30. package/package.json +16 -14
  31. package/src/StatewireThread.drafts.test.tsx +6 -2
  32. package/src/StatewireThread.failed.test.tsx +1 -1
  33. package/src/StatewireThread.runs.test.tsx +1 -1
  34. package/src/StatewireThread.test.tsx +127 -0
  35. package/src/StatewireThread.ts +63 -18
  36. package/src/localStorage.test.ts +108 -29
  37. package/src/localStorage.ts +62 -20
  38. package/src/runCommands.test.ts +44 -1
  39. package/src/runCommands.ts +13 -3
  40. package/src/runsOptimistic.test.ts +1 -1
  41. package/src/runsOptimistic.ts +1 -1
@@ -1,350 +1,348 @@
1
- import { ResourceElement } from "@assistant-ui/tap";
2
- import { ClientOutput } from "@assistant-ui/store";
3
- import { Statewire, StatewireClient, StatewireDocuments } from "statewire";
4
- import { Assistant, AttachmentAdapter, CompleteAttachment, FeedbackAdapter, SpeechSynthesisAdapter, ThreadMessage } from "@assistant-ui/core";
5
- import { ReadonlyJSONValue } from "assistant-stream/utils";
6
- //#region src/StatewireThread.d.ts
7
- declare const symbolStatewireExtras: unique symbol;
8
- declare const asStatewireExtras: (extras: unknown) => StatewireThread.Extras;
9
- declare const StatewireThread: <T>(options: StatewireThread.Options<T>) => ResourceElement<ClientOutput<"thread">>;
10
- declare namespace StatewireThread {
11
- type UserCommands = Assistant.Commands[keyof Assistant.Commands];
12
- export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;
13
- /** A composer draft as persisted: the text plus the completed attachments. */
14
- export type ComposerDraft = {
15
- readonly text: string;
16
- readonly attachments: readonly CompleteAttachment[];
17
- };
18
- /** Composer draft storage seam; `write` must persist synchronously in the caller's flow. */
19
- export type ComposerStorage = {
20
- read(): ComposerDraft | undefined;
21
- write(draft: ComposerDraft): void;
22
- clear(): void;
23
- };
24
- export type Extras = {
25
- [symbolStatewireExtras]: true;
26
- /** Dispatches the command; the promise settles with the accepted command's result payload, rejecting with `StatewireSendError` otherwise. */
27
- sendCommand: (command: Command) => Promise<unknown>;
28
- reconnect: () => void;
29
- connection: StatewireClient.ConnectionState;
30
- /** The mounted documents, or `undefined` on a transport without documents. */
31
- documents: StatewireDocuments.Source | undefined;
32
- /** Sends a statement on a negotiated protocol lane. */
33
- invoke: (protocol: string, method: string, params: readonly unknown[]) => Promise<unknown>;
34
- /** The converter's `state` when it returns one, else the replicated state. */
35
- state: unknown;
36
- status: ThreadStatus;
37
- /** Negation of the server's broadcast idle level (a transport without idle is always busy). */
38
- isBusy: boolean;
39
- inputRequests: readonly InputRequestState[];
40
- runs: Runs;
41
- /** Re-dispatches the failed entry against the current thread and removes it; keyed by the entry's message id. */
42
- retryFailed: (messageId: string) => void;
43
- /** Removes the failed entry; keyed by the entry's message id. */
44
- discardFailed: (messageId: string) => void;
45
- /** Removes the failed entry and returns its text for the composer; keyed by the entry's message id. */
46
- popFailed: (messageId: string) => string;
47
- };
48
- export type TextPart = {
49
- readonly type: "text";
50
- readonly text: string;
51
- };
52
- export type FilePart = {
53
- readonly type: "file";
54
- readonly mediaType: string;
55
- readonly url: string;
56
- readonly filename?: string;
57
- };
58
- export type UserMessage = {
59
- readonly id: string;
60
- readonly role: "user";
61
- readonly parts: readonly (TextPart | FilePart)[];
62
- readonly metadata?: Record<string, unknown>;
63
- };
64
- /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */
65
- export type Placement = {
66
- readonly insertAfter?: string | null;
67
- readonly insertBefore?: string | null;
68
- };
69
- type RunSendCommand<TType extends "run/enqueue" | "run/steer"> = {
70
- readonly type: TType;
71
- /** The run this command targets — the live run's id, or a fresh client-minted uuid on run-creating sends. */
72
- readonly runId: string;
73
- } & ({
74
- readonly message: UserMessage;
75
- /** 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. */
76
- readonly runAnchorMessageId?: string | null;
77
- } | {
78
- readonly messageId: string;
79
- }) & Placement;
80
- export type RunEnqueueCommand = RunSendCommand<"run/enqueue">;
81
- export type RunSteerCommand = RunSendCommand<"run/steer">;
82
- export type RunDequeueCommand = {
83
- readonly type: "run/dequeue";
84
- readonly runId: string;
85
- readonly messageId: string;
86
- };
87
- export type RunEditCommand = {
88
- readonly type: "run/edit";
89
- /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */
90
- readonly runId: string;
91
- readonly message: UserMessage;
92
- readonly sourceId: string;
93
- /** Asserts `sourceId`'s parent — the rewind target; null names the root. */
94
- readonly runAnchorMessageId: string | null;
95
- };
96
- export type RunContinueCommand = {
97
- readonly type: "run/continue";
98
- readonly runId?: string;
99
- };
100
- export type ToolCallInputRequest = {
101
- readonly type: "tool-call";
102
- readonly id: string;
103
- readonly toolCallId: string;
104
- };
105
- export type ToolApprovalInputRequest = {
106
- readonly type: "tool-approval";
107
- readonly id: string;
108
- readonly toolCallId: string;
109
- };
110
- export type CustomInputRequest = {
111
- readonly type: string;
112
- readonly id: string;
113
- readonly [key: string]: ReadonlyJSONValue | undefined;
114
- };
115
- /** A host request parking the run until answered; open union for custom types. */
116
- export type InputRequest = ToolCallInputRequest | ToolApprovalInputRequest | CustomInputRequest;
117
- export type InputResponse = ReadonlyJSONValue;
118
- export type RunInputCommand = {
119
- readonly type: "run/input";
120
- readonly runId?: string;
121
- readonly requestId: string;
122
- readonly response: InputResponse;
123
- };
124
- /** An input request projected out of the host state; a present `response` key marks the entry answered. */
125
- export type InputRequestState = InputRequest & {
126
- readonly response?: InputResponse;
127
- /** The answer's `run/input` meta; absent when the answer carried none. */
128
- readonly meta?: ReadonlyJSONValue;
129
- };
130
- /** 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). */
131
- export type BranchMetadata = {
132
- readonly id: number;
133
- readonly siblings: readonly number[];
134
- };
135
- export type SwitchBranchCommand = {
136
- readonly type: "message/switch-branch";
137
- readonly branchId: number;
138
- };
139
- export type RunReloadCommand = {
140
- readonly type: "run/reload";
141
- /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */
142
- readonly runId: string;
143
- readonly sourceId: string;
144
- /** Asserts `sourceId`'s parent — the rewind target; null names the root. */
145
- readonly runAnchorMessageId: string | null;
146
- };
147
- export type RunCommand = RunEnqueueCommand | RunSteerCommand | RunDequeueCommand | RunEditCommand | RunContinueCommand | RunReloadCommand | RunInputCommand;
148
- export type Command = RunCommand | UserCommands;
149
- /** A queued message projected out of the host state, wire shape. */
150
- export type RunQueueItem = {
151
- readonly id: string;
152
- readonly parts: readonly (TextPart | FilePart)[];
153
- readonly metadata?: Record<string, unknown>;
154
- };
155
- /** Run subsystem status replicated by the host. */
156
- export type RunStatus = "running" | "stopped" | "error" | "input-required";
157
- /** 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. */
158
- export type ThreadStatus = "loading" | "ready" | "evicted" | "disconnected" | RunStatus;
159
- /** A queue-lane entry as replicated: the user message plus host-stamped `meta`. */
160
- export type RunsQueueEntry = UserMessage & {
161
- /** Host-stamped opaque per-entry metadata. */
162
- readonly meta?: ReadonlyJSONValue;
163
- };
164
- /** A failed run send projected out of the retained lane: the entry shape plus its send failure. */
165
- export type RunsFailedEntry = RunsQueueEntry & {
166
- readonly sendFailure: StatewireClient.SendFailure;
167
- };
168
- /** An input outcome riding a dispatch record: the request with its response (null = abandoned) and `run/input` meta. */
169
- export type RunsInputOutcome = {
170
- readonly request: InputRequest;
171
- readonly response: InputResponse | null;
172
- readonly meta: ReadonlyJSONValue | null;
173
- };
174
- /** The dispatch record — the unapplied batch handed to the run; absent between applied and the next dispatch or take. */
175
- export type RunsDispatch = {
176
- readonly trigger: "message-send" | "message-edit" | "message-reload" | "input-resume" | "error-continue" | "stop-continue" | "steer";
177
- readonly messages: readonly RunsQueueEntry[];
178
- /** Present on rewind dispatches: truncate the thread at this id first; null names the root. */
179
- readonly rollbackTo?: string | null;
180
- /** The run-starting op's meta; present only when carried. */
181
- readonly rootMeta?: ReadonlyJSONValue;
182
- /** Present when input outcomes ride the dispatch; visible until applied. */
183
- readonly inputOutcomes?: readonly RunsInputOutcome[];
184
- };
185
- /** The stopping window: present while a stop of the live run is underway; `"message-edit"` / `"message-reload"` pair with `nextDispatch`. */
186
- export type RunsStopping = {
187
- readonly reason: "stop" | "message-edit" | "message-reload";
188
- };
189
- /** The replicated run error — set on an unhandled failure, cleared by the next user-initiated run. */
190
- export type RunsError = {
191
- readonly message: string;
192
- readonly [key: string]: ReadonlyJSONValue | undefined;
193
- };
194
- /** A replicated run entry — one element of the mount's `runs` array. */
195
- export type RunState = {
196
- /** 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. */
197
- readonly runId: string | null;
198
- /** Counts the entry's dispatches; a `run/stop` carrying a stale epoch rejects. */
199
- readonly epoch?: number;
200
- /** The reason carried by `run/stop`; persists through error/stop, cleared at the next dispatch. */
201
- readonly stopReason?: string | null;
202
- readonly status: RunStatus;
203
- readonly queue: readonly RunsQueueEntry[];
204
- readonly steerQueue: readonly RunsQueueEntry[];
205
- /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */
206
- readonly dispatching?: RunsDispatch;
207
- readonly stopping?: RunsStopping;
208
- /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */
209
- readonly nextDispatch?: RunsDispatch;
210
- /** The parked pending set; present only in input-required. */
211
- readonly inputRequests?: readonly InputRequestState[];
212
- /** Set only by an unhandled throw; cleared by the next user-initiated run. */
213
- readonly error?: RunsError;
214
- };
215
- /** App-shaped effects `runsMaterialize` applies for the dispatch record. */
216
- export type MaterializeEffects = {
217
- /** Append one dispatched message to the app's committed message state. */
218
- append: (message: RunsQueueEntry) => void;
219
- /** Truncate to the rolled-back view first (null names the root); required for hosts that dispatch edits/reloads. */
220
- rollback?: (to: string | null) => void;
221
- };
222
- /** The runs mount as replicated: the run entries plus the top-level status projection. */
223
- export type RunsState = {
224
- /** Projection of `runs[0]?.status ?? "ready"`. */
225
- readonly status: "ready" | RunStatus;
226
- /** At most one entry; empty while resting. */
227
- readonly runs: readonly RunState[];
228
- };
229
- /** The run subsystem's typed read — `runs[0]` of the state with unsettled commands folded in, resting defaults while no entry is live. */
230
- export type Runs = {
231
- /** The live run's id — non-null whenever a run entry is live (running, input-required, error/stop); the target for `run/*` sends. */
232
- readonly runId: string | null;
233
- /** Counts the entry's dispatches; rides `run/stop` so a replayed stop cannot end a later leg. */
234
- readonly epoch?: number;
235
- /** The reason carried by `run/stop`; persists through error/stop, cleared at the next dispatch. */
236
- readonly stopReason?: string | null;
237
- readonly queue: readonly RunsQueueEntry[];
238
- readonly steerQueue: readonly RunsQueueEntry[];
239
- /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */
240
- readonly dispatching?: RunsDispatch;
241
- readonly stopping?: RunsStopping;
242
- /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */
243
- readonly nextDispatch?: RunsDispatch;
244
- /** The parked pending set; present only in input-required. */
245
- readonly inputRequests?: readonly InputRequestState[];
246
- /** Set only by an unhandled throw; cleared by the next user-initiated run. */
247
- readonly error?: RunsError;
248
- /** Run sends retained after a non-accepted settle; retry, discard, or pop via the thread extras. */
249
- readonly failed: readonly RunsFailedEntry[];
250
- };
251
- export type ConnectionMetadata = {
252
- pendingCommands: Command[];
253
- isSending: boolean;
254
- /** Statewire connection status; local transports are always `connected`. */
255
- connection: StatewireClient.ConnectionState;
256
- /** The typed runs read. */
257
- runs: Runs;
258
- documents: StatewireDocuments.Source | undefined;
259
- /** The mounted documents as of this pass; a new map whenever one changes. */
260
- mounted: ReadonlyMap<number, StatewireDocuments.Document>;
261
- invoke: (protocol: string, method: string, params: readonly unknown[]) => Promise<unknown>;
262
- };
263
- /** Converter output: app-owned keys only — the lib projects the run mounts itself; `state` replaces the replicated state on the extras and thread. */
264
- export type State = {
265
- readonly messages: readonly ThreadMessage[];
266
- readonly state?: ReadonlyJSONValue;
267
- };
268
- export type StateConverter<T> = (state: T, connectionMetadata: ConnectionMetadata) => State;
269
- /**
270
- * Payload of the built-in `run/stop` command. `reason` is the one well-known
271
- * field; apps extend it with their own JSON-serializable fields.
272
- */
273
- export type StopPayload = {
274
- readonly reason?: string | undefined;
275
- readonly [key: string]: ReadonlyJSONValue | undefined;
276
- };
277
- export type Options<T> = {
278
- transport: Transport<T>;
279
- /** 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. */
280
- initialState: T;
281
- /** Application protocol for optimistic commands; must match the transport's protocol. */
282
- protocol?: string | undefined;
283
- converter: StateConverter<T>;
284
- /** Folds app-owned keys for an unsettled command into the draft; runs after the lib's run-dialect reducer. */
285
- optimistic?: StatewireClient.Optimistic<T, Record<string, (...args: any[]) => unknown>> | undefined;
286
- /** Makes dispatch records concrete in the draft (runs after the optimistic folds); without it, dispatch limbo stays out of `messages`. */
287
- materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;
1
+ import type { ResourceElement } from "@assistant-ui/tap";
2
+ import type { Assistant } from "@assistant-ui/core";
3
+ import type { ClientOutput } from "@assistant-ui/store";
4
+ import type { AttachmentAdapter, CompleteAttachment, FeedbackAdapter, SpeechSynthesisAdapter, ThreadMessage } from "@assistant-ui/core";
5
+ import type { ReadonlyJSONValue } from "assistant-stream/utils";
6
+ import type { Statewire, StatewireClient, StatewireDocuments } from "statewire";
7
+ export declare const symbolStatewireExtras: unique symbol;
8
+ export declare const asStatewireExtras: (extras: unknown) => StatewireThread.Extras;
9
+ export declare const StatewireThread: <T>(options: StatewireThread.Options<T>) => ResourceElement<ClientOutput<"thread">>;
10
+ export declare namespace StatewireThread {
11
+ type UserCommands = Assistant.Commands[keyof Assistant.Commands];
12
+ export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;
13
+ /** A composer draft as persisted: the text plus the completed attachments. */
14
+ export type ComposerDraft = {
15
+ readonly text: string;
16
+ readonly attachments: readonly CompleteAttachment[];
17
+ };
18
+ /** Composer draft storage seam; `write` must persist synchronously in the caller's flow. */
19
+ export type ComposerStorage = {
20
+ read(): ComposerDraft | undefined;
21
+ write(draft: ComposerDraft): void;
22
+ clear(): void;
23
+ };
24
+ export type Extras = {
25
+ [symbolStatewireExtras]: true;
26
+ /** Dispatches the command; the promise settles with the accepted command's result payload, rejecting with `StatewireSendError` otherwise. */
27
+ sendCommand: (command: Command) => Promise<unknown>;
28
+ reconnect: () => void;
29
+ connection: StatewireClient.ConnectionState;
30
+ /** The mounted documents, or `undefined` on a transport without documents. */
31
+ documents: StatewireDocuments.Source | undefined;
32
+ /** Sends a statement on a negotiated protocol lane. */
33
+ invoke: (protocol: string, method: string, params: readonly unknown[]) => Promise<unknown>;
34
+ /** The converter's `state` when it returns one, else the replicated state. */
35
+ state: unknown;
36
+ status: ThreadStatus;
37
+ /** Negation of the server's broadcast idle level (a transport without idle is always busy). */
38
+ isBusy: boolean;
39
+ inputRequests: readonly InputRequestState[];
40
+ runs: Runs;
41
+ /** Re-dispatches the failed entry against the current thread and removes it; keyed by the entry's message id. */
42
+ retryFailed: (messageId: string) => void;
43
+ /** Removes the failed entry; keyed by the entry's message id. */
44
+ discardFailed: (messageId: string) => void;
45
+ /** Removes the failed entry and returns its text for the composer; keyed by the entry's message id. */
46
+ popFailed: (messageId: string) => string;
47
+ };
48
+ export type TextPart = {
49
+ readonly type: "text";
50
+ readonly text: string;
51
+ };
52
+ export type FilePart = {
53
+ readonly type: "file";
54
+ readonly mediaType: string;
55
+ readonly url: string;
56
+ readonly filename?: string;
57
+ };
58
+ export type UserMessage = {
59
+ readonly id: string;
60
+ readonly role: "user";
61
+ readonly parts: readonly (TextPart | FilePart)[];
62
+ readonly metadata?: Record<string, unknown>;
63
+ };
64
+ /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */
65
+ export type Placement = {
66
+ readonly insertAfter?: string | null;
67
+ readonly insertBefore?: string | null;
68
+ };
69
+ type RunSendCommand<TType extends "run/enqueue" | "run/steer"> = {
70
+ readonly type: TType;
71
+ /** The run this command targets — the live run's id, or a fresh client-minted uuid on run-creating sends. */
72
+ readonly runId: string;
73
+ } & ({
74
+ readonly message: UserMessage;
75
+ /** 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. */
76
+ readonly runAnchorMessageId?: string | null;
77
+ } | {
78
+ readonly messageId: string;
79
+ }) & Placement;
80
+ export type RunEnqueueCommand = RunSendCommand<"run/enqueue">;
81
+ export type RunSteerCommand = RunSendCommand<"run/steer">;
82
+ export type RunDequeueCommand = {
83
+ readonly type: "run/dequeue";
84
+ readonly runId: string;
85
+ readonly messageId: string;
86
+ };
87
+ export type RunEditCommand = {
88
+ readonly type: "run/edit";
89
+ /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */
90
+ readonly runId: string;
91
+ readonly message: UserMessage;
92
+ readonly sourceId: string;
93
+ /** Asserts `sourceId`'s parent — the rewind target; null names the root. */
94
+ readonly runAnchorMessageId: string | null;
95
+ };
96
+ export type RunContinueCommand = {
97
+ readonly type: "run/continue";
98
+ readonly runId?: string;
99
+ };
100
+ export type ToolCallInputRequest = {
101
+ readonly type: "tool-call";
102
+ readonly id: string;
103
+ readonly toolCallId: string;
104
+ };
105
+ export type ToolApprovalInputRequest = {
106
+ readonly type: "tool-approval";
107
+ readonly id: string;
108
+ readonly toolCallId: string;
109
+ };
110
+ export type CustomInputRequest = {
111
+ readonly type: string;
112
+ readonly id: string;
113
+ readonly [key: string]: ReadonlyJSONValue | undefined;
114
+ };
115
+ /** A host request parking the run until answered; open union for custom types. */
116
+ export type InputRequest = ToolCallInputRequest | ToolApprovalInputRequest | CustomInputRequest;
117
+ export type InputResponse = ReadonlyJSONValue;
118
+ export type RunInputCommand = {
119
+ readonly type: "run/input";
120
+ readonly runId?: string;
121
+ readonly requestId: string;
122
+ readonly response: InputResponse;
123
+ };
124
+ /** An input request projected out of the host state; a present `response` key marks the entry answered. */
125
+ export type InputRequestState = InputRequest & {
126
+ readonly response?: InputResponse;
127
+ /** The answer's `run/input` meta; absent when the answer carried none. */
128
+ readonly meta?: ReadonlyJSONValue;
129
+ };
130
+ /** 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). */
131
+ export type BranchMetadata = {
132
+ readonly id: number;
133
+ readonly siblings: readonly number[];
134
+ };
135
+ export type SwitchBranchCommand = {
136
+ readonly type: "message/switch-branch";
137
+ readonly branchId: number;
138
+ };
139
+ export type RunReloadCommand = {
140
+ readonly type: "run/reload";
141
+ /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */
142
+ readonly runId: string;
143
+ readonly sourceId: string;
144
+ /** Asserts `sourceId`'s parent — the rewind target; null names the root. */
145
+ readonly runAnchorMessageId: string | null;
146
+ };
147
+ export type RunCommand = RunEnqueueCommand | RunSteerCommand | RunDequeueCommand | RunEditCommand | RunContinueCommand | RunReloadCommand | RunInputCommand;
148
+ export type Command = RunCommand | UserCommands;
149
+ /** A queued message projected out of the host state, wire shape. */
150
+ export type RunQueueItem = {
151
+ readonly id: string;
152
+ readonly parts: readonly (TextPart | FilePart)[];
153
+ readonly metadata?: Record<string, unknown>;
154
+ };
155
+ /** Run subsystem status replicated by the host. */
156
+ export type RunStatus = "running" | "stopped" | "error" | "input-required";
157
+ /** 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. */
158
+ export type ThreadStatus = "loading" | "ready" | "evicted" | "disconnected" | RunStatus;
159
+ /** A queue-lane entry as replicated: the user message plus host-stamped `meta`. */
160
+ export type RunsQueueEntry = UserMessage & {
161
+ /** Host-stamped opaque per-entry metadata. */
162
+ readonly meta?: ReadonlyJSONValue;
163
+ };
164
+ /** A failed run send projected out of the retained lane: the entry shape plus its send failure. */
165
+ export type RunsFailedEntry = RunsQueueEntry & {
166
+ readonly sendFailure: StatewireClient.SendFailure;
167
+ };
168
+ /** An input outcome riding a dispatch record: the request with its response (null = abandoned) and `run/input` meta. */
169
+ export type RunsInputOutcome = {
170
+ readonly request: InputRequest;
171
+ readonly response: InputResponse | null;
172
+ readonly meta: ReadonlyJSONValue | null;
173
+ };
174
+ /** The dispatch record — the unapplied batch handed to the run; absent between applied and the next dispatch or take. */
175
+ export type RunsDispatch = {
176
+ readonly trigger: "message-send" | "message-edit" | "message-reload" | "input-resume" | "error-continue" | "stop-continue" | "steer";
177
+ readonly messages: readonly RunsQueueEntry[];
178
+ /** Present on rewind dispatches: truncate the thread at this id first; null names the root. */
179
+ readonly rollbackTo?: string | null;
180
+ /** The run-starting op's meta; present only when carried. */
181
+ readonly rootMeta?: ReadonlyJSONValue;
182
+ /** Present when input outcomes ride the dispatch; visible until applied. */
183
+ readonly inputOutcomes?: readonly RunsInputOutcome[];
184
+ };
185
+ /** The stopping window: present while a stop of the live run is underway; `"message-edit"` / `"message-reload"` pair with `nextDispatch`. */
186
+ export type RunsStopping = {
187
+ readonly reason: "stop" | "message-edit" | "message-reload";
188
+ };
189
+ /** The replicated run error — set on an unhandled failure, cleared by the next user-initiated run. */
190
+ export type RunsError = {
191
+ readonly message: string;
192
+ readonly [key: string]: ReadonlyJSONValue | undefined;
193
+ };
194
+ /** A replicated run entry — one element of the mount's `runs` array. */
195
+ export type RunState = {
196
+ /** 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. */
197
+ readonly runId: string | null;
198
+ /** Counts the entry's dispatches; a `run/stop` carrying a stale epoch rejects. */
199
+ readonly epoch?: number;
200
+ /** The reason carried by `run/stop`; persists through error/stop, cleared at the next dispatch. */
201
+ readonly stopReason?: string | null;
202
+ readonly status: RunStatus;
203
+ readonly queue: readonly RunsQueueEntry[];
204
+ readonly steerQueue: readonly RunsQueueEntry[];
205
+ /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */
206
+ readonly dispatching?: RunsDispatch;
207
+ readonly stopping?: RunsStopping;
208
+ /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */
209
+ readonly nextDispatch?: RunsDispatch;
210
+ /** The parked pending set; present only in input-required. */
211
+ readonly inputRequests?: readonly InputRequestState[];
212
+ /** Set only by an unhandled throw; cleared by the next user-initiated run. */
213
+ readonly error?: RunsError;
214
+ };
215
+ /** App-shaped effects `runsMaterialize` applies for the dispatch record. */
216
+ export type MaterializeEffects = {
217
+ /** Append one dispatched message to the app's committed message state. */
218
+ append: (message: RunsQueueEntry) => void;
219
+ /** Truncate to the rolled-back view first (null names the root); required for hosts that dispatch edits/reloads. */
220
+ rollback?: (to: string | null) => void;
221
+ };
222
+ /** The runs mount as replicated: the run entries plus the top-level status projection. */
223
+ export type RunsState = {
224
+ /** Projection of `runs[0]?.status ?? "ready"`. */
225
+ readonly status: "ready" | RunStatus;
226
+ /** At most one entry; empty while resting. */
227
+ readonly runs: readonly RunState[];
228
+ };
229
+ /** The run subsystem's typed read — `runs[0]` of the state with unsettled commands folded in, resting defaults while no entry is live. */
230
+ export type Runs = {
231
+ /** The live run's id — non-null whenever a run entry is live (running, input-required, error/stop); the target for `run/*` sends. */
232
+ readonly runId: string | null;
233
+ /** Counts the entry's dispatches; rides `run/stop` so a replayed stop cannot end a later leg. */
234
+ readonly epoch?: number;
235
+ /** The reason carried by `run/stop`; persists through error/stop, cleared at the next dispatch. */
236
+ readonly stopReason?: string | null;
237
+ readonly queue: readonly RunsQueueEntry[];
238
+ readonly steerQueue: readonly RunsQueueEntry[];
239
+ /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */
240
+ readonly dispatching?: RunsDispatch;
241
+ readonly stopping?: RunsStopping;
242
+ /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */
243
+ readonly nextDispatch?: RunsDispatch;
244
+ /** The parked pending set; present only in input-required. */
245
+ readonly inputRequests?: readonly InputRequestState[];
246
+ /** Set only by an unhandled throw; cleared by the next user-initiated run. */
247
+ readonly error?: RunsError;
248
+ /** Run sends retained after a non-accepted settle; retry, discard, or pop via the thread extras. */
249
+ readonly failed: readonly RunsFailedEntry[];
250
+ };
251
+ export type ConnectionMetadata = {
252
+ pendingCommands: Command[];
253
+ isSending: boolean;
254
+ /** Statewire connection status; local transports are always `connected`. */
255
+ connection: StatewireClient.ConnectionState;
256
+ /** The typed runs read. */
257
+ runs: Runs;
258
+ documents: StatewireDocuments.Source | undefined;
259
+ /** The mounted documents as of this pass; a new map whenever one changes. */
260
+ mounted: ReadonlyMap<number, StatewireDocuments.Document>;
261
+ invoke: (protocol: string, method: string, params: readonly unknown[]) => Promise<unknown>;
262
+ };
263
+ /** Converter output: app-owned keys only — the lib projects the run mounts itself; `state` replaces the replicated state on the extras and thread. */
264
+ export type State = {
265
+ readonly messages: readonly ThreadMessage[];
266
+ readonly state?: ReadonlyJSONValue;
267
+ };
268
+ export type StateConverter<T> = (state: T, connectionMetadata: ConnectionMetadata) => State;
288
269
  /**
289
- * "command-send" mirrors the client's ambient model context (system,
290
- * tools, callSettings, config) to native protocol context, restored on
291
- * each attachment and updated whenever it changes.
270
+ * Payload of the built-in `run/stop` command. `reason` is the one well-known
271
+ * field; apps extend it with their own JSON-serializable fields.
292
272
  */
293
- contextSync?: "command-send" | undefined;
294
- /** Supplies the `run/stop` command's payload; omitted, stop sends no payload. */
295
- stopPayload?: (() => StopPayload) | undefined;
296
- /** Observes each command's lifecycle (queued, posted, applied, settled); runs after the built-in pending-command retirement. */
297
- onCommandChange?: ((update: Statewire.CommandUpdate<Record<string, (...args: any[]) => unknown>>, ctx: {
298
- state: NonNullable<T>;
299
- }) => void) | undefined;
300
- /** Observes the transport state: fires with the attach snapshot, then once per change. */
301
- onStateChange?: ((state: NonNullable<T>, ctx: {
302
- changes: Statewire.Changes;
303
- }) => void) | undefined;
304
- /** Observes connection status transitions, starting with the initial status. */
305
- onConnectionChange?: ((connection: StatewireClient.Connection) => void) | undefined;
306
- onError?: ((error: Error) => void) | undefined;
307
- capabilities?: {
308
- edit?: boolean | undefined;
309
- /** The host supports `run/continue` (a continue affordance on aborted runs). */
310
- continue?: boolean | undefined;
311
- /** The host supports `run/reload` (regenerating an assistant message). */
312
- reload?: boolean | undefined;
313
- /** The host supports `message/switch-branch` (thread-global branch switching driven by `metadata.custom.branch`). */
314
- unstable_switchBranch?: boolean | undefined;
315
- } | undefined;
316
- /**
317
- * Durable drafts: the mounted composer storage restores on mount, mirrors
318
- * every change, and clears when the draft is consumed. The session storage
319
- * holds this thread's lane identity and its un-durable commands, which
320
- * resend under their original seqs on the next mount.
321
- */
322
- storage?: {
323
- composer?: ResourceElement<ComposerStorage> | undefined;
324
- session?: ResourceElement<StatewireClient.SessionStorage> | undefined;
325
- } | undefined;
326
- adapters?: {
327
- attachments?: AttachmentAdapter | undefined;
328
- speech?: SpeechSynthesisAdapter | undefined;
329
- feedback?: FeedbackAdapter | undefined;
330
- } | undefined;
331
- };
332
- export {};
273
+ export type StopPayload = {
274
+ readonly reason?: string | undefined;
275
+ readonly [key: string]: ReadonlyJSONValue | undefined;
276
+ };
277
+ export type Options<T> = {
278
+ transport: Transport<T>;
279
+ /** 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. */
280
+ initialState: T;
281
+ /** Application protocol for optimistic commands; must match the transport's protocol. */
282
+ protocol?: string | undefined;
283
+ converter: StateConverter<T>;
284
+ /** Folds app-owned keys for an unsettled command into the draft; runs after the lib's run-dialect reducer. */
285
+ optimistic?: StatewireClient.Optimistic<T, Record<string, (...args: any[]) => unknown>> | undefined;
286
+ /** Makes dispatch records concrete in the draft (runs after the optimistic folds); without it, dispatch limbo stays out of `messages`. */
287
+ materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;
288
+ /**
289
+ * "command-send" mirrors the client's ambient model context (system,
290
+ * tools, callSettings, config) to native protocol context, restored on
291
+ * each attachment and updated whenever it changes.
292
+ */
293
+ contextSync?: "command-send" | undefined;
294
+ /** Supplies the `run/stop` command's payload; omitted, stop sends no payload. */
295
+ stopPayload?: (() => StopPayload) | undefined;
296
+ /** Observes each command's lifecycle (queued, posted, applied, settled); runs after the built-in pending-command retirement. */
297
+ onCommandChange?: ((update: Statewire.CommandUpdate<Record<string, (...args: any[]) => unknown>>, ctx: {
298
+ state: NonNullable<T>;
299
+ }) => void) | undefined;
300
+ /** Observes the transport state: fires with the attach snapshot, then once per change. */
301
+ onStateChange?: ((state: NonNullable<T>, ctx: {
302
+ changes: Statewire.Changes;
303
+ }) => void) | undefined;
304
+ /** Observes connection status transitions, starting with the initial status. */
305
+ onConnectionChange?: ((connection: StatewireClient.Connection) => void) | undefined;
306
+ onError?: ((error: Error) => void) | undefined;
307
+ capabilities?: {
308
+ edit?: boolean | undefined;
309
+ /** The host supports `run/continue` (a continue affordance on aborted runs). */
310
+ continue?: boolean | undefined;
311
+ /** The host supports `run/reload` (regenerating an assistant message). */
312
+ reload?: boolean | undefined;
313
+ /** The host supports `message/switch-branch` (thread-global branch switching driven by `metadata.custom.branch`). */
314
+ unstable_switchBranch?: boolean | undefined;
315
+ } | undefined;
316
+ /**
317
+ * Durable drafts: the mounted composer storage restores on mount, mirrors
318
+ * every change, and clears when the draft is consumed. The session storage
319
+ * holds this thread's lane identity and its un-durable commands, which
320
+ * resend under their original seqs on the next mount.
321
+ */
322
+ storage?: {
323
+ composer?: ResourceElement<ComposerStorage> | undefined;
324
+ session?: ResourceElement<StatewireClient.SessionStorage> | undefined;
325
+ } | undefined;
326
+ adapters?: {
327
+ attachments?: AttachmentAdapter | undefined;
328
+ speech?: SpeechSynthesisAdapter | undefined;
329
+ feedback?: FeedbackAdapter | undefined;
330
+ } | undefined;
331
+ };
332
+ export {};
333
333
  }
334
334
  declare module "@assistant-ui/core" {
335
- namespace Assistant {
336
- interface Commands {
337
- runEnqueue: StatewireThread.RunEnqueueCommand;
338
- runSteer: StatewireThread.RunSteerCommand;
339
- runDequeue: StatewireThread.RunDequeueCommand;
340
- runEdit: StatewireThread.RunEditCommand;
341
- runContinue: StatewireThread.RunContinueCommand;
342
- runReload: StatewireThread.RunReloadCommand;
343
- runInput: StatewireThread.RunInputCommand;
344
- messageSwitchBranch: StatewireThread.SwitchBranchCommand;
335
+ namespace Assistant {
336
+ interface Commands {
337
+ runEnqueue: StatewireThread.RunEnqueueCommand;
338
+ runSteer: StatewireThread.RunSteerCommand;
339
+ runDequeue: StatewireThread.RunDequeueCommand;
340
+ runEdit: StatewireThread.RunEditCommand;
341
+ runContinue: StatewireThread.RunContinueCommand;
342
+ runReload: StatewireThread.RunReloadCommand;
343
+ runInput: StatewireThread.RunInputCommand;
344
+ messageSwitchBranch: StatewireThread.SwitchBranchCommand;
345
+ }
345
346
  }
346
- }
347
347
  }
348
- //#endregion
349
- export { StatewireThread, asStatewireExtras, symbolStatewireExtras };
350
348
  //# sourceMappingURL=StatewireThread.d.ts.map