Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(agent-runtime): ship the agent engine as @three-ws/agent-runtime

nirholas4f04af21bade
diff --git a/package-lock.json b/package-lock.json
index ce8201088..dcc20d4da 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -308,6 +308,67 @@
"node": ">=17"
}
},
+ "agent-payments-sdk/node_modules/@ethereum-attestation-service/eas-sdk": {
+ "version": "0.29.1",
+ "resolved": "https://registry.npmjs.org/@ethereum-attestation-service/eas-sdk/-/eas-sdk-0.29.1.tgz",
+ "integrity": "sha512-UjCpRHOCq+KqMQxCei2+kEa4df8Xnemx12d29kvwzxbVJQ2jPBKyvf+vH2DNbk9CVQ6iIabIqc3OvGcom5751g==",
+ "license": "MIT",
+ "dependencies": {
+ "@ethereum-attestation-service/eas-contracts": "^0.27.1",
+ "ethers": "^5.7.2",
+ "js-base64": "^3.7.5",
+ "multiformats": "9.9.0",
+ "pako": "^2.1.0"
+ }
+ },
+ "agent-payments-sdk/node_modules/@ethereum-attestation-service/eas-sdk/node_modules/ethers": {
+ "version": "5.8.0",
+ "resolved": "https://registry.npmjs.org/ethers/-/ethers-5.8.0.tgz",
+ "integrity": "sha512-DUq+7fHrCg1aPDFCHx6UIPb3nmt2XMpM7Y/g2gLhsl3lIBqeAfOJIl1qEvRf2uq3BiKxmh6Fh5pfp2ieyek7Kg==",
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2"
+ },
+ {
+ "type": "individual",
+ "url": "https://www.buymeacoffee.com/ricmoo"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@ethersproject/abi": "5.8.0",
+ "@ethersproject/abstract-provider": "5.8.0",
+ "@ethersproject/abstract-signer": "5.8.0",
+ "@ethersproject/address": "5.8.0",
+ "@ethersproject/base64": "5.8.0",
+ "@ethersproject/basex": "5.8.0",
+ "@ethersproject/bignumber": "5.8.0",
+ "@ethersproject/bytes": "5.8.0",
+ "@ethersproject/constants": "5.8.0",
+ "@ethersproject/contracts": "5.8.0",
+ "@ethersproject/hash": "5.8.0",
+ "@ethersproject/hdnode": "5.8.0",
+ "@ethersproject/json-wallets": "5.8.0",
+ "@ethersproject/keccak256": "5.8.0",
+ "@ethersproject/logger": "5.8.0",
+ "@ethersproject/networks": "5.8.0",
+ "@ethersproject/pbkdf2": "5.8.0",
+ "@ethersproject/properties": "5.8.0",
+ "@ethersproject/providers": "5.8.0",
+ "@ethersproject/random": "5.8.0",
+ "@ethersproject/rlp": "5.8.0",
+ "@ethersproject/sha2": "5.8.0",
+ "@ethersproject/signing-key": "5.8.0",
+ "@ethersproject/solidity": "5.8.0",
+ "@ethersproject/strings": "5.8.0",
+ "@ethersproject/transactions": "5.8.0",
+ "@ethersproject/units": "5.8.0",
+ "@ethersproject/wallet": "5.8.0",
+ "@ethersproject/web": "5.8.0",
+ "@ethersproject/wordlists": "5.8.0"
+ }
+ },
"agent-payments-sdk/node_modules/@types/node": {
"version": "22.19.17",
"dev": true,
@@ -330,30 +391,10 @@
"base-x": "^3.0.2"
}
},
- "agent-payments-sdk/node_modules/dotenv": {
- "version": "16.6.1",
- "license": "BSD-2-Clause",
- "engines": {
- "node": ">=12"
- },
- "funding": {
- "url": "https://dotenvx.com"
- }
- },
"agent-payments-sdk/node_modules/eventemitter3": {
"version": "4.0.7",
"license": "MIT"
},
- "agent-payments-sdk/node_modules/livepeer": {
- "version": "3.2.4",
- "license": "MIT",
- "dependencies": {
- "dotenv": "^16.4.5"
- },
- "peerDependencies": {
- "zod": ">= 3"
- }
- },
"agent-payments-sdk/node_modules/superstruct": {
"version": "0.15.5",
"license": "MIT"
@@ -512,11 +553,65 @@
"borsh": "^0.7.0"
}
},
- "character-studio/node_modules/@pump-fun/pump-sdk": {
- "version": "1.1.0",
+ "character-studio/node_modules/@ethereum-attestation-service/eas-sdk": {
+ "version": "0.29.1",
+ "resolved": "https://registry.npmjs.org/@ethereum-attestation-service/eas-sdk/-/eas-sdk-0.29.1.tgz",
+ "integrity": "sha512-UjCpRHOCq+KqMQxCei2+kEa4df8Xnemx12d29kvwzxbVJQ2jPBKyvf+vH2DNbk9CVQ6iIabIqc3OvGcom5751g==",
"license": "MIT",
"dependencies": {
- "undici-types": "^6.20.0"
+ "@ethereum-attestation-service/eas-contracts": "^0.27.1",
+ "ethers": "^5.7.2",
+ "js-base64": "^3.7.5",
+ "multiformats": "9.9.0",
+ "pako": "^2.1.0"
+ }
+ },
+ "character-studio/node_modules/@ethereum-attestation-service/eas-sdk/node_modules/ethers": {
+ "version": "5.8.0",
+ "resolved": "https://registry.npmjs.org/ethers/-/ethers-5.8.0.tgz",
+ "integrity": "sha512-DUq+7fHrCg1aPDFCHx6UIPb3nmt2XMpM7Y/g2gLhsl3lIBqeAfOJIl1qEvRf2uq3BiKxmh6Fh5pfp2ieyek7Kg==",
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2"
+ },
+ {
+ "type": "individual",
+ "url": "https://www.buymeacoffee.com/ricmoo"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@ethersproject/abi": "5.8.0",
+ "@ethersproject/abstract-provider": "5.8.0",
+ "@ethersproject/abstract-signer": "5.8.0",
+ "@ethersproject/address": "5.8.0",
+ "@ethersproject/base64": "5.8.0",
+ "@ethersproject/basex": "5.8.0",
+ "@ethersproject/bignumber": "5.8.0",
+ "@ethersproject/bytes": "5.8.0",
+ "@ethersproject/constants": "5.8.0",
+ "@ethersproject/contracts": "5.8.0",
+ "@ethersproject/hash": "5.8.0",
+ "@ethersproject/hdnode": "5.8.0",
+ "@ethersproject/json-wallets": "5.8.0",
+ "@ethersproject/keccak256": "5.8.0",
+ "@ethersproject/logger": "5.8.0",
+ "@ethersproject/networks": "5.8.0",
+ "@ethersproject/pbkdf2": "5.8.0",
+ "@ethersproject/properties": "5.8.0",
+ "@ethersproject/providers": "5.8.0",
+ "@ethersproject/random": "5.8.0",
+ "@ethersproject/rlp": "5.8.0",
+ "@ethersproject/sha2": "5.8.0",
+ "@ethersproject/signing-key": "5.8.0",
+ "@ethersproject/solidity": "5.8.0",
+ "@ethersproject/strings": "5.8.0",
+ "@ethersproject/transactions": "5.8.0",
+ "@ethersproject/units": "5.8.0",
+ "@ethersproject/wallet": "5.8.0",
+ "@ethersproject/web": "5.8.0",
+ "@ethersproject/wordlists": "5.8.0"
}
},
"character-studio/node_modules/@solana/pay": {
@@ -558,16 +653,6 @@
"node": "^20.19.0 || ^22.12.0 || >=24.0.0"
}
},
- "character-studio/node_modules/dotenv": {
- "version": "16.6.1",
- "license": "BSD-2-Clause",
- "engines": {
- "node": ">=12"
- },
- "funding": {
- "url": "https://dotenvx.com"
- }
- },
"character-studio/node_modules/jsdom": {
"version": "29.1.1",
"dev": true,
@@ -607,16 +692,6 @@
}
}
},
- "character-studio/node_modules/livepeer": {
- "version": "3.2.4",
- "license": "MIT",
- "dependencies": {
- "dotenv": "^16.4.5"
- },
- "peerDependencies": {
- "zod": ">= 3"
- }
- },
"character-studio/node_modules/three-mesh-bvh": {
"version": "0.9.10",
"license": "MIT",
@@ -635,23 +710,6 @@
"node": ">=20"
}
},
- "character-studio/node_modules/undici-types": {
- "version": "6.26.0",
- "license": "MIT"
- },
- "character-studio/node_modules/vite-plugin-node-polyfills": {
- "version": "0.2.0",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@esbuild-plugins/node-globals-polyfill": "^0.1.1",
- "@esbuild-plugins/node-modules-polyfill": "^0.1.4",
- "rollup-plugin-node-polyfills": "^0.2.1"
- },
- "funding": {
- "url": "https://github.com/sponsors/voracious"
- }
- },
"character-studio/node_modules/webidl-conversions": {
"version": "8.0.1",
"dev": true,
@@ -756,6 +814,67 @@
"borsh": "^0.7.0"
}
},
+ "mcp-server/node_modules/@ethereum-attestation-service/eas-sdk": {
+ "version": "0.29.1",
+ "resolved": "https://registry.npmjs.org/@ethereum-attestation-service/eas-sdk/-/eas-sdk-0.29.1.tgz",
+ "integrity": "sha512-UjCpRHOCq+KqMQxCei2+kEa4df8Xnemx12d29kvwzxbVJQ2jPBKyvf+vH2DNbk9CVQ6iIabIqc3OvGcom5751g==",
+ "license": "MIT",
+ "dependencies": {
+ "@ethereum-attestation-service/eas-contracts": "^0.27.1",
+ "ethers": "^5.7.2",
+ "js-base64": "^3.7.5",
+ "multiformats": "9.9.0",
+ "pako": "^2.1.0"
+ }
+ },
+ "mcp-server/node_modules/@ethereum-attestation-service/eas-sdk/node_modules/ethers": {
+ "version": "5.8.0",
+ "resolved": "https://registry.npmjs.org/ethers/-/ethers-5.8.0.tgz",
+ "integrity": "sha512-DUq+7fHrCg1aPDFCHx6UIPb3nmt2XMpM7Y/g2gLhsl3lIBqeAfOJIl1qEvRf2uq3BiKxmh6Fh5pfp2ieyek7Kg==",
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2"
+ },
+ {
+ "type": "individual",
+ "url": "https://www.buymeacoffee.com/ricmoo"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@ethersproject/abi": "5.8.0",
+ "@ethersproject/abstract-provider": "5.8.0",
+ "@ethersproject/abstract-signer": "5.8.0",
+ "@ethersproject/address": "5.8.0",
+ "@ethersproject/base64": "5.8.0",
+ "@ethersproject/basex": "5.8.0",
+ "@ethersproject/bignumber": "5.8.0",
+ "@ethersproject/bytes": "5.8.0",
+ "@ethersproject/constants": "5.8.0",
+ "@ethersproject/contracts": "5.8.0",
+ "@ethersproject/hash": "5.8.0",
+ "@ethersproject/hdnode": "5.8.0",
+ "@ethersproject/json-wallets": "5.8.0",
+ "@ethersproject/keccak256": "5.8.0",
+ "@ethersproject/logger": "5.8.0",
+ "@ethersproject/networks": "5.8.0",
+ "@ethersproject/pbkdf2": "5.8.0",
+ "@ethersproject/properties": "5.8.0",
+ "@ethersproject/providers": "5.8.0",
+ "@ethersproject/random": "5.8.0",
+ "@ethersproject/rlp": "5.8.0",
+ "@ethersproject/sha2": "5.8.0",
+ "@ethersproject/signing-key": "5.8.0",
+ "@ethersproject/solidity": "5.8.0",
+ "@ethersproject/strings": "5.8.0",
+ "@ethersproject/transactions": "5.8.0",
+ "@ethersproject/units": "5.8.0",
+ "@ethersproject/wallet": "5.8.0",
+ "@ethersproject/web": "5.8.0",
+ "@ethersproject/wordlists": "5.8.0"
+ }
+ },
"multiplayer": {
"name": "@three-ws/multiplayer",
"version": "0.1.0",
@@ -867,11 +986,65 @@
"@colyseus/core": "0.16.x"
}
},
- "multiplayer/node_modules/@pump-fun/pump-sdk": {
- "version": "1.1.0",
+ "multiplayer/node_modules/@ethereum-attestation-service/eas-sdk": {
+ "version": "0.29.1",
+ "resolved": "https://registry.npmjs.org/@ethereum-attestation-service/eas-sdk/-/eas-sdk-0.29.1.tgz",
+ "integrity": "sha512-UjCpRHOCq+KqMQxCei2+kEa4df8Xnemx12d29kvwzxbVJQ2jPBKyvf+vH2DNbk9CVQ6iIabIqc3OvGcom5751g==",
"license": "MIT",
"dependencies": {
- "undici-types": "^6.20.0"
+ "@ethereum-attestation-service/eas-contracts": "^0.27.1",
+ "ethers": "^5.7.2",
+ "js-base64": "^3.7.5",
+ "multiformats": "9.9.0",
+ "pako": "^2.1.0"
+ }
+ },
+ "multiplayer/node_modules/@ethereum-attestation-service/eas-sdk/node_modules/ethers": {
+ "version": "5.8.0",
+ "resolved": "https://registry.npmjs.org/ethers/-/ethers-5.8.0.tgz",
+ "integrity": "sha512-DUq+7fHrCg1aPDFCHx6UIPb3nmt2XMpM7Y/g2gLhsl3lIBqeAfOJIl1qEvRf2uq3BiKxmh6Fh5pfp2ieyek7Kg==",
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2"
+ },
+ {
+ "type": "individual",
+ "url": "https://www.buymeacoffee.com/ricmoo"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@ethersproject/abi": "5.8.0",
+ "@ethersproject/abstract-provider": "5.8.0",
+ "@ethersproject/abstract-signer": "5.8.0",
+ "@ethersproject/address": "5.8.0",
+ "@ethersproject/base64": "5.8.0",
+ "@ethersproject/basex": "5.8.0",
+ "@ethersproject/bignumber": "5.8.0",
+ "@ethersproject/bytes": "5.8.0",
+ "@ethersproject/constants": "5.8.0",
+ "@ethersproject/contracts": "5.8.0",
+ "@ethersproject/hash": "5.8.0",
+ "@ethersproject/hdnode": "5.8.0",
+ "@ethersproject/json-wallets": "5.8.0",
+ "@ethersproject/keccak256": "5.8.0",
+ "@ethersproject/logger": "5.8.0",
+ "@ethersproject/networks": "5.8.0",
+ "@ethersproject/pbkdf2": "5.8.0",
+ "@ethersproject/properties": "5.8.0",
+ "@ethersproject/providers": "5.8.0",
+ "@ethersproject/random": "5.8.0",
+ "@ethersproject/rlp": "5.8.0",
+ "@ethersproject/sha2": "5.8.0",
+ "@ethersproject/signing-key": "5.8.0",
+ "@ethersproject/solidity": "5.8.0",
+ "@ethersproject/strings": "5.8.0",
+ "@ethersproject/transactions": "5.8.0",
+ "@ethersproject/units": "5.8.0",
+ "@ethersproject/wallet": "5.8.0",
+ "@ethersproject/web": "5.8.0",
+ "@ethersproject/wordlists": "5.8.0"
}
},
"multiplayer/node_modules/@solana/pay": {
@@ -908,26 +1081,6 @@
"@types/node": "*"
}
},
- "multiplayer/node_modules/dotenv": {
- "version": "16.6.1",
- "license": "BSD-2-Clause",
- "engines": {
- "node": ">=12"
- },
- "funding": {
- "url": "https://dotenvx.com"
- }
- },
- "multiplayer/node_modules/livepeer": {
- "version": "3.2.4",
- "license": "MIT",
- "dependencies": {
- "dotenv": "^16.4.5"
- },
- "peerDependencies": {
- "zod": ">= 3"
- }
- },
"multiplayer/node_modules/nanoid": {
"version": "2.1.11",
"license": "MIT"
@@ -936,10 +1089,6 @@
"version": "1.3.7",
"license": "MIT"
},
- "multiplayer/node_modules/undici-types": {
- "version": "6.26.0",
- "license": "MIT"
- },
"node_modules/@0no-co/graphql.web": {
"version": "1.2.0",
"license": "MIT",
@@ -3880,6 +4029,12 @@
"version": "0.1.0",
"license": "Apache-2.0"
},
+ "node_modules/@chainsafe/as-sha256": {
+ "version": "0.3.1",
+ "resolved": "https://registry.npmjs.org/@chainsafe/as-sha256/-/as-sha256-0.3.1.tgz",
+ "integrity": "sha512-hldFFYuf49ed7DAakWVXSJODuq3pzJEguD8tQ7h+sGkM18vja+OFoJI9krnGmgzyuZC2ETX0NOIcCTy31v2Mtg==",
+ "license": "Apache-2.0"
+ },
"node_modules/@chainsafe/is-ip": {
"version": "2.1.0",
"license": "MIT"
@@ -3945,6 +4100,26 @@
"@chainsafe/is-ip": "^2.0.1"
}
},
+ "node_modules/@chainsafe/persistent-merkle-tree": {
+ "version": "0.4.2",
+ "resolved": "https://registry.npmjs.org/@chainsafe/persistent-merkle-tree/-/persistent-merkle-tree-0.4.2.tgz",
+ "integrity": "sha512-lLO3ihKPngXLTus/L7WHKaw9PnNJWizlOF1H9NNzHP6Xvh82vzg9F2bzkXhYIFshMZ2gTCEz8tq6STe7r5NDfQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@chainsafe/as-sha256": "^0.3.1"
+ }
+ },
+ "node_modules/@chainsafe/ssz": {
+ "version": "0.9.4",
+ "resolved": "https://registry.npmjs.org/@chainsafe/ssz/-/ssz-0.9.4.tgz",
+ "integrity": "sha512-77Qtg2N1ayqs4Bg/wvnWfg5Bta7iy7IRh8XqXh7oNMeP2HBbBwx8m6yTpA8p0EHItWPEBkgZd5S5/LSlp3GXuQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@chainsafe/as-sha256": "^0.3.1",
+ "@chainsafe/persistent-merkle-tree": "^0.4.2",
+ "case": "^1.6.3"
+ }
+ },
"node_modules/@chenglou/pretext": {
"version": "0.0.7",
"license": "MIT"
@@ -5602,26 +5777,6 @@
"version": "0.4.0",
"license": "MIT"
},
- "node_modules/@esbuild-plugins/node-globals-polyfill": {
- "version": "0.1.1",
- "dev": true,
- "license": "ISC",
- "peerDependencies": {
- "esbuild": "*"
- }
- },
- "node_modules/@esbuild-plugins/node-modules-polyfill": {
- "version": "0.1.4",
- "dev": true,
- "license": "ISC",
- "dependencies": {
- "escape-string-regexp": "^4.0.0",
- "rollup-plugin-node-polyfills": "^0.2.1"
- },
- "peerDependencies": {
- "esbuild": "*"
- }
- },
"node_modules/@esbuild/aix-ppc64": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz",
@@ -6135,6 +6290,18 @@
"node": "^20.19.0 || ^22.13.0 || >=24"
}
},
+ "node_modules/@ethereum-attestation-service/eas-contracts": {
+ "version": "0.27.1",
+ "resolved": "https://registry.npmjs.org/@ethereum-attestation-service/eas-contracts/-/eas-contracts-0.27.1.tgz",
+ "integrity": "sha512-ly1N/jLbXJjACDL7dnMSkzViBxxuVc+aMZ3EB1kpFxeMWrXkb7nN6w9gxGTH+m3gJztaKvyMsyr/13pA0OYq6Q==",
+ "license": "MIT",
+ "dependencies": {
+ "@typechain/ethers-v5": "^10.2.0",
+ "@typechain/hardhat": "^6.1.5",
+ "hardhat": "2.13.1",
+ "typechain": "^8.1.1"
+ }
+ },
"node_modules/@ethereum-attestation-service/eas-sdk": {
"version": "2.9.1",
"license": "MIT",
@@ -6818,7 +6985,6 @@
}
],
"license": "MIT",
- "optional": true,
"dependencies": {
"@ethersproject/bytes": "^5.8.0",
"@ethersproject/properties": "^5.8.0"
@@ -6877,6 +7043,34 @@
"@ethersproject/bignumber": "^5.8.0"
}
},
+ "node_modules/@ethersproject/contracts": {
+ "version": "5.8.0",
+ "resolved": "https://registry.npmjs.org/@ethersproject/contracts/-/contracts-5.8.0.tgz",
+ "integrity": "sha512-0eFjGz9GtuAi6MZwhb4uvUM216F38xiuR0yYCjKJpNfSEy4HUM8hvqqBj9Jmm0IUz8l0xKEhWwLIhPgxNY0yvQ==",
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2"
+ },
+ {
+ "type": "individual",
+ "url": "https://www.buymeacoffee.com/ricmoo"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@ethersproject/abi": "^5.8.0",
+ "@ethersproject/abstract-provider": "^5.8.0",
+ "@ethersproject/abstract-signer": "^5.8.0",
+ "@ethersproject/address": "^5.8.0",
+ "@ethersproject/bignumber": "^5.8.0",
+ "@ethersproject/bytes": "^5.8.0",
+ "@ethersproject/constants": "^5.8.0",
+ "@ethersproject/logger": "^5.8.0",
+ "@ethersproject/properties": "^5.8.0",
+ "@ethersproject/transactions": "^5.8.0"
+ }
+ },
"node_modules/@ethersproject/hash": {
"version": "5.8.0",
"funding": [
@@ -6902,6 +7096,67 @@
"@ethersproject/strings": "^5.8.0"
}
},
+ "node_modules/@ethersproject/hdnode": {
+ "version": "5.8.0",
+ "resolved": "https://registry.npmjs.org/@ethersproject/hdnode/-/hdnode-5.8.0.tgz",
+ "integrity": "sha512-4bK1VF6E83/3/Im0ERnnUeWOY3P1BZml4ZD3wcH8Ys0/d1h1xaFt6Zc+Dh9zXf9TapGro0T4wvO71UTCp3/uoA==",
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2"
+ },
+ {
+ "type": "individual",
+ "url": "https://www.buymeacoffee.com/ricmoo"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@ethersproject/abstract-signer": "^5.8.0",
+ "@ethersproject/basex": "^5.8.0",
+ "@ethersproject/bignumber": "^5.8.0",
+ "@ethersproject/bytes": "^5.8.0",
+ "@ethersproject/logger": "^5.8.0",
+ "@ethersproject/pbkdf2": "^5.8.0",
+ "@ethersproject/properties": "^5.8.0",
+ "@ethersproject/sha2": "^5.8.0",
+ "@ethersproject/signing-key": "^5.8.0",
+ "@ethersproject/strings": "^5.8.0",
+ "@ethersproject/transactions": "^5.8.0",
+ "@ethersproject/wordlists": "^5.8.0"
+ }
+ },
+ "node_modules/@ethersproject/json-wallets": {
+ "version": "5.8.0",
+ "resolved": "https://registry.npmjs.org/@ethersproject/json-wallets/-/json-wallets-5.8.0.tgz",
+ "integrity": "sha512-HxblNck8FVUtNxS3VTEYJAcwiKYsBIF77W15HufqlBF9gGfhmYOJtYZp8fSDZtn9y5EaXTE87zDwzxRoTFk11w==",
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2"
+ },
+ {
+ "type": "individual",
+ "url": "https://www.buymeacoffee.com/ricmoo"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@ethersproject/abstract-signer": "^5.8.0",
+ "@ethersproject/address": "^5.8.0",
+ "@ethersproject/bytes": "^5.8.0",
+ "@ethersproject/hdnode": "^5.8.0",
+ "@ethersproject/keccak256": "^5.8.0",
+ "@ethersproject/logger": "^5.8.0",
+ "@ethersproject/pbkdf2": "^5.8.0",
+ "@ethersproject/properties": "^5.8.0",
+ "@ethersproject/random": "^5.8.0",
+ "@ethersproject/strings": "^5.8.0",
+ "@ethersproject/transactions": "^5.8.0",
+ "aes-js": "3.0.0",
+ "scrypt-js": "3.0.1"
+ }
+ },
"node_modules/@ethersproject/keccak256": {
"version": "5.8.0",
"funding": [
@@ -6951,6 +7206,26 @@
"@ethersproject/logger": "^5.8.0"
}
},
+ "node_modules/@ethersproject/pbkdf2": {
+ "version": "5.8.0",
+ "resolved": "https://registry.npmjs.org/@ethersproject/pbkdf2/-/pbkdf2-5.8.0.tgz",
+ "integrity": "sha512-wuHiv97BrzCmfEaPbUFpMjlVg/IDkZThp9Ri88BpjRleg4iePJaj2SW8AIyE8cXn5V1tuAaMj6lzvsGJkGWskg==",
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2"
+ },
+ {
+ "type": "individual",
+ "url": "https://www.buymeacoffee.com/ricmoo"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@ethersproject/bytes": "^5.8.0",
+ "@ethersproject/sha2": "^5.8.0"
+ }
+ },
"node_modules/@ethersproject/properties": {
"version": "5.8.0",
"funding": [
@@ -6981,7 +7256,6 @@
}
],
"license": "MIT",
- "optional": true,
"dependencies": {
"@ethersproject/abstract-provider": "^5.8.0",
"@ethersproject/abstract-signer": "^5.8.0",
@@ -7018,7 +7292,6 @@
}
],
"license": "MIT",
- "optional": true,
"dependencies": {
"@ethersproject/bytes": "^5.8.0",
"@ethersproject/logger": "^5.8.0"
@@ -7083,6 +7356,30 @@
"hash.js": "1.1.7"
}
},
+ "node_modules/@ethersproject/solidity": {
+ "version": "5.8.0",
+ "resolved": "https://registry.npmjs.org/@ethersproject/solidity/-/solidity-5.8.0.tgz",
+ "integrity": "sha512-4CxFeCgmIWamOHwYN9d+QWGxye9qQLilpgTU0XhYs1OahkclF+ewO+3V1U0mvpiuQxm5EHHmv8f7ClVII8EHsA==",
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2"
+ },
+ {
+ "type": "individual",
+ "url": "https://www.buymeacoffee.com/ricmoo"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@ethersproject/bignumber": "^5.8.0",
+ "@ethersproject/bytes": "^5.8.0",
+ "@ethersproject/keccak256": "^5.8.0",
+ "@ethersproject/logger": "^5.8.0",
+ "@ethersproject/sha2": "^5.8.0",
+ "@ethersproject/strings": "^5.8.0"
+ }
+ },
"node_modules/@ethersproject/strings": {
"version": "5.8.0",
"funding": [
@@ -7146,6 +7443,39 @@
"@ethersproject/logger": "^5.8.0"
}
},
+ "node_modules/@ethersproject/wallet": {
+ "version": "5.8.0",
+ "resolved": "https://registry.npmjs.org/@ethersproject/wallet/-/wallet-5.8.0.tgz",
+ "integrity": "sha512-G+jnzmgg6UxurVKRKvw27h0kvG75YKXZKdlLYmAHeF32TGUzHkOFd7Zn6QHOTYRFWnfjtSSFjBowKo7vfrXzPA==",
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2"
+ },
+ {
+ "type": "individual",
+ "url": "https://www.buymeacoffee.com/ricmoo"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@ethersproject/abstract-provider": "^5.8.0",
+ "@ethersproject/abstract-signer": "^5.8.0",
+ "@ethersproject/address": "^5.8.0",
+ "@ethersproject/bignumber": "^5.8.0",
+ "@ethersproject/bytes": "^5.8.0",
+ "@ethersproject/hash": "^5.8.0",
+ "@ethersproject/hdnode": "^5.8.0",
+ "@ethersproject/json-wallets": "^5.8.0",
+ "@ethersproject/keccak256": "^5.8.0",
+ "@ethersproject/logger": "^5.8.0",
+ "@ethersproject/properties": "^5.8.0",
+ "@ethersproject/random": "^5.8.0",
+ "@ethersproject/signing-key": "^5.8.0",
+ "@ethersproject/transactions": "^5.8.0",
+ "@ethersproject/wordlists": "^5.8.0"
+ }
+ },
"node_modules/@ethersproject/web": {
"version": "5.8.0",
"funding": [
@@ -7167,6 +7497,29 @@
"@ethersproject/strings": "^5.8.0"
}
},
+ "node_modules/@ethersproject/wordlists": {
+ "version": "5.8.0",
+ "resolved": "https://registry.npmjs.org/@ethersproject/wordlists/-/wordlists-5.8.0.tgz",
+ "integrity": "sha512-2df9bbXicZws2Sb5S6ET493uJ0Z84Fjr3pC4tu/qlnZERibZCeUVuqdtt+7Tv9xxhUxHoIekIA7avrKUWHrezg==",
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2"
+ },
+ {
+ "type": "individual",
+ "url": "https://www.buymeacoffee.com/ricmoo"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@ethersproject/bytes": "^5.8.0",
+ "@ethersproject/hash": "^5.8.0",
+ "@ethersproject/logger": "^5.8.0",
+ "@ethersproject/properties": "^5.8.0",
+ "@ethersproject/strings": "^5.8.0"
+ }
+ },
"node_modules/@exodus/bytes": {
"version": "1.15.0",
"dev": true,
@@ -10751,6 +11104,522 @@
"node": ">= 18"
}
},
+ "node_modules/@nomicfoundation/ethereumjs-block": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/@nomicfoundation/ethereumjs-block/-/ethereumjs-block-5.0.0.tgz",
+ "integrity": "sha512-DfhVbqM5DjriguuSv6r3TgOpyXC76oX8D/VEODsSwJQ1bZGqu4xLLfYPPTacpCAYOnewzJsZli+Ao9TBTAo2uw==",
+ "license": "MPL-2.0",
+ "dependencies": {
+ "@nomicfoundation/ethereumjs-common": "4.0.0",
+ "@nomicfoundation/ethereumjs-rlp": "5.0.0",
+ "@nomicfoundation/ethereumjs-trie": "6.0.0",
+ "@nomicfoundation/ethereumjs-tx": "5.0.0",
+ "@nomicfoundation/ethereumjs-util": "9.0.0",
+ "ethereum-cryptography": "0.1.3",
+ "ethers": "^5.7.1"
+ },
+ "engines": {
+ "node": ">=14"
+ }
+ },
+ "node_modules/@nomicfoundation/ethereumjs-block/node_modules/ethereum-cryptography": {
+ "version": "0.1.3",
+ "resolved": "https://registry.npmjs.org/ethereum-cryptography/-/ethereum-cryptography-0.1.3.tgz",
+ "integrity": "sha512-w8/4x1SGGzc+tO97TASLja6SLd3fRIK2tLVcV2Gx4IB21hE19atll5Cq9o3d0ZmAYC/8aw0ipieTSiekAea4SQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/pbkdf2": "^3.0.0",
+ "@types/secp256k1": "^4.0.1",
+ "blakejs": "^1.1.0",
+ "browserify-aes": "^1.2.0",
+ "bs58check": "^2.1.2",
+ "create-hash": "^1.2.0",
+ "create-hmac": "^1.1.7",
+ "hash.js": "^1.1.7",
+ "keccak": "^3.0.0",
+ "pbkdf2": "^3.0.17",
+ "randombytes": "^2.1.0",
+ "safe-buffer": "^5.1.2",
+ "scrypt-js": "^3.0.0",
+ "secp256k1": "^4.0.1",
+ "setimmediate": "^1.0.5"
+ }
+ },
+ "node_modules/@nomicfoundation/ethereumjs-block/node_modules/ethers": {
+ "version": "5.8.0",
+ "resolved": "https://registry.npmjs.org/ethers/-/ethers-5.8.0.tgz",
+ "integrity": "sha512-DUq+7fHrCg1aPDFCHx6UIPb3nmt2XMpM7Y/g2gLhsl3lIBqeAfOJIl1qEvRf2uq3BiKxmh6Fh5pfp2ieyek7Kg==",
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2"
+ },
+ {
+ "type": "individual",
+ "url": "https://www.buymeacoffee.com/ricmoo"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@ethersproject/abi": "5.8.0",
+ "@ethersproject/abstract-provider": "5.8.0",
+ "@ethersproject/abstract-signer": "5.8.0",
+ "@ethersproject/address": "5.8.0",
+ "@ethersproject/base64": "5.8.0",
+ "@ethersproject/basex": "5.8.0",
+ "@ethersproject/bignumber": "5.8.0",
+ "@ethersproject/bytes": "5.8.0",
+ "@ethersproject/constants": "5.8.0",
+ "@ethersproject/contracts": "5.8.0",
+ "@ethersproject/hash": "5.8.0",
+ "@ethersproject/hdnode": "5.8.0",
+ "@ethersproject/json-wallets": "5.8.0",
+ "@ethersproject/keccak256": "5.8.0",
+ "@ethersproject/logger": "5.8.0",
+ "@ethersproject/networks": "5.8.0",
+ "@ethersproject/pbkdf2": "5.8.0",
+ "@ethersproject/properties": "5.8.0",
+ "@ethersproject/providers": "5.8.0",
+ "@ethersproject/random": "5.8.0",
+ "@ethersproject/rlp": "5.8.0",
+ "@ethersproject/sha2": "5.8.0",
+ "@ethersproject/signing-key": "5.8.0",
+ "@ethersproject/solidity": "5.8.0",
+ "@ethersproject/strings": "5.8.0",
+ "@ethersproject/transactions": "5.8.0",
+ "@ethersproject/units": "5.8.0",
+ "@ethersproject/wallet": "5.8.0",
+ "@ethersproject/web": "5.8.0",
+ "@ethersproject/wordlists": "5.8.0"
+ }
+ },
+ "node_modules/@nomicfoundation/ethereumjs-blockchain": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/@nomicfoundation/ethereumjs-blockchain/-/ethereumjs-blockchain-7.0.0.tgz",
+ "integrity": "sha512-cVRCrXZminZr0Mbx2hm0/109GZLn1v5bf0/k+SIbGn50yZm6YCdQt9CgGT0Gk56N2vy8NhXD4apo167m4LWk6Q==",
+ "license": "MPL-2.0",
+ "dependencies": {
+ "@nomicfoundation/ethereumjs-block": "5.0.0",
+ "@nomicfoundation/ethereumjs-common": "4.0.0",
+ "@nomicfoundation/ethereumjs-ethash": "3.0.0",
+ "@nomicfoundation/ethereumjs-rlp": "5.0.0",
+ "@nomicfoundation/ethereumjs-trie": "6.0.0",
+ "@nomicfoundation/ethereumjs-tx": "5.0.0",
+ "@nomicfoundation/ethereumjs-util": "9.0.0",
+ "abstract-level": "^1.0.3",
+ "debug": "^4.3.3",
+ "ethereum-cryptography": "0.1.3",
+ "level": "^8.0.0",
+ "lru-cache": "^5.1.1",
+ "memory-level": "^1.0.0"
+ },
+ "engines": {
+ "node": ">=14"
+ }
+ },
+ "node_modules/@nomicfoundation/ethereumjs-blockchain/node_modules/ethereum-cryptography": {
+ "version": "0.1.3",
+ "resolved": "https://registry.npmjs.org/ethereum-cryptography/-/ethereum-cryptography-0.1.3.tgz",
+ "integrity": "sha512-w8/4x1SGGzc+tO97TASLja6SLd3fRIK2tLVcV2Gx4IB21hE19atll5Cq9o3d0ZmAYC/8aw0ipieTSiekAea4SQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/pbkdf2": "^3.0.0",
+ "@types/secp256k1": "^4.0.1",
+ "blakejs": "^1.1.0",
+ "browserify-aes": "^1.2.0",
+ "bs58check": "^2.1.2",
+ "create-hash": "^1.2.0",
+ "create-hmac": "^1.1.7",
+ "hash.js": "^1.1.7",
+ "keccak": "^3.0.0",
+ "pbkdf2": "^3.0.17",
+ "randombytes": "^2.1.0",
+ "safe-buffer": "^5.1.2",
+ "scrypt-js": "^3.0.0",
+ "secp256k1": "^4.0.1",
+ "setimmediate": "^1.0.5"
+ }
+ },
+ "node_modules/@nomicfoundation/ethereumjs-blockchain/node_modules/lru-cache": {
+ "version": "5.1.1",
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
+ "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==",
+ "license": "ISC",
+ "dependencies": {
+ "yallist": "^3.0.2"
+ }
+ },
+ "node_modules/@nomicfoundation/ethereumjs-common": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/@nomicfoundation/ethereumjs-common/-/ethereumjs-common-4.0.0.tgz",
+ "integrity": "sha512-UPpm5FAGAf2B6hQ8aVgO44Rdo0k73oMMCViqNJcKMlk1s9l3rxwuPTp1l20NiGvNO2Pzqk3chFL+BzmLL2g4wQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@nomicfoundation/ethereumjs-util": "9.0.0",
+ "crc-32": "^1.2.0"
+ }
+ },
+ "node_modules/@nomicfoundation/ethereumjs-ethash": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/@nomicfoundation/ethereumjs-ethash/-/ethereumjs-ethash-3.0.0.tgz",
+ "integrity": "sha512-6zNv5Y3vNIsxjrsbKjMInVpo8cmR0c7yjZbBpy7NYuIMtm0JKhQoXsiFN56t/1sfn9V3v0wgrkAixo5v6bahpA==",
+ "license": "MPL-2.0",
+ "dependencies": {
+ "@nomicfoundation/ethereumjs-block": "5.0.0",
+ "@nomicfoundation/ethereumjs-rlp": "5.0.0",
+ "@nomicfoundation/ethereumjs-util": "9.0.0",
+ "abstract-level": "^1.0.3",
+ "bigint-crypto-utils": "^3.0.23",
+ "ethereum-cryptography": "0.1.3"
+ },
+ "engines": {
+ "node": ">=14"
+ }
+ },
+ "node_modules/@nomicfoundation/ethereumjs-ethash/node_modules/ethereum-cryptography": {
+ "version": "0.1.3",
+ "resolved": "https://registry.npmjs.org/ethereum-cryptography/-/ethereum-cryptography-0.1.3.tgz",
+ "integrity": "sha512-w8/4x1SGGzc+tO97TASLja6SLd3fRIK2tLVcV2Gx4IB21hE19atll5Cq9o3d0ZmAYC/8aw0ipieTSiekAea4SQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/pbkdf2": "^3.0.0",
+ "@types/secp256k1": "^4.0.1",
+ "blakejs": "^1.1.0",
+ "browserify-aes": "^1.2.0",
+ "bs58check": "^2.1.2",
+ "create-hash": "^1.2.0",
+ "create-hmac": "^1.1.7",
+ "hash.js": "^1.1.7",
+ "keccak": "^3.0.0",
+ "pbkdf2": "^3.0.17",
+ "randombytes": "^2.1.0",
+ "safe-buffer": "^5.1.2",
+ "scrypt-js": "^3.0.0",
+ "secp256k1": "^4.0.1",
+ "setimmediate": "^1.0.5"
+ }
+ },
+ "node_modules/@nomicfoundation/ethereumjs-evm": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/@nomicfoundation/ethereumjs-evm/-/ethereumjs-evm-2.0.0.tgz",
+ "integrity": "sha512-D+tr3M9sictopr3E20OVgme7YF/d0fU566WKh+ofXwmxapz/Dd8RSLSaVeKgfCI2BkzVA+XqXY08NNCV8w8fWA==",
+ "license": "MPL-2.0",
+ "dependencies": {
+ "@ethersproject/providers": "^5.7.1",
+ "@nomicfoundation/ethereumjs-common": "4.0.0",
+ "@nomicfoundation/ethereumjs-tx": "5.0.0",
+ "@nomicfoundation/ethereumjs-util": "9.0.0",
+ "debug": "^4.3.3",
+ "ethereum-cryptography": "0.1.3",
+ "mcl-wasm": "^0.7.1",
+ "rustbn.js": "~0.2.0"
+ },
+ "engines": {
+ "node": ">=14"
+ }
+ },
+ "node_modules/@nomicfoundation/ethereumjs-evm/node_modules/ethereum-cryptography": {
+ "version": "0.1.3",
+ "resolved": "https://registry.npmjs.org/ethereum-cryptography/-/ethereum-cryptography-0.1.3.tgz",
+ "integrity": "sha512-w8/4x1SGGzc+tO97TASLja6SLd3fRIK2tLVcV2Gx4IB21hE19atll5Cq9o3d0ZmAYC/8aw0ipieTSiekAea4SQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/pbkdf2": "^3.0.0",
+ "@types/secp256k1": "^4.0.1",
+ "blakejs": "^1.1.0",
+ "browserify-aes": "^1.2.0",
+ "bs58check": "^2.1.2",
+ "create-hash": "^1.2.0",
+ "create-hmac": "^1.1.7",
+ "hash.js": "^1.1.7",
+ "keccak": "^3.0.0",
+ "pbkdf2": "^3.0.17",
+ "randombytes": "^2.1.0",
+ "safe-buffer": "^5.1.2",
+ "scrypt-js": "^3.0.0",
+ "secp256k1": "^4.0.1",
+ "setimmediate": "^1.0.5"
+ }
+ },
+ "node_modules/@nomicfoundation/ethereumjs-rlp": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/@nomicfoundation/ethereumjs-rlp/-/ethereumjs-rlp-5.0.0.tgz",
+ "integrity": "sha512-U1A0y330PtGb8Wft4yPVv0myWYJTesi89ItGoB0ICdqz7793KmUhpfQb2vJUXBi98wSdnxkIABO/GmsQvGKVDw==",
+ "license": "MPL-2.0",
+ "bin": {
+ "rlp": "bin/rlp"
+ },
+ "engines": {
+ "node": ">=14"
+ }
+ },
+ "node_modules/@nomicfoundation/ethereumjs-statemanager": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/@nomicfoundation/ethereumjs-statemanager/-/ethereumjs-statemanager-2.0.0.tgz",
+ "integrity": "sha512-tgXtsx8yIDlxWMN+ThqPtGK0ITAuITrDy+GYIgGrnT6ZtelvXWM7SUYR0Mcv578lmGCoIwyHFtSBqOkOBYHLjw==",
+ "license": "MPL-2.0",
+ "dependencies": {
+ "@nomicfoundation/ethereumjs-common": "4.0.0",
+ "@nomicfoundation/ethereumjs-rlp": "5.0.0",
+ "debug": "^4.3.3",
+ "ethereum-cryptography": "0.1.3",
+ "ethers": "^5.7.1",
+ "js-sdsl": "^4.1.4"
+ }
+ },
+ "node_modules/@nomicfoundation/ethereumjs-statemanager/node_modules/ethereum-cryptography": {
+ "version": "0.1.3",
+ "resolved": "https://registry.npmjs.org/ethereum-cryptography/-/ethereum-cryptography-0.1.3.tgz",
+ "integrity": "sha512-w8/4x1SGGzc+tO97TASLja6SLd3fRIK2tLVcV2Gx4IB21hE19atll5Cq9o3d0ZmAYC/8aw0ipieTSiekAea4SQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/pbkdf2": "^3.0.0",
+ "@types/secp256k1": "^4.0.1",
+ "blakejs": "^1.1.0",
+ "browserify-aes": "^1.2.0",
+ "bs58check": "^2.1.2",
+ "create-hash": "^1.2.0",
+ "create-hmac": "^1.1.7",
+ "hash.js": "^1.1.7",
+ "keccak": "^3.0.0",
+ "pbkdf2": "^3.0.17",
+ "randombytes": "^2.1.0",
+ "safe-buffer": "^5.1.2",
+ "scrypt-js": "^3.0.0",
+ "secp256k1": "^4.0.1",
+ "setimmediate": "^1.0.5"
+ }
+ },
+ "node_modules/@nomicfoundation/ethereumjs-statemanager/node_modules/ethers": {
+ "version": "5.8.0",
+ "resolved": "https://registry.npmjs.org/ethers/-/ethers-5.8.0.tgz",
+ "integrity": "sha512-DUq+7fHrCg1aPDFCHx6UIPb3nmt2XMpM7Y/g2gLhsl3lIBqeAfOJIl1qEvRf2uq3BiKxmh6Fh5pfp2ieyek7Kg==",
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://gitcoin.co/grants/13/ethersjs-complete-simple-and-tiny-2"
+ },
+ {
+ "type": "individual",
+ "url": "https://www.buymeacoffee.com/ricmoo"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@ethersproject/abi": "5.8.0",
+ "@ethersproject/abstract-provider": "5.8.0",
+ "@ethersproject/abstract-signer": "5.8.0",
+ "@ethersproject/address": "5.8.0",
+ "@ethersproject/base64": "5.8.0",
+ "@ethersproject/basex": "5.8.0",
+ "@ethersproject/bignumber": "5.8.0",
+ "@ethersproject/bytes": "5.8.0",
+ "@ethersproject/constants": "5.8.0",
+ "@ethersproject/contracts": "5.8.0",
+ "@ethersproject/hash": "5.8.0",
+ "@ethersproject/hdnode": "5.8.0",
+ "@ethersproject/json-wallets": "5.8.0",
+ "@ethersproject/keccak256": "5.8.0",
+ "@ethersproject/logger": "5.8.0",
+ "@ethersproject/networks": "5.8.0",
+ "@ethersproject/pbkdf2": "5.8.0",
+ "@ethersproject/properties": "5.8.0",
+ "@ethersproject/providers": "5.8.0",
+ "@ethersproject/random": "5.8.0",
+ "@ethersproject/rlp": "5.8.0",
+ "@ethersproject/sha2": "5.8.0",
+ "@ethersproject/signing-key": "5.8.0",
+ "@ethersproject/solidity": "5.8.0",
+ "@ethersproject/strings": "5.8.0",
+ "@ethersproject/transactions": "5.8.0",
+ "@ethersproject/units": "5.8.0",
+ "@ethersproject/wallet": "5.8.0",
+ "@ethersproject/web": "5.8.0",
+ "@ethersproject/wordlists": "5.8.0"
+ }
+ },
+ "node_modules/@nomicfoundation/ethereumjs-trie": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/@nomicfoundation/ethereumjs-trie/-/ethereumjs-trie-6.0.0.tgz",
+ "integrity": "sha512-YqPWiNxrZvL+Ef7KHqgru1IlaIGXhu78wd2fxNFOvi/NAQBF845dVfTKKXs1L9x0QBRRQRephgxHCKMuISGppw==",
+ "license": "MPL-2.0",
+ "dependencies": {
+ "@nomicfoundation/ethereumjs-rlp": "5.0.0",
+ "@nomicfoundation/ethereumjs-util": "9.0.0",
+ "@types/readable-stream": "^2.3.13",
+ "ethereum-cryptography": "0.1.3",
+ "readable-stream": "^3.6.0"
+ },
+ "engines": {
+ "node": ">=14"
+ }
+ },
+ "node_modules/@nomicfoundation/ethereumjs-trie/node_modules/ethereum-cryptography": {
+ "version": "0.1.3",
+ "resolved": "https://registry.npmjs.org/ethereum-cryptography/-/ethereum-cryptography-0.1.3.tgz",
+ "integrity": "sha512-w8/4x1SGGzc+tO97TASLja6SLd3fRIK2tLVcV2Gx4IB21hE19atll5Cq9o3d0ZmAYC/8aw0ipieTSiekAea4SQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/pbkdf2": "^3.0.0",
+ "@types/secp256k1": "^4.0.1",
+ "blakejs": "^1.1.0",
+ "browserify-aes": "^1.2.0",
+ "bs58check": "^2.1.2",
+ "create-hash": "^1.2.0",
+ "create-hmac": "^1.1.7",
+ "hash.js": "^1.1.7",
+ "keccak": "^3.0.0",
+ "pbkdf2": "^3.0.17",
+ "randombytes": "^2.1.0",
+ "safe-buffer": "^5.1.2",
+ "scrypt-js": "^3.0.0",
+ "secp256k1": "^4.0.1",
+ "setimmediate": "^1.0.5"
+ }
+ },
+ "node_modules/@nomicfoundation/ethereumjs-tx": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/@nomicfoundation/ethereumjs-tx/-/ethereumjs-tx-5.0.0.tgz",
+ "integrity": "sha512-LTyxI+zBJ+HuEBblUGbxvfKl1hg1uJlz2XhnszNagiBWQSgLb1vQCa1QaXV5Q8cUDYkr/Xe4NXWiUGEvH4e6lA==",
+ "license": "MPL-2.0",
+ "dependencies": {
+ "@chainsafe/ssz": "^0.9.2",
+ "@ethersproject/providers": "^5.7.2",
+ "@nomicfoundation/ethereumjs-common": "4.0.0",
+ "@nomicfoundation/ethereumjs-rlp": "5.0.0",
+ "@nomicfoundation/ethereumjs-util": "9.0.0",
+ "ethereum-cryptography": "0.1.3"
+ },
+ "engines": {
+ "node": ">=14"
+ }
+ },
+ "node_modules/@nomicfoundation/ethereumjs-tx/node_modules/ethereum-cryptography": {
+ "version": "0.1.3",
+ "resolved": "https://registry.npmjs.org/ethereum-cryptography/-/ethereum-cryptography-0.1.3.tgz",
+ "integrity": "sha512-w8/4x1SGGzc+tO97TASLja6SLd3fRIK2tLVcV2Gx4IB21hE19atll5Cq9o3d0ZmAYC/8aw0ipieTSiekAea4SQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/pbkdf2": "^3.0.0",
+ "@types/secp256k1": "^4.0.1",
+ "blakejs": "^1.1.0",
+ "browserify-aes": "^1.2.0",
+ "bs58check": "^2.1.2",
+ "create-hash": "^1.2.0",
+ "create-hmac": "^1.1.7",
+ "hash.js": "^1.1.7",
+ "keccak": "^3.0.0",
+ "pbkdf2": "^3.0.17",
+ "randombytes": "^2.1.0",
+ "safe-buffer": "^5.1.2",
+ "scrypt-js": "^3.0.0",
+ "secp256k1": "^4.0.1",
+ "setimmediate": "^1.0.5"
+ }
+ },
+ "node_modules/@nomicfoundation/ethereumjs-util": {
+ "version": "9.0.0",
+ "resolved": "https://registry.npmjs.org/@nomicfoundation/ethereumjs-util/-/ethereumjs-util-9.0.0.tgz",
+ "integrity": "sha512-9EG98CsEC9BnI7AY27F4QXZ8Vf0re8R9XoxQ0//KWF+B7quu6GQvgTq1RlNUjGh/XNCCJNf8E3LOY9ULR85wFQ==",
+ "license": "MPL-2.0",
+ "dependencies": {
+ "@chainsafe/ssz": "^0.10.0",
+ "@nomicfoundation/ethereumjs-rlp": "5.0.0",
+ "ethereum-cryptography": "0.1.3"
+ },
+ "engines": {
+ "node": ">=14"
+ }
+ },
+ "node_modules/@nomicfoundation/ethereumjs-util/node_modules/@chainsafe/persistent-merkle-tree": {
+ "version": "0.5.0",
+ "resolved": "https://registry.npmjs.org/@chainsafe/persistent-merkle-tree/-/persistent-merkle-tree-0.5.0.tgz",
+ "integrity": "sha512-l0V1b5clxA3iwQLXP40zYjyZYospQLZXzBVIhhr9kDg/1qHZfzzHw0jj4VPBijfYCArZDlPkRi1wZaV2POKeuw==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@chainsafe/as-sha256": "^0.3.1"
+ }
+ },
+ "node_modules/@nomicfoundation/ethereumjs-util/node_modules/@chainsafe/ssz": {
+ "version": "0.10.2",
+ "resolved": "https://registry.npmjs.org/@chainsafe/ssz/-/ssz-0.10.2.tgz",
+ "integrity": "sha512-/NL3Lh8K+0q7A3LsiFq09YXS9fPE+ead2rr7vM2QK8PLzrNsw3uqrif9bpRX5UxgeRjM+vYi+boCM3+GM4ovXg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@chainsafe/as-sha256": "^0.3.1",
+ "@chainsafe/persistent-merkle-tree": "^0.5.0"
+ }
+ },
+ "node_modules/@nomicfoundation/ethereumjs-util/node_modules/ethereum-cryptography": {
+ "version": "0.1.3",
+ "resolved": "https://registry.npmjs.org/ethereum-cryptography/-/ethereum-cryptography-0.1.3.tgz",
+ "integrity": "sha512-w8/4x1SGGzc+tO97TASLja6SLd3fRIK2tLVcV2Gx4IB21hE19atll5Cq9o3d0ZmAYC/8aw0ipieTSiekAea4SQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/pbkdf2": "^3.0.0",
+ "@types/secp256k1": "^4.0.1",
+ "blakejs": "^1.1.0",
+ "browserify-aes": "^1.2.0",
+ "bs58check": "^2.1.2",
+ "create-hash": "^1.2.0",
+ "create-hmac": "^1.1.7",
+ "hash.js": "^1.1.7",
+ "keccak": "^3.0.0",
+ "pbkdf2": "^3.0.17",
+ "randombytes": "^2.1.0",
+ "safe-buffer": "^5.1.2",
+ "scrypt-js": "^3.0.0",
+ "secp256k1": "^4.0.1",
+ "setimmediate": "^1.0.5"
+ }
+ },
+ "node_modules/@nomicfoundation/ethereumjs-vm": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/@nomicfoundation/ethereumjs-vm/-/ethereumjs-vm-7.0.0.tgz",
+ "integrity": "sha512-eHkEoe/4r4+g+fZyIIlQjBHEjCPFs8CHiIEEMvMfvFrV4hyHnuTg4LH7l92ok7TGZqpWxgMG2JOEUFkNsXrKuQ==",
+ "license": "MPL-2.0",
+ "dependencies": {
+ "@nomicfoundation/ethereumjs-block": "5.0.0",
+ "@nomicfoundation/ethereumjs-blockchain": "7.0.0",
+ "@nomicfoundation/ethereumjs-common": "4.0.0",
+ "@nomicfoundation/ethereumjs-evm": "2.0.0",
+ "@nomicfoundation/ethereumjs-rlp": "5.0.0",
+ "@nomicfoundation/ethereumjs-statemanager": "2.0.0",
+ "@nomicfoundation/ethereumjs-trie": "6.0.0",
+ "@nomicfoundation/ethereumjs-tx": "5.0.0",
+ "@nomicfoundation/ethereumjs-util": "9.0.0",
+ "debug": "^4.3.3",
+ "ethereum-cryptography": "0.1.3",
+ "mcl-wasm": "^0.7.1",
+ "rustbn.js": "~0.2.0"
+ },
+ "engines": {
+ "node": ">=14"
+ }
+ },
+ "node_modules/@nomicfoundation/ethereumjs-vm/node_modules/ethereum-cryptography": {
+ "version": "0.1.3",
+ "resolved": "https://registry.npmjs.org/ethereum-cryptography/-/ethereum-cryptography-0.1.3.tgz",
+ "integrity": "sha512-w8/4x1SGGzc+tO97TASLja6SLd3fRIK2tLVcV2Gx4IB21hE19atll5Cq9o3d0ZmAYC/8aw0ipieTSiekAea4SQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/pbkdf2": "^3.0.0",
+ "@types/secp256k1": "^4.0.1",
+ "blakejs": "^1.1.0",
+ "browserify-aes": "^1.2.0",
+ "bs58check": "^2.1.2",
+ "create-hash": "^1.2.0",
+ "create-hmac": "^1.1.7",
+ "hash.js": "^1.1.7",
+ "keccak": "^3.0.0",
+ "pbkdf2": "^3.0.17",
+ "randombytes": "^2.1.0",
+ "safe-buffer": "^5.1.2",
+ "scrypt-js": "^3.0.0",
+ "secp256k1": "^4.0.1",
+ "setimmediate": "^1.0.5"
+ }
+ },
"node_modules/@nomicfoundation/solidity-analyzer": {
"version": "0.1.2",
"license": "MIT",
@@ -16913,6 +17782,40 @@
"@jridgewell/sourcemap-codec": "^1.5.5"
}
},
+ "node_modules/@typechain/ethers-v5": {
+ "version": "10.2.1",
+ "resolved": "https://registry.npmjs.org/@typechain/ethers-v5/-/ethers-v5-10.2.1.tgz",
+ "integrity": "sha512-n3tQmCZjRE6IU4h6lqUGiQ1j866n5MTCBJreNEHHVWXa2u9GJTaeYyU1/k+1qLutkyw+sS6VAN+AbeiTqsxd/A==",
+ "license": "MIT",
+ "dependencies": {
+ "lodash": "^4.17.15",
+ "ts-essentials": "^7.0.1"
+ },
+ "peerDependencies": {
+ "@ethersproject/abi": "^5.0.0",
+ "@ethersproject/providers": "^5.0.0",
+ "ethers": "^5.1.3",
+ "typechain": "^8.1.1",
+ "typescript": ">=4.3.0"
+ }
+ },
+ "node_modules/@typechain/hardhat": {
+ "version": "6.1.6",
+ "resolved": "https://registry.npmjs.org/@typechain/hardhat/-/hardhat-6.1.6.tgz",
+ "integrity": "sha512-BiVnegSs+ZHVymyidtK472syodx1sXYlYJJixZfRstHVGYTi8V1O7QG4nsjyb0PC/LORcq7sfBUcHto1y6UgJA==",
+ "license": "MIT",
+ "dependencies": {
+ "fs-extra": "^9.1.0"
+ },
+ "peerDependencies": {
+ "@ethersproject/abi": "^5.4.7",
+ "@ethersproject/providers": "^5.4.7",
+ "@typechain/ethers-v5": "^10.2.1",
+ "ethers": "^5.4.7",
+ "hardhat": "^2.9.9",
+ "typechain": "^8.1.1"
+ }
+ },
"node_modules/@types/aria-query": {
"version": "5.0.4",
"dev": true,
@@ -17161,6 +18064,12 @@
"pg-types": "^4.0.1"
}
},
+ "node_modules/@types/prettier": {
+ "version": "2.7.3",
+ "resolved": "https://registry.npmjs.org/@types/prettier/-/prettier-2.7.3.tgz",
+ "integrity": "sha512-+68kP9yzs4LMp7VNh8gdzMSPZFL44MLGqiHWvttYJe+6qnuVr4Ek9wSBQoveqY/r+LwjCcU29kNVkidwim+kYA==",
+ "license": "MIT"
+ },
"node_modules/@types/qs": {
"version": "6.15.0",
"license": "MIT"
@@ -17177,6 +18086,22 @@
"@types/react": "*"
}
},
+ "node_modules/@types/readable-stream": {
+ "version": "2.3.15",
+ "resolved": "https://registry.npmjs.org/@types/readable-stream/-/readable-stream-2.3.15.tgz",
+ "integrity": "sha512-oM5JSKQCcICF1wvGgmecmHldZ48OZamtMxcGGVICOJA8o8cahXC1zEVAif8iwoc5j8etxFaRFnf095+CDsuoFQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*",
+ "safe-buffer": "~5.1.1"
+ }
+ },
+ "node_modules/@types/readable-stream/node_modules/safe-buffer": {
+ "version": "5.1.2",
+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
+ "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
+ "license": "MIT"
+ },
"node_modules/@types/resolve": {
"version": "1.20.2",
"dev": true,
@@ -19402,10 +20327,63 @@
}
}
},
+ "node_modules/abort-controller": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz",
+ "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==",
+ "license": "MIT",
+ "dependencies": {
+ "event-target-shim": "^5.0.0"
+ },
+ "engines": {
+ "node": ">=6.5"
+ }
+ },
"node_modules/abort-error": {
"version": "1.0.2",
"license": "Apache-2.0 OR MIT"
},
+ "node_modules/abstract-level": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/abstract-level/-/abstract-level-1.0.4.tgz",
+ "integrity": "sha512-eUP/6pbXBkMbXFdx4IH2fVgvB7M0JvR7/lIL33zcs0IBcwjdzSSl31TOJsaCzmKSSDF9h8QYSOJux4Nd4YJqFg==",
+ "license": "MIT",
+ "dependencies": {
+ "buffer": "^6.0.3",
+ "catering": "^2.1.0",
+ "is-buffer": "^2.0.5",
+ "level-supports": "^4.0.0",
+ "level-transcoder": "^1.0.1",
+ "module-error": "^1.0.1",
+ "queue-microtask": "^1.2.3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/abstract-level/node_modules/is-buffer": {
+ "version": "2.0.5",
+ "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-2.0.5.tgz",
+ "integrity": "sha512-i2R6zNFDwgEHJyQUtJEk0XFi1i0dPFn/oqjK3/vPCcDeJvW5NQ83V8QbicfF1SupOaB0h8ntgBC2YiE7dfyctQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=4"
+ }
+ },
"node_modules/accepts": {
"version": "2.0.0",
"license": "MIT",
@@ -19478,6 +20456,12 @@
"node": ">=0.3.0"
}
},
+ "node_modules/aes-js": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/aes-js/-/aes-js-3.0.0.tgz",
+ "integrity": "sha512-H7wUZRn8WpTq9jocdxQ2c8x2sKo9ZVmzfRE13GiNJXfp7NcKYEdvl3vspKjXox6RIG2VtaRe4JFvxG4rqp2Zuw==",
+ "license": "MIT"
+ },
"node_modules/agent-base": {
"version": "7.1.4",
"license": "MIT",
@@ -19762,6 +20746,15 @@
"dequal": "^2.0.3"
}
},
+ "node_modules/array-back": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/array-back/-/array-back-3.1.0.tgz",
+ "integrity": "sha512-TkuxA4UCOvxuDK6NZYXCalszEzj+TLszyASooky+i742l9TqsOdYCMJJupxRic61hwquNtppB3hgcuq9SVSH1Q==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
"node_modules/array-buffer-byte-length": {
"version": "1.0.2",
"dev": true,
@@ -19976,7 +20969,6 @@
},
"node_modules/at-least-node": {
"version": "1.0.0",
- "dev": true,
"license": "ISC",
"engines": {
"node": ">= 4.0.0"
@@ -20462,6 +21454,15 @@
"node": ">= 10.0.0"
}
},
+ "node_modules/bigint-crypto-utils": {
+ "version": "3.3.0",
+ "resolved": "https://registry.npmjs.org/bigint-crypto-utils/-/bigint-crypto-utils-3.3.0.tgz",
+ "integrity": "sha512-jOTSb+drvEDxEq6OuUybOAv/xxoh3cuYRUIPyu8sSHQNKM303UQ2R1DAo45o1AkcIXw6fzbaFI1+xGGdaXs2lg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
"node_modules/bignumber.js": {
"version": "9.3.1",
"license": "MIT",
@@ -20731,6 +21732,18 @@
"version": "1.1.0",
"license": "MIT"
},
+ "node_modules/browser-level": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/browser-level/-/browser-level-1.0.1.tgz",
+ "integrity": "sha512-XECYKJ+Dbzw0lbydyQuJzwNXtOpbMSq737qxJN11sIRTErOMShvDpbzTlgju7orJKvx4epULolZAuJGLzCmWRQ==",
+ "license": "MIT",
+ "dependencies": {
+ "abstract-level": "^1.0.2",
+ "catering": "^2.1.1",
+ "module-error": "^1.0.2",
+ "run-parallel-limit": "^1.1.0"
+ }
+ },
"node_modules/browser-or-node": {
"version": "3.0.0",
"license": "MIT"
@@ -21135,6 +22148,24 @@
"canonicalize": "bin/canonicalize.js"
}
},
+ "node_modules/case": {
+ "version": "1.6.3",
+ "resolved": "https://registry.npmjs.org/case/-/case-1.6.3.tgz",
+ "integrity": "sha512-mzDSXIPaFwVDvZAHqZ9VlbyF4yyXRuX6IvB06WvPYkqJVO24kX1PPhv9bfpKNFZyxYFmmgo03HUiD8iklmJYRQ==",
+ "license": "(MIT OR GPL-3.0-or-later)",
+ "engines": {
+ "node": ">= 0.8.0"
+ }
+ },
+ "node_modules/catering": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/catering/-/catering-2.1.1.tgz",
+ "integrity": "sha512-K7Qy8O9p76sL3/3m7/zLKbRkyOlSZAgzEaLhyj2mXS8PsCud2Eo4hAb8aLtZqHh0QGqLcb9dlJSu6lHRVENm1w==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
"node_modules/cborg": {
"version": "4.5.8",
"license": "Apache-2.0",
@@ -21236,6 +22267,23 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/classic-level": {
+ "version": "1.4.1",
+ "resolved": "https://registry.npmjs.org/classic-level/-/classic-level-1.4.1.tgz",
+ "integrity": "sha512-qGx/KJl3bvtOHrGau2WklEZuXhS3zme+jf+fsu6Ej7W7IP/C49v7KNlWIsT1jZu0YnfzSIYDGcEWpCa1wKGWXQ==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "dependencies": {
+ "abstract-level": "^1.0.2",
+ "catering": "^2.1.0",
+ "module-error": "^1.0.1",
+ "napi-macros": "^2.2.2",
+ "node-gyp-build": "^4.3.0"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
"node_modules/classnames": {
"version": "2.5.1",
"dev": true,
@@ -21404,6 +22452,125 @@
"version": "1.2.9",
"license": "MIT"
},
+ "node_modules/command-line-args": {
+ "version": "5.2.1",
+ "resolved": "https://registry.npmjs.org/command-line-args/-/command-line-args-5.2.1.tgz",
+ "integrity": "sha512-H4UfQhZyakIjC74I9d34fGYDwk3XpSr17QhEd0Q3I9Xq1CETHo4Hcuo87WyWHpAF1aSLjLRf5lD9ZGX2qStUvg==",
+ "license": "MIT",
+ "dependencies": {
+ "array-back": "^3.1.0",
+ "find-replace": "^3.0.0",
+ "lodash.camelcase": "^4.3.0",
+ "typical": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=4.0.0"
+ }
+ },
+ "node_modules/command-line-usage": {
+ "version": "6.1.3",
+ "resolved": "https://registry.npmjs.org/command-line-usage/-/command-line-usage-6.1.3.tgz",
+ "integrity": "sha512-sH5ZSPr+7UStsloltmDh7Ce5fb8XPlHyoPzTpyyMuYCtervL65+ubVZ6Q61cFtFl62UyJlc8/JwERRbAFPUqgw==",
+ "license": "MIT",
+ "dependencies": {
+ "array-back": "^4.0.2",
+ "chalk": "^2.4.2",
+ "table-layout": "^1.0.2",
+ "typical": "^5.2.0"
+ },
+ "engines": {
+ "node": ">=8.0.0"
+ }
+ },
+ "node_modules/command-line-usage/node_modules/ansi-styles": {
+ "version": "3.2.1",
+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz",
+ "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==",
+ "license": "MIT",
+ "dependencies": {
+ "color-convert": "^1.9.0"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/command-line-usage/node_modules/array-back": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/array-back/-/array-back-4.0.2.tgz",
+ "integrity": "sha512-NbdMezxqf94cnNfWLL7V/im0Ub+Anbb0IoZhvzie8+4HJ4nMQuzHuy49FkGYCJK2yAloZ3meiB6AVMClbrI1vg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/command-line-usage/node_modules/chalk": {
+ "version": "2.4.2",
+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz",
+ "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==",
+ "license": "MIT",
+ "dependencies": {
+ "ansi-styles": "^3.2.1",
+ "escape-string-regexp": "^1.0.5",
+ "supports-color": "^5.3.0"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/command-line-usage/node_modules/color-convert": {
+ "version": "1.9.3",
+ "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz",
+ "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==",
+ "license": "MIT",
+ "dependencies": {
+ "color-name": "1.1.3"
+ }
+ },
+ "node_modules/command-line-usage/node_modules/color-name": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz",
+ "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==",
+ "license": "MIT"
+ },
+ "node_modules/command-line-usage/node_modules/escape-string-regexp": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz",
+ "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.8.0"
+ }
+ },
+ "node_modules/command-line-usage/node_modules/has-flag": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz",
+ "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/command-line-usage/node_modules/supports-color": {
+ "version": "5.5.0",
+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz",
+ "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==",
+ "license": "MIT",
+ "dependencies": {
+ "has-flag": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/command-line-usage/node_modules/typical": {
+ "version": "5.2.0",
+ "resolved": "https://registry.npmjs.org/typical/-/typical-5.2.0.tgz",
+ "integrity": "sha512-dvdQgNDNJo+8B2uBQoqdb11eUCE1JQXhvjC/CZtgvZseVd5TYMXnq0+vuUemXbd/Se29cTaUuPX3YIc2xgbvIg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/commander": {
"version": "2.20.3",
"license": "MIT"
@@ -24298,6 +25465,15 @@
"version": "2.0.0",
"license": "MIT"
},
+ "node_modules/event-target-shim": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz",
+ "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
"node_modules/eventemitter2": {
"version": "6.4.9",
"license": "MIT"
@@ -24985,6 +26161,18 @@
"url": "https://github.com/avajs/find-cache-dir?sponsor=1"
}
},
+ "node_modules/find-replace": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/find-replace/-/find-replace-3.0.0.tgz",
+ "integrity": "sha512-6Tb2myMioCAgv5kfvP5/PkZZ/ntTpVK39fHY7WkWBgvbeE+VHd/tZuZ4mrC+bxh4cfOZeYKVPaJIZtZXV7GNCQ==",
+ "license": "MIT",
+ "dependencies": {
+ "array-back": "^3.0.1"
+ },
+ "engines": {
+ "node": ">=4.0.0"
+ }
+ },
"node_modules/find-root": {
"version": "1.1.0",
"license": "MIT"
@@ -25137,7 +26325,6 @@
},
"node_modules/fs-extra": {
"version": "9.1.0",
- "dev": true,
"license": "MIT",
"dependencies": {
"at-least-node": "^1.0.0",
@@ -25203,6 +26390,12 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/functional-red-black-tree": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz",
+ "integrity": "sha512-dsKNQNdj6xA3T+QlADDA7mOSlX0qiMINjn0cgr+eGHGsbSHzTabcIogz2+p/iqP1Xs6EP/sS2SbqH+brGTbq0g==",
+ "license": "MIT"
+ },
"node_modules/functions-have-names": {
"version": "1.2.3",
"dev": true,
@@ -25606,6 +26799,470 @@
"node": ">=0.10.0"
}
},
+ "node_modules/hardhat": {
+ "version": "2.13.1",
+ "resolved": "https://registry.npmjs.org/hardhat/-/hardhat-2.13.1.tgz",
+ "integrity": "sha512-ZZL7LQxHmbw4JQJsiEv2qE35nbR+isr2sIdtgZVPp0+zWqRkpr1OT7gmvhCNYfjpEPyfjZIxWriQWlphJhVPLQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@ethersproject/abi": "^5.1.2",
+ "@metamask/eth-sig-util": "^4.0.0",
+ "@nomicfoundation/ethereumjs-block": "5.0.0",
+ "@nomicfoundation/ethereumjs-blockchain": "7.0.0",
+ "@nomicfoundation/ethereumjs-common": "4.0.0",
+ "@nomicfoundation/ethereumjs-evm": "2.0.0",
+ "@nomicfoundation/ethereumjs-rlp": "5.0.0",
+ "@nomicfoundation/ethereumjs-statemanager": "2.0.0",
+ "@nomicfoundation/ethereumjs-trie": "6.0.0",
+ "@nomicfoundation/ethereumjs-tx": "5.0.0",
+ "@nomicfoundation/ethereumjs-util": "9.0.0",
+ "@nomicfoundation/ethereumjs-vm": "7.0.0",
+ "@nomicfoundation/solidity-analyzer": "^0.1.0",
+ "@sentry/node": "^5.18.1",
+ "@types/bn.js": "^5.1.0",
+ "@types/lru-cache": "^5.1.0",
+ "abort-controller": "^3.0.0",
+ "adm-zip": "^0.4.16",
+ "aggregate-error": "^3.0.0",
+ "ansi-escapes": "^4.3.0",
+ "chalk": "^2.4.2",
+ "chokidar": "^3.4.0",
+ "ci-info": "^2.0.0",
+ "debug": "^4.1.1",
+ "enquirer": "^2.3.0",
+ "env-paths": "^2.2.0",
+ "ethereum-cryptography": "^1.0.3",
+ "ethereumjs-abi": "^0.6.8",
+ "find-up": "^2.1.0",
+ "fp-ts": "1.19.3",
+ "fs-extra": "^7.0.1",
+ "glob": "7.2.0",
+ "immutable": "^4.0.0-rc.12",
+ "io-ts": "1.10.4",
+ "keccak": "^3.0.2",
+ "lodash": "^4.17.11",
+ "mnemonist": "^0.38.0",
+ "mocha": "^10.0.0",
+ "p-map": "^4.0.0",
+ "qs": "^6.7.0",
+ "raw-body": "^2.4.1",
+ "resolve": "1.17.0",
+ "semver": "^6.3.0",
+ "solc": "0.7.3",
+ "source-map-support": "^0.5.13",
+ "stacktrace-parser": "^0.1.10",
+ "tsort": "0.0.1",
+ "undici": "^5.14.0",
+ "uuid": "^8.3.2",
+ "ws": "^7.4.6"
+ },
+ "bin": {
+ "hardhat": "internal/cli/bootstrap.js"
+ },
+ "engines": {
+ "node": ">=14.0.0"
+ },
+ "peerDependencies": {
+ "ts-node": "*",
+ "typescript": "*"
+ },
+ "peerDependenciesMeta": {
+ "ts-node": {
+ "optional": true
+ },
+ "typescript": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/hardhat/node_modules/@noble/hashes": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.2.0.tgz",
+ "integrity": "sha512-FZfhjEDbT5GRswV3C6uvLPHMiVD6lQBmpoX5+eSiPaMTXte/IKqI5dykDxzZB/WBeK/CDuQRBWarPdi3FNY2zQ==",
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://paulmillr.com/funding/"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/hardhat/node_modules/@scure/base": {
+ "version": "1.1.9",
+ "resolved": "https://registry.npmjs.org/@scure/base/-/base-1.1.9.tgz",
+ "integrity": "sha512-8YKhl8GHiNI/pU2VMaofa2Tor7PJRAjwQLBBuilkJ9L5+13yVbC7JO/wS7piioAvPSwR3JKM1IJ/u4xQzbcXKg==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://paulmillr.com/funding/"
+ }
+ },
+ "node_modules/hardhat/node_modules/@scure/bip32": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/@scure/bip32/-/bip32-1.1.5.tgz",
+ "integrity": "sha512-XyNh1rB0SkEqd3tXcXMi+Xe1fvg+kUIcoRIEujP1Jgv7DqW2r9lg3Ah0NkFaCs9sTkQAQA8kw7xiRXzENi9Rtw==",
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://paulmillr.com/funding/"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@noble/hashes": "~1.2.0",
+ "@noble/secp256k1": "~1.7.0",
+ "@scure/base": "~1.1.0"
+ }
+ },
+ "node_modules/hardhat/node_modules/@scure/bip39": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@scure/bip39/-/bip39-1.1.1.tgz",
+ "integrity": "sha512-t+wDck2rVkh65Hmv280fYdVdY25J9YeEUIgn2LG1WM6gxFkGzcksoDiUkWVpVp3Oex9xGC68JU2dSbUfwZ2jPg==",
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://paulmillr.com/funding/"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@noble/hashes": "~1.2.0",
+ "@scure/base": "~1.1.0"
+ }
+ },
+ "node_modules/hardhat/node_modules/ansi-styles": {
+ "version": "3.2.1",
+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz",
+ "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==",
+ "license": "MIT",
+ "dependencies": {
+ "color-convert": "^1.9.0"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/hardhat/node_modules/balanced-match": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
+ "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
+ "license": "MIT"
+ },
+ "node_modules/hardhat/node_modules/brace-expansion": {
+ "version": "1.1.18",
+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz",
+ "integrity": "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==",
+ "license": "MIT",
+ "dependencies": {
+ "balanced-match": "^1.0.0",
+ "concat-map": "0.0.1"
+ }
+ },
+ "node_modules/hardhat/node_modules/chalk": {
+ "version": "2.4.2",
+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz",
+ "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==",
+ "license": "MIT",
+ "dependencies": {
+ "ansi-styles": "^3.2.1",
+ "escape-string-regexp": "^1.0.5",
+ "supports-color": "^5.3.0"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/hardhat/node_modules/chokidar": {
+ "version": "3.6.0",
+ "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz",
+ "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==",
+ "license": "MIT",
+ "dependencies": {
+ "anymatch": "~3.1.2",
+ "braces": "~3.0.2",
+ "glob-parent": "~5.1.2",
+ "is-binary-path": "~2.1.0",
+ "is-glob": "~4.0.1",
+ "normalize-path": "~3.0.0",
+ "readdirp": "~3.6.0"
+ },
+ "engines": {
+ "node": ">= 8.10.0"
+ },
+ "funding": {
+ "url": "https://paulmillr.com/funding/"
+ },
+ "optionalDependencies": {
+ "fsevents": "~2.3.2"
+ }
+ },
+ "node_modules/hardhat/node_modules/ci-info": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-2.0.0.tgz",
+ "integrity": "sha512-5tK7EtrZ0N+OLFMthtqOj4fI2Jeb88C4CAZPu25LDVUgXJ0A3Js4PMGqrn0JU1W0Mh1/Z8wZzYPxqUrXeBboCQ==",
+ "license": "MIT"
+ },
+ "node_modules/hardhat/node_modules/color-convert": {
+ "version": "1.9.3",
+ "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz",
+ "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==",
+ "license": "MIT",
+ "dependencies": {
+ "color-name": "1.1.3"
+ }
+ },
+ "node_modules/hardhat/node_modules/color-name": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz",
+ "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==",
+ "license": "MIT"
+ },
+ "node_modules/hardhat/node_modules/escape-string-regexp": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz",
+ "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.8.0"
+ }
+ },
+ "node_modules/hardhat/node_modules/ethereum-cryptography": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/ethereum-cryptography/-/ethereum-cryptography-1.2.0.tgz",
+ "integrity": "sha512-6yFQC9b5ug6/17CQpCyE3k9eKBMdhyVjzUy1WkiuY/E4vj/SXDBbCw8QEIaXqf0Mf2SnY6RmpDcwlUmBSS0EJw==",
+ "license": "MIT",
+ "dependencies": {
+ "@noble/hashes": "1.2.0",
+ "@noble/secp256k1": "1.7.1",
+ "@scure/bip32": "1.1.5",
+ "@scure/bip39": "1.1.1"
+ }
+ },
+ "node_modules/hardhat/node_modules/find-up": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/find-up/-/find-up-2.1.0.tgz",
+ "integrity": "sha512-NWzkk0jSJtTt08+FBFMvXoeZnOJD+jTtsRmBYbAIzJdX6l7dLgR7CTubCM5/eDdPUBvLCeVasP1brfVR/9/EZQ==",
+ "license": "MIT",
+ "dependencies": {
+ "locate-path": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/hardhat/node_modules/fs-extra": {
+ "version": "7.0.1",
+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-7.0.1.tgz",
+ "integrity": "sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw==",
+ "license": "MIT",
+ "dependencies": {
+ "graceful-fs": "^4.1.2",
+ "jsonfile": "^4.0.0",
+ "universalify": "^0.1.0"
+ },
+ "engines": {
+ "node": ">=6 <7 || >=8"
+ }
+ },
+ "node_modules/hardhat/node_modules/glob": {
+ "version": "7.2.0",
+ "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.0.tgz",
+ "integrity": "sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q==",
+ "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]",
+ "license": "ISC",
+ "dependencies": {
+ "fs.realpath": "^1.0.0",
+ "inflight": "^1.0.4",
+ "inherits": "2",
+ "minimatch": "^3.0.4",
+ "once": "^1.3.0",
+ "path-is-absolute": "^1.0.0"
+ },
+ "engines": {
+ "node": "*"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
+ "node_modules/hardhat/node_modules/glob-parent": {
+ "version": "5.1.2",
+ "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",
+ "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==",
+ "license": "ISC",
+ "dependencies": {
+ "is-glob": "^4.0.1"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
+ "node_modules/hardhat/node_modules/has-flag": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz",
+ "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/hardhat/node_modules/immutable": {
+ "version": "4.3.9",
+ "resolved": "https://registry.npmjs.org/immutable/-/immutable-4.3.9.tgz",
+ "integrity": "sha512-ObHy4YN7ycwZOUCLI1/6svfyAFu7vL8RhAvVu/bh/RZW9EPlOyDaQ9jDQWCtdqzaXUjgXZCW1migtHE7YI7UGQ==",
+ "license": "MIT"
+ },
+ "node_modules/hardhat/node_modules/jsonfile": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz",
+ "integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==",
+ "license": "MIT",
+ "optionalDependencies": {
+ "graceful-fs": "^4.1.6"
+ }
+ },
+ "node_modules/hardhat/node_modules/locate-path": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-2.0.0.tgz",
+ "integrity": "sha512-NCI2kiDkyR7VeEKm27Kda/iQHyKJe1Bu0FlTbYp3CqJu+9IFe9bLyAjMxf5ZDDbEg+iMPzB5zYyUTSm8wVTKmA==",
+ "license": "MIT",
+ "dependencies": {
+ "p-locate": "^2.0.0",
+ "path-exists": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/hardhat/node_modules/minimatch": {
+ "version": "3.1.5",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",
+ "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",
+ "license": "ISC",
+ "dependencies": {
+ "brace-expansion": "^1.1.7"
+ },
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/hardhat/node_modules/p-limit": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-1.3.0.tgz",
+ "integrity": "sha512-vvcXsLAJ9Dr5rQOPk7toZQZJApBl2K4J6dANSsEuh6QI41JYcsS/qhTGa9ErIUUgK3WNQoJYvylxvjqmiqEA9Q==",
+ "license": "MIT",
+ "dependencies": {
+ "p-try": "^1.0.0"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/hardhat/node_modules/p-locate": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-2.0.0.tgz",
+ "integrity": "sha512-nQja7m7gSKuewoVRen45CtVfODR3crN3goVQ0DDZ9N3yHxgpkuBhZqsaiotSQRrADUrne346peY7kT3TSACykg==",
+ "license": "MIT",
+ "dependencies": {
+ "p-limit": "^1.1.0"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/hardhat/node_modules/p-try": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/p-try/-/p-try-1.0.0.tgz",
+ "integrity": "sha512-U1etNYuMJoIz3ZXSrrySFjsXQTWOx2/jdi86L+2pRvph/qMKL6sbcCYdH23fqsbm8TH2Gn0OybpT4eSFlCVHww==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/hardhat/node_modules/path-exists": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz",
+ "integrity": "sha512-bpC7GYwiDYQ4wYLe+FA8lhRjhQCMcQGuSgGGqDkg/QerRWw9CmGRT0iSOVRSZJ29NMLZgIzqaljJ63oaL4NIJQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/hardhat/node_modules/picomatch": {
+ "version": "2.3.2",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz",
+ "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8.6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
+ "node_modules/hardhat/node_modules/readdirp": {
+ "version": "3.6.0",
+ "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz",
+ "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==",
+ "license": "MIT",
+ "dependencies": {
+ "picomatch": "^2.2.1"
+ },
+ "engines": {
+ "node": ">=8.10.0"
+ }
+ },
+ "node_modules/hardhat/node_modules/resolve": {
+ "version": "1.17.0",
+ "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.17.0.tgz",
+ "integrity": "sha512-ic+7JYiV8Vi2yzQGFWOkiZD5Z9z7O2Zhm9XMaTxdJExKasieFCr+yXZ/WmXsckHiKl12ar0y6XiXDx3m4RHn1w==",
+ "license": "MIT",
+ "dependencies": {
+ "path-parse": "^1.0.6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/hardhat/node_modules/supports-color": {
+ "version": "5.5.0",
+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz",
+ "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==",
+ "license": "MIT",
+ "dependencies": {
+ "has-flag": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/hardhat/node_modules/undici": {
+ "version": "6.28.0",
+ "resolved": "https://registry.npmjs.org/undici/-/undici-6.28.0.tgz",
+ "integrity": "sha512-LIY910g9TI13YS95lrMFrs8Rm/u/irgHeTWoKCoteeJ04CUJ92eEfj0rVn+7VKMPBpUPiUoBKfhNyLI23EE/KA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18.17"
+ }
+ },
+ "node_modules/hardhat/node_modules/universalify": {
+ "version": "0.1.2",
+ "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz",
+ "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 4.0.0"
+ }
+ },
+ "node_modules/hardhat/node_modules/uuid": {
+ "version": "8.3.2",
+ "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
+ "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==",
+ "deprecated": "uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).",
+ "license": "MIT",
+ "bin": {
+ "uuid": "dist/bin/uuid"
+ }
+ },
"node_modules/has-bigints": {
"version": "1.1.0",
"dev": true,
@@ -28840,6 +30497,16 @@
"version": "3.0.8",
"license": "MIT"
},
+ "node_modules/js-sdsl": {
+ "version": "4.4.2",
+ "resolved": "https://registry.npmjs.org/js-sdsl/-/js-sdsl-4.4.2.tgz",
+ "integrity": "sha512-dwXFwByc/ajSV6m5bcKAPwe4yDDF6D614pxmIi5odytzxRlwqF6nwoiCek80Ixc7Cvma5awClxrzFtxCQvcM8w==",
+ "license": "MIT",
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/js-sdsl"
+ }
+ },
"node_modules/js-sha3": {
"version": "0.8.0",
"license": "MIT"
@@ -29018,7 +30685,6 @@
},
"node_modules/jsonfile": {
"version": "6.2.0",
- "dev": true,
"license": "MIT",
"dependencies": {
"universalify": "^2.0.0"
@@ -29376,6 +31042,46 @@
"multiformats": "^14.0.0"
}
},
+ "node_modules/level": {
+ "version": "8.0.1",
+ "resolved": "https://registry.npmjs.org/level/-/level-8.0.1.tgz",
+ "integrity": "sha512-oPBGkheysuw7DmzFQYyFe8NAia5jFLAgEnkgWnK3OXAuJr8qFT+xBQIwokAZPME2bhPFzS8hlYcL16m8UZrtwQ==",
+ "license": "MIT",
+ "dependencies": {
+ "abstract-level": "^1.0.4",
+ "browser-level": "^1.0.1",
+ "classic-level": "^1.2.0"
+ },
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/level"
+ }
+ },
+ "node_modules/level-supports": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/level-supports/-/level-supports-4.0.1.tgz",
+ "integrity": "sha512-PbXpve8rKeNcZ9C1mUicC9auIYFyGpkV9/i6g76tLgANwWhtG2v7I4xNBUlkn3lE2/dZF3Pi0ygYGtLc4RXXdA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/level-transcoder": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/level-transcoder/-/level-transcoder-1.0.1.tgz",
+ "integrity": "sha512-t7bFwFtsQeD8cl8NIoQ2iwxA0CL/9IFw7/9gAjOonH0PWTTiRfY7Hq+Ejbsxh86tXobDQ6IOiddjNYIfOBs06w==",
+ "license": "MIT",
+ "dependencies": {
+ "buffer": "^6.0.3",
+ "module-error": "^1.0.1"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
"node_modules/leven": {
"version": "3.1.0",
"license": "MIT",
@@ -30787,6 +32493,15 @@
"node": ">= 0.4"
}
},
+ "node_modules/mcl-wasm": {
+ "version": "0.7.9",
+ "resolved": "https://registry.npmjs.org/mcl-wasm/-/mcl-wasm-0.7.9.tgz",
+ "integrity": "sha512-iJIUcQWA88IJB/5L15GnJVnSQJmf/YaxxV6zRavv83HILHaJQb6y0iFyDMdDO0gN8X37tdxmAOrH/P8B6RB8sQ==",
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=8.9.0"
+ }
+ },
"node_modules/md5": {
"version": "2.3.0",
"license": "BSD-3-Clause",
@@ -30821,6 +32536,20 @@
"version": "6.0.0",
"license": "MIT"
},
+ "node_modules/memory-level": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/memory-level/-/memory-level-1.0.0.tgz",
+ "integrity": "sha512-UXzwewuWeHBz5krr7EvehKcmLFNoXxGcvuYhC41tRnkrTbJohtS7kVn9akmgirtRygg+f7Yjsfi8Uu5SGSQ4Og==",
+ "license": "MIT",
+ "dependencies": {
+ "abstract-level": "^1.0.0",
+ "functional-red-black-tree": "^1.0.1",
+ "module-error": "^1.0.1"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
"node_modules/memorystream": {
"version": "0.3.1",
"engines": {
@@ -31282,6 +33011,15 @@
"version": "1.0.4",
"license": "MIT"
},
+ "node_modules/module-error": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/module-error/-/module-error-1.0.2.tgz",
+ "integrity": "sha512-0yuvsqSCv8LbaOKhnsQ/T5JhyFlCYLPXK3U2sgV10zoKQwzs/MyfuQUOZQ1V/6OCOJsK/TRgNVrPuPDqtdMFtA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ }
+ },
"node_modules/mortice": {
"version": "3.3.1",
"license": "Apache-2.0 OR MIT",
@@ -31446,6 +33184,12 @@
"version": "2.0.0",
"license": "MIT"
},
+ "node_modules/napi-macros": {
+ "version": "2.2.2",
+ "resolved": "https://registry.npmjs.org/napi-macros/-/napi-macros-2.2.2.tgz",
+ "integrity": "sha512-hmEVtAGYzVQpCKdbQea4skABsdXW4RUh5t5mJ2zzqowJS2OyXZTU1KhDVFhx+NlWZ4ap9mqR9TcDO3LTTttd+g==",
+ "license": "MIT"
+ },
"node_modules/napi-postinstall": {
"version": "0.3.4",
"dev": true,
@@ -33674,6 +35418,15 @@
"node": ">=4"
}
},
+ "node_modules/reduce-flatten": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/reduce-flatten/-/reduce-flatten-2.0.0.tgz",
+ "integrity": "sha512-EJ4UNY/U1t2P/2k6oqotuX2Cc3T6nxJwsM0N0asT7dhrtH1ltUxDn4NalSYmPE2rCkVpcf/X6R0wDwcFpzhd4w==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
"node_modules/reflect-metadata": {
"version": "0.2.2",
"license": "Apache-2.0"
@@ -33977,14 +35730,6 @@
"dev": true,
"license": "MIT"
},
- "node_modules/rollup-plugin-node-polyfills": {
- "version": "0.2.1",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "rollup-plugin-inject": "^3.0.0"
- }
- },
"node_modules/rollup-pluginutils": {
"version": "2.8.2",
"dev": true,
@@ -34073,6 +35818,35 @@
"queue-microtask": "^1.2.2"
}
},
+ "node_modules/run-parallel-limit": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/run-parallel-limit/-/run-parallel-limit-1.1.0.tgz",
+ "integrity": "sha512-jJA7irRNM91jaKc3Hcl1npHsFLOXOoTkPCUL1JEa1R82O2miplXXRaGdjW/KM/98YQWDhJLiSs793CnXfblJUw==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "queue-microtask": "^1.2.2"
+ }
+ },
+ "node_modules/rustbn.js": {
+ "version": "0.2.0",
+ "resolved": "https://registry.npmjs.org/rustbn.js/-/rustbn.js-0.2.0.tgz",
+ "integrity": "sha512-4VlvkRUuCJvr2J6Y0ImW7NvTCriMi7ErOAqWk1y69vAdoNIzCF3yPmgeNzx+RQTLEDFq5sHfscn1MwHxP9hNfA==",
+ "license": "(MIT OR Apache-2.0)"
+ },
"node_modules/rxjs": {
"version": "7.8.2",
"license": "Apache-2.0",
@@ -35886,6 +37660,12 @@
"safe-buffer": "~5.2.0"
}
},
+ "node_modules/string-format": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/string-format/-/string-format-2.0.0.tgz",
+ "integrity": "sha512-bbEs3scLeYNXLecRRuk6uJxdXUSj6le/8rNPHChIJTn2V79aXVTR1EH2OH5zLKKoz0V02fOUKZZcw01pLUShZA==",
+ "license": "WTFPL OR MIT"
+ },
"node_modules/string-length": {
"version": "4.0.2",
"license": "MIT",
@@ -36314,6 +38094,39 @@
"url": "https://opencollective.com/synckit"
}
},
+ "node_modules/table-layout": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/table-layout/-/table-layout-1.0.2.tgz",
+ "integrity": "sha512-qd/R7n5rQTRFi+Zf2sk5XVVd9UQl6ZkduPFC3S7WEGJAmetDTjY3qPN50eSKzwuzEyQKy5TN2TiZdkIjos2L6A==",
+ "license": "MIT",
+ "dependencies": {
+ "array-back": "^4.0.1",
+ "deep-extend": "~0.6.0",
+ "typical": "^5.2.0",
+ "wordwrapjs": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=8.0.0"
+ }
+ },
+ "node_modules/table-layout/node_modules/array-back": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/array-back/-/array-back-4.0.2.tgz",
+ "integrity": "sha512-NbdMezxqf94cnNfWLL7V/im0Ub+Anbb0IoZhvzie8+4HJ4nMQuzHuy49FkGYCJK2yAloZ3meiB6AVMClbrI1vg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/table-layout/node_modules/typical": {
+ "version": "5.2.0",
+ "resolved": "https://registry.npmjs.org/typical/-/typical-5.2.0.tgz",
+ "integrity": "sha512-dvdQgNDNJo+8B2uBQoqdb11eUCE1JQXhvjC/CZtgvZseVd5TYMXnq0+vuUemXbd/Se29cTaUuPX3YIc2xgbvIg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/tar-fs": {
"version": "3.1.2",
"license": "MIT",
@@ -36721,6 +38534,46 @@
"typescript": ">=4.8.4"
}
},
+ "node_modules/ts-command-line-args": {
+ "version": "2.5.1",
+ "resolved": "https://registry.npmjs.org/ts-command-line-args/-/ts-command-line-args-2.5.1.tgz",
+ "integrity": "sha512-H69ZwTw3rFHb5WYpQya40YAX2/w7Ut75uUECbgBIsLmM+BNuYnxsltfyyLMxy6sEeKxgijLTnQtLd0nKd6+IYw==",
+ "license": "ISC",
+ "dependencies": {
+ "chalk": "^4.1.0",
+ "command-line-args": "^5.1.1",
+ "command-line-usage": "^6.1.0",
+ "string-format": "^2.0.0"
+ },
+ "bin": {
+ "write-markdown": "dist/write-markdown.js"
+ }
+ },
+ "node_modules/ts-command-line-args/node_modules/chalk": {
+ "version": "4.1.2",
+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
+ "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
+ "license": "MIT",
+ "dependencies": {
+ "ansi-styles": "^4.1.0",
+ "supports-color": "^7.1.0"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/chalk?sponsor=1"
+ }
+ },
+ "node_modules/ts-essentials": {
+ "version": "7.0.3",
+ "resolved": "https://registry.npmjs.org/ts-essentials/-/ts-essentials-7.0.3.tgz",
+ "integrity": "sha512-8+gr5+lqO3G84KdiTSMRLtuyJ+nTBVRKuCrK4lidMPdVeEp0uqC875uE5NMcaA7YYMN7XsNiFQuMvasF8HT/xQ==",
+ "license": "MIT",
+ "peerDependencies": {
+ "typescript": ">=3.7.0"
+ }
+ },
"node_modules/ts-interface-checker": {
"version": "0.1.13",
"dev": true,
@@ -37541,6 +39394,126 @@
"url": "https://opencollective.com/express"
}
},
+ "node_modules/typechain": {
+ "version": "8.3.2",
+ "resolved": "https://registry.npmjs.org/typechain/-/typechain-8.3.2.tgz",
+ "integrity": "sha512-x/sQYr5w9K7yv3es7jo4KTX05CLxOf7TRWwoHlrjRh8H82G64g+k7VuWPJlgMo6qrjfCulOdfBjiaDtmhFYD/Q==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/prettier": "^2.1.1",
+ "debug": "^4.3.1",
+ "fs-extra": "^7.0.0",
+ "glob": "7.1.7",
+ "js-sha3": "^0.8.0",
+ "lodash": "^4.17.15",
+ "mkdirp": "^1.0.4",
+ "prettier": "^2.3.1",
+ "ts-command-line-args": "^2.2.0",
+ "ts-essentials": "^7.0.1"
+ },
+ "bin": {
+ "typechain": "dist/cli/cli.js"
+ },
+ "peerDependencies": {
+ "typescript": ">=4.3.0"
+ }
+ },
+ "node_modules/typechain/node_modules/balanced-match": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
+ "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
+ "license": "MIT"
+ },
+ "node_modules/typechain/node_modules/brace-expansion": {
+ "version": "1.1.18",
+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz",
+ "integrity": "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==",
+ "license": "MIT",
+ "dependencies": {
+ "balanced-match": "^1.0.0",
+ "concat-map": "0.0.1"
+ }
+ },
+ "node_modules/typechain/node_modules/fs-extra": {
+ "version": "7.0.1",
+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-7.0.1.tgz",
+ "integrity": "sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw==",
+ "license": "MIT",
+ "dependencies": {
+ "graceful-fs": "^4.1.2",
+ "jsonfile": "^4.0.0",
+ "universalify": "^0.1.0"
+ },
+ "engines": {
+ "node": ">=6 <7 || >=8"
+ }
+ },
+ "node_modules/typechain/node_modules/glob": {
+ "version": "7.1.7",
+ "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.7.tgz",
+ "integrity": "sha512-OvD9ENzPLbegENnYP5UUfJIirTg4+XwMWGaQfQTY0JenxNvvIKP3U3/tAQSPIu/lHxXYSZmpXlUHeqAIdKzBLQ==",
+ "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]",
+ "license": "ISC",
+ "dependencies": {
+ "fs.realpath": "^1.0.0",
+ "inflight": "^1.0.4",
+ "inherits": "2",
+ "minimatch": "^3.0.4",
+ "once": "^1.3.0",
+ "path-is-absolute": "^1.0.0"
+ },
+ "engines": {
+ "node": "*"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
+ "node_modules/typechain/node_modules/jsonfile": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz",
+ "integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==",
+ "license": "MIT",
+ "optionalDependencies": {
+ "graceful-fs": "^4.1.6"
+ }
+ },
+ "node_modules/typechain/node_modules/minimatch": {
+ "version": "3.1.5",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",
+ "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",
+ "license": "ISC",
+ "dependencies": {
+ "brace-expansion": "^1.1.7"
+ },
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/typechain/node_modules/prettier": {
+ "version": "2.8.8",
+ "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.8.8.tgz",
+ "integrity": "sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==",
+ "license": "MIT",
+ "bin": {
+ "prettier": "bin-prettier.js"
+ },
+ "engines": {
+ "node": ">=10.13.0"
+ },
+ "funding": {
+ "url": "https://github.com/prettier/prettier?sponsor=1"
+ }
+ },
+ "node_modules/typechain/node_modules/universalify": {
+ "version": "0.1.2",
+ "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz",
+ "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 4.0.0"
+ }
+ },
"node_modules/typed-array-buffer": {
"version": "1.0.3",
"license": "MIT",
@@ -37655,6 +39628,15 @@
"typescript": ">=4.8.4 <6.1.0"
}
},
+ "node_modules/typical": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/typical/-/typical-4.0.0.tgz",
+ "integrity": "sha512-VAH4IvQ7BDFYglMd7BPRDfLgxZZX4O4TFcRDA6EN5X7erNJJq+McIEp8np9aVtxrCJ6qx4GTYVfOWNjcqwZgRw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/ufo": {
"version": "1.6.4",
"license": "MIT"
@@ -37807,7 +39789,6 @@
},
"node_modules/universalify": {
"version": "2.0.1",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">= 10.0.0"
@@ -39252,6 +41233,28 @@
"version": "1.0.0",
"license": "MIT"
},
+ "node_modules/wordwrapjs": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/wordwrapjs/-/wordwrapjs-4.0.1.tgz",
+ "integrity": "sha512-kKlNACbvHrkpIw6oPeYDSmdCTu2hdMHoyXLTcUKala++lx5Y+wjJ/e474Jqv5abnVmwxw08DiTuHmw69lJGksA==",
+ "license": "MIT",
+ "dependencies": {
+ "reduce-flatten": "^2.0.0",
+ "typical": "^5.2.0"
+ },
+ "engines": {
+ "node": ">=8.0.0"
+ }
+ },
+ "node_modules/wordwrapjs/node_modules/typical": {
+ "version": "5.2.0",
+ "resolved": "https://registry.npmjs.org/typical/-/typical-5.2.0.tgz",
+ "integrity": "sha512-dvdQgNDNJo+8B2uBQoqdb11eUCE1JQXhvjC/CZtgvZseVd5TYMXnq0+vuUemXbd/Se29cTaUuPX3YIc2xgbvIg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/workbox-background-sync": {
"version": "7.4.1",
"dev": true,
diff --git a/package.json b/package.json
index 529e92d73..a74b7fc62 100644
--- a/package.json
+++ b/package.json
@@ -116,7 +116,8 @@
"tour-sdk",
"packages/alibaba-cloud-mcp",
"packages/tool-sdk",
- "packages/spatial-mcp"
+ "packages/spatial-mcp",
+ "packages/agent-runtime"
],
"main": "src/app.js",
"browserslist": [
diff --git a/packages/agent-runtime/LICENSE b/packages/agent-runtime/LICENSE
new file mode 100644
index 000000000..dff21b7f4
--- /dev/null
+++ b/packages/agent-runtime/LICENSE
@@ -0,0 +1,20 @@
+Copyright 2026 nirholas
+
+All rights reserved.
+
+This software is proprietary and may not be used, copied, modified, distributed,
+translated, or made available to any third party without the express written
+permission of the copyright owner.
+
+No rights are granted by implication, estoppel, or otherwise. Use of this
+software is subject to the terms of a separate license agreement with the
+copyright owner.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT.
+
+IN NO EVENT SHALL THE COPYRIGHT OWNER BE LIABLE FOR ANY CLAIM, DAMAGES, OR
+OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE,
+ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
diff --git a/packages/agent-runtime/README.md b/packages/agent-runtime/README.md
new file mode 100644
index 000000000..ea59cb5ac
--- /dev/null
+++ b/packages/agent-runtime/README.md
@@ -0,0 +1,180 @@
+<p align="center">
+ <a href="https://three.ws"><img src="https://three.ws/three-ws-mcp-icon.svg" width="72" height="72" alt="three.ws" /></a>
+</p>
+
+<h1 align="center">@three-ws/agent-runtime</h1>
+
+<p align="center"><strong>The three.ws agent engine - a plan/execute decision loop with a seven-layer guard chain, a tamper-evident action ledger, and a multi-step transaction pipeline.</strong></p>
+
+<p align="center">
+ <a href="#quick-start">Quick start</a> ·
+ <a href="#the-guardchain">GuardChain</a> ·
+ <a href="#the-decision-loop">Decision loop</a> ·
+ <a href="#action-ledger">Action ledger</a> ·
+ <a href="https://three.ws">three.ws</a>
+</p>
+
+---
+
+> The runtime that sits between a model and anything irreversible. The
+> **decision loop** turns an LLM into an agent (plan, call tools, pause for
+> humans, finish); the **GuardChain** composes every enforcement layer into one
+> deterministic verdict with a per-layer trace; the **action ledger** makes the
+> resulting history tamper-evident. It is pure engine: no chain SDKs, no
+> database, no HTTP - every external fact is injected, which is why the same
+> code path serves the live `/api/agent/guard` preflight, simulators, and
+> tests. Powers the transaction-guard preflight in [three.ws/chat](https://three.ws/chat).
+
+## Why
+
+An agent that can call `solana_transfer` is one bad tool call away from an
+empty wallet. Most stacks scatter their defenses: an approval modal here, a
+spend cap there, a blacklist somewhere else - each invoked from a different
+place, with different inputs, and *nothing that can answer which layer would
+stop a given call, or which layers would silently not evaluate it at all*.
+A guard that never runs looks exactly like a guard that passed.
+
+This package makes enforcement composable and observable:
+
+| Piece | What it does |
+|---|---|
+| `AgentRuntime` | Plan → execute loop: `call_llm`, `call_tool`, batches, `finish`, and three human-in-the-loop instructions (`approve` / `prompt` / `select`), with cost limits, interrupts, and resume |
+| `GeneralChatAgent` | The default "brain": routes phases to instructions, splits tool calls into execute-now vs. needs-approval, compresses context when it outgrows the window |
+| `GuardChain` | Runs all seven layers over one call, returns decision + per-layer trace + **blind spots** (enforcement that should have applied but didn't) + a coverage score |
+| `TradeGuard` | Default domain guard: tier per-tx caps, rolling 24h/7d windows, auto-execute ceiling, MEV slippage clamp, protocol audit lookup |
+| `SpendGuard` | Per-agent spend envelope: per-tx / rolling / daily caps, reserve floor, token + destination firewall, custody-breach latch |
+| `InterventionChecker` | Policy engine for human approval (`never` / `required` / `always`, argument-level rules, security blacklist) |
+| `ActionLedger` | Hash-chained (sha256) append-only ledger primitives: `computeEntryHash`, `verifyChain`, drift audits |
+| `TransactionPipeline` | Multi-step plan execution: dependency order, parallel independent steps, rollback on failure, approval gates |
+| `DecisionJournal` | Fire-and-forget reasoning journal with an injected sink |
+| Reasoning utilities | `SelfReflection` (structured retry prompts), `ExitDecisionEngine`, `ResponseQualityEvaluator`, `ToolRelevanceScorer`, token counting + context-compression checks |
+
+## Install
+
+```bash
+npm install @three-ws/agent-runtime
+```
+
+ESM, Node 18+. One runtime dependency (`tokenx`, for token estimation).
+
+## Quick start
+
+### Preflight a tool call through every guard layer
+
+```js
+import { GuardChain, SpendGuard, TradeGuard, createX402Hook } from '@three-ws/agent-runtime';
+
+const chain = new GuardChain({
+ defiGuard: new TradeGuard(), // tier caps + slippage clamp
+ spendGuard: new SpendGuard({ perTxMaxUsd: 5_000 }), // hard envelope
+ x402Hook: createX402Hook(5), // $5/hour autonomy budget
+});
+
+const verdict = await chain.evaluate({
+ identifier: 'solana_swap',
+ apiName: 'solana_swap',
+ arguments: { inputMint: 'So11111111111111111111111111111111111111112', amount: 120, slippageBps: 300 },
+ valueUsd: 18_400,
+ userTier: 'pro',
+});
+
+verdict.decision; // 'require_approval' (above the auto-execute ceiling)
+verdict.blockedBy; // undefined
+verdict.modifiedArguments; // { ..., slippageBps: 100 } (MEV clamp)
+verdict.coverageScore; // 100
+verdict.blindSpots; // structured gaps, e.g. VALUE_UNRESOLVED, SPEND_UNSCOPED
+```
+
+The layer order is `security_blacklist → intervention → capability →
+permission → defi_guard → spend_guard → x402`. The chain never
+short-circuits: a call blocked by the spend envelope still reports the MEV
+exposure the trade guard saw, and every layer that could not evaluate the
+call says so instead of reading as "green".
+
+### Run the decision loop
+
+```js
+import { AgentRuntime, GeneralChatAgent } from '@three-ws/agent-runtime';
+
+const agent = new GeneralChatAgent({
+ modelRuntimeConfig: { model: 'llama-3.3-70b-versatile', provider: 'groq' },
+});
+agent.modelRuntime = myStreamingLlm; // async generator: yields { content?, tool_calls? }
+agent.tools = { get_price: async (args) => fetchPrice(args) };
+
+let state = AgentRuntime.createInitialState({ operationId: 'op-1' });
+state.messages.push({ role: 'user', content: 'What is SOL at?' });
+
+const runtime = new AgentRuntime(agent);
+let context;
+while (state.status !== 'done' && state.status !== 'error') {
+ const step = await runtime.step(state, context);
+ state = step.newState;
+ context = step.nextContext;
+ if (state.status === 'waiting_for_human') break; // surface state.pendingToolsCalling to the user
+}
+```
+
+When the user approves a pending call, continue with
+`runtime.approveToolCall(state, approvedCall)`. `runtime.interrupt()` /
+`runtime.resume()` cover cancellation.
+
+### Verify a ledger
+
+```js
+import { computeEntryHash, verifyChain } from '@three-ws/agent-runtime';
+
+const rows = await loadAgentLedger(agentId); // ordered rows from your store
+const result = verifyChain(rows);
+result.valid; // false if any historical row was edited or deleted
+result.brokenAt; // exact index where the chain first breaks
+```
+
+## Registering your tools
+
+The guard layers key off two module-level registries seeded with the three.ws
+tool surface (`solana_transfer`, `solana_swap`, `pumpfunBuy`, ...). A host
+adding a new fund-moving tool registers it at boot:
+
+```js
+import { registerFundMovingTool, registerMutatingApi } from '@three-ws/agent-runtime';
+
+registerFundMovingTool('my_bridge_tool');
+registerMutatingApi('executeBridgeV2');
+```
+
+An unregistered fund-moving tool is not "unguarded by design" - the GuardChain
+reports it as a critical `TOOL_UNREGISTERED` blind spot.
+
+## Where it runs on three.ws
+
+- **`POST /api/agent/guard`** preflights tool calls for the chat client: the
+ chat wallet tools (`solana_transfer`, `solana_swap`, `evm_*`, pump.fun
+ trades) are evaluated through this exact chain before their tool body runs,
+ a `block` verdict never reaches the wallet, and the transaction-approval
+ modal renders the verdict (decision, warnings, unchecked blind spots).
+- The server resolves SOL notionals (amount × live SOL price) before
+ evaluating, so dollar caps compare against real numbers.
+
+## Relation to `@three-ws/agent-guards`
+
+[`@three-ws/agent-guards`](../agent-guards) is the *client* for the platform's
+custodial wallet policy (it wraps `/api/agents/:id/trade` limits). This
+package is the *engine*: it evaluates arbitrary tool calls before execution
+anywhere - client wallets, custodial paths, simulators - and is what
+`/api/agent/guard` runs. The custodial trade path keeps its own enforcement;
+both speak the same language of per-tx/daily caps and deny-lists.
+
+## Provenance
+
+Core of the engine (decision loop, guard composition, spend envelope,
+pipeline) was battle-tested in a sibling project of the same author and
+ported here de-branded; the action ledger's hash-chain construction
+originated in the three.ws economy master ledger, so this is that design
+coming home. All chain-specific analysis was left behind: this package is
+chain-agnostic by construction, and three.ws wires Solana-first specifics
+(notional resolution, tool registries) at the edges.
+
+## License
+
+See [LICENSE](./LICENSE).
diff --git a/packages/agent-runtime/package.json b/packages/agent-runtime/package.json
new file mode 100644
index 000000000..1259ef66e
--- /dev/null
+++ b/packages/agent-runtime/package.json
@@ -0,0 +1,63 @@
+{
+ "name": "@three-ws/agent-runtime",
+ "version": "0.1.0",
+ "description": "The three.ws agent engine: a plan/execute decision loop with human-approval gates, a seven-layer GuardChain (security blacklist, intervention, capability, permission, trade guard, spend envelope, x402 budget), a tamper-evident hash-chained action ledger, and a multi-step transaction pipeline with rollback.",
+ "type": "module",
+ "main": "./src/index.js",
+ "module": "./src/index.js",
+ "types": "./src/index.d.ts",
+ "exports": {
+ ".": {
+ "types": "./src/index.d.ts",
+ "import": "./src/index.js",
+ "default": "./src/index.js"
+ },
+ "./core": {
+ "types": "./src/core/index.d.ts",
+ "import": "./src/core/index.js",
+ "default": "./src/core/index.js"
+ },
+ "./package.json": "./package.json"
+ },
+ "files": [
+ "src",
+ "README.md",
+ "LICENSE"
+ ],
+ "scripts": {
+ "test": "vitest run tests"
+ },
+ "keywords": [
+ "agent",
+ "agent-runtime",
+ "decision-loop",
+ "guardrails",
+ "spend-limit",
+ "human-in-the-loop",
+ "tool-calling",
+ "action-ledger",
+ "x402",
+ "solana",
+ "three.ws"
+ ],
+ "author": "nirholas <[email protected]>",
+ "license": "SEE LICENSE IN LICENSE",
+ "homepage": "https://three.ws",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/nirholas/three.ws.git",
+ "directory": "packages/agent-runtime"
+ },
+ "bugs": {
+ "url": "https://github.com/nirholas/three.ws/issues"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "dependencies": {
+ "tokenx": "^1.3.0"
+ },
+ "publishConfig": {
+ "access": "public"
+ }
+}
diff --git a/packages/agent-runtime/src/agents/GeneralChatAgent.d.ts b/packages/agent-runtime/src/agents/GeneralChatAgent.d.ts
new file mode 100644
index 000000000..f6cff332a
--- /dev/null
+++ b/packages/agent-runtime/src/agents/GeneralChatAgent.d.ts
@@ -0,0 +1,45 @@
+import { Agent, AgentInstruction, AgentRuntimeContext, AgentState, GeneralAgentConfig } from '../types/index.js';
+/**
+ * ChatAgent - The "Brain" of the chat agent
+ *
+ * This agent implements a simple but powerful decision loop:
+ * 1. user_input → call_llm (with optional RAG/Search preprocessing)
+ * 2. llm_result → check for tool_calls and intervention requirements
+ * - Tools not requiring intervention → call_tools_batch (execute immediately)
+ * - Tools requiring intervention → request_human_approve (wait for approval)
+ * - Mixed (both types) → [call_tools_batch, request_human_approve] (execute safe ones first, then request approval)
+ * - No tool_calls → finish
+ * 3. tools_batch_result → call_llm (process tool results)
+ *
+ */
+export declare class GeneralChatAgent implements Agent {
+ private config;
+ private defiGuard?;
+ constructor(config: GeneralAgentConfig);
+ /**
+ * Get intervention configuration for a specific tool call
+ */
+ private getToolInterventionConfig;
+ /**
+ * Check if tool calls need human intervention
+ * Combines user's global config with tool's own config
+ * Includes DeFi Guard analysis for mutating DeFi operations
+ * Returns [toolsNeedingIntervention, toolsToExecute]
+ */
+ private checkInterventionNeeded;
+ /**
+ * Extract abort information from current context and state
+ * Returns the necessary data to handle abort scenario
+ */
+ private extractAbortInfo;
+ /**
+ * Find existing compression summary from messages
+ * Looks for MessageGroup with type 'compression' and extracts its content
+ */
+ private findExistingSummary;
+ /**
+ * Handle abort scenario - unified abort handling logic
+ */
+ private handleAbort;
+ runner(context: AgentRuntimeContext, state: AgentState): Promise<AgentInstruction | AgentInstruction[]>;
+}
diff --git a/packages/agent-runtime/src/agents/GeneralChatAgent.js b/packages/agent-runtime/src/agents/GeneralChatAgent.js
new file mode 100644
index 000000000..68ba2748b
--- /dev/null
+++ b/packages/agent-runtime/src/agents/GeneralChatAgent.js
@@ -0,0 +1,519 @@
+import { DEFAULT_SECURITY_BLACKLIST, InterventionChecker } from '../core/index.js';
+import { shouldCompress } from '../utils/tokenCounter.js';
+/**
+ * ChatAgent - The "Brain" of the chat agent
+ *
+ * This agent implements a simple but powerful decision loop:
+ * 1. user_input → call_llm (with optional RAG/Search preprocessing)
+ * 2. llm_result → check for tool_calls and intervention requirements
+ * - Tools not requiring intervention → call_tools_batch (execute immediately)
+ * - Tools requiring intervention → request_human_approve (wait for approval)
+ * - Mixed (both types) → [call_tools_batch, request_human_approve] (execute safe ones first, then request approval)
+ * - No tool_calls → finish
+ * 3. tools_batch_result → call_llm (process tool results)
+ *
+ */
+export class GeneralChatAgent {
+ config;
+ defiGuard;
+ constructor(config) {
+ this.config = config;
+ this.defiGuard = config.domainGuard;
+ }
+ /**
+ * Get intervention configuration for a specific tool call
+ */
+ getToolInterventionConfig(toolCalling, state) {
+ const { identifier, apiName } = toolCalling;
+ const manifest = state.toolManifestMap[identifier];
+ if (!manifest)
+ return undefined;
+ // Find the specific API in the manifest
+ const api = manifest.api?.find((a) => a.name === apiName);
+ // API-level config takes precedence over tool-level config
+ return api?.humanIntervention ?? manifest.humanIntervention;
+ }
+ /**
+ * Check if tool calls need human intervention
+ * Combines user's global config with tool's own config
+ * Includes DeFi Guard analysis for mutating DeFi operations
+ * Returns [toolsNeedingIntervention, toolsToExecute]
+ */
+ async checkInterventionNeeded(toolsCalling, state) {
+ const toolsNeedingIntervention = [];
+ const toolsToExecute = [];
+ // Get security blacklist (use default if not provided)
+ const securityBlacklist = state.securityBlacklist ?? DEFAULT_SECURITY_BLACKLIST;
+ // Get user config (default to 'manual' mode)
+ const userConfig = state.userInterventionConfig || { approvalMode: 'manual' };
+ const { approvalMode, allowList = [] } = userConfig;
+ for (const toolCalling of toolsCalling) {
+ const { identifier, apiName } = toolCalling;
+ const toolKey = `${identifier}/${apiName}`;
+ // Parse arguments for intervention checking
+ let toolArgs = {};
+ try {
+ toolArgs = JSON.parse(toolCalling.arguments || '{}');
+ }
+ catch {
+ // Invalid JSON, treat as empty args
+ }
+ // Priority 0: CRITICAL - Check security blacklist FIRST
+ const securityCheck = InterventionChecker.checkSecurityBlacklist(securityBlacklist, toolArgs);
+ // Priority 0.5: Headless mode - fully automated for async tasks
+ // In headless mode: blacklisted tools are blocked with error feedback, all other tools execute directly
+ if (approvalMode === 'headless') {
+ if (securityCheck.blocked) {
+ // Return an explicit error so the LLM knows the tool was blocked
+ state.messages.push({
+ content: JSON.stringify({
+ blocked: true,
+ error: `Tool "${toolCalling.apiName}" was blocked by security policy: ${securityCheck.reason || 'Matches security blacklist'}. This tool cannot be executed in headless mode.`,
+ }),
+ role: 'tool',
+ tool_call_id: toolCalling.id,
+ });
+ continue;
+ }
+ // All other tools execute directly
+ toolsToExecute.push(toolCalling);
+ continue;
+ }
+ // For non-headless modes: security blacklist requires intervention
+ if (securityCheck.blocked) {
+ toolsNeedingIntervention.push(toolCalling);
+ continue;
+ }
+ // Priority 0.9: DeFi Guard - intercept mutating DeFi operations
+ if (this.defiGuard?.isDeFiTool(identifier) && this.defiGuard.isMutatingApi(apiName)) {
+ const guardResult = await this.defiGuard.analyze({
+ apiName,
+ arguments: toolArgs,
+ identifier,
+ portfolioPositions: state.portfolioPositions,
+ });
+ // Guard analysis is also performed server-side by ToolExecutionService;
+ // no need to attach the result to the tool calling object here.
+ if (guardResult.analysis.decision === 'block') {
+ // Blocked: inject error message so LLM knows
+ state.messages.push({
+ content: JSON.stringify({
+ blocked: true,
+ error: `DeFi Guard blocked this operation: ${guardResult.analysis.reason}`,
+ warnings: guardResult.analysis.warnings,
+ }),
+ role: 'tool',
+ tool_call_id: toolCalling.id,
+ });
+ continue;
+ }
+ if (guardResult.analysis.decision === 'require_approval') {
+ toolsNeedingIntervention.push(toolCalling);
+ continue;
+ }
+ // 'allow' - fall through to subsequent priority checks
+ }
+ // Priority 1: Check 'always' policy - overrides auto-run mode
+ // Some sensitive operations (e.g., installPlugin) must always require user confirmation
+ const config = this.getToolInterventionConfig(toolCalling, state);
+ const hasAlwaysPolicy = config === 'always' ||
+ (Array.isArray(config) &&
+ config.some((rule) => {
+ // Check if the 'always' rule matches current tool args
+ if (rule.policy !== 'always')
+ return false;
+ // If rule has match criteria, check if it matches
+ if (rule.match) {
+ return Object.entries(rule.match).every(([paramName, matcher]) => {
+ const paramValue = toolArgs[paramName];
+ if (paramValue === undefined)
+ return false;
+ // Simple string comparison for basic matching
+ if (typeof matcher === 'string') {
+ return String(paramValue).includes(matcher) || matcher.includes('*');
+ }
+ return true;
+ });
+ }
+ // No match criteria means it's a default 'always' rule
+ return true;
+ }));
+ if (hasAlwaysPolicy) {
+ toolsNeedingIntervention.push(toolCalling);
+ continue;
+ }
+ // Priority 2: User config is 'auto-run', all tools execute directly
+ if (approvalMode === 'auto-run') {
+ toolsToExecute.push(toolCalling);
+ continue;
+ }
+ // Priority 3: User config is 'allow-list', check if tool is in whitelist
+ if (approvalMode === 'allow-list') {
+ if (allowList.includes(toolKey)) {
+ toolsToExecute.push(toolCalling);
+ }
+ else {
+ toolsNeedingIntervention.push(toolCalling);
+ }
+ continue;
+ }
+ // Priority 4: User config is 'manual' (default), use tool's own config
+ // Note: config is already retrieved above for 'always' policy check
+ const policy = InterventionChecker.shouldIntervene({
+ config,
+ securityBlacklist,
+ toolArgs,
+ });
+ if (policy === 'never') {
+ toolsToExecute.push(toolCalling);
+ }
+ else {
+ // 'required' or undefined requires intervention
+ toolsNeedingIntervention.push(toolCalling);
+ }
+ }
+ return [toolsNeedingIntervention, toolsToExecute];
+ }
+ /**
+ * Extract abort information from current context and state
+ * Returns the necessary data to handle abort scenario
+ */
+ extractAbortInfo(context, state) {
+ let hasToolsCalling = false;
+ let toolsCalling = [];
+ let parentMessageId = '';
+ // Extract abort info based on current phase
+ switch (context.phase) {
+ case 'llm_result': {
+ const payload = context.payload;
+ hasToolsCalling = payload.hasToolsCalling || false;
+ toolsCalling = payload.toolsCalling || [];
+ parentMessageId = payload.parentMessageId;
+ break;
+ }
+ case 'human_abort': {
+ // When user cancels during LLM streaming, we enter human_abort phase
+ // The payload contains tool calls info if LLM had started returning them
+ const payload = context.payload;
+ hasToolsCalling = payload.hasToolsCalling || false;
+ toolsCalling = payload.toolsCalling || [];
+ parentMessageId = payload.parentMessageId;
+ break;
+ }
+ case 'tool_result':
+ case 'tools_batch_result': {
+ const payload = context.payload;
+ parentMessageId = payload.parentMessageId;
+ // Check if there are pending tool messages
+ const pendingToolMessages = state.messages.filter((m) => m.role === 'tool' && m.pluginIntervention?.status === 'pending');
+ if (pendingToolMessages.length > 0) {
+ hasToolsCalling = true;
+ toolsCalling = pendingToolMessages.map((m) => m.plugin).filter(Boolean);
+ }
+ break;
+ }
+ }
+ return { hasToolsCalling, parentMessageId, toolsCalling };
+ }
+ /**
+ * Find existing compression summary from messages
+ * Looks for MessageGroup with type 'compression' and extracts its content
+ */
+ findExistingSummary(messages) {
+ // Look for compression group summary in messages
+ // The summary is typically stored as a system message with compression metadata
+ // or as a MessageGroup content field
+ for (const msg of messages) {
+ if (msg.role === 'system' && msg.metadata?.compressionSummary) {
+ return msg.content;
+ }
+ // Check for MessageGroup type compression
+ if (msg.messageGroupType === 'compression' && msg.content) {
+ return msg.content;
+ }
+ }
+ return undefined;
+ }
+ /**
+ * Handle abort scenario - unified abort handling logic
+ */
+ handleAbort(context, state) {
+ const { hasToolsCalling, parentMessageId, toolsCalling } = this.extractAbortInfo(context, state);
+ // If there are pending tool calls, resolve them
+ if (hasToolsCalling && toolsCalling.length > 0) {
+ return {
+ payload: { parentMessageId, toolsCalling },
+ type: 'resolve_aborted_tools',
+ };
+ }
+ // No tools to resolve, directly finish
+ return {
+ reason: 'user_requested',
+ reasonDetail: 'Operation cancelled by user',
+ type: 'finish',
+ };
+ }
+ async runner(context, state) {
+ // Unified abort check: if operation is interrupted, handle abort scenario
+ // This check is placed before phase handling to ensure consistent abort behavior
+ if (state.status === 'interrupted') {
+ return this.handleAbort(context, state);
+ }
+ switch (context.phase) {
+ case 'init':
+ case 'user_input': {
+ // Check if context compression is enabled and needed before calling LLM
+ const compressionEnabled = this.config.compressionConfig?.enabled ?? true; // Default to enabled
+ if (compressionEnabled) {
+ const compressionCheck = shouldCompress(state.messages, {
+ maxWindowToken: this.config.compressionConfig?.maxWindowToken,
+ });
+ if (compressionCheck.needsCompression) {
+ // Context exceeds threshold, compress ALL messages into a single summary
+ return {
+ payload: {
+ currentTokenCount: compressionCheck.currentTokenCount,
+ existingSummary: this.findExistingSummary(state.messages),
+ messages: state.messages,
+ },
+ type: 'compress_context',
+ };
+ }
+ }
+ // User input received, call LLM to generate response
+ // At this point, messages may have been preprocessed with RAG/Search
+ return {
+ payload: {
+ ...context.payload,
+ messages: state.messages,
+ },
+ type: 'call_llm',
+ };
+ }
+ case 'llm_result': {
+ // LLM response received, check if it contains tool calls
+ const { hasToolsCalling, toolsCalling, parentMessageId } = context.payload;
+ if (hasToolsCalling && toolsCalling && toolsCalling.length > 0) {
+ // Check which tools need human intervention (includes DeFi Guard analysis)
+ const [toolsNeedingIntervention, toolsToExecute] = await this.checkInterventionNeeded(toolsCalling, state);
+ const instructions = [];
+ // Execute tools that don't need intervention first
+ // These will run immediately before any approval requests
+ if (toolsToExecute.length > 0) {
+ if (toolsToExecute.length > 1) {
+ instructions.push({
+ payload: {
+ parentMessageId,
+ toolsCalling: toolsToExecute,
+ },
+ type: 'call_tools_batch',
+ });
+ }
+ else {
+ instructions.push({
+ payload: {
+ parentMessageId,
+ toolCalling: toolsToExecute[0],
+ },
+ type: 'call_tool',
+ });
+ }
+ }
+ // Request approval for tools that need intervention
+ // Runtime will execute this after safe tools and pause with status='waiting_for_human'
+ if (toolsNeedingIntervention.length > 0) {
+ instructions.push({
+ pendingToolsCalling: toolsNeedingIntervention,
+ reason: 'human_intervention_required',
+ type: 'request_human_approve',
+ });
+ }
+ return instructions;
+ }
+ // No tool calls, conversation is complete
+ return {
+ reason: 'completed',
+ reasonDetail: 'LLM response completed without tool calls',
+ type: 'finish',
+ };
+ }
+ case 'tool_result': {
+ const { data, parentMessageId, stop } = context.payload;
+ // Check if this is a GTD async task request (only execTask/execTasks are passed here with stop=true)
+ if (stop && data?.state) {
+ const stateType = data.state.type;
+ // GTD async task (single)
+ if (stateType === 'execTask') {
+ const { parentMessageId: execParentId, task } = data.state;
+ return {
+ payload: { parentMessageId: execParentId, task },
+ type: 'exec_task',
+ };
+ }
+ // GTD async tasks (multiple)
+ if (stateType === 'execTasks') {
+ const { parentMessageId: execParentId, tasks } = data.state;
+ return {
+ payload: { parentMessageId: execParentId, tasks },
+ type: 'exec_tasks',
+ };
+ }
+ // GTD client-side async task (single, desktop only)
+ if (stateType === 'execClientTask') {
+ const { parentMessageId: execParentId, task } = data.state;
+ return {
+ payload: { parentMessageId: execParentId, task },
+ type: 'exec_client_task',
+ };
+ }
+ // GTD client-side async tasks (multiple, desktop only)
+ if (stateType === 'execClientTasks') {
+ const { parentMessageId: execParentId, tasks } = data.state;
+ return {
+ payload: { parentMessageId: execParentId, tasks },
+ type: 'exec_client_tasks',
+ };
+ }
+ }
+ // Check if there are still pending tool messages waiting for approval
+ const pendingToolMessages = state.messages.filter((m) => m.role === 'tool' && m.pluginIntervention?.status === 'pending');
+ // If there are pending tools, wait for human approval
+ if (pendingToolMessages.length > 0) {
+ const pendingTools = pendingToolMessages.map((m) => m.plugin).filter(Boolean);
+ return {
+ pendingToolsCalling: pendingTools,
+ reason: 'Some tools still pending approval',
+ skipCreateToolMessage: true,
+ type: 'request_human_approve',
+ };
+ }
+ // No pending tools, continue to call LLM with tool results
+ return {
+ payload: {
+ messages: state.messages,
+ model: this.config.modelRuntimeConfig?.model,
+ parentMessageId,
+ provider: this.config.modelRuntimeConfig?.provider,
+ tools: state.tools,
+ },
+ type: 'call_llm',
+ };
+ }
+ case 'tools_batch_result': {
+ const { parentMessageId } = context.payload;
+ // Check if there are still pending tool messages waiting for approval
+ const pendingToolMessages = state.messages.filter((m) => m.role === 'tool' && m.pluginIntervention?.status === 'pending');
+ // If there are pending tools, wait for human approval
+ if (pendingToolMessages.length > 0) {
+ const pendingTools = pendingToolMessages.map((m) => m.plugin).filter(Boolean);
+ return {
+ pendingToolsCalling: pendingTools,
+ reason: 'Some tools still pending approval',
+ skipCreateToolMessage: true,
+ type: 'request_human_approve',
+ };
+ }
+ // No pending tools, continue to call LLM with tool results
+ return {
+ payload: {
+ messages: state.messages,
+ model: this.config.modelRuntimeConfig?.model,
+ parentMessageId,
+ provider: this.config.modelRuntimeConfig?.provider,
+ tools: state.tools,
+ },
+ type: 'call_llm',
+ };
+ }
+ case 'task_result': {
+ // Single async task completed, continue to call LLM with result
+ const { parentMessageId } = context.payload;
+ // Continue to call LLM with updated messages (task message is already in state)
+ return {
+ payload: {
+ messages: state.messages,
+ model: this.config.modelRuntimeConfig?.model,
+ parentMessageId,
+ provider: this.config.modelRuntimeConfig?.provider,
+ tools: state.tools,
+ },
+ type: 'call_llm',
+ };
+ }
+ case 'tasks_batch_result': {
+ // Async tasks batch completed, continue to call LLM with results
+ const { parentMessageId } = context.payload;
+ // Inject a virtual user message to force the model to summarize or continue
+ // This fixes an issue where some models (e.g., Kimi K2) return empty content
+ // when the last message is a task result, thinking the task is already done
+ const messagesWithPrompt = [
+ ...state.messages,
+ {
+ content: 'All tasks above have been completed. Please summarize the results or continue with your response following user query language.',
+ role: 'user',
+ },
+ ];
+ // Continue to call LLM with updated messages (task messages are already in state)
+ return {
+ payload: {
+ messages: messagesWithPrompt,
+ model: this.config.modelRuntimeConfig?.model,
+ parentMessageId,
+ provider: this.config.modelRuntimeConfig?.provider,
+ tools: state.tools,
+ },
+ type: 'call_llm',
+ };
+ }
+ case 'compression_result': {
+ // Context compression completed, continue to call LLM
+ const compressionPayload = context.payload;
+ // If compression was skipped (no messages to compress), just call LLM
+ // Otherwise, messages have been updated with compressed content
+ // Pass parentMessageId and createAssistantMessage=true to force new message creation
+ return {
+ payload: {
+ // Force create new assistant message after compression
+ createAssistantMessage: true,
+ messages: compressionPayload.compressedMessages,
+ model: this.config.modelRuntimeConfig?.model,
+ parentMessageId: compressionPayload.parentMessageId,
+ provider: this.config.modelRuntimeConfig?.provider,
+ tools: state.tools,
+ },
+ type: 'call_llm',
+ };
+ }
+ case 'human_abort': {
+ // User aborted the operation
+ const { hasToolsCalling, parentMessageId, toolsCalling, reason } = context.payload;
+ // If there are pending tool calls, resolve them
+ if (hasToolsCalling && toolsCalling && toolsCalling.length > 0) {
+ return {
+ payload: { parentMessageId, toolsCalling },
+ type: 'resolve_aborted_tools',
+ };
+ }
+ // No tools to resolve, directly finish
+ return { reason: 'user_requested', reasonDetail: reason, type: 'finish' };
+ }
+ case 'error': {
+ // Error occurred, finish execution
+ const { error } = context.payload;
+ return {
+ reason: 'error_recovery',
+ reasonDetail: error?.message || 'Unknown error occurred',
+ type: 'finish',
+ };
+ }
+ default: {
+ // Unknown phase, finish execution
+ return {
+ reason: 'agent_decision',
+ reasonDetail: `Unknown phase: ${context.phase}`,
+ type: 'finish',
+ };
+ }
+ }
+ }
+}
diff --git a/packages/agent-runtime/src/agents/index.d.ts b/packages/agent-runtime/src/agents/index.d.ts
new file mode 100644
index 000000000..0f2715bc4
--- /dev/null
+++ b/packages/agent-runtime/src/agents/index.d.ts
@@ -0,0 +1 @@
+export * from './GeneralChatAgent.js';
diff --git a/packages/agent-runtime/src/agents/index.js b/packages/agent-runtime/src/agents/index.js
new file mode 100644
index 000000000..0f2715bc4
--- /dev/null
+++ b/packages/agent-runtime/src/agents/index.js
@@ -0,0 +1 @@
+export * from './GeneralChatAgent.js';
diff --git a/packages/agent-runtime/src/core/ActionLedger.d.ts b/packages/agent-runtime/src/core/ActionLedger.d.ts
new file mode 100644
index 000000000..d526c3891
--- /dev/null
+++ b/packages/agent-runtime/src/core/ActionLedger.d.ts
@@ -0,0 +1,164 @@
+/**
+ * ActionLedger - pure hash-chain primitives for the tamper-evident agent action ledger.
+ *
+ * Every value movement an agent initiates on-chain is recorded as one append-only row.
+ * Each row's `entryHash = sha256(canonicalFields ‖ prevHash)`, so the chain head commits the
+ * entire history (Merkle-equivalent): editing or deleting any historical row changes its
+ * `entryHash` and breaks every link from that point forward. `verifyChain()` walks a user's
+ * ordered rows and reports the exact index at which the chain first breaks.
+ *
+ * This module is intentionally I/O-free - no DB, no chain, no clock. It contains only the
+ * deterministic hashing and verification logic (the part that lifts near-verbatim from the
+ * three.ws `economy-ledger.js` hash construction). Storage is supplied by the host: the
+ * API layer injects `computeEntryHash` into its locked append so this package never depends on
+ * the database layer.
+ *
+ * Credits: hash-chain construction ported from the three.ws economy master ledger.
+ */
+/** Genesis link - the `prevHash` of the first entry in a user's chain (seq 1). */
+export declare const LEDGER_GENESIS_HASH: string;
+/**
+ * The canonicalisation field separator, re-exported for audit tooling.
+ *
+ * Load-bearing and frozen - it is folded into every hash ever written, so changing it would
+ * invalidate every existing chain. Exported so an audit bundle can state the exact construction a
+ * third party needs in order to re-derive the hashes offline, without that consumer having to
+ * hard-code a control character it cannot see.
+ */
+export declare const LEDGER_FIELD_SEPARATOR = "\0";
+/**
+ * The canonical field order folded into `entryHash`, in hash order. Purely descriptive - the
+ * authority is `canonicalizeEntry`, and `ActionLedger.test.ts` pins the two together so this
+ * cannot silently drift.
+ */
+export declare const LEDGER_CANONICAL_FIELD_ORDER: readonly ["seq", "ts", "userId", "agentId", "event", "target", "amountWei", "valueUsd", "txHash", "reason", "balanceBeforeWei", "balanceAfterWei", "network", "detail"];
+/** The kind of value-movement event a ledger row records. */
+export type LedgerEvent = 'transfer' | 'failed' | 'blocked' | 'sweep';
+/**
+ * The canonical, hash-committed fields of a ledger entry. Every field here is folded into
+ * `entryHash`; anything not listed (e.g. the surrogate row `id`) is metadata and MUST NOT
+ * affect the hash. Nullable fields are hashed as the empty string.
+ */
+export interface LedgerEntryInput {
+ /** Per-user monotonic sequence number, starting at 1. */
+ seq: number;
+ /** ISO-8601 timestamp of the entry, exactly as stored. */
+ ts: string;
+ /** Owner (multi-tenant isolation key). */
+ userId: string;
+ /** Agent that initiated the movement, if known. */
+ agentId: string | null;
+ event: LedgerEvent;
+ /** Recipient / counterparty address, if any. */
+ target: string | null;
+ /** Amount moved, in wei, as an exact decimal string (never a JS number). */
+ amountWei: string | null;
+ /** USD value at transfer time, if priced. */
+ valueUsd: number | null;
+ /** On-chain transaction hash, if the movement produced one. */
+ txHash: string | null;
+ /** Human-readable reason / provenance for the movement. */
+ reason: string | null;
+ /** Running balance (wei) before this movement. */
+ balanceBeforeWei: string | null;
+ /** Running balance (wei) after this movement. */
+ balanceAfterWei: string | null;
+ /** Network the movement occurred on (e.g. `ethereum`, `base`, `arbitrum`). */
+ network: string;
+ /** Free-form structured detail - hashed via stable (key-sorted) serialisation. */
+ detail: unknown;
+}
+/** A stored chain row: the committed input plus its recorded links. */
+export interface LedgerChainRow extends LedgerEntryInput {
+ prevHash: string;
+ entryHash: string;
+}
+/** Result of verifying a chain. */
+export interface ChainVerification {
+ valid: boolean;
+ /** Number of rows inspected. */
+ length: number;
+ /** 0-based index of the first broken row, or -1 when the chain is intact. */
+ brokenAtIndex: number;
+ /** `seq` of the first broken row, or null when intact. */
+ brokenAtSeq: number | null;
+ /** Why the chain broke, or null when intact. */
+ reason: string | null;
+}
+/**
+ * Produce the canonical string that gets hashed. Field order is fixed and load-bearing - never
+ * reorder it, or previously-written entries will fail verification.
+ */
+export declare const canonicalizeEntry: (entry: LedgerEntryInput) => string;
+/**
+ * Compute a row's `entryHash` from its canonical fields and the previous row's hash.
+ * `entryHash = sha256(canonical(entry) ‖ SEP ‖ prevHash)`.
+ */
+export declare const computeEntryHash: (entry: LedgerEntryInput, prevHash: string) => string;
+/** Where a windowed walk starts from. */
+export interface ChainWindowOptions {
+ /**
+ * The hash the first row's `prevHash` must equal. Defaults to the genesis hash, which is what
+ * makes a walk a whole-chain proof.
+ *
+ * Pass the previous page's `entryHash` to continue a walk across a page boundary, or the first
+ * row's own `prevHash` to check a window's internal consistency without anchoring it.
+ */
+ anchorHash?: string;
+}
+/**
+ * Verify a *window* of a user's chain. Identical to {@link verifyChain} except that the starting
+ * link is caller-supplied, so a page fetched from `seq > 1` can be checked without pretending it
+ * begins at genesis.
+ *
+ * A window anchored to anything other than the genesis hash proves the rows it holds were not
+ * altered relative to each other and relative to that anchor; it proves nothing about entries
+ * before the anchor. Callers must surface that distinction rather than presenting a window as a
+ * whole-chain proof.
+ */
+export declare const verifyChainWindow: (rows: readonly LedgerChainRow[], options?: ChainWindowOptions) => ChainVerification;
+/**
+ * Verify a user's ledger chain. `rows` must already be scoped to a single user; they are sorted
+ * by `seq` before walking. Returns the exact index/seq of the first break, so a reconcile job can
+ * pinpoint tampering. An empty chain is vacuously valid.
+ *
+ * Detects: a missing genesis link, a broken `prevHash` link between consecutive rows, and any row
+ * whose stored `entryHash` does not match a recomputation of its own committed fields.
+ */
+export declare const verifyChain: (rows: readonly LedgerChainRow[]) => ChainVerification;
+/** Per-row outcome of {@link auditChainRows}. */
+export interface LedgerRowCheck {
+ /** `seq` of the row this check describes. */
+ seq: number;
+ /** The hash stored on the row. */
+ storedHash: string;
+ /** The hash recomputed here from the row's own committed fields. */
+ computedHash: string;
+ /** `storedHash === computedHash` - the row's contents are exactly what was hashed. */
+ hashOk: boolean;
+ /** The row's `prevHash` matches its predecessor's `entryHash` (or the window anchor). */
+ linkOk: boolean;
+ /** What this row's `prevHash` was expected to be. */
+ expectedPrevHash: string;
+}
+/**
+ * Audit every row independently and report a per-row verdict, rather than stopping at the first
+ * break like {@link verifyChain} does. This is what a UI needs in order to mark exactly which
+ * entries are intact and which are not - a single break index cannot express that a later row is
+ * *also* self-consistent even though its link is orphaned.
+ *
+ * The walk always continues using each row's own `entryHash` as the next expected link, so one
+ * altered row invalidates its own `hashOk` and the following row's `linkOk` without cascading a
+ * false failure through the entire remainder of the chain.
+ */
+export declare const auditChainRows: (rows: readonly LedgerChainRow[], options?: ChainWindowOptions) => LedgerRowCheck[];
+/**
+ * Find on-chain outbound transactions that were never recorded in the ledger - the
+ * key-compromise / breach signal. Pure set difference: any observed outbound tx hash absent from
+ * the ledger's recorded tx hashes is unrecorded. Comparison is case-insensitive (tx hashes are
+ * hex and casing varies across RPC providers).
+ *
+ * @param onChainOutbound tx hashes observed on-chain as outbound from the agent's wallet(s)
+ * @param ledgerRows the user's recorded ledger rows
+ */
+export declare const findUnrecordedOutbound: (onChainOutbound: readonly string[], ledgerRows: readonly Pick<LedgerChainRow, "txHash">[]) => string[];
diff --git a/packages/agent-runtime/src/core/ActionLedger.js b/packages/agent-runtime/src/core/ActionLedger.js
new file mode 100644
index 000000000..1be380e38
Binary files /dev/null and b/packages/agent-runtime/src/core/ActionLedger.js differ
diff --git a/packages/agent-runtime/src/core/CapabilityGuard.d.ts b/packages/agent-runtime/src/core/CapabilityGuard.d.ts
new file mode 100644
index 000000000..d2c055073
--- /dev/null
+++ b/packages/agent-runtime/src/core/CapabilityGuard.d.ts
@@ -0,0 +1,53 @@
+import type { InstructionExecutor } from '../types/index.js';
+/**
+ * Result of a capability token check.
+ */
+export interface CapabilityCheckResult {
+ /** Whether the action is allowed */
+ allowed: boolean;
+ /** Human-readable reason if denied */
+ reason?: string;
+ /** The token ID that was validated (if any) */
+ tokenId?: string;
+}
+/**
+ * Callback type that the consumer provides to validate
+ * a capability token for a given tool call.
+ *
+ * The runtime package is database-agnostic; the actual token lookup
+ * and validation is injected by the server layer.
+ */
+export type CapabilityCheckFn = (params: {
+ /** The agent ID (from state) */
+ agentId: string;
+ /** Parsed tool arguments */
+ args: unknown;
+ /** Tool name being called */
+ toolName: string;
+}) => Promise<CapabilityCheckResult>;
+/**
+ * CapabilityGuard - wraps a standard `call_tool` InstructionExecutor
+ * with a capability token check that runs **before** the tool handler.
+ *
+ * This is designed to compose with `PermissionGuard`:
+ *
+ * ```ts
+ * const capGuard = new CapabilityGuard(myCapabilityCheckFn);
+ * const permGuard = new PermissionGuard(myPermissionCheckFn);
+ *
+ * // Chain: capability check → permission check → actual tool
+ * const executor = capGuard.wrap(permGuard.wrap(defaultCallToolExecutor));
+ * ```
+ *
+ * If no valid capability token covers the requested tool, the action is
+ * blocked with an error message pushed to the conversation.
+ */
+export declare class CapabilityGuard {
+ private checkCapability;
+ constructor(checkCapability: CapabilityCheckFn);
+ /**
+ * Returns a new InstructionExecutor that intercepts `call_tool`
+ * instructions and gates them through the capability token check.
+ */
+ wrap(innerExecutor: InstructionExecutor): InstructionExecutor;
+}
diff --git a/packages/agent-runtime/src/core/CapabilityGuard.js b/packages/agent-runtime/src/core/CapabilityGuard.js
new file mode 100644
index 000000000..79e7c1961
--- /dev/null
+++ b/packages/agent-runtime/src/core/CapabilityGuard.js
@@ -0,0 +1,79 @@
+/**
+ * CapabilityGuard - wraps a standard `call_tool` InstructionExecutor
+ * with a capability token check that runs **before** the tool handler.
+ *
+ * This is designed to compose with `PermissionGuard`:
+ *
+ * ```ts
+ * const capGuard = new CapabilityGuard(myCapabilityCheckFn);
+ * const permGuard = new PermissionGuard(myPermissionCheckFn);
+ *
+ * // Chain: capability check → permission check → actual tool
+ * const executor = capGuard.wrap(permGuard.wrap(defaultCallToolExecutor));
+ * ```
+ *
+ * If no valid capability token covers the requested tool, the action is
+ * blocked with an error message pushed to the conversation.
+ */
+export class CapabilityGuard {
+ checkCapability;
+ constructor(checkCapability) {
+ this.checkCapability = checkCapability;
+ }
+ /**
+ * Returns a new InstructionExecutor that intercepts `call_tool`
+ * instructions and gates them through the capability token check.
+ */
+ wrap(innerExecutor) {
+ return async (instruction, state, context) => {
+ // Only guard call_tool instructions
+ if (instruction.type !== 'call_tool') {
+ return innerExecutor(instruction, state, context);
+ }
+ const payload = instruction.payload;
+ const toolCalling = payload?.toolCalling;
+ if (!toolCalling) {
+ return innerExecutor(instruction, state, context);
+ }
+ const toolName = toolCalling.apiName;
+ const toolId = toolCalling.id;
+ // Parse args
+ let parsedArgs;
+ try {
+ parsedArgs = JSON.parse(toolCalling.arguments);
+ }
+ catch {
+ parsedArgs = {};
+ }
+ const agentId = state.metadata?.agentId ?? 'unknown';
+ // Run capability check
+ const result = await this.checkCapability({
+ agentId,
+ args: parsedArgs,
+ toolName,
+ });
+ if (!result.allowed) {
+ const newState = structuredClone(state);
+ newState.lastModified = new Date().toISOString();
+ newState.messages.push({
+ content: JSON.stringify({
+ error: 'Capability denied',
+ reason: result.reason ?? 'No valid capability token for this action.',
+ }),
+ role: 'tool',
+ tool_call_id: toolId,
+ });
+ const events = [
+ {
+ id: toolId,
+ result: { blocked: true, reason: result.reason },
+ type: 'tool_result',
+ },
+ ];
+ return { events, newState };
+ }
+ // Capability check passed - proceed to inner executor
+ return innerExecutor(instruction, state, context);
+ };
+ }
+}
diff --git a/packages/agent-runtime/src/core/DecisionJournal.d.ts b/packages/agent-runtime/src/core/DecisionJournal.d.ts
new file mode 100644
index 000000000..9517233c7
--- /dev/null
+++ b/packages/agent-runtime/src/core/DecisionJournal.d.ts
@@ -0,0 +1,33 @@
+export interface DecisionJournalEntry {
+ /** The agent making the decision. */
+ agentId: string;
+ /** The rule / branch taken, e.g. 'approve' | 'block' | 'auto-execute' | a tool identifier. */
+ chosenBranch?: string;
+ /** Confidence in the decision, 0..1. */
+ confidence?: number;
+ /** Kind of decision, e.g. 'tool_selection' | 'intervention' | 'risk_gate' | 'retry' | 'reflection'. */
+ decisionType: string;
+ /** The task execution this decision belongs to, if any. */
+ executionId?: string;
+ /** Everything the agent saw at decision time. */
+ inputsSnapshot?: Record<string, unknown>;
+ /** Reference to the resolved outcome (tx hash, receipt id, …), set once known. */
+ outcomeRef?: string;
+ /** Why this branch was chosen. */
+ reasoning: string;
+}
+/** Persists a journal entry. May be sync or async; its errors are swallowed by the journal. */
+export type DecisionJournalSink = (entry: DecisionJournalEntry) => Promise<unknown> | unknown;
+export declare class DecisionJournal {
+ private readonly sink?;
+ /**
+ * @param sink - Persistence function. When omitted, the journal is a no-op
+ * (useful in tests, dry-runs, or contexts without a DB).
+ */
+ constructor(sink?: DecisionJournalSink);
+ /**
+ * Journal a decision. Non-blocking and never throws - safe to call inline
+ * from the decision loop.
+ */
+ record(entry: DecisionJournalEntry): void;
+}
diff --git a/packages/agent-runtime/src/core/DecisionJournal.js b/packages/agent-runtime/src/core/DecisionJournal.js
new file mode 100644
index 000000000..c8ab3480a
--- /dev/null
+++ b/packages/agent-runtime/src/core/DecisionJournal.js
@@ -0,0 +1,47 @@
+/**
+ * DecisionJournal - records every autonomous decision the agent makes,
+ * together with the reasoning behind it.
+ *
+ * The journal is a thin, fire-and-forget writer. It is deliberately decoupled
+ * from the database: the caller passes a `sink` that persists the entry (in
+ * three.ws this wraps `AgentDecisionJournalModel.create`). This keeps
+ * agent-runtime free of a DB dependency and keeps the decision loop testable.
+ *
+ * Guarantees:
+ * - `record()` NEVER throws into the decision path - a failed or slow sink
+ * must not break the agent's reasoning loop.
+ * - `record()` is non-blocking: it returns immediately and lets the sink
+ * settle in the background. Errors are logged, not propagated.
+ */
+import { debuglog } from 'node:util';
+const log = debuglog('three-ws-agent-runtime-decision-journal');
+export class DecisionJournal {
+ sink;
+ /**
+ * @param sink - Persistence function. When omitted, the journal is a no-op
+ * (useful in tests, dry-runs, or contexts without a DB).
+ */
+ constructor(sink) {
+ this.sink = sink;
+ }
+ /**
+ * Journal a decision. Non-blocking and never throws - safe to call inline
+ * from the decision loop.
+ */
+ record(entry) {
+ if (!this.sink)
+ return;
+ try {
+ const result = this.sink(entry);
+ if (result && typeof result.then === 'function') {
+ result.then(() => { }, (error) => {
+ log('decision journal sink rejected: %O', error);
+ });
+ }
+ }
+ catch (error) {
+ // A synchronous throw from the sink must not reach the decision path.
+ log('decision journal sink threw: %O', error);
+ }
+ }
+}
diff --git a/packages/agent-runtime/src/core/ExitDecisionEngine.d.ts b/packages/agent-runtime/src/core/ExitDecisionEngine.d.ts
new file mode 100644
index 000000000..3b674636b
--- /dev/null
+++ b/packages/agent-runtime/src/core/ExitDecisionEngine.d.ts
@@ -0,0 +1,54 @@
+import type { ExitEvaluablePosition, ExitReason, ExitSentiment, LadderedExitDecision } from '../types/exit.js';
+/**
+ * Coerce to a finite number, or `null`. A `null`/blank input is "disabled"
+ * (`null`) - NOT `0`. (`Number(null) === 0`, so a missing take-profit / trailing
+ * stop would otherwise fire immediately; `null` documents "no TP / no trailing
+ * stop", and this is the single source of truth that honors it.)
+ */
+export declare function pct(n: number | null | undefined): number | null;
+/**
+ * Decide the exit reason for a position, or `null` to hold. Evaluated in priority
+ * order: stop-loss → signal-flip → trailing-stop → take-profit → timeout.
+ *
+ * The hard stop-loss always wins. `signal_flip` is an EARLY warning that cuts a
+ * losing position before it reaches the stop; it only fires while the position is
+ * underwater and never overrides a take-profit. It is inert unless the caller
+ * passes a `sentiment`, so replays that omit it are byte-for-byte unchanged.
+ *
+ * @param pos position to evaluate
+ * @param value current value of the position (wei)
+ * @param peak high-water mark of `value` since entry (wei)
+ * @param now epoch ms for the timeout clock - always injected, never wall time
+ * @param sentiment live sentiment read; `null`/omitted disables signal_flip
+ */
+export declare function decideExit(pos: ExitEvaluablePosition, value: bigint, peak: bigint, now: number, sentiment?: ExitSentiment | null): ExitReason | null;
+/** The take-initials multiple (× entry) or `null` when the ladder is off. Must be
+ * > 1 to make sense - you can't recover initials below cost. */
+export declare function ladderMultiple(n: number | null | undefined): number | null;
+/** Moon-bag floor as a fraction of the position that must ALWAYS be kept on the
+ * take-initials event. Default 15%, clamped to [0, 0.95] so a sell can never be
+ * the whole bag. */
+export declare function moonbagFraction(n: number | null | undefined): number;
+/**
+ * Laddered exit decision: the reason AND what fraction of the CURRENT remaining
+ * position to sell. This is the live-trading source of truth; `decideExit` above
+ * stays the single-shot decider a backtester replays.
+ *
+ * The ladder is OPT-IN: with no `initialsOutMultiple` set it is byte-for-byte the
+ * classic full-exit behavior (sellFraction 1 on any `decideExit` reason), so
+ * existing strategies are unchanged. When set, it encodes the owner's rule:
+ *
+ * - Protective exits are always FULL exits of whatever remains, and the hard
+ * stop-loss still wins: stop_loss → signal_flip → trailing_stop.
+ * - The FIRST time the position reaches `initialsOutMultiple`× entry (e.g. 2×),
+ * sell exactly enough to return the initial cost basis (fraction =
+ * entry/value), but NEVER more than 1 − moonbag floor - so a moon bag always
+ * rides. At 2× that is a 0.5 sell (keep half); at 5× a 0.2 sell (keep 80%).
+ * - After initials are recovered, the moon bag runs, protected by the trailing
+ * stop; an optional classic `takeProfitPct` acts as a ceiling that exits the
+ * remainder. Timeout exits the remainder.
+ *
+ * It NEVER returns a full take-PROFIT exit before initials are recovered - that
+ * is the "sold too much too soon" mistake the rule exists to prevent.
+ */
+export declare function decideLadderedExit(pos: ExitEvaluablePosition, value: bigint, peak: bigint, now: number, sentiment?: ExitSentiment | null): LadderedExitDecision | null;
diff --git a/packages/agent-runtime/src/core/ExitDecisionEngine.js b/packages/agent-runtime/src/core/ExitDecisionEngine.js
new file mode 100644
index 000000000..b38ea31c3
--- /dev/null
+++ b/packages/agent-runtime/src/core/ExitDecisionEngine.js
@@ -0,0 +1,150 @@
+// ExitDecisionEngine - pure exit decision. No I/O, no time source of its own.
+//
+// The single source of truth for "should this position exit, and why", evaluated
+// in strict priority order: stop-loss → signal-flip → trailing-stop → take-profit
+// → timeout. The hard stop-loss always wins; `signal_flip` is an early cut that
+// only fires while underwater. Because the clock is always passed in (never read
+// from wall time here), the exact same function governs live evaluation and
+// historical backtests - the two can never drift.
+//
+// Ported near-verbatim from three.ws `workers/agent-sniper/exit-logic.js`.
+// Solana lamports → EVM wei: entry/value/peak are `bigint`. Ratio comparisons run
+// in float64 (see types/exit.ts for why that is precision-safe).
+/**
+ * Coerce to a finite number, or `null`. A `null`/blank input is "disabled"
+ * (`null`) - NOT `0`. (`Number(null) === 0`, so a missing take-profit / trailing
+ * stop would otherwise fire immediately; `null` documents "no TP / no trailing
+ * stop", and this is the single source of truth that honors it.)
+ */
+export function pct(n) {
+ if (n == null)
+ return null;
+ const x = Number(n);
+ return Number.isFinite(x) ? x : null;
+}
+/** A confident bearish sentiment read. `minConfidence` defaults to 0.7. */
+function isBearishFlip(sentiment) {
+ if (!sentiment || sentiment.signal !== 'bearish')
+ return false;
+ const conf = Number(sentiment.confidence);
+ const floor = Number(sentiment.minConfidence);
+ return Number.isFinite(conf) && conf >= (Number.isFinite(floor) ? floor : 0.7);
+}
+/**
+ * Decide the exit reason for a position, or `null` to hold. Evaluated in priority
+ * order: stop-loss → signal-flip → trailing-stop → take-profit → timeout.
+ *
+ * The hard stop-loss always wins. `signal_flip` is an EARLY warning that cuts a
+ * losing position before it reaches the stop; it only fires while the position is
+ * underwater and never overrides a take-profit. It is inert unless the caller
+ * passes a `sentiment`, so replays that omit it are byte-for-byte unchanged.
+ *
+ * @param pos position to evaluate
+ * @param value current value of the position (wei)
+ * @param peak high-water mark of `value` since entry (wei)
+ * @param now epoch ms for the timeout clock - always injected, never wall time
+ * @param sentiment live sentiment read; `null`/omitted disables signal_flip
+ */
+export function decideExit(pos, value, peak, now, sentiment = null) {
+ const entry = pos.entryQuoteWei ?? 0n;
+ if (entry <= 0n)
+ return null;
+ const ev = Number(entry);
+ const v = Number(value);
+ const pk = Number(peak);
+ const sl = pct(pos.stopLossPct);
+ const ts = pct(pos.trailingStopPct);
+ const tp = pct(pos.takeProfitPct);
+ if (sl != null && v <= ev * (1 - sl / 100))
+ return 'stop_loss';
+ if (isBearishFlip(sentiment) && v < ev)
+ return 'signal_flip';
+ // Trailing stop arms only once the peak has been ABOVE entry, so a coin that
+ // never moves up can't trail-stop on entry noise.
+ if (ts != null && pk > ev && v <= pk * (1 - ts / 100))
+ return 'trailing_stop';
+ if (tp != null && v >= ev * (1 + tp / 100))
+ return 'take_profit';
+ const heldS = (now - pos.openedAt) / 1000;
+ if (pos.maxHoldSeconds != null && heldS >= pos.maxHoldSeconds)
+ return 'timeout';
+ return null;
+}
+/** The take-initials multiple (× entry) or `null` when the ladder is off. Must be
+ * > 1 to make sense - you can't recover initials below cost. */
+export function ladderMultiple(n) {
+ const x = pct(n);
+ return x != null && x > 1 ? x : null;
+}
+/** Moon-bag floor as a fraction of the position that must ALWAYS be kept on the
+ * take-initials event. Default 15%, clamped to [0, 0.95] so a sell can never be
+ * the whole bag. */
+export function moonbagFraction(n) {
+ const x = pct(n);
+ const frac = x == null ? 15 : x;
+ return Math.max(0, Math.min(0.95, frac / 100));
+}
+/**
+ * Laddered exit decision: the reason AND what fraction of the CURRENT remaining
+ * position to sell. This is the live-trading source of truth; `decideExit` above
+ * stays the single-shot decider a backtester replays.
+ *
+ * The ladder is OPT-IN: with no `initialsOutMultiple` set it is byte-for-byte the
+ * classic full-exit behavior (sellFraction 1 on any `decideExit` reason), so
+ * existing strategies are unchanged. When set, it encodes the owner's rule:
+ *
+ * - Protective exits are always FULL exits of whatever remains, and the hard
+ * stop-loss still wins: stop_loss → signal_flip → trailing_stop.
+ * - The FIRST time the position reaches `initialsOutMultiple`× entry (e.g. 2×),
+ * sell exactly enough to return the initial cost basis (fraction =
+ * entry/value), but NEVER more than 1 − moonbag floor - so a moon bag always
+ * rides. At 2× that is a 0.5 sell (keep half); at 5× a 0.2 sell (keep 80%).
+ * - After initials are recovered, the moon bag runs, protected by the trailing
+ * stop; an optional classic `takeProfitPct` acts as a ceiling that exits the
+ * remainder. Timeout exits the remainder.
+ *
+ * It NEVER returns a full take-PROFIT exit before initials are recovered - that
+ * is the "sold too much too soon" mistake the rule exists to prevent.
+ */
+export function decideLadderedExit(pos, value, peak, now, sentiment = null) {
+ const mult = ladderMultiple(pos.initialsOutMultiple);
+ if (mult == null) {
+ // Ladder off → classic single-shot full exit (unchanged behavior).
+ const reason = decideExit(pos, value, peak, now, sentiment);
+ return reason ? { reason, sellFraction: 1 } : null;
+ }
+ const entry = pos.entryQuoteWei ?? 0n;
+ if (entry <= 0n)
+ return null;
+ const ev = Number(entry);
+ const v = Number(value);
+ const pk = Number(peak);
+ const sl = pct(pos.stopLossPct);
+ const ts = pct(pos.trailingStopPct);
+ const tp = pct(pos.takeProfitPct);
+ const moonbag = moonbagFraction(pos.moonbagMinPct);
+ const recovered = pos.initialsRecovered === true;
+ // Protective exits - full exit of the remainder; stop-loss wins on conflict.
+ if (sl != null && v <= ev * (1 - sl / 100))
+ return { reason: 'stop_loss', sellFraction: 1 };
+ if (isBearishFlip(sentiment) && v < ev)
+ return { reason: 'signal_flip', sellFraction: 1 };
+ // Trailing stop arms only once the peak has been ABOVE entry (see decideExit).
+ if (ts != null && pk > ev && v <= pk * (1 - ts / 100))
+ return { reason: 'trailing_stop', sellFraction: 1 };
+ // Take-initials - the first profit event, once, before initials are recovered.
+ if (!recovered && v >= ev * mult) {
+ const recoverFraction = ev / v; // f·value = cost basis
+ const sellFraction = Math.max(0, Math.min(recoverFraction, 1 - moonbag));
+ if (sellFraction > 0)
+ return { reason: 'take_initials', sellFraction, recoversInitials: true };
+ }
+ // Moon-bag ceiling - optional classic take-profit, only AFTER initials are out.
+ if (recovered && tp != null && v >= ev * (1 + tp / 100))
+ return { reason: 'take_profit', sellFraction: 1 };
+ // Timeout - full exit of the remainder.
+ const heldS = (now - pos.openedAt) / 1000;
+ if (pos.maxHoldSeconds != null && heldS >= pos.maxHoldSeconds)
+ return { reason: 'timeout', sellFraction: 1 };
+ return null;
+}
diff --git a/packages/agent-runtime/src/core/GuardChain.d.ts b/packages/agent-runtime/src/core/GuardChain.d.ts
new file mode 100644
index 000000000..fbcfa9b38
--- /dev/null
+++ b/packages/agent-runtime/src/core/GuardChain.d.ts
@@ -0,0 +1,295 @@
+/**
+ * GuardChain - unified, composable evaluation of every three.ws enforcement layer.
+ *
+ * The runtime ships six independent guards, but each is invoked from a different
+ * place, in a different order, with different inputs:
+ *
+ * | Guard | Invoked from | Gates |
+ * |----------------------|---------------------------------------|------------------|
+ * | InterventionChecker | `GeneralChatAgent.runner()` | human approval |
+ * | DeFiGuard | `ToolExecutionService.executeTool()` | risk + MEV |
+ * | CapabilityGuard | executor decorator (`call_tool` only) | capability token |
+ * | PermissionGuard | executor decorator (`call_tool` only) | agent permission |
+ * | SpendGuard | `TransactionPipeline` preflight | spend envelope |
+ * | X402Hook | the x402 payment path | autonomy budget |
+ *
+ * Nothing composes them, so no single caller can answer the two questions that
+ * matter before money moves:
+ *
+ * 1. **Which layer would stop this call, and why?**
+ * 2. **Which layers would silently _not_ evaluate it at all?**
+ *
+ * Question 2 is the important one. A guard that never runs looks exactly like a
+ * guard that passed - `DeFiGuard` on a tool identifier that was never registered
+ * returns `allow`; the dollar caps on a call whose `valueUsd` was never resolved
+ * compare against `0` and pass; the executor-decorator guards are skipped
+ * entirely for tools dispatched in a batch. Every one of those reads as "green".
+ *
+ * `GuardChain` runs all six in a deterministic order over one request, returns a
+ * per-layer trace, and - the novel part - derives a set of {@link GuardBlindSpot}
+ * findings describing the enforcement that *should* have applied but didn't,
+ * together with a {@link GuardChainVerdict.coverageScore} quantifying the gap.
+ *
+ * It is pure and I/O-free. Every external dependency (capability lookup,
+ * permission lookup, clocks) is injected, so the same code path serves live
+ * preflight, the simulator UI, and tests.
+ *
+ * @example
+ * ```ts
+ * const chain = new GuardChain({
+ * defiGuard: new DeFiGuard(),
+ * spendGuard: new SpendGuard({ perTxMaxUsd: 5_000 }),
+ * });
+ *
+ * const verdict = await chain.evaluate({
+ * apiName: 'executeSwap',
+ * arguments: { amount: '2.5', chainId: 1, fromToken: 'ETH', toToken: 'USDC' },
+ * identifier: 'solana_swap',
+ * valueUsd: 18_400,
+ * });
+ *
+ * verdict.decision; // 'require_approval'
+ * verdict.blockedBy; // undefined
+ * verdict.coverageScore; // 100
+ * ```
+ */
+import type { HumanInterventionConfig, SecurityBlacklistRule } from '../types/vendor.js';
+import type { CapabilityCheckFn } from './CapabilityGuard.js';
+import { type DeFiGuard, type UserSwapCaps, type UserSwapVolume } from './toolRegistry.js';
+import type { PermissionCheckFn } from './PermissionGuard.js';
+import type { PortfolioPosition } from './toolRegistry.js';
+import type { SpendGuard } from './SpendGuard.js';
+import type { X402Hook, X402PaymentRequirements } from '../types/runtime.js';
+/** The six enforcement layers, in the order `GuardChain` evaluates them. */
+export type GuardLayerId = 'security_blacklist' | 'intervention' | 'capability' | 'permission' | 'defi_guard' | 'spend_guard' | 'x402';
+/**
+ * Outcome of a single layer.
+ *
+ * `skipped` is deliberately distinct from `pass`: it means the layer did not
+ * evaluate this call at all. Collapsing the two is precisely the failure mode
+ * this module exists to surface.
+ */
+export type GuardLayerStatus = 'pass' | 'warn' | 'approval_required' | 'block' | 'skipped' | 'error';
+/** Result of one layer's evaluation. */
+export interface GuardLayerResult {
+ /** Structured reason code, where the layer produces one. */
+ code?: string;
+ /** Layer-specific payload (risk report, MEV assessment, remaining allowance…). */
+ detail?: Record<string, unknown>;
+ /** Wall-clock milliseconds this layer took. */
+ elapsedMs: number;
+ /** Human-readable layer name, safe to render directly. */
+ label: string;
+ layer: GuardLayerId;
+ /** Deterministic, human-readable explanation of the status. */
+ reason: string;
+ status: GuardLayerStatus;
+}
+/** Structural enforcement gaps derived from the request shape. */
+export type BlindSpotCode =
+/** A DeFi-registered mutating call arrived without an authoritative USD value. */
+'VALUE_UNRESOLVED'
+/** The API mutates on-chain state but the tool identifier is not registered with DeFiGuard. */
+ | 'TOOL_UNREGISTERED'
+/** Dispatched via `call_tools_batch`, which bypasses the executor-decorator guards. */
+ | 'BATCH_BYPASS'
+/** A value-moving call with no spend envelope configured. */
+ | 'SPEND_UNSCOPED'
+/** The target protocol is absent from the audit registry, so it reads as unaudited. */
+ | 'PROTOCOL_UNVERIFIED'
+/** No capability-token checker was wired into this evaluation. */
+ | 'CAPABILITY_UNWIRED'
+/** No permission checker was wired into this evaluation. */
+ | 'PERMISSION_UNWIRED'
+/** A read-only call that DeFiGuard skipped by configuration. */
+ | 'READONLY_UNANALYZED';
+/** One derived enforcement gap. */
+export interface GuardBlindSpot {
+ code: BlindSpotCode;
+ /** What is actually not being checked, in concrete terms. */
+ detail: string;
+ /** The layer whose coverage is degraded. */
+ layer: GuardLayerId;
+ /** The specific action that closes the gap. */
+ remediation: string;
+ severity: 'info' | 'warning' | 'critical';
+ title: string;
+}
+/** The composed result of a full chain evaluation. */
+export interface GuardChainVerdict {
+ /** Enforcement gaps derived from the request shape, ordered critical-first. */
+ blindSpots: GuardBlindSpot[];
+ /** The first layer that returned `block`, if any. */
+ blockedBy?: GuardLayerId;
+ /** Structured code from the deciding layer. */
+ code?: string;
+ /**
+ * Percentage (0-100) of the enforcement weight that *should* apply to this
+ * request and actually evaluated it. A verdict of `allow` at 45% coverage is
+ * a materially weaker statement than the same verdict at 100%.
+ */
+ coverageScore: number;
+ /** Strongest outcome across all layers. */
+ decision: 'allow' | 'require_approval' | 'block';
+ evaluatedAt: number;
+ /** Per-layer trace, in evaluation order. */
+ layers: GuardLayerResult[];
+ /** MEV-protected argument adjustments proposed by DeFiGuard. */
+ modifiedArguments?: Record<string, unknown>;
+ /** Human-readable explanation attributable to the deciding layer. */
+ reason: string;
+ totalElapsedMs: number;
+ /** Non-blocking advisories aggregated from every layer. */
+ warnings: string[];
+}
+/** x402 payment context, supplied only when the call is a paid HTTP request. */
+export interface GuardChainX402Input {
+ /** USDC already spent by this agent in the current hour. */
+ amountSpentThisHourUsdc: number;
+ /** Live USDC balance of the agent wallet. */
+ currentBalanceUsdc: number;
+ /** Structured payment requirements from the `X-PAYMENT-REQUIRED` header. */
+ requirements: X402PaymentRequirements;
+ /** The URL that returned 402. */
+ url: string;
+}
+/** One tool call to evaluate against the full enforcement surface. */
+export interface GuardChainRequest {
+ /** Agent initiating the call - spend is tracked per agent. */
+ agentId?: string;
+ /** Tools pre-approved under `allow-list` mode, formatted `identifier/apiName`. */
+ allowList?: string[];
+ /** Tool API being invoked, e.g. `executeSwap`. */
+ apiName: string;
+ /** Global approval mode in force for the session. */
+ approvalMode?: 'auto-run' | 'allow-list' | 'manual' | 'headless';
+ /** Parsed tool arguments. */
+ arguments?: Record<string, unknown>;
+ /** Agent wallet balance in USD - required to enforce the reserve floor. */
+ balanceUsd?: number;
+ chainId?: number;
+ /** Tool keys the user already confirmed this session. */
+ confirmedHistory?: string[];
+ /** Destination address, for the spend firewall. */
+ destination?: string;
+ /**
+ * How the call would be dispatched. `batch` (`call_tools_batch`) bypasses the
+ * capability and permission executor decorators, which only intercept
+ * `call_tool`.
+ * @default 'single'
+ */
+ executionPath?: 'single' | 'batch';
+ /** Tool identifier, e.g. `solana_swap`. */
+ identifier: string;
+ /** Manifest-level or user-override intervention config. */
+ interventionConfig?: HumanInterventionConfig;
+ /** Portfolio context enabling the risk dimensions. */
+ portfolioPositions?: PortfolioPosition[];
+ /** Target protocol, checked against the audit registry. */
+ protocol?: string;
+ /** Blacklist rules; omit to use the runtime default blacklist. */
+ securityBlacklist?: SecurityBlacklistRule[];
+ /** Token symbol or address moving out, for the spend firewall. */
+ token?: string;
+ userId?: string;
+ /** Per-user caps resolved server-side from `userSwapLimits`. */
+ userSwapCaps?: UserSwapCaps;
+ /** Confirmed swap volume windows resolved from `executionReceipts`. */
+ userSwapVolume?: UserSwapVolume;
+ /** Subscription tier driving the tier limits. */
+ userTier?: string;
+ /**
+ * Authoritative USD value, resolved by the caller. Without it the dollar caps
+ * compare against zero and pass - see {@link BlindSpotCode.VALUE_UNRESOLVED}.
+ */
+ valueUsd?: number;
+ /** Payment context when the call goes through the x402 path. */
+ x402?: GuardChainX402Input;
+}
+/** Injected dependencies. Every guard is optional; an absent guard is reported. */
+export interface GuardChainOptions {
+ /** Capability-token validator, normally backed by `capabilityToken` records. */
+ checkCapability?: CapabilityCheckFn;
+ /** Permission resolver, normally backed by `agentPermission` records. */
+ checkPermission?: PermissionCheckFn;
+ /** Monotonic millisecond source used for per-layer timing. Injectable for tests. */
+ clock?: () => number;
+ defiGuard?: DeFiGuard;
+ /** Wall-clock source for `evaluatedAt`. Injectable for tests. */
+ now?: () => number;
+ spendGuard?: SpendGuard;
+ x402Hook?: X402Hook;
+}
+export declare class GuardChain {
+ private readonly clock;
+ private readonly now;
+ private readonly opts;
+ constructor(options?: GuardChainOptions);
+ /**
+ * Run every applicable layer over a single tool call.
+ *
+ * Layers always run to completion - the chain does not short-circuit on the
+ * first block. A partial trace would defeat the purpose: the operator needs to
+ * know that a call blocked by the spend envelope *also* carried critical MEV
+ * exposure, and that the permission layer never ran at all.
+ */
+ evaluate(request: GuardChainRequest): Promise<GuardChainVerdict>;
+ private runSecurityBlacklist;
+ private runIntervention;
+ private runCapability;
+ private runPermission;
+ private runDeFiGuard;
+ private runSpendGuard;
+ private runX402;
+ /**
+ * Select the layer that determines the verdict: the highest-severity status,
+ * with earlier layers winning ties so the reported reason matches the layer
+ * that would actually fire first at runtime.
+ */
+ private pickDecidingLayer;
+ /**
+ * Coverage is measured against the layers that *should* apply to this request,
+ * not against all seven. Charging a read-only call for skipping the spend
+ * envelope would make the number meaningless.
+ */
+ private computeCoverage;
+ /**
+ * Derive the enforcement gaps this request would hit. These are structural -
+ * they describe checks that did not happen, which no individual guard reports
+ * because from its own perspective nothing went wrong.
+ */
+ private deriveBlindSpots;
+}
+/** One tool identifier's standing in the enforcement registry. */
+export interface GuardCoverageEntry {
+ /** Mutating APIs this identifier is known to expose, if any were supplied. */
+ apis: string[];
+ identifier: string;
+ /** Whether DeFiGuard would analyze calls to this identifier. */
+ registered: boolean;
+}
+/** Registry-wide coverage snapshot. */
+export interface GuardCoverageReport {
+ /** Percentage of supplied identifiers that are registered. */
+ coveragePercent: number;
+ /** Mutating API names the guard recognises. */
+ mutatingApis: string[];
+ /** Identifiers DeFiGuard is configured to analyze. */
+ registered: GuardCoverageEntry[];
+ /** Identifiers supplied by the caller that are absent from the registry. */
+ unregistered: GuardCoverageEntry[];
+}
+/**
+ * Compare a set of live tool identifiers against the DeFi enforcement registry.
+ *
+ * Pass the identifiers actually installed in a deployment to find fund-moving
+ * tools that no guard would ever see. With no argument it reports the registry
+ * itself.
+ */
+export declare function analyzeGuardCoverage(installedIdentifiers?: string[]): GuardCoverageReport;
+/** Human-readable label for a layer id, for callers rendering a trace. */
+export declare function guardLayerLabel(layer: GuardLayerId): string;
+/** Relative enforcement weight of a layer, exposed for callers scoring coverage. */
+export declare function guardLayerWeight(layer: GuardLayerId): number;
+/** The layers `GuardChain` evaluates, in order. */
+export declare const GUARD_LAYER_ORDER: GuardLayerId[];
diff --git a/packages/agent-runtime/src/core/GuardChain.js b/packages/agent-runtime/src/core/GuardChain.js
new file mode 100644
index 000000000..2a2be3094
--- /dev/null
+++ b/packages/agent-runtime/src/core/GuardChain.js
@@ -0,0 +1,742 @@
+import { DEFI_TOOL_IDENTIFIERS, MUTATING_APIS, } from './toolRegistry.js';
+import { DEFAULT_SECURITY_BLACKLIST } from './defaultSecurityBlacklist.js';
+import { InterventionChecker } from './InterventionChecker.js';
+// ============================================================================
+// Constants
+// ============================================================================
+/** Display names for each layer, kept beside the ids so the UI never re-derives them. */
+const LAYER_LABELS = {
+ capability: 'Capability Token',
+ defi_guard: 'DeFi Guard',
+ intervention: 'Human Intervention',
+ permission: 'Agent Permission',
+ security_blacklist: 'Security Blacklist',
+ spend_guard: 'Spend Envelope',
+ x402: 'x402 Autonomy Budget',
+};
+/**
+ * Relative enforcement weight of each layer, used for {@link GuardChainVerdict.coverageScore}.
+ * DeFiGuard carries the most weight because it is the only layer that reasons about
+ * portfolio risk, MEV exposure, and dollar caps together.
+ */
+const LAYER_WEIGHTS = {
+ capability: 10,
+ defi_guard: 30,
+ intervention: 15,
+ permission: 15,
+ security_blacklist: 10,
+ spend_guard: 15,
+ x402: 5,
+};
+/**
+ * Mutating APIs that move value *into* the wallet or are strictly neutral.
+ * These are excluded from spend-envelope gating so a user reclaiming their own
+ * funds never trips a cap. Mirrors the exclusions in `spendGuardPipeline`.
+ */
+const NON_OUTFLOW_APIS = new Set([
+ 'borrow',
+ 'borrowLisUsd',
+ 'cancelDCA',
+ 'cancelLimitOrder',
+ 'claimRewards',
+ 'redeem',
+ 'removeLiquidity',
+ 'revoke',
+ 'revokeAllApprovals',
+ 'revokeApproval',
+ 'unstake',
+ 'unstakeBnb',
+ 'withdraw',
+ 'withdrawFunds',
+ 'withdrawSavings',
+]);
+/**
+ * API-name shapes that mutate on-chain state. Used only to detect tools that
+ * *look* fund-moving but are absent from `MUTATING_APIS` / `DEFI_TOOL_IDENTIFIERS`
+ * - i.e. registration gaps.
+ */
+const MUTATING_NAME_HINTS = [
+ 'approve',
+ 'borrow',
+ 'bridge',
+ 'burn',
+ 'buy',
+ 'claim',
+ 'deposit',
+ 'execute',
+ 'mint',
+ 'pay',
+ 'repay',
+ 'send',
+ 'sell',
+ 'stake',
+ 'supply',
+ 'swap',
+ 'transfer',
+ 'withdraw',
+];
+/** Ranking used to fold per-layer statuses into a single decision. */
+const STATUS_SEVERITY = {
+ approval_required: 2,
+ block: 3,
+ error: 3,
+ pass: 0,
+ skipped: 0,
+ warn: 1,
+};
+const BLIND_SPOT_SEVERITY_ORDER = {
+ critical: 0,
+ info: 2,
+ warning: 1,
+};
+// ============================================================================
+// Helpers
+// ============================================================================
+/** True when the API name suggests an on-chain mutation, by shape rather than registry. */
+function looksMutating(apiName) {
+ const lower = apiName.toLowerCase();
+ return MUTATING_NAME_HINTS.some((hint) => lower.includes(hint));
+}
+/** True when the call moves value out of the agent's wallet. */
+function isOutflow(apiName) {
+ return MUTATING_APIS.has(apiName) && !NON_OUTFLOW_APIS.has(apiName);
+}
+/** Map a DeFiGuard verdict onto a chain layer status. */
+function decisionToStatus(decision) {
+ if (decision === 'block')
+ return 'block';
+ if (decision === 'require_approval')
+ return 'approval_required';
+ return 'pass';
+}
+/** Map an intervention policy onto a chain layer status. */
+function policyToStatus(policy) {
+ return policy === 'never' ? 'pass' : 'approval_required';
+}
+// ============================================================================
+// GuardChain
+// ============================================================================
+export class GuardChain {
+ clock;
+ now;
+ opts;
+ constructor(options = {}) {
+ this.opts = options;
+ this.now = options.now ?? (() => Date.now());
+ this.clock = options.clock ?? (() => Date.now());
+ }
+ /**
+ * Run every applicable layer over a single tool call.
+ *
+ * Layers always run to completion - the chain does not short-circuit on the
+ * first block. A partial trace would defeat the purpose: the operator needs to
+ * know that a call blocked by the spend envelope *also* carried critical MEV
+ * exposure, and that the permission layer never ran at all.
+ */
+ async evaluate(request) {
+ const startedAt = this.clock();
+ const layers = [];
+ const warnings = [];
+ let modifiedArguments;
+ const args = request.arguments ?? {};
+ layers.push(this.runSecurityBlacklist(request, args), this.runIntervention(request, args), await this.runCapability(request, args), await this.runPermission(request, args));
+ const defi = await this.runDeFiGuard(request, args);
+ if (defi.warnings.length > 0)
+ warnings.push(...defi.warnings);
+ if (defi.modifiedArguments)
+ modifiedArguments = defi.modifiedArguments;
+ layers.push(defi.result, this.runSpendGuard(request), await this.runX402(request));
+ const decisionLayer = this.pickDecidingLayer(layers);
+ const decision = decisionLayer === undefined
+ ? 'allow'
+ : decisionLayer.status === 'block' || decisionLayer.status === 'error'
+ ? 'block'
+ : decisionLayer.status === 'approval_required'
+ ? 'require_approval'
+ : 'allow';
+ const blindSpots = this.deriveBlindSpots(request, layers).sort((a, b) => BLIND_SPOT_SEVERITY_ORDER[a.severity] - BLIND_SPOT_SEVERITY_ORDER[b.severity]);
+ // Warn-level layers are advisory; surface them alongside DeFiGuard's own.
+ for (const layer of layers) {
+ if (layer.status === 'warn')
+ warnings.push(`${layer.label}: ${layer.reason}`);
+ }
+ return {
+ blindSpots,
+ blockedBy: decision === 'block' ? decisionLayer?.layer : undefined,
+ code: decisionLayer?.code,
+ coverageScore: this.computeCoverage(request, layers),
+ decision,
+ evaluatedAt: this.now(),
+ layers,
+ modifiedArguments,
+ reason: decisionLayer === undefined || decision === 'allow'
+ ? 'Cleared every applicable enforcement layer.'
+ : `${decisionLayer.label}: ${decisionLayer.reason}`,
+ totalElapsedMs: Math.max(0, this.clock() - startedAt),
+ warnings,
+ };
+ }
+ // ── Layer 1: security blacklist ──────────────────────────────────────────
+ runSecurityBlacklist(request, args) {
+ const t0 = this.clock();
+ // `checkSecurityBlacklist` defaults an absent list to `[]`, while
+ // `shouldIntervene` defaults it to DEFAULT_SECURITY_BLACKLIST. Mirror the
+ // latter - it is what the agent loop actually applies, and defaulting to an
+ // empty list here would silently under-report the blacklist layer.
+ const check = InterventionChecker.checkSecurityBlacklist(request.securityBlacklist ?? DEFAULT_SECURITY_BLACKLIST, args);
+ // Headless runs skip blacklisted tools rather than blocking them, so the
+ // effective outcome differs from an interactive session on the same call.
+ const headless = request.approvalMode === 'headless';
+ return {
+ code: check.blocked ? 'SECURITY_BLACKLIST' : undefined,
+ detail: { approvalMode: request.approvalMode ?? 'manual', headlessSkip: headless },
+ elapsedMs: this.clock() - t0,
+ label: LAYER_LABELS.security_blacklist,
+ layer: 'security_blacklist',
+ reason: check.blocked
+ ? headless
+ ? `Matched a blacklist rule (${check.reason}). In headless mode the call is skipped rather than surfaced for approval.`
+ : (check.reason ?? 'Matched a security blacklist rule.')
+ : 'No blacklist rule matched these arguments.',
+ status: check.blocked ? 'block' : 'pass',
+ };
+ }
+ // ── Layer 2: human intervention ──────────────────────────────────────────
+ runIntervention(request, args) {
+ const t0 = this.clock();
+ const mode = request.approvalMode ?? 'manual';
+ const toolKey = InterventionChecker.generateToolKey(request.identifier, request.apiName, InterventionChecker.hashArguments(args));
+ const policy = InterventionChecker.shouldIntervene({
+ config: request.interventionConfig,
+ confirmedHistory: request.confirmedHistory,
+ securityBlacklist: request.securityBlacklist,
+ toolArgs: args,
+ toolKey,
+ });
+ // The global approval mode can downgrade `required`, but never `always`.
+ let effective = policy;
+ let reason;
+ if (policy === 'always') {
+ // `always` is the one policy no approval mode can downgrade.
+ reason = 'Tool policy is `always` - no approval mode can bypass it.';
+ }
+ else {
+ switch (mode) {
+ case 'allow-list': {
+ const listed = (request.allowList ?? []).includes(`${request.identifier}/${request.apiName}`);
+ effective = listed ? 'never' : policy;
+ reason = listed
+ ? 'Tool is on the session allow list.'
+ : 'Tool is absent from the allow list, so the tool policy stands.';
+ break;
+ }
+ case 'auto-run': {
+ effective = 'never';
+ reason = 'Global auto-run mode bypasses the `required` policy.';
+ break;
+ }
+ case 'headless': {
+ effective = 'never';
+ reason = 'Headless mode executes without a human channel.';
+ break;
+ }
+ default: {
+ reason =
+ policy === 'never'
+ ? 'Tool policy permits unattended execution.'
+ : 'Tool policy requires confirmation before execution.';
+ }
+ }
+ }
+ return {
+ code: effective === 'never' ? undefined : `INTERVENTION_${effective.toUpperCase()}`,
+ detail: { approvalMode: mode, effectivePolicy: effective, toolKey, toolPolicy: policy },
+ elapsedMs: this.clock() - t0,
+ label: LAYER_LABELS.intervention,
+ layer: 'intervention',
+ reason,
+ status: policyToStatus(effective),
+ };
+ }
+ // ── Layer 3: capability token ────────────────────────────────────────────
+ async runCapability(request, args) {
+ const t0 = this.clock();
+ const base = { label: LAYER_LABELS.capability, layer: 'capability' };
+ if (!this.opts.checkCapability) {
+ return {
+ ...base,
+ elapsedMs: this.clock() - t0,
+ reason: 'No capability-token validator is wired into this evaluation.',
+ status: 'skipped',
+ };
+ }
+ if (request.executionPath === 'batch') {
+ return {
+ ...base,
+ code: 'BATCH_BYPASS',
+ elapsedMs: this.clock() - t0,
+ reason: 'Batched dispatch bypasses this guard - the decorator only intercepts `call_tool`.',
+ status: 'skipped',
+ };
+ }
+ try {
+ const result = await this.opts.checkCapability({
+ agentId: request.agentId ?? 'unknown',
+ args,
+ toolName: request.apiName,
+ });
+ return {
+ ...base,
+ code: result.allowed ? undefined : 'CAPABILITY_DENIED',
+ detail: { tokenId: result.tokenId },
+ elapsedMs: this.clock() - t0,
+ reason: result.reason ??
+ (result.allowed
+ ? 'A valid capability token covers this tool.'
+ : 'No valid capability token covers this tool.'),
+ status: result.allowed ? 'pass' : 'block',
+ };
+ }
+ catch (error) {
+ // Fail closed: an unavailable validator must not open the money path.
+ return {
+ ...base,
+ code: 'CAPABILITY_ERROR',
+ elapsedMs: this.clock() - t0,
+ reason: `Capability check failed, so the call is refused: ${error instanceof Error ? error.message : String(error)}`,
+ status: 'error',
+ };
+ }
+ }
+ // ── Layer 4: agent permission ────────────────────────────────────────────
+ async runPermission(request, args) {
+ const t0 = this.clock();
+ const base = { label: LAYER_LABELS.permission, layer: 'permission' };
+ if (!this.opts.checkPermission) {
+ return {
+ ...base,
+ elapsedMs: this.clock() - t0,
+ reason: 'No permission resolver is wired into this evaluation.',
+ status: 'skipped',
+ };
+ }
+ if (request.executionPath === 'batch') {
+ return {
+ ...base,
+ code: 'BATCH_BYPASS',
+ elapsedMs: this.clock() - t0,
+ reason: 'Batched dispatch bypasses this guard - the decorator only intercepts `call_tool`.',
+ status: 'skipped',
+ };
+ }
+ try {
+ const result = await this.opts.checkPermission({
+ agentId: request.agentId ?? 'unknown',
+ args,
+ toolName: request.apiName,
+ });
+ const level = result.level ?? (result.allowed ? 'autonomous' : 'forbidden');
+ const status = result.allowed
+ ? level === 'notify-and-proceed'
+ ? 'warn'
+ : 'pass'
+ : level === 'approval-required'
+ ? 'approval_required'
+ : 'block';
+ return {
+ ...base,
+ code: result.allowed ? undefined : `PERMISSION_${level.toUpperCase().replaceAll('-', '_')}`,
+ detail: { level, pendingApprovalId: result.pendingApprovalId },
+ elapsedMs: this.clock() - t0,
+ reason: result.reason ?? `Permission level resolved to \`${level}\`.`,
+ status,
+ };
+ }
+ catch (error) {
+ return {
+ ...base,
+ code: 'PERMISSION_ERROR',
+ elapsedMs: this.clock() - t0,
+ reason: `Permission check failed, so the call is refused: ${error instanceof Error ? error.message : String(error)}`,
+ status: 'error',
+ };
+ }
+ }
+ // ── Layer 5: DeFi guard ──────────────────────────────────────────────────
+ async runDeFiGuard(request, args) {
+ const t0 = this.clock();
+ const base = { label: LAYER_LABELS.defi_guard, layer: 'defi_guard' };
+ if (!this.opts.defiGuard) {
+ return {
+ result: {
+ ...base,
+ elapsedMs: this.clock() - t0,
+ reason: 'No DeFiGuard instance is wired into this evaluation.',
+ status: 'skipped',
+ },
+ warnings: [],
+ };
+ }
+ if (!this.opts.defiGuard.isDeFiTool(request.identifier)) {
+ return {
+ result: {
+ ...base,
+ code: 'NOT_REGISTERED',
+ detail: { identifier: request.identifier },
+ elapsedMs: this.clock() - t0,
+ reason: `\`${request.identifier}\` is not in the DeFi tool registry, so no risk or MEV analysis ran.`,
+ status: 'skipped',
+ },
+ warnings: [],
+ };
+ }
+ try {
+ const guardResult = await this.opts.defiGuard.analyze({
+ apiName: request.apiName,
+ arguments: args,
+ chainId: request.chainId,
+ identifier: request.identifier,
+ portfolioPositions: request.portfolioPositions,
+ protocol: request.protocol,
+ userId: request.userId,
+ userSwapCaps: request.userSwapCaps,
+ userSwapVolume: request.userSwapVolume,
+ userTier: request.userTier,
+ valueUsd: request.valueUsd,
+ });
+ const { analysis } = guardResult;
+ return {
+ modifiedArguments: guardResult.modifiedArguments,
+ result: {
+ ...base,
+ code: analysis.capCode ?? (analysis.decision === 'allow' ? undefined : 'DEFI_RISK'),
+ detail: {
+ capCode: analysis.capCode,
+ isMutating: analysis.isMutating,
+ mevAssessment: analysis.mevAssessment,
+ parameterAdjustments: analysis.parameterAdjustments,
+ protocolStatus: analysis.protocolStatus,
+ remainingDailyVolumeUsd: analysis.remainingDailyVolumeUsd,
+ riskReport: analysis.riskReport,
+ },
+ elapsedMs: this.clock() - t0,
+ reason: analysis.reason,
+ status: decisionToStatus(analysis.decision),
+ },
+ warnings: analysis.warnings,
+ };
+ }
+ catch (error) {
+ return {
+ result: {
+ ...base,
+ code: 'DEFI_GUARD_ERROR',
+ elapsedMs: this.clock() - t0,
+ reason: `DeFi analysis failed, so the call is refused: ${error instanceof Error ? error.message : String(error)}`,
+ status: 'error',
+ },
+ warnings: [],
+ };
+ }
+ }
+ // ── Layer 6: spend envelope ──────────────────────────────────────────────
+ runSpendGuard(request) {
+ const t0 = this.clock();
+ const base = { label: LAYER_LABELS.spend_guard, layer: 'spend_guard' };
+ if (!this.opts.spendGuard) {
+ return {
+ ...base,
+ elapsedMs: this.clock() - t0,
+ reason: 'No spend envelope is configured for this agent.',
+ status: 'skipped',
+ };
+ }
+ if (!isOutflow(request.apiName)) {
+ return {
+ ...base,
+ detail: { apiName: request.apiName },
+ elapsedMs: this.clock() - t0,
+ reason: MUTATING_APIS.has(request.apiName)
+ ? 'Inflow or neutral operation - deliberately exempt from spend caps.'
+ : 'Read-only operation - no value leaves the wallet.',
+ status: 'skipped',
+ };
+ }
+ const result = this.opts.spendGuard.check({
+ agentId: request.agentId ?? 'unknown',
+ balanceUsd: request.balanceUsd,
+ destination: request.destination,
+ token: request.token,
+ userId: request.userId,
+ valueUsd: request.valueUsd ?? 0,
+ });
+ return {
+ ...base,
+ code: result.code,
+ detail: {
+ remainingDailyUsd: result.remainingDailyUsd,
+ remainingRollingUsd: result.remainingRollingUsd,
+ valueUsd: request.valueUsd ?? 0,
+ },
+ elapsedMs: this.clock() - t0,
+ reason: result.reason,
+ status: result.allowed ? 'pass' : 'block',
+ };
+ }
+ // ── Layer 7: x402 autonomy budget ────────────────────────────────────────
+ async runX402(request) {
+ const t0 = this.clock();
+ const base = { label: LAYER_LABELS.x402, layer: 'x402' };
+ if (!request.x402) {
+ return {
+ ...base,
+ elapsedMs: this.clock() - t0,
+ reason: 'Not an x402-metered request.',
+ status: 'skipped',
+ };
+ }
+ if (!this.opts.x402Hook) {
+ return {
+ ...base,
+ elapsedMs: this.clock() - t0,
+ reason: 'x402 payment context supplied but no autonomy hook is wired.',
+ status: 'skipped',
+ };
+ }
+ try {
+ const result = await this.opts.x402Hook({
+ agentId: request.agentId ?? 'unknown',
+ amountSpentThisHourUsdc: request.x402.amountSpentThisHourUsdc,
+ currentBalanceUsdc: request.x402.currentBalanceUsdc,
+ requirements: request.x402.requirements,
+ url: request.x402.url,
+ });
+ const status = result.action === 'pay' ? 'pass' : result.action === 'queue' ? 'approval_required' : 'block';
+ return {
+ ...base,
+ code: result.action === 'pay' ? undefined : `X402_${result.action.toUpperCase()}`,
+ detail: { action: result.action },
+ elapsedMs: this.clock() - t0,
+ reason: result.action === 'pay' ? 'Within the hourly autonomy budget.' : result.reason,
+ status,
+ };
+ }
+ catch (error) {
+ return {
+ ...base,
+ code: 'X402_ERROR',
+ elapsedMs: this.clock() - t0,
+ reason: `x402 hook failed, so the payment is refused: ${error instanceof Error ? error.message : String(error)}`,
+ status: 'error',
+ };
+ }
+ }
+ // ── Verdict folding ──────────────────────────────────────────────────────
+ /**
+ * Select the layer that determines the verdict: the highest-severity status,
+ * with earlier layers winning ties so the reported reason matches the layer
+ * that would actually fire first at runtime.
+ */
+ pickDecidingLayer(layers) {
+ let best;
+ for (const layer of layers) {
+ if (layer.status === 'skipped' || layer.status === 'pass')
+ continue;
+ if (!best || STATUS_SEVERITY[layer.status] > STATUS_SEVERITY[best.status])
+ best = layer;
+ }
+ return best;
+ }
+ /**
+ * Coverage is measured against the layers that *should* apply to this request,
+ * not against all seven. Charging a read-only call for skipping the spend
+ * envelope would make the number meaningless.
+ */
+ computeCoverage(request, layers) {
+ const applicable = new Set(['security_blacklist', 'intervention']);
+ // The executor-decorator guards apply to any tool dispatched individually.
+ applicable.add('capability');
+ applicable.add('permission');
+ if (DEFI_TOOL_IDENTIFIERS.has(request.identifier) || looksMutating(request.apiName)) {
+ applicable.add('defi_guard');
+ }
+ if (isOutflow(request.apiName))
+ applicable.add('spend_guard');
+ if (request.x402)
+ applicable.add('x402');
+ let expected = 0;
+ let evaluated = 0;
+ for (const layer of layers) {
+ if (!applicable.has(layer.layer))
+ continue;
+ expected += LAYER_WEIGHTS[layer.layer];
+ if (layer.status !== 'skipped')
+ evaluated += LAYER_WEIGHTS[layer.layer];
+ }
+ if (expected === 0)
+ return 100;
+ return Math.round((evaluated / expected) * 100);
+ }
+ // ── Blind-spot derivation ────────────────────────────────────────────────
+ /**
+ * Derive the enforcement gaps this request would hit. These are structural -
+ * they describe checks that did not happen, which no individual guard reports
+ * because from its own perspective nothing went wrong.
+ */
+ deriveBlindSpots(request, layers) {
+ const spots = [];
+ const byId = new Map(layers.map((l) => [l.layer, l]));
+ const registered = DEFI_TOOL_IDENTIFIERS.has(request.identifier);
+ const mutating = MUTATING_APIS.has(request.apiName);
+ // 1. A registered, mutating call with no authoritative USD value: the dollar
+ // caps compare against 0 and pass, and MEV analysis never runs.
+ if (registered && mutating && (request.valueUsd === undefined || request.valueUsd <= 0)) {
+ spots.push({
+ code: 'VALUE_UNRESOLVED',
+ detail: 'No authoritative `valueUsd` was supplied, and the guard never reads a token `amount` as dollars ' +
+ '(0.5 ETH would otherwise be priced at $0.50). Every dollar-denominated check therefore compares ' +
+ 'against $0 and passes: tier limits, per-user caps, the auto-execute ceiling, daily volume, and ' +
+ 'MEV analysis, which needs a notional to estimate extractable value.',
+ layer: 'defi_guard',
+ remediation: 'Resolve the USD notional server-side - amount × spot price, or the quote’s `fromAmountUsd` - and pass it as `valueUsd`.',
+ severity: 'critical',
+ title: 'Dollar caps evaluated against $0',
+ });
+ }
+ // 2. An on-chain mutation on a tool the guard does not know about.
+ if (!registered && (mutating || looksMutating(request.apiName))) {
+ spots.push({
+ code: 'TOOL_UNREGISTERED',
+ detail: `\`${request.apiName}\` mutates on-chain state, but \`${request.identifier}\` is absent from ` +
+ 'the DeFi tool registry. `isDeFiTool()` returns false, so DeFiGuard returns early and the entire ' +
+ 'risk, MEV, cap, and protocol-audit surface is skipped for this call.',
+ layer: 'defi_guard',
+ remediation: `Add \`${request.identifier}\` to DEFI_TOOL_IDENTIFIERS via registerFundMovingTool() in toolRegistry.ts.`,
+ severity: 'critical',
+ title: 'Fund-moving tool not registered with DeFiGuard',
+ });
+ }
+ // 3. Batched dispatch bypasses the executor decorators entirely.
+ if (request.executionPath === 'batch') {
+ spots.push({
+ code: 'BATCH_BYPASS',
+ detail: 'Both guards are executor decorators that intercept only `call_tool`. A tool dispatched through ' +
+ '`call_tools_batch` reaches its handler without any capability-token or permission check - and the ' +
+ 'batch executor applies no concurrency cap, so every tool in the batch runs at once.',
+ layer: 'permission',
+ remediation: 'Route fund-moving tools through single dispatch, or wrap the `call_tools_batch` executor with the same guards.',
+ severity: 'critical',
+ title: 'Capability and permission guards bypassed by batching',
+ });
+ }
+ // 4. Value leaves the wallet with no envelope to bound it.
+ if (isOutflow(request.apiName) && byId.get('spend_guard')?.status === 'skipped') {
+ spots.push({
+ code: 'SPEND_UNSCOPED',
+ detail: `\`${request.apiName}\` moves value out of the agent wallet, but no spend envelope is configured. ` +
+ 'Per-transaction, rolling-window, and daily caps, the reserve floor, and the token/destination ' +
+ 'firewall are all unenforced, and the custody-breach latch can never trip.',
+ layer: 'spend_guard',
+ remediation: 'Attach a SpendGuard with per-tx, rolling, and daily caps for this agent.',
+ severity: 'critical',
+ title: 'Outflow with no spend envelope',
+ });
+ }
+ // 5. Protocol audit status defaults to unaudited when the registry is empty.
+ const defiDetail = byId.get('defi_guard')?.detail;
+ if (registered && request.protocol && defiDetail?.protocolStatus === 'unaudited') {
+ spots.push({
+ code: 'PROTOCOL_UNVERIFIED',
+ detail: `\`${request.protocol}\` is not present in the protocol registry, so it is treated as unaudited. ` +
+ 'With an empty registry every protocol reads the same way, which makes the audit signal carry no information.',
+ layer: 'defi_guard',
+ remediation: 'Populate `protocolRegistry` in the guard config so audited protocols are distinguishable from unknown ones.',
+ severity: 'warning',
+ title: 'Protocol audit status unverifiable',
+ });
+ }
+ // 6/7. Guards that were never wired into this evaluation at all.
+ if (byId.get('capability')?.status === 'skipped' && !this.opts.checkCapability) {
+ spots.push({
+ code: 'CAPABILITY_UNWIRED',
+ detail: 'No capability-token validator was supplied, so scope-limited delegation is not enforced on this path.',
+ layer: 'capability',
+ remediation: 'Inject `checkCapability` backed by the capabilityToken records.',
+ severity: 'warning',
+ title: 'Capability guard not wired',
+ });
+ }
+ if (byId.get('permission')?.status === 'skipped' && !this.opts.checkPermission) {
+ spots.push({
+ code: 'PERMISSION_UNWIRED',
+ detail: 'No permission resolver was supplied, so the agent’s permission level is not consulted on this path.',
+ layer: 'permission',
+ remediation: 'Inject `checkPermission` backed by the agentPermission records.',
+ severity: 'warning',
+ title: 'Permission guard not wired',
+ });
+ }
+ // 8. Read-only DeFi calls are unanalyzed by default.
+ if (registered && !mutating) {
+ spots.push({
+ code: 'READONLY_UNANALYZED',
+ detail: `\`${request.apiName}\` is not a mutating API, and \`analyzeReadOnly\` defaults to false, so the ` +
+ 'guard returns immediately. This is intentional and cheap, but it means read paths carry no risk telemetry.',
+ layer: 'defi_guard',
+ remediation: 'Set `analyzeReadOnly: true` if read-path risk telemetry is wanted.',
+ severity: 'info',
+ title: 'Read-only call not analyzed',
+ });
+ }
+ return spots;
+ }
+}
+/**
+ * Compare a set of live tool identifiers against the DeFi enforcement registry.
+ *
+ * Pass the identifiers actually installed in a deployment to find fund-moving
+ * tools that no guard would ever see. With no argument it reports the registry
+ * itself.
+ */
+export function analyzeGuardCoverage(installedIdentifiers) {
+ const mutatingApis = [...MUTATING_APIS].sort();
+ const registryIds = [...DEFI_TOOL_IDENTIFIERS].sort();
+ const supplied = installedIdentifiers ? [...new Set(installedIdentifiers)].sort() : registryIds;
+ const registered = [];
+ const unregistered = [];
+ for (const identifier of supplied) {
+ const entry = {
+ apis: [],
+ identifier,
+ registered: DEFI_TOOL_IDENTIFIERS.has(identifier),
+ };
+ if (entry.registered)
+ registered.push(entry);
+ else
+ unregistered.push(entry);
+ }
+ return {
+ coveragePercent: supplied.length === 0 ? 100 : Math.round((registered.length / supplied.length) * 100),
+ mutatingApis,
+ registered,
+ unregistered,
+ };
+}
+/** Human-readable label for a layer id, for callers rendering a trace. */
+export function guardLayerLabel(layer) {
+ return LAYER_LABELS[layer];
+}
+/** Relative enforcement weight of a layer, exposed for callers scoring coverage. */
+export function guardLayerWeight(layer) {
+ return LAYER_WEIGHTS[layer];
+}
+/** The layers `GuardChain` evaluates, in order. */
+export const GUARD_LAYER_ORDER = [
+ 'security_blacklist',
+ 'intervention',
+ 'capability',
+ 'permission',
+ 'defi_guard',
+ 'spend_guard',
+ 'x402',
+];
diff --git a/packages/agent-runtime/src/core/InterventionChecker.d.ts b/packages/agent-runtime/src/core/InterventionChecker.d.ts
new file mode 100644
index 000000000..f5c1f33c3
--- /dev/null
+++ b/packages/agent-runtime/src/core/InterventionChecker.d.ts
@@ -0,0 +1,84 @@
+import type { HumanInterventionPolicy, SecurityBlacklistRule, ShouldInterveneParams } from '../types/vendor.js';
+/**
+ * Result of security blacklist check
+ */
+export interface SecurityCheckResult {
+ /**
+ * Whether the operation is blocked by security rules
+ */
+ blocked: boolean;
+ /**
+ * Reason for blocking (if blocked)
+ */
+ reason?: string;
+}
+/**
+ * Intervention Checker
+ * Determines whether a tool call requires human intervention
+ */
+export declare class InterventionChecker {
+ /**
+ * Check if tool call is blocked by security blacklist
+ * This check runs BEFORE all other intervention checks
+ *
+ * @param securityBlacklist - Security blacklist rules
+ * @param toolArgs - Tool call arguments
+ * @returns Security check result
+ */
+ static checkSecurityBlacklist(securityBlacklist?: SecurityBlacklistRule[], toolArgs?: Record<string, any>): SecurityCheckResult;
+ /**
+ * Check if a tool call requires intervention
+ *
+ * @param params - Parameters object containing config, toolArgs, confirmedHistory, and toolKey
+ * @returns Policy to apply
+ */
+ static shouldIntervene(params: ShouldInterveneParams): HumanInterventionPolicy;
+ /**
+ * Check if tool arguments match a security blacklist rule
+ *
+ * @param rule - Security rule to check
+ * @param toolArgs - Tool call arguments
+ * @returns true if matches (should be blocked)
+ */
+ private static matchesSecurityRule;
+ /**
+ * Check if tool arguments match a rule
+ *
+ * @param rule - Rule to check
+ * @param toolArgs - Tool call arguments
+ * @returns true if matches
+ */
+ private static matchesRule;
+ /**
+ * Check if a parameter value matches the matcher
+ *
+ * @param matcher - Argument matcher
+ * @param value - Parameter value
+ * @returns true if matches
+ */
+ private static matchesArgument;
+ /**
+ * Match wildcard pattern (supports * wildcard)
+ *
+ * @param pattern - Pattern with wildcards
+ * @param value - Value to match
+ * @returns true if matches
+ */
+ private static matchPattern;
+ /**
+ * Generate tool key from identifier and API name
+ *
+ * @param identifier - Tool identifier
+ * @param apiName - API name
+ * @param argsHash - Optional hash of arguments
+ * @returns Tool key in format "identifier/apiName" or "identifier/apiName#hash"
+ */
+ static generateToolKey(identifier: string, apiName: string, argsHash?: string): string;
+ /**
+ * Generate simple hash of arguments for tool tracking
+ *
+ * @param args - Tool call arguments
+ * @returns Hash string
+ */
+ static hashArguments(args: Record<string, any>): string;
+}
diff --git a/packages/agent-runtime/src/core/InterventionChecker.js b/packages/agent-runtime/src/core/InterventionChecker.js
new file mode 100644
index 000000000..d86d9b9af
--- /dev/null
+++ b/packages/agent-runtime/src/core/InterventionChecker.js
@@ -0,0 +1,192 @@
+import { DEFAULT_SECURITY_BLACKLIST } from './defaultSecurityBlacklist.js';
+/**
+ * Intervention Checker
+ * Determines whether a tool call requires human intervention
+ */
+export class InterventionChecker {
+ /**
+ * Check if tool call is blocked by security blacklist
+ * This check runs BEFORE all other intervention checks
+ *
+ * @param securityBlacklist - Security blacklist rules
+ * @param toolArgs - Tool call arguments
+ * @returns Security check result
+ */
+ static checkSecurityBlacklist(securityBlacklist = [], toolArgs = {}) {
+ for (const rule of securityBlacklist) {
+ if (this.matchesSecurityRule(rule, toolArgs)) {
+ return {
+ blocked: true,
+ reason: rule.description,
+ };
+ }
+ }
+ return { blocked: false };
+ }
+ /**
+ * Check if a tool call requires intervention
+ *
+ * @param params - Parameters object containing config, toolArgs, confirmedHistory, and toolKey
+ * @returns Policy to apply
+ */
+ static shouldIntervene(params) {
+ const { config, toolArgs = {} } = params;
+ // Use default blacklist if not provided
+ const securityBlacklist = params.securityBlacklist !== undefined
+ ? params.securityBlacklist
+ : DEFAULT_SECURITY_BLACKLIST;
+ // CRITICAL: Check security blacklist first - this overrides ALL other settings
+ const securityCheck = this.checkSecurityBlacklist(securityBlacklist, toolArgs);
+ if (securityCheck.blocked) {
+ // Security blacklist always requires intervention, even in auto-run mode
+ return 'required';
+ }
+ // No config means never intervene (auto-execute)
+ if (!config)
+ return 'never';
+ // Simple policy string
+ if (typeof config === 'string') {
+ return config;
+ }
+ // Array of rules - find first matching rule
+ for (const rule of config) {
+ if (this.matchesRule(rule, toolArgs)) {
+ return rule.policy;
+ }
+ }
+ // No rule matched - default to require for safety
+ return 'required';
+ }
+ /**
+ * Check if tool arguments match a security blacklist rule
+ *
+ * @param rule - Security rule to check
+ * @param toolArgs - Tool call arguments
+ * @returns true if matches (should be blocked)
+ */
+ static matchesSecurityRule(rule, toolArgs) {
+ // Security rules must have match criteria
+ if (!rule.match)
+ return false;
+ // All matchers must match (AND logic)
+ for (const [paramName, matcher] of Object.entries(rule.match)) {
+ const paramValue = toolArgs[paramName];
+ // Parameter not present in args - rule doesn't match
+ if (paramValue === undefined)
+ return false;
+ // Check if value matches
+ if (!this.matchesArgument(matcher, paramValue)) {
+ return false;
+ }
+ }
+ return true;
+ }
+ /**
+ * Check if tool arguments match a rule
+ *
+ * @param rule - Rule to check
+ * @param toolArgs - Tool call arguments
+ * @returns true if matches
+ */
+ static matchesRule(rule, toolArgs) {
+ // No match criteria means it's a default rule
+ if (!rule.match)
+ return true;
+ // Check each parameter matcher
+ for (const [paramName, matcher] of Object.entries(rule.match)) {
+ const paramValue = toolArgs[paramName];
+ // Parameter not present in args
+ if (paramValue === undefined)
+ return false;
+ // Check if value matches
+ if (!this.matchesArgument(matcher, paramValue)) {
+ return false;
+ }
+ }
+ return true;
+ }
+ /**
+ * Check if a parameter value matches the matcher
+ *
+ * @param matcher - Argument matcher
+ * @param value - Parameter value
+ * @returns true if matches
+ */
+ static matchesArgument(matcher, value) {
+ const strValue = String(value);
+ // Simple string matcher
+ if (typeof matcher === 'string') {
+ return this.matchPattern(matcher, strValue);
+ }
+ // Complex matcher with type
+ const { pattern, type } = matcher;
+ switch (type) {
+ case 'exact': {
+ return strValue === pattern;
+ }
+ case 'prefix': {
+ return strValue.startsWith(pattern);
+ }
+ case 'wildcard': {
+ return this.matchPattern(pattern, strValue);
+ }
+ case 'regex': {
+ return new RegExp(pattern).test(strValue);
+ }
+ default: {
+ return false;
+ }
+ }
+ }
+ /**
+ * Match wildcard pattern (supports * wildcard)
+ *
+ * @param pattern - Pattern with wildcards
+ * @param value - Value to match
+ * @returns true if matches
+ */
+ static matchPattern(pattern, value) {
+ // Check for colon-based prefix matching (e.g., "git add:*")
+ if (pattern.includes(':')) {
+ const [prefix, suffix] = pattern.split(':');
+ if (suffix === '*') {
+ return value.startsWith(prefix + ':') || value === prefix;
+ }
+ }
+ // Convert wildcard pattern to regex
+ const regexPattern = pattern
+ .replaceAll(/[$()+.?[\\\]^{|}]/g, '\\$&') // Escape special chars
+ .replaceAll('*', '.*'); // Replace * with .*
+ return new RegExp(`^${regexPattern}$`).test(value);
+ }
+ /**
+ * Generate tool key from identifier and API name
+ *
+ * @param identifier - Tool identifier
+ * @param apiName - API name
+ * @param argsHash - Optional hash of arguments
+ * @returns Tool key in format "identifier/apiName" or "identifier/apiName#hash"
+ */
+ static generateToolKey(identifier, apiName, argsHash) {
+ const baseKey = `${identifier}/${apiName}`;
+ return argsHash ? `${baseKey}#${argsHash}` : baseKey;
+ }
+ /**
+ * Generate simple hash of arguments for tool tracking
+ *
+ * @param args - Tool call arguments
+ * @returns Hash string
+ */
+ static hashArguments(args) {
+ const sortedKeys = Object.keys(args).sort();
+ const str = sortedKeys.map((key) => `${key}=${JSON.stringify(args[key])}`).join('&');
+ // Simple hash function
+ let hash = 0;
+ for (let i = 0; i < str.length; i++) {
+ const char = str.charCodeAt(i);
+ hash = (hash << 5) - hash + char;
+ hash = hash & hash; // Convert to 32-bit integer
+ }
+ return Math.abs(hash).toString(36);
+ }
+}
diff --git a/packages/agent-runtime/src/core/PermissionGuard.d.ts b/packages/agent-runtime/src/core/PermissionGuard.d.ts
new file mode 100644
index 000000000..73c2dd45d
--- /dev/null
+++ b/packages/agent-runtime/src/core/PermissionGuard.d.ts
@@ -0,0 +1,57 @@
+import type { InstructionExecutor } from '../types/index.js';
+/**
+ * Permission check result returned by the guard callback.
+ */
+export interface PermissionCheckResult {
+ /** Whether the action is allowed to proceed */
+ allowed: boolean;
+ /** Human-readable reason */
+ reason?: string;
+ /** Permission level that was applied */
+ level?: string;
+ /** If a pending-approval audit entry was created, its ID */
+ pendingApprovalId?: string;
+}
+/**
+ * Callback type that the consumer provides to perform
+ * the actual permission check against their database / service layer.
+ *
+ * The runtime package itself is database-agnostic; the check is injected.
+ */
+export type PermissionCheckFn = (params: {
+ /** Parsed tool arguments */
+ args: unknown;
+ /** The agent ID (from state) */
+ agentId: string;
+ /** Tool name being called */
+ toolName: string;
+}) => Promise<PermissionCheckResult>;
+/**
+ * PermissionGuard - wraps a standard `call_tool` InstructionExecutor
+ * with a permission check that runs **before** the tool handler is invoked.
+ *
+ * Usage:
+ * ```ts
+ * const guard = new PermissionGuard(myPermissionCheckFn);
+ * const runtime = new AgentRuntime(agent, {
+ * executors: {
+ * call_tool: guard.wrap(defaultCallToolExecutor),
+ * },
+ * });
+ * ```
+ *
+ * Behaviour per permission level:
+ * - FORBIDDEN → tool is not executed; an error tool message is pushed
+ * - APPROVAL_REQUIRED → tool is not executed; a `permission_pending` event is emitted
+ * - NOTIFY_AND_PROCEED → tool executes; a `permission_notify` event is emitted
+ * - AUTONOMOUS → tool executes normally
+ */
+export declare class PermissionGuard {
+ private checkPermission;
+ constructor(checkPermission: PermissionCheckFn);
+ /**
+ * Returns a new InstructionExecutor that intercepts `call_tool`
+ * instructions and gates them through the permission check.
+ */
+ wrap(innerExecutor: InstructionExecutor): InstructionExecutor;
+}
diff --git a/packages/agent-runtime/src/core/PermissionGuard.js b/packages/agent-runtime/src/core/PermissionGuard.js
new file mode 100644
index 000000000..8c8b74e25
--- /dev/null
+++ b/packages/agent-runtime/src/core/PermissionGuard.js
@@ -0,0 +1,119 @@
+/**
+ * PermissionGuard - wraps a standard `call_tool` InstructionExecutor
+ * with a permission check that runs **before** the tool handler is invoked.
+ *
+ * Usage:
+ * ```ts
+ * const guard = new PermissionGuard(myPermissionCheckFn);
+ * const runtime = new AgentRuntime(agent, {
+ * executors: {
+ * call_tool: guard.wrap(defaultCallToolExecutor),
+ * },
+ * });
+ * ```
+ *
+ * Behaviour per permission level:
+ * - FORBIDDEN → tool is not executed; an error tool message is pushed
+ * - APPROVAL_REQUIRED → tool is not executed; a `permission_pending` event is emitted
+ * - NOTIFY_AND_PROCEED → tool executes; a `permission_notify` event is emitted
+ * - AUTONOMOUS → tool executes normally
+ */
+export class PermissionGuard {
+ checkPermission;
+ constructor(checkPermission) {
+ this.checkPermission = checkPermission;
+ }
+ /**
+ * Returns a new InstructionExecutor that intercepts `call_tool`
+ * instructions and gates them through the permission check.
+ */
+ wrap(innerExecutor) {
+ return async (instruction, state, context) => {
+ // Only guard call_tool instructions
+ if (instruction.type !== 'call_tool') {
+ return innerExecutor(instruction, state, context);
+ }
+ const payload = instruction.payload;
+ const toolCalling = payload?.toolCalling;
+ if (!toolCalling) {
+ return innerExecutor(instruction, state, context);
+ }
+ const toolName = toolCalling.apiName;
+ const toolId = toolCalling.id;
+ // Parse args for the permission check
+ let parsedArgs;
+ try {
+ parsedArgs = JSON.parse(toolCalling.arguments);
+ }
+ catch {
+ parsedArgs = {};
+ }
+ // Run permission check
+ // agentId may live in state.metadata (set by the server-side executor)
+ const agentId = state.metadata?.agentId ?? 'unknown';
+ const result = await this.checkPermission({
+ agentId,
+ args: parsedArgs,
+ toolName,
+ });
+ // ── FORBIDDEN ──────────────────────────────────────────
+ if (!result.allowed && result.level === 'forbidden') {
+ const newState = structuredClone(state);
+ newState.lastModified = new Date().toISOString();
+ newState.messages.push({
+ content: JSON.stringify({
+ error: 'Permission denied',
+ level: 'forbidden',
+ reason: result.reason ?? 'This action is forbidden by your permission settings.',
+ }),
+ role: 'tool',
+ tool_call_id: toolId,
+ });
+ const events = [
+ {
+ id: toolId,
+ result: { blocked: true, reason: result.reason },
+ type: 'tool_result',
+ },
+ ];
+ return { events, newState };
+ }
+ // ── APPROVAL_REQUIRED ──────────────────────────────────
+ if (!result.allowed && result.level === 'approval-required') {
+ const newState = structuredClone(state);
+ newState.lastModified = new Date().toISOString();
+ newState.status = 'waiting_for_human';
+ newState.messages.push({
+ content: JSON.stringify({
+ error: 'Awaiting approval',
+ level: 'approval-required',
+ pendingApprovalId: result.pendingApprovalId,
+ reason: result.reason ?? 'This action requires human approval.',
+ }),
+ role: 'tool',
+ tool_call_id: toolId,
+ });
+ const events = [
+ {
+ id: toolId,
+ pendingApprovalId: result.pendingApprovalId,
+ reason: result.reason,
+ type: 'permission_pending',
+ },
+ ];
+ return { events, newState };
+ }
+ // ── NOTIFY_AND_PROCEED / AUTONOMOUS ────────────────────
+ const executorResult = await innerExecutor(instruction, state, context);
+ // For NOTIFY_AND_PROCEED, append a notification event
+ if (result.level === 'notify-and-proceed') {
+ executorResult.events.push({
+ id: toolId,
+ reason: result.reason ?? 'Action executed - user will be notified.',
+ type: 'permission_notify',
+ });
+ }
+ return executorResult;
+ };
+ }
+}
diff --git a/packages/agent-runtime/src/core/ResponseQualityEvaluator.d.ts b/packages/agent-runtime/src/core/ResponseQualityEvaluator.d.ts
new file mode 100644
index 000000000..0b088f109
--- /dev/null
+++ b/packages/agent-runtime/src/core/ResponseQualityEvaluator.d.ts
@@ -0,0 +1,64 @@
+/**
+ * ResponseQualityEvaluator - Post-response quality evaluation for agent outputs.
+ *
+ * After the agent produces a response, this evaluator checks for common
+ * quality issues and flags responses that may need improvement. This enables
+ * a "think twice" pattern where the agent can self-correct before sending.
+ *
+ * Checks performed:
+ * 1. Completeness - Did the agent actually answer the question?
+ * 2. Hallucination signals - Does the response contain known hallucination patterns?
+ * 3. Safety - Does the response contain unsafe content?
+ * 4. Formatting - Is the response well-structured?
+ * 5. Language consistency - Does the response match the query language?
+ */
+export interface QualityIssue {
+ /** Category of the issue */
+ category: 'completeness' | 'hallucination' | 'formatting' | 'language' | 'safety';
+ /** Detailed description */
+ description: string;
+ /** Severity: warning = could be better, error = should be regenerated */
+ severity: 'warning' | 'error';
+}
+export interface QualityEvaluation {
+ /** List of detected issues */
+ issues: QualityIssue[];
+ /** Whether the response passed quality checks */
+ passed: boolean;
+ /** Structured prompt to inject for self-correction if needed */
+ selfCorrectionPrompt?: string;
+}
+export declare class ResponseQualityEvaluator {
+ /**
+ * Evaluate a response against the original query.
+ *
+ * @param query - The user's original query
+ * @param response - The agent's generated response
+ * @param toolResults - Optional tool results that were used
+ * @returns Quality evaluation with issues and optional correction prompt
+ */
+ evaluate(query: string, response: string, toolResults?: Array<{
+ content: string;
+ success: boolean;
+ }>): QualityEvaluation;
+ /**
+ * Check if the response actually addresses the user's query.
+ */
+ private checkCompleteness;
+ /**
+ * Check for common hallucination signals in the response.
+ */
+ private checkHallucinationSignals;
+ /**
+ * Check response formatting quality.
+ */
+ private checkFormatting;
+ /**
+ * Check that response language roughly matches query language.
+ */
+ private checkLanguageConsistency;
+ /**
+ * Generate a self-correction prompt from detected issues.
+ */
+ private generateCorrectionPrompt;
+}
diff --git a/packages/agent-runtime/src/core/ResponseQualityEvaluator.js b/packages/agent-runtime/src/core/ResponseQualityEvaluator.js
new file mode 100644
index 000000000..572b83db0
--- /dev/null
+++ b/packages/agent-runtime/src/core/ResponseQualityEvaluator.js
@@ -0,0 +1,200 @@
+/**
+ * ResponseQualityEvaluator - Post-response quality evaluation for agent outputs.
+ *
+ * After the agent produces a response, this evaluator checks for common
+ * quality issues and flags responses that may need improvement. This enables
+ * a "think twice" pattern where the agent can self-correct before sending.
+ *
+ * Checks performed:
+ * 1. Completeness - Did the agent actually answer the question?
+ * 2. Hallucination signals - Does the response contain known hallucination patterns?
+ * 3. Safety - Does the response contain unsafe content?
+ * 4. Formatting - Is the response well-structured?
+ * 5. Language consistency - Does the response match the query language?
+ */
+export class ResponseQualityEvaluator {
+ /**
+ * Evaluate a response against the original query.
+ *
+ * @param query - The user's original query
+ * @param response - The agent's generated response
+ * @param toolResults - Optional tool results that were used
+ * @returns Quality evaluation with issues and optional correction prompt
+ */
+ evaluate(query, response, toolResults) {
+ const issues = [];
+ // Run all checks
+ issues.push(...this.checkCompleteness(query, response));
+ issues.push(...this.checkHallucinationSignals(response, toolResults));
+ issues.push(...this.checkFormatting(response));
+ issues.push(...this.checkLanguageConsistency(query, response));
+ const hasErrors = issues.some((i) => i.severity === 'error');
+ const passed = !hasErrors;
+ const evaluation = { issues, passed };
+ if (!passed) {
+ evaluation.selfCorrectionPrompt = this.generateCorrectionPrompt(issues, query);
+ }
+ return evaluation;
+ }
+ /**
+ * Check if the response actually addresses the user's query.
+ */
+ checkCompleteness(query, response) {
+ const issues = [];
+ // Empty or near-empty response
+ if (!response || response.trim().length < 10) {
+ issues.push({
+ category: 'completeness',
+ description: 'Response is empty or too short to be useful',
+ severity: 'error',
+ });
+ return issues;
+ }
+ // Response is just a generic filler
+ const genericFillers = [
+ 'i understand',
+ 'sure, i can help',
+ 'let me help you',
+ 'of course',
+ 'certainly',
+ ];
+ const responseLower = response.toLowerCase().trim();
+ if (genericFillers.some((filler) => responseLower === filler)) {
+ issues.push({
+ category: 'completeness',
+ description: 'Response is a generic filler without substantive content',
+ severity: 'warning',
+ });
+ }
+ // Check for question-response mismatch: user asked a question but response doesn't
+ // contain any informational content
+ const isQuestion = /\?|what|how|why|when|where|which|who|can you|could you/i.test(query);
+ if (isQuestion && response.length < 50 && !response.includes('?')) {
+ issues.push({
+ category: 'completeness',
+ description: 'User asked a question but response seems incomplete',
+ severity: 'warning',
+ });
+ }
+ return issues;
+ }
+ /**
+ * Check for common hallucination signals in the response.
+ */
+ checkHallucinationSignals(response, toolResults) {
+ const issues = [];
+ // Pattern: Agent claims specific numbers but no tool was used to fetch data
+ const hasSpecificNumbers = /\$[\d,.]+\s*(billion|million|trillion|B|M|T|k)/i.test(response);
+ const hasToolData = toolResults && toolResults.some((t) => t.success);
+ if (hasSpecificNumbers && !hasToolData) {
+ issues.push({
+ category: 'hallucination',
+ description: 'Response contains specific financial figures but no data tool was called to verify them. These may be outdated or hallucinated.',
+ severity: 'warning',
+ });
+ }
+ // Pattern: Agent invents URLs
+ const urlPattern = /https?:\/\/[^\s)]+/g;
+ const urls = response.match(urlPattern) || [];
+ const suspiciousUrls = urls.filter((url) =>
+ // URLs that look fabricated (unusual TLDs, very long random paths)
+ /[a-z]{20,}/.test(url) || /\d{10,}/.test(url));
+ if (suspiciousUrls.length > 0) {
+ issues.push({
+ category: 'hallucination',
+ description: `Response contains ${suspiciousUrls.length} potentially fabricated URL(s)`,
+ severity: 'warning',
+ });
+ }
+ // Pattern: Contradicts tool results
+ if (toolResults) {
+ const failedTools = toolResults.filter((t) => !t.success);
+ if (failedTools.length > 0) {
+ // Check if response claims success despite tool failures
+ const claimsSuccess = /successfully|completed|done|here are the results/i.test(response) &&
+ !response.toLowerCase().includes('error') &&
+ !response.toLowerCase().includes('failed');
+ if (claimsSuccess) {
+ issues.push({
+ category: 'hallucination',
+ description: 'Response claims success but one or more tools failed. The agent may be fabricating results.',
+ severity: 'error',
+ });
+ }
+ }
+ }
+ return issues;
+ }
+ /**
+ * Check response formatting quality.
+ */
+ checkFormatting(response) {
+ const issues = [];
+ // Unclosed code blocks
+ const codeBlockCount = (response.match(/```/g) || []).length;
+ if (codeBlockCount % 2 !== 0) {
+ issues.push({
+ category: 'formatting',
+ description: 'Response has unclosed code block(s)',
+ severity: 'warning',
+ });
+ }
+ // Excessively long response without structure
+ if (response.length > 2000 && !response.includes('\n\n') && !response.includes('#')) {
+ issues.push({
+ category: 'formatting',
+ description: 'Very long response without paragraph breaks or headings',
+ severity: 'warning',
+ });
+ }
+ // Truncated-looking response (ends mid-sentence)
+ const lastChar = response.trim().slice(-1);
+ if (response.length > 200 &&
+ !'.!?:;)>]}`\'"'.includes(lastChar) &&
+ !response.trim().endsWith('```')) {
+ issues.push({
+ category: 'formatting',
+ description: 'Response appears truncated (ends mid-sentence)',
+ severity: 'warning',
+ });
+ }
+ return issues;
+ }
+ /**
+ * Check that response language roughly matches query language.
+ */
+ checkLanguageConsistency(query, response) {
+ const issues = [];
+ // Simple heuristic: detect CJK characters
+ const queryCJK = /[\u4E00-\u9FFF\u3040-\u309F\u30A0-\u30FF\uAC00-\uD7AF]/.test(query);
+ const responseCJK = /[\u4E00-\u9FFF\u3040-\u309F\u30A0-\u30FF\uAC00-\uD7AF]/.test(response);
+ // If query is in CJK but response is entirely non-CJK (or vice versa for long responses)
+ if (queryCJK && !responseCJK && response.length > 100) {
+ issues.push({
+ category: 'language',
+ description: 'User wrote in CJK language but response is in a different language',
+ severity: 'warning',
+ });
+ }
+ return issues;
+ }
+ /**
+ * Generate a self-correction prompt from detected issues.
+ */
+ generateCorrectionPrompt(issues, originalQuery) {
+ const errorIssues = issues.filter((i) => i.severity === 'error');
+ return `<quality_review>
+Your previous response has quality issues that need to be addressed:
+
+${errorIssues.map((i) => `- [${i.category.toUpperCase()}] ${i.description}`).join('\n')}
+
+Please regenerate your response for the original query: "${originalQuery.slice(0, 200)}"
+
+Requirements:
+- Address all flagged issues
+- If you referenced data, ensure it came from a tool call
+- If a tool failed, acknowledge the error honestly
+- Match the user's language
+</quality_review>`;
+ }
+}
diff --git a/packages/agent-runtime/src/core/SelfReflection.d.ts b/packages/agent-runtime/src/core/SelfReflection.d.ts
new file mode 100644
index 000000000..40b5f0505
--- /dev/null
+++ b/packages/agent-runtime/src/core/SelfReflection.d.ts
@@ -0,0 +1,69 @@
+/**
+ * SelfReflection - Adds self-correction and retry logic to agent tool calls.
+ *
+ * When a tool call fails, instead of raw-feeding the error back to the LLM,
+ * this module injects structured self-correction prompts that help the LLM:
+ * 1. Understand what went wrong
+ * 2. Analyze the root cause
+ * 3. Retry with corrected parameters or choose an alternative tool
+ *
+ * This dramatically improves reliability of tool-calling agents,
+ * especially with complex parameter schemas.
+ */
+export interface ToolErrorContext {
+ /** The API name that was called */
+ apiName: string;
+ /** The arguments that were passed (stringified JSON) */
+ arguments: string;
+ /** The error message or failed result */
+ error: string;
+ /** Number of retries already attempted for this specific call */
+ retryCount: number;
+ /** The tool identifier */
+ toolIdentifier: string;
+}
+export interface SelfReflectionConfig {
+ /** Maximum retries per tool call before giving up. Default: 2 */
+ maxRetries?: number;
+ /** Whether to suggest alternative tools on failure. Default: true */
+ suggestAlternatives?: boolean;
+}
+/**
+ * Classification of tool errors to guide the self-correction strategy
+ */
+export type ToolErrorCategory = 'invalid_arguments' | 'missing_required_field' | 'api_rate_limit' | 'network_error' | 'permission_denied' | 'not_found' | 'timeout' | 'unknown';
+export declare class SelfReflection {
+ private config;
+ /** Maps tool_call_id → retry count */
+ private retryTracker;
+ constructor(config?: SelfReflectionConfig);
+ /**
+ * Classify a tool error into a category to guide the correction strategy.
+ * NOTE: Order matters - more specific patterns must be checked before broad ones
+ * (e.g., 'unauthorized' before 'invalid', 'expected' only with 'type' context).
+ */
+ classifyError(error: string): ToolErrorCategory;
+ /**
+ * Generate a self-correction prompt to inject as a system/tool message
+ * that guides the LLM to fix its tool call.
+ */
+ generateCorrectionPrompt(context: ToolErrorContext): string;
+ /**
+ * Track a retry attempt for a specific tool call.
+ * Returns true if retry is allowed, false if max retries exceeded.
+ */
+ trackRetry(toolCallId: string): boolean;
+ /**
+ * Get the current retry count for a tool call.
+ */
+ getRetryCount(toolCallId: string): number;
+ /**
+ * Check if a tool call should be retried based on the error category.
+ * Some errors (like permission_denied) should never be retried.
+ */
+ shouldRetry(error: string): boolean;
+ /**
+ * Reset retry tracking (e.g., at the start of a new conversation turn)
+ */
+ reset(): void;
+}
diff --git a/packages/agent-runtime/src/core/SelfReflection.js b/packages/agent-runtime/src/core/SelfReflection.js
new file mode 100644
index 000000000..e0004dade
--- /dev/null
+++ b/packages/agent-runtime/src/core/SelfReflection.js
@@ -0,0 +1,203 @@
+/**
+ * SelfReflection - Adds self-correction and retry logic to agent tool calls.
+ *
+ * When a tool call fails, instead of raw-feeding the error back to the LLM,
+ * this module injects structured self-correction prompts that help the LLM:
+ * 1. Understand what went wrong
+ * 2. Analyze the root cause
+ * 3. Retry with corrected parameters or choose an alternative tool
+ *
+ * This dramatically improves reliability of tool-calling agents,
+ * especially with complex parameter schemas.
+ */
+const DEFAULT_CONFIG = {
+ maxRetries: 2,
+ suggestAlternatives: true,
+};
+export class SelfReflection {
+ config;
+ /** Maps tool_call_id → retry count */
+ retryTracker = new Map();
+ constructor(config) {
+ this.config = { ...DEFAULT_CONFIG, ...config };
+ }
+ /**
+ * Classify a tool error into a category to guide the correction strategy.
+ * NOTE: Order matters - more specific patterns must be checked before broad ones
+ * (e.g., 'unauthorized' before 'invalid', 'expected' only with 'type' context).
+ */
+ classifyError(error) {
+ const lower = error.toLowerCase();
+ // Check specific categories FIRST (before broad patterns like 'invalid')
+ if (lower.includes('permission') ||
+ lower.includes('forbidden') ||
+ lower.includes('403') ||
+ lower.includes('unauthorized') ||
+ lower.includes('401')) {
+ return 'permission_denied';
+ }
+ if (lower.includes('rate limit') ||
+ lower.includes('429') ||
+ lower.includes('too many requests')) {
+ return 'api_rate_limit';
+ }
+ if (lower.includes('network') ||
+ lower.includes('econnrefused') ||
+ lower.includes('fetch failed') ||
+ lower.includes('dns')) {
+ return 'network_error';
+ }
+ if (lower.includes('not found') || lower.includes('404') || lower.includes('no results')) {
+ return 'not_found';
+ }
+ if (lower.includes('timeout') || lower.includes('timed out') || lower.includes('deadline')) {
+ return 'timeout';
+ }
+ if (lower.includes('required') ||
+ lower.includes('missing') ||
+ lower.includes('undefined')) {
+ return 'missing_required_field';
+ }
+ // Broad patterns checked LAST
+ if (lower.includes('validation') ||
+ lower.includes('schema') ||
+ lower.includes('type error') ||
+ lower.includes('invalid argument') ||
+ lower.includes('invalid param') ||
+ lower.includes('invalid value')) {
+ return 'invalid_arguments';
+ }
+ return 'unknown';
+ }
+ /**
+ * Generate a self-correction prompt to inject as a system/tool message
+ * that guides the LLM to fix its tool call.
+ */
+ generateCorrectionPrompt(context) {
+ const category = this.classifyError(context.error);
+ const retryCount = context.retryCount;
+ const isLastRetry = retryCount >= this.config.maxRetries - 1;
+ let prompt = `<tool_error_analysis>
+Tool: ${context.toolIdentifier}/${context.apiName}
+Error: ${context.error}
+Category: ${category}
+Attempt: ${retryCount + 1}/${this.config.maxRetries}
+Arguments used: ${context.arguments}
+`;
+ switch (category) {
+ case 'invalid_arguments': {
+ prompt += `
+Action required: The arguments you provided are invalid. Please:
+1. Review the tool's parameter schema carefully
+2. Check the data types (string vs number, array vs object)
+3. Ensure enum values match exactly
+4. Retry with corrected arguments
+`;
+ break;
+ }
+ case 'missing_required_field': {
+ prompt += `
+Action required: A required field is missing. Please:
+1. Check which required parameters the tool expects
+2. Add the missing field(s) with appropriate values
+3. Retry with complete arguments
+`;
+ break;
+ }
+ case 'api_rate_limit': {
+ prompt += `
+Action required: The API is rate-limited. Please:
+1. Do NOT retry this exact call immediately
+2. If possible, use a different data source or tool
+3. Inform the user about the rate limit and suggest waiting
+`;
+ break;
+ }
+ case 'network_error': {
+ prompt += `
+Action required: A network error occurred. This is typically transient. Please:
+1. Retry the same call once
+2. If it fails again, inform the user about connectivity issues
+`;
+ break;
+ }
+ case 'permission_denied': {
+ prompt += `
+Action required: Permission was denied. Please:
+1. Do NOT retry with the same parameters
+2. Inform the user that this action requires additional permissions
+3. Suggest alternative approaches that don't require elevated access
+`;
+ break;
+ }
+ case 'not_found': {
+ prompt += `
+Action required: The requested resource was not found. Please:
+1. Verify the identifier/address/name you searched for
+2. Try with corrected or alternative search terms
+3. If the resource genuinely doesn't exist, inform the user
+`;
+ break;
+ }
+ case 'timeout': {
+ prompt += `
+Action required: The operation timed out. Please:
+1. Retry once with a simpler query if possible
+2. If it fails again, inform the user about the timeout
+`;
+ break;
+ }
+ default: {
+ prompt += `
+Action required: An unexpected error occurred. Please:
+1. Analyze the error message for clues
+2. Try with modified arguments or a different approach
+3. If unsure, inform the user about the error
+`;
+ }
+ }
+ if (isLastRetry && this.config.suggestAlternatives) {
+ prompt += `
+⚠️ This is your last retry attempt. If this doesn't work:
+- Try using a different tool that can accomplish the same goal
+- Or inform the user clearly about what went wrong and suggest alternatives
+`;
+ }
+ prompt += `</tool_error_analysis>`;
+ return prompt;
+ }
+ /**
+ * Track a retry attempt for a specific tool call.
+ * Returns true if retry is allowed, false if max retries exceeded.
+ */
+ trackRetry(toolCallId) {
+ const current = this.retryTracker.get(toolCallId) ?? 0;
+ if (current >= this.config.maxRetries) {
+ return false;
+ }
+ this.retryTracker.set(toolCallId, current + 1);
+ return true;
+ }
+ /**
+ * Get the current retry count for a tool call.
+ */
+ getRetryCount(toolCallId) {
+ return this.retryTracker.get(toolCallId) ?? 0;
+ }
+ /**
+ * Check if a tool call should be retried based on the error category.
+ * Some errors (like permission_denied) should never be retried.
+ */
+ shouldRetry(error) {
+ const category = this.classifyError(error);
+ // These error categories should NOT be retried
+ const nonRetryable = ['permission_denied', 'api_rate_limit'];
+ return !nonRetryable.includes(category);
+ }
+ /**
+ * Reset retry tracking (e.g., at the start of a new conversation turn)
+ */
+ reset() {
+ this.retryTracker.clear();
+ }
+}
diff --git a/packages/agent-runtime/src/core/SpendGuard.d.ts b/packages/agent-runtime/src/core/SpendGuard.d.ts
new file mode 100644
index 000000000..a48666fac
--- /dev/null
+++ b/packages/agent-runtime/src/core/SpendGuard.d.ts
@@ -0,0 +1,180 @@
+/**
+ * SpendGuard - Per-Agent Spend Envelope + Token/Target Firewall + Custody Reconciliation
+ *
+ * The quantitative money-safety layer that `PermissionGuard`, `CapabilityGuard`, and
+ * `DeFiGuard` do not encode. Where `DeFiGuard` scores *risk* and enforces *per-user tier*
+ * limits, `SpendGuard` enforces a hard **per-agent spend envelope**:
+ *
+ * 1. **Per-tx maximum** - a single outflow may never exceed `perTxMaxUsd`.
+ * 2. **Rolling / daily caps** - cumulative outflow over a rolling window (default 24h) may
+ * never exceed `rollingMaxUsd` / `dailyMaxUsd`. This is a true sliding window, not a
+ * calendar-day bucket.
+ * 3. **Reserve floor** - a transaction may not drain the agent wallet below `reserveFloorUsd`.
+ * 4. **Token/target firewall** - an allow/deny layer keyed by token *and* destination, with a
+ * strict mode that blocks anything not on the allowlist.
+ * 5. **Custody reconciliation** - sums the *actual* on-chain outflow (independently observed)
+ * against the outflow the agent *recorded* in the Task 03 tamper-evident ledger; if the
+ * chain moved more than the ledger recorded, that is a breach (key-compromise signal) and
+ * the guard **latches shut** for that agent until explicitly reset.
+ *
+ * Ported from three.ws `economy-master.js` (reserve/per-run/per-target guards + registry
+ * allowlist). The Solana multi-wallet funding topology is intentionally NOT ported - only the
+ * guard envelope. Custody here is EVM (Plutus ERC-4337).
+ *
+ * ── Design contract ──
+ * - **Pure & deterministic.** `check()` has no side effects and, for a fixed clock, always
+ * returns the same decision for the same inputs (runtime rule #4). Spend is only mutated by
+ * the explicit `recordSpend()` call, made *after* a transaction actually lands.
+ * - **DB-agnostic.** Per-agent config is resolved server-side (from `agent_spend_limits`) and
+ * passed in; the ledger totals for reconciliation are injected via a `SpendLedgerReader`.
+ * The runtime package never imports the database, exactly like `PermissionGuard`.
+ */
+/** Allow/deny firewall keyed by token symbol/address and destination address. */
+export interface FirewallConfig {
+ /**
+ * When true, a transaction is blocked unless its token is on `allowTokens`
+ * (if that list is non-empty) AND its destination is on `allowDestinations`
+ * (if that list is non-empty). Deny lists always take precedence.
+ */
+ strictMode?: boolean;
+ /** Tokens explicitly permitted (only enforced in strict mode). */
+ allowTokens?: string[];
+ /** Tokens always blocked, regardless of mode. */
+ denyTokens?: string[];
+ /** Destination addresses explicitly permitted (only enforced in strict mode). */
+ allowDestinations?: string[];
+ /** Destination addresses always blocked, regardless of mode. */
+ denyDestinations?: string[];
+}
+/** Per-agent spend envelope. Every field is optional - an unset limit is not enforced. */
+export interface SpendLimitConfig {
+ /** Maximum USD value of any single transaction. */
+ perTxMaxUsd?: number;
+ /** Maximum cumulative USD over a rolling 24-hour window. */
+ dailyMaxUsd?: number;
+ /** Custom rolling window in milliseconds (defaults to 24h when `rollingMaxUsd` is set). */
+ rollingWindowMs?: number;
+ /** Maximum cumulative USD over the custom rolling window. */
+ rollingMaxUsd?: number;
+ /** Minimum wallet balance (USD) that must remain after a transaction. */
+ reserveFloorUsd?: number;
+ /** Token/destination allow-deny firewall. */
+ firewall?: FirewallConfig;
+ /**
+ * Fractional tolerance for ledger reconciliation. On-chain outflow is only treated as a
+ * breach when it exceeds `ledgerRecordedUsd * (1 + breachTolerance)`. Default 0.
+ */
+ breachTolerance?: number;
+}
+/** A single outflow being evaluated. */
+export interface SpendTx {
+ /** Agent initiating the outflow (spend is tracked per agent). */
+ agentId: string;
+ /** Owning user - for logging / multi-tenant scoping. */
+ userId?: string;
+ /** Token symbol or contract address moving out. */
+ token?: string;
+ /** Destination address. */
+ destination?: string;
+ /** USD value of the outflow. */
+ valueUsd: number;
+ /** Current agent wallet balance in USD (required to enforce the reserve floor). */
+ balanceUsd?: number;
+}
+/** Deterministic reason code for a block decision. */
+export type SpendBlockCode = 'CAP_PER_TX' | 'CAP_ROLLING' | 'CAP_DAILY' | 'RESERVE_FLOOR' | 'FIREWALL_DENY_TOKEN' | 'FIREWALL_DENY_DEST' | 'FIREWALL_NOT_ALLOWED' | 'BREACH';
+/** Result of a spend check. */
+export interface SpendCheckResult {
+ /** Whether the transaction is allowed to proceed. */
+ allowed: boolean;
+ /** Structured block code (present iff `!allowed`). */
+ code?: SpendBlockCode;
+ /** Human-readable, deterministic reason. */
+ reason: string;
+ /** Remaining allowance under the rolling cap after this tx (if a rolling cap is configured). */
+ remainingRollingUsd?: number;
+ /** Remaining allowance under the daily cap after this tx (if a daily cap is configured). */
+ remainingDailyUsd?: number;
+}
+/** Recorded vs. actually-observed outflow for a reconciliation window. */
+export interface SpendReconciliation {
+ /** Outflow the agent recorded in the tamper-evident ledger (Task 03). */
+ ledgerRecordedUsd: number;
+ /** Outflow independently observed on-chain for the same window. */
+ onChainOutflowUsd: number;
+}
+/**
+ * Injected reader that returns reconciliation figures for an agent. Provided by the server
+ * layer (backed by the Task 03 `agentActionLedger` + an on-chain scan). Keeping it injected
+ * means SpendGuard has no hard dependency on Task 03 - it works the moment a reader is wired.
+ */
+export type SpendLedgerReader = (params: {
+ agentId: string;
+ userId?: string;
+}) => Promise<SpendReconciliation>;
+/** Result of a reconciliation pass. */
+export interface ReconcileResult {
+ /** Whether a breach was detected (on-chain outflow exceeded recorded outflow). */
+ breach: boolean;
+ /** The excess USD that was moved on-chain but never recorded. */
+ unrecordedUsd: number;
+ reason: string;
+}
+export declare class SpendGuard {
+ private readonly config;
+ private readonly denyTokens;
+ private readonly allowTokens;
+ private readonly denyDests;
+ private readonly allowDests;
+ private readonly now;
+ /** Per-agent rolling spend log (agentId → entries). */
+ private readonly spendLog;
+ /** Per-agent breach latch. Once set, every check for that agent is blocked. */
+ private readonly tripped;
+ /**
+ * @param config Per-agent spend envelope, resolved server-side from `agent_spend_limits`.
+ * @param opts.now Injectable clock (defaults to `Date.now`) - keeps rolling-window tests
+ * deterministic without touching real time.
+ */
+ constructor(config?: SpendLimitConfig, opts?: {
+ now?: () => number;
+ });
+ /**
+ * Evaluate a single outflow against the full envelope. Pure - no state mutation.
+ *
+ * Order is fixed (hardest / most-specific block first) so the returned code is deterministic:
+ * breach latch → firewall deny → firewall strict allowlist → per-tx cap → reserve floor →
+ * rolling cap → daily cap.
+ */
+ check(tx: SpendTx): SpendCheckResult;
+ /**
+ * Record an outflow that actually landed. Call this AFTER a transaction succeeds so the
+ * rolling/daily windows stay live within a multi-step plan. Never call it for a blocked or
+ * failed transaction.
+ */
+ recordSpend(agentId: string, valueUsd: number, ts?: number): void;
+ /**
+ * Seed the rolling window from a persisted total (e.g. confirmed outflow summed from the
+ * ledger) so the in-memory tracker survives a cold start. Recorded as a single entry at the
+ * current time; only raises the tracked total, never lowers it.
+ */
+ syncSpendFromLedger(agentId: string, confirmedRollingUsd: number, windowMs?: number): void;
+ /** Cumulative recorded spend for an agent over the last `windowMs`. */
+ windowSpend(agentId: string, windowMs: number): number;
+ /** Remaining allowance under the daily cap for an agent (Infinity if uncapped). */
+ remainingDaily(agentId: string): number;
+ /**
+ * Compare recorded vs. observed outflow. If the chain moved more than the ledger recorded
+ * (beyond `breachTolerance`), the agent is **latched shut**: every subsequent `check()`
+ * returns a `BREACH` block until `reset(agentId)` is called. This is the key-compromise
+ * signal from the source `economy-reconcile` cron.
+ */
+ reconcile(agentId: string, figures: SpendReconciliation): ReconcileResult;
+ /** Reconcile using an injected ledger reader (e.g. wired to the Task 03 ledger). */
+ reconcileFromLedger(agentId: string, reader: SpendLedgerReader, userId?: string): Promise<ReconcileResult>;
+ /** Whether an agent is currently latched shut by a breach. */
+ isTripped(agentId: string): boolean;
+ /** Clear the breach latch and spend window for an agent (or all agents if omitted). */
+ reset(agentId?: string): void;
+ private prune;
+}
diff --git a/packages/agent-runtime/src/core/SpendGuard.js b/packages/agent-runtime/src/core/SpendGuard.js
new file mode 100644
index 000000000..1f467433e
--- /dev/null
+++ b/packages/agent-runtime/src/core/SpendGuard.js
@@ -0,0 +1,279 @@
+/**
+ * SpendGuard - Per-Agent Spend Envelope + Token/Target Firewall + Custody Reconciliation
+ *
+ * The quantitative money-safety layer that `PermissionGuard`, `CapabilityGuard`, and
+ * `DeFiGuard` do not encode. Where `DeFiGuard` scores *risk* and enforces *per-user tier*
+ * limits, `SpendGuard` enforces a hard **per-agent spend envelope**:
+ *
+ * 1. **Per-tx maximum** - a single outflow may never exceed `perTxMaxUsd`.
+ * 2. **Rolling / daily caps** - cumulative outflow over a rolling window (default 24h) may
+ * never exceed `rollingMaxUsd` / `dailyMaxUsd`. This is a true sliding window, not a
+ * calendar-day bucket.
+ * 3. **Reserve floor** - a transaction may not drain the agent wallet below `reserveFloorUsd`.
+ * 4. **Token/target firewall** - an allow/deny layer keyed by token *and* destination, with a
+ * strict mode that blocks anything not on the allowlist.
+ * 5. **Custody reconciliation** - sums the *actual* on-chain outflow (independently observed)
+ * against the outflow the agent *recorded* in the Task 03 tamper-evident ledger; if the
+ * chain moved more than the ledger recorded, that is a breach (key-compromise signal) and
+ * the guard **latches shut** for that agent until explicitly reset.
+ *
+ * Ported from three.ws `economy-master.js` (reserve/per-run/per-target guards + registry
+ * allowlist). The Solana multi-wallet funding topology is intentionally NOT ported - only the
+ * guard envelope. Custody here is EVM (Plutus ERC-4337).
+ *
+ * ── Design contract ──
+ * - **Pure & deterministic.** `check()` has no side effects and, for a fixed clock, always
+ * returns the same decision for the same inputs (runtime rule #4). Spend is only mutated by
+ * the explicit `recordSpend()` call, made *after* a transaction actually lands.
+ * - **DB-agnostic.** Per-agent config is resolved server-side (from `agent_spend_limits`) and
+ * passed in; the ledger totals for reconciliation are injected via a `SpendLedgerReader`.
+ * The runtime package never imports the database, exactly like `PermissionGuard`.
+ */
+import { debuglog } from 'node:util';
+const log = debuglog('three-ws-agent-runtime-spend-guard');
+const DEFAULT_ROLLING_WINDOW_MS = 24 * 60 * 60 * 1000; // 24h
+const DAILY_WINDOW_MS = 24 * 60 * 60 * 1000;
+/** Absolute USD epsilon to absorb float noise in comparisons. */
+const USD_EPSILON = 0.01;
+function usd(n) {
+ return `$${n.toLocaleString(undefined, { maximumFractionDigits: 2 })}`;
+}
+function normToken(t) {
+ return (t ?? '').trim().toUpperCase();
+}
+function normAddr(a) {
+ return (a ?? '').trim().toLowerCase();
+}
+// ============================================================================
+// SpendGuard
+// ============================================================================
+export class SpendGuard {
+ config;
+ denyTokens;
+ allowTokens;
+ denyDests;
+ allowDests;
+ now;
+ /** Per-agent rolling spend log (agentId → entries). */
+ spendLog = new Map();
+ /** Per-agent breach latch. Once set, every check for that agent is blocked. */
+ tripped = new Map();
+ /**
+ * @param config Per-agent spend envelope, resolved server-side from `agent_spend_limits`.
+ * @param opts.now Injectable clock (defaults to `Date.now`) - keeps rolling-window tests
+ * deterministic without touching real time.
+ */
+ constructor(config = {}, opts = {}) {
+ this.config = config;
+ this.now = opts.now ?? (() => Date.now());
+ const fw = config.firewall ?? {};
+ this.denyTokens = new Set((fw.denyTokens ?? []).map(normToken));
+ this.allowTokens = new Set((fw.allowTokens ?? []).map(normToken));
+ this.denyDests = new Set((fw.denyDestinations ?? []).map(normAddr));
+ this.allowDests = new Set((fw.allowDestinations ?? []).map(normAddr));
+ }
+ // ── Core check ───────────────────────────────────────────────────────────
+ /**
+ * Evaluate a single outflow against the full envelope. Pure - no state mutation.
+ *
+ * Order is fixed (hardest / most-specific block first) so the returned code is deterministic:
+ * breach latch → firewall deny → firewall strict allowlist → per-tx cap → reserve floor →
+ * rolling cap → daily cap.
+ */
+ check(tx) {
+ // 0. Breach latch - a reconciliation breach blocks everything until reset.
+ const trip = this.tripped.get(tx.agentId);
+ if (trip) {
+ return { allowed: false, code: trip.code, reason: trip.reason };
+ }
+ const token = normToken(tx.token);
+ const dest = normAddr(tx.destination);
+ const fw = this.config.firewall;
+ // 1. Firewall deny lists (always enforced).
+ if (token && this.denyTokens.has(token)) {
+ return {
+ allowed: false,
+ code: 'FIREWALL_DENY_TOKEN',
+ reason: `Token ${token} is on the deny firewall for this agent`,
+ };
+ }
+ if (dest && this.denyDests.has(dest)) {
+ return {
+ allowed: false,
+ code: 'FIREWALL_DENY_DEST',
+ reason: `Destination ${dest} is on the deny firewall for this agent`,
+ };
+ }
+ // 2. Firewall strict allowlist - anything not explicitly allowed is blocked.
+ if (fw?.strictMode) {
+ if (this.allowTokens.size > 0 && !(token && this.allowTokens.has(token))) {
+ return {
+ allowed: false,
+ code: 'FIREWALL_NOT_ALLOWED',
+ reason: `Token ${token || '(unknown)'} is not on the strict-mode allowlist`,
+ };
+ }
+ if (this.allowDests.size > 0 && !(dest && this.allowDests.has(dest))) {
+ return {
+ allowed: false,
+ code: 'FIREWALL_NOT_ALLOWED',
+ reason: `Destination ${dest || '(unknown)'} is not on the strict-mode allowlist`,
+ };
+ }
+ }
+ // 3. Per-transaction maximum.
+ if (this.config.perTxMaxUsd != null && tx.valueUsd > this.config.perTxMaxUsd + USD_EPSILON) {
+ return {
+ allowed: false,
+ code: 'CAP_PER_TX',
+ reason: `Transaction ${usd(tx.valueUsd)} exceeds per-transaction maximum of ${usd(this.config.perTxMaxUsd)}`,
+ };
+ }
+ // 4. Reserve floor - must not drain the wallet below the configured minimum.
+ if (this.config.reserveFloorUsd != null &&
+ tx.balanceUsd != null &&
+ tx.balanceUsd - tx.valueUsd < this.config.reserveFloorUsd - USD_EPSILON) {
+ return {
+ allowed: false,
+ code: 'RESERVE_FLOOR',
+ reason: `Transaction ${usd(tx.valueUsd)} would drain balance ${usd(tx.balanceUsd)} below the reserve floor of ${usd(this.config.reserveFloorUsd)}`,
+ };
+ }
+ // 5. Rolling-window cap.
+ let remainingRollingUsd;
+ if (this.config.rollingMaxUsd != null) {
+ const windowMs = this.config.rollingWindowMs ?? DEFAULT_ROLLING_WINDOW_MS;
+ const spent = this.windowSpend(tx.agentId, windowMs);
+ remainingRollingUsd = Math.max(0, this.config.rollingMaxUsd - spent - tx.valueUsd);
+ if (spent + tx.valueUsd > this.config.rollingMaxUsd + USD_EPSILON) {
+ return {
+ allowed: false,
+ code: 'CAP_ROLLING',
+ reason: `Transaction ${usd(tx.valueUsd)} would exceed the rolling spend cap of ${usd(this.config.rollingMaxUsd)} (already spent ${usd(spent)} in the last ${Math.round(windowMs / 3_600_000)}h)`,
+ remainingRollingUsd,
+ };
+ }
+ }
+ // 6. Daily (rolling 24h) cap.
+ let remainingDailyUsd;
+ if (this.config.dailyMaxUsd != null) {
+ const spent = this.windowSpend(tx.agentId, DAILY_WINDOW_MS);
+ remainingDailyUsd = Math.max(0, this.config.dailyMaxUsd - spent - tx.valueUsd);
+ if (spent + tx.valueUsd > this.config.dailyMaxUsd + USD_EPSILON) {
+ return {
+ allowed: false,
+ code: 'CAP_DAILY',
+ reason: `Transaction ${usd(tx.valueUsd)} would exceed the daily spend cap of ${usd(this.config.dailyMaxUsd)} (already spent ${usd(spent)} today)`,
+ remainingDailyUsd,
+ };
+ }
+ }
+ return {
+ allowed: true,
+ reason: 'Within spend envelope',
+ remainingDailyUsd,
+ remainingRollingUsd,
+ };
+ }
+ // ── Spend recording ────────────────────────────────────────────────────────
+ /**
+ * Record an outflow that actually landed. Call this AFTER a transaction succeeds so the
+ * rolling/daily windows stay live within a multi-step plan. Never call it for a blocked or
+ * failed transaction.
+ */
+ recordSpend(agentId, valueUsd, ts = this.now()) {
+ if (!agentId || !(valueUsd > 0))
+ return;
+ const entries = this.spendLog.get(agentId) ?? [];
+ entries.push({ ts, valueUsd });
+ this.spendLog.set(agentId, entries);
+ // Opportunistically prune anything older than the widest window we track.
+ this.prune(agentId, Math.max(this.config.rollingWindowMs ?? 0, DAILY_WINDOW_MS));
+ }
+ /**
+ * Seed the rolling window from a persisted total (e.g. confirmed outflow summed from the
+ * ledger) so the in-memory tracker survives a cold start. Recorded as a single entry at the
+ * current time; only raises the tracked total, never lowers it.
+ */
+ syncSpendFromLedger(agentId, confirmedRollingUsd, windowMs) {
+ if (!agentId || !(confirmedRollingUsd > 0))
+ return;
+ const w = windowMs ?? this.config.rollingWindowMs ?? DEFAULT_ROLLING_WINDOW_MS;
+ const current = this.windowSpend(agentId, w);
+ const delta = confirmedRollingUsd - current;
+ if (delta > 0)
+ this.recordSpend(agentId, delta);
+ }
+ /** Cumulative recorded spend for an agent over the last `windowMs`. */
+ windowSpend(agentId, windowMs) {
+ const entries = this.spendLog.get(agentId);
+ if (!entries || entries.length === 0)
+ return 0;
+ const cutoff = this.now() - windowMs;
+ let total = 0;
+ for (const e of entries) {
+ if (e.ts >= cutoff)
+ total += e.valueUsd;
+ }
+ return total;
+ }
+ /** Remaining allowance under the daily cap for an agent (Infinity if uncapped). */
+ remainingDaily(agentId) {
+ if (this.config.dailyMaxUsd == null)
+ return Infinity;
+ return Math.max(0, this.config.dailyMaxUsd - this.windowSpend(agentId, DAILY_WINDOW_MS));
+ }
+ // ── Reconciliation / custody audit ──────────────────────────────────────────
+ /**
+ * Compare recorded vs. observed outflow. If the chain moved more than the ledger recorded
+ * (beyond `breachTolerance`), the agent is **latched shut**: every subsequent `check()`
+ * returns a `BREACH` block until `reset(agentId)` is called. This is the key-compromise
+ * signal from the source `economy-reconcile` cron.
+ */
+ reconcile(agentId, figures) {
+ const tolerance = this.config.breachTolerance ?? 0;
+ const ceiling = figures.ledgerRecordedUsd * (1 + tolerance);
+ const unrecorded = figures.onChainOutflowUsd - figures.ledgerRecordedUsd;
+ if (figures.onChainOutflowUsd > ceiling + Math.max(USD_EPSILON, 0)) {
+ const reason = `Custody breach: on-chain outflow ${usd(figures.onChainOutflowUsd)} exceeds ledger-recorded outflow ${usd(figures.ledgerRecordedUsd)} by ${usd(unrecorded)} - agent spending latched until reviewed`;
+ this.tripped.set(agentId, { code: 'BREACH', reason });
+ log('BREACH agent=%s unrecorded=%d', agentId, unrecorded);
+ return { breach: true, reason, unrecordedUsd: unrecorded };
+ }
+ return {
+ breach: false,
+ reason: 'On-chain outflow matches recorded ledger within tolerance',
+ unrecordedUsd: Math.max(0, unrecorded),
+ };
+ }
+ /** Reconcile using an injected ledger reader (e.g. wired to the Task 03 ledger). */
+ async reconcileFromLedger(agentId, reader, userId) {
+ const figures = await reader({ agentId, userId });
+ return this.reconcile(agentId, figures);
+ }
+ /** Whether an agent is currently latched shut by a breach. */
+ isTripped(agentId) {
+ return this.tripped.has(agentId);
+ }
+ // ── Lifecycle ───────────────────────────────────────────────────────────────
+ /** Clear the breach latch and spend window for an agent (or all agents if omitted). */
+ reset(agentId) {
+ if (agentId) {
+ this.tripped.delete(agentId);
+ this.spendLog.delete(agentId);
+ }
+ else {
+ this.tripped.clear();
+ this.spendLog.clear();
+ }
+ }
+ prune(agentId, windowMs) {
+ const entries = this.spendLog.get(agentId);
+ if (!entries)
+ return;
+ const cutoff = this.now() - windowMs;
+ const kept = entries.filter((e) => e.ts >= cutoff);
+ if (kept.length !== entries.length)
+ this.spendLog.set(agentId, kept);
+ }
+}
diff --git a/packages/agent-runtime/src/core/ToolRelevanceScorer.d.ts b/packages/agent-runtime/src/core/ToolRelevanceScorer.d.ts
new file mode 100644
index 000000000..e59c9c33a
--- /dev/null
+++ b/packages/agent-runtime/src/core/ToolRelevanceScorer.d.ts
@@ -0,0 +1,76 @@
+/**
+ * ToolRelevanceScorer - Pre-filters tools based on semantic relevance to the user query.
+ *
+ * Instead of dumping all 35+ tool manifests into the LLM system prompt,
+ * this scorer ranks tools by relevance and returns only the top-K most relevant ones.
+ * This reduces token usage, improves tool selection accuracy, and speeds up inference.
+ *
+ * Strategy:
+ * 1. Keyword extraction from the user query
+ * 2. TF-IDF-style scoring against tool descriptions and API names
+ * 3. Recency boost for recently-used tools in the conversation
+ * 4. Always-include rules for tools marked as essential
+ */
+interface ToolManifest {
+ api?: Array<{
+ description?: string;
+ name: string;
+ }>;
+ description?: string;
+ humanIntervention?: unknown;
+ identifier: string;
+ systemRole?: string;
+}
+export interface ToolRelevanceScorerConfig {
+ /**
+ * Tools that are always included regardless of relevance score.
+ * Useful for critical tools like memory, knowledge base, etc.
+ */
+ alwaysIncludeTools?: string[];
+ /**
+ * Maximum number of tools to return after scoring.
+ * Default: 12
+ */
+ maxTools?: number;
+ /**
+ * Minimum relevance score (0-1) for a tool to be included.
+ * Tools below this threshold are excluded even if maxTools isn't reached.
+ * Default: 0.05
+ */
+ minScore?: number;
+ /**
+ * Boost multiplier for recently-used tools in the conversation.
+ * Default: 1.5
+ */
+ recencyBoost?: number;
+}
+export declare class ToolRelevanceScorer {
+ private config;
+ constructor(config?: ToolRelevanceScorerConfig);
+ /**
+ * Score and filter tools based on relevance to the user query and conversation context.
+ *
+ * @param query - The latest user message / query
+ * @param manifests - All available tool manifests
+ * @param recentToolCalls - Identifiers of tools recently called in this conversation
+ * @returns Filtered and sorted array of tool manifests
+ */
+ scoreTools(query: string, manifests: Record<string, ToolManifest>, recentToolCalls?: string[]): ToolManifest[];
+ /**
+ * Extract meaningful keywords from a text query.
+ * Lowercases, removes punctuation, splits on whitespace, and filters stop words.
+ */
+ private extractKeywords;
+ /**
+ * Compute a relevance score for a tool manifest against query keywords.
+ *
+ * Scoring factors:
+ * - Tool identifier match (high weight)
+ * - Tool description match (medium weight)
+ * - API name match (medium weight)
+ * - API description match (lower weight)
+ * - System role keyword match (lowest weight, but catches domain terms)
+ */
+ private computeRelevanceScore;
+}
+export {};
diff --git a/packages/agent-runtime/src/core/ToolRelevanceScorer.js b/packages/agent-runtime/src/core/ToolRelevanceScorer.js
new file mode 100644
index 000000000..7f60a9d80
--- /dev/null
+++ b/packages/agent-runtime/src/core/ToolRelevanceScorer.js
@@ -0,0 +1,180 @@
+/**
+ * ToolRelevanceScorer - Pre-filters tools based on semantic relevance to the user query.
+ *
+ * Instead of dumping all 35+ tool manifests into the LLM system prompt,
+ * this scorer ranks tools by relevance and returns only the top-K most relevant ones.
+ * This reduces token usage, improves tool selection accuracy, and speeds up inference.
+ *
+ * Strategy:
+ * 1. Keyword extraction from the user query
+ * 2. TF-IDF-style scoring against tool descriptions and API names
+ * 3. Recency boost for recently-used tools in the conversation
+ * 4. Always-include rules for tools marked as essential
+ */
+const DEFAULT_CONFIG = {
+ alwaysIncludeTools: [],
+ maxTools: 12,
+ minScore: 0.05,
+ recencyBoost: 1.5,
+};
+/**
+ * Common stop words to exclude from keyword matching
+ */
+const STOP_WORDS = new Set([
+ 'a',
+ 'an',
+ 'and',
+ 'are',
+ 'as',
+ 'at',
+ 'be',
+ 'by',
+ 'can',
+ 'do',
+ 'for',
+ 'from',
+ 'has',
+ 'have',
+ 'he',
+ 'her',
+ 'his',
+ 'how',
+ 'i',
+ 'if',
+ 'in',
+ 'is',
+ 'it',
+ 'its',
+ 'me',
+ 'my',
+ 'no',
+ 'not',
+ 'of',
+ 'on',
+ 'or',
+ 'our',
+ 'she',
+ 'so',
+ 'that',
+ 'the',
+ 'them',
+ 'then',
+ 'there',
+ 'they',
+ 'this',
+ 'to',
+ 'up',
+ 'us',
+ 'was',
+ 'we',
+ 'what',
+ 'when',
+ 'which',
+ 'who',
+ 'will',
+ 'with',
+ 'you',
+ 'your',
+]);
+export class ToolRelevanceScorer {
+ config;
+ constructor(config) {
+ this.config = { ...DEFAULT_CONFIG, ...config };
+ }
+ /**
+ * Score and filter tools based on relevance to the user query and conversation context.
+ *
+ * @param query - The latest user message / query
+ * @param manifests - All available tool manifests
+ * @param recentToolCalls - Identifiers of tools recently called in this conversation
+ * @returns Filtered and sorted array of tool manifests
+ */
+ scoreTools(query, manifests, recentToolCalls = []) {
+ const queryKeywords = this.extractKeywords(query);
+ // If query is too short or generic, return all tools (let LLM decide)
+ if (queryKeywords.length === 0) {
+ return Object.values(manifests);
+ }
+ const recentSet = new Set(recentToolCalls);
+ const scored = [];
+ for (const [identifier, manifest] of Object.entries(manifests)) {
+ // Always-include tools get max score
+ if (this.config.alwaysIncludeTools.includes(identifier)) {
+ scored.push({ manifest, score: Infinity });
+ continue;
+ }
+ let score = this.computeRelevanceScore(queryKeywords, manifest);
+ // Boost recently-used tools (they're likely still relevant to the conversation)
+ if (recentSet.has(identifier)) {
+ score *= this.config.recencyBoost;
+ }
+ scored.push({ manifest, score });
+ }
+ // Sort by score descending
+ scored.sort((a, b) => b.score - a.score);
+ // Filter by minScore and take top maxTools
+ return scored
+ .filter((s) => s.score >= this.config.minScore || s.score === Infinity)
+ .slice(0, this.config.maxTools)
+ .map((s) => s.manifest);
+ }
+ /**
+ * Extract meaningful keywords from a text query.
+ * Lowercases, removes punctuation, splits on whitespace, and filters stop words.
+ */
+ extractKeywords(text) {
+ return text
+ .toLowerCase()
+ .replace(/[^\w\s-]/g, ' ')
+ .split(/\s+/)
+ .filter((word) => word.length > 1 && !STOP_WORDS.has(word));
+ }
+ /**
+ * Compute a relevance score for a tool manifest against query keywords.
+ *
+ * Scoring factors:
+ * - Tool identifier match (high weight)
+ * - Tool description match (medium weight)
+ * - API name match (medium weight)
+ * - API description match (lower weight)
+ * - System role keyword match (lowest weight, but catches domain terms)
+ */
+ computeRelevanceScore(queryKeywords, manifest) {
+ const identifierTokens = this.extractKeywords(manifest.identifier || '');
+ const descriptionTokens = this.extractKeywords(manifest.description || '');
+ // Collect API-level tokens
+ const apiNameTokens = [];
+ const apiDescTokens = [];
+ for (const api of manifest.api || []) {
+ apiNameTokens.push(...this.extractKeywords(api.name || ''));
+ apiDescTokens.push(...this.extractKeywords(api.description || ''));
+ }
+ // System role is large - sample first 500 chars for keyword matching to keep it fast
+ const systemRoleTokens = this.extractKeywords((manifest.systemRole || '').slice(0, 500));
+ let score = 0;
+ for (const keyword of queryKeywords) {
+ // Exact match in identifier (highest signal)
+ if (identifierTokens.some((t) => t.includes(keyword) || keyword.includes(t))) {
+ score += 3.0;
+ }
+ // Match in tool description
+ if (descriptionTokens.some((t) => t.includes(keyword) || keyword.includes(t))) {
+ score += 2.0;
+ }
+ // Match in API names
+ if (apiNameTokens.some((t) => t.includes(keyword) || keyword.includes(t))) {
+ score += 2.0;
+ }
+ // Match in API descriptions
+ if (apiDescTokens.some((t) => t.includes(keyword) || keyword.includes(t))) {
+ score += 1.0;
+ }
+ // Match in system role (broad catch)
+ if (systemRoleTokens.some((t) => t.includes(keyword) || keyword.includes(t))) {
+ score += 0.5;
+ }
+ }
+ // Normalize by query length to avoid bias toward long queries
+ return queryKeywords.length > 0 ? score / queryKeywords.length : 0;
+ }
+}
diff --git a/packages/agent-runtime/src/core/TradeGuard.d.ts b/packages/agent-runtime/src/core/TradeGuard.d.ts
new file mode 100644
index 000000000..310409105
--- /dev/null
+++ b/packages/agent-runtime/src/core/TradeGuard.d.ts
@@ -0,0 +1,65 @@
+/**
+ * TradeGuard - the default, chain-agnostic domain guard for the GuardChain's
+ * `defi_guard` layer.
+ *
+ * Where {@link SpendGuard} enforces a per-agent spend envelope, TradeGuard
+ * enforces per-user trade policy on fund-moving tool calls:
+ *
+ * 1. **Tier per-transaction caps** - a call whose USD notional exceeds the
+ * user's tier cap is blocked outright (`CAP_PER_TX`).
+ * 2. **Per-user caps** - explicit {@link UserSwapCaps} override the tier cap
+ * and add rolling 24-hour / 7-day windows (`CAP_DAILY` / `CAP_WEEKLY`)
+ * evaluated against {@link UserSwapVolume} resolved from receipts.
+ * 3. **Auto-execute ceiling** - an allowed call above the ceiling is
+ * downgraded to `require_approval`, so large trades always see a human.
+ * 4. **Slippage clamp** - a mutating call carrying a slippage parameter above
+ * the configured maximum on a large notional gets the parameter clamped via
+ * `modifiedArguments`, with a warning attached (cheap MEV protection).
+ * 5. **Protocol audit lookup** - the target protocol is resolved against the
+ * configured registry; anything absent reads as `unaudited`, which the
+ * GuardChain surfaces as a `PROTOCOL_UNVERIFIED` blind spot.
+ *
+ * All checks are pure and deterministic given the request; every external fact
+ * (tier, caps, volume, notional) is resolved by the caller and passed in.
+ * Dollar caps compare against 0 when no `valueUsd` is supplied - by design the
+ * guard never prices token amounts itself, and the GuardChain reports the
+ * missing notional as a `VALUE_UNRESOLVED` blind spot instead.
+ */
+import type { AuditStatus, DeFiGuard, GuardAnalyzeRequest, GuardResult } from './toolRegistry.js';
+/** Default per-transaction USD caps by subscription tier. */
+export declare const DEFAULT_TIER_TX_CAPS_USD: Record<string, number>;
+/** Default USD notional above which an allowed call still needs approval. */
+export declare const DEFAULT_AUTO_EXECUTE_CEILING_USD = 10000;
+/** Default maximum slippage percentage before the clamp fires. */
+export declare const DEFAULT_MAX_SLIPPAGE_PCT = 1;
+/** Default notional below which the slippage clamp does not bother firing. */
+export declare const DEFAULT_MEV_NOTIONAL_THRESHOLD_USD = 10000;
+export interface TradeGuardConfig {
+ /** Per-tier per-transaction caps in USD. Missing tiers fall back to `free`. */
+ tierTxCapsUsd?: Record<string, number>;
+ /** USD notional above which allowed calls are downgraded to approval. */
+ autoExecuteCeilingUsd?: number;
+ /** Maximum slippage percentage before the clamp fires. */
+ maxSlippagePct?: number;
+ /** Minimum USD notional for the slippage clamp to apply. */
+ mevNotionalThresholdUsd?: number;
+ /** Audit registry, keyed by lower-case protocol name. */
+ protocolRegistry?: Record<string, AuditStatus>;
+ /** Extra tool identifiers to analyze beyond the shared registry. */
+ extraToolIdentifiers?: string[];
+ /** Wall-clock source, injectable for tests. */
+ now?: () => number;
+}
+export declare class TradeGuard implements DeFiGuard {
+ private readonly tierCaps;
+ private readonly autoExecuteCeilingUsd;
+ private readonly maxSlippagePct;
+ private readonly mevNotionalThresholdUsd;
+ private readonly protocolRegistry;
+ private readonly extraIdentifiers;
+ private readonly now;
+ constructor(config?: TradeGuardConfig);
+ isDeFiTool(identifier: string): boolean;
+ isMutatingApi(apiName: string): boolean;
+ analyze(request: GuardAnalyzeRequest): GuardResult;
+}
diff --git a/packages/agent-runtime/src/core/TradeGuard.js b/packages/agent-runtime/src/core/TradeGuard.js
new file mode 100644
index 000000000..96e1fccff
--- /dev/null
+++ b/packages/agent-runtime/src/core/TradeGuard.js
@@ -0,0 +1,181 @@
+/**
+ * TradeGuard - the default, chain-agnostic domain guard for the GuardChain's
+ * `defi_guard` layer.
+ *
+ * Where {@link SpendGuard} enforces a per-agent spend envelope, TradeGuard
+ * enforces per-user trade policy on fund-moving tool calls:
+ *
+ * 1. **Tier per-transaction caps** - a call whose USD notional exceeds the
+ * user's tier cap is blocked outright (`CAP_PER_TX`).
+ * 2. **Per-user caps** - explicit {@link UserSwapCaps} override the tier cap
+ * and add rolling 24-hour / 7-day windows (`CAP_DAILY` / `CAP_WEEKLY`)
+ * evaluated against {@link UserSwapVolume} resolved from receipts.
+ * 3. **Auto-execute ceiling** - an allowed call above the ceiling is
+ * downgraded to `require_approval`, so large trades always see a human.
+ * 4. **Slippage clamp** - a mutating call carrying a slippage parameter above
+ * the configured maximum on a large notional gets the parameter clamped via
+ * `modifiedArguments`, with a warning attached (cheap MEV protection).
+ * 5. **Protocol audit lookup** - the target protocol is resolved against the
+ * configured registry; anything absent reads as `unaudited`, which the
+ * GuardChain surfaces as a `PROTOCOL_UNVERIFIED` blind spot.
+ *
+ * All checks are pure and deterministic given the request; every external fact
+ * (tier, caps, volume, notional) is resolved by the caller and passed in.
+ * Dollar caps compare against 0 when no `valueUsd` is supplied - by design the
+ * guard never prices token amounts itself, and the GuardChain reports the
+ * missing notional as a `VALUE_UNRESOLVED` blind spot instead.
+ */
+import { DEFI_TOOL_IDENTIFIERS, MUTATING_APIS } from './toolRegistry.js';
+/** Default per-transaction USD caps by subscription tier. */
+export const DEFAULT_TIER_TX_CAPS_USD = {
+ enterprise: Number.POSITIVE_INFINITY,
+ free: 10_000,
+ basic: 25_000,
+ pro: 100_000,
+};
+/** Default USD notional above which an allowed call still needs approval. */
+export const DEFAULT_AUTO_EXECUTE_CEILING_USD = 10_000;
+/** Default maximum slippage percentage before the clamp fires. */
+export const DEFAULT_MAX_SLIPPAGE_PCT = 1;
+/** Default notional below which the slippage clamp does not bother firing. */
+export const DEFAULT_MEV_NOTIONAL_THRESHOLD_USD = 10_000;
+const SLIPPAGE_PCT_KEYS = ['slippage'];
+const SLIPPAGE_BPS_KEYS = ['slippageBps', 'slippage_bps'];
+const usd = (value) => value === Number.POSITIVE_INFINITY ? 'unlimited' : `$${value.toLocaleString('en-US')}`;
+export class TradeGuard {
+ tierCaps;
+ autoExecuteCeilingUsd;
+ maxSlippagePct;
+ mevNotionalThresholdUsd;
+ protocolRegistry;
+ extraIdentifiers;
+ now;
+ constructor(config = {}) {
+ this.tierCaps = { ...DEFAULT_TIER_TX_CAPS_USD, ...config.tierTxCapsUsd };
+ this.autoExecuteCeilingUsd = config.autoExecuteCeilingUsd ?? DEFAULT_AUTO_EXECUTE_CEILING_USD;
+ this.maxSlippagePct = config.maxSlippagePct ?? DEFAULT_MAX_SLIPPAGE_PCT;
+ this.mevNotionalThresholdUsd =
+ config.mevNotionalThresholdUsd ?? DEFAULT_MEV_NOTIONAL_THRESHOLD_USD;
+ this.protocolRegistry = { ...config.protocolRegistry };
+ this.extraIdentifiers = new Set(config.extraToolIdentifiers ?? []);
+ this.now = config.now ?? (() => Date.now());
+ }
+ isDeFiTool(identifier) {
+ return DEFI_TOOL_IDENTIFIERS.has(identifier) || this.extraIdentifiers.has(identifier);
+ }
+ isMutatingApi(apiName) {
+ return MUTATING_APIS.has(apiName);
+ }
+ analyze(request) {
+ const isDeFi = this.isDeFiTool(request.identifier);
+ const isMutating = this.isMutatingApi(request.apiName);
+ const value = request.valueUsd ?? 0;
+ const warnings = [];
+ const protocolStatus = request.protocol
+ ? (this.protocolRegistry[request.protocol.toLowerCase()] ?? 'unaudited')
+ : undefined;
+ const base = {
+ analyzedAt: this.now(),
+ decision: 'allow',
+ isDeFi,
+ isMutating,
+ protocolStatus,
+ reason: '',
+ warnings,
+ };
+ if (!isMutating) {
+ return {
+ analysis: {
+ ...base,
+ reason: `\`${request.apiName}\` is read-only; no trade policy applies.`,
+ },
+ };
+ }
+ // 1. Per-transaction cap: explicit user caps beat the tier default.
+ const tier = request.userTier ?? 'free';
+ const tierCap = this.tierCaps[tier] ?? this.tierCaps.free;
+ const perTxCap = request.userSwapCaps?.perTxUsdCap ?? tierCap;
+ if (value > perTxCap) {
+ return {
+ analysis: {
+ ...base,
+ capCode: 'CAP_PER_TX',
+ decision: 'block',
+ reason: `Trade of ${usd(value)} exceeds the ${request.userSwapCaps ? 'per-user' : `\`${tier}\` tier`} per-transaction cap of ${usd(perTxCap)}.`,
+ },
+ };
+ }
+ // 2. Rolling windows, when per-user caps and confirmed volume are supplied.
+ if (request.userSwapCaps && request.userSwapVolume) {
+ const { perDayUsdCap, perWeekUsdCap } = request.userSwapCaps;
+ const { last24hUsd, last7dUsd } = request.userSwapVolume;
+ if (last24hUsd + value > perDayUsdCap) {
+ return {
+ analysis: {
+ ...base,
+ capCode: 'CAP_DAILY',
+ decision: 'block',
+ reason: `Trade of ${usd(value)} would exceed the rolling 24-hour cap of ${usd(perDayUsdCap)} (${usd(last24hUsd)} already confirmed).`,
+ remainingDailyVolumeUsd: Math.max(0, perDayUsdCap - last24hUsd),
+ },
+ };
+ }
+ if (last7dUsd + value > perWeekUsdCap) {
+ return {
+ analysis: {
+ ...base,
+ capCode: 'CAP_WEEKLY',
+ decision: 'block',
+ reason: `Trade of ${usd(value)} would exceed the rolling 7-day cap of ${usd(perWeekUsdCap)} (${usd(last7dUsd)} already confirmed).`,
+ },
+ };
+ }
+ base.remainingDailyVolumeUsd = Math.max(0, perDayUsdCap - last24hUsd - value);
+ }
+ // 3. Slippage clamp on large notionals.
+ let modifiedArguments;
+ const parameterAdjustments = {};
+ if (value >= this.mevNotionalThresholdUsd) {
+ for (const key of SLIPPAGE_PCT_KEYS) {
+ const raw = request.arguments?.[key];
+ if (typeof raw === 'number' && raw > this.maxSlippagePct) {
+ modifiedArguments = { ...request.arguments, ...modifiedArguments, [key]: this.maxSlippagePct };
+ parameterAdjustments[key] = { from: raw, to: this.maxSlippagePct };
+ warnings.push(`Slippage reduced to ${this.maxSlippagePct}% for MEV protection (was ${raw}%).`);
+ }
+ }
+ const maxBps = this.maxSlippagePct * 100;
+ for (const key of SLIPPAGE_BPS_KEYS) {
+ const raw = request.arguments?.[key];
+ if (typeof raw === 'number' && raw > maxBps) {
+ modifiedArguments = { ...request.arguments, ...modifiedArguments, [key]: maxBps };
+ parameterAdjustments[key] = { from: raw, to: maxBps };
+ warnings.push(`Slippage reduced to ${maxBps} bps for MEV protection (was ${raw} bps).`);
+ }
+ }
+ }
+ if (Object.keys(parameterAdjustments).length > 0) {
+ base.parameterAdjustments = parameterAdjustments;
+ }
+ // 4. Auto-execute ceiling: allowed, but a human signs off.
+ if (value > this.autoExecuteCeilingUsd) {
+ return {
+ analysis: {
+ ...base,
+ decision: 'require_approval',
+ reason: `Trade of ${usd(value)} exceeds the auto-execute ceiling of ${usd(this.autoExecuteCeilingUsd)}; human approval required.`,
+ },
+ modifiedArguments,
+ };
+ }
+ return {
+ analysis: {
+ ...base,
+ reason: value > 0
+ ? `Trade of ${usd(value)} is within the ${usd(perTxCap)} per-transaction cap.`
+ : 'No USD notional resolved; dollar caps compared against $0.',
+ },
+ modifiedArguments,
+ };
+ }
+}
diff --git a/packages/agent-runtime/src/core/TransactionPipeline.d.ts b/packages/agent-runtime/src/core/TransactionPipeline.d.ts
new file mode 100644
index 000000000..66fca9ddf
--- /dev/null
+++ b/packages/agent-runtime/src/core/TransactionPipeline.d.ts
@@ -0,0 +1,162 @@
+/**
+ * TransactionPipeline - Orchestrates multi-step DeFi transaction execution with
+ * dependency resolution, rollback on failure, gas estimation, and human approval gates.
+ *
+ * This is the "execution engine" that takes a `DeFiPlan` from the `DeFiIntentEngine`
+ * and executes each step in topological order, handling:
+ *
+ * 1. **Dependency resolution**: Steps only execute when all `dependsOn` steps are complete
+ * 2. **Parallel execution**: Independent steps (no shared dependencies) run concurrently
+ * 3. **Rollback on failure**: If a step fails, its `rollbackAction` (and cascading dependents) are rolled back
+ * 4. **Gas estimation**: Pre-execution gas check to prevent wasted transactions
+ * 5. **Human approval gates**: Steps with `requiresApproval: true` pause for user confirmation
+ * 6. **Simulation preflight**: Simulation steps run first and abort the plan if they detect issues
+ * 7. **Timeout management**: Each step has a configurable timeout with grace period
+ * 8. **Event emission**: Every state transition emits events for UI updates
+ *
+ * The pipeline is non-custodial - it produces unsigned transaction instructions
+ * that the wallet-connected frontend must sign and broadcast.
+ *
+ * Credits: Inspired by Gelato Relay, Safe{Wallet} transaction batching, and
+ * LI.FI multi-hop bridge patterns. Built for three.ws as open-source innovation.
+ */
+import type { DeFiPlan, PlanStep } from './toolRegistry.js';
+/** Execution status for a single step */
+export type StepStatus = 'pending' | 'waiting_approval' | 'executing' | 'simulating' | 'completed' | 'failed' | 'rolled_back' | 'skipped' | 'timed_out';
+/** Result of a single step execution */
+export interface StepResult {
+ stepId: string;
+ status: StepStatus;
+ /** Data returned from the tool execution */
+ data?: unknown;
+ /** Error message if failed */
+ error?: string;
+ /** Gas actually consumed (USD) */
+ gasUsedUsd?: number;
+ /** Transaction hash if on-chain */
+ txHash?: string;
+ /** Execution time in milliseconds */
+ executionTimeMs: number;
+ /** Timestamp */
+ completedAt: string;
+}
+/** Overall pipeline execution state */
+export type PipelineStatus = 'idle' | 'executing' | 'paused_for_approval' | 'completed' | 'failed' | 'rolled_back' | 'aborted';
+/** Complete pipeline execution record */
+export interface PipelineExecution {
+ /** Pipeline ID */
+ id: string;
+ /** Reference to the plan being executed */
+ planId: string;
+ /** Current pipeline status */
+ status: PipelineStatus;
+ /** Results per step */
+ stepResults: Map<string, StepResult>;
+ /** Steps currently waiting for approval */
+ pendingApprovals: string[];
+ /** Steps currently executing */
+ activeSteps: string[];
+ /** Total gas consumed so far (USD) */
+ totalGasUsedUsd: number;
+ /** Pipeline start time */
+ startedAt: string;
+ /** Pipeline completion time */
+ completedAt?: string;
+ /** Rollback steps executed */
+ rollbacksExecuted: string[];
+}
+/** Configuration for the pipeline */
+export interface PipelineConfig {
+ /** Maximum time per step in ms (default: 120_000 = 2 minutes) */
+ stepTimeoutMs: number;
+ /** Maximum total pipeline time in ms (default: 600_000 = 10 minutes) */
+ totalTimeoutMs: number;
+ /** Whether to auto-skip simulation failures (default: false - abort on sim failure) */
+ skipFailedSimulations: boolean;
+ /** Maximum gas budget in USD (default: Infinity) */
+ maxGasBudgetUsd: number;
+ /** Whether to execute rollbacks on failure (default: true) */
+ enableRollbacks: boolean;
+ /** Maximum parallel step executions (default: 3) */
+ maxParallelSteps: number;
+ /**
+ * Optional pre-flight guard run before each step executes (after the approval gate).
+ * Use it to register the per-agent `SpendGuard` envelope + firewall alongside `DeFiGuard`.
+ * When absent, every step passes pre-flight (no behaviour change).
+ */
+ preflight?: PipelinePreflight;
+ /**
+ * Optional hook invoked after every step result is finalised (success or failure). Used to
+ * feed confirmed outflow back into a spend tracker via `SpendGuard.recordSpend`. Never
+ * throws into the money path - errors are swallowed and logged.
+ */
+ onStepExecuted?: (step: PlanStep, result: StepResult) => void | Promise<void>;
+}
+/** Event types emitted by the pipeline */
+export type PipelineEventType = 'pipeline_started' | 'step_started' | 'step_completed' | 'step_failed' | 'approval_required' | 'approval_received' | 'simulation_passed' | 'simulation_failed' | 'rollback_started' | 'rollback_completed' | 'pipeline_completed' | 'pipeline_failed' | 'pipeline_aborted' | 'gas_budget_exceeded';
+export interface PipelineEvent {
+ type: PipelineEventType;
+ stepId?: string;
+ data?: unknown;
+ timestamp: string;
+}
+/** Tool executor function signature (injected by the runtime) */
+export type ToolExecutor = (toolIdentifier: string, apiName: string, args: Record<string, unknown>) => Promise<{
+ data: unknown;
+ isSuccess: boolean;
+ txHash?: string;
+ gasUsedUsd?: number;
+}>;
+/** Result of a pre-flight guard check on a single step. */
+export interface PreflightResult {
+ /** Whether the step is cleared to execute. */
+ allowed: boolean;
+ /** Deterministic reason (surfaced when blocked). */
+ reason?: string;
+ /** Structured block code (e.g. a `SpendGuard` `SpendBlockCode`). */
+ code?: string;
+}
+/**
+ * Pre-flight guard invoked immediately before a step executes (after any approval gate).
+ * A blocked result aborts the step - and, like any fatal step failure, triggers rollback of
+ * already-completed steps. Register `SpendGuard` (and any other quantitative guard) here to
+ * run alongside `DeFiGuard`'s risk analysis. Returning `{ allowed: true }` is a pass-through.
+ */
+export type PipelinePreflight = (step: PlanStep) => Promise<PreflightResult> | PreflightResult;
+export declare class TransactionPipeline {
+ private config;
+ private eventListeners;
+ constructor(config?: Partial<PipelineConfig>);
+ /** Subscribe to pipeline events */
+ onEvent(listener: (event: PipelineEvent) => void): () => void;
+ private emit;
+ /**
+ * Validate a plan before execution. Returns a list of issues.
+ */
+ validatePlan(plan: DeFiPlan): string[];
+ /**
+ * Get the topological execution order, resolving dependencies.
+ * Returns steps grouped into parallel batches.
+ */
+ getExecutionOrder(plan: DeFiPlan): PlanStep[][];
+ /**
+ * Execute a DeFi plan step by step.
+ *
+ * @param plan - The plan to execute
+ * @param executor - Tool executor function (injected by runtime)
+ * @param approvalCallback - Called when a step needs human approval; returns true to proceed
+ */
+ execute(plan: DeFiPlan, executor: ToolExecutor, approvalCallback?: (step: PlanStep) => Promise<boolean>): Promise<PipelineExecution>;
+ /**
+ * Abort a running pipeline.
+ */
+ abort(execution: PipelineExecution): void;
+ private _executeStep;
+ /**
+ * Fire the `onStepExecuted` hook, never throwing into the money path.
+ * A stalled spend tracker must not block or revert a transaction that already landed.
+ */
+ private _notifyStepExecuted;
+ private _executeRollbacks;
+ private _executeWithTimeout;
+}
diff --git a/packages/agent-runtime/src/core/TransactionPipeline.js b/packages/agent-runtime/src/core/TransactionPipeline.js
new file mode 100644
index 000000000..a6d1351a5
--- /dev/null
+++ b/packages/agent-runtime/src/core/TransactionPipeline.js
@@ -0,0 +1,423 @@
+/**
+ * TransactionPipeline - Orchestrates multi-step DeFi transaction execution with
+ * dependency resolution, rollback on failure, gas estimation, and human approval gates.
+ *
+ * This is the "execution engine" that takes a `DeFiPlan` from the `DeFiIntentEngine`
+ * and executes each step in topological order, handling:
+ *
+ * 1. **Dependency resolution**: Steps only execute when all `dependsOn` steps are complete
+ * 2. **Parallel execution**: Independent steps (no shared dependencies) run concurrently
+ * 3. **Rollback on failure**: If a step fails, its `rollbackAction` (and cascading dependents) are rolled back
+ * 4. **Gas estimation**: Pre-execution gas check to prevent wasted transactions
+ * 5. **Human approval gates**: Steps with `requiresApproval: true` pause for user confirmation
+ * 6. **Simulation preflight**: Simulation steps run first and abort the plan if they detect issues
+ * 7. **Timeout management**: Each step has a configurable timeout with grace period
+ * 8. **Event emission**: Every state transition emits events for UI updates
+ *
+ * The pipeline is non-custodial - it produces unsigned transaction instructions
+ * that the wallet-connected frontend must sign and broadcast.
+ *
+ * Credits: Inspired by Gelato Relay, Safe{Wallet} transaction batching, and
+ * LI.FI multi-hop bridge patterns. Built for three.ws as open-source innovation.
+ */
+import { debuglog } from 'node:util';
+const log = debuglog('three-ws-agent-runtime-tx-pipeline');
+// ─── Default Config ──────────────────────────────────────────────────────────
+const DEFAULT_CONFIG = {
+ enableRollbacks: true,
+ maxGasBudgetUsd: Infinity,
+ maxParallelSteps: 3,
+ skipFailedSimulations: false,
+ stepTimeoutMs: 120_000,
+ totalTimeoutMs: 600_000,
+};
+// ─── Pipeline ────────────────────────────────────────────────────────────────
+export class TransactionPipeline {
+ config;
+ eventListeners = [];
+ constructor(config = {}) {
+ this.config = { ...DEFAULT_CONFIG, ...config };
+ }
+ /** Subscribe to pipeline events */
+ onEvent(listener) {
+ this.eventListeners.push(listener);
+ return () => {
+ this.eventListeners = this.eventListeners.filter((l) => l !== listener);
+ };
+ }
+ emit(event) {
+ for (const listener of this.eventListeners) {
+ try {
+ listener(event);
+ }
+ catch {
+ // swallow listener errors
+ }
+ }
+ }
+ /**
+ * Validate a plan before execution. Returns a list of issues.
+ */
+ validatePlan(plan) {
+ const issues = [];
+ // Check for empty plans
+ if (plan.steps.length === 0) {
+ issues.push('Plan has no steps to execute.');
+ return issues;
+ }
+ // Check for circular dependencies
+ const visited = new Set();
+ const visiting = new Set();
+ const stepMap = new Map(plan.steps.map((s) => [s.id, s]));
+ const hasCycle = (stepId) => {
+ if (visiting.has(stepId))
+ return true;
+ if (visited.has(stepId))
+ return false;
+ visiting.add(stepId);
+ const step = stepMap.get(stepId);
+ if (step) {
+ for (const dep of step.dependsOn) {
+ if (hasCycle(dep))
+ return true;
+ }
+ }
+ visiting.delete(stepId);
+ visited.add(stepId);
+ return false;
+ };
+ for (const step of plan.steps) {
+ if (hasCycle(step.id)) {
+ issues.push(`Circular dependency detected involving step ${step.id}`);
+ break;
+ }
+ }
+ // Check for missing dependencies
+ const allIds = new Set(plan.steps.map((s) => s.id));
+ for (const step of plan.steps) {
+ for (const dep of step.dependsOn) {
+ if (!allIds.has(dep)) {
+ issues.push(`Step ${step.id} depends on non-existent step ${dep}`);
+ }
+ }
+ }
+ // Check gas budget
+ if (plan.totalEstimatedGasUsd > this.config.maxGasBudgetUsd) {
+ issues.push(`Estimated gas ($${plan.totalEstimatedGasUsd.toFixed(2)}) exceeds budget ($${this.config.maxGasBudgetUsd.toFixed(2)})`);
+ }
+ return issues;
+ }
+ /**
+ * Get the topological execution order, resolving dependencies.
+ * Returns steps grouped into parallel batches.
+ */
+ getExecutionOrder(plan) {
+ const stepMap = new Map(plan.steps.map((s) => [s.id, s]));
+ const completed = new Set();
+ const batches = [];
+ let remaining = [...plan.steps];
+ while (remaining.length > 0) {
+ // Find all steps whose dependencies are all completed
+ const ready = remaining.filter((s) => s.dependsOn.every((dep) => completed.has(dep)));
+ if (ready.length === 0) {
+ // This should not happen if validatePlan() passed - indicates a cycle
+ log('deadlock detected: %d steps remaining with unmet dependencies', remaining.length);
+ break;
+ }
+ // Respect max parallel limit
+ const batch = ready.slice(0, this.config.maxParallelSteps);
+ batches.push(batch);
+ for (const step of batch) {
+ completed.add(step.id);
+ }
+ remaining = remaining.filter((s) => !completed.has(s.id));
+ }
+ return batches;
+ }
+ /**
+ * Execute a DeFi plan step by step.
+ *
+ * @param plan - The plan to execute
+ * @param executor - Tool executor function (injected by runtime)
+ * @param approvalCallback - Called when a step needs human approval; returns true to proceed
+ */
+ async execute(plan, executor, approvalCallback) {
+ const execution = {
+ activeSteps: [],
+ completedAt: undefined,
+ id: `exec_${Date.now()}_${crypto.randomUUID().slice(0, 8)}`,
+ pendingApprovals: [],
+ planId: plan.id,
+ rollbacksExecuted: [],
+ startedAt: new Date().toISOString(),
+ status: 'executing',
+ stepResults: new Map(),
+ totalGasUsedUsd: 0,
+ };
+ // Validate first
+ const issues = this.validatePlan(plan);
+ if (issues.length > 0) {
+ log('plan validation failed: %o', issues);
+ execution.status = 'failed';
+ execution.completedAt = new Date().toISOString();
+ return execution;
+ }
+ this.emit({ data: { planId: plan.id }, timestamp: new Date().toISOString(), type: 'pipeline_started' });
+ const batches = this.getExecutionOrder(plan);
+ const pipelineStart = Date.now();
+ for (const batch of batches) {
+ // Check total timeout
+ if (Date.now() - pipelineStart > this.config.totalTimeoutMs) {
+ log('pipeline total timeout exceeded');
+ execution.status = 'failed';
+ break;
+ }
+ // Execute batch (parallel within batch, sequential between batches)
+ const batchPromises = batch.map(async (step) => {
+ return this._executeStep(step, executor, approvalCallback, execution);
+ });
+ const results = await Promise.allSettled(batchPromises);
+ // Check for failures
+ let hasFatalFailure = false;
+ for (const result of results) {
+ if (result.status === 'rejected') {
+ hasFatalFailure = true;
+ }
+ else if (result.value.status === 'failed' || result.value.status === 'timed_out') {
+ const failedStep = plan.steps.find((s) => s.id === result.value.stepId);
+ if (failedStep?.isSimulation && !this.config.skipFailedSimulations) {
+ log('simulation step %s failed - aborting pipeline', result.value.stepId);
+ this.emit({
+ data: { error: result.value.error },
+ stepId: result.value.stepId,
+ timestamp: new Date().toISOString(),
+ type: 'simulation_failed',
+ });
+ hasFatalFailure = true;
+ }
+ else if (!failedStep?.isSimulation) {
+ hasFatalFailure = true;
+ }
+ }
+ }
+ if (hasFatalFailure) {
+ execution.status = 'failed';
+ // Execute rollbacks if enabled
+ if (this.config.enableRollbacks) {
+ await this._executeRollbacks(plan, execution, executor);
+ }
+ break;
+ }
+ // Check gas budget
+ if (execution.totalGasUsedUsd > this.config.maxGasBudgetUsd) {
+ log('gas budget exceeded: $%d > $%d', execution.totalGasUsedUsd, this.config.maxGasBudgetUsd);
+ this.emit({ timestamp: new Date().toISOString(), type: 'gas_budget_exceeded' });
+ execution.status = 'failed';
+ break;
+ }
+ }
+ if (execution.status === 'executing') {
+ execution.status = 'completed';
+ }
+ execution.completedAt = new Date().toISOString();
+ this.emit({
+ data: { gasUsed: execution.totalGasUsedUsd, status: execution.status },
+ timestamp: new Date().toISOString(),
+ type: execution.status === 'completed' ? 'pipeline_completed' : 'pipeline_failed',
+ });
+ log('pipeline %s finished: status=%s, gas=$%d', execution.id, execution.status, execution.totalGasUsedUsd);
+ return execution;
+ }
+ /**
+ * Abort a running pipeline.
+ */
+ abort(execution) {
+ execution.status = 'aborted';
+ execution.completedAt = new Date().toISOString();
+ this.emit({ timestamp: new Date().toISOString(), type: 'pipeline_aborted' });
+ }
+ // ── Private ──────────────────────────────────────────────────────────────
+ async _executeStep(step, executor, approvalCallback, execution) {
+ const startTime = Date.now();
+ log('executing step %s: %s', step.id, step.description);
+ execution.activeSteps.push(step.id);
+ this.emit({
+ data: { action: step.action, description: step.description },
+ stepId: step.id,
+ timestamp: new Date().toISOString(),
+ type: 'step_started',
+ });
+ // Human approval gate
+ if (step.requiresApproval && approvalCallback) {
+ execution.pendingApprovals.push(step.id);
+ this.emit({ stepId: step.id, timestamp: new Date().toISOString(), type: 'approval_required' });
+ const approved = await approvalCallback(step);
+ execution.pendingApprovals = execution.pendingApprovals.filter((id) => id !== step.id);
+ if (!approved) {
+ const result = {
+ completedAt: new Date().toISOString(),
+ error: 'User rejected step',
+ executionTimeMs: Date.now() - startTime,
+ status: 'skipped',
+ stepId: step.id,
+ };
+ execution.stepResults.set(step.id, result);
+ execution.activeSteps = execution.activeSteps.filter((id) => id !== step.id);
+ return result;
+ }
+ this.emit({ stepId: step.id, timestamp: new Date().toISOString(), type: 'approval_received' });
+ }
+ // Pre-flight guard gate (SpendGuard envelope + firewall, etc.). A block aborts the step.
+ if (this.config.preflight) {
+ let preflight;
+ try {
+ preflight = await this.config.preflight(step);
+ }
+ catch (error) {
+ // A guard that throws must fail closed - never let an error open the money path.
+ const errorMsg = error instanceof Error ? error.message : String(error);
+ log('preflight guard threw for step %s - failing closed: %s', step.id, errorMsg);
+ preflight = { allowed: false, code: 'PREFLIGHT_ERROR', reason: `Pre-flight guard error: ${errorMsg}` };
+ }
+ if (!preflight.allowed) {
+ const reason = preflight.code
+ ? `Spend guard blocked [${preflight.code}]: ${preflight.reason ?? 'blocked by pre-flight guard'}`
+ : `Spend guard blocked: ${preflight.reason ?? 'blocked by pre-flight guard'}`;
+ log('step %s blocked by pre-flight guard: %s', step.id, reason);
+ const result = {
+ completedAt: new Date().toISOString(),
+ error: reason,
+ executionTimeMs: Date.now() - startTime,
+ status: 'failed',
+ stepId: step.id,
+ };
+ execution.stepResults.set(step.id, result);
+ execution.activeSteps = execution.activeSteps.filter((id) => id !== step.id);
+ this.emit({
+ data: { code: preflight.code, error: reason },
+ stepId: step.id,
+ timestamp: new Date().toISOString(),
+ type: 'step_failed',
+ });
+ await this._notifyStepExecuted(step, result);
+ return result;
+ }
+ }
+ try {
+ // Execute with timeout
+ const toolResult = await this._executeWithTimeout(() => executor(step.toolIdentifier, step.apiName, step.args), step.isSimulation ? this.config.stepTimeoutMs / 2 : this.config.stepTimeoutMs);
+ const gasUsed = toolResult.gasUsedUsd ?? 0;
+ execution.totalGasUsedUsd += gasUsed;
+ const result = {
+ completedAt: new Date().toISOString(),
+ data: toolResult.data,
+ error: toolResult.isSuccess ? undefined : 'Tool execution returned failure',
+ executionTimeMs: Date.now() - startTime,
+ gasUsedUsd: gasUsed,
+ status: toolResult.isSuccess
+ ? step.isSimulation
+ ? 'completed'
+ : 'completed'
+ : 'failed',
+ stepId: step.id,
+ txHash: toolResult.txHash,
+ };
+ execution.stepResults.set(step.id, result);
+ if (step.isSimulation && toolResult.isSuccess) {
+ this.emit({ stepId: step.id, timestamp: new Date().toISOString(), type: 'simulation_passed' });
+ }
+ this.emit({
+ data: result,
+ stepId: step.id,
+ timestamp: new Date().toISOString(),
+ type: toolResult.isSuccess ? 'step_completed' : 'step_failed',
+ });
+ await this._notifyStepExecuted(step, result);
+ return result;
+ }
+ catch (error) {
+ const errorMsg = error instanceof Error ? error.message : String(error);
+ const isTimeout = errorMsg.includes('timed out');
+ const result = {
+ completedAt: new Date().toISOString(),
+ error: errorMsg,
+ executionTimeMs: Date.now() - startTime,
+ status: isTimeout ? 'timed_out' : 'failed',
+ stepId: step.id,
+ };
+ execution.stepResults.set(step.id, result);
+ this.emit({
+ data: { error: errorMsg },
+ stepId: step.id,
+ timestamp: new Date().toISOString(),
+ type: 'step_failed',
+ });
+ await this._notifyStepExecuted(step, result);
+ return result;
+ }
+ finally {
+ execution.activeSteps = execution.activeSteps.filter((id) => id !== step.id);
+ }
+ }
+ /**
+ * Fire the `onStepExecuted` hook, never throwing into the money path.
+ * A stalled spend tracker must not block or revert a transaction that already landed.
+ */
+ async _notifyStepExecuted(step, result) {
+ if (!this.config.onStepExecuted)
+ return;
+ try {
+ await this.config.onStepExecuted(step, result);
+ }
+ catch (error) {
+ log('onStepExecuted hook threw for step %s (swallowed): %o', step.id, error);
+ }
+ }
+ async _executeRollbacks(plan, execution, executor) {
+ // Find completed steps that have rollback actions, in reverse order
+ const completedSteps = plan.steps
+ .filter((s) => execution.stepResults.get(s.id)?.status === 'completed' &&
+ s.rollbackAction &&
+ !s.isSimulation)
+ .reverse();
+ for (const step of completedSteps) {
+ if (!step.rollbackAction)
+ continue;
+ log('rolling back step %s: %s', step.id, step.rollbackAction.description);
+ this.emit({
+ data: { description: step.rollbackAction.description },
+ stepId: step.id,
+ timestamp: new Date().toISOString(),
+ type: 'rollback_started',
+ });
+ try {
+ await this._executeWithTimeout(() => executor(step.rollbackAction.toolIdentifier, step.rollbackAction.apiName, step.rollbackAction.args), this.config.stepTimeoutMs);
+ execution.rollbacksExecuted.push(step.id);
+ this.emit({ stepId: step.id, timestamp: new Date().toISOString(), type: 'rollback_completed' });
+ }
+ catch (error) {
+ log('rollback failed for step %s: %o', step.id, error);
+ // Rollback failures are logged but don't cascade
+ }
+ }
+ if (completedSteps.length > 0) {
+ execution.status = 'rolled_back';
+ }
+ }
+ async _executeWithTimeout(fn, timeoutMs) {
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ reject(new Error(`Step execution timed out after ${timeoutMs}ms`));
+ }, timeoutMs);
+ fn()
+ .then((result) => {
+ clearTimeout(timer);
+ resolve(result);
+ })
+ .catch((error) => {
+ clearTimeout(timer);
+ reject(error);
+ });
+ });
+ }
+}
diff --git a/packages/agent-runtime/src/core/UsageCounter.d.ts b/packages/agent-runtime/src/core/UsageCounter.d.ts
new file mode 100644
index 000000000..4b46b3138
--- /dev/null
+++ b/packages/agent-runtime/src/core/UsageCounter.d.ts
@@ -0,0 +1,65 @@
+import { ModelUsage } from '../types/vendor.js';
+import { Cost, Usage } from '../types/usage.js';
+/**
+ * UsageCounter - Pure accumulator for usage and cost tracking
+ * Focuses only on usage/cost calculations without managing state
+ */
+export declare class UsageCounter {
+ /**
+ * Create default usage statistics
+ */
+ private static createDefaultUsage;
+ /**
+ * Create default cost statistics
+ */
+ private static createDefaultCost;
+ /**
+ * Merge two ModelUsage objects by accumulating token counts
+ * @param previous - Previous usage statistics
+ * @param current - Current usage statistics to add
+ * @returns Merged usage statistics
+ */
+ private static mergeModelUsage;
+ /**
+ * Accumulate LLM usage and cost for a specific model
+ * @param params - Accumulation parameters
+ * @param params.usage - Current usage statistics (optional, will be created if not provided)
+ * @param params.cost - Current cost statistics (optional, will be created if not provided)
+ * @param params.provider - Provider name (e.g., "openai")
+ * @param params.model - Model name (e.g., "gpt-4")
+ * @param params.modelUsage - ModelUsage from model-runtime
+ * @returns Updated usage and cost
+ */
+ static accumulateLLM(params: {
+ cost?: Cost;
+ model: string;
+ modelUsage: ModelUsage;
+ provider: string;
+ usage?: Usage;
+ }): {
+ cost?: Cost;
+ usage: Usage;
+ };
+ /**
+ * Accumulate tool usage and cost
+ * @param params - Accumulation parameters
+ * @param params.usage - Current usage statistics (optional, will be created if not provided)
+ * @param params.cost - Current cost statistics (optional, will be created if not provided)
+ * @param params.toolName - Tool identifier
+ * @param params.executionTime - Execution time in milliseconds
+ * @param params.success - Whether the execution was successful
+ * @param params.toolCost - Optional cost for this tool call
+ * @returns Updated usage and cost
+ */
+ static accumulateTool(params: {
+ cost?: Cost;
+ executionTime: number;
+ success: boolean;
+ toolCost?: number;
+ toolName: string;
+ usage?: Usage;
+ }): {
+ cost?: Cost;
+ usage: Usage;
+ };
+}
diff --git a/packages/agent-runtime/src/core/UsageCounter.js b/packages/agent-runtime/src/core/UsageCounter.js
new file mode 100644
index 000000000..2352cc165
--- /dev/null
+++ b/packages/agent-runtime/src/core/UsageCounter.js
@@ -0,0 +1,200 @@
+/**
+ * UsageCounter - Pure accumulator for usage and cost tracking
+ * Focuses only on usage/cost calculations without managing state
+ */
+/* eslint-disable unicorn/no-static-only-class */
+export class UsageCounter {
+ /**
+ * Create default usage statistics
+ */
+ static createDefaultUsage() {
+ return {
+ humanInteraction: {
+ approvalRequests: 0,
+ promptRequests: 0,
+ selectRequests: 0,
+ totalWaitingTimeMs: 0,
+ },
+ llm: {
+ apiCalls: 0,
+ processingTimeMs: 0,
+ tokens: {
+ input: 0,
+ output: 0,
+ total: 0,
+ },
+ },
+ tools: {
+ byTool: [],
+ totalCalls: 0,
+ totalTimeMs: 0,
+ },
+ };
+ }
+ /**
+ * Create default cost statistics
+ */
+ static createDefaultCost() {
+ return {
+ calculatedAt: new Date().toISOString(),
+ currency: 'USD',
+ llm: {
+ byModel: [],
+ currency: 'USD',
+ total: 0,
+ },
+ tools: {
+ byTool: [],
+ currency: 'USD',
+ total: 0,
+ },
+ total: 0,
+ };
+ }
+ /**
+ * Merge two ModelUsage objects by accumulating token counts
+ * @param previous - Previous usage statistics
+ * @param current - Current usage statistics to add
+ * @returns Merged usage statistics
+ */
+ static mergeModelUsage(previous, current) {
+ if (!previous)
+ return current;
+ const merged = { ...current };
+ // Accumulate all numeric token fields
+ const numericFields = [
+ 'inputCachedTokens',
+ 'inputCacheMissTokens',
+ 'inputWriteCacheTokens',
+ 'inputTextTokens',
+ 'inputImageTokens',
+ 'inputAudioTokens',
+ 'inputCitationTokens',
+ 'outputTextTokens',
+ 'outputImageTokens',
+ 'outputAudioTokens',
+ 'outputReasoningTokens',
+ 'acceptedPredictionTokens',
+ 'rejectedPredictionTokens',
+ 'totalInputTokens',
+ 'totalOutputTokens',
+ 'totalTokens',
+ ];
+ for (const field of numericFields) {
+ const prevValue = previous[field];
+ const currValue = current[field];
+ if (prevValue !== undefined || currValue !== undefined) {
+ merged[field] = (prevValue || 0) + (currValue || 0);
+ }
+ }
+ // Accumulate cost
+ if (previous.cost !== undefined || current.cost !== undefined) {
+ merged.cost = (previous.cost || 0) + (current.cost || 0);
+ }
+ return merged;
+ }
+ /**
+ * Accumulate LLM usage and cost for a specific model
+ * @param params - Accumulation parameters
+ * @param params.usage - Current usage statistics (optional, will be created if not provided)
+ * @param params.cost - Current cost statistics (optional, will be created if not provided)
+ * @param params.provider - Provider name (e.g., "openai")
+ * @param params.model - Model name (e.g., "gpt-4")
+ * @param params.modelUsage - ModelUsage from model-runtime
+ * @returns Updated usage and cost
+ */
+ static accumulateLLM(params) {
+ const { usage, cost, provider, model, modelUsage } = params;
+ // Ensure usage exists
+ const newUsage = usage ? structuredClone(usage) : this.createDefaultUsage();
+ // Accumulate token counts to usage.llm
+ newUsage.llm.tokens.input += modelUsage.totalInputTokens ?? 0;
+ newUsage.llm.tokens.output += modelUsage.totalOutputTokens ?? 0;
+ newUsage.llm.tokens.total += modelUsage.totalTokens ?? 0;
+ newUsage.llm.apiCalls += 1;
+ // Ensure cost exists if modelUsage has cost
+ let newCost = cost
+ ? structuredClone(cost)
+ : modelUsage.cost
+ ? this.createDefaultCost()
+ : undefined;
+ if (modelUsage.cost && newCost) {
+ const modelId = `${provider}/${model}`;
+ // Find or create byModel entry
+ let modelEntry = newCost.llm.byModel.find((entry) => entry.id === modelId);
+ if (!modelEntry) {
+ modelEntry = {
+ id: modelId,
+ model,
+ provider,
+ totalCost: 0,
+ usage: {},
+ };
+ newCost.llm.byModel.push(modelEntry);
+ }
+ // Merge usage breakdown
+ modelEntry.usage = UsageCounter.mergeModelUsage(modelEntry.usage, modelUsage);
+ // Accumulate costs
+ modelEntry.totalCost += modelUsage.cost;
+ newCost.llm.total += modelUsage.cost;
+ newCost.total += modelUsage.cost;
+ newCost.calculatedAt = new Date().toISOString();
+ }
+ return { cost: newCost, usage: newUsage };
+ }
+ /**
+ * Accumulate tool usage and cost
+ * @param params - Accumulation parameters
+ * @param params.usage - Current usage statistics (optional, will be created if not provided)
+ * @param params.cost - Current cost statistics (optional, will be created if not provided)
+ * @param params.toolName - Tool identifier
+ * @param params.executionTime - Execution time in milliseconds
+ * @param params.success - Whether the execution was successful
+ * @param params.toolCost - Optional cost for this tool call
+ * @returns Updated usage and cost
+ */
+ static accumulateTool(params) {
+ const { usage, cost, toolName, executionTime, success, toolCost } = params;
+ // Ensure usage exists
+ const newUsage = usage ? structuredClone(usage) : this.createDefaultUsage();
+ // Find or create byTool entry
+ let toolEntry = newUsage.tools.byTool.find((entry) => entry.name === toolName);
+ if (!toolEntry) {
+ toolEntry = {
+ calls: 0,
+ errors: 0,
+ name: toolName,
+ totalTimeMs: 0,
+ };
+ newUsage.tools.byTool.push(toolEntry);
+ }
+ // Accumulate tool usage
+ toolEntry.calls += 1;
+ toolEntry.totalTimeMs += executionTime;
+ if (!success) {
+ toolEntry.errors += 1;
+ }
+ newUsage.tools.totalCalls += 1;
+ newUsage.tools.totalTimeMs += executionTime;
+ // Ensure cost exists if toolCost is provided
+ let newCost = cost ? structuredClone(cost) : toolCost ? this.createDefaultCost() : undefined;
+ if (toolCost && newCost) {
+ let toolCostEntry = newCost.tools.byTool.find((entry) => entry.name === toolName);
+ if (!toolCostEntry) {
+ toolCostEntry = {
+ calls: 0,
+ currency: 'USD',
+ name: toolName,
+ totalCost: 0,
+ };
+ newCost.tools.byTool.push(toolCostEntry);
+ }
+ toolCostEntry.calls += 1;
+ toolCostEntry.totalCost += toolCost;
+ newCost.tools.total += toolCost;
+ newCost.total += toolCost;
+ newCost.calculatedAt = new Date().toISOString();
+ }
+ return { cost: newCost, usage: newUsage };
+ }
+}
diff --git a/packages/agent-runtime/src/core/X402Hook.d.ts b/packages/agent-runtime/src/core/X402Hook.d.ts
new file mode 100644
index 000000000..3dc83dc7a
--- /dev/null
+++ b/packages/agent-runtime/src/core/X402Hook.d.ts
@@ -0,0 +1,19 @@
+import type { X402Hook, X402HookResult, X402PaymentRequirements } from '../types/runtime.js';
+/**
+ * Creates the default x402 autonomy hook.
+ *
+ * Decision logic:
+ *
+ * 1. If `currentBalanceUsdc < amountRequired` → reject (insufficient funds)
+ * 2. If `amountSpentThisHourUsdc + amountRequired > hourlyBudgetUsd` → queue for approval
+ * 3. Otherwise → pay automatically
+ *
+ * @param hourlyBudgetUsd - Max USD an agent may spend per hour autonomously
+ * (default: $5). Pass `Infinity` to disable the budget check.
+ */
+export declare function createX402Hook(hourlyBudgetUsd?: number): X402Hook;
+/**
+ * Re-exports the x402 payment requirements type so callers can use
+ * it without importing from the types module directly.
+ */
+export type { X402Hook, X402HookResult, X402PaymentRequirements };
diff --git a/packages/agent-runtime/src/core/X402Hook.js b/packages/agent-runtime/src/core/X402Hook.js
new file mode 100644
index 000000000..ecfe76f39
--- /dev/null
+++ b/packages/agent-runtime/src/core/X402Hook.js
@@ -0,0 +1,64 @@
+// ─── Default autonomy budget ──────────────────────────────────────────────────
+/** Default hourly spend cap per agent in USD before requiring user approval */
+const DEFAULT_HOURLY_BUDGET_USD = 5.0;
+// ─── Token decimals lookup ───────────────────────────────────────────────────
+/** Resolve decimals for the payment asset. USDC, USDT and EURC all use 6. */
+function getTokenDecimals(accept) {
+ if (typeof accept.decimals === 'number' && Number.isFinite(accept.decimals))
+ return accept.decimals;
+ return 6;
+}
+/** Resolve a display name for the chain from a CAIP-2 network string. */
+function getChainName(network) {
+ if (!network)
+ return 'unknown chain';
+ const chainNames = {
+ 'eip155:1': 'Ethereum',
+ 'eip155:8453': 'Base',
+ 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp': 'Solana',
+ };
+ return chainNames[network] ?? network;
+}
+// ─── Factory ──────────────────────────────────────────────────────────────────
+/**
+ * Creates the default x402 autonomy hook.
+ *
+ * Decision logic:
+ *
+ * 1. If `currentBalanceUsdc < amountRequired` → reject (insufficient funds)
+ * 2. If `amountSpentThisHourUsdc + amountRequired > hourlyBudgetUsd` → queue for approval
+ * 3. Otherwise → pay automatically
+ *
+ * @param hourlyBudgetUsd - Max USD an agent may spend per hour autonomously
+ * (default: $5). Pass `Infinity` to disable the budget check.
+ */
+export function createX402Hook(hourlyBudgetUsd = DEFAULT_HOURLY_BUDGET_USD) {
+ return async ({ currentBalanceUsdc, amountSpentThisHourUsdc, requirements }) => {
+ const accept = requirements.accepts[0];
+ if (!accept) {
+ return {
+ action: 'reject',
+ reason: 'No payment scheme in 402 response',
+ };
+ }
+ const decimals = getTokenDecimals(accept);
+ const amountRequired = Number(accept.maxAmountRequired) / 10 ** decimals;
+ const chainName = getChainName(accept.network);
+ // 1. Insufficient balance
+ if (currentBalanceUsdc < amountRequired) {
+ return {
+ action: 'reject',
+ reason: `Insufficient balance. Need ${amountRequired.toFixed(4)} but wallet has ${currentBalanceUsdc.toFixed(4)} on ${chainName}.`,
+ };
+ }
+ // 2. Would exceed hourly autonomy budget → queue for user approval
+ if (amountSpentThisHourUsdc + amountRequired > hourlyBudgetUsd) {
+ return {
+ action: 'queue',
+ reason: `Payment of ${amountRequired.toFixed(4)} would exceed the agent's hourly autonomy budget of $${hourlyBudgetUsd.toFixed(2)} (already spent: $${amountSpentThisHourUsdc.toFixed(4)} this hour).`,
+ };
+ }
+ // 3. Pay automatically
+ return { action: 'pay' };
+ };
+}
diff --git a/packages/agent-runtime/src/core/defaultSecurityBlacklist.d.ts b/packages/agent-runtime/src/core/defaultSecurityBlacklist.d.ts
new file mode 100644
index 000000000..091a10e16
--- /dev/null
+++ b/packages/agent-runtime/src/core/defaultSecurityBlacklist.d.ts
@@ -0,0 +1,9 @@
+import type { SecurityBlacklistConfig } from '../types/vendor.js';
+/**
+ * Default Security Blacklist
+ * These rules will ALWAYS block execution and require human intervention,
+ * regardless of user settings (even in auto-run mode)
+ *
+ * This is the last line of defense against dangerous operations
+ */
+export declare const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig;
diff --git a/packages/agent-runtime/src/core/defaultSecurityBlacklist.js b/packages/agent-runtime/src/core/defaultSecurityBlacklist.js
new file mode 100644
index 000000000..e7cadd92e
--- /dev/null
+++ b/packages/agent-runtime/src/core/defaultSecurityBlacklist.js
@@ -0,0 +1,323 @@
+/**
+ * Default Security Blacklist
+ * These rules will ALWAYS block execution and require human intervention,
+ * regardless of user settings (even in auto-run mode)
+ *
+ * This is the last line of defense against dangerous operations
+ */
+export const DEFAULT_SECURITY_BLACKLIST = [
+ // ==================== File System Dangers ====================
+ {
+ description: 'Recursive deletion of home directory is extremely dangerous',
+ match: {
+ command: {
+ pattern: 'rm.*-r.*(~|\\$HOME|/Users/[^/]+|/home/[^/]+)/?\\s*$',
+ type: 'regex',
+ },
+ },
+ },
+ {
+ description: 'Recursive deletion of root directory will destroy the system',
+ match: {
+ command: {
+ pattern: 'rm.*-r.*/\\s*$',
+ type: 'regex',
+ },
+ },
+ },
+ {
+ description: 'Force recursive deletion without specific target is too dangerous',
+ match: {
+ command: {
+ pattern: 'rm\\s+-rf\\s+[~./]\\s*$',
+ type: 'regex',
+ },
+ },
+ },
+ // ==================== System Configuration Dangers ====================
+ {
+ description: 'Modifying /etc/passwd could lock you out of the system',
+ match: {
+ command: {
+ pattern: '.*(/etc/passwd|/etc/shadow).*',
+ type: 'regex',
+ },
+ },
+ },
+ {
+ description: 'Modifying sudoers file without proper validation is dangerous',
+ match: {
+ command: {
+ pattern: '.*/etc/sudoers.*',
+ type: 'regex',
+ },
+ },
+ },
+ // ==================== Dangerous Commands ====================
+ {
+ description: 'Fork bomb can crash the system',
+ match: {
+ command: {
+ pattern: '.*:\\(\\).*\\{.*\\|.*&.*\\};.*:.*',
+ type: 'regex',
+ },
+ },
+ },
+ {
+ description: 'Writing random data to disk devices can destroy data',
+ match: {
+ command: {
+ pattern: 'dd.*of=/dev/(sd|hd|nvme).*',
+ type: 'regex',
+ },
+ },
+ },
+ {
+ description: 'Formatting system partitions will destroy data',
+ match: {
+ command: {
+ pattern: '(mkfs|fdisk|parted).*(/dev/(sd|hd|nvme)|/)',
+ type: 'regex',
+ },
+ },
+ },
+ // ==================== Network & Remote Access Dangers ====================
+ {
+ description: 'Disabling firewall exposes system to attacks',
+ match: {
+ command: {
+ pattern: '(ufw\\s+disable|iptables\\s+-F|systemctl\\s+stop\\s+firewalld)',
+ type: 'regex',
+ },
+ },
+ },
+ {
+ description: 'Changing SSH configuration could lock you out',
+ match: {
+ command: {
+ pattern: '.*(/etc/ssh/sshd_config).*',
+ type: 'regex',
+ },
+ },
+ },
+ // ==================== Package Manager Dangers ====================
+ {
+ description: 'Removing essential system packages can break the system',
+ match: {
+ command: {
+ pattern: '(apt|yum|dnf|pacman)\\s+(remove|purge|erase).*(systemd|kernel|glibc|bash|sudo)',
+ type: 'regex',
+ },
+ },
+ },
+ // ==================== Kernel & System Core Dangers ====================
+ {
+ description: 'Modifying kernel parameters without understanding can crash the system',
+ match: {
+ command: {
+ pattern: 'echo.*>/proc/sys/.*',
+ type: 'regex',
+ },
+ },
+ },
+ {
+ description: 'Direct memory access is extremely dangerous',
+ match: {
+ command: {
+ pattern: '.*(/dev/(mem|kmem|port)).*',
+ type: 'regex',
+ },
+ },
+ },
+ // ==================== Privilege Escalation Dangers ====================
+ {
+ description: 'Changing file ownership of system directories is dangerous',
+ match: {
+ command: {
+ pattern: 'chown.*-R.*(/(etc|bin|sbin|usr|var|sys|proc)|~).*',
+ type: 'regex',
+ },
+ },
+ },
+ {
+ description: 'Setting SUID on shells or interpreters is a security risk',
+ match: {
+ command: {
+ pattern: 'chmod.*(4755|u\\+s).*(sh|bash|python|perl|ruby|node)',
+ type: 'regex',
+ },
+ },
+ },
+ // ==================== Sensitive Information Leakage ====================
+ {
+ description: 'Reading .env files may leak sensitive credentials and API keys',
+ match: {
+ command: {
+ pattern: '(cat|less|more|head|tail|vim|nano|vi|emacs|code).*\\.env.*',
+ type: 'regex',
+ },
+ },
+ },
+ {
+ description: 'Reading .env files may leak sensitive credentials and API keys',
+ match: {
+ path: {
+ pattern: '.*\\.env.*',
+ type: 'regex',
+ },
+ },
+ },
+ {
+ description: 'Reading SSH private keys can compromise system security',
+ match: {
+ command: {
+ pattern: '(cat|less|more|head|tail|vim|nano|vi|emacs|code).*(id_rsa|id_ed25519|id_ecdsa)(?!\\.pub).*',
+ type: 'regex',
+ },
+ },
+ },
+ {
+ description: 'Reading SSH private keys can compromise system security',
+ match: {
+ path: {
+ pattern: '.*/\\.ssh/(id_rsa|id_ed25519|id_ecdsa)$',
+ type: 'regex',
+ },
+ },
+ },
+ {
+ description: 'Accessing AWS credentials can leak cloud access keys',
+ match: {
+ command: {
+ pattern: '(cat|less|more|head|tail|vim|nano|vi|emacs|code).*/\\.aws/credentials.*',
+ type: 'regex',
+ },
+ },
+ },
+ {
+ description: 'Accessing AWS credentials can leak cloud access keys',
+ match: {
+ path: {
+ pattern: '.*/\\.aws/credentials.*',
+ type: 'regex',
+ },
+ },
+ },
+ {
+ description: 'Reading Docker config may expose registry credentials',
+ match: {
+ command: {
+ pattern: '(cat|less|more|head|tail|vim|nano|vi|emacs|code).*/\\.docker/config\\.json.*',
+ type: 'regex',
+ },
+ },
+ },
+ {
+ description: 'Reading Docker config may expose registry credentials',
+ match: {
+ path: {
+ pattern: '.*/\\.docker/config\\.json$',
+ type: 'regex',
+ },
+ },
+ },
+ {
+ description: 'Reading Kubernetes config may expose cluster credentials',
+ match: {
+ command: {
+ pattern: '(cat|less|more|head|tail|vim|nano|vi|emacs|code).*/\\.kube/config.*',
+ type: 'regex',
+ },
+ },
+ },
+ {
+ description: 'Reading Kubernetes config may expose cluster credentials',
+ match: {
+ path: {
+ pattern: '.*/\\.kube/config$',
+ type: 'regex',
+ },
+ },
+ },
+ {
+ description: 'Reading Git credentials file may leak access tokens',
+ match: {
+ command: {
+ pattern: '(cat|less|more|head|tail|vim|nano|vi|emacs|code).*/\\.git-credentials.*',
+ type: 'regex',
+ },
+ },
+ },
+ {
+ description: 'Reading Git credentials file may leak access tokens',
+ match: {
+ path: {
+ pattern: '.*/\\.git-credentials$',
+ type: 'regex',
+ },
+ },
+ },
+ {
+ description: 'Reading npm token file may expose package registry credentials',
+ match: {
+ command: {
+ pattern: '(cat|less|more|head|tail|vim|nano|vi|emacs|code).*/\\.npmrc.*',
+ type: 'regex',
+ },
+ },
+ },
+ {
+ description: 'Reading npm token file may expose package registry credentials',
+ match: {
+ path: {
+ pattern: '.*/\\.npmrc$',
+ type: 'regex',
+ },
+ },
+ },
+ {
+ description: 'Reading history files may expose sensitive commands and credentials',
+ match: {
+ command: {
+ pattern: '(cat|less|more|head|tail|vim|nano|vi|emacs|code).*/\\.(bash_history|zsh_history|history).*',
+ type: 'regex',
+ },
+ },
+ },
+ {
+ description: 'Reading history files may expose sensitive commands and credentials',
+ match: {
+ path: {
+ pattern: '.*/\\.(bash_history|zsh_history|history)$',
+ type: 'regex',
+ },
+ },
+ },
+ {
+ description: 'Accessing browser credential storage may leak passwords',
+ match: {
+ command: {
+ pattern: '(cat|less|more|head|tail|vim|nano|vi|emacs|code).*(Cookies|Login Data|Web Data).*',
+ type: 'regex',
+ },
+ },
+ },
+ {
+ description: 'Reading GCP credentials may leak cloud service account keys',
+ match: {
+ command: {
+ pattern: '(cat|less|more|head|tail|vim|nano|vi|emacs|code).*/\\.config/gcloud/.*\\.json.*',
+ type: 'regex',
+ },
+ },
+ },
+ {
+ description: 'Reading GCP credentials may leak cloud service account keys',
+ match: {
+ path: {
+ pattern: '.*/\\.config/gcloud/.*\\.json$',
+ type: 'regex',
+ },
+ },
+ },
+];
diff --git a/packages/agent-runtime/src/core/index.d.ts b/packages/agent-runtime/src/core/index.d.ts
new file mode 100644
index 000000000..1acab1829
--- /dev/null
+++ b/packages/agent-runtime/src/core/index.d.ts
@@ -0,0 +1,19 @@
+export * from './ActionLedger.js';
+export * from './CapabilityGuard.js';
+export * from './DecisionJournal.js';
+export * from './defaultSecurityBlacklist.js';
+export * from './ExitDecisionEngine.js';
+export * from './GuardChain.js';
+export * from './InterventionChecker.js';
+export * from './PermissionGuard.js';
+export * from './ResponseQualityEvaluator.js';
+export * from './runtime.js';
+export * from './SelfReflection.js';
+export * from './SpendGuard.js';
+export * from './spendGuardPipeline.js';
+export * from './toolRegistry.js';
+export * from './TradeGuard.js';
+export * from './TransactionPipeline.js';
+export * from './ToolRelevanceScorer.js';
+export * from './UsageCounter.js';
+export * from './X402Hook.js';
diff --git a/packages/agent-runtime/src/core/index.js b/packages/agent-runtime/src/core/index.js
new file mode 100644
index 000000000..1acab1829
--- /dev/null
+++ b/packages/agent-runtime/src/core/index.js
@@ -0,0 +1,19 @@
+export * from './ActionLedger.js';
+export * from './CapabilityGuard.js';
+export * from './DecisionJournal.js';
+export * from './defaultSecurityBlacklist.js';
+export * from './ExitDecisionEngine.js';
+export * from './GuardChain.js';
+export * from './InterventionChecker.js';
+export * from './PermissionGuard.js';
+export * from './ResponseQualityEvaluator.js';
+export * from './runtime.js';
+export * from './SelfReflection.js';
+export * from './SpendGuard.js';
+export * from './spendGuardPipeline.js';
+export * from './toolRegistry.js';
+export * from './TradeGuard.js';
+export * from './TransactionPipeline.js';
+export * from './ToolRelevanceScorer.js';
+export * from './UsageCounter.js';
+export * from './X402Hook.js';
diff --git a/packages/agent-runtime/src/core/runtime.d.ts b/packages/agent-runtime/src/core/runtime.d.ts
new file mode 100644
index 000000000..d5a0ce507
--- /dev/null
+++ b/packages/agent-runtime/src/core/runtime.d.ts
@@ -0,0 +1,117 @@
+import { ChatToolPayload } from '../types/vendor.js';
+import { Agent, AgentEvent, AgentRuntimeContext, AgentState, Cost, RuntimeConfig, Usage } from '../types/index.js';
+/**
+ * Simplified Agent Runtime - The "Engine" that executes instructions from an "Agent" (Brain).
+ * Now includes built-in call_llm support and allows full executor customization.
+ */
+export declare class AgentRuntime {
+ private agent;
+ private config;
+ private executors;
+ private operationId?;
+ private getOperation?;
+ constructor(agent: Agent, config?: RuntimeConfig);
+ /**
+ * Get operation context (sessionId, topicId, etc.)
+ * Returns the business context captured by the operation
+ */
+ getContext(): Record<string, any>;
+ /**
+ * Get operation abort controller
+ * Returns the AbortController for cancellation
+ */
+ getAbortController(): AbortController | undefined;
+ /**
+ * Executes a single step of the Plan -> Execute loop.
+ * @param state - Current agent state
+ * @param context - Runtime context for this step (required for proper phase detection)
+ */
+ step(state: AgentState, context?: AgentRuntimeContext): Promise<{
+ events: AgentEvent[];
+ newState: AgentState;
+ nextContext?: AgentRuntimeContext;
+ }>;
+ /**
+ * Convenience method for approving and executing a tool call
+ */
+ approveToolCall(state: AgentState, approvedToolCall: ChatToolPayload): Promise<{
+ events: AgentEvent[];
+ newState: AgentState;
+ nextContext?: AgentRuntimeContext;
+ }>;
+ /**
+ * Interrupt the current execution
+ * @param state - Current agent state
+ * @param reason - Reason for interruption
+ * @param canResume - Whether the interruption can be resumed later
+ * @param metadata - Additional metadata about the interruption
+ */
+ interrupt(state: AgentState, reason: string, canResume?: boolean, metadata?: Record<string, unknown>): {
+ events: AgentEvent[];
+ newState: AgentState;
+ };
+ /**
+ * Resume execution from an interrupted state
+ * @param state - Interrupted agent state
+ * @param reason - Reason for resumption
+ * @param context - Optional context to resume with
+ */
+ resume(state: AgentState, reason?: string, context?: AgentRuntimeContext): Promise<{
+ events: AgentEvent[];
+ newState: AgentState;
+ nextContext?: AgentRuntimeContext;
+ }>;
+ /**
+ * Create default usage statistics structure
+ * @returns Default Usage object with all counters set to 0
+ */
+ static createDefaultUsage(): Usage;
+ /**
+ * Create default cost structure
+ * @returns Default Cost object with all costs set to 0
+ */
+ static createDefaultCost(): Cost;
+ /**
+ * Create a new agent state with flexible initialization
+ * @param partialState - Partial state to override defaults
+ * @returns Complete AgentState with defaults filled in
+ */
+ static createInitialState(partialState?: Partial<AgentState> & {
+ operationId: string;
+ }): AgentState;
+ /** Create call_llm executor with streaming support */
+ private createCallLLMExecutor;
+ /** Create call_tool executor */
+ private createCallToolExecutor;
+ /** Create human approve executor */
+ private createHumanApproveExecutor;
+ /** Create human prompt executor */
+ private createHumanPromptExecutor;
+ /** Create human select executor */
+ private createHumanSelectExecutor;
+ /** Create finish executor */
+ private createFinishExecutor;
+ /**
+ * Execute multiple tool calls concurrently
+ */
+ private executeToolsBatch;
+ /**
+ * Merge multiple tool execution results
+ */
+ private mergeToolResults;
+ /**
+ * Handle cost limit exceeded scenario
+ */
+ private handleCostLimitExceeded;
+ /**
+ * Create session context metadata - reusable helper
+ * Note: Uses sessionId in context for backwards compatibility with AgentRuntimeContext
+ */
+ private createSessionContext;
+ /**
+ * Create initial context for the first step (fallback for backward compatibility)
+ */
+ private createInitialContext;
+ /** Create error state and events */
+ private createErrorResult;
+}
diff --git a/packages/agent-runtime/src/core/runtime.js b/packages/agent-runtime/src/core/runtime.js
new file mode 100644
index 000000000..4bf79b4aa
--- /dev/null
+++ b/packages/agent-runtime/src/core/runtime.js
@@ -0,0 +1,721 @@
+/**
+ * Simplified Agent Runtime - The "Engine" that executes instructions from an "Agent" (Brain).
+ * Now includes built-in call_llm support and allows full executor customization.
+ */
+export class AgentRuntime {
+ agent;
+ config;
+ executors;
+ operationId;
+ getOperation;
+ constructor(agent, config = {}) {
+ this.agent = agent;
+ this.config = config;
+ this.operationId = config.operationId;
+ this.getOperation = config.getOperation;
+ // Build executors with priority: agent.executors > config.executors > built-in
+ this.executors = {
+ call_llm: this.createCallLLMExecutor(),
+ call_tool: this.createCallToolExecutor(),
+ finish: this.createFinishExecutor(),
+ request_human_approve: this.createHumanApproveExecutor(),
+ request_human_prompt: this.createHumanPromptExecutor(),
+ request_human_select: this.createHumanSelectExecutor(),
+ // Config executors override built-in
+ ...config.executors,
+ // Agent provided executors have highest priority
+ ...agent.executors,
+ };
+ }
+ /**
+ * Get operation context (sessionId, topicId, etc.)
+ * Returns the business context captured by the operation
+ */
+ getContext() {
+ if (!this.operationId || !this.getOperation) {
+ return undefined;
+ }
+ return this.getOperation(this.operationId).context;
+ }
+ /**
+ * Get operation abort controller
+ * Returns the AbortController for cancellation
+ */
+ getAbortController() {
+ if (!this.operationId || !this.getOperation) {
+ return undefined;
+ }
+ return this.getOperation(this.operationId).abortController;
+ }
+ /**
+ * Executes a single step of the Plan -> Execute loop.
+ * @param state - Current agent state
+ * @param context - Runtime context for this step (required for proper phase detection)
+ */
+ async step(state, context) {
+ try {
+ // Increment step count and check limits
+ const newState = structuredClone(state);
+ newState.stepCount += 1;
+ newState.lastModified = new Date().toISOString();
+ // Check maximum steps limit
+ if (newState.maxSteps && newState.stepCount > newState.maxSteps) {
+ // Finish execution when maxSteps is exceeded
+ newState.status = 'done';
+ const finishEvent = {
+ finalState: newState,
+ reason: 'max_steps_exceeded',
+ reasonDetail: `Maximum steps exceeded: ${newState.maxSteps}`,
+ type: 'done',
+ };
+ return {
+ events: [finishEvent],
+ newState,
+ nextContext: undefined, // No next context when done
+ };
+ }
+ // Use provided context or create initial context
+ const runtimeContext = context || this.createInitialContext(newState);
+ // Get instructions from agent runner and normalize to array
+ let rawInstructions;
+ // Handle human approved tool calls
+ if (runtimeContext.phase === 'human_approved_tool') {
+ const approvedPayload = runtimeContext.payload;
+ const toolCalling = approvedPayload.approvedToolCall;
+ rawInstructions = {
+ payload: {
+ parentMessageId: approvedPayload.parentMessageId,
+ skipCreateToolMessage: approvedPayload.skipCreateToolMessage,
+ toolCalling,
+ },
+ type: 'call_tool',
+ };
+ }
+ else {
+ // Standard flow: Plan -> Execute
+ rawInstructions = await this.agent.runner(runtimeContext, newState);
+ }
+ // Normalize to array
+ const instructions = Array.isArray(rawInstructions) ? rawInstructions : [rawInstructions];
+ // Convert old format to new format
+ const normalizedInstructions = instructions.map((instruction) => {
+ if (instruction.type === 'call_tools_batch' && // Check if payload is array of ToolsCalling (old format)
+ Array.isArray(instruction.payload)) {
+ const toolsCalling = instruction.payload.map((tc) => ({
+ apiName: tc.function.name,
+ arguments: tc.function.arguments,
+ id: tc.id,
+ identifier: tc.function.name,
+ type: 'default',
+ }));
+ return {
+ payload: {
+ parentMessageId: '',
+ toolsCalling,
+ },
+ type: 'call_tools_batch',
+ };
+ }
+ return instruction;
+ });
+ // Execute all instructions sequentially
+ let currentState = newState;
+ const allEvents = [];
+ let finalNextContext = undefined;
+ for (const instruction of normalizedInstructions) {
+ let result;
+ // Special handling for batch tool execution
+ if (instruction.type === 'call_tools_batch') {
+ // Check if custom executor is provided (e.g., server-side with DB access)
+ const customExecutor = this.executors['call_tools_batch'];
+ if (customExecutor) {
+ result = await customExecutor(instruction, currentState, runtimeContext);
+ }
+ else {
+ // Fallback to built-in executeToolsBatch
+ result = await this.executeToolsBatch(instruction, currentState, runtimeContext);
+ }
+ }
+ else {
+ const executor = this.executors[instruction.type];
+ if (!executor) {
+ throw new Error(`No executor found for instruction type: ${instruction.type}`);
+ }
+ // Pass runtimeContext to executor so it can access stepContext
+ result = await executor(instruction, currentState, runtimeContext);
+ }
+ // Accumulate events
+ allEvents.push(...result.events);
+ // Update state
+ currentState = result.newState;
+ // Keep the last nextContext
+ if (result.nextContext) {
+ finalNextContext = result.nextContext;
+ }
+ // Stop execution if blocked
+ if (currentState.status === 'waiting_for_human' || currentState.status === 'interrupted') {
+ break;
+ }
+ }
+ // Ensure stepCount and lastModified are preserved
+ currentState.stepCount = newState.stepCount;
+ currentState.lastModified = newState.lastModified;
+ return {
+ events: allEvents,
+ newState: currentState,
+ nextContext: finalNextContext,
+ };
+ }
+ catch (error) {
+ const errorState = structuredClone(state);
+ errorState.stepCount += 1;
+ errorState.lastModified = new Date().toISOString();
+ return this.createErrorResult(errorState, error);
+ }
+ }
+ /**
+ * Convenience method for approving and executing a tool call
+ */
+ async approveToolCall(state, approvedToolCall) {
+ const context = {
+ operationId: this.operationId,
+ payload: { approvedToolCall },
+ phase: 'human_approved_tool',
+ session: this.createSessionContext(state),
+ };
+ return this.step(state, context);
+ }
+ /**
+ * Interrupt the current execution
+ * @param state - Current agent state
+ * @param reason - Reason for interruption
+ * @param canResume - Whether the interruption can be resumed later
+ * @param metadata - Additional metadata about the interruption
+ */
+ interrupt(state, reason, canResume = true, metadata) {
+ const newState = structuredClone(state);
+ const interruptedAt = new Date().toISOString();
+ newState.status = 'interrupted';
+ newState.lastModified = interruptedAt;
+ newState.interruption = {
+ canResume,
+ interruptedAt,
+ // Store the current step for potential resumption
+ interruptedInstruction: undefined,
+ reason, // Could be enhanced to store current instruction
+ };
+ const interruptEvent = {
+ canResume,
+ interruptedAt,
+ metadata,
+ reason,
+ type: 'interrupted',
+ };
+ return {
+ events: [interruptEvent],
+ newState,
+ };
+ }
+ /**
+ * Resume execution from an interrupted state
+ * @param state - Interrupted agent state
+ * @param reason - Reason for resumption
+ * @param context - Optional context to resume with
+ */
+ async resume(state, reason = 'User resumed execution', context) {
+ if (state.status !== 'interrupted') {
+ throw new Error('Cannot resume: state is not interrupted');
+ }
+ if (state.interruption && !state.interruption.canResume) {
+ throw new Error('Cannot resume: interruption is not resumable');
+ }
+ const newState = structuredClone(state);
+ const resumedAt = new Date().toISOString();
+ const resumedFromStep = state.stepCount;
+ // Clear interruption context and set status back to running
+ newState.status = 'running';
+ newState.lastModified = resumedAt;
+ newState.interruption = undefined;
+ const resumeEvent = {
+ reason,
+ resumedAt,
+ resumedFromStep,
+ type: 'resumed',
+ };
+ // If context is provided, continue with that context
+ if (context) {
+ const result = await this.step(newState, context);
+ return {
+ events: [resumeEvent, ...result.events],
+ newState: result.newState,
+ nextContext: result.nextContext,
+ };
+ }
+ // Otherwise, just return the resumed state
+ const initialContext = this.createInitialContext(newState);
+ return {
+ events: [resumeEvent],
+ newState,
+ nextContext: initialContext,
+ };
+ }
+ /**
+ * Create default usage statistics structure
+ * @returns Default Usage object with all counters set to 0
+ */
+ static createDefaultUsage() {
+ return {
+ humanInteraction: {
+ approvalRequests: 0,
+ promptRequests: 0,
+ selectRequests: 0,
+ totalWaitingTimeMs: 0,
+ },
+ llm: {
+ apiCalls: 0,
+ processingTimeMs: 0,
+ tokens: { input: 0, output: 0, total: 0 },
+ },
+ tools: {
+ byTool: [],
+ totalCalls: 0,
+ totalTimeMs: 0,
+ },
+ };
+ }
+ /**
+ * Create default cost structure
+ * @returns Default Cost object with all costs set to 0
+ */
+ static createDefaultCost() {
+ const now = new Date().toISOString();
+ return {
+ calculatedAt: now,
+ currency: 'USD',
+ llm: {
+ byModel: [],
+ currency: 'USD',
+ total: 0,
+ },
+ tools: {
+ byTool: [],
+ currency: 'USD',
+ total: 0,
+ },
+ total: 0,
+ };
+ }
+ /**
+ * Create a new agent state with flexible initialization
+ * @param partialState - Partial state to override defaults
+ * @returns Complete AgentState with defaults filled in
+ */
+ static createInitialState(partialState) {
+ const now = new Date().toISOString();
+ return {
+ cost: AgentRuntime.createDefaultCost(),
+ // Default values
+ createdAt: now,
+ lastModified: now,
+ messages: [],
+ status: 'idle',
+ stepCount: 0,
+ toolManifestMap: {},
+ usage: AgentRuntime.createDefaultUsage(),
+ // User provided values override defaults
+ ...(partialState || { operationId: '' }),
+ };
+ }
+ // ============ Executor Factory Methods ============
+ /** Create call_llm executor with streaming support */
+ createCallLLMExecutor() {
+ return async (instruction, state) => {
+ const { payload } = instruction;
+ const newState = structuredClone(state);
+ const events = [];
+ newState.status = 'running';
+ newState.lastModified = new Date().toISOString();
+ events.push({ payload, type: 'llm_start' });
+ // Use Agent's modelRuntime first, fallback to config
+ const modelRuntime = this.agent.modelRuntime;
+ if (!modelRuntime) {
+ throw new Error('Model Runtime is required for call_llm instruction. Provide it via Agent.modelRuntime or RuntimeConfig.modelRuntime');
+ }
+ let assistantContent = '';
+ let toolCalls = [];
+ try {
+ // Stream LLM response
+ for await (const chunk of modelRuntime(payload)) {
+ // Emit individual stream events for each chunk
+ events.push({ chunk, type: 'llm_stream' });
+ // Accumulate content and tool calls from chunks
+ if (chunk.content) {
+ assistantContent += chunk.content;
+ }
+ if (chunk.tool_calls) {
+ toolCalls = chunk.tool_calls;
+ }
+ }
+ events.push({
+ result: { content: assistantContent, tool_calls: toolCalls },
+ type: 'llm_result',
+ });
+ // Update usage and cost if agent provides calculation methods
+ if (this.agent.calculateUsage) {
+ newState.usage = this.agent.calculateUsage('llm', { content: assistantContent, tool_calls: toolCalls }, newState.usage);
+ }
+ if (this.agent.calculateCost) {
+ newState.cost = this.agent.calculateCost({
+ costLimit: newState.costLimit,
+ previousCost: newState.cost,
+ usage: newState.usage,
+ });
+ }
+ // Check cost limits
+ if (newState.costLimit && newState.cost.total > newState.costLimit.maxTotalCost) {
+ return this.handleCostLimitExceeded(newState);
+ }
+ // Provide next context based on LLM result
+ const nextContext = {
+ operationId: this.operationId,
+ payload: {
+ hasToolCalls: toolCalls.length > 0,
+ result: { content: assistantContent, tool_calls: toolCalls },
+ toolCalls,
+ },
+ phase: 'llm_result',
+ session: this.createSessionContext(newState),
+ };
+ return { events, newState, nextContext };
+ }
+ catch (error) {
+ return this.createErrorResult(state, error);
+ }
+ };
+ }
+ /** Create call_tool executor */
+ createCallToolExecutor() {
+ return async (instruction, state) => {
+ const { payload } = instruction;
+ const newState = structuredClone(state);
+ const events = [];
+ newState.lastModified = new Date().toISOString();
+ newState.status = 'running';
+ const tools = this.agent.tools || {};
+ const toolCall = payload.toolCalling;
+ // Support both ToolsCalling (OpenAI format) and CallingToolPayload formats
+ const toolName = toolCall.apiName;
+ const toolArgs = toolCall.arguments;
+ const toolId = toolCall.id;
+ const handler = tools[toolName];
+ if (!handler)
+ throw new Error(`Tool not found: ${toolName}`);
+ let args;
+ try {
+ args = JSON.parse(toolArgs);
+ }
+ catch (parseError) {
+ throw new Error(`Failed to parse arguments for tool "${toolName}" (call ${toolId}): ${parseError}`);
+ }
+ const result = await handler(args);
+ const MAX_TOOL_OUTPUT_SIZE = 500_000; // 500KB
+ let serialized = JSON.stringify(result);
+ if (serialized.length > MAX_TOOL_OUTPUT_SIZE) {
+ serialized = JSON.stringify({
+ __truncated: true,
+ error: `Tool output exceeded ${MAX_TOOL_OUTPUT_SIZE / 1000}KB limit. Output was truncated.`,
+ summary: serialized.slice(0, 2000) + '...',
+ });
+ }
+ newState.messages.push({
+ content: serialized,
+ role: 'tool',
+ tool_call_id: toolId,
+ });
+ events.push({ id: toolId, result, type: 'tool_result' });
+ // Update usage and cost if agent provides calculation methods
+ if (this.agent.calculateUsage) {
+ newState.usage = this.agent.calculateUsage('tool', { executionTime: 0, result, toolCall }, // Could track actual execution time
+ newState.usage);
+ }
+ if (this.agent.calculateCost) {
+ newState.cost = this.agent.calculateCost({
+ costLimit: newState.costLimit,
+ previousCost: newState.cost,
+ usage: newState.usage,
+ });
+ }
+ // Check cost limits
+ if (newState.costLimit && newState.cost.total > newState.costLimit.maxTotalCost) {
+ return this.handleCostLimitExceeded(newState);
+ }
+ // Provide next context for tool result
+ const nextContext = {
+ operationId: this.operationId,
+ payload: {
+ result,
+ toolCall,
+ toolCallId: toolCall.id,
+ },
+ phase: 'tool_result',
+ session: this.createSessionContext(newState),
+ };
+ return { events, newState, nextContext };
+ };
+ }
+ /** Create human approve executor */
+ createHumanApproveExecutor() {
+ return async (instruction, state) => {
+ const { pendingToolsCalling } = instruction;
+ const newState = structuredClone(state);
+ newState.lastModified = new Date().toISOString();
+ newState.status = 'waiting_for_human';
+ newState.pendingToolsCalling = pendingToolsCalling;
+ const events = [
+ {
+ operationId: newState.operationId,
+ pendingToolsCalling,
+ type: 'human_approve_required',
+ },
+ ];
+ return { events, newState };
+ };
+ }
+ /** Create human prompt executor */
+ createHumanPromptExecutor() {
+ return async (instruction, state) => {
+ const { metadata, prompt } = instruction;
+ const newState = structuredClone(state);
+ newState.lastModified = new Date().toISOString();
+ newState.status = 'waiting_for_human';
+ newState.pendingHumanPrompt = { metadata, prompt };
+ const events = [
+ {
+ metadata,
+ operationId: newState.operationId,
+ prompt,
+ type: 'human_prompt_required',
+ },
+ ];
+ return { events, newState };
+ };
+ }
+ /** Create human select executor */
+ createHumanSelectExecutor() {
+ return async (instruction, state) => {
+ const { metadata, multi, options, prompt } = instruction;
+ const newState = structuredClone(state);
+ newState.lastModified = new Date().toISOString();
+ newState.status = 'waiting_for_human';
+ newState.pendingHumanSelect = { metadata, multi, options, prompt };
+ const events = [
+ {
+ metadata,
+ multi,
+ operationId: newState.operationId,
+ options,
+ prompt,
+ type: 'human_select_required',
+ },
+ ];
+ return { events, newState };
+ };
+ }
+ /** Create finish executor */
+ createFinishExecutor() {
+ return async (instruction, state) => {
+ const { reason, reasonDetail } = instruction;
+ const newState = structuredClone(state);
+ newState.lastModified = new Date().toISOString();
+ newState.status = 'done';
+ const events = [
+ {
+ finalState: newState,
+ reason,
+ reasonDetail,
+ type: 'done',
+ },
+ ];
+ return { events, newState };
+ };
+ }
+ // ============ Helper Methods ============
+ /**
+ * Execute multiple tool calls concurrently
+ */
+ async executeToolsBatch(instruction, baseState, context) {
+ const { payload } = instruction;
+ // Execute all tools concurrently based on the same state
+ const results = await Promise.all(instruction.payload.toolsCalling.map((toolCalling) => this.executors.call_tool({
+ payload: { parentMessageId: payload.parentMessageId, toolCalling },
+ type: 'call_tool',
+ }, structuredClone(baseState), // Each tool starts from the same base state
+ context)));
+ const lastParentMessageId = results.at(-1).nextContext?.payload
+ ?.parentMessageId;
+ // Merge results
+ return this.mergeToolResults(results, baseState, lastParentMessageId);
+ }
+ /**
+ * Merge multiple tool execution results
+ */
+ mergeToolResults(results, baseState, lastParentMessageId) {
+ const newState = structuredClone(baseState);
+ const allEvents = [];
+ // Merge all tool messages in order
+ // Get the set of tool_call_ids that already exist in baseState to avoid duplicates
+ const existingToolCallIds = new Set(baseState.messages.filter((m) => m.role === 'tool').map((m) => m.tool_call_id));
+ for (const result of results) {
+ // Extract only NEW tool role messages (not already in baseState)
+ const toolMessages = result.newState.messages.filter((m) => m.role === 'tool' && !existingToolCallIds.has(m.tool_call_id));
+ newState.messages.push(...toolMessages);
+ // Merge events
+ allEvents.push(...result.events);
+ // Merge usage statistics (if available)
+ if (result.newState.usage && newState.usage) {
+ newState.usage.tools.totalCalls += result.newState.usage.tools.totalCalls;
+ newState.usage.tools.totalTimeMs += result.newState.usage.tools.totalTimeMs;
+ // Merge per-tool statistics (now using array)
+ result.newState.usage.tools.byTool.forEach((toolStats) => {
+ const existingTool = newState.usage.tools.byTool.find((t) => t.name === toolStats.name);
+ if (existingTool) {
+ existingTool.calls += toolStats.calls;
+ existingTool.totalTimeMs += toolStats.totalTimeMs;
+ existingTool.errors += toolStats.errors || 0;
+ }
+ else {
+ newState.usage.tools.byTool.push({ ...toolStats });
+ }
+ });
+ }
+ // Merge cost statistics (if available)
+ if (result.newState.cost && newState.cost) {
+ newState.cost.tools.total += result.newState.cost.tools.total;
+ newState.cost.total += result.newState.cost.tools.total;
+ // Merge per-tool cost statistics (now using array)
+ result.newState.cost.tools.byTool.forEach((toolCost) => {
+ const existingToolCost = newState.cost.tools.byTool.find((t) => t.name === toolCost.name);
+ if (existingToolCost) {
+ existingToolCost.calls += toolCost.calls;
+ existingToolCost.totalCost += toolCost.totalCost;
+ }
+ else {
+ newState.cost.tools.byTool.push({ ...toolCost });
+ }
+ });
+ }
+ }
+ newState.lastModified = new Date().toISOString();
+ return {
+ events: allEvents,
+ newState,
+ nextContext: {
+ operationId: this.operationId,
+ payload: {
+ parentMessageId: lastParentMessageId,
+ toolCount: results.length,
+ toolResults: results.map((r) => r.nextContext?.payload),
+ },
+ phase: 'tools_batch_result',
+ session: this.createSessionContext(newState),
+ },
+ };
+ }
+ /**
+ * Handle cost limit exceeded scenario
+ */
+ handleCostLimitExceeded(state) {
+ const newState = structuredClone(state);
+ const costLimit = newState.costLimit;
+ switch (costLimit.onExceeded) {
+ case 'stop': {
+ newState.status = 'done';
+ const finishEvent = {
+ finalState: newState,
+ reason: 'cost_limit_exceeded',
+ reasonDetail: `Cost limit exceeded: ${newState.cost.total} ${newState.cost.currency} > ${costLimit.maxTotalCost} ${costLimit.currency}`,
+ type: 'done',
+ };
+ return {
+ events: [finishEvent],
+ newState,
+ nextContext: undefined,
+ };
+ }
+ case 'interrupt': {
+ return {
+ ...this.interrupt(newState, `Cost limit exceeded: ${newState.cost.total} ${newState.cost.currency}`, true, {
+ costExceeded: true,
+ currentCost: newState.cost.total,
+ limitCost: costLimit.maxTotalCost,
+ }),
+ nextContext: undefined,
+ };
+ }
+ default: {
+ // Continue execution but emit warning event
+ const warningEvent = {
+ error: new Error(`Warning: Cost limit exceeded: ${newState.cost.total} ${newState.cost.currency}`),
+ type: 'error',
+ };
+ return {
+ events: [warningEvent],
+ newState,
+ nextContext: {
+ operationId: this.operationId,
+ payload: { error: warningEvent.error, isCostWarning: true },
+ phase: 'error',
+ session: this.createSessionContext(newState),
+ },
+ };
+ }
+ }
+ }
+ /**
+ * Create session context metadata - reusable helper
+ * Note: Uses sessionId in context for backwards compatibility with AgentRuntimeContext
+ */
+ createSessionContext(state) {
+ return {
+ messageCount: state.messages.length,
+ sessionId: state.operationId,
+ status: state.status,
+ stepCount: state.stepCount,
+ };
+ }
+ /**
+ * Create initial context for the first step (fallback for backward compatibility)
+ */
+ createInitialContext(state) {
+ const lastMessage = state.messages.at(-1);
+ if (lastMessage?.role === 'user') {
+ return {
+ operationId: this.operationId,
+ payload: {
+ isFirstMessage: state.messages.length === 1,
+ message: lastMessage,
+ },
+ phase: 'user_input',
+ session: this.createSessionContext(state),
+ };
+ }
+ return {
+ operationId: this.operationId,
+ payload: undefined,
+ phase: 'init',
+ session: this.createSessionContext(state),
+ };
+ }
+ /** Create error state and events */
+ createErrorResult(state, error) {
+ const errorState = structuredClone(state);
+ errorState.status = 'error';
+ errorState.error = error;
+ errorState.lastModified = new Date().toISOString();
+ const errorEvent = { error, type: 'error' };
+ return {
+ events: [errorEvent],
+ newState: errorState,
+ };
+ }
+}
diff --git a/packages/agent-runtime/src/core/spendGuardPipeline.d.ts b/packages/agent-runtime/src/core/spendGuardPipeline.d.ts
new file mode 100644
index 000000000..ef1f1be08
--- /dev/null
+++ b/packages/agent-runtime/src/core/spendGuardPipeline.d.ts
@@ -0,0 +1,48 @@
+/**
+ * spendGuardPipeline - glue between {@link SpendGuard} and {@link TransactionPipeline}.
+ *
+ * Keeps the two decoupled: the pipeline exposes generic `preflight` / `onStepExecuted` hooks,
+ * and this module adapts a `SpendGuard` to them. Wire it once when constructing the pipeline:
+ *
+ * ```ts
+ * const guard = new SpendGuard(await spendLimitModel.findByAgent(agentId));
+ * const base = { agentId, userId, balanceUsd };
+ * const pipeline = new TransactionPipeline({
+ * preflight: createSpendPreflight(guard, base),
+ * onStepExecuted: createSpendRecorder(guard, base),
+ * });
+ * ```
+ *
+ * Registered alongside `DeFiGuard`, this enforces the quantitative envelope (per-tx max,
+ * rolling/daily caps, reserve floor) and the token/target firewall on every mutating step.
+ */
+import type { SpendGuard, SpendTx } from './SpendGuard.js';
+import type { PlanStep } from './toolRegistry.js';
+import type { PipelinePreflight, StepResult } from './TransactionPipeline.js';
+/** Per-run context the pipeline can't derive from a `PlanStep` alone. */
+export interface SpendContext {
+ agentId: string;
+ userId?: string;
+ /** Current agent wallet balance (USD) - required to enforce the reserve floor. */
+ balanceUsd?: number;
+}
+/**
+ * Build a {@link SpendTx} from a plan step, or `null` if the step is not value-moving
+ * (simulation / read-only / inflow actions are not spend-guarded).
+ *
+ * Note: a value-moving step is always resolved even when no USD amount is parseable - the
+ * resulting `valueUsd: 0` passes the caps harmlessly but keeps the **firewall** in force, so a
+ * deny-listed token/destination can never slip through on an unparseable amount.
+ */
+export declare function spendTxFromStep(step: PlanStep, ctx: SpendContext): SpendTx | null;
+/**
+ * Create a pipeline `preflight` that gates every value-moving step through the spend envelope.
+ * Steps that move no value pass through untouched.
+ */
+export declare function createSpendPreflight(guard: SpendGuard, ctx: SpendContext, resolve?: (step: PlanStep, ctx: SpendContext) => SpendTx | null): PipelinePreflight;
+/**
+ * Create a pipeline `onStepExecuted` hook that records confirmed outflow back into the guard's
+ * rolling/daily windows, so caps stay live across the steps of a multi-step plan. Only
+ * successfully-completed, value-moving steps are recorded.
+ */
+export declare function createSpendRecorder(guard: SpendGuard, ctx: SpendContext, resolve?: (step: PlanStep, ctx: SpendContext) => SpendTx | null): (step: PlanStep, result: StepResult) => void;
diff --git a/packages/agent-runtime/src/core/spendGuardPipeline.js b/packages/agent-runtime/src/core/spendGuardPipeline.js
new file mode 100644
index 000000000..ad2a7d6d5
--- /dev/null
+++ b/packages/agent-runtime/src/core/spendGuardPipeline.js
@@ -0,0 +1,115 @@
+/**
+ * spendGuardPipeline - glue between {@link SpendGuard} and {@link TransactionPipeline}.
+ *
+ * Keeps the two decoupled: the pipeline exposes generic `preflight` / `onStepExecuted` hooks,
+ * and this module adapts a `SpendGuard` to them. Wire it once when constructing the pipeline:
+ *
+ * ```ts
+ * const guard = new SpendGuard(await spendLimitModel.findByAgent(agentId));
+ * const base = { agentId, userId, balanceUsd };
+ * const pipeline = new TransactionPipeline({
+ * preflight: createSpendPreflight(guard, base),
+ * onStepExecuted: createSpendRecorder(guard, base),
+ * });
+ * ```
+ *
+ * Registered alongside `DeFiGuard`, this enforces the quantitative envelope (per-tx max,
+ * rolling/daily caps, reserve floor) and the token/target firewall on every mutating step.
+ */
+/**
+ * DeFi actions whose steps move value OUT of the agent wallet (or grant an allowance).
+ * Matched against the real `DeFiAction` union - inflow/neutral actions (withdraw, unstake,
+ * claim, borrow, remove_liquidity, redeem, revoke_approval, simulate) are intentionally
+ * excluded so a user reclaiming their own funds never trips a spend cap. `approve` is included
+ * because the firewall must gate *who* the agent grants an allowance to, even though the approve
+ * itself carries no USD amount. Any NEW value-moving `DeFiAction` must be added here.
+ */
+const VALUE_MOVING_ACTIONS = new Set([
+ 'swap',
+ 'bridge',
+ 'deposit',
+ 'stake',
+ 'add_liquidity',
+ 'repay',
+ 'mint',
+ 'create_dca',
+ 'create_limit_order',
+ 'approve',
+]);
+/** Argument keys that carry the USD value of a step (widest-first). */
+const VALUE_KEYS = ['valueUsd', 'amountUsd', 'value', 'amount', 'positionValue', 'totalValue'];
+/** Argument keys that carry the moving token. */
+const TOKEN_KEYS = ['token', 'fromToken', 'asset', 'symbol', 'tokenIn'];
+/** Argument keys that carry the destination address. */
+const DEST_KEYS = ['destination', 'recipient', 'to', 'toAddress', 'target', 'spender'];
+function firstNumber(args, keys) {
+ for (const key of keys) {
+ const val = args[key];
+ if (typeof val === 'number' && val > 0)
+ return val;
+ if (typeof val === 'string') {
+ const parsed = Number.parseFloat(val.replace(/[,$]/g, ''));
+ if (!Number.isNaN(parsed) && parsed > 0)
+ return parsed;
+ }
+ }
+ return 0;
+}
+function firstString(args, keys) {
+ for (const key of keys) {
+ const val = args[key];
+ if (typeof val === 'string' && val.length > 0)
+ return val;
+ }
+ return undefined;
+}
+/**
+ * Build a {@link SpendTx} from a plan step, or `null` if the step is not value-moving
+ * (simulation / read-only / inflow actions are not spend-guarded).
+ *
+ * Note: a value-moving step is always resolved even when no USD amount is parseable - the
+ * resulting `valueUsd: 0` passes the caps harmlessly but keeps the **firewall** in force, so a
+ * deny-listed token/destination can never slip through on an unparseable amount.
+ */
+export function spendTxFromStep(step, ctx) {
+ if (step.isSimulation)
+ return null;
+ if (!VALUE_MOVING_ACTIONS.has(step.action))
+ return null;
+ return {
+ agentId: ctx.agentId,
+ balanceUsd: ctx.balanceUsd,
+ destination: firstString(step.args, DEST_KEYS),
+ token: firstString(step.args, TOKEN_KEYS),
+ userId: ctx.userId,
+ valueUsd: firstNumber(step.args, VALUE_KEYS),
+ };
+}
+/**
+ * Create a pipeline `preflight` that gates every value-moving step through the spend envelope.
+ * Steps that move no value pass through untouched.
+ */
+export function createSpendPreflight(guard, ctx, resolve = spendTxFromStep) {
+ return (step) => {
+ const tx = resolve(step, ctx);
+ if (!tx)
+ return { allowed: true };
+ const result = guard.check(tx);
+ return { allowed: result.allowed, code: result.code, reason: result.reason };
+ };
+}
+/**
+ * Create a pipeline `onStepExecuted` hook that records confirmed outflow back into the guard's
+ * rolling/daily windows, so caps stay live across the steps of a multi-step plan. Only
+ * successfully-completed, value-moving steps are recorded.
+ */
+export function createSpendRecorder(guard, ctx, resolve = spendTxFromStep) {
+ return (step, result) => {
+ if (result.status !== 'completed')
+ return;
+ const tx = resolve(step, ctx);
+ if (!tx)
+ return;
+ guard.recordSpend(tx.agentId, tx.valueUsd);
+ };
+}
diff --git a/packages/agent-runtime/src/core/toolRegistry.d.ts b/packages/agent-runtime/src/core/toolRegistry.d.ts
new file mode 100644
index 000000000..48c36476d
--- /dev/null
+++ b/packages/agent-runtime/src/core/toolRegistry.d.ts
@@ -0,0 +1,192 @@
+/**
+ * Fund-moving tool registry + the domain-guard contract.
+ *
+ * The upstream runtime hardwired these registries to its own tool catalog and
+ * shipped a concrete EVM DeFi guard. Here the registries are seeded with the
+ * three.ws tool surface (Solana first) and the guard is only a contract: any
+ * object implementing {@link DeFiGuard} can occupy the `defi_guard` layer of
+ * the GuardChain, so the platform can wire its own trade/risk analysis without
+ * this package knowing about chains at all.
+ *
+ * Both Sets are intentionally mutable: a host installing a new fund-moving
+ * tool registers it at boot via {@link registerMutatingApi} /
+ * {@link registerFundMovingTool}. An unregistered fund-moving tool is not
+ * "unguarded by design", it is a blind spot, and GuardChain reports it as one.
+ */
+/**
+ * API names that mutate on-chain state. Checked against the `apiName` of a
+ * tool call. Generic action names cover manifest-style tools; the exact names
+ * cover the three.ws chat tool registry.
+ */
+export declare const MUTATING_APIS: Set<string>;
+/**
+ * Tool identifiers whose calls a wired domain guard should analyze. In the
+ * three.ws chat registry tools are flat, so the identifier equals the API
+ * name; manifest-style hosts register their package identifiers instead.
+ */
+export declare const DEFI_TOOL_IDENTIFIERS: Set<string>;
+/** Register an additional mutating API name at host boot. */
+export declare function registerMutatingApi(apiName: string): void;
+/** Register an additional fund-moving tool identifier at host boot. */
+export declare function registerFundMovingTool(identifier: string): void;
+/** Audit standing of a protocol, as resolved by the host's registry. */
+export type AuditStatus = 'audited' | 'unaudited' | 'unknown';
+/** One position in the agent's portfolio, supplied by the host for risk context. */
+export interface PortfolioPosition {
+ /** Token symbol. */
+ token: string;
+ /** USD value of the position. */
+ valueUsd: number;
+ /** Chain the position is on (e.g. `solana`, `base`). */
+ chain: string;
+ /** Protocol where it is deployed; omit for plain wallet holdings. */
+ protocol?: string;
+ type: 'wallet' | 'lending_supply' | 'lending_borrow' | 'lp' | 'staking' | 'vault' | 'farm';
+ /** For lending: health factor (1.0 = liquidation threshold). */
+ healthFactor?: number;
+ /** For lending: liquidation threshold as a ratio (e.g. 0.825 for 82.5%). */
+ liquidationThreshold?: number;
+ /** For LP positions: pair legs and entry-vs-current price ratio. */
+ lpTokens?: {
+ tokenA: string;
+ tokenB: string;
+ priceRatioEntry: number;
+ priceRatioCurrent: number;
+ };
+ /** Annualized yield. */
+ apy?: number;
+ protocolTvl?: number;
+ isAudited?: boolean;
+ protocolAgeDays?: number;
+ /** Outstanding token approvals, from on-chain scanning. */
+ approvals?: TokenApproval[];
+}
+/** One outstanding token approval. */
+export interface TokenApproval {
+ token: string;
+ spender: string;
+ /** Approved amount; string for uint256-scale values. */
+ amount?: string | number;
+ unlimited?: boolean;
+}
+/** Per-user transaction caps resolved server-side by the host. */
+export interface UserSwapCaps {
+ /** Maximum USD value per single transaction. */
+ perTxUsdCap: number;
+ /** Maximum cumulative USD in any rolling 24-hour window. */
+ perDayUsdCap: number;
+ /** Maximum cumulative USD in any rolling 7-day window. */
+ perWeekUsdCap: number;
+ /** Whether all swaps must use a private mempool / protected route. */
+ privateMempoolRequired?: boolean;
+}
+/** Confirmed swap volume windows resolved from execution receipts. */
+export interface UserSwapVolume {
+ last24hUsd: number;
+ last7dUsd: number;
+}
+/** The verdict a domain guard returns for one analyzed call. */
+export interface GuardAnalysis {
+ /** Whether this was a registered tool that got analyzed. */
+ isDeFi: boolean;
+ /** Whether the API is a mutating (on-chain) operation. */
+ isMutating: boolean;
+ /** Risk analysis payload, in whatever shape the host's analyzer produces. */
+ riskReport?: Record<string, unknown>;
+ /** MEV / sandwich-exposure payload, host-defined shape. */
+ mevAssessment?: Record<string, unknown>;
+ decision: 'allow' | 'require_approval' | 'block';
+ /** Human-readable reason for the decision. */
+ reason: string;
+ warnings: string[];
+ /** Recommended parameter adjustments (e.g. lower slippage). */
+ parameterAdjustments?: Record<string, unknown>;
+ analyzedAt: number;
+ /** Remaining daily volume allocation in USD, when rate-limited. */
+ remainingDailyVolumeUsd?: number;
+ protocolStatus?: AuditStatus;
+ /**
+ * Structured cap-breach code when a block came from a per-user cap:
+ * `CAP_PER_TX` single tx over the per-tx cap, `CAP_DAILY` would exceed the
+ * 24-hour window, `CAP_WEEKLY` would exceed the 7-day window.
+ */
+ capCode?: 'CAP_PER_TX' | 'CAP_DAILY' | 'CAP_WEEKLY';
+}
+/** A domain guard's full return value. */
+export interface GuardResult {
+ analysis: GuardAnalysis;
+ /** MEV-protected argument adjustments to apply before execution. */
+ modifiedArguments?: Record<string, unknown>;
+}
+/** The request a domain guard analyzes. */
+export interface GuardAnalyzeRequest {
+ apiName: string;
+ arguments: Record<string, unknown>;
+ chainId?: number;
+ identifier: string;
+ portfolioPositions?: PortfolioPosition[];
+ protocol?: string;
+ userId?: string;
+ userSwapCaps?: UserSwapCaps;
+ userSwapVolume?: UserSwapVolume;
+ userTier?: string;
+ valueUsd?: number;
+}
+/**
+ * The domain-guard contract for the GuardChain's `defi_guard` layer. three.ws
+ * wires its own implementation (Solana trade limits, pump.fun heuristics);
+ * any object with these three methods qualifies.
+ */
+export interface DeFiGuard {
+ /** Whether calls to this tool identifier should be analyzed at all. */
+ isDeFiTool(identifier: string): boolean;
+ /** Whether this API name mutates on-chain state. */
+ isMutatingApi(apiName: string): boolean;
+ analyze(request: GuardAnalyzeRequest): Promise<GuardResult> | GuardResult;
+}
+/** One step of a multi-step execution plan. */
+export interface PlanStep {
+ id: string;
+ /** The action this step performs (e.g. `swap`, `bridge`, `approve`). */
+ action: string;
+ /** Which tool to invoke. */
+ toolIdentifier: string;
+ apiName: string;
+ args: Record<string, unknown>;
+ /** Steps that must complete before this one, by id. */
+ dependsOn: string[];
+ description: string;
+ /** Estimated gas cost in USD (0 for read-only). */
+ estimatedGasUsd: number;
+ riskLevel: 'low' | 'medium' | 'high' | 'critical';
+ requiresApproval: boolean;
+ /** Rollback action if this step fails. */
+ rollbackAction?: {
+ toolIdentifier: string;
+ apiName: string;
+ args: Record<string, unknown>;
+ description: string;
+ };
+ /** Whether this is a simulation / read-only step. */
+ isSimulation: boolean;
+}
+/** A parsed multi-step execution plan, produced by a host-side planner. */
+export interface DeFiPlan {
+ id: string;
+ /** Original user intent, verbatim. */
+ originalIntent: string;
+ /** Parsed intent category, host-defined. */
+ category: string;
+ /** Ordered steps, respecting the dependency graph. */
+ steps: PlanStep[];
+ riskLevel: 'low' | 'medium' | 'high' | 'critical';
+ totalEstimatedGasUsd: number;
+ /** Whether the plan requires any wallet interaction. */
+ requiresWallet: boolean;
+ chains: string[];
+ tokens: string[];
+ /** How well the planner understood the intent (0-1). */
+ confidence: number;
+ warnings: string[];
+ createdAt: string;
+}
diff --git a/packages/agent-runtime/src/core/toolRegistry.js b/packages/agent-runtime/src/core/toolRegistry.js
new file mode 100644
index 000000000..023a8225e
--- /dev/null
+++ b/packages/agent-runtime/src/core/toolRegistry.js
@@ -0,0 +1,89 @@
+/**
+ * Fund-moving tool registry + the domain-guard contract.
+ *
+ * The upstream runtime hardwired these registries to its own tool catalog and
+ * shipped a concrete EVM DeFi guard. Here the registries are seeded with the
+ * three.ws tool surface (Solana first) and the guard is only a contract: any
+ * object implementing {@link DeFiGuard} can occupy the `defi_guard` layer of
+ * the GuardChain, so the platform can wire its own trade/risk analysis without
+ * this package knowing about chains at all.
+ *
+ * Both Sets are intentionally mutable: a host installing a new fund-moving
+ * tool registers it at boot via {@link registerMutatingApi} /
+ * {@link registerFundMovingTool}. An unregistered fund-moving tool is not
+ * "unguarded by design", it is a blind spot, and GuardChain reports it as one.
+ */
+/**
+ * API names that mutate on-chain state. Checked against the `apiName` of a
+ * tool call. Generic action names cover manifest-style tools; the exact names
+ * cover the three.ws chat tool registry.
+ */
+export const MUTATING_APIS = new Set([
+ // Generic action names
+ 'executeSwap',
+ 'executeTrade',
+ 'createDCA',
+ 'cancelDCA',
+ 'createLimitOrder',
+ 'cancelLimitOrder',
+ 'supply',
+ 'borrow',
+ 'repay',
+ 'withdraw',
+ 'deposit',
+ 'stake',
+ 'unstake',
+ 'approve',
+ 'revoke',
+ 'revokeApproval',
+ 'revokeAllApprovals',
+ 'bridge',
+ 'bridgeTokens',
+ 'executeBridge',
+ 'mint',
+ 'redeem',
+ 'addLiquidity',
+ 'removeLiquidity',
+ 'claimRewards',
+ 'sendPayment',
+ 'placeOrder',
+ 'cancelOrder',
+ // three.ws chat tools (identifier == apiName in the flat registry)
+ 'solana_transfer',
+ 'solana_swap',
+ 'evm_transfer',
+ 'evm_swap',
+ 'pumpfunBuy',
+ 'pumpfunSell',
+ 'pumpfunSellAll',
+ 'LaunchPumpToken',
+ 'MintScene',
+ 'agentPaymentsDistribute',
+ 'agentPaymentsWithdraw',
+]);
+/**
+ * Tool identifiers whose calls a wired domain guard should analyze. In the
+ * three.ws chat registry tools are flat, so the identifier equals the API
+ * name; manifest-style hosts register their package identifiers instead.
+ */
+export const DEFI_TOOL_IDENTIFIERS = new Set([
+ 'solana_transfer',
+ 'solana_swap',
+ 'evm_transfer',
+ 'evm_swap',
+ 'pumpfunBuy',
+ 'pumpfunSell',
+ 'pumpfunSellAll',
+ 'LaunchPumpToken',
+ 'MintScene',
+ 'agentPaymentsDistribute',
+ 'agentPaymentsWithdraw',
+]);
+/** Register an additional mutating API name at host boot. */
+export function registerMutatingApi(apiName) {
+ MUTATING_APIS.add(apiName);
+}
+/** Register an additional fund-moving tool identifier at host boot. */
+export function registerFundMovingTool(identifier) {
+ DEFI_TOOL_IDENTIFIERS.add(identifier);
+}
diff --git a/packages/agent-runtime/src/index.d.ts b/packages/agent-runtime/src/index.d.ts
new file mode 100644
index 000000000..959b0e95a
--- /dev/null
+++ b/packages/agent-runtime/src/index.d.ts
@@ -0,0 +1,4 @@
+export * from './agents/index.js';
+export * from './core/index.js';
+export * from './types/index.js';
+export * from './utils/index.js';
diff --git a/packages/agent-runtime/src/index.js b/packages/agent-runtime/src/index.js
new file mode 100644
index 000000000..959b0e95a
--- /dev/null
+++ b/packages/agent-runtime/src/index.js
@@ -0,0 +1,4 @@
+export * from './agents/index.js';
+export * from './core/index.js';
+export * from './types/index.js';
+export * from './utils/index.js';
diff --git a/packages/agent-runtime/src/types/event.d.ts b/packages/agent-runtime/src/types/event.d.ts
new file mode 100644
index 000000000..2e1efedbe
--- /dev/null
+++ b/packages/agent-runtime/src/types/event.d.ts
@@ -0,0 +1,90 @@
+import { ChatToolPayload } from './vendor.js';
+import type { AgentState, ToolsCalling } from './state.js';
+export interface AgentEventInit {
+ type: 'init';
+}
+export interface AgentEventLlmStart {
+ type: 'llm_start';
+ payload: unknown;
+}
+export interface AgentEventLlmStream {
+ type: 'llm_stream';
+ chunk: unknown;
+}
+export interface AgentEventLlmResult {
+ type: 'llm_result';
+ result: unknown;
+}
+export interface AgentEventToolPending {
+ type: 'tool_pending';
+ toolCalls: ToolsCalling[];
+}
+export interface AgentEventToolResult {
+ type: 'tool_result';
+ id: string;
+ result: any;
+}
+export interface AgentEventHumanApproveRequired {
+ type: 'human_approve_required';
+ pendingToolsCalling: ChatToolPayload[];
+ operationId: string;
+}
+export interface AgentEventHumanPromptRequired {
+ type: 'human_prompt_required';
+ metadata?: Record<string, unknown>;
+ prompt: string;
+ operationId: string;
+}
+export interface AgentEventHumanSelectRequired {
+ type: 'human_select_required';
+ metadata?: Record<string, unknown>;
+ multi?: boolean;
+ options: {
+ label: string;
+ value: string;
+ }[];
+ prompt?: string;
+ operationId: string;
+}
+/**
+ * Standardized finish reasons
+ */
+export type FinishReason = 'completed' | 'user_requested' | 'user_aborted' | 'max_steps_exceeded' | 'cost_limit_exceeded' | 'timeout' | 'agent_decision' | 'error_recovery' | 'system_shutdown';
+export interface AgentEventDone {
+ type: 'done';
+ finalState: AgentState;
+ reason: FinishReason;
+ reasonDetail?: string;
+}
+export interface AgentEventError {
+ type: 'error';
+ error: any;
+}
+export interface AgentEventInterrupted {
+ type: 'interrupted';
+ reason: string;
+ interruptedAt: string;
+ interruptedInstruction?: any;
+ canResume: boolean;
+ metadata?: Record<string, unknown>;
+}
+export interface AgentEventResumed {
+ type: 'resumed';
+ reason: string;
+ resumedAt: string;
+ resumedFromStep: number;
+ metadata?: Record<string, unknown>;
+}
+export interface AgentEventCompressionComplete {
+ type: 'compression_complete';
+ groupId: string;
+ parentMessageId?: string;
+}
+export interface AgentEventCompressionError {
+ type: 'compression_error';
+ error: unknown;
+}
+/**
+ * Events emitted by the AgentRuntime during execution
+ */
+export type AgentEvent = AgentEventInit | AgentEventLlmStart | AgentEventLlmStream | AgentEventLlmResult | AgentEventToolPending | AgentEventToolResult | AgentEventDone | AgentEventError | AgentEventHumanApproveRequired | AgentEventHumanPromptRequired | AgentEventHumanSelectRequired | AgentEventInterrupted | AgentEventResumed | AgentEventCompressionComplete | AgentEventCompressionError;
diff --git a/packages/agent-runtime/src/types/event.js b/packages/agent-runtime/src/types/event.js
new file mode 100644
index 000000000..cb0ff5c3b
--- /dev/null
+++ b/packages/agent-runtime/src/types/event.js
@@ -0,0 +1 @@
+export {};
diff --git a/packages/agent-runtime/src/types/exit.d.ts b/packages/agent-runtime/src/types/exit.d.ts
new file mode 100644
index 000000000..ed97f4e7c
--- /dev/null
+++ b/packages/agent-runtime/src/types/exit.d.ts
@@ -0,0 +1,97 @@
+/** Why a position closed, in the engine's fixed priority order. `take_initials`
+ * is the laddered partial-exit reason (only `decideLadderedExit` returns it). */
+export type ExitReason = 'stop_loss' | 'signal_flip' | 'trailing_stop' | 'take_profit' | 'take_initials' | 'timeout';
+/**
+ * An external sentiment read that can trigger an early `signal_flip` exit. The
+ * hook shape is portable; the *source* is three.ws's own intel (news-sentinel /
+ * risk intel), not three.ws x402. Pass `null`/omit to disable signal_flip so a
+ * replay is byte-for-byte deterministic.
+ */
+export interface ExitSentiment {
+ /** Confidence of the read in [0, 1]. */
+ confidence?: number | null;
+ /** Confidence floor the read must clear to act on. Defaults to 0.7. */
+ minConfidence?: number;
+ /** Directional signal. Only `'bearish'` can trigger an exit. */
+ signal?: string;
+}
+/**
+ * The minimal position shape the exit engine needs. All percentages are plain
+ * numbers (e.g. `15` = 15%); `null`/`undefined` means **disabled**, not `0` -
+ * the null guard is load-bearing (`Number(null) === 0` would fire a missing
+ * take-profit immediately). Ladder fields are optional; when
+ * `initialsOutMultiple` is unset the laddered decider is byte-for-byte the
+ * classic full-exit behavior.
+ */
+export interface ExitEvaluablePosition {
+ /** Entry cost basis in the quote asset's smallest unit (wei on EVM). */
+ entryQuoteWei: bigint;
+ /** Whether the initial cost basis has already been banked (ladder state). */
+ initialsRecovered?: boolean;
+ /** Take-initials multiple (× entry) that arms the first partial exit; must be > 1. */
+ initialsOutMultiple?: number | null;
+ /** Max time to hold, in seconds, before a `timeout` exit. */
+ maxHoldSeconds?: number | null;
+ /** Moon-bag floor as a percent that must always ride past the take-initials event. Default 15. */
+ moonbagMinPct?: number | null;
+ /** Epoch milliseconds the position was opened; used with the injected clock for timeout. */
+ openedAt: number;
+ /** Hard stop-loss as a percent below entry. Always wins on conflict. */
+ stopLossPct?: number | null;
+ /** Take-profit as a percent above entry. */
+ takeProfitPct?: number | null;
+ /** Trailing stop as a percent drawdown from the high-water mark. */
+ trailingStopPct?: number | null;
+}
+/** A laddered exit: the reason and what fraction of the CURRENT remaining
+ * position to sell (0-1). `recoversInitials` marks the one-time take-initials
+ * event so the caller can flip `initialsRecovered`. */
+export interface LadderedExitDecision {
+ reason: ExitReason;
+ /** True only on the take-initials event that banks the cost basis. */
+ recoversInitials?: boolean;
+ /** Fraction of the remaining position to sell, in (0, 1]. */
+ sellFraction: number;
+}
+/**
+ * One recorded observation of an open position's value. `value`/`quote` are the
+ * position's current worth in the entry quote asset's wei; `at` is the epoch-ms
+ * clock injected as `now` when this point is evaluated. `sentiment` is optional
+ * and only matters for the `signal_flip` hook.
+ */
+export interface PricePoint {
+ /** Epoch ms of the observation - injected as the engine's `now`. */
+ at: number;
+ /** Position value at this point, in entry-quote wei. */
+ value: bigint;
+ /** Optional sentiment read for the `signal_flip` early cut. */
+ sentiment?: ExitSentiment | null;
+}
+/** A partial (laddered) sale recorded during a backtest replay. */
+export interface BacktestLadderEvent {
+ /** Epoch ms the partial fired. */
+ at: number;
+ /** Why it fired - `take_initials` for the moon-bag bank. */
+ reason: ExitReason;
+ /** Fraction of the ORIGINAL position sold at this event, in (0, 1). */
+ fractionOfOriginal: number;
+ /** Position value the partial executed at, in wei. */
+ value: bigint;
+}
+/**
+ * Outcome of replaying a strategy over `PricePoint[]`. A `null` `exitReason`
+ * means the position was still open at the final point (moon bag riding); its
+ * P&L is then marked to the last observed value.
+ */
+export interface BacktestResult {
+ /** Terminal exit reason, or `null` if still open at the end of the series. */
+ exitReason: ExitReason | null;
+ /** Value the terminal exit resolved at (wei), or `null` if still open. */
+ exitValue: bigint | null;
+ /** Seconds held from entry to the terminal exit (or to the last point if open). */
+ holdSeconds: number;
+ /** Net P&L as a percentage of entry, blending realized partials + open moon bag. */
+ pnlPct: number;
+ /** Partial (laddered) sales in the order they fired. */
+ ladder: BacktestLadderEvent[];
+}
diff --git a/packages/agent-runtime/src/types/exit.js b/packages/agent-runtime/src/types/exit.js
new file mode 100644
index 000000000..f7fc15c3f
--- /dev/null
+++ b/packages/agent-runtime/src/types/exit.js
@@ -0,0 +1,9 @@
+// Exit-decision types - the position shape and sentiment read consumed by the
+// pure ExitDecisionEngine (`packages/agent-runtime/src/core/ExitDecisionEngine.ts`).
+//
+// Ported from three.ws `workers/agent-sniper/exit-logic.js`. The Solana original
+// worked in lamports; three.ws is EVM-first, so entry/value/peak are `bigint`
+// wei. Ratio comparisons are done in float64 internally - safe because a
+// stop/take-profit threshold is a *relative* comparison, where float64 error
+// (~1e-16) is far below any percentage a strategy would set.
+export {};
diff --git a/packages/agent-runtime/src/types/generalAgent.d.ts b/packages/agent-runtime/src/types/generalAgent.d.ts
new file mode 100644
index 000000000..1577de8d9
--- /dev/null
+++ b/packages/agent-runtime/src/types/generalAgent.d.ts
@@ -0,0 +1,108 @@
+import { ChatToolPayload, MessageToolCall } from './vendor.js';
+import type { DeFiGuard } from '../core/toolRegistry.js';
+export interface GeneralAgentCallLLMInstructionPayload {
+ /** Force create a new assistant message (e.g., after compression) */
+ createAssistantMessage?: boolean;
+ isFirstMessage?: boolean;
+ messages: any[];
+ model: string;
+ parentMessageId?: string;
+ provider: string;
+ tools: any[];
+}
+export interface GeneralAgentCallLLMResultPayload {
+ hasToolsCalling: boolean;
+ parentMessageId: string;
+ result: {
+ content: string;
+ tool_calls: MessageToolCall[];
+ };
+ toolsCalling: ChatToolPayload[];
+}
+export interface GeneralAgentCallingToolInstructionPayload {
+ parentMessageId: string;
+ skipCreateToolMessage?: boolean;
+ toolCalling: ChatToolPayload;
+}
+export interface GeneralAgentCallToolResultPayload {
+ data: any;
+ executionTime: number;
+ isSuccess: boolean;
+ parentMessageId: string;
+ /** Whether tool requested to stop execution (e.g., group management speak/delegate, GTD async tasks) */
+ stop?: boolean;
+ toolCall: ChatToolPayload;
+ toolCallId: string;
+}
+export interface GeneralAgentCallToolsBatchInstructionPayload {
+ parentMessageId: string;
+ toolsCalling: ChatToolPayload[];
+}
+export interface GeneralAgentCallToolsBatchResultPayload {
+ parentMessageId: string;
+ toolCount: number;
+ toolResults: GeneralAgentCallToolResultPayload[];
+}
+export interface GeneralAgentHumanAbortPayload {
+ /** Whether there are pending tool calls */
+ hasToolsCalling?: boolean;
+ /** Parent message ID (assistant message) */
+ parentMessageId: string;
+ /** Reason for the abort */
+ reason: string;
+ /** LLM result including content and tool_calls */
+ result?: {
+ content: string;
+ tool_calls?: any[];
+ };
+ /** Pending tool calls that need to be cancelled */
+ toolsCalling?: ChatToolPayload[];
+}
+export interface GeneralAgentConfig {
+ agentConfig?: {
+ [key: string]: any;
+ maxSteps?: number;
+ };
+ /**
+ * Context compression configuration
+ * When enabled and triggered, ALL messages are compressed into a single MessageGroup summary.
+ */
+ compressionConfig?: {
+ /** Whether context compression is enabled (default: true) */
+ enabled?: boolean;
+ /** Model's max context window token count (default: 128k) */
+ maxWindowToken?: number;
+ };
+ /**
+ * DeFi Guard configuration for risk/MEV analysis.
+ * Overrides default thresholds for blocking, approval, and auto-execute limits.
+ */
+ domainGuard?: DeFiGuard;
+ modelRuntimeConfig?: {
+ /**
+ * Compression model configuration
+ * Used for context compression tasks
+ */
+ compressionModel?: {
+ model: string;
+ provider: string;
+ };
+ model: string;
+ provider: string;
+ };
+ operationId: string;
+ userId?: string;
+}
+/**
+ * Payload for compression_result phase
+ */
+export interface GeneralAgentCompressionResultPayload {
+ /** Compressed messages (summary + pinned + recent) */
+ compressedMessages: any[];
+ /** Compression group ID in database */
+ groupId: string;
+ /** Parent message ID for subsequent LLM call (last assistant message before compression) */
+ parentMessageId?: string;
+ /** Whether compression was skipped (no messages to compress) */
+ skipped?: boolean;
+}
diff --git a/packages/agent-runtime/src/types/generalAgent.js b/packages/agent-runtime/src/types/generalAgent.js
new file mode 100644
index 000000000..cb0ff5c3b
--- /dev/null
+++ b/packages/agent-runtime/src/types/generalAgent.js
@@ -0,0 +1 @@
+export {};
diff --git a/packages/agent-runtime/src/types/index.d.ts b/packages/agent-runtime/src/types/index.d.ts
new file mode 100644
index 000000000..8806c6a92
--- /dev/null
+++ b/packages/agent-runtime/src/types/index.d.ts
@@ -0,0 +1,8 @@
+export * from './event.js';
+export * from './exit.js';
+export * from './generalAgent.js';
+export * from './instruction.js';
+export * from './runtime.js';
+export * from './state.js';
+export * from './usage.js';
+export * from './vendor.js';
diff --git a/packages/agent-runtime/src/types/index.js b/packages/agent-runtime/src/types/index.js
new file mode 100644
index 000000000..8806c6a92
--- /dev/null
+++ b/packages/agent-runtime/src/types/index.js
@@ -0,0 +1,8 @@
+export * from './event.js';
+export * from './exit.js';
+export * from './generalAgent.js';
+export * from './instruction.js';
+export * from './runtime.js';
+export * from './state.js';
+export * from './usage.js';
+export * from './vendor.js';
diff --git a/packages/agent-runtime/src/types/instruction.d.ts b/packages/agent-runtime/src/types/instruction.d.ts
new file mode 100644
index 000000000..5d43d3ccd
--- /dev/null
+++ b/packages/agent-runtime/src/types/instruction.d.ts
@@ -0,0 +1,300 @@
+import { ChatToolPayload, ModelUsage, RuntimeInitialContext, RuntimeStepContext } from './vendor.js';
+import type { FinishReason } from './event.js';
+import { AgentState, ToolRegistry } from './state.js';
+import type { Cost, CostCalculationContext, Usage } from './usage.js';
+/**
+ * Runtime execution context passed to Agent runner
+ */
+export interface AgentRuntimeContext {
+ /**
+ * Initial context captured at operation start
+ * Contains static state like initial page content that doesn't change during execution
+ * Set once during initialization and passed through to Context Engine
+ */
+ initialContext?: RuntimeInitialContext;
+ metadata?: Record<string, unknown>;
+ /** Operation ID (links to Operation for business context) */
+ operationId?: string;
+ /** Phase-specific payload/context */
+ payload?: unknown;
+ /** Current execution phase */
+ phase: 'init' | 'user_input' | 'llm_result' | 'tool_result' | 'tools_batch_result' | 'task_result' | 'tasks_batch_result' | 'human_response' | 'human_approved_tool' | 'human_abort' | 'compression_result' | 'error';
+ /** Session info (kept for backward compatibility, will be optional in the future) */
+ session?: {
+ messageCount: number;
+ sessionId: string;
+ status: AgentState['status'];
+ stepCount: number;
+ };
+ /**
+ * Step context computed at the beginning of each step
+ * Contains dynamic state like GTD todos that changes between steps
+ * Computed by AgentRuntime and passed to Context Engine and Tool Executors
+ */
+ stepContext?: RuntimeStepContext;
+ /** Usage statistics from the current step (if applicable) */
+ stepUsage?: ModelUsage | unknown;
+}
+/**
+ * Represents the "Brain" of an agent.
+ * It contains all the decision-making logic and is completely stateless.
+ */
+export interface Agent {
+ /**
+ * Calculate cost from usage statistics
+ * @param context - Cost calculation context with usage and limits
+ * @returns Updated cost information
+ */
+ calculateCost?(context: CostCalculationContext): Cost;
+ /**
+ * Calculate usage statistics from operation results
+ * @param operationType - Type of operation that was performed
+ * @param operationResult - Result data from the operation
+ * @param previousUsage - Previous usage statistics
+ * @returns Updated usage statistics
+ */
+ calculateUsage?(operationType: 'llm' | 'tool' | 'human_interaction', operationResult: any, previousUsage: Usage): Usage;
+ /** Optional custom executors mapping to extend runtime behaviors */
+ executors?: Partial<Record<AgentInstruction['type'], any>>;
+ /**
+ * Model runtime function for LLM calls - Agent owns its model integration
+ * @param payload - LLM call payload (messages, tools, etc.)
+ * @returns Async iterable of streaming response chunks
+ */
+ modelRuntime?: (payload: unknown) => AsyncIterable<any>;
+ /**
+ * The core runner method. Based on the current execution context and state,
+ * it decides what the next action should be.
+ * @param context - Current runtime context with phase and payload
+ * @param state - Complete agent state for reference
+ */
+ runner(context: AgentRuntimeContext, state: AgentState): Promise<AgentInstruction | AgentInstruction[]>;
+ /** Optional tools registry held by the agent */
+ tools?: ToolRegistry;
+}
+export interface CallLLMPayload {
+ assistantMessageId?: string;
+ isFirstMessage?: boolean;
+ messages: any[];
+ model: string;
+ parentId?: string;
+ parentMessageId?: string;
+ provider: string;
+ tools: any[];
+}
+export interface CallingToolPayload {
+ apiName: string;
+ arguments: string;
+ id: string;
+ identifier: string;
+ type: 'mcp' | 'default' | 'markdown' | 'standalone';
+}
+export interface HumanAbortPayload {
+ /** Whether there are pending tool calls */
+ hasToolsCalling?: boolean;
+ /** Parent message ID (assistant message) */
+ parentMessageId: string;
+ /** Reason for the abort */
+ reason: string;
+ /** LLM result including content and tool_calls */
+ result?: {
+ content: string;
+ tool_calls?: any[];
+ };
+ /** Pending tool calls that need to be cancelled */
+ toolsCalling?: ChatToolPayload[];
+}
+export interface AgentInstructionCallLlm {
+ payload: any;
+ type: 'call_llm';
+}
+export interface AgentInstructionCallTool {
+ payload: {
+ parentMessageId: string;
+ toolCalling: ChatToolPayload;
+ };
+ type: 'call_tool';
+}
+export interface AgentInstructionCallToolsBatch {
+ payload: {
+ parentMessageId: string;
+ toolsCalling: ChatToolPayload[];
+ } & any;
+ type: 'call_tools_batch';
+}
+export interface AgentInstructionRequestHumanPrompt {
+ metadata?: Record<string, unknown>;
+ prompt: string;
+ reason?: string;
+ type: 'request_human_prompt';
+}
+export interface AgentInstructionRequestHumanSelect {
+ metadata?: Record<string, unknown>;
+ multi?: boolean;
+ options: Array<{
+ label: string;
+ value: string;
+ }>;
+ prompt?: string;
+ reason?: string;
+ type: 'request_human_select';
+}
+export interface AgentInstructionRequestHumanApprove {
+ pendingToolsCalling: ChatToolPayload[];
+ reason?: string;
+ skipCreateToolMessage?: boolean;
+ type: 'request_human_approve';
+}
+export interface AgentInstructionFinish {
+ reason: FinishReason;
+ reasonDetail?: string;
+ type: 'finish';
+}
+export interface AgentInstructionResolveAbortedTools {
+ payload: {
+ /** Parent message ID (assistant message) */
+ parentMessageId: string;
+ /** Reason for the abort */
+ reason?: string;
+ /** Tool calls that need to be resolved/cancelled */
+ toolsCalling: ChatToolPayload[];
+ };
+ type: 'resolve_aborted_tools';
+}
+/**
+ * Instruction to execute context compression
+ * When triggered, compresses ALL messages into a single MessageGroup summary
+ */
+export interface AgentInstructionCompressContext {
+ payload: {
+ /** Current token count before compression */
+ currentTokenCount: number;
+ /** Existing summary to incorporate (for incremental compression) */
+ existingSummary?: string;
+ /** Messages to compress */
+ messages: any[];
+ };
+ type: 'compress_context';
+}
+/**
+ * Task definition for exec_tasks instruction
+ */
+export interface ExecTaskItem {
+ /** Brief description of what this task does (shown in UI) */
+ description: string;
+ /** Whether to inherit context messages from parent conversation */
+ inheritMessages?: boolean;
+ /** Detailed instruction/prompt for the task execution */
+ instruction: string;
+ /**
+ * Whether to execute the task on the client side (desktop only).
+ * When true and running on desktop, the task will be executed locally
+ * with access to local tools (file system, shell commands, etc.).
+ *
+ * IMPORTANT: This MUST be set to true when the task requires:
+ * - Reading/writing local files via `local-system` tool
+ * - Executing shell commands
+ * - Any other desktop-only local tool operations
+ *
+ * If not specified or false, the task runs on the server (default behavior).
+ * On non-desktop platforms (web), this flag is ignored and tasks always run on server.
+ */
+ runInClient?: boolean;
+ /** Timeout in milliseconds (optional, default 30 minutes) */
+ timeout?: number;
+}
+/**
+ * Instruction to execute a single async task (server-side)
+ */
+export interface AgentInstructionExecTask {
+ payload: {
+ /** Parent message ID (tool message that triggered the task) */
+ parentMessageId: string;
+ /** Task to execute */
+ task: ExecTaskItem;
+ };
+ type: 'exec_task';
+}
+/**
+ * Instruction to execute multiple async tasks in parallel (server-side)
+ */
+export interface AgentInstructionExecTasks {
+ payload: {
+ /** Parent message ID (tool message that triggered the tasks) */
+ parentMessageId: string;
+ /** Array of tasks to execute */
+ tasks: ExecTaskItem[];
+ };
+ type: 'exec_tasks';
+}
+/**
+ * Instruction to execute a single async task on the client (desktop only)
+ * Used when task requires local tools like file system or shell commands
+ */
+export interface AgentInstructionExecClientTask {
+ payload: {
+ /** Parent message ID (tool message that triggered the task) */
+ parentMessageId: string;
+ /** Task to execute */
+ task: ExecTaskItem;
+ };
+ type: 'exec_client_task';
+}
+/**
+ * Instruction to execute multiple async tasks on the client in parallel (desktop only)
+ * Used when tasks require local tools like file system or shell commands
+ */
+export interface AgentInstructionExecClientTasks {
+ payload: {
+ /** Parent message ID (tool message that triggered the tasks) */
+ parentMessageId: string;
+ /** Array of tasks to execute */
+ tasks: ExecTaskItem[];
+ };
+ type: 'exec_client_tasks';
+}
+/**
+ * Payload for task_result phase (single task)
+ */
+export interface TaskResultPayload {
+ /** Parent message ID */
+ parentMessageId: string;
+ /** Result from executed task */
+ result: {
+ /** Error message if task failed */
+ error?: string;
+ /** Task result content */
+ result?: string;
+ /** Whether the task completed successfully */
+ success: boolean;
+ /** Task message ID */
+ taskMessageId: string;
+ /** Thread ID where the task was executed */
+ threadId: string;
+ };
+}
+/**
+ * Payload for tasks_batch_result phase (multiple tasks)
+ */
+export interface TasksBatchResultPayload {
+ /** Parent message ID */
+ parentMessageId: string;
+ /** Results from executed tasks */
+ results: Array<{
+ /** Error message if task failed */
+ error?: string;
+ /** Task result content */
+ result?: string;
+ /** Whether the task completed successfully */
+ success: boolean;
+ /** Task message ID */
+ taskMessageId: string;
+ /** Thread ID where the task was executed */
+ threadId: string;
+ }>;
+}
+/**
+ * A serializable instruction object that the "Agent" (Brain) returns
+ * to the "AgentRuntime" (Engine) to execute.
+ */
+export type AgentInstruction = AgentInstructionCallLlm | AgentInstructionCallTool | AgentInstructionCallToolsBatch | AgentInstructionExecTask | AgentInstructionExecTasks | AgentInstructionExecClientTask | AgentInstructionExecClientTasks | AgentInstructionRequestHumanPrompt | AgentInstructionRequestHumanSelect | AgentInstructionRequestHumanApprove | AgentInstructionResolveAbortedTools | AgentInstructionCompressContext | AgentInstructionFinish;
diff --git a/packages/agent-runtime/src/types/instruction.js b/packages/agent-runtime/src/types/instruction.js
new file mode 100644
index 000000000..cb0ff5c3b
--- /dev/null
+++ b/packages/agent-runtime/src/types/instruction.js
@@ -0,0 +1 @@
+export {};
diff --git a/packages/agent-runtime/src/types/runtime.d.ts b/packages/agent-runtime/src/types/runtime.d.ts
new file mode 100644
index 000000000..a73eac0c6
--- /dev/null
+++ b/packages/agent-runtime/src/types/runtime.d.ts
@@ -0,0 +1,84 @@
+import type { AgentEvent } from './event.js';
+import { AgentInstruction, AgentRuntimeContext } from './instruction.js';
+import { AgentState } from './state.js';
+export type InstructionExecutor = (instruction: AgentInstruction, state: AgentState,
+/**
+ * Runtime context for this step
+ * Contains stepContext with dynamic state like GTD todos
+ */
+context?: AgentRuntimeContext) => Promise<{
+ events: AgentEvent[];
+ newState: AgentState;
+ /** Next context to pass to Agent runner (if execution should continue) */
+ nextContext?: AgentRuntimeContext;
+}>;
+/** The structured 402 payment requirements returned by an x402-gated server */
+export interface X402PaymentRequirements {
+ accepts: Array<{
+ asset: string;
+ description: string;
+ maxAmountRequired: string;
+ network: string;
+ payTo: string;
+ resource: string;
+ scheme: string;
+ }>;
+ x402Version: number;
+}
+/** Result returned by the onX402Required hook */
+export type X402HookResult = {
+ action: 'pay';
+} | {
+ action: 'queue';
+ reason: string;
+} | {
+ action: 'reject';
+ reason: string;
+};
+/**
+ * Hook invoked whenever an agent tool makes an HTTP request that returns 402.
+ *
+ * The hook must decide one of three actions:
+ *
+ * - `{ action: 'pay' }` - wallet has sufficient balance and the amount is within
+ * the agent's autonomy budget → proceed with automatic payment.
+ *
+ * - `{ action: 'queue', reason }` - the payment would exceed the autonomy limit
+ * → push to DecisionQueue for user approval before settling.
+ *
+ * - `{ action: 'reject', reason }` - balance insufficient or policy blocks payment
+ * → surface a clear error to the agent without crashing.
+ */
+export type X402Hook = (params: {
+ /** Agent identifier making the request */
+ agentId: string;
+ /** How much USDC was already spent this hour */
+ amountSpentThisHourUsdc: number;
+ /** Current USDC balance of the agent wallet (live, from Base RPC) */
+ currentBalanceUsdc: number;
+ /** Full URL that returned 402 */
+ url: string;
+ /** Structured payment requirements from X-PAYMENT-REQUIRED header */
+ requirements: X402PaymentRequirements;
+}) => Promise<X402HookResult>;
+export interface RuntimeConfig {
+ /** Custom executors for specific instruction types */
+ executors?: Partial<Record<AgentInstruction['type'], InstructionExecutor>>;
+ /** Function to get operation context and abort controller */
+ getOperation?: (operationId: string) => {
+ abortController: AbortController;
+ context: Record<string, any>;
+ };
+ /** Operation ID for tracking this runtime instance */
+ operationId?: string;
+ /**
+ * Hook called when an agent HTTP request returns 402 Payment Required.
+ *
+ * Use this to enforce autonomy budgets and route over-limit payments to
+ * the DecisionQueue for user approval.
+ *
+ * If not provided, x402 payments are always attempted automatically
+ * (subject to balance checks in the API route).
+ */
+ onX402Required?: X402Hook;
+}
diff --git a/packages/agent-runtime/src/types/runtime.js b/packages/agent-runtime/src/types/runtime.js
new file mode 100644
index 000000000..cb0ff5c3b
--- /dev/null
+++ b/packages/agent-runtime/src/types/runtime.js
@@ -0,0 +1 @@
+export {};
diff --git a/packages/agent-runtime/src/types/state.d.ts b/packages/agent-runtime/src/types/state.d.ts
new file mode 100644
index 000000000..6bcd4c958
--- /dev/null
+++ b/packages/agent-runtime/src/types/state.d.ts
@@ -0,0 +1,126 @@
+import { ChatToolPayload, SecurityBlacklistConfig, UserInterventionConfig } from './vendor.js';
+import type { Cost, CostLimit, Usage } from './usage.js';
+import type { PortfolioPosition } from '../core/toolRegistry.js';
+/**
+ * Agent's serializable state.
+ * This is the "passport" that can be persisted and transferred.
+ */
+export interface AgentState {
+ operationId: string;
+ status: 'idle' | 'running' | 'waiting_for_human' | 'done' | 'error' | 'interrupted';
+ messages: any[];
+ tools?: any[];
+ systemRole?: string;
+ toolManifestMap: Record<string, any>;
+ /** Tool source map for routing tool execution to correct handler */
+ toolSourceMap?: Record<string, 'builtin' | 'plugin' | 'mcp' | 'klavis' | 'lobehubSkill'>;
+ /**
+ * Portfolio positions for DeFi Guard risk analysis.
+ * Injected by the server when available to enable risk-aware tool execution.
+ */
+ portfolioPositions?: PortfolioPosition[];
+ /**
+ * Model runtime configuration
+ * Used as fallback when call_llm instruction doesn't specify model/provider
+ */
+ modelRuntimeConfig?: {
+ model: string;
+ provider: string;
+ /**
+ * Compression model configuration
+ * Used for context compression tasks
+ */
+ compressionModel?: {
+ model: string;
+ provider: string;
+ };
+ };
+ /**
+ * User's global intervention configuration
+ * Controls how tools requiring approval are handled
+ */
+ userInterventionConfig?: UserInterventionConfig;
+ /**
+ * Security blacklist configuration
+ * These rules will ALWAYS block execution and require human intervention,
+ * regardless of user settings (even in auto-run mode).
+ * If not provided, DEFAULT_SECURITY_BLACKLIST will be used.
+ */
+ securityBlacklist?: SecurityBlacklistConfig;
+ /**
+ * Number of execution steps in this session.
+ * Incremented on each runtime.step() call.
+ */
+ stepCount: number;
+ /**
+ * Optional maximum number of steps allowed.
+ * If set, execution will stop with error when exceeded.
+ */
+ maxSteps?: number;
+ /**
+ * Accumulated usage statistics for this session.
+ * Tracks tokens, API calls, tool usage, etc.
+ */
+ usage: Usage;
+ /**
+ * Current calculated cost for this session.
+ * Updated after each billable operation.
+ */
+ cost: Cost;
+ /**
+ * Optional cost limits configuration.
+ * If set, execution will stop when limits are exceeded.
+ */
+ costLimit?: CostLimit;
+ /**
+ * When status is 'waiting_for_human', this stores pending requests
+ * for human-in-the-loop operations.
+ */
+ pendingToolsCalling?: ChatToolPayload[];
+ pendingHumanPrompt?: {
+ metadata?: Record<string, unknown>;
+ prompt: string;
+ };
+ pendingHumanSelect?: {
+ metadata?: Record<string, unknown>;
+ multi?: boolean;
+ options: Array<{
+ label: string;
+ value: string;
+ }>;
+ prompt?: string;
+ };
+ /**
+ * When status is 'interrupted', this stores the interruption context
+ * for potential resumption or cleanup.
+ */
+ interruption?: {
+ /** Reason for interruption */
+ reason: string;
+ /** Timestamp when interruption occurred */
+ interruptedAt: string;
+ /** The instruction that was being executed when interrupted */
+ interruptedInstruction?: any;
+ /** Whether the interruption can be resumed */
+ canResume: boolean;
+ };
+ createdAt: string;
+ error?: any;
+ lastModified: string;
+ metadata?: Record<string, any>;
+}
+/**
+ * OpenAI Tool Call
+ */
+export interface ToolsCalling {
+ function: {
+ arguments: string;
+ name: string;
+ };
+ id: string;
+ type: 'function';
+}
+/**
+ * A registry for tools, mapping tool names to their implementation.
+ */
+export type ToolRegistry = Record<string, (args: any) => Promise<any>>;
diff --git a/packages/agent-runtime/src/types/state.js b/packages/agent-runtime/src/types/state.js
new file mode 100644
index 000000000..cb0ff5c3b
--- /dev/null
+++ b/packages/agent-runtime/src/types/state.js
@@ -0,0 +1 @@
+export {};
diff --git a/packages/agent-runtime/src/types/usage.d.ts b/packages/agent-runtime/src/types/usage.d.ts
new file mode 100644
index 000000000..f18a33462
--- /dev/null
+++ b/packages/agent-runtime/src/types/usage.d.ts
@@ -0,0 +1,127 @@
+import { ModelUsage } from './vendor.js';
+/**
+ * Token usage tracking for different types of operations
+ */
+export interface TokenUsage {
+ /** Input tokens consumed */
+ input: number;
+ /** Output tokens generated */
+ output: number;
+ /** Total tokens (input + output) */
+ total: number;
+}
+/**
+ * Usage statistics for different operation types
+ */
+export interface Usage {
+ /** Human interaction statistics */
+ humanInteraction: {
+ /** Number of approval requests */
+ approvalRequests: number;
+ /** Number of prompt requests */
+ promptRequests: number;
+ /** Number of selection requests */
+ selectRequests: number;
+ /** Total waiting time for human input */
+ totalWaitingTimeMs: number;
+ };
+ /** LLM model usage */
+ llm: {
+ /** Number of LLM API calls made */
+ apiCalls: number;
+ /** Total processing time in milliseconds */
+ processingTimeMs: number;
+ /** Total token usage across all LLM calls */
+ tokens: TokenUsage;
+ };
+ /** Tool usage statistics */
+ tools: {
+ /** Usage breakdown by tool name */
+ byTool: Array<{
+ /** Number of calls */
+ calls: number;
+ /** Number of errors */
+ errors: number;
+ /** Tool name/identifier */
+ name: string;
+ /** Total execution time in milliseconds */
+ totalTimeMs: number;
+ }>;
+ /** Number of tool calls executed */
+ totalCalls: number;
+ /** Total tool execution time */
+ totalTimeMs: number;
+ };
+}
+/**
+ * Cost calculation result
+ */
+export interface Cost {
+ /** Cost calculation timestamp */
+ calculatedAt: string;
+ currency: string;
+ /** LLM API costs */
+ llm: {
+ /** Cost per model used */
+ byModel: Array<{
+ /** Model identifier in format "provider/model" */
+ id: string;
+ /** Model name */
+ model: string;
+ /** Provider name */
+ provider: string;
+ /** Total cost for this model */
+ totalCost: number;
+ /** Detailed usage breakdown */
+ usage: ModelUsage;
+ }>;
+ currency: string;
+ /** Total LLM cost */
+ total: number;
+ };
+ /** Tool execution costs */
+ tools: {
+ /** Cost per tool (if tool has associated costs) */
+ byTool: Array<{
+ /** Number of calls */
+ calls: number;
+ /** Currency */
+ currency: string;
+ /** Tool name/identifier */
+ name: string;
+ /** Total cost for this tool */
+ totalCost: number;
+ }>;
+ currency: string;
+ /** Total tool cost */
+ total: number;
+ };
+ /** Total session cost */
+ total: number;
+}
+/**
+ * Cost limit configuration
+ */
+export interface CostLimit {
+ /** Currency for cost limits */
+ currency: string;
+ /** Maximum LLM cost allowed */
+ maxLlmCost?: number;
+ /** Maximum tool cost allowed */
+ maxToolCost?: number;
+ /** Maximum total cost allowed */
+ maxTotalCost: number;
+ /** Action to take when limit is exceeded */
+ onExceeded: 'stop' | 'warn' | 'interrupt';
+}
+/**
+ * Cost calculation context passed to Agent
+ */
+export interface CostCalculationContext {
+ /** Cost limits configuration */
+ costLimit?: CostLimit;
+ /** Previous cost calculation (if any) */
+ previousCost?: Cost;
+ /** Current usage statistics */
+ usage: Usage;
+}
diff --git a/packages/agent-runtime/src/types/usage.js b/packages/agent-runtime/src/types/usage.js
new file mode 100644
index 000000000..cb0ff5c3b
--- /dev/null
+++ b/packages/agent-runtime/src/types/usage.js
@@ -0,0 +1 @@
+export {};
diff --git a/packages/agent-runtime/src/types/vendor.d.ts b/packages/agent-runtime/src/types/vendor.d.ts
new file mode 100644
index 000000000..4d2a12a08
--- /dev/null
+++ b/packages/agent-runtime/src/types/vendor.d.ts
@@ -0,0 +1,167 @@
+/**
+ * Host-app types the runtime consumes.
+ *
+ * Inlined from the host chat platform's shared type package so this package
+ * stands alone: the runtime needs the shapes, not the host. Zod schemas were
+ * deliberately left behind; every consumer here treats these as compile-time
+ * contracts only.
+ */
+/** How a tool's result is rendered by the host UI. */
+export type ToolRenderType = 'default' | 'markdown' | 'standalone' | 'builtin' | 'mcp';
+/** Where a tool comes from. */
+export type ToolSource = 'builtin' | 'plugin' | 'mcp' | 'skill';
+/** Human-approval state attached to a tool call by the host. */
+export interface ToolIntervention {
+ rejectedReason?: string;
+ status?: 'pending' | 'approved' | 'rejected' | 'aborted' | 'none';
+}
+/** One tool invocation as the runtime sees it. */
+export interface ChatToolPayload {
+ apiName: string;
+ /** JSON-encoded arguments, exactly as produced by the model. */
+ arguments: string;
+ id: string;
+ identifier: string;
+ intervention?: ToolIntervention;
+ result_msg_id?: string;
+ source?: ToolSource;
+ thoughtSignature?: string;
+ type: ToolRenderType;
+}
+/** The function portion of an OpenAI-format tool call. */
+export interface ToolFunction {
+ /** JSON-encoded arguments; may be invalid JSON, validate before use. */
+ arguments: string;
+ name: string;
+}
+/** OpenAI-format tool call as returned by a model. */
+export interface MessageToolCall {
+ function: ToolFunction;
+ id: string;
+ thoughtSignature?: string;
+ type: 'function' | string;
+}
+/** Token usage breakdown reported by a model call. */
+export interface ModelTokensUsage {
+ inputCachedTokens?: number;
+ inputCacheMissTokens?: number;
+ inputWriteCacheTokens?: number;
+ inputTextTokens?: number;
+ inputImageTokens?: number;
+ inputAudioTokens?: number;
+ inputCitationTokens?: number;
+ outputTextTokens?: number;
+ outputImageTokens?: number;
+ outputAudioTokens?: number;
+ outputReasoningTokens?: number;
+ acceptedPredictionTokens?: number;
+ rejectedPredictionTokens?: number;
+ totalInputTokens?: number;
+ totalOutputTokens?: number;
+ totalTokens?: number;
+ /** @deprecated Use totalInputTokens instead */
+ inputTokens?: number;
+ /** @deprecated Use totalOutputTokens instead */
+ outputTokens?: number;
+ /** @deprecated Use outputReasoningTokens instead */
+ reasoningTokens?: number;
+ /** @deprecated Use outputImageTokens instead */
+ imageTokens?: number;
+ /** @deprecated Use inputCachedTokens instead */
+ cachedTokens?: number;
+}
+/** Usage plus the dollar cost derived from it. */
+export interface ModelUsage extends ModelTokensUsage {
+ /** Dollars. */
+ cost?: number;
+}
+/**
+ * Human intervention policy for a tool API.
+ * - `never`: auto-execute
+ * - `required`: needs approval, bypassable by the user's auto-run mode
+ * - `always`: needs approval, never bypassable
+ */
+export type HumanInterventionPolicy = 'never' | 'required' | 'always';
+/**
+ * Argument matcher for parameter-level rules. A plain string matches by
+ * substring/wildcard; the object form selects an explicit strategy.
+ */
+export type ArgumentMatcher = string | {
+ pattern: string;
+ type: 'exact' | 'prefix' | 'wildcard' | 'regex';
+};
+/** One parameter-level intervention rule. */
+export interface HumanInterventionRule {
+ /** Per-argument matchers; the rule applies when every matcher matches. */
+ match?: Record<string, ArgumentMatcher>;
+ policy: HumanInterventionPolicy;
+}
+/** Either a uniform policy or an ordered rule list. */
+export type HumanInterventionConfig = HumanInterventionPolicy | HumanInterventionRule[];
+/** The user's global approval configuration for a session. */
+export interface UserInterventionConfig {
+ /** Pre-approved tools in `identifier/apiName` form (allow-list mode). */
+ allowList?: string[];
+ /**
+ * - `auto-run`: approve everything
+ * - `allow-list`: approve only listed tools
+ * - `manual`: follow each tool's own config (default)
+ * - `headless`: fully automated; blacklisted tools are skipped, not blocked
+ */
+ approvalMode: 'auto-run' | 'allow-list' | 'manual' | 'headless';
+}
+/** A rule that force-blocks dangerous operations regardless of user settings. */
+export interface SecurityBlacklistRule {
+ /** Why this rule exists; surfaced in error messages. */
+ description: string;
+ match: Record<string, ArgumentMatcher>;
+}
+export type SecurityBlacklistConfig = SecurityBlacklistRule[];
+/** Parameters for `InterventionChecker.shouldIntervene`. */
+export interface ShouldInterveneParams {
+ config: HumanInterventionConfig | undefined;
+ /** Tool keys the user already confirmed (for remember-my-choice flows). */
+ confirmedHistory?: string[];
+ /** Blacklist rules checked first; they override every other setting. */
+ securityBlacklist?: SecurityBlacklistConfig;
+ toolArgs?: Record<string, any>;
+ /** `identifier/apiName` or `identifier/apiName#argsHash`. */
+ toolKey?: string;
+}
+/** Status of a step-context todo item. */
+export type StepContextTodoStatus = 'todo' | 'processing' | 'completed';
+export interface StepContextTodoItem {
+ status: StepContextTodoStatus;
+ text: string;
+}
+export interface StepContextTodos {
+ items: StepContextTodoItem[];
+ updatedAt: string;
+}
+/** Latest page-editor XML, refreshed each step. */
+export interface StepPageEditorContext {
+ xml: string;
+}
+/** Page-editor context captured once at operation start. */
+export interface InitialPageEditorContext {
+ markdown: string;
+ metadata: {
+ charCount?: number;
+ lineCount?: number;
+ title: string;
+ };
+ xml: string;
+}
+/**
+ * Dynamic per-step context, computed by the runtime at the start of each step
+ * and injected into executors. Executors read from it and return new state via
+ * their result, never by mutating it.
+ */
+export interface RuntimeStepContext {
+ stepPageEditor?: StepPageEditorContext;
+ todos?: StepContextTodos;
+}
+/** Context captured at operation initialization; constant for the whole run. */
+export interface RuntimeInitialContext {
+ pageEditor?: InitialPageEditorContext;
+}
diff --git a/packages/agent-runtime/src/types/vendor.js b/packages/agent-runtime/src/types/vendor.js
new file mode 100644
index 000000000..93ad8ac01
--- /dev/null
+++ b/packages/agent-runtime/src/types/vendor.js
@@ -0,0 +1,9 @@
+/**
+ * Host-app types the runtime consumes.
+ *
+ * Inlined from the host chat platform's shared type package so this package
+ * stands alone: the runtime needs the shapes, not the host. Zod schemas were
+ * deliberately left behind; every consumer here treats these as compile-time
+ * contracts only.
+ */
+export {};
diff --git a/packages/agent-runtime/src/utils/importanceScorer.d.ts b/packages/agent-runtime/src/utils/importanceScorer.d.ts
new file mode 100644
index 000000000..be5e7f7b4
--- /dev/null
+++ b/packages/agent-runtime/src/utils/importanceScorer.d.ts
@@ -0,0 +1,76 @@
+/**
+ * ImportanceScorer - Progressive context compression based on message importance.
+ *
+ * Instead of compressing all messages at once when a token threshold is hit,
+ * this scorer evaluates each message's importance and enables progressive
+ * summarization of less important messages first.
+ *
+ * Importance factors:
+ * 1. Recency - newer messages are more important
+ * 2. Role - user messages > tool results > assistant continuations
+ * 3. Semantic relevance - messages containing the current query's keywords
+ * 4. Tool output value - successful tool results > error results
+ * 5. Pinned/bookmarked - user-pinned messages always kept
+ */
+export interface ImportanceScoredMessage {
+ /** The original message */
+ message: any;
+ /** Importance score (0-1, higher = more important) */
+ score: number;
+ /** Estimated token count for this message */
+ tokens: number;
+}
+export interface ProgressiveCompressionConfig {
+ /**
+ * Number of most recent messages to always keep uncompressed.
+ * Default: 6
+ */
+ keepRecentCount?: number;
+ /**
+ * Target token budget after compression.
+ * Messages below importance threshold will be marked for summarization.
+ * Default: 0.4 of maxWindowToken
+ */
+ targetRatio?: number;
+}
+export declare class ImportanceScorer {
+ private config;
+ constructor(config?: ProgressiveCompressionConfig);
+ /**
+ * Score all messages by importance relative to the current conversation context.
+ *
+ * @param messages - All conversation messages
+ * @param currentQuery - The latest user query (for semantic relevance)
+ * @returns Scored messages sorted by position (not score)
+ */
+ scoreMessages(messages: any[], currentQuery?: string): ImportanceScoredMessage[];
+ /**
+ * Given scored messages and a token budget, identify which messages
+ * should be kept verbatim vs. compressed into a summary.
+ *
+ * @param scored - Output from scoreMessages()
+ * @param tokenBudget - Maximum tokens for the final context
+ * @returns Object with messages to keep and messages to compress
+ */
+ partitionForCompression(scored: ImportanceScoredMessage[], tokenBudget: number): {
+ toCompress: ImportanceScoredMessage[];
+ toKeep: ImportanceScoredMessage[];
+ };
+ /**
+ * Role-based importance score.
+ * User messages are highest because they contain the intent.
+ */
+ private getRoleScore;
+ /**
+ * Semantic relevance score based on keyword overlap with current query.
+ */
+ private getSemanticScore;
+ /**
+ * Content quality signals - longer, more substantive messages score higher.
+ */
+ private getContentQualityScore;
+ /**
+ * Extract keywords from text for semantic matching.
+ */
+ private extractKeywords;
+}
diff --git a/packages/agent-runtime/src/utils/importanceScorer.js b/packages/agent-runtime/src/utils/importanceScorer.js
new file mode 100644
index 000000000..1ed302bff
--- /dev/null
+++ b/packages/agent-runtime/src/utils/importanceScorer.js
@@ -0,0 +1,173 @@
+/**
+ * ImportanceScorer - Progressive context compression based on message importance.
+ *
+ * Instead of compressing all messages at once when a token threshold is hit,
+ * this scorer evaluates each message's importance and enables progressive
+ * summarization of less important messages first.
+ *
+ * Importance factors:
+ * 1. Recency - newer messages are more important
+ * 2. Role - user messages > tool results > assistant continuations
+ * 3. Semantic relevance - messages containing the current query's keywords
+ * 4. Tool output value - successful tool results > error results
+ * 5. Pinned/bookmarked - user-pinned messages always kept
+ */
+import { estimateTokens } from './tokenCounter.js';
+const DEFAULT_CONFIG = {
+ keepRecentCount: 6,
+ targetRatio: 0.4,
+};
+export class ImportanceScorer {
+ config;
+ constructor(config) {
+ this.config = { ...DEFAULT_CONFIG, ...config };
+ }
+ /**
+ * Score all messages by importance relative to the current conversation context.
+ *
+ * @param messages - All conversation messages
+ * @param currentQuery - The latest user query (for semantic relevance)
+ * @returns Scored messages sorted by position (not score)
+ */
+ scoreMessages(messages, currentQuery) {
+ const totalMessages = messages.length;
+ const queryKeywords = currentQuery ? this.extractKeywords(currentQuery) : [];
+ return messages.map((message, index) => {
+ let score = 0;
+ // Factor 1: Recency (0-0.15)
+ // Linear boost from oldest to newest - kept small so role importance dominates
+ const recencyScore = totalMessages > 1 ? (index / (totalMessages - 1)) * 0.15 : 0.15;
+ score += recencyScore;
+ // Factor 2: Role importance (0-0.25)
+ score += this.getRoleScore(message);
+ // Factor 3: Semantic relevance to current query (0-0.25)
+ if (queryKeywords.length > 0) {
+ score += this.getSemanticScore(message, queryKeywords);
+ }
+ // Factor 4: Content quality signals (0-0.1)
+ score += this.getContentQualityScore(message);
+ // Factor 5: Pinned / bookmarked (override)
+ if (message.metadata?.pinned || message.extra?.pinned) {
+ score = 1.0; // Max importance - never compress
+ }
+ // Factor 6: System messages are always critical
+ if (message.role === 'system') {
+ score = 1.0;
+ }
+ const tokens = estimateTokens(message.content);
+ return { message, score: Math.min(score, 1.0), tokens };
+ });
+ }
+ /**
+ * Given scored messages and a token budget, identify which messages
+ * should be kept verbatim vs. compressed into a summary.
+ *
+ * @param scored - Output from scoreMessages()
+ * @param tokenBudget - Maximum tokens for the final context
+ * @returns Object with messages to keep and messages to compress
+ */
+ partitionForCompression(scored, tokenBudget) {
+ const toKeep = [];
+ const toCompress = [];
+ // Always keep the most recent N messages
+ const recentCutoff = Math.max(0, scored.length - this.config.keepRecentCount);
+ // First pass: always-keep messages (recent + pinned + system)
+ let usedTokens = 0;
+ for (let i = 0; i < scored.length; i++) {
+ const item = scored[i];
+ const isRecent = i >= recentCutoff;
+ const isPinned = item.score >= 1.0;
+ if (isRecent || isPinned) {
+ toKeep.push(item);
+ usedTokens += item.tokens;
+ }
+ }
+ // Second pass: fill remaining budget with highest-importance older messages
+ const candidates = scored
+ .slice(0, recentCutoff)
+ .filter((item) => item.score < 1.0)
+ .sort((a, b) => b.score - a.score); // highest importance first
+ for (const candidate of candidates) {
+ if (usedTokens + candidate.tokens <= tokenBudget) {
+ toKeep.push(candidate);
+ usedTokens += candidate.tokens;
+ }
+ else {
+ toCompress.push(candidate);
+ }
+ }
+ // Sort toKeep back to conversation order
+ toKeep.sort((a, b) => scored.indexOf(a) - scored.indexOf(b));
+ return { toCompress, toKeep };
+ }
+ /**
+ * Role-based importance score.
+ * User messages are highest because they contain the intent.
+ */
+ getRoleScore(message) {
+ switch (message.role) {
+ case 'user': {
+ return 0.25;
+ }
+ case 'assistant': {
+ // Short assistant messages (acknowledgments) are less important
+ const content = typeof message.content === 'string' ? message.content : '';
+ return content.length > 200 ? 0.2 : 0.1;
+ }
+ case 'tool': {
+ // Successful tool results are more valuable than errors
+ const isError = message.content?.includes('"error"') || message.content?.includes('"blocked"');
+ return isError ? 0.05 : 0.15;
+ }
+ default: {
+ return 0.1;
+ }
+ }
+ }
+ /**
+ * Semantic relevance score based on keyword overlap with current query.
+ */
+ getSemanticScore(message, queryKeywords) {
+ const content = typeof message.content === 'string' ? message.content : '';
+ if (!content)
+ return 0;
+ // Sample first 500 chars of content for performance
+ const contentLower = content.slice(0, 500).toLowerCase();
+ let matches = 0;
+ for (const keyword of queryKeywords) {
+ if (contentLower.includes(keyword)) {
+ matches++;
+ }
+ }
+ // Normalize: 3+ keyword matches = max score
+ return Math.min(matches / 3, 1) * 0.25;
+ }
+ /**
+ * Content quality signals - longer, more substantive messages score higher.
+ */
+ getContentQualityScore(message) {
+ const content = typeof message.content === 'string' ? message.content : '';
+ // Messages with code blocks or structured data are higher quality
+ const hasCode = content.includes('```') || content.includes('`');
+ const hasStructuredData = content.includes('{') && content.includes('}');
+ const isSubstantive = content.length > 100;
+ let score = 0;
+ if (hasCode)
+ score += 0.04;
+ if (hasStructuredData)
+ score += 0.03;
+ if (isSubstantive)
+ score += 0.03;
+ return score;
+ }
+ /**
+ * Extract keywords from text for semantic matching.
+ */
+ extractKeywords(text) {
+ return text
+ .toLowerCase()
+ .replace(/[^\w\s]/g, ' ')
+ .split(/\s+/)
+ .filter((w) => w.length > 2);
+ }
+}
diff --git a/packages/agent-runtime/src/utils/index.d.ts b/packages/agent-runtime/src/utils/index.d.ts
new file mode 100644
index 000000000..353a34754
--- /dev/null
+++ b/packages/agent-runtime/src/utils/index.d.ts
@@ -0,0 +1,4 @@
+export * from './importanceScorer.js';
+export * from './receiptService.js';
+export * from './stepContextComputer.js';
+export * from './tokenCounter.js';
diff --git a/packages/agent-runtime/src/utils/index.js b/packages/agent-runtime/src/utils/index.js
new file mode 100644
index 000000000..353a34754
--- /dev/null
+++ b/packages/agent-runtime/src/utils/index.js
@@ -0,0 +1,4 @@
+export * from './importanceScorer.js';
+export * from './receiptService.js';
+export * from './stepContextComputer.js';
+export * from './tokenCounter.js';
diff --git a/packages/agent-runtime/src/utils/receiptService.d.ts b/packages/agent-runtime/src/utils/receiptService.d.ts
new file mode 100644
index 000000000..a874195ae
--- /dev/null
+++ b/packages/agent-runtime/src/utils/receiptService.d.ts
@@ -0,0 +1,48 @@
+/**
+ * Receipt Service - pure computation for execution receipts.
+ *
+ * Handles hashing of inputs/outputs and building the receipt payload
+ * that will be signed and stored by the server-side tRPC procedure.
+ *
+ * No DB access or private key operations here - those happen server-side.
+ */
+export type ReceiptActionType = 'swap' | 'transfer' | 'strategy' | 'a2a_payment' | 'approval' | 'other';
+export interface ToolCallRecord {
+ toolName: string;
+ params: Record<string, unknown>;
+ result: unknown;
+}
+export interface ReceiptPayload {
+ agentId: string;
+ topicId?: string;
+ messageId?: string;
+ actionType: ReceiptActionType;
+ inputHash: string;
+ outputHash: string;
+ toolCalls: ToolCallRecord[];
+ modelUsed: string;
+ modelProvider: string;
+ tokensUsed?: number;
+ walletAddress: string;
+ chainId?: number;
+ onChainTxHash?: string;
+}
+/**
+ * Detect whether a set of tool calls produced an on-chain action.
+ */
+export declare function detectActionType(toolCalls: ToolCallRecord[]): ReceiptActionType | null;
+/**
+ * SHA-256 of the combined user prompt and agent system prompt snapshot.
+ */
+export declare function hashInput(userPrompt: string, systemPrompt: string): Promise<string>;
+/**
+ * SHA-256 of the final AI response text.
+ */
+export declare function hashOutput(responseText: string): Promise<string>;
+/**
+ * Build the receipt hash that the agent wallet will sign.
+ *
+ * Message: id + inputHash + outputHash + onChainTxHash (or empty string)
+ * This is the same message that viem's recoverMessageAddress() can verify.
+ */
+export declare function buildReceiptMessage(receiptId: string, inputHash: string, outputHash: string, onChainTxHash: string | null | undefined): string;
diff --git a/packages/agent-runtime/src/utils/receiptService.js b/packages/agent-runtime/src/utils/receiptService.js
new file mode 100644
index 000000000..17876bc58
--- /dev/null
+++ b/packages/agent-runtime/src/utils/receiptService.js
@@ -0,0 +1,65 @@
+/**
+ * Receipt Service - pure computation for execution receipts.
+ *
+ * Handles hashing of inputs/outputs and building the receipt payload
+ * that will be signed and stored by the server-side tRPC procedure.
+ *
+ * No DB access or private key operations here - those happen server-side.
+ */
+/** Canonical on-chain actions - any tool result containing these indicates on-chain activity */
+const ON_CHAIN_ACTION_TOOLS = new Set([
+ 'sendPayment',
+ 'executeSwap',
+ 'executeStrategy',
+ 'sendA2APayment',
+ 'approveToken',
+ 'bridgeAsset',
+ 'depositToProtocol',
+ 'withdrawFromProtocol',
+]);
+/**
+ * Detect whether a set of tool calls produced an on-chain action.
+ */
+export function detectActionType(toolCalls) {
+ for (const tc of toolCalls) {
+ if (tc.toolName === 'sendPayment' || tc.toolName === 'sendA2APayment')
+ return 'transfer';
+ if (tc.toolName === 'executeSwap')
+ return 'swap';
+ if (tc.toolName === 'executeStrategy')
+ return 'strategy';
+ if (tc.toolName === 'approveToken')
+ return 'approval';
+ if (ON_CHAIN_ACTION_TOOLS.has(tc.toolName))
+ return 'other';
+ }
+ return null;
+}
+async function sha256Hex(data) {
+ const buf = new TextEncoder().encode(data);
+ const hashBuf = await crypto.subtle.digest('SHA-256', buf);
+ return Array.from(new Uint8Array(hashBuf))
+ .map((b) => b.toString(16).padStart(2, '0'))
+ .join('');
+}
+/**
+ * SHA-256 of the combined user prompt and agent system prompt snapshot.
+ */
+export async function hashInput(userPrompt, systemPrompt) {
+ return sha256Hex(userPrompt + '\x00' + systemPrompt);
+}
+/**
+ * SHA-256 of the final AI response text.
+ */
+export async function hashOutput(responseText) {
+ return sha256Hex(responseText);
+}
+/**
+ * Build the receipt hash that the agent wallet will sign.
+ *
+ * Message: id + inputHash + outputHash + onChainTxHash (or empty string)
+ * This is the same message that viem's recoverMessageAddress() can verify.
+ */
+export function buildReceiptMessage(receiptId, inputHash, outputHash, onChainTxHash) {
+ return `${receiptId}:${inputHash}:${outputHash}:${onChainTxHash ?? ''}`;
+}
diff --git a/packages/agent-runtime/src/utils/stepContextComputer.d.ts b/packages/agent-runtime/src/utils/stepContextComputer.d.ts
new file mode 100644
index 000000000..30b9a021f
--- /dev/null
+++ b/packages/agent-runtime/src/utils/stepContextComputer.d.ts
@@ -0,0 +1,26 @@
+import type { RuntimeStepContext, StepContextTodos } from '../types/vendor.js';
+/**
+ * Input parameters for computeStepContext
+ * Using object parameter for future extensibility
+ */
+export interface ComputeStepContextParams {
+ /**
+ * Pre-computed todos state from message selector
+ * Should be computed using selectTodosFromMessages in chat store selectors
+ */
+ todos?: StepContextTodos;
+}
+/**
+ * Compute the Step Context from pre-computed values
+ *
+ * Called in internal_execAgentRuntime while loop before each runtime.step() call.
+ * The stepContext is then passed through AgentRuntimeContext to Tool Executors.
+ *
+ * Note: The actual data (like todos) should be computed using selectors in the UI layer
+ * (e.g., selectTodosFromMessages in chat store) and passed here.
+ * This separation allows the selector logic to be reused for UI display.
+ *
+ * @param params - Object containing pre-computed state values
+ * @returns RuntimeStepContext assembled from the provided values
+ */
+export declare const computeStepContext: ({ todos }: ComputeStepContextParams) => RuntimeStepContext;
diff --git a/packages/agent-runtime/src/utils/stepContextComputer.js b/packages/agent-runtime/src/utils/stepContextComputer.js
new file mode 100644
index 000000000..254c80d72
--- /dev/null
+++ b/packages/agent-runtime/src/utils/stepContextComputer.js
@@ -0,0 +1,18 @@
+/**
+ * Compute the Step Context from pre-computed values
+ *
+ * Called in internal_execAgentRuntime while loop before each runtime.step() call.
+ * The stepContext is then passed through AgentRuntimeContext to Tool Executors.
+ *
+ * Note: The actual data (like todos) should be computed using selectors in the UI layer
+ * (e.g., selectTodosFromMessages in chat store) and passed here.
+ * This separation allows the selector logic to be reused for UI display.
+ *
+ * @param params - Object containing pre-computed state values
+ * @returns RuntimeStepContext assembled from the provided values
+ */
+export const computeStepContext = ({ todos }) => {
+ return {
+ ...(todos && { todos }),
+ };
+};
diff --git a/packages/agent-runtime/src/utils/tokenCounter.d.ts b/packages/agent-runtime/src/utils/tokenCounter.d.ts
new file mode 100644
index 000000000..266bbe679
--- /dev/null
+++ b/packages/agent-runtime/src/utils/tokenCounter.d.ts
@@ -0,0 +1,64 @@
+/**
+ * Options for token counting and compression threshold calculation
+ */
+export interface TokenCountOptions {
+ /** Model's max context window token count */
+ maxWindowToken?: number;
+ /** Threshold ratio for triggering compression, default 0.75 */
+ thresholdRatio?: number;
+}
+/** Default max context window (128k tokens) */
+export declare const DEFAULT_MAX_CONTEXT = 128000;
+/** Default threshold ratio (50% of max context) */
+export declare const DEFAULT_THRESHOLD_RATIO = 0.5;
+/**
+ * Message interface for token counting
+ */
+export interface TokenCountMessage {
+ content?: string | unknown;
+ metadata?: {
+ usage?: {
+ totalOutputTokens?: number;
+ };
+ } | null;
+ role: string;
+}
+/**
+ * Estimate token count for text content using tokenx
+ * @param content - Text content or object to estimate tokens for
+ * @returns Estimated token count
+ */
+export declare function estimateTokens(content: string | unknown): number;
+/**
+ * Calculate total token count for a list of messages
+ * - Assistant messages: Use metadata.usage.totalOutputTokens if available (exact value)
+ * - User/System messages: Use tokenx estimation
+ *
+ * @param messages - List of messages to count tokens for
+ * @returns Total token count
+ */
+export declare function calculateMessageTokens(messages: TokenCountMessage[]): number;
+/**
+ * Calculate the compression threshold based on max context window
+ * @param options - Token count options
+ * @returns Compression threshold in tokens
+ */
+export declare function getCompressionThreshold(options?: TokenCountOptions): number;
+/**
+ * Result of compression check
+ */
+export interface CompressionCheckResult {
+ /** Current total token count */
+ currentTokenCount: number;
+ /** Whether compression is needed */
+ needsCompression: boolean;
+ /** Compression threshold */
+ threshold: number;
+}
+/**
+ * Check if messages need compression based on token count
+ * @param messages - List of messages to check
+ * @param options - Token count options
+ * @returns Compression check result
+ */
+export declare function shouldCompress(messages: TokenCountMessage[], options?: TokenCountOptions): CompressionCheckResult;
diff --git a/packages/agent-runtime/src/utils/tokenCounter.js b/packages/agent-runtime/src/utils/tokenCounter.js
new file mode 100644
index 000000000..543282523
--- /dev/null
+++ b/packages/agent-runtime/src/utils/tokenCounter.js
@@ -0,0 +1,65 @@
+import { estimateTokenCount } from 'tokenx';
+/** Default max context window (128k tokens) */
+export const DEFAULT_MAX_CONTEXT = 128_000;
+/** Default threshold ratio (50% of max context) */
+export const DEFAULT_THRESHOLD_RATIO = 0.5;
+/**
+ * Estimate token count for text content using tokenx
+ * @param content - Text content or object to estimate tokens for
+ * @returns Estimated token count
+ */
+export function estimateTokens(content) {
+ // Handle null/undefined early
+ if (content === null || content === undefined)
+ return 0;
+ const text = typeof content === 'string' ? content : JSON.stringify(content);
+ if (!text)
+ return 0;
+ return estimateTokenCount(text);
+}
+/**
+ * Calculate total token count for a list of messages
+ * - Assistant messages: Use metadata.usage.totalOutputTokens if available (exact value)
+ * - User/System messages: Use tokenx estimation
+ *
+ * @param messages - List of messages to count tokens for
+ * @returns Total token count
+ */
+export function calculateMessageTokens(messages) {
+ return messages.reduce((total, msg) => {
+ // For assistant messages, prefer the recorded token count from usage metadata
+ if (msg.role === 'assistant') {
+ const outputTokens = msg.metadata?.usage?.totalOutputTokens;
+ if (outputTokens && outputTokens > 0) {
+ return total + outputTokens;
+ }
+ }
+ // For user/system messages or assistant messages without usage data, estimate tokens
+ return total + estimateTokens(msg.content);
+ }, 0);
+}
+/**
+ * Calculate the compression threshold based on max context window
+ * @param options - Token count options
+ * @returns Compression threshold in tokens
+ */
+export function getCompressionThreshold(options = {}) {
+ const maxContext = options.maxWindowToken ?? DEFAULT_MAX_CONTEXT;
+ const ratio = options.thresholdRatio ?? DEFAULT_THRESHOLD_RATIO;
+ return Math.floor(maxContext * ratio);
+}
+/**
+ * Check if messages need compression based on token count
+ * @param messages - List of messages to check
+ * @param options - Token count options
+ * @returns Compression check result
+ */
+export function shouldCompress(messages, options = {}) {
+ const currentTokenCount = calculateMessageTokens(messages);
+ const threshold = getCompressionThreshold(options);
+ return {
+ currentTokenCount,
+ needsCompression: currentTokenCount > threshold,
+ threshold,
+ };
+}
diff --git a/packages/agent-runtime/tests/ActionLedger.test.js b/packages/agent-runtime/tests/ActionLedger.test.js
new file mode 100644
index 000000000..59e8c2076
--- /dev/null
+++ b/packages/agent-runtime/tests/ActionLedger.test.js
@@ -0,0 +1,214 @@
+import { describe, expect, it } from "vitest";
+import {
+ LEDGER_CANONICAL_FIELD_ORDER,
+ LEDGER_FIELD_SEPARATOR,
+ LEDGER_GENESIS_HASH,
+ auditChainRows,
+ canonicalizeEntry,
+ computeEntryHash,
+ findUnrecordedOutbound,
+ verifyChain,
+ verifyChainWindow
+} from "../src/core/ActionLedger.js";
+const baseEntry = (overrides = {}) => ({
+ agentId: "agt_1",
+ amountWei: "1000000000000000000",
+ balanceAfterWei: "4000000000000000000",
+ balanceBeforeWei: "5000000000000000000",
+ detail: { source: "transaction-pipeline" },
+ event: "transfer",
+ network: "arbitrum",
+ reason: "rebalance",
+ seq: 1,
+ target: "0xabc",
+ ts: "2026-07-06T00:00:00.000Z",
+ txHash: "0xhash1",
+ userId: "user_1",
+ valueUsd: 2500,
+ ...overrides
+});
+const buildChain = (n, userId = "user_1") => {
+ const rows = [];
+ let prevHash = LEDGER_GENESIS_HASH;
+ for (let i = 1; i <= n; i++) {
+ const entry = baseEntry({
+ seq: i,
+ txHash: `0xhash${i}`,
+ ts: `2026-07-06T00:0${i}:00.000Z`,
+ userId
+ });
+ const entryHash = computeEntryHash(entry, prevHash);
+ rows.push({ ...entry, entryHash, prevHash });
+ prevHash = entryHash;
+ }
+ return rows;
+};
+describe("computeEntryHash", () => {
+ it("is deterministic for fixed inputs", () => {
+ const entry = baseEntry();
+ const a = computeEntryHash(entry, LEDGER_GENESIS_HASH);
+ const b = computeEntryHash(entry, LEDGER_GENESIS_HASH);
+ expect(a).toBe(b);
+ expect(a).toMatch(/^[\da-f]{64}$/);
+ });
+ it("changes when any committed field changes", () => {
+ const base = computeEntryHash(baseEntry(), LEDGER_GENESIS_HASH);
+ expect(computeEntryHash(baseEntry({ amountWei: "2" }), LEDGER_GENESIS_HASH)).not.toBe(base);
+ expect(computeEntryHash(baseEntry({ target: "0xdef" }), LEDGER_GENESIS_HASH)).not.toBe(base);
+ expect(computeEntryHash(baseEntry({ event: "failed" }), LEDGER_GENESIS_HASH)).not.toBe(base);
+ });
+ it("changes when the previous hash changes (chain linkage)", () => {
+ const entry = baseEntry();
+ expect(computeEntryHash(entry, LEDGER_GENESIS_HASH)).not.toBe(
+ computeEntryHash(entry, "f".repeat(64))
+ );
+ });
+ it("canonicalises detail independent of key order", () => {
+ const a = canonicalizeEntry(baseEntry({ detail: { a: 1, b: 2 } }));
+ const b = canonicalizeEntry(baseEntry({ detail: { b: 2, a: 1 } }));
+ expect(a).toBe(b);
+ });
+});
+describe("verifyChain", () => {
+ it("treats an empty chain as valid", () => {
+ expect(verifyChain([]).valid).toBe(true);
+ });
+ it("passes on a well-formed chain", () => {
+ const result = verifyChain(buildChain(5));
+ expect(result.valid).toBe(true);
+ expect(result.brokenAtIndex).toBe(-1);
+ expect(result.length).toBe(5);
+ });
+ it("is order-independent (sorts by seq before walking)", () => {
+ const chain = buildChain(4);
+ const shuffled = [chain[2], chain[0], chain[3], chain[1]];
+ expect(verifyChain(shuffled).valid).toBe(true);
+ });
+ it("fails at the exact index of a mutated row", () => {
+ const chain = buildChain(5);
+ chain[2] = { ...chain[2], amountWei: "999" };
+ const result = verifyChain(chain);
+ expect(result.valid).toBe(false);
+ expect(result.brokenAtIndex).toBe(2);
+ expect(result.brokenAtSeq).toBe(3);
+ expect(result.reason).toContain("entryHash mismatch");
+ });
+ it("detects a deleted row via the broken prevHash link", () => {
+ const chain = buildChain(5);
+ const withGap = [chain[0], chain[1], chain[3], chain[4]];
+ const result = verifyChain(withGap);
+ expect(result.valid).toBe(false);
+ expect(result.brokenAtIndex).toBe(2);
+ expect(result.reason).toContain("prevHash mismatch");
+ });
+ it("detects a missing genesis link", () => {
+ const chain = buildChain(2);
+ chain[0] = { ...chain[0], prevHash: "a".repeat(64) };
+ const result = verifyChain(chain);
+ expect(result.valid).toBe(false);
+ expect(result.brokenAtIndex).toBe(0);
+ });
+});
+describe("findUnrecordedOutbound", () => {
+ it("returns outbound tx hashes absent from the ledger", () => {
+ const ledger = [{ txHash: "0xAAA" }, { txHash: "0xbbb" }, { txHash: null }];
+ const onChain = ["0xaaa", "0xCCC", "0xbbb", "0xddd"];
+ const unrecorded = findUnrecordedOutbound(onChain, ledger);
+ expect(unrecorded).toEqual(["0xCCC", "0xddd"]);
+ });
+ it("is empty when everything is recorded", () => {
+ const ledger = [{ txHash: "0x1" }, { txHash: "0x2" }];
+ expect(findUnrecordedOutbound(["0x1", "0x2"], ledger)).toEqual([]);
+ });
+ it("deduplicates repeated on-chain hashes", () => {
+ expect(findUnrecordedOutbound(["0xa", "0xa"], [])).toEqual(["0xa"]);
+ });
+});
+describe("LEDGER_CANONICAL_FIELD_ORDER", () => {
+ it("matches the order canonicalizeEntry actually emits", () => {
+ const entry = baseEntry({
+ agentId: "AGENT",
+ amountWei: "AMOUNTWEI",
+ balanceAfterWei: "BALANCEAFTER",
+ balanceBeforeWei: "BALANCEBEFORE",
+ detail: null,
+ network: "NETWORK",
+ reason: "REASON",
+ target: "TARGET",
+ txHash: "TXHASH",
+ userId: "USERID"
+ });
+ const segments = canonicalizeEntry(entry).split(LEDGER_FIELD_SEPARATOR);
+ expect(segments).toHaveLength(LEDGER_CANONICAL_FIELD_ORDER.length);
+ expect(LEDGER_CANONICAL_FIELD_ORDER).toEqual([
+ "seq",
+ "ts",
+ "userId",
+ "agentId",
+ "event",
+ "target",
+ "amountWei",
+ "valueUsd",
+ "txHash",
+ "reason",
+ "balanceBeforeWei",
+ "balanceAfterWei",
+ "network",
+ "detail"
+ ]);
+ expect(segments[LEDGER_CANONICAL_FIELD_ORDER.indexOf("userId")]).toBe("USERID");
+ expect(segments[LEDGER_CANONICAL_FIELD_ORDER.indexOf("network")]).toBe("NETWORK");
+ });
+ it("separates fields with a control character that cannot occur in a value", () => {
+ expect(LEDGER_FIELD_SEPARATOR).toHaveLength(1);
+ expect(LEDGER_FIELD_SEPARATOR.codePointAt(0)).toBeLessThan(32);
+ });
+});
+describe("verifyChainWindow", () => {
+ it("verifies a mid-chain window when anchored to the preceding entry hash", () => {
+ const chain = buildChain(5);
+ const window = chain.slice(2);
+ expect(verifyChainWindow(window, { anchorHash: chain[1].entryHash }).valid).toBe(true);
+ });
+ it("rejects a mid-chain window checked against genesis", () => {
+ const chain = buildChain(5);
+ expect(verifyChainWindow(chain.slice(2)).valid).toBe(false);
+ });
+ it("catches an entry deleted at a window boundary", () => {
+ const chain = buildChain(5);
+ const withHole = [chain[3], chain[4]];
+ expect(verifyChainWindow(withHole, { anchorHash: chain[1].entryHash }).valid).toBe(false);
+ });
+ it("is equivalent to verifyChain when anchored at genesis", () => {
+ const chain = buildChain(4);
+ expect(verifyChainWindow(chain)).toEqual(verifyChain(chain));
+ });
+});
+describe("auditChainRows", () => {
+ it("reports every row as sound for an intact chain", () => {
+ const checks = auditChainRows(buildChain(4));
+ expect(checks).toHaveLength(4);
+ expect(checks.every((c) => c.hashOk && c.linkOk)).toBe(true);
+ expect(checks[0].expectedPrevHash).toBe(LEDGER_GENESIS_HASH);
+ });
+ it("recomputes the same hash that is stored", () => {
+ const [check] = auditChainRows(buildChain(1));
+ expect(check.computedHash).toBe(check.storedHash);
+ });
+ it("flags only the altered row as hash-broken, and only its successor as link-broken", () => {
+ const chain = buildChain(4);
+ chain[1] = { ...chain[1], amountWei: "999" };
+ const checks = auditChainRows(chain);
+ expect(checks.map((c) => c.hashOk)).toEqual([true, false, true, true]);
+ expect(checks.map((c) => c.linkOk)).toEqual([true, true, true, true]);
+ });
+ it("flags the successor link when a row is removed", () => {
+ const chain = buildChain(4);
+ const checks = auditChainRows([chain[0], chain[2], chain[3]]);
+ expect(checks.map((c) => c.linkOk)).toEqual([true, false, true]);
+ expect(checks.every((c) => c.hashOk)).toBe(true);
+ });
+ it("returns an empty array for an empty chain", () => {
+ expect(auditChainRows([])).toEqual([]);
+ });
+});
diff --git a/packages/agent-runtime/tests/CapabilityGuard.test.js b/packages/agent-runtime/tests/CapabilityGuard.test.js
new file mode 100644
index 000000000..0345e5eb9
--- /dev/null
+++ b/packages/agent-runtime/tests/CapabilityGuard.test.js
@@ -0,0 +1,174 @@
+import { describe, expect, it, vi } from "vitest";
+import { CapabilityGuard } from "../src/core/CapabilityGuard.js";
+function makeState(overrides) {
+ return {
+ error: null,
+ lastModified: (/* @__PURE__ */ new Date()).toISOString(),
+ messages: [],
+ metadata: { agentId: "agent-001" },
+ status: "running",
+ ...overrides
+ };
+}
+function makeCallToolInstruction(toolName, args = {}) {
+ return {
+ payload: {
+ toolCalling: {
+ apiName: toolName,
+ arguments: JSON.stringify(args),
+ id: "tool-call-123"
+ }
+ },
+ type: "call_tool"
+ };
+}
+function makeNonToolInstruction() {
+ return {
+ payload: { messages: [] },
+ type: "call_llm"
+ };
+}
+describe("CapabilityGuard", () => {
+ describe("wrap", () => {
+ it("should pass through non-call_tool instructions", async () => {
+ const check = vi.fn();
+ const guard = new CapabilityGuard(check);
+ const innerExecutor = vi.fn().mockResolvedValue({
+ events: [],
+ newState: makeState()
+ });
+ const wrapped = guard.wrap(innerExecutor);
+ const instruction = makeNonToolInstruction();
+ const state = makeState();
+ await wrapped(instruction, state);
+ expect(check).not.toHaveBeenCalled();
+ expect(innerExecutor).toHaveBeenCalledWith(instruction, state, void 0);
+ });
+ it("should allow tool call when capability check passes", async () => {
+ const check = vi.fn().mockResolvedValue({
+ allowed: true,
+ tokenId: "ctk_abc"
+ });
+ const guard = new CapabilityGuard(check);
+ const innerResult = { events: [{ type: "tool_result" }], newState: makeState() };
+ const innerExecutor = vi.fn().mockResolvedValue(innerResult);
+ const wrapped = guard.wrap(innerExecutor);
+ const instruction = makeCallToolInstruction("swap", { amount: 100 });
+ const state = makeState();
+ const result = await wrapped(instruction, state);
+ expect(check).toHaveBeenCalledWith({
+ agentId: "agent-001",
+ args: { amount: 100 },
+ toolName: "swap"
+ });
+ expect(innerExecutor).toHaveBeenCalled();
+ expect(result).toBe(innerResult);
+ });
+ it("should block tool call when capability check fails", async () => {
+ const check = vi.fn().mockResolvedValue({
+ allowed: false,
+ reason: "No valid token for tool:swap"
+ });
+ const guard = new CapabilityGuard(check);
+ const innerExecutor = vi.fn();
+ const wrapped = guard.wrap(innerExecutor);
+ const instruction = makeCallToolInstruction("swap", { amount: 100 });
+ const state = makeState();
+ const result = await wrapped(instruction, state);
+ expect(innerExecutor).not.toHaveBeenCalled();
+ expect(result.events).toHaveLength(1);
+ expect(result.events[0].result.blocked).toBe(true);
+ const lastMessage = result.newState.messages.at(-1);
+ expect(lastMessage?.role).toBe("tool");
+ const content = JSON.parse(lastMessage?.content);
+ expect(content.error).toBe("Capability denied");
+ expect(content.reason).toBe("No valid token for tool:swap");
+ });
+ it("should use default reason when none provided", async () => {
+ const check = vi.fn().mockResolvedValue({
+ allowed: false
+ });
+ const guard = new CapabilityGuard(check);
+ const innerExecutor = vi.fn();
+ const wrapped = guard.wrap(innerExecutor);
+ const result = await wrapped(
+ makeCallToolInstruction("bridge"),
+ makeState()
+ );
+ const content = JSON.parse(result.newState.messages.at(-1)?.content);
+ expect(content.reason).toBe("No valid capability token for this action.");
+ });
+ it("should handle missing toolCalling payload gracefully", async () => {
+ const check = vi.fn();
+ const guard = new CapabilityGuard(check);
+ const innerExecutor = vi.fn().mockResolvedValue({
+ events: [],
+ newState: makeState()
+ });
+ const wrapped = guard.wrap(innerExecutor);
+ const instruction = { payload: {}, type: "call_tool" };
+ await wrapped(instruction, makeState());
+ expect(check).not.toHaveBeenCalled();
+ expect(innerExecutor).toHaveBeenCalled();
+ });
+ it("should handle invalid JSON arguments", async () => {
+ const check = vi.fn().mockResolvedValue({
+ allowed: true
+ });
+ const guard = new CapabilityGuard(check);
+ const innerExecutor = vi.fn().mockResolvedValue({
+ events: [],
+ newState: makeState()
+ });
+ const wrapped = guard.wrap(innerExecutor);
+ const instruction = {
+ payload: {
+ toolCalling: {
+ apiName: "swap",
+ arguments: "not-valid-json{{{",
+ id: "tool-42"
+ }
+ },
+ type: "call_tool"
+ };
+ await wrapped(instruction, makeState());
+ expect(check).toHaveBeenCalledWith(
+ expect.objectContaining({ args: {} })
+ );
+ });
+ it('should use "unknown" agentId when not set in metadata', async () => {
+ const check = vi.fn().mockResolvedValue({
+ allowed: true
+ });
+ const guard = new CapabilityGuard(check);
+ const innerExecutor = vi.fn().mockResolvedValue({
+ events: [],
+ newState: makeState()
+ });
+ const wrapped = guard.wrap(innerExecutor);
+ const state = makeState({ metadata: {} });
+ await wrapped(makeCallToolInstruction("test"), state);
+ expect(check).toHaveBeenCalledWith(
+ expect.objectContaining({ agentId: "unknown" })
+ );
+ });
+ it("should pass context through to inner executor", async () => {
+ const check = vi.fn().mockResolvedValue({
+ allowed: true
+ });
+ const guard = new CapabilityGuard(check);
+ const innerExecutor = vi.fn().mockResolvedValue({
+ events: [],
+ newState: makeState()
+ });
+ const wrapped = guard.wrap(innerExecutor);
+ const context = { phase: "tool_result" };
+ await wrapped(makeCallToolInstruction("test"), makeState(), context);
+ expect(innerExecutor).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.anything(),
+ context
+ );
+ });
+ });
+});
diff --git a/packages/agent-runtime/tests/DecisionJournal.test.js b/packages/agent-runtime/tests/DecisionJournal.test.js
new file mode 100644
index 000000000..58d05c174
--- /dev/null
+++ b/packages/agent-runtime/tests/DecisionJournal.test.js
@@ -0,0 +1,55 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { DecisionJournal } from "../src/core/DecisionJournal.js";
+const entry = {
+ agentId: "agt-1",
+ chosenBranch: "auto-execute",
+ confidence: 0.9,
+ decisionType: "intervention",
+ inputsSnapshot: { usd: 1200 },
+ reasoning: "under threshold"
+};
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+describe("DecisionJournal", () => {
+ it("forwards the entry to the sink", () => {
+ const sink = vi.fn();
+ new DecisionJournal(sink).record(entry);
+ expect(sink).toHaveBeenCalledWith(entry);
+ });
+ it("is a no-op when no sink is provided", () => {
+ expect(() => new DecisionJournal().record(entry)).not.toThrow();
+ });
+ it("does not throw into the decision path when the sink throws synchronously", () => {
+ const sink = vi.fn(() => {
+ throw new Error("db down");
+ });
+ const journal = new DecisionJournal(sink);
+ expect(() => journal.record(entry)).not.toThrow();
+ expect(sink).toHaveBeenCalledOnce();
+ });
+ it("does not reject the caller when the async sink rejects", async () => {
+ let reject;
+ const pending = new Promise((_, r) => {
+ reject = r;
+ });
+ const sink = vi.fn(() => pending);
+ const journal = new DecisionJournal(sink);
+ expect(() => journal.record(entry)).not.toThrow();
+ reject(new Error("write failed"));
+ await expect(pending.catch(() => "swallowed")).resolves.toBe("swallowed");
+ });
+ it("returns synchronously without awaiting a slow sink", () => {
+ let settled = false;
+ const sink = vi.fn(
+ () => new Promise((resolve) => {
+ setTimeout(() => {
+ settled = true;
+ resolve(void 0);
+ }, 1e3);
+ })
+ );
+ new DecisionJournal(sink).record(entry);
+ expect(settled).toBe(false);
+ });
+});
diff --git a/packages/agent-runtime/tests/ExitDecisionEngine.test.js b/packages/agent-runtime/tests/ExitDecisionEngine.test.js
new file mode 100644
index 000000000..ead82fc75
--- /dev/null
+++ b/packages/agent-runtime/tests/ExitDecisionEngine.test.js
@@ -0,0 +1,141 @@
+import { describe, expect, it } from "vitest";
+import {
+ decideExit,
+ decideLadderedExit,
+ ladderMultiple,
+ moonbagFraction,
+ pct
+} from "../src/core/ExitDecisionEngine.js";
+const ENTRY = 10n ** 18n;
+const OPENED_AT = 1e12;
+const x = (mult) => BigInt(Math.round(Number(ENTRY) * mult));
+const pos = (overrides = {}) => ({
+ entryQuoteWei: ENTRY,
+ openedAt: OPENED_AT,
+ ...overrides
+});
+describe("pct", () => {
+ it("treats null/undefined/blank as disabled (null), NOT 0", () => {
+ expect(pct(null)).toBeNull();
+ expect(pct(void 0)).toBeNull();
+ expect(pct(Number.NaN)).toBeNull();
+ });
+ it("passes through finite numbers, including 0", () => {
+ expect(pct(0)).toBe(0);
+ expect(pct(15)).toBe(15);
+ expect(pct(-10)).toBe(-10);
+ });
+});
+describe("decideExit", () => {
+ it("holds (null) when nothing triggers", () => {
+ const p = pos({ stopLossPct: 20, takeProfitPct: 50 });
+ expect(decideExit(p, x(1.1), x(1.1), OPENED_AT)).toBeNull();
+ });
+ it("returns null for a non-positive entry", () => {
+ expect(decideExit(pos({ entryQuoteWei: 0n }), x(2), x(2), OPENED_AT)).toBeNull();
+ });
+ it("stop-loss wins over take-profit when both thresholds are crossed", () => {
+ const p = pos({ stopLossPct: -25, takeProfitPct: 10 });
+ expect(decideExit(p, x(1.2), x(1.2), OPENED_AT)).toBe("stop_loss");
+ });
+ it("fires a normal stop-loss below the threshold", () => {
+ const p = pos({ stopLossPct: 20 });
+ expect(decideExit(p, x(0.79), x(1), OPENED_AT)).toBe("stop_loss");
+ expect(decideExit(p, x(0.81), x(1), OPENED_AT)).toBeNull();
+ });
+ it("never fires a null take-profit or null trailing-stop (the Number(null) trap)", () => {
+ const p = pos({ stopLossPct: null, takeProfitPct: null, trailingStopPct: null });
+ expect(decideExit(p, x(5), x(10), OPENED_AT)).toBeNull();
+ });
+ it("trailing-stop fires only after a peak above entry", () => {
+ const p = pos({ trailingStopPct: 20 });
+ expect(decideExit(p, x(0.75), x(0.95), OPENED_AT)).toBeNull();
+ expect(decideExit(p, x(1.6), x(2), OPENED_AT)).toBe("trailing_stop");
+ expect(decideExit(p, x(1.8), x(2), OPENED_AT)).toBeNull();
+ });
+ it("take-profit fires at/above the threshold", () => {
+ const p = pos({ takeProfitPct: 50 });
+ expect(decideExit(p, x(1.5), x(1.5), OPENED_AT)).toBe("take_profit");
+ expect(decideExit(p, x(1.49), x(1.49), OPENED_AT)).toBeNull();
+ });
+ it("timeout uses the injected clock, not wall time", () => {
+ const p = pos({ maxHoldSeconds: 3600 });
+ const justBefore = OPENED_AT + 3599 * 1e3;
+ const atLimit = OPENED_AT + 3600 * 1e3;
+ expect(decideExit(p, x(1), x(1), justBefore)).toBeNull();
+ expect(decideExit(p, x(1), x(1), atLimit)).toBe("timeout");
+ });
+ describe("signal-flip", () => {
+ const bearish = { confidence: 0.9, minConfidence: 0.7, signal: "bearish" };
+ it("fires only while underwater and only when sentiment is passed", () => {
+ const p = pos({ stopLossPct: 50 });
+ expect(decideExit(p, x(0.8), x(1), OPENED_AT, bearish)).toBe("signal_flip");
+ expect(decideExit(p, x(1.2), x(1.2), OPENED_AT, bearish)).toBeNull();
+ expect(decideExit(p, x(0.8), x(1), OPENED_AT)).toBeNull();
+ });
+ it("ignores a low-confidence or non-bearish read", () => {
+ const p = pos({ stopLossPct: 50 });
+ expect(
+ decideExit(p, x(0.8), x(1), OPENED_AT, { confidence: 0.5, minConfidence: 0.7, signal: "bearish" })
+ ).toBeNull();
+ expect(
+ decideExit(p, x(0.8), x(1), OPENED_AT, { confidence: 0.9, signal: "bullish" })
+ ).toBeNull();
+ });
+ it("never overrides a hard stop-loss", () => {
+ const p = pos({ stopLossPct: 10 });
+ expect(decideExit(p, x(0.85), x(1), OPENED_AT, bearish)).toBe("stop_loss");
+ });
+ });
+});
+describe("ladderMultiple / moonbagFraction", () => {
+ it("ladderMultiple requires > 1, else null", () => {
+ expect(ladderMultiple(2)).toBe(2);
+ expect(ladderMultiple(1)).toBeNull();
+ expect(ladderMultiple(0.5)).toBeNull();
+ expect(ladderMultiple(null)).toBeNull();
+ });
+ it("moonbagFraction defaults to 0.15 and clamps to [0, 0.95]", () => {
+ expect(moonbagFraction(null)).toBeCloseTo(0.15);
+ expect(moonbagFraction(20)).toBeCloseTo(0.2);
+ expect(moonbagFraction(-5)).toBe(0);
+ expect(moonbagFraction(300)).toBe(0.95);
+ });
+});
+describe("decideLadderedExit", () => {
+ it("is classic full-exit when the ladder is off", () => {
+ const p = pos({ takeProfitPct: 50 });
+ expect(decideLadderedExit(p, x(1.5), x(1.5), OPENED_AT)).toEqual({
+ reason: "take_profit",
+ sellFraction: 1
+ });
+ expect(decideLadderedExit(p, x(1.1), x(1.1), OPENED_AT)).toBeNull();
+ });
+ it("banks initials at N\xD7 and NEVER returns a 100% exit while up", () => {
+ const p = pos({ initialsOutMultiple: 2, moonbagMinPct: 15 });
+ const d = decideLadderedExit(p, x(2), x(2), OPENED_AT);
+ expect(d?.reason).toBe("take_initials");
+ expect(d?.recoversInitials).toBe(true);
+ expect(d?.sellFraction).toBeCloseTo(0.5);
+ expect(d?.sellFraction).toBeLessThan(1);
+ });
+ it("scales the take-initials sell down as the multiple grows", () => {
+ const p = pos({ initialsOutMultiple: 5 });
+ expect(decideLadderedExit(p, x(5), x(5), OPENED_AT)?.sellFraction).toBeCloseTo(0.2);
+ });
+ it("does not take initials twice - after recovery, the moon bag rides", () => {
+ const p = pos({ initialsOutMultiple: 2, initialsRecovered: true, takeProfitPct: 400 });
+ expect(decideLadderedExit(p, x(3), x(3), OPENED_AT)).toBeNull();
+ expect(decideLadderedExit(p, x(5), x(5), OPENED_AT)).toEqual({
+ reason: "take_profit",
+ sellFraction: 1
+ });
+ });
+ it("protective exits are always full exits and stop-loss wins", () => {
+ const p = pos({ initialsOutMultiple: 2, stopLossPct: 20 });
+ expect(decideLadderedExit(p, x(0.75), x(2), OPENED_AT)).toEqual({
+ reason: "stop_loss",
+ sellFraction: 1
+ });
+ });
+});
diff --git a/packages/agent-runtime/tests/GeneralChatAgent.test.js b/packages/agent-runtime/tests/GeneralChatAgent.test.js
new file mode 100644
index 000000000..e155598a7
--- /dev/null
+++ b/packages/agent-runtime/tests/GeneralChatAgent.test.js
@@ -0,0 +1,1763 @@
+import { describe, expect, it } from "vitest";
+import { GeneralChatAgent } from "../src/agents/GeneralChatAgent.js";
+describe("GeneralChatAgent", () => {
+ const mockModelRuntimeConfig = {
+ model: "gpt-4o-mini",
+ provider: "openai"
+ };
+ const createMockState = (overrides) => ({
+ operationId: "test-session",
+ status: "running",
+ messages: [],
+ toolManifestMap: {},
+ stepCount: 0,
+ usage: {
+ llm: { apiCalls: 0, processingTimeMs: 0, tokens: { input: 0, output: 0, total: 0 } },
+ tools: { totalCalls: 0, totalTimeMs: 0, byTool: [] },
+ humanInteraction: {
+ approvalRequests: 0,
+ promptRequests: 0,
+ selectRequests: 0,
+ totalWaitingTimeMs: 0
+ }
+ },
+ cost: {
+ calculatedAt: (/* @__PURE__ */ new Date()).toISOString(),
+ currency: "USD",
+ llm: { byModel: [], currency: "USD", total: 0 },
+ tools: { byTool: [], currency: "USD", total: 0 },
+ total: 0
+ },
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
+ lastModified: (/* @__PURE__ */ new Date()).toISOString(),
+ ...overrides
+ });
+ const createMockContext = (phase, payload) => ({
+ phase,
+ payload,
+ session: {
+ // Note: AgentRuntimeContext.session uses sessionId for backward compatibility
+ sessionId: "test-session",
+ messageCount: 0,
+ status: "running",
+ stepCount: 0
+ }
+ });
+ describe("init and user_input phase", () => {
+ it("should return call_llm instruction for init phase", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const state = createMockState({
+ messages: [{ role: "user", content: "Hello" }]
+ });
+ const context = createMockContext("init", { model: "gpt-4o-mini", provider: "openai" });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual({
+ type: "call_llm",
+ payload: {
+ messages: state.messages,
+ model: "gpt-4o-mini",
+ provider: "openai"
+ }
+ });
+ });
+ it("should return call_llm instruction for user_input phase", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const state = createMockState({
+ messages: [{ role: "user", content: "What is the weather?" }]
+ });
+ const context = createMockContext("user_input", {
+ message: { role: "user", content: "What is the weather?" }
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual({
+ type: "call_llm",
+ payload: {
+ messages: state.messages,
+ message: { role: "user", content: "What is the weather?" }
+ }
+ });
+ });
+ });
+ describe("llm_result phase", () => {
+ it("should return finish when no tool calls", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const state = createMockState();
+ const context = createMockContext("llm_result", {
+ hasToolsCalling: false,
+ toolsCalling: [],
+ parentMessageId: "msg-1"
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual({
+ type: "finish",
+ reason: "completed",
+ reasonDetail: "LLM response completed without tool calls"
+ });
+ });
+ it("should return call_tool for single tool that does not need intervention", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const toolCall = {
+ id: "call-1",
+ identifier: "test-plugin",
+ apiName: "test-api",
+ arguments: "{}",
+ type: "default"
+ };
+ const state = createMockState({
+ toolManifestMap: {
+ "test-plugin": {
+ identifier: "test-plugin"
+ // No humanIntervention config = no intervention needed
+ }
+ }
+ });
+ const context = createMockContext("llm_result", {
+ hasToolsCalling: true,
+ toolsCalling: [toolCall],
+ parentMessageId: "msg-1"
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual([
+ {
+ type: "call_tool",
+ payload: {
+ parentMessageId: "msg-1",
+ toolCalling: toolCall
+ }
+ }
+ ]);
+ });
+ it("should return call_tools_batch for multiple tools that do not need intervention", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const toolCalls = [
+ {
+ id: "call-1",
+ identifier: "plugin-1",
+ apiName: "api-1",
+ arguments: "{}",
+ type: "default"
+ },
+ {
+ id: "call-2",
+ identifier: "plugin-2",
+ apiName: "api-2",
+ arguments: "{}",
+ type: "default"
+ }
+ ];
+ const state = createMockState({
+ toolManifestMap: {
+ "plugin-1": { identifier: "plugin-1" },
+ "plugin-2": { identifier: "plugin-2" }
+ }
+ });
+ const context = createMockContext("llm_result", {
+ hasToolsCalling: true,
+ toolsCalling: toolCalls,
+ parentMessageId: "msg-1"
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual([
+ {
+ type: "call_tools_batch",
+ payload: {
+ parentMessageId: "msg-1",
+ toolsCalling: toolCalls
+ }
+ }
+ ]);
+ });
+ it("should handle invalid JSON in tool arguments gracefully", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const toolCall = {
+ id: "call-1",
+ identifier: "test-plugin",
+ apiName: "test-api",
+ arguments: "{invalid json}",
+ // Invalid JSON
+ type: "default"
+ };
+ const state = createMockState({
+ toolManifestMap: {
+ "test-plugin": {
+ identifier: "test-plugin"
+ // No humanIntervention config
+ }
+ }
+ });
+ const context = createMockContext("llm_result", {
+ hasToolsCalling: true,
+ toolsCalling: [toolCall],
+ parentMessageId: "msg-1"
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual([
+ {
+ type: "call_tool",
+ payload: {
+ parentMessageId: "msg-1",
+ toolCalling: toolCall
+ }
+ }
+ ]);
+ });
+ it("should return request_human_approve for tools requiring intervention", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const toolCall = {
+ id: "call-1",
+ identifier: "dangerous-plugin",
+ apiName: "delete-api",
+ arguments: "{}",
+ type: "default"
+ };
+ const state = createMockState({
+ toolManifestMap: {
+ "dangerous-plugin": {
+ identifier: "dangerous-plugin",
+ humanIntervention: "require"
+ // Always require approval
+ }
+ }
+ });
+ const context = createMockContext("llm_result", {
+ hasToolsCalling: true,
+ toolsCalling: [toolCall],
+ parentMessageId: "msg-1"
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual([
+ {
+ type: "request_human_approve",
+ pendingToolsCalling: [toolCall],
+ reason: "human_intervention_required"
+ }
+ ]);
+ });
+ it("should return both call_tools_batch and request_human_approve for mixed tools", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const safeTool = {
+ id: "call-1",
+ identifier: "safe-plugin",
+ apiName: "read-api",
+ arguments: "{}",
+ type: "default"
+ };
+ const dangerousTool = {
+ id: "call-2",
+ identifier: "dangerous-plugin",
+ apiName: "delete-api",
+ arguments: "{}",
+ type: "default"
+ };
+ const state = createMockState({
+ toolManifestMap: {
+ "safe-plugin": {
+ identifier: "safe-plugin"
+ // No intervention
+ },
+ "dangerous-plugin": {
+ identifier: "dangerous-plugin",
+ humanIntervention: "require"
+ }
+ }
+ });
+ const context = createMockContext("llm_result", {
+ hasToolsCalling: true,
+ toolsCalling: [safeTool, dangerousTool],
+ parentMessageId: "msg-1"
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual([
+ {
+ type: "call_tool",
+ payload: {
+ parentMessageId: "msg-1",
+ toolCalling: safeTool
+ }
+ },
+ {
+ type: "request_human_approve",
+ pendingToolsCalling: [dangerousTool],
+ reason: "human_intervention_required"
+ }
+ ]);
+ });
+ });
+ describe("tool_result phase", () => {
+ describe("GTD async tasks", () => {
+ it("should return exec_task for single async task (execTask)", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const state = createMockState();
+ const context = createMockContext("tool_result", {
+ parentMessageId: "tool-msg-1",
+ stop: true,
+ data: {
+ state: {
+ type: "execTask",
+ parentMessageId: "exec-parent-msg",
+ task: { instruction: "Do something async", timeout: 3e4 }
+ }
+ }
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual({
+ type: "exec_task",
+ payload: {
+ parentMessageId: "exec-parent-msg",
+ task: { instruction: "Do something async", timeout: 3e4 }
+ }
+ });
+ });
+ it("should return exec_tasks for multiple async tasks (execTasks)", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const state = createMockState();
+ const tasks = [
+ { instruction: "Task 1", timeout: 3e4 },
+ { instruction: "Task 2", timeout: 3e4 }
+ ];
+ const context = createMockContext("tool_result", {
+ parentMessageId: "tool-msg-1",
+ stop: true,
+ data: {
+ state: {
+ type: "execTasks",
+ parentMessageId: "exec-parent-msg",
+ tasks
+ }
+ }
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual({
+ type: "exec_tasks",
+ payload: {
+ parentMessageId: "exec-parent-msg",
+ tasks
+ }
+ });
+ });
+ it("should return exec_client_task for single client-side async task (execClientTask)", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const state = createMockState();
+ const context = createMockContext("tool_result", {
+ parentMessageId: "tool-msg-1",
+ stop: true,
+ data: {
+ state: {
+ type: "execClientTask",
+ parentMessageId: "exec-parent-msg",
+ task: { type: "localFile", path: "/path/to/file" }
+ }
+ }
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual({
+ type: "exec_client_task",
+ payload: {
+ parentMessageId: "exec-parent-msg",
+ task: { type: "localFile", path: "/path/to/file" }
+ }
+ });
+ });
+ it("should return exec_client_tasks for multiple client-side async tasks (execClientTasks)", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const state = createMockState();
+ const tasks = [
+ { type: "localFile", path: "/path/to/file1" },
+ { type: "localFile", path: "/path/to/file2" }
+ ];
+ const context = createMockContext("tool_result", {
+ parentMessageId: "tool-msg-1",
+ stop: true,
+ data: {
+ state: {
+ type: "execClientTasks",
+ parentMessageId: "exec-parent-msg",
+ tasks
+ }
+ }
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual({
+ type: "exec_client_tasks",
+ payload: {
+ parentMessageId: "exec-parent-msg",
+ tasks
+ }
+ });
+ });
+ it("should not trigger exec_task when stop is false", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const state = createMockState({
+ messages: [
+ { role: "user", content: "Hello" },
+ { role: "assistant", content: "" },
+ { role: "tool", content: "Result", tool_call_id: "call-1" }
+ ]
+ });
+ const context = createMockContext("tool_result", {
+ parentMessageId: "tool-msg-1",
+ stop: false,
+ // stop is false, should not trigger exec_task
+ data: {
+ state: {
+ type: "execTask",
+ parentMessageId: "exec-parent-msg",
+ task: { instruction: "Do something async" }
+ }
+ }
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual({
+ type: "call_llm",
+ payload: {
+ messages: state.messages,
+ model: "gpt-4o-mini",
+ parentMessageId: "tool-msg-1",
+ provider: "openai",
+ tools: void 0
+ }
+ });
+ });
+ it("should not trigger exec_task when data.state is undefined", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const state = createMockState({
+ messages: [
+ { role: "user", content: "Hello" },
+ { role: "assistant", content: "" },
+ { role: "tool", content: "Result", tool_call_id: "call-1" }
+ ]
+ });
+ const context = createMockContext("tool_result", {
+ parentMessageId: "tool-msg-1",
+ stop: true,
+ data: {}
+ // No state property
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual({
+ type: "call_llm",
+ payload: {
+ messages: state.messages,
+ model: "gpt-4o-mini",
+ parentMessageId: "tool-msg-1",
+ provider: "openai",
+ tools: void 0
+ }
+ });
+ });
+ });
+ it("should return call_llm when no pending tools", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const state = createMockState({
+ messages: [
+ { role: "user", content: "Hello" },
+ { role: "assistant", content: "", tools: [] },
+ { role: "tool", content: "Result", tool_call_id: "call-1" }
+ ]
+ });
+ const context = createMockContext("tool_result", {
+ parentMessageId: "tool-msg-1",
+ result: { data: "result" }
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual({
+ type: "call_llm",
+ payload: {
+ messages: state.messages,
+ model: "gpt-4o-mini",
+ parentMessageId: "tool-msg-1",
+ provider: "openai",
+ tools: void 0
+ }
+ });
+ });
+ it("should return request_human_approve when there are pending tools", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const pendingPlugin = {
+ id: "call-2",
+ identifier: "plugin-2",
+ apiName: "api-2",
+ arguments: "{}",
+ type: "default"
+ };
+ const state = createMockState({
+ messages: [
+ { role: "user", content: "Hello" },
+ { role: "assistant", content: "", tools: [] },
+ { role: "tool", content: "Result", tool_call_id: "call-1" },
+ {
+ role: "tool",
+ content: "",
+ tool_call_id: "call-2",
+ plugin: pendingPlugin,
+ pluginIntervention: { status: "pending" }
+ }
+ ]
+ });
+ const context = createMockContext("tool_result", {
+ parentMessageId: "tool-msg-1"
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual({
+ type: "request_human_approve",
+ pendingToolsCalling: [pendingPlugin],
+ reason: "Some tools still pending approval",
+ skipCreateToolMessage: true
+ });
+ });
+ });
+ describe("tools_batch_result phase", () => {
+ it("should return call_llm when no pending tools", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const state = createMockState({
+ messages: [
+ { role: "user", content: "Hello" },
+ { role: "assistant", content: "", tools: [] },
+ { role: "tool", content: "Result 1", tool_call_id: "call-1" },
+ { role: "tool", content: "Result 2", tool_call_id: "call-2" }
+ ]
+ });
+ const context = createMockContext("tools_batch_result", {
+ parentMessageId: "tool-msg-2"
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual({
+ type: "call_llm",
+ payload: {
+ messages: state.messages,
+ model: "gpt-4o-mini",
+ parentMessageId: "tool-msg-2",
+ provider: "openai",
+ tools: void 0
+ }
+ });
+ });
+ it("should return request_human_approve when there are pending tools", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const pendingPlugin = {
+ id: "call-3",
+ identifier: "plugin-3",
+ apiName: "api-3",
+ arguments: "{}",
+ type: "default"
+ };
+ const state = createMockState({
+ messages: [
+ { role: "user", content: "Hello" },
+ { role: "assistant", content: "", tools: [] },
+ { role: "tool", content: "Result 1", tool_call_id: "call-1" },
+ { role: "tool", content: "Result 2", tool_call_id: "call-2" },
+ {
+ role: "tool",
+ content: "",
+ tool_call_id: "call-3",
+ plugin: pendingPlugin,
+ pluginIntervention: { status: "pending" }
+ }
+ ]
+ });
+ const context = createMockContext("tools_batch_result", {
+ parentMessageId: "tool-msg-2"
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual({
+ type: "request_human_approve",
+ pendingToolsCalling: [pendingPlugin],
+ reason: "Some tools still pending approval",
+ skipCreateToolMessage: true
+ });
+ });
+ });
+ describe("error phase", () => {
+ it("should return finish instruction with error details", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const state = createMockState();
+ const errorMessage = "Network timeout";
+ const context = createMockContext("error", {
+ error: new Error(errorMessage)
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual({
+ type: "finish",
+ reason: "error_recovery",
+ reasonDetail: errorMessage
+ });
+ });
+ it("should handle error without message", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const state = createMockState();
+ const context = createMockContext("error", { error: {} });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual({
+ type: "finish",
+ reason: "error_recovery",
+ reasonDetail: "Unknown error occurred"
+ });
+ });
+ });
+ describe("unified abort check", () => {
+ it("should handle abort at llm_result phase when state is interrupted", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const toolCalls = [
+ {
+ apiName: "search",
+ arguments: '{"query":"test"}',
+ id: "call-1",
+ identifier: "web-browsing",
+ type: "default"
+ }
+ ];
+ const state = createMockState({
+ status: "interrupted"
+ // State is interrupted
+ });
+ const context = createMockContext("llm_result", {
+ hasToolsCalling: true,
+ toolsCalling: toolCalls,
+ parentMessageId: "msg-123"
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual({
+ type: "resolve_aborted_tools",
+ payload: {
+ parentMessageId: "msg-123",
+ toolsCalling: toolCalls
+ }
+ });
+ });
+ it("should handle abort at tool_result phase when state is interrupted", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const state = createMockState({
+ status: "interrupted",
+ messages: [
+ {
+ id: "tool-msg-1",
+ role: "tool",
+ content: "",
+ plugin: {
+ id: "call-1",
+ identifier: "bash",
+ apiName: "bash",
+ arguments: '{"command":"ls"}',
+ type: "builtin"
+ },
+ pluginIntervention: { status: "pending" }
+ }
+ ]
+ });
+ const context = createMockContext("tool_result", {
+ parentMessageId: "msg-456"
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual({
+ type: "resolve_aborted_tools",
+ payload: {
+ parentMessageId: "msg-456",
+ toolsCalling: [
+ {
+ id: "call-1",
+ identifier: "bash",
+ apiName: "bash",
+ arguments: '{"command":"ls"}',
+ type: "builtin"
+ }
+ ]
+ }
+ });
+ });
+ it("should return finish when state is interrupted with no tools", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const state = createMockState({
+ status: "interrupted"
+ });
+ const context = createMockContext("llm_result", {
+ hasToolsCalling: false,
+ toolsCalling: [],
+ parentMessageId: "msg-789"
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual({
+ type: "finish",
+ reason: "user_requested",
+ reasonDetail: "Operation cancelled by user"
+ });
+ });
+ it("should continue normal flow when state is not interrupted", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const toolCalls = [
+ {
+ apiName: "search",
+ arguments: '{"query":"test"}',
+ id: "call-1",
+ identifier: "web-browsing",
+ type: "default"
+ }
+ ];
+ const state = createMockState({
+ status: "running"
+ // Normal running state
+ });
+ const context = createMockContext("llm_result", {
+ hasToolsCalling: true,
+ toolsCalling: toolCalls,
+ parentMessageId: "msg-999"
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual([
+ {
+ type: "call_tool",
+ payload: {
+ parentMessageId: "msg-999",
+ toolCalling: toolCalls[0]
+ }
+ }
+ ]);
+ });
+ });
+ describe("unified abort check", () => {
+ it("should handle abort at human_abort phase when state is interrupted", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const toolCalls = [
+ {
+ apiName: "search",
+ arguments: '{"query":"test"}',
+ id: "call-1",
+ identifier: "web-browsing",
+ type: "default"
+ }
+ ];
+ const state = createMockState({
+ status: "interrupted"
+ // Trigger unified abort check
+ });
+ const context = createMockContext("human_abort", {
+ reason: "user_cancelled",
+ parentMessageId: "msg-123",
+ hasToolsCalling: true,
+ toolsCalling: toolCalls,
+ result: { content: "", tool_calls: [] }
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual({
+ type: "resolve_aborted_tools",
+ payload: {
+ parentMessageId: "msg-123",
+ toolsCalling: toolCalls
+ }
+ });
+ });
+ });
+ describe("human_abort phase", () => {
+ it("should return resolve_aborted_tools when there are pending tool calls", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const toolCalls = [
+ {
+ apiName: "search",
+ arguments: '{"query":"test"}',
+ id: "call-1",
+ identifier: "web-browsing",
+ type: "default"
+ },
+ {
+ apiName: "getWeather",
+ arguments: '{"location":"NYC"}',
+ id: "call-2",
+ identifier: "weather-plugin",
+ type: "default"
+ }
+ ];
+ const state = createMockState();
+ const context = createMockContext("human_abort", {
+ reason: "user_cancelled",
+ parentMessageId: "msg-123",
+ hasToolsCalling: true,
+ toolsCalling: toolCalls,
+ result: { content: "", tool_calls: [] }
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual({
+ type: "resolve_aborted_tools",
+ payload: {
+ parentMessageId: "msg-123",
+ toolsCalling: toolCalls
+ }
+ });
+ });
+ it("should return finish when there are no tool calls", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const state = createMockState();
+ const context = createMockContext("human_abort", {
+ reason: "user_cancelled",
+ parentMessageId: "msg-123",
+ hasToolsCalling: false,
+ toolsCalling: [],
+ result: { content: "Hello", tool_calls: [] }
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual({
+ type: "finish",
+ reason: "user_requested",
+ reasonDetail: "user_cancelled"
+ });
+ });
+ it("should return finish when toolsCalling is undefined", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const state = createMockState();
+ const context = createMockContext("human_abort", {
+ reason: "operation_cancelled",
+ parentMessageId: "msg-456",
+ hasToolsCalling: false,
+ result: { content: "Partial response", tool_calls: [] }
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual({
+ type: "finish",
+ reason: "user_requested",
+ reasonDetail: "operation_cancelled"
+ });
+ });
+ it("should return finish when toolsCalling is empty array", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const state = createMockState();
+ const context = createMockContext("human_abort", {
+ reason: "user_cancelled",
+ parentMessageId: "msg-789",
+ hasToolsCalling: true,
+ toolsCalling: [],
+ result: { content: "", tool_calls: [] }
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual({
+ type: "finish",
+ reason: "user_requested",
+ reasonDetail: "user_cancelled"
+ });
+ });
+ });
+ describe("task_result phase (single task)", () => {
+ it("should return call_llm when task completed", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const state = createMockState({
+ messages: [
+ { role: "user", content: "Execute task" },
+ { role: "assistant", content: "" },
+ { role: "task", content: "Task result", metadata: { instruction: "Do task" } }
+ ]
+ });
+ const context = createMockContext("task_result", {
+ parentMessageId: "task-parent-msg",
+ result: {
+ success: true,
+ taskMessageId: "task-1",
+ threadId: "thread-1",
+ result: "Task result"
+ }
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual({
+ type: "call_llm",
+ payload: {
+ messages: state.messages,
+ model: "gpt-4o-mini",
+ parentMessageId: "task-parent-msg",
+ provider: "openai",
+ tools: void 0
+ }
+ });
+ });
+ it("should return call_llm even when task failed", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const state = createMockState({
+ messages: [
+ { role: "user", content: "Execute task" },
+ { role: "assistant", content: "" },
+ { role: "task", content: "Task failed: timeout", metadata: { instruction: "Do task" } }
+ ]
+ });
+ const context = createMockContext("task_result", {
+ parentMessageId: "task-parent-msg",
+ result: {
+ success: false,
+ taskMessageId: "task-1",
+ threadId: "thread-1",
+ error: "Task timeout after 1800000ms"
+ }
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual({
+ type: "call_llm",
+ payload: {
+ messages: state.messages,
+ model: "gpt-4o-mini",
+ parentMessageId: "task-parent-msg",
+ provider: "openai",
+ tools: void 0
+ }
+ });
+ });
+ });
+ describe("tasks_batch_result phase (multiple tasks)", () => {
+ it("should return call_llm when tasks completed", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const state = createMockState({
+ messages: [
+ { role: "user", content: "Execute tasks" },
+ { role: "assistant", content: "" },
+ { role: "task", content: "Task 1 result", metadata: { instruction: "Do task 1" } },
+ { role: "task", content: "Task 2 result", metadata: { instruction: "Do task 2" } }
+ ]
+ });
+ const context = createMockContext("tasks_batch_result", {
+ parentMessageId: "task-parent-msg",
+ results: [
+ { success: true, taskMessageId: "task-1", threadId: "thread-1", result: "Task 1 result" },
+ { success: true, taskMessageId: "task-2", threadId: "thread-2", result: "Task 2 result" }
+ ]
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual({
+ type: "call_llm",
+ payload: {
+ messages: [
+ ...state.messages,
+ {
+ content: "All tasks above have been completed. Please summarize the results or continue with your response following user query language.",
+ role: "user"
+ }
+ ],
+ model: "gpt-4o-mini",
+ parentMessageId: "task-parent-msg",
+ provider: "openai",
+ tools: void 0
+ }
+ });
+ });
+ it("should return call_llm even when some tasks failed", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const state = createMockState({
+ messages: [
+ { role: "user", content: "Execute tasks" },
+ { role: "assistant", content: "" },
+ { role: "task", content: "Task 1 result", metadata: { instruction: "Do task 1" } },
+ { role: "task", content: "Task failed: timeout", metadata: { instruction: "Do task 2" } }
+ ]
+ });
+ const context = createMockContext("tasks_batch_result", {
+ parentMessageId: "task-parent-msg",
+ results: [
+ { success: true, taskMessageId: "task-1", threadId: "thread-1", result: "Task 1 result" },
+ {
+ success: false,
+ taskMessageId: "task-2",
+ threadId: "thread-2",
+ error: "Task timeout after 1800000ms"
+ }
+ ]
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual({
+ type: "call_llm",
+ payload: {
+ messages: [
+ ...state.messages,
+ {
+ content: "All tasks above have been completed. Please summarize the results or continue with your response following user query language.",
+ role: "user"
+ }
+ ],
+ model: "gpt-4o-mini",
+ parentMessageId: "task-parent-msg",
+ provider: "openai",
+ tools: void 0
+ }
+ });
+ });
+ });
+ describe("unknown phase", () => {
+ it("should return finish instruction for unknown phase", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const state = createMockState();
+ const context = createMockContext("unknown_phase");
+ const result = await agent.runner(context, state);
+ expect(result).toEqual({
+ type: "finish",
+ reason: "agent_decision",
+ reasonDetail: "Unknown phase: unknown_phase"
+ });
+ });
+ });
+ describe("intervention checking", () => {
+ it("should check intervention at API level when configured", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const toolCall = {
+ id: "call-1",
+ identifier: "plugin",
+ apiName: "dangerous-api",
+ arguments: "{}",
+ type: "default"
+ };
+ const state = createMockState({
+ toolManifestMap: {
+ plugin: {
+ identifier: "plugin",
+ // Tool-level config
+ humanIntervention: "never",
+ api: [
+ {
+ name: "safe-api"
+ // Safe API
+ },
+ {
+ name: "dangerous-api",
+ // API-level config overrides tool-level
+ humanIntervention: "require"
+ }
+ ]
+ }
+ }
+ });
+ const context = createMockContext("llm_result", {
+ hasToolsCalling: true,
+ toolsCalling: [toolCall],
+ parentMessageId: "msg-1"
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual([
+ {
+ type: "request_human_approve",
+ pendingToolsCalling: [toolCall],
+ reason: "human_intervention_required"
+ }
+ ]);
+ });
+ it("should execute all tools when user approvalMode is auto-run", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const toolCall = {
+ id: "call-1",
+ identifier: "dangerous-tool",
+ apiName: "delete",
+ arguments: "{}",
+ type: "default"
+ };
+ const state = createMockState({
+ toolManifestMap: {
+ "dangerous-tool": {
+ identifier: "dangerous-tool",
+ humanIntervention: "required"
+ // Tool requires approval
+ }
+ },
+ userInterventionConfig: {
+ approvalMode: "auto-run",
+ // But user config overrides
+ allowList: []
+ }
+ });
+ const context = createMockContext("llm_result", {
+ hasToolsCalling: true,
+ toolsCalling: [toolCall],
+ parentMessageId: "msg-1"
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual([
+ {
+ type: "call_tool",
+ payload: {
+ parentMessageId: "msg-1",
+ toolCalling: toolCall
+ }
+ }
+ ]);
+ });
+ it("should respect allowList when approvalMode is allow-list", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const allowedTool = {
+ id: "call-1",
+ identifier: "bash",
+ apiName: "bash",
+ arguments: '{"command":"ls"}',
+ type: "builtin"
+ };
+ const blockedTool = {
+ id: "call-2",
+ identifier: "bash",
+ apiName: "dangerous-command",
+ arguments: '{"command":"rm -rf"}',
+ type: "builtin"
+ };
+ const state = createMockState({
+ toolManifestMap: {
+ bash: {
+ identifier: "bash",
+ humanIntervention: "never"
+ // Tool doesn't require approval by default
+ }
+ },
+ userInterventionConfig: {
+ approvalMode: "allow-list",
+ allowList: ["bash/bash"]
+ // Only bash/bash is allowed
+ }
+ });
+ const context = createMockContext("llm_result", {
+ hasToolsCalling: true,
+ toolsCalling: [allowedTool, blockedTool],
+ parentMessageId: "msg-1"
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual([
+ {
+ type: "call_tool",
+ payload: {
+ parentMessageId: "msg-1",
+ toolCalling: allowedTool
+ }
+ },
+ {
+ type: "request_human_approve",
+ pendingToolsCalling: [blockedTool],
+ reason: "human_intervention_required"
+ }
+ ]);
+ });
+ it("should use tool config when approvalMode is manual", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const safeTool = {
+ id: "call-1",
+ identifier: "web-search",
+ apiName: "search",
+ arguments: "{}",
+ type: "default"
+ };
+ const dangerousTool = {
+ id: "call-2",
+ identifier: "bash",
+ apiName: "bash",
+ arguments: "{}",
+ type: "builtin"
+ };
+ const state = createMockState({
+ toolManifestMap: {
+ "web-search": {
+ identifier: "web-search",
+ humanIntervention: "never"
+ // Safe tool
+ },
+ "bash": {
+ identifier: "bash",
+ humanIntervention: "required"
+ // Dangerous tool
+ }
+ },
+ userInterventionConfig: {
+ approvalMode: "manual"
+ // Use tool's own config
+ }
+ });
+ const context = createMockContext("llm_result", {
+ hasToolsCalling: true,
+ toolsCalling: [safeTool, dangerousTool],
+ parentMessageId: "msg-1"
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual([
+ {
+ type: "call_tool",
+ payload: {
+ parentMessageId: "msg-1",
+ toolCalling: safeTool
+ }
+ },
+ {
+ type: "request_human_approve",
+ pendingToolsCalling: [dangerousTool],
+ reason: "human_intervention_required"
+ }
+ ]);
+ });
+ it('should always require intervention for tools with "always" policy even in auto-run mode', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const alwaysTool = {
+ id: "call-1",
+ identifier: "agent-builder",
+ apiName: "installPlugin",
+ arguments: '{"identifier":"some-plugin","source":"market"}',
+ type: "builtin"
+ };
+ const state = createMockState({
+ toolManifestMap: {
+ "agent-builder": {
+ identifier: "agent-builder",
+ api: [
+ {
+ name: "installPlugin",
+ humanIntervention: "always"
+ // Always requires intervention
+ }
+ ]
+ }
+ },
+ userInterventionConfig: {
+ approvalMode: "auto-run",
+ // User has auto-run enabled
+ allowList: []
+ }
+ });
+ const context = createMockContext("llm_result", {
+ hasToolsCalling: true,
+ toolsCalling: [alwaysTool],
+ parentMessageId: "msg-1"
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual([
+ {
+ type: "request_human_approve",
+ pendingToolsCalling: [alwaysTool],
+ reason: "human_intervention_required"
+ }
+ ]);
+ });
+ it('should always require intervention for tools with tool-level "always" policy', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const alwaysTool = {
+ id: "call-1",
+ identifier: "sensitive-plugin",
+ apiName: "sensitiveAction",
+ arguments: "{}",
+ type: "default"
+ };
+ const state = createMockState({
+ toolManifestMap: {
+ "sensitive-plugin": {
+ identifier: "sensitive-plugin",
+ humanIntervention: "always"
+ // Tool-level always policy
+ }
+ },
+ userInterventionConfig: {
+ approvalMode: "auto-run",
+ allowList: []
+ }
+ });
+ const context = createMockContext("llm_result", {
+ hasToolsCalling: true,
+ toolsCalling: [alwaysTool],
+ parentMessageId: "msg-1"
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual([
+ {
+ type: "request_human_approve",
+ pendingToolsCalling: [alwaysTool],
+ reason: "human_intervention_required"
+ }
+ ]);
+ });
+ it('should handle mixed tools with "always" and regular policies in auto-run mode', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const regularTool = {
+ id: "call-1",
+ identifier: "web-search",
+ apiName: "search",
+ arguments: "{}",
+ type: "default"
+ };
+ const alwaysTool = {
+ id: "call-2",
+ identifier: "agent-builder",
+ apiName: "installPlugin",
+ arguments: "{}",
+ type: "builtin"
+ };
+ const state = createMockState({
+ toolManifestMap: {
+ "web-search": {
+ identifier: "web-search",
+ humanIntervention: "required"
+ // Would be bypassed by auto-run
+ },
+ "agent-builder": {
+ identifier: "agent-builder",
+ api: [
+ {
+ name: "installPlugin",
+ humanIntervention: "always"
+ // Cannot be bypassed
+ }
+ ]
+ }
+ },
+ userInterventionConfig: {
+ approvalMode: "auto-run",
+ allowList: []
+ }
+ });
+ const context = createMockContext("llm_result", {
+ hasToolsCalling: true,
+ toolsCalling: [regularTool, alwaysTool],
+ parentMessageId: "msg-1"
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual([
+ {
+ type: "call_tool",
+ payload: {
+ parentMessageId: "msg-1",
+ toolCalling: regularTool
+ }
+ },
+ {
+ type: "request_human_approve",
+ pendingToolsCalling: [alwaysTool],
+ reason: "human_intervention_required"
+ }
+ ]);
+ });
+ it('should handle "always" policy with rule-based configuration', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const toolCall = {
+ id: "call-1",
+ identifier: "file-system",
+ apiName: "writeFile",
+ arguments: '{"path":"/etc/passwd"}',
+ type: "builtin"
+ };
+ const state = createMockState({
+ toolManifestMap: {
+ "file-system": {
+ identifier: "file-system",
+ api: [
+ {
+ name: "writeFile",
+ // Rule-based config with 'always' policy
+ humanIntervention: [{ policy: "always" }]
+ }
+ ]
+ }
+ },
+ userInterventionConfig: {
+ approvalMode: "auto-run",
+ allowList: []
+ }
+ });
+ const context = createMockContext("llm_result", {
+ hasToolsCalling: true,
+ toolsCalling: [toolCall],
+ parentMessageId: "msg-1"
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual([
+ {
+ type: "request_human_approve",
+ pendingToolsCalling: [toolCall],
+ reason: "human_intervention_required"
+ }
+ ]);
+ });
+ });
+ describe("headless mode (for async tasks)", () => {
+ it("should execute all tools directly in headless mode including those requiring approval", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const toolCall = {
+ id: "call-1",
+ identifier: "dangerous-tool",
+ apiName: "delete",
+ arguments: "{}",
+ type: "default"
+ };
+ const state = createMockState({
+ toolManifestMap: {
+ "dangerous-tool": {
+ identifier: "dangerous-tool",
+ humanIntervention: "required"
+ // Tool requires approval
+ }
+ },
+ userInterventionConfig: {
+ approvalMode: "headless"
+ // Headless mode for async tasks
+ }
+ });
+ const context = createMockContext("llm_result", {
+ hasToolsCalling: true,
+ toolsCalling: [toolCall],
+ parentMessageId: "msg-1"
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual([
+ {
+ type: "call_tool",
+ payload: {
+ parentMessageId: "msg-1",
+ toolCalling: toolCall
+ }
+ }
+ ]);
+ });
+ it('should execute tools with "always" policy in headless mode', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const alwaysTool = {
+ id: "call-1",
+ identifier: "agent-builder",
+ apiName: "installPlugin",
+ arguments: '{"identifier":"some-plugin","source":"market"}',
+ type: "builtin"
+ };
+ const state = createMockState({
+ toolManifestMap: {
+ "agent-builder": {
+ identifier: "agent-builder",
+ api: [
+ {
+ name: "installPlugin",
+ humanIntervention: "always"
+ // Always requires intervention normally
+ }
+ ]
+ }
+ },
+ userInterventionConfig: {
+ approvalMode: "headless"
+ // Headless mode bypasses even 'always'
+ }
+ });
+ const context = createMockContext("llm_result", {
+ hasToolsCalling: true,
+ toolsCalling: [alwaysTool],
+ parentMessageId: "msg-1"
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual([
+ {
+ type: "call_tool",
+ payload: {
+ parentMessageId: "msg-1",
+ toolCalling: alwaysTool
+ }
+ }
+ ]);
+ });
+ it("should skip security blacklisted tools in headless mode", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const blacklistedTool = {
+ id: "call-1",
+ identifier: "bash",
+ apiName: "bash",
+ arguments: '{"command":"rm -rf /"}',
+ // Matches security blacklist
+ type: "builtin"
+ };
+ const state = createMockState({
+ toolManifestMap: {
+ bash: {
+ identifier: "bash",
+ humanIntervention: "never"
+ }
+ },
+ userInterventionConfig: {
+ approvalMode: "headless"
+ }
+ // Using default security blacklist which blocks "rm -rf /"
+ });
+ const context = createMockContext("llm_result", {
+ hasToolsCalling: true,
+ toolsCalling: [blacklistedTool],
+ parentMessageId: "msg-1"
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual([]);
+ });
+ it("should handle mixed tools in headless mode - execute safe ones, skip blacklisted", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const safeTool = {
+ id: "call-1",
+ identifier: "web-search",
+ apiName: "search",
+ arguments: '{"query":"hello"}',
+ type: "default"
+ };
+ const blacklistedTool = {
+ id: "call-2",
+ identifier: "bash",
+ apiName: "bash",
+ arguments: '{"command":"rm -rf /"}',
+ // Matches security blacklist
+ type: "builtin"
+ };
+ const alwaysTool = {
+ id: "call-3",
+ identifier: "agent-builder",
+ apiName: "installPlugin",
+ arguments: "{}",
+ type: "builtin"
+ };
+ const state = createMockState({
+ toolManifestMap: {
+ "web-search": {
+ identifier: "web-search",
+ humanIntervention: "required"
+ },
+ "bash": {
+ identifier: "bash"
+ },
+ "agent-builder": {
+ identifier: "agent-builder",
+ api: [
+ {
+ name: "installPlugin",
+ humanIntervention: "always"
+ }
+ ]
+ }
+ },
+ userInterventionConfig: {
+ approvalMode: "headless"
+ }
+ });
+ const context = createMockContext("llm_result", {
+ hasToolsCalling: true,
+ toolsCalling: [safeTool, blacklistedTool, alwaysTool],
+ parentMessageId: "msg-1"
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual([
+ {
+ type: "call_tools_batch",
+ payload: {
+ parentMessageId: "msg-1",
+ toolsCalling: [safeTool, alwaysTool]
+ }
+ }
+ ]);
+ });
+ it("should execute multiple tools as batch in headless mode", async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: "test-session",
+ modelRuntimeConfig: mockModelRuntimeConfig
+ });
+ const tool1 = {
+ id: "call-1",
+ identifier: "search",
+ apiName: "search",
+ arguments: "{}",
+ type: "default"
+ };
+ const tool2 = {
+ id: "call-2",
+ identifier: "crawl",
+ apiName: "crawl",
+ arguments: "{}",
+ type: "default"
+ };
+ const state = createMockState({
+ toolManifestMap: {
+ search: { identifier: "search", humanIntervention: "required" },
+ crawl: { identifier: "crawl", humanIntervention: "always" }
+ },
+ userInterventionConfig: {
+ approvalMode: "headless"
+ }
+ });
+ const context = createMockContext("llm_result", {
+ hasToolsCalling: true,
+ toolsCalling: [tool1, tool2],
+ parentMessageId: "msg-1"
+ });
+ const result = await agent.runner(context, state);
+ expect(result).toEqual([
+ {
+ type: "call_tools_batch",
+ payload: {
+ parentMessageId: "msg-1",
+ toolsCalling: [tool1, tool2]
+ }
+ }
+ ]);
+ });
+ });
+});
diff --git a/packages/agent-runtime/tests/GuardChain.test.js b/packages/agent-runtime/tests/GuardChain.test.js
new file mode 100644
index 000000000..625a9ceeb
--- /dev/null
+++ b/packages/agent-runtime/tests/GuardChain.test.js
@@ -0,0 +1,519 @@
+import { describe, expect, it, vi } from "vitest";
+import { TradeGuard } from "../src/core/TradeGuard.js";
+import {
+ GUARD_LAYER_ORDER,
+ GuardChain,
+ analyzeGuardCoverage,
+ guardLayerLabel,
+ guardLayerWeight
+} from "../src/core/GuardChain.js";
+import { SpendGuard } from "../src/core/SpendGuard.js";
+import { createX402Hook } from "../src/core/X402Hook.js";
+const FIXED_NOW = 17e11;
+function tickingClock() {
+ let t = 0;
+ return () => t += 1;
+}
+function makeChain(options = {}) {
+ return new GuardChain({ clock: tickingClock(), now: () => FIXED_NOW, ...options });
+}
+function req(overrides = {}) {
+ return {
+ apiName: "executeSwap",
+ arguments: { chainId: 1, fromToken: "ETH", toToken: "USDC" },
+ identifier: "solana_swap",
+ ...overrides
+ };
+}
+function layer(verdict, id) {
+ return verdict.layers.find((l) => l.layer === id);
+}
+describe("GuardChain", () => {
+ describe("trace", () => {
+ it("emits one result per layer, in declared order", async () => {
+ const verdict = await makeChain().evaluate(req());
+ expect(verdict.layers.map((l) => l.layer)).toEqual(GUARD_LAYER_ORDER);
+ });
+ it("runs every layer to completion rather than short-circuiting on a block", async () => {
+ const chain = makeChain({
+ checkCapability: async () => ({ allowed: false, reason: "no token" }),
+ defiGuard: new TradeGuard(),
+ spendGuard: new SpendGuard({ perTxMaxUsd: 10 })
+ });
+ const verdict = await chain.evaluate(req({ valueUsd: 5e3 }));
+ expect(layer(verdict, "capability").status).toBe("block");
+ expect(layer(verdict, "spend_guard").status).toBe("block");
+ expect(layer(verdict, "spend_guard").code).toBe("CAP_PER_TX");
+ });
+ it("labels every layer with a renderable name", async () => {
+ const verdict = await makeChain().evaluate(req());
+ for (const result of verdict.layers) {
+ expect(result.label).toBe(guardLayerLabel(result.layer));
+ expect(result.label.length).toBeGreaterThan(0);
+ expect(result.reason.length).toBeGreaterThan(0);
+ }
+ });
+ it("stamps evaluatedAt from the injected clock", async () => {
+ const verdict = await makeChain().evaluate(req());
+ expect(verdict.evaluatedAt).toBe(FIXED_NOW);
+ });
+ });
+ describe("verdict", () => {
+ it("allows a call that clears every applicable layer", async () => {
+ const chain = makeChain({
+ checkCapability: async () => ({ allowed: true }),
+ checkPermission: async () => ({ allowed: true, level: "autonomous" }),
+ defiGuard: new TradeGuard(),
+ spendGuard: new SpendGuard({ perTxMaxUsd: 1e5 })
+ });
+ const verdict = await chain.evaluate(req({ valueUsd: 500 }));
+ expect(verdict.decision).toBe("allow");
+ expect(verdict.blockedBy).toBeUndefined();
+ });
+ it("escalates to block when any layer blocks, naming the layer", async () => {
+ const chain = makeChain({ spendGuard: new SpendGuard({ perTxMaxUsd: 100 }) });
+ const verdict = await chain.evaluate(req({ valueUsd: 5e3 }));
+ expect(verdict.decision).toBe("block");
+ expect(verdict.blockedBy).toBe("spend_guard");
+ expect(verdict.code).toBe("CAP_PER_TX");
+ expect(verdict.reason).toContain("Spend Envelope");
+ });
+ it("prefers a block over a concurrent approval_required", async () => {
+ const chain = makeChain({
+ checkPermission: async () => ({ allowed: false, level: "approval-required" }),
+ spendGuard: new SpendGuard({ perTxMaxUsd: 100 })
+ });
+ const verdict = await chain.evaluate(req({ valueUsd: 5e3 }));
+ expect(verdict.decision).toBe("block");
+ expect(verdict.blockedBy).toBe("spend_guard");
+ });
+ it("reports require_approval when the strongest outcome is an approval gate", async () => {
+ const chain = makeChain({
+ checkPermission: async () => ({ allowed: false, level: "approval-required" })
+ });
+ const verdict = await chain.evaluate(req({ valueUsd: 100 }));
+ expect(verdict.decision).toBe("require_approval");
+ expect(verdict.blockedBy).toBeUndefined();
+ });
+ it("breaks ties toward the earlier layer, matching runtime firing order", async () => {
+ const chain = makeChain({
+ checkCapability: async () => ({ allowed: false, reason: "capability first" }),
+ checkPermission: async () => ({ allowed: false, level: "forbidden" })
+ });
+ const verdict = await chain.evaluate(req());
+ expect(verdict.blockedBy).toBe("capability");
+ });
+ });
+ describe("intervention layers", () => {
+ it("blocks on the runtime default blacklist when none is supplied", async () => {
+ const verdict = await makeChain().evaluate(
+ req({ apiName: "bash", arguments: { command: "rm -rf /" }, identifier: "bash" })
+ );
+ expect(layer(verdict, "security_blacklist").status).toBe("block");
+ expect(layer(verdict, "security_blacklist").code).toBe("SECURITY_BLACKLIST");
+ expect(verdict.decision).toBe("block");
+ });
+ it("honours an explicitly supplied blacklist", async () => {
+ const verdict = await makeChain().evaluate(
+ req({
+ apiName: "transferAll",
+ arguments: { destination: "0xdeadbeef" },
+ identifier: "agent-wallet",
+ securityBlacklist: [
+ { description: "Known drainer address", match: { destination: "0xdead*" } }
+ ]
+ })
+ );
+ expect(layer(verdict, "security_blacklist").status).toBe("block");
+ expect(layer(verdict, "security_blacklist").reason).toContain("drainer");
+ });
+ it("notes that headless mode skips blacklisted tools instead of surfacing them", async () => {
+ const verdict = await makeChain().evaluate(
+ req({
+ apiName: "bash",
+ approvalMode: "headless",
+ arguments: { command: "rm -rf /" },
+ identifier: "bash"
+ })
+ );
+ expect(layer(verdict, "security_blacklist").reason).toContain("headless");
+ });
+ it("lets auto-run downgrade a `required` policy", async () => {
+ const manual = await makeChain().evaluate(req({ interventionConfig: "required" }));
+ const auto = await makeChain().evaluate(
+ req({ approvalMode: "auto-run", interventionConfig: "required" })
+ );
+ expect(layer(manual, "intervention").status).toBe("approval_required");
+ expect(layer(auto, "intervention").status).toBe("pass");
+ });
+ it("never lets an approval mode downgrade an `always` policy", async () => {
+ for (const mode of ["auto-run", "headless", "allow-list"]) {
+ const verdict = await makeChain().evaluate(
+ req({ approvalMode: mode, interventionConfig: "always" })
+ );
+ expect(layer(verdict, "intervention").status).toBe("approval_required");
+ }
+ });
+ it("honours the session allow list under allow-list mode", async () => {
+ const listed = await makeChain().evaluate(
+ req({
+ allowList: ["solana_swap/executeSwap"],
+ approvalMode: "allow-list",
+ interventionConfig: "required"
+ })
+ );
+ const absent = await makeChain().evaluate(
+ req({ allowList: [], approvalMode: "allow-list", interventionConfig: "required" })
+ );
+ expect(layer(listed, "intervention").status).toBe("pass");
+ expect(layer(absent, "intervention").status).toBe("approval_required");
+ });
+ });
+ describe("capability and permission guards", () => {
+ it("marks both as skipped for batched dispatch", async () => {
+ const chain = makeChain({
+ checkCapability: async () => ({ allowed: true }),
+ checkPermission: async () => ({ allowed: true })
+ });
+ const verdict = await chain.evaluate(req({ executionPath: "batch" }));
+ expect(layer(verdict, "capability").status).toBe("skipped");
+ expect(layer(verdict, "capability").code).toBe("BATCH_BYPASS");
+ expect(layer(verdict, "permission").status).toBe("skipped");
+ });
+ it("does not invoke the injected checkers when batching", async () => {
+ const checkCapability = vi.fn().mockResolvedValue({ allowed: true });
+ const chain = makeChain({ checkCapability });
+ await chain.evaluate(req({ executionPath: "batch" }));
+ expect(checkCapability).not.toHaveBeenCalled();
+ });
+ it("treats notify-and-proceed as a passing warning", async () => {
+ const chain = makeChain({
+ checkPermission: async () => ({ allowed: true, level: "notify-and-proceed" })
+ });
+ const verdict = await chain.evaluate(req());
+ expect(layer(verdict, "permission").status).toBe("warn");
+ expect(verdict.decision).toBe("allow");
+ expect(verdict.warnings.some((w) => w.includes("Agent Permission"))).toBe(true);
+ });
+ it("fails closed when a checker throws", async () => {
+ const chain = makeChain({
+ checkPermission: async () => {
+ throw new Error("permissions service unreachable");
+ }
+ });
+ const verdict = await chain.evaluate(req());
+ expect(layer(verdict, "permission").status).toBe("error");
+ expect(verdict.decision).toBe("block");
+ expect(verdict.reason).toContain("permissions service unreachable");
+ });
+ });
+ describe("defi guard layer", () => {
+ it("skips unregistered identifiers and says so explicitly", async () => {
+ const chain = makeChain({ defiGuard: new TradeGuard() });
+ const verdict = await chain.evaluate(
+ req({ identifier: "some-new-tool", valueUsd: 1e3 })
+ );
+ expect(layer(verdict, "defi_guard").status).toBe("skipped");
+ expect(layer(verdict, "defi_guard").code).toBe("NOT_REGISTERED");
+ });
+ it("requires approval above the auto-execute ceiling", async () => {
+ const chain = makeChain({ defiGuard: new TradeGuard() });
+ const verdict = await chain.evaluate(req({ userTier: "pro", valueUsd: 5e4 }));
+ expect(layer(verdict, "defi_guard").status).toBe("approval_required");
+ expect(verdict.decision).toBe("require_approval");
+ });
+ it("blocks above the tier transaction ceiling", async () => {
+ const chain = makeChain({ defiGuard: new TradeGuard() });
+ const verdict = await chain.evaluate(req({ userTier: "free", valueUsd: 25e3 }));
+ expect(layer(verdict, "defi_guard").status).toBe("block");
+ expect(verdict.blockedBy).toBe("defi_guard");
+ });
+ it("surfaces guard warnings and MEV parameter adjustments on the verdict", async () => {
+ const chain = makeChain({ defiGuard: new TradeGuard() });
+ const verdict = await chain.evaluate(
+ req({ arguments: { chainId: 1, slippage: 3 }, userTier: "pro", valueUsd: 5e4 })
+ );
+ expect(verdict.warnings.some((w) => w.includes("Slippage reduced"))).toBe(true);
+ expect(verdict.modifiedArguments).toMatchObject({ slippage: 1 });
+ });
+ it("flags an unregistered protocol as unverifiable", async () => {
+ const chain = makeChain({ defiGuard: new TradeGuard() });
+ const verdict = await chain.evaluate(
+ req({ protocol: "uniswap", userTier: "pro", valueUsd: 5e3 })
+ );
+ expect(verdict.blindSpots.some((s) => s.code === "PROTOCOL_UNVERIFIED")).toBe(true);
+ });
+ });
+ describe("spend envelope layer", () => {
+ it("exempts inflow operations from spend caps", async () => {
+ const chain = makeChain({ spendGuard: new SpendGuard({ perTxMaxUsd: 1 }) });
+ const verdict = await chain.evaluate(
+ req({ apiName: "withdraw", identifier: "lending-tool", valueUsd: 5e5 })
+ );
+ expect(layer(verdict, "spend_guard").status).toBe("skipped");
+ expect(layer(verdict, "spend_guard").reason).toContain("exempt");
+ });
+ it("gates approvals so the firewall can vet the grantee", async () => {
+ const chain = makeChain({
+ spendGuard: new SpendGuard({
+ firewall: { denyDestinations: ["0xbad"] }
+ })
+ });
+ const verdict = await chain.evaluate(
+ req({
+ apiName: "approve",
+ destination: "0xBAD",
+ identifier: "token-approvals",
+ valueUsd: 0
+ })
+ );
+ expect(layer(verdict, "spend_guard").status).toBe("block");
+ expect(layer(verdict, "spend_guard").code).toBe("FIREWALL_DENY_DEST");
+ });
+ it("skips read-only APIs with a distinct reason", async () => {
+ const chain = makeChain({ spendGuard: new SpendGuard({ perTxMaxUsd: 1 }) });
+ const verdict = await chain.evaluate(
+ req({ apiName: "getQuote", identifier: "solana_swap" })
+ );
+ expect(layer(verdict, "spend_guard").reason).toContain("Read-only");
+ });
+ });
+ describe("x402 layer", () => {
+ const requirements = {
+ accepts: [
+ {
+ asset: "0x1111111111111111111111111111111111111111",
+ description: "API access",
+ maxAmountRequired: "2000000",
+ network: "eip155:8453",
+ payTo: "0xfeed",
+ resource: "https://api.example.com/data",
+ scheme: "exact"
+ }
+ ],
+ x402Version: 1
+ };
+ it("is skipped when the call is not x402-metered", async () => {
+ const chain = makeChain({ x402Hook: createX402Hook() });
+ const verdict = await chain.evaluate(req());
+ expect(layer(verdict, "x402").status).toBe("skipped");
+ });
+ it("passes a payment inside the hourly budget", async () => {
+ const chain = makeChain({ x402Hook: createX402Hook(5) });
+ const verdict = await chain.evaluate(
+ req({
+ x402: {
+ amountSpentThisHourUsdc: 0,
+ currentBalanceUsdc: 100,
+ requirements,
+ url: "https://api.example.com/data"
+ }
+ })
+ );
+ expect(layer(verdict, "x402").status).toBe("pass");
+ });
+ it("queues a payment that would exceed the hourly budget", async () => {
+ const chain = makeChain({ x402Hook: createX402Hook(5) });
+ const verdict = await chain.evaluate(
+ req({
+ x402: {
+ amountSpentThisHourUsdc: 4.5,
+ currentBalanceUsdc: 100,
+ requirements,
+ url: "https://api.example.com/data"
+ }
+ })
+ );
+ expect(layer(verdict, "x402").status).toBe("approval_required");
+ expect(verdict.decision).toBe("require_approval");
+ });
+ it("blocks a payment the wallet cannot cover", async () => {
+ const chain = makeChain({ x402Hook: createX402Hook(5) });
+ const verdict = await chain.evaluate(
+ req({
+ x402: {
+ amountSpentThisHourUsdc: 0,
+ currentBalanceUsdc: 0.5,
+ requirements,
+ url: "https://api.example.com/data"
+ }
+ })
+ );
+ expect(layer(verdict, "x402").status).toBe("block");
+ });
+ });
+ describe("blind spots", () => {
+ it("flags a registered mutating call with no resolved USD value", async () => {
+ const chain = makeChain({ defiGuard: new TradeGuard() });
+ const verdict = await chain.evaluate(req({ arguments: { amount: "0.5" } }));
+ const spot = verdict.blindSpots.find((s) => s.code === "VALUE_UNRESOLVED");
+ expect(spot).toBeDefined();
+ expect(spot.severity).toBe("critical");
+ });
+ it("does not flag VALUE_UNRESOLVED once a value is supplied", async () => {
+ const chain = makeChain({ defiGuard: new TradeGuard() });
+ const verdict = await chain.evaluate(req({ valueUsd: 1200 }));
+ expect(verdict.blindSpots.some((s) => s.code === "VALUE_UNRESOLVED")).toBe(false);
+ });
+ it("flags a fund-moving tool absent from the DeFi registry", async () => {
+ const chain = makeChain({ defiGuard: new TradeGuard() });
+ const verdict = await chain.evaluate(
+ req({ apiName: "executeSwap", identifier: "community-dex-tool", valueUsd: 9e3 })
+ );
+ const spot = verdict.blindSpots.find((s) => s.code === "TOOL_UNREGISTERED");
+ expect(spot).toBeDefined();
+ expect(spot.remediation).toContain("community-dex-tool");
+ });
+ it("flags batched dispatch as bypassing the decorator guards", async () => {
+ const verdict = await makeChain().evaluate(req({ executionPath: "batch" }));
+ expect(verdict.blindSpots.some((s) => s.code === "BATCH_BYPASS")).toBe(true);
+ });
+ it("flags an outflow with no spend envelope attached", async () => {
+ const verdict = await makeChain().evaluate(req({ valueUsd: 4e3 }));
+ const spot = verdict.blindSpots.find((s) => s.code === "SPEND_UNSCOPED");
+ expect(spot).toBeDefined();
+ expect(spot.severity).toBe("critical");
+ });
+ it("does not flag SPEND_UNSCOPED when an envelope is configured", async () => {
+ const chain = makeChain({ spendGuard: new SpendGuard({ perTxMaxUsd: 1e5 }) });
+ const verdict = await chain.evaluate(req({ valueUsd: 4e3 }));
+ expect(verdict.blindSpots.some((s) => s.code === "SPEND_UNSCOPED")).toBe(false);
+ });
+ it("flags unwired capability and permission checkers", async () => {
+ const verdict = await makeChain().evaluate(req());
+ expect(verdict.blindSpots.some((s) => s.code === "CAPABILITY_UNWIRED")).toBe(true);
+ expect(verdict.blindSpots.some((s) => s.code === "PERMISSION_UNWIRED")).toBe(true);
+ });
+ it("reports read-only DeFi calls as unanalyzed at info severity", async () => {
+ const chain = makeChain({ defiGuard: new TradeGuard() });
+ const verdict = await chain.evaluate(req({ apiName: "getQuote" }));
+ const spot = verdict.blindSpots.find((s) => s.code === "READONLY_UNANALYZED");
+ expect(spot).toBeDefined();
+ expect(spot.severity).toBe("info");
+ });
+ it("orders findings critical-first", async () => {
+ const chain = makeChain({ defiGuard: new TradeGuard() });
+ const verdict = await chain.evaluate(req({ executionPath: "batch" }));
+ const rank = { critical: 0, info: 2, warning: 1 };
+ const seq = verdict.blindSpots.map((s) => rank[s.severity]);
+ expect(seq).toEqual([...seq].sort((a, b) => a - b));
+ });
+ it("reports no critical findings for a fully-wired evaluation", async () => {
+ const chain = makeChain({
+ checkCapability: async () => ({ allowed: true }),
+ checkPermission: async () => ({ allowed: true, level: "autonomous" }),
+ defiGuard: new TradeGuard(),
+ spendGuard: new SpendGuard({ perTxMaxUsd: 1e5 })
+ });
+ const verdict = await chain.evaluate(req({ valueUsd: 2500 }));
+ expect(verdict.blindSpots.filter((s) => s.severity === "critical")).toEqual([]);
+ });
+ });
+ describe("coverage score", () => {
+ it("reports 100 when every applicable layer evaluated the call", async () => {
+ const chain = makeChain({
+ checkCapability: async () => ({ allowed: true }),
+ checkPermission: async () => ({ allowed: true, level: "autonomous" }),
+ defiGuard: new TradeGuard(),
+ spendGuard: new SpendGuard({ perTxMaxUsd: 1e5 })
+ });
+ const verdict = await chain.evaluate(req({ valueUsd: 2500 }));
+ expect(verdict.coverageScore).toBe(100);
+ });
+ it("drops when guards are missing, even though the verdict is allow", async () => {
+ const verdict = await makeChain().evaluate(req({ valueUsd: 2500 }));
+ expect(verdict.decision).toBe("allow");
+ expect(verdict.coverageScore).toBeLessThan(50);
+ });
+ it("does not penalise a read-only call for skipping the spend envelope", async () => {
+ const readOnly = makeChain({
+ checkCapability: async () => ({ allowed: true }),
+ checkPermission: async () => ({ allowed: true }),
+ defiGuard: new TradeGuard()
+ });
+ const verdict = await readOnly.evaluate(req({ apiName: "getQuote" }));
+ expect(verdict.coverageScore).toBe(100);
+ expect(verdict.blindSpots.some((s) => s.code === "READONLY_UNANALYZED")).toBe(true);
+ });
+ it('separates "the layer ran" from "the layer checked something"', async () => {
+ const chain = makeChain({
+ checkCapability: async () => ({ allowed: true }),
+ checkPermission: async () => ({ allowed: true, level: "autonomous" }),
+ defiGuard: new TradeGuard(),
+ spendGuard: new SpendGuard({ perTxMaxUsd: 1e5 })
+ });
+ const verdict = await chain.evaluate(req({ arguments: { amount: "0.5" } }));
+ expect(verdict.coverageScore).toBe(100);
+ expect(verdict.decision).toBe("allow");
+ expect(verdict.blindSpots.some((s) => s.code === "VALUE_UNRESOLVED")).toBe(true);
+ });
+ it("falls when batching removes the decorator guards from the surface", async () => {
+ const options = {
+ checkCapability: async () => ({ allowed: true }),
+ checkPermission: async () => ({ allowed: true, level: "autonomous" }),
+ defiGuard: new TradeGuard(),
+ spendGuard: new SpendGuard({ perTxMaxUsd: 1e5 })
+ };
+ const single = await makeChain(options).evaluate(req({ valueUsd: 2500 }));
+ const batched = await makeChain(options).evaluate(
+ req({ executionPath: "batch", valueUsd: 2500 })
+ );
+ expect(batched.coverageScore).toBeLessThan(single.coverageScore);
+ });
+ });
+ describe("determinism", () => {
+ it("returns an identical verdict for identical input", async () => {
+ const build = () => makeChain({
+ defiGuard: new TradeGuard(),
+ spendGuard: new SpendGuard({ perTxMaxUsd: 1e5 })
+ });
+ const a = await build().evaluate(req({ userTier: "pro", valueUsd: 42e3 }));
+ const b = await build().evaluate(req({ userTier: "pro", valueUsd: 42e3 }));
+ const strip = (v) => ({
+ ...v,
+ layers: v.layers.map(({ elapsedMs: _e, detail: _d, ...rest }) => rest),
+ totalElapsedMs: 0
+ });
+ expect(strip(a)).toEqual(strip(b));
+ });
+ });
+});
+describe("analyzeGuardCoverage", () => {
+ it("reports the registry itself as fully covered when given no argument", () => {
+ const report = analyzeGuardCoverage();
+ expect(report.coveragePercent).toBe(100);
+ expect(report.unregistered).toEqual([]);
+ expect(report.registered.length).toBeGreaterThan(0);
+ });
+ it("separates registered from unregistered identifiers", () => {
+ const report = analyzeGuardCoverage(["solana_swap", "unknown-tool"]);
+ expect(report.registered.map((e) => e.identifier)).toEqual(["solana_swap"]);
+ expect(report.unregistered.map((e) => e.identifier)).toEqual(["unknown-tool"]);
+ expect(report.coveragePercent).toBe(50);
+ });
+ it("deduplicates the supplied identifiers", () => {
+ const report = analyzeGuardCoverage(["solana_swap", "solana_swap"]);
+ expect(report.registered).toHaveLength(1);
+ expect(report.coveragePercent).toBe(100);
+ });
+ it("lists the mutating API registry", () => {
+ const report = analyzeGuardCoverage();
+ expect(report.mutatingApis).toContain("executeSwap");
+ expect(report.mutatingApis).toEqual([...report.mutatingApis].sort());
+ });
+ it("treats an empty deployment as fully covered rather than dividing by zero", () => {
+ expect(analyzeGuardCoverage([]).coveragePercent).toBe(100);
+ });
+});
+describe("layer metadata", () => {
+ it("exposes a label and a positive weight for every layer", () => {
+ for (const id of GUARD_LAYER_ORDER) {
+ expect(guardLayerLabel(id)).toBeTruthy();
+ expect(guardLayerWeight(id)).toBeGreaterThan(0);
+ }
+ });
+ it("weights sum to 100 so the coverage score reads as a percentage", () => {
+ const total = GUARD_LAYER_ORDER.reduce((sum, id) => sum + guardLayerWeight(id), 0);
+ expect(total).toBe(100);
+ });
+});
diff --git a/packages/agent-runtime/tests/InterventionChecker.test.js b/packages/agent-runtime/tests/InterventionChecker.test.js
new file mode 100644
index 000000000..994f4a7cc
--- /dev/null
+++ b/packages/agent-runtime/tests/InterventionChecker.test.js
@@ -0,0 +1,654 @@
+import { describe, expect, it } from "vitest";
+import { InterventionChecker } from "../src/core/InterventionChecker.js";
+import { DEFAULT_SECURITY_BLACKLIST } from "../src/core/defaultSecurityBlacklist.js";
+describe("InterventionChecker", () => {
+ describe("shouldIntervene", () => {
+ it("should return never when config is undefined", () => {
+ const result = InterventionChecker.shouldIntervene({
+ config: void 0,
+ securityBlacklist: [],
+ // Disable blacklist for this test
+ toolArgs: {}
+ });
+ expect(result).toBe("never");
+ });
+ it("should return the policy when config is a simple string", () => {
+ expect(
+ InterventionChecker.shouldIntervene({
+ config: "never",
+ securityBlacklist: [],
+ // Disable blacklist for this test
+ toolArgs: {}
+ })
+ ).toBe("never");
+ expect(
+ InterventionChecker.shouldIntervene({
+ config: "required",
+ securityBlacklist: [],
+ // Disable blacklist for this test
+ toolArgs: {}
+ })
+ ).toBe("required");
+ });
+ it("should match rules in order and return first match", () => {
+ const config = [
+ { match: { command: "ls:*" }, policy: "never" },
+ { match: { command: "git commit:*" }, policy: "required" },
+ { policy: "required" }
+ // Default rule
+ ];
+ expect(
+ InterventionChecker.shouldIntervene({
+ config,
+ securityBlacklist: [],
+ // Disable blacklist for this test
+ toolArgs: { command: "ls:" }
+ })
+ ).toBe("never");
+ expect(
+ InterventionChecker.shouldIntervene({
+ config,
+ securityBlacklist: [],
+ // Disable blacklist for this test
+ toolArgs: { command: "git commit:" }
+ })
+ ).toBe("required");
+ expect(
+ InterventionChecker.shouldIntervene({
+ config,
+ securityBlacklist: [],
+ // Disable blacklist for this test
+ toolArgs: { command: "rm -rf /" }
+ })
+ ).toBe("required");
+ });
+ it("should return require as default when no rule matches", () => {
+ const config = [{ match: { command: "ls:*" }, policy: "never" }];
+ const result = InterventionChecker.shouldIntervene({
+ config,
+ securityBlacklist: [],
+ // Disable blacklist for this test
+ toolArgs: { command: "rm -rf /" }
+ });
+ expect(result).toBe("required");
+ });
+ it("should handle multiple parameter matching", () => {
+ const config = [
+ {
+ match: {
+ command: "git add:*",
+ path: "/Users/project/*"
+ },
+ policy: "never"
+ },
+ { policy: "required" }
+ ];
+ expect(
+ InterventionChecker.shouldIntervene({
+ config,
+ securityBlacklist: [],
+ // Disable blacklist for this test
+ toolArgs: {
+ command: "git add:.",
+ path: "/Users/project/file.ts"
+ }
+ })
+ ).toBe("never");
+ expect(
+ InterventionChecker.shouldIntervene({
+ config,
+ securityBlacklist: [],
+ // Disable blacklist for this test
+ toolArgs: {
+ command: "git add:.",
+ path: "/tmp/file.ts"
+ }
+ })
+ ).toBe("required");
+ });
+ it("should handle default rule without match", () => {
+ const config = [
+ { match: { command: "ls:*" }, policy: "never" },
+ { policy: "required" }
+ // Default rule
+ ];
+ const result = InterventionChecker.shouldIntervene({
+ config,
+ securityBlacklist: [],
+ // Disable blacklist for this test
+ toolArgs: { command: "anything" }
+ });
+ expect(result).toBe("required");
+ });
+ });
+ describe("matchPattern", () => {
+ it("should match exact strings", () => {
+ expect(InterventionChecker["matchPattern"]("hello", "hello")).toBe(true);
+ expect(InterventionChecker["matchPattern"]("hello", "world")).toBe(false);
+ });
+ it("should match wildcard patterns", () => {
+ expect(InterventionChecker["matchPattern"]("*.ts", "file.ts")).toBe(true);
+ expect(InterventionChecker["matchPattern"]("*.ts", "file.js")).toBe(false);
+ expect(InterventionChecker["matchPattern"]("test*", "test123")).toBe(true);
+ expect(InterventionChecker["matchPattern"]("test*", "abc123")).toBe(false);
+ });
+ it("should match colon-based prefix patterns", () => {
+ expect(InterventionChecker["matchPattern"]("git add:*", "git add:")).toBe(true);
+ expect(InterventionChecker["matchPattern"]("git add:*", "git add:.")).toBe(true);
+ expect(InterventionChecker["matchPattern"]("git add:*", "git add:--all")).toBe(true);
+ expect(InterventionChecker["matchPattern"]("git add:*", "git commit")).toBe(false);
+ });
+ it("should match path patterns", () => {
+ expect(
+ InterventionChecker["matchPattern"]("/Users/project/*", "/Users/project/file.ts")
+ ).toBe(true);
+ expect(InterventionChecker["matchPattern"]("/Users/project/*", "/tmp/file.ts")).toBe(false);
+ });
+ });
+ describe("matchesArgument", () => {
+ it("should match exact type", () => {
+ const matcher = { pattern: "git add", type: "exact" };
+ expect(InterventionChecker["matchesArgument"](matcher, "git add")).toBe(true);
+ expect(InterventionChecker["matchesArgument"](matcher, "git add:.")).toBe(false);
+ });
+ it("should match prefix type", () => {
+ const matcher = { pattern: "git add", type: "prefix" };
+ expect(InterventionChecker["matchesArgument"](matcher, "git add")).toBe(true);
+ expect(InterventionChecker["matchesArgument"](matcher, "git add:.")).toBe(true);
+ expect(InterventionChecker["matchesArgument"](matcher, "git commit")).toBe(false);
+ });
+ it("should match wildcard type", () => {
+ const matcher = { pattern: "git *", type: "wildcard" };
+ expect(InterventionChecker["matchesArgument"](matcher, "git add")).toBe(true);
+ expect(InterventionChecker["matchesArgument"](matcher, "git commit")).toBe(true);
+ expect(InterventionChecker["matchesArgument"](matcher, "npm install")).toBe(false);
+ });
+ it("should match regex type", () => {
+ const matcher = { pattern: "^git (add|commit)", type: "regex" };
+ expect(InterventionChecker["matchesArgument"](matcher, "git add")).toBe(true);
+ expect(InterventionChecker["matchesArgument"](matcher, "git commit")).toBe(true);
+ expect(InterventionChecker["matchesArgument"](matcher, "git push")).toBe(false);
+ });
+ it("should handle simple string matcher", () => {
+ expect(InterventionChecker["matchesArgument"]("git add:*", "git add:.")).toBe(true);
+ expect(InterventionChecker["matchesArgument"]("*.ts", "file.ts")).toBe(true);
+ expect(InterventionChecker["matchesArgument"]("exact", "exact")).toBe(true);
+ });
+ });
+ describe("generateToolKey", () => {
+ it("should generate key without args hash", () => {
+ const key = InterventionChecker.generateToolKey("web-browsing", "crawlSinglePage");
+ expect(key).toBe("web-browsing/crawlSinglePage");
+ });
+ it("should generate key with args hash", () => {
+ const key = InterventionChecker.generateToolKey("bash", "bash", "a1b2c3");
+ expect(key).toBe("bash/bash#a1b2c3");
+ });
+ });
+ describe("hashArguments", () => {
+ it("should generate consistent hash for same arguments", () => {
+ const args1 = { command: "ls -la", path: "/tmp" };
+ const args2 = { command: "ls -la", path: "/tmp" };
+ const hash1 = InterventionChecker.hashArguments(args1);
+ const hash2 = InterventionChecker.hashArguments(args2);
+ expect(hash1).toBe(hash2);
+ });
+ it("should generate different hash for different arguments", () => {
+ const args1 = { command: "ls -la" };
+ const args2 = { command: "ls -l" };
+ const hash1 = InterventionChecker.hashArguments(args1);
+ const hash2 = InterventionChecker.hashArguments(args2);
+ expect(hash1).not.toBe(hash2);
+ });
+ it("should handle key order independence", () => {
+ const args1 = { a: 1, b: 2 };
+ const args2 = { b: 2, a: 1 };
+ const hash1 = InterventionChecker.hashArguments(args1);
+ const hash2 = InterventionChecker.hashArguments(args2);
+ expect(hash1).toBe(hash2);
+ });
+ it("should handle empty arguments", () => {
+ const hash = InterventionChecker.hashArguments({});
+ expect(hash).toBeDefined();
+ expect(typeof hash).toBe("string");
+ });
+ it("should handle complex nested objects", () => {
+ const args = {
+ config: { nested: { value: "test" } },
+ array: [1, 2, 3]
+ };
+ const hash = InterventionChecker.hashArguments(args);
+ expect(hash).toBeDefined();
+ expect(typeof hash).toBe("string");
+ });
+ });
+ describe("checkSecurityBlacklist", () => {
+ it("should return not blocked when blacklist is empty", () => {
+ const result = InterventionChecker.checkSecurityBlacklist([], { command: "rm -rf /" });
+ expect(result.blocked).toBe(false);
+ expect(result.reason).toBeUndefined();
+ });
+ describe("with DEFAULT_SECURITY_BLACKLIST", () => {
+ it("should block dangerous rm -rf ~/ command", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "rm -rf ~/"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe("Recursive deletion of home directory is extremely dangerous");
+ });
+ it("should block rm -rf on macOS home directory", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "rm -rf /Users/alice"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe("Recursive deletion of home directory is extremely dangerous");
+ });
+ it("should block rm -rf on Linux home directory", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "rm -rf /home/alice"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe("Recursive deletion of home directory is extremely dangerous");
+ });
+ it("should block rm -rf with $HOME variable", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "rm -rf $HOME"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe("Recursive deletion of home directory is extremely dangerous");
+ });
+ it("should block rm -rf / command", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "rm -rf /"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe("Recursive deletion of root directory will destroy the system");
+ });
+ it("should allow safe rm commands", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "rm -rf /tmp/test-folder"
+ });
+ expect(result.blocked).toBe(false);
+ });
+ it("should block fork bomb", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: ":(){ :|:& };:"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe("Fork bomb can crash the system");
+ });
+ it("should block dangerous dd commands to disk devices", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "dd if=/dev/zero of=/dev/sda"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe("Writing random data to disk devices can destroy data");
+ });
+ it("should block reading .env files via command", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "cat .env"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe(
+ "Reading .env files may leak sensitive credentials and API keys"
+ );
+ });
+ it("should block reading .env files via path", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ path: "/project/.env.local"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe(
+ "Reading .env files may leak sensitive credentials and API keys"
+ );
+ });
+ it("should block reading SSH private keys via command", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "cat ~/.ssh/id_rsa"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe("Reading SSH private keys can compromise system security");
+ });
+ it("should block reading SSH private keys via path", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ path: "/home/user/.ssh/id_ed25519"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe("Reading SSH private keys can compromise system security");
+ });
+ it("should allow reading SSH public keys", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "cat ~/.ssh/id_rsa.pub"
+ });
+ expect(result.blocked).toBe(false);
+ });
+ it("should block reading AWS credentials via command", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "cat ~/.aws/credentials"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe("Accessing AWS credentials can leak cloud access keys");
+ });
+ it("should block reading AWS credentials via path", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ path: "/home/user/.aws/credentials"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe("Accessing AWS credentials can leak cloud access keys");
+ });
+ it("should block reading Docker config", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "less ~/.docker/config.json"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe("Reading Docker config may expose registry credentials");
+ });
+ it("should block reading Kubernetes config", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ path: "/home/user/.kube/config"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe("Reading Kubernetes config may expose cluster credentials");
+ });
+ it("should block reading Git credentials", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "cat ~/.git-credentials"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe("Reading Git credentials file may leak access tokens");
+ });
+ it("should block reading npm token file", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ path: "/home/user/.npmrc"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe(
+ "Reading npm token file may expose package registry credentials"
+ );
+ });
+ it("should block reading shell history files", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "cat ~/.bash_history"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe(
+ "Reading history files may expose sensitive commands and credentials"
+ );
+ });
+ it("should block reading GCP credentials", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ path: "/home/user/.config/gcloud/application_default_credentials.json"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe("Reading GCP credentials may leak cloud service account keys");
+ });
+ });
+ describe("with custom blacklist", () => {
+ it("should work with multiple parameter matching", () => {
+ const blacklist = [
+ {
+ description: "Dangerous operation on system files",
+ match: {
+ command: { pattern: "rm.*", type: "regex" },
+ path: "/etc/*"
+ }
+ }
+ ];
+ expect(
+ InterventionChecker.checkSecurityBlacklist(blacklist, {
+ command: "rm -rf",
+ path: "/etc/passwd"
+ }).blocked
+ ).toBe(true);
+ expect(
+ InterventionChecker.checkSecurityBlacklist(blacklist, {
+ command: "rm -rf",
+ path: "/tmp/file"
+ }).blocked
+ ).toBe(false);
+ expect(
+ InterventionChecker.checkSecurityBlacklist(blacklist, {
+ command: "cat",
+ path: "/etc/passwd"
+ }).blocked
+ ).toBe(false);
+ });
+ });
+ });
+ describe("shouldIntervene with security blacklist", () => {
+ describe("with default blacklist behavior", () => {
+ it("should block dangerous commands even in auto-run mode", () => {
+ const result = InterventionChecker.shouldIntervene({
+ config: "never",
+ // Not passing securityBlacklist - should use DEFAULT_SECURITY_BLACKLIST
+ toolArgs: { command: "rm -rf ~/" }
+ });
+ expect(result).toBe("required");
+ });
+ it("should block dangerous commands even with no config", () => {
+ const result = InterventionChecker.shouldIntervene({
+ config: void 0,
+ // Not passing securityBlacklist - should use DEFAULT_SECURITY_BLACKLIST
+ toolArgs: { command: "rm -rf /" }
+ });
+ expect(result).toBe("required");
+ });
+ it("should allow safe commands to follow normal intervention rules", () => {
+ const result = InterventionChecker.shouldIntervene({
+ config: "never",
+ // Not passing securityBlacklist - should use DEFAULT_SECURITY_BLACKLIST
+ toolArgs: { command: "ls -la" }
+ });
+ expect(result).toBe("never");
+ });
+ it("should block reading sensitive files", () => {
+ const result = InterventionChecker.shouldIntervene({
+ config: "never",
+ // Not passing securityBlacklist - should use DEFAULT_SECURITY_BLACKLIST
+ toolArgs: { command: "cat .env" }
+ });
+ expect(result).toBe("required");
+ });
+ });
+ describe("with custom blacklist replacement", () => {
+ it("should use custom blacklist instead of default when provided", () => {
+ const customBlacklist = [
+ {
+ description: "Block all npm commands in production",
+ match: {
+ command: { pattern: "npm.*", type: "regex" }
+ }
+ }
+ ];
+ expect(
+ InterventionChecker.shouldIntervene({
+ config: "never",
+ securityBlacklist: customBlacklist,
+ toolArgs: { command: "npm install" }
+ })
+ ).toBe("required");
+ expect(
+ InterventionChecker.shouldIntervene({
+ config: "never",
+ securityBlacklist: customBlacklist,
+ toolArgs: { command: "rm -rf ~/" }
+ })
+ ).toBe("never");
+ });
+ it("should support extending default blacklist with custom rules", () => {
+ const extendedBlacklist = [
+ ...DEFAULT_SECURITY_BLACKLIST,
+ {
+ description: "Block access to production database",
+ match: {
+ command: { pattern: ".*psql.*production.*", type: "regex" }
+ }
+ }
+ ];
+ expect(
+ InterventionChecker.shouldIntervene({
+ config: "never",
+ securityBlacklist: extendedBlacklist,
+ toolArgs: { command: "rm -rf ~/" }
+ })
+ ).toBe("required");
+ expect(
+ InterventionChecker.shouldIntervene({
+ config: "never",
+ securityBlacklist: extendedBlacklist,
+ toolArgs: { command: "psql -h production.db" }
+ })
+ ).toBe("required");
+ expect(
+ InterventionChecker.shouldIntervene({
+ config: "never",
+ securityBlacklist: extendedBlacklist,
+ toolArgs: { command: "psql -h localhost" }
+ })
+ ).toBe("never");
+ });
+ it("should allow disabling security blacklist by passing empty array", () => {
+ const result = InterventionChecker.shouldIntervene({
+ config: "never",
+ securityBlacklist: [],
+ // Explicitly disable blacklist
+ toolArgs: { command: "rm -rf ~/" }
+ });
+ expect(result).toBe("never");
+ });
+ it("should support project-specific blacklist rules", () => {
+ const projectBlacklist = [
+ {
+ description: "Block modifying package.json in CI",
+ match: {
+ path: { pattern: ".*/package\\.json$", type: "regex" },
+ command: { pattern: "(vim|nano|vi|emacs|code|sed).*", type: "regex" }
+ }
+ }
+ ];
+ expect(
+ InterventionChecker.shouldIntervene({
+ config: "never",
+ securityBlacklist: projectBlacklist,
+ toolArgs: {
+ command: "vim package.json",
+ path: "/project/package.json"
+ }
+ })
+ ).toBe("required");
+ expect(
+ InterventionChecker.shouldIntervene({
+ config: "never",
+ securityBlacklist: projectBlacklist,
+ toolArgs: {
+ command: "cat package.json",
+ path: "/project/package.json"
+ }
+ })
+ ).toBe("never");
+ });
+ });
+ });
+ describe("Integration scenarios", () => {
+ it("should handle Bash tool scenario", () => {
+ const config = [
+ { match: { command: "ls:*" }, policy: "never" },
+ { match: { command: "git add:*" }, policy: "required" },
+ { match: { command: "git commit:*" }, policy: "required" },
+ { match: { command: "rm:*" }, policy: "required" },
+ { policy: "required" }
+ ];
+ expect(
+ InterventionChecker.shouldIntervene({
+ config,
+ securityBlacklist: [],
+ // Disable blacklist for this test
+ toolArgs: { command: "ls:" }
+ })
+ ).toBe("never");
+ expect(
+ InterventionChecker.shouldIntervene({
+ config,
+ securityBlacklist: [],
+ // Disable blacklist for this test
+ toolArgs: { command: "git add:." }
+ })
+ ).toBe("required");
+ expect(
+ InterventionChecker.shouldIntervene({
+ config,
+ securityBlacklist: [],
+ // Disable blacklist for this test
+ toolArgs: { command: "git commit:-m" }
+ })
+ ).toBe("required");
+ expect(
+ InterventionChecker.shouldIntervene({
+ config,
+ securityBlacklist: [],
+ // Disable blacklist for this test
+ toolArgs: { command: "rm:-rf" }
+ })
+ ).toBe("required");
+ expect(
+ InterventionChecker.shouldIntervene({
+ config,
+ securityBlacklist: [],
+ // Disable blacklist for this test
+ toolArgs: { command: "npm install" }
+ })
+ ).toBe("required");
+ });
+ it("should handle LocalSystem tool scenario", () => {
+ const config = [
+ { match: { path: "/Users/project/*" }, policy: "never" },
+ { policy: "required" }
+ ];
+ expect(
+ InterventionChecker.shouldIntervene({
+ config,
+ securityBlacklist: [],
+ // Disable blacklist for this test
+ toolArgs: { path: "/Users/project/file.ts" }
+ })
+ ).toBe("never");
+ expect(
+ InterventionChecker.shouldIntervene({
+ config,
+ securityBlacklist: [],
+ // Disable blacklist for this test
+ toolArgs: { path: "/tmp/file.ts" }
+ })
+ ).toBe("required");
+ });
+ it("should handle Web Browsing tool with simple policy", () => {
+ const config = "required";
+ expect(
+ InterventionChecker.shouldIntervene({
+ config,
+ securityBlacklist: [],
+ // Disable blacklist for this test
+ toolArgs: { url: "https://example.com" }
+ })
+ ).toBe("required");
+ });
+ it("should handle security blacklist overriding user config", () => {
+ const config = "never";
+ const blacklist = DEFAULT_SECURITY_BLACKLIST;
+ expect(
+ InterventionChecker.shouldIntervene({
+ config,
+ securityBlacklist: blacklist,
+ toolArgs: { command: "rm -rf /" }
+ })
+ ).toBe("required");
+ expect(
+ InterventionChecker.shouldIntervene({
+ config,
+ securityBlacklist: blacklist,
+ toolArgs: { command: "ls -la" }
+ })
+ ).toBe("never");
+ });
+ });
+});
diff --git a/packages/agent-runtime/tests/ResponseQualityEvaluator.test.js b/packages/agent-runtime/tests/ResponseQualityEvaluator.test.js
new file mode 100644
index 000000000..6f0a326d6
--- /dev/null
+++ b/packages/agent-runtime/tests/ResponseQualityEvaluator.test.js
@@ -0,0 +1,118 @@
+import { describe, expect, it } from "vitest";
+import { ResponseQualityEvaluator } from "../src/core/ResponseQualityEvaluator.js";
+describe("ResponseQualityEvaluator", () => {
+ const evaluator = new ResponseQualityEvaluator();
+ describe("completeness checks", () => {
+ it("should flag empty responses", () => {
+ const result = evaluator.evaluate("What is Bitcoin?", "");
+ expect(result.passed).toBe(false);
+ expect(result.issues).toContainEqual(
+ expect.objectContaining({ category: "completeness", severity: "error" })
+ );
+ });
+ it("should flag generic filler responses", () => {
+ const result = evaluator.evaluate("What is Bitcoin?", "Sure, I can help");
+ expect(result.issues).toContainEqual(
+ expect.objectContaining({ category: "completeness", severity: "warning" })
+ );
+ });
+ it("should pass for substantive responses", () => {
+ const result = evaluator.evaluate(
+ "What is Bitcoin?",
+ "Bitcoin is a decentralized digital currency created in 2009 by the pseudonymous Satoshi Nakamoto. It uses a proof-of-work consensus mechanism and has a limited supply of 21 million coins."
+ );
+ const completenessIssues = result.issues.filter((i) => i.category === "completeness");
+ expect(completenessIssues).toHaveLength(0);
+ });
+ });
+ describe("hallucination checks", () => {
+ it("should flag specific numbers without tool data", () => {
+ const result = evaluator.evaluate(
+ "What is Aave TVL?",
+ "Aave currently has a TVL of $12.5 billion across all chains."
+ // No tool results
+ );
+ expect(result.issues).toContainEqual(
+ expect.objectContaining({ category: "hallucination", severity: "warning" })
+ );
+ });
+ it("should not flag numbers when tool data is present", () => {
+ const result = evaluator.evaluate(
+ "What is Aave TVL?",
+ "According to the data, Aave has a TVL of $12.5 billion.",
+ [{ content: '{"tvl": 12500000000}', success: true }]
+ );
+ const hallucinationIssues = result.issues.filter((i) => i.category === "hallucination");
+ expect(hallucinationIssues).toHaveLength(0);
+ });
+ it("should flag claims of success when tools failed", () => {
+ const result = evaluator.evaluate(
+ "Swap 1 ETH for USDC",
+ "Successfully completed the swap! Here are the results of the transaction.",
+ [{ content: '{"error": "Insufficient balance"}', success: false }]
+ );
+ expect(result.passed).toBe(false);
+ expect(result.issues).toContainEqual(
+ expect.objectContaining({ category: "hallucination", severity: "error" })
+ );
+ });
+ });
+ describe("formatting checks", () => {
+ it("should flag unclosed code blocks", () => {
+ const result = evaluator.evaluate(
+ "Show me code",
+ "Here is the code:\n```typescript\nconst x = 1;\n// no closing block"
+ );
+ expect(result.issues).toContainEqual(
+ expect.objectContaining({ category: "formatting", severity: "warning" })
+ );
+ });
+ it("should not flag properly closed code blocks", () => {
+ const result = evaluator.evaluate(
+ "Show me code",
+ "Here is the code:\n```typescript\nconst x = 1;\n```"
+ );
+ const formattingIssues = result.issues.filter(
+ (i) => i.category === "formatting" && i.description.includes("code block")
+ );
+ expect(formattingIssues).toHaveLength(0);
+ });
+ });
+ describe("language consistency", () => {
+ it("should flag language mismatch for CJK queries", () => {
+ const result = evaluator.evaluate(
+ "\u6BD4\u7279\u5E01\u7684\u4EF7\u683C\u662F\u591A\u5C11\uFF1F",
+ "Bitcoin is currently trading at around $50,000. The price has been relatively stable over the past few days with moderate volume."
+ );
+ expect(result.issues).toContainEqual(
+ expect.objectContaining({ category: "language", severity: "warning" })
+ );
+ });
+ it("should not flag when query and response are in the same language", () => {
+ const result = evaluator.evaluate(
+ "\u6BD4\u7279\u5E01\u7684\u4EF7\u683C\u662F\u591A\u5C11\uFF1F",
+ "\u6BD4\u7279\u5E01\u76EE\u524D\u7684\u4EF7\u683C\u7EA6\u4E3A50,000\u7F8E\u5143\u3002"
+ );
+ const languageIssues = result.issues.filter((i) => i.category === "language");
+ expect(languageIssues).toHaveLength(0);
+ });
+ });
+ describe("self-correction prompt", () => {
+ it("should generate a correction prompt for failing evaluations", () => {
+ const result = evaluator.evaluate("Swap 1 ETH", "Successfully swapped!", [
+ { content: "error", success: false }
+ ]);
+ expect(result.passed).toBe(false);
+ expect(result.selfCorrectionPrompt).toBeDefined();
+ expect(result.selfCorrectionPrompt).toContain("<quality_review>");
+ expect(result.selfCorrectionPrompt).toContain("HALLUCINATION");
+ });
+ it("should not generate correction prompt for passing evaluations", () => {
+ const result = evaluator.evaluate(
+ "Hello",
+ "Hello! How can I help you today? I am ready to assist with any questions you may have."
+ );
+ expect(result.selfCorrectionPrompt).toBeUndefined();
+ });
+ });
+});
diff --git a/packages/agent-runtime/tests/SelfReflection.test.js b/packages/agent-runtime/tests/SelfReflection.test.js
new file mode 100644
index 000000000..75baea715
--- /dev/null
+++ b/packages/agent-runtime/tests/SelfReflection.test.js
@@ -0,0 +1,120 @@
+import { describe, expect, it } from "vitest";
+import { SelfReflection } from "../src/core/SelfReflection.js";
+describe("SelfReflection", () => {
+ describe("classifyError", () => {
+ it("should classify invalid argument errors", () => {
+ const sr = new SelfReflection();
+ expect(sr.classifyError("Invalid argument: expected number got string")).toBe(
+ "invalid_arguments"
+ );
+ expect(sr.classifyError('Validation failed for field "amount"')).toBe("invalid_arguments");
+ expect(sr.classifyError("Schema mismatch")).toBe("invalid_arguments");
+ });
+ it("should classify missing field errors", () => {
+ const sr = new SelfReflection();
+ expect(sr.classifyError('Required field "address" is missing')).toBe(
+ "missing_required_field"
+ );
+ expect(sr.classifyError('Parameter "chainId" is undefined')).toBe("missing_required_field");
+ });
+ it("should classify rate limit errors", () => {
+ const sr = new SelfReflection();
+ expect(sr.classifyError("429 Too Many Requests")).toBe("api_rate_limit");
+ expect(sr.classifyError("Rate limit exceeded, retry after 60s")).toBe("api_rate_limit");
+ });
+ it("should classify network errors", () => {
+ const sr = new SelfReflection();
+ expect(sr.classifyError("ECONNREFUSED 127.0.0.1:5432")).toBe("network_error");
+ expect(sr.classifyError("fetch failed: DNS resolution error")).toBe("network_error");
+ });
+ it("should classify permission errors", () => {
+ const sr = new SelfReflection();
+ expect(sr.classifyError("403 Forbidden")).toBe("permission_denied");
+ expect(sr.classifyError("Unauthorized: invalid API key")).toBe("permission_denied");
+ });
+ it("should classify not found errors", () => {
+ const sr = new SelfReflection();
+ expect(sr.classifyError("404 Not Found")).toBe("not_found");
+ expect(sr.classifyError("No results found for query")).toBe("not_found");
+ });
+ it("should classify timeout errors", () => {
+ const sr = new SelfReflection();
+ expect(sr.classifyError("Request timed out after 10000ms")).toBe("timeout");
+ expect(sr.classifyError("Deadline exceeded")).toBe("timeout");
+ });
+ it("should return unknown for unclassifiable errors", () => {
+ const sr = new SelfReflection();
+ expect(sr.classifyError("Something completely unexpected happened")).toBe("unknown");
+ });
+ });
+ describe("generateCorrectionPrompt", () => {
+ it("should generate a structured correction prompt", () => {
+ const sr = new SelfReflection();
+ const prompt = sr.generateCorrectionPrompt({
+ apiName: "getTokenPrice",
+ arguments: '{"token": "ETH"}',
+ error: 'Required field "chainId" is missing',
+ retryCount: 0,
+ toolIdentifier: "coingecko"
+ });
+ expect(prompt).toContain("<tool_error_analysis>");
+ expect(prompt).toContain("coingecko/getTokenPrice");
+ expect(prompt).toContain("missing_required_field");
+ expect(prompt).toContain("Attempt: 1/2");
+ expect(prompt).toContain("</tool_error_analysis>");
+ });
+ it("should include last-retry warning on final attempt", () => {
+ const sr = new SelfReflection({ maxRetries: 2 });
+ const prompt = sr.generateCorrectionPrompt({
+ apiName: "swap",
+ arguments: "{}",
+ error: "Invalid argument",
+ retryCount: 1,
+ toolIdentifier: "swap"
+ });
+ expect(prompt).toContain("last retry attempt");
+ expect(prompt).toContain("different tool");
+ });
+ });
+ describe("trackRetry", () => {
+ it("should allow retries up to maxRetries", () => {
+ const sr = new SelfReflection({ maxRetries: 2 });
+ expect(sr.trackRetry("call-1")).toBe(true);
+ expect(sr.trackRetry("call-1")).toBe(true);
+ expect(sr.trackRetry("call-1")).toBe(false);
+ });
+ it("should track retries independently per tool call", () => {
+ const sr = new SelfReflection({ maxRetries: 1 });
+ expect(sr.trackRetry("call-1")).toBe(true);
+ expect(sr.trackRetry("call-1")).toBe(false);
+ expect(sr.trackRetry("call-2")).toBe(true);
+ });
+ });
+ describe("shouldRetry", () => {
+ it("should not retry permission errors", () => {
+ const sr = new SelfReflection();
+ expect(sr.shouldRetry("403 Forbidden")).toBe(false);
+ });
+ it("should not retry rate limit errors", () => {
+ const sr = new SelfReflection();
+ expect(sr.shouldRetry("429 Too Many Requests")).toBe(false);
+ });
+ it("should retry network errors", () => {
+ const sr = new SelfReflection();
+ expect(sr.shouldRetry("ECONNREFUSED")).toBe(true);
+ });
+ it("should retry invalid argument errors", () => {
+ const sr = new SelfReflection();
+ expect(sr.shouldRetry("Invalid argument: expected number")).toBe(true);
+ });
+ });
+ describe("reset", () => {
+ it("should clear all retry tracking", () => {
+ const sr = new SelfReflection({ maxRetries: 1 });
+ sr.trackRetry("call-1");
+ expect(sr.trackRetry("call-1")).toBe(false);
+ sr.reset();
+ expect(sr.trackRetry("call-1")).toBe(true);
+ });
+ });
+});
diff --git a/packages/agent-runtime/tests/SpendGuard.test.js b/packages/agent-runtime/tests/SpendGuard.test.js
new file mode 100644
index 000000000..44e21af43
--- /dev/null
+++ b/packages/agent-runtime/tests/SpendGuard.test.js
@@ -0,0 +1,210 @@
+import { beforeEach, describe, expect, it } from "vitest";
+import { SpendGuard } from "../src/core/SpendGuard.js";
+const AGENT = "agt_test";
+function fixedClock(start = 17e11) {
+ let t = start;
+ return {
+ now: () => t,
+ advance: (ms) => {
+ t += ms;
+ },
+ set: (ms) => {
+ t = ms;
+ }
+ };
+}
+function makeTx(overrides = {}) {
+ return { agentId: AGENT, valueUsd: 100, ...overrides };
+}
+function makeGuard(config, clock = fixedClock()) {
+ return { guard: new SpendGuard(config, { now: clock.now }), clock };
+}
+describe("SpendGuard", () => {
+ describe("per-tx maximum", () => {
+ let guard;
+ beforeEach(() => {
+ guard = new SpendGuard({ perTxMaxUsd: 1e3 });
+ });
+ it("allows a transaction at the per-tx limit", () => {
+ const result = guard.check(makeTx({ valueUsd: 1e3 }));
+ expect(result.allowed).toBe(true);
+ });
+ it("blocks a transaction over the per-tx max with a deterministic reason", () => {
+ const result = guard.check(makeTx({ valueUsd: 1500 }));
+ expect(result.allowed).toBe(false);
+ expect(result.code).toBe("CAP_PER_TX");
+ expect(result.reason).toBe(
+ "Transaction $1,500 exceeds per-transaction maximum of $1,000"
+ );
+ });
+ it("is deterministic - identical inputs yield identical results", () => {
+ const a = guard.check(makeTx({ valueUsd: 2e3 }));
+ const b = guard.check(makeTx({ valueUsd: 2e3 }));
+ expect(a).toEqual(b);
+ });
+ });
+ describe("rolling spend cap", () => {
+ it("blocks the next tx once cumulative spend crosses the rolling cap", () => {
+ const { guard } = makeGuard({ rollingMaxUsd: 1e3 });
+ guard.recordSpend(AGENT, 500);
+ guard.recordSpend(AGENT, 300);
+ expect(guard.check(makeTx({ valueUsd: 150 })).allowed).toBe(true);
+ const blocked = guard.check(makeTx({ valueUsd: 300 }));
+ expect(blocked.allowed).toBe(false);
+ expect(blocked.code).toBe("CAP_ROLLING");
+ expect(blocked.remainingRollingUsd).toBe(0);
+ });
+ it("slides the window - old spend outside the window no longer counts", () => {
+ const { guard, clock } = makeGuard({ rollingMaxUsd: 1e3, rollingWindowMs: 6e4 });
+ guard.recordSpend(AGENT, 900);
+ expect(guard.check(makeTx({ valueUsd: 200 })).allowed).toBe(false);
+ clock.advance(60001);
+ expect(guard.check(makeTx({ valueUsd: 200 })).allowed).toBe(true);
+ });
+ it("enforces the daily (rolling 24h) cap independently", () => {
+ const { guard } = makeGuard({ dailyMaxUsd: 5e3 });
+ guard.recordSpend(AGENT, 4900);
+ const blocked = guard.check(makeTx({ valueUsd: 200 }));
+ expect(blocked.allowed).toBe(false);
+ expect(blocked.code).toBe("CAP_DAILY");
+ });
+ it("tracks spend per agent, not globally", () => {
+ const { guard } = makeGuard({ rollingMaxUsd: 1e3 });
+ guard.recordSpend("agt_a", 900);
+ expect(guard.check(makeTx({ agentId: "agt_b", valueUsd: 900 })).allowed).toBe(true);
+ expect(guard.check(makeTx({ agentId: "agt_a", valueUsd: 900 })).allowed).toBe(false);
+ });
+ });
+ describe("reserve floor", () => {
+ let guard;
+ beforeEach(() => {
+ guard = new SpendGuard({ reserveFloorUsd: 1e3 });
+ });
+ it("allows a tx that leaves the balance at the floor", () => {
+ const result = guard.check(makeTx({ balanceUsd: 1500, valueUsd: 500 }));
+ expect(result.allowed).toBe(true);
+ });
+ it("blocks a tx that would drain below the reserve floor", () => {
+ const result = guard.check(makeTx({ balanceUsd: 1200, valueUsd: 500 }));
+ expect(result.allowed).toBe(false);
+ expect(result.code).toBe("RESERVE_FLOOR");
+ });
+ it("cannot enforce the floor without a balance (passes through)", () => {
+ const result = guard.check(makeTx({ valueUsd: 5e3 }));
+ expect(result.allowed).toBe(true);
+ });
+ });
+ describe("token/target firewall", () => {
+ it("blocks a destination on the deny list", () => {
+ const guard = new SpendGuard({
+ firewall: { denyDestinations: ["0xBADACTOR"] }
+ });
+ const result = guard.check(makeTx({ destination: "0xbadactor", valueUsd: 10 }));
+ expect(result.allowed).toBe(false);
+ expect(result.code).toBe("FIREWALL_DENY_DEST");
+ });
+ it("blocks a token on the deny list (case-insensitive)", () => {
+ const guard = new SpendGuard({ firewall: { denyTokens: ["scam"] } });
+ const result = guard.check(makeTx({ token: "SCAM", valueUsd: 10 }));
+ expect(result.allowed).toBe(false);
+ expect(result.code).toBe("FIREWALL_DENY_TOKEN");
+ });
+ it("blocks an off-allowlist destination in strict mode", () => {
+ const guard = new SpendGuard({
+ firewall: { allowDestinations: ["0xsafe"], strictMode: true }
+ });
+ expect(guard.check(makeTx({ destination: "0xSAFE", valueUsd: 10 })).allowed).toBe(true);
+ const blocked = guard.check(makeTx({ destination: "0xunknown", valueUsd: 10 }));
+ expect(blocked.allowed).toBe(false);
+ expect(blocked.code).toBe("FIREWALL_NOT_ALLOWED");
+ });
+ it("blocks an off-allowlist token in strict mode", () => {
+ const guard = new SpendGuard({
+ firewall: { allowTokens: ["USDC"], strictMode: true }
+ });
+ expect(guard.check(makeTx({ token: "usdc", valueUsd: 10 })).allowed).toBe(true);
+ expect(guard.check(makeTx({ token: "PEPE", valueUsd: 10 })).allowed).toBe(false);
+ });
+ it("does not enforce the allowlist when strict mode is off", () => {
+ const guard = new SpendGuard({
+ firewall: { allowTokens: ["USDC"], strictMode: false }
+ });
+ expect(guard.check(makeTx({ token: "PEPE", valueUsd: 10 })).allowed).toBe(true);
+ });
+ it("deny takes precedence over allow", () => {
+ const guard = new SpendGuard({
+ firewall: { allowTokens: ["USDC"], denyTokens: ["USDC"], strictMode: true }
+ });
+ const result = guard.check(makeTx({ token: "USDC", valueUsd: 10 }));
+ expect(result.allowed).toBe(false);
+ expect(result.code).toBe("FIREWALL_DENY_TOKEN");
+ });
+ });
+ describe("custody reconciliation", () => {
+ it("flags a breach and latches the agent when on-chain outflow exceeds the ledger", () => {
+ const { guard } = makeGuard({ perTxMaxUsd: 1e4 });
+ expect(guard.check(makeTx({ valueUsd: 100 })).allowed).toBe(true);
+ const recon = guard.reconcile(AGENT, {
+ ledgerRecordedUsd: 5e3,
+ onChainOutflowUsd: 7500
+ });
+ expect(recon.breach).toBe(true);
+ expect(recon.unrecordedUsd).toBe(2500);
+ expect(guard.isTripped(AGENT)).toBe(true);
+ const blocked = guard.check(makeTx({ valueUsd: 100 }));
+ expect(blocked.allowed).toBe(false);
+ expect(blocked.code).toBe("BREACH");
+ });
+ it("does not flag a breach when the chain matches the ledger within tolerance", () => {
+ const { guard } = makeGuard({ breachTolerance: 0.01 });
+ const recon = guard.reconcile(AGENT, {
+ ledgerRecordedUsd: 5e3,
+ onChainOutflowUsd: 5040
+ // within 1% tolerance
+ });
+ expect(recon.breach).toBe(false);
+ expect(guard.isTripped(AGENT)).toBe(false);
+ });
+ it("reconciles via an injected ledger reader", async () => {
+ const { guard } = makeGuard({});
+ const recon = await guard.reconcileFromLedger(
+ AGENT,
+ async () => ({ ledgerRecordedUsd: 1e3, onChainOutflowUsd: 3e3 }),
+ "user_1"
+ );
+ expect(recon.breach).toBe(true);
+ expect(guard.isTripped(AGENT)).toBe(true);
+ });
+ it("reset() clears the breach latch", () => {
+ const { guard } = makeGuard({});
+ guard.reconcile(AGENT, { ledgerRecordedUsd: 0, onChainOutflowUsd: 500 });
+ expect(guard.isTripped(AGENT)).toBe(true);
+ guard.reset(AGENT);
+ expect(guard.isTripped(AGENT)).toBe(false);
+ expect(guard.check(makeTx({ valueUsd: 100 })).allowed).toBe(true);
+ });
+ });
+ describe("envelope composition", () => {
+ it("allows a tx that satisfies every configured limit", () => {
+ const { guard } = makeGuard({
+ dailyMaxUsd: 1e4,
+ firewall: { allowTokens: ["USDC"], strictMode: true },
+ perTxMaxUsd: 1e3,
+ reserveFloorUsd: 500,
+ rollingMaxUsd: 5e3
+ });
+ const result = guard.check(
+ makeTx({ balanceUsd: 5e3, token: "USDC", valueUsd: 800 })
+ );
+ expect(result.allowed).toBe(true);
+ expect(result.remainingRollingUsd).toBe(4200);
+ expect(result.remainingDailyUsd).toBe(9200);
+ });
+ it("seeds the rolling window from a persisted ledger total", () => {
+ const { guard } = makeGuard({ rollingMaxUsd: 1e3 });
+ guard.syncSpendFromLedger(AGENT, 950);
+ expect(guard.check(makeTx({ valueUsd: 100 })).allowed).toBe(false);
+ expect(guard.windowSpend(AGENT, 24 * 60 * 60 * 1e3)).toBe(950);
+ });
+ });
+});
diff --git a/packages/agent-runtime/tests/ToolRelevanceScorer.test.js b/packages/agent-runtime/tests/ToolRelevanceScorer.test.js
new file mode 100644
index 000000000..1b70fdee9
--- /dev/null
+++ b/packages/agent-runtime/tests/ToolRelevanceScorer.test.js
@@ -0,0 +1,90 @@
+import { describe, expect, it } from "vitest";
+import { ToolRelevanceScorer } from "../src/core/ToolRelevanceScorer.js";
+const createManifest = (identifier, description, apis = []) => ({
+ api: apis,
+ description,
+ identifier
+});
+describe("ToolRelevanceScorer", () => {
+ it("should return all tools when query is empty or too generic", () => {
+ const scorer = new ToolRelevanceScorer({ maxTools: 20 });
+ const manifests = {
+ "tool-a": createManifest("tool-a", "Does something"),
+ "tool-b": createManifest("tool-b", "Does something else")
+ };
+ expect(scorer.scoreTools("", manifests)).toHaveLength(2);
+ expect(scorer.scoreTools("a", manifests)).toHaveLength(2);
+ });
+ it("should rank tools by relevance to query keywords", () => {
+ const scorer = new ToolRelevanceScorer({ maxTools: 5 });
+ const manifests = {
+ "defi-analytics": createManifest("defi-analytics", "Analyze DeFi protocols and TVL data", [
+ { description: "Get protocol TVL", name: "getProtocolTVL" }
+ ]),
+ "knowledge-base": createManifest("knowledge-base", "Search knowledge documents", [
+ { description: "Search documents", name: "searchDocuments" }
+ ]),
+ "memory": createManifest("memory", "Store and recall user memories", [
+ { description: "Search user memory", name: "searchUserMemory" }
+ ]),
+ "swap": createManifest("swap", "Execute token swaps via DEX aggregators", [
+ { description: "Swap tokens", name: "swapTokens" }
+ ])
+ };
+ const result = scorer.scoreTools("what is the TVL of Aave DeFi protocol", manifests);
+ expect(result[0].identifier).toBe("defi-analytics");
+ });
+ it("should always include tools from alwaysIncludeTools list", () => {
+ const scorer = new ToolRelevanceScorer({
+ alwaysIncludeTools: ["memory"],
+ maxTools: 2
+ });
+ const manifests = {
+ "defi-analytics": createManifest("defi-analytics", "Analyze DeFi metrics"),
+ "memory": createManifest("memory", "Store memories"),
+ "swap": createManifest("swap", "Swap tokens")
+ };
+ const result = scorer.scoreTools("swap ETH for USDC", manifests);
+ const identifiers = result.map((m) => m.identifier);
+ expect(identifiers).toContain("memory");
+ expect(result.length).toBeLessThanOrEqual(2);
+ });
+ it("should boost recently-used tools", () => {
+ const scorer = new ToolRelevanceScorer({ maxTools: 5, recencyBoost: 3 });
+ const manifests = {
+ "markets": createManifest("markets", "Market data and prices"),
+ "swap": createManifest("swap", "Swap tokens on exchanges")
+ };
+ const withoutRecency = scorer.scoreTools("check prices", manifests, []);
+ const withRecency = scorer.scoreTools("check prices", manifests, ["swap"]);
+ const swapIndexWithout = withoutRecency.findIndex((m) => m.identifier === "swap");
+ const swapIndexWith = withRecency.findIndex((m) => m.identifier === "swap");
+ expect(swapIndexWith).toBeLessThanOrEqual(swapIndexWithout);
+ });
+ it("should filter tools below minScore threshold", () => {
+ const scorer = new ToolRelevanceScorer({ maxTools: 10, minScore: 1 });
+ const manifests = {
+ "contract-explorer": createManifest("contract-explorer", "Explore smart contracts"),
+ "swap": createManifest("swap", "Swap tokens"),
+ "weather": createManifest("weather", "Get weather data")
+ };
+ const result = scorer.scoreTools("swap tokens please", manifests);
+ expect(result.length).toBeGreaterThanOrEqual(1);
+ expect(result[0].identifier).toBe("swap");
+ });
+ it("should match against API names and descriptions", () => {
+ const scorer = new ToolRelevanceScorer({ maxTools: 5 });
+ const manifests = {
+ "coingecko": createManifest("coingecko", "CoinGecko data provider", [
+ { description: "Get token reputation and trust score", name: "getTokenReputation" }
+ ]),
+ "erc8004": createManifest("erc8004", "Agent registry protocol", [
+ { description: "Get agent reputation score", name: "getReputation" }
+ ])
+ };
+ const result = scorer.scoreTools("check reputation score", manifests);
+ expect(result.length).toBeGreaterThanOrEqual(1);
+ const identifiers = result.map((m) => m.identifier);
+ expect(identifiers).toContain("erc8004");
+ });
+});
diff --git a/packages/agent-runtime/tests/UsageCounter.test.js b/packages/agent-runtime/tests/UsageCounter.test.js
new file mode 100644
index 000000000..96cb0dde7
--- /dev/null
+++ b/packages/agent-runtime/tests/UsageCounter.test.js
@@ -0,0 +1,768 @@
+import { describe, expect, it } from "vitest";
+import { UsageCounter } from "../src/core/UsageCounter.js";
+import { AgentRuntime } from "../src/core/runtime.js";
+describe("UsageCounter", () => {
+ describe("UsageCounter.accumulateLLM", () => {
+ it("should accumulate LLM usage tokens", () => {
+ const state = AgentRuntime.createInitialState();
+ const modelUsage = {
+ totalInputTokens: 100,
+ totalOutputTokens: 50,
+ totalTokens: 150
+ };
+ const { usage } = UsageCounter.accumulateLLM({
+ cost: state.cost,
+ model: "gpt-4",
+ modelUsage,
+ provider: "openai",
+ usage: state.usage
+ });
+ expect(usage.llm.tokens.input).toBe(100);
+ expect(usage.llm.tokens.output).toBe(50);
+ expect(usage.llm.tokens.total).toBe(150);
+ expect(usage.llm.apiCalls).toBe(1);
+ });
+ it("should not mutate original usage", () => {
+ const state = AgentRuntime.createInitialState();
+ const modelUsage = {
+ totalInputTokens: 100,
+ totalOutputTokens: 50,
+ totalTokens: 150
+ };
+ const { usage } = UsageCounter.accumulateLLM({
+ cost: state.cost,
+ model: "gpt-4",
+ modelUsage,
+ provider: "openai",
+ usage: state.usage
+ });
+ expect(state.usage.llm.tokens.input).toBe(0);
+ expect(usage).not.toBe(state.usage);
+ });
+ it("should create new byModel entry when not exists", () => {
+ const state = AgentRuntime.createInitialState();
+ const modelUsage = {
+ cost: 0.05,
+ totalInputTokens: 100,
+ totalOutputTokens: 50,
+ totalTokens: 150
+ };
+ const { cost } = UsageCounter.accumulateLLM({
+ cost: state.cost,
+ model: "gpt-4",
+ modelUsage,
+ provider: "openai",
+ usage: state.usage
+ });
+ expect(cost?.llm.byModel).toHaveLength(1);
+ expect(cost?.llm.byModel[0]).toEqual({
+ id: "openai/gpt-4",
+ model: "gpt-4",
+ provider: "openai",
+ totalCost: 0.05,
+ usage: {
+ cost: 0.05,
+ totalInputTokens: 100,
+ totalOutputTokens: 50,
+ totalTokens: 150
+ }
+ });
+ });
+ it("should accumulate to existing byModel entry", () => {
+ const state = AgentRuntime.createInitialState();
+ const usage1 = {
+ cost: 0.05,
+ totalInputTokens: 100,
+ totalOutputTokens: 50,
+ totalTokens: 150
+ };
+ const usage2 = {
+ cost: 0.03,
+ totalInputTokens: 50,
+ totalOutputTokens: 25,
+ totalTokens: 75
+ };
+ const result1 = UsageCounter.accumulateLLM({
+ cost: state.cost,
+ model: "gpt-4",
+ modelUsage: usage1,
+ provider: "openai",
+ usage: state.usage
+ });
+ const result2 = UsageCounter.accumulateLLM({
+ cost: result1.cost,
+ model: "gpt-4",
+ modelUsage: usage2,
+ provider: "openai",
+ usage: result1.usage
+ });
+ expect(result2.cost?.llm.byModel).toHaveLength(1);
+ expect(result2.cost?.llm.byModel[0]).toEqual({
+ id: "openai/gpt-4",
+ model: "gpt-4",
+ provider: "openai",
+ totalCost: 0.08,
+ usage: {
+ cost: 0.08,
+ totalInputTokens: 150,
+ totalOutputTokens: 75,
+ totalTokens: 225
+ }
+ });
+ });
+ it("should accumulate multiple models separately", () => {
+ const state = AgentRuntime.createInitialState();
+ const usage1 = {
+ cost: 0.05,
+ totalInputTokens: 100,
+ totalOutputTokens: 50,
+ totalTokens: 150
+ };
+ const usage2 = {
+ cost: 0.02,
+ totalInputTokens: 50,
+ totalOutputTokens: 25,
+ totalTokens: 75
+ };
+ const result1 = UsageCounter.accumulateLLM({
+ cost: state.cost,
+ model: "gpt-4",
+ modelUsage: usage1,
+ provider: "openai",
+ usage: state.usage
+ });
+ const result2 = UsageCounter.accumulateLLM({
+ cost: result1.cost,
+ model: "claude-3-5-sonnet-20241022",
+ modelUsage: usage2,
+ provider: "anthropic",
+ usage: result1.usage
+ });
+ expect(result2.cost?.llm.byModel).toHaveLength(2);
+ expect(result2.cost?.llm.byModel[0].id).toBe("openai/gpt-4");
+ expect(result2.cost?.llm.byModel[1].id).toBe("anthropic/claude-3-5-sonnet-20241022");
+ });
+ it("should accumulate cache-related tokens", () => {
+ const state = AgentRuntime.createInitialState();
+ const modelUsage = {
+ cost: 0.05,
+ inputCacheMissTokens: 60,
+ inputCachedTokens: 40,
+ inputWriteCacheTokens: 20,
+ totalInputTokens: 100,
+ totalOutputTokens: 50,
+ totalTokens: 150
+ };
+ const { cost } = UsageCounter.accumulateLLM({
+ cost: state.cost,
+ model: "claude-3-5-sonnet-20241022",
+ modelUsage,
+ provider: "anthropic",
+ usage: state.usage
+ });
+ expect(cost?.llm.byModel[0].usage).toEqual({
+ cost: 0.05,
+ inputCacheMissTokens: 60,
+ inputCachedTokens: 40,
+ inputWriteCacheTokens: 20,
+ totalInputTokens: 100,
+ totalOutputTokens: 50,
+ totalTokens: 150
+ });
+ });
+ it("should accumulate total costs correctly", () => {
+ const state = AgentRuntime.createInitialState();
+ const usage1 = {
+ cost: 0.05,
+ totalInputTokens: 100,
+ totalOutputTokens: 50,
+ totalTokens: 150
+ };
+ const usage2 = {
+ cost: 0.03,
+ totalInputTokens: 50,
+ totalOutputTokens: 25,
+ totalTokens: 75
+ };
+ const result1 = UsageCounter.accumulateLLM({
+ cost: state.cost,
+ model: "gpt-4",
+ modelUsage: usage1,
+ provider: "openai",
+ usage: state.usage
+ });
+ const result2 = UsageCounter.accumulateLLM({
+ cost: result1.cost,
+ model: "claude-3-5-sonnet-20241022",
+ modelUsage: usage2,
+ provider: "anthropic",
+ usage: result1.usage
+ });
+ expect(result2.cost?.llm.total).toBe(0.08);
+ expect(result2.cost?.total).toBe(0.08);
+ expect(result2.cost?.calculatedAt).toBeDefined();
+ });
+ it("should not accumulate cost when usage.cost is undefined", () => {
+ const state = AgentRuntime.createInitialState();
+ const modelUsage = {
+ totalInputTokens: 100,
+ totalOutputTokens: 50,
+ totalTokens: 150
+ };
+ const { cost } = UsageCounter.accumulateLLM({
+ cost: state.cost,
+ model: "gpt-4",
+ modelUsage,
+ provider: "openai",
+ usage: state.usage
+ });
+ expect(cost?.llm.byModel).toHaveLength(0);
+ expect(cost?.llm.total).toBe(0);
+ expect(cost?.total).toBe(0);
+ });
+ it("should increment apiCalls for each accumulation", () => {
+ const state = AgentRuntime.createInitialState();
+ const modelUsage = {
+ totalInputTokens: 100,
+ totalOutputTokens: 50,
+ totalTokens: 150
+ };
+ const result1 = UsageCounter.accumulateLLM({
+ cost: state.cost,
+ model: "gpt-4",
+ modelUsage,
+ provider: "openai",
+ usage: state.usage
+ });
+ const result2 = UsageCounter.accumulateLLM({
+ cost: result1.cost,
+ model: "gpt-4",
+ modelUsage,
+ provider: "openai",
+ usage: result1.usage
+ });
+ const result3 = UsageCounter.accumulateLLM({
+ cost: result2.cost,
+ model: "claude-3-5-sonnet-20241022",
+ modelUsage,
+ provider: "anthropic",
+ usage: result2.usage
+ });
+ expect(result3.usage.llm.apiCalls).toBe(3);
+ });
+ it("should auto-create usage and cost when not provided", () => {
+ const modelUsage = {
+ cost: 0.05,
+ totalInputTokens: 100,
+ totalOutputTokens: 50,
+ totalTokens: 150
+ };
+ const { usage, cost } = UsageCounter.accumulateLLM({
+ model: "gpt-4",
+ modelUsage,
+ provider: "openai"
+ });
+ expect(usage).toBeDefined();
+ expect(usage.llm.tokens.input).toBe(100);
+ expect(usage.llm.tokens.output).toBe(50);
+ expect(usage.llm.tokens.total).toBe(150);
+ expect(usage.llm.apiCalls).toBe(1);
+ expect(cost).toBeDefined();
+ expect(cost?.total).toBe(0.05);
+ expect(cost?.llm.total).toBe(0.05);
+ });
+ });
+ describe("UsageCounter.accumulateTool", () => {
+ it("should accumulate tool usage", () => {
+ const state = AgentRuntime.createInitialState();
+ const { usage } = UsageCounter.accumulateTool({
+ cost: state.cost,
+ executionTime: 1e3,
+ success: true,
+ toolName: "search",
+ usage: state.usage
+ });
+ expect(usage.tools.byTool).toHaveLength(1);
+ expect(usage.tools.byTool[0]).toEqual({
+ calls: 1,
+ errors: 0,
+ name: "search",
+ totalTimeMs: 1e3
+ });
+ expect(usage.tools.totalCalls).toBe(1);
+ expect(usage.tools.totalTimeMs).toBe(1e3);
+ });
+ it("should not mutate original usage", () => {
+ const state = AgentRuntime.createInitialState();
+ const { usage } = UsageCounter.accumulateTool({
+ cost: state.cost,
+ executionTime: 1e3,
+ success: true,
+ toolName: "search",
+ usage: state.usage
+ });
+ expect(state.usage.tools.totalCalls).toBe(0);
+ expect(usage).not.toBe(state.usage);
+ });
+ it("should accumulate errors when success is false", () => {
+ const state = AgentRuntime.createInitialState();
+ const { usage } = UsageCounter.accumulateTool({
+ cost: state.cost,
+ executionTime: 1e3,
+ success: false,
+ toolName: "search",
+ usage: state.usage
+ });
+ expect(usage.tools.byTool[0]).toEqual({
+ calls: 1,
+ errors: 1,
+ name: "search",
+ totalTimeMs: 1e3
+ });
+ });
+ it("should accumulate multiple tool calls", () => {
+ const state = AgentRuntime.createInitialState();
+ const result1 = UsageCounter.accumulateTool({
+ cost: state.cost,
+ executionTime: 1e3,
+ success: true,
+ toolName: "search",
+ usage: state.usage
+ });
+ const result2 = UsageCounter.accumulateTool({
+ cost: result1.cost,
+ executionTime: 500,
+ success: true,
+ toolName: "search",
+ usage: result1.usage
+ });
+ const result3 = UsageCounter.accumulateTool({
+ cost: result2.cost,
+ executionTime: 200,
+ success: false,
+ toolName: "calculator",
+ usage: result2.usage
+ });
+ expect(result3.usage.tools.byTool).toHaveLength(2);
+ expect(result3.usage.tools.byTool.find((t) => t.name === "search")).toEqual({
+ calls: 2,
+ errors: 0,
+ name: "search",
+ totalTimeMs: 1500
+ });
+ expect(result3.usage.tools.byTool.find((t) => t.name === "calculator")).toEqual({
+ calls: 1,
+ errors: 1,
+ name: "calculator",
+ totalTimeMs: 200
+ });
+ expect(result3.usage.tools.totalCalls).toBe(3);
+ expect(result3.usage.tools.totalTimeMs).toBe(1700);
+ });
+ it("should accumulate tool cost when provided", () => {
+ const state = AgentRuntime.createInitialState();
+ const { cost } = UsageCounter.accumulateTool({
+ cost: state.cost,
+ executionTime: 1e3,
+ success: true,
+ toolCost: 0.01,
+ toolName: "premium-search",
+ usage: state.usage
+ });
+ expect(cost?.tools.byTool).toHaveLength(1);
+ expect(cost?.tools.byTool[0]).toEqual({
+ calls: 1,
+ currency: "USD",
+ name: "premium-search",
+ totalCost: 0.01
+ });
+ expect(cost?.tools.total).toBe(0.01);
+ expect(cost?.total).toBe(0.01);
+ });
+ it("should accumulate tool cost across multiple calls", () => {
+ const state = AgentRuntime.createInitialState();
+ const result1 = UsageCounter.accumulateTool({
+ cost: state.cost,
+ executionTime: 1e3,
+ success: true,
+ toolCost: 0.01,
+ toolName: "premium-search",
+ usage: state.usage
+ });
+ const result2 = UsageCounter.accumulateTool({
+ cost: result1.cost,
+ executionTime: 500,
+ success: true,
+ toolCost: 5e-3,
+ toolName: "premium-search",
+ usage: result1.usage
+ });
+ expect(result2.cost?.tools.byTool).toHaveLength(1);
+ expect(result2.cost?.tools.byTool[0]).toEqual({
+ calls: 2,
+ currency: "USD",
+ name: "premium-search",
+ totalCost: 0.015
+ });
+ expect(result2.cost?.tools.total).toBe(0.015);
+ expect(result2.cost?.total).toBe(0.015);
+ });
+ it("should not accumulate cost when cost is undefined", () => {
+ const state = AgentRuntime.createInitialState();
+ const { cost } = UsageCounter.accumulateTool({
+ cost: state.cost,
+ executionTime: 1e3,
+ success: true,
+ toolName: "free-tool",
+ usage: state.usage
+ });
+ expect(cost?.tools.byTool).toHaveLength(0);
+ expect(cost?.tools.total).toBe(0);
+ });
+ });
+ describe("mixed accumulation", () => {
+ it("should accumulate both LLM and tool costs correctly", () => {
+ const state = AgentRuntime.createInitialState();
+ const llmUsage = {
+ cost: 0.05,
+ totalInputTokens: 100,
+ totalOutputTokens: 50,
+ totalTokens: 150
+ };
+ const result1 = UsageCounter.accumulateLLM({
+ cost: state.cost,
+ model: "gpt-4",
+ modelUsage: llmUsage,
+ provider: "openai",
+ usage: state.usage
+ });
+ const result2 = UsageCounter.accumulateTool({
+ cost: result1.cost,
+ executionTime: 1e3,
+ success: true,
+ toolCost: 0.01,
+ toolName: "premium-search",
+ usage: result1.usage
+ });
+ expect(result2.cost?.llm.total).toBe(0.05);
+ expect(result2.cost?.tools.total).toBe(0.01);
+ expect(result2.cost?.total).toBeCloseTo(0.06);
+ });
+ });
+ describe("mergeModelUsage (private method tests via accumulateLLM)", () => {
+ it("should merge basic token counts", () => {
+ const state = AgentRuntime.createInitialState();
+ const usage1 = {
+ cost: 0.05,
+ totalInputTokens: 100,
+ totalOutputTokens: 50,
+ totalTokens: 150
+ };
+ const usage2 = {
+ cost: 0.03,
+ totalInputTokens: 200,
+ totalOutputTokens: 100,
+ totalTokens: 300
+ };
+ const result1 = UsageCounter.accumulateLLM({
+ cost: state.cost,
+ model: "gpt-4",
+ modelUsage: usage1,
+ provider: "openai",
+ usage: state.usage
+ });
+ const result2 = UsageCounter.accumulateLLM({
+ cost: result1.cost,
+ model: "gpt-4",
+ modelUsage: usage2,
+ provider: "openai",
+ usage: result1.usage
+ });
+ expect(result2.cost?.llm.byModel[0].usage).toEqual({
+ cost: 0.08,
+ totalInputTokens: 300,
+ totalOutputTokens: 150,
+ totalTokens: 450
+ });
+ });
+ it("should merge cache-related tokens", () => {
+ const state = AgentRuntime.createInitialState();
+ const usage1 = {
+ cost: 0.05,
+ inputCacheMissTokens: 30,
+ inputCachedTokens: 50,
+ inputWriteCacheTokens: 20,
+ totalInputTokens: 100,
+ totalOutputTokens: 50,
+ totalTokens: 150
+ };
+ const usage2 = {
+ cost: 0.03,
+ inputCacheMissTokens: 40,
+ inputCachedTokens: 80,
+ inputWriteCacheTokens: 30,
+ totalInputTokens: 150,
+ totalOutputTokens: 75,
+ totalTokens: 225
+ };
+ const result1 = UsageCounter.accumulateLLM({
+ cost: state.cost,
+ model: "claude-3-5-sonnet-20241022",
+ modelUsage: usage1,
+ provider: "anthropic",
+ usage: state.usage
+ });
+ const result2 = UsageCounter.accumulateLLM({
+ cost: result1.cost,
+ model: "claude-3-5-sonnet-20241022",
+ modelUsage: usage2,
+ provider: "anthropic",
+ usage: result1.usage
+ });
+ expect(result2.cost?.llm.byModel[0].usage).toEqual({
+ cost: 0.08,
+ inputCacheMissTokens: 70,
+ inputCachedTokens: 130,
+ inputWriteCacheTokens: 50,
+ totalInputTokens: 250,
+ totalOutputTokens: 125,
+ totalTokens: 375
+ });
+ });
+ it("should merge reasoning tokens", () => {
+ const state = AgentRuntime.createInitialState();
+ const usage1 = {
+ cost: 0.05,
+ outputReasoningTokens: 100,
+ outputTextTokens: 200,
+ totalInputTokens: 100,
+ totalOutputTokens: 300,
+ totalTokens: 400
+ };
+ const usage2 = {
+ cost: 0.03,
+ outputReasoningTokens: 50,
+ outputTextTokens: 100,
+ totalInputTokens: 50,
+ totalOutputTokens: 150,
+ totalTokens: 200
+ };
+ const result1 = UsageCounter.accumulateLLM({
+ cost: state.cost,
+ model: "o1",
+ modelUsage: usage1,
+ provider: "openai",
+ usage: state.usage
+ });
+ const result2 = UsageCounter.accumulateLLM({
+ cost: result1.cost,
+ model: "o1",
+ modelUsage: usage2,
+ provider: "openai",
+ usage: result1.usage
+ });
+ expect(result2.cost?.llm.byModel[0].usage).toEqual({
+ cost: 0.08,
+ outputReasoningTokens: 150,
+ outputTextTokens: 300,
+ totalInputTokens: 150,
+ totalOutputTokens: 450,
+ totalTokens: 600
+ });
+ });
+ it("should merge audio and image tokens", () => {
+ const state = AgentRuntime.createInitialState();
+ const usage1 = {
+ cost: 0.05,
+ inputAudioTokens: 10,
+ inputImageTokens: 20,
+ outputAudioTokens: 5,
+ outputImageTokens: 15,
+ totalInputTokens: 30,
+ totalOutputTokens: 20,
+ totalTokens: 50
+ };
+ const usage2 = {
+ cost: 0.03,
+ inputAudioTokens: 15,
+ inputImageTokens: 25,
+ outputAudioTokens: 8,
+ outputImageTokens: 12,
+ totalInputTokens: 40,
+ totalOutputTokens: 20,
+ totalTokens: 60
+ };
+ const result1 = UsageCounter.accumulateLLM({
+ cost: state.cost,
+ model: "gpt-4o-audio-preview",
+ modelUsage: usage1,
+ provider: "openai",
+ usage: state.usage
+ });
+ const result2 = UsageCounter.accumulateLLM({
+ cost: result1.cost,
+ model: "gpt-4o-audio-preview",
+ modelUsage: usage2,
+ provider: "openai",
+ usage: result1.usage
+ });
+ expect(result2.cost?.llm.byModel[0].usage).toEqual({
+ cost: 0.08,
+ inputAudioTokens: 25,
+ inputImageTokens: 45,
+ outputAudioTokens: 13,
+ outputImageTokens: 27,
+ totalInputTokens: 70,
+ totalOutputTokens: 40,
+ totalTokens: 110
+ });
+ });
+ it("should merge prediction tokens", () => {
+ const state = AgentRuntime.createInitialState();
+ const usage1 = {
+ acceptedPredictionTokens: 50,
+ cost: 0.05,
+ rejectedPredictionTokens: 10,
+ totalInputTokens: 100,
+ totalOutputTokens: 60,
+ totalTokens: 160
+ };
+ const usage2 = {
+ acceptedPredictionTokens: 30,
+ cost: 0.03,
+ rejectedPredictionTokens: 5,
+ totalInputTokens: 50,
+ totalOutputTokens: 35,
+ totalTokens: 85
+ };
+ const result1 = UsageCounter.accumulateLLM({
+ cost: state.cost,
+ model: "gpt-4o",
+ modelUsage: usage1,
+ provider: "openai",
+ usage: state.usage
+ });
+ const result2 = UsageCounter.accumulateLLM({
+ cost: result1.cost,
+ model: "gpt-4o",
+ modelUsage: usage2,
+ provider: "openai",
+ usage: result1.usage
+ });
+ expect(result2.cost?.llm.byModel[0].usage).toEqual({
+ acceptedPredictionTokens: 80,
+ cost: 0.08,
+ rejectedPredictionTokens: 15,
+ totalInputTokens: 150,
+ totalOutputTokens: 95,
+ totalTokens: 245
+ });
+ });
+ it("should handle missing fields gracefully", () => {
+ const state = AgentRuntime.createInitialState();
+ const usage1 = {
+ cost: 0.05,
+ totalInputTokens: 100
+ // totalOutputTokens is missing
+ };
+ const usage2 = {
+ cost: 0.03,
+ totalOutputTokens: 50
+ // totalInputTokens is missing
+ };
+ const result1 = UsageCounter.accumulateLLM({
+ cost: state.cost,
+ model: "gpt-4",
+ modelUsage: usage1,
+ provider: "openai",
+ usage: state.usage
+ });
+ const result2 = UsageCounter.accumulateLLM({
+ cost: result1.cost,
+ model: "gpt-4",
+ modelUsage: usage2,
+ provider: "openai",
+ usage: result1.usage
+ });
+ expect(result2.cost?.llm.byModel[0].usage).toEqual({
+ cost: 0.08,
+ totalInputTokens: 100,
+ totalOutputTokens: 50
+ });
+ });
+ it("should merge all fields in a comprehensive scenario", () => {
+ const state = AgentRuntime.createInitialState();
+ const usage1 = {
+ acceptedPredictionTokens: 10,
+ cost: 0.05,
+ inputAudioTokens: 5,
+ inputCacheMissTokens: 40,
+ inputCachedTokens: 60,
+ inputCitationTokens: 10,
+ inputImageTokens: 20,
+ inputTextTokens: 100,
+ inputWriteCacheTokens: 30,
+ outputAudioTokens: 3,
+ outputImageTokens: 8,
+ outputReasoningTokens: 20,
+ outputTextTokens: 50,
+ rejectedPredictionTokens: 5,
+ totalInputTokens: 200,
+ totalOutputTokens: 80,
+ totalTokens: 280
+ };
+ const usage2 = {
+ acceptedPredictionTokens: 5,
+ cost: 0.03,
+ inputAudioTokens: 3,
+ inputCacheMissTokens: 20,
+ inputCachedTokens: 30,
+ inputCitationTokens: 5,
+ inputImageTokens: 10,
+ inputTextTokens: 50,
+ inputWriteCacheTokens: 15,
+ outputAudioTokens: 2,
+ outputImageTokens: 4,
+ outputReasoningTokens: 10,
+ outputTextTokens: 25,
+ rejectedPredictionTokens: 2,
+ totalInputTokens: 100,
+ totalOutputTokens: 40,
+ totalTokens: 140
+ };
+ const result1 = UsageCounter.accumulateLLM({
+ cost: state.cost,
+ model: "claude-3-5-sonnet-20241022",
+ modelUsage: usage1,
+ provider: "anthropic",
+ usage: state.usage
+ });
+ const result2 = UsageCounter.accumulateLLM({
+ cost: result1.cost,
+ model: "claude-3-5-sonnet-20241022",
+ modelUsage: usage2,
+ provider: "anthropic",
+ usage: result1.usage
+ });
+ expect(result2.cost?.llm.byModel[0].usage).toEqual({
+ acceptedPredictionTokens: 15,
+ cost: 0.08,
+ inputAudioTokens: 8,
+ inputCacheMissTokens: 60,
+ inputCachedTokens: 90,
+ inputCitationTokens: 15,
+ inputImageTokens: 30,
+ inputTextTokens: 150,
+ inputWriteCacheTokens: 45,
+ outputAudioTokens: 5,
+ outputImageTokens: 12,
+ outputReasoningTokens: 30,
+ outputTextTokens: 75,
+ rejectedPredictionTokens: 7,
+ totalInputTokens: 300,
+ totalOutputTokens: 120,
+ totalTokens: 420
+ });
+ });
+ });
+});
diff --git a/packages/agent-runtime/tests/defaultSecurityBlacklist.test.js b/packages/agent-runtime/tests/defaultSecurityBlacklist.test.js
new file mode 100644
index 000000000..f2d76e3be
--- /dev/null
+++ b/packages/agent-runtime/tests/defaultSecurityBlacklist.test.js
@@ -0,0 +1,761 @@
+import { describe, expect, it } from "vitest";
+import { InterventionChecker } from "../src/core/InterventionChecker.js";
+import { DEFAULT_SECURITY_BLACKLIST } from "../src/core/defaultSecurityBlacklist.js";
+describe("DEFAULT_SECURITY_BLACKLIST", () => {
+ describe("File System Dangers", () => {
+ describe("Recursive deletion of home directory", () => {
+ it("should block rm -rf ~/", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "rm -rf ~/"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe("Recursive deletion of home directory is extremely dangerous");
+ });
+ it("should block rm -rf ~ without trailing slash", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "rm -rf ~"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should block rm -rf $HOME", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "rm -rf $HOME"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should block rm -rf /Users/username on macOS", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "rm -rf /Users/alice"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should block rm -rf /home/username on Linux", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "rm -rf /home/alice"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should block rm with different flag orders", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "rm -r -f ~/"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should allow safe deletions in subdirectories", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "rm -rf ~/Projects/temp"
+ });
+ expect(result.blocked).toBe(false);
+ });
+ it("should allow safe deletions in /home subdirectories", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "rm -rf /home/alice/temp-folder"
+ });
+ expect(result.blocked).toBe(false);
+ });
+ });
+ describe("Recursive deletion of root directory", () => {
+ it("should block rm -rf /", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "rm -rf /"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe("Recursive deletion of root directory will destroy the system");
+ });
+ it("should block rm -r /", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "rm -r /"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should allow safe deletions in specific directories", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "rm -rf /tmp/test-folder"
+ });
+ expect(result.blocked).toBe(false);
+ });
+ it("should allow safe deletions in /var/tmp", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "rm -rf /var/tmp/cache"
+ });
+ expect(result.blocked).toBe(false);
+ });
+ });
+ describe("Force recursive deletion without specific target", () => {
+ it("should block rm -rf . (current directory)", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "rm -rf ."
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should block rm -rf ~", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "rm -rf ~"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should block rm -rf /", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "rm -rf /"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should allow rm -rf with specific target", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "rm -rf /tmp/specific-folder"
+ });
+ expect(result.blocked).toBe(false);
+ });
+ });
+ });
+ describe("System Configuration Dangers", () => {
+ describe("Modifying /etc/passwd and /etc/shadow", () => {
+ it("should block commands affecting /etc/passwd", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: 'echo "malicious" >> /etc/passwd'
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe("Modifying /etc/passwd could lock you out of the system");
+ });
+ it("should block cat /etc/shadow", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "cat /etc/shadow"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should block editing /etc/passwd with vim", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "vim /etc/passwd"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should allow reading safe files in /etc", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "cat /etc/hostname"
+ });
+ expect(result.blocked).toBe(false);
+ });
+ });
+ describe("Modifying sudoers file", () => {
+ it("should block editing /etc/sudoers", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "nano /etc/sudoers"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe("Modifying sudoers file without proper validation is dangerous");
+ });
+ it("should block cat /etc/sudoers", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "cat /etc/sudoers"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should block editing sudoers.d files", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "vim /etc/sudoers.d/custom"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ });
+ });
+ describe("Dangerous Commands", () => {
+ describe("Fork bomb", () => {
+ it("should block classic fork bomb syntax", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: ":(){ :|:& };:"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe("Fork bomb can crash the system");
+ });
+ });
+ describe("Writing to disk devices", () => {
+ it("should block dd to /dev/sda", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "dd if=/dev/zero of=/dev/sda"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe("Writing random data to disk devices can destroy data");
+ });
+ it("should block dd to /dev/hda", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "dd if=/dev/urandom of=/dev/hda"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should block dd to NVMe devices", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "dd if=/dev/zero of=/dev/nvme0n1"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should allow safe dd operations to files", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "dd if=/dev/zero of=/tmp/test.img bs=1M count=100"
+ });
+ expect(result.blocked).toBe(false);
+ });
+ });
+ describe("Formatting system partitions", () => {
+ it("should block mkfs on disk devices", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "mkfs.ext4 /dev/sda1"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe("Formatting system partitions will destroy data");
+ });
+ it("should block fdisk on disks", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "fdisk /dev/sda"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should block parted on root", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "parted /"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ });
+ });
+ describe("Network & Remote Access Dangers", () => {
+ describe("Disabling firewall", () => {
+ it("should block ufw disable", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "ufw disable"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe("Disabling firewall exposes system to attacks");
+ });
+ it("should block iptables -F", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "iptables -F"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should block stopping firewalld", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "systemctl stop firewalld"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should allow checking firewall status", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "ufw status"
+ });
+ expect(result.blocked).toBe(false);
+ });
+ });
+ describe("Changing SSH configuration", () => {
+ it("should block editing sshd_config", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "nano /etc/ssh/sshd_config"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe("Changing SSH configuration could lock you out");
+ });
+ it("should block cat /etc/ssh/sshd_config", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "cat /etc/ssh/sshd_config"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should block vim on sshd_config", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "vim /etc/ssh/sshd_config"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ });
+ });
+ describe("Package Manager Dangers", () => {
+ describe("Removing essential system packages", () => {
+ it("should block apt remove systemd", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "apt remove systemd"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe("Removing essential system packages can break the system");
+ });
+ it("should block yum erase kernel", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "yum erase kernel"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should block dnf remove glibc", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "dnf remove glibc"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should block apt purge bash", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "apt purge bash"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should block pacman removing sudo", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "pacman remove sudo"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should allow removing safe packages", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "apt remove cowsay"
+ });
+ expect(result.blocked).toBe(false);
+ });
+ });
+ });
+ describe("Kernel & System Core Dangers", () => {
+ describe("Modifying kernel parameters", () => {
+ it("should block echo to /proc/sys/", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "echo 1>/proc/sys/kernel/panic"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe(
+ "Modifying kernel parameters without understanding can crash the system"
+ );
+ });
+ it("should block modifying network parameters", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "echo 0>/proc/sys/net/ipv4/ip_forward"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should allow reading /proc/sys/", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "cat /proc/sys/kernel/hostname"
+ });
+ expect(result.blocked).toBe(false);
+ });
+ });
+ describe("Direct memory access", () => {
+ it("should block access to /dev/mem", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "dd if=/dev/mem of=/tmp/memory.dump"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe("Direct memory access is extremely dangerous");
+ });
+ it("should block access to /dev/kmem", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "cat /dev/kmem"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should block access to /dev/port", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "hexdump /dev/port"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ });
+ });
+ describe("Privilege Escalation Dangers", () => {
+ describe("Changing file ownership of system directories", () => {
+ it("should block chown -R on /etc", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "chown -R user:user /etc"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe("Changing file ownership of system directories is dangerous");
+ });
+ it("should block chown -R on /bin", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "chown -R alice:alice /bin"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should block chown -R on home directory", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "chown -R root:root ~"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should allow chown on specific user files", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "chown alice:alice /home/alice/file.txt"
+ });
+ expect(result.blocked).toBe(false);
+ });
+ });
+ describe("Setting SUID on shells or interpreters", () => {
+ it("should block chmod 4755 on bash", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "chmod 4755 /bin/bash"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe("Setting SUID on shells or interpreters is a security risk");
+ });
+ it("should block chmod u+s on python", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "chmod u+s /usr/bin/python"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should block SUID on perl", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "chmod 4755 /usr/bin/perl"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should block SUID on node", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "chmod u+s /usr/bin/node"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should allow normal chmod operations", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "chmod 755 /home/user/script.sh"
+ });
+ expect(result.blocked).toBe(false);
+ });
+ });
+ });
+ describe("Sensitive Information Leakage", () => {
+ describe("Reading .env files", () => {
+ it("should block cat .env via command", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "cat .env"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe(
+ "Reading .env files may leak sensitive credentials and API keys"
+ );
+ });
+ it("should block reading .env via path", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ path: "/project/.env"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should block less .env.local", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "less .env.local"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should block vim .env.production", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "vim .env.production"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should block nano .env.development via path", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ path: "/home/user/project/.env.development"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ });
+ describe("Reading SSH private keys", () => {
+ it("should block cat id_rsa via command", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "cat ~/.ssh/id_rsa"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe("Reading SSH private keys can compromise system security");
+ });
+ it("should block reading id_rsa via path", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ path: "/home/user/.ssh/id_rsa"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should block reading id_ed25519", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "cat ~/.ssh/id_ed25519"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should block reading id_ecdsa via path", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ path: "/home/alice/.ssh/id_ecdsa"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should allow reading SSH public keys", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "cat ~/.ssh/id_rsa.pub"
+ });
+ expect(result.blocked).toBe(false);
+ });
+ it("should allow reading authorized_keys", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "cat ~/.ssh/authorized_keys"
+ });
+ expect(result.blocked).toBe(false);
+ });
+ });
+ describe("Reading AWS credentials", () => {
+ it("should block cat ~/.aws/credentials via command", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "cat ~/.aws/credentials"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe("Accessing AWS credentials can leak cloud access keys");
+ });
+ it("should block reading AWS credentials via path", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ path: "/home/user/.aws/credentials"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should block less on AWS credentials", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "less /home/user/.aws/credentials"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should allow reading AWS config", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "cat ~/.aws/config"
+ });
+ expect(result.blocked).toBe(false);
+ });
+ });
+ describe("Reading Docker config", () => {
+ it("should block reading Docker config.json via command", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "cat ~/.docker/config.json"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe("Reading Docker config may expose registry credentials");
+ });
+ it("should block reading Docker config via path", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ path: "/home/user/.docker/config.json"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should block vim on Docker config", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "vim ~/.docker/config.json"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ });
+ describe("Reading Kubernetes config", () => {
+ it("should block reading kube config via command", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "cat ~/.kube/config"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe("Reading Kubernetes config may expose cluster credentials");
+ });
+ it("should block reading kube config via path", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ path: "/home/user/.kube/config"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should block editing kube config", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "nano ~/.kube/config"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ });
+ describe("Reading Git credentials", () => {
+ it("should block reading git-credentials via command", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "cat ~/.git-credentials"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe("Reading Git credentials file may leak access tokens");
+ });
+ it("should block reading git-credentials via path", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ path: "/home/user/.git-credentials"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should block viewing git-credentials with less", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "less ~/.git-credentials"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ });
+ describe("Reading npm token file", () => {
+ it("should block reading .npmrc via command", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "cat ~/.npmrc"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe(
+ "Reading npm token file may expose package registry credentials"
+ );
+ });
+ it("should block reading .npmrc via path", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ path: "/home/user/.npmrc"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should block editing .npmrc", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "vim /home/user/.npmrc"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ });
+ describe("Reading history files", () => {
+ it("should block reading bash_history via command", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "cat ~/.bash_history"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe(
+ "Reading history files may expose sensitive commands and credentials"
+ );
+ });
+ it("should block reading bash_history via path", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ path: "/home/user/.bash_history"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should block reading zsh_history", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "cat ~/.zsh_history"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should block reading .history via path", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ path: "/home/user/.history"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ });
+ describe("Accessing browser credential storage", () => {
+ it("should block reading browser Cookies file", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "cat ~/Library/Application Support/Google/Chrome/Default/Cookies"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe("Accessing browser credential storage may leak passwords");
+ });
+ it("should block reading Login Data", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "less ~/.config/chromium/Default/Login Data"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should block reading Web Data", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "head ~/.mozilla/firefox/profile/Web Data"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ });
+ describe("Reading GCP credentials", () => {
+ it("should block reading GCP JSON credentials via command", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "cat ~/.config/gcloud/application_default_credentials.json"
+ });
+ expect(result.blocked).toBe(true);
+ expect(result.reason).toBe("Reading GCP credentials may leak cloud service account keys");
+ });
+ it("should block reading GCP credentials via path", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ path: "/home/user/.config/gcloud/service-account.json"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should block viewing GCP credentials with vim", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "vim ~/.config/gcloud/credentials.json"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should allow reading non-sensitive gcloud config", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "cat ~/.config/gcloud/config.txt"
+ });
+ expect(result.blocked).toBe(false);
+ });
+ });
+ });
+ describe("Blacklist structure validation", () => {
+ it("should have description for all rules", () => {
+ DEFAULT_SECURITY_BLACKLIST.forEach((rule) => {
+ expect(rule.description).toBeDefined();
+ expect(rule.description.length).toBeGreaterThan(0);
+ });
+ });
+ it("should have match conditions for all rules", () => {
+ DEFAULT_SECURITY_BLACKLIST.forEach((rule) => {
+ expect(rule.match).toBeDefined();
+ expect(Object.keys(rule.match).length).toBeGreaterThan(0);
+ });
+ });
+ it("should use regex type for pattern matching", () => {
+ DEFAULT_SECURITY_BLACKLIST.forEach((rule) => {
+ Object.values(rule.match).forEach((matcher) => {
+ if (typeof matcher === "object" && "type" in matcher) {
+ expect(matcher.type).toBe("regex");
+ }
+ });
+ });
+ });
+ it("should have valid regex patterns", () => {
+ DEFAULT_SECURITY_BLACKLIST.forEach((rule) => {
+ Object.values(rule.match).forEach((matcher) => {
+ if (typeof matcher === "object" && "pattern" in matcher) {
+ expect(() => new RegExp(matcher.pattern)).not.toThrow();
+ }
+ });
+ });
+ });
+ });
+ describe("Edge cases and comprehensive coverage", () => {
+ it("should handle multiple dangerous patterns in single command", () => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: "cat .env && cat ~/.ssh/id_rsa"
+ });
+ expect(result.blocked).toBe(true);
+ });
+ it("should allow safe file operations", () => {
+ const safeCommands = [
+ "cat README.md",
+ "less package.json",
+ "vim src/index.ts",
+ "rm -rf node_modules",
+ "chmod +x script.sh",
+ "chown user file.txt",
+ "ls -la",
+ 'grep "pattern" file.txt'
+ ];
+ safeCommands.forEach((command) => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command
+ });
+ expect(result.blocked).toBe(false);
+ });
+ });
+ it("should block operations across different editors", () => {
+ const editors = ["cat", "less", "more", "head", "tail", "vim", "nano", "vi", "emacs", "code"];
+ editors.forEach((editor) => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command: `${editor} .env`
+ });
+ expect(result.blocked).toBe(true);
+ });
+ });
+ it("should handle commands with various spacing and flags", () => {
+ const variations = ["rm -rf ~/", "rm -rf ~/", "rm -r -f ~/", "rm -r -f ~/"];
+ variations.forEach((command) => {
+ const result = InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, {
+ command
+ });
+ expect(result.blocked).toBe(true);
+ });
+ });
+ });
+});
diff --git a/packages/agent-runtime/tests/importanceScorer.test.js b/packages/agent-runtime/tests/importanceScorer.test.js
new file mode 100644
index 000000000..be625779f
--- /dev/null
+++ b/packages/agent-runtime/tests/importanceScorer.test.js
@@ -0,0 +1,102 @@
+import { describe, expect, it } from "vitest";
+import { ImportanceScorer } from "../src/utils/importanceScorer.js";
+describe("ImportanceScorer", () => {
+ const createMessage = (role, content, extra) => ({
+ content,
+ role,
+ ...extra
+ });
+ describe("scoreMessages", () => {
+ it("should score system messages at maximum importance", () => {
+ const scorer = new ImportanceScorer();
+ const messages = [
+ createMessage("system", "You are a helpful assistant"),
+ createMessage("user", "Hello")
+ ];
+ const scored = scorer.scoreMessages(messages);
+ expect(scored[0].score).toBe(1);
+ });
+ it("should score pinned messages at maximum importance", () => {
+ const scorer = new ImportanceScorer();
+ const messages = [
+ createMessage("user", "Important context", { metadata: { pinned: true } }),
+ createMessage("assistant", "Got it")
+ ];
+ const scored = scorer.scoreMessages(messages);
+ expect(scored[0].score).toBe(1);
+ });
+ it("should score recent messages higher than old ones", () => {
+ const scorer = new ImportanceScorer();
+ const messages = [
+ createMessage("user", "Old message"),
+ createMessage("assistant", "Old response with some significant content and detail"),
+ createMessage("user", "Recent message"),
+ createMessage("assistant", "Recent response with some significant content and detail")
+ ];
+ const scored = scorer.scoreMessages(messages);
+ expect(scored[2].score).toBeGreaterThan(scored[0].score);
+ expect(scored[3].score).toBeGreaterThan(scored[1].score);
+ });
+ it("should boost messages semantically relevant to the current query", () => {
+ const scorer = new ImportanceScorer();
+ const messages = [
+ createMessage("user", "What is the TVL of Aave?"),
+ createMessage("assistant", "Aave has a TVL of $10B across all chains."),
+ createMessage("user", "What about Uniswap?"),
+ createMessage("assistant", "Uniswap has $5B TVL.")
+ ];
+ const scored = scorer.scoreMessages(messages, "Tell me more about Aave TVL");
+ expect(scored[0].score).toBeGreaterThan(0);
+ expect(scored[1].score).toBeGreaterThan(0);
+ });
+ it("should score user messages higher than assistant messages", () => {
+ const scorer = new ImportanceScorer();
+ const messages = [
+ createMessage("user", "A short question"),
+ createMessage("assistant", "A short reply")
+ ];
+ const scored = scorer.scoreMessages(messages);
+ const userScore = scored[0].score;
+ const assistantScore = scored[1].score;
+ expect(userScore).toBeGreaterThanOrEqual(assistantScore);
+ });
+ });
+ describe("partitionForCompression", () => {
+ it("should always keep recent messages", () => {
+ const scorer = new ImportanceScorer({ keepRecentCount: 2 });
+ const messages = Array.from(
+ { length: 10 },
+ (_, i) => createMessage("user", `Message ${i}: ${"x".repeat(100)}`)
+ );
+ const scored = scorer.scoreMessages(messages);
+ const { toKeep } = scorer.partitionForCompression(scored, 500);
+ const keptIndices = toKeep.map((item) => scored.indexOf(item));
+ expect(keptIndices).toContain(8);
+ expect(keptIndices).toContain(9);
+ });
+ it("should always keep pinned messages", () => {
+ const scorer = new ImportanceScorer({ keepRecentCount: 1 });
+ const messages = [
+ createMessage("user", "Important context", { metadata: { pinned: true } }),
+ createMessage("assistant", "Response 1"),
+ createMessage("user", "Later message")
+ ];
+ const scored = scorer.scoreMessages(messages);
+ const { toKeep } = scorer.partitionForCompression(scored, 500);
+ expect(toKeep.some((item) => item.message.content === "Important context")).toBe(true);
+ });
+ it("should compress low-importance messages when budget is tight", () => {
+ const scorer = new ImportanceScorer({ keepRecentCount: 2 });
+ const messages = [
+ createMessage("user", "Old question about weather"),
+ createMessage("assistant", "It is sunny today."),
+ createMessage("user", "What about crypto?"),
+ createMessage("assistant", "Bitcoin is at $50k.")
+ ];
+ const scored = scorer.scoreMessages(messages);
+ const { toCompress, toKeep } = scorer.partitionForCompression(scored, 50);
+ expect(toKeep.length).toBeGreaterThanOrEqual(2);
+ expect(toCompress.length + toKeep.length).toBe(messages.length);
+ });
+ });
+});
diff --git a/packages/agent-runtime/tests/runtime.test.js b/packages/agent-runtime/tests/runtime.test.js
new file mode 100644
index 000000000..ef20857d2
--- /dev/null
+++ b/packages/agent-runtime/tests/runtime.test.js
@@ -0,0 +1,1681 @@
+import { describe, expect, it, vi } from "vitest";
+import { AgentRuntime } from "../src/core/runtime.js";
+class MockAgent {
+ tools = {};
+ executors = {};
+ modelRuntime;
+ async runner(context, state) {
+ switch (context.phase) {
+ case "user_input":
+ return { type: "call_llm", payload: { messages: state.messages } };
+ case "llm_result":
+ const llmPayload = context.payload;
+ if (llmPayload.hasToolCalls) {
+ return {
+ type: "request_human_approve",
+ pendingToolsCalling: llmPayload.result.tool_calls
+ };
+ }
+ return { type: "finish", reason: "completed", reasonDetail: "Done" };
+ case "tool_result":
+ return { type: "call_llm", payload: { messages: state.messages } };
+ default:
+ return { type: "finish", reason: "completed", reasonDetail: "Done" };
+ }
+ }
+}
+function createTestContext(phase, payload, operationId = "test-session") {
+ return {
+ phase,
+ payload,
+ session: {
+ // Note: AgentRuntimeContext.session uses sessionId for backward compatibility
+ sessionId: operationId,
+ messageCount: 1,
+ status: "idle",
+ stepCount: 0
+ }
+ };
+}
+describe("AgentRuntime", () => {
+ describe("Constructor and Executor Priority", () => {
+ it("should use built-in executors by default", () => {
+ const agent = new MockAgent();
+ const runtime = new AgentRuntime(agent);
+ const executors = runtime.executors;
+ expect(executors).toHaveProperty("call_llm");
+ expect(executors).toHaveProperty("call_tool");
+ expect(executors).toHaveProperty("finish");
+ expect(executors).toHaveProperty("request_human_approve");
+ });
+ it("should allow config executors to override built-in ones", () => {
+ const agent = new MockAgent();
+ const customFinish = vi.fn();
+ const config = {
+ executors: {
+ finish: customFinish
+ }
+ };
+ const runtime = new AgentRuntime(agent, config);
+ expect(runtime.executors.finish).toBe(customFinish);
+ });
+ it("should give agent executors highest priority", () => {
+ const agent = new MockAgent();
+ const agentFinish = vi.fn();
+ const configFinish = vi.fn();
+ agent.executors = { finish: agentFinish };
+ const config = {
+ executors: { finish: configFinish }
+ };
+ const runtime = new AgentRuntime(agent, config);
+ expect(runtime.executors.finish).toBe(agentFinish);
+ });
+ });
+ describe("step method", () => {
+ it("should execute approved tool call directly", async () => {
+ const agent = new MockAgent();
+ agent.tools = {
+ test_tool: vi.fn().mockResolvedValue({ result: "success" })
+ };
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({ operationId: "test-session" });
+ const toolCall = {
+ id: "call_123",
+ apiName: "test_tool",
+ identifier: "test_tool",
+ arguments: '{"input": "test"}',
+ type: "default"
+ };
+ const result = await runtime.approveToolCall(state, toolCall);
+ expect(result.events).toHaveLength(1);
+ expect(result.events[0]).toMatchObject({
+ type: "tool_result",
+ id: "call_123",
+ result: { result: "success" }
+ });
+ expect(result.newState.messages).toHaveLength(1);
+ expect(result.newState.messages[0].role).toBe("tool");
+ });
+ it("should follow agent runner -> executor flow", async () => {
+ const agent = new MockAgent();
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({
+ operationId: "test-session",
+ messages: [{ role: "user", content: "Hello" }]
+ });
+ const result = await runtime.step(state);
+ expect(result.events).toHaveLength(1);
+ expect(result.events[0].type).toBe("error");
+ expect(result.newState.status).toBe("error");
+ });
+ it("should handle errors gracefully", async () => {
+ const agent = new MockAgent();
+ agent.runner = vi.fn().mockImplementation(() => Promise.reject(new Error("Agent error")));
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({ operationId: "test-session" });
+ const result = await runtime.step(state);
+ expect(result.events).toHaveLength(1);
+ expect(result.events[0]).toMatchObject({
+ type: "error",
+ error: expect.any(Error)
+ });
+ expect(result.newState.status).toBe("error");
+ expect(result.newState.error).toBeInstanceOf(Error);
+ });
+ });
+ describe("Built-in Executors", () => {
+ describe("call_llm executor", () => {
+ it("should require modelRuntime", async () => {
+ const agent = new MockAgent();
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({
+ operationId: "test-session",
+ messages: [{ role: "user", content: "Hello" }]
+ });
+ const result = await runtime.step(state);
+ expect(result.events[0].type).toBe("error");
+ expect(result.events[0].error.message).toContain(
+ "Model Runtime is required"
+ );
+ });
+ it("should handle streaming LLM response", async () => {
+ const agent = new MockAgent();
+ async function* mockModelRuntime(payload) {
+ yield { content: "Hello" };
+ yield { content: " world" };
+ yield { content: "!" };
+ }
+ agent.modelRuntime = mockModelRuntime;
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({
+ operationId: "test-session",
+ messages: [{ role: "user", content: "Hello" }]
+ });
+ const result = await runtime.step(state);
+ expect(result.events).toHaveLength(5);
+ expect(result.events[0]).toMatchObject({
+ type: "llm_start",
+ payload: expect.anything()
+ });
+ expect(result.events[1]).toMatchObject({
+ type: "llm_stream",
+ chunk: { content: "Hello" }
+ });
+ expect(result.events[4]).toMatchObject({
+ type: "llm_result",
+ result: { content: "Hello world!", tool_calls: [] }
+ });
+ expect(result.newState.messages).toHaveLength(1);
+ expect(result.newState.status).toBe("running");
+ });
+ it("should handle LLM response with tool calls", async () => {
+ const agent = new MockAgent();
+ async function* mockModelRuntime(payload) {
+ yield { content: "I need to use a tool" };
+ yield {
+ tool_calls: [
+ {
+ id: "call_123",
+ type: "function",
+ function: { name: "test_tool", arguments: "{}" }
+ }
+ ]
+ };
+ }
+ agent.modelRuntime = mockModelRuntime;
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({
+ operationId: "test-session",
+ messages: [{ role: "user", content: "Hello" }]
+ });
+ const result = await runtime.step(state);
+ expect(result.events).toContainEqual(
+ expect.objectContaining({
+ type: "llm_result",
+ result: expect.objectContaining({
+ content: "I need to use a tool",
+ tool_calls: [
+ {
+ id: "call_123",
+ type: "function",
+ function: { name: "test_tool", arguments: "{}" }
+ }
+ ]
+ })
+ })
+ );
+ });
+ });
+ describe("call_tool executor", () => {
+ it("should execute tool and add result to messages", async () => {
+ const agent = new MockAgent();
+ agent.tools = {
+ calculator: vi.fn().mockResolvedValue({ result: 42 })
+ };
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({ operationId: "test-session" });
+ const toolCall = {
+ id: "call_123",
+ apiName: "calculator",
+ identifier: "calculator",
+ arguments: '{"expression": "2+2"}',
+ type: "default"
+ };
+ const result = await runtime.approveToolCall(state, toolCall);
+ expect(agent.tools.calculator).toHaveBeenCalledWith({ expression: "2+2" });
+ expect(result.events).toHaveLength(1);
+ expect(result.events[0]).toMatchObject({
+ type: "tool_result",
+ id: "call_123",
+ result: { result: 42 }
+ });
+ expect(result.newState.messages).toHaveLength(1);
+ expect(result.newState.messages[0]).toMatchObject({
+ role: "tool",
+ tool_call_id: "call_123",
+ content: '{"result":42}'
+ });
+ });
+ it("should throw error for unknown tool", async () => {
+ const agent = new MockAgent();
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({ operationId: "test-session" });
+ const toolCall = {
+ id: "call_123",
+ apiName: "unknown_tool",
+ identifier: "unknown_tool",
+ arguments: "{}",
+ type: "default"
+ };
+ const result = await runtime.approveToolCall(state, toolCall);
+ expect(result.events[0].type).toBe("error");
+ expect(result.events[0].error.message).toContain(
+ "Tool not found: unknown_tool"
+ );
+ });
+ });
+ describe("human interaction executors", () => {
+ it("should handle human approve request", async () => {
+ const agent = new MockAgent();
+ agent.runner = vi.fn().mockImplementation(
+ () => Promise.resolve({
+ type: "request_human_approve",
+ pendingToolsCalling: [
+ {
+ apiName: "test_tool",
+ arguments: "{}",
+ id: "call_123",
+ identifier: "test_tool",
+ type: "default"
+ }
+ ]
+ })
+ );
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({ operationId: "test-session" });
+ const result = await runtime.step(state);
+ expect(result.events).toHaveLength(1);
+ expect(result.events[0]).toMatchObject({
+ type: "human_approve_required",
+ operationId: "test-session"
+ });
+ expect(result.newState.status).toBe("waiting_for_human");
+ expect(result.newState.pendingToolsCalling).toBeDefined();
+ });
+ it("should handle human prompt request", async () => {
+ const agent = new MockAgent();
+ agent.runner = vi.fn().mockImplementation(
+ () => Promise.resolve({
+ type: "request_human_prompt",
+ prompt: "Please provide input",
+ metadata: { key: "value" }
+ })
+ );
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({ operationId: "test-session" });
+ const result = await runtime.step(state);
+ expect(result.events).toHaveLength(1);
+ expect(result.events[0]).toMatchObject({
+ type: "human_prompt_required",
+ prompt: "Please provide input",
+ metadata: { key: "value" },
+ operationId: "test-session"
+ });
+ expect(result.newState.status).toBe("waiting_for_human");
+ expect(result.newState.pendingHumanPrompt).toEqual({
+ prompt: "Please provide input",
+ metadata: { key: "value" }
+ });
+ });
+ it("should handle human select request", async () => {
+ const agent = new MockAgent();
+ agent.runner = vi.fn().mockImplementation(
+ () => Promise.resolve({
+ type: "request_human_select",
+ prompt: "Choose an option",
+ options: [
+ { label: "Option 1", value: "opt1" },
+ { label: "Option 2", value: "opt2" }
+ ],
+ multi: false
+ })
+ );
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({ operationId: "test-session" });
+ const result = await runtime.step(state);
+ expect(result.events).toHaveLength(1);
+ expect(result.events[0]).toMatchObject({
+ type: "human_select_required",
+ prompt: "Choose an option",
+ options: [
+ { label: "Option 1", value: "opt1" },
+ { label: "Option 2", value: "opt2" }
+ ],
+ multi: false,
+ operationId: "test-session"
+ });
+ expect(result.newState.status).toBe("waiting_for_human");
+ });
+ });
+ describe("finish executor", () => {
+ it("should mark conversation as done", async () => {
+ const agent = new MockAgent();
+ agent.runner = vi.fn().mockImplementation(
+ () => Promise.resolve({
+ type: "finish",
+ reason: "completed",
+ reasonDetail: "Task completed"
+ })
+ );
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({ operationId: "test-session" });
+ const result = await runtime.step(state);
+ expect(result.events).toHaveLength(1);
+ expect(result.events[0]).toMatchObject({
+ type: "done",
+ finalState: expect.objectContaining({
+ status: "done"
+ }),
+ reason: "completed",
+ reasonDetail: "Task completed"
+ });
+ expect(result.newState.status).toBe("done");
+ });
+ });
+ });
+ describe("createInitialState", () => {
+ it("should create initial state without message", () => {
+ const state = AgentRuntime.createInitialState({ operationId: "test-session" });
+ expect(state).toMatchObject({
+ operationId: "test-session",
+ status: "idle",
+ messages: [],
+ stepCount: 0,
+ createdAt: expect.any(String),
+ lastModified: expect.any(String)
+ });
+ });
+ it("should create initial state with message", () => {
+ const state = AgentRuntime.createInitialState({
+ operationId: "test-session",
+ messages: [{ role: "user", content: "Hello world" }]
+ });
+ expect(state.messages).toHaveLength(1);
+ expect(state.messages[0]).toMatchObject({
+ role: "user",
+ content: "Hello world"
+ });
+ expect(state.stepCount).toBe(0);
+ });
+ it("should create initial state with custom stepCount", () => {
+ const state = AgentRuntime.createInitialState({
+ operationId: "test-session",
+ stepCount: 5
+ });
+ expect(state.stepCount).toBe(5);
+ });
+ it("should create initial state with maxSteps limit", () => {
+ const state = AgentRuntime.createInitialState({
+ operationId: "test-session",
+ maxSteps: 10
+ });
+ expect(state.maxSteps).toBe(10);
+ expect(state.stepCount).toBe(0);
+ });
+ });
+ describe("Step Count Tracking", () => {
+ it("should increment stepCount on each step execution", async () => {
+ const agent = new MockAgent();
+ const runtime = new AgentRuntime(agent);
+ let state = AgentRuntime.createInitialState({ operationId: "test-session" });
+ expect(state.stepCount).toBe(0);
+ const result1 = await runtime.step(state, createTestContext("user_input"));
+ expect(result1.newState.stepCount).toBe(1);
+ const result2 = await runtime.step(result1.newState, createTestContext("user_input"));
+ expect(result2.newState.stepCount).toBe(2);
+ });
+ it("should respect maxSteps limit", async () => {
+ const agent = new MockAgent();
+ agent.modelRuntime = async function* () {
+ yield { content: "test response" };
+ };
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({
+ operationId: "test-session",
+ maxSteps: 3
+ // 允许 3 步
+ });
+ const result1 = await runtime.step(state, createTestContext("user_input"));
+ expect(result1.newState.stepCount).toBe(1);
+ expect(result1.newState.status).not.toBe("error");
+ const result2 = await runtime.step(result1.newState, createTestContext("user_input"));
+ expect(result2.newState.stepCount).toBe(2);
+ expect(result2.newState.status).not.toBe("error");
+ const result3 = await runtime.step(result2.newState, createTestContext("user_input"));
+ expect(result3.newState.stepCount).toBe(3);
+ expect(result3.newState.status).not.toBe("error");
+ const result4 = await runtime.step(result3.newState, createTestContext("user_input"));
+ expect(result4.newState.stepCount).toBe(4);
+ expect(result4.newState.status).toBe("done");
+ expect(result4.events[0]).toMatchObject({
+ type: "done",
+ finalState: expect.objectContaining({
+ status: "done"
+ }),
+ reason: "max_steps_exceeded",
+ reasonDetail: "Maximum steps exceeded: 3"
+ });
+ });
+ it("should include stepCount in session context", async () => {
+ const agent = new MockAgent();
+ const runnerSpy = vi.spyOn(agent, "runner");
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({
+ operationId: "test-session",
+ stepCount: 5,
+ // Start with step 5
+ messages: [{ role: "user", content: "test" }]
+ });
+ await runtime.step(state);
+ expect(runnerSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ session: expect.objectContaining({
+ stepCount: 6
+ // Should be incremented
+ })
+ }),
+ expect.any(Object)
+ );
+ });
+ });
+ describe("Interruption Handling", () => {
+ it("should interrupt execution with reason and metadata", () => {
+ const agent = new MockAgent();
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({
+ operationId: "test-session",
+ stepCount: 3
+ });
+ const result = runtime.interrupt(state, "User requested stop", true, {
+ userAction: "stop_button"
+ });
+ expect(result.newState.status).toBe("interrupted");
+ expect(result.newState.interruption).toMatchObject({
+ reason: "User requested stop",
+ canResume: true,
+ interruptedAt: expect.any(String)
+ });
+ expect(result.events[0]).toMatchObject({
+ type: "interrupted",
+ reason: "User requested stop",
+ canResume: true,
+ metadata: { userAction: "stop_button" },
+ interruptedAt: expect.any(String)
+ });
+ });
+ it("should resume from interrupted state", async () => {
+ const agent = new MockAgent();
+ agent.modelRuntime = async function* () {
+ yield { content: "resumed response" };
+ };
+ const runtime = new AgentRuntime(agent);
+ let state = AgentRuntime.createInitialState({ operationId: "test-session" });
+ const interruptResult = runtime.interrupt(state, "Test interruption");
+ const resumeResult = await runtime.resume(interruptResult.newState, "Test resume");
+ expect(resumeResult.newState.status).toBe("running");
+ expect(resumeResult.newState.interruption).toBeUndefined();
+ expect(resumeResult.events[0]).toMatchObject({
+ type: "resumed",
+ reason: "Test resume",
+ resumedFromStep: 0,
+ resumedAt: expect.any(String)
+ });
+ });
+ it("should not allow resume if canResume is false", async () => {
+ const agent = new MockAgent();
+ const runtime = new AgentRuntime(agent);
+ let state = AgentRuntime.createInitialState({ operationId: "test-session" });
+ const interruptResult = runtime.interrupt(state, "Fatal error", false);
+ await expect(runtime.resume(interruptResult.newState)).rejects.toThrow(
+ "Cannot resume: interruption is not resumable"
+ );
+ });
+ it("should not allow resume from non-interrupted state", async () => {
+ const agent = new MockAgent();
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({ operationId: "test-session" });
+ await expect(runtime.resume(state)).rejects.toThrow(
+ "Cannot resume: state is not interrupted"
+ );
+ });
+ it("should resume with specific context", async () => {
+ const agent = new MockAgent();
+ agent.modelRuntime = async function* () {
+ yield { content: "context-specific response" };
+ };
+ const runtime = new AgentRuntime(agent);
+ let state = AgentRuntime.createInitialState({
+ operationId: "test-session",
+ messages: [{ role: "user", content: "Hello" }]
+ });
+ const interruptResult = runtime.interrupt(state, "Test interruption");
+ const resumeContext = {
+ phase: "user_input",
+ payload: { message: { role: "user", content: "Hello" } },
+ session: {
+ // Note: AgentRuntimeContext.session uses sessionId for backward compatibility
+ sessionId: "test-session",
+ messageCount: 1,
+ status: "interrupted",
+ stepCount: 0
+ }
+ };
+ const resumeResult = await runtime.resume(
+ interruptResult.newState,
+ "Resume with context",
+ resumeContext
+ );
+ expect(resumeResult.events.length).toBeGreaterThanOrEqual(2);
+ expect(resumeResult.events[0].type).toBe("resumed");
+ expect(resumeResult.newState.status).toBe("running");
+ expect(resumeResult.events.map((e) => e.type)).toContain("llm_start");
+ expect(resumeResult.events.map((e) => e.type)).toContain("llm_result");
+ });
+ });
+ describe("Usage and Cost Tracking", () => {
+ it("should initialize with zero usage and cost", () => {
+ const state = AgentRuntime.createInitialState({ operationId: "test-session" });
+ expect(state.usage).toMatchObject({
+ llm: {
+ tokens: { input: 0, output: 0, total: 0 },
+ apiCalls: 0,
+ processingTimeMs: 0
+ },
+ tools: {
+ totalCalls: 0,
+ byTool: [],
+ totalTimeMs: 0
+ },
+ humanInteraction: {
+ approvalRequests: 0,
+ promptRequests: 0,
+ selectRequests: 0,
+ totalWaitingTimeMs: 0
+ }
+ });
+ expect(state.cost).toMatchObject({
+ llm: {
+ byModel: [],
+ total: 0,
+ currency: "USD"
+ },
+ tools: {
+ byTool: [],
+ total: 0,
+ currency: "USD"
+ },
+ total: 0,
+ currency: "USD",
+ calculatedAt: expect.any(String)
+ });
+ });
+ it("should track usage and cost through agent methods", async () => {
+ class CostTrackingAgent {
+ tools = {
+ test_tool: async () => ({ result: "success" })
+ };
+ async runner(context, state2) {
+ switch (context.phase) {
+ case "user_input":
+ return { type: "call_llm", payload: { messages: state2.messages } };
+ default:
+ return {
+ type: "finish",
+ reason: "completed",
+ reasonDetail: "Done"
+ };
+ }
+ }
+ calculateUsage(operationType, operationResult, previousUsage) {
+ const newUsage = structuredClone(previousUsage);
+ if (operationType === "llm") {
+ newUsage.llm.tokens.input += 100;
+ newUsage.llm.tokens.output += 50;
+ newUsage.llm.tokens.total += 150;
+ newUsage.llm.apiCalls += 1;
+ newUsage.llm.processingTimeMs += 1e3;
+ }
+ return newUsage;
+ }
+ calculateCost(context) {
+ const newCost = structuredClone(context.previousCost || context.usage);
+ const tokenCost = context.usage.llm.tokens.total / 1e3 * 0.01;
+ newCost.llm.total = tokenCost;
+ newCost.total = tokenCost;
+ newCost.calculatedAt = (/* @__PURE__ */ new Date()).toISOString();
+ return newCost;
+ }
+ modelRuntime = async function* () {
+ yield { content: "test response" };
+ };
+ }
+ const agent = new CostTrackingAgent();
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({
+ operationId: "test-session",
+ messages: [{ role: "user", content: "Hello" }]
+ });
+ const result = await runtime.step(state, createTestContext("user_input"));
+ expect(result.newState.usage.llm.tokens.total).toBe(150);
+ expect(result.newState.usage.llm.apiCalls).toBe(1);
+ expect(result.newState.cost.total).toBe(15e-4);
+ });
+ it("should respect cost limits with stop action", async () => {
+ class CostTrackingAgent {
+ async runner(context, state2) {
+ return { type: "call_llm", payload: { messages: state2.messages } };
+ }
+ calculateUsage(operationType, operationResult, previousUsage) {
+ const newUsage = structuredClone(previousUsage);
+ newUsage.llm.tokens.total += 1e3;
+ return newUsage;
+ }
+ calculateCost(context) {
+ const newCost = structuredClone(context.previousCost || {});
+ newCost.total = 10;
+ newCost.currency = "USD";
+ newCost.calculatedAt = (/* @__PURE__ */ new Date()).toISOString();
+ return newCost;
+ }
+ modelRuntime = async function* () {
+ yield { content: "test response" };
+ };
+ }
+ const agent = new CostTrackingAgent();
+ const runtime = new AgentRuntime(agent);
+ const costLimit = {
+ maxTotalCost: 5,
+ currency: "USD",
+ onExceeded: "stop"
+ };
+ const state = AgentRuntime.createInitialState({
+ operationId: "test-session",
+ messages: [{ role: "user", content: "Hello" }],
+ costLimit
+ });
+ const result = await runtime.step(state, createTestContext("user_input"));
+ expect(result.newState.status).toBe("done");
+ expect(result.events[0]).toMatchObject({
+ type: "done",
+ reason: "cost_limit_exceeded",
+ reasonDetail: expect.stringContaining("Cost limit exceeded")
+ });
+ });
+ it("should handle cost limit with interrupt action", async () => {
+ class CostTrackingAgent {
+ async runner(context, state2) {
+ return { type: "call_llm", payload: { messages: state2.messages } };
+ }
+ calculateCost(context) {
+ return {
+ llm: { byModel: [], total: 15, currency: "USD" },
+ tools: { byTool: [], total: 0, currency: "USD" },
+ total: 15,
+ currency: "USD",
+ calculatedAt: (/* @__PURE__ */ new Date()).toISOString()
+ };
+ }
+ modelRuntime = async function* () {
+ yield { content: "test response" };
+ };
+ }
+ const agent = new CostTrackingAgent();
+ const runtime = new AgentRuntime(agent);
+ const costLimit = {
+ maxTotalCost: 10,
+ currency: "USD",
+ onExceeded: "interrupt"
+ };
+ const state = AgentRuntime.createInitialState({
+ operationId: "test-session",
+ messages: [{ role: "user", content: "Hello" }],
+ costLimit
+ });
+ const result = await runtime.step(state, createTestContext("user_input"));
+ expect(result.newState.status).toBe("interrupted");
+ expect(result.events[0]).toMatchObject({
+ type: "interrupted",
+ reason: expect.stringContaining("Cost limit exceeded"),
+ metadata: expect.objectContaining({
+ costExceeded: true
+ })
+ });
+ });
+ });
+ describe("Integration Tests", () => {
+ it("should complete a full conversation flow", async () => {
+ const agent = new MockAgent();
+ agent.tools = {
+ get_weather: vi.fn().mockResolvedValue({
+ temperature: 25,
+ condition: "sunny"
+ })
+ };
+ agent.runner = vi.fn().mockImplementation((context, state2) => {
+ switch (context.phase) {
+ case "user_input":
+ return Promise.resolve({ type: "call_llm", payload: { messages: state2.messages } });
+ case "llm_result":
+ const llmPayload = context.payload;
+ if (llmPayload.hasToolCalls) {
+ const pendingToolsCalling = llmPayload.result.tool_calls.map((tc) => ({
+ apiName: tc.function.name,
+ arguments: tc.function.arguments,
+ id: tc.id,
+ identifier: tc.function.name,
+ type: "default"
+ }));
+ return Promise.resolve({
+ pendingToolsCalling,
+ type: "request_human_approve"
+ });
+ }
+ return Promise.resolve({ type: "finish", reason: "completed", reasonDetail: "Done" });
+ case "human_approved_tool":
+ const approvedPayload = context.payload;
+ return Promise.resolve({
+ payload: {
+ parentMessageId: "user-msg-id",
+ toolCalling: approvedPayload.approvedToolCall
+ },
+ type: "call_tool"
+ });
+ case "tool_result":
+ return Promise.resolve({ type: "call_llm", payload: { messages: state2.messages } });
+ default:
+ return Promise.resolve({ type: "finish", reason: "completed", reasonDetail: "Done" });
+ }
+ });
+ async function* mockModelRuntime(payload) {
+ const messages = payload.messages;
+ const lastMessage = messages[messages.length - 1];
+ if (lastMessage.role === "user") {
+ yield { content: "I'll check the weather for you." };
+ yield {
+ tool_calls: [
+ {
+ id: "call_weather",
+ type: "function",
+ function: {
+ name: "get_weather",
+ arguments: '{"city": "Beijing"}'
+ }
+ }
+ ]
+ };
+ } else if (lastMessage.role === "tool") {
+ yield { content: "The weather in Beijing is 25\xB0C and sunny." };
+ }
+ }
+ agent.modelRuntime = mockModelRuntime;
+ const runtime = new AgentRuntime(agent);
+ let state = AgentRuntime.createInitialState({
+ operationId: "test-session",
+ messages: [{ role: "user", content: "What's the weather in Beijing?" }]
+ });
+ let result = await runtime.step(state);
+ expect(result.newState.status).toBe("running");
+ expect(result.newState.messages).toHaveLength(1);
+ expect(result.events).toContainEqual(
+ expect.objectContaining({
+ type: "llm_result",
+ result: expect.objectContaining({
+ tool_calls: expect.arrayContaining([
+ expect.objectContaining({
+ id: "call_weather",
+ type: "function"
+ })
+ ])
+ })
+ })
+ );
+ result = await runtime.step(result.newState, result.nextContext);
+ expect(result.newState.status).toBe("waiting_for_human");
+ expect(result.newState.pendingToolsCalling).toHaveLength(1);
+ const pendingToolCall = result.newState.pendingToolsCalling[0];
+ const toolCall = {
+ apiName: pendingToolCall.apiName,
+ arguments: pendingToolCall.arguments,
+ id: pendingToolCall.id,
+ identifier: pendingToolCall.identifier,
+ type: "default"
+ };
+ result = await runtime.approveToolCall(result.newState, toolCall);
+ expect(agent.tools.get_weather).toHaveBeenCalledWith({ city: "Beijing" });
+ expect(result.newState.messages).toHaveLength(2);
+ result = await runtime.step(result.newState, result.nextContext);
+ expect(result.events).toContainEqual(
+ expect.objectContaining({
+ type: "llm_result",
+ result: expect.objectContaining({
+ content: expect.stringContaining("25\xB0C and sunny")
+ })
+ })
+ );
+ });
+ });
+ describe("Batch Tool Execution", () => {
+ it("should execute multiple tools concurrently with call_tools_batch instruction", async () => {
+ class BatchToolAgent {
+ tools = {
+ tool_a: vi.fn().mockResolvedValue({ result: "result_a" }),
+ tool_b: vi.fn().mockResolvedValue({ result: "result_b" }),
+ tool_c: vi.fn().mockResolvedValue({ result: "result_c" })
+ };
+ async runner(context, _state) {
+ if (context.phase === "user_input") {
+ return {
+ payload: [
+ {
+ id: "call_a",
+ type: "function",
+ function: { name: "tool_a", arguments: "{}" }
+ },
+ {
+ id: "call_b",
+ type: "function",
+ function: { name: "tool_b", arguments: "{}" }
+ },
+ {
+ id: "call_c",
+ type: "function",
+ function: { name: "tool_c", arguments: "{}" }
+ }
+ ],
+ type: "call_tools_batch"
+ };
+ }
+ return { type: "finish", reason: "completed" };
+ }
+ }
+ const agent = new BatchToolAgent();
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({
+ operationId: "batch-test",
+ messages: [{ role: "user", content: "Execute tools" }]
+ });
+ const result = await runtime.step(state);
+ expect(agent.tools.tool_a).toHaveBeenCalled();
+ expect(agent.tools.tool_b).toHaveBeenCalled();
+ expect(agent.tools.tool_c).toHaveBeenCalled();
+ expect(result.events.filter((e) => e.type === "tool_result")).toHaveLength(3);
+ const toolMessages = result.newState.messages.filter((m) => m.role === "tool");
+ expect(toolMessages).toHaveLength(3);
+ expect(result.nextContext?.phase).toBe("tools_batch_result");
+ expect(result.nextContext?.payload).toHaveProperty("toolCount", 3);
+ });
+ it("should support agent returning instruction array", async () => {
+ class ArrayReturnAgent {
+ tools = {
+ tool_1: vi.fn().mockResolvedValue({ result: "tool_1_result" }),
+ tool_2: vi.fn().mockResolvedValue({ result: "tool_2_result" })
+ };
+ async runner(context, _state) {
+ if (context.phase === "user_input") {
+ return [
+ {
+ payload: {
+ parentMessageId: "user-msg-id",
+ toolCalling: {
+ id: "call_1",
+ type: "default",
+ apiName: "tool_1",
+ identifier: "tool_1",
+ arguments: "{}"
+ }
+ },
+ type: "call_tool"
+ },
+ {
+ payload: {
+ parentMessageId: "user-msg-id",
+ toolCalling: {
+ id: "call_2",
+ type: "default",
+ apiName: "tool_2",
+ identifier: "tool_2",
+ arguments: "{}"
+ }
+ },
+ type: "call_tool"
+ }
+ ];
+ }
+ return { type: "finish", reason: "completed" };
+ }
+ }
+ const agent = new ArrayReturnAgent();
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({
+ operationId: "array-test",
+ messages: [{ role: "user", content: "Execute tools" }]
+ });
+ const result = await runtime.step(state);
+ expect(agent.tools.tool_1).toHaveBeenCalled();
+ expect(agent.tools.tool_2).toHaveBeenCalled();
+ expect(result.events.filter((e) => e.type === "tool_result")).toHaveLength(2);
+ const toolMessages = result.newState.messages.filter((m) => m.role === "tool");
+ expect(toolMessages).toHaveLength(2);
+ });
+ it("should stop execution when encountering blocking status", async () => {
+ class BlockingAgent {
+ tools = {
+ safe_tool: vi.fn().mockResolvedValue({ result: "safe_result" })
+ };
+ async runner(context, _state) {
+ if (context.phase === "user_input") {
+ return [
+ {
+ payload: {
+ parentMessageId: "user-msg-id",
+ toolCalling: {
+ id: "call_safe",
+ type: "default",
+ apiName: "safe_tool",
+ identifier: "safe_tool",
+ arguments: "{}"
+ }
+ },
+ type: "call_tool"
+ },
+ {
+ pendingToolsCalling: [
+ {
+ apiName: "danger_tool",
+ arguments: "{}",
+ id: "call_danger",
+ identifier: "danger_tool",
+ type: "default"
+ }
+ ],
+ type: "request_human_approve"
+ }
+ ];
+ }
+ return { type: "finish", reason: "completed" };
+ }
+ }
+ const agent = new BlockingAgent();
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({
+ operationId: "blocking-test",
+ messages: [{ role: "user", content: "Execute" }]
+ });
+ const result = await runtime.step(state);
+ expect(agent.tools.safe_tool).toHaveBeenCalled();
+ expect(result.newState.status).toBe("waiting_for_human");
+ expect(result.newState.pendingToolsCalling).toHaveLength(1);
+ expect(result.newState.pendingToolsCalling[0].apiName).toBe("danger_tool");
+ expect(result.events).toContainEqual(expect.objectContaining({ type: "tool_result" }));
+ expect(result.events).toContainEqual(
+ expect.objectContaining({ type: "human_approve_required" })
+ );
+ });
+ it("should merge tool results correctly", async () => {
+ class UsageTrackingAgent {
+ tools = {
+ expensive_tool: vi.fn().mockResolvedValue({ cost: 10 }),
+ cheap_tool: vi.fn().mockResolvedValue({ cost: 1 })
+ };
+ calculateUsage(operationType, operationResult, previousUsage) {
+ if (operationType === "tool") {
+ return {
+ ...previousUsage,
+ tools: {
+ ...previousUsage.tools,
+ totalCalls: previousUsage.tools.totalCalls + 1,
+ totalTimeMs: previousUsage.tools.totalTimeMs + 100
+ }
+ };
+ }
+ return previousUsage;
+ }
+ async runner(context, _state) {
+ if (context.phase === "user_input") {
+ return {
+ payload: {
+ parentMessageId: "user-msg-id",
+ toolsCalling: [
+ {
+ id: "call_expensive",
+ type: "default",
+ apiName: "expensive_tool",
+ identifier: "expensive_tool",
+ arguments: "{}"
+ },
+ {
+ id: "call_cheap",
+ type: "default",
+ apiName: "cheap_tool",
+ identifier: "cheap_tool",
+ arguments: "{}"
+ }
+ ]
+ },
+ type: "call_tools_batch"
+ };
+ }
+ return { type: "finish", reason: "completed" };
+ }
+ }
+ const agent = new UsageTrackingAgent();
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({
+ operationId: "merge-test",
+ messages: [{ role: "user", content: "Execute" }]
+ });
+ const result = await runtime.step(state);
+ expect(agent.tools.expensive_tool).toHaveBeenCalled();
+ expect(agent.tools.cheap_tool).toHaveBeenCalled();
+ expect(result.newState.usage.tools.totalCalls).toBe(2);
+ });
+ });
+ describe("Multi-Round Batch Tool Execution (upstream issue 1657)", () => {
+ it("should not duplicate tool messages across multiple batch executions", async () => {
+ const executionLog = [];
+ class MultiRoundBatchAgent {
+ roundCount = 0;
+ tools = {
+ search_tool: vi.fn().mockImplementation(async (args) => {
+ executionLog.push(`search_tool(${args.query})`);
+ return { result: `search result for ${args.query}` };
+ }),
+ crawl_tool: vi.fn().mockImplementation(async (args) => {
+ executionLog.push(`crawl_tool(${args.url})`);
+ return { content: `content from ${args.url}` };
+ })
+ };
+ async runner(context, state2) {
+ executionLog.push(`runner(${context.phase})`);
+ switch (context.phase) {
+ case "user_input":
+ return { type: "call_llm", payload: { messages: state2.messages } };
+ case "llm_result": {
+ const llmPayload = context.payload;
+ if (llmPayload.hasToolCalls) {
+ this.roundCount++;
+ const toolsCalling = llmPayload.result.tool_calls.map((tc) => ({
+ id: tc.id,
+ type: "default",
+ apiName: tc.function.name,
+ identifier: tc.function.name,
+ arguments: tc.function.arguments
+ }));
+ return {
+ type: "call_tools_batch",
+ payload: {
+ parentMessageId: "assistant-msg",
+ toolsCalling
+ }
+ };
+ }
+ return { type: "finish", reason: "completed" };
+ }
+ case "tools_batch_result":
+ return { type: "call_llm", payload: { messages: state2.messages } };
+ default:
+ return { type: "finish", reason: "completed" };
+ }
+ }
+ // Mock LLM that returns tool calls for first 2 rounds, then finishes
+ modelRuntime = async function* (payload) {
+ const toolMessages2 = payload.messages.filter((m) => m.role === "tool");
+ executionLog.push(`modelRuntime(tool_messages=${toolMessages2.length})`);
+ if (this.roundCount < 2) {
+ yield { content: `Round ${this.roundCount + 1}: I will use tools.` };
+ yield {
+ tool_calls: [
+ {
+ id: `call_search_${this.roundCount + 1}`,
+ type: "function",
+ function: {
+ name: "search_tool",
+ arguments: JSON.stringify({ query: `query_${this.roundCount + 1}` })
+ }
+ },
+ {
+ id: `call_crawl_${this.roundCount + 1}`,
+ type: "function",
+ function: {
+ name: "crawl_tool",
+ arguments: JSON.stringify({ url: `url_${this.roundCount + 1}` })
+ }
+ }
+ ]
+ };
+ } else {
+ yield { content: "All done!" };
+ }
+ }.bind(this);
+ }
+ const agent = new MultiRoundBatchAgent();
+ const runtime = new AgentRuntime(agent);
+ let state = AgentRuntime.createInitialState({
+ operationId: "multi-round-test",
+ messages: [{ role: "user", content: "Please search and crawl some pages" }]
+ });
+ let result = await runtime.step(state);
+ expect(result.newState.status).toBe("running");
+ result = await runtime.step(result.newState, result.nextContext);
+ expect(result.events.filter((e) => e.type === "tool_result")).toHaveLength(2);
+ let toolMessages = result.newState.messages.filter((m) => m.role === "tool");
+ expect(toolMessages).toHaveLength(2);
+ expect(toolMessages.map((m) => m.tool_call_id).sort()).toEqual([
+ "call_crawl_1",
+ "call_search_1"
+ ]);
+ result = await runtime.step(result.newState, result.nextContext);
+ result = await runtime.step(result.newState, result.nextContext);
+ expect(result.events.filter((e) => e.type === "tool_result")).toHaveLength(2);
+ toolMessages = result.newState.messages.filter((m) => m.role === "tool");
+ expect(toolMessages).toHaveLength(4);
+ const toolCallIds = toolMessages.map((m) => m.tool_call_id);
+ const uniqueToolCallIds = [...new Set(toolCallIds)];
+ expect(toolCallIds).toHaveLength(uniqueToolCallIds.length);
+ expect(toolCallIds.sort()).toEqual([
+ "call_crawl_1",
+ "call_crawl_2",
+ "call_search_1",
+ "call_search_2"
+ ]);
+ result = await runtime.step(result.newState, result.nextContext);
+ result = await runtime.step(result.newState, result.nextContext);
+ expect(result.newState.status).toBe("done");
+ toolMessages = result.newState.messages.filter((m) => m.role === "tool");
+ expect(toolMessages).toHaveLength(4);
+ });
+ it("should handle mixed scenarios: existing tool messages + new batch execution", async () => {
+ class TwoBatchAgent {
+ batchCount = 0;
+ tools = {
+ tool_a: vi.fn().mockResolvedValue({ result: "a" }),
+ tool_b: vi.fn().mockResolvedValue({ result: "b" })
+ };
+ async runner(context, _state) {
+ if (context.phase === "user_input" || context.phase === "tools_batch_result") {
+ this.batchCount++;
+ if (this.batchCount === 1) {
+ return {
+ type: "call_tools_batch",
+ payload: {
+ parentMessageId: "msg",
+ toolsCalling: [
+ {
+ id: "batch1_call_a",
+ type: "default",
+ apiName: "tool_a",
+ identifier: "tool_a",
+ arguments: "{}"
+ }
+ ]
+ }
+ };
+ } else if (this.batchCount === 2) {
+ return {
+ type: "call_tools_batch",
+ payload: {
+ parentMessageId: "msg",
+ toolsCalling: [
+ {
+ id: "batch2_call_a",
+ type: "default",
+ apiName: "tool_a",
+ identifier: "tool_a",
+ arguments: "{}"
+ },
+ {
+ id: "batch2_call_b",
+ type: "default",
+ apiName: "tool_b",
+ identifier: "tool_b",
+ arguments: "{}"
+ }
+ ]
+ }
+ };
+ }
+ }
+ return { type: "finish", reason: "completed" };
+ }
+ }
+ const agent = new TwoBatchAgent();
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({
+ operationId: "two-batch-test",
+ messages: [{ role: "user", content: "test" }]
+ });
+ let result = await runtime.step(state);
+ let toolMessages = result.newState.messages.filter((m) => m.role === "tool");
+ expect(toolMessages).toHaveLength(1);
+ expect(toolMessages[0].tool_call_id).toBe("batch1_call_a");
+ result = await runtime.step(result.newState, result.nextContext);
+ toolMessages = result.newState.messages.filter((m) => m.role === "tool");
+ expect(toolMessages).toHaveLength(3);
+ const toolCallIds = toolMessages.map((m) => m.tool_call_id);
+ expect(new Set(toolCallIds).size).toBe(3);
+ expect(toolCallIds.sort()).toEqual(["batch1_call_a", "batch2_call_a", "batch2_call_b"]);
+ });
+ });
+ describe("StepContext Passing", () => {
+ it("should pass stepContext to agent runner", async () => {
+ const agent = new MockAgent();
+ const runnerSpy = vi.spyOn(agent, "runner");
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({
+ operationId: "test-session",
+ messages: [{ role: "user", content: "Hello" }]
+ });
+ const stepContext = {
+ todos: {
+ items: [
+ { text: "Buy milk", status: "todo" },
+ { text: "Call mom", status: "completed" }
+ ],
+ updatedAt: "2024-06-01T00:00:00.000Z"
+ }
+ };
+ const context = {
+ phase: "user_input",
+ payload: { message: { role: "user", content: "Hello" } },
+ session: {
+ sessionId: "test-session",
+ messageCount: 1,
+ status: "idle",
+ stepCount: 0
+ },
+ stepContext
+ };
+ await runtime.step(state, context);
+ expect(runnerSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ stepContext: expect.objectContaining({
+ todos: expect.objectContaining({
+ items: expect.arrayContaining([
+ expect.objectContaining({ text: "Buy milk", status: "todo" })
+ ])
+ })
+ })
+ }),
+ expect.any(Object)
+ );
+ });
+ it("should pass stepContext to custom executors", async () => {
+ const customExecutor = vi.fn().mockResolvedValue({
+ events: [{ type: "done", finalState: {}, reason: "completed" }],
+ newState: { status: "done" }
+ });
+ const agent = new MockAgent();
+ agent.runner = vi.fn().mockResolvedValue({
+ type: "finish",
+ reason: "completed"
+ });
+ const config = {
+ executors: {
+ finish: customExecutor
+ }
+ };
+ const runtime = new AgentRuntime(agent, config);
+ const state = AgentRuntime.createInitialState({ operationId: "test-session" });
+ const stepContext = {
+ todos: {
+ items: [{ text: "Task 1", status: "todo" }],
+ updatedAt: "2024-06-01T00:00:00.000Z"
+ }
+ };
+ const context = {
+ phase: "init",
+ session: {
+ sessionId: "test-session",
+ messageCount: 0,
+ status: "idle",
+ stepCount: 0
+ },
+ stepContext
+ };
+ await runtime.step(state, context);
+ expect(customExecutor).toHaveBeenCalledWith(
+ expect.any(Object),
+ // instruction
+ expect.any(Object),
+ // state
+ expect.objectContaining({
+ stepContext: expect.objectContaining({
+ todos: expect.objectContaining({
+ items: expect.arrayContaining([expect.objectContaining({ text: "Task 1" })])
+ })
+ })
+ })
+ );
+ });
+ it("should pass stepContext to batch tool execution", async () => {
+ const toolASpy = vi.fn().mockResolvedValue({ result: "a" });
+ const toolBSpy = vi.fn().mockResolvedValue({ result: "b" });
+ class BatchToolAgent {
+ tools = {
+ tool_a: toolASpy,
+ tool_b: toolBSpy
+ };
+ async runner(context2, _state) {
+ if (context2.phase === "user_input") {
+ return {
+ type: "call_tools_batch",
+ payload: {
+ parentMessageId: "msg",
+ toolsCalling: [
+ {
+ id: "call_a",
+ type: "default",
+ apiName: "tool_a",
+ identifier: "tool_a",
+ arguments: "{}"
+ },
+ {
+ id: "call_b",
+ type: "default",
+ apiName: "tool_b",
+ identifier: "tool_b",
+ arguments: "{}"
+ }
+ ]
+ }
+ };
+ }
+ return { type: "finish", reason: "completed" };
+ }
+ }
+ const agent = new BatchToolAgent();
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({
+ operationId: "batch-test",
+ messages: [{ role: "user", content: "Execute tools" }]
+ });
+ const stepContext = {
+ todos: {
+ items: [{ text: "Batch task", status: "todo" }],
+ updatedAt: "2024-06-01T00:00:00.000Z"
+ }
+ };
+ const context = {
+ phase: "user_input",
+ payload: { message: { role: "user", content: "Execute tools" } },
+ session: {
+ sessionId: "batch-test",
+ messageCount: 1,
+ status: "idle",
+ stepCount: 0
+ },
+ stepContext
+ };
+ const result = await runtime.step(state, context);
+ expect(toolASpy).toHaveBeenCalled();
+ expect(toolBSpy).toHaveBeenCalled();
+ expect(result.nextContext?.phase).toBe("tools_batch_result");
+ });
+ it("should handle undefined stepContext gracefully", async () => {
+ const agent = new MockAgent();
+ agent.runner = vi.fn().mockResolvedValue({
+ type: "finish",
+ reason: "completed"
+ });
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({ operationId: "test-session" });
+ const context = {
+ phase: "init",
+ session: {
+ sessionId: "test-session",
+ messageCount: 0,
+ status: "idle",
+ stepCount: 0
+ }
+ // No stepContext
+ };
+ const result = await runtime.step(state, context);
+ expect(result.newState.status).toBe("done");
+ expect(result.events[0].type).toBe("done");
+ });
+ });
+ describe("Edge Cases and Error Handling", () => {
+ it("should handle unknown instruction type", async () => {
+ const agent = new MockAgent();
+ agent.runner = vi.fn().mockResolvedValue({ type: "unknown_instruction_type" });
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({ operationId: "test-session" });
+ const result = await runtime.step(state);
+ expect(result.events[0].type).toBe("error");
+ expect(result.events[0].error.message).toContain(
+ "No executor found for instruction type"
+ );
+ });
+ it("should handle LLM errors", async () => {
+ const agent = new MockAgent();
+ agent.modelRuntime = async function* () {
+ throw new Error("LLM API error");
+ };
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({
+ messages: [{ role: "user", content: "test" }],
+ operationId: "test-session"
+ });
+ const result = await runtime.step(state);
+ expect(result.events[0].type).toBe("error");
+ expect(result.events[0].error.message).toBe("LLM API error");
+ });
+ it("should handle cost limit with warn action", async () => {
+ class WarnCostAgent {
+ async runner(context, state2) {
+ return { type: "call_llm", payload: { messages: state2.messages } };
+ }
+ calculateCost(context) {
+ return {
+ calculatedAt: (/* @__PURE__ */ new Date()).toISOString(),
+ currency: "USD",
+ llm: { byModel: [], currency: "USD", total: 15 },
+ tools: { byTool: [], currency: "USD", total: 0 },
+ total: 15
+ };
+ }
+ modelRuntime = async function* () {
+ yield { content: "test" };
+ };
+ }
+ const agent = new WarnCostAgent();
+ const runtime = new AgentRuntime(agent);
+ const costLimit = {
+ currency: "USD",
+ maxTotalCost: 10,
+ onExceeded: "warn"
+ };
+ const state = AgentRuntime.createInitialState({
+ costLimit,
+ messages: [{ role: "user", content: "test" }],
+ operationId: "test-session"
+ });
+ const result = await runtime.step(state);
+ expect(result.events[0]).toMatchObject({
+ type: "error"
+ });
+ expect(result.events[0].error.message).toContain(
+ "Warning: Cost limit exceeded"
+ );
+ expect(result.newState.status).toBe("running");
+ });
+ it("should track tool cost limits", async () => {
+ class ToolCostAgent {
+ tools = {
+ expensive_tool: vi.fn().mockResolvedValue({ result: "done" })
+ };
+ async runner(context, state2) {
+ if (context.phase === "user_input") {
+ return {
+ payload: {
+ parentMessageId: "user-msg-id",
+ toolCalling: {
+ apiName: "expensive_tool",
+ arguments: "{}",
+ id: "call_1",
+ identifier: "expensive_tool",
+ type: "default"
+ }
+ },
+ type: "call_tool"
+ };
+ }
+ return { reason: "completed", type: "finish" };
+ }
+ calculateCost(context) {
+ return {
+ calculatedAt: (/* @__PURE__ */ new Date()).toISOString(),
+ currency: "USD",
+ llm: { byModel: [], currency: "USD", total: 0 },
+ tools: { byTool: [], currency: "USD", total: 20 },
+ total: 20
+ };
+ }
+ }
+ const agent = new ToolCostAgent();
+ const runtime = new AgentRuntime(agent);
+ const costLimit = {
+ currency: "USD",
+ maxTotalCost: 10,
+ onExceeded: "stop"
+ };
+ const state = AgentRuntime.createInitialState({
+ costLimit,
+ messages: [{ role: "user", content: "test" }],
+ operationId: "test-session"
+ });
+ const result = await runtime.step(state);
+ expect(result.newState.status).toBe("done");
+ expect(result.events[0]).toMatchObject({
+ reason: "cost_limit_exceeded",
+ type: "done"
+ });
+ });
+ it("should merge cost statistics in batch tool execution", async () => {
+ class BatchCostAgent {
+ tools = {
+ tool_1: vi.fn().mockResolvedValue({ result: "result_1" }),
+ tool_2: vi.fn().mockResolvedValue({ result: "result_2" })
+ };
+ calculateCost(context) {
+ const baseCost = context.previousCost || {
+ calculatedAt: (/* @__PURE__ */ new Date()).toISOString(),
+ currency: "USD",
+ llm: { byModel: [], currency: "USD", total: 0 },
+ tools: { byTool: [], currency: "USD", total: 0 },
+ total: 0
+ };
+ return {
+ ...baseCost,
+ calculatedAt: (/* @__PURE__ */ new Date()).toISOString(),
+ tools: {
+ byTool: [],
+ currency: "USD",
+ total: baseCost.tools.total + 5
+ },
+ total: baseCost.total + 5
+ };
+ }
+ async runner(context, _state) {
+ if (context.phase === "user_input") {
+ return {
+ payload: {
+ parentMessageId: "user-msg-id",
+ toolsCalling: [
+ {
+ apiName: "tool_1",
+ arguments: "{}",
+ id: "call_1",
+ identifier: "tool_1",
+ type: "default"
+ },
+ {
+ apiName: "tool_2",
+ arguments: "{}",
+ id: "call_2",
+ identifier: "tool_2",
+ type: "default"
+ }
+ ]
+ },
+ type: "call_tools_batch"
+ };
+ }
+ return { reason: "completed", type: "finish" };
+ }
+ }
+ const agent = new BatchCostAgent();
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({
+ messages: [{ role: "user", content: "Execute" }],
+ operationId: "cost-merge-test"
+ });
+ const result = await runtime.step(state);
+ expect(result.newState.cost.tools.total).toBeGreaterThan(0);
+ expect(result.newState.cost.total).toBeGreaterThan(0);
+ });
+ it("should merge per-tool usage statistics in batch execution", async () => {
+ class DetailedUsageAgent {
+ tools = {
+ analytics_tool: vi.fn().mockResolvedValue({ result: "analytics_done" }),
+ logging_tool: vi.fn().mockResolvedValue({ result: "logged" })
+ };
+ calculateUsage(operationType, operationResult, previousUsage) {
+ if (operationType === "tool") {
+ const toolName = operationResult.toolCall.apiName;
+ const newUsage = structuredClone(previousUsage);
+ newUsage.tools.totalCalls += 1;
+ newUsage.tools.totalTimeMs += 100;
+ const existingTool = newUsage.tools.byTool.find((t) => t.name === toolName);
+ if (existingTool) {
+ existingTool.calls += 1;
+ existingTool.totalTimeMs += 100;
+ } else {
+ newUsage.tools.byTool.push({
+ calls: 1,
+ errors: 0,
+ name: toolName,
+ totalTimeMs: 100
+ });
+ }
+ return newUsage;
+ }
+ return previousUsage;
+ }
+ async runner(context, _state) {
+ if (context.phase === "user_input") {
+ return {
+ payload: {
+ parentMessageId: "user-msg-id",
+ toolsCalling: [
+ {
+ apiName: "analytics_tool",
+ arguments: "{}",
+ id: "call_analytics",
+ identifier: "analytics_tool",
+ type: "default"
+ },
+ {
+ apiName: "logging_tool",
+ arguments: "{}",
+ id: "call_logging",
+ identifier: "logging_tool",
+ type: "default"
+ }
+ ]
+ },
+ type: "call_tools_batch"
+ };
+ }
+ return { reason: "completed", type: "finish" };
+ }
+ }
+ const agent = new DetailedUsageAgent();
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({
+ messages: [{ role: "user", content: "Execute" }],
+ operationId: "usage-merge-test"
+ });
+ const result = await runtime.step(state);
+ expect(result.newState.usage.tools.totalCalls).toBe(2);
+ const analyticsTool = result.newState.usage.tools.byTool.find(
+ (t) => t.name === "analytics_tool"
+ );
+ const loggingTool = result.newState.usage.tools.byTool.find((t) => t.name === "logging_tool");
+ expect(analyticsTool).toBeDefined();
+ expect(analyticsTool.calls).toBe(1);
+ expect(loggingTool).toBeDefined();
+ expect(loggingTool.calls).toBe(1);
+ });
+ });
+});
diff --git a/packages/agent-runtime/tests/spendGuardPipeline.test.js b/packages/agent-runtime/tests/spendGuardPipeline.test.js
new file mode 100644
index 000000000..8543be1ef
--- /dev/null
+++ b/packages/agent-runtime/tests/spendGuardPipeline.test.js
@@ -0,0 +1,97 @@
+import { describe, expect, it, vi } from "vitest";
+import { SpendGuard } from "../src/core/SpendGuard.js";
+import { createSpendPreflight, createSpendRecorder, spendTxFromStep } from "../src/core/spendGuardPipeline.js";
+import { TransactionPipeline } from "../src/core/TransactionPipeline.js";
+function step(overrides = {}) {
+ return {
+ action: "swap",
+ apiName: "executeSwap",
+ args: { amount: 500, toToken: "USDC" },
+ dependsOn: [],
+ description: "Swap step",
+ estimatedGasUsd: 1,
+ id: "step_1",
+ isSimulation: false,
+ requiresApproval: false,
+ riskLevel: "low",
+ toolIdentifier: "solana_swap",
+ ...overrides
+ };
+}
+function plan(steps) {
+ return {
+ category: "swap",
+ chains: ["arbitrum"],
+ confidence: 0.9,
+ createdAt: "2024-01-01T00:00:00.000Z",
+ id: "plan_test",
+ originalIntent: "test",
+ requiresWallet: true,
+ riskLevel: "low",
+ steps,
+ tokens: ["USDC"],
+ totalEstimatedGasUsd: steps.reduce((s, st) => s + st.estimatedGasUsd, 0),
+ warnings: []
+ };
+}
+const okExecutor = async () => ({ data: { ok: true }, isSuccess: true, txHash: "0xabc" });
+const CTX = { agentId: "agt_1", userId: "user_1" };
+describe("spendTxFromStep", () => {
+ it("extracts value, token, and destination from a value-moving step", () => {
+ const tx = spendTxFromStep(
+ step({ args: { amount: 1200, fromToken: "USDC", recipient: "0xDEAD" } }),
+ CTX
+ );
+ expect(tx).toMatchObject({ agentId: "agt_1", destination: "0xDEAD", token: "USDC", valueUsd: 1200 });
+ });
+ it("returns null for simulation / read-only / inflow steps", () => {
+ expect(spendTxFromStep(step({ isSimulation: true }), CTX)).toBeNull();
+ expect(spendTxFromStep(step({ action: "withdraw" }), CTX)).toBeNull();
+ expect(spendTxFromStep(step({ action: "claim" }), CTX)).toBeNull();
+ });
+ it("resolves a value-moving step even with no parseable amount (keeps firewall in force)", () => {
+ const tx = spendTxFromStep(
+ step({ action: "approve", apiName: "approve", args: { spender: "0xBAD", token: "USDC" } }),
+ CTX
+ );
+ expect(tx).toMatchObject({ destination: "0xBAD", token: "USDC", valueUsd: 0 });
+ });
+});
+describe("SpendGuard \u2194 TransactionPipeline", () => {
+ it("blocks a step over the per-tx max and aborts the plan", async () => {
+ const guard = new SpendGuard({ perTxMaxUsd: 100 });
+ const pipeline = new TransactionPipeline({
+ preflight: createSpendPreflight(guard, CTX)
+ });
+ const executor = vi.fn(okExecutor);
+ const execution = await pipeline.execute(plan([step({ args: { amount: 500 } })]), executor);
+ expect(execution.status).toBe("failed");
+ expect(executor).not.toHaveBeenCalled();
+ expect(execution.stepResults.get("step_1")?.error).toContain("Spend guard blocked [CAP_PER_TX]");
+ });
+ it("allows a within-envelope step and records its spend across the plan", async () => {
+ const guard = new SpendGuard({ perTxMaxUsd: 1e3, rollingMaxUsd: 700 });
+ const pipeline = new TransactionPipeline({
+ preflight: createSpendPreflight(guard, CTX),
+ onStepExecuted: createSpendRecorder(guard, CTX)
+ });
+ const s1 = step({ args: { amount: 500 }, id: "step_1" });
+ const s2 = step({ args: { amount: 500 }, dependsOn: ["step_1"], id: "step_2" });
+ const execution = await pipeline.execute(plan([s1, s2]), okExecutor);
+ expect(execution.stepResults.get("step_1")?.status).toBe("completed");
+ expect(execution.stepResults.get("step_2")?.error).toContain("Spend guard blocked [CAP_ROLLING]");
+ expect(guard.windowSpend("agt_1", 24 * 60 * 60 * 1e3)).toBe(500);
+ });
+ it("latches shut after a reconciliation breach - every step blocked", async () => {
+ const guard = new SpendGuard({ perTxMaxUsd: 1e4 });
+ guard.reconcile("agt_1", { ledgerRecordedUsd: 100, onChainOutflowUsd: 5e3 });
+ const pipeline = new TransactionPipeline({
+ preflight: createSpendPreflight(guard, CTX)
+ });
+ const executor = vi.fn(okExecutor);
+ const execution = await pipeline.execute(plan([step({ args: { amount: 50 } })]), executor);
+ expect(execution.status).toBe("failed");
+ expect(executor).not.toHaveBeenCalled();
+ expect(execution.stepResults.get("step_1")?.error).toContain("Spend guard blocked [BREACH]");
+ });
+});
diff --git a/packages/agent-runtime/tests/stepContextComputer.test.js b/packages/agent-runtime/tests/stepContextComputer.test.js
new file mode 100644
index 000000000..9b366a96e
--- /dev/null
+++ b/packages/agent-runtime/tests/stepContextComputer.test.js
@@ -0,0 +1,43 @@
+import { describe, expect, it } from "vitest";
+import { computeStepContext } from "../src/utils/stepContextComputer.js";
+describe("computeStepContext", () => {
+ describe("assembles stepContext from pre-computed values", () => {
+ it("should include todos when provided", () => {
+ const todos = {
+ items: [
+ { text: "Buy milk", status: "todo" },
+ { text: "Call mom", status: "completed" }
+ ],
+ updatedAt: "2024-06-01T00:00:00.000Z"
+ };
+ const result = computeStepContext({ todos });
+ expect(result.todos).toBeDefined();
+ expect(result.todos?.items).toHaveLength(2);
+ expect(result.todos?.items[0].text).toBe("Buy milk");
+ expect(result.todos?.items[0].status).toBe("todo");
+ expect(result.todos?.items[1].text).toBe("Call mom");
+ expect(result.todos?.items[1].status).toBe("completed");
+ });
+ it("should not include todos key when undefined", () => {
+ const result = computeStepContext({});
+ expect(result.todos).toBeUndefined();
+ expect("todos" in result).toBe(false);
+ });
+ it("should return empty object when no params provided", () => {
+ const result = computeStepContext({});
+ expect(result).toEqual({});
+ });
+ });
+ describe("object parameter extensibility", () => {
+ it("should accept object parameter for future extensibility", () => {
+ const result = computeStepContext({
+ todos: {
+ items: [{ text: "Task", status: "todo" }],
+ updatedAt: "2024-01-01T00:00:00.000Z"
+ }
+ });
+ expect(result).toBeDefined();
+ expect(result.todos).toBeDefined();
+ });
+ });
+});
diff --git a/packages/agent-runtime/tests/tokenCounter.test.js b/packages/agent-runtime/tests/tokenCounter.test.js
new file mode 100644
index 000000000..e1fc31372
--- /dev/null
+++ b/packages/agent-runtime/tests/tokenCounter.test.js
@@ -0,0 +1,173 @@
+import { describe, expect, it } from "vitest";
+import {
+ DEFAULT_MAX_CONTEXT,
+ DEFAULT_THRESHOLD_RATIO,
+ calculateMessageTokens,
+ estimateTokens,
+ getCompressionThreshold,
+ shouldCompress
+} from "../src/utils/tokenCounter.js";
+describe("tokenCounter", () => {
+ describe("estimateTokens", () => {
+ it("should estimate tokens for string content", () => {
+ const tokens = estimateTokens("Hello, world!");
+ expect(tokens).toBeGreaterThan(0);
+ });
+ it("should return 0 for empty string", () => {
+ expect(estimateTokens("")).toBe(0);
+ });
+ it("should handle null/undefined content", () => {
+ expect(estimateTokens(null)).toBe(0);
+ expect(estimateTokens(void 0)).toBe(0);
+ });
+ it("should handle object content by JSON stringifying", () => {
+ const tokens = estimateTokens({ key: "value", nested: { a: 1 } });
+ expect(tokens).toBeGreaterThan(0);
+ });
+ it("should handle array content", () => {
+ const tokens = estimateTokens(["item1", "item2", "item3"]);
+ expect(tokens).toBeGreaterThan(0);
+ });
+ });
+ describe("calculateMessageTokens", () => {
+ it("should use totalOutputTokens for assistant messages when available", () => {
+ const messages = [
+ {
+ content: "This content should be ignored",
+ metadata: { usage: { totalOutputTokens: 100 } },
+ role: "assistant"
+ }
+ ];
+ expect(calculateMessageTokens(messages)).toBe(100);
+ });
+ it("should estimate tokens for assistant messages without usage data", () => {
+ const messages = [{ content: "Hello from assistant", role: "assistant" }];
+ const tokens = calculateMessageTokens(messages);
+ expect(tokens).toBeGreaterThan(0);
+ expect(tokens).not.toBe(100);
+ });
+ it("should estimate tokens for user messages", () => {
+ const messages = [{ content: "Hello from user", role: "user" }];
+ const tokens = calculateMessageTokens(messages);
+ expect(tokens).toBeGreaterThan(0);
+ });
+ it("should estimate tokens for system messages", () => {
+ const messages = [{ content: "System prompt", role: "system" }];
+ const tokens = calculateMessageTokens(messages);
+ expect(tokens).toBeGreaterThan(0);
+ });
+ it("should sum tokens from multiple messages", () => {
+ const messages = [
+ { content: "Hello", role: "user" },
+ { content: "Hi there!", metadata: { usage: { totalOutputTokens: 50 } }, role: "assistant" },
+ { content: "How are you?", role: "user" }
+ ];
+ const tokens = calculateMessageTokens(messages);
+ expect(tokens).toBeGreaterThan(50);
+ });
+ it("should handle empty messages array", () => {
+ expect(calculateMessageTokens([])).toBe(0);
+ });
+ it("should handle messages with empty content", () => {
+ const messages = [
+ { content: "", role: "user" },
+ { content: void 0, role: "assistant" }
+ ];
+ expect(calculateMessageTokens(messages)).toBe(0);
+ });
+ it("should skip assistant usage with 0 tokens and estimate instead", () => {
+ const messages = [
+ {
+ content: "Some content",
+ metadata: { usage: { totalOutputTokens: 0 } },
+ role: "assistant"
+ }
+ ];
+ const tokens = calculateMessageTokens(messages);
+ expect(tokens).toBeGreaterThan(0);
+ });
+ });
+ describe("getCompressionThreshold", () => {
+ it("should use default values", () => {
+ const threshold = getCompressionThreshold();
+ expect(threshold).toBe(Math.floor(DEFAULT_MAX_CONTEXT * DEFAULT_THRESHOLD_RATIO));
+ expect(threshold).toBe(64e3);
+ });
+ it("should use custom maxWindowToken", () => {
+ const threshold = getCompressionThreshold({ maxWindowToken: 2e5 });
+ expect(threshold).toBe(1e5);
+ });
+ it("should use custom thresholdRatio", () => {
+ const threshold = getCompressionThreshold({ thresholdRatio: 0.5 });
+ expect(threshold).toBe(64e3);
+ });
+ it("should use both custom values", () => {
+ const threshold = getCompressionThreshold({
+ maxWindowToken: 1e5,
+ thresholdRatio: 0.8
+ });
+ expect(threshold).toBe(8e4);
+ });
+ it("should floor the result", () => {
+ const threshold = getCompressionThreshold({
+ maxWindowToken: 100,
+ thresholdRatio: 0.33
+ });
+ expect(threshold).toBe(33);
+ });
+ });
+ describe("shouldCompress", () => {
+ it("should return needsCompression=false when under threshold", () => {
+ const messages = [{ content: "Hi", role: "user" }];
+ const result = shouldCompress(messages);
+ expect(result.needsCompression).toBe(false);
+ expect(result.currentTokenCount).toBeGreaterThan(0);
+ expect(result.threshold).toBe(64e3);
+ });
+ it("should return needsCompression=true when over threshold", () => {
+ const messages = [
+ {
+ content: "",
+ metadata: { usage: { totalOutputTokens: 7e4 } },
+ role: "assistant"
+ }
+ ];
+ const result = shouldCompress(messages);
+ expect(result.needsCompression).toBe(true);
+ expect(result.currentTokenCount).toBe(7e4);
+ expect(result.threshold).toBe(64e3);
+ });
+ it("should return needsCompression=false when exactly at threshold", () => {
+ const messages = [
+ {
+ content: "",
+ metadata: { usage: { totalOutputTokens: 64e3 } },
+ role: "assistant"
+ }
+ ];
+ const result = shouldCompress(messages);
+ expect(result.needsCompression).toBe(false);
+ expect(result.currentTokenCount).toBe(64e3);
+ });
+ it("should use custom options", () => {
+ const messages = [
+ {
+ content: "",
+ metadata: { usage: { totalOutputTokens: 5e4 } },
+ role: "assistant"
+ }
+ ];
+ const result = shouldCompress(messages, {
+ maxWindowToken: 6e4,
+ thresholdRatio: 0.75
+ });
+ expect(result.needsCompression).toBe(true);
+ expect(result.threshold).toBe(45e3);
+ });
+ it("should handle empty messages", () => {
+ const result = shouldCompress([]);
+ expect(result.needsCompression).toBe(false);
+ expect(result.currentTokenCount).toBe(0);
+ });
+ });
+});