@assistant-ui/react-statewire 0.1.0 → 0.2.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.
@@ -11,13 +11,15 @@ import type { ClientOutput } from "@assistant-ui/store";
11
11
  import type {
12
12
  AppendMessage,
13
13
  AttachmentAdapter,
14
+ ExternalThreadQueueAdapter,
14
15
  ModelContext,
16
+ QueuePlacement,
15
17
  ThreadMessage,
16
18
  } from "@assistant-ui/core";
17
19
  import { toToolsJSONSchema } from "assistant-stream";
18
20
  import type { ReadonlyJSONValue } from "assistant-stream/utils";
19
21
  import { useStatewire } from "statewire";
20
- import type { Statewire } from "statewire";
22
+ import type { Statewire, StatewireClient } from "statewire";
21
23
  import {
22
24
  convertAppendMessageToCommand,
23
25
  symbolAssistantTransportExtras,
@@ -30,10 +32,7 @@ type AnyCommands = Record<string, (...args: any[]) => unknown>;
30
32
  const ambientContextOf = (context: ModelContext): Record<string, unknown> => ({
31
33
  ...(context.system !== undefined && { system: context.system }),
32
34
  ...(context.tools !== undefined && {
33
- // cast: core >=0.3.5 widens tool generics beyond assistant-stream's Tool
34
- tools: toToolsJSONSchema(
35
- context.tools as unknown as Parameters<typeof toToolsJSONSchema>[0],
36
- ),
35
+ tools: toToolsJSONSchema(context.tools),
37
36
  }),
38
37
  ...(context.callSettings !== undefined && {
39
38
  callSettings: context.callSettings,
@@ -41,19 +40,120 @@ const ambientContextOf = (context: ModelContext): Record<string, unknown> => ({
41
40
  ...(context.config !== undefined && { config: context.config }),
42
41
  });
43
42
 
43
+ const toWireMessage = (
44
+ message: AppendMessage,
45
+ id: string,
46
+ ): StatewireThread.UserMessage => {
47
+ if (message.role !== "user")
48
+ throw new Error("statewire: only user messages are supported");
49
+ const files: StatewireThread.FilePart[] = [];
50
+ const texts: string[] = [];
51
+ const source = [
52
+ ...message.content,
53
+ ...(message.attachments?.flatMap((a) => a.content) ?? []),
54
+ ];
55
+ for (const part of source) {
56
+ if (part.type === "text") {
57
+ texts.push(part.text);
58
+ } else if (part.type === "image") {
59
+ files.push({ type: "file", mediaType: "image/*", url: part.image });
60
+ } else if (part.type === "file") {
61
+ files.push({
62
+ type: "file",
63
+ mediaType: part.mimeType,
64
+ url: part.data,
65
+ ...(part.filename !== undefined && { filename: part.filename }),
66
+ });
67
+ } else {
68
+ throw new Error(`statewire: unsupported message part "${part.type}"`);
69
+ }
70
+ }
71
+ // default-safe against host capabilities: files first, one merged text part
72
+ const parts: (StatewireThread.TextPart | StatewireThread.FilePart)[] = [
73
+ ...files,
74
+ ...(texts.length > 0
75
+ ? [{ type: "text" as const, text: texts.join("\n\n") }]
76
+ : []),
77
+ ];
78
+ if (parts.length === 0)
79
+ throw new Error("statewire: cannot send an empty message");
80
+ return { id, role: "user", parts };
81
+ };
82
+
83
+ const toQueueItemState = (item: StatewireThread.QueueItem) => ({
84
+ id: item.id,
85
+ prompt: item.parts
86
+ .flatMap((part) => (part.type === "text" ? [part.text] : []))
87
+ .join("\n\n"),
88
+ parts: item.parts.map((part) =>
89
+ part.type === "text"
90
+ ? part
91
+ : {
92
+ type: "file" as const,
93
+ data: part.url,
94
+ mimeType: part.mediaType,
95
+ ...(part.filename !== undefined && { filename: part.filename }),
96
+ },
97
+ ),
98
+ });
99
+
100
+ const placementFields = (placement: QueuePlacement) => ({
101
+ ...(placement.insertAfter !== undefined && {
102
+ insertAfter: placement.insertAfter,
103
+ }),
104
+ ...(placement.insertBefore !== undefined && {
105
+ insertBefore: placement.insertBefore,
106
+ }),
107
+ });
108
+
109
+ const withSessionLostFallback = (
110
+ transport: StatewireThread.Transport<any>,
111
+ latest: { current: StatewireThread.Options<any> },
112
+ ): StatewireThread.Transport<any> => {
113
+ const [transportOptions, ...rest] = transport.args as [
114
+ Record<string, unknown>,
115
+ ...unknown[],
116
+ ];
117
+ if (
118
+ rest.length > 0 ||
119
+ typeof transportOptions !== "object" ||
120
+ transportOptions === null
121
+ ) {
122
+ throw new Error(
123
+ "statewire: onCommandSessionLost requires a transport element that takes a single options object",
124
+ );
125
+ }
126
+ const transportLevel = transportOptions.onCommandSessionLost as
127
+ | ((command: StatewireClient.SessionLostCommand) => "replay" | void)
128
+ | undefined;
129
+ return {
130
+ ...transport,
131
+ args: [
132
+ {
133
+ ...transportOptions,
134
+ onCommandSessionLost: (
135
+ command: StatewireClient.SessionLostCommand,
136
+ ): "replay" | void =>
137
+ transportLevel?.(command) ??
138
+ latest.current.onCommandSessionLost?.(command),
139
+ },
140
+ ],
141
+ };
142
+ };
143
+
44
144
  const useStatewireThread = (
45
145
  options: StatewireThread.Options<any>,
46
146
  ): ClientOutput<"thread"> => {
47
147
  const latest = useRef(options);
48
148
  latest.current = options;
49
149
 
50
- const [pending, setPending] = useState<readonly AssistantTransportCommand[]>(
150
+ const [pending, setPending] = useState<readonly StatewireThread.Command[]>(
51
151
  [],
52
152
  );
53
153
  const [retire] = useState(
54
154
  () => (command: unknown) =>
55
155
  setPending((prev) =>
56
- prev.includes(command as AssistantTransportCommand)
156
+ prev.includes(command as StatewireThread.Command)
57
157
  ? prev.filter((c) => c !== command)
58
158
  : prev,
59
159
  ),
@@ -62,9 +162,13 @@ const useStatewireThread = (
62
162
  const {
63
163
  state: transportState,
64
164
  commands,
165
+ connection,
65
166
  setContext,
66
167
  } = useStatewire<unknown, AnyCommands>({
67
- transport: options.transport,
168
+ transport:
169
+ options.onCommandSessionLost === undefined
170
+ ? options.transport
171
+ : withSessionLostFallback(options.transport, latest),
68
172
  onCommandChange: (update) => {
69
173
  if (update.status === "acked" || update.status === "settled")
70
174
  retire(update.params[0]);
@@ -100,7 +204,7 @@ const useStatewireThread = (
100
204
  }, [contextSync, clientRef, syncState]);
101
205
 
102
206
  const dispatch = useCallback(
103
- (command: AssistantTransportCommand) => {
207
+ (command: StatewireThread.Command) => {
104
208
  setPending((prev) => [...prev, command]);
105
209
  void commands[command.type]!(command).catch((error: Error) => {
106
210
  retire(command);
@@ -115,21 +219,84 @@ const useStatewireThread = (
115
219
  (): StatewireThread.ConnectionMetadata => ({
116
220
  pendingCommands: [...pending],
117
221
  isSending: pending.length > 0,
222
+ connection,
118
223
  }),
119
- [pending],
224
+ [pending, connection],
120
225
  );
121
226
  const converted = useMemo(
122
227
  () => converter(state, metadata),
123
228
  [converter, state, metadata],
124
229
  );
230
+ const queueItems = converted.queue;
231
+ const steerQueueItems = converted.steerQueue;
232
+ if (steerQueueItems !== undefined && queueItems === undefined)
233
+ throw new Error(
234
+ "statewire: the converter's steerQueue projection requires the queue projection",
235
+ );
236
+ const [queueSeam] = useState(() => ({
237
+ present: queueItems !== undefined,
238
+ }));
239
+ if (queueSeam.present !== (queueItems !== undefined))
240
+ throw new Error(
241
+ "statewire: the converter's queue projection must be stable — it was " +
242
+ (queueSeam.present ? "defined" : "undefined") +
243
+ " on first convert and changed since",
244
+ );
245
+
246
+ const queue = useMemo((): ExternalThreadQueueAdapter | undefined => {
247
+ if (!queueItems) return undefined;
248
+ const laneOf = (queueItemId: string): "queue" | "steer" => {
249
+ if (steerQueueItems?.some((item) => item.id === queueItemId))
250
+ return "steer";
251
+ if (queueItems.some((item) => item.id === queueItemId)) return "queue";
252
+ throw new Error(`statewire: unknown queue item "${queueItemId}"`);
253
+ };
254
+ return {
255
+ items: queueItems.map(toQueueItemState),
256
+ steerItems: (steerQueueItems ?? []).map(toQueueItemState),
257
+ enqueue: (message) =>
258
+ dispatch({
259
+ type: "run/enqueue",
260
+ message: toWireMessage(message, crypto.randomUUID()),
261
+ }),
262
+ steer: (message) =>
263
+ dispatch({
264
+ type: "run/steer",
265
+ message: toWireMessage(message, crypto.randomUUID()),
266
+ }),
267
+ move: (queueItemId, placement) => {
268
+ const lane = placement.lane ?? laneOf(queueItemId);
269
+ const fields = {
270
+ messageId: queueItemId,
271
+ ...placementFields(placement),
272
+ };
273
+ dispatch(
274
+ lane === "steer"
275
+ ? { type: "run/steer", ...fields }
276
+ : { type: "run/enqueue", ...fields },
277
+ );
278
+ },
279
+ edit: (queueItemId, message) => {
280
+ const wireMessage = toWireMessage(message, queueItemId);
281
+ dispatch(
282
+ laneOf(queueItemId) === "steer"
283
+ ? { type: "run/steer", message: wireMessage }
284
+ : { type: "run/enqueue", message: wireMessage },
285
+ );
286
+ },
287
+ remove: (queueItemId) =>
288
+ dispatch({ type: "run/dequeue", messageId: queueItemId }),
289
+ };
290
+ }, [queueItems, steerQueueItems, dispatch]);
125
291
 
126
292
  const extras = useMemo(
127
293
  (): AssistantTransportExtras => ({
128
294
  [symbolAssistantTransportExtras]: true,
129
295
  sendCommand: dispatch,
296
+ reconnect: connection.reconnect,
130
297
  state,
131
298
  }),
132
- [dispatch, state],
299
+ [dispatch, connection.reconnect, state],
133
300
  );
134
301
 
135
302
  const handleAppend = (message: AppendMessage) => {
@@ -138,6 +305,17 @@ const useStatewireThread = (
138
305
  dispatch(command);
139
306
  };
140
307
 
308
+ const handleEdit = (message: AppendMessage) => {
309
+ if (!queueItems) return handleAppend(message);
310
+ if (message.sourceId == null)
311
+ throw new Error("statewire: run/edit requires a sourceId");
312
+ dispatch({
313
+ type: "run/edit",
314
+ message: toWireMessage(message, crypto.randomUUID()),
315
+ sourceId: message.sourceId,
316
+ });
317
+ };
318
+
141
319
  return useResource(
142
320
  ExternalThread({
143
321
  messages: converted.messages as readonly ExternalThreadMessage[],
@@ -147,9 +325,25 @@ const useStatewireThread = (
147
325
  extras,
148
326
  attachmentAdapter: options.adapters?.attachments,
149
327
  onNew: handleAppend,
150
- ...(options.capabilities?.edit && { onEdit: handleAppend }),
328
+ ...(queue && { queue }),
329
+ ...(options.capabilities?.edit && { onEdit: handleEdit }),
330
+ ...(options.capabilities?.continue && {
331
+ onResume: () => dispatch({ type: "run/continue" }),
332
+ }),
151
333
  onCancel: () => {
152
- void commands["cancel"]!().catch((error: Error) => {
334
+ const payload = latest.current.cancelPayload?.();
335
+ if (
336
+ payload !== undefined &&
337
+ (typeof payload !== "object" ||
338
+ payload === null ||
339
+ Array.isArray(payload))
340
+ )
341
+ throw new Error(
342
+ "statewire: cancelPayload must return a plain object",
343
+ );
344
+ void commands["run/cancel"]!(
345
+ ...(payload === undefined ? [] : [payload]),
346
+ ).catch((error: Error) => {
153
347
  latest.current.onError?.(error);
154
348
  });
155
349
  },
@@ -165,15 +359,91 @@ export const StatewireThread = <T>(
165
359
  export namespace StatewireThread {
166
360
  export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;
167
361
 
362
+ export type TextPart = {
363
+ readonly type: "text";
364
+ readonly text: string;
365
+ };
366
+
367
+ export type FilePart = {
368
+ readonly type: "file";
369
+ readonly mediaType: string;
370
+ readonly url: string;
371
+ readonly filename?: string;
372
+ };
373
+
374
+ export type UserMessage = {
375
+ readonly id: string;
376
+ readonly role: "user";
377
+ readonly parts: readonly (TextPart | FilePart)[];
378
+ readonly metadata?: Record<string, unknown>;
379
+ };
380
+
381
+ /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */
382
+ export type Placement = {
383
+ readonly insertAfter?: string | null;
384
+ readonly insertBefore?: string | null;
385
+ };
386
+
387
+ export type RunEnqueueCommand = {
388
+ readonly type: "run/enqueue";
389
+ } & ({ readonly message: UserMessage } | { readonly messageId: string }) &
390
+ Placement;
391
+
392
+ export type RunSteerCommand = {
393
+ readonly type: "run/steer";
394
+ } & ({ readonly message: UserMessage } | { readonly messageId: string }) &
395
+ Placement;
396
+
397
+ export type RunDequeueCommand = {
398
+ readonly type: "run/dequeue";
399
+ readonly messageId: string;
400
+ };
401
+
402
+ export type RunEditCommand = {
403
+ readonly type: "run/edit";
404
+ readonly message: UserMessage;
405
+ readonly sourceId: string;
406
+ };
407
+
408
+ export type RunContinueCommand = {
409
+ readonly type: "run/continue";
410
+ };
411
+
412
+ export type RunCommand =
413
+ | RunEnqueueCommand
414
+ | RunSteerCommand
415
+ | RunDequeueCommand
416
+ | RunEditCommand
417
+ | RunContinueCommand;
418
+
419
+ export type Command = AssistantTransportCommand | RunCommand;
420
+
421
+ /** A queued message projected out of the host state, wire shape. */
422
+ export type QueueItem = {
423
+ readonly id: string;
424
+ readonly parts: readonly (TextPart | FilePart)[];
425
+ };
426
+
168
427
  export type State = {
169
428
  readonly messages: readonly ThreadMessage[];
170
429
  readonly state?: ReadonlyJSONValue;
171
430
  readonly isRunning: boolean;
431
+ /**
432
+ * The host's regular queue lane projected out of the state. Returning it
433
+ * (even empty) turns on the queue capability: sends become `run/enqueue`
434
+ * / `run/steer` commands and item controls send the `run/*` queue
435
+ * commands. Presence must be stable across conversions.
436
+ */
437
+ readonly queue?: readonly QueueItem[];
438
+ /** The host's steer lane; requires `queue`. Absent means empty. */
439
+ readonly steerQueue?: readonly QueueItem[];
172
440
  };
173
441
 
174
442
  export type ConnectionMetadata = {
175
- pendingCommands: AssistantTransportCommand[];
443
+ pendingCommands: Command[];
176
444
  isSending: boolean;
445
+ /** Statewire connection status; local transports are always `live`. */
446
+ connection: StatewireClient.ConnectionState;
177
447
  };
178
448
 
179
449
  export type StateConverter<T> = (
@@ -181,6 +451,15 @@ export namespace StatewireThread {
181
451
  connectionMetadata: ConnectionMetadata,
182
452
  ) => State;
183
453
 
454
+ /**
455
+ * Payload of the built-in `run/cancel` command. `reason` is the one well-known
456
+ * field; apps extend it with their own JSON-serializable fields.
457
+ */
458
+ export type CancelPayload = {
459
+ readonly reason?: string | undefined;
460
+ readonly [key: string]: ReadonlyJSONValue | undefined;
461
+ };
462
+
184
463
  export type Options<T> = {
185
464
  transport: Transport<T>;
186
465
  initialState: T;
@@ -191,10 +470,23 @@ export namespace StatewireThread {
191
470
  * on connect and whenever it changes. Requires a remote transport.
192
471
  */
193
472
  contextSync?: "command-send" | undefined;
473
+ /** Supplies the `run/cancel` command's payload; omitted, cancel sends no payload. */
474
+ cancelPayload?: (() => CancelPayload) | undefined;
475
+ /**
476
+ * Offered each pending command when a remote transport's session is
477
+ * evicted; return "replay" to re-enqueue it under the rotated client id.
478
+ * A callback set on the transport options is consulted first; this one
479
+ * runs for commands it declined.
480
+ */
481
+ onCommandSessionLost?:
482
+ | ((command: StatewireClient.SessionLostCommand) => "replay" | void)
483
+ | undefined;
194
484
  onError?: ((error: Error) => void) | undefined;
195
485
  capabilities?:
196
486
  | {
197
487
  edit?: boolean | undefined;
488
+ /** The host supports `run/continue` (a continue affordance on aborted runs). */
489
+ continue?: boolean | undefined;
198
490
  }
199
491
  | undefined;
200
492
  adapters?:
@@ -45,7 +45,7 @@ export const defaultConverter: AssistantTransportStateConverter<TestState> = (
45
45
  messages: [
46
46
  ...state.messages.map(toThreadMessage),
47
47
  ...meta.pendingCommands.flatMap((c, i) =>
48
- c.type === "add-message" && c.message.role === "user"
48
+ c.type === "message/add" && c.message.role === "user"
49
49
  ? [
50
50
  toThreadMessage({
51
51
  id: `optimistic-${i}`,
@@ -13,7 +13,7 @@ import type { ExternalThreadMessage } from "@assistant-ui/react";
13
13
  import { AssistantTransportThread } from "./AssistantTransportThread";
14
14
  import { useAssistantTransportSendCommand } from "./hooks";
15
15
  import type {
16
- AddMessageCommand,
16
+ MessageAddCommand,
17
17
  AssistantTransportCommand,
18
18
  AssistantTransportOptions,
19
19
  AssistantTransportStateConverter,
@@ -41,13 +41,13 @@ type LangGraphState = {
41
41
 
42
42
  const INITIAL_STATE: LangGraphState = { messages: [], todos: [] };
43
43
 
44
- // Athena's optimistic dedup: each add-message command gets a stable
44
+ // Athena's optimistic dedup: each message/add command gets a stable
45
45
  // trackingId; the server echoes it on the human message, which retires the
46
46
  // optimistic copy without a flicker frame or a phantom duplicate.
47
47
  const createConverter = () => {
48
- const trackingIds = new WeakMap<AddMessageCommand, string>();
48
+ const trackingIds = new WeakMap<MessageAddCommand, string>();
49
49
  let nextTrackingId = 0;
50
- const trackingIdOf = (command: AddMessageCommand) => {
50
+ const trackingIdOf = (command: MessageAddCommand) => {
51
51
  let id = trackingIds.get(command);
52
52
  if (id === undefined) {
53
53
  id = `track-${nextTrackingId++}`;
@@ -108,8 +108,8 @@ const createConverter = () => {
108
108
  }
109
109
 
110
110
  for (const c of meta.pendingCommands) {
111
- if (c.type !== "add-message" || c.message.role !== "user") continue;
112
- const trackingId = trackingIdOf(c as AddMessageCommand);
111
+ if (c.type !== "message/add" || c.message.role !== "user") continue;
112
+ const trackingId = trackingIdOf(c as MessageAddCommand);
113
113
  const echoed = state.messages.some(
114
114
  (m) => m.type === "human" && m.trackingId === trackingId,
115
115
  );
@@ -168,13 +168,13 @@ const mountDeepAgent = () => {
168
168
  prepareSendCommandsRequest: (body) => ({
169
169
  ...body,
170
170
  commands: body.commands.map((c) =>
171
- c.type === "add-message"
171
+ c.type === "message/add"
172
172
  ? {
173
173
  ...c,
174
- trackingId: trackingIdOf(c as AddMessageCommand),
174
+ trackingId: trackingIdOf(c as MessageAddCommand),
175
175
  message: {
176
- ...(c as AddMessageCommand).message,
177
- parts: (c as AddMessageCommand).message.parts.filter(
176
+ ...(c as MessageAddCommand).message,
177
+ parts: (c as MessageAddCommand).message.parts.filter(
178
178
  (p) => p.type !== "image",
179
179
  ),
180
180
  },
@@ -197,7 +197,7 @@ const mountDeepAgent = () => {
197
197
  messages: [
198
198
  ...state.messages,
199
199
  ...commands.flatMap((c, i) =>
200
- c.type === "add-message" && c.message.role === "user"
200
+ c.type === "message/add" && c.message.role === "user"
201
201
  ? [
202
202
  {
203
203
  id: `reattached-${i}`,
@@ -205,7 +205,7 @@ const mountDeepAgent = () => {
205
205
  content:
206
206
  c.message.parts.find((p) => p.type === "text")?.text ??
207
207
  "",
208
- trackingId: trackingIdOf(c as AddMessageCommand),
208
+ trackingId: trackingIdOf(c as MessageAddCommand),
209
209
  },
210
210
  ]
211
211
  : [],
@@ -308,7 +308,7 @@ describe("deep-agent e2e", () => {
308
308
  // prepareSendCommandsRequest stripped the image part, kept trackingId.
309
309
  expect(r1.body.commands).toEqual([
310
310
  {
311
- type: "add-message",
311
+ type: "message/add",
312
312
  trackingId: "track-0",
313
313
  message: {
314
314
  role: "user",
@@ -384,13 +384,13 @@ describe("deep-agent e2e", () => {
384
384
  });
385
385
  servers[0]!.done();
386
386
 
387
- // 3 — frontend tool executes and posts add-tool-result in a follow-up run.
387
+ // 3 — frontend tool executes and posts tool-result/add in a follow-up run.
388
388
  await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
389
389
  const r2 = fetchMock.requests[1]!;
390
390
  expect(r2.url).toBe("https://sync.example.com/api/chat");
391
391
  expect(r2.body.commands).toEqual([
392
392
  {
393
- type: "add-tool-result",
393
+ type: "tool-result/add",
394
394
  toolCallId: "tc1",
395
395
  toolName: "get_weather",
396
396
  result: { temp: 20, city: "SF" },
@@ -547,7 +547,7 @@ describe("deep-agent e2e", () => {
547
547
  await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
548
548
  expect(fetchMock.requests[0]!.body.commands).toEqual([
549
549
  {
550
- type: "add-message",
550
+ type: "message/add",
551
551
  trackingId: "track-0",
552
552
  message: {
553
553
  role: "user",
@@ -613,7 +613,7 @@ describe("deep-agent e2e", () => {
613
613
  aui().thread().append("save this message");
614
614
 
615
615
  await waitFor(() => expect(harness.errored).toHaveLength(1));
616
- expect(harness.errored[0]!.map((c) => c.type)).toEqual(["add-message"]);
616
+ expect(harness.errored[0]!.map((c) => c.type)).toEqual(["message/add"]);
617
617
 
618
618
  // The command left the queue (no longer optimistic/pending) but the
619
619
  // re-attached copy keeps it visible.
package/src/host.ts CHANGED
@@ -183,12 +183,7 @@ const useHostLoop = (
183
183
  state: getAgent(),
184
184
  system: modelContext.system,
185
185
  tools: modelContext.tools
186
- ? // cast: core >=0.3.5 widens tool generics beyond assistant-stream's Tool
187
- toToolsJSONSchema(
188
- modelContext.tools as unknown as Parameters<
189
- typeof toToolsJSONSchema
190
- >[0],
191
- )
186
+ ? toToolsJSONSchema(modelContext.tools)
192
187
  : undefined,
193
188
  threadId,
194
189
  ...(runParentId !== undefined && { parentId: runParentId }),
package/src/index.ts CHANGED
@@ -15,8 +15,8 @@ export namespace AssistantTransportThread {
15
15
  export type State = types.AssistantTransportState;
16
16
  export type ConnectionMetadata = types.AssistantTransportConnectionMetadata;
17
17
  export type StateConverter<T> = types.AssistantTransportStateConverter<T>;
18
- export type AddMessageCommand = types.AddMessageCommand;
19
- export type AddToolResultCommand = types.AddToolResultCommand;
18
+ export type MessageAddCommand = types.MessageAddCommand;
19
+ export type ToolResultAddCommand = types.ToolResultAddCommand;
20
20
  export type SendCommandsRequestBody = types.SendCommandsRequestBody;
21
21
  export type UserMessage = types.UserMessage;
22
22
  export type AssistantMessage = types.AssistantMessage;
@@ -46,7 +46,7 @@ const converter: AssistantTransportStateConverter<TestState> = (
46
46
  }) as unknown as ExternalThreadMessage,
47
47
  ),
48
48
  ...meta.pendingCommands.flatMap((c, i) =>
49
- c.type === "add-message" && c.message.role === "user"
49
+ c.type === "message/add" && c.message.role === "user"
50
50
  ? [
51
51
  {
52
52
  id: `optimistic-${i}`,
@@ -71,6 +71,19 @@ const converter: AssistantTransportStateConverter<TestState> = (
71
71
 
72
72
  type RecordedRequest = { url: string; body: Record<string, any> };
73
73
 
74
+ // deliberate divergence: the namespaced wire rename ("add-message" →
75
+ // "message/add", "add-tool-result" → "tool-result/add") postdates the legacy
76
+ // runtime; legacy bodies are renamed before comparison.
77
+ const WIRE_RENAMES: Record<string, string> = {
78
+ "add-message": "message/add",
79
+ "add-tool-result": "tool-result/add",
80
+ };
81
+ const renameWire = (commands: unknown) =>
82
+ (commands as { type: string }[]).map((c) => ({
83
+ ...c,
84
+ type: WIRE_RENAMES[c.type] ?? c.type,
85
+ }));
86
+
74
87
  // Scripted server: request N gets transcript N, streamed whole.
75
88
  const installScriptedFetch = (transcript: string[][]) => {
76
89
  const requests: RecordedRequest[] = [];
@@ -153,7 +166,7 @@ const observeLegacy = async (): Promise<{
153
166
  api: "https://example.com/api",
154
167
  protocol: "assistant-transport",
155
168
  headers: {},
156
- converter,
169
+ converter: converter as never,
157
170
  });
158
171
  return (
159
172
  <AssistantRuntimeProvider runtime={captured.runtime}>
@@ -362,8 +375,8 @@ const installToolScriptedFetch = (transcript: string[][]) => {
362
375
  return requests;
363
376
  };
364
377
 
365
- // Inferred literal type — structurally satisfies both the legacy and the new
366
- // options types under exactOptionalPropertyTypes.
378
+ // Inferred literal type — written against the new options type; the legacy
379
+ // call site casts (the command union diverged with the wire rename).
367
380
  const toolOptions = (events: CallbackEvent[]) => ({
368
381
  initialState: { messages: [] } as ToolState,
369
382
  api: "https://example.com/api",
@@ -420,7 +433,7 @@ const observeLegacyToolRun = async (): Promise<ToolObserved> => {
420
433
  } = {};
421
434
  const App: FC = () => {
422
435
  captured.runtime = useAssistantTransportRuntime<ToolState>(
423
- toolOptions(events),
436
+ toolOptions(events) as never,
424
437
  );
425
438
  return (
426
439
  <AssistantRuntimeProvider runtime={captured.runtime}>
@@ -543,7 +556,7 @@ describe("legacy diff", () => {
543
556
  legacy.requests[0]!.body,
544
557
  modern.requests[0]!.body,
545
558
  ];
546
- expect(modernBody.commands).toEqual(legacyBody.commands);
559
+ expect(modernBody.commands).toEqual(renameWire(legacyBody.commands));
547
560
  expect(modernBody.state).toEqual(legacyBody.state);
548
561
  expect(modernBody.system).toEqual(legacyBody.system);
549
562
  expect(modernBody.tools).toEqual(legacyBody.tools);
@@ -563,7 +576,7 @@ describe("legacy diff", () => {
563
576
  modern.requests[i]!.body,
564
577
  ];
565
578
  expect(modern.requests[i]!.url).toEqual(legacy.requests[i]!.url);
566
- expect(modernBody.commands).toEqual(legacyBody.commands);
579
+ expect(modernBody.commands).toEqual(renameWire(legacyBody.commands));
567
580
  expect(modernBody.state).toEqual(legacyBody.state);
568
581
  // deliberate divergence (sw-73): the tool-result follow-up does not
569
582
  // repeat the parentId the first run already consumed
@@ -572,7 +585,11 @@ describe("legacy diff", () => {
572
585
  expect(modernBody.tools).toEqual(legacyBody.tools);
573
586
  }
574
587
 
575
- expect(modern.events).toEqual(legacy.events);
588
+ expect(modern.events).toEqual(
589
+ legacy.events.map((e) =>
590
+ "commands" in e ? { ...e, commands: renameWire(e.commands) } : e,
591
+ ),
592
+ );
576
593
  expect(modern.texts).toEqual(legacy.texts);
577
594
  expect(modern.ids).toEqual(legacy.ids);
578
595
  expect(modern.isRunning).toEqual(legacy.isRunning);