@nexface/chat 0.1.15-alpha.1 → 0.1.15-alpha.2

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 (130) hide show
  1. package/dist/assistant-attachments.js +60 -17
  2. package/dist/assistant-components.d.ts +3 -3
  3. package/dist/assistant-components.js +77 -29
  4. package/dist/assistant-runtime.d.ts +1 -1
  5. package/dist/assistant-runtime.js +100 -43
  6. package/dist/attachments.js +36 -15
  7. package/dist/client.js +309 -77
  8. package/dist/config.js +4 -5
  9. package/dist/default-chat.d.ts +1 -1
  10. package/dist/default-chat.js +2102 -728
  11. package/dist/errors.d.ts +1 -0
  12. package/dist/errors.js +69 -18
  13. package/dist/index.js +0 -1
  14. package/dist/messages.js +0 -1
  15. package/dist/page-confirmation.js +3 -4
  16. package/dist/protocol-messages.js +290 -66
  17. package/dist/protocol-response.js +38 -18
  18. package/dist/react.d.ts +1 -1
  19. package/dist/react.js +147 -50
  20. package/dist/shared/errors.d.ts +1 -1
  21. package/dist/shared/errors.js +0 -1
  22. package/dist/shared/runtime-controller.d.ts +1 -0
  23. package/dist/shared/runtime-controller.js +0 -1
  24. package/dist/shared/runtime-execution.js +0 -1
  25. package/dist/shared/schema.js +45 -19
  26. package/dist/storage.js +130 -53
  27. package/dist/styles.css +99 -20
  28. package/dist/tool-result.js +7 -3
  29. package/dist/types.js +0 -1
  30. package/dist/ui/attachment.aui.d.ts +1 -1
  31. package/dist/ui/attachment.aui.js +16 -20
  32. package/dist/ui/avatar.js +0 -1
  33. package/dist/ui/button.js +0 -1
  34. package/dist/ui/code-block.js +2 -3
  35. package/dist/ui/collapsible.js +2 -3
  36. package/dist/ui/composer-voice.js +3 -2
  37. package/dist/ui/dialog.d.ts +1 -1
  38. package/dist/ui/dialog.js +9 -4
  39. package/dist/ui/dropdown-menu.js +2 -3
  40. package/dist/ui/home-demo/action-bar.js +0 -1
  41. package/dist/ui/home-demo/composer.js +7 -4
  42. package/dist/ui/home-demo/greeting.d.ts +1 -1
  43. package/dist/ui/home-demo/greeting.js +1 -2
  44. package/dist/ui/home-demo/messages.d.ts +1 -1
  45. package/dist/ui/home-demo/messages.js +4 -5
  46. package/dist/ui/home-demo/styles.js +0 -1
  47. package/dist/ui/home-demo/suggestions.d.ts +1 -1
  48. package/dist/ui/home-demo/suggestions.js +5 -3
  49. package/dist/ui/home-demo/surfaces.js +3 -2
  50. package/dist/ui/home-demo/thread.d.ts +1 -1
  51. package/dist/ui/home-demo/thread.js +1 -2
  52. package/dist/ui/home-demo/trace-line.d.ts +1 -1
  53. package/dist/ui/home-demo/trace-line.js +2 -3
  54. package/dist/ui/home-demo/trace.d.ts +1 -1
  55. package/dist/ui/home-demo/trace.js +28 -9
  56. package/dist/ui/home-demo/type.js +0 -1
  57. package/dist/ui/input.js +0 -1
  58. package/dist/ui/markdown-text.js +2 -3
  59. package/dist/ui/reasoning.aui.js +2 -3
  60. package/dist/ui/reasoning.d.ts +1 -1
  61. package/dist/ui/reasoning.js +6 -9
  62. package/dist/ui/surface.js +27 -8
  63. package/dist/ui/thread-list.aui.d.ts +2 -2
  64. package/dist/ui/thread-list.aui.js +18 -12
  65. package/dist/ui/tool-group.aui.js +2 -3
  66. package/dist/ui/tooltip-icon-button.js +1 -2
  67. package/dist/ui/tooltip.js +0 -1
  68. package/dist/ui/use-attachment-src.js +1 -2
  69. package/dist/ui/use-copy-to-clipboard.d.ts +1 -1
  70. package/dist/ui/use-copy-to-clipboard.js +1 -2
  71. package/dist/ui/utils.js +9 -3
  72. package/dist/use-next-message.js +7 -4
  73. package/dist/voice/types.js +0 -1
  74. package/dist/voice/use-voice.js +35 -13
  75. package/package.json +8 -4
  76. package/dist/assistant-attachments.js.map +0 -1
  77. package/dist/assistant-components.js.map +0 -1
  78. package/dist/assistant-runtime.js.map +0 -1
  79. package/dist/attachments.js.map +0 -1
  80. package/dist/client.js.map +0 -1
  81. package/dist/config.js.map +0 -1
  82. package/dist/default-chat.js.map +0 -7
  83. package/dist/errors.js.map +0 -1
  84. package/dist/index.js.map +0 -1
  85. package/dist/messages.js.map +0 -1
  86. package/dist/page-confirmation.js.map +0 -1
  87. package/dist/protocol-messages.js.map +0 -1
  88. package/dist/protocol-response.js.map +0 -1
  89. package/dist/react.js.map +0 -1
  90. package/dist/shared/errors.js.map +0 -1
  91. package/dist/shared/runtime-controller.js.map +0 -1
  92. package/dist/shared/runtime-execution.js.map +0 -1
  93. package/dist/shared/schema.js.map +0 -1
  94. package/dist/storage.js.map +0 -1
  95. package/dist/tool-result.js.map +0 -1
  96. package/dist/types.js.map +0 -1
  97. package/dist/ui/attachment.aui.js.map +0 -1
  98. package/dist/ui/avatar.js.map +0 -1
  99. package/dist/ui/button.js.map +0 -1
  100. package/dist/ui/code-block.js.map +0 -1
  101. package/dist/ui/collapsible.js.map +0 -1
  102. package/dist/ui/composer-voice.js.map +0 -1
  103. package/dist/ui/dialog.js.map +0 -1
  104. package/dist/ui/dropdown-menu.js.map +0 -1
  105. package/dist/ui/home-demo/action-bar.js.map +0 -1
  106. package/dist/ui/home-demo/composer.js.map +0 -1
  107. package/dist/ui/home-demo/greeting.js.map +0 -1
  108. package/dist/ui/home-demo/messages.js.map +0 -1
  109. package/dist/ui/home-demo/styles.js.map +0 -1
  110. package/dist/ui/home-demo/suggestions.js.map +0 -1
  111. package/dist/ui/home-demo/surfaces.js.map +0 -1
  112. package/dist/ui/home-demo/thread.js.map +0 -1
  113. package/dist/ui/home-demo/trace-line.js.map +0 -1
  114. package/dist/ui/home-demo/trace.js.map +0 -1
  115. package/dist/ui/home-demo/type.js.map +0 -1
  116. package/dist/ui/input.js.map +0 -1
  117. package/dist/ui/markdown-text.js.map +0 -1
  118. package/dist/ui/reasoning.aui.js.map +0 -1
  119. package/dist/ui/reasoning.js.map +0 -1
  120. package/dist/ui/surface.js.map +0 -1
  121. package/dist/ui/thread-list.aui.js.map +0 -1
  122. package/dist/ui/tool-group.aui.js.map +0 -1
  123. package/dist/ui/tooltip-icon-button.js.map +0 -1
  124. package/dist/ui/tooltip.js.map +0 -1
  125. package/dist/ui/use-attachment-src.js.map +0 -1
  126. package/dist/ui/use-copy-to-clipboard.js.map +0 -1
  127. package/dist/ui/utils.js.map +0 -1
  128. package/dist/use-next-message.js.map +0 -1
  129. package/dist/voice/types.js.map +0 -1
  130. package/dist/voice/use-voice.js.map +0 -1
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, reportError, 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)
@@ -149,30 +165,48 @@ class ChatClientImplementation {
149
165
  if (this.#reported.has(error.id))
150
166
  return;
151
167
  this.#reported.add(error.id);
152
- 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 } : {}) });
154
- // Also contain rejected promises from async diagnostic callbacks.
155
- void Promise.resolve(result).catch(() => undefined);
156
- }
157
- catch { /* Diagnostics must not affect task execution. */ }
168
+ reportError({
169
+ cause,
170
+ code: error.code,
171
+ ...(error.scope === "tool" ? { toolCallId: error.toolCallId } : {}),
172
+ sessionId: this.id,
173
+ ...(this.#runId ? { runId: this.#runId } : {}),
174
+ }, this.#options.onError);
158
175
  }
159
176
  #event(event) {
160
177
  if (event.type === EventType.RUN_STARTED)
161
178
  this.#runId = event.runId;
162
179
  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;
180
+ const owner = [...this.#messages]
181
+ .reverse()
182
+ .find((message) => message.role === "assistant" &&
183
+ message.toolCalls?.some((call) => call.id === event.toolCallId));
184
+ const call = owner?.role === "assistant"
185
+ ? owner.toolCalls?.find((call) => call.id === event.toolCallId)
186
+ : undefined;
165
187
  let name = call?.function.name;
166
188
  if (name === "nxf_callAppTool")
167
189
  try {
168
190
  name = JSON.parse(call.function.arguments).name;
169
191
  }
170
- catch { /* Incomplete calls have no local diagnostic. */ }
192
+ catch {
193
+ /* Incomplete calls have no local diagnostic. */
194
+ }
171
195
  const presentation = toolError(event.messageId, event.toolCallId, event.content, event.metadata?.nexface?.parentErrorId, false, name);
172
196
  const localCause = presentation.toolState && name ? this.#runtimeCauses.get(name)?.shift() : undefined;
173
197
  if (presentation.toolState === "cancelled" && localCause !== undefined) {
174
198
  // 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 } } };
199
+ event = {
200
+ ...event,
201
+ metadata: {
202
+ ...event.metadata,
203
+ nexface: {
204
+ ...event.metadata?.nexface,
205
+ executionUnknown: true,
206
+ parentErrorId: this.#failureId,
207
+ },
208
+ },
209
+ };
176
210
  }
177
211
  if (presentation.error && !presentation.error.parentErrorId)
178
212
  this.#report(presentation.error, this.#toolCauses.get(event.toolCallId) ?? localCause ?? presentation.cause);
@@ -182,16 +216,24 @@ class ChatClientImplementation {
182
216
  event = { ...event, threadId: this.id };
183
217
  this.#messages = this.#updateMessages(this.#messages, event);
184
218
  if (event.type === EventType.MESSAGES_SNAPSHOT) {
185
- const receipts = new Map(event.messages.filter((message) => message.role === "tool").map((message) => [message.id, message]));
219
+ const receipts = new Map(event.messages
220
+ .filter((message) => message.role === "tool")
221
+ .map((message) => [message.id, message]));
186
222
  for (const message of projectMessages(this.#messages))
187
223
  for (const part of message.parts) {
188
- if (part.type !== "tool" || !part.error || part.error.parentErrorId || this.#reported.has(part.error.id))
224
+ if (part.type !== "tool" ||
225
+ !part.error ||
226
+ part.error.parentErrorId ||
227
+ this.#reported.has(part.error.id))
189
228
  continue;
190
229
  const receipt = receipts.get(part.error.id);
191
230
  if (!receipt)
192
231
  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);
232
+ const diagnostic = toolError(receipt.id, part.toolCallId, receipt.content, undefined, false, part.name)
233
+ .cause ?? receipt.error;
234
+ this.#report(part.error, this.#toolCauses.get(part.toolCallId) ??
235
+ this.#runtimeCauses.get(part.name)?.shift() ??
236
+ diagnostic);
195
237
  this.#toolCauses.delete(part.toolCallId);
196
238
  }
197
239
  }
@@ -199,12 +241,18 @@ class ChatClientImplementation {
199
241
  this.#settled.get(event.toolCallId)?.();
200
242
  this.#settled.delete(event.toolCallId);
201
243
  }
202
- if (event.type === EventType.CUSTOM && event.name === "nexface.tool-execution" && this.#operation) {
244
+ if (event.type === EventType.CUSTOM &&
245
+ event.name === "nexface.tool-execution" &&
246
+ this.#operation) {
203
247
  const value = event.value;
204
248
  const runtime = getRuntimeController(this.runtime);
205
249
  const current = runtime.getOperationSnapshot()?.taskProgress;
206
250
  if (value.status === "running")
207
- runtime.setTaskProgress(this.#operation, { phase: "tool", toolCallId: value.toolCallId, ...(value.progressLabel ? { progressLabel: value.progressLabel } : {}) });
251
+ runtime.setTaskProgress(this.#operation, {
252
+ phase: "tool",
253
+ toolCallId: value.toolCallId,
254
+ ...(value.progressLabel ? { progressLabel: value.progressLabel } : {}),
255
+ });
208
256
  else if (current?.phase === "tool" && current.toolCallId === value.toolCallId)
209
257
  runtime.setTaskProgress(this.#operation, { phase: "processing" });
210
258
  }
@@ -224,7 +272,12 @@ class ChatClientImplementation {
224
272
  if (this.#disposed || this.#replacement)
225
273
  throw new ClientError("CHAT_RUN_ACTIVE", "The Client is disposed or already replacing a task.");
226
274
  try {
227
- content = typeof content === "string" ? content.trim() : content.map((part) => part.type === "text" ? TextInputContentSchema.parse(part) : ImageInputContentSchema.parse(part));
275
+ content =
276
+ typeof content === "string"
277
+ ? content.trim()
278
+ : content.map((part) => part.type === "text"
279
+ ? TextInputContentSchema.parse(part)
280
+ : ImageInputContentSchema.parse(part));
228
281
  if (!content.length)
229
282
  throw new Error("Chat message is required.");
230
283
  }
@@ -246,7 +299,9 @@ class ChatClientImplementation {
246
299
  }
247
300
  await this.#task.catch(() => undefined);
248
301
  if (cancellationFailure)
249
- throw cancellationFailure instanceof SubscriptionError ? cancellationFailure.failure : cancellationFailure;
302
+ throw cancellationFailure instanceof SubscriptionError
303
+ ? cancellationFailure.failure
304
+ : cancellationFailure;
250
305
  if (replacement.cancelled || this.#disposed)
251
306
  throw abortError();
252
307
  }
@@ -262,8 +317,10 @@ class ChatClientImplementation {
262
317
  }
263
318
  const task = this.#send(content, userMessage);
264
319
  this.#task = task;
265
- const clear = () => { if (this.#task === task)
266
- this.#task = undefined; };
320
+ const clear = () => {
321
+ if (this.#task === task)
322
+ this.#task = undefined;
323
+ };
267
324
  void task.then(clear, clear);
268
325
  return task;
269
326
  }
@@ -273,9 +330,21 @@ class ChatClientImplementation {
273
330
  const userId = userMessage?.id ?? id();
274
331
  let initialRun;
275
332
  if (this.agent)
276
- initialRun = this.agent.run({ messages: [{ id: userId, role: "user", content: typeof content === "string" ? content : [...content] }] }, { signal: controller.signal });
333
+ initialRun = this.agent.run({
334
+ messages: [
335
+ {
336
+ id: userId,
337
+ role: "user",
338
+ content: typeof content === "string" ? content : [...content],
339
+ },
340
+ ],
341
+ }, { signal: controller.signal });
277
342
  else {
278
- this.#operation = getRuntimeController(this.runtime).beginInternalOperation({ signal: controller.signal, onCancel: () => this.cancel(), taskProgress: { phase: "processing" } });
343
+ this.#operation = getRuntimeController(this.runtime).beginInternalOperation({
344
+ signal: controller.signal,
345
+ onCancel: () => this.cancel(),
346
+ taskProgress: { phase: "processing" },
347
+ });
279
348
  }
280
349
  this.#stateBeforeLastMessage = this.#state;
281
350
  this.#resumeBeforeLastMessage = this.#cancelledResume;
@@ -291,12 +360,33 @@ class ChatClientImplementation {
291
360
  ...(message.error ? [message.error.id] : []),
292
361
  ...message.parts.flatMap((part) => part.type === "tool" && part.error ? [part.error.id] : []),
293
362
  ]));
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 } } } : {}) }];
363
+ this.#messages = [
364
+ ...this.#messages,
365
+ {
366
+ id: userId,
367
+ role: "user",
368
+ content: typeof content === "string" ? content : [...content],
369
+ ...(userMessage
370
+ ? {
371
+ metadata: {
372
+ nexface: {
373
+ restoredParts: userMessage.parts,
374
+ attachments: userMessage.attachments ?? [],
375
+ revisionOf: userMessage.revisionOf,
376
+ },
377
+ },
378
+ }
379
+ : {}),
380
+ },
381
+ ];
295
382
  const runtime = getRuntimeController(this.runtime);
296
383
  const operationId = runtime.getOperationSnapshot()?.id;
297
384
  const unsubscribe = runtime.subscribeOperation(() => {
298
385
  const operation = runtime.getOperationSnapshot();
299
- if (operation && operation.id === operationId && operation.status === "cancelling" && !controller.signal.aborted)
386
+ if (operation &&
387
+ operation.id === operationId &&
388
+ operation.status === "cancelling" &&
389
+ !controller.signal.aborted)
300
390
  this.cancel();
301
391
  });
302
392
  const unsubscribeExecution = this.runtime.on("toolexecution", (event) => {
@@ -309,7 +399,9 @@ class ChatClientImplementation {
309
399
  let succeeded = false;
310
400
  try {
311
401
  this.#publish();
312
- const result = initialRun ? await this.#local(initialRun, controller.signal) : await this.#remote(controller.signal);
402
+ const result = initialRun
403
+ ? await this.#local(initialRun, controller.signal)
404
+ : await this.#remote(controller.signal);
313
405
  controller.signal.throwIfAborted();
314
406
  succeeded = true;
315
407
  return result;
@@ -324,18 +416,43 @@ class ChatClientImplementation {
324
416
  if (failure instanceof SubscriptionError)
325
417
  failure = failure.failure;
326
418
  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 } : {}) });
419
+ this.#error =
420
+ failure instanceof Error
421
+ ? failure
422
+ : Object.assign(new Error(typeof record?.message === "string" ? record.message : String(failure)), {
423
+ name: typeof record?.name === "string" ? record.name : "Error",
424
+ ...(typeof record?.code === "string" ? { code: record.code } : {}),
425
+ });
328
426
  const cancelled = controller.signal.aborted;
329
- const lastUser = this.#messages.reduce((last, message, index) => message.role === "user" ? index : last, -1);
427
+ const lastUser = this.#messages.reduce((last, message, index) => (message.role === "user" ? index : last), -1);
330
428
  const current = this.#messages.slice(lastUser + 1);
331
429
  const unknownTools = projectMessages(current).some((message) => message.parts.some((part) => part.type === "tool" && part.toolState === "unknown"));
332
430
  const error = cancelled ? undefined : runError(this.#failureId, failure, unknownTools);
333
431
  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);
432
+ ? {
433
+ ...message,
434
+ metadata: {
435
+ ...message.metadata,
436
+ nexface: {
437
+ ...message.metadata.nexface,
438
+ state: cancelled ? "cancelled" : "error",
439
+ },
440
+ },
441
+ }
442
+ : message);
335
443
  // 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
- } } });
444
+ this.#messages.push({
445
+ id: id(),
446
+ role: "assistant",
447
+ content: "",
448
+ metadata: {
449
+ nexface: {
450
+ displayOnly: true,
451
+ state: cancelled ? "cancelled" : "error",
452
+ ...(error ? { error } : {}),
453
+ },
454
+ },
455
+ });
339
456
  const rejection = this.#error;
