@oracle-agent/oracle 0.28.27 → 0.28.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +10 -3
  2. package/SETUP.md +3 -0
  3. package/dist/assets/skills/bankrbot/SKILL.md +24 -0
  4. package/dist/assets/skills/oracle-agentic-crypto/SKILL.md +39 -0
  5. package/dist/assets/skills/oracle-chain-graphs-telegram-cards/SKILL.md +2 -0
  6. package/dist/assets/skills/oracle-desk-product/SKILL.md +1 -1
  7. package/dist/assets/skills/oracle-uniswap-v4-hooks/SKILL.md +31 -0
  8. package/dist/assets/skills/oracle-x402/SKILL.md +30 -0
  9. package/dist/bin/desk-server.mjs +28 -26
  10. package/dist/bin/oracle-data-mcp.mjs +32 -12
  11. package/dist/bin/oracle-gateway.mjs +39 -26
  12. package/dist/bin/oracle-mev-arb-shadow.mjs +5 -5
  13. package/dist/bin/oracle-mev-shadow.mjs +5 -5
  14. package/dist/bin/oracle-public-server.mjs +4 -4
  15. package/dist/bin/oracle-route.mjs +15 -15
  16. package/dist/bin/oracle-scan.mjs +11 -11
  17. package/dist/bin/oracle.mjs +4 -3
  18. package/dist/cli/commands/auth.mjs +6 -6
  19. package/dist/cli/commands/chat.mjs +155 -155
  20. package/dist/cli/commands/doctor.mjs +1 -1
  21. package/dist/cli/commands/eval.mjs +77 -77
  22. package/dist/cli/commands/harness.mjs +4 -4
  23. package/dist/cli/commands/model.mjs +157 -157
  24. package/dist/cli/commands/receipt.mjs +1 -1
  25. package/dist/cli/commands/setup.mjs +23 -23
  26. package/dist/cli/commands/signer.mjs +8 -8
  27. package/dist/cli/commands/snipe.mjs +24 -0
  28. package/dist/cli/commands/swap.mjs +25 -25
  29. package/dist/cli/commands/venues.mjs +1 -1
  30. package/dist/control/approval-binding.mjs +1 -0
  31. package/dist/control/finality.mjs +1 -0
  32. package/dist/control-plane/index.mjs +6 -0
  33. package/dist/data/desk-data.mjs +26 -24
  34. package/dist/governance-prepare.mjs +2 -0
  35. package/dist/index.mjs +44 -31
  36. package/dist/local-marketplace.mjs +3 -0
  37. package/dist/local-pack-registry.mjs +3 -0
  38. package/dist/local-signer/index.mjs +3 -3
  39. package/dist/local-signer/runtime.mjs +8 -8
  40. package/dist/local-x402.mjs +3 -0
  41. package/dist/nft/index.mjs +1 -1
  42. package/dist/notifications/index.mjs +3 -0
  43. package/dist/position-health.mjs +2 -0
  44. package/dist/router/index.mjs +2 -2
  45. package/dist/router/prepare-bridge.mjs +2 -2
  46. package/dist/safety-intelligence.mjs +1 -0
  47. package/dist/scanner/index.mjs +3 -3
  48. package/dist/task.d.mts +130 -0
  49. package/dist/task.mjs +2 -0
  50. package/dist/tax-lots.mjs +5 -0
  51. package/dist/tenant-rbac.mjs +1 -0
  52. package/dist/workflow-telemetry.mjs +1 -0
  53. package/package.json +17 -2
  54. package/public/agent-connect/index.html +2 -2
  55. package/public/install.sh +2 -2
  56. package/public/oracle-splash/index.html +2 -2
  57. package/public/oracle-splash/install.sh +2 -2
