@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.
@@ -0,0 +1,105 @@
1
+ //#region src/runCommands.ts
2
+ const toWireMessage = (message, id) => {
3
+ if (message.role !== "user") throw new Error("statewire: only user messages are supported");
4
+ const files = [];
5
+ const texts = [];
6
+ const source = [...message.content, ...message.attachments?.flatMap((a) => a.content) ?? []];
7
+ for (const part of source) if (part.type === "text") texts.push(part.text);
8
+ else if (part.type === "image") files.push({
9
+ type: "file",
10
+ mediaType: "image/*",
11
+ url: part.image
12
+ });
13
+ else if (part.type === "file") files.push({
14
+ type: "file",
15
+ mediaType: part.mimeType,
16
+ url: part.data,
17
+ ...part.filename !== void 0 && { filename: part.filename }
18
+ });
19
+ else throw new Error(`statewire: unsupported message part "${part.type}"`);
20
+ const parts = [...files, ...texts.length > 0 ? [{
21
+ type: "text",
22
+ text: texts.join("\n\n")
23
+ }] : []];
24
+ if (parts.length === 0) throw new Error("statewire: cannot send an empty message");
25
+ return {
26
+ id,
27
+ role: "user",
28
+ parts
29
+ };
30
+ };
31
+ const toQueueItemState = (item) => ({
32
+ id: item.id,
33
+ prompt: item.parts.flatMap((part) => part.type === "text" ? [part.text] : []).join("\n\n"),
34
+ parts: item.parts.map((part) => part.type === "text" ? part : {
35
+ type: "file",
36
+ data: part.url,
37
+ mimeType: part.mediaType,
38
+ ...part.filename !== void 0 && { filename: part.filename }
39
+ })
40
+ });
41
+ const placementFields = (placement) => ({
42
+ ...placement.insertAfter !== void 0 && { insertAfter: placement.insertAfter },
43
+ ...placement.insertBefore !== void 0 && { insertBefore: placement.insertBefore }
44
+ });
45
+ const createRunQueueAdapter = (queueItems, steerQueueItems, dispatch) => {
46
+ const laneOf = (queueItemId) => {
47
+ if (steerQueueItems?.some((item) => item.id === queueItemId)) return "steer";
48
+ if (queueItems.some((item) => item.id === queueItemId)) return "queue";
49
+ throw new Error(`statewire: unknown queue item "${queueItemId}"`);
50
+ };
51
+ return {
52
+ items: queueItems.map(toQueueItemState),
53
+ steerItems: (steerQueueItems ?? []).map(toQueueItemState),
54
+ enqueue: (message) => dispatch({
55
+ type: "run/enqueue",
56
+ message: toWireMessage(message, crypto.randomUUID())
57
+ }),
58
+ steer: (message) => dispatch({
59
+ type: "run/steer",
60
+ message: toWireMessage(message, crypto.randomUUID())
61
+ }),
62
+ move: (queueItemId, placement) => {
63
+ const lane = placement.lane ?? laneOf(queueItemId);
64
+ const fields = {
65
+ messageId: queueItemId,
66
+ ...placementFields(placement)
67
+ };
68
+ dispatch(lane === "steer" ? {
69
+ type: "run/steer",
70
+ ...fields
71
+ } : {
72
+ type: "run/enqueue",
73
+ ...fields
74
+ });
75
+ },
76
+ edit: (queueItemId, message) => {
77
+ const wireMessage = toWireMessage(message, queueItemId);
78
+ dispatch(laneOf(queueItemId) === "steer" ? {
79
+ type: "run/steer",
80
+ message: wireMessage
81
+ } : {
82
+ type: "run/enqueue",
83
+ message: wireMessage
84
+ });
85
+ },
86
+ remove: (queueItemId) => dispatch({
87
+ type: "run/dequeue",
88
+ messageId: queueItemId
89
+ })
90
+ };
91
+ };
92
+ const resolveReloadCommand = (messages, parentId) => {
93
+ const index = parentId === null ? 0 : messages.findIndex((message) => message.id === parentId) + 1;
94
+ if (parentId !== null && index === 0) throw new Error(`statewire: run/reload parent "${parentId}" is unknown`);
95
+ const target = messages[index];
96
+ if (target === void 0 || target.role !== "assistant") throw new Error("statewire: run/reload requires an assistant message to regenerate");
97
+ return {
98
+ type: "run/reload",
99
+ sourceId: target.id
100
+ };
101
+ };
102
+ //#endregion
103
+ export { createRunQueueAdapter, resolveReloadCommand, toQueueItemState, toWireMessage };
104
+
105
+ //# sourceMappingURL=runCommands.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runCommands.js","names":["AppendMessage","ExternalThreadQueueAdapter","QueuePlacement","FilePart","RunCommand","RunQueueItem","RunReloadCommand","RunUserMessage","TextPart","toWireMessage","message","id","role","Error","files","texts","source","content","attachments","flatMap","a","part","type","push","text","mediaType","url","image","mimeType","data","filename","undefined","parts","length","const","join","toQueueItemState","item","prompt","map","placementFields","placement","insertAfter","insertBefore","createRunQueueAdapter","queueItems","steerQueueItems","dispatch","command","laneOf","queueItemId","some","items","steerItems","enqueue","crypto","randomUUID","steer","move","lane","fields","messageId","edit","wireMessage","remove","resolveReloadCommand","messages","parentId","index","findIndex","target","sourceId"],"sources":["../src/runCommands.ts"],"sourcesContent":["import type {\n AppendMessage,\n ExternalThreadQueueAdapter,\n QueuePlacement,\n} from \"@assistant-ui/core\";\nimport type {\n FilePart,\n RunCommand,\n RunQueueItem,\n RunReloadCommand,\n RunUserMessage,\n TextPart,\n} from \"./types\";\n\nexport const toWireMessage = (\n message: AppendMessage,\n id: string,\n): RunUserMessage => {\n if (message.role !== \"user\")\n throw new Error(\"statewire: only user messages are supported\");\n const files: FilePart[] = [];\n const texts: string[] = [];\n const source = [\n ...message.content,\n ...(message.attachments?.flatMap((a) => a.content) ?? []),\n ];\n for (const part of source) {\n if (part.type === \"text\") {\n texts.push(part.text);\n } else if (part.type === \"image\") {\n files.push({ type: \"file\", mediaType: \"image/*\", url: part.image });\n } else if (part.type === \"file\") {\n files.push({\n type: \"file\",\n mediaType: part.mimeType,\n url: part.data,\n ...(part.filename !== undefined && { filename: part.filename }),\n });\n } else {\n throw new Error(`statewire: unsupported message part \"${part.type}\"`);\n }\n }\n // default-safe against host capabilities: files first, one merged text part\n const parts: (TextPart | FilePart)[] = [\n ...files,\n ...(texts.length > 0\n ? [{ type: \"text\" as const, text: texts.join(\"\\n\\n\") }]\n : []),\n ];\n if (parts.length === 0)\n throw new Error(\"statewire: cannot send an empty message\");\n return { id, role: \"user\", parts };\n};\n\nexport const toQueueItemState = (item: RunQueueItem) => ({\n id: item.id,\n prompt: item.parts\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\"),\n parts: item.parts.map((part) =>\n part.type === \"text\"\n ? part\n : {\n type: \"file\" as const,\n data: part.url,\n mimeType: part.mediaType,\n ...(part.filename !== undefined && { filename: part.filename }),\n },\n ),\n});\n\nconst placementFields = (placement: QueuePlacement) => ({\n ...(placement.insertAfter !== undefined && {\n insertAfter: placement.insertAfter,\n }),\n ...(placement.insertBefore !== undefined && {\n insertBefore: placement.insertBefore,\n }),\n});\n\nexport const createRunQueueAdapter = (\n queueItems: readonly RunQueueItem[],\n steerQueueItems: readonly RunQueueItem[] | undefined,\n dispatch: (command: RunCommand) => void,\n): ExternalThreadQueueAdapter => {\n const laneOf = (queueItemId: string): \"queue\" | \"steer\" => {\n if (steerQueueItems?.some((item) => item.id === queueItemId))\n return \"steer\";\n if (queueItems.some((item) => item.id === queueItemId)) return \"queue\";\n throw new Error(`statewire: unknown queue item \"${queueItemId}\"`);\n };\n return {\n items: queueItems.map(toQueueItemState),\n steerItems: (steerQueueItems ?? []).map(toQueueItemState),\n enqueue: (message) =>\n dispatch({\n type: \"run/enqueue\",\n message: toWireMessage(message, crypto.randomUUID()),\n }),\n steer: (message) =>\n dispatch({\n type: \"run/steer\",\n message: toWireMessage(message, crypto.randomUUID()),\n }),\n move: (queueItemId, placement) => {\n const lane = placement.lane ?? laneOf(queueItemId);\n const fields = {\n messageId: queueItemId,\n ...placementFields(placement),\n };\n dispatch(\n lane === \"steer\"\n ? { type: \"run/steer\", ...fields }\n : { type: \"run/enqueue\", ...fields },\n );\n },\n edit: (queueItemId, message) => {\n const wireMessage = toWireMessage(message, queueItemId);\n dispatch(\n laneOf(queueItemId) === \"steer\"\n ? { type: \"run/steer\", message: wireMessage }\n : { type: \"run/enqueue\", message: wireMessage },\n );\n },\n remove: (queueItemId) =>\n dispatch({ type: \"run/dequeue\", messageId: queueItemId }),\n };\n};\n\nexport const resolveReloadCommand = (\n messages: readonly { id: string; role: string }[],\n parentId: string | null,\n): RunReloadCommand => {\n const index =\n parentId === null\n ? 0\n : messages.findIndex((message) => message.id === parentId) + 1;\n if (parentId !== null && index === 0)\n throw new Error(`statewire: run/reload parent \"${parentId}\" is unknown`);\n const target = messages[index];\n if (target === undefined || target.role !== \"assistant\")\n throw new Error(\n \"statewire: run/reload requires an assistant message to regenerate\",\n );\n return { type: \"run/reload\", sourceId: target.id };\n};\n"],"mappings":"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"}
package/dist/types.d.ts CHANGED
@@ -27,6 +27,12 @@ type AddMessageCommand = {
27
27
  readonly message: UserMessage | AssistantMessage;
28
28
  readonly parentId: string | null;
29
29
  readonly sourceId: string | null;
30
+ /**
31
+ * How the host handles the message while a run is active: `"queue"`
32
+ * appends to the queue, `"steer"` moves it to the front and interrupts
33
+ * the run. Absent, the host decides. Ignored when the host is idle.
34
+ */
35
+ readonly behavior?: "queue" | "steer";
30
36
  };
