@nexface/chat 0.1.6 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.js CHANGED
@@ -433,16 +433,13 @@ class ChatClientImplementation {
433
433
  const response = await abortable(this.#runHandler(input, { signal }), signal);
434
434
  if (!response.ok || !response.body)
435
435
  throw new ClientError("CHAT_REQUEST_FAILED", `Agent request failed (${response.status}).`);
436
+ let terminal;
436
437
  let terminalEvent;
437
438
  let messageSnapshot;
438
439
  let stateSnapshot;
439
440
  let started = false;
440
441
  for await (const event of readEvents(response, signal)) {
441
442
  if (event.type === EventType.RUN_ERROR) {
442
- if (started && messageSnapshot && stateSnapshot) {
443
- terminalEvent = event;
444
- break;
445
- }
446
443
  this.#event(event);
447
444
  throw new ClientError(event.code ?? "CHAT_RUN_ERROR", event.message);
448
445
  }
@@ -470,6 +467,7 @@ class ChatClientImplementation {
470
467
  if (event.type === EventType.RUN_FINISHED) {
471
468
  if (!started || !event.outcome || !messageSnapshot || !stateSnapshot)
472
469
  throw new ClientError("CHAT_STREAM_INCOMPLETE", "Agent terminal is missing its recovery snapshots or outcome.");
470
+ terminal = { ...event.result, outcome: event.outcome };
473
471
  terminalEvent = event;
474
472
  break;
475
473
  }
@@ -477,11 +475,11 @@ class ChatClientImplementation {
477
475
  throw new ClientError("CHAT_STREAM_INCOMPLETE", "Unexpected event between recovery snapshots and terminal.");
478
476
  this.#event(event);
479
477
  }
480
- if (!terminalEvent || !messageSnapshot || !stateSnapshot)
478
+ if (!terminal || !terminalEvent || !messageSnapshot || !stateSnapshot)
481
479
  throw new ClientError("CHAT_STREAM_INCOMPLETE", "Agent stream ended without complete recovery snapshots.");
482
480
  let decoded;
483
481
  try {
484
- decoded = decodeAgentResponse(messageSnapshot.messages, stateSnapshot.snapshot, terminalEvent, this.id);
482
+ decoded = decodeAgentResponse(messageSnapshot.messages, stateSnapshot.snapshot, terminalEvent);
485
483
  }
486
484
  catch (error) {
487
485
  throw new ClientError("CHAT_STREAM_INCOMPLETE", error instanceof Error ? error.message : "Invalid Agent recovery response.");
@@ -495,10 +493,6 @@ class ChatClientImplementation {
495
493
  this.#event(stateSnapshot);
496
494
  this.#event(terminalEvent);
497
495
  };
498
- if (decoded.type === "error") {
499
- commit();
500
- throw new ClientError(decoded.code, decoded.message);
501
- }
502
496
  if (decoded.type === "success") {
503
497
  commit();
504
498
  return decoded.result;
@@ -568,10 +562,7 @@ class ChatClientImplementation {
568
562
  signal.throwIfAborted();
569
563
  if (error instanceof ClientError && error.code === "TOOL_CONFIRMATION_INVALIDATED")
570
564
  throw error;
571
- const code = error instanceof ClientError || isToolRuntimeError(error) ? error.code : "TOOL_ERROR";
572
- // An executor error cannot establish that the outer tool was never executed.
573
- const executionError = code === "TOOL_CONFIRMATION_REJECTED" && this.#executingBrowserCall === action.toolCallId;
574
- return { toolCallId: action.toolCallId, error: { code: executionError ? "TOOL_ERROR" : code, message: error instanceof Error ? error.message : String(error) }, ...(confirmed ? { confirmed } : {}) };
565
+ return { toolCallId: action.toolCallId, error: { code: error instanceof ClientError || isToolRuntimeError(error) ? error.code : "TOOL_ERROR", message: error instanceof Error ? error.message : String(error) }, ...(confirmed ? { confirmed } : {}) };
575
566
  }
576
567
  finally {
577
568
  if (!signal.aborted)
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAwI,MAAM,gBAAgB,CAAC;AACnL,OAAO,EAAE,mBAAmB,EAAmD,MAAM,wBAAwB,CAAC;AAC9G,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAEpD,OAAO,EAAE,sBAAsB,EAAE,sBAAsB,EAAE,MAAM,yBAAyB,CAAC;AACzF,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,uBAAuB,EAAgB,MAAM,aAAa,CAAC;AAC1I,OAAO,EAAE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EAAE,KAAK,CAAC,CAAC;QAC3C,sDAAsD;QACtD,KAAK,MAAM,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;QAC5C,MAAM,CAAC,WAAW,EAAE,CAAC;IACvB,CAAC;AACH,CAAC","sourcesContent":["import { createAgent, type Agent, type AgentInputContent, type AgentMessage, type AgentRun, type AgentRunResult, type RunAgentInput, type AgentModelConfig } from \"@nexface/agent\";\nimport { decodeAgentResponse, type BrowserToolResult, type AgentBrowserAction } from \"./protocol-response.js\";\nimport { isToolRuntimeError } from \"@nexface/tools\";\nimport type { RuntimeAgentTool, ToolOperation, ToolRuntime } from \"@nexface/tools\";\nimport { getInternalToolRuntime, validateAgentToolInput } from \"@nexface/tools/internal\";\nimport { EventType, EventSchemas, RunAgentInputSchema, TextInputContentSchema, ImageInputContentSchema, type Message } from \"@ag-ui/core\";\nimport { createMessageUpdater, restoreMessages, settleApproval, type ProtocolEvent } from \"./protocol-messages.js\";\nimport { resolveModelConfig, type NexfaceAgentConfig } from \"./config.js\";\nimport { type UIMessage } from \"./messages.js\";\n\nexport type { Message } from \"@ag-ui/core\";\nexport type { ProtocolEvent } from \"./protocol-messages.js\";\nexport type { ToolApprovalInterruptDescriptor } from \"@nexface/agent\";\nimport type { ToolApprovalInterruptDescriptor } from \"@nexface/agent\";\nexport type ChatClientStatus = \"idle\" | \"running\" | \"waiting\" | \"error\";\nexport type RunHandler = (input: RunAgentInput, options: { signal: AbortSignal }) => Promise<Response>;\nexport type ChatClientOptions = { toolRuntime: ToolRuntime } & (\n | { agent: NexfaceAgentConfig; run?: never }\n | { run: RunHandler; agent?: never }\n);\nexport interface ChatClient {\n getMessages(): readonly Message[];\n subscribeEvents(listener: (event: ProtocolEvent) => void): () => void;\n getStatus(): ChatClientStatus;\n getApproval(): ToolApprovalInterruptDescriptor | undefined;\n getError(): Error | undefined;\n /**\n * @experimental State subscriptions may change in future releases.\n * @beta\n */\n subscribe(listener: () => void): () => void;\n sendMessage(content: string | readonly AgentInputContent[]): Promise<Extract<AgentRunResult, { outcome: { type: \"success\" } }>>;\n respondToApproval(id: string, response: { approved: boolean }): Promise<void>;\n cancel(): void;\n dispose(): void;\n}\n\ninterface AgentController {\n conversationBefore(messageId: string): { messages: readonly AgentMessage[]; replay?: unknown };\n restoreConversation(messages: readonly AgentMessage[], replay?: unknown): void;\n settle(id: string, decision: { type: \"cancel\" } | { type: \"invalidate\"; message: string; reason: string }, receipts?: readonly Message[]): boolean;\n authorizePageResponse(response: object): void;\n setPageConfirmationResolver(resolver: (name: string) => boolean): void;\n}\nconst controllerSymbol = Symbol.for(\"@nexface/agent/chat-controller\");\nconst agentController = (agent: Agent) => (agent as Agent & { [controllerSymbol]: AgentController })[controllerSymbol];\nconst id = () => globalThis.crypto.randomUUID();\nconst abortError = () => new DOMException(\"Agent task cancelled.\", \"AbortError\");\nexport class ClientError extends Error {\n readonly type = \"chat_error\" as const;\n constructor(readonly code: string, message: string) { super(message); this.name = \"ChatError\"; }\n}\n\nclass SubscriptionError extends Error {\n constructor(readonly failure: unknown) {\n super(failure instanceof Error ? failure.message : String(failure));\n }\n}\n\nexport function createChatClient(options: ChatClientOptions): ChatClient {\n return new ChatClientImplementation(options);\n}\n\n// This controller is package-private; page confirmation remains Provider-owned.\nexport function getClientController(client: ChatClient): ChatClientImplementation {\n if (!(client instanceof ChatClientImplementation)) throw new TypeError(\"Invalid ChatClient.\");\n return client;\n}\n\nclass ChatClientImplementation implements ChatClient {\n id: string = id();\n readonly agent: Agent | undefined;\n readonly #options: ChatClientOptions;\n #model: AgentModelConfig | undefined;\n readonly runtime: ToolRuntime;\n readonly #runHandler: RunHandler | undefined;\n #messages: Message[] = [];\n #updateMessages = createMessageUpdater();\n #eventListeners = new Set<(event: ProtocolEvent) => void>();\n #status: ChatClientStatus = \"idle\";\n #error: Error | undefined;\n #listeners = new Set<() => void>();\n #controller: AbortController | undefined;\n #activeRun: AgentRun | undefined;\n #operation: ToolOperation | undefined;\n #disposed = false;\n #state: unknown;\n #stateBeforeLastMessage: unknown;\n #resumeBeforeLastMessage: RunAgentInput[\"resume\"];\n #recoveryUnavailable = false;\n #remoteInterruptId: string | undefined;\n #cancelledResume: RunAgentInput[\"resume\"];\n #task: Promise<Extract<AgentRunResult, { outcome: { type: \"success\" } }>> | undefined;\n #replacement: { cancelled: boolean } | undefined;\n #approval: ToolApprovalInterruptDescriptor | undefined;\n #pending: { resolve(approved: boolean): void; reject(error: Error): void; cleanup(): void } | undefined;\n #settled = new Map<string, () => void>();\n #hasPageHook = (_name: string) => false;\n #cancelled = false;\n #executingBrowserCall: string | undefined;\n\n constructor(options: ChatClientOptions, model?: AgentModelConfig) {\n if (!options?.toolRuntime || Boolean(options.agent) === Boolean(options.run)) throw new ClientError(\"INVALID_INPUT\", \"Provide exactly one agent config or run function and a ToolRuntime.\");\n this.#options = options;\n this.#model = options.agent ? model ?? resolveModelConfig(options.agent.model) : undefined;\n this.runtime = options.toolRuntime;\n this.#runHandler = options.run;\n this.agent = options.agent ? createAgent({ ...options.agent, model: this.#model!, toolRuntime: this.runtime }) : undefined;\n }\n getMessages = (): readonly Message[] => this.#messages;\n getStatus = (): ChatClientStatus => this.#status;\n getApproval = (): ToolApprovalInterruptDescriptor | undefined => this.#approval;\n getError = (): Error | undefined => this.#error;\n subscribe = (listener: () => void): (() => void) => { this.#listeners.add(listener); return () => { this.#listeners.delete(listener); }; };\n subscribeEvents = (listener: (event: ProtocolEvent) => void): (() => void) => { this.#eventListeners.add(listener); return () => { this.#eventListeners.delete(listener); }; };\n #publish(): void {\n for (const listener of this.#listeners) {\n try { listener(); }\n catch (error) { this.#listeners.delete(listener); throw new SubscriptionError(error); }\n }\n }\n get cancelling(): boolean { return Boolean(this.#controller?.signal.aborted); }\n get busy(): boolean { return Boolean(this.#controller); }\n setPageResolver(resolver: (name: string) => boolean): void {\n this.#hasPageHook = resolver;\n if (this.agent) agentController(this.agent).setPageConfirmationResolver(resolver);\n }\n restore(messages: UIMessage[], conversation: readonly AgentMessage[]): void {\n if (this.busy || this.#messages.length) throw new Error(\"Restore requires a new Client.\");\n this.#messages = restoreMessages(structuredClone(messages));\n if (this.agent) agentController(this.agent).restoreConversation(conversation);\n }\n recreateBefore(messageId: string): ChatClient {\n if (this.busy || this.#disposed) throw new ClientError(\"CHAT_RUN_ACTIVE\", \"Wait for the active task to finish.\");\n const index = this.#messages.findIndex((message) => message.role === \"user\" && message.id === messageId);\n if (index < 0 || this.#messages.slice(index + 1).some((message) => message.role === \"user\")) throw new ClientError(\"INVALID_INPUT\", \"Only the last user message can be edited.\");\n const client = new ChatClientImplementation(this.#options, this.#model);\n client.id = this.id;\n client.setPageResolver(this.#hasPageHook);\n client.#messages = structuredClone(this.#messages.slice(0, index));\n client.#state = this.#stateBeforeLastMessage;\n client.#cancelledResume = this.#resumeBeforeLastMessage;\n if (this.agent) {\n const retained = agentController(this.agent).conversationBefore(messageId);\n agentController(client.agent!).restoreConversation(retained.messages, retained.replay);\n }\n return client;\n }\n async switchModel(model: AgentModelConfig): Promise<void> {\n if (!this.agent || this.busy) throw new ClientError(\"CHAT_MODEL_SWITCH_BLOCKED\", \"Model switching is unavailable.\");\n await this.agent.switchModel(model);\n this.#model = model;\n this.#publish();\n }\n #event(event: ProtocolEvent): void {\n if (event.type === EventType.RUN_STARTED || event.type === EventType.RUN_FINISHED) event = { ...event, threadId: this.id };\n this.#messages = this.#updateMessages(this.#messages, event);\n if (event.type === EventType.TOOL_CALL_RESULT) { this.#settled.get(event.toolCallId)?.(); this.#settled.delete(event.toolCallId); }\n if (event.type === EventType.CUSTOM && event.name === \"nexface.tool-execution\" && this.#operation) {\n const value = event.value as { status: string; toolCallId: string; progressLabel?: string };\n const runtime = getInternalToolRuntime(this.runtime);\n const current = runtime.getActivitySnapshot().operation?.taskProgress;\n if (value.status === \"running\") runtime.setTaskProgress(this.#operation, { phase: \"tool\", toolCallId: value.toolCallId, ...(value.progressLabel ? { progressLabel: value.progressLabel } : {}) });\n else if (current?.phase === \"tool\" && current.toolCallId === value.toolCallId) runtime.setTaskProgress(this.#operation, { phase: \"processing\" });\n }\n this.#publish();\n for (const listener of this.#eventListeners) {\n try { listener(event); }\n catch (error) { this.#eventListeners.delete(listener); throw new SubscriptionError(error); }\n }\n }\n sendMessage = (content: string | readonly AgentInputContent[]) => this.send(content);\n async send(content: string | readonly AgentInputContent[], userMessage?: UIMessage): Promise<Extract<AgentRunResult, { outcome: { type: \"success\" } }>> {\n if (this.#disposed || this.#replacement) throw new ClientError(\"CHAT_RUN_ACTIVE\", \"The Client is disposed or already replacing a task.\");\n try {\n content = typeof content === \"string\" ? content.trim() : content.map((part) =>\n part.type === \"text\" ? TextInputContentSchema.parse(part) : ImageInputContentSchema.parse(part));\n if (!content.length) throw new Error(\"Chat message is required.\");\n } catch (error) { throw new ClientError(\"INVALID_INPUT\", error instanceof Error ? error.message : \"Invalid chat message.\"); }\n if (this.busy) {\n if (this.#status !== \"waiting\" || !this.#pending || !this.#task) throw new ClientError(\"CHAT_RUN_ACTIVE\", \"The Client is already running.\");\n const replacement = { cancelled: false };\n this.#replacement = replacement;\n try {\n let cancellationFailure: unknown;\n try { this.#cancelCurrent(); } catch (error) { cancellationFailure = error; }\n await this.#task.catch(() => undefined);\n if (cancellationFailure) throw cancellationFailure instanceof SubscriptionError ? cancellationFailure.failure : cancellationFailure;\n if (replacement.cancelled || this.#disposed) throw abortError();\n } finally { this.#replacement = undefined; }\n }\n if (this.#recoveryUnavailable) {\n this.#error = new ClientError(\"CHAT_RECOVERY_UNAVAILABLE\", \"The previous task has no complete recovery state. Start a new conversation to continue.\");\n this.#status = \"error\";\n this.#publish();\n throw this.#error;\n }\n const task = this.#send(content, userMessage);\n this.#task = task;\n const clear = () => { if (this.#task === task) this.#task = undefined; };\n void task.then(clear, clear);\n return task;\n }\n async #send(content: string | readonly AgentInputContent[], userMessage?: UIMessage): Promise<Extract<AgentRunResult, { outcome: { type: \"success\" } }>> {\n const controller = new AbortController();\n // Claim the Runtime before appending a user message.\n const userId = userMessage?.id ?? id();\n let initialRun: AgentRun | undefined;\n if (this.agent) initialRun = this.agent.run({ messages: [{ id: userId, role: \"user\", content: typeof content === \"string\" ? content : [...content] }] }, { signal: controller.signal });\n else {\n this.#operation = getInternalToolRuntime(this.runtime).beginInternalOperation({ signal: controller.signal, onCancel: () => this.cancel(), taskProgress: { phase: \"processing\" } });\n }\n this.#stateBeforeLastMessage = this.#state;\n this.#resumeBeforeLastMessage = this.#cancelledResume;\n this.#controller = controller;\n this.#cancelled = false;\n this.#executingBrowserCall = undefined;\n this.#status = \"running\";\n this.#error = undefined;\n this.#messages = [...this.#messages, { id: userId, role: \"user\", content: typeof content === \"string\" ? content : [...content], ...(userMessage ? { metadata: { nexface: { restoredParts: userMessage.parts, attachments: userMessage.attachments ?? [], revisionOf: userMessage.revisionOf } } } : {}) }];\n const runtime = getInternalToolRuntime(this.runtime);\n const operationId = runtime.getActivitySnapshot().operation?.id;\n const unsubscribe = runtime.subscribeActivity(() => {\n const operation = runtime.getActivitySnapshot().operation;\n if (operation && operation.id === operationId && operation.status === \"cancelling\" && !controller.signal.aborted) this.cancel();\n });\n let succeeded = false;\n try {\n this.#publish();\n const result = initialRun ? await this.#local(initialRun, controller.signal) : await this.#remote(controller.signal);\n controller.signal.throwIfAborted();\n succeeded = true;\n return result;\n } catch (failure) {\n unsubscribe();\n const failedRun = this.#activeRun ?? initialRun;\n if (failedRun) {\n failedRun.cancel();\n await failedRun.result.catch(() => undefined);\n }\n if (failure instanceof SubscriptionError) failure = failure.failure;\n const record = failure as { name?: unknown; message?: unknown; code?: unknown } | null;\n this.#error = failure instanceof Error ? failure : Object.assign(new Error(typeof record?.message === \"string\" ? record.message : String(failure)), { name: typeof record?.name === \"string\" ? record.name : \"Error\", ...(typeof record?.code === \"string\" ? { code: record.code } : {}) });\n const text = controller.signal.aborted ? \"任务已取消。\" : this.#error.message;\n this.#messages = [\n ...this.#messages.map((message): Message => message.metadata?.nexface?.state === \"running\" ? { ...message, metadata: { ...message.metadata, nexface: { ...message.metadata.nexface, state: \"error\" } } } : message),\n { id: id(), role: \"assistant\", content: text, metadata: { nexface: { state: \"error\" } } },\n ];\n throw this.#error;\n } finally {\n unsubscribe();\n this.#pending?.cleanup(); this.#pending = undefined; this.#approval = undefined;\n if (this.#operation) await this.#operation.end({ outcome: succeeded ? \"completed\" : controller.signal.aborted ? \"cancelled\" : \"failed\" });\n this.#operation = undefined; this.#activeRun = undefined; this.#controller = undefined;\n for (const settle of this.#settled.values()) settle(); this.#settled.clear();\n this.#status = succeeded || controller.signal.aborted ? \"idle\" : \"error\";\n this.#publish();\n }\n }\n async #consume(run: AgentRun): Promise<AgentRunResult> {\n this.#activeRun = run;\n const outcomes = await Promise.allSettled([run.result, (async () => {\n try { for await (const event of run) this.#event(event); }\n catch (error) { run.cancel(); throw error; }\n })()]);\n if (outcomes[1].status === \"rejected\") throw outcomes[1].reason;\n if (outcomes[0].status === \"rejected\") throw outcomes[0].reason;\n return outcomes[0].value;\n }\n async #local(run: AgentRun, signal: AbortSignal): Promise<Extract<AgentRunResult, { outcome: { type: \"success\" } }>> {\n for (;;) {\n const result = await this.#consume(run);\n if (result.outcome.type === \"success\") {\n if (typeof result.output !== \"string\") throw new Error(\"Missing completion output.\");\n return { ...result, outcome: result.outcome, output: result.output };\n }\n const interrupt = result.outcome.interrupts[0];\n const extension = interrupt?.metadata?.nexface;\n if (result.outcome.interrupts.length !== 1 || extension?.kind !== \"tool-approval\") throw new Error(\"Unexpected local interrupt.\");\n const approval = extension.approval as ToolApprovalInterruptDescriptor;\n const tool = this.runtime.getTools().find((item) => item.definition.name === approval.toolName);\n if (!tool) throw new ClientError(\"TOOL_CONFIRMATION_INVALIDATED\", \"Tool Binding was removed.\");\n const approved = await this.#wait(approval, tool, signal);\n if (signal.aborted) {\n this.#messages = settleApproval(this.#messages, approval, \"TOOL_CANCELLED\", \"The pending Tool confirmation was cancelled.\", \"interrupt_cancelled\");\n agentController(this.agent!).settle(approval.id, { type: \"cancel\" }, this.#messages);\n }\n signal.throwIfAborted();\n const response = { interruptId: interrupt!.id, status: \"resolved\" as const, payload: { approved } };\n if (approval.mode === \"page\") agentController(this.agent!).authorizePageResponse(response);\n run = this.agent!.run({ resume: [response] }, { signal });\n }\n }\n #wait(approval: ToolApprovalInterruptDescriptor, tool: RuntimeAgentTool, signal: AbortSignal): Promise<boolean> {\n signal.throwIfAborted();\n this.#approval = Object.freeze(approval);\n this.#status = \"waiting\";\n const waiting = new Promise<boolean>((resolve, reject) => {\n const abort = () => reject(signal.reason);\n const removed = () => this.invalidate(\"Tool Binding was removed.\");\n const cleanup = () => { signal.removeEventListener(\"abort\", abort); tool.lifecycleSignal.removeEventListener(\"abort\", removed); };\n this.#pending = { resolve, reject, cleanup };\n signal.addEventListener(\"abort\", abort, { once: true });\n tool.lifecycleSignal.addEventListener(\"abort\", removed, { once: true });\n if (tool.lifecycleSignal.aborted) removed();\n });\n this.#operation?.setWaitingForUser(true);\n this.#publish();\n return waiting;\n }\n async #respond(id: string, approved: boolean, source: \"chat\" | \"page\"): Promise<void> {\n const pending = this.#pending;\n if (!pending || this.#approval?.id !== id || this.#approval.mode !== source || typeof approved !== \"boolean\" || (source === \"page\" && !approved)) throw new ClientError(\"INVALID_INPUT\", \"Confirmation is no longer pending or has the wrong source.\");\n pending.cleanup(); this.#pending = undefined; this.#approval = undefined;\n this.#status = \"running\"; this.#operation?.setWaitingForUser(false);\n pending.resolve(approved); this.#publish();\n }\n respondToApproval = (id: string, response: { approved: boolean }): Promise<void> => this.#respond(id, response.approved, \"chat\");\n confirmPage(): Promise<void> | undefined {\n const approval = this.#approval;\n if (approval?.mode !== \"page\") return;\n const settled = new Promise<void>((resolve) => this.#settled.set(approval.toolCallId, resolve));\n void this.#respond(approval.id, true, \"page\").catch(() => { this.#settled.get(approval.toolCallId)?.(); this.#settled.delete(approval.toolCallId); });\n return settled;\n }\n invalidate(message: string): void {\n const approval = this.#approval;\n if (!approval) return;\n this.#messages = settleApproval(this.#messages, approval, \"TOOL_CONFIRMATION_INVALIDATED\", message, \"binding_changed\");\n if (this.agent) {\n agentController(this.agent).settle(approval.id, { type: \"invalidate\", message, reason: \"binding_changed\" }, this.#messages);\n }\n this.#queueRemoteCancellation();\n const pending = this.#pending;\n pending?.cleanup(); this.#pending = undefined; this.#approval = undefined;\n this.#status = \"running\"; this.#operation?.setWaitingForUser(false);\n pending?.reject(new ClientError(\"TOOL_CONFIRMATION_INVALIDATED\", message));\n this.#publish();\n }\n cancel = (): void => {\n if (this.#replacement) this.#replacement.cancelled = true;\n this.#cancelCurrent();\n };\n #queueRemoteCancellation(): void {\n if (this.#remoteInterruptId) this.#cancelledResume = [{ interruptId: this.#remoteInterruptId, status: \"cancelled\" }];\n }\n #cancelCurrent(): void {\n if (!this.#controller || this.#cancelled) return;\n this.#cancelled = true;\n if (this.#approval) {\n this.#messages = settleApproval(this.#messages, this.#approval, \"TOOL_CANCELLED\", \"The pending Tool confirmation was cancelled.\", \"interrupt_cancelled\");\n if (this.agent) agentController(this.agent).settle(this.#approval.id, { type: \"cancel\" }, this.#messages);\n this.#queueRemoteCancellation();\n }\n const pending = this.#pending;\n pending?.cleanup(); this.#pending = undefined; this.#approval = undefined;\n this.#controller.abort(abortError());\n pending?.reject(this.#controller.signal.reason);\n this.#activeRun?.cancel(); this.#publish();\n }\n dispose = (): void => { if (this.#disposed) return; this.#disposed = true; this.cancel(); this.#listeners.clear(); this.#eventListeners.clear(); };\n\n async #remote(signal: AbortSignal): Promise<Extract<AgentRunResult, { outcome: { type: \"success\" } }>> {\n let resume = this.#cancelledResume;\n let inFlight = false;\n let completedBrowserCall = false;\n try {\n for (;;) {\n signal.throwIfAborted();\n const catalog = [...this.runtime.getTools()];\n const contexts = await this.runtime.getContexts({ signal });\n const runId = id();\n const input: RunAgentInput = {\n threadId: this.id, runId, messages: this.#messages, state: this.#state ?? null,\n ...(resume ? { resume } : {}),\n tools: catalog.map(({ definition }) => ({ name: definition.name, description: definition.description, parameters: definition.inputSchema ?? { type: \"object\", properties: {} } })),\n context: contexts.map((context) => ({ description: context.description ?? context.name, value: JSON.stringify(context) })),\n forwardedProps: { nexface: { version: 3,\n toolMetadata: Object.fromEntries(catalog.map(({ definition }) => [definition.name, { ...(definition.effect ? { effect: definition.effect } : {}) }])),\n } },\n };\n RunAgentInputSchema.parse(input);\n inFlight = true;\n completedBrowserCall = false;\n this.#remoteInterruptId = undefined;\n const response = await abortable(this.#runHandler!(input, { signal }), signal);\n if (!response.ok || !response.body) throw new ClientError(\"CHAT_REQUEST_FAILED\", `Agent request failed (${response.status}).`);\n let terminalEvent: Extract<ProtocolEvent, { type: EventType.RUN_FINISHED | EventType.RUN_ERROR }> | undefined;\n let messageSnapshot: Extract<ProtocolEvent, { type: EventType.MESSAGES_SNAPSHOT }> | undefined;\n let stateSnapshot: Extract<ProtocolEvent, { type: EventType.STATE_SNAPSHOT }> | undefined;\n let started = false;\n for await (const event of readEvents(response, signal)) {\n if (event.type === EventType.RUN_ERROR) {\n if (started && messageSnapshot && stateSnapshot) {\n terminalEvent = event;\n break;\n }\n this.#event(event);\n throw new ClientError(event.code ?? \"CHAT_RUN_ERROR\", event.message);\n }\n if (event.type === EventType.RUN_STARTED || event.type === EventType.RUN_FINISHED) {\n if (event.threadId !== this.id || event.runId !== runId) throw new Error(\"Agent response identity does not match its request.\");\n }\n if (event.type === EventType.RUN_STARTED) {\n if (started) throw new Error(\"Duplicate Agent start event.\");\n started = true;\n }\n if (event.type === EventType.MESSAGES_SNAPSHOT) {\n if (messageSnapshot || stateSnapshot) throw new ClientError(\"CHAT_STREAM_INCOMPLETE\", \"Invalid recovery snapshot order.\");\n messageSnapshot = event;\n continue;\n }\n if (event.type === EventType.STATE_SNAPSHOT) {\n if (!messageSnapshot || stateSnapshot) throw new ClientError(\"CHAT_STREAM_INCOMPLETE\", \"Invalid recovery snapshot order.\");\n stateSnapshot = event;\n continue;\n }\n if (event.type === EventType.RUN_FINISHED) {\n if (!started || !event.outcome || !messageSnapshot || !stateSnapshot) throw new ClientError(\"CHAT_STREAM_INCOMPLETE\", \"Agent terminal is missing its recovery snapshots or outcome.\");\n terminalEvent = event;\n break;\n }\n if (messageSnapshot) throw new ClientError(\"CHAT_STREAM_INCOMPLETE\", \"Unexpected event between recovery snapshots and terminal.\");\n this.#event(event);\n }\n if (!terminalEvent || !messageSnapshot || !stateSnapshot) throw new ClientError(\"CHAT_STREAM_INCOMPLETE\", \"Agent stream ended without complete recovery snapshots.\");\n let decoded: ReturnType<typeof decodeAgentResponse>;\n try { decoded = decodeAgentResponse(messageSnapshot.messages, stateSnapshot.snapshot, terminalEvent, this.id); }\n catch (error) { throw new ClientError(\"CHAT_STREAM_INCOMPLETE\", error instanceof Error ? error.message : \"Invalid Agent recovery response.\"); }\n const commit = () => {\n // Only a complete terminal commits the matching messages and state.\n this.#state = structuredClone(stateSnapshot.snapshot);\n this.#cancelledResume = undefined;\n inFlight = false;\n this.#event(messageSnapshot);\n this.#event(stateSnapshot);\n this.#event(terminalEvent);\n };\n if (decoded.type === \"error\") {\n commit();\n throw new ClientError(decoded.code, decoded.message);\n }\n if (decoded.type === \"success\") {\n commit();\n return decoded.result;\n }\n this.#remoteInterruptId = decoded.interruptId;\n commit();\n const toolResult = await this.#browserAction(decoded.action, catalog, signal);\n completedBrowserCall = true;\n const messageId = id();\n this.#event({ type: EventType.TOOL_CALL_RESULT, messageId, role: \"tool\", toolCallId: toolResult.toolCallId, content: JSON.stringify(toolResult.error ? { error: toolResult.error } : { result: toolResult.result ?? null }) });\n resume = [{ interruptId: decoded.interruptId, status: \"resolved\", payload: { toolResultMessageId: messageId, ...(toolResult.confirmed ? { confirmed: true } : {}) } }];\n }\n } catch (error) {\n const unknown = inFlight || completedBrowserCall || this.#executingBrowserCall !== undefined;\n if (unknown) this.#recoveryUnavailable = true;\n else this.#queueRemoteCancellation();\n const lastUser = this.#messages.reduce((last, message, index) => message.role === \"user\" ? index : last, -1);\n const current = this.#messages.slice(lastUser);\n for (const [index, message] of current.entries()) if (message.role === \"assistant\" && message.toolCalls?.length) {\n const following = current.slice(index + 1);\n const nextBatch = following.findIndex((item) => item.role === \"assistant\" && Boolean(item.toolCalls?.length));\n const receipts = nextBatch < 0 ? following : following.slice(0, nextBatch);\n for (const call of message.toolCalls) {\n if (receipts.some((item) => item.role === \"tool\" && item.toolCallId === call.id)) continue;\n const unknown = inFlight || this.#executingBrowserCall === call.id;\n this.#event({ type: EventType.TOOL_CALL_RESULT, messageId: id(), role: \"tool\", toolCallId: call.id, content: JSON.stringify({ error: { code: unknown ? \"EXECUTION_OUTCOME_UNKNOWN\" : \"TOOL_CANCELLED\", message: unknown ? \"The execution outcome is unknown; this call may have executed.\" : \"Task ended before execution.\" } }) });\n }\n }\n throw error;\n }\n }\n async #browserAction(action: AgentBrowserAction, catalog: RuntimeAgentTool[], signal: AbortSignal): Promise<BrowserToolResult> {\n let confirmed = false;\n this.#executingBrowserCall = undefined;\n try {\n if (!action || typeof action.toolCallId !== \"string\" || !action.definition) throw new Error(\"Invalid browser action.\");\n const tool = catalog.find((item) => JSON.stringify(item.definition) === JSON.stringify(action.definition));\n if (!tool || !this.runtime.getTools().includes(tool)) throw new ClientError(\"TOOL_CONFIRMATION_INVALIDATED\", \"The original Tool Binding is no longer available.\");\n const errors = validateAgentToolInput(tool.definition.inputSchema, action.input);\n if (errors.length) throw new ClientError(\"INVALID_INPUT\", errors.join(\" \"));\n const confirmation = tool.confirmation;\n if (confirmation) {\n if (confirmation.mode === \"page\" && !this.#hasPageHook(tool.definition.name)) throw new ClientError(\"TOOL_CONFIRMATION_UNAVAILABLE\", \"An active usePageConfirmation Hook is required.\");\n confirmed = true;\n const approval = { ...confirmation, type: \"tool-approval\" as const, id: id(), runId: this.id, toolCallId: action.toolCallId, toolName: tool.definition.name, input: structuredClone(action.input) };\n const approved = await this.#wait(approval, tool, signal);\n if (!approved) throw new ClientError(\"TOOL_CONFIRMATION_REJECTED\", \"The user rejected this tool call.\");\n }\n signal.throwIfAborted();\n this.#executingBrowserCall = action.toolCallId;\n const result = await getInternalToolRuntime(this.runtime).executeWithProgress(tool, action.input, { signal, ...(action.progressLabel ? { progressLabel: action.progressLabel } : {}) });\n return { toolCallId: action.toolCallId, result: result ?? null, ...(confirmed ? { confirmed } : {}) };\n } catch (error) {\n if (error instanceof SubscriptionError) throw error;\n signal.throwIfAborted();\n if (error instanceof ClientError && error.code === \"TOOL_CONFIRMATION_INVALIDATED\") throw error;\n const code = error instanceof ClientError || isToolRuntimeError(error) ? error.code : \"TOOL_ERROR\";\n // An executor error cannot establish that the outer tool was never executed.\n const executionError = code === \"TOOL_CONFIRMATION_REJECTED\" && this.#executingBrowserCall === action.toolCallId;\n return { toolCallId: action.toolCallId, error: { code: executionError ? \"TOOL_ERROR\" : code, message: error instanceof Error ? error.message : String(error) }, ...(confirmed ? { confirmed } : {}) };\n } finally {\n if (!signal.aborted) this.#executingBrowserCall = undefined;\n this.#settled.get(action.toolCallId)?.(); this.#settled.delete(action.toolCallId);\n }\n }\n}\n\nasync function abortable<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {\n signal.throwIfAborted();\n let abort!: () => void;\n try { return await Promise.race([promise, new Promise<never>((_resolve, reject) => { abort = () => reject(signal.reason); signal.addEventListener(\"abort\", abort, { once: true }); })]); }\n finally { signal.removeEventListener(\"abort\", abort); }\n}\n\nasync function* readEvents(response: Response, signal: AbortSignal): AsyncGenerator<ProtocolEvent> {\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n const abort = () => { void reader.cancel(signal.reason).catch(() => undefined); };\n signal.addEventListener(\"abort\", abort, { once: true });\n try {\n for (;;) {\n signal.throwIfAborted();\n const next = await reader.read();\n buffer = (buffer + decoder.decode(next.value, { stream: !next.done })).replace(/\\r\\n/g, \"\\n\");\n let boundary: number;\n while ((boundary = buffer.indexOf(\"\\n\\n\")) >= 0) {\n const packet = buffer.slice(0, boundary); buffer = buffer.slice(boundary + 2);\n const data = packet.split(\"\\n\").filter((line) => line.startsWith(\"data:\")).map((line) => line.slice(5).trimStart()).join(\"\\n\");\n if (data) { signal.throwIfAborted(); yield EventSchemas.parse(JSON.parse(data)); }\n }\n if (next.done) { signal.throwIfAborted(); if (buffer.trim()) throw new Error(\"Truncated SSE event.\"); return; }\n }\n } finally {\n signal.removeEventListener(\"abort\", abort);\n // Transport cleanup must not delay terminal delivery.\n void reader.cancel().catch(() => undefined);\n reader.releaseLock();\n }\n}\n"]}
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAwI,MAAM,gBAAgB,CAAC;AACnL,OAAO,EAAE,mBAAmB,EAAmD,MAAM,wBAAwB,CAAC;AAC9G,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAEpD,OAAO,EAAE,sBAAsB,EAAE,sBAAsB,EAAE,MAAM,yBAAyB,CAAC;AACzF,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,uBAAuB,EAAgB,MAAM,aAAa,CAAC;AAC1I,OAAO,EAAE,oBAAoB,EAAE,eAAe,EAAE,cAAc,EAAsB,MAAM,wBAAwB,CAAC;AACnH,OAAO,EAAE,kBAAkB,EAA2B,MAAM,aAAa,CAAC;AAqC1E,MAAM,gBAAgB,GAAG,MAAM,CAAC,GAAG,CAAC,gCAAgC,CAAC,CAAC;AACtE,MAAM,eAAe,GAAG,CAAC,KAAY,EAAE,EAAE,CAAE,KAAyD,CAAC,gBAAgB,CAAC,CAAC;AACvH,MAAM,EAAE,GAAG,GAAG,EAAE,CAAC,UAAU,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC;AAChD,MAAM,UAAU,GAAG,GAAG,EAAE,CAAC,IAAI,YAAY,CAAC,uBAAuB,EAAE,YAAY,CAAC,CAAC;AACjF,MAAM,OAAO,WAAY,SAAQ,KAAK;IAEf;IADZ,IAAI,GAAG,YAAqB,CAAC;I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AI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC;gBAAC,CAAC;YACpF,CAAC;YACD,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;gBAAC,MAAM,CAAC,cAAc,EAAE,CAAC;gBAAC,IAAI,MAAM,CAAC,IAAI,EAAE;oBAAE,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC,CAAC;gBAAC,OAAO;YAAC,CAAC;QACjH,CAAC;IACH,CAAC;YAAS,CAAC;QACT,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;QAC3C,sDAAsD;QACtD,KAAK,MAAM,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;QAC5C,MAAM,CAAC,WAAW,EAAE,CAAC;IACvB,CAAC;AACH,CAAC","sourcesContent":["import { createAgent, type Agent, type AgentInputContent, type AgentMessage, type AgentRun, type AgentRunResult, type RunAgentInput, type AgentModelConfig } from \"@nexface/agent\";\nimport { decodeAgentResponse, type BrowserToolResult, type AgentBrowserAction } from \"./protocol-response.js\";\nimport { isToolRuntimeError } from \"@nexface/tools\";\nimport type { RuntimeAgentTool, ToolOperation, ToolRuntime } from \"@nexface/tools\";\nimport { getInternalToolRuntime, validateAgentToolInput } from \"@nexface/tools/internal\";\nimport { EventType, EventSchemas, RunAgentInputSchema, TextInputContentSchema, ImageInputContentSchema, type Message } from \"@ag-ui/core\";\nimport { createMessageUpdater, restoreMessages, settleApproval, type ProtocolEvent } from \"./protocol-messages.js\";\nimport { resolveModelConfig, type NexfaceAgentConfig } from \"./config.js\";\nimport { type UIMessage } from \"./messages.js\";\n\nexport type { Message } from \"@ag-ui/core\";\nexport type { ProtocolEvent } from \"./protocol-messages.js\";\nexport type { ToolApprovalInterruptDescriptor } from \"@nexface/agent\";\nimport type { ToolApprovalInterruptDescriptor } from \"@nexface/agent\";\nexport type ChatClientStatus = \"idle\" | \"running\" | \"waiting\" | \"error\";\nexport type RunHandler = (input: RunAgentInput, options: { signal: AbortSignal }) => Promise<Response>;\nexport type ChatClientOptions = { toolRuntime: ToolRuntime } & (\n | { agent: NexfaceAgentConfig; run?: never }\n | { run: RunHandler; agent?: never }\n);\nexport interface ChatClient {\n getMessages(): readonly Message[];\n subscribeEvents(listener: (event: ProtocolEvent) => void): () => void;\n getStatus(): ChatClientStatus;\n getApproval(): ToolApprovalInterruptDescriptor | undefined;\n getError(): Error | undefined;\n /**\n * @experimental State subscriptions may change in future releases.\n * @beta\n */\n subscribe(listener: () => void): () => void;\n sendMessage(content: string | readonly AgentInputContent[]): Promise<Extract<AgentRunResult, { outcome: { type: \"success\" } }>>;\n respondToApproval(id: string, response: { approved: boolean }): Promise<void>;\n cancel(): void;\n dispose(): void;\n}\n\ninterface AgentController {\n conversationBefore(messageId: string): { messages: readonly AgentMessage[]; replay?: unknown };\n restoreConversation(messages: readonly AgentMessage[], replay?: unknown): void;\n settle(id: string, decision: { type: \"cancel\" } | { type: \"invalidate\"; message: string; reason: string }, receipts?: readonly Message[]): boolean;\n authorizePageResponse(response: object): void;\n setPageConfirmationResolver(resolver: (name: string) => boolean): void;\n}\nconst controllerSymbol = Symbol.for(\"@nexface/agent/chat-controller\");\nconst agentController = (agent: Agent) => (agent as Agent & { [controllerSymbol]: AgentController })[controllerSymbol];\nconst id = () => globalThis.crypto.randomUUID();\nconst abortError = () => new DOMException(\"Agent task cancelled.\", \"AbortError\");\nexport class ClientError extends Error {\n readonly type = \"chat_error\" as const;\n constructor(readonly code: string, message: string) { super(message); this.name = \"ChatError\"; }\n}\n\nclass SubscriptionError extends Error {\n constructor(readonly failure: unknown) {\n super(failure instanceof Error ? failure.message : String(failure));\n }\n}\n\nexport function createChatClient(options: ChatClientOptions): ChatClient {\n return new ChatClientImplementation(options);\n}\n\n// This controller is package-private; page confirmation remains Provider-owned.\nexport function getClientController(client: ChatClient): ChatClientImplementation {\n if (!(client instanceof ChatClientImplementation)) throw new TypeError(\"Invalid ChatClient.\");\n return client;\n}\n\nclass ChatClientImplementation implements ChatClient {\n id: string = id();\n readonly agent: Agent | undefined;\n readonly #options: ChatClientOptions;\n #model: AgentModelConfig | undefined;\n readonly runtime: ToolRuntime;\n readonly #runHandler: RunHandler | undefined;\n #messages: Message[] = [];\n #updateMessages = createMessageUpdater();\n #eventListeners = new Set<(event: ProtocolEvent) => void>();\n #status: ChatClientStatus = \"idle\";\n #error: Error | undefined;\n #listeners = new Set<() => void>();\n #controller: AbortController | undefined;\n #activeRun: AgentRun | undefined;\n #operation: ToolOperation | undefined;\n #disposed = false;\n #state: unknown;\n #stateBeforeLastMessage: unknown;\n #resumeBeforeLastMessage: RunAgentInput[\"resume\"];\n #recoveryUnavailable = false;\n #remoteInterruptId: string | undefined;\n #cancelledResume: RunAgentInput[\"resume\"];\n #task: Promise<Extract<AgentRunResult, { outcome: { type: \"success\" } }>> | undefined;\n #replacement: { cancelled: boolean } | undefined;\n #approval: ToolApprovalInterruptDescriptor | undefined;\n #pending: { resolve(approved: boolean): void; reject(error: Error): void; cleanup(): void } | undefined;\n #settled = new Map<string, () => void>();\n #hasPageHook = (_name: string) => false;\n #cancelled = false;\n #executingBrowserCall: string | undefined;\n\n constructor(options: ChatClientOptions, model?: AgentModelConfig) {\n if (!options?.toolRuntime || Boolean(options.agent) === Boolean(options.run)) throw new ClientError(\"INVALID_INPUT\", \"Provide exactly one agent config or run function and a ToolRuntime.\");\n this.#options = options;\n this.#model = options.agent ? model ?? resolveModelConfig(options.agent.model) : undefined;\n this.runtime = options.toolRuntime;\n this.#runHandler = options.run;\n this.agent = options.agent ? createAgent({ ...options.agent, model: this.#model!, toolRuntime: this.runtime }) : undefined;\n }\n getMessages = (): readonly Message[] => this.#messages;\n getStatus = (): ChatClientStatus => this.#status;\n getApproval = (): ToolApprovalInterruptDescriptor | undefined => this.#approval;\n getError = (): Error | undefined => this.#error;\n subscribe = (listener: () => void): (() => void) => { this.#listeners.add(listener); return () => { this.#listeners.delete(listener); }; };\n subscribeEvents = (listener: (event: ProtocolEvent) => void): (() => void) => { this.#eventListeners.add(listener); return () => { this.#eventListeners.delete(listener); }; };\n #publish(): void {\n for (const listener of this.#listeners) {\n try { listener(); }\n catch (error) { this.#listeners.delete(listener); throw new SubscriptionError(error); }\n }\n }\n get cancelling(): boolean { return Boolean(this.#controller?.signal.aborted); }\n get busy(): boolean { return Boolean(this.#controller); }\n setPageResolver(resolver: (name: string) => boolean): void {\n this.#hasPageHook = resolver;\n if (this.agent) agentController(this.agent).setPageConfirmationResolver(resolver);\n }\n restore(messages: UIMessage[], conversation: readonly AgentMessage[]): void {\n if (this.busy || this.#messages.length) throw new Error(\"Restore requires a new Client.\");\n this.#messages = restoreMessages(structuredClone(messages));\n if (this.agent) agentController(this.agent).restoreConversation(conversation);\n }\n recreateBefore(messageId: string): ChatClient {\n if (this.busy || this.#disposed) throw new ClientError(\"CHAT_RUN_ACTIVE\", \"Wait for the active task to finish.\");\n const index = this.#messages.findIndex((message) => message.role === \"user\" && message.id === messageId);\n if (index < 0 || this.#messages.slice(index + 1).some((message) => message.role === \"user\")) throw new ClientError(\"INVALID_INPUT\", \"Only the last user message can be edited.\");\n const client = new ChatClientImplementation(this.#options, this.#model);\n client.id = this.id;\n client.setPageResolver(this.#hasPageHook);\n client.#messages = structuredClone(this.#messages.slice(0, index));\n client.#state = this.#stateBeforeLastMessage;\n client.#cancelledResume = this.#resumeBeforeLastMessage;\n if (this.agent) {\n const retained = agentController(this.agent).conversationBefore(messageId);\n agentController(client.agent!).restoreConversation(retained.messages, retained.replay);\n }\n return client;\n }\n async switchModel(model: AgentModelConfig): Promise<void> {\n if (!this.agent || this.busy) throw new ClientError(\"CHAT_MODEL_SWITCH_BLOCKED\", \"Model switching is unavailable.\");\n await this.agent.switchModel(model);\n this.#model = model;\n this.#publish();\n }\n #event(event: ProtocolEvent): void {\n if (event.type === EventType.RUN_STARTED || event.type === EventType.RUN_FINISHED) event = { ...event, threadId: this.id };\n this.#messages = this.#updateMessages(this.#messages, event);\n if (event.type === EventType.TOOL_CALL_RESULT) { this.#settled.get(event.toolCallId)?.(); this.#settled.delete(event.toolCallId); }\n if (event.type === EventType.CUSTOM && event.name === \"nexface.tool-execution\" && this.#operation) {\n const value = event.value as { status: string; toolCallId: string; progressLabel?: string };\n const runtime = getInternalToolRuntime(this.runtime);\n const current = runtime.getActivitySnapshot().operation?.taskProgress;\n if (value.status === \"running\") runtime.setTaskProgress(this.#operation, { phase: \"tool\", toolCallId: value.toolCallId, ...(value.progressLabel ? { progressLabel: value.progressLabel } : {}) });\n else if (current?.phase === \"tool\" && current.toolCallId === value.toolCallId) runtime.setTaskProgress(this.#operation, { phase: \"processing\" });\n }\n this.#publish();\n for (const listener of this.#eventListeners) {\n try { listener(event); }\n catch (error) { this.#eventListeners.delete(listener); throw new SubscriptionError(error); }\n }\n }\n sendMessage = (content: string | readonly AgentInputContent[]) => this.send(content);\n async send(content: string | readonly AgentInputContent[], userMessage?: UIMessage): Promise<Extract<AgentRunResult, { outcome: { type: \"success\" } }>> {\n if (this.#disposed || this.#replacement) throw new ClientError(\"CHAT_RUN_ACTIVE\", \"The Client is disposed or already replacing a task.\");\n try {\n content = typeof content === \"string\" ? content.trim() : content.map((part) =>\n part.type === \"text\" ? TextInputContentSchema.parse(part) : ImageInputContentSchema.parse(part));\n if (!content.length) throw new Error(\"Chat message is required.\");\n } catch (error) { throw new ClientError(\"INVALID_INPUT\", error instanceof Error ? error.message : \"Invalid chat message.\"); }\n if (this.busy) {\n if (this.#status !== \"waiting\" || !this.#pending || !this.#task) throw new ClientError(\"CHAT_RUN_ACTIVE\", \"The Client is already running.\");\n const replacement = { cancelled: false };\n this.#replacement = replacement;\n try {\n let cancellationFailure: unknown;\n try { this.#cancelCurrent(); } catch (error) { cancellationFailure = error; }\n await this.#task.catch(() => undefined);\n if (cancellationFailure) throw cancellationFailure instanceof SubscriptionError ? cancellationFailure.failure : cancellationFailure;\n if (replacement.cancelled || this.#disposed) throw abortError();\n } finally { this.#replacement = undefined; }\n }\n if (this.#recoveryUnavailable) {\n this.#error = new ClientError(\"CHAT_RECOVERY_UNAVAILABLE\", \"The previous task has no complete recovery state. Start a new conversation to continue.\");\n this.#status = \"error\";\n this.#publish();\n throw this.#error;\n }\n const task = this.#send(content, userMessage);\n this.#task = task;\n const clear = () => { if (this.#task === task) this.#task = undefined; };\n void task.then(clear, clear);\n return task;\n }\n async #send(content: string | readonly AgentInputContent[], userMessage?: UIMessage): Promise<Extract<AgentRunResult, { outcome: { type: \"success\" } }>> {\n const controller = new AbortController();\n // Claim the Runtime before appending a user message.\n const userId = userMessage?.id ?? id();\n let initialRun: AgentRun | undefined;\n if (this.agent) initialRun = this.agent.run({ messages: [{ id: userId, role: \"user\", content: typeof content === \"string\" ? content : [...content] }] }, { signal: controller.signal });\n else {\n this.#operation = getInternalToolRuntime(this.runtime).beginInternalOperation({ signal: controller.signal, onCancel: () => this.cancel(), taskProgress: { phase: \"processing\" } });\n }\n this.#stateBeforeLastMessage = this.#state;\n this.#resumeBeforeLastMessage = this.#cancelledResume;\n this.#controller = controller;\n this.#cancelled = false;\n this.#executingBrowserCall = undefined;\n this.#status = \"running\";\n this.#error = undefined;\n this.#messages = [...this.#messages, { id: userId, role: \"user\", content: typeof content === \"string\" ? content : [...content], ...(userMessage ? { metadata: { nexface: { restoredParts: userMessage.parts, attachments: userMessage.attachments ?? [], revisionOf: userMessage.revisionOf } } } : {}) }];\n const runtime = getInternalToolRuntime(this.runtime);\n const operationId = runtime.getActivitySnapshot().operation?.id;\n const unsubscribe = runtime.subscribeActivity(() => {\n const operation = runtime.getActivitySnapshot().operation;\n if (operation && operation.id === operationId && operation.status === \"cancelling\" && !controller.signal.aborted) this.cancel();\n });\n let succeeded = false;\n try {\n this.#publish();\n const result = initialRun ? await this.#local(initialRun, controller.signal) : await this.#remote(controller.signal);\n controller.signal.throwIfAborted();\n succeeded = true;\n return result;\n } catch (failure) {\n unsubscribe();\n const failedRun = this.#activeRun ?? initialRun;\n if (failedRun) {\n failedRun.cancel();\n await failedRun.result.catch(() => undefined);\n }\n if (failure instanceof SubscriptionError) failure = failure.failure;\n const record = failure as { name?: unknown; message?: unknown; code?: unknown } | null;\n this.#error = failure instanceof Error ? failure : Object.assign(new Error(typeof record?.message === \"string\" ? record.message : String(failure)), { name: typeof record?.name === \"string\" ? record.name : \"Error\", ...(typeof record?.code === \"string\" ? { code: record.code } : {}) });\n const text = controller.signal.aborted ? \"任务已取消。\" : this.#error.message;\n this.#messages = [\n ...this.#messages.map((message): Message => message.metadata?.nexface?.state === \"running\" ? { ...message, metadata: { ...message.metadata, nexface: { ...message.metadata.nexface, state: \"error\" } } } : message),\n { id: id(), role: \"assistant\", content: text, metadata: { nexface: { state: \"error\" } } },\n ];\n throw this.#error;\n } finally {\n unsubscribe();\n this.#pending?.cleanup(); this.#pending = undefined; this.#approval = undefined;\n if (this.#operation) await this.#operation.end({ outcome: succeeded ? \"completed\" : controller.signal.aborted ? \"cancelled\" : \"failed\" });\n this.#operation = undefined; this.#activeRun = undefined; this.#controller = undefined;\n for (const settle of this.#settled.values()) settle(); this.#settled.clear();\n this.#status = succeeded || controller.signal.aborted ? \"idle\" : \"error\";\n this.#publish();\n }\n }\n async #consume(run: AgentRun): Promise<AgentRunResult> {\n this.#activeRun = run;\n const outcomes = await Promise.allSettled([run.result, (async () => {\n try { for await (const event of run) this.#event(event); }\n catch (error) { run.cancel(); throw error; }\n })()]);\n if (outcomes[1].status === \"rejected\") throw outcomes[1].reason;\n if (outcomes[0].status === \"rejected\") throw outcomes[0].reason;\n return outcomes[0].value;\n }\n async #local(run: AgentRun, signal: AbortSignal): Promise<Extract<AgentRunResult, { outcome: { type: \"success\" } }>> {\n for (;;) {\n const result = await this.#consume(run);\n if (result.outcome.type === \"success\") {\n if (typeof result.output !== \"string\") throw new Error(\"Missing completion output.\");\n return { ...result, outcome: result.outcome, output: result.output };\n }\n const interrupt = result.outcome.interrupts[0];\n const extension = interrupt?.metadata?.nexface;\n if (result.outcome.interrupts.length !== 1 || extension?.kind !== \"tool-approval\") throw new Error(\"Unexpected local interrupt.\");\n const approval = extension.approval as ToolApprovalInterruptDescriptor;\n const tool = this.runtime.getTools().find((item) => item.definition.name === approval.toolName);\n if (!tool) throw new ClientError(\"TOOL_CONFIRMATION_INVALIDATED\", \"Tool Binding was removed.\");\n const approved = await this.#wait(approval, tool, signal);\n if (signal.aborted) {\n this.#messages = settleApproval(this.#messages, approval, \"TOOL_CANCELLED\", \"The pending Tool confirmation was cancelled.\", \"interrupt_cancelled\");\n agentController(this.agent!).settle(approval.id, { type: \"cancel\" }, this.#messages);\n }\n signal.throwIfAborted();\n const response = { interruptId: interrupt!.id, status: \"resolved\" as const, payload: { approved } };\n if (approval.mode === \"page\") agentController(this.agent!).authorizePageResponse(response);\n run = this.agent!.run({ resume: [response] }, { signal });\n }\n }\n #wait(approval: ToolApprovalInterruptDescriptor, tool: RuntimeAgentTool, signal: AbortSignal): Promise<boolean> {\n signal.throwIfAborted();\n this.#approval = Object.freeze(approval);\n this.#status = \"waiting\";\n const waiting = new Promise<boolean>((resolve, reject) => {\n const abort = () => reject(signal.reason);\n const removed = () => this.invalidate(\"Tool Binding was removed.\");\n const cleanup = () => { signal.removeEventListener(\"abort\", abort); tool.lifecycleSignal.removeEventListener(\"abort\", removed); };\n this.#pending = { resolve, reject, cleanup };\n signal.addEventListener(\"abort\", abort, { once: true });\n tool.lifecycleSignal.addEventListener(\"abort\", removed, { once: true });\n if (tool.lifecycleSignal.aborted) removed();\n });\n this.#operation?.setWaitingForUser(true);\n this.#publish();\n return waiting;\n }\n async #respond(id: string, approved: boolean, source: \"chat\" | \"page\"): Promise<void> {\n const pending = this.#pending;\n if (!pending || this.#approval?.id !== id || this.#approval.mode !== source || typeof approved !== \"boolean\" || (source === \"page\" && !approved)) throw new ClientError(\"INVALID_INPUT\", \"Confirmation is no longer pending or has the wrong source.\");\n pending.cleanup(); this.#pending = undefined; this.#approval = undefined;\n this.#status = \"running\"; this.#operation?.setWaitingForUser(false);\n pending.resolve(approved); this.#publish();\n }\n respondToApproval = (id: string, response: { approved: boolean }): Promise<void> => this.#respond(id, response.approved, \"chat\");\n confirmPage(): Promise<void> | undefined {\n const approval = this.#approval;\n if (approval?.mode !== \"page\") return;\n const settled = new Promise<void>((resolve) => this.#settled.set(approval.toolCallId, resolve));\n void this.#respond(approval.id, true, \"page\").catch(() => { this.#settled.get(approval.toolCallId)?.(); this.#settled.delete(approval.toolCallId); });\n return settled;\n }\n invalidate(message: string): void {\n const approval = this.#approval;\n if (!approval) return;\n this.#messages = settleApproval(this.#messages, approval, \"TOOL_CONFIRMATION_INVALIDATED\", message, \"binding_changed\");\n if (this.agent) {\n agentController(this.agent).settle(approval.id, { type: \"invalidate\", message, reason: \"binding_changed\" }, this.#messages);\n }\n this.#queueRemoteCancellation();\n const pending = this.#pending;\n pending?.cleanup(); this.#pending = undefined; this.#approval = undefined;\n this.#status = \"running\"; this.#operation?.setWaitingForUser(false);\n pending?.reject(new ClientError(\"TOOL_CONFIRMATION_INVALIDATED\", message));\n this.#publish();\n }\n cancel = (): void => {\n if (this.#replacement) this.#replacement.cancelled = true;\n this.#cancelCurrent();\n };\n #queueRemoteCancellation(): void {\n if (this.#remoteInterruptId) this.#cancelledResume = [{ interruptId: this.#remoteInterruptId, status: \"cancelled\" }];\n }\n #cancelCurrent(): void {\n if (!this.#controller || this.#cancelled) return;\n this.#cancelled = true;\n if (this.#approval) {\n this.#messages = settleApproval(this.#messages, this.#approval, \"TOOL_CANCELLED\", \"The pending Tool confirmation was cancelled.\", \"interrupt_cancelled\");\n if (this.agent) agentController(this.agent).settle(this.#approval.id, { type: \"cancel\" }, this.#messages);\n this.#queueRemoteCancellation();\n }\n const pending = this.#pending;\n pending?.cleanup(); this.#pending = undefined; this.#approval = undefined;\n this.#controller.abort(abortError());\n pending?.reject(this.#controller.signal.reason);\n this.#activeRun?.cancel(); this.#publish();\n }\n dispose = (): void => { if (this.#disposed) return; this.#disposed = true; this.cancel(); this.#listeners.clear(); this.#eventListeners.clear(); };\n\n async #remote(signal: AbortSignal): Promise<Extract<AgentRunResult, { outcome: { type: \"success\" } }>> {\n let resume = this.#cancelledResume;\n let inFlight = false;\n let completedBrowserCall = false;\n try {\n for (;;) {\n signal.throwIfAborted();\n const catalog = [...this.runtime.getTools()];\n const contexts = await this.runtime.getContexts({ signal });\n const runId = id();\n const input: RunAgentInput = {\n threadId: this.id, runId, messages: this.#messages, state: this.#state ?? null,\n ...(resume ? { resume } : {}),\n tools: catalog.map(({ definition }) => ({ name: definition.name, description: definition.description, parameters: definition.inputSchema ?? { type: \"object\", properties: {} } })),\n context: contexts.map((context) => ({ description: context.description ?? context.name, value: JSON.stringify(context) })),\n forwardedProps: { nexface: { version: 3,\n toolMetadata: Object.fromEntries(catalog.map(({ definition }) => [definition.name, { ...(definition.effect ? { effect: definition.effect } : {}) }])),\n } },\n };\n RunAgentInputSchema.parse(input);\n inFlight = true;\n completedBrowserCall = false;\n this.#remoteInterruptId = undefined;\n const response = await abortable(this.#runHandler!(input, { signal }), signal);\n if (!response.ok || !response.body) throw new ClientError(\"CHAT_REQUEST_FAILED\", `Agent request failed (${response.status}).`);\n let terminal: AgentRunResult | undefined;\n let terminalEvent: Extract<ProtocolEvent, { type: EventType.RUN_FINISHED }> | undefined;\n let messageSnapshot: Extract<ProtocolEvent, { type: EventType.MESSAGES_SNAPSHOT }> | undefined;\n let stateSnapshot: Extract<ProtocolEvent, { type: EventType.STATE_SNAPSHOT }> | undefined;\n let started = false;\n for await (const event of readEvents(response, signal)) {\n if (event.type === EventType.RUN_ERROR) {\n this.#event(event);\n throw new ClientError(event.code ?? \"CHAT_RUN_ERROR\", event.message);\n }\n if (event.type === EventType.RUN_STARTED || event.type === EventType.RUN_FINISHED) {\n if (event.threadId !== this.id || event.runId !== runId) throw new Error(\"Agent response identity does not match its request.\");\n }\n if (event.type === EventType.RUN_STARTED) {\n if (started) throw new Error(\"Duplicate Agent start event.\");\n started = true;\n }\n if (event.type === EventType.MESSAGES_SNAPSHOT) {\n if (messageSnapshot || stateSnapshot) throw new ClientError(\"CHAT_STREAM_INCOMPLETE\", \"Invalid recovery snapshot order.\");\n messageSnapshot = event;\n continue;\n }\n if (event.type === EventType.STATE_SNAPSHOT) {\n if (!messageSnapshot || stateSnapshot) throw new ClientError(\"CHAT_STREAM_INCOMPLETE\", \"Invalid recovery snapshot order.\");\n stateSnapshot = event;\n continue;\n }\n if (event.type === EventType.RUN_FINISHED) {\n if (!started || !event.outcome || !messageSnapshot || !stateSnapshot) throw new ClientError(\"CHAT_STREAM_INCOMPLETE\", \"Agent terminal is missing its recovery snapshots or outcome.\");\n terminal = { ...event.result, outcome: event.outcome } as AgentRunResult;\n terminalEvent = event;\n break;\n }\n if (messageSnapshot) throw new ClientError(\"CHAT_STREAM_INCOMPLETE\", \"Unexpected event between recovery snapshots and terminal.\");\n this.#event(event);\n }\n if (!terminal || !terminalEvent || !messageSnapshot || !stateSnapshot) throw new ClientError(\"CHAT_STREAM_INCOMPLETE\", \"Agent stream ended without complete recovery snapshots.\");\n let decoded: ReturnType<typeof decodeAgentResponse>;\n try { decoded = decodeAgentResponse(messageSnapshot.messages, stateSnapshot.snapshot, terminalEvent); }\n catch (error) { throw new ClientError(\"CHAT_STREAM_INCOMPLETE\", error instanceof Error ? error.message : \"Invalid Agent recovery response.\"); }\n const commit = () => {\n // Only a complete terminal commits the matching messages and state.\n this.#state = structuredClone(stateSnapshot.snapshot);\n this.#cancelledResume = undefined;\n inFlight = false;\n this.#event(messageSnapshot);\n this.#event(stateSnapshot);\n this.#event(terminalEvent);\n };\n if (decoded.type === \"success\") {\n commit();\n return decoded.result;\n }\n this.#remoteInterruptId = decoded.interruptId;\n commit();\n const toolResult = await this.#browserAction(decoded.action, catalog, signal);\n completedBrowserCall = true;\n const messageId = id();\n this.#event({ type: EventType.TOOL_CALL_RESULT, messageId, role: \"tool\", toolCallId: toolResult.toolCallId, content: JSON.stringify(toolResult.error ? { error: toolResult.error } : { result: toolResult.result ?? null }) });\n resume = [{ interruptId: decoded.interruptId, status: \"resolved\", payload: { toolResultMessageId: messageId, ...(toolResult.confirmed ? { confirmed: true } : {}) } }];\n }\n } catch (error) {\n const unknown = inFlight || completedBrowserCall || this.#executingBrowserCall !== undefined;\n if (unknown) this.#recoveryUnavailable = true;\n else this.#queueRemoteCancellation();\n const lastUser = this.#messages.reduce((last, message, index) => message.role === \"user\" ? index : last, -1);\n const current = this.#messages.slice(lastUser);\n for (const [index, message] of current.entries()) if (message.role === \"assistant\" && message.toolCalls?.length) {\n const following = current.slice(index + 1);\n const nextBatch = following.findIndex((item) => item.role === \"assistant\" && Boolean(item.toolCalls?.length));\n const receipts = nextBatch < 0 ? following : following.slice(0, nextBatch);\n for (const call of message.toolCalls) {\n if (receipts.some((item) => item.role === \"tool\" && item.toolCallId === call.id)) continue;\n const unknown = inFlight || this.#executingBrowserCall === call.id;\n this.#event({ type: EventType.TOOL_CALL_RESULT, messageId: id(), role: \"tool\", toolCallId: call.id, content: JSON.stringify({ error: { code: unknown ? \"EXECUTION_OUTCOME_UNKNOWN\" : \"TOOL_CANCELLED\", message: unknown ? \"The execution outcome is unknown; this call may have executed.\" : \"Task ended before execution.\" } }) });\n }\n }\n throw error;\n }\n }\n async #browserAction(action: AgentBrowserAction, catalog: RuntimeAgentTool[], signal: AbortSignal): Promise<BrowserToolResult> {\n let confirmed = false;\n this.#executingBrowserCall = undefined;\n try {\n if (!action || typeof action.toolCallId !== \"string\" || !action.definition) throw new Error(\"Invalid browser action.\");\n const tool = catalog.find((item) => JSON.stringify(item.definition) === JSON.stringify(action.definition));\n if (!tool || !this.runtime.getTools().includes(tool)) throw new ClientError(\"TOOL_CONFIRMATION_INVALIDATED\", \"The original Tool Binding is no longer available.\");\n const errors = validateAgentToolInput(tool.definition.inputSchema, action.input);\n if (errors.length) throw new ClientError(\"INVALID_INPUT\", errors.join(\" \"));\n const confirmation = tool.confirmation;\n if (confirmation) {\n if (confirmation.mode === \"page\" && !this.#hasPageHook(tool.definition.name)) throw new ClientError(\"TOOL_CONFIRMATION_UNAVAILABLE\", \"An active usePageConfirmation Hook is required.\");\n confirmed = true;\n const approval = { ...confirmation, type: \"tool-approval\" as const, id: id(), runId: this.id, toolCallId: action.toolCallId, toolName: tool.definition.name, input: structuredClone(action.input) };\n const approved = await this.#wait(approval, tool, signal);\n if (!approved) throw new ClientError(\"TOOL_CONFIRMATION_REJECTED\", \"The user rejected this tool call.\");\n }\n signal.throwIfAborted();\n this.#executingBrowserCall = action.toolCallId;\n const result = await getInternalToolRuntime(this.runtime).executeWithProgress(tool, action.input, { signal, ...(action.progressLabel ? { progressLabel: action.progressLabel } : {}) });\n return { toolCallId: action.toolCallId, result: result ?? null, ...(confirmed ? { confirmed } : {}) };\n } catch (error) {\n if (error instanceof SubscriptionError) throw error;\n signal.throwIfAborted();\n if (error instanceof ClientError && error.code === \"TOOL_CONFIRMATION_INVALIDATED\") throw error;\n return { toolCallId: action.toolCallId, error: { code: error instanceof ClientError || isToolRuntimeError(error) ? error.code : \"TOOL_ERROR\", message: error instanceof Error ? error.message : String(error) }, ...(confirmed ? { confirmed } : {}) };\n } finally {\n if (!signal.aborted) this.#executingBrowserCall = undefined;\n this.#settled.get(action.toolCallId)?.(); this.#settled.delete(action.toolCallId);\n }\n }\n}\n\nasync function abortable<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {\n signal.throwIfAborted();\n let abort!: () => void;\n try { return await Promise.race([promise, new Promise<never>((_resolve, reject) => { abort = () => reject(signal.reason); signal.addEventListener(\"abort\", abort, { once: true }); })]); }\n finally { signal.removeEventListener(\"abort\", abort); }\n}\n\nasync function* readEvents(response: Response, signal: AbortSignal): AsyncGenerator<ProtocolEvent> {\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n const abort = () => { void reader.cancel(signal.reason).catch(() => undefined); };\n signal.addEventListener(\"abort\", abort, { once: true });\n try {\n for (;;) {\n signal.throwIfAborted();\n const next = await reader.read();\n buffer = (buffer + decoder.decode(next.value, { stream: !next.done })).replace(/\\r\\n/g, \"\\n\");\n let boundary: number;\n while ((boundary = buffer.indexOf(\"\\n\\n\")) >= 0) {\n const packet = buffer.slice(0, boundary); buffer = buffer.slice(boundary + 2);\n const data = packet.split(\"\\n\").filter((line) => line.startsWith(\"data:\")).map((line) => line.slice(5).trimStart()).join(\"\\n\");\n if (data) { signal.throwIfAborted(); yield EventSchemas.parse(JSON.parse(data)); }\n }\n if (next.done) { signal.throwIfAborted(); if (buffer.trim()) throw new Error(\"Truncated SSE event.\"); return; }\n }\n } finally {\n signal.removeEventListener(\"abort\", abort);\n // Transport cleanup must not delay terminal delivery.\n void reader.cancel().catch(() => undefined);\n reader.releaseLock();\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- import type { Message, RunFinishedEvent, RunErrorEvent } from "@ag-ui/core";
1
+ import type { Message, RunFinishedEvent } from "@ag-ui/core";
2
2
  import type { AgentRunResult } from "@nexface/agent";
3
3
  import type { AgentToolDefinition } from "@nexface/tools";
4
4
  export interface BrowserToolResult {
@@ -17,10 +17,6 @@ export interface AgentBrowserAction {
17
17
  readonly progressLabel?: string;
18
18
  }
19
19
  type AgentResponse = {
20
- type: "error";
21
- code: string;
22
- message: string;
23
- } | {
24
20
  type: "success";
25
21
  result: Extract<AgentRunResult, {
26
22
  outcome: {
@@ -32,5 +28,5 @@ type AgentResponse = {
32
28
  interruptId: string;
33
29
  action: AgentBrowserAction;
34
30
  };
35
- export declare function decodeAgentResponse(messages: readonly Message[], snapshot: unknown, terminal: RunFinishedEvent | RunErrorEvent, threadId: string): AgentResponse;
31
+ export declare function decodeAgentResponse(messages: readonly Message[], snapshot: unknown, terminal: RunFinishedEvent): AgentResponse;
36
32
  export {};
@@ -1,7 +1,7 @@
1
- export function decodeAgentResponse(messages, snapshot, terminal, threadId) {
1
+ export function decodeAgentResponse(messages, snapshot, terminal) {
2
2
  const state = snapshot;
3
3
  const continuation = state?.nexface;
4
- if (!continuation || continuation.version !== 3 || continuation.threadId !== threadId || !Array.isArray(continuation.timeline)) {
4
+ if (!continuation || continuation.version !== 3 || continuation.threadId !== terminal.threadId || !Array.isArray(continuation.timeline)) {
5
5
  throw new Error("Invalid Agent recovery state or protocol version. Upgrade client and server together and start a new conversation.");
6
6
  }
7
7
  const legacy = new Set(["callAppTool", "getSnapshot", "executeCode", "loadSkill", "finish"]);
@@ -23,13 +23,8 @@ export function decodeAgentResponse(messages, snapshot, terminal, threadId) {
23
23
  || references.length !== history.length || references.some((id, index) => id !== history[index].id)) {
24
24
  throw new Error("Agent messages and recovery state do not match.");
25
25
  }
26
- const pending = continuation.pending;
27
- if (terminal.type === "RUN_ERROR") {
28
- if (terminal.code !== "AGENT_RUN_LIMIT_REACHED" || pending)
29
- throw new Error("Invalid recoverable Agent error.");
30
- return { type: "error", code: terminal.code, message: terminal.message };
31
- }
32
26
  const outcome = terminal.outcome;
27
+ const pending = continuation.pending;
33
28
  if (outcome?.type === "success") {
34
29
  if (typeof terminal.result?.output !== "string" || pending)
35
30
  throw new Error("Invalid completion output or pending state.");
@@ -1 +1 @@
1
- {"version":3,"file":"protocol-response.js","sourceRoot":"","sources":["../src/protocol-response.ts"],"names":[],"mappings":"AAsCA,MAAM,UAAU,mBAAmB,CACjC,QAA4B,EAC5B,QAAiB,EACjB,QAA0C,EAC1C,QAAgB;IAEhB,MAAM,KAAK,GAAG,QAAqC,CAAC;IACpD,MAAM,YAAY,GAAG,KAAK,EAAE,OAAO,CAAC;IACpC,IAAI,CAAC,YAAY,IAAI,YAAY,CAAC,OAAO,KAAK,CAAC,IAAI,YAAY,CAAC,QAAQ,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,YAAY,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC/H,MAAM,IAAI,KAAK,CAAC,oHAAoH,CAAC,CAAC;IACxI,CAAC;IACD,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,CAAC,aAAa,EAAE,aAAa,EAAE,aAAa,EAAE,WAAW,EAA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C,CAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,eAAe,CAAC,CAAC,CAAC;IACvJ,IAAI,SAAS,CAAC,IAAI,KAAK,uBAAuB;QAAE,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;IACjG,MAAM,MAAM,GAAG,SAAS,CAAC,MAAwC,CAAC;IAClE,IAAI,CAAC,MAAM,IAAI,MAAM,CAAC,UAAU,KAAK,IAAI,CAAC,EAAE,IAAI,IAAI,KAAK,MAAM,CAAC,UAAU,EAAE,IAAI,IAAI,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,KAAK,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;QAC/I,MAAM,IAAI,KAAK,CAAC,kDAAkD,CAAC,CAAC;IACtE,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,uBAAuB,EAAE,WAAW,EAAE,SAAS,CAAC,EAAE,EAAE,MAAM,EAAE,CAAC;AAC9E,CAAC","sourcesContent":["import type { Message, RunFinishedEvent, RunErrorEvent } from \"@ag-ui/core\";\nimport type { AgentRunResult } from \"@nexface/agent\";\n\nimport type { AgentToolDefinition } from \"@nexface/tools\";\n\nexport interface BrowserToolResult {\n readonly toolCallId: string;\n readonly result?: unknown;\n readonly error?: { readonly code: string; readonly message: string };\n readonly confirmed?: boolean;\n}\n\nexport interface AgentBrowserAction {\n readonly toolCallId: string;\n readonly definition: AgentToolDefinition<any, any>;\n readonly input: unknown;\n readonly progressLabel?: string;\n}\n\n// Only the response fields needed to validate a client handoff belong here.\ninterface ResponseState {\n nexface: {\n version: number;\n threadId: string;\n timeline: Array<{ messageId: string } | { internal: { role: string } }>;\n pending?: {\n kind: string;\n interruptId: string;\n calls: Array<{ id: string; name: string; arguments: string }>;\n };\n };\n}\n\ntype AgentResponse =\n | { type: \"error\"; code: string; message: string }\n | { type: \"success\"; result: Extract<AgentRunResult, { outcome: { type: \"success\" } }> }\n | { type: \"client-tool-execution\"; interruptId: string; action: AgentBrowserAction };\n\nexport function decodeAgentResponse(\n messages: readonly Message[],\n snapshot: unknown,\n terminal: RunFinishedEvent | RunErrorEvent,\n threadId: string,\n): AgentResponse {\n const state = snapshot as ResponseState | undefined;\n const continuation = state?.nexface;\n if (!continuation || continuation.version !== 3 || continuation.threadId !== threadId || !Array.isArray(continuation.timeline)) {\n throw new Error(\"Invalid Agent recovery state or protocol version. Upgrade client and server together and start a new conversation.\");\n }\n const legacy = new Set([\"callAppTool\", \"getSnapshot\", \"executeCode\", \"loadSkill\", \"finish\"]);\n if (messages.some((message) => message.role === \"assistant\" && message.toolCalls?.some((call) => legacy.has(call.function.name)))\n || continuation.pending?.calls?.some((call) => legacy.has(call.name))) throw new Error(\"Unsupported legacy tool history. Start a new conversation.\");\n const history = messages.filter((message) => message.role !== \"activity\" && message.role !== \"reasoning\");\n const references = continuation.timeline.flatMap((entry) => {\n if (entry && \"internal\" in entry) {\n if (\"messageId\" in entry || (entry.internal?.role !== \"system\" && entry.internal?.role !== \"application_context\")) throw new Error(\"Invalid internal history reference.\");\n return [];\n }\n if (!entry || !(\"messageId\" in entry) || typeof entry.messageId !== \"string\") throw new Error(\"Invalid Agent history reference.\");\n return [entry.messageId];\n });\n if (new Set(messages.map((message) => message.id)).size !== messages.length\n || references.length !== history.length || references.some((id, index) => id !== history[index]!.id)) {\n throw new Error(\"Agent messages and recovery state do not match.\");\n }\n const pending = continuation.pending;\n if (terminal.type === \"RUN_ERROR\") {\n if (terminal.code !== \"AGENT_RUN_LIMIT_REACHED\" || pending) throw new Error(\"Invalid recoverable Agent error.\");\n return { type: \"error\", code: terminal.code, message: terminal.message };\n }\n const outcome = terminal.outcome;\n if (outcome?.type === \"success\") {\n if (typeof terminal.result?.output !== \"string\" || pending) throw new Error(\"Invalid completion output or pending state.\");\n return { type: \"success\", result: { outcome, output: terminal.result.output } };\n }\n if (outcome?.type !== \"interrupt\" || outcome.interrupts.length !== 1) throw new Error(\"Invalid remote interrupt.\");\n const interrupt = outcome.interrupts[0]!;\n const extension = interrupt.metadata?.nexface;\n const call = pending?.calls?.[0];\n if (!extension || !pending || !Array.isArray(pending.calls) || !call\n || pending.interruptId !== interrupt.id || interrupt.toolCallId !== call.id || pending.kind !== extension.kind) {\n throw new Error(\"Invalid remote interrupt.\");\n }\n const ownerIndex = history.reduce((last, message, index) => message.role === \"assistant\" ? index : last, -1);\n const owner = history[ownerIndex];\n const calls = owner?.role === \"assistant\" ? owner.toolCalls ?? [] : [];\n const first = calls.findIndex((item) => item.id === call.id);\n if (first < 0 || calls.length - first !== pending.calls.length\n || pending.calls.some((item, index) => item.id !== calls[first + index]!.id\n || item.name !== calls[first + index]!.function.name || item.arguments !== calls[first + index]!.function.arguments)\n || history.slice(ownerIndex + 1).some((message) => message.role === \"tool\" && pending.calls.some((item) => item.id === message.toolCallId))) {\n throw new Error(\"Pending calls do not match their assistant message.\");\n }\n const args: unknown = JSON.parse(call.arguments);\n if (!args || typeof args !== \"object\" || Array.isArray(args)) throw new Error(\"Invalid pending tool arguments.\");\n const input = args as Record<string, unknown>;\n const name = call.name === \"nxf_callAppTool\" ? input.name : call.name;\n const toolInput = call.name === \"nxf_callAppTool\" ? input.input : Object.fromEntries(Object.entries(input).filter(([key]) => key !== \"progressLabel\"));\n if (extension.kind !== \"client-tool-execution\") throw new Error(\"Unsupported remote interrupt.\");\n const action = extension.action as AgentBrowserAction | undefined;\n if (!action || action.toolCallId !== call.id || name !== action.definition?.name || JSON.stringify(toolInput) !== JSON.stringify(action.input)) {\n throw new Error(\"Browser action does not match its original call.\");\n }\n return { type: \"client-tool-execution\", interruptId: interrupt.id, action };\n}\n"]}
1
+ {"version":3,"file":"protocol-response.js","sourceRoot":"","sources":["../src/protocol-response.ts"],"names":[],"mappings":"AAqCA,MAAM,UAAU,mBAAmB,CACjC,QAA4B,EAC5B,QAAiB,EACjB,QAA0B;IAE1B,MAAM,KAAK,GAAG,QAAqC,CAAC;IACpD,MAAM,YAAY,GAAG,KA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WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,eAAe,CAAC,CAAC,CAAC;IACvJ,IAAI,SAAS,CAAC,IAAI,KAAK,uBAAuB;QAAE,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;IACjG,MAAM,MAAM,GAAG,SAAS,CAAC,MAAwC,CAAC;IAClE,IAAI,CAAC,MAAM,IAAI,MAAM,CAAC,UAAU,KAAK,IAAI,CAAC,EAAE,IAAI,IAAI,KAAK,MAAM,CAAC,UAAU,EAAE,IAAI,IAAI,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,KAAK,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;QAC/I,MAAM,IAAI,KAAK,CAAC,kDAAkD,CAAC,CAAC;IACtE,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,uBAAuB,EAAE,WAAW,EAAE,SAAS,CAAC,EAAE,EAAE,MAAM,EAAE,CAAC;AAC9E,CAAC","sourcesContent":["import type { Message, RunFinishedEvent } from \"@ag-ui/core\";\nimport type { AgentRunResult } from \"@nexface/agent\";\n\nimport type { AgentToolDefinition } from \"@nexface/tools\";\n\nexport interface BrowserToolResult {\n readonly toolCallId: string;\n readonly result?: unknown;\n readonly error?: { readonly code: string; readonly message: string };\n readonly confirmed?: boolean;\n}\n\nexport interface AgentBrowserAction {\n readonly toolCallId: string;\n readonly definition: AgentToolDefinition<any, any>;\n readonly input: unknown;\n readonly progressLabel?: string;\n}\n\n// Only the response fields needed to validate a client handoff belong here.\ninterface ResponseState {\n nexface: {\n version: number;\n threadId: string;\n timeline: Array<{ messageId: string } | { internal: { role: string } }>;\n pending?: {\n kind: string;\n interruptId: string;\n calls: Array<{ id: string; name: string; arguments: string }>;\n };\n };\n}\n\ntype AgentResponse =\n | { type: \"success\"; result: Extract<AgentRunResult, { outcome: { type: \"success\" } }> }\n | { type: \"client-tool-execution\"; interruptId: string; action: AgentBrowserAction };\n\nexport function decodeAgentResponse(\n messages: readonly Message[],\n snapshot: unknown,\n terminal: RunFinishedEvent,\n): AgentResponse {\n const state = snapshot as ResponseState | undefined;\n const continuation = state?.nexface;\n if (!continuation || continuation.version !== 3 || continuation.threadId !== terminal.threadId || !Array.isArray(continuation.timeline)) {\n throw new Error(\"Invalid Agent recovery state or protocol version. Upgrade client and server together and start a new conversation.\");\n }\n const legacy = new Set([\"callAppTool\", \"getSnapshot\", \"executeCode\", \"loadSkill\", \"finish\"]);\n if (messages.some((message) => message.role === \"assistant\" && message.toolCalls?.some((call) => legacy.has(call.function.name)))\n || continuation.pending?.calls?.some((call) => legacy.has(call.name))) throw new Error(\"Unsupported legacy tool history. Start a new conversation.\");\n const history = messages.filter((message) => message.role !== \"activity\" && message.role !== \"reasoning\");\n const references = continuation.timeline.flatMap((entry) => {\n if (entry && \"internal\" in entry) {\n if (\"messageId\" in entry || (entry.internal?.role !== \"system\" && entry.internal?.role !== \"application_context\")) throw new Error(\"Invalid internal history reference.\");\n return [];\n }\n if (!entry || !(\"messageId\" in entry) || typeof entry.messageId !== \"string\") throw new Error(\"Invalid Agent history reference.\");\n return [entry.messageId];\n });\n if (new Set(messages.map((message) => message.id)).size !== messages.length\n || references.length !== history.length || references.some((id, index) => id !== history[index]!.id)) {\n throw new Error(\"Agent messages and recovery state do not match.\");\n }\n const outcome = terminal.outcome;\n const pending = continuation.pending;\n if (outcome?.type === \"success\") {\n if (typeof terminal.result?.output !== \"string\" || pending) throw new Error(\"Invalid completion output or pending state.\");\n return { type: \"success\", result: { outcome, output: terminal.result.output } };\n }\n if (outcome?.type !== \"interrupt\" || outcome.interrupts.length !== 1) throw new Error(\"Invalid remote interrupt.\");\n const interrupt = outcome.interrupts[0]!;\n const extension = interrupt.metadata?.nexface;\n const call = pending?.calls?.[0];\n if (!extension || !pending || !Array.isArray(pending.calls) || !call\n || pending.interruptId !== interrupt.id || interrupt.toolCallId !== call.id || pending.kind !== extension.kind) {\n throw new Error(\"Invalid remote interrupt.\");\n }\n const ownerIndex = history.reduce((last, message, index) => message.role === \"assistant\" ? index : last, -1);\n const owner = history[ownerIndex];\n const calls = owner?.role === \"assistant\" ? owner.toolCalls ?? [] : [];\n const first = calls.findIndex((item) => item.id === call.id);\n if (first < 0 || calls.length - first !== pending.calls.length\n || pending.calls.some((item, index) => item.id !== calls[first + index]!.id\n || item.name !== calls[first + index]!.function.name || item.arguments !== calls[first + index]!.function.arguments)\n || history.slice(ownerIndex + 1).some((message) => message.role === \"tool\" && pending.calls.some((item) => item.id === message.toolCallId))) {\n throw new Error(\"Pending calls do not match their assistant message.\");\n }\n const args: unknown = JSON.parse(call.arguments);\n if (!args || typeof args !== \"object\" || Array.isArray(args)) throw new Error(\"Invalid pending tool arguments.\");\n const input = args as Record<string, unknown>;\n const name = call.name === \"nxf_callAppTool\" ? input.name : call.name;\n const toolInput = call.name === \"nxf_callAppTool\" ? input.input : Object.fromEntries(Object.entries(input).filter(([key]) => key !== \"progressLabel\"));\n if (extension.kind !== \"client-tool-execution\") throw new Error(\"Unsupported remote interrupt.\");\n const action = extension.action as AgentBrowserAction | undefined;\n if (!action || action.toolCallId !== call.id || name !== action.definition?.name || JSON.stringify(toolInput) !== JSON.stringify(action.input)) {\n throw new Error(\"Browser action does not match its original call.\");\n }\n return { type: \"client-tool-execution\", interruptId: interrupt.id, action };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nexface/chat",
3
- "version": "0.1.6",
3
+ "version": "0.1.7",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=22.19.0"
@@ -17,7 +17,7 @@
17
17
  "@assistant-ui/react": "0.15.21",
18
18
  "@assistant-ui/react-markdown": "0.14.16",
19
19
  "@base-ui/react": "1.8.0",
20
- "@nexface/agent": "0.1.6",
20
+ "@nexface/agent": "0.1.7",
21
21
  "class-variance-authority": "0.7.1",
22
22
  "clsx": "2.1.1",
23
23
  "fast-json-patch": "3.1.1",
@@ -27,7 +27,7 @@
27
27
  "tailwind-merge": "3.6.0"
28
28
  },
29
29
  "peerDependencies": {
30
- "@nexface/tools": "0.1.6",
30
+ "@nexface/tools": "0.1.7",
31
31
  "react": ">=18",
32
32
  "react-dom": ">=18"
33
33
  },