@nexface/chat 0.1.1-alpha.0
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/attachments.d.ts +10 -0
- package/dist/attachments.js +42 -0
- package/dist/attachments.js.map +1 -0
- package/dist/config.d.ts +18 -0
- package/dist/config.js +28 -0
- package/dist/config.js.map +1 -0
- package/dist/default-chat.d.ts +2 -0
- package/dist/default-chat.js +180 -0
- package/dist/default-chat.js.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -0
- package/dist/page-confirmation.d.ts +11 -0
- package/dist/page-confirmation.js +85 -0
- package/dist/page-confirmation.js.map +1 -0
- package/dist/react.d.ts +76 -0
- package/dist/react.js +704 -0
- package/dist/react.js.map +1 -0
- package/dist/styles.css +115 -0
- package/dist/types.d.ts +29 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/package.json +42 -0
package/dist/react.js
ADDED
|
@@ -0,0 +1,704 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useReducer, } from "react";
|
|
3
|
+
import { createAgent, } from "@nexface/agent";
|
|
4
|
+
import { ToolsProvider } from "@nexface/tools";
|
|
5
|
+
import { OperationHostContext } from "@nexface/tools/internal/react";
|
|
6
|
+
import { PageConfirmationProvider } from "./page-confirmation.js";
|
|
7
|
+
import { resolveModelConfig } from "./config.js";
|
|
8
|
+
import { EventType } from "@ag-ui/core";
|
|
9
|
+
const agentChatControllerSymbol = Symbol.for("@nexface/agent/chat-controller");
|
|
10
|
+
function getAgentChatController(agent) {
|
|
11
|
+
return agent[agentChatControllerSymbol];
|
|
12
|
+
}
|
|
13
|
+
export function isChatError(error) {
|
|
14
|
+
if (!error || typeof error !== "object")
|
|
15
|
+
return false;
|
|
16
|
+
const candidate = error;
|
|
17
|
+
return candidate.type === "chat_error"
|
|
18
|
+
&& typeof candidate.code === "string"
|
|
19
|
+
&& typeof candidate.message === "string";
|
|
20
|
+
}
|
|
21
|
+
class ChatErrorImplementation extends Error {
|
|
22
|
+
code;
|
|
23
|
+
type = "chat_error";
|
|
24
|
+
constructor(code, message) {
|
|
25
|
+
super(message);
|
|
26
|
+
this.code = code;
|
|
27
|
+
this.name = "ChatError";
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
const ChatError = ChatErrorImplementation;
|
|
31
|
+
function createId() {
|
|
32
|
+
return globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random()}`;
|
|
33
|
+
}
|
|
34
|
+
const maxChatToolDetailLength = 4_000;
|
|
35
|
+
function compactToolDetail(value) {
|
|
36
|
+
if (value.length <= maxChatToolDetailLength)
|
|
37
|
+
return value;
|
|
38
|
+
return JSON.stringify({
|
|
39
|
+
contentOmitted: true,
|
|
40
|
+
preview: value.slice(0, maxChatToolDetailLength),
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
function messageText(message) {
|
|
44
|
+
return message.parts
|
|
45
|
+
.filter((part) => part.type === "text")
|
|
46
|
+
.map((part) => part.text)
|
|
47
|
+
.join("");
|
|
48
|
+
}
|
|
49
|
+
function sessionTitle(session, index) {
|
|
50
|
+
if (session.title)
|
|
51
|
+
return session.title;
|
|
52
|
+
const firstUserMessage = session.messages.find((message) => message.role === "user");
|
|
53
|
+
const text = firstUserMessage ? messageText(firstUserMessage).trim() : "";
|
|
54
|
+
if (!text)
|
|
55
|
+
return `会话 ${index + 1}`;
|
|
56
|
+
return text.length > 24 ? `${text.slice(0, 24)}…` : text;
|
|
57
|
+
}
|
|
58
|
+
function settledToolState(parts) {
|
|
59
|
+
const toolParts = parts.filter((part) => part.type === "tool");
|
|
60
|
+
if (toolParts.some((part) => part.result === undefined))
|
|
61
|
+
return "running";
|
|
62
|
+
return toolParts.some((part) => part.isError) ? "error" : "success";
|
|
63
|
+
}
|
|
64
|
+
function toolErrorResult(code, message, details) {
|
|
65
|
+
return JSON.stringify({ error: { code, message, details } });
|
|
66
|
+
}
|
|
67
|
+
function settleInterruptMessages(messages, interrupt, code, message, reason) {
|
|
68
|
+
let pendingSeen = false;
|
|
69
|
+
return messages.map((chatMessage) => {
|
|
70
|
+
let changed = false;
|
|
71
|
+
const parts = chatMessage.parts.map((part) => {
|
|
72
|
+
if (part.type !== "tool" || part.result !== undefined)
|
|
73
|
+
return part;
|
|
74
|
+
if (part.toolCallId === interrupt.toolCallId) {
|
|
75
|
+
pendingSeen = true;
|
|
76
|
+
changed = true;
|
|
77
|
+
return {
|
|
78
|
+
...part,
|
|
79
|
+
result: toolErrorResult(code, message, {
|
|
80
|
+
reason,
|
|
81
|
+
toolExecuted: false,
|
|
82
|
+
}),
|
|
83
|
+
isError: true,
|
|
84
|
+
errorMessage: message,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
if (!pendingSeen)
|
|
88
|
+
return part;
|
|
89
|
+
changed = true;
|
|
90
|
+
const skippedMessage = "Skipped because an earlier tool call required confirmation.";
|
|
91
|
+
return {
|
|
92
|
+
...part,
|
|
93
|
+
result: toolErrorResult("TOOL_SKIPPED", skippedMessage, {
|
|
94
|
+
failedToolCallId: interrupt.toolCallId,
|
|
95
|
+
}),
|
|
96
|
+
isError: true,
|
|
97
|
+
errorMessage: skippedMessage,
|
|
98
|
+
};
|
|
99
|
+
});
|
|
100
|
+
return changed ? { ...chatMessage, parts, state: "error" } : chatMessage;
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
function updateSession(state, sessionId, update) {
|
|
104
|
+
return {
|
|
105
|
+
...state,
|
|
106
|
+
sessions: state.sessions.map((session) => session.id === sessionId ? update(session) : session),
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
export function applyEvent(messages, event) {
|
|
110
|
+
if (event.type === EventType.TEXT_MESSAGE_START) {
|
|
111
|
+
if (messages.some((message) => message.id === event.messageId))
|
|
112
|
+
return messages;
|
|
113
|
+
return [...messages, { id: event.messageId, role: "assistant", parts: [], state: "running" }];
|
|
114
|
+
}
|
|
115
|
+
if (event.type === EventType.TEXT_MESSAGE_CONTENT || event.type === EventType.TEXT_MESSAGE_END) {
|
|
116
|
+
return messages.map((message) => {
|
|
117
|
+
if (message.id !== event.messageId)
|
|
118
|
+
return message;
|
|
119
|
+
if (event.type === EventType.TEXT_MESSAGE_END)
|
|
120
|
+
return { ...message, state: "success" };
|
|
121
|
+
const parts = [...message.parts];
|
|
122
|
+
const index = parts.findIndex((part) => part.type === "text");
|
|
123
|
+
const current = parts[index];
|
|
124
|
+
if (current?.type === "text")
|
|
125
|
+
parts[index] = { type: "text", text: current.text + event.delta };
|
|
126
|
+
else
|
|
127
|
+
parts.push({ type: "text", text: event.delta });
|
|
128
|
+
return { ...message, parts };
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
if (event.type === EventType.TOOL_CALL_START) {
|
|
132
|
+
const id = event.parentMessageId ?? event.toolCallId;
|
|
133
|
+
const base = messages.some((message) => message.id === id) ? messages
|
|
134
|
+
: [...messages, { id, role: "assistant", parts: [] }];
|
|
135
|
+
return base.map((message) => message.id !== id ? message : {
|
|
136
|
+
...message, state: "running", parts: [...message.parts, {
|
|
137
|
+
type: "tool", toolCallId: event.toolCallId, name: event.toolCallName, arguments: "",
|
|
138
|
+
}],
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
if (event.type === EventType.TOOL_CALL_ARGS || event.type === EventType.TOOL_CALL_RESULT) {
|
|
142
|
+
return messages.map((message) => {
|
|
143
|
+
if (!message.parts.some((part) => part.type === "tool" && part.toolCallId === event.toolCallId))
|
|
144
|
+
return message;
|
|
145
|
+
const parts = message.parts.map((part) => {
|
|
146
|
+
if (part.type !== "tool" || part.toolCallId !== event.toolCallId)
|
|
147
|
+
return part;
|
|
148
|
+
if (event.type === EventType.TOOL_CALL_ARGS)
|
|
149
|
+
return { ...part, arguments: part.arguments + event.delta };
|
|
150
|
+
let isError = false;
|
|
151
|
+
let errorMessage;
|
|
152
|
+
try {
|
|
153
|
+
const error = JSON.parse(event.content).error;
|
|
154
|
+
isError = Boolean(error);
|
|
155
|
+
if (typeof error?.message === "string")
|
|
156
|
+
errorMessage = error.message;
|
|
157
|
+
}
|
|
158
|
+
catch { /* Plain Tool results are valid. */ }
|
|
159
|
+
return { ...part, result: compactToolDetail(event.content), isError,
|
|
160
|
+
...(errorMessage === undefined ? {} : { errorMessage }),
|
|
161
|
+
};
|
|
162
|
+
});
|
|
163
|
+
return { ...message, parts, state: settledToolState(parts) };
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
return messages;
|
|
167
|
+
}
|
|
168
|
+
function reducer(state, action) {
|
|
169
|
+
switch (action.type) {
|
|
170
|
+
case "replace-session":
|
|
171
|
+
return { ...state,
|
|
172
|
+
sessions: state.sessions.map((session) => session.id === action.sessionId ? { ...action.session, ...(session.title ? { title: session.title } : {}) } : session),
|
|
173
|
+
activeSessionId: state.activeSessionId === action.sessionId ? action.session.id : state.activeSessionId,
|
|
174
|
+
error: undefined,
|
|
175
|
+
};
|
|
176
|
+
case "rename-session":
|
|
177
|
+
return updateSession(state, action.sessionId, (session) => ({ ...session, title: action.title }));
|
|
178
|
+
case "remove-session":
|
|
179
|
+
return { ...state, sessions: state.sessions.filter((session) => session.id !== action.sessionId), activeSessionId: action.activeSessionId, error: undefined };
|
|
180
|
+
case "create-session":
|
|
181
|
+
return {
|
|
182
|
+
...state,
|
|
183
|
+
sessions: [...state.sessions, action.session],
|
|
184
|
+
activeSessionId: action.session.id,
|
|
185
|
+
error: undefined,
|
|
186
|
+
};
|
|
187
|
+
case "switch-session":
|
|
188
|
+
return { ...state, activeSessionId: action.sessionId, error: undefined };
|
|
189
|
+
case "append-message":
|
|
190
|
+
return updateSession(state, action.sessionId, (session) => ({
|
|
191
|
+
...session,
|
|
192
|
+
messages: [...session.messages, action.message],
|
|
193
|
+
}));
|
|
194
|
+
case "apply-event":
|
|
195
|
+
return updateSession(state, action.sessionId, (session) => ({
|
|
196
|
+
...session,
|
|
197
|
+
messages: applyEvent(session.messages, action.event),
|
|
198
|
+
}));
|
|
199
|
+
case "append-result":
|
|
200
|
+
return updateSession(state, action.sessionId, (session) => ({
|
|
201
|
+
...session,
|
|
202
|
+
messages: [
|
|
203
|
+
...session.messages,
|
|
204
|
+
{
|
|
205
|
+
id: createId(),
|
|
206
|
+
role: "assistant",
|
|
207
|
+
parts: [{ type: "text", text: action.text }],
|
|
208
|
+
state: "success",
|
|
209
|
+
},
|
|
210
|
+
],
|
|
211
|
+
}));
|
|
212
|
+
case "append-terminal":
|
|
213
|
+
return updateSession(state, action.sessionId, (session) => ({
|
|
214
|
+
...session,
|
|
215
|
+
messages: [
|
|
216
|
+
...session.messages.map((message) => message.state === "running"
|
|
217
|
+
? { ...message, state: "error" }
|
|
218
|
+
: message),
|
|
219
|
+
{
|
|
220
|
+
id: createId(),
|
|
221
|
+
role: "assistant",
|
|
222
|
+
parts: [{ type: "text", text: action.text }],
|
|
223
|
+
state: "error",
|
|
224
|
+
},
|
|
225
|
+
],
|
|
226
|
+
}));
|
|
227
|
+
case "interrupt":
|
|
228
|
+
return updateSession(state, action.sessionId, (session) => {
|
|
229
|
+
const { interrupt: _interrupt, ...rest } = session;
|
|
230
|
+
return action.interrupt === undefined
|
|
231
|
+
? rest
|
|
232
|
+
: { ...rest, interrupt: action.interrupt };
|
|
233
|
+
});
|
|
234
|
+
case "settle-interrupt":
|
|
235
|
+
return updateSession(state, action.sessionId, (session) => {
|
|
236
|
+
const { interrupt: _interrupt, ...rest } = session;
|
|
237
|
+
return {
|
|
238
|
+
...rest,
|
|
239
|
+
messages: settleInterruptMessages(session.messages, action.interrupt, action.code, action.message, action.reason),
|
|
240
|
+
};
|
|
241
|
+
});
|
|
242
|
+
case "invalidate-tool-interrupts":
|
|
243
|
+
return {
|
|
244
|
+
...state,
|
|
245
|
+
sessions: state.sessions.map((session) => {
|
|
246
|
+
if (session.interrupt?.toolName !== action.toolName)
|
|
247
|
+
return session;
|
|
248
|
+
const { interrupt: _interrupt, ...rest } = session;
|
|
249
|
+
return {
|
|
250
|
+
...rest,
|
|
251
|
+
messages: [
|
|
252
|
+
...settleInterruptMessages(session.messages, session.interrupt, "TOOL_CONFIRMATION_INVALIDATED", "The Tool Binding changed.", "binding_changed"),
|
|
253
|
+
{
|
|
254
|
+
id: createId(),
|
|
255
|
+
role: "assistant",
|
|
256
|
+
parts: [{
|
|
257
|
+
type: "text",
|
|
258
|
+
text: "页面能力已发生变化,本次任务已中断。你可以发送新消息继续。",
|
|
259
|
+
}],
|
|
260
|
+
state: "error",
|
|
261
|
+
},
|
|
262
|
+
],
|
|
263
|
+
};
|
|
264
|
+
}),
|
|
265
|
+
};
|
|
266
|
+
case "completed":
|
|
267
|
+
return {
|
|
268
|
+
...state,
|
|
269
|
+
completed: { id: createId(), sessionId: action.sessionId, result: action.result },
|
|
270
|
+
};
|
|
271
|
+
case "status":
|
|
272
|
+
return {
|
|
273
|
+
...state,
|
|
274
|
+
status: action.status,
|
|
275
|
+
...(action.error === undefined ? { error: undefined } : { error: action.error }),
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
function errorFromRun(error) {
|
|
280
|
+
const errorRecord = typeof error === "object" && error !== null
|
|
281
|
+
? error
|
|
282
|
+
: undefined;
|
|
283
|
+
const name = typeof errorRecord?.name === "string"
|
|
284
|
+
? errorRecord.name
|
|
285
|
+
: "CHAT_RUN_ERROR";
|
|
286
|
+
const message = typeof errorRecord?.message === "string"
|
|
287
|
+
? errorRecord.message
|
|
288
|
+
: String(error);
|
|
289
|
+
const candidateCode = errorRecord?.code;
|
|
290
|
+
const code = typeof candidateCode === "string" && candidateCode
|
|
291
|
+
? candidateCode
|
|
292
|
+
: name;
|
|
293
|
+
return new ChatError(code, message);
|
|
294
|
+
}
|
|
295
|
+
const ChatContext = createContext(null);
|
|
296
|
+
export function NexfaceProvider({ agent: agentConfig, toolRuntime, children, webMcp = true }) {
|
|
297
|
+
const operationSurface = useRef(null);
|
|
298
|
+
const pageConfirmationToolsRef = useRef(new Set());
|
|
299
|
+
const runtimeRef = useRef(toolRuntime);
|
|
300
|
+
if (runtimeRef.current !== toolRuntime) {
|
|
301
|
+
throw new ChatError("CHAT_RUNTIME_CHANGED", "NexfaceProvider requires a stable ToolRuntime. Remount the Provider to reset it.");
|
|
302
|
+
}
|
|
303
|
+
if (!agentConfig || typeof agentConfig !== "object"
|
|
304
|
+
|| "toolRuntime" in agentConfig || "toolBridge" in agentConfig || "run" in agentConfig) {
|
|
305
|
+
throw new ChatError("INVALID_INPUT", "agent must be a NexfaceAgentConfig, without a Runtime, Bridge, or Agent instance.");
|
|
306
|
+
}
|
|
307
|
+
const createSessionAgent = useCallback(() => {
|
|
308
|
+
const agent = createAgent({
|
|
309
|
+
...agentConfig,
|
|
310
|
+
model: resolveModelConfig(agentConfig.model),
|
|
311
|
+
toolRuntime,
|
|
312
|
+
});
|
|
313
|
+
getAgentChatController(agent).setPageConfirmationResolver((toolName) => pageConfirmationToolsRef.current.has(toolName));
|
|
314
|
+
return agent;
|
|
315
|
+
}, [agentConfig, toolRuntime]);
|
|
316
|
+
const initialAgentRef = useRef(undefined);
|
|
317
|
+
if (!initialAgentRef.current) {
|
|
318
|
+
initialAgentRef.current = createSessionAgent();
|
|
319
|
+
}
|
|
320
|
+
const initialAgent = initialAgentRef.current;
|
|
321
|
+
const sessionAgentsByIdRef = useRef(undefined);
|
|
322
|
+
if (!sessionAgentsByIdRef.current) {
|
|
323
|
+
sessionAgentsByIdRef.current = new Map([[initialAgent.id, initialAgent]]);
|
|
324
|
+
}
|
|
325
|
+
const consumedCompletionIdRef = useRef(undefined);
|
|
326
|
+
const activeSessionIdRef = useRef(initialAgent.id);
|
|
327
|
+
const [state, dispatch] = useReducer(reducer, {
|
|
328
|
+
sessions: [{ id: initialAgent.id, agent: initialAgent, messages: [] }],
|
|
329
|
+
activeSessionId: initialAgent.id,
|
|
330
|
+
status: "idle",
|
|
331
|
+
error: undefined,
|
|
332
|
+
});
|
|
333
|
+
const stateRef = useRef(state);
|
|
334
|
+
stateRef.current = state;
|
|
335
|
+
const pendingInterruptsRef = useRef(new Map());
|
|
336
|
+
const activeRunRef = useRef(undefined);
|
|
337
|
+
const modelSwitchRef = useRef(undefined);
|
|
338
|
+
const mountedRef = useRef(false);
|
|
339
|
+
useEffect(() => {
|
|
340
|
+
mountedRef.current = true;
|
|
341
|
+
return () => {
|
|
342
|
+
mountedRef.current = false;
|
|
343
|
+
queueMicrotask(() => {
|
|
344
|
+
if (mountedRef.current)
|
|
345
|
+
return;
|
|
346
|
+
activeRunRef.current?.run.cancel();
|
|
347
|
+
});
|
|
348
|
+
};
|
|
349
|
+
}, []);
|
|
350
|
+
useEffect(() => toolRuntime.on("toolchange", (event) => {
|
|
351
|
+
if (event.change !== "unregistered")
|
|
352
|
+
return;
|
|
353
|
+
let changed = false;
|
|
354
|
+
for (const [sessionId, interrupt] of pendingInterruptsRef.current) {
|
|
355
|
+
if (interrupt.toolName !== event.toolName)
|
|
356
|
+
continue;
|
|
357
|
+
pendingInterruptsRef.current.delete(sessionId);
|
|
358
|
+
changed = true;
|
|
359
|
+
}
|
|
360
|
+
if (!changed)
|
|
361
|
+
return;
|
|
362
|
+
dispatch({
|
|
363
|
+
type: "invalidate-tool-interrupts",
|
|
364
|
+
toolName: event.toolName,
|
|
365
|
+
});
|
|
366
|
+
}), [toolRuntime]);
|
|
367
|
+
const consumeRun = useCallback(async (sessionId, run) => {
|
|
368
|
+
activeRunRef.current = { sessionId, run };
|
|
369
|
+
dispatch({ type: "status", status: "running" });
|
|
370
|
+
const consumeEvents = async () => {
|
|
371
|
+
for await (const event of run) {
|
|
372
|
+
dispatch({ type: "apply-event", sessionId, event });
|
|
373
|
+
}
|
|
374
|
+
};
|
|
375
|
+
const [resultOutcome, eventOutcome] = await Promise.allSettled([
|
|
376
|
+
run.result,
|
|
377
|
+
consumeEvents(),
|
|
378
|
+
]);
|
|
379
|
+
if (activeRunRef.current?.run === run)
|
|
380
|
+
activeRunRef.current = undefined;
|
|
381
|
+
const failure = resultOutcome.status === "rejected"
|
|
382
|
+
? resultOutcome.reason
|
|
383
|
+
: eventOutcome.status === "rejected"
|
|
384
|
+
? eventOutcome.reason
|
|
385
|
+
: undefined;
|
|
386
|
+
const runError = failure === undefined ? undefined : errorFromRun(failure);
|
|
387
|
+
const terminalError = runError;
|
|
388
|
+
if (resultOutcome.status === "fulfilled"
|
|
389
|
+
&& resultOutcome.value.status === "interrupted") {
|
|
390
|
+
pendingInterruptsRef.current.set(sessionId, resultOutcome.value.interrupt);
|
|
391
|
+
dispatch({
|
|
392
|
+
type: "interrupt",
|
|
393
|
+
sessionId,
|
|
394
|
+
interrupt: resultOutcome.value.interrupt,
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
if (resultOutcome.status === "fulfilled"
|
|
398
|
+
&& resultOutcome.value.status === "completed") {
|
|
399
|
+
pendingInterruptsRef.current.delete(sessionId);
|
|
400
|
+
dispatch({ type: "interrupt", sessionId, interrupt: undefined });
|
|
401
|
+
dispatch({ type: "completed", sessionId, result: resultOutcome.value });
|
|
402
|
+
}
|
|
403
|
+
if (terminalError) {
|
|
404
|
+
dispatch({
|
|
405
|
+
type: "append-terminal",
|
|
406
|
+
sessionId,
|
|
407
|
+
text: runError?.code === "AbortError"
|
|
408
|
+
? "任务已取消。"
|
|
409
|
+
: terminalError.message,
|
|
410
|
+
});
|
|
411
|
+
}
|
|
412
|
+
dispatch({
|
|
413
|
+
type: "status",
|
|
414
|
+
status: "idle",
|
|
415
|
+
...(terminalError ? { error: terminalError } : {}),
|
|
416
|
+
});
|
|
417
|
+
if (resultOutcome.status === "rejected")
|
|
418
|
+
throw resultOutcome.reason;
|
|
419
|
+
if (eventOutcome.status === "rejected")
|
|
420
|
+
throw eventOutcome.reason;
|
|
421
|
+
return resultOutcome.value;
|
|
422
|
+
}, []);
|
|
423
|
+
const settlePendingInterrupt = useCallback((sessionId, settlement) => {
|
|
424
|
+
const session = stateRef.current.sessions.find(({ id }) => id === sessionId);
|
|
425
|
+
const interrupt = pendingInterruptsRef.current.get(sessionId);
|
|
426
|
+
if (!session || !interrupt)
|
|
427
|
+
return;
|
|
428
|
+
if (!getAgentChatController(session.agent).settle(interrupt.id, settlement))
|
|
429
|
+
return;
|
|
430
|
+
pendingInterruptsRef.current.delete(sessionId);
|
|
431
|
+
const cancelled = settlement.type === "cancel";
|
|
432
|
+
dispatch({
|
|
433
|
+
type: "settle-interrupt",
|
|
434
|
+
sessionId,
|
|
435
|
+
interrupt,
|
|
436
|
+
code: cancelled ? "TOOL_CANCELLED" : "TOOL_CONFIRMATION_INVALIDATED",
|
|
437
|
+
message: cancelled
|
|
438
|
+
? "The pending Tool confirmation was cancelled."
|
|
439
|
+
: settlement.message,
|
|
440
|
+
reason: cancelled ? "interrupt_cancelled" : settlement.reason,
|
|
441
|
+
});
|
|
442
|
+
}, []);
|
|
443
|
+
const cancelPendingInterrupt = useCallback((sessionId) => {
|
|
444
|
+
settlePendingInterrupt(sessionId, { type: "cancel" });
|
|
445
|
+
}, [settlePendingInterrupt]);
|
|
446
|
+
const invalidatePendingInterrupt = useCallback((sessionId, reason, message = "The active confirmation context changed.") => {
|
|
447
|
+
settlePendingInterrupt(sessionId, { type: "invalidate", message, reason });
|
|
448
|
+
}, [settlePendingInterrupt]);
|
|
449
|
+
const sendMessage = useCallback(async (text, attachments = [], revisionOf) => {
|
|
450
|
+
if (activeRunRef.current || modelSwitchRef.current) {
|
|
451
|
+
throw new ChatError("CHAT_RUN_ACTIVE", "A chat run is already active.");
|
|
452
|
+
}
|
|
453
|
+
const content = text.trim();
|
|
454
|
+
if (!content && !attachments.length)
|
|
455
|
+
throw new ChatError("INVALID_INPUT", "Chat message is required.");
|
|
456
|
+
const sessionId = activeSessionIdRef.current;
|
|
457
|
+
const agent = sessionAgentsByIdRef.current.get(sessionId);
|
|
458
|
+
if (!agent)
|
|
459
|
+
throw new ChatError("UNKNOWN_SESSION", "The active chat session does not exist.");
|
|
460
|
+
const pending = pendingInterruptsRef.current.get(sessionId);
|
|
461
|
+
if (pending) {
|
|
462
|
+
pendingInterruptsRef.current.delete(sessionId);
|
|
463
|
+
dispatch({
|
|
464
|
+
type: "settle-interrupt",
|
|
465
|
+
sessionId,
|
|
466
|
+
interrupt: pending,
|
|
467
|
+
code: "TOOL_CONFIRMATION_INVALIDATED",
|
|
468
|
+
message: "A new user message started.",
|
|
469
|
+
reason: "new_message",
|
|
470
|
+
});
|
|
471
|
+
}
|
|
472
|
+
dispatch({
|
|
473
|
+
type: "append-message",
|
|
474
|
+
sessionId,
|
|
475
|
+
message: {
|
|
476
|
+
id: createId(),
|
|
477
|
+
role: "user",
|
|
478
|
+
parts: [{ type: "text", text: content }],
|
|
479
|
+
attachments,
|
|
480
|
+
...(revisionOf ? { revisionOf } : {}),
|
|
481
|
+
},
|
|
482
|
+
});
|
|
483
|
+
const parts = [
|
|
484
|
+
...(content ? [{ type: "text", text: revisionOf ? "修订上一条用户请求(保留已执行操作):" + content : content }] : []),
|
|
485
|
+
...attachments.map((attachment) => attachment.content),
|
|
486
|
+
];
|
|
487
|
+
return consumeRun(sessionId, agent.run({ message: { content: attachments.length ? parts : parts[0]?.type === "text" ? parts[0].text : content } }));
|
|
488
|
+
}, [consumeRun]);
|
|
489
|
+
const cancel = useCallback(() => {
|
|
490
|
+
const active = activeRunRef.current;
|
|
491
|
+
if (!active) {
|
|
492
|
+
cancelPendingInterrupt(activeSessionIdRef.current);
|
|
493
|
+
return;
|
|
494
|
+
}
|
|
495
|
+
dispatch({ type: "status", status: "cancelling" });
|
|
496
|
+
active.run.cancel();
|
|
497
|
+
}, [cancelPendingInterrupt]);
|
|
498
|
+
const createSession = useCallback(() => {
|
|
499
|
+
if (activeRunRef.current || modelSwitchRef.current) {
|
|
500
|
+
throw new ChatError("CHAT_SESSION_CREATE_BLOCKED", "A session cannot be created while a chat run is active.");
|
|
501
|
+
}
|
|
502
|
+
const sessionAgent = createSessionAgent();
|
|
503
|
+
invalidatePendingInterrupt(activeSessionIdRef.current, "session_changed");
|
|
504
|
+
sessionAgentsByIdRef.current.set(sessionAgent.id, sessionAgent);
|
|
505
|
+
activeSessionIdRef.current = sessionAgent.id;
|
|
506
|
+
dispatch({
|
|
507
|
+
type: "create-session",
|
|
508
|
+
session: { id: sessionAgent.id, agent: sessionAgent, messages: [] },
|
|
509
|
+
});
|
|
510
|
+
return sessionAgent.id;
|
|
511
|
+
}, [createSessionAgent, invalidatePendingInterrupt]);
|
|
512
|
+
const switchSession = useCallback((sessionId) => {
|
|
513
|
+
if (activeRunRef.current || modelSwitchRef.current) {
|
|
514
|
+
throw new ChatError("CHAT_SESSION_SWITCH_BLOCKED", "A session cannot be switched while a chat run is active.");
|
|
515
|
+
}
|
|
516
|
+
if (!sessionAgentsByIdRef.current.has(sessionId)) {
|
|
517
|
+
throw new ChatError("UNKNOWN_SESSION", `Unknown chat session: ${sessionId}.`);
|
|
518
|
+
}
|
|
519
|
+
if (sessionId === activeSessionIdRef.current)
|
|
520
|
+
return;
|
|
521
|
+
invalidatePendingInterrupt(activeSessionIdRef.current, "session_changed");
|
|
522
|
+
activeSessionIdRef.current = sessionId;
|
|
523
|
+
dispatch({ type: "switch-session", sessionId });
|
|
524
|
+
}, [invalidatePendingInterrupt]);
|
|
525
|
+
const assertIdle = () => {
|
|
526
|
+
if (activeRunRef.current || modelSwitchRef.current)
|
|
527
|
+
throw new ChatError("CHAT_RUN_ACTIVE", "请等待当前运行结束。");
|
|
528
|
+
};
|
|
529
|
+
const renameSession = (id, title) => {
|
|
530
|
+
if (!sessionAgentsByIdRef.current.has(id))
|
|
531
|
+
throw new ChatError("UNKNOWN_SESSION", "会话不存在。");
|
|
532
|
+
if (!title.trim())
|
|
533
|
+
throw new ChatError("INVALID_INPUT", "会话名称不能为空。");
|
|
534
|
+
dispatch({ type: "rename-session", sessionId: id, title: title.trim().slice(0, 80) });
|
|
535
|
+
};
|
|
536
|
+
const deleteSession = (id) => {
|
|
537
|
+
assertIdle();
|
|
538
|
+
const agents = sessionAgentsByIdRef.current;
|
|
539
|
+
const agent = agents.get(id);
|
|
540
|
+
if (!agent)
|
|
541
|
+
throw new ChatError("UNKNOWN_SESSION", "会话不存在。");
|
|
542
|
+
invalidatePendingInterrupt(id, "session_deleted");
|
|
543
|
+
if (agents.size === 1)
|
|
544
|
+
createSession();
|
|
545
|
+
agents.delete(id);
|
|
546
|
+
if (activeSessionIdRef.current === id)
|
|
547
|
+
activeSessionIdRef.current = agents.keys().next().value;
|
|
548
|
+
dispatch({ type: "remove-session", sessionId: id, activeSessionId: activeSessionIdRef.current });
|
|
549
|
+
};
|
|
550
|
+
const clearSession = (id = activeSessionIdRef.current) => {
|
|
551
|
+
assertIdle();
|
|
552
|
+
const agents = sessionAgentsByIdRef.current;
|
|
553
|
+
const previous = agents.get(id);
|
|
554
|
+
if (!previous)
|
|
555
|
+
throw new ChatError("UNKNOWN_SESSION", "会话不存在。");
|
|
556
|
+
const agent = createSessionAgent();
|
|
557
|
+
invalidatePendingInterrupt(id, "session_cleared");
|
|
558
|
+
agents.delete(id);
|
|
559
|
+
agents.set(agent.id, agent);
|
|
560
|
+
if (activeSessionIdRef.current === id)
|
|
561
|
+
activeSessionIdRef.current = agent.id;
|
|
562
|
+
dispatch({ type: "replace-session", sessionId: id, session: { id: agent.id, agent, messages: [] } });
|
|
563
|
+
};
|
|
564
|
+
const clearAllSessions = () => {
|
|
565
|
+
assertIdle();
|
|
566
|
+
const ids = [...sessionAgentsByIdRef.current.keys()];
|
|
567
|
+
createSession();
|
|
568
|
+
ids.forEach(deleteSession);
|
|
569
|
+
};
|
|
570
|
+
const switchModel = useCallback(async (model) => {
|
|
571
|
+
if (activeRunRef.current || modelSwitchRef.current) {
|
|
572
|
+
throw new ChatError("CHAT_MODEL_SWITCH_BLOCKED", "The model cannot be switched while the chat is busy.");
|
|
573
|
+
}
|
|
574
|
+
const sessionId = activeSessionIdRef.current;
|
|
575
|
+
const sessionAgent = sessionAgentsByIdRef.current.get(sessionId);
|
|
576
|
+
if (!sessionAgent) {
|
|
577
|
+
throw new ChatError("UNKNOWN_SESSION", "The active chat session does not exist.");
|
|
578
|
+
}
|
|
579
|
+
dispatch({ type: "status", status: "switching-model" });
|
|
580
|
+
const switching = sessionAgent.switchModel(model);
|
|
581
|
+
modelSwitchRef.current = switching;
|
|
582
|
+
try {
|
|
583
|
+
await switching;
|
|
584
|
+
dispatch({ type: "status", status: "idle" });
|
|
585
|
+
}
|
|
586
|
+
catch (error) {
|
|
587
|
+
const chatError = errorFromRun(error);
|
|
588
|
+
dispatch({ type: "status", status: "idle", error: chatError });
|
|
589
|
+
throw chatError;
|
|
590
|
+
}
|
|
591
|
+
finally {
|
|
592
|
+
if (modelSwitchRef.current === switching)
|
|
593
|
+
modelSwitchRef.current = undefined;
|
|
594
|
+
}
|
|
595
|
+
}, []);
|
|
596
|
+
const activeSession = state.sessions.find(({ id }) => id === state.activeSessionId);
|
|
597
|
+
const resumeInterrupt = useCallback((session, approved, source) => {
|
|
598
|
+
const pending = session.interrupt;
|
|
599
|
+
if (!pending)
|
|
600
|
+
return undefined;
|
|
601
|
+
if (pending.mode !== source || (source === "page" && !approved)) {
|
|
602
|
+
return undefined;
|
|
603
|
+
}
|
|
604
|
+
if (pendingInterruptsRef.current.get(session.id)?.id !== pending.id) {
|
|
605
|
+
return undefined;
|
|
606
|
+
}
|
|
607
|
+
pendingInterruptsRef.current.delete(session.id);
|
|
608
|
+
dispatch({ type: "interrupt", sessionId: session.id, interrupt: undefined });
|
|
609
|
+
try {
|
|
610
|
+
const response = {
|
|
611
|
+
interruptId: pending.id,
|
|
612
|
+
status: "resolved",
|
|
613
|
+
payload: { approved },
|
|
614
|
+
};
|
|
615
|
+
if (source === "page") {
|
|
616
|
+
getAgentChatController(session.agent).authorizePageResponse(response);
|
|
617
|
+
}
|
|
618
|
+
const run = session.agent.run({
|
|
619
|
+
resume: [response],
|
|
620
|
+
});
|
|
621
|
+
const toolSettled = (async () => {
|
|
622
|
+
for await (const event of run) {
|
|
623
|
+
if (event.type === EventType.TOOL_CALL_RESULT
|
|
624
|
+
&& event.toolCallId === pending.toolCallId)
|
|
625
|
+
return;
|
|
626
|
+
}
|
|
627
|
+
})();
|
|
628
|
+
return {
|
|
629
|
+
completion: consumeRun(session.id, run),
|
|
630
|
+
toolSettled,
|
|
631
|
+
};
|
|
632
|
+
}
|
|
633
|
+
catch (error) {
|
|
634
|
+
const chatError = errorFromRun(error);
|
|
635
|
+
dispatch({ type: "append-terminal", sessionId: session.id, text: chatError.message });
|
|
636
|
+
dispatch({ type: "status", status: "idle", error: chatError });
|
|
637
|
+
return undefined;
|
|
638
|
+
}
|
|
639
|
+
}, [consumeRun]);
|
|
640
|
+
const confirmInterrupt = useCallback(() => {
|
|
641
|
+
void resumeInterrupt(activeSession, true, "chat")?.completion.catch(() => undefined);
|
|
642
|
+
}, [activeSession, resumeInterrupt]);
|
|
643
|
+
const rejectInterrupt = useCallback(() => {
|
|
644
|
+
if (activeSession.interrupt?.mode !== "chat")
|
|
645
|
+
return;
|
|
646
|
+
void resumeInterrupt(activeSession, false, "chat")?.completion.catch(() => undefined);
|
|
647
|
+
}, [activeSession, resumeInterrupt]);
|
|
648
|
+
const consumeCompletion = useCallback((id) => {
|
|
649
|
+
if (consumedCompletionIdRef.current === id)
|
|
650
|
+
return false;
|
|
651
|
+
consumedCompletionIdRef.current = id;
|
|
652
|
+
return true;
|
|
653
|
+
}, []);
|
|
654
|
+
const value = useMemo(() => ({
|
|
655
|
+
sessions: state.sessions.map((session, index) => ({
|
|
656
|
+
id: session.id,
|
|
657
|
+
title: sessionTitle(session, index),
|
|
658
|
+
messageCount: session.messages.length,
|
|
659
|
+
})),
|
|
660
|
+
activeSessionId: state.activeSessionId,
|
|
661
|
+
messages: activeSession.messages,
|
|
662
|
+
status: state.status,
|
|
663
|
+
model: activeSession.agent.model,
|
|
664
|
+
...(activeSession.interrupt === undefined
|
|
665
|
+
? {}
|
|
666
|
+
: { interrupt: activeSession.interrupt }),
|
|
667
|
+
...(state.completed?.sessionId === activeSession.id
|
|
668
|
+
? { completed: { id: state.completed.id, result: state.completed.result } }
|
|
669
|
+
: {}),
|
|
670
|
+
...(state.error === undefined ? {} : { error: state.error }),
|
|
671
|
+
consumeCompletion,
|
|
672
|
+
sendMessage,
|
|
673
|
+
cancel,
|
|
674
|
+
confirmInterrupt,
|
|
675
|
+
rejectInterrupt,
|
|
676
|
+
createSession,
|
|
677
|
+
switchSession,
|
|
678
|
+
switchModel,
|
|
679
|
+
renameSession, deleteSession, clearSession, clearAllSessions,
|
|
680
|
+
}), [activeSession, cancel, confirmInterrupt, consumeCompletion, createSession, rejectInterrupt, sendMessage, state, switchModel, switchSession]);
|
|
681
|
+
return (_jsx(ChatContext.Provider, { value: value, children: _jsx(OperationHostContext.Provider, { value: {
|
|
682
|
+
toolRuntime, operationSurface,
|
|
683
|
+
sessionId: activeSession.id,
|
|
684
|
+
turnId: `${activeSession.id}:${[...activeSession.messages].reverse().find((message) => message.role === "user")?.id ?? ""}`,
|
|
685
|
+
taskLabel: [...activeSession.messages].reverse().find((message) => message.role === "user")?.parts
|
|
686
|
+
.filter((part) => part.type === "text").map((part) => part.text).join(" ") ?? "",
|
|
687
|
+
running: state.status === "running" || state.status === "cancelling",
|
|
688
|
+
waiting: Boolean(activeSession.interrupt),
|
|
689
|
+
failed: Boolean(state.error && state.error.code !== "AbortError"),
|
|
690
|
+
cancel,
|
|
691
|
+
}, children: _jsx(ToolsProvider, { toolRuntime: toolRuntime, webMcp: webMcp, children: _jsx(PageConfirmationProvider, { interrupt: activeSession.interrupt, onConfirm: () => resumeInterrupt(activeSession, true, "page")?.toolSettled, onBindingRemoved: () => invalidatePendingInterrupt(activeSession.id, "page_confirmation_hook_removed", "Page confirmation entry was removed."), onBindingRegistration: (toolName, registered) => {
|
|
692
|
+
if (registered)
|
|
693
|
+
pageConfirmationToolsRef.current.add(toolName);
|
|
694
|
+
else
|
|
695
|
+
pageConfirmationToolsRef.current.delete(toolName);
|
|
696
|
+
}, children: children }) }) }) }));
|
|
697
|
+
}
|
|
698
|
+
export function useChat() {
|
|
699
|
+
const chat = useContext(ChatContext);
|
|
700
|
+
if (!chat)
|
|
701
|
+
throw new Error("useChat must be used inside NexfaceProvider.");
|
|
702
|
+
return chat;
|
|
703
|
+
}
|
|
704
|
+
//# sourceMappingURL=react.js.map
|