@oracle-agent/oracle 0.35.31 → 0.35.34

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 (56) hide show
  1. package/README.md +19 -1
  2. package/dist/agent-lifecycle.mjs +3 -3
  3. package/dist/agent-sessions.mjs +7 -7
  4. package/dist/assets/skills/oracle-desk-product/SKILL.md +1 -1
  5. package/dist/bin/desk-server.mjs +37 -37
  6. package/dist/bin/oracle-data-mcp.mjs +17 -17
  7. package/dist/bin/oracle-gateway.mjs +16 -16
  8. package/dist/bin/oracle-investigate.mjs +11 -0
  9. package/dist/bin/oracle-launch-radar-shadow.mjs +6 -6
  10. package/dist/bin/oracle-mev-arb-shadow.mjs +6 -6
  11. package/dist/bin/oracle-mev-shadow.mjs +6 -6
  12. package/dist/bin/oracle-public-server.mjs +5 -5
  13. package/dist/bin/oracle-route.mjs +22 -22
  14. package/dist/bin/oracle-scan.mjs +15 -15
  15. package/dist/cli/commands/agent-session.mjs +7 -7
  16. package/dist/cli/commands/auth.mjs +17 -16
  17. package/dist/cli/commands/chat.mjs +208 -198
  18. package/dist/cli/commands/context.mjs +6 -6
  19. package/dist/cli/commands/doctor.mjs +9 -9
  20. package/dist/cli/commands/eval.mjs +104 -95
  21. package/dist/cli/commands/farm.mjs +22 -22
  22. package/dist/cli/commands/follow.mjs +16 -16
  23. package/dist/cli/commands/harness.mjs +1 -1
  24. package/dist/cli/commands/lifecycle.mjs +6 -6
  25. package/dist/cli/commands/model.mjs +212 -202
  26. package/dist/cli/commands/quickstart.mjs +7 -7
  27. package/dist/cli/commands/receipt.mjs +12 -12
  28. package/dist/cli/commands/resolve.mjs +12 -12
  29. package/dist/cli/commands/setup.mjs +57 -56
  30. package/dist/cli/commands/sign.mjs +15 -13
  31. package/dist/cli/commands/signer.mjs +19 -19
  32. package/dist/cli/commands/snipe.mjs +11 -11
  33. package/dist/cli/commands/strategy.mjs +5 -5
  34. package/dist/cli/commands/swap.mjs +31 -31
  35. package/dist/cli/commands/venues.mjs +2 -2
  36. package/dist/context-graph.mjs +3 -3
  37. package/dist/data/desk-data.mjs +35 -35
  38. package/dist/data/names.mjs +3 -3
  39. package/dist/data/providers/farming.mjs +2 -2
  40. package/dist/data/providers/lp-destination-discovery.mjs +4 -4
  41. package/dist/index.mjs +49 -49
  42. package/dist/investigator/index.mjs +2 -0
  43. package/dist/launch-radar/index.mjs +5 -5
  44. package/dist/local-signer/anvil-attestation-worker.mjs +1 -1
  45. package/dist/local-signer/index.mjs +3 -3
  46. package/dist/local-signer/runtime.mjs +19 -19
  47. package/dist/nft/universal-mint-router.mjs +4 -4
  48. package/dist/router/index.mjs +3 -3
  49. package/dist/router/prepare-bridge.mjs +2 -2
  50. package/dist/scanner/index.mjs +4 -4
  51. package/dist/strategy/index.mjs +3 -3
  52. package/dist/tui/standalone-client.mjs +77 -68
  53. package/package.json +3 -1
  54. package/public/eval-report.json +2 -2
  55. package/public/oracle-splash/index.html +2 -2
  56. package/server.json +2 -2
