@nexface/chat 0.1.13-alpha.4 → 0.1.13-alpha.5

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 (58) hide show
  1. package/dist/assistant-attachments.js +60 -16
  2. package/dist/assistant-components.d.ts +3 -3
  3. package/dist/assistant-components.js +77 -28
  4. package/dist/assistant-runtime.d.ts +1 -1
  5. package/dist/assistant-runtime.js +100 -42
  6. package/dist/attachments.js +36 -14
  7. package/dist/client.js +312 -72
  8. package/dist/config.js +4 -4
  9. package/dist/default-chat.d.ts +1 -1
  10. package/dist/default-chat.js +2102 -727
  11. package/dist/errors.js +55 -17
  12. package/dist/page-confirmation.js +3 -3
  13. package/dist/protocol-messages.js +290 -65
  14. package/dist/protocol-response.js +38 -17
  15. package/dist/react.js +146 -49
  16. package/dist/shared/errors.d.ts +1 -1
  17. package/dist/shared/schema.js +45 -18
  18. package/dist/storage.js +130 -52
  19. package/dist/styles.css +99 -20
  20. package/dist/tool-result.js +7 -2
  21. package/dist/ui/attachment.aui.d.ts +1 -1
  22. package/dist/ui/attachment.aui.js +16 -19
  23. package/dist/ui/code-block.js +2 -2
  24. package/dist/ui/collapsible.js +2 -2
  25. package/dist/ui/composer-voice.js +3 -1
  26. package/dist/ui/dialog.d.ts +1 -1
  27. package/dist/ui/dialog.js +9 -3
  28. package/dist/ui/dropdown-menu.js +2 -2
  29. package/dist/ui/home-demo/composer.js +7 -3
  30. package/dist/ui/home-demo/greeting.d.ts +1 -1
  31. package/dist/ui/home-demo/greeting.js +1 -1
  32. package/dist/ui/home-demo/messages.d.ts +1 -1
  33. package/dist/ui/home-demo/messages.js +4 -4
  34. package/dist/ui/home-demo/suggestions.d.ts +1 -1
  35. package/dist/ui/home-demo/suggestions.js +5 -2
  36. package/dist/ui/home-demo/surfaces.js +3 -1
  37. package/dist/ui/home-demo/thread.d.ts +1 -1
  38. package/dist/ui/home-demo/thread.js +1 -1
  39. package/dist/ui/home-demo/trace-line.d.ts +1 -1
  40. package/dist/ui/home-demo/trace-line.js +2 -2
  41. package/dist/ui/home-demo/trace.d.ts +1 -1
  42. package/dist/ui/home-demo/trace.js +28 -8
  43. package/dist/ui/markdown-text.js +2 -2
  44. package/dist/ui/reasoning.aui.js +2 -2
  45. package/dist/ui/reasoning.d.ts +1 -1
  46. package/dist/ui/reasoning.js +6 -8
  47. package/dist/ui/surface.js +27 -7
  48. package/dist/ui/thread-list.aui.d.ts +2 -2
  49. package/dist/ui/thread-list.aui.js +18 -11
  50. package/dist/ui/tool-group.aui.js +2 -2
  51. package/dist/ui/tooltip-icon-button.js +1 -1
  52. package/dist/ui/use-attachment-src.js +1 -1
  53. package/dist/ui/use-copy-to-clipboard.d.ts +1 -1
  54. package/dist/ui/use-copy-to-clipboard.js +1 -1
  55. package/dist/ui/utils.js +9 -2
  56. package/dist/use-next-message.js +7 -3
  57. package/dist/voice/use-voice.js +35 -12
  58. package/package.json +3 -3
package/dist/client.js CHANGED
@@ -1,14 +1,14 @@
1
1
  import { pageDecisionSymbol } from "./shared/runtime-execution.js";
2
- import { createAgent } from "@nexface/agent";
3
- import { decodeAgentResponse } from "./protocol-response.js";
2
+ import { createAgent, } from "@nexface/agent";
3
+ import { decodeAgentResponse, } from "./protocol-response.js";
4
4
  import { isToolRuntimeError } from "@nexface/tools";
5
5
  import { getRuntimeController } from "./shared/runtime-controller.js";
6
6
  import { validateAgentToolInput } from "./shared/schema.js";
7
- import { EventType, EventSchemas, RunAgentInputSchema, TextInputContentSchema, ImageInputContentSchema } from "@ag-ui/core";
7
+ import { EventType, EventSchemas, RunAgentInputSchema, TextInputContentSchema, ImageInputContentSchema, } from "@ag-ui/core";
8
8
  import { conversationFromMessages } from "./storage.js";
9
- import { createMessageUpdater, restoreMessages, settleApproval, projectMessages } from "./protocol-messages.js";
9
+ import { createMessageUpdater, restoreMessages, settleApproval, projectMessages, } from "./protocol-messages.js";
10
10
  import { resolveModelConfig } from "./config.js";