340
457
  markErrorPresented(rejection);
341
458
  if (cancelled)
@@ -353,7 +470,9 @@ class ChatClientImplementation {
353
470
  this.#pending = undefined;
354
471
  this.#approval = undefined;
355
472
  if (this.#operation)
356
- await this.#operation.end({ outcome: succeeded ? "completed" : controller.signal.aborted ? "cancelled" : "failed" });
473
+ await this.#operation.end({
474
+ outcome: succeeded ? "completed" : controller.signal.aborted ? "cancelled" : "failed",
475
+ });
357
476
  this.#operation = undefined;
358
477
  this.#activeRun = undefined;
359
478
  this.#controller = undefined;
@@ -366,7 +485,9 @@ class ChatClientImplementation {
366
485
  }
367
486
  async #consume(run) {
368
487
  this.#activeRun = run;
369
- const outcomes = await Promise.allSettled([run.result, (async () => {
488
+ const outcomes = await Promise.allSettled([
489
+ run.result,
490
+ (async () => {
370
491
  try {
371
492
  for await (const event of run)
372
493
  this.#event(event);
@@ -375,7 +496,8 @@ class ChatClientImplementation {
375
496
  run.cancel();
376
497
  throw error;
377
498
  }
378
- })()]);
499
+ })(),
500
+ ]);
379
501
  if (outcomes[1].status === "rejected")
380
502
  throw outcomes[1].reason;
381
503
  if (outcomes[0].status === "rejected")
@@ -395,7 +517,9 @@ class ChatClientImplementation {
395
517
  if (result.outcome.interrupts.length !== 1 || extension?.kind !== "tool-approval")
396
518
  throw new Error("Unexpected local interrupt.");
397
519
  const approval = extension.approval;
398
- const tool = this.runtime.getTools().find((item) => item.definition.name === approval.toolName);
520
+ const tool = this.runtime
521
+ .getTools()
522
+ .find((item) => item.definition.name === approval.toolName);
399
523
  if (!tool)
400
524
  throw new ClientError("TOOL_CONFIRMATION_INVALIDATED", "Tool Binding was removed.");
401
525
  const approved = await this.#wait(approval, tool, signal);
@@ -404,7 +528,11 @@ class ChatClientImplementation {
404
528
  agentController(this.agent).settle(approval.id, { type: "cancel" }, this.#messages);
405
529
  }
406
530
  signal.throwIfAborted();
407
- const response = { interruptId: interrupt.id, status: "resolved", payload: { approved } };
531
+ const response = {
532
+ interruptId: interrupt.id,
533
+ status: "resolved",
534
+ payload: { approved },
535
+ };
408
536
  if (approval.mode === "page")
409
537
  agentController(this.agent).authorizePageResponse(response);
410
538
  run = this.agent.run({ resume: [response] }, { signal });
@@ -417,7 +545,10 @@ class ChatClientImplementation {
417
545
  const waiting = new Promise((resolve, reject) => {
418
546
  const abort = () => reject(signal.reason);
419
547
  const removed = () => this.invalidate("Tool Binding was removed.");
420
- const cleanup = () => { signal.removeEventListener("abort", abort); tool.lifecycleSignal.removeEventListener("abort", removed); };
548
+ const cleanup = () => {
549
+ signal.removeEventListener("abort", abort);
550
+ tool.lifecycleSignal.removeEventListener("abort", removed);
551
+ };
421
552
  this.#pending = { resolve, reject, cleanup };
422
553
  signal.addEventListener("abort", abort, { once: true });
423
554
  tool.lifecycleSignal.addEventListener("abort", removed, { once: true });
@@ -431,7 +562,11 @@ class ChatClientImplementation {
431
562
  }
432
563
  async #respond(id, approved, source) {
433
564
  const pending = this.#pending;
434
- if (!pending || this.#approval?.id !== id || this.#approval.mode !== source || typeof approved !== "boolean" || (source === "page" && !approved))
565
+ if (!pending ||
566
+ this.#approval?.id !== id ||
567
+ this.#approval.mode !== source ||
568
+ typeof approved !== "boolean" ||
569
+ (source === "page" && !approved))
435
570
  throw new ClientError("INVALID_INPUT", "Confirmation is no longer pending or has the wrong source.");
436
571
  pending.cleanup();
437
572
  this.#pending = undefined;
@@ -448,7 +583,10 @@ class ChatClientImplementation {
448
583
  if (approval?.mode !== "page")
449
584
  return;
450
585
  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); });
586
+ void this.#respond(approval.id, true, "page").catch(() => {
587
+ this.#settled.get(approval.toolCallId)?.();
588
+ this.#settled.delete(approval.toolCallId);
589
+ });
452
590
  return settled;
453
591
  }
454
592
  invalidate(message) {
@@ -456,8 +594,15 @@ class ChatClientImplementation {
456
594
  if (!approval)
457
595
  return;
458
596
  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 } } });
