@notic/agent-engine 1.1.1 → 2.0.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/CHANGELOG.md +46 -0
- package/README.md +434 -292
- package/dist/adapter/AnthropicAdapter.d.ts +3 -1
- package/dist/adapter/AnthropicAdapter.d.ts.map +1 -1
- package/dist/adapter/AnthropicAdapter.js +40 -2
- package/dist/adapter/AnthropicAdapter.js.map +1 -1
- package/dist/adapter/GeminiAdapter.d.ts +3 -1
- package/dist/adapter/GeminiAdapter.d.ts.map +1 -1
- package/dist/adapter/GeminiAdapter.js +76 -3
- package/dist/adapter/GeminiAdapter.js.map +1 -1
- package/dist/adapter/MessageAdapter.d.ts +17 -0
- package/dist/adapter/MessageAdapter.d.ts.map +1 -1
- package/dist/adapter/MessageAdapter.js.map +1 -1
- package/dist/adapter/OpenAIAdapter.d.ts +3 -1
- package/dist/adapter/OpenAIAdapter.d.ts.map +1 -1
- package/dist/adapter/OpenAIAdapter.js +19 -2
- package/dist/adapter/OpenAIAdapter.js.map +1 -1
- package/dist/adapter/OpenAIResponsesAdapter.d.ts +23 -0
- package/dist/adapter/OpenAIResponsesAdapter.d.ts.map +1 -0
- package/dist/adapter/OpenAIResponsesAdapter.js +231 -0
- package/dist/adapter/OpenAIResponsesAdapter.js.map +1 -0
- package/dist/adapter/index.d.ts +2 -1
- package/dist/adapter/index.d.ts.map +1 -1
- package/dist/adapter/index.js +3 -1
- package/dist/adapter/index.js.map +1 -1
- package/dist/agent/Agent.d.ts +57 -16
- package/dist/agent/Agent.d.ts.map +1 -1
- package/dist/agent/Agent.js +292 -54
- package/dist/agent/Agent.js.map +1 -1
- package/dist/agent/index.d.ts +1 -1
- package/dist/agent/index.d.ts.map +1 -1
- package/dist/agent/index.js +4 -1
- package/dist/agent/index.js.map +1 -1
- package/dist/client/ModelClient.d.ts +74 -0
- package/dist/client/ModelClient.d.ts.map +1 -0
- package/dist/client/ModelClient.js +85 -0
- package/dist/client/ModelClient.js.map +1 -0
- package/dist/client/index.d.ts +2 -0
- package/dist/client/index.d.ts.map +1 -0
- package/dist/client/index.js +11 -0
- package/dist/client/index.js.map +1 -0
- package/dist/index.d.ts +11 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +31 -5
- package/dist/index.js.map +1 -1
- package/dist/media/BrowserMediaResolver.d.ts +14 -0
- package/dist/media/BrowserMediaResolver.d.ts.map +1 -0
- package/dist/media/BrowserMediaResolver.js +52 -0
- package/dist/media/BrowserMediaResolver.js.map +1 -0
- package/dist/media/index.d.ts +1 -0
- package/dist/media/index.d.ts.map +1 -1
- package/dist/media/index.js +3 -1
- package/dist/media/index.js.map +1 -1
- package/dist/message/Message.d.ts +7 -0
- package/dist/message/Message.d.ts.map +1 -1
- package/dist/message/Message.js +52 -0
- package/dist/message/Message.js.map +1 -1
- package/dist/message/MessagePart.d.ts +2 -0
- package/dist/message/MessagePart.d.ts.map +1 -1
- package/dist/node.d.ts +3 -0
- package/dist/node.d.ts.map +1 -0
- package/dist/node.js +6 -0
- package/dist/node.js.map +1 -0
- package/dist/provider/Provider.d.ts +48 -0
- package/dist/provider/Provider.d.ts.map +1 -0
- package/dist/provider/Provider.js +73 -0
- package/dist/provider/Provider.js.map +1 -0
- package/dist/provider/index.d.ts +2 -0
- package/dist/provider/index.d.ts.map +1 -0
- package/dist/provider/index.js +10 -0
- package/dist/provider/index.js.map +1 -0
- package/dist/session/Session.d.ts +0 -3
- package/dist/session/Session.d.ts.map +1 -1
- package/dist/session/Session.js +0 -13
- package/dist/session/Session.js.map +1 -1
- package/dist/stream/AnthropicStreamParser.d.ts +26 -0
- package/dist/stream/AnthropicStreamParser.d.ts.map +1 -0
- package/dist/stream/AnthropicStreamParser.js +176 -0
- package/dist/stream/AnthropicStreamParser.js.map +1 -0
- package/dist/stream/GeminiStreamParser.d.ts +21 -0
- package/dist/stream/GeminiStreamParser.d.ts.map +1 -0
- package/dist/stream/GeminiStreamParser.js +144 -0
- package/dist/stream/GeminiStreamParser.js.map +1 -0
- package/dist/stream/MessageStreamParser.d.ts +13 -0
- package/dist/stream/MessageStreamParser.d.ts.map +1 -0
- package/dist/stream/MessageStreamParser.js +3 -0
- package/dist/stream/MessageStreamParser.js.map +1 -0
- package/dist/stream/OpenAIResponsesStreamParser.d.ts +30 -0
- package/dist/stream/OpenAIResponsesStreamParser.d.ts.map +1 -0
- package/dist/stream/OpenAIResponsesStreamParser.js +273 -0
- package/dist/stream/OpenAIResponsesStreamParser.js.map +1 -0
- package/dist/stream/StreamEvent.d.ts +13 -1
- package/dist/stream/StreamEvent.d.ts.map +1 -1
- package/dist/stream/StreamEvent.js +2 -0
- package/dist/stream/StreamEvent.js.map +1 -1
- package/dist/stream/StreamParser.d.ts +2 -1
- package/dist/stream/StreamParser.d.ts.map +1 -1
- package/dist/stream/StreamParser.js.map +1 -1
- package/dist/stream/index.d.ts +5 -1
- package/dist/stream/index.d.ts.map +1 -1
- package/dist/stream/index.js +7 -1
- package/dist/stream/index.js.map +1 -1
- package/dist/tool/ToolKit.d.ts +4 -0
- package/dist/tool/ToolKit.d.ts.map +1 -1
- package/dist/tool/ToolKit.js +50 -14
- package/dist/tool/ToolKit.js.map +1 -1
- package/dist/tool/index.d.ts +1 -1
- package/dist/tool/index.d.ts.map +1 -1
- package/dist/tool/index.js +2 -1
- package/dist/tool/index.js.map +1 -1
- package/docs/API.md +1676 -1455
- package/package.json +33 -9
package/dist/agent/Agent.js
CHANGED
|
@@ -1,17 +1,21 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.Agent = exports.AgentTimeoutError = exports.AgentAbortError = void 0;
|
|
3
|
+
exports.Agent = exports.AgentToolApprovalTimeoutError = exports.AgentToolApprovalError = exports.AgentAlreadyRunningError = exports.AgentTimeoutError = exports.AgentAbortError = void 0;
|
|
4
4
|
const Message_1 = require("../message/Message");
|
|
5
|
+
const Role_1 = require("../message/Role");
|
|
5
6
|
const OpenAIAdapter_1 = require("../adapter/OpenAIAdapter");
|
|
6
7
|
const ToolKit_1 = require("../tool/ToolKit");
|
|
7
8
|
const StreamParser_1 = require("../stream/StreamParser");
|
|
8
9
|
const StreamEvent_1 = require("../stream/StreamEvent");
|
|
9
10
|
const utils_1 = require("../utils");
|
|
11
|
+
const client_1 = require("../client");
|
|
10
12
|
/** Agent 主动中断错误 */
|
|
11
13
|
class AgentAbortError extends Error {
|
|
12
|
-
|
|
14
|
+
cause;
|
|
15
|
+
constructor(message = "Agent run aborted", cause) {
|
|
13
16
|
super(message);
|
|
14
17
|
this.name = "AbortError";
|
|
18
|
+
this.cause = cause;
|
|
15
19
|
}
|
|
16
20
|
}
|
|
17
21
|
exports.AgentAbortError = AgentAbortError;
|
|
@@ -23,6 +27,39 @@ class AgentTimeoutError extends Error {
|
|
|
23
27
|
}
|
|
24
28
|
}
|
|
25
29
|
exports.AgentTimeoutError = AgentTimeoutError;
|
|
30
|
+
/** 同一个 Agent 实例不允许同时运行多个任务 */
|
|
31
|
+
class AgentAlreadyRunningError extends Error {
|
|
32
|
+
constructor() {
|
|
33
|
+
super("Agent 已有运行中的任务,请等待完成或先中断当前任务");
|
|
34
|
+
this.name = "AgentAlreadyRunningError";
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
exports.AgentAlreadyRunningError = AgentAlreadyRunningError;
|
|
38
|
+
/** 工具审批函数执行失败 */
|
|
39
|
+
class AgentToolApprovalError extends Error {
|
|
40
|
+
request;
|
|
41
|
+
cause;
|
|
42
|
+
constructor(request, cause) {
|
|
43
|
+
const message = cause instanceof Error ? cause.message : String(cause);
|
|
44
|
+
super(`工具审批失败 [${request.name}]: ${message}`);
|
|
45
|
+
this.name = "ToolApprovalError";
|
|
46
|
+
this.request = request;
|
|
47
|
+
this.cause = cause;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
exports.AgentToolApprovalError = AgentToolApprovalError;
|
|
51
|
+
/** 等待手动工具审批超时 */
|
|
52
|
+
class AgentToolApprovalTimeoutError extends Error {
|
|
53
|
+
request;
|
|
54
|
+
timeoutMs;
|
|
55
|
+
constructor(request, timeoutMs) {
|
|
56
|
+
super(`工具审批超时 [${request.name}]: ${timeoutMs}ms`);
|
|
57
|
+
this.name = "ToolApprovalTimeoutError";
|
|
58
|
+
this.request = request;
|
|
59
|
+
this.timeoutMs = timeoutMs;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
exports.AgentToolApprovalTimeoutError = AgentToolApprovalTimeoutError;
|
|
26
63
|
/** 默认 handler 错误处理器 */
|
|
27
64
|
const defaultHandlerErrorHandler = (error, event) => {
|
|
28
65
|
// eslint-disable-next-line no-console
|
|
@@ -46,6 +83,7 @@ class Agent {
|
|
|
46
83
|
_client;
|
|
47
84
|
_model;
|
|
48
85
|
_adapter;
|
|
86
|
+
_parserFactory;
|
|
49
87
|
_toolkit;
|
|
50
88
|
_session;
|
|
51
89
|
_promptBuilder;
|
|
@@ -63,9 +101,18 @@ class Agent {
|
|
|
63
101
|
_lastRunState;
|
|
64
102
|
_handlerErrorHandler = defaultHandlerErrorHandler;
|
|
65
103
|
constructor(options) {
|
|
66
|
-
|
|
104
|
+
const client = options.client
|
|
105
|
+
? (0, client_1.toModelClient)(options.client)
|
|
106
|
+
: options.provider?.client;
|
|
107
|
+
if (!client) {
|
|
108
|
+
throw new Error("Agent requires either client or provider");
|
|
109
|
+
}
|
|
110
|
+
this._client = client;
|
|
67
111
|
this._model = options.model;
|
|
68
|
-
this._adapter = options.adapter
|
|
112
|
+
this._adapter = options.adapter ?? options.provider?.adapter ?? new OpenAIAdapter_1.OpenAIAdapter();
|
|
113
|
+
this._parserFactory = options.parserFactory
|
|
114
|
+
?? options.provider?.parserFactory
|
|
115
|
+
?? (() => new StreamParser_1.StreamParser());
|
|
69
116
|
this._toolkit = options.toolkit;
|
|
70
117
|
this._session = options.session;
|
|
71
118
|
this._promptBuilder = options.promptBuilder;
|
|
@@ -104,7 +151,7 @@ class Agent {
|
|
|
104
151
|
once(event, handler) {
|
|
105
152
|
const wrapper = (e) => {
|
|
106
153
|
this.off(event, wrapper);
|
|
107
|
-
handler(e);
|
|
154
|
+
return handler(e);
|
|
108
155
|
};
|
|
109
156
|
return this.on(event, wrapper);
|
|
110
157
|
}
|
|
@@ -145,38 +192,43 @@ class Agent {
|
|
|
145
192
|
* 保留其所有 parts(多模态内容)、tags、metadata。
|
|
146
193
|
*/
|
|
147
194
|
async runWith(message, options) {
|
|
195
|
+
this.ensureIdle();
|
|
148
196
|
this._session.addMessage(message);
|
|
149
197
|
return this.executeLoop(options);
|
|
150
198
|
}
|
|
199
|
+
/**
|
|
200
|
+
* 基于当前 Session 直接生成 Assistant,不自动追加新的 User 消息。
|
|
201
|
+
* 适合调用方已经通过 Session、Inserter 或 PromptBuilder 准备好上下文的场景。
|
|
202
|
+
*/
|
|
203
|
+
async generate(options) {
|
|
204
|
+
this.ensureIdle();
|
|
205
|
+
return this.executeLoop(options);
|
|
206
|
+
}
|
|
151
207
|
/**
|
|
152
208
|
* 直接传入历史运行(不走Session)
|
|
153
209
|
*/
|
|
154
210
|
async runRaw(messages, options) {
|
|
211
|
+
this.ensureIdle();
|
|
155
212
|
const run = this.prepareRunOptions(options);
|
|
156
213
|
try {
|
|
157
214
|
this.throwIfAborted(run.signal);
|
|
158
215
|
const configParams = this._config ? this._config.build() : {};
|
|
159
216
|
const mergedOptions = { ...configParams, ...this._requestOptions, ...run.requestOptions };
|
|
160
|
-
const
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
messages: serialized,
|
|
165
|
-
stream: true,
|
|
166
|
-
...mergedOptions,
|
|
167
|
-
};
|
|
168
|
-
if (this._toolkit && this._toolkit.size > 0) {
|
|
169
|
-
requestParams.tools = this._toolkit.schemas;
|
|
217
|
+
const requestParams = await this.buildModelRequest(messages, mergedOptions, run);
|
|
218
|
+
if (!run.stream) {
|
|
219
|
+
const { assistantMsg } = await this.executeCompleteRequest(requestParams, run);
|
|
220
|
+
return assistantMsg;
|
|
170
221
|
}
|
|
171
|
-
const
|
|
222
|
+
const parser = this._parserFactory();
|
|
223
|
+
const stream = await this.raceWithAbort(this._client.stream(requestParams, this.createClientOptions(run.signal)), run.signal);
|
|
172
224
|
for await (const chunk of stream) {
|
|
173
225
|
this.throwIfAborted(run.signal);
|
|
174
226
|
const events = parser.feed(chunk);
|
|
175
|
-
this.
|
|
227
|
+
this.emitParserEvents(events);
|
|
176
228
|
}
|
|
177
229
|
this.throwIfAborted(run.signal);
|
|
178
230
|
const finalEvents = parser.finish();
|
|
179
|
-
this.
|
|
231
|
+
this.emitParserEvents(finalEvents);
|
|
180
232
|
const message = this.extractMessage(finalEvents);
|
|
181
233
|
return message;
|
|
182
234
|
}
|
|
@@ -282,7 +334,7 @@ class Agent {
|
|
|
282
334
|
}
|
|
283
335
|
/** 当前是否有运行中的请求 */
|
|
284
336
|
get isRunning() {
|
|
285
|
-
return !!this._activeAbortController
|
|
337
|
+
return !!this._activeAbortController;
|
|
286
338
|
}
|
|
287
339
|
/**
|
|
288
340
|
* 中断当前运行中的 Agent。
|
|
@@ -293,9 +345,11 @@ class Agent {
|
|
|
293
345
|
if (!this._activeAbortController || this._activeAbortController.signal.aborted) {
|
|
294
346
|
return false;
|
|
295
347
|
}
|
|
296
|
-
const error = reason instanceof
|
|
348
|
+
const error = reason instanceof AgentAbortError
|
|
297
349
|
? reason
|
|
298
|
-
:
|
|
350
|
+
: reason instanceof Error
|
|
351
|
+
? new AgentAbortError(reason.message, reason)
|
|
352
|
+
: new AgentAbortError(reason ?? "Agent run aborted by user");
|
|
299
353
|
this._activeAbortController.abort(error);
|
|
300
354
|
return true;
|
|
301
355
|
}
|
|
@@ -345,17 +399,32 @@ class Agent {
|
|
|
345
399
|
let lastAssistantMsg;
|
|
346
400
|
for (let turn = 0; turn < this._maxTurns; turn++) {
|
|
347
401
|
this.throwIfAborted(run.signal);
|
|
348
|
-
const parser =
|
|
402
|
+
const parser = run.stream ? this._parserFactory() : undefined;
|
|
349
403
|
currentParser = parser;
|
|
350
404
|
partialAlreadyPersisted = false;
|
|
351
405
|
this.updateRunState({ turn });
|
|
352
406
|
this.emit({ type: StreamEvent_1.StreamEventType.TURN_START, turn });
|
|
353
407
|
// 流式调用 + 解析
|
|
354
|
-
const
|
|
408
|
+
const response = parser
|
|
409
|
+
? await this.executeSingleStream(parser, mergedOptions, run)
|
|
410
|
+
: await this.executeSingleComplete(mergedOptions, run);
|
|
411
|
+
// 模型响应已经完整返回;提交前生命周期失败时不应回退为未转换的 partial。
|
|
412
|
+
currentParser = undefined;
|
|
413
|
+
const commitEvent = {
|
|
414
|
+
type: StreamEvent_1.StreamEventType.BEFORE_ASSISTANT_COMMIT,
|
|
415
|
+
message: response.assistantMsg,
|
|
416
|
+
turn,
|
|
417
|
+
finishReason: response.finishReason,
|
|
418
|
+
};
|
|
419
|
+
await this.emitAsync(commitEvent);
|
|
420
|
+
const assistantMsg = commitEvent.message;
|
|
421
|
+
const finishReason = response.finishReason;
|
|
422
|
+
if (assistantMsg.role !== Role_1.Role.Assistant) {
|
|
423
|
+
throw new Error("BEFORE_ASSISTANT_COMMIT 必须返回 Assistant 消息");
|
|
424
|
+
}
|
|
355
425
|
// 添加到 Session
|
|
356
426
|
this._session.addAssistant(assistantMsg);
|
|
357
427
|
lastAssistantMsg = assistantMsg;
|
|
358
|
-
currentParser = undefined;
|
|
359
428
|
partialAlreadyPersisted = true;
|
|
360
429
|
this.updateRunState({ lastMessage: assistantMsg });
|
|
361
430
|
// 输出长度限制
|
|
@@ -382,8 +451,12 @@ class Agent {
|
|
|
382
451
|
const partial = currentParser && !partialAlreadyPersisted
|
|
383
452
|
? this.persistPartialSnapshot(currentParser, reason)
|
|
384
453
|
: undefined;
|
|
454
|
+
const canResume = !!partial || this.isContinuableError(error);
|
|
455
|
+
if (canResume) {
|
|
456
|
+
this.completeInterruptedToolCalls(error, reason);
|
|
457
|
+
}
|
|
385
458
|
if (this._lastRunState?.error !== error) {
|
|
386
|
-
this.failRunState(error, reason, partial,
|
|
459
|
+
this.failRunState(error, reason, partial, canResume);
|
|
387
460
|
}
|
|
388
461
|
this.emitError(error);
|
|
389
462
|
throw error;
|
|
@@ -399,6 +472,28 @@ class Agent {
|
|
|
399
472
|
const configParams = this._config ? this._config.build() : {};
|
|
400
473
|
return { ...configParams, ...this._requestOptions, ...runOptions };
|
|
401
474
|
}
|
|
475
|
+
async buildModelRequest(messages, options, run) {
|
|
476
|
+
const serialized = await this.raceWithAbort(this._adapter.serialize(messages, run.serializeOptions), run.signal);
|
|
477
|
+
const tools = this._toolkit?.size ? this._toolkit.schemas : undefined;
|
|
478
|
+
if (this._adapter.buildRequest) {
|
|
479
|
+
return this._adapter.buildRequest({
|
|
480
|
+
model: this._model,
|
|
481
|
+
serialized,
|
|
482
|
+
tools,
|
|
483
|
+
options,
|
|
484
|
+
stream: run.stream,
|
|
485
|
+
});
|
|
486
|
+
}
|
|
487
|
+
const request = {
|
|
488
|
+
model: this._model,
|
|
489
|
+
messages: serialized.messages,
|
|
490
|
+
...options,
|
|
491
|
+
stream: run.stream,
|
|
492
|
+
};
|
|
493
|
+
if (tools)
|
|
494
|
+
request.tools = tools;
|
|
495
|
+
return request;
|
|
496
|
+
}
|
|
402
497
|
/**
|
|
403
498
|
* 执行单轮流式调用:序列化 → 请求 → 解析 → 返回 Message
|
|
404
499
|
*/
|
|
@@ -408,29 +503,19 @@ class Agent {
|
|
|
408
503
|
const context = this._promptBuilder
|
|
409
504
|
? this._promptBuilder.build(history, run.promptBuildOptions)
|
|
410
505
|
: history;
|
|
411
|
-
const
|
|
412
|
-
// 构建请求参数
|
|
413
|
-
const requestParams = {
|
|
414
|
-
model: this._model,
|
|
415
|
-
messages: serialized,
|
|
416
|
-
stream: true,
|
|
417
|
-
...mergedOptions,
|
|
418
|
-
};
|
|
419
|
-
if (this._toolkit && this._toolkit.size > 0) {
|
|
420
|
-
requestParams.tools = this._toolkit.schemas;
|
|
421
|
-
}
|
|
506
|
+
const adaptedRequest = await this.buildModelRequest(context, mergedOptions, run);
|
|
422
507
|
// 流式调用
|
|
423
|
-
const stream = await this.raceWithAbort(this._client.
|
|
508
|
+
const stream = await this.raceWithAbort(this._client.stream(adaptedRequest, this.createClientOptions(run.signal)), run.signal);
|
|
424
509
|
// 解析 chunks
|
|
425
510
|
for await (const chunk of stream) {
|
|
426
511
|
this.throwIfAborted(run.signal);
|
|
427
512
|
const events = parser.feed(chunk);
|
|
428
|
-
this.
|
|
513
|
+
this.emitParserEvents(events);
|
|
429
514
|
}
|
|
430
515
|
this.throwIfAborted(run.signal);
|
|
431
516
|
// 结束解析
|
|
432
517
|
const finalEvents = parser.finish();
|
|
433
|
-
this.
|
|
518
|
+
this.emitParserEvents(finalEvents);
|
|
434
519
|
// 提取组装好的 Message
|
|
435
520
|
const assistantMsg = this.extractMessage(finalEvents);
|
|
436
521
|
const finishReason = this.extractFinishReason(finalEvents);
|
|
@@ -438,6 +523,60 @@ class Agent {
|
|
|
438
523
|
assistantMsg.model = this._model;
|
|
439
524
|
return { assistantMsg, finishReason };
|
|
440
525
|
}
|
|
526
|
+
/** Execute one complete-response turn without a stream parser. */
|
|
527
|
+
async executeSingleComplete(mergedOptions, run) {
|
|
528
|
+
const history = this._session.history();
|
|
529
|
+
const context = this._promptBuilder
|
|
530
|
+
? this._promptBuilder.build(history, run.promptBuildOptions)
|
|
531
|
+
: history;
|
|
532
|
+
const request = await this.buildModelRequest(context, mergedOptions, run);
|
|
533
|
+
return this.executeCompleteRequest(request, run);
|
|
534
|
+
}
|
|
535
|
+
async executeCompleteRequest(request, run) {
|
|
536
|
+
if (!this._client.complete) {
|
|
537
|
+
throw new Error("The configured ModelClient does not support non-streaming requests; implement complete() or use stream: true");
|
|
538
|
+
}
|
|
539
|
+
const raw = await this.raceWithAbort(this._client.complete(request, this.createClientOptions(run.signal)), run.signal);
|
|
540
|
+
this.throwIfAborted(run.signal);
|
|
541
|
+
const assistantMsg = this._adapter.deserializeResponse
|
|
542
|
+
? this._adapter.deserializeResponse(raw)
|
|
543
|
+
: this._adapter.deserialize(raw);
|
|
544
|
+
const finishReason = this._adapter.getFinishReason?.(raw);
|
|
545
|
+
assistantMsg.model ??= this._model;
|
|
546
|
+
this.emitCompleteResponseEvents(assistantMsg, finishReason);
|
|
547
|
+
return { assistantMsg, finishReason };
|
|
548
|
+
}
|
|
549
|
+
emitCompleteResponseEvents(message, finishReason) {
|
|
550
|
+
if (message.thinking) {
|
|
551
|
+
this.emit({
|
|
552
|
+
type: StreamEvent_1.StreamEventType.THINKING_DONE,
|
|
553
|
+
thinking: message.thinking,
|
|
554
|
+
});
|
|
555
|
+
}
|
|
556
|
+
if (message.text) {
|
|
557
|
+
this.emit({ type: StreamEvent_1.StreamEventType.TEXT_DONE, text: message.text });
|
|
558
|
+
}
|
|
559
|
+
message.toolCalls.forEach((toolCall, index) => {
|
|
560
|
+
this.emit({
|
|
561
|
+
type: StreamEvent_1.StreamEventType.TOOL_CALL_START,
|
|
562
|
+
index,
|
|
563
|
+
toolCallId: toolCall.toolCallId,
|
|
564
|
+
name: toolCall.name,
|
|
565
|
+
});
|
|
566
|
+
this.emit({
|
|
567
|
+
type: StreamEvent_1.StreamEventType.TOOL_CALL_DONE,
|
|
568
|
+
index,
|
|
569
|
+
toolCallId: toolCall.toolCallId,
|
|
570
|
+
name: toolCall.name,
|
|
571
|
+
arguments: toolCall.arguments,
|
|
572
|
+
});
|
|
573
|
+
});
|
|
574
|
+
this.emit({
|
|
575
|
+
type: StreamEvent_1.StreamEventType.MESSAGE_DONE,
|
|
576
|
+
message,
|
|
577
|
+
finishReason,
|
|
578
|
+
});
|
|
579
|
+
}
|
|
441
580
|
/**
|
|
442
581
|
* 处理工具调用:审批 → 执行 → 结果回写 Session
|
|
443
582
|
*/
|
|
@@ -503,20 +642,36 @@ class Agent {
|
|
|
503
642
|
* agent.emit({ type: "abort" });
|
|
504
643
|
*/
|
|
505
644
|
emit(event) {
|
|
506
|
-
const handlers = this._handlers.get(event.type) || [];
|
|
645
|
+
const handlers = [...(this._handlers.get(event.type) || [])];
|
|
507
646
|
for (const handler of handlers) {
|
|
508
647
|
try {
|
|
509
|
-
handler(event);
|
|
648
|
+
const result = handler(event);
|
|
649
|
+
if (result && typeof result.then === "function") {
|
|
650
|
+
Promise.resolve(result).catch((error) => {
|
|
651
|
+
this.reportHandlerError(error, event);
|
|
652
|
+
});
|
|
653
|
+
}
|
|
510
654
|
}
|
|
511
655
|
catch (e) {
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
656
|
+
this.reportHandlerError(e, event);
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
/**
|
|
661
|
+
* 按注册顺序等待事件监听器完成。
|
|
662
|
+
*
|
|
663
|
+
* 与 emit() 的通知语义不同,监听器失败会在上报后继续向调用方抛出,
|
|
664
|
+
* 适合提交前转换等必须完成后才能继续的生命周期。
|
|
665
|
+
*/
|
|
666
|
+
async emitAsync(event) {
|
|
667
|
+
const handlers = [...(this._handlers.get(event.type) || [])];
|
|
668
|
+
for (const handler of handlers) {
|
|
669
|
+
try {
|
|
670
|
+
await handler(event);
|
|
671
|
+
}
|
|
672
|
+
catch (error) {
|
|
673
|
+
this.reportHandlerError(error, event);
|
|
674
|
+
throw error;
|
|
520
675
|
}
|
|
521
676
|
}
|
|
522
677
|
}
|
|
@@ -530,9 +685,27 @@ class Agent {
|
|
|
530
685
|
this._handlerErrorHandler = handler ?? defaultHandlerErrorHandler;
|
|
531
686
|
return this;
|
|
532
687
|
}
|
|
533
|
-
|
|
688
|
+
emitParserEvents(events) {
|
|
689
|
+
let parserError;
|
|
534
690
|
for (const event of events) {
|
|
535
|
-
|
|
691
|
+
if (event.type === StreamEvent_1.StreamEventType.ERROR) {
|
|
692
|
+
parserError ??= event.error;
|
|
693
|
+
}
|
|
694
|
+
else {
|
|
695
|
+
this.emit(event);
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
if (parserError) {
|
|
699
|
+
throw parserError;
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
reportHandlerError(errorLike, event) {
|
|
703
|
+
const error = errorLike instanceof Error ? errorLike : new Error(String(errorLike));
|
|
704
|
+
try {
|
|
705
|
+
this._handlerErrorHandler(error, event);
|
|
706
|
+
}
|
|
707
|
+
catch {
|
|
708
|
+
// 错误处理器本身也抛错时静默吞掉,避免递归
|
|
536
709
|
}
|
|
537
710
|
}
|
|
538
711
|
// ========================
|
|
@@ -599,6 +772,11 @@ class Agent {
|
|
|
599
772
|
if (!result)
|
|
600
773
|
continue;
|
|
601
774
|
this.throwIfAborted(signal);
|
|
775
|
+
const toolError = result.metadata.toolExecutionError;
|
|
776
|
+
if (toolError) {
|
|
777
|
+
this.emitToolExecutionError(new ToolKit_1.ToolExecutionError(tc.toolCallId, tc.name, new Error(toolError.message || "工具执行失败")), tc, result);
|
|
778
|
+
continue;
|
|
779
|
+
}
|
|
602
780
|
this.emit({
|
|
603
781
|
type: StreamEvent_1.StreamEventType.TOOL_EXECUTE_DONE,
|
|
604
782
|
toolCallId: tc.toolCallId,
|
|
@@ -647,7 +825,20 @@ class Agent {
|
|
|
647
825
|
type: StreamEvent_1.StreamEventType.TOOL_APPROVAL_REQUIRED,
|
|
648
826
|
...request,
|
|
649
827
|
});
|
|
650
|
-
|
|
828
|
+
let approvalResult;
|
|
829
|
+
try {
|
|
830
|
+
approvalResult = await this.resolveToolApproval(request, signal);
|
|
831
|
+
}
|
|
832
|
+
catch (e) {
|
|
833
|
+
const error = this.toError(e);
|
|
834
|
+
if (error instanceof AgentAbortError ||
|
|
835
|
+
error instanceof AgentTimeoutError ||
|
|
836
|
+
error instanceof AgentToolApprovalTimeoutError) {
|
|
837
|
+
throw error;
|
|
838
|
+
}
|
|
839
|
+
throw new AgentToolApprovalError(request, error);
|
|
840
|
+
}
|
|
841
|
+
const normalized = this.normalizeApprovalResult(approvalResult);
|
|
651
842
|
if (normalized.approved) {
|
|
652
843
|
this.emit({
|
|
653
844
|
type: StreamEvent_1.StreamEventType.TOOL_APPROVAL_ACCEPTED,
|
|
@@ -721,7 +912,7 @@ class Agent {
|
|
|
721
912
|
if (this._toolApprovalTimeoutMs !== undefined) {
|
|
722
913
|
timer = setTimeout(() => {
|
|
723
914
|
if (this._toolApprovalTimeoutPolicy === "abort") {
|
|
724
|
-
settleReject(new
|
|
915
|
+
settleReject(new AgentToolApprovalTimeoutError(request, Math.max(0, this._toolApprovalTimeoutMs)));
|
|
725
916
|
}
|
|
726
917
|
else {
|
|
727
918
|
settleResolve({ approved: false, reason: "工具审批超时" });
|
|
@@ -756,7 +947,8 @@ class Agent {
|
|
|
756
947
|
return (0, utils_1.generateId)("approval");
|
|
757
948
|
}
|
|
758
949
|
prepareRunOptions(options) {
|
|
759
|
-
|
|
950
|
+
this.ensureIdle();
|
|
951
|
+
const { signal: externalSignal, timeoutMs, promptBuildOptions, serializeOptions, stream = true, ...requestOptions } = options ?? {};
|
|
760
952
|
const cleanupFns = [];
|
|
761
953
|
const controller = new AbortController();
|
|
762
954
|
const signal = controller.signal;
|
|
@@ -777,6 +969,7 @@ class Agent {
|
|
|
777
969
|
}
|
|
778
970
|
return {
|
|
779
971
|
requestOptions,
|
|
972
|
+
stream,
|
|
780
973
|
signal,
|
|
781
974
|
promptBuildOptions,
|
|
782
975
|
serializeOptions,
|
|
@@ -792,6 +985,11 @@ class Agent {
|
|
|
792
985
|
createClientOptions(signal) {
|
|
793
986
|
return signal ? { signal } : undefined;
|
|
794
987
|
}
|
|
988
|
+
ensureIdle() {
|
|
989
|
+
if (this.isRunning) {
|
|
990
|
+
throw new AgentAlreadyRunningError();
|
|
991
|
+
}
|
|
992
|
+
}
|
|
795
993
|
throwIfAborted(signal) {
|
|
796
994
|
if (signal?.aborted) {
|
|
797
995
|
throw this.getAbortReason(signal);
|
|
@@ -868,8 +1066,14 @@ class Agent {
|
|
|
868
1066
|
classifyStopReason(error) {
|
|
869
1067
|
if (error instanceof AgentTimeoutError || error.name === "TimeoutError")
|
|
870
1068
|
return "timeout";
|
|
1069
|
+
if (error instanceof AgentToolApprovalTimeoutError ||
|
|
1070
|
+
error.name === "ToolApprovalTimeoutError")
|
|
1071
|
+
return "timeout";
|
|
871
1072
|
if (error instanceof AgentAbortError || error.name === "AbortError")
|
|
872
1073
|
return "abort";
|
|
1074
|
+
if (error instanceof AgentToolApprovalError ||
|
|
1075
|
+
error.name === "ToolApprovalError")
|
|
1076
|
+
return "tool_approval_error";
|
|
873
1077
|
if (error instanceof ToolKit_1.ToolExecutionError || error.name === "ToolExecutionError")
|
|
874
1078
|
return "tool_execution_error";
|
|
875
1079
|
const name = (error.name || "").toLowerCase();
|
|
@@ -911,6 +1115,8 @@ class Agent {
|
|
|
911
1115
|
isContinuableError(error) {
|
|
912
1116
|
if (error instanceof AgentTimeoutError ||
|
|
913
1117
|
error instanceof AgentAbortError ||
|
|
1118
|
+
error instanceof AgentToolApprovalTimeoutError ||
|
|
1119
|
+
error instanceof AgentToolApprovalError ||
|
|
914
1120
|
error instanceof ToolKit_1.ToolExecutionError ||
|
|
915
1121
|
error.name === "TimeoutError" ||
|
|
916
1122
|
error.name === "AbortError" ||
|
|
@@ -920,6 +1126,38 @@ class Agent {
|
|
|
920
1126
|
const reason = this.classifyStopReason(error);
|
|
921
1127
|
return reason === "network_error" || reason === "stream_error";
|
|
922
1128
|
}
|
|
1129
|
+
completeInterruptedToolCalls(error, reason) {
|
|
1130
|
+
const history = this._session.history();
|
|
1131
|
+
let assistantIndex = -1;
|
|
1132
|
+
for (let i = history.length - 1; i >= 0; i--) {
|
|
1133
|
+
if (history[i].role === "assistant" && history[i].toolCalls.length > 0) {
|
|
1134
|
+
assistantIndex = i;
|
|
1135
|
+
break;
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
if (assistantIndex === -1)
|
|
1139
|
+
return;
|
|
1140
|
+
const assistant = history[assistantIndex];
|
|
1141
|
+
const completedIds = new Set();
|
|
1142
|
+
for (let i = assistantIndex + 1; i < history.length; i++) {
|
|
1143
|
+
for (const part of history[i].parts) {
|
|
1144
|
+
if (part.type === "tool_result") {
|
|
1145
|
+
completedIds.add(part.toolCallId);
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
1149
|
+
const missingResults = assistant.toolCalls
|
|
1150
|
+
.filter((toolCall) => toolCall.toolCallId && !completedIds.has(toolCall.toolCallId))
|
|
1151
|
+
.map((toolCall) => Message_1.Message.tool(toolCall.toolCallId, JSON.stringify({
|
|
1152
|
+
error: error.message,
|
|
1153
|
+
interrupted: true,
|
|
1154
|
+
outcome: "unknown",
|
|
1155
|
+
stopReason: reason,
|
|
1156
|
+
}), toolCall.name).tag("interrupted", "recoverable").setMeta("interrupted", true));
|
|
1157
|
+
if (missingResults.length > 0) {
|
|
1158
|
+
this._session.addTool(missingResults);
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
923
1161
|
}
|
|
924
1162
|
exports.Agent = Agent;
|
|
925
1163
|
//# sourceMappingURL=Agent.js.map
|