31
37
  type AddToolResultCommand = {
32
38
  readonly type: "add-tool-result";
@@ -37,30 +43,118 @@ type AddToolResultCommand = {
37
43
  readonly artifact?: ReadonlyJSONValue;
38
44
  readonly modelContent?: readonly ToolModelContentPart[];
39
45
  };
40
- type EnqueueMessageCommand = {
41
- readonly type: "enqueue-message";
42
- readonly message: UserMessage | AssistantMessage;
43
- readonly parentId: string | null;
44
- readonly sourceId: string | null;
45
- readonly steer: boolean;
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;
46
111
  };
47
- type SteerQueueItemCommand = {
48
- readonly type: "steer-queue-item";
49
- readonly queueItemId: string;
112
+ type ToolApprovalInputResponse = {
113
+ readonly decision: "approve" | "reject" | "edit" | "respond";
114
+ readonly editedArgs?: ReadonlyJSONValue;
115
+ readonly message?: string;
50
116
  };
51
- type RemoveQueueItemCommand = {
52
- readonly type: "remove-queue-item";
53
- readonly queueItemId: string;
117
+ type InputResponse = ReadonlyJSONValue;
118
+ type RunInputCommand = {
119
+ readonly type: "run/input";
120
+ readonly requestId: string;
121
+ readonly response: InputResponse;
54
122
  };
55
- type ClearQueueCommand = {
56
- readonly type: "clear-queue";
57
- readonly reason: "edit" | "reload" | "cancel-run";
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)[];
58
137
  };
59
- type AssistantTransportCommand = AddMessageCommand | AddToolResultCommand | EnqueueMessageCommand | SteerQueueItemCommand | RemoveQueueItemCommand | ClearQueueCommand | UserCommands;
60
138
  type AssistantTransportState = {
61
139
  readonly messages: readonly ThreadMessage[];
62
140
  readonly state?: ReadonlyJSONValue;
63
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[];
64
158
  };
65
159
  type AssistantTransportConnectionMetadata = {
66
160
  pendingCommands: AssistantTransportCommand[];
@@ -111,13 +205,16 @@ type AssistantTransportOptions<T> = {
111
205
  /**
112
206
  * Buffer messages sent during a run in an in-memory queue and dispatch
113
207
  * them once the run settles. Steering interrupts the active run.
208
+ * Mutually exclusive with the converter's `queue` projection.
114
209
  */
115
210
  queue?: boolean | undefined;
211
+ /** The host supports `run/continue` (a continue affordance on aborted runs). */
212
+ continue?: boolean | undefined;
116
213
  } | undefined;
117
214
  adapters?: {
118
215
  attachments?: AttachmentAdapter | undefined;
119
216
  } | undefined;
120
217
  };
121
218
  //#endregion
122
- export { AddMessageCommand, AddToolResultCommand, AssistantMessage, AssistantTransportCommand, AssistantTransportConnectionMetadata, AssistantTransportOptions, AssistantTransportProtocol, AssistantTransportState, AssistantTransportStateConverter, ClearQueueCommand, EnqueueMessageCommand, HeadersValue, ImagePart, RemoveQueueItemCommand, SendCommandsRequestBody, SteerQueueItemCommand, TextPart, 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 };
123
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;;KAGC;WACD;WACA;WACA;WACA,QAAQ;WACR;WACA,WAAW;WACX,wBAAwB;;KAGvB;WACD;WACA,SAAS,cAAc;WACvB;WACA;WACA;;KAGC;WACD;WACA;;KAGC;WACD;WACA;;KAGC;WACD;WACA;;KAGC,4BACR,oBACA,uBACA,wBACA,wBACA,yBACA,oBACA;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.1.1",
3
+ "version": "0.3.0",
4
4
  "description": "assistant-ui thread binding for statewire backends",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -30,14 +30,14 @@
30
30
  "test": "vitest run"
31
31
  },
32
32
  "dependencies": {
33
- "@assistant-ui/core": "^0.3.0",
33
+ "@assistant-ui/core": "^0.3.7",
34
34
  "@assistant-ui/store": "^0.3.0",
35
35
  "@assistant-ui/tap": "^0.9.7",
36
36
  "assistant-stream": "^0.3.33",
37
- "statewire": "^0.0.4"
37
+ "statewire": "^0.0.5"
38
38
  },
39
39
  "peerDependencies": {
40
- "@assistant-ui/react": ">=0.14.0",
40
+ "@assistant-ui/react": ">=0.15.6",
41
41
  "react": "^18 || ^19"
42
42
  },
43
43
  "devDependencies": {
@@ -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
- AddMessageCommand,
41
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
- ): AddMessageCommand | 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: "add-message",
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);
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) {
@@ -266,7 +299,7 @@ const useAssistantTransportThread = (
266
299
  cancel: () => driverRef.current.cancel(),
267
300
  });
