@assistant-ui/react-statewire 0.4.1 → 0.4.3
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/StatewireThread.d.ts +4 -2
- package/dist/StatewireThread.d.ts.map +1 -1
- package/dist/StatewireThread.js +2 -1
- package/dist/StatewireThread.js.map +1 -1
- package/dist/runCommands.js +1 -2
- package/dist/runCommands.js.map +1 -1
- package/dist/types.d.ts +0 -2
- package/dist/types.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/StatewireThread.test.tsx +38 -2
- package/src/StatewireThread.ts +11 -3
- package/src/runCommands.ts +1 -5
- package/src/transport.test.tsx +0 -2
- package/src/types.ts +0 -2
|
@@ -100,8 +100,6 @@ declare namespace StatewireThread {
|
|
|
100
100
|
type RunReloadCommand = {
|
|
101
101
|
readonly type: "run/reload";
|
|
102
102
|
readonly sourceId: string;
|
|
103
|
-
/** Client-generated id of the regenerated assistant message. */
|
|
104
|
-
readonly messageId: string;
|
|
105
103
|
};
|
|
106
104
|
type RunCommand = RunEnqueueCommand | RunSteerCommand | RunDequeueCommand | RunEditCommand | RunContinueCommand | RunReloadCommand | RunInputCommand;
|
|
107
105
|
type Command = AssistantTransportCommand | RunCommand;
|
|
@@ -165,6 +163,10 @@ declare namespace StatewireThread {
|
|
|
165
163
|
* runs for commands it declined.
|
|
166
164
|
*/
|
|
167
165
|
onCommandSessionLost?: ((command: StatewireClient.SessionLostCommand) => "replay" | void) | undefined;
|
|
166
|
+
/** Observes each command's lifecycle (queued, posted, acked, settled); runs after the built-in pending-command retirement. */
|
|
167
|
+
onCommandChange?: ((update: Statewire.CommandUpdate<Record<string, (...args: any[]) => unknown>>, ctx: {
|
|
168
|
+
state: NonNullable<T>;
|
|
169
|
+
}) => void) | undefined;
|
|
168
170
|
onError?: ((error: Error) => void) | undefined;
|
|
169
171
|
capabilities?: {
|
|
170
172
|
edit?: boolean | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;;cA6Ra,kBAAmB,GAC9B,SAAS,gBAAgB,QAAQ,OAChC,gBAAgB;kBAGF;OACH,UAAU,KAAK,gBAAgB,UAAU;OAEzC;aACD;aACA;;OAGC;aACD;aACA;aACA;aACA;;OAGC;aACD;aACA;aACA,iBAAiB,WAAW;aAC5B,WAAW;;;OAIV;aACD;aACA;;OAGC;aACD;;aAGI,SAAS;;aAET;;aAEA;OAEb;OAEU;aACD;;aAGI,SAAS;;aAET;;aAEA;OAEb;OAEU;aACD;aACA;;OAGC;aACD;aACA,SAAS;aACT;;OAGC;aACD;;OAGC;aACD;aACA;aACA;;OAGC;aACD;aACA;aACA;;OAGC;aACD;aACA;cACC,cAAc;;;OAId,eACR,uBACA,2BACA;OAEQ;aACD,QAAQ;;aAER;aACA,WAAW;;OAGV;aACD;aACA,aAAa;aACb;;OAGC,gBAAgB;OAEhB;aACD;aACA;aACA,UAAU;;;OAIT,oBAAoB;aACrB,UAAU;;OAGT;aACD;aACA;;OAGC,aACR,oBACA,kBACA,oBACA,iBACA,qBACA,mBACA;OAEQ,UAAU,4BAA4B;;OAGtC;aACD;aACA,iBAAiB,WAAW;;OAG3B;aACD,mBAAmB;aACnB,QAAQ;aACR;;;;;;;aAOA,iBAAiB;;aAEjB,sBAAsB;;;;;;;aAOtB,yBAAyB;;OAGxB;IACV,iBAAiB;IACjB;;IAEA,YAAY,gBAAgB;;OAGlB,eAAe,MACzB,OAAO,GACP,oBAAoB,uBACjB;;;;;OAMO;aACD;cACC,cAAc;;OAGd,QAAQ;IAClB,WAAW,UAAU;IACrB,cAAc;IACd,WAAW,eAAe;;;;;;IAM1B;;IAEA,qBAAqB;;;;;;;IAOrB,yBACM,SAAS,gBAAgB;;IAG/B,oBAEM,QAAQ,UAAU,cAChB,mBAAmB,2BAErB;MAAO,OAAO,YAAY;;IAGhC,YAAY,OAAO;IACnB;MAEM;;MAEA;;MAEA;;IAGN;MAEM,cAAc"}
|
package/dist/StatewireThread.js
CHANGED
|
@@ -33,8 +33,9 @@ const useStatewireThread = (options) => {
|
|
|
33
33
|
const [retire] = useState(() => (command) => setPending((prev) => prev.includes(command) ? prev.filter((c) => c !== command) : prev));
|
|
34
34
|
const { state: transportState, commands, connection, setContext } = useStatewire({
|
|
35
35
|
transport: options.onCommandSessionLost === void 0 ? options.transport : withSessionLostFallback(options.transport, latest),
|
|
36
|
-
onCommandChange: (update) => {
|
|
36
|
+
onCommandChange: (update, ctx) => {
|
|
37
37
|
if (update.status === "acked" || update.status === "settled") retire(update.params[0]);
|
|
38
|
+
latest.current.onCommandChange?.(update, ctx);
|
|
38
39
|
}
|
|
39
40
|
});
|
|
40
41
|
const attached = transportState !== void 0;
|
|
@@ -1 +1 @@
|
|
|
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","viewedLeafId","resolveToolApprovalInput","resolveToolResultInput","AssistantTransportCommand","AnyCommands","Record","args","ambientContextOf","context","system","undefined","tools","callSettings","config","withSessionLostFallback","transport","StatewireThread","Transport","latest","current","Options","transportOptions","rest","length","Error","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","type","converter","metadata","ConnectionMetadata","pendingCommands","isSending","converted","queueItems","queue","steerQueueItems","steerQueue","queueSeam","present","messages","inputRequests","inputSeam","extras","sendCommand","reconnect","handleAppend","message","crypto","randomUUID","anchorMessageId","handleReload","parentId","handleEdit","sourceId","isRunning","isLoading","attachmentAdapter","adapters","attachments","onNew","capabilities","edit","onEdit","continue","onResume","reload","onReload","onAddToolResult","toolOptions","onRespondToToolApproval","approval","onCancel","payload","stopPayload","Array","isArray","T","TextPart","text","FilePart","mediaType","url","filename","UserMessage","id","role","parts","Placement","insertAfter","insertBefore","RunEnqueueCommand","messageId","RunSteerCommand","RunDequeueCommand","RunEditCommand","RunContinueCommand","ToolCallInputRequest","toolCallId","ToolApprovalInputRequest","CustomInputRequest","InputRequest","ToolCallInputResponse","output","isError","artifact","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 viewedLeafId,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\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 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(\n converted.messages,\n queueItems,\n steerQueueItems,\n dispatch,\n )\n : undefined,\n [converted.messages, 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 dispatch({\n type: \"run/steer\",\n message: toWireMessage(message, crypto.randomUUID()),\n anchorMessageId: viewedLeafId(converted.messages),\n });\n };\n\n const handleReload = (parentId: string | null) => {\n dispatch(resolveReloadCommand(converted.messages, parentId));\n };\n\n const handleEdit = (message: AppendMessage) => {\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 dispatch(resolveToolResultInput(inputRequests, toolOptions)),\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 } & (\n | {\n readonly message: UserMessage;\n /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */\n readonly anchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunSteerCommand = {\n readonly type: \"run/steer\";\n } & (\n | {\n readonly message: UserMessage;\n /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */\n readonly anchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\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 /** Client-generated id of the regenerated assistant message. */\n readonly messageId: 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.\nfor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C,YAAiB;IACxB9C,OAAOC,QAAQ8C,UAAUD,OAAK;GAChC,CAAC;EACH;CACF,CAAC,CACH;AACF;AAEA,MAAahD,mBACXc,YAEAvD,SAASsD,kBAAkB,CAAC,CAACC,OAAuC;AAkOtElD,uBACEiD,oBACAnD,eAAegC,KAAAA,CAAkB,CAAC,CAAC0J,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","viewedLeafId","resolveToolApprovalInput","resolveToolResultInput","AssistantTransportCommand","AnyCommands","Record","args","ambientContextOf","context","system","undefined","tools","callSettings","config","withSessionLostFallback","transport","StatewireThread","Transport","latest","current","Options","transportOptions","rest","length","Error","transportLevel","onCommandSessionLost","command","SessionLostCommand","useStatewireThread","options","pending","setPending","Command","retire","prev","includes","filter","c","state","transportState","commands","connection","setContext","onCommandChange","update","ctx","status","params","attached","initialState","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","catch","error","onError","subscribe","dispatch","type","converter","metadata","ConnectionMetadata","pendingCommands","isSending","converted","queueItems","queue","steerQueueItems","steerQueue","queueSeam","present","messages","inputRequests","inputSeam","extras","sendCommand","reconnect","handleAppend","message","crypto","randomUUID","anchorMessageId","handleReload","parentId","handleEdit","sourceId","isRunning","isLoading","attachmentAdapter","adapters","attachments","onNew","capabilities","edit","onEdit","continue","onResume","reload","onReload","onAddToolResult","toolOptions","onRespondToToolApproval","approval","onCancel","payload","stopPayload","Array","isArray","T","TextPart","text","FilePart","mediaType","url","filename","UserMessage","id","role","parts","Placement","insertAfter","insertBefore","RunEnqueueCommand","messageId","RunSteerCommand","RunDequeueCommand","RunEditCommand","RunContinueCommand","ToolCallInputRequest","toolCallId","ToolApprovalInputRequest","CustomInputRequest","InputRequest","ToolCallInputResponse","output","isError","artifact","ToolApprovalInputResponse","decision","editedArgs","InputResponse","RunInputCommand","requestId","response","InputRequestState","RunReloadCommand","RunCommand","QueueItem","State","ConnectionState","StateConverter","connectionMetadata","StopPayload","reason","CommandUpdate","NonNullable","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 viewedLeafId,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\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 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, ctx) => {\n if (update.status === \"acked\" || update.status === \"settled\")\n retire(update.params[0]);\n latest.current.onCommandChange?.(update, ctx);\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(\n converted.messages,\n queueItems,\n steerQueueItems,\n dispatch,\n )\n : undefined,\n [converted.messages, 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 dispatch({\n type: \"run/steer\",\n message: toWireMessage(message, crypto.randomUUID()),\n anchorMessageId: viewedLeafId(converted.messages),\n });\n };\n\n const handleReload = (parentId: string | null) => {\n dispatch(resolveReloadCommand(converted.messages, parentId));\n };\n\n const handleEdit = (message: AppendMessage) => {\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 dispatch(resolveToolResultInput(inputRequests, toolOptions)),\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 } & (\n | {\n readonly message: UserMessage;\n /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */\n readonly anchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunSteerCommand = {\n readonly type: \"run/steer\";\n } & (\n | {\n readonly message: UserMessage;\n /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */\n readonly anchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\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 /** Observes each command's lifecycle (queued, posted, acked, settled); runs after the built-in pending-command retirement. */\n onCommandChange?:\n | ((\n update: Statewire.CommandUpdate<\n Record<string, (...args: any[]) => unknown>\n >,\n ctx: { state: NonNullable<T> },\n ) => 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":";;;;;;;;;;AAuCA,MAAMqC,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWC,KAAAA,KAAa,EAAED,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQG,U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,CAACC,OAAuC;AAyOtElD,uBACEiD,oBACAnD,eAAegC,KAAAA,CAAkB,CAAC,CAAC6J,IACrC"}
|
package/dist/runCommands.js
CHANGED
|
@@ -99,8 +99,7 @@ const resolveReloadCommand = (messages, parentId) => {
|
|
|
99
99
|
if (target === void 0 || target.role !== "assistant") throw new Error("statewire: run/reload requires an assistant message to regenerate");
|
|
100
100
|
return {
|
|
101
101
|
type: "run/reload",
|
|
102
|
-
sourceId: target.id
|
|
103
|
-
messageId: crypto.randomUUID()
|
|
102
|
+
sourceId: target.id
|
|
104
103
|
};
|
|
105
104
|
};
|
|
106
105
|
//#endregion
|
package/dist/runCommands.js.map
CHANGED
|
@@ -1 +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","viewedLeafId","messages","at","createRunQueueAdapter","queueItems","steerQueueItems","dispatch","command","laneOf","queueItemId","some","items","steerItems","enqueue","crypto","randomUUID","anchorMessageId","steer","move","lane","fields","messageId","edit","wireMessage","remove","resolveReloadCommand","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 viewedLeafId = (\n messages: readonly { id: string }[],\n): string | null => messages.at(-1)?.id ?? null;\n\nexport const createRunQueueAdapter = (\n messages: readonly { id: string }[],\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 anchorMessageId: viewedLeafId(messages),\n }),\n steer: (message) =>\n dispatch({\n type: \"run/steer\",\n message: toWireMessage(message, crypto.randomUUID()),\n anchorMessageId: viewedLeafId(messages),\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 {
|
|
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","viewedLeafId","messages","at","createRunQueueAdapter","queueItems","steerQueueItems","dispatch","command","laneOf","queueItemId","some","items","steerItems","enqueue","crypto","randomUUID","anchorMessageId","steer","move","lane","fields","messageId","edit","wireMessage","remove","resolveReloadCommand","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 viewedLeafId = (\n messages: readonly { id: string }[],\n): string | null => messages.at(-1)?.id ?? null;\n\nexport const createRunQueueAdapter = (\n messages: readonly { id: string }[],\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 anchorMessageId: viewedLeafId(messages),\n }),\n steer: (message) =>\n dispatch({\n type: \"run/steer\",\n message: toWireMessage(message, crypto.randomUUID()),\n anchorMessageId: viewedLeafId(messages),\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":";AAcA,MAAaS,iBACXC,SACAC,OACmB;CACnB,IAAID,QAAQE,SAAS,QACnB,MAAM,IAAIC,MAAM,6CAA6C;CAC/D,MAAMC,QAAoB,CAAA;CAC1B,MAAMC,QAAkB,CAAA;CACxB,MAAMC,SAAS,CACb,GAAGN,QAAQO,SACX,GAAIP,QAAQQ,aAAaC,SAASC,MAAMA,EAAEH,OAAO,KAAK,CAAA,CAAG;CAE3D,KAAK,MAAMI,QAAQL,QACjB,IAAIK,KAAKC,SAAS,QAChBP,MAAMQ,KAAKF,KAAKG,IAAI;MACf,IAAIH,KAAKC,SAAS,SACvBR,MAAMS,KAAK;EAAED,MAAM;EAAQG,WAAW;EAAWC,KAAKL,KAAKM;CAAM,CAAC;MAC7D,IAAIN,KAAKC,SAAS,QACvBR,MAAMS,KAAK;EACTD,MAAM;EACNG,WAAWJ,KAAKO;EAChBF,KAAKL,KAAKQ;EACV,GAAIR,KAAKS,aAAaC,KAAAA,KAAa,EAAED,UAAUT,KAAKS,SAAS;CAC/D,CAAC;MAED,MAAM,IAAIjB,MAAM,wCAAwCQ,KAAKC,KAAI,EAAG;CAIxE,MAAMU,QAAiC,CACrC,GAAGlB,OACH,GAAIC,MAAMkB,SAAS,IACf,CAAC;EAAEX,MAAM;EAAiBE,MAAMT,MAAMoB,KAAK,MAAM;CAAE,CAAC,IACpD,CAAA,CAAG;CAET,IAAIH,MAAMC,WAAW,GACnB,MAAM,IAAIpB,MAAM,yCAAyC;CAC3D,OAAO;EAAEF;EAAIC,MAAM;EAAQoB;CAAM;AACnC;AAEA,MAAaI,oBAAoBC,UAAwB;CACvD1B,IAAI0B,KAAK1B;CACT2B,QAAQD,KAAKL,MACVb,SAASE,SAAUA,KAAKC,SAAS,SAAS,CAACD,KAAKG,IAAI,IAAI,CAAA,CAAG,CAAC,CAC5DW,KAAK,MAAM;CACdH,OAAOK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C9B;GACAS,SACEa,SAAS,UACL;IAAEzC,MAAM;IAAa,GAAG0C;GAAO,IAC/B;IAAE1C,MAAM;IAAe,GAAG0C;GAAO,CACvC;EACF;EACAE,OAAOb,aAAa3C,YAAY;GAC9B,MAAMyD,cAAc1D,cAAcC,SAAS2C,WAAW;GACtDH,SACEE,OAAOC,WAAW,MAAM,UACpB;IAAE/B,MAAM;IAAaZ,SAASyD;GAAY,IAC1C;IAAE7C,MAAM;IAAeZ,SAASyD;GAAY,CAClD;EACF;EACAC,SAASf,gBACPH,SAAS;GAAE5B,MAAM;GAAe2C,WAAWZ;EAAY,CAAC;CAC5D;AACF;AAEA,MAAagB,wBACXxB,UACAyB,aACqB;CACrB,MAAMC,QACJD,aAAa,OACT,IACAzB,SAAS2B,WAAW9D,YAAYA,QAAQC,OAAO2D,QAAQ,IAAI;CACjE,IAAIA,aAAa,QAAQC,UAAU,GACjC,MAAM,IAAI1D,MAAM,iCAAiCyD,SAAQ,aAAc;CACzE,MAAMG,SAAS5B,SAAS0B;CACxB,IAAIE,WAAW1C,KAAAA,KAAa0C,OAAO7D,SAAS,aAC1C,MAAM,IAAIC,MACR,mEACF;CACF,OAAO;EAAES,MAAM;EAAcoD,UAAUD,OAAO9D;CAAG;AACnD"}
|
package/dist/types.d.ts
CHANGED
|
@@ -96,8 +96,6 @@ type InputRequestState = InputRequest & {
|
|
|
96
96
|
type RunReloadCommand = {
|
|
97
97
|
readonly type: "run/reload";
|
|
98
98
|
readonly sourceId: string;
|
|
99
|
-
/** Client-generated id of the regenerated assistant message. */
|
|
100
|
-
readonly messageId: string;
|
|
101
99
|
};
|
|
102
100
|
type RunCommand = RunEnqueueCommand | RunSteerCommand | RunDequeueCommand | RunEditCommand | RunContinueCommand | RunReloadCommand | RunInputCommand;
|
|
103
101
|
type AssistantTransportCommand = RunCommand | UserCommands;
|
package/dist/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","names":[],"sources":["../src/types.ts"],"mappings":";;;;KAUY,eAAe,UAAU,eAAe,UAAU;KAClD,0BAA0B,UAAU,8BAC5C,0BACA,UAAU,oBAAoB,UAAU;KAEhC;WACD;WACA;;KAGC;WACD;WACA;WACA;WACA;;KAGC;WACD;WACA;WACA,iBAAiB,WAAW;WAC5B,WAAW;;;KAIV;WACD;WACA;;KAGC;WACD;;WAGI,SAAS;;WAET;;WAEA;KAEb;KAEU;WACD;;WAGI,SAAS;;WAET;;WAEA;KAEb;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;;
|
|
1
|
+
{"version":3,"file":"types.d.ts","names":[],"sources":["../src/types.ts"],"mappings":";;;;KAUY,eAAe,UAAU,eAAe,UAAU;KAClD,0BAA0B,UAAU,8BAC5C,0BACA,UAAU,oBAAoB,UAAU;KAEhC;WACD;WACA;;KAGC;WACD;WACA;WACA;WACA;;KAGC;WACD;WACA;WACA,iBAAiB,WAAW;WAC5B,WAAW;;;KAIV;WACD;WACA;;KAGC;WACD;;WAGI,SAAS;;WAET;;WAEA;KAEb;KAEU;WACD;;WAGI,SAAS;;WAET;;WAEA;KAEb;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,4BAA4B,aAAa;;KAGzC;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
|
@@ -15,6 +15,7 @@ import {
|
|
|
15
15
|
useStatewireState,
|
|
16
16
|
} from "statewire/host";
|
|
17
17
|
import { createMockTransport } from "statewire/testing";
|
|
18
|
+
import type { Statewire } from "statewire";
|
|
18
19
|
import { StatewireThread } from "./StatewireThread";
|
|
19
20
|
import { asAssistantTransportExtras } from "./AssistantTransportThread";
|
|
20
21
|
import { useAssistantTransportState } from "./hooks";
|
|
@@ -401,6 +402,43 @@ describe("StatewireThread", () => {
|
|
|
401
402
|
await waitFor(() => expect(metas.at(-1)!.pendingCommands).toEqual([]));
|
|
402
403
|
});
|
|
403
404
|
|
|
405
|
+
it("reports the command lifecycle through onCommandChange after retiring the pending command", async () => {
|
|
406
|
+
const server = createServer();
|
|
407
|
+
const updates: Statewire.CommandUpdate<
|
|
408
|
+
Record<string, (...args: any[]) => unknown>
|
|
409
|
+
>[] = [];
|
|
410
|
+
const states: ServerState[] = [];
|
|
411
|
+
const metas: StatewireThread.ConnectionMetadata[] = [];
|
|
412
|
+
const { aui } = mountThread({
|
|
413
|
+
transport: server.transport,
|
|
414
|
+
converter: (state, meta) => {
|
|
415
|
+
metas.push(meta);
|
|
416
|
+
return converter(state, meta);
|
|
417
|
+
},
|
|
418
|
+
onCommandChange: (update, ctx) => {
|
|
419
|
+
updates.push(update);
|
|
420
|
+
states.push(ctx.state);
|
|
421
|
+
},
|
|
422
|
+
});
|
|
423
|
+
|
|
424
|
+
aui().thread().append("hello");
|
|
425
|
+
|
|
426
|
+
await waitFor(() =>
|
|
427
|
+
expect(updates.map((u) => u.status)).toEqual([
|
|
428
|
+
"queued",
|
|
429
|
+
"posted",
|
|
430
|
+
"acked",
|
|
431
|
+
"settled",
|
|
432
|
+
]),
|
|
433
|
+
);
|
|
434
|
+
expect(updates.at(-1)).toMatchObject({
|
|
435
|
+
method: "run/steer",
|
|
436
|
+
params: [{ type: "run/steer" }],
|
|
437
|
+
});
|
|
438
|
+
expect(states.at(-1)!.messages.map((m) => m.text)).toEqual(["hello"]);
|
|
439
|
+
await waitFor(() => expect(metas.at(-1)!.pendingCommands).toEqual([]));
|
|
440
|
+
});
|
|
441
|
+
|
|
404
442
|
describe("contextSync: command-send", () => {
|
|
405
443
|
const contextValueOf = (command: { context?: unknown }) => {
|
|
406
444
|
const ops = command.context as [
|
|
@@ -993,7 +1031,6 @@ describe("StatewireThread", () => {
|
|
|
993
1031
|
expect(server.received).toContainEqual({
|
|
994
1032
|
type: "run/reload",
|
|
995
1033
|
sourceId: "a1",
|
|
996
|
-
messageId: expect.stringMatching(/^[0-9a-f-]{36}$/),
|
|
997
1034
|
}),
|
|
998
1035
|
);
|
|
999
1036
|
});
|
|
@@ -1016,7 +1053,6 @@ describe("StatewireThread", () => {
|
|
|
1016
1053
|
expect(server.received).toContainEqual({
|
|
1017
1054
|
type: "run/reload",
|
|
1018
1055
|
sourceId: "a0",
|
|
1019
|
-
messageId: expect.stringMatching(/^[0-9a-f-]{36}$/),
|
|
1020
1056
|
}),
|
|
1021
1057
|
);
|
|
1022
1058
|
});
|
package/src/StatewireThread.ts
CHANGED
|
@@ -111,9 +111,10 @@ const useStatewireThread = (
|
|
|
111
111
|
options.onCommandSessionLost === undefined
|
|
112
112
|
? options.transport
|
|
113
113
|
: withSessionLostFallback(options.transport, latest),
|
|
114
|
-
onCommandChange: (update) => {
|
|
114
|
+
onCommandChange: (update, ctx) => {
|
|
115
115
|
if (update.status === "acked" || update.status === "settled")
|
|
116
116
|
retire(update.params[0]);
|
|
117
|
+
latest.current.onCommandChange?.(update, ctx);
|
|
117
118
|
},
|
|
118
119
|
});
|
|
119
120
|
const attached = transportState !== undefined;
|
|
@@ -407,8 +408,6 @@ export namespace StatewireThread {
|
|
|
407
408
|
export type RunReloadCommand = {
|
|
408
409
|
readonly type: "run/reload";
|
|
409
410
|
readonly sourceId: string;
|
|
410
|
-
/** Client-generated id of the regenerated assistant message. */
|
|
411
|
-
readonly messageId: string;
|
|
412
411
|
};
|
|
413
412
|
|
|
414
413
|
export type RunCommand =
|
|
@@ -492,6 +491,15 @@ export namespace StatewireThread {
|
|
|
492
491
|
onCommandSessionLost?:
|
|
493
492
|
| ((command: StatewireClient.SessionLostCommand) => "replay" | void)
|
|
494
493
|
| undefined;
|
|
494
|
+
/** Observes each command's lifecycle (queued, posted, acked, settled); runs after the built-in pending-command retirement. */
|
|
495
|
+
onCommandChange?:
|
|
496
|
+
| ((
|
|
497
|
+
update: Statewire.CommandUpdate<
|
|
498
|
+
Record<string, (...args: any[]) => unknown>
|
|
499
|
+
>,
|
|
500
|
+
ctx: { state: NonNullable<T> },
|
|
501
|
+
) => void)
|
|
502
|
+
| undefined;
|
|
495
503
|
onError?: ((error: Error) => void) | undefined;
|
|
496
504
|
capabilities?:
|
|
497
505
|
| {
|
package/src/runCommands.ts
CHANGED
|
@@ -149,9 +149,5 @@ export const resolveReloadCommand = (
|
|
|
149
149
|
throw new Error(
|
|
150
150
|
"statewire: run/reload requires an assistant message to regenerate",
|
|
151
151
|
);
|
|
152
|
-
return {
|
|
153
|
-
type: "run/reload",
|
|
154
|
-
sourceId: target.id,
|
|
155
|
-
messageId: crypto.randomUUID(),
|
|
156
|
-
};
|
|
152
|
+
return { type: "run/reload", sourceId: target.id };
|
|
157
153
|
};
|
package/src/transport.test.tsx
CHANGED
|
@@ -1965,7 +1965,6 @@ describe("reload", () => {
|
|
|
1965
1965
|
{
|
|
1966
1966
|
type: "run/reload",
|
|
1967
1967
|
sourceId: "m2",
|
|
1968
|
-
messageId: expect.stringMatching(/^[0-9a-f-]{36}$/),
|
|
1969
1968
|
},
|
|
1970
1969
|
]);
|
|
1971
1970
|
expect("parentId" in fetchMock.requests[1]!.body).toBe(false);
|
|
@@ -2000,7 +1999,6 @@ describe("reload", () => {
|
|
|
2000
1999
|
{
|
|
2001
2000
|
type: "run/reload",
|
|
2002
2001
|
sourceId: "m2",
|
|
2003
|
-
messageId: expect.stringMatching(/^[0-9a-f-]{36}$/),
|
|
2004
2002
|
},
|
|
2005
2003
|
]);
|
|
2006
2004
|
});
|
package/src/types.ts
CHANGED
|
@@ -130,8 +130,6 @@ export type InputRequestState = InputRequest & {
|
|
|
130
130
|
export type RunReloadCommand = {
|
|
131
131
|
readonly type: "run/reload";
|
|
132
132
|
readonly sourceId: string;
|
|
133
|
-
/** Client-generated id of the regenerated assistant message. */
|
|
134
|
-
readonly messageId: string;
|
|
135
133
|
};
|
|
136
134
|
|
|
137
135
|
export type RunCommand =
|