@ai-setting/roy-agent-core 1.5.17-beta.1 → 1.5.22

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.
Files changed (54) hide show
  1. package/dist/env/index.js +20 -8
  2. package/dist/env/log-trace/index.js +1 -1
  3. package/dist/env/prompt/index.js +1 -1
  4. package/dist/env/workflow/engine/index.js +1 -1
  5. package/dist/env/workflow/index.js +2 -2
  6. package/dist/index.js +6 -7
  7. package/dist/shared/@ai-setting/{roy-agent-core-xq8hhqb8.js → roy-agent-core-4wjywp3c.js} +4 -2
  8. package/dist/shared/@ai-setting/roy-agent-core-8jxva565.js +19 -0
  9. package/dist/shared/@ai-setting/roy-agent-core-avq1x4t7.js +84 -0
  10. package/dist/shared/@ai-setting/{roy-agent-core-gq20wsgv.js → roy-agent-core-ffb9fq4v.js} +23 -2
  11. package/dist/shared/@ai-setting/{roy-agent-core-93zfb3r1.js → roy-agent-core-mrcxzpbg.js} +1 -1
  12. package/dist/shared/@ai-setting/{roy-agent-core-rhmtwnw1.js → roy-agent-core-pw7cv1px.js} +1 -1
  13. package/dist/shared/@ai-setting/{roy-agent-core-gbqcyegm.js → roy-agent-core-rccptwv0.js} +512 -673
  14. package/dist/shared/@ai-setting/{roy-agent-core-wrcy0h6z.js → roy-agent-core-ty94k28r.js} +1 -1
  15. package/package.json +8 -29
  16. package/dist/config/index.d.ts +0 -1250
  17. package/dist/env/agent/index.d.ts +0 -2279
  18. package/dist/env/commands/index.d.ts +0 -1131
  19. package/dist/env/debug/formatters/index.d.ts +0 -236
  20. package/dist/env/debug/index.d.ts +0 -1652
  21. package/dist/env/hook/index.d.ts +0 -279
  22. package/dist/env/index.d.ts +0 -3481
  23. package/dist/env/llm/index.d.ts +0 -1760
  24. package/dist/env/log-trace/index.d.ts +0 -1574
  25. package/dist/env/mcp/index.d.ts +0 -1331
  26. package/dist/env/mcp/tool/index.d.ts +0 -183
  27. package/dist/env/memory/built-in/index.d.ts +0 -232
  28. package/dist/env/memory/index.d.ts +0 -1799
  29. package/dist/env/memory/plugin/index.d.ts +0 -747
  30. package/dist/env/prompt/index.d.ts +0 -1164
  31. package/dist/env/session/index.d.ts +0 -1908
  32. package/dist/env/session/storage/index.d.ts +0 -564
  33. package/dist/env/skill/index.d.ts +0 -1266
  34. package/dist/env/skill/tool/index.d.ts +0 -193
  35. package/dist/env/task/delegate/index.d.ts +0 -1612
  36. package/dist/env/task/events/index.d.ts +0 -171
  37. package/dist/env/task/hooks/index.d.ts +0 -624
  38. package/dist/env/task/index.d.ts +0 -1553
  39. package/dist/env/task/plugins/index.d.ts +0 -466
  40. package/dist/env/task/storage/index.d.ts +0 -241
  41. package/dist/env/task/tools/index.d.ts +0 -1485
  42. package/dist/env/task/tools/operation/index.d.ts +0 -1484
  43. package/dist/env/tool/built-in/index.d.ts +0 -218
  44. package/dist/env/tool/index.d.ts +0 -1396
  45. package/dist/env/workflow/decorators/index.d.ts +0 -2161
  46. package/dist/env/workflow/engine/index.d.ts +0 -3453
  47. package/dist/env/workflow/index.d.ts +0 -3546
  48. package/dist/env/workflow/nodes/index.d.ts +0 -2092
  49. package/dist/env/workflow/service/index.d.ts +0 -227
  50. package/dist/env/workflow/storage/index.d.ts +0 -165
  51. package/dist/env/workflow/tools/index.d.ts +0 -416
  52. package/dist/env/workflow/types/index.d.ts +0 -2255
  53. package/dist/env/workflow/utils/index.d.ts +0 -2031
  54. package/dist/index.d.ts +0 -7858
