@oracle-agent/oracle 0.16.0 → 0.18.0

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.
@@ -1,45 +1,45 @@
1
- var jn=Object.defineProperty;var ft=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Mn=(e,t)=>{for(var n in t)jn(e,n,{get:t[n],enumerable:!0})};import Fn from"node:fs";import Un from"node:os";import V from"node:path";import{fileURLToPath as Dn}from"node:url";function ie(){return process.env.ORACLE_FAKE_HOME||Un.homedir()}function Kn(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function z(){return Kn()?process.env.ORACLE_CONFIG_DIR||V.join(ie(),".config","oracle"):V.join(ie(),".config","oracle")}function F(){return process.env.HERMES_HOME?V.resolve(process.env.HERMES_HOME):V.join(ie(),".hermes")}function R(e){return Fn.mkdirSync(e,{recursive:!0}),e}var Bn,M,Y=ft(()=>{Bn=V.dirname(Dn(import.meta.url)),M=V.resolve(Bn,"../..")});var _n={};Mn(_n,{createOAuthStore:()=>ot,default:()=>ko,getOAuthStore:()=>ne,hasOAuthCredentials:()=>yn,loginOAuth:()=>xn,oauthProviderConfig:()=>rt,oauthProviderId:()=>K,oauthRuntimeConfig:()=>bn,refreshOAuthCredentials:()=>it,resolveOAuthCredentials:()=>gn});import{createHash as lo,randomBytes as tt,timingSafeEqual as fo}from"node:crypto";import j from"node:fs";import ee from"node:path";import po from"node:readline/promises";import{spawn as mo,spawnSync as ho}from"node:child_process";function nt(e={}){return typeof e.now=="function"?Number(e.now()):Date.now()}function K(e){let t=String(e||"").trim().toLowerCase();for(let[n,r]of Object.entries(te))if(r.aliases.includes(t))return n;throw new Error(`unsupported OAuth provider: ${e||"(empty)"}`)}function rt(e){let t=K(e);return{id:t,...te[t]}}function P(e,t={}){if(!j.existsSync(e))return t;try{let n=JSON.parse(j.readFileSync(e,"utf8"));if(!n||typeof n!="object"||Array.isArray(n))throw new Error("invalid object");return n}catch{throw new Error(`credential store is unreadable or corrupt: ${ee.basename(e)}`)}}function hn(e){R(e),process.platform!=="win32"&&j.chmodSync(e,448)}function W(e,t){hn(ee.dirname(e));let n=`${e}.${process.pid}.${tt(4).toString("hex")}.tmp`;j.writeFileSync(n,`${JSON.stringify(t,null,2)}
2
- `,{mode:384}),j.renameSync(n,e),process.platform!=="win32"&&j.chmodSync(e,384)}function xo(e){if(process.platform!=="linux")return!1;let t=e("secret-tool",["--version"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return!t.error&&t.status===0}function Ze(e){let t=String(e||"").trim().toLowerCase();if(!/^[a-z0-9][a-z0-9._-]*$/.test(t))throw new Error(`invalid API-key provider: ${e||"(empty)"}`);return t}function ue(e={}){let t=String(e.accessToken||e.access_token||"").trim(),n=String(e.refreshToken||e.refresh_token||"").trim(),r=Number(e.expiresAt||e.expires_at||0);if(!t)throw new Error("OAuth credential is missing access token");return{accessToken:t,refreshToken:n,expiresAt:Number.isFinite(r)?r:0,tokenType:String(e.tokenType||e.token_type||"Bearer"),source:String(e.source||"oracle"),...e.discovery?{discovery:e.discovery}:{},...e.scope?{scope:e.scope}:{},...e.idToken||e.id_token?{idToken:String(e.idToken||e.id_token)}:{}}}function ot(e={}){let t=e.file||ee.join(z(),"oauth.json"),n=e.metadataFile||ee.join(ee.dirname(t),"oauth-meta.json"),r=e.spawnFn||ho,o=e.keychain!==!1&&process.env.ORACLE_AUTH_FILE_STORE!=="1"&&xo(r),i=o?"linux-secret-service":"private-file",c=`${t}.lock`;async function a(b){hn(ee.dirname(c));let m;for(let h=0;h<400;h+=1)try{m=j.openSync(c,"wx",384);break}catch(l){if(l?.code!=="EEXIST")throw l;try{Date.now()-j.statSync(c).mtimeMs>3e5&&j.unlinkSync(c)}catch{}await new Promise(f=>setTimeout(f,25))}if(m===void 0)throw new Error("timed out waiting for OAuth credential lock");try{return await b()}finally{try{j.closeSync(m)}catch{}try{j.unlinkSync(c)}catch{}}}function u(b,m="oauth"){return["application","oracle","kind",m,"provider",b]}function s(b){let m=K(b);if(o){let f=r("secret-tool",["lookup",...u(m)],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(f.error||f.status!==0||!String(f.stdout||"").trim())return null;try{return ue(JSON.parse(String(f.stdout).trim()))}catch{return null}}let l=P(t,{providers:{}}).providers?.[m];if(!l)return null;try{return ue(l)}catch{return null}}function d(b,m){let h=K(b),l=ue(m);if(o){let w=r("secret-tool",["store",`--label=Oracle ${h} OAuth`,...u(h)],{input:JSON.stringify(l),encoding:"utf8",stdio:["pipe","ignore","pipe"]});if(w.error||w.status!==0)throw new Error("OS credential store rejected OAuth credential");let O=P(n,{providers:{}});return O.providers||={},O.providers[h]={expiresAt:l.expiresAt,source:l.source},W(n,O),l}let f=P(t,{providers:{}});return f.providers||={},f.providers[h]=l,W(t,f),l}function p(b){let m=K(b);if(o){let f=r("secret-tool",["clear",...u(m)],{encoding:"utf8",stdio:["ignore","ignore","pipe"]}),w=P(n,{providers:{}});return w.providers&&delete w.providers[m],W(n,w),!f.error&&f.status===0}let h=P(t,{providers:{}}),l=!!h.providers?.[m];return h.providers&&delete h.providers[m],W(t,h),l}function y(b){let m=Ze(b);if(o){let h=r("secret-tool",["lookup",...u(m,"api-key")],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return h.error||h.status!==0?"":String(h.stdout||"").trim()}return String(P(t,{apiKeys:{}}).apiKeys?.[m]||"").trim()}function x(b,m){let h=Ze(b),l=String(m||"").trim();if(!l)throw new Error("API key is empty");if(o){let w=r("secret-tool",["store",`--label=Oracle ${h} API key`,...u(h,"api-key")],{input:l,encoding:"utf8",stdio:["pipe","ignore","pipe"]});if(w.error||w.status!==0)throw new Error("OS credential store rejected API key");let O=P(n,{providers:{},apiKeys:{}});return O.apiKeys||={},O.apiKeys[h]={configured:!0},W(n,O),!0}let f=P(t,{providers:{},apiKeys:{}});return f.apiKeys||={},f.apiKeys[h]=l,W(t,f),!0}function _(b){let m=Ze(b);if(o){let f=r("secret-tool",["clear",...u(m,"api-key")],{encoding:"utf8",stdio:["ignore","ignore","pipe"]}),w=P(n,{providers:{},apiKeys:{}});return w.apiKeys&&delete w.apiKeys[m],W(n,w),!f.error&&f.status===0}let h=P(t,{providers:{},apiKeys:{}}),l=!!h.apiKeys?.[m];return h.apiKeys&&delete h.apiKeys[m],W(t,h),l}function v(){let b={},m={};if(o){let h=P(n,{providers:{},apiKeys:{}});for(let[l,f]of Object.entries(h.providers||{}))b[l]={loggedIn:!!s(l),expiresAt:Number(f.expiresAt||0),source:String(f.source||"oracle"),storage:i};for(let l of Object.keys(h.apiKeys||{}))m[l]={configured:!!y(l),storage:i}}else{let h=P(t,{providers:{},apiKeys:{}});for(let[l,f]of Object.entries(h.providers||{}))b[l]={loggedIn:!!f?.accessToken,expiresAt:Number(f?.expiresAt||0),source:String(f?.source||"oracle"),storage:i};for(let[l,f]of Object.entries(h.apiKeys||{}))m[l]={configured:!!f,storage:i}}return{storage:i,providers:b,apiKeys:m}}return Object.freeze({file:t,storage:i,get:s,set:d,remove:p,getApiKey:y,setApiKey:x,removeApiKey:_,status:v,withLock:a})}function ne(){return mn||=ot(),mn}function et(e){return Buffer.from(e).toString("base64url")}function go(){let e=et(tt(32));return{verifier:e,challenge:et(lo("sha256").update(e).digest()),state:et(tt(24))}}function yo(e,t){let n=Buffer.from(String(e||"")),r=Buffer.from(String(t||""));return n.length===r.length&&fo(n,r)}function bo(e){let t=String(e),n=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd.exe",["/d","/s","/c","start","",t]]:["xdg-open",[t]];try{return mo(n[0],n[1],{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function ke(e){return new URLSearchParams(e).toString()}async function H(e,t){if(!e?.ok){let r="";try{r=String((await e.json())?.error||"")}catch{}throw new Error(`${t} failed (HTTP ${e?.status||"unknown"}${r?`, ${r}`:""})`)}let n=await e.json();if(!n||typeof n!="object")throw new Error(`${t} returned invalid JSON`);return n}async function _o(e){if(e)return String(await e()).trim();let t=po.createInterface({input:process.stdin,output:process.stdout});try{return String(await t.question("Authorization code: ")).trim()}finally{t.close()}}function Ee(e,t={}){let n=String(e.access_token||"").trim(),r=String(e.refresh_token||t.refreshToken||"").trim();if(!n)throw new Error("OAuth token response is missing access token");let o=Number(e.expires_in||3600);return ue({accessToken:n,refreshToken:r,expiresAt:nt(t)+Math.max(1,o)*1e3,tokenType:e.token_type||"Bearer",idToken:e.id_token,source:"oracle",...t.discovery?{discovery:t.discovery}:{},...e.scope?{scope:e.scope}:{}})}async function wo(e){let t=te["anthropic-oauth"],n=e.pkce||go(),r=new URLSearchParams({code:"true",client_id:t.clientId,response_type:"code",redirect_uri:t.redirectUri,scope:t.scope,code_challenge:n.challenge,code_challenge_method:"S256",state:n.state}),o=`${t.authorizeUrl}?${r}`;e.output(`Open: ${o}`),e.openFn(o);let i=await _o(e.inputFn),[c,a]=i.split("#",2);if(!c||!yo(a,n.state))throw new Error("Claude OAuth state mismatch");let u=await e.fetchFn(t.tokenUrl,{method:"POST",headers:{"content-type":"application/json","user-agent":"axios/1.7.9"},body:JSON.stringify({grant_type:"authorization_code",client_id:t.clientId,code:c,state:a,redirect_uri:t.redirectUri,code_verifier:n.verifier})});return Ee(await H(u,"Claude OAuth token exchange"),e)}async function vo(e){let t=te["openai-codex"],n=await H(await e.fetchFn(`${t.issuer}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({client_id:t.clientId})}),"Codex device authorization");if(!n.user_code||!n.device_auth_id)throw new Error("Codex device authorization returned incomplete data");let r=`${t.issuer}/codex/device`;e.output(`Open: ${r}`),e.output(`Code: ${n.user_code}`),e.openFn(r);let o=Math.max(3,Number(n.interval||5)),i;for(let a=0;a<Math.ceil(900/o);a+=1){await e.sleepFn(o*1e3);let u=await e.fetchFn(`${t.issuer}/api/accounts/deviceauth/token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({device_auth_id:n.device_auth_id,user_code:n.user_code})});if(u.ok){i=await H(u,"Codex device authorization");break}if(![403,404].includes(u.status))throw new Error(`Codex device authorization failed (HTTP ${u.status})`)}if(!i)throw new Error("Codex device authorization timed out");let c=await e.fetchFn(t.tokenUrl,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:ke({grant_type:"authorization_code",code:i.authorization_code,redirect_uri:`${t.issuer}/deviceauth/callback`,client_id:t.clientId,code_verifier:i.code_verifier})});return Ee(await H(c,"Codex OAuth token exchange"),e)}function G(e){let t=new URL(String(e)),n=t.hostname.toLowerCase();if(t.protocol!=="https:"||n!=="x.ai"&&!n.endsWith(".x.ai"))throw new Error("xAI OAuth discovery returned an untrusted endpoint");return t.toString()}async function So(e){let t=te["xai-oauth"],n=await H(await e.fetchFn(t.discoveryUrl,{headers:{accept:"application/json"}}),"xAI OAuth discovery");G(n.authorization_endpoint);let r=G(n.token_endpoint),o=await H(await e.fetchFn(t.deviceUrl,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:ke({client_id:t.clientId,scope:t.scope})}),"xAI device authorization");if(!o.device_code||!o.user_code||!o.verification_uri)throw new Error("xAI device authorization returned incomplete data");let i=G(o.verification_uri_complete||o.verification_uri);e.output(`Open: ${i}`),e.output(`Code: ${o.user_code}`),e.openFn(i);let c=Math.max(1,Number(o.interval||5)),a=Math.ceil(Math.max(1,Number(o.expires_in||600))/c);for(let u=0;u<a;u+=1){let s=await e.fetchFn(r,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:ke({grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:t.clientId,device_code:o.device_code})});if(s.ok){let p=await H(s,"xAI OAuth token exchange");return Ee(p,{...e,discovery:{authorization_endpoint:G(n.authorization_endpoint),token_endpoint:r}})}let d="";try{d=String((await s.json())?.error||"")}catch{}if(d==="slow_down")await e.sleepFn((c+1)*1e3);else if(d==="authorization_pending")await e.sleepFn(c*1e3);else throw new Error(`xAI OAuth token exchange failed (HTTP ${s.status}${d?`, ${d}`:""})`)}throw new Error("xAI device authorization timed out")}async function xn(e,t={}){let n=K(e),r={fetchFn:t.fetchFn||globalThis.fetch,inputFn:t.inputFn,sleepFn:t.sleepFn||(o=>new Promise(i=>setTimeout(i,o))),openFn:t.openFn||bo,output:t.output||(o=>process.stdout.write(`${o}
3
- `)),now:t.now,pkce:t.pkce};return n==="anthropic-oauth"?wo(r):n==="openai-codex"?vo(r):So(r)}async function it(e,t,n={}){let r=K(e),o=te[r],i=ue(t);if(!i.refreshToken)throw new Error(`${r} OAuth credential cannot refresh; run oracle auth login`);let c=i.discovery,a,u=n.fetchFn||globalThis.fetch;if(r==="xai-oauth"){if(!c?.token_endpoint){let p=await u(o.discoveryUrl),y=await H(p,"xAI OAuth discovery");c={...y.authorization_endpoint?{authorization_endpoint:G(y.authorization_endpoint)}:{},token_endpoint:G(y.token_endpoint)}}a=G(c.token_endpoint)}else a=o.tokenUrl;let s=await u(a,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json",...r==="anthropic-oauth"?{"user-agent":"axios/1.7.9"}:{}},body:ke({grant_type:"refresh_token",refresh_token:i.refreshToken,client_id:o.clientId})}),d=await H(s,`${r} OAuth refresh`);return Ee(d,{...n,refreshToken:i.refreshToken,discovery:c})}async function gn(e,t={}){let n=K(e),r=t.store||ne(),o=r.get(n);if(!o)throw new Error(`${n} OAuth is not logged in; run oracle auth login ${e}`);let i=nt(t);if(!o.expiresAt||o.expiresAt>i+pn)return o;let c=async()=>{let a=r.get(n);if(!a)throw new Error(`${n} OAuth is not logged in; run oracle auth login ${e}`);let u=nt(t);if(!a.expiresAt||a.expiresAt>u+pn)return a;let s=await it(n,a,t);return r.set(n,s),s};return typeof r.withLock=="function"?r.withLock(c):c()}function yn(e,t={}){try{return!!(t.store||ne()).get(e)?.accessToken}catch{return!1}}function bn(e){let t=rt(e);return{kind:"standalone",provider:t.id,model:t.model,baseUrl:t.baseUrl,authType:"oauth",protocol:t.protocol}}var te,pn,mn,ko,st=ft(()=>{Y();te=Object.freeze({"anthropic-oauth":{aliases:["anthropic-oauth","anthropic","claude","claude-oauth"],clientId:"9d1c250a-e61b-44d9-88ed-5944d1962f5e",authorizeUrl:"https://claude.ai/oauth/authorize",tokenUrl:"https://platform.claude.com/v1/oauth/token",redirectUri:"https://console.anthropic.com/oauth/code/callback",scope:"org:create_api_key user:profile user:inference",baseUrl:"https://api.anthropic.com/v1",model:"claude-sonnet-4-6",protocol:"anthropic-messages"},"openai-codex":{aliases:["openai-codex","openai-oauth","codex","codex-oauth"],clientId:"app_EMoamEEZ73f0CkXaXp7hrann",issuer:"https://auth.openai.com",tokenUrl:"https://auth.openai.com/oauth/token",baseUrl:"https://chatgpt.com/backend-api/codex",model:"gpt-5.6-sol",protocol:"responses"},"xai-oauth":{aliases:["xai-oauth","xai","grok","grok-oauth"],clientId:"b1a00492-073a-47ea-816f-4c329264a828",issuer:"https://auth.x.ai",discoveryUrl:"https://auth.x.ai/.well-known/openid-configuration",deviceUrl:"https://auth.x.ai/oauth2/device/code",scope:"openid profile email offline_access grok-cli:access api:access",baseUrl:"https://api.x.ai/v1",model:"grok-4.5",protocol:"responses"}}),pn=12e4;ko={createOAuthStore:ot,getOAuthStore:ne,hasOAuthCredentials:yn,loginOAuth:xn,oauthProviderConfig:rt,oauthProviderId:K,oauthRuntimeConfig:bn,refreshOAuthCredentials:it,resolveOAuthCredentials:gn}});Y();import A from"node:fs";import S from"node:path";import{spawnSync as Vo}from"node:child_process";import pt from"node:fs";import qn from"node:path";var Hn=Object.freeze([{key:"hyperliquid",aliases:["hl","hyperevm","hype","999"],chainId:999,name:"hyperliquid",kind:"evm",family:"hyperliquid",agent:"hyperliquid-agent",note:"perps \xB7 hip-3/4 \xB7 hyperevm 999",build:!0},{key:"ethereum",aliases:["eth","mainnet","1"],chainId:1,name:"ethereum",kind:"evm",family:"evm",agent:"oracle",note:"l1 \xB7 bridge hub",build:!0},{key:"base",aliases:["8453"],chainId:8453,name:"base",kind:"evm",family:"evm",agent:"oracle",note:"evm l2",build:!0},{key:"arbitrum",aliases:["arb","42161"],chainId:42161,name:"arbitrum",kind:"evm",family:"evm",agent:"oracle",note:"evm l2",build:!0},{key:"optimism",aliases:["op","10"],chainId:10,name:"optimism",kind:"evm",family:"evm",agent:"oracle",note:"op mainnet",build:!0},{key:"polygon",aliases:["matic","137"],chainId:137,name:"polygon",kind:"evm",family:"evm",agent:"oracle",note:"evm l2",build:!0},{key:"bsc",aliases:["bnb","56"],chainId:56,name:"bnb chain",kind:"evm",family:"evm",agent:"oracle",note:"bsc",build:!0},{key:"avalanche",aliases:["avax","43114"],chainId:43114,name:"avalanche",kind:"evm",family:"evm",agent:"oracle",note:"c-chain",build:!0},{key:"abstract",aliases:["abs","2741"],chainId:2741,name:"abstract",kind:"evm",family:"evm",agent:"oracle",note:"open / add agent",build:!0},{key:"stable",aliases:["988"],chainId:988,name:"stable",kind:"evm",family:"stable",agent:"stable-agent",note:"usdt0 gas \xB7 stable agent",build:!0},{key:"robinhood",aliases:["rh","4663"],chainId:4663,name:"robinhood",kind:"evm",family:"robinhood",agent:"robinhood-agent",note:"rh chain 4663",build:!0},{key:"solana",aliases:["sol"],chainId:"SOL",name:"solana",kind:"svm",family:"solana",agent:"solana-agent",note:"jup \xB7 nfts \xB7 dexs",build:!0},{key:"bitcoin",aliases:["btc"],chainId:"BTC",name:"bitcoin",kind:"utxo",family:"bitcoin",agent:"bitcoin-agent",note:"ord \xB7 runes \xB7 l1",build:!0},{key:"polymarket",aliases:["poly","polygon-poly"],chainId:137,name:"polymarket",kind:"venue",family:"polymarket",agent:"polymarket-agent",note:"prediction markets (polygon venue)",build:!1}]);function Oe(e){return String(e||"").trim().toLowerCase().replace(/^\/+/,"").replace(/\s+/g,"-")}function dt(e){let t=Oe(e);if(!t)return null;for(let n of Hn)if(n.key===t||String(n.chainId).toLowerCase()===t||(n.aliases||[]).map(Oe).includes(t)||Oe(n.name)===t)return n;return null}Y();function zn(){return qn.join(z(),"active-chain.json")}function Wn(){let e=zn();if(!pt.existsSync(e))return null;try{let t=JSON.parse(pt.readFileSync(e,"utf8"));if(!t||typeof t!="object"||!t.key)return null;let n=dt(t.key);return n?{key:n.key,chainId:n.chainId,name:n.name,agent:n.agent,selectedAt:t.selectedAt||null}:null}catch{return null}}function pe(e={}){let t=Wn(),n={...process.env,...e};return t&&(n.ORACLE_ACTIVE_CHAIN=t.key,n.ORACLE_ACTIVE_CHAIN_ID=String(t.chainId),n.ORACLE_ACTIVE_AGENT=t.agent||"oracle"),n}Y();import mt from"node:fs";import Yn from"node:path";var Gn=new Set(["auto","standalone","hermes","remote","arch"]),Jn=new Set(["openrouter","openai","xai","deepseek","gemini","custom","anthropic-oauth","openai-codex","xai-oauth"]);function Vn(){return Yn.join(z(),"model.json")}function U(e){return String(e||"").trim()||void 0}function Xn(e={}){let t=U(e.backend)?.toLowerCase()||"auto",n=U(e.provider)?.toLowerCase(),r=U(e.model),o=U(e.baseUrl)?.replace(/\/+$/,""),i=U(e.apiKeyEnv),c=Number.parseInt(String(e.contextLength||""),10),a=U(e.reasoningEffort),u=U(e.computeHost||e.remoteHost),s=U(e.computeUser||e.remoteUser),d=U(e.computePath||e.remotePath);if(!Gn.has(t))throw new Error(`unsupported backend: ${t}`);if(process.env.ORACLE_PUBLIC_DESKTOP==="1"&&["remote","arch"].includes(t))throw new Error("remote compute backends are disabled in the public desktop");if(n&&!Jn.has(n))throw new Error(`unsupported provider: ${n}`);if(o&&n!=="custom")throw new Error("baseUrl is only supported for the custom provider");if(i&&!/^[A-Z][A-Z0-9_]*$/.test(i))throw new Error("api key env must be an uppercase environment variable name");if(n==="custom"&&!o)throw new Error("custom provider requires baseUrl");if(t==="standalone"&&!r)throw new Error("standalone backend requires a model");if(t==="remote"&&!u)throw new Error("remote backend requires computeHost");return{backend:t,...n?{provider:n}:{},...r?{model:r}:{},...o?{baseUrl:o}:{},...i?{apiKeyEnv:i}:{},...Number.isFinite(c)&&c>0?{contextLength:c}:{},...a?{reasoningEffort:a}:{},...u?{computeHost:u}:{},...s?{computeUser:s}:{},...d?{computePath:d}:{}}}function ht(){let e=Vn();if(!mt.existsSync(e))return null;try{return Xn(JSON.parse(mt.readFileSync(e,"utf8")))}catch{return null}}import{spawn as Qn}from"node:child_process";var Zn=["SIGINT","SIGTERM","SIGHUP"];function me(e,t=[],n={},r=e){return new Promise(o=>{let i=Qn(e,t,n),c=!1,a=null,u=new Map(Zn.map(d=>[d,()=>{a||=d,i.exitCode===null&&i.signalCode===null&&i.kill(d)}]));for(let[d,p]of u)process.on(d,p);let s=()=>{for(let[d,p]of u)process.off(d,p)};i.once("error",d=>{c||(c=!0,s(),process.stderr.write(`oracle: could not start ${r}: ${d.message}
4
- `),o(1))}),i.once("exit",(d,p)=>{if(c)return;c=!0,s();let y=a||p;if(y){process.kill(process.pid,y);return}o(d??1)})})}import gt from"node:fs";import X from"node:path";Y();var er="0.19.0",Ri=`hermes-agent==${er}`;var xt="0.12.1",Pi=Object.freeze({posix:Object.freeze({url:`https://github.com/astral-sh/uv/releases/download/${xt}/uv-installer.sh`,sha256:"d3f5412d38c99f9d024901843bf98206f0d2c6dbe64df40d0b740e2751ca62c1"}),windows:Object.freeze({url:`https://github.com/astral-sh/uv/releases/download/${xt}/uv-installer.ps1`,sha256:"b9ec035151bfbb11d616dbd69886498d885551489eddf095ea3c0ad59f640eb0"})});function tr(){return X.join(z(),"runtime")}function nr(){return X.join(tr(),"venv")}function rr(e){let t=process.platform==="win32"?"Scripts":"bin",n=process.platform==="win32"?`${e}.exe`:e;return X.join(nr(),t,n)}function or(){return rr("hermes")}function ir(e){let t=process.platform==="win32"&&!X.extname(e)?["",".exe",".cmd",".bat"]:[""];for(let n of(process.env.PATH||"").split(X.delimiter))if(n)for(let r of t){let o=X.join(n,`${e}${r}`);try{if(gt.existsSync(o))return o}catch{}}return null}function Ce(){if(process.env.ORACLE_HERMES_BIN)return{ok:!0,bin:process.env.ORACLE_HERMES_BIN,source:"env"};let e=ir("hermes");if(e)return{ok:!0,bin:e,source:"path"};let t=or();return gt.existsSync(t)?{ok:!0,bin:t,source:"managed"}:{ok:!1,bin:null,source:null}}import{EventEmitter as Fr}from"node:events";import{spawn as sr}from"node:child_process";import{EventEmitter as cr}from"node:events";import{createInterface as yt}from"node:readline";var ar=15e3,ur=12e4;function lr(e){let t=typeof e=="string"?e:e?.message||"Gateway request failed",n=new Error(t);return n.error=e,n}function fr(e){let t=Buffer.from(e);if(t.length<=4096)return e;let n=t.length-4096;return`${t.subarray(0,4096).toString("utf8")} ... [truncated ${n} bytes]`}function bt({python:e,pythonArgs:t=[],cwd:n,env:r,spawnFn:o=sr,startupTimeoutMs:i=ar,requestTimeoutMs:c=ur}={}){let a=new cr,u=new Map,s=null,d=1,p=null,y=null,x=!1;function _(f){a.listenerCount("error")>0&&a.emit("error",f)}function v(f){for(let w of u.values())clearTimeout(w.timer),w.reject(f);u.clear()}function b(f){if(!("id"in f)){a.emit("event",f);return}let w=u.get(f.id);w&&(u.delete(f.id),clearTimeout(w.timer),"error"in f?w.reject(lr(f.error)):w.resolve(f.result))}function m(){return p||(p=new Promise((f,w)=>{let O=!1,k,g=C=>{O||(O=!0,clearTimeout(k),C?w(C):f())};try{s=o(e,[...t,"-m","tui_gateway.entry"],{cwd:n,env:r})}catch(C){g(C),_(C);return}let I=yt({input:s.stdout}),q=yt({input:s.stderr});I.on("line",C=>{let N;try{N=JSON.parse(C)}catch{a.emit("log",C);return}g(),b(N)}),q.on("line",C=>a.emit("log",fr(C))),s.once("error",C=>{g(C),v(C),_(C)}),s.once("exit",(C,N)=>{x=!0;let re=new Error(`Gateway exited with code ${C} and signal ${N}`);g(re),v(re),a.emit("exit",{code:C,signal:N})}),k=setTimeout(()=>{g(new Error(`Gateway startup timed out after ${i} ms`))},i)}),p)}function h(f,w){if(!s||x)return Promise.reject(new Error("Gateway is not running"));let O=d++;return new Promise((k,g)=>{let I=setTimeout(()=>{u.delete(O),g(new Error(`Gateway request ${O} timed out after ${c} ms`))},c);u.set(O,{resolve:k,reject:g,timer:I});try{s.stdin.write(`${JSON.stringify({id:O,method:f,params:w})}
5
- `)}catch(q){clearTimeout(I),u.delete(O),g(q)}})}function l(){if(y)return y;if(!s||x)return Promise.resolve();let f=new Error("Gateway stopped while requests were pending");return v(f),y=new Promise(w=>{s.once("exit",w);try{s.kill()}catch{w()}}),y}return{start:m,request:h,stop:l,on(f,w){return a.on(f,w),this},off(f,w){return a.off(f,w),this}}}var se=Buffer.alloc(0),dr=new Set(["return","backspace","tab","escape","up","down","left","right","home","end","delete","insert","pageup","pagedown","unknown"]),pr={A:"up",B:"down",C:"right",D:"left",H:"home",F:"end",P:"f1",Q:"f2",R:"f3",S:"f4"},mr={1:"home",2:"insert",3:"delete",4:"end",5:"pageup",6:"pagedown",7:"home",8:"end"};function $({name:e=null,ctrl:t=!1,meta:n=!1,shift:r=!1,sequence:o=""}){return{name:e,ctrl:t,meta:n,shift:r,sequence:o}}function St(e){return e<128?1:e>=240?4:e>=224?3:e>=192?2:1}function hr(e){return e>=64&&e<=126}function _t(e){let t=e.toLowerCase();return $({name:t,shift:e!==t,sequence:e})}function xr(e){return e===13?$({name:"return",sequence:"\r"}):e===10?$({name:"return",sequence:`
6
- `}):e===9?$({name:"tab",sequence:" "}):e===127?$({name:"backspace",sequence:"\x7F"}):e===8?$({name:"backspace",sequence:"\b"}):e>=1&&e<=26?$({name:String.fromCharCode(e+96),ctrl:!0,sequence:String.fromCharCode(e)}):$({name:"unknown",sequence:String.fromCharCode(e)})}function gr(e){let t=/^\u001b[\[O](\d*)(?:;(\d+))?(.)$/s.exec(e);if(!t)return $({name:"unknown",sequence:e});let n=t[1]===""?null:Number(t[1]),r=t[2]===void 0?null:Number(t[2]),o=t[3],i=null,c=r;if(o==="~"?i=mr[n]??null:(i=pr[o]??null,c===null&&n!==null&&n>1&&(c=n)),!i)return $({name:"unknown",sequence:e});let a=c===null?0:Math.max(0,c-1);return $({name:i,shift:(a&1)!==0,meta:(a&2)!==0,ctrl:(a&4)!==0,sequence:e})}function yr(e,t,n,r){let o=()=>(n.push($({name:"escape",sequence:"\x1B"})),1);if(t+1>=e.length)return r?o():0;let i=e[t+1];if(i===91||i===79){let s=t+2;for(;s<e.length&&!hr(e[s]);)s+=1;return s>=e.length?r?o():0:(n.push(gr(e.toString("utf8",t,s+1))),s+1-t)}if(i===27)return o();let c=St(i);if(t+1+c>e.length)return r?o():0;let a=e.toString("utf8",t+1,t+1+c),u=a.toLowerCase();return n.push($({name:u,meta:!0,shift:a!==u,sequence:`\x1B${a}`})),1+c}function wt(e,t){let n=[],r=0;for(;r<e.length;){let o=e[r];if(o===27){let c=yr(e,r,n,t);if(c===0)return{keys:n,rest:Buffer.from(e.subarray(r))};r+=c;continue}if(o<32||o===127){n.push(xr(o)),r+=1;continue}let i=St(o);if(r+i>e.length)return t?(n.push(_t(e.toString("utf8",r))),{keys:n,rest:se}):{keys:n,rest:Buffer.from(e.subarray(r))};n.push(_t(e.toString("utf8",r,r+i))),r+=i}return{keys:n,rest:se}}function vt(e){return Buffer.isBuffer(e)?e:e==null?se:typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}function br(){let e=se;return{push(t){let n=e.length===0?vt(t):Buffer.concat([e,vt(t)]),{keys:r,rest:o}=wt(n,!1);return e=o,r},flush(){if(e.length===0)return[];let{keys:t}=wt(e,!0);return e=se,t},get pending(){return e.length}}}function _r({history:e=[]}={}){let t=[...e];return{buffer:"",cursor:0,history:t,historyIndex:t.length,draft:""}}function Ie(e,t){if(t<=0)return 0;let n=t-1,r=e.charCodeAt(n);if(r>=56320&&r<=57343&&n>0){let o=e.charCodeAt(n-1);if(o>=55296&&o<=56319)return n-1}return n}function Le(e,t){if(t>=e.length)return e.length;let n=e.charCodeAt(t);return n>=55296&&n<=56319&&t+1<e.length?t+2:t+1}function E(e,t){return{...e,...t}}function kt(e,t){return E(e,{...t,historyIndex:e.history.length,draft:""})}function wr(e){if(e.ctrl||e.meta||!e.sequence||dr.has(e.name))return!1;for(let t of e.sequence){let n=t.codePointAt(0);if(n<32||n===127)return!1}return!0}function vr(e,t){let n=t;for(;n>0&&/\s/.test(e[n-1]);)n-=1;for(;n>0&&!/\s/.test(e[n-1]);)n-=1;return n}function Sr(e){if(e.historyIndex<=0)return{state:E(e,{}),action:null};let t=e.historyIndex>=e.history.length,n=e.historyIndex-1,r=e.history[n]??"";return{state:E(e,{buffer:r,cursor:r.length,historyIndex:n,draft:t?e.buffer:e.draft}),action:null}}function kr(e){if(e.historyIndex>=e.history.length)return{state:E(e,{}),action:null};let t=e.historyIndex+1,n=t>=e.history.length,r=n?e.draft:e.history[t]??"";return{state:E(e,{buffer:r,cursor:r.length,historyIndex:t,draft:n?"":e.draft}),action:null}}function Er(e){let t=e.buffer.trim();if(t==="")return{state:kt(e,{buffer:"",cursor:0}),action:null};let n=e.history[e.history.length-1]===t?[...e.history]:[...e.history,t];return{state:E(e,{buffer:"",cursor:0,history:n,historyIndex:n.length,draft:""}),action:{type:"submit",value:t}}}function Ar(e,t){if(!t)return{state:E(e,{}),action:null};let{buffer:n,cursor:r}=e;if(t.ctrl&&!t.meta)switch(t.name){case"c":return{state:kt(e,{buffer:"",cursor:0}),action:{type:"cancel"}};case"d":return n===""?{state:E(e,{}),action:{type:"eof"}}:{state:E(e,{}),action:null};case"l":return{state:E(e,{}),action:{type:"clear"}};case"a":return{state:E(e,{cursor:0}),action:null};case"e":return{state:E(e,{cursor:n.length}),action:null};case"u":return{state:E(e,{buffer:n.slice(r),cursor:0}),action:null};case"k":return{state:E(e,{buffer:n.slice(0,r)}),action:null};case"w":{let o=vr(n,r);return{state:E(e,{buffer:n.slice(0,o)+n.slice(r),cursor:o}),action:null}}case"b":return{state:E(e,{cursor:Ie(n,r)}),action:null};case"f":return{state:E(e,{cursor:Le(n,r)}),action:null};default:return{state:E(e,{}),action:null}}switch(t.name){case"return":return Er(e);case"left":return{state:E(e,{cursor:Ie(n,r)}),action:null};case"right":return{state:E(e,{cursor:Le(n,r)}),action:null};case"home":return{state:E(e,{cursor:0}),action:null};case"end":return{state:E(e,{cursor:n.length}),action:null};case"up":return Sr(e);case"down":return kr(e);case"backspace":{if(r===0)return{state:E(e,{}),action:null};let o=Ie(n,r);return{state:E(e,{buffer:n.slice(0,o)+n.slice(r),cursor:o}),action:null}}case"delete":{if(r>=n.length)return{state:E(e,{}),action:null};let o=Le(n,r);return{state:E(e,{buffer:n.slice(0,r)+n.slice(o)}),action:null}}default:break}if(wr(t)){let o=t.sequence;return{state:E(e,{buffer:n.slice(0,r)+o+n.slice(r),cursor:r+o.length}),action:null}}return{state:E(e,{}),action:null}}function Et(e={}){let{stdin:t,stdout:n,history:r=[],onSubmit:o,onCancel:i,onEof:c,onClear:a,onRender:u}=e,s=t??process.stdin,d=n??process.stdout,p=br(),y={submit:o,cancel:i,eof:c,clear:a},x=_r({history:r}),_=!1,v=!1,b=!1,m=l=>{if(!l)return;let f=y[l.type];typeof f=="function"&&f(l.value,x)},h=l=>{for(let f of p.push(l)){let w=Ar(x,f);x=w.state,m(w.action),typeof u=="function"&&u(x)}};return{start(){_||(_=!0,s.isTTY&&typeof s.setRawMode=="function"&&(b=s.isRaw===!0,s.setRawMode(!0),v=!0),typeof s.resume=="function"&&s.resume(),s.on("data",h),typeof u=="function"&&u(x))},stop(){_&&(_=!1,typeof s.off=="function"?s.off("data",h):typeof s.removeListener=="function"&&s.removeListener("data",h),v&&typeof s.setRawMode=="function"&&(s.setRawMode(b),v=!1),typeof s.pause=="function"&&s.pause())},getState(){return x},setState(l){return x=l,x},write(l){d&&typeof d.write=="function"&&d.write(l)},get isRunning(){return _}}}var Te="\x1B[?25l",he="\x1B[?25h",At="\x1B[2K",xe="\x1B[0J";var Or="\x1B\\[[0-9;?]*[a-zA-Z]";function It(){return new RegExp(Or,"g")}function Cr(e){return String(e??"").replace(It(),"")}function Ot(e,t){return t.some(([n,r])=>e>=n&&e<=r)}function Lt(e){return e===0||e<32||e>=127&&e<160||Ot(e,[[768,879],[1155,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1552,1562],[1611,1631],[1648,1648],[1750,1757],[1759,1764],[1767,1768],[1770,1773],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2070,2073],[2075,2083],[2085,2087],[2089,2093],[2137,2139],[2259,2273],[2275,2307],[2362,2364],[2369,2376],[2381,2381],[2385,2391],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2641,2641],[2672,2673],[2677,2677],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2884],[2893,2893],[2902,2902],[2914,2915],[2946,2946],[3008,3008],[3021,3021],[3072,3072],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3170,3171],[3201,3201],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3329,3329],[3393,3396],[3405,3405],[3426,3427],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3981,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4151],[4153,4154],[4157,4158],[4184,4185],[4190,4192],[4209,4212],[4226,4226],[4229,4230],[4237,4237],[4253,4253],[4957,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6277,6278],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6683,6683],[6742,6742],[6744,6750],[6752,6752],[6754,6754],[6757,6764],[6771,6780],[6783,6783],[6832,6911],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7040,7041],[7074,7077],[7080,7081],[7083,7085],[7142,7142],[7144,7145],[7149,7149],[7151,7153],[7212,7219],[7222,7223],[7376,7378],[7380,7392],[7394,7400],[7405,7405],[7412,7412],[7416,7417],[7616,7679],[8203,8207],[8234,8238],[8288,8292],[8294,8303],[8400,8447],[65024,65039],[65056,65071],[917760,917999]])?0:Ot(e,[[4352,4447],[8986,8987],[9001,9002],[9193,9196],[9200,9200],[9203,9203],[9725,9726],[9748,9749],[9800,9811],[9855,9855],[9875,9875],[9889,9889],[9898,9899],[9917,9918],[9924,9925],[9934,9934],[9940,9940],[9962,9962],[9970,9971],[9973,9973],[9978,9978],[9981,9981],[9989,9989],[9994,9995],[10024,10024],[10060,10060],[10062,10062],[10067,10069],[10071,10071],[10133,10135],[10160,10160],[10175,10175],[11035,11036],[11088,11088],[11093,11093],[11904,12350],[12352,42191],[44032,55203],[63744,64255],[65040,65049],[65072,65135],[65280,65376],[65504,65510],[127744,128591],[129280,129535],[131072,262141]])?2:1}function Ir(e){let t=0;for(let n of Array.from(e))t+=Lt(n.codePointAt(0));return t}function Lr(e){return Ir(Cr(e))}function Tr(e){return/^\u001b\[0*m$/.test(e)}function Ct(e,t){let n="",r=0;for(let o of Array.from(e)){let i=Lt(o.codePointAt(0));if(r+i>t)break;n+=o,r+=i}return{text:n,width:r}}function $r(e,t){let n=String(e??"");if(t<=0)return"";if(Lr(n)<=t)return n;let r=It(),o="",i=0,c=!1,a=0,u=r.exec(n);for(;u!==null;){let d=Ct(n.slice(a,u.index),t-i);if(o+=d.text,i+=d.width,i>=t)return c?`${o}\x1B[0m`:o;o+=u[0],u[0].endsWith("m")&&(c=!Tr(u[0])),a=u.index+u[0].length,u=r.exec(n)}let s=Ct(n.slice(a),t-i);return o+=s.text,c?`${o}\x1B[0m`:o}function Rr(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function Tt({stdout:e,rows:t,columns:n}={}){if(!e||typeof e.write!="function")throw new TypeError("createRenderer requires a stdout with a write(string) method");let r=Number.isFinite(t)?Math.trunc(t):null,o=Number.isFinite(n)?Math.trunc(n):null,i=r??(Number.isFinite(e.rows)?Math.trunc(e.rows):24),c=o??(Number.isFinite(e.columns)?Math.trunc(e.columns):80),a=[],u=0,s=null,d=!1,p=!1,y=()=>{r===null&&(i=Number.isFinite(e.rows)?Math.trunc(e.rows):24),o===null&&(c=Number.isFinite(e.columns)?Math.trunc(e.columns):80),d=!0},x=typeof e.on=="function";x&&e.on("resize",y);function _(m){let h=m-u;return u=m,h===0?"":h<0?`\x1B[${-h}A`:`\x1B[${h}B`}function v(m){let l=(Array.isArray(m)?m:[]).map(f=>$r(String(f??""),c));if(s!==null)for(l.length>s&&(l=l.slice(0,s));l.length<s;)l.push("");return l}function b(m){if(!d&&Rr(a,m))return;let h=[Te];d&&a.length>0&&(h.push(_(0),"\r",xe),a=[],u=0),d=!1;let l=Math.min(a.length,m.length);for(let f=0;f<l;f+=1)a[f]!==m[f]&&h.push(_(f),"\r",At,m[f]);if(m.length>a.length){a.length>0&&h.push(_(a.length-1));for(let f=a.length;f<m.length;f+=1)f>0&&h.push(`
7
- `),h.push("\r",At,m[f]),u=f}else m.length<a.length&&h.push(_(m.length),"\r",xe);m.length>0&&h.push(_(m.length-1)),h.push(he),a=m,e.write(h.join(""))}return{render(m){p||b(v(m))},writeAbove(m){if(p)return;let h=String(m??""),l=Te;a.length>0&&(l+=`${_(0)}\r${xe}`),l+=h.endsWith(`
8
- `)||h===""?h:`${h}
9
- `,e.write(l);let f=a;a=[],u=0,f.length>0?b(f):e.write(he)},clear(){if(p)return;let m=Te;a.length>0&&(m+=`${_(0)}\r${xe}`),m+=he,e.write(m),a=[],u=0,d=!1},setLines(m){s=Number.isFinite(m)&&m>=0?Math.trunc(m):null},getLines(){return a.slice()},getSize(){return{rows:i,columns:c}},dispose(){if(!p){if(p=!0,x){let m=typeof e.off=="function"?e.off:e.removeListener;typeof m=="function"&&m.call(e,"resize",y)}e.write(he)}}}}var L=Object.freeze({accent:"#B8F0FF",prompt:"#B8F0FF",banner_title:"#B8F0FF",banner_accent:"#91C2D7",ui_label:"#A5D9EB",banner_text:"#EAF2F8",status_bar_strong:"#EAF2F8",banner_border:"#455867",input_rule:"#455867",session_border:"#455867",banner_dim:"#60717F",status_bar_dim:"#60717F",status_bar_bg:"#11161B",status_bar_text:"#91A2B1",ok:"#7EE7B5",error:"#FF7B7B",warn:"#F0C674",bad:"#FF9B71",selection_bg:"#23313B"});function Pr(e){if(typeof e!="string")return null;let t=e.startsWith("#")?e.slice(1):e;if(!/^(?:[\da-f]{3}|[\da-f]{6})$/i.test(t))return null;let n=t.length===3?[...t].map(r=>r.repeat(2)).join(""):t;return{r:Number.parseInt(n.slice(0,2),16),g:Number.parseInt(n.slice(2,4),16),b:Number.parseInt(n.slice(4,6),16)}}function $t(e,t,n){let r=Pr(t);return r?`\x1B[${e};2;${r.r};${r.g};${r.b}m${String(n)}\x1B[0m`:String(n)}function $e({color:e=!0}={}){return e&&!Object.hasOwn(process.env,"NO_COLOR")?Object.freeze({fg:(n,r)=>$t(38,n,r),bg:(n,r)=>$t(48,n,r),bold:n=>`\x1B[1m${String(n)}\x1B[0m`,dim:n=>`\x1B[2m${String(n)}\x1B[0m`}):Object.freeze({fg:(n,r)=>String(r),bg:(n,r)=>String(r),bold:n=>String(n),dim:n=>String(n)})}var Ki=$e();function Rt(e){return String(e).replace(/\u001B\[[0-9;]*m/g,"")}var Pt=Object.freeze([["#B8F0FF"," \u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588 "],["#B8F0FF"," \u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588 \u2591\u2591\u2591\u2591\u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588 "],["#ACDEEF"," \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2591\u2591 \u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2591\u2591 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2588 "],["#A5D9EB"," \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588\u2591\u2591\u2591 "],["#9FCBDD"," \u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588 "],["#B8F0FF"," \u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591 "]]),Re="THE FUTURE IS AGENTIC / by DEMI",Pe=/\u001B\[[0-9;]*m/g;function jt(e){if(new RegExp("\\p{Mark}","u").test(e))return 0;let t=e.codePointAt(0);return t===8205||t===65039?0:t>=4352&&(t<=4447||t===9001||t===9002||t>=11904&&t<=42191&&t!==12351||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65040&&t<=65049||t>=65072&&t<=65135||t>=65280&&t<=65376||t>=65504&&t<=65510||t>=127744&&t<=129791||t>=131072&&t<=262141)?2:t<32||t>=127&&t<160?0:1}function D(e){return[...Rt(e)].reduce((t,n)=>t+jt(n),0)}function je(e,t){if(t<=0)return"";let n=String(e).split(/(\u001B\[[0-9;]*m)/g),r="",o=0,i=!1;for(let c of n)if(c){if(Pe.test(c)){Pe.lastIndex=0,r+=c,i=c!=="\x1B[0m";continue}Pe.lastIndex=0;for(let a of c){let u=jt(a);if(o+u>t)return i?`${r}\x1B[0m`:r;r+=a,o+=u}}return r}function Q(e,t,n="left"){let r=Math.max(0,Math.floor(Number(t)||0)),o=je(String(e),r),i=Math.max(0,r-D(o));if(n==="right")return`${" ".repeat(i)}${o}`;if(n==="center"){let c=Math.floor(i/2);return`${" ".repeat(c)}${o}${" ".repeat(i-c)}`}return`${o}${" ".repeat(i)}`}function Me(e,t){let n=Math.max(1,Math.floor(Number(t)||1)),r=[];for(let o of String(e??"").split(`
10
- `)){if(o===""){r.push("");continue}let i="",c=0;for(let a of o.split(" ")){let u=D(a);if(c>0&&c+1+u>n&&(r.push(i),i="",c=0),u>n){c>0&&(r.push(i),i="",c=0);let s=a;for(;D(s)>n;){let d=je(s,n);r.push(d),s=s.slice(d.length)}i=s,c=D(s);continue}i=c===0?a:`${i} ${a}`,c=c===0?u:c+1+u}r.push(i)}return r}function Nr(e){let t=Math.max(0,Math.floor(Number(e)||0)),n=Math.max(36,Math.min(t-4,76)),r=Math.max(0,Math.floor((t-n)/2)),o=r+3,i=Math.max(0,n-6);return{target:t,panelWidth:n,panelLeft:r,contentLeft:o,inner:i}}function jr(e){let t=1/0,n=-1;for(let r of e)for(let o=0;o<r.length;o+=1)r[o]!==" "&&(o<t&&(t=o),o>n&&(n=o));return n<0?{offset:0,width:0}:{offset:t,width:n-t+1}}function Nt(e,t,n=0){let{target:r,contentLeft:o,inner:i}=e,a=Math.round((r-t)/2)-n-o,u=Math.max(0,i-t-n);return Math.max(0,Math.min(u,a))}function Fe({width:e,palette:t}){let n=Nr(e),{target:r,panelWidth:o,panelLeft:i,inner:c}=n;if(r<72||c<=0)return[Q(t.bold(t.fg(L.accent,"oracle")),r,"center"),Q(t.fg(L.banner_text,Re),r,"center")];let a=Pt.map(([,l])=>l),{offset:u,width:s}=jr(a),d=" ".repeat(Nt(n,s,u)),p=" ".repeat(Nt(n,D(Re))),y=[];for(let[l,f]of Pt)y.push(t.bold(t.fg(l,`${d}${f.replace(/\s+$/,"")}`)));y.push(""),y.push(t.bold(t.fg(L.banner_text,`${p}${Re}`)));let x=l=>t.fg(L.banner_border,l),_=" ".repeat(i),v="\u2500".repeat(Math.max(0,o-2)),b=l=>Q(`${_}${l}`,r),m=[b(`${x("\u256D")}${x(v)}${x("\u256E")}`)],h=b(`${x("\u2502")}${" ".repeat(Math.max(0,o-2))}${x("\u2502")}`);m.push(h);for(let l of y)m.push(b(`${x("\u2502")} ${Q(l,c)} ${x("\u2502")}`));return m.push(h),m.push(b(`${x("\u2570")}${x(v)}${x("\u256F")}`)),m}function Mt({lines:e,width:t,palette:n,title:r=""}){let o=Math.max(2,Math.floor(Number(t)||0)),i=Math.max(0,o-2),c=je(String(r),Math.max(0,i-2)),a=c?` ${c} `:"",u=`${a}${"\u2500".repeat(Math.max(0,i-D(a)))}`,s=d=>n.fg(L.banner_border,d);return[`${s("\u256D")}${s(u)}${s("\u256E")}`,...e.map(d=>`${s("\u2502")}${Q(d,i)}${s("\u2502")}`),`${s("\u2570")}${s("\u2500".repeat(i))}${s("\u256F")}`]}function Ne(e){let t=Number(e);return Number.isFinite(t)?t>=1e6?`${(t/1e6).toFixed(1).replace(/\.0$/,"")}M`:t>=1e3?`${(t/1e3).toFixed(0)}K`:String(Math.round(t)):"0"}function Mr(e,t){let n=Math.max(0,Math.floor(Number(t)||0)),r=Number(e),o=Number.isFinite(r)?Math.min(100,Math.max(0,r)):0,i=Math.round(n*o/100);return`${"\u2588".repeat(i)}${"\u2591".repeat(n-i)}`}function ge(e){let t=Number(e);if(!Number.isFinite(t)||t<0)return"0s";let n=Math.floor(t/1e3);if(n<60)return`${n}s`;let r=Math.floor(n/60),o=n%60;return r<60?`${r}m${String(o).padStart(2,"0")}s`:`${Math.floor(r/60)}h${String(r%60).padStart(2,"0")}m`}function Ft({model:e,contextTokens:t,contextLength:n,percent:r,effort:o,thinking:i,chain:c,width:a,palette:u}){let s=Math.max(0,Math.floor(Number(a)||0)),d=u.fg(L.status_bar_dim," / "),p=s>=120?12:s>=60?8:4,y=Number(n)>0?`${Ne(t)}/${Ne(n)}`:Ne(t),x=Number.isFinite(Number(r))?`${Math.round(Number(r))}%`:"0%",_=[{text:String(e??""),strong:!0}];Number(n)>0&&_.push({text:`ctx ${Mr(r,p)} ${y} ${x}`}),o&&_.push({text:String(o)}),i&&_.push({text:String(i)}),typeof c=="string"&&c.length>0&&_.push({text:c});let v=_,b=h=>h.reduce((l,f,w)=>l+D(f.text)+(w>0?3:0),0);for(;v.length>1&&b(v)>s;)v=v.slice(0,-1);let m=v.map(h=>h.strong?u.fg(L.status_bar_strong,h.text):u.fg(L.status_bar_text,h.text)).join(d);return u.bg(L.status_bar_bg,Q(m,s))}var Ur=6;function Dr(e=[]){let t={pass:[],query:null,model:null,provider:null,quiet:!1,cont:!1};for(let n=0;n<e.length;n+=1){let r=e[n];if((r==="-q"||r==="--query")&&e[n+1]){t.query=e[++n],t.pass.push("-q",t.query);continue}if((r==="--model"||r==="-m")&&e[n+1]){t.model=e[++n],t.pass.push("--model",t.model);continue}if(r==="--provider"&&e[n+1]){t.provider=e[++n],t.pass.push("--provider",t.provider);continue}if(r==="--quiet"||r==="-Q"){t.quiet=!0,t.pass.push(r);continue}if(r==="--continue"||r==="-c"){t.cont=!0,t.pass.push("--continue");continue}t.pass.push(r)}return t}function Ue(e,t){if(!t||typeof t!="object")return;let n=Number(t.context_used??t.context_tokens??t.input??t.prompt),r=Number(t.context_max??t.context_length);Number.isFinite(n)&&n>0&&(e.contextTokens=n),Number.isFinite(r)&&r>0&&(e.contextLength=r);let o=Number(t.context_percent);Number.isFinite(o)?e.contextPercent=o:e.contextLength>0&&(e.contextPercent=Math.round(e.contextTokens/e.contextLength*100))}function Br(e){let t=e.width,n=`${e.promptLabel} `,r=Math.max(1,t-2-D(n)),o=e.buffer||"",i=Math.max(0,Math.min(e.cursor??o.length,o.length)),c=0;i>r&&(c=i-r);let a=o.slice(c,c+r),u=i-c,s=a.slice(0,u),d=a.slice(u,u+1)||" ",p=a.slice(u+1),y=e.palette;return[`${y.fg(L.accent,n)}${s}${y.bg(L.selection_bg,d)}${p}`]}function Kr(e){let t=e.width,n=[];if(e.liveLines.length>0){for(let r of e.liveLines.slice(-Ur))n.push(r);n.push("")}return n.push(...Mt({lines:Br(e),width:t,palette:e.palette,title:"Ask Oracle \u203A"})),n.push(Ft({model:e.model,contextTokens:e.contextTokens,contextLength:e.contextLength,percent:e.contextPercent,effort:e.effort,thinking:e.thinking,chain:e.chain,width:t,palette:e.palette})),n}function Hr(e){let t=e?.params||e||{};return{type:t.type||e?.type||"",sessionId:t.session_id||e?.session_id||"",payload:t.payload||e?.payload||{}}}function ye(e={}){return typeof e.text=="string"?e.text:typeof e.rendered=="string"?e.rendered:typeof e.message=="string"?e.message:""}function qr(e={}){let t=e.stdout||process.stdout,n=e.stdin||process.stdin,r=Math.max(20,Number(t.columns||e.columns||80)),o=e.palette||$e({color:t.isTTY!==!1}),i=e.renderer||Tt({stdout:t,rows:t.rows,columns:r}),c=e.client||bt({python:e.python,pythonArgs:e.pythonArgs||[],cwd:e.cwd||process.cwd(),env:e.env||process.env,spawnFn:e.spawnFn,startupTimeoutMs:e.startupTimeoutMs,requestTimeoutMs:e.requestTimeoutMs}),a=new Fr,u=e.now||(()=>Date.now()),s={palette:o,width:r,promptLabel:"oracle \u203A",buffer:"",cursor:0,model:e.model||"model",contextTokens:0,contextLength:0,contextPercent:0,effort:e.effort||"",thinking:"0s",chain:(e.env||process.env).ORACLE_ACTIVE_CHAIN||"",busy:!1,cancelled:!1,sessionId:null,assistantBuffer:"",flushedLines:0,liveLines:[],startedAt:0},d=null,p=null,y={renderer:i,state:s};function x(){i.render(Kr(s))}function _(k){i.writeAbove(`${k}
11
- `)}function v(){let k=s.assistantBuffer.split(`
12
- `),g=k[k.length-1]||"";s.liveLines=g?Me(g,s.width):[]}function b({final:k=!1}={}){let g=s.assistantBuffer.split(`
13
- `),I=k?g.length:g.length-1,q=!1;for(;s.flushedLines<I;){let C=g[s.flushedLines];for(let N of Me(C,s.width))_(N);s.flushedLines+=1,q=!0}return k?s.liveLines=[]:v(),q}function m(){p||(p=setInterval(()=>{s.busy&&(s.thinking=ge(u()-s.startedAt),x())},250),typeof p.unref=="function"&&p.unref())}function h(){p&&(clearInterval(p),p=null)}async function l(k){let g=String(k||"").trim();if(g){if(g==="/exit"||g==="/quit"){await O();return}if(g==="/clear"){i.clear();for(let I of Fe({width:s.width,palette:o}))_(I);x();return}s.busy=!0,s.assistantBuffer="",s.flushedLines=0,s.liveLines=[],s.startedAt=u(),s.thinking="0s",_(`${o.bold(o.fg(L.prompt,"you"))} ${g}`),_(""),m(),x(),await c.request("prompt.submit",{session_id:s.sessionId,text:g})}}function f(k){let g=Hr(k);if(g.type!=="gateway.ready"){if(g.type==="session.info"&&g.payload){g.payload.model&&(s.model=g.payload.model),g.payload.reasoning_effort&&(s.effort=g.payload.reasoning_effort),Ue(s,g.payload.usage),x();return}if(g.type==="message.start"){s.busy=!0,s.cancelled=!1,s.assistantBuffer="",s.flushedLines=0,s.liveLines=[],_(o.bold(o.fg(L.accent,"oracle"))),x();return}if(g.type==="thinking.delta"||g.type==="reasoning.delta"){if(s.cancelled)return;ye(g.payload).trim()&&(s.thinking=`${ge(u()-s.startedAt)}`),x();return}if(g.type==="message.delta"){if(s.cancelled)return;s.assistantBuffer+=ye(g.payload),b(),x();return}if(g.type==="message.complete"){if(s.cancelled){s.cancelled=!1;return}let I=ye(g.payload);I&&I.length>=s.assistantBuffer.length&&(s.assistantBuffer=I),b({final:!0}),_(""),s.busy=!1,h(),Ue(s,g.payload?.usage||g.payload?.context),s.thinking=ge(u()-s.startedAt),x();return}g.type==="error"&&(s.busy=!1,h(),_(o.fg(L.error,`error: ${ye(g.payload)||"unknown"}`)),x())}}async function w(){await c.start(),c.on("event",f),c.on("log",g=>a.emit("log",g)),c.on("error",g=>a.emit("error",g));let k=await c.request("session.create",{cols:s.width,cwd:e.cwd||process.cwd(),source:"cli",profile:e.profile||"oracle",close_on_disconnect:!0,...e.model?{model:e.model}:{},...e.provider?{provider:e.provider}:{}});s.sessionId=k.session_id,s.model=k.info?.model||s.model,k.info?.reasoning_effort&&(s.effort=k.info.reasoning_effort),Ue(s,k.info?.usage);for(let g of Fe({width:s.width,palette:o}))_(g);_(""),x(),d=Et({stdin:n,stdout:t,onSubmit:g=>{l(g).catch(I=>a.emit("error",I))},onCancel:()=>{s.busy&&(s.busy=!1,s.cancelled=!0,h(),b({final:!0}),_(o.fg(L.warn,"interrupted")),_(""),x(),c.request("session.interrupt",{session_id:s.sessionId}).catch(g=>a.emit("error",g)))},onEof:()=>{O().catch(g=>a.emit("error",g))},onClear:()=>{i.clear(),x()},onRender:g=>{s.buffer=g.buffer||"",s.cursor=g.cursor??s.buffer.length,x()}}),d.start()}async function O(){h(),d&&d.stop(),i.dispose(),await c.stop(),a.emit("stop")}return Object.freeze({start:w,stop:O,on:a.on.bind(a),off:a.off.bind(a),state:s,handleEvent:f,submit:l})}async function De({hermesPython:e,client:t,tuiFactory:n=qr,args:r=[],env:o=process.env,cwd:i=process.cwd(),stdout:c=process.stdout,stdin:a=process.stdin}={}){let u=Dr(r);if(u.query)return{native:!1,pass:u.pass};if(!a.isTTY||!c.isTTY)return{native:!1,pass:u.pass};if(o.ORACLE_NATIVE_TUI==="0")return{native:!1,pass:u.pass};let s=e;if(!t&&!s)return{native:!1,pass:u.pass};let d=pe({...o,ORACLE_CHAT_SURFACE:"1",ORACLE_PROFILE:"oracle",ORACLE_NODE_BIN:process.execPath}),p=n({...t?{client:t}:{},...s?{python:s.command,pythonArgs:s.prefix||[]}:{},cwd:i,env:d,stdin:a,stdout:c,model:u.model,provider:u.provider,profile:"oracle"});return p.on("log",y=>{o.ORACLE_CLI_DEBUG&&process.stderr.write(`${y}
14
- `)}),p.on("error",y=>{process.stderr.write(`oracle chat: ${y.message}
15
- `)}),await p.start(),new Promise(y=>{let x=!1,_=async()=>{x||(x=!0,await p.stop(),y({native:!0,code:0}))};p.on("stop",()=>{x||(x=!0,y({native:!0,code:0}))}),process.once("SIGINT",_),process.once("SIGTERM",_)})}import zr from"node:fs";import Ut from"node:path";var Dt=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"},xai:{key:"XAI_API_KEY",baseUrl:"https://api.x.ai/v1",model:"grok-4-latest"},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"}}),Wr=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-latest",protocol:"responses"}});function Yr(e,t){let n=Number(e);return Number.isSafeInteger(n)&&n>0?n:t}function Gr(e,t){let n=String(e.ORACLE_PROVIDER||t.provider||"").trim().toLowerCase();if(n)return n;if(e.ORACLE_BASE_URL||t.baseUrl)return"custom";for(let[r,o]of Object.entries(Dt))if(e[o.key]||o.alternateKey&&e[o.alternateKey])return r;return null}function Jr(e=process.env,t={},n=()=>!1,r=()=>""){let o=Gr(e,t);if(!o)return null;let i=Wr[o],c=Dt[o]||i,a=String(e.ORACLE_API_KEY_ENV||t.apiKeyEnv||""),u=String(e.ORACLE_API_KEY||a&&e[a]||c&&(e[c.key]||c.alternateKey&&e[c.alternateKey])||r(o)||""),s=String(i?i.baseUrl:o==="custom"?e.ORACLE_BASE_URL||t.baseUrl||"":c?.baseUrl||"").replace(/\/+$/,""),d=String(e.ORACLE_MODEL||t.model||c?.model||"");if(!s||!d)return null;let p=!!(i&&n(o));return i&&!p||!i&&o!=="custom"&&!u?null:{kind:"standalone",provider:o,model:d,baseUrl:s,...p?{authType:"oauth",protocol:i.protocol}:{apiKey:u},contextLength:Yr(e.ORACLE_CONTEXT_LENGTH||t.contextLength,128e3),reasoningEffort:String(e.ORACLE_REASONING_EFFORT||t.reasoningEffort||"high")}}function Z(e=""){return["Oracle runs its own native chat \u2014 no Hermes or external agent required.","Set OPENROUTER_API_KEY, run `oracle auth login claude|codex|grok`, or configure a custom OpenAI-compatible endpoint.","`oracle harness detect` finds any Agent Plugins-compatible clients installed on this machine.",e].filter(Boolean).join(`
16
- `)}function Vr(e=process.env,t={}){if(e.ORACLE_PUBLIC_DESKTOP==="1"||e.ORACLE_REMOTE_COMPUTE_DISABLE==="1")return null;let n=String(e.ORACLE_CHAT_BACKEND||t.backend||"auto").trim().toLowerCase(),r=String(e.ORACLE_COMPUTE_HOST||t.computeHost||"").trim();if(!["remote","arch"].includes(n)&&!e.ORACLE_COMPUTE_HOST||!r)return null;let o=String(e.ORACLE_COMPUTE_USER||t.computeUser||"").trim(),i=String(e.ORACLE_COMPUTE_PATH||t.computePath||"$HOME/.local/bin:/usr/local/bin:/usr/bin:/bin:/opt/homebrew/bin").trim();return{kind:"remote",host:r,user:o,path:i}}var Xr=Object.freeze([{name:"oracle",bin:"oracle",label:"Oracle Native (default)",kind:"oracle"},{name:"hermes",bin:"hermes",label:"Hermes Agent",kind:"hermes"},{name:"opencode",bin:"opencode",label:"OpenCode",kind:"mcp"},{name:"claude",bin:"claude",label:"Claude Code",kind:"mcp"},{name:"codex",bin:"codex",label:"OpenAI Codex CLI",kind:"mcp"},{name:"cursor",bin:"cursor",label:"Cursor IDE",kind:"mcp"},{name:"windsurf",bin:"windsurf",label:"Windsurf",kind:"mcp"},{name:"aider",bin:"aider",label:"Aider",kind:"mcp"},{name:"continue",bin:"continue",label:"Continue",kind:"mcp"}]);function Qr(e){for(let t of(process.env.PATH||"").split(Ut.delimiter)){let n=Ut.join(t,e);try{if(zr.existsSync(n))return n}catch{}}return null}function Bt({env:e=process.env,hermes:t={ok:!1},storedConfig:n=null,oauthAvailable:r=()=>!1,apiKeyResolver:o=()=>""}={}){let i=String(e.ORACLE_CHAT_BACKEND||n?.backend||"auto").trim().toLowerCase(),c=Vr(e,n||{});if(i==="remote"||i==="arch")return c?{kind:"remote",config:c}:{kind:"unconfigured",reason:Z(`${i} compute backend was requested, but no compute host is configured.`)};let a=Jr(e,n||{},r,o);if(i==="standalone")return a?{kind:"standalone",config:a}:{kind:"unconfigured",reason:Z("ORACLE_CHAT_BACKEND=standalone was requested, but no standalone model is configured.")};if(i==="hermes")return t?.ok?{kind:"hermes",bin:t.bin}:{kind:"unconfigured",reason:Z("ORACLE_CHAT_BACKEND=hermes was requested, but Hermes was not found.")};if(i!=="auto"){for(let u of Xr)if(u.name===i){let s=Qr(u.bin);return s?{kind:"harness",harness:{...u,path:s}}:{kind:"unconfigured",reason:Z(`ORACLE_CHAT_BACKEND=${i} was requested, but ${u.bin} was not found on PATH.`)}}return{kind:"unconfigured",reason:Z(`Unknown ORACLE_CHAT_BACKEND value: ${i}`)}}return c?{kind:"remote",config:c}:a?{kind:"standalone",config:a}:t?.ok?{kind:"hermes",bin:t.bin}:{kind:"unconfigured",reason:Z()}}Y();import Eo from"node:fs";import kn from"node:path";import{randomUUID as wn}from"node:crypto";import{EventEmitter as Ao}from"node:events";import{spawnSync as Oo}from"node:child_process";import be from"node:fs";import Kt from"node:path";import{homedir as Zr}from"node:os";var Ke=process.env.ORACLE_CONFIG_DIR||Kt.join(Zr(),".config","oracle"),Ht=Kt.join(Ke,"memory.json"),Be=2200;function qt(e){be.existsSync(e)||be.mkdirSync(e,{recursive:!0})}function He(){qt(Ke);try{let e=be.readFileSync(Ht,"utf8");return JSON.parse(e)}catch{return{version:1,updatedAt:new Date().toISOString(),entries:[]}}}function zt(e){qt(Ke),e.updatedAt=new Date().toISOString(),be.writeFileSync(Ht,JSON.stringify(e,null,2),{mode:384})}function Wt(e,t){let n=He(),r=n.entries.findIndex(o=>o.key===e);for(r>=0?n.entries[r]={key:e,content:t,addedAt:new Date().toISOString()}:n.entries.push({key:e,content:t,addedAt:new Date().toISOString()});JSON.stringify(n.entries).length>Be&&n.entries.length>1;)n.entries.shift();zt(n)}function Yt(e){let t=He(),n=t.entries.length;return t.entries=t.entries.filter(r=>r.key!==e),t.entries.length<n?(zt(t),{ok:!0}):{ok:!1}}function Gt(){let e=He();if(e.entries.length===0)return"";let t=JSON.stringify(e.entries).length,n=Math.round(t/Be*100),r=e.entries.map(o=>`${o.key}: ${o.content}`);return["\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",`MEMORY [${n}% \u2014 ${t}/${Be} chars]`,"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",...r].join(`
17
- `)}var Jt=[{type:"function",function:{name:"memory_add",description:"Save a durable fact to memory for future sessions.",parameters:{type:"object",properties:{key:{type:"string",description:"Short unique key"},content:{type:"string",description:"The fact to remember"}},required:["key","content"],additionalProperties:!1}}},{type:"function",function:{name:"memory_remove",description:"Remove a memory entry by key.",parameters:{type:"object",properties:{key:{type:"string",description:"The key to remove"}},required:["key"],additionalProperties:!1}}}];import B from"node:fs";import _e from"node:path";import{homedir as eo}from"node:os";var to=process.env.ORACLE_CONFIG_DIR||_e.join(eo(),".config","oracle"),ce=_e.join(to,"skills"),no=/^[a-z0-9][a-z0-9_-]{0,63}$/;function Vt(e){B.existsSync(e)||B.mkdirSync(e,{recursive:!0})}function Xt(e){let t=String(e??"").trim();if(!no.test(t))throw new Error("invalid skill name");return _e.join(ce,`${t}.md`)}function qe(){Vt(ce);let e=[];try{for(let t of B.readdirSync(ce,{withFileTypes:!0})){if(!t.isFile()||!t.name.endsWith(".md"))continue;let n=_e.join(ce,t.name),r=B.readFileSync(n,"utf8"),o=t.name.replace(/\.md$/,""),i="",c=r.match(/^description:\s*(.+)$/m);c?i=c[1].trim():i=r.split(`
18
- `)[0].replace(/^#+\s*/,"").trim()||o,e.push({name:o,description:i,path:n,size:r.length})}}catch{}return e}function ze(e){try{let t=Xt(e);return B.lstatSync(t).isFile()?B.readFileSync(t,"utf8"):null}catch{return null}}function Qt(e){let t=qe();if(t.length===0)return`## Skills
1
+ var Yn=Object.defineProperty;var _t=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Gn=(e,t)=>{for(var n in t)Yn(e,n,{get:t[n],enumerable:!0})};import ue from"node:fs";import Jn from"node:os";import Y from"node:path";import{fileURLToPath as Vn}from"node:url";function le(){return process.env.ORACLE_FAKE_HOME||Jn.homedir()}function Qn(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function U(){return Qn()?process.env.ORACLE_CONFIG_DIR||Y.join(le(),".config","oracle"):Y.join(le(),".config","oracle")}function Zn(){return Y.join(U(),"desk.json")}function er(){return Y.join(U(),"env")}function ee({force:e=!1}={}){if(ee._done&&!e)return ee._result||null;ee._done=!0;let t={},n=(o,i)=>{if(i==null)return;let s=String(i).trim();s&&(process.env[o]!=null&&String(process.env[o]).trim()!==""||(process.env[o]=s,t[o]=s))};try{let o=er();if(ue.existsSync(o))for(let i of ue.readFileSync(o,"utf8").split(/\r?\n/)){let s=i.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!s||s[2].startsWith("#"))continue;let c=s[2];(c.startsWith('"')&&c.endsWith('"')||c.startsWith("'")&&c.endsWith("'"))&&(c=c.slice(1,-1)),n(s[1],c)}}catch{}try{let o=Zn();if(ue.existsSync(o)){let i=JSON.parse(ue.readFileSync(o,"utf8"));i&&typeof i=="object"&&(n("ORACLE_DESK_URL",i.deskUrl||i.dataUrl||i.url),n("ORACLE_DATA_URL",i.dataUrl||i.deskUrl||i.url),n("ORACLE_API_URL",i.apiUrl||i.dataUrl||i.deskUrl),n("ORACLE_PUBLIC_URL",i.publicUrl||i.deskUrl||i.dataUrl),n("ORACLE_EXEC_URL",i.execUrl),n("MAD_DESK_URL",i.deskUrl||i.dataUrl))}}catch{}let r=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return r&&(n("ORACLE_DESK_URL",r),n("ORACLE_DATA_URL",r),n("ORACLE_API_URL",r),n("ORACLE_PUBLIC_URL",r),n("MAD_DESK_URL",r)),ee._result=Object.keys(t).length?t:null,ee._result}function D(){return process.env.HERMES_HOME?Y.resolve(process.env.HERMES_HOME):Y.join(le(),".hermes")}function N(e){return ue.mkdirSync(e,{recursive:!0}),e}var Xn,B,V=_t(()=>{Xn=Y.dirname(Vn(import.meta.url)),B=Y.resolve(Xn,"../..");try{ee()}catch{}});var Tn={};Gn(Tn,{createOAuthStore:()=>pt,default:()=>Do,getOAuthStore:()=>se,hasOAuthCredentials:()=>Ln,loginOAuth:()=>On,oauthProviderConfig:()=>dt,oauthProviderId:()=>q,oauthRuntimeConfig:()=>In,refreshOAuthCredentials:()=>mt,resolveOAuthCredentials:()=>Cn});import{createHash as Oo,randomBytes as lt,timingSafeEqual as Co}from"node:crypto";import j from"node:fs";import z from"node:path";import Lo from"node:readline/promises";import{spawn as Io,spawnSync as To}from"node:child_process";function ft(e={}){return typeof e.now=="function"?Number(e.now()):Date.now()}function q(e){let t=String(e||"").trim().toLowerCase();for(let[n,r]of Object.entries(Q))if(r.aliases.includes(t))return n;throw new Error(`unsupported OAuth provider: ${e||"(empty)"}`)}function dt(e){let t=q(e);return{id:t,...Q[t]}}function $(e,t={}){if(!j.existsSync(e))return t;try{let n=JSON.parse(j.readFileSync(e,"utf8"));if(!n||typeof n!="object"||Array.isArray(n))throw new Error("invalid object");return n}catch{throw new Error(`credential store is unreadable or corrupt: ${z.basename(e)}`)}}function An(e){N(e),process.platform!=="win32"&&j.chmodSync(e,448)}function J(e,t){An(z.dirname(e));let n=`${e}.${process.pid}.${lt(4).toString("hex")}.tmp`;j.writeFileSync(n,`${JSON.stringify(t,null,2)}
2
+ `,{mode:384}),j.renameSync(n,e),process.platform!=="win32"&&j.chmodSync(e,384)}function Ro(e){if(process.platform!=="linux")return!1;let t=e("secret-tool",["--version"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return!t.error&&t.status===0}function ct(e){let t=String(e||"").trim().toLowerCase();if(!/^[a-z0-9][a-z0-9._-]*$/.test(t))throw new Error(`invalid API-key provider: ${e||"(empty)"}`);return t}function ie(e={}){let t=String(e.accessToken||e.access_token||"").trim(),n=String(e.refreshToken||e.refresh_token||"").trim(),r=Number(e.expiresAt||e.expires_at||0);if(!t)throw new Error("OAuth credential is missing access token");return{accessToken:t,refreshToken:n,expiresAt:Number.isFinite(r)?r:0,tokenType:String(e.tokenType||e.token_type||"Bearer"),source:String(e.source||"oracle"),...e.discovery?{discovery:e.discovery}:{},...e.scope?{scope:e.scope}:{},...e.idToken||e.id_token?{idToken:String(e.idToken||e.id_token)}:{}}}function pt(e={}){let t=e.file||z.join(U(),"oauth.json"),n=e.metadataFile||z.join(z.dirname(t),"oauth-meta.json"),r=e.linksFile||z.join(z.dirname(t),"oauth-links.json"),o=()=>typeof e.now=="function"?Number(e.now()):Date.now(),i=e.spawnFn||To,s=e.keychain!==!1&&process.env.ORACLE_AUTH_FILE_STORE!=="1"&&Ro(i),c=s?"linux-secret-service":"private-file",u=`${t}.lock`;async function a(d){An(z.dirname(u));let l;for(let h=0;h<400;h+=1)try{l=j.openSync(u,"wx",384);break}catch(_){if(_?.code!=="EEXIST")throw _;try{Date.now()-j.statSync(u).mtimeMs>3e5&&j.unlinkSync(u)}catch{}await new Promise(y=>setTimeout(y,25))}if(l===void 0)throw new Error("timed out waiting for OAuth credential lock");try{return await d()}finally{try{j.closeSync(l)}catch{}try{j.unlinkSync(u)}catch{}}}function f(d,l="oauth"){return["application","oracle","kind",l,"provider",d]}function p(d){if(!j.existsSync(r))return null;let h=$(r,{providers:{}}).providers?.[d];if(!Array.isArray(h))return null;let _=[];for(let y of h)if(z.isAbsolute(String(y||"")))try{let m=$(y,{}),A=d==="anthropic-oauth"?m.claudeAiOauth:null;if(!A)continue;let M=ie(A);_.push({...M,refreshToken:"",source:"external-access-only"})}catch{}return _.length?_.find(y=>!y.expiresAt||y.expiresAt>o()+Le)||_[0]:null}function g(d){let l=q(d);if(s){let y=i("secret-tool",["lookup",...f(l)],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(!y.error&&y.status===0&&String(y.stdout||"").trim())try{return ie(JSON.parse(String(y.stdout).trim()))}catch{}return p(l)}let _=$(t,{providers:{}}).providers?.[l];if(_)try{return ie(_)}catch{}return p(l)}function x(d,l){let h=q(d),_=ie(l);if(s){let m=i("secret-tool",["store",`--label=Oracle ${h} OAuth`,...f(h)],{input:JSON.stringify(_),encoding:"utf8",stdio:["pipe","ignore","pipe"]});if(m.error||m.status!==0)throw new Error("OS credential store rejected OAuth credential");let A=$(n,{providers:{}});return A.providers||={},A.providers[h]={expiresAt:_.expiresAt,source:_.source},J(n,A),_}let y=$(t,{providers:{}});return y.providers||={},y.providers[h]=_,J(t,y),_}function w(d){let l=q(d);if(s){let y=i("secret-tool",["clear",...f(l)],{encoding:"utf8",stdio:["ignore","ignore","pipe"]}),m=$(n,{providers:{}});return m.providers&&delete m.providers[l],J(n,m),!y.error&&y.status===0}let h=$(t,{providers:{}}),_=!!h.providers?.[l];return h.providers&&delete h.providers[l],J(t,h),_}function S(d){let l=ct(d);if(s){let h=i("secret-tool",["lookup",...f(l,"api-key")],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return h.error||h.status!==0?"":String(h.stdout||"").trim()}return String($(t,{apiKeys:{}}).apiKeys?.[l]||"").trim()}function k(d,l){let h=ct(d),_=String(l||"").trim();if(!_)throw new Error("API key is empty");if(s){let m=i("secret-tool",["store",`--label=Oracle ${h} API key`,...f(h,"api-key")],{input:_,encoding:"utf8",stdio:["pipe","ignore","pipe"]});if(m.error||m.status!==0)throw new Error("OS credential store rejected API key");let A=$(n,{providers:{},apiKeys:{}});return A.apiKeys||={},A.apiKeys[h]={configured:!0},J(n,A),!0}let y=$(t,{providers:{},apiKeys:{}});return y.apiKeys||={},y.apiKeys[h]=_,J(t,y),!0}function b(d){let l=ct(d);if(s){let y=i("secret-tool",["clear",...f(l,"api-key")],{encoding:"utf8",stdio:["ignore","ignore","pipe"]}),m=$(n,{providers:{},apiKeys:{}});return m.apiKeys&&delete m.apiKeys[l],J(n,m),!y.error&&y.status===0}let h=$(t,{providers:{},apiKeys:{}}),_=!!h.apiKeys?.[l];return h.apiKeys&&delete h.apiKeys[l],J(t,h),_}function v(){let d={},l={};if(s){let h=$(n,{providers:{},apiKeys:{}});for(let[_,y]of Object.entries(h.providers||{}))d[_]={loggedIn:!!g(_),expiresAt:Number(y.expiresAt||0),source:String(y.source||"oracle"),storage:c};for(let _ of Object.keys(h.apiKeys||{}))l[_]={configured:!!S(_),storage:c}}else{let h=$(t,{providers:{},apiKeys:{}});for(let[_,y]of Object.entries(h.providers||{}))d[_]={loggedIn:!!y?.accessToken,expiresAt:Number(y?.expiresAt||0),source:String(y?.source||"oracle"),storage:c};for(let[_,y]of Object.entries(h.apiKeys||{}))l[_]={configured:!!y,storage:c}}for(let h of Object.keys(Q)){if(d[h])continue;let _=p(h);_&&(d[h]={loggedIn:!0,expiresAt:_.expiresAt,source:_.source,storage:"external-access-source"})}return{storage:c,providers:d,apiKeys:l}}return Object.freeze({file:t,storage:c,get:g,set:x,remove:w,getApiKey:S,setApiKey:k,removeApiKey:b,status:v,withLock:a})}function se(){return En||=pt(),En}function ut(e){return Buffer.from(e).toString("base64url")}function $o(){let e=ut(lt(32));return{verifier:e,challenge:ut(Oo("sha256").update(e).digest()),state:ut(lt(24))}}function Po(e,t){let n=Buffer.from(String(e||"")),r=Buffer.from(String(t||""));return n.length===r.length&&Co(n,r)}function No(e){let t=String(e),n=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd.exe",["/d","/s","/c","start","",t]]:["xdg-open",[t]];try{return Io(n[0],n[1],{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function Ie(e){return new URLSearchParams(e).toString()}async function W(e,t){if(!e?.ok){let r="";try{r=String((await e.json())?.error||"")}catch{}throw new Error(`${t} failed (HTTP ${e?.status||"unknown"}${r?`, ${r}`:""})`)}let n=await e.json();if(!n||typeof n!="object")throw new Error(`${t} returned invalid JSON`);return n}async function jo(e){if(e)return String(await e()).trim();let t=Lo.createInterface({input:process.stdin,output:process.stdout});try{return String(await t.question("Authorization code: ")).trim()}finally{t.close()}}function Te(e,t={}){let n=String(e.access_token||"").trim(),r=String(e.refresh_token||t.refreshToken||"").trim();if(!n)throw new Error("OAuth token response is missing access token");let o=Number(e.expires_in||3600);return ie({accessToken:n,refreshToken:r,expiresAt:ft(t)+Math.max(1,o)*1e3,tokenType:e.token_type||"Bearer",idToken:e.id_token,source:"oracle",...t.discovery?{discovery:t.discovery}:{},...e.scope?{scope:e.scope}:{}})}async function Fo(e){let t=Q["anthropic-oauth"],n=e.pkce||$o(),r=new URLSearchParams({code:"true",client_id:t.clientId,response_type:"code",redirect_uri:t.redirectUri,scope:t.scope,code_challenge:n.challenge,code_challenge_method:"S256",state:n.state}),o=`${t.authorizeUrl}?${r}`;e.output(`Open: ${o}`),e.openFn(o);let i=await jo(e.inputFn),[s,c]=i.split("#",2);if(!s||!Po(c,n.state))throw new Error("Claude OAuth state mismatch");let u=await e.fetchFn(t.tokenUrl,{method:"POST",headers:{"content-type":"application/json","user-agent":"axios/1.7.9"},body:JSON.stringify({grant_type:"authorization_code",client_id:t.clientId,code:s,state:c,redirect_uri:t.redirectUri,code_verifier:n.verifier})});return Te(await W(u,"Claude OAuth token exchange"),e)}async function Mo(e){let t=Q["openai-codex"],n=await W(await e.fetchFn(`${t.issuer}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({client_id:t.clientId})}),"Codex device authorization");if(!n.user_code||!n.device_auth_id)throw new Error("Codex device authorization returned incomplete data");let r=`${t.issuer}/codex/device`;e.output(`Open: ${r}`),e.output(`Code: ${n.user_code}`),e.openFn(r);let o=Math.max(3,Number(n.interval||5)),i;for(let c=0;c<Math.ceil(900/o);c+=1){await e.sleepFn(o*1e3);let u=await e.fetchFn(`${t.issuer}/api/accounts/deviceauth/token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({device_auth_id:n.device_auth_id,user_code:n.user_code})});if(u.ok){i=await W(u,"Codex device authorization");break}if(![403,404].includes(u.status))throw new Error(`Codex device authorization failed (HTTP ${u.status})`)}if(!i)throw new Error("Codex device authorization timed out");let s=await e.fetchFn(t.tokenUrl,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:Ie({grant_type:"authorization_code",code:i.authorization_code,redirect_uri:`${t.issuer}/deviceauth/callback`,client_id:t.clientId,code_verifier:i.code_verifier})});return Te(await W(s,"Codex OAuth token exchange"),e)}function X(e){let t=new URL(String(e)),n=t.hostname.toLowerCase();if(t.protocol!=="https:"||n!=="x.ai"&&!n.endsWith(".x.ai"))throw new Error("xAI OAuth discovery returned an untrusted endpoint");return t.toString()}async function Uo(e){let t=Q["xai-oauth"],n=await W(await e.fetchFn(t.discoveryUrl,{headers:{accept:"application/json"}}),"xAI OAuth discovery");X(n.authorization_endpoint);let r=X(n.token_endpoint),o=await W(await e.fetchFn(t.deviceUrl,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:Ie({client_id:t.clientId,scope:t.scope})}),"xAI device authorization");if(!o.device_code||!o.user_code||!o.verification_uri)throw new Error("xAI device authorization returned incomplete data");let i=X(o.verification_uri_complete||o.verification_uri);e.output(`Open: ${i}`),e.output(`Code: ${o.user_code}`),e.openFn(i);let s=Math.max(1,Number(o.interval||5)),c=Math.ceil(Math.max(1,Number(o.expires_in||600))/s);for(let u=0;u<c;u+=1){let a=await e.fetchFn(r,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:Ie({grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:t.clientId,device_code:o.device_code})});if(a.ok){let p=await W(a,"xAI OAuth token exchange");return Te(p,{...e,discovery:{authorization_endpoint:X(n.authorization_endpoint),token_endpoint:r}})}let f="";try{f=String((await a.json())?.error||"")}catch{}if(f==="slow_down")await e.sleepFn((s+1)*1e3);else if(f==="authorization_pending")await e.sleepFn(s*1e3);else throw new Error(`xAI OAuth token exchange failed (HTTP ${a.status}${f?`, ${f}`:""})`)}throw new Error("xAI device authorization timed out")}async function On(e,t={}){let n=q(e),r={fetchFn:t.fetchFn||globalThis.fetch,inputFn:t.inputFn,sleepFn:t.sleepFn||(o=>new Promise(i=>setTimeout(i,o))),openFn:t.openFn||No,output:t.output||(o=>process.stdout.write(`${o}
3
+ `)),now:t.now,pkce:t.pkce};return n==="anthropic-oauth"?Fo(r):n==="openai-codex"?Mo(r):Uo(r)}async function mt(e,t,n={}){let r=q(e),o=Q[r],i=ie(t);if(!i.refreshToken)throw new Error(`${r} OAuth credential cannot refresh; run oracle auth login`);let s=i.discovery,c,u=n.fetchFn||globalThis.fetch;if(r==="xai-oauth"){if(!s?.token_endpoint){let p=await u(o.discoveryUrl),g=await W(p,"xAI OAuth discovery");s={...g.authorization_endpoint?{authorization_endpoint:X(g.authorization_endpoint)}:{},token_endpoint:X(g.token_endpoint)}}c=X(s.token_endpoint)}else c=o.tokenUrl;let a=await u(c,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json",...r==="anthropic-oauth"?{"user-agent":"axios/1.7.9"}:{}},body:Ie({grant_type:"refresh_token",refresh_token:i.refreshToken,client_id:o.clientId})}),f=await W(a,`${r} OAuth refresh`);return Te(f,{...n,refreshToken:i.refreshToken,discovery:s})}async function Cn(e,t={}){let n=q(e),r=t.store||se(),o=r.get(n);if(!o)throw new Error(`${n} OAuth is not logged in; run oracle auth login ${e}`);let i=ft(t);if(o.source==="external-access-only"&&o.expiresAt&&o.expiresAt<=i+Le)throw new Error(`${n} external OAuth access source is expired or near expiry; refresh the source authority`);if(!o.expiresAt||o.expiresAt>i+Le)return o;let s=async()=>{let c=r.get(n);if(!c)throw new Error(`${n} OAuth is not logged in; run oracle auth login ${e}`);let u=ft(t);if(!c.expiresAt||c.expiresAt>u+Le)return c;let a=await mt(n,c,t);return r.set(n,a),a};return typeof r.withLock=="function"?r.withLock(s):s()}function Ln(e,t={}){try{return!!(t.store||se()).get(e)?.accessToken}catch{return!1}}function In(e){let t=dt(e);return{kind:"standalone",provider:t.id,model:t.model,baseUrl:t.baseUrl,authType:"oauth",protocol:t.protocol}}var Q,Le,En,Do,ht=_t(()=>{V();Q=Object.freeze({"anthropic-oauth":{aliases:["anthropic-oauth","anthropic","claude","claude-oauth"],clientId:"9d1c250a-e61b-44d9-88ed-5944d1962f5e",authorizeUrl:"https://claude.ai/oauth/authorize",tokenUrl:"https://platform.claude.com/v1/oauth/token",redirectUri:"https://console.anthropic.com/oauth/code/callback",scope:"org:create_api_key user:profile user:inference",baseUrl:"https://api.anthropic.com/v1",model:"claude-sonnet-4-6",protocol:"anthropic-messages"},"openai-codex":{aliases:["openai-codex","openai-oauth","codex","codex-oauth"],clientId:"app_EMoamEEZ73f0CkXaXp7hrann",issuer:"https://auth.openai.com",tokenUrl:"https://auth.openai.com/oauth/token",baseUrl:"https://chatgpt.com/backend-api/codex",model:"gpt-5.6-sol",protocol:"responses"},"xai-oauth":{aliases:["xai-oauth","xai","grok","grok-oauth"],clientId:"b1a00492-073a-47ea-816f-4c329264a828",issuer:"https://auth.x.ai",discoveryUrl:"https://auth.x.ai/.well-known/openid-configuration",deviceUrl:"https://auth.x.ai/oauth2/device/code",scope:"openid profile email offline_access grok-cli:access api:access",baseUrl:"https://api.x.ai/v1",model:"grok-4.5",protocol:"responses"}}),Le=12e4;Do={createOAuthStore:pt,getOAuthStore:se,hasOAuthCredentials:Ln,loginOAuth:On,oauthProviderConfig:dt,oauthProviderId:q,oauthRuntimeConfig:In,refreshOAuthCredentials:mt,resolveOAuthCredentials:Cn}});V();import C from"node:fs";import E from"node:path";import{spawnSync as di}from"node:child_process";import vt from"node:fs";import nr from"node:path";var tr=Object.freeze([{key:"hyperliquid",aliases:["hl","hyperevm","hype","999"],chainId:999,name:"hyperliquid",kind:"evm",family:"hyperliquid",agent:"hyperliquid-agent",note:"perps \xB7 hip-3/4 \xB7 hyperevm 999",build:!0},{key:"ethereum",aliases:["eth","mainnet","1"],chainId:1,name:"ethereum",kind:"evm",family:"evm",agent:"oracle",note:"l1 \xB7 bridge hub",build:!0},{key:"base",aliases:["8453"],chainId:8453,name:"base",kind:"evm",family:"evm",agent:"oracle",note:"evm l2",build:!0},{key:"arbitrum",aliases:["arb","42161"],chainId:42161,name:"arbitrum",kind:"evm",family:"evm",agent:"oracle",note:"evm l2",build:!0},{key:"optimism",aliases:["op","10"],chainId:10,name:"optimism",kind:"evm",family:"evm",agent:"oracle",note:"op mainnet",build:!0},{key:"polygon",aliases:["matic","137"],chainId:137,name:"polygon",kind:"evm",family:"evm",agent:"oracle",note:"evm l2",build:!0},{key:"bsc",aliases:["bnb","56"],chainId:56,name:"bnb chain",kind:"evm",family:"evm",agent:"oracle",note:"bsc",build:!0},{key:"avalanche",aliases:["avax","43114"],chainId:43114,name:"avalanche",kind:"evm",family:"evm",agent:"oracle",note:"c-chain",build:!0},{key:"abstract",aliases:["abs","2741"],chainId:2741,name:"abstract",kind:"evm",family:"evm",agent:"oracle",note:"open / add agent",build:!0},{key:"stable",aliases:["988"],chainId:988,name:"stable",kind:"evm",family:"stable",agent:"stable-agent",note:"usdt0 gas \xB7 stable agent",build:!0},{key:"robinhood",aliases:["rh","4663"],chainId:4663,name:"robinhood",kind:"evm",family:"robinhood",agent:"robinhood-agent",note:"rh chain 4663",build:!0},{key:"solana",aliases:["sol"],chainId:"SOL",name:"solana",kind:"svm",family:"solana",agent:"solana-agent",note:"jup \xB7 nfts \xB7 dexs",build:!0},{key:"bitcoin",aliases:["btc"],chainId:"BTC",name:"bitcoin",kind:"utxo",family:"bitcoin",agent:"bitcoin-agent",note:"ord \xB7 runes \xB7 l1",build:!0},{key:"polymarket",aliases:["poly","polygon-poly"],chainId:137,name:"polymarket",kind:"venue",family:"polymarket",agent:"polymarket-agent",note:"prediction markets (polygon venue)",build:!1}]);function $e(e){return String(e||"").trim().toLowerCase().replace(/^\/+/,"").replace(/\s+/g,"-")}function wt(e){let t=$e(e);if(!t)return null;for(let n of tr)if(n.key===t||String(n.chainId).toLowerCase()===t||(n.aliases||[]).map($e).includes(t)||$e(n.name)===t)return n;return null}V();function rr(){return nr.join(U(),"active-chain.json")}function or(){let e=rr();if(!vt.existsSync(e))return null;try{let t=JSON.parse(vt.readFileSync(e,"utf8"));if(!t||typeof t!="object"||!t.key)return null;let n=wt(t.key);return n?{key:n.key,chainId:n.chainId,name:n.name,agent:n.agent,selectedAt:t.selectedAt||null}:null}catch{return null}}function ge(e={}){let t=or(),n={...process.env,...e};return t&&(n.ORACLE_ACTIVE_CHAIN=t.key,n.ORACLE_ACTIVE_CHAIN_ID=String(t.chainId),n.ORACLE_ACTIVE_AGENT=t.agent||"oracle"),n}V();import kt from"node:fs";import ir from"node:path";var sr=new Set(["auto","standalone","hermes","remote","arch"]),ar=new Set(["openrouter","openai","xai","deepseek","gemini","custom","anthropic-oauth","openai-codex","xai-oauth"]);function cr(){return ir.join(U(),"model.json")}function K(e){return String(e||"").trim()||void 0}function ur(e={}){let t=K(e.backend)?.toLowerCase()||"auto",n=K(e.provider)?.toLowerCase(),r=K(e.model),o=K(e.baseUrl)?.replace(/\/+$/,""),i=K(e.apiKeyEnv),s=Number.parseInt(String(e.contextLength||""),10),c=K(e.reasoningEffort),u=K(e.computeHost||e.remoteHost),a=K(e.computeUser||e.remoteUser),f=K(e.computePath||e.remotePath);if(!sr.has(t))throw new Error(`unsupported backend: ${t}`);if(process.env.ORACLE_PUBLIC_DESKTOP==="1"&&["remote","arch"].includes(t))throw new Error("remote compute backends are disabled in the public desktop");if(n&&!ar.has(n))throw new Error(`unsupported provider: ${n}`);if(o&&n!=="custom")throw new Error("baseUrl is only supported for the custom provider");if(i&&!/^[A-Z][A-Z0-9_]*$/.test(i))throw new Error("api key env must be an uppercase environment variable name");if(n==="custom"&&!o)throw new Error("custom provider requires baseUrl");if(t==="standalone"&&!r)throw new Error("standalone backend requires a model");if(t==="remote"&&!u)throw new Error("remote backend requires computeHost");return{backend:t,...n?{provider:n}:{},...r?{model:r}:{},...o?{baseUrl:o}:{},...i?{apiKeyEnv:i}:{},...Number.isFinite(s)&&s>0?{contextLength:s}:{},...c?{reasoningEffort:c}:{},...u?{computeHost:u}:{},...a?{computeUser:a}:{},...f?{computePath:f}:{}}}function St(){let e=cr();if(!kt.existsSync(e))return null;try{return ur(JSON.parse(kt.readFileSync(e,"utf8")))}catch{return null}}import{spawn as lr}from"node:child_process";var fr=["SIGINT","SIGTERM","SIGHUP"];function ye(e,t=[],n={},r=e){return new Promise(o=>{let i=lr(e,t,n),s=!1,c=null,u=new Map(fr.map(f=>[f,()=>{c||=f,i.exitCode===null&&i.signalCode===null&&i.kill(f)}]));for(let[f,p]of u)process.on(f,p);let a=()=>{for(let[f,p]of u)process.off(f,p)};i.once("error",f=>{s||(s=!0,a(),process.stderr.write(`oracle: could not start ${r}: ${f.message}
4
+ `),o(1))}),i.once("exit",(f,p)=>{if(s)return;s=!0,a();let g=c||p;if(g){process.kill(process.pid,g);return}o(f??1)})})}import At from"node:fs";import te from"node:path";V();var dr="0.19.0",Ji=`hermes-agent==${dr}`;var Et="0.12.1",Vi=Object.freeze({posix:Object.freeze({url:`https://github.com/astral-sh/uv/releases/download/${Et}/uv-installer.sh`,sha256:"d3f5412d38c99f9d024901843bf98206f0d2c6dbe64df40d0b740e2751ca62c1"}),windows:Object.freeze({url:`https://github.com/astral-sh/uv/releases/download/${Et}/uv-installer.ps1`,sha256:"b9ec035151bfbb11d616dbd69886498d885551489eddf095ea3c0ad59f640eb0"})});function pr(){return te.join(U(),"runtime")}function mr(){return te.join(pr(),"venv")}function hr(e){let t=process.platform==="win32"?"Scripts":"bin",n=process.platform==="win32"?`${e}.exe`:e;return te.join(mr(),t,n)}function xr(){return hr("hermes")}function gr(e){let t=process.platform==="win32"&&!te.extname(e)?["",".exe",".cmd",".bat"]:[""];for(let n of(process.env.PATH||"").split(te.delimiter))if(n)for(let r of t){let o=te.join(n,`${e}${r}`);try{if(At.existsSync(o))return o}catch{}}return null}function Pe(){if(process.env.ORACLE_HERMES_BIN)return{ok:!0,bin:process.env.ORACLE_HERMES_BIN,source:"env"};let e=gr("hermes");if(e)return{ok:!0,bin:e,source:"path"};let t=xr();return At.existsSync(t)?{ok:!0,bin:t,source:"managed"}:{ok:!1,bin:null,source:null}}import{EventEmitter as Vr}from"node:events";import{spawn as yr}from"node:child_process";import{EventEmitter as br}from"node:events";import{createInterface as Ot}from"node:readline";var _r=15e3,wr=12e4;function vr(e){let t=typeof e=="string"?e:e?.message||"Gateway request failed",n=new Error(t);return n.error=e,n}function kr(e){let t=Buffer.from(e);if(t.length<=4096)return e;let n=t.length-4096;return`${t.subarray(0,4096).toString("utf8")} ... [truncated ${n} bytes]`}function Ct({python:e,pythonArgs:t=[],cwd:n,env:r,spawnFn:o=yr,startupTimeoutMs:i=_r,requestTimeoutMs:s=wr}={}){let c=new br,u=new Map,a=null,f=1,p=null,g=null,x=!1;function w(l){c.listenerCount("error")>0&&c.emit("error",l)}function S(l){for(let h of u.values())clearTimeout(h.timer),h.reject(l);u.clear()}function k(l){if(!("id"in l)){c.emit("event",l);return}let h=u.get(l.id);h&&(u.delete(l.id),clearTimeout(h.timer),"error"in l?h.reject(vr(l.error)):h.resolve(l.result))}function b(){return p||(p=new Promise((l,h)=>{let _=!1,y,m=I=>{_||(_=!0,clearTimeout(y),I?h(I):l())};try{a=o(e,[...t,"-m","tui_gateway.entry"],{cwd:n,env:r})}catch(I){m(I),w(I);return}let A=Ot({input:a.stdout}),M=Ot({input:a.stderr});A.on("line",I=>{let F;try{F=JSON.parse(I)}catch{c.emit("log",I);return}m(),k(F)}),M.on("line",I=>c.emit("log",kr(I))),a.once("error",I=>{m(I),S(I),w(I)}),a.once("exit",(I,F)=>{x=!0;let ae=new Error(`Gateway exited with code ${I} and signal ${F}`);m(ae),S(ae),c.emit("exit",{code:I,signal:F})}),y=setTimeout(()=>{m(new Error(`Gateway startup timed out after ${i} ms`))},i)}),p)}function v(l,h){if(!a||x)return Promise.reject(new Error("Gateway is not running"));let _=f++;return new Promise((y,m)=>{let A=setTimeout(()=>{u.delete(_),m(new Error(`Gateway request ${_} timed out after ${s} ms`))},s);u.set(_,{resolve:y,reject:m,timer:A});try{a.stdin.write(`${JSON.stringify({id:_,method:l,params:h})}
5
+ `)}catch(M){clearTimeout(A),u.delete(_),m(M)}})}function d(){if(g)return g;if(!a||x)return Promise.resolve();let l=new Error("Gateway stopped while requests were pending");return S(l),g=new Promise(h=>{a.once("exit",h);try{a.kill()}catch{h()}}),g}return{start:b,request:v,stop:d,on(l,h){return c.on(l,h),this},off(l,h){return c.off(l,h),this}}}var fe=Buffer.alloc(0),Sr=new Set(["return","backspace","tab","escape","up","down","left","right","home","end","delete","insert","pageup","pagedown","unknown"]),Er={A:"up",B:"down",C:"right",D:"left",H:"home",F:"end",P:"f1",Q:"f2",R:"f3",S:"f4"},Ar={1:"home",2:"insert",3:"delete",4:"end",5:"pageup",6:"pagedown",7:"home",8:"end"};function P({name:e=null,ctrl:t=!1,meta:n=!1,shift:r=!1,sequence:o=""}){return{name:e,ctrl:t,meta:n,shift:r,sequence:o}}function Rt(e){return e<128?1:e>=240?4:e>=224?3:e>=192?2:1}function Or(e){return e>=64&&e<=126}function Lt(e){let t=e.toLowerCase();return P({name:t,shift:e!==t,sequence:e})}function Cr(e){return e===13?P({name:"return",sequence:"\r"}):e===10?P({name:"return",sequence:`
6
+ `}):e===9?P({name:"tab",sequence:" "}):e===127?P({name:"backspace",sequence:"\x7F"}):e===8?P({name:"backspace",sequence:"\b"}):e>=1&&e<=26?P({name:String.fromCharCode(e+96),ctrl:!0,sequence:String.fromCharCode(e)}):P({name:"unknown",sequence:String.fromCharCode(e)})}function Lr(e){let t=/^\u001b[\[O](\d*)(?:;(\d+))?(.)$/s.exec(e);if(!t)return P({name:"unknown",sequence:e});let n=t[1]===""?null:Number(t[1]),r=t[2]===void 0?null:Number(t[2]),o=t[3],i=null,s=r;if(o==="~"?i=Ar[n]??null:(i=Er[o]??null,s===null&&n!==null&&n>1&&(s=n)),!i)return P({name:"unknown",sequence:e});let c=s===null?0:Math.max(0,s-1);return P({name:i,shift:(c&1)!==0,meta:(c&2)!==0,ctrl:(c&4)!==0,sequence:e})}function Ir(e,t,n,r){let o=()=>(n.push(P({name:"escape",sequence:"\x1B"})),1);if(t+1>=e.length)return r?o():0;let i=e[t+1];if(i===91||i===79){let a=t+2;for(;a<e.length&&!Or(e[a]);)a+=1;return a>=e.length?r?o():0:(n.push(Lr(e.toString("utf8",t,a+1))),a+1-t)}if(i===27)return o();let s=Rt(i);if(t+1+s>e.length)return r?o():0;let c=e.toString("utf8",t+1,t+1+s),u=c.toLowerCase();return n.push(P({name:u,meta:!0,shift:c!==u,sequence:`\x1B${c}`})),1+s}function It(e,t){let n=[],r=0;for(;r<e.length;){let o=e[r];if(o===27){let s=Ir(e,r,n,t);if(s===0)return{keys:n,rest:Buffer.from(e.subarray(r))};r+=s;continue}if(o<32||o===127){n.push(Cr(o)),r+=1;continue}let i=Rt(o);if(r+i>e.length)return t?(n.push(Lt(e.toString("utf8",r))),{keys:n,rest:fe}):{keys:n,rest:Buffer.from(e.subarray(r))};n.push(Lt(e.toString("utf8",r,r+i))),r+=i}return{keys:n,rest:fe}}function Tt(e){return Buffer.isBuffer(e)?e:e==null?fe:typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}function Tr(){let e=fe;return{push(t){let n=e.length===0?Tt(t):Buffer.concat([e,Tt(t)]),{keys:r,rest:o}=It(n,!1);return e=o,r},flush(){if(e.length===0)return[];let{keys:t}=It(e,!0);return e=fe,t},get pending(){return e.length}}}function Rr({history:e=[]}={}){let t=[...e];return{buffer:"",cursor:0,history:t,historyIndex:t.length,draft:""}}function Ne(e,t){if(t<=0)return 0;let n=t-1,r=e.charCodeAt(n);if(r>=56320&&r<=57343&&n>0){let o=e.charCodeAt(n-1);if(o>=55296&&o<=56319)return n-1}return n}function je(e,t){if(t>=e.length)return e.length;let n=e.charCodeAt(t);return n>=55296&&n<=56319&&t+1<e.length?t+2:t+1}function O(e,t){return{...e,...t}}function $t(e,t){return O(e,{...t,historyIndex:e.history.length,draft:""})}function $r(e){if(e.ctrl||e.meta||!e.sequence||Sr.has(e.name))return!1;for(let t of e.sequence){let n=t.codePointAt(0);if(n<32||n===127)return!1}return!0}function Pr(e,t){let n=t;for(;n>0&&/\s/.test(e[n-1]);)n-=1;for(;n>0&&!/\s/.test(e[n-1]);)n-=1;return n}function Nr(e){if(e.historyIndex<=0)return{state:O(e,{}),action:null};let t=e.historyIndex>=e.history.length,n=e.historyIndex-1,r=e.history[n]??"";return{state:O(e,{buffer:r,cursor:r.length,historyIndex:n,draft:t?e.buffer:e.draft}),action:null}}function jr(e){if(e.historyIndex>=e.history.length)return{state:O(e,{}),action:null};let t=e.historyIndex+1,n=t>=e.history.length,r=n?e.draft:e.history[t]??"";return{state:O(e,{buffer:r,cursor:r.length,historyIndex:t,draft:n?"":e.draft}),action:null}}function Fr(e){let t=e.buffer.trim();if(t==="")return{state:$t(e,{buffer:"",cursor:0}),action:null};let n=e.history[e.history.length-1]===t?[...e.history]:[...e.history,t];return{state:O(e,{buffer:"",cursor:0,history:n,historyIndex:n.length,draft:""}),action:{type:"submit",value:t}}}function Mr(e,t){if(!t)return{state:O(e,{}),action:null};let{buffer:n,cursor:r}=e;if(t.ctrl&&!t.meta)switch(t.name){case"c":return{state:$t(e,{buffer:"",cursor:0}),action:{type:"cancel"}};case"d":return n===""?{state:O(e,{}),action:{type:"eof"}}:{state:O(e,{}),action:null};case"l":return{state:O(e,{}),action:{type:"clear"}};case"a":return{state:O(e,{cursor:0}),action:null};case"e":return{state:O(e,{cursor:n.length}),action:null};case"u":return{state:O(e,{buffer:n.slice(r),cursor:0}),action:null};case"k":return{state:O(e,{buffer:n.slice(0,r)}),action:null};case"w":{let o=Pr(n,r);return{state:O(e,{buffer:n.slice(0,o)+n.slice(r),cursor:o}),action:null}}case"b":return{state:O(e,{cursor:Ne(n,r)}),action:null};case"f":return{state:O(e,{cursor:je(n,r)}),action:null};default:return{state:O(e,{}),action:null}}switch(t.name){case"return":return Fr(e);case"left":return{state:O(e,{cursor:Ne(n,r)}),action:null};case"right":return{state:O(e,{cursor:je(n,r)}),action:null};case"home":return{state:O(e,{cursor:0}),action:null};case"end":return{state:O(e,{cursor:n.length}),action:null};case"up":return Nr(e);case"down":return jr(e);case"backspace":{if(r===0)return{state:O(e,{}),action:null};let o=Ne(n,r);return{state:O(e,{buffer:n.slice(0,o)+n.slice(r),cursor:o}),action:null}}case"delete":{if(r>=n.length)return{state:O(e,{}),action:null};let o=je(n,r);return{state:O(e,{buffer:n.slice(0,r)+n.slice(o)}),action:null}}default:break}if($r(t)){let o=t.sequence;return{state:O(e,{buffer:n.slice(0,r)+o+n.slice(r),cursor:r+o.length}),action:null}}return{state:O(e,{}),action:null}}function Pt(e={}){let{stdin:t,stdout:n,history:r=[],onSubmit:o,onCancel:i,onEof:s,onClear:c,onRender:u}=e,a=t??process.stdin,f=n??process.stdout,p=Tr(),g={submit:o,cancel:i,eof:s,clear:c},x=Rr({history:r}),w=!1,S=!1,k=!1,b=d=>{if(!d)return;let l=g[d.type];typeof l=="function"&&l(d.value,x)},v=d=>{for(let l of p.push(d)){let h=Mr(x,l);x=h.state,b(h.action),typeof u=="function"&&u(x)}};return{start(){w||(w=!0,a.isTTY&&typeof a.setRawMode=="function"&&(k=a.isRaw===!0,a.setRawMode(!0),S=!0),typeof a.resume=="function"&&a.resume(),a.on("data",v),typeof u=="function"&&u(x))},stop(){w&&(w=!1,typeof a.off=="function"?a.off("data",v):typeof a.removeListener=="function"&&a.removeListener("data",v),S&&typeof a.setRawMode=="function"&&(a.setRawMode(k),S=!1),typeof a.pause=="function"&&a.pause())},getState(){return x},setState(d){return x=d,x},write(d){f&&typeof f.write=="function"&&f.write(d)},get isRunning(){return w}}}var Fe="\x1B[?25l",be="\x1B[?25h",Nt="\x1B[2K",_e="\x1B[0J";var Ur="\x1B\\[[0-9;?]*[a-zA-Z]";function Mt(){return new RegExp(Ur,"g")}function Dr(e){return String(e??"").replace(Mt(),"")}function jt(e,t){return t.some(([n,r])=>e>=n&&e<=r)}function Ut(e){return e===0||e<32||e>=127&&e<160||jt(e,[[768,879],[1155,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1552,1562],[1611,1631],[1648,1648],[1750,1757],[1759,1764],[1767,1768],[1770,1773],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2070,2073],[2075,2083],[2085,2087],[2089,2093],[2137,2139],[2259,2273],[2275,2307],[2362,2364],[2369,2376],[2381,2381],[2385,2391],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2641,2641],[2672,2673],[2677,2677],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2884],[2893,2893],[2902,2902],[2914,2915],[2946,2946],[3008,3008],[3021,3021],[3072,3072],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3170,3171],[3201,3201],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3329,3329],[3393,3396],[3405,3405],[3426,3427],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3981,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4151],[4153,4154],[4157,4158],[4184,4185],[4190,4192],[4209,4212],[4226,4226],[4229,4230],[4237,4237],[4253,4253],[4957,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6277,6278],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6683,6683],[6742,6742],[6744,6750],[6752,6752],[6754,6754],[6757,6764],[6771,6780],[6783,6783],[6832,6911],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7040,7041],[7074,7077],[7080,7081],[7083,7085],[7142,7142],[7144,7145],[7149,7149],[7151,7153],[7212,7219],[7222,7223],[7376,7378],[7380,7392],[7394,7400],[7405,7405],[7412,7412],[7416,7417],[7616,7679],[8203,8207],[8234,8238],[8288,8292],[8294,8303],[8400,8447],[65024,65039],[65056,65071],[917760,917999]])?0:jt(e,[[4352,4447],[8986,8987],[9001,9002],[9193,9196],[9200,9200],[9203,9203],[9725,9726],[9748,9749],[9800,9811],[9855,9855],[9875,9875],[9889,9889],[9898,9899],[9917,9918],[9924,9925],[9934,9934],[9940,9940],[9962,9962],[9970,9971],[9973,9973],[9978,9978],[9981,9981],[9989,9989],[9994,9995],[10024,10024],[10060,10060],[10062,10062],[10067,10069],[10071,10071],[10133,10135],[10160,10160],[10175,10175],[11035,11036],[11088,11088],[11093,11093],[11904,12350],[12352,42191],[44032,55203],[63744,64255],[65040,65049],[65072,65135],[65280,65376],[65504,65510],[127744,128591],[129280,129535],[131072,262141]])?2:1}function Br(e){let t=0;for(let n of Array.from(e))t+=Ut(n.codePointAt(0));return t}function Kr(e){return Br(Dr(e))}function Hr(e){return/^\u001b\[0*m$/.test(e)}function Ft(e,t){let n="",r=0;for(let o of Array.from(e)){let i=Ut(o.codePointAt(0));if(r+i>t)break;n+=o,r+=i}return{text:n,width:r}}function zr(e,t){let n=String(e??"");if(t<=0)return"";if(Kr(n)<=t)return n;let r=Mt(),o="",i=0,s=!1,c=0,u=r.exec(n);for(;u!==null;){let f=Ft(n.slice(c,u.index),t-i);if(o+=f.text,i+=f.width,i>=t)return s?`${o}\x1B[0m`:o;o+=u[0],u[0].endsWith("m")&&(s=!Hr(u[0])),c=u.index+u[0].length,u=r.exec(n)}let a=Ft(n.slice(c),t-i);return o+=a.text,s?`${o}\x1B[0m`:o}function qr(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function Dt({stdout:e,rows:t,columns:n}={}){if(!e||typeof e.write!="function")throw new TypeError("createRenderer requires a stdout with a write(string) method");let r=Number.isFinite(t)?Math.trunc(t):null,o=Number.isFinite(n)?Math.trunc(n):null,i=r??(Number.isFinite(e.rows)?Math.trunc(e.rows):24),s=o??(Number.isFinite(e.columns)?Math.trunc(e.columns):80),c=[],u=0,a=null,f=!1,p=!1,g=()=>{r===null&&(i=Number.isFinite(e.rows)?Math.trunc(e.rows):24),o===null&&(s=Number.isFinite(e.columns)?Math.trunc(e.columns):80),f=!0},x=typeof e.on=="function";x&&e.on("resize",g);function w(b){let v=b-u;return u=b,v===0?"":v<0?`\x1B[${-v}A`:`\x1B[${v}B`}function S(b){let d=(Array.isArray(b)?b:[]).map(l=>zr(String(l??""),s));if(a!==null)for(d.length>a&&(d=d.slice(0,a));d.length<a;)d.push("");return d}function k(b){if(!f&&qr(c,b))return;let v=[Fe];f&&c.length>0&&(v.push(w(0),"\r",_e),c=[],u=0),f=!1;let d=Math.min(c.length,b.length);for(let l=0;l<d;l+=1)c[l]!==b[l]&&v.push(w(l),"\r",Nt,b[l]);if(b.length>c.length){c.length>0&&v.push(w(c.length-1));for(let l=c.length;l<b.length;l+=1)l>0&&v.push(`
7
+ `),v.push("\r",Nt,b[l]),u=l}else b.length<c.length&&v.push(w(b.length),"\r",_e);b.length>0&&v.push(w(b.length-1)),v.push(be),c=b,e.write(v.join(""))}return{render(b){p||k(S(b))},writeAbove(b){if(p)return;let v=String(b??""),d=Fe;c.length>0&&(d+=`${w(0)}\r${_e}`),d+=v.endsWith(`
8
+ `)||v===""?v:`${v}
9
+ `,e.write(d);let l=c;c=[],u=0,l.length>0?k(l):e.write(be)},clear(){if(p)return;let b=Fe;c.length>0&&(b+=`${w(0)}\r${_e}`),b+=be,e.write(b),c=[],u=0,f=!1},setLines(b){a=Number.isFinite(b)&&b>=0?Math.trunc(b):null},getLines(){return c.slice()},getSize(){return{rows:i,columns:s}},dispose(){if(!p){if(p=!0,x){let b=typeof e.off=="function"?e.off:e.removeListener;typeof b=="function"&&b.call(e,"resize",g)}e.write(be)}}}}var T=Object.freeze({accent:"#B8F0FF",prompt:"#B8F0FF",banner_title:"#B8F0FF",banner_accent:"#91C2D7",ui_label:"#A5D9EB",banner_text:"#EAF2F8",status_bar_strong:"#EAF2F8",banner_border:"#455867",input_rule:"#455867",session_border:"#455867",banner_dim:"#60717F",status_bar_dim:"#60717F",status_bar_bg:"#11161B",status_bar_text:"#91A2B1",ok:"#7EE7B5",error:"#FF7B7B",warn:"#F0C674",bad:"#FF9B71",selection_bg:"#23313B"});function Wr(e){if(typeof e!="string")return null;let t=e.startsWith("#")?e.slice(1):e;if(!/^(?:[\da-f]{3}|[\da-f]{6})$/i.test(t))return null;let n=t.length===3?[...t].map(r=>r.repeat(2)).join(""):t;return{r:Number.parseInt(n.slice(0,2),16),g:Number.parseInt(n.slice(2,4),16),b:Number.parseInt(n.slice(4,6),16)}}function Bt(e,t,n){let r=Wr(t);return r?`\x1B[${e};2;${r.r};${r.g};${r.b}m${String(n)}\x1B[0m`:String(n)}function Me({color:e=!0}={}){return e&&!Object.hasOwn(process.env,"NO_COLOR")?Object.freeze({fg:(n,r)=>Bt(38,n,r),bg:(n,r)=>Bt(48,n,r),bold:n=>`\x1B[1m${String(n)}\x1B[0m`,dim:n=>`\x1B[2m${String(n)}\x1B[0m`}):Object.freeze({fg:(n,r)=>String(r),bg:(n,r)=>String(r),bold:n=>String(n),dim:n=>String(n)})}var os=Me();function Kt(e){return String(e).replace(/\u001B\[[0-9;]*m/g,"")}var Ht=Object.freeze([["#B8F0FF"," \u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588 "],["#B8F0FF"," \u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588 \u2591\u2591\u2591\u2591\u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588 "],["#ACDEEF"," \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2591\u2591 \u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2591\u2591 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2588 "],["#A5D9EB"," \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588\u2591\u2591\u2591 "],["#9FCBDD"," \u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588 "],["#B8F0FF"," \u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591 "]]),Ue="THE FUTURE IS AGENTIC / by DEMI",De=/\u001B\[[0-9;]*m/g;function qt(e){if(new RegExp("\\p{Mark}","u").test(e))return 0;let t=e.codePointAt(0);return t===8205||t===65039?0:t>=4352&&(t<=4447||t===9001||t===9002||t>=11904&&t<=42191&&t!==12351||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65040&&t<=65049||t>=65072&&t<=65135||t>=65280&&t<=65376||t>=65504&&t<=65510||t>=127744&&t<=129791||t>=131072&&t<=262141)?2:t<32||t>=127&&t<160?0:1}function H(e){return[...Kt(e)].reduce((t,n)=>t+qt(n),0)}function Ke(e,t){if(t<=0)return"";let n=String(e).split(/(\u001B\[[0-9;]*m)/g),r="",o=0,i=!1;for(let s of n)if(s){if(De.test(s)){De.lastIndex=0,r+=s,i=s!=="\x1B[0m";continue}De.lastIndex=0;for(let c of s){let u=qt(c);if(o+u>t)return i?`${r}\x1B[0m`:r;r+=c,o+=u}}return r}function ne(e,t,n="left"){let r=Math.max(0,Math.floor(Number(t)||0)),o=Ke(String(e),r),i=Math.max(0,r-H(o));if(n==="right")return`${" ".repeat(i)}${o}`;if(n==="center"){let s=Math.floor(i/2);return`${" ".repeat(s)}${o}${" ".repeat(i-s)}`}return`${o}${" ".repeat(i)}`}function He(e,t){let n=Math.max(1,Math.floor(Number(t)||1)),r=[];for(let o of String(e??"").split(`
10
+ `)){if(o===""){r.push("");continue}let i="",s=0;for(let c of o.split(" ")){let u=H(c);if(s>0&&s+1+u>n&&(r.push(i),i="",s=0),u>n){s>0&&(r.push(i),i="",s=0);let a=c;for(;H(a)>n;){let f=Ke(a,n);r.push(f),a=a.slice(f.length)}i=a,s=H(a);continue}i=s===0?c:`${i} ${c}`,s=s===0?u:s+1+u}r.push(i)}return r}function Yr(e){let t=Math.max(0,Math.floor(Number(e)||0)),n=Math.max(36,Math.min(t-4,76)),r=Math.max(0,Math.floor((t-n)/2)),o=r+3,i=Math.max(0,n-6);return{target:t,panelWidth:n,panelLeft:r,contentLeft:o,inner:i}}function Gr(e){let t=1/0,n=-1;for(let r of e)for(let o=0;o<r.length;o+=1)r[o]!==" "&&(o<t&&(t=o),o>n&&(n=o));return n<0?{offset:0,width:0}:{offset:t,width:n-t+1}}function zt(e,t,n=0){let{target:r,contentLeft:o,inner:i}=e,c=Math.round((r-t)/2)-n-o,u=Math.max(0,i-t-n);return Math.max(0,Math.min(u,c))}function ze({width:e,palette:t}){let n=Yr(e),{target:r,panelWidth:o,panelLeft:i,inner:s}=n;if(r<72||s<=0)return[ne(t.bold(t.fg(T.accent,"oracle")),r,"center"),ne(t.fg(T.banner_text,Ue),r,"center")];let c=Ht.map(([,d])=>d),{offset:u,width:a}=Gr(c),f=" ".repeat(zt(n,a,u)),p=" ".repeat(zt(n,H(Ue))),g=[];for(let[d,l]of Ht)g.push(t.bold(t.fg(d,`${f}${l.replace(/\s+$/,"")}`)));g.push(""),g.push(t.bold(t.fg(T.banner_text,`${p}${Ue}`)));let x=d=>t.fg(T.banner_border,d),w=" ".repeat(i),S="\u2500".repeat(Math.max(0,o-2)),k=d=>ne(`${w}${d}`,r),b=[k(`${x("\u256D")}${x(S)}${x("\u256E")}`)],v=k(`${x("\u2502")}${" ".repeat(Math.max(0,o-2))}${x("\u2502")}`);b.push(v);for(let d of g)b.push(k(`${x("\u2502")} ${ne(d,s)} ${x("\u2502")}`));return b.push(v),b.push(k(`${x("\u2570")}${x(S)}${x("\u256F")}`)),b}function Wt({lines:e,width:t,palette:n,title:r=""}){let o=Math.max(2,Math.floor(Number(t)||0)),i=Math.max(0,o-2),s=Ke(String(r),Math.max(0,i-2)),c=s?` ${s} `:"",u=`${c}${"\u2500".repeat(Math.max(0,i-H(c)))}`,a=f=>n.fg(T.banner_border,f);return[`${a("\u256D")}${a(u)}${a("\u256E")}`,...e.map(f=>`${a("\u2502")}${ne(f,i)}${a("\u2502")}`),`${a("\u2570")}${a("\u2500".repeat(i))}${a("\u256F")}`]}function Be(e){let t=Number(e);return Number.isFinite(t)?t>=1e6?`${(t/1e6).toFixed(1).replace(/\.0$/,"")}M`:t>=1e3?`${(t/1e3).toFixed(0)}K`:String(Math.round(t)):"0"}function Jr(e,t){let n=Math.max(0,Math.floor(Number(t)||0)),r=Number(e),o=Number.isFinite(r)?Math.min(100,Math.max(0,r)):0,i=Math.round(n*o/100);return`${"\u2588".repeat(i)}${"\u2591".repeat(n-i)}`}function we(e){let t=Number(e);if(!Number.isFinite(t)||t<0)return"0s";let n=Math.floor(t/1e3);if(n<60)return`${n}s`;let r=Math.floor(n/60),o=n%60;return r<60?`${r}m${String(o).padStart(2,"0")}s`:`${Math.floor(r/60)}h${String(r%60).padStart(2,"0")}m`}function Yt({model:e,contextTokens:t,contextLength:n,percent:r,effort:o,thinking:i,chain:s,width:c,palette:u}){let a=Math.max(0,Math.floor(Number(c)||0)),f=u.fg(T.status_bar_dim," / "),p=a>=120?12:a>=60?8:4,g=Number(n)>0?`${Be(t)}/${Be(n)}`:Be(t),x=Number.isFinite(Number(r))?`${Math.round(Number(r))}%`:"0%",w=[{text:String(e??""),strong:!0}];Number(n)>0&&w.push({text:`ctx ${Jr(r,p)} ${g} ${x}`}),o&&w.push({text:String(o)}),i&&w.push({text:String(i)}),typeof s=="string"&&s.length>0&&w.push({text:s});let S=w,k=v=>v.reduce((d,l,h)=>d+H(l.text)+(h>0?3:0),0);for(;S.length>1&&k(S)>a;)S=S.slice(0,-1);let b=S.map(v=>v.strong?u.fg(T.status_bar_strong,v.text):u.fg(T.status_bar_text,v.text)).join(f);return u.bg(T.status_bar_bg,ne(b,a))}var Xr=6;function Qr(e=[]){let t={pass:[],query:null,model:null,provider:null,quiet:!1,cont:!1};for(let n=0;n<e.length;n+=1){let r=e[n];if((r==="-q"||r==="--query")&&e[n+1]){t.query=e[++n],t.pass.push("-q",t.query);continue}if((r==="--model"||r==="-m")&&e[n+1]){t.model=e[++n],t.pass.push("--model",t.model);continue}if(r==="--provider"&&e[n+1]){t.provider=e[++n],t.pass.push("--provider",t.provider);continue}if(r==="--quiet"||r==="-Q"){t.quiet=!0,t.pass.push(r);continue}if(r==="--continue"||r==="-c"){t.cont=!0,t.pass.push("--continue");continue}t.pass.push(r)}return t}function qe(e,t){if(!t||typeof t!="object")return;let n=Number(t.context_used??t.context_tokens??t.input??t.prompt),r=Number(t.context_max??t.context_length);Number.isFinite(n)&&n>0&&(e.contextTokens=n),Number.isFinite(r)&&r>0&&(e.contextLength=r);let o=Number(t.context_percent);Number.isFinite(o)?e.contextPercent=o:e.contextLength>0&&(e.contextPercent=Math.round(e.contextTokens/e.contextLength*100))}function Zr(e){let t=e.width,n=`${e.promptLabel} `,r=Math.max(1,t-2-H(n)),o=e.buffer||"",i=Math.max(0,Math.min(e.cursor??o.length,o.length)),s=0;i>r&&(s=i-r);let c=o.slice(s,s+r),u=i-s,a=c.slice(0,u),f=c.slice(u,u+1)||" ",p=c.slice(u+1),g=e.palette;return[`${g.fg(T.accent,n)}${a}${g.bg(T.selection_bg,f)}${p}`]}function eo(e){let t=e.width,n=[];if(e.liveLines.length>0){for(let r of e.liveLines.slice(-Xr))n.push(r);n.push("")}return n.push(...Wt({lines:Zr(e),width:t,palette:e.palette,title:"Ask Oracle \u203A"})),n.push(Yt({model:e.model,contextTokens:e.contextTokens,contextLength:e.contextLength,percent:e.contextPercent,effort:e.effort,thinking:e.thinking,chain:e.chain,width:t,palette:e.palette})),n}function to(e){let t=e?.params||e||{};return{type:t.type||e?.type||"",sessionId:t.session_id||e?.session_id||"",payload:t.payload||e?.payload||{}}}function ve(e={}){return typeof e.text=="string"?e.text:typeof e.rendered=="string"?e.rendered:typeof e.message=="string"?e.message:""}function no(e={}){let t=e.stdout||process.stdout,n=e.stdin||process.stdin,r=Math.max(20,Number(t.columns||e.columns||80)),o=e.palette||Me({color:t.isTTY!==!1}),i=e.renderer||Dt({stdout:t,rows:t.rows,columns:r}),s=e.client||Ct({python:e.python,pythonArgs:e.pythonArgs||[],cwd:e.cwd||process.cwd(),env:e.env||process.env,spawnFn:e.spawnFn,startupTimeoutMs:e.startupTimeoutMs,requestTimeoutMs:e.requestTimeoutMs}),c=new Vr,u=e.now||(()=>Date.now()),a={palette:o,width:r,promptLabel:"oracle \u203A",buffer:"",cursor:0,model:e.model||"model",contextTokens:0,contextLength:0,contextPercent:0,effort:e.effort||"",thinking:"0s",chain:(e.env||process.env).ORACLE_ACTIVE_CHAIN||"",busy:!1,cancelled:!1,sessionId:null,assistantBuffer:"",flushedLines:0,liveLines:[],startedAt:0},f=null,p=null,g={renderer:i,state:a};function x(){i.render(eo(a))}function w(y){i.writeAbove(`${y}
11
+ `)}function S(){let y=a.assistantBuffer.split(`
12
+ `),m=y[y.length-1]||"";a.liveLines=m?He(m,a.width):[]}function k({final:y=!1}={}){let m=a.assistantBuffer.split(`
13
+ `),A=y?m.length:m.length-1,M=!1;for(;a.flushedLines<A;){let I=m[a.flushedLines];for(let F of He(I,a.width))w(F);a.flushedLines+=1,M=!0}return y?a.liveLines=[]:S(),M}function b(){p||(p=setInterval(()=>{a.busy&&(a.thinking=we(u()-a.startedAt),x())},250),typeof p.unref=="function"&&p.unref())}function v(){p&&(clearInterval(p),p=null)}async function d(y){let m=String(y||"").trim();if(m){if(m==="/exit"||m==="/quit"){await _();return}if(m==="/clear"){i.clear();for(let A of ze({width:a.width,palette:o}))w(A);x();return}a.busy=!0,a.assistantBuffer="",a.flushedLines=0,a.liveLines=[],a.startedAt=u(),a.thinking="0s",w(`${o.bold(o.fg(T.prompt,"you"))} ${m}`),w(""),b(),x(),await s.request("prompt.submit",{session_id:a.sessionId,text:m})}}function l(y){let m=to(y);if(m.type!=="gateway.ready"){if(m.type==="session.info"&&m.payload){m.payload.model&&(a.model=m.payload.model),m.payload.reasoning_effort&&(a.effort=m.payload.reasoning_effort),qe(a,m.payload.usage),x();return}if(m.type==="message.start"){a.busy=!0,a.cancelled=!1,a.assistantBuffer="",a.flushedLines=0,a.liveLines=[],w(o.bold(o.fg(T.accent,"oracle"))),x();return}if(m.type==="thinking.delta"||m.type==="reasoning.delta"){if(a.cancelled)return;ve(m.payload).trim()&&(a.thinking=`${we(u()-a.startedAt)}`),x();return}if(m.type==="message.delta"){if(a.cancelled)return;a.assistantBuffer+=ve(m.payload),k(),x();return}if(m.type==="message.complete"){if(a.cancelled){a.cancelled=!1;return}let A=ve(m.payload);A&&A.length>=a.assistantBuffer.length&&(a.assistantBuffer=A),k({final:!0}),w(""),a.busy=!1,v(),qe(a,m.payload?.usage||m.payload?.context),a.thinking=we(u()-a.startedAt),x();return}m.type==="error"&&(a.busy=!1,v(),w(o.fg(T.error,`error: ${ve(m.payload)||"unknown"}`)),x())}}async function h(){await s.start(),s.on("event",l),s.on("log",m=>c.emit("log",m)),s.on("error",m=>c.emit("error",m));let y=await s.request("session.create",{cols:a.width,cwd:e.cwd||process.cwd(),source:"cli",profile:e.profile||"oracle",close_on_disconnect:!0,...e.model?{model:e.model}:{},...e.provider?{provider:e.provider}:{}});a.sessionId=y.session_id,a.model=y.info?.model||a.model,y.info?.reasoning_effort&&(a.effort=y.info.reasoning_effort),qe(a,y.info?.usage);for(let m of ze({width:a.width,palette:o}))w(m);w(""),x(),f=Pt({stdin:n,stdout:t,onSubmit:m=>{d(m).catch(A=>c.emit("error",A))},onCancel:()=>{a.busy&&(a.busy=!1,a.cancelled=!0,v(),k({final:!0}),w(o.fg(T.warn,"interrupted")),w(""),x(),s.request("session.interrupt",{session_id:a.sessionId}).catch(m=>c.emit("error",m)))},onEof:()=>{_().catch(m=>c.emit("error",m))},onClear:()=>{i.clear(),x()},onRender:m=>{a.buffer=m.buffer||"",a.cursor=m.cursor??a.buffer.length,x()}}),f.start()}async function _(){v(),f&&f.stop(),i.dispose(),await s.stop(),c.emit("stop")}return Object.freeze({start:h,stop:_,on:c.on.bind(c),off:c.off.bind(c),state:a,handleEvent:l,submit:d})}async function We({hermesPython:e,client:t,tuiFactory:n=no,args:r=[],env:o=process.env,cwd:i=process.cwd(),stdout:s=process.stdout,stdin:c=process.stdin}={}){let u=Qr(r);if(u.query)return{native:!1,pass:u.pass};if(!c.isTTY||!s.isTTY)return{native:!1,pass:u.pass};if(o.ORACLE_NATIVE_TUI==="0")return{native:!1,pass:u.pass};let a=e;if(!t&&!a)return{native:!1,pass:u.pass};let f=ge({...o,ORACLE_CHAT_SURFACE:"1",ORACLE_PROFILE:"oracle",ORACLE_NODE_BIN:process.execPath}),p=n({...t?{client:t}:{},...a?{python:a.command,pythonArgs:a.prefix||[]}:{},cwd:i,env:f,stdin:c,stdout:s,model:u.model,provider:u.provider,profile:"oracle"});return p.on("log",g=>{o.ORACLE_CLI_DEBUG&&process.stderr.write(`${g}
14
+ `)}),p.on("error",g=>{process.stderr.write(`oracle chat: ${g.message}
15
+ `)}),await p.start(),new Promise(g=>{let x=!1,w=async()=>{x||(x=!0,await p.stop(),g({native:!0,code:0}))};p.on("stop",()=>{x||(x=!0,g({native:!0,code:0}))}),process.once("SIGINT",w),process.once("SIGTERM",w)})}import ro from"node:fs";import Gt from"node:path";var Jt=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"},xai:{key:"XAI_API_KEY",baseUrl:"https://api.x.ai/v1",model:"grok-4-latest"},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"}}),oo=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-latest",protocol:"responses"}});function io(e,t){let n=Number(e);return Number.isSafeInteger(n)&&n>0?n:t}function so(e,t){let n=String(e.ORACLE_PROVIDER||t.provider||"").trim().toLowerCase();if(n)return n;if(e.ORACLE_BASE_URL||t.baseUrl)return"custom";for(let[r,o]of Object.entries(Jt))if(e[o.key]||o.alternateKey&&e[o.alternateKey])return r;return null}function ao(e=process.env,t={},n=()=>!1,r=()=>""){let o=so(e,t);if(!o)return null;let i=oo[o],s=Jt[o]||i,c=String(e.ORACLE_API_KEY_ENV||t.apiKeyEnv||""),u=String(e.ORACLE_API_KEY||c&&e[c]||s&&(e[s.key]||s.alternateKey&&e[s.alternateKey])||r(o)||""),a=String(i?i.baseUrl:o==="custom"?e.ORACLE_BASE_URL||t.baseUrl||"":s?.baseUrl||"").replace(/\/+$/,""),f=String(e.ORACLE_MODEL||t.model||s?.model||"");if(!a||!f)return null;let p=!!(i&&n(o));return i&&!p||!i&&o!=="custom"&&!u?null:{kind:"standalone",provider:o,model:f,baseUrl:a,...p?{authType:"oauth",protocol:i.protocol}:{apiKey:u},contextLength:io(e.ORACLE_CONTEXT_LENGTH||t.contextLength,128e3),reasoningEffort:String(e.ORACLE_REASONING_EFFORT||t.reasoningEffort||"high")}}function re(e=""){return["Oracle runs its own native chat \u2014 no Hermes or external agent required.","Set OPENROUTER_API_KEY, run `oracle auth login claude|codex|grok`, or configure a custom OpenAI-compatible endpoint.","`oracle harness detect` finds any Agent Plugins-compatible clients installed on this machine.",e].filter(Boolean).join(`
16
+ `)}function co(e=process.env,t={}){if(e.ORACLE_PUBLIC_DESKTOP==="1"||e.ORACLE_REMOTE_COMPUTE_DISABLE==="1")return null;let n=String(e.ORACLE_CHAT_BACKEND||t.backend||"auto").trim().toLowerCase(),r=String(e.ORACLE_COMPUTE_HOST||t.computeHost||"").trim();if(!["remote","arch"].includes(n)&&!e.ORACLE_COMPUTE_HOST||!r)return null;let o=String(e.ORACLE_COMPUTE_USER||t.computeUser||"").trim(),i=String(e.ORACLE_COMPUTE_PATH||t.computePath||"$HOME/.local/bin:/usr/local/bin:/usr/bin:/bin:/opt/homebrew/bin").trim();return{kind:"remote",host:r,user:o,path:i}}var uo=Object.freeze([{name:"oracle",bin:"oracle",label:"Oracle Native (default)",kind:"oracle"},{name:"hermes",bin:"hermes",label:"Hermes Agent",kind:"hermes"},{name:"opencode",bin:"opencode",label:"OpenCode",kind:"mcp"},{name:"claude",bin:"claude",label:"Claude Code",kind:"mcp"},{name:"codex",bin:"codex",label:"OpenAI Codex CLI",kind:"mcp"},{name:"cursor",bin:"cursor",label:"Cursor IDE",kind:"mcp"},{name:"windsurf",bin:"windsurf",label:"Windsurf",kind:"mcp"},{name:"aider",bin:"aider",label:"Aider",kind:"mcp"},{name:"continue",bin:"continue",label:"Continue",kind:"mcp"}]);function lo(e){for(let t of(process.env.PATH||"").split(Gt.delimiter)){let n=Gt.join(t,e);try{if(ro.existsSync(n))return n}catch{}}return null}function Vt({env:e=process.env,hermes:t={ok:!1},storedConfig:n=null,oauthAvailable:r=()=>!1,apiKeyResolver:o=()=>""}={}){let i=String(e.ORACLE_CHAT_BACKEND||n?.backend||"auto").trim().toLowerCase(),s=co(e,n||{});if(i==="remote"||i==="arch")return s?{kind:"remote",config:s}:{kind:"unconfigured",reason:re(`${i} compute backend was requested, but no compute host is configured.`)};let c=ao(e,n||{},r,o);if(i==="standalone")return c?{kind:"standalone",config:c}:{kind:"unconfigured",reason:re("ORACLE_CHAT_BACKEND=standalone was requested, but no standalone model is configured.")};if(i==="hermes")return t?.ok?{kind:"hermes",bin:t.bin}:{kind:"unconfigured",reason:re("ORACLE_CHAT_BACKEND=hermes was requested, but Hermes was not found.")};if(i!=="auto"){for(let u of uo)if(u.name===i){let a=lo(u.bin);return a?{kind:"harness",harness:{...u,path:a}}:{kind:"unconfigured",reason:re(`ORACLE_CHAT_BACKEND=${i} was requested, but ${u.bin} was not found on PATH.`)}}return{kind:"unconfigured",reason:re(`Unknown ORACLE_CHAT_BACKEND value: ${i}`)}}return s?{kind:"remote",config:s}:c?{kind:"standalone",config:c}:t?.ok?{kind:"hermes",bin:t.bin}:{kind:"unconfigured",reason:re()}}V();import Bo from"node:fs";import Nn from"node:path";import{randomUUID as Rn}from"node:crypto";import{EventEmitter as Ko}from"node:events";import{spawnSync as Ho}from"node:child_process";import{existsSync as Qt,readFileSync as fo}from"node:fs";import{dirname as Xt,join as Ye}from"node:path";import{fileURLToPath as po}from"node:url";function mo(e){let t=Xt(po(e));for(let n=0;n<8;n+=1){let r=Ye(t,"package.json");if(Qt(r))try{let i=JSON.parse(fo(r,"utf8"));if(i&&typeof i.version=="string")return t}catch{}let o=Xt(t);if(o===t)break;t=o}throw new Error(`oracle: could not resolve package root from ${e}`)}function ke(e,t){let n=mo(t),r=Ye(n,"dist","assets",e);return Qt(r)?r:Ye(n,e)}import Se from"node:fs";import Zt from"node:path";import{homedir as ho}from"node:os";var Je=process.env.ORACLE_CONFIG_DIR||Zt.join(ho(),".config","oracle"),en=Zt.join(Je,"memory.json"),Ge=2200;function tn(e){Se.existsSync(e)||Se.mkdirSync(e,{recursive:!0})}function Ve(){tn(Je);try{let e=Se.readFileSync(en,"utf8");return JSON.parse(e)}catch{return{version:1,updatedAt:new Date().toISOString(),entries:[]}}}function nn(e){tn(Je),e.updatedAt=new Date().toISOString(),Se.writeFileSync(en,JSON.stringify(e,null,2),{mode:384})}function rn(e,t){let n=Ve(),r=n.entries.findIndex(o=>o.key===e);for(r>=0?n.entries[r]={key:e,content:t,addedAt:new Date().toISOString()}:n.entries.push({key:e,content:t,addedAt:new Date().toISOString()});JSON.stringify(n.entries).length>Ge&&n.entries.length>1;)n.entries.shift();nn(n)}function on(e){let t=Ve(),n=t.entries.length;return t.entries=t.entries.filter(r=>r.key!==e),t.entries.length<n?(nn(t),{ok:!0}):{ok:!1}}function sn(){let e=Ve();if(e.entries.length===0)return"";let t=JSON.stringify(e.entries).length,n=Math.round(t/Ge*100),r=e.entries.map(o=>`${o.key}: ${o.content}`);return["\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",`MEMORY [${n}% \u2014 ${t}/${Ge} chars]`,"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",...r].join(`
17
+ `)}var an=[{type:"function",function:{name:"memory_add",description:"Save a durable fact to memory for future sessions.",parameters:{type:"object",properties:{key:{type:"string",description:"Short unique key"},content:{type:"string",description:"The fact to remember"}},required:["key","content"],additionalProperties:!1}}},{type:"function",function:{name:"memory_remove",description:"Remove a memory entry by key.",parameters:{type:"object",properties:{key:{type:"string",description:"The key to remove"}},required:["key"],additionalProperties:!1}}}];import L from"node:fs";import G from"node:path";import{homedir as xo}from"node:os";var go=process.env.ORACLE_CONFIG_DIR||G.join(xo(),".config","oracle"),oe=G.join(go,"skills"),de=ke("skills",import.meta.url),Xe=/^[a-z0-9][a-z0-9_-]{0,63}$/;function Qe(e){L.existsSync(e)||L.mkdirSync(e,{recursive:!0,mode:448});let t=L.lstatSync(e);if(t.isSymbolicLink()||!t.isDirectory())throw new Error("skills directory must be a real directory")}function cn(){return L.constants.O_NOFOLLOW||0}function Ee(e){let t=L.lstatSync(e);if(t.isSymbolicLink()||!t.isFile())return null;let n=L.openSync(e,L.constants.O_RDONLY|cn());try{return L.readFileSync(n,"utf8")}finally{L.closeSync(n)}}function yo(e,t){if(L.existsSync(e)){let r=L.lstatSync(e);if(r.isSymbolicLink()||!r.isFile())throw new Error("skill path must be a regular file")}let n=L.openSync(e,L.constants.O_WRONLY|L.constants.O_CREAT|L.constants.O_TRUNC|cn(),384);try{L.writeFileSync(n,t)}finally{L.closeSync(n)}try{L.chmodSync(e,384)}catch{}}function un(e){let t=String(e??"").trim();if(!Xe.test(t))throw new Error("invalid skill name");return G.join(oe,`${t}.md`)}function ln(e,t){let n=t.match(/^description:\s*(.+)$/m);return n?n[1].trim():t.split(`
18
+ `)[0].replace(/^#+\s*/,"").trim()||e}function bo(){let e=[];for(let t of L.readdirSync(de,{withFileTypes:!0})){let n,r;if(t.isFile()&&t.name.endsWith(".md"))n=t.name.replace(/\.md$/,""),r=G.join(de,t.name);else if(t.isDirectory()&&Xe.test(t.name))n=t.name,r=G.join(de,t.name,"SKILL.md");else continue;if(!Xe.test(n)||!L.existsSync(r))continue;let o=Ee(r);o!==null&&e.push({name:n,description:ln(n,o),path:r,size:o.length})}return e}function Ze(){try{Qe(oe);let e=new Map(bo().map(t=>[t.name,t]));for(let t of L.readdirSync(oe,{withFileTypes:!0})){if(!t.isFile()||!t.name.endsWith(".md"))continue;let n=G.join(oe,t.name),r=Ee(n);if(r===null)continue;let o=t.name.replace(/\.md$/,"");e.set(o,{name:o,description:ln(o,r),path:n,size:r.length})}return[...e.values()].sort((t,n)=>t.name.localeCompare(n.name))}catch{return[]}}function et(e){try{Qe(oe);let t=un(e);if(L.existsSync(t))return Ee(t);for(let n of[G.join(de,e,"SKILL.md"),G.join(de,`${e}.md`)]){if(!L.existsSync(n))continue;let r=Ee(n);if(r!==null)return r}return null}catch{return null}}function fn(e){let t=Ze();if(t.length===0)return`## Skills
19
19
  No skills installed. Use skill_create to save a successful workflow.
20
- `;let n=t;if(e){let o=e.toLowerCase();n=[...t].sort((i,c)=>{let a=(i.name.toLowerCase().includes(o)?2:0)+(i.description.toLowerCase().includes(o)?1:0);return(c.name.toLowerCase().includes(o)?2:0)+(c.description.toLowerCase().includes(o)?1:0)-a})}return["## Skills","Available (use skill_load <name>):",...n.map(o=>`- **${o.name}**: ${o.description}`)].join(`
21
- `)}function Zt(e,t){Vt(ce);let n=Xt(e);if(B.existsSync(n)&&!B.lstatSync(n).isFile())throw new Error("skill path must be a regular file");B.writeFileSync(n,t,{mode:384})}var en=[{type:"function",function:{name:"skill_load",description:"Load full content of a skill by name.",parameters:{type:"object",properties:{name:{type:"string",pattern:"^[a-z0-9][a-z0-9_-]{0,63}$",description:"Skill name using lowercase letters, digits, hyphens, or underscores"}},required:["name"],additionalProperties:!1}}},{type:"function",function:{name:"skill_create",description:"Save a new skill from a workflow or pattern.",parameters:{type:"object",properties:{name:{type:"string",pattern:"^[a-z0-9][a-z0-9_-]{0,63}$",description:"Lowercase letters, digits, hyphens, or underscores"},content:{type:"string",description:"Full SKILL.md content"}},required:["name","content"],additionalProperties:!1}}},{type:"function",function:{name:"skill_list",description:"List all installed skills.",parameters:{type:"object",properties:{},additionalProperties:!1}}}];import we from"node:fs";import nn from"node:path";import{homedir as ro}from"node:os";import{EventEmitter as oo}from"node:events";var We=process.env.ORACLE_CONFIG_DIR||nn.join(ro(),".config","oracle"),rn=nn.join(We,"cron.json");function on(e){we.existsSync(e)||we.mkdirSync(e,{recursive:!0})}function ae(){on(We);try{return JSON.parse(we.readFileSync(rn,"utf8"))}catch{return{version:1,jobs:[]}}}function Ye(e){on(We),we.writeFileSync(rn,JSON.stringify(e,null,2),{mode:384})}function ve(e){let t=String(e||"").toLowerCase().trim(),n=t.match(/^every\s+(\d+)\s*m/i);if(n)return parseInt(n[1])*6e4;let r=t.match(/^every\s+(\d+)\s*h/i);return r?parseInt(r[1])*36e5:t.includes("daily")?864e5:t.includes("hourly")?36e5:t.split(/\s+/).length===5?6e4:null}function Ge(){return ae().jobs}function Je(e){let t=ae(),n=`cron_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`,r=ve(e.schedule)||36e5,o={...e,id:n,createdAt:new Date().toISOString(),nextRunAt:new Date(Date.now()+r).toISOString()};return t.jobs.push(o),Ye(t),o}function Ve(e){let t=ae(),n=t.jobs.length;return t.jobs=t.jobs.filter(r=>r.id!==e),t.jobs.length<n?(Ye(t),!0):!1}function tn(e){let t=ae(),n=t.jobs.find(i=>i.id===e);if(!n)return;n.lastRunAt=new Date().toISOString();let r=ve(n.schedule)||36e5,o=n.lastRunAt?new Date(n.lastRunAt).getTime():Date.now();n.nextRunAt=new Date(o+r).toISOString(),Ye(t)}function sn(e){let t=new oo,n=new Map;function r(){let i=ae();for(let c of i.jobs){if(!c.enabled)continue;let a=ve(c.schedule);if(!a)continue;let u=setInterval(async()=>{try{t.emit("run",{id:c.id,name:c.name}),await e(c.prompt,c.skills),tn(c.id),t.emit("complete",{id:c.id,name:c.name})}catch(s){t.emit("error",{id:c.id,name:c.name,error:s})}},a);n.set(c.id,u)}t.emit("started",{count:n.size})}function o(){for(let[i,c]of n)clearInterval(c),n.delete(i);t.emit("stopped")}return{on:t.on.bind(t),off:t.off.bind(t),once:t.once.bind(t),emit:t.emit.bind(t),start:r,stop:o,add:i=>{let c=Je(i);if(c.enabled){let a=ve(c.schedule);if(a){let u=setInterval(async()=>{try{t.emit("run",{id:c.id,name:c.name}),await e(c.prompt,c.skills),tn(c.id),t.emit("complete",{id:c.id,name:c.name})}catch(s){t.emit("error",{id:c.id,name:c.name,error:s})}},a);n.set(c.id,u)}}return c},remove:i=>{let c=n.get(i);return c&&(clearInterval(c),n.delete(i)),Ve(i)},list:Ge}}var cn=[{type:"function",function:{name:"cron_add",description:"Schedule a recurring agent job.",parameters:{type:"object",properties:{name:{type:"string",description:"Human-readable name"},schedule:{type:"string",description:"'every 30m', 'daily', 'every 6h'"},prompt:{type:"string",description:"Agent prompt to run on schedule"},skills:{type:"array",items:{type:"string"},description:"Optional skill names"}},required:["name","schedule","prompt"],additionalProperties:!1}}},{type:"function",function:{name:"cron_list",description:"List all scheduled cron jobs.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"cron_remove",description:"Remove a cron job by id.",parameters:{type:"object",properties:{id:{type:"string",description:"Job id from cron_list"}},required:["id"],additionalProperties:!1}}}];var Se=[],io=5,so=1;function an(e){Se.push(e),Se.length>20&&Se.shift()}function un(){let e=Se.slice(-3);if(e.length<1)return null;let t=e[e.length-1];return t.toolCalls>=io&&t.errors===0?{shouldCreate:!0,suggestion:`You completed a ${t.toolCalls}-step workflow. Save it as a skill with skill_create.`}:e.filter(r=>r.errors>0&&r.recovered).length>=so&&t.toolCalls>=3?{shouldCreate:!0,suggestion:"You recovered from errors. Save the corrected approach as a skill."}:{shouldCreate:!1,suggestion:"No skill suggestions yet."}}var ln=[{type:"function",function:{name:"meta_analyze",description:"Analyze recent interactions and suggest skills to create.",parameters:{type:"object",properties:{},additionalProperties:!1}}}];import{homedir as Xe}from"node:os";import{join as Qe}from"node:path";var fn=process.env.ORACLE_PUBLIC_DESKTOP==="1",co=fn?process.env.ORACLE_CONFIG_DIR||Qe(Xe(),".config","oracle"):Qe(Xe(),".config","oracle"),vs=fn?co:Qe(Xe(),".config","mad-desk");function ao(e,t,n=""){let r=process.env[e];if(r!=null&&String(r).trim()!=="")return r;let o=t?process.env[t]:void 0;return o!=null&&String(o).trim()!==""?o:n}var uo=["0","false","off","no"];function dn(e,t,n=!0){let r=String(ao(e,t,"")).trim().toLowerCase();return r===""?n:!uo.includes(r)}var Co=new Set(["chain","data","scan","route","prepare"]),Io=new Set(["list","show"]),Lo=new Set(["call","catalog","health"]),To=new Set(["swap","bridge","prepare","prepare-bridge"]),$o=Object.freeze({"anthropic-oauth":"https://api.anthropic.com/v1","openai-codex":"https://chatgpt.com/backend-api/codex","xai-oauth":"https://api.x.ai/v1"}),ct=2e4,vn=6,Ro=Object.freeze({type:"function",function:{name:"oracle_cli",description:"Run a bounded read or prepare-only Oracle CLI command. It cannot sign or broadcast transactions.",parameters:{type:"object",properties:{argv:{type:"array",items:{type:"string"},minItems:1,maxItems:24,description:'Arguments after the oracle executable, for example ["scan","chains"] or ["data","health"].'}},required:["argv"],additionalProperties:!1}}}),ut=Object.freeze([Ro,...Jt,...en,...cn,...ln]);function Sn(e){let t=String(e||"");return t.length<=ct?t:`${t.slice(0,ct)}
22
- [truncated ${t.length-ct} chars]`}async function Po(e,t,n){switch(e){case"oracle_cli":return n(t.argv);case"memory_add":return Wt(t.key,t.content),{ok:!0,stored:t.key};case"memory_remove":return Yt(t.key);case"skill_load":{let r=ze(t.name);return r?{ok:!0,name:t.name,content:r}:{ok:!1,error:`skill not found: ${t.name}`}}case"skill_create":return Zt(t.name,t.content),{ok:!0,created:t.name};case"skill_list":return{ok:!0,skills:qe().map(o=>({name:o.name,description:o.description}))};case"cron_add":return{ok:!0,job:Je({name:t.name,schedule:t.schedule,prompt:t.prompt,skills:t.skills||[],enabled:!0})};case"cron_list":return{ok:!0,jobs:Ge()};case"cron_remove":return{ok:Ve(t.id),removed:t.id};case"meta_analyze":return{ok:!0,...un()||{shouldCreate:!1,suggestion:"No skill suggestions yet."}};default:return{ok:!1,error:`unknown tool: ${e}`}}}function No(e){if(!Array.isArray(e)||e.length===0||e.length>24)return"argv must contain 1 to 24 arguments";if(e.some(n=>typeof n!="string"||n.length>1e3))return"every argument must be a string no longer than 1000 characters";let t=e[0];return Co.has(t)?t==="chain"&&!Io.has(e[1]||"list")?`command not allowed: chain${e[1]?` ${e[1]}`:""}`:t==="data"&&!Lo.has(e[1]||"")?`command not allowed: data${e[1]?` ${e[1]}`:""}`:t==="route"&&!To.has(e[1]||"")?`command not allowed: route${e[1]?` ${e[1]}`:""}`:null:`command not allowed: ${t}`}async function jo(e,t={}){let n=No(e);if(n)return{ok:!1,error:n};let r=t.spawnFn||Oo,o=t.packageRoot||M,i=r(process.execPath,[kn.join(o,"bin","oracle.mjs"),...e],{encoding:"utf8",timeout:t.timeoutMs||45e3,maxBuffer:1024*1024,env:{...process.env,ORACLE_CHAT_TOOL:"1"}});return i.error?{ok:!1,error:i.error.message}:{ok:i.status===0,status:typeof i.status=="number"?i.status:1,stdout:Sn(i.stdout),stderr:Sn(i.stderr)}}function Mo(){let e=kn.join(M,"profiles","oracle","SOUL.md"),t=Eo.readFileSync(e,"utf8"),n=Gt(),r=Qt(),o=[t.trim()];return n&&o.push(n),o.push(r),o.push("You have tools for Oracle CLI commands, durable memory, skills, cron scheduling, and meta-learning.","Use memory_add to persist facts. Use skill_create to save successful workflows. Use cron_add to schedule recurring tasks."),o.join(`
20
+ `;let n=t;if(e){let o=e.toLowerCase();n=[...t].sort((i,s)=>{let c=(i.name.toLowerCase().includes(o)?2:0)+(i.description.toLowerCase().includes(o)?1:0);return(s.name.toLowerCase().includes(o)?2:0)+(s.description.toLowerCase().includes(o)?1:0)-c})}return["## Skills","Available (use skill_load <name>):",...n.map(o=>`- **${o.name}**: ${o.description}`)].join(`
21
+ `)}function dn(e,t){Qe(oe);let n=un(e);if(L.existsSync(n)&&!L.lstatSync(n).isFile())throw new Error("skill path must be a regular file");yo(n,t)}var pn=[{type:"function",function:{name:"skill_load",description:"Load full content of a skill by name.",parameters:{type:"object",properties:{name:{type:"string",pattern:"^[a-z0-9][a-z0-9_-]{0,63}$",description:"Skill name using lowercase letters, digits, hyphens, or underscores"}},required:["name"],additionalProperties:!1}}},{type:"function",function:{name:"skill_create",description:"Save a new skill from a workflow or pattern.",parameters:{type:"object",properties:{name:{type:"string",pattern:"^[a-z0-9][a-z0-9_-]{0,63}$",description:"Lowercase letters, digits, hyphens, or underscores"},content:{type:"string",description:"Full SKILL.md content"}},required:["name","content"],additionalProperties:!1}}},{type:"function",function:{name:"skill_list",description:"List all installed skills.",parameters:{type:"object",properties:{},additionalProperties:!1}}}];import Ae from"node:fs";import hn from"node:path";import{homedir as _o}from"node:os";import{EventEmitter as wo}from"node:events";var tt=process.env.ORACLE_CONFIG_DIR||hn.join(_o(),".config","oracle"),xn=hn.join(tt,"cron.json");function gn(e){Ae.existsSync(e)||Ae.mkdirSync(e,{recursive:!0})}function pe(){gn(tt);try{return JSON.parse(Ae.readFileSync(xn,"utf8"))}catch{return{version:1,jobs:[]}}}function nt(e){gn(tt),Ae.writeFileSync(xn,JSON.stringify(e,null,2),{mode:384})}function Oe(e){let t=String(e||"").toLowerCase().trim(),n=t.match(/^every\s+(\d+)\s*m/i);if(n)return parseInt(n[1])*6e4;let r=t.match(/^every\s+(\d+)\s*h/i);return r?parseInt(r[1])*36e5:t.includes("daily")?864e5:t.includes("hourly")?36e5:t.split(/\s+/).length===5?6e4:null}function rt(){return pe().jobs}function ot(e){let t=pe(),n=`cron_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`,r=Oe(e.schedule)||36e5,o={...e,id:n,createdAt:new Date().toISOString(),nextRunAt:new Date(Date.now()+r).toISOString()};return t.jobs.push(o),nt(t),o}function it(e){let t=pe(),n=t.jobs.length;return t.jobs=t.jobs.filter(r=>r.id!==e),t.jobs.length<n?(nt(t),!0):!1}function mn(e){let t=pe(),n=t.jobs.find(i=>i.id===e);if(!n)return;n.lastRunAt=new Date().toISOString();let r=Oe(n.schedule)||36e5,o=n.lastRunAt?new Date(n.lastRunAt).getTime():Date.now();n.nextRunAt=new Date(o+r).toISOString(),nt(t)}function yn(e){let t=new wo,n=new Map;function r(){let i=pe();for(let s of i.jobs){if(!s.enabled)continue;let c=Oe(s.schedule);if(!c)continue;let u=setInterval(async()=>{try{t.emit("run",{id:s.id,name:s.name}),await e(s.prompt,s.skills),mn(s.id),t.emit("complete",{id:s.id,name:s.name})}catch(a){t.emit("error",{id:s.id,name:s.name,error:a})}},c);n.set(s.id,u)}t.emit("started",{count:n.size})}function o(){for(let[i,s]of n)clearInterval(s),n.delete(i);t.emit("stopped")}return{on:t.on.bind(t),off:t.off.bind(t),once:t.once.bind(t),emit:t.emit.bind(t),start:r,stop:o,add:i=>{let s=ot(i);if(s.enabled){let c=Oe(s.schedule);if(c){let u=setInterval(async()=>{try{t.emit("run",{id:s.id,name:s.name}),await e(s.prompt,s.skills),mn(s.id),t.emit("complete",{id:s.id,name:s.name})}catch(a){t.emit("error",{id:s.id,name:s.name,error:a})}},c);n.set(s.id,u)}}return s},remove:i=>{let s=n.get(i);return s&&(clearInterval(s),n.delete(i)),it(i)},list:rt}}var bn=[{type:"function",function:{name:"cron_add",description:"Schedule a recurring agent job.",parameters:{type:"object",properties:{name:{type:"string",description:"Human-readable name"},schedule:{type:"string",description:"'every 30m', 'daily', 'every 6h'"},prompt:{type:"string",description:"Agent prompt to run on schedule"},skills:{type:"array",items:{type:"string"},description:"Optional skill names"}},required:["name","schedule","prompt"],additionalProperties:!1}}},{type:"function",function:{name:"cron_list",description:"List all scheduled cron jobs.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"cron_remove",description:"Remove a cron job by id.",parameters:{type:"object",properties:{id:{type:"string",description:"Job id from cron_list"}},required:["id"],additionalProperties:!1}}}];var Ce=[],vo=5,ko=1;function _n(e){Ce.push(e),Ce.length>20&&Ce.shift()}function wn(){let e=Ce.slice(-3);if(e.length<1)return null;let t=e[e.length-1];return t.toolCalls>=vo&&t.errors===0?{shouldCreate:!0,suggestion:`You completed a ${t.toolCalls}-step workflow. Save it as a skill with skill_create.`}:e.filter(r=>r.errors>0&&r.recovered).length>=ko&&t.toolCalls>=3?{shouldCreate:!0,suggestion:"You recovered from errors. Save the corrected approach as a skill."}:{shouldCreate:!1,suggestion:"No skill suggestions yet."}}var vn=[{type:"function",function:{name:"meta_analyze",description:"Analyze recent interactions and suggest skills to create.",parameters:{type:"object",properties:{},additionalProperties:!1}}}];import{homedir as st}from"node:os";import{join as at}from"node:path";var kn=process.env.ORACLE_PUBLIC_DESKTOP==="1",So=kn?process.env.ORACLE_CONFIG_DIR||at(st(),".config","oracle"):at(st(),".config","oracle"),Hs=kn?So:at(st(),".config","mad-desk");function Eo(e,t,n=""){let r=process.env[e];if(r!=null&&String(r).trim()!=="")return r;let o=t?process.env[t]:void 0;return o!=null&&String(o).trim()!==""?o:n}var Ao=["0","false","off","no"];function Sn(e,t,n=!0){let r=String(Eo(e,t,"")).trim().toLowerCase();return r===""?n:!Ao.includes(r)}var zo=new Set(["chain","data","scan","route","prepare"]),qo=new Set(["list","show"]),Wo=new Set(["call","catalog","health"]),Yo=new Set(["swap","bridge","prepare","prepare-bridge"]),Go=Object.freeze({"anthropic-oauth":"https://api.anthropic.com/v1","openai-codex":"https://chatgpt.com/backend-api/codex","xai-oauth":"https://api.x.ai/v1"}),xt=2e4,$n=6,Jo=Object.freeze({type:"function",function:{name:"oracle_cli",description:["Run a bounded read or prepare-only Oracle CLI command. It cannot sign or broadcast transactions.","Live market/chain data comes from the data plane: argv ['data','call','<provider>','<op>','key=value'].","Parameters are key=value positionals \u2014 never a bare value.","Prefer the TARGETED op over a bulk dump: hl-markets coin coin=HYPE returns one asset's mark price, funding, and book,","while hl-info allMids returns every market at once and wastes the step budget.","Providers include bitcoin-esplora (tipHeight, fees, address, utxos, tx), hl-markets (coin, markets, spot),","hl-info (allMids, l2Book, meta, metaAndAssetCtxs, candleSnapshot), poly-public (markets slug=<slug>, book token_id=<id>, midpoint, spread, price, events),","solana-rpc (latestBlockhash, getBalance, tokenAccounts), evm-rpc (blockNumber, getBalance, call), and defillama (prices, protocols, yields, stablecoins).","Use data catalog (argv ['data','catalog']) to list every provider and its ops before guessing a verb."].join(" "),parameters:{type:"object",properties:{argv:{type:"array",items:{type:"string"},minItems:1,maxItems:24,description:["Arguments after the oracle executable.","Allowed top-level verbs: chain (list|show), data (call|catalog|health), scan, route (swap|bridge|prepare|prepare-bridge), prepare.","The live-data shape is: data call <provider> <op> [key=value ...]. Bare positionals are rejected.",'Examples: ["data","call","bitcoin-esplora","tipHeight"], ["data","call","hl-markets","coin","coin=HYPE"],','["data","call","poly-public","markets","slug=some-market-slug"], ["data","catalog"], ["scan","chains"].'].join(" ")}},required:["argv"],additionalProperties:!1}}}),yt=Object.freeze([Jo,...an,...pn,...bn,...vn]);function Pn(e){let t=String(e||"");return t.length<=xt?t:`${t.slice(0,xt)}
22
+ [truncated ${t.length-xt} chars]`}async function Vo(e,t,n){switch(e){case"oracle_cli":return n(t.argv);case"memory_add":return rn(t.key,t.content),{ok:!0,stored:t.key};case"memory_remove":return on(t.key);case"skill_load":{let r=et(t.name);return r?{ok:!0,name:t.name,content:r}:{ok:!1,error:`skill not found: ${t.name}`}}case"skill_create":return dn(t.name,t.content),{ok:!0,created:t.name};case"skill_list":return{ok:!0,skills:Ze().map(o=>({name:o.name,description:o.description}))};case"cron_add":return{ok:!0,job:ot({name:t.name,schedule:t.schedule,prompt:t.prompt,skills:t.skills||[],enabled:!0})};case"cron_list":return{ok:!0,jobs:rt()};case"cron_remove":return{ok:it(t.id),removed:t.id};case"meta_analyze":return{ok:!0,...wn()||{shouldCreate:!1,suggestion:"No skill suggestions yet."}};default:return{ok:!1,error:`unknown tool: ${e}`}}}function Xo(e){if(!Array.isArray(e)||e.length===0||e.length>24)return"argv must contain 1 to 24 arguments";if(e.some(n=>typeof n!="string"||n.length>1e3))return"every argument must be a string no longer than 1000 characters";let t=e[0];return zo.has(t)?t==="chain"&&!qo.has(e[1]||"list")?`command not allowed: chain${e[1]?` ${e[1]}`:""}`:t==="data"&&!Wo.has(e[1]||"")?`command not allowed: data${e[1]?` ${e[1]}`:""}`:t==="route"&&!Yo.has(e[1]||"")?`command not allowed: route${e[1]?` ${e[1]}`:""}`:null:`command not allowed: ${t}`}async function Qo(e,t={}){let n=Xo(e);if(n)return{ok:!1,error:n};let r=t.spawnFn||Ho,o=t.packageRoot||B,i=r(process.execPath,[Nn.join(o,"bin","oracle.mjs"),...e],{encoding:"utf8",timeout:t.timeoutMs||45e3,maxBuffer:1024*1024,env:{...process.env,ORACLE_CHAT_TOOL:"1"}});return i.error?{ok:!1,error:i.error.message}:{ok:i.status===0,status:typeof i.status=="number"?i.status:1,stdout:Pn(i.stdout),stderr:Pn(i.stderr)}}function Zo(){let e=Nn.join(ke("profiles",import.meta.url),"oracle","SOUL.md"),t=Bo.readFileSync(e,"utf8"),n=sn(),r=fn(),o=[t.trim()];return n&&o.push(n),o.push(r),o.push("You have tools for Oracle CLI commands, durable memory, skills, cron scheduling, and meta-learning.","Use memory_add to persist facts. Use skill_create to save successful workflows. Use cron_add to schedule recurring tasks."),o.join(`
23
23
 
24
- `)}function Fo(e,t,n={}){return{method:"event",params:{type:e,session_id:t,payload:n}}}async function Uo(e){return new Error(`model request failed (HTTP ${e?.status||"unknown"})`)}async function*lt(e){if(!e?.ok)throw await Uo(e);if(!e.body)throw new Error("model response had no body");let t=e.body.getReader(),n=new TextDecoder,r="";for(;;){let{value:i,done:c}=await t.read();r+=n.decode(i||new Uint8Array,{stream:!c});let a=r.split(/\r?\n\r?\n/);r=a.pop()||"";for(let u of a){let s=u.split(/\r?\n/).filter(d=>d.startsWith("data:")).map(d=>d.slice(5).trimStart()).join(`
25
- `);!s||s==="[DONE]"||(yield JSON.parse(s))}if(c)break}let o=r.trim();if(o.startsWith("data:")){let i=o.slice(5).trim();i&&i!=="[DONE]"&&(yield JSON.parse(i))}}function Do(e,t){let n=Number(t.index||0),r=e.get(n)||{id:"",type:"function",function:{name:"",arguments:""}};t.id&&(r.id+=t.id),t.type&&(r.type=t.type),t.function?.name&&(r.function.name+=t.function.name),t.function?.arguments&&(r.function.arguments+=t.function.arguments),e.set(n,r)}function Bo(e,t){let n=Number(e?.prompt_tokens||e?.input_tokens||0),r=Number(e?.completion_tokens||e?.output_tokens||0);return{context_used:n,context_max:t,context_percent:t>0?Math.round(n/t*100):0,input:n,output:r}}function Ko(){return ut.map(e=>({type:"function",name:e.function.name,description:e.function.description,parameters:e.function.parameters,strict:!1}))}function Ho(){return ut.map(e=>({name:e.function.name,description:e.function.description,input_schema:e.function.parameters}))}function at(e,t,n){let r=Array.isArray(n)?n:[{type:"text",text:String(n||"")}],o=e.at(-1);o?.role===t?o.content.push(...r):e.push({role:t,content:r})}function qo(e){let t=[];for(let n of e)if(n.role!=="system"){if(n.role==="user"){at(t,"user",[{type:"text",text:String(n.content||"")}]);continue}if(n.role==="assistant"){let r=[];n.content&&r.push({type:"text",text:String(n.content)});for(let o of n.tool_calls||[]){let i={};try{i=JSON.parse(o.function?.arguments||"{}")}catch{}r.push({type:"tool_use",id:o.id,name:o.function?.name,input:i})}r.length&&at(t,"assistant",r);continue}n.role==="tool"&&at(t,"user",[{type:"tool_result",tool_use_id:n.tool_call_id,content:String(n.content||"")}])}return t}function zo(e){let t=[];for(let n of e)if(n.role!=="system"){if(n.role==="user"){t.push({role:"user",content:[{type:"input_text",text:String(n.content||"")}]});continue}if(n.role==="assistant"){n.content&&t.push({role:"assistant",status:"completed",content:[{type:"output_text",text:String(n.content)}]});for(let r of n.tool_calls||[])t.push({type:"function_call",id:r.response_item_id||void 0,call_id:r.id,name:r.function?.name,arguments:r.function?.arguments||"{}"});continue}n.role==="tool"&&t.push({type:"function_call_output",call_id:n.tool_call_id,output:String(n.content||"")})}return t.map(n=>Object.fromEntries(Object.entries(n).filter(([,r])=>r!==void 0)))}function Wo(e){try{let t=JSON.parse(Buffer.from(String(e).split(".")[1],"base64url").toString("utf8"));return String(t?.["https://api.openai.com/auth"]?.chatgpt_account_id||"")}catch{return""}}async function Yo({config:e,messages:t,fetchFn:n,signal:r,onText:o}){let i=await n(`${e.baseUrl}/chat/completions`,{method:"POST",headers:{"content-type":"application/json",...e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{},...e.provider==="openrouter"?{"HTTP-Referer":"https://oracle-agent.dev","X-Title":"Oracle CLI"}:{}},body:JSON.stringify({model:e.model,messages:t,tools:ut,tool_choice:"auto",stream:!0,stream_options:{include_usage:!0}}),signal:r}),c=new Map,a="",u=null;for await(let s of lt(i)){s.usage&&(u=s.usage);let d=s.choices?.[0]?.delta||{};typeof d.content=="string"&&d.content&&(a+=d.content,o(d.content));for(let p of d.tool_calls||[])Do(c,p)}return{text:a,usage:u,toolCalls:[...c.entries()].sort(([s],[d])=>s-d).map(([,s])=>s)}}async function Go({config:e,messages:t,persona:n,credential:r,fetchFn:o,signal:i,onText:c}){let a=await o(`${e.baseUrl}/messages`,{method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream",Authorization:`Bearer ${r.accessToken}`,"anthropic-version":"2023-06-01","anthropic-beta":"interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14,claude-code-20250219,oauth-2025-04-20","user-agent":`claude-code/${process.env.ORACLE_CLAUDE_CODE_VERSION||"2.1.220"} (external, cli)`,"x-app":"cli"},body:JSON.stringify({model:e.model,max_tokens:Number(e.maxOutputTokens||8192),system:[{type:"text",text:"You are Claude Code, Anthropic's official CLI for Claude."},{type:"text",text:n}],messages:qo(t),tools:Ho(),tool_choice:{type:"auto"},stream:!0}),signal:i}),u=new Map,s="",d=null;for await(let p of lt(a)){if(p.type==="message_start"&&(d={...d||{},...p.message?.usage||{}}),p.type==="message_delta"&&(d={...d||{},...p.usage||{}}),p.type==="content_block_start"&&p.content_block?.type==="tool_use"){let y=p.content_block;u.set(Number(p.index||0),{id:y.id,type:"function",function:{name:y.name,arguments:y.input&&Object.keys(y.input).length?JSON.stringify(y.input):""}})}if(p.type==="content_block_delta"&&p.delta?.type==="text_delta"&&(s+=p.delta.text||"",p.delta.text&&c(p.delta.text)),p.type==="content_block_delta"&&p.delta?.type==="input_json_delta"){let y=Number(p.index||0),x=u.get(y);x&&(x.function.arguments+=p.delta.partial_json||"")}if(p.type==="error")throw new Error(p.error?.message||"Claude stream failed")}return{text:s,usage:d,toolCalls:[...u.entries()].sort(([p],[y])=>p-y).map(([,p])=>(p.function.arguments||(p.function.arguments="{}"),p))}}async function Jo({config:e,messages:t,persona:n,sessionId:r,credential:o,fetchFn:i,signal:c,onText:a}){let u=e.provider==="openai-codex",s=u?Wo(o.accessToken):"",d={"content-type":"application/json",accept:"text/event-stream",Authorization:`Bearer ${o.accessToken}`,...u?{"user-agent":"codex_cli_rs/0.0.0 (Oracle CLI)",originator:"codex_cli_rs",...s?{"ChatGPT-Account-ID":s}:{},session_id:r,"x-client-request-id":r}:{"x-grok-conv-id":r}},p={model:e.model,instructions:n,input:zo(t),tools:Ko(),tool_choice:"auto",parallel_tool_calls:!0,store:!1,stream:!0,...u?{reasoning:{effort:e.reasoningEffort||"high",summary:"auto"}}:{}},y=await i(`${e.baseUrl}/responses`,{method:"POST",headers:d,body:JSON.stringify(p),signal:c}),x=new Map,_="",v=null;for await(let b of lt(y)){b.type==="response.output_text.delta"&&typeof b.delta=="string"&&(_+=b.delta,a(b.delta));let m=b.item;if((b.type==="response.output_item.added"||b.type==="response.output_item.done")&&m?.type==="function_call"){let h=String(m.call_id||m.id||b.output_index||x.size);x.set(h,{id:m.call_id||m.id,response_item_id:m.id,type:"function",function:{name:m.name,arguments:m.arguments||"{}"}})}if(b.type==="response.function_call_arguments.delta"){let h=String(b.call_id||b.item_id||b.output_index||""),l=x.get(h);l&&(l.function.arguments+=b.delta||"")}if(b.type==="response.completed"&&(v=b.response?.usage||v),b.type==="response.failed"||b.type==="error")throw new Error(b.response?.error?.message||b.error?.message||"Responses stream failed")}return{text:_,usage:v,toolCalls:[...x.values()]}}function En(e={}){let t=e.config;if(!t?.baseUrl||!t?.model)throw new Error("standalone model configuration is incomplete");if(t.authType==="oauth"){let l=$o[t.provider],f=String(t.baseUrl).replace(/\/+$/,"");if(!l||f!==l)throw new Error(`${t.provider||"unknown"} OAuth endpoint is not trusted`)}let n=new Ao,r=e.fetchFn||globalThis.fetch,o=e.toolRunner||(l=>jo(l,e)),i=e.credentialProvider||(async l=>{let{resolveOAuthCredentials:f}=await Promise.resolve().then(()=>(st(),_n));return f(l)}),c=e.persona||Mo(),a=e.sessionId||`oracle-${wn()}`,u=[],s=null,d=!1,p=!1,y=sn(async(l,f)=>{if(d)return;let w=(f||[]).map(k=>{let g=ze(k);return g?`## Skill: ${k}
26
- ${g}`:null}).filter(Boolean),O=w.length>0?`
24
+ `)}function ei(e,t,n={}){return{method:"event",params:{type:e,session_id:t,payload:n}}}async function ti(e){return new Error(`model request failed (HTTP ${e?.status||"unknown"})`)}async function*bt(e){if(!e?.ok)throw await ti(e);if(!e.body)throw new Error("model response had no body");let t=e.body.getReader(),n=new TextDecoder,r="";for(;;){let{value:i,done:s}=await t.read();r+=n.decode(i||new Uint8Array,{stream:!s});let c=r.split(/\r?\n\r?\n/);r=c.pop()||"";for(let u of c){let a=u.split(/\r?\n/).filter(f=>f.startsWith("data:")).map(f=>f.slice(5).trimStart()).join(`
25
+ `);!a||a==="[DONE]"||(yield JSON.parse(a))}if(s)break}let o=r.trim();if(o.startsWith("data:")){let i=o.slice(5).trim();i&&i!=="[DONE]"&&(yield JSON.parse(i))}}function ni(e,t){let n=Number(t.index||0),r=e.get(n)||{id:"",type:"function",function:{name:"",arguments:""}};t.id&&(r.id+=t.id),t.type&&(r.type=t.type),t.function?.name&&(r.function.name+=t.function.name),t.function?.arguments&&(r.function.arguments+=t.function.arguments),e.set(n,r)}function ri(e,t){let n=Number(e?.prompt_tokens||e?.input_tokens||0),r=Number(e?.completion_tokens||e?.output_tokens||0);return{context_used:n,context_max:t,context_percent:t>0?Math.round(n/t*100):0,input:n,output:r}}function oi(){return yt.map(e=>({type:"function",name:e.function.name,description:e.function.description,parameters:e.function.parameters,strict:!1}))}function ii(){return yt.map(e=>({name:e.function.name,description:e.function.description,input_schema:e.function.parameters}))}function gt(e,t,n){let r=Array.isArray(n)?n:[{type:"text",text:String(n||"")}],o=e.at(-1);o?.role===t?o.content.push(...r):e.push({role:t,content:r})}function si(e){let t=[];for(let n of e)if(n.role!=="system"){if(n.role==="user"){gt(t,"user",[{type:"text",text:String(n.content||"")}]);continue}if(n.role==="assistant"){let r=[];n.content&&r.push({type:"text",text:String(n.content)});for(let o of n.tool_calls||[]){let i={};try{i=JSON.parse(o.function?.arguments||"{}")}catch{}r.push({type:"tool_use",id:o.id,name:o.function?.name,input:i})}r.length&&gt(t,"assistant",r);continue}n.role==="tool"&&gt(t,"user",[{type:"tool_result",tool_use_id:n.tool_call_id,content:String(n.content||"")}])}return t}function ai(e){let t=[];for(let n of e)if(n.role!=="system"){if(n.role==="user"){t.push({role:"user",content:[{type:"input_text",text:String(n.content||"")}]});continue}if(n.role==="assistant"){n.content&&t.push({role:"assistant",status:"completed",content:[{type:"output_text",text:String(n.content)}]});for(let r of n.tool_calls||[])t.push({type:"function_call",id:r.response_item_id||void 0,call_id:r.id,name:r.function?.name,arguments:r.function?.arguments||"{}"});continue}n.role==="tool"&&t.push({type:"function_call_output",call_id:n.tool_call_id,output:String(n.content||"")})}return t.map(n=>Object.fromEntries(Object.entries(n).filter(([,r])=>r!==void 0)))}function ci(e){try{let t=JSON.parse(Buffer.from(String(e).split(".")[1],"base64url").toString("utf8"));return String(t?.["https://api.openai.com/auth"]?.chatgpt_account_id||"")}catch{return""}}async function ui({config:e,messages:t,fetchFn:n,signal:r,onText:o}){let i=await n(`${e.baseUrl}/chat/completions`,{method:"POST",headers:{"content-type":"application/json",...e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{},...e.provider==="openrouter"?{"HTTP-Referer":"https://oracle-agent.dev","X-Title":"Oracle CLI"}:{}},body:JSON.stringify({model:e.model,messages:t,tools:yt,tool_choice:"auto",stream:!0,stream_options:{include_usage:!0}}),signal:r}),s=new Map,c="",u=null;for await(let a of bt(i)){a.usage&&(u=a.usage);let f=a.choices?.[0]?.delta||{};typeof f.content=="string"&&f.content&&(c+=f.content,o(f.content));for(let p of f.tool_calls||[])ni(s,p)}return{text:c,usage:u,toolCalls:[...s.entries()].sort(([a],[f])=>a-f).map(([,a])=>a)}}async function li({config:e,messages:t,persona:n,credential:r,fetchFn:o,signal:i,onText:s}){let c=await o(`${e.baseUrl}/messages`,{method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream",Authorization:`Bearer ${r.accessToken}`,"anthropic-version":"2023-06-01","anthropic-beta":"interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14,claude-code-20250219,oauth-2025-04-20","user-agent":`claude-code/${process.env.ORACLE_CLAUDE_CODE_VERSION||"2.1.220"} (external, cli)`,"x-app":"cli"},body:JSON.stringify({model:e.model,max_tokens:Number(e.maxOutputTokens||8192),system:[{type:"text",text:"You are Claude Code, Anthropic's official CLI for Claude."},{type:"text",text:n}],messages:si(t),tools:ii(),tool_choice:{type:"auto"},stream:!0}),signal:i}),u=new Map,a="",f=null;for await(let p of bt(c)){if(p.type==="message_start"&&(f={...f||{},...p.message?.usage||{}}),p.type==="message_delta"&&(f={...f||{},...p.usage||{}}),p.type==="content_block_start"&&p.content_block?.type==="tool_use"){let g=p.content_block;u.set(Number(p.index||0),{id:g.id,type:"function",function:{name:g.name,arguments:g.input&&Object.keys(g.input).length?JSON.stringify(g.input):""}})}if(p.type==="content_block_delta"&&p.delta?.type==="text_delta"&&(a+=p.delta.text||"",p.delta.text&&s(p.delta.text)),p.type==="content_block_delta"&&p.delta?.type==="input_json_delta"){let g=Number(p.index||0),x=u.get(g);x&&(x.function.arguments+=p.delta.partial_json||"")}if(p.type==="error")throw new Error(p.error?.message||"Claude stream failed")}return{text:a,usage:f,toolCalls:[...u.entries()].sort(([p],[g])=>p-g).map(([,p])=>(p.function.arguments||(p.function.arguments="{}"),p))}}async function fi({config:e,messages:t,persona:n,sessionId:r,credential:o,fetchFn:i,signal:s,onText:c}){let u=e.provider==="openai-codex",a=u?ci(o.accessToken):"",f={"content-type":"application/json",accept:"text/event-stream",Authorization:`Bearer ${o.accessToken}`,...u?{"user-agent":"codex_cli_rs/0.0.0 (Oracle CLI)",originator:"codex_cli_rs",...a?{"ChatGPT-Account-ID":a}:{},session_id:r,"x-client-request-id":r}:{"x-grok-conv-id":r}},p={model:e.model,instructions:n,input:ai(t),tools:oi(),tool_choice:"auto",parallel_tool_calls:!0,store:!1,stream:!0,...u?{reasoning:{effort:e.reasoningEffort||"high",summary:"auto"}}:{}},g=await i(`${e.baseUrl}/responses`,{method:"POST",headers:f,body:JSON.stringify(p),signal:s}),x=new Map,w="",S=null;for await(let k of bt(g)){k.type==="response.output_text.delta"&&typeof k.delta=="string"&&(w+=k.delta,c(k.delta));let b=k.item;if((k.type==="response.output_item.added"||k.type==="response.output_item.done")&&b?.type==="function_call"){let v=String(b.call_id||b.id||k.output_index||x.size);x.set(v,{id:b.call_id||b.id,response_item_id:b.id,type:"function",function:{name:b.name,arguments:b.arguments||"{}"}})}if(k.type==="response.function_call_arguments.delta"){let v=String(k.call_id||k.item_id||k.output_index||""),d=x.get(v);d&&(d.function.arguments+=k.delta||"")}if(k.type==="response.completed"&&(S=k.response?.usage||S),k.type==="response.failed"||k.type==="error")throw new Error(k.response?.error?.message||k.error?.message||"Responses stream failed")}return{text:w,usage:S,toolCalls:[...x.values()]}}function jn(e={}){let t=e.config;if(!t?.baseUrl||!t?.model)throw new Error("standalone model configuration is incomplete");if(t.authType==="oauth"){let d=Go[t.provider],l=String(t.baseUrl).replace(/\/+$/,"");if(!d||l!==d)throw new Error(`${t.provider||"unknown"} OAuth endpoint is not trusted`)}let n=new Ko,r=e.fetchFn||globalThis.fetch,o=e.toolRunner||(d=>Qo(d,e)),i=e.credentialProvider||(async d=>{let{resolveOAuthCredentials:l}=await Promise.resolve().then(()=>(ht(),Tn));return l(d)}),s=e.persona||Zo(),c=e.sessionId||`oracle-${Rn()}`,u=[],a=null,f=!1,p=!1,g=yn(async(d,l)=>{if(f)return;let h=(l||[]).map(y=>{let m=et(y);return m?`## Skill: ${y}
26
+ ${m}`:null}).filter(Boolean),_=h.length>0?`
27
27
 
28
- ${w.join(`
28
+ ${h.join(`
29
29
 
30
- `)}`:"";await v(`${l}${O}`)});dn("ORACLE_CRON_ENABLED","MAD_CRON_ENABLED",!0)&&(y.on("run",l=>x("cron.run",l)),y.on("complete",l=>x("cron.complete",l)),y.on("error",l=>x("cron.error",l)),y.start());function x(l,f={}){n.emit("event",Fo(l,a,f))}function _(l){x("error",{message:l?.message||String(l)}),n.listenerCount("error")>0&&n.emit("error",l)}async function v(l){p=!0,s=new AbortController;let f=[{role:"system",content:c},...u,{role:"user",content:l}],w="",O=null,k=!1;try{for(let g=0;g<vn;g+=1){let I=t.authType==="oauth"?await i(t.provider):null,q=J=>{k||(x("message.start",{}),k=!0),w+=J,x("message.delta",{text:J})},C={config:t,messages:f,persona:c,sessionId:a,credential:I,fetchFn:r,signal:s.signal,onText:q},N=t.protocol==="anthropic-messages"?await Go(C):t.protocol==="responses"?await Jo(C):await Yo(C),re=N.text,oe=N.toolCalls;if(O=N.usage||O,oe.length===0){f.push({role:"assistant",content:re}),u=f.slice(1),k||x("message.start",{}),x("message.complete",{text:w,usage:Bo(O,t.contextLength)});return}f.push({role:"assistant",content:re||null,tool_calls:oe});let Nn=oe.length,fe=0;for(let J of oe){let de;try{let Ae=JSON.parse(J.function.arguments||"{}");de=await Po(J.function.name,Ae,o)}catch(Ae){de={ok:!1,error:`invalid tool arguments: ${Ae.message}`},fe++}de.ok||fe++,f.push({role:"tool",tool_call_id:J.id||`call_${wn()}`,content:JSON.stringify(de)})}an({userMessage:l,toolCalls:Nn,errors:fe,recovered:fe>0?!!oe.length:!1,durationMs:0})}throw new Error(`agent exceeded ${vn} tool steps`)}catch(g){g?.name!=="AbortError"&&_(g)}finally{p=!1,s=null}}async function b(){if(d)throw new Error("standalone client is stopped")}async function m(l,f={}){if(d)throw new Error("standalone client is stopped");if(l==="session.create")return x("session.info",{model:f.model||t.model,reasoning_effort:t.reasoningEffort,usage:{context_max:t.contextLength},backend:"standalone"}),{session_id:a,info:{model:f.model||t.model,reasoning_effort:t.reasoningEffort,usage:{context_max:t.contextLength},backend:"standalone"}};if(l==="prompt.submit"){if(p)throw new Error("a turn is already active");let w=String(f.text||"").trim();if(!w)throw new Error("prompt text is required");return queueMicrotask(()=>{v(w).catch(_)}),{accepted:!0}}if(l==="session.interrupt"){let w=!!(s&&p);return s?.abort(),{interrupted:w}}if(l==="session.usage")return{calls:0,input:0,output:0,total:0};throw new Error(`unsupported standalone method: ${l}`)}async function h(){d||(d=!0,s?.abort(),y.stop())}return Object.freeze({start:b,request:m,stop:h,on:n.on.bind(n),off:n.off.bind(n)})}async function An({client:e,text:t,stdout:n=process.stdout,stderr:r=process.stderr}={}){if(!e)throw new Error("standalone client is required");await e.start();let o=await e.request("session.create",{source:"cli"}),i="",c=!1;try{return await new Promise((a,u)=>{let s=d=>{let p=d?.params?.type,y=d?.params?.payload||{};if(p==="message.delta"&&typeof y.text=="string"){i+=y.text,n.write(y.text);return}if(p==="message.complete"){!i&&y.text&&n.write(String(y.text)),n.write(`
31
- `),c=!0,a(0);return}if(p==="error"){let x=y.message||y.text||"standalone chat failed";r.write(`oracle chat: ${x}
32
- `),c=!0,u(new Error(x))}};e.on("event",s),e.request("prompt.submit",{session_id:o.session_id,text:t}).catch(d=>{c||(c=!0,u(d))})})}finally{await e.stop()}}st();var T="oracle",le="oracle";function Rn(e){if(e==="hermes"){let t=Ce();return t.ok?t.bin:null}for(let t of(process.env.PATH||"").split(S.delimiter)){let n=S.join(t,e);try{if(A.existsSync(n))return n}catch{}}return null}function On(e){try{let t=A.readFileSync(e,"utf8").split(/\r?\n/,1)[0];if(!t.startsWith("#!"))return null;let n=t.slice(2).trim().split(/\s+/);if(n[0]?.endsWith("/env")&&n[1]?.startsWith("python"))return{command:n[0],prefix:[n[1]]};if(S.basename(n[0]||"").startsWith("python"))return{command:n[0],prefix:n.slice(1)}}catch{}return null}function Pn(e){let t=On(e);if(t)return t;try{let r=A.readFileSync(e,"utf8").match(/["']([^"'\r\n]+\/bin\/hermes)["']/);if(r)return On(r[1])}catch{}return null}function Xo(){return S.join(M,"src","cli","oracle-harness.py")}function Cn(e,t){let n=Xo(),r=process.env.ORACLE_PLAIN_HARNESS==="0"?null:Pn(e);return r&&A.existsSync(n)?{command:r.command,args:[...r.prefix,n,...t]}:{command:e,args:t}}function Qo(){return S.join(M,"skins","oracle.yaml")}function Zo(e=T){let t=S.join(M,"profiles","oracle","SOUL.md");if(!A.existsSync(t))return{ok:!1,reason:"oracle persona missing from package"};let n=S.join(F(),"profiles",e,"SOUL.md");return A.existsSync(n)&&!A.readFileSync(n,"utf8").startsWith("You are Hermes Agent, an intelligent AI assistant created by Nous Research.")?{ok:!0,reused:!0}:(R(S.dirname(n)),A.copyFileSync(t,n),{ok:!0,reused:!1})}function ei(e=T){let t=Qo();if(!A.existsSync(t))return{ok:!1,reason:"skin missing from package"};let n=S.join(F(),"skins"),r=S.join(F(),"profiles",e,"skins");R(n),R(r);let o=A.readFileSync(t,"utf8");return A.writeFileSync(S.join(n,`${le}.yaml`),o),A.writeFileSync(S.join(r,`${le}.yaml`),o),{ok:!0,skin:le}}function ti(e=T){let t=S.join(F(),"profiles",e,"config.yaml");if(!A.existsSync(t))return{ok:!1,reason:"profile config missing"};let n=Rn("oracle")||S.join(M,"bin","oracle.mjs"),r=S.join(F(),"profiles",e,"oracle");R(r);let o={profile:e,skin:le,oracleBin:n,commands:{chain:[n,"chain"],setup:[n,"setup"]},updatedAt:new Date().toISOString()};return A.writeFileSync(S.join(r,"chat-surface.json"),JSON.stringify(o,null,2)+`
33
- `,{mode:384}),{ok:!0,marker:o}}function ni(e=T){let t=S.join(M,"skills","oracle-chat");if(!A.existsSync(t))return{ok:!1,reason:"oracle-chat skill missing"};let n=S.join(F(),"profiles",e,"skills","oracle-chat");R(n);for(let r of A.readdirSync(t)){let o=S.join(t,r),i=S.join(n,r);A.statSync(o).isFile()&&A.copyFileSync(o,i)}for(let r of["chain","setup"]){let o=S.join(F(),"profiles",e,"skills",r);R(o);let i=S.join(t,`${r}.SKILL.md`),c=S.join(t,"SKILL.md"),a=A.existsSync(i)?A.readFileSync(i,"utf8"):A.readFileSync(c,"utf8");A.writeFileSync(S.join(o,"SKILL.md"),a)}return{ok:!0}}function ri(e=T){let t=Rn("hermes");if(!t)return{ok:!1,reason:"hermes missing"};let n=Vo(t,["-p",e,"config","set","display.skin",le],{encoding:"utf8",timeout:3e4});return n.status!==0?{ok:!1,reason:(n.stderr||n.stdout||"config set failed").trim()}:{ok:!0}}function In(e){if(!A.existsSync(e))return!1;let t=A.readFileSync(e,"utf8");if(/^model:\s*\S+/m.test(t))return!0;let n=t.match(/^model:\s*\n((?:[ \t]+.*(?:\n|$))*)/m)?.[1]||"";return/^\s+(?:default|provider):\s*\S+/m.test(n)}function oi(e=T){let t=F();if(A.existsSync(S.join(t,"auth.json"))||A.existsSync(S.join(t,"profiles",e,"auth.json")))return!0;let n=["OPENROUTER_API_KEY","ANTHROPIC_API_KEY","OPENAI_API_KEY","XAI_API_KEY","GOOGLE_API_KEY","GEMINI_API_KEY","DEEPSEEK_API_KEY","HF_TOKEN","GLM_API_KEY","KIMI_API_KEY","MINIMAX_API_KEY"];if(n.some(r=>process.env[r]))return!0;for(let r of[S.join(t,".env"),S.join(t,"profiles",e,".env")]){if(!A.existsSync(r))continue;let o=A.readFileSync(r,"utf8");if(n.some(i=>new RegExp(`^${i}=.+`,"m").test(o)))return!0}return!1}function Ln(e=T){let t=F();return In(S.join(t,"config.yaml"))||In(S.join(t,"profiles",e,"config.yaml"))||oi(e)}function Tn(){return["oracle chat, filled lowercase oracle chat",""," oracle chat open interactive oracle chat",' oracle chat -q "..." one-shot query'," oracle chat --model <m> use a model for this session"," oracle chat --print-banner show filled oracle banner only","","inside chat:"," /chain list/select chains"," /setup messaging setup menu"," /model switch models (still one oracle persona)","","brand: filled lowercase oracle / classic boxed layout"].join(`
34
- `)}function ii(){let e=Number(process.stdout?.columns||process.env.COLUMNS||80);return Number.isFinite(e)&&e>0?Math.floor(e):80}function si(e){return Array.from(String(e)).length}function ci(e,t){let n=e.map(c=>c.trimEnd()),r=Math.max(0,...n.map(c=>si(c))),o=Math.max(0,Math.floor((t-r)/2)),i=" ".repeat(o);return n.map(c=>c?`${i}${c}`:"")}function $n(e){return`'${String(e).replace(/'/g,"'\\''")}'`}function ai(e){return e.user?`${e.user}@${e.host}`:e.host}function ui(e,t){let n=e.path||"$HOME/.local/bin:/usr/local/bin:/usr/bin:/bin:/opt/homebrew/bin",r=["oracle","chat",...t].map($n).join(" ");return[/^[A-Za-z0-9_:$/.~+-]+$/.test(n)?`export PATH=${n}`:`export PATH=${$n(n)}`,"export ORACLE_REMOTE_COMPUTE_DISABLE=1","export ORACLE_CHAT_BACKEND=auto",r].join("; ")}function li(){let e=[""," \u2588\u2588\u2588\u2588"," \u2591\u2591\u2588\u2588\u2588"," \u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588"," \u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588 \u2591\u2591\u2591\u2591\u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588","\u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2591\u2591 \u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2591\u2591 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588\u2591\u2591\u2591","\u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588"," \u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591",""];process.stdout.write(ci(e,ii()).join(`
30
+ `)}`:"";await S(`${d}${_}`)});Sn("ORACLE_CRON_ENABLED","MAD_CRON_ENABLED",!0)&&(g.on("run",d=>x("cron.run",d)),g.on("complete",d=>x("cron.complete",d)),g.on("error",d=>x("cron.error",d)),g.start());function x(d,l={}){n.emit("event",ei(d,c,l))}function w(d){x("error",{message:d?.message||String(d)}),n.listenerCount("error")>0&&n.emit("error",d)}async function S(d){p=!0,a=new AbortController;let l=[{role:"system",content:s},...u,{role:"user",content:d}],h="",_=null,y=!1;try{for(let m=0;m<$n;m+=1){let A=t.authType==="oauth"?await i(t.provider):null,M=Z=>{y||(x("message.start",{}),y=!0),h+=Z,x("message.delta",{text:Z})},I={config:t,messages:l,persona:s,sessionId:c,credential:A,fetchFn:r,signal:a.signal,onText:M},F=t.protocol==="anthropic-messages"?await li(I):t.protocol==="responses"?await fi(I):await ui(I),ae=F.text,ce=F.toolCalls;if(_=F.usage||_,ce.length===0){l.push({role:"assistant",content:ae}),u=l.slice(1),y||x("message.start",{}),x("message.complete",{text:h,usage:ri(_,t.contextLength)});return}l.push({role:"assistant",content:ae||null,tool_calls:ce});let Wn=ce.length,he=0;for(let Z of ce){let xe;try{let Re=JSON.parse(Z.function.arguments||"{}");xe=await Vo(Z.function.name,Re,o)}catch(Re){xe={ok:!1,error:`invalid tool arguments: ${Re.message}`},he++}xe.ok||he++,l.push({role:"tool",tool_call_id:Z.id||`call_${Rn()}`,content:JSON.stringify(xe)})}_n({userMessage:d,toolCalls:Wn,errors:he,recovered:he>0?!!ce.length:!1,durationMs:0})}throw new Error(`agent exceeded ${$n} tool steps`)}catch(m){m?.name!=="AbortError"&&w(m)}finally{p=!1,a=null}}async function k(){if(f)throw new Error("standalone client is stopped")}async function b(d,l={}){if(f)throw new Error("standalone client is stopped");if(d==="session.create")return x("session.info",{model:l.model||t.model,reasoning_effort:t.reasoningEffort,usage:{context_max:t.contextLength},backend:"standalone"}),{session_id:c,info:{model:l.model||t.model,reasoning_effort:t.reasoningEffort,usage:{context_max:t.contextLength},backend:"standalone"}};if(d==="prompt.submit"){if(p)throw new Error("a turn is already active");let h=String(l.text||"").trim();if(!h)throw new Error("prompt text is required");return queueMicrotask(()=>{S(h).catch(w)}),{accepted:!0}}if(d==="session.interrupt"){let h=!!(a&&p);return a?.abort(),{interrupted:h}}if(d==="session.usage")return{calls:0,input:0,output:0,total:0};throw new Error(`unsupported standalone method: ${d}`)}async function v(){f||(f=!0,a?.abort(),g.stop())}return Object.freeze({start:k,request:b,stop:v,on:n.on.bind(n),off:n.off.bind(n)})}async function Fn({client:e,text:t,stdout:n=process.stdout,stderr:r=process.stderr}={}){if(!e)throw new Error("standalone client is required");await e.start();let o=await e.request("session.create",{source:"cli"}),i="",s=!1;try{return await new Promise((c,u)=>{let a=f=>{let p=f?.params?.type,g=f?.params?.payload||{};if(p==="message.delta"&&typeof g.text=="string"){i+=g.text,n.write(g.text);return}if(p==="message.complete"){!i&&g.text&&n.write(String(g.text)),n.write(`
31
+ `),s=!0,c(0);return}if(p==="error"){let x=g.message||g.text||"standalone chat failed";r.write(`oracle chat: ${x}
32
+ `),s=!0,u(new Error(x))}};e.on("event",a),e.request("prompt.submit",{session_id:o.session_id,text:t}).catch(f=>{s||(s=!0,u(f))})})}finally{await e.stop()}}ht();var R="oracle",me="oracle";function zn(e){if(e==="hermes"){let t=Pe();return t.ok?t.bin:null}for(let t of(process.env.PATH||"").split(E.delimiter)){let n=E.join(t,e);try{if(C.existsSync(n))return n}catch{}}return null}function Mn(e){try{let t=C.readFileSync(e,"utf8").split(/\r?\n/,1)[0];if(!t.startsWith("#!"))return null;let n=t.slice(2).trim().split(/\s+/);if(n[0]?.endsWith("/env")&&n[1]?.startsWith("python"))return{command:n[0],prefix:[n[1]]};if(E.basename(n[0]||"").startsWith("python"))return{command:n[0],prefix:n.slice(1)}}catch{}return null}function qn(e){let t=Mn(e);if(t)return t;try{let r=C.readFileSync(e,"utf8").match(/["']([^"'\r\n]+\/bin\/hermes)["']/);if(r)return Mn(r[1])}catch{}return null}function pi(){return E.join(B,"src","cli","oracle-harness.py")}function Un(e,t){let n=pi(),r=process.env.ORACLE_PLAIN_HARNESS==="0"?null:qn(e);return r&&C.existsSync(n)?{command:r.command,args:[...r.prefix,n,...t]}:{command:e,args:t}}function mi(){return E.join(B,"skins","oracle.yaml")}function hi(e=R){let t=E.join(B,"profiles","oracle","SOUL.md");if(!C.existsSync(t))return{ok:!1,reason:"oracle persona missing from package"};let n=E.join(D(),"profiles",e,"SOUL.md");return C.existsSync(n)&&!C.readFileSync(n,"utf8").startsWith("You are Hermes Agent, an intelligent AI assistant created by Nous Research.")?{ok:!0,reused:!0}:(N(E.dirname(n)),C.copyFileSync(t,n),{ok:!0,reused:!1})}function xi(e=R){let t=mi();if(!C.existsSync(t))return{ok:!1,reason:"skin missing from package"};let n=E.join(D(),"skins"),r=E.join(D(),"profiles",e,"skins");N(n),N(r);let o=C.readFileSync(t,"utf8");return C.writeFileSync(E.join(n,`${me}.yaml`),o),C.writeFileSync(E.join(r,`${me}.yaml`),o),{ok:!0,skin:me}}function gi(e=R){let t=E.join(D(),"profiles",e,"config.yaml");if(!C.existsSync(t))return{ok:!1,reason:"profile config missing"};let n=zn("oracle")||E.join(B,"bin","oracle.mjs"),r=E.join(D(),"profiles",e,"oracle");N(r);let o={profile:e,skin:me,oracleBin:n,commands:{chain:[n,"chain"],setup:[n,"setup"]},updatedAt:new Date().toISOString()};return C.writeFileSync(E.join(r,"chat-surface.json"),JSON.stringify(o,null,2)+`
33
+ `,{mode:384}),{ok:!0,marker:o}}function yi(e=R){let t=E.join(B,"skills","oracle-chat");if(!C.existsSync(t))return{ok:!1,reason:"oracle-chat skill missing"};let n=E.join(D(),"profiles",e,"skills","oracle-chat");N(n);for(let r of C.readdirSync(t)){let o=E.join(t,r),i=E.join(n,r);C.statSync(o).isFile()&&C.copyFileSync(o,i)}for(let r of["chain","setup"]){let o=E.join(D(),"profiles",e,"skills",r);N(o);let i=E.join(t,`${r}.SKILL.md`),s=E.join(t,"SKILL.md"),c=C.existsSync(i)?C.readFileSync(i,"utf8"):C.readFileSync(s,"utf8");C.writeFileSync(E.join(o,"SKILL.md"),c)}return{ok:!0}}function bi(e=R){let t=zn("hermes");if(!t)return{ok:!1,reason:"hermes missing"};let n=di(t,["-p",e,"config","set","display.skin",me],{encoding:"utf8",timeout:3e4});return n.status!==0?{ok:!1,reason:(n.stderr||n.stdout||"config set failed").trim()}:{ok:!0}}function Dn(e){if(!C.existsSync(e))return!1;let t=C.readFileSync(e,"utf8");if(/^model:\s*\S+/m.test(t))return!0;let n=t.match(/^model:\s*\n((?:[ \t]+.*(?:\n|$))*)/m)?.[1]||"";return/^\s+(?:default|provider):\s*\S+/m.test(n)}function _i(e=R){let t=D();if(C.existsSync(E.join(t,"auth.json"))||C.existsSync(E.join(t,"profiles",e,"auth.json")))return!0;let n=["OPENROUTER_API_KEY","ANTHROPIC_API_KEY","OPENAI_API_KEY","XAI_API_KEY","GOOGLE_API_KEY","GEMINI_API_KEY","DEEPSEEK_API_KEY","HF_TOKEN","GLM_API_KEY","KIMI_API_KEY","MINIMAX_API_KEY"];if(n.some(r=>process.env[r]))return!0;for(let r of[E.join(t,".env"),E.join(t,"profiles",e,".env")]){if(!C.existsSync(r))continue;let o=C.readFileSync(r,"utf8");if(n.some(i=>new RegExp(`^${i}=.+`,"m").test(o)))return!0}return!1}function Bn(e=R){let t=D();return Dn(E.join(t,"config.yaml"))||Dn(E.join(t,"profiles",e,"config.yaml"))||_i(e)}function Kn(){return["oracle chat, filled lowercase oracle chat",""," oracle chat open interactive oracle chat",' oracle chat -q "..." one-shot query'," oracle chat --model <m> use a model for this session"," oracle chat --print-banner show filled oracle banner only","","inside chat:"," /chain list/select chains"," /setup messaging setup menu"," /model switch models (still one oracle persona)","","brand: filled lowercase oracle / classic boxed layout"].join(`
34
+ `)}function wi(){let e=Number(process.stdout?.columns||process.env.COLUMNS||80);return Number.isFinite(e)&&e>0?Math.floor(e):80}function vi(e){return Array.from(String(e)).length}function ki(e,t){let n=e.map(s=>s.trimEnd()),r=Math.max(0,...n.map(s=>vi(s))),o=Math.max(0,Math.floor((t-r)/2)),i=" ".repeat(o);return n.map(s=>s?`${i}${s}`:"")}function Hn(e){return`'${String(e).replace(/'/g,"'\\''")}'`}function Si(e){return e.user?`${e.user}@${e.host}`:e.host}function Ei(e,t){let n=e.path||"$HOME/.local/bin:/usr/local/bin:/usr/bin:/bin:/opt/homebrew/bin",r=["oracle","chat",...t].map(Hn).join(" ");return[/^[A-Za-z0-9_:$/.~+-]+$/.test(n)?`export PATH=${n}`:`export PATH=${Hn(n)}`,"export ORACLE_REMOTE_COMPUTE_DISABLE=1","export ORACLE_CHAT_BACKEND=auto",r].join("; ")}function Ai(){let e=[""," \u2588\u2588\u2588\u2588"," \u2591\u2591\u2588\u2588\u2588"," \u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588"," \u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588 \u2591\u2591\u2591\u2591\u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588","\u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2591\u2591 \u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2591\u2591 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588\u2591\u2591\u2591","\u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588"," \u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591",""];process.stdout.write(ki(e,wi()).join(`
35
35
  `)+`
36
- `)}function fi(e){let t={pass:[],query:null,model:null,provider:null};for(let n=0;n<e.length;n+=1){let r=e[n];if((r==="--model"||r==="-m")&&e[n+1]){t.model=e[++n],t.pass.push("--model",t.model);continue}if(r==="--provider"&&e[n+1]){t.provider=e[++n],t.pass.push("--provider",t.provider);continue}if((r==="-q"||r==="--query")&&e[n+1]){t.query=e[++n],t.pass.push("-q",t.query);continue}if(r==="--quiet"||r==="-Q"){t.pass.push("--quiet");continue}if(r==="--continue"||r==="-c"){t.pass.push("--continue");continue}t.pass.push(r)}return t}var ec={name:"chat",summary:"open the one oracle chat surface (telegram-like, multi-model)",group:"read",usage:Tn(),async run(e){let t=[...e.argv];if(t.includes("-h")||t.includes("--help"))return process.stdout.write(Tn()+`
37
- `),0;if(t.includes("--print-banner"))return li(),0;let n=fi(t),r={...process.env,...n.model?{ORACLE_MODEL:n.model}:{},...n.provider?{ORACLE_PROVIDER:n.provider}:{}},o=ne(),i=Bt({env:r,hermes:Ce(),storedConfig:ht(),oauthAvailable:_=>!!o.get(_),apiKeyResolver:_=>o.getApiKey(_)});if(i.kind==="unconfigured")return process.stderr.write(`${i.reason}
38
- `),1;if(i.kind==="remote")return me("ssh",["-o","BatchMode=yes","-o","ConnectTimeout=12",ai(i.config),ui(i.config,n.pass)],{stdio:"inherit",env:process.env},"oracle-remote-compute");let c=pe({ORACLE_CHAT_SURFACE:"1",ORACLE_PROFILE:T,ORACLE_NODE_BIN:process.execPath,ORACLE_CLI_ENTRY:S.join(M,"bin","oracle.mjs")});if(i.kind==="standalone"){let _=En({config:{...i.config,...n.model?{model:n.model}:{}}});if(n.query)try{return await An({client:_,text:n.query,stdout:process.stdout,stderr:process.stderr})}catch{return 1}let v=await De({client:_,args:t,env:c,cwd:process.cwd(),stdin:process.stdin,stdout:process.stdout});return v.native?v.code:(process.stderr.write(process.env.ORACLE_NATIVE_TUI==="0"?`oracle standalone chat requires the native TUI; remove ORACLE_NATIVE_TUI=0
36
+ `)}function Oi(e){let t={pass:[],query:null,model:null,provider:null};for(let n=0;n<e.length;n+=1){let r=e[n];if((r==="--model"||r==="-m")&&e[n+1]){t.model=e[++n],t.pass.push("--model",t.model);continue}if(r==="--provider"&&e[n+1]){t.provider=e[++n],t.pass.push("--provider",t.provider);continue}if((r==="-q"||r==="--query")&&e[n+1]){t.query=e[++n],t.pass.push("-q",t.query);continue}if(r==="--quiet"||r==="-Q"){t.pass.push("--quiet");continue}if(r==="--continue"||r==="-c"){t.pass.push("--continue");continue}t.pass.push(r)}return t}var va={name:"chat",summary:"open the one oracle chat surface (telegram-like, multi-model)",group:"read",usage:Kn(),async run(e){let t=[...e.argv];if(t.includes("-h")||t.includes("--help"))return process.stdout.write(Kn()+`
37
+ `),0;if(t.includes("--print-banner"))return Ai(),0;let n=Oi(t),r={...process.env,...n.model?{ORACLE_MODEL:n.model}:{},...n.provider?{ORACLE_PROVIDER:n.provider}:{}},o=se(),i=Vt({env:r,hermes:Pe(),storedConfig:St(),oauthAvailable:w=>!!o.get(w),apiKeyResolver:w=>o.getApiKey(w)});if(i.kind==="unconfigured")return process.stderr.write(`${i.reason}
38
+ `),1;if(i.kind==="remote")return ye("ssh",["-o","BatchMode=yes","-o","ConnectTimeout=12",Si(i.config),Ei(i.config,n.pass)],{stdio:"inherit",env:process.env},"oracle-remote-compute");let s=ge({ORACLE_CHAT_SURFACE:"1",ORACLE_PROFILE:R,ORACLE_NODE_BIN:process.execPath,ORACLE_CLI_ENTRY:E.join(B,"bin","oracle.mjs")});if(i.kind==="standalone"){let w=jn({config:{...i.config,...n.model?{model:n.model}:{}}});if(n.query)try{return await Fn({client:w,text:n.query,stdout:process.stdout,stderr:process.stderr})}catch{return 1}let S=await We({client:w,args:t,env:s,cwd:process.cwd(),stdin:process.stdin,stdout:process.stdout});return S.native?S.code:(process.stderr.write(process.env.ORACLE_NATIVE_TUI==="0"?`oracle standalone chat requires the native TUI; remove ORACLE_NATIVE_TUI=0
39
39
  `:`oracle standalone chat requires an interactive TTY or -q <query>
40
- `),1)}let a=i.bin;Zo(T),ei(T),ni(T);let u=ri(T);ti(T),!u.ok&&process.env.ORACLE_CLI_DEBUG&&process.stderr.write(`oracle chat: skin note: ${u.reason}
41
- `);let s=!!(n.model||n.provider);if(!Ln(T)&&!s){if(!process.stdin.isTTY||!process.stdout.isTTY)return process.stderr.write(`oracle chat needs a configured model
40
+ `),1)}let c=i.bin;hi(R),xi(R),yi(R);let u=bi(R);gi(R),!u.ok&&process.env.ORACLE_CLI_DEBUG&&process.stderr.write(`oracle chat: skin note: ${u.reason}
41
+ `);let a=!!(n.model||n.provider);if(!Bn(R)&&!a){if(!process.stdin.isTTY||!process.stdout.isTTY)return process.stderr.write(`oracle chat needs a configured model
42
42
  run: oracle model
43
43
  `),1;process.stdout.write(`choose oracle's model before first chat
44
44
 
45
- `);let _=Cn(a,["-p",T,"model"]),v=await me(_.command,_.args,{stdio:"inherit",env:process.env},"oracle-model");if(v!==0||!Ln(T))return v||1}let d=["-p",T,"chat"],p=Pn(a),y=await De({hermesPython:p,args:t,env:c,cwd:process.cwd(),stdin:process.stdin,stdout:process.stdout});if(y.native)return y.code;let x=Cn(a,[...d,...n.pass]);return me(x.command,x.args,{stdio:"inherit",env:c},"oracle-chat")}};export{ec as default,Xo as harnessSourcePath,Cn as oracleHarnessInvocation,Pn as resolveHermesPython};
45
+ `);let w=Un(c,["-p",R,"model"]),S=await ye(w.command,w.args,{stdio:"inherit",env:process.env},"oracle-model");if(S!==0||!Bn(R))return S||1}let f=["-p",R,"chat"],p=qn(c),g=await We({hermesPython:p,args:t,env:s,cwd:process.cwd(),stdin:process.stdin,stdout:process.stdout});if(g.native)return g.code;let x=Un(c,[...f,...n.pass]);return ye(x.command,x.args,{stdio:"inherit",env:s},"oracle-chat")}};export{va as default,pi as harnessSourcePath,Un as oracleHarnessInvocation,qn as resolveHermesPython};