268
301
  } else if (!enableQueue && queueRef.current) {
269
- queueRef.current.adapter.clear("cancel-run");
302
+ queueRef.current.clear();
270
303
  queueRef.current = null;
271
304
  }
272
305
  const messageQueue = queueRef.current;
@@ -278,6 +311,11 @@ const useAssistantTransportThread = (
278
311
  () => messageQueue?.adapter.items ?? EMPTY_QUEUE_ITEMS,
279
312
  () => EMPTY_QUEUE_ITEMS,
280
313
  );
314
+ const steerQueueItems = useSyncExternalStore(
315
+ messageQueue?.subscribe ?? subscribeNoop,
316
+ () => messageQueue?.adapter.steerItems ?? EMPTY_QUEUE_ITEMS,
317
+ () => EMPTY_QUEUE_ITEMS,
318
+ );
281
319
 
282
320
  // settled edge: the queue only advances once the host run loop has fully
283
321
  // released (isSending), the converted state agrees, and no client tool from
@@ -301,22 +339,45 @@ const useAssistantTransportThread = (
301
339
  extras,
302
340
  attachmentAdapter: options.adapters?.attachments,
303
341
  onNew: handleAppend,
304
- ...(messageQueue && {
305
- queue: { ...messageQueue.adapter, items: queueItems },
306
- }),
307
- ...(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 }),
308
352
  onReload: (parentId: string | null) => {
309
- void toolInvocations.abort().then(() => {
310
- void commands.reload(parentId).catch(() => {});
311
- });
353
+ const command = resolveReloadCommand(
354
+ convertedRef.current.messages,
355
+ parentId,
356
+ );
357
+ void toolInvocations.abort().then(() => dispatch(command));
358
+ },
359
+ onCancel: () => {
360
+ // user cancel drops pending lanes; a steer interrupt (driver.cancel) keeps them
361
+ messageQueue?.clear();
362
+ handleCancel();
312
363
  },