@@ -1,7 +1,7 @@
1
- var se="0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",W={1:["https://mainnet.gateway.tenderly.co","https://eth.drpc.org","https://rpc.flashbots.net"],8453:["https://base.gateway.tenderly.co","https://mainnet.base.org","https://base.drpc.org"],42161:["https://arbitrum.gateway.tenderly.co","https://arb1.arbitrum.io/rpc","https://arbitrum.drpc.org"]},Oe=1e4,He=t=>new Promise(e=>setTimeout(e,t)),ae=t=>"0x"+BigInt(t).toString(16),Me=t=>"0x"+"0".repeat(24)+t.slice(2).toLowerCase(),ce=t=>"0x"+t.slice(26).toLowerCase(),Fe=/timeout|timed out|too many requests|rate.?limit|429|502|503|504|internal error|temporarily|aborted|fetch failed|ECONNRESET|socket hang up/i,Ue=/too many|exceeds|limited to|not supported on free plan|response too large|range must not exceed|narrow your filter/i,P=class extends Error{constructor(e,{transient:r=!1,tooBig:n=!1,http:a=0}={}){super(e),this.transient=r,this.tooBig=n,this.http=a}};async function De(t,e,r,n){let a=new AbortController,i=setTimeout(()=>a.abort(),n),o,d;try{o=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:e,params:r}),signal:a.signal}),d=await o.text()}catch(f){throw new P(`${e} network: ${f.message}`,{transient:!0})}finally{clearTimeout(i)}let s;try{s=JSON.parse(d)}catch{throw new P(`${e} non-JSON http=${o.status}: ${d.slice(0,80)}`,{transient:o.status>=500||o.status===429,http:o.status})}if(s.error){let f=s.error.message||"rpc error";throw new P(`${e} rpc: ${f}`,{transient:Fe.test(f),tooBig:Ue.test(f),http:o.status})}if(o.status!==200)throw new P(`${e} http=${o.status}: ${d.slice(0,80)}`,{transient:o.status>=500||o.status===429,http:o.status});return s.result}async function ie(t,e,r,{retries:n,timeoutMs:a,onWarn:i}){let o;for(let d of t){for(let s=0;s<=n;s++)try{return{result:await De(d,e,r,a),url:d}}catch(f){if(o=f,f.tooBig)throw f;if(!f.transient||s===n)break;let h=Math.min(2e3*2**s,8e3)+Math.random()*250;i?.(`retry ${d} (${f.message.slice(0,70)}) in ${Math.round(h)}ms`),await He(h)}i?.(`endpoint exhausted: ${d} -> ${o?.message.slice(0,70)}`)}throw o??new P("no endpoints available")}async function V(t,e,r,n,a,i){let o=[{...e,fromBlock:ae(r),toBlock:ae(n)}];try{let{result:s}=await ie(t,"eth_getLogs",o,a);Array.isArray(s)&&i.push(...s);return}catch(s){if(!s.tooBig||n<=r)throw s;a.onWarn?.(`splitting ${r}-${n} (${s.message.slice(0,60)})`)}let d=r+Math.floor((n-r)/2);await Promise.all([V(t,e,r,d,a,i),V(t,e,d+1,n,a,i)])}async function le(t,e={}){if(!/^0x[0-9a-fA-F]{40}$/.test(t||""))throw new Error(`invalid address: ${t}`);let{chains:r=[1,8453,42161],lookback:n=1e5,fromBlock:a,toBlock:i,chunkSize:o=Oe,tokens:d,direction:s="both",retries:f=3,timeoutMs:h=2e4,concurrency:c=4,endpoints:u=W,onWarn:l}=e,E={retries:f,timeoutMs:h,onWarn:l},_=Me(t),b=[],R=[],C={},v=new Set;return await Promise.all(r.map(async m=>{let y=u[m];if(!y?.length){R.push({chainId:m,stage:"config",error:"no endpoints configured"});return}try{let w=i;if(w==null){let{result:g}=await ie(y,"eth_blockNumber",[],E);w=parseInt(g,16)}let p=Math.max(0,a??w-n+1),x=Math.max(p,w);C[m]={fromBlock:p,toBlock:x,blocks:x-p+1};let I=[];for(let g=p;g<=x;g+=o)I.push([g,Math.min(g+o-1,x)]);let S=[],$=d?.length?{address:d}:{};(s==="in"||s==="both")&&S.push({...$,topics:[se,null,_]}),(s==="out"||s==="both")&&S.push({...$,topics:[se,_,null]});let T=[];for(let g of S)for(let N of I)T.push([g,N]);let k=[],A=0,J=Array.from({length:Math.min(c,T.length)},async()=>{for(;A<T.length;){let[g,[N,H]]=T[A++];try{await V(y,g,N,H,E,k)}catch(Be){R.push({chainId:m,stage:"getLogs",range:[N,H],error:Be.message})}}});await Promise.all(J);for(let g of k){if(!g?.topics||g.topics.length<3)continue;let N=parseInt(g.logIndex,16),H=`${m}|${g.transactionHash}|${N}`;v.has(H)||(v.add(H),b.push({chainId:m,token:g.address.toLowerCase(),from:ce(g.topics[1]),to:ce(g.topics[2]),value:BigInt(g.data==="0x"?"0x0":g.data).toString(),blockNumber:parseInt(g.blockNumber,16),txHash:g.transactionHash,logIndex:N}))}}catch(w){R.push({chainId:m,stage:"range",error:w.message})}})),b.sort((m,y)=>y.blockNumber-m.blockNumber||y.logIndex-m.logIndex),{events:b,errors:R,ranges:C}}import{keccak_256 as te}from"@noble/hashes/sha3.js";import{createHash as fe}from"node:crypto";import L from"node:net";import je from"node:dns";var ze=new Set(["localhost","metadata.google.internal","metadata.goog"]);function j(t){let e=String(t).toLowerCase().split("%")[0];if((e.match(/::/g)||[]).length>1)return null;let r=h=>{if(!h)return[];let c=h.split(":"),u=c.at(-1);if(u?.includes(".")){let l=u.split(".").map(Number);if(l.length!==4||l.some(E=>!Number.isInteger(E)||E<0||E>255))return null;c.splice(c.length-1,1,(l[0]<<8|l[1]).toString(16),(l[2]<<8|l[3]).toString(16))}return c.some(l=>!/^[0-9a-f]{1,4}$/.test(l))?null:c.map(l=>Number.parseInt(l,16))},[n,a]=e.split("::"),i=r(n),o=r(a);if(!i||!o)return null;let d=e.includes("::"),s=8-i.length-o.length;if(!d&&s!==0||d&&s<1)return null;let f=[...i,...Array(Math.max(0,s)).fill(0),...o];return f.length!==8?null:Uint8Array.from(f.flatMap(h=>[h>>8,h&255]))}function G(t,e,r){let n=Math.floor(r/8),a=r%8;for(let o=0;o<n;o+=1)if(t[o]!==e[o])return!1;if(!a)return!0;let i=255<<8-a;return(t[n]&i)===(e[n]&i)}function Y(t){if(L.isIPv4(t)){let e=t.split(".").map(Number);return!(e[0]===0||e[0]===10||e[0]===127||e[0]>=224||e[0]===100&&e[1]>=64&&e[1]<=127||e[0]===169&&e[1]===254||e[0]===172&&e[1]>=16&&e[1]<=31||e[0]===192&&(e[1]===0||e[1]===2||e[1]===168)||e[0]===192&&e[1]===88&&e[2]===99||e[0]===198&&(e[1]===18||e[1]===19||e[1]===51)||e[0]===203&&e[1]===0&&e[2]===113)}if(L.isIPv6(t)){let e=j(t);if(!e)return!1;let r=j("::ffff:0:0");return G(e,r,96)?Y([...e.slice(12)].join(".")):G(e,j("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([a,i])=>G(e,j(a),i)):!1}return!1}function Je(t){let e;try{e=new URL(String(t))}catch{return{ok:!1,error:`not a valid URL: ${String(t).slice(0,120)}`}}if(e.protocol!=="http:"&&e.protocol!=="https:")return{ok:!1,error:`refused protocol ${e.protocol} (only http/https)`};let r=e.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"");if(ze.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let n=L.isIP(r);return n!==0&&!Y(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:e,host:r,isLiteralIp:n!==0}}async function q(t,{lookupFn:e=je.promises.lookup}={}){let r=Je(t);if(!r.ok)return r;if(r.isLiteralIp)return{ok:!0,url:r.url,addresses:[{address:r.host,family:L.isIPv6(r.host)?6:4}]};let n;try{n=await e(r.host,{all:!0,verbatim:!0})}catch{return{ok:!1,error:`refused: ${r.host} did not resolve`}}return!Array.isArray(n)||n.length===0||n.some(a=>!Y(a.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:n}}async function K({requireUndici:t=!1,importUndici:e=()=>import("undici")}={}){let r,n;try{let c=await e();r=c.Agent,n=c.fetch}catch(c){if(t)throw new Error(`egress-guard: untrustedUrl pinning requires the undici package, which failed to load: ${c?.message||c}`);return null}if(typeof r!="function"||typeof n!="function"){if(t)throw new Error("egress-guard: untrustedUrl pinning requires undici's Agent and fetch exports, which were not found on the imported module");return null}let a=c=>String(c).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),i=new Map,o=c=>(Array.isArray(c)?c:[c]).map(u=>typeof u=="string"?{address:u}:u).filter(u=>u&&u.address).map(u=>({address:u.address,family:u.family||(L.isIPv6(u.address)?6:4)})),d=(c,u,l)=>{i.set(a(c),o(typeof u=="string"?[{address:u,family:l}]:u))},s=c=>{let u=a(c);if(L.isIP(u))return[{address:u,family:L.isIPv6(u)?6:4}];let l=i.get(u);if(!l||!l.length)throw new Error(`refused: unpinned host ${c} during pinned fetch`);return l},f=new r({connect:{lookup(c,u,l){let E;try{E=s(c)}catch(_){return l(_)}return u?.all?l(null,E):l(null,E[0].address,E[0].family)}}}),h=Ve((c,u={})=>n(c,{...u,dispatcher:f}),d);return{dispatcher:f,fetch:h,pin:d,resolve:s,async close(){try{await f.destroy()}catch{}}}}var X=Symbol.for("oracle.egressGuard.pinCapableFetch");function Ve(t,e){if(typeof t!="function")throw new Error("markPinCapableFetch: fetchImpl must be a function");if(typeof e!="function")throw new Error("markPinCapableFetch: pin must be a function");return t[X]=Object.freeze({pin:e}),t}function Z(t){return typeof t=="function"&&typeof t[X]?.pin=="function"}function ue(t,e,r){if(!Z(t))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");t[X].pin(e,r)}var We=new Set([408,425,429,500,502,503,504]),de=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),Ge=2,he=4e3,be=["authorization","x-api-key","x-tensor-api-key","0x-api-key","api-key","cookie","proxy-authorization"],Ye=new Set([301,302,303,307,308]),pe=3,qe=64*1024;function Ke(t){let e=String(t||"").toLowerCase();return be.includes(e)||/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(e)}function Xe(t){let e={};for(let[r,n]of Object.entries(t||{}))Ke(r)||(e[r]=n);return e}function Ze(t,e){if(!t)throw new Error(`HTTP redirect from ${e} missing Location`);let r=new URL(String(t),String(e));if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error(`HTTP redirect from ${e} used unsupported protocol ${r.protocol}`);return r.toString()}function Qe(t,e){return new URL(String(t)).origin===new URL(String(e)).origin}var Q=new Map,et=/(?:^|_)(send|submit|broadcast|sign|requestAirdrop)(?=[A-Z_]|$)/i,tt=new Set(["allMids","l2Book","outcomeMeta","spotClearinghouseState","userFills","meta","metaAndAssetCtxs","perpDexs","candleSnapshot","fundingHistory","openOrders","frontendOpenOrders","clearinghouseState","spotMeta","validatorSummaries","delegatorSummary","delegations","delegatorRewards","delegatorHistory","maxBuilderFee"]);function me(t){let e=String(t?.method||"");return e?!et.test(e):!1}function rt(t,e){if(t==="GET"&&e==null)return!0;if(t!=="POST"||e==null)return!1;let r=e;if(typeof e=="string")try{r=JSON.parse(e)}catch{return!1}return Array.isArray(r)?r.length>0&&r.every(me):!r||typeof r!="object"?!1:r.jsonrpc&&r.method?me(r):typeof r.type=="string"&&tt.has(r.type)&&r.action==null&&r.signature==null&&r.nonce==null}function nt(t,e,r,n={},a=null){let i={};for(let[u,l]of Object.entries(r||{}))i[u.toLowerCase()]=l;let o=Object.keys(i).filter(u=>/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(u)),s=[...new Set([...be,...o])].sort().map(u=>`${u}=${i[u]??""}`).join(`
2
- `),f=fe("sha256").update(s).digest("hex").slice(0,32),h=`${n.untrustedUrl?"untrusted":"trusted"}:${n.maxResponseBytes??"unbounded"}`,c=a==null?"-":fe("sha256").update(String(a)).digest("hex").slice(0,32);return`${t} ${e} ${h} ${f} ${c}`}function ot(t,e){let r=Number(e);return Number.isFinite(r)&&r>0?Math.min(r*1e3,he):Math.min(250*2**t,he)+Math.floor(Math.random()*100)}var st=t=>new Promise(e=>setTimeout(e,t));function M(t,e={}){let r=new Error(t);return r.retryable=!1,Object.assign(r,e),r}function ee(t,e,r){return M(`HTTP response from ${t} exceeded maxResponseBytes ${r} (${e})`,{oversize:!0})}function F(t){try{let e=t?.body?.cancel?.();e&&typeof e.then=="function"&&e.catch(()=>{})}catch{}}function at(t){return t?t.byteLength??t.length??0:0}async function we(t,e,{url:r,truncate:n=!1,onOversize:a}={}){if(e==null)return await t.text();let i=Number(t.headers?.get?.("content-length"));if(Number.isFinite(i)&&i>e&&(F(t),!n))throw ee(r,`content-length ${i}`,e);let o=t.body?.getReader?.();if(!o){let c=await t.text(),u=Buffer.byteLength(c,"utf8");if(u>e){if(!n)throw ee(r,`body ${u} bytes`,e);return Buffer.from(c,"utf8").subarray(0,e).toString("utf8")}return c}let d=[],s=0,f=!1;try{for(;;){let{value:c,done:u}=await o.read();if(u)break;if(c&&(d.push(Buffer.from(c)),s+=at(c),s>e)){f=!0;break}}}finally{if(f)try{await o.cancel()}catch{}try{o.releaseLock?.()}catch{}}if(f&&(typeof a=="function"&&a(),!n))throw ee(r,`streamed ${s} bytes`,e);let h=Buffer.concat(d);return(f?h.subarray(0,e):h).toString("utf8")}function ge(t){if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function ct(t,{fetchImpl:e,method:r,headers:n,body:a,timeoutMs:i,lookupFn:o,realFetch:d,untrustedUrl:s=!1,maxResponseBytes:f=null,importUndici:h,validateResponse:c,signal:u}){let l=new AbortController,E=setTimeout(()=>l.abort(),i),_=u?typeof AbortSignal.any=="function"?AbortSignal.any([u,l.signal]):u:l.signal,b=null,R=e,C=o?{lookupFn:o}:{};if(s&&!d&&!Z(R))throw M(`HTTP refused ${t}: untrustedUrl requires a pin-capable fetchImpl (see markPinCapableFetch in egress-guard.mjs) or no fetchImpl override so Oracle can pin the connection itself`);let v=async(m,{status:y=null}={})=>{let w=await q(m,C);if(!w.ok)throw M(y==null?`HTTP refused ${m}: ${w.error}`:`HTTP redirect to ${m} ${w.error}`,y==null?{}:{status:y});let p=new URL(m).hostname;if(d){if(b&&(await b.close(),b=null),!b)try{b=await K({requireUndici:!0,...h?{importUndici:h}:{}})}catch(x){throw M(y==null?`HTTP refused ${m}: ${x?.message||x}`:`HTTP redirect to ${m} refused: ${x?.message||x}`,y==null?{}:{status:y})}b.pin(p,w.addresses),R=b.fetch}else ue(R,p,w.addresses);return w};try{let m=String(t),y={...n||{}};s&&await v(m);for(let w=0;w<=pe;w+=1){let p=await R(m,{method:r,headers:y,body:a,signal:_,redirect:"manual"});if(Ye.has(p.status)){if(r!=="GET"&&r!=="HEAD"){let k=await we(p,f??qe,{url:m,truncate:!0}),A=new Error(`HTTP ${p.status} ${r} ${m} redirected non-idempotent request`);throw A.status=p.status,A.body=ge(k)??k.slice(0,300),A}if(w===pe)throw F(p),new Error(`HTTP redirect loop for ${t}`);let S=p.headers?.get?.("location"),$;try{$=Ze(S,m)}catch(k){throw F(p),k}let T=!Qe($,m);if(F(p),T&&(y=Xe(y)),s)await v($,{status:p.status});else if(T){let k=await q($,C);if(!k.ok){let A=new Error(`HTTP redirect from ${m} ${k.error}`);throw A.status=p.status,A.retryable=!1,A}d&&k.addresses?.length&&(b||(b=await K(h?{importUndici:h}:{})),b&&(b.pin(new URL($).hostname,k.addresses),R=b.fetch))}m=$;continue}if(typeof c=="function")try{await c(p,{url:m})}catch(S){throw F(p),M(S?.message||String(S))}let x=await we(p,f,{url:m,onOversize:()=>l.abort()}),I=ge(x);if(!p.ok){let S=new Error(`HTTP ${p.status} ${r} ${m}`);throw S.status=p.status,S.retryAfter=p.headers?.get?.("retry-after")??null,S.body=I??x.slice(0,300),S}return I??x}throw new Error(`HTTP redirect loop for ${t}`)}finally{clearTimeout(E),b&&await b.close()}}async function ye(t,e={}){let r=e.fetchImpl||globalThis.fetch;if(typeof r!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let n=e.timeoutMs??12e3,a=(e.method||"GET").toUpperCase(),i={Accept:"application/json",...e.headers||{}},o=e.body;o!=null&&typeof o!="string"&&(i["Content-Type"]=i["Content-Type"]||"application/json",o=JSON.stringify(o));let d=Number.isInteger(e.retries)?Math.max(e.retries,0):Ge,s=e.lookupFn,f=!e.fetchImpl,h=e.untrustedUrl===!0,c=e.importUndici,u=e.validateResponse,l=e.signal,E=Number(e.maxResponseBytes),_=Number.isFinite(E)&&E>0?Math.floor(E):null,b=async()=>{let y;for(let w=0;w<=d;w++){l?.throwIfAborted?.();try{return await ct(t,{fetchImpl:r,method:a,headers:i,body:o,timeoutMs:n,lookupFn:s,realFetch:f,untrustedUrl:h,maxResponseBytes:_,importUndici:c,validateResponse:u,signal:l})}catch(p){y=p;let x=p?.status,I=p?.name==="AbortError"||p?.name==="TimeoutError"||l?.aborted,S=new Set([408,425,429]),$=p?.retryable===!1?!1:x!=null?S.has(x)||We.has(x)&&de.has(a):!I&&de.has(a);if(w===d||!$)throw p;let T=ot(w,p?.retryAfter);l?await new Promise((k,A)=>{let J=setTimeout(k,T);l.addEventListener("abort",()=>{clearTimeout(J),A(l.reason||new DOMException("Aborted","AbortError"))},{once:!0})}):await st(T)}}throw y};if(!(e.dedupe!==!1&&!l&&rt(a,o)))return b();let C=nt(a,t,i,{untrustedUrl:h,maxResponseBytes:_},o),v=Q.get(C);if(v)return v;let m=b().finally(()=>Q.delete(C));return Q.set(C,m),m}var Ee={robinhood:{chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC"],evm:!0},ethereum:{chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],evm:!0},polygon:{chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],evm:!0},arbitrum:{chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],evm:!0},base:{chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],evm:!0},hyperevm:{chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],evm:!0},bsc:{chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],evm:!0},avalanche:{chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],evm:!0},optimism:{chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],evm:!0},abstract:{chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],evm:!0},stable:{chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],evm:!0}},it=new Map(Object.values(Ee).map(t=>[t.chainId,t]));function xe(t){return it.get(Number(t))||null}function Se(t,e=process.env){let r=xe(t);if(!r)return null;for(let n of r.rpcEnv){let a=(e[n]||"").trim();if(a)return a}return null}import{Interface as lt,getAddress as Jt}from"ethers";var Vt=new lt(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);var ut={1:"https://ethereum.publicnode.com",137:"https://polygon-bor-rpc.publicnode.com",42161:"https://arbitrum-one-rpc.publicnode.com",8453:"https://base-rpc.publicnode.com",10:"https://optimism-rpc.publicnode.com",988:"https://rpc.stable.xyz",56:"https://bsc-rpc.publicnode.com",43114:"https://avalanche-c-chain-rpc.publicnode.com",999:"https://rpc.hyperliquid.xyz/evm",2741:"https://api.mainnet.abs.xyz",4663:"https://rpc.mainnet.chain.robinhood.com"};function ft(t,{rpcUrl:e,env:r=process.env}={}){if(e)return e;let n=Se(t,r);return n||ut[Number(t)]||null}var dt=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function ht(t){let e=String(t||""),r=e.toLowerCase();if(e!==e.trim()||!/^[a-zA-Z0-9_]+$/.test(e)||!dt.test(r))throw new Error(`evm-rpc: ${e} refused \u2014 @oracle-agent/oracle is prepare-only (read RPC only; no broadcast/sign)`);return r}var U=new Map,ke=new Map;function pt(t){let e=new Error(t?.message||JSON.stringify(t));return e.code=t?.code,e}function mt(t){if(t?.error)throw pt(t.error);return t?.result}function wt(t,e,r){return`${t}
1
+ var ge="0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",oe={1:["https://mainnet.gateway.tenderly.co","https://eth.drpc.org","https://rpc.flashbots.net"],8453:["https://base.gateway.tenderly.co","https://mainnet.base.org","https://base.drpc.org"],42161:["https://arbitrum.gateway.tenderly.co","https://arb1.arbitrum.io/rpc","https://arbitrum.drpc.org"]},Xe=1e4,Qe=t=>new Promise(e=>setTimeout(e,t)),Te=t=>"0x"+BigInt(t).toString(16),et=t=>"0x"+"0".repeat(24)+t.slice(2).toLowerCase(),Ee=t=>"0x"+t.slice(26).toLowerCase(),tt=/timeout|timed out|too many requests|rate.?limit|429|502|503|504|internal error|temporarily|aborted|fetch failed|ECONNRESET|socket hang up/i,rt=/too many|exceeds|limited to|not supported on free plan|response too large|range must not exceed|narrow your filter/i,D=class extends Error{constructor(e,{transient:r=!1,tooBig:n=!1,http:i=0}={}){super(e),this.transient=r,this.tooBig=n,this.http=i}};async function nt(t,e,r,n){let i=new AbortController,l=setTimeout(()=>i.abort(),n),s,f;try{s=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:e,params:r}),signal:i.signal}),f=await s.text()}catch(u){throw new D(`${e} network: ${u.message}`,{transient:!0})}finally{clearTimeout(l)}let o;try{o=JSON.parse(f)}catch{throw new D(`${e} non-JSON http=${s.status}: ${f.slice(0,80)}`,{transient:s.status>=500||s.status===429,http:s.status})}if(o.error){let u=o.error.message||"rpc error";throw new D(`${e} rpc: ${u}`,{transient:tt.test(u),tooBig:rt.test(u),http:s.status})}if(s.status!==200)throw new D(`${e} http=${s.status}: ${f.slice(0,80)}`,{transient:s.status>=500||s.status===429,http:s.status});return o.result}async function Oe(t,e,r,{retries:n,timeoutMs:i,onWarn:l}){let s;for(let f of t){for(let o=0;o<=n;o++)try{return{result:await nt(f,e,r,i),url:f}}catch(u){if(s=u,u.tooBig)throw u;if(!u.transient||o===n)break;let a=Math.min(2e3*2**o,8e3)+Math.random()*250;l?.(`retry ${f} (${u.message.slice(0,70)}) in ${Math.round(a)}ms`),await Qe(a)}l?.(`endpoint exhausted: ${f} -> ${s?.message.slice(0,70)}`)}throw s??new D("no endpoints available")}async function ne(t,e,r,n,i,l){let s=[{...e,fromBlock:Te(r),toBlock:Te(n)}];try{let{result:o}=await Oe(t,"eth_getLogs",s,i);Array.isArray(o)&&l.push(...o);return}catch(o){if(!o.tooBig||n<=r)throw o;i.onWarn?.(`splitting ${r}-${n} (${o.message.slice(0,60)})`)}let f=r+Math.floor((n-r)/2);await Promise.all([ne(t,e,r,f,i,l),ne(t,e,f+1,n,i,l)])}async function Se(t,e={}){if(!/^0x[0-9a-fA-F]{40}$/.test(t||""))throw new Error(`invalid address: ${t}`);let{chains:r=[1,8453,42161],lookback:n=1e5,fromBlock:i,toBlock:l,chunkSize:s=Xe,tokens:f,direction:o="both",retries:u=3,timeoutMs:a=2e4,concurrency:c=4,endpoints:p=oe,onWarn:d}=e,m={retries:u,timeoutMs:a,onWarn:d},A=et(t),R=[],k=[],j={},g=new Set;return await Promise.all(r.map(async T=>{let N=p[T];if(!N?.length){k.push({chainId:T,stage:"config",error:"no endpoints configured"});return}try{let I=l;if(I==null){let{result:w}=await Oe(N,"eth_blockNumber",[],m);I=parseInt(w,16)}let y=Math.max(0,i??I-n+1),O=Math.max(y,I);j[T]={fromBlock:y,toBlock:O,blocks:O-y+1};let P=[];for(let w=y;w<=O;w+=s)P.push([w,Math.min(w+s-1,O)]);let C=[],h=f?.length?{address:f}:{};(o==="in"||o==="both")&&C.push({...h,topics:[ge,null,A]}),(o==="out"||o==="both")&&C.push({...h,topics:[ge,A,null]});let _=[];for(let w of C)for(let $ of P)_.push([w,$]);let B=[],v=0,K=Array.from({length:Math.min(c,_.length)},async()=>{for(;v<_.length;){let[w,[$,b]]=_[v++];try{await ne(N,w,$,b,m,B)}catch(E){k.push({chainId:T,stage:"getLogs",range:[$,b],error:E.message})}}});await Promise.all(K);for(let w of B){if(!w?.topics||w.topics.length<3)continue;let $=parseInt(w.logIndex,16),b=`${T}|${w.transactionHash}|${$}`;g.has(b)||(g.add(b),R.push({chainId:T,token:w.address.toLowerCase(),from:Ee(w.topics[1]),to:Ee(w.topics[2]),value:BigInt(w.data==="0x"?"0x0":w.data).toString(),blockNumber:parseInt(w.blockNumber,16),txHash:w.transactionHash,logIndex:$}))}}catch(I){k.push({chainId:T,stage:"range",error:I.message})}})),R.sort((T,N)=>N.blockNumber-T.blockNumber||N.logIndex-T.logIndex),{events:R,errors:k,ranges:j}}import{keccak_256 as he}from"@noble/hashes/sha3.js";import{createHash as ct}from"node:crypto";import{types as L}from"node:util";import F from"node:net";import ot from"node:dns";var st=new Set(["localhost","metadata.google.internal","metadata.goog"]);function Z(t){let e=String(t).toLowerCase().split("%")[0];if((e.match(/::/g)||[]).length>1)return null;let r=a=>{if(!a)return[];let c=a.split(":"),p=c.at(-1);if(p?.includes(".")){let d=p.split(".").map(Number);if(d.length!==4||d.some(m=>!Number.isInteger(m)||m<0||m>255))return null;c.splice(c.length-1,1,(d[0]<<8|d[1]).toString(16),(d[2]<<8|d[3]).toString(16))}return c.some(d=>!/^[0-9a-f]{1,4}$/.test(d))?null:c.map(d=>Number.parseInt(d,16))},[n,i]=e.split("::"),l=r(n),s=r(i);if(!l||!s)return null;let f=e.includes("::"),o=8-l.length-s.length;if(!f&&o!==0||f&&o<1)return null;let u=[...l,...Array(Math.max(0,o)).fill(0),...s];return u.length!==8?null:Uint8Array.from(u.flatMap(a=>[a>>8,a&255]))}function se(t,e,r){let n=Math.floor(r/8),i=r%8;for(let s=0;s<n;s+=1)if(t[s]!==e[s])return!1;if(!i)return!0;let l=255<<8-i;return(t[n]&l)===(e[n]&l)}function ae(t){if(F.isIPv4(t)){let e=t.split(".").map(Number);return!(e[0]===0||e[0]===10||e[0]===127||e[0]>=224||e[0]===100&&e[1]>=64&&e[1]<=127||e[0]===169&&e[1]===254||e[0]===172&&e[1]>=16&&e[1]<=31||e[0]===192&&(e[1]===0||e[1]===2||e[1]===168)||e[0]===192&&e[1]===88&&e[2]===99||e[0]===198&&(e[1]===18||e[1]===19||e[1]===51)||e[0]===203&&e[1]===0&&e[2]===113)}if(F.isIPv6(t)){let e=Z(t);if(!e)return!1;let r=Z("::ffff:0:0");return se(e,r,96)?ae([...e.slice(12)].join(".")):se(e,Z("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([i,l])=>se(e,Z(i),l)):!1}return!1}function at(t){let e;try{e=new URL(String(t))}catch{return{ok:!1,error:`not a valid URL: ${String(t).slice(0,120)}`}}if(e.protocol!=="http:"&&e.protocol!=="https:")return{ok:!1,error:`refused protocol ${e.protocol} (only http/https)`};let r=e.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"");if(st.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let n=F.isIP(r);return n!==0&&!ae(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:e,host:r,isLiteralIp:n!==0}}async function ie(t,{lookupFn:e=ot.promises.lookup}={}){let r=at(t);if(!r.ok)return r;if(r.isLiteralIp)return{ok:!0,url:r.url,addresses:[{address:r.host,family:F.isIPv6(r.host)?6:4}]};let n;try{n=await e(r.host,{all:!0,verbatim:!0})}catch{return{ok:!1,error:`refused: ${r.host} did not resolve`}}return!Array.isArray(n)||n.length===0||n.some(i=>!ae(i.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:n}}async function ce({requireUndici:t=!1,importUndici:e=()=>import("undici")}={}){let r,n;try{let c=await e();r=c.Agent,n=c.fetch}catch(c){if(t)throw new Error(`egress-guard: untrustedUrl pinning requires the undici package, which failed to load: ${c?.message||c}`);return null}if(typeof r!="function"||typeof n!="function"){if(t)throw new Error("egress-guard: untrustedUrl pinning requires undici's Agent and fetch exports, which were not found on the imported module");return null}let i=c=>String(c).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),l=new Map,s=c=>(Array.isArray(c)?c:[c]).map(p=>typeof p=="string"?{address:p}:p).filter(p=>p&&p.address).map(p=>({address:p.address,family:p.family||(F.isIPv6(p.address)?6:4)})),f=(c,p,d)=>{l.set(i(c),s(typeof p=="string"?[{address:p,family:d}]:p))},o=c=>{let p=i(c);if(F.isIP(p))return[{address:p,family:F.isIPv6(p)?6:4}];let d=l.get(p);if(!d||!d.length)throw new Error(`refused: unpinned host ${c} during pinned fetch`);return d},u=new r({connect:{lookup(c,p,d){let m;try{m=o(c)}catch(A){return d(A)}return p?.all?d(null,m):d(null,m[0].address,m[0].family)}}}),a=it((c,p={})=>n(c,{...p,dispatcher:u}),f);return{dispatcher:u,fetch:a,pin:f,resolve:o,async close(){try{await u.destroy()}catch{}}}}var le=Symbol.for("oracle.egressGuard.pinCapableFetch");function it(t,e){if(typeof t!="function")throw new Error("markPinCapableFetch: fetchImpl must be a function");if(typeof e!="function")throw new Error("markPinCapableFetch: pin must be a function");return t[le]=Object.freeze({pin:e}),t}function ue(t){return typeof t=="function"&&typeof t[le]?.pin=="function"}function xe(t,e,r){if(!ue(t))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");t[le].pin(e,r)}var lt=new Set([408,425,429,500,502,503,504]),Pe=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),ut=2,Ae=4e3,ft=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"aborted")?.get,dt=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"reason")?.get,pt=AbortSignal.prototype.throwIfAborted,ht=EventTarget.prototype.addEventListener,Re=typeof AbortSignal.any=="function"?AbortSignal.any.bind(AbortSignal):null,pe=t=>t?ft.call(t):!1,mt=t=>t?dt.call(t):void 0,wt=new Set([301,302,303,307,308]),Q=3,lr=64*1024,H=Object.freeze({depth:32,nodes:1e4,fields:1e4,arrayLength:1e4,bytes:1024*1024});function x(t){return M(`HTTP JSON body refused: ${t}`)}function yt(t){return["isArgumentsObject","isArrayBuffer","isAnyArrayBuffer","isArrayBufferView","isBoxedPrimitive","isDataView","isDate","isExternal","isGeneratorObject","isKeyObject","isCryptoKey","isMap","isMapIterator","isModuleNamespaceObject","isNativeError","isPromise","isRegExp","isSet","isSetIterator","isTypedArray","isWeakMap","isWeakSet"].some(e=>typeof L[e]=="function"&&L[e](t))}function bt(t){let e=[],r=0,n=0,i=0,l=0,s=new WeakSet,f=a=>{if(r+=Buffer.byteLength(a,"utf8"),r>H.bytes)throw x("serialized byte limit exceeded");e.push(a)},o=a=>{if(Buffer.byteLength(a,"utf8")>H.bytes)throw x("serialized byte limit exceeded");return JSON.stringify(a)},u=(a,c)=>{if(n+=1,n>H.nodes)throw x("node limit exceeded");if(c>H.depth)throw x("depth limit exceeded");if(a===null){f("null");return}if(typeof a=="string"){f(o(a));return}if(typeof a=="boolean"){f(a?"true":"false");return}if(typeof a=="number"){if(!Number.isFinite(a))throw x("non-finite number");f(Object.is(a,-0)?"0":String(a));return}if(typeof a!="object")throw x("unsupported non-JSON value");if(L.isProxy(a))throw x("proxy value");if(yt(a))throw x("unsupported exotic object");if(s.has(a))throw x("cyclic value");s.add(a);try{if(Object.getOwnPropertySymbols(a).length>0)throw x("symbol-keyed fields are unsupported");if(Array.isArray(a)){let m=Object.getPrototypeOf(a),A=0;for(;m!==null;){if(L.isProxy(m))throw x("proxy array prototype");if(A+=1,A>H.depth)throw x("array prototype depth limit exceeded");m=Object.getPrototypeOf(m)}if(a.length>H.arrayLength)throw x("array length limit exceeded");for(let k=0;k<a.length;k+=1){let j=Object.getOwnPropertyDescriptor(a,String(k));if(!j||!Object.hasOwn(j,"value")||j.enumerable!==!0)throw x("array entries must be dense enumerable own data")}let R=0;for(let k in a){if(l+=1,l>H.fields)throw x("enumeration limit exceeded");if(Object.hasOwn(a,k)&&(R+=1,R>a.length))throw x("named array fields are unsupported")}if(R!==a.length)throw x("array entries must be dense enumerable own data");f("[");for(let k=0;k<a.length;k+=1)k&&f(","),u(Object.getOwnPropertyDescriptor(a,String(k)).value,c+1);f("]");return}let p=Object.getPrototypeOf(a);if(p!==Object.prototype&&p!==null)throw x("non-plain object");let d=[];for(let m in a){if(l+=1,l>H.fields)throw x("enumeration limit exceeded");if(!Object.hasOwn(a,m))continue;if(i+=1,i>H.fields)throw x("field limit exceeded");let A=Object.getOwnPropertyDescriptor(a,m);if(!A||!Object.hasOwn(A,"value")||A.enumerable!==!0)throw x("object fields must be enumerable own data");d.push([m,A.value])}f("{");for(let m=0;m<d.length;m+=1)m&&f(","),f(o(d[m][0])),f(":"),u(d[m][1],c+1);f("}")}finally{s.delete(a)}};return u(t,0),e.join("")}function gt(t){let e=Object.create(null);if(t==null)return e;if(typeof t!="object"&&typeof t!="function")throw new TypeError("HTTP headers must be an object");if(L.isProxy(t))throw new TypeError("HTTP headers must not be a proxy");if(Object.getOwnPropertySymbols(t).length>0)throw new TypeError("HTTP headers must not contain symbol fields");let r=new Set;for(let n of Object.keys(t)){if(!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u.test(n))throw new TypeError("HTTP header names must be valid tokens");let i=n.toLowerCase();if(r.has(i))throw new TypeError("HTTP headers contain a duplicate canonical name");r.add(i);let l=Object.getOwnPropertyDescriptor(t,n);if(!l||!Object.hasOwn(l,"value"))throw new TypeError("HTTP headers must contain own data properties");let s=l.value;if(s==null||["object","function","symbol"].includes(typeof s))throw new TypeError("HTTP header values must be scalar");e[n]=String(s)}return e}function Tt(){return Object.assign(Object.create(null),{Accept:"application/json"})}function Et(t,e){if(!t)throw new Error(`HTTP redirect from ${e} missing Location`);let r=new URL(String(t),String(e));if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error(`HTTP redirect from ${e} used unsupported protocol ${r.protocol}`);return r.toString()}function Ot(t,e){return new URL(String(t)).origin===new URL(String(e)).origin}var fe=new Map,ke=new WeakMap,_e=1;function X(t){if((typeof t!="object"||t===null)&&typeof t!="function")return`${typeof t}:${String(t)}`;let e=ke.get(t);return e||(e=_e,_e+=1,ke.set(t,e)),`reference:${e}`}var St=new Set(["eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","getHealth","minimumLedgerSlot","net_version","simulateTransaction","web3_clientVersion"]),xt=new Set(["allMids","l2Book","outcomeMeta","spotClearinghouseState","userFills","meta","metaAndAssetCtxs","perpDexs","candleSnapshot","fundingHistory","openOrders","frontendOpenOrders","clearinghouseState","spotMeta","validatorSummaries","delegatorSummary","delegations","delegatorRewards","delegatorHistory","maxBuilderFee"]);function ve(t){if(!t||typeof t!="object"||Array.isArray(t)||!Object.hasOwn(t,"jsonrpc")||!Object.hasOwn(t,"method")||t.jsonrpc!=="2.0")return!1;let e=typeof t.method=="string"?t.method:"";return e?St.has(e)||/^get[A-Z0-9_]/u.test(e)||/^is[A-Z0-9_]/u.test(e)||/^eth_get[A-Z0-9_]/u.test(e):!1}function $e(t,e){if(t==="GET"&&e==null)return!0;if(t!=="POST"||e==null)return!1;let r=e;if(typeof e=="string")try{r=JSON.parse(e)}catch{return!1}if(Array.isArray(r))return r.length>0&&r.every(ve);if(!r||typeof r!="object")return!1;if(Object.hasOwn(r,"jsonrpc")||Object.hasOwn(r,"method"))return ve(r);let n=Object.hasOwn(r,"type")?r.type:null;return typeof n=="string"&&xt.has(n)&&(!Object.hasOwn(r,"action")||r.action==null)&&(!Object.hasOwn(r,"signature")||r.signature==null)&&(!Object.hasOwn(r,"nonce")||r.nonce==null)}function Pt(t,e,r,n={},i=null){let l=ct("sha256"),s=(o,u)=>{let a=String(u);l.update(String(Buffer.byteLength(o,"utf8"))).update(":").update(o),l.update("=").update(String(Buffer.byteLength(a,"utf8"))).update(":").update(a).update(`
2
+ `)};s("method",t),s("url",e),Object.keys(r||{}).map((o,u)=>({name:o.toLowerCase(),order:u,value:String(r[o])})).sort((o,u)=>o.name.localeCompare(u.name)||o.order-u.order).forEach((o,u)=>{s(`header-name-${u}`,o.name),s(`header-value-${u}`,o.value)}),s("body",i??"-");for(let o of["untrustedUrl","maxResponseBytes","sameOriginRedirectsOnly","redirectPolicy","maxRedirects","timeoutMs","retries","fetchImpl","realFetch","lookupFn","importUndici","validateResponse"])s(`context-${o}`,n[o]??"-");return l.digest("hex")}function At(t,e){let r=Number(e);return Number.isFinite(r)&&r>0?Math.min(r*1e3,Ae):Math.min(250*2**t,Ae)+Math.floor(Math.random()*100)}var Rt=t=>new Promise(e=>setTimeout(e,t));function M(t,e={}){let r=new Error(t);return r.retryable=!1,Object.assign(r,e),r}function de(t,e,r){return M(`HTTP response from ${t} exceeded maxResponseBytes ${r} (${e})`,{oversize:!0})}function z(t){try{let e=t?.body?.cancel?.();e&&typeof e.then=="function"&&e.catch(()=>{})}catch{}}function kt(t){return t?t.byteLength??t.length??0:0}async function _t(t,e,{url:r,truncate:n=!1,onOversize:i}={}){if(e==null)return await t.text();let l=Number(t.headers?.get?.("content-length"));if(Number.isFinite(l)&&l>e&&(z(t),!n))throw de(r,`content-length ${l}`,e);let s=t.body?.getReader?.();if(!s){let c=await t.text(),p=Buffer.byteLength(c,"utf8");if(p>e){if(!n)throw de(r,`body ${p} bytes`,e);return Buffer.from(c,"utf8").subarray(0,e).toString("utf8")}return c}let f=[],o=0,u=!1;try{for(;;){let{value:c,done:p}=await s.read();if(p)break;if(c&&(f.push(Buffer.from(c)),o+=kt(c),o>e)){u=!0;break}}}finally{if(u)try{await s.cancel()}catch{}try{s.releaseLock?.()}catch{}}if(u&&(typeof i=="function"&&i(),!n))throw de(r,`streamed ${o} bytes`,e);let a=Buffer.concat(f);return(u?a.subarray(0,e):a).toString("utf8")}function vt(t){if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function $t(t,{fetchImpl:e,method:r,headers:n,body:i,timeoutMs:l,lookupFn:s,realFetch:f,untrustedUrl:o=!1,maxResponseBytes:u=null,sameOriginRedirectsOnly:a=!1,importUndici:c,validateResponse:p,signal:d,redirectPolicy:m="follow",maxRedirects:A=Q}){let R=new AbortController,k=setTimeout(()=>R.abort(),l),j=d?Re?Re([d,R.signal]):d:R.signal,g=null,T=e,N=s?{lookupFn:s}:{};if(o&&!f&&!ue(T))throw M(`HTTP refused ${t}: untrustedUrl requires a pin-capable fetchImpl (see markPinCapableFetch in egress-guard.mjs) or no fetchImpl override so Oracle can pin the connection itself`);let I=async(y,{status:O=null}={})=>{let P=await ie(y,N);if(!P.ok)throw M(O==null?`HTTP refused ${y}: ${P.error}`:`HTTP redirect to ${y} ${P.error}`,O==null?{}:{status:O});let C=new URL(y).hostname;if(f){if(g&&(await g.close(),g=null),!g)try{g=await ce({requireUndici:!0,...c?{importUndici:c}:{}})}catch(h){throw M(O==null?`HTTP refused ${y}: ${h?.message||h}`:`HTTP redirect to ${y} refused: ${h?.message||h}`,O==null?{}:{status:O})}g.pin(C,P.addresses),T=g.fetch}else xe(T,C,P.addresses);return P};try{let y=String(t),O=Object.assign(Object.create(null),n||{});o&&await I(y);for(let P=0;P<=A;P+=1){let C=Object.assign(Object.create(null),{method:r,headers:O,body:i,signal:j,redirect:"manual",dispatcher:void 0}),h=await T(y,C);if((m==="error"||A===0)&&h.status>=300&&h.status<400)throw z(h),M(`HTTP ${h.status} ${r} redirect refused`,{status:h.status,redirectRefused:!0});if(wt.has(h.status)){let v=a===!0&&r==="POST"&&[307,308].includes(h.status)&&$e(r,i);if(r!=="GET"&&r!=="HEAD"&&!v){z(h);let b=new Error(`HTTP ${h.status} ${r} ${y} redirected non-idempotent request`);throw b.status=h.status,b}if(P===A)throw z(h),M(`HTTP ${h.status} ${r} redirect budget exhausted`,{status:h.status,redirectRefused:!0});let K=h.headers?.get?.("location"),w;try{w=Et(K,y)}catch(b){throw z(h),b}let $=!Ot(w,y);if(z(h),$&&r==="POST"){let b=new Error(`HTTP ${h.status} ${r} cross-origin redirect refused`);throw b.status=h.status,b}if($&&a){let b=new Error(`HTTP ${h.status} ${r} cross-origin redirect refused`);throw b.status=h.status,b.retryable=!1,b}if($&&(O=Tt(O)),o)await I(w,{status:h.status});else if($){let b=await ie(w,N);if(!b.ok){let E=new Error(`HTTP redirect from ${y} ${b.error}`);throw E.status=h.status,E.retryable=!1,E}f&&b.addresses?.length&&(g||(g=await ce(c?{importUndici:c}:{})),g&&(g.pin(new URL(w).hostname,b.addresses),T=g.fetch))}y=w;continue}if(typeof p=="function")try{await p(h,{url:y})}catch(v){throw z(h),M(v?.message||String(v))}let _=await _t(h,u,{url:y,onOversize:()=>R.abort()}),B=vt(_);if(!h.ok){let v=new Error(`HTTP ${h.status} ${r} ${y}`);throw v.status=h.status,v.retryAfter=h.headers?.get?.("retry-after")??null,v.body=B??_.slice(0,300),v}return B??_}throw new Error(`HTTP redirect loop for ${t}`)}catch(y){if(R.signal.aborted&&!pe(d)){let O=y&&(typeof y=="object"||typeof y=="function")&&!L.isProxy(y)?y:null,P=O?Object.getOwnPropertyDescriptor(O,"oversize"):null;if(!(P&&Object.hasOwn(P,"value")&&P.value===!0))try{if(!O)throw new TypeError("unsafe rejection");Object.defineProperties(O,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}})}catch{let h=new Error("HTTP request timed out");throw Object.defineProperties(h,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}}),h}}throw y}finally{clearTimeout(k),g&&await g.close()}}async function Ne(t,e={}){if(e!=null&&typeof e!="object"&&typeof e!="function")throw new TypeError("HTTP options must be an object");if(e!=null&&L.isProxy(e))throw new TypeError("HTTP options must not be a proxy");let r=new Set(["body","dedupe","fetchImpl","headers","importUndici","lookupFn","maxRedirects","maxResponseBytes","method","redirectPolicy","retries","sameOriginRedirectsOnly","signal","timeoutMs","untrustedUrl","validateResponse"]);if(e!=null){if(Object.getOwnPropertySymbols(e).length>0)throw new TypeError("HTTP options contain unknown fields");for(let E of Object.getOwnPropertyNames(e)){let S=Object.getOwnPropertyDescriptor(e,E);if(!(E==="toJSON"&&S&&Object.hasOwn(S,"value")&&S.value===void 0)){if(!r.has(E))throw new TypeError("HTTP options contain unknown fields");if(!S||!S.enumerable||!Object.hasOwn(S,"value"))throw new TypeError("HTTP options must contain enumerable own data properties")}}}let n=E=>{if(e==null||!Object.hasOwn(e,E))return;let S=Object.getOwnPropertyDescriptor(e,E);if(!S||!Object.hasOwn(S,"value"))throw new TypeError("HTTP options must contain own data properties");return S.value};if(typeof t!="string"||t.length===0||t.length>8192)throw new TypeError("HTTP URL must be a bounded string");let i=n("method");if(i!==void 0&&(typeof i!="string"||!/^[A-Za-z]+$/u.test(i)))throw new TypeError("HTTP method must be a string token");let l=n("timeoutMs");if(l!==void 0&&(!Number.isInteger(l)||l<1||l>12e4))throw new TypeError("HTTP timeoutMs must be a bounded integer");let s=n("retries");if(s!==void 0&&(!Number.isInteger(s)||s<0||s>10))throw new TypeError("HTTP retries must be a bounded integer");let f=n("redirectPolicy");if(f!==void 0&&f!=="follow"&&f!=="error")throw new TypeError('HTTP redirectPolicy must be "follow" or "error"');let o=n("maxRedirects");if(o!==void 0&&(!Number.isInteger(o)||o<0||o>Q))throw new TypeError(`HTTP maxRedirects must be an integer from 0 through ${Q}`);if(f==="error"&&o!==void 0&&o!==0)throw new TypeError('HTTP redirectPolicy "error" requires maxRedirects 0 when supplied');let u=f??"follow",a=u==="error"?0:o??Q;for(let E of["dedupe","untrustedUrl","sameOriginRedirectsOnly"]){let S=n(E);if(S!==void 0&&typeof S!="boolean")throw new TypeError(`HTTP ${E} must be boolean`)}let c=n("maxResponseBytes");if(c!==void 0&&(!Number.isInteger(c)||c<1||c>64*1024*1024))throw new TypeError("HTTP maxResponseBytes must be a bounded integer");let p=n("signal");if(p!==void 0){if(L.isProxy(p)||!(p instanceof AbortSignal))throw new TypeError("HTTP signal must be a native AbortSignal");try{pe(p)}catch{throw new TypeError("HTTP signal must be a native AbortSignal")}}for(let E of["importUndici","lookupFn","validateResponse"]){let S=n(E);if(S!==void 0&&typeof S!="function")throw new TypeError(`HTTP ${E} must be a function`)}let d=n("fetchImpl"),m=d||globalThis.fetch;if(typeof m!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let A=l??12e3,R=(i||"GET").toUpperCase(),k=n("headers"),j=gt(k),g=Object.assign(Object.create(null),j);Object.keys(g).some(E=>E.toLowerCase()==="accept")||(g.Accept="application/json");let T=n("body");T!=null&&typeof T!="string"&&(Object.keys(g).find(S=>S.toLowerCase()==="content-type")||(g["Content-Type"]="application/json"),T=bt(T));let N=s??ut,I=n("lookupFn"),y=!d,O=n("untrustedUrl")===!0,P=n("sameOriginRedirectsOnly")===!0,C=n("importUndici"),h=n("validateResponse"),_=p,B=c??null,v=async()=>{let E;for(let S=0;S<=N;S++){_&&pt.call(_);try{return await $t(t,{fetchImpl:m,method:R,headers:g,body:T,timeoutMs:A,lookupFn:I,realFetch:y,untrustedUrl:O,maxResponseBytes:B,sameOriginRedirectsOnly:P,importUndici:C,validateResponse:h,signal:_,redirectPolicy:u,maxRedirects:a})}catch(U){E=U;let V=re=>{if(!U||typeof U!="object"&&typeof U!="function"||L.isProxy(U))return;let W=Object.getOwnPropertyDescriptor(U,re);return W&&Object.hasOwn(W,"value")?W.value:void 0},te=V("status"),Ye=V("oracleTimeout")===!0||V("name")==="AbortError"||V("name")==="TimeoutError"||pe(_),qe=new Set([408,425,429]),Ke=V("retryable")===!1?!1:te!=null?qe.has(te)||lt.has(te)&&Pe.has(R):!Ye&&Pe.has(R);if(S===N||!Ke)throw U;let be=At(S,V("retryAfter"));_?await new Promise((re,W)=>{let Ze=setTimeout(re,be);ht.call(_,"abort",()=>{clearTimeout(Ze),W(mt(_)||new DOMException("Aborted","AbortError"))},{once:!0})}):await Rt(be)}}throw E};if(!(n("dedupe")!==!1&&!_&&$e(R,T)))return v();let w=Pt(R,t,g,{untrustedUrl:O,maxResponseBytes:B,sameOriginRedirectsOnly:P,redirectPolicy:u,maxRedirects:a,timeoutMs:A,retries:N,fetchImpl:X(m),realFetch:y,lookupFn:X(I),importUndici:X(C),validateResponse:X(h)},T),$=fe.get(w);if($)return $;let b=v().finally(()=>fe.delete(w));return fe.set(w,b),b}var Ie={robinhood:{chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC"],evm:!0},ethereum:{chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],evm:!0},polygon:{chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],evm:!0},arbitrum:{chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],evm:!0},base:{chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],evm:!0},hyperevm:{chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],evm:!0},bsc:{chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],evm:!0},avalanche:{chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],evm:!0},optimism:{chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],evm:!0},abstract:{chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],evm:!0},stable:{chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],evm:!0}},Nt=new Map(Object.values(Ie).map(t=>[t.chainId,t]));function Ce(t){return Nt.get(Number(t))||null}function je(t,e=process.env){let r=Ce(t);if(!r)return null;for(let n of r.rpcEnv){let i=(e[n]||"").trim();if(i)return i}return null}import{Interface as It,getAddress as wr}from"ethers";var yr=new It(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);var Ct={1:"https://ethereum.publicnode.com",137:"https://polygon-bor-rpc.publicnode.com",42161:"https://arbitrum-one-rpc.publicnode.com",8453:"https://base-rpc.publicnode.com",10:"https://optimism-rpc.publicnode.com",988:"https://rpc.stable.xyz",56:"https://bsc-rpc.publicnode.com",43114:"https://avalanche-c-chain-rpc.publicnode.com",999:"https://rpc.hyperliquid.xyz/evm",2741:"https://api.mainnet.abs.xyz",4663:"https://rpc.mainnet.chain.robinhood.com"};function jt(t,{rpcUrl:e,env:r=process.env}={}){if(e)return e;let n=je(t,r);return n||Ct[Number(t)]||null}var Ht=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function Lt(t){let e=String(t||""),r=e.toLowerCase();if(e!==e.trim()||!/^[a-zA-Z0-9_]+$/.test(e)||!Ht.test(r))throw new Error(`evm-rpc: ${e} refused \u2014 @oracle-agent/oracle is prepare-only (read RPC only; no broadcast/sign)`);return r}var Y=new Map,He=new Map;function Bt(t){let e=new Error(t?.message||JSON.stringify(t));return e.code=t?.code,e}function Mt(t){if(t?.error)throw Bt(t.error);return t?.result}function Ut(t,e,r){return`${t}
3
3
  ${e}
4
- ${JSON.stringify(r??[])}`}async function gt(t,e,r){return ye(t,{method:"POST",body:e,fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs??12e3,signal:r.signal})}async function Ae(t,e,r=[],n={}){let a=String(e||""),i=ht(a),o=ft(t,n);if(!o)throw new Error(`No RPC URL for chainId ${t} (set env from chain registry rpcEnv or pass rpcUrl)`);if(i==="eth_chainid"&&n.cacheChainId!==!1){let h=ke.get(o);if(h!=null)return h}let s=n.dedupe!==!1&&!n.signal?wt(o,a,r):null;if(s&&U.has(s))return U.get(s);let f=(async()=>{let h=await gt(o,{jsonrpc:"2.0",id:1,method:e,params:r},n),c=mt(h);return i==="eth_chainid"&&typeof c=="string"&&ke.set(o,c),c})();return s&&(U.set(s,f),f.finally(()=>{U.get(s)===f&&U.delete(s)}).catch(()=>{})),f}var ne=999,re=1,bt=8453,Re="0x1d9d87eBc14e71490bB87f1C39F65BDB979f3cb7",yt="0x4d5e4ed4D5e4A160Fa136853597cDc2eBBe66494",$e="0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",Et="0xC6d566A56A1aFf6508b41f6c90ff131615583BCD",xt=".80002105.reverse",Te=/^0x[a-fA-F0-9]{40}$/,_e=new TextEncoder,Ce=t=>"0x"+Buffer.from(t).toString("hex"),B=t=>Ce(te(_e.encode(t))).slice(0,10),ve=t=>t.toLowerCase().replace(/^0x/,"").padStart(64,"0");function z(t){let e=new Uint8Array(32);if(t)for(let r of String(t).split(".").reverse()){let n=te(_e.encode(r)),a=new Uint8Array(64);a.set(e,0),a.set(n,32),e=te(a)}return Ce(e)}function oe(t){if(!t||t==="0x"||/^0x0*$/.test(t))return"";try{let e=t.slice(2),r=parseInt(e.slice(0,64),16)*2,n=parseInt(e.slice(r,r+64),16);if(!Number.isFinite(n)||n<=0)return"";let a=e.slice(r+64,r+64+n*2);return Buffer.from(a,"hex").toString("utf8")}catch{return""}}async function O(t,e,r){try{return await Ae(t,"eth_call",[{to:e,data:r},"latest"])}catch{return null}}async function St(t){let e=await O(ne,Re,B("primaryName(address)")+ve(t)),r=oe(e);return r?r.endsWith(".hl")?r:`${r}.hl`:null}async function kt(t){let e=await O(ne,yt,B("getName(address)")+ve(t)),r=oe(e);return r?r.endsWith(".hype")?r:`${r}.hype`:null}async function Ie(t,e,r){let n=await O(t,r,B("name(bytes32)")+e.slice(2));return oe(n)||null}async function At(t){let e=z(`${t.slice(2).toLowerCase()}.addr.reverse`),r=await O(re,$e,B("resolver(bytes32)")+e.slice(2));if(!r)return null;let n="0x"+r.slice(-40);return/^0x0+$/.test(n)?null:Ie(re,e,n)}async function Rt(t){let e=z(t.slice(2).toLowerCase()+xt);return Ie(bt,e,Et)}var $t=[{source:"hl",fn:St},{source:"hype",fn:kt},{source:"ens",fn:At},{source:"basename",fn:Rt}];async function Tt(t){let e=z(t),r=await O(ne,Re,B("ownerOf(uint256)")+e.slice(2));if(!r||r.length<66)return null;let n="0x"+r.slice(-40);return/^0x0+$/.test(n)?null:n}async function _t(t,e,r){let n=z(e),a=await O(t,r,B("resolver(bytes32)")+n.slice(2));if(!a)return null;let i="0x"+a.slice(-40);if(/^0x0+$/.test(i))return null;let o=await O(t,i,B("addr(bytes32)")+n.slice(2));if(!o)return null;let d="0x"+o.slice(-40);return/^0x0+$/.test(d)?null:d}async function Ne(t){let e=String(t||"").trim().toLowerCase();if(!e||!e.includes("."))return null;if(e.endsWith(".hl")){let r=await Tt(e);return r?{address:r,source:"hl",name:e}:null}if(e.endsWith(".eth")){let r=await _t(re,e,$e);return r?{address:r,source:e.endsWith(".base.eth")?"basename":"ens",name:e}:null}return null}var qt=$t.map(t=>t.source);var D={1:"ethereum",8453:"base",42161:"arbitrum"},Ct=Object.fromEntries(Object.entries(D).map(([t,e])=>[e,Number(t)])),Le=`oracle follow <name-or-address> [--chain <name>] [--blocks <n>] [--json]
4
+ ${JSON.stringify(r??[])}`}async function Dt(t,e,r){return Ne(t,{method:"POST",body:e,fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs??12e3,signal:r.signal})}async function Le(t,e,r=[],n={}){let i=String(e||""),l=Lt(i),s=jt(t,n);if(!s)throw new Error(`No RPC URL for chainId ${t} (set env from chain registry rpcEnv or pass rpcUrl)`);if(l==="eth_chainid"&&n.cacheChainId!==!1){let a=He.get(s);if(a!=null)return a}let o=n.dedupe!==!1&&!n.signal?Ut(s,i,r):null;if(o&&Y.has(o))return Y.get(o);let u=(async()=>{let a=await Dt(s,{jsonrpc:"2.0",id:1,method:e,params:r},n),c=Mt(a);return l==="eth_chainid"&&typeof c=="string"&&He.set(s,c),c})();return o&&(Y.set(o,u),u.finally(()=>{Y.get(o)===u&&Y.delete(o)}).catch(()=>{})),u}var we=999,me=1,Ft=8453,Be="0x1d9d87eBc14e71490bB87f1C39F65BDB979f3cb7",zt="0x4d5e4ed4D5e4A160Fa136853597cDc2eBBe66494",Me="0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",Jt="0xC6d566A56A1aFf6508b41f6c90ff131615583BCD",Gt=".80002105.reverse",Ue=/^0x[a-fA-F0-9]{40}$/,De=new TextEncoder,Fe=t=>"0x"+Buffer.from(t).toString("hex"),J=t=>Fe(he(De.encode(t))).slice(0,10),ze=t=>t.toLowerCase().replace(/^0x/,"").padStart(64,"0");function ee(t){let e=new Uint8Array(32);if(t)for(let r of String(t).split(".").reverse()){let n=he(De.encode(r)),i=new Uint8Array(64);i.set(e,0),i.set(n,32),e=he(i)}return Fe(e)}function ye(t){if(!t||t==="0x"||/^0x0*$/.test(t))return"";try{let e=t.slice(2),r=parseInt(e.slice(0,64),16)*2,n=parseInt(e.slice(r,r+64),16);if(!Number.isFinite(n)||n<=0)return"";let i=e.slice(r+64,r+64+n*2);return Buffer.from(i,"hex").toString("utf8")}catch{return""}}async function G(t,e,r){try{return await Le(t,"eth_call",[{to:e,data:r},"latest"])}catch{return null}}async function Vt(t){let e=await G(we,Be,J("primaryName(address)")+ze(t)),r=ye(e);return r?r.endsWith(".hl")?r:`${r}.hl`:null}async function Wt(t){let e=await G(we,zt,J("getName(address)")+ze(t)),r=ye(e);return r?r.endsWith(".hype")?r:`${r}.hype`:null}async function Je(t,e,r){let n=await G(t,r,J("name(bytes32)")+e.slice(2));return ye(n)||null}async function Yt(t){let e=ee(`${t.slice(2).toLowerCase()}.addr.reverse`),r=await G(me,Me,J("resolver(bytes32)")+e.slice(2));if(!r)return null;let n="0x"+r.slice(-40);return/^0x0+$/.test(n)?null:Je(me,e,n)}async function qt(t){let e=ee(t.slice(2).toLowerCase()+Gt);return Je(Ft,e,Jt)}var Kt=[{source:"hl",fn:Vt},{source:"hype",fn:Wt},{source:"ens",fn:Yt},{source:"basename",fn:qt}];async function Zt(t){let e=ee(t),r=await G(we,Be,J("ownerOf(uint256)")+e.slice(2));if(!r||r.length<66)return null;let n="0x"+r.slice(-40);return/^0x0+$/.test(n)?null:n}async function Xt(t,e,r){let n=ee(e),i=await G(t,r,J("resolver(bytes32)")+n.slice(2));if(!i)return null;let l="0x"+i.slice(-40);if(/^0x0+$/.test(l))return null;let s=await G(t,l,J("addr(bytes32)")+n.slice(2));if(!s)return null;let f="0x"+s.slice(-40);return/^0x0+$/.test(f)?null:f}async function Ge(t){let e=String(t||"").trim().toLowerCase();if(!e||!e.includes("."))return null;if(e.endsWith(".hl")){let r=await Zt(e);return r?{address:r,source:"hl",name:e}:null}if(e.endsWith(".eth")){let r=await Xt(me,e,Me);return r?{address:r,source:e.endsWith(".base.eth")?"basename":"ens",name:e}:null}return null}var Er=Kt.map(t=>t.source);var q={1:"ethereum",8453:"base",42161:"arbitrum"},Qt=Object.fromEntries(Object.entries(q).map(([t,e])=>[e,Number(t)])),We=`oracle follow <name-or-address> [--chain <name>] [--blocks <n>] [--json]
5
5
 
6
6
  oracle follow vitalik.eth
7
7
  oracle follow demi.hl --chain base
@@ -10,21 +10,21 @@ ${JSON.stringify(r??[])}`}async function gt(t,e,r){return ye(t,{method:"POST",bo
10
10
  Reads ERC20 transfer activity for a wallet. Read-only: this calls
11
11
  eth_getLogs and eth_blockNumber and nothing else, so it can never move funds.
12
12
 
13
- Chains: ${Object.values(D).join(", ")}. Default: ethereum.
13
+ Chains: ${Object.values(q).join(", ")}. Default: ethereum.
14
14
  Lookback defaults to 40000 blocks. Endpoints are keyless.
15
15
 
16
16
  Note publicnode-class RPCs are deliberately excluded: they retain only ~128
17
- blocks, so they return an empty result instead of an error.`;function Pe(t,e){let r=t.indexOf(e);return r>=0?t[r+1]:void 0}function vt(t){let e=String(t??"");return e.length>22?`${e.slice(0,19)}...`:e}async function It(t=[]){let e=t.includes("--json"),r=[];for(let s=0;s<t.length;s+=1){let f=t[s];if(f!=="--json"){if(f==="--chain"||f==="--blocks"){s+=1;continue}r.push(f)}}let n=(r[0]||"").trim();if(!n||n==="--help"||n==="-h")return process.stdout.write(`${Le}
18
- `),n?0:1;let a=(Pe(t,"--chain")||"ethereum").toLowerCase(),i=Ct[a]??Number(a);if(!W[i])return process.stderr.write(`follow: unsupported chain "${a}". Supported: ${Object.values(D).join(", ")}
19
- `),1;let o=Pe(t,"--blocks"),d=o?Number(o):4e4;if(!Number.isFinite(d)||d<=0)return process.stderr.write(`follow: --blocks must be a positive number, got "${o}"
20
- `),1;try{let s=n,f=null;if(!Te.test(n)){let l=await Ne(n);if(!l?.address)return process.stderr.write(`follow: could not resolve "${n}" to an address
21
- `),1;s=l.address,f=n}let h=await le(s,{chains:[i],lookback:d,onWarn:e?void 0:l=>process.stderr.write(` warn: ${l}
22
- `)}),c=h.events||[];if(e)return process.stdout.write(`${JSON.stringify({address:s,resolvedFrom:f,chain:D[i]||String(i),lookbackBlocks:d,count:c.length,errors:h.errors||[],events:c})}
23
- `),0;let u=f?`${f} ${s}`:s;process.stdout.write(`${u}
24
- `),process.stdout.write(` ${D[i]||i} \xB7 last ${d} blocks \xB7 ${c.length} transfer${c.length===1?"":"s"}
17
+ blocks, so they return an empty result instead of an error.`;function Ve(t,e){let r=t.indexOf(e);return r>=0?t[r+1]:void 0}function er(t){let e=String(t??"");return e.length>22?`${e.slice(0,19)}...`:e}async function tr(t=[]){let e=t.includes("--json"),r=[];for(let o=0;o<t.length;o+=1){let u=t[o];if(u!=="--json"){if(u==="--chain"||u==="--blocks"){o+=1;continue}r.push(u)}}let n=(r[0]||"").trim();if(!n||n==="--help"||n==="-h")return process.stdout.write(`${We}
18
+ `),n?0:1;let i=(Ve(t,"--chain")||"ethereum").toLowerCase(),l=Qt[i]??Number(i);if(!oe[l])return process.stderr.write(`follow: unsupported chain "${i}". Supported: ${Object.values(q).join(", ")}
19
+ `),1;let s=Ve(t,"--blocks"),f=s?Number(s):4e4;if(!Number.isFinite(f)||f<=0)return process.stderr.write(`follow: --blocks must be a positive number, got "${s}"
20
+ `),1;try{let o=n,u=null;if(!Ue.test(n)){let d=await Ge(n);if(!d?.address)return process.stderr.write(`follow: could not resolve "${n}" to an address
21
+ `),1;o=d.address,u=n}let a=await Se(o,{chains:[l],lookback:f,onWarn:e?void 0:d=>process.stderr.write(` warn: ${d}
22
+ `)}),c=a.events||[];if(e)return process.stdout.write(`${JSON.stringify({address:o,resolvedFrom:u,chain:q[l]||String(l),lookbackBlocks:f,count:c.length,errors:a.errors||[],events:c})}
23
+ `),0;let p=u?`${u} ${o}`:o;process.stdout.write(`${p}
24
+ `),process.stdout.write(` ${q[l]||l} \xB7 last ${f} blocks \xB7 ${c.length} transfer${c.length===1?"":"s"}
25
25
  `),c.length||process.stdout.write(` no ERC20 transfers in this window
26
- `);for(let l of c.slice(0,25)){let E=l.to?.toLowerCase()===s.toLowerCase()?"in ":"out";process.stdout.write(` ${E} blk ${l.blockNumber} token ${l.token} ${vt(l.value)}
26
+ `);for(let d of c.slice(0,25)){let m=d.to?.toLowerCase()===o.toLowerCase()?"in ":"out";process.stdout.write(` ${m} blk ${d.blockNumber} token ${d.token} ${er(d.value)}
27
27
  `)}c.length>25&&process.stdout.write(` ... ${c.length-25} more (use --json for all)
28
- `);for(let l of h.errors||[])process.stderr.write(` error: ${l.stage||"rpc"}: ${l.error}
29
- `);return 0}catch(s){return process.stderr.write(`follow failed: ${s?.message||s}
30
- `),1}}var Qt={name:"follow",summary:"read a wallet's recent ERC20 transfer activity",group:"read",usage:Le,async run(t){return It(t.argv||[])}};export{Qt as default};
28
+ `);for(let d of a.errors||[])process.stderr.write(` error: ${d.stage||"rpc"}: ${d.error}
29
+ `);return 0}catch(o){return process.stderr.write(`follow failed: ${o?.message||o}
30
+ `),1}}var Pr={name:"follow",summary:"read a wallet's recent ERC20 transfer activity",group:"read",usage:We,async run(t){return tr(t.argv||[])}};export{Pr as default};
@@ -1,4 +1,4 @@
1
- import k from"node:fs";import m from"node:path";var s=Object.freeze([{id:"oracle",label:"Oracle Native",kind:"oracle",bins:["oracle"],website:!0,detect:!0},{id:"hermes",label:"Hermes Agent",kind:"mcp",bins:["hermes"],mcpTarget:"generic",configKey:"hermes",website:!0,detect:!0},{id:"claude",label:"Claude Code",kind:"mcp",bins:["claude"],mcpTarget:"claude-code",configKey:"claudeCode",website:!0,detect:!0},{id:"claude-desktop",label:"Claude Desktop",kind:"mcp",bins:[],mcpTarget:"claude-desktop",configKey:"claudeDesktop",website:!0,detect:!1},{id:"chatgpt",label:"ChatGPT",kind:"mcp",bins:[],mcpTarget:"chatgpt",configKey:"chatgpt",website:!0,detect:!1},{id:"codex",label:"OpenAI Codex",kind:"mcp",bins:["codex"],mcpTarget:"codex",configKey:"codex",website:!0,detect:!0},{id:"cursor",label:"Cursor",kind:"mcp",bins:["cursor","cursor-agent"],mcpTarget:"cursor",configKey:"cursor",website:!0,detect:!0},{id:"windsurf",label:"Windsurf",kind:"mcp",bins:["windsurf"],mcpTarget:"vscode",configKey:"windsurf",website:!0,detect:!0},{id:"vscode",label:"VS Code / Copilot",kind:"mcp",bins:["code","code-insiders"],mcpTarget:"vscode",configKey:"vscode",website:!0,detect:!0},{id:"openclaw",label:"OpenClaw",kind:"mcp",bins:["openclaw","claw"],mcpTarget:"generic",configKey:"openclaw",website:!0,detect:!0},{id:"perplexity",label:"Perplexity",kind:"mcp",bins:["perplexity","pplx"],mcpTarget:"generic",configKey:"perplexity",website:!0,detect:!0},{id:"manus",label:"Manus",kind:"mcp",bins:["manus"],mcpTarget:"generic",configKey:"manus",website:!0,detect:!0},{id:"prime",label:"Prime Intellect Agent",kind:"mcp",bins:["prime-agent","prime"],mcpTarget:"generic",configKey:"prime",website:!1,detect:!0},{id:"opencode",label:"OpenCode",kind:"mcp",bins:["opencode"],mcpTarget:"generic",configKey:"opencode",website:!1,detect:!0},{id:"aider",label:"Aider",kind:"mcp",bins:["aider"],mcpTarget:"generic",configKey:"aider",website:!1,detect:!0},{id:"continue",label:"Continue",kind:"mcp",bins:["continue"],mcpTarget:"vscode",configKey:"continue",website:!1,detect:!0},{id:"goose",label:"Goose",kind:"mcp",bins:["goose"],mcpTarget:"generic",configKey:"goose",website:!1,detect:!0},{id:"amp",label:"Amp",kind:"mcp",bins:["amp"],mcpTarget:"generic",configKey:"amp",website:!1,detect:!0},{id:"generic",label:"Generic MCP",kind:"mcp",bins:[],mcpTarget:"generic",configKey:"genericMcp",website:!0,detect:!1}]);function c(){return s.filter(e=>e.website)}function p(){return s.filter(e=>e.detect!==!1&&(e.bins?.length||e.kind==="oracle"))}function l(e){return s.find(n=>n.id===e)?.mcpTarget||"generic"}function d(e){return e==="oracle"?"oracle chat":`oracle mcp install ${l(e)}`}var I=Object.freeze({openrouter:{key:"OPENROUTER_API_KEY",baseUrl:"https://openrouter.ai/api/v1",model:"openrouter/auto"},openai:{key:"OPENAI_API_KEY",baseUrl:"https://api.openai.com/v1",model:"gpt-4.1-mini"},anthropic:{key:"ANTHROPIC_API_KEY",baseUrl:"https://api.anthropic.com/v1",model:"claude-sonnet-4-6",protocol:"anthropic-messages"},xai:{key:"XAI_API_KEY",baseUrl:"https://api.x.ai/v1",model:"grok-4.6"},deepseek:{key:"DEEPSEEK_API_KEY",baseUrl:"https://api.deepseek.com/v1",model:"deepseek-chat"},gemini:{key:"GEMINI_API_KEY",alternateKey:"GOOGLE_API_KEY",baseUrl:"https://generativelanguage.googleapis.com/v1beta/openai",model:"gemini-2.5-flash"},kimi:{key:"MOONSHOT_API_KEY",alternateKey:"KIMI_API_KEY",baseUrl:"https://api.moonshot.ai/v1",model:"kimi-k3",protocol:"openai-chat"},mistral:{key:"MISTRAL_API_KEY",baseUrl:"https://api.mistral.ai/v1",model:"mistral-large-latest",protocol:"openai-chat"},nous:{key:"NOUS_API_KEY",baseUrl:"https://inference-api.nousresearch.com/v1",model:"moonshotai/kimi-k3",protocol:"openai-chat"},qwen:{key:"DASHSCOPE_API_KEY",alternateKey:"QWEN_API_KEY",baseUrl:"https://dashscope-intl.aliyuncs.com/compatible-mode/v1",model:"qwen-plus",protocol:"openai-chat"},glm:{key:"ZHIPU_API_KEY",alternateKey:"GLM_API_KEY",baseUrl:"https://open.bigmodel.cn/api/paas/v4",model:"glm-4.5",protocol:"openai-chat"},local:{baseUrl:"http://127.0.0.1:8080/v1",model:"Qwen3-8B-Q4_K_M",protocol:"openai-chat",keyless:!0},ollama:{baseUrl:"http://127.0.0.1:11434/v1",model:"llama3.2",protocol:"openai-chat",keyless:!0}}),L=Object.freeze({"anthropic-oauth":{key:"ANTHROPIC_API_KEY",baseUrl:"https://api.anthropic.com/v1",model:"claude-sonnet-4-20250514",protocol:"anthropic-messages"},"openai-codex":{key:"OPENAI_API_KEY",baseUrl:"https://chatgpt.com/backend-api/codex",model:"gpt-5.4",protocol:"responses"},"xai-oauth":{key:"XAI_API_KEY",baseUrl:"https://api.x.ai/v1",model:"grok-4.6",protocol:"responses"}});var U=Object.freeze(["xai-oauth","anthropic-oauth","openai-codex"]);function A(){return p().map(e=>({name:e.id,bin:e.bins?.[0]||e.id,label:e.label,kind:e.kind,altBins:(e.bins||[]).slice(1)}))}function h(e){for(let o of(process.env.PATH||"").split(m.delimiter)){let n=m.join(o,e);try{if(k.existsSync(n))return n}catch{}}return null}function _(e){let o=[e.bin,...e.altBins||[]].filter(Boolean);for(let n of o){let r=h(n);if(r)return r}return null}function f(e=process.env){let o=[];for(let r of A()){if(r.kind==="oracle"||r.name==="oracle"){o.push({...r,path:process.argv[1]||"oracle"});continue}let i=_(r);i&&o.push({name:r.name,bin:r.bin,label:r.label,kind:r.kind,path:i})}let n=String(e.ORACLE_HARNESS_EXTRA||e.ORACLE_CLIENT_EXTRA||"").split(",").map(r=>r.trim()).filter(Boolean);for(let r of n){if(o.some(t=>t.bin===r||t.name===r))continue;let i=h(r);i&&o.push({name:r,bin:r,label:r,kind:"mcp",path:i})}return o}function O(e){if(e.kind==="oracle"||e.name==="oracle")return{...e,direction:"native",integrate:"oracle chat",outbound:"oracle chat",inbound:null,plugins:null,backendEnv:null,note:"Oracle native harness. Default. No external harness required."};let o=l(e.name)||"generic",n=e.name==="hermes"?"hermes":e.name;return{...e,direction:"client",integrate:`oracle mcp install ${o}`,outbound:`oracle chat --backend ${n}`,inbound:`oracle mcp install ${o}`,plugins:"oracle plugins install <path|git-url>",backendEnv:`ORACLE_CHAT_BACKEND=${n}`,note:"Use through Oracle (`oracle chat --backend \u2026`) or wire Oracle into this harness (`oracle mcp install`). Detection never auto-selects."}}function w(e){let o=e.map(O),n=o.find(a=>a.direction==="native"),r=o.filter(a=>a.direction!=="native"),i=c().filter(a=>a.kind==="mcp"),t=[];if(t.push(""),t.push("Three ways to run Oracle:"),t.push(` 1) Oracle native harness ${n?n.path:"oracle"}`),t.push(" oracle setup model && oracle chat"),t.push(" 2) Through Oracle attach Hermes / Claude / Codex as the engine"),t.push(" oracle chat --backend hermes"),t.push(" 3) Into your harness wire Oracle MCP into the agent you already use"),t.push(" oracle mcp install <target> | oracle plugins install <path>"),t.push(""),t.push("Oracle native is the default harness. Detection never auto-selects another harness."),t.push(""),t.push("Detected on this machine:"),r.length===0)t.push(" (none, Oracle native is enough)");else for(let a of r)t.push(` ${a.label.padEnd(22)} ${a.path}`),t.push(` ${" ".repeat(22)} \u2192 through Oracle: ${a.outbound}`),t.push(` ${" ".repeat(22)} into harness: ${a.inbound}`);t.push(""),t.push("Supported harness roster (MCP install targets):");for(let a of i){let b=d(a.id),g=r.find(E=>E.name===a.id);t.push(` ${a.label.padEnd(22)} ${b}${g?" [detected]":""}`)}return t.push(""),t.push("Also:"),t.push(" oracle mcp print --target generic"),t.push(" oracle plugins list"),t.push(" ORACLE_HARNESS_EXTRA=foo,bar # detect extra bins"),t.push(""),t.push("Models on the site (Grok, Gemini, DeepSeek, Qwen, Kimi) are providers for"),t.push("Oracle native, configure with oracle setup model / oracle auth, not as harnesses."),t.join(`
1
+ import k from"node:fs";import m from"node:path";var s=Object.freeze([{id:"oracle",label:"Oracle Native",kind:"oracle",bins:["oracle"],website:!0,detect:!0},{id:"hermes",label:"Hermes Agent",kind:"mcp",bins:["hermes"],mcpTarget:"generic",configKey:"hermes",website:!0,detect:!0},{id:"claude",label:"Claude Code",kind:"mcp",bins:["claude"],mcpTarget:"claude-code",configKey:"claudeCode",website:!0,detect:!0},{id:"claude-desktop",label:"Claude Desktop",kind:"mcp",bins:[],mcpTarget:"claude-desktop",configKey:"claudeDesktop",website:!0,detect:!1},{id:"chatgpt",label:"ChatGPT",kind:"mcp",bins:[],mcpTarget:"chatgpt",configKey:"chatgpt",website:!0,detect:!1},{id:"codex",label:"OpenAI Codex",kind:"mcp",bins:["codex"],mcpTarget:"codex",configKey:"codex",website:!0,detect:!0},{id:"cursor",label:"Cursor",kind:"mcp",bins:["cursor","cursor-agent"],mcpTarget:"cursor",configKey:"cursor",website:!0,detect:!0},{id:"windsurf",label:"Windsurf",kind:"mcp",bins:["windsurf"],mcpTarget:"vscode",configKey:"windsurf",website:!0,detect:!0},{id:"vscode",label:"VS Code / Copilot",kind:"mcp",bins:["code","code-insiders"],mcpTarget:"vscode",configKey:"vscode",website:!0,detect:!0},{id:"openclaw",label:"OpenClaw",kind:"mcp",bins:["openclaw","claw"],mcpTarget:"generic",configKey:"openclaw",website:!0,detect:!0},{id:"perplexity",label:"Perplexity",kind:"mcp",bins:["perplexity","pplx"],mcpTarget:"generic",configKey:"perplexity",website:!0,detect:!0},{id:"manus",label:"Manus",kind:"mcp",bins:["manus"],mcpTarget:"generic",configKey:"manus",website:!0,detect:!0},{id:"prime",label:"Prime Intellect Agent",kind:"mcp",bins:["prime-agent","prime"],mcpTarget:"generic",configKey:"prime",website:!1,detect:!0},{id:"opencode",label:"OpenCode",kind:"mcp",bins:["opencode"],mcpTarget:"generic",configKey:"opencode",website:!1,detect:!0},{id:"aider",label:"Aider",kind:"mcp",bins:["aider"],mcpTarget:"generic",configKey:"aider",website:!1,detect:!0},{id:"continue",label:"Continue",kind:"mcp",bins:["continue"],mcpTarget:"vscode",configKey:"continue",website:!1,detect:!0},{id:"goose",label:"Goose",kind:"mcp",bins:["goose"],mcpTarget:"generic",configKey:"goose",website:!1,detect:!0},{id:"amp",label:"Amp",kind:"mcp",bins:["amp"],mcpTarget:"generic",configKey:"amp",website:!1,detect:!0},{id:"generic",label:"Generic MCP",kind:"mcp",bins:[],mcpTarget:"generic",configKey:"genericMcp",website:!0,detect:!1}]);function c(){return s.filter(e=>e.website)}function p(){return s.filter(e=>e.detect!==!1&&(e.bins?.length||e.kind==="oracle"))}function l(e){return s.find(n=>n.id===e)?.mcpTarget||"generic"}function d(e){return e==="oracle"?"oracle chat":`oracle mcp install ${l(e)}`}var I=Object.freeze({openrouter:{key:"OPENROUTER_API_KEY",baseUrl:"https://openrouter.ai/api/v1",model:"openrouter/auto"},openai:{key:"OPENAI_API_KEY",baseUrl:"https://api.openai.com/v1",model:"gpt-4.1-mini"},anthropic:{key:"ANTHROPIC_API_KEY",baseUrl:"https://api.anthropic.com/v1",model:"claude-sonnet-4-6",protocol:"anthropic-messages"},xai:{key:"XAI_API_KEY",baseUrl:"https://api.x.ai/v1",model:"grok-4.6"},deepseek:{key:"DEEPSEEK_API_KEY",baseUrl:"https://api.deepseek.com/v1",model:"deepseek-chat"},gemini:{key:"GEMINI_API_KEY",alternateKey:"GOOGLE_API_KEY",baseUrl:"https://generativelanguage.googleapis.com/v1beta/openai",model:"gemini-2.5-flash"},kimi:{key:"MOONSHOT_API_KEY",alternateKey:"KIMI_API_KEY",baseUrl:"https://api.moonshot.ai/v1",model:"kimi-k3",protocol:"openai-chat"},mistral:{key:"MISTRAL_API_KEY",baseUrl:"https://api.mistral.ai/v1",model:"mistral-large-latest",protocol:"openai-chat"},nous:{key:"NOUS_API_KEY",baseUrl:"https://inference-api.nousresearch.com/v1",model:"moonshotai/kimi-k3",protocol:"openai-chat"},qwen:{key:"DASHSCOPE_API_KEY",alternateKey:"QWEN_API_KEY",baseUrl:"https://dashscope-intl.aliyuncs.com/compatible-mode/v1",model:"qwen-plus",protocol:"openai-chat"},glm:{key:"ZHIPU_API_KEY",alternateKey:"GLM_API_KEY",baseUrl:"https://open.bigmodel.cn/api/paas/v4",model:"glm-4.5",protocol:"openai-chat"},local:{baseUrl:"http://127.0.0.1:8080/v1",model:"Qwen3-8B-Q4_K_M",protocol:"openai-chat",keyless:!0},ollama:{baseUrl:"http://127.0.0.1:11434/v1",model:"llama3.2",protocol:"openai-chat",keyless:!0}}),L=Object.freeze({"anthropic-oauth":{key:"ANTHROPIC_API_KEY",baseUrl:"https://api.anthropic.com/v1",model:"claude-sonnet-4-20250514",protocol:"anthropic-messages"},"openai-codex":{key:"OPENAI_API_KEY",baseUrl:"https://chatgpt.com/backend-api/codex",model:"gpt-5.6-sol",protocol:"responses"},"xai-oauth":{key:"XAI_API_KEY",baseUrl:"https://api.x.ai/v1",model:"grok-4.6",protocol:"responses"}});var U=Object.freeze(["xai-oauth","anthropic-oauth","openai-codex"]);function A(){return p().map(e=>({name:e.id,bin:e.bins?.[0]||e.id,label:e.label,kind:e.kind,altBins:(e.bins||[]).slice(1)}))}function h(e){for(let o of(process.env.PATH||"").split(m.delimiter)){let n=m.join(o,e);try{if(k.existsSync(n))return n}catch{}}return null}function _(e){let o=[e.bin,...e.altBins||[]].filter(Boolean);for(let n of o){let r=h(n);if(r)return r}return null}function f(e=process.env){let o=[];for(let r of A()){if(r.kind==="oracle"||r.name==="oracle"){o.push({...r,path:process.argv[1]||"oracle"});continue}let i=_(r);i&&o.push({name:r.name,bin:r.bin,label:r.label,kind:r.kind,path:i})}let n=String(e.ORACLE_HARNESS_EXTRA||e.ORACLE_CLIENT_EXTRA||"").split(",").map(r=>r.trim()).filter(Boolean);for(let r of n){if(o.some(t=>t.bin===r||t.name===r))continue;let i=h(r);i&&o.push({name:r,bin:r,label:r,kind:"mcp",path:i})}return o}function O(e){if(e.kind==="oracle"||e.name==="oracle")return{...e,direction:"native",integrate:"oracle chat",outbound:"oracle chat",inbound:null,plugins:null,backendEnv:null,note:"Oracle native harness. Default. No external harness required."};let o=l(e.name)||"generic",n=e.name==="hermes"?"hermes":e.name;return{...e,direction:"client",integrate:`oracle mcp install ${o}`,outbound:`oracle chat --backend ${n}`,inbound:`oracle mcp install ${o}`,plugins:"oracle plugins install <path|git-url>",backendEnv:`ORACLE_CHAT_BACKEND=${n}`,note:"Use through Oracle (`oracle chat --backend \u2026`) or wire Oracle into this harness (`oracle mcp install`). Detection never auto-selects."}}function w(e){let o=e.map(O),n=o.find(a=>a.direction==="native"),r=o.filter(a=>a.direction!=="native"),i=c().filter(a=>a.kind==="mcp"),t=[];if(t.push(""),t.push("Three ways to run Oracle:"),t.push(` 1) Oracle native harness ${n?n.path:"oracle"}`),t.push(" oracle setup model && oracle chat"),t.push(" 2) Through Oracle attach Hermes / Claude / Codex as the engine"),t.push(" oracle chat --backend hermes"),t.push(" 3) Into your harness wire Oracle MCP into the agent you already use"),t.push(" oracle mcp install <target> | oracle plugins install <path>"),t.push(""),t.push("Oracle native is the default harness. Detection never auto-selects another harness."),t.push(""),t.push("Detected on this machine:"),r.length===0)t.push(" (none, Oracle native is enough)");else for(let a of r)t.push(` ${a.label.padEnd(22)} ${a.path}`),t.push(` ${" ".repeat(22)} \u2192 through Oracle: ${a.outbound}`),t.push(` ${" ".repeat(22)} into harness: ${a.inbound}`);t.push(""),t.push("Supported harness roster (MCP install targets):");for(let a of i){let b=d(a.id),g=r.find(E=>E.name===a.id);t.push(` ${a.label.padEnd(22)} ${b}${g?" [detected]":""}`)}return t.push(""),t.push("Also:"),t.push(" oracle mcp print --target generic"),t.push(" oracle plugins list"),t.push(" ORACLE_HARNESS_EXTRA=foo,bar # detect extra bins"),t.push(""),t.push("Models on the site (Grok, Gemini, DeepSeek, Qwen, Kimi) are providers for"),t.push("Oracle native, configure with oracle setup model / oracle auth, not as harnesses."),t.join(`
2
2
  `)}function u(){return["oracle harness, detect installed agent harnesses",""," oracle harness detect scan PATH + show supported harness roster"," oracle harness list alias of detect","","Modes:"," Oracle native harness oracle chat"," Through Oracle oracle chat --backend hermes|claude|codex|\u2026"," Into your harness oracle mcp install <target>","",`Harness roster: ${c().map(o=>o.id).join(", ")}`,"Extra bins: ORACLE_HARNESS_EXTRA=foo,bar","","Detection never selects a backend."].join(`
3
3
  `)}var M={name:"harness",aliases:["clients"],summary:"detect agent harnesses; use Oracle native or wire MCP into them",usage:u,async run(e,o){let n=e[0];if(n==="help"||n==="--help"||n==="-h")return process.stdout.write(u()+`
4
4
  `),0;if(n&&n!=="detect"&&n!=="list")return process.stderr.write(`oracle harness: unknown subcommand '${n}'
@@ -1,6 +1,6 @@
1
- import{readFileSync as We}from"node:fs";import{homedir as $t}from"node:os";import{join as qt}from"node:path";import{createHash as Ke}from"node:crypto";var G=1,B=1,Qe=1,ye="local-owner",me="local-owner",et=Object.freeze(["owner","operator","agent","viewer"]),tt=Object.freeze(["tenant","config","policy","grant","workflow","trade","receipt","audit","telemetry","context","lifecycle"]),ge=Object.freeze({read:"read",create:"create",update:"update",delete:"delete",manage:"manage",prepare:"prepare",cancel:"cancel",export:"export",approve:"approve"}),nt=Object.freeze(["owner"]),T=Object.freeze({ALLOW_ROLE_PERMISSION:"allow.role_permission",DENY_MISSING_CONTEXT:"deny.missing_context",DENY_INVALID_CONTEXT:"deny.invalid_context",DENY_INVALID_REQUEST:"deny.invalid_request",DENY_UNKNOWN_RESOURCE:"deny.unknown_resource",DENY_UNKNOWN_ACTION:"deny.unknown_action",DENY_UNBOUND_OBJECT:"deny.unbound_object",DENY_TENANT_MISMATCH:"deny.tenant_mismatch",DENY_RESOURCE_MISMATCH:"deny.resource_mismatch",DENY_ROLE_PERMISSION:"deny.role_permission",DENY_POLICY_NOT_APPROVER:"deny.policy_not_approver"}),Se=new Set(et),ie=new Set(tt),rt=new Set(Object.values(ge)),Ie=new Set(["user","service","local-owner"]),Ee=new Set(["verified-session","service-credential","desktop-session","owner-arm-token","local-owner"]),Z=/^[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}$/,be="tob1",Oe=new WeakSet,ot=new WeakMap,Ne=Object.freeze({owner:Object.freeze(["tenant:read","tenant:manage","config:read","config:manage","policy:read","policy:manage","grant:read","grant:create","grant:update","grant:delete","grant:manage","workflow:read","workflow:create","workflow:update","workflow:delete","workflow:cancel","workflow:approve","trade:read","trade:prepare","receipt:read","receipt:export","audit:read","audit:export","telemetry:read","telemetry:create","telemetry:export","context:read","context:create","context:update","context:delete","context:manage","context:export","lifecycle:read","lifecycle:create","lifecycle:update","lifecycle:delete","lifecycle:manage","lifecycle:approve","lifecycle:export"]),operator:Object.freeze(["tenant:read","config:read","policy:read","grant:read","workflow:read","workflow:create","workflow:update","workflow:cancel","trade:read","trade:prepare","receipt:read","audit:read","telemetry:read","telemetry:create","context:read","context:create","context:update","context:delete","lifecycle:read","lifecycle:create","lifecycle:update","lifecycle:manage"]),agent:Object.freeze(["tenant:read","config:read","policy:read","grant:read","workflow:read","workflow:create","workflow:update","trade:read","trade:prepare","receipt:read","telemetry:create","context:read","context:create","context:update","lifecycle:read"]),viewer:Object.freeze(["tenant:read","config:read","grant:read","workflow:read","trade:read","receipt:read","audit:read","telemetry:read","context:read","lifecycle:read"])}),Yt=Object.freeze(Object.fromEntries(Object.entries(Ne).map(([e,n])=>[e,Object.freeze([...n])]))),v=class extends Error{constructor(n,t="invalid-context"){super(n),this.name="TenantContextError",this.code=t}};function re(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function W(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let n of Object.values(e))W(n)}return e}function oe(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(oe).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${oe(e[n])}`).join(",")}}`}function _e(e){return Ke("sha256").update(oe(e)).digest("hex")}function he(e,n,t){if(!re(e))throw new v(`${t} must be a plain object`);let r=Object.keys(e).filter(o=>!n.has(o));if(r.length)throw new v(`${t} has unknown fields: ${r.sort().join(", ")}`)}function we(e,n){let t=String(e??"").trim();if(!Z.test(t))throw new v(`${n} is invalid`);return t}function ve(e,n="assignedRoles"){if(!Array.isArray(e)||e.length===0)throw new v(`${n} must contain at least one trusted role`,"missing-role-assignment");let t=[...new Set(e.map(o=>String(o??"").trim()))].sort(),r=t.filter(o=>!Se.has(o));if(r.length)throw new v(`${n} contains unknown roles: ${r.join(", ")}`,"unknown-role");return t}function Te(e,n){return e.length===n.length&&e.every((t,r)=>t===n[r])}function it(e){if(!re(e)||e.schemaVersion!==G||!Z.test(e.tenantId||"")||typeof e.localCompatibility!="boolean")return!1;let n=e.actor;if(!re(n)||n.schemaVersion!==B||!Z.test(n.actorId||"")||!Ie.has(n.actorType)||!Ee.has(n.authSource)||!Array.isArray(n.roles)||n.roles.length===0)return!1;let t=[...new Set(n.roles)].sort();return t.every(r=>Se.has(r))&&Te(t,n.roles)}function st(e,{assignedTenantId:n,assignedActorId:t,assignedActorType:r,assignedAuthSource:o,assignedRoles:i,assignedContextDomains:a=null,localCompatibility:l=!1}={}){let E=e;if(he(E,new Set(["schemaVersion","tenantId","actor","localCompatibility"]),"tenant claims"),E.schemaVersion!=null&&E.schemaVersion!==G)throw new v("unsupported tenant context schema version","unsupported-version");if(![n,t,r,o].every(O=>O!=null))throw new v("trusted tenant and actor identity assignments are required","missing-trusted-identity");let A=E.actor??{};if(he(A,new Set(["schemaVersion","actorId","actorType","authSource","roles"]),"actor claims"),A.schemaVersion!=null&&A.schemaVersion!==B)throw new v("unsupported actor identity schema version","unsupported-version");let x=we(n,"tenantId"),$=we(t,"actorId"),q=String(r).trim(),M=String(o).trim();if(!Ie.has(q))throw new v("actorType is invalid");if(!Ee.has(M))throw new v("authSource is invalid");let D=ve(i);if(!Array.isArray(a)&&a!=null)throw new v("assignedContextDomains must be an array","invalid-domain-assignment");let z=a==null?D.includes("owner")?["*"]:[]:[...new Set(a.map(O=>String(O??"").trim()))].sort();if(z.some(O=>O!=="*"&&!/^[a-z0-9][a-z0-9._-]{0,95}$/.test(O)))throw new v("assignedContextDomains contains an invalid domain","invalid-domain-assignment");if(A.roles!==void 0){let O;try{O=ve(A.roles,"claimed roles")}catch{throw new v("claimed roles do not match the trusted assignment","forged-role")}if(!Te(O,D))throw new v("claimed roles do not match the trusted assignment","forged-role")}if(E.localCompatibility!==void 0&&E.localCompatibility!==l)throw new v("local compatibility may only be set by the trusted boundary","forged-local-compatibility");if([[E.tenantId,x],[A.actorId,$],[A.actorType,q],[A.authSource,M]].some(([O,te])=>O!==void 0&&String(O).trim()!==te))throw new v("claimed identity does not match the trusted assignment","forged-identity");let L=W({schemaVersion:G,tenantId:x,actor:{schemaVersion:B,actorId:$,actorType:q,authSource:M,roles:D},localCompatibility:l===!0});return Oe.add(L),ot.set(L,Object.freeze(z)),L}function ke({authSource:e="local-owner"}={}){if(!new Set(["local-owner","desktop-session","owner-arm-token"]).has(e))throw new v("local owner authSource is invalid");return st({schemaVersion:G,tenantId:ye,actor:{schemaVersion:B,actorId:me,actorType:"local-owner",authSource:e}},{assignedTenantId:ye,assignedActorId:me,assignedActorType:"local-owner",assignedAuthSource:e,assignedRoles:["owner"],localCompatibility:!0})}function J(e){return Oe.has(e)&&it(e)}function at(e){if(!J(e))throw new v("a resolved tenant context is required","unresolved-context");return e}function F(e){return Buffer.from(e,"utf8").toString("base64url")}function ne(e,n){if(!e||!/^[A-Za-z0-9_-]+$/.test(e))throw new v(`${n} binding is invalid`,"invalid-object-binding");let t=Buffer.from(e,"base64url").toString("utf8");if(!t||F(t)!==e)throw new v(`${n} binding is non-canonical`,"invalid-object-binding");return t}function Re(e){let n=String(e??"").trim();if(!n||n.length>256||/[\u0000-\u001f\u007f]/.test(n))throw new v("objectId is invalid","invalid-object-id");return n}function xe(e,n,t){at(e);let r=String(n??"").trim();if(!ie.has(r))throw new v("resource is unknown","unknown-resource");let o=Re(t);return`${be}.${F(e.tenantId)}.${F(r)}.${F(o)}`}function ct(e){let n=String(e??""),t=n.split(".");if(t.length!==4||t[0]!==be)throw new v("tenant-bound object id required","unbound-object");let r=ne(t[1],"tenant"),o=ne(t[2],"resource"),i=ne(t[3],"object");if(!Z.test(r)||!ie.has(o))throw new v("tenant-bound object id is invalid","invalid-object-binding");return Re(i),W({schemaVersion:1,tenantId:r,resource:o,objectId:i,boundId:n})}function dt(e){if(typeof e!="string"||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(e))return null;let n=Date.parse(e);return Number.isFinite(n)&&new Date(n).toISOString()===e?e:null}function Ae(e){let n={...e,decisionId:_e(e)};return W(n)}function lt({context:e,resource:n,action:t,objectId:r=null,decidedAt:o}={}){let i=dt(o),a={schemaVersion:Qe,recordType:"tenant.access-decision",decidedAt:i,tenantId:J(e)?e.tenantId:null,actor:J(e)?{actorId:e.actor.actorId,actorType:e.actor.actorType,authSource:e.actor.authSource,roles:[...e.actor.roles]}:null,request:{resource:typeof n=="string"?n:null,action:typeof t=="string"?t:null,objectRefHash:r==null?null:_e(String(r))}},l=S=>Ae({...a,allowed:!1,outcome:"deny",reason:S});if(e==null)return l(T.DENY_MISSING_CONTEXT);if(!J(e))return l(T.DENY_INVALID_CONTEXT);if(!i)return l(T.DENY_INVALID_REQUEST);if(!ie.has(n))return l(T.DENY_UNKNOWN_RESOURCE);if(!rt.has(t))return l(T.DENY_UNKNOWN_ACTION);if(r!=null){let S;try{S=ct(r)}catch{return l(T.DENY_UNBOUND_OBJECT)}if(S.tenantId!==e.tenantId)return l(T.DENY_TENANT_MISMATCH);if(S.resource!==n)return l(T.DENY_RESOURCE_MISMATCH)}if(t===ge.approve&&!e.actor.roles.some(A=>nt.includes(A)))return l(T.DENY_ROLE_PERMISSION);let E=`${n}:${t}`,_=e.actor.roles.some(S=>Ne[S]?.includes(E));return Ae({...a,allowed:_,outcome:_?"allow":"deny",reason:_?T.ALLOW_ROLE_PERMISSION:T.DENY_ROLE_PERMISSION})}function Ce(e){let n=lt(e);if(!n.allowed){let t=new v(`tenant access denied: ${n.reason}`,"access-denied");throw t.decision=n,t}return n}import{createHash as ut,randomUUID as ft}from"node:crypto";import{chmodSync as pt,closeSync as K,constants as H,existsSync as se,fsyncSync as ae,lstatSync as De,mkdirSync as je,openSync as ce,readFileSync as yt,renameSync as mt,unlinkSync as de,writeFileSync as ze}from"node:fs";import{dirname as Le,resolve as $e}from"node:path";function le(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(le).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${le(e[n])}`).join(",")}}`}function C(e){return ut("sha256").update(le(e)).digest("hex")}function k(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let n of Object.values(e))k(n)}return e}function ht(e,n,t){let r=$e(e),o=Le(r);if(je(o,{recursive:!0,mode:448}),se(r)){let a=De(r);if(!a.isFile()||a.isSymbolicLink())throw t("state path must be a regular non-symlink file","unsafe-file")}let i=`${r}.${ft()}.tmp`;try{ze(i,`${JSON.stringify(n)}
2
- `,{encoding:"utf8",mode:384,flag:"wx"});let a=ce(i,H.O_RDONLY);try{ae(a)}finally{K(a)}mt(i,r),pt(r,384);let l;try{l=ce(o,H.O_RDONLY),ae(l)}finally{l!==void 0&&K(l)}}catch(a){try{se(i)&&de(i)}catch{}throw a}}function wt(e,n,t){if(!e||typeof e!="object"||Array.isArray(e))throw t("state must be an object","integrity-failed");if(e.schemaVersion!==n||!Array.isArray(e.events))throw t("state schema is invalid","integrity-failed");let r=null;for(let a=0;a<e.events.length;a+=1){let l=e.events[a];if(!l||typeof l!="object"||Array.isArray(l))throw t("event is invalid","integrity-failed");if(l.record&&typeof l.record.recordHash=="string"){let{recordHash:S,...A}=l.record;if(C(A)!==S)throw t("record hash integrity failed; state may be tampered","integrity-failed")}let{eventHash:E,..._}=l;if(l.sequence!==a+1||l.previousEventHash!==r||C(_)!==E)throw t("event hash chain integrity failed; state may be tampered","integrity-failed");r=E}let{stateHash:o,...i}=e;if(C(i)!==o)throw t("state hash integrity failed; state may be tampered","integrity-failed");return e}function X(e,n,t){if(!se(e)){let i={schemaVersion:n,events:[]};return{...i,stateHash:C(i)}}let r=De(e);if(!r.isFile()||r.isSymbolicLink())throw t("state path must be a regular non-symlink file","unsafe-file");if((r.mode&511)!==384)throw t("state file permissions must be 0600","unsafe-permissions");let o;try{o=JSON.parse(yt(e,"utf8"))}catch{throw t("state JSON is malformed","integrity-failed")}return wt(o,n,t)}function vt(e,n,t){let r=`${e}.lock`,o;try{o=ce(r,H.O_CREAT|H.O_EXCL|H.O_WRONLY,384),ze(o,`${JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()})}
3
- `,"utf8"),ae(o)}catch(i){if(o!==void 0){K(o);try{de(r)}catch{}}throw i?.code==="EEXIST"?n("state is locked by another writer","state-locked"):i}try{return t()}finally{try{K(o)}finally{de(r)}}}function qe({path:e,schemaVersion:n,fail:t}){if(typeof e!="string"||e.length<1||e.length>4096)throw t("bounded state path required","invalid-path");if(typeof t!="function")throw new TypeError("fail factory required");let r=$e(e);je(Le(r),{recursive:!0,mode:448});let o=X(r,n,t);function i(){let l={schemaVersion:n,events:o.events};o={...l,stateHash:C(l)},ht(r,o,t)}function a({tenantId:l,recordType:E,recordId:_,operation:S,occurredAt:A,record:x,expectedRecordHash:$=null}){return vt(r,t,()=>{if(o=X(r,n,t),(([...o.events].reverse().find(U=>U.record?.boundId===x?.boundId)??null)?.record?.recordHash??null)!==$)throw t("record changed concurrently; retry from current state","state-conflict");if(x&&typeof x.recordHash=="string"){let{recordHash:U,...L}=x;if(C(L)!==U)throw t("record hash is inconsistent","integrity-failed")}let D={sequence:o.events.length+1,previousEventHash:o.events.at(-1)?.eventHash??null,tenantId:l,recordType:E,recordId:_,operation:S,occurredAt:A,record:x},z=k({...D,eventHash:C(D)});return o={...o,events:[...o.events,z]},i(),z})}return Object.freeze({append:a,events:()=>(o=X(r,n,t),o.events.map(l=>structuredClone(l))),verify:()=>{try{return o=X(r,n,t),{ok:!0,count:o.events.length,stateHash:o.stateHash}}catch(l){return{ok:!1,reason:l?.code||"integrity-failed"}}},path:r})}var At=Object.freeze([/(?:^|\s)Bearer\s+\S+/i,/-----BEGIN [A-Z ]*PRIVATE KEY-----/i,/\b(?:sk-|xprv|gh[pousr]_|github_pat_|AKIA|ASIA)[A-Za-z0-9_/-]{12,}\b/i,/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/,/\b(?:0x)?[0-9a-f]{64}\b/i,/(?<![1-9A-HJ-NP-Za-km-z])[59KLc][1-9A-HJ-NP-Za-km-z]{50,51}(?![1-9A-HJ-NP-Za-km-z])/,/(?<![1-9A-HJ-NP-Za-km-z])[1-9A-HJ-NP-Za-km-z]{64,88}(?![1-9A-HJ-NP-Za-km-z])/]),gt=new Set(["apikey","key","token","accesstoken","secret","password","passwd","auth","authorization","bearer","signertoken","credential","credentials","clientsecret","privatekey","xapikey","accesskey","refreshtoken"]),St=Object.freeze(["apikey","accesskey","privatekey","clientsecret","accesstoken","refreshtoken","signertoken","credential","password","passwd","authorization","bearer","secret","token"]);function It(e){return String(e??"").replace(/[^a-z0-9]/gi,"").toLowerCase()}function Et(e){let n;try{n=new URL(e)}catch{return!1}if(n.username||n.password)return!0;for(let t of n.searchParams.keys()){let r=It(t);if(gt.has(r)||St.some(o=>r.includes(o)))return!0}return!1}function Me(e){try{let n=decodeURIComponent(e);return n===e?null:n}catch{return null}}var bt=/[a-z][a-z0-9+.-]{1,15}(?::\/\/|%3a%2f%2f)\S+/gi;function Ot(e){return e.replace(/[),.;:!?'"\]}]+$/,"")}function Nt(e){let n=e.match(bt)||[];for(let t of n){let r=Ot(t),o=Me(r),i=o?Me(o):null;for(let a of[r,o,i])if(a&&Et(a))return!0}return!1}function ue(e){return typeof e!="string"||e.length===0?!1:At.some(n=>n.test(e))?!0:Nt(e)}var _t="oracle.agent-lifecycle/1",Tt="oracle.agent-lifecycle-state/1",kt=Object.freeze(["agent","tool","workflow","credential"]),Rt=Object.freeze(["active","quarantined","retired","pending_reactivation"]),Q=Object.freeze({inactivityMs:2160*60*60*1e3,maxEvalAgeMs:720*60*60*1e3}),xt=50,Ue=100,Ye=new Set(kt),Ge=/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,127}$/,Ct=512,Pe=300*1e3,Dt=["authorization","apikey","accesskey","cookie","password","passphrase","secret","token","privatekey","seed","mnemonic","keystore","signature"],fe=class extends Error{constructor(n,t="invalid-agent-lifecycle"){super(`agent-lifecycle: ${n}`),this.name="AgentLifecycleError",this.code=t}};function f(e,n){return new fe(e,n)}function j(e,n){if(typeof e!="string")throw f(`${n} must be an ISO timestamp`,"invalid-time");let t=Date.parse(e);if(!Number.isFinite(t)||new Date(t).toISOString()!==e)throw f(`${n} must be an ISO timestamp`,"invalid-time");return e}function b(e,n){let t=String(e??"").trim();if(ue(t))throw f(`${n} contains secret-shaped material`,"secret-material");if(!Ge.test(t))throw f(`${n} is invalid`,"invalid-id");return t}function V(e,n,{required:t=!0}={}){let r=String(e??"").trim();if(t&&!r||r.length>Ct||/[\u0000-\u001f\u007f]/.test(r)||ue(r))throw f(`${n} is invalid or contains secret-shaped material`,"invalid-text");return r}function jt(e={}){if(!e||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)throw f("metadata must be a plain object","invalid-metadata");let n=Object.keys(e).sort();if(n.length>24)throw f("metadata field limit exceeded","metadata-limit");let t={};for(let r of n){if(!/^[A-Za-z][A-Za-z0-9_.-]{0,47}$/.test(r))throw f(`metadata key ${r} is invalid`,"invalid-metadata");let o=r.replace(/[^a-z0-9]/gi,"").toLowerCase();if(Dt.some(a=>o.includes(a)))throw f(`metadata key ${r} is forbidden because it may contain a secret`,"secret-material");let i=e[r];if(typeof i=="string")t[r]=V(i,`metadata.${r}`,{required:!1});else if(typeof i=="boolean"||i===null)t[r]=i;else if(typeof i=="number"&&Number.isFinite(i))t[r]=i;else throw f(`metadata.${r} must be a scalar`,"invalid-metadata")}return t}function He(e=[]){if(!Array.isArray(e)||e.length>32)throw f("credentialRefs must be a bounded array","invalid-credentials");let n=new Set;return e.map(t=>{if(!t||typeof t!="object"||Array.isArray(t))throw f("credential reference is invalid","invalid-credentials");let r=Object.keys(t).filter(i=>!["ref","expiresAt"].includes(i));if(r.length)throw f(`credential reference has unknown fields: ${r.sort().join(", ")}`,"invalid-credentials");let o=b(V(t.ref,"credential ref"),"credential ref");if(n.has(o))throw f("credential references must be unique","invalid-credentials");return n.add(o),{ref:o,expiresAt:j(t.expiresAt,"credential expiresAt")}}).sort((t,r)=>t.ref.localeCompare(r.ref))}function zt(e={}){let n=e.inactivityMs??Q.inactivityMs,t=e.maxEvalAgeMs??Q.maxEvalAgeMs;if(!Number.isSafeInteger(n)||n<1440*60*1e3||n>3660*24*60*60*1e3)throw f("policy.inactivityMs is invalid","invalid-policy");if(!Number.isSafeInteger(t)||t<1||t>3660*24*60*60*1e3)throw f("policy.maxEvalAgeMs is invalid","invalid-policy");return{inactivityMs:n,maxEvalAgeMs:t}}function Ve(e){let n=e==null||e===""?xt:Number(e);if(!Number.isSafeInteger(n)||n<1||n>Ue)throw f(`limit must be an integer from 1 to ${Ue}`,"invalid-limit");return n}function Be(e){return Buffer.from(JSON.stringify(e),"utf8").toString("base64url")}function Lt(e,n){if(typeof e!="string"||e.length<1||e.length>2048||!/^[A-Za-z0-9_-]+$/.test(e))throw f("cursor is invalid","invalid-cursor");let t;try{t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}catch{throw f("cursor is invalid","invalid-cursor")}let r=t&&typeof t=="object"&&!Array.isArray(t)?Object.keys(t).sort():[],o=["after","checkedAt","entityType","kind","sequence","status","tenantId","version"].sort();if(JSON.stringify(r)!==JSON.stringify(o)||t.version!==1||t.kind!==n.kind||t.tenantId!==n.tenantId||t.entityType!==n.entityType||t.status!==n.status||!Number.isSafeInteger(t.sequence)||t.sequence<0||t.sequence>n.headSequence||typeof t.after!="string"||!Ge.test(t.after)||Be(t)!==e)throw f("cursor does not match this lifecycle query","invalid-cursor");try{j(t.checkedAt,"cursor checkedAt")}catch{throw f("cursor is invalid","invalid-cursor")}if(Date.parse(t.checkedAt)>Date.parse(n.authorizedAt))throw f("cursor timestamp is in the future","invalid-cursor");return t}function Je(e){let n=new Map;for(let t of e)n.set(`${t.tenantId}\0${t.recordId}`,t.record);return n}function Fe(e,{at:n=new Date().toISOString(),inactivityMs:t=Q.inactivityMs,maxEvalAgeMs:r=Q.maxEvalAgeMs}={}){let o=j(n,"at"),i=Date.parse(o),a=[];if(e.latestEval&&(e.latestEval.passed===!1||e.latestEval.score<e.latestEval.threshold)&&a.push("eval-below-threshold"),e.latestEval?.passed===!0&&i-Date.parse(e.latestEval.evaluatedAt)>r&&a.push("eval-stale"),(e.credentialRefs||[]).some(E=>Date.parse(E.expiresAt)<=i)&&a.push("credential-expired"),e.entityType==="credential"&&e.expiresAt&&Date.parse(e.expiresAt)<=i&&a.push("credential-expired"),a.length)return k({status:"quarantined",reasons:a.sort(),evaluatedAt:o});let l=e.lastUsedAt??e.registeredAt;return i-Date.parse(l)>=t?k({status:"retired",reasons:["inactive"],evaluatedAt:o}):k({status:"active",reasons:[],evaluatedAt:o})}function Ze({path:e,now:n=()=>new Date().toISOString(),policy:t={}}={}){let r=zt(t),o=qe({path:e,schemaVersion:Tt,fail:f});function i(){return j(n(),"now")}function a(s,y,p=i()){return Ce({context:s,resource:"lifecycle",action:y,decidedAt:p})}function l(s,y){return Je(o.events()).get(`${s.tenantId}\0${y}`)??null}function E({context:s,kind:y,cursor:p,checkedAt:d,entityType:u=null,status:c=null}){let m=o.events(),h=m.at(-1)?.sequence??0,g=p==null?null:Lt(p,{kind:y,tenantId:s.tenantId,entityType:u,status:c,headSequence:h,authorizedAt:d}),w=g?.sequence??h,I=g?.checkedAt??d,Y=g?.after??null;return{records:[...Je(m.filter(N=>N.sequence<=w)).values()].filter(N=>N.tenantId===s.tenantId).filter(N=>u==null||N.entityType===u).sort((N,P)=>N.entityId.localeCompare(P.entityId)).filter(N=>Y==null||N.entityId.localeCompare(Y)>0),sequence:w,checkedAt:I}}function _({items:s,hasMore:y,lastEntityId:p,kind:d,context:u,entityType:c=null,status:m=null,sequence:h,checkedAt:g}){let w=y?Be({version:1,kind:d,tenantId:u.tenantId,entityType:c,status:m,sequence:h,checkedAt:g,after:p}):null;return k({items:s,nextCursor:w,sequence:h})}function S(s,y){let p=Fe(s,{at:y,...r}),d=["quarantined","retired","pending_reactivation"].includes(s.status)&&p.status==="active",u=d?s.status:p.status,c=d?[...s.reasons||[]]:[...p.reasons];return k({...structuredClone(s),status:u,reasons:c,evaluatedAt:p.evaluatedAt})}function A(s,y,p,d=i()){let u=p.recordHash??null,c={...p};delete c.recordHash;let m=k({...c,recordHash:C(c)});return o.append({tenantId:s.tenantId,recordType:"lifecycle",recordId:m.entityId,operation:y,occurredAt:d,record:m,expectedRecordHash:u}),m}function x({context:s,input:y}={}){let p=i();a(s,"create",p);let d=b(y?.entityId,"entityId");if(l(s,d))throw f("entity already exists","duplicate-entity");let u=String(y?.entityType??"").trim();if(!Ye.has(u))throw f("entityType is invalid","invalid-entity-type");let c=He(y?.credentialRefs);if(u==="credential"&&c.length)throw f("credential entities cannot contain credentialRefs","invalid-credentials");let m=u==="credential"?j(y?.expiresAt,"expiresAt"):null,h=c.some(I=>Date.parse(I.expiresAt)<=Date.parse(p))||m!=null&&Date.parse(m)<=Date.parse(p),g=b(y?.ownerActorId,"ownerActorId"),w=b(s.actor.actorId,"registering actorId");if(!s.actor.roles.includes("owner")&&g!==w)throw f("only an owner may assign lifecycle ownership to another actor","owner-assignment-required");return A(s,"register",{schemaVersion:_t,tenantId:s.tenantId,boundId:xe(s,"lifecycle",d),entityId:d,entityType:u,label:V(y?.label,"label"),ownerActorId:g,registeredBy:w,credentialRefs:c,expiresAt:m,metadata:jt(y?.metadata),status:h?"quarantined":"active",reasons:h?["credential-expired"]:[],registeredAt:p,updatedAt:p,lastUsedAt:null,latestEval:null,reactivation:null,revision:1},p)}function $({context:s,entityId:y}={}){let p=i();a(s,"read",p);let d=l(s,b(y,"entityId"));return d?S(d,p):null}function q({context:s,entityType:y=null,status:p=null,limit:d=null,cursor:u=null}={}){let c=i();if(a(s,"read",c),y!=null&&!Ye.has(y))throw f("entityType is invalid","invalid-entity-type");if(p!=null&&!Rt.includes(p))throw f("status is invalid","invalid-status");let m=Ve(d),h=E({context:s,kind:"list",cursor:u,checkedAt:c,entityType:y,status:p}),g=h.records.map(I=>S(I,h.checkedAt)).filter(I=>p==null||I.status===p),w=g.slice(0,m).map(I=>k(structuredClone(I)));return _({items:w,hasMore:g.length>m,lastEntityId:w.at(-1)?.entityId??null,kind:"list",context:s,entityType:y,status:p,sequence:h.sequence,checkedAt:h.checkedAt})}function M({context:s,entityId:y,outcome:p,occurredAt:d=null}={}){let u=i();a(s,"update",u);let c=l(s,b(y,"entityId"));if(!c)throw f("entity not found","not-found");let m=new Set(["succeeded","failed","denied","cancelled","skipped"]),h=String(p??"").trim();if(!m.has(h))throw f("usage outcome is invalid","invalid-outcome");let g=j(d??u,"occurredAt"),w=S(c,u);if(w.status!=="active")throw(w.status!==c.status||JSON.stringify(w.reasons)!==JSON.stringify(c.reasons||[]))&&A(s,"usage-denied",{...c,status:w.status,reasons:[...w.reasons],evaluatedAt:w.evaluatedAt,updatedAt:u,revision:c.revision+1},u),f(`entity is not active: ${w.status}`,"entity-not-active");if(Date.parse(g)>Date.parse(u)+Pe)throw f("occurredAt is too far in the future","future-usage");if(c.lastUsedAt&&Date.parse(g)<Date.parse(c.lastUsedAt))throw f("occurredAt must be monotonic","non-monotonic-usage");return A(s,"usage",{...c,lastUsedAt:g,lastOutcome:h,updatedAt:u,revision:c.revision+1},u)}function D({context:s,entityId:y,suite:p,score:d,threshold:u,evaluatedAt:c=null}={}){let m=i();a(s,"update",m);let h=l(s,b(y,"entityId"));if(!h)throw f("entity not found","not-found");let g=Number(d),w=Number(u);if(![g,w].every(P=>Number.isFinite(P)&&P>=0&&P<=1))throw f("eval score and threshold must be from 0 to 1","invalid-eval");let I=j(c??m,"evaluatedAt");if(Date.parse(I)>Date.parse(m)+Pe)throw f("evaluatedAt is too far in the future","future-eval");if(h.latestEval&&Date.parse(I)<Date.parse(h.latestEval.evaluatedAt))throw f("evaluatedAt must be monotonic","non-monotonic-eval");let Y={suite:b(p,"eval suite"),score:g,threshold:w,evaluatedAt:I,evaluatorActorId:b(s.actor.actorId,"evaluatorActorId"),passed:g>=w},pe={...h,latestEval:Y},N=S(pe,m);return A(s,"eval",{...h,latestEval:Y,status:N.status,reasons:[...N.reasons],evaluatedAt:N.evaluatedAt,updatedAt:m,revision:h.revision+1},m)}function z({context:s,entityId:y,refs:p}={}){let d=i();a(s,"update",d);let u=l(s,b(y,"entityId"));if(!u)throw f("entity not found","not-found");let c=S(u,d);if(c.entityType==="credential")throw f("credential entities use updateCredentialExpiry","invalid-credentials");let m=He(p),h=m.some(g=>Date.parse(g.expiresAt)<=Date.parse(d));return A(s,"credential-refs",{...c,credentialRefs:m,status:h?"quarantined":c.status,reasons:h?[...new Set([...c.reasons||[],"credential-expired"])].sort():c.reasons,updatedAt:d,revision:c.revision+1},d)}function U({context:s,entityId:y,expiresAt:p}={}){let d=i();a(s,"update",d);let u=l(s,b(y,"entityId"));if(!u)throw f("entity not found","not-found");let c=S(u,d);if(c.entityType!=="credential")throw f("entity is not a credential","invalid-entity-type");let m=j(p,"expiresAt"),h=Date.parse(m)<=Date.parse(d);return A(s,"credential-expiry",{...c,expiresAt:m,status:h?"quarantined":c.status,reasons:h?[...new Set([...c.reasons||[],"credential-expired"])].sort():c.reasons,updatedAt:d,revision:c.revision+1},d)}function L({context:s,limit:y=null,cursor:p=null}={}){let d=i();a(s,"manage",d);let u=Ve(y),c=E({context:s,kind:"sweep",cursor:p,checkedAt:d}),m=c.checkedAt,h=[],g=c.records.slice(0,u);for(let w of g){let I=S(w,m);(I.status!==w.status||JSON.stringify(I.reasons)!==JSON.stringify(w.reasons||[]))&&A(s,"sweep",{...w,status:I.status,reasons:[...I.reasons],evaluatedAt:m,updatedAt:m,revision:w.revision+1},m),h.push({entityId:w.entityId,status:I.status,reasons:[...I.reasons],evaluatedAt:m})}return _({items:h.map(w=>k(w)),hasMore:c.records.length>u,lastEntityId:g.at(-1)?.entityId??null,kind:"sweep",context:s,sequence:c.sequence,checkedAt:m})}function O({context:s,entityId:y,reason:p}={}){let d=i();a(s,"update",d);let u=l(s,b(y,"entityId"));if(!u)throw f("entity not found","not-found");let c=S(u,d);if(!["quarantined","retired"].includes(c.status))throw f("only quarantined or retired entities may request reactivation","invalid-transition");return A(s,"reactivation-requested",{...c,status:"pending_reactivation",reactivation:{requestedAt:d,requestedBy:b(s.actor.actorId,"requestedBy"),reason:V(p,"reactivation reason"),reviewedAt:null,reviewedBy:null,review:null},updatedAt:d,revision:c.revision+1},d)}function te({context:s,entityId:y,review:p}={}){let d=i();a(s,"approve",d);let u=l(s,b(y,"entityId"));if(!u)throw f("entity not found","not-found");if(u.status!=="pending_reactivation"||!u.reactivation)throw f("reactivation request is required","invalid-transition");let c=Fe(u,{at:d,...r});if(c.status!=="active")throw f(`reactivation remediation incomplete: ${c.reasons.join(", ")}`,"remediation-required");let m=d;return A(s,"reactivation-approved",{...u,status:"active",reasons:[],reactivation:{...u.reactivation,reviewedAt:m,reviewedBy:b(s.actor.actorId,"reviewedBy"),review:V(p,"reactivation review")},updatedAt:m,revision:u.revision+1},d)}return Object.freeze({register:x,get:$,list:q,recordUsage:M,recordEval:D,updateCredentialRefs:z,updateCredentialExpiry:U,sweep:L,requestReactivation:O,approveReactivation:te,verify:o.verify})}var ee=`oracle lifecycle <command> [options]
1
+ import{readFileSync as We}from"node:fs";import{homedir as $t}from"node:os";import{join as Ut}from"node:path";import{createHash as Ke}from"node:crypto";var B=1,G=1,Qe=1,ye="local-owner",me="local-owner",et=Object.freeze(["owner","operator","agent","viewer"]),tt=Object.freeze(["tenant","config","policy","grant","workflow","trade","receipt","audit","telemetry","context","lifecycle"]),ge=Object.freeze({read:"read",create:"create",update:"update",delete:"delete",manage:"manage",prepare:"prepare",cancel:"cancel",export:"export",approve:"approve"}),nt=Object.freeze(["owner"]),x=Object.freeze({ALLOW_ROLE_PERMISSION:"allow.role_permission",DENY_MISSING_CONTEXT:"deny.missing_context",DENY_INVALID_CONTEXT:"deny.invalid_context",DENY_INVALID_REQUEST:"deny.invalid_request",DENY_UNKNOWN_RESOURCE:"deny.unknown_resource",DENY_UNKNOWN_ACTION:"deny.unknown_action",DENY_UNBOUND_OBJECT:"deny.unbound_object",DENY_TENANT_MISMATCH:"deny.tenant_mismatch",DENY_RESOURCE_MISMATCH:"deny.resource_mismatch",DENY_ROLE_PERMISSION:"deny.role_permission",DENY_POLICY_NOT_APPROVER:"deny.policy_not_approver"}),Se=new Set(et),ie=new Set(tt),rt=new Set(Object.values(ge)),Ee=new Set(["user","service","local-owner"]),Ie=new Set(["verified-session","service-credential","desktop-session","owner-arm-token","local-owner"]),Z=/^[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}$/,be="tob1",Oe=new WeakSet,ot=new WeakMap,Ne=Object.freeze({owner:Object.freeze(["tenant:read","tenant:manage","config:read","config:manage","policy:read","policy:manage","grant:read","grant:create","grant:update","grant:delete","grant:manage","workflow:read","workflow:create","workflow:update","workflow:delete","workflow:cancel","workflow:approve","trade:read","trade:prepare","receipt:read","receipt:export","audit:read","audit:export","telemetry:read","telemetry:create","telemetry:export","context:read","context:create","context:update","context:delete","context:manage","context:export","lifecycle:read","lifecycle:create","lifecycle:update","lifecycle:delete","lifecycle:manage","lifecycle:approve","lifecycle:export"]),operator:Object.freeze(["tenant:read","config:read","policy:read","grant:read","workflow:read","workflow:create","workflow:update","workflow:cancel","trade:read","trade:prepare","receipt:read","audit:read","telemetry:read","telemetry:create","context:read","context:create","context:update","context:delete","lifecycle:read","lifecycle:create","lifecycle:update","lifecycle:manage"]),agent:Object.freeze(["tenant:read","config:read","policy:read","grant:read","workflow:read","workflow:create","workflow:update","trade:read","trade:prepare","receipt:read","telemetry:create","context:read","context:create","context:update","lifecycle:read"]),viewer:Object.freeze(["tenant:read","config:read","grant:read","workflow:read","trade:read","receipt:read","audit:read","telemetry:read","context:read","lifecycle:read"])}),Pt=Object.freeze(Object.fromEntries(Object.entries(Ne).map(([e,n])=>[e,Object.freeze([...n])]))),A=class extends Error{constructor(n,t="invalid-context"){super(n),this.name="TenantContextError",this.code=t}};function re(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function W(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let n of Object.values(e))W(n)}return e}function oe(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(oe).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${oe(e[n])}`).join(",")}}`}function _e(e){return Ke("sha256").update(oe(e)).digest("hex")}function he(e,n,t){if(!re(e))throw new A(`${t} must be a plain object`);let r=Object.keys(e).filter(o=>!n.has(o));if(r.length)throw new A(`${t} has unknown fields: ${r.sort().join(", ")}`)}function we(e,n){let t=String(e??"").trim();if(!Z.test(t))throw new A(`${n} is invalid`);return t}function Ae(e,n="assignedRoles"){if(!Array.isArray(e)||e.length===0)throw new A(`${n} must contain at least one trusted role`,"missing-role-assignment");let t=[...new Set(e.map(o=>String(o??"").trim()))].sort(),r=t.filter(o=>!Se.has(o));if(r.length)throw new A(`${n} contains unknown roles: ${r.join(", ")}`,"unknown-role");return t}function xe(e,n){return e.length===n.length&&e.every((t,r)=>t===n[r])}function it(e){if(!re(e)||e.schemaVersion!==B||!Z.test(e.tenantId||"")||typeof e.localCompatibility!="boolean")return!1;let n=e.actor;if(!re(n)||n.schemaVersion!==G||!Z.test(n.actorId||"")||!Ee.has(n.actorType)||!Ie.has(n.authSource)||!Array.isArray(n.roles)||n.roles.length===0)return!1;let t=[...new Set(n.roles)].sort();return t.every(r=>Se.has(r))&&xe(t,n.roles)}function st(e,{assignedTenantId:n,assignedActorId:t,assignedActorType:r,assignedAuthSource:o,assignedRoles:i,assignedContextDomains:a=null,localCompatibility:l=!1}={}){let I=e;if(he(I,new Set(["schemaVersion","tenantId","actor","localCompatibility"]),"tenant claims"),I.schemaVersion!=null&&I.schemaVersion!==B)throw new A("unsupported tenant context schema version","unsupported-version");if(![n,t,r,o].every(O=>O!=null))throw new A("trusted tenant and actor identity assignments are required","missing-trusted-identity");let v=I.actor??{};if(he(v,new Set(["schemaVersion","actorId","actorType","authSource","roles"]),"actor claims"),v.schemaVersion!=null&&v.schemaVersion!==G)throw new A("unsupported actor identity schema version","unsupported-version");let R=we(n,"tenantId"),$=we(t,"actorId"),U=String(r).trim(),q=String(o).trim();if(!Ee.has(U))throw new A("actorType is invalid");if(!Ie.has(q))throw new A("authSource is invalid");let j=Ae(i);if(!Array.isArray(a)&&a!=null)throw new A("assignedContextDomains must be an array","invalid-domain-assignment");let z=a==null?j.includes("owner")?["*"]:[]:[...new Set(a.map(O=>String(O??"").trim()))].sort();if(z.some(O=>O!=="*"&&!/^[a-z0-9][a-z0-9._-]{0,95}$/.test(O)))throw new A("assignedContextDomains contains an invalid domain","invalid-domain-assignment");if(v.roles!==void 0){let O;try{O=Ae(v.roles,"claimed roles")}catch{throw new A("claimed roles do not match the trusted assignment","forged-role")}if(!xe(O,j))throw new A("claimed roles do not match the trusted assignment","forged-role")}if(I.localCompatibility!==void 0&&I.localCompatibility!==l)throw new A("local compatibility may only be set by the trusted boundary","forged-local-compatibility");if([[I.tenantId,R],[v.actorId,$],[v.actorType,U],[v.authSource,q]].some(([O,te])=>O!==void 0&&String(O).trim()!==te))throw new A("claimed identity does not match the trusted assignment","forged-identity");let L=W({schemaVersion:B,tenantId:R,actor:{schemaVersion:G,actorId:$,actorType:U,authSource:q,roles:j},localCompatibility:l===!0});return Oe.add(L),ot.set(L,Object.freeze(z)),L}function Te({authSource:e="local-owner"}={}){if(!new Set(["local-owner","desktop-session","owner-arm-token"]).has(e))throw new A("local owner authSource is invalid");return st({schemaVersion:B,tenantId:ye,actor:{schemaVersion:G,actorId:me,actorType:"local-owner",authSource:e}},{assignedTenantId:ye,assignedActorId:me,assignedActorType:"local-owner",assignedAuthSource:e,assignedRoles:["owner"],localCompatibility:!0})}function F(e){return Oe.has(e)&&it(e)}function at(e){if(!F(e))throw new A("a resolved tenant context is required","unresolved-context");return e}function J(e){return Buffer.from(e,"utf8").toString("base64url")}function ne(e,n){if(!e||!/^[A-Za-z0-9_-]+$/.test(e))throw new A(`${n} binding is invalid`,"invalid-object-binding");let t=Buffer.from(e,"base64url").toString("utf8");if(!t||J(t)!==e)throw new A(`${n} binding is non-canonical`,"invalid-object-binding");return t}function ke(e){let n=String(e??"").trim();if(!n||n.length>256||/[\u0000-\u001f\u007f]/.test(n))throw new A("objectId is invalid","invalid-object-id");return n}function Re(e,n,t){at(e);let r=String(n??"").trim();if(!ie.has(r))throw new A("resource is unknown","unknown-resource");let o=ke(t);return`${be}.${J(e.tenantId)}.${J(r)}.${J(o)}`}function ct(e){let n=String(e??""),t=n.split(".");if(t.length!==4||t[0]!==be)throw new A("tenant-bound object id required","unbound-object");let r=ne(t[1],"tenant"),o=ne(t[2],"resource"),i=ne(t[3],"object");if(!Z.test(r)||!ie.has(o))throw new A("tenant-bound object id is invalid","invalid-object-binding");return ke(i),W({schemaVersion:1,tenantId:r,resource:o,objectId:i,boundId:n})}function dt(e){if(typeof e!="string"||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(e))return null;let n=Date.parse(e);return Number.isFinite(n)&&new Date(n).toISOString()===e?e:null}function ve(e){let n={...e,decisionId:_e(e)};return W(n)}function lt({context:e,resource:n,action:t,objectId:r=null,decidedAt:o}={}){let i=dt(o),a={schemaVersion:Qe,recordType:"tenant.access-decision",decidedAt:i,tenantId:F(e)?e.tenantId:null,actor:F(e)?{actorId:e.actor.actorId,actorType:e.actor.actorType,authSource:e.actor.authSource,roles:[...e.actor.roles]}:null,request:{resource:typeof n=="string"?n:null,action:typeof t=="string"?t:null,objectRefHash:r==null?null:_e(String(r))}},l=S=>ve({...a,allowed:!1,outcome:"deny",reason:S});if(e==null)return l(x.DENY_MISSING_CONTEXT);if(!F(e))return l(x.DENY_INVALID_CONTEXT);if(!i)return l(x.DENY_INVALID_REQUEST);if(!ie.has(n))return l(x.DENY_UNKNOWN_RESOURCE);if(!rt.has(t))return l(x.DENY_UNKNOWN_ACTION);if(r!=null){let S;try{S=ct(r)}catch{return l(x.DENY_UNBOUND_OBJECT)}if(S.tenantId!==e.tenantId)return l(x.DENY_TENANT_MISMATCH);if(S.resource!==n)return l(x.DENY_RESOURCE_MISMATCH)}if(t===ge.approve&&!e.actor.roles.some(v=>nt.includes(v)))return l(x.DENY_ROLE_PERMISSION);let I=`${n}:${t}`,_=e.actor.roles.some(S=>Ne[S]?.includes(I));return ve({...a,allowed:_,outcome:_?"allow":"deny",reason:_?x.ALLOW_ROLE_PERMISSION:x.DENY_ROLE_PERMISSION})}function Ce(e){let n=lt(e);if(!n.allowed){let t=new A(`tenant access denied: ${n.reason}`,"access-denied");throw t.decision=n,t}return n}import{createHash as ut,randomUUID as ft}from"node:crypto";import{chmodSync as pt,closeSync as K,constants as H,existsSync as se,fsyncSync as ae,lstatSync as je,mkdirSync as De,openSync as ce,readFileSync as yt,renameSync as mt,unlinkSync as de,writeFileSync as ze}from"node:fs";import{dirname as Le,resolve as $e}from"node:path";function le(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(le).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${le(e[n])}`).join(",")}}`}function C(e){return ut("sha256").update(le(e)).digest("hex")}function T(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let n of Object.values(e))T(n)}return e}function ht(e,n,t){let r=$e(e),o=Le(r);if(De(o,{recursive:!0,mode:448}),se(r)){let a=je(r);if(!a.isFile()||a.isSymbolicLink())throw t("state path must be a regular non-symlink file","unsafe-file")}let i=`${r}.${ft()}.tmp`;try{ze(i,`${JSON.stringify(n)}
2
+ `,{encoding:"utf8",mode:384,flag:"wx"});let a=ce(i,H.O_RDONLY);try{ae(a)}finally{K(a)}mt(i,r),pt(r,384);let l;try{l=ce(o,H.O_RDONLY),ae(l)}finally{l!==void 0&&K(l)}}catch(a){try{se(i)&&de(i)}catch{}throw a}}function wt(e,n,t){if(!e||typeof e!="object"||Array.isArray(e))throw t("state must be an object","integrity-failed");if(e.schemaVersion!==n||!Array.isArray(e.events))throw t("state schema is invalid","integrity-failed");let r=null;for(let a=0;a<e.events.length;a+=1){let l=e.events[a];if(!l||typeof l!="object"||Array.isArray(l))throw t("event is invalid","integrity-failed");if(l.record&&typeof l.record.recordHash=="string"){let{recordHash:S,...v}=l.record;if(C(v)!==S)throw t("record hash integrity failed; state may be tampered","integrity-failed")}let{eventHash:I,..._}=l;if(l.sequence!==a+1||l.previousEventHash!==r||C(_)!==I)throw t("event hash chain integrity failed; state may be tampered","integrity-failed");r=I}let{stateHash:o,...i}=e;if(C(i)!==o)throw t("state hash integrity failed; state may be tampered","integrity-failed");return e}function X(e,n,t){if(!se(e)){let i={schemaVersion:n,events:[]};return{...i,stateHash:C(i)}}let r=je(e);if(!r.isFile()||r.isSymbolicLink())throw t("state path must be a regular non-symlink file","unsafe-file");if((r.mode&511)!==384)throw t("state file permissions must be 0600","unsafe-permissions");let o;try{o=JSON.parse(yt(e,"utf8"))}catch{throw t("state JSON is malformed","integrity-failed")}return wt(o,n,t)}function At(e,n,t){let r=`${e}.lock`,o;try{o=ce(r,H.O_CREAT|H.O_EXCL|H.O_WRONLY,384),ze(o,`${JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()})}
3
+ `,"utf8"),ae(o)}catch(i){if(o!==void 0){K(o);try{de(r)}catch{}}throw i?.code==="EEXIST"?n("state is locked by another writer","state-locked"):i}try{return t()}finally{try{K(o)}finally{de(r)}}}function Ue({path:e,schemaVersion:n,fail:t}){if(typeof e!="string"||e.length<1||e.length>4096)throw t("bounded state path required","invalid-path");if(typeof t!="function")throw new TypeError("fail factory required");let r=$e(e);De(Le(r),{recursive:!0,mode:448});let o=X(r,n,t);function i(){let l={schemaVersion:n,events:o.events};o={...l,stateHash:C(l)},ht(r,o,t)}function a({tenantId:l,recordType:I,recordId:_,operation:S,occurredAt:v,record:R,expectedRecordHash:$=null}){return At(r,t,()=>{if(o=X(r,n,t),(([...o.events].reverse().find(M=>M.record?.boundId===R?.boundId)??null)?.record?.recordHash??null)!==$)throw t("record changed concurrently; retry from current state","state-conflict");if(R&&typeof R.recordHash=="string"){let{recordHash:M,...L}=R;if(C(L)!==M)throw t("record hash is inconsistent","integrity-failed")}let j={sequence:o.events.length+1,previousEventHash:o.events.at(-1)?.eventHash??null,tenantId:l,recordType:I,recordId:_,operation:S,occurredAt:v,record:R},z=T({...j,eventHash:C(j)});return o={...o,events:[...o.events,z]},i(),z})}return Object.freeze({append:a,events:()=>(o=X(r,n,t),o.events.map(l=>structuredClone(l))),verify:()=>{try{return o=X(r,n,t),{ok:!0,count:o.events.length,stateHash:o.stateHash}}catch(l){return{ok:!1,reason:l?.code||"integrity-failed"}}},path:r})}var vt=Object.freeze([/(?:^|\s)Bearer\s+\S+/i,/-----BEGIN [A-Z ]*PRIVATE KEY-----/i,/\b(?:sk-|xprv|gh[pousr]_|github_pat_|AKIA|ASIA)[A-Za-z0-9_/-]{12,}\b/i,/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/,/\b(?:0x)?[0-9a-f]{64}\b/i,/(?<![1-9A-HJ-NP-Za-km-z])[59KLc][1-9A-HJ-NP-Za-km-z]{50,51}(?![1-9A-HJ-NP-Za-km-z])/,/(?<![1-9A-HJ-NP-Za-km-z])[1-9A-HJ-NP-Za-km-z]{64,88}(?![1-9A-HJ-NP-Za-km-z])/]),gt=new Set(["apikey","key","token","accesstoken","secret","password","passwd","auth","authorization","bearer","signertoken","credential","credentials","clientsecret","privatekey","xapikey","accesskey","refreshtoken"]),St=Object.freeze(["apikey","accesskey","privatekey","clientsecret","accesstoken","refreshtoken","signertoken","credential","password","passwd","authorization","bearer","secret","token"]);function Et(e){return String(e??"").replace(/[^a-z0-9]/gi,"").toLowerCase()}function It(e){let n;try{n=new URL(e)}catch{return!1}if(n.username||n.password)return!0;for(let t of n.searchParams.keys()){let r=Et(t);if(gt.has(r)||St.some(o=>r.includes(o)))return!0}return!1}function qe(e){try{let n=decodeURIComponent(e);return n===e?null:n}catch{return null}}var bt=/[a-z][a-z0-9+.-]{1,15}(?::\/\/|%3a%2f%2f)\S+/gi;function Ot(e){return e.replace(/[),.;:!?'"\]}]+$/,"")}function Nt(e){let n=e.match(bt)||[];for(let t of n){let r=Ot(t),o=qe(r),i=o?qe(o):null;for(let a of[r,o,i])if(a&&It(a))return!0}return!1}var Bt=Object.freeze([Object.freeze([120,112,114,118]),Object.freeze([115,107,45]),Object.freeze([103,104,112,95]),Object.freeze([103,104,111,95]),Object.freeze([103,104,117,95]),Object.freeze([103,104,115,95]),Object.freeze([103,104,114,95]),Object.freeze([103,105,116,104,117,98,95,112,97,116,95]),Object.freeze([97,107,105,97]),Object.freeze([97,115,105,97])]);function ue(e){return typeof e!="string"||e.length===0?!1:vt.some(n=>n.test(e))?!0:Nt(e)}var _t="oracle.agent-lifecycle/1",xt="oracle.agent-lifecycle-state/1",Tt=Object.freeze(["agent","tool","workflow","credential"]),kt=Object.freeze(["active","quarantined","retired","pending_reactivation"]),Q=Object.freeze({inactivityMs:2160*60*60*1e3,maxEvalAgeMs:720*60*60*1e3}),Rt=50,Me=100,Pe=new Set(Tt),Be=/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,127}$/,Ct=512,Ye=300*1e3,jt=["authorization","apikey","accesskey","cookie","password","passphrase","secret","token","privatekey","seed","mnemonic","keystore","signature"],fe=class extends Error{constructor(n,t="invalid-agent-lifecycle"){super(`agent-lifecycle: ${n}`),this.name="AgentLifecycleError",this.code=t}};function f(e,n){return new fe(e,n)}function D(e,n){if(typeof e!="string")throw f(`${n} must be an ISO timestamp`,"invalid-time");let t=Date.parse(e);if(!Number.isFinite(t)||new Date(t).toISOString()!==e)throw f(`${n} must be an ISO timestamp`,"invalid-time");return e}function b(e,n){let t=String(e??"").trim();if(ue(t))throw f(`${n} contains secret-shaped material`,"secret-material");if(!Be.test(t))throw f(`${n} is invalid`,"invalid-id");return t}function V(e,n,{required:t=!0}={}){let r=String(e??"").trim();if(t&&!r||r.length>Ct||/[\u0000-\u001f\u007f]/.test(r)||ue(r))throw f(`${n} is invalid or contains secret-shaped material`,"invalid-text");return r}function Dt(e={}){if(!e||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)throw f("metadata must be a plain object","invalid-metadata");let n=Object.keys(e).sort();if(n.length>24)throw f("metadata field limit exceeded","metadata-limit");let t={};for(let r of n){if(!/^[A-Za-z][A-Za-z0-9_.-]{0,47}$/.test(r))throw f(`metadata key ${r} is invalid`,"invalid-metadata");let o=r.replace(/[^a-z0-9]/gi,"").toLowerCase();if(jt.some(a=>o.includes(a)))throw f(`metadata key ${r} is forbidden because it may contain a secret`,"secret-material");let i=e[r];if(typeof i=="string")t[r]=V(i,`metadata.${r}`,{required:!1});else if(typeof i=="boolean"||i===null)t[r]=i;else if(typeof i=="number"&&Number.isFinite(i))t[r]=i;else throw f(`metadata.${r} must be a scalar`,"invalid-metadata")}return t}function He(e=[]){if(!Array.isArray(e)||e.length>32)throw f("credentialRefs must be a bounded array","invalid-credentials");let n=new Set;return e.map(t=>{if(!t||typeof t!="object"||Array.isArray(t))throw f("credential reference is invalid","invalid-credentials");let r=Object.keys(t).filter(i=>!["ref","expiresAt"].includes(i));if(r.length)throw f(`credential reference has unknown fields: ${r.sort().join(", ")}`,"invalid-credentials");let o=b(V(t.ref,"credential ref"),"credential ref");if(n.has(o))throw f("credential references must be unique","invalid-credentials");return n.add(o),{ref:o,expiresAt:D(t.expiresAt,"credential expiresAt")}}).sort((t,r)=>t.ref.localeCompare(r.ref))}function zt(e={}){let n=e.inactivityMs??Q.inactivityMs,t=e.maxEvalAgeMs??Q.maxEvalAgeMs;if(!Number.isSafeInteger(n)||n<1440*60*1e3||n>3660*24*60*60*1e3)throw f("policy.inactivityMs is invalid","invalid-policy");if(!Number.isSafeInteger(t)||t<1||t>3660*24*60*60*1e3)throw f("policy.maxEvalAgeMs is invalid","invalid-policy");return{inactivityMs:n,maxEvalAgeMs:t}}function Ve(e){let n=e==null||e===""?Rt:Number(e);if(!Number.isSafeInteger(n)||n<1||n>Me)throw f(`limit must be an integer from 1 to ${Me}`,"invalid-limit");return n}function Ge(e){return Buffer.from(JSON.stringify(e),"utf8").toString("base64url")}function Lt(e,n){if(typeof e!="string"||e.length<1||e.length>2048||!/^[A-Za-z0-9_-]+$/.test(e))throw f("cursor is invalid","invalid-cursor");let t;try{t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}catch{throw f("cursor is invalid","invalid-cursor")}let r=t&&typeof t=="object"&&!Array.isArray(t)?Object.keys(t).sort():[],o=["after","checkedAt","entityType","kind","sequence","status","tenantId","version"].sort();if(JSON.stringify(r)!==JSON.stringify(o)||t.version!==1||t.kind!==n.kind||t.tenantId!==n.tenantId||t.entityType!==n.entityType||t.status!==n.status||!Number.isSafeInteger(t.sequence)||t.sequence<0||t.sequence>n.headSequence||typeof t.after!="string"||!Be.test(t.after)||Ge(t)!==e)throw f("cursor does not match this lifecycle query","invalid-cursor");try{D(t.checkedAt,"cursor checkedAt")}catch{throw f("cursor is invalid","invalid-cursor")}if(Date.parse(t.checkedAt)>Date.parse(n.authorizedAt))throw f("cursor timestamp is in the future","invalid-cursor");return t}function Fe(e){let n=new Map;for(let t of e)n.set(`${t.tenantId}\0${t.recordId}`,t.record);return n}function Je(e,{at:n=new Date().toISOString(),inactivityMs:t=Q.inactivityMs,maxEvalAgeMs:r=Q.maxEvalAgeMs}={}){let o=D(n,"at"),i=Date.parse(o),a=[];if(e.latestEval&&(e.latestEval.passed===!1||e.latestEval.score<e.latestEval.threshold)&&a.push("eval-below-threshold"),e.latestEval?.passed===!0&&i-Date.parse(e.latestEval.evaluatedAt)>r&&a.push("eval-stale"),(e.credentialRefs||[]).some(I=>Date.parse(I.expiresAt)<=i)&&a.push("credential-expired"),e.entityType==="credential"&&e.expiresAt&&Date.parse(e.expiresAt)<=i&&a.push("credential-expired"),a.length)return T({status:"quarantined",reasons:a.sort(),evaluatedAt:o});let l=e.lastUsedAt??e.registeredAt;return i-Date.parse(l)>=t?T({status:"retired",reasons:["inactive"],evaluatedAt:o}):T({status:"active",reasons:[],evaluatedAt:o})}function Ze({path:e,now:n=()=>new Date().toISOString(),policy:t={}}={}){let r=zt(t),o=Ue({path:e,schemaVersion:xt,fail:f});function i(){return D(n(),"now")}function a(s,y,p=i()){return Ce({context:s,resource:"lifecycle",action:y,decidedAt:p})}function l(s,y){return Fe(o.events()).get(`${s.tenantId}\0${y}`)??null}function I({context:s,kind:y,cursor:p,checkedAt:d,entityType:u=null,status:c=null}){let m=o.events(),h=m.at(-1)?.sequence??0,g=p==null?null:Lt(p,{kind:y,tenantId:s.tenantId,entityType:u,status:c,headSequence:h,authorizedAt:d}),w=g?.sequence??h,E=g?.checkedAt??d,P=g?.after??null;return{records:[...Fe(m.filter(N=>N.sequence<=w)).values()].filter(N=>N.tenantId===s.tenantId).filter(N=>u==null||N.entityType===u).sort((N,Y)=>N.entityId.localeCompare(Y.entityId)).filter(N=>P==null||N.entityId.localeCompare(P)>0),sequence:w,checkedAt:E}}function _({items:s,hasMore:y,lastEntityId:p,kind:d,context:u,entityType:c=null,status:m=null,sequence:h,checkedAt:g}){let w=y?Ge({version:1,kind:d,tenantId:u.tenantId,entityType:c,status:m,sequence:h,checkedAt:g,after:p}):null;return T({items:s,nextCursor:w,sequence:h})}function S(s,y){let p=Je(s,{at:y,...r}),d=["quarantined","retired","pending_reactivation"].includes(s.status)&&p.status==="active",u=d?s.status:p.status,c=d?[...s.reasons||[]]:[...p.reasons];return T({...structuredClone(s),status:u,reasons:c,evaluatedAt:p.evaluatedAt})}function v(s,y,p,d=i()){let u=p.recordHash??null,c={...p};delete c.recordHash;let m=T({...c,recordHash:C(c)});return o.append({tenantId:s.tenantId,recordType:"lifecycle",recordId:m.entityId,operation:y,occurredAt:d,record:m,expectedRecordHash:u}),m}function R({context:s,input:y}={}){let p=i();a(s,"create",p);let d=b(y?.entityId,"entityId");if(l(s,d))throw f("entity already exists","duplicate-entity");let u=String(y?.entityType??"").trim();if(!Pe.has(u))throw f("entityType is invalid","invalid-entity-type");let c=He(y?.credentialRefs);if(u==="credential"&&c.length)throw f("credential entities cannot contain credentialRefs","invalid-credentials");let m=u==="credential"?D(y?.expiresAt,"expiresAt"):null,h=c.some(E=>Date.parse(E.expiresAt)<=Date.parse(p))||m!=null&&Date.parse(m)<=Date.parse(p),g=b(y?.ownerActorId,"ownerActorId"),w=b(s.actor.actorId,"registering actorId");if(!s.actor.roles.includes("owner")&&g!==w)throw f("only an owner may assign lifecycle ownership to another actor","owner-assignment-required");return v(s,"register",{schemaVersion:_t,tenantId:s.tenantId,boundId:Re(s,"lifecycle",d),entityId:d,entityType:u,label:V(y?.label,"label"),ownerActorId:g,registeredBy:w,credentialRefs:c,expiresAt:m,metadata:Dt(y?.metadata),status:h?"quarantined":"active",reasons:h?["credential-expired"]:[],registeredAt:p,updatedAt:p,lastUsedAt:null,latestEval:null,reactivation:null,revision:1},p)}function $({context:s,entityId:y}={}){let p=i();a(s,"read",p);let d=l(s,b(y,"entityId"));return d?S(d,p):null}function U({context:s,entityType:y=null,status:p=null,limit:d=null,cursor:u=null}={}){let c=i();if(a(s,"read",c),y!=null&&!Pe.has(y))throw f("entityType is invalid","invalid-entity-type");if(p!=null&&!kt.includes(p))throw f("status is invalid","invalid-status");let m=Ve(d),h=I({context:s,kind:"list",cursor:u,checkedAt:c,entityType:y,status:p}),g=h.records.map(E=>S(E,h.checkedAt)).filter(E=>p==null||E.status===p),w=g.slice(0,m).map(E=>T(structuredClone(E)));return _({items:w,hasMore:g.length>m,lastEntityId:w.at(-1)?.entityId??null,kind:"list",context:s,entityType:y,status:p,sequence:h.sequence,checkedAt:h.checkedAt})}function q({context:s,entityId:y,outcome:p,occurredAt:d=null}={}){let u=i();a(s,"update",u);let c=l(s,b(y,"entityId"));if(!c)throw f("entity not found","not-found");let m=new Set(["succeeded","failed","denied","cancelled","skipped"]),h=String(p??"").trim();if(!m.has(h))throw f("usage outcome is invalid","invalid-outcome");let g=D(d??u,"occurredAt"),w=S(c,u);if(w.status!=="active")throw(w.status!==c.status||JSON.stringify(w.reasons)!==JSON.stringify(c.reasons||[]))&&v(s,"usage-denied",{...c,status:w.status,reasons:[...w.reasons],evaluatedAt:w.evaluatedAt,updatedAt:u,revision:c.revision+1},u),f(`entity is not active: ${w.status}`,"entity-not-active");if(Date.parse(g)>Date.parse(u)+Ye)throw f("occurredAt is too far in the future","future-usage");if(c.lastUsedAt&&Date.parse(g)<Date.parse(c.lastUsedAt))throw f("occurredAt must be monotonic","non-monotonic-usage");return v(s,"usage",{...c,lastUsedAt:g,lastOutcome:h,updatedAt:u,revision:c.revision+1},u)}function j({context:s,entityId:y,suite:p,score:d,threshold:u,evaluatedAt:c=null}={}){let m=i();a(s,"update",m);let h=l(s,b(y,"entityId"));if(!h)throw f("entity not found","not-found");let g=Number(d),w=Number(u);if(![g,w].every(Y=>Number.isFinite(Y)&&Y>=0&&Y<=1))throw f("eval score and threshold must be from 0 to 1","invalid-eval");let E=D(c??m,"evaluatedAt");if(Date.parse(E)>Date.parse(m)+Ye)throw f("evaluatedAt is too far in the future","future-eval");if(h.latestEval&&Date.parse(E)<Date.parse(h.latestEval.evaluatedAt))throw f("evaluatedAt must be monotonic","non-monotonic-eval");let P={suite:b(p,"eval suite"),score:g,threshold:w,evaluatedAt:E,evaluatorActorId:b(s.actor.actorId,"evaluatorActorId"),passed:g>=w},pe={...h,latestEval:P},N=S(pe,m);return v(s,"eval",{...h,latestEval:P,status:N.status,reasons:[...N.reasons],evaluatedAt:N.evaluatedAt,updatedAt:m,revision:h.revision+1},m)}function z({context:s,entityId:y,refs:p}={}){let d=i();a(s,"update",d);let u=l(s,b(y,"entityId"));if(!u)throw f("entity not found","not-found");let c=S(u,d);if(c.entityType==="credential")throw f("credential entities use updateCredentialExpiry","invalid-credentials");let m=He(p),h=m.some(g=>Date.parse(g.expiresAt)<=Date.parse(d));return v(s,"credential-refs",{...c,credentialRefs:m,status:h?"quarantined":c.status,reasons:h?[...new Set([...c.reasons||[],"credential-expired"])].sort():c.reasons,updatedAt:d,revision:c.revision+1},d)}function M({context:s,entityId:y,expiresAt:p}={}){let d=i();a(s,"update",d);let u=l(s,b(y,"entityId"));if(!u)throw f("entity not found","not-found");let c=S(u,d);if(c.entityType!=="credential")throw f("entity is not a credential","invalid-entity-type");let m=D(p,"expiresAt"),h=Date.parse(m)<=Date.parse(d);return v(s,"credential-expiry",{...c,expiresAt:m,status:h?"quarantined":c.status,reasons:h?[...new Set([...c.reasons||[],"credential-expired"])].sort():c.reasons,updatedAt:d,revision:c.revision+1},d)}function L({context:s,limit:y=null,cursor:p=null}={}){let d=i();a(s,"manage",d);let u=Ve(y),c=I({context:s,kind:"sweep",cursor:p,checkedAt:d}),m=c.checkedAt,h=[],g=c.records.slice(0,u);for(let w of g){let E=S(w,m);(E.status!==w.status||JSON.stringify(E.reasons)!==JSON.stringify(w.reasons||[]))&&v(s,"sweep",{...w,status:E.status,reasons:[...E.reasons],evaluatedAt:m,updatedAt:m,revision:w.revision+1},m),h.push({entityId:w.entityId,status:E.status,reasons:[...E.reasons],evaluatedAt:m})}return _({items:h.map(w=>T(w)),hasMore:c.records.length>u,lastEntityId:g.at(-1)?.entityId??null,kind:"sweep",context:s,sequence:c.sequence,checkedAt:m})}function O({context:s,entityId:y,reason:p}={}){let d=i();a(s,"update",d);let u=l(s,b(y,"entityId"));if(!u)throw f("entity not found","not-found");let c=S(u,d);if(!["quarantined","retired"].includes(c.status))throw f("only quarantined or retired entities may request reactivation","invalid-transition");return v(s,"reactivation-requested",{...c,status:"pending_reactivation",reactivation:{requestedAt:d,requestedBy:b(s.actor.actorId,"requestedBy"),reason:V(p,"reactivation reason"),reviewedAt:null,reviewedBy:null,review:null},updatedAt:d,revision:c.revision+1},d)}function te({context:s,entityId:y,review:p}={}){let d=i();a(s,"approve",d);let u=l(s,b(y,"entityId"));if(!u)throw f("entity not found","not-found");if(u.status!=="pending_reactivation"||!u.reactivation)throw f("reactivation request is required","invalid-transition");let c=Je(u,{at:d,...r});if(c.status!=="active")throw f(`reactivation remediation incomplete: ${c.reasons.join(", ")}`,"remediation-required");let m=d;return v(s,"reactivation-approved",{...u,status:"active",reasons:[],reactivation:{...u.reactivation,reviewedAt:m,reviewedBy:b(s.actor.actorId,"reviewedBy"),review:V(p,"reactivation review")},updatedAt:m,revision:u.revision+1},d)}return Object.freeze({register:R,get:$,list:U,recordUsage:q,recordEval:j,updateCredentialRefs:z,updateCredentialExpiry:M,sweep:L,requestReactivation:O,approveReactivation:te,verify:o.verify})}var ee=`oracle lifecycle <command> [options]
4
4
  register <input.json|->
5
5
  get --id ID
6
6
  list [--type agent|tool|workflow|credential] [--status STATUS] [--limit N] [--cursor CURSOR]
@@ -12,6 +12,6 @@ import{readFileSync as We}from"node:fs";import{homedir as $t}from"node:os";impor
12
12
  reactivate-request --id ID --reason TEXT
13
13
  reactivate-approve --id ID --review TEXT
14
14
  verify
15
- Options: --store PATH --inactivity-days N --limit N --cursor CURSOR`;function Mt(e){let n=[],t={},r=new Set(["store","id","type","status","outcome","occurred-at","suite","score","threshold","evaluated-at","expires-at","reason","review","inactivity-days","limit","cursor"]);for(let o=0;o<e.length;o+=1){let i=e[o];if(!i.startsWith("--")){n.push(i);continue}let a=i.slice(2);if(!r.has(a)||e[o+1]==null)throw new TypeError(ee);t[a]=e[++o]}return{positionals:n,options:t}}function Xe(e){let n=e==="-"?We(0,"utf8"):We(e,"utf8");return JSON.parse(n)}function R(e){process.stdout.write(`${JSON.stringify(e,null,2)}
16
- `)}var rn={name:"lifecycle",summary:"inventory and govern agent, tool, workflow, and credential lifecycles",group:"system",usage:ee,async run(e){let{positionals:n,options:t}=Mt(e.argv??[]),r=n[0];if(!r||["help","--help","-h"].includes(r))return process.stdout.write(`${ee}
17
- `),0;let o=t["inactivity-days"]==null?90:Number(t["inactivity-days"]),i=Ze({path:t.store||qt($t(),".config","oracle","agent-lifecycle.json"),policy:{inactivityMs:o*24*60*60*1e3}}),a=ke();if(r==="register")R(i.register({context:a,input:Xe(n[1])}));else if(r==="get")R(i.get({context:a,entityId:t.id}));else if(r==="list")R(i.list({context:a,entityType:t.type||null,status:t.status||null,limit:t.limit==null?void 0:Number(t.limit),cursor:t.cursor}));else if(r==="usage")R(i.recordUsage({context:a,entityId:t.id,outcome:t.outcome,occurredAt:t["occurred-at"]}));else if(r==="eval")R(i.recordEval({context:a,entityId:t.id,suite:t.suite,score:Number(t.score),threshold:Number(t.threshold),evaluatedAt:t["evaluated-at"]}));else if(r==="credentials")R(i.updateCredentialRefs({context:a,entityId:t.id,refs:Xe(n[1])}));else if(r==="credential-expiry")R(i.updateCredentialExpiry({context:a,entityId:t.id,expiresAt:t["expires-at"]}));else if(r==="sweep")R(i.sweep({context:a,limit:t.limit==null?void 0:Number(t.limit),cursor:t.cursor}));else if(r==="reactivate-request")R(i.requestReactivation({context:a,entityId:t.id,reason:t.reason}));else if(r==="reactivate-approve")R(i.approveReactivation({context:a,entityId:t.id,review:t.review}));else if(r==="verify")R(i.verify());else throw new TypeError(ee);return 0}};export{rn as default};
15
+ Options: --store PATH --inactivity-days N --limit N --cursor CURSOR`;function qt(e){let n=[],t={},r=new Set(["store","id","type","status","outcome","occurred-at","suite","score","threshold","evaluated-at","expires-at","reason","review","inactivity-days","limit","cursor"]);for(let o=0;o<e.length;o+=1){let i=e[o];if(!i.startsWith("--")){n.push(i);continue}let a=i.slice(2);if(!r.has(a)||e[o+1]==null)throw new TypeError(ee);t[a]=e[++o]}return{positionals:n,options:t}}function Xe(e){let n=e==="-"?We(0,"utf8"):We(e,"utf8");return JSON.parse(n)}function k(e){process.stdout.write(`${JSON.stringify(e,null,2)}
16
+ `)}var on={name:"lifecycle",summary:"inventory and govern agent, tool, workflow, and credential lifecycles",group:"system",usage:ee,async run(e){let{positionals:n,options:t}=qt(e.argv??[]),r=n[0];if(!r||["help","--help","-h"].includes(r))return process.stdout.write(`${ee}
17
+ `),0;let o=t["inactivity-days"]==null?90:Number(t["inactivity-days"]),i=Ze({path:t.store||Ut($t(),".config","oracle","agent-lifecycle.json"),policy:{inactivityMs:o*24*60*60*1e3}}),a=Te();if(r==="register")k(i.register({context:a,input:Xe(n[1])}));else if(r==="get")k(i.get({context:a,entityId:t.id}));else if(r==="list")k(i.list({context:a,entityType:t.type||null,status:t.status||null,limit:t.limit==null?void 0:Number(t.limit),cursor:t.cursor}));else if(r==="usage")k(i.recordUsage({context:a,entityId:t.id,outcome:t.outcome,occurredAt:t["occurred-at"]}));else if(r==="eval")k(i.recordEval({context:a,entityId:t.id,suite:t.suite,score:Number(t.score),threshold:Number(t.threshold),evaluatedAt:t["evaluated-at"]}));else if(r==="credentials")k(i.updateCredentialRefs({context:a,entityId:t.id,refs:Xe(n[1])}));else if(r==="credential-expiry")k(i.updateCredentialExpiry({context:a,entityId:t.id,expiresAt:t["expires-at"]}));else if(r==="sweep")k(i.sweep({context:a,limit:t.limit==null?void 0:Number(t.limit),cursor:t.cursor}));else if(r==="reactivate-request")k(i.requestReactivation({context:a,entityId:t.id,reason:t.reason}));else if(r==="reactivate-approve")k(i.approveReactivation({context:a,entityId:t.id,review:t.review}));else if(r==="verify")k(i.verify());else throw new TypeError(ee);return 0}};export{on as default};