@assistant-ui/react-statewire 0.1.1 → 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/src/host.ts CHANGED
@@ -11,7 +11,6 @@ import type { AssistantTransportStateOperation } from "assistant-stream";
11
11
  import { asAsyncIterableStream } from "assistant-stream/utils";
12
12
  import type { Statewire } from "statewire";
13
13
  import {
14
- CommandExecution,
15
14
  useStatewireCommands,
16
15
  useStatewireEmit,
17
16
  useStatewireState,
@@ -61,13 +60,18 @@ export type AssistantTransportHostCommands = {
61
60
  setParentId(parentId: string | null): void;
62
61
  cancel(): void;
63
62
  resume(): void;
64
- reload(parentId: string | null): void;
65
63
  importState(state: unknown): void;
66
64
  };
67
65
 
66
+ type EntrySettlement = {
67
+ ack: () => void;
68
+ resolve: () => void;
69
+ reject: (error: unknown) => void;
70
+ };
71
+
68
72
  type QueueEntry = {
69
73
  command: AssistantTransportCommand;
70
- execution: StatewireHost.ExecutionResolvers;
74
+ execution: EntrySettlement;
71
75
  };
72
76
 
73
77
  type EntryQueue = {
@@ -367,14 +371,26 @@ const useHostLoop = (
367
371
  };
368
372
 
369
373
  return {
370
- send: (command: AssistantTransportCommand, opts?: SendOptions) => {
371
- const [execution, resolvers] = CommandExecution.withResolvers();
374
+ send: function (
375
+ this: StatewireHost.Ctx,
376
+ command: AssistantTransportCommand,
377
+ opts?: SendOptions,
378
+ ) {
379
+ let resolve!: () => void;
380
+ let reject!: (error: unknown) => void;
381
+ const promise = new Promise<void>((res, rej) => {
382
+ resolve = res;
383
+ reject = rej;
384
+ });
372
385
  setQueue({
373
- queued: [...s.queue.queued, { command, execution: resolvers }],
386
+ queued: [
387
+ ...s.queue.queued,
388
+ { command, execution: { ack: this.ack, resolve, reject } },
389
+ ],
374
390
  inTransit: s.queue.inTransit,
375
391
  });
376
392
  if (opts?.schedule !== false) schedule();
377
- return execution;
393
+ return promise;
378
394
  },
379
395
  setParentId: (id: string | null) => {
380
396
  s.parentId = id;
@@ -391,10 +407,6 @@ const useHostLoop = (
391
407
  s.resumeRequested = true;
392
408
  schedule();
393
409
  },
394
- reload: (id: string | null) => {
395
- s.parentId = id;
396
- schedule();
397
- },
398
410
  importState: replaceAgent,
399
411
  };
400
412
  };
package/src/index.ts CHANGED
@@ -17,15 +17,31 @@ export namespace AssistantTransportThread {
17
17
  export type StateConverter<T> = types.AssistantTransportStateConverter<T>;
18
18
  export type AddMessageCommand = types.AddMessageCommand;
19
19
  export type AddToolResultCommand = types.AddToolResultCommand;
20
- export type EnqueueMessageCommand = types.EnqueueMessageCommand;
21
- export type SteerQueueItemCommand = types.SteerQueueItemCommand;
22
- export type RemoveQueueItemCommand = types.RemoveQueueItemCommand;
23
- export type ClearQueueCommand = types.ClearQueueCommand;
20
+ export type RunCommand = types.RunCommand;
21
+ export type RunEnqueueCommand = types.RunEnqueueCommand;
22
+ export type RunSteerCommand = types.RunSteerCommand;
23
+ export type RunDequeueCommand = types.RunDequeueCommand;
24
+ export type RunEditCommand = types.RunEditCommand;
25
+ export type RunContinueCommand = types.RunContinueCommand;
26
+ export type RunReloadCommand = types.RunReloadCommand;
27
+ export type RunInputCommand = types.RunInputCommand;
28
+ export type InputRequest = types.InputRequest;
29
+ export type ToolCallInputRequest = types.ToolCallInputRequest;
30
+ export type ToolApprovalInputRequest = types.ToolApprovalInputRequest;
31
+ export type CustomInputRequest = types.CustomInputRequest;
32
+ export type InputRequestState = types.InputRequestState;
33
+ export type InputResponse = types.InputResponse;
34
+ export type ToolCallInputResponse = types.ToolCallInputResponse;
35
+ export type ToolApprovalInputResponse = types.ToolApprovalInputResponse;
36
+ export type RunUserMessage = types.RunUserMessage;
37
+ export type RunQueueItem = types.RunQueueItem;
38
+ export type RunPlacement = types.RunPlacement;
24
39
  export type SendCommandsRequestBody = types.SendCommandsRequestBody;
25
40
  export type UserMessage = types.UserMessage;
26
41
  export type AssistantMessage = types.AssistantMessage;
27
42
  export type UserMessagePart = types.UserMessagePart;
28
43
  export type TextPart = types.TextPart;
44
+ export type FilePart = types.FilePart;
29
45
  export type ImagePart = types.ImagePart;
30
46
  export type HeadersValue = types.HeadersValue;
31
47
  }
@@ -0,0 +1,57 @@
1
+ import type { RespondToToolApprovalOptions } from "@assistant-ui/core";
2
+ import type { ReadonlyJSONValue } from "assistant-stream/utils";
3
+ import type { InputRequestState, RunInputCommand } from "./types";
4
+
5
+ const assertUnanswered = (request: InputRequestState) => {
6
+ if (request.response !== null)
7
+ throw new Error(
8
+ `statewire: input request "${request.id}" is already answered`,
9
+ );
10
+ };
11
+
12
+ export const resolveToolResultInput = (
13
+ inputRequests: readonly InputRequestState[],
14
+ options: {
15
+ toolCallId: string;
16
+ result: ReadonlyJSONValue;
17
+ isError: boolean;
18
+ artifact?: ReadonlyJSONValue | undefined;
19
+ },
20
+ ): RunInputCommand | undefined => {
21
+ const request = inputRequests.find(
22
+ (r) => r.type === "tool-call" && r.toolCallId === options.toolCallId,
23
+ );
24
+ if (request === undefined) return undefined;
25
+ assertUnanswered(request);
26
+ return {
27
+ type: "run/input",
28
+ requestId: request.id,
29
+ response: {
30
+ output: options.result,
31
+ ...(options.isError && { isError: true }),
32
+ ...(options.artifact !== undefined && { artifact: options.artifact }),
33
+ },
34
+ };
35
+ };
36
+
37
+ export const resolveToolApprovalInput = (
38
+ inputRequests: readonly InputRequestState[],
39
+ options: RespondToToolApprovalOptions,
40
+ ): RunInputCommand => {
41
+ const request = inputRequests.find(
42
+ (r) => r.type === "tool-approval" && r.id === options.approvalId,
43
+ );
44
+ if (request === undefined)
45
+ throw new Error(
46
+ `statewire: no tool-approval input request "${options.approvalId}"`,
47
+ );
48
+ assertUnanswered(request);
49
+ return {
50
+ type: "run/input",
51
+ requestId: request.id,
52
+ response: {
53
+ decision: options.approved ? "approve" : "reject",
54
+ ...(options.reason !== undefined && { message: options.reason }),
55
+ },
56
+ };
57
+ };
@@ -46,7 +46,9 @@ 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 === "run/steer" || c.type === "add-message") &&
50
+ "message" in c &&
51
+ c.message.role === "user"
50
52
  ? [
51
53
  {
52
54
  id: `optimistic-${i}`,
@@ -71,6 +73,24 @@ const converter: AssistantTransportStateConverter<TestState> = (
71
73
 
72
74
  type RecordedRequest = { url: string; body: Record<string, any> };
73
75
 
76
+ // deliberate divergence: the re-implementation sends finalized user messages
77
+ // as run/steer (with a client-generated message id, no per-command
78
+ // parentId/sourceId — parentId rides the request body); legacy add-message
79
+ // bodies are translated before comparison. add-tool-result is unchanged.
80
+ const renameWire = (commands: unknown) =>
81
+ (commands as Record<string, any>[]).map((c) =>
82
+ c.type === "add-message"
83
+ ? {
84
+ type: "run/steer",
85
+ message: {
86
+ id: expect.any(String),
87
+ role: c.message.role,
88
+ parts: c.message.parts,
89
+ },
90
+ }
91
+ : c,
92
+ );
93
+
74
94
  // Scripted server: request N gets transcript N, streamed whole.
75
95
  const installScriptedFetch = (transcript: string[][]) => {
76
96
  const requests: RecordedRequest[] = [];
@@ -153,7 +173,7 @@ const observeLegacy = async (): Promise<{
153
173
  api: "https://example.com/api",
154
174
  protocol: "assistant-transport",
155
175
  headers: {},
156
- converter,
176
+ converter: converter as never,
157
177
  });
158
178
  return (
159
179
  <AssistantRuntimeProvider runtime={captured.runtime}>
@@ -362,8 +382,8 @@ const installToolScriptedFetch = (transcript: string[][]) => {
362
382
  return requests;
363
383
  };
364
384
 
365
- // Inferred literal type — structurally satisfies both the legacy and the new
366
- // options types under exactOptionalPropertyTypes.
385
+ // Inferred literal type — written against the new options type; the legacy
386
+ // call site casts (the command union diverged with the wire rename).
367
387
  const toolOptions = (events: CallbackEvent[]) => ({
368
388
  initialState: { messages: [] } as ToolState,
369
389
  api: "https://example.com/api",
@@ -420,7 +440,7 @@ const observeLegacyToolRun = async (): Promise<ToolObserved> => {
420
440
  } = {};
421
441
  const App: FC = () => {
422
442
  captured.runtime = useAssistantTransportRuntime<ToolState>(
423
- toolOptions(events),
443
+ toolOptions(events) as never,
424
444
  );
425
445
  return (
426
446
  <AssistantRuntimeProvider runtime={captured.runtime}>
@@ -543,7 +563,7 @@ describe("legacy diff", () => {
543
563
  legacy.requests[0]!.body,
544
564
  modern.requests[0]!.body,
545
565
  ];
546
- expect(modernBody.commands).toEqual(legacyBody.commands);
566
+ expect(modernBody.commands).toEqual(renameWire(legacyBody.commands));
547
567
  expect(modernBody.state).toEqual(legacyBody.state);
548
568
  expect(modernBody.system).toEqual(legacyBody.system);
549
569
  expect(modernBody.tools).toEqual(legacyBody.tools);
@@ -563,7 +583,7 @@ describe("legacy diff", () => {
563
583
  modern.requests[i]!.body,
564
584
  ];
565
585
  expect(modern.requests[i]!.url).toEqual(legacy.requests[i]!.url);
566
- expect(modernBody.commands).toEqual(legacyBody.commands);
586
+ expect(modernBody.commands).toEqual(renameWire(legacyBody.commands));
567
587
  expect(modernBody.state).toEqual(legacyBody.state);
568
588
  // deliberate divergence (sw-73): the tool-result follow-up does not
569
589
  // repeat the parentId the first run already consumed
@@ -572,7 +592,11 @@ describe("legacy diff", () => {
572
592
  expect(modernBody.tools).toEqual(legacyBody.tools);
573
593
  }
574
594
 
575
- expect(modern.events).toEqual(legacy.events);
595
+ expect(modern.events).toEqual(
596
+ legacy.events.map((e) =>
597
+ "commands" in e ? { ...e, commands: renameWire(e.commands) } : e,
598
+ ),
599
+ );
576
600
  expect(modern.texts).toEqual(legacy.texts);
577
601
  expect(modern.ids).toEqual(legacy.ids);
578
602
  expect(modern.isRunning).toEqual(legacy.isRunning);
@@ -0,0 +1,146 @@
1
+ import type {
2
+ AppendMessage,
3
+ ExternalThreadQueueAdapter,
4
+ QueuePlacement,
5
+ } from "@assistant-ui/core";
6
+ import type {
7
+ FilePart,
8
+ RunCommand,
9
+ RunQueueItem,
10
+ RunReloadCommand,
11
+ RunUserMessage,
12
+ TextPart,
13
+ } from "./types";
14
+
15
+ export const toWireMessage = (
16
+ message: AppendMessage,
17
+ id: string,
18
+ ): RunUserMessage => {
19
+ if (message.role !== "user")
20
+ throw new Error("statewire: only user messages are supported");
21
+ const files: FilePart[] = [];
22
+ const texts: string[] = [];
23
+ const source = [
24
+ ...message.content,
25
+ ...(message.attachments?.flatMap((a) => a.content) ?? []),
26
+ ];
27
+ for (const part of source) {
28
+ if (part.type === "text") {
29
+ texts.push(part.text);
30
+ } else if (part.type === "image") {
31
+ files.push({ type: "file", mediaType: "image/*", url: part.image });
32
+ } else if (part.type === "file") {
33
+ files.push({
34
+ type: "file",
35
+ mediaType: part.mimeType,
36
+ url: part.data,
37
+ ...(part.filename !== undefined && { filename: part.filename }),
38
+ });
39
+ } else {
40
+ throw new Error(`statewire: unsupported message part "${part.type}"`);
41
+ }
42
+ }
43
+ // default-safe against host capabilities: files first, one merged text part
44
+ const parts: (TextPart | FilePart)[] = [
45
+ ...files,
46
+ ...(texts.length > 0
47
+ ? [{ type: "text" as const, text: texts.join("\n\n") }]
48
+ : []),
49
+ ];
50
+ if (parts.length === 0)
51
+ throw new Error("statewire: cannot send an empty message");
52
+ return { id, role: "user", parts };
53
+ };
54
+
55
+ export const toQueueItemState = (item: RunQueueItem) => ({
56
+ id: item.id,
57
+ prompt: item.parts
58
+ .flatMap((part) => (part.type === "text" ? [part.text] : []))
59
+ .join("\n\n"),
60
+ parts: item.parts.map((part) =>
61
+ part.type === "text"
62
+ ? part
63
+ : {
64
+ type: "file" as const,
65
+ data: part.url,
66
+ mimeType: part.mediaType,
67
+ ...(part.filename !== undefined && { filename: part.filename }),
68
+ },
69
+ ),
70
+ });
71
+
72
+ const placementFields = (placement: QueuePlacement) => ({
73
+ ...(placement.insertAfter !== undefined && {
74
+ insertAfter: placement.insertAfter,
75
+ }),
76
+ ...(placement.insertBefore !== undefined && {
77
+ insertBefore: placement.insertBefore,
78
+ }),
79
+ });
80
+
81
+ export const createRunQueueAdapter = (
82
+ queueItems: readonly RunQueueItem[],
83
+ steerQueueItems: readonly RunQueueItem[] | undefined,
84
+ dispatch: (command: RunCommand) => void,
85
+ ): ExternalThreadQueueAdapter => {
86
+ const laneOf = (queueItemId: string): "queue" | "steer" => {
87
+ if (steerQueueItems?.some((item) => item.id === queueItemId))
88
+ return "steer";
89
+ if (queueItems.some((item) => item.id === queueItemId)) return "queue";
90
+ throw new Error(`statewire: unknown queue item "${queueItemId}"`);
91
+ };
92
+ return {
93
+ items: queueItems.map(toQueueItemState),
94
+ steerItems: (steerQueueItems ?? []).map(toQueueItemState),
95
+ enqueue: (message) =>
96
+ dispatch({
97
+ type: "run/enqueue",
98
+ message: toWireMessage(message, crypto.randomUUID()),
99
+ }),
100
+ steer: (message) =>
101
+ dispatch({
102
+ type: "run/steer",
103
+ message: toWireMessage(message, crypto.randomUUID()),
104
+ }),
105
+ move: (queueItemId, placement) => {
106
+ const lane = placement.lane ?? laneOf(queueItemId);
107
+ const fields = {
108
+ messageId: queueItemId,
109
+ ...placementFields(placement),
110
+ };
111
+ dispatch(
112
+ lane === "steer"
113
+ ? { type: "run/steer", ...fields }
114
+ : { type: "run/enqueue", ...fields },
115
+ );
116
+ },
117
+ edit: (queueItemId, message) => {
118
+ const wireMessage = toWireMessage(message, queueItemId);
119
+ dispatch(
120
+ laneOf(queueItemId) === "steer"
121
+ ? { type: "run/steer", message: wireMessage }
122
+ : { type: "run/enqueue", message: wireMessage },
123
+ );
124
+ },
125
+ remove: (queueItemId) =>
126
+ dispatch({ type: "run/dequeue", messageId: queueItemId }),
127
+ };
128
+ };
129
+
130
+ export const resolveReloadCommand = (
131
+ messages: readonly { id: string; role: string }[],
132
+ parentId: string | null,
133
+ ): RunReloadCommand => {
134
+ const index =
135
+ parentId === null
136
+ ? 0
137
+ : messages.findIndex((message) => message.id === parentId) + 1;
138
+ if (parentId !== null && index === 0)
139
+ throw new Error(`statewire: run/reload parent "${parentId}" is unknown`);
140
+ const target = messages[index];
141
+ if (target === undefined || target.role !== "assistant")
142
+ throw new Error(
143
+ "statewire: run/reload requires an assistant message to regenerate",
144
+ );
145
+ return { type: "run/reload", sourceId: target.id };
146
+ };