@assistant-ui/react-statewire 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/types.d.ts CHANGED
@@ -22,8 +22,8 @@ type AssistantMessage = {
22
22
  readonly role: "assistant";
23
23
  readonly parts: readonly TextPart[];
24
24
  };
25
- type MessageAddCommand = {
26
- readonly type: "message/add";
25
+ type AddMessageCommand = {
26
+ readonly type: "add-message";
27
27
  readonly message: UserMessage | AssistantMessage;
28
28
  readonly parentId: string | null;
29
29
  readonly sourceId: string | null;
@@ -34,8 +34,8 @@ type MessageAddCommand = {
34
34
  */
35
35
  readonly behavior?: "queue" | "steer";
36
36
  };
37
- type ToolResultAddCommand = {
38
- readonly type: "tool-result/add";
37
+ type AddToolResultCommand = {
38
+ readonly type: "add-tool-result";
39
39
  readonly toolCallId: string;
40
40
  readonly toolName: string;
41
41
  readonly result: ReadonlyJSONValue;
@@ -43,11 +43,118 @@ type ToolResultAddCommand = {
43
43
  readonly artifact?: ReadonlyJSONValue;
44
44
  readonly modelContent?: readonly ToolModelContentPart[];
45
45
  };
46
- type AssistantTransportCommand = MessageAddCommand | ToolResultAddCommand | UserCommands;
46
+ type FilePart = {
47
+ readonly type: "file";
48
+ readonly mediaType: string;
49
+ readonly url: string;
50
+ readonly filename?: string;
51
+ };
52
+ type RunUserMessage = {
53
+ readonly id: string;
54
+ readonly role: "user";
55
+ readonly parts: readonly (TextPart | FilePart)[];
56
+ readonly metadata?: Record<string, unknown>;
57
+ };
58
+ /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */
59
+ type RunPlacement = {
60
+ readonly insertAfter?: string | null;
61
+ readonly insertBefore?: string | null;
62
+ };
63
+ type RunEnqueueCommand = {
64
+ readonly type: "run/enqueue";
65
+ } & ({
66
+ readonly message: RunUserMessage;
67
+ } | {
68
+ readonly messageId: string;
69
+ }) & RunPlacement;
70
+ type RunSteerCommand = {
71
+ readonly type: "run/steer";
72
+ } & ({
73
+ readonly message: RunUserMessage;
74
+ } | {
75
+ readonly messageId: string;
76
+ }) & RunPlacement;
77
+ type RunDequeueCommand = {
78
+ readonly type: "run/dequeue";
79
+ readonly messageId: string;
80
+ };
81
+ type RunEditCommand = {
82
+ readonly type: "run/edit";
83
+ readonly message: RunUserMessage;
84
+ readonly sourceId: string;
85
+ };
86
+ type RunContinueCommand = {
87
+ readonly type: "run/continue";
88
+ };
89
+ type ToolCallInputRequest = {
90
+ readonly type: "tool-call";
91
+ readonly id: string;
92
+ readonly toolCallId: string;
93
+ };
94
+ type ToolApprovalInputRequest = {
95
+ readonly type: "tool-approval";
96
+ readonly id: string;
97
+ readonly toolCallId: string;
98
+ };
99
+ type CustomInputRequest = {
100
+ readonly type: string;
101
+ readonly id: string;
102
+ readonly [key: string]: ReadonlyJSONValue | undefined;
103
+ };
104
+ /** A host request parking the run until answered; open union for custom types. */
105
+ type InputRequest = ToolCallInputRequest | ToolApprovalInputRequest | CustomInputRequest;
106
+ type ToolCallInputResponse = {
107
+ readonly output: ReadonlyJSONValue;
108
+ /** Default false; when true, `output` carries the error payload. */
109
+ readonly isError?: boolean;
110
+ readonly artifact?: ReadonlyJSONValue;
111
+ };
112
+ type ToolApprovalInputResponse = {
113
+ readonly decision: "approve" | "reject" | "edit" | "respond";
114
+ readonly editedArgs?: ReadonlyJSONValue;
115
+ readonly message?: string;
116
+ };
117
+ type InputResponse = ReadonlyJSONValue;
118
+ type RunInputCommand = {
119
+ readonly type: "run/input";
120
+ readonly requestId: string;
121
+ readonly response: InputResponse;
122
+ };
123
+ /** An input request projected out of the host state with its response echo. */
124
+ type InputRequestState = InputRequest & {
125
+ readonly response: InputResponse | null;
126
+ };
127
+ type RunReloadCommand = {
128
+ readonly type: "run/reload";
129
+ readonly sourceId: string;
130
+ };
131
+ type RunCommand = RunEnqueueCommand | RunSteerCommand | RunDequeueCommand | RunEditCommand | RunContinueCommand | RunReloadCommand | RunInputCommand;
132
+ type AssistantTransportCommand = AddMessageCommand | AddToolResultCommand | RunCommand | UserCommands;
133
+ /** A queued message projected out of the host state, wire shape. */
134
+ type RunQueueItem = {
135
+ readonly id: string;
136
+ readonly parts: readonly (TextPart | FilePart)[];
137
+ };
47
138
  type AssistantTransportState = {
48
139
  readonly messages: readonly ThreadMessage[];
49
140
  readonly state?: ReadonlyJSONValue;
50
141
  readonly isRunning: boolean;
142
+ /**
143
+ * The host's regular queue lane projected out of the state. Returning it
144
+ * (even empty) turns on the server-side queue: sends become `run/enqueue`
145
+ * / `run/steer` commands and item controls send the `run/*` queue
146
+ * commands. Presence must be stable across conversions and excludes the
147
+ * client-local `capabilities.queue` buffer.
148
+ */
149
+ readonly queue?: readonly RunQueueItem[];
150
+ /** The host's steer lane; requires `queue`. Absent means empty. */
151
+ readonly steerQueue?: readonly RunQueueItem[];
152
+ /**
153
+ * The host's parked input requests projected out of the state. Returning it
154
+ * (even empty) routes tool results and approvals with a matching pending
155
+ * request through `run/input`. Presence must be stable across conversions.
156
+ */
157
+ readonly inputRequests?: readonly InputRequestState[];
51
158
  };
52
159
  type AssistantTransportConnectionMetadata = {
53
160
  pendingCommands: AssistantTransportCommand[];
@@ -98,13 +205,16 @@ type AssistantTransportOptions<T> = {
98
205
  /**
99
206
  * Buffer messages sent during a run in an in-memory queue and dispatch
100
207
  * them once the run settles. Steering interrupts the active run.
208
+ * Mutually exclusive with the converter's `queue` projection.
101
209
  */
102
210
  queue?: boolean | undefined;
211
+ /** The host supports `run/continue` (a continue affordance on aborted runs). */
212
+ continue?: boolean | undefined;
103
213
  } | undefined;
104
214
  adapters?: {
105
215
  attachments?: AttachmentAdapter | undefined;
106
216
  } | undefined;
107
217
  };
108
218
  //#endregion
109
- export { AssistantMessage, AssistantTransportCommand, AssistantTransportConnectionMetadata, AssistantTransportOptions, AssistantTransportProtocol, AssistantTransportState, AssistantTransportStateConverter, HeadersValue, ImagePart, MessageAddCommand, SendCommandsRequestBody, TextPart, ToolResultAddCommand, UserCommands, UserExternalState, UserMessage, UserMessagePart };
219
+ export { AddMessageCommand, AddToolResultCommand, AssistantMessage, AssistantTransportCommand, AssistantTransportConnectionMetadata, AssistantTransportOptions, AssistantTransportProtocol, AssistantTransportState, AssistantTransportStateConverter, CustomInputRequest, FilePart, HeadersValue, ImagePart, InputRequest, InputRequestState, InputResponse, RunCommand, RunContinueCommand, RunDequeueCommand, RunEditCommand, RunEnqueueCommand, RunInputCommand, RunPlacement, RunQueueItem, RunReloadCommand, RunSteerCommand, RunUserMessage, SendCommandsRequestBody, TextPart, ToolApprovalInputRequest, ToolApprovalInputResponse, ToolCallInputRequest, ToolCallInputResponse, UserCommands, UserExternalState, UserMessage, UserMessagePart };
110
220
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","names":[],"sources":["../src/types.ts"],"mappings":";;;;;KAWY,eAAe,UAAU,eAAe,UAAU;KAClD,0BAA0B,UAAU,8BAC5C,0BACA,UAAU,oBAAoB,UAAU;KAEhC;WACD;WACA;;KAGC;WACD;WACA;;KAGC,kBAAkB,WAAW;KAE7B;WACD;WACA,gBAAgB;;KAGf;WACD;WACA,gBAAgB;;KAGf;WACD;WACA,SAAS,cAAc;WACvB;WACA;;;;;;WAMA;;KAGC;WACD;WACA;WACA;WACA,QAAQ;WACR;WACA,WAAW;WACX,wBAAwB;;KAGvB,4BACR,oBACA,uBACA;KAEQ;WACD,mBAAmB;WACnB,QAAQ;WACR;;KAGC;EACV,iBAAiB;EACjB;EACA,cAAc,eAAe;;KAGnB,iCAAiC,MAC3C,OAAO,GACP,oBAAoB,yCACjB;KAEO,eAAe,yBAAyB;KAExC;KAEA;EACV,UAAU;EACV;EACA;EACA,OAAO;EACP,cAAc;EACd,QAAQ;EACR;EACA;GACC;;KAGS,0BAA0B;EACpC,cAAc;EACd,WAAW,iCAAiC;EAC5C;EACA;EACA,WAAW;EACX,SAAS,sBAAsB,QAAQ;EACvC,uBAAuB;;EAEvB,+BAEM,MAAM,4BACH,0BAA0B,QAAQ;EAE3C,eAAe,UAAU;EACzB;EACA,YAEM,OAAO,OACP;IACE,UAAU;IACV,cAAc,UAAU,OAAO,MAAM;eAE7B;;;;;EAMhB,aACM;IACA,UAAU;IACV,cAAc,UAAU,OAAO,MAAM;IACrC,QAAQ;;EAGd;IAEM;;;;;IAKA;;EAGN;IAEM,cAAc"}
1
+ {"version":3,"file":"types.d.ts","names":[],"sources":["../src/types.ts"],"mappings":";;;;;KAWY,eAAe,UAAU,eAAe,UAAU;KAClD,0BAA0B,UAAU,8BAC5C,0BACA,UAAU,oBAAoB,UAAU;KAEhC;WACD;WACA;;KAGC;WACD;WACA;;KAGC,kBAAkB,WAAW;KAE7B;WACD;WACA,gBAAgB;;KAGf;WACD;WACA,gBAAgB;;KAGf;WACD;WACA,SAAS,cAAc;WACvB;WACA;;;;;;WAMA;;KAGC;WACD;WACA;WACA;WACA,QAAQ;WACR;WACA,WAAW;WACX,wBAAwB;;KAGvB;WACD;WACA;WACA;WACA;;KAGC;WACD;WACA;WACA,iBAAiB,WAAW;WAC5B,WAAW;;;KAIV;WACD;WACA;;KAGC;WACD;;WACK,SAAS;;WAA8B;KACrD;KAEU;WACD;;WACK,SAAS;;WAA8B;KACrD;KAEU;WACD;WACA;;KAGC;WACD;WACA,SAAS;WACT;;KAGC;WACD;;KAGC;WACD;WACA;WACA;;KAGC;WACD;WACA;WACA;;KAGC;WACD;WACA;YACC,cAAc;;;KAId,eACR,uBACA,2BACA;KAEQ;WACD,QAAQ;;WAER;WACA,WAAW;;KAGV;WACD;WACA,aAAa;WACb;;KAGC,gBAAgB;KAEhB;WACD;WACA;WACA,UAAU;;;KAIT,oBAAoB;WACrB,UAAU;;KAGT;WACD;WACA;;KAGC,aACR,oBACA,kBACA,oBACA,iBACA,qBACA,mBACA;KAEQ,4BACR,oBACA,uBACA,aACA;;KAGQ;WACD;WACA,iBAAiB,WAAW;;KAG3B;WACD,mBAAmB;WACnB,QAAQ;WACR;;;;;;;;WAQA,iBAAiB;;WAEjB,sBAAsB;;;;;;WAMtB,yBAAyB;;KAGxB;EACV,iBAAiB;EACjB;EACA,cAAc,eAAe;;KAGnB,iCAAiC,MAC3C,OAAO,GACP,oBAAoB,yCACjB;KAEO,eAAe,yBAAyB;KAExC;KAEA;EACV,UAAU;EACV;EACA;EACA,OAAO;EACP,cAAc;EACd,QAAQ;EACR;EACA;GACC;;KAGS,0BAA0B;EACpC,cAAc;EACd,WAAW,iCAAiC;EAC5C;EACA;EACA,WAAW;EACX,SAAS,sBAAsB,QAAQ;EACvC,uBAAuB;;EAEvB,+BAEM,MAAM,4BACH,0BAA0B,QAAQ;EAE3C,eAAe,UAAU;EACzB;EACA,YAEM,OAAO,OACP;IACE,UAAU;IACV,cAAc,UAAU,OAAO,MAAM;eAE7B;;;;;EAMhB,aACM;IACA,UAAU;IACV,cAAc,UAAU,OAAO,MAAM;IACrC,QAAQ;;EAGd;IAEM;;;;;;IAMA;;IAEA;;EAGN;IAEM,cAAc"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@assistant-ui/react-statewire",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "assistant-ui thread binding for statewire backends",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -21,6 +21,7 @@ import type {
21
21
  AppendMessage,
22
22
  MessageQueueController,
23
23
  MessageQueueDriver,
24
+ RespondToToolApprovalOptions,
24
25
  ResumeToolCallOptions,
25
26
  ThreadMessage,
26
27
  ToolExecutionStatus,
@@ -36,12 +37,20 @@ import type {
36
37
  HostRunContext,
37
38
  SendOptions,
38
39
  } from "./host";
40
+ import {
41
+ createRunQueueAdapter,
42
+ resolveReloadCommand,
43
+ toWireMessage,
44
+ } from "./runCommands";
45
+ import {
46
+ resolveToolApprovalInput,
47
+ resolveToolResultInput,
48
+ } from "./inputRequests";
39
49
  import type {
40
- MessageAddCommand,
41
- ToolResultAddCommand,
50
+ AddToolResultCommand,
42
51
  AssistantTransportCommand,
43
52
  AssistantTransportOptions,
44
- UserMessagePart,
53
+ InputRequestState,
45
54
  } from "./types";
46
55
 
47
56
  const EMPTY_TOOL_STATUSES: Record<string, ToolExecutionStatus> = {};
@@ -57,6 +66,8 @@ export type AssistantTransportExtras = {
57
66
  sendCommand: (command: AssistantTransportCommand) => void;
58
67
  reconnect: () => void;
59
68
  state: unknown;
69
+ /** The host's parked input requests; absent when the converter does not project them. */
70
+ inputRequests?: readonly InputRequestState[];
60
71
  };
61
72
 
62
73
  export const asAssistantTransportExtras = (
@@ -74,38 +85,6 @@ export const asAssistantTransportExtras = (
74
85
  return extras as AssistantTransportExtras;
75
86
  };
76
87
 
77
- export const convertAppendMessageToCommand = (
78
- message: AppendMessage,
79
- ): MessageAddCommand | null => {
80
- if (message.role !== "user")
81
- throw new Error("Only user messages are supported");
82
-
83
- const parts: UserMessagePart[] = [];
84
- const content = [
85
- ...message.content,
86
- ...(message.attachments?.flatMap((a) => a.content) ?? []),
87
- ];
88
- for (const contentPart of content) {
89
- if (contentPart.type === "text") {
90
- parts.push({ type: "text", text: contentPart.text });
91
- } else if (contentPart.type === "image") {
92
- parts.push({ type: "image", image: contentPart.image });
93
- }
94
- }
95
-
96
- if (parts.length === 0) return null;
97
-
98
- return {
99
- type: "message/add",
100
- message: {
101
- role: "user",
102
- parts,
103
- },
104
- parentId: message.parentId,
105
- sourceId: message.sourceId,
106
- };
107
- };
108
-
109
88
  const messagesContainToolCall = (
110
89
  messages: readonly ThreadMessage[],
111
90
  toolCallId: string,
@@ -184,7 +163,11 @@ const useAssistantTransportThread = (
184
163
  const messages = convertedRef.current
185
164
  .messages as readonly ThreadMessage[];
186
165
  if (!messagesContainToolCall(messages, command.toolCallId)) return;
187
- dispatch({ ...command, type: "tool-result/add" });
166
+ const requests = convertedRef.current.inputRequests;
167
+ dispatch(
168
+ (requests && resolveToolResultInput(requests, command)) ??
169
+ command,
170
+ );
188
171
  },
189
172
  onStatusesChange: (statuses) => {
190
173
  setToolStatuses(
@@ -211,25 +194,37 @@ const useAssistantTransportThread = (
211
194
  [toolInvocations],
212
195
  );
213
196
 
197
+ const inputRequests = converted.inputRequests;
198
+ const [inputSeam] = useState(() => ({
199
+ present: inputRequests !== undefined,
200
+ }));
201
+ if (inputSeam.present !== (inputRequests !== undefined))
202
+ throw new Error(
203
+ "statewire: the converter's inputRequests projection must be stable — it was " +
204
+ (inputSeam.present ? "defined" : "undefined") +
205
+ " on first convert and changed since",
206
+ );
207
+
214
208
  const extras = useMemo(
215
209
  (): AssistantTransportExtras => ({
216
210
  [symbolAssistantTransportExtras]: true,
217
211
  sendCommand: dispatch,
218
212
  reconnect: connection.reconnect,
219
213
  state: agentState,
214
+ ...(inputRequests !== undefined && { inputRequests }),
220
215
  }),
221
- [dispatch, connection.reconnect, agentState],
216
+ [dispatch, connection.reconnect, agentState, inputRequests],
222
217
  );
223
218
 
224
219
  const handleAppend = (message: AppendMessage) => {
225
220
  const startRun = message.startRun ?? message.role === "user";
226
- const command = convertAppendMessageToCommand(message);
221
+ const command: AssistantTransportCommand = {
222
+ type: "run/steer",
223
+ message: toWireMessage(message, crypto.randomUUID()),
224
+ };
227
225
  void commands.setParentId(message.parentId).catch(() => {});
228
226
 
229
- const send = () => {
230
- if (!command) return;
231
- dispatch(command, { schedule: startRun });
232
- };
227
+ const send = () => dispatch(command, { schedule: startRun });
233
228
  if (startRun) {
234
229
  // abort in-flight tool executions so their late results cannot race the new turn
235
230
  void toolInvocations.abort().then(send);
@@ -238,6 +233,17 @@ const useAssistantTransportThread = (
238
233
  }
239
234
  };
240
235
 
236
+ const handleEdit = (message: AppendMessage) => {
237
+ if (message.sourceId == null)
238
+ throw new Error("statewire: run/edit requires a sourceId");
239
+ const command: AssistantTransportCommand = {
240
+ type: "run/edit",
241
+ message: toWireMessage(message, crypto.randomUUID()),
242
+ sourceId: message.sourceId,
243
+ };
244
+ void toolInvocations.abort().then(() => dispatch(command));
245
+ };
246
+
241
247
  const handleCancel = () => {
242
248
  void toolInvocations.abort();
243
249
  void commands.cancel().catch(() => {});
@@ -258,6 +264,33 @@ const useAssistantTransportThread = (
258
264
  cancel: handleCancel,
259
265
  };
260
266
 
267
+ const queueProjection = converted.queue;
268
+ const steerProjection = converted.steerQueue;
269
+ if (steerProjection !== undefined && queueProjection === undefined)
270
+ throw new Error(
271
+ "statewire: the converter's steerQueue projection requires the queue projection",
272
+ );
273
+ if (queueProjection !== undefined && options.capabilities?.queue)
274
+ throw new Error(
275
+ "statewire: the converter's queue projection excludes capabilities.queue",
276
+ );
277
+ const [queueSeam] = useState(() => ({
278
+ present: queueProjection !== undefined,
279
+ }));
280
+ if (queueSeam.present !== (queueProjection !== undefined))
281
+ throw new Error(
282
+ "statewire: the converter's queue projection must be stable — it was " +
283
+ (queueSeam.present ? "defined" : "undefined") +
284
+ " on first convert and changed since",
285
+ );
286
+ const serverQueue = useMemo(
287
+ () =>
288
+ queueProjection
289
+ ? createRunQueueAdapter(queueProjection, steerProjection, dispatch)
290
+ : undefined,
291
+ [queueProjection, steerProjection, dispatch],
292
+ );
293
+
261
294
  const enableQueue = options.capabilities?.queue === true;
262
295
  const queueRef = useRef<MessageQueueController | null>(null);
263
296
  if (enableQueue && !queueRef.current) {
@@ -306,18 +339,22 @@ const useAssistantTransportThread = (
306
339
  extras,
307
340
  attachmentAdapter: options.adapters?.attachments,
308
341
  onNew: handleAppend,
309
- ...(messageQueue && {
310
- queue: {
311
- ...messageQueue.adapter,
312
- items: queueItems,
313
- steerItems: steerQueueItems,
314
- },
315
- }),
316
- ...(options.capabilities?.edit && { onEdit: handleAppend }),
342
+ ...(serverQueue
343
+ ? { queue: serverQueue }
344
+ : messageQueue && {
345
+ queue: {
346
+ ...messageQueue.adapter,
347
+ items: queueItems,
348
+ steerItems: steerQueueItems,
349
+ },
350
+ }),
351
+ ...(options.capabilities?.edit && { onEdit: handleEdit }),
317
352
  onReload: (parentId: string | null) => {
318
- void toolInvocations.abort().then(() => {
319
- void commands.reload(parentId).catch(() => {});
320
- });
353
+ const command = resolveReloadCommand(
354
+ convertedRef.current.messages,
355
+ parentId,
356
+ );
357
+ void toolInvocations.abort().then(() => dispatch(command));
321
358
  },
322
359
  onCancel: () => {
323
360
  // user cancel drops pending lanes; a steer interrupt (driver.cancel) keeps them
@@ -325,13 +362,24 @@ const useAssistantTransportThread = (
325
362
  handleCancel();
326
363
  },
327
364
  onResume: () => {
365
+ if (options.capabilities?.continue) {
366
+ dispatch({ type: "run/continue" });
367
+ return;
368
+ }
328
369
  if (!options.resumeApi)
329
370
  throw new Error("Must pass resumeApi to options to resume runs");
330
371
  void commands.resume().catch(() => {});
331
372
  },
332
373
  onAddToolResult: (toolOptions: AddToolResultOptions) => {
333
- const command: ToolResultAddCommand = {
334
- type: "tool-result/add",
374
+ const requests = convertedRef.current.inputRequests;
375
+ const inputCommand =
376
+ requests && resolveToolResultInput(requests, toolOptions);
377
+ if (inputCommand) {
378
+ dispatch(inputCommand);
379
+ return;
380
+ }
381
+ const command: AddToolResultCommand = {
382
+ type: "add-tool-result",
335
383
  toolCallId: toolOptions.toolCallId,
336
384
  result: toolOptions.result as ReadonlyJSONObject,
337
385
  toolName: toolOptions.toolName,
@@ -344,6 +392,15 @@ const useAssistantTransportThread = (
344
392
 
345
393
  dispatch(command);
346
394
  },
395
+ ...(inputRequests !== undefined && {
396
+ onRespondToToolApproval: (options: RespondToToolApprovalOptions) =>
397
+ dispatch(
398
+ resolveToolApprovalInput(
399
+ convertedRef.current.inputRequests!,
400
+ options,
401
+ ),
402
+ ),
403
+ }),
347
404
  onResumeToolCall: ({ toolCallId, payload }: ResumeToolCallOptions) => {
348
405
  if (!toolInvocations.resume(toolCallId, payload))
349
406
  throw new Error(`Tool call ${toolCallId} is not waiting for resume.`);