@nexface/chat 0.1.1-alpha.8 → 0.1.1-alpha.9
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/assistant-attachments.d.ts +31 -0
- package/dist/assistant-attachments.js +158 -0
- package/dist/assistant-attachments.js.map +1 -0
- package/dist/assistant-components.d.ts +18 -0
- package/dist/assistant-components.js +36 -0
- package/dist/assistant-components.js.map +1 -0
- package/dist/assistant-runtime.d.ts +24 -0
- package/dist/assistant-runtime.js +104 -0
- package/dist/assistant-runtime.js.map +1 -0
- package/dist/attachments.d.ts +3 -1
- package/dist/attachments.js +13 -0
- package/dist/attachments.js.map +1 -1
- package/dist/client.d.ts +2 -1
- package/dist/client.js +35 -4
- package/dist/client.js.map +1 -1
- package/dist/default-chat.d.ts +2 -1
- package/dist/default-chat.js +58 -106
- package/dist/default-chat.js.map +1 -1
- package/dist/protocol-messages.js +1 -1
- package/dist/protocol-messages.js.map +1 -1
- package/dist/protocol-response.d.ts +32 -0
- package/dist/protocol-response.js +62 -0
- package/dist/protocol-response.js.map +1 -0
- package/dist/react.d.ts +4 -3
- package/dist/react.js +58 -7
- package/dist/react.js.map +1 -1
- package/dist/storage.js +4 -2
- package/dist/storage.js.map +1 -1
- package/dist/styles.css +42 -52
- package/dist/tool-result.d.ts +1 -0
- package/dist/tool-result.js +12 -0
- package/dist/tool-result.js.map +1 -0
- package/dist/types.d.ts +35 -0
- package/dist/types.js.map +1 -1
- package/package.json +15 -7
package/dist/client.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createAgent } from "@nexface/agent";
|
|
2
|
-
import { decodeAgentResponse } from "
|
|
2
|
+
import { decodeAgentResponse } from "./protocol-response.js";
|
|
3
3
|
import { getInternalToolRuntime, validateAgentToolInput } from "@nexface/tools/internal";
|
|
4
4
|
import { EventType, EventSchemas, RunAgentInputSchema, TextInputContentSchema, ImageInputContentSchema } from "@ag-ui/core";
|
|
5
5
|
import { createMessageUpdater, restoreMessages, settleApproval } from "./protocol-messages.js";
|
|
@@ -36,6 +36,8 @@ export function getClientController(client) {
|
|
|
36
36
|
class ChatClientImplementation {
|
|
37
37
|
id = id();
|
|
38
38
|
agent;
|
|
39
|
+
#options;
|
|
40
|
+
#model;
|
|
39
41
|
runtime;
|
|
40
42
|
#runHandler;
|
|
41
43
|
#messages = [];
|
|
@@ -49,6 +51,8 @@ class ChatClientImplementation {
|
|
|
49
51
|
#operation;
|
|
50
52
|
#disposed = false;
|
|
51
53
|
#state;
|
|
54
|
+
#stateBeforeLastMessage;
|
|
55
|
+
#resumeBeforeLastMessage;
|
|
52
56
|
#recoveryUnavailable = false;
|
|
53
57
|
#remoteInterruptId;
|
|
54
58
|
#cancelledResume;
|
|
@@ -60,12 +64,14 @@ class ChatClientImplementation {
|
|
|
60
64
|
#hasPageHook = (_name) => false;
|
|
61
65
|
#cancelled = false;
|
|
62
66
|
#executingBrowserCall;
|
|
63
|
-
constructor(options) {
|
|
67
|
+
constructor(options, model) {
|
|
64
68
|
if (!options?.toolRuntime || Boolean(options.agent) === Boolean(options.run))
|
|
65
69
|
throw new ClientError("INVALID_INPUT", "Provide exactly one agent config or run function and a ToolRuntime.");
|
|
70
|
+
this.#options = options;
|
|
71
|
+
this.#model = options.agent ? model ?? resolveModelConfig(options.agent.model) : undefined;
|
|
66
72
|
this.runtime = options.toolRuntime;
|
|
67
73
|
this.#runHandler = options.run;
|
|
68
|
-
this.agent = options.agent ? createAgent({ ...options.agent, model:
|
|
74
|
+
this.agent = options.agent ? createAgent({ ...options.agent, model: this.#model, toolRuntime: this.runtime }) : undefined;
|
|
69
75
|
}
|
|
70
76
|
getMessages = () => this.#messages;
|
|
71
77
|
getStatus = () => this.#status;
|
|
@@ -98,10 +104,29 @@ class ChatClientImplementation {
|
|
|
98
104
|
if (this.agent)
|
|
99
105
|
agentController(this.agent).restoreConversation(conversation);
|
|
100
106
|
}
|
|
107
|
+
recreateBefore(messageId) {
|
|
108
|
+
if (this.busy || this.#disposed)
|
|
109
|
+
throw new ClientError("CHAT_RUN_ACTIVE", "Wait for the active task to finish.");
|
|
110
|
+
const index = this.#messages.findIndex((message) => message.role === "user" && message.id === messageId);
|
|
111
|
+
if (index < 0 || this.#messages.slice(index + 1).some((message) => message.role === "user"))
|
|
112
|
+
throw new ClientError("INVALID_INPUT", "Only the last user message can be edited.");
|
|
113
|
+
const client = new ChatClientImplementation(this.#options, this.#model);
|
|
114
|
+
client.id = this.id;
|
|
115
|
+
client.setPageResolver(this.#hasPageHook);
|
|
116
|
+
client.#messages = structuredClone(this.#messages.slice(0, index));
|
|
117
|
+
client.#state = this.#stateBeforeLastMessage;
|
|
118
|
+
client.#cancelledResume = this.#resumeBeforeLastMessage;
|
|
119
|
+
if (this.agent) {
|
|
120
|
+
const retained = agentController(this.agent).conversationBefore(messageId);
|
|
121
|
+
agentController(client.agent).restoreConversation(retained.messages, retained.replay);
|
|
122
|
+
}
|
|
123
|
+
return client;
|
|
124
|
+
}
|
|
101
125
|
async switchModel(model) {
|
|
102
126
|
if (!this.agent || this.busy)
|
|
103
127
|
throw new ClientError("CHAT_MODEL_SWITCH_BLOCKED", "Model switching is unavailable.");
|
|
104
128
|
await this.agent.switchModel(model);
|
|
129
|
+
this.#model = model;
|
|
105
130
|
this.#publish();
|
|
106
131
|
}
|
|
107
132
|
#event(event) {
|
|
@@ -190,12 +215,14 @@ class ChatClientImplementation {
|
|
|
190
215
|
else {
|
|
191
216
|
this.#operation = getInternalToolRuntime(this.runtime).beginInternalOperation({ signal: controller.signal, onCancel: () => this.cancel(), taskProgress: { phase: "processing" } });
|
|
192
217
|
}
|
|
218
|
+
this.#stateBeforeLastMessage = this.#state;
|
|
219
|
+
this.#resumeBeforeLastMessage = this.#cancelledResume;
|
|
193
220
|
this.#controller = controller;
|
|
194
221
|
this.#cancelled = false;
|
|
195
222
|
this.#executingBrowserCall = undefined;
|
|
196
223
|
this.#status = "running";
|
|
197
224
|
this.#error = undefined;
|
|
198
|
-
this.#messages = [...this.#messages, { id: userId, role: "user", content: typeof content === "string" ? content : [...content], ...(userMessage ? { metadata: { nexface: { attachments: userMessage.attachments ?? [], revisionOf: userMessage.revisionOf } } } : {}) }];
|
|
225
|
+
this.#messages = [...this.#messages, { id: userId, role: "user", content: typeof content === "string" ? content : [...content], ...(userMessage ? { metadata: { nexface: { restoredParts: userMessage.parts, attachments: userMessage.attachments ?? [], revisionOf: userMessage.revisionOf } } } : {}) }];
|
|
199
226
|
const runtime = getInternalToolRuntime(this.runtime);
|
|
200
227
|
const operationId = runtime.getActivitySnapshot().operation?.id;
|
|
201
228
|
const unsubscribe = runtime.subscribeActivity(() => {
|
|
@@ -281,6 +308,10 @@ class ChatClientImplementation {
|
|
|
281
308
|
if (!tool)
|
|
282
309
|
throw new ClientError("TOOL_CONFIRMATION_INVALIDATED", "Tool Binding was removed.");
|
|
283
310
|
const approved = await this.#wait(approval, tool, signal);
|
|
311
|
+
if (signal.aborted) {
|
|
312
|
+
this.#messages = settleApproval(this.#messages, approval, "TOOL_CANCELLED", "The pending Tool confirmation was cancelled.", "interrupt_cancelled");
|
|
313
|
+
agentController(this.agent).settle(approval.id, { type: "cancel" }, this.#messages);
|
|
314
|
+
}
|
|
284
315
|
signal.throwIfAborted();
|
|
285
316
|
const response = { interruptId: interrupt.id, status: "resolved", payload: { approved } };
|
|
286
317
|
if (approval.mode === "page")
|
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAwI,MAAM,gBAAgB,CAAC;AACnL,OAAO,EAAE,mBAAmB,EAAgF,MAAM,yBAAyB,CAAC;AAE5I,OAAO,EAAE,sBAAsB,EAAE,sBAAsB,EAAE,MAAM,yBAAyB,CAAC;AACzF,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,uBAAuB,EAAgB,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AAC,CAAC;QAC3C,sDAAsD;QACtD,KAAK,MAAM,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;QAC5C,MAAM,CAAC,WAAW,EAAE,CAAC;IACvB,CAAC;AACH,CAAC","sourcesContent":["import { createAgent, type Agent, type AgentInputContent, type AgentMessage, type AgentRun, type AgentRunResult, type RunAgentInput, type AgentModelConfig } from \"@nexface/agent\";\nimport { decodeAgentResponse, type BrowserToolResult, type AgentBrowserAction, type InternalAgentRunResult } from \"@nexface/agent/internal\";\nimport type { RuntimeAgentTool, ToolOperation, ToolRuntime } from \"@nexface/tools\";\nimport { getInternalToolRuntime, validateAgentToolInput } from \"@nexface/tools/internal\";\nimport { EventType, EventSchemas, RunAgentInputSchema, TextInputContentSchema, ImageInputContentSchema, type Message } from \"@ag-ui/core\";\nimport { createMessageUpdater, restoreMessages, settleApproval, type ProtocolEvent } from \"./protocol-messages.js\";\nimport { resolveModelConfig, type NexfaceAgentConfig } from \"./config.js\";\nimport { type UIMessage } from \"./messages.js\";\n\nexport type { Message } from \"@ag-ui/core\";\nexport type { ProtocolEvent } from \"./protocol-messages.js\";\nexport type { ToolApprovalInterruptDescriptor } from \"@nexface/agent\";\nimport type { ToolApprovalInterruptDescriptor } from \"@nexface/agent\";\nexport type ChatClientStatus = \"idle\" | \"running\" | \"waiting\" | \"error\";\nexport type RunHandler = (input: RunAgentInput, options: { signal: AbortSignal }) => Promise<Response>;\nexport type ChatClientOptions = { toolRuntime: ToolRuntime } & (\n | { agent: NexfaceAgentConfig; run?: never }\n | { run: RunHandler; agent?: never }\n);\nexport interface ChatClient {\n getMessages(): readonly Message[];\n subscribeEvents(listener: (event: ProtocolEvent) => void): () => void;\n getStatus(): ChatClientStatus;\n getApproval(): ToolApprovalInterruptDescriptor | undefined;\n getError(): Error | undefined;\n /**\n * @experimental State subscriptions may change in future releases.\n * @beta\n */\n subscribe(listener: () => void): () => void;\n sendMessage(content: string | readonly AgentInputContent[]): Promise<Extract<AgentRunResult, { outcome: { type: \"success\" } }>>;\n respondToApproval(id: string, response: { approved: boolean }): Promise<void>;\n cancel(): void;\n dispose(): void;\n}\n\ninterface AgentController {\n restoreConversation(messages: readonly AgentMessage[]): void;\n settle(id: string, decision: { type: \"cancel\" } | { type: \"invalidate\"; message: string; reason: string }, receipts?: readonly Message[]): boolean;\n authorizePageResponse(response: object): void;\n setPageConfirmationResolver(resolver: (name: string) => boolean): void;\n}\nconst controllerSymbol = Symbol.for(\"@nexface/agent/chat-controller\");\nconst agentController = (agent: Agent) => (agent as Agent & { [controllerSymbol]: AgentController })[controllerSymbol];\nconst id = () => globalThis.crypto.randomUUID();\nconst abortError = () => new DOMException(\"Agent task cancelled.\", \"AbortError\");\nexport class ClientError extends Error {\n readonly type = \"chat_error\" as const;\n constructor(readonly code: string, message: string) { super(message); this.name = \"ChatError\"; }\n}\n\nclass SubscriptionError extends Error {\n constructor(readonly failure: unknown) {\n super(failure instanceof Error ? failure.message : String(failure));\n }\n}\n\nexport function createChatClient(options: ChatClientOptions): ChatClient {\n return new ChatClientImplementation(options);\n}\n\n// This controller is package-private; page confirmation remains Provider-owned.\nexport function getClientController(client: ChatClient): ChatClientImplementation {\n if (!(client instanceof ChatClientImplementation)) throw new TypeError(\"Invalid ChatClient.\");\n return client;\n}\n\nclass ChatClientImplementation implements ChatClient {\n id: string = id();\n readonly agent: Agent | undefined;\n readonly runtime: ToolRuntime;\n readonly #runHandler: RunHandler | undefined;\n #messages: Message[] = [];\n #updateMessages = createMessageUpdater();\n #eventListeners = new Set<(event: ProtocolEvent) => void>();\n #status: ChatClientStatus = \"idle\";\n #error: Error | undefined;\n #listeners = new Set<() => void>();\n #controller: AbortController | undefined;\n #activeRun: AgentRun | undefined;\n #operation: ToolOperation | undefined;\n #disposed = false;\n #state: unknown;\n #recoveryUnavailable = false;\n #remoteInterruptId: string | undefined;\n #cancelledResume: RunAgentInput[\"resume\"];\n #task: Promise<Extract<AgentRunResult, { outcome: { type: \"success\" } }>> | undefined;\n #replacement: { cancelled: boolean } | undefined;\n #approval: ToolApprovalInterruptDescriptor | undefined;\n #pending: { resolve(approved: boolean): void; reject(error: Error): void; cleanup(): void } | undefined;\n #settled = new Map<string, () => void>();\n #hasPageHook = (_name: string) => false;\n #cancelled = false;\n #executingBrowserCall: string | undefined;\n\n constructor(options: ChatClientOptions) {\n if (!options?.toolRuntime || Boolean(options.agent) === Boolean(options.run)) throw new ClientError(\"INVALID_INPUT\", \"Provide exactly one agent config or run function and a ToolRuntime.\");\n this.runtime = options.toolRuntime;\n this.#runHandler = options.run;\n this.agent = options.agent ? createAgent({ ...options.agent, model: resolveModelConfig(options.agent.model), toolRuntime: this.runtime }) : undefined;\n }\n getMessages = (): readonly Message[] => this.#messages;\n getStatus = (): ChatClientStatus => this.#status;\n getApproval = (): ToolApprovalInterruptDescriptor | undefined => this.#approval;\n getError = (): Error | undefined => this.#error;\n subscribe = (listener: () => void): (() => void) => { this.#listeners.add(listener); return () => { this.#listeners.delete(listener); }; };\n subscribeEvents = (listener: (event: ProtocolEvent) => void): (() => void) => { this.#eventListeners.add(listener); return () => { this.#eventListeners.delete(listener); }; };\n #publish(): void {\n for (const listener of this.#listeners) {\n try { listener(); }\n catch (error) { this.#listeners.delete(listener); throw new SubscriptionError(error); }\n }\n }\n get cancelling(): boolean { return Boolean(this.#controller?.signal.aborted); }\n get busy(): boolean { return Boolean(this.#controller); }\n setPageResolver(resolver: (name: string) => boolean): void {\n this.#hasPageHook = resolver;\n if (this.agent) agentController(this.agent).setPageConfirmationResolver(resolver);\n }\n restore(messages: UIMessage[], conversation: readonly AgentMessage[]): void {\n if (this.busy || this.#messages.length) throw new Error(\"Restore requires a new Client.\");\n this.#messages = restoreMessages(structuredClone(messages));\n if (this.agent) agentController(this.agent).restoreConversation(conversation);\n }\n async switchModel(model: AgentModelConfig): Promise<void> {\n if (!this.agent || this.busy) throw new ClientError(\"CHAT_MODEL_SWITCH_BLOCKED\", \"Model switching is unavailable.\");\n await this.agent.switchModel(model);\n this.#publish();\n }\n #event(event: ProtocolEvent): void {\n if (event.type === EventType.RUN_STARTED || event.type === EventType.RUN_FINISHED) event = { ...event, threadId: this.id };\n this.#messages = this.#updateMessages(this.#messages, event);\n if (event.type === EventType.TOOL_CALL_RESULT) { this.#settled.get(event.toolCallId)?.(); this.#settled.delete(event.toolCallId); }\n if (event.type === EventType.CUSTOM && event.name === \"nexface.tool-execution\" && this.#operation) {\n const value = event.value as { status: string; toolCallId: string; progressLabel?: string };\n const runtime = getInternalToolRuntime(this.runtime);\n const current = runtime.getActivitySnapshot().operation?.taskProgress;\n if (value.status === \"running\") runtime.setTaskProgress(this.#operation, { phase: \"tool\", toolCallId: value.toolCallId, ...(value.progressLabel ? { progressLabel: value.progressLabel } : {}) });\n else if (current?.phase === \"tool\" && current.toolCallId === value.toolCallId) runtime.setTaskProgress(this.#operation, { phase: \"processing\" });\n }\n this.#publish();\n for (const listener of this.#eventListeners) {\n try { listener(event); }\n catch (error) { this.#eventListeners.delete(listener); throw new SubscriptionError(error); }\n }\n }\n sendMessage = (content: string | readonly AgentInputContent[]) => this.send(content);\n async send(content: string | readonly AgentInputContent[], userMessage?: UIMessage): Promise<Extract<AgentRunResult, { outcome: { type: \"success\" } }>> {\n if (this.#disposed || this.#replacement) throw new ClientError(\"CHAT_RUN_ACTIVE\", \"The Client is disposed or already replacing a task.\");\n try {\n content = typeof content === \"string\" ? content.trim() : content.map((part) =>\n part.type === \"text\" ? TextInputContentSchema.parse(part) : ImageInputContentSchema.parse(part));\n if (!content.length) throw new Error(\"Chat message is required.\");\n } catch (error) { throw new ClientError(\"INVALID_INPUT\", error instanceof Error ? error.message : \"Invalid chat message.\"); }\n if (this.busy) {\n if (this.#status !== \"waiting\" || !this.#pending || !this.#task) throw new ClientError(\"CHAT_RUN_ACTIVE\", \"The Client is already running.\");\n const replacement = { cancelled: false };\n this.#replacement = replacement;\n try {\n let cancellationFailure: unknown;\n try { this.#cancelCurrent(); } catch (error) { cancellationFailure = error; }\n await this.#task.catch(() => undefined);\n if (cancellationFailure) throw cancellationFailure instanceof SubscriptionError ? cancellationFailure.failure : cancellationFailure;\n if (replacement.cancelled || this.#disposed) throw abortError();\n } finally { this.#replacement = undefined; }\n }\n if (this.#recoveryUnavailable) {\n this.#error = new ClientError(\"CHAT_RECOVERY_UNAVAILABLE\", \"The previous task has no complete recovery state. Start a new conversation to continue.\");\n this.#status = \"error\";\n this.#publish();\n throw this.#error;\n }\n const task = this.#send(content, userMessage);\n this.#task = task;\n const clear = () => { if (this.#task === task) this.#task = undefined; };\n void task.then(clear, clear);\n return task;\n }\n async #send(content: string | readonly AgentInputContent[], userMessage?: UIMessage): Promise<Extract<AgentRunResult, { outcome: { type: \"success\" } }>> {\n const controller = new AbortController();\n // Claim the Runtime before appending a user message.\n const userId = userMessage?.id ?? id();\n let initialRun: AgentRun | undefined;\n if (this.agent) initialRun = this.agent.run({ messages: [{ id: userId, role: \"user\", content: typeof content === \"string\" ? content : [...content] }] }, { signal: controller.signal });\n else {\n this.#operation = getInternalToolRuntime(this.runtime).beginInternalOperation({ signal: controller.signal, onCancel: () => this.cancel(), taskProgress: { phase: \"processing\" } });\n }\n this.#controller = controller;\n this.#cancelled = false;\n this.#executingBrowserCall = undefined;\n this.#status = \"running\";\n this.#error = undefined;\n this.#messages = [...this.#messages, { id: userId, role: \"user\", content: typeof content === \"string\" ? content : [...content], ...(userMessage ? { metadata: { nexface: { attachments: userMessage.attachments ?? [], revisionOf: userMessage.revisionOf } } } : {}) }];\n const runtime = getInternalToolRuntime(this.runtime);\n const operationId = runtime.getActivitySnapshot().operation?.id;\n const unsubscribe = runtime.subscribeActivity(() => {\n const operation = runtime.getActivitySnapshot().operation;\n if (operation && operation.id === operationId && operation.status === \"cancelling\" && !controller.signal.aborted) this.cancel();\n });\n let succeeded = false;\n try {\n this.#publish();\n const result = initialRun ? await this.#local(initialRun, controller.signal) : await this.#remote(controller.signal);\n controller.signal.throwIfAborted();\n succeeded = true;\n return result;\n } catch (failure) {\n unsubscribe();\n const failedRun = this.#activeRun ?? initialRun;\n if (failedRun) {\n failedRun.cancel();\n await failedRun.result.catch(() => undefined);\n }\n if (failure instanceof SubscriptionError) failure = failure.failure;\n const record = failure as { name?: unknown; message?: unknown; code?: unknown } | null;\n this.#error = failure instanceof Error ? failure : Object.assign(new Error(typeof record?.message === \"string\" ? record.message : String(failure)), { name: typeof record?.name === \"string\" ? record.name : \"Error\", ...(typeof record?.code === \"string\" ? { code: record.code } : {}) });\n const text = controller.signal.aborted ? \"任务已取消。\" : this.#error.message;\n this.#messages = [\n ...this.#messages.map((message): Message => message.metadata?.nexface?.state === \"running\" ? { ...message, metadata: { ...message.metadata, nexface: { ...message.metadata.nexface, state: \"error\" } } } : message),\n { id: id(), role: \"assistant\", content: text, metadata: { nexface: { state: \"error\" } } },\n ];\n throw this.#error;\n } finally {\n unsubscribe();\n this.#pending?.cleanup(); this.#pending = undefined; this.#approval = undefined;\n if (this.#operation) await this.#operation.end({ outcome: succeeded ? \"completed\" : controller.signal.aborted ? \"cancelled\" : \"failed\" });\n this.#operation = undefined; this.#activeRun = undefined; this.#controller = undefined;\n for (const settle of this.#settled.values()) settle(); this.#settled.clear();\n this.#status = succeeded || controller.signal.aborted ? \"idle\" : \"error\";\n this.#publish();\n }\n }\n async #consume(run: AgentRun): Promise<AgentRunResult> {\n this.#activeRun = run;\n const outcomes = await Promise.allSettled([run.result, (async () => {\n try { for await (const event of run) this.#event(event); }\n catch (error) { run.cancel(); throw error; }\n })()]);\n if (outcomes[1].status === \"rejected\") throw outcomes[1].reason;\n if (outcomes[0].status === \"rejected\") throw outcomes[0].reason;\n return outcomes[0].value;\n }\n async #local(run: AgentRun, signal: AbortSignal): Promise<Extract<AgentRunResult, { outcome: { type: \"success\" } }>> {\n for (;;) {\n const result = await this.#consume(run);\n if (result.outcome.type === \"success\") {\n if (typeof result.output !== \"string\") throw new Error(\"Missing completion output.\");\n return { ...result, outcome: result.outcome, output: result.output };\n }\n const interrupt = result.outcome.interrupts[0];\n const extension = interrupt?.metadata?.nexface;\n if (result.outcome.interrupts.length !== 1 || extension?.kind !== \"tool-approval\") throw new Error(\"Unexpected local interrupt.\");\n const approval = extension.approval as ToolApprovalInterruptDescriptor;\n const tool = this.runtime.getTools().find((item) => item.definition.name === approval.toolName);\n if (!tool) throw new ClientError(\"TOOL_CONFIRMATION_INVALIDATED\", \"Tool Binding was removed.\");\n const approved = await this.#wait(approval, tool, signal);\n signal.throwIfAborted();\n const response = { interruptId: interrupt!.id, status: \"resolved\" as const, payload: { approved } };\n if (approval.mode === \"page\") agentController(this.agent!).authorizePageResponse(response);\n run = this.agent!.run({ resume: [response] }, { signal });\n }\n }\n #wait(approval: ToolApprovalInterruptDescriptor, tool: RuntimeAgentTool, signal: AbortSignal): Promise<boolean> {\n signal.throwIfAborted();\n this.#approval = Object.freeze(approval);\n this.#status = \"waiting\";\n const waiting = new Promise<boolean>((resolve, reject) => {\n const abort = () => reject(signal.reason);\n const removed = () => this.invalidate(\"Tool Binding was removed.\");\n const cleanup = () => { signal.removeEventListener(\"abort\", abort); tool.lifecycleSignal.removeEventListener(\"abort\", removed); };\n this.#pending = { resolve, reject, cleanup };\n signal.addEventListener(\"abort\", abort, { once: true });\n tool.lifecycleSignal.addEventListener(\"abort\", removed, { once: true });\n if (tool.lifecycleSignal.aborted) removed();\n });\n this.#operation?.setWaitingForUser(true);\n this.#publish();\n return waiting;\n }\n async #respond(id: string, approved: boolean, source: \"chat\" | \"page\"): Promise<void> {\n const pending = this.#pending;\n if (!pending || this.#approval?.id !== id || this.#approval.mode !== source || typeof approved !== \"boolean\" || (source === \"page\" && !approved)) throw new ClientError(\"INVALID_INPUT\", \"Confirmation is no longer pending or has the wrong source.\");\n pending.cleanup(); this.#pending = undefined; this.#approval = undefined;\n this.#status = \"running\"; this.#operation?.setWaitingForUser(false);\n pending.resolve(approved); this.#publish();\n }\n respondToApproval = (id: string, response: { approved: boolean }): Promise<void> => this.#respond(id, response.approved, \"chat\");\n confirmPage(): Promise<void> | undefined {\n const approval = this.#approval;\n if (approval?.mode !== \"page\") return;\n const settled = new Promise<void>((resolve) => this.#settled.set(approval.toolCallId, resolve));\n void this.#respond(approval.id, true, \"page\").catch(() => { this.#settled.get(approval.toolCallId)?.(); this.#settled.delete(approval.toolCallId); });\n return settled;\n }\n invalidate(message: string): void {\n const approval = this.#approval;\n if (!approval) return;\n this.#messages = settleApproval(this.#messages, approval, \"TOOL_CONFIRMATION_INVALIDATED\", message, \"binding_changed\");\n if (this.agent) {\n agentController(this.agent).settle(approval.id, { type: \"invalidate\", message, reason: \"binding_changed\" }, this.#messages);\n }\n this.#queueRemoteCancellation();\n const pending = this.#pending;\n pending?.cleanup(); this.#pending = undefined; this.#approval = undefined;\n this.#status = \"running\"; this.#operation?.setWaitingForUser(false);\n pending?.reject(new ClientError(\"TOOL_CONFIRMATION_INVALIDATED\", message));\n this.#publish();\n }\n cancel = (): void => {\n if (this.#replacement) this.#replacement.cancelled = true;\n this.#cancelCurrent();\n };\n #queueRemoteCancellation(): void {\n if (this.#remoteInterruptId) this.#cancelledResume = [{ interruptId: this.#remoteInterruptId, status: \"cancelled\" }];\n }\n #cancelCurrent(): void {\n if (!this.#controller || this.#cancelled) return;\n this.#cancelled = true;\n if (this.#approval) {\n this.#messages = settleApproval(this.#messages, this.#approval, \"TOOL_CANCELLED\", \"The pending Tool confirmation was cancelled.\", \"interrupt_cancelled\");\n if (this.agent) agentController(this.agent).settle(this.#approval.id, { type: \"cancel\" }, this.#messages);\n this.#queueRemoteCancellation();\n }\n const pending = this.#pending;\n pending?.cleanup(); this.#pending = undefined; this.#approval = undefined;\n this.#controller.abort(abortError());\n pending?.reject(this.#controller.signal.reason);\n this.#activeRun?.cancel(); this.#publish();\n }\n dispose = (): void => { if (this.#disposed) return; this.#disposed = true; this.cancel(); this.#listeners.clear(); this.#eventListeners.clear(); };\n\n async #remote(signal: AbortSignal): Promise<Extract<AgentRunResult, { outcome: { type: \"success\" } }>> {\n let resume = this.#cancelledResume;\n let inFlight = false;\n let completedBrowserCall = false;\n try {\n for (;;) {\n signal.throwIfAborted();\n const catalog = [...this.runtime.getTools()];\n const contexts = await this.runtime.getContexts({ signal });\n const runId = id();\n const input: RunAgentInput = {\n threadId: this.id, runId, messages: this.#messages, state: this.#state ?? null,\n ...(resume ? { resume } : {}),\n tools: catalog.map(({ definition }) => ({ name: definition.name, description: definition.description, parameters: definition.inputSchema ?? { type: \"object\", properties: {} } })),\n context: contexts.map((context) => ({ description: context.description ?? context.name, value: JSON.stringify(context) })),\n forwardedProps: { nexface: { version: 2,\n toolMetadata: Object.fromEntries(catalog.map(({ definition }) => [definition.name, { ...(definition.effect ? { effect: definition.effect } : {}) }])),\n } },\n };\n RunAgentInputSchema.parse(input);\n inFlight = true;\n completedBrowserCall = false;\n this.#remoteInterruptId = undefined;\n const response = await abortable(this.#runHandler!(input, { signal }), signal);\n if (!response.ok || !response.body) throw new ClientError(\"CHAT_REQUEST_FAILED\", `Agent request failed (${response.status}).`);\n let terminal: InternalAgentRunResult | undefined;\n let terminalEvent: Extract<ProtocolEvent, { type: EventType.RUN_FINISHED }> | undefined;\n let messageSnapshot: Extract<ProtocolEvent, { type: EventType.MESSAGES_SNAPSHOT }> | undefined;\n let stateSnapshot: Extract<ProtocolEvent, { type: EventType.STATE_SNAPSHOT }> | undefined;\n let started = false;\n for await (const event of readEvents(response, signal)) {\n if (event.type === EventType.RUN_ERROR) {\n this.#event(event);\n throw new ClientError(event.code ?? \"CHAT_RUN_ERROR\", event.message);\n }\n if (event.type === EventType.RUN_STARTED || event.type === EventType.RUN_FINISHED) {\n if (event.threadId !== this.id || event.runId !== runId) throw new Error(\"Agent response identity does not match its request.\");\n }\n if (event.type === EventType.RUN_STARTED) {\n if (started) throw new Error(\"Duplicate Agent start event.\");\n started = true;\n }\n if (event.type === EventType.MESSAGES_SNAPSHOT) {\n if (messageSnapshot || stateSnapshot) throw new ClientError(\"CHAT_STREAM_INCOMPLETE\", \"Invalid recovery snapshot order.\");\n messageSnapshot = event;\n continue;\n }\n if (event.type === EventType.STATE_SNAPSHOT) {\n if (!messageSnapshot || stateSnapshot) throw new ClientError(\"CHAT_STREAM_INCOMPLETE\", \"Invalid recovery snapshot order.\");\n stateSnapshot = event;\n continue;\n }\n if (event.type === EventType.RUN_FINISHED) {\n if (!started || !event.outcome || !messageSnapshot || !stateSnapshot) throw new ClientError(\"CHAT_STREAM_INCOMPLETE\", \"Agent terminal is missing its recovery snapshots or outcome.\");\n terminal = { ...event.result, outcome: event.outcome } as InternalAgentRunResult;\n terminalEvent = event;\n break;\n }\n if (messageSnapshot) throw new ClientError(\"CHAT_STREAM_INCOMPLETE\", \"Unexpected event between recovery snapshots and terminal.\");\n this.#event(event);\n }\n if (!terminal || !terminalEvent || !messageSnapshot || !stateSnapshot) throw new ClientError(\"CHAT_STREAM_INCOMPLETE\", \"Agent stream ended without complete recovery snapshots.\");\n let decoded: ReturnType<typeof decodeAgentResponse>;\n try { decoded = decodeAgentResponse(messageSnapshot.messages, stateSnapshot.snapshot, terminalEvent); }\n catch (error) { throw new ClientError(\"CHAT_STREAM_INCOMPLETE\", error instanceof Error ? error.message : \"Invalid Agent recovery response.\"); }\n const commit = () => {\n // Only a complete terminal commits the matching messages and state.\n this.#state = structuredClone(stateSnapshot.snapshot);\n this.#cancelledResume = undefined;\n inFlight = false;\n this.#event(messageSnapshot);\n this.#event(stateSnapshot);\n this.#event(terminalEvent);\n };\n if (decoded.type === \"success\") {\n commit();\n return decoded.result;\n }\n this.#remoteInterruptId = decoded.interruptId;\n commit();\n const toolResult = await this.#browserAction(decoded.action, catalog, signal);\n completedBrowserCall = true;\n const messageId = id();\n this.#event({ type: EventType.TOOL_CALL_RESULT, messageId, role: \"tool\", toolCallId: toolResult.toolCallId, content: JSON.stringify(toolResult.error ? { error: toolResult.error } : { result: toolResult.result ?? null }) });\n resume = [{ interruptId: decoded.interruptId, status: \"resolved\", payload: { toolResultMessageId: messageId, ...(toolResult.confirmed ? { confirmed: true } : {}) } }];\n }\n } catch (error) {\n const unknown = inFlight || completedBrowserCall || this.#executingBrowserCall !== undefined;\n if (unknown) this.#recoveryUnavailable = true;\n else this.#queueRemoteCancellation();\n const lastUser = this.#messages.reduce((last, message, index) => message.role === \"user\" ? index : last, -1);\n const current = this.#messages.slice(lastUser);\n for (const [index, message] of current.entries()) if (message.role === \"assistant\" && message.toolCalls?.length) {\n const following = current.slice(index + 1);\n const nextBatch = following.findIndex((item) => item.role === \"assistant\" && Boolean(item.toolCalls?.length));\n const receipts = nextBatch < 0 ? following : following.slice(0, nextBatch);\n for (const call of message.toolCalls) {\n if (receipts.some((item) => item.role === \"tool\" && item.toolCallId === call.id)) continue;\n const unknown = inFlight || this.#executingBrowserCall === call.id;\n this.#event({ type: EventType.TOOL_CALL_RESULT, messageId: id(), role: \"tool\", toolCallId: call.id, content: JSON.stringify({ error: { code: unknown ? \"EXECUTION_OUTCOME_UNKNOWN\" : \"TOOL_CANCELLED\", message: unknown ? \"The execution outcome is unknown; this call may have executed.\" : \"Task ended before execution.\" } }) });\n }\n }\n throw error;\n }\n }\n async #browserAction(action: AgentBrowserAction, catalog: RuntimeAgentTool[], signal: AbortSignal): Promise<BrowserToolResult> {\n let confirmed = false;\n this.#executingBrowserCall = undefined;\n try {\n if (!action || typeof action.toolCallId !== \"string\" || !action.definition) throw new Error(\"Invalid browser action.\");\n const tool = catalog.find((item) => JSON.stringify(item.definition) === JSON.stringify(action.definition));\n if (!tool || !this.runtime.getTools().includes(tool)) throw new ClientError(\"TOOL_CONFIRMATION_INVALIDATED\", \"The original Tool Binding is no longer available.\");\n const errors = validateAgentToolInput(tool.definition.inputSchema, action.input);\n if (errors.length) throw new ClientError(\"INVALID_INPUT\", errors.join(\" \"));\n const confirmation = tool.confirmation;\n if (confirmation) {\n if (confirmation.mode === \"page\" && !this.#hasPageHook(tool.definition.name)) throw new ClientError(\"TOOL_CONFIRMATION_UNAVAILABLE\", \"An active usePageConfirmation Hook is required.\");\n confirmed = true;\n const approval = { ...confirmation, type: \"tool-approval\" as const, id: id(), runId: this.id, toolCallId: action.toolCallId, toolName: tool.definition.name, input: structuredClone(action.input) };\n const approved = await this.#wait(approval, tool, signal);\n if (!approved) throw new ClientError(\"TOOL_CONFIRMATION_REJECTED\", \"The user rejected this tool call.\");\n }\n signal.throwIfAborted();\n this.#executingBrowserCall = action.toolCallId;\n const result = await getInternalToolRuntime(this.runtime).executeWithProgress(tool, action.input, { signal, ...(action.progressLabel ? { progressLabel: action.progressLabel } : {}) });\n return { toolCallId: action.toolCallId, result: result ?? null, ...(confirmed ? { confirmed } : {}) };\n } catch (error) {\n if (error instanceof SubscriptionError) throw error;\n signal.throwIfAborted();\n if (error instanceof ClientError && error.code === \"TOOL_CONFIRMATION_INVALIDATED\") throw error;\n return { toolCallId: action.toolCallId, error: { code: error instanceof ClientError ? error.code : \"TOOL_ERROR\", message: error instanceof Error ? error.message : String(error) }, ...(confirmed ? { confirmed } : {}) };\n } finally {\n if (!signal.aborted) this.#executingBrowserCall = undefined;\n this.#settled.get(action.toolCallId)?.(); this.#settled.delete(action.toolCallId);\n }\n }\n}\n\nasync function abortable<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {\n signal.throwIfAborted();\n let abort!: () => void;\n try { return await Promise.race([promise, new Promise<never>((_resolve, reject) => { abort = () => reject(signal.reason); signal.addEventListener(\"abort\", abort, { once: true }); })]); }\n finally { signal.removeEventListener(\"abort\", abort); }\n}\n\nasync function* readEvents(response: Response, signal: AbortSignal): AsyncGenerator<ProtocolEvent> {\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n const abort = () => { void reader.cancel(signal.reason).catch(() => undefined); };\n signal.addEventListener(\"abort\", abort, { once: true });\n try {\n for (;;) {\n signal.throwIfAborted();\n const next = await reader.read();\n buffer = (buffer + decoder.decode(next.value, { stream: !next.done })).replace(/\\r\\n/g, \"\\n\");\n let boundary: number;\n while ((boundary = buffer.indexOf(\"\\n\\n\")) >= 0) {\n const packet = buffer.slice(0, boundary); buffer = buffer.slice(boundary + 2);\n const data = packet.split(\"\\n\").filter((line) => line.startsWith(\"data:\")).map((line) => line.slice(5).trimStart()).join(\"\\n\");\n if (data) { signal.throwIfAborted(); yield EventSchemas.parse(JSON.parse(data)); }\n }\n if (next.done) { signal.throwIfAborted(); if (buffer.trim()) throw new Error(\"Truncated SSE event.\"); return; }\n }\n } finally {\n signal.removeEventListener(\"abort\", abort);\n // Transport cleanup must not delay terminal delivery.\n void reader.cancel().catch(() => undefined);\n reader.releaseLock();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAwI,MAAM,gBAAgB,CAAC;AACnL,OAAO,EAAE,mBAAmB,EAAmD,MAAM,wBAAwB,CAAC;AAE9G,OAAO,EAAE,sBAAsB,EAAE,sBAAsB,EAAE,MAAM,yBAAyB,CAAC;AACzF,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,uBAAuB,EAAgB,MAAM,aAAa,CAAC;AAC1I,OAAO,EAAE,oBAAoB,EAAE,eAAe,EAAE,cAAc,EAAsB,MAAM,wBAAwB,CAAC;AACnH,OAAO,EAAE,kBAAkB,EAA2B,MAAM,aAAa,CAAC;AAqC1E,MAAM,gBAAgB,GAAG,MAAM,CAAC,GAAG,CAAC,gCAAgC,CAAC,CAAC;AACtE,MAAM,eAAe,GAAG,CAAC,KAAY,EAAE,EAAE,CAAE,KAAyD,CAAC,gBAAgB,CAAC,CAAC;AACvH,MAAM,EAAE,GAAG,GAAG,EAAE,CAAC,UAAU,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC;AAChD,MAAM,UAAU,GAAG,GAAG,EAAE,CAAC,IAAI,YAAY,CAAC,uBAAuB,EAAE,YAAY,CAAC,CAAC;AACjF,MAAM,OAAO,WAAY,SAAQ,KAAK;IAEf;IADZ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,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC;gBAAC,CAAC;YACpF,CAAC;YACD,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;gBAAC,MAAM,CAAC,cAAc,EAAE,CAAC;gBAAC,IAAI,MAAM,CAAC,IAAI,EAAE;oBAAE,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC,CAAC;gBAAC,OAAO;YAAC,CAAC;QACjH,CAAC;IACH,CAAC;YAAS,CAAC;QACT,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;QAC3C,sDAAsD;QACtD,KAAK,MAAM,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;QAC5C,MAAM,CAAC,WAAW,EAAE,CAAC;IACvB,CAAC;AACH,CAAC","sourcesContent":["import { createAgent, type Agent, type AgentInputContent, type AgentMessage, type AgentRun, type AgentRunResult, type RunAgentInput, type AgentModelConfig } from \"@nexface/agent\";\nimport { decodeAgentResponse, type BrowserToolResult, type AgentBrowserAction } from \"./protocol-response.js\";\nimport type { RuntimeAgentTool, ToolOperation, ToolRuntime } from \"@nexface/tools\";\nimport { getInternalToolRuntime, validateAgentToolInput } from \"@nexface/tools/internal\";\nimport { EventType, EventSchemas, RunAgentInputSchema, TextInputContentSchema, ImageInputContentSchema, type Message } from \"@ag-ui/core\";\nimport { createMessageUpdater, restoreMessages, settleApproval, type ProtocolEvent } from \"./protocol-messages.js\";\nimport { resolveModelConfig, type NexfaceAgentConfig } from \"./config.js\";\nimport { type UIMessage } from \"./messages.js\";\n\nexport type { Message } from \"@ag-ui/core\";\nexport type { ProtocolEvent } from \"./protocol-messages.js\";\nexport type { ToolApprovalInterruptDescriptor } from \"@nexface/agent\";\nimport type { ToolApprovalInterruptDescriptor } from \"@nexface/agent\";\nexport type ChatClientStatus = \"idle\" | \"running\" | \"waiting\" | \"error\";\nexport type RunHandler = (input: RunAgentInput, options: { signal: AbortSignal }) => Promise<Response>;\nexport type ChatClientOptions = { toolRuntime: ToolRuntime } & (\n | { agent: NexfaceAgentConfig; run?: never }\n | { run: RunHandler; agent?: never }\n);\nexport interface ChatClient {\n getMessages(): readonly Message[];\n subscribeEvents(listener: (event: ProtocolEvent) => void): () => void;\n getStatus(): ChatClientStatus;\n getApproval(): ToolApprovalInterruptDescriptor | undefined;\n getError(): Error | undefined;\n /**\n * @experimental State subscriptions may change in future releases.\n * @beta\n */\n subscribe(listener: () => void): () => void;\n sendMessage(content: string | readonly AgentInputContent[]): Promise<Extract<AgentRunResult, { outcome: { type: \"success\" } }>>;\n respondToApproval(id: string, response: { approved: boolean }): Promise<void>;\n cancel(): void;\n dispose(): void;\n}\n\ninterface AgentController {\n conversationBefore(messageId: string): { messages: readonly AgentMessage[]; replay?: unknown };\n restoreConversation(messages: readonly AgentMessage[], replay?: unknown): void;\n settle(id: string, decision: { type: \"cancel\" } | { type: \"invalidate\"; message: string; reason: string }, receipts?: readonly Message[]): boolean;\n authorizePageResponse(response: object): void;\n setPageConfirmationResolver(resolver: (name: string) => boolean): void;\n}\nconst controllerSymbol = Symbol.for(\"@nexface/agent/chat-controller\");\nconst agentController = (agent: Agent) => (agent as Agent & { [controllerSymbol]: AgentController })[controllerSymbol];\nconst id = () => globalThis.crypto.randomUUID();\nconst abortError = () => new DOMException(\"Agent task cancelled.\", \"AbortError\");\nexport class ClientError extends Error {\n readonly type = \"chat_error\" as const;\n constructor(readonly code: string, message: string) { super(message); this.name = \"ChatError\"; }\n}\n\nclass SubscriptionError extends Error {\n constructor(readonly failure: unknown) {\n super(failure instanceof Error ? failure.message : String(failure));\n }\n}\n\nexport function createChatClient(options: ChatClientOptions): ChatClient {\n return new ChatClientImplementation(options);\n}\n\n// This controller is package-private; page confirmation remains Provider-owned.\nexport function getClientController(client: ChatClient): ChatClientImplementation {\n if (!(client instanceof ChatClientImplementation)) throw new TypeError(\"Invalid ChatClient.\");\n return client;\n}\n\nclass ChatClientImplementation implements ChatClient {\n id: string = id();\n readonly agent: Agent | undefined;\n readonly #options: ChatClientOptions;\n #model: AgentModelConfig | undefined;\n readonly runtime: ToolRuntime;\n readonly #runHandler: RunHandler | undefined;\n #messages: Message[] = [];\n #updateMessages = createMessageUpdater();\n #eventListeners = new Set<(event: ProtocolEvent) => void>();\n #status: ChatClientStatus = \"idle\";\n #error: Error | undefined;\n #listeners = new Set<() => void>();\n #controller: AbortController | undefined;\n #activeRun: AgentRun | undefined;\n #operation: ToolOperation | undefined;\n #disposed = false;\n #state: unknown;\n #stateBeforeLastMessage: unknown;\n #resumeBeforeLastMessage: RunAgentInput[\"resume\"];\n #recoveryUnavailable = false;\n #remoteInterruptId: string | undefined;\n #cancelledResume: RunAgentInput[\"resume\"];\n #task: Promise<Extract<AgentRunResult, { outcome: { type: \"success\" } }>> | undefined;\n #replacement: { cancelled: boolean } | undefined;\n #approval: ToolApprovalInterruptDescriptor | undefined;\n #pending: { resolve(approved: boolean): void; reject(error: Error): void; cleanup(): void } | undefined;\n #settled = new Map<string, () => void>();\n #hasPageHook = (_name: string) => false;\n #cancelled = false;\n #executingBrowserCall: string | undefined;\n\n constructor(options: ChatClientOptions, model?: AgentModelConfig) {\n if (!options?.toolRuntime || Boolean(options.agent) === Boolean(options.run)) throw new ClientError(\"INVALID_INPUT\", \"Provide exactly one agent config or run function and a ToolRuntime.\");\n this.#options = options;\n this.#model = options.agent ? model ?? resolveModelConfig(options.agent.model) : undefined;\n this.runtime = options.toolRuntime;\n this.#runHandler = options.run;\n this.agent = options.agent ? createAgent({ ...options.agent, model: this.#model!, toolRuntime: this.runtime }) : undefined;\n }\n getMessages = (): readonly Message[] => this.#messages;\n getStatus = (): ChatClientStatus => this.#status;\n getApproval = (): ToolApprovalInterruptDescriptor | undefined => this.#approval;\n getError = (): Error | undefined => this.#error;\n subscribe = (listener: () => void): (() => void) => { this.#listeners.add(listener); return () => { this.#listeners.delete(listener); }; };\n subscribeEvents = (listener: (event: ProtocolEvent) => void): (() => void) => { this.#eventListeners.add(listener); return () => { this.#eventListeners.delete(listener); }; };\n #publish(): void {\n for (const listener of this.#listeners) {\n try { listener(); }\n catch (error) { this.#listeners.delete(listener); throw new SubscriptionError(error); }\n }\n }\n get cancelling(): boolean { return Boolean(this.#controller?.signal.aborted); }\n get busy(): boolean { return Boolean(this.#controller); }\n setPageResolver(resolver: (name: string) => boolean): void {\n this.#hasPageHook = resolver;\n if (this.agent) agentController(this.agent).setPageConfirmationResolver(resolver);\n }\n restore(messages: UIMessage[], conversation: readonly AgentMessage[]): void {\n if (this.busy || this.#messages.length) throw new Error(\"Restore requires a new Client.\");\n this.#messages = restoreMessages(structuredClone(messages));\n if (this.agent) agentController(this.agent).restoreConversation(conversation);\n }\n recreateBefore(messageId: string): ChatClient {\n if (this.busy || this.#disposed) throw new ClientError(\"CHAT_RUN_ACTIVE\", \"Wait for the active task to finish.\");\n const index = this.#messages.findIndex((message) => message.role === \"user\" && message.id === messageId);\n if (index < 0 || this.#messages.slice(index + 1).some((message) => message.role === \"user\")) throw new ClientError(\"INVALID_INPUT\", \"Only the last user message can be edited.\");\n const client = new ChatClientImplementation(this.#options, this.#model);\n client.id = this.id;\n client.setPageResolver(this.#hasPageHook);\n client.#messages = structuredClone(this.#messages.slice(0, index));\n client.#state = this.#stateBeforeLastMessage;\n client.#cancelledResume = this.#resumeBeforeLastMessage;\n if (this.agent) {\n const retained = agentController(this.agent).conversationBefore(messageId);\n agentController(client.agent!).restoreConversation(retained.messages, retained.replay);\n }\n return client;\n }\n async switchModel(model: AgentModelConfig): Promise<void> {\n if (!this.agent || this.busy) throw new ClientError(\"CHAT_MODEL_SWITCH_BLOCKED\", \"Model switching is unavailable.\");\n await this.agent.switchModel(model);\n this.#model = model;\n this.#publish();\n }\n #event(event: ProtocolEvent): void {\n if (event.type === EventType.RUN_STARTED || event.type === EventType.RUN_FINISHED) event = { ...event, threadId: this.id };\n this.#messages = this.#updateMessages(this.#messages, event);\n if (event.type === EventType.TOOL_CALL_RESULT) { this.#settled.get(event.toolCallId)?.(); this.#settled.delete(event.toolCallId); }\n if (event.type === EventType.CUSTOM && event.name === \"nexface.tool-execution\" && this.#operation) {\n const value = event.value as { status: string; toolCallId: string; progressLabel?: string };\n const runtime = getInternalToolRuntime(this.runtime);\n const current = runtime.getActivitySnapshot().operation?.taskProgress;\n if (value.status === \"running\") runtime.setTaskProgress(this.#operation, { phase: \"tool\", toolCallId: value.toolCallId, ...(value.progressLabel ? { progressLabel: value.progressLabel } : {}) });\n else if (current?.phase === \"tool\" && current.toolCallId === value.toolCallId) runtime.setTaskProgress(this.#operation, { phase: \"processing\" });\n }\n this.#publish();\n for (const listener of this.#eventListeners) {\n try { listener(event); }\n catch (error) { this.#eventListeners.delete(listener); throw new SubscriptionError(error); }\n }\n }\n sendMessage = (content: string | readonly AgentInputContent[]) => this.send(content);\n async send(content: string | readonly AgentInputContent[], userMessage?: UIMessage): Promise<Extract<AgentRunResult, { outcome: { type: \"success\" } }>> {\n if (this.#disposed || this.#replacement) throw new ClientError(\"CHAT_RUN_ACTIVE\", \"The Client is disposed or already replacing a task.\");\n try {\n content = typeof content === \"string\" ? content.trim() : content.map((part) =>\n part.type === \"text\" ? TextInputContentSchema.parse(part) : ImageInputContentSchema.parse(part));\n if (!content.length) throw new Error(\"Chat message is required.\");\n } catch (error) { throw new ClientError(\"INVALID_INPUT\", error instanceof Error ? error.message : \"Invalid chat message.\"); }\n if (this.busy) {\n if (this.#status !== \"waiting\" || !this.#pending || !this.#task) throw new ClientError(\"CHAT_RUN_ACTIVE\", \"The Client is already running.\");\n const replacement = { cancelled: false };\n this.#replacement = replacement;\n try {\n let cancellationFailure: unknown;\n try { this.#cancelCurrent(); } catch (error) { cancellationFailure = error; }\n await this.#task.catch(() => undefined);\n if (cancellationFailure) throw cancellationFailure instanceof SubscriptionError ? cancellationFailure.failure : cancellationFailure;\n if (replacement.cancelled || this.#disposed) throw abortError();\n } finally { this.#replacement = undefined; }\n }\n if (this.#recoveryUnavailable) {\n this.#error = new ClientError(\"CHAT_RECOVERY_UNAVAILABLE\", \"The previous task has no complete recovery state. Start a new conversation to continue.\");\n this.#status = \"error\";\n this.#publish();\n throw this.#error;\n }\n const task = this.#send(content, userMessage);\n this.#task = task;\n const clear = () => { if (this.#task === task) this.#task = undefined; };\n void task.then(clear, clear);\n return task;\n }\n async #send(content: string | readonly AgentInputContent[], userMessage?: UIMessage): Promise<Extract<AgentRunResult, { outcome: { type: \"success\" } }>> {\n const controller = new AbortController();\n // Claim the Runtime before appending a user message.\n const userId = userMessage?.id ?? id();\n let initialRun: AgentRun | undefined;\n if (this.agent) initialRun = this.agent.run({ messages: [{ id: userId, role: \"user\", content: typeof content === \"string\" ? content : [...content] }] }, { signal: controller.signal });\n else {\n this.#operation = getInternalToolRuntime(this.runtime).beginInternalOperation({ signal: controller.signal, onCancel: () => this.cancel(), taskProgress: { phase: \"processing\" } });\n }\n this.#stateBeforeLastMessage = this.#state;\n this.#resumeBeforeLastMessage = this.#cancelledResume;\n this.#controller = controller;\n this.#cancelled = false;\n this.#executingBrowserCall = undefined;\n this.#status = \"running\";\n this.#error = undefined;\n this.#messages = [...this.#messages, { id: userId, role: \"user\", content: typeof content === \"string\" ? content : [...content], ...(userMessage ? { metadata: { nexface: { restoredParts: userMessage.parts, attachments: userMessage.attachments ?? [], revisionOf: userMessage.revisionOf } } } : {}) }];\n const runtime = getInternalToolRuntime(this.runtime);\n const operationId = runtime.getActivitySnapshot().operation?.id;\n const unsubscribe = runtime.subscribeActivity(() => {\n const operation = runtime.getActivitySnapshot().operation;\n if (operation && operation.id === operationId && operation.status === \"cancelling\" && !controller.signal.aborted) this.cancel();\n });\n let succeeded = false;\n try {\n this.#publish();\n const result = initialRun ? await this.#local(initialRun, controller.signal) : await this.#remote(controller.signal);\n controller.signal.throwIfAborted();\n succeeded = true;\n return result;\n } catch (failure) {\n unsubscribe();\n const failedRun = this.#activeRun ?? initialRun;\n if (failedRun) {\n failedRun.cancel();\n await failedRun.result.catch(() => undefined);\n }\n if (failure instanceof SubscriptionError) failure = failure.failure;\n const record = failure as { name?: unknown; message?: unknown; code?: unknown } | null;\n this.#error = failure instanceof Error ? failure : Object.assign(new Error(typeof record?.message === \"string\" ? record.message : String(failure)), { name: typeof record?.name === \"string\" ? record.name : \"Error\", ...(typeof record?.code === \"string\" ? { code: record.code } : {}) });\n const text = controller.signal.aborted ? \"任务已取消。\" : this.#error.message;\n this.#messages = [\n ...this.#messages.map((message): Message => message.metadata?.nexface?.state === \"running\" ? { ...message, metadata: { ...message.metadata, nexface: { ...message.metadata.nexface, state: \"error\" } } } : message),\n { id: id(), role: \"assistant\", content: text, metadata: { nexface: { state: \"error\" } } },\n ];\n throw this.#error;\n } finally {\n unsubscribe();\n this.#pending?.cleanup(); this.#pending = undefined; this.#approval = undefined;\n if (this.#operation) await this.#operation.end({ outcome: succeeded ? \"completed\" : controller.signal.aborted ? \"cancelled\" : \"failed\" });\n this.#operation = undefined; this.#activeRun = undefined; this.#controller = undefined;\n for (const settle of this.#settled.values()) settle(); this.#settled.clear();\n this.#status = succeeded || controller.signal.aborted ? \"idle\" : \"error\";\n this.#publish();\n }\n }\n async #consume(run: AgentRun): Promise<AgentRunResult> {\n this.#activeRun = run;\n const outcomes = await Promise.allSettled([run.result, (async () => {\n try { for await (const event of run) this.#event(event); }\n catch (error) { run.cancel(); throw error; }\n })()]);\n if (outcomes[1].status === \"rejected\") throw outcomes[1].reason;\n if (outcomes[0].status === \"rejected\") throw outcomes[0].reason;\n return outcomes[0].value;\n }\n async #local(run: AgentRun, signal: AbortSignal): Promise<Extract<AgentRunResult, { outcome: { type: \"success\" } }>> {\n for (;;) {\n const result = await this.#consume(run);\n if (result.outcome.type === \"success\") {\n if (typeof result.output !== \"string\") throw new Error(\"Missing completion output.\");\n return { ...result, outcome: result.outcome, output: result.output };\n }\n const interrupt = result.outcome.interrupts[0];\n const extension = interrupt?.metadata?.nexface;\n if (result.outcome.interrupts.length !== 1 || extension?.kind !== \"tool-approval\") throw new Error(\"Unexpected local interrupt.\");\n const approval = extension.approval as ToolApprovalInterruptDescriptor;\n const tool = this.runtime.getTools().find((item) => item.definition.name === approval.toolName);\n if (!tool) throw new ClientError(\"TOOL_CONFIRMATION_INVALIDATED\", \"Tool Binding was removed.\");\n const approved = await this.#wait(approval, tool, signal);\n if (signal.aborted) {\n this.#messages = settleApproval(this.#messages, approval, \"TOOL_CANCELLED\", \"The pending Tool confirmation was cancelled.\", \"interrupt_cancelled\");\n agentController(this.agent!).settle(approval.id, { type: \"cancel\" }, this.#messages);\n }\n signal.throwIfAborted();\n const response = { interruptId: interrupt!.id, status: \"resolved\" as const, payload: { approved } };\n if (approval.mode === \"page\") agentController(this.agent!).authorizePageResponse(response);\n run = this.agent!.run({ resume: [response] }, { signal });\n }\n }\n #wait(approval: ToolApprovalInterruptDescriptor, tool: RuntimeAgentTool, signal: AbortSignal): Promise<boolean> {\n signal.throwIfAborted();\n this.#approval = Object.freeze(approval);\n this.#status = \"waiting\";\n const waiting = new Promise<boolean>((resolve, reject) => {\n const abort = () => reject(signal.reason);\n const removed = () => this.invalidate(\"Tool Binding was removed.\");\n const cleanup = () => { signal.removeEventListener(\"abort\", abort); tool.lifecycleSignal.removeEventListener(\"abort\", removed); };\n this.#pending = { resolve, reject, cleanup };\n signal.addEventListener(\"abort\", abort, { once: true });\n tool.lifecycleSignal.addEventListener(\"abort\", removed, { once: true });\n if (tool.lifecycleSignal.aborted) removed();\n });\n this.#operation?.setWaitingForUser(true);\n this.#publish();\n return waiting;\n }\n async #respond(id: string, approved: boolean, source: \"chat\" | \"page\"): Promise<void> {\n const pending = this.#pending;\n if (!pending || this.#approval?.id !== id || this.#approval.mode !== source || typeof approved !== \"boolean\" || (source === \"page\" && !approved)) throw new ClientError(\"INVALID_INPUT\", \"Confirmation is no longer pending or has the wrong source.\");\n pending.cleanup(); this.#pending = undefined; this.#approval = undefined;\n this.#status = \"running\"; this.#operation?.setWaitingForUser(false);\n pending.resolve(approved); this.#publish();\n }\n respondToApproval = (id: string, response: { approved: boolean }): Promise<void> => this.#respond(id, response.approved, \"chat\");\n confirmPage(): Promise<void> | undefined {\n const approval = this.#approval;\n if (approval?.mode !== \"page\") return;\n const settled = new Promise<void>((resolve) => this.#settled.set(approval.toolCallId, resolve));\n void this.#respond(approval.id, true, \"page\").catch(() => { this.#settled.get(approval.toolCallId)?.(); this.#settled.delete(approval.toolCallId); });\n return settled;\n }\n invalidate(message: string): void {\n const approval = this.#approval;\n if (!approval) return;\n this.#messages = settleApproval(this.#messages, approval, \"TOOL_CONFIRMATION_INVALIDATED\", message, \"binding_changed\");\n if (this.agent) {\n agentController(this.agent).settle(approval.id, { type: \"invalidate\", message, reason: \"binding_changed\" }, this.#messages);\n }\n this.#queueRemoteCancellation();\n const pending = this.#pending;\n pending?.cleanup(); this.#pending = undefined; this.#approval = undefined;\n this.#status = \"running\"; this.#operation?.setWaitingForUser(false);\n pending?.reject(new ClientError(\"TOOL_CONFIRMATION_INVALIDATED\", message));\n this.#publish();\n }\n cancel = (): void => {\n if (this.#replacement) this.#replacement.cancelled = true;\n this.#cancelCurrent();\n };\n #queueRemoteCancellation(): void {\n if (this.#remoteInterruptId) this.#cancelledResume = [{ interruptId: this.#remoteInterruptId, status: \"cancelled\" }];\n }\n #cancelCurrent(): void {\n if (!this.#controller || this.#cancelled) return;\n this.#cancelled = true;\n if (this.#approval) {\n this.#messages = settleApproval(this.#messages, this.#approval, \"TOOL_CANCELLED\", \"The pending Tool confirmation was cancelled.\", \"interrupt_cancelled\");\n if (this.agent) agentController(this.agent).settle(this.#approval.id, { type: \"cancel\" }, this.#messages);\n this.#queueRemoteCancellation();\n }\n const pending = this.#pending;\n pending?.cleanup(); this.#pending = undefined; this.#approval = undefined;\n this.#controller.abort(abortError());\n pending?.reject(this.#controller.signal.reason);\n this.#activeRun?.cancel(); this.#publish();\n }\n dispose = (): void => { if (this.#disposed) return; this.#disposed = true; this.cancel(); this.#listeners.clear(); this.#eventListeners.clear(); };\n\n async #remote(signal: AbortSignal): Promise<Extract<AgentRunResult, { outcome: { type: \"success\" } }>> {\n let resume = this.#cancelledResume;\n let inFlight = false;\n let completedBrowserCall = false;\n try {\n for (;;) {\n signal.throwIfAborted();\n const catalog = [...this.runtime.getTools()];\n const contexts = await this.runtime.getContexts({ signal });\n const runId = id();\n const input: RunAgentInput = {\n threadId: this.id, runId, messages: this.#messages, state: this.#state ?? null,\n ...(resume ? { resume } : {}),\n tools: catalog.map(({ definition }) => ({ name: definition.name, description: definition.description, parameters: definition.inputSchema ?? { type: \"object\", properties: {} } })),\n context: contexts.map((context) => ({ description: context.description ?? context.name, value: JSON.stringify(context) })),\n forwardedProps: { nexface: { version: 2,\n toolMetadata: Object.fromEntries(catalog.map(({ definition }) => [definition.name, { ...(definition.effect ? { effect: definition.effect } : {}) }])),\n } },\n };\n RunAgentInputSchema.parse(input);\n inFlight = true;\n completedBrowserCall = false;\n this.#remoteInterruptId = undefined;\n const response = await abortable(this.#runHandler!(input, { signal }), signal);\n if (!response.ok || !response.body) throw new ClientError(\"CHAT_REQUEST_FAILED\", `Agent request failed (${response.status}).`);\n let terminal: AgentRunResult | undefined;\n let terminalEvent: Extract<ProtocolEvent, { type: EventType.RUN_FINISHED }> | undefined;\n let messageSnapshot: Extract<ProtocolEvent, { type: EventType.MESSAGES_SNAPSHOT }> | undefined;\n let stateSnapshot: Extract<ProtocolEvent, { type: EventType.STATE_SNAPSHOT }> | undefined;\n let started = false;\n for await (const event of readEvents(response, signal)) {\n if (event.type === EventType.RUN_ERROR) {\n this.#event(event);\n throw new ClientError(event.code ?? \"CHAT_RUN_ERROR\", event.message);\n }\n if (event.type === EventType.RUN_STARTED || event.type === EventType.RUN_FINISHED) {\n if (event.threadId !== this.id || event.runId !== runId) throw new Error(\"Agent response identity does not match its request.\");\n }\n if (event.type === EventType.RUN_STARTED) {\n if (started) throw new Error(\"Duplicate Agent start event.\");\n started = true;\n }\n if (event.type === EventType.MESSAGES_SNAPSHOT) {\n if (messageSnapshot || stateSnapshot) throw new ClientError(\"CHAT_STREAM_INCOMPLETE\", \"Invalid recovery snapshot order.\");\n messageSnapshot = event;\n continue;\n }\n if (event.type === EventType.STATE_SNAPSHOT) {\n if (!messageSnapshot || stateSnapshot) throw new ClientError(\"CHAT_STREAM_INCOMPLETE\", \"Invalid recovery snapshot order.\");\n stateSnapshot = event;\n continue;\n }\n if (event.type === EventType.RUN_FINISHED) {\n if (!started || !event.outcome || !messageSnapshot || !stateSnapshot) throw new ClientError(\"CHAT_STREAM_INCOMPLETE\", \"Agent terminal is missing its recovery snapshots or outcome.\");\n terminal = { ...event.result, outcome: event.outcome } as AgentRunResult;\n terminalEvent = event;\n break;\n }\n if (messageSnapshot) throw new ClientError(\"CHAT_STREAM_INCOMPLETE\", \"Unexpected event between recovery snapshots and terminal.\");\n this.#event(event);\n }\n if (!terminal || !terminalEvent || !messageSnapshot || !stateSnapshot) throw new ClientError(\"CHAT_STREAM_INCOMPLETE\", \"Agent stream ended without complete recovery snapshots.\");\n let decoded: ReturnType<typeof decodeAgentResponse>;\n try { decoded = decodeAgentResponse(messageSnapshot.messages, stateSnapshot.snapshot, terminalEvent); }\n catch (error) { throw new ClientError(\"CHAT_STREAM_INCOMPLETE\", error instanceof Error ? error.message : \"Invalid Agent recovery response.\"); }\n const commit = () => {\n // Only a complete terminal commits the matching messages and state.\n this.#state = structuredClone(stateSnapshot.snapshot);\n this.#cancelledResume = undefined;\n inFlight = false;\n this.#event(messageSnapshot);\n this.#event(stateSnapshot);\n this.#event(terminalEvent);\n };\n if (decoded.type === \"success\") {\n commit();\n return decoded.result;\n }\n this.#remoteInterruptId = decoded.interruptId;\n commit();\n const toolResult = await this.#browserAction(decoded.action, catalog, signal);\n completedBrowserCall = true;\n const messageId = id();\n this.#event({ type: EventType.TOOL_CALL_RESULT, messageId, role: \"tool\", toolCallId: toolResult.toolCallId, content: JSON.stringify(toolResult.error ? { error: toolResult.error } : { result: toolResult.result ?? null }) });\n resume = [{ interruptId: decoded.interruptId, status: \"resolved\", payload: { toolResultMessageId: messageId, ...(toolResult.confirmed ? { confirmed: true } : {}) } }];\n }\n } catch (error) {\n const unknown = inFlight || completedBrowserCall || this.#executingBrowserCall !== undefined;\n if (unknown) this.#recoveryUnavailable = true;\n else this.#queueRemoteCancellation();\n const lastUser = this.#messages.reduce((last, message, index) => message.role === \"user\" ? index : last, -1);\n const current = this.#messages.slice(lastUser);\n for (const [index, message] of current.entries()) if (message.role === \"assistant\" && message.toolCalls?.length) {\n const following = current.slice(index + 1);\n const nextBatch = following.findIndex((item) => item.role === \"assistant\" && Boolean(item.toolCalls?.length));\n const receipts = nextBatch < 0 ? following : following.slice(0, nextBatch);\n for (const call of message.toolCalls) {\n if (receipts.some((item) => item.role === \"tool\" && item.toolCallId === call.id)) continue;\n const unknown = inFlight || this.#executingBrowserCall === call.id;\n this.#event({ type: EventType.TOOL_CALL_RESULT, messageId: id(), role: \"tool\", toolCallId: call.id, content: JSON.stringify({ error: { code: unknown ? \"EXECUTION_OUTCOME_UNKNOWN\" : \"TOOL_CANCELLED\", message: unknown ? \"The execution outcome is unknown; this call may have executed.\" : \"Task ended before execution.\" } }) });\n }\n }\n throw error;\n }\n }\n async #browserAction(action: AgentBrowserAction, catalog: RuntimeAgentTool[], signal: AbortSignal): Promise<BrowserToolResult> {\n let confirmed = false;\n this.#executingBrowserCall = undefined;\n try {\n if (!action || typeof action.toolCallId !== \"string\" || !action.definition) throw new Error(\"Invalid browser action.\");\n const tool = catalog.find((item) => JSON.stringify(item.definition) === JSON.stringify(action.definition));\n if (!tool || !this.runtime.getTools().includes(tool)) throw new ClientError(\"TOOL_CONFIRMATION_INVALIDATED\", \"The original Tool Binding is no longer available.\");\n const errors = validateAgentToolInput(tool.definition.inputSchema, action.input);\n if (errors.length) throw new ClientError(\"INVALID_INPUT\", errors.join(\" \"));\n const confirmation = tool.confirmation;\n if (confirmation) {\n if (confirmation.mode === \"page\" && !this.#hasPageHook(tool.definition.name)) throw new ClientError(\"TOOL_CONFIRMATION_UNAVAILABLE\", \"An active usePageConfirmation Hook is required.\");\n confirmed = true;\n const approval = { ...confirmation, type: \"tool-approval\" as const, id: id(), runId: this.id, toolCallId: action.toolCallId, toolName: tool.definition.name, input: structuredClone(action.input) };\n const approved = await this.#wait(approval, tool, signal);\n if (!approved) throw new ClientError(\"TOOL_CONFIRMATION_REJECTED\", \"The user rejected this tool call.\");\n }\n signal.throwIfAborted();\n this.#executingBrowserCall = action.toolCallId;\n const result = await getInternalToolRuntime(this.runtime).executeWithProgress(tool, action.input, { signal, ...(action.progressLabel ? { progressLabel: action.progressLabel } : {}) });\n return { toolCallId: action.toolCallId, result: result ?? null, ...(confirmed ? { confirmed } : {}) };\n } catch (error) {\n if (error instanceof SubscriptionError) throw error;\n signal.throwIfAborted();\n if (error instanceof ClientError && error.code === \"TOOL_CONFIRMATION_INVALIDATED\") throw error;\n return { toolCallId: action.toolCallId, error: { code: error instanceof ClientError ? error.code : \"TOOL_ERROR\", message: error instanceof Error ? error.message : String(error) }, ...(confirmed ? { confirmed } : {}) };\n } finally {\n if (!signal.aborted) this.#executingBrowserCall = undefined;\n this.#settled.get(action.toolCallId)?.(); this.#settled.delete(action.toolCallId);\n }\n }\n}\n\nasync function abortable<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {\n signal.throwIfAborted();\n let abort!: () => void;\n try { return await Promise.race([promise, new Promise<never>((_resolve, reject) => { abort = () => reject(signal.reason); signal.addEventListener(\"abort\", abort, { once: true }); })]); }\n finally { signal.removeEventListener(\"abort\", abort); }\n}\n\nasync function* readEvents(response: Response, signal: AbortSignal): AsyncGenerator<ProtocolEvent> {\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n const abort = () => { void reader.cancel(signal.reason).catch(() => undefined); };\n signal.addEventListener(\"abort\", abort, { once: true });\n try {\n for (;;) {\n signal.throwIfAborted();\n const next = await reader.read();\n buffer = (buffer + decoder.decode(next.value, { stream: !next.done })).replace(/\\r\\n/g, \"\\n\");\n let boundary: number;\n while ((boundary = buffer.indexOf(\"\\n\\n\")) >= 0) {\n const packet = buffer.slice(0, boundary); buffer = buffer.slice(boundary + 2);\n const data = packet.split(\"\\n\").filter((line) => line.startsWith(\"data:\")).map((line) => line.slice(5).trimStart()).join(\"\\n\");\n if (data) { signal.throwIfAborted(); yield EventSchemas.parse(JSON.parse(data)); }\n }\n if (next.done) { signal.throwIfAborted(); if (buffer.trim()) throw new Error(\"Truncated SSE event.\"); return; }\n }\n } finally {\n signal.removeEventListener(\"abort\", abort);\n // Transport cleanup must not delay terminal delivery.\n void reader.cancel().catch(() => undefined);\n reader.releaseLock();\n }\n}\n"]}
|
package/dist/default-chat.d.ts
CHANGED
|
@@ -1,2 +1,3 @@
|
|
|
1
|
+
import { type JSX } from "react";
|
|
1
2
|
import type { ChatProps } from "./types.js";
|
|
2
|
-
export declare function Chat({ title, avatar, welcomeMessage, welcomeDescription, placeholder, layout, side, className, style, suggestions, attachments, showToolDetails, onFullscreenChange, onRunResult }: ChatProps):
|
|
3
|
+
export declare function Chat({ title, avatar, welcomeMessage, welcomeDescription, open, onOpenChange, placeholder, layout, side, className, style, suggestions, attachments, showToolDetails, onFullscreenChange, onRunResult }: ChatProps): JSX.Element | null;
|