genesis-ai-cli 9.3.0 → 10.0.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 (49) hide show
  1. package/dist/src/a2a/client.d.ts +117 -0
  2. package/dist/src/a2a/client.js +506 -0
  3. package/dist/src/a2a/index.d.ts +19 -0
  4. package/dist/src/a2a/index.js +36 -0
  5. package/dist/src/a2a/protocol.d.ts +403 -0
  6. package/dist/src/a2a/protocol.js +123 -0
  7. package/dist/src/a2a/server.d.ts +82 -0
  8. package/dist/src/a2a/server.js +519 -0
  9. package/dist/src/active-inference/types.d.ts +1 -1
  10. package/dist/src/active-inference/types.js +2 -0
  11. package/dist/src/active-inference/value-integration.js +2 -0
  12. package/dist/src/allostasis/index.js +28 -6
  13. package/dist/src/brain/types.d.ts +1 -1
  14. package/dist/src/deployment/index.d.ts +1 -0
  15. package/dist/src/deployment/index.js +16 -0
  16. package/dist/src/deployment/self-deployment.d.ts +293 -0
  17. package/dist/src/deployment/self-deployment.js +867 -0
  18. package/dist/src/healing/fixer.js +3 -2
  19. package/dist/src/hooks/index.js +2 -1
  20. package/dist/src/mcp/cache.js +2 -0
  21. package/dist/src/mcp/index.js +8 -1
  22. package/dist/src/mcp/streaming.js +1 -1
  23. package/dist/src/mcp/transformers.js +2 -0
  24. package/dist/src/mcp-server/index.d.ts +13 -0
  25. package/dist/src/mcp-server/index.js +34 -0
  26. package/dist/src/mcp-server/server.d.ts +91 -0
  27. package/dist/src/mcp-server/server.js +795 -0
  28. package/dist/src/mcp-server/types.d.ts +254 -0
  29. package/dist/src/mcp-server/types.js +80 -0
  30. package/dist/src/memory/cache.js +3 -1
  31. package/dist/src/memory/consolidation.d.ts +10 -0
  32. package/dist/src/memory/consolidation.js +58 -1
  33. package/dist/src/memory/vector-store.d.ts +7 -0
  34. package/dist/src/memory/vector-store.js +26 -0
  35. package/dist/src/memory-production/index.js +6 -5
  36. package/dist/src/orchestrator.js +7 -0
  37. package/dist/src/payments/api.d.ts +50 -0
  38. package/dist/src/payments/api.js +299 -0
  39. package/dist/src/payments/index.d.ts +10 -0
  40. package/dist/src/payments/index.js +40 -0
  41. package/dist/src/payments/payment-service.d.ts +148 -0
  42. package/dist/src/payments/payment-service.js +649 -0
  43. package/dist/src/payments/revenue-tracker.d.ts +143 -0
  44. package/dist/src/payments/revenue-tracker.js +343 -0
  45. package/dist/src/payments/types.d.ts +225 -0
  46. package/dist/src/payments/types.js +8 -0
  47. package/dist/src/types.d.ts +1 -1
  48. package/dist/test/brain.test.js +5 -5
  49. package/package.json +1 -1
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Genesis A2A Client
3
+ *
4
+ * Client for discovering and communicating with remote Genesis agents.
5
+ * Supports HTTP, WebSocket, and MessageBus transports.
6
+ */
7
+ import { EventEmitter } from 'events';
8
+ import { A2AAgentId, A2AMessage, A2AResponse, A2AEndpoint, A2AKeyPair, AgentCapability, AgentAnnouncement, TaskRequest, TaskResult, TaskProgress, TrustScore, PaymentQuote, PaymentCommitment } from './protocol.js';
9
+ export interface A2AClientConfig {
10
+ agentId: A2AAgentId;
11
+ keyPair: A2AKeyPair;
12
+ directory?: AgentDirectory;
13
+ defaultTimeout?: number;
14
+ autoRetry?: boolean;
15
+ maxRetries?: number;
16
+ debug?: boolean;
17
+ }
18
+ export interface AgentDirectory {
19
+ lookup(agentId: A2AAgentId): Promise<AgentAnnouncement | null>;
20
+ search(query: {
21
+ capabilities?: string[];
22
+ minTrust?: number;
23
+ limit?: number;
24
+ }): Promise<AgentAnnouncement[]>;
25
+ register(announcement: AgentAnnouncement): Promise<void>;
26
+ unregister(agentId: A2AAgentId): Promise<void>;
27
+ }
28
+ export interface PendingRequest {
29
+ resolve: (response: A2AResponse) => void;
30
+ reject: (error: Error) => void;
31
+ timeout: NodeJS.Timeout;
32
+ created: Date;
33
+ }
34
+ export interface A2AClientEvents {
35
+ connected: (endpoint: A2AEndpoint) => void;
36
+ disconnected: (endpoint: A2AEndpoint) => void;
37
+ message: (message: A2AMessage) => void;
38
+ response: (response: A2AResponse) => void;
39
+ error: (error: Error) => void;
40
+ 'task:progress': (taskId: string, progress: TaskProgress) => void;
41
+ 'task:complete': (taskId: string, result: TaskResult) => void;
42
+ }
43
+ export declare class A2AClient extends EventEmitter {
44
+ private config;
45
+ private connections;
46
+ private pendingRequests;
47
+ private knownAgents;
48
+ private trustCache;
49
+ private metrics;
50
+ constructor(config: A2AClientConfig);
51
+ discover(options?: {
52
+ capabilities?: string[];
53
+ minTrust?: number;
54
+ limit?: number;
55
+ }): Promise<AgentAnnouncement[]>;
56
+ ping(agentId: A2AAgentId): Promise<{
57
+ latency: number;
58
+ version: string;
59
+ }>;
60
+ announce(announcement: AgentAnnouncement): Promise<void>;
61
+ registerAgent(announcement: AgentAnnouncement): void;
62
+ getCapabilities(agentId: A2AAgentId): Promise<AgentCapability[]>;
63
+ queryCapabilities(query: {
64
+ category?: string;
65
+ tags?: string[];
66
+ search?: string;
67
+ maxCostTier?: string;
68
+ }): Promise<Array<{
69
+ agent: AgentAnnouncement;
70
+ capability: AgentCapability;
71
+ }>>;
72
+ delegateTask(agentId: A2AAgentId, capabilityId: string, input: Record<string, unknown>, options?: {
73
+ priority?: TaskRequest['priority'];
74
+ timeout?: number;
75
+ payment?: PaymentCommitment;
76
+ onProgress?: (progress: TaskProgress) => void;
77
+ }): Promise<TaskResult>;
78
+ cancelTask(agentId: A2AAgentId, taskId: string, reason?: string): Promise<void>;
79
+ private waitForTaskCompletion;
80
+ validateResult(agentId: A2AAgentId, taskId: string, result: TaskResult): Promise<{
81
+ valid: boolean;
82
+ score: number;
83
+ issues?: string[];
84
+ }>;
85
+ disputeResult(agentId: A2AAgentId, taskId: string, reason: string, resolution: 'refund' | 'redo' | 'partial-refund' | 'arbitration'): Promise<void>;
86
+ getTrust(agentId: A2AAgentId): Promise<TrustScore>;
87
+ attestTrust(agentId: A2AAgentId, type: 'task-completion' | 'quality' | 'behavior', rating: number, taskId?: string, comment?: string): Promise<void>;
88
+ reportAgent(agentId: A2AAgentId, type: 'spam' | 'fraud' | 'abuse' | 'quality' | 'payment', severity: 'low' | 'medium' | 'high' | 'critical', description: string, evidence?: unknown): Promise<void>;
89
+ getQuote(agentId: A2AAgentId, capabilityId: string, estimatedInput?: Record<string, unknown>): Promise<PaymentQuote>;
90
+ negotiatePayment(agentId: A2AAgentId, quoteId: string, counterOffer?: number): Promise<{
91
+ accepted: boolean;
92
+ finalPrice?: number;
93
+ }>;
94
+ commitPayment(quote: PaymentQuote): Promise<PaymentCommitment>;
95
+ releasePayment(agentId: A2AAgentId, commitmentId: string, taskId: string, reason?: 'completed' | 'partial' | 'refund'): Promise<void>;
96
+ private sendRequest;
97
+ private sendWithRetry;
98
+ private send;
99
+ private selectEndpoint;
100
+ private sendHttp;
101
+ private sign;
102
+ private findCapability;
103
+ private getDefaultTrust;
104
+ private trustLevelToScore;
105
+ private log;
106
+ getMetrics(): {
107
+ knownAgents: number;
108
+ pendingRequests: number;
109
+ requestsSent: number;
110
+ responsesReceived: number;
111
+ errors: number;
112
+ avgLatency: number;
113
+ tasksDelegated: number;
114
+ tasksCompleted: number;
115
+ };
116
+ }
117
+ export declare function generateA2AKeyPair(): A2AKeyPair;
@@ -0,0 +1,506 @@
1
+ "use strict";
2
+ /**
3
+ * Genesis A2A Client
4
+ *
5
+ * Client for discovering and communicating with remote Genesis agents.
6
+ * Supports HTTP, WebSocket, and MessageBus transports.
7
+ */
8
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9
+ if (k2 === undefined) k2 = k;
10
+ var desc = Object.getOwnPropertyDescriptor(m, k);
11
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
12
+ desc = { enumerable: true, get: function() { return m[k]; } };
13
+ }
14
+ Object.defineProperty(o, k2, desc);
15
+ }) : (function(o, m, k, k2) {
16
+ if (k2 === undefined) k2 = k;
17
+ o[k2] = m[k];
18
+ }));
19
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
20
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
21
+ }) : function(o, v) {
22
+ o["default"] = v;
23
+ });
24
+ var __importStar = (this && this.__importStar) || (function () {
25
+ var ownKeys = function(o) {
26
+ ownKeys = Object.getOwnPropertyNames || function (o) {
27
+ var ar = [];
28
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
29
+ return ar;
30
+ };
31
+ return ownKeys(o);
32
+ };
33
+ return function (mod) {
34
+ if (mod && mod.__esModule) return mod;
35
+ var result = {};
36
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
37
+ __setModuleDefault(result, mod);
38
+ return result;
39
+ };
40
+ })();
41
+ Object.defineProperty(exports, "__esModule", { value: true });
42
+ exports.A2AClient = void 0;
43
+ exports.generateA2AKeyPair = generateA2AKeyPair;
44
+ const events_1 = require("events");
45
+ const crypto = __importStar(require("crypto"));
46
+ const protocol_js_1 = require("./protocol.js");
47
+ // ============================================================================
48
+ // A2A Client Class
49
+ // ============================================================================
50
+ class A2AClient extends events_1.EventEmitter {
51
+ config;
52
+ connections = new Map();
53
+ pendingRequests = new Map();
54
+ knownAgents = new Map();
55
+ trustCache = new Map();
56
+ metrics = {
57
+ requestsSent: 0,
58
+ responsesReceived: 0,
59
+ errors: 0,
60
+ avgLatency: 0,
61
+ tasksDelegated: 0,
62
+ tasksCompleted: 0,
63
+ };
64
+ constructor(config) {
65
+ super();
66
+ this.config = {
67
+ defaultTimeout: 30000,
68
+ autoRetry: true,
69
+ maxRetries: 3,
70
+ debug: false,
71
+ ...config,
72
+ };
73
+ }
74
+ // ============================================================================
75
+ // Discovery
76
+ // ============================================================================
77
+ async discover(options = {}) {
78
+ if (this.config.directory) {
79
+ return this.config.directory.search(options);
80
+ }
81
+ const message = (0, protocol_js_1.createA2AMessage)('a2a.discover', {
82
+ from: this.config.agentId,
83
+ filter: {
84
+ capabilities: options.capabilities,
85
+ minTrust: options.minTrust,
86
+ limit: options.limit,
87
+ },
88
+ });
89
+ this.log('Broadcasting discovery request');
90
+ return Array.from(this.knownAgents.values());
91
+ }
92
+ async ping(agentId) {
93
+ const startTime = Date.now();
94
+ const response = await this.sendRequest(agentId, 'a2a.ping', {
95
+ from: this.config.agentId,
96
+ to: agentId,
97
+ });
98
+ return {
99
+ latency: Date.now() - startTime,
100
+ version: response.result?.version || 'unknown',
101
+ };
102
+ }
103
+ async announce(announcement) {
104
+ if (this.config.directory) {
105
+ await this.config.directory.register(announcement);
106
+ }
107
+ this.knownAgents.set(this.config.agentId, announcement);
108
+ this.log(`Announced agent ${this.config.agentId}`);
109
+ }
110
+ registerAgent(announcement) {
111
+ this.knownAgents.set(announcement.agentId, announcement);
112
+ }
113
+ // ============================================================================
114
+ // Capability Queries
115
+ // ============================================================================
116
+ async getCapabilities(agentId) {
117
+ const response = await this.sendRequest(agentId, 'a2a.capabilities.list', {
118
+ from: this.config.agentId,
119
+ to: agentId,
120
+ });
121
+ return response.result?.capabilities || [];
122
+ }
123
+ async queryCapabilities(query) {
124
+ const results = [];
125
+ for (const agent of this.knownAgents.values()) {
126
+ for (const cap of agent.capabilities) {
127
+ let matches = true;
128
+ if (query.category && cap.category !== query.category)
129
+ matches = false;
130
+ if (query.tags && !query.tags.some((t) => cap.tags?.includes(t)))
131
+ matches = false;
132
+ if (query.search && !cap.name.toLowerCase().includes(query.search.toLowerCase())) {
133
+ matches = false;
134
+ }
135
+ if (matches) {
136
+ results.push({ agent, capability: cap });
137
+ }
138
+ }
139
+ }
140
+ return results;
141
+ }
142
+ // ============================================================================
143
+ // Task Delegation
144
+ // ============================================================================
145
+ async delegateTask(agentId, capabilityId, input, options = {}) {
146
+ this.metrics.tasksDelegated++;
147
+ const trust = await this.getTrust(agentId);
148
+ const capability = await this.findCapability(agentId, capabilityId);
149
+ if (capability?.requiredTrust) {
150
+ const requiredLevel = this.trustLevelToScore(capability.requiredTrust);
151
+ if (trust.overall < requiredLevel) {
152
+ throw new Error(`Insufficient trust: ${trust.overall} < ${requiredLevel}`);
153
+ }
154
+ }
155
+ let payment = options.payment;
156
+ if (capability && capability.costTier !== 'free' && !payment) {
157
+ const quote = await this.getQuote(agentId, capabilityId, input);
158
+ payment = await this.commitPayment(quote);
159
+ }
160
+ const message = (0, protocol_js_1.createTaskRequest)(this.config.agentId, agentId, capabilityId, input, {
161
+ priority: options.priority,
162
+ timeout: options.timeout || this.config.defaultTimeout,
163
+ payment,
164
+ });
165
+ const taskId = message.params.task.id;
166
+ if (options.onProgress) {
167
+ const progressHandler = (progress) => {
168
+ if (progress.taskId === taskId) {
169
+ options.onProgress(progress);
170
+ }
171
+ };
172
+ this.on('task:progress', progressHandler);
173
+ this.once('task:complete', (completedId) => {
174
+ if (completedId === taskId) {
175
+ this.off('task:progress', progressHandler);
176
+ }
177
+ });
178
+ }
179
+ const response = await this.sendRequest(agentId, 'a2a.task.request', message.params, {
180
+ timeout: options.timeout || this.config.defaultTimeout * 2,
181
+ });
182
+ if (response.result?.accepted === false) {
183
+ throw new Error(response.result?.reason || 'Task rejected');
184
+ }
185
+ const result = await this.waitForTaskCompletion(taskId, options.timeout);
186
+ this.metrics.tasksCompleted++;
187
+ return result;
188
+ }
189
+ async cancelTask(agentId, taskId, reason) {
190
+ await this.sendRequest(agentId, 'a2a.task.cancel', {
191
+ from: this.config.agentId,
192
+ to: agentId,
193
+ taskId,
194
+ reason,
195
+ });
196
+ }
197
+ async waitForTaskCompletion(taskId, timeout) {
198
+ return new Promise((resolve, reject) => {
199
+ const timeoutMs = timeout || this.config.defaultTimeout * 2;
200
+ const timeoutId = setTimeout(() => {
201
+ this.off('task:complete', handler);
202
+ reject(new Error(`Task ${taskId} timed out after ${timeoutMs}ms`));
203
+ }, timeoutMs);
204
+ const handler = (completedId, result) => {
205
+ if (completedId === taskId) {
206
+ clearTimeout(timeoutId);
207
+ this.off('task:complete', handler);
208
+ resolve(result);
209
+ }
210
+ };
211
+ this.on('task:complete', handler);
212
+ });
213
+ }
214
+ // ============================================================================
215
+ // Result Validation
216
+ // ============================================================================
217
+ async validateResult(agentId, taskId, result) {
218
+ const response = await this.sendRequest(agentId, 'a2a.result.validate', {
219
+ from: this.config.agentId,
220
+ to: agentId,
221
+ taskId,
222
+ result,
223
+ });
224
+ return response.result;
225
+ }
226
+ async disputeResult(agentId, taskId, reason, resolution) {
227
+ await this.sendRequest(agentId, 'a2a.result.dispute', {
228
+ from: this.config.agentId,
229
+ to: agentId,
230
+ taskId,
231
+ dispute: { taskId, reason, resolution },
232
+ });
233
+ }
234
+ // ============================================================================
235
+ // Trust & Reputation
236
+ // ============================================================================
237
+ async getTrust(agentId) {
238
+ const cached = this.trustCache.get(agentId);
239
+ if (cached) {
240
+ return cached;
241
+ }
242
+ try {
243
+ const response = await this.sendRequest(agentId, 'a2a.trust.query', {
244
+ from: this.config.agentId,
245
+ query: { agentId },
246
+ });
247
+ const trust = response.result;
248
+ this.trustCache.set(agentId, trust);
249
+ return trust;
250
+ }
251
+ catch {
252
+ return this.getDefaultTrust(agentId);
253
+ }
254
+ }
255
+ async attestTrust(agentId, type, rating, taskId, comment) {
256
+ const attestation = {
257
+ id: crypto.randomUUID(),
258
+ from: this.config.agentId,
259
+ about: agentId,
260
+ type,
261
+ rating,
262
+ taskId,
263
+ comment,
264
+ timestamp: new Date().toISOString(),
265
+ signature: this.sign(JSON.stringify({ agentId, type, rating, taskId })),
266
+ };
267
+ await this.sendRequest(agentId, 'a2a.trust.attest', {
268
+ from: this.config.agentId,
269
+ to: agentId,
270
+ about: agentId,
271
+ attestation,
272
+ });
273
+ this.trustCache.delete(agentId);
274
+ }
275
+ async reportAgent(agentId, type, severity, description, evidence) {
276
+ await this.sendRequest(agentId, 'a2a.trust.report', {
277
+ from: this.config.agentId,
278
+ about: agentId,
279
+ report: {
280
+ id: crypto.randomUUID(),
281
+ from: this.config.agentId,
282
+ about: agentId,
283
+ type,
284
+ severity,
285
+ description,
286
+ evidence,
287
+ },
288
+ });
289
+ }
290
+ // ============================================================================
291
+ // Payment
292
+ // ============================================================================
293
+ async getQuote(agentId, capabilityId, estimatedInput) {
294
+ const response = await this.sendRequest(agentId, 'a2a.payment.quote', {
295
+ from: this.config.agentId,
296
+ to: agentId,
297
+ quote: {
298
+ id: crypto.randomUUID(),
299
+ capabilityId,
300
+ estimatedInput,
301
+ price: 0,
302
+ currency: 'credits',
303
+ validUntil: new Date(Date.now() + 3600000).toISOString(),
304
+ },
305
+ });
306
+ return response.result;
307
+ }
308
+ async negotiatePayment(agentId, quoteId, counterOffer) {
309
+ const response = await this.sendRequest(agentId, 'a2a.payment.negotiate', {
310
+ from: this.config.agentId,
311
+ to: agentId,
312
+ negotiation: { quoteId, counterOffer, round: 1 },
313
+ });
314
+ return response.result;
315
+ }
316
+ async commitPayment(quote) {
317
+ return {
318
+ id: crypto.randomUUID(),
319
+ quoteId: quote.id,
320
+ amount: quote.price,
321
+ currency: quote.currency,
322
+ conditions: [{ type: 'task-complete' }],
323
+ };
324
+ }
325
+ async releasePayment(agentId, commitmentId, taskId, reason = 'completed') {
326
+ await this.sendRequest(agentId, 'a2a.payment.release', {
327
+ from: this.config.agentId,
328
+ to: agentId,
329
+ release: { commitmentId, amount: 0, taskId, reason },
330
+ });
331
+ }
332
+ // ============================================================================
333
+ // Transport Layer
334
+ // ============================================================================
335
+ async sendRequest(agentId, method, params, options = {}) {
336
+ const message = (0, protocol_js_1.createA2AMessage)(method, params);
337
+ message.signature = this.sign(JSON.stringify({ method, params }));
338
+ this.metrics.requestsSent++;
339
+ return this.sendWithRetry(agentId, message, options.timeout);
340
+ }
341
+ async sendWithRetry(agentId, message, timeout, attempt = 1) {
342
+ try {
343
+ return await this.send(agentId, message, timeout);
344
+ }
345
+ catch (error) {
346
+ if (this.config.autoRetry && attempt < (this.config.maxRetries || 3)) {
347
+ const delay = Math.pow(2, attempt) * 1000;
348
+ await new Promise((resolve) => setTimeout(resolve, delay));
349
+ return this.sendWithRetry(agentId, message, timeout, attempt + 1);
350
+ }
351
+ throw error;
352
+ }
353
+ }
354
+ async send(agentId, message, timeout) {
355
+ const agent = this.knownAgents.get(agentId);
356
+ if (!agent) {
357
+ if (this.config.directory) {
358
+ const discovered = await this.config.directory.lookup(agentId);
359
+ if (discovered) {
360
+ this.knownAgents.set(agentId, discovered);
361
+ return this.send(agentId, message, timeout);
362
+ }
363
+ }
364
+ throw new Error(`Unknown agent: ${agentId}`);
365
+ }
366
+ const endpoint = this.selectEndpoint(agent.endpoints);
367
+ switch (endpoint.transport) {
368
+ case 'http':
369
+ return this.sendHttp(endpoint, message, timeout);
370
+ case 'websocket':
371
+ throw new Error('WebSocket transport not yet implemented');
372
+ case 'messagebus':
373
+ throw new Error('MessageBus transport not yet implemented');
374
+ default:
375
+ throw new Error(`Unsupported transport: ${endpoint.transport}`);
376
+ }
377
+ }
378
+ selectEndpoint(endpoints) {
379
+ const ws = endpoints.find((e) => e.transport === 'websocket');
380
+ if (ws)
381
+ return ws;
382
+ const http = endpoints.find((e) => e.transport === 'http');
383
+ if (http)
384
+ return http;
385
+ return endpoints[0];
386
+ }
387
+ async sendHttp(endpoint, message, timeout) {
388
+ const url = endpoint.secure ? `https://${endpoint.url}` : `http://${endpoint.url}`;
389
+ const port = endpoint.port ? `:${endpoint.port}` : '';
390
+ const controller = new AbortController();
391
+ const timeoutId = setTimeout(() => controller.abort(), timeout || this.config.defaultTimeout);
392
+ try {
393
+ const response = await fetch(`${url}${port}/a2a`, {
394
+ method: 'POST',
395
+ headers: {
396
+ 'Content-Type': 'application/json',
397
+ 'X-A2A-Protocol': protocol_js_1.A2A_PROTOCOL_VERSION,
398
+ },
399
+ body: JSON.stringify(message),
400
+ signal: controller.signal,
401
+ });
402
+ clearTimeout(timeoutId);
403
+ if (!response.ok) {
404
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
405
+ }
406
+ const result = (await response.json());
407
+ this.metrics.responsesReceived++;
408
+ if (result.error) {
409
+ throw new Error(`A2A Error ${result.error.code}: ${result.error.message}`);
410
+ }
411
+ return result;
412
+ }
413
+ catch (error) {
414
+ clearTimeout(timeoutId);
415
+ this.metrics.errors++;
416
+ throw error;
417
+ }
418
+ }
419
+ // ============================================================================
420
+ // Cryptography
421
+ // ============================================================================
422
+ sign(data) {
423
+ const nonce = crypto.randomUUID();
424
+ const timestamp = new Date().toISOString();
425
+ const payload = `${data}:${nonce}:${timestamp}`;
426
+ const signature = crypto
427
+ .createHmac('sha256', this.config.keyPair.privateKey)
428
+ .update(payload)
429
+ .digest('hex');
430
+ return {
431
+ algorithm: this.config.keyPair.algorithm,
432
+ publicKey: this.config.keyPair.publicKey,
433
+ value: signature,
434
+ timestamp,
435
+ nonce,
436
+ };
437
+ }
438
+ // ============================================================================
439
+ // Utilities
440
+ // ============================================================================
441
+ async findCapability(agentId, capabilityId) {
442
+ const agent = this.knownAgents.get(agentId);
443
+ if (agent) {
444
+ return agent.capabilities.find((c) => c.id === capabilityId) || null;
445
+ }
446
+ const capabilities = await this.getCapabilities(agentId);
447
+ return capabilities.find((c) => c.id === capabilityId) || null;
448
+ }
449
+ getDefaultTrust(agentId) {
450
+ return {
451
+ agentId,
452
+ overall: 0.5,
453
+ components: {
454
+ reliability: 0.5,
455
+ quality: 0.5,
456
+ responsiveness: 0.5,
457
+ financial: 0.5,
458
+ },
459
+ level: 'basic',
460
+ interactions: 0,
461
+ confidence: 0.1,
462
+ };
463
+ }
464
+ trustLevelToScore(level) {
465
+ const levels = {
466
+ untrusted: 0,
467
+ minimal: 0.2,
468
+ basic: 0.4,
469
+ verified: 0.6,
470
+ trusted: 0.8,
471
+ 'highly-trusted': 0.95,
472
+ };
473
+ return levels[level] || 0;
474
+ }
475
+ log(message) {
476
+ if (this.config.debug) {
477
+ console.log(`[A2AClient:${this.config.agentId.split(':').pop()}] ${message}`);
478
+ }
479
+ }
480
+ // ============================================================================
481
+ // Metrics
482
+ // ============================================================================
483
+ getMetrics() {
484
+ return {
485
+ ...this.metrics,
486
+ knownAgents: this.knownAgents.size,
487
+ pendingRequests: this.pendingRequests.size,
488
+ };
489
+ }
490
+ }
491
+ exports.A2AClient = A2AClient;
492
+ // ============================================================================
493
+ // Key Generation Utility
494
+ // ============================================================================
495
+ function generateA2AKeyPair() {
496
+ const id = crypto.randomUUID();
497
+ const privateKey = crypto.randomBytes(32).toString('hex');
498
+ const publicKey = crypto.createHash('sha256').update(privateKey).digest('hex');
499
+ return {
500
+ keyId: id,
501
+ privateKey,
502
+ publicKey,
503
+ algorithm: 'ed25519',
504
+ created: new Date().toISOString(),
505
+ };
506
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Genesis A2A Protocol
3
+ *
4
+ * Agent-to-Agent communication for distributed Genesis collaboration.
5
+ *
6
+ * Enables Genesis instances to:
7
+ * - Discover each other on a network
8
+ * - Advertise and query capabilities
9
+ * - Delegate tasks with payment negotiation
10
+ * - Build trust through attestations
11
+ *
12
+ * Scientific Grounding:
13
+ * - Global Workspace Theory: Network-wide capability broadcast
14
+ * - Free Energy Principle: Trust minimizes surprise in outcomes
15
+ * - Autopoiesis: Agents maintain identity via signatures
16
+ */
17
+ export { A2A_PROTOCOL_VERSION, type A2AAgentId, type A2AEndpoint, type A2AMessage, type A2AResponse, type A2AError, type A2AMethod, type A2AParams, A2AErrorCode, type AgentCapability, type CapabilityCategory, type CapabilityQuery, type PricingModel, type RateLimit, type DiscoveryParams, type DiscoveryFilter, type AgentAnnouncement, type TaskRequest, type TaskPriority, type TaskContext, type TaskProgress, type TaskResult, type TaskMetrics, type TaskArtifact, type RetryPolicy, type ResultParams, type ResultValidation, type ValidationIssue, type ResultDispute, type TrustLevel, type TrustScore, type TrustAttestation, type TrustReport, type TrustQuery, type TrustParams, type PaymentQuote, type PaymentNegotiation, type PaymentCommitment, type PaymentCondition, type PaymentRelease, type PaymentDispute, type PaymentParams, type A2ASignature, type A2AKeyPair, type StreamParams, createA2AMessage, createA2AResponse, createA2AError, createTaskRequest, createCapabilityAdvertisement, } from './protocol.js';
18
+ export { A2AClient, generateA2AKeyPair, type A2AClientConfig, type AgentDirectory, type PendingRequest, type A2AClientEvents, } from './client.js';
19
+ export { A2AServer, type A2AServerConfig, type ActiveTask, type A2AMethodHandler, type HandlerContext, } from './server.js';
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ /**
3
+ * Genesis A2A Protocol
4
+ *
5
+ * Agent-to-Agent communication for distributed Genesis collaboration.
6
+ *
7
+ * Enables Genesis instances to:
8
+ * - Discover each other on a network
9
+ * - Advertise and query capabilities
10
+ * - Delegate tasks with payment negotiation
11
+ * - Build trust through attestations
12
+ *
13
+ * Scientific Grounding:
14
+ * - Global Workspace Theory: Network-wide capability broadcast
15
+ * - Free Energy Principle: Trust minimizes surprise in outcomes
16
+ * - Autopoiesis: Agents maintain identity via signatures
17
+ */
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.A2AServer = exports.generateA2AKeyPair = exports.A2AClient = exports.createCapabilityAdvertisement = exports.createTaskRequest = exports.createA2AError = exports.createA2AResponse = exports.createA2AMessage = exports.A2AErrorCode = exports.A2A_PROTOCOL_VERSION = void 0;
20
+ // Protocol types and constants
21
+ var protocol_js_1 = require("./protocol.js");
22
+ Object.defineProperty(exports, "A2A_PROTOCOL_VERSION", { enumerable: true, get: function () { return protocol_js_1.A2A_PROTOCOL_VERSION; } });
23
+ Object.defineProperty(exports, "A2AErrorCode", { enumerable: true, get: function () { return protocol_js_1.A2AErrorCode; } });
24
+ // Factory functions
25
+ Object.defineProperty(exports, "createA2AMessage", { enumerable: true, get: function () { return protocol_js_1.createA2AMessage; } });
26
+ Object.defineProperty(exports, "createA2AResponse", { enumerable: true, get: function () { return protocol_js_1.createA2AResponse; } });
27
+ Object.defineProperty(exports, "createA2AError", { enumerable: true, get: function () { return protocol_js_1.createA2AError; } });
28
+ Object.defineProperty(exports, "createTaskRequest", { enumerable: true, get: function () { return protocol_js_1.createTaskRequest; } });
29
+ Object.defineProperty(exports, "createCapabilityAdvertisement", { enumerable: true, get: function () { return protocol_js_1.createCapabilityAdvertisement; } });
30
+ // Client
31
+ var client_js_1 = require("./client.js");
32
+ Object.defineProperty(exports, "A2AClient", { enumerable: true, get: function () { return client_js_1.A2AClient; } });
33
+ Object.defineProperty(exports, "generateA2AKeyPair", { enumerable: true, get: function () { return client_js_1.generateA2AKeyPair; } });
34
+ // Server
35
+ var server_js_1 = require("./server.js");
36
+ Object.defineProperty(exports, "A2AServer", { enumerable: true, get: function () { return server_js_1.A2AServer; } });