@nexface/chat 0.1.5 → 0.1.6

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
@@ -1,5 +1,6 @@
1
1
  import { createAgent } from "@nexface/agent";
2
2
  import { decodeAgentResponse } from "./protocol-response.js";
3
+ import { isToolRuntimeError } from "@nexface/tools";
3
4
  import { getInternalToolRuntime, validateAgentToolInput } from "@nexface/tools/internal";
4
5
  import { EventType, EventSchemas, RunAgentInputSchema, TextInputContentSchema, ImageInputContentSchema } from "@ag-ui/core";
5
6
  import { createMessageUpdater, restoreMessages, settleApproval } from "./protocol-messages.js";
@@ -421,7 +422,7 @@ class ChatClientImplementation {
421
422
  ...(resume ? { resume } : {}),
422
423
  tools: catalog.map(({ definition }) => ({ name: definition.name, description: definition.description, parameters: definition.inputSchema ?? { type: "object", properties: {} } })),
423
424
  context: contexts.map((context) => ({ description: context.description ?? context.name, value: JSON.stringify(context) })),
424
- forwardedProps: { nexface: { version: 2,
425
+ forwardedProps: { nexface: { version: 3,
425
426
  toolMetadata: Object.fromEntries(catalog.map(({ definition }) => [definition.name, { ...(definition.effect ? { effect: definition.effect } : {}) }])),
426
427
  } },
427
428
  };
@@ -432,13 +433,16 @@ class ChatClientImplementation {
432
433
  const response = await abortable(this.#runHandler(input, { signal }), signal);
433
434
  if (!response.ok || !response.body)
434
435
  throw new ClientError("CHAT_REQUEST_FAILED", `Agent request failed (${response.status}).`);
435
- let terminal;
436
436
  let terminalEvent;
437
437
  let messageSnapshot;
438
438
  let stateSnapshot;
439
439
  let started = false;
440
440
  for await (const event of readEvents(response, signal)) {
441
441
  if (event.type === EventType.RUN_ERROR) {
442
+ if (started && messageSnapshot && stateSnapshot) {
443
+ terminalEvent = event;
444
+ break;
445
+ }
442
446
  this.#event(event);
443
447
  throw new ClientError(event.code ?? "CHAT_RUN_ERROR", event.message);
444
448
  }
@@ -466,7 +470,6 @@ class ChatClientImplementation {
466
470
  if (event.type === EventType.RUN_FINISHED) {
467
471
  if (!started || !event.outcome || !messageSnapshot || !stateSnapshot)
468
472
  throw new ClientError("CHAT_STREAM_INCOMPLETE", "Agent terminal is missing its recovery snapshots or outcome.");
469
- terminal = { ...event.result, outcome: event.outcome };
470
473
  terminalEvent = event;
471
474
  break;
472
475
  }
@@ -474,11 +477,11 @@ class ChatClientImplementation {
474
477
  throw new ClientError("CHAT_STREAM_INCOMPLETE", "Unexpected event between recovery snapshots and terminal.");
475
478
  this.#event(event);
476
479
  }
477
- if (!terminal || !terminalEvent || !messageSnapshot || !stateSnapshot)
480
+ if (!terminalEvent || !messageSnapshot || !stateSnapshot)
478
481
  throw new ClientError("CHAT_STREAM_INCOMPLETE", "Agent stream ended without complete recovery snapshots.");
479
482
  let decoded;
480
483
  try {
481
- decoded = decodeAgentResponse(messageSnapshot.messages, stateSnapshot.snapshot, terminalEvent);
484
+ decoded = decodeAgentResponse(messageSnapshot.messages, stateSnapshot.snapshot, terminalEvent, this.id);
482
485
  }
483
486
  catch (error) {
484
487
  throw new ClientError("CHAT_STREAM_INCOMPLETE", error instanceof Error ? error.message : "Invalid Agent recovery response.");
@@ -492,6 +495,10 @@ class ChatClientImplementation {
492
495
  this.#event(stateSnapshot);
493
496
  this.#event(terminalEvent);
494
497
  };
498
+ if (decoded.type === "error") {
499
+ commit();
500
+ throw new ClientError(decoded.code, decoded.message);
501
+ }
495
502
  if (decoded.type === "success") {
496
503
  commit();
497
504
  return decoded.result;
@@ -561,7 +568,10 @@ class ChatClientImplementation {
561
568
  signal.throwIfAborted();
562
569
  if (error instanceof ClientError && error.code === "TOOL_CONFIRMATION_INVALIDATED")
563
570
  throw error;
564
- return { toolCallId: action.toolCallId, error: { code: error instanceof ClientError ? error.code : "TOOL_ERROR", message: error instanceof Error ? error.message : String(error) }, ...(confirmed ? { confirmed } : {}) };
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
575
  }
566
576
  finally {
567
577
  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;AAE9G,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;IACtC,YAAqB,IAAY,EAAE,OAAe;QAAI,KAAK,CAAC,OAAO,CAAC,CAAC;QAAhD,SAAI,GAAJ,IAAI,CAAQ;QAAqC,IAAI,CAAC,IAA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C,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 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: 2,\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 ? 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
+ {"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;IACtC,YAAqB,IAAY,EAAE,OAAe;QAAI,KAAK,CAAC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C,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;gBAC/H,IAAI,IAAI,EAAE,CAAC;oBAAC,MAAM,CAAC,cAAc,EAAE,CAAC;oBAAC,MAAM,YAAY,CAAC,KAAK,CAAC,IAAI,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 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"]}
package/dist/config.d.ts CHANGED
@@ -14,5 +14,10 @@ export type NexfaceModelConfig = (CompletionsOptions & {
14
14
  });
15
15
  export type NexfaceAgentConfig = Pick<Parameters<typeof createAgent>[0], "tools" | "skills" | "maxSteps" | "maxRetries" | "applicationContext"> & {
16
16
  model: NexfaceModelConfig;
17
+ /**
18
+ * @experimental Page decisions may change in future releases.
19
+ * @beta
20
+ */
21
+ pageDecision?: NonNullable<Parameters<typeof createAgent>[0]["pageDecision"]>;
17
22
  };
18
23
  export declare function resolveModelConfig(config: NexfaceModelConfig): import("@nexface/agent").AgentModelConfig;
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,IAAI,WAAW,EAAiD,MAAM,mCAAmC,CAAC;AACpI,OAAO,EAAE,iBAAiB,IAAI,SAAS,EAA+C,MAAM,iCAAiC,CAAC;AAC9H,OAAO,EAAE,iBAAiB,IAAI,SAAS,EAA+C,MAAM,mCAAmC,CAAC;AAChI,OAAO,EAAE,iBAAiB,IAAI,MAAM,EAA4C,MAAM,qCAAqC,CAAC;AAa5H,MAAM,UAAU,kBAAkB,CAAC,MAA0B;IAC3D,QAAQ,MAAM,CAAC,QAAQ,EAAE,CAAC;QACxB,KAAK,SAAS,CAAC;QACf,KAAK,oBAAoB,CAAC,CAAC,CAAC;YAC1B,MAAM,EAAE,QAAQ,EAAE,GAAG,OAAO,EAAE,GAAG,MAAM,CAAC;YACxC,OAAO,WAAW,CAAC,OAAO,CAAC,CAAC;QAC9B,CAAC;QACD,KAAK,kBAAkB,CAAC,CAAC,CAAC;YACxB,MAAM,EAAE,QAAQ,EAAE,GAAG,OAAO,EAAE,GAAG,MAAM,CAAC;YACxC,OAAO,SAAS,CAAC,OAAO,CAAC,CAAC;QAC5B,CAAC;QACD,KAAK,oBAAoB,CAAC,CAAC,CAAC;YAC1B,MAAM,EAAE,QAAQ,EAAE,GAAG,OAAO,EAAE,GAAG,MAAM,CAAC;YACxC,OAAO,SAAS,CAAC,OAAO,CAAC,CAAC;QAC5B,CAAC;QACD,KAAK,sBAAsB,CAAC,CAAC,CAAC;YAC5B,MAAM,EAAE,QAAQ,EAAE,GAAG,OAAO,EAAE,GAAG,MAAM,CAAC;YACxC,OAAO,MAAM,CAAC,OAAO,CAAC,CAAC;QACzB,CAAC;QACD;YACE,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;IAC3D,CAAC;AACH,CAAC","sourcesContent":["import type { createAgent } from \"@nexface/agent\";\nimport { createModelConfig as completions, type ModelConfigOptions as CompletionsOptions } from \"@nexface/agent/openai-completions\";\nimport { createModelConfig as responses, type ModelConfigOptions as ResponsesOptions } from \"@nexface/agent/openai-responses\";\nimport { createModelConfig as anthropic, type ModelConfigOptions as AnthropicOptions } from \"@nexface/agent/anthropic-messages\";\nimport { createModelConfig as google, type ModelConfigOptions as GoogleOptions } from \"@nexface/agent/google-generative-ai\";\n\nexport type NexfaceModelConfig =\n | (CompletionsOptions & { protocol?: \"openai-completions\" })\n | (ResponsesOptions & { protocol: \"openai-responses\" })\n | (AnthropicOptions & { protocol: \"anthropic-messages\" })\n | (GoogleOptions & { protocol: \"google-generative-ai\" });\n\nexport type NexfaceAgentConfig = Pick<\n Parameters<typeof createAgent>[0],\n \"tools\" | \"skills\" | \"maxSteps\" | \"maxRetries\" | \"applicationContext\"\n> & { model: NexfaceModelConfig };\n\nexport function resolveModelConfig(config: NexfaceModelConfig) {\n switch (config.protocol) {\n case undefined:\n case \"openai-completions\": {\n const { protocol, ...options } = config;\n return completions(options);\n }\n case \"openai-responses\": {\n const { protocol, ...options } = config;\n return responses(options);\n }\n case \"anthropic-messages\": {\n const { protocol, ...options } = config;\n return anthropic(options);\n }\n case \"google-generative-ai\": {\n const { protocol, ...options } = config;\n return google(options);\n }\n default:\n throw new Error(\"Unsupported Nexface model protocol.\");\n }\n}\n"]}
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,IAAI,WAAW,EAAiD,MAAM,mCAAmC,CAAC;AACpI,OAAO,EAAE,iBAAiB,IAAI,SAAS,EAA+C,MAAM,iCAAiC,CAAC;AAC9H,OAAO,EAAE,iBAAiB,IAAI,SAAS,EAA+C,MAAM,mCAAmC,CAAC;AAChI,OAAO,EAAE,iBAAiB,IAAI,MAAM,EAA4C,MAAM,qCAAqC,CAAC;AAoB5H,MAAM,UAAU,kBAAkB,CAAC,MAA0B;IAC3D,QAAQ,MAAM,CAAC,QAAQ,EAAE,CAAC;QACxB,KAAK,SAAS,CAAC;QACf,KAAK,oBAAoB,CAAC,CAAC,CAAC;YAC1B,MAAM,EAAE,QAAQ,EAAE,GAAG,OAAO,EAAE,GAAG,MAAM,CAAC;YACxC,OAAO,WAAW,CAAC,OAAO,CAAC,CAAC;QAC9B,CAAC;QACD,KAAK,kBAAkB,CAAC,CAAC,CAAC;YACxB,MAAM,EAAE,QAAQ,EAAE,GAAG,OAAO,EAAE,GAAG,MAAM,CAAC;YACxC,OAAO,SAAS,CAAC,OAAO,CAAC,CAAC;QAC5B,CAAC;QACD,KAAK,oBAAoB,CAAC,CAAC,CAAC;YAC1B,MAAM,EAAE,QAAQ,EAAE,GAAG,OAAO,EAAE,GAAG,MAAM,CAAC;YACxC,OAAO,SAAS,CAAC,OAAO,CAAC,CAAC;QAC5B,CAAC;QACD,KAAK,sBAAsB,CAAC,CAAC,CAAC;YAC5B,MAAM,EAAE,QAAQ,EAAE,GAAG,OAAO,EAAE,GAAG,MAAM,CAAC;YACxC,OAAO,MAAM,CAAC,OAAO,CAAC,CAAC;QACzB,CAAC;QACD;YACE,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;IAC3D,CAAC;AACH,CAAC","sourcesContent":["import type { createAgent } from \"@nexface/agent\";\nimport { createModelConfig as completions, type ModelConfigOptions as CompletionsOptions } from \"@nexface/agent/openai-completions\";\nimport { createModelConfig as responses, type ModelConfigOptions as ResponsesOptions } from \"@nexface/agent/openai-responses\";\nimport { createModelConfig as anthropic, type ModelConfigOptions as AnthropicOptions } from \"@nexface/agent/anthropic-messages\";\nimport { createModelConfig as google, type ModelConfigOptions as GoogleOptions } from \"@nexface/agent/google-generative-ai\";\n\nexport type NexfaceModelConfig =\n | (CompletionsOptions & { protocol?: \"openai-completions\" })\n | (ResponsesOptions & { protocol: \"openai-responses\" })\n | (AnthropicOptions & { protocol: \"anthropic-messages\" })\n | (GoogleOptions & { protocol: \"google-generative-ai\" });\n\nexport type NexfaceAgentConfig = Pick<\n Parameters<typeof createAgent>[0],\n \"tools\" | \"skills\" | \"maxSteps\" | \"maxRetries\" | \"applicationContext\"\n> & {\n model: NexfaceModelConfig;\n /**\n * @experimental Page decisions may change in future releases.\n * @beta\n */\n pageDecision?: NonNullable<Parameters<typeof createAgent>[0][\"pageDecision\"]>;\n};\n\nexport function resolveModelConfig(config: NexfaceModelConfig) {\n switch (config.protocol) {\n case undefined:\n case \"openai-completions\": {\n const { protocol, ...options } = config;\n return completions(options);\n }\n case \"openai-responses\": {\n const { protocol, ...options } = config;\n return responses(options);\n }\n case \"anthropic-messages\": {\n const { protocol, ...options } = config;\n return anthropic(options);\n }\n case \"google-generative-ai\": {\n const { protocol, ...options } = config;\n return google(options);\n }\n default:\n throw new Error(\"Unsupported Nexface model protocol.\");\n }\n}\n"]}
@@ -1,3 +1,3 @@
1
1
  import { type JSX } from "react";
2
2
  import type { ChatProps } from "./types.js";
3
- export declare function Chat({ title, avatar, welcomeMessage, welcomeDescription, open, onOpenChange, placeholder, layout, side, className, style, suggestions, attachments, showSessionList, showToolDetails, onFullscreenChange, onRunResult }: ChatProps): JSX.Element | null;
3
+ export declare function Chat({ title, avatar, welcomeMessage, welcomeDescription, open, onOpenChange, placeholder, layout, side, className, style, suggestions, attachments, sessionSidebar, showToolDetails, onFullscreenChange, onRunResult }: ChatProps): JSX.Element | null;
@@ -24,13 +24,33 @@ const Icon = forwardRef(function Icon({ label, children, className, ...props },
24
24
  return _jsx("button", { ref: ref, type: "button", "aria-label": label, title: label, className: cn("text-muted-foreground hover:text-foreground rounded-control grid size-7 place-items-center transition-colors [&>svg]:size-4", className), ...props, children: children });
25
25
  });
26
26
  function Resize({ label, width, onResize, side = "left", edge = "left", min, max }) {
27
+ const handle = useRef(null);
27
28
  const drag = useRef(null);
29
+ const readWidth = () => handle.current?.parentElement?.getBoundingClientRect().width || width;
30
+ const update = () => {
31
+ const element = handle.current;
32
+ if (!element)
33
+ return;
34
+ const current = Math.round(readWidth());
35
+ element.setAttribute("aria-valuenow", String(current));
36
+ element.setAttribute("aria-valuemin", String(Math.min(min, current)));
37
+ element.setAttribute("aria-valuemax", String(Math.max(max, current)));
38
+ };
39
+ useLayoutEffect(update);
40
+ useLayoutEffect(() => {
41
+ const panel = handle.current?.parentElement;
42
+ if (!panel || typeof ResizeObserver === "undefined")
43
+ return;
44
+ const observer = new ResizeObserver(update);
45
+ observer.observe(panel);
46
+ return () => observer.disconnect();
47
+ }, [min, max]);
28
48
  const clamp = (value) => Math.max(min, Math.min(max, window.innerWidth - 32, value));
29
- return _jsx("div", { className: cn("absolute inset-y-0 z-3 w-1.5 cursor-col-resize touch-none max-sm:hidden", edge === "left" ? "left-0" : "right-0"), role: "separator", "aria-label": label, "aria-orientation": "vertical", "aria-valuemin": min, "aria-valuemax": max, "aria-valuenow": width, tabIndex: 0, onKeyDown: (event) => { if (!["ArrowLeft", "ArrowRight"].includes(event.key))
30
- return; event.preventDefault(); onResize(clamp(width + (event.key === "ArrowRight" ? 16 : -16) * (side === "left" ? 1 : -1))); }, onPointerDown: (event) => { drag.current = { x: event.clientX, width }; event.currentTarget.setPointerCapture(event.pointerId); }, onPointerMove: (event) => { if (drag.current)
49
+ return _jsx("div", { ref: handle, className: cn("absolute inset-y-0 z-3 w-1.5 cursor-col-resize touch-none max-sm:hidden", edge === "left" ? "left-0" : "right-0"), role: "separator", "aria-label": label, "aria-orientation": "vertical", tabIndex: 0, onKeyDown: (event) => { if (!["ArrowLeft", "ArrowRight"].includes(event.key))
50
+ return; event.preventDefault(); onResize(clamp(readWidth() + (event.key === "ArrowRight" ? 16 : -16) * (side === "left" ? 1 : -1))); }, onPointerDown: (event) => { drag.current = { x: event.clientX, width: readWidth() }; event.currentTarget.setPointerCapture(event.pointerId); }, onPointerMove: (event) => { if (drag.current)
31
51
  onResize(clamp(drag.current.width + (event.clientX - drag.current.x) * (side === "left" ? 1 : -1))); }, onPointerUp: () => { drag.current = null; }, onPointerCancel: () => { drag.current = null; } });
32
52
  }
33
- export function Chat({ title = "Nexface", avatar, welcomeMessage = "今天想让我帮你做什么?", welcomeDescription, open = true, onOpenChange, placeholder = "描述你的任务...", layout = "floating", side = "right", className, style, suggestions = [], attachments = {}, showSessionList = true, showToolDetails = false, onFullscreenChange, onRunResult }) {
53
+ export function Chat({ title = "Nexface", avatar, welcomeMessage = "今天想让我帮你做什么?", welcomeDescription, open = true, onOpenChange, placeholder = "描述你的任务...", layout = "floating", side = "right", className, style, suggestions = [], attachments = {}, sessionSidebar = true, showToolDetails = false, onFullscreenChange, onRunResult }) {
34
54
  const chat = useChat();
35
55
  const { activeSessionId: sessionId, messages, status, interrupt } = chat;
36
56
  const busy = status !== "idle" && status !== "error";
@@ -47,28 +67,33 @@ export function Chat({ title = "Nexface", avatar, welcomeMessage = "今天想让
47
67
  }
48
68
  }, [open, fullscreen, onFullscreenChange]);
49
69
  const [sidebar, setSidebar] = useState(false);
50
- const sidebarOpen = showSessionList && sidebar;
51
- useEffect(() => { if (!showSessionList)
52
- setSidebar(false); }, [showSessionList]);
70
+ const sidebarEnabled = sessionSidebar !== false;
71
+ const sidebarLayout = layout === "inline" && !fullscreen && typeof sessionSidebar === "object" && sessionSidebar.layout === "outside" ? "outside" : "overlay";
72
+ const sidebarOpen = sidebarEnabled && sidebar;
73
+ useEffect(() => { if (!sidebarEnabled)
74
+ setSidebar(false); }, [sidebarEnabled]);
53
75
  const [threadSearch, setThreadSearch] = useState("");
54
76
  const [width, setWidth] = useState(546);
55
- const [sidebarWidth, setSidebarWidth] = useState(240);
77
+ const [sidebarWidth, setSidebarWidth] = useState();
56
78
  const submitting = useRef(undefined);
57
79
  const [editing, setEditing] = useState();
58
80
  const [notice, setNotice] = useState("");
59
81
  const dialogReturnFocus = useRef(null);
60
82
  const panel = useRef(null);
61
- const sidebarHadFocus = useRef(false);
83
+ const sidebarWasOpen = useRef(false);
84
+ const sidebarNav = useRef(null);
85
+ const sidebarTrigger = useRef(null);
62
86
  const headerFocusButton = useRef(null);
63
87
  useLayoutEffect(() => {
64
88
  if (sidebarOpen) {
65
- sidebarHadFocus.current = false;
89
+ sidebarWasOpen.current = true;
90
+ sidebarNav.current?.querySelector('input[type="search"]')?.focus();
66
91
  return;
67
92
  }
68
- if (sidebarHadFocus.current && document.activeElement === document.body)
69
- headerFocusButton.current?.focus();
70
- sidebarHadFocus.current = false;
71
- }, [sidebarOpen]);
93
+ if (sidebarWasOpen.current)
94
+ (sidebarTrigger.current ?? headerFocusButton.current)?.focus();
95
+ sidebarWasOpen.current = false;
96
+ }, [sidebarOpen, sidebarLayout]);
72
97
  const [dialog, updateDialog] = useState();
73
98
  const setDialog = (next) => {
74
99
  if (next)
@@ -78,7 +103,7 @@ export function Chat({ title = "Nexface", avatar, welcomeMessage = "今天想让
78
103
  const byId = useMemo(() => new Map(projectMessages(messages).map((message) => [message.id, message])), [messages]);
79
104
  const visited = useRef(new Set());
80
105
  visited.current.add(sessionId);
81
- const activeTitle = chat.sessions.find((session) => session.id === sessionId)?.title || title;
106
+ const activeTitle = messages.length ? chat.sessions.find((session) => session.id === sessionId)?.title || title : title;
82
107
  const latestUser = [...messages].reverse().find((message) => message.role === "user");
83
108
  useEffect(() => { if (chat.completed && chat.consumeCompletion(chat.completed.id))
84
109
  onRunResult?.(chat.completed.result); }, [chat.completed, chat.consumeCompletion, onRunResult]);
@@ -122,8 +147,15 @@ export function Chat({ title = "Nexface", avatar, welcomeMessage = "今天想让
122
147
  else
123
148
  perform();
124
149
  });
125
- return _jsx(_Fragment, { children: chat.sessions.filter((session) => visited.current.has(session.id)).map((session) => _jsx(SessionRuntime, { id: session.id, chat: chat, options: attachments, blocked: sessionBusy, active: session.id === sessionId, onEdit: editThroughRuntime, children: (binding) => open ? _jsx(ChatSurface, { className: `nexface-chat${className ? ` ${className}` : ""}`, "data-layout": layout, "data-side": side, "data-open": open || undefined, "data-fullscreen": fullscreen && open || undefined, "data-nexface-ignore": true, style: { "--nexface-chat-panel-width": `${width}px`, ...style, ...(fullscreen ? { border: 0, borderRadius: 0 } : {}) }, children: _jsxs("section", { ref: panel, className: cn("nexface-chat__panel relative flex h-full min-h-0 rounded-[inherit] bg-background"), "aria-label": `${title} chat`, children: [layout === "docked" && !fullscreen ? _jsx(Resize, { label: "\u8C03\u6574\u804A\u5929\u5BBD\u5EA6", width: width, onResize: setWidth, side: side, edge: side === "left" ? "right" : "left", min: 320, max: 960 }) : null, sidebarOpen ? _jsxs("nav", { onFocusCapture: () => { sidebarHadFocus.current = true; }, onBlurCapture: (event) => { if (!event.currentTarget.contains(event.relatedTarget))
126
- sidebarHadFocus.current = false; }, className: cn("relative flex shrink-0 flex-col overflow-auto border-r border-foreground/10 bg-foreground/[0.025] dark:bg-foreground/[0.04] max-sm:absolute max-sm:inset-y-0 max-sm:left-0 max-sm:z-4 max-sm:max-w-[85%]"), style: { width: sidebarWidth }, "aria-label": "\u4F1A\u8BDD\u5386\u53F2", children: [_jsx(Resize, { label: "\u8C03\u6574\u4F1A\u8BDD\u5386\u53F2\u680F\u5BBD\u5EA6", width: sidebarWidth, onResize: setSidebarWidth, edge: "right", min: 180, max: 400 }), _jsxs("div", { className: cn("flex h-12 shrink-0 items-center gap-2 border-b border-foreground/10 px-4"), children: [_jsxs(Avatar, { children: [avatar ? _jsx(AvatarImage, { src: avatar, alt: "" }) : null, _jsx(AvatarFallback, { children: _jsx(Robot, { size: 20 }) })] }), _jsx("strong", { className: cn("min-w-0 flex-1 truncate text-[13px] font-medium"), children: title }), _jsx(Icon, { label: "\u6536\u8D77\u4F1A\u8BDD\u5386\u53F2", "aria-expanded": sidebarOpen, className: cn("size-7 shrink-0"), onClick: () => setSidebar(false), children: _jsx(PanelLeftIcon, { className: cn("size-4") }) })] }), _jsxs("div", { className: cn("flex min-h-0 flex-1 flex-col p-3"), children: [_jsx(ThreadListNew, { disabled: sessionBusy || binding.sending, onClick: (event) => { event.preventDefault(); safe(() => chat.createSession()); } }), _jsx(ThreadListSearch, { value: threadSearch, onValueChange: setThreadSearch }), _jsx("small", { className: cn("text-muted-foreground mt-5 mb-1 px-2 text-xs font-medium"), children: "\u6700\u8FD1\u4F1A\u8BDD" }), _jsx(ThreadListRoot, { children: _jsx(ThreadListPrimitive.Items, { children: ({ threadListItem: session }) => (session.title ?? "新会话").toLocaleLowerCase().includes(threadSearch.trim().toLocaleLowerCase()) ? _jsx(ThreadListItem, { disabled: sessionBusy || binding.sending, menu: (beginRename) => _jsxs(_Fragment, { children: [_jsx(DropdownMenuItem, { disabled: sessionBusy || binding.sending, onSelect: beginRename, children: "\u91CD\u547D\u540D" }), _jsx(DropdownMenuItem, { variant: "destructive", disabled: busy || binding.sending, onSelect: () => setDialog({ title: "清空消息?", description: "该会话消息将被清除,业务操作不会回滚。", dangerous: true, action: () => chat.clearSession(session.id) }), children: "\u6E05\u7A7A\u6D88\u606F" }), _jsx(DropdownMenuItem, { variant: "destructive", disabled: busy || binding.sending, onSelect: () => setDialog({ title: "删除会话?", description: "聊天记录将被删除,此操作无法撤销。", dangerous: true, action: () => chat.deleteSession(session.id) }), children: "\u5220\u9664\u4F1A\u8BDD" })] }) }) : null }) }), threadSearch.trim() && !chat.sessions.some((session) => session.title.toLocaleLowerCase().includes(threadSearch.trim().toLocaleLowerCase())) ? _jsx("div", { "data-slot": "aui_thread-list-empty", className: cn("text-muted-foreground px-2.5 py-4 text-sm"), children: "\u672A\u627E\u5230\u4F1A\u8BDD" }) : null] })] }) : null, _jsxs("div", { className: cn("flex min-h-0 min-w-0 flex-1 flex-col"), children: [_jsxs("header", { "data-slot": "nexface_chat_header", className: cn("border-foreground/10 flex h-12 shrink-0 min-w-0 items-center gap-2 border-b px-4 md:px-5"), children: [_jsxs("div", { className: cn("flex min-w-0 flex-1 items-center gap-2 whitespace-nowrap"), children: [showSessionList && !sidebarOpen ? _jsx(Icon, { label: "\u67E5\u770B\u4F1A\u8BDD\u5386\u53F2", "aria-expanded": sidebarOpen, className: cn("size-7 shrink-0"), onClick: () => setSidebar(true), children: _jsx(PanelLeftIcon, { className: cn("size-4") }) }) : null, _jsx("strong", { className: cn("truncate text-[13px] font-medium"), children: activeTitle })] }), _jsxs("div", { className: cn("-me-1.5 ml-auto flex shrink-0 items-center gap-1.5"), children: [_jsxs(DropdownMenu, { modal: false, children: [_jsx(DropdownMenuTrigger, { asChild: true, children: _jsx(Icon, { label: "\u66F4\u591A\u4F1A\u8BDD\u64CD\u4F5C", children: _jsx(MoreHorizontalIcon, {}) }) }), _jsx(DropdownMenuContent, { align: "end", children: _jsx(DropdownMenuItem, { variant: "destructive", disabled: busy || binding.sending, onSelect: () => setDialog({ title: "清空全部历史?", description: "所有聊天记录将被清除,业务操作不会回滚。", dangerous: true, action: chat.clearAllSessions }), children: "\u6E05\u7A7A\u5168\u90E8\u5386\u53F2" }) })] }), _jsx(Icon, { label: "\u65B0\u5EFA\u804A\u5929\u4F1A\u8BDD", disabled: sessionBusy || binding.sending, onClick: () => safe(() => chat.createSession()), children: _jsx(Plus, {}) }), _jsx(Icon, { ref: headerFocusButton, label: fullscreen ? "退出全屏" : "全屏", onClick: () => changeFullscreen(!fullscreen), children: fullscreen ? _jsx(Collapse, {}) : _jsx(Expand, {}) }), onOpenChange ? _jsx(Icon, { label: "\u5173\u95ED Agent \u5BF9\u8BDD", onClick: () => onOpenChange(false), children: _jsx(X, {}) }) : null] })] }), _jsx("div", { "data-slot": "nexface_chat_body", className: cn("relative flex min-h-0 flex-1"), children: _jsx(Thread, { empty: !messages.length, welcome: _jsx(Greeting, { title: welcomeMessage, description: welcomeDescription }), suggestions: _jsx(Suggestions, { suggestions: suggestions, disabled: busy || binding.sending, onSend: (prompt) => void execute(prompt) }), footer: _jsxs(_Fragment, { children: [_jsx(FollowUps, { disabled: busy || binding.sending, onSend: (prompt) => { binding.runtime.thread.composer.setText(prompt); void binding.send(); } }), chat.storageWarning ? _jsx("div", { role: "alert", className: cn("text-muted-foreground text-xs"), children: chat.storageWarning }) : null, notice ? _jsxs("div", { role: "status", className: cn("text-muted-foreground text-xs"), children: [notice, _jsx("button", { onClick: () => setNotice(""), children: "\u00D7" })] }) : null, binding.notice ? _jsxs("div", { role: "alert", className: cn("text-muted-foreground text-xs"), children: [binding.notice, _jsx("button", { onClick: () => binding.setNotice(""), children: "\u5173\u95ED" })] }) : null] }), composer: _jsx(AssistantComposer, { binding: binding, options: attachments, placeholder: placeholder, busy: busy || Boolean(interrupt), cancelling: status === "cancelling", cancel: chat.cancel }), renderMessage: ({ message: rendered }) => {
150
+ return _jsx(_Fragment, { children: chat.sessions.filter((session) => visited.current.has(session.id)).map((session) => _jsx(SessionRuntime, { id: session.id, chat: chat, options: attachments, blocked: sessionBusy, active: session.id === sessionId, onEdit: editThroughRuntime, children: (binding) => open ? _jsx(ChatSurface, { className: `nexface-chat${className ? ` ${className}` : ""}`, "data-layout": layout, "data-side": side, "data-open": open || undefined, "data-fullscreen": fullscreen && open || undefined, "data-session-sidebar-open": sidebarOpen || undefined, "data-nexface-ignore": true, style: { "--nexface-chat-panel-width": `${width}px`, ...style, ...(fullscreen ? { border: 0, borderRadius: 0 } : {}) }, children: _jsxs("section", { ref: panel, className: cn("nexface-chat__panel relative flex h-full min-h-0 rounded-[inherit] bg-background"), "aria-label": `${title} chat`, children: [layout === "docked" && !fullscreen ? _jsx(Resize, { label: "\u8C03\u6574\u804A\u5929\u5BBD\u5EA6", width: width, onResize: setWidth, side: side, edge: side === "left" ? "right" : "left", min: 320, max: 960 }) : null, sidebarOpen ? _jsxs(_Fragment, { children: [sidebarLayout === "overlay" ? _jsx("button", { type: "button", tabIndex: -1, "aria-label": "\u5173\u95ED\u4F1A\u8BDD\u5386\u53F2\u6D6E\u5C42", className: cn("absolute inset-0 z-4 rounded-[inherit] bg-black/10"), onClick: () => setSidebar(false) }) : null, _jsxs("nav", { ref: sidebarNav, onKeyDown: (event) => {
151
+ if (event.key === "Escape" && !event.nativeEvent.isComposing && !event.target.closest('[data-slot="aui_thread-list-item-rename"]')) {
152
+ event.preventDefault();
153
+ setSidebar(false);
154
+ }
155
+ }, onClick: (event) => {
156
+ if (event.target.closest('[data-slot="aui_thread-list-item-trigger"], [data-slot="aui_thread-list-new"]'))
157
+ setSidebar(false);
158
+ }, "data-slot": "nexface_session-sidebar", "data-layout": sidebarLayout, className: cn("nexface-chat__session-sidebar absolute inset-y-0 z-5 flex flex-col overflow-auto border-r border-foreground/10 bg-background shadow-lg"), style: sidebarLayout === "overlay" && sidebarWidth !== undefined ? { width: sidebarWidth } : undefined, "aria-label": "\u4F1A\u8BDD\u5386\u53F2", children: [sidebarLayout === "overlay" ? _jsx(Resize, { label: "\u8C03\u6574\u4F1A\u8BDD\u5386\u53F2\u680F\u5BBD\u5EA6", width: sidebarWidth ?? 240, onResize: setSidebarWidth, edge: "right", min: 180, max: 400 }) : null, _jsxs("div", { className: cn("flex h-12 shrink-0 items-center gap-2 border-b border-foreground/10 px-4 md:px-5"), children: [sidebarLayout === "overlay" ? _jsx(Icon, { label: "\u6536\u8D77\u4F1A\u8BDD\u5386\u53F2", "aria-expanded": sidebarOpen, className: cn("size-7 shrink-0"), onClick: () => setSidebar(false), children: _jsx(PanelLeftIcon, { className: cn("size-4") }) }) : null, _jsxs(Avatar, { children: [avatar ? _jsx(AvatarImage, { src: avatar, alt: "" }) : null, _jsx(AvatarFallback, { children: _jsx(Robot, { size: 20 }) })] }), _jsx("strong", { className: cn("min-w-0 flex-1 truncate text-[13px] font-medium"), children: title })] }), _jsxs("div", { className: cn("flex min-h-0 flex-1 flex-col p-3"), children: [_jsx(ThreadListNew, { disabled: sessionBusy || binding.sending, onClick: (event) => { event.preventDefault(); safe(() => chat.createSession()); } }), _jsx(ThreadListSearch, { value: threadSearch, onValueChange: setThreadSearch }), _jsx("small", { className: cn("text-muted-foreground mt-5 mb-1 px-2 text-xs font-medium"), children: "\u6700\u8FD1\u4F1A\u8BDD" }), _jsx(ThreadListRoot, { children: _jsx(ThreadListPrimitive.Items, { children: ({ threadListItem: session }) => (session.title ?? "新会话").toLocaleLowerCase().includes(threadSearch.trim().toLocaleLowerCase()) ? _jsx(ThreadListItem, { disabled: sessionBusy || binding.sending, menu: (beginRename) => _jsxs(_Fragment, { children: [_jsx(DropdownMenuItem, { disabled: sessionBusy || binding.sending, onSelect: beginRename, children: "\u91CD\u547D\u540D" }), _jsx(DropdownMenuItem, { variant: "destructive", disabled: busy || binding.sending, onSelect: () => setDialog({ title: "清空消息?", description: "该会话消息将被清除,业务操作不会回滚。", dangerous: true, action: () => chat.clearSession(session.id) }), children: "\u6E05\u7A7A\u6D88\u606F" }), _jsx(DropdownMenuItem, { variant: "destructive", disabled: busy || binding.sending, onSelect: () => setDialog({ title: "删除会话?", description: "聊天记录将被删除,此操作无法撤销。", dangerous: true, action: () => chat.deleteSession(session.id) }), children: "\u5220\u9664\u4F1A\u8BDD" })] }) }) : null }) }), threadSearch.trim() && !chat.sessions.some((session) => session.title.toLocaleLowerCase().includes(threadSearch.trim().toLocaleLowerCase())) ? _jsx("div", { "data-slot": "aui_thread-list-empty", className: cn("text-muted-foreground px-2.5 py-4 text-sm"), children: "\u672A\u627E\u5230\u4F1A\u8BDD" }) : null] })] })] }) : null, _jsxs("div", { inert: sidebarOpen && sidebarLayout === "overlay", className: cn("flex min-h-0 min-w-0 flex-1 flex-col"), children: [_jsxs("header", { "data-slot": "nexface_chat_header", className: cn("border-foreground/10 flex h-12 shrink-0 min-w-0 items-center gap-2 border-b px-4 md:px-5"), children: [_jsxs("div", { className: cn("flex min-w-0 flex-1 items-center gap-2 whitespace-nowrap"), children: [sidebarEnabled && (sidebarLayout === "outside" || !sidebarOpen) ? _jsx(Icon, { ref: sidebarTrigger, label: sidebarOpen ? "收起会话历史" : "查看会话历史", "aria-expanded": sidebarOpen, className: cn("size-7 shrink-0"), onClick: () => setSidebar((value) => !value), children: _jsx(PanelLeftIcon, { className: cn("size-4") }) }) : null, _jsx("strong", { className: cn("truncate text-[13px] font-medium"), children: activeTitle })] }), _jsxs("div", { className: cn("-me-1.5 ml-auto flex shrink-0 items-center gap-1.5"), children: [_jsxs(DropdownMenu, { modal: false, children: [_jsx(DropdownMenuTrigger, { asChild: true, children: _jsx(Icon, { label: "\u66F4\u591A\u4F1A\u8BDD\u64CD\u4F5C", children: _jsx(MoreHorizontalIcon, {}) }) }), _jsx(DropdownMenuContent, { align: "end", children: _jsx(DropdownMenuItem, { variant: "destructive", disabled: busy || binding.sending, onSelect: () => setDialog({ title: "清空全部历史?", description: "所有聊天记录将被清除,业务操作不会回滚。", dangerous: true, action: chat.clearAllSessions }), children: "\u6E05\u7A7A\u5168\u90E8\u5386\u53F2" }) })] }), _jsx(Icon, { label: "\u65B0\u5EFA\u804A\u5929\u4F1A\u8BDD", disabled: sessionBusy || binding.sending, onClick: () => safe(() => chat.createSession()), children: _jsx(Plus, {}) }), _jsx(Icon, { ref: headerFocusButton, label: fullscreen ? "退出全屏" : "全屏", onClick: () => changeFullscreen(!fullscreen), children: fullscreen ? _jsx(Collapse, {}) : _jsx(Expand, {}) }), onOpenChange ? _jsx(Icon, { label: "\u5173\u95ED Agent \u5BF9\u8BDD", onClick: () => onOpenChange(false), children: _jsx(X, {}) }) : null] })] }), _jsx("div", { "data-slot": "nexface_chat_body", className: cn("relative flex min-h-0 flex-1"), children: _jsx(Thread, { empty: !messages.length, welcome: _jsx(Greeting, { title: welcomeMessage, description: welcomeDescription }), suggestions: _jsx(Suggestions, { suggestions: suggestions, disabled: busy || binding.sending, onSend: (prompt) => void execute(prompt) }), footer: _jsxs(_Fragment, { children: [_jsx(FollowUps, { disabled: busy || binding.sending, onSend: (prompt) => { binding.runtime.thread.composer.setText(prompt); void binding.send(); } }), chat.storageWarning ? _jsx("div", { role: "alert", className: cn("text-muted-foreground text-xs"), children: chat.storageWarning }) : null, notice ? _jsxs("div", { role: "status", className: cn("text-muted-foreground text-xs"), children: [notice, _jsx("button", { onClick: () => setNotice(""), children: "\u00D7" })] }) : null, binding.notice ? _jsxs("div", { role: "alert", className: cn("text-muted-foreground text-xs"), children: [binding.notice, _jsx("button", { onClick: () => binding.setNotice(""), children: "\u5173\u95ED" })] }) : null] }), composer: _jsx(AssistantComposer, { binding: binding, options: attachments, placeholder: placeholder, busy: busy || Boolean(interrupt), cancelling: status === "cancelling", cancel: chat.cancel }), renderMessage: ({ message: rendered }) => {
127
159
  const message = byId.get(rendered.id);
128
160
  return message ? _jsx(_Fragment, { children: editing?.id === message.id ? _jsx(EditComposer, { onKeyDown: (event) => { if (event.key === "Escape" && !event.nativeEvent.isComposing)
129
161
  setEditing(undefined); }, inputProps: { "aria-label": "编辑消息内容", value: editing.text, disabled: busy || binding.sending, onChange: (event) => setEditing({ ...editing, text: event.target.value }) }, cancelProps: { type: "button", onClick: () => setEditing(undefined) }, sendProps: { type: "button", disabled: busy || binding.sending || (!editing.text.trim() && !editing.files.length) }, children: editing.files.map((file) => _jsxs("div", { className: cn("bg-muted flex min-w-0 items-center gap-2 rounded-md px-3 py-2 text-sm"), children: [_jsx(Paperclip, { className: cn("size-4 shrink-0") }), _jsx("span", { className: cn("min-w-0 flex-1 truncate"), children: file.name }), _jsx(TooltipIconButton, { tooltip: "\u79FB\u9664\u9644\u4EF6", type: "button", disabled: busy || binding.sending, "aria-label": `移除 ${file.name}`, onClick: () => setEditing({ ...editing, files: editing.files.filter((item) => item.id !== file.id) }), children: _jsx(X, {}) })] }, file.id)) }) : _jsx(_Fragment, { children: message.role === "user" ? _jsx(UserMessage, { attachments: _jsx("div", { className: cn("aui-user-message-attachments-end col-span-full col-start-1 row-start-1 flex w-full flex-row justify-end gap-2 empty:hidden"), children: _jsx(MessagePrimitive.Attachments, { children: ({ attachment }) => _jsx(AttachmentTile, { savedPreview: message.attachments?.find((file) => file.id === attachment.id)?.preview }) }) }), actions: message.id === latestUser?.id ? _jsx(ActionBarPrimitive.Edit, { asChild: true, children: _jsx("button", { type: "button", "aria-label": "\u7F16\u8F91\u6D88\u606F", className: cn(actionButtonClass), disabled: busy || binding.sending, onClick: () => setEditing({ id: message.id, text: textOf(message), files: message.attachments ?? [] }), children: _jsx(Edit, { className: cn("size-4") }) }) }) : null, children: _jsx(MessagePrimitive.Parts, {}) }) : _jsx(AssistantMessage, { children: _jsx(AssistantParts, { showDetails: showToolDetails, errors: message.parts.flatMap((part) => part.type === "tool" && part.isError ? [{ id: part.toolCallId, message: part.errorMessage ?? "操作执行失败" }] : []) }) }) }) }) : _jsx(AssistantMessage, { children: _jsx(AssistantParts, { showDetails: showToolDetails, errors: [] }) });