@assistant-ui/react-statewire 0.0.4 → 0.1.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/StatewireThread.d.ts +7 -0
- package/dist/StatewireThread.d.ts.map +1 -1
- package/dist/StatewireThread.js +43 -13
- package/dist/StatewireThread.js.map +1 -1
- package/dist/host.d.ts +1 -2
- package/dist/host.d.ts.map +1 -1
- package/dist/host.js.map +1 -1
- package/package.json +2 -2
- package/src/StatewireThread.test.tsx +122 -17
- package/src/StatewireThread.ts +62 -9
- package/src/host.ts +6 -1
- package/src/transport.test.tsx +6 -3
|
@@ -20,7 +20,14 @@ declare namespace StatewireThread {
|
|
|
20
20
|
type StateConverter<T> = (state: T, connectionMetadata: ConnectionMetadata) => State;
|
|
21
21
|
type Options<T> = {
|
|
22
22
|
transport: Transport<T>;
|
|
23
|
+
initialState: T;
|
|
23
24
|
converter: StateConverter<T>;
|
|
25
|
+
/**
|
|
26
|
+
* "command-send" mirrors the client's ambient model context (system,
|
|
27
|
+
* tools, callSettings, config) to the server over the command channel —
|
|
28
|
+
* on connect and whenever it changes. Requires a remote transport.
|
|
29
|
+
*/
|
|
30
|
+
contextSync?: "command-send" | undefined;
|
|
24
31
|
onError?: ((error: Error) => void) | undefined;
|
|
25
32
|
capabilities?: {
|
|
26
33
|
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":";;;;;;;cA+Ja,kBAAmB,GAC9B,SAAS,gBAAgB,QAAQ,OAChC,gBAAgB;kBAGF;OACH,UAAU,KAAK,gBAAgB,UAAU;OAEzC;aACD,mBAAmB;aACnB,QAAQ;aACR;;OAGC;IACV,iBAAiB;IACjB;;OAGU,eAAe,MACzB,OAAO,GACP,oBAAoB,uBACjB;OAEO,QAAQ;IAClB,WAAW,UAAU;IACrB,cAAc;IACd,WAAW,eAAe;;;;;;IAM1B;IACA,YAAY,OAAO;IACnB;MAEM;;IAGN;MAEM,cAAc"}
|
package/dist/StatewireThread.js
CHANGED
|
@@ -1,30 +1,60 @@
|
|
|
1
1
|
import { convertAppendMessageToCommand, symbolAssistantTransportExtras } from "./AssistantTransportThread.js";
|
|
2
|
-
import { useCallback, useMemo, useRef, useState } from "@assistant-ui/tap/react-shim";
|
|
2
|
+
import { useCallback, useEffect, useMemo, useRef, useState } from "@assistant-ui/tap/react-shim";
|
|
3
3
|
import { resource, useResource } from "@assistant-ui/tap";
|
|
4
4
|
import { ExternalThread } from "@assistant-ui/react";
|
|
5
|
-
import { forwardTransformScopes } from "@assistant-ui/store";
|
|
5
|
+
import { forwardTransformScopes, useAssistantClientRef } from "@assistant-ui/store";
|
|
6
6
|
import { useStatewire } from "statewire";
|
|
7
|
+
import { toToolsJSONSchema } from "assistant-stream";
|
|
7
8
|
//#region src/StatewireThread.ts
|
|
8
|
-
const
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
}
|
|
9
|
+
const ambientContextOf = (context) => ({
|
|
10
|
+
...context.system !== void 0 && { system: context.system },
|
|
11
|
+
...context.tools !== void 0 && { tools: toToolsJSONSchema(context.tools) },
|
|
12
|
+
...context.callSettings !== void 0 && { callSettings: context.callSettings },
|
|
13
|
+
...context.config !== void 0 && { config: context.config }
|
|
14
|
+
});
|
|
12
15
|
const useStatewireThread = (options) => {
|
|
13
16
|
const latest = useRef(options);
|
|
14
17
|
latest.current = options;
|
|
15
18
|
const [pending, setPending] = useState([]);
|
|
16
19
|
const [retire] = useState(() => (command) => setPending((prev) => prev.includes(command) ? prev.filter((c) => c !== command) : prev));
|
|
17
|
-
const { state, commands } = useStatewire({
|
|
20
|
+
const { state: transportState, commands, setContext } = useStatewire({
|
|
18
21
|
transport: options.transport,
|
|
19
22
|
onCommandChange: (update) => {
|
|
20
23
|
if (update.status === "acked" || update.status === "settled") retire(update.params[0]);
|
|
21
24
|
}
|
|
22
25
|
});
|
|
26
|
+
const attached = transportState !== void 0;
|
|
27
|
+
const state = attached ? transportState : options.initialState;
|
|
28
|
+
const clientRef = useAssistantClientRef();
|
|
29
|
+
const setContextRef = useRef(setContext);
|
|
30
|
+
setContextRef.current = setContext;
|
|
31
|
+
const [syncState] = useState(() => ({ lastSent: void 0 }));
|
|
32
|
+
const { contextSync } = options;
|
|
33
|
+
useEffect(() => {
|
|
34
|
+
if (contextSync === void 0) return;
|
|
35
|
+
const modelContext = (clientRef.current ?? clientRef.parent).modelContext();
|
|
36
|
+
const send = () => {
|
|
37
|
+
const value = ambientContextOf(modelContext.getModelContext());
|
|
38
|
+
const key = JSON.stringify(value);
|
|
39
|
+
if (key === syncState.lastSent) return;
|
|
40
|
+
syncState.lastSent = key;
|
|
41
|
+
setContextRef.current(value).catch((error) => {
|
|
42
|
+
latest.current.onError?.(error);
|
|
43
|
+
});
|
|
44
|
+
};
|
|
45
|
+
send();
|
|
46
|
+
if (!modelContext.subscribe) throw new Error("statewire: contextSync requires a subscribable model context");
|
|
47
|
+
return modelContext.subscribe(send);
|
|
48
|
+
}, [
|
|
49
|
+
contextSync,
|
|
50
|
+
clientRef,
|
|
51
|
+
syncState
|
|
52
|
+
]);
|
|
23
53
|
const dispatch = useCallback((command_0) => {
|
|
24
54
|
setPending((prev_0) => [...prev_0, command_0]);
|
|
25
|
-
commands[command_0.type](command_0).catch((
|
|
55
|
+
commands[command_0.type](command_0).catch((error_0) => {
|
|
26
56
|
retire(command_0);
|
|
27
|
-
latest.current.onError?.(
|
|
57
|
+
latest.current.onError?.(error_0);
|
|
28
58
|
});
|
|
29
59
|
}, [commands, retire]);
|
|
30
60
|
const { converter } = options;
|
|
@@ -32,7 +62,7 @@ const useStatewireThread = (options) => {
|
|
|
32
62
|
pendingCommands: [...pending],
|
|
33
63
|
isSending: pending.length > 0
|
|
34
64
|
}), [pending]);
|
|
35
|
-
const converted = useMemo(() =>
|
|
65
|
+
const converted = useMemo(() => converter(state, metadata), [
|
|
36
66
|
converter,
|
|
37
67
|
state,
|
|
38
68
|
metadata
|
|
@@ -50,15 +80,15 @@ const useStatewireThread = (options) => {
|
|
|
50
80
|
return useResource(ExternalThread({
|
|
51
81
|
messages: converted.messages,
|
|
52
82
|
isRunning: converted.isRunning,
|
|
53
|
-
isLoading:
|
|
83
|
+
isLoading: !attached,
|
|
54
84
|
state: converted.state,
|
|
55
85
|
extras,
|
|
56
86
|
attachmentAdapter: options.adapters?.attachments,
|
|
57
87
|
onNew: handleAppend,
|
|
58
88
|
...options.capabilities?.edit && { onEdit: handleAppend },
|
|
59
89
|
onCancel: () => {
|
|
60
|
-
commands["cancel"]().catch((
|
|
61
|
-
latest.current.onError?.(
|
|
90
|
+
commands["cancel"]().catch((error_1) => {
|
|
91
|
+
latest.current.onError?.(error_1);
|
|
62
92
|
});
|
|
63
93
|
}
|
|
64
94
|
}));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StatewireThread.js","names":["useCallback","useMemo","useRef","useState","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","forwardTransformScopes","ClientOutput","AppendMessage","AttachmentAdapter","ThreadMessage","ReadonlyJSONValue","useStatewire","Statewire","convertAppendMessageToCommand","symbolAssistantTransportExtras","AssistantTransportExtras","AssistantTransportCommand","AnyCommands","Record","args","EMPTY_CONVERTED","StatewireThread","State","messages","isRunning","useStatewireThread","options","Options","latest","current","pending","setPending","retire","command","prev","includes","filter","c","state","commands","transport","onCommandChange","update","status","params","dispatch","type","catch","error","Error","onError","converter","metadata","ConnectionMetadata","pendingCommands","isSending","length","converted","undefined","extras","sendCommand","handleAppend","message","isLoading","attachmentAdapter","adapters","attachments","onNew","capabilities","edit","onEdit","onCancel","T","Transport","StateConverter","connectionMetadata","hook"],"sources":["../src/StatewireThread.ts"],"sourcesContent":["import { useCallback, 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 { forwardTransformScopes } from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport type {\n AppendMessage,\n AttachmentAdapter,\n ThreadMessage,\n} from \"@assistant-ui/core\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { useStatewire } from \"statewire\";\nimport type { Statewire } 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 EMPTY_CONVERTED: StatewireThread.State = {\n messages: [],\n isRunning: false,\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 { state, commands } = 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\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 }),\n [pending],\n );\n const converted = useMemo(\n () => (state === undefined ? EMPTY_CONVERTED : converter(state, metadata)),\n [converter, state, metadata],\n );\n\n const extras = useMemo(\n (): AssistantTransportExtras => ({\n [symbolAssistantTransportExtras]: true,\n sendCommand: dispatch,\n state,\n }),\n [dispatch, 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: state === undefined,\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n onNew: handleAppend,\n ...(options.capabilities?.edit && { onEdit: handleAppend }),\n onCancel: () => {\n void commands[\"cancel\"]!().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 State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n readonly isRunning: boolean;\n };\n\n export type ConnectionMetadata = {\n pendingCommands: AssistantTransportCommand[];\n isSending: boolean;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n export type Options<T> = {\n transport: Transport<T>;\n converter: StateConverter<T>;\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":";;;;;;;AAwBA,MAAMwB,kBAAyC;CAC7CG,UAAU,CAAA;CACVC,WAAW;AACb;AAEA,MAAMC,sBACJC,YAC2B;CAC3B,MAAME,SAAS9B,OAAO4B,OAAO;CAC7BE,OAAO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ACrBuC,WAAWzB,UAAUoB,KAAAA;EACrBpB,OAAOmB,UAAUnB;EACjBqB;EACAK,mBAAmBtC,QAAQuC,UAAUC;EACrCC,OAAON;EACP,GAAInC,QAAQ0C,cAAcC,QAAQ,EAAEC,QAAQT,aAAa;EACzDU,gBAAgB;GACd,SAAc,SAAS,CAAE,CAAC,CAACxB,OAAOC,YAAiB;IACjDpB,OAAOC,QAAQqB,UAAUF,OAAK;GAChC,CAAC;EACH;CACF,CAAC,CACH;AACF;AAEA,MAAa3B,mBACXK,YAEA1B,SAASyB,kBAAkB,CAAC,CAACC,OAAuC;AAuCtErB,uBACEoB,oBACAtB,eAAeuD,KAAAA,CAAkB,CAAC,CAACkB,IACrC"}
|
|
1
|
+
{"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","AppendMessage","AttachmentAdapter","ModelContext","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","convertAppendMessageToCommand","symbolAssistantTransportExtras","AssistantTransportExtras","AssistantTransportCommand","AnyCommands","Record","args","ambientContextOf","context","system","undefined","tools","Parameters","callSettings","config","useStatewireThread","options","StatewireThread","Options","latest","current","pending","setPending","retire","command","prev","includes","filter","c","state","transportState","commands","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","extras","sendCommand","handleAppend","message","messages","isRunning","isLoading","attachmentAdapter","adapters","attachments","onNew","capabilities","edit","onEdit","onCancel","T","Transport","State","StateConverter","connectionMetadata","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 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 } 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 // cast: core >=0.3.5 widens tool generics beyond assistant-stream's Tool\n tools: toToolsJSONSchema(\n context.tools as unknown as Parameters<typeof toToolsJSONSchema>[0],\n ),\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 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 }),\n [pending],\n );\n const converted = useMemo(\n () => converter(state, metadata),\n [converter, state, metadata],\n );\n\n const extras = useMemo(\n (): AssistantTransportExtras => ({\n [symbolAssistantTransportExtras]: true,\n sendCommand: dispatch,\n state,\n }),\n [dispatch, 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 ...(options.capabilities?.edit && { onEdit: handleAppend }),\n onCancel: () => {\n void commands[\"cancel\"]!().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 State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n readonly isRunning: boolean;\n };\n\n export type ConnectionMetadata = {\n pendingCommands: AssistantTransportCommand[];\n isSending: boolean;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\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 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":";;;;;;;;AA6BA,MAAM4B,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWC,KAAAA,KAAa,EAAED,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQG,UAAUD,KAAAA,KAAa,EAEjCC,OAAOf,kBACLY,QAAQG,KACV,EACF;CACA,GAAIH,QAAQK,iBAAiBH,KAAAA,KAAa,EACxCG,cAAcL,QAAQK,aACxB;CACA,GAAIL,QAAQM,WAAWJ,KAAAA,KAAa,EAAEI,QAAQN,QAAQM,OAAO;AAC/D;AAEA,MAAMC,sBACJC,YAC2B;CAC3B,MAAMG,SAASrC,OAAOkC,OAAO;CAC7BG,OAAOC,UAAUJ;CAEjB,MAAM,CAACK,SAASC,cAAcvC,SAC5B,CAAA,CACF;CACA,MAAM,CAACwC,UAAUxC,gBACRyC,YACLF,YAAYG,SACVA,KAAKC,SAAS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,SAAO,CAAC,CAAC6B,OAAOC,YAAiB;GAC5D/B,OAAOC,SAAO;GACdL,OAAOC,QAAQoC,UAAUF,OAAK;EAChC,CAAC;CACH,GACA,CAACvB,UAAUR,MAAM,CACnB;CAEA,MAAM,EAAEqC,cAAc5C;CACtB,MAAM6C,WAAWhF,eAC4B;EACzCkF,iBAAiB,CAAC,GAAG1C,OAAO;EAC5B2C,WAAW3C,QAAQ4C,SAAS;CAC9B,IACA,CAAC5C,OAAO,CACV;CACA,MAAM6C,YAAYrF,cACV+E,UAAU/B,OAAOgC,QAAQ,GAC/B;EAACD;EAAW/B;EAAOgC;CAAQ,CAC7B;CAEA,MAAMM,SAAStF,eACoB;GAC9BoB,iCAAiC;EAClCmE,aAAaV;EACb7B;CACF,IACA,CAAC6B,UAAU7B,KAAK,CAClB;CAEA,MAAMwC,gBAAgBC,YAA2B;EAC/C,MAAM9C,YAAUxB,8BAA8BsE,OAAO;EACrD,IAAI,CAAC9C,WAAS;EACdkC,SAASlC,SAAO;CAClB;CAEA,OAAOvC,YACLE,eAAe;EACboF,UAAUL,UAAUK;EACpBC,WAAWN,UAAUM;EACrBC,WAAW,CAACnC;EACZT,OAAOqC,UAAUrC;EACjBsC;EACAO,mBAAmB1D,QAAQ2D,UAAUC;EACrCC,OAAOR;EACP,GAAIrD,QAAQ8D,cAAcC,QAAQ,EAAEC,QAAQX,aAAa;EACzDY,gBAAgB;GACd,SAAc,SAAS,CAAE,CAAC,CAAC5B,OAAOC,YAAiB;IACjDnC,OAAOC,QAAQoC,UAAUF,OAAK;GAChC,CAAC;EACH;CACF,CAAC,CACH;AACF;AAEA,MAAarC,mBACXD,YAEAhC,SAAS+B,kBAAkB,CAAC,CAACC,OAAuC;AA8CtE3B,uBACE0B,oBACA5B,eAAeuB,KAAAA,CAAkB,CAAC,CAAC6E,IACrC"}
|
package/dist/host.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { AssistantTransportCommand, AssistantTransportOptions } from "./types.js";
|
|
2
|
-
import { Statewire } from "statewire";
|
|
3
2
|
import { ModelContext } from "@assistant-ui/core";
|
|
4
3
|
//#region src/host.d.ts
|
|
5
4
|
type SendOptions = {
|
|
@@ -34,7 +33,7 @@ type AssistantTransportHostCommands = {
|
|
|
34
33
|
reload(parentId: string | null): void;
|
|
35
34
|
importState(state: unknown): void;
|
|
36
35
|
};
|
|
37
|
-
declare const AssistantTransportHost: import("@assistant-ui/tap").Resource<Statewire<AssistantTransportHostState, AssistantTransportHostCommands
|
|
36
|
+
declare const AssistantTransportHost: import("@assistant-ui/tap").Resource<Statewire<AssistantTransportHostState, AssistantTransportHostCommands>, [options: HostOptions]>;
|
|
38
37
|
//#endregion
|
|
39
38
|
export { AssistantTransportHost, AssistantTransportHostCommands, AssistantTransportHostState, HostOptions, HostQueue, HostQueueCell, HostRunContext, SendOptions };
|
|
40
39
|
//# sourceMappingURL=host.d.ts.map
|
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":";;;KA2BY;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,OAAO;EACP,YAAY;;cA+WD,oDAAsB,SAAA,UAAA,6BAAA,kCAAA,SAAA"}
|
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;CAE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,kBAAkB;GACpBvC,SAAS;EACX;EACAyB,SAASwG,SAAsB;GAC7BhF,EAAE3B,WAAW2G;GACbjI,SAAS;EACX;EACA0B,aAAagC;CACf;AACF;AAEA,MAAMwE,6BACJC,YAC2E;CAC3E,MAAMC,gBAAgB1J,OAAOyJ,OAAO;CACpCC,cAAc5H,UAAU2H;CAExB,MAAM,CAACxG,OAAOmB,OAAOtD,yBAAsD;EACzEqB,OAAOsH,QAAQE;EACfvH,cAAc;EACdC,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","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","Parameters","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 ? // cast: core >=0.3.5 widens tool generics beyond assistant-stream's Tool\n toToolsJSONSchema(\n modelContext.tools as unknown as Parameters<\n typeof toToolsJSONSchema\n >[0],\n )\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;EAAM,CAAC,CAAC;CAC3D;CAEA,MAAMK,gBAAgBC,SAAkB;EACtCb,IAAIQ,MAAM,CAAC;GAAEC,IAAI;GAAWC,MAAM,CAAC,OAAO;GAAGH,OAAO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,WACMA,IAAI2F,SAAS,CAAC,CAAC5H,KAGe2H,CAEtBhE;EAAU+D;CAAK;AACjC;AAEA,MAAaG,yBAAyB9J,SAASuJ,yBAAyB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@assistant-ui/react-statewire",
|
|
3
|
-
"version": "0.0
|
|
3
|
+
"version": "0.1.0",
|
|
4
4
|
"description": "assistant-ui thread binding for statewire backends",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
"@assistant-ui/store": "^0.3.0",
|
|
35
35
|
"@assistant-ui/tap": "^0.9.7",
|
|
36
36
|
"assistant-stream": "^0.3.33",
|
|
37
|
-
"statewire": "^0.0.
|
|
37
|
+
"statewire": "^0.0.3"
|
|
38
38
|
},
|
|
39
39
|
"peerDependencies": {
|
|
40
40
|
"@assistant-ui/react": ">=0.14.0",
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
// statewire host stands in for the server.
|
|
5
5
|
|
|
6
6
|
import { render, waitFor } from "@testing-library/react";
|
|
7
|
-
import type { FC } from "react";
|
|
7
|
+
import type { FC, ReactNode } from "react";
|
|
8
8
|
import { useState } from "react";
|
|
9
9
|
import { describe, expect, it } from "vitest";
|
|
10
10
|
import { AuiProvider, useAui } from "@assistant-ui/store";
|
|
@@ -16,9 +16,15 @@ import {
|
|
|
16
16
|
useStatewireState,
|
|
17
17
|
} from "statewire/host";
|
|
18
18
|
import type { StatewireHost } from "statewire/host";
|
|
19
|
+
import { createMockTransport } from "statewire/testing";
|
|
19
20
|
import { StatewireThread } from "./StatewireThread";
|
|
21
|
+
import { useAssistantTransportState } from "./hooks";
|
|
20
22
|
import type { AddMessageCommand, AssistantTransportCommand } from "./types";
|
|
21
|
-
import {
|
|
23
|
+
import {
|
|
24
|
+
sendCommand,
|
|
25
|
+
threadTexts,
|
|
26
|
+
toThreadMessage,
|
|
27
|
+
} from "./__tests__/testHelpers";
|
|
22
28
|
|
|
23
29
|
type ServerState = {
|
|
24
30
|
messages: { id: string; role: "user" | "assistant"; text: string }[];
|
|
@@ -38,7 +44,13 @@ const converter: StatewireThread.StateConverter<ServerState> = (
|
|
|
38
44
|
...state.messages.map(toThreadMessage),
|
|
39
45
|
...meta.pendingCommands.flatMap((c, i) =>
|
|
40
46
|
c.type === "add-message" && c.message.role === "user"
|
|
41
|
-
? [
|
|
47
|
+
? [
|
|
48
|
+
toThreadMessage({
|
|
49
|
+
id: `optimistic-${i}`,
|
|
50
|
+
role: "user",
|
|
51
|
+
text: textOf(c),
|
|
52
|
+
}),
|
|
53
|
+
]
|
|
42
54
|
: [],
|
|
43
55
|
),
|
|
44
56
|
] as StatewireThread.State["messages"],
|
|
@@ -87,17 +99,26 @@ const createServer = (init?: { messages?: ServerState["messages"] }) => {
|
|
|
87
99
|
return { transport, received, cell };
|
|
88
100
|
};
|
|
89
101
|
|
|
90
|
-
const
|
|
102
|
+
const INITIAL_STATE: ServerState = { messages: [], running: false };
|
|
103
|
+
|
|
104
|
+
const mountThread = (
|
|
105
|
+
options: Omit<StatewireThread.Options<ServerState>, "initialState"> &
|
|
106
|
+
Partial<Pick<StatewireThread.Options<ServerState>, "initialState">>,
|
|
107
|
+
children?: ReactNode,
|
|
108
|
+
) => {
|
|
91
109
|
const captured: { aui?: ReturnType<typeof useAui> } = {};
|
|
92
110
|
const Capture: FC = () => {
|
|
93
111
|
captured.aui = useAui();
|
|
94
112
|
return null;
|
|
95
113
|
};
|
|
96
114
|
const App: FC = () => {
|
|
97
|
-
const aui = useAui({
|
|
115
|
+
const aui = useAui({
|
|
116
|
+
thread: StatewireThread({ initialState: INITIAL_STATE, ...options }),
|
|
117
|
+
});
|
|
98
118
|
return (
|
|
99
119
|
<AuiProvider value={aui}>
|
|
100
120
|
<Capture />
|
|
121
|
+
{children}
|
|
101
122
|
</AuiProvider>
|
|
102
123
|
);
|
|
103
124
|
};
|
|
@@ -122,7 +143,7 @@ describe("StatewireThread", () => {
|
|
|
122
143
|
expect(aui().thread().getState().isRunning).toBe(false);
|
|
123
144
|
});
|
|
124
145
|
|
|
125
|
-
it("
|
|
146
|
+
it("serves initialState until the first snapshot replaces it", async () => {
|
|
126
147
|
const cell: { attach?: () => void } = {};
|
|
127
148
|
const transport = resource(() => {
|
|
128
149
|
const [attached, setAttached] = useState(false);
|
|
@@ -135,15 +156,29 @@ describe("StatewireThread", () => {
|
|
|
135
156
|
return { state: attached ? state : undefined, commands };
|
|
136
157
|
})();
|
|
137
158
|
|
|
138
|
-
const
|
|
159
|
+
const initialState: ServerState = {
|
|
160
|
+
messages: [{ id: "i1", role: "assistant", text: "local" }],
|
|
161
|
+
running: false,
|
|
162
|
+
};
|
|
163
|
+
const observed: unknown[] = [];
|
|
164
|
+
const Probe: FC = () => {
|
|
165
|
+
observed.push(useAssistantTransportState());
|
|
166
|
+
return null;
|
|
167
|
+
};
|
|
168
|
+
const { aui } = mountThread(
|
|
169
|
+
{ transport, converter, initialState },
|
|
170
|
+
<Probe />,
|
|
171
|
+
);
|
|
139
172
|
|
|
140
|
-
|
|
141
|
-
expect(threadTexts(aui)).toEqual([]);
|
|
173
|
+
expect(observed[0]).toBe(initialState);
|
|
174
|
+
expect(threadTexts(aui)).toEqual(["local"]);
|
|
175
|
+
expect(aui().thread().getState().isLoading).toBe(true);
|
|
142
176
|
|
|
143
177
|
cell.attach!();
|
|
144
178
|
|
|
145
179
|
await waitFor(() => expect(threadTexts(aui)).toEqual(["welcome"]));
|
|
146
180
|
expect(aui().thread().getState().isLoading).toBe(false);
|
|
181
|
+
expect((observed.at(-1) as ServerState).messages[0]!.text).toBe("welcome");
|
|
147
182
|
});
|
|
148
183
|
|
|
149
184
|
it("round-trips an appended message through the add-message command", async () => {
|
|
@@ -161,9 +196,7 @@ describe("StatewireThread", () => {
|
|
|
161
196
|
});
|
|
162
197
|
|
|
163
198
|
await waitFor(() => expect(threadTexts(aui)).toEqual(["hello"]));
|
|
164
|
-
await waitFor(() =>
|
|
165
|
-
expect(aui().thread().getState().isRunning).toBe(true),
|
|
166
|
-
);
|
|
199
|
+
await waitFor(() => expect(aui().thread().getState().isRunning).toBe(true));
|
|
167
200
|
|
|
168
201
|
server.cell.state!.messages.push({
|
|
169
202
|
id: "a1",
|
|
@@ -210,9 +243,7 @@ describe("StatewireThread", () => {
|
|
|
210
243
|
const { aui } = mountThread({ transport: server.transport, converter });
|
|
211
244
|
|
|
212
245
|
aui().thread().append("hello");
|
|
213
|
-
await waitFor(() =>
|
|
214
|
-
expect(aui().thread().getState().isRunning).toBe(true),
|
|
215
|
-
);
|
|
246
|
+
await waitFor(() => expect(aui().thread().getState().isRunning).toBe(true));
|
|
216
247
|
|
|
217
248
|
aui().thread().cancelRun();
|
|
218
249
|
|
|
@@ -239,14 +270,88 @@ describe("StatewireThread", () => {
|
|
|
239
270
|
},
|
|
240
271
|
});
|
|
241
272
|
|
|
242
|
-
await waitFor(() =>
|
|
243
|
-
|
|
273
|
+
await waitFor(() =>
|
|
274
|
+
expect(aui().thread().getState().isLoading).toBe(false),
|
|
275
|
+
);
|
|
276
|
+
sendCommand(aui, {
|
|
277
|
+
type: "reject-me",
|
|
278
|
+
} as unknown as AssistantTransportCommand);
|
|
244
279
|
|
|
245
280
|
await waitFor(() => expect(errors).toHaveLength(1));
|
|
246
281
|
expect(errors[0]!.message).toContain("nope");
|
|
247
282
|
await waitFor(() => expect(metas.at(-1)!.pendingCommands).toEqual([]));
|
|
248
283
|
});
|
|
249
284
|
|
|
285
|
+
describe("contextSync: command-send", () => {
|
|
286
|
+
const contextValueOf = (command: { context?: unknown }) => {
|
|
287
|
+
const ops = command.context as [
|
|
288
|
+
{ op: string; path: unknown[]; value: unknown },
|
|
289
|
+
];
|
|
290
|
+
expect(ops).toHaveLength(1);
|
|
291
|
+
expect(ops[0]).toMatchObject({ op: "replace", path: [] });
|
|
292
|
+
return ops[0].value as Record<string, unknown>;
|
|
293
|
+
};
|
|
294
|
+
|
|
295
|
+
it("sends the ambient model context on connect and on every change", async () => {
|
|
296
|
+
const mock = createMockTransport<ServerState>({
|
|
297
|
+
messages: [],
|
|
298
|
+
running: false,
|
|
299
|
+
});
|
|
300
|
+
const { aui } = mountThread({
|
|
301
|
+
transport: mock.transport,
|
|
302
|
+
converter,
|
|
303
|
+
contextSync: "command-send",
|
|
304
|
+
});
|
|
305
|
+
|
|
306
|
+
await waitFor(() => expect(mock.commands).toHaveLength(1));
|
|
307
|
+
const initial = contextValueOf(mock.commands[0]!);
|
|
308
|
+
expect(initial["system"]).toBeUndefined();
|
|
309
|
+
|
|
310
|
+
aui()
|
|
311
|
+
.modelContext()
|
|
312
|
+
.register({ getModelContext: () => ({ system: "be nice" }) });
|
|
313
|
+
|
|
314
|
+
await waitFor(() => expect(mock.commands).toHaveLength(2));
|
|
315
|
+
expect(contextValueOf(mock.commands[1]!)["system"]).toBe("be nice");
|
|
316
|
+
});
|
|
317
|
+
|
|
318
|
+
it("skips resends while the serialized context is unchanged", async () => {
|
|
319
|
+
const mock = createMockTransport<ServerState>({
|
|
320
|
+
messages: [],
|
|
321
|
+
running: false,
|
|
322
|
+
});
|
|
323
|
+
const { aui } = mountThread({
|
|
324
|
+
transport: mock.transport,
|
|
325
|
+
converter,
|
|
326
|
+
contextSync: "command-send",
|
|
327
|
+
});
|
|
328
|
+
await waitFor(() => expect(mock.commands).toHaveLength(1));
|
|
329
|
+
|
|
330
|
+
// notifies subscribers without changing the merged context
|
|
331
|
+
aui()
|
|
332
|
+
.modelContext()
|
|
333
|
+
.register({ getModelContext: () => ({}) });
|
|
334
|
+
aui()
|
|
335
|
+
.modelContext()
|
|
336
|
+
.register({ getModelContext: () => ({ system: "be nice" }) });
|
|
337
|
+
|
|
338
|
+
await waitFor(() => expect(mock.commands).toHaveLength(2));
|
|
339
|
+
expect(contextValueOf(mock.commands[1]!)["system"]).toBe("be nice");
|
|
340
|
+
});
|
|
341
|
+
|
|
342
|
+
it("stays off the wire without the option", async () => {
|
|
343
|
+
const mock = createMockTransport<ServerState>({
|
|
344
|
+
messages: [],
|
|
345
|
+
running: false,
|
|
346
|
+
});
|
|
347
|
+
const { aui } = mountThread({ transport: mock.transport, converter });
|
|
348
|
+
await waitFor(() =>
|
|
349
|
+
expect(aui().thread().getState().isLoading).toBe(false),
|
|
350
|
+
);
|
|
351
|
+
expect(mock.commands).toEqual([]);
|
|
352
|
+
});
|
|
353
|
+
});
|
|
354
|
+
|
|
250
355
|
it("enables the edit capability from options", async () => {
|
|
251
356
|
const server = createServer();
|
|
252
357
|
const { aui } = mountThread({
|
package/src/StatewireThread.ts
CHANGED
|
@@ -1,15 +1,20 @@
|
|
|
1
|
-
import { useCallback, useMemo, useRef, useState } from "react";
|
|
1
|
+
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
2
2
|
import { resource, useResource } from "@assistant-ui/tap";
|
|
3
3
|
import type { ResourceElement } from "@assistant-ui/tap";
|
|
4
4
|
import { ExternalThread } from "@assistant-ui/react";
|
|
5
5
|
import type { ExternalThreadMessage } from "@assistant-ui/react";
|
|
6
|
-
import {
|
|
6
|
+
import {
|
|
7
|
+
forwardTransformScopes,
|
|
8
|
+
useAssistantClientRef,
|
|
9
|
+
} from "@assistant-ui/store";
|
|
7
10
|
import type { ClientOutput } from "@assistant-ui/store";
|
|
8
11
|
import type {
|
|
9
12
|
AppendMessage,
|
|
10
13
|
AttachmentAdapter,
|
|
14
|
+
ModelContext,
|
|
11
15
|
ThreadMessage,
|
|
12
16
|
} from "@assistant-ui/core";
|
|
17
|
+
import { toToolsJSONSchema } from "assistant-stream";
|
|
13
18
|
import type { ReadonlyJSONValue } from "assistant-stream/utils";
|
|
14
19
|
import { useStatewire } from "statewire";
|
|
15
20
|
import type { Statewire } from "statewire";
|
|
@@ -22,10 +27,19 @@ import type { AssistantTransportCommand } from "./types";
|
|
|
22
27
|
|
|
23
28
|
type AnyCommands = Record<string, (...args: any[]) => unknown>;
|
|
24
29
|
|
|
25
|
-
const
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
30
|
+
const ambientContextOf = (context: ModelContext): Record<string, unknown> => ({
|
|
31
|
+
...(context.system !== undefined && { system: context.system }),
|
|
32
|
+
...(context.tools !== undefined && {
|
|
33
|
+
// cast: core >=0.3.5 widens tool generics beyond assistant-stream's Tool
|
|
34
|
+
tools: toToolsJSONSchema(
|
|
35
|
+
context.tools as unknown as Parameters<typeof toToolsJSONSchema>[0],
|
|
36
|
+
),
|
|
37
|
+
}),
|
|
38
|
+
...(context.callSettings !== undefined && {
|
|
39
|
+
callSettings: context.callSettings,
|
|
40
|
+
}),
|
|
41
|
+
...(context.config !== undefined && { config: context.config }),
|
|
42
|
+
});
|
|
29
43
|
|
|
30
44
|
const useStatewireThread = (
|
|
31
45
|
options: StatewireThread.Options<any>,
|
|
@@ -45,13 +59,45 @@ const useStatewireThread = (
|
|
|
45
59
|
),
|
|
46
60
|
);
|
|
47
61
|
|
|
48
|
-
const {
|
|
62
|
+
const {
|
|
63
|
+
state: transportState,
|
|
64
|
+
commands,
|
|
65
|
+
setContext,
|
|
66
|
+
} = useStatewire<unknown, AnyCommands>({
|
|
49
67
|
transport: options.transport,
|
|
50
68
|
onCommandChange: (update) => {
|
|
51
69
|
if (update.status === "acked" || update.status === "settled")
|
|
52
70
|
retire(update.params[0]);
|
|
53
71
|
},
|
|
54
72
|
});
|
|
73
|
+
const attached = transportState !== undefined;
|
|
74
|
+
const state = attached ? transportState : options.initialState;
|
|
75
|
+
|
|
76
|
+
const clientRef = useAssistantClientRef();
|
|
77
|
+
const setContextRef = useRef(setContext);
|
|
78
|
+
setContextRef.current = setContext;
|
|
79
|
+
const [syncState] = useState(() => ({ lastSent: undefined as unknown }));
|
|
80
|
+
const { contextSync } = options;
|
|
81
|
+
useEffect(() => {
|
|
82
|
+
if (contextSync === undefined) return;
|
|
83
|
+
const modelContext = (clientRef.current ?? clientRef.parent).modelContext();
|
|
84
|
+
const send = () => {
|
|
85
|
+
const value = ambientContextOf(modelContext.getModelContext());
|
|
86
|
+
const key = JSON.stringify(value);
|
|
87
|
+
if (key === syncState.lastSent) return;
|
|
88
|
+
syncState.lastSent = key;
|
|
89
|
+
void setContextRef.current(value).catch((error: Error) => {
|
|
90
|
+
latest.current.onError?.(error);
|
|
91
|
+
});
|
|
92
|
+
};
|
|
93
|
+
send();
|
|
94
|
+
if (!modelContext.subscribe) {
|
|
95
|
+
throw new Error(
|
|
96
|
+
"statewire: contextSync requires a subscribable model context",
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
return modelContext.subscribe(send);
|
|
100
|
+
}, [contextSync, clientRef, syncState]);
|
|
55
101
|
|
|
56
102
|
const dispatch = useCallback(
|
|
57
103
|
(command: AssistantTransportCommand) => {
|
|
@@ -73,7 +119,7 @@ const useStatewireThread = (
|
|
|
73
119
|
[pending],
|
|
74
120
|
);
|
|
75
121
|
const converted = useMemo(
|
|
76
|
-
() =>
|
|
122
|
+
() => converter(state, metadata),
|
|
77
123
|
[converter, state, metadata],
|
|
78
124
|
);
|
|
79
125
|
|
|
@@ -96,7 +142,7 @@ const useStatewireThread = (
|
|
|
96
142
|
ExternalThread({
|
|
97
143
|
messages: converted.messages as readonly ExternalThreadMessage[],
|
|
98
144
|
isRunning: converted.isRunning,
|
|
99
|
-
isLoading:
|
|
145
|
+
isLoading: !attached,
|
|
100
146
|
state: converted.state,
|
|
101
147
|
extras,
|
|
102
148
|
attachmentAdapter: options.adapters?.attachments,
|
|
@@ -137,7 +183,14 @@ export namespace StatewireThread {
|
|
|
137
183
|
|
|
138
184
|
export type Options<T> = {
|
|
139
185
|
transport: Transport<T>;
|
|
186
|
+
initialState: T;
|
|
140
187
|
converter: StateConverter<T>;
|
|
188
|
+
/**
|
|
189
|
+
* "command-send" mirrors the client's ambient model context (system,
|
|
190
|
+
* tools, callSettings, config) to the server over the command channel —
|
|
191
|
+
* on connect and whenever it changes. Requires a remote transport.
|
|
192
|
+
*/
|
|
193
|
+
contextSync?: "command-send" | undefined;
|
|
141
194
|
onError?: ((error: Error) => void) | undefined;
|
|
142
195
|
capabilities?:
|
|
143
196
|
| {
|
package/src/host.ts
CHANGED
|
@@ -183,7 +183,12 @@ const useHostLoop = (
|
|
|
183
183
|
state: getAgent(),
|
|
184
184
|
system: modelContext.system,
|
|
185
185
|
tools: modelContext.tools
|
|
186
|
-
?
|
|
186
|
+
? // cast: core >=0.3.5 widens tool generics beyond assistant-stream's Tool
|
|
187
|
+
toToolsJSONSchema(
|
|
188
|
+
modelContext.tools as unknown as Parameters<
|
|
189
|
+
typeof toToolsJSONSchema
|
|
190
|
+
>[0],
|
|
191
|
+
)
|
|
187
192
|
: undefined,
|
|
188
193
|
threadId,
|
|
189
194
|
...(runParentId !== undefined && { parentId: runParentId }),
|
package/src/transport.test.tsx
CHANGED
|
@@ -1782,13 +1782,16 @@ describe("AssistantTransportThread", () => {
|
|
|
1782
1782
|
it("sends threadId null when the thread list item lookup throws", async () => {
|
|
1783
1783
|
const fetchMock = installFetch();
|
|
1784
1784
|
|
|
1785
|
+
const brokenItem = {
|
|
1786
|
+
getState: () => {
|
|
1787
|
+
throw new Error("no current item");
|
|
1788
|
+
},
|
|
1789
|
+
};
|
|
1785
1790
|
const BrokenThreads = resource(
|
|
1786
1791
|
() =>
|
|
1787
1792
|
({
|
|
1788
1793
|
getState: () => ({}),
|
|
1789
|
-
item: () =>
|
|
1790
|
-
throw new Error("no current item");
|
|
1791
|
-
},
|
|
1794
|
+
item: () => brokenItem,
|
|
1792
1795
|
}) as never,
|
|
1793
1796
|
);
|
|
1794
1797
|
|