mcard-js 2.1.39 → 2.1.41
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.
- package/dist/AbstractSqlEngine-BSfp8S_Y.d.cts +451 -0
- package/dist/AbstractSqlEngine-BSfp8S_Y.d.ts +451 -0
- package/dist/CardCollection-MXTUJV4J.js +9 -0
- package/dist/EventProducer-AWD6YMZR.js +47 -0
- package/dist/Handle-3N4QOA3U.js +13 -0
- package/dist/IndexedDBEngine-2G5KCISA.js +11 -0
- package/dist/LLMRuntime-LBWUJ7ON.js +16 -0
- package/dist/LambdaRuntime-B6D6IQKZ.js +18 -0
- package/dist/Loader-3LSJXJQG.js +11 -0
- package/dist/MCard-H56VOJLR.js +8 -0
- package/dist/NetworkRuntime-IAFHPQSX.js +1570 -0
- package/dist/OllamaProvider-QPX2JXL2.js +8 -0
- package/dist/chunk-2R4ESMZB.js +110 -0
- package/dist/chunk-3EIBJPNF.js +17 -0
- package/dist/chunk-3LPY36OG.js +355 -0
- package/dist/chunk-3MMMJ7NH.js +1068 -0
- package/dist/chunk-42VF42KH.js +273 -0
- package/dist/chunk-4PDYHPR6.js +297 -0
- package/dist/chunk-ADV52544.js +95 -0
- package/dist/chunk-FIE4LAJG.js +215 -0
- package/dist/chunk-PNKVD2UK.js +26 -0
- package/dist/chunk-RSTKX7WM.js +907 -0
- package/dist/chunk-VXV35I5J.js +2315 -0
- package/dist/index.browser.cjs +375 -276
- package/dist/index.browser.d.cts +4 -4
- package/dist/index.browser.d.ts +4 -4
- package/dist/index.browser.js +18 -13
- package/dist/index.cjs +382 -453
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +26 -21
- package/dist/storage/SqliteNodeEngine.cjs +395 -270
- package/dist/storage/SqliteNodeEngine.d.cts +9 -94
- package/dist/storage/SqliteNodeEngine.d.ts +9 -94
- package/dist/storage/SqliteNodeEngine.js +6 -5
- package/dist/storage/SqliteWasmEngine.cjs +382 -252
- package/dist/storage/SqliteWasmEngine.d.cts +8 -29
- package/dist/storage/SqliteWasmEngine.d.ts +8 -29
- package/dist/storage/SqliteWasmEngine.js +6 -5
- package/package.json +1 -1
|
@@ -0,0 +1,1570 @@
|
|
|
1
|
+
import {
|
|
2
|
+
MCard
|
|
3
|
+
} from "./chunk-3MMMJ7NH.js";
|
|
4
|
+
import "./chunk-7NKII2JA.js";
|
|
5
|
+
import "./chunk-PNKVD2UK.js";
|
|
6
|
+
|
|
7
|
+
// src/ptr/node/NetworkRuntime.ts
|
|
8
|
+
import * as http from "http";
|
|
9
|
+
|
|
10
|
+
// src/ptr/node/P2PChatSession.ts
|
|
11
|
+
var P2PChatSession = class {
|
|
12
|
+
sessionId;
|
|
13
|
+
collection;
|
|
14
|
+
buffer = [];
|
|
15
|
+
previousHash = null;
|
|
16
|
+
sequence = 0;
|
|
17
|
+
maxBufferSize;
|
|
18
|
+
constructor(collection, sessionId, maxBufferSize = 5, initialHeadHash = null) {
|
|
19
|
+
this.collection = collection;
|
|
20
|
+
this.sessionId = sessionId;
|
|
21
|
+
this.maxBufferSize = maxBufferSize;
|
|
22
|
+
this.previousHash = initialHeadHash;
|
|
23
|
+
if (initialHeadHash) {
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Add a message to the current session buffer.
|
|
28
|
+
* Automatically checkpoints if buffer exceeds size.
|
|
29
|
+
*/
|
|
30
|
+
async addMessage(sender, content) {
|
|
31
|
+
this.buffer.push({
|
|
32
|
+
sender,
|
|
33
|
+
content,
|
|
34
|
+
timestamp: Date.now()
|
|
35
|
+
});
|
|
36
|
+
if (this.buffer.length >= this.maxBufferSize) {
|
|
37
|
+
return this.checkpoint();
|
|
38
|
+
}
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Force write the current buffer to a new MCard.
|
|
43
|
+
*/
|
|
44
|
+
async checkpoint() {
|
|
45
|
+
if (this.buffer.length === 0) {
|
|
46
|
+
return this.previousHash || "";
|
|
47
|
+
}
|
|
48
|
+
const payload = {
|
|
49
|
+
type: "p2p_session_segment",
|
|
50
|
+
sessionId: this.sessionId,
|
|
51
|
+
sequence: this.sequence++,
|
|
52
|
+
messages: [...this.buffer],
|
|
53
|
+
previousHash: this.previousHash,
|
|
54
|
+
timestamp: Date.now()
|
|
55
|
+
};
|
|
56
|
+
const card = await MCard.create(JSON.stringify(payload));
|
|
57
|
+
await this.collection.add(card);
|
|
58
|
+
this.previousHash = card.hash;
|
|
59
|
+
this.buffer = [];
|
|
60
|
+
console.log(`[P2PSession] Checkpoint created: ${card.hash} (Seq: ${payload.sequence})`);
|
|
61
|
+
return card.hash;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Get the hash of the latest segment (Head of the list)
|
|
65
|
+
*/
|
|
66
|
+
getHeadHash() {
|
|
67
|
+
return this.previousHash;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Compile all segments into one MCard and remove original segments unless keepOriginals is true.
|
|
71
|
+
*/
|
|
72
|
+
async summarize(keepOriginals = false) {
|
|
73
|
+
if (this.buffer.length > 0) {
|
|
74
|
+
await this.checkpoint();
|
|
75
|
+
}
|
|
76
|
+
const headToUse = this.previousHash || null;
|
|
77
|
+
console.log(`[P2PSession] Summarizing session starting from head: ${headToUse}`);
|
|
78
|
+
const { messages, hashes } = headToUse ? await this.traverseChain(headToUse) : { messages: [], hashes: [] };
|
|
79
|
+
const summaryPayload = {
|
|
80
|
+
type: "p2p_session_summary",
|
|
81
|
+
sessionId: this.sessionId,
|
|
82
|
+
originalHeadHash: headToUse,
|
|
83
|
+
// Cast or update interface
|
|
84
|
+
fullTranscript: messages,
|
|
85
|
+
timestamp: Date.now()
|
|
86
|
+
};
|
|
87
|
+
const summaryContent = JSON.stringify(summaryPayload, null, 2);
|
|
88
|
+
const summaryCard = await MCard.create(summaryContent);
|
|
89
|
+
await this.collection.add(summaryCard);
|
|
90
|
+
console.log(`[P2PSession] Summary created: ${summaryCard.hash}`);
|
|
91
|
+
if (!keepOriginals) {
|
|
92
|
+
console.log(`[P2PSession] Cleaning up ${hashes.length} segment MCards...`);
|
|
93
|
+
for (const hash of hashes) {
|
|
94
|
+
try {
|
|
95
|
+
await this.collection.delete(hash);
|
|
96
|
+
} catch (e) {
|
|
97
|
+
console.error(`[P2PSession] Failed to delete segment ${hash}`, e);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
console.log(`[P2PSession] Cleanup complete.`);
|
|
101
|
+
} else {
|
|
102
|
+
console.log(`[P2PSession] Skipping cleanup (keepOriginals=true). Preserved ${hashes.length} segments.`);
|
|
103
|
+
}
|
|
104
|
+
return summaryCard.hash;
|
|
105
|
+
}
|
|
106
|
+
async traverseChain(headHash) {
|
|
107
|
+
const messages = [];
|
|
108
|
+
const hashes = [];
|
|
109
|
+
let currentHash = headHash;
|
|
110
|
+
while (currentHash) {
|
|
111
|
+
hashes.push(currentHash);
|
|
112
|
+
const card = await this.collection.get(currentHash);
|
|
113
|
+
if (!card) {
|
|
114
|
+
console.warn(`[P2PSession] Broken chain at ${currentHash}`);
|
|
115
|
+
break;
|
|
116
|
+
}
|
|
117
|
+
try {
|
|
118
|
+
const contentStr = new TextDecoder().decode(card.content);
|
|
119
|
+
const payload = JSON.parse(contentStr);
|
|
120
|
+
if (payload.type === "p2p_session_segment") {
|
|
121
|
+
messages.unshift(...payload.messages);
|
|
122
|
+
currentHash = payload.previousHash;
|
|
123
|
+
} else {
|
|
124
|
+
console.warn(`[P2PSession] Invalid card type at ${currentHash}`);
|
|
125
|
+
break;
|
|
126
|
+
}
|
|
127
|
+
} catch (e) {
|
|
128
|
+
console.error(`[P2PSession] Parse error at ${currentHash}`, e);
|
|
129
|
+
break;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return { messages, hashes };
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
// src/ptr/node/SignalingServer.ts
|
|
137
|
+
import { createServer } from "http";
|
|
138
|
+
import { exec } from "child_process";
|
|
139
|
+
function killProcessOnPort(port) {
|
|
140
|
+
return new Promise((resolve) => {
|
|
141
|
+
exec(`lsof -ti:${port} | xargs kill -9 2>/dev/null`, (error) => {
|
|
142
|
+
if (error) {
|
|
143
|
+
console.log(`[Signal] No existing process on port ${port} to kill`);
|
|
144
|
+
} else {
|
|
145
|
+
console.log(`[Signal] Killed existing process on port ${port}`);
|
|
146
|
+
}
|
|
147
|
+
setTimeout(resolve, 500);
|
|
148
|
+
});
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
async function createSignalingServer(config = {}) {
|
|
152
|
+
const startPort = config.port || 3e3;
|
|
153
|
+
const maxTries = config.maxPortTries || 10;
|
|
154
|
+
const autoFindPort = config.autoFindPort !== false;
|
|
155
|
+
const clients = /* @__PURE__ */ new Map();
|
|
156
|
+
const messageBuffer = /* @__PURE__ */ new Map();
|
|
157
|
+
const server = createServer((req, res) => {
|
|
158
|
+
res.setHeader("Access-Control-Allow-Origin", "*");
|
|
159
|
+
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
|
160
|
+
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
|
|
161
|
+
if (req.method === "OPTIONS") {
|
|
162
|
+
res.writeHead(204);
|
|
163
|
+
res.end();
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
const url = new URL(req.url || "/", `http://${req.headers.host}`);
|
|
167
|
+
const path = url.pathname;
|
|
168
|
+
if (req.method === "GET" && path === "/health") {
|
|
169
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
170
|
+
res.end(JSON.stringify({
|
|
171
|
+
status: "ok",
|
|
172
|
+
clients: Array.from(clients.keys()),
|
|
173
|
+
buffered: Array.from(messageBuffer.keys())
|
|
174
|
+
}));
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
if (req.method === "GET" && path === "/signal") {
|
|
178
|
+
const peerId = url.searchParams.get("peer_id");
|
|
179
|
+
if (!peerId) {
|
|
180
|
+
res.writeHead(400);
|
|
181
|
+
res.end("Missing peer_id");
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
console.log(`[Signal] Client connected: ${peerId}`);
|
|
185
|
+
res.writeHead(200, {
|
|
186
|
+
"Content-Type": "text/event-stream",
|
|
187
|
+
"Cache-Control": "no-cache",
|
|
188
|
+
"Connection": "keep-alive"
|
|
189
|
+
});
|
|
190
|
+
const keepAlive = setInterval(() => {
|
|
191
|
+
res.write(": keep-alive\n\n");
|
|
192
|
+
}, 15e3);
|
|
193
|
+
clients.set(peerId, res);
|
|
194
|
+
if (messageBuffer.has(peerId)) {
|
|
195
|
+
const msgs = messageBuffer.get(peerId);
|
|
196
|
+
for (const msg of msgs) {
|
|
197
|
+
res.write(`data: ${JSON.stringify(msg)}
|
|
198
|
+
|
|
199
|
+
`);
|
|
200
|
+
}
|
|
201
|
+
messageBuffer.delete(peerId);
|
|
202
|
+
}
|
|
203
|
+
req.on("close", () => {
|
|
204
|
+
console.log(`[Signal] Client disconnected: ${peerId}`);
|
|
205
|
+
clearInterval(keepAlive);
|
|
206
|
+
clients.delete(peerId);
|
|
207
|
+
});
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
if (req.method === "POST" && path === "/signal") {
|
|
211
|
+
let body = "";
|
|
212
|
+
req.on("data", (chunk) => body += chunk);
|
|
213
|
+
req.on("end", () => {
|
|
214
|
+
try {
|
|
215
|
+
const msg = JSON.parse(body);
|
|
216
|
+
const target = msg.target;
|
|
217
|
+
if (!target) {
|
|
218
|
+
res.writeHead(400);
|
|
219
|
+
res.end("Missing target");
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
console.log(`[Signal] Relaying ${msg.type} to ${target}`);
|
|
223
|
+
if (clients.has(target)) {
|
|
224
|
+
clients.get(target).write(`data: ${JSON.stringify(msg)}
|
|
225
|
+
|
|
226
|
+
`);
|
|
227
|
+
} else {
|
|
228
|
+
console.log(`[Signal] Target ${target} offline, buffering...`);
|
|
229
|
+
if (!messageBuffer.has(target)) {
|
|
230
|
+
messageBuffer.set(target, []);
|
|
231
|
+
}
|
|
232
|
+
messageBuffer.get(target).push(msg);
|
|
233
|
+
}
|
|
234
|
+
res.writeHead(200);
|
|
235
|
+
res.end("Sent");
|
|
236
|
+
} catch (e) {
|
|
237
|
+
console.error(e);
|
|
238
|
+
res.writeHead(500);
|
|
239
|
+
res.end(String(e));
|
|
240
|
+
}
|
|
241
|
+
});
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
res.writeHead(404);
|
|
245
|
+
res.end();
|
|
246
|
+
});
|
|
247
|
+
for (let attempt = 0; attempt < maxTries; attempt++) {
|
|
248
|
+
const port = startPort + attempt;
|
|
249
|
+
try {
|
|
250
|
+
await new Promise((resolve, reject) => {
|
|
251
|
+
server.once("error", (err) => {
|
|
252
|
+
if (err.code === "EADDRINUSE") {
|
|
253
|
+
reject(err);
|
|
254
|
+
} else {
|
|
255
|
+
reject(err);
|
|
256
|
+
}
|
|
257
|
+
});
|
|
258
|
+
server.listen(port, () => {
|
|
259
|
+
server.removeAllListeners("error");
|
|
260
|
+
resolve();
|
|
261
|
+
});
|
|
262
|
+
});
|
|
263
|
+
console.log(`[Signal] Server running on port ${port}`);
|
|
264
|
+
return {
|
|
265
|
+
success: true,
|
|
266
|
+
port,
|
|
267
|
+
server,
|
|
268
|
+
message: `Signaling server started on port ${port}`
|
|
269
|
+
};
|
|
270
|
+
} catch (err) {
|
|
271
|
+
server.removeAllListeners("error");
|
|
272
|
+
if (attempt === 0 && autoFindPort) {
|
|
273
|
+
console.log(`[Signal] Port ${port} in use, trying to kill existing process...`);
|
|
274
|
+
await killProcessOnPort(port);
|
|
275
|
+
try {
|
|
276
|
+
await new Promise((resolve, reject) => {
|
|
277
|
+
server.once("error", reject);
|
|
278
|
+
server.listen(port, () => {
|
|
279
|
+
server.removeAllListeners("error");
|
|
280
|
+
resolve();
|
|
281
|
+
});
|
|
282
|
+
});
|
|
283
|
+
console.log(`[Signal] Server running on port ${port} (after kill)`);
|
|
284
|
+
return {
|
|
285
|
+
success: true,
|
|
286
|
+
port,
|
|
287
|
+
server,
|
|
288
|
+
message: `Signaling server started on port ${port}`
|
|
289
|
+
};
|
|
290
|
+
} catch {
|
|
291
|
+
server.removeAllListeners("error");
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
if (!autoFindPort) {
|
|
295
|
+
return {
|
|
296
|
+
success: false,
|
|
297
|
+
error: `Port ${port} is already in use`
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
console.log(`[Signal] Port ${port} still in use, trying next...`);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
return {
|
|
304
|
+
success: false,
|
|
305
|
+
error: `Could not find available port after ${maxTries} attempts starting from ${startPort}`
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// src/ptr/node/network/NetworkSecurity.ts
|
|
310
|
+
var NetworkSecurity = class {
|
|
311
|
+
config;
|
|
312
|
+
constructor(config) {
|
|
313
|
+
this.config = config || this.loadSecurityConfigFromEnv();
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Load security configuration from environment variables
|
|
317
|
+
*/
|
|
318
|
+
loadSecurityConfigFromEnv() {
|
|
319
|
+
const parseList = (value) => {
|
|
320
|
+
if (!value) return void 0;
|
|
321
|
+
return value.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
|
|
322
|
+
};
|
|
323
|
+
return {
|
|
324
|
+
allowed_domains: parseList(process.env.CLM_ALLOWED_DOMAINS),
|
|
325
|
+
blocked_domains: parseList(process.env.CLM_BLOCKED_DOMAINS),
|
|
326
|
+
allowed_protocols: parseList(process.env.CLM_ALLOWED_PROTOCOLS),
|
|
327
|
+
block_private_ips: process.env.CLM_BLOCK_PRIVATE_IPS === "true",
|
|
328
|
+
block_localhost: process.env.CLM_BLOCK_LOCALHOST === "true"
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* Validate URL against security policy
|
|
333
|
+
* Throws SecurityViolationError if URL is not allowed
|
|
334
|
+
*/
|
|
335
|
+
validateUrl(urlString) {
|
|
336
|
+
let url;
|
|
337
|
+
try {
|
|
338
|
+
url = new URL(urlString);
|
|
339
|
+
} catch {
|
|
340
|
+
throw this.createSecurityError("DOMAIN_BLOCKED", `Invalid URL: ${urlString}`, urlString);
|
|
341
|
+
}
|
|
342
|
+
const hostname = url.hostname.toLowerCase();
|
|
343
|
+
const protocol = url.protocol.replace(":", "");
|
|
344
|
+
if (this.config.blocked_domains) {
|
|
345
|
+
for (const pattern of this.config.blocked_domains) {
|
|
346
|
+
if (this.matchDomainPattern(hostname, pattern)) {
|
|
347
|
+
throw this.createSecurityError(
|
|
348
|
+
"DOMAIN_BLOCKED",
|
|
349
|
+
`Domain '${hostname}' is blocked by security policy`,
|
|
350
|
+
urlString
|
|
351
|
+
);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
if (this.config.allowed_domains && this.config.allowed_domains.length > 0) {
|
|
356
|
+
const isAllowed = this.config.allowed_domains.some(
|
|
357
|
+
(pattern) => this.matchDomainPattern(hostname, pattern)
|
|
358
|
+
);
|
|
359
|
+
if (!isAllowed) {
|
|
360
|
+
throw this.createSecurityError(
|
|
361
|
+
"DOMAIN_NOT_ALLOWED",
|
|
362
|
+
`Domain '${hostname}' is not in the allowed list`,
|
|
363
|
+
urlString
|
|
364
|
+
);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
if (this.config.allowed_protocols && this.config.allowed_protocols.length > 0) {
|
|
368
|
+
if (!this.config.allowed_protocols.includes(protocol)) {
|
|
369
|
+
throw this.createSecurityError(
|
|
370
|
+
"PROTOCOL_NOT_ALLOWED",
|
|
371
|
+
`Protocol '${protocol}' is not allowed. Allowed: ${this.config.allowed_protocols.join(", ")}`,
|
|
372
|
+
urlString
|
|
373
|
+
);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
if (this.config.block_localhost) {
|
|
377
|
+
if (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1") {
|
|
378
|
+
throw this.createSecurityError(
|
|
379
|
+
"LOCALHOST_BLOCKED",
|
|
380
|
+
"Localhost access is blocked by security policy",
|
|
381
|
+
urlString
|
|
382
|
+
);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
if (this.config.block_private_ips) {
|
|
386
|
+
if (this.isPrivateIP(hostname)) {
|
|
387
|
+
throw this.createSecurityError(
|
|
388
|
+
"PRIVATE_IP_BLOCKED",
|
|
389
|
+
`Private IP '${hostname}' is blocked by security policy`,
|
|
390
|
+
urlString
|
|
391
|
+
);
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
/**
|
|
396
|
+
* Match hostname against domain pattern (supports wildcards like *.example.com)
|
|
397
|
+
*/
|
|
398
|
+
matchDomainPattern(hostname, pattern) {
|
|
399
|
+
const patternLower = pattern.toLowerCase();
|
|
400
|
+
if (patternLower.startsWith("*.")) {
|
|
401
|
+
const suffix = patternLower.slice(1);
|
|
402
|
+
return hostname.endsWith(suffix) || hostname === patternLower.slice(2);
|
|
403
|
+
}
|
|
404
|
+
return hostname === patternLower;
|
|
405
|
+
}
|
|
406
|
+
/**
|
|
407
|
+
* Check if hostname is a private IP address
|
|
408
|
+
*/
|
|
409
|
+
isPrivateIP(hostname) {
|
|
410
|
+
const privatePatterns = [
|
|
411
|
+
/^10\.\d+\.\d+\.\d+$/,
|
|
412
|
+
// 10.x.x.x
|
|
413
|
+
/^192\.168\.\d+\.\d+$/,
|
|
414
|
+
// 192.168.x.x
|
|
415
|
+
/^172\.(1[6-9]|2\d|3[01])\.\d+\.\d+$/,
|
|
416
|
+
// 172.16-31.x.x
|
|
417
|
+
/^169\.254\.\d+\.\d+$/,
|
|
418
|
+
// Link-local
|
|
419
|
+
/^fc00:/i,
|
|
420
|
+
// IPv6 private
|
|
421
|
+
/^fd00:/i
|
|
422
|
+
// IPv6 private
|
|
423
|
+
];
|
|
424
|
+
return privatePatterns.some((pattern) => pattern.test(hostname));
|
|
425
|
+
}
|
|
426
|
+
createSecurityError(code, message, url) {
|
|
427
|
+
const error = new Error(message);
|
|
428
|
+
error.securityViolation = { code, message, url };
|
|
429
|
+
return error;
|
|
430
|
+
}
|
|
431
|
+
};
|
|
432
|
+
|
|
433
|
+
// src/ptr/node/network/MCardSerialization.ts
|
|
434
|
+
var MCardSerialization = class {
|
|
435
|
+
/**
|
|
436
|
+
* Serialize an MCard to a JSON-safe payload for network transfer
|
|
437
|
+
*/
|
|
438
|
+
static serialize(card) {
|
|
439
|
+
return {
|
|
440
|
+
hash: card.hash,
|
|
441
|
+
content: Buffer.from(card.content).toString("base64"),
|
|
442
|
+
g_time: card.g_time,
|
|
443
|
+
contentType: card.contentType,
|
|
444
|
+
hashFunction: card.hashFunction
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
/**
|
|
448
|
+
* Deserialize a JSON payload back to an MCard
|
|
449
|
+
* Uses fromData if hash/g_time provided (preserves identity)
|
|
450
|
+
* Otherwise creates new MCard (generates new hash/g_time)
|
|
451
|
+
*/
|
|
452
|
+
static async deserialize(json) {
|
|
453
|
+
if (!json.content) {
|
|
454
|
+
throw new Error("Missing content in MCard payload");
|
|
455
|
+
}
|
|
456
|
+
const content = Buffer.from(json.content, "base64");
|
|
457
|
+
if (json.hash && json.g_time) {
|
|
458
|
+
return MCard.fromData(content, json.hash, json.g_time);
|
|
459
|
+
}
|
|
460
|
+
return MCard.create(content);
|
|
461
|
+
}
|
|
462
|
+
/**
|
|
463
|
+
* Verify hash matches content (optional strict mode)
|
|
464
|
+
*/
|
|
465
|
+
static verifyHash(card, expectedHash) {
|
|
466
|
+
if (card.hash !== expectedHash) {
|
|
467
|
+
console.warn(`[Network] Hash mismatch. Expected: ${expectedHash}, Got: ${card.hash}`);
|
|
468
|
+
return false;
|
|
469
|
+
}
|
|
470
|
+
return true;
|
|
471
|
+
}
|
|
472
|
+
};
|
|
473
|
+
|
|
474
|
+
// src/ptr/node/network/NetworkInfrastructure.ts
|
|
475
|
+
var RateLimiter = class {
|
|
476
|
+
limits;
|
|
477
|
+
defaultLimit;
|
|
478
|
+
constructor(tokensPerSecond = 10, maxBurst = 20) {
|
|
479
|
+
this.limits = /* @__PURE__ */ new Map();
|
|
480
|
+
this.defaultLimit = { tokensPerSecond, maxBurst };
|
|
481
|
+
}
|
|
482
|
+
/**
|
|
483
|
+
* Check if request allowed. Consumes a token if allowed.
|
|
484
|
+
*/
|
|
485
|
+
check(domain) {
|
|
486
|
+
const now = Date.now();
|
|
487
|
+
const bucket = this.limits.get(domain) || {
|
|
488
|
+
tokens: this.defaultLimit.maxBurst,
|
|
489
|
+
lastRefill: now
|
|
490
|
+
};
|
|
491
|
+
const elapsed = (now - bucket.lastRefill) / 1e3;
|
|
492
|
+
const refill = elapsed * this.defaultLimit.tokensPerSecond;
|
|
493
|
+
bucket.tokens = Math.min(this.defaultLimit.maxBurst, bucket.tokens + refill);
|
|
494
|
+
bucket.lastRefill = now;
|
|
495
|
+
if (bucket.tokens >= 1) {
|
|
496
|
+
bucket.tokens -= 1;
|
|
497
|
+
this.limits.set(domain, bucket);
|
|
498
|
+
return true;
|
|
499
|
+
}
|
|
500
|
+
this.limits.set(domain, bucket);
|
|
501
|
+
return false;
|
|
502
|
+
}
|
|
503
|
+
/**
|
|
504
|
+
* Wait until rate limit allows request
|
|
505
|
+
*/
|
|
506
|
+
async waitFor(domain) {
|
|
507
|
+
while (!this.check(domain)) {
|
|
508
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
};
|
|
512
|
+
var NetworkCache = class {
|
|
513
|
+
memoryCache;
|
|
514
|
+
collection;
|
|
515
|
+
constructor(collection) {
|
|
516
|
+
this.memoryCache = /* @__PURE__ */ new Map();
|
|
517
|
+
this.collection = collection;
|
|
518
|
+
}
|
|
519
|
+
/**
|
|
520
|
+
* Generate cache key from request config
|
|
521
|
+
*/
|
|
522
|
+
static generateKey(method, url, body) {
|
|
523
|
+
const keyData = `${method}:${url}:${body || ""}`;
|
|
524
|
+
let hash = 0;
|
|
525
|
+
for (let i = 0; i < keyData.length; i++) {
|
|
526
|
+
const char = keyData.charCodeAt(i);
|
|
527
|
+
hash = (hash << 5) - hash + char;
|
|
528
|
+
hash = hash & hash;
|
|
529
|
+
}
|
|
530
|
+
return `cache_${Math.abs(hash).toString(36)}`;
|
|
531
|
+
}
|
|
532
|
+
/**
|
|
533
|
+
* Get cached response if valid
|
|
534
|
+
*/
|
|
535
|
+
get(cacheKey) {
|
|
536
|
+
const cached = this.memoryCache.get(cacheKey);
|
|
537
|
+
if (cached && cached.expiresAt > Date.now()) {
|
|
538
|
+
return { ...cached.response, timing: { ...cached.response.timing, total: 0 } };
|
|
539
|
+
}
|
|
540
|
+
if (cached) {
|
|
541
|
+
this.memoryCache.delete(cacheKey);
|
|
542
|
+
}
|
|
543
|
+
return null;
|
|
544
|
+
}
|
|
545
|
+
/**
|
|
546
|
+
* Cache a response with TTL
|
|
547
|
+
*/
|
|
548
|
+
async set(cacheKey, response, ttlSeconds, persist = false) {
|
|
549
|
+
this.memoryCache.set(cacheKey, {
|
|
550
|
+
response,
|
|
551
|
+
expiresAt: Date.now() + ttlSeconds * 1e3
|
|
552
|
+
});
|
|
553
|
+
if (persist && this.collection) {
|
|
554
|
+
const cacheEntry = {
|
|
555
|
+
key: cacheKey,
|
|
556
|
+
response,
|
|
557
|
+
expiresAt: Date.now() + ttlSeconds * 1e3,
|
|
558
|
+
cachedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
559
|
+
};
|
|
560
|
+
const card = await MCard.create(JSON.stringify(cacheEntry));
|
|
561
|
+
await this.collection.add(card);
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
};
|
|
565
|
+
var RetryUtils = class {
|
|
566
|
+
static calculateBackoffDelay(attempt, strategy, baseDelay, maxDelay) {
|
|
567
|
+
let delay;
|
|
568
|
+
switch (strategy) {
|
|
569
|
+
case "exponential":
|
|
570
|
+
delay = baseDelay * Math.pow(2, attempt - 1);
|
|
571
|
+
break;
|
|
572
|
+
case "linear":
|
|
573
|
+
delay = baseDelay * attempt;
|
|
574
|
+
break;
|
|
575
|
+
case "constant":
|
|
576
|
+
default:
|
|
577
|
+
delay = baseDelay;
|
|
578
|
+
}
|
|
579
|
+
const jitter = delay * 0.1 * (Math.random() * 2 - 1);
|
|
580
|
+
delay = Math.round(delay + jitter);
|
|
581
|
+
return maxDelay ? Math.min(delay, maxDelay) : delay;
|
|
582
|
+
}
|
|
583
|
+
static shouldRetryStatus(status, retryOn) {
|
|
584
|
+
const defaultRetryStatuses = [408, 429, 500, 502, 503, 504];
|
|
585
|
+
const retryStatuses = retryOn || defaultRetryStatuses;
|
|
586
|
+
return retryStatuses.includes(status);
|
|
587
|
+
}
|
|
588
|
+
};
|
|
589
|
+
|
|
590
|
+
// src/ptr/node/network/HttpClient.ts
|
|
591
|
+
var HttpClient = class {
|
|
592
|
+
rateLimiter;
|
|
593
|
+
cache;
|
|
594
|
+
constructor(rateLimiter, cache) {
|
|
595
|
+
this.rateLimiter = rateLimiter;
|
|
596
|
+
this.cache = cache;
|
|
597
|
+
}
|
|
598
|
+
async request(url, method, headers, body, config) {
|
|
599
|
+
const startTime = Date.now();
|
|
600
|
+
const fetchUrl = new URL(url);
|
|
601
|
+
const cacheConfig = config.cache;
|
|
602
|
+
const cacheKey = NetworkCache.generateKey(method, fetchUrl.toString(), typeof body === "string" ? body : void 0);
|
|
603
|
+
if (cacheConfig?.enabled && method === "GET") {
|
|
604
|
+
const cachedResponse = this.cache.get(cacheKey);
|
|
605
|
+
if (cachedResponse) {
|
|
606
|
+
console.log(`[Network] Cache hit for ${url}`);
|
|
607
|
+
return { ...cachedResponse, cached: true };
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
const domain = fetchUrl.hostname;
|
|
611
|
+
await this.rateLimiter.waitFor(domain);
|
|
612
|
+
const retryConfig = config.retry || {
|
|
613
|
+
max_attempts: 1,
|
|
614
|
+
backoff: "exponential",
|
|
615
|
+
base_delay: 1e3,
|
|
616
|
+
max_delay: 3e4
|
|
617
|
+
};
|
|
618
|
+
let lastError = null;
|
|
619
|
+
let lastStatus = null;
|
|
620
|
+
let retriesAttempted = 0;
|
|
621
|
+
for (let attempt = 1; attempt <= retryConfig.max_attempts; attempt++) {
|
|
622
|
+
const timeout = config.timeout || 3e4;
|
|
623
|
+
const controller = new AbortController();
|
|
624
|
+
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
|
625
|
+
try {
|
|
626
|
+
const ttfbStart = Date.now();
|
|
627
|
+
const response = await fetch(fetchUrl.toString(), {
|
|
628
|
+
method,
|
|
629
|
+
headers,
|
|
630
|
+
body,
|
|
631
|
+
signal: controller.signal
|
|
632
|
+
});
|
|
633
|
+
clearTimeout(timeoutId);
|
|
634
|
+
if (!response.ok && RetryUtils.shouldRetryStatus(response.status, retryConfig.retry_on)) {
|
|
635
|
+
lastStatus = response.status;
|
|
636
|
+
if (attempt < retryConfig.max_attempts) {
|
|
637
|
+
retriesAttempted++;
|
|
638
|
+
const delay = RetryUtils.calculateBackoffDelay(
|
|
639
|
+
attempt,
|
|
640
|
+
retryConfig.backoff,
|
|
641
|
+
retryConfig.base_delay,
|
|
642
|
+
retryConfig.max_delay
|
|
643
|
+
);
|
|
644
|
+
console.log(`[Network] Retry ${attempt}/${retryConfig.max_attempts} for ${url} (status: ${response.status}, delay: ${delay}ms)`);
|
|
645
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
646
|
+
continue;
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
const ttfbTime = Date.now() - ttfbStart;
|
|
650
|
+
let responseBody;
|
|
651
|
+
const responseType = config.responseType || "json";
|
|
652
|
+
if (responseType === "json") {
|
|
653
|
+
try {
|
|
654
|
+
responseBody = await response.json();
|
|
655
|
+
} catch {
|
|
656
|
+
responseBody = await response.text();
|
|
657
|
+
}
|
|
658
|
+
} else if (responseType === "text") {
|
|
659
|
+
responseBody = await response.text();
|
|
660
|
+
} else if (responseType === "binary") {
|
|
661
|
+
const arrayBuffer = await response.arrayBuffer();
|
|
662
|
+
responseBody = Buffer.from(arrayBuffer).toString("base64");
|
|
663
|
+
} else {
|
|
664
|
+
responseBody = await response.text();
|
|
665
|
+
}
|
|
666
|
+
const totalTime = Date.now() - startTime;
|
|
667
|
+
let mcard_hash;
|
|
668
|
+
try {
|
|
669
|
+
const bodyStr = typeof responseBody === "string" ? responseBody : JSON.stringify(responseBody);
|
|
670
|
+
const responseCard = await MCard.create(bodyStr);
|
|
671
|
+
mcard_hash = responseCard.hash;
|
|
672
|
+
} catch {
|
|
673
|
+
}
|
|
674
|
+
const timing = {
|
|
675
|
+
dns: 0,
|
|
676
|
+
connect: 0,
|
|
677
|
+
ttfb: ttfbTime,
|
|
678
|
+
total: totalTime
|
|
679
|
+
};
|
|
680
|
+
const result = {
|
|
681
|
+
success: true,
|
|
682
|
+
status: response.status,
|
|
683
|
+
headers: Object.fromEntries(response.headers.entries()),
|
|
684
|
+
body: responseBody,
|
|
685
|
+
timing,
|
|
686
|
+
mcard_hash
|
|
687
|
+
};
|
|
688
|
+
if (cacheConfig?.enabled && method === "GET" && response.ok) {
|
|
689
|
+
await this.cache.set(cacheKey, result, cacheConfig.ttl, cacheConfig.storage === "mcard");
|
|
690
|
+
}
|
|
691
|
+
return result;
|
|
692
|
+
} catch (error) {
|
|
693
|
+
clearTimeout(timeoutId);
|
|
694
|
+
lastError = error;
|
|
695
|
+
if (attempt < retryConfig.max_attempts) {
|
|
696
|
+
retriesAttempted++;
|
|
697
|
+
const delay = RetryUtils.calculateBackoffDelay(
|
|
698
|
+
attempt,
|
|
699
|
+
retryConfig.backoff,
|
|
700
|
+
retryConfig.base_delay,
|
|
701
|
+
retryConfig.max_delay
|
|
702
|
+
);
|
|
703
|
+
console.log(`[Network] Retry ${attempt}/${retryConfig.max_attempts} for ${url} (error: ${lastError.message}, delay: ${delay}ms)`);
|
|
704
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
705
|
+
continue;
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
const err = lastError;
|
|
710
|
+
return {
|
|
711
|
+
success: false,
|
|
712
|
+
error: {
|
|
713
|
+
code: err?.name === "AbortError" ? "TIMEOUT" : "HTTP_ERROR",
|
|
714
|
+
message: err?.message || "Request failed after retries",
|
|
715
|
+
status: lastStatus,
|
|
716
|
+
retries_attempted: retriesAttempted
|
|
717
|
+
}
|
|
718
|
+
};
|
|
719
|
+
}
|
|
720
|
+
};
|
|
721
|
+
|
|
722
|
+
// src/ptr/node/NetworkRuntime.ts
|
|
723
|
+
var NetworkRuntime = class {
|
|
724
|
+
collection;
|
|
725
|
+
security;
|
|
726
|
+
cache;
|
|
727
|
+
rateLimiter;
|
|
728
|
+
httpClient;
|
|
729
|
+
sessions;
|
|
730
|
+
_signalingServer;
|
|
731
|
+
constructor(collection) {
|
|
732
|
+
this.collection = collection;
|
|
733
|
+
this.security = new NetworkSecurity();
|
|
734
|
+
this.cache = new NetworkCache(collection);
|
|
735
|
+
this.rateLimiter = new RateLimiter();
|
|
736
|
+
this.httpClient = new HttpClient(this.rateLimiter, this.cache);
|
|
737
|
+
this.sessions = /* @__PURE__ */ new Map();
|
|
738
|
+
}
|
|
739
|
+
async execute(_code, context, config, _chapterDir) {
|
|
740
|
+
const builtin = config.builtin;
|
|
741
|
+
const builtinConfig = config.config ?? {};
|
|
742
|
+
if (!builtin) {
|
|
743
|
+
throw new Error('NetworkRuntime requires "builtin" to be defined in config.');
|
|
744
|
+
}
|
|
745
|
+
switch (builtin) {
|
|
746
|
+
case "http_request":
|
|
747
|
+
return this.handleHttpRequest(builtinConfig, context);
|
|
748
|
+
case "http_get":
|
|
749
|
+
return this.handleHttpGet(builtinConfig, context);
|
|
750
|
+
case "http_post":
|
|
751
|
+
return this.handleHttpPost(builtinConfig, context);
|
|
752
|
+
case "load_url":
|
|
753
|
+
return this.handleLoadUrl(builtinConfig, context);
|
|
754
|
+
case "mcard_send":
|
|
755
|
+
return this.handleMCardSend(builtinConfig, context);
|
|
756
|
+
case "listen_http":
|
|
757
|
+
return this.handleListenHttp(builtinConfig, context);
|
|
758
|
+
case "mcard_sync":
|
|
759
|
+
return this.handleMCardSync(builtinConfig, context);
|
|
760
|
+
case "listen_sync":
|
|
761
|
+
return this.handleListenSync(builtinConfig, context);
|
|
762
|
+
case "webrtc_connect":
|
|
763
|
+
return this.handleWebRTCConnect(builtinConfig, context);
|
|
764
|
+
case "webrtc_listen":
|
|
765
|
+
return this.handleWebRTCListen(builtinConfig, context);
|
|
766
|
+
case "session_record":
|
|
767
|
+
return this.handleSessionRecord(builtinConfig, context);
|
|
768
|
+
case "mcard_read":
|
|
769
|
+
return this.handleMCardRead(builtinConfig, context);
|
|
770
|
+
case "run_command":
|
|
771
|
+
return this.handleRunCommand(builtinConfig, context);
|
|
772
|
+
case "clm_orchestrator":
|
|
773
|
+
return this.handleOrchestrator(builtinConfig, context);
|
|
774
|
+
case "signaling_server":
|
|
775
|
+
return this.handleSignalingServer(builtinConfig, context);
|
|
776
|
+
default:
|
|
777
|
+
throw new Error(`Unknown network builtin: ${builtin}`);
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
async handleHttpGet(config, context) {
|
|
781
|
+
return this.handleHttpRequest({ ...config, method: "GET" }, context);
|
|
782
|
+
}
|
|
783
|
+
async handleHttpPost(config, context) {
|
|
784
|
+
const params = { ...config, method: "POST" };
|
|
785
|
+
if (config.json) {
|
|
786
|
+
params.headers = { ...params.headers, "Content-Type": "application/json" };
|
|
787
|
+
params.body = JSON.stringify(config.json);
|
|
788
|
+
}
|
|
789
|
+
return this.handleHttpRequest(params, context);
|
|
790
|
+
}
|
|
791
|
+
async handleHttpRequest(config, context) {
|
|
792
|
+
const url = this.interpolate(config.url ?? "", context);
|
|
793
|
+
this.security.validateUrl(url);
|
|
794
|
+
const method = config.method || "GET";
|
|
795
|
+
const headers = this.interpolateHeaders(config.headers || {}, context);
|
|
796
|
+
let body = config.body;
|
|
797
|
+
if (typeof body === "string") {
|
|
798
|
+
body = this.interpolate(body, context);
|
|
799
|
+
} else if (typeof body === "object" && body !== null) {
|
|
800
|
+
body = JSON.stringify(body);
|
|
801
|
+
}
|
|
802
|
+
const fetchUrl = new URL(url);
|
|
803
|
+
if (config.query_params) {
|
|
804
|
+
for (const [key, value] of Object.entries(config.query_params)) {
|
|
805
|
+
fetchUrl.searchParams.append(key, this.interpolate(String(value), context));
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
return this.httpClient.request(
|
|
809
|
+
fetchUrl.toString(),
|
|
810
|
+
method,
|
|
811
|
+
headers,
|
|
812
|
+
body,
|
|
813
|
+
{
|
|
814
|
+
retry: config.retry,
|
|
815
|
+
cache: config.cache,
|
|
816
|
+
timeout: typeof config.timeout === "number" ? config.timeout : config.timeout?.total,
|
|
817
|
+
responseType: config.response_type
|
|
818
|
+
}
|
|
819
|
+
);
|
|
820
|
+
}
|
|
821
|
+
async handleLoadUrl(config, context) {
|
|
822
|
+
const url = this.interpolate(config.url, context);
|
|
823
|
+
this.security.validateUrl(url);
|
|
824
|
+
try {
|
|
825
|
+
const res = await fetch(url);
|
|
826
|
+
const text = await res.text();
|
|
827
|
+
return {
|
|
828
|
+
url,
|
|
829
|
+
content: text,
|
|
830
|
+
status: res.status,
|
|
831
|
+
headers: Object.fromEntries(res.headers.entries())
|
|
832
|
+
};
|
|
833
|
+
} catch (e) {
|
|
834
|
+
return { success: false, error: String(e) };
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
async handleMCardSend(config, context) {
|
|
838
|
+
if (!this.collection) {
|
|
839
|
+
throw new Error("MCard Send requires a CardCollection.");
|
|
840
|
+
}
|
|
841
|
+
const hash = this.interpolate(config.hash, context);
|
|
842
|
+
const url = this.interpolate(config.url, context);
|
|
843
|
+
const card = await this.collection.get(hash);
|
|
844
|
+
if (!card) {
|
|
845
|
+
return { success: false, error: `MCard not found: ${hash}` };
|
|
846
|
+
}
|
|
847
|
+
const payload = MCardSerialization.serialize(card);
|
|
848
|
+
return this.handleHttpPost({
|
|
849
|
+
url,
|
|
850
|
+
json: payload,
|
|
851
|
+
headers: config.headers
|
|
852
|
+
}, context);
|
|
853
|
+
}
|
|
854
|
+
async handleListenHttp(config, context) {
|
|
855
|
+
const port = Number(this.interpolate(String(config.port || 3e3), context));
|
|
856
|
+
const path = this.interpolate(config.path || "/mcard", context);
|
|
857
|
+
return new Promise((resolve, reject) => {
|
|
858
|
+
const server = http.createServer(async (req, res) => {
|
|
859
|
+
if (req.method === "POST" && req.url === path) {
|
|
860
|
+
const bodyChunks = [];
|
|
861
|
+
req.on("data", (chunk) => bodyChunks.push(chunk));
|
|
862
|
+
req.on("end", async () => {
|
|
863
|
+
try {
|
|
864
|
+
const body = Buffer.concat(bodyChunks).toString();
|
|
865
|
+
const json = JSON.parse(body);
|
|
866
|
+
const card = await MCardSerialization.deserialize(json);
|
|
867
|
+
if (json.hash) {
|
|
868
|
+
MCardSerialization.verifyHash(card, json.hash);
|
|
869
|
+
}
|
|
870
|
+
if (this.collection) {
|
|
871
|
+
await this.collection.add(card);
|
|
872
|
+
}
|
|
873
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
874
|
+
res.end(JSON.stringify({ success: true, hash: card.hash }));
|
|
875
|
+
} catch (e) {
|
|
876
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
877
|
+
res.end(JSON.stringify({ success: false, error: String(e) }));
|
|
878
|
+
}
|
|
879
|
+
});
|
|
880
|
+
} else {
|
|
881
|
+
res.writeHead(404);
|
|
882
|
+
res.end();
|
|
883
|
+
}
|
|
884
|
+
});
|
|
885
|
+
server.listen(port, () => {
|
|
886
|
+
console.log(`[Network] Listening on port ${port} at ${path}`);
|
|
887
|
+
resolve({
|
|
888
|
+
success: true,
|
|
889
|
+
message: `Server started on port ${port}`
|
|
890
|
+
});
|
|
891
|
+
});
|
|
892
|
+
server.on("error", (err) => {
|
|
893
|
+
reject(err);
|
|
894
|
+
});
|
|
895
|
+
});
|
|
896
|
+
}
|
|
897
|
+
async handleMCardSync(config, context) {
|
|
898
|
+
if (!this.collection) {
|
|
899
|
+
throw new Error("MCard Sync requires a CardCollection.");
|
|
900
|
+
}
|
|
901
|
+
const mode = this.interpolate(config.mode || "pull", context);
|
|
902
|
+
const urlParams = this.interpolate(config.url ?? "", context);
|
|
903
|
+
const url = urlParams.endsWith("/") ? urlParams.slice(0, -1) : urlParams;
|
|
904
|
+
const localCards = await this.collection.getAllMCardsRaw();
|
|
905
|
+
const localHashes = new Set(localCards.map((c) => c.hash));
|
|
906
|
+
const manifestRes = await this.handleHttpRequest({
|
|
907
|
+
url: `${url}/manifest`,
|
|
908
|
+
method: "GET"
|
|
909
|
+
}, context);
|
|
910
|
+
const manifestResult = manifestRes;
|
|
911
|
+
if (!manifestResult.success) {
|
|
912
|
+
const errorMessage = typeof manifestResult.error === "string" ? manifestResult.error : manifestResult.error?.message;
|
|
913
|
+
throw new Error(`Failed to fetch remote manifest: ${errorMessage}`);
|
|
914
|
+
}
|
|
915
|
+
const remoteHashes = new Set(manifestResult.body ?? []);
|
|
916
|
+
const stats = {
|
|
917
|
+
mode,
|
|
918
|
+
local_total: localHashes.size,
|
|
919
|
+
remote_total: remoteHashes.size,
|
|
920
|
+
synced: 0,
|
|
921
|
+
pushed: 0,
|
|
922
|
+
pulled: 0
|
|
923
|
+
};
|
|
924
|
+
const pushCards = async () => {
|
|
925
|
+
const toSend = [];
|
|
926
|
+
for (const card of localCards) {
|
|
927
|
+
if (!remoteHashes.has(card.hash)) {
|
|
928
|
+
toSend.push(card);
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
if (toSend.length > 0) {
|
|
932
|
+
const payload = {
|
|
933
|
+
cards: toSend.map((card) => MCardSerialization.serialize(card))
|
|
934
|
+
};
|
|
935
|
+
const pushRes = await this.handleHttpPost({
|
|
936
|
+
url: `${url}/batch`,
|
|
937
|
+
json: payload,
|
|
938
|
+
headers: config.headers
|
|
939
|
+
}, context);
|
|
940
|
+
const pushResult = pushRes;
|
|
941
|
+
if (!pushResult.success) {
|
|
942
|
+
const errorMessage = typeof pushResult.error === "string" ? pushResult.error : pushResult.error?.message;
|
|
943
|
+
throw new Error(`Failed to push batch: ${errorMessage}`);
|
|
944
|
+
}
|
|
945
|
+
return toSend.length;
|
|
946
|
+
}
|
|
947
|
+
return 0;
|
|
948
|
+
};
|
|
949
|
+
const pullCards = async () => {
|
|
950
|
+
const neededHashes = [];
|
|
951
|
+
for (const h of remoteHashes) {
|
|
952
|
+
if (!localHashes.has(h)) {
|
|
953
|
+
neededHashes.push(h);
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
if (neededHashes.length > 0) {
|
|
957
|
+
const fetchRes = await this.handleHttpPost({
|
|
958
|
+
url: `${url}/get`,
|
|
959
|
+
json: { hashes: neededHashes },
|
|
960
|
+
headers: config.headers
|
|
961
|
+
}, context);
|
|
962
|
+
const fetchResult = fetchRes;
|
|
963
|
+
if (!fetchResult.success) {
|
|
964
|
+
const errorMessage = typeof fetchResult.error === "string" ? fetchResult.error : fetchResult.error?.message;
|
|
965
|
+
throw new Error(`Failed to pull batch: ${errorMessage}`);
|
|
966
|
+
}
|
|
967
|
+
const receivedCards = fetchResult.body?.cards ?? [];
|
|
968
|
+
for (const json of receivedCards) {
|
|
969
|
+
const card = await MCardSerialization.deserialize(json);
|
|
970
|
+
await this.collection.add(card);
|
|
971
|
+
}
|
|
972
|
+
return receivedCards.length;
|
|
973
|
+
}
|
|
974
|
+
return 0;
|
|
975
|
+
};
|
|
976
|
+
if (mode === "push") {
|
|
977
|
+
stats.pushed = await pushCards();
|
|
978
|
+
stats.synced = stats.pushed;
|
|
979
|
+
} else if (mode === "pull") {
|
|
980
|
+
stats.pulled = await pullCards();
|
|
981
|
+
stats.synced = stats.pulled;
|
|
982
|
+
} else if (mode === "both" || mode === "bidirectional") {
|
|
983
|
+
const pushed = await pushCards();
|
|
984
|
+
const pulled = await pullCards();
|
|
985
|
+
stats.synced = pushed + pulled;
|
|
986
|
+
stats.pushed = pushed;
|
|
987
|
+
stats.pulled = pulled;
|
|
988
|
+
}
|
|
989
|
+
return { success: true, stats };
|
|
990
|
+
}
|
|
991
|
+
// ============ WebRTC Implementation ============
|
|
992
|
+
getPeerConnectionClass() {
|
|
993
|
+
if (typeof RTCPeerConnection !== "undefined") {
|
|
994
|
+
return RTCPeerConnection;
|
|
995
|
+
}
|
|
996
|
+
const globalWithRtc = globalThis;
|
|
997
|
+
if (globalWithRtc.RTCPeerConnection) {
|
|
998
|
+
return globalWithRtc.RTCPeerConnection;
|
|
999
|
+
}
|
|
1000
|
+
return null;
|
|
1001
|
+
}
|
|
1002
|
+
async handleWebRTCConnect(config, context) {
|
|
1003
|
+
const PeerConnection = this.getPeerConnectionClass();
|
|
1004
|
+
if (!PeerConnection) {
|
|
1005
|
+
return {
|
|
1006
|
+
success: false,
|
|
1007
|
+
error: "WebRTC not supported in this environment (RTCPeerConnection not found)."
|
|
1008
|
+
};
|
|
1009
|
+
}
|
|
1010
|
+
const signalingUrl = this.interpolate(config.signaling_url ?? "", context);
|
|
1011
|
+
const targetPeerId = this.interpolate(config.target_peer_id ?? "", context);
|
|
1012
|
+
const myPeerId = config.peer_id ? this.interpolate(config.peer_id, context) : `peer_${Date.now()}`;
|
|
1013
|
+
const channelLabel = config.channel_label || "mcard-sync";
|
|
1014
|
+
if (signalingUrl === "mock://p2p") {
|
|
1015
|
+
return new Promise((resolve) => {
|
|
1016
|
+
setTimeout(() => {
|
|
1017
|
+
resolve({
|
|
1018
|
+
success: true,
|
|
1019
|
+
peer_id: myPeerId,
|
|
1020
|
+
channel: channelLabel,
|
|
1021
|
+
status: "connected",
|
|
1022
|
+
mock: true
|
|
1023
|
+
});
|
|
1024
|
+
}, 100);
|
|
1025
|
+
});
|
|
1026
|
+
}
|
|
1027
|
+
console.log(`[WebRTC] Connecting to ${targetPeerId} via ${signalingUrl} as ${myPeerId}`);
|
|
1028
|
+
const pc = new PeerConnection({
|
|
1029
|
+
iceServers: config.ice_servers || [{ urls: "stun:stun.l.google.com:19302" }]
|
|
1030
|
+
});
|
|
1031
|
+
const dc = pc.createDataChannel(channelLabel);
|
|
1032
|
+
const connectionPromise = new Promise((resolve, reject) => {
|
|
1033
|
+
const timeoutMs = config.timeout || 3e4;
|
|
1034
|
+
const timeoutId = setTimeout(() => {
|
|
1035
|
+
pc.close();
|
|
1036
|
+
reject(new Error("WebRTC connection timed out"));
|
|
1037
|
+
}, timeoutMs);
|
|
1038
|
+
dc.onopen = () => {
|
|
1039
|
+
clearTimeout(timeoutId);
|
|
1040
|
+
console.log(`[WebRTC] Data channel '${channelLabel}' open`);
|
|
1041
|
+
if (config.message) {
|
|
1042
|
+
const msg = typeof config.message === "string" ? this.interpolate(config.message, context) : JSON.stringify(config.message);
|
|
1043
|
+
dc.send(msg);
|
|
1044
|
+
}
|
|
1045
|
+
resolve({
|
|
1046
|
+
success: true,
|
|
1047
|
+
peer_id: myPeerId,
|
|
1048
|
+
channel: channelLabel,
|
|
1049
|
+
status: "connected"
|
|
1050
|
+
});
|
|
1051
|
+
};
|
|
1052
|
+
dc.onerror = (err) => {
|
|
1053
|
+
clearTimeout(timeoutId);
|
|
1054
|
+
console.error("[WebRTC] Data channel error:", err);
|
|
1055
|
+
reject(err);
|
|
1056
|
+
};
|
|
1057
|
+
this._setupP2PProtocol(dc);
|
|
1058
|
+
});
|
|
1059
|
+
const offer = await pc.createOffer();
|
|
1060
|
+
await pc.setLocalDescription(offer);
|
|
1061
|
+
console.log("[WebRTC] Local Offer created. SDP ready to send.");
|
|
1062
|
+
if (config.await_response !== false) {
|
|
1063
|
+
return connectionPromise;
|
|
1064
|
+
}
|
|
1065
|
+
return {
|
|
1066
|
+
success: true,
|
|
1067
|
+
status: "initiating",
|
|
1068
|
+
peer_id: myPeerId
|
|
1069
|
+
};
|
|
1070
|
+
}
|
|
1071
|
+
_setupP2PProtocol(dc) {
|
|
1072
|
+
dc.onmessage = async (event) => {
|
|
1073
|
+
try {
|
|
1074
|
+
const msg = JSON.parse(event.data);
|
|
1075
|
+
if (msg.type === "sync_manifest") {
|
|
1076
|
+
if (!this.collection) return;
|
|
1077
|
+
const remoteHashes = new Set(msg.hashes);
|
|
1078
|
+
const localCards = await this.collection.getAllMCardsRaw();
|
|
1079
|
+
const localHashes = new Set(localCards.map((c) => c.hash));
|
|
1080
|
+
const needed = [...remoteHashes].filter((h) => !localHashes.has(h));
|
|
1081
|
+
const toPush = localCards.filter((c) => !remoteHashes.has(c.hash));
|
|
1082
|
+
if (needed.length > 0) {
|
|
1083
|
+
dc.send(JSON.stringify({ type: "sync_request", hashes: needed }));
|
|
1084
|
+
}
|
|
1085
|
+
if (toPush.length > 0) {
|
|
1086
|
+
const payload = {
|
|
1087
|
+
type: "batch_push",
|
|
1088
|
+
cards: toPush.map((c) => MCardSerialization.serialize(c))
|
|
1089
|
+
};
|
|
1090
|
+
dc.send(JSON.stringify(payload));
|
|
1091
|
+
}
|
|
1092
|
+
} else if (msg.type === "sync_request") {
|
|
1093
|
+
if (!this.collection) return;
|
|
1094
|
+
const requested = msg.hashes || [];
|
|
1095
|
+
const foundCards = [];
|
|
1096
|
+
for (const h of requested) {
|
|
1097
|
+
const c = await this.collection.get(h);
|
|
1098
|
+
if (c) foundCards.push(MCardSerialization.serialize(c));
|
|
1099
|
+
}
|
|
1100
|
+
if (foundCards.length > 0) {
|
|
1101
|
+
dc.send(JSON.stringify({ type: "batch_push", cards: foundCards }));
|
|
1102
|
+
}
|
|
1103
|
+
} else if (msg.type === "batch_push") {
|
|
1104
|
+
if (!this.collection) return;
|
|
1105
|
+
const cards = msg.cards || [];
|
|
1106
|
+
let added = 0;
|
|
1107
|
+
for (const cJson of cards) {
|
|
1108
|
+
const card = await MCardSerialization.deserialize(cJson);
|
|
1109
|
+
await this.collection.add(card);
|
|
1110
|
+
added++;
|
|
1111
|
+
}
|
|
1112
|
+
console.log(`[WebRTC] Synced ${added} cards from peer.`);
|
|
1113
|
+
}
|
|
1114
|
+
} catch (e) {
|
|
1115
|
+
console.error("[WebRTC] Protocol error:", e);
|
|
1116
|
+
}
|
|
1117
|
+
};
|
|
1118
|
+
}
|
|
1119
|
+
async handleWebRTCListen(config, context) {
|
|
1120
|
+
const PeerConnection = this.getPeerConnectionClass();
|
|
1121
|
+
if (!PeerConnection) {
|
|
1122
|
+
return {
|
|
1123
|
+
success: false,
|
|
1124
|
+
error: "WebRTC not supported in this environment (RTCPeerConnection not found)."
|
|
1125
|
+
};
|
|
1126
|
+
}
|
|
1127
|
+
const signalingUrl = this.interpolate(config.signaling_url ?? "", context);
|
|
1128
|
+
const myPeerId = config.peer_id ? this.interpolate(config.peer_id, context) : `listener_${Date.now()}`;
|
|
1129
|
+
if (signalingUrl === "mock://p2p") {
|
|
1130
|
+
return new Promise((resolve) => {
|
|
1131
|
+
setTimeout(() => {
|
|
1132
|
+
resolve({
|
|
1133
|
+
success: true,
|
|
1134
|
+
peer_id: myPeerId,
|
|
1135
|
+
status: "listening",
|
|
1136
|
+
mock: true
|
|
1137
|
+
});
|
|
1138
|
+
}, 100);
|
|
1139
|
+
});
|
|
1140
|
+
}
|
|
1141
|
+
console.log(`[WebRTC] Listening on ${signalingUrl} as ${myPeerId}`);
|
|
1142
|
+
return {
|
|
1143
|
+
success: true,
|
|
1144
|
+
status: "listening",
|
|
1145
|
+
peer_id: myPeerId,
|
|
1146
|
+
note: "Signaling loop implementation pending specific server protocol."
|
|
1147
|
+
};
|
|
1148
|
+
}
|
|
1149
|
+
async handleListenSync(config, context) {
|
|
1150
|
+
if (!this.collection) {
|
|
1151
|
+
throw new Error("Listen Sync requires a CardCollection.");
|
|
1152
|
+
}
|
|
1153
|
+
const port = Number(this.interpolate(String(config.port || 3e3), context));
|
|
1154
|
+
const basePath = this.interpolate(config.base_path || "/sync", context);
|
|
1155
|
+
return new Promise((resolve, reject) => {
|
|
1156
|
+
const server = http.createServer(async (req, res) => {
|
|
1157
|
+
const url = req.url || "";
|
|
1158
|
+
const readBody = async () => {
|
|
1159
|
+
return new Promise((res2, rej) => {
|
|
1160
|
+
const chunks = [];
|
|
1161
|
+
req.on("data", (c) => chunks.push(c));
|
|
1162
|
+
req.on("end", () => {
|
|
1163
|
+
try {
|
|
1164
|
+
const str = Buffer.concat(chunks).toString();
|
|
1165
|
+
res2(JSON.parse(str || "{}"));
|
|
1166
|
+
} catch (e) {
|
|
1167
|
+
rej(e);
|
|
1168
|
+
}
|
|
1169
|
+
});
|
|
1170
|
+
req.on("error", rej);
|
|
1171
|
+
});
|
|
1172
|
+
};
|
|
1173
|
+
try {
|
|
1174
|
+
if (req.method === "GET" && url === `${basePath}/manifest`) {
|
|
1175
|
+
const all = await this.collection.getAllMCardsRaw();
|
|
1176
|
+
const hashes = all.map((c) => c.hash);
|
|
1177
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
1178
|
+
res.end(JSON.stringify(hashes));
|
|
1179
|
+
return;
|
|
1180
|
+
}
|
|
1181
|
+
if (req.method === "POST" && url === `${basePath}/batch`) {
|
|
1182
|
+
const json = await readBody();
|
|
1183
|
+
const cards = Array.isArray(json.cards) ? json.cards : [];
|
|
1184
|
+
let added = 0;
|
|
1185
|
+
for (const cJson of cards) {
|
|
1186
|
+
const card = await MCardSerialization.deserialize(cJson);
|
|
1187
|
+
await this.collection.add(card);
|
|
1188
|
+
added++;
|
|
1189
|
+
}
|
|
1190
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
1191
|
+
res.end(JSON.stringify({ success: true, added }));
|
|
1192
|
+
return;
|
|
1193
|
+
}
|
|
1194
|
+
if (req.method === "POST" && url === `${basePath}/get`) {
|
|
1195
|
+
const json = await readBody();
|
|
1196
|
+
const requestedHashes = Array.isArray(json.hashes) ? json.hashes : [];
|
|
1197
|
+
const foundCards = [];
|
|
1198
|
+
for (const h of requestedHashes) {
|
|
1199
|
+
const card = await this.collection.get(h);
|
|
1200
|
+
if (card) {
|
|
1201
|
+
foundCards.push(MCardSerialization.serialize(card));
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
1205
|
+
res.end(JSON.stringify({ success: true, cards: foundCards }));
|
|
1206
|
+
return;
|
|
1207
|
+
}
|
|
1208
|
+
res.writeHead(404);
|
|
1209
|
+
res.end();
|
|
1210
|
+
} catch (e) {
|
|
1211
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
1212
|
+
res.end(JSON.stringify({ success: false, error: String(e) }));
|
|
1213
|
+
}
|
|
1214
|
+
});
|
|
1215
|
+
server.listen(port, () => {
|
|
1216
|
+
console.log(`[Network] Sync listening on port ${port} at ${basePath}`);
|
|
1217
|
+
resolve({
|
|
1218
|
+
success: true,
|
|
1219
|
+
message: `Sync Server started on port ${port}`,
|
|
1220
|
+
port,
|
|
1221
|
+
basePath
|
|
1222
|
+
});
|
|
1223
|
+
});
|
|
1224
|
+
server.on("error", (err) => {
|
|
1225
|
+
reject(err);
|
|
1226
|
+
});
|
|
1227
|
+
});
|
|
1228
|
+
}
|
|
1229
|
+
interpolate(text, context) {
|
|
1230
|
+
if (!text || typeof text !== "string") return text;
|
|
1231
|
+
return text.replace(/\$\{([^}]+)\}/g, (_, path) => {
|
|
1232
|
+
const keys = path.split(".");
|
|
1233
|
+
let val = context;
|
|
1234
|
+
for (const key of keys) {
|
|
1235
|
+
if (val && typeof val === "object" && key in val) {
|
|
1236
|
+
val = val[key];
|
|
1237
|
+
} else {
|
|
1238
|
+
return "";
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
return String(val);
|
|
1242
|
+
});
|
|
1243
|
+
}
|
|
1244
|
+
interpolateHeaders(headers, context) {
|
|
1245
|
+
const result = {};
|
|
1246
|
+
for (const [key, val] of Object.entries(headers)) {
|
|
1247
|
+
result[key] = this.interpolate(val, context);
|
|
1248
|
+
}
|
|
1249
|
+
return result;
|
|
1250
|
+
}
|
|
1251
|
+
async handleSessionRecord(config, context) {
|
|
1252
|
+
if (!this.collection) {
|
|
1253
|
+
throw new Error("Session Record requires a CardCollection.");
|
|
1254
|
+
}
|
|
1255
|
+
const sessionId = this.interpolate(config.sessionId ?? "", context);
|
|
1256
|
+
let operation = config.operation ?? "add";
|
|
1257
|
+
if (typeof operation === "string" && operation.includes("${")) {
|
|
1258
|
+
const interpolated = this.interpolate(operation, context);
|
|
1259
|
+
if (interpolated === "init" || interpolated === "add" || interpolated === "flush" || interpolated === "batch" || interpolated === "summarize") {
|
|
1260
|
+
operation = interpolated;
|
|
1261
|
+
}
|
|
1262
|
+
}
|
|
1263
|
+
if (operation === "init") {
|
|
1264
|
+
if (this.sessions.has(sessionId)) {
|
|
1265
|
+
return { success: true, message: "Session already exists", sessionId };
|
|
1266
|
+
}
|
|
1267
|
+
let bufferSize = config.maxBufferSize || 5;
|
|
1268
|
+
if (typeof config.maxBufferSize === "string") {
|
|
1269
|
+
bufferSize = parseInt(this.interpolate(config.maxBufferSize, context), 10);
|
|
1270
|
+
}
|
|
1271
|
+
let initialHead = config.initialHeadHash || null;
|
|
1272
|
+
if (typeof config.initialHeadHash === "string") {
|
|
1273
|
+
initialHead = this.interpolate(config.initialHeadHash, context);
|
|
1274
|
+
if (initialHead === "null" || initialHead === "undefined" || initialHead === "") initialHead = null;
|
|
1275
|
+
}
|
|
1276
|
+
const session2 = new P2PChatSession(this.collection, sessionId, bufferSize, initialHead);
|
|
1277
|
+
this.sessions.set(sessionId, session2);
|
|
1278
|
+
return { success: true, message: "Session initialized", sessionId, bufferSize, initialHead };
|
|
1279
|
+
}
|
|
1280
|
+
if (operation === "batch") {
|
|
1281
|
+
const results = [];
|
|
1282
|
+
const ctx = context;
|
|
1283
|
+
const subOps = Array.isArray(config.operations) ? config.operations : ctx?.params?.operations || ctx?.operations || [];
|
|
1284
|
+
for (const op of subOps) {
|
|
1285
|
+
const subConfig = { ...config, ...op };
|
|
1286
|
+
results.push(await this.handleSessionRecord(subConfig, context));
|
|
1287
|
+
}
|
|
1288
|
+
return {
|
|
1289
|
+
success: true,
|
|
1290
|
+
operation: "batch",
|
|
1291
|
+
results
|
|
1292
|
+
};
|
|
1293
|
+
}
|
|
1294
|
+
if (operation === "summarize") {
|
|
1295
|
+
let session2 = this.sessions.get(sessionId);
|
|
1296
|
+
if (!session2) {
|
|
1297
|
+
session2 = new P2PChatSession(this.collection, sessionId, 5, null);
|
|
1298
|
+
this.sessions.set(sessionId, session2);
|
|
1299
|
+
}
|
|
1300
|
+
const keepOriginals = config.keepOriginals === true;
|
|
1301
|
+
const summaryHash = await session2.summarize(keepOriginals);
|
|
1302
|
+
return {
|
|
1303
|
+
success: true,
|
|
1304
|
+
operation: "summarize",
|
|
1305
|
+
summary_hash: summaryHash,
|
|
1306
|
+
sessionId
|
|
1307
|
+
};
|
|
1308
|
+
}
|
|
1309
|
+
const session = this.sessions.get(sessionId);
|
|
1310
|
+
if (!session) {
|
|
1311
|
+
const newSession = new P2PChatSession(this.collection, sessionId, 5, null);
|
|
1312
|
+
this.sessions.set(sessionId, newSession);
|
|
1313
|
+
}
|
|
1314
|
+
const validSession = this.sessions.get(sessionId);
|
|
1315
|
+
if (operation === "add") {
|
|
1316
|
+
const sender = this.interpolate(config.sender || "unknown", context);
|
|
1317
|
+
const content = this.interpolate(config.content || "", context);
|
|
1318
|
+
const hash = await validSession.addMessage(sender, content);
|
|
1319
|
+
const head = validSession.getHeadHash();
|
|
1320
|
+
return {
|
|
1321
|
+
success: true,
|
|
1322
|
+
checkpoint_hash: hash,
|
|
1323
|
+
head_hash: head,
|
|
1324
|
+
sessionId
|
|
1325
|
+
};
|
|
1326
|
+
} else if (operation === "flush") {
|
|
1327
|
+
const hash = await validSession.checkpoint();
|
|
1328
|
+
return {
|
|
1329
|
+
success: true,
|
|
1330
|
+
checkpoint_hash: hash,
|
|
1331
|
+
sessionId
|
|
1332
|
+
};
|
|
1333
|
+
}
|
|
1334
|
+
return { success: false, error: `Unknown operation ${operation}` };
|
|
1335
|
+
}
|
|
1336
|
+
async handleMCardRead(config, context) {
|
|
1337
|
+
if (!this.collection) {
|
|
1338
|
+
throw new Error("MCard Read requires a CardCollection.");
|
|
1339
|
+
}
|
|
1340
|
+
const hash = this.interpolate(config.hash, context);
|
|
1341
|
+
if (!hash) throw new Error("Hash is required for mcard_read");
|
|
1342
|
+
const card = await this.collection.get(hash);
|
|
1343
|
+
if (!card) return { success: false, error: "MCard not found", hash };
|
|
1344
|
+
let content = card.getContentAsText();
|
|
1345
|
+
if (config.parse_json !== false) {
|
|
1346
|
+
try {
|
|
1347
|
+
if (typeof content === "string") {
|
|
1348
|
+
content = JSON.parse(content);
|
|
1349
|
+
}
|
|
1350
|
+
} catch (e) {
|
|
1351
|
+
}
|
|
1352
|
+
}
|
|
1353
|
+
return {
|
|
1354
|
+
success: true,
|
|
1355
|
+
hash,
|
|
1356
|
+
content,
|
|
1357
|
+
g_time: card.g_time
|
|
1358
|
+
};
|
|
1359
|
+
}
|
|
1360
|
+
async handleOrchestrator(config, context) {
|
|
1361
|
+
const steps = config.steps || [];
|
|
1362
|
+
const state = {};
|
|
1363
|
+
let allSuccess = true;
|
|
1364
|
+
console.log(`[NetworkRuntime] Starting Orchestration with ${steps.length} steps.`);
|
|
1365
|
+
for (const step of steps) {
|
|
1366
|
+
const stepName = step.name || step.action;
|
|
1367
|
+
console.log(`[Orchestrator] Step: ${stepName}`);
|
|
1368
|
+
try {
|
|
1369
|
+
if (step.action === "start_process") {
|
|
1370
|
+
const cmd = this.interpolate(step.command ?? "", context);
|
|
1371
|
+
const { spawn } = await import("child_process");
|
|
1372
|
+
const parts = cmd.split(" ");
|
|
1373
|
+
const env = { ...process.env, ...step.env || {} };
|
|
1374
|
+
const proc = spawn(parts[0], parts.slice(1), {
|
|
1375
|
+
detached: true,
|
|
1376
|
+
stdio: "inherit",
|
|
1377
|
+
cwd: process.cwd(),
|
|
1378
|
+
env
|
|
1379
|
+
});
|
|
1380
|
+
proc.unref();
|
|
1381
|
+
if (step.id_key && proc.pid !== void 0) {
|
|
1382
|
+
state[step.id_key] = proc.pid;
|
|
1383
|
+
console.log(`[Orchestrator] Process started (PID: ${proc.pid}) stored in '${step.id_key}'`);
|
|
1384
|
+
} else {
|
|
1385
|
+
console.log(`[Orchestrator] Process started (PID: ${proc.pid})`);
|
|
1386
|
+
}
|
|
1387
|
+
if (step.wait_after) {
|
|
1388
|
+
await new Promise((r) => setTimeout(r, step.wait_after));
|
|
1389
|
+
}
|
|
1390
|
+
} else if (step.action === "run_clm") {
|
|
1391
|
+
if (!context.runCLM) throw new Error("runCLM capability not available in context");
|
|
1392
|
+
const file = step.file;
|
|
1393
|
+
if (!file) {
|
|
1394
|
+
throw new Error("run_clm step requires file");
|
|
1395
|
+
}
|
|
1396
|
+
const input = step.input || {};
|
|
1397
|
+
console.log(`[Orchestrator] Running CLM: ${file}`);
|
|
1398
|
+
const res = await context.runCLM(file, input);
|
|
1399
|
+
if (!res.success) {
|
|
1400
|
+
console.error(`[Orchestrator] CLM Failed: ${file}`, res.error);
|
|
1401
|
+
if (!step.continue_on_error) {
|
|
1402
|
+
allSuccess = false;
|
|
1403
|
+
break;
|
|
1404
|
+
}
|
|
1405
|
+
} else {
|
|
1406
|
+
console.log(`[Orchestrator] CLM Passed: ${file}`);
|
|
1407
|
+
}
|
|
1408
|
+
} else if (step.action === "run_clm_background") {
|
|
1409
|
+
const file = step.file;
|
|
1410
|
+
if (!file) {
|
|
1411
|
+
throw new Error("run_clm_background step requires file");
|
|
1412
|
+
}
|
|
1413
|
+
const filter = file.replace(/\.(yaml|yml|clm)$/i, "");
|
|
1414
|
+
const cmd = `npx tsx examples/run-all-clms.ts ${filter}`;
|
|
1415
|
+
const { spawn } = await import("child_process");
|
|
1416
|
+
const parts = cmd.split(" ");
|
|
1417
|
+
const env = { ...process.env, ...step.env || {} };
|
|
1418
|
+
const proc = spawn(parts[0], parts.slice(1), {
|
|
1419
|
+
detached: true,
|
|
1420
|
+
stdio: "inherit",
|
|
1421
|
+
cwd: process.cwd(),
|
|
1422
|
+
env
|
|
1423
|
+
});
|
|
1424
|
+
proc.unref();
|
|
1425
|
+
if (step.id_key && proc.pid !== void 0) {
|
|
1426
|
+
state[step.id_key] = proc.pid;
|
|
1427
|
+
console.log(`[Orchestrator] Background CLM started (PID: ${proc.pid}) stored in '${step.id_key}'`);
|
|
1428
|
+
}
|
|
1429
|
+
if (step.wait_after) {
|
|
1430
|
+
await new Promise((r) => setTimeout(r, step.wait_after));
|
|
1431
|
+
}
|
|
1432
|
+
} else if (step.action === "stop_process") {
|
|
1433
|
+
const key = step.pid_key;
|
|
1434
|
+
if (!key) {
|
|
1435
|
+
console.warn("[Orchestrator] stop_process missing pid_key");
|
|
1436
|
+
continue;
|
|
1437
|
+
}
|
|
1438
|
+
const pid = state[key];
|
|
1439
|
+
if (typeof pid === "number") {
|
|
1440
|
+
try {
|
|
1441
|
+
context.process?.kill(pid);
|
|
1442
|
+
console.log(`[Orchestrator] Stopped process ${pid} (${key})`);
|
|
1443
|
+
} catch (e) {
|
|
1444
|
+
console.warn(`[Orchestrator] Failed to stop process ${pid}: ${e}`);
|
|
1445
|
+
}
|
|
1446
|
+
} else {
|
|
1447
|
+
console.warn(`[Orchestrator] No PID found for key '${key}'`);
|
|
1448
|
+
}
|
|
1449
|
+
} else if (step.action === "sleep") {
|
|
1450
|
+
const ms = step.ms || 1e3;
|
|
1451
|
+
await new Promise((r) => setTimeout(r, ms));
|
|
1452
|
+
} else if (step.action === "start_signaling_server") {
|
|
1453
|
+
const port = step.port || 3e3;
|
|
1454
|
+
console.log(`[Orchestrator] Starting builtin signaling server on port ${port}...`);
|
|
1455
|
+
const result = await this.handleSignalingServer({ port, background: true }, context);
|
|
1456
|
+
if (result.success) {
|
|
1457
|
+
console.log(`[Orchestrator] Signaling server started on port ${result.port}`);
|
|
1458
|
+
if (step.id_key) {
|
|
1459
|
+
state[step.id_key] = {
|
|
1460
|
+
type: "signaling_server",
|
|
1461
|
+
port: result.port,
|
|
1462
|
+
server: this._signalingServer
|
|
1463
|
+
};
|
|
1464
|
+
}
|
|
1465
|
+
} else {
|
|
1466
|
+
console.error(`[Orchestrator] Failed to start signaling server: ${result.error}`);
|
|
1467
|
+
if (!step.continue_on_error) {
|
|
1468
|
+
allSuccess = false;
|
|
1469
|
+
break;
|
|
1470
|
+
}
|
|
1471
|
+
}
|
|
1472
|
+
if (step.wait_after) {
|
|
1473
|
+
await new Promise((r) => setTimeout(r, step.wait_after));
|
|
1474
|
+
}
|
|
1475
|
+
} else if (step.action === "stop_signaling_server") {
|
|
1476
|
+
const key = step.id_key;
|
|
1477
|
+
if (!key) {
|
|
1478
|
+
console.warn("[Orchestrator] stop_signaling_server missing id_key");
|
|
1479
|
+
continue;
|
|
1480
|
+
}
|
|
1481
|
+
const serverInfo = state[key];
|
|
1482
|
+
if (typeof serverInfo === "object" && serverInfo && "server" in serverInfo && serverInfo.server) {
|
|
1483
|
+
try {
|
|
1484
|
+
serverInfo.server.close();
|
|
1485
|
+
console.log(`[Orchestrator] Signaling server stopped (${key})`);
|
|
1486
|
+
} catch (e) {
|
|
1487
|
+
console.warn(`[Orchestrator] Failed to stop signaling server: ${e}`);
|
|
1488
|
+
}
|
|
1489
|
+
} else if (this._signalingServer) {
|
|
1490
|
+
try {
|
|
1491
|
+
this._signalingServer.close();
|
|
1492
|
+
console.log(`[Orchestrator] Signaling server stopped`);
|
|
1493
|
+
} catch (e) {
|
|
1494
|
+
console.warn(`[Orchestrator] Failed to stop signaling server: ${e}`);
|
|
1495
|
+
}
|
|
1496
|
+
} else {
|
|
1497
|
+
console.warn(`[Orchestrator] No signaling server found to stop`);
|
|
1498
|
+
}
|
|
1499
|
+
}
|
|
1500
|
+
} catch (e) {
|
|
1501
|
+
console.error(`[Orchestrator] Step '${stepName}' caused error:`, e);
|
|
1502
|
+
allSuccess = false;
|
|
1503
|
+
if (!step.continue_on_error) break;
|
|
1504
|
+
}
|
|
1505
|
+
}
|
|
1506
|
+
return {
|
|
1507
|
+
success: allSuccess,
|
|
1508
|
+
state
|
|
1509
|
+
};
|
|
1510
|
+
}
|
|
1511
|
+
async handleRunCommand(config, context) {
|
|
1512
|
+
const command = this.interpolate(config.command, context);
|
|
1513
|
+
console.log(`[NetworkRuntime] Executing command: ${command}`);
|
|
1514
|
+
const { exec: exec2, spawn } = await import("child_process");
|
|
1515
|
+
if (config.background) {
|
|
1516
|
+
const parts = command.split(" ");
|
|
1517
|
+
const cmd = parts[0];
|
|
1518
|
+
const args = parts.slice(1);
|
|
1519
|
+
if (!cmd) {
|
|
1520
|
+
throw new Error("Command is required");
|
|
1521
|
+
}
|
|
1522
|
+
const subprocess = spawn(cmd, args, {
|
|
1523
|
+
detached: true,
|
|
1524
|
+
stdio: "ignore"
|
|
1525
|
+
});
|
|
1526
|
+
subprocess.unref();
|
|
1527
|
+
console.log(`[NetworkRuntime] Started background process with PID: ${subprocess.pid}`);
|
|
1528
|
+
return {
|
|
1529
|
+
success: true,
|
|
1530
|
+
pid: subprocess.pid,
|
|
1531
|
+
message: "Background process started"
|
|
1532
|
+
};
|
|
1533
|
+
}
|
|
1534
|
+
return new Promise((resolve, reject) => {
|
|
1535
|
+
exec2(command, (error, stdout, stderr) => {
|
|
1536
|
+
if (error) {
|
|
1537
|
+
console.error(`[NetworkRuntime] Command failed: ${error.message}`);
|
|
1538
|
+
return resolve({
|
|
1539
|
+
success: false,
|
|
1540
|
+
error: error.message,
|
|
1541
|
+
stderr
|
|
1542
|
+
});
|
|
1543
|
+
}
|
|
1544
|
+
console.log(`[NetworkRuntime] Command output:
|
|
1545
|
+
${stdout}`);
|
|
1546
|
+
resolve({
|
|
1547
|
+
success: true,
|
|
1548
|
+
stdout,
|
|
1549
|
+
stderr
|
|
1550
|
+
});
|
|
1551
|
+
});
|
|
1552
|
+
});
|
|
1553
|
+
}
|
|
1554
|
+
async handleSignalingServer(config, _context) {
|
|
1555
|
+
const port = config.port || 3e3;
|
|
1556
|
+
console.log(`[NetworkRuntime] Starting signaling server on port ${port}...`);
|
|
1557
|
+
const result = await createSignalingServer({
|
|
1558
|
+
port,
|
|
1559
|
+
autoFindPort: true,
|
|
1560
|
+
maxPortTries: 10
|
|
1561
|
+
});
|
|
1562
|
+
if (result.success && result.server) {
|
|
1563
|
+
this._signalingServer = result.server;
|
|
1564
|
+
}
|
|
1565
|
+
return result;
|
|
1566
|
+
}
|
|
1567
|
+
};
|
|
1568
|
+
export {
|
|
1569
|
+
NetworkRuntime
|
|
1570
|
+
};
|