597
+ this.#messages = settleApproval(this.#messages, approval, "TOOL_CONFIRMATION_INVALIDATED", message, "binding_changed").map((item) => previousIds.has(item.id)
598
+ ? item
599
+ : {
600
+ ...item,
601
+ metadata: {
602
+ ...item.metadata,
603
+ nexface: { ...item.metadata?.nexface, parentErrorId: this.#failureId },
604
+ },
605
+ });
461
606
  if (this.agent) {
462
607
  agentController(this.agent).settle(approval.id, { type: "invalidate", message, reason: "binding_changed" }, this.#messages);
463
608
  }
@@ -500,8 +645,14 @@ class ChatClientImplementation {
500
645
  this.#activeRun?.cancel();
501
646
  this.#publish();
502
647
  }
503
- dispose = () => { if (this.#disposed)
504
- return; this.#disposed = true; this.cancel(); this.#listeners.clear(); this.#eventListeners.clear(); };
648
+ dispose = () => {
649
+ if (this.#disposed)
650
+ return;
651
+ this.#disposed = true;
652
+ this.cancel();
653
+ this.#listeners.clear();
654
+ this.#eventListeners.clear();
655
+ };
505
656
  async #remote(signal) {
506
657
  let resume = this.#cancelledResume;
507
658
  let inFlight = false;
@@ -516,13 +667,29 @@ class ChatClientImplementation {
516
667
  const runId = id();
517
668
  this.#runId = runId;
518
669
  const input = {
519
- threadId: this.id, runId, messages: this.#messages.filter((message) => !message.metadata?.nexface?.displayOnly), state: this.#state ?? null,
670
+ threadId: this.id,
671
+ runId,
672
+ messages: this.#messages.filter((message) => !message.metadata?.nexface?.displayOnly),
673
+ state: this.#state ?? null,
520
674
  ...(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
- } },
675
+ tools: catalog.map(({ definition }) => ({
676
+ name: definition.name,
677
+ description: definition.description,
678
+ parameters: definition.inputSchema ?? { type: "object", properties: {} },
679
+ })),
680
+ context: contexts.map((context) => ({
681
+ description: context.description ?? context.name,
682
+ value: JSON.stringify(context),
683
+ })),
684
+ forwardedProps: {
685
+ nexface: {
686
+ version: 3,
687
+ toolMetadata: Object.fromEntries(catalog.map(({ definition }) => [
688
+ definition.name,
689
+ { ...(definition.effect ? { effect: definition.effect } : {}) },
690
+ ])),
691
+ },
692
+ },
526
693
  };
527
694
  RunAgentInputSchema.parse(input);
528
695
  clientToolExecutionOnly = false;
@@ -538,9 +705,10 @@ class ChatClientImplementation {
538
705
  let started = false;
539
706
  for await (const event of readEvents(response, signal)) {
540
707
  // 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"))
708
+ if (event.type === EventType.TOOL_CALL_START ||
709
+ event.type === EventType.TOOL_CALL_CHUNK ||
710
+ event.type === EventType.TOOL_CALL_RESULT ||
711
+ (event.type === EventType.CUSTOM && event.name === "nexface.tool-execution"))
544
712
  uncommittedToolCall = true;
545
713
  if (event.type === EventType.RUN_ERROR) {
546
714
  this.#event(event);
@@ -608,20 +776,36 @@ class ChatClientImplementation {
608
776
  const toolResult = await this.#browserAction(decoded.action, catalog, signal);
609
777
  completedBrowserCall = true;
610
778
  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 } : {}) } }];
779
+ this.#event({
780
+ type: EventType.TOOL_CALL_RESULT,
781
+ messageId,
782
+ role: "tool",
783
+ toolCallId: toolResult.toolCallId,
784
+ content: JSON.stringify(toolResult.error ? { error: toolResult.error } : { result: toolResult.result ?? null }),
785
+ });
786
+ resume = [
787
+ {
788
+ interruptId: decoded.interruptId,
789
+ status: "resolved",
790
+ payload: {
791
+ toolResultMessageId: messageId,
792
+ ...(toolResult.confirmed ? { confirmed: true } : {}),
793
+ },
794
+ },
795
+ ];
613
796
  }
