@starlink-awaken/agentmesh 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/CHANGELOG.md +31 -1
  2. package/dist/src/cli/release.d.ts +2 -0
  3. package/dist/src/cli/release.js +94 -0
  4. package/dist/src/cli.js +117 -31
  5. package/dist/src/core/agent-registry.d.ts +2 -0
  6. package/dist/src/core/agent-registry.js +12 -154
  7. package/dist/src/core/agents.default.d.ts +7 -0
  8. package/dist/src/core/agents.default.js +154 -0
  9. package/dist/src/core/config.d.ts +21 -0
  10. package/dist/src/core/context-manager.d.ts +2 -0
  11. package/dist/src/core/context-manager.js +4 -0
  12. package/dist/src/core/gateway.d.ts +79 -0
  13. package/dist/src/core/gateway.js +223 -0
  14. package/dist/src/core/pipeline.d.ts +21 -0
  15. package/dist/src/core/pipeline.js +48 -0
  16. package/dist/src/core/router.d.ts +2 -1
  17. package/dist/src/core/scheduler.d.ts +28 -0
  18. package/dist/src/core/scheduler.js +68 -0
  19. package/dist/src/core/store.d.ts +18 -0
  20. package/dist/src/core/store.js +77 -0
  21. package/dist/src/core/task-manager.d.ts +19 -27
  22. package/dist/src/core/task-manager.js +89 -80
  23. package/dist/src/core/vector-store.d.ts +2 -0
  24. package/dist/src/core/vector-store.js +4 -0
  25. package/dist/src/hermes/routes.d.ts +13 -0
  26. package/dist/src/hermes/routes.js +115 -0
  27. package/dist/src/index.js +76 -50
  28. package/dist/src/model-gateway/rate-limit.js +9 -0
  29. package/dist/src/model-gateway/routes.js +5 -5
  30. package/dist/src/routes/api.js +71 -7
  31. package/dist/src/routes/dashboard.d.ts +2 -0
  32. package/dist/src/routes/dashboard.js +113 -0
  33. package/dist/src/routes/sse.d.ts +2 -0
  34. package/dist/src/routes/sse.js +64 -0
  35. package/dist/src/types/index.d.ts +0 -19
  36. package/dist/src/types/index.js +2 -0
  37. package/dist/tests/model-gateway/routes.test.js +4 -4
  38. package/package.json +2 -1
