mcard-js 2.1.41 → 2.1.43

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