@f2a/network 0.1.2 → 0.2.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 (226) hide show
  1. package/README.md +278 -63
  2. package/dist/cli/commands.d.ts.map +1 -1
  3. package/dist/cli/commands.js +29 -2
  4. package/dist/cli/commands.js.map +1 -1
  5. package/dist/cli/config.d.ts +176 -0
  6. package/dist/cli/config.d.ts.map +1 -0
  7. package/dist/cli/config.js +386 -0
  8. package/dist/cli/config.js.map +1 -0
  9. package/dist/cli/daemon.d.ts +54 -0
  10. package/dist/cli/daemon.d.ts.map +1 -0
  11. package/dist/cli/daemon.js +572 -0
  12. package/dist/cli/daemon.js.map +1 -0
  13. package/dist/cli/index.js +90 -16
  14. package/dist/cli/index.js.map +1 -1
  15. package/dist/cli/init.d.ts +13 -0
  16. package/dist/cli/init.d.ts.map +1 -0
  17. package/dist/cli/init.js +352 -0
  18. package/dist/cli/init.js.map +1 -0
  19. package/dist/core/e2ee-crypto.d.ts +127 -1
  20. package/dist/core/e2ee-crypto.d.ts.map +1 -1
  21. package/dist/core/e2ee-crypto.js +446 -12
  22. package/dist/core/e2ee-crypto.js.map +1 -1
  23. package/dist/core/f2a.d.ts +2 -1
  24. package/dist/core/f2a.d.ts.map +1 -1
  25. package/dist/core/f2a.js +6 -2
  26. package/dist/core/f2a.js.map +1 -1
  27. package/dist/core/identity/encrypted-key-store.d.ts +19 -0
  28. package/dist/core/identity/encrypted-key-store.d.ts.map +1 -0
  29. package/dist/core/identity/encrypted-key-store.js +72 -0
  30. package/dist/core/identity/encrypted-key-store.js.map +1 -0
  31. package/dist/core/identity/identity-manager.d.ts +133 -0
  32. package/dist/core/identity/identity-manager.d.ts.map +1 -0
  33. package/dist/core/identity/identity-manager.js +454 -0
  34. package/dist/core/identity/identity-manager.js.map +1 -0
  35. package/dist/core/identity/index.d.ts +8 -0
  36. package/dist/core/identity/index.d.ts.map +1 -0
  37. package/dist/core/identity/index.js +7 -0
  38. package/dist/core/identity/index.js.map +1 -0
  39. package/dist/core/identity/types.d.ts +70 -0
  40. package/dist/core/identity/types.d.ts.map +1 -0
  41. package/dist/core/identity/types.js +17 -0
  42. package/dist/core/identity/types.js.map +1 -0
  43. package/dist/core/p2p-network.d.ts +26 -0
  44. package/dist/core/p2p-network.d.ts.map +1 -1
  45. package/dist/core/p2p-network.js +434 -105
  46. package/dist/core/p2p-network.js.map +1 -1
  47. package/dist/core/reputation-security.d.ts +15 -0
  48. package/dist/core/reputation-security.d.ts.map +1 -1
  49. package/dist/core/reputation-security.js +73 -3
  50. package/dist/core/reputation-security.js.map +1 -1
  51. package/dist/core/reputation.d.ts +129 -4
  52. package/dist/core/reputation.d.ts.map +1 -1
  53. package/dist/core/reputation.js +294 -1
  54. package/dist/core/reputation.js.map +1 -1
  55. package/dist/core/review-committee.d.ts +2 -2
  56. package/dist/core/review-committee.d.ts.map +1 -1
  57. package/dist/core/review-committee.js +17 -0
  58. package/dist/core/review-committee.js.map +1 -1
  59. package/dist/daemon/control-server.d.ts.map +1 -1
  60. package/dist/daemon/control-server.js +44 -1
  61. package/dist/daemon/control-server.js.map +1 -1
  62. package/dist/daemon/webhook.d.ts +3 -0
  63. package/dist/daemon/webhook.d.ts.map +1 -1
  64. package/dist/daemon/webhook.js +318 -6
  65. package/dist/daemon/webhook.js.map +1 -1
  66. package/dist/index.d.ts +3 -3
  67. package/dist/index.d.ts.map +1 -1
  68. package/dist/index.js +7 -3
  69. package/dist/index.js.map +1 -1
  70. package/dist/types/index.d.ts +4 -0
  71. package/dist/types/index.d.ts.map +1 -1
  72. package/dist/types/index.js.map +1 -1
  73. package/dist/types/result.d.ts +1 -1
  74. package/dist/types/result.d.ts.map +1 -1
  75. package/dist/types/result.js.map +1 -1
  76. package/dist/utils/crypto-utils.d.ts +17 -0
  77. package/dist/utils/crypto-utils.d.ts.map +1 -0
  78. package/dist/utils/crypto-utils.js +28 -0
  79. package/dist/utils/crypto-utils.js.map +1 -0
  80. package/dist/utils/logger.d.ts +1 -0
  81. package/dist/utils/logger.d.ts.map +1 -1
  82. package/dist/utils/logger.js +9 -3
  83. package/dist/utils/logger.js.map +1 -1
  84. package/dist/utils/rate-limiter.d.ts.map +1 -1
  85. package/dist/utils/rate-limiter.js +3 -1
  86. package/dist/utils/rate-limiter.js.map +1 -1
  87. package/dist/utils/signature.d.ts +47 -1
  88. package/dist/utils/signature.d.ts.map +1 -1
  89. package/dist/utils/signature.js +166 -11
  90. package/dist/utils/signature.js.map +1 -1
  91. package/package.json +9 -1
  92. package/.github/workflows/ci.yml +0 -113
  93. package/.github/workflows/publish.yml +0 -60
  94. package/MONOREPO.md +0 -58
  95. package/SKILL.md +0 -137
  96. package/dist/adapters/openclaw.d.ts +0 -103
  97. package/dist/adapters/openclaw.d.ts.map +0 -1
  98. package/dist/adapters/openclaw.js +0 -297
  99. package/dist/adapters/openclaw.js.map +0 -1
  100. package/dist/core/connection-manager.d.ts +0 -80
  101. package/dist/core/connection-manager.d.ts.map +0 -1
  102. package/dist/core/connection-manager.js +0 -235
  103. package/dist/core/connection-manager.js.map +0 -1
  104. package/dist/core/connection-manager.test.d.ts +0 -2
  105. package/dist/core/connection-manager.test.d.ts.map +0 -1
  106. package/dist/core/connection-manager.test.js +0 -52
  107. package/dist/core/connection-manager.test.js.map +0 -1
  108. package/dist/core/identity.d.ts +0 -47
  109. package/dist/core/identity.d.ts.map +0 -1
  110. package/dist/core/identity.js +0 -130
  111. package/dist/core/identity.js.map +0 -1
  112. package/dist/core/identity.test.d.ts +0 -2
  113. package/dist/core/identity.test.d.ts.map +0 -1
  114. package/dist/core/identity.test.js +0 -43
  115. package/dist/core/identity.test.js.map +0 -1
  116. package/dist/core/serverless.d.ts +0 -155
  117. package/dist/core/serverless.d.ts.map +0 -1
  118. package/dist/core/serverless.js +0 -615
  119. package/dist/core/serverless.js.map +0 -1
  120. package/dist/daemon/webhook.test.d.ts +0 -2
  121. package/dist/daemon/webhook.test.d.ts.map +0 -1
  122. package/dist/daemon/webhook.test.js +0 -24
  123. package/dist/daemon/webhook.test.js.map +0 -1
  124. package/dist/protocol/messages.d.ts +0 -739
  125. package/dist/protocol/messages.d.ts.map +0 -1
  126. package/dist/protocol/messages.js +0 -188
  127. package/dist/protocol/messages.js.map +0 -1
  128. package/dist/protocol/messages.test.d.ts +0 -2
  129. package/dist/protocol/messages.test.d.ts.map +0 -1
  130. package/dist/protocol/messages.test.js +0 -55
  131. package/dist/protocol/messages.test.js.map +0 -1
  132. package/docs/F2A-PROTOCOL.md +0 -61
  133. package/docs/MOBILE_BOOTSTRAP_DESIGN.md +0 -126
  134. package/docs/a2a-lessons.md +0 -316
  135. package/docs/middleware-guide.md +0 -448
  136. package/docs/readme-update-checklist.md +0 -90
  137. package/docs/reputation-guide.md +0 -396
  138. package/docs/rfcs/001-reputation-system.md +0 -712
  139. package/docs/security-design.md +0 -247
  140. package/install.sh +0 -231
  141. package/packages/openclaw-adapter/README.md +0 -510
  142. package/packages/openclaw-adapter/openclaw.plugin.json +0 -106
  143. package/packages/openclaw-adapter/package.json +0 -40
  144. package/packages/openclaw-adapter/src/announcement-queue.test.ts +0 -449
  145. package/packages/openclaw-adapter/src/announcement-queue.ts +0 -403
  146. package/packages/openclaw-adapter/src/capability-detector.test.ts +0 -99
  147. package/packages/openclaw-adapter/src/capability-detector.ts +0 -183
  148. package/packages/openclaw-adapter/src/claim-handlers.test.ts +0 -974
  149. package/packages/openclaw-adapter/src/claim-handlers.ts +0 -482
  150. package/packages/openclaw-adapter/src/connector.business.test.ts +0 -583
  151. package/packages/openclaw-adapter/src/connector.ts +0 -795
  152. package/packages/openclaw-adapter/src/index.test.ts +0 -82
  153. package/packages/openclaw-adapter/src/index.ts +0 -18
  154. package/packages/openclaw-adapter/src/integration.e2e.test.ts +0 -829
  155. package/packages/openclaw-adapter/src/logger.ts +0 -51
  156. package/packages/openclaw-adapter/src/network-client.test.ts +0 -266
  157. package/packages/openclaw-adapter/src/network-client.ts +0 -251
  158. package/packages/openclaw-adapter/src/network-recovery.test.ts +0 -465
  159. package/packages/openclaw-adapter/src/node-manager.test.ts +0 -136
  160. package/packages/openclaw-adapter/src/node-manager.ts +0 -429
  161. package/packages/openclaw-adapter/src/plugin.test.ts +0 -439
  162. package/packages/openclaw-adapter/src/plugin.ts +0 -104
  163. package/packages/openclaw-adapter/src/reputation.test.ts +0 -221
  164. package/packages/openclaw-adapter/src/reputation.ts +0 -368
  165. package/packages/openclaw-adapter/src/task-guard.test.ts +0 -502
  166. package/packages/openclaw-adapter/src/task-guard.ts +0 -860
  167. package/packages/openclaw-adapter/src/task-queue.concurrency.test.ts +0 -462
  168. package/packages/openclaw-adapter/src/task-queue.edge-cases.test.ts +0 -284
  169. package/packages/openclaw-adapter/src/task-queue.persistence.test.ts +0 -408
  170. package/packages/openclaw-adapter/src/task-queue.ts +0 -668
  171. package/packages/openclaw-adapter/src/tool-handlers.test.ts +0 -906
  172. package/packages/openclaw-adapter/src/tool-handlers.ts +0 -574
  173. package/packages/openclaw-adapter/src/types.ts +0 -361
  174. package/packages/openclaw-adapter/src/webhook-pusher.test.ts +0 -188
  175. package/packages/openclaw-adapter/src/webhook-pusher.ts +0 -220
  176. package/packages/openclaw-adapter/src/webhook-server.test.ts +0 -580
  177. package/packages/openclaw-adapter/src/webhook-server.ts +0 -202
  178. package/packages/openclaw-adapter/tsconfig.json +0 -20
  179. package/src/cli/commands.test.ts +0 -157
  180. package/src/cli/commands.ts +0 -129
  181. package/src/cli/index.test.ts +0 -77
  182. package/src/cli/index.ts +0 -234
  183. package/src/core/autonomous-economy.test.ts +0 -291
  184. package/src/core/autonomous-economy.ts +0 -428
  185. package/src/core/e2ee-crypto.test.ts +0 -125
  186. package/src/core/e2ee-crypto.ts +0 -246
  187. package/src/core/f2a.test.ts +0 -269
  188. package/src/core/f2a.ts +0 -618
  189. package/src/core/p2p-network.test.ts +0 -199
  190. package/src/core/p2p-network.ts +0 -1432
  191. package/src/core/reputation-security.test.ts +0 -403
  192. package/src/core/reputation-security.ts +0 -562
  193. package/src/core/reputation.test.ts +0 -260
  194. package/src/core/reputation.ts +0 -576
  195. package/src/core/review-committee.test.ts +0 -380
  196. package/src/core/review-committee.ts +0 -401
  197. package/src/core/token-manager.test.ts +0 -133
  198. package/src/core/token-manager.ts +0 -140
  199. package/src/daemon/control-server.test.ts +0 -216
  200. package/src/daemon/control-server.ts +0 -292
  201. package/src/daemon/index.test.ts +0 -85
  202. package/src/daemon/index.ts +0 -89
  203. package/src/daemon/main.ts +0 -44
  204. package/src/daemon/start.ts +0 -29
  205. package/src/daemon/webhook.test.ts +0 -68
  206. package/src/daemon/webhook.ts +0 -105
  207. package/src/index.test.ts +0 -436
  208. package/src/index.ts +0 -72
  209. package/src/types/index.test.ts +0 -87
  210. package/src/types/index.ts +0 -341
  211. package/src/types/result.ts +0 -68
  212. package/src/utils/benchmark.ts +0 -237
  213. package/src/utils/logger.ts +0 -331
  214. package/src/utils/middleware.ts +0 -229
  215. package/src/utils/rate-limiter.ts +0 -207
  216. package/src/utils/signature.ts +0 -136
  217. package/src/utils/validation.ts +0 -186
  218. package/tests/docker/Dockerfile.node +0 -23
  219. package/tests/docker/Dockerfile.runner +0 -18
  220. package/tests/docker/docker-compose.test.yml +0 -73
  221. package/tests/integration/message-passing.test.ts +0 -109
  222. package/tests/integration/multi-node.test.ts +0 -92
  223. package/tests/integration/p2p-connection.test.ts +0 -83
  224. package/tests/integration/test-config.ts +0 -32
  225. package/tsconfig.json +0 -21
  226. package/vitest.config.ts +0 -26
