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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,4 @@
1
+ import { decodeToolProxy } from "./shared/tool-proxy.js";
1
2
  import { toolError, isNexfaceError } from "./errors.js";
2
3
  import { EventType, mergeMetadata } from "@ag-ui/core";
3
4
  import { getToolResultError } from "./tool-result.js";
@@ -389,9 +390,9 @@ export function projectMessages(messages) {
389
390
  let name = call.function.name, args = call.function.arguments;
390
391
  if (name === "nxf_callAppTool")
391
392
  try {
392
- const parsed = JSON.parse(args);
393
+ const parsed = decodeToolProxy(JSON.parse(args));
393
394
  name = parsed.name;
394
- args = JSON.stringify(parsed.input);
395
+ args = JSON.stringify(parsed.arguments);
395
396
  }
396
397
  catch {
397
398
  /* Incomplete arguments remain visible. */
@@ -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
@@ -61,6 +61,7 @@ export type NexfaceProviderProps = {
61
61
  }) => Promise<Response>;
62
62
  agent?: never;
63
63
  });
64
+ export declare function canEditChatSession(chat: UseChatResult, sessionId: string): boolean;
64
65
  export declare function assertChatSendable(chat: UseChatResult, sessionId: string): void;
65
66
  export declare function useToolPresentations(): {
66
67
  controller: ToolPresentationController | undefined;
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";
@@ -16,6 +17,10 @@ export function isChatError(error) {
16
17
  typeof value.message === "string");
17
18
  }
18
19
  const sendGuards = new WeakMap();
20
+ const appendOnlySessions = new WeakMap();
21
+ export function canEditChatSession(chat, sessionId) {
22
+ return !appendOnlySessions.get(chat)?.has(sessionId);
23
+ }
19
24
  // Read the live Store at draft submission, including updates before React commits.
