@oracle-agent/oracle 0.16.0 → 0.17.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(`
1
+ var Dn=Object.defineProperty;var mt=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Bn=(e,t)=>{for(var n in t)Dn(e,n,{get:t[n],enumerable:!0})};import ce from"node:fs";import Kn from"node:os";import W from"node:path";import{fileURLToPath as Hn}from"node:url";function ae(){return process.env.ORACLE_FAKE_HOME||Kn.homedir()}function zn(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function U(){return zn()?process.env.ORACLE_CONFIG_DIR||W.join(ae(),".config","oracle"):W.join(ae(),".config","oracle")}function Wn(){return W.join(U(),"desk.json")}function Yn(){return W.join(U(),"env")}function X({force:e=!1}={}){if(X._done&&!e)return X._result||null;X._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=Yn();if(ce.existsSync(o))for(let i of ce.readFileSync(o,"utf8").split(/\r?\n/)){let s=i.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!s||s[2].startsWith("#"))continue;let a=s[2];(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),n(s[1],a)}}catch{}try{let o=Wn();if(ce.existsSync(o)){let i=JSON.parse(ce.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)),X._result=Object.keys(t).length?t:null,X._result}function D(){return process.env.HERMES_HOME?W.resolve(process.env.HERMES_HOME):W.join(ae(),".hermes")}function P(e){return ce.mkdirSync(e,{recursive:!0}),e}var qn,M,G=mt(()=>{qn=W.dirname(Hn(import.meta.url)),M=W.resolve(qn,"../..");try{X()}catch{}});var kn={};Bn(kn,{createOAuthStore:()=>ct,default:()=>Io,getOAuthStore:()=>oe,hasOAuthCredentials:()=>Sn,loginOAuth:()=>_n,oauthProviderConfig:()=>st,oauthProviderId:()=>H,oauthRuntimeConfig:()=>vn,refreshOAuthCredentials:()=>at,resolveOAuthCredentials:()=>wn});import{createHash as yo,randomBytes as ot,timingSafeEqual as go}from"node:crypto";import F from"node:fs";import ne from"node:path";import bo from"node:readline/promises";import{spawn as _o,spawnSync as wo}from"node:child_process";function it(e={}){return typeof e.now=="function"?Number(e.now()):Date.now()}function H(e){let t=String(e||"").trim().toLowerCase();for(let[n,r]of Object.entries(re))if(r.aliases.includes(t))return n;throw new Error(`unsupported OAuth provider: ${e||"(empty)"}`)}function st(e){let t=H(e);return{id:t,...re[t]}}function N(e,t={}){if(!F.existsSync(e))return t;try{let n=JSON.parse(F.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: ${ne.basename(e)}`)}}function bn(e){P(e),process.platform!=="win32"&&F.chmodSync(e,448)}function Y(e,t){bn(ne.dirname(e));let n=`${e}.${process.pid}.${ot(4).toString("hex")}.tmp`;F.writeFileSync(n,`${JSON.stringify(t,null,2)}
2
+ `,{mode:384}),F.renameSync(n,e),process.platform!=="win32"&&F.chmodSync(e,384)}function So(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 nt(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 fe(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 ct(e={}){let t=e.file||ne.join(U(),"oauth.json"),n=e.metadataFile||ne.join(ne.dirname(t),"oauth-meta.json"),r=e.spawnFn||wo,o=e.keychain!==!1&&process.env.ORACLE_AUTH_FILE_STORE!=="1"&&So(r),i=o?"linux-secret-service":"private-file",s=`${t}.lock`;async function a(b){bn(ne.dirname(s));let m;for(let h=0;h<400;h+=1)try{m=F.openSync(s,"wx",384);break}catch(l){if(l?.code!=="EEXIST")throw l;try{Date.now()-F.statSync(s).mtimeMs>3e5&&F.unlinkSync(s)}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{F.closeSync(m)}catch{}try{F.unlinkSync(s)}catch{}}}function u(b,m="oauth"){return["application","oracle","kind",m,"provider",b]}function c(b){let m=H(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 fe(JSON.parse(String(f.stdout).trim()))}catch{return null}}let l=N(t,{providers:{}}).providers?.[m];if(!l)return null;try{return fe(l)}catch{return null}}function d(b,m){let h=H(b),l=fe(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=N(n,{providers:{}});return O.providers||={},O.providers[h]={expiresAt:l.expiresAt,source:l.source},Y(n,O),l}let f=N(t,{providers:{}});return f.providers||={},f.providers[h]=l,Y(t,f),l}function p(b){let m=H(b);if(o){let f=r("secret-tool",["clear",...u(m)],{encoding:"utf8",stdio:["ignore","ignore","pipe"]}),w=N(n,{providers:{}});return w.providers&&delete w.providers[m],Y(n,w),!f.error&&f.status===0}let h=N(t,{providers:{}}),l=!!h.providers?.[m];return h.providers&&delete h.providers[m],Y(t,h),l}function g(b){let m=nt(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(N(t,{apiKeys:{}}).apiKeys?.[m]||"").trim()}function x(b,m){let h=nt(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=N(n,{providers:{},apiKeys:{}});return O.apiKeys||={},O.apiKeys[h]={configured:!0},Y(n,O),!0}let f=N(t,{providers:{},apiKeys:{}});return f.apiKeys||={},f.apiKeys[h]=l,Y(t,f),!0}function _(b){let m=nt(b);if(o){let f=r("secret-tool",["clear",...u(m,"api-key")],{encoding:"utf8",stdio:["ignore","ignore","pipe"]}),w=N(n,{providers:{},apiKeys:{}});return w.apiKeys&&delete w.apiKeys[m],Y(n,w),!f.error&&f.status===0}let h=N(t,{providers:{},apiKeys:{}}),l=!!h.apiKeys?.[m];return h.apiKeys&&delete h.apiKeys[m],Y(t,h),l}function S(){let b={},m={};if(o){let h=N(n,{providers:{},apiKeys:{}});for(let[l,f]of Object.entries(h.providers||{}))b[l]={loggedIn:!!c(l),expiresAt:Number(f.expiresAt||0),source:String(f.source||"oracle"),storage:i};for(let l of Object.keys(h.apiKeys||{}))m[l]={configured:!!g(l),storage:i}}else{let h=N(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:c,set:d,remove:p,getApiKey:g,setApiKey:x,removeApiKey:_,status:S,withLock:a})}function oe(){return gn||=ct(),gn}function rt(e){return Buffer.from(e).toString("base64url")}function vo(){let e=rt(ot(32));return{verifier:e,challenge:rt(yo("sha256").update(e).digest()),state:rt(ot(24))}}function ko(e,t){let n=Buffer.from(String(e||"")),r=Buffer.from(String(t||""));return n.length===r.length&&go(n,r)}function Eo(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 _o(n[0],n[1],{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function Ae(e){return new URLSearchParams(e).toString()}async function q(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 Ao(e){if(e)return String(await e()).trim();let t=bo.createInterface({input:process.stdin,output:process.stdout});try{return String(await t.question("Authorization code: ")).trim()}finally{t.close()}}function Oe(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 fe({accessToken:n,refreshToken:r,expiresAt:it(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 Oo(e){let t=re["anthropic-oauth"],n=e.pkce||vo(),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 Ao(e.inputFn),[s,a]=i.split("#",2);if(!s||!ko(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:s,state:a,redirect_uri:t.redirectUri,code_verifier:n.verifier})});return Oe(await q(u,"Claude OAuth token exchange"),e)}async function Co(e){let t=re["openai-codex"],n=await q(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 q(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:Ae({grant_type:"authorization_code",code:i.authorization_code,redirect_uri:`${t.issuer}/deviceauth/callback`,client_id:t.clientId,code_verifier:i.code_verifier})});return Oe(await q(s,"Codex OAuth token exchange"),e)}function J(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 Lo(e){let t=re["xai-oauth"],n=await q(await e.fetchFn(t.discoveryUrl,{headers:{accept:"application/json"}}),"xAI OAuth discovery");J(n.authorization_endpoint);let r=J(n.token_endpoint),o=await q(await e.fetchFn(t.deviceUrl,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:Ae({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=J(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)),a=Math.ceil(Math.max(1,Number(o.expires_in||600))/s);for(let u=0;u<a;u+=1){let c=await e.fetchFn(r,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:Ae({grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:t.clientId,device_code:o.device_code})});if(c.ok){let p=await q(c,"xAI OAuth token exchange");return Oe(p,{...e,discovery:{authorization_endpoint:J(n.authorization_endpoint),token_endpoint:r}})}let d="";try{d=String((await c.json())?.error||"")}catch{}if(d==="slow_down")await e.sleepFn((s+1)*1e3);else if(d==="authorization_pending")await e.sleepFn(s*1e3);else throw new Error(`xAI OAuth token exchange failed (HTTP ${c.status}${d?`, ${d}`:""})`)}throw new Error("xAI device authorization timed out")}async function _n(e,t={}){let n=H(e),r={fetchFn:t.fetchFn||globalThis.fetch,inputFn:t.inputFn,sleepFn:t.sleepFn||(o=>new Promise(i=>setTimeout(i,o))),openFn:t.openFn||Eo,output:t.output||(o=>process.stdout.write(`${o}
3
+ `)),now:t.now,pkce:t.pkce};return n==="anthropic-oauth"?Oo(r):n==="openai-codex"?Co(r):Lo(r)}async function at(e,t,n={}){let r=H(e),o=re[r],i=fe(t);if(!i.refreshToken)throw new Error(`${r} OAuth credential cannot refresh; run oracle auth login`);let s=i.discovery,a,u=n.fetchFn||globalThis.fetch;if(r==="xai-oauth"){if(!s?.token_endpoint){let p=await u(o.discoveryUrl),g=await q(p,"xAI OAuth discovery");s={...g.authorization_endpoint?{authorization_endpoint:J(g.authorization_endpoint)}:{},token_endpoint:J(g.token_endpoint)}}a=J(s.token_endpoint)}else a=o.tokenUrl;let c=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:Ae({grant_type:"refresh_token",refresh_token:i.refreshToken,client_id:o.clientId})}),d=await q(c,`${r} OAuth refresh`);return Oe(d,{...n,refreshToken:i.refreshToken,discovery:s})}async function wn(e,t={}){let n=H(e),r=t.store||oe(),o=r.get(n);if(!o)throw new Error(`${n} OAuth is not logged in; run oracle auth login ${e}`);let i=it(t);if(!o.expiresAt||o.expiresAt>i+yn)return o;let s=async()=>{let a=r.get(n);if(!a)throw new Error(`${n} OAuth is not logged in; run oracle auth login ${e}`);let u=it(t);if(!a.expiresAt||a.expiresAt>u+yn)return a;let c=await at(n,a,t);return r.set(n,c),c};return typeof r.withLock=="function"?r.withLock(s):s()}function Sn(e,t={}){try{return!!(t.store||oe()).get(e)?.accessToken}catch{return!1}}function vn(e){let t=st(e);return{kind:"standalone",provider:t.id,model:t.model,baseUrl:t.baseUrl,authType:"oauth",protocol:t.protocol}}var re,yn,gn,Io,ut=mt(()=>{G();re=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"}}),yn=12e4;Io={createOAuthStore:ct,getOAuthStore:oe,hasOAuthCredentials:Sn,loginOAuth:_n,oauthProviderConfig:st,oauthProviderId:H,oauthRuntimeConfig:vn,refreshOAuthCredentials:at,resolveOAuthCredentials:wn}});G();import A from"node:fs";import v from"node:path";import{spawnSync as ni}from"node:child_process";import xt from"node:fs";import Jn from"node:path";var Gn=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 Le(e){return String(e||"").trim().toLowerCase().replace(/^\/+/,"").replace(/\s+/g,"-")}function ht(e){let t=Le(e);if(!t)return null;for(let n of Gn)if(n.key===t||String(n.chainId).toLowerCase()===t||(n.aliases||[]).map(Le).includes(t)||Le(n.name)===t)return n;return null}G();function Vn(){return Jn.join(U(),"active-chain.json")}function Xn(){let e=Vn();if(!xt.existsSync(e))return null;try{let t=JSON.parse(xt.readFileSync(e,"utf8"));if(!t||typeof t!="object"||!t.key)return null;let n=ht(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 he(e={}){let t=Xn(),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}G();import yt from"node:fs";import Qn from"node:path";var Zn=new Set(["auto","standalone","hermes","remote","arch"]),er=new Set(["openrouter","openai","xai","deepseek","gemini","custom","anthropic-oauth","openai-codex","xai-oauth"]);function tr(){return Qn.join(U(),"model.json")}function B(e){return String(e||"").trim()||void 0}function nr(e={}){let t=B(e.backend)?.toLowerCase()||"auto",n=B(e.provider)?.toLowerCase(),r=B(e.model),o=B(e.baseUrl)?.replace(/\/+$/,""),i=B(e.apiKeyEnv),s=Number.parseInt(String(e.contextLength||""),10),a=B(e.reasoningEffort),u=B(e.computeHost||e.remoteHost),c=B(e.computeUser||e.remoteUser),d=B(e.computePath||e.remotePath);if(!Zn.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&&!er.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}:{},...a?{reasoningEffort:a}:{},...u?{computeHost:u}:{},...c?{computeUser:c}:{},...d?{computePath:d}:{}}}function gt(){let e=tr();if(!yt.existsSync(e))return null;try{return nr(JSON.parse(yt.readFileSync(e,"utf8")))}catch{return null}}import{spawn as rr}from"node:child_process";var or=["SIGINT","SIGTERM","SIGHUP"];function xe(e,t=[],n={},r=e){return new Promise(o=>{let i=rr(e,t,n),s=!1,a=null,u=new Map(or.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 c=()=>{for(let[d,p]of u)process.off(d,p)};i.once("error",d=>{s||(s=!0,c(),process.stderr.write(`oracle: could not start ${r}: ${d.message}
4
+ `),o(1))}),i.once("exit",(d,p)=>{if(s)return;s=!0,c();let g=a||p;if(g){process.kill(process.pid,g);return}o(d??1)})})}import _t from"node:fs";import Q from"node:path";G();var ir="0.19.0",Ui=`hermes-agent==${ir}`;var bt="0.12.1",Di=Object.freeze({posix:Object.freeze({url:`https://github.com/astral-sh/uv/releases/download/${bt}/uv-installer.sh`,sha256:"d3f5412d38c99f9d024901843bf98206f0d2c6dbe64df40d0b740e2751ca62c1"}),windows:Object.freeze({url:`https://github.com/astral-sh/uv/releases/download/${bt}/uv-installer.ps1`,sha256:"b9ec035151bfbb11d616dbd69886498d885551489eddf095ea3c0ad59f640eb0"})});function sr(){return Q.join(U(),"runtime")}function cr(){return Q.join(sr(),"venv")}function ar(e){let t=process.platform==="win32"?"Scripts":"bin",n=process.platform==="win32"?`${e}.exe`:e;return Q.join(cr(),t,n)}function ur(){return ar("hermes")}function lr(e){let t=process.platform==="win32"&&!Q.extname(e)?["",".exe",".cmd",".bat"]:[""];for(let n of(process.env.PATH||"").split(Q.delimiter))if(n)for(let r of t){let o=Q.join(n,`${e}${r}`);try{if(_t.existsSync(o))return o}catch{}}return null}function Ie(){if(process.env.ORACLE_HERMES_BIN)return{ok:!0,bin:process.env.ORACLE_HERMES_BIN,source:"env"};let e=lr("hermes");if(e)return{ok:!0,bin:e,source:"path"};let t=ur();return _t.existsSync(t)?{ok:!0,bin:t,source:"managed"}:{ok:!1,bin:null,source:null}}import{EventEmitter as Hr}from"node:events";import{spawn as fr}from"node:child_process";import{EventEmitter as dr}from"node:events";import{createInterface as wt}from"node:readline";var pr=15e3,mr=12e4;function hr(e){let t=typeof e=="string"?e:e?.message||"Gateway request failed",n=new Error(t);return n.error=e,n}function xr(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 St({python:e,pythonArgs:t=[],cwd:n,env:r,spawnFn:o=fr,startupTimeoutMs:i=pr,requestTimeoutMs:s=mr}={}){let a=new dr,u=new Map,c=null,d=1,p=null,g=null,x=!1;function _(f){a.listenerCount("error")>0&&a.emit("error",f)}function S(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(hr(f.error)):w.resolve(f.result))}function m(){return p||(p=new Promise((f,w)=>{let O=!1,k,y=C=>{O||(O=!0,clearTimeout(k),C?w(C):f())};try{c=o(e,[...t,"-m","tui_gateway.entry"],{cwd:n,env:r})}catch(C){y(C),_(C);return}let I=wt({input:c.stdout}),z=wt({input:c.stderr});I.on("line",C=>{let j;try{j=JSON.parse(C)}catch{a.emit("log",C);return}y(),b(j)}),z.on("line",C=>a.emit("log",xr(C))),c.once("error",C=>{y(C),S(C),_(C)}),c.once("exit",(C,j)=>{x=!0;let ie=new Error(`Gateway exited with code ${C} and signal ${j}`);y(ie),S(ie),a.emit("exit",{code:C,signal:j})}),k=setTimeout(()=>{y(new Error(`Gateway startup timed out after ${i} ms`))},i)}),p)}function h(f,w){if(!c||x)return Promise.reject(new Error("Gateway is not running"));let O=d++;return new Promise((k,y)=>{let I=setTimeout(()=>{u.delete(O),y(new Error(`Gateway request ${O} timed out after ${s} ms`))},s);u.set(O,{resolve:k,reject:y,timer:I});try{c.stdin.write(`${JSON.stringify({id:O,method:f,params:w})}
5
+ `)}catch(z){clearTimeout(I),u.delete(O),y(z)}})}function l(){if(g)return g;if(!c||x)return Promise.resolve();let f=new Error("Gateway stopped while requests were pending");return S(f),g=new Promise(w=>{c.once("exit",w);try{c.kill()}catch{w()}}),g}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 ue=Buffer.alloc(0),yr=new Set(["return","backspace","tab","escape","up","down","left","right","home","end","delete","insert","pageup","pagedown","unknown"]),gr={A:"up",B:"down",C:"right",D:"left",H:"home",F:"end",P:"f1",Q:"f2",R:"f3",S:"f4"},br={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 At(e){return e<128?1:e>=240?4:e>=224?3:e>=192?2:1}function _r(e){return e>=64&&e<=126}function vt(e){let t=e.toLowerCase();return $({name:t,shift:e!==t,sequence:e})}function wr(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 Sr(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,s=r;if(o==="~"?i=br[n]??null:(i=gr[o]??null,s===null&&n!==null&&n>1&&(s=n)),!i)return $({name:"unknown",sequence:e});let a=s===null?0:Math.max(0,s-1);return $({name:i,shift:(a&1)!==0,meta:(a&2)!==0,ctrl:(a&4)!==0,sequence:e})}function vr(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 c=t+2;for(;c<e.length&&!_r(e[c]);)c+=1;return c>=e.length?r?o():0:(n.push(Sr(e.toString("utf8",t,c+1))),c+1-t)}if(i===27)return o();let s=At(i);if(t+1+s>e.length)return r?o():0;let a=e.toString("utf8",t+1,t+1+s),u=a.toLowerCase();return n.push($({name:u,meta:!0,shift:a!==u,sequence:`\x1B${a}`})),1+s}function kt(e,t){let n=[],r=0;for(;r<e.length;){let o=e[r];if(o===27){let s=vr(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(wr(o)),r+=1;continue}let i=At(o);if(r+i>e.length)return t?(n.push(vt(e.toString("utf8",r))),{keys:n,rest:ue}):{keys:n,rest:Buffer.from(e.subarray(r))};n.push(vt(e.toString("utf8",r,r+i))),r+=i}return{keys:n,rest:ue}}function Et(e){return Buffer.isBuffer(e)?e:e==null?ue:typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}function kr(){let e=ue;return{push(t){let n=e.length===0?Et(t):Buffer.concat([e,Et(t)]),{keys:r,rest:o}=kt(n,!1);return e=o,r},flush(){if(e.length===0)return[];let{keys:t}=kt(e,!0);return e=ue,t},get pending(){return e.length}}}function Er({history:e=[]}={}){let t=[...e];return{buffer:"",cursor:0,history:t,historyIndex:t.length,draft:""}}function Re(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 Te(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 Ot(e,t){return E(e,{...t,historyIndex:e.history.length,draft:""})}function Ar(e){if(e.ctrl||e.meta||!e.sequence||yr.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 Or(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 Cr(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 Lr(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 Ir(e){let t=e.buffer.trim();if(t==="")return{state:Ot(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 Rr(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:Ot(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=Or(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:Re(n,r)}),action:null};case"f":return{state:E(e,{cursor:Te(n,r)}),action:null};default:return{state:E(e,{}),action:null}}switch(t.name){case"return":return Ir(e);case"left":return{state:E(e,{cursor:Re(n,r)}),action:null};case"right":return{state:E(e,{cursor:Te(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 Cr(e);case"down":return Lr(e);case"backspace":{if(r===0)return{state:E(e,{}),action:null};let o=Re(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=Te(n,r);return{state:E(e,{buffer:n.slice(0,r)+n.slice(o)}),action:null}}default:break}if(Ar(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 Ct(e={}){let{stdin:t,stdout:n,history:r=[],onSubmit:o,onCancel:i,onEof:s,onClear:a,onRender:u}=e,c=t??process.stdin,d=n??process.stdout,p=kr(),g={submit:o,cancel:i,eof:s,clear:a},x=Er({history:r}),_=!1,S=!1,b=!1,m=l=>{if(!l)return;let f=g[l.type];typeof f=="function"&&f(l.value,x)},h=l=>{for(let f of p.push(l)){let w=Rr(x,f);x=w.state,m(w.action),typeof u=="function"&&u(x)}};return{start(){_||(_=!0,c.isTTY&&typeof c.setRawMode=="function"&&(b=c.isRaw===!0,c.setRawMode(!0),S=!0),typeof c.resume=="function"&&c.resume(),c.on("data",h),typeof u=="function"&&u(x))},stop(){_&&(_=!1,typeof c.off=="function"?c.off("data",h):typeof c.removeListener=="function"&&c.removeListener("data",h),S&&typeof c.setRawMode=="function"&&(c.setRawMode(b),S=!1),typeof c.pause=="function"&&c.pause())},getState(){return x},setState(l){return x=l,x},write(l){d&&typeof d.write=="function"&&d.write(l)},get isRunning(){return _}}}var $e="\x1B[?25l",ye="\x1B[?25h",Lt="\x1B[2K",ge="\x1B[0J";var Tr="\x1B\\[[0-9;?]*[a-zA-Z]";function Tt(){return new RegExp(Tr,"g")}function $r(e){return String(e??"").replace(Tt(),"")}function It(e,t){return t.some(([n,r])=>e>=n&&e<=r)}function $t(e){return e===0||e<32||e>=127&&e<160||It(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:It(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 Pr(e){let t=0;for(let n of Array.from(e))t+=$t(n.codePointAt(0));return t}function Nr(e){return Pr($r(e))}function jr(e){return/^\u001b\[0*m$/.test(e)}function Rt(e,t){let n="",r=0;for(let o of Array.from(e)){let i=$t(o.codePointAt(0));if(r+i>t)break;n+=o,r+=i}return{text:n,width:r}}function Fr(e,t){let n=String(e??"");if(t<=0)return"";if(Nr(n)<=t)return n;let r=Tt(),o="",i=0,s=!1,a=0,u=r.exec(n);for(;u!==null;){let d=Rt(n.slice(a,u.index),t-i);if(o+=d.text,i+=d.width,i>=t)return s?`${o}\x1B[0m`:o;o+=u[0],u[0].endsWith("m")&&(s=!jr(u[0])),a=u.index+u[0].length,u=r.exec(n)}let c=Rt(n.slice(a),t-i);return o+=c.text,s?`${o}\x1B[0m`:o}function Mr(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 Pt({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),a=[],u=0,c=null,d=!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),d=!0},x=typeof e.on=="function";x&&e.on("resize",g);function _(m){let h=m-u;return u=m,h===0?"":h<0?`\x1B[${-h}A`:`\x1B[${h}B`}function S(m){let l=(Array.isArray(m)?m:[]).map(f=>Fr(String(f??""),s));if(c!==null)for(l.length>c&&(l=l.slice(0,c));l.length<c;)l.push("");return l}function b(m){if(!d&&Mr(a,m))return;let h=[$e];d&&a.length>0&&(h.push(_(0),"\r",ge),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",Lt,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",Lt,m[f]),u=f}else m.length<a.length&&h.push(_(m.length),"\r",ge);m.length>0&&h.push(_(m.length-1)),h.push(ye),a=m,e.write(h.join(""))}return{render(m){p||b(S(m))},writeAbove(m){if(p)return;let h=String(m??""),l=$e;a.length>0&&(l+=`${_(0)}\r${ge}`),l+=h.endsWith(`
8
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
9
+ `,e.write(l);let f=a;a=[],u=0,f.length>0?b(f):e.write(ye)},clear(){if(p)return;let m=$e;a.length>0&&(m+=`${_(0)}\r${ge}`),m+=ye,e.write(m),a=[],u=0,d=!1},setLines(m){c=Number.isFinite(m)&&m>=0?Math.trunc(m):null},getLines(){return a.slice()},getSize(){return{rows:i,columns:s}},dispose(){if(!p){if(p=!0,x){let m=typeof e.off=="function"?e.off:e.removeListener;typeof m=="function"&&m.call(e,"resize",g)}e.write(ye)}}}}var R=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 Ur(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 Nt(e,t,n){let r=Ur(t);return r?`\x1B[${e};2;${r.r};${r.g};${r.b}m${String(n)}\x1B[0m`:String(n)}function Pe({color:e=!0}={}){return e&&!Object.hasOwn(process.env,"NO_COLOR")?Object.freeze({fg:(n,r)=>Nt(38,n,r),bg:(n,r)=>Nt(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 Gi=Pe();function jt(e){return String(e).replace(/\u001B\[[0-9;]*m/g,"")}var Ft=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 "]]),Ne="THE FUTURE IS AGENTIC / by DEMI",je=/\u001B\[[0-9;]*m/g;function Ut(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 K(e){return[...jt(e)].reduce((t,n)=>t+Ut(n),0)}function Me(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(je.test(s)){je.lastIndex=0,r+=s,i=s!=="\x1B[0m";continue}je.lastIndex=0;for(let a of s){let u=Ut(a);if(o+u>t)return i?`${r}\x1B[0m`:r;r+=a,o+=u}}return r}function Z(e,t,n="left"){let r=Math.max(0,Math.floor(Number(t)||0)),o=Me(String(e),r),i=Math.max(0,r-K(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 Ue(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 a of o.split(" ")){let u=K(a);if(s>0&&s+1+u>n&&(r.push(i),i="",s=0),u>n){s>0&&(r.push(i),i="",s=0);let c=a;for(;K(c)>n;){let d=Me(c,n);r.push(d),c=c.slice(d.length)}i=c,s=K(c);continue}i=s===0?a:`${i} ${a}`,s=s===0?u:s+1+u}r.push(i)}return r}function Dr(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 Br(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 Mt(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 De({width:e,palette:t}){let n=Dr(e),{target:r,panelWidth:o,panelLeft:i,inner:s}=n;if(r<72||s<=0)return[Z(t.bold(t.fg(R.accent,"oracle")),r,"center"),Z(t.fg(R.banner_text,Ne),r,"center")];let a=Ft.map(([,l])=>l),{offset:u,width:c}=Br(a),d=" ".repeat(Mt(n,c,u)),p=" ".repeat(Mt(n,K(Ne))),g=[];for(let[l,f]of Ft)g.push(t.bold(t.fg(l,`${d}${f.replace(/\s+$/,"")}`)));g.push(""),g.push(t.bold(t.fg(R.banner_text,`${p}${Ne}`)));let x=l=>t.fg(R.banner_border,l),_=" ".repeat(i),S="\u2500".repeat(Math.max(0,o-2)),b=l=>Z(`${_}${l}`,r),m=[b(`${x("\u256D")}${x(S)}${x("\u256E")}`)],h=b(`${x("\u2502")}${" ".repeat(Math.max(0,o-2))}${x("\u2502")}`);m.push(h);for(let l of g)m.push(b(`${x("\u2502")} ${Z(l,s)} ${x("\u2502")}`));return m.push(h),m.push(b(`${x("\u2570")}${x(S)}${x("\u256F")}`)),m}function Dt({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=Me(String(r),Math.max(0,i-2)),a=s?` ${s} `:"",u=`${a}${"\u2500".repeat(Math.max(0,i-K(a)))}`,c=d=>n.fg(R.banner_border,d);return[`${c("\u256D")}${c(u)}${c("\u256E")}`,...e.map(d=>`${c("\u2502")}${Z(d,i)}${c("\u2502")}`),`${c("\u2570")}${c("\u2500".repeat(i))}${c("\u256F")}`]}function Fe(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 Kr(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 be(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 Bt({model:e,contextTokens:t,contextLength:n,percent:r,effort:o,thinking:i,chain:s,width:a,palette:u}){let c=Math.max(0,Math.floor(Number(a)||0)),d=u.fg(R.status_bar_dim," / "),p=c>=120?12:c>=60?8:4,g=Number(n)>0?`${Fe(t)}/${Fe(n)}`:Fe(t),x=Number.isFinite(Number(r))?`${Math.round(Number(r))}%`:"0%",_=[{text:String(e??""),strong:!0}];Number(n)>0&&_.push({text:`ctx ${Kr(r,p)} ${g} ${x}`}),o&&_.push({text:String(o)}),i&&_.push({text:String(i)}),typeof s=="string"&&s.length>0&&_.push({text:s});let S=_,b=h=>h.reduce((l,f,w)=>l+K(f.text)+(w>0?3:0),0);for(;S.length>1&&b(S)>c;)S=S.slice(0,-1);let m=S.map(h=>h.strong?u.fg(R.status_bar_strong,h.text):u.fg(R.status_bar_text,h.text)).join(d);return u.bg(R.status_bar_bg,Z(m,c))}var qr=6;function zr(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 Be(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 Wr(e){let t=e.width,n=`${e.promptLabel} `,r=Math.max(1,t-2-K(n)),o=e.buffer||"",i=Math.max(0,Math.min(e.cursor??o.length,o.length)),s=0;i>r&&(s=i-r);let a=o.slice(s,s+r),u=i-s,c=a.slice(0,u),d=a.slice(u,u+1)||" ",p=a.slice(u+1),g=e.palette;return[`${g.fg(R.accent,n)}${c}${g.bg(R.selection_bg,d)}${p}`]}function Yr(e){let t=e.width,n=[];if(e.liveLines.length>0){for(let r of e.liveLines.slice(-qr))n.push(r);n.push("")}return n.push(...Dt({lines:Wr(e),width:t,palette:e.palette,title:"Ask Oracle \u203A"})),n.push(Bt({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 Gr(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 _e(e={}){return typeof e.text=="string"?e.text:typeof e.rendered=="string"?e.rendered:typeof e.message=="string"?e.message:""}function Jr(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||Pe({color:t.isTTY!==!1}),i=e.renderer||Pt({stdout:t,rows:t.rows,columns:r}),s=e.client||St({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 Hr,u=e.now||(()=>Date.now()),c={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,g={renderer:i,state:c};function x(){i.render(Yr(c))}function _(k){i.writeAbove(`${k}
11
+ `)}function S(){let k=c.assistantBuffer.split(`
12
+ `),y=k[k.length-1]||"";c.liveLines=y?Ue(y,c.width):[]}function b({final:k=!1}={}){let y=c.assistantBuffer.split(`
13
+ `),I=k?y.length:y.length-1,z=!1;for(;c.flushedLines<I;){let C=y[c.flushedLines];for(let j of Ue(C,c.width))_(j);c.flushedLines+=1,z=!0}return k?c.liveLines=[]:S(),z}function m(){p||(p=setInterval(()=>{c.busy&&(c.thinking=be(u()-c.startedAt),x())},250),typeof p.unref=="function"&&p.unref())}function h(){p&&(clearInterval(p),p=null)}async function l(k){let y=String(k||"").trim();if(y){if(y==="/exit"||y==="/quit"){await O();return}if(y==="/clear"){i.clear();for(let I of De({width:c.width,palette:o}))_(I);x();return}c.busy=!0,c.assistantBuffer="",c.flushedLines=0,c.liveLines=[],c.startedAt=u(),c.thinking="0s",_(`${o.bold(o.fg(R.prompt,"you"))} ${y}`),_(""),m(),x(),await s.request("prompt.submit",{session_id:c.sessionId,text:y})}}function f(k){let y=Gr(k);if(y.type!=="gateway.ready"){if(y.type==="session.info"&&y.payload){y.payload.model&&(c.model=y.payload.model),y.payload.reasoning_effort&&(c.effort=y.payload.reasoning_effort),Be(c,y.payload.usage),x();return}if(y.type==="message.start"){c.busy=!0,c.cancelled=!1,c.assistantBuffer="",c.flushedLines=0,c.liveLines=[],_(o.bold(o.fg(R.accent,"oracle"))),x();return}if(y.type==="thinking.delta"||y.type==="reasoning.delta"){if(c.cancelled)return;_e(y.payload).trim()&&(c.thinking=`${be(u()-c.startedAt)}`),x();return}if(y.type==="message.delta"){if(c.cancelled)return;c.assistantBuffer+=_e(y.payload),b(),x();return}if(y.type==="message.complete"){if(c.cancelled){c.cancelled=!1;return}let I=_e(y.payload);I&&I.length>=c.assistantBuffer.length&&(c.assistantBuffer=I),b({final:!0}),_(""),c.busy=!1,h(),Be(c,y.payload?.usage||y.payload?.context),c.thinking=be(u()-c.startedAt),x();return}y.type==="error"&&(c.busy=!1,h(),_(o.fg(R.error,`error: ${_e(y.payload)||"unknown"}`)),x())}}async function w(){await s.start(),s.on("event",f),s.on("log",y=>a.emit("log",y)),s.on("error",y=>a.emit("error",y));let k=await s.request("session.create",{cols:c.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}:{}});c.sessionId=k.session_id,c.model=k.info?.model||c.model,k.info?.reasoning_effort&&(c.effort=k.info.reasoning_effort),Be(c,k.info?.usage);for(let y of De({width:c.width,palette:o}))_(y);_(""),x(),d=Ct({stdin:n,stdout:t,onSubmit:y=>{l(y).catch(I=>a.emit("error",I))},onCancel:()=>{c.busy&&(c.busy=!1,c.cancelled=!0,h(),b({final:!0}),_(o.fg(R.warn,"interrupted")),_(""),x(),s.request("session.interrupt",{session_id:c.sessionId}).catch(y=>a.emit("error",y)))},onEof:()=>{O().catch(y=>a.emit("error",y))},onClear:()=>{i.clear(),x()},onRender:y=>{c.buffer=y.buffer||"",c.cursor=y.cursor??c.buffer.length,x()}}),d.start()}async function O(){h(),d&&d.stop(),i.dispose(),await s.stop(),a.emit("stop")}return Object.freeze({start:w,stop:O,on:a.on.bind(a),off:a.off.bind(a),state:c,handleEvent:f,submit:l})}async function Ke({hermesPython:e,client:t,tuiFactory:n=Jr,args:r=[],env:o=process.env,cwd:i=process.cwd(),stdout:s=process.stdout,stdin:a=process.stdin}={}){let u=zr(r);if(u.query)return{native:!1,pass:u.pass};if(!a.isTTY||!s.isTTY)return{native:!1,pass:u.pass};if(o.ORACLE_NATIVE_TUI==="0")return{native:!1,pass:u.pass};let c=e;if(!t&&!c)return{native:!1,pass:u.pass};let d=he({...o,ORACLE_CHAT_SURFACE:"1",ORACLE_PROFILE:"oracle",ORACLE_NODE_BIN:process.execPath}),p=n({...t?{client:t}:{},...c?{python:c.command,pythonArgs:c.prefix||[]}:{},cwd:i,env:d,stdin:a,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,_=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",_),process.once("SIGTERM",_)})}import Vr from"node:fs";import Kt from"node:path";var Ht=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"}}),Xr=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 Qr(e,t){let n=Number(e);return Number.isSafeInteger(n)&&n>0?n:t}function Zr(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(Ht))if(e[o.key]||o.alternateKey&&e[o.alternateKey])return r;return null}function eo(e=process.env,t={},n=()=>!1,r=()=>""){let o=Zr(e,t);if(!o)return null;let i=Xr[o],s=Ht[o]||i,a=String(e.ORACLE_API_KEY_ENV||t.apiKeyEnv||""),u=String(e.ORACLE_API_KEY||a&&e[a]||s&&(e[s.key]||s.alternateKey&&e[s.alternateKey])||r(o)||""),c=String(i?i.baseUrl:o==="custom"?e.ORACLE_BASE_URL||t.baseUrl||"":s?.baseUrl||"").replace(/\/+$/,""),d=String(e.ORACLE_MODEL||t.model||s?.model||"");if(!c||!d)return null;let p=!!(i&&n(o));return i&&!p||!i&&o!=="custom"&&!u?null:{kind:"standalone",provider:o,model:d,baseUrl:c,...p?{authType:"oauth",protocol:i.protocol}:{apiKey:u},contextLength:Qr(e.ORACLE_CONTEXT_LENGTH||t.contextLength,128e3),reasoningEffort:String(e.ORACLE_REASONING_EFFORT||t.reasoningEffort||"high")}}function ee(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 to(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 no=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 ro(e){for(let t of(process.env.PATH||"").split(Kt.delimiter)){let n=Kt.join(t,e);try{if(Vr.existsSync(n))return n}catch{}}return null}function qt({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=to(e,n||{});if(i==="remote"||i==="arch")return s?{kind:"remote",config:s}:{kind:"unconfigured",reason:ee(`${i} compute backend was requested, but no compute host is configured.`)};let a=eo(e,n||{},r,o);if(i==="standalone")return a?{kind:"standalone",config:a}:{kind:"unconfigured",reason:ee("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:ee("ORACLE_CHAT_BACKEND=hermes was requested, but Hermes was not found.")};if(i!=="auto"){for(let u of no)if(u.name===i){let c=ro(u.bin);return c?{kind:"harness",harness:{...u,path:c}}:{kind:"unconfigured",reason:ee(`ORACLE_CHAT_BACKEND=${i} was requested, but ${u.bin} was not found on PATH.`)}}return{kind:"unconfigured",reason:ee(`Unknown ORACLE_CHAT_BACKEND value: ${i}`)}}return s?{kind:"remote",config:s}:a?{kind:"standalone",config:a}:t?.ok?{kind:"hermes",bin:t.bin}:{kind:"unconfigured",reason:ee()}}G();import Ro from"node:fs";import Cn from"node:path";import{randomUUID as En}from"node:crypto";import{EventEmitter as To}from"node:events";import{spawnSync as $o}from"node:child_process";import we from"node:fs";import zt from"node:path";import{homedir as oo}from"node:os";var qe=process.env.ORACLE_CONFIG_DIR||zt.join(oo(),".config","oracle"),Wt=zt.join(qe,"memory.json"),He=2200;function Yt(e){we.existsSync(e)||we.mkdirSync(e,{recursive:!0})}function ze(){Yt(qe);try{let e=we.readFileSync(Wt,"utf8");return JSON.parse(e)}catch{return{version:1,updatedAt:new Date().toISOString(),entries:[]}}}function Gt(e){Yt(qe),e.updatedAt=new Date().toISOString(),we.writeFileSync(Wt,JSON.stringify(e,null,2),{mode:384})}function Jt(e,t){let n=ze(),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>He&&n.entries.length>1;)n.entries.shift();Gt(n)}function Vt(e){let t=ze(),n=t.entries.length;return t.entries=t.entries.filter(r=>r.key!==e),t.entries.length<n?(Gt(t),{ok:!0}):{ok:!1}}function Xt(){let e=ze();if(e.entries.length===0)return"";let t=JSON.stringify(e.entries).length,n=Math.round(t/He*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}/${He} 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 Qt=[{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 Se from"node:path";import{homedir as io}from"node:os";var so=process.env.ORACLE_CONFIG_DIR||Se.join(io(),".config","oracle"),te=Se.join(so,"skills"),co=/^[a-z0-9][a-z0-9_-]{0,63}$/;function We(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 Zt(){return L.constants.O_NOFOLLOW||0}function en(e){let t=L.lstatSync(e);if(t.isSymbolicLink()||!t.isFile())return null;let n=L.openSync(e,L.constants.O_RDONLY|Zt());try{return L.readFileSync(n,"utf8")}finally{L.closeSync(n)}}function ao(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|Zt(),384);try{L.writeFileSync(n,t)}finally{L.closeSync(n)}try{L.chmodSync(e,384)}catch{}}function tn(e){let t=String(e??"").trim();if(!co.test(t))throw new Error("invalid skill name");return Se.join(te,`${t}.md`)}function Ye(){let e=[];try{We(te);for(let t of L.readdirSync(te,{withFileTypes:!0})){if(!t.isFile()||!t.name.endsWith(".md"))continue;let n=Se.join(te,t.name),r=en(n);if(r===null)continue;let o=t.name.replace(/\.md$/,""),i="",s=r.match(/^description:\s*(.+)$/m);s?i=s[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 Ge(e){try{We(te);let t=tn(e);return en(t)}catch{return null}}function nn(e){let t=Ye();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 a=(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)-a})}return["## Skills","Available (use skill_load <name>):",...n.map(o=>`- **${o.name}**: ${o.description}`)].join(`
21
+ `)}function rn(e,t){We(te);let n=tn(e);if(L.existsSync(n)&&!L.lstatSync(n).isFile())throw new Error("skill path must be a regular file");ao(n,t)}var on=[{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 ve from"node:fs";import cn from"node:path";import{homedir as uo}from"node:os";import{EventEmitter as lo}from"node:events";var Je=process.env.ORACLE_CONFIG_DIR||cn.join(uo(),".config","oracle"),an=cn.join(Je,"cron.json");function un(e){ve.existsSync(e)||ve.mkdirSync(e,{recursive:!0})}function le(){un(Je);try{return JSON.parse(ve.readFileSync(an,"utf8"))}catch{return{version:1,jobs:[]}}}function Ve(e){un(Je),ve.writeFileSync(an,JSON.stringify(e,null,2),{mode:384})}function ke(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 Xe(){return le().jobs}function Qe(e){let t=le(),n=`cron_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`,r=ke(e.schedule)||36e5,o={...e,id:n,createdAt:new Date().toISOString(),nextRunAt:new Date(Date.now()+r).toISOString()};return t.jobs.push(o),Ve(t),o}function Ze(e){let t=le(),n=t.jobs.length;return t.jobs=t.jobs.filter(r=>r.id!==e),t.jobs.length<n?(Ve(t),!0):!1}function sn(e){let t=le(),n=t.jobs.find(i=>i.id===e);if(!n)return;n.lastRunAt=new Date().toISOString();let r=ke(n.schedule)||36e5,o=n.lastRunAt?new Date(n.lastRunAt).getTime():Date.now();n.nextRunAt=new Date(o+r).toISOString(),Ve(t)}function ln(e){let t=new lo,n=new Map;function r(){let i=le();for(let s of i.jobs){if(!s.enabled)continue;let a=ke(s.schedule);if(!a)continue;let u=setInterval(async()=>{try{t.emit("run",{id:s.id,name:s.name}),await e(s.prompt,s.skills),sn(s.id),t.emit("complete",{id:s.id,name:s.name})}catch(c){t.emit("error",{id:s.id,name:s.name,error:c})}},a);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=Qe(i);if(s.enabled){let a=ke(s.schedule);if(a){let u=setInterval(async()=>{try{t.emit("run",{id:s.id,name:s.name}),await e(s.prompt,s.skills),sn(s.id),t.emit("complete",{id:s.id,name:s.name})}catch(c){t.emit("error",{id:s.id,name:s.name,error:c})}},a);n.set(s.id,u)}}return s},remove:i=>{let s=n.get(i);return s&&(clearInterval(s),n.delete(i)),Ze(i)},list:Xe}}var fn=[{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 Ee=[],fo=5,po=1;function dn(e){Ee.push(e),Ee.length>20&&Ee.shift()}function pn(){let e=Ee.slice(-3);if(e.length<1)return null;let t=e[e.length-1];return t.toolCalls>=fo&&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>=po&&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 mn=[{type:"function",function:{name:"meta_analyze",description:"Analyze recent interactions and suggest skills to create.",parameters:{type:"object",properties:{},additionalProperties:!1}}}];import{homedir as et}from"node:os";import{join as tt}from"node:path";var hn=process.env.ORACLE_PUBLIC_DESKTOP==="1",mo=hn?process.env.ORACLE_CONFIG_DIR||tt(et(),".config","oracle"):tt(et(),".config","oracle"),Cs=hn?mo:tt(et(),".config","mad-desk");function ho(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 xo=["0","false","off","no"];function xn(e,t,n=!0){let r=String(ho(e,t,"")).trim().toLowerCase();return r===""?n:!xo.includes(r)}var Po=new Set(["chain","data","scan","route","prepare"]),No=new Set(["list","show"]),jo=new Set(["call","catalog","health"]),Fo=new Set(["swap","bridge","prepare","prepare-bridge"]),Mo=Object.freeze({"anthropic-oauth":"https://api.anthropic.com/v1","openai-codex":"https://chatgpt.com/backend-api/codex","xai-oauth":"https://api.x.ai/v1"}),lt=2e4,An=6,Uo=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}}}),dt=Object.freeze([Uo,...Qt,...on,...fn,...mn]);function On(e){let t=String(e||"");return t.length<=lt?t:`${t.slice(0,lt)}
22
+ [truncated ${t.length-lt} chars]`}async function Do(e,t,n){switch(e){case"oracle_cli":return n(t.argv);case"memory_add":return Jt(t.key,t.content),{ok:!0,stored:t.key};case"memory_remove":return Vt(t.key);case"skill_load":{let r=Ge(t.name);return r?{ok:!0,name:t.name,content:r}:{ok:!1,error:`skill not found: ${t.name}`}}case"skill_create":return rn(t.name,t.content),{ok:!0,created:t.name};case"skill_list":return{ok:!0,skills:Ye().map(o=>({name:o.name,description:o.description}))};case"cron_add":return{ok:!0,job:Qe({name:t.name,schedule:t.schedule,prompt:t.prompt,skills:t.skills||[],enabled:!0})};case"cron_list":return{ok:!0,jobs:Xe()};case"cron_remove":return{ok:Ze(t.id),removed:t.id};case"meta_analyze":return{ok:!0,...pn()||{shouldCreate:!1,suggestion:"No skill suggestions yet."}};default:return{ok:!1,error:`unknown tool: ${e}`}}}function Bo(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 Po.has(t)?t==="chain"&&!No.has(e[1]||"list")?`command not allowed: chain${e[1]?` ${e[1]}`:""}`:t==="data"&&!jo.has(e[1]||"")?`command not allowed: data${e[1]?` ${e[1]}`:""}`:t==="route"&&!Fo.has(e[1]||"")?`command not allowed: route${e[1]?` ${e[1]}`:""}`:null:`command not allowed: ${t}`}async function Ko(e,t={}){let n=Bo(e);if(n)return{ok:!1,error:n};let r=t.spawnFn||$o,o=t.packageRoot||M,i=r(process.execPath,[Cn.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:On(i.stdout),stderr:On(i.stderr)}}function Ho(){let e=Cn.join(M,"profiles","oracle","SOUL.md"),t=Ro.readFileSync(e,"utf8"),n=Xt(),r=nn(),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 qo(e,t,n={}){return{method:"event",params:{type:e,session_id:t,payload:n}}}async function zo(e){return new Error(`model request failed (HTTP ${e?.status||"unknown"})`)}async function*pt(e){if(!e?.ok)throw await zo(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 a=r.split(/\r?\n\r?\n/);r=a.pop()||"";for(let u of a){let c=u.split(/\r?\n/).filter(d=>d.startsWith("data:")).map(d=>d.slice(5).trimStart()).join(`
25
+ `);!c||c==="[DONE]"||(yield JSON.parse(c))}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 Wo(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 Yo(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 Go(){return dt.map(e=>({type:"function",name:e.function.name,description:e.function.description,parameters:e.function.parameters,strict:!1}))}function Jo(){return dt.map(e=>({name:e.function.name,description:e.function.description,input_schema:e.function.parameters}))}function ft(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 Vo(e){let t=[];for(let n of e)if(n.role!=="system"){if(n.role==="user"){ft(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&&ft(t,"assistant",r);continue}n.role==="tool"&&ft(t,"user",[{type:"tool_result",tool_use_id:n.tool_call_id,content:String(n.content||"")}])}return t}function Xo(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 Qo(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 Zo({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:dt,tool_choice:"auto",stream:!0,stream_options:{include_usage:!0}}),signal:r}),s=new Map,a="",u=null;for await(let c of pt(i)){c.usage&&(u=c.usage);let d=c.choices?.[0]?.delta||{};typeof d.content=="string"&&d.content&&(a+=d.content,o(d.content));for(let p of d.tool_calls||[])Wo(s,p)}return{text:a,usage:u,toolCalls:[...s.entries()].sort(([c],[d])=>c-d).map(([,c])=>c)}}async function ei({config:e,messages:t,persona:n,credential:r,fetchFn:o,signal:i,onText:s}){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:Vo(t),tools:Jo(),tool_choice:{type:"auto"},stream:!0}),signal:i}),u=new Map,c="",d=null;for await(let p of pt(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 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"&&(c+=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:c,usage:d,toolCalls:[...u.entries()].sort(([p],[g])=>p-g).map(([,p])=>(p.function.arguments||(p.function.arguments="{}"),p))}}async function ti({config:e,messages:t,persona:n,sessionId:r,credential:o,fetchFn:i,signal:s,onText:a}){let u=e.provider==="openai-codex",c=u?Qo(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",...c?{"ChatGPT-Account-ID":c}:{},session_id:r,"x-client-request-id":r}:{"x-grok-conv-id":r}},p={model:e.model,instructions:n,input:Xo(t),tools:Go(),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:d,body:JSON.stringify(p),signal:s}),x=new Map,_="",S=null;for await(let b of pt(g)){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"&&(S=b.response?.usage||S),b.type==="response.failed"||b.type==="error")throw new Error(b.response?.error?.message||b.error?.message||"Responses stream failed")}return{text:_,usage:S,toolCalls:[...x.values()]}}function Ln(e={}){let t=e.config;if(!t?.baseUrl||!t?.model)throw new Error("standalone model configuration is incomplete");if(t.authType==="oauth"){let l=Mo[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 To,r=e.fetchFn||globalThis.fetch,o=e.toolRunner||(l=>Ko(l,e)),i=e.credentialProvider||(async l=>{let{resolveOAuthCredentials:f}=await Promise.resolve().then(()=>(ut(),kn));return f(l)}),s=e.persona||Ho(),a=e.sessionId||`oracle-${En()}`,u=[],c=null,d=!1,p=!1,g=ln(async(l,f)=>{if(d)return;let w=(f||[]).map(k=>{let y=Ge(k);return y?`## Skill: ${k}
26
+ ${y}`:null}).filter(Boolean),O=w.length>0?`
27
27
 
28
28
  ${w.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(`${l}${O}`)});xn("ORACLE_CRON_ENABLED","MAD_CRON_ENABLED",!0)&&(g.on("run",l=>x("cron.run",l)),g.on("complete",l=>x("cron.complete",l)),g.on("error",l=>x("cron.error",l)),g.start());function x(l,f={}){n.emit("event",qo(l,a,f))}function _(l){x("error",{message:l?.message||String(l)}),n.listenerCount("error")>0&&n.emit("error",l)}async function S(l){p=!0,c=new AbortController;let f=[{role:"system",content:s},...u,{role:"user",content:l}],w="",O=null,k=!1;try{for(let y=0;y<An;y+=1){let I=t.authType==="oauth"?await i(t.provider):null,z=V=>{k||(x("message.start",{}),k=!0),w+=V,x("message.delta",{text:V})},C={config:t,messages:f,persona:s,sessionId:a,credential:I,fetchFn:r,signal:c.signal,onText:z},j=t.protocol==="anthropic-messages"?await ei(C):t.protocol==="responses"?await ti(C):await Zo(C),ie=j.text,se=j.toolCalls;if(O=j.usage||O,se.length===0){f.push({role:"assistant",content:ie}),u=f.slice(1),k||x("message.start",{}),x("message.complete",{text:w,usage:Yo(O,t.contextLength)});return}f.push({role:"assistant",content:ie||null,tool_calls:se});let Un=se.length,pe=0;for(let V of se){let me;try{let Ce=JSON.parse(V.function.arguments||"{}");me=await Do(V.function.name,Ce,o)}catch(Ce){me={ok:!1,error:`invalid tool arguments: ${Ce.message}`},pe++}me.ok||pe++,f.push({role:"tool",tool_call_id:V.id||`call_${En()}`,content:JSON.stringify(me)})}dn({userMessage:l,toolCalls:Un,errors:pe,recovered:pe>0?!!se.length:!1,durationMs:0})}throw new Error(`agent exceeded ${An} tool steps`)}catch(y){y?.name!=="AbortError"&&_(y)}finally{p=!1,c=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(()=>{S(w).catch(_)}),{accepted:!0}}if(l==="session.interrupt"){let w=!!(c&&p);return c?.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,c?.abort(),g.stop())}return Object.freeze({start:b,request:m,stop:h,on:n.on.bind(n),off:n.off.bind(n)})}async function In({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((a,u)=>{let c=d=>{let p=d?.params?.type,g=d?.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,a(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",c),e.request("prompt.submit",{session_id:o.session_id,text:t}).catch(d=>{s||(s=!0,u(d))})})}finally{await e.stop()}}ut();var T="oracle",de="oracle";function Fn(e){if(e==="hermes"){let t=Ie();return t.ok?t.bin:null}for(let t of(process.env.PATH||"").split(v.delimiter)){let n=v.join(t,e);try{if(A.existsSync(n))return n}catch{}}return null}function Rn(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(v.basename(n[0]||"").startsWith("python"))return{command:n[0],prefix:n.slice(1)}}catch{}return null}function Mn(e){let t=Rn(e);if(t)return t;try{let r=A.readFileSync(e,"utf8").match(/["']([^"'\r\n]+\/bin\/hermes)["']/);if(r)return Rn(r[1])}catch{}return null}function ri(){return v.join(M,"src","cli","oracle-harness.py")}function Tn(e,t){let n=ri(),r=process.env.ORACLE_PLAIN_HARNESS==="0"?null:Mn(e);return r&&A.existsSync(n)?{command:r.command,args:[...r.prefix,n,...t]}:{command:e,args:t}}function oi(){return v.join(M,"skins","oracle.yaml")}function ii(e=T){let t=v.join(M,"profiles","oracle","SOUL.md");if(!A.existsSync(t))return{ok:!1,reason:"oracle persona missing from package"};let n=v.join(D(),"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}:(P(v.dirname(n)),A.copyFileSync(t,n),{ok:!0,reused:!1})}function si(e=T){let t=oi();if(!A.existsSync(t))return{ok:!1,reason:"skin missing from package"};let n=v.join(D(),"skins"),r=v.join(D(),"profiles",e,"skins");P(n),P(r);let o=A.readFileSync(t,"utf8");return A.writeFileSync(v.join(n,`${de}.yaml`),o),A.writeFileSync(v.join(r,`${de}.yaml`),o),{ok:!0,skin:de}}function ci(e=T){let t=v.join(D(),"profiles",e,"config.yaml");if(!A.existsSync(t))return{ok:!1,reason:"profile config missing"};let n=Fn("oracle")||v.join(M,"bin","oracle.mjs"),r=v.join(D(),"profiles",e,"oracle");P(r);let o={profile:e,skin:de,oracleBin:n,commands:{chain:[n,"chain"],setup:[n,"setup"]},updatedAt:new Date().toISOString()};return A.writeFileSync(v.join(r,"chat-surface.json"),JSON.stringify(o,null,2)+`
33
+ `,{mode:384}),{ok:!0,marker:o}}function ai(e=T){let t=v.join(M,"skills","oracle-chat");if(!A.existsSync(t))return{ok:!1,reason:"oracle-chat skill missing"};let n=v.join(D(),"profiles",e,"skills","oracle-chat");P(n);for(let r of A.readdirSync(t)){let o=v.join(t,r),i=v.join(n,r);A.statSync(o).isFile()&&A.copyFileSync(o,i)}for(let r of["chain","setup"]){let o=v.join(D(),"profiles",e,"skills",r);P(o);let i=v.join(t,`${r}.SKILL.md`),s=v.join(t,"SKILL.md"),a=A.existsSync(i)?A.readFileSync(i,"utf8"):A.readFileSync(s,"utf8");A.writeFileSync(v.join(o,"SKILL.md"),a)}return{ok:!0}}function ui(e=T){let t=Fn("hermes");if(!t)return{ok:!1,reason:"hermes missing"};let n=ni(t,["-p",e,"config","set","display.skin",de],{encoding:"utf8",timeout:3e4});return n.status!==0?{ok:!1,reason:(n.stderr||n.stdout||"config set failed").trim()}:{ok:!0}}function $n(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 li(e=T){let t=D();if(A.existsSync(v.join(t,"auth.json"))||A.existsSync(v.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[v.join(t,".env"),v.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 Pn(e=T){let t=D();return $n(v.join(t,"config.yaml"))||$n(v.join(t,"profiles",e,"config.yaml"))||li(e)}function Nn(){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 fi(){let e=Number(process.stdout?.columns||process.env.COLUMNS||80);return Number.isFinite(e)&&e>0?Math.floor(e):80}function di(e){return Array.from(String(e)).length}function pi(e,t){let n=e.map(s=>s.trimEnd()),r=Math.max(0,...n.map(s=>di(s))),o=Math.max(0,Math.floor((t-r)/2)),i=" ".repeat(o);return n.map(s=>s?`${i}${s}`:"")}function jn(e){return`'${String(e).replace(/'/g,"'\\''")}'`}function mi(e){return e.user?`${e.user}@${e.host}`:e.host}function hi(e,t){let n=e.path||"$HOME/.local/bin:/usr/local/bin:/usr/bin:/bin:/opt/homebrew/bin",r=["oracle","chat",...t].map(jn).join(" ");return[/^[A-Za-z0-9_:$/.~+-]+$/.test(n)?`export PATH=${n}`:`export PATH=${jn(n)}`,"export ORACLE_REMOTE_COMPUTE_DISABLE=1","export ORACLE_CHAT_BACKEND=auto",r].join("; ")}function xi(){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(pi(e,fi()).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 yi(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 sc={name:"chat",summary:"open the one oracle chat surface (telegram-like, multi-model)",group:"read",usage:Nn(),async run(e){let t=[...e.argv];if(t.includes("-h")||t.includes("--help"))return process.stdout.write(Nn()+`
37
+ `),0;if(t.includes("--print-banner"))return xi(),0;let n=yi(t),r={...process.env,...n.model?{ORACLE_MODEL:n.model}:{},...n.provider?{ORACLE_PROVIDER:n.provider}:{}},o=oe(),i=qt({env:r,hermes:Ie(),storedConfig:gt(),oauthAvailable:_=>!!o.get(_),apiKeyResolver:_=>o.getApiKey(_)});if(i.kind==="unconfigured")return process.stderr.write(`${i.reason}
38
+ `),1;if(i.kind==="remote")return xe("ssh",["-o","BatchMode=yes","-o","ConnectTimeout=12",mi(i.config),hi(i.config,n.pass)],{stdio:"inherit",env:process.env},"oracle-remote-compute");let s=he({ORACLE_CHAT_SURFACE:"1",ORACLE_PROFILE:T,ORACLE_NODE_BIN:process.execPath,ORACLE_CLI_ENTRY:v.join(M,"bin","oracle.mjs")});if(i.kind==="standalone"){let _=Ln({config:{...i.config,...n.model?{model:n.model}:{}}});if(n.query)try{return await In({client:_,text:n.query,stdout:process.stdout,stderr:process.stderr})}catch{return 1}let S=await Ke({client:_,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 a=i.bin;ii(T),si(T),ai(T);let u=ui(T);ci(T),!u.ok&&process.env.ORACLE_CLI_DEBUG&&process.stderr.write(`oracle chat: skin note: ${u.reason}
41
+ `);let c=!!(n.model||n.provider);if(!Pn(T)&&!c){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 _=Tn(a,["-p",T,"model"]),S=await xe(_.command,_.args,{stdio:"inherit",env:process.env},"oracle-model");if(S!==0||!Pn(T))return S||1}let d=["-p",T,"chat"],p=Mn(a),g=await Ke({hermesPython:p,args:t,env:s,cwd:process.cwd(),stdin:process.stdin,stdout:process.stdout});if(g.native)return g.code;let x=Tn(a,[...d,...n.pass]);return xe(x.command,x.args,{stdio:"inherit",env:s},"oracle-chat")}};export{sc as default,ri as harnessSourcePath,Tn as oracleHarnessInvocation,Mn as resolveHermesPython};