@nexface/chat 0.1.20-alpha.1 → 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,12 @@ export function projectMessages(messages) {
413
418
  arguments: args,
414
419
  ...(result?.role === "tool"
415
420
  ? {
416
- result: result.content,
421
+ result: result.content.length > 4000 && !parseConfirmationResult(result.content)
422
+ ? JSON.stringify({
423
+ contentOmitted: true,
424
+ preview: result.content.slice(0, 4000),
425
+ })
426
+ : result.content,
417
427
  isError,
418
428
  }
419
429
  : {}),
@@ -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
@@ -8,7 +8,6 @@ import type { NexfaceAgentConfig } from "./config.js";
8
8
  import type { ChatRunResult } from "./types.js";
9
9
  import { type Attachment } from "./attachments.js";
10
10
  import type { UIMessage } from "./messages.js";
11
- import { type ToolPresentationController } from "./shared/tool-presentation.js";
12
11
  export type { UIMessage, UIMessagePart } from "./messages.js";
13
12
  export type ChatCommandErrorCode = "CHAT_MODEL_SWITCH_BLOCKED" | "CHAT_RUNTIME_CHANGED" | "CHAT_RUN_ACTIVE" | "CHAT_SESSION_CREATE_BLOCKED" | "CHAT_SESSION_SWITCH_BLOCKED" | "INVALID_INPUT" | "UNKNOWN_SESSION";
14
13
  export interface ChatError {
@@ -61,10 +60,8 @@ export type NexfaceProviderProps = {
61
60
  }) => Promise<Response>;
62
61
  agent?: never;
63
62
  });
63
+ export declare function isChatRecoveryUnavailable(chat: UseChatResult): boolean;
64
+ export declare function canEditChatSession(chat: UseChatResult, sessionId: string): boolean;
64
65
  export declare function assertChatSendable(chat: UseChatResult, sessionId: string): void;
65
- export declare function useToolPresentations(): {
66
- controller: ToolPresentationController | undefined;
67
- report(cause: unknown, sessionId: string, toolCallId: string): void;
68
- } | null;
69
66
  export declare function NexfaceProvider(props: NexfaceProviderProps): ReactElement;
70
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";
@@ -7,7 +8,6 @@ import { createChatClient, getClientController, ClientError, } from "./client.js
7
8
  import { attachmentContent } from "./attachments.js";
8
9
  import { projectMessages } from "./protocol-messages.js";
9
10
  import { chatStorageKey, readChatStorage, writeChatStorage } from "./storage.js";
10
- import { getToolPresentationController, } from "./shared/tool-presentation.js";
11
11
  export function isChatError(error) {
12
12
  const value = error;
13
13
  return (!!value &&
@@ -16,25 +16,19 @@ export function isChatError(error) {
16
16
  typeof value.message === "string");
17
17
  }
18
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
+ }
19
27
  // Read the live Store at draft submission, including updates before React commits.
20
28
  export function assertChatSendable(chat, sessionId) {
21
29
  sendGuards.get(chat.sendMessage)?.(sessionId);
22
30
  }
23
31
  const ChatContext = createContext(null);
24
- const ToolPresentationContext = createContext(null);
25
- function ToolPresentationProvider({ controller, report, children, }) {
26
- const [, changed] = useReducer((revision) => revision + 1, 0);
27
- useLayoutEffect(() => {
28
- const unsubscribe = controller?.subscribe(changed);
29
- // Child bindings may have registered before this provider's layout effect.
30
- changed();
31
- return unsubscribe;
32
- }, [controller]);
33
- return (_jsx(ToolPresentationContext.Provider, { value: { controller, report }, children: children }));
34
- }
35
- export function useToolPresentations() {
36
- return useContext(ToolPresentationContext);
37
- }
38
32
  const createId = () => globalThis.crypto.randomUUID();
39
33
  const textOf = (message) => message.parts
40
34
  .filter((part) => part.type === "text")
@@ -81,8 +75,12 @@ export function NexfaceProvider(props) {
81
75
  controller.id = saved.id;
82
76
  controller.setPageResolver((name) => pageTools.current.has(name));
83
77
  if (saved)
84
- controller.restore(saved.messages);
78
+ controller.restore(saved.messages, saved.appendOnly);
85
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
+ },
86
84
  id: saved?.id ?? controller.id,
87
85
  client,
88
86
  ...(saved?.title ? { title: saved.title } : {}),
@@ -148,6 +146,7 @@ export function NexfaceProvider(props) {
148
146
  sessions: store.sessions.map((session) => ({
149
147
  id: session.id,
150
148
  ...(session.title ? { title: session.title } : {}),
149
+ ...(getClientController(session.client).appendOnly ? { appendOnly: true } : {}),
151
150
  messages: [...projectMessages(session.client.getMessages())],
152
151
  })),
153
152
  };
@@ -284,6 +283,82 @@ export function NexfaceProvider(props) {
284
283
  throw new ClientError("CHAT_RUN_ACTIVE", "A task is already running. Try sending again later.");
285
284
  getClientController(active().client).assertRecoveryAvailable();
286
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
+ });
287
362
  const session = active();
288
363
  const client = session.client;
289
364
  const controller = getClientController(client);
@@ -371,17 +446,17 @@ export function NexfaceProvider(props) {
371
446
  }
372
447
  },
373
448
  };
374
- return (_jsx(ChatContext.Provider, { value: value, children: _jsx(ToolPresentationProvider, { controller: getToolPresentationController(toolRuntime), report: (cause, sessionId, toolCallId) => reportError({
375
- cause,
376
- sessionId,
377
- toolCallId,
378
- code: "CHAT_TOOL_RENDER_FAILED",
379
- }, onError.current), 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) => {
380
- if (registered)
381
- pageTools.current.add(name);
382
- else
383
- pageTools.current.delete(name);
384
- }, children: children }) }) }) }));
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)));
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) => {
455
+ if (registered)
456
+ pageTools.current.add(name);
457
+ else
458
+ pageTools.current.delete(name);
459
+ }, children: children }) }) }));
385
460
  }
386
461
  export function useChat() {
387
462
  const chat = useContext(ChatContext);
@@ -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