20
25
  export function assertChatSendable(chat, sessionId) {
21
26
  sendGuards.get(chat.sendMessage)?.(sessionId);
@@ -81,8 +86,12 @@ export function NexfaceProvider(props) {
81
86
  controller.id = saved.id;
82
87
  controller.setPageResolver((name) => pageTools.current.has(name));
83
88
  if (saved)
84
- controller.restore(saved.messages);
89
+ controller.restore(saved.messages, saved.appendOnly);
85
90
  return {
91
+ confirmations: {
92
+ restored: new Set(saved?.messages.flatMap((message) => message.parts.flatMap((part) => (part.type === "tool" ? [part.toolCallId] : []))) ?? []),
93
+ decisions: new Map(),
94
+ },
86
95
  id: saved?.id ?? controller.id,
87
96
  client,
88
97
  ...(saved?.title ? { title: saved.title } : {}),
@@ -148,12 +157,13 @@ export function NexfaceProvider(props) {
148
157
  sessions: store.sessions.map((session) => ({
149
158
  id: session.id,
150
159
  ...(session.title ? { title: session.title } : {}),
160
+ ...(getClientController(session.client).appendOnly ? { appendOnly: true } : {}),
151
161
  messages: [...projectMessages(session.client.getMessages())],
152
162
  })),
153
163
  };
154
164
  if (writeChatStorage(chatStorageKey, stored, store.version) === "conflict") {
155
165
  store.warning =
156
- "Chat history was updated in another tab. Saving is paused in this tab. Copy any new messages you want to keep, then refresh to load the latest history.";
166
+ "Chat history changed in another tab or window. Saving is paused here. Copy any new messages you want to keep, then refresh to load the latest history.";
157
167
  changed();
158
168
  }
159
169
  };
@@ -284,6 +294,82 @@ export function NexfaceProvider(props) {
284
294
  throw new ClientError("CHAT_RUN_ACTIVE", "A task is already running. Try sending again later.");
285
295
  getClientController(active().client).assertRecoveryAvailable();
286
296
  });
297
+ const confirmationState = (sessionId, request) => {
298
+ const session = store.sessions.find((item) => item.id === sessionId);
299
+ if (!session)
300
+ return "expired";
301
+ const decided = session.confirmations.decisions.get(request.toolCallId);
302
+ if (decided)
303
+ return decided;
304
+ if (session.confirmations.restored.has(request.toolCallId))
305
+ return "expired";
306
+ const messages = projectMessages(session.client.getMessages());
307
+ const lastUser = messages.reduce((last, message, index) => (message.role === "user" ? index : last), -1);
308
+ const owner = messages.findIndex((message) => message.parts.some((part) => {
309
+ const actual = confirmationRequest(part);
310
+ return (actual?.toolCallId === request.toolCallId &&
311
+ actual.requestId === request.requestId &&
312
+ actual.toolName === request.toolName);
313
+ }));
314
+ for (const message of messages)
315
+ for (const part of message.parts) {
316
+ if (part.type !== "tool" || part.name !== request.toolName)
317
+ continue;
318
+ try {
319
+ const decision = JSON.parse(part.arguments)?.confirmation;
320
+ if (decision?.requestId === request.requestId && typeof decision.approved === "boolean")
321
+ return decision.approved ? "approved" : "rejected";
322
+ }
323
+ catch {
324
+ /* Streaming arguments may be incomplete. */
325
+ }
326
+ }
327
+ return owner > lastUser && store.activeId === sessionId ? "pending" : "expired";
328
+ };
329
+ confirmationControllers.set(sendMessage, {
330
+ state: confirmationState,
331
+ async respond(sessionId, request, approved) {
332
+ sendGuards.get(sendMessage)?.(sessionId);
333
+ if (confirmationState(sessionId, request) !== "pending")
334
+ throw new ClientError("INVALID_INPUT", "This confirmation is no longer available.");
335
+ const session = active();
336
+ const controller = getClientController(session.client);
337
+ const messageId = createId();
338
+ session.confirmations.decisions.set(request.toolCallId, "sending");
339
+ changed();
340
+ try {
341
+ const decision = approved ? "确认" : "拒绝";
342
+ const pending = controller.send(JSON.stringify({
343
+ userDecision: {
344
+ toolName: request.toolName,
345
+ toolCallId: request.toolCallId,
346
+ requestId: request.requestId,
347
+ approved,
348
+ },
349
+ message: `${decision}:${request.message}`,
350
+ }), {
351
+ id: messageId,
352
+ role: "user",
353
+ parts: [{ type: "text", text: `${decision}此操作` }],
354
+ });
355
+ if (controller.getMessages().some((message) => message.id === messageId)) {
356
+ session.confirmations.decisions.set(request.toolCallId, approved ? "approved" : "rejected");
357
+ delete store.completion;
358
+ changed();
359
+ }
360
+ const result = await pending;
361
+ store.completion = { id: createId(), sessionId, result };
362
+ }
363
+ finally {
364
+ // An admitted reply remains answered even if the following model run fails.
365
+ if (controller.getMessages().some((message) => message.id === messageId))
366
+ session.confirmations.decisions.set(request.toolCallId, approved ? "approved" : "rejected");
367
+ else
368
+ session.confirmations.decisions.delete(request.toolCallId);
369
+ changed();
370
+ }
371
+ },
372
+ });
287
373
  const session = active();
288
374
  const client = session.client;
289
375
  const controller = getClientController(client);
@@ -371,6 +457,9 @@ export function NexfaceProvider(props) {
371
457
  }
372
458
  },
373
459
  };
460
+ appendOnlySessions.set(value, new Set(store.sessions
461
+ .filter(({ client }) => getClientController(client).appendOnly)
462
+ .map(({ id }) => id)));
374
463
  return (_jsx(ChatContext.Provider, { value: value, children: _jsx(ToolPresentationProvider, { controller: getToolPresentationController(toolRuntime), report: (cause, sessionId, toolCallId) => reportError({
375
464
  cause,
376
465
  sessionId,
@@ -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-alpha.1",
3
+ "version": "0.1.20-alpha.2",
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-alpha.1",
22
+ "@nexface/agent": "0.1.20-alpha.2",
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-alpha.1",
31
+ "@nexface/tools": "0.1.20-alpha.2",
32
32
  "react": ">=17",
33
33
  "react-dom": ">=17"
34
34
  },