mcard-js 2.1.47 → 2.1.49

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