@@ -1,51 +0,0 @@
1
- /**
2
- * OpenClaw Adapter 统一日志模块
3
- *
4
- * 设计说明:
5
- * - 提供统一的日志接口,便于维护和测试
6
- * - 支持结构化日志输出
7
- * - 默认使用 console,未来可扩展为其他日志系统
8
- */
9
-
10
- export interface Logger {
11
- debug(message: string, ...args: unknown[]): void;
12
- info(message: string, ...args: unknown[]): void;
13
- warn(message: string, ...args: unknown[]): void;
14
- error(message: string, ...args: unknown[]): void;
15
- }
16
-
17
- /** 默认日志前缀 */
18
- const DEFAULT_PREFIX = '[F2A]';
19
-
20
- /**
21
- * 创建日志记录器
22
- * @param component 组件名称(可选)
23
- */
24
- export function createLogger(component?: string): Logger {
25
- const prefix = component ? `[F2A:${component}]` : DEFAULT_PREFIX;
26
-
27
- return {
28
- debug(message: string, ...args: unknown[]): void {
29
- console.log(`${prefix} ${message}`, ...args);
30
- },
31
- info(message: string, ...args: unknown[]): void {
32
- console.log(`${prefix} ${message}`, ...args);
33
- },
34
- warn(message: string, ...args: unknown[]): void {
35
- console.warn(`${prefix} ${message}`, ...args);
36
- },
37
- error(message: string, ...args: unknown[]): void {
38
- console.error(`${prefix} ${message}`, ...args);
39
- }
40
- };
41
- }
42
-
43
- /** 默认日志记录器 */
44
- export const logger = createLogger();
45
-
46
- /** 组件专用日志记录器 */
47
- export const webhookLogger = createLogger('Webhook');
48
- export const taskGuardLogger = createLogger('TaskGuard');
49
- export const queueLogger = createLogger('Queue');
50
- export const nodeLogger = createLogger('Node');
51
- export const pluginLogger = createLogger('Plugin');
@@ -1,266 +0,0 @@
1
- import { describe, it, expect, vi, beforeEach } from 'vitest';
2
- import { F2ANetworkClient } from './network-client';
3
- import { F2ANodeConfig } from './types';
4
-
5
- // Mock global fetch
6
- const mockFetch = vi.fn();
7
- global.fetch = mockFetch;
8
-
9
- describe('F2ANetworkClient', () => {
10
- let client: F2ANetworkClient;
11
- const mockConfig: F2ANodeConfig = {
12
- nodePath: './F2A',
13
- controlPort: 9001,
14
- controlToken: 'test-token',
15
- p2pPort: 9000,
16
- enableMDNS: true,
17
- };
18
-
19
- beforeEach(() => {
20
- vi.clearAllMocks();
21
- client = new F2ANetworkClient(mockConfig);
22
- });
23
-
24
- describe('HTTP request handling', () => {
25
- it('should include correct headers in requests', async () => {
26
- mockFetch.mockResolvedValueOnce({
27
- ok: true,
28
- json: async () => ({ success: true, data: [] }),
29
- });
30
-
31
- await client.getConnectedPeers();
32
-
33
- expect(mockFetch).toHaveBeenCalledWith(
34
- 'http://localhost:9001/peers',
35
- expect.objectContaining({
36
- headers: {
37
- 'Authorization': 'Bearer test-token',
38
- 'Content-Type': 'application/json',
39
- },
40
- })
41
- );
42
- });
43
-
44
- it('should handle HTTP errors correctly', async () => {
45
- mockFetch.mockResolvedValueOnce({
46
- ok: false,
47
- status: 401,
48
- text: async () => 'Unauthorized',
49
- });
50
-
51
- const result = await client.getConnectedPeers();
52
-
53
- expect(result.success).toBe(false);
54
- // 新的 Result 类型中 error 是 F2AError 对象
55
- if (!result.success) {
56
- expect(result.error.message).toContain('401');
57
- expect(result.error.code).toBe('CONNECTION_FAILED');
58
- }
59
- });
60
-
61
- it('should handle network errors', async () => {
62
- mockFetch.mockRejectedValueOnce(new Error('Connection refused'));
63
-
64
- const result = await client.getConnectedPeers();
65
-
66
- expect(result.success).toBe(false);
67
- // 新的 Result 类型中 error 是 F2AError 对象
68
- if (!result.success) {
69
- expect(result.error.message).toBe('Connection refused');
70
- expect(result.error.code).toBe('CONNECTION_FAILED');
71
- }
72
- });
73
-
74
- it('should handle JSON parsing errors', async () => {
75
- mockFetch.mockResolvedValueOnce({
76
- ok: true,
77
- json: async () => { throw new Error('Invalid JSON'); },
78
- });
79
-
80
- const result = await client.getConnectedPeers();
81
-
82
- expect(result.success).toBe(false);
83
- });
84
- });
85
-
86
- describe('discoverAgents', () => {
87
- it('should discover agents without capability filter', async () => {
88
- const mockAgents = [
89
- { peerId: 'peer-1', displayName: 'Agent 1', capabilities: [] },
90
- ];
91
- mockFetch.mockResolvedValueOnce({
92
- ok: true,
93
- json: async () => mockAgents,
94
- });
95
-
96
- const result = await client.discoverAgents();
97
-
98
- expect(result.success).toBe(true);
99
- expect(result.data).toEqual(mockAgents);
100
- expect(mockFetch).toHaveBeenCalledWith(
101
- 'http://localhost:9001/discover',
102
- expect.objectContaining({
103
- method: 'POST',
104
- body: JSON.stringify({ capability: undefined }),
105
- })
106
- );
107
- });
108
-
109
- it('should discover agents with capability filter', async () => {
110
- mockFetch.mockResolvedValueOnce({
111
- ok: true,
112
- json: async () => ({ success: true, data: [] }),
113
- });
114
-
115
- await client.discoverAgents('code-generation');
116
-
117
- expect(mockFetch).toHaveBeenCalledWith(
118
- 'http://localhost:9001/discover',
119
- expect.objectContaining({
120
- body: JSON.stringify({ capability: 'code-generation' }),
121
- })
122
- );
123
- });
124
- });
125
-
126
- describe('delegateTask', () => {
127
- it('should send task delegation request', async () => {
128
- mockFetch.mockResolvedValueOnce({
129
- ok: true,
130
- json: async () => ({ success: true, data: { result: 'done' } }),
131
- });
132
-
133
- const result = await client.delegateTask({
134
- peerId: 'peer-1',
135
- taskType: 'test-task',
136
- description: 'Test description',
137
- parameters: { key: 'value' },
138
- timeout: 30000,
139
- });
140
-
141
- expect(result.success).toBe(true);
142
- expect(mockFetch).toHaveBeenCalledWith(
143
- 'http://localhost:9001/delegate',
144
- expect.objectContaining({
145
- method: 'POST',
146
- body: expect.stringContaining('peer-1'),
147
- })
148
- );
149
- });
150
- });
151
-
152
- describe('sendTaskResponse', () => {
153
- it('should send task response with all fields', async () => {
154
- mockFetch.mockResolvedValueOnce({
155
- ok: true,
156
- json: async () => ({ success: true }),
157
- });
158
-
159
- const result = await client.sendTaskResponse('peer-1', {
160
- taskId: 'task-123',
161
- status: 'success',
162
- result: { output: 'hello' },
163
- latency: 100,
164
- });
165
-
166
- expect(result.success).toBe(true);
167
- const callBody = JSON.parse(mockFetch.mock.calls[0][1].body);
168
- expect(callBody).toMatchObject({
169
- peerId: 'peer-1',
170
- taskId: 'task-123',
171
- status: 'success',
172
- });
173
- });
174
- });
175
-
176
- describe('registerWebhook', () => {
177
- it('should register webhook with default events', async () => {
178
- mockFetch.mockResolvedValueOnce({
179
- ok: true,
180
- json: async () => ({ success: true }),
181
- });
182
-
183
- const result = await client.registerWebhook('http://localhost:9002/webhook');
184
-
185
- expect(result.success).toBe(true);
186
- const callBody = JSON.parse(mockFetch.mock.calls[0][1].body);
187
- expect(callBody).toEqual({
188
- url: 'http://localhost:9002/webhook',
189
- events: ['discover', 'delegate', 'status'],
190
- });
191
- });
192
- });
193
-
194
- describe('updateAgentInfo', () => {
195
- it('should update agent info', async () => {
196
- mockFetch.mockResolvedValueOnce({
197
- ok: true,
198
- json: async () => ({ success: true }),
199
- });
200
-
201
- const result = await client.updateAgentInfo({
202
- displayName: 'Test Agent',
203
- capabilities: [{ name: 'test', description: 'Test capability', tools: [] }],
204
- });
205
-
206
- expect(result.success).toBe(true);
207
- });
208
- });
209
-
210
- describe('getPendingTasks', () => {
211
- it('should get pending tasks', async () => {
212
- const mockTasks = [{ taskId: 'task-1', description: 'Test' }];
213
- mockFetch.mockResolvedValueOnce({
214
- ok: true,
215
- json: async () => mockTasks,
216
- });
217
-
218
- const result = await client.getPendingTasks();
219
-
220
- expect(result.success).toBe(true);
221
- expect(result.data).toEqual(mockTasks);
222
- });
223
- });
224
-
225
- describe('confirmConnection', () => {
226
- it('should confirm connection', async () => {
227
- mockFetch.mockResolvedValueOnce({
228
- ok: true,
229
- json: async () => ({ success: true }),
230
- });
231
-
232
- const result = await client.confirmConnection('peer-1');
233
-
234
- expect(result.success).toBe(true);
235
- const callBody = JSON.parse(mockFetch.mock.calls[0][1].body);
236
- expect(callBody).toEqual({ peerId: 'peer-1' });
237
- });
238
- });
239
-
240
- describe('rejectConnection', () => {
241
- it('should reject connection with reason', async () => {
242
- mockFetch.mockResolvedValueOnce({
243
- ok: true,
244
- json: async () => ({ success: true }),
245
- });
246
-
247
- const result = await client.rejectConnection('peer-1', 'suspicious');
248
-
249
- expect(result.success).toBe(true);
250
- const callBody = JSON.parse(mockFetch.mock.calls[0][1].body);
251
- expect(callBody).toEqual({ peerId: 'peer-1', reason: 'suspicious' });
252
- });
253
-
254
- it('should reject connection without reason', async () => {
255
- mockFetch.mockResolvedValueOnce({
256
- ok: true,
257
- json: async () => ({ success: true }),
258
- });
259
-
260
- await client.rejectConnection('peer-1');
261
-
262
- const callBody = JSON.parse(mockFetch.mock.calls[0][1].body);
263
- expect(callBody).toEqual({ peerId: 'peer-1', reason: undefined });
264
- });
265
- });
266
- });
@@ -1,251 +0,0 @@
1
- /**
2
- * F2A Network Client
3
- * 与 F2A Node 的 HTTP API 通信
4
- */
5
-
6
- import type {
7
- F2ANodeConfig,
8
- AgentInfo,
9
- PeerInfo,
10
- TaskRequest,
11
- TaskResponse,
12
- DelegateOptions
13
- } from './types.js';
14
- import { Result, failure, success, createError } from './types.js';
15
- import { nodeLogger as logger } from './logger.js';
16
-
17
- /** 默认请求超时(毫秒) */
18
- const DEFAULT_TIMEOUT_MS = 30000;
19
-
20
- /** 默认重试配置 */
21
- const DEFAULT_MAX_RETRIES = 3;
22
- const DEFAULT_BASE_DELAY_MS = 1000;
23
-
24
- /** 可重试的错误码 */
25
- const RETRYABLE_ERROR_CODES = [
26
- 'ECONNRESET',
27
- 'ENOTFOUND',
28
- 'ETIMEDOUT',
29
- 'ECONNREFUSED',
30
- 'EHOSTUNREACH',
31
- 'ENETUNREACH',
32
- 'EAI_AGAIN'
33
- ];
34
-
35
- /** 可重试的 HTTP 状态码 */
36
- const RETRYABLE_STATUS_CODES = [502, 503, 504, 429];
37
-
38
- export class F2ANetworkClient {
39
- private baseUrl: string;
40
- private token: string;
41
- private timeoutMs: number;
42
- private maxRetries: number;
43
- private baseDelayMs: number;
44
-
45
- constructor(config: F2ANodeConfig) {
46
- this.baseUrl = `http://localhost:${config.controlPort}`;
47
- this.token = config.controlToken;
48
- this.timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
49
- this.maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;
50
- this.baseDelayMs = config.retryDelayMs ?? DEFAULT_BASE_DELAY_MS;
51
- }
52
-
53
- /**
54
- * 判断错误是否可重试
55
- */
56
- private isRetryableError(error: unknown): boolean {
57
- if (error instanceof Error) {
58
- // 网络错误
59
- if (RETRYABLE_ERROR_CODES.some(code => error.message.includes(code))) {
60
- return true;
61
- }
62
- // 超时错误
63
- if (error.name === 'AbortError' || error.message.includes('timeout')) {
64
- return true;
65
- }
66
- }
67
- return false;
68
- }
69
-
70
- /**
71
- * 计算重试延迟(指数退避 + 抖动)
72
- */
73
- private calculateDelay(attempt: number): number {
74
- const exponentialDelay = this.baseDelayMs * Math.pow(2, attempt);
75
- const jitter = Math.random() * this.baseDelayMs * 0.5;
76
- return Math.min(exponentialDelay + jitter, 30000); // 最大 30 秒
77
- }
78
-
79
- /**
80
- * 延迟函数
81
- */
82
- private delay(ms: number): Promise<void> {
83
- return new Promise(resolve => setTimeout(resolve, ms));
84
- }
85
-
86
- private async request<T>(
87
- method: string,
88
- path: string,
89
- body?: unknown
90
- ): Promise<Result<T>> {
91
- // P1 修复:初始化 lastError 为有意义的默认值,避免 null 问题
92
- let lastError: Error = new Error('Request failed before any attempt');
93
-
94
- for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
95
- // 使用 AbortController 设置超时
96
- const controller = new AbortController();
97
- const timeoutId = setTimeout(() => controller.abort(), this.timeoutMs);
98
-
99
- try {
100
- const response = await fetch(`${this.baseUrl}${path}`, {
101
- method,
102
- headers: {
103
- 'Authorization': `Bearer ${this.token}`,
104
- 'Content-Type': 'application/json'
105
- },
106
- body: body ? JSON.stringify(body) : undefined,
107
- signal: controller.signal
108
- });
109
-
110
- if (!response.ok) {
111
- const errorText = await response.text();
112
-
113
- // 检查是否是可重试的 HTTP 错误
114
- if (RETRYABLE_STATUS_CODES.includes(response.status) && attempt < this.maxRetries) {
115
- lastError = new Error(`HTTP ${response.status}: ${errorText}`);
116
- const delayMs = this.calculateDelay(attempt);
117
- logger.info(`Retrying request to ${path} after ${delayMs}ms (attempt ${attempt + 1}/${this.maxRetries})`);
118
- clearTimeout(timeoutId);
119
- await this.delay(delayMs);
120
- continue;
121
- }
122
-
123
- return failure(createError(
124
- 'CONNECTION_FAILED',
125
- `HTTP ${response.status}: ${errorText}`
126
- ));
127
- }
128
-
129
- const data = await response.json() as T;
130
- return success(data);
131
-
132
- } catch (error) {
133
- // 处理超时错误
134
- if (error instanceof Error && error.name === 'AbortError') {
135
- if (attempt < this.maxRetries) {
136
- const delayMs = this.calculateDelay(attempt);
137
- logger.info(`Retrying request to ${path} after timeout (${delayMs}ms, attempt ${attempt + 1}/${this.maxRetries})`);
138
- clearTimeout(timeoutId);
139
- await this.delay(delayMs);
140
- continue;
141
- }
142
- // 所有重试都因超时失败
143
- return failure(createError(
144
- 'CONNECTION_FAILED',
145
- `Request timed out after ${this.timeoutMs}ms`
146
- ));
147
- }
148
-
149
- // 检查是否可重试
150
- if (this.isRetryableError(error) && attempt < this.maxRetries) {
151
- lastError = error instanceof Error ? error : new Error(String(error));
152
- const delayMs = this.calculateDelay(attempt);
153
- logger.info(`Retrying request to ${path} after ${delayMs}ms (attempt ${attempt + 1}/${this.maxRetries})`);
154
- clearTimeout(timeoutId);
155
- await this.delay(delayMs);
156
- continue;
157
- }
158
-
159
- // P1 修复:确保返回有意义的错误信息
160
- const errorMessage = error instanceof Error ? error.message : String(error);
161
- lastError = error instanceof Error ? error : new Error(errorMessage);
162
-
163
- return failure(createError(
164
- 'CONNECTION_FAILED',
165
- errorMessage
166
- ));
167
- } finally {
168
- clearTimeout(timeoutId);
169
- }
170
- }
171
-
172
- // 所有重试都失败了
173
- // P1 修复:lastError 此时一定有值,不再需要 optional chaining
174
- return failure(createError(
175
- 'CONNECTION_FAILED',
176
- lastError.message
177
- ));
178
- }
179
-
180
- /**
181
- * 发现网络中的 Agents
182
- */
183
- async discoverAgents(capability?: string): Promise<Result<AgentInfo[]>> {
184
- return this.request<AgentInfo[]>('POST', '/discover', { capability });
185
- }
186
-
187
- /**
188
- * 获取已连接的 Peers
189
- */
190
- async getConnectedPeers(): Promise<Result<PeerInfo[]>> {
191
- return this.request<PeerInfo[]>('GET', '/peers');
192
- }
193
-
194
- /**
195
- * 委托任务给特定 Peer
196
- */
197
- async delegateTask(options: DelegateOptions): Promise<Result<unknown>> {
198
- return this.request<unknown>('POST', '/delegate', options);
199
- }
200
-
201
- /**
202
- * 发送任务响应
203
- */
204
- async sendTaskResponse(
205
- peerId: string,
206
- response: TaskResponse
207
- ): Promise<Result<void>> {
208
- return this.request<void>('POST', '/task/response', {
209
- peerId,
210
- ...response
211
- });
212
- }
213
-
214
- /**
215
- * 注册 Webhook
216
- */
217
- async registerWebhook(webhookUrl: string): Promise<Result<void>> {
218
- return this.request<void>('POST', '/webhook/register', {
219
- url: webhookUrl,
220
- events: ['discover', 'delegate', 'status']
221
- });
222
- }
223
-
224
- /**
225
- * 更新 Agent 信息
226
- */
227
- async updateAgentInfo(agentInfo: Partial<AgentInfo>): Promise<Result<void>> {
228
- return this.request<void>('POST', '/agent/update', agentInfo);
229
- }
230
-
231
- /**
232
- * 获取待处理任务
233
- */
234
- async getPendingTasks(): Promise<Result<TaskRequest[]>> {
235
- return this.request<TaskRequest[]>('GET', '/tasks/pending');
236
- }
237
-
238
- /**
239
- * 确认连接请求
240
- */
241
- async confirmConnection(peerId: string): Promise<Result<void>> {
242
- return this.request<void>('POST', '/connection/confirm', { peerId });
243
- }
244
-
245
- /**
246
- * 拒绝连接请求
247
- */
248
- async rejectConnection(peerId: string, reason?: string): Promise<Result<void>> {
249
- return this.request<void>('POST', '/connection/reject', { peerId, reason });
250
- }
251
- }