@oracle-agent/oracle 0.35.32 → 0.35.35

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 (52) hide show
  1. package/README.md +10 -8
  2. package/artifacts/specialist-packs/oracle-full-crypto.json +11 -0
  3. package/dist/agent-sessions.mjs +1 -1
  4. package/dist/assets/profiles/canton-agent/SOUL.md +44 -0
  5. package/dist/assets/profiles/canton-agent/profile.json +30 -0
  6. package/dist/assets/profiles/oracle/SOUL.md +1 -0
  7. package/dist/assets/skills/oracle-canton/SKILL.md +49 -0
  8. package/dist/assets/skills/oracle-desk-product/SKILL.md +1 -1
  9. package/dist/bin/desk-server.mjs +35 -35
  10. package/dist/bin/oracle-data-mcp.mjs +17 -17
  11. package/dist/bin/oracle-gateway.mjs +14 -14
  12. package/dist/bin/oracle-launch-radar-shadow.mjs +4 -4
  13. package/dist/bin/oracle-mev-arb-shadow.mjs +4 -4
  14. package/dist/bin/oracle-mev-shadow.mjs +4 -4
  15. package/dist/bin/oracle-public-server.mjs +4 -4
  16. package/dist/bin/oracle-route.mjs +8 -8
  17. package/dist/bin/oracle-scan.mjs +10 -10
  18. package/dist/cli/commands/agent-session.mjs +3 -3
  19. package/dist/cli/commands/auth.mjs +17 -16
  20. package/dist/cli/commands/chain.mjs +1 -1
  21. package/dist/cli/commands/chat.mjs +210 -199
  22. package/dist/cli/commands/doctor.mjs +5 -5
  23. package/dist/cli/commands/eval.mjs +118 -108
  24. package/dist/cli/commands/farm.mjs +22 -22
  25. package/dist/cli/commands/harness.mjs +1 -1
  26. package/dist/cli/commands/model.mjs +214 -203
  27. package/dist/cli/commands/plugins.mjs +42 -39
  28. package/dist/cli/commands/quickstart.mjs +6 -6
  29. package/dist/cli/commands/setup.mjs +57 -56
  30. package/dist/cli/commands/sign.mjs +12 -12
  31. package/dist/cli/commands/signer.mjs +25 -23
  32. package/dist/cli/commands/snipe.mjs +6 -6
  33. package/dist/cli/commands/swap.mjs +12 -12
  34. package/dist/cli/commands/venues.mjs +2 -2
  35. package/dist/data/desk-data.mjs +33 -33
  36. package/dist/data/providers/farming.mjs +2 -2
  37. package/dist/data/providers/lp-destination-discovery.mjs +4 -4
  38. package/dist/index.mjs +50 -49
  39. package/dist/launch-radar/index.mjs +4 -4
  40. package/dist/local-signer/anvil-attestation-worker.mjs +1 -1
  41. package/dist/local-signer/index.mjs +3 -3
  42. package/dist/local-signer/runtime.mjs +22 -20
  43. package/dist/router/index.mjs +3 -3
  44. package/dist/router/prepare-bridge.mjs +1 -1
  45. package/dist/scanner/index.mjs +4 -4
  46. package/dist/task.mjs +2 -2
  47. package/dist/teams/index.mjs +3 -1
  48. package/dist/tui/standalone-client.mjs +81 -71
  49. package/package.json +2 -2
  50. package/public/eval-report.json +6 -6
  51. package/public/oracle-splash/index.html +4 -4
  52. package/server.json +2 -2
