@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/dist/AssistantTransportThread.d.ts +4 -4
- package/dist/AssistantTransportThread.d.ts.map +1 -1
- package/dist/AssistantTransportThread.js +65 -45
- package/dist/AssistantTransportThread.js.map +1 -1
- package/dist/StatewireThread.d.ts +122 -10
- package/dist/StatewireThread.d.ts.map +1 -1
- package/dist/StatewireThread.js +90 -38
- package/dist/StatewireThread.js.map +1 -1
- package/dist/host.d.ts +0 -1
- package/dist/host.d.ts.map +1 -1
- package/dist/host.js +20 -12
- package/dist/host.js.map +1 -1
- package/dist/index.d.ts +21 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/inputRequests.d.ts +14 -0
- package/dist/inputRequests.d.ts.map +1 -0
- package/dist/inputRequests.js +35 -0
- package/dist/inputRequests.js.map +1 -0
- package/dist/runCommands.d.ts +22 -0
- package/dist/runCommands.d.ts.map +1 -0
- package/dist/runCommands.js +105 -0
- package/dist/runCommands.js.map +1 -0
- package/dist/types.d.ts +114 -17
- package/dist/types.d.ts.map +1 -1
- package/package.json +4 -4
- package/src/AssistantTransportThread.ts +120 -50
- package/src/StatewireThread.test.tsx +587 -61
- package/src/StatewireThread.ts +310 -47
- package/src/__tests__/testHelpers.tsx +1 -1
- package/src/athena.e2e.test.tsx +34 -25
- package/src/host.ts +23 -11
- package/src/index.ts +20 -4
- package/src/inputRequests.ts +57 -0
- package/src/legacy-diff.test.tsx +32 -8
- package/src/runCommands.ts +146 -0
- package/src/transport.test.tsx +581 -57
- package/src/types.ts +133 -19
package/dist/StatewireThread.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { createRunQueueAdapter, resolveReloadCommand, toWireMessage } from "./runCommands.js";
|
|
2
|
+
import { resolveToolApprovalInput, resolveToolResultInput } from "./inputRequests.js";
|
|
3
|
+
import { symbolAssistantTransportExtras } from "./AssistantTransportThread.js";
|
|
2
4
|
import { useCallback, useEffect, useMemo, useRef, useState } from "@assistant-ui/tap/react-shim";
|
|
3
5
|
import { resource, useResource } from "@assistant-ui/tap";
|
|
4
6
|
import { ExternalThread } from "@assistant-ui/react";
|
|
@@ -12,13 +14,48 @@ const ambientContextOf = (context) => ({
|
|
|
12
14
|
...context.callSettings !== void 0 && { callSettings: context.callSettings },
|
|
13
15
|
...context.config !== void 0 && { config: context.config }
|
|
14
16
|
});
|
|
17
|
+
const convertAppendMessageToCommand = (message) => {
|
|
18
|
+
if (message.role !== "user") throw new Error("Only user messages are supported");
|
|
19
|
+
const parts = [];
|
|
20
|
+
const content = [...message.content, ...message.attachments?.flatMap((a) => a.content) ?? []];
|
|
21
|
+
for (const contentPart of content) if (contentPart.type === "text") parts.push({
|
|
22
|
+
type: "text",
|
|
23
|
+
text: contentPart.text
|
|
24
|
+
});
|
|
25
|
+
else if (contentPart.type === "image") parts.push({
|
|
26
|
+
type: "image",
|
|
27
|
+
image: contentPart.image
|
|
28
|
+
});
|
|
29
|
+
if (parts.length === 0) return null;
|
|
30
|
+
return {
|
|
31
|
+
type: "add-message",
|
|
32
|
+
message: {
|
|
33
|
+
role: "user",
|
|
34
|
+
parts
|
|
35
|
+
},
|
|
36
|
+
parentId: message.parentId,
|
|
37
|
+
sourceId: message.sourceId
|
|
38
|
+
};
|
|
39
|
+
};
|
|
40
|
+
const withSessionLostFallback = (transport, latest) => {
|
|
41
|
+
const [transportOptions, ...rest] = transport.args;
|
|
42
|
+
if (rest.length > 0 || typeof transportOptions !== "object" || transportOptions === null) throw new Error("statewire: onCommandSessionLost requires a transport element that takes a single options object");
|
|
43
|
+
const transportLevel = transportOptions.onCommandSessionLost;
|
|
44
|
+
return {
|
|
45
|
+
...transport,
|
|
46
|
+
args: [{
|
|
47
|
+
...transportOptions,
|
|
48
|
+
onCommandSessionLost: (command) => transportLevel?.(command) ?? latest.current.onCommandSessionLost?.(command)
|
|
49
|
+
}]
|
|
50
|
+
};
|
|
51
|
+
};
|
|
15
52
|
const useStatewireThread = (options) => {
|
|
16
53
|
const latest = useRef(options);
|
|
17
54
|
latest.current = options;
|
|
18
55
|
const [pending, setPending] = useState([]);
|
|
19
56
|
const [retire] = useState(() => (command) => setPending((prev) => prev.includes(command) ? prev.filter((c) => c !== command) : prev));
|
|
20
57
|
const { state: transportState, commands, connection, setContext } = useStatewire({
|
|
21
|
-
transport: options.transport,
|
|
58
|
+
transport: options.onCommandSessionLost === void 0 ? options.transport : withSessionLostFallback(options.transport, latest),
|
|
22
59
|
onCommandChange: (update) => {
|
|
23
60
|
if (update.status === "acked" || update.status === "settled") retire(update.params[0]);
|
|
24
61
|
}
|
|
@@ -68,49 +105,47 @@ const useStatewireThread = (options) => {
|
|
|
68
105
|
state,
|
|
69
106
|
metadata
|
|
70
107
|
]);
|
|
71
|
-
const convertedRef = useRef(converted);
|
|
72
|
-
convertedRef.current = converted;
|
|
73
108
|
const queueItems = converted.queue;
|
|
109
|
+
const steerQueueItems = converted.steerQueue;
|
|
110
|
+
if (steerQueueItems !== void 0 && queueItems === void 0) throw new Error("statewire: the converter's steerQueue projection requires the queue projection");
|
|
74
111
|
const [queueSeam] = useState(() => ({ present: queueItems !== void 0 }));
|
|
75
112
|
if (queueSeam.present !== (queueItems !== void 0)) throw new Error("statewire: the converter's queue projection must be stable — it was " + (queueSeam.present ? "defined" : "undefined") + " on first convert and changed since");
|
|
76
|
-
const queue = useMemo(() => queueItems
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
steer
|
|
85
|
-
} : command_1);
|
|
86
|
-
},
|
|
87
|
-
steer: (queueItemId) => dispatch({
|
|
88
|
-
type: "steer-queue-item",
|
|
89
|
-
queueItemId
|
|
90
|
-
}),
|
|
91
|
-
remove: (queueItemId_0) => dispatch({
|
|
92
|
-
type: "remove-queue-item",
|
|
93
|
-
queueItemId: queueItemId_0
|
|
94
|
-
}),
|
|
95
|
-
clear: (reason) => dispatch({
|
|
96
|
-
type: "clear-queue",
|
|
97
|
-
reason
|
|
98
|
-
})
|
|
99
|
-
}, [queueItems, dispatch]);
|
|
113
|
+
const queue = useMemo(() => queueItems ? createRunQueueAdapter(queueItems, steerQueueItems, dispatch) : void 0, [
|
|
114
|
+
queueItems,
|
|
115
|
+
steerQueueItems,
|
|
116
|
+
dispatch
|
|
117
|
+
]);
|
|
118
|
+
const inputRequests = converted.inputRequests;
|
|
119
|
+
const [inputSeam] = useState(() => ({ present: inputRequests !== void 0 }));
|
|
120
|
+
if (inputSeam.present !== (inputRequests !== void 0)) throw new Error("statewire: the converter's inputRequests projection must be stable — it was " + (inputSeam.present ? "defined" : "undefined") + " on first convert and changed since");
|
|
100
121
|
const extras = useMemo(() => ({
|
|
101
122
|
[symbolAssistantTransportExtras]: true,
|
|
102
123
|
sendCommand: dispatch,
|
|
103
124
|
reconnect: connection.reconnect,
|
|
104
|
-
state
|
|
125
|
+
state,
|
|
126
|
+
...inputRequests !== void 0 && { inputRequests }
|
|
105
127
|
}), [
|
|
106
128
|
dispatch,
|
|
107
129
|
connection.reconnect,
|
|
108
|
-
state
|
|
130
|
+
state,
|
|
131
|
+
inputRequests
|
|
109
132
|
]);
|
|
110
|
-
const handleAppend = (
|
|
111
|
-
const
|
|
112
|
-
if (!
|
|
113
|
-
dispatch(
|
|
133
|
+
const handleAppend = (message) => {
|
|
134
|
+
const command_1 = convertAppendMessageToCommand(message);
|
|
135
|
+
if (!command_1) return;
|
|
136
|
+
dispatch(command_1);
|
|
137
|
+
};
|
|
138
|
+
const handleReload = (parentId) => {
|
|
139
|
+
dispatch(resolveReloadCommand(converted.messages, parentId));
|
|
140
|
+
};
|
|
141
|
+
const handleEdit = (message_0) => {
|
|
142
|
+
if (!queueItems) return handleAppend(message_0);
|
|
143
|
+
if (message_0.sourceId == null) throw new Error("statewire: run/edit requires a sourceId");
|
|
144
|
+
dispatch({
|
|
145
|
+
type: "run/edit",
|
|
146
|
+
message: toWireMessage(message_0, crypto.randomUUID()),
|
|
147
|
+
sourceId: message_0.sourceId
|
|
148
|
+
});
|
|
114
149
|
};
|
|
115
150
|
return useResource(ExternalThread({
|
|
116
151
|
messages: converted.messages,
|
|
@@ -121,11 +156,28 @@ const useStatewireThread = (options) => {
|
|
|
121
156
|
attachmentAdapter: options.adapters?.attachments,
|
|
122
157
|
onNew: handleAppend,
|
|
123
158
|
...queue && { queue },
|
|
124
|
-
...options.capabilities?.edit && { onEdit:
|
|
159
|
+
...options.capabilities?.edit && { onEdit: handleEdit },
|
|
160
|
+
...options.capabilities?.continue && { onResume: () => dispatch({ type: "run/continue" }) },
|
|
161
|
+
...options.capabilities?.reload && { onReload: handleReload },
|
|
162
|
+
...inputRequests !== void 0 && {
|
|
163
|
+
onAddToolResult: (toolOptions) => {
|
|
164
|
+
const inputCommand = resolveToolResultInput(inputRequests, toolOptions);
|
|
165
|
+
dispatch(inputCommand ?? {
|
|
166
|
+
type: "add-tool-result",
|
|
167
|
+
toolCallId: toolOptions.toolCallId,
|
|
168
|
+
toolName: toolOptions.toolName,
|
|
169
|
+
result: toolOptions.result,
|
|
170
|
+
isError: toolOptions.isError,
|
|
171
|
+
...toolOptions.artifact !== void 0 && { artifact: toolOptions.artifact },
|
|
172
|
+
...toolOptions.modelContent !== void 0 && { modelContent: toolOptions.modelContent }
|
|
173
|
+
});
|
|
174
|
+
},
|
|
175
|
+
onRespondToToolApproval: (approval) => dispatch(resolveToolApprovalInput(inputRequests, approval))
|
|
176
|
+
},
|
|
125
177
|
onCancel: () => {
|
|
126
|
-
const payload = latest.current.
|
|
127
|
-
if (payload !== void 0 && (typeof payload !== "object" || payload === null || Array.isArray(payload))) throw new Error("statewire:
|
|
128
|
-
commands["
|
|
178
|
+
const payload = latest.current.stopPayload?.();
|
|
179
|
+
if (payload !== void 0 && (typeof payload !== "object" || payload === null || Array.isArray(payload))) throw new Error("statewire: stopPayload must return a plain object");
|
|
180
|
+
commands["run/stop"](...payload === void 0 ? [] : [payload]).catch((error_1) => {
|
|
129
181
|
latest.current.onError?.(error_1);
|
|
130
182
|
});
|
|
131
183
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","AppendMessage","AttachmentAdapter","ExternalThreadQueueAdapter","ModelContext","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","StatewireClient","convertAppendMessageToCommand","symbolAssistantTransportExtras","AssistantTransportExtras","AssistantTransportCommand","AnyCommands","Record","args","ambientContextOf","context","system","undefined","tools","callSettings","config","useStatewireThread","options","StatewireThread","Options","latest","current","pending","setPending","retire","command","prev","includes","filter","c","state","transportState","commands","connection","setContext","transport","onCommandChange","update","status","params","attached","initialState","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","catch","error","Error","onError","subscribe","dispatch","type","converter","metadata","ConnectionMetadata","pendingCommands","isSending","length","converted","convertedRef","queueItems","queue","queueSeam","present","items","enqueue","message","steer","isRunning","queueItemId","remove","clear","reason","extras","sendCommand","reconnect","handleAppend","messages","isLoading","attachmentAdapter","adapters","attachments","onNew","capabilities","edit","onEdit","onCancel","payload","cancelPayload","Array","isArray","T","Transport","QueueItem","id","prompt","State","ConnectionState","StateConverter","connectionMetadata","CancelPayload","hook"],"sources":["../src/StatewireThread.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { resource, useResource } from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/react\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/react\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport type {\n AppendMessage,\n AttachmentAdapter,\n ExternalThreadQueueAdapter,\n ModelContext,\n ThreadMessage,\n} from \"@assistant-ui/core\";\nimport { toToolsJSONSchema } from \"assistant-stream\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { useStatewire } from \"statewire\";\nimport type { Statewire, StatewireClient } from \"statewire\";\nimport {\n convertAppendMessageToCommand,\n symbolAssistantTransportExtras,\n} from \"./AssistantTransportThread\";\nimport type { AssistantTransportExtras } from \"./AssistantTransportThread\";\nimport type { AssistantTransportCommand } from \"./types\";\n\ntype AnyCommands = Record<string, (...args: any[]) => unknown>;\n\nconst ambientContextOf = (context: ModelContext): Record<string, unknown> => ({\n ...(context.system !== undefined && { system: context.system }),\n ...(context.tools !== undefined && {\n tools: toToolsJSONSchema(context.tools),\n }),\n ...(context.callSettings !== undefined && {\n callSettings: context.callSettings,\n }),\n ...(context.config !== undefined && { config: context.config }),\n});\n\nconst useStatewireThread = (\n options: StatewireThread.Options<any>,\n): ClientOutput<\"thread\"> => {\n const latest = useRef(options);\n latest.current = options;\n\n const [pending, setPending] = useState<readonly AssistantTransportCommand[]>(\n [],\n );\n const [retire] = useState(\n () => (command: unknown) =>\n setPending((prev) =>\n prev.includes(command as AssistantTransportCommand)\n ? prev.filter((c) => c !== command)\n : prev,\n ),\n );\n\n const {\n state: transportState,\n commands,\n connection,\n setContext,\n } = useStatewire<unknown, AnyCommands>({\n transport: options.transport,\n onCommandChange: (update) => {\n if (update.status === \"acked\" || update.status === \"settled\")\n retire(update.params[0]);\n },\n });\n const attached = transportState !== undefined;\n const state = attached ? transportState : options.initialState;\n\n const clientRef = useAssistantClientRef();\n const setContextRef = useRef(setContext);\n setContextRef.current = setContext;\n const [syncState] = useState(() => ({ lastSent: undefined as unknown }));\n const { contextSync } = options;\n useEffect(() => {\n if (contextSync === undefined) return;\n const modelContext = (clientRef.current ?? clientRef.parent).modelContext();\n const send = () => {\n const value = ambientContextOf(modelContext.getModelContext());\n const key = JSON.stringify(value);\n if (key === syncState.lastSent) return;\n syncState.lastSent = key;\n void setContextRef.current(value).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n };\n send();\n if (!modelContext.subscribe) {\n throw new Error(\n \"statewire: contextSync requires a subscribable model context\",\n );\n }\n return modelContext.subscribe(send);\n }, [contextSync, clientRef, syncState]);\n\n const dispatch = useCallback(\n (command: AssistantTransportCommand) => {\n setPending((prev) => [...prev, command]);\n void commands[command.type]!(command).catch((error: Error) => {\n retire(command);\n latest.current.onError?.(error);\n });\n },\n [commands, retire],\n );\n\n const { converter } = options;\n const metadata = useMemo(\n (): StatewireThread.ConnectionMetadata => ({\n pendingCommands: [...pending],\n isSending: pending.length > 0,\n connection,\n }),\n [pending, connection],\n );\n const converted = useMemo(\n () => converter(state, metadata),\n [converter, state, metadata],\n );\n const convertedRef = useRef(converted);\n convertedRef.current = converted;\n\n const queueItems = converted.queue;\n const [queueSeam] = useState(() => ({\n present: queueItems !== undefined,\n }));\n if (queueSeam.present !== (queueItems !== undefined))\n throw new Error(\n \"statewire: the converter's queue projection must be stable — it was \" +\n (queueSeam.present ? \"defined\" : \"undefined\") +\n \" on first convert and changed since\",\n );\n\n const queue = useMemo(\n (): ExternalThreadQueueAdapter | undefined =>\n queueItems && {\n items: queueItems,\n enqueue: (message, { steer }) => {\n const command = convertAppendMessageToCommand(message);\n if (!command) return;\n dispatch(\n convertedRef.current.isRunning\n ? { ...command, type: \"enqueue-message\", steer }\n : command,\n );\n },\n steer: (queueItemId) =>\n dispatch({ type: \"steer-queue-item\", queueItemId }),\n remove: (queueItemId) =>\n dispatch({ type: \"remove-queue-item\", queueItemId }),\n clear: (reason) => dispatch({ type: \"clear-queue\", reason }),\n },\n [queueItems, dispatch],\n );\n\n const extras = useMemo(\n (): AssistantTransportExtras => ({\n [symbolAssistantTransportExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state,\n }),\n [dispatch, connection.reconnect, state],\n );\n\n const handleAppend = (message: AppendMessage) => {\n const command = convertAppendMessageToCommand(message);\n if (!command) return;\n dispatch(command);\n };\n\n return useResource(\n ExternalThread({\n messages: converted.messages as readonly ExternalThreadMessage[],\n isRunning: converted.isRunning,\n isLoading: !attached,\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n onNew: handleAppend,\n ...(queue && { queue }),\n ...(options.capabilities?.edit && { onEdit: handleAppend }),\n onCancel: () => {\n const payload = latest.current.cancelPayload?.();\n if (\n payload !== undefined &&\n (typeof payload !== \"object\" ||\n payload === null ||\n Array.isArray(payload))\n )\n throw new Error(\n \"statewire: cancelPayload must return a plain object\",\n );\n void commands[\"cancel\"]!(\n ...(payload === undefined ? [] : [payload]),\n ).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n },\n }),\n );\n};\n\nexport const StatewireThread = <T>(\n options: StatewireThread.Options<T>,\n): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useStatewireThread)(options as StatewireThread.Options<any>);\n\nexport namespace StatewireThread {\n export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;\n\n export type QueueItem = {\n readonly id: string;\n readonly prompt: string;\n };\n\n export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n readonly isRunning: boolean;\n /**\n * Server-owned message queue projected out of the state. Returning it\n * (even empty) turns on the queue capability: sends during a run become\n * `enqueue-message` commands and item controls send the queue commands.\n * Presence must be stable across conversions.\n */\n readonly queue?: readonly QueueItem[];\n };\n\n export type ConnectionMetadata = {\n pendingCommands: AssistantTransportCommand[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `live`. */\n connection: StatewireClient.ConnectionState;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n /**\n * Payload of the built-in `cancel` command. `reason` is the one well-known\n * field; apps extend it with their own JSON-serializable fields.\n */\n export type CancelPayload = {\n readonly reason?: string | undefined;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n export type Options<T> = {\n transport: Transport<T>;\n initialState: T;\n converter: StateConverter<T>;\n /**\n * \"command-send\" mirrors the client's ambient model context (system,\n * tools, callSettings, config) to the server over the command channel —\n * on connect and whenever it changes. Requires a remote transport.\n */\n contextSync?: \"command-send\" | undefined;\n /** Supplies the `cancel` command's payload; omitted, cancel sends no payload. */\n cancelPayload?: (() => CancelPayload) | undefined;\n onError?: ((error: Error) => void) | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n }\n | undefined;\n };\n}\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useStatewireThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;AA8BA,MAAM8B,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWC,KAAAA,KAAa,EAAED,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQG,UAAUD,KAAAA,KAAa,EACjCC,OAAOhB,kBAAkBa,QAAQG,KAAK,EACxC;CACA,GAAIH,QAAQI,iBAAiBF,KAAAA,KAAa,EACxCE,cAAcJ,QAAQI,aACxB;CACA,GAAIJ,QAAQK,WAAWH,KAAAA,KAAa,EAAEG,QAAQL,QAAQK,OAAO;AAC/D;AAEA,MAAMC,sBACJC,YAC2B;CAC3B,MAAMG,SAAStC,OAAOmC,OAAO;CAC7BG,OAAOC,UAAUJ;CAEjB,MAAM,CAACK,SAASC,cAAcxC,SAC5B,CAAA,CACF;CACA,MAAM,CAACyC,UAAUzC,gBACR0C,YACLF,YAAYG,SACVA,KAAKC,SAASF,OAAoC,IAC9CC,KAAKE,QAAQC,MAAMA,MAAMJ,OAAO,IAChCC,IACN,CACJ;CAEA,MAAM,EACJI,OAAOC,gBACPC,UACAC,YACAC,eACEnC,aAAmC;EACrCoC,WAAWlB,QAAQkB;EACnBC,kBAAkBC,WAAW;GAC3B,IAAIA,OAAOC,WAAW,WAAWD,OAAOC,WAAW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YACLE,eAAe;EACboG,UAAUnB,UAAUmB;EACpBT,WAAWV,UAAUU;EACrBU,WAAW,CAAChD;EACZV,OAAOsC,UAAUtC;EACjBqD;EACAM,mBAAmBxE,QAAQyE,UAAUC;EACrCC,OAAON;EACP,GAAIf,SAAS,EAAEA,MAAM;EACrB,GAAItD,QAAQ4E,cAAcC,QAAQ,EAAEC,QAAQT,aAAa;EACzDU,gBAAgB;GACd,MAAMC,UAAU7E,OAAOC,QAAQ6E,gBAAgB;GAC/C,IACED,YAAYrF,KAAAA,MACX,OAAOqF,YAAY,YAClBA,YAAY,QACZE,MAAMC,QAAQH,OAAO,IAEvB,MAAM,IAAIxC,MACR,qDACF;GACF,SAAc,SAAS,CACrB,GAAIwC,YAAYrF,KAAAA,IAAY,CAAA,IAAK,CAACqF,OAAO,CAC3C,CAAC,CAAC1C,OAAOC,YAAiB;IACxBpC,OAAOC,QAAQqC,UAAUF,OAAK;GAChC,CAAC;EACH;CACF,CAAC,CACH;AACF;AAEA,MAAatC,mBACXD,YAEAjC,SAASgC,kBAAkB,CAAC,CAACC,OAAuC;AAuEtE5B,uBACE2B,oBACA7B,eAAeyB,KAAAA,CAAkB,CAAC,CAACmG,IACrC"}
|
|
1
|
+
{"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","AddToolResultOptions","AppendMessage","AttachmentAdapter","ExternalThreadQueueAdapter","ModelContext","RespondToToolApprovalOptions","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","StatewireClient","symbolAssistantTransportExtras","AssistantTransportExtras","createRunQueueAdapter","resolveReloadCommand","toWireMessage","resolveToolApprovalInput","resolveToolResultInput","AddMessageCommand","AssistantTransportCommand","UserMessagePart","AnyCommands","Record","args","ambientContextOf","context","system","undefined","tools","callSettings","config","convertAppendMessageToCommand","message","role","Error","parts","content","attachments","flatMap","a","contentPart","type","push","text","image","length","parentId","sourceId","withSessionLostFallback","transport","StatewireThread","Transport","latest","current","Options","transportOptions","rest","transportLevel","onCommandSessionLost","command","SessionLostCommand","useStatewireThread","options","pending","setPending","Command","retire","prev","includes","filter","c","state","transportState","commands","connection","setContext","onCommandChange","update","status","params","attached","initialState","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","catch","error","onError","subscribe","dispatch","converter","metadata","ConnectionMetadata","pendingCommands","isSending","converted","queueItems","queue","steerQueueItems","steerQueue","queueSeam","present","inputRequests","inputSeam","extras","sendCommand","reconnect","handleAppend","handleReload","messages","handleEdit","crypto","randomUUID","isRunning","isLoading","attachmentAdapter","adapters","onNew","capabilities","edit","onEdit","continue","onResume","reload","onReload","onAddToolResult","toolOptions","inputCommand","toolCallId","toolName","result","isError","artifact","modelContent","onRespondToToolApproval","approval","onCancel","payload","stopPayload","Array","isArray","T","TextPart","FilePart","mediaType","url","filename","UserMessage","id","Placement","insertAfter","insertBefore","RunEnqueueCommand","messageId","RunSteerCommand","RunDequeueCommand","RunEditCommand","RunContinueCommand","ToolCallInputRequest","ToolApprovalInputRequest","CustomInputRequest","InputRequest","ToolCallInputResponse","output","ToolApprovalInputResponse","decision","editedArgs","InputResponse","RunInputCommand","requestId","response","InputRequestState","RunReloadCommand","RunCommand","QueueItem","State","ConnectionState","StateConverter","connectionMetadata","StopPayload","reason","hook"],"sources":["../src/StatewireThread.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { resource, useResource } from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/react\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/react\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n AttachmentAdapter,\n ExternalThreadQueueAdapter,\n ModelContext,\n RespondToToolApprovalOptions,\n ThreadMessage,\n} from \"@assistant-ui/core\";\nimport { toToolsJSONSchema } from \"assistant-stream\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { useStatewire } from \"statewire\";\nimport type { Statewire, StatewireClient } from \"statewire\";\nimport { symbolAssistantTransportExtras } from \"./AssistantTransportThread\";\nimport type { AssistantTransportExtras } from \"./AssistantTransportThread\";\nimport {\n createRunQueueAdapter,\n resolveReloadCommand,\n toWireMessage,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\nimport type {\n AddMessageCommand,\n AssistantTransportCommand,\n UserMessagePart,\n} from \"./types\";\n\ntype AnyCommands = Record<string, (...args: any[]) => unknown>;\n\nconst ambientContextOf = (context: ModelContext): Record<string, unknown> => ({\n ...(context.system !== undefined && { system: context.system }),\n ...(context.tools !== undefined && {\n tools: toToolsJSONSchema(context.tools),\n }),\n ...(context.callSettings !== undefined && {\n callSettings: context.callSettings,\n }),\n ...(context.config !== undefined && { config: context.config }),\n});\n\nconst convertAppendMessageToCommand = (\n message: AppendMessage,\n): AddMessageCommand | null => {\n if (message.role !== \"user\")\n throw new Error(\"Only user messages are supported\");\n\n const parts: UserMessagePart[] = [];\n const content = [\n ...message.content,\n ...(message.attachments?.flatMap((a) => a.content) ?? []),\n ];\n for (const contentPart of content) {\n if (contentPart.type === \"text\") {\n parts.push({ type: \"text\", text: contentPart.text });\n } else if (contentPart.type === \"image\") {\n parts.push({ type: \"image\", image: contentPart.image });\n }\n }\n\n if (parts.length === 0) return null;\n\n return {\n type: \"add-message\",\n message: {\n role: \"user\",\n parts,\n },\n parentId: message.parentId,\n sourceId: message.sourceId,\n };\n};\n\nconst withSessionLostFallback = (\n transport: StatewireThread.Transport<any>,\n latest: { current: StatewireThread.Options<any> },\n): StatewireThread.Transport<any> => {\n const [transportOptions, ...rest] = transport.args as [\n Record<string, unknown>,\n ...unknown[],\n ];\n if (\n rest.length > 0 ||\n typeof transportOptions !== \"object\" ||\n transportOptions === null\n ) {\n throw new Error(\n \"statewire: onCommandSessionLost requires a transport element that takes a single options object\",\n );\n }\n const transportLevel = transportOptions.onCommandSessionLost as\n | ((command: StatewireClient.SessionLostCommand) => \"replay\" | void)\n | undefined;\n return {\n ...transport,\n args: [\n {\n ...transportOptions,\n onCommandSessionLost: (\n command: StatewireClient.SessionLostCommand,\n ): \"replay\" | void =>\n transportLevel?.(command) ??\n latest.current.onCommandSessionLost?.(command),\n },\n ],\n };\n};\n\nconst useStatewireThread = (\n options: StatewireThread.Options<any>,\n): ClientOutput<\"thread\"> => {\n const latest = useRef(options);\n latest.current = options;\n\n const [pending, setPending] = useState<readonly StatewireThread.Command[]>(\n [],\n );\n const [retire] = useState(\n () => (command: unknown) =>\n setPending((prev) =>\n prev.includes(command as StatewireThread.Command)\n ? prev.filter((c) => c !== command)\n : prev,\n ),\n );\n\n const {\n state: transportState,\n commands,\n connection,\n setContext,\n } = useStatewire<unknown, AnyCommands>({\n transport:\n options.onCommandSessionLost === undefined\n ? options.transport\n : withSessionLostFallback(options.transport, latest),\n onCommandChange: (update) => {\n if (update.status === \"acked\" || update.status === \"settled\")\n retire(update.params[0]);\n },\n });\n const attached = transportState !== undefined;\n const state = attached ? transportState : options.initialState;\n\n const clientRef = useAssistantClientRef();\n const setContextRef = useRef(setContext);\n setContextRef.current = setContext;\n const [syncState] = useState(() => ({ lastSent: undefined as unknown }));\n const { contextSync } = options;\n useEffect(() => {\n if (contextSync === undefined) return;\n const modelContext = (clientRef.current ?? clientRef.parent).modelContext();\n const send = () => {\n const value = ambientContextOf(modelContext.getModelContext());\n const key = JSON.stringify(value);\n if (key === syncState.lastSent) return;\n syncState.lastSent = key;\n void setContextRef.current(value).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n };\n send();\n if (!modelContext.subscribe) {\n throw new Error(\n \"statewire: contextSync requires a subscribable model context\",\n );\n }\n return modelContext.subscribe(send);\n }, [contextSync, clientRef, syncState]);\n\n const dispatch = useCallback(\n (command: StatewireThread.Command) => {\n setPending((prev) => [...prev, command]);\n void commands[command.type]!(command).catch((error: Error) => {\n retire(command);\n latest.current.onError?.(error);\n });\n },\n [commands, retire],\n );\n\n const { converter } = options;\n const metadata = useMemo(\n (): StatewireThread.ConnectionMetadata => ({\n pendingCommands: [...pending],\n isSending: pending.length > 0,\n connection,\n }),\n [pending, connection],\n );\n const converted = useMemo(\n () => converter(state, metadata),\n [converter, state, metadata],\n );\n const queueItems = converted.queue;\n const steerQueueItems = converted.steerQueue;\n if (steerQueueItems !== undefined && queueItems === undefined)\n throw new Error(\n \"statewire: the converter's steerQueue projection requires the queue projection\",\n );\n const [queueSeam] = useState(() => ({\n present: queueItems !== undefined,\n }));\n if (queueSeam.present !== (queueItems !== undefined))\n throw new Error(\n \"statewire: the converter's queue projection must be stable — it was \" +\n (queueSeam.present ? \"defined\" : \"undefined\") +\n \" on first convert and changed since\",\n );\n\n const queue = useMemo(\n (): ExternalThreadQueueAdapter | undefined =>\n queueItems\n ? createRunQueueAdapter(queueItems, steerQueueItems, dispatch)\n : undefined,\n [queueItems, steerQueueItems, dispatch],\n );\n\n const inputRequests = converted.inputRequests;\n const [inputSeam] = useState(() => ({\n present: inputRequests !== undefined,\n }));\n if (inputSeam.present !== (inputRequests !== undefined))\n throw new Error(\n \"statewire: the converter's inputRequests projection must be stable — it was \" +\n (inputSeam.present ? \"defined\" : \"undefined\") +\n \" on first convert and changed since\",\n );\n\n const extras = useMemo(\n (): AssistantTransportExtras => ({\n [symbolAssistantTransportExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state,\n ...(inputRequests !== undefined && { inputRequests }),\n }),\n [dispatch, connection.reconnect, state, inputRequests],\n );\n\n const handleAppend = (message: AppendMessage) => {\n const command = convertAppendMessageToCommand(message);\n if (!command) return;\n dispatch(command);\n };\n\n const handleReload = (parentId: string | null) => {\n dispatch(resolveReloadCommand(converted.messages, parentId));\n };\n\n const handleEdit = (message: AppendMessage) => {\n if (!queueItems) return handleAppend(message);\n if (message.sourceId == null)\n throw new Error(\"statewire: run/edit requires a sourceId\");\n dispatch({\n type: \"run/edit\",\n message: toWireMessage(message, crypto.randomUUID()),\n sourceId: message.sourceId,\n });\n };\n\n return useResource(\n ExternalThread({\n messages: converted.messages as readonly ExternalThreadMessage[],\n isRunning: converted.isRunning,\n isLoading: !attached,\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n onNew: handleAppend,\n ...(queue && { queue }),\n ...(options.capabilities?.edit && { onEdit: handleEdit }),\n ...(options.capabilities?.continue && {\n onResume: () => dispatch({ type: \"run/continue\" }),\n }),\n ...(options.capabilities?.reload && { onReload: handleReload }),\n ...(inputRequests !== undefined && {\n onAddToolResult: (toolOptions: AddToolResultOptions) => {\n const inputCommand = resolveToolResultInput(\n inputRequests,\n toolOptions,\n );\n dispatch(\n inputCommand ?? {\n type: \"add-tool-result\",\n toolCallId: toolOptions.toolCallId,\n toolName: toolOptions.toolName,\n result: toolOptions.result,\n isError: toolOptions.isError,\n ...(toolOptions.artifact !== undefined && {\n artifact: toolOptions.artifact,\n }),\n ...(toolOptions.modelContent !== undefined && {\n modelContent: toolOptions.modelContent,\n }),\n },\n );\n },\n onRespondToToolApproval: (approval: RespondToToolApprovalOptions) =>\n dispatch(resolveToolApprovalInput(inputRequests, approval)),\n }),\n onCancel: () => {\n const payload = latest.current.stopPayload?.();\n if (\n payload !== undefined &&\n (typeof payload !== \"object\" ||\n payload === null ||\n Array.isArray(payload))\n )\n throw new Error(\"statewire: stopPayload must return a plain object\");\n void commands[\"run/stop\"]!(\n ...(payload === undefined ? [] : [payload]),\n ).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n },\n }),\n );\n};\n\nexport const StatewireThread = <T>(\n options: StatewireThread.Options<T>,\n): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useStatewireThread)(options as StatewireThread.Options<any>);\n\nexport namespace StatewireThread {\n export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;\n\n export type TextPart = {\n readonly type: \"text\";\n readonly text: string;\n };\n\n export type FilePart = {\n readonly type: \"file\";\n readonly mediaType: string;\n readonly url: string;\n readonly filename?: string;\n };\n\n export type UserMessage = {\n readonly id: string;\n readonly role: \"user\";\n readonly parts: readonly (TextPart | FilePart)[];\n readonly metadata?: Record<string, unknown>;\n };\n\n /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */\n export type Placement = {\n readonly insertAfter?: string | null;\n readonly insertBefore?: string | null;\n };\n\n export type RunEnqueueCommand = {\n readonly type: \"run/enqueue\";\n } & ({ readonly message: UserMessage } | { readonly messageId: string }) &\n Placement;\n\n export type RunSteerCommand = {\n readonly type: \"run/steer\";\n } & ({ readonly message: UserMessage } | { readonly messageId: string }) &\n Placement;\n\n export type RunDequeueCommand = {\n readonly type: \"run/dequeue\";\n readonly messageId: string;\n };\n\n export type RunEditCommand = {\n readonly type: \"run/edit\";\n readonly message: UserMessage;\n readonly sourceId: string;\n };\n\n export type RunContinueCommand = {\n readonly type: \"run/continue\";\n };\n\n export type ToolCallInputRequest = {\n readonly type: \"tool-call\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type ToolApprovalInputRequest = {\n readonly type: \"tool-approval\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type CustomInputRequest = {\n readonly type: string;\n readonly id: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A host request parking the run until answered; open union for custom types. */\n export type InputRequest =\n | ToolCallInputRequest\n | ToolApprovalInputRequest\n | CustomInputRequest;\n\n export type ToolCallInputResponse = {\n readonly output: ReadonlyJSONValue;\n /** Default false; when true, `output` carries the error payload. */\n readonly isError?: boolean;\n readonly artifact?: ReadonlyJSONValue;\n };\n\n export type ToolApprovalInputResponse = {\n readonly decision: \"approve\" | \"reject\" | \"edit\" | \"respond\";\n readonly editedArgs?: ReadonlyJSONValue;\n readonly message?: string;\n };\n\n export type InputResponse = ReadonlyJSONValue;\n\n export type RunInputCommand = {\n readonly type: \"run/input\";\n readonly requestId: string;\n readonly response: InputResponse;\n };\n\n /** An input request projected out of the host state with its response echo. */\n export type InputRequestState = InputRequest & {\n readonly response: InputResponse | null;\n };\n\n export type RunReloadCommand = {\n readonly type: \"run/reload\";\n readonly sourceId: string;\n };\n\n export type RunCommand =\n | RunEnqueueCommand\n | RunSteerCommand\n | RunDequeueCommand\n | RunEditCommand\n | RunContinueCommand\n | RunReloadCommand\n | RunInputCommand;\n\n export type Command = AssistantTransportCommand | RunCommand;\n\n /** A queued message projected out of the host state, wire shape. */\n export type QueueItem = {\n readonly id: string;\n readonly parts: readonly (TextPart | FilePart)[];\n };\n\n export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n readonly isRunning: boolean;\n /**\n * The host's regular queue lane projected out of the state. Returning it\n * (even empty) turns on the queue capability: sends become `run/enqueue`\n * / `run/steer` commands and item controls send the `run/*` queue\n * commands. Presence must be stable across conversions.\n */\n readonly queue?: readonly QueueItem[];\n /** The host's steer lane; requires `queue`. Absent means empty. */\n readonly steerQueue?: readonly QueueItem[];\n /**\n * The host's parked input requests projected out of the state. Returning\n * it (even empty) routes tool results and approvals with a matching\n * pending request through `run/input`. Presence must be stable across\n * conversions.\n */\n readonly inputRequests?: readonly InputRequestState[];\n };\n\n export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `live`. */\n connection: StatewireClient.ConnectionState;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n /**\n * Payload of the built-in `run/stop` command. `reason` is the one well-known\n * field; apps extend it with their own JSON-serializable fields.\n */\n export type StopPayload = {\n readonly reason?: string | undefined;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n export type Options<T> = {\n transport: Transport<T>;\n initialState: T;\n converter: StateConverter<T>;\n /**\n * \"command-send\" mirrors the client's ambient model context (system,\n * tools, callSettings, config) to the server over the command channel —\n * on connect and whenever it changes. Requires a remote transport.\n */\n contextSync?: \"command-send\" | undefined;\n /** Supplies the `run/stop` command's payload; omitted, stop sends no payload. */\n stopPayload?: (() => StopPayload) | undefined;\n /**\n * Offered each pending command when a remote transport's session is\n * evicted; return \"replay\" to re-enqueue it under the rotated client id.\n * A callback set on the transport options is consulted first; this one\n * runs for commands it declined.\n */\n onCommandSessionLost?:\n | ((command: StatewireClient.SessionLostCommand) => \"replay\" | void)\n | undefined;\n onError?: ((error: Error) => void) | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n /** The host supports `run/continue` (a continue affordance on aborted runs). */\n continue?: boolean | undefined;\n /** The host supports `run/reload` (regenerating an assistant message). */\n reload?: boolean | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n }\n | undefined;\n };\n}\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useStatewireThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;;;AA0CA,MAAMsC,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWC,KAAAA,KAAa,EAAED,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQG,UAAUD,KAAAA,KAAa,EACjCC,OAAOtB,kBAAkBmB,QAAQG,KAAK,EACxC;CACA,GAAIH,QAAQI,iBAAiBF,KAAAA,KAAa,EACxCE,cAAcJ,QAAQI,aACxB;CACA,GAAIJ,QAAQK,WAAWH,KAAAA,KAAa,EAAEG,QAAQL,QAAQK,OAAO;AAC/D;AAEA,MAAMC,iCACJC,YAC6B;CAC7B,IAAIA,QAAQC,SAAS,QACnB,MAAM,IAAIC,MAAM,kCAAkC;CAEpD,MAAMC,QAA2B,CAAA;CACjC,MAAMC,UAAU,CACd,GAAGJ,QAAQI,SACX,GAAIJ,QAAQK,aAAaC,SAASC,MAAMA,EAAEH,OAAO,KAAK,CAAA,CAA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UAAU/F,OAAOC,QAAQ+F,cAAc;GAC7C,IACED,YAAYxH,KAAAA,MACX,OAAOwH,YAAY,YAClBA,YAAY,QACZE,MAAMC,QAAQH,OAAO,IAEvB,MAAM,IAAIjH,MAAM,mDAAmD;GACrE,SAAc,WAAW,CACvB,GAAIiH,YAAYxH,KAAAA,IAAY,CAAA,IAAK,CAACwH,OAAO,CAC3C,CAAC,CAACpD,OAAOC,YAAiB;IACxB5C,OAAOC,QAAQ4C,UAAUD,OAAK;GAChC,CAAC;EACH;CACF,CAAC,CACH;AACF;AAEA,MAAa9C,mBACXY,YAEAvE,SAASsE,kBAAkB,CAAC,CAACC,OAAuC;AAkNtElE,uBACEiE,oBACAnE,eAAeiC,KAAAA,CAAkB,CAAC,CAACoK,IACrC"}
|
package/dist/host.d.ts
CHANGED
|
@@ -31,7 +31,6 @@ type AssistantTransportHostCommands = {
|
|
|
31
31
|
setParentId(parentId: string | null): void;
|
|
32
32
|
cancel(): void;
|
|
33
33
|
resume(): void;
|
|
34
|
-
reload(parentId: string | null): void;
|
|
35
34
|
importState(state: unknown): void;
|
|
36
35
|
};
|
|
37
36
|
declare const AssistantTransportHost: import("@assistant-ui/tap").Resource<Statewire<AssistantTransportHostState, AssistantTransportHostCommands, any>, [options: HostOptions]>;
|
package/dist/host.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"host.d.ts","names":[],"sources":["../src/host.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"host.d.ts","names":[],"sources":["../src/host.ts"],"mappings":";;;;KA0BY;EACV;;KAGU;EACV,cAAc;EACd;;KAGU;EACV,QAAQ;EACR,WAAW;;KAMD;EAAkB,SAAS;;KAE3B,cAAc;EACxB,qBAAqB;EACrB,WAAW;;KAGD;EACV;EACA;EACA;EACA;;KAGU;EACV,KAAK,SAAS,2BAA2B,OAAO;EAChD,YAAY;EACZ;EACA;EACA,YAAY;;cAwXD,oDAAsB,SAAA,UAAA,6BAAA,uCAAA,SAAA"}
|
package/dist/host.js
CHANGED
|
@@ -5,7 +5,7 @@ import { resource } from "@assistant-ui/tap";
|
|
|
5
5
|
import { createRequestHeaders } from "@assistant-ui/core";
|
|
6
6
|
import { AssistantTransportDecoder, DataStreamDecoder, toToolsJSONSchema } from "assistant-stream";
|
|
7
7
|
import { asAsyncIterableStream } from "assistant-stream/utils";
|
|
8
|
-
import {
|
|
8
|
+
import { useStatewireCommands, useStatewireEmit, useStatewireState } from "statewire/host";
|
|
9
9
|
//#region src/host.ts
|
|
10
10
|
const commandsOf = (entries) => entries.map((e) => e.command);
|
|
11
11
|
const useHostLoop = (getOptions, ctl, getAgent) => {
|
|
@@ -213,8 +213,10 @@ const useHostLoop = (getOptions, ctl, getAgent) => {
|
|
|
213
213
|
resolveActive();
|
|
214
214
|
} catch (error_1) {
|
|
215
215
|
s.followUpRequested = false;
|
|
216
|
-
if (!s.disposed)
|
|
217
|
-
|
|
216
|
+
if (!s.disposed) {
|
|
217
|
+
if (ac.signal.aborted) settleCancelled();
|
|
218
|
+
else await settleFailed(error_1);
|
|
219
|
+
}
|
|
218
220
|
} finally {
|
|
219
221
|
if (s.disposed) s.abortController = null;
|
|
220
222
|
else {
|
|
@@ -236,17 +238,26 @@ const useHostLoop = (getOptions, ctl, getAgent) => {
|
|
|
236
238
|
startRun();
|
|
237
239
|
};
|
|
238
240
|
return {
|
|
239
|
-
send: (command, opts)
|
|
240
|
-
|
|
241
|
+
send: function(command, opts) {
|
|
242
|
+
let resolve;
|
|
243
|
+
let reject;
|
|
244
|
+
const promise = new Promise((res, rej) => {
|
|
245
|
+
resolve = res;
|
|
246
|
+
reject = rej;
|
|
247
|
+
});
|
|
241
248
|
setQueue({
|
|
242
249
|
queued: [...s.queue.queued, {
|
|
243
250
|
command,
|
|
244
|
-
execution:
|
|
251
|
+
execution: {
|
|
252
|
+
ack: this.ack,
|
|
253
|
+
resolve,
|
|
254
|
+
reject
|
|
255
|
+
}
|
|
245
256
|
}],
|
|
246
257
|
inTransit: s.queue.inTransit
|
|
247
258
|
});
|
|
248
259
|
if (opts?.schedule !== false) schedule();
|
|
249
|
-
return
|
|
260
|
+
return promise;
|
|
250
261
|
},
|
|
251
262
|
setParentId: (id) => {
|
|
252
263
|
s.parentId = id;
|
|
@@ -261,10 +272,6 @@ const useHostLoop = (getOptions, ctl, getAgent) => {
|
|
|
261
272
|
s.resumeRequested = true;
|
|
262
273
|
schedule();
|
|
263
274
|
},
|
|
264
|
-
reload: (id_0) => {
|
|
265
|
-
s.parentId = id_0;
|
|
266
|
-
schedule();
|
|
267
|
-
},
|
|
268
275
|
importState: replaceAgent
|
|
269
276
|
};
|
|
270
277
|
};
|
|
@@ -278,9 +285,10 @@ const useAssistantTransportHost = (options) => {
|
|
|
278
285
|
isReplaying: false
|
|
279
286
|
}));
|
|
280
287
|
const emit = useStatewireEmit();
|
|
288
|
+
const handlers = useHostLoop(() => latestOptions.current, ctl, () => ctl.snapshot().agent);
|
|
281
289
|
return {
|
|
282
290
|
state,
|
|
283
|
-
commands: useStatewireCommands(
|
|
291
|
+
commands: useStatewireCommands(handlers),
|
|
284
292
|
emit
|
|
285
293
|
};
|
|
286
294
|
};
|
package/dist/host.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"host.js","names":["useEffect","useRef","useState","resource","createRequestHeaders","ModelContext","AssistantTransportDecoder","DataStreamDecoder","toToolsJSONSchema","AssistantTransportStateOperation","asAsyncIterableStream","Statewire","CommandExecution","useStatewireCommands","useStatewireEmit","useStatewireState","StatewireHost","createReplayBoundaryStream","translateStateOp","AssistantTransportCommand","AssistantTransportOptions","SendCommandsRequestBody","SendOptions","schedule","HostRunContext","modelContext","threadId","HostQueue","queued","inTransit","HostQueueCell","current","HostOptions","getRunContext","queueCell","AssistantTransportHostState","agent","queueVersion","isSending","isReplaying","AssistantTransportHostCommands","send","command","opts","setParentId","parentId","cancel","resume","reload","importState","state","QueueEntry","execution","ExecutionResolvers","EntryQueue","commandsOf","entries","map","e","LoopState","queue","activeEntries","resumeRequested","followUpRequested","disposed","abortController","AbortController","useHostLoop","getOptions","ctl","StateCtl","getAgent","s","undefined","abort","setReplaying","value","apply","op","path","setSending","replaceAgent","next","updateState","updater","applyChunkOps","operations","operation","setQueue","takeQueuedIntoTransit","length","drainQueue","drained","buildRequestBody","o","commands","runParentId","bodyValue","body","requestBody","Record","system","tools","callSettings","config","prepareSendCommandsRequest","run","signal","AbortSignal","isResume","runRequest","error","aborted","headers","response","fetch","resumeApi","api","method","JSON","stringify","onResponse","ok","Error","status","text","strict","decoder","protocol","streamError","delivered","markDelivered","entry","ack","chunks","pipeThrough","chunk","type","resolveActive","splice","resolve","settleCancelled","onCancel","settleFailed","reject","onError","startRun","ac","setTimeout","onFinish","resolvers","withResolvers","id","useAssistantTransportHost","options","latestOptions","initialState","emit","handlers","snapshot","AssistantTransportHost"],"sources":["../src/host.ts"],"sourcesContent":["import { useEffect, useRef, useState } from \"react\";\nimport { resource } from \"@assistant-ui/tap\";\nimport { createRequestHeaders } from \"@assistant-ui/core\";\nimport type { ModelContext } from \"@assistant-ui/core\";\nimport {\n AssistantTransportDecoder,\n DataStreamDecoder,\n toToolsJSONSchema,\n} from \"assistant-stream\";\nimport type { AssistantTransportStateOperation } from \"assistant-stream\";\nimport { asAsyncIterableStream } from \"assistant-stream/utils\";\nimport type { Statewire } from \"statewire\";\nimport {\n CommandExecution,\n useStatewireCommands,\n useStatewireEmit,\n useStatewireState,\n} from \"statewire/host\";\nimport type { StatewireHost } from \"statewire/host\";\nimport { createReplayBoundaryStream } from \"./replayBoundaryStream\";\nimport { translateStateOp } from \"./stateOps\";\nimport type {\n AssistantTransportCommand,\n AssistantTransportOptions,\n SendCommandsRequestBody,\n} from \"./types\";\n\nexport type SendOptions = {\n schedule?: boolean;\n};\n\nexport type HostRunContext = {\n modelContext: ModelContext;\n threadId: string | null;\n};\n\nexport type HostQueue = {\n queued: AssistantTransportCommand[];\n inTransit: AssistantTransportCommand[];\n};\n\n// Statewire state sanitizes values on apply; command objects must keep their\n// identity for converter-side caches, so the host publishes them through this\n// cell and bumps queueVersion in state to signal the change.\nexport type HostQueueCell = { current: HostQueue };\n\nexport type HostOptions = AssistantTransportOptions<unknown> & {\n getRunContext: () => HostRunContext;\n queueCell: HostQueueCell;\n};\n\nexport type AssistantTransportHostState = {\n agent: unknown;\n queueVersion: number;\n isSending: boolean;\n isReplaying: boolean;\n};\n\nexport type AssistantTransportHostCommands = {\n send(command: AssistantTransportCommand, opts?: SendOptions): void;\n setParentId(parentId: string | null): void;\n cancel(): void;\n resume(): void;\n reload(parentId: string | null): void;\n importState(state: unknown): void;\n};\n\ntype QueueEntry = {\n command: AssistantTransportCommand;\n execution: StatewireHost.ExecutionResolvers;\n};\n\ntype EntryQueue = {\n queued: QueueEntry[];\n inTransit: QueueEntry[];\n};\n\nconst commandsOf = (entries: QueueEntry[]) => entries.map((e) => e.command);\n\ntype LoopState = {\n queue: EntryQueue;\n activeEntries: QueueEntry[];\n parentId: string | null | undefined;\n resumeRequested: boolean;\n followUpRequested: boolean;\n isReplaying: boolean;\n disposed: boolean;\n abortController: AbortController | null;\n queueVersion: number;\n};\n\nconst useHostLoop = (\n getOptions: () => HostOptions,\n ctl: StatewireHost.StateCtl,\n getAgent: () => unknown,\n) => {\n const [s] = useState(\n (): LoopState => ({\n queue: { queued: [], inTransit: [] },\n activeEntries: [],\n parentId: undefined,\n resumeRequested: false,\n followUpRequested: false,\n isReplaying: false,\n disposed: false,\n abortController: null,\n queueVersion: 0,\n }),\n );\n\n useEffect(() => {\n s.disposed = false;\n return () => {\n s.disposed = true;\n s.followUpRequested = false;\n s.abortController?.abort();\n };\n }, [s]);\n\n const setReplaying = (value: boolean) => {\n if (s.isReplaying === value) return;\n s.isReplaying = value;\n ctl.apply([{ op: \"replace\", path: [\"isReplaying\"], value }]);\n };\n\n const setSending = (value: boolean) => {\n ctl.apply([{ op: \"replace\", path: [\"isSending\"], value }]);\n };\n\n const replaceAgent = (next: unknown) => {\n ctl.apply([{ op: \"replace\", path: [\"agent\"], value: next }]);\n };\n\n const updateState = (updater: (state: unknown) => unknown) => {\n replaceAgent(updater(getAgent()));\n };\n\n // Ops commit one-by-one — an op error leaves the chunk's prefix applied.\n const applyChunkOps = (\n operations: readonly AssistantTransportStateOperation[],\n ) => {\n for (const operation of operations) {\n const op = translateStateOp(getAgent(), operation);\n if (op === undefined) continue;\n ctl.apply([{ ...op, path: [\"agent\", ...op.path] }]);\n }\n };\n\n const setQueue = (next: EntryQueue) => {\n s.queue = next;\n getOptions().queueCell.current = {\n queued: commandsOf(next.queued),\n inTransit: commandsOf(next.inTransit),\n };\n ctl.apply([\n { op: \"replace\", path: [\"queueVersion\"], value: ++s.queueVersion },\n ]);\n };\n\n const takeQueuedIntoTransit = (): QueueEntry[] => {\n const { queued, inTransit } = s.queue;\n if (queued.length === 0) return [];\n setQueue({ queued: [], inTransit: [...inTransit, ...queued] });\n return queued;\n };\n\n const drainQueue = (): EntryQueue => {\n const drained = s.queue;\n setQueue({ queued: [], inTransit: [] });\n return drained;\n };\n\n const buildRequestBody = async (\n o: HostOptions,\n commands: AssistantTransportCommand[],\n runParentId: string | null | undefined,\n ) => {\n const bodyValue = typeof o.body === \"function\" ? await o.body() : o.body;\n const { modelContext, threadId } = o.getRunContext();\n\n const requestBody: Record<string, unknown> = {\n commands,\n state: getAgent(),\n system: modelContext.system,\n tools: modelContext.tools\n ? toToolsJSONSchema(modelContext.tools)\n : undefined,\n threadId,\n ...(runParentId !== undefined && { parentId: runParentId }),\n callSettings: modelContext.callSettings,\n config: modelContext.config,\n // deprecated top-level spread, kept for legacy parity\n ...modelContext.callSettings,\n ...modelContext.config,\n ...(bodyValue ?? {}),\n };\n\n if (!o.prepareSendCommandsRequest) return requestBody;\n return o.prepareSendCommandsRequest(requestBody as SendCommandsRequestBody);\n };\n\n const run = async (signal: AbortSignal) => {\n const o = getOptions();\n const isResume = s.resumeRequested;\n s.resumeRequested = false;\n setReplaying(false);\n s.activeEntries = isResume ? [] : takeQueuedIntoTransit();\n if (s.activeEntries.length === 0 && !isResume && s.parentId === undefined)\n return;\n\n const runParentId = s.parentId;\n s.parentId = undefined;\n try {\n await runRequest(o, isResume, runParentId, signal);\n } catch (error) {\n if (!signal.aborted && s.parentId === undefined) s.parentId = runParentId;\n throw error;\n }\n };\n\n const runRequest = async (\n o: HostOptions,\n isResume: boolean,\n runParentId: string | null | undefined,\n signal: AbortSignal,\n ) => {\n const headers = await createRequestHeaders(o.headers);\n const requestBody = await buildRequestBody(\n o,\n commandsOf(s.activeEntries),\n runParentId,\n );\n\n const response = await fetch(isResume ? o.resumeApi! : o.api, {\n method: \"POST\",\n headers,\n body: JSON.stringify(requestBody),\n signal,\n });\n\n o.onResponse?.(response);\n\n if (!response.ok) {\n throw new Error(`Status ${response.status}: ${await response.text()}`);\n }\n if (!response.body) {\n throw new Error(\"Response body is null\");\n }\n\n const body = await createReplayBoundaryStream(response, setReplaying);\n const strict = !isResume;\n const decoder =\n (o.protocol ?? \"data-stream\") === \"assistant-transport\"\n ? new AssistantTransportDecoder({ strict })\n : new DataStreamDecoder({ strict });\n\n let streamError: string | undefined;\n let delivered = false;\n\n const markDelivered = () => {\n for (const entry of s.activeEntries) entry.execution.ack();\n setQueue({ ...s.queue, inTransit: [] });\n delivered = true;\n };\n\n const chunks = body.pipeThrough(decoder);\n for await (const chunk of asAsyncIterableStream(chunks)) {\n if (chunk.type === \"error\") {\n streamError = chunk.error;\n continue;\n }\n if (chunk.type !== \"update-state\" || chunk.operations.length === 0)\n continue;\n\n applyChunkOps(chunk.operations);\n\n // only after the chunk committed — a failing first chunk must leave\n // the commands in transit for onError (legacy parity)\n if (!delivered) markDelivered();\n }\n\n if (streamError) {\n throw new Error(streamError);\n }\n\n if (!delivered) markDelivered();\n\n // commands that coalesced into a resume run must not starve\n if (isResume && s.queue.queued.length > 0) s.followUpRequested = true;\n };\n\n const resolveActive = () => {\n for (const entry of s.activeEntries.splice(0)) entry.execution.resolve();\n };\n\n const settleCancelled = () => {\n setReplaying(false);\n const { queued, inTransit } = drainQueue();\n resolveActive();\n for (const entry of [...inTransit, ...queued]) entry.execution.resolve();\n getOptions().onCancel?.({\n commands: commandsOf([...inTransit, ...queued]),\n updateState,\n });\n };\n\n const settleFailed = async (error: Error) => {\n setReplaying(false);\n const { queued, inTransit } = drainQueue();\n for (const entry of inTransit) entry.execution.reject(error);\n resolveActive();\n try {\n await getOptions().onError?.(error, {\n commands: commandsOf(inTransit),\n updateState,\n });\n } finally {\n getOptions().onCancel?.({\n commands: commandsOf(queued),\n updateState,\n error,\n });\n for (const entry of queued) entry.execution.resolve();\n }\n };\n\n const startRun = () => {\n s.followUpRequested = false;\n const ac = new AbortController();\n s.abortController = ac;\n setSending(true);\n\n // macrotask: every command admitted this turn coalesces into the take\n setTimeout(async () => {\n try {\n await run(ac.signal);\n resolveActive();\n } catch (error) {\n s.followUpRequested = false;\n // disposed means unmounted mid-run: the abort is ours, no callbacks\n if (!s.disposed) {\n if (ac.signal.aborted) settleCancelled();\n else await settleFailed(error as Error);\n }\n } finally {\n if (s.disposed) {\n s.abortController = null;\n } else {\n getOptions().onFinish?.();\n if (s.followUpRequested) {\n startRun();\n } else {\n s.abortController = null;\n setSending(false);\n }\n }\n }\n }, 0);\n };\n\n const schedule = () => {\n if (s.abortController) {\n s.followUpRequested = true;\n return;\n }\n startRun();\n };\n\n return {\n send: (command: AssistantTransportCommand, opts?: SendOptions) => {\n const [execution, resolvers] = CommandExecution.withResolvers();\n setQueue({\n queued: [...s.queue.queued, { command, execution: resolvers }],\n inTransit: s.queue.inTransit,\n });\n if (opts?.schedule !== false) schedule();\n return execution;\n },\n setParentId: (id: string | null) => {\n s.parentId = id;\n },\n cancel: () => {\n s.resumeRequested = false;\n s.followUpRequested = false;\n s.abortController?.abort();\n },\n resume: () => {\n if (!getOptions().resumeApi)\n throw new Error(\"Must pass resumeApi to options to resume runs\");\n\n s.resumeRequested = true;\n schedule();\n },\n reload: (id: string | null) => {\n s.parentId = id;\n schedule();\n },\n importState: replaceAgent,\n };\n};\n\nconst useAssistantTransportHost = (\n options: HostOptions,\n): Statewire<AssistantTransportHostState, AssistantTransportHostCommands> => {\n const latestOptions = useRef(options);\n latestOptions.current = options;\n\n const [state, ctl] = useStatewireState<AssistantTransportHostState>(() => ({\n agent: options.initialState,\n queueVersion: 0,\n isSending: false,\n isReplaying: false,\n }));\n const emit = useStatewireEmit();\n\n const handlers = useHostLoop(\n () => latestOptions.current,\n ctl,\n () => ctl.snapshot().agent,\n );\n\n const commands = useStatewireCommands(handlers);\n\n return { state, commands, emit };\n};\n\nexport const AssistantTransportHost = resource(useAssistantTransportHost);\n"],"mappings":";;;;;;;;;AA6EA,MAAMuD,cAAcC,YAA0BA,QAAQC,KAAKC,MAAMA,EAAEhB,OAAO;AAc1E,MAAMyB,eACJC,YACAC,KACAE,aACG;CACH,MAAM,CAACC,KAAKtE,gBACQ;EAChB0D,OAAO;GAAEhC,QAAQ,CAAA;GAAIC,WAAW,CAAA;EAAG;EACnCgC,eAAe,CAAA;EACfhB,UAAU4B,KAAAA;EACVX,iBAAiB;EACjBC,mBAAmB;EACnBxB,aAAa;EACbyB,UAAU;EACVC,iBAAiB;EACjB5B,cAAc;CAChB,EACF;CAEArC,gBAAgB;EACdwE,EAAER,WAAW;EACb,aAAa;GACXQ,EAAER,WAAW;GACbQ,EAAET,oBAAoB;GACtBS,EAAEP,iBAAiBS,MAAM;EAC3B;CACF,GAAG,CAACF,CAAC,CAAC;CAEN,MAAMG,gBAAgBC,UAAmB;EACvC,IAAIJ,EAAEjC,gBAAgBqC,OAAO;EAC7BJ,EAAEjC,cAAcqC;EAChBP,IAAIQ,MAAM,CAAC;GAAEC,IAAI;GAAWC,MAAM,CAAC,aAAa;GAAGH;EAAM,CAAC,CAAC;CAC7D;CAEA,MAAMI,cAAcJ,YAAmB;EACrCP,IAAIQ,MAAM,CAAC;GAAEC,IAAI;GAAWC,MAAM,CAAC,WAAW;GAAGH,OAAAA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,WAAW;EACXC,aAAa;CACf,EAAE;CACF,MAAMsH,OAAO/I,iBAAiB;CAU9B,OAAO;EAAEoC;EAAO6C,UAFClF,qBANAsD,kBACTwF,cAAc5H,SACpBsC,WACMA,IAAI0F,SAAS,CAAC,CAAC3H,KAGe0H,CAEtB/D;EAAU8D;CAAK;AACjC;AAEA,MAAaG,yBAAyB7J,SAASsJ,yBAAyB"}
|
|
1
|
+
{"version":3,"file":"host.js","names":["useEffect","useRef","useState","resource","createRequestHeaders","ModelContext","AssistantTransportDecoder","DataStreamDecoder","toToolsJSONSchema","AssistantTransportStateOperation","asAsyncIterableStream","Statewire","useStatewireCommands","useStatewireEmit","useStatewireState","StatewireHost","createReplayBoundaryStream","translateStateOp","AssistantTransportCommand","AssistantTransportOptions","SendCommandsRequestBody","SendOptions","schedule","HostRunContext","modelContext","threadId","HostQueue","queued","inTransit","HostQueueCell","current","HostOptions","getRunContext","queueCell","AssistantTransportHostState","agent","queueVersion","isSending","isReplaying","AssistantTransportHostCommands","send","command","opts","setParentId","parentId","cancel","resume","importState","state","EntrySettlement","ack","resolve","reject","error","QueueEntry","execution","EntryQueue","commandsOf","entries","map","e","LoopState","queue","activeEntries","resumeRequested","followUpRequested","disposed","abortController","AbortController","useHostLoop","getOptions","ctl","StateCtl","getAgent","s","undefined","abort","setReplaying","value","apply","op","path","setSending","replaceAgent","next","updateState","updater","applyChunkOps","operations","operation","setQueue","takeQueuedIntoTransit","length","drainQueue","drained","buildRequestBody","o","commands","runParentId","bodyValue","body","requestBody","Record","system","tools","callSettings","config","prepareSendCommandsRequest","run","signal","AbortSignal","isResume","runRequest","aborted","headers","response","fetch","resumeApi","api","method","JSON","stringify","onResponse","ok","Error","status","text","strict","decoder","protocol","streamError","delivered","markDelivered","entry","chunks","pipeThrough","chunk","type","resolveActive","splice","settleCancelled","onCancel","settleFailed","onError","startRun","ac","setTimeout","onFinish","this","Ctx","promise","Promise","res","rej","id","useAssistantTransportHost","options","latestOptions","initialState","emit","handlers","snapshot","AssistantTransportHost"],"sources":["../src/host.ts"],"sourcesContent":["import { useEffect, useRef, useState } from \"react\";\nimport { resource } from \"@assistant-ui/tap\";\nimport { createRequestHeaders } from \"@assistant-ui/core\";\nimport type { ModelContext } from \"@assistant-ui/core\";\nimport {\n AssistantTransportDecoder,\n DataStreamDecoder,\n toToolsJSONSchema,\n} from \"assistant-stream\";\nimport type { AssistantTransportStateOperation } from \"assistant-stream\";\nimport { asAsyncIterableStream } from \"assistant-stream/utils\";\nimport type { Statewire } from \"statewire\";\nimport {\n useStatewireCommands,\n useStatewireEmit,\n useStatewireState,\n} from \"statewire/host\";\nimport type { StatewireHost } from \"statewire/host\";\nimport { createReplayBoundaryStream } from \"./replayBoundaryStream\";\nimport { translateStateOp } from \"./stateOps\";\nimport type {\n AssistantTransportCommand,\n AssistantTransportOptions,\n SendCommandsRequestBody,\n} from \"./types\";\n\nexport type SendOptions = {\n schedule?: boolean;\n};\n\nexport type HostRunContext = {\n modelContext: ModelContext;\n threadId: string | null;\n};\n\nexport type HostQueue = {\n queued: AssistantTransportCommand[];\n inTransit: AssistantTransportCommand[];\n};\n\n// Statewire state sanitizes values on apply; command objects must keep their\n// identity for converter-side caches, so the host publishes them through this\n// cell and bumps queueVersion in state to signal the change.\nexport type HostQueueCell = { current: HostQueue };\n\nexport type HostOptions = AssistantTransportOptions<unknown> & {\n getRunContext: () => HostRunContext;\n queueCell: HostQueueCell;\n};\n\nexport type AssistantTransportHostState = {\n agent: unknown;\n queueVersion: number;\n isSending: boolean;\n isReplaying: boolean;\n};\n\nexport type AssistantTransportHostCommands = {\n send(command: AssistantTransportCommand, opts?: SendOptions): void;\n setParentId(parentId: string | null): void;\n cancel(): void;\n resume(): void;\n importState(state: unknown): void;\n};\n\ntype EntrySettlement = {\n ack: () => void;\n resolve: () => void;\n reject: (error: unknown) => void;\n};\n\ntype QueueEntry = {\n command: AssistantTransportCommand;\n execution: EntrySettlement;\n};\n\ntype EntryQueue = {\n queued: QueueEntry[];\n inTransit: QueueEntry[];\n};\n\nconst commandsOf = (entries: QueueEntry[]) => entries.map((e) => e.command);\n\ntype LoopState = {\n queue: EntryQueue;\n activeEntries: QueueEntry[];\n parentId: string | null | undefined;\n resumeRequested: boolean;\n followUpRequested: boolean;\n isReplaying: boolean;\n disposed: boolean;\n abortController: AbortController | null;\n queueVersion: number;\n};\n\nconst useHostLoop = (\n getOptions: () => HostOptions,\n ctl: StatewireHost.StateCtl,\n getAgent: () => unknown,\n) => {\n const [s] = useState(\n (): LoopState => ({\n queue: { queued: [], inTransit: [] },\n activeEntries: [],\n parentId: undefined,\n resumeRequested: false,\n followUpRequested: false,\n isReplaying: false,\n disposed: false,\n abortController: null,\n queueVersion: 0,\n }),\n );\n\n useEffect(() => {\n s.disposed = false;\n return () => {\n s.disposed = true;\n s.followUpRequested = false;\n s.abortController?.abort();\n };\n }, [s]);\n\n const setReplaying = (value: boolean) => {\n if (s.isReplaying === value) return;\n s.isReplaying = value;\n ctl.apply([{ op: \"replace\", path: [\"isReplaying\"], value }]);\n };\n\n const setSending = (value: boolean) => {\n ctl.apply([{ op: \"replace\", path: [\"isSending\"], value }]);\n };\n\n const replaceAgent = (next: unknown) => {\n ctl.apply([{ op: \"replace\", path: [\"agent\"], value: next }]);\n };\n\n const updateState = (updater: (state: unknown) => unknown) => {\n replaceAgent(updater(getAgent()));\n };\n\n // Ops commit one-by-one — an op error leaves the chunk's prefix applied.\n const applyChunkOps = (\n operations: readonly AssistantTransportStateOperation[],\n ) => {\n for (const operation of operations) {\n const op = translateStateOp(getAgent(), operation);\n if (op === undefined) continue;\n ctl.apply([{ ...op, path: [\"agent\", ...op.path] }]);\n }\n };\n\n const setQueue = (next: EntryQueue) => {\n s.queue = next;\n getOptions().queueCell.current = {\n queued: commandsOf(next.queued),\n inTransit: commandsOf(next.inTransit),\n };\n ctl.apply([\n { op: \"replace\", path: [\"queueVersion\"], value: ++s.queueVersion },\n ]);\n };\n\n const takeQueuedIntoTransit = (): QueueEntry[] => {\n const { queued, inTransit } = s.queue;\n if (queued.length === 0) return [];\n setQueue({ queued: [], inTransit: [...inTransit, ...queued] });\n return queued;\n };\n\n const drainQueue = (): EntryQueue => {\n const drained = s.queue;\n setQueue({ queued: [], inTransit: [] });\n return drained;\n };\n\n const buildRequestBody = async (\n o: HostOptions,\n commands: AssistantTransportCommand[],\n runParentId: string | null | undefined,\n ) => {\n const bodyValue = typeof o.body === \"function\" ? await o.body() : o.body;\n const { modelContext, threadId } = o.getRunContext();\n\n const requestBody: Record<string, unknown> = {\n commands,\n state: getAgent(),\n system: modelContext.system,\n tools: modelContext.tools\n ? toToolsJSONSchema(modelContext.tools)\n : undefined,\n threadId,\n ...(runParentId !== undefined && { parentId: runParentId }),\n callSettings: modelContext.callSettings,\n config: modelContext.config,\n // deprecated top-level spread, kept for legacy parity\n ...modelContext.callSettings,\n ...modelContext.config,\n ...(bodyValue ?? {}),\n };\n\n if (!o.prepareSendCommandsRequest) return requestBody;\n return o.prepareSendCommandsRequest(requestBody as SendCommandsRequestBody);\n };\n\n const run = async (signal: AbortSignal) => {\n const o = getOptions();\n const isResume = s.resumeRequested;\n s.resumeRequested = false;\n setReplaying(false);\n s.activeEntries = isResume ? [] : takeQueuedIntoTransit();\n if (s.activeEntries.length === 0 && !isResume && s.parentId === undefined)\n return;\n\n const runParentId = s.parentId;\n s.parentId = undefined;\n try {\n await runRequest(o, isResume, runParentId, signal);\n } catch (error) {\n if (!signal.aborted && s.parentId === undefined) s.parentId = runParentId;\n throw error;\n }\n };\n\n const runRequest = async (\n o: HostOptions,\n isResume: boolean,\n runParentId: string | null | undefined,\n signal: AbortSignal,\n ) => {\n const headers = await createRequestHeaders(o.headers);\n const requestBody = await buildRequestBody(\n o,\n commandsOf(s.activeEntries),\n runParentId,\n );\n\n const response = await fetch(isResume ? o.resumeApi! : o.api, {\n method: \"POST\",\n headers,\n body: JSON.stringify(requestBody),\n signal,\n });\n\n o.onResponse?.(response);\n\n if (!response.ok) {\n throw new Error(`Status ${response.status}: ${await response.text()}`);\n }\n if (!response.body) {\n throw new Error(\"Response body is null\");\n }\n\n const body = await createReplayBoundaryStream(response, setReplaying);\n const strict = !isResume;\n const decoder =\n (o.protocol ?? \"data-stream\") === \"assistant-transport\"\n ? new AssistantTransportDecoder({ strict })\n : new DataStreamDecoder({ strict });\n\n let streamError: string | undefined;\n let delivered = false;\n\n const markDelivered = () => {\n for (const entry of s.activeEntries) entry.execution.ack();\n setQueue({ ...s.queue, inTransit: [] });\n delivered = true;\n };\n\n const chunks = body.pipeThrough(decoder);\n for await (const chunk of asAsyncIterableStream(chunks)) {\n if (chunk.type === \"error\") {\n streamError = chunk.error;\n continue;\n }\n if (chunk.type !== \"update-state\" || chunk.operations.length === 0)\n continue;\n\n applyChunkOps(chunk.operations);\n\n // only after the chunk committed — a failing first chunk must leave\n // the commands in transit for onError (legacy parity)\n if (!delivered) markDelivered();\n }\n\n if (streamError) {\n throw new Error(streamError);\n }\n\n if (!delivered) markDelivered();\n\n // commands that coalesced into a resume run must not starve\n if (isResume && s.queue.queued.length > 0) s.followUpRequested = true;\n };\n\n const resolveActive = () => {\n for (const entry of s.activeEntries.splice(0)) entry.execution.resolve();\n };\n\n const settleCancelled = () => {\n setReplaying(false);\n const { queued, inTransit } = drainQueue();\n resolveActive();\n for (const entry of [...inTransit, ...queued]) entry.execution.resolve();\n getOptions().onCancel?.({\n commands: commandsOf([...inTransit, ...queued]),\n updateState,\n });\n };\n\n const settleFailed = async (error: Error) => {\n setReplaying(false);\n const { queued, inTransit } = drainQueue();\n for (const entry of inTransit) entry.execution.reject(error);\n resolveActive();\n try {\n await getOptions().onError?.(error, {\n commands: commandsOf(inTransit),\n updateState,\n });\n } finally {\n getOptions().onCancel?.({\n commands: commandsOf(queued),\n updateState,\n error,\n });\n for (const entry of queued) entry.execution.resolve();\n }\n };\n\n const startRun = () => {\n s.followUpRequested = false;\n const ac = new AbortController();\n s.abortController = ac;\n setSending(true);\n\n // macrotask: every command admitted this turn coalesces into the take\n setTimeout(async () => {\n try {\n await run(ac.signal);\n resolveActive();\n } catch (error) {\n s.followUpRequested = false;\n // disposed means unmounted mid-run: the abort is ours, no callbacks\n if (!s.disposed) {\n if (ac.signal.aborted) settleCancelled();\n else await settleFailed(error as Error);\n }\n } finally {\n if (s.disposed) {\n s.abortController = null;\n } else {\n getOptions().onFinish?.();\n if (s.followUpRequested) {\n startRun();\n } else {\n s.abortController = null;\n setSending(false);\n }\n }\n }\n }, 0);\n };\n\n const schedule = () => {\n if (s.abortController) {\n s.followUpRequested = true;\n return;\n }\n startRun();\n };\n\n return {\n send: function (\n this: StatewireHost.Ctx,\n command: AssistantTransportCommand,\n opts?: SendOptions,\n ) {\n let resolve!: () => void;\n let reject!: (error: unknown) => void;\n const promise = new Promise<void>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n setQueue({\n queued: [\n ...s.queue.queued,\n { command, execution: { ack: this.ack, resolve, reject } },\n ],\n inTransit: s.queue.inTransit,\n });\n if (opts?.schedule !== false) schedule();\n return promise;\n },\n setParentId: (id: string | null) => {\n s.parentId = id;\n },\n cancel: () => {\n s.resumeRequested = false;\n s.followUpRequested = false;\n s.abortController?.abort();\n },\n resume: () => {\n if (!getOptions().resumeApi)\n throw new Error(\"Must pass resumeApi to options to resume runs\");\n\n s.resumeRequested = true;\n schedule();\n },\n importState: replaceAgent,\n };\n};\n\nconst useAssistantTransportHost = (\n options: HostOptions,\n): Statewire<AssistantTransportHostState, AssistantTransportHostCommands> => {\n const latestOptions = useRef(options);\n latestOptions.current = options;\n\n const [state, ctl] = useStatewireState<AssistantTransportHostState>(() => ({\n agent: options.initialState,\n queueVersion: 0,\n isSending: false,\n isReplaying: false,\n }));\n const emit = useStatewireEmit();\n\n const handlers = useHostLoop(\n () => latestOptions.current,\n ctl,\n () => ctl.snapshot().agent,\n );\n\n const commands = useStatewireCommands(handlers);\n\n return { state, commands, emit };\n};\n\nexport const AssistantTransportHost = resource(useAssistantTransportHost);\n"],"mappings":";;;;;;;;;AAiF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AAIC;GACJ,MAAMkG,UAAU,IAAIC,SAAeC,KAAKC,QAAQ;IAC9CtG,UAAUqG;IACVpG,SAASqG;GACX,CAAC;GACD/D,SAAS;IACP/D,QAAQ,CACN,GAAG+C,EAAEZ,MAAMnC,QACX;KAAEc;KAASc,WAAW;MAAEL,KAAK,KAAKA;MAAKC;MAASC;KAAO;IAAE,CAAC;IAE5DxB,WAAW8C,EAAEZ,MAAMlC;GACrB,CAAC;GACD,IAAIc,MAAMpB,aAAa,OAAOA,SAAS;GACvC,OAAOgI;EACT;EACA3G,cAAc+G,OAAsB;GAClChF,EAAE9B,WAAW8G;EACf;EACA7G,cAAc;GACZ6B,EAAEV,kBAAkB;GACpBU,EAAET,oBAAoB;GACtBS,EAAEP,iBAAiBS,MAAM;EAC3B;EACA9B,cAAc;GACZ,IAAI,CAACwB,WAAW,CAAC,CAAC+C,WAChB,MAAM,IAAIO,MAAM,+CAA+C;GAEjElD,EAAEV,kBAAkB;GACpB1C,SAAS;EACX;EACAyB,aAAaoC;CACf;AACF;AAEA,MAAMwE,6BACJC,YAC2E;CAC3E,MAAMC,gBAAgB5J,OAAO2J,OAAO;CACpCC,cAAc/H,UAAU8H;CAExB,MAAM,CAAC5G,OAAOuB,OAAOzD,yBAAsD;EACzEqB,OAAOyH,QAAQE;EACf1H,cAAc;EACdC,WAAW;EACXC,aAAa;CACf,EAAE;CACF,MAAMyH,OAAOlJ,iBAAiB;CAE9B,MAAMmJ,WAAW3F,kBACTwF,cAAc/H,SACpByC,WACMA,IAAI0F,SAAS,CAAC,CAAC9H,KACvB;CAIA,OAAO;EAAEa;EAAOiD,UAFCrF,qBAAqBoJ,QAEtB/D;EAAU8D;CAAK;AACjC;AAEA,MAAaG,yBAAyB/J,SAASwJ,yBAAyB"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AddMessageCommand, AddToolResultCommand, AssistantMessage, AssistantTransportCommand, AssistantTransportConnectionMetadata, AssistantTransportOptions, AssistantTransportProtocol, AssistantTransportState, AssistantTransportStateConverter,
|
|
1
|
+
import { 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, UserMessage, UserMessagePart } from "./types.js";
|
|
2
2
|
import { AssistantTransportThread } from "./AssistantTransportThread.js";
|
|
3
3
|
import { StatewireThread } from "./StatewireThread.js";
|
|
4
4
|
import { useAssistantTransportSendCommand, useAssistantTransportState } from "./hooks.js";
|
|
@@ -12,15 +12,31 @@ declare namespace AssistantTransportThread {
|
|
|
12
12
|
type StateConverter<T> = AssistantTransportStateConverter<T>;
|
|
13
13
|
type AddMessageCommand = AddMessageCommand;
|
|
14
14
|
type AddToolResultCommand = AddToolResultCommand;
|
|
15
|
-
type
|
|
16
|
-
type
|
|
17
|
-
type
|
|
18
|
-
type
|
|
15
|
+
type RunCommand = RunCommand;
|
|
16
|
+
type RunEnqueueCommand = RunEnqueueCommand;
|
|
17
|
+
type RunSteerCommand = RunSteerCommand;
|
|
18
|
+
type RunDequeueCommand = RunDequeueCommand;
|
|
19
|
+
type RunEditCommand = RunEditCommand;
|
|
20
|
+
type RunContinueCommand = RunContinueCommand;
|
|
21
|
+
type RunReloadCommand = RunReloadCommand;
|
|
22
|
+
type RunInputCommand = RunInputCommand;
|
|
23
|
+
type InputRequest = InputRequest;
|
|
24
|
+
type ToolCallInputRequest = ToolCallInputRequest;
|
|
25
|
+
type ToolApprovalInputRequest = ToolApprovalInputRequest;
|
|
26
|
+
type CustomInputRequest = CustomInputRequest;
|
|
27
|
+
type InputRequestState = InputRequestState;
|
|
28
|
+
type InputResponse = InputResponse;
|
|
29
|
+
type ToolCallInputResponse = ToolCallInputResponse;
|
|
30
|
+
type ToolApprovalInputResponse = ToolApprovalInputResponse;
|
|
31
|
+
type RunUserMessage = RunUserMessage;
|
|
32
|
+
type RunQueueItem = RunQueueItem;
|
|
33
|
+
type RunPlacement = RunPlacement;
|
|
19
34
|
type SendCommandsRequestBody = SendCommandsRequestBody;
|
|
20
35
|
type UserMessage = UserMessage;
|
|
21
36
|
type AssistantMessage = AssistantMessage;
|
|
22
37
|
type UserMessagePart = UserMessagePart;
|
|
23
38
|
type TextPart = TextPart;
|
|
39
|
+
type FilePart = FilePart;
|
|
24
40
|
type ImagePart = ImagePart;
|
|
25
41
|
type HeadersValue = HeadersValue;
|
|
26
42
|
}
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;kBAUiB;OACH,QAAQ,KAAK,0BAAgC;OAC7C,UAAU;OACV,WAAW;OACX,QAAQ;OACR,qBAAqB;OACrB,eAAe,KAAK,iCAAuC;OAC3D,oBAAoB;OACpB,uBAAuB;OACvB,
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;kBAUiB;OACH,QAAQ,KAAK,0BAAgC;OAC7C,UAAU;OACV,WAAW;OACX,QAAQ;OACR,qBAAqB;OACrB,eAAe,KAAK,iCAAuC;OAC3D,oBAAoB;OACpB,uBAAuB;OACvB,aAAa;OACb,oBAAoB;OACpB,kBAAkB;OAClB,oBAAoB;OACpB,iBAAiB;OACjB,qBAAqB;OACrB,mBAAmB;OACnB,kBAAkB;OAClB,eAAe;OACf,uBAAuB;OACvB,2BAA2B;OAC3B,qBAAqB;OACrB,oBAAoB;OACpB,gBAAgB;OAChB,wBAAwB;OACxB,4BAA4B;OAC5B,iBAAiB;OACjB,eAAe;OACf,eAAe;OACf,0BAA0B;OAC1B,cAAc;OACd,mBAAmB;OACnB,kBAAkB;OAClB,WAAW;OACX,WAAW;OACX,YAAY;OACZ,eAAe"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { InputRequestState, RunInputCommand } from "./types.js";
|
|
2
|
+
import { RespondToToolApprovalOptions } from "@assistant-ui/core";
|
|
3
|
+
import { ReadonlyJSONValue } from "assistant-stream/utils";
|
|
4
|
+
//#region src/inputRequests.d.ts
|
|
5
|
+
declare const resolveToolResultInput: (inputRequests: readonly InputRequestState[], options: {
|
|
6
|
+
toolCallId: string;
|
|
7
|
+
result: ReadonlyJSONValue;
|
|
8
|
+
isError: boolean;
|
|
9
|
+
artifact?: ReadonlyJSONValue | undefined;
|
|
10
|
+
}) => RunInputCommand | undefined;
|
|
11
|
+
declare const resolveToolApprovalInput: (inputRequests: readonly InputRequestState[], options: RespondToToolApprovalOptions) => RunInputCommand;
|
|
12
|
+
//#endregion
|
|
13
|
+
export { resolveToolApprovalInput, resolveToolResultInput };
|
|
14
|
+
//# sourceMappingURL=inputRequests.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"inputRequests.d.ts","names":[],"sources":["../src/inputRequests.ts"],"mappings":";;;;cAWa,yBACX,wBAAwB,qBACxB;EACE;EACA,QAAQ;EACR;EACA,WAAW;MAEZ;cAiBU,2BACX,wBAAwB,qBACxB,SAAS,iCACR"}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
//#region src/inputRequests.ts
|
|
2
|
+
const assertUnanswered = (request) => {
|
|
3
|
+
if (request.response !== null) throw new Error(`statewire: input request "${request.id}" is already answered`);
|
|
4
|
+
};
|
|
5
|
+
const resolveToolResultInput = (inputRequests, options) => {
|
|
6
|
+
const request = inputRequests.find((r) => r.type === "tool-call" && r.toolCallId === options.toolCallId);
|
|
7
|
+
if (request === void 0) return void 0;
|
|
8
|
+
assertUnanswered(request);
|
|
9
|
+
return {
|
|
10
|
+
type: "run/input",
|
|
11
|
+
requestId: request.id,
|
|
12
|
+
response: {
|
|
13
|
+
output: options.result,
|
|
14
|
+
...options.isError && { isError: true },
|
|
15
|
+
...options.artifact !== void 0 && { artifact: options.artifact }
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
};
|
|
19
|
+
const resolveToolApprovalInput = (inputRequests, options) => {
|
|
20
|
+
const request = inputRequests.find((r) => r.type === "tool-approval" && r.id === options.approvalId);
|
|
21
|
+
if (request === void 0) throw new Error(`statewire: no tool-approval input request "${options.approvalId}"`);
|
|
22
|
+
assertUnanswered(request);
|
|
23
|
+
return {
|
|
24
|
+
type: "run/input",
|
|
25
|
+
requestId: request.id,
|
|
26
|
+
response: {
|
|
27
|
+
decision: options.approved ? "approve" : "reject",
|
|
28
|
+
...options.reason !== void 0 && { message: options.reason }
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
};
|
|
32
|
+
//#endregion
|
|
33
|
+
export { resolveToolApprovalInput, resolveToolResultInput };
|
|
34
|
+
|
|
35
|
+
//# sourceMappingURL=inputRequests.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"inputRequests.js","names":["RespondToToolApprovalOptions","ReadonlyJSONValue","InputRequestState","RunInputCommand","assertUnanswered","request","response","Error","id","resolveToolResultInput","inputRequests","options","toolCallId","result","isError","artifact","find","r","type","undefined","requestId","output","resolveToolApprovalInput","approvalId","decision","approved","reason","message"],"sources":["../src/inputRequests.ts"],"sourcesContent":["import type { RespondToToolApprovalOptions } from \"@assistant-ui/core\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport type { InputRequestState, RunInputCommand } from \"./types\";\n\nconst assertUnanswered = (request: InputRequestState) => {\n if (request.response !== null)\n throw new Error(\n `statewire: input request \"${request.id}\" is already answered`,\n );\n};\n\nexport const resolveToolResultInput = (\n inputRequests: readonly InputRequestState[],\n options: {\n toolCallId: string;\n result: ReadonlyJSONValue;\n isError: boolean;\n artifact?: ReadonlyJSONValue | undefined;\n },\n): RunInputCommand | undefined => {\n const request = inputRequests.find(\n (r) => r.type === \"tool-call\" && r.toolCallId === options.toolCallId,\n );\n if (request === undefined) return undefined;\n assertUnanswered(request);\n return {\n type: \"run/input\",\n requestId: request.id,\n response: {\n output: options.result,\n ...(options.isError && { isError: true }),\n ...(options.artifact !== undefined && { artifact: options.artifact }),\n },\n };\n};\n\nexport const resolveToolApprovalInput = (\n inputRequests: readonly InputRequestState[],\n options: RespondToToolApprovalOptions,\n): RunInputCommand => {\n const request = inputRequests.find(\n (r) => r.type === \"tool-approval\" && r.id === options.approvalId,\n );\n if (request === undefined)\n throw new Error(\n `statewire: no tool-approval input request \"${options.approvalId}\"`,\n );\n assertUnanswered(request);\n return {\n type: \"run/input\",\n requestId: request.id,\n response: {\n decision: options.approved ? \"approve\" : \"reject\",\n ...(options.reason !== undefined && { message: options.reason }),\n },\n };\n};\n"],"mappings":";AAIA,MAAMI,oBAAoBC,YAA+B;CACvD,IAAIA,QAAQC,aAAa,MACvB,MAAM,IAAIC,MACR,6BAA6BF,QAAQG,GAAE,sBACzC;AACJ;AAEA,MAAaC,0BACXC,eACAC,YAMgC;CAChC,MAAMN,UAAUK,cAAcM,MAC3BC,MAAMA,EAAEC,SAAS,eAAeD,EAAEL,eAAeD,QAAQC,UAC5D;CACA,IAAIP,YAAYc,KAAAA,GAAW,OAAOA,KAAAA;CAClCf,iBAAiBC,OAAO;CACxB,OAAO;EACLa,MAAM;EACNE,WAAWf,QAAQG;EACnBF,UAAU;GACRe,QAAQV,QAAQE;GAChB,GAAIF,QAAQG,WAAW,EAAEA,SAAS,KAAK;GACvC,GAAIH,QAAQI,aAAaI,KAAAA,KAAa,EAAEJ,UAAUJ,QAAQI,SAAS;EACrE;CACF;AACF;AAEA,MAAaO,4BACXZ,eACAC,YACoB;CACpB,MAAMN,UAAUK,cAAcM,MAC3BC,MAAMA,EAAEC,SAAS,mBAAmBD,EAAET,OAAOG,QAAQY,UACxD;CACA,IAAIlB,YAAYc,KAAAA,GACd,MAAM,IAAIZ,MACR,8CAA8CI,QAAQY,WAAU,EAClE;CACFnB,iBAAiBC,OAAO;CACxB,OAAO;EACLa,MAAM;EACNE,WAAWf,QAAQG;EACnBF,UAAU;GACRkB,UAAUb,QAAQc,WAAW,YAAY;GACzC,GAAId,QAAQe,WAAWP,KAAAA,KAAa,EAAEQ,SAAShB,QAAQe,OAAO;EAChE;CACF;AACF"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { RunCommand, RunQueueItem, RunReloadCommand, RunUserMessage, TextPart } from "./types.js";
|
|
2
|
+
import { AppendMessage, ExternalThreadQueueAdapter } from "@assistant-ui/core";
|
|
3
|
+
//#region src/runCommands.d.ts
|
|
4
|
+
declare const toWireMessage: (message: AppendMessage, id: string) => RunUserMessage;
|
|
5
|
+
declare const toQueueItemState: (item: RunQueueItem) => {
|
|
6
|
+
id: string;
|
|
7
|
+
prompt: string;
|
|
8
|
+
parts: (TextPart | {
|
|
9
|
+
filename?: string;
|
|
10
|
+
type: "file";
|
|
11
|
+
data: string;
|
|
12
|
+
mimeType: string;
|
|
13
|
+
})[];
|
|
14
|
+
};
|
|
15
|
+
declare const createRunQueueAdapter: (queueItems: readonly RunQueueItem[], steerQueueItems: readonly RunQueueItem[] | undefined, dispatch: (command: RunCommand) => void) => ExternalThreadQueueAdapter;
|
|
16
|
+
declare const resolveReloadCommand: (messages: readonly {
|
|
17
|
+
id: string;
|
|
18
|
+
role: string;
|
|
19
|
+
}[], parentId: string | null) => RunReloadCommand;
|
|
20
|
+
//#endregion
|
|
21
|
+
export { createRunQueueAdapter, resolveReloadCommand, toQueueItemState, toWireMessage };
|
|
22
|
+
//# sourceMappingURL=runCommands.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runCommands.d.ts","names":[],"sources":["../src/runCommands.ts"],"mappings":";;;cAca,gBACX,SAAS,eACT,eACC;cAqCU,mBAAoB,MAAM;;;UAAA;;;;;;;cA0B1B,wBACX,qBAAqB,gBACrB,0BAA0B,4BAC1B,WAAW,SAAS,wBACnB;cA6CU,uBACX;EAAqB;EAAY;KACjC,4BACC"}
|