@@ -1,3 +1,3 @@
1
- var b={robinhood:{chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC"],evm:!0},ethereum:{chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],evm:!0},polygon:{chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],evm:!0},arbitrum:{chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],evm:!0},base:{chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],evm:!0},hyperevm:{chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],evm:!0},bsc:{chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],evm:!0},avalanche:{chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],evm:!0},optimism:{chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],evm:!0},abstract:{chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],evm:!0},stable:{chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],evm:!0}},_e=new Map(Object.values(b).map(e=>[e.chainId,e]));import O from"node:fs";import U from"node:path";import{homedir as he}from"node:os";function x(e){let r=e?.transactionHash||e?.hash||e?.txid||null;return r?{happened:!0,hash:String(r),note:null}:{happened:!1,hash:null,note:"no transaction hash \u2014 the action did not succeed"}}import c from"node:path";import pe from"node:os";import{createHash as me,randomBytes as Xo}from"node:crypto";import{Interface as N,keccak256 as Zo}from"ethers";import{Transaction as ti}from"@scure/btc-signer";import{ed25519 as ni}from"@noble/curves/ed25519.js";import{base58 as vn}from"@scure/base";import{Interface as $}from"ethers";import{Interface as Q,MaxUint256 as wt,isAddress as gt,keccak256 as yt,toUtf8Bytes as Et}from"ethers";import{Interface as Y,isAddress as Xe}from"ethers";import{isAddress as Je}from"ethers";var tt=new Y(["function approve(address spender,uint256 amount) returns (bool)"]);import{Interface as X,isAddress as ot}from"ethers";var ct=new X(["function approve(address spender,uint256 amount) returns (bool)"]),ut=Object.freeze({42161:"0x1c3fa76e6e1088bce750f23a5bfcffa1efef6a41",43114:"0x8f550e53dfe96c055d5bdb267c21f268fcaf63b2"});var kt=new Q(["function approve(address spender,uint256 amount) returns (bool)"]);var Tt=300*1e3,Nt=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})();import{Address as Pt,NETWORK as _t,OutScript as Bt,RawTx as $t,SigHash as Ft,TEST_NETWORK as Mt,Transaction as qt}from"@scure/btc-signer";import{createHash as ee}from"node:crypto";import{base58 as Wt}from"@scure/base";import{getCompiledTransactionMessageDecoder as Jt}from"@solana/transaction-messages";var L=e=>ee("sha256").update(`global:${e}`).digest().subarray(0,8).toString("hex"),zt=new Map([[L("route"),{name:"route",prefixBytes:0}],[L("shared_accounts_route"),{name:"shared_accounts_route",prefixBytes:1}]]);var er=64*1024;var fr=Object.freeze({"perp-order":"order","hip3-order":"order","hip4-order":"order","perp-bracket":"order","perp-cancel":"cancel","perp-leverage":"leverage","perp-isolated-margin":"margin","builder-fee-approval":"approveBuilder","hype-stake-deposit":"stake","hype-stake-withdraw":"unstake","hype-delegate":"delegate","hype-undelegate":"delegate"}),pr=Object.freeze({"perp-order":"order","hip3-order":"order","hip4-order":"order","perp-bracket":"order","perp-cancel":"cancel","perp-leverage":"updateLeverage","perp-isolated-margin":"updateIsolatedMargin","builder-fee-approval":"approveBuilderFee","hype-stake-deposit":"cDeposit","hype-stake-withdraw":"cWithdraw","hype-delegate":"tokenDelegate","hype-undelegate":"tokenDelegate"});var wr="0x"+"00".repeat(32);var te=Object.freeze([["salt","uint256"],["maker","address"],["signer","address"],["tokenId","uint256"],["makerAmount","uint256"],["takerAmount","uint256"],["side","uint8"],["signatureType","uint8"],["timestamp","uint256"],["metadata","bytes32"],["builder","bytes32"]]),xr=Object.freeze(te.map(e=>e[0]));var ae=new Set(["evm","evm-swap","evm-bridge","evm-nft","btc","sol","hl","poly","lighter"]);var qr=Object.freeze({swap:5,bridge:5,perps:0,nft:0,mint:0,transfer:0,approve:0,order:0,cancel:0,leverage:0,margin:0,approveBuilder:0,stake:0,unstake:0,delegate:0});var se=Object.freeze({"0x04e45aaf":{provider:"uniswap-v3",action:"swap",layout:"router02-exact-input-single"},"0x414bf389":{provider:"uniswap-v3",action:"swap",layout:"swap-router-exact-input-single"},"0xc04b8d59":{provider:"uniswap-v3",action:"swap",layout:"exact-input-deadline"},"0xb858183f":{provider:"uniswap-v3",action:"swap",layout:"exact-input"},"0x5ae401dc":{provider:"uniswap-v3",action:"swap",layout:"multicall-deadline"},"0xa026383e":{provider:"aerodrome",action:"swap",layout:"aerodrome-exact-input-single"},"0x7b939232":{provider:"across-v3",action:"bridge",layout:"across-deposit-v3"}}),Dr=Object.freeze({"0x161ac21f":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-public"},"0xc2f6663a":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-allowlist"}}),Ur=new $(["function buySpecificNFT(uint256 tokenId,uint256 maxCost) payable","function sellNFT(uint256 tokenId,uint256 minPayout) payable"]),jr=new $(["function mintAllowList(address nftContract,address feeRecipient,address minterIfNotPayer,uint256 quantity,(uint80 mintPrice,uint48 maxTotalMintableByWallet,uint48 startTime,uint48 endTime,uint48 dropStageIndex,uint32 maxTokenSupplyForStage,uint16 feeBps,bool restrictFeeRecipients) mintParams,bytes32[] proof) payable"]),Wr=Object.freeze({"0xa0712d68":{provider:"nft-mint",action:"mint",layout:"mint-quantity"},"0x1249c58b":{provider:"nft-mint",action:"mint",layout:"mint-no-args"},"0x2db11544":{provider:"nft-mint",action:"mint",layout:"mint-quantity"},"0xefef39a1":{provider:"nft-mint",action:"mint",layout:"mint-quantity"},"0xa6f2ae3a":{provider:"nft-mint",action:"mint",layout:"mint-no-args"}});var ce=Object.freeze([...ae]),Hr=Object.freeze({...se});import{ed25519 as sn}from"@noble/curves/ed25519.js";import{base58 as un}from"@scure/base";import{RawTx as dn,SigHash as fn,Transaction as pn}from"@scure/btc-signer";import{Transaction as hn,keccak256 as wn,verifyTypedData as gn}from"ethers";import{encode as Gr}from"@msgpack/msgpack";import{keccak256 as Kr,verifyTypedData as Yr}from"ethers";var Xr=Object.freeze({name:"Exchange",version:"1",chainId:1337,verifyingContract:"0x0000000000000000000000000000000000000000"}),Qr=Object.freeze({Agent:[{name:"source",type:"string"},{name:"connectionId",type:"bytes32"}]});var $n=Object.freeze({N:1<<17,r:8,p:1}),Fn=256*1024*1024,Mn=16*1024;var Dn=Object.freeze({1:{name:"ethereum",mode:"mempool-private",endpoints:["https://rpc.flashbots.net/fast","https://rpc.mevblocker.io"]},8453:{name:"base",mode:"sequencer",endpoints:["https://mainnet-sequencer.base.org"]},10:{name:"optimism",mode:"sequencer",endpoints:["https://mainnet-sequencer.optimism.io"]},42161:{name:"arbitrum",mode:"sequencer",endpoints:["https://arb1-sequencer.arbitrum.io/rpc"]},56:{name:"bsc",mode:"mempool-private",endpoints:["https://rpc.48.club","https://bsc.rpc.blxrbdn.com"]},137:{name:"polygon",mode:"mempool-private",endpoints:["https://polygon-bor-rpc.publicnode.com"]},43114:{name:"avalanche",mode:"public-only",endpoints:[]},999:{name:"hyperevm",mode:"public-only",endpoints:[]}});import{homedir as I}from"node:os";import{join as T}from"node:path";var M=process.env.ORACLE_PUBLIC_DESKTOP==="1",de=M?process.env.ORACLE_CONFIG_DIR||T(I(),".config","oracle"):T(I(),".config","oracle"),Hn=M?de:T(I(),".config","mad-desk");var Kn="0".repeat(64),Yn=Object.freeze({PREPARE:"exec.prepare",SIGN:"exec.sign",BROADCAST:"exec.broadcast",POLICY_REJECT:"policy.reject",AUTH_GRANT:"auth.grant",AUTH_OK:"auth.verify.ok",AUTH_FAIL:"auth.verify.fail"});var Xn=Promise.resolve();import{Wallet as so}from"ethers";import{base58 as uo}from"@scure/base";import{ed25519 as fo}from"@noble/curves/ed25519.js";import{NETWORK as mo,TEST_NETWORK as ho,WIF as wo,p2wpkh as go}from"@scure/btc-signer";import{pubECDSA as Eo}from"@scure/btc-signer/utils.js";var ki=new N(["function collection() view returns (address)","function token() view returns (address)","function robinhoodSwapFeeWei() view returns (uint256)","function quoteSpecificBuy(uint256 tokenId) view returns (uint256 totalCost,uint256 baseCost,uint256 fee,uint256 protocolFee,bool available)","function quoteSellNFT() view returns (uint256 netPayout,uint256 grossPayout,uint256 fee,uint256 protocolFee)","function inventory(uint256 tokenId) view returns (bool)","function buySpecificNFT(uint256 tokenId,uint256 maxCost) payable","function sellNFT(uint256 tokenId,uint256 minPayout) payable"]),Ii=new N(["function decimals() view returns (uint8)","function allowance(address owner,address spender) view returns (uint256)"]),Ti=new N(["function ownerOf(uint256 tokenId) view returns (address)","function getApproved(uint256 tokenId) view returns (address)","function isApprovedForAll(address owner,address operator) view returns (bool)"]);function D(e){let r=process.env.ORACLE_SIGNER_STATE_DIR||c.join(process.env.XDG_STATE_HOME||c.join(pe.homedir(),".local","state"),"oracle"),t=me("sha256").update(c.resolve(e)).digest("hex").slice(0,16);return{vault:c.join(e,"vault.json"),policy:c.join(e,"signer-policy.json"),policyKey:c.join(e,"policy-integrity-key"),policyAnchor:c.join(r,`signer-policy-${t}.high-water`),ledger:c.join(e,"signer-ledger.json"),ledgerAnchor:c.join(r,`signer-ledger-${t}.high-water`),token:c.join(e,"signer-token"),lock:c.join(r,`signer-${t}.lock`)}}function we(){return process.env.ORACLE_CONFIG_DIR||U.join(he(),".config","oracle")}function h(){let e=D(U.join(we(),"signer")),r=O.existsSync(e.vault),t=O.existsSync(e.lock),o=r?t?"disarmed":"armed-owner-confirmed":"inert-no-key";return{vaultExists:r,policyConfigured:O.existsSync(e.policy),armed:r&&!t,disarmed:t,capabilities:{swap:o,bridge:o},autonomous:!1,note:"Keys stay on this machine. Exact confirmation is required before any broadcast."}}var Mi=Object.freeze([{type:"function",function:{name:"vault_status",description:"Read local Oracle vault/signer readiness. Never returns key material.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"signer_status",description:"Ping the loopback signer. Fails closed if it is not running.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"signer_execute",description:"Broadcast one already-confirmed local artifact. Requires a one-use confirmationNonce from the local signer TTY confirm. Cannot mint confirmation itself.",parameters:{type:"object",properties:{artifact:{type:"object"},confirmationNonce:{type:"string",minLength:32,maxLength:128}},required:["artifact","confirmationNonce"],additionalProperties:!1}}},{type:"function",function:{name:"signer_disarm",description:"Global kill switch. Stops the local signer from broadcasting.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"receipt_report",description:"Receipt or it did not happen. Requires transactionHash/hash/txid.",parameters:{type:"object",properties:{receipt:{type:"object"},transactionHash:{type:"string"},hash:{type:"string"},txid:{type:"string"}},additionalProperties:!1}}},{type:"function",function:{name:"watch_create",description:"Create an alert-only watch. Never execute.",parameters:{type:"object",properties:{chain:{type:"string"},token:{type:"string"},condition:{type:"string"},note:{type:"string"}},required:["chain","token","condition"],additionalProperties:!1}}},{type:"function",function:{name:"watch_list",description:"List local alert-only watches.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"portfolio_snapshot",description:"How to read the one portfolio snapshot. knownUsd is incomplete if a provider is missing.",parameters:{type:"object",properties:{},additionalProperties:!1}}}]);import H from"node:fs";import Te from"node:path";import w from"node:fs";import ge from"node:os";import f from"node:path";import{fileURLToPath as ye}from"node:url";var Ee=f.dirname(ye(import.meta.url)),Hi=f.resolve(Ee,"../..");function j(){return process.env.ORACLE_FAKE_HOME||ge.homedir()}function be(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function g(){return be()?process.env.ORACLE_CONFIG_DIR||f.join(j(),".config","oracle"):f.join(j(),".config","oracle")}function xe(){return f.join(g(),"desk.json")}function Se(){return f.join(g(),"env")}function d({force:e=!1}={}){if(d._done&&!e)return d._result||null;d._done=!0;let r={},t=(i,n)=>{if(n==null)return;let a=String(n).trim();a&&(process.env[i]!=null&&String(process.env[i]).trim()!==""||(process.env[i]=a,r[i]=a))};try{let i=Se();if(w.existsSync(i))for(let n of w.readFileSync(i,"utf8").split(/\r?\n/)){let a=n.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!a||a[2].startsWith("#"))continue;let s=a[2];(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1)),t(a[1],s)}}catch{}try{let i=xe();if(w.existsSync(i)){let n=JSON.parse(w.readFileSync(i,"utf8"));n&&typeof n=="object"&&(t("ORACLE_DESK_URL",n.deskUrl||n.dataUrl||n.url),t("ORACLE_DATA_URL",n.dataUrl||n.deskUrl||n.url),t("ORACLE_API_URL",n.apiUrl||n.dataUrl||n.deskUrl),t("ORACLE_PUBLIC_URL",n.publicUrl||n.deskUrl||n.dataUrl),t("ORACLE_EXEC_URL",n.execUrl),t("MAD_DESK_URL",n.deskUrl||n.dataUrl))}}catch{}let o=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return o&&(t("ORACLE_DESK_URL",o),t("ORACLE_DATA_URL",o),t("ORACLE_API_URL",o),t("ORACLE_PUBLIC_URL",o),t("MAD_DESK_URL",o)),d._result=Object.keys(r).length?r:null,d._result}try{d()}catch{}var Ae=new Set(["openrouter","openai","anthropic","xai","deepseek","gemini","kimi","mistral","nous","custom","anthropic-oauth","openai-codex","xai-oauth"]);function y(e){return String(e||"").trim()||void 0}function ve(e,{required:r=!1}={}){let t=y(e)?.toLowerCase();if(!t){if(r)throw new Error("model provider is required");return}if(!Ae.has(t))throw new Error(`unsupported provider: ${t}`);return t}function ke(e,{required:r=!1}={}){let t=y(e);if(!t){if(r)throw new Error("model is required");return}if(t.includes("..")||t.startsWith("/")||!/^[a-zA-Z0-9._:/-]{1,200}$/.test(t))throw new Error("invalid model id");return t}function Ie(e){let r=y(e);if(!r||r.length>2048)throw new Error("invalid custom base URL");let t;try{t=new URL(r)}catch{throw new Error("invalid custom base URL")}let o=t.hostname.toLowerCase().replace(/^\[|\]$/g,""),i=o==="localhost"||o==="127.0.0.1"||o==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&i)||t.username||t.password||t.search||t.hash)throw new Error("custom base URL must use HTTPS or loopback HTTP without credentials, query, or fragment");return t.toString().replace(/\/+$/,"")}function W({provider:e,model:r,baseUrl:t}={},{requireModel:o=!1}={}){let i=ve(e),n=ke(r,{required:o});if(i==="custom")return{provider:i,...n?{model:n}:{},baseUrl:Ie(t)};if(y(t))throw new Error("baseUrl is only supported for the custom provider");return{...i?{provider:i}:{},...n?{model:n}:{}}}var Ne=new Set(["auto","standalone","hermes","remote","arch"]);function Oe(){return Te.join(g(),"model.json")}function p(e){return String(e||"").trim()||void 0}function Ce(e={}){let r=p(e.backend)?.toLowerCase()||"auto",t=W({provider:e.provider,model:e.model,baseUrl:e.baseUrl},{requireModel:r==="standalone"}),o=p(e.apiKeyEnv),i=Number.parseInt(String(e.contextLength||""),10),n=p(e.reasoningEffort),a=p(e.computeHost||e.remoteHost),s=p(e.computeUser||e.remoteUser),u=p(e.computePath||e.remotePath);if(!Ne.has(r))throw new Error(`unsupported backend: ${r}`);if(process.env.ORACLE_PUBLIC_DESKTOP==="1"&&["remote","arch"].includes(r))throw new Error("remote compute backends are disabled in the public desktop");if(o&&!/^[A-Z][A-Z0-9_]*$/.test(o))throw new Error("api key env must be an uppercase environment variable name");if(r==="remote"&&!a)throw new Error("remote backend requires computeHost");return{backend:r,...t,...o?{apiKeyEnv:o}:{},...Number.isFinite(i)&&i>0?{contextLength:i}:{},...n?{reasoningEffort:n}:{},...a?{computeHost:a}:{},...s?{computeUser:s}:{},...u?{computePath:u}:{}}}function J(){let e=Oe();if(!H.existsSync(e))return null;try{return Ce(JSON.parse(H.readFileSync(e,"utf8")))}catch{return null}}var Le=new Set(["127.0.0.1","::1","localhost"]);function C({env:e=process.env,vault:r=null}={}){let t=r||h(),o=[];for(let[i,n]of Object.entries(b)){let a=(n.rpcEnv||[]).some(u=>String(e[u]||"").trim()),s="prepare";n.evm?a&&(s="live"):s="unavailable",o.push({key:i,chainId:n.chainId,name:n.name,family:"evm",status:s,execute:!!(t.vaultExists&&t.armed&&!t.disarmed),note:a?"rpc configured":"public read/prepare; set RPC for live reads"})}return o.push({key:"solana",chainId:null,name:"Solana",family:"sol",status:"prepare",execute:!1,note:"Jupiter quote/prepare; local sol signer"},{key:"bitcoin",chainId:null,name:"Bitcoin",family:"btc",status:"prepare",execute:!1,note:"Esplora read; local btc signer"},{key:"hyperliquid-l1",chainId:null,name:"Hyperliquid L1",family:"data",status:"live",execute:!1,note:"data/prepare only \u2014 not an EVM signer family"},{key:"polymarket",chainId:null,name:"Polymarket",family:"data",status:"live",execute:!1,note:"data/prepare only \u2014 not a signer family"}),o}function Re({env:e=process.env,model:r=J(),vault:t=h(),signerReachable:o=!1,quote:i=null}={}){let n=[],a=(l,E,z,G=null)=>n.push({id:l,status:E,detail:z,fix:G}),s=(()=>{let[l,E]=process.versions.node.split(".").map(Number);return l>20||l===20&&E>=19})();a("node",s?"ok":"fail",`node ${process.versions.node}`,s?null:"install node >= 20.19"),r?r.backend==="hermes"?a("model","warn","backend=hermes (opt-in attach)","oracle model --backend standalone"):a("model","ok",`${r.backend||"auto"} ${r.provider||""} ${r.model||""}`.trim()):a("model","fail","no model.json","oracle setup model"),t.vaultExists?t.disarmed?a("vault","warn","vault present, DISARMED","oracle signer (re-arm after confirm)"):a("vault",t.armed?"ok":"warn",t.armed?"present, armed":"present, not armed"):a("vault","fail","no local vault","oracle sign init");let u=e.ORACLE_SIGNER_HOST||"127.0.0.1";return Le.has(u)?a("signer",o?"ok":"warn",o?`loopback ${u}:${e.ORACLE_SIGNER_PORT||9462}`:"loopback signer not reachable",o?null:"oracle signer"):a("signer","fail",`signer host ${u} is not loopback`,"unset ORACLE_SIGNER_HOST"),i?i.ok?a("quote","ok",i.detail||"net quote returned"):a("quote","warn",i.detail||"quote unavailable","check network / oracle data serve"):a("quote","warn","quote not probed",null),{ok:!n.some(l=>l.status==="fail"),checks:n,venues:C({env:e,vault:t})}}async function aa(e=process.env){let r=e.ORACLE_SIGNER_HOST||"127.0.0.1",t=e.ORACLE_SIGNER_PORT||9462;try{return(await fetch(`http://${r}:${t}/status`,{signal:AbortSignal.timeout(1500)})).ok}catch{return!1}}async function sa(){try{let e=await fetch("https://api.dexscreener.com/latest/dex/search?q=WETH%20USDC",{signal:AbortSignal.timeout(4e3)});if(!e.ok)return{ok:!1,detail:`dexscreener ${e.status}`};let t=(await e.json())?.pairs?.[0];return!t?.chainId||!t?.priceUsd?{ok:!1,detail:"no pair"}:{ok:!0,detail:`${t.chainId} ${t.baseToken?.symbol}/${t.quoteToken?.symbol} $${t.priceUsd}`}}catch(e){return{ok:!1,detail:e instanceof Error?e.message:"quote failed"}}}var ca={name:"venues",summary:"label every shipped venue live / prepare / unavailable",group:"read",usage:"oracle venues [--json]",async run(e){let r=e.argv.includes("--json"),t=C();if(r)return process.stdout.write(`${JSON.stringify({venues:t},null,2)}
1
+ var b={robinhood:{chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC"],evm:!0},ethereum:{chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],evm:!0},polygon:{chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],evm:!0},arbitrum:{chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],evm:!0},base:{chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],evm:!0},hyperevm:{chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],evm:!0},bsc:{chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],evm:!0},avalanche:{chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],evm:!0},optimism:{chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],evm:!0},abstract:{chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],evm:!0},stable:{chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],evm:!0}},_e=new Map(Object.values(b).map(e=>[e.chainId,e]));import O from"node:fs";import U from"node:path";import{homedir as he}from"node:os";function x(e){let r=e?.transactionHash||e?.hash||e?.txid||null;return r?{happened:!0,hash:String(r),note:null}:{happened:!1,hash:null,note:"no transaction hash \u2014 the action did not succeed"}}import c from"node:path";import pe from"node:os";import{createHash as me,randomBytes as Xo}from"node:crypto";import{Interface as N,keccak256 as Zo}from"ethers";import{Transaction as ti}from"@scure/btc-signer";import{ed25519 as ni}from"@noble/curves/ed25519.js";import{base58 as vn}from"@scure/base";import{Interface as $}from"ethers";import{Interface as Q,MaxUint256 as wt,isAddress as gt,keccak256 as yt,toUtf8Bytes as Et}from"ethers";import{Interface as Y,isAddress as Xe}from"ethers";import{isAddress as Je}from"ethers";var tt=new Y(["function approve(address spender,uint256 amount) returns (bool)"]);import{Interface as X,isAddress as ot}from"ethers";var ct=new X(["function approve(address spender,uint256 amount) returns (bool)"]),ut=Object.freeze({42161:"0x1c3fa76e6e1088bce750f23a5bfcffa1efef6a41",43114:"0x8f550e53dfe96c055d5bdb267c21f268fcaf63b2"});var kt=new Q(["function approve(address spender,uint256 amount) returns (bool)"]);var Tt=300*1e3,Nt=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})();import{Address as Pt,NETWORK as _t,OutScript as Bt,RawTx as $t,SigHash as Ft,TEST_NETWORK as qt,Transaction as Mt}from"@scure/btc-signer";import{createHash as ee}from"node:crypto";import{base58 as Wt}from"@scure/base";import{getCompiledTransactionMessageDecoder as Jt}from"@solana/transaction-messages";var C=e=>ee("sha256").update(`global:${e}`).digest().subarray(0,8).toString("hex"),zt=new Map([[C("route"),{name:"route",prefixBytes:0}],[C("shared_accounts_route"),{name:"shared_accounts_route",prefixBytes:1}]]);var er=64*1024;var fr=Object.freeze({"perp-order":"order","hip3-order":"order","hip4-order":"order","perp-bracket":"order","perp-cancel":"cancel","perp-leverage":"leverage","perp-isolated-margin":"margin","builder-fee-approval":"approveBuilder","hype-stake-deposit":"stake","hype-stake-withdraw":"unstake","hype-delegate":"delegate","hype-undelegate":"delegate"}),pr=Object.freeze({"perp-order":"order","hip3-order":"order","hip4-order":"order","perp-bracket":"order","perp-cancel":"cancel","perp-leverage":"updateLeverage","perp-isolated-margin":"updateIsolatedMargin","builder-fee-approval":"approveBuilderFee","hype-stake-deposit":"cDeposit","hype-stake-withdraw":"cWithdraw","hype-delegate":"tokenDelegate","hype-undelegate":"tokenDelegate"});var wr="0x"+"00".repeat(32);var te=Object.freeze([["salt","uint256"],["maker","address"],["signer","address"],["tokenId","uint256"],["makerAmount","uint256"],["takerAmount","uint256"],["side","uint8"],["signatureType","uint8"],["timestamp","uint256"],["metadata","bytes32"],["builder","bytes32"]]),xr=Object.freeze(te.map(e=>e[0]));var ae=new Set(["evm","evm-swap","evm-bridge","evm-nft","btc","sol","hl","poly","lighter"]);var Mr=Object.freeze({swap:5,bridge:5,perps:0,nft:0,mint:0,transfer:0,approve:0,order:0,cancel:0,leverage:0,margin:0,approveBuilder:0,stake:0,unstake:0,delegate:0});var se=Object.freeze({"0x04e45aaf":{provider:"uniswap-v3",action:"swap",layout:"router02-exact-input-single"},"0x414bf389":{provider:"uniswap-v3",action:"swap",layout:"swap-router-exact-input-single"},"0xc04b8d59":{provider:"uniswap-v3",action:"swap",layout:"exact-input-deadline"},"0xb858183f":{provider:"uniswap-v3",action:"swap",layout:"exact-input"},"0x5ae401dc":{provider:"uniswap-v3",action:"swap",layout:"multicall-deadline"},"0xa026383e":{provider:"aerodrome",action:"swap",layout:"aerodrome-exact-input-single"},"0x7b939232":{provider:"across-v3",action:"bridge",layout:"across-deposit-v3"}}),Dr=Object.freeze({"0x161ac21f":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-public"},"0xc2f6663a":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-allowlist"}}),Ur=new $(["function buySpecificNFT(uint256 tokenId,uint256 maxCost) payable","function sellNFT(uint256 tokenId,uint256 minPayout) payable"]),jr=new $(["function mintAllowList(address nftContract,address feeRecipient,address minterIfNotPayer,uint256 quantity,(uint80 mintPrice,uint48 maxTotalMintableByWallet,uint48 startTime,uint48 endTime,uint48 dropStageIndex,uint32 maxTokenSupplyForStage,uint16 feeBps,bool restrictFeeRecipients) mintParams,bytes32[] proof) payable"]),Wr=Object.freeze({"0xa0712d68":{provider:"nft-mint",action:"mint",layout:"mint-quantity"},"0x1249c58b":{provider:"nft-mint",action:"mint",layout:"mint-no-args"},"0x2db11544":{provider:"nft-mint",action:"mint",layout:"mint-quantity"},"0xefef39a1":{provider:"nft-mint",action:"mint",layout:"mint-quantity"},"0xa6f2ae3a":{provider:"nft-mint",action:"mint",layout:"mint-no-args"}});var ce=Object.freeze([...ae]),Hr=Object.freeze({...se});import{ed25519 as sn}from"@noble/curves/ed25519.js";import{base58 as un}from"@scure/base";import{RawTx as dn,SigHash as fn,Transaction as pn}from"@scure/btc-signer";import{Transaction as hn,keccak256 as wn,verifyTypedData as gn}from"ethers";import{encode as Gr}from"@msgpack/msgpack";import{keccak256 as Kr,verifyTypedData as Yr}from"ethers";var Xr=Object.freeze({name:"Exchange",version:"1",chainId:1337,verifyingContract:"0x0000000000000000000000000000000000000000"}),Qr=Object.freeze({Agent:[{name:"source",type:"string"},{name:"connectionId",type:"bytes32"}]});var $n=Object.freeze({N:1<<17,r:8,p:1}),Fn=256*1024*1024,qn=16*1024;var Dn=Object.freeze({1:{name:"ethereum",mode:"mempool-private",endpoints:["https://rpc.flashbots.net/fast","https://rpc.mevblocker.io"]},8453:{name:"base",mode:"sequencer",endpoints:["https://mainnet-sequencer.base.org"]},10:{name:"optimism",mode:"sequencer",endpoints:["https://mainnet-sequencer.optimism.io"]},42161:{name:"arbitrum",mode:"sequencer",endpoints:["https://arb1-sequencer.arbitrum.io/rpc"]},56:{name:"bsc",mode:"mempool-private",endpoints:["https://rpc.48.club","https://bsc.rpc.blxrbdn.com"]},137:{name:"polygon",mode:"mempool-private",endpoints:["https://polygon-bor-rpc.publicnode.com"]},43114:{name:"avalanche",mode:"public-only",endpoints:[]},999:{name:"hyperevm",mode:"public-only",endpoints:[]}});import{homedir as I}from"node:os";import{join as T}from"node:path";var q=process.env.ORACLE_PUBLIC_DESKTOP==="1",de=q?process.env.ORACLE_CONFIG_DIR||T(I(),".config","oracle"):T(I(),".config","oracle"),Hn=q?de:T(I(),".config","mad-desk");var Kn="0".repeat(64),Yn=Object.freeze({PREPARE:"exec.prepare",SIGN:"exec.sign",BROADCAST:"exec.broadcast",POLICY_REJECT:"policy.reject",AUTH_GRANT:"auth.grant",AUTH_OK:"auth.verify.ok",AUTH_FAIL:"auth.verify.fail"});var Xn=Promise.resolve();import{Wallet as so}from"ethers";import{base58 as uo}from"@scure/base";import{ed25519 as fo}from"@noble/curves/ed25519.js";import{NETWORK as mo,TEST_NETWORK as ho,WIF as wo,p2wpkh as go}from"@scure/btc-signer";import{pubECDSA as Eo}from"@scure/btc-signer/utils.js";var ki=new N(["function collection() view returns (address)","function token() view returns (address)","function robinhoodSwapFeeWei() view returns (uint256)","function quoteSpecificBuy(uint256 tokenId) view returns (uint256 totalCost,uint256 baseCost,uint256 fee,uint256 protocolFee,bool available)","function quoteSellNFT() view returns (uint256 netPayout,uint256 grossPayout,uint256 fee,uint256 protocolFee)","function inventory(uint256 tokenId) view returns (bool)","function buySpecificNFT(uint256 tokenId,uint256 maxCost) payable","function sellNFT(uint256 tokenId,uint256 minPayout) payable"]),Ii=new N(["function decimals() view returns (uint8)","function allowance(address owner,address spender) view returns (uint256)"]),Ti=new N(["function ownerOf(uint256 tokenId) view returns (address)","function getApproved(uint256 tokenId) view returns (address)","function isApprovedForAll(address owner,address operator) view returns (bool)"]);function D(e){let r=process.env.ORACLE_SIGNER_STATE_DIR||c.join(process.env.XDG_STATE_HOME||c.join(pe.homedir(),".local","state"),"oracle"),t=me("sha256").update(c.resolve(e)).digest("hex").slice(0,16);return{vault:c.join(e,"vault.json"),policy:c.join(e,"signer-policy.json"),policyKey:c.join(e,"policy-integrity-key"),policyAnchor:c.join(r,`signer-policy-${t}.high-water`),ledger:c.join(e,"signer-ledger.json"),ledgerAnchor:c.join(r,`signer-ledger-${t}.high-water`),token:c.join(e,"signer-token"),lock:c.join(r,`signer-${t}.lock`)}}function we(){return process.env.ORACLE_CONFIG_DIR||U.join(he(),".config","oracle")}function h(){let e=D(U.join(we(),"signer")),r=O.existsSync(e.vault),t=O.existsSync(e.lock),o=r?t?"disarmed":"armed-owner-confirmed":"inert-no-key";return{vaultExists:r,policyConfigured:O.existsSync(e.policy),armed:r&&!t,disarmed:t,capabilities:{swap:o,bridge:o},autonomous:!1,note:"Keys stay on this machine. Exact confirmation is required before any broadcast."}}var qi=Object.freeze([{type:"function",function:{name:"vault_status",description:"Read local Oracle vault/signer readiness. Never returns key material.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"signer_status",description:"Ping the loopback signer. Fails closed if it is not running.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"signer_pending",description:"List pending local-signer artifacts. Read-only. Does not approve, sign, or broadcast.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"signer_queue",description:"Queue a prepared unsigned artifact on the loopback signer. Does not broadcast.",parameters:{type:"object",properties:{artifact:{type:"object"}},required:["artifact"],additionalProperties:!1}}},{type:"function",function:{name:"signer_ack",description:"Execute one pending artifact through the armed local signer (same path as Telegram Allow). Fails if the signer is not running or disarmed. Never holds keys.",parameters:{type:"object",properties:{id:{type:"string"},digest:{type:"string"}},additionalProperties:!1}}},{type:"function",function:{name:"signer_deny",description:"Drop one pending local-signer artifact. Nothing signed.",parameters:{type:"object",properties:{id:{type:"string"},digest:{type:"string"}},additionalProperties:!1}}},{type:"function",function:{name:"signer_execute",description:"Broadcast one already-confirmed local artifact. Requires a one-use confirmationNonce from the local signer TTY confirm. Cannot mint confirmation itself.",parameters:{type:"object",properties:{artifact:{type:"object"},confirmationNonce:{type:"string",minLength:32,maxLength:128}},required:["artifact","confirmationNonce"],additionalProperties:!1}}},{type:"function",function:{name:"signer_disarm",description:"Global kill switch. Stops the local signer from broadcasting.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"receipt_report",description:"Receipt or it did not happen. Requires transactionHash/hash/txid.",parameters:{type:"object",properties:{receipt:{type:"object"},transactionHash:{type:"string"},hash:{type:"string"},txid:{type:"string"}},additionalProperties:!1}}},{type:"function",function:{name:"watch_create",description:"Create an alert-only watch. Never execute.",parameters:{type:"object",properties:{chain:{type:"string"},token:{type:"string"},condition:{type:"string"},note:{type:"string"}},required:["chain","token","condition"],additionalProperties:!1}}},{type:"function",function:{name:"watch_list",description:"List local alert-only watches.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"portfolio_snapshot",description:"How to read the one portfolio snapshot. knownUsd is incomplete if a provider is missing.",parameters:{type:"object",properties:{},additionalProperties:!1}}}]);import H from"node:fs";import Te from"node:path";import w from"node:fs";import ge from"node:os";import f from"node:path";import{fileURLToPath as ye}from"node:url";var Ee=f.dirname(ye(import.meta.url)),Hi=f.resolve(Ee,"../..");function j(){return process.env.ORACLE_FAKE_HOME||ge.homedir()}function be(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function g(){return be()?process.env.ORACLE_CONFIG_DIR||f.join(j(),".config","oracle"):f.join(j(),".config","oracle")}function xe(){return f.join(g(),"desk.json")}function Se(){return f.join(g(),"env")}function d({force:e=!1}={}){if(d._done&&!e)return d._result||null;d._done=!0;let r={},t=(i,n)=>{if(n==null)return;let a=String(n).trim();a&&(process.env[i]!=null&&String(process.env[i]).trim()!==""||(process.env[i]=a,r[i]=a))};try{let i=Se();if(w.existsSync(i))for(let n of w.readFileSync(i,"utf8").split(/\r?\n/)){let a=n.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!a||a[2].startsWith("#"))continue;let s=a[2];(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1)),t(a[1],s)}}catch{}try{let i=xe();if(w.existsSync(i)){let n=JSON.parse(w.readFileSync(i,"utf8"));n&&typeof n=="object"&&(t("ORACLE_DESK_URL",n.deskUrl||n.dataUrl||n.url),t("ORACLE_DATA_URL",n.dataUrl||n.deskUrl||n.url),t("ORACLE_API_URL",n.apiUrl||n.dataUrl||n.deskUrl),t("ORACLE_PUBLIC_URL",n.publicUrl||n.deskUrl||n.dataUrl),t("ORACLE_EXEC_URL",n.execUrl),t("MAD_DESK_URL",n.deskUrl||n.dataUrl))}}catch{}let o=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return o&&(t("ORACLE_DESK_URL",o),t("ORACLE_DATA_URL",o),t("ORACLE_API_URL",o),t("ORACLE_PUBLIC_URL",o),t("MAD_DESK_URL",o)),d._result=Object.keys(r).length?r:null,d._result}try{d()}catch{}var Ae=new Set(["openrouter","openai","anthropic","xai","deepseek","gemini","kimi","mistral","nous","qwen","glm","custom","anthropic-oauth","openai-codex","xai-oauth"]);function y(e){return String(e||"").trim()||void 0}function ve(e,{required:r=!1}={}){let t=y(e)?.toLowerCase();if(!t){if(r)throw new Error("model provider is required");return}if(!Ae.has(t))throw new Error(`unsupported provider: ${t}`);return t}function ke(e,{required:r=!1}={}){let t=y(e);if(!t){if(r)throw new Error("model is required");return}if(t.includes("..")||t.startsWith("/")||!/^[a-zA-Z0-9._:/-]{1,200}$/.test(t))throw new Error("invalid model id");return t}function Ie(e){let r=y(e);if(!r||r.length>2048)throw new Error("invalid custom base URL");let t;try{t=new URL(r)}catch{throw new Error("invalid custom base URL")}let o=t.hostname.toLowerCase().replace(/^\[|\]$/g,""),i=o==="localhost"||o==="127.0.0.1"||o==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&i)||t.username||t.password||t.search||t.hash)throw new Error("custom base URL must use HTTPS or loopback HTTP without credentials, query, or fragment");return t.toString().replace(/\/+$/,"")}function W({provider:e,model:r,baseUrl:t}={},{requireModel:o=!1}={}){let i=ve(e),n=ke(r,{required:o});if(i==="custom")return{provider:i,...n?{model:n}:{},baseUrl:Ie(t)};if(y(t))throw new Error("baseUrl is only supported for the custom provider");return{...i?{provider:i}:{},...n?{model:n}:{}}}var Ne=new Set(["auto","standalone","hermes","remote","arch"]);function Oe(){return Te.join(g(),"model.json")}function p(e){return String(e||"").trim()||void 0}function Le(e={}){let r=p(e.backend)?.toLowerCase()||"auto",t=W({provider:e.provider,model:e.model,baseUrl:e.baseUrl},{requireModel:r==="standalone"}),o=p(e.apiKeyEnv),i=Number.parseInt(String(e.contextLength||""),10),n=p(e.reasoningEffort),a=p(e.computeHost||e.remoteHost),s=p(e.computeUser||e.remoteUser),u=p(e.computePath||e.remotePath);if(!Ne.has(r))throw new Error(`unsupported backend: ${r}`);if(process.env.ORACLE_PUBLIC_DESKTOP==="1"&&["remote","arch"].includes(r))throw new Error("remote compute backends are disabled in the public desktop");if(o&&!/^[A-Z][A-Z0-9_]*$/.test(o))throw new Error("api key env must be an uppercase environment variable name");if(r==="remote"&&!a)throw new Error("remote backend requires computeHost");return{backend:r,...t,...o?{apiKeyEnv:o}:{},...Number.isFinite(i)&&i>0?{contextLength:i}:{},...n?{reasoningEffort:n}:{},...a?{computeHost:a}:{},...s?{computeUser:s}:{},...u?{computePath:u}:{}}}function J(){let e=Oe();if(!H.existsSync(e))return null;try{return Le(JSON.parse(H.readFileSync(e,"utf8")))}catch{return null}}var Ce=new Set(["127.0.0.1","::1","localhost"]);function L({env:e=process.env,vault:r=null}={}){let t=r||h(),o=[];for(let[i,n]of Object.entries(b)){let a=(n.rpcEnv||[]).some(u=>String(e[u]||"").trim()),s="prepare";n.evm?a&&(s="live"):s="unavailable",o.push({key:i,chainId:n.chainId,name:n.name,family:"evm",status:s,execute:!!(t.vaultExists&&t.armed&&!t.disarmed),note:a?"rpc configured":"public read/prepare; set RPC for live reads"})}return o.push({key:"solana",chainId:null,name:"Solana",family:"sol",status:"prepare",execute:!1,note:"Jupiter quote/prepare; local sol signer"},{key:"bitcoin",chainId:null,name:"Bitcoin",family:"btc",status:"prepare",execute:!1,note:"Esplora read; local btc signer"},{key:"hyperliquid-l1",chainId:null,name:"Hyperliquid L1",family:"data",status:"live",execute:!1,note:"data/prepare only \u2014 not an EVM signer family"},{key:"polymarket",chainId:null,name:"Polymarket",family:"data",status:"live",execute:!1,note:"data/prepare only \u2014 not a signer family"}),o}function Re({env:e=process.env,model:r=J(),vault:t=h(),signerReachable:o=!1,quote:i=null}={}){let n=[],a=(l,E,z,G=null)=>n.push({id:l,status:E,detail:z,fix:G}),s=(()=>{let[l,E]=process.versions.node.split(".").map(Number);return l>20||l===20&&E>=19})();a("node",s?"ok":"fail",`node ${process.versions.node}`,s?null:"install node >= 20.19"),r?r.backend==="hermes"?a("model","warn","backend=hermes (opt-in attach)","oracle model --backend standalone"):a("model","ok",`${r.backend||"auto"} ${r.provider||""} ${r.model||""}`.trim()):a("model","fail","no model.json","oracle setup model"),t.vaultExists?t.disarmed?a("vault","warn","vault present, DISARMED","oracle signer (re-arm after confirm)"):a("vault",t.armed?"ok":"warn",t.armed?"present, armed":"present, not armed"):a("vault","fail","no local vault","oracle sign init");let u=e.ORACLE_SIGNER_HOST||"127.0.0.1";return Ce.has(u)?a("signer",o?"ok":"warn",o?`loopback ${u}:${e.ORACLE_SIGNER_PORT||9462}`:"loopback signer not reachable",o?null:"oracle signer"):a("signer","fail",`signer host ${u} is not loopback`,"unset ORACLE_SIGNER_HOST"),i?i.ok?a("quote","ok",i.detail||"net quote returned"):a("quote","warn",i.detail||"quote unavailable","check network / oracle data serve"):a("quote","warn","quote not probed",null),{ok:!n.some(l=>l.status==="fail"),checks:n,venues:L({env:e,vault:t})}}async function aa(e=process.env){let r=e.ORACLE_SIGNER_HOST||"127.0.0.1",t=e.ORACLE_SIGNER_PORT||9462;try{return(await fetch(`http://${r}:${t}/status`,{signal:AbortSignal.timeout(1500)})).ok}catch{return!1}}async function sa(){try{let e=await fetch("https://api.dexscreener.com/latest/dex/search?q=WETH%20USDC",{signal:AbortSignal.timeout(4e3)});if(!e.ok)return{ok:!1,detail:`dexscreener ${e.status}`};let t=(await e.json())?.pairs?.[0];return!t?.chainId||!t?.priceUsd?{ok:!1,detail:"no pair"}:{ok:!0,detail:`${t.chainId} ${t.baseToken?.symbol}/${t.quoteToken?.symbol} $${t.priceUsd}`}}catch(e){return{ok:!1,detail:e instanceof Error?e.message:"quote failed"}}}var ca={name:"venues",summary:"label every shipped venue live / prepare / unavailable",group:"read",usage:"oracle venues [--json]",async run(e){let r=e.argv.includes("--json"),t=L();if(r)return process.stdout.write(`${JSON.stringify({venues:t},null,2)}
2
2
  `),0;for(let o of t)process.stdout.write(`${o.status.padEnd(12)} ${o.key.padEnd(16)} ${o.name} exec=${o.execute?"local":"no"}
3
3
  `);return 0}};export{x as classifyReceipt,ca as default,Re as firstHourReport,sa as probeQuote,aa as probeSigner,h as vaultStatus};
@@ -0,0 +1 @@
1
+ import{createHash as tr,timingSafeEqual as nr}from"node:crypto";import{createHash as je,createHmac as Hr,timingSafeEqual as Kr}from"node:crypto";var Fe=2,k=300*1e3,ee=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})();function V(e){let r=e==null||e===""?k:Number(e);return!Number.isFinite(r)||r<0?k:Math.min(r,ee)}function L(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(L).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${L(e[t])}`).join(",")}}`}function Le(e){let{prepareHash:r,prepareMac:t,note:n,...o}=e||{};return o}function G(e){let r=Le(e);return je("sha256").update(L(r)).digest("hex")}function re(e,{maxAgeMs:r=k,nowMs:t=Date.now(),providers:n=null,kinds:o=null,label:s="operator"}={}){if(!e||typeof e!="object")throw new Error(`${s}: prepared envelope object required`);if(e.oraclePrepared!==!0)throw new Error(`${s}: prepared integrity envelope missing \u2014 use an @oracle-agent/oracle prepare result`);if(Number(e.prepareVersion)!==Fe)throw new Error(`${s}: unsupported prepareVersion ${e.prepareVersion}`);let i=G(e);if(String(e.prepareHash||"")!==i)throw new Error(`${s}: prepareHash mismatch \u2014 payload was altered after prepare`);let a=Number(e.preparedAt),c=Number(e.expiresAt),m=V(r),d=t-a,p=c-a;if(!Number.isFinite(d)||!Number.isFinite(c)||!Number.isFinite(p)||d<0||p<=0||p>ee||d>m||t>=c)throw new Error(`${s}: prepare envelope expired or clock-skewed (ageMs=${d}, max=${m})`);if(n&&!new Set(n).has(e.provider))throw new Error(`${s}: provider ${e.provider} not allowed here`);if(o&&!new Set(o).has(e.kind))throw new Error(`${s}: kind ${e.kind} not allowed here`);return!0}function Ge(e,r="value"){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${r} must be a finite number`);if(Math.abs(e)>Number.MAX_SAFE_INTEGER)throw new Error(`${r} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`);if(Number.isInteger(e)&&!Number.isSafeInteger(e))throw new Error(`${r} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`);return String(e)}if(typeof e=="string"){if(e!==e.trim())throw new Error(`${r} must be a number or decimal string`);return e}throw new Error(`${r} must be a number or decimal string`)}function te(e,r="amount"){if(typeof e=="bigint")return e;if(typeof e=="number"){if(!Number.isInteger(e))throw new Error(`${r} must be an integer`);if(!Number.isSafeInteger(e))throw new Error(`${r} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`);return BigInt(e)}let t=Ge(e,r);if(t==="")throw new Error(`${r} is required`);if(!/^-?\d+$/.test(t)&&!/^0x[0-9a-fA-F]+$/.test(t))throw new Error(`${r} must be an integer in decimal or 0x-hex form, got ${JSON.stringify(t)}`);try{return BigInt(t)}catch{throw new Error(`${r} must be an integer, got ${JSON.stringify(t)}`)}}function z(e,r,t="guard"){if(typeof r!="number"||!Number.isFinite(r))throw new Error(`${t}: current time must be a finite number (got ${ze(r)})`);let n=r,o=Number(e?.issuedAtMs),s=Number(e?.expiresAtMs);if(!Number.isFinite(s))throw new Error(`${t}: expiresAtMs is required and must be a finite number`);if(n>s)throw new Error(`${t} expired at ${s}, now ${n}`);if(e?.issuedAtMs!=null){if(!Number.isFinite(o))throw new Error(`${t}: issuedAtMs must be a finite number when present`);if(s<=o)throw new Error(`${t}: expiry must be after issuance`)}return{now:n,issuedAtMs:o,expiresAtMs:s}}function ze(e){return e===null?"null":e===void 0?"undefined":typeof e=="number"?String(e):`${typeof e} ${JSON.stringify(String(e)).slice(0,24)}`}import{createHash as qe}from"node:crypto";var le=1,ne=Object.freeze(["chainId","agentAddress","accountAddress","actions","targets","maxValueWei","maxGasWei","maxSlippageBps","expiresAt","nonce","revocationKey"]),Ce=Object.freeze(["read","simulate"]),oe=1e4,se=1440*60,ie=128,ae=256,ce=64,pe=256,ue=/^0x[0-9a-fA-F]{40}$/,We=/^[a-z][a-z0-9_-]*:[a-z0-9._-]+$/,He=/^[a-z][a-z0-9_-]*:\*$/,Ke=/^[A-Za-z0-9._:-]+$/,Ye=/^[A-Za-z0-9._:-]+$/,de=/^(0|[1-9][0-9]*)$/,B=class extends Error{constructor(r){let t=r.map(n=>`${n.field}: ${n.message}`);super(`invalid grant (${r.length} error${r.length===1?"":"s"}): ${t.join("; ")}`),this.name="GrantValidationError",this.errors=r}};function Ue(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function Xe(e){if(typeof e=="bigint")return e>=0n?e.toString(10):null;if(typeof e=="number")return!Number.isSafeInteger(e)||e<0?null:String(e);if(typeof e=="string"){let r=e.trim();return de.test(r)?r:null}return null}function M(e){if(typeof e=="bigint")return e<0n||e>BigInt(Number.MAX_SAFE_INTEGER)?null:Number(e);if(typeof e=="number")return!Number.isSafeInteger(e)||e<0?null:e;if(typeof e=="string"){let r=e.trim();if(!de.test(r))return null;let t=Number(r);return Number.isSafeInteger(t)?t:null}return null}function fe(e){let r=String(e).split(":")[0];return Ce.includes(r)}function Je(e,r={}){let t=[],n=(p,u)=>t.push({field:p,message:u});if(!Ue(e))return n("grant","grant must be a plain object"),{ok:!1,errors:t,grant:null};for(let p of Object.keys(e))ne.includes(p)||n(p,"unknown field is not allowed");for(let p of ne)(!(p in e)||e[p]==null)&&n(p,"required field is missing");if(t.length)return{ok:!1,errors:t,grant:null};let o={},s=M(e.chainId);s==null||s<=0?n("chainId","must be a positive integer chain id"):o.chainId=s;for(let p of["agentAddress","accountAddress"]){let u=e[p];typeof u!="string"||!ue.test(u.trim())?n(p,"must be a 0x-prefixed 20-byte hex address"):o[p]=u.trim().toLowerCase()}if(!Array.isArray(e.actions)||e.actions.length===0)n("actions","must be a non-empty array of action scopes");else if(e.actions.length>ce)n("actions",`too many actions (max ${ce})`);else{let p=[];for(let u of e.actions){let x=typeof u=="string"?u.trim():null;if(!x){n("actions","action entries must be non-empty strings");continue}if(x.includes("*")){r.allowWildcardActions===!0&&He.test(x)?p.push(x):n("actions",`broad wildcard action "${x}" is rejected (fail closed)`);continue}if(!We.test(x)){n("actions",`malformed action "${x}" (expected verb:resource)`);continue}p.push(x)}o.actions=[...new Set(p)].sort()}if(!Array.isArray(e.targets))n("targets","must be an array of contract addresses");else if(e.targets.length>pe)n("targets",`too many targets (max ${pe})`);else{let p=[];for(let u of e.targets){let x=typeof u=="string"?u.trim():null;if(!x||!ue.test(x)){n("targets",`target "${u}" must be a 0x-prefixed 20-byte hex address (wildcards not allowed)`);continue}p.push(x.toLowerCase())}if(o.targets=[...new Set(p)].sort(),o.targets.length===0&&Array.isArray(o.actions)){let u=o.actions.filter(x=>!fe(x));(u.length>0||o.actions.length===0)&&n("targets",`empty targets are only allowed for read/simulate scopes (blocked by: ${u.join(", ")||"no valid actions"})`)}}for(let p of["maxValueWei","maxGasWei"]){let u=Xe(e[p]);u==null?n(p,"must be a non-negative integer wei amount"):o[p]=u}let i=M(e.maxSlippageBps);i==null||i>oe?n("maxSlippageBps",`must be an integer between 0 and ${oe}`):o.maxSlippageBps=i;let a=864e10,c=M(e.expiresAt);if(c==null||c<=0)n("expiresAt","must be a positive unix-seconds timestamp");else if(c>a)n("expiresAt","exceeds the max unix-seconds timestamp (pass seconds, not milliseconds)");else if(o.expiresAt=c,r.now!=null){let p=M(r.now);p==null?n("expiresAt","opts.now must be a unix-seconds integer"):c<=p?n("expiresAt",`grant is expired (expiresAt ${c} <= now ${p})`):c-p>se&&n("expiresAt",`grant exceeds the hard 24-hour TTL (${se} seconds)`)}let m=typeof e.nonce=="string"?e.nonce.trim():M(e.nonce)!=null?String(M(e.nonce)):null;!m||m.length>ie||!Ke.test(m)?n("nonce",`must be a non-empty string (max ${ie} chars, [A-Za-z0-9._:-])`):o.nonce=m;let d=typeof e.revocationKey=="string"?e.revocationKey.trim():null;return!d||d.length>ae||!Ye.test(d)?n("revocationKey",`must be a non-empty public identifier (max ${ae} chars, [A-Za-z0-9._:-])`):o.revocationKey=d,t.length?{ok:!1,errors:t,grant:null}:{ok:!0,errors:[],grant:o}}function me(e,r={}){let{ok:t,errors:n,grant:o}=Je(e,r);if(!t)throw new B(n);return o}function ge(e,r={}){let t=me(e,r),o=Object.keys(t).sort().map(s=>`${JSON.stringify(s)}:${JSON.stringify(t[s])}`);return`{"version":${le},${o.join(",")}}`}function q(e,r={}){return qe("sha256").update(ge(e,r),"utf8").digest("hex")}var S=class extends Error{constructor(r,t){super(`secret material must never appear in a public API object (at ${r}, rule: ${t})`),this.name="SecretLeakError",this.path=r,this.rule=t}},Ze=/(private[_-]?key|secret|bearer|keystore|mnemonic|seed[_-]?phrase|passphrase|password|api[_-]?key|access[_-]?token|auth[_-]?token|session[_-]?token|signer[_-]?url|signature)/i,Qe=Object.freeze(["privkey","wif","xprv","seed"]);function xe(e){let r=String(e),t=r.toLowerCase().replace(/[\s._-]+/g,"");return Ze.test(r)||Qe.includes(t)}var er=Object.freeze([{rule:"raw-32-byte-hex-key",re:/^0x[0-9a-fA-F]{64}$/},{rule:"raw-32-byte-hex-bare",re:/^[0-9a-fA-F]{64}$/},{rule:"extended-private-key",re:/\b(?:xprv|tprv|yprv|zprv)[1-9A-HJ-NP-Za-km-z]{107}\b/},{rule:"bitcoin-wif",re:/\b[59KLc][1-9A-HJ-NP-Za-km-z]{50,51}\b/},{rule:"bip39-mnemonic",re:/\b(?:[a-z]{3,8}\s+){11,23}[a-z]{3,8}\b/},{rule:"bearer-token",re:/bearer\s+[A-Za-z0-9._~+/=-]+/i},{rule:"pem-private-key",re:/-----BEGIN[A-Z ]*PRIVATE KEY-----/},{rule:"keystore-path",re:/keystore/i},{rule:"signer-url",re:/https?:\/\/\S*sign/i},{rule:"authorization-header",re:/authorization\s*:/i}]),rr=Object.freeze(["grantid","id","hash","sha256","sha256hex","checksum","txhash","transactionhash","blockhash","digest","userophash","commithash","prevhash","intenthash","canonicalhash","payloadhash","requestid"]);function $(e,r="$",t=new Set,n=""){if(e==null)return e;if(typeof e=="string"){let o=rr.includes(String(n).toLowerCase().replace(/[_-]/g,""));for(let{rule:s,re:i}of er)if(!(o&&s.startsWith("raw-32-byte-hex"))&&i.test(e))throw new S(r,s);return e}if(typeof e!="object"||t.has(e)||(t.add(e),ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e;if(e instanceof Map){for(let[o,s]of e.entries()){if(typeof o=="string"&&xe(o))throw new S(`${r}[${JSON.stringify(o)}]`,"forbidden-key-name");$(o,`${r}[key]`,t),$(s,`${r}[${String(o)}]`,t)}return e}if(e instanceof Set){let o=0;for(let s of e.values())$(s,`${r}[${o++}]`,t);return e}if(Array.isArray(e))return e.forEach((o,s)=>$(o,`${r}[${s}]`,t)),e;for(let[o,s]of Object.entries(e)){if(xe(o))throw new S(`${r}.${o}`,"forbidden-key-name");$(s,`${r}.${o}`,t,o)}return e}var O=1,C=1,N=1,W="oracle.approval-binding/1",H="0.28.26+approval-binding.1",K="oracle.approval-binding.v1",he=2e4,ye=he,or=Object.freeze(["evm-swap","evm-approval","evm-transfer","evm-bridge","nft-mint"]),sr=Object.freeze(["legacy","eip2930","eip1559"]),ir=Object.freeze(["eip4844","eip7702"]),at=Object.freeze({custody:"none",execution:"prepare-only",authenticatesApprover:!1,maxExecutions:1,networkIo:!1,signer:!1}),ar=(1n<<256n)-1n,Ee=new Set(or),cr=new Set(["human","ownerKey"]),pr=new Set(sr),ur=Object.freeze({legacy:"legacy","0x0":"legacy",0:"legacy",0:"legacy",eip2930:"eip2930","0x1":"eip2930",1:"eip2930",1:"eip2930",eip1559:"eip1559","0x2":"eip1559",2:"eip1559",2:"eip1559",eip4844:"eip4844","0x3":"eip4844",3:"eip4844",3:"eip4844",eip7702:"eip7702","0x4":"eip7702",4:"eip7702",4:"eip7702"}),lr=/^(signhash|signature|sig|privatekey|privkey|secret|secretkey|mnemonic|seed|seedphrase|passphrase|password|apikey|authorization|bearer|keystore|wif|xprv)$/i,dr=/(?:hash|digest|checksum|mac|id)$/i,Y=/^[0-9a-f]{64}$/,fr=/^0x[0-9a-f]{64}$/,mr=/^0x[0-9a-f]{40}$/,gr=/^0x(?:[0-9a-f]{2})*$/,xr=/^[^\u0000-\u001f\u007f]+$/,wr=Object.freeze(["allowedChainIds","destinationAllowlist","expiresAtMs","grant","maxDailyValueWei","maxFeePerGasWei","maxGasLimit","maxPriorityFeePerGasWei","maxSlippageBps","maxValuePerTxWei","policyVersion"]),hr=Object.freeze(["allowedChainIds","destinationAllowlist","expiresAtMs","grantExpiresAtMs","grantId","maxDailyValueWei","maxFeePerGasWei","maxGasLimit","maxPriorityFeePerGasWei","maxSlippageBps","maxValuePerTxWei","policyVersion"]),yr=Object.freeze(["chainId","destinations"]),Er=Object.freeze(["accessList","chainId","data","from","gasLimit","gasPrice","maxFeePerGas","maxPriorityFeePerGas","nonce","to","type","value"]),Ar=Object.freeze(["provider","routeId","venue"]),br=Object.freeze(["provider","routeDigest","routeId","venue"]),Ae=Object.freeze(["account","amountIn","amountOut","assetIn","assetOut","minAmountOut","quoteId","recipient","slippageBps","slippageGuardDigest"]),vr=Object.freeze([...Ae,"quoteDigest"]),Ir=Object.freeze(["balanceDeltasDigest","blockHash","blockNumber","engine","logsDigest","stateOverridesDigest","status"]),be=Object.freeze(["builtAtMs","calls","custody","execution","expiresAtMs","policyDigest","postconditions","prepare","previewId","previewVersion","quote","route","simulation","surface"]),$r=Object.freeze([...be,"previewHash"]),Sr=Object.freeze(["approvalTtlMs","bindingVersion","expectedSigner","issuedAtMs","nowMs","preview","requestedExpiresAtMs","resolvedPolicy","sessionExpiresAtMs","tenantId"]),Pr=Object.freeze(["approvalTtlMs","grantExpiresAtMs","issuedAtMs","policyExpiresAtMs","prepareExpiresAtMs","previewExpiresAtMs","requestedExpiresAtMs","sessionExpiresAtMs"]),Mr=Object.freeze(["bindingVersion","buildVersion","calls","custody","domainSeparator","execution","expectedFrom","expectedSigner","expiresAtMs","expiryBounds","maxExecutions","oneShot","policyDigest","postconditions","prepareHash","previewHash","previewId","quote","route","schemaVersion","simulation","surface","tenantId"]),_r=Object.freeze(["approvalVersion","approver","binding","issuedAtMs","maxExecutions","oneShot"]),Or=Object.freeze(["approvalDigest","approvalId","approvalVersion","approver","binding","custody","execution","expiresAtMs","issuedAtMs","maxExecutions","oneShot","previewId"]),Nr=Object.freeze(["kind","ref"]),Tr=Object.freeze(["executionCount","expectedApprovalDigest","expectedFrom","nowMs","preview","resolvedPolicy","tenantId"]),Rr=Object.freeze(["address","storageKeys"]);function Dr(e){if(e==null||typeof e!="object"||Array.isArray(e))return!1;let r=Object.getPrototypeOf(e);return r===Object.prototype||r===null}function X(e,r){if(!Dr(e))throw new TypeError(`${r} must be a plain object`);for(let t of Reflect.ownKeys(e)){if(typeof t!="string")throw new TypeError(`${r} may contain only string keys`);let n=Object.getOwnPropertyDescriptor(e,t);if(!n?.enumerable||!("value"in n))throw new TypeError(`${r}.${t} must be an enumerable data field`)}return e}function g(e,r,t){X(e,t);let n=Object.keys(e).sort(),o=[...r].sort();if(n.length!==o.length||n.some((s,i)=>s!==o[i])){let s=o.filter(a=>!n.includes(a)),i=n.filter(a=>!o.includes(a));throw new TypeError(`${t} keys must be exact (missing: ${s.join(",")||"none"}; unknown: ${i.join(",")||"none"})`)}}function E(e,r,{min:t=0,max:n=1e3}={}){if(!Array.isArray(e)||e.length<t||e.length>n)throw new TypeError(`${r} must be an array with ${t}..${n} entries`);return e}function f(e,r,{min:t=0,max:n=Number.MAX_SAFE_INTEGER}={}){if(typeof e!="number"||!Number.isSafeInteger(e)||e<t||e>n)throw new TypeError(`${r} must be a safe integer from ${t} through ${n}`);return e}function T(e,r){return e===null?null:f(e,r,{min:1})}function h(e,r,t=256){if(typeof e!="string"||e.length<1||e.length>t||e!==e.trim()||!xr.test(e))throw new TypeError(`${r} must be non-empty printable text up to ${t} characters`);return e}function y(e,r){if(typeof e!="string"||!Y.test(e))throw new TypeError(`${r} must be lowercase sha256 hex`);return e}function w(e,r){if(typeof e!="string"||!mr.test(e.toLowerCase()))throw new TypeError(`${r} must be a 20-byte EVM address`);return e.toLowerCase()}function l(e,r,{positive:t=!1}={}){if(typeof e=="string"&&!/^(0|[1-9][0-9]*)$/.test(e))throw new TypeError(`${r} must be an unsigned decimal integer`);let n=te(e,r);if(n<0n||n>ar||t&&n===0n)throw new RangeError(`${r} is outside uint256 bounds`);return n.toString(10)}function R(e,r){return l(e,r,{positive:!0})}function we(e,r){if(typeof e!="string"||!gr.test(e.toLowerCase()))throw new TypeError(`${r} must be complete, even-length 0x calldata`);return e.toLowerCase()}function b(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let r of Object.values(e))b(r);Object.freeze(e)}return e}var kr=new Set(["requiresUserSignature","signingReady","broadcastReady","executionReady","oraclePrepared","prepareHash","prepareMac","prepareVersion","preparedAt","expiresAt","provider","kind","note"]);function U(e,r=new WeakMap){if(e==null||typeof e!="object")return e;if(r.has(e))return r.get(e);if(Array.isArray(e)){let n=[];r.set(e,n);for(let o of e)n.push(U(o,r));return n}let t={};r.set(e,t);for(let[n,o]of Object.entries(e)){let s=String(n).toLowerCase().replace(/[_-]/g,"");if(!(kr.has(n)||n==="storageKeys")){if(lr.test(s))throw new S(`$.${n}`,"forbidden-key-name");if(typeof o=="string"&&/^(?:0x)?[0-9a-f]{64}$/i.test(o)&&dr.test(s)){t[n]="public-digest";continue}t[n]=U(o,r)}}return t}function v(e,r){$(U(e),r)}function J(e,r){let t=h(e,r,128);if(!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(t))throw new TypeError(`${r} must be a bounded tenant identifier`);return t}function Vr(e,r){if(typeof e!="string"||!/^0x[0-9a-f]{64}$/.test(e.toLowerCase()))throw new TypeError(`${r} must be a 32-byte storage key`);return e.toLowerCase()}function Br(e,r){return E(e,r,{min:0,max:128}).map((t,n)=>{let o=`${r}[${n}]`;g(t,Rr,o);let s=[...new Set(E(t.storageKeys,`${o}.storageKeys`,{min:0,max:256}).map((i,a)=>Vr(i,`${o}.storageKeys[${a}]`)))].sort();return{address:w(t.address,`${o}.address`),storageKeys:s}}).sort((t,n)=>t.address<n.address?-1:t.address>n.address?1:0)}function jr(e,r){let t=ur[typeof e=="string"?e.trim().toLowerCase():e];if(t==null)throw new TypeError(`${r} must be a closed EVM transaction type`);if(ir.includes(t))throw new TypeError(`${r} ${t} is unsupported; blob and EIP-7702 fields are refused rather than partially bound`);if(!pr.has(t))throw new TypeError(`${r} is unsupported`);return t}function P(e){let r=new Set;function t(n,o,s){if(s>256)throw new TypeError(`canonical JSON nesting exceeds 256 at ${o}`);if(n===null)return"null";if(typeof n=="string"||typeof n=="boolean")return JSON.stringify(n);if(typeof n=="number"){if(!Number.isSafeInteger(n))throw new TypeError(`canonical JSON number at ${o} must be a safe integer`);return JSON.stringify(n)}if(typeof n!="object")throw new TypeError(`canonical JSON does not allow ${typeof n} at ${o}`);if(r.has(n))throw new TypeError(`canonical JSON does not allow cycles at ${o}`);r.add(n);let i;return Array.isArray(n)?i=`[${n.map((a,c)=>t(a,`${o}[${c}]`,s+1)).join(",")}]`:(X(n,o),i=`{${Object.keys(n).sort().map(c=>`${JSON.stringify(c)}:${t(n[c],`${o}.${c}`,s+1)}`).join(",")}}`),r.delete(n),i}return t(e,"$",0)}function D(e){return tr("sha256").update(P(e),"utf8").digest("hex")}function ve(e,r,t){let n=E(e,t,{min:1,max:1e3}).map((o,s)=>{let i=`${t}[${s}]`;g(o,yr,i);let a=R(o.chainId,`${i}.chainId`),c=[...new Set(E(o.destinations,`${i}.destinations`,{min:1,max:2e3}).map((m,d)=>w(m,`${i}.destinations[${d}]`)))].sort();return{chainId:a,destinations:c}}).sort((o,s)=>BigInt(o.chainId)<BigInt(s.chainId)?-1:BigInt(o.chainId)>BigInt(s.chainId)?1:0);if(new Set(n.map(o=>o.chainId)).size!==n.length)throw new TypeError(`${t} has duplicate chainId rows`);if(n.some(o=>!r.includes(o.chainId))||r.some(o=>!n.some(s=>s.chainId===o)))throw new TypeError(`${t} must contain exactly one row for every allowed chain`);return n}function ct(e){if(v(e,"resolved policy input"),g(e,wr,"resolved policy input"),e.policyVersion!==1)throw new TypeError("resolved policy input.policyVersion must be 1");let r=[...new Set(E(e.allowedChainIds,"resolved policy input.allowedChainIds",{min:1,max:1e3}).map((i,a)=>R(i,`resolved policy input.allowedChainIds[${a}]`)))].sort((i,a)=>BigInt(i)<BigInt(a)?-1:BigInt(i)>BigInt(a)?1:0),t=ve(e.destinationAllowlist,r,"resolved policy input.destinationAllowlist"),n=null,o=null;if(e.grant!==null){if(n=q(e.grant),o=f(e.grant?.expiresAt,"resolved policy input.grant.expiresAt",{min:1})*1e3,!Number.isSafeInteger(o))throw new RangeError("resolved policy input grant expiry cannot be represented in milliseconds");let a=R(e.grant.chainId,"resolved policy input.grant.chainId");if(!r.includes(a))throw new Error("resolved policy input grant chain is not allowed")}let s={policyVersion:1,allowedChainIds:r,destinationAllowlist:t,maxValuePerTxWei:l(e.maxValuePerTxWei,"resolved policy input.maxValuePerTxWei"),maxDailyValueWei:l(e.maxDailyValueWei,"resolved policy input.maxDailyValueWei"),maxGasLimit:l(e.maxGasLimit,"resolved policy input.maxGasLimit",{positive:!0}),maxFeePerGasWei:l(e.maxFeePerGasWei,"resolved policy input.maxFeePerGasWei"),maxPriorityFeePerGasWei:l(e.maxPriorityFeePerGasWei,"resolved policy input.maxPriorityFeePerGasWei"),maxSlippageBps:f(e.maxSlippageBps,"resolved policy input.maxSlippageBps",{min:0,max:1e4}),expiresAtMs:f(e.expiresAtMs,"resolved policy input.expiresAtMs",{min:1}),grantId:n,grantExpiresAtMs:o};if(BigInt(s.maxValuePerTxWei)>BigInt(s.maxDailyValueWei))throw new RangeError("resolved policy per-transaction value cap exceeds daily cap");if(BigInt(s.maxPriorityFeePerGasWei)>BigInt(s.maxFeePerGasWei))throw new RangeError("resolved policy priority fee cap exceeds total fee cap");return b(s)}function Z(e){v(e,"resolved policy"),g(e,hr,"resolved policy");let r=e.grantId===null?null:y(e.grantId,"resolved policy.grantId"),t=T(e.grantExpiresAtMs,"resolved policy.grantExpiresAtMs");if(r===null!=(t===null))throw new TypeError("resolved policy grant id and expiry must both be null or present");let n=[...new Set(E(e.allowedChainIds,"resolved policy.allowedChainIds",{min:1,max:1e3}).map((s,i)=>R(s,`resolved policy.allowedChainIds[${i}]`)))].sort((s,i)=>BigInt(s)<BigInt(i)?-1:BigInt(s)>BigInt(i)?1:0),o={policyVersion:e.policyVersion,allowedChainIds:n,destinationAllowlist:ve(e.destinationAllowlist,n,"resolved policy.destinationAllowlist"),maxValuePerTxWei:l(e.maxValuePerTxWei,"resolved policy.maxValuePerTxWei"),maxDailyValueWei:l(e.maxDailyValueWei,"resolved policy.maxDailyValueWei"),maxGasLimit:l(e.maxGasLimit,"resolved policy.maxGasLimit",{positive:!0}),maxFeePerGasWei:l(e.maxFeePerGasWei,"resolved policy.maxFeePerGasWei"),maxPriorityFeePerGasWei:l(e.maxPriorityFeePerGasWei,"resolved policy.maxPriorityFeePerGasWei"),maxSlippageBps:f(e.maxSlippageBps,"resolved policy.maxSlippageBps",{min:0,max:1e4}),expiresAtMs:f(e.expiresAtMs,"resolved policy.expiresAtMs",{min:1}),grantId:r,grantExpiresAtMs:t};if(o.policyVersion!==1)throw new TypeError("resolved policy.policyVersion must be 1");if(BigInt(o.maxValuePerTxWei)>BigInt(o.maxDailyValueWei))throw new RangeError("resolved policy per-transaction value cap exceeds daily cap");if(BigInt(o.maxPriorityFeePerGasWei)>BigInt(o.maxFeePerGasWei))throw new RangeError("resolved policy priority fee cap exceeds total fee cap");return o}function Ie(e){return D(Z(e))}function $e(e,r){let t=`calls[${r}]`;g(e,Er,t);let n=jr(e.type,`${t}.type`),o=w(e.from,`${t}.from`),s=Br(e.accessList,`${t}.accessList`);if(n==="legacy"){if(e.maxFeePerGas!==null||e.maxPriorityFeePerGas!==null)throw new TypeError(`${t} legacy transactions bind gasPrice and leave eip1559 fees null`);if(s.length!==0)throw new TypeError(`${t} legacy transactions must use an empty accessList`);return{type:n,chainId:R(e.chainId,`${t}.chainId`),from:o,to:w(e.to,`${t}.to`),value:l(e.value,`${t}.value`),data:we(e.data,`${t}.data`),gasLimit:l(e.gasLimit,`${t}.gasLimit`,{positive:!0}),gasPrice:l(e.gasPrice,`${t}.gasPrice`),maxFeePerGas:null,maxPriorityFeePerGas:null,accessList:s,nonce:l(e.nonce,`${t}.nonce`)}}if(e.gasPrice!==null)throw new TypeError(`${t} typed transactions bind eip1559 fees and leave gasPrice null`);if(n==="eip1559"&&s.length!==0)throw new TypeError(`${t} eip1559 transactions must use an empty accessList; use eip2930 to bind accessList`);let i=l(e.maxFeePerGas,`${t}.maxFeePerGas`),a=l(e.maxPriorityFeePerGas,`${t}.maxPriorityFeePerGas`);if(BigInt(a)>BigInt(i))throw new RangeError(`${t} priority fee exceeds max fee`);return{type:n,chainId:R(e.chainId,`${t}.chainId`),from:o,to:w(e.to,`${t}.to`),value:l(e.value,`${t}.value`),data:we(e.data,`${t}.data`),gasLimit:l(e.gasLimit,`${t}.gasLimit`,{positive:!0}),gasPrice:null,maxFeePerGas:i,maxPriorityFeePerGas:a,accessList:s,nonce:l(e.nonce,`${t}.nonce`)}}function Q(e,r,t){let n=w(r,t);for(let[o,s]of e.entries())if(s.from!==n)throw new Error(`${t} does not match calls[${o}].from`);return n}function Se(e){g(e,Ar,"route");let r={provider:h(e.provider,"route.provider",128),venue:w(e.venue,"route.venue"),routeId:h(e.routeId,"route.routeId",512)};return{...r,routeDigest:D(r)}}function Pe(e){g(e,br,"route");let{routeDigest:r,...t}=e,n=Se(t);if(y(r,"route.routeDigest")!==n.routeDigest)throw new Error("route digest mismatch");return n}function Fr(e){return{quoteId:e.quoteId===null?null:h(e.quoteId,"quote.quoteId",512),account:w(e.account,"quote.account"),recipient:w(e.recipient,"quote.recipient"),assetIn:w(e.assetIn,"quote.assetIn"),assetOut:w(e.assetOut,"quote.assetOut"),amountIn:l(e.amountIn,"quote.amountIn"),amountOut:l(e.amountOut,"quote.amountOut"),minAmountOut:l(e.minAmountOut,"quote.minAmountOut"),slippageBps:f(e.slippageBps,"quote.slippageBps",{min:0,max:1e4}),slippageGuardDigest:y(e.slippageGuardDigest,"quote.slippageGuardDigest")}}function Me(e){g(e,Ae,"quote");let r=Fr(e);if(BigInt(r.minAmountOut)>BigInt(r.amountOut))throw new RangeError("quote.minAmountOut exceeds quote.amountOut");return{...r,quoteDigest:D(r)}}function _e(e){g(e,vr,"quote");let{quoteDigest:r,...t}=e,n=Me(t);if(y(r,"quote.quoteDigest")!==n.quoteDigest)throw new Error("quote digest mismatch");return n}function Oe(e){if(g(e,Ir,"simulation"),h(e.status,"simulation.status",32).toLowerCase()!=="success")throw new Error(`simulation status ${JSON.stringify(e.status)} is not successful`);if(e.stateOverridesDigest!==null)throw new Error("mainnet approval refuses simulation state overrides");if(typeof e.blockHash!="string"||!fr.test(e.blockHash.toLowerCase()))throw new TypeError("simulation.blockHash must be a 32-byte block hash");return{engine:h(e.engine,"simulation.engine",128),status:"success",blockNumber:l(e.blockNumber,"simulation.blockNumber",{positive:!0}),blockHash:e.blockHash.toLowerCase(),stateOverridesDigest:null,balanceDeltasDigest:y(e.balanceDeltasDigest,"simulation.balanceDeltasDigest"),logsDigest:y(e.logsDigest,"simulation.logsDigest")}}function Ne(e,r,t){let o={balanceAtLeast:["account","asset"],balanceAtMost:["account","asset"],allowanceEquals:["account","asset","spender"],ownerOf:["collection","tokenId"],positionSizeAtMost:["account","asset"],noNewApproval:["account","allowedSpender"]}[e];if(!o)throw new TypeError(`${t} kind is unsupported`);g(r,o,`${t}.subject`);let s={};for(let i of o)s[i]=i==="tokenId"?l(r[i],`${t}.subject.${i}`):w(r[i],`${t}.subject.${i}`);return s}function Te(e,r){let t=`postconditions[${r}]`;g(e,["comparator","kind","subject","value"],t);let n=h(e.kind,`${t}.kind`,64),o={balanceAtLeast:"gte",balanceAtMost:"lte",allowanceEquals:"eq",ownerOf:"eq",positionSizeAtMost:"lte",noNewApproval:"eq"};if(!(n in o))throw new TypeError(`${t}.kind is unsupported`);if(e.comparator!==o[n])throw new TypeError(`${t}.comparator must be ${o[n]} for ${n}`);let s;if(n==="ownerOf")s=w(e.value,`${t}.value`);else if(n==="noNewApproval"){if(e.value!=="true")throw new TypeError(`${t}.value must be the string "true"`);s="true"}else s=l(e.value,`${t}.value`);return{kind:n,subject:Ne(n,e.subject,t),comparator:o[n],value:s}}function _(e,r){return e.some(r)}function Re(e,r,t,n){let o=(s,i)=>s===i;if(e==="evm-swap"){if(!_(r,s=>s.kind==="balanceAtLeast"&&o(s.subject.account,t.recipient)&&o(s.subject.asset,t.assetOut)&&BigInt(s.value)>=BigInt(t.minAmountOut)))throw new Error("evm-swap requires balanceAtLeast(recipient, assetOut, minAmountOut)");if(!_(r,s=>s.kind==="noNewApproval"&&o(s.subject.account,t.account)&&o(s.subject.allowedSpender,n.venue)))throw new Error("evm-swap requires noNewApproval(account, route venue)")}else if(e==="evm-approval"){if(!_(r,s=>s.kind==="allowanceEquals"&&o(s.subject.account,t.account)))throw new Error("evm-approval requires allowanceEquals(account, spender, exactAmount)")}else if(e==="evm-transfer"){if(!_(r,s=>s.kind==="balanceAtLeast"&&o(s.subject.account,t.recipient)&&o(s.subject.asset,t.assetOut)))throw new Error("evm-transfer requires balanceAtLeast(recipient, asset, amount)")}else if(e==="evm-bridge"){if(!_(r,s=>s.kind==="balanceAtMost"&&o(s.subject.account,t.account)&&o(s.subject.asset,t.assetIn)))throw new Error("evm-bridge requires source balanceAtMost(account, assetIn, bound)")}else if(e==="nft-mint"&&!_(r,s=>s.kind==="ownerOf"||s.kind==="balanceAtLeast"&&o(s.subject.account,t.account)&&o(s.subject.asset,t.assetOut)))throw new Error("nft-mint requires ownerOf or balanceAtLeast ownership evidence")}function Lr(e,r){if(X(e,"prepare"),e.requiresUserSignature!==!0||e.signingReady!==!1||e.broadcastReady!==!1||e.executionReady!==!1||e.oraclePrepared!==!0)throw new Error("prepare must be custody-none, user-signature-required, and prepare-only");if(!Number.isSafeInteger(e.preparedAt)||!Number.isSafeInteger(e.expiresAt))throw new TypeError("prepare timestamps must be safe integers");if(G(e)!==e.prepareHash)throw new Error("prepareHash mismatch");return re(e,{nowMs:r,maxAgeMs:V(k),label:"approval binding"}),e}function F(e,{input:r=!1,nowMs:t}={}){if(g(e,r?be:$r,"preview"),e.previewVersion!==C)throw new TypeError(`preview.previewVersion must be ${C}`);let n=f(t,"nowMs",{min:1}),o=f(e.builtAtMs,"preview.builtAtMs",{min:1}),s=f(e.expiresAtMs,"preview.expiresAtMs",{min:1});if(o>n+5e3)throw new Error("preview was built in the future");z({issuedAtMs:o,expiresAtMs:s},n,"approval preview");let i=Lr(e.prepare,n);if(s>i.expiresAt)throw new Error("preview expiry cannot exceed prepare expiry");let a=h(e.surface,"preview.surface",64);if(!Ee.has(a))throw new TypeError(`preview.surface ${JSON.stringify(a)} is unsupported`);let c=E(e.calls,"preview.calls",{min:1,max:256}).map($e);Q(c,c[0].from,"preview.calls[0].from");let m=r?Se(e.route):Pe(e.route),d=r?Me(e.quote):_e(e.quote),p=Oe(e.simulation),u=E(e.postconditions,"preview.postconditions",{min:1,max:256}).map(Te);if(Re(a,u,d,m),m.provider!==i.provider)throw new Error("preview route provider does not match prepare provider");let x={previewVersion:C,previewId:h(e.previewId,"preview.previewId",512),builtAtMs:o,expiresAtMs:s,surface:a,calls:c,route:m,quote:d,simulation:p,postconditions:u,prepare:i,policyDigest:y(e.policyDigest,"preview.policyDigest"),custody:e.custody,execution:e.execution};if(x.custody!=="none"||x.execution!=="prepare-only")throw new Error("preview must declare custody none and execution prepare-only");return x}function pt(e,{nowMs:r}={}){v(e,"preview input");let t=F(e,{input:!0,nowMs:r});return b({...t,previewHash:D(t)})}function Gr(e,{nowMs:r}={}){v(e,"preview");let t=F(e,{nowMs:r});return D(t)}function De(e,{nowMs:r}={}){let t=Gr(e,{nowMs:r});if(!A(e.previewHash,t))throw new Error("previewHash mismatch");return!0}function ke(e,r){let t=new Map(r.destinationAllowlist.map(n=>[n.chainId,new Set(n.destinations)]));for(let n of e.calls){if(!r.allowedChainIds.includes(n.chainId))throw new Error(`policy mismatch: chain ${n.chainId} is not allowed`);if(!t.get(n.chainId)?.has(n.to))throw new Error(`policy mismatch: destination ${n.to} is not allowed on chain ${n.chainId}`);if(BigInt(n.value)>BigInt(r.maxValuePerTxWei))throw new Error("policy mismatch: transaction value exceeds cap");if(BigInt(n.gasLimit)>BigInt(r.maxGasLimit))throw new Error("policy mismatch: gas limit exceeds cap");let o=n.type==="legacy"?n.gasPrice:n.maxFeePerGas,s=n.type==="legacy"?"0":n.maxPriorityFeePerGas;if(BigInt(o)>BigInt(r.maxFeePerGasWei))throw new Error("policy mismatch: max fee exceeds cap");if(BigInt(s)>BigInt(r.maxPriorityFeePerGasWei))throw new Error("policy mismatch: priority fee exceeds cap")}if(!e.calls.some(n=>t.get(n.chainId)?.has(e.route.venue)))throw new Error("policy mismatch: route venue was not in the consulted destination allowlist");if(e.quote.slippageBps>r.maxSlippageBps)throw new Error("policy mismatch: quote slippage exceeds ceiling")}function zr(e){return g(e,Pr,"binding.expiryBounds"),{issuedAtMs:f(e.issuedAtMs,"binding.expiryBounds.issuedAtMs",{min:1}),previewExpiresAtMs:f(e.previewExpiresAtMs,"binding.expiryBounds.previewExpiresAtMs",{min:1}),prepareExpiresAtMs:f(e.prepareExpiresAtMs,"binding.expiryBounds.prepareExpiresAtMs",{min:1}),grantExpiresAtMs:T(e.grantExpiresAtMs,"binding.expiryBounds.grantExpiresAtMs"),sessionExpiresAtMs:T(e.sessionExpiresAtMs,"binding.expiryBounds.sessionExpiresAtMs"),policyExpiresAtMs:f(e.policyExpiresAtMs,"binding.expiryBounds.policyExpiresAtMs",{min:1}),approvalTtlMs:f(e.approvalTtlMs,"binding.expiryBounds.approvalTtlMs",{min:1,max:ye}),requestedExpiresAtMs:T(e.requestedExpiresAtMs,"binding.expiryBounds.requestedExpiresAtMs")}}function Ve(e){let r=[e.previewExpiresAtMs,e.prepareExpiresAtMs,e.grantExpiresAtMs,e.sessionExpiresAtMs,e.policyExpiresAtMs,e.issuedAtMs+e.approvalTtlMs,e.requestedExpiresAtMs].filter(t=>t!==null);return Math.min(...r)}function I(e){if(v(e,"approval binding"),g(e,Mr,"approval binding"),e.bindingVersion!==O)throw new TypeError(`approval binding.bindingVersion must be ${O}`);if(e.custody!=="none"||e.execution!=="prepare-only")throw new Error("approval binding must be custody-none and prepare-only");if(e.maxExecutions!==1||e.oneShot!==!0)throw new Error("approval binding must be one-shot with maxExecutions 1");if(e.schemaVersion!==W)throw new TypeError("approval binding.schemaVersion mismatch");if(e.buildVersion!==H)throw new TypeError("approval binding.buildVersion mismatch");if(e.domainSeparator!==K)throw new TypeError("approval binding.domainSeparator mismatch");let r=h(e.surface,"approval binding.surface",64);if(!Ee.has(r))throw new TypeError("approval binding surface is unsupported");let t=J(e.tenantId,"approval binding.tenantId"),n=E(e.calls,"approval binding.calls",{min:1,max:256}).map($e),o=Q(n,e.expectedFrom,"approval binding.expectedFrom"),s=w(e.expectedSigner,"approval binding.expectedSigner");if(s!==o)throw new Error("approval binding expectedSigner must equal expectedFrom");let i=Pe(e.route),a=_e(e.quote),c=Oe(e.simulation),m=E(e.postconditions,"approval binding.postconditions",{min:1,max:256}).map(Te);Re(r,m,a,i);let d=zr(e.expiryBounds),p=f(e.expiresAtMs,"approval binding.expiresAtMs",{min:1});if(p!==Ve(d))throw new Error("approval binding expiry does not equal composed minimum ceiling");return{bindingVersion:O,schemaVersion:W,buildVersion:H,domainSeparator:K,tenantId:t,previewId:h(e.previewId,"approval binding.previewId",512),previewHash:y(e.previewHash,"approval binding.previewHash"),prepareHash:y(e.prepareHash,"approval binding.prepareHash"),custody:"none",execution:"prepare-only",surface:r,expectedFrom:o,expectedSigner:s,calls:n,route:i,quote:a,simulation:c,policyDigest:y(e.policyDigest,"approval binding.policyDigest"),postconditions:m,expiryBounds:d,expiresAtMs:p,oneShot:!0,maxExecutions:1}}function ut(e){if(v(e,"approval binding input"),g(e,Sr,"approval binding input"),e.bindingVersion!==O)throw new TypeError(`approval binding input.bindingVersion must be ${O}`);let r=f(e.nowMs,"approval binding input.nowMs",{min:1}),t=f(e.issuedAtMs,"approval binding input.issuedAtMs",{min:1});if(t>r+5e3)throw new Error("approval binding issuance is in the future");De(e.preview,{nowMs:r});let n=F(e.preview,{nowMs:r}),o=Z(e.resolvedPolicy),s=Ie(o);if(!A(n.policyDigest,s))throw new Error("policy mismatch: preview policy digest is stale");if(o.expiresAtMs<=r||o.grantExpiresAtMs!==null&&o.grantExpiresAtMs<=r)throw new Error("resolved policy or grant is expired");let i=T(e.sessionExpiresAtMs,"approval binding input.sessionExpiresAtMs");if(i!==null&&i<=r)throw new Error("approval session is expired");ke(n,o);let a=J(e.tenantId,"approval binding input.tenantId"),c=w(e.expectedSigner,"approval binding input.expectedSigner"),m=Q(n.calls,c,"approval binding input.expectedSigner"),d=e.approvalTtlMs===null?he:f(e.approvalTtlMs,"approval binding input.approvalTtlMs",{min:1});d=Math.min(d,ye,V(d));let p={issuedAtMs:t,previewExpiresAtMs:n.expiresAtMs,prepareExpiresAtMs:n.prepare.expiresAt,grantExpiresAtMs:o.grantExpiresAtMs,sessionExpiresAtMs:i,policyExpiresAtMs:o.expiresAtMs,approvalTtlMs:d,requestedExpiresAtMs:T(e.requestedExpiresAtMs,"approval binding input.requestedExpiresAtMs")},u=Ve(p);if(u<=r||u<=t)throw new Error("approval binding inputs are expired or leave no execution window");let x={bindingVersion:O,schemaVersion:W,buildVersion:H,domainSeparator:K,tenantId:a,previewId:n.previewId,previewHash:e.preview.previewHash,prepareHash:n.prepare.prepareHash,custody:"none",execution:"prepare-only",surface:n.surface,expectedFrom:m,expectedSigner:c,calls:n.calls,route:n.route,quote:n.quote,simulation:n.simulation,policyDigest:s,postconditions:n.postconditions,expiryBounds:p,expiresAtMs:u,oneShot:!0,maxExecutions:1};return b(I(x))}function j(e){return D(I(e))}function A(e,r){if(typeof e!="string"||typeof r!="string"||!Y.test(e)||!Y.test(r))return!1;let t=Buffer.from(e,"hex"),n=Buffer.from(r,"hex");return t.length!==n.length?!1:nr(t,n)}function lt(e,r){return A(e,r)}function Be(e){g(e,Nr,"approver");let r=h(e.kind,"approver.kind",32);if(!cr.has(r))throw new TypeError("approver.kind is unsupported");return{kind:r,ref:h(e.ref,"approver.ref",512)}}function dt(e){if(v(e,"approval request input"),g(e,_r,"approval request input"),e.approvalVersion!==N)throw new TypeError(`approval request input.approvalVersion must be ${N}`);if(e.oneShot!==!0||e.maxExecutions!==1)throw new Error("approval request must be one-shot with maxExecutions 1");let r=I(e.binding),t=f(e.issuedAtMs,"approval request input.issuedAtMs",{min:1});if(t!==r.expiryBounds.issuedAtMs)throw new Error("approval request issuance does not match bound issuance");let n=j(r),o={approvalVersion:N,approvalId:n,previewId:r.previewId,approvalDigest:n,binding:r,issuedAtMs:t,expiresAtMs:r.expiresAtMs,approver:Be(e.approver),oneShot:!0,maxExecutions:1,custody:"none",execution:"prepare-only"};return b(o)}function qr(e){if(v(e,"approval request"),g(e,Or,"approval request"),e.approvalVersion!==N)throw new TypeError(`approval request.approvalVersion must be ${N}`);if(e.oneShot!==!0||e.maxExecutions!==1)throw new Error("approval request must be one-shot with maxExecutions 1");if(e.custody!=="none"||e.execution!=="prepare-only")throw new Error("approval request must be custody-none and prepare-only");let r=I(e.binding),t={approvalVersion:N,approvalId:y(e.approvalId,"approval request.approvalId"),previewId:h(e.previewId,"approval request.previewId",512),approvalDigest:y(e.approvalDigest,"approval request.approvalDigest"),binding:r,issuedAtMs:f(e.issuedAtMs,"approval request.issuedAtMs",{min:1}),expiresAtMs:f(e.expiresAtMs,"approval request.expiresAtMs",{min:1}),approver:Be(e.approver),oneShot:!0,maxExecutions:1,custody:"none",execution:"prepare-only"};if(t.previewId!==r.previewId||t.expiresAtMs!==r.expiresAtMs||t.issuedAtMs!==r.expiryBounds.issuedAtMs)throw new Error("approval request does not match its binding");return t}function ft(e,r){v(r,"approval verification context"),g(r,Tr,"approval verification context");let t=qr(e),n=f(r.nowMs,"approval verification context.nowMs",{min:1});if(z(t,n,"approval request"),n>=t.expiresAtMs)throw new Error("approval request expired");if(f(r.executionCount,"approval verification context.executionCount",{min:0})!==0)throw new Error("one-shot approval was already used");if(J(r.tenantId,"approval verification context.tenantId")!==t.binding.tenantId)throw new Error("approval tenant mismatch");if(w(r.expectedFrom,"approval verification context.expectedFrom")!==t.binding.expectedFrom)throw new Error("approval expectedFrom mismatch");let a=j(t.binding);if(!A(t.approvalDigest,a)||!A(t.approvalId,a)||!A(r.expectedApprovalDigest,a))throw new Error("approval digest mismatch");if(De(r.preview,{nowMs:n}),!A(r.preview.previewHash,t.binding.previewHash)||r.preview.previewId!==t.previewId||!A(r.preview.prepare.prepareHash,t.binding.prepareHash))throw new Error("approval preview mismatch");let c=F(r.preview,{nowMs:n}),m={surface:t.binding.surface,calls:t.binding.calls,route:t.binding.route,quote:t.binding.quote,simulation:t.binding.simulation,policyDigest:t.binding.policyDigest,postconditions:t.binding.postconditions},d={surface:c.surface,calls:c.calls,route:c.route,quote:c.quote,simulation:c.simulation,policyDigest:c.policyDigest,postconditions:c.postconditions};if(P(m)!==P(d))throw new Error("approval preview evidence mismatch");let p=Z(r.resolvedPolicy),u=Ie(p);if(!A(u,t.binding.policyDigest))throw new Error("approval policy mismatch");if(p.expiresAtMs<=n||p.grantExpiresAtMs!==null&&p.grantExpiresAtMs<=n)throw new Error("approval policy expired");return ke(c,p),b(t)}function Cr(e,r,t){if(e.kind==="ownerOf")return w(r,t);if(e.kind==="noNewApproval"){if(r!=="true"&&r!=="false")throw new TypeError(`${t} must be "true" or "false"`);return r}return l(r,t)}function mt(e){let r=I(e),t=r.calls[0],n=t.type==="legacy"?`gasPrice ${t.gasPrice}`:`maxFeePerGas ${t.maxFeePerGas} maxPriorityFeePerGas ${t.maxPriorityFeePerGas}`;return b({schemaVersion:r.schemaVersion,buildVersion:r.buildVersion,domainSeparator:r.domainSeparator,tenantId:r.tenantId,surface:r.surface,expectedFrom:r.expectedFrom,expectedSigner:r.expectedSigner,oneShot:r.oneShot,maxExecutions:r.maxExecutions,expiresAtMs:r.expiresAtMs,calls:r.calls.map(o=>({type:o.type,chainId:o.chainId,from:o.from,to:o.to,value:o.value,data:o.data,nonce:o.nonce,gasLimit:o.gasLimit,gasPrice:o.gasPrice,maxFeePerGas:o.maxFeePerGas,maxPriorityFeePerGas:o.maxPriorityFeePerGas,accessList:o.accessList})),route:r.route,quote:r.quote,simulation:r.simulation,postconditions:r.postconditions,summary:[`${r.surface} for tenant ${r.tenantId}`,`from ${r.expectedFrom} type ${t.type} nonce ${t.nonce} ${n}`,`to ${t.to} value ${t.value} data ${t.data}`,`expiresAtMs ${r.expiresAtMs} oneShot ${r.oneShot} maxExecutions ${r.maxExecutions}`].join(" | ")})}function gt(e,r){let t=I(e),n=I(r);if(t.tenantId!==n.tenantId)throw new Error("replacement tenant mismatch");if(t.expectedFrom!==n.expectedFrom)throw new Error("replacement expectedFrom mismatch");if(t.calls.length!==n.calls.length)throw new Error("replacement call count mismatch");for(let[i,a]of t.calls.entries()){let c=n.calls[i];if(a.chainId!==c.chainId||a.from!==c.from||a.nonce!==c.nonce)throw new Error(`replacement calls[${i}] is a different EVM identity, not a fee replacement`)}let o=j(t),s=j(n);if(A(o,s))throw new Error("replacement must produce a new approval digest");return b({originalDigest:o,replacementDigest:s})}function xt(e,r){let t=I(e),n=E(r,"observations",{min:0,max:1e3}).map((s,i)=>{let a=`observations[${i}]`;g(s,["kind","subject","value"],a);let c=t.postconditions.find(m=>m.kind===s.kind&&P(m.subject)===P(s.subject));if(!c)throw new Error(`${a} is not bound by an approval postcondition`);return{kind:c.kind,subject:Ne(c.kind,s.subject,a),value:Cr(c,s.value,`${a}.value`)}}),o=t.postconditions.map(s=>{let i=n.find(c=>c.kind===s.kind&&P(c.subject)===P(s.subject)),a=!1;return i&&(s.comparator==="eq"?a=i.value===s.value:s.comparator==="gte"?a=BigInt(i.value)>=BigInt(s.value):s.comparator==="lte"&&(a=BigInt(i.value)<=BigInt(s.value))),{condition:s,observedValue:i?.value??null,pass:a}});return b({status:o.every(s=>s.pass)?"final":"failed",results:o})}export{at as APPROVAL_BINDING_POSTURE,O as APPROVAL_BINDING_VERSION,H as APPROVAL_BUILD_VERSION,he as APPROVAL_DEFAULT_TTL_MS,K as APPROVAL_DOMAIN_SEPARATOR,ye as APPROVAL_MAX_TTL_MS,C as APPROVAL_PREVIEW_VERSION,N as APPROVAL_REQUEST_VERSION,W as APPROVAL_SCHEMA_VERSION,or as APPROVAL_SURFACES,sr as APPROVAL_TX_TYPES,ir as APPROVAL_UNSUPPORTED_TX_TYPES,S as SecretLeakError,lt as approvalDigestsEqual,De as assertApprovalPreview,gt as assertReplacementRequiresNewDigest,P as canonicalApprovalJson,j as computeApprovalDigest,Ie as computeApprovalPolicyDigest,Gr as computeApprovalPreviewHash,ut as createApprovalBinding,pt as createApprovalPreview,dt as createApprovalRequest,ct as createResolvedApprovalPolicy,xt as evaluateApprovalPostconditions,mt as renderApprovalReview,ft as verifyApprovalRequest};
@@ -0,0 +1 @@
1
+ import{wordlists as C}from"ethers";var D=Object.freeze(["chainId","agentAddress","accountAddress","actions","targets","maxValueWei","maxGasWei","maxSlippageBps","expiresAt","nonce","revocationKey"]),F=Object.freeze(["read","simulate"]);var U=1440*60;var a=class extends Error{constructor(t,r){super(`secret material must never appear in a public API object (at ${t}, rule: ${r})`),this.name="SecretLeakError",this.path=t,this.rule=r}},N=/(private[_-]?key|secret|bearer|keystore|mnemonic|seed[_-]?phrase|passphrase|password|api[_-]?key|access[_-]?token|auth[_-]?token|session[_-]?token|signer[_-]?url|signature)/i,S=Object.freeze(["privkey","wif","xprv","seed"]);function y(e){let t=String(e),r=t.toLowerCase().replace(/[\s._-]+/g,"");return N.test(t)||S.includes(r)}var b=Object.freeze([{rule:"raw-32-byte-hex-key",re:/^0x[0-9a-fA-F]{64}$/},{rule:"raw-32-byte-hex-bare",re:/^[0-9a-fA-F]{64}$/},{rule:"extended-private-key",re:/\b(?:xprv|tprv|yprv|zprv)[1-9A-HJ-NP-Za-km-z]{107}\b/},{rule:"bitcoin-wif",re:/\b[59KLc][1-9A-HJ-NP-Za-km-z]{50,51}\b/},{rule:"bip39-mnemonic",re:/\b(?:[a-z]{3,8}\s+){11,23}[a-z]{3,8}\b/},{rule:"bearer-token",re:/bearer\s+[A-Za-z0-9._~+/=-]+/i},{rule:"pem-private-key",re:/-----BEGIN[A-Z ]*PRIVATE KEY-----/},{rule:"keystore-path",re:/keystore/i},{rule:"signer-url",re:/https?:\/\/\S*sign/i},{rule:"authorization-header",re:/authorization\s*:/i}]),w=Object.freeze(["grantid","id","hash","sha256","sha256hex","checksum","txhash","transactionhash","blockhash","digest","userophash","commithash","prevhash","intenthash","canonicalhash","payloadhash","requestid"]);function I(e){return e.replace(/"([A-Za-z0-9_-]+)"\s*:\s*"(?:0x)?([0-9a-fA-F]{64})"/g,(t,r)=>w.includes(String(r).toLowerCase().replace(/[_-]/g,""))?`"${r}":"<hex64>"`:t)}function x(e){let t;try{t=JSON.stringify(e)}catch(n){throw new a("$",`unserializable-payload: ${String(n?.message||n)}`)}if(t===void 0)return"null";let r=I(t);for(let{rule:n,re:i}of b)if(i.test(r))throw new a("$<serialized>",n);if(/(?:^|[^0-9a-fA-Fx])0x[0-9a-fA-F]{64}(?![0-9a-fA-F])/.test(r))throw new a("$<serialized>","raw-32-byte-hex-embedded");return JSON.parse(t,(n,i)=>{if(n&&y(n))throw new a(`$<serialized>.${n}`,"forbidden-key-name");return i}),t}function c(e,t="$",r=new Set,o=""){if(e==null)return e;if(typeof e=="string"){let n=w.includes(String(o).toLowerCase().replace(/[_-]/g,""));for(let{rule:i,re:l}of b)if(!(n&&i.startsWith("raw-32-byte-hex"))&&l.test(e))throw new a(t,i);return e}if(typeof e!="object"||r.has(e)||(r.add(e),ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e;if(e instanceof Map){for(let[n,i]of e.entries()){if(typeof n=="string"&&y(n))throw new a(`${t}[${JSON.stringify(n)}]`,"forbidden-key-name");c(n,`${t}[key]`,r),c(i,`${t}[${String(n)}]`,r)}return e}if(e instanceof Set){let n=0;for(let i of e.values())c(i,`${t}[${n++}]`,r);return e}if(Array.isArray(e))return e.forEach((n,i)=>c(n,`${t}[${i}]`,r)),e;for(let[n,i]of Object.entries(e)){if(y(n))throw new a(`${t}.${n}`,"forbidden-key-name");c(i,`${t}.${n}`,r,n)}return e}var _=/[\u0000-\u001f\u007f]/;function m(e,t){if(!e||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)throw new TypeError(`${t} must be a plain object`);return e}function h(e,t="control input"){try{c(e,t),x(e)}catch(r){throw new TypeError(`${t} contains secret or custody material: ${r.message}`)}return e}function u(e,{required:t=[],optional:r=[]}={},o="object"){m(e,o);let n=new Set([...t,...r]),i=Object.keys(e).filter(l=>!n.has(l));if(i.length)throw new TypeError(`${o} has unknown field ${i[0]}`);for(let l of t)if(!Object.hasOwn(e,l))throw new TypeError(`${o}.${l} is required`);return e}function g(e,t,r=200,{lower:o=!1}={}){if(typeof e!="string"||!e.trim()||e.length>r||_.test(e))throw new TypeError(`${t} must be non-empty control-free text up to ${r} characters`);let n=e.trim();return o?n.toLowerCase():n}function d(e,t,r=80){let o=g(e,t,r,{lower:!0});if(!/^[a-z0-9][a-z0-9._:-]*$/.test(o))throw new TypeError(`${t} must be a lowercase identifier`);return o}function p(e,t,{positive:r=!1}={}){if(!Number.isSafeInteger(e)||e<0||r&&e===0)throw new TypeError(`${t} must be a ${r?"positive":"non-negative"} safe integer`);return e}function s(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))s(t);Object.freeze(e)}return e}var O=Object.freeze(["confirmations","finalizedTag","checkpoint"]),f=Object.freeze({UNKNOWN:"UNKNOWN",INCLUDED:"INCLUDED",FINAL:"FINAL"}),T=Object.freeze(["LIVE","STALE","UNKNOWN","UNAVAILABLE"]);function A({family:e,chainId:t},r="chain"){let o=d(e,`${r}.family`,40),n;if(o==="evm"){if(typeof t=="number")n=String(p(t,`${r}.chainId`,{positive:!0}));else if(n=g(t,`${r}.chainId`,40),!/^[1-9][0-9]*$/.test(n))throw new TypeError(`${r}.chainId must be a positive decimal EVM chain id`)}else n=d(t,`${r}.chainId`,80);return{family:o,chainId:n}}function z(e,t="chain"){return u(e,{required:["family","chainId"]},t),s(A(e,t))}function E(e,t="finality rule"){h(e,t),m(e,t);let r=e.rule;if(!O.includes(r))throw new TypeError(`${t}.rule must be confirmations, finalizedTag, or checkpoint`);let o=r==="confirmations"?"confirmations":r;u(e,{required:["family","chainId","rule",o]},t);let n=A(e,t);return r==="confirmations"?{...n,rule:r,confirmations:p(e.confirmations,`${t}.confirmations`,{positive:!0})}:{...n,rule:r,[o]:d(e[o],`${t}.${o}`,80)}}function $(e){if(!Array.isArray(e))throw new TypeError("finality policy rules must be an array");let t=e.map((o,n)=>E(o,`finality policy rule ${n}`)),r=new Set;for(let o of t){let n=`${o.family}\0${o.chainId}`;if(r.has(n))throw new TypeError(`duplicate finality rule for ${o.family}:${o.chainId}`);r.add(n)}return s({policyVersion:1,rules:t})}var v=$;function k(e){if(u(e,{required:["policyVersion","rules"]},"finality policy"),e.policyVersion!==1||!Array.isArray(e.rules))throw new TypeError("unsupported finality policy");return $(e.rules)}function ee(e,t){let r=z(t,"finality query"),n=k(e).rules.find(i=>i.family===r.family&&i.chainId===r.chainId);return n?s({status:"KNOWN",...r,rule:n}):s({status:f.UNKNOWN,reason:"MISSING_FINALITY_RULE",...r,rule:null})}function R(e,t){if(e==null)return null;h(e,"finality evidence");let r=t.rule==="confirmations"?"confirmations":t.rule;if(u(e,{required:["status"],optional:[r]},"finality evidence"),!T.includes(e.status))throw new TypeError("finality evidence.status is unknown");let o={status:e.status};return e[r]!=null&&(o[r]=t.rule==="confirmations"?p(e.confirmations,"finality evidence.confirmations",{positive:!0}):d(e[r],`finality evidence.${r}`,80)),o}function te(e,t){if(!e||e.status===f.UNKNOWN||e.rule==null)return s({status:f.UNKNOWN,final:!1,reason:"MISSING_FINALITY_RULE"});let r=E(e.rule??e,"resolved finality rule"),o=R(t,r);if(o==null)return s({status:f.UNKNOWN,final:!1,reason:"MISSING_FINALITY_EVIDENCE"});if(o.status!=="LIVE")return s({status:f.UNKNOWN,final:!1,reason:`${o.status}_EVIDENCE`});let n=!1;return r.rule==="confirmations"?n=o.confirmations!=null&&o.confirmations>=r.confirmations:r.rule==="finalizedTag"?n=o.finalizedTag===r.finalizedTag:n=o.checkpoint===r.checkpoint,s({status:n?f.FINAL:f.INCLUDED,final:n,reason:n?"PINNED_RULE_SATISFIED":"PINNED_RULE_NOT_SATISFIED",rule:r})}export{T as FINALITY_EVIDENCE_STATUSES,O as FINALITY_RULE_TYPES,f as FINALITY_STATUSES,v as createFinalityPolicy,$ as defineFinalityPolicy,te as evaluateFinality,z as normalizeChainReference,ee as resolveFinalityRule};
@@ -0,0 +1,6 @@
1
+ import{createHash as $t}from"node:crypto";import{wordlists as vt}from"ethers";import{wordlists as kt}from"ethers";var Et=new Set(["privatekey","privkey","secretkey","seedphrase","seed","mnemonic","passphrase","password","keystore","keymaterial","wif","xprv","xpriv","bearer","authorization","signature","apikey","credential"]),gt=[/\b[5KL][1-9A-HJ-NP-Za-km-z]{50,51}\b/,/\bxprv[0-9A-Za-z]{50,}\b/],bt=new Set([12,15,18,21,24]);function At(e){let t=String(e).trim().toLowerCase().split(/\s+/).filter(Boolean);return bt.has(t.length)&&t.every(n=>kt.en.getWordIndex(n)>=0)}var It=/^\s*(?:0x)?[0-9a-fA-F]{64}\s*$/,St=/(hash|digest|root|salt|nonce|proof|commitment|sig|id)(?:e?s)?$/i,xt=new Set(["calldata","data","publickey","pubkey","message","payload","input","extradata"]);function Ot(e){let t=Te(e);return xt.has(t)||St.test(t)}var B=class extends Error{constructor(t){super(`action receipt refused: secret-bearing field at ${t}`),this.name="ActionReceiptSecretError",this.code="ACTION_RECEIPT_SECRET"}};function Te(e){return String(e).replace(/[^a-z0-9]/gi,"").toLowerCase()}function _t(e){let t=Te(e);return[...Et].some(n=>t.includes(n))}function Rt(e,t,n){if(typeof t=="string"){if(gt.some(r=>r.test(t))||At(t))throw new B(n);if(It.test(t)&&!Ot(e))throw new B(n)}}function pe(e,t="$",n=""){if(e==null||typeof e=="boolean")return e;if(typeof e=="string")return Rt(n,e,t),e;if(typeof e=="number"){if(!Number.isFinite(e))throw new TypeError(`action receipt: non-finite number at ${t}`);return e}if(typeof e=="bigint")return e.toString();if(Array.isArray(e))return e.map((o,i)=>pe(o,`${t}[${i}]`,n));if(typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype)throw new TypeError(`action receipt: JSON-like value required at ${t}`);let r={};for(let o of Object.keys(e).sort()){let i=`${t}.${o}`;if(_t(o))throw new B(i);e[o]!==void 0&&(r[o]=pe(e[o],i,o))}return r}function Ce(e){return pe(e)}var D="oracle.control-plane/1",_="0.28.26+control-plane.1",K=64*1024,We=32,Nt=32*1024,Lt=2e3,Ht=512,Tt=/^(?:0|[1-9][0-9]*)$/,Ct=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,199}$/,Pt=/^[a-f0-9]{64}$/,Wt=/(?:amount|quantity|value|notional|balance|price|fee|gas|slippage|bps|basispoints|limit|maximum|minimum|cap|allowance|decimals|confirmations|executions|sequence|count)(?:$|[A-Z_])/i,zt=/^\s*(?:0x)?[0-9a-fA-F]{64}\s*$/,Kt=[/\b[5KL][1-9A-HJ-NP-Za-km-z]{50,51}\b/,/\bxprv[0-9A-Za-z]{50,}\b/],Dt=new Set(["privatekey","privkey","secretkey","seedphrase","seed","mnemonic","passphrase","password","keystore","keymaterial","wif","xprv","xpriv","bearer","authorization","signature","apikey","credential"]),qt=/(hash|digest|root|salt|nonce|proof|commitment|sig|id)(?:e?s)?$/i,jt=new Set(["calldata","data","publickey","pubkey","message","payload","input","extradata"]),Ft=new Set([12,15,18,21,24]),s=class extends TypeError{constructor(t,n="CONTROL_PLANE_INVALID"){super(`control-plane: ${t}`),this.name="ControlPlaneValidationError",this.code=n}};function I(e,t="value",{positive:n=!1}={}){if(typeof e!="string"||!Tt.test(e))throw new s(`${t} must be a canonical integer string`);if(n&&e==="0")throw new s(`${t} must be a positive integer string`);return e}function c(e,t="id"){if(typeof e!="string"||!Ct.test(e))throw new s(`${t} must be a bounded explicit id`);return e}function k(e,t="timestamp"){if(typeof e!="string"||e.length>64)throw new s(`${t} must be an explicit ISO timestamp`);let n=Date.parse(e);if(!Number.isFinite(n)||new Date(n).toISOString()!==e)throw new s(`${t} must be a canonical ISO timestamp`);return e}function b(e,t="hash",{nullable:n=!1}={}){if(n&&e===null)return e;if(typeof e!="string"||!Pt.test(e))throw new s(`${t} must be a lowercase sha256 hash`);return e}function p(e,t,n,r="record"){if(!e||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)throw new s(`${r} must be a plain object`);let o=new Set(t);for(let i of Object.keys(e))if(!o.has(i))throw new s(`${r} has unexpected field ${i}`);for(let i of n)if(!Object.hasOwn(e,i))throw new s(`${r}.${i} is required`)}function O(e,t){return`${c(e,"tenantId")}\0${c(t,"workflowId")}`}function ye(e,t,n){return`${O(e,t)}\0${c(n,"idempotencyKey")}`}function Pe(e,t){return e==="quantities"||Wt.test(t)}function ze(e){return String(e).replace(/[^a-z0-9]/gi,"").toLowerCase()}function Bt(e){let t=ze(e);return[...Dt].some(n=>t.includes(n))}function Vt(e){let t=ze(e);return jt.has(t)||qt.test(t)}function Mt(e){let t=String(e).trim().toLowerCase().split(/\s+/).filter(Boolean);return Ft.has(t.length)&&t.every(n=>vt.en.getWordIndex(n)>=0)}function Gt(e,t,n){if(typeof t=="string"){if(Kt.some(r=>r.test(t))||Mt(t))throw new s(`${n} contains secret or custody material`,"CONTROL_PLANE_SECRET");if(zt.test(t)&&!Vt(e))throw new s(`${n} contains secret or custody material`,"CONTROL_PLANE_SECRET")}}function Yt(e){return[...new Set([...Object.getOwnPropertyNames(e),...Object.keys(e)])]}function he(e,t="record",n="",r=new WeakSet){if(!(e===null||typeof e=="boolean"||typeof e=="number")){if(typeof e=="string"){Gt(n,e,t);return}if(!(typeof e=="bigint"||e===void 0)){if(typeof e=="function")throw new s(`${t} functions are not JSON-safe public data`,"CONTROL_PLANE_SECRET");if(typeof e!="object")throw new s(`${t} must contain JSON-safe plain objects only`,"CONTROL_PLANE_SECRET");if(r.has(e))throw new s(`${t} cyclic values are not JSON-safe`,"CONTROL_PLANE_SECRET");if(r.add(e),Buffer.isBuffer(e)||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)throw new s(`${t} binary buffers and typed arrays are not JSON-safe public data`,"CONTROL_PLANE_SECRET");if(typeof e.toJSON=="function")throw new s(`${t} toJSON is not allowed on control-plane records`,"CONTROL_PLANE_SECRET");if(Array.isArray(e)){e.forEach((o,i)=>he(o,`${t}[${i}]`,n,r));return}if(Object.getPrototypeOf(e)!==Object.prototype)throw new s(`${t} must contain JSON-safe plain objects only`,"CONTROL_PLANE_SECRET");for(let o of Yt(e)){let i=`${t}.${o}`;if(Bt(o))throw new s(`${i} contains secret or custody material`,"CONTROL_PLANE_SECRET");let d=Object.getOwnPropertyDescriptor(e,o);if(d&&(typeof d.get=="function"||typeof d.set=="function"))throw new s(`${i} getters are not JSON-safe public data`,"CONTROL_PLANE_SECRET");he(e[o],i,o,r)}}}}function me(e,t,n,r,o,i){if(o>We)throw new s(`${t} exceeds depth limit`);if(e===null||typeof e=="boolean")return i.bytes+=e===null||e?4:5,e;if(typeof e=="string"){let a=Buffer.byteLength(e,"utf8");if(a>Nt)throw new s(`${t} exceeds string size limit`);return Pe(r,n)&&I(e,t),i.bytes+=a+2,e}if(typeof e=="number"){if(!Number.isFinite(e)||!Number.isSafeInteger(e))throw new s(`${t} must be a finite safe integer or an exact integer string`);if(Pe(r,n))throw new s(`${t} financial quantity must be an exact integer string`);return i.bytes+=String(e).length,e}if(typeof e=="bigint")throw new s(`${t} bigint is not JSON-safe; use an exact integer string`);if(e===void 0)throw new s(`${t} undefined is not JSON-safe`);if(typeof e=="function")throw new s(`${t} functions are not JSON-safe public data`);if(Array.isArray(e)){if(e.length>Lt)throw new s(`${t} exceeds array item limit`);i.bytes+=2;let a=e.map((l,v)=>me(l,`${t}[${v}]`,n,r,o+1,i));if(i.bytes>K)throw new s(`${t} exceeds size limit`);return a}if(Buffer.isBuffer(e)||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)throw new s(`${t} binary buffers and typed arrays are not JSON-safe public data`);if(!e||typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype)throw new s(`${t} must contain JSON-safe plain objects only`);if(typeof e.toJSON=="function")throw new s(`${t} toJSON is not allowed on control-plane records`);let d=Object.keys(e).sort();if(d.length>Ht)throw new s(`${t} exceeds object key limit`);let u={};i.bytes+=2;for(let a of d){let l=Object.getOwnPropertyDescriptor(e,a);if(l&&(typeof l.get=="function"||typeof l.set=="function"))throw new s(`${t}.${a} getters are not JSON-safe public data`);if(i.bytes+=Buffer.byteLength(a,"utf8")+3,u[a]=me(e[a],`${t}.${a}`,a,n,o+1,i),i.bytes>K)throw new s(`${t} exceeds size limit`)}return u}function h(e,t="record"){try{Ce(e)}catch(i){throw new s(`${t} contains secret or custody material`,i?.code||"CONTROL_PLANE_SECRET")}try{he(e,t)}catch(i){throw i instanceof s?i:new s(`${t} contains secret or custody material`,i?.code||"CONTROL_PLANE_SECRET")}let r=me(e,t,"","",0,{bytes:0});if(Buffer.byteLength(re(r),"utf8")>K)throw new s(`${t} exceeds size limit`);return r}function re(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(re).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${re(e[t])}`).join(",")}}`}function L(e){return re(h(e))}function oe(e){return $t("sha256").update(L(e),"utf8").digest("hex")}function y(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))y(t);Object.freeze(e)}return e}function H(e){if(!e||typeof e!="object"||Array.isArray(e))throw new s("record object required");let{recordHash:t,eventHash:n,...r}=e;return oe(r)}function se(e,t){return h({schemaVersion:D,buildVersion:_,recordType:e,execution:"prepare-only",custody:"none",...t})}function ae(e,t){if(e.schemaVersion!==D)throw new s("schemaVersion mismatch");if(e.buildVersion!==_)throw new s("buildVersion mismatch");if(e.recordType!==t)throw new s(`recordType must be ${t}`);if(e.execution!=="prepare-only")throw new s("execution must be prepare-only");if(e.custody!=="none")throw new s("custody must be none")}var Jt=["schemaVersion","buildVersion","recordType","execution","custody"],Ke=[...Jt,"recordHash"],Ut=new Set(["draft","checked","approval","signed","submitted","finalized","reorged","orphaned","compensating","compensated","failed","cancelled"]),Xt=new Set(["pass","fail","unknown"]),Zt=new Set(["workflow.approval_granted","workflow.signed","workflow.submitted","workflow.finalized","workflow.reorged","workflow.orphaned","workflow.compensating","workflow.compensated","workflow.annotated"]),Qt=new Set(["signed","broadcast"]),en=Object.freeze({signed:new Set(["workflow.signed","legacy.signed"]),submitted:new Set(["workflow.submitted","legacy.broadcast"]),finalized:new Set(["workflow.finalized"]),reorged:new Set(["workflow.reorged"]),orphaned:new Set(["workflow.orphaned"]),compensating:new Set(["workflow.compensating"]),compensated:new Set(["workflow.compensated"])}),tn=new Set(["block","blockNumber","blockHash","inclusionBlock","inclusionBlockNumber","inclusionBlockHash","receipt","receiptHash","transactionIndex","logIndex","confirmations"]),nn=/^(?:0x)?[a-f0-9]{64}$/,rn=/^(?:0x)[a-f0-9]{64}$/;function ke(e,t){return e===null?e:c(e,t)}function ge(e,t){return e===null?e:k(e,t)}function G(e,t){let n=se(e,t);return y({...n,recordHash:H(n)})}function Y(e,t,n,r){p(e,[...Ke,...n],[...Ke,...r],t),ae(e,t),b(e.recordHash,`${t}.recordHash`);let o=H(e);if(e.recordHash!==o)throw new s(`${t} hash mismatch`);h(e,t)}function J(e,t){c(e.tenantId,`${t}.tenantId`),c(e.id,`${t}.id`),c(e.workflowId,`${t}.workflowId`),k(e.createdAt,`${t}.createdAt`)}function on(e,t){let n=`Plan.steps[${t}]`;if(p(e,["id","kind","target","quantities","data"],["id","kind","target","quantities","data"],n),c(e.id,`${n}.id`),c(e.kind,`${n}.kind`),e.target!==null&&(typeof e.target!="string"||e.target.length<1||e.target.length>4096))throw new s(`${n}.target must be null or a bounded string`);h(e.quantities,`${n}.quantities`),h(e.data,`${n}.data`)}function Ee(e,t){if(p(e,["status","source","reference","observedAt"],["status","source","reference","observedAt"],t),!new Set(["known","verified","unknown"]).has(e.status))throw new s(`${t}.status must be known, verified, or unknown`);if(c(e.source,`${t}.source`),typeof e.reference!="string"||e.reference.length<1||e.reference.length>4096)throw new s(`${t}.reference must be a bounded explicit reference`);ge(e.observedAt,`${t}.observedAt`)}function sn(e,t=null){return{status:e?.status,source:e?.source,reference:e?.reference,observedAt:e?.observedAt??t}}function ie(e,t=new WeakSet){if(!e||typeof e!="object"||t.has(e))return!1;if(t.add(e),Array.isArray(e))return e.some(n=>ie(n,t));for(let[n,r]of Object.entries(e))if(tn.has(n)||ie(r,t))return!0;return!1}function U(e,t,{min:n=1,max:r=4096}={}){if(typeof e!="string"||e.length<n||e.length>r)throw new s(`${t} must be an explicit bounded string`);return e}function qe(e,t){if(U(e,t,{min:66,max:66}),!rn.test(e))throw new s(`${t} must be a 0x-prefixed 32-byte hash`);return e}function V(e,t){if(U(e,t,{min:64,max:66}),!nn.test(e))throw new s(`${t} must be a 32-byte digest`);return e}function je(e,t,{positive:n=!1}={}){return I(e,t,{positive:n})}function an(e,t){if(ie(e))throw new s(`${t} signed proof must not require or carry inclusion block fields`);let n=e.artifactHash??e.signedArtifactHash??e.digest,r=e.signer??e.expectedSigner??e.from;V(n,`${t}.artifactHash`),U(r,`${t}.signer`,{min:1,max:256})}function cn(e,t){if(ie(e))throw new s(`${t} submitted proof must not require or carry inclusion block fields`);let n=e.transactionHash??e.txHash,r=e.endpoint??e.submissionEndpoint??e.provider;qe(n,`${t}.transactionHash`),U(r,`${t}.endpoint`,{min:1,max:4096})}function De(e,t,{requireReceiptStatus:n=!1}={}){let r=e.transactionHash??e.txHash,o=e.blockNumber,i=e.blockHash;qe(r,`${t}.transactionHash`),je(o,`${t}.blockNumber`,{positive:!0}),V(i,`${t}.blockHash`),e.receiptHash!=null&&V(e.receiptHash,`${t}.receiptHash`),(n||e.receiptStatus!=null)&&U(e.receiptStatus,`${t}.receiptStatus`,{min:1,max:32})}function M(e,t,n){switch(e){case"workflow.signed":case"legacy.signed":an(t,n);break;case"workflow.submitted":case"legacy.broadcast":cn(t,n);break;case"workflow.finalized":De(t,n,{requireReceiptStatus:!0}),t.confirmations!=null&&je(t.confirmations,`${n}.confirmations`);break;case"workflow.reorged":case"workflow.orphaned":De(t,n),t.observedBlockHash!=null&&V(t.observedBlockHash,`${n}.observedBlockHash`),t.replacementBlockHash!=null&&V(t.replacementBlockHash,`${n}.replacementBlockHash`);break;default:break}}function dn(e,t){let n=`RunRecord.externalFacts[${t}]`;if(!e||typeof e!="object"||Array.isArray(e))throw new s(`${n} external fact must be a plain object`);if(e.source==="trade-lifecycle-v1"){if(p(e,["source","state","eventHash","asOf","evidence","data"],["source","state","eventHash","asOf","evidence","data"],n),!Qt.has(e.state))throw new s(`${n}.state is not an external legacy fact`);if(b(e.eventHash,`${n}.eventHash`),!Number.isFinite(Number(e.asOf)))throw new s(`${n}.asOf must be finite`);if(Ee(e.evidence,`${n}.evidence`),e.evidence.status!=="verified"||e.evidence.source!=="external")throw new s(`${n} must have verified external evidence`);return h(e.data,`${n}.data`),M(`legacy.${e.state}`,e.data,`${n}.data`),`legacy.${e.state}`}if(p(e,["id","type","eventHash","occurredAt","evidence","data"],["id","type","eventHash","occurredAt","evidence","data"],n),c(e.id,`${n}.id`),!Zt.has(e.type))throw new s(`${n}.type is not an external workflow fact`);if(b(e.eventHash,`${n}.eventHash`),k(e.occurredAt,`${n}.occurredAt`),Ee(e.evidence,`${n}.evidence`),e.evidence.status!=="verified"||e.evidence.source!=="external")throw new s(`${n} must have verified external evidence`);return h(e.data,`${n}.data`),M(e.type,e.data,`${n}.data`),e.type}function ln(e={}){p(e,["tenantId","id","workflowId","createdAt","action","chainId","actor","quantities","constraints","metadata"],["tenantId","id","workflowId","createdAt","action","chainId"],"IntentSpec input");let t=G("IntentSpec",{tenantId:e.tenantId,id:e.id,workflowId:e.workflowId,createdAt:e.createdAt,action:e.action,chainId:e.chainId,actor:e.actor??null,quantities:e.quantities??{},constraints:e.constraints??{},metadata:e.metadata??{}});return Fe(t),t}function Fe(e){let t=["tenantId","id","workflowId","createdAt","action","chainId","actor","quantities","constraints","metadata"];if(Y(e,"IntentSpec",t,t),J(e,"IntentSpec"),c(e.action,"IntentSpec.action"),I(e.chainId,"IntentSpec.chainId",{positive:!0}),e.actor!==null&&(typeof e.actor!="string"||e.actor.length<1||e.actor.length>256))throw new s("IntentSpec.actor must be null or a bounded public identifier");return h(e.quantities,"IntentSpec.quantities"),h(e.constraints,"IntentSpec.constraints"),h(e.metadata,"IntentSpec.metadata"),!0}function fn(e={}){p(e,["tenantId","id","workflowId","intentSpecId","createdAt","expiresAt","steps","assumptions","metadata"],["tenantId","id","workflowId","intentSpecId","createdAt","steps"],"Plan input");let t=G("Plan",{tenantId:e.tenantId,id:e.id,workflowId:e.workflowId,intentSpecId:e.intentSpecId,createdAt:e.createdAt,expiresAt:e.expiresAt??null,steps:e.steps,assumptions:e.assumptions??[],metadata:e.metadata??{}});return Be(t),t}function Be(e){let t=["tenantId","id","workflowId","intentSpecId","createdAt","expiresAt","steps","assumptions","metadata"];if(Y(e,"Plan",t,t),J(e,"Plan"),c(e.intentSpecId,"Plan.intentSpecId"),ge(e.expiresAt,"Plan.expiresAt"),e.expiresAt!==null&&Date.parse(e.expiresAt)<=Date.parse(e.createdAt))throw new s("Plan.expiresAt must be after createdAt");if(!Array.isArray(e.steps)||e.steps.length<1||e.steps.length>100)throw new s("Plan.steps must contain 1..100 steps");if(e.steps.forEach(on),!Array.isArray(e.assumptions)||e.assumptions.length>100||e.assumptions.some(n=>typeof n!="string"||n.length>4096))throw new s("Plan.assumptions must be bounded strings");return h(e.metadata,"Plan.metadata"),!0}function un(e={}){p(e,["tenantId","id","workflowId","planId","createdAt","expiresAt","checks","summary","metadata"],["tenantId","id","workflowId","planId","createdAt","checks","summary"],"Preview input");let t=Array.isArray(e.checks)?e.checks.map(r=>({id:r?.id,status:r?.status,checkedAt:r?.checkedAt,evidence:sn(r?.evidence,r?.checkedAt??null)})):e.checks,n=G("Preview",{tenantId:e.tenantId,id:e.id,workflowId:e.workflowId,planId:e.planId,createdAt:e.createdAt,expiresAt:e.expiresAt??null,checks:t,summary:e.summary,metadata:e.metadata??{}});return Ve(n),n}function Ve(e){let t=["tenantId","id","workflowId","planId","createdAt","expiresAt","checks","summary","metadata"];if(Y(e,"Preview",t,t),J(e,"Preview"),c(e.planId,"Preview.planId"),ge(e.expiresAt,"Preview.expiresAt"),!Array.isArray(e.checks)||e.checks.length<1||e.checks.length>100)throw new s("Preview.checks must contain 1..100 checks");return e.checks.forEach((n,r)=>{let o=`Preview.checks[${r}]`;if(p(n,["id","status","checkedAt","evidence"],["id","status","checkedAt","evidence"],o),c(n.id,`${o}.id`),!Xt.has(n.status))throw new s(`${o}.status is invalid`);k(n.checkedAt,`${o}.checkedAt`),Ee(n.evidence,`${o}.evidence`)}),h(e.summary,"Preview.summary"),h(e.metadata,"Preview.metadata"),!0}function wn(e={}){p(e,["tenantId","id","workflowId","previewId","createdAt","expiresAt","requestedFrom","scope","metadata"],["tenantId","id","workflowId","previewId","createdAt","expiresAt","requestedFrom","scope"],"ApprovalRequest input");let t=G("ApprovalRequest",{tenantId:e.tenantId,id:e.id,workflowId:e.workflowId,previewId:e.previewId,createdAt:e.createdAt,expiresAt:e.expiresAt,requestedFrom:e.requestedFrom,scope:e.scope,metadata:e.metadata??{}});return Me(t),t}function Me(e){let t=["tenantId","id","workflowId","previewId","createdAt","expiresAt","requestedFrom","scope","metadata"];if(Y(e,"ApprovalRequest",t,t),J(e,"ApprovalRequest"),c(e.previewId,"ApprovalRequest.previewId"),k(e.expiresAt,"ApprovalRequest.expiresAt"),Date.parse(e.expiresAt)<=Date.parse(e.createdAt))throw new s("ApprovalRequest.expiresAt must be after createdAt");if(typeof e.requestedFrom!="string"||e.requestedFrom.length<1||e.requestedFrom.length>256)throw new s("ApprovalRequest.requestedFrom must be explicit and bounded");return h(e.scope,"ApprovalRequest.scope"),h(e.metadata,"ApprovalRequest.metadata"),!0}function X(e={}){p(e,["tenantId","id","workflowId","intentSpecId","planId","previewId","approvalRequestId","createdAt","updatedAt","state","eventCount","headEventHash","externalFacts","metadata","authority","sourceKind"],["tenantId","id","workflowId","intentSpecId","createdAt","state","eventCount"],"RunRecord input");let t=G("RunRecord",{tenantId:e.tenantId,id:e.id,workflowId:e.workflowId,intentSpecId:e.intentSpecId,planId:e.planId??null,previewId:e.previewId??null,approvalRequestId:e.approvalRequestId??null,createdAt:e.createdAt,updatedAt:e.updatedAt??e.createdAt,state:e.state,eventCount:e.eventCount,headEventHash:e.headEventHash??null,externalFacts:e.externalFacts??[],authority:e.authority??"projection",sourceKind:e.sourceKind??"workflow-events",metadata:e.metadata??{}});return Ge(t),t}function Ge(e){let t=["tenantId","id","workflowId","intentSpecId","planId","previewId","approvalRequestId","createdAt","updatedAt","state","eventCount","headEventHash","externalFacts","authority","sourceKind","metadata"];if(Y(e,"RunRecord",t,t),J(e,"RunRecord"),c(e.intentSpecId,"RunRecord.intentSpecId"),ke(e.planId,"RunRecord.planId"),ke(e.previewId,"RunRecord.previewId"),ke(e.approvalRequestId,"RunRecord.approvalRequestId"),k(e.updatedAt,"RunRecord.updatedAt"),Date.parse(e.updatedAt)<Date.parse(e.createdAt))throw new s("RunRecord.updatedAt must not precede createdAt");if(!Ut.has(e.state))throw new s("RunRecord.state is invalid");if(I(e.eventCount,"RunRecord.eventCount"),b(e.headEventHash,"RunRecord.headEventHash",{nullable:!0}),e.eventCount==="0"!=(e.headEventHash===null))throw new s("RunRecord eventCount/headEventHash mismatch");if(e.authority!=="projection")throw new s("RunRecord is a projection, not an authoritative ledger");if(!new Set(["workflow-events","legacy-trade-lifecycle"]).has(e.sourceKind))throw new s("RunRecord.sourceKind is invalid");if(!Array.isArray(e.externalFacts))throw new s("RunRecord.externalFacts must be an array");let n=new Set(e.externalFacts.map(dn)),r=en[e.state];if(r&&![...r].some(o=>n.has(o)))throw new s(`RunRecord ${e.state} state requires verified phase-specific external evidence`);return h(e.metadata,"RunRecord.metadata"),!0}var pn=Object.freeze(["draft","checked","approval","signed","submitted","finalized","reorged","orphaned","compensating","compensated","failed","cancelled"]),Je=Object.freeze(["workflow.drafted","workflow.checked","workflow.approval_requested","workflow.approval_granted","workflow.signed","workflow.submitted","workflow.finalized","workflow.reorged","workflow.orphaned","workflow.compensating","workflow.compensated","workflow.failed","workflow.cancelled","workflow.annotated"]),Ue=new Set(Je),hn=new Set(["workflow.approval_granted","workflow.signed","workflow.submitted","workflow.finalized","workflow.reorged","workflow.orphaned","workflow.compensating","workflow.compensated"]),Xe=new Set(["workflow.signed","workflow.submitted","workflow.finalized","workflow.reorged","workflow.orphaned"]),mn=new Set(["failed","cancelled","compensated"]),Ye=["schemaVersion","buildVersion","recordType","execution","custody","tenantId","id","workflowId","sequence","previousEventHash","idempotencyKey","occurredAt","recordedAt","type","external","evidence","data","eventHash"],ce=["tenantId","id","workflowId","idempotencyKey","occurredAt","recordedAt","type","external","evidence","data"];function yn(e,t){return{status:e?.status,source:e?.source,reference:e?.reference,observedAt:e?.observedAt??t}}function Ze(e,t="WorkflowEvent.evidence"){if(p(e,["status","source","reference","observedAt"],["status","source","reference","observedAt"],t),!new Set(["known","verified","unknown"]).has(e.status))throw new s(`${t}.status is invalid`);if(e.status==="unknown")throw new s("UNKNOWN evidence fails closed");if(c(e.source,`${t}.source`),typeof e.reference!="string"||e.reference.length<1||e.reference.length>4096)throw new s(`${t}.reference must be an explicit bounded reference`);k(e.observedAt,`${t}.observedAt`)}function Qe(e){return hn.has(e)}function be(e={}){p(e,ce,ce,"WorkflowEvent input");let t=h({tenantId:e.tenantId,id:e.id,workflowId:e.workflowId,idempotencyKey:e.idempotencyKey,occurredAt:e.occurredAt,recordedAt:e.recordedAt,type:e.type,external:e.external,evidence:yn(e.evidence,e.recordedAt),data:e.data},"WorkflowEvent input");if(c(t.tenantId,"WorkflowEvent.tenantId"),c(t.id,"WorkflowEvent.id"),c(t.workflowId,"WorkflowEvent.workflowId"),c(t.idempotencyKey,"WorkflowEvent.idempotencyKey"),k(t.occurredAt,"WorkflowEvent.occurredAt"),k(t.recordedAt,"WorkflowEvent.recordedAt"),!Ue.has(t.type))throw new s(`unknown workflow event type ${String(t.type)}`);if(typeof t.external!="boolean")throw new s("WorkflowEvent.external must be boolean");if(Ze(t.evidence),Qe(t.type)){if(t.external!==!0)throw new s(`${t.type} must be an explicitly external fact`);if(t.evidence.status!=="verified"||t.evidence.source!=="external")throw new s(`${t.type} requires verified external evidence; caller external:true is not proof`)}else if(t.external===!0)throw new s(`${t.type} is not an external fact; caller external:true is not proof`);return h(t.data,"WorkflowEvent.data"),Xe.has(t.type)&&M(t.type,t.data,"WorkflowEvent.data"),y(t)}function de(e={}){let t=e.sequence,n=e.previousEventHash,r=Object.fromEntries(ce.map(a=>[a,e[a]])),o=Object.keys(e).filter(a=>!ce.includes(a)&&a!=="sequence"&&a!=="previousEventHash");if(o.length)throw new s(`WorkflowEvent input has unexpected field ${o[0]}`);let i=be(r);if(I(t,"WorkflowEvent.sequence",{positive:!0}),t==="1"){if(n!==null)throw new s("first WorkflowEvent previousEventHash must be null")}else b(n,"WorkflowEvent.previousEventHash");let d=se("WorkflowEvent",{...i,sequence:t,previousEventHash:n}),u=y({...d,eventHash:H(d)});return Z(u),u}function Z(e){if(p(e,Ye,Ye,"WorkflowEvent"),ae(e,"WorkflowEvent"),c(e.tenantId,"WorkflowEvent.tenantId"),c(e.id,"WorkflowEvent.id"),c(e.workflowId,"WorkflowEvent.workflowId"),c(e.idempotencyKey,"WorkflowEvent.idempotencyKey"),I(e.sequence,"WorkflowEvent.sequence",{positive:!0}),e.sequence==="1"){if(e.previousEventHash!==null)throw new s("first WorkflowEvent previousEventHash must be null")}else b(e.previousEventHash,"WorkflowEvent.previousEventHash");if(k(e.occurredAt,"WorkflowEvent.occurredAt"),k(e.recordedAt,"WorkflowEvent.recordedAt"),!Ue.has(e.type))throw new s(`unknown workflow event type ${String(e.type)}`);if(typeof e.external!="boolean")throw new s("WorkflowEvent.external must be boolean");if(Ze(e.evidence),Qe(e.type)){if(e.external!==!0)throw new s(`${e.type} must be an explicitly external fact`);if(e.evidence.status!=="verified"||e.evidence.source!=="external")throw new s(`${e.type} requires verified external evidence; caller external:true is not proof`)}else if(e.external===!0)throw new s(`${e.type} is not an external fact; caller external:true is not proof`);if(h(e.data,"WorkflowEvent.data"),Xe.has(e.type)&&M(e.type,e.data,"WorkflowEvent.data"),b(e.eventHash,"WorkflowEvent.eventHash"),H(e)!==e.eventHash)throw new s("WorkflowEvent hash mismatch");return!0}function E(e,t){throw new s(`invalid workflow transition ${e??"NONE"} -> ${t.type}`)}function T(e=[]){if(!Array.isArray(e)||e.length<1)throw new s("workflow replay requires at least one event");let t=null,n=null,r=null,o=null,i=!1,d=null,u=[];for(let a of e){if(Z(a),t===null&&(t=a.tenantId),n===null&&(n=a.workflowId),r===null&&(r=O(a.tenantId,a.workflowId)),a.tenantId!==t)throw new s("workflow replay cannot mix tenant ids");if(a.workflowId!==n)throw new s("workflow replay cannot mix workflow ids");if(O(a.tenantId,a.workflowId)!==r)throw new s("workflow replay cannot mix tenant-scoped streams");let l=String(BigInt(d?.sequence??"0")+1n);if(a.sequence!==l)throw new s(`workflow sequence gap at ${a.sequence}`);if(a.previousEventHash!==(d?.eventHash??null))throw new s(`workflow previous-event hash mismatch at ${a.sequence}`);if(d&&Date.parse(a.recordedAt)<Date.parse(d.recordedAt))throw new s(`workflow recordedAt is not monotonic at ${a.sequence}`);if(mn.has(o))throw new s(`workflow state ${o} is terminal`);switch(a.type){case"workflow.drafted":o!==null&&E(o,a),o="draft";break;case"workflow.checked":if(o!=="draft"&&E(o,a),a.evidence.status!=="verified"||a.data?.checksPassed!==!0)throw new s("workflow.checked requires verified evidence and checksPassed=true");o="checked";break;case"workflow.approval_requested":o!=="checked"&&E(o,a),o="approval",i=!1;break;case"workflow.approval_granted":o!=="approval"&&E(o,a),i=!0;break;case"workflow.signed":if(o!=="approval"&&E(o,a),!i)throw new s("external approval must be granted before signed state");o="signed";break;case"workflow.submitted":o!=="signed"&&E(o,a),o="submitted";break;case"workflow.finalized":o!=="submitted"&&E(o,a),o="finalized";break;case"workflow.reorged":o!=="submitted"&&o!=="finalized"&&E(o,a),o="reorged";break;case"workflow.orphaned":o!=="submitted"&&o!=="finalized"&&o!=="reorged"&&E(o,a),o="orphaned";break;case"workflow.compensating":o!=="reorged"&&o!=="orphaned"&&E(o,a),o="compensating";break;case"workflow.compensated":o!=="compensating"&&E(o,a),o="compensated";break;case"workflow.failed":if(o==="finalized"||o==="compensated")throw new s("failed must not follow finalized");new Set(["draft","checked","approval","signed","submitted","reorged","orphaned","compensating"]).has(o)||E(o,a),o="failed";break;case"workflow.cancelled":new Set(["draft","checked","approval","signed"]).has(o)||E(o,a),o="cancelled";break;case"workflow.annotated":o===null&&E(o,a);break;default:E(o,a)}a.external&&u.push({id:a.id,type:a.type,eventHash:a.eventHash,occurredAt:a.occurredAt,evidence:a.evidence,data:a.data}),d=a}return y({schemaVersion:D,buildVersion:_,tenantId:t,workflowId:n,streamKey:r,state:o,approvalGranted:i,eventCount:String(e.length),headEventHash:d.eventHash,externalFacts:u,authority:"event-ledger",execution:"prepare-only",custody:"none"})}function kn(e,t={}){let n=T(e);return X({tenantId:n.tenantId,id:t.id,workflowId:n.workflowId,intentSpecId:t.intentSpecId,planId:t.planId??null,previewId:t.previewId??null,approvalRequestId:t.approvalRequestId??null,createdAt:t.createdAt,updatedAt:t.updatedAt??e.at(-1).recordedAt,state:n.state,eventCount:n.eventCount,headEventHash:n.headEventHash,externalFacts:n.externalFacts,authority:"projection",sourceKind:"workflow-events",metadata:t.metadata??{}})}var En=T;import{createHash as gn,randomUUID as nt}from"node:crypto";import{chmodSync as Ie,closeSync as P,constants as S,existsSync as C,fstatSync as bn,fsyncSync as ue,lstatSync as An,mkdirSync as In,openSync as we,readFileSync as le,renameSync as Sn,unlinkSync as Se,writeSync as xn}from"node:fs";import{dirname as rt,resolve as On}from"node:path";import{setTimeout as _n}from"node:timers/promises";var Rn="oracle.control-plane-ledger/1",xe="oracle.control-plane-ledger-checkpoint/1",Oe="oracle.control-plane-ledger-lock/1",j=64*1024*1024,ot=1e4,st=K,et=["schemaVersion","buildVersion","totalEvents","fileSize","ledgerHash","lastEventHash","workflowHeads","checkpointHash"],tt=["schemaVersion","token","pid","createdAt"],f=class extends Error{constructor(t,n="WORKFLOW_LEDGER_ERROR",r=null){super(`workflow-ledger: ${t}`),this.name="WorkflowLedgerError",this.code=n,this.detail=r}};function R(e){if(typeof e!="string"||e.length<1||e.length>4096)throw new f("bounded path required","PATH_INVALID");let t=On(e);return{ledger:t,checkpoint:`${t}.checkpoint`,lock:`${t}.lock`,directory:rt(t)}}function $n(e){In(e,{recursive:!0,mode:448})}function fe(e,t){let n=An(e);if(!n.isFile()||n.isSymbolicLink())throw new f(`${t} must be a regular non-symlink file`,"UNSAFE_FILE");if((n.mode&511)!==384)throw new f(`${t} permissions must be 0600`,"UNSAFE_PERMISSIONS");return n}function te(e){let t;try{t=we(e,S.O_RDONLY),ue(t)}finally{t!==void 0&&P(t)}}function _e(e,t){let n=0;for(;n<t.length;)n+=xn(e,t,n,t.length-n)}function vn(e){let t=S.O_WRONLY|S.O_CREAT|S.O_APPEND|(S.O_NOFOLLOW||0),n=we(e,t,384);if(!bn(n).isFile())throw P(n),new f("ledger target is not a regular file","UNSAFE_FILE");return n}function Nn(e){Z(e);let t=de({tenantId:e.tenantId,id:e.id,workflowId:e.workflowId,sequence:e.sequence,previousEventHash:e.previousEventHash,idempotencyKey:e.idempotencyKey,occurredAt:e.occurredAt,recordedAt:e.recordedAt,type:e.type,external:e.external,evidence:e.evidence,data:e.data});if(t.eventHash!==e.eventHash)throw new s("WorkflowEvent hash mismatch");return t}function Ae(e){return O(e.tenantId,e.workflowId)}function Ln(e){let t={};for(let n of e)t[Ae(n)]={tenantId:n.tenantId,workflowId:n.workflowId,sequence:n.sequence,eventHash:n.eventHash};return Object.fromEntries(Object.entries(t).sort(([n],[r])=>n.localeCompare(r)))}function at(e,t,n=null){let r=n??(C(e)?le(e):Buffer.alloc(0));return h({schemaVersion:xe,buildVersion:_,totalEvents:String(t.length),fileSize:String(r.length),ledgerHash:gn("sha256").update(r).digest("hex"),lastEventHash:t.at(-1)?.eventHash??null,workflowHeads:Ln(t)},"workflow checkpoint")}function it(e,t,n=null){let r=at(e,t,n);return y({...r,checkpointHash:oe(r)})}function Hn(e){if(p(e,et,et,"workflow checkpoint"),e.schemaVersion!==xe)throw new f("checkpoint schema mismatch","CHECKPOINT_INVALID");if(e.buildVersion!==_)throw new f("checkpoint build mismatch","CHECKPOINT_INVALID");if(I(e.totalEvents,"workflow checkpoint.totalEvents"),I(e.fileSize,"workflow checkpoint.fileSize"),b(e.ledgerHash,"workflow checkpoint.ledgerHash"),b(e.lastEventHash,"workflow checkpoint.lastEventHash",{nullable:!0}),!e.workflowHeads||typeof e.workflowHeads!="object"||Array.isArray(e.workflowHeads))throw new f("checkpoint workflowHeads invalid","CHECKPOINT_INVALID");for(let[r,o]of Object.entries(e.workflowHeads)){if(p(o,["tenantId","workflowId","sequence","eventHash"],["tenantId","workflowId","sequence","eventHash"],`workflow checkpoint.${r}`),c(o.tenantId,`workflow checkpoint.${r}.tenantId`),c(o.workflowId,`workflow checkpoint.${r}.workflowId`),O(o.tenantId,o.workflowId)!==r)throw new f("checkpoint workflowHeads stream key mismatch","CHECKPOINT_INVALID");I(o.sequence,`workflow checkpoint.${r}.sequence`,{positive:!0}),b(o.eventHash,`workflow checkpoint.${r}.eventHash`)}b(e.checkpointHash,"workflow checkpoint.checkpointHash");let{checkpointHash:t,...n}=e;if(oe(n)!==t)throw new f("checkpoint hash mismatch","CHECKPOINT_INVALID");if(e.totalEvents==="0"!=(e.lastEventHash===null))throw new f("checkpoint event count/head mismatch","CHECKPOINT_INVALID");return!0}function ct(e,t,n=null,r=null){let{checkpoint:o,directory:i}=R(e),d=r??it(e,t,n),u=`${o}.${nt()}.tmp`,a;try{a=we(u,S.O_WRONLY|S.O_CREAT|S.O_EXCL|(S.O_NOFOLLOW||0),384),_e(a,Buffer.from(`${JSON.stringify(d)}
2
+ `,"utf8")),ue(a),P(a),a=void 0,Sn(u,o),Ie(o,384),te(i)}catch(l){a!==void 0&&P(a);try{C(u)&&Se(u)}catch{}throw l}return d}function Tn(e,t){let n=BigInt(e.totalEvents),r=BigInt(t.totalEvents);if(n>r)return{ok:!1,reason:"checkpoint-ahead",recoverable:!1};if(n<r)return{ok:!1,reason:"checkpoint-behind",recoverable:!0};let o=BigInt(e.fileSize),i=BigInt(t.fileSize);return o>i?{ok:!1,reason:"checkpoint-ahead",recoverable:!1}:o<i?{ok:!1,reason:"checkpoint-behind",recoverable:!0}:e.ledgerHash!==t.ledgerHash?{ok:!1,reason:"checkpoint-mismatch",recoverable:!1}:e.lastEventHash!==t.lastEventHash?{ok:!1,reason:"checkpoint-mismatch",recoverable:!1}:L(e.workflowHeads)!==L(t.workflowHeads)?{ok:!1,reason:"checkpoint-mismatch",recoverable:!1}:{ok:!0}}function Q({path:e,maxBytes:t=j,checkCheckpoint:n=!0}={}){let r=R(e);if(!Number.isSafeInteger(t)||t<1||t>1024*1024*1024)return{ok:!1,reason:"size-limit",count:0,workflows:0,events:[],paths:r};try{if(!C(r.ledger))return n&&C(r.checkpoint)?{ok:!1,reason:"checkpoint-ahead",recoverable:!1,count:0,workflows:0,events:[],paths:r}:{ok:!0,count:0,workflows:0,events:[],heads:new Map,paths:r,empty:!0};if(fe(r.ledger,"ledger").size>t)return{ok:!1,reason:"size-limit",count:0,workflows:0,events:[],paths:r};let i=le(r.ledger);if(i.length>0&&i.at(-1)!==10)return{ok:!1,reason:"truncated-line",count:0,workflows:0,events:[],paths:r};let d=i.toString("utf8"),u=i.length===0?[]:d.slice(0,-1).split(`
3
+ `),a=[],l=new Map,v=new Set,N=new Set;for(let w=0;w<u.length;w+=1){let g=u[w];if(Buffer.byteLength(g,"utf8")>st)return{ok:!1,reason:"event-size-limit",line:w+1,count:a.length,workflows:l.size,events:a,paths:r};let x;try{x=JSON.parse(g)}catch{return{ok:!1,reason:"malformed-json",line:w+1,count:a.length,workflows:l.size,events:a,paths:r}}let m;try{m=Nn(x)}catch(He){return{ok:!1,reason:"event-invalid",line:w+1,detail:String(He?.message||He),count:a.length,workflows:l.size,events:a,paths:r}}if(v.has(m.id))return{ok:!1,reason:"duplicate-event-id",line:w+1,count:a.length,workflows:l.size,events:a,paths:r};let F=Ae(m),$=ye(m.tenantId,m.workflowId,m.idempotencyKey);if(N.has($))return{ok:!1,reason:"duplicate-idempotency-key",line:w+1,count:a.length,workflows:l.size,events:a,paths:r};let A=l.get(F)??null,yt=String(BigInt(A?.sequence??"0")+1n);if(m.sequence!==yt)return{ok:!1,reason:"sequence-gap",line:w+1,count:a.length,workflows:l.size,events:a,paths:r};if(m.previousEventHash!==(A?.eventHash??null))return{ok:!1,reason:"previous-event-hash-mismatch",line:w+1,count:a.length,workflows:l.size,events:a,paths:r};if(A&&Date.parse(m.recordedAt)<Date.parse(A.recordedAt))return{ok:!1,reason:"recorded-at-regression",line:w+1,count:a.length,workflows:l.size,events:a,paths:r};v.add(m.id),N.add($),l.set(F,m),a.push(m)}let z=new Map;for(let w of a){let g=Ae(w);z.has(g)||z.set(g,[]),z.get(g).push(w)}for(let[w,g]of z)try{T(g)}catch(x){return{ok:!1,reason:"workflow-invalid",streamKey:w,detail:String(x?.message||x),count:a.length,workflows:l.size,events:a,heads:l,paths:r}}if(n){if(!C(r.checkpoint))return a.length===0?{ok:!0,count:0,workflows:0,events:a,heads:l,paths:r,empty:!0}:{ok:!1,reason:"checkpoint-missing",recoverable:!0,count:a.length,workflows:l.size,events:a,heads:l,paths:r};let w;try{fe(r.checkpoint,"checkpoint");let m=le(r.checkpoint,"utf8");if(!m.endsWith(`
4
+ `))throw new f("checkpoint truncated","CHECKPOINT_INVALID");w=JSON.parse(m),Hn(w)}catch(m){return{ok:!1,reason:"checkpoint-invalid",recoverable:!1,detail:String(m?.message||m),count:a.length,workflows:l.size,events:a,heads:l,paths:r}}let g=at(r.ledger,a,i),x=Tn(w,g);if(!x.ok)return{...x,count:a.length,workflows:l.size,events:a,heads:l,paths:r}}return{ok:!0,count:a.length,workflows:l.size,events:a,heads:l,paths:r,raw:i,lastEventHash:a.at(-1)?.eventHash??null}}catch(o){return{ok:!1,reason:"io-error",detail:String(o?.message||o),count:0,workflows:0,events:[],paths:r}}}function ee(e){let t={ok:e.ok,count:e.count,workflows:e.workflows,...e.reason?{reason:e.reason}:{},...e.line?{line:e.line}:{},...e.detail?{detail:e.detail}:{},...e.recoverable!==void 0?{recoverable:e.recoverable}:{},...e.lastEventHash!==void 0?{lastEventHash:e.lastEventHash}:{}};return y(t)}function Cn(e={}){return ee(Q(e))}function dt({path:e,tenantId:t,workflowId:n,maxBytes:r=j}={}){let o=Q({path:e,maxBytes:r});if(!o.ok)throw new f(`cannot read corrupt ledger: ${o.reason}`,"LEDGER_CORRUPT",ee(o));t!==void 0&&c(t,"tenantId"),n!==void 0&&c(n,"workflowId");let i=o.events.filter(d=>(t===void 0||d.tenantId===t)&&(n===void 0||d.workflowId===n));return y([...i])}function Pn({path:e,tenantId:t,workflowId:n,maxBytes:r=j}={}){c(t,"tenantId"),c(n,"workflowId");let o=dt({path:e,tenantId:t,workflowId:n,maxBytes:r});if(o.length===0)throw new f(`workflow ${t}:${n} not found`,"WORKFLOW_NOT_FOUND");return T(o)}function lt(e){if(!Number.isSafeInteger(e)||e<=0)return"invalid";try{return process.kill(e,0),"active"}catch(t){return t?.code==="ESRCH"?"stale":"active"}}function Re(e){let{lock:t}=R(e);fe(t,"lock");let n=JSON.parse(le(t,"utf8"));if(p(n,tt,tt,"workflow ledger lock"),n.schemaVersion!==Oe)throw new f("lock schema mismatch","LOCK_INVALID");if(c(n.token,"workflow ledger lock.token"),!Number.isSafeInteger(n.pid)||n.pid<=0)throw new f("lock pid invalid","LOCK_INVALID");return k(n.createdAt,"workflow ledger lock.createdAt"),n}function $e({path:e}={}){let{lock:t}=R(e);if(!C(t))return y({state:"unlocked",lock:null});try{let n=Re(e);return y({state:lt(n.pid),lock:n})}catch(n){return y({state:"invalid",lock:null,error:String(n?.message||n)})}}function ft(e){let t=R(e);$n(t.directory);let n={schemaVersion:Oe,token:nt(),pid:process.pid,createdAt:new Date().toISOString()},r;try{return r=we(t.lock,S.O_WRONLY|S.O_CREAT|S.O_EXCL|(S.O_NOFOLLOW||0),384),_e(r,Buffer.from(`${JSON.stringify(n)}
5
+ `,"utf8")),ue(r),P(r),r=void 0,Ie(t.lock,384),te(t.directory),n}catch(o){throw r!==void 0&&P(r),o}}async function Wn(e,t){if(!Number.isSafeInteger(t)||t<0||t>12e4)throw new f("lockTimeoutMs out of bounds","LOCK_TIMEOUT_INVALID");let n=Date.now();for(;;)try{return ft(e)}catch(r){if(r?.code!=="EEXIST")throw r;if(Date.now()-n>=t){let o=$e({path:e});throw new f(`ledger busy (${o.state} lock); explicit token-bound recovery is required for stale locks`,"LEDGER_BUSY",o)}await _n(10)}}function q(e,t){let n=Re(e);if(n.token!==t||n.pid!==process.pid)throw new f("lock fencing token no longer owned","LOCK_FENCED");return!0}function ut(e,t){let n=R(e);q(e,t),Se(n.lock),te(n.directory)}function zn({path:e,expectedToken:t}={}){c(t,"expectedToken");let n=$e({path:e});if(n.state==="unlocked")throw new f("lock is already absent","LOCK_ABSENT");if(n.state==="invalid")throw new f("invalid lock is not recoverable automatically","LOCK_INVALID");if(n.lock.token!==t)throw new f("lock token mismatch","LOCK_TOKEN_MISMATCH");if(n.state==="active")throw new f("active lock owner cannot be recovered","LOCK_ACTIVE");let r=Re(e);if(r.token!==t||lt(r.pid)!=="stale")throw new f("lock changed during recovery","LOCK_FENCED");let o=R(e);return Se(o.lock),te(o.directory),y({recovered:!0,token:t})}function Kn(e){return{tenantId:e.tenantId,id:e.id,workflowId:e.workflowId,idempotencyKey:e.idempotencyKey,occurredAt:e.occurredAt,recordedAt:e.recordedAt,type:e.type,external:e.external,evidence:e.evidence,data:e.data}}async function Dn(e={}){p(e,["path","event","lockTimeoutMs","maxBytes"],["path","event"],"appendWorkflowEvent options");let t=R(e.path).ledger,n=be(e.event),r=e.lockTimeoutMs??ot,o=e.maxBytes??j,i=await Wn(t,r),d=null;try{q(t,i.token);let u=Q({path:t,maxBytes:o});if(!u.ok)throw new f(`append refused until ledger recovery: ${u.reason}`,"LEDGER_CORRUPT",ee(u));let a=u.events.find(A=>A.tenantId===n.tenantId&&A.workflowId===n.workflowId&&A.idempotencyKey===n.idempotencyKey);if(a){if(L(Kn(a))!==L(n))throw new f("idempotency key reused with different payload","IDEMPOTENCY_CONFLICT");return y({event:a,duplicate:!0})}if(u.events.some(A=>A.id===n.id))throw new f("event id already exists","EVENT_ID_CONFLICT");let l=O(n.tenantId,n.workflowId),v=u.heads.get(l)??null,N=de({...n,sequence:String(BigInt(v?.sequence??"0")+1n),previousEventHash:v?.eventHash??null}),z=u.events.filter(A=>O(A.tenantId,A.workflowId)===l);T([...z,N]);let w=Buffer.from(`${JSON.stringify(N)}
6
+ `,"utf8");if(w.length>st)throw new f("event exceeds size limit","EVENT_SIZE_LIMIT");let g=Buffer.concat([u.raw??Buffer.alloc(0),w]);if(g.length>o)throw new f("append would exceed ledger size limit","LEDGER_SIZE_LIMIT");let x=[...u.events,N],m=it(t,x,g),F=C(t);F&&fe(t,"ledger"),q(t,i.token);let $;try{$=vn(t),_e($,w),ue($)}finally{$!==void 0&&P($)}return Ie(t,384),F||te(rt(t)),q(t,i.token),ct(t,x,g,m),y({event:N,duplicate:!1})}catch(u){throw d=u,u}finally{try{ut(t,i.token)}catch(u){if(d===null)throw u}}}function qn({path:e,expectedLastEventHash:t,maxBytes:n=j}={}){let r=R(e).ledger,o=ft(r);try{q(r,o.token);let i=Q({path:r,maxBytes:n,checkCheckpoint:!1});if(!i.ok)throw new f(`ledger content is not recoverable: ${i.reason}`,"LEDGER_CORRUPT",ee(i));if(i.events.length===0)throw new f("empty ledger has no checkpoint head to recover","LEDGER_EMPTY");if(i.events.at(-1).eventHash!==t)throw new f("expected head does not match verified ledger head","RECOVERY_HEAD_MISMATCH");return q(r,o.token),ct(r,i.events,i.raw),ee(Q({path:r,maxBytes:n}))}finally{ut(r,o.token)}}import{createHash as Mn}from"node:crypto";var Er=Object.freeze(["chainId","agentAddress","accountAddress","actions","targets","maxValueWei","maxGasWei","maxSlippageBps","expiresAt","nonce","revocationKey"]),gr=Object.freeze(["read","simulate"]);var br=1440*60;var ne=class extends Error{constructor(t,n){super(`secret material must never appear in a public API object (at ${t}, rule: ${n})`),this.name="SecretLeakError",this.path=t,this.rule=n}},jn=/(private[_-]?key|secret|bearer|keystore|mnemonic|seed[_-]?phrase|passphrase|password|api[_-]?key|access[_-]?token|auth[_-]?token|session[_-]?token|signer[_-]?url|signature)/i,Fn=Object.freeze(["privkey","wif","xprv","seed"]);function wt(e){let t=String(e),n=t.toLowerCase().replace(/[\s._-]+/g,"");return jn.test(t)||Fn.includes(n)}var Bn=Object.freeze([{rule:"raw-32-byte-hex-key",re:/^0x[0-9a-fA-F]{64}$/},{rule:"raw-32-byte-hex-bare",re:/^[0-9a-fA-F]{64}$/},{rule:"extended-private-key",re:/\b(?:xprv|tprv|yprv|zprv)[1-9A-HJ-NP-Za-km-z]{107}\b/},{rule:"bitcoin-wif",re:/\b[59KLc][1-9A-HJ-NP-Za-km-z]{50,51}\b/},{rule:"bip39-mnemonic",re:/\b(?:[a-z]{3,8}\s+){11,23}[a-z]{3,8}\b/},{rule:"bearer-token",re:/bearer\s+[A-Za-z0-9._~+/=-]+/i},{rule:"pem-private-key",re:/-----BEGIN[A-Z ]*PRIVATE KEY-----/},{rule:"keystore-path",re:/keystore/i},{rule:"signer-url",re:/https?:\/\/\S*sign/i},{rule:"authorization-header",re:/authorization\s*:/i}]),Vn=Object.freeze(["grantid","id","hash","sha256","sha256hex","checksum","txhash","transactionhash","blockhash","digest","userophash","commithash","prevhash","intenthash","canonicalhash","payloadhash","requestid"]);function W(e,t="$",n=new Set,r=""){if(e==null)return e;if(typeof e=="string"){let o=Vn.includes(String(r).toLowerCase().replace(/[_-]/g,""));for(let{rule:i,re:d}of Bn)if(!(o&&i.startsWith("raw-32-byte-hex"))&&d.test(e))throw new ne(t,i);return e}if(typeof e!="object"||n.has(e)||(n.add(e),ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e;if(e instanceof Map){for(let[o,i]of e.entries()){if(typeof o=="string"&&wt(o))throw new ne(`${t}[${JSON.stringify(o)}]`,"forbidden-key-name");W(o,`${t}[key]`,n),W(i,`${t}[${String(o)}]`,n)}return e}if(e instanceof Set){let o=0;for(let i of e.values())W(i,`${t}[${o++}]`,n);return e}if(Array.isArray(e))return e.forEach((o,i)=>W(o,`${t}[${i}]`,n)),e;for(let[o,i]of Object.entries(e)){if(wt(o))throw new ne(`${t}.${o}`,"forbidden-key-name");W(i,`${t}.${o}`,n,o)}return e}var ve=Object.freeze(["intent","quote_comparison","simulation","prepared","approval","signed","broadcast","settlement","balance_delta","position"]),Gn=Object.freeze(Object.fromEntries(ve.map((e,t)=>[e,Object.freeze(t+1<ve.length?[ve[t+1]]:[])]))),Yn=new Set(["signed","broadcast"]);function Ne(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(Ne).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Ne(e[t])}`).join(",")}}`}function Jn(e,t="fact"){try{W(e,t)}catch{throw new Error(`${t} contains custody material and is forbidden`)}}function Un(e){return Mn("sha256").update(Ne(e)).digest("hex")}function pt(e){if(!e||!Array.isArray(e.events)||e.events.length===0)throw new Error("invalid trade lifecycle");if(e.custody!=="none")throw new Error("trade lifecycle custody must be none");if(e.execution!=="prepare-only")throw new Error("trade lifecycle execution must be prepare-only");let t=null;for(let n=0;n<e.events.length;n+=1){let r=e.events[n],{hash:o,...i}=r;if(Un(i)!==o)throw new Error(`trade event ${n} hash mismatch`);if(Jn(r.fact,`trade event ${n} fact`),!Number.isFinite(Number(r.asOf))||t&&Number(r.asOf)<Number(t.asOf))throw new Error(`trade event ${n} asOf must be finite and monotonic`);if(r.tradeId!==e.tradeId||r.previousHash!==t?.hash&&n>0)throw new Error(`trade event ${n} chain mismatch`);if(n===0&&(r.state!=="intent"||r.previousHash!==null))throw new Error("trade lifecycle must start with intent");if(t&&!Gn[t.state]?.includes(r.state))throw new Error(`invalid recorded transition ${t.state} -> ${r.state}`);if(Yn.has(r.state)&&r.external!==!0)throw new Error(`${r.state} is not externally supplied`);t=r}if(e.state!==t.state||e.headHash!==t.hash)throw new Error("trade lifecycle head mismatch");return!0}var ht=Object.freeze({intent:"draft",quote_comparison:"draft",simulation:"draft",prepared:"checked",approval:"approval",signed:"signed",broadcast:"submitted",settlement:"finalized",balance_delta:"compensated",position:"compensated"});function Le(e,t,n){if(typeof e=="string")return e;if(Number.isFinite(Number(e)))return new Date(Number(e)).toISOString();if(t!==void 0)return t;throw new s(`${n} must be supplied explicitly`)}function Xn(e){return{status:"verified",source:"external",reference:`trade-lifecycle:${e.state}:${e.hash}`,observedAt:Le(e.asOf,void 0,"legacy trade event asOf")}}function Zn(e){if(e.state==="signed")return{artifactHash:e.hash,signer:e.evidence?.signer??e.evidence?.from??"legacy-owner-wallet"};if(e.state==="broadcast"){let t=e.evidence?.txHash??e.evidence?.transactionHash;return{transactionHash:typeof t=="string"&&/^0x[a-f0-9]{64}$/.test(t)?t:`0x${e.hash}`,endpoint:e.evidence?.endpoint??e.evidence?.provider??"legacy-broadcast-endpoint"}}return e.evidence&&typeof e.evidence=="object"?e.evidence:{}}function mt(e,t={}){p(t,["tenantId","runId","intentSpecId","createdAt","updatedAt","metadata"],["tenantId","runId","createdAt"],"bridgeTradeLifecycle options"),c(t.tenantId,"bridgeTradeLifecycle.tenantId"),pt(e);let n=ht[e.state];if(!n)throw new s(`legacy trade state ${String(e.state)} has no compatibility mapping`);let r=Le(t.createdAt,void 0,"bridgeTradeLifecycle.createdAt"),o=Le(t.updatedAt??r,r,"bridgeTradeLifecycle.updatedAt"),i=e.events.filter(d=>d.external===!0).map(d=>({source:"trade-lifecycle-v1",state:d.state,eventHash:d.hash,asOf:d.asOf,evidence:Xn(d),data:Zn(d)}));return X({tenantId:t.tenantId,id:t.runId,workflowId:e.tradeId,intentSpecId:t.intentSpecId??`${e.tradeId}:intent`,createdAt:r,updatedAt:o,state:n,eventCount:String(e.events.length),headEventHash:e.headHash,externalFacts:i,authority:"projection",sourceKind:"legacy-trade-lifecycle",metadata:{...t.metadata??{},compatibility:{source:"trade-lifecycle-v1",authority:"projection",legacyState:e.state,legacyHeadHash:e.headHash,legacyEventCount:String(e.events.length),mapping:"conservative-v1"}}})}var Qn=mt;export{_ as CONTROL_PLANE_BUILD_VERSION,We as CONTROL_PLANE_MAX_DEPTH,K as CONTROL_PLANE_MAX_RECORD_BYTES,D as CONTROL_PLANE_SCHEMA_VERSION,s as ControlPlaneValidationError,ot as DEFAULT_WORKFLOW_LEDGER_LOCK_TIMEOUT_MS,j as DEFAULT_WORKFLOW_LEDGER_MAX_BYTES,ht as LEGACY_TRADE_STATE_MAP,Je as WORKFLOW_EVENT_TYPES,xe as WORKFLOW_LEDGER_CHECKPOINT_VERSION,Oe as WORKFLOW_LEDGER_LOCK_VERSION,Rn as WORKFLOW_LEDGER_SCHEMA_VERSION,pn as WORKFLOW_STATES,f as WorkflowLedgerError,Dn as appendWorkflowEvent,Me as assertApprovalRequest,I as assertCanonicalIntegerString,Fe as assertIntentSpec,Be as assertPlan,Ve as assertPreview,Ge as assertRunRecord,Z as assertWorkflowEvent,mt as bridgeTradeLifecycle,L as canonicalControlPlaneJson,wn as createApprovalRequest,ln as createIntentSpec,fn as createPlan,un as createPreview,X as createRunRecord,kn as createRunRecordFromEvents,de as createWorkflowEvent,H as hashControlPlaneRecord,$e as inspectWorkflowLedgerLock,dt as readWorkflowEvents,qn as recoverWorkflowLedgerCheckpoint,zn as recoverWorkflowLedgerLock,T as reduceWorkflowEvents,En as replayWorkflowEvents,Pn as replayWorkflowLedger,Qn as runRecordFromTradeLifecycle,Cn as verifyWorkflowLedger,ye as workflowIdempotencyId,O as workflowStreamKey};