614
797
  }
615
798
  catch (error) {
616
799
  // Keep the last committed state and partial text for a new instruction.
617
800
  // 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;
801
+ const unknown = (inFlight && (!signal.aborted || !clientToolExecutionOnly || uncommittedToolCall)) ||
802
+ completedBrowserCall ||
803
+ this.#executingBrowserCall !== undefined;
620
804
  if (unknown)
621
805
  this.#recoveryUnavailable = true;
622
806
  else
623
807
  this.#queueRemoteCancellation();
624
- const lastUser = this.#messages.reduce((last, message, index) => message.role === "user" ? index : last, -1);
808
+ const lastUser = this.#messages.reduce((last, message, index) => (message.role === "user" ? index : last), -1);
625
809
  const current = this.#messages.slice(lastUser);
626
810
  for (const [index, message] of current.entries())
627
811
  if (message.role === "assistant" && message.toolCalls?.length) {
@@ -632,7 +816,21 @@ class ChatClientImplementation {
632
816
  if (receipts.some((item) => item.role === "tool" && item.toolCallId === call.id))
633
817
  continue;
634
818
  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." } }) });
819
+ this.#event({
820
+ type: EventType.TOOL_CALL_RESULT,
821
+ messageId: id(),
822
+ role: "tool",
823
+ toolCallId: call.id,
824
+ metadata: { nexface: { parentErrorId: this.#failureId } },
825
+ content: JSON.stringify({
826
+ error: {
827
+ code: unknown ? "EXECUTION_OUTCOME_UNKNOWN" : "TOOL_CANCELLED",
828
+ message: unknown
829
+ ? "The execution outcome is unknown; this call may have executed."
830
+ : "Task ended before execution.",
831
+ },
832
+ }),
833
+ });
636
834
  }
637
835
  }
638
836
  throw error;
@@ -655,15 +853,31 @@ class ChatClientImplementation {
655
853
  if (confirmation.mode === "page" && !this.#hasPageHook(tool.definition.name))
656
854
  throw new ClientError("TOOL_CONFIRMATION_UNAVAILABLE", "An active usePageConfirmation Hook is required.");
657
855
  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) };
856
+ const approval = {
857
+ ...confirmation,
858
+ type: "tool-approval",
859
+ id: id(),
860
+ runId: this.id,
861
+ toolCallId: action.toolCallId,
862
+ toolName: tool.definition.name,
863
+ input: structuredClone(action.input),
864
+ };
659
865
  const approved = await this.#wait(approval, tool, signal);
660
866
  if (!approved)
661
867
  throw new ClientError("TOOL_CONFIRMATION_REJECTED", "The user rejected this tool call.");
662
868
  }
