@nexface/chat 0.1.1-alpha.1 → 0.1.1-alpha.10

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.
Files changed (103) hide show
  1. package/dist/THIRD_PARTY_LICENSES.txt +44 -0
  2. package/dist/assistant-attachments.d.ts +31 -0
  3. package/dist/assistant-attachments.js +158 -0
  4. package/dist/assistant-attachments.js.map +1 -0
  5. package/dist/assistant-components.d.ts +19 -0
  6. package/dist/assistant-components.js +39 -0
  7. package/dist/assistant-components.js.map +1 -0
  8. package/dist/assistant-runtime.d.ts +24 -0
  9. package/dist/assistant-runtime.js +104 -0
  10. package/dist/assistant-runtime.js.map +1 -0
  11. package/dist/attachments.d.ts +3 -1
  12. package/dist/attachments.js +13 -0
  13. package/dist/attachments.js.map +1 -1
  14. package/dist/client.d.ts +89 -0
  15. package/dist/client.js +620 -0
  16. package/dist/client.js.map +1 -0
  17. package/dist/config.d.ts +1 -1
  18. package/dist/config.js.map +1 -1
  19. package/dist/default-chat.d.ts +2 -1
  20. package/dist/default-chat.js +85 -115
  21. package/dist/default-chat.js.map +1 -1
  22. package/dist/index.js.map +1 -1
  23. package/dist/messages.d.ts +27 -0
  24. package/dist/messages.js +121 -0
  25. package/dist/messages.js.map +1 -0
  26. package/dist/page-confirmation.d.ts +2 -1
  27. package/dist/page-confirmation.js.map +1 -1
  28. package/dist/protocol-messages.d.ts +9 -0
  29. package/dist/protocol-messages.js +249 -0
  30. package/dist/protocol-messages.js.map +1 -0
  31. package/dist/protocol-response.d.ts +32 -0
  32. package/dist/protocol-response.js +62 -0
  33. package/dist/protocol-response.js.map +1 -0
  34. package/dist/react.d.ts +29 -41
  35. package/dist/react.js +225 -662
  36. package/dist/react.js.map +1 -1
  37. package/dist/storage.d.ts +19 -0
  38. package/dist/storage.js +111 -0
  39. package/dist/storage.js.map +1 -0
  40. package/dist/styles.css +2337 -95
  41. package/dist/tool-result.d.ts +1 -0
  42. package/dist/tool-result.js +12 -0
  43. package/dist/tool-result.js.map +1 -0
  44. package/dist/types.d.ts +40 -1
  45. package/dist/types.js.map +1 -1
  46. package/dist/ui/attachment.aui.d.ts +7 -0
  47. package/dist/ui/attachment.aui.js +93 -0
  48. package/dist/ui/attachment.aui.js.map +1 -0
  49. package/dist/ui/avatar.d.ts +11 -0
  50. package/dist/ui/avatar.js +24 -0
  51. package/dist/ui/avatar.js.map +1 -0
  52. package/dist/ui/button.d.ts +13 -0
  53. package/dist/ui/button.js +38 -0
  54. package/dist/ui/button.js.map +1 -0
  55. package/dist/ui/dialog.d.ts +17 -0
  56. package/dist/ui/dialog.js +43 -0
  57. package/dist/ui/dialog.js.map +1 -0
  58. package/dist/ui/dropdown-menu.d.ts +25 -0
  59. package/dist/ui/dropdown-menu.js +60 -0
  60. package/dist/ui/dropdown-menu.js.map +1 -0
  61. package/dist/ui/input.d.ts +3 -0
  62. package/dist/ui/input.js +9 -0
  63. package/dist/ui/input.js.map +1 -0
  64. package/dist/ui/markdown-text.d.ts +7 -0
  65. package/dist/ui/markdown-text.js +73 -0
  66. package/dist/ui/markdown-text.js.map +1 -0
  67. package/dist/ui/skeleton.d.ts +2 -0
  68. package/dist/ui/skeleton.js +8 -0
  69. package/dist/ui/skeleton.js.map +1 -0
  70. package/dist/ui/surface.d.ts +4 -0
  71. package/dist/ui/surface.js +53 -0
  72. package/dist/ui/surface.js.map +1 -0
  73. package/dist/ui/thread-list.aui.d.ts +9 -0
  74. package/dist/ui/thread-list.aui.js +19 -0
  75. package/dist/ui/thread-list.aui.js.map +1 -0
  76. package/dist/ui/thread.aui.d.ts +29 -0
  77. package/dist/ui/thread.aui.js +25 -0
  78. package/dist/ui/thread.aui.js.map +1 -0
  79. package/dist/ui/tooltip-icon-button.d.ts +7 -0
  80. package/dist/ui/tooltip-icon-button.js +12 -0
  81. package/dist/ui/tooltip-icon-button.js.map +1 -0
  82. package/dist/ui/tooltip.d.ts +7 -0
  83. package/dist/ui/tooltip.js +23 -0
  84. package/dist/ui/tooltip.js.map +1 -0
  85. package/dist/ui/use-attachment-src.d.ts +1 -0
  86. package/dist/ui/use-attachment-src.js +28 -0
  87. package/dist/ui/use-attachment-src.js.map +1 -0
  88. package/dist/ui/use-copy-to-clipboard.d.ts +7 -0
  89. package/dist/ui/use-copy-to-clipboard.js +16 -0
  90. package/dist/ui/use-copy-to-clipboard.js.map +1 -0
  91. package/dist/ui/utils.d.ts +2 -0
  92. package/dist/ui/utils.js +8 -0
  93. package/dist/ui/utils.js.map +1 -0
  94. package/package.json +25 -12
  95. package/dist/operation-surface.d.ts +0 -7
  96. package/dist/operation-surface.js +0 -79
  97. package/dist/operation-surface.js.map +0 -1
  98. package/dist/operation-types.d.ts +0 -17
  99. package/dist/operation-types.js +0 -2
  100. package/dist/operation-types.js.map +0 -1
  101. package/dist/operation-view.d.ts +0 -13
  102. package/dist/operation-view.js +0 -367
  103. package/dist/operation-view.js.map +0 -1
