@oracle-agent/oracle 0.17.0 → 0.18.1

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