@sparkysolutions/agentrail 0.1.0 → 0.1.1

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 (113) hide show
  1. package/README.md +249 -146
  2. package/dist/cli/mcp-stdio.d.ts +8 -0
  3. package/dist/cli/mcp-stdio.js +454 -0
  4. package/dist/cli/pipeline.d.ts +40 -0
  5. package/dist/cli/pipeline.js +114 -0
  6. package/dist/cli/sandbox.d.ts +15 -1
  7. package/dist/cli/sandbox.js +30 -5
  8. package/dist/index.d.ts +13 -0
  9. package/dist/index.js +13 -0
  10. package/dist/lib/agent-badge-issuer.d.ts +36 -0
  11. package/dist/lib/agent-badge-issuer.js +166 -0
  12. package/dist/lib/agent-registry.d.ts +136 -0
  13. package/dist/lib/agent-registry.js +124 -0
  14. package/dist/lib/agenthustle-pipeline.d.ts +68 -0
  15. package/dist/lib/agenthustle-pipeline.js +143 -0
  16. package/dist/lib/agentpass-pipeline.d.ts +44 -0
  17. package/dist/lib/agentpass-pipeline.js +84 -0
  18. package/dist/lib/audit-trail-provider.d.ts +24 -0
  19. package/dist/lib/audit-trail-provider.js +60 -0
  20. package/dist/lib/axis-clob-provider.d.ts +50 -0
  21. package/dist/lib/axis-clob-provider.js +150 -0
  22. package/dist/lib/circuit-breaker.d.ts +60 -0
  23. package/dist/lib/circuit-breaker.js +136 -0
  24. package/dist/lib/conditional-escrow.d.ts +42 -0
  25. package/dist/lib/conditional-escrow.js +126 -0
  26. package/dist/lib/mcp-server.d.ts +29 -0
  27. package/dist/lib/mcp-server.js +165 -0
  28. package/dist/lib/receipts.d.ts +153 -0
  29. package/dist/lib/receipts.js +173 -0
  30. package/dist/lib/reflector-oracle-adapter.d.ts +44 -0
  31. package/dist/lib/reflector-oracle-adapter.js +173 -0
  32. package/dist/lib/scoped-allowance.d.ts +4 -0
  33. package/dist/lib/scoped-allowance.js +22 -1
  34. package/dist/lib/universal-adapters.d.ts +42 -0
  35. package/dist/lib/universal-adapters.js +69 -0
  36. package/dist/lib/x402-gateway.d.ts +86 -0
  37. package/dist/lib/x402-gateway.js +128 -0
  38. package/dist/lib/x402-pipeline.d.ts +51 -0
  39. package/dist/lib/x402-pipeline.js +105 -0
  40. package/dist/types.d.ts +109 -0
  41. package/glama.json +12 -0
  42. package/package.json +56 -40
  43. package/smithery.json +43 -0
  44. package/smithery.yaml +29 -0
  45. package/.github/ISSUE_TEMPLATE/drips_wave_task.md +0 -33
  46. package/.github/workflows/auto-merge.yml +0 -119
  47. package/.github/workflows/ci.yml +0 -35
  48. package/BENCHMARKS.md +0 -67
  49. package/CONTRIBUTING.md +0 -40
  50. package/DRIPS_WAVE.md +0 -81
  51. package/FUNDING.json +0 -7
  52. package/ISSUES_PIPELINE.json +0 -106
  53. package/RUNBOOK.md +0 -95
  54. package/SCF_ACTIVATION_PROPOSAL.md +0 -137
  55. package/assets/sorobanagents_avatar.jpg +0 -0
  56. package/assets/sorobanagents_avatar.png +0 -0
  57. package/assets/sorobanagents_avatar_elite.png +0 -0
  58. package/contracts/agentrail/Cargo.lock +0 -1895
  59. package/contracts/agentrail/Cargo.toml +0 -25
  60. package/contracts/agentrail/src/lib.rs +0 -296
  61. package/contracts/agentrail/src/test.rs +0 -442
  62. package/contracts/agentrail/test_snapshots/test/test_circuit_breaker_pause_and_unpause.1.json +0 -195
  63. package/contracts/agentrail/test_snapshots/test/test_double_initialize_fails.1.json +0 -123
  64. package/contracts/agentrail/test_snapshots/test/test_execute_spend_deducts_and_accumulates.1.json +0 -347
  65. package/contracts/agentrail/test_snapshots/test/test_get_allowance_returns_none_for_unregistered.1.json +0 -61
  66. package/contracts/agentrail/test_snapshots/test/test_get_version_matches_cargo_toml.1.json +0 -61
  67. package/contracts/agentrail/test_snapshots/test/test_grant_allowance_negative_amount_fails.1.json +0 -123
  68. package/contracts/agentrail/test_snapshots/test/test_grant_allowance_success.1.json +0 -250
  69. package/contracts/agentrail/test_snapshots/test/test_grant_allowance_zero_amount_fails.1.json +0 -123
  70. package/contracts/agentrail/test_snapshots/test/test_initialize_and_protocol_fee.1.json +0 -154
  71. package/contracts/agentrail/test_snapshots/test/test_initialize_success.1.json +0 -124
  72. package/contracts/agentrail/test_snapshots/test/test_initialize_with_excessive_fee_fails.1.json +0 -61
  73. package/contracts/agentrail/test_snapshots/test/test_max_protocol_fee_spend_boundary.1.json +0 -298
  74. package/contracts/agentrail/test_snapshots/test/test_multi_agent_allowance_isolation.1.json +0 -426
  75. package/contracts/agentrail/test_snapshots/test/test_multi_owner_isolation.1.json +0 -426
  76. package/contracts/agentrail/test_snapshots/test/test_regrant_allowance_updates_limits.1.json +0 -346
  77. package/contracts/agentrail/test_snapshots/test/test_revoke_allowance_freezes_spending.1.json +0 -292
  78. package/contracts/agentrail/test_snapshots/test/test_set_protocol_fee_by_admin.1.json +0 -165
  79. package/contracts/agentrail/test_snapshots/test/test_spend_after_expiry_fails.1.json +0 -250
  80. package/contracts/agentrail/test_snapshots/test/test_spend_exact_allowance_boundary.1.json +0 -298
  81. package/contracts/agentrail/test_snapshots/test/test_spend_exceeding_allowance_fails.1.json +0 -250
  82. package/contracts/agentrail/test_snapshots/test/test_spend_fails_when_circuit_breaker_tripped.1.json +0 -285
  83. package/contracts/agentrail/test_snapshots/test/test_spend_negative_amount_fails.1.json +0 -250
  84. package/contracts/agentrail/test_snapshots/test/test_spend_non_existent_allowance_fails.1.json +0 -123
  85. package/contracts/agentrail/test_snapshots/test/test_spend_on_revoked_allowance_fails.1.json +0 -292
  86. package/contracts/agentrail/test_snapshots/test/test_spend_with_protocol_fee.1.json +0 -286
  87. package/contracts/agentrail/test_snapshots/test/test_spend_zero_amount_fails.1.json +0 -250
  88. package/contracts/agentrail/test_snapshots/test/test_unpause_restores_spend_operations.1.json +0 -370
  89. package/contracts/agentrail/test_snapshots/test/test_zero_protocol_fee_spend.1.json +0 -298
  90. package/deployment.testnet.json +0 -15
  91. package/docs/assets/favicon.png +0 -0
  92. package/docs/assets/logo.png +0 -0
  93. package/docs/index.html +0 -840
  94. package/scripts/demo-agent.ts +0 -52
  95. package/scripts/deploy-testnet.ts +0 -228
  96. package/scripts/security-audit.mjs +0 -159
  97. package/src/cli/sandbox.ts +0 -127
  98. package/src/index.ts +0 -11
  99. package/src/lib/micro-stream.ts +0 -52
  100. package/src/lib/proof-of-task.ts +0 -39
  101. package/src/lib/scoped-allowance.ts +0 -112
  102. package/src/lib/ttl-keeper.ts +0 -44
  103. package/src/sdk/agent-client.ts +0 -66
  104. package/src/types.ts +0 -78
  105. package/tests/agent-client.test.ts +0 -62
  106. package/tests/cli.test.ts +0 -68
  107. package/tests/micro-stream.test.ts +0 -38
  108. package/tests/proof-of-task.test.ts +0 -78
  109. package/tests/scoped-allowance.test.ts +0 -135
  110. package/tests/security-audit.test.ts +0 -76
  111. package/tests/ttl-keeper.test.ts +0 -36
  112. package/tsconfig.json +0 -16
  113. package/vitest.config.ts +0 -8
