@ai-setting/roy-agent-core 1.5.14-test → 1.5.15-test

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 (141) hide show
  1. package/package.json +1 -1
  2. package/dist/config/index.d.ts +0 -1250
  3. package/dist/config/index.js +0 -32
  4. package/dist/env/agent/index.d.ts +0 -2279
  5. package/dist/env/agent/index.js +0 -24
  6. package/dist/env/commands/index.d.ts +0 -1131
  7. package/dist/env/commands/index.js +0 -14
  8. package/dist/env/debug/formatters/index.d.ts +0 -236
  9. package/dist/env/debug/formatters/index.js +0 -11
  10. package/dist/env/debug/index.d.ts +0 -1652
  11. package/dist/env/debug/index.js +0 -26
  12. package/dist/env/hook/index.d.ts +0 -279
  13. package/dist/env/hook/index.js +0 -29
  14. package/dist/env/index.d.ts +0 -3481
  15. package/dist/env/index.js +0 -82
  16. package/dist/env/llm/index.d.ts +0 -1760
  17. package/dist/env/llm/index.js +0 -40
  18. package/dist/env/log-trace/index.d.ts +0 -1574
  19. package/dist/env/log-trace/index.js +0 -83
  20. package/dist/env/mcp/index.d.ts +0 -1331
  21. package/dist/env/mcp/index.js +0 -39
  22. package/dist/env/mcp/tool/index.d.ts +0 -183
  23. package/dist/env/mcp/tool/index.js +0 -14
  24. package/dist/env/memory/built-in/index.d.ts +0 -232
  25. package/dist/env/memory/built-in/index.js +0 -11
  26. package/dist/env/memory/index.d.ts +0 -1799
  27. package/dist/env/memory/index.js +0 -56
  28. package/dist/env/memory/plugin/index.d.ts +0 -747
  29. package/dist/env/memory/plugin/index.js +0 -36
  30. package/dist/env/prompt/index.d.ts +0 -1164
  31. package/dist/env/prompt/index.js +0 -20
  32. package/dist/env/session/index.d.ts +0 -1908
  33. package/dist/env/session/index.js +0 -25
  34. package/dist/env/session/storage/index.d.ts +0 -564
  35. package/dist/env/session/storage/index.js +0 -18
  36. package/dist/env/skill/index.d.ts +0 -1266
  37. package/dist/env/skill/index.js +0 -34
  38. package/dist/env/skill/tool/index.d.ts +0 -193
  39. package/dist/env/skill/tool/index.js +0 -9
  40. package/dist/env/task/delegate/index.d.ts +0 -1612
  41. package/dist/env/task/delegate/index.js +0 -18
  42. package/dist/env/task/events/index.d.ts +0 -171
  43. package/dist/env/task/events/index.js +0 -7
  44. package/dist/env/task/hooks/index.d.ts +0 -624
  45. package/dist/env/task/hooks/index.js +0 -7
  46. package/dist/env/task/index.d.ts +0 -1553
  47. package/dist/env/task/index.js +0 -34
  48. package/dist/env/task/plugins/index.d.ts +0 -466
  49. package/dist/env/task/plugins/index.js +0 -23
  50. package/dist/env/task/storage/index.d.ts +0 -241
  51. package/dist/env/task/storage/index.js +0 -14
  52. package/dist/env/task/tools/index.d.ts +0 -1485
  53. package/dist/env/task/tools/index.js +0 -17
  54. package/dist/env/task/tools/operation/index.d.ts +0 -1484
  55. package/dist/env/task/tools/operation/index.js +0 -15
  56. package/dist/env/tool/built-in/index.d.ts +0 -218
  57. package/dist/env/tool/built-in/index.js +0 -25
  58. package/dist/env/tool/index.d.ts +0 -1396
  59. package/dist/env/tool/index.js +0 -39
  60. package/dist/env/workflow/decorators/index.d.ts +0 -2161
  61. package/dist/env/workflow/decorators/index.js +0 -27
  62. package/dist/env/workflow/engine/index.d.ts +0 -3453
  63. package/dist/env/workflow/engine/index.js +0 -28
  64. package/dist/env/workflow/index.d.ts +0 -3546
  65. package/dist/env/workflow/index.js +0 -136
  66. package/dist/env/workflow/nodes/index.d.ts +0 -2092
  67. package/dist/env/workflow/nodes/index.js +0 -19
  68. package/dist/env/workflow/service/index.d.ts +0 -227
  69. package/dist/env/workflow/service/index.js +0 -13
  70. package/dist/env/workflow/storage/index.d.ts +0 -165
  71. package/dist/env/workflow/storage/index.js +0 -27
  72. package/dist/env/workflow/tools/index.d.ts +0 -416
  73. package/dist/env/workflow/tools/index.js +0 -159
  74. package/dist/env/workflow/types/index.d.ts +0 -2255
  75. package/dist/env/workflow/types/index.js +0 -98
  76. package/dist/env/workflow/utils/index.d.ts +0 -2031
  77. package/dist/env/workflow/utils/index.js +0 -637
  78. package/dist/index.d.ts +0 -7858
  79. package/dist/index.js +0 -399
  80. package/dist/shared/@ai-setting/roy-agent-core-0rtxwr28.js +0 -258
  81. package/dist/shared/@ai-setting/roy-agent-core-0vbdz0x7.js +0 -36
  82. package/dist/shared/@ai-setting/roy-agent-core-1akcqxj9.js +0 -349
  83. package/dist/shared/@ai-setting/roy-agent-core-1ce3fqrk.js +0 -117
  84. package/dist/shared/@ai-setting/roy-agent-core-2dhd60aw.js +0 -11
  85. package/dist/shared/@ai-setting/roy-agent-core-3jywqmdd.js +0 -393
  86. package/dist/shared/@ai-setting/roy-agent-core-3rr5k71j.js +0 -200
  87. package/dist/shared/@ai-setting/roy-agent-core-44hnfb02.js +0 -299
  88. package/dist/shared/@ai-setting/roy-agent-core-4t40mkpv.js +0 -206
  89. package/dist/shared/@ai-setting/roy-agent-core-4txzpsbt.js +0 -393
  90. package/dist/shared/@ai-setting/roy-agent-core-5x94xmt6.js +0 -350
  91. package/dist/shared/@ai-setting/roy-agent-core-69jskqjg.js +0 -180
  92. package/dist/shared/@ai-setting/roy-agent-core-6kvtahqv.js +0 -408
  93. package/dist/shared/@ai-setting/roy-agent-core-7fgf85wc.js +0 -284
  94. package/dist/shared/@ai-setting/roy-agent-core-81w1963m.js +0 -762
  95. package/dist/shared/@ai-setting/roy-agent-core-8gxth0eh.js +0 -10
  96. package/dist/shared/@ai-setting/roy-agent-core-92z6t4he.js +0 -14
  97. package/dist/shared/@ai-setting/roy-agent-core-93zfb3r1.js +0 -922
  98. package/dist/shared/@ai-setting/roy-agent-core-9yxb3ty9.js +0 -15
  99. package/dist/shared/@ai-setting/roy-agent-core-b0x5dda6.js +0 -1130
  100. package/dist/shared/@ai-setting/roy-agent-core-bcbqy27c.js +0 -14
  101. package/dist/shared/@ai-setting/roy-agent-core-bvr1761x.js +0 -653
  102. package/dist/shared/@ai-setting/roy-agent-core-ctdhjv68.js +0 -93
  103. package/dist/shared/@ai-setting/roy-agent-core-d7cyjkf7.js +0 -872
  104. package/dist/shared/@ai-setting/roy-agent-core-dh9d7a3m.js +0 -11
  105. package/dist/shared/@ai-setting/roy-agent-core-e25xkv53.js +0 -64
  106. package/dist/shared/@ai-setting/roy-agent-core-eajcvp4e.js +0 -378
  107. package/dist/shared/@ai-setting/roy-agent-core-f7q2x5z6.js +0 -492
  108. package/dist/shared/@ai-setting/roy-agent-core-fs0mn2jk.js +0 -52
  109. package/dist/shared/@ai-setting/roy-agent-core-g1s2h0e5.js +0 -171
  110. package/dist/shared/@ai-setting/roy-agent-core-g99pxzn5.js +0 -862
  111. package/dist/shared/@ai-setting/roy-agent-core-gbqcyegm.js +0 -1387
  112. package/dist/shared/@ai-setting/roy-agent-core-gjq1yk68.js +0 -208
  113. package/dist/shared/@ai-setting/roy-agent-core-gq20wsgv.js +0 -139
  114. package/dist/shared/@ai-setting/roy-agent-core-gwc4h96n.js +0 -534
  115. package/dist/shared/@ai-setting/roy-agent-core-jfh9q2qh.js +0 -204
  116. package/dist/shared/@ai-setting/roy-agent-core-jvatggbb.js +0 -603
  117. package/dist/shared/@ai-setting/roy-agent-core-kkbwepqb.js +0 -97
  118. package/dist/shared/@ai-setting/roy-agent-core-pjr12nnd.js +0 -587
  119. package/dist/shared/@ai-setting/roy-agent-core-psv4v63c.js +0 -176
  120. package/dist/shared/@ai-setting/roy-agent-core-psvxt4c9.js +0 -60
  121. package/dist/shared/@ai-setting/roy-agent-core-qqceba6k.js +0 -442
  122. package/dist/shared/@ai-setting/roy-agent-core-qxhq8ven.js +0 -57
  123. package/dist/shared/@ai-setting/roy-agent-core-qxnbvgwe.js +0 -66
  124. package/dist/shared/@ai-setting/roy-agent-core-r9ezzemr.js +0 -10
  125. package/dist/shared/@ai-setting/roy-agent-core-rhmtwnw1.js +0 -267
  126. package/dist/shared/@ai-setting/roy-agent-core-rvv6ydff.js +0 -584
  127. package/dist/shared/@ai-setting/roy-agent-core-rvxg1wps.js +0 -102
  128. package/dist/shared/@ai-setting/roy-agent-core-satmq6sh.js +0 -549
  129. package/dist/shared/@ai-setting/roy-agent-core-sx7wsvnn.js +0 -15
  130. package/dist/shared/@ai-setting/roy-agent-core-t94ktchq.js +0 -213
  131. package/dist/shared/@ai-setting/roy-agent-core-vf215qfv.js +0 -812
  132. package/dist/shared/@ai-setting/roy-agent-core-vkz81f7v.js +0 -1316
  133. package/dist/shared/@ai-setting/roy-agent-core-vn2bc59q.js +0 -1205
  134. package/dist/shared/@ai-setting/roy-agent-core-wa1kzqky.js +0 -328
  135. package/dist/shared/@ai-setting/roy-agent-core-wft9ra24.js +0 -20
  136. package/dist/shared/@ai-setting/roy-agent-core-wrcy0h6z.js +0 -2098
  137. package/dist/shared/@ai-setting/roy-agent-core-xq8hhqb8.js +0 -419
  138. package/dist/shared/@ai-setting/roy-agent-core-xs5rsgat.js +0 -368
  139. package/dist/shared/@ai-setting/roy-agent-core-zbkpc41z.js +0 -377
  140. package/dist/shared/@ai-setting/roy-agent-core-zgypchmt.js +0 -172
  141. package/dist/shared/@ai-setting/roy-agent-core-zpn0bqa8.js +0 -103
