@nexface/chat 0.1.14 → 0.1.15-alpha.0

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