@@ -1,52 +0,0 @@
1
- #!/usr/bin/env node
2
- import { provisionSandbox, executeSandboxSpend, inspectBalance } from "../src/cli/sandbox.js";
3
-
4
- async function runDemo() {
5
- console.log("================================================================================");
6
- console.log("🚂 AGENTRAIL: AUTONOMOUS AI AGENT MICRO-SETTLEMENT PROTOCOL (SOROBAN / STELLAR)");
7
- console.log("================================================================================");
8
- console.log("Contract ID: CBSWWN2CLUPW4VLYTGVJTT4XWXKF6LLJFQXEC7KK2KTAW3A26WIBZIN6");
9
- console.log("Network: Stellar Testnet (Protocol 29)");
10
- console.log("Treasury Address: GDDJH64X5VEXI7UWZMJA3YUG7ANYHKRRRFHLD2SF5OWEETNFBVYMRXZT");
11
- console.log("Protocol Fee: 20 bps (0.20% Automated On-Chain Routing)");
12
- console.log("--------------------------------------------------------------------------------\n");
13
-
14
- console.log("1. Provisioning Autonomous Agent Sandbox Session...");
15
- const env = provisionSandbox("Claude-Code-Agent-7", "25.00", 20);
16
- console.log(` [OK] Agent Name: ${env.agent.name}`);
17
- console.log(` [OK] Agent Public Key: ${env.agent.publicKey.substring(0, 16)}...`);
18
- console.log(` [OK] Scoped Allowance: $25.00 USDC (TTL: 24 Hours)`);
19
- console.log(` [OK] Owner Public Key: ${env.ownerAddress.substring(0, 16)}...`);
20
-
21
- console.log("\n2. Inspecting Initial Balance...");
22
- let bal = inspectBalance(env, env.allowance.id);
23
- console.log(` [Balance] Remaining: $${bal.remainingUsdc} USDC (${bal.remainingStroops} stroops)`);
24
- console.log(` [Status] Active: ${bal.active} | Expired: ${bal.isExpired}`);
25
-
26
- console.log("\n3. Simulating Autonomous AI Agent LLM Inference Micro-Spend ($0.45 USDC)...");
27
- const { result, feeStroops, netStroops } = executeSandboxSpend(env, "0.45", "inference:gemini-1.5-pro");
28
-
29
- if (result.ok) {
30
- console.log(` [SUCCESS] Transaction Authorized on Soroban Execution Engine!`);
31
- console.log(` [Split] Gross Spend: $0.4500000 USDC`);
32
- console.log(` [Split] Protocol Fee: ${feeStroops} stroops (20 bps -> Treasury ${env.treasuryAddress.substring(0, 10)}...)`);
33
- console.log(` [Split] Net to Provider: ${netStroops} stroops`);
34
- console.log(` [Circuit] Circuit Breaker Status: HEALTHY (Unpaused)`);
35
- } else {
36
- console.error(` [FAILED] Spend rejected: ${result.message}`);
37
- }
38
-
39
- console.log("\n4. Inspecting Updated Post-Spend Balance...");
40
- bal = inspectBalance(env, env.allowance.id);
41
- console.log(` [Balance] Remaining: $${bal.remainingUsdc} USDC (${bal.remainingStroops} stroops)`);
42
- console.log(` [Spent] Accumulated Spent: ${bal.spentStroops} stroops`);
43
-
44
- console.log("\n================================================================================");
45
- console.log("✅ AGENTRAIL DEMO COMPLETED: 100% Deterministic Soroban Settlement Verified!");
46
- console.log("================================================================================");
47
- }
48
-
49
- runDemo().catch((err) => {
50
- console.error("Demo failed:", err);
51
- process.exit(1);
52
- });
@@ -1,228 +0,0 @@
1
- import {
2
- Keypair,
3
- rpc,
4
- Operation,
5
- TransactionBuilder,
6
- Networks,
7
- Address,
8
- xdr,
9
- } from "@stellar/stellar-sdk";
10
- import fs from "fs";
11
- import path from "path";
12
- import crypto from "crypto";
13
-
14
- const RPC_URL = "https://soroban-testnet.stellar.org";
15
- const NETWORK_PASSPHRASE = Networks.TESTNET;
16
- const WASM_PATH = path.resolve(
17
- __dirname,
18
- "../contracts/agentrail/target/wasm32v1-none/release/agentrail_contract.wasm"
19
- );
20
-
21
- async function sleep(ms: number) {
22
- return new Promise((resolve) => setTimeout(resolve, ms));
23
- }
24
-
25
- async function fundWithFriendbot(publicKey: string): Promise<void> {
26
- console.log(`[1/5] Funding deployer address via Friendbot: ${publicKey}...`);
27
- const response = await fetch(`https://friendbot.stellar.org?addr=${publicKey}`);
28
- if (!response.ok) {
29
- const text = await response.text();
30
- console.warn(`Friendbot notice: ${text}`);
31
- } else {
32
- console.log(`[1/5] Deployer funded with 10,000 Testnet XLM!`);
33
- }
34
- }
35
-
36
- async function pollRawTransaction(txHash: string): Promise<any> {
37
- for (let i = 0; i < 30; i++) {
38
- const res = await fetch(RPC_URL, {
39
- method: "POST",
40
- headers: {
41
- "Content-Type": "application/json",
42
- "User-Agent": "Mozilla/5.0",
43
- },
44
- body: JSON.stringify({
45
- jsonrpc: "2.0",
46
- id: 1,
47
- method: "getTransaction",
48
- params: { hash: txHash },
49
- }),
50
- });
51
- const data: any = await res.json();
52
- if (data.result) {
53
- if (data.result.status === "SUCCESS") {
54
- return data.result;
55
- }
56
- if (data.result.status === "FAILED") {
57
- throw new Error(`Transaction failed: ${JSON.stringify(data.result)}`);
58
- }
59
- }
60
- await sleep(2000);
61
- }
62
- throw new Error(`Transaction timed out: ${txHash}`);
63
- }
64
-
65
- async function main() {
66
- console.log("==================================================");
67
- console.log("🚀 AGENTRAIL PROTOCOL — SOROBAN TESTNET DEPLOYER");
68
- console.log("==================================================");
69
-
70
- // 1. Prepare Keypair
71
- const keyPath = path.resolve(__dirname, "../.deployer_key.json");
72
- if (!fs.existsSync(keyPath)) {
73
- throw new Error("Missing deployer key at " + keyPath);
74
- }
75
- const rawKey = JSON.parse(fs.readFileSync(keyPath, "utf-8"));
76
- const deployerKeypair = Keypair.fromSecret(rawKey.secretKey);
77
- console.log(`[1/5] Deployer Address: ${deployerKeypair.publicKey()}`);
78
-
79
- await fundWithFriendbot(deployerKeypair.publicKey());
80
-
81
- const server = new rpc.Server(RPC_URL, {
82
- headers: { "User-Agent": "Mozilla/5.0" },
83
- });
84
-
85
- // 2. Read and Hash WASM
86
- const wasmBuffer = fs.readFileSync(WASM_PATH);
87
- const wasmHashBuffer = crypto.createHash("sha256").update(wasmBuffer).digest();
88
- const wasmHashHex = wasmHashBuffer.toString("hex");
89
- console.log(`[2/5] Contract WASM Size: ${(wasmBuffer.length / 1024).toFixed(2)} KB`);
90
- console.log(`[2/5] Computed WASM SHA256: ${wasmHashHex}`);
91
-
92
- // 3. Upload WASM
93
- console.log(`[3/5] Uploading Contract WASM to Stellar Testnet...`);
94
- let account = await server.getAccount(deployerKeypair.publicKey());
95
-
96
- const uploadOp = Operation.uploadContractWasm({
97
- wasm: wasmBuffer,
98
- });
99
-
100
- const uploadTx = new TransactionBuilder(account, {
101
- fee: "100000",
102
- networkPassphrase: NETWORK_PASSPHRASE,
103
- })
104
- .addOperation(uploadOp)
105
- .setTimeout(30)
106
- .build();
107
-
108
- console.log("Simulating WASM upload transaction...");
109
- const simUpload = await server.simulateTransaction(uploadTx);
110
- if (rpc.Api.isSimulationError(simUpload)) {
111
- console.log(`Simulation note (WASM may already exist): ${simUpload.error}`);
112
- } else {
113
- const preparedUploadTx = rpc.assembleTransaction(uploadTx, simUpload).build();
114
- preparedUploadTx.sign(deployerKeypair);
115
- const uploadSend = await server.sendTransaction(preparedUploadTx);
116
- if (uploadSend.status === "ERROR") {
117
- throw new Error(`Upload tx send error: ${JSON.stringify(uploadSend)}`);
118
- }
119
- console.log(`Sent WASM upload tx (${uploadSend.hash}), waiting for ledger inclusion...`);
120
- await pollRawTransaction(uploadSend.hash);
121
- console.log(`WASM successfully uploaded and anchored in ledger!`);
122
- }
123
-
124
- // 4. Instantiate Contract
125
- console.log(`[4/5] Instantiating Smart Contract Instance on Testnet...`);
126
- account = await server.getAccount(deployerKeypair.publicKey());
127
-
128
- const createOp = Operation.createCustomContract({
129
- address: Address.fromString(deployerKeypair.publicKey()),
130
- wasmHash: wasmHashBuffer,
131
- });
132
-
133
- const createTx = new TransactionBuilder(account, {
134
- fee: "100000",
135
- networkPassphrase: NETWORK_PASSPHRASE,
136
- })
137
- .addOperation(createOp)
138
- .setTimeout(30)
139
- .build();
140
-
141
- console.log("Simulating contract instantiation...");
142
- const simCreate = await server.simulateTransaction(createTx);
143
- if (rpc.Api.isSimulationError(simCreate)) {
144
- throw new Error(`Contract creation simulation failed: ${simCreate.error}`);
145
- }
146
-
147
- const preparedCreateTx = rpc.assembleTransaction(createTx, simCreate).build();
148
- preparedCreateTx.sign(deployerKeypair);
149
-
150
- const createSend = await server.sendTransaction(preparedCreateTx);
151
- if (createSend.status === "ERROR") {
152
- throw new Error(`Failed to send contract creation tx: ${JSON.stringify(createSend)}`);
153
- }
154
- console.log(`Sent contract creation tx (${createSend.hash}), waiting for ledger inclusion...`);
155
- const createResult = await pollRawTransaction(createSend.hash);
156
-
157
- // Derive contractId from simulation result
158
- const contractAddress = Address.fromScVal(simCreate.result.retval);
159
- const contractId = contractAddress.toString();
160
-
161
- console.log("==================================================");
162
- console.log(`🎉 AGENTRAIL CONTRACT DEPLOYED ON STELLAR TESTNET!`);
163
- console.log(`Contract ID: ${contractId}`);
164
- console.log(`Explorer Link: https://stellar.expert/explorer/testnet/contract/${contractId}`);
165
- console.log("==================================================");
166
-
167
- // 5. Initialize Contract with Admin, Mock Token, Treasury & Protocol Fee
168
- const TREASURY_WALLET = "GDDJH64X5VEXI7UWZMJA3YUG7ANYHKRRRFHLD2SF5OWEETNFBVYMRXZT";
169
- const DEFAULT_FEE_BPS = 20; // 0.20% protocol monetization fee
170
-
171
- console.log(`[5/5] Initializing contract with Admin, Token, Treasury (${TREASURY_WALLET}), and ${DEFAULT_FEE_BPS} bps fee...`);
172
- account = await server.getAccount(deployerKeypair.publicKey());
173
-
174
- const contractInstance = new (require("@stellar/stellar-sdk").Contract)(contractId);
175
- const initOp = contractInstance.call(
176
- "initialize",
177
- Address.fromString(deployerKeypair.publicKey()).toScVal(),
178
- Address.fromString(deployerKeypair.publicKey()).toScVal(),
179
- Address.fromString(TREASURY_WALLET).toScVal(),
180
- xdr.ScVal.scvU32(DEFAULT_FEE_BPS)
181
- );
182
-
183
- const initTx = new TransactionBuilder(account, {
184
- fee: "100000",
185
- networkPassphrase: NETWORK_PASSPHRASE,
186
- })
187
- .addOperation(initOp)
188
- .setTimeout(30)
189
- .build();
190
-
191
- const simInit = await server.simulateTransaction(initTx);
192
- if (rpc.Api.isSimulationError(simInit)) {
193
- console.warn(`Init simulation note: ${simInit.error} (proceeding)`);
194
- } else {
195
- const preparedInitTx = rpc.assembleTransaction(initTx, simInit).build();
196
- preparedInitTx.sign(deployerKeypair);
197
- const initSend = await server.sendTransaction(preparedInitTx);
198
- console.log(`Sent initialize tx (${initSend.hash}), waiting for confirmation...`);
199
- await pollRawTransaction(initSend.hash);
200
- console.log(`✅ Contract initialized successfully with active monetization fee!`);
201
- }
202
-
203
- // 6. Save Deployment Metadata
204
- const deploymentInfo = {
205
- network: "Stellar Testnet",
206
- rpcUrl: RPC_URL,
207
- deployerAddress: deployerKeypair.publicKey(),
208
- wasmHash: wasmHashHex,
209
- contractId: contractId,
210
- treasuryAddress: TREASURY_WALLET,
211
- protocolFeeBps: DEFAULT_FEE_BPS,
212
- explorerUrl: `https://stellar.expert/explorer/testnet/contract/${contractId}`,
213
- deployedAt: new Date().toISOString(),
214
- };
215
-
216
- fs.writeFileSync(
217
- path.resolve(__dirname, "../deployment.testnet.json"),
218
- JSON.stringify(deploymentInfo, null, 2)
219
- );
220
- console.log("✅ Wrote deployment.testnet.json successfully!");
221
-
222
- return deploymentInfo;
223
- }
224
-
225
- main().catch((err) => {
226
- console.error("Deployment failed:", err);
227
- process.exit(1);
228
- });
@@ -1,159 +0,0 @@
1
- import fs from "node:fs";
2
- import path from "node:path";
3
-
4
- const FORBIDDEN_PATTERNS = [
5
- {
6
- rule: "NO_EVAL_OR_DYNAMIC_EXECUTION",
7
- severity: "CRITICAL",
8
- regex: /\b(eval\s*\(|new\s+Function\s*\(|setTimeout\s*\(\s*["'`]|setInterval\s*\(\s*["'`])/,
9
- explanation: "Dynamic code evaluation can execute unverified arbitrary bytecode payloads."
10
- },
11
- {
12
- rule: "NO_CHILD_PROCESS_EXEC",
13
- severity: "CRITICAL",
14
- regex: /\b(child_process|execSync|spawnSync|execFile|spawn\s*\(|exec\s*\()/,
15
- explanation: "Executing shell commands or subprocesses is strictly prohibited inside SDK modules."
16
- },
17
- {
18
- rule: "NO_WEBHOOK_OR_C2_EXFILTRATION",
19
- severity: "CRITICAL",
20
- regex: /(discord\.com\/api\/webhooks|api\.telegram\.org|pastebin\.com|ngrok\.io|webhook\.site|pipedream\.net|requestbin)/i,
21
- explanation: "Hardcoded webhook or exfiltration endpoints indicate potential credential/key theft."
22
- },
23
- {
24
- rule: "NO_RAW_IP_ENDPOINT_CALLS",
25
- severity: "CRITICAL",
26
- regex: /https?:\/\/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/,
27
- explanation: "Direct IP network requests bypass domain reputation and indicate command-and-control communication."
28
- },
29
- {
30
- rule: "NO_OBFUSCATED_CHAR_CODE_CHAINS",
31
- severity: "HIGH",
32
- regex: /String\.fromCharCode\s*\((?:\s*\d+\s*,\s*){6,}/,
33
- explanation: "Obfuscated character code arrays are a common evasion technique for malicious payloads."
34
- },
35
- {
36
- rule: "NO_ENV_CREDENTIAL_SCRAPING",
37
- severity: "HIGH",
38
- regex: /process\.env\.(?:PRIVATE_KEY|SECRET_KEY|MNEMONIC|SEED|WALLET_KEY|STELLAR_SECRET)/i,
39
- explanation: "Accessing sensitive raw private key environment variables directly in library modules is restricted.",
40
- allowedFiles: /test/i
41
- },
42
- {
43
- rule: "NO_ARBITRARY_FETCH_IN_CORE",
44
- severity: "HIGH",
45
- regex: /\b(fetch|axios|http\.request|https\.request)\s*\(/,
46
- explanation: "Core cryptographic logic must not perform arbitrary external network requests. Network I/O must be isolated to designated RPC providers.",
47
- allowedFiles: /(rpc|provider|network|test)/i
48
- }
49
- ];
50
-
51
- function scanDirectory(dir, baseDir, violations) {
52
- const entries = fs.readdirSync(dir, { withFileTypes: true });
53
-
54
- for (const entry of entries) {
55
- const fullPath = path.join(dir, entry.name);
56
- const relPath = path.relative(baseDir, fullPath).replace(/\\/g, "/");
57
-
58
- if (entry.isDirectory()) {
59
- if (entry.name === "node_modules" || entry.name === "dist" || entry.name === ".git") {
60
- continue;
61
- }
62
- scanDirectory(fullPath, baseDir, violations);
63
- } else if (entry.isFile()) {
64
- if (relPath.endsWith("security-audit.test.ts") || relPath.endsWith("security-audit.mjs")) {
65
- continue;
66
- }
67
- if (/\.(ts|js|mjs|cjs)$/.test(entry.name)) {
68
- scanFile(fullPath, relPath, violations);
69
- }
70
- }
71
- }
72
- }
73
-
74
- function scanFile(filePath, relPath, violations) {
75
- const content = fs.readFileSync(filePath, "utf-8");
76
- const lines = content.split(/\r?\n/);
77
-
78
- for (let i = 0; i < lines.length; i++) {
79
- const line = lines[i];
80
- const lineNum = i + 1;
81
-
82
- for (const pattern of FORBIDDEN_PATTERNS) {
83
- if (pattern.allowedFiles && pattern.allowedFiles.test(relPath)) {
84
- continue;
85
- }
86
-
87
- if (pattern.regex.test(line)) {
88
- if (/^\s*\/\//.test(line) && !line.includes("http")) {
89
- continue;
90
- }
91
-
92
- violations.push({
93
- file: relPath,
94
- line: lineNum,
95
- rule: pattern.rule,
96
- severity: pattern.severity,
97
- snippet: line.trim().slice(0, 120),
98
- explanation: pattern.explanation
99
- });
100
- }
101
- }
102
- }
103
- }
104
-
105
- export function runSecurityAudit(rootDir) {
106
- const violations = [];
107
- const srcDir = path.join(rootDir, "src");
108
- const testsDir = path.join(rootDir, "tests");
109
-
110
- if (fs.existsSync(srcDir)) {
111
- scanDirectory(srcDir, rootDir, violations);
112
- }
113
- if (fs.existsSync(testsDir)) {
114
- scanDirectory(testsDir, rootDir, violations);
115
- }
116
-
117
- const pkgPath = path.join(rootDir, "package.json");
118
- if (fs.existsSync(pkgPath)) {
119
- const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
120
- const scripts = pkg.scripts || {};
121
- const dangerousScripts = ["postinstall", "preinstall", "install"];
122
-
123
- for (const s of dangerousScripts) {
124
- if (scripts[s] && !scripts[s].includes("npm-run-all")) {
125
- violations.push({
126
- file: "package.json",
127
- line: 1,
128
- rule: "NO_DANGEROUS_LIFECYCLE_SCRIPTS",
129
- severity: "CRITICAL",
130
- snippet: `\"${s}\": \"${scripts[s]}\"`,
131
- explanation: `Automated lifecycle script '${s}' detected. Attackers use postinstall scripts to execute malware during npm install.`
132
- });
133
- }
134
- }
135
- }
136
-
137
- return violations;
138
- }
139
-
140
- // CLI Execution
141
- if (import.meta.url === `file://${process.argv[1].replace(/\\/g, "/")}` || process.argv[1].endsWith("security-audit.mjs")) {
142
- const root = process.cwd();
143
- console.log("🛡️ Running AgentRail Autonomous Anti-Drainer Security Audit...");
144
- const violations = runSecurityAudit(root);
145
-
146
- if (violations.length === 0) {
147
- console.log("✅ Zero security violations detected. Codebase is clean of drainer & exfiltration patterns.");
148
- process.exit(0);
149
- } else {
150
- console.error(`\n❌ [SECURITY REJECT] Detected ${violations.length} high-risk code pattern(s):\n`);
151
- for (const v of violations) {
152
- console.error(` [${v.severity}] ${v.rule} at ${v.file}:${v.line}`);
153
- console.error(` Explanation: ${v.explanation}`);
154
- console.error(` Code Snippet: ${v.snippet}\n`);
155
- }
156
- console.error("🛑 Pull Request BLOCKED by CI Security Guard. Remove the prohibited code to proceed.");
157
- process.exit(1);
158
- }
159
- }
@@ -1,127 +0,0 @@
1
- import { AgentRailClient } from "../sdk/agent-client.js";
2
- import { ScopedAllowance, SpendResult } from "../types.js";
3
- import { usdcToStroops, stroopsToUsdc } from "../lib/micro-stream.js";
4
-
5
- export interface SandboxAgent {
6
- id: string;
7
- name: string;
8
- publicKey: string;
9
- role: string;
10
- }
11
-
12
- export interface SandboxEnvironment {
13
- client: AgentRailClient;
14
- ownerAddress: string;
15
- treasuryAddress: string;
16
- agent: SandboxAgent;
17
- allowance: ScopedAllowance;
18
- protocolFeeBps: number;
19
- }
20
-
21
- export interface BalanceInspection {
22
- allowanceId: string;
23
- totalLimitStroops: string;
24
- spentStroops: string;
25
- remainingStroops: string;
26
- remainingUsdc: string;
27
- active: boolean;
28
- isExpired: boolean;
29
- }
30
-
31
- /**
32
- * Provision a sandboxed environment for autonomous AI agent micro-spend simulation.
33
- */
34
- export function provisionSandbox(
35
- agentName = "Gemini-Soroban-Worker-01",
36
- budgetUsdc = "50.00",
37
- feeBps = 20
38
- ): SandboxEnvironment {
39
- const client = new AgentRailClient();
40
- const ownerAddress = "GDDJH64X5VEXI7UWZMJA3YUG7ANYHKRRRFHLD2SF5OWEETNFBVYMRXZT";
41
- const treasuryAddress = "GDDJH64X5VEXI7UWZMJA3YUG7ANYHKRRRFHLD2SF5OWEETNFBVYMRXZT";
42
- const agentKey = "GAUTON0M0USAGNT77777777777777777777777777777777777777777";
43
- const now = Math.floor(Date.now() / 1000);
44
-
45
- const agent: SandboxAgent = {
46
- id: `agent_${Date.now()}`,
47
- name: agentName,
48
- publicKey: agentKey,
49
- role: "Autonomous Inference & Data Processing",
50
- };
51
-
52
- const limitStroops = usdcToStroops(budgetUsdc);
53
- const allowance: ScopedAllowance = {
54
- id: `allowance_${agent.id}`,
55
- ownerPublicKey: ownerAddress,
56
- agentPublicKey: agent.publicKey,
57
- maxStroops: limitStroops,
58
- spentStroops: 0n,
59
- validFrom: now - 60,
60
- validUntil: now + 86400, // 24h
61
- active: true,
62
- protocolFeeBps: feeBps,
63
- treasuryPublicKey: treasuryAddress,
64
- };
65
-
66
- client.registerAllowance(allowance);
67
-
68
- return {
69
- client,
70
- ownerAddress,
71
- treasuryAddress,
72
- agent,
73
- allowance,
74
- protocolFeeBps: feeBps,
75
- };
76
- }
77
-
78
- /**
79
- * Inspect live allowance balance and capacity for an agent.
80
- */
81
- export function inspectBalance(
82
- env: SandboxEnvironment,
83
- allowanceId: string,
84
- currentTimeSec: number = Math.floor(Date.now() / 1000)
85
- ): BalanceInspection {
86
- const allowance = (env.client as any).allowances.get(allowanceId) as ScopedAllowance | undefined;
87
- if (!allowance) {
88
- throw new Error(`Allowance ${allowanceId} does not exist in sandbox.`);
89
- }
90
-
91
- const remaining = allowance.maxStroops - allowance.spentStroops;
92
- const isExpired = currentTimeSec > allowance.validUntil;
93
-
94
- return {
95
- allowanceId: allowance.id,
96
- totalLimitStroops: allowance.maxStroops.toString(),
97
- spentStroops: allowance.spentStroops.toString(),
98
- remainingStroops: remaining.toString(),
99
- remainingUsdc: stroopsToUsdc(remaining),
100
- active: allowance.active && !isExpired,
101
- isExpired,
102
- };
103
- }
104
-
105
- /**
106
- * Execute an automated micro-spend within the sandbox.
107
- */
108
- export function executeSandboxSpend(
109
- env: SandboxEnvironment,
110
- amountUsdc: string,
111
- memo = "inference:gemini-pro-1.5"
112
- ): { result: SpendResult; feeStroops: bigint; netStroops: bigint } {
113
- const amountStroops = usdcToStroops(amountUsdc);
114
- const feeStroops = (amountStroops * BigInt(env.protocolFeeBps)) / 10000n;
115
- const netStroops = amountStroops - feeStroops;
116
-
117
- const result = env.client.spend({
118
- allowanceId: env.allowance.id,
119
- agentPublicKey: env.agent.publicKey,
120
- destination: "GDEST1NAT10NPR0V1DER9999999999999999999999999999999999999",
121
- amountStroops,
122
- timestamp: Math.floor(Date.now() / 1000),
123
- memo,
124
- });
125
-
126
- return { result, feeStroops, netStroops };
127
- }
package/src/index.ts DELETED
@@ -1,11 +0,0 @@
1
- /**
2
- * AgentRail Protocol Entrypoint.
3
- */
4
-
5
- export * from "./types.js";
6
- export * from "./lib/scoped-allowance.js";
7
- export * from "./lib/micro-stream.js";
8
- export * from "./lib/ttl-keeper.js";
9
- export * from "./lib/proof-of-task.js";
10
- export * from "./sdk/agent-client.js";
11
- export * from "./cli/sandbox.js";
@@ -1,52 +0,0 @@
1
- /**
2
- * Real-time micro-payment streaming calculations for LLM inference, API usage, and continuous work.
3
- */
4
-
5
- export interface TokenPricingRate {
6
- /** Cost in stroops per 1,000 prompt tokens (1 USDC = 10,000,000 stroops). */
7
- promptStroopsPer1k: bigint;
8
- /** Cost in stroops per 1,000 completion tokens. */
9
- completionStroopsPer1k: bigint;
10
- }
11
-
12
- /**
13
- * Calculate the exact stroop amount for given token usage.
14
- */
15
- export function calculateTokenCost(
16
- promptTokens: number,
17
- completionTokens: number,
18
- rates: TokenPricingRate
19
- ): bigint {
20
- if (promptTokens < 0 || completionTokens < 0) {
21
- throw new Error("Token counts must be non-negative");
22
- }
23
-
24
- const promptCost = (BigInt(promptTokens) * rates.promptStroopsPer1k) / 1000n;
25
- const completionCost = (BigInt(completionTokens) * rates.completionStroopsPer1k) / 1000n;
26
-
27
- return promptCost + completionCost;
28
- }
29
-
30
- /**
31
- * Convert human-readable decimal USDC amount string to integer stroops (7 decimals).
32
- */
33
- export function usdcToStroops(usdcAmount: string): bigint {
34
- const parts = usdcAmount.trim().split(".");
35
- if (parts.length > 2) throw new Error("Invalid decimal format");
36
-
37
- const whole = BigInt(parts[0] || "0");
38
- const fractionStr = (parts[1] || "").slice(0, 7).padEnd(7, "0");
39
- const fraction = BigInt(fractionStr);
40
-
41
- return whole * 10_000_000n + fraction;
42
- }
43
-
44
- /**
45
- * Convert stroops integer to human-readable 7-decimal USDC string.
46
- */
47
- export function stroopsToUsdc(stroops: bigint): string {
48
- if (stroops < 0n) throw new Error("Stroops must be non-negative");
49
- const whole = stroops / 10_000_000n;
50
- const fraction = stroops % 10_000_000n;
51
- return `${whole}.${fraction.toString().padStart(7, "0")}`;
52
- }
@@ -1,39 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import { EscrowTask, ProofOfTaskSubmission } from "../types.js";
3
-
4
- /**
5
- * Compute the canonical SHA-256 commitment hash for a task output and nonce.
6
- */
7
- export function computeTaskCommitment(outputPayload: string, nonce: string): string {
8
- return createHash("sha256")
9
- .update(`${outputPayload}:${nonce}`, "utf8")
10
- .digest("hex");
11
- }
12
-
13
- /**
14
- * Verify an autonomous AI agent's submitted proof against the on-chain task escrow.
15
- */
16
- export function verifyTaskProof(
17
- task: EscrowTask,
18
- submission: ProofOfTaskSubmission,
19
- currentTimestamp: number
20
- ): { ok: boolean; reason?: string } {
21
- if (task.status !== "pending") {
22
- return { ok: false, reason: `Task is not pending (status: ${task.status})` };
23
- }
24
-
25
- if (submission.agentWorkerPublicKey !== task.agentWorkerPublicKey) {
26
- return { ok: false, reason: "Proof submitter does not match designated worker key" };
27
- }
28
-
29
- if (currentTimestamp > task.expiresAt) {
30
- return { ok: false, reason: "Task escrow deadline has expired; refund available" };
31
- }
32
-
33
- const computedHash = computeTaskCommitment(submission.outputPayload, submission.nonce);
34
- if (computedHash !== task.taskCommitmentHash) {
35
- return { ok: false, reason: "Cryptographic commitment hash mismatch" };
36
- }
37
-
38
- return { ok: true };
39
- }