663
869
  signal.throwIfAborted();
664
870
  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 } : {}) };
871
+ const result = await this.runtime.execute(tool, action.input, {
872
+ signal,
873
+ ...(action.pageDecision ? { [pageDecisionSymbol]: true } : {}),
874
+ ...(action.progressLabel ? { progressLabel: action.progressLabel } : {}),
875
+ });
876
+ return {
877
+ toolCallId: action.toolCallId,
878
+ result: result ?? null,
879
+ ...(confirmed ? { confirmed } : {}),
880
+ };
667
881
  }
668
882
  catch (error) {
669
883
  if (error instanceof SubscriptionError)
@@ -675,7 +889,14 @@ class ChatClientImplementation {
675
889
  const code = error instanceof ClientError || isToolRuntimeError(error) ? error.code : "TOOL_ERROR";
676
890
  // Once execution starts, an executor cannot report an approval rejection.
677
891
  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 } : {}) };
892
+ return {
893
+ toolCallId: action.toolCallId,
894
+ error: {
895
+ code: executionError ? "TOOL_ERROR" : code,
896
+ message: error instanceof Error ? error.message : String(error),
897
+ },
898
+ ...(confirmed ? { confirmed } : {}),
899
+ };
679
900
  }
680
901
  finally {
681
902
  if (!signal.aborted)
@@ -689,7 +910,13 @@ async function abortable(promise, signal) {
689
910
  signal.throwIfAborted();
690
911
  let abort;
691
912
  try {
692
- return await Promise.race([promise, new Promise((_resolve, reject) => { abort = () => reject(signal.reason); signal.addEventListener("abort", abort, { once: true }); })]);
913
+ return await Promise.race([
914
+ promise,
915
+ new Promise((_resolve, reject) => {
916
+ abort = () => reject(signal.reason);
917
+ signal.addEventListener("abort", abort, { once: true });
918
+ }),
919
+ ]);
693
920
  }
694
921
  finally {
695
922
  signal.removeEventListener("abort", abort);
@@ -699,7 +926,9 @@ async function* readEvents(response, signal) {
699
926
  const reader = response.body.getReader();
700
927
  const decoder = new TextDecoder();
701
928
  let buffer = "";
702
- const abort = () => { void reader.cancel(signal.reason).catch(() => undefined); };
929
+ const abort = () => {
930
+ void reader.cancel(signal.reason).catch(() => undefined);
931
+ };
703
932
  signal.addEventListener("abort", abort, { once: true });
704
933
  try {
705
934
  for (;;) {
@@ -710,7 +939,11 @@ async function* readEvents(response, signal) {
710
939
  while ((boundary = buffer.indexOf("\n\n")) >= 0) {
711
940
  const packet = buffer.slice(0, boundary);
712
941
  buffer = buffer.slice(boundary + 2);
713
- const data = packet.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart()).join("\n");
942
+ const data = packet
943
+ .split("\n")
944
+ .filter((line) => line.startsWith("data:"))
945
+ .map((line) => line.slice(5).trimStart())
946
+ .join("\n");
714
947
  if (data) {
715
948
  signal.throwIfAborted();
716
949
  yield EventSchemas.parse(JSON.parse(data));
@@ -731,4 +964,3 @@ async function* readEvents(response, signal) {
731
964
  reader.releaseLock();
732
965
  }
733
966
  }
734
- //# sourceMappingURL=client.js.map