@nexface/chat 0.1.20 → 0.1.21

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.
@@ -1,3 +1,5 @@
1
+ import { parseConfirmationResult } from "./tool-confirmation.js";
2
+ import { decodeToolProxy } from "./shared/tool-proxy.js";
1
3
  import { toolError, isNexfaceError } from "./errors.js";
2
4
  import { EventType, mergeMetadata } from "@ag-ui/core";
3
5
  import { getToolResultError } from "./tool-result.js";
@@ -349,14 +351,16 @@ export function projectMessages(messages) {
349
351
  if (message.role === "reasoning" && assistantIds.has(metadata?.reasoningOwnerId))
350
352
  return [];
351
353
  const parts = [];
352
- const text = typeof metadata?.reasoningText === "string"
353
- ? metadata.reasoningText
354
- : typeof message.content === "string"
355
- ? message.content
356
- : (message.content ?? [])
357
- .filter((part) => part.type === "text")
358
- .map((part) => part.text)
359
- .join("");
354
+ const text = typeof metadata?.stoppedText === "string"
355
+ ? metadata.stoppedText
356
+ : typeof metadata?.reasoningText === "string"
357
+ ? metadata.reasoningText
358
+ : typeof message.content === "string"
359
+ ? message.content
360
+ : (message.content ?? [])
361
+ .filter((part) => part.type === "text")
362
+ .map((part) => part.text)
363
+ .join("");
360
364
  const reasoning = ownedReasoning.get(message.id) ?? [];
361
365
  let offset = 0;
362
366
  for (const entry of reasoning) {
@@ -376,6 +380,7 @@ export function projectMessages(messages) {
376
380
  if (message.role === "reasoning" && !text)
377
381
  return [];
378
382
  if (typeof metadata?.reasoningText === "string" &&
383
+ typeof metadata?.stoppedText !== "string" &&
379
384
  typeof message.content === "string" &&
380
385
  message.content !== text) {
381
386
  parts.push({ type: "text", text: message.content });
@@ -389,9 +394,9 @@ export function projectMessages(messages) {
389
394
  let name = call.function.name, args = call.function.arguments;
390
395
  if (name === "nxf_callAppTool")
391
396
  try {
392
- const parsed = JSON.parse(args);
397
+ const parsed = decodeToolProxy(JSON.parse(args));
393
398
  name = parsed.name;
394
- args = JSON.stringify(parsed.input);
399
+ args = JSON.stringify(parsed.arguments);
395
400
  }
396
401
  catch {
397
402
  /* Incomplete arguments remain visible. */
@@ -413,7 +418,7 @@ export function projectMessages(messages) {
413
418
  arguments: args,
414
419
  ...(result?.role === "tool"
415
420
  ? {
416
- result: result.content.length > 4000
421
+ result: result.content.length > 4000 && !parseConfirmationResult(result.content)
417
422
  ? JSON.stringify({
418
423
  contentOmitted: true,
419
424
  preview: result.content.slice(0, 4000),
@@ -1,3 +1,4 @@
1
+ import { decodeToolProxy } from "./shared/tool-proxy.js";
1
2
  export function decodeAgentResponse(messages, snapshot, terminal) {
2
3
  const state = snapshot;
3
4
  const continuation = state?.nexface;
@@ -68,10 +69,13 @@ export function decodeAgentResponse(messages, snapshot, terminal) {
68
69
  if (!args || typeof args !== "object" || Array.isArray(args))
69
70
  throw new Error("Invalid pending tool arguments.");
70
71
  const input = args;
71
- const name = call.name === "nxf_callAppTool" ? input.name : call.name;
72
+ const proxy = call.name === "nxf_callAppTool" ? decodeToolProxy(input) : undefined;
73
+ const name = proxy ? proxy.name : call.name;
72
74
  const toolInput = call.name === "nxf_callAppTool"
73
- ? input.input
74
- : Object.fromEntries(Object.entries(input).filter(([key]) => key !== "progressLabel"));
75
+ ? proxy.arguments
76
+ : actionIsNative(call.name)
77
+ ? Object.fromEntries(Object.entries(input).filter(([key]) => key !== "progressLabel"))
78
+ : input;
75
79
  if (extension.kind !== "client-tool-execution")
76
80
  throw new Error("Unsupported remote interrupt.");
77
81
  const action = extension.action;
@@ -87,3 +91,6 @@ export function decodeAgentResponse(messages, snapshot, terminal) {
87
91
  }
88
92
  return { type: "client-tool-execution", interruptId: interrupt.id, action };
89
93
  }
94
+ function actionIsNative(name) {
95
+ return ["nxf_getSnapshot", "nxf_executeAction", "nxf_applyAction"].includes(name);
96
+ }
package/dist/react.d.ts CHANGED
@@ -60,6 +60,8 @@ export type NexfaceProviderProps = {
60
60
  }) => Promise<Response>;
61
61
  agent?: never;
62
62
  });
63
+ export declare function isChatRecoveryUnavailable(chat: UseChatResult): boolean;
64
+ export declare function canEditChatSession(chat: UseChatResult, sessionId: string): boolean;
63
65
  export declare function assertChatSendable(chat: UseChatResult, sessionId: string): void;
64
66
  export declare function NexfaceProvider(props: NexfaceProviderProps): ReactElement;
65
67
  export declare function useChat(): UseChatResult;
package/dist/react.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { confirmationControllers, confirmationRequest, } from "./tool-confirmation.js";
2
3
  import { reportError } from "./errors.js";
3
4
  import { createContext, useContext, useEffect, useLayoutEffect, useRef, useReducer, useCallback, } from "react";
4
5
  import { ToolsProvider } from "@nexface/tools";
@@ -15,6 +16,14 @@ export function isChatError(error) {
15
16
  typeof value.message === "string");
16
17
  }
17
18
  const sendGuards = new WeakMap();
19
+ const appendOnlySessions = new WeakMap();
20
+ const chatsWithoutRecovery = new WeakSet();
21
+ export function isChatRecoveryUnavailable(chat) {
22
+ return chatsWithoutRecovery.has(chat);
23
+ }
24
+ export function canEditChatSession(chat, sessionId) {
25
+ return !appendOnlySessions.get(chat)?.has(sessionId);
26
+ }
18
27
  // Read the live Store at draft submission, including updates before React commits.
19
28
  export function assertChatSendable(chat, sessionId) {
20
29
  sendGuards.get(chat.sendMessage)?.(sessionId);
@@ -66,8 +75,12 @@ export function NexfaceProvider(props) {
66
75
  controller.id = saved.id;
67
76
  controller.setPageResolver((name) => pageTools.current.has(name));
68
77
  if (saved)
69
- controller.restore(saved.messages);
78
+ controller.restore(saved.messages, saved.appendOnly);
70
79
  return {
80
+ confirmations: {
81
+ restored: new Set(saved?.messages.flatMap((message) => message.parts.flatMap((part) => (part.type === "tool" ? [part.toolCallId] : []))) ?? []),
82
+ decisions: new Map(),
83
+ },
71
84
  id: saved?.id ?? controller.id,
72
85
  client,
73
86
  ...(saved?.title ? { title: saved.title } : {}),
@@ -133,6 +146,7 @@ export function NexfaceProvider(props) {
133
146
  sessions: store.sessions.map((session) => ({
134
147
  id: session.id,
135
148
  ...(session.title ? { title: session.title } : {}),
149
+ ...(getClientController(session.client).appendOnly ? { appendOnly: true } : {}),
136
150
  messages: [...projectMessages(session.client.getMessages())],
137
151
  })),
138
152
  };
@@ -269,6 +283,82 @@ export function NexfaceProvider(props) {
269
283
  throw new ClientError("CHAT_RUN_ACTIVE", "A task is already running. Try sending again later.");
270
284
  getClientController(active().client).assertRecoveryAvailable();
271
285
  });
286
+ const confirmationState = (sessionId, request) => {
287
+ const session = store.sessions.find((item) => item.id === sessionId);
288
+ if (!session)
289
+ return "expired";
290
+ const decided = session.confirmations.decisions.get(request.toolCallId);
291
+ if (decided)
292
+ return decided;
293
+ if (session.confirmations.restored.has(request.toolCallId))
294
+ return "expired";
295
+ const messages = projectMessages(session.client.getMessages());
296
+ const lastUser = messages.reduce((last, message, index) => (message.role === "user" ? index : last), -1);
297
+ const owner = messages.findIndex((message) => message.parts.some((part) => {
298
+ const actual = confirmationRequest(part);
299
+ return (actual?.toolCallId === request.toolCallId &&
300
+ actual.requestId === request.requestId &&
301
+ actual.toolName === request.toolName);
302
+ }));
303
+ for (const message of messages)
304
+ for (const part of message.parts) {
305
+ if (part.type !== "tool" || part.name !== request.toolName)
306
+ continue;
307
+ try {
308
+ const decision = JSON.parse(part.arguments)?.confirmation;
309
+ if (decision?.requestId === request.requestId && typeof decision.approved === "boolean")
310
+ return decision.approved ? "approved" : "rejected";
311
+ }
312
+ catch {
313
+ /* Streaming arguments may be incomplete. */
314
+ }
315
+ }
316
+ return owner > lastUser && store.activeId === sessionId ? "pending" : "expired";
317
+ };
318
+ confirmationControllers.set(sendMessage, {
319
+ state: confirmationState,
320
+ async respond(sessionId, request, approved) {
321
+ sendGuards.get(sendMessage)?.(sessionId);
322
+ if (confirmationState(sessionId, request) !== "pending")
323
+ throw new ClientError("INVALID_INPUT", "This confirmation is no longer available.");
324
+ const session = active();
325
+ const controller = getClientController(session.client);
326
+ const messageId = createId();
327
+ session.confirmations.decisions.set(request.toolCallId, "sending");
328
+ changed();
329
+ try {
330
+ const decision = approved ? "确认" : "拒绝";
331
+ const pending = controller.send(JSON.stringify({
332
+ userDecision: {
333
+ toolName: request.toolName,
334
+ toolCallId: request.toolCallId,
335
+ requestId: request.requestId,
336
+ approved,
337
+ },
338
+ message: `${decision}:${request.message}`,
339
+ }), {
340
+ id: messageId,
341
+ role: "user",
342
+ parts: [{ type: "text", text: `${decision}此操作` }],
343
+ });
344
+ if (controller.getMessages().some((message) => message.id === messageId)) {
345
+ session.confirmations.decisions.set(request.toolCallId, approved ? "approved" : "rejected");
346
+ delete store.completion;
347
+ changed();
348
+ }
349
+ const result = await pending;
350
+ store.completion = { id: createId(), sessionId, result };
351
+ }
352
+ finally {
353
+ // An admitted reply remains answered even if the following model run fails.
354
+ if (controller.getMessages().some((message) => message.id === messageId))
355
+ session.confirmations.decisions.set(request.toolCallId, approved ? "approved" : "rejected");
356
+ else
357
+ session.confirmations.decisions.delete(request.toolCallId);
358
+ changed();
359
+ }
360
+ },
361
+ });
272
362
  const session = active();
273
363
  const client = session.client;
274
364
  const controller = getClientController(client);
@@ -356,6 +446,11 @@ export function NexfaceProvider(props) {
356
446
  }
357
447
  },
358
448
  };
449
+ if (controller.recoveryUnavailable)
450
+ chatsWithoutRecovery.add(value);
451
+ appendOnlySessions.set(value, new Set(store.sessions
452
+ .filter(({ client }) => getClientController(client).appendOnly)
453
+ .map(({ id }) => id)));
359
454
  return (_jsx(ChatContext.Provider, { value: value, children: _jsx(ToolsProvider, { toolRuntime: toolRuntime, webMcp: webMcp, children: _jsx(PageConfirmationProvider, { interrupt: approval, onConfirm: () => getClientController(active().client).confirmPage(), onBindingRemoved: () => getClientController(active().client).invalidate("Page confirmation entry was removed."), onBindingRegistration: (name, registered) => {
360
455
  if (registered)
361
456
  pageTools.current.add(name);
@@ -1,4 +1,4 @@
1
- export declare const TOOL_ERROR_CODES: readonly ["EXECUTION_OUTCOME_UNKNOWN", "ACTION_IN_FLIGHT", "ACTION_NOT_HANDLED", "ACTION_TARGET_UNAVAILABLE", "BROWSER_EXECUTION_FAILED", "BROWSER_SNAPSHOT_REQUIRED", "BROWSER_TOOLS_UNAVAILABLE", "CONTRACT_MISMATCH", "DUPLICATE_BINDING", "INVALID_INPUT", "INVALID_TOOL_RUNTIME", "OPERATION_BUSY", "TOOL_CANCELLED", "TOOL_CONFIRMATION_INVALIDATED", "TOOL_CONFIRMATION_REJECTED", "TOOL_ERROR", "TOOL_REGISTRATION_TIMEOUT", "TOOL_SKIPPED", "TOOL_UNAVAILABLE", "UNKNOWN_TOOL"];
1
+ export declare const TOOL_ERROR_CODES: readonly ["EXECUTION_OUTCOME_UNKNOWN", "ACTION_IN_FLIGHT", "ACTION_NOT_HANDLED", "ACTION_TARGET_UNAVAILABLE", "BROWSER_EXECUTION_FAILED", "BROWSER_SNAPSHOT_REQUIRED", "BROWSER_TOOLS_UNAVAILABLE", "CONTRACT_MISMATCH", "DUPLICATE_BINDING", "INVALID_INPUT", "INVALID_CONFIRMATION_RESULT", "TOOL_CONFIRMATION_LIMIT", "INVALID_TOOL_RUNTIME", "OPERATION_BUSY", "TOOL_CANCELLED", "TOOL_CONFIRMATION_INVALIDATED", "TOOL_CONFIRMATION_REJECTED", "TOOL_ERROR", "TOOL_REGISTRATION_TIMEOUT", "TOOL_SKIPPED", "TOOL_UNAVAILABLE", "UNKNOWN_TOOL"];
2
2
  type AgentToolErrorCode = (typeof TOOL_ERROR_CODES)[number];
3
3
  export declare class AgentToolError extends Error {
4
4
  readonly code: AgentToolErrorCode;
@@ -10,6 +10,8 @@ export const TOOL_ERROR_CODES = [
10
10
  "CONTRACT_MISMATCH",
11
11
  "DUPLICATE_BINDING",
12
12
  "INVALID_INPUT",
13
+ "INVALID_CONFIRMATION_RESULT",
14
+ "TOOL_CONFIRMATION_LIMIT",
13
15
  "INVALID_TOOL_RUNTIME",
14
16
  "OPERATION_BUSY",
15
17
  "TOOL_CANCELLED",
@@ -0,0 +1,6 @@
1
+ /** Decode the proxy envelope without changing business arguments. */
2
+ export declare function decodeToolProxy(value: Record<string, unknown>): {
3
+ name: string;
4
+ arguments: Record<string, unknown>;
5
+ progressLabel?: string;
6
+ };
@@ -0,0 +1,25 @@
1
+ // Generated from shared/tool-proxy.ts. Do not edit manually.
2
+ /** Decode the proxy envelope without changing business arguments. */
3
+ export function decodeToolProxy(value) {
4
+ if (typeof value.name !== "string" || !value.name.trim())
5
+ throw new Error("nxf_callAppTool needs a non-empty string name.");
6
+ const keys = Object.keys(value).filter((key) => !["name", "arguments", "input", "progressLabel"].includes(key));
7
+ if (keys.length)
8
+ throw new Error(`nxf_callAppTool received unexpected fields: ${keys.join(", ")}.`);
9
+ const modern = Object.hasOwn(value, "arguments");
10
+ const legacy = Object.hasOwn(value, "input");
11
+ if (modern === legacy)
12
+ throw new Error("nxf_callAppTool requires exactly one of arguments or legacy input.");
13
+ const args = modern ? value.arguments : value.input;
14
+ if (!args || typeof args !== "object" || Array.isArray(args))
15
+ throw new Error(`nxf_callAppTool arguments for "${value.name}" must be an object.`);
16
+ if (value.progressLabel !== undefined && typeof value.progressLabel !== "string")
17
+ throw new Error("nxf_callAppTool progressLabel must be a string.");
18
+ return {
19
+ name: value.name,
20
+ arguments: args,
21
+ ...(typeof value.progressLabel === "string" && value.progressLabel.trim()
22
+ ? { progressLabel: value.progressLabel.trim() }
23
+ : {}),
24
+ };
25
+ }
package/dist/storage.d.ts CHANGED
@@ -4,6 +4,7 @@ export declare const chatStorageKey = "nexface:chat:sessions:v3";
4
4
  interface StoredSession {
5
5
  id: string;
6
6
  title?: string;
7
+ appendOnly?: boolean;
7
8
  messages: UIMessage[];
8
9
  }
9
10
  interface StoredChat {
package/dist/storage.js CHANGED
@@ -176,6 +176,7 @@ export function readChatStorage(key, version) {
176
176
  typeof session.id !== "string" ||
177
177
  !session.id ||
178
178
  (session.title !== undefined && typeof session.title !== "string") ||
179
+ (session.appendOnly !== undefined && typeof session.appendOnly !== "boolean") ||
179
180
  !Array.isArray(session.messages) ||
180
181
  !session.messages.every(isMessage) ||
181
182
  sessions.some((existing) => existing.id === session.id))
@@ -183,6 +184,7 @@ export function readChatStorage(key, version) {
183
184
  sessions.push({
184
185
  id: session.id,
185
186
  ...(session.title ? { title: session.title } : {}),
187
+ ...(session.appendOnly ? { appendOnly: true } : {}),
186
188
  messages: migratePageTaskResults(withoutReasoning(session.messages)).map(restoreMessage),
187
189
  });
188
190
  }
@@ -198,9 +200,10 @@ export function writeChatStorage(key, state, version) {
198
200
  const next = JSON.stringify({
199
201
  version: 3,
200
202
  activeSessionId: state.activeSessionId,
201
- sessions: state.sessions.map(({ id, title, messages }) => ({
203
+ sessions: state.sessions.map(({ id, title, appendOnly, messages }) => ({
202
204
  id,
203
205
  title,
206
+ ...(appendOnly ? { appendOnly } : {}),
204
207
  messages: withoutReasoning(messages).map((message) => ({
205
208
  ...message,
206
209
  parts: message.parts.map((part) => part.type === "tool" && part.error
@@ -0,0 +1,5 @@
1
+ import type { UIMessagePart } from "./messages.js";
2
+ export declare function ToolConfirmationCards({ sessionId, parts, }: {
3
+ sessionId: string;
4
+ parts: readonly UIMessagePart[];
5
+ }): import("react").JSX.Element;
@@ -0,0 +1,33 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { useState } from "react";
3
+ import { useChat } from "./react.js";
4
+ import { confirmationControllers, confirmationRequest } from "./tool-confirmation.js";
5
+ import { Button } from "./ui/button.js";
6
+ import { cn } from "./ui/utils.js";
7
+ export function ToolConfirmationCards({ sessionId, parts, }) {
8
+ const chat = useChat();
9
+ const [error, setError] = useState();
10
+ const controller = confirmationControllers.get(chat.sendMessage);
11
+ return (_jsx(_Fragment, { children: parts.map((part) => {
12
+ const request = confirmationRequest(part);
13
+ if (!request || !controller)
14
+ return null;
15
+ const state = controller.state(sessionId, request);
16
+ const disabled = state !== "pending" || (chat.status !== "idle" && chat.status !== "error");
17
+ const respond = (approved) => {
18
+ setError(undefined);
19
+ void controller.respond(sessionId, request, approved).catch(() => {
20
+ if (controller.state(sessionId, request) === "pending")
21
+ setError({
22
+ toolCallId: request.toolCallId,
23
+ message: "Could not send your response. Please try again.",
24
+ });
25
+ });
26
+ };
27
+ return (_jsxs("section", { "aria-label": "\u64CD\u4F5C\u786E\u8BA4", className: cn("my-3 rounded-lg border p-4"), children: [_jsx("p", { className: cn("mb-3 whitespace-pre-wrap"), children: request.message }), state === "pending" || state === "sending" ? (_jsxs("div", { className: cn("flex gap-2"), children: [_jsx(Button, { disabled: disabled, onClick: () => respond(true), children: "\u786E\u8BA4" }), _jsx(Button, { variant: "outline", disabled: disabled, onClick: () => respond(false), children: "\u62D2\u7EDD" })] })) : (_jsx("p", { role: "status", children: state === "approved"
28
+ ? "已确认"
29
+ : state === "rejected"
30
+ ? "已拒绝"
31
+ : "此确认已失效,请重新发起操作。" })), error?.toolCallId === request.toolCallId ? _jsx("p", { role: "alert", children: error.message }) : null] }, request.toolCallId));
32
+ }) }));
33
+ }
@@ -0,0 +1,23 @@
1
+ import type { UIMessagePart } from "./messages.js";
2
+ export type ConfirmationRequest = {
3
+ toolCallId: string;
4
+ toolName: string;
5
+ requestId: string;
6
+ message: string;
7
+ };
8
+ export declare function parseConfirmationResult(content: string): {
9
+ requestId: string;
10
+ message: string;
11
+ } | undefined;
12
+ export declare function confirmationRequest(part: UIMessagePart): ConfirmationRequest | undefined;
13
+ export type ConfirmationState = "pending" | "sending" | "approved" | "rejected" | "expired";
14
+ export type ConfirmationSession = {
15
+ restored: Set<string>;
16
+ decisions: Map<string, ConfirmationState>;
17
+ };
18
+ type Controller = {
19
+ state(sessionId: string, request: ConfirmationRequest): ConfirmationState;
20
+ respond(sessionId: string, request: ConfirmationRequest, approved: boolean): Promise<void>;
21
+ };
22
+ export declare const confirmationControllers: WeakMap<(text: string, attachments?: import("./attachments.js").Attachment[], revisionOf?: string) => Promise<import("@nexface/agent").AgentRunResult>, Controller>;
23
+ export {};
@@ -0,0 +1,25 @@
1
+ export function parseConfirmationResult(content) {
2
+ try {
3
+ const parsed = JSON.parse(content);
4
+ const result = parsed?.result;
5
+ if (result?.status === "confirmation_required" &&
6
+ typeof result.requestId === "string" &&
7
+ result.requestId.trim() &&
8
+ typeof result.message === "string" &&
9
+ result.message.trim() &&
10
+ !parsed.error) {
11
+ return { requestId: result.requestId, message: result.message };
12
+ }
13
+ }
14
+ catch {
15
+ /* Other tool results are not confirmation requests. */
16
+ }
17
+ }
18
+ export function confirmationRequest(part) {
19
+ if (part.type !== "tool" || part.isError || !part.result)
20
+ return;
21
+ const result = parseConfirmationResult(part.result);
22
+ return result ? { ...result, toolCallId: part.toolCallId, toolName: part.name } : undefined;
23
+ }
24
+ // Internal bridge: the public useChat and Chat interfaces stay unchanged.
25
+ export const confirmationControllers = new WeakMap();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nexface/chat",
3
- "version": "0.1.20",
3
+ "version": "0.1.21",
4
4
  "type": "module",
5
5
  "types": "./dist/index.d.ts",
6
6
  "sideEffects": [
@@ -19,7 +19,7 @@
19
19
  },
20
20
  "dependencies": {
21
21
  "@ag-ui/core": "0.0.59",
22
- "@nexface/agent": "0.1.20",
22
+ "@nexface/agent": "0.1.21",
23
23
  "class-variance-authority": "0.7.1",
24
24
  "clsx": "2.1.1",
25
25
  "fast-json-patch": "3.1.1",
@@ -28,7 +28,7 @@
28
28
  "use-sync-external-store": "1.7.0"
29
29
  },
30
30
  "peerDependencies": {
31
- "@nexface/tools": "0.1.20",
31
+ "@nexface/tools": "0.1.21",
32
32
  "react": ">=17",
33
33
  "react-dom": ">=17"
34
34
  },