package/dist/client.js ADDED
@@ -0,0 +1,620 @@
1
+ import { createAgent } from "@nexface/agent";
2
+ import { decodeAgentResponse } from "./protocol-response.js";
3
+ import { getInternalToolRuntime, validateAgentToolInput } from "@nexface/tools/internal";
4
+ import { EventType, EventSchemas, RunAgentInputSchema, TextInputContentSchema, ImageInputContentSchema } from "@ag-ui/core";
5
+ import { createMessageUpdater, restoreMessages, settleApproval } from "./protocol-messages.js";
6
+ import { resolveModelConfig } from "./config.js";
7
+ const controllerSymbol = Symbol.for("@nexface/agent/chat-controller");
8
+ const agentController = (agent) => agent[controllerSymbol];
9
+ const id = () => globalThis.crypto.randomUUID();
10
+ const abortError = () => new DOMException("Agent task cancelled.", "AbortError");
11
+ export class ClientError extends Error {
12
+ code;
13
+ type = "chat_error";
14
+ constructor(code, message) {
15
+ super(message);
16
+ this.code = code;
17
+ this.name = "ChatError";
18
+ }
19
+ }
20
+ class SubscriptionError extends Error {
21
+ failure;
22
+ constructor(failure) {
23
+ super(failure instanceof Error ? failure.message : String(failure));
24
+ this.failure = failure;
25
+ }
26
+ }
27
+ export function createChatClient(options) {
28
+ return new ChatClientImplementation(options);
29
+ }
30
+ // This controller is package-private; page confirmation remains Provider-owned.
31
+ export function getClientController(client) {
32
+ if (!(client instanceof ChatClientImplementation))
33
+ throw new TypeError("Invalid ChatClient.");
34
+ return client;
35
+ }
36
+ class ChatClientImplementation {
37
+ id = id();
38
+ agent;
39
+ #options;
40
+ #model;
41
+ runtime;
42
+ #runHandler;
43
+ #messages = [];
44
+ #updateMessages = createMessageUpdater();
45
+ #eventListeners = new Set();
46
+ #status = "idle";
47
+ #error;
48
+ #listeners = new Set();
49
+ #controller;
50
+ #activeRun;
51
+ #operation;
52
+ #disposed = false;
53
+ #state;
54
+ #stateBeforeLastMessage;
55
+ #resumeBeforeLastMessage;
56
+ #recoveryUnavailable = false;
57
+ #remoteInterruptId;
58
+ #cancelledResume;
59
+ #task;
60
+ #replacement;
61
+ #approval;
62
+ #pending;
63
+ #settled = new Map();
64
+ #hasPageHook = (_name) => false;
65
+ #cancelled = false;
66
+ #executingBrowserCall;
67
+ constructor(options, model) {
68
+ if (!options?.toolRuntime || Boolean(options.agent) === Boolean(options.run))
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;
72
+ this.runtime = options.toolRuntime;
73
+ this.#runHandler = options.run;
74
+ this.agent = options.agent ? createAgent({ ...options.agent, model: this.#model, toolRuntime: this.runtime }) : undefined;
75
+ }
76
+ getMessages = () => this.#messages;
77
+ getStatus = () => this.#status;
78
+ getApproval = () => this.#approval;
79
+ getError = () => this.#error;
80
+ subscribe = (listener) => { this.#listeners.add(listener); return () => { this.#listeners.delete(listener); }; };
81
+ subscribeEvents = (listener) => { this.#eventListeners.add(listener); return () => { this.#eventListeners.delete(listener); }; };
82
+ #publish() {
83
+ for (const listener of this.#listeners) {
84
+ try {
85
+ listener();
86
+ }
87
+ catch (error) {
88
+ this.#listeners.delete(listener);
89
+ throw new SubscriptionError(error);
90
+ }
91
+ }
92
+ }
93
+ get cancelling() { return Boolean(this.#controller?.signal.aborted); }
94
+ get busy() { return Boolean(this.#controller); }
95
+ setPageResolver(resolver) {
96
+ this.#hasPageHook = resolver;
97
+ if (this.agent)
98
+ agentController(this.agent).setPageConfirmationResolver(resolver);
99
+ }
100
+ restore(messages, conversation) {
101
+ if (this.busy || this.#messages.length)
102
+ throw new Error("Restore requires a new Client.");
103
+ this.#messages = restoreMessages(structuredClone(messages));
104
+ if (this.agent)
105
+ agentController(this.agent).restoreConversation(conversation);
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
+ }
125
+ async switchModel(model) {
126
+ if (!this.agent || this.busy)
127
+ throw new ClientError("CHAT_MODEL_SWITCH_BLOCKED", "Model switching is unavailable.");
128
+ await this.agent.switchModel(model);
129
+ this.#model = model;
130
+ this.#publish();
131
+ }
132
+ #event(event) {
133
+ if (event.type === EventType.RUN_STARTED || event.type === EventType.RUN_FINISHED)
134
+ event = { ...event, threadId: this.id };
135
+ this.#messages = this.#updateMessages(this.#messages, event);
136
+ if (event.type === EventType.TOOL_CALL_RESULT) {
137
+ this.#settled.get(event.toolCallId)?.();
138
+ this.#settled.delete(event.toolCallId);
139
+ }
140
+ if (event.type === EventType.CUSTOM && event.name === "nexface.tool-execution" && this.#operation) {
141
+ const value = event.value;
142
+ const runtime = getInternalToolRuntime(this.runtime);
143
+ const current = runtime.getActivitySnapshot().operation?.taskProgress;
144
+ if (value.status === "running")
145
+ runtime.setTaskProgress(this.#operation, { phase: "tool", toolCallId: value.toolCallId, ...(value.progressLabel ? { progressLabel: value.progressLabel } : {}) });
146
+ else if (current?.phase === "tool" && current.toolCallId === value.toolCallId)
147
+ runtime.setTaskProgress(this.#operation, { phase: "processing" });
148
+ }
149
+ this.#publish();
150
+ for (const listener of this.#eventListeners) {
151
+ try {
152
+ listener(event);
153
+ }
154
+ catch (error) {
155
+ this.#eventListeners.delete(listener);
156
+ throw new SubscriptionError(error);
157
+ }
158
+ }
159
+ }
160
+ sendMessage = (content) => this.send(content);
161
+ async send(content, userMessage) {
162
+ if (this.#disposed || this.#replacement)
163
+ throw new ClientError("CHAT_RUN_ACTIVE", "The Client is disposed or already replacing a task.");
164
+ try {
165
+ content = typeof content === "string" ? content.trim() : content.map((part) => part.type === "text" ? TextInputContentSchema.parse(part) : ImageInputContentSchema.parse(part));
166
+ if (!content.length)
167
+ throw new Error("Chat message is required.");
168
+ }
169
+ catch (error) {
170
+ throw new ClientError("INVALID_INPUT", error instanceof Error ? error.message : "Invalid chat message.");
171
+ }
172
+ if (this.busy) {
173
+ if (this.#status !== "waiting" || !this.#pending || !this.#task)
174
+ throw new ClientError("CHAT_RUN_ACTIVE", "The Client is already running.");
175
+ const replacement = { cancelled: false };
176
+ this.#replacement = replacement;
177
+ try {
178
+ let cancellationFailure;
179
+ try {
180
+ this.#cancelCurrent();
181
+ }
182
+ catch (error) {
183
+ cancellationFailure = error;
184
+ }
185
+ await this.#task.catch(() => undefined);
186
+ if (cancellationFailure)
187
+ throw cancellationFailure instanceof SubscriptionError ? cancellationFailure.failure : cancellationFailure;
188
+ if (replacement.cancelled || this.#disposed)
189
+ throw abortError();
190
+ }
191
+ finally {
192
+ this.#replacement = undefined;
193
+ }
194
+ }
195
+ if (this.#recoveryUnavailable) {
196
+ this.#error = new ClientError("CHAT_RECOVERY_UNAVAILABLE", "The previous task has no complete recovery state. Start a new conversation to continue.");
197
+ this.#status = "error";
198
+ this.#publish();
199
+ throw this.#error;
200
+ }
201
+ const task = this.#send(content, userMessage);
202
+ this.#task = task;
203
+ const clear = () => { if (this.#task === task)
204
+ this.#task = undefined; };
205
+ void task.then(clear, clear);
206
+ return task;
207
+ }
208
+ async #send(content, userMessage) {
209
+ const controller = new AbortController();
210
+ // Claim the Runtime before appending a user message.
211
+ const userId = userMessage?.id ?? id();
212
+ let initialRun;
213
+ if (this.agent)
214
+ initialRun = this.agent.run({ messages: [{ id: userId, role: "user", content: typeof content === "string" ? content : [...content] }] }, { signal: controller.signal });
215
+ else {
216
+ this.#operation = getInternalToolRuntime(this.runtime).beginInternalOperation({ signal: controller.signal, onCancel: () => this.cancel(), taskProgress: { phase: "processing" } });
217
+ }
218
+ this.#stateBeforeLastMessage = this.#state;
219
+ this.#resumeBeforeLastMessage = this.#cancelledResume;
220
+ this.#controller = controller;
221
+ this.#cancelled = false;
222
+ this.#executingBrowserCall = undefined;
223
+ this.#status = "running";
224
+ this.#error = undefined;
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 } } } : {}) }];
226
+ const runtime = getInternalToolRuntime(this.runtime);
227
+ const operationId = runtime.getActivitySnapshot().operation?.id;
228
+ const unsubscribe = runtime.subscribeActivity(() => {
229
+ const operation = runtime.getActivitySnapshot().operation;
230
+ if (operation && operation.id === operationId && operation.status === "cancelling" && !controller.signal.aborted)
231
+ this.cancel();
232
+ });
233
+ let succeeded = false;
234
+ try {
235
+ this.#publish();
236
+ const result = initialRun ? await this.#local(initialRun, controller.signal) : await this.#remote(controller.signal);
237
+ controller.signal.throwIfAborted();
238
+ succeeded = true;
239
+ return result;
240
+ }
241
+ catch (failure) {
242
+ unsubscribe();
243
+ const failedRun = this.#activeRun ?? initialRun;
244
+ if (failedRun) {
245
+ failedRun.cancel();
246
+ await failedRun.result.catch(() => undefined);
247
+ }
248
+ if (failure instanceof SubscriptionError)
249
+ failure = failure.failure;
250
+ const record = failure;
251
+ 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 } : {}) });
252
+ const text = controller.signal.aborted ? "任务已取消。" : this.#error.message;
253
+ this.#messages = [
254
+ ...this.#messages.map((message) => message.metadata?.nexface?.state === "running" ? { ...message, metadata: { ...message.metadata, nexface: { ...message.metadata.nexface, state: "error" } } } : message),
255
+ { id: id(), role: "assistant", content: text, metadata: { nexface: { state: "error" } } },
256
+ ];
257
+ throw this.#error;
258
+ }
259
+ finally {
260
+ unsubscribe();
261
+ this.#pending?.cleanup();
262
+ this.#pending = undefined;
263
+ this.#approval = undefined;
264
+ if (this.#operation)
265
+ await this.#operation.end({ outcome: succeeded ? "completed" : controller.signal.aborted ? "cancelled" : "failed" });
266
+ this.#operation = undefined;
267
+ this.#activeRun = undefined;
268
+ this.#controller = undefined;
269
+ for (const settle of this.#settled.values())
270
+ settle();
271
+ this.#settled.clear();
272
+ this.#status = succeeded || controller.signal.aborted ? "idle" : "error";
273
+ this.#publish();
274
+ }
275
+ }
276
+ async #consume(run) {
277
+ this.#activeRun = run;
278
+ const outcomes = await Promise.allSettled([run.result, (async () => {
279
+ try {
280
+ for await (const event of run)
281
+ this.#event(event);
282
+ }
283
+ catch (error) {
284
+ run.cancel();
285
+ throw error;
286
+ }
287
+ })()]);
288
+ if (outcomes[1].status === "rejected")
289
+ throw outcomes[1].reason;
290
+ if (outcomes[0].status === "rejected")
291
+ throw outcomes[0].reason;
292
+ return outcomes[0].value;
293
+ }
294
+ async #local(run, signal) {
295
+ for (;;) {
296
+ const result = await this.#consume(run);
297
+ if (result.outcome.type === "success") {
298
+ if (typeof result.output !== "string")
299
+ throw new Error("Missing completion output.");
300
+ return { ...result, outcome: result.outcome, output: result.output };
301
+ }
302
+ const interrupt = result.outcome.interrupts[0];
303
+ const extension = interrupt?.metadata?.nexface;
304
+ if (result.outcome.interrupts.length !== 1 || extension?.kind !== "tool-approval")
305
+ throw new Error("Unexpected local interrupt.");
306
+ const approval = extension.approval;
307
+ const tool = this.runtime.getTools().find((item) => item.definition.name === approval.toolName);
308
+ if (!tool)
309
+ throw new ClientError("TOOL_CONFIRMATION_INVALIDATED", "Tool Binding was removed.");
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
+ }
315
+ signal.throwIfAborted();
316
+ const response = { interruptId: interrupt.id, status: "resolved", payload: { approved } };
317
+ if (approval.mode === "page")
318
+ agentController(this.agent).authorizePageResponse(response);
319
+ run = this.agent.run({ resume: [response] }, { signal });
320
+ }
321
+ }
322
+ #wait(approval, tool, signal) {
323
+ signal.throwIfAborted();
324
+ this.#approval = Object.freeze(approval);
325
+ this.#status = "waiting";
326
+ const waiting = new Promise((resolve, reject) => {
327
+ const abort = () => reject(signal.reason);
328
+ const removed = () => this.invalidate("Tool Binding was removed.");
329
+ const cleanup = () => { signal.removeEventListener("abort", abort); tool.lifecycleSignal.removeEventListener("abort", removed); };
330
+ this.#pending = { resolve, reject, cleanup };
331
+ signal.addEventListener("abort", abort, { once: true });
332
+ tool.lifecycleSignal.addEventListener("abort", removed, { once: true });
333
+ if (tool.lifecycleSignal.aborted)
334
+ removed();
335
+ });
336
+ this.#operation?.setWaitingForUser(true);
337
+ this.#publish();
338
+ return waiting;
339
+ }
340
+ async #respond(id, approved, source) {
341
+ const pending = this.#pending;
342
+ if (!pending || this.#approval?.id !== id || this.#approval.mode !== source || typeof approved !== "boolean" || (source === "page" && !approved))
343
+ throw new ClientError("INVALID_INPUT", "Confirmation is no longer pending or has the wrong source.");
344
+ pending.cleanup();
345
+ this.#pending = undefined;
346
+ this.#approval = undefined;
347
+ this.#status = "running";
348
+ this.#operation?.setWaitingForUser(false);
349
+ pending.resolve(approved);
350
+ this.#publish();
351
+ }
352
+ respondToApproval = (id, response) => this.#respond(id, response.approved, "chat");
353
+ confirmPage() {
354
+ const approval = this.#approval;
355
+ if (approval?.mode !== "page")
356
+ return;
357
+ const settled = new Promise((resolve) => this.#settled.set(approval.toolCallId, resolve));
358
+ void this.#respond(approval.id, true, "page").catch(() => { this.#settled.get(approval.toolCallId)?.(); this.#settled.delete(approval.toolCallId); });
359
+ return settled;
360
+ }
361
+ invalidate(message) {
362
+ const approval = this.#approval;
363
+ if (!approval)
364
+ return;
365
+ this.#messages = settleApproval(this.#messages, approval, "TOOL_CONFIRMATION_INVALIDATED", message, "binding_changed");
366
+ if (this.agent) {
367
+ agentController(this.agent).settle(approval.id, { type: "invalidate", message, reason: "binding_changed" }, this.#messages);
368
+ }
369
+ this.#queueRemoteCancellation();
370
+ const pending = this.#pending;
371
+ pending?.cleanup();
372
+ this.#pending = undefined;
373
+ this.#approval = undefined;
374
+ this.#status = "running";
375
+ this.#operation?.setWaitingForUser(false);
376
+ pending?.reject(new ClientError("TOOL_CONFIRMATION_INVALIDATED", message));
377
+ this.#publish();
378
+ }
379
+ cancel = () => {
380
+ if (this.#replacement)
381
+ this.#replacement.cancelled = true;
382
+ this.#cancelCurrent();
383
+ };
384
+ #queueRemoteCancellation() {
385
+ if (this.#remoteInterruptId)
386
+ this.#cancelledResume = [{ interruptId: this.#remoteInterruptId, status: "cancelled" }];
387
+ }
388
+ #cancelCurrent() {
389
+ if (!this.#controller || this.#cancelled)
390
+ return;
391
+ this.#cancelled = true;
392
+ if (this.#approval) {
393
+ this.#messages = settleApproval(this.#messages, this.#approval, "TOOL_CANCELLED", "The pending Tool confirmation was cancelled.", "interrupt_cancelled");
394
+ if (this.agent)
395
+ agentController(this.agent).settle(this.#approval.id, { type: "cancel" }, this.#messages);
396
+ this.#queueRemoteCancellation();
397
+ }
398
+ const pending = this.#pending;
399
+ pending?.cleanup();
400
+ this.#pending = undefined;
401
+ this.#approval = undefined;
402
+ this.#controller.abort(abortError());
403
+ pending?.reject(this.#controller.signal.reason);
404
+ this.#activeRun?.cancel();
405
+ this.#publish();
406
+ }
407
+ dispose = () => { if (this.#disposed)
408
+ return; this.#disposed = true; this.cancel(); this.#listeners.clear(); this.#eventListeners.clear(); };
409
+ async #remote(signal) {
410
+ let resume = this.#cancelledResume;
411
+ let inFlight = false;
412
+ let completedBrowserCall = false;
413
+ try {
414
+ for (;;) {
415
+ signal.throwIfAborted();
416
+ const catalog = [...this.runtime.getTools()];
417
+ const contexts = await this.runtime.getContexts({ signal });
418
+ const runId = id();
419
+ const input = {
420
+ threadId: this.id, runId, messages: this.#messages, state: this.#state ?? null,
421
+ ...(resume ? { resume } : {}),
422
+ tools: catalog.map(({ definition }) => ({ name: definition.name, description: definition.description, parameters: definition.inputSchema ?? { type: "object", properties: {} } })),
423
+ context: contexts.map((context) => ({ description: context.description ?? context.name, value: JSON.stringify(context) })),
424
+ forwardedProps: { nexface: { version: 2,
425
+ toolMetadata: Object.fromEntries(catalog.map(({ definition }) => [definition.name, { ...(definition.effect ? { effect: definition.effect } : {}) }])),
426
+ } },
427
+ };
428
+ RunAgentInputSchema.parse(input);
429
+ inFlight = true;
430
+ completedBrowserCall = false;
431
+ this.#remoteInterruptId = undefined;
432
+ const response = await abortable(this.#runHandler(input, { signal }), signal);
433
+ if (!response.ok || !response.body)
434
+ throw new ClientError("CHAT_REQUEST_FAILED", `Agent request failed (${response.status}).`);
435
+ let terminal;
436
+ let terminalEvent;
437
+ let messageSnapshot;
438
+ let stateSnapshot;
439
+ let started = false;
440
+ for await (const event of readEvents(response, signal)) {
441
+ if (event.type === EventType.RUN_ERROR) {
442
+ this.#event(event);
443
+ throw new ClientError(event.code ?? "CHAT_RUN_ERROR", event.message);
444
+ }
445
+ if (event.type === EventType.RUN_STARTED || event.type === EventType.RUN_FINISHED) {
446
+ if (event.threadId !== this.id || event.runId !== runId)
447
+ throw new Error("Agent response identity does not match its request.");
448
+ }
449
+ if (event.type === EventType.RUN_STARTED) {
450
+ if (started)
451
+ throw new Error("Duplicate Agent start event.");
452
+ started = true;
453
+ }
454
+ if (event.type === EventType.MESSAGES_SNAPSHOT) {
455
+ if (messageSnapshot || stateSnapshot)
456
+ throw new ClientError("CHAT_STREAM_INCOMPLETE", "Invalid recovery snapshot order.");
457
+ messageSnapshot = event;
458
+ continue;
459
+ }
460
+ if (event.type === EventType.STATE_SNAPSHOT) {
461
+ if (!messageSnapshot || stateSnapshot)
462
+ throw new ClientError("CHAT_STREAM_INCOMPLETE", "Invalid recovery snapshot order.");
463
+ stateSnapshot = event;
464
+ continue;
465
+ }
466
+ if (event.type === EventType.RUN_FINISHED) {
467
+ if (!started || !event.outcome || !messageSnapshot || !stateSnapshot)
468
+ throw new ClientError("CHAT_STREAM_INCOMPLETE", "Agent terminal is missing its recovery snapshots or outcome.");
469
+ terminal = { ...event.result, outcome: event.outcome };
470
+ terminalEvent = event;
471
+ break;
472
+ }
473
+ if (messageSnapshot)
474
+ throw new ClientError("CHAT_STREAM_INCOMPLETE", "Unexpected event between recovery snapshots and terminal.");
475
+ this.#event(event);
476
+ }
477
+ if (!terminal || !terminalEvent || !messageSnapshot || !stateSnapshot)
478
+ throw new ClientError("CHAT_STREAM_INCOMPLETE", "Agent stream ended without complete recovery snapshots.");
479
+ let decoded;
480
+ try {
481
+ decoded = decodeAgentResponse(messageSnapshot.messages, stateSnapshot.snapshot, terminalEvent);
482
+ }
483
+ catch (error) {
484
+ throw new ClientError("CHAT_STREAM_INCOMPLETE", error instanceof Error ? error.message : "Invalid Agent recovery response.");
485
+ }
486
+ const commit = () => {
487
+ // Only a complete terminal commits the matching messages and state.
488
+ this.#state = structuredClone(stateSnapshot.snapshot);
489
+ this.#cancelledResume = undefined;
490
+ inFlight = false;
491
+ this.#event(messageSnapshot);
492
+ this.#event(stateSnapshot);
493
+ this.#event(terminalEvent);
494
+ };
495
+ if (decoded.type === "success") {
496
+ commit();
497
+ return decoded.result;
498
+ }
499
+ this.#remoteInterruptId = decoded.interruptId;
500
+ commit();
501
+ const toolResult = await this.#browserAction(decoded.action, catalog, signal);
502
+ completedBrowserCall = true;
503
+ const messageId = id();
504
+ 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 }) });
505
+ resume = [{ interruptId: decoded.interruptId, status: "resolved", payload: { toolResultMessageId: messageId, ...(toolResult.confirmed ? { confirmed: true } : {}) } }];
506
+ }
507
+ }
508
+ catch (error) {
509
+ const unknown = inFlight || completedBrowserCall || this.#executingBrowserCall !== undefined;
510
+ if (unknown)
511
+ this.#recoveryUnavailable = true;
512
+ else
513
+ this.#queueRemoteCancellation();
514
+ const lastUser = this.#messages.reduce((last, message, index) => message.role === "user" ? index : last, -1);
515
+ const current = this.#messages.slice(lastUser);
516
+ for (const [index, message] of current.entries())
517
+ if (message.role === "assistant" && message.toolCalls?.length) {
518
+ const following = current.slice(index + 1);
519
+ const nextBatch = following.findIndex((item) => item.role === "assistant" && Boolean(item.toolCalls?.length));
520
+ const receipts = nextBatch < 0 ? following : following.slice(0, nextBatch);
521
+ for (const call of message.toolCalls) {
522
+ if (receipts.some((item) => item.role === "tool" && item.toolCallId === call.id))
523
+ continue;
524
+ const unknown = inFlight || this.#executingBrowserCall === call.id;
525
+ 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." } }) });
526
+ }
527
+ }
528
+ throw error;
529
+ }
530
+ }
531
+ async #browserAction(action, catalog, signal) {
532
+ let confirmed = false;
533
+ this.#executingBrowserCall = undefined;
534
+ try {
535
+ if (!action || typeof action.toolCallId !== "string" || !action.definition)
536
+ throw new Error("Invalid browser action.");
537
+ const tool = catalog.find((item) => JSON.stringify(item.definition) === JSON.stringify(action.definition));
538
+ if (!tool || !this.runtime.getTools().includes(tool))
539
+ throw new ClientError("TOOL_CONFIRMATION_INVALIDATED", "The original Tool Binding is no longer available.");
540
+ const errors = validateAgentToolInput(tool.definition.inputSchema, action.input);
541
+ if (errors.length)
542
+ throw new ClientError("INVALID_INPUT", errors.join(" "));
543
+ const confirmation = tool.confirmation;
544
+ if (confirmation) {
545
+ if (confirmation.mode === "page" && !this.#hasPageHook(tool.definition.name))
546
+ throw new ClientError("TOOL_CONFIRMATION_UNAVAILABLE", "An active usePageConfirmation Hook is required.");
547
+ confirmed = true;
548
+ const approval = { ...confirmation, type: "tool-approval", id: id(), runId: this.id, toolCallId: action.toolCallId, toolName: tool.definition.name, input: structuredClone(action.input) };
549
+ const approved = await this.#wait(approval, tool, signal);
550
+ if (!approved)
551
+ throw new ClientError("TOOL_CONFIRMATION_REJECTED", "The user rejected this tool call.");
552
+ }
553
+ signal.throwIfAborted();
554
+ this.#executingBrowserCall = action.toolCallId;
555
+ const result = await getInternalToolRuntime(this.runtime).executeWithProgress(tool, action.input, { signal, ...(action.progressLabel ? { progressLabel: action.progressLabel } : {}) });
556
+ return { toolCallId: action.toolCallId, result: result ?? null, ...(confirmed ? { confirmed } : {}) };
557
+ }
558
+ catch (error) {
559
+ if (error instanceof SubscriptionError)
560
+ throw error;
561
+ signal.throwIfAborted();
562
+ if (error instanceof ClientError && error.code === "TOOL_CONFIRMATION_INVALIDATED")
563
+ throw error;
564
+ return { toolCallId: action.toolCallId, error: { code: error instanceof ClientError ? error.code : "TOOL_ERROR", message: error instanceof Error ? error.message : String(error) }, ...(confirmed ? { confirmed } : {}) };
565
+ }
566
+ finally {
567
+ if (!signal.aborted)
568
+ this.#executingBrowserCall = undefined;
569
+ this.#settled.get(action.toolCallId)?.();
570
+ this.#settled.delete(action.toolCallId);
571
+ }
572
+ }
573
+ }
574
+ async function abortable(promise, signal) {
575
+ signal.throwIfAborted();
576
+ let abort;
577
+ try {
578
+ return await Promise.race([promise, new Promise((_resolve, reject) => { abort = () => reject(signal.reason); signal.addEventListener("abort", abort, { once: true }); })]);
579
+ }
580
+ finally {
581
+ signal.removeEventListener("abort", abort);
582
+ }
583
+ }
584
+ async function* readEvents(response, signal) {
585
+ const reader = response.body.getReader();
586
+ const decoder = new TextDecoder();
587
+ let buffer = "";
588
+ const abort = () => { void reader.cancel(signal.reason).catch(() => undefined); };
589
+ signal.addEventListener("abort", abort, { once: true });
590
+ try {
591
+ for (;;) {
592
+ signal.throwIfAborted();
593
+ const next = await reader.read();
594
+ buffer = (buffer + decoder.decode(next.value, { stream: !next.done })).replace(/\r\n/g, "\n");
595
+ let boundary;
596
+ while ((boundary = buffer.indexOf("\n\n")) >= 0) {
597
+ const packet = buffer.slice(0, boundary);
598
+ buffer = buffer.slice(boundary + 2);
599
+ const data = packet.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart()).join("\n");
600
+ if (data) {
601
+ signal.throwIfAborted();
602
+ yield EventSchemas.parse(JSON.parse(data));
603
+ }
604
+ }
605
+ if (next.done) {
606
+ signal.throwIfAborted();
607
+ if (buffer.trim())
608
+ throw new Error("Truncated SSE event.");
609
+ return;
610
+ }
611
+ }
612
+ }
613
+ finally {
614
+ signal.removeEventListener("abort", abort);
615
+ // Transport cleanup must not delay terminal delivery.
616
+ void reader.cancel().catch(() => undefined);
617
+ reader.releaseLock();
618
+ }
619
+ }
620
+ //# sourceMappingURL=client.js.map