313
- onCancel: handleCancel,
314
364
  onResume: () => {
365
+ if (options.capabilities?.continue) {
366
+ dispatch({ type: "run/continue" });
367
+ return;
368
+ }
315
369
  if (!options.resumeApi)
316
370
  throw new Error("Must pass resumeApi to options to resume runs");
317
371
  void commands.resume().catch(() => {});
318
372
  },
319
373
  onAddToolResult: (toolOptions: AddToolResultOptions) => {
374
+ const requests = convertedRef.current.inputRequests;
375
+ const inputCommand =
376
+ requests && resolveToolResultInput(requests, toolOptions);
377
+ if (inputCommand) {
378
+ dispatch(inputCommand);
379
+ return;
380
+ }
320
381
  const command: AddToolResultCommand = {
321
382
  type: "add-tool-result",
322
383
  toolCallId: toolOptions.toolCallId,
@@ -331,6 +392,15 @@ const useAssistantTransportThread = (
331
392
 
332
393
  dispatch(command);
333
394
  },
395
+ ...(inputRequests !== undefined && {
396
+ onRespondToToolApproval: (options: RespondToToolApprovalOptions) =>
397
+ dispatch(
398
+ resolveToolApprovalInput(
399
+ convertedRef.current.inputRequests!,
400
+ options,
401
+ ),
402
+ ),
403
+ }),
334
404
  onResumeToolCall: ({ toolCallId, payload }: ResumeToolCallOptions) => {
335
405
  if (!toolInvocations.resume(toolCallId, payload))
336
406
  throw new Error(`Tool call ${toolCallId} is not waiting for resume.`);