enigma-memory 0.1.17 → 0.1.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +85 -27
- package/apps/cli/bin/enigma-desktop.mjs +140 -0
- package/apps/cli/bin/enigma-terminal.mjs +78 -0
- package/apps/cli/bin/enigma.mjs +4979 -3263
- package/apps/desktop/electron-main.cjs +217 -0
- package/apps/desktop/package.json +12 -0
- package/apps/desktop/src/app.js +264 -7
- package/apps/desktop/src/index.html +3514 -1373
- package/apps/desktop/src/launch-electron.mjs +51 -0
- package/apps/desktop/src/server.mjs +2914 -0
- package/apps/desktop/src/styles.css +2972 -260
- package/apps/desktop/src/zk-browser-prove.mjs +53 -0
- package/apps/desktop/src/zk-state.mjs +1789 -0
- package/apps/gateway/bin/enigma-gateway.mjs +102 -5
- package/apps/gateway/src/server.mjs +271 -8
- package/apps/ios/EnigmaCore/Package.swift +12 -0
- package/apps/ios/EnigmaCore/Sources/EnigmaCore/EnigmaAPIClient.swift +227 -0
- package/apps/ios/EnigmaCore/Sources/EnigmaCore/Models.swift +278 -0
- package/apps/ios/EnigmaCore/Sources/EnigmaCore/PKCE.swift +96 -0
- package/apps/ios/EnigmaCore/Sources/EnigmaCore/PrivacyMinimizer.swift +187 -0
- package/apps/ios/EnigmaCore/Sources/EnigmaCore/ToolModels.swift +129 -0
- package/apps/ios/EnigmaCore/Tests/EnigmaCoreTests/EnigmaCoreTests.swift +42 -0
- package/apps/ios/EnigmaIOS/Enigma/AppModel.swift +346 -0
- package/apps/ios/EnigmaIOS/Enigma/Assets.xcassets/AccentColor.colorset/Contents.json +12 -0
- package/apps/ios/EnigmaIOS/Enigma/Assets.xcassets/AppIcon.appiconset/Contents.json +11 -0
- package/apps/ios/EnigmaIOS/Enigma/Assets.xcassets/AppIcon.appiconset/EnigmaAppIcon.png +0 -0
- package/apps/ios/EnigmaIOS/Enigma/Assets.xcassets/Contents.json +3 -0
- package/apps/ios/EnigmaIOS/Enigma/Assets.xcassets/LaunchBackground.colorset/Contents.json +12 -0
- package/apps/ios/EnigmaIOS/Enigma/ChatView.swift +181 -0
- package/apps/ios/EnigmaIOS/Enigma/CouncilView.swift +78 -0
- package/apps/ios/EnigmaIOS/Enigma/CreateView.swift +152 -0
- package/apps/ios/EnigmaIOS/Enigma/EnigmaApp.swift +52 -0
- package/apps/ios/EnigmaIOS/Enigma/Info.plist +52 -0
- package/apps/ios/EnigmaIOS/Enigma/NaturalLanguagePrivacyTagger.swift +26 -0
- package/apps/ios/EnigmaIOS/Enigma/OAuthClient.swift +321 -0
- package/apps/ios/EnigmaIOS/Enigma/OnboardingView.swift +105 -0
- package/apps/ios/EnigmaIOS/Enigma/PrivateVaultView.swift +275 -0
- package/apps/ios/EnigmaIOS/Enigma/SecureStore.swift +76 -0
- package/apps/ios/EnigmaIOS/Enigma/SettingsView.swift +60 -0
- package/apps/ios/EnigmaIOS/Enigma/Theme.swift +80 -0
- package/apps/ios/EnigmaIOS/EnigmaIOS.xcodeproj/project.pbxproj +211 -0
- package/apps/ios/EnigmaIOS/EnigmaIOS.xcodeproj/xcshareddata/xcschemes/Enigma.xcscheme +23 -0
- package/apps/native-host/README.md +19 -8
- package/apps/native-host/bin/enigma-native-host.mjs +229 -13
- package/apps/relay/bin/enigma-relay.mjs +103 -5
- package/apps/relay/src/federation-runtime.mjs +618 -0
- package/apps/relay/src/server.mjs +310 -9
- package/apps/verifier/bin/enigma-verify.mjs +327 -11
- package/cortex-v3/circuits/build/intent_vk_bytes.json +35 -0
- package/cortex-v3/circuits/build/sale_vk_bytes.json +35 -0
- package/cortex-v3/circuits/build/vk_bytes.json +32 -0
- package/cortex-v3/proving-assets.json +64 -0
- package/cortex-v3/zk/BUILD-CONTRACT.md +87 -0
- package/cortex-v3/zk/action-transition-vk.json +119 -0
- package/cortex-v3/zk/alias-adversarial.test.mjs +220 -0
- package/cortex-v3/zk/groth16-verify-child.mjs +17 -0
- package/cortex-v3/zk/intent-witness.mjs +365 -0
- package/cortex-v3/zk/intent-witness.test.mjs +485 -0
- package/cortex-v3/zk/proving-assets.mjs +203 -0
- package/cortex-v3/zk/sale-witness.mjs +783 -0
- package/cortex-v3/zk/sale-witness.test.mjs +784 -0
- package/cortex-v3/zk/sealed-sale-release-vk.json +119 -0
- package/cortex-v3/zk/settlement-evidence.mjs +722 -0
- package/cortex-v3/zk/setup-intent.mjs +688 -0
- package/cortex-v3/zk/setup-sale.mjs +666 -0
- package/cortex-v3/zk/setup.mjs +594 -0
- package/cortex-v3/zk/witness.mjs +184 -0
- package/cortex-v3/zk/zk-codec.mjs +232 -0
- package/cortex-v3/zk/zk-codec.test.mjs +293 -0
- package/cortex-v3/zk/zk-settle.mjs +370 -0
- package/cortex-v3/zk/zk-tree.mjs +256 -0
- package/cortex-v3/zk/zk-tree.test.mjs +419 -0
- package/deploy/SIMULATION.md +14 -9
- package/deploy/docker-compose.local-production-simulation.yml +54 -12
- package/docs/benchmark-attestation-network.md +487 -487
- package/docs/benchmark-reproducibility.md +289 -289
- package/docs/blockchain-only-mechanisms.md +400 -400
- package/docs/browser-extension-install.md +8 -6
- package/docs/client-connectors.md +16 -12
- package/docs/demo-proof-network.md +275 -275
- package/docs/developer-ecosystem.md +15 -13
- package/docs/developer-proof-quickstart.md +325 -325
- package/docs/enigma-memory-ready-conformance.md +378 -376
- package/docs/install-anywhere.md +64 -30
- package/docs/installers-and-desktop.md +8 -7
- package/docs/memory-benchmarks.md +1 -1
- package/docs/memory-drive-health-model.md +690 -690
- package/docs/novelty-invention-candidates.md +161 -161
- package/docs/proof-network-build-notes.md +240 -240
- package/docs/proof-network-claim-boundaries.md +320 -318
- package/docs/proof-network.md +339 -339
- package/docs/sdk-api.md +324 -324
- package/docs/solana-proof-rail.md +453 -453
- package/examples/01-quickstart-agent/index.mjs +49 -0
- package/examples/01_agent_memory_quickstart.mjs +57 -0
- package/examples/02-multi-agent-swarm/index.mjs +57 -0
- package/examples/02_cross_model_passport.mjs +64 -0
- package/examples/03-langchain-memory/index.mjs +41 -0
- package/examples/03_poseidon_commitment_verification.mjs +71 -0
- package/examples/04-python-trading-agent/trader.py +49 -0
- package/examples/README.md +27 -0
- package/examples/ci/github-actions.yml +7 -2
- package/package.json +410 -278
- package/packages/adapters/PACKAGE_CONTRACT.md +1 -1
- package/packages/connectors/src/index.js +196 -4
- package/packages/connectors/swarm-router.mjs +168 -0
- package/packages/core/src/index.js +249 -2
- package/packages/core/src/version.mjs +7 -0
- package/packages/dev-tools/package.json +19 -0
- package/packages/dev-tools/src/index.js +4 -0
- package/packages/dev-tools/src/memory-benchmark-suite.js +112 -0
- package/packages/dev-tools/src/swarm-simulator.js +101 -0
- package/packages/dev-tools/src/vault-inspector.js +114 -0
- package/packages/dev-tools/src/vector-benchmark.js +100 -0
- package/packages/developer-platform/src/access-credentials.js +341 -0
- package/packages/developer-platform/src/http.js +132 -0
- package/packages/developer-platform/src/index.js +4 -0
- package/packages/developer-platform/src/usage-http.js +60 -0
- package/packages/developer-platform/src/usage.js +295 -0
- package/packages/enclave-runtime/attestation.mjs +159 -0
- package/packages/enclave-runtime/index.mjs +47 -0
- package/packages/enclave-runtime/session-manager.mjs +253 -0
- package/packages/enclave-runtime/zeroization-proof.mjs +227 -0
- package/packages/enigma-reflex/package.json +14 -0
- package/packages/enigma-reflex/src/index.js +204 -0
- package/packages/enigma-reflex/training/generate-dataset.mjs +40 -0
- package/packages/enigma-reflex/training/requirements.txt +8 -0
- package/packages/enigma-reflex/training/train.py +314 -0
- package/packages/enigma-weave/LICENSE +22 -0
- package/packages/enigma-weave/UPSTREAM.json +21 -0
- package/packages/enigma-weave/package.json +14 -0
- package/packages/enigma-weave/src/index.js +286 -0
- package/packages/hosted-cloud/src/index.js +80 -5
- package/packages/importers/src/index.js +432 -0
- package/packages/inference-runtime/src/browser.js +401 -0
- package/packages/inference-runtime/src/chat.js +265 -0
- package/packages/inference-runtime/src/code.js +407 -0
- package/packages/inference-runtime/src/contracts.js +162 -0
- package/packages/inference-runtime/src/http.js +232 -0
- package/packages/inference-runtime/src/image.js +186 -0
- package/packages/inference-runtime/src/index.js +10 -0
- package/packages/inference-runtime/src/model-router.js +320 -0
- package/packages/inference-runtime/src/platform.js +125 -0
- package/packages/inference-runtime/src/privacy.js +400 -0
- package/packages/inference-runtime/src/video.js +253 -0
- package/packages/mcp-server/README.md +22 -6
- package/packages/mcp-server/bin/enigma-mcp.mjs +2 -1
- package/packages/mcp-server/src/index.js +2498 -1185
- package/packages/mcp-server/src/oauth.js +561 -0
- package/packages/mcp-server/src/private-handoff.js +84 -0
- package/packages/mcp-server/src/remote-http.js +273 -0
- package/packages/mcp-server/src/remote-policy.js +72 -0
- package/packages/mcp-server/swarm-bridge.mjs +361 -0
- package/packages/mesh/index.d.ts +283 -0
- package/packages/mesh/package.json +23 -0
- package/packages/mesh/src/crypto.js +189 -0
- package/packages/mesh/src/federation-packets.js +353 -0
- package/packages/mesh/src/gossip.js +311 -0
- package/packages/mesh/src/index.js +6 -0
- package/packages/mesh/src/protocol.js +255 -0
- package/packages/mesh/src/router.js +279 -0
- package/packages/mesh/src/transport.js +306 -0
- package/packages/passport/src/index.js +436 -7
- package/packages/private-economy/src/credits-http.js +100 -0
- package/packages/private-economy/src/credits.js +447 -0
- package/packages/private-economy/src/index.js +5 -0
- package/packages/private-economy/src/payments-http.js +120 -0
- package/packages/private-economy/src/payments.js +509 -0
- package/packages/private-economy/src/x402.js +346 -0
- package/packages/proof-network/PACKAGE_CONTRACT.md +21 -0
- package/packages/rag/index.d.ts +182 -0
- package/packages/rag/models/Xenova/all-MiniLM-L6-v2/THIRD_PARTY_LICENSES.txt +207 -0
- package/packages/rag/models/Xenova/all-MiniLM-L6-v2/config.json +25 -0
- package/packages/rag/models/Xenova/all-MiniLM-L6-v2/onnx/model_quantized.onnx +0 -0
- package/packages/rag/models/Xenova/all-MiniLM-L6-v2/sha256-manifest.json +28 -0
- package/packages/rag/models/Xenova/all-MiniLM-L6-v2/tokenizer.json +30686 -0
- package/packages/rag/models/Xenova/all-MiniLM-L6-v2/tokenizer_config.json +15 -0
- package/packages/rag/package.json +27 -0
- package/packages/rag/src/blinded-search.js +109 -0
- package/packages/rag/src/bm25.js +169 -0
- package/packages/rag/src/embeddings.js +459 -0
- package/packages/rag/src/hybrid.js +76 -0
- package/packages/rag/src/index.js +38 -0
- package/packages/rag/src/reranker.js +61 -0
- package/packages/rag/src/research.js +107 -0
- package/packages/rag/src/vector-store.js +430 -0
- package/packages/rag/src/verify-model-artifacts.mjs +4 -0
- package/packages/sdk/index.d.ts +760 -0
- package/packages/sdk/package.json +33 -0
- package/packages/sdk/python/README.md +24 -0
- package/packages/sdk/python/enigma_sdk.py +250 -0
- package/packages/sdk/python/pyproject.toml +34 -0
- package/packages/sdk/python/requirements.txt +1 -0
- package/packages/sdk/python/setup.py +20 -0
- package/packages/sdk/src/federation/capability-grant.js +389 -0
- package/packages/sdk/src/federation/federation-router.js +360 -0
- package/packages/sdk/src/federation/ghostmesh-bridge.js +497 -0
- package/packages/sdk/src/federation/index.js +3 -0
- package/packages/sdk/src/index.js +1796 -0
- package/packages/sdk/src/intelligence/contradiction.js +337 -0
- package/packages/sdk/src/intelligence/decision-engine.js +155 -0
- package/packages/sdk/src/intelligence/index.js +4 -0
- package/packages/sdk/src/intelligence/ontology.js +122 -0
- package/packages/sdk/src/intelligence/temporal.js +123 -0
- package/packages/sdk/src/market-client.js +142 -0
- package/packages/sdk/src/mesh-client.js +110 -0
- package/packages/sdk/src/middleware/index.js +3 -0
- package/packages/sdk/src/middleware/langchain.js +159 -0
- package/packages/sdk/src/middleware/llamaindex.js +101 -0
- package/packages/sdk/src/middleware/vercel-ai.js +112 -0
- package/packages/sdk/src/rag-client.js +85 -0
- package/packages/sdk/src/swarm-orchestrator.js +260 -0
- package/packages/settlement/PACKAGE_CONTRACT.md +1 -1
- package/packages/snapcompact/THIRD_PARTY_LICENSES.txt +40 -0
- package/packages/snapcompact/assets/8x13-latin1.bdf +3837 -0
- package/packages/snapcompact/index.d.ts +284 -0
- package/packages/snapcompact/package.json +25 -0
- package/packages/snapcompact/src/index.js +716 -0
- package/packages/storage/PACKAGE_CONTRACT.md +1 -1
- package/packages/terminal-console/animations.mjs +240 -0
- package/packages/terminal-console/auto-anchor.mjs +220 -0
- package/packages/terminal-console/banner.mjs +91 -0
- package/packages/terminal-console/commands.mjs +459 -0
- package/packages/terminal-console/delegation.mjs +152 -0
- package/packages/terminal-console/index.mjs +5 -0
- package/packages/terminal-console/outbox.mjs +143 -0
- package/packages/terminal-console/phantom-bridge.mjs +637 -0
- package/packages/terminal-console/repl.mjs +136 -0
- package/packages/terminal-console/signer-store.mjs +130 -0
- package/packages/terminal-console/solana-rpc.mjs +214 -0
- package/packages/terminal-console/solana-transport.mjs +189 -0
- package/packages/terminal-tui/dashboard.mjs +214 -0
- package/packages/terminal-tui/index.mjs +28 -0
- package/packages/terminal-tui/merkle-tree-renderer.mjs +268 -0
- package/packages/terminal-tui/telemetry-hud.mjs +137 -0
- package/packages/vault/index.d.ts +449 -0
- package/packages/vault/package.json +27 -0
- package/packages/vault/src/e2ee.mjs +393 -0
- package/packages/vault/src/enclave.js +481 -0
- package/packages/vault/src/erasure.js +207 -0
- package/packages/vault/src/index.js +1150 -125
- package/packages/vault/src/persistence.js +307 -0
- package/packages/vault/src/poseidon.js +354 -0
- package/packages/vault/src/receipt.js +459 -0
- package/scripts/benchmark-optical-context.mjs +166 -0
- package/scripts/bootstrap-enigma.mjs +502 -0
- package/scripts/build-edge-backend-workers.mjs +20 -5
- package/scripts/build-goal-completion-audit.mjs +72 -25
- package/scripts/build-hosted-api-key-lifecycle.mjs +292 -274
- package/scripts/build-hosted-customer-lifecycle.mjs +493 -476
- package/scripts/build-hosted-probe-worker.mjs +19 -4
- package/scripts/build-installer-assets.mjs +409 -389
- package/scripts/build-operator-evidence-starter.mjs +59 -1
- package/scripts/build-production-backend-env-kit.mjs +2 -0
- package/scripts/build-production-unblocker.mjs +4 -1
- package/scripts/build-proof-network-packet.mjs +213 -213
- package/scripts/check.mjs +25 -4
- package/scripts/collect-hosted-backend-live-evidence.mjs +49 -12
- package/scripts/install-enigma-local.mjs +18 -5
- package/scripts/release-audit.mjs +74 -115
- package/scripts/release-provenance.mjs +12 -2
- package/scripts/run-backend-readiness-smoke.mjs +112 -10
- package/scripts/run-standard-memory-benchmarks.mjs +1354 -1352
- package/scripts/scan-secrets.mjs +178 -0
- package/scripts/simulate-production-env.mjs +71 -10
- package/scripts/validate-hosted-backend-live.mjs +112 -1
- package/specs/antibody-pack-v1.schema.json +95 -0
- package/specs/antigen-envelope-v1.schema.json +81 -0
- package/specs/boundary-manifest-v1.schema.json +35 -35
- package/specs/capsule-v1.schema.json +55 -55
- package/specs/claim-boundary-manifest-v1.schema.json +22 -22
- package/specs/claim-ledger-v1.schema.json +291 -0
- package/specs/context-passport-v1.schema.json +59 -0
- package/specs/deletion-tombstone-v1.schema.json +26 -26
- package/specs/evidence-packet-v1.schema.json +177 -0
- package/specs/hosted-backend-live-evidence-v1.schema.json +72 -3
- package/specs/immune-scan-report-v1.schema.json +112 -0
- package/specs/lifecycle-receipt-log-v1.schema.json +67 -0
- package/specs/memory-atom-v1.schema.json +59 -0
- package/specs/memory-event-v1.schema.json +42 -42
- package/specs/passport-v1.schema.json +50 -50
- package/specs/proof-of-non-use-v1.schema.json +65 -0
- package/specs/quarantine-record-v1.schema.json +126 -0
- package/specs/receipt-v1.schema.json +61 -61
- package/specs/state-checkpoint-v1.schema.json +37 -37
- package/specs/trust-bundle-v1.schema.json +56 -56
- package/specs/trust-card-v1.schema.json +119 -0
- package/docs/proof-network-launch-plan.md +0 -421
- package/packages/metering/PACKAGE_CONTRACT.md +0 -20
- package/scripts/build-ai-orchestration-plan.mjs +0 -248
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
export const X402_VERSION = 2;
|
|
2
|
+
export const X402_HEADERS = Object.freeze({
|
|
3
|
+
paymentRequired: 'PAYMENT-REQUIRED',
|
|
4
|
+
paymentSignature: 'PAYMENT-SIGNATURE',
|
|
5
|
+
paymentResponse: 'PAYMENT-RESPONSE',
|
|
6
|
+
});
|
|
7
|
+
|
|
8
|
+
function requiredString(value, name, maximum = 16_384) {
|
|
9
|
+
if (typeof value !== 'string' || !value.trim()) throw new TypeError(`${name} is required`);
|
|
10
|
+
const normalized = value.trim();
|
|
11
|
+
if (normalized.length > maximum) throw new TypeError(`${name} exceeds ${maximum} characters`);
|
|
12
|
+
return normalized;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function plainObject(value) {
|
|
16
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function canonicalize(value) {
|
|
20
|
+
if (Array.isArray(value)) return value.map(canonicalize);
|
|
21
|
+
if (!plainObject(value)) return value;
|
|
22
|
+
return Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonicalize(value[key])]));
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function sameJson(left, right) {
|
|
26
|
+
return JSON.stringify(canonicalize(left)) === JSON.stringify(canonicalize(right));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function secureUrl(value, name) {
|
|
30
|
+
const url = new URL(requiredString(value, name, 4096));
|
|
31
|
+
const loopback = ['127.0.0.1', 'localhost', '::1'].includes(url.hostname);
|
|
32
|
+
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) throw new TypeError(`${name} must use HTTPS outside localhost`);
|
|
33
|
+
if (url.username || url.password || url.hash) throw new TypeError(`${name} must not contain credentials or a fragment`);
|
|
34
|
+
return url;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function base64Json(value) {
|
|
38
|
+
return Buffer.from(JSON.stringify(value), 'utf8').toString('base64');
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function parseBase64Json(value, name, maximumBytes = 256 * 1024) {
|
|
42
|
+
const encoded = requiredString(value, name, Math.ceil(maximumBytes * 4 / 3) + 16);
|
|
43
|
+
if (!/^[A-Za-z0-9+/]*={0,2}$/.test(encoded) || encoded.length % 4 !== 0) throw new TypeError(`${name} is not canonical base64`);
|
|
44
|
+
const bytes = Buffer.from(encoded, 'base64');
|
|
45
|
+
if (bytes.length > maximumBytes || bytes.toString('base64') !== encoded) throw new TypeError(`${name} is invalid or too large`);
|
|
46
|
+
try {
|
|
47
|
+
const parsed = JSON.parse(bytes.toString('utf8'));
|
|
48
|
+
if (!plainObject(parsed)) throw new Error();
|
|
49
|
+
return parsed;
|
|
50
|
+
} catch {
|
|
51
|
+
throw new TypeError(`${name} does not contain a JSON object`);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function validateResource(resource, name = 'resource') {
|
|
56
|
+
if (!plainObject(resource)) throw new TypeError(`${name} must be an object`);
|
|
57
|
+
const url = secureUrl(resource.url, `${name}.url`).toString();
|
|
58
|
+
if (resource.description !== undefined) requiredString(resource.description, `${name}.description`, 1024);
|
|
59
|
+
if (resource.mimeType !== undefined) requiredString(resource.mimeType, `${name}.mimeType`, 256);
|
|
60
|
+
return { ...resource, url };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function validateRequirement(value, name = 'payment requirement') {
|
|
64
|
+
if (!plainObject(value)) throw new TypeError(`${name} must be an object`);
|
|
65
|
+
const requirement = {
|
|
66
|
+
scheme: requiredString(value.scheme, `${name}.scheme`, 64),
|
|
67
|
+
network: requiredString(value.network, `${name}.network`, 160),
|
|
68
|
+
amount: requiredString(value.amount, `${name}.amount`, 100),
|
|
69
|
+
asset: requiredString(value.asset, `${name}.asset`, 256),
|
|
70
|
+
payTo: requiredString(value.payTo, `${name}.payTo`, 256),
|
|
71
|
+
maxTimeoutSeconds: value.maxTimeoutSeconds,
|
|
72
|
+
...(value.extra === undefined ? {} : { extra: value.extra }),
|
|
73
|
+
};
|
|
74
|
+
if (!/^\d+$/.test(requirement.amount)) throw new TypeError(`${name}.amount must be atomic units as a decimal string`);
|
|
75
|
+
if (!Number.isInteger(requirement.maxTimeoutSeconds) || requirement.maxTimeoutSeconds < 1 || requirement.maxTimeoutSeconds > 86_400) {
|
|
76
|
+
throw new TypeError(`${name}.maxTimeoutSeconds is invalid`);
|
|
77
|
+
}
|
|
78
|
+
if (requirement.extra !== undefined && !plainObject(requirement.extra)) throw new TypeError(`${name}.extra must be an object`);
|
|
79
|
+
return requirement;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function parsePaymentRequiredHeader(value) {
|
|
83
|
+
const parsed = parseBase64Json(value, X402_HEADERS.paymentRequired);
|
|
84
|
+
if (parsed.x402Version !== X402_VERSION) throw new TypeError('unsupported x402 version');
|
|
85
|
+
const resource = validateResource(parsed.resource);
|
|
86
|
+
if (!Array.isArray(parsed.accepts) || !parsed.accepts.length || parsed.accepts.length > 32) throw new TypeError('x402 payment requirements must contain one through 32 accepts entries');
|
|
87
|
+
const accepts = parsed.accepts.map((entry, index) => validateRequirement(entry, `accepts[${index}]`));
|
|
88
|
+
if (parsed.extensions !== undefined && !plainObject(parsed.extensions)) throw new TypeError('x402 extensions must be an object');
|
|
89
|
+
return { x402Version: X402_VERSION, ...(parsed.error ? { error: String(parsed.error).slice(0, 1024) } : {}), resource, accepts, ...(parsed.extensions ? { extensions: parsed.extensions } : {}) };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function parsePaymentPayloadHeader(value) {
|
|
93
|
+
const parsed = parseBase64Json(value, X402_HEADERS.paymentSignature);
|
|
94
|
+
if (parsed.x402Version !== X402_VERSION) throw new TypeError('unsupported x402 payment payload version');
|
|
95
|
+
if (!plainObject(parsed.payload)) throw new TypeError('x402 payment payload is missing scheme payload');
|
|
96
|
+
if (parsed.extensions !== undefined && !plainObject(parsed.extensions)) throw new TypeError('x402 payment payload extensions must be an object');
|
|
97
|
+
return {
|
|
98
|
+
x402Version: X402_VERSION,
|
|
99
|
+
...(parsed.resource ? { resource: validateResource(parsed.resource, 'payment resource') } : {}),
|
|
100
|
+
accepted: validateRequirement(parsed.accepted, 'accepted'),
|
|
101
|
+
payload: parsed.payload,
|
|
102
|
+
...(parsed.extensions ? { extensions: parsed.extensions } : {}),
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function parseSettlementResponseHeader(value) {
|
|
107
|
+
const parsed = parseBase64Json(value, X402_HEADERS.paymentResponse);
|
|
108
|
+
if (typeof parsed.success !== 'boolean') throw new TypeError('x402 settlement success must be boolean');
|
|
109
|
+
const transaction = typeof parsed.transaction === 'string' ? parsed.transaction : '';
|
|
110
|
+
const network = requiredString(parsed.network, 'x402 settlement network', 160);
|
|
111
|
+
if (parsed.success && !transaction) throw new TypeError('successful x402 settlement requires a transaction');
|
|
112
|
+
return {
|
|
113
|
+
success: parsed.success,
|
|
114
|
+
transaction,
|
|
115
|
+
network,
|
|
116
|
+
...(parsed.errorReason ? { errorReason: String(parsed.errorReason).slice(0, 1024) } : {}),
|
|
117
|
+
...(parsed.payer ? { payer: String(parsed.payer).slice(0, 256) } : {}),
|
|
118
|
+
...(parsed.amount ? { amount: String(parsed.amount).slice(0, 100) } : {}),
|
|
119
|
+
...(parsed.extensions && plainObject(parsed.extensions) ? { extensions: parsed.extensions } : {}),
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function paymentFlow(requirement) {
|
|
124
|
+
return requirement.extra?.paymentFlow || 'authorization';
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function validateExtensions(required, supplied) {
|
|
128
|
+
if (!required) return;
|
|
129
|
+
if (!supplied || !plainObject(supplied)) throw new TypeError('x402 payment payload omitted required extensions');
|
|
130
|
+
for (const [name, extension] of Object.entries(required)) {
|
|
131
|
+
if (!Object.hasOwn(supplied, name) || !plainObject(extension) || !plainObject(supplied[name])) throw new TypeError(`x402 extension ${name} is missing`);
|
|
132
|
+
if (!sameJson(extension.info, supplied[name].info)) throw new TypeError(`x402 extension ${name} changed server-provided info`);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function validatePayloadBinding(payload, required, requirement) {
|
|
137
|
+
if (!sameJson(payload.accepted, requirement)) throw new TypeError('x402 payment payload accepted terms do not exactly match the server offer');
|
|
138
|
+
if (payload.resource && payload.resource.url !== required.resource.url) throw new TypeError('x402 payment payload resource URL mismatch');
|
|
139
|
+
validateExtensions(required.extensions, payload.extensions);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export function createX402FacilitatorClient(options = {}) {
|
|
143
|
+
const baseUrl = secureUrl(options.baseUrl, 'x402 facilitator URL');
|
|
144
|
+
if (!baseUrl.pathname.endsWith('/')) baseUrl.pathname += '/';
|
|
145
|
+
const apiKey = options.apiKey ? requiredString(options.apiKey, 'x402 facilitator API key', 4096) : null;
|
|
146
|
+
const timeoutMs = Number.isInteger(options.timeoutMs) ? options.timeoutMs : 30_000;
|
|
147
|
+
if (timeoutMs < 1000 || timeoutMs > 120_000) throw new TypeError('x402 facilitator timeout is invalid');
|
|
148
|
+
|
|
149
|
+
async function request(path, body) {
|
|
150
|
+
const controller = new AbortController();
|
|
151
|
+
const timer = setTimeout(() => controller.abort(new Error('x402 facilitator timed out')), timeoutMs);
|
|
152
|
+
try {
|
|
153
|
+
const response = await fetch(new URL(path, baseUrl), {
|
|
154
|
+
method: body === undefined ? 'GET' : 'POST',
|
|
155
|
+
headers: { Accept: 'application/json', ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}) },
|
|
156
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
157
|
+
redirect: 'error',
|
|
158
|
+
signal: controller.signal,
|
|
159
|
+
});
|
|
160
|
+
const payload = await response.json().catch(() => null);
|
|
161
|
+
if (!response.ok || !plainObject(payload)) throw new Error(`x402 facilitator failed with HTTP ${response.status}`);
|
|
162
|
+
return payload;
|
|
163
|
+
} finally {
|
|
164
|
+
clearTimeout(timer);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
return Object.freeze({
|
|
169
|
+
supported: () => request('supported'),
|
|
170
|
+
async verify(paymentPayload, paymentRequirements) {
|
|
171
|
+
const result = await request('verify', { x402Version: X402_VERSION, paymentPayload, paymentRequirements });
|
|
172
|
+
if (typeof result.isValid !== 'boolean') throw new Error('x402 facilitator returned an invalid verify response');
|
|
173
|
+
return result;
|
|
174
|
+
},
|
|
175
|
+
async settle(paymentPayload, paymentRequirements) {
|
|
176
|
+
const result = await request('settle', { x402Version: X402_VERSION, paymentPayload, paymentRequirements });
|
|
177
|
+
if (typeof result.success !== 'boolean' || typeof result.transaction !== 'string' || typeof result.network !== 'string') {
|
|
178
|
+
throw new Error('x402 facilitator returned an invalid settlement response');
|
|
179
|
+
}
|
|
180
|
+
if (result.success && !result.transaction) throw new Error('x402 facilitator reported success without a transaction');
|
|
181
|
+
return result;
|
|
182
|
+
},
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function normalizeRoute(route) {
|
|
187
|
+
if (!route || typeof route !== 'object' || typeof route.execute !== 'function') throw new TypeError('x402 route requires execute()');
|
|
188
|
+
const method = requiredString(route.method || 'POST', 'x402 route method', 16).toUpperCase();
|
|
189
|
+
const path = requiredString(route.path, 'x402 route path', 2048);
|
|
190
|
+
if (!path.startsWith('/') || path.includes('?') || path.includes('#')) throw new TypeError('x402 route path must be absolute without query or fragment');
|
|
191
|
+
const resource = validateResource(route.resource);
|
|
192
|
+
const accepts = (route.accepts || []).map((entry, index) => validateRequirement(entry, `accepts[${index}]`));
|
|
193
|
+
if (!accepts.length) throw new TypeError('x402 route requires at least one payment requirement');
|
|
194
|
+
for (const requirement of accepts) {
|
|
195
|
+
const flow = paymentFlow(requirement);
|
|
196
|
+
if (flow !== 'upfront') throw new TypeError('x402 paid execution routes require explicit upfront settlement before resource execution');
|
|
197
|
+
}
|
|
198
|
+
return Object.freeze({ method, path, resource, accepts: Object.freeze(accepts), extensions: route.extensions || {}, execute: route.execute });
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
async function readRequestBody(request, maximum) {
|
|
202
|
+
const chunks = [];
|
|
203
|
+
let size = 0;
|
|
204
|
+
let tooLarge = false;
|
|
205
|
+
for await (const chunk of request) {
|
|
206
|
+
size += chunk.length;
|
|
207
|
+
if (size > maximum) tooLarge = true;
|
|
208
|
+
else chunks.push(chunk);
|
|
209
|
+
}
|
|
210
|
+
if (tooLarge) throw Object.assign(new Error('x402 request body is too large'), { statusCode: 413 });
|
|
211
|
+
return Buffer.concat(chunks, size);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function writeJson(response, status, payload, headers = {}) {
|
|
215
|
+
const body = JSON.stringify(payload);
|
|
216
|
+
response.statusCode = status;
|
|
217
|
+
response.setHeader('Cache-Control', 'no-store');
|
|
218
|
+
response.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
219
|
+
response.setHeader('Content-Length', Buffer.byteLength(body));
|
|
220
|
+
response.setHeader('X-Content-Type-Options', 'nosniff');
|
|
221
|
+
for (const [name, value] of Object.entries(headers)) response.setHeader(name, value);
|
|
222
|
+
response.end(body);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export function createX402ResourceHandler(options = {}) {
|
|
226
|
+
const facilitator = options.facilitator;
|
|
227
|
+
if (!facilitator || typeof facilitator.verify !== 'function' || typeof facilitator.settle !== 'function') throw new TypeError('x402 facilitator is required');
|
|
228
|
+
const routes = (options.routes || []).map(normalizeRoute);
|
|
229
|
+
const routeMap = new Map(routes.map((route) => [`${route.method} ${route.path}`, route]));
|
|
230
|
+
if (routeMap.size !== routes.length) throw new TypeError('duplicate x402 route');
|
|
231
|
+
const maxBodyBytes = Number.isInteger(options.maxBodyBytes) ? options.maxBodyBytes : 8 * 1024 * 1024;
|
|
232
|
+
|
|
233
|
+
return async function x402ResourceHandler(request, response, parsedUrl = null) {
|
|
234
|
+
const url = parsedUrl || new URL(request.url || '/', 'http://localhost');
|
|
235
|
+
const route = routeMap.get(`${request.method} ${url.pathname}`);
|
|
236
|
+
if (!route) return false;
|
|
237
|
+
const required = { x402Version: X402_VERSION, error: `${X402_HEADERS.paymentSignature} header is required`, resource: route.resource, accepts: route.accepts, extensions: route.extensions };
|
|
238
|
+
const paymentHeader = request.headers['payment-signature'];
|
|
239
|
+
if (!paymentHeader) {
|
|
240
|
+
writeJson(response, 402, { error: 'payment_required' }, { [X402_HEADERS.paymentRequired]: base64Json(required) });
|
|
241
|
+
return true;
|
|
242
|
+
}
|
|
243
|
+
let phase = 'payment';
|
|
244
|
+
let settlement = null;
|
|
245
|
+
let accepted = null;
|
|
246
|
+
try {
|
|
247
|
+
const payload = parsePaymentPayloadHeader(paymentHeader);
|
|
248
|
+
accepted = route.accepts.find((entry) => sameJson(entry, payload.accepted));
|
|
249
|
+
if (!accepted) throw new TypeError('x402 payment payload selected an unoffered requirement');
|
|
250
|
+
validatePayloadBinding(payload, required, accepted);
|
|
251
|
+
phase = 'request';
|
|
252
|
+
const rawBody = await readRequestBody(request, maxBodyBytes);
|
|
253
|
+
phase = 'payment';
|
|
254
|
+
const flow = paymentFlow(accepted);
|
|
255
|
+
if (flow !== 'upfront') throw new Error('x402 paid execution route is not prepaid');
|
|
256
|
+
settlement = await facilitator.settle(payload, accepted);
|
|
257
|
+
if (!settlement.success) throw new Error(settlement.errorReason || 'x402 upfront settlement failed');
|
|
258
|
+
if (settlement.network !== accepted.network) throw new Error('x402 facilitator settled on a different network');
|
|
259
|
+
phase = 'resource';
|
|
260
|
+
const result = await route.execute({ request, url, rawBody, payment: payload, requirement: accepted });
|
|
261
|
+
writeJson(response, result?.status || 200, result?.body ?? result ?? null, { [X402_HEADERS.paymentResponse]: base64Json(settlement) });
|
|
262
|
+
return true;
|
|
263
|
+
} catch (error) {
|
|
264
|
+
if (phase === 'resource') {
|
|
265
|
+
writeJson(response, 500, { error: 'resource_error', message: 'paid resource execution failed' }, settlement?.success ? { [X402_HEADERS.paymentResponse]: base64Json(settlement) } : {});
|
|
266
|
+
return true;
|
|
267
|
+
}
|
|
268
|
+
if (phase === 'request') {
|
|
269
|
+
writeJson(response, error.statusCode || 400, { error: 'invalid_request', message: error.message || 'invalid x402 request' });
|
|
270
|
+
return true;
|
|
271
|
+
}
|
|
272
|
+
const failed = { success: false, errorReason: error.message || 'payment_failed', transaction: '', network: accepted?.network || route.accepts[0].network };
|
|
273
|
+
writeJson(response, error instanceof TypeError ? 400 : 402, { error: 'payment_failed', message: failed.errorReason }, { [X402_HEADERS.paymentResponse]: base64Json(failed), [X402_HEADERS.paymentRequired]: base64Json(required) });
|
|
274
|
+
return true;
|
|
275
|
+
}
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function replayableBody(value) {
|
|
280
|
+
if (value === undefined || value === null) return undefined;
|
|
281
|
+
if (typeof value === 'string') return value;
|
|
282
|
+
if (Buffer.isBuffer(value)) return Buffer.from(value);
|
|
283
|
+
if (value instanceof Uint8Array) return Buffer.from(value);
|
|
284
|
+
if (value instanceof URLSearchParams) return value.toString();
|
|
285
|
+
throw new TypeError('x402 client request body must be replayable bytes, string, or URLSearchParams');
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
function requirementAllowed(requirement, policy) {
|
|
289
|
+
if (policy.schemes?.length && !policy.schemes.includes(requirement.scheme)) return false;
|
|
290
|
+
if (policy.networks?.length && !policy.networks.includes(requirement.network)) return false;
|
|
291
|
+
if (policy.assets?.length && !policy.assets.includes(requirement.asset)) return false;
|
|
292
|
+
if (policy.payTo?.length && !policy.payTo.includes(requirement.payTo)) return false;
|
|
293
|
+
if (policy.paymentFlows?.length && !policy.paymentFlows.includes(paymentFlow(requirement))) return false;
|
|
294
|
+
const maximum = policy.maxAmounts?.[`${requirement.network}/${requirement.asset}`] ?? policy.maxAmount;
|
|
295
|
+
if (maximum !== undefined && BigInt(requirement.amount) > BigInt(maximum)) return false;
|
|
296
|
+
return true;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
export function createX402HttpClient(options = {}) {
|
|
300
|
+
if (typeof options.createPaymentPayload !== 'function') throw new TypeError('x402 client requires createPaymentPayload() from a real wallet signer');
|
|
301
|
+
if (!Array.isArray(options.networks) || !options.networks.length) throw new TypeError('x402 client requires an explicit network allowlist');
|
|
302
|
+
if (!Array.isArray(options.assets) || !options.assets.length) throw new TypeError('x402 client requires an explicit asset allowlist');
|
|
303
|
+
if (!Array.isArray(options.payTo) || !options.payTo.length) throw new TypeError('x402 client requires an explicit recipient allowlist');
|
|
304
|
+
if (options.maxAmount === undefined && !Object.keys(options.maxAmounts || {}).length) throw new TypeError('x402 client requires an explicit payment budget');
|
|
305
|
+
const policy = Object.freeze({
|
|
306
|
+
schemes: options.schemes || ['exact'],
|
|
307
|
+
networks: options.networks || [],
|
|
308
|
+
assets: options.assets || [],
|
|
309
|
+
payTo: options.payTo || [],
|
|
310
|
+
paymentFlows: options.paymentFlows || ['authorization'],
|
|
311
|
+
maxAmounts: options.maxAmounts || {},
|
|
312
|
+
maxAmount: options.maxAmount,
|
|
313
|
+
});
|
|
314
|
+
|
|
315
|
+
return async function x402Fetch(input, init = {}) {
|
|
316
|
+
const url = secureUrl(input, 'x402 resource URL');
|
|
317
|
+
const body = replayableBody(init.body);
|
|
318
|
+
const headers = new Headers(init.headers || {});
|
|
319
|
+
headers.delete(X402_HEADERS.paymentSignature);
|
|
320
|
+
headers.delete(X402_HEADERS.paymentRequired);
|
|
321
|
+
headers.delete(X402_HEADERS.paymentResponse);
|
|
322
|
+
const requestInit = { ...init, headers, body, redirect: 'manual' };
|
|
323
|
+
const first = await fetch(url, requestInit);
|
|
324
|
+
if (first.status !== 402) return { response: first, settlement: null, paymentRequired: null };
|
|
325
|
+
const paymentRequired = parsePaymentRequiredHeader(first.headers.get(X402_HEADERS.paymentRequired));
|
|
326
|
+
if (paymentRequired.resource.url !== url.toString()) throw new Error('x402 server requested payment for a different resource URL');
|
|
327
|
+
const acceptable = paymentRequired.accepts.filter((requirement) => requirementAllowed(requirement, policy));
|
|
328
|
+
if (!acceptable.length) throw new Error('x402 payment requirements exceed the configured wallet policy');
|
|
329
|
+
const selected = typeof options.selectPayment === 'function' ? await options.selectPayment(acceptable, paymentRequired) : acceptable[0];
|
|
330
|
+
if (!acceptable.some((entry) => sameJson(entry, selected))) throw new Error('x402 payment selector returned an unoffered requirement');
|
|
331
|
+
const payload = await options.createPaymentPayload({ requirement: selected, paymentRequired, resourceUrl: url.toString() });
|
|
332
|
+
const validated = parsePaymentPayloadHeader(base64Json(payload));
|
|
333
|
+
validatePayloadBinding(validated, paymentRequired, selected);
|
|
334
|
+
await first.body?.cancel?.();
|
|
335
|
+
const paidHeaders = new Headers(headers);
|
|
336
|
+
paidHeaders.set(X402_HEADERS.paymentSignature, base64Json(validated));
|
|
337
|
+
const paid = await fetch(url, { ...requestInit, headers: paidHeaders, body: replayableBody(body) });
|
|
338
|
+
if (paid.status >= 300 && paid.status < 400) throw new Error('x402 paid request redirect was blocked');
|
|
339
|
+
const responseHeader = paid.headers.get(X402_HEADERS.paymentResponse);
|
|
340
|
+
if (!responseHeader) throw new Error('x402 paid response omitted PAYMENT-RESPONSE');
|
|
341
|
+
const settlement = parseSettlementResponseHeader(responseHeader);
|
|
342
|
+
if (!settlement.success) throw new Error(settlement.errorReason || 'x402 payment failed');
|
|
343
|
+
if (settlement.network !== selected.network) throw new Error('x402 settlement network mismatch');
|
|
344
|
+
return { response: paid, settlement, paymentRequired };
|
|
345
|
+
};
|
|
346
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# Proof Network Contract
|
|
2
|
+
|
|
3
|
+
`enigma-memory/proof-network` defines canonical schema validation and normalization for sovereign proof network artifacts: anchor batches, capability grants, benchmark attestations, and registry batches.
|
|
4
|
+
|
|
5
|
+
## Purpose
|
|
6
|
+
|
|
7
|
+
The package normalizes and validates public-safe cryptographic proof objects:
|
|
8
|
+
- `anchor_batch`: Merkle roots, sequence intervals, and ledger anchoring metadata
|
|
9
|
+
- `capability_grant`: Signed scoped delegation grants
|
|
10
|
+
- `capability_revocation`: Explicit capability invalidations
|
|
11
|
+
- `benchmark_attestation`: Cryptographic benchmark performance records
|
|
12
|
+
- `packet`: Transport envelopes for proof verification
|
|
13
|
+
- `registry_entry` and `registry_batch`: Aggregated proof network registry records
|
|
14
|
+
|
|
15
|
+
## Boundary & Privacy Guarantees
|
|
16
|
+
|
|
17
|
+
The package enforces strict zero-leakage boundaries:
|
|
18
|
+
- Zero raw memory or prompt plaintext in proof artifacts
|
|
19
|
+
- Zero embedding vector content on-chain
|
|
20
|
+
- Rejects ungrounded claims, secrets, private keys, tokens, and raw customer data
|
|
21
|
+
- Operates purely offline with deterministic cryptographic validations
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
|
|
3
|
+
export interface LexicalHashDescriptor {
|
|
4
|
+
readonly provider: string;
|
|
5
|
+
readonly version: string;
|
|
6
|
+
readonly dimension: number;
|
|
7
|
+
readonly architecture: string;
|
|
8
|
+
readonly description: string;
|
|
9
|
+
}
|
|
10
|
+
export declare const LEXICAL_HASH_DESCRIPTOR: LexicalHashDescriptor;
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
export interface LocalMiniLmArtifact {
|
|
14
|
+
readonly path: string;
|
|
15
|
+
readonly size: number;
|
|
16
|
+
readonly sha256: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface LocalMiniLmDescriptor {
|
|
20
|
+
readonly provider: 'huggingface_transformers_local';
|
|
21
|
+
readonly package: '@huggingface/transformers';
|
|
22
|
+
readonly packageVersion: '4.2.0';
|
|
23
|
+
readonly modelId: 'Xenova/all-MiniLM-L6-v2';
|
|
24
|
+
readonly immutableCommit: '751bff37182d3f1213fa05d7196b954e230abad9';
|
|
25
|
+
readonly dimension: 384;
|
|
26
|
+
readonly maxSequenceLength: 512;
|
|
27
|
+
readonly dtype: 'q8';
|
|
28
|
+
readonly device: 'cpu';
|
|
29
|
+
readonly pooling: 'mean';
|
|
30
|
+
readonly normalization: 'l2_unit_sphere';
|
|
31
|
+
readonly manifest: 'sha256-manifest.json';
|
|
32
|
+
readonly manifestSha256: string;
|
|
33
|
+
readonly artifacts: readonly LocalMiniLmArtifact[];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export declare const LOCAL_MINILM_DESCRIPTOR: LocalMiniLmDescriptor;
|
|
37
|
+
export declare const ONNX_INTEGRATION_SPEC: LocalMiniLmDescriptor;
|
|
38
|
+
export declare const EMBEDDING_DIM: number;
|
|
39
|
+
export declare function verifyBundledModel(): Promise<void>;
|
|
40
|
+
|
|
41
|
+
export interface TokenSubword {
|
|
42
|
+
token: string;
|
|
43
|
+
isSubword: boolean;
|
|
44
|
+
pos: number;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export declare function tokenizeSubwords(text: string): TokenSubword[];
|
|
48
|
+
export declare function computeLexicalEmbedding(text: string, dim?: number): Float32Array;
|
|
49
|
+
|
|
50
|
+
export interface EmbeddingProvider {
|
|
51
|
+
readonly providerType: 'local_minilm' | 'lexical_hash' | 'onnx_runtime_adapter' | string;
|
|
52
|
+
readonly descriptor: LocalMiniLmDescriptor | LexicalHashDescriptor;
|
|
53
|
+
dimension: number;
|
|
54
|
+
embed(text: string): Promise<Float32Array>;
|
|
55
|
+
embedSync(text: string): Float32Array;
|
|
56
|
+
embedBatch(texts: string[]): Promise<Float32Array[]>;
|
|
57
|
+
dispose(): Promise<void>;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface OnnxEmbeddingRunner {
|
|
61
|
+
run(texts: string[]): Promise<Float32Array[] | number[][]>;
|
|
62
|
+
dispose?(): void | Promise<void>;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export declare function createEmbeddingProvider(options?: {
|
|
66
|
+
dimension?: number;
|
|
67
|
+
modelType?: 'neural' | 'lexical' | 'onnx';
|
|
68
|
+
onnxRunner?: ((text: string) => Promise<Float32Array | number[]>) | OnnxEmbeddingRunner;
|
|
69
|
+
}): EmbeddingProvider;
|
|
70
|
+
|
|
71
|
+
export declare function cosineSimilarity(a: Float32Array, b: Float32Array): number;
|
|
72
|
+
export declare function quantizeVector(floatVec: Float32Array): Int8Array;
|
|
73
|
+
export declare function dequantizeVector(int8Vec: Int8Array): Float32Array;
|
|
74
|
+
|
|
75
|
+
export declare class BM25Index {
|
|
76
|
+
k1: number;
|
|
77
|
+
b: number;
|
|
78
|
+
docs: Map<string, unknown>;
|
|
79
|
+
invertedIndex: Map<string, Set<string>>;
|
|
80
|
+
totalDocLength: number;
|
|
81
|
+
|
|
82
|
+
constructor(options?: { k1?: number; b?: number });
|
|
83
|
+
tokenize(text: string): string[];
|
|
84
|
+
add(id: string, text: string, scope?: string): void;
|
|
85
|
+
remove(id: string): void;
|
|
86
|
+
clear(): void;
|
|
87
|
+
search(queryText: string, options?: { topK?: number; scope?: string }): Array<{ id: string; text: string; score: number; scope: string }>;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export declare function reciprocalRankFusion(
|
|
91
|
+
denseResults: Array<{ id: string; text: string; score: number; scope: string; metadata?: Record<string, unknown> }>,
|
|
92
|
+
bm25Results: Array<{ id: string; text: string; score: number; scope: string }>,
|
|
93
|
+
options?: { k?: number; denseWeight?: number; bm25Weight?: number; topK?: number }
|
|
94
|
+
): Array<{ id: string; text: string; score: number; denseScore: number; bm25Score: number; scope: string; metadata?: Record<string, unknown> }>;
|
|
95
|
+
|
|
96
|
+
export declare function semanticReranker(
|
|
97
|
+
queryText: string,
|
|
98
|
+
candidates: Array<{ id: string; text: string; score: number; scope: string; metadata?: Record<string, unknown>; importance?: number }>,
|
|
99
|
+
options?: { topK?: number; phraseBonus?: number; coverageWeight?: number }
|
|
100
|
+
): Array<{ id: string; text: string; score: number; originalScore: number; scope: string; metadata?: Record<string, unknown> }>;
|
|
101
|
+
|
|
102
|
+
export interface EncryptedVectorStoreOptions {
|
|
103
|
+
embeddingProvider?: EmbeddingProvider;
|
|
104
|
+
dimension?: number;
|
|
105
|
+
quantize?: boolean;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export interface VectorDocument {
|
|
109
|
+
id: string;
|
|
110
|
+
text: string;
|
|
111
|
+
scope: string;
|
|
112
|
+
importance: number;
|
|
113
|
+
createdAt: number;
|
|
114
|
+
metadata: Record<string, unknown>;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export interface SearchResultItem {
|
|
118
|
+
id: string;
|
|
119
|
+
text: string;
|
|
120
|
+
score: number;
|
|
121
|
+
cosine?: number;
|
|
122
|
+
scope: string;
|
|
123
|
+
importance?: number;
|
|
124
|
+
createdAt?: number;
|
|
125
|
+
metadata?: Record<string, unknown>;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export interface ContextPackCompilation {
|
|
129
|
+
contextText: string;
|
|
130
|
+
items: SearchResultItem[];
|
|
131
|
+
totalChars: number;
|
|
132
|
+
estimatedTokens: number;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export interface EncryptedVectorBundle {
|
|
136
|
+
format: string;
|
|
137
|
+
ciphertext: string;
|
|
138
|
+
iv: string;
|
|
139
|
+
authTag: string;
|
|
140
|
+
count: number;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export declare class EncryptedVectorStore {
|
|
144
|
+
dimension: number;
|
|
145
|
+
quantize: boolean;
|
|
146
|
+
embedder: EmbeddingProvider;
|
|
147
|
+
documents: Map<string, VectorDocument>;
|
|
148
|
+
vectors: Map<string, Int8Array | Float32Array>;
|
|
149
|
+
bm25: BM25Index;
|
|
150
|
+
|
|
151
|
+
constructor(options?: EncryptedVectorStoreOptions);
|
|
152
|
+
|
|
153
|
+
add(
|
|
154
|
+
id: string,
|
|
155
|
+
text: string,
|
|
156
|
+
metadata?: Record<string, unknown>,
|
|
157
|
+
options?: { epoch?: number; signal?: AbortSignal }
|
|
158
|
+
): Promise<{ id: string; scope: string; dimension: number; quantized: boolean } | null>;
|
|
159
|
+
addSync(id: string, text: string, metadata?: Record<string, unknown>): { id: string; scope: string; dimension: number; quantized: boolean };
|
|
160
|
+
addBatch(items: Array<{ id: string; text: string; metadata?: Record<string, unknown> }>): Promise<number>;
|
|
161
|
+
remove(id: string): boolean;
|
|
162
|
+
delete(id: string): boolean;
|
|
163
|
+
clear(): void;
|
|
164
|
+
get size(): number;
|
|
165
|
+
search(query: string | Float32Array, options?: { mode?: 'hybrid' | 'dense' | 'bm25'; topK?: number; threshold?: number; scope?: string; denseWeight?: number; bm25Weight?: number }): Promise<SearchResultItem[]>;
|
|
166
|
+
searchSync(query: string | Float32Array, options?: { mode?: 'hybrid' | 'dense' | 'bm25'; topK?: number; threshold?: number; scope?: string }): SearchResultItem[];
|
|
167
|
+
searchByVector(queryVec: Float32Array, options?: { topK?: number; threshold?: number; scope?: string }): SearchResultItem[];
|
|
168
|
+
compileContextPack(query: string, options?: { maxTokens?: number; topK?: number; scope?: string }): Promise<ContextPackCompilation>;
|
|
169
|
+
|
|
170
|
+
encryptForVault(vaultKey: Buffer | string): EncryptedVectorBundle;
|
|
171
|
+
static decryptFromVault(encryptedBundle: EncryptedVectorBundle, vaultKey: Buffer | string, options?: { embeddingProvider?: EmbeddingProvider }): EncryptedVectorStore;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export declare const RESEARCH_DISCLAIMER: {
|
|
175
|
+
readonly status: string;
|
|
176
|
+
readonly warning: string;
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
export declare function generateResearchOrthogonalBasis(seed: string, dim?: number): Float32Array[];
|
|
180
|
+
export declare function applyResearchBasisTransform(vec: Float32Array, basis: Float32Array[]): Float32Array;
|
|
181
|
+
export declare function createResearchBlindedQuery(queryVec: Float32Array, basis: Float32Array[], alpha?: number): { blindedVector: Float32Array; scalar: number };
|
|
182
|
+
export declare function evaluateResearchBlindedRanking(blindedQuery: Float32Array, transformedDocs: Map<string, Float32Array>, topK?: number): Array<{ id: string; rawScore: number }>;
|