@nekzus/liop 2.5.0-beta.1 → 2.5.0-beta.3

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 (104) hide show
  1. package/NOTICE +19 -0
  2. package/README.md +148 -69
  3. package/dist/bin/agent.js +27 -303
  4. package/dist/bridge.d.ts +4 -3
  5. package/dist/bridge.js +1 -4
  6. package/dist/chunk-2XHSALII.js +3 -0
  7. package/dist/chunk-2ZYX736J.js +2 -0
  8. package/dist/chunk-3WRKTVOF.js +2 -0
  9. package/dist/chunk-6KFKO6ZX.js +2 -0
  10. package/dist/chunk-6VK2XALI.js +2 -0
  11. package/dist/chunk-AYDF3IFZ.js +2 -0
  12. package/dist/chunk-CTTTLCGL.js +31 -0
  13. package/dist/chunk-ECRS6N33.js +4 -0
  14. package/dist/chunk-FDJMH4CB.js +2 -0
  15. package/dist/chunk-FTF6AMF6.js +2 -0
  16. package/dist/chunk-GWVSCZUS.js +2 -0
  17. package/dist/chunk-LEXMMIQI.js +15 -0
  18. package/dist/chunk-LM26HOJ6.js +31 -0
  19. package/dist/chunk-MQ5SU26J.js +2 -0
  20. package/dist/chunk-N35BC62H.js +2 -0
  21. package/dist/chunk-P6IJ3VBD.js +3 -0
  22. package/dist/chunk-TKLRW52V.js +2 -0
  23. package/dist/chunk-V35CXJQN.js +2 -0
  24. package/dist/chunk-WP5ER7RH.js +3 -0
  25. package/dist/chunk-XLVEDKM6.js +2 -0
  26. package/dist/chunk-Y675R34Z.js +2 -0
  27. package/dist/chunk-YD2AF2M6.js +46 -0
  28. package/dist/chunk-YLCNV764.js +3 -0
  29. package/dist/chunk-ZZMSFCJP.js +3 -0
  30. package/dist/client.d.ts +6 -4
  31. package/dist/client.js +1 -9
  32. package/dist/gateway.d.ts +6 -5
  33. package/dist/gateway.js +1 -10
  34. package/dist/{hybrid-CF__0YnC.d.ts → hybrid-BZpCiUaV.d.ts} +6 -5
  35. package/dist/{index-cMV0_yD9.d.ts → index-BYDtRGue.d.ts} +45 -36
  36. package/dist/{index-BW95kAL4.d.ts → index-ByzjpRCk.d.ts} +37 -72
  37. package/dist/index.d.ts +221 -50
  38. package/dist/index.js +4 -312
  39. package/dist/kyber-PULV7PQX.js +2 -0
  40. package/dist/mesh.d.ts +27 -143
  41. package/dist/mesh.js +1 -4
  42. package/dist/node-Djzm6UYd.d.ts +172 -0
  43. package/dist/protocol/liop_core.proto +25 -6
  44. package/dist/server.d.ts +4 -3
  45. package/dist/server.js +1 -7
  46. package/dist/types-29zv9X1V.d.ts +455 -0
  47. package/dist/types.d.ts +2 -1
  48. package/dist/types.js +1 -2
  49. package/dist/verifier-DqZ9MQ9l.d.ts +82 -0
  50. package/dist/verifier-J4NQYZX5.js +2 -0
  51. package/dist/workers/logic-execution.d.ts +7 -0
  52. package/dist/workers/logic-execution.js +1 -271
  53. package/dist/workers/zk-verifier.d.ts +9 -0
  54. package/dist/workers/zk-verifier.js +1 -173
  55. package/dist/zk-DzYNWBgo.d.ts +104 -0
  56. package/package.json +56 -45
  57. package/dist/bin/agent.js.map +0 -1
  58. package/dist/bridge.js.map +0 -1
  59. package/dist/chunk-32ADSAJS.js +0 -104
  60. package/dist/chunk-32ADSAJS.js.map +0 -1
  61. package/dist/chunk-547TYL27.js +0 -208109
  62. package/dist/chunk-547TYL27.js.map +0 -1
  63. package/dist/chunk-72MNYFR6.js +0 -64
  64. package/dist/chunk-72MNYFR6.js.map +0 -1
  65. package/dist/chunk-74CISO2I.js +0 -853
  66. package/dist/chunk-74CISO2I.js.map +0 -1
  67. package/dist/chunk-CRZBVFDV.js +0 -616
  68. package/dist/chunk-CRZBVFDV.js.map +0 -1
  69. package/dist/chunk-GA3Q2S7O.js +0 -558
  70. package/dist/chunk-GA3Q2S7O.js.map +0 -1
  71. package/dist/chunk-JIJPZFR2.js +0 -51
  72. package/dist/chunk-JIJPZFR2.js.map +0 -1
  73. package/dist/chunk-OUUTDSOW.js +0 -24
  74. package/dist/chunk-OUUTDSOW.js.map +0 -1
  75. package/dist/chunk-PYKRQAER.js +0 -77
  76. package/dist/chunk-PYKRQAER.js.map +0 -1
  77. package/dist/chunk-QLCOEP5J.js +0 -68
  78. package/dist/chunk-QLCOEP5J.js.map +0 -1
  79. package/dist/chunk-RWRRBYG4.js +0 -3
  80. package/dist/chunk-RWRRBYG4.js.map +0 -1
  81. package/dist/chunk-SONUORBT.js +0 -421
  82. package/dist/chunk-SONUORBT.js.map +0 -1
  83. package/dist/chunk-T5IUZF47.js +0 -716
  84. package/dist/chunk-T5IUZF47.js.map +0 -1
  85. package/dist/chunk-U5BZ66VX.js +0 -447
  86. package/dist/chunk-U5BZ66VX.js.map +0 -1
  87. package/dist/chunk-WCCGE4QR.js +0 -3520
  88. package/dist/chunk-WCCGE4QR.js.map +0 -1
  89. package/dist/chunk-WSW6YJNY.js +0 -168
  90. package/dist/chunk-WSW6YJNY.js.map +0 -1
  91. package/dist/client.js.map +0 -1
  92. package/dist/gateway.js.map +0 -1
  93. package/dist/index.js.map +0 -1
  94. package/dist/kyber-3ULIJSE3.js +0 -3
  95. package/dist/kyber-3ULIJSE3.js.map +0 -1
  96. package/dist/mesh.js.map +0 -1
  97. package/dist/server.js.map +0 -1
  98. package/dist/types-lJIxBlWF.d.ts +0 -256
  99. package/dist/types.js.map +0 -1
  100. package/dist/verifier-3FAKCFNN.js +0 -5
  101. package/dist/verifier-3FAKCFNN.js.map +0 -1
  102. package/dist/verifier-COnid_dg.d.ts +0 -31
  103. package/dist/workers/logic-execution.js.map +0 -1
  104. package/dist/workers/zk-verifier.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,140 +1,4 @@