@@ -1 +1,3 @@
1
- var M=Object.freeze(["draft","shadow","confirm","armed","autonomous","halted"]),J=Object.freeze([["TOTAL","Total crypto market cap, also called TOTAL1"],["TOTAL2","Crypto market cap excluding BTC"],["TOTAL3","Crypto market cap excluding BTC and ETH"],["OTHERS","Crypto market cap outside the largest tracked assets"],["BTC.D","Bitcoin market-cap dominance"],["ETH.D","Ether market-cap dominance"],["USDT.D","Tether market-cap dominance"]].map(([e,n])=>Object.freeze({id:e,description:n}))),Z=Object.freeze([["sma","Simple moving average"],["ema","Exponential moving average"],["rsi","Relative strength index"],["macd","Moving-average convergence divergence"],["bollinger","Bollinger bands"],["atr","Average true range"],["vwap","Volume-weighted average price"],["volume","Traded volume"],["cvd","Cumulative volume delta"],["funding","Perpetual funding rate"],["open-interest","Open interest and change"],["liquidations","Liquidation flow"],["basis","Perpetual-to-spot basis"]].map(([e,n])=>Object.freeze({id:e,description:n}))),Q=Object.freeze([["relative-value","Long-short relative value basket"],["beta-neutral","Beta-balanced directional basket"],["spread-mean-reversion","Bounded spread mean reversion"],["funding-carry","Cross-market funding carry"]].map(([e,n])=>Object.freeze({id:e,description:n}))),D=Object.freeze([["anthropic-oauth","oauth"],["openai-codex","oauth"],["xai-oauth","oauth"],["openrouter","api-key"],["openai","api-key"],["anthropic","api-key"],["xai","api-key"],["deepseek","api-key"],["gemini","api-key"],["kimi","api-key"],["mistral","api-key"],["nous","api-key"],["qwen","api-key"],["glm","api-key"],["local","local"],["ollama","local"]].map(([e,n])=>Object.freeze({id:e,auth:n}))),X=[["market.scan","Read bounded market observations"],["market.breadth","Read TOTAL, TOTAL2, TOTAL3, OTHERS, and dominance evidence"],["perp.indicators","Calculate bounded price, volume, positioning, and derivatives signals"],["basket.construct","Construct an exact bounded multi-leg basket plan"],["basket.backtest","Backtest a bounded basket against supplied history"],["sentiment.read","Read cited public sentiment"],["wallet.watch","Observe public wallet activity"],["contract.read","Inspect public contract state"],["nft.inspect","Inspect public mint state"],["strategy.analyze","Analyze a strategy without executing it"],["strategy.backtest","Backtest against supplied history"],["risk.evaluate","Evaluate an intent against policy"],["intent.prepare","Prepare a non-executable intent"],["operator.handoff","Create an operator confirmation handoff"]],$=Object.freeze(X.map(([e,n])=>Object.freeze({id:e,description:n,signs:!1,broadcasts:!1}))),ee=[["hyperliquid-markets","Research Hyperliquid market evidence"],["crypto-market-breadth","Analyze crypto market breadth and dominance evidence"],["perp-technical-analysis","Analyze bounded perpetual technical and positioning signals"],["perp-strategy-planning","Plan bounded perpetual strategies"],["basket-trading","Construct exact non-atomic multi-leg basket plans"],["relative-value-risk","Evaluate per-leg and aggregate relative-value risk"],["armed-local-routing","Route an approved exact plan to the local operator boundary"],["social-sentiment","Score cited public sentiment"],["wallet-monitoring","Analyze public wallet activity"],["contract-research","Research public contract state"],["mint-research","Research public mint state"],["bounded-strategy-analysis","Analyze bounded strategy evidence"],["bounded-backtesting","Backtest against supplied history"],["bounded-risk","Evaluate evidence against fixed policy"],["prepare-only-execution","Prepare an operator confirmation handoff"]],P=Object.freeze(ee.map(([e,n])=>Object.freeze({id:e,description:n,signs:!1,broadcasts:!1}))),te=Object.freeze({autonomousOptIn:!1,requiresWalletConfirmation:!0,killSwitchRequired:!0,maxNotionalUsd:100,maxDailyLossUsd:10,chainAllowlist:Object.freeze(["ethereum"]),expiresAt:41024448e5});function S({id:e,name:n,scannerName:o,scannerTool:s,scannerSkill:u,scannerArtifact:l,chainAllowlist:E}){return Object.freeze({id:e,name:n,mode:"draft",agents:Object.freeze([Object.freeze({id:"scanner",name:o,role:"scanner",runtime:"deterministic",soul:"Collect bounded public evidence with source times.",toolIds:Object.freeze([s]),skillIds:Object.freeze([u])}),Object.freeze({id:"sentiment",name:"Grok Sentiment",role:"sentiment",runtime:"model",provider:"xai",model:"grok-4.6",soul:"Score narrative direction and cite every claim.",toolIds:Object.freeze(["sentiment.read"]),skillIds:Object.freeze(["social-sentiment"])}),Object.freeze({id:"strategy",name:"Strategy Analyst",role:"strategy",runtime:"model",provider:"openai",model:"gpt-5.6-sol",soul:"Produce a falsifiable thesis from typed evidence.",toolIds:Object.freeze(["strategy.analyze"]),skillIds:Object.freeze(["bounded-strategy-analysis"])}),Object.freeze({id:"risk",name:"Risk Gate",role:"risk",runtime:"policy",soul:"Enforce every cap exactly and reject unsupported intent.",toolIds:Object.freeze(["risk.evaluate"]),skillIds:Object.freeze(["bounded-risk"])}),Object.freeze({id:"executor",name:"Executor",role:"executor",runtime:"operator",soul:"Prepare an exact operator handoff. Never sign or broadcast.",toolIds:Object.freeze(["intent.prepare","operator.handoff"]),skillIds:Object.freeze(["prepare-only-execution"])})]),edges:Object.freeze([Object.freeze({from:"scanner",to:"sentiment",artifactKind:l}),Object.freeze({from:"sentiment",to:"strategy",artifactKind:"scored-thesis"}),Object.freeze({from:"strategy",to:"risk",artifactKind:"strategy-analysis"}),Object.freeze({from:"risk",to:"executor",artifactKind:"approved-intent"})]),policy:Object.freeze({...te,chainAllowlist:Object.freeze(E)})})}var re=Object.freeze([S({id:"hyperliquid-alpha",name:"Hyperliquid Alpha",scannerName:"Market Scanner",scannerTool:"market.scan",scannerSkill:"hyperliquid-markets",scannerArtifact:"market-evidence",chainAllowlist:["hyperliquid"]}),S({id:"perp-market-breadth",name:"Perp Market Breadth",scannerName:"Breadth Scanner",scannerTool:"market.breadth",scannerSkill:"crypto-market-breadth",scannerArtifact:"breadth-evidence",chainAllowlist:["hyperliquid"]}),S({id:"perp-technical-strategy",name:"Perp Technical Strategy",scannerName:"Perp Technical Scanner",scannerTool:"perp.indicators",scannerSkill:"perp-technical-analysis",scannerArtifact:"technical-evidence",chainAllowlist:["hyperliquid"]}),S({id:"basket-relative-value",name:"Basket Relative Value",scannerName:"Basket Constructor",scannerTool:"basket.construct",scannerSkill:"basket-trading",scannerArtifact:"basket-evidence",chainAllowlist:["hyperliquid"]}),S({id:"wallet-watch",name:"Wallet Watch",scannerName:"Wallet Monitor",scannerTool:"wallet.watch",scannerSkill:"wallet-monitoring",scannerArtifact:"wallet-flow",chainAllowlist:["ethereum","base"]}),S({id:"evm-launch-radar",name:"EVM Launch Radar",scannerName:"Launch Scanner",scannerTool:"contract.read",scannerSkill:"contract-research",scannerArtifact:"contract-evidence",chainAllowlist:["ethereum","base","arbitrum"]}),S({id:"nft-mint-guard",name:"NFT Mint Guard",scannerName:"Mint Scanner",scannerTool:"nft.inspect",scannerSkill:"mint-research",scannerArtifact:"mint-evidence",chainAllowlist:["ethereum","base"]})]);import{createHash as ne}from"node:crypto";var ae=/^[a-z0-9][a-z0-9._-]{0,63}$/,oe=new Set(["deterministic","model","policy","operator"]),ie=new Set($.map(({id:e})=>e)),se=new Set(P.map(({id:e})=>e)),ce=new Set(D.map(({id:e})=>e)),de=["secret","privatekey","seed","seedphrase","mnemonic","password","passphrase","credential","apikey","apitoken","accesstoken","authtoken","authorization","signingmaterial","walletexport","keymaterial"],N=/(?:\bshell\b|terminal|raw[ _.-]?http|\bmcp\b|private[ _.-]?key|seed[ _.-]?phrase|mnemonic|key[ _.-]?(?:import|export)|wallet[ _.-]?(?:key|custody)|\bcustod(?:y|ial)\b|\bsign(?:ing|er)?\b|\bbroadcast(?:ing)?\b|(?:execute|place)[ _.-]?(?:transaction|trade|order|swap)s?|submit[ _.-]?transactions?|transfer[ _.-]?(?:funds|assets|tokens|coins)|hold[ _.-]?(?:keys|funds|assets)|ignore (?:the )?policy|bypass|widen (?:the )?(?:cap|policy)|reveal (?:credential|secret))/i,le=Object.freeze(["market-evidence","breadth-evidence","technical-evidence","basket-evidence","wallet-flow","contract-evidence","mint-evidence","scored-thesis","strategy-analysis","risk-decision","approved-intent","prepared-intent","prepared-basket","receipt"]),fe=new Set(le);function c(e){throw new TypeError(e)}function R(e,n){(!e||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)&&c(`${n} must be a plain object`)}function ue(e){return String(e).toLowerCase().replace(/[^a-z0-9]/g,"")}function V(e){let n=ue(e);return n==="auth"||de.some(o=>n.includes(o))}function K(e,n="team",o=new Set){if(e&&typeof e=="object"){o.has(e)&&c(`unsafe cyclic field at ${n}`),o.add(e);for(let[s,u]of Object.entries(e))V(s)&&c(`forbidden secret-like field ${n}.${s}`),K(u,`${n}.${s}`,o);o.delete(e)}}function T(e){return e===null||typeof e=="string"||typeof e=="boolean"?e:typeof e=="number"?(Number.isFinite(e)||c("value must be finite"),e):Array.isArray(e)?e.map(T):(R(e,"value"),Object.fromEntries(Object.keys(e).sort().map(n=>(V(n)&&c(`forbidden secret-like field ${n}`),[n,T(e[n])]))))}function v(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let n of Object.values(e))v(n);Object.freeze(e)}return e}function _(e){return ne("sha256").update(JSON.stringify(T(e))).digest("hex")}function z(e,n,o=500){return(typeof e!="string"||!e.trim()||e.length>o)&&c(`${n} is invalid`),e}function O(e,n){return z(e,n,64),ae.test(e)||c(`${n} is invalid`),e}function pe(e){let n=String.raw`(?:sign(?:ing)?|broadcast(?:ing)?|(?:execute|place|submit|transfer|hold|assume)\b[^.!?\n]*?\b(?:transactions?|trades?|orders?|swaps?|funds|assets|tokens|coins|keys|custody))`,o=e.replace(new RegExp(String.raw`\b(?:never|do not|don't|cannot|can't|must not|may not)\s+(?:directly\s+)?${n}(?:\s+or\s+${n})?`,"gi"),"");return N.test(o)||new RegExp(String.raw`\b${n}\b`,"i").test(o)}function U(e){return O(e,"artifact kind"),fe.has(e)||c(`artifact kind ${e} is not allowed`),e}function B(e,{nowMs:n=Date.now(),mode:o="shadow"}={}){R(e,"policy"),K(e,"policy");let s=["autonomousOptIn","requiresWalletConfirmation","killSwitchRequired"];for(let l of s)typeof e[l]!="boolean"&&c(`policy.${l} must be boolean`);(!e.requiresWalletConfirmation||!e.killSwitchRequired)&&c("unsafe policy: wallet confirmation and kill switch are required");for(let l of["maxNotionalUsd","maxDailyLossUsd"])(!Number.isFinite(e[l])||e[l]<=0)&&c(`policy.${l} must be a positive finite cap`);(!Array.isArray(e.chainAllowlist)||!e.chainAllowlist.length)&&c("policy.chainAllowlist must be bounded");let u=e.chainAllowlist.map(l=>O(l,"chain id"));return new Set(u).size!==u.length&&c("duplicate chain id"),(!Number.isSafeInteger(e.expiresAt)||e.expiresAt<=n)&&c("policy expiry must be in the future"),o==="autonomous"&&!e.autonomousOptIn&&c("autonomous mode requires explicit opt-in"),{autonomousOptIn:e.autonomousOptIn,requiresWalletConfirmation:!0,killSwitchRequired:!0,maxNotionalUsd:e.maxNotionalUsd,maxDailyLossUsd:e.maxDailyLossUsd,chainAllowlist:u,expiresAt:e.expiresAt}}function G(e,{nowMs:n=Date.now()}={}){R(e,"team"),K(e),O(e.id,"team id"),z(e.name,"team name",120),M.includes(e.mode)||c("unsupported team mode"),(!Array.isArray(e.agents)||!e.agents.length)&&c("agents must be non-empty");let o=new Set,s=e.agents.map((r,m)=>{R(r,`agent ${m}`);let y=O(r.id,"agent id");o.has(y)&&c(`duplicate agent id ${y}`),o.add(y),z(r.name,"agent name",120),O(r.role,"agent role"),oe.has(r.runtime)||c("invalid agent runtime");let x=z(r.soul,"agent Soul",2e3);pe(x)&&c("unsafe Soul authority"),(!Array.isArray(r.toolIds)||!Array.isArray(r.skillIds))&&c("tool and skill IDs must be arrays");let j=r.toolIds.map(k=>(O(k,"tool id"),(!ie.has(k)||N.test(k))&&c(`forbidden tool ${k}`),k)),q=r.skillIds.map(k=>(O(k,"skill id"),(!se.has(k)||N.test(k))&&c(`forbidden skill ${k}`),k));(new Set(j).size!==j.length||new Set(q).size!==q.length)&&c("duplicate tool or skill ID");let Y=r.runtime==="model";return Y?(z(r.provider,"model provider",100),ce.has(r.provider)||c("unsupported model provider"),z(r.model,"model",160)):(r.provider!==void 0||r.model!==void 0)&&c("provider/model only allowed for model runtime"),r.role==="executor"&&r.runtime!=="operator"&&c("executor must use operator runtime"),r.runtime==="operator"&&r.role!=="executor"&&c("operator runtime is reserved for the executor"),r.role!=="executor"&&j.some(k=>k==="intent.prepare"||k==="operator.handoff")&&c("executor tools require operator authority"),{id:y,name:r.name,role:r.role,runtime:r.runtime,...Y?{provider:r.provider,model:r.model}:{},soul:x,toolIds:j,skillIds:q}}),u=s.filter(r=>r.role==="executor");u.length!==1&&c("exactly one executor operator is required");let l=u[0];(!l.toolIds.includes("intent.prepare")||!l.toolIds.includes("operator.handoff"))&&c("executor requires prepare-only handoff tools"),Array.isArray(e.edges)||c("edges must be an array");let E=new Set,g=new Map([...o].map(r=>[r,[]])),A=e.edges.map(r=>{R(r,"edge"),O(r.from,"edge source"),O(r.to,"edge target");let m=U(r.artifactKind);(!o.has(r.from)||!o.has(r.to))&&c("broken edge references unknown agent"),r.from===r.to&&c("cycle in team DAG");let y=`${r.from}\0${r.to}\0${m}`;return E.has(y)&&c("duplicate edge"),E.add(y),g.get(r.from).push(r.to),{from:r.from,to:r.to,artifactKind:m}}),h=new Set,f=new Set;function i(r){if(h.has(r)&&c("cycle in team DAG"),!f.has(r)){h.add(r);for(let m of g.get(r))i(m);h.delete(r),f.add(r)}}for(let r of o)i(r);g.get(l.id).length&&c("executor must be the terminal team agent");let a=r=>{let m=[r],y=new Set;for(;m.length;){let x=m.shift();if(x===l.id)return!0;y.has(x)||(y.add(x),m.push(...g.get(x)))}return!1};for(let r of o)a(r)||c(`agent ${r} is disconnected from executor`);let t=s.filter(r=>!A.some(m=>m.to===r.id));t.length!==1&&c("team pipeline requires exactly one root agent");for(let r of s){let m=A.filter(x=>x.to===r.id).length,y=A.filter(x=>x.from===r.id).length;(r.id===t[0].id?m!==0:m!==1)&&c("team pipeline requires exactly one incoming handoff per non-root agent"),(r.id===l.id?y!==0:y!==1)&&c("team pipeline requires exactly one outgoing handoff per non-executor agent")}let d=A.filter(r=>r.to===l.id);(d.length!==1||d[0].artifactKind!=="approved-intent")&&c("executor requires exactly one approved-intent input"),s.find(r=>r.id===d[0].from)?.runtime!=="policy"&&c("executor input must come from a policy agent");let p=B(e.policy,{nowMs:n,mode:e.mode}),w=T({id:e.id,name:e.name,mode:e.mode,agents:s,edges:A,policy:p});return v({team:w,teamHash:_(w),execution:{executionAllowed:!1,backendSigner:!1,signingReady:!1,broadcastReady:!1,requiresOperatorConfirmation:!0}})}var me=/^[a-z0-9][a-z0-9._:-]{0,127}$/i,he=/^[0-9a-f]{64}$/,we=/^evidence:sha256:[0-9a-f]{64}$/,ye=new Set(["approved-intent","prepared-intent","prepared-basket"]),ge=new Set(["perp-order","hip3-order","hip4-order","perp-bracket"]),be=/^[A-Za-z0-9@:_./-]{1,64}$/;function L(e,n){if(typeof e!="string"||!me.test(e))throw new TypeError(`${n} is invalid`);return e}function Ae(e,n){if(typeof e!="string"||!he.test(e))throw new TypeError(`${n} is invalid`);return e}function C(e,n){if(!e||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)throw new TypeError(`${n} must be a plain object`)}function W(e,n,o){for(let s of Object.keys(e))if(!n.has(s))throw new TypeError(`${o}.${s} is not allowed`)}function I(e,n,{allowZero:o=!1}={}){if(!Number.isFinite(e)||(o?e<0:e<=0))throw new TypeError(`${n} must be ${o?"non-negative":"positive"}`);let s=e*100;if(!Number.isSafeInteger(Math.round(s))||Math.abs(s-Math.round(s))>1e-8)throw new TypeError(`${n} must use exact USD cents`);return Math.round(s)}function xe(e,n,{nowMs:o,expiresAt:s}){if(C(e,"basket leg artifact"),e.version!==1)throw new TypeError("basket leg artifact must be version 1");if(e.surface!=="hl")throw new TypeError("basket leg artifact surface must be hl");if(e.action!=="order"||e.destination!=="hyperliquid")throw new TypeError("basket leg artifact must be a Hyperliquid order");if(!Number.isSafeInteger(e.expiresAtMs)||e.expiresAtMs<=o||e.expiresAtMs>s)throw new TypeError("basket leg artifact expiry must fit the handoff TTL");if(C(e.artifact,"basket leg artifact payload"),!ge.has(e.artifact.kind))throw new TypeError("basket leg artifact kind is not an order");if(e.artifact.coin!==n.market)throw new TypeError("basket leg artifact market mismatch");if(e.artifact.side!==n.side)throw new TypeError("basket leg artifact side mismatch");if(I(e.artifact.notionalUsd,"basket leg artifact notional")!==I(n.notionalUsd,"basket leg notional"))throw new TypeError("basket leg artifact notional mismatch")}function ke(e,n,o){let s=e.executionPlan;if(s===void 0){if(o.mode==="armed")throw new TypeError("armed intent requires an exact execution plan");return}if(e.chainId!=="hyperliquid")throw new TypeError("armed execution plans require the Hyperliquid chain");if(e.intentType!=="perp"&&e.intentType!=="basket")throw new TypeError("intentType must be perp or basket");if(C(s,"executionPlan"),W(s,new Set(["atomic","partialFillRiskAcknowledged","legs"]),"executionPlan"),s.atomic!==!1)throw new TypeError("basket and perp plans must be explicitly non-atomic");if(!Array.isArray(s.legs))throw new TypeError("executionPlan.legs must be an array");let u=e.intentType==="basket"?2:1,l=e.intentType==="basket"?12:1;if(s.legs.length<u||s.legs.length>l)throw new TypeError(`${e.intentType} execution plan requires ${u}-${l} legs`);if(e.intentType==="basket"&&s.partialFillRiskAcknowledged!==!0)throw new TypeError("basket partial-fill risk must be acknowledged");if(e.intentType==="perp"&&typeof s.partialFillRiskAcknowledged!="boolean")throw new TypeError("perp partial-fill risk acknowledgement must be boolean");let E=new Set,g=0,A=0;for(let[h,f]of s.legs.entries()){if(C(f,`executionPlan.legs[${h}]`),W(f,new Set(["market","side","notionalUsd","weightBps","artifact"]),`executionPlan.legs[${h}]`),typeof f.market!="string"||!be.test(f.market))throw new TypeError("basket leg market is invalid");if(E.has(f.market))throw new TypeError(`duplicate basket market ${f.market}`);if(E.add(f.market),f.side!=="buy"&&f.side!=="sell")throw new TypeError("basket leg side must be buy or sell");if(g+=I(f.notionalUsd,"basket leg notional"),!Number.isSafeInteger(f.weightBps)||f.weightBps<=0||f.weightBps>1e4)throw new TypeError("basket leg weight must be positive basis points");A+=f.weightBps,xe(f.artifact,f,o)}if(A!==1e4)throw new TypeError("basket leg weights must sum to 10000 bps");if(g!==I(e.notionalUsd,"intent notional"))throw new TypeError("basket aggregate notional must equal the exact leg sum");if(g>I(n.maxNotionalUsd,"policy maxNotionalUsd"))throw new TypeError("basket aggregate notional exceeds policy cap")}function Te(e,n,o){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("intent payload must be an object");if(typeof e.chainId!="string"||!n.chainAllowlist.includes(e.chainId))throw new TypeError("intent chain is outside policy allowlist");if(!Number.isFinite(e.notionalUsd)||e.notionalUsd<=0||e.notionalUsd>n.maxNotionalUsd)throw new TypeError("intent notional exceeds policy cap");if(!Number.isFinite(e.maxLossUsd)||e.maxLossUsd<0||e.maxLossUsd>n.maxDailyLossUsd)throw new TypeError("intent loss exceeds policy cap");I(e.notionalUsd,"intent notional"),I(e.maxLossUsd,"intent max loss",{allowZero:!0}),ke(e,n,o)}function F(e,{compiled:n}={}){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("handoff must be an object");if(!n?.team||typeof n.teamHash!="string")throw new TypeError("compiled team snapshot is required");let o=e.nowMs??Date.now();if(!Number.isSafeInteger(o))throw new TypeError("nowMs is invalid");if(!Number.isSafeInteger(e.ttlMs)||e.ttlMs<=0||e.ttlMs>6e4)throw new TypeError("TTL must be bounded to 60 seconds");let s=L(e.teamId,"teamId"),u=Ae(e.teamHash,"teamHash");if(n.team.id!==s||n.teamHash!==u)throw new TypeError("handoff team snapshot mismatch");let l=L(e.sourceAgentId,"sourceAgentId"),E=L(e.targetAgentId,"targetAgentId"),g=U(e.artifactKind);if(!n.team.edges.some(t=>t.from===l&&t.to===E&&t.artifactKind===g))throw new TypeError("handoff does not match compiled team edge");if(!Array.isArray(e.evidenceRefs)||!e.evidenceRefs.length)throw new TypeError("evidenceRefs must be non-empty");let A=e.evidenceRefs.map(t=>{if(typeof t!="string"||!we.test(t))throw new TypeError("evidence reference must be a SHA-256 content hash");return t});if(new Set(A).size!==A.length)throw new TypeError("duplicate evidence reference");let h=T(e.payload),f=B(n.team.policy,{nowMs:o,mode:n.team.mode}),i=o+e.ttlMs;if(i>f.expiresAt)throw new TypeError("handoff TTL exceeds policy expiry");ye.has(g)&&Te(h,f,{mode:n.team.mode,nowMs:o,expiresAt:i});let a={teamId:s,teamHash:u,runId:L(e.runId,"runId"),sourceAgentId:l,targetAgentId:E,artifactKind:g,payload:h,payloadHash:_(h),evidenceRefs:A,ttlMs:e.ttlMs,issuedAt:o,expiresAt:i,policy:f,policyHash:_(f)};return v(T({...a,handoffHash:_(a),executionAllowed:!1,backendSigner:!1,signingReady:!1,broadcastReady:!1,requiresOperatorConfirmation:!0}))}import{randomUUID as Ee}from"node:crypto";function H(e,n,o){if(o>=n.compiled.team.policy.expiresAt)throw e.status="expired",e.updatedAt=o,new Error("team policy expired")}function Oe({now:e=Date.now,storage:n,executionAdapter:o}={}){let s=n??new Map,u=new Map,l=new Map,E=async(i,a)=>s.set(i,T(a)),g=async i=>s.get(i),A=async()=>s instanceof Map?[...s.values()]:s.list(),h=i=>v(T(i));async function f(){if(typeof o?.status!="function")throw new Error("armed mode requires a local execution adapter");let i=await o.status();if(!i?.configured||!i?.reachable||i?.armed!==!0)throw new Error("local signer is not armed and reachable");if(typeof o?.executeConfirmedArtifact!="function")throw new Error("armed mode requires a local execution adapter");return i}return Object.freeze({async save(i){let a=G(i,{nowMs:e()});return await E(a.team.id,a),h(a)},async list(){return h(await A())},async get(i){let a=await g(i);return a===void 0?null:h(a)},async getRun(i){let a=u.get(i);return a===void 0?null:h(a)},async start(i){let a=await g(i);if(!a)throw new Error(`unknown team ${i}`);let t=v(T(a));if(t.team.mode==="draft")throw new Error("draft team must be promoted before running");if(t.team.mode==="halted")throw new Error("team kill switch is active");let d=e();if(d>=t.team.policy.expiresAt)throw new Error("team policy expired");let b=t.team.mode==="armed";b&&await f();let p=t.team.agents.find(r=>!t.team.edges.some(m=>m.to===r.id));if(!p)throw new Error("team pipeline has no root agent");let w={id:Ee(),teamId:i,teamHash:t.teamHash,status:t.team.mode==="shadow"?"shadowing":"running",mode:t.team.mode,armed:b,startedAt:d,updatedAt:d,expiresAt:t.team.policy.expiresAt,maxSteps:t.team.edges.length,steps:[],receipts:[],executionAllowed:!1,backendSigner:b,signingReady:b,broadcastReady:b,requiresOperatorConfirmation:!0,signed:!1,broadcast:!1};return u.set(w.id,w),l.set(w.id,{compiled:t,currentAgentId:p.id,previousHandoffHash:null,consumedHandoffHashes:new Set,executionConsumed:!1,confirmationPending:!1}),h(w)},async step(i,a){let t=u.get(i),d=l.get(i);if(!t||!d)throw new Error(`unknown run ${i}`);if(t.status==="halted")throw new Error("run is halted");if(t.status==="paused")throw new Error("run is paused");if(t.status!=="running"&&t.status!=="shadowing")throw new Error("run cannot step from its current state");let b=e();if(H(t,d,b),t.steps.length>=t.maxSteps)throw new Error("run step budget exhausted");if(a?.agentId!==d.currentAgentId)throw new TypeError("step agent is out of order");let p=d.compiled.team.edges.find(y=>y.from===a.agentId);if(!p||p.to!==a?.targetAgentId||p.artifactKind!==a?.artifactKind)throw new TypeError("artifact does not match the exact next team edge");let w,r=null;if(d.previousHandoffHash===null){if(a.inputHandoffHash!==void 0)throw new TypeError("root step cannot consume a prior handoff");w=a.evidenceRefs}else{if(a.inputHandoffHash!==d.previousHandoffHash)throw new TypeError("step must consume the exact prior handoff");if(d.consumedHandoffHashes.has(a.inputHandoffHash))throw new TypeError("handoff was already consumed");r=a.inputHandoffHash,w=[`evidence:sha256:${a.inputHandoffHash}`]}let m=F({teamId:t.teamId,teamHash:t.teamHash,runId:i,sourceAgentId:p.from,targetAgentId:p.to,artifactKind:p.artifactKind,payload:a.payload,evidenceRefs:w,ttlMs:a.ttlMs,nowMs:b},{compiled:d.compiled});return r!==null&&d.consumedHandoffHashes.add(r),t.steps.push(m),t.updatedAt=b,d.currentAgentId=p.to,d.previousHandoffHash=m.handoffHash,p.to===d.compiled.team.agents.find(y=>y.role==="executor").id&&(t.status=t.mode==="armed"?"awaiting-confirmation":"prepared",t.preparedAt=b,t.mode!=="armed"&&(t.completedAt=b)),h(t)},async confirm(i,a){let t=u.get(i),d=l.get(i);if(!t||!d)throw new Error(`unknown run ${i}`);if(t.status==="halted")throw new Error("run is halted");if(t.status!=="awaiting-confirmation")throw new Error("run cannot confirm from its current state or was already executed");let b=e();H(t,d,b);let p=t.steps.at(-1);if(!p||p.artifactKind!=="approved-intent")throw new Error("approved intent handoff is required");if(b>=p.expiresAt)throw new Error("approved intent handoff expired");if(a?.handoffHash!==p.handoffHash)throw new TypeError("confirmation must bind the exact handoff hash");if(a?.operatorConfirmed!==!0||a?.sign!==!0||a?.broadcast!==!0)throw new TypeError("explicit confirm, sign, and broadcast instruction is required");if(d.executionConsumed||d.confirmationPending)throw new Error("approved intent is already executing or was already executed");d.confirmationPending=!0;try{await f();let w=e();if(H(t,d,w),t.status==="halted")throw new Error("run was halted before execution");if(t.status!=="awaiting-confirmation")throw new Error("run cannot confirm from its current state");if(w>=p.expiresAt)throw new Error("approved intent handoff expired");let r=p.payload?.executionPlan?.legs;if(!Array.isArray(r)||!r.length)throw new Error("approved intent has no executable legs");d.executionConsumed=!0,t.status="executing",t.updatedAt=w;for(let[m,y]of r.entries()){if(t.status==="halted")throw new Error("run was halted during sequential basket execution");let x=e();if(H(t,d,x),x>=p.expiresAt)throw new Error("approved intent handoff expired during execution");let j=await o.executeConfirmedArtifact(T(y.artifact),{runId:i,handoffHash:p.handoffHash,legIndex:m,legCount:r.length});if(t.receipts.push(T(j)),t.updatedAt=e(),t.status==="halted")throw new Error("run was halted during sequential basket execution");if(H(t,d,t.updatedAt),t.updatedAt>=p.expiresAt)throw new Error("approved intent handoff expired during execution")}return t.status="completed",t.executionAllowed=!1,t.requiresOperatorConfirmation=!1,t.signed=!0,t.broadcast=!0,t.completedAt=e(),t.updatedAt=t.completedAt,h(t)}catch(w){throw d.executionConsumed&&(t.status!=="halted"&&t.status!=="expired"&&(t.status="failed"),t.executionAllowed=!1,t.partialExecution=t.receipts.length>0,t.error=w instanceof Error?w.message:"local execution failed",t.updatedAt=e()),w}finally{d.confirmationPending=!1}},async pause(i){let a=u.get(i);if(!a)throw new Error(`unknown run ${i}`);if(a.status!=="running"&&a.status!=="shadowing")throw new Error("only an active run can be paused");return a.resumeStatus=a.status,a.status="paused",a.updatedAt=e(),h(a)},async resume(i){let a=u.get(i),t=l.get(i);if(!a||!t)throw new Error(`unknown run ${i}`);if(a.status!=="paused")throw new Error("only a paused run can be resumed");let d=e();return H(a,t,d),a.status=a.resumeStatus==="shadowing"?"shadowing":"running",delete a.resumeStatus,a.updatedAt=d,h(a)},async halt(i){let a=u.get(i);if(!a)throw new Error(`unknown run ${i}`);return a.status="halted",delete a.resumeStatus,a.updatedAt=e(),h(a)}})}export{Q as BASKET_STRATEGY_CATALOG,P as CRYPTO_SKILL_CATALOG,$ as CRYPTO_TOOL_CATALOG,J as MARKET_BREADTH_CATALOG,D as MODEL_PROVIDER_CATALOG,Z as PERP_SIGNAL_CATALOG,M as TEAM_MODES,re as TEAM_TEMPLATES,G as compileTeamDefinition,F as createTeamHandoff,Oe as createTeamService};
1
+ var ee=Object.freeze(["draft","shadow","confirm","armed","autonomous","halted"]),Ie=Object.freeze([["TOTAL","Total crypto market cap, also called TOTAL1"],["TOTAL2","Crypto market cap excluding BTC"],["TOTAL3","Crypto market cap excluding BTC and ETH"],["OTHERS","Crypto market cap outside the largest tracked assets"],["BTC.D","Bitcoin market-cap dominance"],["ETH.D","Ether market-cap dominance"],["USDT.D","Tether market-cap dominance"]].map(([e,t])=>Object.freeze({id:e,description:t}))),je=Object.freeze([["sma","Simple moving average"],["ema","Exponential moving average"],["rsi","Relative strength index"],["macd","Moving-average convergence divergence"],["bollinger","Bollinger bands"],["atr","Average true range"],["vwap","Volume-weighted average price"],["volume","Traded volume"],["cvd","Cumulative volume delta"],["funding","Perpetual funding rate"],["open-interest","Open interest and change"],["liquidations","Liquidation flow"],["basis","Perpetual-to-spot basis"]].map(([e,t])=>Object.freeze({id:e,description:t}))),Le=Object.freeze([["relative-value","Long-short relative value basket"],["beta-neutral","Beta-balanced directional basket"],["spread-mean-reversion","Bounded spread mean reversion"],["funding-carry","Cross-market funding carry"]].map(([e,t])=>Object.freeze({id:e,description:t}))),te=Object.freeze([["anthropic-oauth","oauth"],["openai-codex","oauth"],["xai-oauth","oauth"],["openrouter","api-key"],["openai","api-key"],["anthropic","api-key"],["xai","api-key"],["deepseek","api-key"],["gemini","api-key"],["kimi","api-key"],["mistral","api-key"],["nous","api-key"],["qwen","api-key"],["glm","api-key"],["local","local"],["ollama","local"]].map(([e,t])=>Object.freeze({id:e,auth:t}))),ze=[["market.scan","Read bounded market observations"],["market.breadth","Read TOTAL, TOTAL2, TOTAL3, OTHERS, and dominance evidence"],["perp.indicators","Calculate bounded price, volume, positioning, and derivatives signals"],["basket.construct","Construct an exact bounded multi-leg basket plan"],["basket.backtest","Backtest a bounded basket against supplied history"],["sentiment.read","Read cited public sentiment"],["wallet.watch","Observe public wallet activity"],["contract.read","Inspect public contract state"],["nft.inspect","Inspect public mint state"],["strategy.analyze","Analyze a strategy without executing it"],["strategy.backtest","Backtest against supplied history"],["risk.evaluate","Evaluate an intent against policy"],["intent.prepare","Prepare a non-executable intent"],["operator.handoff","Create an operator confirmation handoff"]],re=Object.freeze(ze.map(([e,t])=>Object.freeze({id:e,description:t,signs:!1,broadcasts:!1}))),qe=[["hyperliquid-markets","Research Hyperliquid market evidence"],["crypto-market-breadth","Analyze crypto market breadth and dominance evidence"],["perp-technical-analysis","Analyze bounded perpetual technical and positioning signals"],["perp-strategy-planning","Plan bounded perpetual strategies"],["basket-trading","Construct exact non-atomic multi-leg basket plans"],["relative-value-risk","Evaluate per-leg and aggregate relative-value risk"],["armed-local-routing","Route an approved exact plan to the local operator boundary"],["social-sentiment","Score cited public sentiment"],["wallet-monitoring","Analyze public wallet activity"],["contract-research","Research public contract state"],["mint-research","Research public mint state"],["bounded-strategy-analysis","Analyze bounded strategy evidence"],["bounded-backtesting","Backtest against supplied history"],["bounded-risk","Evaluate evidence against fixed policy"],["prepare-only-execution","Prepare an operator confirmation handoff"]],ne=Object.freeze(qe.map(([e,t])=>Object.freeze({id:e,description:t,signs:!1,broadcasts:!1}))),Ne=Object.freeze({autonomousOptIn:!1,requiresWalletConfirmation:!0,killSwitchRequired:!0,maxNotionalUsd:100,maxDailyLossUsd:10,chainAllowlist:Object.freeze(["ethereum"]),expiresAt:41024448e5});function P({id:e,name:t,scannerName:n,scannerTool:s,scannerSkill:p,scannerArtifact:l,chainAllowlist:b}){return Object.freeze({id:e,name:t,mode:"draft",agents:Object.freeze([Object.freeze({id:"scanner",name:n,role:"scanner",runtime:"deterministic",soul:"Collect bounded public evidence with source times.",toolIds:Object.freeze([s]),skillIds:Object.freeze([p])}),Object.freeze({id:"sentiment",name:"Grok Sentiment",role:"sentiment",runtime:"model",provider:"xai",model:"grok-4.6",soul:"Score narrative direction and cite every claim.",toolIds:Object.freeze(["sentiment.read"]),skillIds:Object.freeze(["social-sentiment"])}),Object.freeze({id:"strategy",name:"Strategy Analyst",role:"strategy",runtime:"model",provider:"openai",model:"gpt-5.6-sol",soul:"Produce a falsifiable thesis from typed evidence.",toolIds:Object.freeze(["strategy.analyze"]),skillIds:Object.freeze(["bounded-strategy-analysis"])}),Object.freeze({id:"risk",name:"Risk Gate",role:"risk",runtime:"policy",soul:"Enforce every cap exactly and reject unsupported intent.",toolIds:Object.freeze(["risk.evaluate"]),skillIds:Object.freeze(["bounded-risk"])}),Object.freeze({id:"executor",name:"Executor",role:"executor",runtime:"operator",soul:"Prepare an exact operator handoff. Never sign or broadcast.",toolIds:Object.freeze(["intent.prepare","operator.handoff"]),skillIds:Object.freeze(["prepare-only-execution"])})]),edges:Object.freeze([Object.freeze({from:"scanner",to:"sentiment",artifactKind:l}),Object.freeze({from:"sentiment",to:"strategy",artifactKind:"scored-thesis"}),Object.freeze({from:"strategy",to:"risk",artifactKind:"strategy-analysis"}),Object.freeze({from:"risk",to:"executor",artifactKind:"approved-intent"})]),policy:Object.freeze({...Ne,chainAllowlist:Object.freeze(b)})})}var Me=Object.freeze([P({id:"hyperliquid-alpha",name:"Hyperliquid Alpha",scannerName:"Market Scanner",scannerTool:"market.scan",scannerSkill:"hyperliquid-markets",scannerArtifact:"market-evidence",chainAllowlist:["hyperliquid"]}),P({id:"perp-market-breadth",name:"Perp Market Breadth",scannerName:"Breadth Scanner",scannerTool:"market.breadth",scannerSkill:"crypto-market-breadth",scannerArtifact:"breadth-evidence",chainAllowlist:["hyperliquid"]}),P({id:"perp-technical-strategy",name:"Perp Technical Strategy",scannerName:"Perp Technical Scanner",scannerTool:"perp.indicators",scannerSkill:"perp-technical-analysis",scannerArtifact:"technical-evidence",chainAllowlist:["hyperliquid"]}),P({id:"basket-relative-value",name:"Basket Relative Value",scannerName:"Basket Constructor",scannerTool:"basket.construct",scannerSkill:"basket-trading",scannerArtifact:"basket-evidence",chainAllowlist:["hyperliquid"]}),P({id:"wallet-watch",name:"Wallet Watch",scannerName:"Wallet Monitor",scannerTool:"wallet.watch",scannerSkill:"wallet-monitoring",scannerArtifact:"wallet-flow",chainAllowlist:["ethereum","base"]}),P({id:"evm-launch-radar",name:"EVM Launch Radar",scannerName:"Launch Scanner",scannerTool:"contract.read",scannerSkill:"contract-research",scannerArtifact:"contract-evidence",chainAllowlist:["ethereum","base","arbitrum"]}),P({id:"nft-mint-guard",name:"NFT Mint Guard",scannerName:"Mint Scanner",scannerTool:"nft.inspect",scannerSkill:"mint-research",scannerArtifact:"mint-evidence",chainAllowlist:["ethereum","base"]})]);import{createHash as Pe}from"node:crypto";var De=/^[a-z0-9][a-z0-9._-]{0,63}$/,Ke=new Set(["deterministic","model","policy","operator"]),Be=new Set(re.map(({id:e})=>e)),Ue=new Set(ne.map(({id:e})=>e)),Fe=new Set(te.map(({id:e})=>e)),Ge=["secret","privatekey","seed","seedphrase","mnemonic","password","passphrase","credential","apikey","apitoken","accesstoken","authtoken","authorization","signingmaterial","walletexport","keymaterial"],oe=/(?:\bshell\b|terminal|raw[ _.-]?http|\bmcp\b|private[ _.-]?key|seed[ _.-]?phrase|mnemonic|key[ _.-]?(?:import|export)|wallet[ _.-]?(?:key|custody)|\bcustod(?:y|ial)\b|\bsign(?:ing|er)?\b|\bbroadcast(?:ing)?\b|(?:execute|place)[ _.-]?(?:transaction|trade|order|swap)s?|submit[ _.-]?transactions?|transfer[ _.-]?(?:funds|assets|tokens|coins)|hold[ _.-]?(?:keys|funds|assets)|ignore (?:the )?policy|bypass|widen (?:the )?(?:cap|policy)|reveal (?:credential|secret))/i,Ve=Object.freeze(["market-evidence","breadth-evidence","technical-evidence","basket-evidence","wallet-flow","contract-evidence","mint-evidence","scored-thesis","strategy-analysis","risk-decision","approved-intent","prepared-intent","prepared-basket","receipt"]),Ye=new Set(Ve);function u(e){throw new TypeError(e)}function G(e,t){(!e||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)&&u(`${t} must be a plain object`)}function We(e){return String(e).toLowerCase().replace(/[^a-z0-9]/g,"")}function we(e){let t=We(e);return t==="auth"||Ge.some(n=>t.includes(n))}function ie(e,t="team",n=new Set){if(e&&typeof e=="object"){n.has(e)&&u(`unsafe cyclic field at ${t}`),n.add(e);for(let[s,p]of Object.entries(e))we(s)&&u(`forbidden secret-like field ${t}.${s}`),ie(p,`${t}.${s}`,n);n.delete(e)}}function y(e){return e===null||typeof e=="string"||typeof e=="boolean"?e:typeof e=="number"?(Number.isFinite(e)||u("value must be finite"),e):Array.isArray(e)?e.map(y):(G(e,"value"),Object.fromEntries(Object.keys(e).sort().map(t=>(we(t)&&u(`forbidden secret-like field ${t}`),[t,y(e[t])]))))}function q(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))q(t);Object.freeze(e)}return e}function V(e){return Pe("sha256").update(JSON.stringify(y(e))).digest("hex")}function U(e,t,n=500){return(typeof e!="string"||!e.trim()||e.length>n)&&u(`${t} is invalid`),e}function z(e,t){return U(e,t,64),De.test(e)||u(`${t} is invalid`),e}function Je(e){let t=String.raw`(?:sign(?:ing)?|broadcast(?:ing)?|(?:execute|place|submit|transfer|hold|assume)\b[^.!?\n]*?\b(?:transactions?|trades?|orders?|swaps?|funds|assets|tokens|coins|keys|custody))`,n=e.replace(new RegExp(String.raw`\b(?:never|do not|don't|cannot|can't|must not|may not)\s+(?:directly\s+)?${t}(?:\s+or\s+${t})?`,"gi"),"");return oe.test(n)||new RegExp(String.raw`\b${t}\b`,"i").test(n)}function ae(e){return z(e,"artifact kind"),Ye.has(e)||u(`artifact kind ${e} is not allowed`),e}function se(e,{nowMs:t=Date.now(),mode:n="shadow"}={}){G(e,"policy"),ie(e,"policy");let s=["autonomousOptIn","requiresWalletConfirmation","killSwitchRequired"];for(let l of s)typeof e[l]!="boolean"&&u(`policy.${l} must be boolean`);(!e.requiresWalletConfirmation||!e.killSwitchRequired)&&u("unsafe policy: wallet confirmation and kill switch are required");for(let l of["maxNotionalUsd","maxDailyLossUsd"])(!Number.isFinite(e[l])||e[l]<=0)&&u(`policy.${l} must be a positive finite cap`);(!Array.isArray(e.chainAllowlist)||!e.chainAllowlist.length)&&u("policy.chainAllowlist must be bounded");let p=e.chainAllowlist.map(l=>z(l,"chain id"));return new Set(p).size!==p.length&&u("duplicate chain id"),(!Number.isSafeInteger(e.expiresAt)||e.expiresAt<=t)&&u("policy expiry must be in the future"),n==="autonomous"&&!e.autonomousOptIn&&u("autonomous mode requires explicit opt-in"),{autonomousOptIn:e.autonomousOptIn,requiresWalletConfirmation:!0,killSwitchRequired:!0,maxNotionalUsd:e.maxNotionalUsd,maxDailyLossUsd:e.maxDailyLossUsd,chainAllowlist:p,expiresAt:e.expiresAt}}function ce(e,{nowMs:t=Date.now()}={}){G(e,"team"),ie(e),z(e.id,"team id"),U(e.name,"team name",120),ee.includes(e.mode)||u("unsupported team mode"),(!Array.isArray(e.agents)||!e.agents.length)&&u("agents must be non-empty");let n=new Set,s=e.agents.map((i,E)=>{G(i,`agent ${E}`);let O=z(i.id,"agent id");n.has(O)&&u(`duplicate agent id ${O}`),n.add(O),U(i.name,"agent name",120),z(i.role,"agent role"),Ke.has(i.runtime)||u("invalid agent runtime");let g=U(i.soul,"agent Soul",2e3);Je(g)&&u("unsafe Soul authority"),(!Array.isArray(i.toolIds)||!Array.isArray(i.skillIds))&&u("tool and skill IDs must be arrays");let C=i.toolIds.map(o=>(z(o,"tool id"),(!Be.has(o)||oe.test(o))&&u(`forbidden tool ${o}`),o)),B=i.skillIds.map(o=>(z(o,"skill id"),(!Ue.has(o)||oe.test(o))&&u(`forbidden skill ${o}`),o));(new Set(C).size!==C.length||new Set(B).size!==B.length)&&u("duplicate tool or skill ID");let r=i.runtime==="model";return r?(U(i.provider,"model provider",100),Fe.has(i.provider)||u("unsupported model provider"),U(i.model,"model",160)):(i.provider!==void 0||i.model!==void 0)&&u("provider/model only allowed for model runtime"),i.role==="executor"&&i.runtime!=="operator"&&u("executor must use operator runtime"),i.runtime==="operator"&&i.role!=="executor"&&u("operator runtime is reserved for the executor"),i.role!=="executor"&&C.some(o=>o==="intent.prepare"||o==="operator.handoff")&&u("executor tools require operator authority"),{id:O,name:i.name,role:i.role,runtime:i.runtime,...r?{provider:i.provider,model:i.model}:{},soul:g,toolIds:C,skillIds:B}}),p=s.filter(i=>i.role==="executor");p.length!==1&&u("exactly one executor operator is required");let l=p[0];(!l.toolIds.includes("intent.prepare")||!l.toolIds.includes("operator.handoff"))&&u("executor requires prepare-only handoff tools"),Array.isArray(e.edges)||u("edges must be an array");let b=new Set,A=new Map([...n].map(i=>[i,[]])),x=e.edges.map(i=>{G(i,"edge"),z(i.from,"edge source"),z(i.to,"edge target");let E=ae(i.artifactKind);(!n.has(i.from)||!n.has(i.to))&&u("broken edge references unknown agent"),i.from===i.to&&u("cycle in team DAG");let O=`${i.from}\0${i.to}\0${E}`;return b.has(O)&&u("duplicate edge"),b.add(O),A.get(i.from).push(i.to),{from:i.from,to:i.to,artifactKind:E}}),k=new Set,h=new Set;function H(i){if(k.has(i)&&u("cycle in team DAG"),!h.has(i)){k.add(i);for(let E of A.get(i))H(E);k.delete(i),h.add(i)}}for(let i of n)H(i);A.get(l.id).length&&u("executor must be the terminal team agent");let T=i=>{let E=[i],O=new Set;for(;E.length;){let g=E.shift();if(g===l.id)return!0;O.has(g)||(O.add(g),E.push(...A.get(g)))}return!1};for(let i of n)T(i)||u(`agent ${i} is disconnected from executor`);let $=s.filter(i=>!x.some(E=>E.to===i.id));$.length!==1&&u("team pipeline requires exactly one root agent");for(let i of s){let E=x.filter(g=>g.to===i.id).length,O=x.filter(g=>g.from===i.id).length;(i.id===$[0].id?E!==0:E!==1)&&u("team pipeline requires exactly one incoming handoff per non-root agent"),(i.id===l.id?O!==0:O!==1)&&u("team pipeline requires exactly one outgoing handoff per non-executor agent")}let j=x.filter(i=>i.to===l.id);(j.length!==1||j[0].artifactKind!=="approved-intent")&&u("executor requires exactly one approved-intent input"),s.find(i=>i.id===j[0].from)?.runtime!=="policy"&&u("executor input must come from a policy agent");let R=se(e.policy,{nowMs:t,mode:e.mode}),W=y({id:e.id,name:e.name,mode:e.mode,agents:s,edges:x,policy:R});return q({team:W,teamHash:V(W),execution:{executionAllowed:!1,backendSigner:!1,signingReady:!1,broadcastReady:!1,requiresOperatorConfirmation:!0}})}var Xe=/^[a-z0-9][a-z0-9._:-]{0,127}$/i,Ze=/^[0-9a-f]{64}$/,Qe=/^evidence:sha256:[0-9a-f]{64}$/,et=new Set(["approved-intent","prepared-intent","prepared-basket"]),tt=new Set(["perp-order","hip3-order","hip4-order","perp-bracket"]),rt=/^[A-Za-z0-9@:_./-]{1,64}$/;function X(e,t){if(typeof e!="string"||!Xe.test(e))throw new TypeError(`${t} is invalid`);return e}function nt(e,t){if(typeof e!="string"||!Ze.test(e))throw new TypeError(`${t} is invalid`);return e}function Z(e,t){if(!e||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)throw new TypeError(`${t} must be a plain object`)}function ye(e,t,n){for(let s of Object.keys(e))if(!t.has(s))throw new TypeError(`${n}.${s} is not allowed`)}function D(e,t,{allowZero:n=!1}={}){if(!Number.isFinite(e)||(n?e<0:e<=0))throw new TypeError(`${t} must be ${n?"non-negative":"positive"}`);let s=e*100;if(!Number.isSafeInteger(Math.round(s))||Math.abs(s-Math.round(s))>1e-8)throw new TypeError(`${t} must use exact USD cents`);return Math.round(s)}function ot(e,t,{nowMs:n,expiresAt:s}){if(Z(e,"basket leg artifact"),e.version!==1)throw new TypeError("basket leg artifact must be version 1");if(e.surface!=="hl")throw new TypeError("basket leg artifact surface must be hl");if(e.action!=="order"||e.destination!=="hyperliquid")throw new TypeError("basket leg artifact must be a Hyperliquid order");if(!Number.isSafeInteger(e.expiresAtMs)||e.expiresAtMs<=n||e.expiresAtMs>s)throw new TypeError("basket leg artifact expiry must fit the handoff TTL");if(Z(e.artifact,"basket leg artifact payload"),!tt.has(e.artifact.kind))throw new TypeError("basket leg artifact kind is not an order");if(e.artifact.coin!==t.market)throw new TypeError("basket leg artifact market mismatch");if(e.artifact.side!==t.side)throw new TypeError("basket leg artifact side mismatch");if(D(e.artifact.notionalUsd,"basket leg artifact notional")!==D(t.notionalUsd,"basket leg notional"))throw new TypeError("basket leg artifact notional mismatch")}function it(e,t,n){let s=e.executionPlan;if(s===void 0){if(n.mode==="armed")throw new TypeError("armed intent requires an exact execution plan");return}if(e.chainId!=="hyperliquid")throw new TypeError("armed execution plans require the Hyperliquid chain");if(e.intentType!=="perp"&&e.intentType!=="basket")throw new TypeError("intentType must be perp or basket");if(Z(s,"executionPlan"),ye(s,new Set(["atomic","partialFillRiskAcknowledged","legs"]),"executionPlan"),s.atomic!==!1)throw new TypeError("basket and perp plans must be explicitly non-atomic");if(!Array.isArray(s.legs))throw new TypeError("executionPlan.legs must be an array");let p=e.intentType==="basket"?2:1,l=e.intentType==="basket"?12:1;if(s.legs.length<p||s.legs.length>l)throw new TypeError(`${e.intentType} execution plan requires ${p}-${l} legs`);if(e.intentType==="basket"&&s.partialFillRiskAcknowledged!==!0)throw new TypeError("basket partial-fill risk must be acknowledged");if(e.intentType==="perp"&&typeof s.partialFillRiskAcknowledged!="boolean")throw new TypeError("perp partial-fill risk acknowledgement must be boolean");let b=new Set,A=0,x=0;for(let[k,h]of s.legs.entries()){if(Z(h,`executionPlan.legs[${k}]`),ye(h,new Set(["market","side","notionalUsd","weightBps","artifact"]),`executionPlan.legs[${k}]`),typeof h.market!="string"||!rt.test(h.market))throw new TypeError("basket leg market is invalid");if(b.has(h.market))throw new TypeError(`duplicate basket market ${h.market}`);if(b.add(h.market),h.side!=="buy"&&h.side!=="sell")throw new TypeError("basket leg side must be buy or sell");if(A+=D(h.notionalUsd,"basket leg notional"),!Number.isSafeInteger(h.weightBps)||h.weightBps<=0||h.weightBps>1e4)throw new TypeError("basket leg weight must be positive basis points");x+=h.weightBps,ot(h.artifact,h,n)}if(x!==1e4)throw new TypeError("basket leg weights must sum to 10000 bps");if(A!==D(e.notionalUsd,"intent notional"))throw new TypeError("basket aggregate notional must equal the exact leg sum");if(A>D(t.maxNotionalUsd,"policy maxNotionalUsd"))throw new TypeError("basket aggregate notional exceeds policy cap")}function at(e,t,n){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("intent payload must be an object");if(typeof e.chainId!="string"||!t.chainAllowlist.includes(e.chainId))throw new TypeError("intent chain is outside policy allowlist");if(!Number.isFinite(e.notionalUsd)||e.notionalUsd<=0||e.notionalUsd>t.maxNotionalUsd)throw new TypeError("intent notional exceeds policy cap");if(!Number.isFinite(e.maxLossUsd)||e.maxLossUsd<0||e.maxLossUsd>t.maxDailyLossUsd)throw new TypeError("intent loss exceeds policy cap");D(e.notionalUsd,"intent notional"),D(e.maxLossUsd,"intent max loss",{allowZero:!0}),it(e,t,n)}function de(e,{compiled:t}={}){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("handoff must be an object");if(!t?.team||typeof t.teamHash!="string")throw new TypeError("compiled team snapshot is required");let n=e.nowMs??Date.now();if(!Number.isSafeInteger(n))throw new TypeError("nowMs is invalid");if(!Number.isSafeInteger(e.ttlMs)||e.ttlMs<=0||e.ttlMs>6e4)throw new TypeError("TTL must be bounded to 60 seconds");let s=X(e.teamId,"teamId"),p=nt(e.teamHash,"teamHash");if(t.team.id!==s||t.teamHash!==p)throw new TypeError("handoff team snapshot mismatch");let l=X(e.sourceAgentId,"sourceAgentId"),b=X(e.targetAgentId,"targetAgentId"),A=ae(e.artifactKind);if(!t.team.edges.some($=>$.from===l&&$.to===b&&$.artifactKind===A))throw new TypeError("handoff does not match compiled team edge");if(!Array.isArray(e.evidenceRefs)||!e.evidenceRefs.length)throw new TypeError("evidenceRefs must be non-empty");let x=e.evidenceRefs.map($=>{if(typeof $!="string"||!Qe.test($))throw new TypeError("evidence reference must be a SHA-256 content hash");return $});if(new Set(x).size!==x.length)throw new TypeError("duplicate evidence reference");let k=y(e.payload),h=se(t.team.policy,{nowMs:n,mode:t.team.mode}),H=n+e.ttlMs;if(H>h.expiresAt)throw new TypeError("handoff TTL exceeds policy expiry");et.has(A)&&at(k,h,{mode:t.team.mode,nowMs:n,expiresAt:H});let T={teamId:s,teamHash:p,runId:X(e.runId,"runId"),sourceAgentId:l,targetAgentId:b,artifactKind:A,payload:k,payloadHash:V(k),evidenceRefs:x,ttlMs:e.ttlMs,issuedAt:n,expiresAt:H,policy:h,policyHash:V(h)};return q(y({...T,handoffHash:V(T),executionAllowed:!1,backendSigner:!1,signingReady:!1,broadcastReady:!1,requiresOperatorConfirmation:!0}))}import{createHash as ge,randomUUID as st}from"node:crypto";function ct(e,t,n){let s=ge("sha256").update(JSON.stringify(t)).digest("hex");return`sha256:${ge("sha256").update(`${e}\0${s}\0${n}`).digest("hex")}`}function dt(e){return{...y({compiled:e.compiled,currentAgentId:e.currentAgentId,previousHandoffHash:e.previousHandoffHash,executionConsumed:e.executionConsumed,confirmationPending:!1}),consumedHandoffHashes:[...e.consumedHandoffHashes]}}function ft(e){return{...y(e),consumedHandoffHashes:new Set(e?.consumedHandoffHashes||[]),confirmationPending:!1}}function fe(e){return{...y({compiled:e.compiled,currentAgentId:e.currentAgentId,previousHandoffHash:e.previousHandoffHash,executionConsumed:e.executionConsumed,confirmationPending:e.confirmationPending}),consumedHandoffHashes:new Set(e.consumedHandoffHashes)}}function K(e,t,n){if(n>=t.compiled.team.policy.expiresAt)throw e.status="expired",e.updatedAt=n,new Error("team policy expired")}function le(e,t){e.clear();for(let[n,s]of t)e.set(n,s)}function lt({now:e=Date.now,storage:t,stateStore:n,tenantId:s="local-owner",executionAdapter:p}={}){let l=String(s||"").trim();if(!l)throw new TypeError("tenantId is required");let b=t??new Map,A=new Map,x=new Map,k=!n,h=null,H=0,T=Promise.resolve(),$=async(r,o)=>b.set(r,y(o)),j=async r=>b.get(r),F=async()=>b instanceof Map?[...b.values()]:b.list(),R=r=>q(y(r));function W(r){let o=T.then(r,r);return T=o.catch(()=>{}),o}function i(){if(!(b instanceof Map)){if(n)throw new Error("durable team state requires map-backed definitions");return{definitions:null,runs:new Map([...A].map(([r,o])=>[r,y(o)])),contexts:new Map([...x].map(([r,o])=>[r,fe(o)]))}}return{definitions:new Map([...b].map(([r,o])=>[r,y(o)])),runs:new Map([...A].map(([r,o])=>[r,y(o)])),contexts:new Map([...x].map(([r,o])=>[r,fe(o)]))}}function E(r,o){return{version:1,revision:o,tenantId:l,definitions:[...r.definitions.values()].map(y),runs:[...r.runs.values()].map(y),contexts:[...r.contexts.entries()].map(([w,d])=>({runId:w,context:dt(d)}))}}function O(r){r.definitions&&le(b,r.definitions),le(A,r.runs),le(x,r.contexts)}function g(r,{persist:o=!0}={}){return W(async()=>{let w=i(),d=r(w),a=H;if(o&&n){let f=H;a=(await n.save(E(w,f),{expectedRevision:f})).revision}return O(w),H=a,d})}async function C(){k||(h||(h=(async()=>{let r=await n.load();if(r.tenantId!==l)throw new Error("team state tenant mismatch");if(!Number.isSafeInteger(r.revision)||r.revision<0)throw new Error("team state revision is invalid");if(!(b instanceof Map))throw new Error("durable team state requires map-backed definitions");let o={definitions:new Map,runs:new Map,contexts:new Map};for(let a of r.definitions)o.definitions.set(a.team.id,y(a));for(let a of r.runs)o.runs.set(a.id,y(a));for(let a of r.contexts)o.contexts.set(a.runId,ft(a.context));let w=!1;for(let a of o.runs.values()){if(!(a.status==="executing"||a.attempts?.some(m=>m.status==="submission-unknown")))continue;a.status="reconciliation-required",a.executionAllowed=!1,a.requiresOperatorConfirmation=!1,a.uncertainExecution=!0,a.updatedAt=e();let c=o.contexts.get(a.id);c&&(c.executionConsumed=!0,c.confirmationPending=!1),w=!0}let d=r.revision;w&&(d=(await n.save(E(o,d),{expectedRevision:d})).revision),O(o),H=d,k=!0})()),await h)}async function B(){if(typeof p?.status!="function")throw new Error("armed mode requires a local execution adapter");let r=await p.status();if(!r?.configured||!r?.reachable||r?.armed!==!0)throw new Error("local signer is not armed and reachable");if(typeof p?.executeConfirmedArtifact!="function")throw new Error("armed mode requires a local execution adapter");return r}return Object.freeze({async save(r){await C();let o=ce(r,{nowMs:e()});if(!(b instanceof Map))return await $(o.team.id,o),R(o);let w=await g(d=>(d.definitions.set(o.team.id,y(o)),d.definitions.get(o.team.id)));return R(w)},async list(){return await C(),R(await F())},async get(r){await C();let o=await j(r);return o===void 0?null:R(o)},async getRun(r){await C();let o=A.get(r);return o===void 0?null:R(o)},async start(r){await C();let o=await j(r);if(!o)throw new Error(`unknown team ${r}`);let w=q(y(o));w.team.mode==="armed"&&await B();let d=await g(a=>{let f=a.definitions?a.definitions.get(r):w;if(!f)throw new Error(`unknown team ${r}`);if(f.team.mode==="draft")throw new Error("draft team must be promoted before running");if(f.team.mode==="halted")throw new Error("team kill switch is active");let c=e();if(c>=f.team.policy.expiresAt)throw new Error("team policy expired");let m=f.team.mode==="armed",S=f.team.agents.find(M=>!f.team.edges.some(I=>I.to===M.id));if(!S)throw new Error("team pipeline has no root agent");let v={id:st(),tenantId:l,teamId:r,teamHash:f.teamHash,status:f.team.mode==="shadow"?"shadowing":"running",mode:f.team.mode,armed:m,startedAt:c,updatedAt:c,expiresAt:f.team.policy.expiresAt,maxSteps:f.team.edges.length,steps:[],receipts:[],attempts:[],executionAllowed:!1,backendSigner:m,signingReady:m,broadcastReady:m,requiresOperatorConfirmation:!0,signed:!1,broadcast:!1};return a.runs.set(v.id,v),a.contexts.set(v.id,{compiled:q(y(f)),currentAgentId:S.id,previousHandoffHash:null,consumedHandoffHashes:new Set,executionConsumed:!1,confirmationPending:!1}),v});return R(d)},async step(r,o){await C();let w=await g(d=>{let a=d.runs.get(r),f=d.contexts.get(r);if(!a||!f)throw new Error(`unknown run ${r}`);if(a.status==="halted")throw new Error("run is halted");if(a.status==="paused")throw new Error("run is paused");if(a.status!=="running"&&a.status!=="shadowing")throw new Error("run cannot step from its current state");let c=e();if(K(a,f,c),a.steps.length>=a.maxSteps)throw new Error("run step budget exhausted");if(o?.agentId!==f.currentAgentId)throw new TypeError("step agent is out of order");let m=f.compiled.team.edges.find(I=>I.from===o.agentId);if(!m||m.to!==o?.targetAgentId||m.artifactKind!==o?.artifactKind)throw new TypeError("artifact does not match the exact next team edge");let S,v=null;if(f.previousHandoffHash===null){if(o.inputHandoffHash!==void 0)throw new TypeError("root step cannot consume a prior handoff");S=o.evidenceRefs}else{if(o.inputHandoffHash!==f.previousHandoffHash)throw new TypeError("step must consume the exact prior handoff");if(f.consumedHandoffHashes.has(o.inputHandoffHash))throw new TypeError("handoff was already consumed");v=o.inputHandoffHash,S=[`evidence:sha256:${o.inputHandoffHash}`]}let M=de({teamId:a.teamId,teamHash:a.teamHash,runId:r,sourceAgentId:m.from,targetAgentId:m.to,artifactKind:m.artifactKind,payload:o.payload,evidenceRefs:S,ttlMs:o.ttlMs,nowMs:c},{compiled:f.compiled});return v!==null&&f.consumedHandoffHashes.add(v),a.steps.push(M),a.updatedAt=c,f.currentAgentId=m.to,f.previousHandoffHash=M.handoffHash,m.to===f.compiled.team.agents.find(I=>I.role==="executor").id&&(a.status=a.mode==="armed"?"awaiting-confirmation":"prepared",a.preparedAt=c,a.mode!=="armed"&&(a.completedAt=c)),a});return R(w)},async confirm(r,o){await C();let w=await g(d=>{let a=d.runs.get(r),f=d.contexts.get(r);if(!a||!f)throw new Error(`unknown run ${r}`);if(a.status==="halted")throw new Error("run is halted");if(a.status!=="awaiting-confirmation")throw new Error("run cannot confirm from its current state or was already executed");let c=e();K(a,f,c);let m=a.steps.at(-1);if(!m||m.artifactKind!=="approved-intent")throw new Error("approved intent handoff is required");if(c>=m.expiresAt)throw new Error("approved intent handoff expired");if(o?.handoffHash!==m.handoffHash)throw new TypeError("confirmation must bind the exact handoff hash");if(o?.operatorConfirmed!==!0||o?.sign!==!0||o?.broadcast!==!0)throw new TypeError("explicit confirm, sign, and broadcast instruction is required");if(f.executionConsumed||f.confirmationPending)throw new Error("approved intent is already executing or was already executed");return f.confirmationPending=!0,y(m)},{persist:!1});try{await B();let d=w.payload?.executionPlan?.legs;if(!Array.isArray(d)||!d.length)throw new Error("approved intent has no executable legs");await g(f=>{let c=f.runs.get(r),m=f.contexts.get(r);if(!c||!m)throw new Error(`unknown run ${r}`);let S=e();if(K(c,m,S),c.status==="halted")throw new Error("run was halted before execution");if(c.status!=="awaiting-confirmation")throw new Error("run cannot confirm from its current state");if(!m.confirmationPending||m.executionConsumed)throw new Error("approved intent is already executing or was already executed");if(S>=w.expiresAt)throw new Error("approved intent handoff expired");m.executionConsumed=!0,c.status="executing",c.updatedAt=S});for(let[f,c]of d.entries()){let m=ct(l,c.artifact,f);await g(I=>{let _=I.runs.get(r),L=I.contexts.get(r);if(!_||!L)throw new Error(`unknown run ${r}`);if(_.status==="halted")throw new Error("run was halted during sequential basket execution");if(_.status!=="executing")throw new Error("run cannot execute from its current state");let J=e();if(K(_,L,J),J>=w.expiresAt)throw new Error("approved intent handoff expired during execution");_.attempts[f]={legIndex:f,idempotencyKey:m,status:"submission-unknown",submittedAt:J},_.updatedAt=J});let S=await p.executeConfirmedArtifact(y(c.artifact),{tenantId:l,runId:r,handoffHash:w.handoffHash,idempotencyKey:m,legIndex:f,legCount:d.length});await g(I=>{let _=I.runs.get(r);if(!_)throw new Error(`unknown run ${r}`);let L=_.attempts[f];if(!L||L.idempotencyKey!==m)throw new Error("execution attempt state changed before receipt persistence");L.status="receipt-recorded",L.receipt=y(S),L.receivedAt=e(),_.receipts.push(y(S)),_.updatedAt=L.receivedAt});let v=A.get(r),M=x.get(r);if(v?.status==="halted")throw new Error("run was halted during sequential basket execution");if(!v||!M)throw new Error(`unknown run ${r}`);if(K(y(v),fe(M),v.updatedAt),v.updatedAt>=w.expiresAt)throw new Error("approved intent handoff expired during execution")}let a=await g(f=>{let c=f.runs.get(r),m=f.contexts.get(r);if(!c||!m)throw new Error(`unknown run ${r}`);if(c.status==="halted")throw new Error("run was halted during sequential basket execution");if(c.status!=="executing")throw new Error("run cannot complete from its current state");if(K(c,m,c.updatedAt),c.updatedAt>=w.expiresAt)throw new Error("approved intent handoff expired during execution");return c.status="completed",c.executionAllowed=!1,c.requiresOperatorConfirmation=!1,c.signed=!0,c.broadcast=!0,c.completedAt=e(),c.updatedAt=c.completedAt,c});return R(a)}catch(d){if(x.get(r)?.executionConsumed)try{await g(f=>{let c=f.runs.get(r),m=f.contexts.get(r);if(!c||!m)return;let S=c.attempts.some(v=>v.status==="submission-unknown");c.status!=="halted"&&c.status!=="expired"&&(c.status=S?"reconciliation-required":"failed"),c.executionAllowed=!1,c.uncertainExecution=S,c.partialExecution=c.receipts.length>0,c.error=d instanceof Error?d.message:"local execution failed",c.updatedAt=e()})}catch{}throw d}finally{await g(d=>{let a=d.contexts.get(r);a&&(a.confirmationPending=!1)},{persist:!1})}},async pause(r){await C();let o=await g(w=>{let d=w.runs.get(r);if(!d)throw new Error(`unknown run ${r}`);if(d.status!=="running"&&d.status!=="shadowing")throw new Error("only an active run can be paused");return d.resumeStatus=d.status,d.status="paused",d.updatedAt=e(),d});return R(o)},async resume(r){await C();let o=await g(w=>{let d=w.runs.get(r),a=w.contexts.get(r);if(!d||!a)throw new Error(`unknown run ${r}`);if(d.status!=="paused")throw new Error("only a paused run can be resumed");let f=e();return K(d,a,f),d.status=d.resumeStatus==="shadowing"?"shadowing":"running",delete d.resumeStatus,d.updatedAt=f,d});return R(o)},async halt(r){await C();let o=await g(w=>{let d=w.runs.get(r);if(!d)throw new Error(`unknown run ${r}`);return d.status="halted",delete d.resumeStatus,d.updatedAt=e(),d});return R(o)}})}import{closeSync as Q,constants as N,fchmodSync as Ae,fsyncSync as pe,lstatSync as ve,mkdirSync as Et,openSync as me,readFileSync as Tt,renameSync as Ot,rmSync as ke,writeFileSync as Ee}from"node:fs";import{createHash as St,randomBytes as vt}from"node:crypto";import{homedir as Ht}from"node:os";import{dirname as $t,join as he,resolve as Ct}from"node:path";import{wordlists as ut}from"ethers";var pt=new Set(["privatekey","privkey","secretkey","seedphrase","seed","mnemonic","passphrase","password","keystore","keymaterial","wif","xprv","xpriv","bearer","authorization","signature","apikey","credential"]),mt=[/\b[5KL][1-9A-HJ-NP-Za-km-z]{50,51}\b/,/\bxprv[0-9A-Za-z]{50,}\b/],ht=new Set([12,15,18,21,24]);function wt(e){let t=String(e).trim().toLowerCase().split(/\s+/).filter(Boolean);return ht.has(t.length)&&t.every(n=>ut.en.getWordIndex(n)>=0)}var yt=/^\s*(?:0x)?[0-9a-fA-F]{64}\s*$/,gt=/(hash|digest|root|salt|nonce|proof|commitment|sig|id)(?:e?s)?$/i,bt=new Set(["calldata","data","publickey","pubkey","message","payload","input","extradata"]);function xt(e){let t=be(e);return bt.has(t)||gt.test(t)}var Y=class extends Error{constructor(t){super(`action receipt refused: secret-bearing field at ${t}`),this.name="ActionReceiptSecretError",this.code="ACTION_RECEIPT_SECRET"}};function be(e){return String(e).replace(/[^a-z0-9]/gi,"").toLowerCase()}function At(e){let t=be(e);return[...pt].some(n=>t.includes(n))}function kt(e,t,n){if(typeof t=="string"){if(mt.some(s=>s.test(t))||wt(t))throw new Y(n);if(yt.test(t)&&!xt(e))throw new Y(n)}}function ue(e,t="$",n=""){if(e==null||typeof e=="boolean")return e;if(typeof e=="string")return kt(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((p,l)=>ue(p,`${t}[${l}]`,n));if(typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype)throw new TypeError(`action receipt: JSON-like value required at ${t}`);let s={};for(let p of Object.keys(e).sort()){let l=`${t}.${p}`;if(At(p))throw new Y(l);e[p]!==void 0&&(s[p]=ue(e[p],l,p))}return s}function xe(e){return ue(e)}var He=1,Te=N.O_NOFOLLOW??0;function Rt(e){let t=String(e||"").trim();if(!t||t.length>200||/[\u0000-\u001f\u007f]/.test(t))throw new TypeError("tenantId is required");return t}function $e(e){return e==null?e:structuredClone(e)}function Ce(e,t,n=!1){let s=n?!e.isDirectory():!e.isFile(),p=typeof process.getuid=="function"&&e.uid!==process.getuid();if(e.isSymbolicLink()||s||p||(e.mode&18)!==0)throw new Error(`${t} must be an owner-controlled ${n?"directory":"regular file"}`)}function Oe(e){Et(e,{recursive:!0,mode:448});let t=ve(e);Ce(t,"team state directory",!0)}function _t(e,t){let n=St("sha256").update(t).digest("hex");return he(e,`${n}.json`)}function Re(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("team state snapshot must be an object");if(e.version!==He||e.tenantId!==t)throw new TypeError("team state tenant or version mismatch");if(!Number.isSafeInteger(e.revision)||e.revision<0)throw new TypeError("team state revision must be a non-negative safe integer");for(let n of["definitions","runs","contexts"])if(!Array.isArray(e[n]))throw new TypeError(`team state ${n} must be an array`);return xe(e),$e(e)}function It(e){return{version:He,revision:0,tenantId:e,definitions:[],runs:[],contexts:[]}}function Se(e,t){try{let n=ve(e);if(Ce(n,"team state file"),n.size>16*1024*1024)throw new Error("team state file is too large");return Re(JSON.parse(Tt(e,"utf8")),t)}catch(n){if(n?.code==="ENOENT")return It(t);throw n}}function _e(e=process.env){let t=String(e?.ORACLE_CONFIG_DIR||"").trim()||he(Ht(),".config","oracle");return he(t,"teams","state")}function jt(e={}){let{rootDir:t=_e(),tenantId:n}=e,s=Rt(n),p=Ct(t),l=_t(p,s),b=`${l}.lock`;return Object.freeze({tenantId:s,file:l,async load(){return Oe(p),Se(l,s)},async save(A,{expectedRevision:x}={}){if(Oe(p),!Number.isSafeInteger(x)||x<0)throw new TypeError("team state expectedRevision must be a non-negative safe integer");let k,h=!1,H=`${l}.${process.pid}.${vt(8).toString("hex")}.tmp`,T;try{k=me(b,N.O_CREAT|N.O_EXCL|N.O_WRONLY|Te,384),h=!0,Ee(k,`${process.pid}
2
+ `,"utf8"),pe(k),Ae(k,384);let $=Se(l,s);if($.revision!==x)throw new Error(`team state changed: stale revision ${x}; current revision ${$.revision}`);let j=Re({...A,revision:x+1},s);T=me(H,N.O_CREAT|N.O_EXCL|N.O_WRONLY|Te,384),Ee(T,`${JSON.stringify(j)}
3
+ `,"utf8"),pe(T),Ae(T,384),Q(T),T=void 0,Ot(H,l);let F=me($t(l),N.O_RDONLY);try{pe(F)}finally{Q(F)}return $e(j)}finally{T!==void 0&&Q(T),ke(H,{force:!0}),k!==void 0&&Q(k),h&&ke(b,{force:!0})}}})}export{Le as BASKET_STRATEGY_CATALOG,ne as CRYPTO_SKILL_CATALOG,re as CRYPTO_TOOL_CATALOG,Ie as MARKET_BREADTH_CATALOG,te as MODEL_PROVIDER_CATALOG,je as PERP_SIGNAL_CATALOG,ee as TEAM_MODES,Me as TEAM_TEMPLATES,ce as compileTeamDefinition,jt as createDurableTeamStore,de as createTeamHandoff,lt as createTeamService,_e as defaultTeamStateRoot};