@starlink-awaken/agentmesh 1.0.2 → 1.0.3

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.
@@ -0,0 +1,128 @@
1
+ import { v4 as uuidv4 } from 'uuid';
2
+ import { taskManager } from '../core/task-manager.js';
3
+ import { router } from '../core/router.js';
4
+ import { contextManager } from '../core/context-manager.js';
5
+ export async function apiRoutes(fastify) {
6
+ // 健康检查
7
+ fastify.get('/health', async (_request, _reply) => {
8
+ return {
9
+ status: 'ok',
10
+ timestamp: Date.now(),
11
+ agents: router.getAllAgents().map(a => ({
12
+ id: a.id,
13
+ name: a.name,
14
+ status: a.status
15
+ }))
16
+ };
17
+ });
18
+ // 提交任务
19
+ fastify.post('/tasks', async (request, reply) => {
20
+ const body = request.body || {};
21
+ const message = {
22
+ id: uuidv4(),
23
+ type: 'request',
24
+ source: body.source || 'api',
25
+ target: 'gateway',
26
+ correlation_id: body.correlation_id || uuidv4(),
27
+ timestamp: Date.now(),
28
+ payload: body.payload
29
+ };
30
+ try {
31
+ const task = await taskManager.processTask(message);
32
+ reply.code(202).send({
33
+ task_id: task.id,
34
+ status: task.status,
35
+ message: 'Task submitted successfully'
36
+ });
37
+ }
38
+ catch (error) {
39
+ const errorMessage = error instanceof Error ? error.message : String(error);
40
+ reply.code(500).send({
41
+ error: {
42
+ code: 'TASK_FAILED',
43
+ message: errorMessage
44
+ }
45
+ });
46
+ }
47
+ });
48
+ // 获取任务状态
49
+ fastify.get('/tasks/:taskId', async (request, reply) => {
50
+ const { taskId } = request.params;
51
+ const task = taskManager.getTask(taskId);
52
+ if (!task) {
53
+ reply.code(404).send({
54
+ error: {
55
+ code: 'TASK_NOT_FOUND',
56
+ message: `Task ${taskId} not found`
57
+ }
58
+ });
59
+ return;
60
+ }
61
+ reply.send({
62
+ id: task.id,
63
+ status: task.status,
64
+ assigned_agents: task.assignedAgents,
65
+ result: task.result,
66
+ error: task.error,
67
+ created_at: task.createdAt,
68
+ updated_at: task.updatedAt
69
+ });
70
+ });
71
+ // 获取所有任务
72
+ fastify.get('/tasks', async (_request, reply) => {
73
+ const tasks = taskManager.getAllTasks();
74
+ reply.send(tasks.map(t => ({
75
+ id: t.id,
76
+ status: t.status,
77
+ assigned_agents: t.assignedAgents,
78
+ created_at: t.createdAt
79
+ })));
80
+ });
81
+ // 创建共享空间
82
+ fastify.post('/spaces', async (request, reply) => {
83
+ const { metadata } = request.body || {};
84
+ const spaceId = await contextManager.createSharedSpace(metadata);
85
+ reply.code(201).send({ space_id: spaceId });
86
+ });
87
+ // 获取共享空间
88
+ fastify.get('/spaces/:spaceId', async (request, reply) => {
89
+ const { spaceId } = request.params;
90
+ const context = await contextManager.getSharedSpace(spaceId);
91
+ if (!context) {
92
+ reply.code(404).send({
93
+ error: {
94
+ code: 'SPACE_NOT_FOUND',
95
+ message: `Shared space ${spaceId} not found`
96
+ }
97
+ });
98
+ return;
99
+ }
100
+ reply.send({
101
+ shared_space_id: context.shared_space_id,
102
+ message_count: context.messages.length,
103
+ artifact_count: context.artifacts.size,
104
+ metadata: context.metadata,
105
+ created_at: context.createdAt,
106
+ updated_at: context.updatedAt
107
+ });
108
+ });
109
+ // 获取 Agent 列表
110
+ fastify.get('/agents', async (_request, reply) => {
111
+ const agents = router.getAllAgents();
112
+ reply.send(agents);
113
+ });
114
+ // 注册 Agent
115
+ fastify.post('/agents', async (request, reply) => {
116
+ const body = request.body || {};
117
+ router.registerAgent({
118
+ id: body.id || 'unknown',
119
+ name: body.name || 'Unknown',
120
+ type: body.type || 'process',
121
+ capabilities: body.capabilities || [],
122
+ status: 'online',
123
+ endpoint: body.endpoint,
124
+ lastSeen: Date.now()
125
+ });
126
+ reply.code(201).send({ id: body.id, status: 'registered' });
127
+ });
128
+ }
@@ -0,0 +1,2 @@
1
+ import type { FastifyInstance } from 'fastify';
2
+ export declare function websocketRoutes(fastify: FastifyInstance): Promise<void>;
@@ -0,0 +1,64 @@
1
+ import { v4 as uuidv4 } from 'uuid';
2
+ import { taskManager } from '../core/task-manager.js';
3
+ import { agentRegistry } from '../core/agent-registry.js';
4
+ export async function websocketRoutes(fastify) {
5
+ const clients = new Map();
6
+ // SSE 端点 - 用于实时任务更新
7
+ fastify.get('/events', async (request, reply) => {
8
+ const { taskId, spaceId } = request.query;
9
+ reply.raw.writeHead(200, {
10
+ 'Content-Type': 'text/event-stream',
11
+ 'Cache-Control': 'no-cache',
12
+ 'Connection': 'keep-alive'
13
+ });
14
+ const clientId = uuidv4();
15
+ clients.set(clientId, {
16
+ id: clientId,
17
+ reply
18
+ });
19
+ // 发送初始连接消息
20
+ reply.raw.write(`data: ${JSON.stringify({ type: 'connected', client_id: clientId })}\n\n`);
21
+ // 订阅任务事件
22
+ if (taskId) {
23
+ const task = taskManager.getTask(taskId);
24
+ if (task) {
25
+ reply.raw.write(`data: ${JSON.stringify({ type: 'task_status', task })}\n\n`);
26
+ }
27
+ }
28
+ // 发送欢迎消息
29
+ reply.raw.write(`data: ${JSON.stringify({ type: 'welcome', agents: agentRegistry.getAgents() })}\n\n`);
30
+ // 心跳
31
+ const heartbeat = setInterval(() => {
32
+ reply.raw.write(`data: ${JSON.stringify({ type: 'heartbeat', timestamp: Date.now() })}\n\n`);
33
+ }, 30000);
34
+ request.raw.on('close', () => {
35
+ clearInterval(heartbeat);
36
+ clients.delete(clientId);
37
+ });
38
+ });
39
+ // WebSocket 模拟端点 - 返回 SSE 连接信息
40
+ fastify.get('/ws-info', async (_request, reply) => {
41
+ reply.send({
42
+ message: 'Use /events for Server-Sent Events streaming',
43
+ endpoints: {
44
+ events: '/events?taskId=<task_id>&spaceId=<space_id>',
45
+ description: 'Subscribe to real-time task updates and agent responses'
46
+ },
47
+ example: 'curl -N http://localhost:3000/events?taskId=<task_id>'
48
+ });
49
+ });
50
+ // 广播消息到所有客户端
51
+ fastify.post('/broadcast', async (request, reply) => {
52
+ const { type, data } = request.body || {};
53
+ const message = JSON.stringify({ type, data, timestamp: Date.now() });
54
+ for (const client of clients.values()) {
55
+ try {
56
+ client.reply.raw.write(`data: ${message}\n\n`);
57
+ }
58
+ catch (e) {
59
+ // 客户端可能已断开
60
+ }
61
+ }
62
+ reply.send({ delivered: clients.size });
63
+ });
64
+ }
@@ -0,0 +1,71 @@
1
+ export type MessageType = 'request' | 'response' | 'event' | 'stream' | 'stream_end';
2
+ export type EventType = 'agent.registered' | 'agent.unregistered' | 'task.submitted' | 'task.assigned' | 'task.started' | 'task.progress' | 'task.completed' | 'task.failed' | 'context.updated';
3
+ export interface ContextRef {
4
+ shared_space_id: string;
5
+ history?: string[];
6
+ artifacts?: string[];
7
+ }
8
+ export interface Payload {
9
+ task?: string;
10
+ context?: ContextRef;
11
+ files?: string[];
12
+ options?: {
13
+ stream?: boolean;
14
+ timeout?: number;
15
+ };
16
+ }
17
+ export interface Error {
18
+ code: string;
19
+ message: string;
20
+ }
21
+ export interface AgentMessage {
22
+ id: string;
23
+ type: MessageType;
24
+ source: string;
25
+ target: string;
26
+ correlation_id: string;
27
+ timestamp: number;
28
+ payload?: Payload;
29
+ event_type?: EventType;
30
+ event_data?: Record<string, unknown>;
31
+ result?: unknown;
32
+ error?: Error;
33
+ }
34
+ export interface Agent {
35
+ id: string;
36
+ name: string;
37
+ type: 'claude-code' | 'openclaw' | 'process' | 'http';
38
+ capabilities: string[];
39
+ status: 'online' | 'offline' | 'busy';
40
+ endpoint?: string;
41
+ lastSeen: number;
42
+ }
43
+ export interface Task {
44
+ id: string;
45
+ status: 'pending' | 'assigned' | 'running' | 'completed' | 'failed';
46
+ request: AgentMessage;
47
+ assignedAgents: string[];
48
+ result?: unknown;
49
+ error?: Error;
50
+ createdAt: number;
51
+ updatedAt: number;
52
+ }
53
+ export interface RoutingRule {
54
+ name: string;
55
+ keywords: string[];
56
+ agent?: string;
57
+ strategy?: 'direct' | 'broadcast';
58
+ agents?: string[];
59
+ priority: number;
60
+ }
61
+ export interface GatewayConfig {
62
+ port: number;
63
+ wsPort: number;
64
+ host: string;
65
+ dataDir: string;
66
+ logDir: string;
67
+ routing: {
68
+ rules: RoutingRule[];
69
+ defaultAgent?: string;
70
+ };
71
+ }
@@ -0,0 +1 @@
1
+ // Agent Gateway 通信协议类型定义
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@starlink-awaken/agentmesh",
3
- "version": "1.0.2",
3
+ "version": "1.0.3",
4
4
  "description": "Unified Agent Gateway - Multi-Agent Scheduler and Router",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",