1
- export { WasiSandbox, calculateAstInstructionFuel, getDefaultEnvironment } from './chunk-SONUORBT.js';
2
- export { LiopClient, LiopRpcClient } from './chunk-CRZBVFDV.js';
3
- export { LiopMcpBridge, LiopStreamBridge } from './chunk-GA3Q2S7O.js';
4
- export { GRPC_WEB_CONSTANTS, InMemoryRateLimiter, LiopHybridGateway, buildProtectedResourceMetadata, decodeFrames, dispatchGrpcWebRequest, encodeDataFrame, encodeTrailerFrame, isGrpcWebRequest } from './chunk-T5IUZF47.js';
5
- export { AUTH_DEFAULTS, AuditLogger, GENESIS_HASH, JwtValidator, LiopRpcServer, LiopServer, NerScanner, PII_PATTERNS, PII_PRESETS, PiiScanner, computeEntryHash, createOAuthServer, globalAuditLogger } from './chunk-WCCGE4QR.js';
6
- export { sanitizeOutput } from './chunk-JIJPZFR2.js';
7
- export { HeuristicTokenEstimator, LiopMcpRouter, LiopOTelBridge, RealTokenEstimator, TokenTelemetryEngine, createSyncTokenEstimator, createTokenEstimator } from './chunk-547TYL27.js';
8
- import './chunk-32ADSAJS.js';
9
- import './chunk-OUUTDSOW.js';
10
- export { Kyber768Wrapper } from './chunk-QLCOEP5J.js';
11
- export { Counter, DILITHIUM65_CONSTANTS, Dilithium65Wrapper, Gauge, Histogram, LIOP_SCOPES, MetricsRegistry, authorizeRequest, egressBlocksTotal, fuelConsumed, manifestCacheSize, meshPeersConnected, protocolMetrics, toolCallsTotal, zkVerificationDurationMs } from './chunk-U5BZ66VX.js';
12
- export { GRPC_CHANNEL_OPTIONS } from './chunk-WSW6YJNY.js';
13
- export { MCP_LEGACY_SUPPORT_ENABLED, MCP_PROTOCOL_VERSION, MCP_PROTOCOL_VERSION_LEGACY, PromptSchema, ResourceSchema, ToolSchema } from './chunk-PYKRQAER.js';
14
- export { MeshNode } from './chunk-74CISO2I.js';
15
- import { log } from './chunk-72MNYFR6.js';
16
- import * as crypto from 'crypto';
17
- import { EventEmitter } from 'events';
18
- import * as fs from 'fs';
19
-
20
- // src/errors.ts
21
- var ErrorCode = /* @__PURE__ */ ((ErrorCode2) => {
22
- ErrorCode2["CapabilityViolation"] = "CapabilityViolation";
23
- ErrorCode2["SandboxEscape"] = "SandboxEscape";
24
- ErrorCode2["PiiLeak"] = "PiiLeak";
25
- ErrorCode2["InvalidIntent"] = "InvalidIntent";
26
- ErrorCode2["Throttled"] = "Throttled";
27
- ErrorCode2["ZkVerificationFailed"] = "ZkVerificationFailed";
28
- ErrorCode2["MeshUnavailable"] = "MeshUnavailable";
29
- ErrorCode2["ConnectionFailed"] = "ConnectionFailed";
30
- return ErrorCode2;
31
- })(ErrorCode || {});
32
- var LiopError = class extends Error {
33
- code;
34
- constructor(code, message) {
35
- super(message);
36
- this.name = "LiopError";
37
- this.code = code;
38
- }
39
- };
40
- var TRACEPARENT_REGEX = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;
41
- var LiopTracer = class _LiopTracer {
42
- static generateTraceId() {
43
- let id;
44
- do {
45
- id = crypto.randomBytes(16).toString("hex");
46
- } while (id === "0".repeat(32));
47
- return id;
48
- }
49
- static generateSpanId() {
50
- let id;
51
- do {
52
- id = crypto.randomBytes(8).toString("hex");
53
- } while (id === "0".repeat(16));
54
- return id;
55
- }
56
- static formatTraceparent(traceId, spanId, sampled = true) {
57
- const flags = sampled ? "01" : "00";
58
- return `00-${traceId}-${spanId}-${flags}`;
59
- }
60
- static parseTraceparent(header) {
61
- if (!header || typeof header !== "string") {
62
- return null;
63
- }
64
- const trimmed = header.trim();
65
- const match = TRACEPARENT_REGEX.exec(trimmed);
66
- if (!match) {
67
- return null;
68
- }
69
- const [, version, traceId, spanId, flags] = match;
70
- if (version === "00") {
71
- if (traceId === "0".repeat(32) || spanId === "0".repeat(16)) {
72
- return null;
73
- }
74
- }
75
- const sampled = (Number.parseInt(flags, 16) & 1) === 1;
76
- return {
77
- traceId,
78
- spanId,
79
- sampled
80
- };
81
- }
82
- static injectTraceparent(carrier, context) {
83
- carrier.traceparent = _LiopTracer.formatTraceparent(
84
- context.traceId,
85
- context.spanId,
86
- context.sampled
87
- );
88
- }
89
- static extractTraceparent(carrier) {
90
- const val = carrier.traceparent || carrier.Traceparent;
91
- if (Array.isArray(val)) {
92
- return _LiopTracer.parseTraceparent(val[0]);
93
- }
94
- return _LiopTracer.parseTraceparent(val);
95
- }
96
- startSpan(name, parent, attributes = {}) {
97
- const traceId = parent?.traceId || _LiopTracer.generateTraceId();
98
- const spanId = _LiopTracer.generateSpanId();
99
- const sampled = parent ? parent.sampled : true;
100
- const context = {
101
- traceId,
102
- spanId,
103
- sampled
104
- };
105
- const span = {
106
- name,
107
- context,
108
- startTime: Date.now(),
109
- attributes: { ...attributes },
110
- status: "OK",
111
- setAttribute(key, value) {
112
- this.attributes[key] = value;
113
- return this;
114
- },
115
- recordException(err) {
116
- this.status = "ERROR";
117
- this.error = typeof err === "string" ? err : err.message;
118
- return this;
119
- },
120
- end() {
121
- this.endTime = Date.now();
122
- }
123
- };
124
- return span;
125
- }
126
- };
127
- var defaultTracer = new LiopTracer();
128
-
129
- // src/prompts/adapters.ts
130
- var PROVIDER_CONFIGS = {
131
- claude: { xmlStandard: true, jsonSchemaPreferred: false },
132
- openai: { xmlStandard: false, jsonSchemaPreferred: true },
133
- gemini: { xmlStandard: false, jsonSchemaPreferred: true }
134
- };
135
- function generateSystemInstructions(provider) {
136
- const config = PROVIDER_CONFIGS[provider];
137
- let instructions = `[LIOP-PROTO-V1: LOGIC-ON-ORIGIN SPECIFICATION]
1
+ export{d as WasiSandbox,c as calculateAstInstructionFuel,b as getDefaultEnvironment}from'./chunk-CTTTLCGL.js';export{a as VERIFICATION_LATENCY_BUDGET_MS,f as deserializeGrothProof,d as deserializeVKey,e as serializeGrothProof,c as serializeVKey,b as verifyGroth16Proof}from'./chunk-FDJMH4CB.js';export{b as AesGcmWrapper,c as LiopClient,a as LiopRpcClient}from'./chunk-WP5ER7RH.js';export{b as LiopMcpBridge,a as LiopStreamBridge}from'./chunk-P6IJ3VBD.js';export{a as GRPC_WEB_CONSTANTS,i as InMemoryRateLimiter,j as LiopHybridGateway,g as buildProtectedResourceMetadata,e as decodeFrames,f as dispatchGrpcWebRequest,c as encodeDataFrame,d as encodeTrailerFrame,h as executeGatewayInterceptor,b as isGrpcWebRequest}from'./chunk-LEXMMIQI.js';export{a as RoutingTable,b as probeTopology}from'./chunk-2XHSALII.js';export{a as TokenManager}from'./chunk-N35BC62H.js';export{f as AUTH_DEFAULTS,d as AuditLogger,b as GENESIS_HASH,g as JwtValidator,a as LiopRpcServer,m as LiopServer,i as NerScanner,j as PII_PATTERNS,k as PII_PRESETS,l as PiiScanner,c as computeEntryHash,h as createOAuthServer,e as globalAuditLogger}from'./chunk-YD2AF2M6.js';export{a as sanitizeOutput}from'./chunk-MQ5SU26J.js';export{a as LiopMcpRouter}from'./chunk-LM26HOJ6.js';export{a as LiopVerifier}from'./chunk-6KFKO6ZX.js';import'./chunk-TKLRW52V.js';export{a as Kyber768Wrapper}from'./chunk-Y675R34Z.js';export{b as LIOP_SCOPES,a as authorizeRequest}from'./chunk-XLVEDKM6.js';export{a as DILITHIUM65_CONSTANTS,b as Dilithium65Wrapper}from'./chunk-2ZYX736J.js';export{j as GRPC_CHANNEL_OPTIONS,b as HeuristicTokenEstimator,e as LiopOTelBridge,a as RealTokenEstimator,f as TokenTelemetryEngine,i as createChannelCredentials,h as createServerCredentials,d as createSyncTokenEstimator,c as createTokenEstimator}from'./chunk-ECRS6N33.js';export{a as Counter,b as Gauge,c as Histogram,d as MetricsRegistry,k as egressBlocksTotal,h as fuelConsumed,j as manifestCacheSize,i as meshPeersConnected,t as operationDurationMs,u as pqcHandshakeDurationMs,v as pqcHandshakesTotal,e as protocolMetrics,q as tokensInputTotal,r as tokensOutputTotal,s as tokensSavedTotal,g as toolCallErrorsTotal,f as toolCallsTotal,w as wireEgressBytesTotal,x as wireSavedBytesTotal,n as zkProofsByTypeTotal,o as zkProvingDurationMs,l as zkVerificationDurationMs,m as zkVerificationsTotal,p as zkVkeyCacheSize}from'./chunk-ZZMSFCJP.js';export{a as MCP_LEGACY_SUPPORT_ENABLED,h as MCP_PROTOCOL_VERSION,b as MCP_PROTOCOL_VERSION_LEGACY,k as PromptSchema,j as ResourceSchema,i as ToolSchema}from'./chunk-GWVSCZUS.js';export{a as ProofType,b as RECEIPT_VERSION_V1,c as RECEIPT_VERSION_V2,d as ZK_JOURNAL_V2_SIZE,e as ZkVerificationError,i as ZkVerifier,g as decodeJournalV2,f as encodeJournalV2,h as receiptCodec}from'./chunk-6VK2XALI.js';export{a as SWARM_KEY_BYTE_LENGTH,b as createSwarmKey,d as deserializeSwarmKey,g as loadSwarmKey,e as parseSwarmKey,f as saveSwarmKey,c as serializeSwarmKey}from'./chunk-YLCNV764.js';export{a as MeshNode}from'./chunk-V35CXJQN.js';import {b}from'./chunk-3WRKTVOF.js';export{a as LiopLogger,b as log}from'./chunk-3WRKTVOF.js';import {a}from'./chunk-AYDF3IFZ.js';import*as h from'crypto';import {EventEmitter}from'events';import*as i from'fs';var A=(o=>(o.CapabilityViolation="CapabilityViolation",o.SandboxEscape="SandboxEscape",o.PiiLeak="PiiLeak",o.InvalidIntent="InvalidIntent",o.Throttled="Throttled",o.ZkVerificationFailed="ZkVerificationFailed",o.MeshUnavailable="MeshUnavailable",o.ConnectionFailed="ConnectionFailed",o))(A||{}),y=class extends Error{static{a(this,"LiopError");}code;constructor(t,e){super(e),this.name="LiopError",this.code=t;}};var D=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/,g=class n{static{a(this,"LiopTracer");}static generateTraceId(){let t;do t=h.randomBytes(16).toString("hex");while(t==="0".repeat(32));return t}static generateSpanId(){let t;do t=h.randomBytes(8).toString("hex");while(t==="0".repeat(16));return t}static formatTraceparent(t,e,r=true){return `00-${t}-${e}-${r?"01":"00"}`}static parseTraceparent(t){if(!t||typeof t!="string")return null;let e=t.trim(),r=D.exec(e);if(!r)return null;let[,a,c,l,m]=r;if(a==="00"&&(c==="0".repeat(32)||l==="0".repeat(16)))return null;let o=(Number.parseInt(m,16)&1)===1;return {traceId:c,spanId:l,sampled:o}}static injectTraceparent(t,e){t.traceparent=n.formatTraceparent(e.traceId,e.spanId,e.sampled);}static extractTraceparent(t){let e=t.traceparent||t.Traceparent;return Array.isArray(e)?n.parseTraceparent(e[0]):n.parseTraceparent(e)}startSpan(t,e,r={}){let a=e?.traceId||n.generateTraceId(),c=n.generateSpanId(),l=e?e.sampled:true;return {name:t,context:{traceId:a,spanId:c,sampled:l},startTime:Date.now(),attributes:{...r},status:"OK",setAttribute(d,T){return this.attributes[d]=T,this},recordException(d){return this.status="ERROR",this.error=typeof d=="string"?d:d.message,this},end(){this.endTime=Date.now();}}}},Mt=new g;var k={claude:{xmlStandard:true,jsonSchemaPreferred:false},openai:{xmlStandard:false,jsonSchemaPreferred:true},gemini:{xmlStandard:false,jsonSchemaPreferred:true}};function Bt(n){let t=k[n],e=`[LIOP-PROTO-V1: LOGIC-ON-ORIGIN SPECIFICATION]
138
2
  You are interacting with a Logic-Injection-on-Origin Protocol (LIOP) Mesh Network.
139
3
  Unlike standard MCP where you pull context to evaluate it remotely, in LIOP you WRITE code that executes on the data's origin.
140
4
 
@@ -159,9 +23,7 @@ To prevent database reconstruction and inference attacks, numeric query outputs
159
23
  - Poisoned globals: eval, Function, setTimeout, setInterval, Buffer, ArrayBuffer, and TypedArrays are undefined.
160
24
  - Frozen prototypes: Modifications to Object.prototype, Array.prototype, etc., are blocked.
161
25
  - K-Anonymity constraints: Small datasets (< 10 records) limit outputs to max 3 scalar keys with NO nesting. Datasets with >= 10 records limit outputs to max 10 fields.
162
- `;
163
- if (config.xmlStandard) {
164
- instructions += `
26
+ `;return t.xmlStandard?e+=`
165
27
  ### PAYLOAD FORMATTING (CLAUDE-XML PREFERRED)
166
28
  You must wrap your logic precisely within <liop_logic> tags.
167
29
  Example:
@@ -170,9 +32,7 @@ const records = await liop.readResource("liop://vault/patients");
170
32
  const filtered = records.filter(r => r.disease === "Hypertension");
171
33
  return { alert: "High risk demographic", targetCount: filtered.length };
172
34
  </liop_logic>
173
- `;
174
- } else if (config.jsonSchemaPreferred) {
175
- instructions += `
35
+ `:t.jsonSchemaPreferred&&(e+=`
176
36
  ### PAYLOAD FORMATTING (JSON PARSING PREFERRED)
177
37
  You must provide your logic strictly within a JSON string key called \`"logic_blob"\` inside your tool call parameters.
178
38
  Example:
@@ -180,173 +40,5 @@ Example:
180
40
  "target": "liop://vault/patients",
181
41
  "logic_blob": "const records = await liop.readResource(args.target); return { targetCount: records.filter(r => r.disease === 'Hypertension').length };"
182
42
  }
183
- `;
184
- }
185
- return instructions;
186
- }
187
- var CertManager = class extends EventEmitter {
188
- constructor(options) {
189
- super();
190
- this.options = options;
191
- this.warningDays = options.warningDays ?? 30;
192
- this.debounceMs = options.debounceMs ?? 150;
193
- this.loadCertificates();
194
- if (options.watchFiles !== false) {
195
- this.setupWatchers();
196
- }
197
- }
198
- options;
199
- rootCertBuffer = null;
200
- certChainBuffer = null;
201
- privateKeyBuffer = null;
202
- watchers = [];
203
- reloadDebounceTimer = null;
204
- warningDays;
205
- debounceMs;
206
- /**
207
- * Synchronously loads or reloads certificates from filesystem into memory.
208
- */
209
- loadCertificates() {
210
- try {
211
- if (this.options.rootCertPath && fs.existsSync(this.options.rootCertPath)) {
212
- this.rootCertBuffer = fs.readFileSync(this.options.rootCertPath);
213
- }
214
- if (!fs.existsSync(this.options.certChainPath)) {
215
- throw new Error(
216
- `Certificate chain file not found: ${this.options.certChainPath}`
217
- );
218
- }
219
- if (!fs.existsSync(this.options.privateKeyPath)) {
220
- throw new Error(
221
- `Private key file not found: ${this.options.privateKeyPath}`
222
- );
223
- }
224
- this.certChainBuffer = fs.readFileSync(this.options.certChainPath);
225
- this.privateKeyBuffer = fs.readFileSync(this.options.privateKeyPath);
226
- log.info("[CertManager] Certificates loaded successfully.");
227
- } catch (error) {
228
- log.error(`[CertManager] Failed to load certificates: ${error}`);
229
- throw error;
230
- }
231
- }
232
- /**
233
- * Inspects the loaded server/client certificate chain using Node.js native X509Certificate.
234
- */
235
- inspectCertificate() {
236
- if (!this.certChainBuffer) {
237
- throw new Error("[CertManager] No certificate loaded to inspect.");
238
- }
239
- const x509 = new crypto.X509Certificate(this.certChainBuffer);
240
- const validToDate = new Date(x509.validTo);
241
- const now = /* @__PURE__ */ new Date();
242
- const msRemaining = validToDate.getTime() - now.getTime();
243
- const daysRemaining = Math.max(
244
- 0,
245
- Math.floor(msRemaining / (1e3 * 60 * 60 * 24))
246
- );
247
- const isExpired = msRemaining <= 0;
248
- const isExpiringSoon = daysRemaining <= this.warningDays;
249
- return {
250
- subject: x509.subject,
251
- issuer: x509.issuer,
252
- validFrom: x509.validFrom,
253
- validTo: x509.validTo,
254
- fingerprint256: x509.fingerprint256,
255
- daysRemaining,
256
- isExpired,
257
- isExpiringSoon
258
- };
259
- }
260
- /**
261
- * Sets up non-blocking filesystem watchers to detect certificate renewals
262
- * and trigger hot-reloading without process restarts.
263
- */
264
- setupWatchers() {
265
- const filesToWatch = [
266
- this.options.certChainPath,
267
- this.options.privateKeyPath,
268
- this.options.rootCertPath
269
- ].filter((p) => Boolean(p && fs.existsSync(p)));
270
- for (const filePath of filesToWatch) {
271
- try {
272
- const watcher = fs.watch(filePath, () => {
273
- this.scheduleReload();
274
- });
275
- this.watchers.push(watcher);
276
- } catch (err) {
277
- log.warn(
278
- `[CertManager] Could not watch ${filePath} for hot reloading: ${err}`
279
- );
280
- }
281
- }
282
- }
283
- /**
284
- * Debounces reload events to ensure files have finished writing.
285
- */
286
- scheduleReload() {
287
- if (this.reloadDebounceTimer) {
288
- clearTimeout(this.reloadDebounceTimer);
289
- }
290
- this.reloadDebounceTimer = setTimeout(() => {
291
- try {
292
- this.loadCertificates();
293
- const certInfo = this.inspectCertificate();
294
- log.info(
295
- `[CertManager] Hot reload complete. Certificate expires in ${certInfo.daysRemaining} days.`
296
- );
297
- this.emit("reload", certInfo);
298
- } catch (error) {
299
- log.error(`[CertManager] Hot reload failed: ${error}`);
300
- this.emit("error", error);
301
- }
302
- }, this.debounceMs);
303
- }
304
- /**
305
- * Manually triggers a reload of certificates and emits the 'reload' event.
306
- */
307
- reload() {
308
- this.loadCertificates();
309
- const certInfo = this.inspectCertificate();
310
- log.info(
311
- `[CertManager] Hot reload complete. Certificate expires in ${certInfo.daysRemaining} days.`
312
- );
313
- this.emit("reload", certInfo);
314
- return certInfo;
315
- }
316
- getRootCert() {
317
- return this.rootCertBuffer;
318
- }
319
- getCertChain() {
320
- if (!this.certChainBuffer) {
321
- throw new Error("[CertManager] Certificate chain not loaded.");
322
- }
323
- return this.certChainBuffer;
324
- }
325
- getPrivateKey() {
326
- if (!this.privateKeyBuffer) {
327
- throw new Error("[CertManager] Private key not loaded.");
328
- }
329
- return this.privateKeyBuffer;
330
- }
331
- /**
332
- * Stops all active file watchers and releases resources.
333
- */
334
- dispose() {
335
- if (this.reloadDebounceTimer) {
336
- clearTimeout(this.reloadDebounceTimer);
337
- this.reloadDebounceTimer = null;
338
- }
339
- for (const watcher of this.watchers) {
340
- try {
341
- watcher.close();
342
- } catch {
343
- }
344
- }
345
- this.watchers = [];
346
- this.removeAllListeners();
347
- }
348
- };
349
-
350
- export { CertManager, ErrorCode, LiopError, LiopTracer, defaultTracer, generateSystemInstructions };
351
- //# sourceMappingURL=index.js.map
43
+ `),e}a(Bt,"generateSystemInstructions");var x=class extends EventEmitter{constructor(e){super();this.options=e;this.warningDays=e.warningDays??30,this.debounceMs=e.debounceMs??150,this.loadCertificates(),e.watchFiles!==false&&this.setupWatchers();}options;static{a(this,"CertManager");}rootCertBuffer=null;certChainBuffer=null;privateKeyBuffer=null;watchers=[];reloadDebounceTimer=null;warningDays;debounceMs;loadCertificates(){try{if(this.options.rootCertPath&&i.existsSync(this.options.rootCertPath)&&(this.rootCertBuffer=i.readFileSync(this.options.rootCertPath)),!i.existsSync(this.options.certChainPath))throw new Error(`Certificate chain file not found: ${this.options.certChainPath}`);if(!i.existsSync(this.options.privateKeyPath))throw new Error(`Private key file not found: ${this.options.privateKeyPath}`);this.certChainBuffer=i.readFileSync(this.options.certChainPath),this.privateKeyBuffer=i.readFileSync(this.options.privateKeyPath),b.info("[CertManager] Certificates loaded successfully.");}catch(e){throw b.error(`[CertManager] Failed to load certificates: ${e}`),e}}inspectCertificate(){if(!this.certChainBuffer)throw new Error("[CertManager] No certificate loaded to inspect.");let e=new h.X509Certificate(this.certChainBuffer),r=new Date(e.validTo),a=new Date,c=r.getTime()-a.getTime(),l=Math.max(0,Math.floor(c/(1e3*60*60*24))),m=c<=0,o=l<=this.warningDays;return {subject:e.subject,issuer:e.issuer,validFrom:e.validFrom,validTo:e.validTo,fingerprint256:e.fingerprint256,daysRemaining:l,isExpired:m,isExpiringSoon:o}}setupWatchers(){let e=[this.options.certChainPath,this.options.privateKeyPath,this.options.rootCertPath].filter(r=>!!(r&&i.existsSync(r)));for(let r of e)try{let a=i.watch(r,()=>{this.scheduleReload();});this.watchers.push(a);}catch(a){b.warn(`[CertManager] Could not watch ${r} for hot reloading: ${a}`);}}scheduleReload(){this.reloadDebounceTimer&&clearTimeout(this.reloadDebounceTimer),this.reloadDebounceTimer=setTimeout(()=>{try{this.loadCertificates();let e=this.inspectCertificate();b.info(`[CertManager] Hot reload complete. Certificate expires in ${e.daysRemaining} days.`),this.emit("reload",e);}catch(e){b.error(`[CertManager] Hot reload failed: ${e}`),this.emit("error",e);}},this.debounceMs);}reload(){this.loadCertificates();let e=this.inspectCertificate();return b.info(`[CertManager] Hot reload complete. Certificate expires in ${e.daysRemaining} days.`),this.emit("reload",e),e}getRootCert(){return this.rootCertBuffer}getCertChain(){if(!this.certChainBuffer)throw new Error("[CertManager] Certificate chain not loaded.");return this.certChainBuffer}getPrivateKey(){if(!this.privateKeyBuffer)throw new Error("[CertManager] Private key not loaded.");return this.privateKeyBuffer}dispose(){this.reloadDebounceTimer&&(clearTimeout(this.reloadDebounceTimer),this.reloadDebounceTimer=null);for(let e of this.watchers)try{e.close();}catch{}this.watchers=[],this.removeAllListeners();}};export{x as CertManager,A as ErrorCode,y as LiopError,g as LiopTracer,Mt as defaultTracer,Bt as generateSystemInstructions};//# sourceMappingURL=index.js.map
352
44
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,2 @@
1
+ export{a as Kyber768Wrapper}from'./chunk-Y675R34Z.js';import'./chunk-AYDF3IFZ.js';//# sourceMappingURL=kyber-PULV7PQX.js.map
2
+ //# sourceMappingURL=kyber-PULV7PQX.js.map
package/dist/mesh.d.ts CHANGED
@@ -1,148 +1,32 @@
1
+ export { L as LiopManifest, a as MeshNode, M as MeshNodeConfig } from './node-Djzm6UYd.js';
2
+
3
+ declare const SWARM_KEY_BYTE_LENGTH = 95;
4
+ /**
5
+ * Creates a freshly generated 95-byte Pre-Shared Key (PSK) for libp2p Private Networks (pnet).
6
+ * Follows the canonical format `/key/swarm/psk/1.0.0/\n/base16/\n<hex>\n`.
7
+ */
8
+ declare function createSwarmKey(): Uint8Array;
9
+ /**
10
+ * Serializes a 95-byte PSK into a Base64 string for safe environment variable passing or JSON config.
11
+ */
12
+ declare function serializeSwarmKey(psk: Uint8Array): string;
13
+ /**
14
+ * Deserializes a Base64-encoded string into a 95-byte PSK Uint8Array.
15
+ */
16
+ declare function deserializeSwarmKey(base64Str: string): Uint8Array;
17
+ /**
18
+ * Parses raw text format PSK or Base64 string into a 95-byte PSK Uint8Array.
19
+ * Allows loading either the canonical multiline text (`/key/swarm/psk/1.0.0/...`) or Base64.
20
+ */
21
+ declare function parseSwarmKey(rawText: string): Uint8Array;
1
22
  /**
2
- * Manifest describing a node's capabilities in the LIOP Mesh.
3
- * Exchanged via the /liop/manifest/1.0.0 protocol stream.
23
+ * Saves a 95-byte Swarm Key to a file on disk (written as canonical text).
4
24
  */
5
- interface LiopManifest {
6
- peerId: string;
7
- grpcPort: number;
8
- tools: Array<{
9
- name: string;
10
- description?: string;
11
- inputSchema?: Record<string, unknown>;
12
- }>;
13
- resources: Array<{
14
- name: string;
15
- uri: string;
16
- description?: string;
17
- mimeType?: string;
18
- text?: string;
19
- }>;
20
- serverInfo: {
21
- name: string;
22
- version: string;
23
- };
24
- taxonomy?: {
25
- domain: string;
26
- clearanceTier: number;
27
- executionTypes: string[];
28
- };
29
- authRequired?: boolean;
30
- /** Canonical slug for deterministic token resolution. Agents resolve LIOP_TOKEN_<tokenSlug>. Must match /^[A-Z][A-Z0-9_]*$/. */
31
- tokenSlug?: string;
32
- /** ML-DSA-65 (FIPS 204) Post-Quantum Digital Signature for Manifest Attestation (Base64) */
33
- pqcSignature?: string;
34
- /** ML-DSA-65 (FIPS 204) Post-Quantum Public Key (Base64) */
35
- pqcPublicKey?: string;
36
- }
37
- interface MeshNodeConfig {
38
- listenAddresses?: string[];
39
- bootstrapNodes?: string[];
40
- identityPath?: string;
41
- enableWAN?: boolean;
42
- dhtStoragePath?: string;
43
- /** Optional function to translate multiaddrs (e.g. for Docker NAT traversal). Return null to drop an address. */
44
- addressMapper?: (addr: string) => string | null;
45
- /** Enable AutoNAT reachability detection (default: true) */
46
- enableAutoNAT?: boolean;
47
- /** Enable Circuit Relay v2 transport & server for NAT traversal (default: true) */
48
- enableRelay?: boolean;
49
- /** Enable DCUtR decentralized hole punching (default: true) */
50
- enableDcutr?: boolean;
51
- /** Enable mDNS peer discovery for local networks (default: false in WAN, true in LAN) */
52
- enableMdns?: boolean;
53
- }
25
+ declare function saveSwarmKey(psk: Uint8Array, filePath: string): Promise<void>;
54
26
  /**
55
- * P2P Mesh Node backed by libp2p + Kademlia DHT.
56
- *
57
- * Provides capability advertisement via CID-based content routing
58
- * and decentralized peer discovery.
27
+ * Loads a 95-byte Swarm Key from a file on disk.
28
+ * Supports both raw binary/canonical format and Base64-encoded text.
59
29
  */
60
- declare class MeshNode {
61
- private node;
62
- private config;
63
- private manifestDialFailureState;
64
- private static readonly MANIFEST_DIAL_BASE_COOLDOWN_MS;
65
- private static readonly MANIFEST_DIAL_MAX_COOLDOWN_MS;
66
- private static readonly MANIFEST_DIAL_SKIP_LOG_THROTTLE_MS;
67
- /**
68
- * Buffer of capability hashes that have been announced.
69
- * Used to re-announce capabilities when new peers connect
70
- * (critical for small / isolated clusters where the initial
71
- * provide() finds zero peers in the routing table).
72
- */
73
- private announcedCapabilities;
74
- /** Guards against concurrent re-announcement storms. */
75
- private reannouncing;
76
- /** Callback that returns the local node's manifest on request. */
77
- private manifestProvider;
78
- /** Flag to ensure the manifest protocol is only registered once. */
79
- private manifestProtocolRegistered;
80
- /** Local Ed25519 Private Key for protocol signatures */
81
- private localPrivateKey;
82
- constructor(config?: MeshNodeConfig);
83
- private shouldSkipManifestDial;
84
- private recordManifestDialFailure;
85
- private clearManifestDialFailure;
86
- /**
87
- * Loads a persistent identity from disk or generates a new Ed25519 keypair.
88
- * Uses privateKeyToProtobuf/privateKeyFromProtobuf (libp2p v3.x official API).
89
- */
90
- private loadOrCreateIdentity;
91
- /**
92
- * Persists the private key to disk using protobuf serialization (libp2p v3.x).
93
- */
94
- private saveIdentity;
95
- /**
96
- * Creates a CID v1 (raw codec 0x55) from a SHA-256 hash of the capability string.
97
- * Required by @libp2p/kad-dht v16+ for provide/findProviders.
98
- */
99
- private capabilityToCID;
100
- /**
101
- * Re-announces all buffered capabilities after a new peer connects.
102
- * Uses a small delay to allow the DHT protocol handshake to complete.
103
- */
104
- private reannounceAll;
105
- start(): Promise<void>;
106
- stop(): Promise<void>;
107
- private loadRoutingTable;
108
- private saveRoutingTable;
109
- /**
110
- * Internal logic to register protocol handlers against the libp2p node.
111
- * Can be called multiple times; handles idempotent registration.
112
- */
113
- private applyHandlers;
114
- /**
115
- * Registers a callback as the manifest provider.
116
- * Will be applied immediately if the node is already initialized.
117
- */
118
- registerManifestHandler(provider: () => LiopManifest): void;
119
- /**
120
- * Queries a remote peer's manifest by opening a /liop/manifest/1.0.0 stream.
121
- * Returns null if the peer doesn't support the protocol or is unreachable.
122
- */
123
- queryManifest(peerIdStr: string): Promise<LiopManifest | null>;
124
- /**
125
- * Discovers all peers in the DHT that have announced "liop:manifest".
126
- * Returns their PeerIDs for subsequent manifest queries.
127
- */
128
- discoverManifestProviders(): Promise<string[]>;
129
- /**
130
- * Announces this node as a manifest provider in the DHT.
131
- * Should be called after tools/resources have been registered.
132
- */
133
- announceManifest(): Promise<void>;
134
- /**
135
- * Returns the current size of the routing table for diagnostic purposes.
136
- */
137
- getRoutingTableSize(): number;
138
- getPeerId(): string;
139
- sign(data: Uint8Array): Promise<Uint8Array>;
140
- getMultiaddrs(): string[];
141
- announceCapability(hash: string): Promise<void>;
142
- findProviders(hash: string): Promise<string[]>;
143
- resolvePeer(peerIdStr: string): Promise<string[]>;
144
- isStarted(): boolean;
145
- getPeers(): string[];
146
- }
30
+ declare function loadSwarmKey(filePath: string): Promise<Uint8Array>;
147
31
 
148
- export { type LiopManifest, MeshNode, type MeshNodeConfig };
32
+ export { SWARM_KEY_BYTE_LENGTH, createSwarmKey, deserializeSwarmKey, loadSwarmKey, parseSwarmKey, saveSwarmKey, serializeSwarmKey };
package/dist/mesh.js CHANGED
@@ -1,5 +1,2 @@
1
- import './chunk-RWRRBYG4.js';
2
- export { MeshNode } from './chunk-74CISO2I.js';
3
- import './chunk-72MNYFR6.js';
4
- //# sourceMappingURL=mesh.js.map
1
+ import'./chunk-FTF6AMF6.js';export{a as SWARM_KEY_BYTE_LENGTH,b as createSwarmKey,d as deserializeSwarmKey,g as loadSwarmKey,e as parseSwarmKey,f as saveSwarmKey,c as serializeSwarmKey}from'./chunk-YLCNV764.js';export{a as MeshNode}from'./chunk-V35CXJQN.js';import'./chunk-3WRKTVOF.js';import'./chunk-AYDF3IFZ.js';//# sourceMappingURL=mesh.js.map
5
2
  //# sourceMappingURL=mesh.js.map