@ai-setting/roy-agent-core 1.5.16-test → 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 +1 -1
  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,1908 +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 { ZodType as ZodType3, ZodTypeDef as ZodTypeDef2 } from "zod";
206
- /**
207
- * @fileoverview Environment types and interfaces
208
- *
209
- * 定义 Environment 的核心类型,包括:
210
- * - Environment 配置
211
- * - EnvEvent 事件类型
212
- */
213
- /**
214
- * Environment Config
215
- */
216
- interface EnvironmentConfig {
217
- /** 环境名称 */
218
- name: string;
219
- /** 环境版本 */
220
- version: string;
221
- /** 是否启用 */
222
- enabled: boolean;
223
- }
224
- /**
225
- * EnvEvent 元信息
226
- */
227
- interface EnvEventMetadata {
228
- /** 触发事件的 session ID */
229
- trigger_session_id?: string;
230
- /** 触发事件的 agent ID */
231
- trigger_agent_id?: string;
232
- /** Agent 名称 */
233
- trigger_agent_name?: string;
234
- /** 环境名称 */
235
- env_name?: string;
236
- /** 事件来源 */
237
- source?: string;
238
- /** 其他元数据 */
239
- [key: string]: unknown;
240
- }
241
- /**
242
- * EnvEvent
243
- *
244
- * 统一的事件机制,用于:
245
- * - Stream 事件(stream.start, stream.text, stream.completed 等)
246
- * - 工具调用事件(tool.call, tool.result 等)
247
- * - 会话事件(session.created, session.updated 等)
248
- * - Agent 事件(agent.thinking, agent.acting 等)
249
- */
250
- interface EnvEvent<T = unknown> {
251
- /** 事件 ID */
252
- id: string;
253
- /** 事件类型 */
254
- type: string;
255
- /** 时间戳 */
256
- timestamp: number;
257
- /** 元信息 */
258
- metadata: EnvEventMetadata;
259
- /** 事件负载 */
260
- payload: T;
261
- }
262
- /**
263
- * EnvEvent Handler
264
- */
265
- type EnvEventHandler = (event: EnvEvent) => void | Promise<void>;
266
- /**
267
- * EnvEvent 创建参数(部分属性,可选)
268
- *
269
- * 用于 pushEnvEvent 方法,允许传入部分属性,自动补全必填字段
270
- */
271
- interface EnvEventInput {
272
- /** 事件类型(必填) */
273
- type: string;
274
- /** 事件 ID(可选,自动生成) */
275
- id?: string;
276
- /** 时间戳(可选,自动生成) */
277
- timestamp?: number;
278
- /** 元信息(可选,自动创建) */
279
- metadata?: EnvEventMetadata;
280
- /** 事件负载(可选) */
281
- payload?: unknown;
282
- }
283
- /**
284
- * Action 类型
285
- */
286
- interface Action {
287
- /** Action 类型 */
288
- type: string;
289
- /** Action 参数 */
290
- params?: Record<string, unknown>;
291
- }
292
- /**
293
- * Tool Result
294
- */
295
- interface ToolResult {
296
- /** 是否成功 */
297
- success: boolean;
298
- /** 输出内容 */
299
- output: string | Record<string, unknown>;
300
- /** 错误信息 */
301
- error?: string;
302
- }
303
- /**
304
- * Context
305
- */
306
- interface Context {
307
- /** 会话 ID */
308
- sessionId?: string;
309
- /** 用户 ID */
310
- userId?: string;
311
- /** 工作目录 */
312
- workdir?: string;
313
- /** 中断信号 */
314
- abort?: AbortSignal;
315
- /** 元数据 */
316
- metadata?: Record<string, unknown>;
317
- }
318
- type AbortSignalType = AbortSignal;
319
- /**
320
- * Agent 执行上下文
321
- */
322
- interface AgentContext {
323
- /** 会话 ID */
324
- sessionId?: string;
325
- /** 消息 ID */
326
- messageId?: string;
327
- /** 中断信号 */
328
- abort?: AbortSignalType;
329
- /** 额外的上下文信息(会添加到 system prompt) */
330
- additionInfo?: string;
331
- /** 元数据 */
332
- metadata?: Record<string, unknown>;
333
- /** Agent 类型(用于选择 Behavior Spec) */
334
- agentType?: string;
335
- /** 使用的模型 */
336
- model?: string;
337
- /** 允许的工具列表(上下文级别,会覆盖 agent 配置) */
338
- allowedTools?: string[];
339
- /** 拒绝的工具列表(上下文级别,会覆盖 agent 配置) */
340
- deniedTools?: string[];
341
- /** 是否过滤 history 中的 tool 消息(上下文级别,会覆盖 agent 配置) */
342
- filterHistory?: boolean;
343
- }
344
- import { ZodType as ZodType2, ZodTypeDef } from "zod";
345
- /**
346
- * ConfigSource 类型
347
- */
348
- type ConfigSourceType = "memory" | "file" | "env" | "remote";
349
- /**
350
- * SourceRegistration - Source 注册配置
351
- */
352
- interface SourceRegistration {
353
- /** Source 类型 */
354
- type: ConfigSourceType;
355
- /** 相对路径(file 类型使用,基于 XDG_DATA_HOME) */
356
- relativePath?: string;
357
- /** 环境变量前缀(env 类型使用) */
358
- envPrefix?: string;
359
- /** 优先级,默认值:memory=0, file=10, env=20 */
360
- priority?: number;
361
- /** 是否可选(file 类型使用,文件不存在时不报错) */
362
- optional?: boolean;
363
- /** 是否启用文件监听(file 类型使用,默认 true) */
364
- watch?: boolean;
365
- }
366
- /**
367
- * KeyRegistration - 配置 Key 注册
368
- */
369
- interface KeyRegistration {
370
- /** 配置 Key(支持点号嵌套,如 "llm.provider") */
371
- key: string;
372
- /** 优先使用的 Source 列表(按优先级从低到高) */
373
- sources: ConfigSourceType[];
374
- /** 自定义优先级(覆盖默认优先级) */
375
- priority?: number;
376
- /** 默认值 */
377
- default?: unknown;
378
- }
379
- /**
380
- * ComponentRegistration - Component 注册配置
381
- */
382
- interface ComponentRegistration {
383
- /** Component 名称 */
384
- name: string;
385
- /** 声明需要的 Source */
386
- sources: SourceRegistration[];
387
- /** 声明需要的配置 Key */
388
- keys: KeyRegistration[];
389
- /** 配置 Schema(用于验证,可选) */
390
- schema?: ZodType2<unknown, ZodTypeDef, unknown>;
391
- /** 默认值 */
392
- defaults?: Record<string, unknown>;
393
- }
394
- /**
395
- * ConfigSource 接口
396
- */
397
- interface ConfigSource {
398
- readonly name: ConfigSourceType;
399
- readonly priority: number;
400
- read(key: string): unknown | undefined;
401
- write?(key: string, value: unknown): boolean;
402
- delete?(key: string): boolean;
403
- list(): Array<{
404
- key: string;
405
- value: unknown;
406
- }>;
407
- watch?(callback: (event: ConfigChangeEvent) => void): () => void;
408
- }
409
- /**
410
- * Config 变更事件
411
- */
412
- interface ConfigChangeEvent {
413
- type: "change" | "add" | "delete";
414
- key: string;
415
- oldValue: unknown;
416
- newValue: unknown;
417
- source: ConfigSourceType;
418
- timestamp: number;
419
- }
420
- /**
421
- * ConfigComponent 配置
422
- */
423
- interface ConfigComponentOptions {
424
- /** 持久化文件路径 */
425
- persistFile?: string;
426
- /** 防抖延迟(ms) */
427
- debounceMs?: number;
428
- /** 最大批量大小 */
429
- maxBatchSize?: number;
430
- }
431
- /**
432
- * ConfigComponent
433
- */
434
- declare class ConfigComponent extends BaseComponent {
435
- readonly name = "config";
436
- readonly version = "1.0.0";
437
- private memorySource;
438
- private sources;
439
- private componentSchemas;
440
- private componentPaths;
441
- private watchers;
442
- /** Source watch unsubscribe 函数 */
443
- private sourceUnwatchFns;
444
- private persistQueue;
445
- private persistFile?;
446
- /** Key 注册表:key -> KeyRegistration */
447
- private keyRegistry;
448
- /** Component 注册表:name -> ComponentRegistration */
449
- private componentRegistrations;
450
- /** 协议解析器 */
451
- private protocolResolver?;
452
- /** XDG_DATA_HOME 缓存(用于测试注入) */
453
- private __xdgDataHome?;
454
- /** Source 注册配置(延迟创建) */
455
- private pendingSources;
456
- /** Source 唯一标识缓存:type:relativePath -> true */
457
- private sourceKeys;
458
- /**
459
- * 获取 XDG_DATA_HOME(动态获取,支持运行时覆盖)
460
- */
461
- getXdgDataHome(): string;
462
- /**
463
- * 设置 XDG_DATA_HOME(用于测试)
464
- */
465
- setXdgDataHome(path: string): void;
466
- constructor(options?: ConfigComponentOptions);
467
- /**
468
- * 注册 Component Schema
469
- */
470
- register(schema: ComponentSchema): void;
471
- /**
472
- * 注销 Component
473
- */
474
- unregister(name: string): boolean;
475
- /**
476
- * 检查是否已注册
477
- */
478
- isRegistered(name: string): boolean;
479
- /**
480
- * 列出所有注册的 Component
481
- */
482
- listComponents(): string[];
483
- /**
484
- * 获取配置值(支持 xxx.yyy.zzz 嵌套访问)
485
- * 支持两种模式:
486
- * 1. 完整 key:直接查找,如 "component.key" -> 读取 "component.key"
487
- * 2. 嵌套对象:查找 component 对象后从中获取属性,如 "component.nested.deep"
488
- * -> 先找 "component.nested",再获取其 "deep" 属性
489
- */
490
- get(key: string): unknown;
491
- /**
492
- * 批量获取
493
- */
494
- getMany(keys: string[]): Record<string, unknown>;
495
- /**
496
- * 设置配置值(内存级别 + 异步持久化)
497
- */
498
- set(key: string, value: unknown): Promise<void>;
499
- /**
500
- * 批量设置
501
- */
502
- setMany(config: Record<string, unknown>): Promise<void>;
503
- /**
504
- * 获取 Component 的路径
505
- */
506
- getPath(component: string, subPath?: string): string;
507
- /**
508
- * 手动持久化
509
- */
510
- save(key?: string): Promise<void>;
511
- /**
512
- * 重置到默认值
513
- */
514
- reset(key: string): Promise<void>;
515
- /**
516
- * 监听配置变更
517
- */
518
- watch(pattern: string, callback: ComponentWatchCallback): () => void;
519
- /**
520
- * 添加配置源
521
- */
522
- addSource(source: ConfigSource): void;
523
- /**
524
- * 获取 Source 唯一标识
525
- */
526
- private getSourceKey;
527
- /**
528
- * 移除配置源
529
- */
530
- removeSource(name: ConfigSourceType): boolean;
531
- /**
532
- * 关闭所有配置源的 watcher(用于优雅退出)
533
- */
534
- unwatchAll(): void;
535
- /**
536
- * 获取配置源列表
537
- */
538
- getSources(): ConfigSource[];
539
- private getNestedValue;
540
- private notifyWatchers;
541
- private persistToFile;
542
- /**
543
- * 注册配置 Source
544
- *
545
- * Source 会在首次 load() 时被创建
546
- *
547
- * @example
548
- * config.registerSource({ type: "file", relativePath: "llm-config.jsonc" });
549
- * config.registerSource({ type: "env", envPrefix: "LLM" });
550
- */
551
- registerSource(registration: SourceRegistration): void;
552
- /**
553
- * 创建 Source 实例
554
- */
555
- private createSource;
556
- /**
557
- * 确保所有待创建的 Source 已被创建
558
- */
559
- private ensureSourcesCreated;
560
- /**
561
- * 注册配置 Key
562
- *
563
- * @example
564
- * config.registerKeys([
565
- * { key: "llm.provider", sources: ["file", "memory"], default: "openai" },
566
- * { key: "llm.model", sources: ["file"] },
567
- * ]);
568
- */
569
- registerKeys(keys: KeyRegistration[]): void;
570
- /**
571
- * 注册 Component(一次性注册 Source 和 Keys)
572
- *
573
- * @example
574
- * config.registerComponent({
575
- * name: "llm",
576
- * sources: [
577
- * { type: "file", relativePath: "llm-config.jsonc" },
578
- * { type: "env", envPrefix: "LLM" },
579
- * ],
580
- * keys: [
581
- * { key: "llm.provider", sources: ["file", "env", "memory"] },
582
- * ],
583
- * });
584
- */
585
- registerComponent(registration: ComponentRegistration): void;
586
- /**
587
- * 按需加载配置
588
- *
589
- * 从注册的 Source 加载已注册 Keys 的配置值到内存中
590
- *
591
- * @param componentName - 可选,指定要加载的 Component 名称
592
- *
593
- * @example
594
- * // 加载所有已注册的 Keys
595
- * await config.load();
596
- *
597
- * // 只加载指定 Component 的 Keys
598
- * await config.load("llm");
599
- */
600
- load(componentName?: string): Promise<void>;
601
- /**
602
- * 获取已注册的 Source 列表
603
- */
604
- getRegisteredSources(): ConfigSource[];
605
- }
606
- /**
607
- * 服务配置接口
608
- */
609
- interface ServiceConfig {
610
- /** 环境配置 */
611
- environment?: {
612
- name?: string;
613
- version?: string;
614
- };
615
- /** 组件配置映射 */
616
- components?: Record<string, ComponentConfigEntry>;
617
- }
618
- /**
619
- * 组件配置项
620
- */
621
- interface ComponentConfigEntry {
622
- /** 配置文件路径(可选) */
623
- configPath?: string;
624
- /** 环境变量前缀(可选) */
625
- envPrefix?: string;
626
- /** 直接配置对象(可选) */
627
- config?: Record<string, unknown>;
628
- /** 是否启用(可选,默认 true) */
629
- enabled?: boolean;
630
- }
631
- /**
632
- * 组件初始化选项(由 generateComponentOptions 生成)
633
- */
634
- interface GeneratedComponentOptions {
635
- /** ConfigComponent 实例 */
636
- configComponent: ConfigComponent;
637
- /** 配置文件路径 */
638
- configPath?: string;
639
- /** 环境变量前缀 */
640
- envPrefix?: string;
641
- /** 直接配置对象 */
642
- config?: Record<string, unknown>;
643
- /** 允许的其他属性 */
644
- [key: string]: unknown;
645
- }
646
- /**
647
- * Environment 接口
648
- *
649
- * 定义 Agent 运行时的核心能力接口。
650
- */
651
- interface Environment {
652
- /** 环境名称 */
653
- readonly name: string;
654
- /** 环境版本 */
655
- readonly version: string;
656
- /** 获取环境配置 */
657
- getConfig(): EnvironmentConfig;
658
- /**
659
- * 注册组件
660
- */
661
- registerComponent(component: Component): void;
662
- /**
663
- * 注销组件
664
- */
665
- unregisterComponent(name: string): void;
666
- /**
667
- * 获取组件
668
- */
669
- getComponent<T extends Component>(name: string): T | undefined;
670
- /**
671
- * 列出所有组件
672
- */
673
- listComponents(): Component[];
674
- /**
675
- * 处理自然语言查询(核心入口)
676
- *
677
- * @param query 用户查询文本
678
- * @param context 执行上下文(可选)
679
- * @returns 完整的文本响应
680
- */
681
- handle_query(query: string, context?: AgentContext): Promise<string>;
682
- /**
683
- * 处理动作
684
- */
685
- handle_action(action: Action, context: Context): Promise<ToolResult>;
686
- /**
687
- * 订阅 EnvEvent(返回取消订阅函数)
688
- */
689
- subscribe(handler: EnvEventHandler): () => void;
690
- /**
691
- * 订阅指定类型事件
692
- */
693
- subscribeTo(eventType: string | string[], handler: EnvEventHandler): () => void;
694
- /**
695
- * 订阅所有事件(通配符)
696
- */
697
- subscribeAll(handler: EnvEventHandler): () => void;
698
- /**
699
- * 推送事件
700
- *
701
- * @param event EnvEvent 或 EnvEventInput(部分属性)
702
- */
703
- pushEnvEvent(event: EnvEvent | EnvEventInput): void;
704
- /**
705
- * 从配置文件加载服务配置
706
- *
707
- * @param configPath 配置文件路径(基于 XDG_DATA_HOME)
708
- * @returns 解析后的服务配置对象
709
- */
710
- loadServiceConfig(configPath: string): Promise<ServiceConfig>;
711
- /**
712
- * 生成组件初始化选项
713
- *
714
- * 根据组件配置项生成可用于初始化的选项对象。
715
- *
716
- * @param componentName 组件名称
717
- * @param configEntry 组件配置项
718
- * @returns 生成的组件初始化选项
719
- */
720
- generateComponentOptions(componentName: string, configEntry: ComponentConfigEntry): GeneratedComponentOptions;
721
- /**
722
- * 注册组件并用配置初始化
723
- *
724
- * 便捷方法:注册组件并通过 ConfigComponent 初始化。
725
- *
726
- * @param component 要注册的组件实例
727
- * @param configEntry 组件配置项
728
- */
729
- registerComponentWithConfig(component: Component, configEntry: ComponentConfigEntry): Promise<void>;
730
- /**
731
- * 从配置文件初始化整个环境
732
- *
733
- * 加载服务配置,注册并初始化所有配置的组件。
734
- *
735
- * @param configPath 配置文件路径(基于 XDG_DATA_HOME)
736
- */
737
- initFromConfig(configPath: string): Promise<void>;
738
- }
739
- /**
740
- * Component 状态
741
- */
742
- type ComponentStatus = "created" | "initializing" | "running" | "stopping" | "stopped" | "error";
743
- /**
744
- * Component 配置
745
- */
746
- interface ComponentConfig {
747
- name: string;
748
- version: string;
749
- enabled: boolean;
750
- options?: Record<string, unknown>;
751
- /**
752
- * Environment 实例(可选)
753
- *
754
- * 推荐在 init 时接收 env 实例,以便:
755
- * - 通过 env.getComponent() 获取其他组件
756
- * - 通过 env.pushEnvEvent() 发布事件
757
- * - 通过 env.handle_query() 处理查询
758
- *
759
- * 如果未提供,部分 Component 仍可正常工作(如测试场景)
760
- *
761
- * @example
762
- * ```typescript
763
- * async onInit(): Promise<void> {
764
- * if (this.env) {
765
- * const configComp = this.env.getComponent("config");
766
- * }
767
- * }
768
- * ```
769
- */
770
- env?: Environment;
771
- }
772
- /**
773
- * Component 路径声明
774
- */
775
- interface ComponentPaths {
776
- base: "config" | "state" | "data" | "cache";
777
- subPath: string;
778
- isDirectory: boolean;
779
- }
780
- /**
781
- * Component Schema(注册配置)
782
- */
783
- interface ComponentSchema {
784
- /** Component 名称 */
785
- name: string;
786
- /** 配置 Schema(Zod) */
787
- schema: ZodType3<unknown, ZodTypeDef2, unknown>;
788
- /** 默认值(从 Schema 提取) */
789
- defaults: Record<string, unknown>;
790
- /** 路径声明 */
791
- paths?: Record<string, ComponentPaths>;
792
- /** 元信息 */
793
- metadata?: {
794
- description?: string;
795
- version?: string;
796
- author?: string;
797
- };
798
- }
799
- /**
800
- * Component 配置变更事件
801
- */
802
- interface ComponentConfigChangeEvent {
803
- /** Component 名称 */
804
- component: string;
805
- /** 变更的配置键 */
806
- key: string;
807
- /** 旧值 */
808
- oldValue: unknown;
809
- /** 新值 */
810
- newValue: unknown;
811
- /** 是否持久化 */
812
- persisted: boolean;
813
- /** 时间戳 */
814
- timestamp: number;
815
- }
816
- /**
817
- * Component 配置监听回调
818
- */
819
- type ComponentWatchCallback = (event: ComponentConfigChangeEvent) => void | Promise<void>;
820
- /**
821
- * Component 基类接口
822
- */
823
- interface Component {
824
- /** Component 名称 */
825
- readonly name: string;
826
- /** Component 版本 */
827
- readonly version: string;
828
- /** 获取状态 */
829
- getStatus(): ComponentStatus;
830
- /** 获取配置 */
831
- getConfig(): ComponentConfig;
832
- /** 初始化 */
833
- init(config: ComponentConfig): Promise<void>;
834
- /** 启动 */
835
- start(): Promise<void>;
836
- /** 停止 */
837
- stop(): Promise<void>;
838
- }
839
- /**
840
- * Component 基类实现
841
- */
842
- declare abstract class BaseComponent implements Component {
843
- abstract readonly name: string;
844
- abstract readonly version: string;
845
- protected _status: ComponentStatus;
846
- protected _enabled: boolean;
847
- protected env: Environment;
848
- /** Hook 管理器 - 子类初始化时由构造函数设置 */
849
- readonly hookManager: HookManager;
850
- constructor();
851
- getStatus(): ComponentStatus;
852
- getConfig(): ComponentConfig;
853
- /**
854
- * 检查 Environment 是否已初始化
855
- */
856
- protected isEnvInitialized(): boolean;
857
- protected setStatus(status: ComponentStatus): void;
858
- /**
859
- * 获取 Environment 实例
860
- */
861
- protected getEnv(): Environment;
862
- init(config?: ComponentConfig): Promise<void>;
863
- start(): Promise<void>;
864
- stop(): Promise<void>;
865
- /**
866
- * 子类可覆盖的钩子方法
867
- */
868
- protected onInit(): Promise<void>;
869
- protected onStart(): Promise<void>;
870
- protected onStop(): Promise<void>;
871
- /**
872
- * 注册 Hook
873
- *
874
- * @param hookPoint Hook 点名称
875
- * @param hook Hook 实例
876
- */
877
- protected registerHook<T = unknown>(hookPoint: string, hook: Hook<T>): void;
878
- /**
879
- * 便捷方法:快速注册 Hook
880
- */
881
- protected addHook<T = unknown>(hookPoint: string, name: string, fn: HookFn<T>, priority?: number): void;
882
- /**
883
- * 便捷方法:按名称取消注册 Hook
884
- */
885
- protected removeHook(hookPoint: string, name: string): boolean;
886
- /**
887
- * 执行 Hook
888
- */
889
- protected executeHooks<T = unknown>(hookPoint: string, data: T, metadata?: Record<string, unknown>): Promise<void>;
890
- /**
891
- * 获取 ConfigComponent 实例
892
- *
893
- * 子类可使用此方法获取配置组件,支持热更新
894
- */
895
- protected getConfigComponent(): {
896
- get(key: string): unknown;
897
- } | undefined;
898
- /**
899
- * 动态获取运行时配置值
900
- *
901
- * 优先从 ConfigComponent 获取(支持热更新),否则返回默认值
902
- * 适用于运行时可能变化的配置(如 API Keys、模型参数)
903
- *
904
- * @param key 配置键(支持点号分隔的路径,如 "llm.temperature")
905
- * @param defaultValue 默认值
906
- * @returns 配置值或默认值
907
- *
908
- * @example
909
- * ```typescript
910
- * // 获取 LLM 温度配置(可能支持热更新)
911
- * const temperature = this.getRuntimeConfig("llm.temperature", 0.7);
912
- *
913
- * // 获取 API Key
914
- * const apiKey = this.getRuntimeConfig<string>("llm.providers.openai.apiKey");
915
- * ```
916
- */
917
- protected getRuntimeConfig<T>(key: string, defaultValue: T): T;
918
- }
919
- import { z as z2 } from "zod";
920
- /**
921
- * Session Component configuration schema
922
- */
923
- declare const SessionConfigSchema: unknown;
924
- type SessionConfig = z2.infer<typeof SessionConfigSchema>;
925
- /**
926
- * Checkpoint type
927
- */
928
- type CheckpointType = "compact" | "manual";
929
- /**
930
- * Checkpoint metadata (stored in Session.metadata)
931
- */
932
- interface CheckpointMeta {
933
- id: string;
934
- messageIndex: number;
935
- title: string;
936
- createdAt: number;
937
- type: CheckpointType;
938
- }
939
- /**
940
- * User Intent type - represents a user's intent extracted from conversation
941
- */
942
- type UserIntent = string;
943
- /**
944
- * Recent message for checkpoint
945
- *
946
- * Stores a simplified version of a message for context preservation
947
- */
948
- interface RecentMessage {
949
- role: string;
950
- content: string;
951
- }
952
- /**
953
- * Complete checkpoint information (includes generated content)
954
- */
955
- interface SessionCheckpoint extends CheckpointMeta {
956
- summary: string;
957
- processKeyPoints: string[];
958
- currentState: string;
959
- nextSteps: string[];
960
- messageCountBefore: number;
961
- metadata?: Record<string, unknown>;
962
- /** User intents extracted from the conversation */
963
- userIntents: UserIntent[];
964
- /**
965
- * Recent messages preserved from the compacted conversation
966
- *
967
- * Contains the last N turns of user query + assistant text response
968
- * (excluding tool calls and tool results).
969
- * This allows the checkpoint to serve as a fresh history context.
970
- *
971
- * Format: [user, assistant, user, assistant, ...] from most recent
972
- */
973
- recentMessages?: RecentMessage[];
974
- }
975
- /**
976
- * Checkpoints metadata in session
977
- */
978
- interface SessionCheckpointsMeta {
979
- latestCheckpointId?: string;
980
- checkpoints: CheckpointMeta[];
981
- }
982
- /**
983
- * Session entity
984
- */
985
- interface Session {
986
- id: string;
987
- title: string;
988
- directory: string;
989
- parentID?: string;
990
- createdAt: number;
991
- updatedAt: number;
992
- messageCount: number;
993
- metadata?: SessionMetadata;
994
- }
995
- /**
996
- * Session metadata
997
- */
998
- interface SessionMetadata extends Record<string, unknown> {
999
- /** Total number of messages in the session */
1000
- messageCount?: number;
1001
- checkpoints?: SessionCheckpointsMeta;
1002
- checkpointDetails?: Record<string, SessionCheckpoint>;
1003
- }
1004
- /**
1005
- * Session message
1006
- */
1007
- interface SessionMessage {
1008
- id: string;
1009
- sessionID: string;
1010
- role: Role;
1011
- content: string;
1012
- timestamp: number;
1013
- parts?: MessagePart[];
1014
- /** Whether the message has been archived (compacted) */
1015
- isArchived?: boolean;
1016
- /** Timestamp when the message was archived */
1017
- archivedAt?: number;
1018
- /** Checkpoint ID this message belongs to */
1019
- checkpointId?: string;
1020
- /** Message metadata (includes checkpoint info if this is a checkpoint message) */
1021
- metadata?: MessageMetadata;
1022
- }
1023
- /**
1024
- * Message metadata
1025
- */
1026
- interface MessageMetadata extends Record<string, unknown> {
1027
- /** 消息类型标识,用于过滤和分类 */
1028
- type?: "tool_call" | "tool_result" | "checkpoint" | "user_intent" | "workflow.node.start" | "workflow.node.interrupt" | "workflow.node.end" | "workflow.node.resume";
1029
- isCheckpoint?: boolean;
1030
- checkpointId?: string;
1031
- checkpointMeta?: SessionCheckpoint;
1032
- /** Workflow node ID (for workflow.node.* messages) */
1033
- workflowNodeId?: string;
1034
- /** Workflow node type (for workflow.node.* messages) */
1035
- workflowNodeType?: string;
1036
- /** Agent session ID (for agent nodes in workflow) */
1037
- agentSessionId?: string;
1038
- /** User response (for workflow.node.resume messages) */
1039
- response?: string;
1040
- /** Success flag (for workflow.node.end messages) */
1041
- success?: boolean;
1042
- }
1043
- /**
1044
- * Message role
1045
- */
1046
- type Role = "user" | "assistant" | "system" | "tool" | "workflow.node.start" | "workflow.node.interrupt" | "workflow.node.end" | "workflow.node.resume";
1047
- /**
1048
- * Message part
1049
- */
1050
- type MessagePart = SessionPart;
1051
- /**
1052
- * Text part - plain text content
1053
- */
1054
- interface TextPart {
1055
- type: "text";
1056
- content: string;
1057
- /** If true, this part was generated by the system (e.g., auto-summary) */
1058
- synthetic?: boolean;
1059
- /** If true, this part should be ignored (e.g., replaced by reasoning) */
1060
- ignored?: boolean;
1061
- }
1062
- /**
1063
- * Tool call part - represents a tool invocation
1064
- */
1065
- interface ToolCallPart {
1066
- type: "tool-call";
1067
- /** AI SDK standard field name */
1068
- toolCallId: string;
1069
- toolName: string;
1070
- /** Tool arguments - can be string (JSON) or object */
1071
- arguments: string | Record<string, unknown>;
1072
- state: "pending" | "running";
1073
- }
1074
- /**
1075
- * Tool result part - represents the result of a tool execution
1076
- */
1077
- interface ToolResultPart {
1078
- type: "tool-result";
1079
- toolCallId: string;
1080
- toolName: string;
1081
- output: string;
1082
- error?: string;
1083
- state: "completed" | "error";
1084
- }
1085
- /**
1086
- * Reasoning part - AI thinking/thought content
1087
- */
1088
- interface ReasoningPart {
1089
- type: "reasoning";
1090
- /** Reasoning content */
1091
- content: string;
1092
- /** Reasoning type (for different models) */
1093
- reasoningType?: "core" | "effort" | "summary";
1094
- /** State */
1095
- state?: "thinking" | "completed";
1096
- /** Whether to collapse by default (like AI SDK default) */
1097
- isCollapsed?: boolean;
1098
- /** Metadata */
1099
- metadata?: {
1100
- tokenCount?: number;
1101
- time?: {
1102
- start: number;
1103
- end?: number;
1104
- };
1105
- };
1106
- }
1107
- /**
1108
- * File part - file attachment
1109
- */
1110
- interface FilePart {
1111
- type: "file";
1112
- mime: string;
1113
- url: string;
1114
- filename?: string;
1115
- }
1116
- /**
1117
- * Checkpoint part - compaction checkpoint marker
1118
- *
1119
- * Represents a checkpoint message in the conversation history.
1120
- * This is stored as a user role message with markdown content summarizing
1121
- * the compacted conversation segment.
1122
- */
1123
- interface CheckpointPart {
1124
- type: "checkpoint";
1125
- /** Checkpoint ID reference */
1126
- checkpointId: string;
1127
- /** Markdown content summarizing the checkpoint */
1128
- content: string;
1129
- /** Title of the checkpoint */
1130
- title?: string;
1131
- /** Process key points */
1132
- processKeyPoints?: string[];
1133
- /** Current state description */
1134
- currentState?: string;
1135
- /** Next steps */
1136
- nextSteps?: string[];
1137
- /** Number of messages that were compacted */
1138
- messageCountBefore?: number;
1139
- /** Creation timestamp */
1140
- createdAt?: number;
1141
- }
1142
- /**
1143
- * Union type for all Session Part types
1144
- */
1145
- type SessionPart = TextPart | ToolCallPart | ToolResultPart | ReasoningPart | FilePart | CheckpointPart | WorkflowNodeStartPart | WorkflowNodeInterruptPart | WorkflowNodeEndPart | WorkflowNodeResumePart;
1146
- /**
1147
- * workflow.node.start 消息 part (对应 tool-call)
1148
- */
1149
- interface WorkflowNodeStartPart {
1150
- type: "workflow-node-start";
1151
- nodeId: string;
1152
- nodeType: string;
1153
- input?: unknown;
1154
- startTime: number;
1155
- /** Agent session ID (only for agent nodes) */
1156
- agentSessionId?: string;
1157
- }
1158
- /**
1159
- * workflow.node.interrupt 消息 part
1160
- */
1161
- interface WorkflowNodeInterruptPart {
1162
- type: "workflow-node-interrupt";
1163
- nodeId: string;
1164
- nodeType: string;
1165
- query: string;
1166
- options?: string[];
1167
- timestamp: number;
1168
- /** Agent session ID (only for agent nodes) */
1169
- agentSessionId?: string;
1170
- }
1171
- /**
1172
- * workflow.node.end 消息 part (对应 tool-result)
1173
- */
1174
- interface WorkflowNodeEndPart {
1175
- type: "workflow-node-end";
1176
- nodeId: string;
1177
- nodeType: string;
1178
- output?: unknown;
1179
- error?: string;
1180
- durationMs: number;
1181
- /** Agent session ID (only for agent nodes) */
1182
- agentSessionId?: string;
1183
- }
1184
- /**
1185
- * workflow.node.resume 消息 part
1186
- */
1187
- interface WorkflowNodeResumePart {
1188
- type: "workflow-node-resume";
1189
- nodeId: string;
1190
- response: string;
1191
- timestamp: number;
1192
- /** Agent session ID (only for agent nodes) */
1193
- agentSessionId?: string;
1194
- }
1195
- /**
1196
- * Options for creating a session
1197
- */
1198
- interface CreateSessionOptions {
1199
- /** Custom session ID (optional, will be generated if not provided) */
1200
- id?: string;
1201
- title?: string;
1202
- directory?: string;
1203
- parentID?: string;
1204
- metadata?: Record<string, unknown>;
1205
- hooks?: SessionHooksConfig;
1206
- }
1207
- /**
1208
- * Options for updating a session
1209
- */
1210
- interface UpdateSessionOptions {
1211
- title?: string;
1212
- metadata?: Record<string, unknown>;
1213
- }
1214
- /**
1215
- * Options for listing sessions
1216
- */
1217
- interface ListSessionsOptions {
1218
- filter?: {
1219
- metadata?: Record<string, unknown>;
1220
- startTime?: number;
1221
- endTime?: number;
1222
- };
1223
- sort?: {
1224
- field: "updatedAt" | "createdAt" | "title";
1225
- order: "asc" | "desc";
1226
- };
1227
- offset?: number;
1228
- limit?: number;
1229
- }
1230
- /**
1231
- * Options for adding a message
1232
- */
1233
- interface AddMessageOptions {
1234
- role: Role;
1235
- content: string;
1236
- parts?: MessagePart[];
1237
- metadata?: MessageMetadata;
1238
- }
1239
- /**
1240
- * Options for compact operation
1241
- */
1242
- interface CompactOptions {
1243
- /** User-provided summary hint for checkpoint generation */
1244
- summary?: string;
1245
- /** User-provided process key points hint */
1246
- processKeyPoints?: string[];
1247
- /** User-provided current state hint */
1248
- currentState?: string;
1249
- /** User-provided next steps hint */
1250
- nextSteps?: string[];
1251
- /** Whether this is auto-triggered compact */
1252
- auto?: boolean;
1253
- /**
1254
- * Scenario hint for guiding checkpoint generation
1255
- *
1256
- * A natural language description that provides context about the current scenario.
1257
- * This helps the SummaryAgent generate more relevant checkpoints based on the specific
1258
- * situation. Examples:
1259
- * - "Task execution in progress: implementing feature X, current working directory is /path/to/project"
1260
- * - "Bug investigation: analyzing crash dump, current hypothesis is memory corruption"
1261
- * - "Code review session: reviewing PR #123, focus on security implications"
1262
- *
1263
- * When provided, this will be prepended to the system prompt to guide the checkpoint
1264
- * generation with scenario-specific emphasis.
1265
- */
1266
- scenarioHint?: string;
1267
- }
1268
- /**
1269
- * Result of compact operation
1270
- */
1271
- interface CompactResult {
1272
- checkpoint: SessionCheckpoint;
1273
- deletedMessageCount: number;
1274
- remainingMessageCount: number;
1275
- checkpointCount: number;
1276
- }
1277
- /**
1278
- * Preview of compact operation
1279
- */
1280
- interface CompactPreview {
1281
- messageCountToCompact: number;
1282
- estimatedCheckpointTokens: number;
1283
- wouldTrigger: boolean;
1284
- }
1285
- /**
1286
- * Options for getting session context
1287
- */
1288
- interface GetContextOptions {
1289
- /** Start from specified checkpoint */
1290
- fromCheckpoint?: string;
1291
- /** Start from latest checkpoint (default: true) */
1292
- fromLatestCheckpoint?: boolean;
1293
- /** Read full history (ignore checkpoints) */
1294
- fullHistory?: boolean;
1295
- /** Message limit */
1296
- messageLimit?: number;
1297
- /** Minimum user messages to include (ensures starting from user message boundary) */
1298
- minUserMessages?: number;
1299
- /** Include checkpoint details */
1300
- includeCheckpoints?: boolean;
1301
- }
1302
- /**
1303
- * Result of getting session context
1304
- */
1305
- interface GetContextResult {
1306
- session: Session;
1307
- checkpoints: SessionCheckpoint[];
1308
- startCheckpoint?: SessionCheckpoint;
1309
- messages: SessionMessage[];
1310
- totalMessageCount: number;
1311
- activeMessageCount: number;
1312
- archivedMessageCount: number;
1313
- estimatedTokens: number;
1314
- }
1315
- /**
1316
- * Options for getting messages
1317
- */
1318
- interface GetMessagesOptions {
1319
- /** Include archived messages */
1320
- includeArchived?: boolean;
1321
- /** From checkpoint ID */
1322
- fromCheckpointId?: string;
1323
- /** Reverse order */
1324
- reverse?: boolean;
1325
- }
1326
- /**
1327
- * Session hook type
1328
- */
1329
- type SessionHookType = "before.session.create" | "after.session.create" | "before.session.get" | "after.session.get" | "before.session.list" | "after.session.list" | "before.session.update" | "after.session.update" | "before.session.delete" | "after.session.delete" | "before.session.compact" | "after.session.compact" | "before.session.createCheckpoint" | "after.session.createCheckpoint" | "before.session.deleteCheckpoint" | "after.session.deleteCheckpoint";
1330
- /**
1331
- * Session hook context
1332
- */
1333
- interface SessionHookContext2 {
1334
- session?: Session;
1335
- id?: string;
1336
- options?: CreateSessionOptions | UpdateSessionOptions;
1337
- checkpoint?: SessionCheckpoint;
1338
- }
1339
- /**
1340
- * Session hook callback
1341
- */
1342
- type SessionHookCallback = (context?: any) => Promise<void>;
1343
- /**
1344
- * Session hook definition
1345
- */
1346
- interface SessionHook {
1347
- name: string;
1348
- before?: SessionHookCallback;
1349
- after?: SessionHookCallback;
1350
- }
1351
- /**
1352
- * Session hooks configuration
1353
- */
1354
- interface SessionHooksConfig {
1355
- [key: string]: SessionHook[];
1356
- }
1357
- /**
1358
- * Options for searching messages
1359
- */
1360
- interface SearchMessagesOptions {
1361
- /** Search query (supports AND/OR/NOT syntax) */
1362
- query: string;
1363
- /** Limit search to specific session ID */
1364
- sessionId?: string;
1365
- /** Maximum number of results per session */
1366
- limit?: number;
1367
- /** Maximum total results */
1368
- maxResults?: number;
1369
- /** Only search messages before this timestamp */
1370
- beforeTime?: number;
1371
- /** Only search messages after this timestamp */
1372
- afterTime?: number;
1373
- /** Include archived messages */
1374
- includeArchived?: boolean;
1375
- /** Include context (messages before/after matches) */
1376
- includeContext?: boolean;
1377
- /** Number of context lines before/after */
1378
- contextLines?: number;
1379
- }
1380
- /**
1381
- * A single message match
1382
- */
1383
- interface MessageMatch {
1384
- /** Message ID */
1385
- messageId: string;
1386
- /** Session ID */
1387
- sessionId: string;
1388
- /** Message role */
1389
- role: Role;
1390
- /** Message content */
1391
- content: string;
1392
- /** Message timestamp */
1393
- timestamp: number;
1394
- /** Context before the match (if enabled) */
1395
- contextBefore?: string;
1396
- /** Context after the match (if enabled) */
1397
- contextAfter?: string;
1398
- /** Match score (relevance) */
1399
- score?: number;
1400
- }
1401
- /**
1402
- * Search result aggregated by session
1403
- */
1404
- interface SearchResult {
1405
- /** Session ID */
1406
- sessionId: string;
1407
- /** Session title */
1408
- sessionTitle: string;
1409
- /** Session directory */
1410
- sessionDirectory: string;
1411
- /** Session update timestamp */
1412
- updatedAt: number;
1413
- /** Total message count in session */
1414
- messageCount: number;
1415
- /** Matching messages in this session */
1416
- matches: MessageMatch[];
1417
- }
1418
- /**
1419
- * SessionComponent
1420
- *
1421
- * Manages session lifecycle including:
1422
- * - Session CRUD operations
1423
- * - Message management
1424
- * - Active session tracking
1425
- */
1426
- declare class SessionComponent extends BaseComponent {
1427
- readonly name = "session";
1428
- readonly version = "1.1.0";
1429
- private config?;
1430
- private store?;
1431
- private activeSessionId?;
1432
- private hooksConfig;
1433
- /** ConfigComponent 用于配置管理 */
1434
- private configComponent?;
1435
- /** 配置变更 watcher 清理函数 */
1436
- private configWatcher?;
1437
- /** Summary Agent for checkpoint generation [new] */
1438
- private summaryAgent?;
1439
- /** PromptComponent reference for SummaryAgent */
1440
- private promptComponent?;
1441
- /** LLMComponent reference for SummaryAgent */
1442
- private llmComponent?;
1443
- constructor();
1444
- /**
1445
- * Initialize the component
1446
- *
1447
- * 配置加载优先级(从高到低):
1448
- * 1. Object - 直接传入的 config 对象
1449
- * 2. Env - 环境变量(通过 envPrefix 配置前缀)
1450
- * 3. File - 配置文件(通过 configPath 指定)
1451
- */
1452
- init(config?: ComponentConfig): Promise<void>;
1453
- /**
1454
- * 获取默认 session 数据库路径
1455
- */
1456
- private getDefaultSessionDbPath;
1457
- /**
1458
- * 注册配置到 ConfigComponent
1459
- *
1460
- * 配置加载顺序(优先级从低到高):
1461
- * 1. Defaults - 默认值(最低)
1462
- * 2. FileSource - 从配置文件加载
1463
- * 3. EnvSource - 从环境变量加载
1464
- * 4. config 对象 - 直接传入的配置(最高)
1465
- */
1466
- private registerConfig;
1467
- /**
1468
- * 构建最终配置对象
1469
- */
1470
- private buildConfig;
1471
- /**
1472
- * 将配置对象展平为点号路径
1473
- */
1474
- private flattenConfig;
1475
- /**
1476
- * 注册配置热更新监听
1477
- */
1478
- private registerConfigWatcher;
1479
- /**
1480
- * 处理配置变更
1481
- */
1482
- protected onConfigChange(event: {
1483
- key: string;
1484
- oldValue?: unknown;
1485
- newValue?: unknown;
1486
- }): void;
1487
- /**
1488
- * Start the component
1489
- */
1490
- onStart(): Promise<void>;
1491
- /**
1492
- * Stop the component
1493
- */
1494
- onStop(): Promise<void>;
1495
- /**
1496
- * Create a new session
1497
- */
1498
- create(options?: CreateSessionOptions): Promise<Session>;
1499
- /**
1500
- * Get a session by ID
1501
- */
1502
- get(id: string): Promise<Session | undefined>;
1503
- /**
1504
- * Get a session with full context (for Memory Agent)
1505
- */
1506
- getSession(id: string): Promise<{
1507
- sessionId: string;
1508
- title: string;
1509
- messages: any[];
1510
- } | null>;
1511
- /**
1512
- * Search sessions by query (for Memory Agent)
1513
- *
1514
- * Simple implementation: list all sessions and return them for the agent to filter
1515
- */
1516
- searchSessions(query: string, options?: {
1517
- session_id?: string;
1518
- limit?: number;
1519
- }): Promise<Array<{
1520
- sessionId: string;
1521
- title: string;
1522
- preview: string;
1523
- timestamp: number;
1524
- }>>;
1525
- /**
1526
- * List all sessions
1527
- */
1528
- list(options?: ListSessionsOptions): Promise<Session[]>;
1529
- /**
1530
- * Get total session count
1531
- */
1532
- getCount(): Promise<number>;
1533
- /**
1534
- * Update a session
1535
- */
1536
- update(id: string, updates: UpdateSessionOptions): Promise<boolean>;
1537
- /**
1538
- * Delete a session
1539
- */
1540
- delete(id: string): Promise<boolean>;
1541
- /**
1542
- * Get the current active session
1543
- */
1544
- getActiveSession(): Session | undefined;
1545
- /**
1546
- * Get the active session ID
1547
- */
1548
- getActiveSessionId(): string | undefined;
1549
- /**
1550
- * Set the active session
1551
- */
1552
- setActiveSession(id: string): Promise<boolean>;
1553
- /**
1554
- * Add a message to a session
1555
- */
1556
- addMessage(sessionId: string, message: AddMessageOptions): Promise<string | undefined>;
1557
- /**
1558
- * Get messages from a session
1559
- */
1560
- getMessages(sessionId: string, options?: {
1561
- offset?: number;
1562
- limit?: number;
1563
- }): Promise<SessionMessage[]>;
1564
- /**
1565
- * Get message count for a session
1566
- */
1567
- getMessageCount(sessionId: string, includeArchived?: boolean): Promise<number>;
1568
- /**
1569
- * Get indexes of all messages with the specified role
1570
- * @param sessionId - Session ID
1571
- * @param role - Role to filter by (e.g., "user", "assistant")
1572
- * @returns Array of message indexes (0-indexed, in chronological order)
1573
- */
1574
- getMessageIndexes(sessionId: string, role: string): Promise<number[]>;
1575
- private executeBeforeHooks;
1576
- private executeAfterHooks;
1577
- private generateTitle;
1578
- /**
1579
- * Set components for SummaryAgent
1580
- *
1581
- * Call this after initialization if you need compact functionality
1582
- */
1583
- setSummaryComponents(promptComponent: any, llmComponent: any): void;
1584
- /**
1585
- * 初始化 SummaryAgent(如未初始化)
1586
- */
1587
- private ensureSummaryAgent;
1588
- /**
1589
- * 生成场景化压缩提示 (Compact Hint)
1590
- *
1591
- * 两阶段自动压缩的第一阶段:
1592
- * 根据会话历史生成场景化的压缩提示
1593
- *
1594
- * @param sessionId 会话 ID
1595
- * @returns 生成的场景化提示
1596
- */
1597
- generateCompactHint(sessionId: string): Promise<string>;
1598
- /**
1599
- * Compact a session
1600
- *
1601
- * 1. Get messages from latest checkpoint to current
1602
- * 2. Call Summary Agent to generate checkpoint
1603
- * 3. Save checkpoint and archive messages
1604
- *
1605
- * 支持 scenarioHint 参数,用于指导不同场景下的压缩重点提取
1606
- */
1607
- compact(sessionId: string, options?: CompactOptions): Promise<CompactResult>;
1608
- /**
1609
- * Extract recent messages from the conversation for checkpoint context
1610
- *
1611
- * Extracts the last N turns of user query + assistant text response,
1612
- * excluding tool calls and tool results.
1613
- *
1614
- * @param messages - All messages in the conversation
1615
- * @param turnCount - Number of turns to extract (default: 2)
1616
- * @returns Array of recent messages formatted as { role, content }
1617
- */
1618
- private extractRecentMessages;
1619
- /**
1620
- * Preview compact operation
1621
- */
1622
- previewCompact(sessionId: string): Promise<CompactPreview>;
1623
- /**
1624
- * Get all checkpoints for a session
1625
- */
1626
- getCheckpoints(sessionId: string): Promise<SessionCheckpoint[]>;
1627
- /**
1628
- * Get a specific checkpoint
1629
- */
1630
- getCheckpoint(sessionId: string, checkpointId: string): Promise<SessionCheckpoint | undefined>;
1631
- /**
1632
- * Delete a checkpoint and restore archived messages
1633
- */
1634
- deleteCheckpoint(sessionId: string, checkpointId: string): Promise<boolean>;
1635
- /**
1636
- * Get session context
1637
- *
1638
- * Returns messages starting from the latest checkpoint by default
1639
- */
1640
- getContext(sessionId: string, options?: GetContextOptions): Promise<GetContextResult>;
1641
- /**
1642
- * Check if session needs compaction
1643
- */
1644
- shouldCompact(sessionId: string): Promise<boolean>;
1645
- /**
1646
- * Search messages across sessions
1647
- *
1648
- * Searches all messages matching the query, aggregated by session.
1649
- * Supports SQLite FTS5 for fast full-text search.
1650
- */
1651
- searchMessages(options: SearchMessagesOptions): Promise<SearchResult[]>;
1652
- /**
1653
- * Get latest checkpoint from session
1654
- */
1655
- private getLatestCheckpoint;
1656
- /**
1657
- * Create checkpoint message (user role)
1658
- *
1659
- * Generates a markdown-formatted checkpoint summary as a user message,
1660
- * allowing it to appear in the message list and provide context for
1661
- * subsequent LLM calls.
1662
- */
1663
- private createCheckpointMessage;
1664
- }
1665
- interface ModelMessage2 {
1666
- role: "user" | "assistant" | "system" | "tool";
1667
- content: string | ModelContentPart[];
1668
- }
1669
- /**
1670
- * Content part for AI SDK ModelMessage
1671
- */
1672
- type ModelContentPart = TextContentPart | ReasoningContentPart | ToolCallContentPart | ToolResultContentPart | FileContentPart;
1673
- interface TextContentPart {
1674
- type: "text";
1675
- text: string;
1676
- synthetic?: boolean;
1677
- }
1678
- interface ReasoningContentPart {
1679
- type: "reasoning";
1680
- text: string;
1681
- reasoningType?: "core" | "effort" | "summary";
1682
- }
1683
- interface ToolCallContentPart {
1684
- type: "tool-call";
1685
- toolCallId: string;
1686
- toolName: string;
1687
- input: Record<string, unknown>;
1688
- }
1689
- interface ToolResultContentPart {
1690
- type: "tool-result";
1691
- toolCallId: string;
1692
- toolName: string;
1693
- output: string;
1694
- }
1695
- interface FileContentPart {
1696
- type: "file";
1697
- url: string;
1698
- mimeType?: string;
1699
- filename?: string;
1700
- }
1701
- /**
1702
- * SessionMessageConverter
1703
- *
1704
- * Converts between SessionMessage (storage format) and AI SDK ModelMessage (LLM format).
1705
- *
1706
- * @example
1707
- * ```typescript
1708
- * const converter = new SessionMessageConverter();
1709
- * const modelMsg = converter.toModelMessage(sessionMsg);
1710
- * const sessionMsg = converter.fromModelMessage(modelMsg);
1711
- * ```
1712
- */
1713
- declare class SessionMessageConverter {
1714
- /**
1715
- * Convert a SessionMessage to AI SDK ModelMessage format
1716
- *
1717
- * @param msg - SessionMessage to convert
1718
- * @returns ModelMessage compatible with AI SDK v6
1719
- */
1720
- toModelMessage(msg: SessionMessage): ModelMessage2;
1721
- /**
1722
- * Convert an AI SDK ModelMessage to SessionMessage format
1723
- *
1724
- * @param aiMsg - AI SDK ModelMessage to convert (accepts any object with role and content)
1725
- * @param options - Optional sessionID and messageID
1726
- * @returns SessionMessage compatible with storage format
1727
- *
1728
- * 设置 metadata.type 以便后续正确过滤:
1729
- * - "tool_call": assistant 消息包含 tool-call parts
1730
- * - "tool_result": tool 消息
1731
- */
1732
- fromModelMessage(aiMsg: {
1733
- role: string;
1734
- content: unknown;
1735
- [key: string]: unknown;
1736
- }, options?: {
1737
- sessionID?: string;
1738
- messageID?: string;
1739
- }): SessionMessage;
1740
- /**
1741
- * Convert a list of SessionMessages to AI SDK history format
1742
- *
1743
- * @param messages - Array of SessionMessages to convert
1744
- * @returns Array of ModelMessages filtered by archived status
1745
- */
1746
- sessionToHistory(messages: SessionMessage[]): ModelMessage2[];
1747
- /**
1748
- * Extract provider-specific options from SessionMessage
1749
- *
1750
- * Some models (e.g., DeepSeek R1, Kimi k2.5) require reasoning configuration
1751
- * through providerOptions.
1752
- *
1753
- * @param msg - SessionMessage to extract options from
1754
- * @returns Provider-specific options object for LLM calls
1755
- */
1756
- extractProviderOptions(msg: SessionMessage): Record<string, unknown>;
1757
- /**
1758
- * Migrate old format message to new format
1759
- *
1760
- * Handles backward compatibility by converting old messages with just content
1761
- * to new format with proper parts array.
1762
- *
1763
- * @param oldMsg - Message in possibly old format
1764
- * @returns Message in new format with parts array
1765
- */
1766
- migrateMessage(oldMsg: Partial<SessionMessage>): SessionMessage;
1767
- }
1768
- /**
1769
- * Session Store Interface
1770
- * Defines the contract for session storage implementations
1771
- */
1772
- interface SessionStore {
1773
- /**
1774
- * Create a new session
1775
- */
1776
- create(options: CreateSessionOptions): Promise<Session>;
1777
- /**
1778
- * Get a session by ID
1779
- */
1780
- get(id: string): Promise<Session | undefined>;
1781
- /**
1782
- * List sessions with optional filtering
1783
- */
1784
- list(options?: ListSessionsOptions): Promise<Session[]>;
1785
- /**
1786
- * Update a session
1787
- */
1788
- update(id: string, updates: UpdateSessionOptions): Promise<boolean>;
1789
- /**
1790
- * Delete a session
1791
- */
1792
- delete(id: string): Promise<boolean>;
1793
- /**
1794
- * Get total session count (without pagination)
1795
- */
1796
- getCount(): Promise<number>;
1797
- /**
1798
- * Add a message to a session
1799
- */
1800
- addMessage(sessionId: string, message: {
1801
- role: string;
1802
- content: string;
1803
- parts?: unknown[];
1804
- metadata?: Record<string, unknown>;
1805
- }): Promise<string>;
1806
- /**
1807
- * Get messages from a session
1808
- * @param sessionId - Session ID
1809
- * @param offset - Starting index
1810
- * @param limit - Number of messages to return
1811
- * @param options - Additional options (includeArchived, fromCheckpointId, reverse)
1812
- */
1813
- getMessages(sessionId: string, offset?: number, limit?: number, options?: GetMessagesOptions): Promise<SessionMessage[]>;
1814
- /**
1815
- * Get message indexes by role
1816
- * @param sessionId - Session ID
1817
- * @param role - Role to filter by
1818
- */
1819
- getMessageIndexes(sessionId: string, role: string): Promise<number[]>;
1820
- /**
1821
- * Get message count for a session
1822
- * @param sessionId - Session ID
1823
- * @param includeArchived - Whether to include archived messages
1824
- */
1825
- getMessageCount(sessionId: string, includeArchived?: boolean): Promise<number>;
1826
- /**
1827
- * Save a checkpoint to session metadata
1828
- */
1829
- saveCheckpoint(sessionId: string, checkpoint: SessionCheckpoint): Promise<void>;
1830
- /**
1831
- * Get all checkpoints for a session
1832
- */
1833
- getCheckpoints(sessionId: string): Promise<SessionCheckpoint[]>;
1834
- /**
1835
- * Get a specific checkpoint
1836
- */
1837
- getCheckpoint(sessionId: string, checkpointId: string): Promise<SessionCheckpoint | undefined>;
1838
- /**
1839
- * Delete a checkpoint and restore archived messages
1840
- */
1841
- deleteCheckpoint(sessionId: string, checkpointId: string): Promise<boolean>;
1842
- /**
1843
- * Archive messages (mark as archived for compact)
1844
- * @returns Number of messages archived
1845
- */
1846
- archiveMessages(sessionId: string, checkpointId: string, beforeIndex: number): Promise<number>;
1847
- /**
1848
- * Get active (non-archived) messages only
1849
- */
1850
- getActiveMessages(sessionId: string, offset?: number, limit?: number): Promise<SessionMessage[]>;
1851
- /**
1852
- * Close and cleanup resources
1853
- */
1854
- close(): Promise<void>;
1855
- /**
1856
- * Search messages across all sessions
1857
- *
1858
- * @param options - Search options including query, session filter, time range
1859
- * @returns Array of message matches
1860
- */
1861
- searchMessages(options: SearchMessagesOptions): Promise<MessageMatch[]>;
1862
- }
1863
- /**
1864
- * Memory-based Session Store with checkpoint support
1865
- */
1866
- declare class MemorySessionStore implements SessionStore {
1867
- private sessions;
1868
- private messages;
1869
- private checkpoints;
1870
- private messageConverter;
1871
- create(options: CreateSessionOptions): Promise<Session>;
1872
- get(id: string): Promise<Session | undefined>;
1873
- list(options?: ListSessionsOptions): Promise<Session[]>;
1874
- update(id: string, updates: UpdateSessionOptions): Promise<boolean>;
1875
- delete(id: string): Promise<boolean>;
1876
- getCount(): Promise<number>;
1877
- addMessage(sessionId: string, message: {
1878
- role: string;
1879
- content: string;
1880
- parts?: unknown[];
1881
- metadata?: Record<string, unknown>;
1882
- }): Promise<string>;
1883
- getMessages(sessionId: string, offset?: number, limit?: number, options?: GetMessagesOptions): Promise<SessionMessage[]>;
1884
- getMessageCount(sessionId: string, includeArchived?: boolean): Promise<number>;
1885
- getMessageIndexes(sessionId: string, role: string): Promise<number[]>;
1886
- saveCheckpoint(sessionId: string, checkpoint: SessionCheckpoint): Promise<void>;
1887
- getCheckpoints(sessionId: string): Promise<SessionCheckpoint[]>;
1888
- getCheckpoint(sessionId: string, checkpointId: string): Promise<SessionCheckpoint | undefined>;
1889
- deleteCheckpoint(sessionId: string, checkpointId: string): Promise<boolean>;
1890
- archiveMessages(sessionId: string, checkpointId: string, beforeIndex: number): Promise<number>;
1891
- getActiveMessages(sessionId: string, offset?: number, limit?: number): Promise<SessionMessage[]>;
1892
- searchMessages(options: SearchMessagesOptions): Promise<MessageMatch[]>;
1893
- /**
1894
- * Parse simple query into terms
1895
- */
1896
- private parseQuery;
1897
- close(): Promise<void>;
1898
- }
1899
- type SessionHookType2 = SessionHookType;
1900
- type SessionHookContext3 = SessionHookContext2;
1901
- /**
1902
- * Session hook registration
1903
- */
1904
- interface SessionHookRegistration {
1905
- type: SessionHookType2;
1906
- hook: Hook;
1907
- }
1908
- export { UpdateSessionOptions, SessionStore, SessionMessageConverter, SessionMessage, SessionHookType2 as SessionHookType, SessionHookRegistration, SessionHookContext3 as SessionHookContext, SessionConfig, SessionComponent, SessionCheckpointsMeta, SessionCheckpoint, Session, MemorySessionStore, ListSessionsOptions, GetMessagesOptions, GetContextResult, GetContextOptions, CreateSessionOptions, CompactResult, CompactPreview, CompactOptions, AddMessageOptions };