@assistant-ui/react-statewire 0.4.2 → 0.4.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/AssistantTransportThread.d.ts +190 -4
- package/dist/AssistantTransportThread.d.ts.map +1 -1
- package/dist/AssistantTransportThread.js.map +1 -1
- package/dist/StatewireThread.d.ts +6 -2
- package/dist/StatewireThread.d.ts.map +1 -1
- package/dist/StatewireThread.js +2 -1
- package/dist/StatewireThread.js.map +1 -1
- package/dist/hooks.d.ts +4 -2
- package/dist/hooks.d.ts.map +1 -1
- package/dist/hooks.js.map +1 -1
- package/dist/host.d.ts +5 -5
- package/dist/host.d.ts.map +1 -1
- package/dist/host.js.map +1 -1
- package/dist/index.d.ts +1 -36
- package/dist/inputRequests.d.ts +4 -4
- package/dist/inputRequests.d.ts.map +1 -1
- package/dist/inputRequests.js.map +1 -1
- package/dist/runCommands.d.ts +6 -6
- package/dist/runCommands.d.ts.map +1 -1
- package/dist/runCommands.js.map +1 -1
- package/package.json +1 -1
- package/src/AssistantTransportThread.ts +258 -14
- package/src/StatewireThread.test.tsx +41 -2
- package/src/StatewireThread.ts +16 -4
- package/src/__tests__/testHelpers.tsx +11 -17
- package/src/athena.e2e.test.tsx +15 -19
- package/src/hooks.ts +7 -2
- package/src/host.ts +11 -13
- package/src/index.ts +1 -36
- package/src/inputRequests.ts +8 -6
- package/src/legacy-diff.test.tsx +4 -7
- package/src/runCommands.ts +14 -16
- package/src/transport.test.tsx +12 -16
- package/dist/index.d.ts.map +0 -1
- package/dist/types.d.ts +0 -189
- package/dist/types.d.ts.map +0 -1
- package/dist/types.js +0 -0
- package/src/types.ts +0 -255
|
@@ -1,18 +1,204 @@
|
|
|
1
|
-
import { AssistantTransportCommand, AssistantTransportOptions, InputRequestState } from "./types.js";
|
|
2
1
|
import { ResourceElement } from "@assistant-ui/tap";
|
|
2
|
+
import { Assistant } from "@assistant-ui/react";
|
|
3
3
|
import { ClientOutput } from "@assistant-ui/store";
|
|
4
|
+
import { AttachmentAdapter, LanguageModelConfig, LanguageModelV1CallSettings, ThreadMessage, ToolExecutionStatus } from "@assistant-ui/core";
|
|
5
|
+
import { ReadonlyJSONValue } from "assistant-stream/utils";
|
|
4
6
|
//#region src/AssistantTransportThread.d.ts
|
|
5
7
|
declare const symbolAssistantTransportExtras: unique symbol;
|
|
6
8
|
type AssistantTransportExtras = {
|
|
7
9
|
[symbolAssistantTransportExtras]: true;
|
|
8
|
-
sendCommand: (command:
|
|
10
|
+
sendCommand: (command: AssistantTransportThread.Command) => void;
|
|
9
11
|
reconnect: () => void;
|
|
10
12
|
state: unknown;
|
|
11
13
|
/** The host's parked input requests; absent when the converter does not project them. */
|
|
12
|
-
inputRequests?: readonly InputRequestState[];
|
|
14
|
+
inputRequests?: readonly AssistantTransportThread.InputRequestState[];
|
|
13
15
|
};
|
|
14
16
|
declare const asAssistantTransportExtras: (extras: unknown) => AssistantTransportExtras;
|
|
15
|
-
declare const AssistantTransportThread: <T>(options:
|
|
17
|
+
declare const AssistantTransportThread: <T>(options: AssistantTransportThread.Options<T>) => ResourceElement<ClientOutput<"thread">>;
|
|
18
|
+
declare namespace AssistantTransportThread {
|
|
19
|
+
type UserCommands = Assistant.Commands[keyof Assistant.Commands];
|
|
20
|
+
export type TextPart = {
|
|
21
|
+
readonly type: "text";
|
|
22
|
+
readonly text: string;
|
|
23
|
+
};
|
|
24
|
+
export type FilePart = {
|
|
25
|
+
readonly type: "file";
|
|
26
|
+
readonly mediaType: string;
|
|
27
|
+
readonly url: string;
|
|
28
|
+
readonly filename?: string;
|
|
29
|
+
};
|
|
30
|
+
export type RunUserMessage = {
|
|
31
|
+
readonly id: string;
|
|
32
|
+
readonly role: "user";
|
|
33
|
+
readonly parts: readonly (TextPart | FilePart)[];
|
|
34
|
+
readonly metadata?: Record<string, unknown>;
|
|
35
|
+
};
|
|
36
|
+
/** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */
|
|
37
|
+
export type RunPlacement = {
|
|
38
|
+
readonly insertAfter?: string | null;
|
|
39
|
+
readonly insertBefore?: string | null;
|
|
40
|
+
};
|
|
41
|
+
export type RunEnqueueCommand = {
|
|
42
|
+
readonly type: "run/enqueue";
|
|
43
|
+
} & ({
|
|
44
|
+
readonly message: RunUserMessage;
|
|
45
|
+
/** 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. */
|
|
46
|
+
readonly anchorMessageId?: string | null;
|
|
47
|
+
} | {
|
|
48
|
+
readonly messageId: string;
|
|
49
|
+
}) & RunPlacement;
|
|
50
|
+
export type RunSteerCommand = {
|
|
51
|
+
readonly type: "run/steer";
|
|
52
|
+
} & ({
|
|
53
|
+
readonly message: RunUserMessage;
|
|
54
|
+
/** 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. */
|
|
55
|
+
readonly anchorMessageId?: string | null;
|
|
56
|
+
} | {
|
|
57
|
+
readonly messageId: string;
|
|
58
|
+
}) & RunPlacement;
|
|
59
|
+
export type RunDequeueCommand = {
|
|
60
|
+
readonly type: "run/dequeue";
|
|
61
|
+
readonly messageId: string;
|
|
62
|
+
};
|
|
63
|
+
export type RunEditCommand = {
|
|
64
|
+
readonly type: "run/edit";
|
|
65
|
+
readonly message: RunUserMessage;
|
|
66
|
+
readonly sourceId: string;
|
|
67
|
+
};
|
|
68
|
+
export type RunContinueCommand = {
|
|
69
|
+
readonly type: "run/continue";
|
|
70
|
+
};
|
|
71
|
+
export type ToolCallInputRequest = {
|
|
72
|
+
readonly type: "tool-call";
|
|
73
|
+
readonly id: string;
|
|
74
|
+
readonly toolCallId: string;
|
|
75
|
+
};
|
|
76
|
+
export type ToolApprovalInputRequest = {
|
|
77
|
+
readonly type: "tool-approval";
|
|
78
|
+
readonly id: string;
|
|
79
|
+
readonly toolCallId: string;
|
|
80
|
+
};
|
|
81
|
+
export type CustomInputRequest = {
|
|
82
|
+
readonly type: string;
|
|
83
|
+
readonly id: string;
|
|
84
|
+
readonly [key: string]: ReadonlyJSONValue | undefined;
|
|
85
|
+
};
|
|
86
|
+
/** A host request parking the run until answered; open union for custom types. */
|
|
87
|
+
export type InputRequest = ToolCallInputRequest | ToolApprovalInputRequest | CustomInputRequest;
|
|
88
|
+
export type ToolCallInputResponse = {
|
|
89
|
+
readonly output: ReadonlyJSONValue;
|
|
90
|
+
/** Default false; when true, `output` carries the error payload. */
|
|
91
|
+
readonly isError?: boolean;
|
|
92
|
+
readonly artifact?: ReadonlyJSONValue;
|
|
93
|
+
};
|
|
94
|
+
export type ToolApprovalInputResponse = {
|
|
95
|
+
readonly decision: "approve" | "reject" | "edit" | "respond";
|
|
96
|
+
readonly editedArgs?: ReadonlyJSONValue;
|
|
97
|
+
readonly message?: string;
|
|
98
|
+
};
|
|
99
|
+
export type InputResponse = ReadonlyJSONValue;
|
|
100
|
+
export type RunInputCommand = {
|
|
101
|
+
readonly type: "run/input";
|
|
102
|
+
readonly requestId: string;
|
|
103
|
+
readonly response: InputResponse;
|
|
104
|
+
};
|
|
105
|
+
/** An input request projected out of the host state with its response echo. */
|
|
106
|
+
export type InputRequestState = InputRequest & {
|
|
107
|
+
readonly response: InputResponse | null;
|
|
108
|
+
};
|
|
109
|
+
export type RunReloadCommand = {
|
|
110
|
+
readonly type: "run/reload";
|
|
111
|
+
readonly sourceId: string;
|
|
112
|
+
};
|
|
113
|
+
export type RunCommand = RunEnqueueCommand | RunSteerCommand | RunDequeueCommand | RunEditCommand | RunContinueCommand | RunReloadCommand | RunInputCommand;
|
|
114
|
+
export type Command = RunCommand | UserCommands;
|
|
115
|
+
/** A queued message projected out of the host state, wire shape. */
|
|
116
|
+
export type RunQueueItem = {
|
|
117
|
+
readonly id: string;
|
|
118
|
+
readonly parts: readonly (TextPart | FilePart)[];
|
|
119
|
+
};
|
|
120
|
+
export type State = {
|
|
121
|
+
readonly messages: readonly ThreadMessage[];
|
|
122
|
+
readonly state?: ReadonlyJSONValue;
|
|
123
|
+
readonly isRunning: boolean;
|
|
124
|
+
/**
|
|
125
|
+
* The host's regular queue lane projected out of the state. Returning it
|
|
126
|
+
* (even empty) turns on the server-side queue: sends become `run/enqueue`
|
|
127
|
+
* / `run/steer` commands and item controls send the `run/*` queue
|
|
128
|
+
* commands. Presence must be stable across conversions and excludes the
|
|
129
|
+
* client-local `capabilities.queue` buffer.
|
|
130
|
+
*/
|
|
131
|
+
readonly queue?: readonly RunQueueItem[];
|
|
132
|
+
/** The host's steer lane; requires `queue`. Absent means empty. */
|
|
133
|
+
readonly steerQueue?: readonly RunQueueItem[];
|
|
134
|
+
/**
|
|
135
|
+
* The host's parked input requests projected out of the state. Returning it
|
|
136
|
+
* (even empty) routes tool results and approvals with a matching pending
|
|
137
|
+
* request through `run/input`. Presence must be stable across conversions.
|
|
138
|
+
*/
|
|
139
|
+
readonly inputRequests?: readonly AssistantTransportThread.InputRequestState[];
|
|
140
|
+
};
|
|
141
|
+
export type ConnectionMetadata = {
|
|
142
|
+
pendingCommands: Command[];
|
|
143
|
+
isSending: boolean;
|
|
144
|
+
toolStatuses: Record<string, ToolExecutionStatus>;
|
|
145
|
+
};
|
|
146
|
+
export type StateConverter<T> = (state: T, connectionMetadata: ConnectionMetadata) => State;
|
|
147
|
+
export type HeadersValue = Record<string, string> | Headers;
|
|
148
|
+
export type Protocol = "data-stream" | "assistant-transport";
|
|
149
|
+
export type SendCommandsRequestBody = {
|
|
150
|
+
commands: Command[];
|
|
151
|
+
state: unknown;
|
|
152
|
+
system: string | undefined;
|
|
153
|
+
tools: Record<string, unknown> | undefined;
|
|
154
|
+
callSettings: LanguageModelV1CallSettings | undefined;
|
|
155
|
+
config: LanguageModelConfig | undefined;
|
|
156
|
+
threadId: string | null;
|
|
157
|
+
parentId?: string | null;
|
|
158
|
+
[key: string]: unknown;
|
|
159
|
+
};
|
|
160
|
+
export type Options<T> = {
|
|
161
|
+
initialState: T;
|
|
162
|
+
converter: StateConverter<T>;
|
|
163
|
+
api: string;
|
|
164
|
+
resumeApi?: string | undefined;
|
|
165
|
+
protocol?: Protocol | undefined;
|
|
166
|
+
headers: HeadersValue | (() => Promise<HeadersValue>);
|
|
167
|
+
body?: object | (() => Promise<object | undefined>) | undefined;
|
|
168
|
+
/** Transform the fully assembled request body before it is sent. */
|
|
169
|
+
prepareSendCommandsRequest?: ((body: SendCommandsRequestBody) => Record<string, unknown> | Promise<Record<string, unknown>>) | undefined;
|
|
170
|
+
onResponse?: ((response: Response) => void) | undefined;
|
|
171
|
+
onFinish?: (() => void) | undefined;
|
|
172
|
+
onError?: ((error: Error, params: {
|
|
173
|
+
commands: Command[];
|
|
174
|
+
updateState: (updater: (state: T) => T) => void;
|
|
175
|
+
}) => void | Promise<void>) | undefined;
|
|
176
|
+
/**
|
|
177
|
+
* Called when commands are cancelled. After an error, queued commands are
|
|
178
|
+
* cancelled once `onError` settles; `error` then carries the cause.
|
|
179
|
+
*/
|
|
180
|
+
onCancel?: ((params: {
|
|
181
|
+
commands: Command[];
|
|
182
|
+
updateState: (updater: (state: T) => T) => void;
|
|
183
|
+
error?: Error;
|
|
184
|
+
}) => void) | undefined;
|
|
185
|
+
capabilities?: {
|
|
186
|
+
edit?: boolean | undefined;
|
|
187
|
+
/**
|
|
188
|
+
* Buffer messages sent during a run in an in-memory queue and dispatch
|
|
189
|
+
* them once the run settles. Steering interrupts the active run.
|
|
190
|
+
* Mutually exclusive with the converter's `queue` projection.
|
|
191
|
+
*/
|
|
192
|
+
queue?: boolean | undefined;
|
|
193
|
+
/** The host supports `run/continue` (a continue affordance on aborted runs). */
|
|
194
|
+
continue?: boolean | undefined;
|
|
195
|
+
} | undefined;
|
|
196
|
+
adapters?: {
|
|
197
|
+
attachments?: AttachmentAdapter | undefined;
|
|
198
|
+
} | undefined;
|
|
199
|
+
};
|
|
200
|
+
export {};
|
|
201
|
+
}
|
|
16
202
|
//#endregion
|
|
17
203
|
export { AssistantTransportExtras, AssistantTransportThread, asAssistantTransportExtras, symbolAssistantTransportExtras };
|
|
18
204
|
//# sourceMappingURL=AssistantTransportThread.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AssistantTransportThread.d.ts","names":[],"sources":["../src/AssistantTransportThread.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"AssistantTransportThread.d.ts","names":[],"sources":["../src/AssistantTransportThread.ts"],"mappings":";;;;;;cAyDa;KAID;GACT;EACD,cAAc,SAAS,yBAAyB;EAChD;EACA;;EAEA,yBAAyB,yBAAyB;;cAGvC,6BACX,oBACC;cAoVU,2BAA4B,GACvC,SAAS,yBAAyB,QAAQ,OACzC,gBAAgB;kBAKF;OACV,eAAe,UAAU,eAAe,UAAU;cAE3C;aACD;aACA;;cAGC;aACD;aACA;aACA;aACA;;cAGC;aACD;aACA;aACA,iBAAiB,WAAW;aAC5B,WAAW;;;cAIV;aACD;aACA;;cAGC;aACD;;aAGI,SAAS;;aAET;;aAEA;OAEb;cAEU;aACD;;aAGI,SAAS;;aAET;;aAEA;OAEb;cAEU;aACD;aACA;;cAGC;aACD;aACA,SAAS;aACT;;cAGC;aACD;;cAGC;aACD;aACA;aACA;;cAGC;aACD;aACA;aACA;;cAGC;aACD;aACA;cACC,cAAc;;;cAId,eACR,uBACA,2BACA;cAEQ;aACD,QAAQ;;aAER;aACA,WAAW;;cAGV;aACD;aACA,aAAa;aACb;;cAGC,gBAAgB;cAEhB;aACD;aACA;aACA,UAAU;;;cAIT,oBAAoB;aACrB,UAAU;;cAGT;aACD;aACA;;cAGC,aACR,oBACA,kBACA,oBACA,iBACA,qBACA,mBACA;cAEQ,UAAU,aAAa;;cAGvB;aACD;aACA,iBAAiB,WAAW;;cAG3B;aACD,mBAAmB;aACnB,QAAQ;aACR;;;;;;;;aAQA,iBAAiB;;aAEjB,sBAAsB;;;;;;aAMtB,yBAAyB,yBAAyB;;cAGjD;IACV,iBAAiB;IACjB;IACA,cAAc,eAAe;;cAGnB,eAAe,MACzB,OAAO,GACP,oBAAoB,uBACjB;cAEO,eAAe,yBAAyB;cAExC;cAEA;IACV,UAAU;IACV;IACA;IACA,OAAO;IACP,cAAc;IACd,QAAQ;IACR;IACA;KACC;;cAGS,QAAQ;IAClB,cAAc;IACd,WAAW,eAAe;IAC1B;IACA;IACA,WAAW;IACX,SAAS,sBAAsB,QAAQ;IACvC,uBAAuB;;IAEvB,+BAEM,MAAM,4BACH,0BAA0B,QAAQ;IAE3C,eAAe,UAAU;IACzB;IACA,YAEM,OAAO,OACP;MACE,UAAU;MACV,cAAc,UAAU,OAAO,MAAM;iBAE7B;;;;;IAMhB,aACM;MACA,UAAU;MACV,cAAc,UAAU,OAAO,MAAM;MACrC,QAAQ;;IAGd;MAEM;;;;;;MAMA;;MAEA;;IAGN;MAEM,cAAc"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AssistantTransportThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","useSyncExternalStore","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","createMessageQueue","AddToolResultOptions","AppendMessage","MessageQueueController","MessageQueueDriver","RespondToToolApprovalOptions","ResumeToolCallOptions","ThreadMessage","ToolExecutionStatus","ToolInvocationTracker","useStatewire","AssistantTransportHost","AssistantTransportHostCommands","AssistantTransportHostState","HostQueueCell","HostRunContext","SendOptions","createRunQueueAdapter","resolveReloadCommand","toWireMessage","viewedLeafId","resolveToolApprovalInput","resolveToolResultInput","AssistantTransportCommand","AssistantTransportOptions","InputRequestState","EMPTY_TOOL_STATUSES","Record","EMPTY_QUEUE_ITEMS","subscribeNoop","symbolAssistantTransportExtras","Symbol","AssistantTransportExtras","sendCommand","command","reconnect","state","inputRequests","asAssistantTransportExtras","extras","Error","messagesContainToolCall","messages","toolCallId","some","message","content","part","type","undefined","useAssistantTransportThread","options","clientRef","getRunContext","aui","current","parent","threadId","threadListItem","getState","remoteId","modelContext","getModelContext","queueCell","queued","inTransit","commands","connection","transport","agent","agentState","isSending","isReplaying","queue","dispatch","opts","send","catch","toolStatuses","setToolStatuses","converter","converted","pendingCommands","convertedRef","toolInvocations","tools","onResult","onStatusesChange","statuses","size","Object","fromEntries","setState","isRunning","isLoading","reset","inputSeam","present","handleAppend","startRun","role","crypto","randomUUID","anchorMessageId","setParentId","parentId","schedule","abort","then","handleEdit","sourceId","handleCancel","cancel","driverRef","run","at","id","queueProjection","steerProjection","steerQueue","capabilities","queueSeam","serverQueue","enableQueue","queueRef","clear","messageQueue","queueItems","subscribe","adapter","items","steerQueueItems","steerItems","busy","keys","length","wasBusyRef","notifyBusy","notifyIdle","attachmentAdapter","adapters","attachments","onNew","edit","onEdit","onReload","onCancel","onResume","continue","resumeApi","resume","onAddToolResult","toolOptions","onRespondToToolApproval","onResumeToolCall","payload","onLoadExternalState","imported","importState","AssistantTransportThread","T","hook"],"sources":["../src/AssistantTransportThread.ts"],"sourcesContent":["import {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} 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 { createMessageQueue } from \"@assistant-ui/core\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n MessageQueueController,\n MessageQueueDriver,\n RespondToToolApprovalOptions,\n ResumeToolCallOptions,\n ThreadMessage,\n ToolExecutionStatus,\n} from \"@assistant-ui/core\";\nimport { ToolInvocationTracker } from \"@assistant-ui/core/internal\";\nimport { useStatewire } from \"statewire\";\nimport { AssistantTransportHost } from \"./host\";\nimport type {\n AssistantTransportHostCommands,\n AssistantTransportHostState,\n HostQueueCell,\n HostRunContext,\n SendOptions,\n} from \"./host\";\nimport {\n createRunQueueAdapter,\n resolveReloadCommand,\n toWireMessage,\n viewedLeafId,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\nimport type {\n AssistantTransportCommand,\n AssistantTransportOptions,\n InputRequestState,\n} from \"./types\";\n\nconst EMPTY_TOOL_STATUSES: Record<string, ToolExecutionStatus> = {};\nconst EMPTY_QUEUE_ITEMS: MessageQueueController[\"adapter\"][\"items\"] = [];\nconst subscribeNoop = () => () => {};\n\nexport const symbolAssistantTransportExtras = Symbol(\n \"assistant-transport-extras\",\n);\n\nexport type AssistantTransportExtras = {\n [symbolAssistantTransportExtras]: true;\n sendCommand: (command: AssistantTransportCommand) => void;\n reconnect: () => void;\n state: unknown;\n /** The host's parked input requests; absent when the converter does not project them. */\n inputRequests?: readonly InputRequestState[];\n};\n\nexport const asAssistantTransportExtras = (\n extras: unknown,\n): AssistantTransportExtras => {\n if (\n typeof extras !== \"object\" ||\n extras == null ||\n !(symbolAssistantTransportExtras in extras)\n )\n throw new Error(\n \"This method can only be called when you are using AssistantTransportThread or StatewireThread\",\n );\n\n return extras as AssistantTransportExtras;\n};\n\nconst messagesContainToolCall = (\n messages: readonly ThreadMessage[],\n toolCallId: string,\n): boolean =>\n messages.some((message) =>\n message.content.some(\n (part) =>\n part.type === \"tool-call\" &&\n (part.toolCallId === toolCallId ||\n (part.messages !== undefined &&\n messagesContainToolCall(part.messages, toolCallId))),\n ),\n );\n\nconst useAssistantTransportThread = (\n options: AssistantTransportOptions<any>,\n): ClientOutput<\"thread\"> => {\n const clientRef = useAssistantClientRef();\n const [getRunContext] = useState(() => (): HostRunContext => {\n const aui = clientRef.current ?? clientRef.parent;\n // legacy parity: a threadListItem throw must not kill the run\n let threadId: string | null = null;\n try {\n threadId = aui.threadListItem().getState().remoteId ?? null;\n } catch {}\n return {\n modelContext: aui.modelContext().getModelContext(),\n threadId,\n };\n });\n\n const [queueCell] = useState(\n (): HostQueueCell => ({ current: { queued: [], inTransit: [] } }),\n );\n const { state, commands, connection } = useStatewire<\n AssistantTransportHostState,\n AssistantTransportHostCommands\n >({\n transport: AssistantTransportHost({ ...options, getRunContext, queueCell }),\n });\n const { agent: agentState, isSending, isReplaying } = state;\n const queue = queueCell.current;\n\n const dispatch = useCallback(\n (command: AssistantTransportCommand, opts?: SendOptions) => {\n void commands.send(command, opts).catch(() => {});\n },\n [commands],\n );\n\n const [toolStatuses, setToolStatuses] =\n useState<Record<string, ToolExecutionStatus>>(EMPTY_TOOL_STATUSES);\n\n const { converter } = options;\n const converted = useMemo(\n () =>\n converter(agentState, {\n pendingCommands: [...queue.inTransit, ...queue.queued],\n isSending,\n toolStatuses,\n }),\n [converter, agentState, queue, isSending, toolStatuses],\n );\n const convertedRef = useRef(converted);\n convertedRef.current = converted;\n\n const [toolInvocations] = useState(\n () =>\n new ToolInvocationTracker(\n () => {\n const aui = clientRef.current ?? clientRef.parent;\n return aui.modelContext().getModelContext().tools;\n },\n {\n onResult: (command) => {\n const messages = convertedRef.current\n .messages as readonly ThreadMessage[];\n if (!messagesContainToolCall(messages, command.toolCallId)) return;\n dispatch(\n resolveToolResultInput(\n convertedRef.current.inputRequests ?? [],\n command,\n ),\n );\n },\n onStatusesChange: (statuses) => {\n setToolStatuses(\n statuses.size === 0\n ? EMPTY_TOOL_STATUSES\n : Object.fromEntries(statuses),\n );\n },\n },\n ),\n );\n // dep-less by design: setState dedups identical snapshots internally\n useEffect(() => {\n toolInvocations.setState({\n messages: converted.messages as readonly ThreadMessage[],\n isRunning: converted.isRunning,\n isLoading: isReplaying,\n });\n });\n useEffect(\n () => () => {\n toolInvocations.reset();\n },\n [toolInvocations],\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: agentState,\n ...(inputRequests !== undefined && { inputRequests }),\n }),\n [dispatch, connection.reconnect, agentState, inputRequests],\n );\n\n const handleAppend = (message: AppendMessage) => {\n const startRun = message.startRun ?? message.role === \"user\";\n const command: AssistantTransportCommand = {\n type: \"run/steer\",\n message: toWireMessage(message, crypto.randomUUID()),\n anchorMessageId: viewedLeafId(convertedRef.current.messages),\n };\n void commands.setParentId(message.parentId).catch(() => {});\n\n const send = () => dispatch(command, { schedule: startRun });\n if (startRun) {\n // abort in-flight tool executions so their late results cannot race the new turn\n void toolInvocations.abort().then(send);\n } else {\n send();\n }\n };\n\n const handleEdit = (message: AppendMessage) => {\n if (message.sourceId == null)\n throw new Error(\"statewire: run/edit requires a sourceId\");\n const command: AssistantTransportCommand = {\n type: \"run/edit\",\n message: toWireMessage(message, crypto.randomUUID()),\n sourceId: message.sourceId,\n };\n void toolInvocations.abort().then(() => dispatch(command));\n };\n\n const handleCancel = () => {\n void toolInvocations.abort();\n void commands.cancel().catch(() => {});\n };\n\n const driverRef = useRef<{\n run: MessageQueueDriver[\"run\"];\n cancel: () => void;\n }>(undefined as never);\n driverRef.current = {\n // the queued message was stamped with the head at enqueue time; restamp so\n // it appends to the thread the finished run left behind\n run: (message) =>\n handleAppend({\n ...message,\n parentId: convertedRef.current.messages.at(-1)?.id ?? null,\n }),\n cancel: handleCancel,\n };\n\n const queueProjection = converted.queue;\n const steerProjection = converted.steerQueue;\n if (steerProjection !== undefined && queueProjection === undefined)\n throw new Error(\n \"statewire: the converter's steerQueue projection requires the queue projection\",\n );\n if (queueProjection !== undefined && options.capabilities?.queue)\n throw new Error(\n \"statewire: the converter's queue projection excludes capabilities.queue\",\n );\n const [queueSeam] = useState(() => ({\n present: queueProjection !== undefined,\n }));\n if (queueSeam.present !== (queueProjection !== 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 const serverQueue = useMemo(\n () =>\n queueProjection\n ? createRunQueueAdapter(\n converted.messages,\n queueProjection,\n steerProjection,\n dispatch,\n )\n : undefined,\n [converted.messages, queueProjection, steerProjection, dispatch],\n );\n\n const enableQueue = options.capabilities?.queue === true;\n const queueRef = useRef<MessageQueueController | null>(null);\n if (enableQueue && !queueRef.current) {\n queueRef.current = createMessageQueue({\n run: (message, opts) => driverRef.current.run(message, opts),\n cancel: () => driverRef.current.cancel(),\n });\n } else if (!enableQueue && queueRef.current) {\n queueRef.current.clear();\n queueRef.current = null;\n }\n const messageQueue = queueRef.current;\n\n // fresh view per snapshot: the controller mutates adapter.items in place,\n // which a stable prop identity would hide from the thread resource\n const queueItems = useSyncExternalStore(\n messageQueue?.subscribe ?? subscribeNoop,\n () => messageQueue?.adapter.items ?? EMPTY_QUEUE_ITEMS,\n () => EMPTY_QUEUE_ITEMS,\n );\n const steerQueueItems = useSyncExternalStore(\n messageQueue?.subscribe ?? subscribeNoop,\n () => messageQueue?.adapter.steerItems ?? EMPTY_QUEUE_ITEMS,\n () => EMPTY_QUEUE_ITEMS,\n );\n\n // settled edge: the queue only advances once the host run loop has fully\n // released (isSending), the converted state agrees, and no client tool from\n // the finished run is still executing\n const busy =\n isSending || converted.isRunning || Object.keys(toolStatuses).length > 0;\n const wasBusyRef = useRef(false);\n useEffect(() => {\n if (wasBusyRef.current === busy) return;\n wasBusyRef.current = busy;\n if (busy) messageQueue?.notifyBusy();\n else messageQueue?.notifyIdle();\n });\n\n return useResource(\n ExternalThread({\n messages: converted.messages as readonly ExternalThreadMessage[],\n isRunning: converted.isRunning,\n isLoading: isReplaying,\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n onNew: handleAppend,\n ...(serverQueue\n ? { queue: serverQueue }\n : messageQueue && {\n queue: {\n ...messageQueue.adapter,\n items: queueItems,\n steerItems: steerQueueItems,\n },\n }),\n ...(options.capabilities?.edit && { onEdit: handleEdit }),\n onReload: (parentId: string | null) => {\n const command = resolveReloadCommand(\n convertedRef.current.messages,\n parentId,\n );\n void toolInvocations.abort().then(() => dispatch(command));\n },\n onCancel: () => {\n // user cancel drops pending lanes; a steer interrupt (driver.cancel) keeps them\n messageQueue?.clear();\n handleCancel();\n },\n onResume: () => {\n if (options.capabilities?.continue) {\n dispatch({ type: \"run/continue\" });\n return;\n }\n if (!options.resumeApi)\n throw new Error(\"Must pass resumeApi to options to resume runs\");\n void commands.resume().catch(() => {});\n },\n ...(inputRequests !== undefined && {\n onAddToolResult: (toolOptions: AddToolResultOptions) =>\n dispatch(\n resolveToolResultInput(\n convertedRef.current.inputRequests!,\n toolOptions,\n ),\n ),\n onRespondToToolApproval: (options: RespondToToolApprovalOptions) =>\n dispatch(\n resolveToolApprovalInput(\n convertedRef.current.inputRequests!,\n options,\n ),\n ),\n }),\n onResumeToolCall: ({ toolCallId, payload }: ResumeToolCallOptions) => {\n if (!toolInvocations.resume(toolCallId, payload))\n throw new Error(`Tool call ${toolCallId} is not waiting for resume.`);\n },\n onLoadExternalState: (imported: unknown) => {\n void commands.importState(imported).catch(() => {});\n // reset() aborts tools before React re-renders — gate their late results against the imported state\n convertedRef.current = options.converter(imported, {\n pendingCommands: [...queue.inTransit, ...queue.queued],\n isSending,\n toolStatuses: EMPTY_TOOL_STATUSES,\n });\n toolInvocations.reset();\n setToolStatuses(EMPTY_TOOL_STATUSES);\n },\n }),\n );\n};\n\nexport const AssistantTransportThread = <T>(\n options: AssistantTransportOptions<T>,\n): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useAssistantTransportThread)(\n options as AssistantTransportOptions<any>,\n );\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useAssistantTransportThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;;;;AAsDA,MAAMwC,sBAA2D,CAAC;AAClE,MAAME,oBAAgE,CAAA;AACtE,MAAMC,4BAA4B,CA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,WAAU,4BAA6B;EACxE;EACAiH,sBAAsBC,aAAsB;GAC1C,SAAcC,YAAYD,QAAQ,CAAC,CAAChF,YAAY,CAAC,CAAC;GAElDM,aAAa5B,UAAUJ,QAAQ6B,UAAU6E,UAAU;IACjD3E,iBAAiB,CAAC,GAAGT,MAAMR,WAAW,GAAGQ,MAAMT,MAAM;IACrDO;IACAO,cAAcpD;GAChB,CAAC;GACD0D,gBAAgBW,MAAM;GACtBhB,gBAAgBrD,mBAAmB;EACrC;CACF,CAAC,CACH;AACF;AAEA,MAAaqI,4BACX5G,YAEA3D,SAAS0D,2BAA2B,CAAC,CACnCC,OACF;AAGFtD,uBACEqD,6BACAvD,eAAesD,KAAAA,CAAkB,CAAC,CAACgH,IACrC"}
|
|
1
|
+
{"version":3,"file":"AssistantTransportThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","useSyncExternalStore","resource","useResource","ResourceElement","ExternalThread","Assistant","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","createMessageQueue","AddToolResultOptions","AppendMessage","AttachmentAdapter","LanguageModelConfig","LanguageModelV1CallSettings","MessageQueueController","MessageQueueDriver","RespondToToolApprovalOptions","ResumeToolCallOptions","ThreadMessage","ToolExecutionStatus","ReadonlyJSONValue","ToolInvocationTracker","useStatewire","AssistantTransportHost","AssistantTransportHostCommands","AssistantTransportHostState","HostQueueCell","HostRunContext","SendOptions","createRunQueueAdapter","resolveReloadCommand","toWireMessage","viewedLeafId","resolveToolApprovalInput","resolveToolResultInput","EMPTY_TOOL_STATUSES","Record","EMPTY_QUEUE_ITEMS","subscribeNoop","symbolAssistantTransportExtras","Symbol","AssistantTransportExtras","sendCommand","command","AssistantTransportThread","Command","reconnect","state","inputRequests","InputRequestState","asAssistantTransportExtras","extras","Error","messagesContainToolCall","messages","toolCallId","some","message","content","part","type","undefined","useAssistantTransportThread","options","Options","clientRef","getRunContext","aui","current","parent","threadId","threadListItem","getState","remoteId","modelContext","getModelContext","queueCell","queued","inTransit","commands","connection","transport","agent","agentState","isSending","isReplaying","queue","dispatch","opts","send","catch","toolStatuses","setToolStatuses","converter","converted","pendingCommands","convertedRef","toolInvocations","tools","onResult","onStatusesChange","statuses","size","Object","fromEntries","setState","isRunning","isLoading","reset","inputSeam","present","handleAppend","startRun","role","crypto","randomUUID","anchorMessageId","setParentId","parentId","schedule","abort","then","handleEdit","sourceId","handleCancel","cancel","driverRef","run","at","id","queueProjection","steerProjection","steerQueue","capabilities","queueSeam","serverQueue","enableQueue","queueRef","clear","messageQueue","queueItems","subscribe","adapter","items","steerQueueItems","steerItems","busy","keys","length","wasBusyRef","notifyBusy","notifyIdle","attachmentAdapter","adapters","attachments","onNew","edit","onEdit","onReload","onCancel","onResume","continue","resumeApi","resume","onAddToolResult","toolOptions","onRespondToToolApproval","onResumeToolCall","payload","onLoadExternalState","imported","importState","T","UserCommands","Commands","TextPart","text","FilePart","mediaType","url","filename","RunUserMessage","parts","metadata","RunPlacement","insertAfter","insertBefore","RunEnqueueCommand","messageId","RunSteerCommand","RunDequeueCommand","RunEditCommand","RunContinueCommand","ToolCallInputRequest","ToolApprovalInputRequest","CustomInputRequest","key","InputRequest","ToolCallInputResponse","output","isError","artifact","ToolApprovalInputResponse","decision","editedArgs","InputResponse","RunInputCommand","requestId","response","RunReloadCommand","RunCommand","RunQueueItem","State","ConnectionMetadata","StateConverter","connectionMetadata","HeadersValue","Headers","Protocol","SendCommandsRequestBody","system","callSettings","config","initialState","api","protocol","headers","Promise","body","prepareSendCommandsRequest","onResponse","Response","onFinish","onError","error","params","updateState","updater","hook"],"sources":["../src/AssistantTransportThread.ts"],"sourcesContent":["import {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport { resource, useResource } from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/react\";\nimport type { Assistant, ExternalThreadMessage } from \"@assistant-ui/react\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport { createMessageQueue } from \"@assistant-ui/core\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n AttachmentAdapter,\n LanguageModelConfig,\n LanguageModelV1CallSettings,\n MessageQueueController,\n MessageQueueDriver,\n RespondToToolApprovalOptions,\n ResumeToolCallOptions,\n ThreadMessage,\n ToolExecutionStatus,\n} from \"@assistant-ui/core\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { ToolInvocationTracker } from \"@assistant-ui/core/internal\";\nimport { useStatewire } from \"statewire\";\nimport { AssistantTransportHost } from \"./host\";\nimport type {\n AssistantTransportHostCommands,\n AssistantTransportHostState,\n HostQueueCell,\n HostRunContext,\n SendOptions,\n} from \"./host\";\nimport {\n createRunQueueAdapter,\n resolveReloadCommand,\n toWireMessage,\n viewedLeafId,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\n\nconst EMPTY_TOOL_STATUSES: Record<string, ToolExecutionStatus> = {};\nconst EMPTY_QUEUE_ITEMS: MessageQueueController[\"adapter\"][\"items\"] = [];\nconst subscribeNoop = () => () => {};\n\nexport const symbolAssistantTransportExtras = Symbol(\n \"assistant-transport-extras\",\n);\n\nexport type AssistantTransportExtras = {\n [symbolAssistantTransportExtras]: true;\n sendCommand: (command: AssistantTransportThread.Command) => void;\n reconnect: () => void;\n state: unknown;\n /** The host's parked input requests; absent when the converter does not project them. */\n inputRequests?: readonly AssistantTransportThread.InputRequestState[];\n};\n\nexport const asAssistantTransportExtras = (\n extras: unknown,\n): AssistantTransportExtras => {\n if (\n typeof extras !== \"object\" ||\n extras == null ||\n !(symbolAssistantTransportExtras in extras)\n )\n throw new Error(\n \"This method can only be called when you are using AssistantTransportThread or StatewireThread\",\n );\n\n return extras as AssistantTransportExtras;\n};\n\nconst messagesContainToolCall = (\n messages: readonly ThreadMessage[],\n toolCallId: string,\n): boolean =>\n messages.some((message) =>\n message.content.some(\n (part) =>\n part.type === \"tool-call\" &&\n (part.toolCallId === toolCallId ||\n (part.messages !== undefined &&\n messagesContainToolCall(part.messages, toolCallId))),\n ),\n );\n\nconst useAssistantTransportThread = (\n options: AssistantTransportThread.Options<any>,\n): ClientOutput<\"thread\"> => {\n const clientRef = useAssistantClientRef();\n const [getRunContext] = useState(() => (): HostRunContext => {\n const aui = clientRef.current ?? clientRef.parent;\n // legacy parity: a threadListItem throw must not kill the run\n let threadId: string | null = null;\n try {\n threadId = aui.threadListItem().getState().remoteId ?? null;\n } catch {}\n return {\n modelContext: aui.modelContext().getModelContext(),\n threadId,\n };\n });\n\n const [queueCell] = useState(\n (): HostQueueCell => ({ current: { queued: [], inTransit: [] } }),\n );\n const { state, commands, connection } = useStatewire<\n AssistantTransportHostState,\n AssistantTransportHostCommands\n >({\n transport: AssistantTransportHost({ ...options, getRunContext, queueCell }),\n });\n const { agent: agentState, isSending, isReplaying } = state;\n const queue = queueCell.current;\n\n const dispatch = useCallback(\n (command: AssistantTransportThread.Command, opts?: SendOptions) => {\n void commands.send(command, opts).catch(() => {});\n },\n [commands],\n );\n\n const [toolStatuses, setToolStatuses] =\n useState<Record<string, ToolExecutionStatus>>(EMPTY_TOOL_STATUSES);\n\n const { converter } = options;\n const converted = useMemo(\n () =>\n converter(agentState, {\n pendingCommands: [...queue.inTransit, ...queue.queued],\n isSending,\n toolStatuses,\n }),\n [converter, agentState, queue, isSending, toolStatuses],\n );\n const convertedRef = useRef(converted);\n convertedRef.current = converted;\n\n const [toolInvocations] = useState(\n () =>\n new ToolInvocationTracker(\n () => {\n const aui = clientRef.current ?? clientRef.parent;\n return aui.modelContext().getModelContext().tools;\n },\n {\n onResult: (command) => {\n const messages = convertedRef.current\n .messages as readonly ThreadMessage[];\n if (!messagesContainToolCall(messages, command.toolCallId)) return;\n dispatch(\n resolveToolResultInput(\n convertedRef.current.inputRequests ?? [],\n command,\n ),\n );\n },\n onStatusesChange: (statuses) => {\n setToolStatuses(\n statuses.size === 0\n ? EMPTY_TOOL_STATUSES\n : Object.fromEntries(statuses),\n );\n },\n },\n ),\n );\n // dep-less by design: setState dedups identical snapshots internally\n useEffect(() => {\n toolInvocations.setState({\n messages: converted.messages as readonly ThreadMessage[],\n isRunning: converted.isRunning,\n isLoading: isReplaying,\n });\n });\n useEffect(\n () => () => {\n toolInvocations.reset();\n },\n [toolInvocations],\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: agentState,\n ...(inputRequests !== undefined && { inputRequests }),\n }),\n [dispatch, connection.reconnect, agentState, inputRequests],\n );\n\n const handleAppend = (message: AppendMessage) => {\n const startRun = message.startRun ?? message.role === \"user\";\n const command: AssistantTransportThread.Command = {\n type: \"run/steer\",\n message: toWireMessage(message, crypto.randomUUID()),\n anchorMessageId: viewedLeafId(convertedRef.current.messages),\n };\n void commands.setParentId(message.parentId).catch(() => {});\n\n const send = () => dispatch(command, { schedule: startRun });\n if (startRun) {\n // abort in-flight tool executions so their late results cannot race the new turn\n void toolInvocations.abort().then(send);\n } else {\n send();\n }\n };\n\n const handleEdit = (message: AppendMessage) => {\n if (message.sourceId == null)\n throw new Error(\"statewire: run/edit requires a sourceId\");\n const command: AssistantTransportThread.Command = {\n type: \"run/edit\",\n message: toWireMessage(message, crypto.randomUUID()),\n sourceId: message.sourceId,\n };\n void toolInvocations.abort().then(() => dispatch(command));\n };\n\n const handleCancel = () => {\n void toolInvocations.abort();\n void commands.cancel().catch(() => {});\n };\n\n const driverRef = useRef<{\n run: MessageQueueDriver[\"run\"];\n cancel: () => void;\n }>(undefined as never);\n driverRef.current = {\n // the queued message was stamped with the head at enqueue time; restamp so\n // it appends to the thread the finished run left behind\n run: (message) =>\n handleAppend({\n ...message,\n parentId: convertedRef.current.messages.at(-1)?.id ?? null,\n }),\n cancel: handleCancel,\n };\n\n const queueProjection = converted.queue;\n const steerProjection = converted.steerQueue;\n if (steerProjection !== undefined && queueProjection === undefined)\n throw new Error(\n \"statewire: the converter's steerQueue projection requires the queue projection\",\n );\n if (queueProjection !== undefined && options.capabilities?.queue)\n throw new Error(\n \"statewire: the converter's queue projection excludes capabilities.queue\",\n );\n const [queueSeam] = useState(() => ({\n present: queueProjection !== undefined,\n }));\n if (queueSeam.present !== (queueProjection !== 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 const serverQueue = useMemo(\n () =>\n queueProjection\n ? createRunQueueAdapter(\n converted.messages,\n queueProjection,\n steerProjection,\n dispatch,\n )\n : undefined,\n [converted.messages, queueProjection, steerProjection, dispatch],\n );\n\n const enableQueue = options.capabilities?.queue === true;\n const queueRef = useRef<MessageQueueController | null>(null);\n if (enableQueue && !queueRef.current) {\n queueRef.current = createMessageQueue({\n run: (message, opts) => driverRef.current.run(message, opts),\n cancel: () => driverRef.current.cancel(),\n });\n } else if (!enableQueue && queueRef.current) {\n queueRef.current.clear();\n queueRef.current = null;\n }\n const messageQueue = queueRef.current;\n\n // fresh view per snapshot: the controller mutates adapter.items in place,\n // which a stable prop identity would hide from the thread resource\n const queueItems = useSyncExternalStore(\n messageQueue?.subscribe ?? subscribeNoop,\n () => messageQueue?.adapter.items ?? EMPTY_QUEUE_ITEMS,\n () => EMPTY_QUEUE_ITEMS,\n );\n const steerQueueItems = useSyncExternalStore(\n messageQueue?.subscribe ?? subscribeNoop,\n () => messageQueue?.adapter.steerItems ?? EMPTY_QUEUE_ITEMS,\n () => EMPTY_QUEUE_ITEMS,\n );\n\n // settled edge: the queue only advances once the host run loop has fully\n // released (isSending), the converted state agrees, and no client tool from\n // the finished run is still executing\n const busy =\n isSending || converted.isRunning || Object.keys(toolStatuses).length > 0;\n const wasBusyRef = useRef(false);\n useEffect(() => {\n if (wasBusyRef.current === busy) return;\n wasBusyRef.current = busy;\n if (busy) messageQueue?.notifyBusy();\n else messageQueue?.notifyIdle();\n });\n\n return useResource(\n ExternalThread({\n messages: converted.messages as readonly ExternalThreadMessage[],\n isRunning: converted.isRunning,\n isLoading: isReplaying,\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n onNew: handleAppend,\n ...(serverQueue\n ? { queue: serverQueue }\n : messageQueue && {\n queue: {\n ...messageQueue.adapter,\n items: queueItems,\n steerItems: steerQueueItems,\n },\n }),\n ...(options.capabilities?.edit && { onEdit: handleEdit }),\n onReload: (parentId: string | null) => {\n const command = resolveReloadCommand(\n convertedRef.current.messages,\n parentId,\n );\n void toolInvocations.abort().then(() => dispatch(command));\n },\n onCancel: () => {\n // user cancel drops pending lanes; a steer interrupt (driver.cancel) keeps them\n messageQueue?.clear();\n handleCancel();\n },\n onResume: () => {\n if (options.capabilities?.continue) {\n dispatch({ type: \"run/continue\" });\n return;\n }\n if (!options.resumeApi)\n throw new Error(\"Must pass resumeApi to options to resume runs\");\n void commands.resume().catch(() => {});\n },\n ...(inputRequests !== undefined && {\n onAddToolResult: (toolOptions: AddToolResultOptions) =>\n dispatch(\n resolveToolResultInput(\n convertedRef.current.inputRequests!,\n toolOptions,\n ),\n ),\n onRespondToToolApproval: (options: RespondToToolApprovalOptions) =>\n dispatch(\n resolveToolApprovalInput(\n convertedRef.current.inputRequests!,\n options,\n ),\n ),\n }),\n onResumeToolCall: ({ toolCallId, payload }: ResumeToolCallOptions) => {\n if (!toolInvocations.resume(toolCallId, payload))\n throw new Error(`Tool call ${toolCallId} is not waiting for resume.`);\n },\n onLoadExternalState: (imported: unknown) => {\n void commands.importState(imported).catch(() => {});\n // reset() aborts tools before React re-renders — gate their late results against the imported state\n convertedRef.current = options.converter(imported, {\n pendingCommands: [...queue.inTransit, ...queue.queued],\n isSending,\n toolStatuses: EMPTY_TOOL_STATUSES,\n });\n toolInvocations.reset();\n setToolStatuses(EMPTY_TOOL_STATUSES);\n },\n }),\n );\n};\n\nexport const AssistantTransportThread = <T>(\n options: AssistantTransportThread.Options<T>,\n): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useAssistantTransportThread)(\n options as AssistantTransportThread.Options<any>,\n );\n\nexport namespace AssistantTransportThread {\n type UserCommands = Assistant.Commands[keyof Assistant.Commands];\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 RunUserMessage = {\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 RunPlacement = {\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: RunUserMessage;\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 RunPlacement;\n\n export type RunSteerCommand = {\n readonly type: \"run/steer\";\n } & (\n | {\n readonly message: RunUserMessage;\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 RunPlacement;\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: RunUserMessage;\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 = RunCommand | UserCommands;\n\n /** A queued message projected out of the host state, wire shape. */\n export type RunQueueItem = {\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 server-side queue: sends become `run/enqueue`\n * / `run/steer` commands and item controls send the `run/*` queue\n * commands. Presence must be stable across conversions and excludes the\n * client-local `capabilities.queue` buffer.\n */\n readonly queue?: readonly RunQueueItem[];\n /** The host's steer lane; requires `queue`. Absent means empty. */\n readonly steerQueue?: readonly RunQueueItem[];\n /**\n * The host's parked input requests projected out of the state. Returning it\n * (even empty) routes tool results and approvals with a matching pending\n * request through `run/input`. Presence must be stable across conversions.\n */\n readonly inputRequests?: readonly AssistantTransportThread.InputRequestState[];\n };\n\n export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n toolStatuses: Record<string, ToolExecutionStatus>;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n export type HeadersValue = Record<string, string> | Headers;\n\n export type Protocol = \"data-stream\" | \"assistant-transport\";\n\n export type SendCommandsRequestBody = {\n commands: Command[];\n state: unknown;\n system: string | undefined;\n tools: Record<string, unknown> | undefined;\n callSettings: LanguageModelV1CallSettings | undefined;\n config: LanguageModelConfig | undefined;\n threadId: string | null;\n parentId?: string | null;\n [key: string]: unknown;\n };\n\n export type Options<T> = {\n initialState: T;\n converter: StateConverter<T>;\n api: string;\n resumeApi?: string | undefined;\n protocol?: Protocol | undefined;\n headers: HeadersValue | (() => Promise<HeadersValue>);\n body?: object | (() => Promise<object | undefined>) | undefined;\n /** Transform the fully assembled request body before it is sent. */\n prepareSendCommandsRequest?:\n | ((\n body: SendCommandsRequestBody,\n ) => Record<string, unknown> | Promise<Record<string, unknown>>)\n | undefined;\n onResponse?: ((response: Response) => void) | undefined;\n onFinish?: (() => void) | undefined;\n onError?:\n | ((\n error: Error,\n params: {\n commands: Command[];\n updateState: (updater: (state: T) => T) => void;\n },\n ) => void | Promise<void>)\n | undefined;\n /**\n * Called when commands are cancelled. After an error, queued commands are\n * cancelled once `onError` settles; `error` then carries the cause.\n */\n onCancel?:\n | ((params: {\n commands: Command[];\n updateState: (updater: (state: T) => T) => void;\n error?: Error;\n }) => void)\n | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n /**\n * Buffer messages sent during a run in an in-memory queue and dispatch\n * them once the run settles. Steering interrupts the active run.\n * Mutually exclusive with the converter's `queue` projection.\n */\n queue?: boolean | undefined;\n /** The host supports `run/continue` (a continue affordance on aborted runs). */\n continue?: 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 useAssistantTransportThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;;;;AAqDA,MAAM0C,sBAA2D,CAAC;AAClE,MAAME,oBAAgE,CAAA;AACtE,MAAMC,4BAA4B,CAAC;AAEnC,MAAaC,iCAAiCC,OAC5C,4BACF;AAWA,MAAaU,8BACXC,WAC6B;CAC7B,IACE,OAAOA,WAAW,YAClBA,UAAU,QACV,EAAEZ,kCAAkCY,SAEpC,MAAM,IAAIC,MACR,+FACF;CAEF,OAAOD;AACT;AAEA,MAAME,2BACJC,UACAC,eAEAD,SAASE,MAAMC,YACbA,QAAQC,QAAQF,MACbG,SACCA,KAAKC,SAAS,gBACbD,KAAKJ,eAAeA,cAClBI,KAAKL,aAAaO,KAAAA,KACjBR,wBAAwBM,KAAKL,UAAUC,UAAU,EACzD,CACF;AAEF,MAAMO,+BACJC,YAC2B;CAC3B,MAAME,YAAY3D,sBAAsB;CACxC,MAAM,CAAC4D,iBAAiBrE,qBAAqC;EAC3D,MAAMsE,MAAMF,UAAUG,WAAWH,UAAUI;EAE3C,IAAIC,WAA0B;EAC9B,IAAI;GACFA,WAAWH,IAAII,eAAe,CAAC,CAACC,SAAS,CAAC,CAACC,YAAY;EACzD,QAAQ,CAAC;EACT,OAAO;GACLC,cAAcP,IAAIO,aAAa,CAAC,CAACC,gBAAgB;GACjDL;EACF;CACF,CAAC;CAED,MAAM,CAACM,aAAa/E,gBACI,EAAEuE,SAAS;EAAES,QAAQ,CAAA;EAAIC,WAAW,CAAA;CAAG,EAAE,EACjE;CACA,MAAM,EAAE/B,OAAOgC,UAAUC,eAAe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MAAM,+CAA+C;GACjE,SAAc+G,OAAO,CAAC,CAACzE,YAAY,CAAC,CAAC;EACvC;EACA,GAAI1C,kBAAkBa,KAAAA,KAAa;GACjCuG,kBAAkBC,gBAChB9E,SACErD,uBACE8D,aAAa5B,QAAQpB,eACrBqH,WACF,CACF;GACFC,0BAA0BvG,cACxBwB,SACEtD,yBACE+D,aAAa5B,QAAQpB,eACrBe,SACF,CACF;EACJ;EACAwG,mBAAmB,EAAEhH,YAAYiH,cAAqC;GACpE,IAAI,CAACvE,gBAAgBkE,OAAO5G,YAAYiH,OAAO,GAC7C,MAAM,IAAIpH,MAAM,aAAaG,WAAU,4BAA6B;EACxE;EACAkH,sBAAsBC,aAAsB;GAC1C,SAAcC,YAAYD,QAAQ,CAAC,CAAChF,YAAY,CAAC,CAAC;GAElDM,aAAa5B,UAAUL,QAAQ8B,UAAU6E,UAAU;IACjD3E,iBAAiB,CAAC,GAAGT,MAAMR,WAAW,GAAGQ,MAAMT,MAAM;IACrDO;IACAO,cAAcxD;GAChB,CAAC;GACD8D,gBAAgBW,MAAM;GACtBhB,gBAAgBzD,mBAAmB;EACrC;CACF,CAAC,CACH;AACF;AAEA,MAAaS,4BACXmB,YAEAhE,SAAS+D,2BAA2B,CAAC,CACnCC,OACF;AAwPF1D,uBACEyD,6BACA5D,eAAe2D,KAAAA,CAAkB,CAAC,CAACiL,IACrC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { AssistantTransportThread } from "./AssistantTransportThread.js";
|
|
2
2
|
import { ResourceElement } from "@assistant-ui/tap";
|
|
3
3
|
import { ClientOutput } from "@assistant-ui/store";
|
|
4
4
|
import { AttachmentAdapter, ThreadMessage } from "@assistant-ui/core";
|
|
@@ -102,7 +102,7 @@ declare namespace StatewireThread {
|
|
|
102
102
|
readonly sourceId: string;
|
|
103
103
|
};
|
|
104
104
|
type RunCommand = RunEnqueueCommand | RunSteerCommand | RunDequeueCommand | RunEditCommand | RunContinueCommand | RunReloadCommand | RunInputCommand;
|
|
105
|
-
type Command =
|
|
105
|
+
type Command = AssistantTransportThread.Command | RunCommand;
|
|
106
106
|
/** A queued message projected out of the host state, wire shape. */
|
|
107
107
|
type QueueItem = {
|
|
108
108
|
readonly id: string;
|
|
@@ -163,6 +163,10 @@ declare namespace StatewireThread {
|
|
|
163
163
|
* runs for commands it declined.
|
|
164
164
|
*/
|
|
165
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;
|
|
166
170
|
onError?: ((error: Error) => void) | undefined;
|
|
167
171
|
capabilities?: {
|
|
168
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":";;;;;;;cA+Ra,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,yBAAyB,UAAU;;OAG7C;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 };\n\n export type RunCommand =\n | RunEnqueueCommand\n | RunSteerCommand\n | RunDequeueCommand\n | RunEditCommand\n | RunContinueCommand\n | RunReloadCommand\n | RunInputCommand;\n\n export type Command = AssistantTransportCommand | RunCommand;\n\n /** A queued message projected out of the host state, wire shape. */\n export type QueueItem = {\n readonly id: string;\n readonly parts: readonly (TextPart | FilePart)[];\n };\n\n export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n readonly isRunning: boolean;\n /**\n * The host's regular queue lane projected out of the state. Returning it\n * (even empty) turns on the queue capability: sends become `run/enqueue`\n * / `run/steer` commands and item controls send the `run/*` queue\n * commands. Presence must be stable across conversions.\n */\n readonly queue?: readonly QueueItem[];\n /** The host's steer lane; requires `queue`. Absent means empty. */\n readonly steerQueue?: readonly QueueItem[];\n /**\n * The host's parked input requests projected out of the state. Returning\n * it (even empty) routes tool results and approvals with a matching\n * pending request through `run/input`. Presence must be stable across\n * conversions.\n */\n readonly inputRequests?: readonly InputRequestState[];\n };\n\n export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `live`. */\n connection: StatewireClient.ConnectionState;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n /**\n * Payload of the built-in `run/stop` command. `reason` is the one well-known\n * field; apps extend it with their own JSON-serializable fields.\n */\n export type StopPayload = {\n readonly reason?: string | undefined;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n export type Options<T> = {\n transport: Transport<T>;\n initialState: T;\n converter: StateConverter<T>;\n /**\n * \"command-send\" mirrors the client's ambient model context (system,\n * tools, callSettings, config) to the server over the command channel —\n * on connect and whenever it changes. Requires a remote transport.\n */\n contextSync?: \"command-send\" | undefined;\n /** Supplies the `run/stop` command's payload; omitted, stop sends no payload. */\n stopPayload?: (() => StopPayload) | undefined;\n /**\n * Offered each pending command when a remote transport's session is\n * evicted; return \"replay\" to re-enqueue it under the rotated client id.\n * A callback set on the transport options is consulted first; this one\n * runs for commands it declined.\n */\n onCommandSessionLost?:\n | ((command: StatewireClient.SessionLostCommand) => \"replay\" | void)\n | undefined;\n onError?: ((error: Error) => void) | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n /** The host supports `run/continue` (a continue affordance on aborted runs). */\n continue?: boolean | undefined;\n /** The host supports `run/reload` (regenerating an assistant message). */\n reload?: boolean | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n }\n | undefined;\n };\n}\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useStatewireThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;;;AAuCA,MAAMqC,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWC,KAAAA,KAAa,EAAED,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQG,UAAUD,KAAAA,KAAa,EACjCC,OAAOrB,kBAAkBkB,QAAQG,KAAK,EACxC;CACA,GAAIH,QAAQI,iBAAiBF,KAAAA,KAAa,EACxCE,cAAcJ,QAAQI,aACxB;CACA,GAAIJ,QAAQK,WAAWH,KAAAA,KAAa,EAAEG,QAAQL,QAAQK,OAAO;AAC/D;AAEA,MAAMC,2BACJC,WACAG,WACmC;CACnC,MAAM,CAACG,kBAAkB,GAAGC,QAAQP,UAAUT;CAI9C,IACEgB,KAAKC,SAAS,KACd,OAAOF,qBAAqB,YAC5BA,qBAAqB,MAErB,MAAM,IAAIG,MACR,iGACF;CAEF,MAAMC,iBAAiBJ,iBAAiBK;CAGxC,OAAO;EACL,GAAGX;EACHT,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cAAcG,YAAY,EACpCC,gBAAgBvC,SAAS,EAAEC,MAAM,eAAe,CAAC,EACnD;EACA,GAAItC,QAAQwE,cAAcK,UAAU,EAAEC,UAAUhB,aAAa;EAC7D,GAAIV,kBAAkBxE,KAAAA,KAAa;GACjCmG,kBAAkBC,gBAChB3C,SAASjE,uBAAuBgF,eAAe4B,WAAW,CAAC;GAC7DC,0BAA0BC,aACxB7C,SAASlE,yBAAyBiF,eAAe8B,QAAQ,CAAC;EAC9D;EACAC,gBAAgB;GACd,MAAMC,UAAUhG,OAAOC,QAAQgG,cAAc;GAC7C,IACED,YAAYxG,KAAAA,MACX,OAAOwG,YAAY,YAClBA,YAAY,QACZE,MAAMC,QAAQH,OAAO,IAEvB,MAAM,IAAI1F,MAAM,mDAAmD;GACrE,SAAc,WAAW,CACvB,GAAI0F,YAAYxG,KAAAA,IAAY,CAAA,IAAK,CAACwG,OAAO,CAC3C,CAAC,CAACnD,OAAOC,YAAiB;IACxB9C,OAAOC,QAAQ8C,UAAUD,OAAK;GAChC,CAAC;EACH;CACF,CAAC,CACH;AACF;AAEA,MAAahD,mBACXc,YAEAvD,SAASsD,kBAAkB,CAAC,CAACC,OAAuC;AAgOtElD,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","AssistantTransportThread","createRunQueueAdapter","resolveReloadCommand","toWireMessage","viewedLeafId","resolveToolApprovalInput","resolveToolResultInput","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 {\n AssistantTransportExtras,\n AssistantTransportThread,\n} from \"./AssistantTransportThread\";\nimport {\n createRunQueueAdapter,\n resolveReloadCommand,\n toWireMessage,\n viewedLeafId,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\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 = AssistantTransportThread.Command | 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":";;;;;;;;;;AAyCA,MAAMqC,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWC,KAAAA,KAAa,EAAED,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQG,UAAUD,KAAAA,KAAa,EACjCC,OAAOrB,kBAAkBkB,QAAQG,KAAK,EACxC;CACA,GAAIH,QAAQI,iBAAiBF,KAAAA,KAAa,EACxCE,cAAcJ,QAAQI,aACxB;CACA,GAAIJ,QAAQK,WAAWH,KAAAA,KAAa,EAAEG,QAAQL,QAAQK,OAAO;AAC/D;AAEA,MAAMC,2BACJC,WACAG,WACmC;CACnC,MAAM,CAACG,kBAAkB,GAAGC,QAAQP,UAAUT;CAI9C,IACEgB,KAAKC,SAAS,KACd,OAAOF,qBAAqB,YAC5BA,qBAAqB,MAErB,MAAM,IAAIG,MACR,iGACF;CAEF,MAAMC,iBAAiBJ,iBAAiBK;CAGxC,OAAO;EACL,GAAGX;EACHT,MAAM,CACJ;GACE,GAAGe;GACHK,uBACEC,YAEAF,iBAAiBE,OAAO,KACxBT,OAAOC,QAAQO,uBAAuBC,OAAO;EACjD,CAAC;CAEL;AACF;AAEA,MAAME,sBACJC,YAC2B;CAC3B,MAAMZ,SAAS7C,OAAOyD,OAAO;CAC7BZ,OAAOC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BzE,KAAAA,KAAa;GACjCoG,kBAAkBC,gBAChB3C,SAASjE,uBAAuBgF,eAAe4B,WAAW,CAAC;GAC7DC,0BAA0BC,aACxB7C,SAASlE,yBAAyBiF,eAAe8B,QAAQ,CAAC;EAC9D;EACAC,gBAAgB;GACd,MAAMC,UAAUjG,OAAOC,QAAQiG,cAAc;GAC7C,IACED,YAAYzG,KAAAA,MACX,OAAOyG,YAAY,YAClBA,YAAY,QACZE,MAAMC,QAAQH,OAAO,IAEvB,MAAM,IAAI3F,MAAM,mDAAmD;GACrE,SAAc,WAAW,CACvB,GAAI2F,YAAYzG,KAAAA,IAAY,CAAA,IAAK,CAACyG,OAAO,CAC3C,CAAC,CAACnD,OAAOC,YAAiB;IACxB/C,OAAOC,QAAQ+C,UAAUD,OAAK;GAChC,CAAC;EACH;CACF,CAAC,CACH;AACF;AAEA,MAAajD,mBACXc,YAEAvD,SAASsD,kBAAkB,CAAC,CAACC,OAAuC;AAyOtElD,uBACEiD,oBACAnD,eAAegC,KAAAA,CAAkB,CAAC,CAAC6J,IACrC"}
|
package/dist/hooks.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { AssistantTransportThread } from "./AssistantTransportThread.js";
|
|
2
|
+
import { Assistant } from "@assistant-ui/react";
|
|
2
3
|
//#region src/hooks.d.ts
|
|
3
|
-
|
|
4
|
+
type UserExternalState = keyof Assistant.ExternalState extends never ? Record<string, unknown> : Assistant.ExternalState[keyof Assistant.ExternalState];
|
|
5
|
+
declare const useAssistantTransportSendCommand: () => (command: AssistantTransportThread.Command) => void;
|
|
4
6
|
declare function useAssistantTransportState(): UserExternalState;
|
|
5
7
|
declare function useAssistantTransportState<T>(selector: (state: UserExternalState) => T): T;
|
|
6
8
|
//#endregion
|
package/dist/hooks.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hooks.d.ts","names":[],"sources":["../src/hooks.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"hooks.d.ts","names":[],"sources":["../src/hooks.ts"],"mappings":";;;KAOK,0BAA0B,UAAU,8BACrC,0BACA,UAAU,oBAAoB,UAAU;cAE/B,yCAGH,SAAS,yBAAyB;iBAM5B,8BAA8B;iBAC9B,2BAA2B,GACzC,WAAW,OAAO,sBAAsB,IACvC"}
|
package/dist/hooks.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hooks.js","names":["c","_c","useAui","useAuiState","asAssistantTransportExtras","
|
|
1
|
+
{"version":3,"file":"hooks.js","names":["c","_c","useAui","useAuiState","asAssistantTransportExtras","Assistant","AssistantTransportThread","UserExternalState","ExternalState","Record","useAssistantTransportSendCommand","$","aui","t0","command","extras","thread","getState","sendCommand","useAssistantTransportState","selector","state","T","t","s"],"sources":["../src/hooks.ts"],"sourcesContent":["\"use client\";\n\nimport { useAui, useAuiState } from \"@assistant-ui/store\";\nimport { asAssistantTransportExtras } from \"./AssistantTransportThread\";\nimport type { Assistant } from \"@assistant-ui/react\";\nimport type { AssistantTransportThread } from \"./AssistantTransportThread\";\n\ntype UserExternalState = keyof Assistant.ExternalState extends never\n ? Record<string, unknown>\n : Assistant.ExternalState[keyof Assistant.ExternalState];\n\nexport const useAssistantTransportSendCommand = () => {\n const aui = useAui();\n\n return (command: AssistantTransportThread.Command) => {\n const extras = aui.thread().getState().extras;\n asAssistantTransportExtras(extras).sendCommand(command);\n };\n};\n\nexport function useAssistantTransportState(): UserExternalState;\nexport function useAssistantTransportState<T>(\n selector: (state: UserExternalState) => T,\n): T;\nexport function useAssistantTransportState<T>(\n selector: (state: UserExternalState) => T = (t) => t as T,\n): T | UserExternalState {\n return useAuiState((s) =>\n selector(\n asAssistantTransportExtras(s.thread.extras).state as UserExternalState,\n ),\n );\n}\n"],"mappings":";;;;;AAWA,MAAaU,yCAAmC;CAAA,MAAAC,IAAAV,EAAA,CAAA;CAC9C,MAAAW,MAAYV,OAAO;CAAE,IAAAW;CAAA,IAAAF,EAAA,OAAAC,KAAA;EAEdC,MAAAC,YAAA;GACL,MAAAC,SAAeH,IAAGI,OAAQ,CAAC,CAAAC,SAAU,CAAC,CAAAF;GACtCX,2BAA2BW,MAAM,CAAC,CAAAG,YAAaJ,OAAO;EAAC;EACxDH,EAAA,KAAAC;EAAAD,EAAA,KAAAE;CAAA,OAAAA,KAAAF,EAAA;CAAA,OAHME;AAGN;AAOH,SAAgBM,2BACdC,YAA6CG,MAAMA,GAC5B;CACvB,OAAOpB,aAAaqB,MAClBJ,SACEhB,2BAA2BoB,EAAER,OAAOD,MAAM,CAAC,CAACM,KAC9C,CACF;AACF"}
|
package/dist/host.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { AssistantTransportThread } from "./AssistantTransportThread.js";
|
|
2
2
|
import { ModelContext } from "@assistant-ui/core";
|
|
3
3
|
//#region src/host.d.ts
|
|
4
4
|
type SendOptions = {
|
|
@@ -9,13 +9,13 @@ type HostRunContext = {
|
|
|
9
9
|
threadId: string | null;
|
|
10
10
|
};
|
|
11
11
|
type HostQueue = {
|
|
12
|
-
queued:
|
|
13
|
-
inTransit:
|
|
12
|
+
queued: AssistantTransportThread.Command[];
|
|
13
|
+
inTransit: AssistantTransportThread.Command[];
|
|
14
14
|
};
|
|
15
15
|
type HostQueueCell = {
|
|
16
16
|
current: HostQueue;
|
|
17
17
|
};
|
|
18
|
-
type HostOptions =
|
|
18
|
+
type HostOptions = AssistantTransportThread.Options<unknown> & {
|
|
19
19
|
getRunContext: () => HostRunContext;
|
|
20
20
|
queueCell: HostQueueCell;
|
|
21
21
|
};
|
|
@@ -26,7 +26,7 @@ type AssistantTransportHostState = {
|
|
|
26
26
|
isReplaying: boolean;
|
|
27
27
|
};
|
|
28
28
|
type AssistantTransportHostCommands = {
|
|
29
|
-
send(command:
|
|
29
|
+
send(command: AssistantTransportThread.Command, opts?: SendOptions): void;
|
|
30
30
|
setParentId(parentId: string | null): void;
|
|
31
31
|
cancel(): void;
|
|
32
32
|
resume(): void;
|
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":";;;KAsBY;EACV;;KAGU;EACV,cAAc;EACd;;KAGU;EACV,QAAQ,yBAAyB;EACjC,WAAW,yBAAyB;;KAM1B;EAAkB,SAAS;;KAE3B,cAAc,yBAAyB;EACjD,qBAAqB;EACrB,WAAW;;KAGD;EACV;EACA;EACA;EACA;;KAGU;EACV,KAAK,SAAS,yBAAyB,SAAS,OAAO;EACvD,YAAY;EACZ;EACA;EACA,YAAY;;cA0XD,oDAAsB,SAAA,UAAA,6BAAA,kCAAA,SAAA"}
|