11
- import { markErrorPresented, runError, toolError } from "./errors.js";
11
+ import { markErrorPresented, runError, toolError, } from "./errors.js";
12
12
  const controllerSymbol = Symbol.for("@nexface/agent/chat-controller");
13
13
  const agentController = (agent) => agent[controllerSymbol];
14
14
  const id = () => globalThis.crypto.randomUUID();
@@ -78,10 +78,12 @@ class ChatClientImplementation {
78
78
  if (!options?.toolRuntime || Boolean(options.agent) === Boolean(options.run))
79
79
  throw new ClientError("INVALID_INPUT", "Provide exactly one agent config or run function and a ToolRuntime.");
80
80
  this.#options = options;
81
- this.#model = options.agent ? model ?? resolveModelConfig(options.agent.model) : undefined;
81
+ this.#model = options.agent ? (model ?? resolveModelConfig(options.agent.model)) : undefined;
82
82
  this.runtime = options.toolRuntime;
83
83
  this.#runHandler = options.run;
84
- this.agent = options.agent ? createAgent({ ...options.agent, model: this.#model, toolRuntime: this.runtime }) : undefined;
84
+ this.agent = options.agent
85
+ ? createAgent({ ...options.agent, model: this.#model, toolRuntime: this.runtime })
86
+ : undefined;
85
87
  }
86
88
  getMessages = () => this.#messages;
87
89
  getStatus = () => this.#status;
@@ -91,8 +93,18 @@ class ChatClientImplementation {
91
93
  if (this.#recoveryUnavailable)
92
94
  throw new ClientError("CHAT_RECOVERY_UNAVAILABLE", "This chat cannot continue. Check the action results, then start a new chat.");
93
95
  }
94
- subscribe = (listener) => { this.#listeners.add(listener); return () => { this.#listeners.delete(listener); }; };
95
- subscribeEvents = (listener) => { this.#eventListeners.add(listener); return () => { this.#eventListeners.delete(listener); }; };
96
+ subscribe = (listener) => {
97
+ this.#listeners.add(listener);
98
+ return () => {
99
+ this.#listeners.delete(listener);
100
+ };
101
+ };
102
+ subscribeEvents = (listener) => {
103
+ this.#eventListeners.add(listener);
104
+ return () => {
105
+ this.#eventListeners.delete(listener);
106
+ };
107
+ };
96
108
  #publish() {
97
109
  for (const listener of this.#listeners) {
98
110
  try {
@@ -104,8 +116,12 @@ class ChatClientImplementation {
104
116
  }
105
117
  }
106
118
  }
107
- get cancelling() { return Boolean(this.#controller?.signal.aborted); }
108
- get busy() { return Boolean(this.#controller); }
119
+ get cancelling() {
120
+ return Boolean(this.#controller?.signal.aborted);
121
+ }
122
+ get busy() {
123
+ return Boolean(this.#controller);
124
+ }
109
125
  setPageResolver(resolver) {
110
126
  this.#hasPageHook = resolver;
111
127
  if (this.agent)
@@ -150,29 +166,54 @@ class ChatClientImplementation {
150
166
  return;
151
167
  this.#reported.add(error.id);
152
168
  try {
153
- const result = this.#options.onError?.({ cause, code: error.code, ...(error.scope === "tool" ? { toolCallId: error.toolCallId } : {}), sessionId: this.id, ...(this.#runId ? { runId: this.#runId } : {}) });
169
+ const result = this.#options.onError?.({
170
+ cause,
171
+ code: error.code,
172
+ ...(error.scope === "tool" ? { toolCallId: error.toolCallId } : {}),
173
+ sessionId: this.id,
174
+ ...(this.#runId ? { runId: this.#runId } : {}),
175
+ });
154
176
  // Also contain rejected promises from async diagnostic callbacks.
155
177
  void Promise.resolve(result).catch(() => undefined);
156
178
  }
157
- catch { /* Diagnostics must not affect task execution. */ }
179
+ catch {
180
+ /* Diagnostics must not affect task execution. */
181
+ }
158
182
  }
159
183
  #event(event) {
160
184
  if (event.type === EventType.RUN_STARTED)
161
185
  this.#runId = event.runId;
162
186
  if (event.type === EventType.TOOL_CALL_RESULT) {
163
- const owner = [...this.#messages].reverse().find((message) => message.role === "assistant" && message.toolCalls?.some((call) => call.id === event.toolCallId));
164
- const call = owner?.role === "assistant" ? owner.toolCalls?.find((call) => call.id === event.toolCallId) : undefined;
187
+ const owner = [...this.#messages]
188
+ .reverse()
189
+ .find((message) => message.role === "assistant" &&
190
+ message.toolCalls?.some((call) => call.id === event.toolCallId));
191
+ const call = owner?.role === "assistant"
192
+ ? owner.toolCalls?.find((call) => call.id === event.toolCallId)
193
+ : undefined;
165
194
  let name = call?.function.name;
166
195
  if (name === "nxf_callAppTool")
167
196
  try {
168
197
  name = JSON.parse(call.function.arguments).name;
169
198
  }
170
- catch { /* Incomplete calls have no local diagnostic. */ }
199
+ catch {
200
+ /* Incomplete calls have no local diagnostic. */
201
+ }
171
202
  const presentation = toolError(event.messageId, event.toolCallId, event.content, event.metadata?.nexface?.parentErrorId, false, name);
172
203
  const localCause = presentation.toolState && name ? this.#runtimeCauses.get(name)?.shift() : undefined;
173
204
  if (presentation.toolState === "cancelled" && localCause !== undefined) {
174
205
  // Cancellation after execution began cannot prove that effects were undone.
175
- event = { ...event, metadata: { ...event.metadata, nexface: { ...event.metadata?.nexface, executionUnknown: true, parentErrorId: this.#failureId } } };
206
+ event = {
207
+ ...event,
208
+ metadata: {
209
+ ...event.metadata,
210
+ nexface: {
211
+ ...event.metadata?.nexface,
212
+ executionUnknown: true,
213
+ parentErrorId: this.#failureId,
214
+ },
215
+ },
216
+ };
176
217
  }
177
218
  if (presentation.error && !presentation.error.parentErrorId)
178
219
  this.#report(presentation.error, this.#toolCauses.get(event.toolCallId) ?? localCause ?? presentation.cause);
@@ -182,16 +223,24 @@ class ChatClientImplementation {
182
223
  event = { ...event, threadId: this.id };
183
224
  this.#messages = this.#updateMessages(this.#messages, event);
184
225
  if (event.type === EventType.MESSAGES_SNAPSHOT) {
185
- const receipts = new Map(event.messages.filter((message) => message.role === "tool").map((message) => [message.id, message]));
226
+ const receipts = new Map(event.messages
227
+ .filter((message) => message.role === "tool")
228
+ .map((message) => [message.id, message]));
186
229
  for (const message of projectMessages(this.#messages))
187
230
  for (const part of message.parts) {
188
- if (part.type !== "tool" || !part.error || part.error.parentErrorId || this.#reported.has(part.error.id))
231
+ if (part.type !== "tool" ||
232
+ !part.error ||
233
+ part.error.parentErrorId ||
234
+ this.#reported.has(part.error.id))
189
235
  continue;
190
236
  const receipt = receipts.get(part.error.id);
191
237
  if (!receipt)
192
238
  continue;
193
- const diagnostic = toolError(receipt.id, part.toolCallId, receipt.content, undefined, false, part.name).cause ?? receipt.error;
194
- this.#report(part.error, this.#toolCauses.get(part.toolCallId) ?? this.#runtimeCauses.get(part.name)?.shift() ?? diagnostic);
239
+ const diagnostic = toolError(receipt.id, part.toolCallId, receipt.content, undefined, false, part.name)
240
+ .cause ?? receipt.error;
241
+ this.#report(part.error, this.#toolCauses.get(part.toolCallId) ??
242
+ this.#runtimeCauses.get(part.name)?.shift() ??
243
+ diagnostic);
195
244
  this.#toolCauses.delete(part.toolCallId);
196
245
  }
197
246
  }
@@ -199,12 +248,18 @@ class ChatClientImplementation {
199
248
  this.#settled.get(event.toolCallId)?.();
200
249
  this.#settled.delete(event.toolCallId);
201
250
  }
202
- if (event.type === EventType.CUSTOM && event.name === "nexface.tool-execution" && this.#operation) {
251
+ if (event.type === EventType.CUSTOM &&
252
+ event.name === "nexface.tool-execution" &&
253
+ this.#operation) {
203
254
  const value = event.value;
204
255
  const runtime = getRuntimeController(this.runtime);
205
256
  const current = runtime.getOperationSnapshot()?.taskProgress;
206
257
  if (value.status === "running")
207
- runtime.setTaskProgress(this.#operation, { phase: "tool", toolCallId: value.toolCallId, ...(value.progressLabel ? { progressLabel: value.progressLabel } : {}) });
258
+ runtime.setTaskProgress(this.#operation, {
259
+ phase: "tool",
260
+ toolCallId: value.toolCallId,
261
+ ...(value.progressLabel ? { progressLabel: value.progressLabel } : {}),
262
+ });
208
263
  else if (current?.phase === "tool" && current.toolCallId === value.toolCallId)
209
264
  runtime.setTaskProgress(this.#operation, { phase: "processing" });
210
265
  }
@@ -224,7 +279,12 @@ class ChatClientImplementation {
224
279
  if (this.#disposed || this.#replacement)
225
280
  throw new ClientError("CHAT_RUN_ACTIVE", "The Client is disposed or already replacing a task.");
226
281
  try {
227
- content = typeof content === "string" ? content.trim() : content.map((part) => part.type === "text" ? TextInputContentSchema.parse(part) : ImageInputContentSchema.parse(part));
282
+ content =
283
+ typeof content === "string"
284
+ ? content.trim()
285
+ : content.map((part) => part.type === "text"
286
+ ? TextInputContentSchema.parse(part)
287
+ : ImageInputContentSchema.parse(part));
228
288
  if (!content.length)
229
289
  throw new Error("Chat message is required.");
230
290
  }
@@ -246,7 +306,9 @@ class ChatClientImplementation {
246
306
  }
247
307
  await this.#task.catch(() => undefined);
248
308
  if (cancellationFailure)
249
- throw cancellationFailure instanceof SubscriptionError ? cancellationFailure.failure : cancellationFailure;
309
+ throw cancellationFailure instanceof SubscriptionError
310
+ ? cancellationFailure.failure
311
+ : cancellationFailure;
250
312
  if (replacement.cancelled || this.#disposed)
251
313
  throw abortError();
252
314
  }
@@ -262,8 +324,10 @@ class ChatClientImplementation {
262
324
  }
263
325
  const task = this.#send(content, userMessage);
264
326
  this.#task = task;
265
- const clear = () => { if (this.#task === task)
266
- this.#task = undefined; };
327
+ const clear = () => {
328
+ if (this.#task === task)
329
+ this.#task = undefined;
330
+ };
267
331
  void task.then(clear, clear);
268
332
  return task;
269
333
  }
@@ -273,9 +337,21 @@ class ChatClientImplementation {
273
337
  const userId = userMessage?.id ?? id();
274
338
  let initialRun;
275
339
  if (this.agent)
276
- initialRun = this.agent.run({ messages: [{ id: userId, role: "user", content: typeof content === "string" ? content : [...content] }] }, { signal: controller.signal });
340
+ initialRun = this.agent.run({
341
+ messages: [
342
+ {
343
+ id: userId,
344
+ role: "user",
345
+ content: typeof content === "string" ? content : [...content],
346
+ },
347
+ ],
348
+ }, { signal: controller.signal });
277
349
  else {
278
- this.#operation = getRuntimeController(this.runtime).beginInternalOperation({ signal: controller.signal, onCancel: () => this.cancel(), taskProgress: { phase: "processing" } });
350
+ this.#operation = getRuntimeController(this.runtime).beginInternalOperation({
351
+ signal: controller.signal,
352
+ onCancel: () => this.cancel(),
353
+ taskProgress: { phase: "processing" },
354
+ });
279
355
  }
280
356
  this.#stateBeforeLastMessage = this.#state;
281
357
  this.#resumeBeforeLastMessage = this.#cancelledResume;
@@ -291,12 +367,33 @@ class ChatClientImplementation {
291
367
  ...(message.error ? [message.error.id] : []),
292
368
  ...message.parts.flatMap((part) => part.type === "tool" && part.error ? [part.error.id] : []),
293
369
  ]));
294
- 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 } } } : {}) }];
370
+ this.#messages = [
371
+ ...this.#messages,
372
+ {
373
+ id: userId,
374
+ role: "user",
375
+ content: typeof content === "string" ? content : [...content],
376
+ ...(userMessage
377
+ ? {
378
+ metadata: {
379
+ nexface: {
380
+ restoredParts: userMessage.parts,
381
+ attachments: userMessage.attachments ?? [],
382
+ revisionOf: userMessage.revisionOf,
383
+ },
384
+ },
385
+ }
386
+ : {}),
387
+ },
388
+ ];
295
389
  const runtime = getRuntimeController(this.runtime);
296
390
  const operationId = runtime.getOperationSnapshot()?.id;
297
391
  const unsubscribe = runtime.subscribeOperation(() => {
298
392
  const operation = runtime.getOperationSnapshot();
299
- if (operation && operation.id === operationId && operation.status === "cancelling" && !controller.signal.aborted)
393
+ if (operation &&
394
+ operation.id === operationId &&
395
+ operation.status === "cancelling" &&
396
+ !controller.signal.aborted)
300
397
  this.cancel();
301
398
  });
302
399
  const unsubscribeExecution = this.runtime.on("toolexecution", (event) => {
@@ -309,7 +406,9 @@ class ChatClientImplementation {
309
406
  let succeeded = false;
310
407
  try {
311
408
  this.#publish();
312
- const result = initialRun ? await this.#local(initialRun, controller.signal) : await this.#remote(controller.signal);
409
+ const result = initialRun
410
+ ? await this.#local(initialRun, controller.signal)
411
+ : await this.#remote(controller.signal);
313
412
  controller.signal.throwIfAborted();
314
413
  succeeded = true;
315
414
  return result;
@@ -324,18 +423,43 @@ class ChatClientImplementation {
324
423
  if (failure instanceof SubscriptionError)
325
424
  failure = failure.failure;
326
425
  const record = failure;
327
- 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 } : {}) });
426
+ this.#error =
427
+ failure instanceof Error
428
+ ? failure
429
+ : Object.assign(new Error(typeof record?.message === "string" ? record.message : String(failure)), {
430
+ name: typeof record?.name === "string" ? record.name : "Error",
431
+ ...(typeof record?.code === "string" ? { code: record.code } : {}),
432
+ });
328
433
  const cancelled = controller.signal.aborted;
329
- const lastUser = this.#messages.reduce((last, message, index) => message.role === "user" ? index : last, -1);
434
+ const lastUser = this.#messages.reduce((last, message, index) => (message.role === "user" ? index : last), -1);
330
435
  const current = this.#messages.slice(lastUser + 1);
331
436
  const unknownTools = projectMessages(current).some((message) => message.parts.some((part) => part.type === "tool" && part.toolState === "unknown"));
332
437
  const error = cancelled ? undefined : runError(this.#failureId, failure, unknownTools);
333
438
  this.#messages = this.#messages.map((message, index) => index > lastUser && message.metadata?.nexface?.state === "running"
334
- ? { ...message, metadata: { ...message.metadata, nexface: { ...message.metadata.nexface, state: cancelled ? "cancelled" : "error" } } } : message);
439
+ ? {
440
+ ...message,
441
+ metadata: {
442
+ ...message.metadata,
443
+ nexface: {
444
+ ...message.metadata.nexface,
445
+ state: cancelled ? "cancelled" : "error",
446
+ },
447
+ },
448
+ }
449
+ : message);
335
450
  // A display-only row carries the terminal state without inventing model text.
336
- this.#messages.push({ id: id(), role: "assistant", content: "", metadata: { nexface: {
337
- displayOnly: true, state: cancelled ? "cancelled" : "error", ...(error ? { error } : {}),
338
- } } });
451
+ this.#messages.push({
452
+ id: id(),
453
+ role: "assistant",
454
+ content: "",
455
+ metadata: {
456
+ nexface: {
457
+ displayOnly: true,
458
+ state: cancelled ? "cancelled" : "error",
459
+ ...(error ? { error } : {}),
460
+ },
461
+ },
462
+ });
339
463
  const rejection = this.#error;
340
464
  markErrorPresented(rejection);
341
465
  if (cancelled)
@@ -353,7 +477,9 @@ class ChatClientImplementation {
353
477
  this.#pending = undefined;
354
478
  this.#approval = undefined;
355
479
  if (this.#operation)
356
- await this.#operation.end({ outcome: succeeded ? "completed" : controller.signal.aborted ? "cancelled" : "failed" });
480
+ await this.#operation.end({
481
+ outcome: succeeded ? "completed" : controller.signal.aborted ? "cancelled" : "failed",
482
+ });
357
483
  this.#operation = undefined;
358
484
  this.#activeRun = undefined;
359
485
  this.#controller = undefined;
@@ -366,7 +492,9 @@ class ChatClientImplementation {
366
492
  }
367
493
  async #consume(run) {
368
494
  this.#activeRun = run;
369
- const outcomes = await Promise.allSettled([run.result, (async () => {
495
+ const outcomes = await Promise.allSettled([
496
+ run.result,
497
+ (async () => {
370
498
  try {
371
499
  for await (const event of run)
372
500
  this.#event(event);
@@ -375,7 +503,8 @@ class ChatClientImplementation {
375
503
  run.cancel();
376
504
  throw error;
377
505
  }
378
- })()]);
506
+ })(),
507
+ ]);
379
508
  if (outcomes[1].status === "rejected")
380
509
  throw outcomes[1].reason;
381
510
  if (outcomes[0].status === "rejected")
@@ -395,7 +524,9 @@ class ChatClientImplementation {
395
524
  if (result.outcome.interrupts.length !== 1 || extension?.kind !== "tool-approval")
396
525
  throw new Error("Unexpected local interrupt.");
397
526
  const approval = extension.approval;
398
- const tool = this.runtime.getTools().find((item) => item.definition.name === approval.toolName);
527
+ const tool = this.runtime
528
+ .getTools()
529
+ .find((item) => item.definition.name === approval.toolName);
399
530
  if (!tool)
400
531
  throw new ClientError("TOOL_CONFIRMATION_INVALIDATED", "Tool Binding was removed.");
401
532
  const approved = await this.#wait(approval, tool, signal);
@@ -404,7 +535,11 @@ class ChatClientImplementation {
404
535
  agentController(this.agent).settle(approval.id, { type: "cancel" }, this.#messages);
405
536
  }
406
537
  signal.throwIfAborted();
407
- const response = { interruptId: interrupt.id, status: "resolved", payload: { approved } };
538
+ const response = {
539
+ interruptId: interrupt.id,
540
+ status: "resolved",
541
+ payload: { approved },
542
+ };
408
543
  if (approval.mode === "page")
409
544
  agentController(this.agent).authorizePageResponse(response);
410
545
  run = this.agent.run({ resume: [response] }, { signal });
@@ -417,7 +552,10 @@ class ChatClientImplementation {
417
552
  const waiting = new Promise((resolve, reject) => {
418
553
  const abort = () => reject(signal.reason);
419
554
  const removed = () => this.invalidate("Tool Binding was removed.");
420
- const cleanup = () => { signal.removeEventListener("abort", abort); tool.lifecycleSignal.removeEventListener("abort", removed); };
555
+ const cleanup = () => {
556
+ signal.removeEventListener("abort", abort);
557
+ tool.lifecycleSignal.removeEventListener("abort", removed);
558
+ };
421
559
  this.#pending = { resolve, reject, cleanup };
422
560
  signal.addEventListener("abort", abort, { once: true });
423
561
  tool.lifecycleSignal.addEventListener("abort", removed, { once: true });
@@ -431,7 +569,11 @@ class ChatClientImplementation {
431
569
  }
432
570
  async #respond(id, approved, source) {
433
571
  const pending = this.#pending;
434
- if (!pending || this.#approval?.id !== id || this.#approval.mode !== source || typeof approved !== "boolean" || (source === "page" && !approved))
572
+ if (!pending ||
573
+ this.#approval?.id !== id ||
574
+ this.#approval.mode !== source ||
575
+ typeof approved !== "boolean" ||
576
+ (source === "page" && !approved))
435
577
  throw new ClientError("INVALID_INPUT", "Confirmation is no longer pending or has the wrong source.");
436
578
  pending.cleanup();
437
579
  this.#pending = undefined;
@@ -448,7 +590,10 @@ class ChatClientImplementation {
448
590
  if (approval?.mode !== "page")
449
591
  return;
450
592
  const settled = new Promise((resolve) => this.#settled.set(approval.toolCallId, resolve));
451
- void this.#respond(approval.id, true, "page").catch(() => { this.#settled.get(approval.toolCallId)?.(); this.#settled.delete(approval.toolCallId); });
593
+ void this.#respond(approval.id, true, "page").catch(() => {
594
+ this.#settled.get(approval.toolCallId)?.();
595
+ this.#settled.delete(approval.toolCallId);
596
+ });
452
597
  return settled;
453
598
  }
454
599
  invalidate(message) {
@@ -456,8 +601,15 @@ class ChatClientImplementation {
456
601
  if (!approval)
457
602
  return;
458
603
  const previousIds = new Set(this.#messages.map((item) => item.id));
459
- this.#messages = settleApproval(this.#messages, approval, "TOOL_CONFIRMATION_INVALIDATED", message, "binding_changed")
460
- .map((item) => previousIds.has(item.id) ? item : { ...item, metadata: { ...item.metadata, nexface: { ...item.metadata?.nexface, parentErrorId: this.#failureId } } });
604
+ this.#messages = settleApproval(this.#messages, approval, "TOOL_CONFIRMATION_INVALIDATED", message, "binding_changed").map((item) => previousIds.has(item.id)
605
+ ? item
606
+ : {
607
+ ...item,
608
+ metadata: {
609
+ ...item.metadata,
610
+ nexface: { ...item.metadata?.nexface, parentErrorId: this.#failureId },
611
+ },
612
+ });
461
613
  if (this.agent) {
462
614
  agentController(this.agent).settle(approval.id, { type: "invalidate", message, reason: "binding_changed" }, this.#messages);
463
615
  }
@@ -500,8 +652,14 @@ class ChatClientImplementation {
500
652
  this.#activeRun?.cancel();
501
653
  this.#publish();
502
654
  }
503
- dispose = () => { if (this.#disposed)
504
- return; this.#disposed = true; this.cancel(); this.#listeners.clear(); this.#eventListeners.clear(); };
655
+ dispose = () => {
656
+ if (this.#disposed)
657
+ return;
658
+ this.#disposed = true;
659
+ this.cancel();
660
+ this.#listeners.clear();
661
+ this.#eventListeners.clear();
662
+ };
505
663
  async #remote(signal) {
506
664
  let resume = this.#cancelledResume;
507
665
  let inFlight = false;
@@ -516,13 +674,29 @@ class ChatClientImplementation {
516
674
  const runId = id();
517
675
  this.#runId = runId;
518
676
  const input = {
519
- threadId: this.id, runId, messages: this.#messages.filter((message) => !message.metadata?.nexface?.displayOnly), state: this.#state ?? null,
677
+ threadId: this.id,
678
+ runId,
679
+ messages: this.#messages.filter((message) => !message.metadata?.nexface?.displayOnly),
680
+ state: this.#state ?? null,
520
681
  ...(resume ? { resume } : {}),
521
- tools: catalog.map(({ definition }) => ({ name: definition.name, description: definition.description, parameters: definition.inputSchema ?? { type: "object", properties: {} } })),
522
- context: contexts.map((context) => ({ description: context.description ?? context.name, value: JSON.stringify(context) })),
523
- forwardedProps: { nexface: { version: 3,
524
- toolMetadata: Object.fromEntries(catalog.map(({ definition }) => [definition.name, { ...(definition.effect ? { effect: definition.effect } : {}) }])),
525
- } },
682
+ tools: catalog.map(({ definition }) => ({
683
+ name: definition.name,
684
+ description: definition.description,
685
+ parameters: definition.inputSchema ?? { type: "object", properties: {} },
686
+ })),
687
+ context: contexts.map((context) => ({
688
+ description: context.description ?? context.name,
689
+ value: JSON.stringify(context),
690
+ })),
691
+ forwardedProps: {
692
+ nexface: {
693
+ version: 3,
694
+ toolMetadata: Object.fromEntries(catalog.map(({ definition }) => [
695
+ definition.name,
696
+ { ...(definition.effect ? { effect: definition.effect } : {}) },
697
+ ])),
698
+ },
699
+ },
526
700
  };
527
701
  RunAgentInputSchema.parse(input);
528
702
  clientToolExecutionOnly = false;
@@ -538,9 +712,10 @@ class ChatClientImplementation {
538
712
  let started = false;
539
713
  for await (const event of readEvents(response, signal)) {
540
714
  // A tool event may precede a server-side effect; text alone does not.
541
- if (event.type === EventType.TOOL_CALL_START || event.type === EventType.TOOL_CALL_CHUNK
542
- || event.type === EventType.TOOL_CALL_RESULT
543
- || (event.type === EventType.CUSTOM && event.name === "nexface.tool-execution"))
715
+ if (event.type === EventType.TOOL_CALL_START ||
716
+ event.type === EventType.TOOL_CALL_CHUNK ||
717
+ event.type === EventType.TOOL_CALL_RESULT ||
718
+ (event.type === EventType.CUSTOM && event.name === "nexface.tool-execution"))
544
719
  uncommittedToolCall = true;
545
720
  if (event.type === EventType.RUN_ERROR) {
546
721
  this.#event(event);
@@ -608,20 +783,36 @@ class ChatClientImplementation {
608
783
  const toolResult = await this.#browserAction(decoded.action, catalog, signal);
609
784
  completedBrowserCall = true;
610
785
  const messageId = id();
611
- 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 }) });
612
- resume = [{ interruptId: decoded.interruptId, status: "resolved", payload: { toolResultMessageId: messageId, ...(toolResult.confirmed ? { confirmed: true } : {}) } }];
786
+ this.#event({
787
+ type: EventType.TOOL_CALL_RESULT,
788
+ messageId,
789
+ role: "tool",
790
+ toolCallId: toolResult.toolCallId,
791
+ content: JSON.stringify(toolResult.error ? { error: toolResult.error } : { result: toolResult.result ?? null }),
792
+ });
793
+ resume = [
794
+ {
795
+ interruptId: decoded.interruptId,
796
+ status: "resolved",
797
+ payload: {
798
+ toolResultMessageId: messageId,
799
+ ...(toolResult.confirmed ? { confirmed: true } : {}),
800
+ },
801
+ },
802
+ ];
613
803
  }
614
804
  }
615
805
  catch (error) {
616
806
  // Keep the last committed state and partial text for a new instruction.
617
807
  // Never resume a call whose effects have not reached a complete terminal.
618
- const unknown = (inFlight && (!signal.aborted || !clientToolExecutionOnly || uncommittedToolCall))
619
- || completedBrowserCall || this.#executingBrowserCall !== undefined;
808
+ const unknown = (inFlight && (!signal.aborted || !clientToolExecutionOnly || uncommittedToolCall)) ||
809
+ completedBrowserCall ||
810
+ this.#executingBrowserCall !== undefined;
620
811
  if (unknown)
621
812
  this.#recoveryUnavailable = true;
622
813
  else
623
814
  this.#queueRemoteCancellation();
624
- const lastUser = this.#messages.reduce((last, message, index) => message.role === "user" ? index : last, -1);
815
+ const lastUser = this.#messages.reduce((last, message, index) => (message.role === "user" ? index : last), -1);
625
816
  const current = this.#messages.slice(lastUser);
626
817
  for (const [index, message] of current.entries())
627
818
  if (message.role === "assistant" && message.toolCalls?.length) {
@@ -632,7 +823,21 @@ class ChatClientImplementation {
632
823
  if (receipts.some((item) => item.role === "tool" && item.toolCallId === call.id))
633
824
  continue;
634
825
  const unknown = inFlight || this.#executingBrowserCall === call.id;
635
- this.#event({ type: EventType.TOOL_CALL_RESULT, messageId: id(), role: "tool", toolCallId: call.id, metadata: { nexface: { parentErrorId: this.#failureId } }, 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." } }) });
826
+ this.#event({
827
+ type: EventType.TOOL_CALL_RESULT,
828
+ messageId: id(),
829
+ role: "tool",
830
+ toolCallId: call.id,
831
+ metadata: { nexface: { parentErrorId: this.#failureId } },
832
+ content: JSON.stringify({
833
+ error: {
834
+ code: unknown ? "EXECUTION_OUTCOME_UNKNOWN" : "TOOL_CANCELLED",
835
+ message: unknown
836
+ ? "The execution outcome is unknown; this call may have executed."
837
+ : "Task ended before execution.",
838
+ },
839
+ }),
840
+ });
636
841
  }
637
842
  }
638
843
  throw error;
@@ -655,15 +860,31 @@ class ChatClientImplementation {
655
860
  if (confirmation.mode === "page" && !this.#hasPageHook(tool.definition.name))
656
861
  throw new ClientError("TOOL_CONFIRMATION_UNAVAILABLE", "An active usePageConfirmation Hook is required.");
657
862
  confirmed = true;
658
- const approval = { ...confirmation, type: "tool-approval", id: id(), runId: this.id, toolCallId: action.toolCallId, toolName: tool.definition.name, input: structuredClone(action.input) };
863
+ const approval = {
864
+ ...confirmation,
865
+ type: "tool-approval",
866
+ id: id(),
867
+ runId: this.id,
868
+ toolCallId: action.toolCallId,
869
+ toolName: tool.definition.name,
870
+ input: structuredClone(action.input),
871
+ };
659
872
  const approved = await this.#wait(approval, tool, signal);
660
873
  if (!approved)
661
874
  throw new ClientError("TOOL_CONFIRMATION_REJECTED", "The user rejected this tool call.");
662
875
  }
663
876
  signal.throwIfAborted();
664
877
  this.#executingBrowserCall = action.toolCallId;
665
- const result = await this.runtime.execute(tool, action.input, { signal, ...(action.pageDecision ? { [pageDecisionSymbol]: true } : {}), ...(action.progressLabel ? { progressLabel: action.progressLabel } : {}) });
666
- return { toolCallId: action.toolCallId, result: result ?? null, ...(confirmed ? { confirmed } : {}) };
878
+ const result = await this.runtime.execute(tool, action.input, {
879
+ signal,
880
+ ...(action.pageDecision ? { [pageDecisionSymbol]: true } : {}),
881
+ ...(action.progressLabel ? { progressLabel: action.progressLabel } : {}),
882
+ });
883
+ return {
884
+ toolCallId: action.toolCallId,
885
+ result: result ?? null,
886
+ ...(confirmed ? { confirmed } : {}),
887
+ };
667
888
  }
668
889
  catch (error) {
669
890
  if (error instanceof SubscriptionError)
@@ -675,7 +896,14 @@ class ChatClientImplementation {
675
896
  const code = error instanceof ClientError || isToolRuntimeError(error) ? error.code : "TOOL_ERROR";
676
897
  // Once execution starts, an executor cannot report an approval rejection.
677
898
  const executionError = code === "TOOL_CONFIRMATION_REJECTED" && this.#executingBrowserCall === action.toolCallId;
678
- return { toolCallId: action.toolCallId, error: { code: executionError ? "TOOL_ERROR" : code, message: error instanceof Error ? error.message : String(error) }, ...(confirmed ? { confirmed } : {}) };
899
+ return {
900
+ toolCallId: action.toolCallId,
901
+ error: {
902
+ code: executionError ? "TOOL_ERROR" : code,
903
+ message: error instanceof Error ? error.message : String(error),
904
+ },
905
+ ...(confirmed ? { confirmed } : {}),
906
+ };
679
907
  }
680
908
  finally {
681
909
  if (!signal.aborted)
@@ -689,7 +917,13 @@ async function abortable(promise, signal) {
689
917
  signal.throwIfAborted();
690
918
  let abort;
691
919
  try {
692
- return await Promise.race([promise, new Promise((_resolve, reject) => { abort = () => reject(signal.reason); signal.addEventListener("abort", abort, { once: true }); })]);
920
+ return await Promise.race([
921
+ promise,
922
+ new Promise((_resolve, reject) => {
923
+ abort = () => reject(signal.reason);
924
+ signal.addEventListener("abort", abort, { once: true });
925
+ }),
926
+ ]);
693
927
  }
694
928
  finally {
695
929
  signal.removeEventListener("abort", abort);
@@ -699,7 +933,9 @@ async function* readEvents(response, signal) {
699
933
  const reader = response.body.getReader();
700
934
  const decoder = new TextDecoder();
701
935
  let buffer = "";
702
- const abort = () => { void reader.cancel(signal.reason).catch(() => undefined); };
936
+ const abort = () => {
937
+ void reader.cancel(signal.reason).catch(() => undefined);
938
+ };
703
939
  signal.addEventListener("abort", abort, { once: true });
704
940
  try {
705
941
  for (;;) {
@@ -710,7 +946,11 @@ async function* readEvents(response, signal) {
710
946
  while ((boundary = buffer.indexOf("\n\n")) >= 0) {
711
947
  const packet = buffer.slice(0, boundary);
712
948
  buffer = buffer.slice(boundary + 2);
713
- const data = packet.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart()).join("\n");
949
+ const data = packet
950
+ .split("\n")
951
+ .filter((line) => line.startsWith("data:"))
952
+ .map((line) => line.slice(5).trimStart())
953
+ .join("\n");
714
954
  if (data) {
715
955
  signal.throwIfAborted();
716
956
  yield EventSchemas.parse(JSON.parse(data));