@@ -1,3453 +0,0 @@
1
- /**
2
- * @fileoverview Hook 系统统一类型定义
3
- *
4
- * 提供所有 Component 使用的统一 Hook 接口
5
- */
6
- /**
7
- * Hook 执行阶段
8
- */
9
- type HookPhase = "before" | "after" | "error";
10
- /**
11
- * Hook 元信息
12
- */
13
- interface HookMeta {
14
- /** Hook 唯一名称 */
15
- name: string;
16
- /** 执行优先级,默认 0,数值越小越先执行 */
17
- priority?: number;
18
- /** 描述 */
19
- description?: string;
20
- }
21
- /**
22
- * 统一 Hook 上下文
23
- *
24
- * 泛型参数 T 表示该 Component 的上下文数据类型
25
- */
26
- interface HookContext<T = unknown> {
27
- /** 当前组件信息 */
28
- component: {
29
- /** 组件名称 */
30
- name: string;
31
- /** 组件版本 */
32
- version: string;
33
- };
34
- /** 上下文数据(Component 特定) */
35
- data: T;
36
- /** 元数据(可用于传递额外信息) */
37
- metadata: Record<string, unknown>;
38
- /** 执行阶段 */
39
- phase: HookPhase;
40
- /** 关联的 hook 点名称 */
41
- hookPoint: string;
42
- }
43
- /**
44
- * 统一 Hook 接口
45
- *
46
- * 所有 Component 的 Hook 都应实现此接口
47
- */
48
- interface Hook<T = unknown> extends HookMeta {
49
- /** 执行 Hook
50
- * @param ctx 上下文
51
- */
52
- execute(ctx: HookContext<T>): void | Promise<void>;
53
- }
54
- /**
55
- * Hook 函数类型(便捷别名)
56
- */
57
- type HookFn<T = unknown> = (ctx: HookContext<T>) => void | Promise<void>;
58
- /**
59
- * Hook 干预动作类型
60
- */
61
- type HookActionType = "stop" | "retry" | "compress" | "extract_memory" | "inject_message" | "skip_tool" | "custom";
62
- /**
63
- * Hook 干预动作
64
- */
65
- interface HookAction {
66
- /** 动作类型 */
67
- type: HookActionType;
68
- /** 动作参数 */
69
- params?: Record<string, unknown>;
70
- /** 动作描述 */
71
- description?: string;
72
- }
73
- /**
74
- * Hook 执行结果
75
- */
76
- interface HookResult {
77
- /** 是否被停止 */
78
- stopped?: boolean;
79
- /** 干预动作(如果有) */
80
- action?: HookAction;
81
- /** 执行结果数据 */
82
- results?: unknown[];
83
- }
84
- /**
85
- * HookManager 配置
86
- */
87
- interface HookManagerOptions {
88
- /** 组件名称(用于上下文) */
89
- componentName?: string;
90
- /** 组件版本(用于上下文) */
91
- componentVersion?: string;
92
- /** 默认优先级 */
93
- defaultPriority?: number;
94
- }
95
- /**
96
- * HookManager
97
- *
98
- * 统一管理 Component 的 Hook
99
- *
100
- * @example
101
- * ```typescript
102
- * const manager = new HookManager<MyContext>();
103
- *
104
- * // 注册 Hook
105
- * manager.register("before-action", {
106
- * name: "my-hook",
107
- * priority: 10,
108
- * execute: async (ctx) => { /* ... *\/ }
109
- * });
110
- *
111
- * // 执行 Hooks
112
- * await manager.execute("before-action", data);
113
- * ```
114
- */
115
- declare class HookManager<T = unknown> {
116
- private _hooks;
117
- private componentName;
118
- private componentVersion;
119
- private defaultPriority;
120
- constructor(options?: HookManagerOptions);
121
- /**
122
- * 注册 Hook 到指定 hook 点
123
- */
124
- register(hookPoint: string, hook: Hook<T>): void;
125
- /**
126
- * 注册多个 Hook
127
- */
128
- registerMany(hookPoint: string, hooks: Hook<T>[]): void;
129
- /**
130
- * 按名称取消注册 Hook
131
- * @returns 是否成功取消注册
132
- */
133
- unregister(hookPoint: string, name: string): boolean;
134
- /**
135
- * 取消注册所有指定 hook 点的 Hook
136
- */
137
- unregisterAll(hookPoint: string): void;
138
- /**
139
- * 执行指定 hook 点的所有 Hook
140
- */
141
- execute(hookPoint: string, data: T, metadata?: Record<string, unknown>): Promise<void>;
142
- /**
143
- * 执行指定 hook 点的所有 Hook 并收集返回值
144
- */
145
- executeAndCollect<R>(hookPoint: string, data: T, metadata?: Record<string, unknown>): Promise<R[]>;
146
- /**
147
- * 获取指定 hook 点的 Hook 数量
148
- */
149
- count(hookPoint: string): number;
150
- /**
151
- * 清空所有 Hook
152
- */
153
- clear(): void;
154
- /**
155
- * 获取所有已注册的 hook 点
156
- */
157
- getHookPoints(): string[];
158
- /**
159
- * 检查 hook 点是否有任何 Hook
160
- */
161
- hasHooks(hookPoint: string): boolean;
162
- /**
163
- * 设置组件信息
164
- */
165
- setComponentInfo(name: string, version: string): void;
166
- /**
167
- * 获取所有注册的 hooks(只读副本)
168
- */
169
- get hooks(): ReadonlyMap<string, Hook<T>[]>;
170
- /**
171
- * 执行 Hook 并支持干预机制
172
- *
173
- * 如果任何一个 Hook 返回 { stop: true },执行会停止
174
- * Hook 可以通过返回 HookResult 来执行干预动作
175
- *
176
- * @param hookPoint Hook 点
177
- * @param data 数据
178
- * @param metadata 元数据
179
- * @returns 执行结果
180
- */
181
- executeWithIntervention(hookPoint: string, data: T, metadata?: Record<string, unknown>): Promise<HookResult>;
182
- /**
183
- * 获取或创建 hook 列表
184
- */
185
- private getOrCreateHooks;
186
- /**
187
- * 按优先级排序 Hook
188
- *
189
- * 优先级相同时保持原顺序(稳定排序)
190
- */
191
- private sortHooks;
192
- /**
193
- * 创建 Hook 上下文
194
- */
195
- private createContext;
196
- /**
197
- * 安全执行 Hook(错误隔离)
198
- */
199
- private safeExecute;
200
- /**
201
- * 安全执行 Hook 并返回结果
202
- */
203
- private safeExecuteAndReturn;
204
- }
205
- import { z as z5 } from "zod";
206
- import { z as z4 } from "zod";
207
- import { z } from "zod";
208
- declare const WorkflowEventSchema: unknown;
209
- type WorkflowEvent = z.infer<typeof WorkflowEventSchema>;
210
- type EventHandler = (event: WorkflowEvent) => void | Promise<void>;
211
- /**
212
- * EventBus for workflow events.
213
- * Custom event bus implementation with support for wildcard subscriptions.
214
- */
215
- declare class EventBus {
216
- private handlers;
217
- private wildcardHandlers;
218
- constructor();
219
- /**
220
- * Subscribe to a specific event type.
221
- * @returns Unsubscribe function
222
- */
223
- on(eventType: string, handler: EventHandler): () => void;
224
- /**
225
- * Subscribe to an event type only once (auto-unsubscribe after first call).
226
- * @returns Unsubscribe function
227
- */
228
- once(eventType: string, handler: EventHandler): () => void;
229
- /**
230
- * Unsubscribe from an event type.
231
- */
232
- off(eventType: string, handler: EventHandler): void;
233
- /**
234
- * Subscribe to all events (wildcard subscription).
235
- * @returns Unsubscribe function
236
- */
237
- onAny(handler: EventHandler): () => void;
238
- /**
239
- * Publish an event to all subscribers.
240
- * Handler errors are caught and do not crash the bus.
241
- *
242
- * @param event - The event to publish
243
- * @param waitForHandlers - If true, waits for all async handlers to complete (default: false)
244
- */
245
- publish(event: WorkflowEvent, waitForHandlers?: boolean): Promise<void>;
246
- /**
247
- * Execute a handler safely, catching any errors.
248
- */
249
- private executeHandler;
250
- /**
251
- * Clear all subscriptions.
252
- */
253
- clear(): void;
254
- /**
255
- * Get statistics about the event bus.
256
- */
257
- getStats(): {
258
- eventTypes: number;
259
- wildcardHandlers: number;
260
- totalHandlers: number;
261
- };
262
- }
263
- import { ZodType as ZodType3, ZodTypeDef as ZodTypeDef2 } from "zod";
264
- /**
265
- * @fileoverview Environment types and interfaces
266
- *
267
- * 定义 Environment 的核心类型,包括:
268
- * - Environment 配置
269
- * - EnvEvent 事件类型
270
- */
271
- /**
272
- * Environment Config
273
- */
274
- interface EnvironmentConfig {
275
- /** 环境名称 */
276
- name: string;
277
- /** 环境版本 */
278
- version: string;
279
- /** 是否启用 */
280
- enabled: boolean;
281
- }
282
- /**
283
- * EnvEvent 元信息
284
- */
285
- interface EnvEventMetadata {
286
- /** 触发事件的 session ID */
287
- trigger_session_id?: string;
288
- /** 触发事件的 agent ID */
289
- trigger_agent_id?: string;
290
- /** Agent 名称 */
291
- trigger_agent_name?: string;
292
- /** 环境名称 */
293
- env_name?: string;
294
- /** 事件来源 */
295
- source?: string;
296
- /** 其他元数据 */
297
- [key: string]: unknown;
298
- }
299
- /**
300
- * EnvEvent
301
- *
302
- * 统一的事件机制,用于:
303
- * - Stream 事件(stream.start, stream.text, stream.completed 等)
304
- * - 工具调用事件(tool.call, tool.result 等)
305
- * - 会话事件(session.created, session.updated 等)
306
- * - Agent 事件(agent.thinking, agent.acting 等)
307
- */
308
- interface EnvEvent<T = unknown> {
309
- /** 事件 ID */
310
- id: string;
311
- /** 事件类型 */
312
- type: string;
313
- /** 时间戳 */
314
- timestamp: number;
315
- /** 元信息 */
316
- metadata: EnvEventMetadata;
317
- /** 事件负载 */
318
- payload: T;
319
- }
320
- /**
321
- * EnvEvent Handler
322
- */
323
- type EnvEventHandler = (event: EnvEvent) => void | Promise<void>;
324
- /**
325
- * EnvEvent 创建参数(部分属性,可选)
326
- *
327
- * 用于 pushEnvEvent 方法,允许传入部分属性,自动补全必填字段
328
- */
329
- interface EnvEventInput {
330
- /** 事件类型(必填) */
331
- type: string;
332
- /** 事件 ID(可选,自动生成) */
333
- id?: string;
334
- /** 时间戳(可选,自动生成) */
335
- timestamp?: number;
336
- /** 元信息(可选,自动创建) */
337
- metadata?: EnvEventMetadata;
338
- /** 事件负载(可选) */
339
- payload?: unknown;
340
- }
341
- /**
342
- * Action 类型
343
- */
344
- interface Action {
345
- /** Action 类型 */
346
- type: string;
347
- /** Action 参数 */
348
- params?: Record<string, unknown>;
349
- }
350
- /**
351
- * Tool Result
352
- */
353
- interface ToolResult {
354
- /** 是否成功 */
355
- success: boolean;
356
- /** 输出内容 */
357
- output: string | Record<string, unknown>;
358
- /** 错误信息 */
359
- error?: string;
360
- }
361
- /**
362
- * Context
363
- */
364
- interface Context {
365
- /** 会话 ID */
366
- sessionId?: string;
367
- /** 用户 ID */
368
- userId?: string;
369
- /** 工作目录 */
370
- workdir?: string;
371
- /** 中断信号 */
372
- abort?: AbortSignal;
373
- /** 元数据 */
374
- metadata?: Record<string, unknown>;
375
- }
376
- import { ModelMessage } from "ai";
377
- import { z as z2, ZodType, ZodError } from "zod";
378
- /**
379
- * 沙箱配置
380
- */
381
- interface SandboxConfig {
382
- /** 是否启用沙箱 */
383
- enabled: boolean;
384
- /** 沙箱类型 */
385
- type: "native" | "docker";
386
- /** 动作过滤 */
387
- actionFilter?: {
388
- /** 包含的动作 */
389
- include?: string[];
390
- /** 排除的动作 */
391
- exclude?: string[];
392
- };
393
- /** 文件系统限制 */
394
- filesystem?: {
395
- /** 允许读取 */
396
- allowRead?: string[];
397
- /** 禁止读取 */
398
- denyRead?: string[];
399
- /** 允许写入 */
400
- allowWrite?: string[];
401
- /** 禁止写入 */
402
- denyWrite?: string[];
403
- };
404
- /** 网络限制 */
405
- network?: {
406
- /** 允许的域名 */
407
- allowedDomains?: string[];
408
- /** 禁止的域名 */
409
- deniedDomains?: string[];
410
- };
411
- /** Docker 配置 */
412
- docker?: {
413
- /** 镜像 */
414
- image?: string;
415
- /** 网络模式 */
416
- networkMode?: "bridge" | "host" | "none";
417
- /** 卷挂载 */
418
- volumes?: Record<string, string>;
419
- };
420
- }
421
- /**
422
- * 工具执行上下文
423
- */
424
- interface ToolContext {
425
- /** 工作目录 */
426
- workdir?: string;
427
- /** 用户 ID */
428
- user_id?: string;
429
- /** 会话 ID */
430
- session_id?: string;
431
- /** 消息 ID */
432
- message_id?: string;
433
- /** 中断信号 */
434
- abort?: AbortSignal;
435
- /** 额外元数据 */
436
- metadata?: Record<string, unknown>;
437
- /** 沙箱配置 */
438
- sandbox?: SandboxConfig;
439
- /** 沙箱 Provider */
440
- sandboxProvider?: unknown | null;
441
- }
442
- /**
443
- * 工具结果元数据
444
- */
445
- interface ToolResultMetadata {
446
- /** 执行时间(毫秒) */
447
- execution_time_ms: number;
448
- /** 输出大小(字节) */
449
- output_size?: number;
450
- /** 标准输出 */
451
- stdout?: string;
452
- /** 标准错误 */
453
- stderr?: string;
454
- /** 退出码 */
455
- exit_code?: number;
456
- /** Token 使用量 */
457
- usage?: {
458
- inputTokens: number;
459
- outputTokens: number;
460
- totalTokens?: number;
461
- };
462
- /** 额外元数据 */
463
- [key: string]: unknown;
464
- }
465
- /**
466
- * 工具执行结果
467
- */
468
- interface ToolResult2 {
469
- /** 是否成功 */
470
- success: boolean;
471
- /** 输出内容 */
472
- output: string | Record<string, unknown>;
473
- /** 错误信息 */
474
- error?: string;
475
- /** 结果元数据 */
476
- metadata?: ToolResultMetadata;
477
- }
478
- /**
479
- * 工具元数据
480
- */
481
- interface ToolMetadata {
482
- /** 分类 */
483
- category?: string;
484
- /** 标签 */
485
- tags?: string[];
486
- /** 版本 */
487
- version?: string;
488
- /** 作者 */
489
- author?: string;
490
- /** 是否实验性 */
491
- experimental?: boolean;
492
- /** MCP 工具信息(MCP adapter 使用) */
493
- mcpTool?: {
494
- originalName: string;
495
- originalDescription: string;
496
- inputSchema?: unknown;
497
- };
498
- }
499
- /**
500
- * 工具沙箱配置
501
- */
502
- interface ToolSandboxConfig {
503
- /** 是否启用沙箱 */
504
- enabled: boolean;
505
- /** 沙箱配置 */
506
- config?: Partial<SandboxConfig>;
507
- }
508
- /**
509
- * 工具权限配置
510
- */
511
- interface ToolPermissionConfig {
512
- /** 是否需要用户确认 */
513
- requireConfirmation?: boolean;
514
- /** 权限级别 */
515
- level?: "safe" | "dangerous" | "critical";
516
- }
517
- /**
518
- * 工具信息
519
- */
520
- interface ToolInfo<Parameters extends ZodType = ZodType> {
521
- /** 工具名称 */
522
- name: string;
523
- /** 工具描述 */
524
- description: string;
525
- /** 参数 Schema */
526
- parameters: Parameters;
527
- /** 初始化函数(可选) */
528
- init?: (ctx?: ToolContext) => Promise<void>;
529
- /** 执行函数 */
530
- execute: (args: z2.infer<Parameters>, ctx: ToolContext) => Promise<ToolResult2>;
531
- /** 参数验证错误格式化(可选) */
532
- formatValidationError?: (error: ZodError) => string;
533
- /** 沙箱配置 */
534
- sandbox?: ToolSandboxConfig;
535
- /** 权限配置 */
536
- permission?: ToolPermissionConfig;
537
- /** 工具元数据 */
538
- metadata?: ToolMetadata;
539
- }
540
- /**
541
- * 工具类型别名
542
- */
543
- type Tool = ToolInfo;
544
- type AbortSignalType = AbortSignal;
545
- interface ProjectSummary {
546
- projectPath: string;
547
- projectName: string;
548
- lastUpdated: number;
549
- summary: string;
550
- shortSummary: string;
551
- draftCount: number;
552
- memoryMdPath: string;
553
- draftsDir: string;
554
- detailsDir: string;
555
- }
556
- /**
557
- * Agent 执行上下文
558
- */
559
- interface AgentContext {
560
- /** 会话 ID */
561
- sessionId?: string;
562
- /** 消息 ID */
563
- messageId?: string;
564
- /** 中断信号 */
565
- abort?: AbortSignalType;
566
- /** 额外的上下文信息(会添加到 system prompt) */
567
- additionInfo?: string;
568
- /** 元数据 */
569
- metadata?: Record<string, unknown>;
570
- /** Agent 类型(用于选择 Behavior Spec) */
571
- agentType?: string;
572
- /** 使用的模型 */
573
- model?: string;
574
- /** 允许的工具列表(上下文级别,会覆盖 agent 配置) */
575
- allowedTools?: string[];
576
- /** 拒绝的工具列表(上下文级别,会覆盖 agent 配置) */
577
- deniedTools?: string[];
578
- /** 是否过滤 history 中的 tool 消息(上下文级别,会覆盖 agent 配置) */
579
- filterHistory?: boolean;
580
- }
581
- /**
582
- * 工具调用(内部使用)
583
- */
584
- interface ToolCall2 {
585
- /** 调用 ID */
586
- id: string;
587
- /** 工具名称 */
588
- name: string;
589
- /** 调用参数 */
590
- arguments: Record<string, unknown>;
591
- }
592
- /**
593
- * 工具调用结果
594
- */
595
- interface ToolCallResult {
596
- /** 调用 ID */
597
- id: string;
598
- /** 工具名称 */
599
- name: string;
600
- /** 调用结果 */
601
- result: ToolResult2;
602
- /** 是否成功 */
603
- success: boolean;
604
- }
605
- /**
606
- * Hook 点枚举(带 component 前缀)
607
- */
608
- type HookPoint = "agent:before.start" | "agent:before.llm" | "agent:after.llm" | "agent:before.tool" | "agent:after.tool" | "agent:on.iteration" | "agent:on.threshold" | "agent:after.complete" | "agent:on.error" | "agent:after.react" | "on.error";
609
- /**
610
- * Hook 上下文(Agent 特有版本)
611
- *
612
- * 注意:这是 AgentComponent 使用的 HookContext 扩展版本
613
- * 包含 iteration, maxIterations, messages 等 Agent 特有字段
614
- */
615
- interface HookContext2 {
616
- /** 当前 LLM 输出(after.llm hook 可用) */
617
- llmOutput?: AgentLLMOutput;
618
- /** 当前工具调用(before.tool/after.tool hook 可用) */
619
- currentToolCall?: ToolCall2;
620
- /** 工具执行结果(after.tool hook 可用) */
621
- toolResult?: ToolCallResult;
622
- /** 阈值信息(on.threshold hook 可用) */
623
- threshold?: {
624
- type: "tokens" | "turns" | "iterations" | "custom";
625
- value: number;
626
- limit?: number;
627
- };
628
- /** 当前错误(on.error hook 可用) */
629
- error?: Error;
630
- /** 当前 Agent 实例 */
631
- agent: AgentInstance;
632
- /** 当前迭代次数(可修改) */
633
- iteration: number;
634
- /** 最大迭代次数限制(before.llm hook 可用) */
635
- maxIterations: number;
636
- /** 消息列表(可直接修改) */
637
- messages: ModelMessage[];
638
- /** 可用工具列表(可直接修改) */
639
- tools: Tool[];
640
- /** 当前 system prompt(可直接修改) */
641
- systemPrompt: string;
642
- /** 额外的上下文信息(可直接修改) */
643
- additionInfo?: string;
644
- /** 执行上下文(可直接修改属性) */
645
- context: AgentContext;
646
- /** 是否已停止 */
647
- _stopped?: boolean;
648
- /** 停止原因 */
649
- _stopReason?: string;
650
- /** 待执行的干预动作 */
651
- _pendingAction?: {
652
- type: HookActionType2;
653
- payload?: unknown;
654
- };
655
- /** 错误列表 */
656
- _errors?: Array<{
657
- plugin: string;
658
- error: string;
659
- }>;
660
- /** Project Memory Agent 生成的摘要列表(由 Project Agent 写入,Global Agent 读取) */
661
- projectSummaries?: ProjectSummary[];
662
- }
663
- /**
664
- * Hook 干预动作
665
- */
666
- type HookActionType2 = "stop" | "retry" | "compress" | "extract_memory" | "inject_message" | "skip_tool";
667
- /**
668
- * Hook 返回结果
669
- */
670
- interface HookResult2 {
671
- /** 是否继续执行(false = 停止 Agent) */
672
- continue: boolean;
673
- /** 干预动作(可选) */
674
- action?: {
675
- type: HookActionType2;
676
- payload?: unknown;
677
- };
678
- }
679
- /**
680
- * Plugin 定义
681
- */
682
- interface Plugin {
683
- /** Plugin 唯一名称 */
684
- name: string;
685
- /** Plugin 版本 */
686
- version: string;
687
- /** Plugin 描述 */
688
- description?: string;
689
- /** 订阅的 Hook 点及优先级 */
690
- hooks: Array<{
691
- point: HookPoint;
692
- /** 优先级,默认 0,数字越大越先执行 */
693
- priority?: number;
694
- }>;
695
- /** 执行函数 */
696
- execute: (ctx: HookContext2) => HookResult2 | Promise<HookResult2>;
697
- }
698
- /**
699
- * Agent 类型
700
- */
701
- type AgentType = "primary" | "sub" | "summary";
702
- /**
703
- * Agent 状态
704
- */
705
- type AgentStatus = "idle" | "running" | "paused" | "stopped" | "error";
706
- /**
707
- * Agent 实例配置
708
- */
709
- interface AgentInstanceConfig {
710
- /** Agent 类型 */
711
- type: AgentType;
712
- /** Agent 名称 */
713
- name?: string;
714
- /** System Prompt */
715
- systemPrompt?: string;
716
- /** Behavior Spec ID */
717
- behaviorSpecId?: string;
718
- /** 使用的模型 */
719
- model?: string;
720
- /** 最大迭代次数 */
721
- maxIterations?: number;
722
- /** 最大错误重试次数 */
723
- maxErrorRetries?: number;
724
- /** 死循环检测阈值 */
725
- doomLoopThreshold?: number;
726
- /** 允许的工具列表 */
727
- allowedTools?: string[];
728
- /** 拒绝的工具列表 */
729
- deniedTools?: string[];
730
- /** 工具超时(毫秒) */
731
- toolTimeout?: number;
732
- /** 工具重试次数 */
733
- toolRetries?: number;
734
- /** 是否过滤 history 中的 tool 消息(默认过滤,避免上下文过长) */
735
- filterHistory?: boolean;
736
- }
737
- /**
738
- * Agent 实例
739
- */
740
- interface AgentInstance {
741
- /** Agent 名称 */
742
- name: string;
743
- /** Agent 配置 */
744
- config: Required<AgentInstanceConfig>;
745
- /** 当前状态 */
746
- status: AgentStatus;
747
- /** 注册的 Plugins */
748
- plugins: Map<string, Plugin>;
749
- }
750
- /**
751
- * Agent 执行结果
752
- */
753
- interface AgentRunResult {
754
- /** 最终文本响应 */
755
- finalText?: string;
756
- /** 是否被 hook 停止 */
757
- stopped?: boolean;
758
- /** 停止原因 */
759
- stopReason?: string;
760
- /** 执行的迭代次数 */
761
- iterations: number;
762
- /** 工具调用列表 */
763
- toolCalls: ToolCall2[];
764
- /** 错误信息(如有) */
765
- error?: string;
766
- }
767
- /**
768
- * Agent 内部使用的 LLM 输出
769
- * 独立定义以避免与 LLMOutput 的类型冲突
770
- */
771
- interface AgentLLMOutput {
772
- /** 生成的内容 */
773
- content: string;
774
- /** 完成原因 */
775
- finishReason: "stop" | "length" | "content-filter" | "tool-calls" | "function-call";
776
- /** 工具调用(兼容格式) */
777
- toolCalls?: Array<{
778
- id: string;
779
- function?: {
780
- name: string;
781
- arguments: string;
782
- };
783
- name?: string;
784
- arguments?: string;
785
- }>;
786
- /** Usage 信息 */
787
- usage?: {
788
- promptTokens: number;
789
- completionTokens: number;
790
- totalTokens: number;
791
- };
792
- /** 生成模型 */
793
- model?: string;
794
- /** 推理内容(思考过程) */
795
- reasoning?: string;
796
- }
797
- import { ZodType as ZodType2, ZodTypeDef } from "zod";
798
- /**
799
- * ConfigSource 类型
800
- */
801
- type ConfigSourceType = "memory" | "file" | "env" | "remote";
802
- /**
803
- * SourceRegistration - Source 注册配置
804
- */
805
- interface SourceRegistration {
806
- /** Source 类型 */
807
- type: ConfigSourceType;
808
- /** 相对路径(file 类型使用,基于 XDG_DATA_HOME) */
809
- relativePath?: string;
810
- /** 环境变量前缀(env 类型使用) */
811
- envPrefix?: string;
812
- /** 优先级,默认值:memory=0, file=10, env=20 */
813
- priority?: number;
814
- /** 是否可选(file 类型使用,文件不存在时不报错) */
815
- optional?: boolean;
816
- /** 是否启用文件监听(file 类型使用,默认 true) */
817
- watch?: boolean;
818
- }
819
- /**
820
- * KeyRegistration - 配置 Key 注册
821
- */
822
- interface KeyRegistration {
823
- /** 配置 Key(支持点号嵌套,如 "llm.provider") */
824
- key: string;
825
- /** 优先使用的 Source 列表(按优先级从低到高) */
826
- sources: ConfigSourceType[];
827
- /** 自定义优先级(覆盖默认优先级) */
828
- priority?: number;
829
- /** 默认值 */
830
- default?: unknown;
831
- }
832
- /**
833
- * ComponentRegistration - Component 注册配置
834
- */
835
- interface ComponentRegistration {
836
- /** Component 名称 */
837
- name: string;
838
- /** 声明需要的 Source */
839
- sources: SourceRegistration[];
840
- /** 声明需要的配置 Key */
841
- keys: KeyRegistration[];
842
- /** 配置 Schema(用于验证,可选) */
843
- schema?: ZodType2<unknown, ZodTypeDef, unknown>;
844
- /** 默认值 */
845
- defaults?: Record<string, unknown>;
846
- }
847
- /**
848
- * ConfigSource 接口
849
- */
850
- interface ConfigSource {
851
- readonly name: ConfigSourceType;
852
- readonly priority: number;
853
- read(key: string): unknown | undefined;
854
- write?(key: string, value: unknown): boolean;
855
- delete?(key: string): boolean;
856
- list(): Array<{
857
- key: string;
858
- value: unknown;
859
- }>;
860
- watch?(callback: (event: ConfigChangeEvent) => void): () => void;
861
- }
862
- /**
863
- * Config 变更事件
864
- */
865
- interface ConfigChangeEvent {
866
- type: "change" | "add" | "delete";
867
- key: string;
868
- oldValue: unknown;
869
- newValue: unknown;
870
- source: ConfigSourceType;
871
- timestamp: number;
872
- }
873
- /**
874
- * ConfigComponent 配置
875
- */
876
- interface ConfigComponentOptions {
877
- /** 持久化文件路径 */
878
- persistFile?: string;
879
- /** 防抖延迟(ms) */
880
- debounceMs?: number;
881
- /** 最大批量大小 */
882
- maxBatchSize?: number;
883
- }
884
- /**
885
- * ConfigComponent
886
- */
887
- declare class ConfigComponent extends BaseComponent {
888
- readonly name = "config";
889
- readonly version = "1.0.0";
890
- private memorySource;
891
- private sources;
892
- private componentSchemas;
893
- private componentPaths;
894
- private watchers;
895
- /** Source watch unsubscribe 函数 */
896
- private sourceUnwatchFns;
897
- private persistQueue;
898
- private persistFile?;
899
- /** Key 注册表:key -> KeyRegistration */
900
- private keyRegistry;
901
- /** Component 注册表:name -> ComponentRegistration */
902
- private componentRegistrations;
903
- /** 协议解析器 */
904
- private protocolResolver?;
905
- /** XDG_DATA_HOME 缓存(用于测试注入) */
906
- private __xdgDataHome?;
907
- /** Source 注册配置(延迟创建) */
908
- private pendingSources;
909
- /** Source 唯一标识缓存:type:relativePath -> true */
910
- private sourceKeys;
911
- /**
912
- * 获取 XDG_DATA_HOME(动态获取,支持运行时覆盖)
913
- */
914
- getXdgDataHome(): string;
915
- /**
916
- * 设置 XDG_DATA_HOME(用于测试)
917
- */
918
- setXdgDataHome(path: string): void;
919
- constructor(options?: ConfigComponentOptions);
920
- /**
921
- * 注册 Component Schema
922
- */
923
- register(schema: ComponentSchema): void;
924
- /**
925
- * 注销 Component
926
- */
927
- unregister(name: string): boolean;
928
- /**
929
- * 检查是否已注册
930
- */
931
- isRegistered(name: string): boolean;
932
- /**
933
- * 列出所有注册的 Component
934
- */
935
- listComponents(): string[];
936
- /**
937
- * 获取配置值(支持 xxx.yyy.zzz 嵌套访问)
938
- * 支持两种模式:
939
- * 1. 完整 key:直接查找,如 "component.key" -> 读取 "component.key"
940
- * 2. 嵌套对象:查找 component 对象后从中获取属性,如 "component.nested.deep"
941
- * -> 先找 "component.nested",再获取其 "deep" 属性
942
- */
943
- get(key: string): unknown;
944
- /**
945
- * 批量获取
946
- */
947
- getMany(keys: string[]): Record<string, unknown>;
948
- /**
949
- * 设置配置值(内存级别 + 异步持久化)
950
- */
951
- set(key: string, value: unknown): Promise<void>;
952
- /**
953
- * 批量设置
954
- */
955
- setMany(config: Record<string, unknown>): Promise<void>;
956
- /**
957
- * 获取 Component 的路径
958
- */
959
- getPath(component: string, subPath?: string): string;
960
- /**
961
- * 手动持久化
962
- */
963
- save(key?: string): Promise<void>;
964
- /**
965
- * 重置到默认值
966
- */
967
- reset(key: string): Promise<void>;
968
- /**
969
- * 监听配置变更
970
- */
971
- watch(pattern: string, callback: ComponentWatchCallback): () => void;
972
- /**
973
- * 添加配置源
974
- */
975
- addSource(source: ConfigSource): void;
976
- /**
977
- * 获取 Source 唯一标识
978
- */
979
- private getSourceKey;
980
- /**
981
- * 移除配置源
982
- */
983
- removeSource(name: ConfigSourceType): boolean;
984
- /**
985
- * 关闭所有配置源的 watcher(用于优雅退出)
986
- */
987
- unwatchAll(): void;
988
- /**
989
- * 获取配置源列表
990
- */
991
- getSources(): ConfigSource[];
992
- private getNestedValue;
993
- private notifyWatchers;
994
- private persistToFile;
995
- /**
996
- * 注册配置 Source
997
- *
998
- * Source 会在首次 load() 时被创建
999
- *
1000
- * @example
1001
- * config.registerSource({ type: "file", relativePath: "llm-config.jsonc" });
1002
- * config.registerSource({ type: "env", envPrefix: "LLM" });
1003
- */
1004
- registerSource(registration: SourceRegistration): void;
1005
- /**
1006
- * 创建 Source 实例
1007
- */
1008
- private createSource;
1009
- /**
1010
- * 确保所有待创建的 Source 已被创建
1011
- */
1012
- private ensureSourcesCreated;
1013
- /**
1014
- * 注册配置 Key
1015
- *
1016
- * @example
1017
- * config.registerKeys([
1018
- * { key: "llm.provider", sources: ["file", "memory"], default: "openai" },
1019
- * { key: "llm.model", sources: ["file"] },
1020
- * ]);
1021
- */
1022
- registerKeys(keys: KeyRegistration[]): void;
1023
- /**
1024
- * 注册 Component(一次性注册 Source 和 Keys)
1025
- *
1026
- * @example
1027
- * config.registerComponent({
1028
- * name: "llm",
1029
- * sources: [
1030
- * { type: "file", relativePath: "llm-config.jsonc" },
1031
- * { type: "env", envPrefix: "LLM" },
1032
- * ],
1033
- * keys: [
1034
- * { key: "llm.provider", sources: ["file", "env", "memory"] },
1035
- * ],
1036
- * });
1037
- */
1038
- registerComponent(registration: ComponentRegistration): void;
1039
- /**
1040
- * 按需加载配置
1041
- *
1042
- * 从注册的 Source 加载已注册 Keys 的配置值到内存中
1043
- *
1044
- * @param componentName - 可选,指定要加载的 Component 名称
1045
- *
1046
- * @example
1047
- * // 加载所有已注册的 Keys
1048
- * await config.load();
1049
- *
1050
- * // 只加载指定 Component 的 Keys
1051
- * await config.load("llm");
1052
- */
1053
- load(componentName?: string): Promise<void>;
1054
- /**
1055
- * 获取已注册的 Source 列表
1056
- */
1057
- getRegisteredSources(): ConfigSource[];
1058
- }
1059
- /**
1060
- * 服务配置接口
1061
- */
1062
- interface ServiceConfig {
1063
- /** 环境配置 */
1064
- environment?: {
1065
- name?: string;
1066
- version?: string;
1067
- };
1068
- /** 组件配置映射 */
1069
- components?: Record<string, ComponentConfigEntry>;
1070
- }
1071
- /**
1072
- * 组件配置项
1073
- */
1074
- interface ComponentConfigEntry {
1075
- /** 配置文件路径(可选) */
1076
- configPath?: string;
1077
- /** 环境变量前缀(可选) */
1078
- envPrefix?: string;
1079
- /** 直接配置对象(可选) */
1080
- config?: Record<string, unknown>;
1081
- /** 是否启用(可选,默认 true) */
1082
- enabled?: boolean;
1083
- }
1084
- /**
1085
- * 组件初始化选项(由 generateComponentOptions 生成)
1086
- */
1087
- interface GeneratedComponentOptions {
1088
- /** ConfigComponent 实例 */
1089
- configComponent: ConfigComponent;
1090
- /** 配置文件路径 */
1091
- configPath?: string;
1092
- /** 环境变量前缀 */
1093
- envPrefix?: string;
1094
- /** 直接配置对象 */
1095
- config?: Record<string, unknown>;
1096
- /** 允许的其他属性 */
1097
- [key: string]: unknown;
1098
- }
1099
- /**
1100
- * Environment 接口
1101
- *
1102
- * 定义 Agent 运行时的核心能力接口。
1103
- */
1104
- interface Environment {
1105
- /** 环境名称 */
1106
- readonly name: string;
1107
- /** 环境版本 */
1108
- readonly version: string;
1109
- /** 获取环境配置 */
1110
- getConfig(): EnvironmentConfig;
1111
- /**
1112
- * 注册组件
1113
- */
1114
- registerComponent(component: Component): void;
1115
- /**
1116
- * 注销组件
1117
- */
1118
- unregisterComponent(name: string): void;
1119
- /**
1120
- * 获取组件
1121
- */
1122
- getComponent<T extends Component>(name: string): T | undefined;
1123
- /**
1124
- * 列出所有组件
1125
- */
1126
- listComponents(): Component[];
1127
- /**
1128
- * 处理自然语言查询(核心入口)
1129
- *
1130
- * @param query 用户查询文本
1131
- * @param context 执行上下文(可选)
1132
- * @returns 完整的文本响应
1133
- */
1134
- handle_query(query: string, context?: AgentContext): Promise<string>;
1135
- /**
1136
- * 处理动作
1137
- */
1138
- handle_action(action: Action, context: Context): Promise<ToolResult>;
1139
- /**
1140
- * 订阅 EnvEvent(返回取消订阅函数)
1141
- */
1142
- subscribe(handler: EnvEventHandler): () => void;
1143
- /**
1144
- * 订阅指定类型事件
1145
- */
1146
- subscribeTo(eventType: string | string[], handler: EnvEventHandler): () => void;
1147
- /**
1148
- * 订阅所有事件(通配符)
1149
- */
1150
- subscribeAll(handler: EnvEventHandler): () => void;
1151
- /**
1152
- * 推送事件
1153
- *
1154
- * @param event EnvEvent 或 EnvEventInput(部分属性)
1155
- */
1156
- pushEnvEvent(event: EnvEvent | EnvEventInput): void;
1157
- /**
1158
- * 从配置文件加载服务配置
1159
- *
1160
- * @param configPath 配置文件路径(基于 XDG_DATA_HOME)
1161
- * @returns 解析后的服务配置对象
1162
- */
1163
- loadServiceConfig(configPath: string): Promise<ServiceConfig>;
1164
- /**
1165
- * 生成组件初始化选项
1166
- *
1167
- * 根据组件配置项生成可用于初始化的选项对象。
1168
- *
1169
- * @param componentName 组件名称
1170
- * @param configEntry 组件配置项
1171
- * @returns 生成的组件初始化选项
1172
- */
1173
- generateComponentOptions(componentName: string, configEntry: ComponentConfigEntry): GeneratedComponentOptions;
1174
- /**
1175
- * 注册组件并用配置初始化
1176
- *
1177
- * 便捷方法:注册组件并通过 ConfigComponent 初始化。
1178
- *
1179
- * @param component 要注册的组件实例
1180
- * @param configEntry 组件配置项
1181
- */
1182
- registerComponentWithConfig(component: Component, configEntry: ComponentConfigEntry): Promise<void>;
1183
- /**
1184
- * 从配置文件初始化整个环境
1185
- *
1186
- * 加载服务配置,注册并初始化所有配置的组件。
1187
- *
1188
- * @param configPath 配置文件路径(基于 XDG_DATA_HOME)
1189
- */
1190
- initFromConfig(configPath: string): Promise<void>;
1191
- }
1192
- /**
1193
- * Component 状态
1194
- */
1195
- type ComponentStatus = "created" | "initializing" | "running" | "stopping" | "stopped" | "error";
1196
- /**
1197
- * Component 配置
1198
- */
1199
- interface ComponentConfig {
1200
- name: string;
1201
- version: string;
1202
- enabled: boolean;
1203
- options?: Record<string, unknown>;
1204
- /**
1205
- * Environment 实例(可选)
1206
- *
1207
- * 推荐在 init 时接收 env 实例,以便:
1208
- * - 通过 env.getComponent() 获取其他组件
1209
- * - 通过 env.pushEnvEvent() 发布事件
1210
- * - 通过 env.handle_query() 处理查询
1211
- *
1212
- * 如果未提供,部分 Component 仍可正常工作(如测试场景)
1213
- *
1214
- * @example
1215
- * ```typescript
1216
- * async onInit(): Promise<void> {
1217
- * if (this.env) {
1218
- * const configComp = this.env.getComponent("config");
1219
- * }
1220
- * }
1221
- * ```
1222
- */
1223
- env?: Environment;
1224
- }
1225
- /**
1226
- * Component 路径声明
1227
- */
1228
- interface ComponentPaths {
1229
- base: "config" | "state" | "data" | "cache";
1230
- subPath: string;
1231
- isDirectory: boolean;
1232
- }
1233
- /**
1234
- * Component Schema(注册配置)
1235
- */
1236
- interface ComponentSchema {
1237
- /** Component 名称 */
1238
- name: string;
1239
- /** 配置 Schema(Zod) */
1240
- schema: ZodType3<unknown, ZodTypeDef2, unknown>;
1241
- /** 默认值(从 Schema 提取) */
1242
- defaults: Record<string, unknown>;
1243
- /** 路径声明 */
1244
- paths?: Record<string, ComponentPaths>;
1245
- /** 元信息 */
1246
- metadata?: {
1247
- description?: string;
1248
- version?: string;
1249
- author?: string;
1250
- };
1251
- }
1252
- /**
1253
- * Component 配置变更事件
1254
- */
1255
- interface ComponentConfigChangeEvent {
1256
- /** Component 名称 */
1257
- component: string;
1258
- /** 变更的配置键 */
1259
- key: string;
1260
- /** 旧值 */
1261
- oldValue: unknown;
1262
- /** 新值 */
1263
- newValue: unknown;
1264
- /** 是否持久化 */
1265
- persisted: boolean;
1266
- /** 时间戳 */
1267
- timestamp: number;
1268
- }
1269
- /**
1270
- * Component 配置监听回调
1271
- */
1272
- type ComponentWatchCallback = (event: ComponentConfigChangeEvent) => void | Promise<void>;
1273
- /**
1274
- * Component 基类接口
1275
- */
1276
- interface Component {
1277
- /** Component 名称 */
1278
- readonly name: string;
1279
- /** Component 版本 */
1280
- readonly version: string;
1281
- /** 获取状态 */
1282
- getStatus(): ComponentStatus;
1283
- /** 获取配置 */
1284
- getConfig(): ComponentConfig;
1285
- /** 初始化 */
1286
- init(config: ComponentConfig): Promise<void>;
1287
- /** 启动 */
1288
- start(): Promise<void>;
1289
- /** 停止 */
1290
- stop(): Promise<void>;
1291
- }
1292
- /**
1293
- * Component 基类实现
1294
- */
1295
- declare abstract class BaseComponent implements Component {
1296
- abstract readonly name: string;
1297
- abstract readonly version: string;
1298
- protected _status: ComponentStatus;
1299
- protected _enabled: boolean;
1300
- protected env: Environment;
1301
- /** Hook 管理器 - 子类初始化时由构造函数设置 */
1302
- readonly hookManager: HookManager;
1303
- constructor();
1304
- getStatus(): ComponentStatus;
1305
- getConfig(): ComponentConfig;
1306
- /**
1307
- * 检查 Environment 是否已初始化
1308
- */
1309
- protected isEnvInitialized(): boolean;
1310
- protected setStatus(status: ComponentStatus): void;
1311
- /**
1312
- * 获取 Environment 实例
1313
- */
1314
- protected getEnv(): Environment;
1315
- init(config?: ComponentConfig): Promise<void>;
1316
- start(): Promise<void>;
1317
- stop(): Promise<void>;
1318
- /**
1319
- * 子类可覆盖的钩子方法
1320
- */
1321
- protected onInit(): Promise<void>;
1322
- protected onStart(): Promise<void>;
1323
- protected onStop(): Promise<void>;
1324
- /**
1325
- * 注册 Hook
1326
- *
1327
- * @param hookPoint Hook 点名称
1328
- * @param hook Hook 实例
1329
- */
1330
- protected registerHook<T = unknown>(hookPoint: string, hook: Hook<T>): void;
1331
- /**
1332
- * 便捷方法:快速注册 Hook
1333
- */
1334
- protected addHook<T = unknown>(hookPoint: string, name: string, fn: HookFn<T>, priority?: number): void;
1335
- /**
1336
- * 便捷方法:按名称取消注册 Hook
1337
- */
1338
- protected removeHook(hookPoint: string, name: string): boolean;
1339
- /**
1340
- * 执行 Hook
1341
- */
1342
- protected executeHooks<T = unknown>(hookPoint: string, data: T, metadata?: Record<string, unknown>): Promise<void>;
1343
- /**
1344
- * 获取 ConfigComponent 实例
1345
- *
1346
- * 子类可使用此方法获取配置组件,支持热更新
1347
- */
1348
- protected getConfigComponent(): {
1349
- get(key: string): unknown;
1350
- } | undefined;
1351
- /**
1352
- * 动态获取运行时配置值
1353
- *
1354
- * 优先从 ConfigComponent 获取(支持热更新),否则返回默认值
1355
- * 适用于运行时可能变化的配置(如 API Keys、模型参数)
1356
- *
1357
- * @param key 配置键(支持点号分隔的路径,如 "llm.temperature")
1358
- * @param defaultValue 默认值
1359
- * @returns 配置值或默认值
1360
- *
1361
- * @example
1362
- * ```typescript
1363
- * // 获取 LLM 温度配置(可能支持热更新)
1364
- * const temperature = this.getRuntimeConfig("llm.temperature", 0.7);
1365
- *
1366
- * // 获取 API Key
1367
- * const apiKey = this.getRuntimeConfig<string>("llm.providers.openai.apiKey");
1368
- * ```
1369
- */
1370
- protected getRuntimeConfig<T>(key: string, defaultValue: T): T;
1371
- }
1372
- /**
1373
- * Checkpoint type
1374
- */
1375
- type CheckpointType = "compact" | "manual";
1376
- /**
1377
- * Checkpoint metadata (stored in Session.metadata)
1378
- */
1379
- interface CheckpointMeta {
1380
- id: string;
1381
- messageIndex: number;
1382
- title: string;
1383
- createdAt: number;
1384
- type: CheckpointType;
1385
- }
1386
- /**
1387
- * User Intent type - represents a user's intent extracted from conversation
1388
- */
1389
- type UserIntent = string;
1390
- /**
1391
- * Recent message for checkpoint
1392
- *
1393
- * Stores a simplified version of a message for context preservation
1394
- */
1395
- interface RecentMessage {
1396
- role: string;
1397
- content: string;
1398
- }
1399
- /**
1400
- * Complete checkpoint information (includes generated content)
1401
- */
1402
- interface SessionCheckpoint extends CheckpointMeta {
1403
- summary: string;
1404
- processKeyPoints: string[];
1405
- currentState: string;
1406
- nextSteps: string[];
1407
- messageCountBefore: number;
1408
- metadata?: Record<string, unknown>;
1409
- /** User intents extracted from the conversation */
1410
- userIntents: UserIntent[];
1411
- /**
1412
- * Recent messages preserved from the compacted conversation
1413
- *
1414
- * Contains the last N turns of user query + assistant text response
1415
- * (excluding tool calls and tool results).
1416
- * This allows the checkpoint to serve as a fresh history context.
1417
- *
1418
- * Format: [user, assistant, user, assistant, ...] from most recent
1419
- */
1420
- recentMessages?: RecentMessage[];
1421
- }
1422
- /**
1423
- * Checkpoints metadata in session
1424
- */
1425
- interface SessionCheckpointsMeta {
1426
- latestCheckpointId?: string;
1427
- checkpoints: CheckpointMeta[];
1428
- }
1429
- /**
1430
- * Session entity
1431
- */
1432
- interface Session {
1433
- id: string;
1434
- title: string;
1435
- directory: string;
1436
- parentID?: string;
1437
- createdAt: number;
1438
- updatedAt: number;
1439
- messageCount: number;
1440
- metadata?: SessionMetadata;
1441
- }
1442
- /**
1443
- * Session metadata
1444
- */
1445
- interface SessionMetadata extends Record<string, unknown> {
1446
- /** Total number of messages in the session */
1447
- messageCount?: number;
1448
- checkpoints?: SessionCheckpointsMeta;
1449
- checkpointDetails?: Record<string, SessionCheckpoint>;
1450
- }
1451
- /**
1452
- * Session message
1453
- */
1454
- interface SessionMessage {
1455
- id: string;
1456
- sessionID: string;
1457
- role: Role;
1458
- content: string;
1459
- timestamp: number;
1460
- parts?: MessagePart[];
1461
- /** Whether the message has been archived (compacted) */
1462
- isArchived?: boolean;
1463
- /** Timestamp when the message was archived */
1464
- archivedAt?: number;
1465
- /** Checkpoint ID this message belongs to */
1466
- checkpointId?: string;
1467
- /** Message metadata (includes checkpoint info if this is a checkpoint message) */
1468
- metadata?: MessageMetadata;
1469
- }
1470
- /**
1471
- * Message metadata
1472
- */
1473
- interface MessageMetadata extends Record<string, unknown> {
1474
- /** 消息类型标识,用于过滤和分类 */
1475
- type?: "tool_call" | "tool_result" | "checkpoint" | "user_intent" | "workflow.node.start" | "workflow.node.interrupt" | "workflow.node.end" | "workflow.node.resume";
1476
- isCheckpoint?: boolean;
1477
- checkpointId?: string;
1478
- checkpointMeta?: SessionCheckpoint;
1479
- /** Workflow node ID (for workflow.node.* messages) */
1480
- workflowNodeId?: string;
1481
- /** Workflow node type (for workflow.node.* messages) */
1482
- workflowNodeType?: string;
1483
- /** Agent session ID (for agent nodes in workflow) */
1484
- agentSessionId?: string;
1485
- /** User response (for workflow.node.resume messages) */
1486
- response?: string;
1487
- /** Success flag (for workflow.node.end messages) */
1488
- success?: boolean;
1489
- }
1490
- /**
1491
- * Message role
1492
- */
1493
- type Role = "user" | "assistant" | "system" | "tool" | "workflow.node.start" | "workflow.node.interrupt" | "workflow.node.end" | "workflow.node.resume";
1494
- /**
1495
- * Message part
1496
- */
1497
- type MessagePart = SessionPart;
1498
- /**
1499
- * Text part - plain text content
1500
- */
1501
- interface TextPart {
1502
- type: "text";
1503
- content: string;
1504
- /** If true, this part was generated by the system (e.g., auto-summary) */
1505
- synthetic?: boolean;
1506
- /** If true, this part should be ignored (e.g., replaced by reasoning) */
1507
- ignored?: boolean;
1508
- }
1509
- /**
1510
- * Tool call part - represents a tool invocation
1511
- */
1512
- interface ToolCallPart {
1513
- type: "tool-call";
1514
- /** AI SDK standard field name */
1515
- toolCallId: string;
1516
- toolName: string;
1517
- /** Tool arguments - can be string (JSON) or object */
1518
- arguments: string | Record<string, unknown>;
1519
- state: "pending" | "running";
1520
- }
1521
- /**
1522
- * Tool result part - represents the result of a tool execution
1523
- */
1524
- interface ToolResultPart {
1525
- type: "tool-result";
1526
- toolCallId: string;
1527
- toolName: string;
1528
- output: string;
1529
- error?: string;
1530
- state: "completed" | "error";
1531
- }
1532
- /**
1533
- * Reasoning part - AI thinking/thought content
1534
- */
1535
- interface ReasoningPart {
1536
- type: "reasoning";
1537
- /** Reasoning content */
1538
- content: string;
1539
- /** Reasoning type (for different models) */
1540
- reasoningType?: "core" | "effort" | "summary";
1541
- /** State */
1542
- state?: "thinking" | "completed";
1543
- /** Whether to collapse by default (like AI SDK default) */
1544
- isCollapsed?: boolean;
1545
- /** Metadata */
1546
- metadata?: {
1547
- tokenCount?: number;
1548
- time?: {
1549
- start: number;
1550
- end?: number;
1551
- };
1552
- };
1553
- }
1554
- /**
1555
- * File part - file attachment
1556
- */
1557
- interface FilePart {
1558
- type: "file";
1559
- mime: string;
1560
- url: string;
1561
- filename?: string;
1562
- }
1563
- /**
1564
- * Checkpoint part - compaction checkpoint marker
1565
- *
1566
- * Represents a checkpoint message in the conversation history.
1567
- * This is stored as a user role message with markdown content summarizing
1568
- * the compacted conversation segment.
1569
- */
1570
- interface CheckpointPart {
1571
- type: "checkpoint";
1572
- /** Checkpoint ID reference */
1573
- checkpointId: string;
1574
- /** Markdown content summarizing the checkpoint */
1575
- content: string;
1576
- /** Title of the checkpoint */
1577
- title?: string;
1578
- /** Process key points */
1579
- processKeyPoints?: string[];
1580
- /** Current state description */
1581
- currentState?: string;
1582
- /** Next steps */
1583
- nextSteps?: string[];
1584
- /** Number of messages that were compacted */
1585
- messageCountBefore?: number;
1586
- /** Creation timestamp */
1587
- createdAt?: number;
1588
- }
1589
- /**
1590
- * Union type for all Session Part types
1591
- */
1592
- type SessionPart = TextPart | ToolCallPart | ToolResultPart | ReasoningPart | FilePart | CheckpointPart | WorkflowNodeStartPart | WorkflowNodeInterruptPart | WorkflowNodeEndPart | WorkflowNodeResumePart;
1593
- /**
1594
- * workflow.node.start 消息 part (对应 tool-call)
1595
- */
1596
- interface WorkflowNodeStartPart {
1597
- type: "workflow-node-start";
1598
- nodeId: string;
1599
- nodeType: string;
1600
- input?: unknown;
1601
- startTime: number;
1602
- /** Agent session ID (only for agent nodes) */
1603
- agentSessionId?: string;
1604
- }
1605
- /**
1606
- * workflow.node.interrupt 消息 part
1607
- */
1608
- interface WorkflowNodeInterruptPart {
1609
- type: "workflow-node-interrupt";
1610
- nodeId: string;
1611
- nodeType: string;
1612
- query: string;
1613
- options?: string[];
1614
- timestamp: number;
1615
- /** Agent session ID (only for agent nodes) */
1616
- agentSessionId?: string;
1617
- }
1618
- /**
1619
- * workflow.node.end 消息 part (对应 tool-result)
1620
- */
1621
- interface WorkflowNodeEndPart {
1622
- type: "workflow-node-end";
1623
- nodeId: string;
1624
- nodeType: string;
1625
- output?: unknown;
1626
- error?: string;
1627
- durationMs: number;
1628
- /** Agent session ID (only for agent nodes) */
1629
- agentSessionId?: string;
1630
- }
1631
- /**
1632
- * workflow.node.resume 消息 part
1633
- */
1634
- interface WorkflowNodeResumePart {
1635
- type: "workflow-node-resume";
1636
- nodeId: string;
1637
- response: string;
1638
- timestamp: number;
1639
- /** Agent session ID (only for agent nodes) */
1640
- agentSessionId?: string;
1641
- }
1642
- /**
1643
- * Options for creating a session
1644
- */
1645
- interface CreateSessionOptions {
1646
- /** Custom session ID (optional, will be generated if not provided) */
1647
- id?: string;
1648
- title?: string;
1649
- directory?: string;
1650
- parentID?: string;
1651
- metadata?: Record<string, unknown>;
1652
- hooks?: SessionHooksConfig;
1653
- }
1654
- /**
1655
- * Options for updating a session
1656
- */
1657
- interface UpdateSessionOptions {
1658
- title?: string;
1659
- metadata?: Record<string, unknown>;
1660
- }
1661
- /**
1662
- * Options for listing sessions
1663
- */
1664
- interface ListSessionsOptions {
1665
- filter?: {
1666
- metadata?: Record<string, unknown>;
1667
- startTime?: number;
1668
- endTime?: number;
1669
- };
1670
- sort?: {
1671
- field: "updatedAt" | "createdAt" | "title";
1672
- order: "asc" | "desc";
1673
- };
1674
- offset?: number;
1675
- limit?: number;
1676
- }
1677
- /**
1678
- * Options for adding a message
1679
- */
1680
- interface AddMessageOptions {
1681
- role: Role;
1682
- content: string;
1683
- parts?: MessagePart[];
1684
- metadata?: MessageMetadata;
1685
- }
1686
- /**
1687
- * Options for compact operation
1688
- */
1689
- interface CompactOptions {
1690
- /** User-provided summary hint for checkpoint generation */
1691
- summary?: string;
1692
- /** User-provided process key points hint */
1693
- processKeyPoints?: string[];
1694
- /** User-provided current state hint */
1695
- currentState?: string;
1696
- /** User-provided next steps hint */
1697
- nextSteps?: string[];
1698
- /** Whether this is auto-triggered compact */
1699
- auto?: boolean;
1700
- /**
1701
- * Scenario hint for guiding checkpoint generation
1702
- *
1703
- * A natural language description that provides context about the current scenario.
1704
- * This helps the SummaryAgent generate more relevant checkpoints based on the specific
1705
- * situation. Examples:
1706
- * - "Task execution in progress: implementing feature X, current working directory is /path/to/project"
1707
- * - "Bug investigation: analyzing crash dump, current hypothesis is memory corruption"
1708
- * - "Code review session: reviewing PR #123, focus on security implications"
1709
- *
1710
- * When provided, this will be prepended to the system prompt to guide the checkpoint
1711
- * generation with scenario-specific emphasis.
1712
- */
1713
- scenarioHint?: string;
1714
- }
1715
- /**
1716
- * Result of compact operation
1717
- */
1718
- interface CompactResult {
1719
- checkpoint: SessionCheckpoint;
1720
- deletedMessageCount: number;
1721
- remainingMessageCount: number;
1722
- checkpointCount: number;
1723
- }
1724
- /**
1725
- * Preview of compact operation
1726
- */
1727
- interface CompactPreview {
1728
- messageCountToCompact: number;
1729
- estimatedCheckpointTokens: number;
1730
- wouldTrigger: boolean;
1731
- }
1732
- /**
1733
- * Options for getting session context
1734
- */
1735
- interface GetContextOptions {
1736
- /** Start from specified checkpoint */
1737
- fromCheckpoint?: string;
1738
- /** Start from latest checkpoint (default: true) */
1739
- fromLatestCheckpoint?: boolean;
1740
- /** Read full history (ignore checkpoints) */
1741
- fullHistory?: boolean;
1742
- /** Message limit */
1743
- messageLimit?: number;
1744
- /** Minimum user messages to include (ensures starting from user message boundary) */
1745
- minUserMessages?: number;
1746
- /** Include checkpoint details */
1747
- includeCheckpoints?: boolean;
1748
- }
1749
- /**
1750
- * Result of getting session context
1751
- */
1752
- interface GetContextResult {
1753
- session: Session;
1754
- checkpoints: SessionCheckpoint[];
1755
- startCheckpoint?: SessionCheckpoint;
1756
- messages: SessionMessage[];
1757
- totalMessageCount: number;
1758
- activeMessageCount: number;
1759
- archivedMessageCount: number;
1760
- estimatedTokens: number;
1761
- }
1762
- /**
1763
- * Session hook callback
1764
- */
1765
- type SessionHookCallback = (context?: any) => Promise<void>;
1766
- /**
1767
- * Session hook definition
1768
- */
1769
- interface SessionHook {
1770
- name: string;
1771
- before?: SessionHookCallback;
1772
- after?: SessionHookCallback;
1773
- }
1774
- /**
1775
- * Session hooks configuration
1776
- */
1777
- interface SessionHooksConfig {
1778
- [key: string]: SessionHook[];
1779
- }
1780
- /**
1781
- * Options for searching messages
1782
- */
1783
- interface SearchMessagesOptions {
1784
- /** Search query (supports AND/OR/NOT syntax) */
1785
- query: string;
1786
- /** Limit search to specific session ID */
1787
- sessionId?: string;
1788
- /** Maximum number of results per session */
1789
- limit?: number;
1790
- /** Maximum total results */
1791
- maxResults?: number;
1792
- /** Only search messages before this timestamp */
1793
- beforeTime?: number;
1794
- /** Only search messages after this timestamp */
1795
- afterTime?: number;
1796
- /** Include archived messages */
1797
- includeArchived?: boolean;
1798
- /** Include context (messages before/after matches) */
1799
- includeContext?: boolean;
1800
- /** Number of context lines before/after */
1801
- contextLines?: number;
1802
- }
1803
- /**
1804
- * A single message match
1805
- */
1806
- interface MessageMatch {
1807
- /** Message ID */
1808
- messageId: string;
1809
- /** Session ID */
1810
- sessionId: string;
1811
- /** Message role */
1812
- role: Role;
1813
- /** Message content */
1814
- content: string;
1815
- /** Message timestamp */
1816
- timestamp: number;
1817
- /** Context before the match (if enabled) */
1818
- contextBefore?: string;
1819
- /** Context after the match (if enabled) */
1820
- contextAfter?: string;
1821
- /** Match score (relevance) */
1822
- score?: number;
1823
- }
1824
- /**
1825
- * Search result aggregated by session
1826
- */
1827
- interface SearchResult {
1828
- /** Session ID */
1829
- sessionId: string;
1830
- /** Session title */
1831
- sessionTitle: string;
1832
- /** Session directory */
1833
- sessionDirectory: string;
1834
- /** Session update timestamp */
1835
- updatedAt: number;
1836
- /** Total message count in session */
1837
- messageCount: number;
1838
- /** Matching messages in this session */
1839
- matches: MessageMatch[];
1840
- }
1841
- /**
1842
- * SessionComponent
1843
- *
1844
- * Manages session lifecycle including:
1845
- * - Session CRUD operations
1846
- * - Message management
1847
- * - Active session tracking
1848
- */
1849
- declare class SessionComponent extends BaseComponent {
1850
- readonly name = "session";
1851
- readonly version = "1.1.0";
1852
- private config?;
1853
- private store?;
1854
- private activeSessionId?;
1855
- private hooksConfig;
1856
- /** ConfigComponent 用于配置管理 */
1857
- private configComponent?;
1858
- /** 配置变更 watcher 清理函数 */
1859
- private configWatcher?;
1860
- /** Summary Agent for checkpoint generation [new] */
1861
- private summaryAgent?;
1862
- /** PromptComponent reference for SummaryAgent */
1863
- private promptComponent?;
1864
- /** LLMComponent reference for SummaryAgent */
1865
- private llmComponent?;
1866
- constructor();
1867
- /**
1868
- * Initialize the component
1869
- *
1870
- * 配置加载优先级(从高到低):
1871
- * 1. Object - 直接传入的 config 对象
1872
- * 2. Env - 环境变量(通过 envPrefix 配置前缀)
1873
- * 3. File - 配置文件(通过 configPath 指定)
1874
- */
1875
- init(config?: ComponentConfig): Promise<void>;
1876
- /**
1877
- * 获取默认 session 数据库路径
1878
- */
1879
- private getDefaultSessionDbPath;
1880
- /**
1881
- * 注册配置到 ConfigComponent
1882
- *
1883
- * 配置加载顺序(优先级从低到高):
1884
- * 1. Defaults - 默认值(最低)
1885
- * 2. FileSource - 从配置文件加载
1886
- * 3. EnvSource - 从环境变量加载
1887
- * 4. config 对象 - 直接传入的配置(最高)
1888
- */
1889
- private registerConfig;
1890
- /**
1891
- * 构建最终配置对象
1892
- */
1893
- private buildConfig;
1894
- /**
1895
- * 将配置对象展平为点号路径
1896
- */
1897
- private flattenConfig;
1898
- /**
1899
- * 注册配置热更新监听
1900
- */
1901
- private registerConfigWatcher;
1902
- /**
1903
- * 处理配置变更
1904
- */
1905
- protected onConfigChange(event: {
1906
- key: string;
1907
- oldValue?: unknown;
1908
- newValue?: unknown;
1909
- }): void;
1910
- /**
1911
- * Start the component
1912
- */
1913
- onStart(): Promise<void>;
1914
- /**
1915
- * Stop the component
1916
- */
1917
- onStop(): Promise<void>;
1918
- /**
1919
- * Create a new session
1920
- */
1921
- create(options?: CreateSessionOptions): Promise<Session>;
1922
- /**
1923
- * Get a session by ID
1924
- */
1925
- get(id: string): Promise<Session | undefined>;
1926
- /**
1927
- * Get a session with full context (for Memory Agent)
1928
- */
1929
- getSession(id: string): Promise<{
1930
- sessionId: string;
1931
- title: string;
1932
- messages: any[];
1933
- } | null>;
1934
- /**
1935
- * Search sessions by query (for Memory Agent)
1936
- *
1937
- * Simple implementation: list all sessions and return them for the agent to filter
1938
- */
1939
- searchSessions(query: string, options?: {
1940
- session_id?: string;
1941
- limit?: number;
1942
- }): Promise<Array<{
1943
- sessionId: string;
1944
- title: string;
1945
- preview: string;
1946
- timestamp: number;
1947
- }>>;
1948
- /**
1949
- * List all sessions
1950
- */
1951
- list(options?: ListSessionsOptions): Promise<Session[]>;
1952
- /**
1953
- * Get total session count
1954
- */
1955
- getCount(): Promise<number>;
1956
- /**
1957
- * Update a session
1958
- */
1959
- update(id: string, updates: UpdateSessionOptions): Promise<boolean>;
1960
- /**
1961
- * Delete a session
1962
- */
1963
- delete(id: string): Promise<boolean>;
1964
- /**
1965
- * Get the current active session
1966
- */
1967
- getActiveSession(): Session | undefined;
1968
- /**
1969
- * Get the active session ID
1970
- */
1971
- getActiveSessionId(): string | undefined;
1972
- /**
1973
- * Set the active session
1974
- */
1975
- setActiveSession(id: string): Promise<boolean>;
1976
- /**
1977
- * Add a message to a session
1978
- */
1979
- addMessage(sessionId: string, message: AddMessageOptions): Promise<string | undefined>;
1980
- /**
1981
- * Get messages from a session
1982
- */
1983
- getMessages(sessionId: string, options?: {
1984
- offset?: number;
1985
- limit?: number;
1986
- }): Promise<SessionMessage[]>;
1987
- /**
1988
- * Get message count for a session
1989
- */
1990
- getMessageCount(sessionId: string, includeArchived?: boolean): Promise<number>;
1991
- /**
1992
- * Get indexes of all messages with the specified role
1993
- * @param sessionId - Session ID
1994
- * @param role - Role to filter by (e.g., "user", "assistant")
1995
- * @returns Array of message indexes (0-indexed, in chronological order)
1996
- */
1997
- getMessageIndexes(sessionId: string, role: string): Promise<number[]>;
1998
- private executeBeforeHooks;
1999
- private executeAfterHooks;
2000
- private generateTitle;
2001
- /**
2002
- * Set components for SummaryAgent
2003
- *
2004
- * Call this after initialization if you need compact functionality
2005
- */
2006
- setSummaryComponents(promptComponent: any, llmComponent: any): void;
2007
- /**
2008
- * 初始化 SummaryAgent(如未初始化)
2009
- */
2010
- private ensureSummaryAgent;
2011
- /**
2012
- * 生成场景化压缩提示 (Compact Hint)
2013
- *
2014
- * 两阶段自动压缩的第一阶段:
2015
- * 根据会话历史生成场景化的压缩提示
2016
- *
2017
- * @param sessionId 会话 ID
2018
- * @returns 生成的场景化提示
2019
- */
2020
- generateCompactHint(sessionId: string): Promise<string>;
2021
- /**
2022
- * Compact a session
2023
- *
2024
- * 1. Get messages from latest checkpoint to current
2025
- * 2. Call Summary Agent to generate checkpoint
2026
- * 3. Save checkpoint and archive messages
2027
- *
2028
- * 支持 scenarioHint 参数,用于指导不同场景下的压缩重点提取
2029
- */
2030
- compact(sessionId: string, options?: CompactOptions): Promise<CompactResult>;
2031
- /**
2032
- * Extract recent messages from the conversation for checkpoint context
2033
- *
2034
- * Extracts the last N turns of user query + assistant text response,
2035
- * excluding tool calls and tool results.
2036
- *
2037
- * @param messages - All messages in the conversation
2038
- * @param turnCount - Number of turns to extract (default: 2)
2039
- * @returns Array of recent messages formatted as { role, content }
2040
- */
2041
- private extractRecentMessages;
2042
- /**
2043
- * Preview compact operation
2044
- */
2045
- previewCompact(sessionId: string): Promise<CompactPreview>;
2046
- /**
2047
- * Get all checkpoints for a session
2048
- */
2049
- getCheckpoints(sessionId: string): Promise<SessionCheckpoint[]>;
2050
- /**
2051
- * Get a specific checkpoint
2052
- */
2053
- getCheckpoint(sessionId: string, checkpointId: string): Promise<SessionCheckpoint | undefined>;
2054
- /**
2055
- * Delete a checkpoint and restore archived messages
2056
- */
2057
- deleteCheckpoint(sessionId: string, checkpointId: string): Promise<boolean>;
2058
- /**
2059
- * Get session context
2060
- *
2061
- * Returns messages starting from the latest checkpoint by default
2062
- */
2063
- getContext(sessionId: string, options?: GetContextOptions): Promise<GetContextResult>;
2064
- /**
2065
- * Check if session needs compaction
2066
- */
2067
- shouldCompact(sessionId: string): Promise<boolean>;
2068
- /**
2069
- * Search messages across sessions
2070
- *
2071
- * Searches all messages matching the query, aggregated by session.
2072
- * Supports SQLite FTS5 for fast full-text search.
2073
- */
2074
- searchMessages(options: SearchMessagesOptions): Promise<SearchResult[]>;
2075
- /**
2076
- * Get latest checkpoint from session
2077
- */
2078
- private getLatestCheckpoint;
2079
- /**
2080
- * Create checkpoint message (user role)
2081
- *
2082
- * Generates a markdown-formatted checkpoint summary as a user message,
2083
- * allowing it to appear in the message list and provide context for
2084
- * subsequent LLM calls.
2085
- */
2086
- private createCheckpointMessage;
2087
- }
2088
- declare const RunStatusSchema: unknown;
2089
- type RunStatus = z4.infer<typeof RunStatusSchema>;
2090
- declare const NodeStatusSchema: unknown;
2091
- type NodeStatus = z4.infer<typeof NodeStatusSchema>;
2092
- interface RunOptions {
2093
- input?: Record<string, any>;
2094
- debug?: boolean;
2095
- parallelLimit?: number | null;
2096
- timeout?: number | null;
2097
- /** @deprecated No-op: workflow always waits for completion */
2098
- sync?: boolean;
2099
- }
2100
- interface RunResult {
2101
- runId: string;
2102
- /** Session ID (workflow_{runId} format) - useful for CLI resume */
2103
- sessionId?: string;
2104
- status: RunStatus;
2105
- output?: Record<string, any>;
2106
- error?: string;
2107
- durationMs?: number;
2108
- /** Pending node ID (when status is 'paused') */
2109
- pendingNodeId?: string;
2110
- /** Query from ask_user (when status is 'paused') */
2111
- query?: string;
2112
- /** Agent sub-session ID (for resuming agent nodes) */
2113
- agentSessionId?: string;
2114
- }
2115
- /**
2116
- * 节点执行上下文
2117
- *
2118
- * 扩展后包含:
2119
- * - sessionId: Session ID,用于消息持久化
2120
- * - askUser(): 方法,让节点可以请求用户输入
2121
- */
2122
- interface NodeExecutionContext {
2123
- runId: string;
2124
- sessionId: string;
2125
- workflowName: string;
2126
- nodeId: string;
2127
- input: unknown;
2128
- previousOutputs: Map<string, unknown>;
2129
- nodeOutputs: Map<string, unknown>;
2130
- config: Record<string, unknown>;
2131
- debug: boolean;
2132
- eventBus: EventBus;
2133
- workflowHistory?: Array<{
2134
- role: "user" | "assistant" | "tool";
2135
- content: string;
2136
- toolCallId?: string;
2137
- toolName?: string;
2138
- nodeId?: string;
2139
- }>;
2140
- sessionComponent?: SessionComponent;
2141
- agentSessionId?: string;
2142
- workflowInput?: Record<string, unknown>;
2143
- /**
2144
- * 请求用户输入
2145
- *
2146
- * 调用此方法会抛出 AskUserError,引擎捕获后会暂停 workflow
2147
- *
2148
- * @param query - 向用户询问的问题
2149
- * @throws AskUserError - 总是抛出此异常
2150
- */
2151
- askUser(query: string): never;
2152
- }
2153
- interface NodeExecutionResult {
2154
- success?: boolean;
2155
- output?: any;
2156
- error?: string | Error;
2157
- duration?: number;
2158
- durationMs?: number;
2159
- metadata?: Record<string, unknown>;
2160
- }
2161
- declare const RetryConfigSchema: unknown;
2162
- type RetryConfig = z5.infer<typeof RetryConfigSchema>;
2163
- declare const NodeDefinitionSchema: unknown;
2164
- type NodeDefinition = z5.infer<typeof NodeDefinitionSchema>;
2165
- /**
2166
- * Node interface - base interface for all workflow nodes
2167
- */
2168
- interface Node {
2169
- /** Node type identifier */
2170
- readonly type: string;
2171
- /** Node unique identifier */
2172
- readonly id: string;
2173
- /** Execute the node with the given context */
2174
- execute(context: NodeExecutionContext): Promise<NodeExecutionResult>;
2175
- }
2176
- declare const WorkflowConfigSchema: unknown;
2177
- type WorkflowConfig = z5.infer<typeof WorkflowConfigSchema>;
2178
- declare const WorkflowMetadataSchema: unknown;
2179
- type WorkflowMetadata = z5.infer<typeof WorkflowMetadataSchema>;
2180
- declare const WorkflowDefinitionSchema: unknown;
2181
- type WorkflowDefinition = z5.infer<typeof WorkflowDefinitionSchema>;
2182
- interface WorkflowDefinitionExtended extends WorkflowDefinition {
2183
- computedEntry: string[];
2184
- nodeMap: Map<string, NodeDefinition>;
2185
- topologicalOrder: string[];
2186
- }
2187
- interface Workflow {
2188
- id: string;
2189
- name: string;
2190
- version: string;
2191
- description?: string;
2192
- definition: WorkflowDefinition;
2193
- config: WorkflowConfig;
2194
- metadata: WorkflowMetadata;
2195
- tags: string[];
2196
- createdAt: Date;
2197
- updatedAt: Date;
2198
- }
2199
- /**
2200
- * DAG Analysis Result
2201
- */
2202
- interface DAGAnalysis {
2203
- /** 入口节点(无依赖) */
2204
- entryNodes: string[];
2205
- /** 出口节点(无下游) */
2206
- exitNodes: string[];
2207
- /** 按层级组织的节点,用于并行执行 */
2208
- levels: string[][];
2209
- /** 每个节点的依赖 */
2210
- dependencies: Map<string, string[]>;
2211
- /** 每个节点的下游 */
2212
- dependents: Map<string, string[]>;
2213
- /** 关键路径 */
2214
- criticalPath: string[];
2215
- }
2216
- /**
2217
- * DAG Manager
2218
- *
2219
- * Manages Directed Acyclic Graph (DAG) operations for workflow execution.
2220
- * Provides analysis, topological sorting, and validation of workflow structures.
2221
- */
2222
- declare class DAGManager {
2223
- private workflow;
2224
- private nodeMap;
2225
- private extendedDefinition;
2226
- private cachedAnalysis;
2227
- constructor(workflow: WorkflowDefinition);
2228
- /**
2229
- * Get extended workflow definition with computed properties
2230
- */
2231
- getExtendedDefinition(): WorkflowDefinitionExtended;
2232
- /**
2233
- * Analyze the DAG structure
2234
- */
2235
- analyze(): DAGAnalysis;
2236
- /**
2237
- * Build a map of node dependencies
2238
- */
2239
- private buildDependenciesMap;
2240
- /**
2241
- * Build a map of node dependents (reverse of dependencies)
2242
- */
2243
- private buildDependentsMap;
2244
- /**
2245
- * Find entry nodes (nodes with no dependencies)
2246
- */
2247
- private findEntryNodes;
2248
- /**
2249
- * Find exit nodes (nodes with no dependents)
2250
- */
2251
- private findExitNodes;
2252
- /**
2253
- * Compute levels for parallel execution
2254
- * Nodes at the same level can be executed in parallel
2255
- */
2256
- private computeLevels;
2257
- /**
2258
- * Find critical path (longest path through the DAG)
2259
- */
2260
- private findCriticalPath;
2261
- /**
2262
- * Get topological order using Kahn's algorithm
2263
- */
2264
- getTopologicalOrder(): string[];
2265
- /**
2266
- * Get nodes that are ready to execute (dependencies met and not completed)
2267
- */
2268
- getReadyNodes(completedNodes: Set<string>): string[];
2269
- /**
2270
- * Check if all dependencies for a node are completed
2271
- */
2272
- areDependenciesMet(nodeId: string, completedNodes: Set<string>): boolean;
2273
- /**
2274
- * Check if the workflow contains a cycle
2275
- */
2276
- isCyclic(): boolean;
2277
- /**
2278
- * Internal topological sort that detects cycles
2279
- */
2280
- private getTopologicalOrderInternal;
2281
- /**
2282
- * Validate the workflow
2283
- */
2284
- validate(): {
2285
- valid: boolean;
2286
- errors: string[];
2287
- };
2288
- /**
2289
- * Add a new node to the workflow dynamically
2290
- *
2291
- * @param node - The node definition to add
2292
- * @throws Error if a node with the same ID already exists
2293
- * @throws Error if the node depends on a non-existent node
2294
- * @throws Error if adding this node would create a cycle
2295
- */
2296
- addNode(node: NodeDefinition): void;
2297
- /**
2298
- * Remove a node from the workflow dynamically
2299
- *
2300
- * @param nodeId - The ID of the node to remove
2301
- * @throws Error if the node doesn't exist
2302
- * @throws Error if other nodes depend on this node
2303
- */
2304
- removeNode(nodeId: string): void;
2305
- /**
2306
- * Get direct dependents of a node (nodes that depend on this node)
2307
- */
2308
- getDependents(nodeId: string): string[];
2309
- /**
2310
- * Get the workflow definition (current state)
2311
- */
2312
- getDefinition(): WorkflowDefinition;
2313
- /**
2314
- * Get a node by ID
2315
- */
2316
- getNode(nodeId: string): NodeDefinition | undefined;
2317
- /**
2318
- * Get all node IDs
2319
- */
2320
- getNodeIds(): string[];
2321
- /**
2322
- * Get the number of nodes in the workflow
2323
- */
2324
- getNodeCount(): number;
2325
- }
2326
- /**
2327
- * Scheduler Options
2328
- */
2329
- interface SchedulerOptions {
2330
- /** Maximum number of nodes that can run in parallel. null = unlimited */
2331
- parallelLimit: number | null;
2332
- }
2333
- /**
2334
- * Scheduler State
2335
- */
2336
- interface SchedulerState {
2337
- /** Nodes that have not been started yet */
2338
- pending: string[];
2339
- /** Nodes that are ready to execute (dependencies met, not started) */
2340
- ready: string[];
2341
- /** Nodes that are currently running */
2342
- running: string[];
2343
- /** Nodes that have completed successfully */
2344
- completed: string[];
2345
- /** Nodes that have failed */
2346
- failed: string[];
2347
- /** Nodes that were skipped (not executed) */
2348
- skipped: string[];
2349
- }
2350
- /**
2351
- * Scheduler
2352
- *
2353
- * Determines which nodes are ready to execute based on:
2354
- * - DAG dependencies
2355
- * - Parallel execution limit
2356
- * - Node completion status
2357
- *
2358
- * The scheduler tracks the state of all nodes and manages the execution queue.
2359
- */
2360
- declare class Scheduler {
2361
- private dagManager;
2362
- private options;
2363
- private pending;
2364
- private ready;
2365
- private running;
2366
- private completed;
2367
- private failed;
2368
- private skipped;
2369
- /**
2370
- * Create a new Scheduler
2371
- * @param dagManager - The DAG manager for the workflow
2372
- * @param options - Scheduler options
2373
- */
2374
- constructor(dagManager: DAGManager, options?: Partial<SchedulerOptions>);
2375
- /**
2376
- * Get nodes that are ready to execute
2377
- * Ready nodes are those whose dependencies are met and are not already running/completed/failed
2378
- * @param completedNodes - Set of completed node IDs (external tracking)
2379
- */
2380
- getReadyNodes(completedNodes: Set<string>): string[];
2381
- /**
2382
- * Get the number of currently running nodes
2383
- */
2384
- getRunningCount(): number;
2385
- /**
2386
- * Check if more nodes can be started based on the parallel limit
2387
- */
2388
- canStartMore(): boolean;
2389
- /**
2390
- * Mark a node as started
2391
- * @param nodeId - The node ID
2392
- */
2393
- markStarted(nodeId: string): void;
2394
- /**
2395
- * Check if a node is currently running
2396
- * @param nodeId - The node ID
2397
- */
2398
- isRunning(nodeId: string): boolean;
2399
- /**
2400
- * Check if a node has completed
2401
- * @param nodeId - The node ID
2402
- */
2403
- isCompleted(nodeId: string): boolean;
2404
- /**
2405
- * Check if a node has failed
2406
- * @param nodeId - The node ID
2407
- */
2408
- isFailed(nodeId: string): boolean;
2409
- /**
2410
- * Check if a node is in pending state
2411
- * @param nodeId - The node ID
2412
- */
2413
- isPending(nodeId: string): boolean;
2414
- /**
2415
- * Check if a node is ready to execute
2416
- * @param nodeId - The node ID
2417
- */
2418
- isReady(nodeId: string): boolean;
2419
- /**
2420
- * Mark a node as completed successfully
2421
- * @param nodeId - The node ID
2422
- */
2423
- markCompleted(nodeId: string): void;
2424
- /**
2425
- * Mark a node as failed
2426
- * @param nodeId - The node ID
2427
- */
2428
- markFailed(nodeId: string): void;
2429
- /**
2430
- * Mark a node as skipped (not executed)
2431
- * @param nodeId - The node ID
2432
- */
2433
- markSkipped(nodeId: string): void;
2434
- /**
2435
- * Reset the scheduler state
2436
- * Clears all running, completed, failed, and skipped nodes
2437
- */
2438
- reset(): void;
2439
- /**
2440
- * Get the current state of the scheduler
2441
- */
2442
- getState(): SchedulerState;
2443
- /**
2444
- * Update the ready set based on completed nodes
2445
- */
2446
- private updateReadyNodes;
2447
- /**
2448
- * Get the parallel limit
2449
- */
2450
- getParallelLimit(): number | null;
2451
- /**
2452
- * Update the parallel limit
2453
- * @param limit - New parallel limit (null for unlimited)
2454
- */
2455
- setParallelLimit(limit: number | null): void;
2456
- }
2457
- /**
2458
- * Tool Registry interface for looking up tools
2459
- * Supports both the full ToolRegistration and simplified Tool interface
2460
- */
2461
- interface ToolRegistry {
2462
- getTool?(name: string): ToolRegistration2 | undefined;
2463
- getToolByName?(name: string): Tool2 | undefined;
2464
- hasTool?(name: string): boolean;
2465
- }
2466
- /**
2467
- * Tool Registration interface (from ToolComponent)
2468
- */
2469
- interface ToolRegistration2 {
2470
- tool: Tool2;
2471
- enabled: boolean;
2472
- source?: string;
2473
- }
2474
- /**
2475
- * Tool interface for execution
2476
- */
2477
- interface Tool2 {
2478
- name: string;
2479
- execute(input: any, context?: any): Promise<any>;
2480
- }
2481
- /**
2482
- * Skill Registry interface for looking up skills
2483
- */
2484
- interface SkillRegistry {
2485
- getSkill(name: string): Skill | undefined;
2486
- hasSkill(name: string): boolean;
2487
- }
2488
- /**
2489
- * Skill interface for invocation
2490
- */
2491
- interface Skill {
2492
- name: string;
2493
- invoke(input: any, context: any): Promise<any>;
2494
- }
2495
- /**
2496
- * Agent 注册配置
2497
- */
2498
- interface AgentRegistrationConfig {
2499
- /** Agent 类型 */
2500
- type?: string;
2501
- /** 系统提示词 */
2502
- systemPrompt?: string;
2503
- /** 模型名称 */
2504
- model?: string;
2505
- /** 最大迭代次数 */
2506
- maxIterations?: number;
2507
- /** 允许的工具列表 */
2508
- allowedTools?: string[];
2509
- /** 禁止的工具列表 */
2510
- deniedTools?: string[];
2511
- }
2512
- /**
2513
- * AgentRunner 接口
2514
- *
2515
- * 用于运行 AI Agent 的接口
2516
- */
2517
- interface AgentRunner {
2518
- /**
2519
- * 运行 Agent
2520
- * @param config Agent 配置
2521
- * @param resumeOptions 可选的恢复选项(用于恢复暂停的 agent)
2522
- * @returns Agent 执行结果
2523
- */
2524
- run(config: AgentConfig, resumeOptions?: {
2525
- userQuery?: string;
2526
- agentSessionId?: string;
2527
- }): Promise<AgentResult>;
2528
- /**
2529
- * 恢复暂停的 Agent
2530
- *
2531
- * @param agentSessionId Agent session ID
2532
- * @param userQuery 用户的响应
2533
- * @param config 原始的 agent 配置
2534
- * @returns Agent 执行结果
2535
- */
2536
- resumeAgent?(agentSessionId: string, userQuery: string, config: AgentConfig): Promise<AgentResult>;
2537
- /**
2538
- * 获取当前 agent session ID
2539
- */
2540
- getCurrentAgentSessionId?(): string | undefined;
2541
- /**
2542
- * 设置 SessionComponent
2543
- */
2544
- setSessionComponent?(sessionComponent: SessionComponent): void;
2545
- /**
2546
- * 获取待恢复的 session 信息
2547
- */
2548
- getPendingSession?(agentSessionId: string): {
2549
- agentSessionId: string;
2550
- nodeId: string;
2551
- runId: string;
2552
- createdAt: number;
2553
- } | undefined;
2554
- /**
2555
- * 注册 Agent(如果不存在)
2556
- */
2557
- registerAgent?(name: string, config: AgentRegistrationConfig): void;
2558
- /**
2559
- * 检查 Agent 是否已注册
2560
- */
2561
- hasAgent?(name: string): boolean;
2562
- }
2563
- /**
2564
- * Agent 配置
2565
- */
2566
- interface AgentConfig {
2567
- /** Agent 类型 */
2568
- type: string;
2569
- /** Prompt(任务描述) */
2570
- prompt: string;
2571
- /** 可选配置 */
2572
- options?: {
2573
- /** 超时时间(毫秒) */
2574
- timeout?: number;
2575
- /** 模型名称 */
2576
- model?: string;
2577
- /** 允许的工具列表(用于限制 agent 可用的工具) */
2578
- allowedTools?: string[];
2579
- /** 拒绝的工具列表 */
2580
- deniedTools?: string[];
2581
- };
2582
- /** Workflow 历史消息(来自前置 agent 节点) */
2583
- workflowHistory?: Array<{
2584
- role: "user" | "assistant" | "tool";
2585
- content: string;
2586
- toolCallId?: string;
2587
- toolName?: string;
2588
- nodeId?: string;
2589
- }>;
2590
- /** 节点 ID(用于 history 标记) */
2591
- nodeId?: string;
2592
- /** Agent sub-session ID(用于 HiL resume) */
2593
- agentSessionId?: string;
2594
- }
2595
- /**
2596
- * Agent 执行结果
2597
- */
2598
- interface AgentResult {
2599
- /** Agent 输出 */
2600
- output: unknown;
2601
- /** 执行元数据 */
2602
- metadata?: {
2603
- /** 消耗的 token 数量 */
2604
- tokens?: number;
2605
- /** 执行耗时(毫秒) */
2606
- duration?: number;
2607
- /** 其他元数据 */
2608
- [key: string]: unknown;
2609
- };
2610
- /** 生成的消息列表(用于 workflow history 累积) */
2611
- messages?: Array<{
2612
- role: "user" | "assistant" | "tool";
2613
- content: string;
2614
- toolCallId?: string;
2615
- toolName?: string;
2616
- nodeId?: string;
2617
- }>;
2618
- }
2619
- import { ModelMessage as ModelMessage2 } from "ai";
2620
- import { z as z7 } from "zod";
2621
- /**
2622
- * AgentComponent 配置 Schema
2623
- */
2624
- declare const AgentComponentConfigSchema: unknown;
2625
- type AgentComponentConfig = z7.infer<typeof AgentComponentConfigSchema>;
2626
- /**
2627
- * AgentComponent
2628
- *
2629
- * 提供 Agent 执行能力和 Hook 扩展机制
2630
- */
2631
- declare class AgentComponent extends BaseComponent {
2632
- readonly name = "agent";
2633
- readonly version = "1.0.0";
2634
- private agents;
2635
- private config;
2636
- private llmComponent;
2637
- private toolComponent;
2638
- private aborted;
2639
- private abortControllers;
2640
- private defaultTools;
2641
- private doomLoopCaches;
2642
- /** ConfigComponent 用于配置管理 */
2643
- private configComponent?;
2644
- /** 配置变更 watcher 清理函数 */
2645
- private configWatcher?;
2646
- /** Session 消息转换器 */
2647
- private messageConverter;
2648
- /** 构造函数传入的配置(最高优先级) */
2649
- private _constructorConfig?;
2650
- /** Run ID 计数器(用于生成唯一的 runId) */
2651
- private runCounter;
2652
- constructor(options?: {
2653
- config?: Partial<AgentComponentConfig>;
2654
- });
2655
- /**
2656
- * 初始化组件
2657
- *
2658
- * 配置加载优先级(从高到低):
2659
- * 1. Object - 直接传入的 config 对象
2660
- * 2. Env - 环境变量(通过 envPrefix 配置前缀)
2661
- * 3. File - 配置文件(通过 configPath 指定)
2662
- */
2663
- init(config: ComponentConfig): Promise<void>;
2664
- /**
2665
- * 注册配置到 ConfigComponent
2666
- *
2667
- * 配置加载顺序(优先级从低到高):
2668
- * 1. Defaults - 默认值(最低)
2669
- * 2. FileSource - 从配置文件加载
2670
- * 3. EnvSource - 从环境变量加载
2671
- * 4. config 对象 - 直接传入的配置(最高)
2672
- */
2673
- private registerConfig;
2674
- /**
2675
- * 将配置对象展平为点号路径
2676
- */
2677
- private flattenConfig;
2678
- /**
2679
- * 注册配置热更新监听
2680
- */
2681
- private registerConfigWatcher;
2682
- /**
2683
- * 处理配置变更
2684
- */
2685
- protected onConfigChange(event: {
2686
- key: string;
2687
- oldValue?: unknown;
2688
- newValue?: unknown;
2689
- }): void;
2690
- /**
2691
- * 组件停止时的清理逻辑
2692
- *
2693
- * 清理内容:
2694
- * 1. 终止所有正在运行的 Agent(调用 abort() 以中断 LLM 调用)
2695
- * 2. 清空 AbortController 注册表
2696
- * 3. 清空 Doom Loop 缓存
2697
- * 4. 取消配置变更监听
2698
- * 5. 清空 Agent 注册表
2699
- */
2700
- protected onStop(): Promise<void>;
2701
- /**
2702
- * 刷新依赖组件引用
2703
- *
2704
- * 当组件被添加到 Environment 后调用,以确保获取到最新的组件引用
2705
- */
2706
- refreshDependencies(): void;
2707
- /**
2708
- * 获取 Agent 实例
2709
- */
2710
- getAgent(agentName: string): AgentInstance | undefined;
2711
- /**
2712
- * 获取所有 Agent 实例
2713
- */
2714
- listAgents(): AgentInstance[];
2715
- /**
2716
- * Add placeholder tool results for remaining unprocessed tool calls
2717
- *
2718
- * This ensures that the message history maintains a 1:1 correspondence
2719
- * between tool-calls and tool-results, which is required by AI SDK v6.
2720
- *
2721
- * @param ctx - Hook context containing messages
2722
- * @param allToolCalls - All tool calls from the LLM response
2723
- * @param processedCount - Number of tool calls that have been processed
2724
- * @param reason - Reason for the abort/interruption
2725
- */
2726
- private addRemainingToolResults;
2727
- /**
2728
- * 注册 Agent
2729
- *
2730
- * 配置优先级(从高到低):
2731
- * 1. registerAgent 传入的 config(来自 PromptComponent)
2732
- * 2. defaultAgent 配置(来自 ConfigComponent,作为 fallback)
2733
- */
2734
- registerAgent(name: string, config: Partial<AgentInstanceConfig>): AgentInstance;
2735
- /**
2736
- * 注销 Agent
2737
- */
2738
- unregisterAgent(name: string): boolean;
2739
- /**
2740
- * 注册 Plugin 到指定 Agent
2741
- */
2742
- registerPlugin(agentName: string, plugin: Plugin): void;
2743
- /**
2744
- * 注销 Plugin
2745
- */
2746
- unregisterPlugin(agentName: string, pluginName: string): boolean;
2747
- /**
2748
- * 设置默认工具列表
2749
- */
2750
- setDefaultTools(tools: Tool[]): void;
2751
- /**
2752
- * 获取可用工具
2753
- */
2754
- getAvailableTools(agent: AgentInstance, context?: AgentContext): Tool[];
2755
- /**
2756
- * 执行 Agent
2757
- *
2758
- * @param agentName Agent 名称
2759
- * @param query 用户查询
2760
- * @param context 执行上下文
2761
- * @returns Agent 执行结果
2762
- */
2763
- run(agentName: string, query: string, context?: AgentContext): Promise<AgentRunResult>;
2764
- private pushMessage;
2765
- /**
2766
- * 执行 Agent(核心方法,内部实现)
2767
- */
2768
- private _run;
2769
- /**
2770
- * 中止 Agent
2771
- *
2772
- * 调用此方法会:
2773
- * 1. 设置 aborted 标志(用于 ReAct 循环检查)
2774
- * 2. 触发 AbortController.abort()(用于中断正在进行的 LLM 调用)
2775
- *
2776
- * 注意:不直接修改 agent.status,由 _run() 的 finally 统一处理
2777
- */
2778
- abort(agentName: string): void;
2779
- /**
2780
- * 构建消息列表
2781
- *
2782
- * 注意:ctx.messages 已经包含了历史消息(包括 system prompt 和 user query)
2783
- * 这里只需要构建当前请求的消息,不重复添加
2784
- */
2785
- private buildMessages;
2786
- /**
2787
- * 调用 LLM
2788
- *
2789
- * 流式事件由 LLMComponent 通过 env.pushEnvEvent() 发布
2790
- */
2791
- private invokeLLM;
2792
- /**
2793
- * 执行工具
2794
- */
2795
- private executeTool;
2796
- /**
2797
- * 执行 Plugin Hooks (Agent 特有的 Hook 执行机制)
2798
- */
2799
- private executePluginHooks;
2800
- /**
2801
- * 处理 Hook 动作
2802
- */
2803
- private handleHookAction;
2804
- /**
2805
- * 通知消息添加(扩展点)
2806
- */
2807
- protected notifyMessageAdded(message: ModelMessage2): void;
2808
- /**
2809
- * 结束结果
2810
- */
2811
- private finalizeResult;
2812
- /**
2813
- * Record messages to session
2814
- *
2815
- * 存储策略:
2816
- * 1. 存储 allMessages 中的所有 user、assistant、tool 消息
2817
- * 2. 跳过 system 消息
2818
- * 3. 跳过空内容的 assistant/tool 消息
2819
- */
2820
- private recordSessionMessages;
2821
- /**
2822
- * 检查消息内容是否为空
2823
- *
2824
- * 空内容定义:
2825
- * - 空字符串 ""
2826
- * - 空数组 []
2827
- * - null
2828
- * - undefined
2829
- *
2830
- * @param content - 消息内容
2831
- * @returns 是否为空
2832
- */
2833
- private isEmptyMessage;
2834
- /**
2835
- * 通过 Environment 发送事件
2836
- */
2837
- private pushEnvEvent;
2838
- /**
2839
- * 获取会话对话历史
2840
- *
2841
- * 核心逻辑:
2842
- * 1. 使用 sessionComponent.getContext() 获取消息(自动从 checkpoint 开始)
2843
- * 2. 根据 messageLimit 限制消息数量(向后兼容 minUserMessages)
2844
- * 3. 过滤掉 tool_call/tool_result 消息(如果 filterHistory=true)
2845
- *
2846
- * 关键改进:利用 checkpoint 概念,避免重复获取已压缩的历史消息,
2847
- * 从而减少重复触发压缩的问题。
2848
- *
2849
- * @param sessionComponent - SessionComponent 实例
2850
- * @param sessionId - 会话 ID
2851
- * @param options - 配置选项
2852
- * @param options.minUserMessages - 最少包含的 user 消息数量(默认 100)
2853
- * @param options.filterHistory - 是否过滤 tool 消息(默认 true)
2854
- * @returns 过滤后的会话消息列表
2855
- */
2856
- private getConversationHistory;
2857
- }
2858
- /**
2859
- * Pending Agent Session - Stores info needed to resume an agent after user input
2860
- */
2861
- interface PendingAgentSession {
2862
- agentSessionId: string;
2863
- nodeId: string;
2864
- runId: string;
2865
- createdAt: number;
2866
- }
2867
- /**
2868
- * AgentComponentAdapter
2869
- *
2870
- * Adapts AgentComponent to the AgentRunner interface expected by Workflow's AgentNode.
2871
- * Provides session isolation for agent execution within workflow context.
2872
- *
2873
- * Features:
2874
- * - Creates dedicated agent sessions for each workflow agent node execution
2875
- * - Tracks pending sessions for resume after user input
2876
- * - Supports mapping agent sessions to workflow run session messages
2877
- */
2878
- declare class AgentComponentAdapter implements AgentRunner {
2879
- private agentComponent;
2880
- private options;
2881
- private _sessionComponent?;
2882
- /** Session prefix for agent sessions */
2883
- private agentSessionPrefix;
2884
- /** Current agent session ID */
2885
- private _currentAgentSessionId?;
2886
- /** Pending agent sessions (waiting for user input) */
2887
- private pendingSessions;
2888
- /** Map from workflow run session to agent sessions */
2889
- private runSessionToAgentSessions;
2890
- constructor(agentComponent: AgentComponent, options?: AgentComponentAdapterOptions, _sessionComponent?: SessionComponent);
2891
- /**
2892
- * Set the SessionComponent for agent session management
2893
- */
2894
- setSessionComponent(sessionComponent: SessionComponent): void;
2895
- /**
2896
- * Get the current agent session ID
2897
- */
2898
- getCurrentAgentSessionId(): string | undefined;
2899
- /**
2900
- * Register an agent that can be used in workflows
2901
- *
2902
- * @param name - Agent name (used as agent_type in workflow definition)
2903
- * @param config - Agent configuration
2904
- */
2905
- registerAgent(name: string, config: AgentRegistrationConfig2): void;
2906
- /**
2907
- * Run an agent
2908
- *
2909
- * Implements AgentRunner interface.
2910
- * Creates a dedicated agent session for each execution within workflow context.
2911
- *
2912
- * @param config - Agent configuration
2913
- * @param resumeOptions - Optional options for resuming a paused agent
2914
- * @returns Agent execution result
2915
- */
2916
- run(config: AgentConfig, resumeOptions?: {
2917
- userQuery?: string;
2918
- agentSessionId?: string;
2919
- }): Promise<AgentResult>;
2920
- /**
2921
- * Resume a paused agent with user response
2922
- *
2923
- * This method is called when workflow resumes after user input.
2924
- * It retrieves the pending agent session and continues execution.
2925
- *
2926
- * @param agentSessionId - The agent session ID to resume
2927
- * @param userQuery - User's response to the ask_user query
2928
- * @param config - Original agent config
2929
- * @returns Agent execution result
2930
- */
2931
- resumeAgent(agentSessionId: string, userQuery: string, config: AgentConfig): Promise<AgentResult>;
2932
- /**
2933
- * Get pending agent session by agent session ID
2934
- */
2935
- getPendingSession(agentSessionId: string): PendingAgentSession | undefined;
2936
- /**
2937
- * Get pending agent sessions for a workflow run
2938
- */
2939
- getPendingSessionsForRun(runId: string): PendingAgentSession[];
2940
- /**
2941
- * Get all agent session IDs associated with a workflow session
2942
- */
2943
- getAgentSessionsForWorkflowSession(workflowSessionId: string): string[];
2944
- /**
2945
- * Check if an agent is registered
2946
- */
2947
- hasAgent(name: string): boolean;
2948
- /**
2949
- * List all registered agents
2950
- */
2951
- listAgents(): string[];
2952
- /**
2953
- * Get the underlying AgentComponent
2954
- */
2955
- getAgentComponent(): AgentComponent;
2956
- private agentSessionPrefixes;
2957
- }
2958
- /**
2959
- * Options for AgentComponentAdapter
2960
- */
2961
- interface AgentComponentAdapterOptions {
2962
- /** Default timeout for agent execution (ms) */
2963
- defaultTimeout?: number;
2964
- /** Default session ID prefix */
2965
- defaultSessionPrefix?: string;
2966
- }
2967
- /**
2968
- * Configuration for registering an agent
2969
- */
2970
- interface AgentRegistrationConfig2 {
2971
- /** Agent type */
2972
- type?: "general" | "research" | "coder" | "critic";
2973
- /** Model to use */
2974
- model?: string;
2975
- /** System prompt */
2976
- systemPrompt?: string;
2977
- /** Max iterations */
2978
- maxIterations?: number;
2979
- /** Allowed tools */
2980
- allowedTools?: string[];
2981
- /** Denied tools */
2982
- deniedTools?: string[];
2983
- /** Timeout (ms) */
2984
- timeout?: number;
2985
- /** Max error retries */
2986
- maxErrorRetries?: number;
2987
- /** Session ID prefix for workflow isolation */
2988
- sessionIdPrefix?: string;
2989
- }
2990
- /**
2991
- * WorkflowRunner interface for running sub-workflows
2992
- */
2993
- interface WorkflowRunner {
2994
- /**
2995
- * Run a workflow by name
2996
- * @param workflowName - Name of the workflow to run
2997
- * @param input - Optional input to pass to the workflow
2998
- * @returns Promise resolving to the workflow run result
2999
- */
3000
- run(workflowName: string, input?: any): Promise<WorkflowRunResult>;
3001
- /**
3002
- * Get the status of a workflow run
3003
- * @param runId - The run ID to check
3004
- * @returns Promise resolving to the run result or null if not found
3005
- */
3006
- getRun(runId: string): Promise<WorkflowRunResult | null>;
3007
- }
3008
- /**
3009
- * Result from a workflow run
3010
- */
3011
- interface WorkflowRunResult {
3012
- /** Unique run ID */
3013
- runId: string;
3014
- /** Final status of the run */
3015
- status: "completed" | "failed" | "stopped";
3016
- /** Output from the workflow (if completed) */
3017
- output?: any;
3018
- /** Error message (if failed or stopped) */
3019
- error?: string;
3020
- }
3021
- /**
3022
- * NodeRegistry initialization options
3023
- */
3024
- interface NodeRegistryOptions {
3025
- /** Registry for looking up tools */
3026
- toolRegistry?: ToolRegistry;
3027
- /** Registry for looking up skills */
3028
- skillRegistry?: SkillRegistry;
3029
- /** AgentComponent for executing agent nodes (auto-creates adapter) */
3030
- agentComponent?: AgentComponent;
3031
- /** Explicit AgentRunner (takes precedence over agentComponent) */
3032
- agentRunner?: AgentRunner;
3033
- /** Runner for executing workflow nodes */
3034
- workflowRunner?: WorkflowRunner;
3035
- /** Session component for agent session management */
3036
- sessionComponent?: SessionComponent;
3037
- /** @deprecated Use agentRunner instead */
3038
- agentRunner2?: AgentRunner;
3039
- }
3040
- /**
3041
- * NodeContext for node creation
3042
- *
3043
- * Context information passed to node factories when creating nodes.
3044
- */
3045
- interface NodeContext {
3046
- /** Run ID for this workflow execution */
3047
- runId: string;
3048
- /** Workflow name */
3049
- workflowName: string;
3050
- /** Event bus for workflow events */
3051
- eventBus: EventBus;
3052
- /** Debug mode flag */
3053
- debug: boolean;
3054
- }
3055
- /**
3056
- * NodeFactory function type
3057
- *
3058
- * Factory function that creates a Node instance from a NodeDefinition.
3059
- */
3060
- type NodeFactory = (definition: NodeDefinition, context: NodeContext) => Node;
3061
- /**
3062
- * NodeRegistry
3063
- *
3064
- * Registry for creating Node instances from NodeDefinition.
3065
- *
3066
- * Features:
3067
- * - Built-in node types: tool, skill, agent, workflow
3068
- * - Custom node type registration via factory functions
3069
- * - Node creation based on node type
3070
- *
3071
- * @example
3072
- * ```typescript
3073
- * const registry = new NodeRegistry(
3074
- * toolRegistry,
3075
- * skillRegistry,
3076
- * agentRunner,
3077
- * workflowRunner
3078
- * );
3079
- *
3080
- * // Register custom node type
3081
- * registry.register('custom', (definition, context) => {
3082
- * return new CustomNode(definition);
3083
- * });
3084
- *
3085
- * // Create node from definition
3086
- * const node = registry.createNode(definition);
3087
- * ```
3088
- */
3089
- declare class NodeRegistry {
3090
- /** Map of registered node factories by type */
3091
- private factories;
3092
- /** Tool registry for looking up tools */
3093
- private toolRegistry?;
3094
- /** Skill registry for looking up skills */
3095
- private skillRegistry?;
3096
- /** Agent runner for executing agent nodes */
3097
- private agentRunner?;
3098
- /** Workflow runner for executing workflow nodes */
3099
- private workflowRunner?;
3100
- /** AgentComponent adapter (auto-created if agentComponent is provided) */
3101
- private agentComponentAdapter?;
3102
- /** Session component for agent session management */
3103
- private sessionComponent?;
3104
- /**
3105
- * Create a new NodeRegistry
3106
- *
3107
- * @param options - Registry options
3108
- * @param options.toolRegistry - Registry for looking up tools (optional)
3109
- * @param options.skillRegistry - Registry for looking up skills (optional)
3110
- * @param options.agentComponent - AgentComponent for executing agent nodes (optional, auto-creates adapter)
3111
- * @param options.agentRunner - Explicit AgentRunner (takes precedence over agentComponent)
3112
- * @param options.workflowRunner - Runner for executing workflow nodes (optional)
3113
- * @param options.sessionComponent - Session component for agent session management (optional)
3114
- */
3115
- constructor(options?: NodeRegistryOptions);
3116
- /**
3117
- * Get the AgentComponentAdapter if available
3118
- */
3119
- getAgentAdapter(): AgentComponentAdapter | undefined;
3120
- /**
3121
- * Get the AgentRunner
3122
- */
3123
- getAgentRunner(): AgentRunner | undefined;
3124
- /**
3125
- * Get the SessionComponent
3126
- */
3127
- getSessionComponent(): SessionComponent | undefined;
3128
- /**
3129
- * Register built-in node types
3130
- */
3131
- private registerBuiltInTypes;
3132
- /**
3133
- * Register a custom node factory
3134
- *
3135
- * @param type - Node type identifier
3136
- * @param factory - Factory function to create nodes of this type
3137
- */
3138
- register(type: string, factory: NodeFactory): void;
3139
- /**
3140
- * Check if a node type is registered
3141
- *
3142
- * @param type - Node type identifier
3143
- * @returns True if the type is registered
3144
- */
3145
- has(type: string): boolean;
3146
- /**
3147
- * List all registered node types
3148
- *
3149
- * @returns Array of registered type names
3150
- */
3151
- list(): string[];
3152
- /**
3153
- * Create a Node instance from a NodeDefinition
3154
- *
3155
- * @param definition - Node definition
3156
- * @param context - Node context (optional, for future use)
3157
- * @returns Node instance
3158
- * @throws Error if the node type is not registered
3159
- */
3160
- createNode(definition: NodeDefinition, context?: NodeContext): Node;
3161
- }
3162
- /**
3163
- * Executor Options
3164
- */
3165
- interface ExecutorOptions {
3166
- /** Global timeout for node execution (ms). null = no timeout */
3167
- globalTimeout: number | null;
3168
- /** Global retry configuration */
3169
- globalRetry: RetryConfig | null;
3170
- /** Debug mode */
3171
- debug: boolean;
3172
- }
3173
- /**
3174
- * Executor
3175
- *
3176
- * Executes nodes in a workflow with support for:
3177
- * - Timeout handling
3178
- * - Retry with configurable backoff
3179
- * - Error propagation
3180
- * - Session message writing
3181
- * - AskUserError handling
3182
- *
3183
- * @example
3184
- * ```typescript
3185
- * const executor = new Executor(nodeRegistry, eventBus, {
3186
- * globalTimeout: 60000,
3187
- * globalRetry: { max_attempts: 3, backoff: 'exponential', initial_delay: 1000 },
3188
- * debug: false
3189
- * });
3190
- *
3191
- * const result = await executor.executeNode(nodeDefinition, context);
3192
- * ```
3193
- */
3194
- declare class Executor {
3195
- private nodeRegistry;
3196
- private eventBus;
3197
- private options;
3198
- private sessionComponent?;
3199
- private abortControllers;
3200
- constructor(nodeRegistry: NodeRegistry, eventBus: EventBus, options: ExecutorOptions, sessionComponent?: SessionComponent);
3201
- /**
3202
- * Execute a node with timeout and retry handling
3203
- */
3204
- executeNode(definition: NodeDefinition, context: NodeExecutionContext): Promise<NodeExecutionResult>;
3205
- /**
3206
- * Execute node with timeout handling
3207
- */
3208
- private executeWithTimeout;
3209
- /**
3210
- * Execute node with retry handling
3211
- */
3212
- private executeWithRetry;
3213
- /**
3214
- * Cancel execution of a specific node
3215
- */
3216
- cancelNode(nodeId: string): void;
3217
- /**
3218
- * Cancel all running nodes
3219
- */
3220
- cancelAll(): void;
3221
- /**
3222
- * Combine two abort signals
3223
- */
3224
- private combineAbortSignals;
3225
- /**
3226
- * Sleep for specified milliseconds
3227
- */
3228
- private sleep;
3229
- /**
3230
- * Write workflow.node.start message
3231
- * 对应 tool-call,节点开始执行
3232
- */
3233
- writeNodeStart(sessionId: string, nodeId: string, nodeType: string, input: unknown, agentSessionId?: string): Promise<void>;
3234
- /**
3235
- * Create a meaningful content summary for call message
3236
- */
3237
- private summarizeCall;
3238
- /**
3239
- * Write workflow.node.interrupt message
3240
- */
3241
- writeNodeInterrupt(sessionId: string, nodeId: string, nodeType: string, query: string, agentSessionId?: string): Promise<void>;
3242
- /**
3243
- * Write workflow.node.end message (对应 tool-result)
3244
- */
3245
- writeNodeEnd(sessionId: string, nodeId: string, nodeType: string, output: unknown, error: string | undefined, durationMs: number, agentSessionId?: string): Promise<void>;
3246
- /**
3247
- * Create a meaningful content summary for result display
3248
- */
3249
- private summarizeResult;
3250
- /**
3251
- * Write workflow.node.resume message
3252
- */
3253
- writeNodeResume(sessionId: string, nodeId: string, response: string, agentSessionId?: string): Promise<void>;
3254
- }
3255
- import { EventEmitter } from "events";
3256
- /**
3257
- * Options for creating WorkflowEngine via static factory
3258
- */
3259
- interface WorkflowEngineCreateOptions {
3260
- env?: {
3261
- getComponent<T>(name: string): T | undefined;
3262
- };
3263
- toolRegistry?: any;
3264
- skillRegistry?: any;
3265
- workflowRunner?: any;
3266
- sessionComponent?: SessionComponent;
3267
- /** Repository for loading workflow definitions during resume */
3268
- workflowRepository?: WorkflowRepository;
3269
- }
3270
- /**
3271
- * Workflow Repository interface (abstraction)
3272
- */
3273
- interface WorkflowRepository {
3274
- getById(id: string): Workflow | null;
3275
- getByName(name: string): Workflow | null;
3276
- }
3277
- /**
3278
- * WorkflowEngine Configuration
3279
- */
3280
- interface WorkflowEngineConfig {
3281
- parallelLimit: number | null;
3282
- timeout: number | null;
3283
- debug: boolean;
3284
- }
3285
- /**
3286
- * WorkflowEngine
3287
- *
3288
- * Session-based workflow execution engine.
3289
- * Uses Session to manage workflow run state and node execution history.
3290
- */
3291
- declare class WorkflowEngine extends EventEmitter {
3292
- /** 活跃的 session 状态,key 为 sessionId */
3293
- private activeSessions;
3294
- /** Session ID 计数器 */
3295
- private sessionIdCounter;
3296
- /** Session component */
3297
- private sessionComponent?;
3298
- /** Node registry */
3299
- private nodeRegistry;
3300
- /** Workflow repository for loading definitions during resume */
3301
- private workflowRepository?;
3302
- /**
3303
- * Create a new WorkflowEngine
3304
- */
3305
- constructor(nodeRegistry: NodeRegistry, sessionComponent?: SessionComponent, workflowRepository?: WorkflowRepository);
3306
- /**
3307
- * Create a WorkflowEngine with automatic AgentComponent integration
3308
- */
3309
- static create(options: WorkflowEngineCreateOptions): Promise<WorkflowEngine>;
3310
- /**
3311
- * Generate a unique run ID
3312
- */
3313
- private generateRunId;
3314
- /**
3315
- * Extract runId from sessionId
3316
- * sessionId format: workflow_{runId}
3317
- */
3318
- private getRunIdFromSessionId;
3319
- /**
3320
- * Get session ID for a run
3321
- */
3322
- getSessionId(runId: string): string;
3323
- /**
3324
- * Create a new workflow session
3325
- *
3326
- * @param workflow - Workflow definition or entity
3327
- * @param options - Optional configuration
3328
- * @returns Promise resolving to sessionId (format: workflow_{runId})
3329
- */
3330
- createSession(workflow: Workflow | WorkflowDefinition, options?: RunOptions): Promise<string>;
3331
- /**
3332
- * Run a workflow by sessionId (unified entry point)
3333
- *
3334
- * This method supports both:
3335
- * 1. First run: session doesn't exist → create session, start from entry node
3336
- * 2. Resume: session exists with messages → infer next node from messages
3337
- *
3338
- * @param sessionId - Session ID (format: workflow_{runId} or any string)
3339
- * @param options - Optional configuration
3340
- * @returns Promise resolving to RunResult
3341
- */
3342
- run(sessionId: string, options?: RunOptions & {
3343
- workflowId?: string;
3344
- }): Promise<RunResult>;
3345
- /**
3346
- * Initialize session state
3347
- */
3348
- private initializeSessionState;
3349
- /**
3350
- * Run with resume point
3351
- *
3352
- * Simplified logic:
3353
- * - input is passed directly to execution (string or object)
3354
- * - For resume with ask_user, the input should contain userQuery
3355
- * - agentSessionId comes from session messages via resumePoint
3356
- */
3357
- private runWithResume;
3358
- /**
3359
- * Convenience method to run a workflow directly
3360
- */
3361
- runWorkflow(workflow: Workflow | WorkflowDefinition, options?: RunOptions): Promise<RunResult>;
3362
- /**
3363
- * Pause a running workflow
3364
- */
3365
- pause(sessionId: string): Promise<void>;
3366
- /**
3367
- * Stop a running or paused workflow
3368
- */
3369
- stop(sessionId: string, reason?: string): Promise<void>;
3370
- /**
3371
- * Get session status
3372
- */
3373
- getSessionStatus(sessionId: string): RunStatus | null;
3374
- /**
3375
- * Check if session is active
3376
- */
3377
- isSessionActive(sessionId: string): boolean;
3378
- /**
3379
- * Setup event handlers for a run
3380
- */
3381
- private setupEventHandlers;
3382
- /**
3383
- * Write node interrupt message
3384
- */
3385
- private writeNodeInterrupt;
3386
- /**
3387
- * Main scheduling loop
3388
- */
3389
- private scheduleAndExecute;
3390
- /**
3391
- * Wait for next node event
3392
- */
3393
- private waitForNextNodeEvent;
3394
- /**
3395
- * Start execution of a single node
3396
- */
3397
- private startNode;
3398
- /**
3399
- * Write workflow.node.start message
3400
- */
3401
- private writeNodeStart;
3402
- /**
3403
- * Write node resume message with user response
3404
- */
3405
- private writeNodeResume;
3406
- /**
3407
- * Resume execution of a paused node
3408
- *
3409
- * Simplified logic:
3410
- * - Load agent session from agentSessionId
3411
- * - Pass userQuery from input to agentNode
3412
- * - No complex userResponse distinction
3413
- */
3414
- private resumeNode;
3415
- /**
3416
- * Create execution context for a node
3417
- *
3418
- * @param sessionState - Active session state
3419
- * @param nodeId - Node ID to create context for
3420
- * @param globalInput - Global workflow input (for entry nodes or resume)
3421
- * @param forceGlobalInput - Force merge globalInput even for non-entry nodes (for resume)
3422
- */
3423
- private createExecutionContext;
3424
- /**
3425
- * Check if workflow is complete and finalize
3426
- */
3427
- private checkAndFinalize;
3428
- /**
3429
- * Complete a workflow successfully
3430
- */
3431
- private completeWorkflow;
3432
- /**
3433
- * Fail a workflow
3434
- */
3435
- private failWorkflow;
3436
- /**
3437
- * Cleanup session resources
3438
- */
3439
- private cleanupSession;
3440
- /**
3441
- * Wait for a run to complete
3442
- */
3443
- private waitForCompletion;
3444
- /**
3445
- * Get session metadata
3446
- */
3447
- private getSessionMetadata;
3448
- /**
3449
- * Find workflow definition from repository
3450
- */
3451
- private findDefinitionForWorkflow;
3452
- }
3453
- export { WorkflowRepository, WorkflowEngineCreateOptions, WorkflowEngineConfig, WorkflowEngine, SchedulerState, SchedulerOptions, Scheduler, RunStatus, RunResult, RunOptions, NodeStatus, NodeRegistry, NodeFactory, NodeExecutionContext, NodeContext, ExecutorOptions, Executor, EventBus, DAGManager, DAGAnalysis };