@@ -0,0 +1,154 @@
1
+ // 默认 Agent CLI 配置 — 25+ 内置 Agent 命令映射
2
+ // 这些是兜底默认值,gateway.yaml 中的 agents 配置会覆盖它们
3
+ export const DEFAULT_AGENT_CONFIGS = {
4
+ 'claude-code': {
5
+ name: 'Claude Code',
6
+ capabilities: ['code-generation', 'code-review', 'debugging', 'refactoring', 'documentation', 'file-operations'],
7
+ command: 'claude',
8
+ args: ['-p']
9
+ },
10
+ 'openclaw': {
11
+ name: 'OpenClaw',
12
+ capabilities: ['browser-automation', 'web-scraping', 'form-filling', 'ui-testing'],
13
+ command: 'openclaw',
14
+ args: ['--task']
15
+ },
16
+ 'opencode': {
17
+ name: 'OpenCode',
18
+ capabilities: ['code-completion', 'code-generation', 'refactoring', 'debugging'],
19
+ command: 'opencode',
20
+ args: ['--task']
21
+ },
22
+ 'gemini': {
23
+ name: 'Google Gemini CLI',
24
+ capabilities: ['code-generation', 'multimodal', 'reasoning', 'analysis'],
25
+ command: 'gemini',
26
+ args: ['--prompt']
27
+ },
28
+ 'codex': {
29
+ name: 'OpenAI Codex',
30
+ capabilities: ['code-generation', 'code-explanation', 'refactoring'],
31
+ command: 'codex',
32
+ args: ['complete']
33
+ },
34
+ 'github-copilot': {
35
+ name: 'GitHub Copilot',
36
+ capabilities: ['code-completion', 'code-suggestions', 'refactoring'],
37
+ command: 'copilot',
38
+ args: ['--ask']
39
+ },
40
+ 'qwen-code': {
41
+ name: 'Qwen Code',
42
+ capabilities: ['code-generation', 'code-review', 'multilingual'],
43
+ command: 'qwen-code',
44
+ args: ['--task']
45
+ },
46
+ 'crush': {
47
+ name: 'CRUSH AI',
48
+ capabilities: ['code-generation', 'debugging', 'security-analysis'],
49
+ command: 'crush',
50
+ args: ['run']
51
+ },
52
+ 'droid': {
53
+ name: 'Droid Agent',
54
+ capabilities: ['android-development', 'mobile-debugging', 'device-control'],
55
+ command: 'droid',
56
+ args: ['--task']
57
+ },
58
+ 'factory': {
59
+ name: 'Factory AI',
60
+ capabilities: ['code-generation', 'testing', 'documentation', 'refactoring'],
61
+ command: 'factory',
62
+ args: ['--task']
63
+ },
64
+ 'cursor': {
65
+ name: 'Cursor',
66
+ capabilities: ['code-completion', 'code-generation', 'refactoring', 'chat'],
67
+ command: 'cursor',
68
+ args: ['--task']
69
+ },
70
+ 'windsurf': {
71
+ name: 'Windsurf',
72
+ capabilities: ['code-generation', 'agentic-coding', 'flow-state'],
73
+ command: 'windsurf',
74
+ args: ['--task']
75
+ },
76
+ 'zed': {
77
+ name: 'Zed AI',
78
+ capabilities: ['code-generation', 'collaboration', 'high-performance'],
79
+ command: 'zed',
80
+ args: ['--ai-task']
81
+ },
82
+ 'aider': {
83
+ name: 'Aider',
84
+ capabilities: ['git-based-editing', 'code-refactoring', 'multi-file-changes'],
85
+ command: 'aider',
86
+ args: ['--message']
87
+ },
88
+ 'cline': {
89
+ name: 'Cline',
90
+ capabilities: ['autonomous-coding', 'file-operations', 'command-execution'],
91
+ command: 'cline',
92
+ args: ['--task']
93
+ },
94
+ 'roo-code': {
95
+ name: 'Roo Code',
96
+ capabilities: ['code-generation', 'agentic-mode', 'workspace-awareness'],
97
+ command: 'roo-code',
98
+ args: ['--task']
99
+ },
100
+ 'perplexity': {
101
+ name: 'Perplexity',
102
+ capabilities: ['research', 'web-search', 'fact-checking', 'analysis'],
103
+ command: 'perplexity',
104
+ args: ['--query']
105
+ },
106
+ 'grok': {
107
+ name: 'xAI Grok',
108
+ capabilities: ['reasoning', 'humor', 'code-generation', 'analysis'],
109
+ command: 'grok',
110
+ args: ['--prompt']
111
+ },
112
+ 'phind': {
113
+ name: 'Phind',
114
+ capabilities: ['developer-search', 'code-search', 'documentation-search'],
115
+ command: 'phind',
116
+ args: ['--search']
117
+ },
118
+ 'you': {
119
+ name: 'You.com AI',
120
+ capabilities: ['web-search', 'code-search', 'general-assistant'],
121
+ command: 'you',
122
+ args: ['--query']
123
+ },
124
+ 'lepton': {
125
+ name: 'Lepton AI',
126
+ capabilities: ['code-generation', 'conversation', 'analysis'],
127
+ command: 'lepton',
128
+ args: ['--prompt']
129
+ },
130
+ 'ollama': {
131
+ name: 'Ollama',
132
+ capabilities: ['local-llm', 'code-generation', 'privacy-focused'],
133
+ command: 'ollama',
134
+ args: ['run']
135
+ },
136
+ 'llama': {
137
+ name: 'Meta Llama',
138
+ capabilities: ['code-generation', 'reasoning', 'open-source'],
139
+ command: 'llama',
140
+ args: ['--prompt']
141
+ },
142
+ 'mistral': {
143
+ name: 'Mistral AI',
144
+ capabilities: ['code-generation', 'reasoning', 'multilingual'],
145
+ command: 'mistral',
146
+ args: ['--task']
147
+ },
148
+ 'anthropic': {
149
+ name: 'Anthropic CLI',
150
+ capabilities: ['conversation', 'reasoning', 'code-generation'],
151
+ command: 'anthropic',
152
+ args: ['--prompt']
153
+ }
154
+ };
@@ -1,3 +1,4 @@
1
+ import type { ModelGatewayConfig } from '../model-gateway/types.js';
1
2
  export interface AgentConfig {
2
3
  id: string;
3
4
  name: string;
@@ -16,6 +17,25 @@ export interface RoutingRule {
16
17
  agents?: string[];
17
18
  priority: number;
18
19
  }
20
+ export interface ModelsSection extends ModelGatewayConfig {
21
+ defaults?: {
22
+ circuit_breaker?: {
23
+ failure_threshold?: number;
24
+ half_open_max_requests?: number;
25
+ reset_timeout_ms?: number;
26
+ };
27
+ retry?: {
28
+ base_delay_ms?: number;
29
+ max_delay_ms?: number;
30
+ max_retries?: number;
31
+ retryable_statuses?: number[];
32
+ };
33
+ rate_limit?: Record<string, {
34
+ rpm?: number;
35
+ enabled?: boolean;
36
+ }>;
37
+ };
38
+ }
19
39
  export interface GatewayConfig {
20
40
  port: number;
21
41
  wsPort: number;
@@ -28,6 +48,7 @@ export interface GatewayConfig {
28
48
  rules: RoutingRule[];
29
49
  };
30
50
  agents: AgentConfig[];
51
+ models?: ModelsSection;
31
52
  }
32
53
  /**
33
54
  * 加载配置文件
@@ -11,6 +11,8 @@ export declare class ContextManager {
11
11
  private memoryCache;
12
12
  private baseDir;
13
13
  constructor(baseDir?: string);
14
+ /** 从配置中更新存储路径 */
15
+ configure(baseDir: string): void;
14
16
  /**
15
17
  * 创建共享空间
16
18
  */
@@ -8,6 +8,10 @@ export class ContextManager {
8
8
  constructor(baseDir = './data/tasks') {
9
9
  this.baseDir = baseDir;
10
10
  }
11
+ /** 从配置中更新存储路径 */
12
+ configure(baseDir) {
13
+ this.baseDir = baseDir;
14
+ }
11
15
  /**
12
16
  * 创建共享空间
13
17
  */
@@ -0,0 +1,79 @@
1
+ import type { GatewayConfig } from './config.js';
2
+ import { TaskStore } from './store.js';
3
+ import type { Agent, AgentMessage, Task, EventType } from '../types/index.js';
4
+ export declare function setGateway(instance: GatewayContainer): void;
5
+ export declare function getGateway(): GatewayContainer | null;
6
+ /**
7
+ * GatewayContainer — 核心实例生命周期管理器
8
+ * 包装现有模块级单例,提供统一的 init → reload → dispose 生命周期
9
+ */
10
+ export declare class GatewayContainer {
11
+ readonly config: GatewayConfig;
12
+ readonly eventBus: import("./event-bus.js").EventBus;
13
+ readonly router: import("./router.js").Router;
14
+ readonly agentRegistry: import("./agent-registry.js").AgentRegistry;
15
+ readonly taskManager: import("./task-manager.js").TaskManager;
16
+ readonly contextManager: import("./context-manager.js").ContextManager;
17
+ readonly vectorStore: import("./vector-store.js").VectorStore;
18
+ readonly circuitBreakerRegistry: import("../model-gateway/circuit-breaker.js").CircuitBreakerRegistry;
19
+ readonly scheduler: import("./scheduler.js").Scheduler;
20
+ readonly pipeline: import("./pipeline.js").AgentPipeline;
21
+ readonly store: TaskStore;
22
+ private _started;
23
+ private _startTime;
24
+ private _configWatcher;
25
+ private _fsWatcher;
26
+ private _modelProviderCount;
27
+ constructor(config: GatewayConfig);
28
+ /** 完整初始化:配置 → Agent → 向量存储 */
29
+ initialize(): Promise<void>;
30
+ /** 运行时间(秒) */
31
+ get uptimeSeconds(): number;
32
+ /** 健康状态快照 */
33
+ health(): {
34
+ status: 'ok' | 'degraded' | 'starting';
35
+ uptime_seconds: number;
36
+ agents: {
37
+ total: number;
38
+ online: number;
39
+ };
40
+ models: {
41
+ total: number;
42
+ };
43
+ tasks: {
44
+ pending: number;
45
+ running: number;
46
+ completed: number;
47
+ failed: number;
48
+ };
49
+ circuit_breakers: Record<string, {
50
+ state: string;
51
+ failures: number;
52
+ }>;
53
+ };
54
+ /** 设置 Pino 日志桥接(Fastify 创建后调用) */
55
+ setPinoLogger(pino: any): void;
56
+ /** 热重载 Agent — 重新加载配置并增量更新注册 */
57
+ reloadAgents(): Promise<{
58
+ added: string[];
59
+ removed: string[];
60
+ updated: string[];
61
+ }>;
62
+ /** 启动配置文件监听(热重载) */
63
+ startConfigWatcher(configPath: string, debounceMs?: number): void;
64
+ /** 停止配置文件监听 */
65
+ stopConfigWatcher(): Promise<void>;
66
+ submitTask(message: AgentMessage): Promise<Task>;
67
+ getTask(taskId: string): Task | undefined;
68
+ getAllTasks(): Task[];
69
+ getOnlineAgents(): Agent[];
70
+ getAllAgents(): Agent[];
71
+ createSpace(metadata?: Record<string, unknown>): Promise<string>;
72
+ onEvent(eventType: EventType, handler: (event: {
73
+ type: EventType;
74
+ data: AgentMessage;
75
+ timestamp: number;
76
+ }) => void): () => void;
77
+ /** 优雅关闭 */
78
+ dispose(): Promise<void>;
79
+ }
@@ -0,0 +1,223 @@
1
+ import { eventBus } from './event-bus.js';
2
+ import { router } from './router.js';
3
+ import { agentRegistry } from './agent-registry.js';
4
+ import { taskManager } from './task-manager.js';
5
+ import { contextManager } from './context-manager.js';
6
+ import { vectorStore } from './vector-store.js';
7
+ import { initLogger, logger } from './logger.js';
8
+ import { circuitBreakerRegistry } from '../model-gateway/circuit-breaker.js';
9
+ import { TaskStore } from './store.js';
10
+ import { scheduler } from './scheduler.js';
11
+ import { agentPipeline } from './pipeline.js';
12
+ // 全局容器引用(供路由模块等访问)
13
+ let _instance = null;
14
+ export function setGateway(instance) { _instance = instance; }
15
+ export function getGateway() { return _instance; }
16
+ /**
17
+ * GatewayContainer — 核心实例生命周期管理器
18
+ * 包装现有模块级单例,提供统一的 init → reload → dispose 生命周期
19
+ */
20
+ export class GatewayContainer {
21
+ config;
22
+ eventBus = eventBus;
23
+ router = router;
24
+ agentRegistry = agentRegistry;
25
+ taskManager = taskManager;
26
+ contextManager = contextManager;
27
+ vectorStore = vectorStore;
28
+ circuitBreakerRegistry = circuitBreakerRegistry;
29
+ scheduler = scheduler;
30
+ pipeline = agentPipeline;
31
+ store;
32
+ _started = false;
33
+ _startTime = 0;
34
+ _configWatcher = null;
35
+ _fsWatcher = null; // fs.StatsWatcher (类型取决于 @types/node 版本)
36
+ _modelProviderCount = 0;
37
+ constructor(config) {
38
+ this.config = config;
39
+ this.store = new TaskStore(config.dataDir + '/gateway.db');
40
+ }
41
+ /** 完整初始化:配置 → Agent → 向量存储 */
42
+ async initialize() {
43
+ if (this._started)
44
+ return;
45
+ // Logger 桥接(由 index.ts 在 Fastify 创建后调用 setPino)
46
+ initLogger({ dir: this.config.logDir, level: this.config.logLevel });
47
+ // 存储路径
48
+ this.contextManager.configure(this.config.dataDir + '/tasks');
49
+ this.vectorStore.configure(this.config.dataDir + '/vector-db');
50
+ // Task 持久化
51
+ this.taskManager.useStore(this.store);
52
+ // Router
53
+ this.router.configure(this.config.routing.rules, this.config.routing.defaultAgent);
54
+ // Agent Registry
55
+ this.agentRegistry.initialize();
56
+ for (const agent of this.agentRegistry.getAgents()) {
57
+ this.router.registerAgent(agent);
58
+ }
59
+ // VectorStore 异步预热
60
+ this.vectorStore.initialize().catch(err => {
61
+ logger.warn('[Gateway] VectorStore init failed:', { error: String(err) });
62
+ });
63
+ // 启动定时任务调度器
64
+ this.scheduler.start();
65
+ // 缓存静态模型计数
66
+ this._modelProviderCount = this.config.models ? Object.keys(this.config.models.providers || {}).length : 0;
67
+ this._started = true;
68
+ this._startTime = Date.now();
69
+ logger.info('[Gateway] Container initialized');
70
+ }
71
+ /** 运行时间(秒) */
72
+ get uptimeSeconds() {
73
+ if (!this._started)
74
+ return 0;
75
+ return Math.floor((Date.now() - this._startTime) / 1000);
76
+ }
77
+ /** 健康状态快照 */
78
+ health() {
79
+ const allAgents = this.router.getAllAgents();
80
+ const onlineAgents = allAgents.filter(a => a.status === 'online');
81
+ const allTasks = this.taskManager.getAllTasks();
82
+ return {
83
+ status: this._started ? 'ok' : 'starting',
84
+ uptime_seconds: this.uptimeSeconds,
85
+ agents: {
86
+ total: allAgents.length,
87
+ online: onlineAgents.length,
88
+ },
89
+ models: { total: this._modelProviderCount },
90
+ tasks: {
91
+ pending: allTasks.filter(t => t.status === 'pending').length,
92
+ running: allTasks.filter(t => t.status === 'running').length,
93
+ completed: allTasks.filter(t => t.status === 'completed').length,
94
+ failed: allTasks.filter(t => t.status === 'failed').length,
95
+ },
96
+ circuit_breakers: this.circuitBreakerRegistry.getStatus(),
97
+ };
98
+ }
99
+ /** 设置 Pino 日志桥接(Fastify 创建后调用) */
100
+ setPinoLogger(pino) {
101
+ initLogger({ pino, dir: this.config.logDir, level: this.config.logLevel });
102
+ }
103
+ /** 热重载 Agent — 重新加载配置并增量更新注册 */
104
+ async reloadAgents() {
105
+ const before = new Set(this.agentRegistry.getAgents().map(a => a.id));
106
+ this.agentRegistry.reload();
107
+ const after = this.agentRegistry.getAgents();
108
+ const afterIds = new Set(after.map(a => a.id));
109
+ const added = [];
110
+ const removed = [];
111
+ const updated = [];
112
+ for (const agent of after) {
113
+ if (!before.has(agent.id)) {
114
+ this.router.registerAgent(agent);
115
+ added.push(agent.id);
116
+ this.eventBus.publishAgentEvent('agent.registered', {
117
+ id: agent.id, type: 'event',
118
+ source: 'gateway', target: 'system',
119
+ correlation_id: agent.id, timestamp: Date.now(),
120
+ });
121
+ }
122
+ else {
123
+ // 仅变更时重新注册
124
+ const existing = this.router.getAgent(agent.id);
125
+ if (!existing || existing.status !== agent.status || existing.capabilities.join(',') !== agent.capabilities.join(',')) {
126
+ this.router.registerAgent(agent);
127
+ updated.push(agent.id);
128
+ }
129
+ }
130
+ }
131
+ for (const oldId of before) {
132
+ if (!afterIds.has(oldId)) {
133
+ this.router.unregisterAgent(oldId);
134
+ removed.push(oldId);
135
+ this.eventBus.publishAgentEvent('agent.unregistered', {
136
+ id: oldId, type: 'event',
137
+ source: 'gateway', target: 'system',
138
+ correlation_id: oldId, timestamp: Date.now(),
139
+ });
140
+ }
141
+ }
142
+ if (added.length || removed.length) {
143
+ logger.info('[Gateway] Agents reloaded', { added, removed, updated: updated.length });
144
+ }
145
+ return { added, removed, updated };
146
+ }
147
+ /** 启动配置文件监听(热重载) */
148
+ startConfigWatcher(configPath, debounceMs = 3000) {
149
+ if (this._configWatcher)
150
+ return;
151
+ import('node:fs').then(({ watchFile, existsSync }) => {
152
+ const handler = () => {
153
+ setTimeout(async () => {
154
+ if (!existsSync(configPath))
155
+ return;
156
+ logger.info('[Gateway] Config changed, reloading...');
157
+ try {
158
+ const { reloadConfig, getRoutingRules, getDefaultAgent } = await import('./config.js');
159
+ const newConfig = reloadConfig(configPath);
160
+ this.contextManager.configure(newConfig.dataDir + '/tasks');
161
+ this.vectorStore.configure(newConfig.dataDir + '/vector-db');
162
+ const rules = getRoutingRules();
163
+ const defaultAgent = getDefaultAgent();
164
+ this.router.configure(rules, defaultAgent);
165
+ await this.reloadAgents();
166
+ logger.info('[Gateway] Config reloaded successfully');
167
+ }
168
+ catch (err) {
169
+ logger.error('[Gateway] Config reload failed:', { error: err.message });
170
+ }
171
+ }, debounceMs);
172
+ };
173
+ const watcher = watchFile(configPath, handler);
174
+ this._fsWatcher = watcher;
175
+ logger.info('[Gateway] Config watcher started: ' + configPath);
176
+ });
177
+ this._configWatcher = setInterval(() => { }, 2_147_483_647);
178
+ }
179
+ /** 停止配置文件监听 */
180
+ async stopConfigWatcher() {
181
+ if (this._configWatcher) {
182
+ clearInterval(this._configWatcher);
183
+ this._configWatcher = null;
184
+ }
185
+ if (this._fsWatcher) {
186
+ const { unwatchFile } = await import('node:fs');
187
+ unwatchFile(this._fsWatcher);
188
+ this._fsWatcher = null;
189
+ }
190
+ }
191
+ // —— 委托方法 ——
192
+ submitTask(message) {
193
+ return this.taskManager.processTask(message);
194
+ }
195
+ getTask(taskId) {
196
+ return this.taskManager.getTask(taskId);
197
+ }
198
+ getAllTasks() {
199
+ return this.taskManager.getAllTasks();
200
+ }
201
+ getOnlineAgents() {
202
+ return this.router.getOnlineAgents();
203
+ }
204
+ getAllAgents() {
205
+ return this.router.getAllAgents();
206
+ }
207
+ createSpace(metadata) {
208
+ return this.contextManager.createSharedSpace(metadata);
209
+ }
210
+ onEvent(eventType, handler) {
211
+ return this.eventBus.subscribe(eventType, handler);
212
+ }
213
+ /** 优雅关闭 */
214
+ async dispose() {
215
+ this.stopConfigWatcher();
216
+ this.scheduler.stop();
217
+ this.taskManager.purgeCompleted(30);
218
+ this.store.close();
219
+ this.eventBus.removeAllListeners();
220
+ this._started = false;
221
+ logger.info('[Gateway] Container disposed');
222
+ }
223
+ }
@@ -0,0 +1,21 @@
1
+ interface PipelineStep {
2
+ agentId: string;
3
+ transform?: (input: string) => string;
4
+ }
5
+ export interface PipelineResult {
6
+ taskIds: string[];
7
+ outputs: Array<{
8
+ agentId: string;
9
+ result?: unknown;
10
+ error?: string;
11
+ }>;
12
+ }
13
+ /**
14
+ * AgentPipeline — 串联多个 Agent 依次执行
15
+ * 通过 taskManager.processTask() 委托执行,不重复实现任务生命周期
16
+ */
17
+ export declare class AgentPipeline {
18
+ execute(steps: PipelineStep[], initialInput: string): Promise<PipelineResult>;
19
+ }
20
+ export declare const agentPipeline: AgentPipeline;
21
+ export {};
@@ -0,0 +1,48 @@
1
+ import { taskManager } from './task-manager.js';
2
+ import { router } from './router.js';
3
+ /**
4
+ * AgentPipeline — 串联多个 Agent 依次执行
5
+ * 通过 taskManager.processTask() 委托执行,不重复实现任务生命周期
6
+ */
7
+ export class AgentPipeline {
8
+ async execute(steps, initialInput) {
9
+ const taskIds = [];
10
+ const outputs = [];
11
+ let currentInput = initialInput;
12
+ for (const step of steps) {
13
+ const input = step.transform ? step.transform(currentInput) : currentInput;
14
+ const message = {
15
+ id: '', type: 'request', source: 'pipeline', target: step.agentId,
16
+ correlation_id: '', timestamp: Date.now(),
17
+ payload: { task: input },
18
+ };
19
+ // 验证 Agent 可用
20
+ const { agentIds } = router.route(message);
21
+ if (agentIds.length === 0 || !agentIds.includes(step.agentId)) {
22
+ outputs.push({ agentId: step.agentId, error: `Agent ${step.agentId} not available` });
23
+ return { taskIds, outputs };
24
+ }
25
+ // 委托给 TaskManager 执行完整生命周期
26
+ let task;
27
+ try {
28
+ task = await taskManager.processTask(message);
29
+ }
30
+ catch (err) {
31
+ outputs.push({ agentId: step.agentId, error: err.message });
32
+ return { taskIds, outputs };
33
+ }
34
+ taskIds.push(task.id);
35
+ if (task.status === 'completed' && task.result !== undefined) {
36
+ const resultStr = typeof task.result === 'string' ? task.result : JSON.stringify(task.result);
37
+ outputs.push({ agentId: step.agentId, result: task.result });
38
+ currentInput = resultStr;
39
+ }
40
+ else {
41
+ outputs.push({ agentId: step.agentId, error: task.error?.message || 'Unknown error' });
42
+ break;
43
+ }
44
+ }
45
+ return { taskIds, outputs };
46
+ }
47
+ }
48
+ export const agentPipeline = new AgentPipeline();
@@ -1,4 +1,5 @@
1
- import type { Agent, RoutingRule, AgentMessage } from '../types/index.js';
1
+ import type { Agent, AgentMessage } from '../types/index.js';
2
+ import type { RoutingRule } from './config.js';
2
3
  export declare class Router {
3
4
  private rules;
4
5
  private agents;
@@ -0,0 +1,28 @@
1
+ import type { AgentMessage } from '../types/index.js';
2
+ interface ScheduledTask {
3
+ id: string;
4
+ name: string;
5
+ cron: string;
6
+ message: AgentMessage;
7
+ enabled: boolean;
8
+ lastRun?: number;
9
+ nextRun?: number | null;
10
+ }
11
+ export declare class Scheduler {
12
+ private jobs;
13
+ private timer;
14
+ /** 添加定时任务 */
15
+ add(name: string, cronExpr: string, message: AgentMessage): string;
16
+ /** 移除定时任务 */
17
+ remove(id: string): boolean;
18
+ /** 列出所有定时任务 */
19
+ list(): ScheduledTask[];
20
+ /** 启动调度器 */
21
+ start(intervalMs?: number): void;
22
+ /** 停止调度器 */
23
+ stop(): void;
24
+ private _tick;
25
+ private _nextRun;
26
+ }
27
+ export declare const scheduler: Scheduler;
28
+ export {};