forked from EvoMap/evolver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
250 lines (216 loc) · 7.64 KB
/
Copy pathindex.js
File metadata and controls
250 lines (216 loc) · 7.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
'use strict';
const path = require('path');
const os = require('os');
const { MailboxStore } = require('./mailbox/store');
const { ProxyHttpServer } = require('./server/http');
const { buildRoutes } = require('./server/routes');
const { SyncEngine } = require('./sync/engine');
const { LifecycleManager } = require('./lifecycle/manager');
const { TaskMonitor } = require('./task/monitor');
const { SkillUpdater } = require('./extensions/skillUpdater');
const { DmHandler } = require('./extensions/dmHandler');
const { SessionHandler } = require('./extensions/sessionHandler');
const DEFAULT_DATA_DIR = path.join(os.homedir(), '.evomap', 'mailbox');
class EvoMapProxy {
constructor(opts = {}) {
this.hubUrl = (opts.hubUrl || process.env.A2A_HUB_URL || '').replace(/\/+$/, '');
this.dataDir = opts.dataDir || opts.dbPath || DEFAULT_DATA_DIR;
this.port = opts.port;
this.logger = opts.logger || console;
this._skillPath = opts.skillPath || null;
this.store = null;
this.server = null;
this.sync = null;
this.lifecycle = null;
this.taskMonitor = null;
this.skillUpdater = null;
this.dmHandler = null;
this.sessionHandler = null;
this._started = false;
}
async start() {
if (this._started) throw new Error('Proxy already started');
this.store = new MailboxStore(this.dataDir);
this.lifecycle = new LifecycleManager({
hubUrl: this.hubUrl,
store: this.store,
logger: this.logger,
getTaskMeta: () => this.taskMonitor ? this.taskMonitor.getHeartbeatMeta() : {},
});
this.taskMonitor = new TaskMonitor({
store: this.store,
logger: this.logger,
});
this.skillUpdater = new SkillUpdater({
store: this.store,
skillPath: this._skillPath,
logger: this.logger,
});
this.dmHandler = new DmHandler({
store: this.store,
logger: this.logger,
});
this.sessionHandler = new SessionHandler({
store: this.store,
logger: this.logger,
});
const getHeaders = () => this.lifecycle._buildHeaders();
const taskMonitor = this.taskMonitor;
this.sync = new SyncEngine({
store: this.store,
hubUrl: this.hubUrl,
getHeaders,
logger: this.logger,
onAuthError: () => this.lifecycle.reAuthenticate(),
onInboundReceived: () => {
try { this.skillUpdater?.pollAndApply(); } catch (e) {
this.logger?.warn?.('[proxy] skillUpdater.pollAndApply failed:', e.message);
}
},
});
const proxyHandlers = {
assetFetch: (body) => this._proxyHttp('/a2a/fetch', body),
assetSearch: (body) => this._proxyHttp('/a2a/assets/search', body),
assetValidate: (body) => this._proxyHttp('/a2a/validate', body),
// ATP passthrough (#460 Bug 2): merchant/consumer flows that used to call
// hub directly via src/atp/hubClient.js must route through the proxy when
// EVOMAP_PROXY=1 so proxy sees the transaction (for audit + offline queue).
atpPost: (endpoint, body) => this._proxyHttp(endpoint, body),
atpGet: (endpoint, query) => this._proxyHttp(endpoint, null, { method: 'GET', query }),
};
const routes = buildRoutes(this.store, proxyHandlers, this.taskMonitor, {
dmHandler: this.dmHandler,
skillUpdater: this.skillUpdater,
sessionHandler: this.sessionHandler,
getHubMailboxStatus: () => this._getHubMailboxStatus(),
});
const OUTBOUND_ROUTES = [
'POST /mailbox/send',
'POST /asset/submit',
'POST /task/claim',
'POST /task/complete',
'POST /task/subscribe',
'POST /task/unsubscribe',
'POST /dm/send',
'POST /session/create',
'POST /session/join',
'POST /session/leave',
'POST /session/message',
'POST /session/delegate',
'POST /session/submit',
];
for (const key of OUTBOUND_ROUTES) {
const original = routes[key];
if (!original) continue;
routes[key] = async (ctx) => {
const result = await original(ctx);
this.sync.notifyNewOutbound();
return result;
};
}
this.server = new ProxyHttpServer(routes, {
port: this.port,
logger: this.logger,
});
const serverInfo = await this.server.start();
if (this.hubUrl) {
await this.lifecycle.hello();
this.lifecycle.startHeartbeatLoop();
this.sync.start();
} else {
this.logger.warn('[proxy] No A2A_HUB_URL set, running in offline/local mode');
}
this._started = true;
return {
url: serverInfo.url,
port: serverInfo.port,
nodeId: this.lifecycle.nodeId,
};
}
async stop() {
if (!this._started) return;
this.sync?.stop();
this.lifecycle?.stopHeartbeatLoop();
await this.server?.stop();
this.store?.close();
this._started = false;
this.logger.log('[proxy] stopped');
}
get mailbox() {
return this.store;
}
async _proxyHttp(path, body, opts = {}) {
if (!this.hubUrl) throw Object.assign(new Error('Hub not configured'), { statusCode: 503 });
const method = (opts.method || 'POST').toUpperCase();
const query = opts.query && typeof opts.query === 'object' ? opts.query : null;
const timeoutMs = opts.timeoutMs || 30_000;
let fullPath = path;
if (query) {
const qs = new URLSearchParams();
for (const [k, v] of Object.entries(query)) {
if (v !== undefined && v !== null) qs.set(k, String(v));
}
const qsString = qs.toString();
if (qsString) fullPath += (path.includes('?') ? '&' : '?') + qsString;
}
const endpoint = `${this.hubUrl}${fullPath}`;
const init = {
method,
headers: this.lifecycle._buildHeaders(),
signal: AbortSignal.timeout(timeoutMs),
};
if (method !== 'GET' && method !== 'HEAD') {
init.body = JSON.stringify(body || {});
}
const res = await fetch(endpoint, init);
if (res.status === 403 || res.status === 401) {
const recovered = await this.lifecycle.reAuthenticate();
if (recovered) {
const retryInit = {
method,
headers: this.lifecycle._buildHeaders(),
signal: AbortSignal.timeout(timeoutMs),
};
if (method !== 'GET' && method !== 'HEAD') {
retryInit.body = JSON.stringify(body || {});
}
const retry = await fetch(endpoint, retryInit);
if (!retry.ok) {
const text = await retry.text().catch(() => '');
throw Object.assign(new Error(`Hub ${retry.status}: ${text}`), { statusCode: retry.status });
}
return retry.json();
}
const text = await res.text().catch(() => '');
throw Object.assign(new Error(`Hub ${res.status} (re-auth failed): ${text}`), { statusCode: res.status });
}
if (!res.ok) {
const text = await res.text().catch(() => '');
throw Object.assign(new Error(`Hub ${res.status}: ${text}`), { statusCode: res.status });
}
return res.json();
}
async _getHubMailboxStatus() {
if (!this.hubUrl) return { error: 'Hub not configured' };
const nodeId = this.lifecycle.nodeId;
if (!nodeId) return { error: 'No node_id yet' };
const endpoint = `${this.hubUrl}/a2a/mailbox/status?node_id=${encodeURIComponent(nodeId)}`;
try {
const res = await fetch(endpoint, {
method: 'GET',
headers: this.lifecycle._buildHeaders(),
signal: AbortSignal.timeout(10_000),
});
if (!res.ok) return { error: `Hub ${res.status}` };
return res.json();
} catch (err) {
return { error: err.message };
}
}
}
async function startProxy(opts = {}) {
const proxy = new EvoMapProxy(opts);
const info = await proxy.start();
return { proxy, ...info };
}
module.exports = { EvoMapProxy, startProxy };