@@ -1,2031 +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 } from "zod";
207
- declare const WorkflowEventSchema: unknown;
208
- type WorkflowEvent = z.infer<typeof WorkflowEventSchema>;
209
- type EventHandler = (event: WorkflowEvent) => void | Promise<void>;
210
- /**
211
- * EventBus for workflow events.
212
- * Custom event bus implementation with support for wildcard subscriptions.
213
- */
214
- declare class EventBus {
215
- private handlers;
216
- private wildcardHandlers;
217
- constructor();
218
- /**
219
- * Subscribe to a specific event type.
220
- * @returns Unsubscribe function
221
- */
222
- on(eventType: string, handler: EventHandler): () => void;
223
- /**
224
- * Subscribe to an event type only once (auto-unsubscribe after first call).
225
- * @returns Unsubscribe function
226
- */
227
- once(eventType: string, handler: EventHandler): () => void;
228
- /**
229
- * Unsubscribe from an event type.
230
- */
231
- off(eventType: string, handler: EventHandler): void;
232
- /**
233
- * Subscribe to all events (wildcard subscription).
234
- * @returns Unsubscribe function
235
- */
236
- onAny(handler: EventHandler): () => void;
237
- /**
238
- * Publish an event to all subscribers.
239
- * Handler errors are caught and do not crash the bus.
240
- *
241
- * @param event - The event to publish
242
- * @param waitForHandlers - If true, waits for all async handlers to complete (default: false)
243
- */
244
- publish(event: WorkflowEvent, waitForHandlers?: boolean): Promise<void>;
245
- /**
246
- * Execute a handler safely, catching any errors.
247
- */
248
- private executeHandler;
249
- /**
250
- * Clear all subscriptions.
251
- */
252
- clear(): void;
253
- /**
254
- * Get statistics about the event bus.
255
- */
256
- getStats(): {
257
- eventTypes: number;
258
- wildcardHandlers: number;
259
- totalHandlers: number;
260
- };
261
- }
262
- import { ZodType as ZodType3, ZodTypeDef as ZodTypeDef2 } from "zod";
263
- /**
264
- * @fileoverview Environment types and interfaces
265
- *
266
- * 定义 Environment 的核心类型,包括:
267
- * - Environment 配置
268
- * - EnvEvent 事件类型
269
- */
270
- /**
271
- * Environment Config
272
- */
273
- interface EnvironmentConfig {
274
- /** 环境名称 */
275
- name: string;
276
- /** 环境版本 */
277
- version: string;
278
- /** 是否启用 */
279
- enabled: boolean;
280
- }
281
- /**
282
- * EnvEvent 元信息
283
- */
284
- interface EnvEventMetadata {
285
- /** 触发事件的 session ID */
286
- trigger_session_id?: string;
287
- /** 触发事件的 agent ID */
288
- trigger_agent_id?: string;
289
- /** Agent 名称 */
290
- trigger_agent_name?: string;
291
- /** 环境名称 */
292
- env_name?: string;
293
- /** 事件来源 */
294
- source?: string;
295
- /** 其他元数据 */
296
- [key: string]: unknown;
297
- }
298
- /**
299
- * EnvEvent
300
- *
301
- * 统一的事件机制,用于:
302
- * - Stream 事件(stream.start, stream.text, stream.completed 等)
303
- * - 工具调用事件(tool.call, tool.result 等)
304
- * - 会话事件(session.created, session.updated 等)
305
- * - Agent 事件(agent.thinking, agent.acting 等)
306
- */
307
- interface EnvEvent<T = unknown> {
308
- /** 事件 ID */
309
- id: string;
310
- /** 事件类型 */
311
- type: string;
312
- /** 时间戳 */
313
- timestamp: number;
314
- /** 元信息 */
315
- metadata: EnvEventMetadata;
316
- /** 事件负载 */
317
- payload: T;
318
- }
319
- /**
320
- * EnvEvent Handler
321
- */
322
- type EnvEventHandler = (event: EnvEvent) => void | Promise<void>;
323
- /**
324
- * EnvEvent 创建参数(部分属性,可选)
325
- *
326
- * 用于 pushEnvEvent 方法,允许传入部分属性,自动补全必填字段
327
- */
328
- interface EnvEventInput {
329
- /** 事件类型(必填) */
330
- type: string;
331
- /** 事件 ID(可选,自动生成) */
332
- id?: string;
333
- /** 时间戳(可选,自动生成) */
334
- timestamp?: number;
335
- /** 元信息(可选,自动创建) */
336
- metadata?: EnvEventMetadata;
337
- /** 事件负载(可选) */
338
- payload?: unknown;
339
- }
340
- /**
341
- * Action 类型
342
- */
343
- interface Action {
344
- /** Action 类型 */
345
- type: string;
346
- /** Action 参数 */
347
- params?: Record<string, unknown>;
348
- }
349
- /**
350
- * Tool Result
351
- */
352
- interface ToolResult {
353
- /** 是否成功 */
354
- success: boolean;
355
- /** 输出内容 */
356
- output: string | Record<string, unknown>;
357
- /** 错误信息 */
358
- error?: string;
359
- }
360
- /**
361
- * Context
362
- */
363
- interface Context {
364
- /** 会话 ID */
365
- sessionId?: string;
366
- /** 用户 ID */
367
- userId?: string;
368
- /** 工作目录 */
369
- workdir?: string;
370
- /** 中断信号 */
371
- abort?: AbortSignal;
372
- /** 元数据 */
373
- metadata?: Record<string, unknown>;
374
- }
375
- type AbortSignalType = AbortSignal;
376
- /**
377
- * Agent 执行上下文
378
- */
379
- interface AgentContext {
380
- /** 会话 ID */
381
- sessionId?: string;
382
- /** 消息 ID */
383
- messageId?: string;
384
- /** 中断信号 */
385
- abort?: AbortSignalType;
386
- /** 额外的上下文信息(会添加到 system prompt) */
387
- additionInfo?: string;
388
- /** 元数据 */
389
- metadata?: Record<string, unknown>;
390
- /** Agent 类型(用于选择 Behavior Spec) */
391
- agentType?: string;
392
- /** 使用的模型 */
393
- model?: string;
394
- /** 允许的工具列表(上下文级别,会覆盖 agent 配置) */
395
- allowedTools?: string[];
396
- /** 拒绝的工具列表(上下文级别,会覆盖 agent 配置) */
397
- deniedTools?: string[];
398
- /** 是否过滤 history 中的 tool 消息(上下文级别,会覆盖 agent 配置) */
399
- filterHistory?: boolean;
400
- }
401
- import { ZodType as ZodType2, ZodTypeDef } from "zod";
402
- /**
403
- * ConfigSource 类型
404
- */
405
- type ConfigSourceType = "memory" | "file" | "env" | "remote";
406
- /**
407
- * SourceRegistration - Source 注册配置
408
- */
409
- interface SourceRegistration {
410
- /** Source 类型 */
411
- type: ConfigSourceType;
412
- /** 相对路径(file 类型使用,基于 XDG_DATA_HOME) */
413
- relativePath?: string;
414
- /** 环境变量前缀(env 类型使用) */
415
- envPrefix?: string;
416
- /** 优先级,默认值:memory=0, file=10, env=20 */
417
- priority?: number;
418
- /** 是否可选(file 类型使用,文件不存在时不报错) */
419
- optional?: boolean;
420
- /** 是否启用文件监听(file 类型使用,默认 true) */
421
- watch?: boolean;
422
- }
423
- /**
424
- * KeyRegistration - 配置 Key 注册
425
- */
426
- interface KeyRegistration {
427
- /** 配置 Key(支持点号嵌套,如 "llm.provider") */
428
- key: string;
429
- /** 优先使用的 Source 列表(按优先级从低到高) */
430
- sources: ConfigSourceType[];
431
- /** 自定义优先级(覆盖默认优先级) */
432
- priority?: number;
433
- /** 默认值 */
434
- default?: unknown;
435
- }
436
- /**
437
- * ComponentRegistration - Component 注册配置
438
- */
439
- interface ComponentRegistration {
440
- /** Component 名称 */
441
- name: string;
442
- /** 声明需要的 Source */
443
- sources: SourceRegistration[];
444
- /** 声明需要的配置 Key */
445
- keys: KeyRegistration[];
446
- /** 配置 Schema(用于验证,可选) */
447
- schema?: ZodType2<unknown, ZodTypeDef, unknown>;
448
- /** 默认值 */
449
- defaults?: Record<string, unknown>;
450
- }
451
- /**
452
- * ConfigSource 接口
453
- */
454
- interface ConfigSource {
455
- readonly name: ConfigSourceType;
456
- readonly priority: number;
457
- read(key: string): unknown | undefined;
458
- write?(key: string, value: unknown): boolean;
459
- delete?(key: string): boolean;
460
- list(): Array<{
461
- key: string;
462
- value: unknown;
463
- }>;
464
- watch?(callback: (event: ConfigChangeEvent) => void): () => void;
465
- }
466
- /**
467
- * Config 变更事件
468
- */
469
- interface ConfigChangeEvent {
470
- type: "change" | "add" | "delete";
471
- key: string;
472
- oldValue: unknown;
473
- newValue: unknown;
474
- source: ConfigSourceType;
475
- timestamp: number;
476
- }
477
- /**
478
- * ConfigComponent 配置
479
- */
480
- interface ConfigComponentOptions {
481
- /** 持久化文件路径 */
482
- persistFile?: string;
483
- /** 防抖延迟(ms) */
484
- debounceMs?: number;
485
- /** 最大批量大小 */
486
- maxBatchSize?: number;
487
- }
488
- /**
489
- * ConfigComponent
490
- */
491
- declare class ConfigComponent extends BaseComponent {
492
- readonly name = "config";
493
- readonly version = "1.0.0";
494
- private memorySource;
495
- private sources;
496
- private componentSchemas;
497
- private componentPaths;
498
- private watchers;
499
- /** Source watch unsubscribe 函数 */
500
- private sourceUnwatchFns;
501
- private persistQueue;
502
- private persistFile?;
503
- /** Key 注册表:key -> KeyRegistration */
504
- private keyRegistry;
505
- /** Component 注册表:name -> ComponentRegistration */
506
- private componentRegistrations;
507
- /** 协议解析器 */
508
- private protocolResolver?;
509
- /** XDG_DATA_HOME 缓存(用于测试注入) */
510
- private __xdgDataHome?;
511
- /** Source 注册配置(延迟创建) */
512
- private pendingSources;
513
- /** Source 唯一标识缓存:type:relativePath -> true */
514
- private sourceKeys;
515
- /**
516
- * 获取 XDG_DATA_HOME(动态获取,支持运行时覆盖)
517
- */
518
- getXdgDataHome(): string;
519
- /**
520
- * 设置 XDG_DATA_HOME(用于测试)
521
- */
522
- setXdgDataHome(path: string): void;
523
- constructor(options?: ConfigComponentOptions);
524
- /**
525
- * 注册 Component Schema
526
- */
527
- register(schema: ComponentSchema): void;
528
- /**
529
- * 注销 Component
530
- */
531
- unregister(name: string): boolean;
532
- /**
533
- * 检查是否已注册
534
- */
535
- isRegistered(name: string): boolean;
536
- /**
537
- * 列出所有注册的 Component
538
- */
539
- listComponents(): string[];
540
- /**
541
- * 获取配置值(支持 xxx.yyy.zzz 嵌套访问)
542
- * 支持两种模式:
543
- * 1. 完整 key:直接查找,如 "component.key" -> 读取 "component.key"
544
- * 2. 嵌套对象:查找 component 对象后从中获取属性,如 "component.nested.deep"
545
- * -> 先找 "component.nested",再获取其 "deep" 属性
546
- */
547
- get(key: string): unknown;
548
- /**
549
- * 批量获取
550
- */
551
- getMany(keys: string[]): Record<string, unknown>;
552
- /**
553
- * 设置配置值(内存级别 + 异步持久化)
554
- */
555
- set(key: string, value: unknown): Promise<void>;
556
- /**
557
- * 批量设置
558
- */
559
- setMany(config: Record<string, unknown>): Promise<void>;
560
- /**
561
- * 获取 Component 的路径
562
- */
563
- getPath(component: string, subPath?: string): string;
564
- /**
565
- * 手动持久化
566
- */
567
- save(key?: string): Promise<void>;
568
- /**
569
- * 重置到默认值
570
- */
571
- reset(key: string): Promise<void>;
572
- /**
573
- * 监听配置变更
574
- */
575
- watch(pattern: string, callback: ComponentWatchCallback): () => void;
576
- /**
577
- * 添加配置源
578
- */
579
- addSource(source: ConfigSource): void;
580
- /**
581
- * 获取 Source 唯一标识
582
- */
583
- private getSourceKey;
584
- /**
585
- * 移除配置源
586
- */
587
- removeSource(name: ConfigSourceType): boolean;
588
- /**
589
- * 关闭所有配置源的 watcher(用于优雅退出)
590
- */
591
- unwatchAll(): void;
592
- /**
593
- * 获取配置源列表
594
- */
595
- getSources(): ConfigSource[];
596
- private getNestedValue;
597
- private notifyWatchers;
598
- private persistToFile;
599
- /**
600
- * 注册配置 Source
601
- *
602
- * Source 会在首次 load() 时被创建
603
- *
604
- * @example
605
- * config.registerSource({ type: "file", relativePath: "llm-config.jsonc" });
606
- * config.registerSource({ type: "env", envPrefix: "LLM" });
607
- */
608
- registerSource(registration: SourceRegistration): void;
609
- /**
610
- * 创建 Source 实例
611
- */
612
- private createSource;
613
- /**
614
- * 确保所有待创建的 Source 已被创建
615
- */
616
- private ensureSourcesCreated;
617
- /**
618
- * 注册配置 Key
619
- *
620
- * @example
621
- * config.registerKeys([
622
- * { key: "llm.provider", sources: ["file", "memory"], default: "openai" },
623
- * { key: "llm.model", sources: ["file"] },
624
- * ]);
625
- */
626
- registerKeys(keys: KeyRegistration[]): void;
627
- /**
628
- * 注册 Component(一次性注册 Source 和 Keys)
629
- *
630
- * @example
631
- * config.registerComponent({
632
- * name: "llm",
633
- * sources: [
634
- * { type: "file", relativePath: "llm-config.jsonc" },
635
- * { type: "env", envPrefix: "LLM" },
636
- * ],
637
- * keys: [
638
- * { key: "llm.provider", sources: ["file", "env", "memory"] },
639
- * ],
640
- * });
641
- */
642
- registerComponent(registration: ComponentRegistration): void;
643
- /**
644
- * 按需加载配置
645
- *
646
- * 从注册的 Source 加载已注册 Keys 的配置值到内存中
647
- *
648
- * @param componentName - 可选,指定要加载的 Component 名称
649
- *
650
- * @example
651
- * // 加载所有已注册的 Keys
652
- * await config.load();
653
- *
654
- * // 只加载指定 Component 的 Keys
655
- * await config.load("llm");
656
- */
657
- load(componentName?: string): Promise<void>;
658
- /**
659
- * 获取已注册的 Source 列表
660
- */
661
- getRegisteredSources(): ConfigSource[];
662
- }
663
- /**
664
- * 服务配置接口
665
- */
666
- interface ServiceConfig {
667
- /** 环境配置 */
668
- environment?: {
669
- name?: string;
670
- version?: string;
671
- };
672
- /** 组件配置映射 */
673
- components?: Record<string, ComponentConfigEntry>;
674
- }
675
- /**
676
- * 组件配置项
677
- */
678
- interface ComponentConfigEntry {
679
- /** 配置文件路径(可选) */
680
- configPath?: string;
681
- /** 环境变量前缀(可选) */
682
- envPrefix?: string;
683
- /** 直接配置对象(可选) */
684
- config?: Record<string, unknown>;
685
- /** 是否启用(可选,默认 true) */
686
- enabled?: boolean;
687
- }
688
- /**
689
- * 组件初始化选项(由 generateComponentOptions 生成)
690
- */
691
- interface GeneratedComponentOptions {
692
- /** ConfigComponent 实例 */
693
- configComponent: ConfigComponent;
694
- /** 配置文件路径 */
695
- configPath?: string;
696
- /** 环境变量前缀 */
697
- envPrefix?: string;
698
- /** 直接配置对象 */
699
- config?: Record<string, unknown>;
700
- /** 允许的其他属性 */
701
- [key: string]: unknown;
702
- }
703
- /**
704
- * Environment 接口
705
- *
706
- * 定义 Agent 运行时的核心能力接口。
707
- */
708
- interface Environment {
709
- /** 环境名称 */
710
- readonly name: string;
711
- /** 环境版本 */
712
- readonly version: string;
713
- /** 获取环境配置 */
714
- getConfig(): EnvironmentConfig;
715
- /**
716
- * 注册组件
717
- */
718
- registerComponent(component: Component): void;
719
- /**
720
- * 注销组件
721
- */
722
- unregisterComponent(name: string): void;
723
- /**
724
- * 获取组件
725
- */
726
- getComponent<T extends Component>(name: string): T | undefined;
727
- /**
728
- * 列出所有组件
729
- */
730
- listComponents(): Component[];
731
- /**
732
- * 处理自然语言查询(核心入口)
733
- *
734
- * @param query 用户查询文本
735
- * @param context 执行上下文(可选)
736
- * @returns 完整的文本响应
737
- */
738
- handle_query(query: string, context?: AgentContext): Promise<string>;
739
- /**
740
- * 处理动作
741
- */
742
- handle_action(action: Action, context: Context): Promise<ToolResult>;
743
- /**
744
- * 订阅 EnvEvent(返回取消订阅函数)
745
- */
746
- subscribe(handler: EnvEventHandler): () => void;
747
- /**
748
- * 订阅指定类型事件
749
- */
750
- subscribeTo(eventType: string | string[], handler: EnvEventHandler): () => void;
751
- /**
752
- * 订阅所有事件(通配符)
753
- */
754
- subscribeAll(handler: EnvEventHandler): () => void;
755
- /**
756
- * 推送事件
757
- *
758
- * @param event EnvEvent 或 EnvEventInput(部分属性)
759
- */
760
- pushEnvEvent(event: EnvEvent | EnvEventInput): void;
761
- /**
762
- * 从配置文件加载服务配置
763
- *
764
- * @param configPath 配置文件路径(基于 XDG_DATA_HOME)
765
- * @returns 解析后的服务配置对象
766
- */
767
- loadServiceConfig(configPath: string): Promise<ServiceConfig>;
768
- /**
769
- * 生成组件初始化选项
770
- *
771
- * 根据组件配置项生成可用于初始化的选项对象。
772
- *
773
- * @param componentName 组件名称
774
- * @param configEntry 组件配置项
775
- * @returns 生成的组件初始化选项
776
- */
777
- generateComponentOptions(componentName: string, configEntry: ComponentConfigEntry): GeneratedComponentOptions;
778
- /**
779
- * 注册组件并用配置初始化
780
- *
781
- * 便捷方法:注册组件并通过 ConfigComponent 初始化。
782
- *
783
- * @param component 要注册的组件实例
784
- * @param configEntry 组件配置项
785
- */
786
- registerComponentWithConfig(component: Component, configEntry: ComponentConfigEntry): Promise<void>;
787
- /**
788
- * 从配置文件初始化整个环境
789
- *
790
- * 加载服务配置,注册并初始化所有配置的组件。
791
- *
792
- * @param configPath 配置文件路径(基于 XDG_DATA_HOME)
793
- */
794
- initFromConfig(configPath: string): Promise<void>;
795
- }
796
- /**
797
- * Component 状态
798
- */
799
- type ComponentStatus = "created" | "initializing" | "running" | "stopping" | "stopped" | "error";
800
- /**
801
- * Component 配置
802
- */
803
- interface ComponentConfig {
804
- name: string;
805
- version: string;
806
- enabled: boolean;
807
- options?: Record<string, unknown>;
808
- /**
809
- * Environment 实例(可选)
810
- *
811
- * 推荐在 init 时接收 env 实例,以便:
812
- * - 通过 env.getComponent() 获取其他组件
813
- * - 通过 env.pushEnvEvent() 发布事件
814
- * - 通过 env.handle_query() 处理查询
815
- *
816
- * 如果未提供,部分 Component 仍可正常工作(如测试场景)
817
- *
818
- * @example
819
- * ```typescript
820
- * async onInit(): Promise<void> {
821
- * if (this.env) {
822
- * const configComp = this.env.getComponent("config");
823
- * }
824
- * }
825
- * ```
826
- */
827
- env?: Environment;
828
- }
829
- /**
830
- * Component 路径声明
831
- */
832
- interface ComponentPaths {
833
- base: "config" | "state" | "data" | "cache";
834
- subPath: string;
835
- isDirectory: boolean;
836
- }
837
- /**
838
- * Component Schema(注册配置)
839
- */
840
- interface ComponentSchema {
841
- /** Component 名称 */
842
- name: string;
843
- /** 配置 Schema(Zod) */
844
- schema: ZodType3<unknown, ZodTypeDef2, unknown>;
845
- /** 默认值(从 Schema 提取) */
846
- defaults: Record<string, unknown>;
847
- /** 路径声明 */
848
- paths?: Record<string, ComponentPaths>;
849
- /** 元信息 */
850
- metadata?: {
851
- description?: string;
852
- version?: string;
853
- author?: string;
854
- };
855
- }
856
- /**
857
- * Component 配置变更事件
858
- */
859
- interface ComponentConfigChangeEvent {
860
- /** Component 名称 */
861
- component: string;
862
- /** 变更的配置键 */
863
- key: string;
864
- /** 旧值 */
865
- oldValue: unknown;
866
- /** 新值 */
867
- newValue: unknown;
868
- /** 是否持久化 */
869
- persisted: boolean;
870
- /** 时间戳 */
871
- timestamp: number;
872
- }
873
- /**
874
- * Component 配置监听回调
875
- */
876
- type ComponentWatchCallback = (event: ComponentConfigChangeEvent) => void | Promise<void>;
877
- /**
878
- * Component 基类接口
879
- */
880
- interface Component {
881
- /** Component 名称 */
882
- readonly name: string;
883
- /** Component 版本 */
884
- readonly version: string;
885
- /** 获取状态 */
886
- getStatus(): ComponentStatus;
887
- /** 获取配置 */
888
- getConfig(): ComponentConfig;
889
- /** 初始化 */
890
- init(config: ComponentConfig): Promise<void>;
891
- /** 启动 */
892
- start(): Promise<void>;
893
- /** 停止 */
894
- stop(): Promise<void>;
895
- }
896
- /**
897
- * Component 基类实现
898
- */
899
- declare abstract class BaseComponent implements Component {
900
- abstract readonly name: string;
901
- abstract readonly version: string;
902
- protected _status: ComponentStatus;
903
- protected _enabled: boolean;
904
- protected env: Environment;
905
- /** Hook 管理器 - 子类初始化时由构造函数设置 */
906
- readonly hookManager: HookManager;
907
- constructor();
908
- getStatus(): ComponentStatus;
909
- getConfig(): ComponentConfig;
910
- /**
911
- * 检查 Environment 是否已初始化
912
- */
913
- protected isEnvInitialized(): boolean;
914
- protected setStatus(status: ComponentStatus): void;
915
- /**
916
- * 获取 Environment 实例
917
- */
918
- protected getEnv(): Environment;
919
- init(config?: ComponentConfig): Promise<void>;
920
- start(): Promise<void>;
921
- stop(): Promise<void>;
922
- /**
923
- * 子类可覆盖的钩子方法
924
- */
925
- protected onInit(): Promise<void>;
926
- protected onStart(): Promise<void>;
927
- protected onStop(): Promise<void>;
928
- /**
929
- * 注册 Hook
930
- *
931
- * @param hookPoint Hook 点名称
932
- * @param hook Hook 实例
933
- */
934
- protected registerHook<T = unknown>(hookPoint: string, hook: Hook<T>): void;
935
- /**
936
- * 便捷方法:快速注册 Hook
937
- */
938
- protected addHook<T = unknown>(hookPoint: string, name: string, fn: HookFn<T>, priority?: number): void;
939
- /**
940
- * 便捷方法:按名称取消注册 Hook
941
- */
942
- protected removeHook(hookPoint: string, name: string): boolean;
943
- /**
944
- * 执行 Hook
945
- */
946
- protected executeHooks<T = unknown>(hookPoint: string, data: T, metadata?: Record<string, unknown>): Promise<void>;
947
- /**
948
- * 获取 ConfigComponent 实例
949
- *
950
- * 子类可使用此方法获取配置组件,支持热更新
951
- */
952
- protected getConfigComponent(): {
953
- get(key: string): unknown;
954
- } | undefined;
955
- /**
956
- * 动态获取运行时配置值
957
- *
958
- * 优先从 ConfigComponent 获取(支持热更新),否则返回默认值
959
- * 适用于运行时可能变化的配置(如 API Keys、模型参数)
960
- *
961
- * @param key 配置键(支持点号分隔的路径,如 "llm.temperature")
962
- * @param defaultValue 默认值
963
- * @returns 配置值或默认值
964
- *
965
- * @example
966
- * ```typescript
967
- * // 获取 LLM 温度配置(可能支持热更新)
968
- * const temperature = this.getRuntimeConfig("llm.temperature", 0.7);
969
- *
970
- * // 获取 API Key
971
- * const apiKey = this.getRuntimeConfig<string>("llm.providers.openai.apiKey");
972
- * ```
973
- */
974
- protected getRuntimeConfig<T>(key: string, defaultValue: T): T;
975
- }
976
- /**
977
- * Checkpoint type
978
- */
979
- type CheckpointType = "compact" | "manual";
980
- /**
981
- * Checkpoint metadata (stored in Session.metadata)
982
- */
983
- interface CheckpointMeta {
984
- id: string;
985
- messageIndex: number;
986
- title: string;
987
- createdAt: number;
988
- type: CheckpointType;
989
- }
990
- /**
991
- * User Intent type - represents a user's intent extracted from conversation
992
- */
993
- type UserIntent = string;
994
- /**
995
- * Recent message for checkpoint
996
- *
997
- * Stores a simplified version of a message for context preservation
998
- */
999
- interface RecentMessage {
1000
- role: string;
1001
- content: string;
1002
- }
1003
- /**
1004
- * Complete checkpoint information (includes generated content)
1005
- */
1006
- interface SessionCheckpoint extends CheckpointMeta {
1007
- summary: string;
1008
- processKeyPoints: string[];
1009
- currentState: string;
1010
- nextSteps: string[];
1011
- messageCountBefore: number;
1012
- metadata?: Record<string, unknown>;
1013
- /** User intents extracted from the conversation */
1014
- userIntents: UserIntent[];
1015
- /**
1016
- * Recent messages preserved from the compacted conversation
1017
- *
1018
- * Contains the last N turns of user query + assistant text response
1019
- * (excluding tool calls and tool results).
1020
- * This allows the checkpoint to serve as a fresh history context.
1021
- *
1022
- * Format: [user, assistant, user, assistant, ...] from most recent
1023
- */
1024
- recentMessages?: RecentMessage[];
1025
- }
1026
- /**
1027
- * Checkpoints metadata in session
1028
- */
1029
- interface SessionCheckpointsMeta {
1030
- latestCheckpointId?: string;
1031
- checkpoints: CheckpointMeta[];
1032
- }
1033
- /**
1034
- * Session entity
1035
- */
1036
- interface Session {
1037
- id: string;
1038
- title: string;
1039
- directory: string;
1040
- parentID?: string;
1041
- createdAt: number;
1042
- updatedAt: number;
1043
- messageCount: number;
1044
- metadata?: SessionMetadata;
1045
- }
1046
- /**
1047
- * Session metadata
1048
- */
1049
- interface SessionMetadata extends Record<string, unknown> {
1050
- /** Total number of messages in the session */
1051
- messageCount?: number;
1052
- checkpoints?: SessionCheckpointsMeta;
1053
- checkpointDetails?: Record<string, SessionCheckpoint>;
1054
- }
1055
- /**
1056
- * Session message
1057
- */
1058
- interface SessionMessage {
1059
- id: string;
1060
- sessionID: string;
1061
- role: Role;
1062
- content: string;
1063
- timestamp: number;
1064
- parts?: MessagePart[];
1065
- /** Whether the message has been archived (compacted) */
1066
- isArchived?: boolean;
1067
- /** Timestamp when the message was archived */
1068
- archivedAt?: number;
1069
- /** Checkpoint ID this message belongs to */
1070
- checkpointId?: string;
1071
- /** Message metadata (includes checkpoint info if this is a checkpoint message) */
1072
- metadata?: MessageMetadata;
1073
- }
1074
- /**
1075
- * Message metadata
1076
- */
1077
- interface MessageMetadata extends Record<string, unknown> {
1078
- /** 消息类型标识,用于过滤和分类 */
1079
- type?: "tool_call" | "tool_result" | "checkpoint" | "user_intent" | "workflow.node.start" | "workflow.node.interrupt" | "workflow.node.end" | "workflow.node.resume";
1080
- isCheckpoint?: boolean;
1081
- checkpointId?: string;
1082
- checkpointMeta?: SessionCheckpoint;
1083
- /** Workflow node ID (for workflow.node.* messages) */
1084
- workflowNodeId?: string;
1085
- /** Workflow node type (for workflow.node.* messages) */
1086
- workflowNodeType?: string;
1087
- /** Agent session ID (for agent nodes in workflow) */
1088
- agentSessionId?: string;
1089
- /** User response (for workflow.node.resume messages) */
1090
- response?: string;
1091
- /** Success flag (for workflow.node.end messages) */
1092
- success?: boolean;
1093
- }
1094
- /**
1095
- * Message role
1096
- */
1097
- type Role = "user" | "assistant" | "system" | "tool" | "workflow.node.start" | "workflow.node.interrupt" | "workflow.node.end" | "workflow.node.resume";
1098
- /**
1099
- * Message part
1100
- */
1101
- type MessagePart = SessionPart;
1102
- /**
1103
- * Text part - plain text content
1104
- */
1105
- interface TextPart {
1106
- type: "text";
1107
- content: string;
1108
- /** If true, this part was generated by the system (e.g., auto-summary) */
1109
- synthetic?: boolean;
1110
- /** If true, this part should be ignored (e.g., replaced by reasoning) */
1111
- ignored?: boolean;
1112
- }
1113
- /**
1114
- * Tool call part - represents a tool invocation
1115
- */
1116
- interface ToolCallPart {
1117
- type: "tool-call";
1118
- /** AI SDK standard field name */
1119
- toolCallId: string;
1120
- toolName: string;
1121
- /** Tool arguments - can be string (JSON) or object */
1122
- arguments: string | Record<string, unknown>;
1123
- state: "pending" | "running";
1124
- }
1125
- /**
1126
- * Tool result part - represents the result of a tool execution
1127
- */
1128
- interface ToolResultPart {
1129
- type: "tool-result";
1130
- toolCallId: string;
1131
- toolName: string;
1132
- output: string;
1133
- error?: string;
1134
- state: "completed" | "error";
1135
- }
1136
- /**
1137
- * Reasoning part - AI thinking/thought content
1138
- */
1139
- interface ReasoningPart {
1140
- type: "reasoning";
1141
- /** Reasoning content */
1142
- content: string;
1143
- /** Reasoning type (for different models) */
1144
- reasoningType?: "core" | "effort" | "summary";
1145
- /** State */
1146
- state?: "thinking" | "completed";
1147
- /** Whether to collapse by default (like AI SDK default) */
1148
- isCollapsed?: boolean;
1149
- /** Metadata */
1150
- metadata?: {
1151
- tokenCount?: number;
1152
- time?: {
1153
- start: number;
1154
- end?: number;
1155
- };
1156
- };
1157
- }
1158
- /**
1159
- * File part - file attachment
1160
- */
1161
- interface FilePart {
1162
- type: "file";
1163
- mime: string;
1164
- url: string;
1165
- filename?: string;
1166
- }
1167
- /**
1168
- * Checkpoint part - compaction checkpoint marker
1169
- *
1170
- * Represents a checkpoint message in the conversation history.
1171
- * This is stored as a user role message with markdown content summarizing
1172
- * the compacted conversation segment.
1173
- */
1174
- interface CheckpointPart {
1175
- type: "checkpoint";
1176
- /** Checkpoint ID reference */
1177
- checkpointId: string;
1178
- /** Markdown content summarizing the checkpoint */
1179
- content: string;
1180
- /** Title of the checkpoint */
1181
- title?: string;
1182
- /** Process key points */
1183
- processKeyPoints?: string[];
1184
- /** Current state description */
1185
- currentState?: string;
1186
- /** Next steps */
1187
- nextSteps?: string[];
1188
- /** Number of messages that were compacted */
1189
- messageCountBefore?: number;
1190
- /** Creation timestamp */
1191
- createdAt?: number;
1192
- }
1193
- /**
1194
- * Union type for all Session Part types
1195
- */
1196
- type SessionPart = TextPart | ToolCallPart | ToolResultPart | ReasoningPart | FilePart | CheckpointPart | WorkflowNodeStartPart | WorkflowNodeInterruptPart | WorkflowNodeEndPart | WorkflowNodeResumePart;
1197
- /**
1198
- * workflow.node.start 消息 part (对应 tool-call)
1199
- */
1200
- interface WorkflowNodeStartPart {
1201
- type: "workflow-node-start";
1202
- nodeId: string;
1203
- nodeType: string;
1204
- input?: unknown;
1205
- startTime: number;
1206
- /** Agent session ID (only for agent nodes) */
1207
- agentSessionId?: string;
1208
- }
1209
- /**
1210
- * workflow.node.interrupt 消息 part
1211
- */
1212
- interface WorkflowNodeInterruptPart {
1213
- type: "workflow-node-interrupt";
1214
- nodeId: string;
1215
- nodeType: string;
1216
- query: string;
1217
- options?: string[];
1218
- timestamp: number;
1219
- /** Agent session ID (only for agent nodes) */
1220
- agentSessionId?: string;
1221
- }
1222
- /**
1223
- * workflow.node.end 消息 part (对应 tool-result)
1224
- */
1225
- interface WorkflowNodeEndPart {
1226
- type: "workflow-node-end";
1227
- nodeId: string;
1228
- nodeType: string;
1229
- output?: unknown;
1230
- error?: string;
1231
- durationMs: number;
1232
- /** Agent session ID (only for agent nodes) */
1233
- agentSessionId?: string;
1234
- }
1235
- /**
1236
- * workflow.node.resume 消息 part
1237
- */
1238
- interface WorkflowNodeResumePart {
1239
- type: "workflow-node-resume";
1240
- nodeId: string;
1241
- response: string;
1242
- timestamp: number;
1243
- /** Agent session ID (only for agent nodes) */
1244
- agentSessionId?: string;
1245
- }
1246
- /**
1247
- * Options for creating a session
1248
- */
1249
- interface CreateSessionOptions {
1250
- /** Custom session ID (optional, will be generated if not provided) */
1251
- id?: string;
1252
- title?: string;
1253
- directory?: string;
1254
- parentID?: string;
1255
- metadata?: Record<string, unknown>;
1256
- hooks?: SessionHooksConfig;
1257
- }
1258
- /**
1259
- * Options for updating a session
1260
- */
1261
- interface UpdateSessionOptions {
1262
- title?: string;
1263
- metadata?: Record<string, unknown>;
1264
- }
1265
- /**
1266
- * Options for listing sessions
1267
- */
1268
- interface ListSessionsOptions {
1269
- filter?: {
1270
- metadata?: Record<string, unknown>;
1271
- startTime?: number;
1272
- endTime?: number;
1273
- };
1274
- sort?: {
1275
- field: "updatedAt" | "createdAt" | "title";
1276
- order: "asc" | "desc";
1277
- };
1278
- offset?: number;
1279
- limit?: number;
1280
- }
1281
- /**
1282
- * Options for adding a message
1283
- */
1284
- interface AddMessageOptions {
1285
- role: Role;
1286
- content: string;
1287
- parts?: MessagePart[];
1288
- metadata?: MessageMetadata;
1289
- }
1290
- /**
1291
- * Options for compact operation
1292
- */
1293
- interface CompactOptions {
1294
- /** User-provided summary hint for checkpoint generation */
1295
- summary?: string;
1296
- /** User-provided process key points hint */
1297
- processKeyPoints?: string[];
1298
- /** User-provided current state hint */
1299
- currentState?: string;
1300
- /** User-provided next steps hint */
1301
- nextSteps?: string[];
1302
- /** Whether this is auto-triggered compact */
1303
- auto?: boolean;
1304
- /**
1305
- * Scenario hint for guiding checkpoint generation
1306
- *
1307
- * A natural language description that provides context about the current scenario.
1308
- * This helps the SummaryAgent generate more relevant checkpoints based on the specific
1309
- * situation. Examples:
1310
- * - "Task execution in progress: implementing feature X, current working directory is /path/to/project"
1311
- * - "Bug investigation: analyzing crash dump, current hypothesis is memory corruption"
1312
- * - "Code review session: reviewing PR #123, focus on security implications"
1313
- *
1314
- * When provided, this will be prepended to the system prompt to guide the checkpoint
1315
- * generation with scenario-specific emphasis.
1316
- */
1317
- scenarioHint?: string;
1318
- }
1319
- /**
1320
- * Result of compact operation
1321
- */
1322
- interface CompactResult {
1323
- checkpoint: SessionCheckpoint;
1324
- deletedMessageCount: number;
1325
- remainingMessageCount: number;
1326
- checkpointCount: number;
1327
- }
1328
- /**
1329
- * Preview of compact operation
1330
- */
1331
- interface CompactPreview {
1332
- messageCountToCompact: number;
1333
- estimatedCheckpointTokens: number;
1334
- wouldTrigger: boolean;
1335
- }
1336
- /**
1337
- * Options for getting session context
1338
- */
1339
- interface GetContextOptions {
1340
- /** Start from specified checkpoint */
1341
- fromCheckpoint?: string;
1342
- /** Start from latest checkpoint (default: true) */
1343
- fromLatestCheckpoint?: boolean;
1344
- /** Read full history (ignore checkpoints) */
1345
- fullHistory?: boolean;
1346
- /** Message limit */
1347
- messageLimit?: number;
1348
- /** Minimum user messages to include (ensures starting from user message boundary) */
1349
- minUserMessages?: number;
1350
- /** Include checkpoint details */
1351
- includeCheckpoints?: boolean;
1352
- }
1353
- /**
1354
- * Result of getting session context
1355
- */
1356
- interface GetContextResult {
1357
- session: Session;
1358
- checkpoints: SessionCheckpoint[];
1359
- startCheckpoint?: SessionCheckpoint;
1360
- messages: SessionMessage[];
1361
- totalMessageCount: number;
1362
- activeMessageCount: number;
1363
- archivedMessageCount: number;
1364
- estimatedTokens: number;
1365
- }
1366
- /**
1367
- * Session hook callback
1368
- */
1369
- type SessionHookCallback = (context?: any) => Promise<void>;
1370
- /**
1371
- * Session hook definition
1372
- */
1373
- interface SessionHook {
1374
- name: string;
1375
- before?: SessionHookCallback;
1376
- after?: SessionHookCallback;
1377
- }
1378
- /**
1379
- * Session hooks configuration
1380
- */
1381
- interface SessionHooksConfig {
1382
- [key: string]: SessionHook[];
1383
- }
1384
- /**
1385
- * Options for searching messages
1386
- */
1387
- interface SearchMessagesOptions {
1388
- /** Search query (supports AND/OR/NOT syntax) */
1389
- query: string;
1390
- /** Limit search to specific session ID */
1391
- sessionId?: string;
1392
- /** Maximum number of results per session */
1393
- limit?: number;
1394
- /** Maximum total results */
1395
- maxResults?: number;
1396
- /** Only search messages before this timestamp */
1397
- beforeTime?: number;
1398
- /** Only search messages after this timestamp */
1399
- afterTime?: number;
1400
- /** Include archived messages */
1401
- includeArchived?: boolean;
1402
- /** Include context (messages before/after matches) */
1403
- includeContext?: boolean;
1404
- /** Number of context lines before/after */
1405
- contextLines?: number;
1406
- }
1407
- /**
1408
- * A single message match
1409
- */
1410
- interface MessageMatch {
1411
- /** Message ID */
1412
- messageId: string;
1413
- /** Session ID */
1414
- sessionId: string;
1415
- /** Message role */
1416
- role: Role;
1417
- /** Message content */
1418
- content: string;
1419
- /** Message timestamp */
1420
- timestamp: number;
1421
- /** Context before the match (if enabled) */
1422
- contextBefore?: string;
1423
- /** Context after the match (if enabled) */
1424
- contextAfter?: string;
1425
- /** Match score (relevance) */
1426
- score?: number;
1427
- }
1428
- /**
1429
- * Search result aggregated by session
1430
- */
1431
- interface SearchResult {
1432
- /** Session ID */
1433
- sessionId: string;
1434
- /** Session title */
1435
- sessionTitle: string;
1436
- /** Session directory */
1437
- sessionDirectory: string;
1438
- /** Session update timestamp */
1439
- updatedAt: number;
1440
- /** Total message count in session */
1441
- messageCount: number;
1442
- /** Matching messages in this session */
1443
- matches: MessageMatch[];
1444
- }
1445
- /**
1446
- * SessionComponent
1447
- *
1448
- * Manages session lifecycle including:
1449
- * - Session CRUD operations
1450
- * - Message management
1451
- * - Active session tracking
1452
- */
1453
- declare class SessionComponent extends BaseComponent {
1454
- readonly name = "session";
1455
- readonly version = "1.1.0";
1456
- private config?;
1457
- private store?;
1458
- private activeSessionId?;
1459
- private hooksConfig;
1460
- /** ConfigComponent 用于配置管理 */
1461
- private configComponent?;
1462
- /** 配置变更 watcher 清理函数 */
1463
- private configWatcher?;
1464
- /** Summary Agent for checkpoint generation [new] */
1465
- private summaryAgent?;
1466
- /** PromptComponent reference for SummaryAgent */
1467
- private promptComponent?;
1468
- /** LLMComponent reference for SummaryAgent */
1469
- private llmComponent?;
1470
- constructor();
1471
- /**
1472
- * Initialize the component
1473
- *
1474
- * 配置加载优先级(从高到低):
1475
- * 1. Object - 直接传入的 config 对象
1476
- * 2. Env - 环境变量(通过 envPrefix 配置前缀)
1477
- * 3. File - 配置文件(通过 configPath 指定)
1478
- */
1479
- init(config?: ComponentConfig): Promise<void>;
1480
- /**
1481
- * 获取默认 session 数据库路径
1482
- */
1483
- private getDefaultSessionDbPath;
1484
- /**
1485
- * 注册配置到 ConfigComponent
1486
- *
1487
- * 配置加载顺序(优先级从低到高):
1488
- * 1. Defaults - 默认值(最低)
1489
- * 2. FileSource - 从配置文件加载
1490
- * 3. EnvSource - 从环境变量加载
1491
- * 4. config 对象 - 直接传入的配置(最高)
1492
- */
1493
- private registerConfig;
1494
- /**
1495
- * 构建最终配置对象
1496
- */
1497
- private buildConfig;
1498
- /**
1499
- * 将配置对象展平为点号路径
1500
- */
1501
- private flattenConfig;
1502
- /**
1503
- * 注册配置热更新监听
1504
- */
1505
- private registerConfigWatcher;
1506
- /**
1507
- * 处理配置变更
1508
- */
1509
- protected onConfigChange(event: {
1510
- key: string;
1511
- oldValue?: unknown;
1512
- newValue?: unknown;
1513
- }): void;
1514
- /**
1515
- * Start the component
1516
- */
1517
- onStart(): Promise<void>;
1518
- /**
1519
- * Stop the component
1520
- */
1521
- onStop(): Promise<void>;
1522
- /**
1523
- * Create a new session
1524
- */
1525
- create(options?: CreateSessionOptions): Promise<Session>;
1526
- /**
1527
- * Get a session by ID
1528
- */
1529
- get(id: string): Promise<Session | undefined>;
1530
- /**
1531
- * Get a session with full context (for Memory Agent)
1532
- */
1533
- getSession(id: string): Promise<{
1534
- sessionId: string;
1535
- title: string;
1536
- messages: any[];
1537
- } | null>;
1538
- /**
1539
- * Search sessions by query (for Memory Agent)
1540
- *
1541
- * Simple implementation: list all sessions and return them for the agent to filter
1542
- */
1543
- searchSessions(query: string, options?: {
1544
- session_id?: string;
1545
- limit?: number;
1546
- }): Promise<Array<{
1547
- sessionId: string;
1548
- title: string;
1549
- preview: string;
1550
- timestamp: number;
1551
- }>>;
1552
- /**
1553
- * List all sessions
1554
- */
1555
- list(options?: ListSessionsOptions): Promise<Session[]>;
1556
- /**
1557
- * Get total session count
1558
- */
1559
- getCount(): Promise<number>;
1560
- /**
1561
- * Update a session
1562
- */
1563
- update(id: string, updates: UpdateSessionOptions): Promise<boolean>;
1564
- /**
1565
- * Delete a session
1566
- */
1567
- delete(id: string): Promise<boolean>;
1568
- /**
1569
- * Get the current active session
1570
- */
1571
- getActiveSession(): Session | undefined;
1572
- /**
1573
- * Get the active session ID
1574
- */
1575
- getActiveSessionId(): string | undefined;
1576
- /**
1577
- * Set the active session
1578
- */
1579
- setActiveSession(id: string): Promise<boolean>;
1580
- /**
1581
- * Add a message to a session
1582
- */
1583
- addMessage(sessionId: string, message: AddMessageOptions): Promise<string | undefined>;
1584
- /**
1585
- * Get messages from a session
1586
- */
1587
- getMessages(sessionId: string, options?: {
1588
- offset?: number;
1589
- limit?: number;
1590
- }): Promise<SessionMessage[]>;
1591
- /**
1592
- * Get message count for a session
1593
- */
1594
- getMessageCount(sessionId: string, includeArchived?: boolean): Promise<number>;
1595
- /**
1596
- * Get indexes of all messages with the specified role
1597
- * @param sessionId - Session ID
1598
- * @param role - Role to filter by (e.g., "user", "assistant")
1599
- * @returns Array of message indexes (0-indexed, in chronological order)
1600
- */
1601
- getMessageIndexes(sessionId: string, role: string): Promise<number[]>;
1602
- private executeBeforeHooks;
1603
- private executeAfterHooks;
1604
- private generateTitle;
1605
- /**
1606
- * Set components for SummaryAgent
1607
- *
1608
- * Call this after initialization if you need compact functionality
1609
- */
1610
- setSummaryComponents(promptComponent: any, llmComponent: any): void;
1611
- /**
1612
- * 初始化 SummaryAgent(如未初始化)
1613
- */
1614
- private ensureSummaryAgent;
1615
- /**
1616
- * 生成场景化压缩提示 (Compact Hint)
1617
- *
1618
- * 两阶段自动压缩的第一阶段:
1619
- * 根据会话历史生成场景化的压缩提示
1620
- *
1621
- * @param sessionId 会话 ID
1622
- * @returns 生成的场景化提示
1623
- */
1624
- generateCompactHint(sessionId: string): Promise<string>;
1625
- /**
1626
- * Compact a session
1627
- *
1628
- * 1. Get messages from latest checkpoint to current
1629
- * 2. Call Summary Agent to generate checkpoint
1630
- * 3. Save checkpoint and archive messages
1631
- *
1632
- * 支持 scenarioHint 参数,用于指导不同场景下的压缩重点提取
1633
- */
1634
- compact(sessionId: string, options?: CompactOptions): Promise<CompactResult>;
1635
- /**
1636
- * Extract recent messages from the conversation for checkpoint context
1637
- *
1638
- * Extracts the last N turns of user query + assistant text response,
1639
- * excluding tool calls and tool results.
1640
- *
1641
- * @param messages - All messages in the conversation
1642
- * @param turnCount - Number of turns to extract (default: 2)
1643
- * @returns Array of recent messages formatted as { role, content }
1644
- */
1645
- private extractRecentMessages;
1646
- /**
1647
- * Preview compact operation
1648
- */
1649
- previewCompact(sessionId: string): Promise<CompactPreview>;
1650
- /**
1651
- * Get all checkpoints for a session
1652
- */
1653
- getCheckpoints(sessionId: string): Promise<SessionCheckpoint[]>;
1654
- /**
1655
- * Get a specific checkpoint
1656
- */
1657
- getCheckpoint(sessionId: string, checkpointId: string): Promise<SessionCheckpoint | undefined>;
1658
- /**
1659
- * Delete a checkpoint and restore archived messages
1660
- */
1661
- deleteCheckpoint(sessionId: string, checkpointId: string): Promise<boolean>;
1662
- /**
1663
- * Get session context
1664
- *
1665
- * Returns messages starting from the latest checkpoint by default
1666
- */
1667
- getContext(sessionId: string, options?: GetContextOptions): Promise<GetContextResult>;
1668
- /**
1669
- * Check if session needs compaction
1670
- */
1671
- shouldCompact(sessionId: string): Promise<boolean>;
1672
- /**
1673
- * Search messages across sessions
1674
- *
1675
- * Searches all messages matching the query, aggregated by session.
1676
- * Supports SQLite FTS5 for fast full-text search.
1677
- */
1678
- searchMessages(options: SearchMessagesOptions): Promise<SearchResult[]>;
1679
- /**
1680
- * Get latest checkpoint from session
1681
- */
1682
- private getLatestCheckpoint;
1683
- /**
1684
- * Create checkpoint message (user role)
1685
- *
1686
- * Generates a markdown-formatted checkpoint summary as a user message,
1687
- * allowing it to appear in the message list and provide context for
1688
- * subsequent LLM calls.
1689
- */
1690
- private createCheckpointMessage;
1691
- }
1692
- /**
1693
- * 节点执行上下文
1694
- *
1695
- * 扩展后包含:
1696
- * - sessionId: Session ID,用于消息持久化
1697
- * - askUser(): 方法,让节点可以请求用户输入
1698
- */
1699
- interface NodeExecutionContext {
1700
- runId: string;
1701
- sessionId: string;
1702
- workflowName: string;
1703
- nodeId: string;
1704
- input: unknown;
1705
- previousOutputs: Map<string, unknown>;
1706
- nodeOutputs: Map<string, unknown>;
1707
- config: Record<string, unknown>;
1708
- debug: boolean;
1709
- eventBus: EventBus;
1710
- workflowHistory?: Array<{
1711
- role: "user" | "assistant" | "tool";
1712
- content: string;
1713
- toolCallId?: string;
1714
- toolName?: string;
1715
- nodeId?: string;
1716
- }>;
1717
- sessionComponent?: SessionComponent;
1718
- agentSessionId?: string;
1719
- workflowInput?: Record<string, unknown>;
1720
- /**
1721
- * 请求用户输入
1722
- *
1723
- * 调用此方法会抛出 AskUserError,引擎捕获后会暂停 workflow
1724
- *
1725
- * @param query - 向用户询问的问题
1726
- * @throws AskUserError - 总是抛出此异常
1727
- */
1728
- askUser(query: string): never;
1729
- }
1730
- declare const WorkflowDefinitionSchema: unknown;
1731
- type WorkflowDefinition = z5.infer<typeof WorkflowDefinitionSchema>;
1732
- /**
1733
- * Template resolution options
1734
- */
1735
- interface TemplateResolverOptions {
1736
- /** Input passed to the workflow/node */
1737
- input?: Record<string, unknown>;
1738
- /** Map of previous node outputs */
1739
- previousOutputs?: Map<string, unknown>;
1740
- }
1741
- /**
1742
- * Result of template resolution
1743
- */
1744
- interface ResolvedValue {
1745
- /** Whether the value was resolved */
1746
- resolved: boolean;
1747
- /** The resolved value */
1748
- value: unknown;
1749
- }
1750
- /**
1751
- * TemplateResolver
1752
- *
1753
- * Resolves template strings that reference workflow inputs and node outputs.
1754
- */
1755
- declare class TemplateResolver {
1756
- private input;
1757
- private previousOutputs;
1758
- constructor(options?: TemplateResolverOptions);
1759
- /**
1760
- * Create a TemplateResolver from NodeExecutionContext
1761
- *
1762
- * @param context - Node execution context
1763
- * @returns TemplateResolver instance
1764
- */
1765
- static fromContext(context: NodeExecutionContext): TemplateResolver;
1766
- /**
1767
- * Resolve template references in an input value.
1768
- *
1769
- * Handles:
1770
- * - Primitive values (returned as-is)
1771
- * - Objects (recursively resolved)
1772
- * - Arrays (recursively resolved)
1773
- * - Strings (template resolution)
1774
- *
1775
- * Key behavior for template strings:
1776
- * - If the string is a pure template reference (e.g., "{{nodes.fetch}}"),
1777
- * the resolved value is returned as-is (preserving objects/arrays)
1778
- * - If the string contains text + templates (e.g., "Hello {{name}}"),
1779
- * returns a string with interpolated values
1780
- *
1781
- * @param input - Input value that may contain template strings
1782
- * @returns Input with template references resolved
1783
- */
1784
- resolveValue(input: unknown): unknown;
1785
- /**
1786
- * Check if a string is a pure template reference (starts with {{ and ends with }})
1787
- * @param str - String to check
1788
- * @returns The template content if pure, null otherwise
1789
- */
1790
- private extractPureTemplate;
1791
- /**
1792
- * Resolve a pure template reference and return the value as-is.
1793
- * @param templateContent - Content between {{ and }}
1794
- * @returns The resolved value (may be object, array, or primitive)
1795
- */
1796
- private resolvePureTemplate;
1797
- /**
1798
- * Resolve template content (the part inside {{ }}) and return the value.
1799
- * @param templateContent - The path to resolve (e.g., "input.key", "nodes.fetch.data")
1800
- * @returns The resolved value
1801
- */
1802
- private resolveTemplateContent;
1803
- /**
1804
- * Resolve a single template string.
1805
- *
1806
- * Supports patterns:
1807
- * - {{input.key}} - Input variable
1808
- * - {{nodeId}} - Node's entire output
1809
- * - {{nodeId.output}} - Node's output property
1810
- * - {{nodeId.output.path}} - Node's nested output property
1811
- * - {{nodes.nodeId}} - Node's entire output (with prefix)
1812
- * - {{nodes.nodeId.output.path}} - Node's nested property (with prefix)
1813
- *
1814
- * @param template - Template string to resolve
1815
- * @returns Resolved string
1816
- */
1817
- resolveString(template: string): string;
1818
- /**
1819
- * Resolve a node output path.
1820
- *
1821
- * @param path - Path like "nodeId" or "nodeId.output" or "nodeId.output.path"
1822
- * @returns The resolved value or undefined
1823
- */
1824
- private resolveNodePath;
1825
- /**
1826
- * Get a nested value from an object using dot notation.
1827
- *
1828
- * @param obj - Object to traverse
1829
- * @param path - Dot-separated path
1830
- * @returns The nested value or undefined
1831
- */
1832
- private getNestedValue;
1833
- /**
1834
- * Convert a value to string, or return the original template if value is undefined.
1835
- */
1836
- private stringify;
1837
- /**
1838
- * Check if a string contains template references.
1839
- *
1840
- * @param str - String to check
1841
- * @returns True if the string contains template references
1842
- */
1843
- containsTemplates(str: string): boolean;
1844
- /**
1845
- * Extract all template references from a string.
1846
- *
1847
- * @param str - String to extract from
1848
- * @returns Array of template references
1849
- */
1850
- extractTemplates(str: string): string[];
1851
- }
1852
- /**
1853
- * Resolve template references in input using context.
1854
- *
1855
- * @param input - Input value with potential templates
1856
- * @param context - Node execution context
1857
- * @returns Resolved input
1858
- */
1859
- declare function resolveTemplates(input: unknown, context: NodeExecutionContext): unknown;
1860
- /**
1861
- * Resolve a template string using context.
1862
- *
1863
- * @param template - Template string
1864
- * @param context - Node execution context
1865
- * @returns Resolved string
1866
- */
1867
- declare function resolveTemplateString(template: string, context: NodeExecutionContext): string;
1868
- /**
1869
- * Validation Rules for Workflow Recovery
1870
- *
1871
- * Defines types for validation errors, results, and recovery plans.
1872
- */
1873
- /**
1874
- * Validation error types for workflow recovery
1875
- */
1876
- declare enum ValidationErrorType {
1877
- /** Variable referenced by node input is missing */
1878
- MISSING_VARIABLE = "MISSING_VARIABLE",
1879
- /** Parallel branch is incomplete */
1880
- INCOMPLETE_PARALLEL = "INCOMPLETE_PARALLEL",
1881
- /** Condition branch cannot be determined */
1882
- AMBIGUOUS_BRANCH = "AMBIGUOUS_BRANCH",
1883
- /** Loop state is lost */
1884
- LOOP_STATE_LOST = "LOOP_STATE_LOST",
1885
- /** Nested workflow state is invalid */
1886
- NESTED_WORKFLOW_INVALID = "NESTED_WORKFLOW_INVALID",
1887
- /** Node execution state is inconsistent */
1888
- NODE_STATE_INCONSISTENT = "NODE_STATE_INCONSISTENT",
1889
- /** Critical dependency is missing */
1890
- MISSING_DEPENDENCY = "MISSING_DEPENDENCY"
1891
- }
1892
- /**
1893
- * Suggested actions for recovery
1894
- */
1895
- declare enum SuggestedAction {
1896
- /** Re-run the workflow from the beginning */
1897
- RE_RUN = "RE_RUN",
1898
- /** Confirm with user before proceeding */
1899
- CONFIRM = "CONFIRM",
1900
- /** Skip the problematic node */
1901
- SKIP = "SKIP",
1902
- /** Provide the missing value */
1903
- PROVIDE_VALUE = "PROVIDE_VALUE",
1904
- /** Ignore the warning and proceed */
1905
- IGNORE = "IGNORE"
1906
- }
1907
- /**
1908
- * Validation error detail
1909
- */
1910
- interface ValidationError {
1911
- /** Error type */
1912
- type: ValidationErrorType;
1913
- /** Node ID where error occurred */
1914
- nodeId: string;
1915
- /** Human-readable error description */
1916
- description: string;
1917
- /** Suggested action to resolve */
1918
- suggestedAction: SuggestedAction;
1919
- /** Additional context information */
1920
- context?: Record<string, unknown>;
1921
- }
1922
- /**
1923
- * Result of validation
1924
- */
1925
- interface ValidationResult2 {
1926
- /** Whether the workflow can be safely resumed */
1927
- isValid: boolean;
1928
- /** List of validation errors */
1929
- errors: ValidationError[];
1930
- /** List of warnings (non-critical issues) */
1931
- warnings: string[];
1932
- }
1933
- /**
1934
- * Recovery plan for resuming a workflow
1935
- */
1936
- interface RecoveryPlan {
1937
- /** Whether the workflow can be resumed */
1938
- canResume: boolean;
1939
- /** Node ID where execution should resume */
1940
- resumePoint: string;
1941
- /** List of completed node IDs */
1942
- completedNodes: string[];
1943
- /** List of pending node IDs */
1944
- pendingNodes: string[];
1945
- /** List of node IDs that will be skipped */
1946
- skippedNodes: string[];
1947
- /** Validation errors encountered */
1948
- validationErrors: ValidationError[];
1949
- /** Human-readable summary */
1950
- summary: string;
1951
- }
1952
- /**
1953
- * Execution state of a workflow
1954
- */
1955
- interface ExecutionState {
1956
- /** Set of completed node IDs */
1957
- completedNodes: Set<string>;
1958
- /** Set of in-progress node IDs */
1959
- inProgressNodes: Set<string>;
1960
- /** Set of pending node IDs */
1961
- pendingNodes: Set<string>;
1962
- /** Map of node ID to output */
1963
- nodeOutputs: Map<string, unknown>;
1964
- /** Map of node ID to input */
1965
- nodeInputs: Map<string, unknown>;
1966
- /** Map of variable name to value */
1967
- variables: Map<string, unknown>;
1968
- /** Loop iteration counts */
1969
- loopCounts: Map<string, number>;
1970
- }
1971
- /**
1972
- * RecoveryValidator - 分层恢复验证框架
1973
- *
1974
- * 遵循保守策略,严格验证状态完整性
1975
- */
1976
- declare class RecoveryValidator {
1977
- private stateBuilder;
1978
- constructor();
1979
- validate(messages: SessionMessage[], definition: WorkflowDefinition): Promise<ValidationResult2>;
1980
- generatePlan(messages: SessionMessage[], definition: WorkflowDefinition): Promise<RecoveryPlan>;
1981
- private validateStateIntegrity;
1982
- private validateParallelBranches;
1983
- private validateConditionBranches;
1984
- private validateLoopState;
1985
- private validateNestedWorkflows;
1986
- private extractVariableRefs;
1987
- private identifyParallelGroups;
1988
- private findMergeNodeForParallel;
1989
- private identifyLoops;
1990
- private determineResumePoint;
1991
- private generateSummary;
1992
- }
1993
- /**
1994
- * Builder for constructing ExecutionState from session data
1995
- */
1996
- declare class ExecutionStateBuilder {
1997
- build(messages: SessionMessage[], definition: WorkflowDefinition): ExecutionState;
1998
- /**
1999
- * Parse session messages to extract node states and outputs
2000
- */
2001
- private parseMessages;
2002
- /**
2003
- * Build pending nodes from workflow definition
2004
- */
2005
- private buildPendingNodes;
2006
- /**
2007
- * Get entry nodes from workflow definition
2008
- */
2009
- private getEntryNodes;
2010
- /**
2011
- * Mark all nodes as pending starting from a given node
2012
- */
2013
- private markPendingFromNode;
2014
- /**
2015
- * Get direct children of a node
2016
- */
2017
- private getDirectChildren;
2018
- /**
2019
- * Extract input from a workflow.node.call message
2020
- */
2021
- private extractInput;
2022
- /**
2023
- * Extract output from a workflow.node.result message
2024
- */
2025
- private extractOutput;
2026
- /**
2027
- * Extract variables from node output and add to state
2028
- */
2029
- private extractVariables;
2030
- }
2031
- export { resolveTemplates, resolveTemplateString, ValidationResult2 as ValidationResult, ValidationErrorType, ValidationError, TemplateResolverOptions, TemplateResolver, SuggestedAction, ResolvedValue, RecoveryValidator, RecoveryPlan, ExecutionStateBuilder, ExecutionState };