@oracle-agent/oracle 0.24.1 → 0.24.2

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 (45) hide show
  1. package/dist/assets/skills/chain/SKILL.md +34 -0
  2. package/dist/assets/skills/chain-defi-ecosystem-analysis/SKILL.md +181 -0
  3. package/dist/assets/skills/chain-ecosystem-gap-analysis/SKILL.md +162 -0
  4. package/dist/assets/skills/cross-chain-twap-execution/SKILL.md +125 -0
  5. package/dist/assets/skills/defi-protocol-pmf-assessment/SKILL.md +332 -0
  6. package/dist/assets/skills/evm-contract-research.md +8 -3
  7. package/dist/assets/skills/multi-venue-prepare-only-ranking/SKILL.md +93 -0
  8. package/dist/assets/skills/oracle-access-control/SKILL.md +71 -0
  9. package/dist/assets/skills/oracle-action-arming/SKILL.md +99 -0
  10. package/dist/assets/skills/oracle-airdrop-calculator/SKILL.md +111 -0
  11. package/dist/assets/skills/oracle-desk-product/SKILL.md +341 -0
  12. package/dist/assets/skills/oracle-evm/SKILL.md +55 -0
  13. package/dist/assets/skills/oracle-harness/SKILL.md +41 -0
  14. package/dist/assets/skills/oracle-mcp-install/SKILL.md +140 -0
  15. package/dist/assets/skills/oracle-multichain-convert/SKILL.md +87 -0
  16. package/dist/assets/skills/oracle-native-harness/SKILL.md +32 -0
  17. package/dist/assets/skills/oracle-ownership-gate/SKILL.md +42 -0
  18. package/dist/assets/skills/oracle-public-product-ux/SKILL.md +114 -0
  19. package/dist/assets/skills/oracle-tailscale/SKILL.md +32 -0
  20. package/dist/assets/skills/oracle-thin-client/SKILL.md +47 -0
  21. package/dist/assets/skills/perp-venue-funding-research/SKILL.md +161 -0
  22. package/dist/assets/skills/polymarket/SKILL.md +160 -0
  23. package/dist/assets/skills/protocol-api-key-integration/SKILL.md +141 -0
  24. package/dist/assets/skills/self-custodial-onchain-execution/SKILL.md +1284 -0
  25. package/dist/assets/skills/setup/SKILL.md +40 -0
  26. package/dist/assets/skills/stable-launch-ops/SKILL.md +89 -0
  27. package/dist/assets/skills/trade-loop-circuit-breaker/SKILL.md +441 -0
  28. package/dist/assets/skills/venue-capability-boundaries/SKILL.md +32 -0
  29. package/dist/bin/desk-server.mjs +16 -16
  30. package/dist/bin/oracle-data-mcp.mjs +1 -1
  31. package/dist/bin/oracle-equities.mjs +1 -1
  32. package/dist/bin/oracle-init.mjs +9 -9
  33. package/dist/cli/commands/bootstrap.mjs +1 -1
  34. package/dist/cli/commands/chat.mjs +78 -77
  35. package/dist/cli/commands/doctor.mjs +8 -6
  36. package/dist/cli/commands/eval.mjs +1 -1
  37. package/dist/cli/commands/harness.mjs +6 -6
  38. package/dist/cli/commands/model.mjs +82 -81
  39. package/dist/cli/commands/receipt.mjs +5 -0
  40. package/dist/cli/commands/setup.mjs +1 -1
  41. package/dist/cli/commands/venues.mjs +3 -0
  42. package/dist/cli/commands/watch.mjs +16 -0
  43. package/dist/equities/index.mjs +1 -1
  44. package/dist/index.mjs +1 -1
  45. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{realpathSync as wt}from"node:fs";import{fileURLToPath as br}from"node:url";var $r=Object.freeze({mantissa:10000n,scale:0});function P(e){if(!Number.isSafeInteger(e)||e<0||e>1e3)throw new RangeError("scale must be a safe integer from 0 through 1000")}function T(e,t){if(typeof e!="bigint")throw new TypeError("mantissa must be a bigint");return P(t),Object.freeze({mantissa:e,scale:t})}function N(e,t="value"){if(e===null||typeof e!="object")throw new TypeError(`${t} must be a fixed point value`);if(typeof e.mantissa!="bigint")throw new TypeError(`${t}.mantissa must be a bigint`);P(e.scale)}function Y(e){return P(e),10n**BigInt(e)}function f(e){if(typeof e!="string"||!/^[+-]?\d+(?:\.\d+)?$/.test(e))throw new TypeError("value must be a plain decimal string");let t=e.startsWith("-"),n=e[0]==="-"||e[0]==="+"?e.slice(1):e,[r,s=""]=n.split("."),o=`${r}${s}`,i=BigInt(o)*(t?-1n:1n);return T(i,s.length)}function $(e,t){if(P(t),typeof e=="bigint")return T(e,t);if(typeof e!="string"||!/^[+-]?\d+$/.test(e))throw new TypeError("value must be an integer string or bigint");return T(BigInt(e),t)}function S(e){N(e);let t=e.mantissa<0n,n=(t?-e.mantissa:e.mantissa).toString();if(e.scale===0)return`${t?"-":""}${n}`;let r=n.padStart(e.scale+1,"0"),s=r.length-e.scale;return`${t?"-":""}${r.slice(0,s)}.${r.slice(s)}`}function W(e,t){return N(e),P(t),t===e.scale?T(e.mantissa,e.scale):t>e.scale?T(e.mantissa*Y(t-e.scale),t):T(e.mantissa/Y(e.scale-t),t)}function ce(e,t){N(e,"left"),N(t,"right");let n=Math.max(e.scale,t.scale);return[W(e,n),W(t,n),n]}function D(e,t){let[n,r,s]=ce(e,t);return T(n.mantissa+r.mantissa,s)}function Q(e,t){let[n,r,s]=ce(e,t);return T(n.mantissa-r.mantissa,s)}function E(e,t){N(e,"left"),N(t,"right");let n=e.scale+t.scale;return P(n),T(e.mantissa*t.mantissa,n)}function R(e,t,n=Math.max(e?.scale??0,t?.scale??0)){if(N(e,"left"),N(t,"right"),P(n),t.mantissa===0n)throw new RangeError("division by zero");let r=e.mantissa*Y(t.scale+n),s=t.mantissa*Y(e.scale);return T(r/s,n)}function M(e,t){let[n,r]=ce(e,t);return n.mantissa<r.mantissa?-1:n.mantissa>r.mantissa?1:0}import{readFileSync as It,existsSync as Tt}from"node:fs";import{fileURLToPath as _t}from"node:url";import{dirname as Nt,join as Me}from"node:path";import{existsSync as _e,readFileSync as qt}from"node:fs";import{dirname as Te,join as le}from"node:path";import{fileURLToPath as Ot}from"node:url";function Rt(e){let t=Te(Ot(e));for(let n=0;n<8;n+=1){let r=le(t,"package.json");if(_e(r))try{let o=JSON.parse(qt(r,"utf8"));if(o&&typeof o.version=="string")return t}catch{}let s=Te(t);if(s===t)break;t=s}throw new Error(`oracle: could not resolve package root from ${e}`)}function Ne(e,t){let n=Rt(t),r=le(n,"dist","assets",e);return _e(r)?r:le(n,e)}var Dt=Me(Nt(_t(import.meta.url)),"fixtures");function Mt(){try{let e=Ne("equities-fixtures",import.meta.url);if(e&&Tt(e))return e}catch{}return Dt}var Ut=Mt();var Ue=Object.freeze({venues:"venues.json",universe:"universe.json",oracles:"oracles.json",nyseHolidays:"nyse_holidays.json",dstTransitions:"dst_transitions.json",equityDexPools:"equity_dex_pools.json",rhPoolState:"rh_pool_state.json",solanaXstocks:"solana_xstocks.json",tonXstocks:"ton_xstocks.json",hip3L2Books:"hip3_l2books.json"});function jt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function d(e,t){throw new TypeError(`Fixture fixtures/${e}: ${t}`)}function k(e,t,n){jt(e)||d(t,`${n} must be an object`)}function m(e,t,n){(typeof e!="string"||e.length===0)&&d(t,`${n} must be a nonempty string`)}function _(e,t,n){Number.isSafeInteger(e)||d(t,`${n} must be a safe integer`)}function U(e,t,n){k(e,t,n);for(let[r,s]of Object.entries(e))m(r,t,`${n} key`),k(s,t,`${n}.${r}`)}function Ft(e,t){k(e,t,"root"),_(e.capturedAt,t,"capturedAt"),k(e.venues,t,"venues");let n=[["hyperliquid_hip3","dexs"],["arcus","markets"],["arcus_spot","pairs"],["rh_uniswap","pools"],["rh_chainlink_oracles","assets"]];for(let[r,s]of n){let o=e.venues[r];k(o,t,`venues.${r}`),m(o.type,t,`venues.${r}.type`),m(o.chain,t,`venues.${r}.chain`),m(o.tier,t,`venues.${r}.tier`),U(o[s],t,`venues.${r}.${s}`)}for(let[r,s]of Object.entries(e.venues.hyperliquid_hip3.dexs))U(s,t,`venues.hyperliquid_hip3.dexs.${r}`)}function Pt(e,t){U(e,t,"root"),Object.keys(e).length===0&&d(t,"root must not be empty");for(let[n,r]of Object.entries(e))Array.isArray(r.venues)||d(t,`${n}.venues must be an array`),r.venues.forEach((s,o)=>m(s,t,`${n}.venues[${o}]`))}function Bt(e,t){k(e,t,"root");for(let n of["chainId","block","oracleScaleExp","usdgDecimals","equityDecimals"])_(e[n],t,n);m(e.usdg,t,"usdg"),U(e.assets,t,"assets");for(let[n,r]of Object.entries(e.assets))m(r.oracle,t,`assets.${n}.oracle`),m(r.token,t,`assets.${n}.token`),(typeof r.rawPrice!="string"||!/^\d+$/.test(r.rawPrice))&&d(t,`assets.${n}.rawPrice must be an integer string`),(typeof r.usd!="number"||!Number.isFinite(r.usd)||r.usd<0)&&d(t,`assets.${n}.usd must be a nonnegative finite source number`)}function Ct(e,t){k(e,t,"root");for(let r of["holidayDayIndex","names","dates"])Array.isArray(e[r])||d(t,`${r} must be an array`);let n=e.holidayDayIndex.length;(e.names.length!==n||e.dates.length!==n)&&d(t,"holidayDayIndex, names, and dates must have equal lengths"),e.holidayDayIndex.forEach((r,s)=>_(r,t,`holidayDayIndex[${s}]`)),e.names.forEach((r,s)=>m(r,t,`names[${s}]`)),e.dates.forEach((r,s)=>{(typeof r!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(r))&&d(t,`dates[${s}] must use YYYY-MM-DD`)})}function Ht(e,t){k(e,t,"root"),(!Array.isArray(e.dstTransitions)||e.dstTransitions.length===0)&&d(t,"dstTransitions must be a nonempty array");let n=new Set;e.dstTransitions.forEach((r,s)=>{k(r,t,`dstTransitions[${s}]`);for(let o of["year","startUtc","endUtc"])_(r[o],t,`dstTransitions[${s}].${o}`);r.startUtc>=r.endUtc&&d(t,`dstTransitions[${s}] startUtc must be before endUtc`),n.has(r.year)&&d(t,`dstTransitions contains duplicate year ${r.year}`),n.add(r.year)})}function zt(e,t){U(e,t,"root"),Object.keys(e).length===0&&d(t,"root must not be empty");for(let[n,r]of Object.entries(e)){for(let s of["addr","quote","quoteAddr","dex","pair"])m(r[s],t,`${n}.${s}`);(typeof r.liq!="number"||!Number.isFinite(r.liq)||r.liq<0)&&d(t,`${n}.liq must be a nonnegative finite source number`)}}function Lt(e,t){k(e,t,"root"),_(e.capturedAt,t,"capturedAt"),_(e.block,t,"block"),_(e.chainId,t,"chainId"),m(e.gasPriceWei,t,"gasPriceWei"),m(e.stateView,t,"stateView"),U(e.pools,t,"pools"),Object.keys(e.pools).length===0&&d(t,"pools must not be empty");for(let[n,r]of Object.entries(e.pools)){for(let s of["pair","version","quote","token","sqrtPriceX96"])m(r[s],t,`pools.${n}.${s}`);r.version!=="v3"&&r.version!=="v4"&&d(t,`pools.${n}.version must be v3 or v4`),typeof r.quoteIsToken0!="boolean"&&d(t,`pools.${n}.quoteIsToken0 must be a boolean`),(!/^[0-9]+$/.test(r.sqrtPriceX96)||BigInt(r.sqrtPriceX96)<=0n)&&d(t,`pools.${n}.sqrtPriceX96 must be a positive integer string`)}}function Wt(e,t){k(e,t,"root"),_(e.capturedAt,t,"capturedAt"),m(e.source,t,"source"),k(e.books,t,"books"),Object.keys(e.books).length===0&&d(t,"books must not be empty");for(let[n,r]of Object.entries(e.books)){k(r,t,`books.${n}`),(!Array.isArray(r.bids)||!Array.isArray(r.asks))&&d(t,`books.${n} must have bids and asks arrays`);for(let[s,o]of r.bids.entries())k(o,t,`books.${n}.bids[${s}]`),m(o.px,t,`books.${n}.bids[${s}].px`),m(o.sz,t,`books.${n}.bids[${s}].sz`);for(let[s,o]of r.asks.entries())k(o,t,`books.${n}.asks[${s}]`),m(o.px,t,`books.${n}.asks[${s}].px`),m(o.sz,t,`books.${n}.asks[${s}].sz`)}}function Qt(e,t){k(e,t,"root"),_(e.capturedAt,t,"capturedAt"),m(e.source,t,"source"),m(e.chain,t,"chain"),U(e.tokens,t,"tokens"),k(e.pairs,t,"pairs"),Object.keys(e.tokens).length===0&&d(t,"tokens must not be empty");for(let[n,r]of Object.entries(e.tokens)){m(r.symbolRaw,t,`tokens.${n}.symbolRaw`),m(r.mint,t,`tokens.${n}.mint`),Object.hasOwn(e.pairs,n)||d(t,`pairs.${n} is required for token ${n}`),(!Array.isArray(e.pairs[n])||e.pairs[n].length===0)&&d(t,`pairs.${n} must be a nonempty array`);for(let[s,o]of e.pairs[n].entries())k(o,t,`pairs.${n}[${s}]`),m(o.pairAddress,t,`pairs.${n}[${s}].pairAddress`),m(o.dexId,t,`pairs.${n}[${s}].dexId`),(typeof o.priceUsd!="number"||!Number.isFinite(o.priceUsd)||o.priceUsd<=0)&&d(t,`pairs.${n}[${s}].priceUsd must be a positive finite number`),(typeof o.liquidityUsd!="number"||!Number.isFinite(o.liquidityUsd)||o.liquidityUsd<0)&&d(t,`pairs.${n}[${s}].liquidityUsd must be a nonnegative finite number`)}}function Xt(e,t){k(e,t,"root"),_(e.capturedAt,t,"capturedAt"),m(e.source,t,"source"),m(e.chain,t,"chain"),e.chain!=="ton"&&d(t,'chain must be "ton"'),U(e.tokens,t,"tokens"),k(e.pairs,t,"pairs"),Object.keys(e.tokens).length===0&&d(t,"tokens must not be empty");for(let[n,r]of Object.entries(e.tokens)){m(r.symbolRaw,t,`tokens.${n}.symbolRaw`),m(r.mint,t,`tokens.${n}.mint`),Object.hasOwn(e.pairs,n)||d(t,`pairs.${n} is required for token ${n}`),(!Array.isArray(e.pairs[n])||e.pairs[n].length===0)&&d(t,`pairs.${n} must be a nonempty array`);for(let[s,o]of e.pairs[n].entries())k(o,t,`pairs.${n}[${s}]`),m(o.pairAddress,t,`pairs.${n}[${s}].pairAddress`),m(o.dexId,t,`pairs.${n}[${s}].dexId`),(typeof o.priceUsd!="number"||!Number.isFinite(o.priceUsd)||o.priceUsd<=0)&&d(t,`pairs.${n}[${s}].priceUsd must be a positive finite number`),(typeof o.liquidityUsd!="number"||!Number.isFinite(o.liquidityUsd)||o.liquidityUsd<0)&&d(t,`pairs.${n}[${s}].liquidityUsd must be a nonnegative finite number`)}}var Vt=Object.freeze({venues:Ft,universe:Pt,oracles:Bt,nyseHolidays:Ct,dstTransitions:Ht,equityDexPools:zt,rhPoolState:Lt,solanaXstocks:Qt,tonXstocks:Xt,hip3L2Books:Wt});function Kt(e,t){let n=Ue[t],r=Me(e,n),s;try{s=It(r,"utf8")}catch(i){throw i?.code==="ENOENT"?new Error(`Fixture fixtures/${n} is missing at ${r}`):new Error(`Fixture fixtures/${n} could not be read: ${i.message}`)}let o;try{o=JSON.parse(s)}catch(i){throw new SyntaxError(`Fixture fixtures/${n} contains invalid JSON: ${i.message}`)}return Vt[t](o,n),o}function je(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.values(e))je(t)}return e}function Fe({fixtureDir:e=Ut}={}){if(typeof e!="string"||e.length===0)throw new TypeError("fixtureDir must be a nonempty path string");let t={};for(let n of Object.keys(Ue))t[n]=Kt(e,n);return je(t)}var De;function j(){return De??=Fe(),De}function q(){return j().venues}function Pe(){return j().oracles}function Be(){return j().nyseHolidays}function Ce(){return j().dstTransitions}function J(){return j().rhPoolState}function He(){return j().solanaXstocks}function ze(){return j().tonXstocks}function Le(){return j().hip3L2Books}var pe=1e3,Xe=60*pe,de=60*Xe,We=24*de,Yt=-5*de,Jt=-4*de,Ve=240,Ke=570,Ye=960,Je=1200,Mr=Object.freeze([Ve,Ke,Ye,Je]),Ur=Object.freeze(["core","extended","dark"]),Qe,fe;function Gt(){let e=Ce().dstTransitions.map(r=>({year:r.year,startMs:r.startUtc*pe,endMs:r.endUtc*pe}));e.sort((r,s)=>r.startMs-s.startMs);let t=e[0].year,n=e[e.length-1].year;return Object.freeze({rows:Object.freeze(e),firstYear:t,lastYear:n,coverageStartMs:Date.UTC(t,0,1),coverageEndMs:Date.UTC(n+1,0,1)})}function Ge(){return Qe??=Gt(),Qe}function Zt(){return fe===void 0&&(fe=new Set(Be().holidayDayIndex)),fe}function Ze(e,t){if(!Number.isSafeInteger(e))throw new TypeError(`${t}: epochMs must be a safe integer number of milliseconds`)}function en(e,t){let{coverageStartMs:n,coverageEndMs:r,firstYear:s,lastYear:o}=Ge();if(e<n||e>=r)throw new RangeError(`${t}: ${new Date(e).toISOString()} is outside DST fixture coverage (${s} through ${o}). Refusing to assume a UTC offset.`)}function tn(e){for(let t of Ge().rows)if(e>=t.startMs&&e<t.endMs)return!0;return!1}function nn(e){return tn(e)?Jt:Yt}function rn(e){let t=e+nn(e),n=Math.floor(t/We),r=t-n*We,s=new Date(t);return{dayIndex:n,minuteOfDay:Math.floor(r/Xe),msIntoDay:r,weekday:s.getUTCDay()}}function sn({dayIndex:e,weekday:t}){return t===0||t===6?!1:!Zt().has(e)}function on(e){return e<Ve?"dark":e<Ke?"extended":e<Ye?"core":e<Je?"extended":"dark"}function X(e){Ze(e,"sessionState"),en(e,"sessionState");let t=rn(e);return sn(t)?on(t.minuteOfDay):"dark"}function me(e){return Ze(e,"isDark"),X(e)==="dark"}var G=Object.freeze({DORMANT_VENUE:"dormant-venue",CROSSED_BOOK:"crossed-book",STALE_QUOTE:"stale-quote",STALE_ORACLE:"stale-oracle"}),un=12e4,an=6e5;function Z(e,t){e.push(Object.freeze({venue:t.venue,symbol:t.symbol??null,reason:t.reason,evidence:t.evidence??null}))}function cn(e){let t=e.raw?.vol24h;return!!(t===0||t===0||typeof t=="number"&&Number.isFinite(t)&&t<=0)}function ln(e){return!e.bid||!e.ask?!1:M(e.bid,e.ask)>0}function et(e,t,n){return Number.isSafeInteger(e.capturedAt)?t-e.capturedAt>n:!1}function ee(e,t={}){if(!Array.isArray(e))throw new TypeError("quotes must be an array");let n=t.nowMs??Date.now(),r=t.quoteFreshnessMs??un,s=t.oracleFreshnessMs??an,o=t.includeDormant===!0,i=[],u=[];for(let a of e){if(cn(a)){o?i.push(Object.freeze({...a,staleData:!0})):Z(u,{venue:a.venue,symbol:a.symbolRaw??a.symbol,reason:G.DORMANT_VENUE,evidence:{vol24h:a.raw?.vol24h??null}});continue}if(ln(a)){Z(u,{venue:a.venue,symbol:a.symbolRaw??a.symbol,reason:G.CROSSED_BOOK,evidence:{bid:a.bid?String(a.bid.mantissa)+"e-"+a.bid.scale:null,ask:a.ask?String(a.ask.mantissa)+"e-"+a.ask.scale:null}});continue}if(et(a,n,r)){Z(u,{venue:a.venue,symbol:a.symbolRaw??a.symbol,reason:G.STALE_QUOTE,evidence:{capturedAt:a.capturedAt,nowMs:n,ageMs:n-a.capturedAt,freshnessMs:r}});continue}if(a.tier==="read-only"&&a.raw?.oracleRaw!==void 0){let l=X(n),c=l==="core"?s:s*2;if(et(a,n,c)){Z(u,{venue:a.venue,symbol:a.symbolRaw??a.symbol,reason:G.STALE_ORACLE,evidence:{capturedAt:a.capturedAt,nowMs:n,session:l}});continue}}i.push(a)}return{survivors:i,excluded:u}}function fn(e){if(typeof e!="number"||!Number.isFinite(e))throw new TypeError("value must be a finite number");let t=String(e);if(!t.includes("e")&&!t.includes("E"))return t;let[n,r]=t.split(/[eE]/),s=Number(r),o=n.startsWith("-"),i=o?n.slice(1):n,[u,a=""]=i.split("."),l=`${u}${a}`,c=u.length+s,p;return c<=0?p=`0.${"0".repeat(-c)}${l}`:c>=l.length?p=`${l}${"0".repeat(c-l.length)}`:p=`${l.slice(0,c)}.${l.slice(c)}`,`${o?"-":""}${p}`}function w(e){return e==null?null:typeof e=="string"?f(e):typeof e!="number"||!Number.isFinite(e)?null:f(fn(e))}function I(e,t){let n=w(e);if(n===null)throw new TypeError(`${t} must be a finite source number`);return n}var pn=new Set(["spot","perp"]),dn=new Set(["read-only","quote-only","prepare","intent"]),mn=new Set(["buy","sell"]),bn=new Set(["net-of-cost","gross"]),yn=new Set(["homogeneous","heterogeneous"]),hn=["bid","ask","mid","mark"],tt=["fees","gasEstimate","priceImpact","fundingHourly"],gn=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function h(e,t){throw new TypeError(`${e} ${t}`)}function rt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function B(e,t){rt(e)||h(t,"must be an object")}function st(e,t,n){Object.hasOwn(e,t)||h(`${n}.${t}`,"is required")}function C(e,t){(typeof e!="string"||e.length===0)&&h(t,"must be a nonempty string")}function V(e,t,n){t.has(e)||h(n,`must be one of ${[...t].join(", ")}`)}function ye(e,t){(!Number.isSafeInteger(e)||e<0)&&h(t,"must be a nonnegative safe integer")}function be(e,t,n=!1){e===null&&n||(rt(e)||h(t,"must be a fixed point value"),typeof e.mantissa!="bigint"&&h(`${t}.mantissa`,"must be a bigint"),(!Number.isSafeInteger(e.scale)||e.scale<0)&&h(`${t}.scale`,"must be a nonnegative safe integer"))}function te(e,t,n=!1){e===null&&n||B(e,t)}function nt(e,t){B(e,t),C(e.venue,`${t}.venue`),C(e.reason,`${t}.reason`),gn.test(e.reason)||h(`${t}.reason`,"must be a machine readable lower case code"),Object.hasOwn(e,"symbol")&&e.symbol!==null&&C(e.symbol,`${t}.symbol`)}function v(e){B(e,"quote");for(let n of["venue","chain","instrument","tier","symbolRaw","symbol","side","requestedSize",...tt,"costAccounted","capturedAt","blockOrSeq","raw"])st(e,n,"quote");C(e.venue,"quote.venue"),!(typeof e.chain=="string"&&e.chain.length>0)&&!(Number.isSafeInteger(e.chain)&&e.chain>=0)&&h("quote.chain","must be a nonempty string or nonnegative chain id"),V(e.instrument,pn,"quote.instrument"),V(e.tier,dn,"quote.tier"),C(e.symbolRaw,"quote.symbolRaw"),C(e.symbol,"quote.symbol"),V(e.side,mn,"quote.side"),be(e.requestedSize,"quote.requestedSize"),e.requestedSize.mantissa<0n&&h("quote.requestedSize","must not be negative");let t=0;for(let n of hn)Object.hasOwn(e,n)&&(be(e[n],`quote.${n}`),t+=1);t===0&&h("quote","must contain at least one of bid, ask, mid, mark");for(let n of tt)be(e[n],`quote.${n}`,!0);if(typeof e.costAccounted!="boolean"&&h("quote.costAccounted","must be a boolean"),e.costAccounted){for(let n of["fees","gasEstimate","priceImpact"])e[n]===null&&h(`quote.${n}`,"cannot be unknown when costAccounted is true");e.instrument==="perp"&&e.fundingHourly===null&&h("quote.fundingHourly","cannot be unknown when costAccounted is true for a perp")}return e.instrument==="spot"&&e.fundingHourly!==null&&h("quote.fundingHourly","must be null for a spot quote"),ye(e.capturedAt,"quote.capturedAt"),e.blockOrSeq!==null&&!(typeof e.blockOrSeq=="string"&&e.blockOrSeq.length>0)&&!(Number.isSafeInteger(e.blockOrSeq)&&e.blockOrSeq>=0)&&h("quote.blockOrSeq","must be null, a nonempty string, or a nonnegative safe integer"),B(e.raw,"quote.raw"),e}function he(e){B(e,"rankResult");for(let t of["rankedOn","ranked","winner","runnersUp","improvementBps","sourcesAnswered","sourcesTried","failed","excluded","darkWindow","instrumentMix","bestPreparable"])st(e,t,"rankResult");return V(e.rankedOn,bn,"rankResult.rankedOn"),Array.isArray(e.ranked)||h("rankResult.ranked","must be an array"),e.ranked.forEach((t,n)=>te(t,`rankResult.ranked[${n}]`)),te(e.winner,"rankResult.winner",!0),e.ranked.length===0&&e.winner!==null&&h("rankResult.winner","must be null when ranked is empty"),e.ranked.length>0&&e.winner===null&&h("rankResult.winner","must be present when ranked is not empty"),Array.isArray(e.runnersUp)||h("rankResult.runnersUp","must be an array"),e.runnersUp.forEach((t,n)=>te(t,`rankResult.runnersUp[${n}]`)),e.improvementBps!==null&&!(typeof e.improvementBps=="number"&&Number.isFinite(e.improvementBps))&&h("rankResult.improvementBps","must be a finite number or null"),ye(e.sourcesAnswered,"rankResult.sourcesAnswered"),ye(e.sourcesTried,"rankResult.sourcesTried"),e.sourcesAnswered>e.sourcesTried&&h("rankResult.sourcesAnswered","must not exceed sourcesTried"),Array.isArray(e.failed)||h("rankResult.failed","must be an array"),e.failed.forEach((t,n)=>nt(t,`failed[${n}]`)),Array.isArray(e.excluded)||h("rankResult.excluded","must be an array"),e.excluded.forEach((t,n)=>nt(t,`excluded[${n}]`)),e.darkWindow!==null&&B(e.darkWindow,"rankResult.darkWindow"),V(e.instrumentMix,yn,"rankResult.instrumentMix"),te(e.bestPreparable,"rankResult.bestPreparable",!0),Object.hasOwn(e,"carry")&&e.carry!==null&&B(e.carry,"rankResult.carry"),e}var kn="arcus_perp",xn="robinhood-4663",wn="quote-only",ne="0.00000480324074074";function ot(){return q().venues.arcus}function Sn(){return Object.keys(ot().markets).sort()}function $n({symbol:e,side:t="buy",sizeUsd:n=null}={}){if(typeof e!="string"||e.length===0)return null;let r=e.endsWith("-USD")?e.slice(0,-4):e,s=ot().markets[r];if(!s)return null;let o=I(s.mark,`${r}.mark`),i=w(s.oracle),u=w(s.fundingHourly),a=n===null?f("0"):n,l={venue:kn,chain:xn,instrument:"perp",tier:wn,symbolRaw:e,symbol:r,side:t,requestedSize:a,mark:o,fees:null,gasEstimate:null,priceImpact:null,fundingHourly:u,costAccounted:!1,capturedAt:q().capturedAt*1e3,blockOrSeq:null,raw:{fixture:"fixtures/venues.json#venues.arcus",oraclePrice:s.oracle,vol24h:s.vol24h,oi:s.oi,fundingAnnPct:s.fundingAnnPct,category:s.category,isOutsideRth:s.isOutsideRth===!0,rth:s.rth,darkWindowFundingHourly:ne,initialMarginFraction:s.initialMarginFraction??null,offHoursInitialMarginFraction:s.offHoursInitialMarginFraction??null,reasonCostUnknown:"fees, gas, and impact at size not captured for Arcus perps"}};return i!==null&&(l.raw.oracleFixed=i),v(l)}function re({side:e="buy",sizeUsd:t=null}={}){return Sn().map(n=>$n({symbol:n,side:e,sizeUsd:t})).filter(n=>n!==null)}var it=36e5,Zr=24*365;function ge(e,t,n=8){if(e==null)throw new TypeError("hourlyFundingRate is required");if(!Number.isFinite(t)||t<0)throw new RangeError("horizonHours must be a nonnegative finite number");if(t===0)return f("0");let r=f(String(t)),s=$(10000n,0);return E(E(e,r),s)}function ut(e,t,n={}){if(e.instrument!=="perp")return{model:"current-funding-held-constant",horizonHours:t,carryBps:f("0"),carryBpsDisplay:"0",confidence:"estimate",note:"spot has no funding carry"};let r=n.nowMs??Date.now(),s=n.applyDarkWindowLock===!0,o=e.fundingHourly;if(s&&o!==null){let u=An(r,t),a=t-u,l=f(ne),c=ge(o,a),p=ge(l,u),y=Math.max(c.scale,p.scale),b={mantissa:c.mantissa*10n**BigInt(y-c.scale)+p.mantissa*10n**BigInt(y-p.scale),scale:y};return{model:"current-funding-held-constant",horizonHours:t,carryBps:b,carryBpsDisplay:S(b),confidence:"estimate",darkHours:u,litHours:a,darkWindowRate:ne,compounding:"ignored",compoundingErrorBoundNote:"simple sum; at 30d and 1e-5/h the ignored compound is under 0.5bp"}}if(o===null)return{model:"current-funding-held-constant",horizonHours:t,carryBps:null,carryBpsDisplay:null,confidence:"estimate",note:"funding rate unknown"};let i=ge(o,t);return{model:"current-funding-held-constant",horizonHours:t,carryBps:i,carryBpsDisplay:S(i),confidence:"estimate",compounding:"ignored",compoundingErrorBoundNote:"simple sum; at 30d and 1e-5/h the ignored compound is under 0.5bp"}}function An(e,t){if(t<=0)return 0;let n=0,r=Math.floor(t);for(let s=0;s<r;s+=1)me(e+s*it)&&(n+=1);return t>r&&me(e+r*it)&&(n+=t-r),n}function En(e){return e.mid??e.mark??e.ask??e.bid??null}function vn(e){let t=En(e);if(t===null)return null;let n=e.costAccounted===!0,r=f("0");e.fees!==null?r=D(r,e.fees):n=!1,e.priceImpact!==null?r=D(r,e.priceImpact):e.requestedSize&&e.requestedSize.mantissa>0n&&(n=!1),e.gasEstimate===null?n=!1:r=D(r,e.gasEstimate);let s;if(e.fees!==null&&M(e.fees,f("1"))<0&&M(e.fees,f("0"))>=0){let o=D(f("1"),e.fees);s=E(t,o),e.priceImpact!==null&&(s=D(s,E(t,e.priceImpact)))}else s=D(t,r);return{net:s,costAccounted:n,px:t}}function qn(e,t,n=null){return{venue:e.venue,chain:e.chain,instrument:e.instrument,tier:e.tier,symbol:e.symbol,symbolRaw:e.symbolRaw,side:e.side,price:t.px,net:t.net,costAccounted:t.costAccounted,fundingHourly:e.fundingHourly,carry:n,quote:e}}function On(e,t){if(!e||!t||!e.costAccounted||!t.costAccounted||e.instrument!==t.instrument||e.net.mantissa===0n)return null;let n=Q(t.net,e.net);return R(E(n,$(10000n,0)),t.net,4)}function ke(e,t={}){if(!Array.isArray(e))throw new TypeError("quotes must be an array");let n=t.nowMs??e[0]?.capturedAt??Date.now(),r=e.length,s=e,o=[];if(!t.skipLiveness){let x=ee(e,{nowMs:n});s=x.survivors,o=x.excluded}let i=e.length,u=[],a=t.horizonHours,l=Number.isFinite(a)&&a>0,c=[];for(let x of s){let A=vn(x);if(A===null)continue;let O=null;if(l&&x.instrument==="perp"&&(O=ut(x,a,{nowMs:n}),O.carryBps!==null)){let vt=D(f("1"),R(O.carryBps,$(10000n,0),12));A.net=E(A.net,vt),A.costAccounted=!1}c.push(qn(x,A,O))}let p=c,y="homogeneous";if(l)y="heterogeneous",p=c;else{let x=c.filter(O=>O.instrument==="spot"),A=c.filter(O=>O.instrument==="perp");x.length>0&&A.length>0?(p=x.length>=A.length?x:A,y="homogeneous"):(p=c,y="homogeneous")}p.sort((x,A)=>{let O=M(x.net,A.net);return O!==0?O:x.venue<A.venue?-1:x.venue>A.venue?1:0});let b=p[0]??null,g=p.slice(1),F=p,L="gross";b&&b.costAccounted&&(g.length===0||g[0].costAccounted)&&(L="net-of-cost");let Re=g.length===0?null:On(b,g[0]),$t=c.find(x=>x.tier==="prepare")??null,ae=X(n),At=ae==="core"?null:{session:ae,warning:ae==="dark"?"market is dark; marks are not real price discovery":"extended session; thinner books and higher staleness risk"},Ie=null;l&&(Ie=Rn(c));let Et={rankedOn:L,ranked:F,winner:b,runnersUp:g,improvementBps:Re===null?null:Number(S(Re)),sourcesAnswered:i,sourcesTried:r,failed:u,excluded:o,darkWindow:At,instrumentMix:y,bestPreparable:$t,carry:b?.carry??null,breakEvenHorizonHours:Ie};return he(Et)}function Rn(e){let t=e.filter(o=>o.instrument==="spot").sort((o,i)=>M(o.net,i.net))[0],n=e.filter(o=>o.instrument==="perp").sort((o,i)=>M(o.net,i.net))[0];if(!t||!n||n.fundingHourly===null)return null;let r=Q(t.net,n.net);if(r.mantissa===0n)return 0;let s=E(n.fundingHourly,n.price);if(s.mantissa===0n)return null;try{let o=R(r,s,4),i=Number(S(o));return!Number.isFinite(i)||i<0?null:i}catch{return null}}var In="rh_uniswap",Tn=4663,_n="prepare",Nn=1n<<192n,H=18,Dn=Object.freeze({v3:180000n,v4:240000n});function xe(){return J()}function Mn(e){return{mantissa:e*e*10n**BigInt(H)/Nn,scale:H}}function Un(e){let t=Mn(BigInt(e.sqrtPriceX96)),n=e.quote==="USDG"?6:18,r=18;if(e.quoteIsToken0){let s=R(E(t,$(10n**BigInt(n),0)),$(10n**BigInt(r),0),H);return s.mantissa===0n?null:R(f("1"),s,H)}return R(E(t,$(10n**BigInt(r),0)),$(10n**BigInt(n),0),H)}function jn(e){let t=Pe(),n=t.assets[e];return n?$(n.rawPrice,t.oracleScaleExp):null}function Fn(e,t){if(e===null||t===null||e.mantissa<=0n||t.mantissa<=0n)return null;let n={...e};return R(t,Pn(n,t),H)}function Pn(e,t){let n=Math.max(e.scale,t.scale);return{mantissa:W(e,n).mantissa+W(t,n).mantissa,scale:n}}function Bn(e){let t=xe(),n=Dn[e];return n?{wei:BigInt(t.gasPriceWei)*n,units:n,native:"ETH"}:null}function we(){return Object.keys(xe().pools).sort()}function z({symbol:e,side:t="buy",sizeUsd:n=null}={}){if(typeof e!="string"||e.length===0)throw new TypeError("symbol must be a nonempty string");let r=xe(),s=r.pools[e];if(!s)return null;let o=Un(s);if(o===null)return null;let i=w(s.liqUsd),u=n===null?f("0"):n,a=s.feePpm===null||s.feePpm===void 0?null:R($(BigInt(s.feePpm),0),$(1000000n,0),8),l=u.mantissa===0n?f("0"):Fn(i,u),c=Bn(s.version),b={venue:In,chain:Tn,instrument:"spot",tier:_n,symbolRaw:e,symbol:e,side:t,requestedSize:u,mid:o,fees:a,gasEstimate:null,priceImpact:l,fundingHourly:null,costAccounted:!1,capturedAt:r.capturedAt*1e3,blockOrSeq:r.block,raw:{fixture:"fixtures/rh_pool_state.json",pair:s.pair,version:s.version,sqrtPriceX96:s.sqrtPriceX96,quote:s.quote,quoteIsToken0:s.quoteIsToken0,liqUsd:s.liqUsd,gasNativeWei:c===null?null:c.wei.toString(),gasUnits:c===null?null:c.units.toString(),impactModel:"constant-product-estimate",notes:["price read live from chain 4663",s.version==="v4"?"v4 fee may be dynamic via hook and was not captured":"v3 fee tier is the pool static fee","gas known in native wei only, no ETH price captured to denominate it"]}},g=jn(e);return g!==null&&(b.referencePrice=g,b.referenceBasisBps=S(R(E(Q(o,g),$(10000n,0)),g,4))),v(b)}function at({side:e="buy",sizeUsd:t=null}={}){return we().map(n=>z({symbol:n,side:e,sizeUsd:t})).filter(n=>n!==null)}var ct=12e4,Cn="0x0000000000000000000000000000000000000000",Hn="0x84b75b19A3cdf8E2F56d0507d22D442847B2053C";function Se(e={}){let{symbol:t,side:n="buy",sizeUsd:r=null,recipient:s,nowMs:o=Date.now()}=e;if(typeof t!="string"||!t)throw new TypeError("symbol is required");if(typeof s!="string"||!/^0x[0-9a-fA-F]{40}$/.test(s))throw new TypeError("recipient must be a 0x-prefixed 20 byte address");let i=z({symbol:t,side:n,sizeUsd:r});if(i===null)throw new Error(`no RH Uniswap pool for ${t}`);if(i.tier!=="prepare")throw new Error(`route tier is ${i.tier}, only prepare tier can be prepared`);let u=o-i.capturedAt;if(u>ct)throw new Error(`quote is stale (${u}ms old, bound ${ct}ms); re-quote before preparing`);let l=J().pools[t],c=l.version==="v4"?Hn:Cn,p=c,y=n==="buy"?l.quoteAddr:l.token;return Object.freeze({artifactKind:"unsigned-tx",chainId:4663,to:c,data:"0x",value:"0",requiresApproval:{spender:p,token:y,amount:null},requiresWalletSignature:!0,backendSigner:!1,unsigned:!0,houseSigned:!1,quoteRef:{venue:i.venue,symbol:i.symbol,symbolRaw:i.symbolRaw,capturedAt:i.capturedAt,blockOrSeq:i.blockOrSeq,mid:i.mid,version:l.version,pair:l.pair},quoteAgeMs:u,recipient:s,side:n,notes:["prepare-only: user wallet must sign","calldata encoding is deferred; this artifact is the bound intent",l.version==="v4"?"V4 route via PoolManager":"V3 route via SwapRouter (address not yet pinned)"]})}var zn="hyperliquid_hip3",Ln="hyperliquid",Wn="quote-only";function K(){return q().venues.hyperliquid_hip3}function lt(){return Object.keys(K().dexs).sort()}function Qn(){let e=[];for(let[t,n]of Object.entries(K().dexs))for(let r of Object.keys(n))e.push(`${t}:${r}`);return e.sort()}function Xn(e){if(typeof e!="string"||e.length===0)return[];let t=e.indexOf(":");if(t>0){let r=e.slice(0,t),s=e.slice(t+1),o=K().dexs[r]?.[s];return o?[{dex:r,ticker:s,market:o}]:[]}let n=[];for(let[r,s]of Object.entries(K().dexs))Object.hasOwn(s,e)&&n.push({dex:r,ticker:e,market:s[e]});return n}function Vn(e,t){try{return Le().books[`${e}:${t}`]??null}catch{return null}}function Kn(e,t,n){if(!e||n===null||n.mantissa<=0n)return null;let r=t==="buy"?e.asks:e.bids;if(!r||r.length===0)return null;let s=Number(S(n));if(!Number.isFinite(s)||s<=0)return null;let o=0,i=0,u=0;for(let a of r){let l=Number(a.px),c=Number(a.sz);if(!(l>0)||!(c>0))continue;let p=l*c,y=Math.min(s,p),b=y/l;if(o+=y,i+=b,s-=y,u+=1,s<=1e-9)break}return i<=0?null:{vwap:o/i,filledUsd:o,unfilledUsd:Math.max(0,s),levelsUsed:u}}function Yn(e,t,n,r){let s=Kn(e,t,n);if(!s)return{impact:null,depth:null};let o=Number(S(r));if(!(o>0))return{impact:null,depth:s};let i=t==="buy"?(s.vwap-o)/o:(o-s.vwap)/o,u=Math.max(0,i);return{impact:w(Number(u.toPrecision(12))),depth:{...s,impactFraction:u,fullyFilled:s.unfilledUsd<=1e-6}}}function ft({dex:e,ticker:t,market:n,side:r,size:s}){let o=I(n.mark,`${e}:${t}.mark`),i=w(n.fundingHourly),u=w(n.vol24h),a=w(n.oi),l=s===null?f("0"):s,c=Vn(e,t),p=null,y=null,b="fees and gas not captured";if(l.mantissa>0n)if(c){let L=Yn(c,r,l,o);p=L.impact,y=L.depth,y?.fullyFilled?b="impact measured from l2Book; fees and gas still not captured":b="book walked but size exceeds visible depth; fees and gas not captured"}else b="no order book depth wired for this coin; fees and gas not captured";else c?b="zero size; fees and gas not captured":b="no order book depth wired for this coin; fees and gas not captured";let F={venue:zn,chain:Ln,instrument:"perp",tier:Wn,symbolRaw:`${e}:${t}`,symbol:t,side:r,requestedSize:l,mark:o,fees:null,gasEstimate:null,priceImpact:p,fundingHourly:i,costAccounted:!1,capturedAt:q().capturedAt*1e3,blockOrSeq:null,raw:{fixture:"fixtures/venues.json#venues.hyperliquid_hip3",dex:e,ticker:t,vol24h:n.vol24h,oi:n.oi,fundingAnnPct:n.fundingAnnPct,maxLev:n.maxLev,reasonCostUnknown:b,hasL2Book:c!==null,l2BookFixture:c?"fixtures/hip3_l2books.json":null,depth:y}};return u!==null&&(F.raw.vol24hFixed=u),a!==null&&(F.raw.oiFixed=a),c?.bids?.[0]&&c?.asks?.[0]&&(F.bid=f(String(c.bids[0].px)),F.ask=f(String(c.asks[0].px))),v(F)}function pt({symbol:e,side:t="buy",sizeUsd:n=null}={}){let r=Xn(e);return r.length===0||r.length>1?null:ft({...r[0],side:t,size:n})}function se({side:e="buy",sizeUsd:t=null,ticker:n=null}={}){let r=[];for(let s of Qn()){let[o,i]=s.split(":");if(n!==null&&i!==n)continue;let u=K().dexs[o][i];r.push(ft({dex:o,ticker:i,market:u,side:e,size:t}))}return r}var Jn="arcus_spot",Gn="robinhood-4663",Zn="quote-only";function dt(){return q().venues.arcus_spot}function er(){return Object.keys(dt().pairs).sort()}function tr({symbol:e,side:t="buy",sizeUsd:n=null}={}){if(typeof e!="string"||e.length===0)return null;let r=dt().pairs[e];if(!r)return null;let s=r.bid===void 0||r.bid===null?null:I(r.bid,`${e}.bid`),o=r.ask===void 0||r.ask===null?null:I(r.ask,`${e}.ask`),i=w(r.last),u=null;if(s!==null&&o!==null){u={mantissa:s.mantissa+o.mantissa,scale:s.scale===o.scale?s.scale+1:Math.max(s.scale,o.scale)+1};let p=Math.max(s.scale,o.scale),y=s.scale===p?s.mantissa:s.mantissa*10n**BigInt(p-s.scale),b=o.scale===p?o.mantissa:o.mantissa*10n**BigInt(p-o.scale);u={mantissa:y+b,scale:p+1},u={mantissa:(y+b)/2n,scale:p}}else i!==null&&(u=i);if(s===null&&o===null&&u===null)return null;let a=n===null?f("0"):n,l=f("0"),c={venue:Jn,chain:Gn,instrument:"spot",tier:Zn,symbolRaw:e,symbol:e,side:t,requestedSize:a,fees:l,gasEstimate:null,priceImpact:null,fundingHourly:null,costAccounted:!1,capturedAt:q().capturedAt*1e3,blockOrSeq:null,raw:{fixture:"fixtures/venues.json#venues.arcus_spot",last:r.last,bid:r.bid,ask:r.ask,vol24h:r.vol24h,feeKnownZero:!0,reasonCostUnknown:"gas and impact at size not captured; fee is a known zero"}};return s!==null&&(c.bid=s),o!==null&&(c.ask=o),u!==null&&(c.mid=u),v(c)}function oe({side:e="buy",sizeUsd:t=null}={}){return er().map(n=>tr({symbol:n,side:e,sizeUsd:t})).filter(n=>n!==null)}var nr="solana_xstocks",rr="solana",sr="quote-only",mt=25e3;function ie(){return He()}function $e(){return Object.keys(ie().tokens).sort()}function or(e){let t=ie().pairs[e];return!t||t.length===0?null:[...t].sort((n,r)=>(r.liquidityUsd??0)-(n.liquidityUsd??0))[0]}function ir(e,t){if(e===null||t===null)return null;if(e.mantissa<=0n||t.mantissa<=0n)return f("0");let n=Math.max(e.scale,t.scale),r=e.scale===n?e.mantissa:e.mantissa*10n**BigInt(n-e.scale),s=t.scale===n?t.mantissa:t.mantissa*10n**BigInt(n-t.scale),o=s*10n**6n,i=r+s;return{mantissa:o/i,scale:6}}function Ae({symbol:e,side:t="buy",sizeUsd:n=null}={}){if(typeof e!="string"||e.length===0)return null;let r=e,s=e,o=ie().tokens;if(Object.hasOwn(o,e))r=e,s=o[e].symbolRaw;else if(e.endsWith("x")||e.endsWith("X")){let g=e.slice(0,-1).toUpperCase();if(Object.hasOwn(o,g))r=g,s=o[g].symbolRaw;else return null}else return null;let i=o[r],u=or(r);if(!i||!u)return null;let a=I(u.priceUsd,`${r}.priceUsd`),l=w(u.liquidityUsd),c=n===null?f("0"):n,p=c.mantissa===0n?f("0"):ir(l,c),y=!1;c.mantissa===0n&&(u.liquidityUsd??0)>=mt&&(y=!1);let b={venue:nr,chain:rr,instrument:"spot",tier:sr,symbolRaw:s,symbol:r,side:t,requestedSize:c,mid:a,fees:null,gasEstimate:null,priceImpact:p,fundingHourly:null,costAccounted:y,capturedAt:ie().capturedAt*1e3,blockOrSeq:null,raw:{fixture:"fixtures/solana_xstocks.json",mint:i.mint,pairAddress:u.pairAddress,dexId:u.dexId,quote:u.quote,liquidityUsd:u.liquidityUsd,volume24h:u.volume24h,priceUsd:u.priceUsd,source:"dexscreener",approximate:!0,reasonCostUnknown:"DexScreener liquidity.usd is a third-party float; fees and SOL gas not captured; impact is modeled",thin:(u.liquidityUsd??0)<mt}};return v(b)}function bt({side:e="buy",sizeUsd:t=null}={}){return $e().map(n=>Ae({symbol:n,side:e,sizeUsd:t})).filter(n=>n!==null)}var ur="ton_stonfi",ar="ton",cr="quote-only",lr=25e3,fr=.01;function ue(){return ze()}function Ee(){return Object.keys(ue().tokens).sort()}function pr(e){let t=ue().pairs[e];return!t||t.length===0?null:[...t].sort((n,r)=>(r.liquidityUsd??0)-(n.liquidityUsd??0))[0]}function dr(e,t){if(e===null||t===null)return null;if(e.mantissa<=0n||t.mantissa<=0n)return f("0");let n=Math.max(e.scale,t.scale),r=e.scale===n?e.mantissa:e.mantissa*10n**BigInt(n-e.scale),s=t.scale===n?t.mantissa:t.mantissa*10n**BigInt(n-t.scale),o=s*10n**6n,i=r+s;return{mantissa:o/i,scale:6}}function ve({symbol:e,side:t="buy",sizeUsd:n=null}={}){if(typeof e!="string"||e.length===0)return null;let r=e,s=e,o=ue().tokens;if(Object.hasOwn(o,e))r=e,s=o[e].symbolRaw;else if(e.endsWith("x")||e.endsWith("X")){let g=e.slice(0,-1).toUpperCase();if(Object.hasOwn(o,g))r=g,s=o[g].symbolRaw;else return null}else{let g=e.toUpperCase();if(Object.hasOwn(o,g))r=g,s=o[g].symbolRaw;else return null}let i=o[r],u=pr(r);if(!i||!u)return null;let a=I(u.priceUsd,`${r}.priceUsd`),l=w(u.liquidityUsd),c=n===null?f("0"):n,p=c.mantissa===0n?f("0"):dr(l,c),b={venue:ur,chain:ar,instrument:"spot",tier:cr,symbolRaw:s,symbol:r,side:t,requestedSize:c,mid:a,fees:null,gasEstimate:null,priceImpact:p,fundingHourly:null,costAccounted:!1,capturedAt:ue().capturedAt*1e3,blockOrSeq:null,raw:{fixture:"fixtures/ton_xstocks.json",mint:i.mint,pairAddress:u.pairAddress,dexId:u.dexId,quote:u.quote,liquidityUsd:u.liquidityUsd,volume24h:u.volume24h,priceUsd:u.priceUsd,source:"dexscreener",approximate:!0,reasonCostUnknown:"DexScreener liquidity.usd is a third-party float; fees and TON gas not captured; impact is modeled; TON books are thin",thin:(u.liquidityUsd??0)<lr,impactSizeFractionHint:fr}};return v(b)}function yt({side:e="buy",sizeUsd:t=null}={}){return Ee().map(n=>ve({symbol:n,side:e,sizeUsd:t})).filter(n=>n!==null)}var ht=3600*1e3;function qe(e){return e==null||e===""?null:typeof e=="object"&&e&&typeof e.mantissa=="bigint"?e:f(String(e))}function mr(e,{sizeUsd:t=null}={}){if(typeof e!="string"||!e.trim())throw new TypeError("ticker is required");let n=e.trim().toUpperCase(),r=qe(t),s=[],o=pt({symbol:`xyz:${n}`,sizeUsd:r});if(o)s.push(o);else for(let l of se({ticker:n,sizeUsd:r}))s.push(l);for(let l of re({sizeUsd:r}))l.symbol===n&&s.push(l);for(let l of oe({sizeUsd:r}))l.symbol===n&&s.push(l);let i=z({symbol:n,sizeUsd:r});i&&s.push(i);let u=Ae({symbol:n,sizeUsd:r});u&&s.push(u);let a=ve({symbol:n,sizeUsd:r});return a&&s.push(a),s}function gt(e={}){let t=String(e.ticker||e.symbol||"").trim().toUpperCase();if(!t)throw new Error("bestEquityRoute requires ticker");let n=qe(e.sizeUsd??e.size??null),r=mr(t,{sizeUsd:n});if(r.length===0)return{ticker:t,rankedOn:"gross",ranked:[],winner:null,runnersUp:[],improvementBps:null,sourcesAnswered:0,sourcesTried:0,failed:[],excluded:[],bestPreparable:null,instrumentMix:"homogeneous",note:"no venue answered for this ticker in the pinned fixture capture"};let s=r[0].capturedAt,o=String(s).length<=10?s*1e3:s,i=e.nowMs==null,u=e.nowMs??s+1e3,a=Math.max(0,Date.now()-o),l=ke(r,{nowMs:u,horizonHours:e.horizonHours!=null?Number(e.horizonHours):void 0,skipLiveness:e.skipLiveness===!0});return{ticker:t,...l,dataSource:i?"fixture":"caller-clock",capturedAt:o,ageMs:a,stale:a>ht}}function kt(){let e=[{venue:"hyperliquid_hip3",tier:"quote-only",chain:"hyperliquid",n:se().length},{venue:"arcus_perp",tier:"quote-only",chain:"robinhood-4663",n:re().length},{venue:"arcus_spot",tier:"quote-only",chain:"robinhood-4663",n:oe().length},{venue:"rh_uniswap",tier:"prepare",chain:4663,n:we().length},{venue:"solana_xstocks",tier:"quote-only",chain:"solana",n:$e().length},{venue:"ton_stonfi",tier:"quote-only",chain:"ton",n:Ee().length}],t=[...se(),...re(),...oe(),...at(),...bt(),...yt()],n=(t[0]?.capturedAt??Date.now())+1e3,{survivors:r,excluded:s}=ee(t,{nowMs:n});return{inventory:e,hip3Dexs:lt(),liveness:{survivors:r.length,excluded:s.length,byReason:s.reduce((o,i)=>(o[i.reason]=(o[i.reason]??0)+1,o),{})},capturedAt:q().capturedAt,custody:"prepare-only",note:"quote-only venues are ranked for discovery; only rh_uniswap is preparable in v1"}}function xt(e={}){let t=String(e.ticker||e.symbol||"").trim().toUpperCase(),n=e.recipient||e.taker;if(!t)throw new Error("prepareEquityRoute requires ticker");if(!n)throw new Error("prepareEquityRoute requires recipient (signing wallet)");let r=qe(e.sizeUsd??e.size??null),s=z({symbol:t,sizeUsd:r});if(!s)return{ok:!1,failureKind:"no-prepare-path",ticker:t,note:"no RH Uniswap prepare-tier route for this ticker in fixtures"};try{let o=String(s.capturedAt).length<=10?s.capturedAt*1e3:s.capturedAt,i=e.nowMs!=null,u=i?Number(e.nowMs):Date.now(),a=Math.max(0,Date.now()-o),l=Se({symbol:t,sizeUsd:r,recipient:n,nowMs:u});return{ok:!0,ticker:t,artifact:l,bestPreparableVenue:"rh_uniswap",dataSource:i?"caller-clock":"live-clock",capturedAt:o,ageMs:a,stale:a>ht}}catch(o){return{ok:!1,failureKind:"prepare-refused",ticker:t,error:String(o.message||o)}}}function Oe(e){return JSON.parse(JSON.stringify(e,(t,n)=>typeof n=="bigint"?n.toString():n))}function St(){return`oracle equities <command>
2
+ import{realpathSync as wt}from"node:fs";import{fileURLToPath as br}from"node:url";var $r=Object.freeze({mantissa:10000n,scale:0});function P(e){if(!Number.isSafeInteger(e)||e<0||e>1e3)throw new RangeError("scale must be a safe integer from 0 through 1000")}function T(e,t){if(typeof e!="bigint")throw new TypeError("mantissa must be a bigint");return P(t),Object.freeze({mantissa:e,scale:t})}function N(e,t="value"){if(e===null||typeof e!="object")throw new TypeError(`${t} must be a fixed point value`);if(typeof e.mantissa!="bigint")throw new TypeError(`${t}.mantissa must be a bigint`);P(e.scale)}function Y(e){return P(e),10n**BigInt(e)}function f(e){if(typeof e!="string"||!/^[+-]?\d+(?:\.\d+)?$/.test(e))throw new TypeError("value must be a plain decimal string");let t=e.startsWith("-"),n=e[0]==="-"||e[0]==="+"?e.slice(1):e,[r,s=""]=n.split("."),o=`${r}${s}`,i=BigInt(o)*(t?-1n:1n);return T(i,s.length)}function $(e,t){if(P(t),typeof e=="bigint")return T(e,t);if(typeof e!="string"||!/^[+-]?\d+$/.test(e))throw new TypeError("value must be an integer string or bigint");return T(BigInt(e),t)}function S(e){N(e);let t=e.mantissa<0n,n=(t?-e.mantissa:e.mantissa).toString();if(e.scale===0)return`${t?"-":""}${n}`;let r=n.padStart(e.scale+1,"0"),s=r.length-e.scale;return`${t?"-":""}${r.slice(0,s)}.${r.slice(s)}`}function W(e,t){return N(e),P(t),t===e.scale?T(e.mantissa,e.scale):t>e.scale?T(e.mantissa*Y(t-e.scale),t):T(e.mantissa/Y(e.scale-t),t)}function ce(e,t){N(e,"left"),N(t,"right");let n=Math.max(e.scale,t.scale);return[W(e,n),W(t,n),n]}function D(e,t){let[n,r,s]=ce(e,t);return T(n.mantissa+r.mantissa,s)}function Q(e,t){let[n,r,s]=ce(e,t);return T(n.mantissa-r.mantissa,s)}function E(e,t){N(e,"left"),N(t,"right");let n=e.scale+t.scale;return P(n),T(e.mantissa*t.mantissa,n)}function R(e,t,n=Math.max(e?.scale??0,t?.scale??0)){if(N(e,"left"),N(t,"right"),P(n),t.mantissa===0n)throw new RangeError("division by zero");let r=e.mantissa*Y(t.scale+n),s=t.mantissa*Y(e.scale);return T(r/s,n)}function M(e,t){let[n,r]=ce(e,t);return n.mantissa<r.mantissa?-1:n.mantissa>r.mantissa?1:0}import{readFileSync as It,existsSync as Tt}from"node:fs";import{fileURLToPath as _t}from"node:url";import{dirname as Nt,join as Me}from"node:path";import{existsSync as _e,readFileSync as qt}from"node:fs";import{dirname as Te,join as le}from"node:path";import{fileURLToPath as Ot}from"node:url";function Rt(e){let t=Te(Ot(e));for(let n=0;n<8;n+=1){let r=le(t,"package.json");if(_e(r))try{let o=JSON.parse(qt(r,"utf8"));if(o&&typeof o.version=="string")return t}catch{}let s=Te(t);if(s===t)break;t=s}throw new Error(`oracle: could not resolve package root from ${e}`)}function Ne(e,t){let n=Rt(t),r=le(n,e);return _e(r)?r:le(n,"dist","assets",e)}var Dt=Me(Nt(_t(import.meta.url)),"fixtures");function Mt(){try{let e=Ne("equities-fixtures",import.meta.url);if(e&&Tt(e))return e}catch{}return Dt}var Ut=Mt();var Ue=Object.freeze({venues:"venues.json",universe:"universe.json",oracles:"oracles.json",nyseHolidays:"nyse_holidays.json",dstTransitions:"dst_transitions.json",equityDexPools:"equity_dex_pools.json",rhPoolState:"rh_pool_state.json",solanaXstocks:"solana_xstocks.json",tonXstocks:"ton_xstocks.json",hip3L2Books:"hip3_l2books.json"});function jt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function d(e,t){throw new TypeError(`Fixture fixtures/${e}: ${t}`)}function k(e,t,n){jt(e)||d(t,`${n} must be an object`)}function m(e,t,n){(typeof e!="string"||e.length===0)&&d(t,`${n} must be a nonempty string`)}function _(e,t,n){Number.isSafeInteger(e)||d(t,`${n} must be a safe integer`)}function U(e,t,n){k(e,t,n);for(let[r,s]of Object.entries(e))m(r,t,`${n} key`),k(s,t,`${n}.${r}`)}function Ft(e,t){k(e,t,"root"),_(e.capturedAt,t,"capturedAt"),k(e.venues,t,"venues");let n=[["hyperliquid_hip3","dexs"],["arcus","markets"],["arcus_spot","pairs"],["rh_uniswap","pools"],["rh_chainlink_oracles","assets"]];for(let[r,s]of n){let o=e.venues[r];k(o,t,`venues.${r}`),m(o.type,t,`venues.${r}.type`),m(o.chain,t,`venues.${r}.chain`),m(o.tier,t,`venues.${r}.tier`),U(o[s],t,`venues.${r}.${s}`)}for(let[r,s]of Object.entries(e.venues.hyperliquid_hip3.dexs))U(s,t,`venues.hyperliquid_hip3.dexs.${r}`)}function Pt(e,t){U(e,t,"root"),Object.keys(e).length===0&&d(t,"root must not be empty");for(let[n,r]of Object.entries(e))Array.isArray(r.venues)||d(t,`${n}.venues must be an array`),r.venues.forEach((s,o)=>m(s,t,`${n}.venues[${o}]`))}function Bt(e,t){k(e,t,"root");for(let n of["chainId","block","oracleScaleExp","usdgDecimals","equityDecimals"])_(e[n],t,n);m(e.usdg,t,"usdg"),U(e.assets,t,"assets");for(let[n,r]of Object.entries(e.assets))m(r.oracle,t,`assets.${n}.oracle`),m(r.token,t,`assets.${n}.token`),(typeof r.rawPrice!="string"||!/^\d+$/.test(r.rawPrice))&&d(t,`assets.${n}.rawPrice must be an integer string`),(typeof r.usd!="number"||!Number.isFinite(r.usd)||r.usd<0)&&d(t,`assets.${n}.usd must be a nonnegative finite source number`)}function Ct(e,t){k(e,t,"root");for(let r of["holidayDayIndex","names","dates"])Array.isArray(e[r])||d(t,`${r} must be an array`);let n=e.holidayDayIndex.length;(e.names.length!==n||e.dates.length!==n)&&d(t,"holidayDayIndex, names, and dates must have equal lengths"),e.holidayDayIndex.forEach((r,s)=>_(r,t,`holidayDayIndex[${s}]`)),e.names.forEach((r,s)=>m(r,t,`names[${s}]`)),e.dates.forEach((r,s)=>{(typeof r!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(r))&&d(t,`dates[${s}] must use YYYY-MM-DD`)})}function Ht(e,t){k(e,t,"root"),(!Array.isArray(e.dstTransitions)||e.dstTransitions.length===0)&&d(t,"dstTransitions must be a nonempty array");let n=new Set;e.dstTransitions.forEach((r,s)=>{k(r,t,`dstTransitions[${s}]`);for(let o of["year","startUtc","endUtc"])_(r[o],t,`dstTransitions[${s}].${o}`);r.startUtc>=r.endUtc&&d(t,`dstTransitions[${s}] startUtc must be before endUtc`),n.has(r.year)&&d(t,`dstTransitions contains duplicate year ${r.year}`),n.add(r.year)})}function zt(e,t){U(e,t,"root"),Object.keys(e).length===0&&d(t,"root must not be empty");for(let[n,r]of Object.entries(e)){for(let s of["addr","quote","quoteAddr","dex","pair"])m(r[s],t,`${n}.${s}`);(typeof r.liq!="number"||!Number.isFinite(r.liq)||r.liq<0)&&d(t,`${n}.liq must be a nonnegative finite source number`)}}function Lt(e,t){k(e,t,"root"),_(e.capturedAt,t,"capturedAt"),_(e.block,t,"block"),_(e.chainId,t,"chainId"),m(e.gasPriceWei,t,"gasPriceWei"),m(e.stateView,t,"stateView"),U(e.pools,t,"pools"),Object.keys(e.pools).length===0&&d(t,"pools must not be empty");for(let[n,r]of Object.entries(e.pools)){for(let s of["pair","version","quote","token","sqrtPriceX96"])m(r[s],t,`pools.${n}.${s}`);r.version!=="v3"&&r.version!=="v4"&&d(t,`pools.${n}.version must be v3 or v4`),typeof r.quoteIsToken0!="boolean"&&d(t,`pools.${n}.quoteIsToken0 must be a boolean`),(!/^[0-9]+$/.test(r.sqrtPriceX96)||BigInt(r.sqrtPriceX96)<=0n)&&d(t,`pools.${n}.sqrtPriceX96 must be a positive integer string`)}}function Wt(e,t){k(e,t,"root"),_(e.capturedAt,t,"capturedAt"),m(e.source,t,"source"),k(e.books,t,"books"),Object.keys(e.books).length===0&&d(t,"books must not be empty");for(let[n,r]of Object.entries(e.books)){k(r,t,`books.${n}`),(!Array.isArray(r.bids)||!Array.isArray(r.asks))&&d(t,`books.${n} must have bids and asks arrays`);for(let[s,o]of r.bids.entries())k(o,t,`books.${n}.bids[${s}]`),m(o.px,t,`books.${n}.bids[${s}].px`),m(o.sz,t,`books.${n}.bids[${s}].sz`);for(let[s,o]of r.asks.entries())k(o,t,`books.${n}.asks[${s}]`),m(o.px,t,`books.${n}.asks[${s}].px`),m(o.sz,t,`books.${n}.asks[${s}].sz`)}}function Qt(e,t){k(e,t,"root"),_(e.capturedAt,t,"capturedAt"),m(e.source,t,"source"),m(e.chain,t,"chain"),U(e.tokens,t,"tokens"),k(e.pairs,t,"pairs"),Object.keys(e.tokens).length===0&&d(t,"tokens must not be empty");for(let[n,r]of Object.entries(e.tokens)){m(r.symbolRaw,t,`tokens.${n}.symbolRaw`),m(r.mint,t,`tokens.${n}.mint`),Object.hasOwn(e.pairs,n)||d(t,`pairs.${n} is required for token ${n}`),(!Array.isArray(e.pairs[n])||e.pairs[n].length===0)&&d(t,`pairs.${n} must be a nonempty array`);for(let[s,o]of e.pairs[n].entries())k(o,t,`pairs.${n}[${s}]`),m(o.pairAddress,t,`pairs.${n}[${s}].pairAddress`),m(o.dexId,t,`pairs.${n}[${s}].dexId`),(typeof o.priceUsd!="number"||!Number.isFinite(o.priceUsd)||o.priceUsd<=0)&&d(t,`pairs.${n}[${s}].priceUsd must be a positive finite number`),(typeof o.liquidityUsd!="number"||!Number.isFinite(o.liquidityUsd)||o.liquidityUsd<0)&&d(t,`pairs.${n}[${s}].liquidityUsd must be a nonnegative finite number`)}}function Xt(e,t){k(e,t,"root"),_(e.capturedAt,t,"capturedAt"),m(e.source,t,"source"),m(e.chain,t,"chain"),e.chain!=="ton"&&d(t,'chain must be "ton"'),U(e.tokens,t,"tokens"),k(e.pairs,t,"pairs"),Object.keys(e.tokens).length===0&&d(t,"tokens must not be empty");for(let[n,r]of Object.entries(e.tokens)){m(r.symbolRaw,t,`tokens.${n}.symbolRaw`),m(r.mint,t,`tokens.${n}.mint`),Object.hasOwn(e.pairs,n)||d(t,`pairs.${n} is required for token ${n}`),(!Array.isArray(e.pairs[n])||e.pairs[n].length===0)&&d(t,`pairs.${n} must be a nonempty array`);for(let[s,o]of e.pairs[n].entries())k(o,t,`pairs.${n}[${s}]`),m(o.pairAddress,t,`pairs.${n}[${s}].pairAddress`),m(o.dexId,t,`pairs.${n}[${s}].dexId`),(typeof o.priceUsd!="number"||!Number.isFinite(o.priceUsd)||o.priceUsd<=0)&&d(t,`pairs.${n}[${s}].priceUsd must be a positive finite number`),(typeof o.liquidityUsd!="number"||!Number.isFinite(o.liquidityUsd)||o.liquidityUsd<0)&&d(t,`pairs.${n}[${s}].liquidityUsd must be a nonnegative finite number`)}}var Vt=Object.freeze({venues:Ft,universe:Pt,oracles:Bt,nyseHolidays:Ct,dstTransitions:Ht,equityDexPools:zt,rhPoolState:Lt,solanaXstocks:Qt,tonXstocks:Xt,hip3L2Books:Wt});function Kt(e,t){let n=Ue[t],r=Me(e,n),s;try{s=It(r,"utf8")}catch(i){throw i?.code==="ENOENT"?new Error(`Fixture fixtures/${n} is missing at ${r}`):new Error(`Fixture fixtures/${n} could not be read: ${i.message}`)}let o;try{o=JSON.parse(s)}catch(i){throw new SyntaxError(`Fixture fixtures/${n} contains invalid JSON: ${i.message}`)}return Vt[t](o,n),o}function je(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.values(e))je(t)}return e}function Fe({fixtureDir:e=Ut}={}){if(typeof e!="string"||e.length===0)throw new TypeError("fixtureDir must be a nonempty path string");let t={};for(let n of Object.keys(Ue))t[n]=Kt(e,n);return je(t)}var De;function j(){return De??=Fe(),De}function q(){return j().venues}function Pe(){return j().oracles}function Be(){return j().nyseHolidays}function Ce(){return j().dstTransitions}function J(){return j().rhPoolState}function He(){return j().solanaXstocks}function ze(){return j().tonXstocks}function Le(){return j().hip3L2Books}var pe=1e3,Xe=60*pe,de=60*Xe,We=24*de,Yt=-5*de,Jt=-4*de,Ve=240,Ke=570,Ye=960,Je=1200,Mr=Object.freeze([Ve,Ke,Ye,Je]),Ur=Object.freeze(["core","extended","dark"]),Qe,fe;function Gt(){let e=Ce().dstTransitions.map(r=>({year:r.year,startMs:r.startUtc*pe,endMs:r.endUtc*pe}));e.sort((r,s)=>r.startMs-s.startMs);let t=e[0].year,n=e[e.length-1].year;return Object.freeze({rows:Object.freeze(e),firstYear:t,lastYear:n,coverageStartMs:Date.UTC(t,0,1),coverageEndMs:Date.UTC(n+1,0,1)})}function Ge(){return Qe??=Gt(),Qe}function Zt(){return fe===void 0&&(fe=new Set(Be().holidayDayIndex)),fe}function Ze(e,t){if(!Number.isSafeInteger(e))throw new TypeError(`${t}: epochMs must be a safe integer number of milliseconds`)}function en(e,t){let{coverageStartMs:n,coverageEndMs:r,firstYear:s,lastYear:o}=Ge();if(e<n||e>=r)throw new RangeError(`${t}: ${new Date(e).toISOString()} is outside DST fixture coverage (${s} through ${o}). Refusing to assume a UTC offset.`)}function tn(e){for(let t of Ge().rows)if(e>=t.startMs&&e<t.endMs)return!0;return!1}function nn(e){return tn(e)?Jt:Yt}function rn(e){let t=e+nn(e),n=Math.floor(t/We),r=t-n*We,s=new Date(t);return{dayIndex:n,minuteOfDay:Math.floor(r/Xe),msIntoDay:r,weekday:s.getUTCDay()}}function sn({dayIndex:e,weekday:t}){return t===0||t===6?!1:!Zt().has(e)}function on(e){return e<Ve?"dark":e<Ke?"extended":e<Ye?"core":e<Je?"extended":"dark"}function X(e){Ze(e,"sessionState"),en(e,"sessionState");let t=rn(e);return sn(t)?on(t.minuteOfDay):"dark"}function me(e){return Ze(e,"isDark"),X(e)==="dark"}var G=Object.freeze({DORMANT_VENUE:"dormant-venue",CROSSED_BOOK:"crossed-book",STALE_QUOTE:"stale-quote",STALE_ORACLE:"stale-oracle"}),un=12e4,an=6e5;function Z(e,t){e.push(Object.freeze({venue:t.venue,symbol:t.symbol??null,reason:t.reason,evidence:t.evidence??null}))}function cn(e){let t=e.raw?.vol24h;return!!(t===0||t===0||typeof t=="number"&&Number.isFinite(t)&&t<=0)}function ln(e){return!e.bid||!e.ask?!1:M(e.bid,e.ask)>0}function et(e,t,n){return Number.isSafeInteger(e.capturedAt)?t-e.capturedAt>n:!1}function ee(e,t={}){if(!Array.isArray(e))throw new TypeError("quotes must be an array");let n=t.nowMs??Date.now(),r=t.quoteFreshnessMs??un,s=t.oracleFreshnessMs??an,o=t.includeDormant===!0,i=[],u=[];for(let a of e){if(cn(a)){o?i.push(Object.freeze({...a,staleData:!0})):Z(u,{venue:a.venue,symbol:a.symbolRaw??a.symbol,reason:G.DORMANT_VENUE,evidence:{vol24h:a.raw?.vol24h??null}});continue}if(ln(a)){Z(u,{venue:a.venue,symbol:a.symbolRaw??a.symbol,reason:G.CROSSED_BOOK,evidence:{bid:a.bid?String(a.bid.mantissa)+"e-"+a.bid.scale:null,ask:a.ask?String(a.ask.mantissa)+"e-"+a.ask.scale:null}});continue}if(et(a,n,r)){Z(u,{venue:a.venue,symbol:a.symbolRaw??a.symbol,reason:G.STALE_QUOTE,evidence:{capturedAt:a.capturedAt,nowMs:n,ageMs:n-a.capturedAt,freshnessMs:r}});continue}if(a.tier==="read-only"&&a.raw?.oracleRaw!==void 0){let l=X(n),c=l==="core"?s:s*2;if(et(a,n,c)){Z(u,{venue:a.venue,symbol:a.symbolRaw??a.symbol,reason:G.STALE_ORACLE,evidence:{capturedAt:a.capturedAt,nowMs:n,session:l}});continue}}i.push(a)}return{survivors:i,excluded:u}}function fn(e){if(typeof e!="number"||!Number.isFinite(e))throw new TypeError("value must be a finite number");let t=String(e);if(!t.includes("e")&&!t.includes("E"))return t;let[n,r]=t.split(/[eE]/),s=Number(r),o=n.startsWith("-"),i=o?n.slice(1):n,[u,a=""]=i.split("."),l=`${u}${a}`,c=u.length+s,p;return c<=0?p=`0.${"0".repeat(-c)}${l}`:c>=l.length?p=`${l}${"0".repeat(c-l.length)}`:p=`${l.slice(0,c)}.${l.slice(c)}`,`${o?"-":""}${p}`}function w(e){return e==null?null:typeof e=="string"?f(e):typeof e!="number"||!Number.isFinite(e)?null:f(fn(e))}function I(e,t){let n=w(e);if(n===null)throw new TypeError(`${t} must be a finite source number`);return n}var pn=new Set(["spot","perp"]),dn=new Set(["read-only","quote-only","prepare","intent"]),mn=new Set(["buy","sell"]),bn=new Set(["net-of-cost","gross"]),yn=new Set(["homogeneous","heterogeneous"]),hn=["bid","ask","mid","mark"],tt=["fees","gasEstimate","priceImpact","fundingHourly"],gn=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function h(e,t){throw new TypeError(`${e} ${t}`)}function rt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function B(e,t){rt(e)||h(t,"must be an object")}function st(e,t,n){Object.hasOwn(e,t)||h(`${n}.${t}`,"is required")}function C(e,t){(typeof e!="string"||e.length===0)&&h(t,"must be a nonempty string")}function V(e,t,n){t.has(e)||h(n,`must be one of ${[...t].join(", ")}`)}function ye(e,t){(!Number.isSafeInteger(e)||e<0)&&h(t,"must be a nonnegative safe integer")}function be(e,t,n=!1){e===null&&n||(rt(e)||h(t,"must be a fixed point value"),typeof e.mantissa!="bigint"&&h(`${t}.mantissa`,"must be a bigint"),(!Number.isSafeInteger(e.scale)||e.scale<0)&&h(`${t}.scale`,"must be a nonnegative safe integer"))}function te(e,t,n=!1){e===null&&n||B(e,t)}function nt(e,t){B(e,t),C(e.venue,`${t}.venue`),C(e.reason,`${t}.reason`),gn.test(e.reason)||h(`${t}.reason`,"must be a machine readable lower case code"),Object.hasOwn(e,"symbol")&&e.symbol!==null&&C(e.symbol,`${t}.symbol`)}function v(e){B(e,"quote");for(let n of["venue","chain","instrument","tier","symbolRaw","symbol","side","requestedSize",...tt,"costAccounted","capturedAt","blockOrSeq","raw"])st(e,n,"quote");C(e.venue,"quote.venue"),!(typeof e.chain=="string"&&e.chain.length>0)&&!(Number.isSafeInteger(e.chain)&&e.chain>=0)&&h("quote.chain","must be a nonempty string or nonnegative chain id"),V(e.instrument,pn,"quote.instrument"),V(e.tier,dn,"quote.tier"),C(e.symbolRaw,"quote.symbolRaw"),C(e.symbol,"quote.symbol"),V(e.side,mn,"quote.side"),be(e.requestedSize,"quote.requestedSize"),e.requestedSize.mantissa<0n&&h("quote.requestedSize","must not be negative");let t=0;for(let n of hn)Object.hasOwn(e,n)&&(be(e[n],`quote.${n}`),t+=1);t===0&&h("quote","must contain at least one of bid, ask, mid, mark");for(let n of tt)be(e[n],`quote.${n}`,!0);if(typeof e.costAccounted!="boolean"&&h("quote.costAccounted","must be a boolean"),e.costAccounted){for(let n of["fees","gasEstimate","priceImpact"])e[n]===null&&h(`quote.${n}`,"cannot be unknown when costAccounted is true");e.instrument==="perp"&&e.fundingHourly===null&&h("quote.fundingHourly","cannot be unknown when costAccounted is true for a perp")}return e.instrument==="spot"&&e.fundingHourly!==null&&h("quote.fundingHourly","must be null for a spot quote"),ye(e.capturedAt,"quote.capturedAt"),e.blockOrSeq!==null&&!(typeof e.blockOrSeq=="string"&&e.blockOrSeq.length>0)&&!(Number.isSafeInteger(e.blockOrSeq)&&e.blockOrSeq>=0)&&h("quote.blockOrSeq","must be null, a nonempty string, or a nonnegative safe integer"),B(e.raw,"quote.raw"),e}function he(e){B(e,"rankResult");for(let t of["rankedOn","ranked","winner","runnersUp","improvementBps","sourcesAnswered","sourcesTried","failed","excluded","darkWindow","instrumentMix","bestPreparable"])st(e,t,"rankResult");return V(e.rankedOn,bn,"rankResult.rankedOn"),Array.isArray(e.ranked)||h("rankResult.ranked","must be an array"),e.ranked.forEach((t,n)=>te(t,`rankResult.ranked[${n}]`)),te(e.winner,"rankResult.winner",!0),e.ranked.length===0&&e.winner!==null&&h("rankResult.winner","must be null when ranked is empty"),e.ranked.length>0&&e.winner===null&&h("rankResult.winner","must be present when ranked is not empty"),Array.isArray(e.runnersUp)||h("rankResult.runnersUp","must be an array"),e.runnersUp.forEach((t,n)=>te(t,`rankResult.runnersUp[${n}]`)),e.improvementBps!==null&&!(typeof e.improvementBps=="number"&&Number.isFinite(e.improvementBps))&&h("rankResult.improvementBps","must be a finite number or null"),ye(e.sourcesAnswered,"rankResult.sourcesAnswered"),ye(e.sourcesTried,"rankResult.sourcesTried"),e.sourcesAnswered>e.sourcesTried&&h("rankResult.sourcesAnswered","must not exceed sourcesTried"),Array.isArray(e.failed)||h("rankResult.failed","must be an array"),e.failed.forEach((t,n)=>nt(t,`failed[${n}]`)),Array.isArray(e.excluded)||h("rankResult.excluded","must be an array"),e.excluded.forEach((t,n)=>nt(t,`excluded[${n}]`)),e.darkWindow!==null&&B(e.darkWindow,"rankResult.darkWindow"),V(e.instrumentMix,yn,"rankResult.instrumentMix"),te(e.bestPreparable,"rankResult.bestPreparable",!0),Object.hasOwn(e,"carry")&&e.carry!==null&&B(e.carry,"rankResult.carry"),e}var kn="arcus_perp",xn="robinhood-4663",wn="quote-only",ne="0.00000480324074074";function ot(){return q().venues.arcus}function Sn(){return Object.keys(ot().markets).sort()}function $n({symbol:e,side:t="buy",sizeUsd:n=null}={}){if(typeof e!="string"||e.length===0)return null;let r=e.endsWith("-USD")?e.slice(0,-4):e,s=ot().markets[r];if(!s)return null;let o=I(s.mark,`${r}.mark`),i=w(s.oracle),u=w(s.fundingHourly),a=n===null?f("0"):n,l={venue:kn,chain:xn,instrument:"perp",tier:wn,symbolRaw:e,symbol:r,side:t,requestedSize:a,mark:o,fees:null,gasEstimate:null,priceImpact:null,fundingHourly:u,costAccounted:!1,capturedAt:q().capturedAt*1e3,blockOrSeq:null,raw:{fixture:"fixtures/venues.json#venues.arcus",oraclePrice:s.oracle,vol24h:s.vol24h,oi:s.oi,fundingAnnPct:s.fundingAnnPct,category:s.category,isOutsideRth:s.isOutsideRth===!0,rth:s.rth,darkWindowFundingHourly:ne,initialMarginFraction:s.initialMarginFraction??null,offHoursInitialMarginFraction:s.offHoursInitialMarginFraction??null,reasonCostUnknown:"fees, gas, and impact at size not captured for Arcus perps"}};return i!==null&&(l.raw.oracleFixed=i),v(l)}function re({side:e="buy",sizeUsd:t=null}={}){return Sn().map(n=>$n({symbol:n,side:e,sizeUsd:t})).filter(n=>n!==null)}var it=36e5,Zr=24*365;function ge(e,t,n=8){if(e==null)throw new TypeError("hourlyFundingRate is required");if(!Number.isFinite(t)||t<0)throw new RangeError("horizonHours must be a nonnegative finite number");if(t===0)return f("0");let r=f(String(t)),s=$(10000n,0);return E(E(e,r),s)}function ut(e,t,n={}){if(e.instrument!=="perp")return{model:"current-funding-held-constant",horizonHours:t,carryBps:f("0"),carryBpsDisplay:"0",confidence:"estimate",note:"spot has no funding carry"};let r=n.nowMs??Date.now(),s=n.applyDarkWindowLock===!0,o=e.fundingHourly;if(s&&o!==null){let u=An(r,t),a=t-u,l=f(ne),c=ge(o,a),p=ge(l,u),y=Math.max(c.scale,p.scale),b={mantissa:c.mantissa*10n**BigInt(y-c.scale)+p.mantissa*10n**BigInt(y-p.scale),scale:y};return{model:"current-funding-held-constant",horizonHours:t,carryBps:b,carryBpsDisplay:S(b),confidence:"estimate",darkHours:u,litHours:a,darkWindowRate:ne,compounding:"ignored",compoundingErrorBoundNote:"simple sum; at 30d and 1e-5/h the ignored compound is under 0.5bp"}}if(o===null)return{model:"current-funding-held-constant",horizonHours:t,carryBps:null,carryBpsDisplay:null,confidence:"estimate",note:"funding rate unknown"};let i=ge(o,t);return{model:"current-funding-held-constant",horizonHours:t,carryBps:i,carryBpsDisplay:S(i),confidence:"estimate",compounding:"ignored",compoundingErrorBoundNote:"simple sum; at 30d and 1e-5/h the ignored compound is under 0.5bp"}}function An(e,t){if(t<=0)return 0;let n=0,r=Math.floor(t);for(let s=0;s<r;s+=1)me(e+s*it)&&(n+=1);return t>r&&me(e+r*it)&&(n+=t-r),n}function En(e){return e.mid??e.mark??e.ask??e.bid??null}function vn(e){let t=En(e);if(t===null)return null;let n=e.costAccounted===!0,r=f("0");e.fees!==null?r=D(r,e.fees):n=!1,e.priceImpact!==null?r=D(r,e.priceImpact):e.requestedSize&&e.requestedSize.mantissa>0n&&(n=!1),e.gasEstimate===null?n=!1:r=D(r,e.gasEstimate);let s;if(e.fees!==null&&M(e.fees,f("1"))<0&&M(e.fees,f("0"))>=0){let o=D(f("1"),e.fees);s=E(t,o),e.priceImpact!==null&&(s=D(s,E(t,e.priceImpact)))}else s=D(t,r);return{net:s,costAccounted:n,px:t}}function qn(e,t,n=null){return{venue:e.venue,chain:e.chain,instrument:e.instrument,tier:e.tier,symbol:e.symbol,symbolRaw:e.symbolRaw,side:e.side,price:t.px,net:t.net,costAccounted:t.costAccounted,fundingHourly:e.fundingHourly,carry:n,quote:e}}function On(e,t){if(!e||!t||!e.costAccounted||!t.costAccounted||e.instrument!==t.instrument||e.net.mantissa===0n)return null;let n=Q(t.net,e.net);return R(E(n,$(10000n,0)),t.net,4)}function ke(e,t={}){if(!Array.isArray(e))throw new TypeError("quotes must be an array");let n=t.nowMs??e[0]?.capturedAt??Date.now(),r=e.length,s=e,o=[];if(!t.skipLiveness){let x=ee(e,{nowMs:n});s=x.survivors,o=x.excluded}let i=e.length,u=[],a=t.horizonHours,l=Number.isFinite(a)&&a>0,c=[];for(let x of s){let A=vn(x);if(A===null)continue;let O=null;if(l&&x.instrument==="perp"&&(O=ut(x,a,{nowMs:n}),O.carryBps!==null)){let vt=D(f("1"),R(O.carryBps,$(10000n,0),12));A.net=E(A.net,vt),A.costAccounted=!1}c.push(qn(x,A,O))}let p=c,y="homogeneous";if(l)y="heterogeneous",p=c;else{let x=c.filter(O=>O.instrument==="spot"),A=c.filter(O=>O.instrument==="perp");x.length>0&&A.length>0?(p=x.length>=A.length?x:A,y="homogeneous"):(p=c,y="homogeneous")}p.sort((x,A)=>{let O=M(x.net,A.net);return O!==0?O:x.venue<A.venue?-1:x.venue>A.venue?1:0});let b=p[0]??null,g=p.slice(1),F=p,L="gross";b&&b.costAccounted&&(g.length===0||g[0].costAccounted)&&(L="net-of-cost");let Re=g.length===0?null:On(b,g[0]),$t=c.find(x=>x.tier==="prepare")??null,ae=X(n),At=ae==="core"?null:{session:ae,warning:ae==="dark"?"market is dark; marks are not real price discovery":"extended session; thinner books and higher staleness risk"},Ie=null;l&&(Ie=Rn(c));let Et={rankedOn:L,ranked:F,winner:b,runnersUp:g,improvementBps:Re===null?null:Number(S(Re)),sourcesAnswered:i,sourcesTried:r,failed:u,excluded:o,darkWindow:At,instrumentMix:y,bestPreparable:$t,carry:b?.carry??null,breakEvenHorizonHours:Ie};return he(Et)}function Rn(e){let t=e.filter(o=>o.instrument==="spot").sort((o,i)=>M(o.net,i.net))[0],n=e.filter(o=>o.instrument==="perp").sort((o,i)=>M(o.net,i.net))[0];if(!t||!n||n.fundingHourly===null)return null;let r=Q(t.net,n.net);if(r.mantissa===0n)return 0;let s=E(n.fundingHourly,n.price);if(s.mantissa===0n)return null;try{let o=R(r,s,4),i=Number(S(o));return!Number.isFinite(i)||i<0?null:i}catch{return null}}var In="rh_uniswap",Tn=4663,_n="prepare",Nn=1n<<192n,H=18,Dn=Object.freeze({v3:180000n,v4:240000n});function xe(){return J()}function Mn(e){return{mantissa:e*e*10n**BigInt(H)/Nn,scale:H}}function Un(e){let t=Mn(BigInt(e.sqrtPriceX96)),n=e.quote==="USDG"?6:18,r=18;if(e.quoteIsToken0){let s=R(E(t,$(10n**BigInt(n),0)),$(10n**BigInt(r),0),H);return s.mantissa===0n?null:R(f("1"),s,H)}return R(E(t,$(10n**BigInt(r),0)),$(10n**BigInt(n),0),H)}function jn(e){let t=Pe(),n=t.assets[e];return n?$(n.rawPrice,t.oracleScaleExp):null}function Fn(e,t){if(e===null||t===null||e.mantissa<=0n||t.mantissa<=0n)return null;let n={...e};return R(t,Pn(n,t),H)}function Pn(e,t){let n=Math.max(e.scale,t.scale);return{mantissa:W(e,n).mantissa+W(t,n).mantissa,scale:n}}function Bn(e){let t=xe(),n=Dn[e];return n?{wei:BigInt(t.gasPriceWei)*n,units:n,native:"ETH"}:null}function we(){return Object.keys(xe().pools).sort()}function z({symbol:e,side:t="buy",sizeUsd:n=null}={}){if(typeof e!="string"||e.length===0)throw new TypeError("symbol must be a nonempty string");let r=xe(),s=r.pools[e];if(!s)return null;let o=Un(s);if(o===null)return null;let i=w(s.liqUsd),u=n===null?f("0"):n,a=s.feePpm===null||s.feePpm===void 0?null:R($(BigInt(s.feePpm),0),$(1000000n,0),8),l=u.mantissa===0n?f("0"):Fn(i,u),c=Bn(s.version),b={venue:In,chain:Tn,instrument:"spot",tier:_n,symbolRaw:e,symbol:e,side:t,requestedSize:u,mid:o,fees:a,gasEstimate:null,priceImpact:l,fundingHourly:null,costAccounted:!1,capturedAt:r.capturedAt*1e3,blockOrSeq:r.block,raw:{fixture:"fixtures/rh_pool_state.json",pair:s.pair,version:s.version,sqrtPriceX96:s.sqrtPriceX96,quote:s.quote,quoteIsToken0:s.quoteIsToken0,liqUsd:s.liqUsd,gasNativeWei:c===null?null:c.wei.toString(),gasUnits:c===null?null:c.units.toString(),impactModel:"constant-product-estimate",notes:["price read live from chain 4663",s.version==="v4"?"v4 fee may be dynamic via hook and was not captured":"v3 fee tier is the pool static fee","gas known in native wei only, no ETH price captured to denominate it"]}},g=jn(e);return g!==null&&(b.referencePrice=g,b.referenceBasisBps=S(R(E(Q(o,g),$(10000n,0)),g,4))),v(b)}function at({side:e="buy",sizeUsd:t=null}={}){return we().map(n=>z({symbol:n,side:e,sizeUsd:t})).filter(n=>n!==null)}var ct=12e4,Cn="0x0000000000000000000000000000000000000000",Hn="0x84b75b19A3cdf8E2F56d0507d22D442847B2053C";function Se(e={}){let{symbol:t,side:n="buy",sizeUsd:r=null,recipient:s,nowMs:o=Date.now()}=e;if(typeof t!="string"||!t)throw new TypeError("symbol is required");if(typeof s!="string"||!/^0x[0-9a-fA-F]{40}$/.test(s))throw new TypeError("recipient must be a 0x-prefixed 20 byte address");let i=z({symbol:t,side:n,sizeUsd:r});if(i===null)throw new Error(`no RH Uniswap pool for ${t}`);if(i.tier!=="prepare")throw new Error(`route tier is ${i.tier}, only prepare tier can be prepared`);let u=o-i.capturedAt;if(u>ct)throw new Error(`quote is stale (${u}ms old, bound ${ct}ms); re-quote before preparing`);let l=J().pools[t],c=l.version==="v4"?Hn:Cn,p=c,y=n==="buy"?l.quoteAddr:l.token;return Object.freeze({artifactKind:"unsigned-tx",chainId:4663,to:c,data:"0x",value:"0",requiresApproval:{spender:p,token:y,amount:null},requiresWalletSignature:!0,backendSigner:!1,unsigned:!0,houseSigned:!1,quoteRef:{venue:i.venue,symbol:i.symbol,symbolRaw:i.symbolRaw,capturedAt:i.capturedAt,blockOrSeq:i.blockOrSeq,mid:i.mid,version:l.version,pair:l.pair},quoteAgeMs:u,recipient:s,side:n,notes:["prepare-only: user wallet must sign","calldata encoding is deferred; this artifact is the bound intent",l.version==="v4"?"V4 route via PoolManager":"V3 route via SwapRouter (address not yet pinned)"]})}var zn="hyperliquid_hip3",Ln="hyperliquid",Wn="quote-only";function K(){return q().venues.hyperliquid_hip3}function lt(){return Object.keys(K().dexs).sort()}function Qn(){let e=[];for(let[t,n]of Object.entries(K().dexs))for(let r of Object.keys(n))e.push(`${t}:${r}`);return e.sort()}function Xn(e){if(typeof e!="string"||e.length===0)return[];let t=e.indexOf(":");if(t>0){let r=e.slice(0,t),s=e.slice(t+1),o=K().dexs[r]?.[s];return o?[{dex:r,ticker:s,market:o}]:[]}let n=[];for(let[r,s]of Object.entries(K().dexs))Object.hasOwn(s,e)&&n.push({dex:r,ticker:e,market:s[e]});return n}function Vn(e,t){try{return Le().books[`${e}:${t}`]??null}catch{return null}}function Kn(e,t,n){if(!e||n===null||n.mantissa<=0n)return null;let r=t==="buy"?e.asks:e.bids;if(!r||r.length===0)return null;let s=Number(S(n));if(!Number.isFinite(s)||s<=0)return null;let o=0,i=0,u=0;for(let a of r){let l=Number(a.px),c=Number(a.sz);if(!(l>0)||!(c>0))continue;let p=l*c,y=Math.min(s,p),b=y/l;if(o+=y,i+=b,s-=y,u+=1,s<=1e-9)break}return i<=0?null:{vwap:o/i,filledUsd:o,unfilledUsd:Math.max(0,s),levelsUsed:u}}function Yn(e,t,n,r){let s=Kn(e,t,n);if(!s)return{impact:null,depth:null};let o=Number(S(r));if(!(o>0))return{impact:null,depth:s};let i=t==="buy"?(s.vwap-o)/o:(o-s.vwap)/o,u=Math.max(0,i);return{impact:w(Number(u.toPrecision(12))),depth:{...s,impactFraction:u,fullyFilled:s.unfilledUsd<=1e-6}}}function ft({dex:e,ticker:t,market:n,side:r,size:s}){let o=I(n.mark,`${e}:${t}.mark`),i=w(n.fundingHourly),u=w(n.vol24h),a=w(n.oi),l=s===null?f("0"):s,c=Vn(e,t),p=null,y=null,b="fees and gas not captured";if(l.mantissa>0n)if(c){let L=Yn(c,r,l,o);p=L.impact,y=L.depth,y?.fullyFilled?b="impact measured from l2Book; fees and gas still not captured":b="book walked but size exceeds visible depth; fees and gas not captured"}else b="no order book depth wired for this coin; fees and gas not captured";else c?b="zero size; fees and gas not captured":b="no order book depth wired for this coin; fees and gas not captured";let F={venue:zn,chain:Ln,instrument:"perp",tier:Wn,symbolRaw:`${e}:${t}`,symbol:t,side:r,requestedSize:l,mark:o,fees:null,gasEstimate:null,priceImpact:p,fundingHourly:i,costAccounted:!1,capturedAt:q().capturedAt*1e3,blockOrSeq:null,raw:{fixture:"fixtures/venues.json#venues.hyperliquid_hip3",dex:e,ticker:t,vol24h:n.vol24h,oi:n.oi,fundingAnnPct:n.fundingAnnPct,maxLev:n.maxLev,reasonCostUnknown:b,hasL2Book:c!==null,l2BookFixture:c?"fixtures/hip3_l2books.json":null,depth:y}};return u!==null&&(F.raw.vol24hFixed=u),a!==null&&(F.raw.oiFixed=a),c?.bids?.[0]&&c?.asks?.[0]&&(F.bid=f(String(c.bids[0].px)),F.ask=f(String(c.asks[0].px))),v(F)}function pt({symbol:e,side:t="buy",sizeUsd:n=null}={}){let r=Xn(e);return r.length===0||r.length>1?null:ft({...r[0],side:t,size:n})}function se({side:e="buy",sizeUsd:t=null,ticker:n=null}={}){let r=[];for(let s of Qn()){let[o,i]=s.split(":");if(n!==null&&i!==n)continue;let u=K().dexs[o][i];r.push(ft({dex:o,ticker:i,market:u,side:e,size:t}))}return r}var Jn="arcus_spot",Gn="robinhood-4663",Zn="quote-only";function dt(){return q().venues.arcus_spot}function er(){return Object.keys(dt().pairs).sort()}function tr({symbol:e,side:t="buy",sizeUsd:n=null}={}){if(typeof e!="string"||e.length===0)return null;let r=dt().pairs[e];if(!r)return null;let s=r.bid===void 0||r.bid===null?null:I(r.bid,`${e}.bid`),o=r.ask===void 0||r.ask===null?null:I(r.ask,`${e}.ask`),i=w(r.last),u=null;if(s!==null&&o!==null){u={mantissa:s.mantissa+o.mantissa,scale:s.scale===o.scale?s.scale+1:Math.max(s.scale,o.scale)+1};let p=Math.max(s.scale,o.scale),y=s.scale===p?s.mantissa:s.mantissa*10n**BigInt(p-s.scale),b=o.scale===p?o.mantissa:o.mantissa*10n**BigInt(p-o.scale);u={mantissa:y+b,scale:p+1},u={mantissa:(y+b)/2n,scale:p}}else i!==null&&(u=i);if(s===null&&o===null&&u===null)return null;let a=n===null?f("0"):n,l=f("0"),c={venue:Jn,chain:Gn,instrument:"spot",tier:Zn,symbolRaw:e,symbol:e,side:t,requestedSize:a,fees:l,gasEstimate:null,priceImpact:null,fundingHourly:null,costAccounted:!1,capturedAt:q().capturedAt*1e3,blockOrSeq:null,raw:{fixture:"fixtures/venues.json#venues.arcus_spot",last:r.last,bid:r.bid,ask:r.ask,vol24h:r.vol24h,feeKnownZero:!0,reasonCostUnknown:"gas and impact at size not captured; fee is a known zero"}};return s!==null&&(c.bid=s),o!==null&&(c.ask=o),u!==null&&(c.mid=u),v(c)}function oe({side:e="buy",sizeUsd:t=null}={}){return er().map(n=>tr({symbol:n,side:e,sizeUsd:t})).filter(n=>n!==null)}var nr="solana_xstocks",rr="solana",sr="quote-only",mt=25e3;function ie(){return He()}function $e(){return Object.keys(ie().tokens).sort()}function or(e){let t=ie().pairs[e];return!t||t.length===0?null:[...t].sort((n,r)=>(r.liquidityUsd??0)-(n.liquidityUsd??0))[0]}function ir(e,t){if(e===null||t===null)return null;if(e.mantissa<=0n||t.mantissa<=0n)return f("0");let n=Math.max(e.scale,t.scale),r=e.scale===n?e.mantissa:e.mantissa*10n**BigInt(n-e.scale),s=t.scale===n?t.mantissa:t.mantissa*10n**BigInt(n-t.scale),o=s*10n**6n,i=r+s;return{mantissa:o/i,scale:6}}function Ae({symbol:e,side:t="buy",sizeUsd:n=null}={}){if(typeof e!="string"||e.length===0)return null;let r=e,s=e,o=ie().tokens;if(Object.hasOwn(o,e))r=e,s=o[e].symbolRaw;else if(e.endsWith("x")||e.endsWith("X")){let g=e.slice(0,-1).toUpperCase();if(Object.hasOwn(o,g))r=g,s=o[g].symbolRaw;else return null}else return null;let i=o[r],u=or(r);if(!i||!u)return null;let a=I(u.priceUsd,`${r}.priceUsd`),l=w(u.liquidityUsd),c=n===null?f("0"):n,p=c.mantissa===0n?f("0"):ir(l,c),y=!1;c.mantissa===0n&&(u.liquidityUsd??0)>=mt&&(y=!1);let b={venue:nr,chain:rr,instrument:"spot",tier:sr,symbolRaw:s,symbol:r,side:t,requestedSize:c,mid:a,fees:null,gasEstimate:null,priceImpact:p,fundingHourly:null,costAccounted:y,capturedAt:ie().capturedAt*1e3,blockOrSeq:null,raw:{fixture:"fixtures/solana_xstocks.json",mint:i.mint,pairAddress:u.pairAddress,dexId:u.dexId,quote:u.quote,liquidityUsd:u.liquidityUsd,volume24h:u.volume24h,priceUsd:u.priceUsd,source:"dexscreener",approximate:!0,reasonCostUnknown:"DexScreener liquidity.usd is a third-party float; fees and SOL gas not captured; impact is modeled",thin:(u.liquidityUsd??0)<mt}};return v(b)}function bt({side:e="buy",sizeUsd:t=null}={}){return $e().map(n=>Ae({symbol:n,side:e,sizeUsd:t})).filter(n=>n!==null)}var ur="ton_stonfi",ar="ton",cr="quote-only",lr=25e3,fr=.01;function ue(){return ze()}function Ee(){return Object.keys(ue().tokens).sort()}function pr(e){let t=ue().pairs[e];return!t||t.length===0?null:[...t].sort((n,r)=>(r.liquidityUsd??0)-(n.liquidityUsd??0))[0]}function dr(e,t){if(e===null||t===null)return null;if(e.mantissa<=0n||t.mantissa<=0n)return f("0");let n=Math.max(e.scale,t.scale),r=e.scale===n?e.mantissa:e.mantissa*10n**BigInt(n-e.scale),s=t.scale===n?t.mantissa:t.mantissa*10n**BigInt(n-t.scale),o=s*10n**6n,i=r+s;return{mantissa:o/i,scale:6}}function ve({symbol:e,side:t="buy",sizeUsd:n=null}={}){if(typeof e!="string"||e.length===0)return null;let r=e,s=e,o=ue().tokens;if(Object.hasOwn(o,e))r=e,s=o[e].symbolRaw;else if(e.endsWith("x")||e.endsWith("X")){let g=e.slice(0,-1).toUpperCase();if(Object.hasOwn(o,g))r=g,s=o[g].symbolRaw;else return null}else{let g=e.toUpperCase();if(Object.hasOwn(o,g))r=g,s=o[g].symbolRaw;else return null}let i=o[r],u=pr(r);if(!i||!u)return null;let a=I(u.priceUsd,`${r}.priceUsd`),l=w(u.liquidityUsd),c=n===null?f("0"):n,p=c.mantissa===0n?f("0"):dr(l,c),b={venue:ur,chain:ar,instrument:"spot",tier:cr,symbolRaw:s,symbol:r,side:t,requestedSize:c,mid:a,fees:null,gasEstimate:null,priceImpact:p,fundingHourly:null,costAccounted:!1,capturedAt:ue().capturedAt*1e3,blockOrSeq:null,raw:{fixture:"fixtures/ton_xstocks.json",mint:i.mint,pairAddress:u.pairAddress,dexId:u.dexId,quote:u.quote,liquidityUsd:u.liquidityUsd,volume24h:u.volume24h,priceUsd:u.priceUsd,source:"dexscreener",approximate:!0,reasonCostUnknown:"DexScreener liquidity.usd is a third-party float; fees and TON gas not captured; impact is modeled; TON books are thin",thin:(u.liquidityUsd??0)<lr,impactSizeFractionHint:fr}};return v(b)}function yt({side:e="buy",sizeUsd:t=null}={}){return Ee().map(n=>ve({symbol:n,side:e,sizeUsd:t})).filter(n=>n!==null)}var ht=3600*1e3;function qe(e){return e==null||e===""?null:typeof e=="object"&&e&&typeof e.mantissa=="bigint"?e:f(String(e))}function mr(e,{sizeUsd:t=null}={}){if(typeof e!="string"||!e.trim())throw new TypeError("ticker is required");let n=e.trim().toUpperCase(),r=qe(t),s=[],o=pt({symbol:`xyz:${n}`,sizeUsd:r});if(o)s.push(o);else for(let l of se({ticker:n,sizeUsd:r}))s.push(l);for(let l of re({sizeUsd:r}))l.symbol===n&&s.push(l);for(let l of oe({sizeUsd:r}))l.symbol===n&&s.push(l);let i=z({symbol:n,sizeUsd:r});i&&s.push(i);let u=Ae({symbol:n,sizeUsd:r});u&&s.push(u);let a=ve({symbol:n,sizeUsd:r});return a&&s.push(a),s}function gt(e={}){let t=String(e.ticker||e.symbol||"").trim().toUpperCase();if(!t)throw new Error("bestEquityRoute requires ticker");let n=qe(e.sizeUsd??e.size??null),r=mr(t,{sizeUsd:n});if(r.length===0)return{ticker:t,rankedOn:"gross",ranked:[],winner:null,runnersUp:[],improvementBps:null,sourcesAnswered:0,sourcesTried:0,failed:[],excluded:[],bestPreparable:null,instrumentMix:"homogeneous",note:"no venue answered for this ticker in the pinned fixture capture"};let s=r[0].capturedAt,o=String(s).length<=10?s*1e3:s,i=e.nowMs==null,u=e.nowMs??s+1e3,a=Math.max(0,Date.now()-o),l=ke(r,{nowMs:u,horizonHours:e.horizonHours!=null?Number(e.horizonHours):void 0,skipLiveness:e.skipLiveness===!0});return{ticker:t,...l,dataSource:i?"fixture":"caller-clock",capturedAt:o,ageMs:a,stale:a>ht}}function kt(){let e=[{venue:"hyperliquid_hip3",tier:"quote-only",chain:"hyperliquid",n:se().length},{venue:"arcus_perp",tier:"quote-only",chain:"robinhood-4663",n:re().length},{venue:"arcus_spot",tier:"quote-only",chain:"robinhood-4663",n:oe().length},{venue:"rh_uniswap",tier:"prepare",chain:4663,n:we().length},{venue:"solana_xstocks",tier:"quote-only",chain:"solana",n:$e().length},{venue:"ton_stonfi",tier:"quote-only",chain:"ton",n:Ee().length}],t=[...se(),...re(),...oe(),...at(),...bt(),...yt()],n=(t[0]?.capturedAt??Date.now())+1e3,{survivors:r,excluded:s}=ee(t,{nowMs:n});return{inventory:e,hip3Dexs:lt(),liveness:{survivors:r.length,excluded:s.length,byReason:s.reduce((o,i)=>(o[i.reason]=(o[i.reason]??0)+1,o),{})},capturedAt:q().capturedAt,custody:"prepare-only",note:"quote-only venues are ranked for discovery; only rh_uniswap is preparable in v1"}}function xt(e={}){let t=String(e.ticker||e.symbol||"").trim().toUpperCase(),n=e.recipient||e.taker;if(!t)throw new Error("prepareEquityRoute requires ticker");if(!n)throw new Error("prepareEquityRoute requires recipient (signing wallet)");let r=qe(e.sizeUsd??e.size??null),s=z({symbol:t,sizeUsd:r});if(!s)return{ok:!1,failureKind:"no-prepare-path",ticker:t,note:"no RH Uniswap prepare-tier route for this ticker in fixtures"};try{let o=String(s.capturedAt).length<=10?s.capturedAt*1e3:s.capturedAt,i=e.nowMs!=null,u=i?Number(e.nowMs):Date.now(),a=Math.max(0,Date.now()-o),l=Se({symbol:t,sizeUsd:r,recipient:n,nowMs:u});return{ok:!0,ticker:t,artifact:l,bestPreparableVenue:"rh_uniswap",dataSource:i?"caller-clock":"live-clock",capturedAt:o,ageMs:a,stale:a>ht}}catch(o){return{ok:!1,failureKind:"prepare-refused",ticker:t,error:String(o.message||o)}}}function Oe(e){return JSON.parse(JSON.stringify(e,(t,n)=>typeof n=="bigint"?n.toString():n))}function St(){return`oracle equities <command>
3
3
 
4
4
  Commands:
5
5
  venues inventory + tiers + liveness snapshot
@@ -1,22 +1,22 @@
1
1
  #!/usr/bin/env node
2
- import n from"node:fs";import o from"node:path";import m from"node:os";import{randomBytes as H}from"node:crypto";import{execFileSync as F}from"node:child_process";import{fileURLToPath as q}from"node:url";import{existsSync as M,readFileSync as J}from"node:fs";import{dirname as C,join as O}from"node:path";import{fileURLToPath as B}from"node:url";function K(e){let t=C(B(e));for(let s=0;s<8;s+=1){let i=O(t,"package.json");if(M(i))try{let d=JSON.parse(J(i,"utf8"));if(d&&typeof d.version=="string")return t}catch{}let r=C(t);if(r===t)break;t=r}throw new Error(`oracle: could not resolve package root from ${e}`)}function R(e,t){let s=K(t),i=O(s,"dist","assets",e);return M(i)?i:O(s,e)}var z=o.dirname(q(import.meta.url)),$=R("profiles",import.meta.url),E=R("skills",import.meta.url),g=process.argv.slice(2),p=g.includes("--apply"),I=g.includes("--force"),D=g.includes("--json"),b=(()=>{let e=g.indexOf("--only");return e>=0?g[e+1]:null})(),l=(...e)=>{D||console.log(...e)};function W(){return JSON.parse(n.readFileSync(o.join($,"profile.schema.json"),"utf8"))}function Y(e,t,s){let i=[],r=t.required||[];for(let a of r)e[a]===void 0&&i.push(`missing required field: ${a}`);e.id&&!/^[a-z_][a-z0-9-]*$/.test(e.id)&&i.push(`id "${e.id}" must be lowercase, no dots (Hermes rejects dots)`);let d=t.properties.role.enum;e.role&&!d.includes(e.role)&&i.push(`role "${e.role}" not one of ${d.join(", ")}`);let u=e.posture||{};u.default!=="DISARMED"&&i.push("posture.default must be DISARMED -- a lane that ships armed is a bug"),u.signing&&!["none","user-wallet"].includes(u.signing)&&i.push(`posture.signing "${u.signing}" invalid -- Oracle holds no keys`);let c=t.properties.posture.properties.grantActions.items.enum;for(let a of u.grantActions||[])c.includes(a)||i.push(`grantAction "${a}" not allowed (broadcast/sign actions are forbidden)`);typeof u.rationale=="string"&&u.rationale.length<20&&i.push("posture.rationale too short -- justify the grant");for(let a of e.skills||[])s.has(a)||i.push(`skill "${a}" does not exist in skills/`);return i}function G(){if(!n.existsSync(E))return new Map;let e=new Map;for(let t of n.readdirSync(E,{withFileTypes:!0})){if(!t.isDirectory())continue;let s=o.join(E,t.name,"SKILL.md");n.existsSync(s)&&e.set(t.name,s)}return e}function Q(){if(!n.existsSync($))return[];let e=[];for(let t of n.readdirSync($,{withFileTypes:!0})){if(!t.isDirectory())continue;let s=o.join($,t.name,"profile.json");if(!n.existsSync(s))continue;let i=JSON.parse(n.readFileSync(s,"utf8"));i.__dir=o.join($,t.name),e.push(i)}return e}function V(){try{return F("hermes",["--version"],{stdio:"pipe",timeout:2e4}),!0}catch{return!1}}function L(){let e=(process.env.HERMES_HOME||"").trim();if(e){let t=e.split(o.sep),s=t.lastIndexOf("profiles");return s>0&&s===t.length-2?t.slice(0,s).join(o.sep):e}return o.join(m.homedir(),".hermes")}function X(e){try{let t=F("hermes",["profile","list"],{encoding:"utf8",timeout:3e4});return new RegExp(`(^|\\s)${e}(\\s|$)`,"m").test(t)}catch{return!1}}var U=[],h=[],k=[];function N(e,t){try{return n.readFileSync(e,"utf8")===n.readFileSync(t,"utf8")}catch{return!1}}function f(e,t){U.push({kind:e,detail:t,applied:p}),l(`${p?" \u2714":" \xB7"} ${e}: ${t}`)}function Z(e){return e===""||/[:#\[\]{},&*!|>'"%@`\s]/.test(e)||/^(?:null|true|false|\d+)$/i.test(e)?JSON.stringify(e):e}function ee(e,t){return[` ${e}:`," command: node"," args:",` - ${Z(t)}`," enabled: true"].join(`
3
- `)}function te(e,t,s){let i=ee(t,s);if(!n.existsSync(e))return n.writeFileSync(e,`mcp_servers:
2
+ import s from"node:fs";import o from"node:path";import m from"node:os";import{randomBytes as H}from"node:crypto";import{execFileSync as F}from"node:child_process";import{fileURLToPath as q}from"node:url";import{existsSync as M,readFileSync as J}from"node:fs";import{dirname as C,join as O}from"node:path";import{fileURLToPath as B}from"node:url";function K(e){let t=C(B(e));for(let n=0;n<8;n+=1){let i=O(t,"package.json");if(M(i))try{let d=JSON.parse(J(i,"utf8"));if(d&&typeof d.version=="string")return t}catch{}let r=C(t);if(r===t)break;t=r}throw new Error(`oracle: could not resolve package root from ${e}`)}function R(e,t){let n=K(t),i=O(n,e);return M(i)?i:O(n,"dist","assets",e)}var z=o.dirname(q(import.meta.url)),$=R("profiles",import.meta.url),E=R("skills",import.meta.url),g=process.argv.slice(2),p=g.includes("--apply"),I=g.includes("--force"),D=g.includes("--json"),N=(()=>{let e=g.indexOf("--only");return e>=0?g[e+1]:null})(),l=(...e)=>{D||console.log(...e)};function W(){return JSON.parse(s.readFileSync(o.join($,"profile.schema.json"),"utf8"))}function Y(e,t,n){let i=[],r=t.required||[];for(let a of r)e[a]===void 0&&i.push(`missing required field: ${a}`);e.id&&!/^[a-z_][a-z0-9-]*$/.test(e.id)&&i.push(`id "${e.id}" must be lowercase, no dots (Hermes rejects dots)`);let d=t.properties.role.enum;e.role&&!d.includes(e.role)&&i.push(`role "${e.role}" not one of ${d.join(", ")}`);let u=e.posture||{};u.default!=="DISARMED"&&i.push("posture.default must be DISARMED -- a lane that ships armed is a bug"),u.signing&&!["none","user-wallet"].includes(u.signing)&&i.push(`posture.signing "${u.signing}" invalid -- Oracle holds no keys`);let c=t.properties.posture.properties.grantActions.items.enum;for(let a of u.grantActions||[])c.includes(a)||i.push(`grantAction "${a}" not allowed (broadcast/sign actions are forbidden)`);typeof u.rationale=="string"&&u.rationale.length<20&&i.push("posture.rationale too short -- justify the grant");for(let a of e.skills||[])n.has(a)||i.push(`skill "${a}" does not exist in skills/`);return i}function G(){if(!s.existsSync(E))return new Map;let e=new Map;for(let t of s.readdirSync(E,{withFileTypes:!0})){if(!t.isDirectory())continue;let n=o.join(E,t.name,"SKILL.md");s.existsSync(n)&&e.set(t.name,n)}return e}function Q(){if(!s.existsSync($))return[];let e=[];for(let t of s.readdirSync($,{withFileTypes:!0})){if(!t.isDirectory())continue;let n=o.join($,t.name,"profile.json");if(!s.existsSync(n))continue;let i=JSON.parse(s.readFileSync(n,"utf8"));i.__dir=o.join($,t.name),e.push(i)}return e}function V(){try{return F("hermes",["--version"],{stdio:"pipe",timeout:2e4}),!0}catch{return!1}}function L(){let e=(process.env.HERMES_HOME||"").trim();if(e){let t=e.split(o.sep),n=t.lastIndexOf("profiles");return n>0&&n===t.length-2?t.slice(0,n).join(o.sep):e}return o.join(m.homedir(),".hermes")}function X(e){try{let t=F("hermes",["profile","list"],{encoding:"utf8",timeout:3e4});return new RegExp(`(^|\\s)${e}(\\s|$)`,"m").test(t)}catch{return!1}}var U=[],h=[],k=[];function b(e,t){try{return s.readFileSync(e,"utf8")===s.readFileSync(t,"utf8")}catch{return!1}}function f(e,t){U.push({kind:e,detail:t,applied:p}),l(`${p?" \u2714":" \xB7"} ${e}: ${t}`)}function Z(e){return e===""||/[:#\[\]{},&*!|>'"%@`\s]/.test(e)||/^(?:null|true|false|\d+)$/i.test(e)?JSON.stringify(e):e}function ee(e,t){return[` ${e}:`," command: node"," args:",` - ${Z(t)}`," enabled: true"].join(`
3
+ `)}function te(e,t,n){let i=ee(t,n);if(!s.existsSync(e))return s.writeFileSync(e,`mcp_servers:
4
4
  ${i}
5
- `,"utf8"),"created";let r=n.readFileSync(e,"utf8");if(r.includes(s)&&new RegExp(`^\\s*${t}:\\s*$`,"m").test(r))return"present";let d=new RegExp(`^([ \\t]*)${t}:\\s*\\n(?:\\1[ \\t]+.*\\n)*`,"m");return d.test(r)?(r=r.replace(d,`${i}
6
- `),n.writeFileSync(e,r,"utf8"),"updated"):(/^mcp_servers:\s*$/m.test(r)||/^mcp_servers:\s*\n/m.test(r)?r=r.replace(/^(mcp_servers:\s*\n)/m,`$1${i}
5
+ `,"utf8"),"created";let r=s.readFileSync(e,"utf8");if(r.includes(n)&&new RegExp(`^\\s*${t}:\\s*$`,"m").test(r))return"present";let d=new RegExp(`^([ \\t]*)${t}:\\s*\\n(?:\\1[ \\t]+.*\\n)*`,"m");return d.test(r)?(r=r.replace(d,`${i}
6
+ `),s.writeFileSync(e,r,"utf8"),"updated"):(/^mcp_servers:\s*$/m.test(r)||/^mcp_servers:\s*\n/m.test(r)?r=r.replace(/^(mcp_servers:\s*\n)/m,`$1${i}
7
7
  `):/^_config_version:.*$/m.test(r)?r=r.replace(/^(_config_version:.*\n)/m,`$1mcp_servers:
8
8
  ${i}
9
9
  `):r=`mcp_servers:
10
10
  ${i}
11
- ${r}`,n.writeFileSync(e,r,"utf8"),"wired")}var ne=W(),_=G(),P=new Set(_.keys()),S=Q();S=S.filter(e=>!e.template);b&&(S=S.filter(e=>e.id===b));l(`oracle-init ${p?"(APPLY)":"(dry run -- pass --apply to install)"}`);l(` profiles: ${S.length} skills: ${_.size}`);var T=[];for(let e of S){let t=Y(e,ne,P);t.length&&T.push({id:e.id,errors:t})}if(T.length){if(D)process.stdout.write(`${JSON.stringify({ok:!1,invalid:T},null,2)}
11
+ ${r}`,s.writeFileSync(e,r,"utf8"),"wired")}var se=W(),_=G(),P=new Set(_.keys()),S=Q();S=S.filter(e=>!e.template);N&&(S=S.filter(e=>e.id===N));l(`oracle-init ${p?"(APPLY)":"(dry run -- pass --apply to install)"}`);l(` profiles: ${S.length} skills: ${_.size}`);var T=[];for(let e of S){let t=Y(e,se,P);t.length&&T.push({id:e.id,errors:t})}if(T.length){if(D)process.stdout.write(`${JSON.stringify({ok:!1,invalid:T},null,2)}
12
12
  `);else{console.error(`
13
- validation failed:`);for(let e of T){console.error(` ${e.id}:`);for(let t of e.errors)console.error(` - ${t}`)}}process.exit(1)}l(" validation: ok");{let e=o.join(m.homedir(),".config","oracle"),t=o.join(e,"exec.env"),s=!!(process.env.ORACLE_ROUTE_ATTESTATION_SECRET||process.env.MAD_ROUTE_ATTESTATION_SECRET);if(!s&&n.existsSync(t))try{let i=n.readFileSync(t,"utf8");s=/^ORACLE_ROUTE_ATTESTATION_SECRET=.+$/m.test(i)||/^MAD_ROUTE_ATTESTATION_SECRET=.+$/m.test(i)}catch{}if(s)f("attestation secret","present");else if(f("attestation secret",`generate -> ${o.relative(m.homedir(),t)}`),p){n.mkdirSync(e,{recursive:!0,mode:448});try{n.chmodSync(e,448)}catch{}let r=`ORACLE_ROUTE_ATTESTATION_SECRET=${H(32).toString("hex")}
14
- `;if(n.existsSync(t)){let d=n.readFileSync(t,"utf8");!/ORACLE_ROUTE_ATTESTATION_SECRET=/.test(d)&&!/MAD_ROUTE_ATTESTATION_SECRET=/.test(d)&&n.appendFileSync(t,d.endsWith(`
13
+ validation failed:`);for(let e of T){console.error(` ${e.id}:`);for(let t of e.errors)console.error(` - ${t}`)}}process.exit(1)}l(" validation: ok");{let e=o.join(m.homedir(),".config","oracle"),t=o.join(e,"exec.env"),n=!!(process.env.ORACLE_ROUTE_ATTESTATION_SECRET||process.env.MAD_ROUTE_ATTESTATION_SECRET);if(!n&&s.existsSync(t))try{let i=s.readFileSync(t,"utf8");n=/^ORACLE_ROUTE_ATTESTATION_SECRET=.+$/m.test(i)||/^MAD_ROUTE_ATTESTATION_SECRET=.+$/m.test(i)}catch{}if(n)f("attestation secret","present");else if(f("attestation secret",`generate -> ${o.relative(m.homedir(),t)}`),p){s.mkdirSync(e,{recursive:!0,mode:448});try{s.chmodSync(e,448)}catch{}let r=`ORACLE_ROUTE_ATTESTATION_SECRET=${H(32).toString("hex")}
14
+ `;if(s.existsSync(t)){let d=s.readFileSync(t,"utf8");!/ORACLE_ROUTE_ATTESTATION_SECRET=/.test(d)&&!/MAD_ROUTE_ATTESTATION_SECRET=/.test(d)&&s.appendFileSync(t,d.endsWith(`
15
15
  `)||d.length===0?r:`
16
- ${r}`,{mode:384})}else n.writeFileSync(t,r,{mode:384});try{n.chmodSync(t,384)}catch{}}}var v=V();l(v?" hermes CLI: found":` hermes CLI: not found -- installing profile files directly.
16
+ ${r}`,{mode:384})}else s.writeFileSync(t,r,{mode:384});try{s.chmodSync(t,384)}catch{}}}var v=V();l(v?" hermes CLI: found":` hermes CLI: not found -- installing profile files directly.
17
17
  (Hermes discovers any directory under <root>/profiles/, so this works.
18
18
  MCP wiring is the one step that needs the CLI; instructions printed at the end.)`);for(let e of S){l(`
19
- ${e.label} (${e.id})`);let t=o.join(L(),"profiles",e.id),s=o.join(t,"SOUL.md"),i=n.existsSync(s),r=new Map((e.skills||[]).map(c=>[c,n.existsSync(o.join(t,"skills",c,"SKILL.md"))]));if(v?X(e.id):n.existsSync(t))f("profile exists",e.id);else if(v){if(f("create profile",e.id),p)try{F("hermes",["profile","create",e.id],{stdio:"pipe",timeout:12e4})}catch{f("create note",`hermes profile create failed for ${e.id}; writing files directly`)}}else f("create profile dir",e.id),p&&n.mkdirSync(t,{recursive:!0});let u=o.join(e.__dir,"SOUL.md");if(n.existsSync(u)){let c=i&&!N(u,s);if(c&&!I)f("SKIP SOUL.md (exists)",`${o.relative(m.homedir(),s)} -- kept yours; --force to overwrite`),h.push({lane:e.id,file:"SOUL.md",reason:"already exists"});else if(f("install SOUL.md",o.relative(m.homedir(),s)),p){if(n.mkdirSync(o.dirname(s),{recursive:!0}),c){let a=`${s}.bak-oracle-init-${Date.now()}`;n.copyFileSync(s,a),f("backed up",o.relative(m.homedir(),a))}n.copyFileSync(u,s)}}for(let c of e.skills||[]){let a=o.join(t,"skills",c,"SKILL.md");if(r.get(c)&&!N(_.get(c),a)&&!I){f("SKIP skill (exists)",`${c} -> ${e.id}`),h.push({lane:e.id,file:`skills/${c}`,reason:"already exists"});continue}f("install skill",`${c} -> ${e.id}`),p&&(n.mkdirSync(o.dirname(a),{recursive:!0}),n.copyFileSync(_.get(c),a))}for(let c of e.mcp||[]){let a=o.join(z,"oracle-data-mcp.mjs"),y=o.join(t,"config.yaml"),x=`hermes -p ${e.id} mcp add ${c} --command node --args ${a}`;if(c!=="oracle-data"){f("mcp manual",x),k.push({lane:e.id,server:c,command:x});continue}if(f("wire mcp",`${c} (${e.id}) -> ${o.relative(m.homedir(),y)}`),p)try{n.mkdirSync(t,{recursive:!0});let w=te(y,c,a);f("mcp config",`${w}: ${o.relative(m.homedir(),y)}`)}catch(w){f("mcp note",`could not write ${y}: ${w.message}`),k.push({lane:e.id,server:c,command:x})}}f("posture",`DISARMED (${(e.posture.grantActions||[]).join(", ")})`)}var A=o.join(m.homedir(),".config","oracle","skills"),j=E;if(p&&n.existsSync(j)){n.mkdirSync(A,{recursive:!0});let e=0;for(let t of n.readdirSync(j,{withFileTypes:!0})){if(!t.isFile()||!t.name.endsWith(".md"))continue;let s=o.join(j,t.name),i=o.join(A,t.name);if(!I&&n.existsSync(i)){h.push({lane:"standalone",file:t.name});continue}try{n.copyFileSync(s,i),e++}catch(r){f("skill copy",`failed ${t.name}: ${r.message}`)}}e&&l(` standalone skills: ${e} installed to ${A}`)}var se={ok:!0,applied:p,profiles:S.map(e=>e.id),skills:[...P],actions:U.length,skipped:h,mcpManual:k,hermesDetected:v,hermesRoot:L()};if(D)process.stdout.write(`${JSON.stringify(se,null,2)}
19
+ ${e.label} (${e.id})`);let t=o.join(L(),"profiles",e.id),n=o.join(t,"SOUL.md"),i=s.existsSync(n),r=new Map((e.skills||[]).map(c=>[c,s.existsSync(o.join(t,"skills",c,"SKILL.md"))]));if(v?X(e.id):s.existsSync(t))f("profile exists",e.id);else if(v){if(f("create profile",e.id),p)try{F("hermes",["profile","create",e.id],{stdio:"pipe",timeout:12e4})}catch{f("create note",`hermes profile create failed for ${e.id}; writing files directly`)}}else f("create profile dir",e.id),p&&s.mkdirSync(t,{recursive:!0});let u=o.join(e.__dir,"SOUL.md");if(s.existsSync(u)){let c=i&&!b(u,n);if(c&&!I)f("SKIP SOUL.md (exists)",`${o.relative(m.homedir(),n)} -- kept yours; --force to overwrite`),h.push({lane:e.id,file:"SOUL.md",reason:"already exists"});else if(f("install SOUL.md",o.relative(m.homedir(),n)),p){if(s.mkdirSync(o.dirname(n),{recursive:!0}),c){let a=`${n}.bak-oracle-init-${Date.now()}`;s.copyFileSync(n,a),f("backed up",o.relative(m.homedir(),a))}s.copyFileSync(u,n)}}for(let c of e.skills||[]){let a=o.join(t,"skills",c,"SKILL.md");if(r.get(c)&&!b(_.get(c),a)&&!I){f("SKIP skill (exists)",`${c} -> ${e.id}`),h.push({lane:e.id,file:`skills/${c}`,reason:"already exists"});continue}f("install skill",`${c} -> ${e.id}`),p&&(s.mkdirSync(o.dirname(a),{recursive:!0}),s.copyFileSync(_.get(c),a))}for(let c of e.mcp||[]){let a=o.join(z,"oracle-data-mcp.mjs"),y=o.join(t,"config.yaml"),x=`hermes -p ${e.id} mcp add ${c} --command node --args ${a}`;if(c!=="oracle-data"){f("mcp manual",x),k.push({lane:e.id,server:c,command:x});continue}if(f("wire mcp",`${c} (${e.id}) -> ${o.relative(m.homedir(),y)}`),p)try{s.mkdirSync(t,{recursive:!0});let w=te(y,c,a);f("mcp config",`${w}: ${o.relative(m.homedir(),y)}`)}catch(w){f("mcp note",`could not write ${y}: ${w.message}`),k.push({lane:e.id,server:c,command:x})}}f("posture",`DISARMED (${(e.posture.grantActions||[]).join(", ")})`)}var A=o.join(m.homedir(),".config","oracle","skills"),j=E;if(p&&s.existsSync(j)){s.mkdirSync(A,{recursive:!0});let e=0;for(let t of s.readdirSync(j,{withFileTypes:!0})){if(!t.isFile()||!t.name.endsWith(".md"))continue;let n=o.join(j,t.name),i=o.join(A,t.name);if(!I&&s.existsSync(i)){h.push({lane:"standalone",file:t.name});continue}try{s.copyFileSync(n,i),e++}catch(r){f("skill copy",`failed ${t.name}: ${r.message}`)}}e&&l(` standalone skills: ${e} installed to ${A}`)}var ne={ok:!0,applied:p,profiles:S.map(e=>e.id),skills:[...P],actions:U.length,skipped:h,mcpManual:k,hermesDetected:v,hermesRoot:L()};if(D)process.stdout.write(`${JSON.stringify(ne,null,2)}
20
20
  `);else{if(l(`
21
21
  ${p?"installed":"would install"} ${S.length} lanes.`),h.length){l(`${h.length} file(s) already existed and were kept:`);for(let e of h)l(` - ${e.lane}/${e.file}`);l("pass --force to overwrite (a timestamped .bak is written first).")}if(k.length){l(`
22
22
  MCP wiring needed a manual follow-up:`);for(let e of k)l(` ${e.command}`)}p||l("re-run with --apply to make changes."),l(`
@@ -1,4 +1,4 @@
1
- import a from"node:fs";import c from"node:path";import{createHash as Y}from"node:crypto";import{spawnSync as y}from"node:child_process";import x from"node:fs";import M from"node:os";import m from"node:path";import{fileURLToPath as B}from"node:url";var T=m.dirname(B(import.meta.url)),oe=m.resolve(T,"../..");function _(){return process.env.ORACLE_FAKE_HOME||M.homedir()}function V(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function S(){return V()?process.env.ORACLE_CONFIG_DIR||m.join(_(),".config","oracle"):m.join(_(),".config","oracle")}function F(){return m.join(S(),"desk.json")}function K(){return m.join(S(),"env")}function h({force:t=!1}={}){if(h._done&&!t)return h._result||null;h._done=!0;let n={},e=(s,r)=>{if(r==null)return;let i=String(r).trim();i&&(process.env[s]!=null&&String(process.env[s]).trim()!==""||(process.env[s]=i,n[s]=i))};try{let s=K();if(x.existsSync(s))for(let r of x.readFileSync(s,"utf8").split(/\r?\n/)){let i=r.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!i||i[2].startsWith("#"))continue;let u=i[2];(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),e(i[1],u)}}catch{}try{let s=F();if(x.existsSync(s)){let r=JSON.parse(x.readFileSync(s,"utf8"));r&&typeof r=="object"&&(e("ORACLE_DESK_URL",r.deskUrl||r.dataUrl||r.url),e("ORACLE_DATA_URL",r.dataUrl||r.deskUrl||r.url),e("ORACLE_API_URL",r.apiUrl||r.dataUrl||r.deskUrl),e("ORACLE_PUBLIC_URL",r.publicUrl||r.deskUrl||r.dataUrl),e("ORACLE_EXEC_URL",r.execUrl),e("MAD_DESK_URL",r.deskUrl||r.dataUrl))}}catch{}let o=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return o&&(e("ORACLE_DESK_URL",o),e("ORACLE_DATA_URL",o),e("ORACLE_API_URL",o),e("ORACLE_PUBLIC_URL",o),e("MAD_DESK_URL",o)),h._result=Object.keys(n).length?n:null,h._result}try{h()}catch{}function R(t){return x.mkdirSync(t,{recursive:!0}),t}var W="0.19.0",j=`hermes-agent==${W}`,U=[3,11],L=[3,14],g="3.13",A="0.12.1",k=Object.freeze({posix:Object.freeze({url:`https://github.com/astral-sh/uv/releases/download/${A}/uv-installer.sh`,sha256:"d3f5412d38c99f9d024901843bf98206f0d2c6dbe64df40d0b740e2751ca62c1"}),windows:Object.freeze({url:`https://github.com/astral-sh/uv/releases/download/${A}/uv-installer.ps1`,sha256:"b9ec035151bfbb11d616dbd69886498d885551489eddf095ea3c0ad59f640eb0"})});function z(t,{windows:n=process.platform==="win32"}={}){let e=Buffer.isBuffer(t)?t:Buffer.from(t),o=n?k.windows:k.posix,s=Y("sha256").update(e).digest("hex"),r=e.toString("utf8");return s===o.sha256&&r.length>=1e3&&r.includes(A)}function p(){return c.join(S(),"runtime")}function P(){return c.join(p(),"venv")}function C(t){let n=process.platform==="win32"?"Scripts":"bin",e=process.platform==="win32"?`${t}.exe`:t;return c.join(P(),n,e)}function b(){return C("hermes")}function J(){let t=C("python3");return a.existsSync(t)?t:C("python")}function E(){return c.join(p(),"uv",process.platform==="win32"?"uv.exe":"uv")}function v(t){let n=process.platform==="win32"&&!c.extname(t)?["",".exe",".cmd",".bat"]:[""];for(let e of(process.env.PATH||"").split(c.delimiter))if(e)for(let o of n){let s=c.join(e,`${t}${o}`);try{if(a.existsSync(s))return s}catch{}}return null}function X(t){let n=/Python (\d+)\.(\d+)\.(\d+)/.exec(t||"");return n?[Number(n[1]),Number(n[2]),Number(n[3])]:null}function G(t){if(!t)return!1;let[n,e]=t;return!(n<U[0]||n===U[0]&&e<U[1]||n>L[0]||n===L[0]&&e>=L[1])}function $(){let t=[process.env.ORACLE_PYTHON,"python3.13","python3.12","python3.11","python3","python"].filter(Boolean);for(let n of t){let e=c.isAbsolute(n)?a.existsSync(n)?n:null:v(n);if(!e)continue;let o=y(e,["--version"],{encoding:"utf8",timeout:15e3}),s=X(`${o.stdout||""}${o.stderr||""}`);if(G(s))return{bin:e,version:s.join("."),source:"host"}}return null}function D(){return process.env.ORACLE_UV_BIN||v("uv")||(a.existsSync(c.join(_(),".local","bin","uv"))?c.join(_(),".local","bin","uv"):null)||(a.existsSync(E())?E():null)}function Z(t,n){let e=["const fs=require('node:fs');","const [url,dest]=process.argv.slice(1);","fetch(url).then(r=>{if(!r.ok)throw new Error('http '+r.status);return r.arrayBuffer()})",".then(b=>fs.writeFileSync(dest,Buffer.from(b)))",".catch(e=>{console.error(e.message);process.exit(1)});"].join("");return y(process.execPath,["-e",e,t,n],{encoding:"utf8",timeout:2*6e4})}function Q({quiet:t=!1}={}){let n=D();if(n)return{ok:!0,bin:n,reused:!0};R(p());let e=process.platform==="win32",o=c.join(p(),e?"uv-install.ps1":"uv-install.sh"),s=e?k.windows:k.posix,r=Z(s.url,o);if(r.status!==0)return{ok:!1,reason:`could not download the uv installer (${r.status})`,stderr:(r.stderr||"").slice(-800)};let i=a.readFileSync(o);if(!z(i,{windows:e}))return{ok:!1,reason:`uv ${A} installer checksum mismatch`};let u=c.dirname(E());R(u);let d=e?v("powershell.exe")||v("powershell"):v("sh")||"/bin/sh";if(!d)return{ok:!1,reason:e?"PowerShell not found":"sh not found"};let f=y(d,e?["-NoProfile","-ExecutionPolicy","Bypass","-File",o]:[o],{stdio:t?"pipe":"inherit",encoding:"utf8",timeout:5*6e4,env:{...process.env,UV_INSTALL_DIR:u,UV_NO_MODIFY_PATH:"1"}});return f.status!==0||!a.existsSync(E())?{ok:!1,reason:`uv install failed (${f.status})`,stderr:(f.stderr||"").slice(-800)}:{ok:!0,bin:E(),reused:!1}}function O({quiet:t=!1}={}){let n=Q({quiet:t});if(!n.ok)return n;let e=n.bin,o={...process.env,UV_PYTHON_INSTALL_DIR:c.join(p(),"python"),UV_CACHE_DIR:c.join(p(),"cache")},s=y(e,["python","install","--no-bin",g],{stdio:t?"pipe":"inherit",encoding:"utf8",timeout:15*6e4,env:o});if(s.status!==0)return{ok:!1,reason:`uv python install ${g} failed (${s.status})`,stderr:(s.stderr||"").slice(-800)};let r=y(e,["python","find",g],{encoding:"utf8",timeout:6e4,env:o}),i=(r.stdout||"").trim().split(/\r?\n/)[0];return r.status!==0||!i||!a.existsSync(i)?{ok:!1,reason:`uv could not locate python ${g}`}:{ok:!0,bin:i,version:g,source:"uv"}}function q(){if(process.env.ORACLE_HERMES_BIN)return{ok:!0,bin:process.env.ORACLE_HERMES_BIN,source:"env"};let t=v("hermes");if(t)return{ok:!0,bin:t,source:"path"};let n=b();return a.existsSync(n)?{ok:!0,bin:n,source:"managed"}:{ok:!1,bin:null,source:null}}function H(){let t=q(),n=$();return{hermes:t,managedVenv:P(),managedInstalled:a.existsSync(b()),hostPython:n,uv:D()}}function w(t,n,{quiet:e}){return y(t,n,{stdio:e?"pipe":"inherit",encoding:"utf8",timeout:20*6e4})}function I({quiet:t=!1,upgrade:n=!1}={}){let e=$();if(!e){let l=O({quiet:t});if(l.ok)e={bin:l.bin,version:l.version,source:"uv"};else return{ok:!1,reason:`no supported python found (need 3.11-3.13) and uv could not provide one: ${l.reason}. install uv (https://docs.astral.sh/uv) or python 3.13, then re-run 'oracle bootstrap'`}}R(p());let o=P();if(a.existsSync(b())&&!n)return{ok:!0,bin:b(),reused:!0};if(!a.existsSync(c.join(o,"pyvenv.cfg"))){let l=w(e.bin,["-m","venv",o],{quiet:t});if(l.status!==0&&e.source!=="uv"){a.rmSync(o,{recursive:!0,force:!0});let f=O({quiet:t});if(f.ok)e={bin:f.bin,version:f.version,source:"uv"},l=w(e.bin,["-m","venv",o],{quiet:t});else return{ok:!1,reason:`python -m venv failed (${l.status}) and uv fallback failed: ${f.reason}`,stderr:(l.stderr||"").slice(-800)}}if(l.status!==0)return{ok:!1,reason:`isolated python -m venv failed (${l.status})`,stderr:(l.stderr||"").slice(-800)}}let r=J();if(!a.existsSync(r))return{ok:!1,reason:`venv python missing at ${r}`};let i=["-m","pip","install","--disable-pip-version-check"];n&&i.push("--upgrade"),i.push(j);let u=w(r,i,{quiet:t});if(u.status!==0)return{ok:!1,reason:`pip install ${j} failed (${u.status})`,stderr:(u.stderr||"").slice(-1200)};let d=b();return a.existsSync(d)?{ok:!0,bin:d,reused:!1,python:e.version}:{ok:!1,reason:`hermes entrypoint not found after install (${d})`}}function N(){return["oracle bootstrap - optional Hermes install (never required for native Oracle)",""," oracle bootstrap install into ~/.config/oracle/runtime/venv"," oracle bootstrap --upgrade upgrade the managed Hermes runtime"," oracle bootstrap --status show detected Hermes (if any)"," oracle bootstrap --json machine-readable status","","notes:"," native chat/model/auth never need this"," detection never selects Hermes; opt in with ORACLE_CHAT_BACKEND=hermes"," a hermes on PATH wins over managed install; bootstrap never touches system python"," read/prepare commands (chain, scan, route, data) never need this"].join(`
1
+ import a from"node:fs";import c from"node:path";import{createHash as Y}from"node:crypto";import{spawnSync as y}from"node:child_process";import x from"node:fs";import M from"node:os";import m from"node:path";import{fileURLToPath as B}from"node:url";var T=m.dirname(B(import.meta.url)),oe=m.resolve(T,"../..");function _(){return process.env.ORACLE_FAKE_HOME||M.homedir()}function V(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function S(){return V()?process.env.ORACLE_CONFIG_DIR||m.join(_(),".config","oracle"):m.join(_(),".config","oracle")}function F(){return m.join(S(),"desk.json")}function K(){return m.join(S(),"env")}function h({force:t=!1}={}){if(h._done&&!t)return h._result||null;h._done=!0;let n={},e=(s,r)=>{if(r==null)return;let i=String(r).trim();i&&(process.env[s]!=null&&String(process.env[s]).trim()!==""||(process.env[s]=i,n[s]=i))};try{let s=K();if(x.existsSync(s))for(let r of x.readFileSync(s,"utf8").split(/\r?\n/)){let i=r.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!i||i[2].startsWith("#"))continue;let u=i[2];(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),e(i[1],u)}}catch{}try{let s=F();if(x.existsSync(s)){let r=JSON.parse(x.readFileSync(s,"utf8"));r&&typeof r=="object"&&(e("ORACLE_DESK_URL",r.deskUrl||r.dataUrl||r.url),e("ORACLE_DATA_URL",r.dataUrl||r.deskUrl||r.url),e("ORACLE_API_URL",r.apiUrl||r.dataUrl||r.deskUrl),e("ORACLE_PUBLIC_URL",r.publicUrl||r.deskUrl||r.dataUrl),e("ORACLE_EXEC_URL",r.execUrl),e("MAD_DESK_URL",r.deskUrl||r.dataUrl))}}catch{}let o=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return o&&(e("ORACLE_DESK_URL",o),e("ORACLE_DATA_URL",o),e("ORACLE_API_URL",o),e("ORACLE_PUBLIC_URL",o),e("MAD_DESK_URL",o)),h._result=Object.keys(n).length?n:null,h._result}try{h()}catch{}function R(t){return x.mkdirSync(t,{recursive:!0}),t}var W="0.19.0",j=`hermes-agent==${W}`,U=[3,11],L=[3,14],g="3.13",A="0.12.1",k=Object.freeze({posix:Object.freeze({url:`https://github.com/astral-sh/uv/releases/download/${A}/uv-installer.sh`,sha256:"d3f5412d38c99f9d024901843bf98206f0d2c6dbe64df40d0b740e2751ca62c1"}),windows:Object.freeze({url:`https://github.com/astral-sh/uv/releases/download/${A}/uv-installer.ps1`,sha256:"b9ec035151bfbb11d616dbd69886498d885551489eddf095ea3c0ad59f640eb0"})});function z(t,{windows:n=process.platform==="win32"}={}){let e=Buffer.isBuffer(t)?t:Buffer.from(t),o=n?k.windows:k.posix,s=Y("sha256").update(e).digest("hex"),r=e.toString("utf8");return s===o.sha256&&r.length>=1e3&&r.includes(A)}function p(){return c.join(S(),"runtime")}function P(){return c.join(p(),"venv")}function C(t){let n=process.platform==="win32"?"Scripts":"bin",e=process.platform==="win32"?`${t}.exe`:t;return c.join(P(),n,e)}function b(){return C("hermes")}function J(){let t=C("python3");return a.existsSync(t)?t:C("python")}function E(){return c.join(p(),"uv",process.platform==="win32"?"uv.exe":"uv")}function v(t){let n=process.platform==="win32"&&!c.extname(t)?["",".exe",".cmd",".bat"]:[""];for(let e of(process.env.PATH||"").split(c.delimiter))if(e)for(let o of n){let s=c.join(e,`${t}${o}`);try{if(a.existsSync(s))return s}catch{}}return null}function X(t){let n=/Python (\d+)\.(\d+)\.(\d+)/.exec(t||"");return n?[Number(n[1]),Number(n[2]),Number(n[3])]:null}function G(t){if(!t)return!1;let[n,e]=t;return!(n<U[0]||n===U[0]&&e<U[1]||n>L[0]||n===L[0]&&e>=L[1])}function $(){let t=[process.env.ORACLE_PYTHON,"python3.13","python3.12","python3.11","python3","python"].filter(Boolean);for(let n of t){let e=c.isAbsolute(n)?a.existsSync(n)?n:null:v(n);if(!e)continue;let o=y(e,["--version"],{encoding:"utf8",timeout:15e3}),s=X(`${o.stdout||""}${o.stderr||""}`);if(G(s))return{bin:e,version:s.join("."),source:"host"}}return null}function D(){return process.env.ORACLE_UV_BIN||v("uv")||(a.existsSync(c.join(_(),".local","bin","uv"))?c.join(_(),".local","bin","uv"):null)||(a.existsSync(E())?E():null)}function Z(t,n){let e=["const fs=require('node:fs');","const [url,dest]=process.argv.slice(1);","fetch(url).then(r=>{if(!r.ok)throw new Error('http '+r.status);return r.arrayBuffer()})",".then(b=>fs.writeFileSync(dest,Buffer.from(b)))",".catch(e=>{console.error(e.message);process.exit(1)});"].join("");return y(process.execPath,["-e",e,t,n],{encoding:"utf8",timeout:2*6e4})}function Q({quiet:t=!1}={}){let n=D();if(n)return{ok:!0,bin:n,reused:!0};R(p());let e=process.platform==="win32",o=c.join(p(),e?"uv-install.ps1":"uv-install.sh"),s=e?k.windows:k.posix,r=Z(s.url,o);if(r.status!==0)return{ok:!1,reason:`could not download the uv installer (${r.status})`,stderr:(r.stderr||"").slice(-800)};let i=a.readFileSync(o);if(!z(i,{windows:e}))return{ok:!1,reason:`uv ${A} installer checksum mismatch`};let u=c.dirname(E());R(u);let d=e?v("powershell.exe")||v("powershell"):v("sh")||"/bin/sh";if(!d)return{ok:!1,reason:e?"PowerShell not found":"sh not found"};let f=y(d,e?["-NoProfile","-ExecutionPolicy","Bypass","-File",o]:[o],{stdio:t?"pipe":"inherit",encoding:"utf8",timeout:5*6e4,env:{...process.env,UV_INSTALL_DIR:u,UV_NO_MODIFY_PATH:"1"}});return f.status!==0||!a.existsSync(E())?{ok:!1,reason:`uv install failed (${f.status})`,stderr:(f.stderr||"").slice(-800)}:{ok:!0,bin:E(),reused:!1}}function O({quiet:t=!1}={}){let n=Q({quiet:t});if(!n.ok)return n;let e=n.bin,o={...process.env,UV_PYTHON_INSTALL_DIR:c.join(p(),"python"),UV_CACHE_DIR:c.join(p(),"cache")},s=y(e,["python","install","--no-bin",g],{stdio:t?"pipe":"inherit",encoding:"utf8",timeout:15*6e4,env:o});if(s.status!==0)return{ok:!1,reason:`uv python install ${g} failed (${s.status})`,stderr:(s.stderr||"").slice(-800)};let r=y(e,["python","find",g],{encoding:"utf8",timeout:6e4,env:o}),i=(r.stdout||"").trim().split(/\r?\n/)[0];return r.status!==0||!i||!a.existsSync(i)?{ok:!1,reason:`uv could not locate python ${g}`}:{ok:!0,bin:i,version:g,source:"uv"}}function q(){if(process.env.ORACLE_HERMES_BIN)return{ok:!0,bin:process.env.ORACLE_HERMES_BIN,source:"env"};let t=b();if(a.existsSync(t))return{ok:!0,bin:t,source:"managed"};let n=v("hermes");return n?{ok:!0,bin:n,source:"path"}:{ok:!1,bin:null,source:null}}function H(){let t=q(),n=$();return{hermes:t,managedVenv:P(),managedInstalled:a.existsSync(b()),hostPython:n,uv:D()}}function w(t,n,{quiet:e}){return y(t,n,{stdio:e?"pipe":"inherit",encoding:"utf8",timeout:20*6e4})}function I({quiet:t=!1,upgrade:n=!1}={}){let e=$();if(!e){let l=O({quiet:t});if(l.ok)e={bin:l.bin,version:l.version,source:"uv"};else return{ok:!1,reason:`no supported python found (need 3.11-3.13) and uv could not provide one: ${l.reason}. install uv (https://docs.astral.sh/uv) or python 3.13, then re-run 'oracle bootstrap'`}}R(p());let o=P();if(a.existsSync(b())&&!n)return{ok:!0,bin:b(),reused:!0};if(!a.existsSync(c.join(o,"pyvenv.cfg"))){let l=w(e.bin,["-m","venv",o],{quiet:t});if(l.status!==0&&e.source!=="uv"){a.rmSync(o,{recursive:!0,force:!0});let f=O({quiet:t});if(f.ok)e={bin:f.bin,version:f.version,source:"uv"},l=w(e.bin,["-m","venv",o],{quiet:t});else return{ok:!1,reason:`python -m venv failed (${l.status}) and uv fallback failed: ${f.reason}`,stderr:(l.stderr||"").slice(-800)}}if(l.status!==0)return{ok:!1,reason:`isolated python -m venv failed (${l.status})`,stderr:(l.stderr||"").slice(-800)}}let r=J();if(!a.existsSync(r))return{ok:!1,reason:`venv python missing at ${r}`};let i=["-m","pip","install","--disable-pip-version-check"];n&&i.push("--upgrade"),i.push(j);let u=w(r,i,{quiet:t});if(u.status!==0)return{ok:!1,reason:`pip install ${j} failed (${u.status})`,stderr:(u.stderr||"").slice(-1200)};let d=b();return a.existsSync(d)?{ok:!0,bin:d,reused:!1,python:e.version}:{ok:!1,reason:`hermes entrypoint not found after install (${d})`}}function N(){return["oracle bootstrap - optional Hermes install (never required for native Oracle)",""," oracle bootstrap install into ~/.config/oracle/runtime/venv"," oracle bootstrap --upgrade upgrade the managed Hermes runtime"," oracle bootstrap --status show detected Hermes (if any)"," oracle bootstrap --json machine-readable status","","notes:"," native chat/model/auth never need this"," detection never selects Hermes; opt in with ORACLE_CHAT_BACKEND=hermes"," a hermes on PATH wins over managed install; bootstrap never touches system python"," read/prepare commands (chain, scan, route, data) never need this"].join(`
2
2
  `)}var de={name:"bootstrap",summary:"optionally install a Hermes compatibility runtime",group:"read",usage:N(),async run(t){let n=t.argv;if(n.includes("-h")||n.includes("--help"))return process.stdout.write(N()+`
3
3
  `),0;let e=n.includes("--json"),o=H();if(n.includes("--status")||e)return e?(process.stdout.write(JSON.stringify(o,null,2)+`
4
4
  `),0):(process.stdout.write([`hermes: ${o.hermes.ok?`${o.hermes.bin} (${o.hermes.source})`:"not installed"}`,`managed venv: ${o.managedVenv}`,`managed built: ${o.managedInstalled?"yes":"no"}`,`host python: ${o.hostPython?`${o.hostPython.bin} (${o.hostPython.version})`:"none supported (need 3.11-3.13)"}`,`uv: ${o.uv||"not installed (oracle will install it locally)"}`,""].join(`