@oracle-agent/oracle 0.32.0 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,70 +1,72 @@
1
- import{spawnSync as Jr}from"node:child_process";import{stdin as Y,stdout as Ct}from"node:process";var Ie=Object.freeze([{key:"telegram",name:"telegram",hermes:["gateway","setup"],required:["TELEGRAM_BOT_TOKEN"],optional:["TELEGRAM_ALLOWED_USERS","TELEGRAM_PROXY"],note:"dms \xB7 groups \xB7 topics"},{key:"discord",name:"discord",hermes:["gateway","setup"],required:["DISCORD_BOT_TOKEN"],optional:["DISCORD_ALLOWED_USERS"],note:"dms \xB7 channels \xB7 threads"},{key:"slack",name:"slack",hermes:["gateway","setup"],required:["SLACK_BOT_TOKEN","SLACK_APP_TOKEN"],optional:["SLACK_ALLOWED_USERS"],note:"socket mode"},{key:"whatsapp",name:"whatsapp",hermes:["whatsapp"],required:[],optional:["WHATSAPP_ALLOWED_USERS","WHATSAPP_MODE"],note:"qr bridge"},{key:"whatsapp-cloud",name:"whatsapp cloud",hermes:["whatsapp-cloud"],required:[],optional:[],note:"business cloud api"},{key:"signal",name:"signal",hermes:["gateway","setup"],required:["SIGNAL_HTTP_URL","SIGNAL_ACCOUNT"],optional:["SIGNAL_ALLOWED_USERS"],note:"signal-cli rest bridge"},{key:"matrix",name:"matrix",hermes:["gateway","setup"],required:["MATRIX_HOMESERVER","MATRIX_ACCESS_TOKEN","MATRIX_USER_ID"],optional:["MATRIX_ALLOWED_USERS"],note:"rooms \xB7 dms"},{key:"mattermost",name:"mattermost",hermes:["gateway","setup"],required:["MATTERMOST_URL","MATTERMOST_TOKEN"],optional:["MATTERMOST_ALLOWED_USERS"],note:"channels \xB7 dms"},{key:"email",name:"email",hermes:["gateway","setup"],required:["EMAIL_ADDRESS","EMAIL_PASSWORD","EMAIL_IMAP_HOST","EMAIL_SMTP_HOST"],optional:[],note:"imap/smtp mailbox"},{key:"bluebubbles",name:"bluebubbles",hermes:["gateway","setup"],required:[],optional:[],note:"imessage via bluebubbles"},{key:"photon",name:"photon",hermes:["photon"],required:["PHOTON_PROJECT_ID","PHOTON_PROJECT_SECRET"],optional:["PHOTON_ALLOWED_USERS","PHOTON_HOME_CHANNEL"],note:"imessage via spectrum (no mac)"},{key:"homeassistant",name:"homeassistant",hermes:["gateway","setup"],required:["HASS_URL","HASS_TOKEN"],optional:[],note:"smart home"},{key:"webhook",name:"webhook",hermes:["gateway","setup"],required:[],optional:[],note:"http ingress"},{key:"api-server",name:"api server",hermes:["gateway","setup"],required:[],optional:[],note:"local http api"},{key:"dingtalk",name:"dingtalk",hermes:["gateway","setup"],required:[],optional:[],note:"dingtalk bot"},{key:"feishu",name:"feishu",hermes:["gateway","setup"],required:[],optional:[],note:"feishu / lark"},{key:"wecom",name:"wecom",hermes:["gateway","setup"],required:[],optional:[],note:"wecom"},{key:"weixin",name:"weixin",hermes:["gateway","setup"],required:[],optional:[],note:"weixin"},{key:"qqbot",name:"qqbot",hermes:["gateway","setup"],required:[],optional:[],note:"qq bot"}]);function ot(e){return String(e||"").trim().toLowerCase().replace(/^\/+/,"").replace(/\s+/g,"-")}function Q(){return Ie.slice()}function G(e){let t=ot(e);if(!t)return null;for(let r of Ie)if(r.key===t||ot(r.name)===t)return r;return null}function st({profile:e="oracle",statuses:t={}}={}){let r=["oracle setup","","one oracle. many models. every connected channel.",`profile: ${e}`,"","start here (most people):"," 1. oracle setup model connect Claude / Codex / Grok / API key"," 2. oracle setup telegram bot token \u2192 dm your bot"," oracle setup discord bot token \u2192 channels / dms"," oracle setup whatsapp qr bridge (or whatsapp-cloud)"," 3. oracle setup gateway restart apply channel config","","messaging platforms:",""];for(let n of Ie){let o=t[n.key]||"unset";r.push(` ${n.key.padEnd(16)} ${String(o).padEnd(8)} ${n.note}`)}return r.push(""),r.push("commands:"),r.push(" oracle setup this menu"),r.push(" oracle setup model standalone OAuth / API keys"),r.push(" oracle setup messaging open hermes gateway setup wizard"),r.push(" oracle setup telegram set TELEGRAM_BOT_TOKEN (stdin or --token)"),r.push(" oracle setup discord set DISCORD_BOT_TOKEN"),r.push(" oracle setup whatsapp qr link via hermes"),r.push(" oracle setup slack bot + app tokens"),r.push(" oracle setup status show configured platforms (no secrets)"),r.push(" oracle setup gateway start/status/restart hermes gateway"),r.push(" /setup same menu inside the tui"),r.push(" /setup telegram|discord|whatsapp channel how-to (no secrets)"),r.push(""),r.push("notes:"),r.push(" tokens stay in the hermes profile .env on this machine"),r.push(" oracle never prints bot tokens or app secrets"),r.push(' pipe tokens: echo "$TOKEN" | oracle setup telegram'),r.push(" after token setup: oracle setup gateway restart"),r.join(`
1
+ import{spawnSync as Jr}from"node:child_process";import{stdin as Y,stdout as Ct}from"node:process";var De=Object.freeze([{key:"telegram",name:"telegram",hermes:["gateway","setup"],required:["TELEGRAM_BOT_TOKEN"],optional:["TELEGRAM_ALLOWED_USERS","TELEGRAM_PROXY"],note:"dms \xB7 groups \xB7 topics"},{key:"discord",name:"discord",hermes:["gateway","setup"],required:["DISCORD_BOT_TOKEN"],optional:["DISCORD_ALLOWED_USERS"],note:"dms \xB7 channels \xB7 threads"},{key:"slack",name:"slack",hermes:["gateway","setup"],required:["SLACK_BOT_TOKEN","SLACK_APP_TOKEN"],optional:["SLACK_ALLOWED_USERS"],note:"socket mode"},{key:"whatsapp",name:"whatsapp",hermes:["whatsapp"],required:[],optional:["WHATSAPP_ALLOWED_USERS","WHATSAPP_MODE"],note:"qr bridge"},{key:"whatsapp-cloud",name:"whatsapp cloud",hermes:["whatsapp-cloud"],required:[],optional:[],note:"business cloud api"},{key:"signal",name:"signal",hermes:["gateway","setup"],required:["SIGNAL_HTTP_URL","SIGNAL_ACCOUNT"],optional:["SIGNAL_ALLOWED_USERS"],note:"signal-cli rest bridge"},{key:"matrix",name:"matrix",hermes:["gateway","setup"],required:["MATRIX_HOMESERVER","MATRIX_ACCESS_TOKEN","MATRIX_USER_ID"],optional:["MATRIX_ALLOWED_USERS"],note:"rooms \xB7 dms"},{key:"mattermost",name:"mattermost",hermes:["gateway","setup"],required:["MATTERMOST_URL","MATTERMOST_TOKEN"],optional:["MATTERMOST_ALLOWED_USERS"],note:"channels \xB7 dms"},{key:"email",name:"email",hermes:["gateway","setup"],required:["EMAIL_ADDRESS","EMAIL_PASSWORD","EMAIL_IMAP_HOST","EMAIL_SMTP_HOST"],optional:[],note:"imap/smtp mailbox"},{key:"bluebubbles",name:"bluebubbles",hermes:["gateway","setup"],required:[],optional:[],note:"imessage via bluebubbles"},{key:"photon",name:"photon",hermes:["photon"],required:["PHOTON_PROJECT_ID","PHOTON_PROJECT_SECRET"],optional:["PHOTON_ALLOWED_USERS","PHOTON_HOME_CHANNEL"],note:"imessage via spectrum (no mac)"},{key:"homeassistant",name:"homeassistant",hermes:["gateway","setup"],required:["HASS_URL","HASS_TOKEN"],optional:[],note:"smart home"},{key:"webhook",name:"webhook",hermes:["gateway","setup"],required:[],optional:[],note:"http ingress"},{key:"api-server",name:"api server",hermes:["gateway","setup"],required:[],optional:[],note:"local http api"},{key:"dingtalk",name:"dingtalk",hermes:["gateway","setup"],required:[],optional:[],note:"dingtalk bot"},{key:"feishu",name:"feishu",hermes:["gateway","setup"],required:[],optional:[],note:"feishu / lark"},{key:"wecom",name:"wecom",hermes:["gateway","setup"],required:[],optional:[],note:"wecom"},{key:"weixin",name:"weixin",hermes:["gateway","setup"],required:[],optional:[],note:"weixin"},{key:"qqbot",name:"qqbot",hermes:["gateway","setup"],required:[],optional:[],note:"qq bot"}]);function st(e){return String(e||"").trim().toLowerCase().replace(/^\/+/,"").replace(/\s+/g,"-")}function Q(){return De.slice()}function G(e){let t=st(e);if(!t)return null;for(let r of De)if(r.key===t||st(r.name)===t)return r;return null}function it({profile:e="oracle",statuses:t={}}={}){let r=["oracle setup","","one oracle. many models. every connected channel.",`profile: ${e}`,"","start here (most people):"," 1. oracle setup model connect Claude / Codex / Grok / API key"," 2. oracle setup telegram bot token \u2192 dm your bot"," oracle setup discord bot token \u2192 channels / dms"," oracle setup whatsapp qr bridge (or whatsapp-cloud)"," 3. oracle setup gateway restart apply channel config","","messaging platforms:",""];for(let n of De){let o=t[n.key]||"unset";r.push(` ${n.key.padEnd(16)} ${String(o).padEnd(8)} ${n.note}`)}return r.push(""),r.push("commands:"),r.push(" oracle setup this menu"),r.push(" oracle setup model standalone OAuth / API keys"),r.push(" oracle setup messaging open hermes gateway setup wizard"),r.push(" oracle setup telegram set TELEGRAM_BOT_TOKEN (stdin or --token)"),r.push(" oracle setup discord set DISCORD_BOT_TOKEN"),r.push(" oracle setup whatsapp qr link via hermes"),r.push(" oracle setup slack bot + app tokens"),r.push(" oracle setup status show configured platforms (no secrets)"),r.push(" oracle setup gateway start/status/restart hermes gateway"),r.push(" /setup same menu inside the tui"),r.push(" /setup telegram|discord|whatsapp channel how-to (no secrets)"),r.push(""),r.push("notes:"),r.push(" tokens stay in the hermes profile .env on this machine"),r.push(" oracle never prints bot tokens or app secrets"),r.push(' pipe tokens: echo "$TOKEN" | oracle setup telegram'),r.push(" after token setup: oracle setup gateway restart"),r.join(`
2
2
  `)+`
3
- `}import F from"node:fs";import zt from"node:os";import Le from"node:path";import fe from"node:fs";import jt from"node:os";import q from"node:path";import{fileURLToPath as Ut}from"node:url";var Bt=q.dirname(Ut(import.meta.url)),cn=q.resolve(Bt,"../..");function te(){return process.env.ORACLE_FAKE_HOME||jt.homedir()}function Kt(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function N(){return Kt()?process.env.ORACLE_CONFIG_DIR||q.join(te(),".config","oracle"):q.join(te(),".config","oracle")}function Ht(){return q.join(N(),"desk.json")}function qt(){return q.join(N(),"env")}function ee({force:e=!1}={}){if(ee._done&&!e)return ee._result||null;ee._done=!0;let t={},r=(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=qt();if(fe.existsSync(o))for(let s of fe.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)),r(i[1],c)}}catch{}try{let o=Ht();if(fe.existsSync(o)){let s=JSON.parse(fe.readFileSync(o,"utf8"));s&&typeof s=="object"&&(r("ORACLE_DESK_URL",s.deskUrl||s.dataUrl||s.url),r("ORACLE_DATA_URL",s.dataUrl||s.deskUrl||s.url),r("ORACLE_API_URL",s.apiUrl||s.dataUrl||s.deskUrl),r("ORACLE_PUBLIC_URL",s.publicUrl||s.deskUrl||s.dataUrl),r("ORACLE_EXEC_URL",s.execUrl),r("MAD_DESK_URL",s.deskUrl||s.dataUrl))}}catch{}let n=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return n&&(r("ORACLE_DESK_URL",n),r("ORACLE_DATA_URL",n),r("ORACLE_API_URL",n),r("ORACLE_PUBLIC_URL",n),r("MAD_DESK_URL",n)),ee._result=Object.keys(t).length?t:null,ee._result}try{ee()}catch{}function de(){return process.env.HERMES_HOME?q.resolve(process.env.HERMES_HOME):q.join(te(),".hermes")}function D(e){return fe.mkdirSync(e,{recursive:!0}),e}var Wt=/(TOKEN|SECRET|PASSWORD|KEY|AUTH|PRIVATE|MNEMONIC|SEED)/i;function we(e="oracle"){return Le.join(de(),"profiles",e,".env")}function Yt(e){let t={};for(let r of String(e||"").split(/\r?\n/)){let n=r.trim();if(!n||n.startsWith("#"))continue;let o=n.indexOf("=");if(o<=0)continue;let s=n.slice(0,o).trim(),i=n.slice(o+1).trim();(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),t[s]=i}return t}function at(e="oracle"){let t=we(e);return F.existsSync(t)?Yt(F.readFileSync(t,"utf8")):{}}function it(e,t,r){if(!t||Wt.test(t)===!1&&/[^A-Z0-9_]/.test(t),!/^[A-Z][A-Z0-9_]*$/.test(t)){let l=new Error(`invalid env key '${t}'`);throw l.code="BAD_KEY",l}if(r==null||String(r).trim()===""){let l=new Error(`empty value for ${t}`);throw l.code="EMPTY",l}let n=we(e);D(Le.dirname(n));let o=F.existsSync(n)?F.readFileSync(n,"utf8"):"",s=o?o.split(/\r?\n/):[],i=[],c=!1,a=`${t}=${String(r)}`;for(let l of s)l.startsWith(`${t}=`)?(i.push(a),c=!0):(l.length||i.length)&&i.push(l);for(c||(i.length&&i[i.length-1]!==""&&i.push(""),i.push(a));i.length&&i[i.length-1]==="";)i.pop();i.push(""),F.writeFileSync(n,i.join(`
4
- `),{mode:384});try{F.chmodSync(n,384)}catch{}return{path:n,key:t,set:!0}}function re(e="oracle"){let t=at(e),r={};for(let n of Q()){if(!n.required.length){r[n.key]="manual";continue}let o=n.required.filter(s=>!String(t[s]||"").trim());r[n.key]=o.length?"unset":"ready"}return{profile:e,statuses:r,envPath:we(e)}}function be(e="oracle"){let{statuses:t}=re(e);return st({profile:e,statuses:t})}function ke(e,t,r,n={}){let o=G(t);if(!o){let u=new Error(`unknown platform '${t}'`);throw u.code="UNKNOWN_PLATFORM",u}if(!o.required.length){let u=new Error(`${o.key} uses hermes interactive setup (oracle setup messaging)`);throw u.code="NEEDS_INTERACTIVE",u}let i=o.required.filter(u=>/(TOKEN|PASSWORD|SECRET)$/i.test(u))[0]||(o.required.length===1?o.required[0]:null);if(!i){let u=new Error(`${o.key} has no single token field; provide each of [${o.required.join(", ")}] explicitly`);throw u.code="NEEDS_EXPLICIT_KEYS",u}let c=new Set([i,...Object.keys(n||{}).filter(u=>n[u]!=null&&String(n[u]).trim())]),a=at(e),l=o.required.filter(u=>!c.has(u)&&!String(a[u]||"").trim());if(l.length){let u=new Error(`${o.key} also requires [${l.join(", ")}]; pass them explicitly (setup would otherwise be marked ready while unusable)`);throw u.code="MISSING_REQUIRED",u}it(e,i,r);for(let[u,y]of Object.entries(n||{}))y!=null&&String(y).trim()&&it(e,u,y);return{platform:o.key,set:o.required,profile:e,path:we(e)}}function Gt(){return Le.join(N(),"setup-state.json")}function V(e={}){D(N());let t=Gt(),r={};if(F.existsSync(t))try{r=JSON.parse(F.readFileSync(t,"utf8"))}catch{r={}}let n={...r,...e,updatedAt:new Date().toISOString(),host:zt.hostname()};return F.writeFileSync(t,JSON.stringify(n,null,2)+`
5
- `,{mode:384}),n}import R from"node:fs";import T from"node:path";import{createHash as Vt}from"node:crypto";import{spawnSync as oe}from"node:child_process";var Jt="0.19.0",ct=`hermes-agent==${Jt}`,Ce=[3,11],Ne=[3,14],pe="3.13",_e="0.12.1",ve=Object.freeze({posix:Object.freeze({url:`https://github.com/astral-sh/uv/releases/download/${_e}/uv-installer.sh`,sha256:"d3f5412d38c99f9d024901843bf98206f0d2c6dbe64df40d0b740e2751ca62c1"}),windows:Object.freeze({url:`https://github.com/astral-sh/uv/releases/download/${_e}/uv-installer.ps1`,sha256:"b9ec035151bfbb11d616dbd69886498d885551489eddf095ea3c0ad59f640eb0"})});function Xt(e,{windows:t=process.platform==="win32"}={}){let r=Buffer.isBuffer(e)?e:Buffer.from(e),n=t?ve.windows:ve.posix,o=Vt("sha256").update(r).digest("hex"),s=r.toString("utf8");return o===n.sha256&&s.length>=1e3&&s.includes(_e)}function J(){return T.join(N(),"runtime")}function lt(){return T.join(J(),"venv")}function Fe(e){let t=process.platform==="win32"?"Scripts":"bin",r=process.platform==="win32"?`${e}.exe`:e;return T.join(lt(),t,r)}function xe(){return Fe("hermes")}function Zt(){let e=Fe("python3");return R.existsSync(e)?e:Fe("python")}function me(){return T.join(J(),"uv",process.platform==="win32"?"uv.exe":"uv")}function ne(e){let t=process.platform==="win32"&&!T.extname(e)?["",".exe",".cmd",".bat"]:[""];for(let r of(process.env.PATH||"").split(T.delimiter))if(r)for(let n of t){let o=T.join(r,`${e}${n}`);try{if(R.existsSync(o))return o}catch{}}return null}function Qt(e){let t=/Python (\d+)\.(\d+)\.(\d+)/.exec(e||"");return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function er(e){if(!e)return!1;let[t,r]=e;return!(t<Ce[0]||t===Ce[0]&&r<Ce[1]||t>Ne[0]||t===Ne[0]&&r>=Ne[1])}function tr(){let e=[process.env.ORACLE_PYTHON,"python3.13","python3.12","python3.11","python3","python"].filter(Boolean);for(let t of e){let r=T.isAbsolute(t)?R.existsSync(t)?t:null:ne(t);if(!r)continue;let n=oe(r,["--version"],{encoding:"utf8",timeout:15e3}),o=Qt(`${n.stdout||""}${n.stderr||""}`);if(er(o))return{bin:r,version:o.join("."),source:"host"}}return null}function rr(){return process.env.ORACLE_UV_BIN||ne("uv")||(R.existsSync(T.join(te(),".local","bin","uv"))?T.join(te(),".local","bin","uv"):null)||(R.existsSync(me())?me():null)}function nr(e,t){let r=["const fs=require('node:fs');","const [url,dest]=process.argv.slice(1);","fetch(url).then(r=>{if(!r.ok)throw new Error('http '+r.status);return r.arrayBuffer()})",".then(b=>fs.writeFileSync(dest,Buffer.from(b)))",".catch(e=>{console.error(e.message);process.exit(1)});"].join("");return oe(process.execPath,["-e",r,e,t],{encoding:"utf8",timeout:2*6e4})}function or({quiet:e=!1}={}){let t=rr();if(t)return{ok:!0,bin:t,reused:!0};D(J());let r=process.platform==="win32",n=T.join(J(),r?"uv-install.ps1":"uv-install.sh"),o=r?ve.windows:ve.posix,s=nr(o.url,n);if(s.status!==0)return{ok:!1,reason:`could not download the uv installer (${s.status})`,stderr:(s.stderr||"").slice(-800)};let i=R.readFileSync(n);if(!Xt(i,{windows:r}))return{ok:!1,reason:`uv ${_e} installer checksum mismatch`};let c=T.dirname(me());D(c);let a=r?ne("powershell.exe")||ne("powershell"):ne("sh")||"/bin/sh";if(!a)return{ok:!1,reason:r?"PowerShell not found":"sh not found"};let u=oe(a,r?["-NoProfile","-ExecutionPolicy","Bypass","-File",n]:[n],{stdio:e?"pipe":"inherit",encoding:"utf8",timeout:5*6e4,env:{...process.env,UV_INSTALL_DIR:c,UV_NO_MODIFY_PATH:"1"}});return u.status!==0||!R.existsSync(me())?{ok:!1,reason:`uv install failed (${u.status})`,stderr:(u.stderr||"").slice(-800)}:{ok:!0,bin:me(),reused:!1}}function ut({quiet:e=!1}={}){let t=or({quiet:e});if(!t.ok)return t;let r=t.bin,n={...process.env,UV_PYTHON_INSTALL_DIR:T.join(J(),"python"),UV_CACHE_DIR:T.join(J(),"cache")},o=oe(r,["python","install","--no-bin",pe],{stdio:e?"pipe":"inherit",encoding:"utf8",timeout:15*6e4,env:n});if(o.status!==0)return{ok:!1,reason:`uv python install ${pe} failed (${o.status})`,stderr:(o.stderr||"").slice(-800)};let s=oe(r,["python","find",pe],{encoding:"utf8",timeout:6e4,env:n}),i=(s.stdout||"").trim().split(/\r?\n/)[0];return s.status!==0||!i||!R.existsSync(i)?{ok:!1,reason:`uv could not locate python ${pe}`}:{ok:!0,bin:i,version:pe,source:"uv"}}function se(){if(process.env.ORACLE_HERMES_BIN)return{ok:!0,bin:process.env.ORACLE_HERMES_BIN,source:"env"};let e=xe();if(R.existsSync(e))return{ok:!0,bin:e,source:"managed"};let t=ne("hermes");return t?{ok:!0,bin:t,source:"path"}:{ok:!1,bin:null,source:null}}function De(e,t,{quiet:r}){return oe(e,t,{stdio:r?"pipe":"inherit",encoding:"utf8",timeout:20*6e4})}function ft({quiet:e=!1,upgrade:t=!1}={}){let r=tr();if(!r){let l=ut({quiet:e});if(l.ok)r={bin:l.bin,version:l.version,source:"uv"};else return{ok:!1,reason:`no supported python found (need 3.11-3.13) and uv could not provide one: ${l.reason}. install uv (https://docs.astral.sh/uv) or python 3.13, then re-run 'oracle bootstrap'`}}D(J());let n=lt();if(R.existsSync(xe())&&!t)return{ok:!0,bin:xe(),reused:!0};if(!R.existsSync(T.join(n,"pyvenv.cfg"))){let l=De(r.bin,["-m","venv",n],{quiet:e});if(l.status!==0&&r.source!=="uv"){R.rmSync(n,{recursive:!0,force:!0});let u=ut({quiet:e});if(u.ok)r={bin:u.bin,version:u.version,source:"uv"},l=De(r.bin,["-m","venv",n],{quiet:e});else return{ok:!1,reason:`python -m venv failed (${l.status}) and uv fallback failed: ${u.reason}`,stderr:(l.stderr||"").slice(-800)}}if(l.status!==0)return{ok:!1,reason:`isolated python -m venv failed (${l.status})`,stderr:(l.stderr||"").slice(-800)}}let s=Zt();if(!R.existsSync(s))return{ok:!1,reason:`venv python missing at ${s}`};let i=["-m","pip","install","--disable-pip-version-check"];t&&i.push("--upgrade"),i.push(ct);let c=De(s,i,{quiet:e});if(c.status!==0)return{ok:!1,reason:`pip install ${ct} failed (${c.status})`,stderr:(c.stderr||"").slice(-1200)};let a=xe();return R.existsSync(a)?{ok:!0,bin:a,reused:!1,python:r.version}:{ok:!1,reason:`hermes entrypoint not found after install (${a})`}}import{createHash as sr,randomBytes as Be,timingSafeEqual as ir}from"node:crypto";import L from"node:fs";import j from"node:path";import ar from"node:readline/promises";import{spawn as cr,spawnSync as ur}from"node:child_process";var ae=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.6",protocol:"responses"}}),lr=12e4;function fr(e={}){return typeof e.now=="function"?Number(e.now()):Date.now()}function X(e){let t=String(e||"").trim().toLowerCase();for(let[r,n]of Object.entries(ae))if(n.aliases.includes(t))return r;throw new Error(`unsupported OAuth provider: ${e||"(empty)"}`)}function W(e){let t=X(e);return{id:t,...ae[t]}}function P(e,t={}){if(!L.existsSync(e))return t;try{let r=JSON.parse(L.readFileSync(e,"utf8"));if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid object");return r}catch{throw new Error(`credential store is unreadable or corrupt: ${j.basename(e)}`)}}function pt(e){D(e),process.platform!=="win32"&&L.chmodSync(e,448)}function z(e,t){pt(j.dirname(e));let r=`${e}.${process.pid}.${Be(4).toString("hex")}.tmp`;L.writeFileSync(r,`${JSON.stringify(t,null,2)}
6
- `,{mode:384}),L.renameSync(r,e),process.platform!=="win32"&&L.chmodSync(e,384)}function dr(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 je(e){let t=String(e||"").trim().toLowerCase();if(!/^[a-z0-9][a-z0-9._-]*$/.test(t))throw new Error(`invalid API-key provider: ${e||"(empty)"}`);return t}function ie(e={}){let t=String(e.accessToken||e.access_token||"").trim(),r=String(e.refreshToken||e.refresh_token||"").trim(),n=Number(e.expiresAt||e.expires_at||0);if(Number.isFinite(n)&&n>=1e9&&n<1e12&&(n=n*1e3),!t)throw new Error("OAuth credential is missing access token");return{accessToken:t,refreshToken:r,expiresAt:Number.isFinite(n)?n: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 pr(e={}){let t=e.file||j.join(N(),"oauth.json"),r=e.metadataFile||j.join(j.dirname(t),"oauth-meta.json"),n=e.linksFile||j.join(j.dirname(t),"oauth-links.json"),o=()=>typeof e.now=="function"?Number(e.now()):Date.now(),s=e.spawnFn||ur,i=e.keychain!==!1&&process.env.ORACLE_AUTH_FILE_STORE!=="1"&&dr(s),c=i?"linux-secret-service":"private-file",a=`${t}.lock`;async function l(w){pt(j.dirname(a));let g;for(let p=0;p<400;p+=1)try{g=L.openSync(a,"wx",384);break}catch(f){if(f?.code!=="EEXIST")throw f;try{Date.now()-L.statSync(a).mtimeMs>3e5&&L.unlinkSync(a)}catch{}await new Promise(h=>setTimeout(h,25))}if(g===void 0)throw new Error("timed out waiting for OAuth credential lock");try{return await w()}finally{try{L.closeSync(g)}catch{}try{L.unlinkSync(a)}catch{}}}function u(w,g="oauth"){return["application","oracle","kind",g,"provider",w]}function y(w){if(!L.existsSync(n))return null;let p=P(n,{providers:{}}).providers?.[w];if(!Array.isArray(p))return null;let f=[];for(let h of p)if(j.isAbsolute(String(h||"")))try{let x=P(h,{});if(w==="anthropic-oauth"&&x.claudeAiOauth){let C=ie(x.claudeAiOauth);f.push({...C,refreshToken:"",source:"external-access-only"});continue}let v=x.credential_pool&&typeof x.credential_pool=="object"?x.credential_pool:null;if(v){let C=v[w]||v[w.replace(/-oauth$/,"")]||[],K=Array.isArray(C)?C:C?[C]:[];for(let H of K)if(!(!H||typeof H!="object"))try{let Pe=ie(H);f.push({...Pe,refreshToken:"",source:"external-access-only"})}catch{}}}catch{}return f.length?f.find(h=>!h.expiresAt||h.expiresAt>o()+lr)||f[0]:null}function m(w){let g=X(w);if(i){let h=s("secret-tool",["lookup",...u(g)],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(!h.error&&h.status===0&&String(h.stdout||"").trim())try{return ie(JSON.parse(String(h.stdout).trim()))}catch{}return y(g)}let f=P(t,{providers:{}}).providers?.[g];if(f)try{return ie(f)}catch{}return y(g)}function O(w,g){let p=X(w),f=ie(g);if(i){let x=s("secret-tool",["store",`--label=Oracle ${p} OAuth`,...u(p)],{input:JSON.stringify(f),encoding:"utf8",stdio:["pipe","ignore","pipe"]});if(x.error||x.status!==0)throw new Error("OS credential store rejected OAuth credential");let v=P(r,{providers:{}});return v.providers||={},v.providers[p]={expiresAt:f.expiresAt,source:f.source},z(r,v),f}let h=P(t,{providers:{}});return h.providers||={},h.providers[p]=f,z(t,h),f}function _(w){let g=X(w);if(i){let h=s("secret-tool",["clear",...u(g)],{encoding:"utf8",stdio:["ignore","ignore","pipe"]}),x=P(r,{providers:{}});return x.providers&&delete x.providers[g],z(r,x),!h.error&&h.status===0}let p=P(t,{providers:{}}),f=!!p.providers?.[g];return p.providers&&delete p.providers[g],z(t,p),f}function M(w){let g=je(w);if(i){let p=s("secret-tool",["lookup",...u(g,"api-key")],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return p.error||p.status!==0?"":String(p.stdout||"").trim()}return String(P(t,{apiKeys:{}}).apiKeys?.[g]||"").trim()}function k(w,g){let p=je(w),f=String(g||"").trim();if(!f)throw new Error("API key is empty");if(i){let x=s("secret-tool",["store",`--label=Oracle ${p} API key`,...u(p,"api-key")],{input:f,encoding:"utf8",stdio:["pipe","ignore","pipe"]});if(x.error||x.status!==0)throw new Error("OS credential store rejected API key");let v=P(r,{providers:{},apiKeys:{}});return v.apiKeys||={},v.apiKeys[p]={configured:!0},z(r,v),!0}let h=P(t,{providers:{},apiKeys:{}});return h.apiKeys||={},h.apiKeys[p]=f,z(t,h),!0}function A(w){let g=je(w);if(i){let h=s("secret-tool",["clear",...u(g,"api-key")],{encoding:"utf8",stdio:["ignore","ignore","pipe"]}),x=P(r,{providers:{},apiKeys:{}});return x.apiKeys&&delete x.apiKeys[g],z(r,x),!h.error&&h.status===0}let p=P(t,{providers:{},apiKeys:{}}),f=!!p.apiKeys?.[g];return p.apiKeys&&delete p.apiKeys[g],z(t,p),f}function B(){let w={},g={};if(i){let p=P(r,{providers:{},apiKeys:{}});for(let[f,h]of Object.entries(p.providers||{}))w[f]={loggedIn:!!m(f),expiresAt:Number(h.expiresAt||0),source:String(h.source||"oracle"),storage:c};for(let f of Object.keys(p.apiKeys||{}))g[f]={configured:!!M(f),storage:c}}else{let p=P(t,{providers:{},apiKeys:{}});for(let[f,h]of Object.entries(p.providers||{}))w[f]={loggedIn:!!h?.accessToken,expiresAt:Number(h?.expiresAt||0),source:String(h?.source||"oracle"),storage:c};for(let[f,h]of Object.entries(p.apiKeys||{}))g[f]={configured:!!h,storage:c}}for(let p of Object.keys(ae)){if(w[p])continue;let f=y(p);f&&(w[p]={loggedIn:!0,expiresAt:f.expiresAt,source:f.source,storage:"external-access-source"})}return{storage:c,providers:w,apiKeys:g}}return Object.freeze({file:t,storage:c,get:m,set:O,remove:_,getApiKey:M,setApiKey:k,removeApiKey:A,status:B,withLock:l})}var dt;function U(){return dt||=pr(),dt}function Ue(e){return Buffer.from(e).toString("base64url")}function mr(){let e=Ue(Be(32));return{verifier:e,challenge:Ue(sr("sha256").update(e).digest()),state:Ue(Be(24))}}function hr(e,t){let r=Buffer.from(String(e||"")),n=Buffer.from(String(t||""));return r.length===n.length&&ir(r,n)}function gr(e){let t=String(e),r=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd.exe",["/d","/s","/c","start","",t]]:["xdg-open",[t]];try{return cr(r[0],r[1],{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function Ke(e){return new URLSearchParams(e).toString()}async function Z(e,t){if(!e?.ok){let n="";try{n=String((await e.json())?.error||"")}catch{}throw new Error(`${t} failed (HTTP ${e?.status||"unknown"}${n?`, ${n}`:""})`)}let r=await e.json();if(!r||typeof r!="object")throw new Error(`${t} returned invalid JSON`);return r}async function yr(e){if(e)return String(await e()).trim();let t=ar.createInterface({input:process.stdin,output:process.stdout});try{return String(await t.question("Authorization code: ")).trim()}finally{t.close()}}function He(e,t={}){let r=String(e.access_token||"").trim(),n=String(e.refresh_token||t.refreshToken||"").trim();if(!r)throw new Error("OAuth token response is missing access token");let o=Number(e.expires_in||3600);return ie({accessToken:r,refreshToken:n,expiresAt:fr(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 wr(e){let t=ae["anthropic-oauth"],r=e.pkce||mr(),n=new URLSearchParams({code:"true",client_id:t.clientId,response_type:"code",redirect_uri:t.redirectUri,scope:t.scope,code_challenge:r.challenge,code_challenge_method:"S256",state:r.state}),o=`${t.authorizeUrl}?${n}`;e.output(`Open: ${o}`),e.openFn(o);let s=await yr(e.inputFn),[i,c]=s.split("#",2);if(!i||!hr(c,r.state))throw new Error("Claude OAuth state mismatch");let a=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:r.verifier})});return He(await Z(a,"Claude OAuth token exchange"),e)}async function br(e){let t=ae["openai-codex"],r=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(!r.user_code||!r.device_auth_id)throw new Error("Codex device authorization returned incomplete data");let n=`${t.issuer}/codex/device`;e.output(`Open: ${n}`),e.output(`Code: ${r.user_code}`),e.openFn(n);let o=Math.max(3,Number(r.interval||5)),s;for(let c=0;c<Math.ceil(900/o);c+=1){await e.sleepFn(o*1e3);let a=await e.fetchFn(`${t.issuer}/api/accounts/deviceauth/token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({device_auth_id:r.device_auth_id,user_code:r.user_code})});if(a.ok){s=await Z(a,"Codex device authorization");break}if(![403,404].includes(a.status))throw new Error(`Codex device authorization failed (HTTP ${a.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:Ke({grant_type:"authorization_code",code:s.authorization_code,redirect_uri:`${t.issuer}/deviceauth/callback`,client_id:t.clientId,code_verifier:s.code_verifier})});return He(await Z(i,"Codex OAuth token exchange"),e)}function Se(e){let t=new URL(String(e)),r=t.hostname.toLowerCase();if(t.protocol!=="https:"||r!=="x.ai"&&!r.endsWith(".x.ai"))throw new Error("xAI OAuth discovery returned an untrusted endpoint");return t.toString()}async function kr(e){let t=ae["xai-oauth"],r=await Z(await e.fetchFn(t.discoveryUrl,{headers:{accept:"application/json"}}),"xAI OAuth discovery");Se(r.authorization_endpoint);let n=Se(r.token_endpoint),o=await Z(await e.fetchFn(t.deviceUrl,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:Ke({client_id:t.clientId,scope:t.scope})}),"xAI device authorization");if(!o.device_code||!o.user_code||!o.verification_uri)throw new Error("xAI device authorization returned incomplete data");let s=Se(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 a=0;a<c;a+=1){let l=await e.fetchFn(n,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:Ke({grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:t.clientId,device_code:o.device_code})});if(l.ok){let y=await Z(l,"xAI OAuth token exchange");return He(y,{...e,discovery:{authorization_endpoint:Se(r.authorization_endpoint),token_endpoint:n}})}let u="";try{u=String((await l.json())?.error||"")}catch{}if(u==="slow_down")await e.sleepFn((i+1)*1e3);else if(u==="authorization_pending")await e.sleepFn(i*1e3);else throw new Error(`xAI OAuth token exchange failed (HTTP ${l.status}${u?`, ${u}`:""})`)}throw new Error("xAI device authorization timed out")}async function mt(e,t={}){let r=X(e),n={fetchFn:t.fetchFn||globalThis.fetch,inputFn:t.inputFn,sleepFn:t.sleepFn||(o=>new Promise(s=>setTimeout(s,o))),openFn:t.openFn||gr,output:t.output||(o=>process.stdout.write(`${o}
7
- `)),now:t.now,pkce:t.pkce};return r==="anthropic-oauth"?wr(n):r==="openai-codex"?br(n):kr(n)}import $e from"node:fs";import qe from"node:path";var xr=new Set(["openrouter","openai","anthropic","xai","deepseek","gemini","kimi","mistral","nous","qwen","glm","custom","anthropic-oauth","openai-codex","xai-oauth"]);function Ae(e){return String(e||"").trim()||void 0}function _r(e,{required:t=!1}={}){let r=Ae(e)?.toLowerCase();if(!r){if(t)throw new Error("model provider is required");return}if(!xr.has(r))throw new Error(`unsupported provider: ${r}`);return r}function vr(e,{required:t=!1}={}){let r=Ae(e);if(!r){if(t)throw new Error("model is required");return}if(r.includes("..")||r.startsWith("/")||!/^[a-zA-Z0-9._:/-]{1,200}$/.test(r))throw new Error("invalid model id");return r}function Sr(e){let t=Ae(e);if(!t||t.length>2048)throw new Error("invalid custom base URL");let r;try{r=new URL(t)}catch{throw new Error("invalid custom base URL")}let n=r.hostname.toLowerCase().replace(/^\[|\]$/g,""),o=n==="localhost"||n==="127.0.0.1"||n==="::1";if(r.protocol!=="https:"&&!(r.protocol==="http:"&&o)||r.username||r.password||r.search||r.hash)throw new Error("custom base URL must use HTTPS or loopback HTTP without credentials, query, or fragment");return r.toString().replace(/\/+$/,"")}function Ee({provider:e,model:t,baseUrl:r}={},{requireModel:n=!1}={}){let o=_r(e),s=vr(t,{required:n});if(o==="custom")return{provider:o,...s?{model:s}:{},baseUrl:Sr(r)};if(Ae(r))throw new Error("baseUrl is only supported for the custom provider");return{...o?{provider:o}:{},...s?{model:s}:{}}}var Ar=new Set(["auto","standalone","hermes","remote","arch"]);function Er(){return qe.join(N(),"model.json")}function ce(e){return String(e||"").trim()||void 0}function $r(e={}){let t=ce(e.backend)?.toLowerCase()||"auto",r=Ee({provider:e.provider,model:e.model,baseUrl:e.baseUrl},{requireModel:t==="standalone"}),n=ce(e.apiKeyEnv),o=Number.parseInt(String(e.contextLength||""),10),s=ce(e.reasoningEffort),i=ce(e.computeHost||e.remoteHost),c=ce(e.computeUser||e.remoteUser),a=ce(e.computePath||e.remotePath);if(!Ar.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&&!/^[A-Z][A-Z0-9_]*$/.test(n))throw new Error("api key env must be an uppercase environment variable name");if(t==="remote"&&!i)throw new Error("remote backend requires computeHost");return{backend:t,...r,...n?{apiKeyEnv:n}:{},...Number.isFinite(o)&&o>0?{contextLength:o}:{},...s?{reasoningEffort:s}:{},...i?{computeHost:i}:{},...c?{computeUser:c}:{},...a?{computePath:a}:{}}}function ht(e){let t=$r(e),r=Er();D(qe.dirname(r)),process.platform!=="win32"&&$e.chmodSync(qe.dirname(r),448);let n=`${r}.${process.pid}.tmp`;return $e.writeFileSync(n,`${JSON.stringify(t,null,2)}
8
- `,{mode:384}),$e.renameSync(n,r),process.platform!=="win32"&&$e.chmodSync(r,384),t}var gt=Object.freeze({openrouter:{model:"openrouter/auto"},openai:{model:"gpt-4.1-mini"},anthropic:{model:"claude-sonnet-4-6"},xai:{model:"grok-4.6"},deepseek:{model:"deepseek-chat"},gemini:{model:"gemini-2.5-flash"},kimi:{model:"kimi-k3"},mistral:{model:"mistral-large-latest"},nous:{model:"moonshotai/kimi-k3"},qwen:{model:"qwen-plus"},glm:{model:"glm-4.5"},custom:{model:""}});function ze(e,t){let r=e.indexOf(t);return r>=0&&e[r+1]?e[r+1]:""}async function Or(){let e="";for await(let t of process.stdin)e+=t;return e.trim()}function Mr(e="API key: "){if(!process.stdin.isTTY||!process.stdin.setRawMode)throw new Error("non-interactive API-key input requires --stdin");return process.stdout.write(e),new Promise((t,r)=>{let n="",o=()=>{process.stdin.off("data",s),process.stdin.setRawMode(!1),process.stdin.pause(),process.stdout.write(`
9
- `)},s=i=>{let c=String(i);for(let a of c){if(a==="\r"||a===`
10
- `){o(),t(n.trim());return}if(a===""){o(),r(new Error("cancelled"));return}a==="\x7F"||a==="\b"?n=n.slice(0,-1):n+=a}};process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",s)})}function We(e,t,{baseUrl:r=""}={}){if(e==="custom"&&!String(r||"").trim())throw new Error("custom provider requires --base-url");return{backend:"standalone",...Ee({provider:e,model:t,baseUrl:r},{requireModel:!0})}}function yt(e,t,r={}){return ht(We(e,t,r))}function Tr(e){process.stdout.write(`storage: ${e.storage}
3
+ `}import F from"node:fs";import zt from"node:os";import Fe from"node:path";import fe from"node:fs";import jt from"node:os";import q from"node:path";import{fileURLToPath as Ut}from"node:url";var Bt=q.dirname(Ut(import.meta.url)),cn=q.resolve(Bt,"../..");function te(){return process.env.ORACLE_FAKE_HOME||jt.homedir()}function Kt(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function N(){return Kt()?process.env.ORACLE_CONFIG_DIR||q.join(te(),".config","oracle"):q.join(te(),".config","oracle")}function Ht(){return q.join(N(),"desk.json")}function qt(){return q.join(N(),"env")}function ee({force:e=!1}={}){if(ee._done&&!e)return ee._result||null;ee._done=!0;let t={},r=(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=qt();if(fe.existsSync(o))for(let s of fe.readFileSync(o,"utf8").split(/\r?\n/)){let i=s.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!i||i[2].startsWith("#"))continue;let a=i[2];(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),r(i[1],a)}}catch{}try{let o=Ht();if(fe.existsSync(o)){let s=JSON.parse(fe.readFileSync(o,"utf8"));s&&typeof s=="object"&&(r("ORACLE_DESK_URL",s.deskUrl||s.dataUrl||s.url),r("ORACLE_DATA_URL",s.dataUrl||s.deskUrl||s.url),r("ORACLE_API_URL",s.apiUrl||s.dataUrl||s.deskUrl),r("ORACLE_PUBLIC_URL",s.publicUrl||s.deskUrl||s.dataUrl),r("ORACLE_EXEC_URL",s.execUrl),r("MAD_DESK_URL",s.deskUrl||s.dataUrl))}}catch{}let n=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return n&&(r("ORACLE_DESK_URL",n),r("ORACLE_DATA_URL",n),r("ORACLE_API_URL",n),r("ORACLE_PUBLIC_URL",n),r("MAD_DESK_URL",n)),ee._result=Object.keys(t).length?t:null,ee._result}try{ee()}catch{}function de(){return process.env.HERMES_HOME?q.resolve(process.env.HERMES_HOME):q.join(te(),".hermes")}function D(e){return fe.mkdirSync(e,{recursive:!0}),e}var Wt=/(TOKEN|SECRET|PASSWORD|KEY|AUTH|PRIVATE|MNEMONIC|SEED)/i;function ke(e="oracle"){return Fe.join(de(),"profiles",e,".env")}function Yt(e){let t={};for(let r of String(e||"").split(/\r?\n/)){let n=r.trim();if(!n||n.startsWith("#"))continue;let o=n.indexOf("=");if(o<=0)continue;let s=n.slice(0,o).trim(),i=n.slice(o+1).trim();(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),t[s]=i}return t}function ct(e="oracle"){let t=ke(e);return F.existsSync(t)?Yt(F.readFileSync(t,"utf8")):{}}function at(e,t,r){if(!t||Wt.test(t)===!1&&/[^A-Z0-9_]/.test(t),!/^[A-Z][A-Z0-9_]*$/.test(t)){let l=new Error(`invalid env key '${t}'`);throw l.code="BAD_KEY",l}if(r==null||String(r).trim()===""){let l=new Error(`empty value for ${t}`);throw l.code="EMPTY",l}let n=ke(e);D(Fe.dirname(n));let o=F.existsSync(n)?F.readFileSync(n,"utf8"):"",s=o?o.split(/\r?\n/):[],i=[],a=!1,c=`${t}=${String(r)}`;for(let l of s)l.startsWith(`${t}=`)?(i.push(c),a=!0):(l.length||i.length)&&i.push(l);for(a||(i.length&&i[i.length-1]!==""&&i.push(""),i.push(c));i.length&&i[i.length-1]==="";)i.pop();i.push(""),F.writeFileSync(n,i.join(`
4
+ `),{mode:384});try{F.chmodSync(n,384)}catch{}return{path:n,key:t,set:!0}}function re(e="oracle"){let t=ct(e),r={};for(let n of Q()){if(!n.required.length){r[n.key]="manual";continue}let o=n.required.filter(s=>!String(t[s]||"").trim());r[n.key]=o.length?"unset":"ready"}return{profile:e,statuses:r,envPath:ke(e)}}function xe(e="oracle"){let{statuses:t}=re(e);return it({profile:e,statuses:t})}function _e(e,t,r,n={}){let o=G(t);if(!o){let u=new Error(`unknown platform '${t}'`);throw u.code="UNKNOWN_PLATFORM",u}if(!o.required.length){let u=new Error(`${o.key} uses hermes interactive setup (oracle setup messaging)`);throw u.code="NEEDS_INTERACTIVE",u}let i=o.required.filter(u=>/(TOKEN|PASSWORD|SECRET)$/i.test(u))[0]||(o.required.length===1?o.required[0]:null);if(!i){let u=new Error(`${o.key} has no single token field; provide each of [${o.required.join(", ")}] explicitly`);throw u.code="NEEDS_EXPLICIT_KEYS",u}let a=new Set([i,...Object.keys(n||{}).filter(u=>n[u]!=null&&String(n[u]).trim())]),c=ct(e),l=o.required.filter(u=>!a.has(u)&&!String(c[u]||"").trim());if(l.length){let u=new Error(`${o.key} also requires [${l.join(", ")}]; pass them explicitly (setup would otherwise be marked ready while unusable)`);throw u.code="MISSING_REQUIRED",u}at(e,i,r);for(let[u,y]of Object.entries(n||{}))y!=null&&String(y).trim()&&at(e,u,y);return{platform:o.key,set:o.required,profile:e,path:ke(e)}}function Gt(){return Fe.join(N(),"setup-state.json")}function V(e={}){D(N());let t=Gt(),r={};if(F.existsSync(t))try{r=JSON.parse(F.readFileSync(t,"utf8"))}catch{r={}}let n={...r,...e,updatedAt:new Date().toISOString(),host:zt.hostname()};return F.writeFileSync(t,JSON.stringify(n,null,2)+`
5
+ `,{mode:384}),n}import R from"node:fs";import T from"node:path";import{createHash as Vt}from"node:crypto";import{spawnSync as oe}from"node:child_process";var Jt="0.19.0",ut=`hermes-agent==${Jt}`,je=[3,11],Ue=[3,14],pe="3.13",Se="0.12.1",Ae=Object.freeze({posix:Object.freeze({url:`https://github.com/astral-sh/uv/releases/download/${Se}/uv-installer.sh`,sha256:"d3f5412d38c99f9d024901843bf98206f0d2c6dbe64df40d0b740e2751ca62c1"}),windows:Object.freeze({url:`https://github.com/astral-sh/uv/releases/download/${Se}/uv-installer.ps1`,sha256:"b9ec035151bfbb11d616dbd69886498d885551489eddf095ea3c0ad59f640eb0"})});function Xt(e,{windows:t=process.platform==="win32"}={}){let r=Buffer.isBuffer(e)?e:Buffer.from(e),n=t?Ae.windows:Ae.posix,o=Vt("sha256").update(r).digest("hex"),s=r.toString("utf8");return o===n.sha256&&s.length>=1e3&&s.includes(Se)}function J(){return T.join(N(),"runtime")}function ft(){return T.join(J(),"venv")}function Ke(e){let t=process.platform==="win32"?"Scripts":"bin",r=process.platform==="win32"?`${e}.exe`:e;return T.join(ft(),t,r)}function ve(){return Ke("hermes")}function Zt(){let e=Ke("python3");return R.existsSync(e)?e:Ke("python")}function me(){return T.join(J(),"uv",process.platform==="win32"?"uv.exe":"uv")}function ne(e){let t=process.platform==="win32"&&!T.extname(e)?["",".exe",".cmd",".bat"]:[""];for(let r of(process.env.PATH||"").split(T.delimiter))if(r)for(let n of t){let o=T.join(r,`${e}${n}`);try{if(R.existsSync(o))return o}catch{}}return null}function Qt(e){let t=/Python (\d+)\.(\d+)\.(\d+)/.exec(e||"");return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function er(e){if(!e)return!1;let[t,r]=e;return!(t<je[0]||t===je[0]&&r<je[1]||t>Ue[0]||t===Ue[0]&&r>=Ue[1])}function tr(){let e=[process.env.ORACLE_PYTHON,"python3.13","python3.12","python3.11","python3","python"].filter(Boolean);for(let t of e){let r=T.isAbsolute(t)?R.existsSync(t)?t:null:ne(t);if(!r)continue;let n=oe(r,["--version"],{encoding:"utf8",timeout:15e3}),o=Qt(`${n.stdout||""}${n.stderr||""}`);if(er(o))return{bin:r,version:o.join("."),source:"host"}}return null}function rr(){return process.env.ORACLE_UV_BIN||ne("uv")||(R.existsSync(T.join(te(),".local","bin","uv"))?T.join(te(),".local","bin","uv"):null)||(R.existsSync(me())?me():null)}function nr(e,t){let r=["const fs=require('node:fs');","const [url,dest]=process.argv.slice(1);","fetch(url).then(r=>{if(!r.ok)throw new Error('http '+r.status);return r.arrayBuffer()})",".then(b=>fs.writeFileSync(dest,Buffer.from(b)))",".catch(e=>{console.error(e.message);process.exit(1)});"].join("");return oe(process.execPath,["-e",r,e,t],{encoding:"utf8",timeout:2*6e4})}function or({quiet:e=!1}={}){let t=rr();if(t)return{ok:!0,bin:t,reused:!0};D(J());let r=process.platform==="win32",n=T.join(J(),r?"uv-install.ps1":"uv-install.sh"),o=r?Ae.windows:Ae.posix,s=nr(o.url,n);if(s.status!==0)return{ok:!1,reason:`could not download the uv installer (${s.status})`,stderr:(s.stderr||"").slice(-800)};let i=R.readFileSync(n);if(!Xt(i,{windows:r}))return{ok:!1,reason:`uv ${Se} installer checksum mismatch`};let a=T.dirname(me());D(a);let c=r?ne("powershell.exe")||ne("powershell"):ne("sh")||"/bin/sh";if(!c)return{ok:!1,reason:r?"PowerShell not found":"sh not found"};let u=oe(c,r?["-NoProfile","-ExecutionPolicy","Bypass","-File",n]:[n],{stdio:e?"pipe":"inherit",encoding:"utf8",timeout:5*6e4,env:{...process.env,UV_INSTALL_DIR:a,UV_NO_MODIFY_PATH:"1"}});return u.status!==0||!R.existsSync(me())?{ok:!1,reason:`uv install failed (${u.status})`,stderr:(u.stderr||"").slice(-800)}:{ok:!0,bin:me(),reused:!1}}function lt({quiet:e=!1}={}){let t=or({quiet:e});if(!t.ok)return t;let r=t.bin,n={...process.env,UV_PYTHON_INSTALL_DIR:T.join(J(),"python"),UV_CACHE_DIR:T.join(J(),"cache")},o=oe(r,["python","install","--no-bin",pe],{stdio:e?"pipe":"inherit",encoding:"utf8",timeout:15*6e4,env:n});if(o.status!==0)return{ok:!1,reason:`uv python install ${pe} failed (${o.status})`,stderr:(o.stderr||"").slice(-800)};let s=oe(r,["python","find",pe],{encoding:"utf8",timeout:6e4,env:n}),i=(s.stdout||"").trim().split(/\r?\n/)[0];return s.status!==0||!i||!R.existsSync(i)?{ok:!1,reason:`uv could not locate python ${pe}`}:{ok:!0,bin:i,version:pe,source:"uv"}}function se(){if(process.env.ORACLE_HERMES_BIN)return{ok:!0,bin:process.env.ORACLE_HERMES_BIN,source:"env"};let e=ve();if(R.existsSync(e))return{ok:!0,bin:e,source:"managed"};let t=ne("hermes");return t?{ok:!0,bin:t,source:"path"}:{ok:!1,bin:null,source:null}}function Be(e,t,{quiet:r}){return oe(e,t,{stdio:r?"pipe":"inherit",encoding:"utf8",timeout:20*6e4})}function dt({quiet:e=!1,upgrade:t=!1}={}){let r=tr();if(!r){let l=lt({quiet:e});if(l.ok)r={bin:l.bin,version:l.version,source:"uv"};else return{ok:!1,reason:`no supported python found (need 3.11-3.13) and uv could not provide one: ${l.reason}. install uv (https://docs.astral.sh/uv) or python 3.13, then re-run 'oracle bootstrap'`}}D(J());let n=ft();if(R.existsSync(ve())&&!t)return{ok:!0,bin:ve(),reused:!0};if(!R.existsSync(T.join(n,"pyvenv.cfg"))){let l=Be(r.bin,["-m","venv",n],{quiet:e});if(l.status!==0&&r.source!=="uv"){R.rmSync(n,{recursive:!0,force:!0});let u=lt({quiet:e});if(u.ok)r={bin:u.bin,version:u.version,source:"uv"},l=Be(r.bin,["-m","venv",n],{quiet:e});else return{ok:!1,reason:`python -m venv failed (${l.status}) and uv fallback failed: ${u.reason}`,stderr:(l.stderr||"").slice(-800)}}if(l.status!==0)return{ok:!1,reason:`isolated python -m venv failed (${l.status})`,stderr:(l.stderr||"").slice(-800)}}let s=Zt();if(!R.existsSync(s))return{ok:!1,reason:`venv python missing at ${s}`};let i=["-m","pip","install","--disable-pip-version-check"];t&&i.push("--upgrade"),i.push(ut);let a=Be(s,i,{quiet:e});if(a.status!==0)return{ok:!1,reason:`pip install ${ut} failed (${a.status})`,stderr:(a.stderr||"").slice(-1200)};let c=ve();return R.existsSync(c)?{ok:!0,bin:c,reused:!1,python:r.version}:{ok:!1,reason:`hermes entrypoint not found after install (${c})`}}import{createHash as sr,randomBytes as ze,timingSafeEqual as ir}from"node:crypto";import L from"node:fs";import j from"node:path";import ar from"node:readline/promises";import{spawn as cr,spawnSync as ur}from"node:child_process";var ae=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.6",protocol:"responses"}}),lr=12e4;function fr(e={}){return typeof e.now=="function"?Number(e.now()):Date.now()}function X(e){let t=String(e||"").trim().toLowerCase();for(let[r,n]of Object.entries(ae))if(n.aliases.includes(t))return r;throw new Error(`unsupported OAuth provider: ${e||"(empty)"}`)}function W(e){let t=X(e);return{id:t,...ae[t]}}function P(e,t={}){if(!L.existsSync(e))return t;try{let r=JSON.parse(L.readFileSync(e,"utf8"));if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid object");return r}catch{throw new Error(`credential store is unreadable or corrupt: ${j.basename(e)}`)}}function mt(e){D(e),process.platform!=="win32"&&L.chmodSync(e,448)}function z(e,t){mt(j.dirname(e));let r=`${e}.${process.pid}.${ze(4).toString("hex")}.tmp`;L.writeFileSync(r,`${JSON.stringify(t,null,2)}
6
+ `,{mode:384}),L.renameSync(r,e),process.platform!=="win32"&&L.chmodSync(e,384)}function dr(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 He(e){let t=String(e||"").trim().toLowerCase();if(!/^[a-z0-9][a-z0-9._-]*$/.test(t))throw new Error(`invalid API-key provider: ${e||"(empty)"}`);return t}function ie(e={}){let t=String(e.accessToken||e.access_token||"").trim(),r=String(e.refreshToken||e.refresh_token||"").trim(),n=Number(e.expiresAt||e.expires_at||0);if(Number.isFinite(n)&&n>=1e9&&n<1e12&&(n=n*1e3),!t)throw new Error("OAuth credential is missing access token");return{accessToken:t,refreshToken:r,expiresAt:Number.isFinite(n)?n: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 pr(e={}){let t=e.file||j.join(N(),"oauth.json"),r=e.metadataFile||j.join(j.dirname(t),"oauth-meta.json"),n=e.linksFile||j.join(j.dirname(t),"oauth-links.json"),o=()=>typeof e.now=="function"?Number(e.now()):Date.now(),s=e.spawnFn||ur,i=e.keychain!==!1&&process.env.ORACLE_AUTH_FILE_STORE!=="1"&&dr(s),a=i?"linux-secret-service":"private-file",c=`${t}.lock`;async function l(w){mt(j.dirname(c));let g;for(let p=0;p<400;p+=1)try{g=L.openSync(c,"wx",384);break}catch(f){if(f?.code!=="EEXIST")throw f;try{Date.now()-L.statSync(c).mtimeMs>3e5&&L.unlinkSync(c)}catch{}await new Promise(h=>setTimeout(h,25))}if(g===void 0)throw new Error("timed out waiting for OAuth credential lock");try{return await w()}finally{try{L.closeSync(g)}catch{}try{L.unlinkSync(c)}catch{}}}function u(w,g="oauth"){return["application","oracle","kind",g,"provider",w]}function y(w){if(!L.existsSync(n))return null;let p=P(n,{providers:{}}).providers?.[w];if(!Array.isArray(p))return null;let f=[];for(let h of p)if(j.isAbsolute(String(h||"")))try{let x=P(h,{});if(w==="anthropic-oauth"&&x.claudeAiOauth){let C=ie(x.claudeAiOauth);f.push({...C,refreshToken:"",source:"external-access-only"});continue}let v=x.credential_pool&&typeof x.credential_pool=="object"?x.credential_pool:null;if(v){let C=v[w]||v[w.replace(/-oauth$/,"")]||[],K=Array.isArray(C)?C:C?[C]:[];for(let H of K)if(!(!H||typeof H!="object"))try{let Ne=ie(H);f.push({...Ne,refreshToken:"",source:"external-access-only"})}catch{}}}catch{}return f.length?f.find(h=>!h.expiresAt||h.expiresAt>o()+lr)||f[0]:null}function m(w){let g=X(w);if(i){let h=s("secret-tool",["lookup",...u(g)],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(!h.error&&h.status===0&&String(h.stdout||"").trim())try{return ie(JSON.parse(String(h.stdout).trim()))}catch{}return y(g)}let f=P(t,{providers:{}}).providers?.[g];if(f)try{return ie(f)}catch{}return y(g)}function O(w,g){let p=X(w),f=ie(g);if(i){let x=s("secret-tool",["store",`--label=Oracle ${p} OAuth`,...u(p)],{input:JSON.stringify(f),encoding:"utf8",stdio:["pipe","ignore","pipe"]});if(x.error||x.status!==0)throw new Error("OS credential store rejected OAuth credential");let v=P(r,{providers:{}});return v.providers||={},v.providers[p]={expiresAt:f.expiresAt,source:f.source},z(r,v),f}let h=P(t,{providers:{}});return h.providers||={},h.providers[p]=f,z(t,h),f}function _(w){let g=X(w);if(i){let h=s("secret-tool",["clear",...u(g)],{encoding:"utf8",stdio:["ignore","ignore","pipe"]}),x=P(r,{providers:{}});return x.providers&&delete x.providers[g],z(r,x),!h.error&&h.status===0}let p=P(t,{providers:{}}),f=!!p.providers?.[g];return p.providers&&delete p.providers[g],z(t,p),f}function M(w){let g=He(w);if(i){let p=s("secret-tool",["lookup",...u(g,"api-key")],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return p.error||p.status!==0?"":String(p.stdout||"").trim()}return String(P(t,{apiKeys:{}}).apiKeys?.[g]||"").trim()}function k(w,g){let p=He(w),f=String(g||"").trim();if(!f)throw new Error("API key is empty");if(i){let x=s("secret-tool",["store",`--label=Oracle ${p} API key`,...u(p,"api-key")],{input:f,encoding:"utf8",stdio:["pipe","ignore","pipe"]});if(x.error||x.status!==0)throw new Error("OS credential store rejected API key");let v=P(r,{providers:{},apiKeys:{}});return v.apiKeys||={},v.apiKeys[p]={configured:!0},z(r,v),!0}let h=P(t,{providers:{},apiKeys:{}});return h.apiKeys||={},h.apiKeys[p]=f,z(t,h),!0}function A(w){let g=He(w);if(i){let h=s("secret-tool",["clear",...u(g,"api-key")],{encoding:"utf8",stdio:["ignore","ignore","pipe"]}),x=P(r,{providers:{},apiKeys:{}});return x.apiKeys&&delete x.apiKeys[g],z(r,x),!h.error&&h.status===0}let p=P(t,{providers:{},apiKeys:{}}),f=!!p.apiKeys?.[g];return p.apiKeys&&delete p.apiKeys[g],z(t,p),f}function B(){let w={},g={};if(i){let p=P(r,{providers:{},apiKeys:{}});for(let[f,h]of Object.entries(p.providers||{}))w[f]={loggedIn:!!m(f),expiresAt:Number(h.expiresAt||0),source:String(h.source||"oracle"),storage:a};for(let f of Object.keys(p.apiKeys||{}))g[f]={configured:!!M(f),storage:a}}else{let p=P(t,{providers:{},apiKeys:{}});for(let[f,h]of Object.entries(p.providers||{}))w[f]={loggedIn:!!h?.accessToken,expiresAt:Number(h?.expiresAt||0),source:String(h?.source||"oracle"),storage:a};for(let[f,h]of Object.entries(p.apiKeys||{}))g[f]={configured:!!h,storage:a}}for(let p of Object.keys(ae)){if(w[p])continue;let f=y(p);f&&(w[p]={loggedIn:!0,expiresAt:f.expiresAt,source:f.source,storage:"external-access-source"})}return{storage:a,providers:w,apiKeys:g}}return Object.freeze({file:t,storage:a,get:m,set:O,remove:_,getApiKey:M,setApiKey:k,removeApiKey:A,status:B,withLock:l})}var pt;function U(){return pt||=pr(),pt}function qe(e){return Buffer.from(e).toString("base64url")}function mr(){let e=qe(ze(32));return{verifier:e,challenge:qe(sr("sha256").update(e).digest()),state:qe(ze(24))}}function hr(e,t){let r=Buffer.from(String(e||"")),n=Buffer.from(String(t||""));return r.length===n.length&&ir(r,n)}function gr(e){let t=String(e),r=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd.exe",["/d","/s","/c","start","",t]]:["xdg-open",[t]];try{return cr(r[0],r[1],{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function We(e){return new URLSearchParams(e).toString()}async function Z(e,t){if(!e?.ok){let n="";try{n=String((await e.json())?.error||"")}catch{}throw new Error(`${t} failed (HTTP ${e?.status||"unknown"}${n?`, ${n}`:""})`)}let r=await e.json();if(!r||typeof r!="object")throw new Error(`${t} returned invalid JSON`);return r}async function yr(e){if(e)return String(await e()).trim();let t=ar.createInterface({input:process.stdin,output:process.stdout});try{return String(await t.question("Authorization code: ")).trim()}finally{t.close()}}function Ye(e,t={}){let r=String(e.access_token||"").trim(),n=String(e.refresh_token||t.refreshToken||"").trim();if(!r)throw new Error("OAuth token response is missing access token");let o=Number(e.expires_in||3600);return ie({accessToken:r,refreshToken:n,expiresAt:fr(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 wr(e){let t=ae["anthropic-oauth"],r=e.pkce||mr(),n=new URLSearchParams({code:"true",client_id:t.clientId,response_type:"code",redirect_uri:t.redirectUri,scope:t.scope,code_challenge:r.challenge,code_challenge_method:"S256",state:r.state}),o=`${t.authorizeUrl}?${n}`;e.output(`Open: ${o}`),e.openFn(o);let s=await yr(e.inputFn),[i,a]=s.split("#",2);if(!i||!hr(a,r.state))throw new Error("Claude OAuth state mismatch");let c=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:a,redirect_uri:t.redirectUri,code_verifier:r.verifier})});return Ye(await Z(c,"Claude OAuth token exchange"),e)}async function br(e){let t=ae["openai-codex"],r=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(!r.user_code||!r.device_auth_id)throw new Error("Codex device authorization returned incomplete data");let n=`${t.issuer}/codex/device`;e.output(`Open: ${n}`),e.output(`Code: ${r.user_code}`),e.openFn(n);let o=Math.max(3,Number(r.interval||5)),s;for(let a=0;a<Math.ceil(900/o);a+=1){await e.sleepFn(o*1e3);let c=await e.fetchFn(`${t.issuer}/api/accounts/deviceauth/token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({device_auth_id:r.device_auth_id,user_code:r.user_code})});if(c.ok){s=await Z(c,"Codex device authorization");break}if(![403,404].includes(c.status))throw new Error(`Codex device authorization failed (HTTP ${c.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:We({grant_type:"authorization_code",code:s.authorization_code,redirect_uri:`${t.issuer}/deviceauth/callback`,client_id:t.clientId,code_verifier:s.code_verifier})});return Ye(await Z(i,"Codex OAuth token exchange"),e)}function Ee(e){let t=new URL(String(e)),r=t.hostname.toLowerCase();if(t.protocol!=="https:"||r!=="x.ai"&&!r.endsWith(".x.ai"))throw new Error("xAI OAuth discovery returned an untrusted endpoint");return t.toString()}async function kr(e){let t=ae["xai-oauth"],r=await Z(await e.fetchFn(t.discoveryUrl,{headers:{accept:"application/json"}}),"xAI OAuth discovery");Ee(r.authorization_endpoint);let n=Ee(r.token_endpoint),o=await Z(await e.fetchFn(t.deviceUrl,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:We({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=Ee(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)),a=Math.ceil(Math.max(1,Number(o.expires_in||600))/i);for(let c=0;c<a;c+=1){let l=await e.fetchFn(n,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:We({grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:t.clientId,device_code:o.device_code})});if(l.ok){let y=await Z(l,"xAI OAuth token exchange");return Ye(y,{...e,discovery:{authorization_endpoint:Ee(r.authorization_endpoint),token_endpoint:n}})}let u="";try{u=String((await l.json())?.error||"")}catch{}if(u==="slow_down")await e.sleepFn((i+1)*1e3);else if(u==="authorization_pending")await e.sleepFn(i*1e3);else throw new Error(`xAI OAuth token exchange failed (HTTP ${l.status}${u?`, ${u}`:""})`)}throw new Error("xAI device authorization timed out")}async function ht(e,t={}){let r=X(e),n={fetchFn:t.fetchFn||globalThis.fetch,inputFn:t.inputFn,sleepFn:t.sleepFn||(o=>new Promise(s=>setTimeout(s,o))),openFn:t.openFn||gr,output:t.output||(o=>process.stdout.write(`${o}
7
+ `)),now:t.now,pkce:t.pkce};return r==="anthropic-oauth"?wr(n):r==="openai-codex"?br(n):kr(n)}import Me from"node:fs";import Ge from"node:path";var xr=new Set(["openrouter","openai","anthropic","xai","deepseek","gemini","kimi","mistral","nous","qwen","glm","local","ollama","custom","anthropic-oauth","openai-codex","xai-oauth"]);function $e(e){return String(e||"").trim()||void 0}function _r(e,{required:t=!1}={}){let r=$e(e)?.toLowerCase();if(!r){if(t)throw new Error("model provider is required");return}if(!xr.has(r))throw new Error(`unsupported provider: ${r}`);return r}function vr(e,{required:t=!1}={}){let r=$e(e);if(!r){if(t)throw new Error("model is required");return}if(r.includes("..")||r.startsWith("/")||!/^[a-zA-Z0-9._:/-]{1,200}$/.test(r))throw new Error("invalid model id");return r}function Sr(e){let t=$e(e);if(!t||t.length>2048)throw new Error("invalid custom base URL");let r;try{r=new URL(t)}catch{throw new Error("invalid custom base URL")}let n=r.hostname.toLowerCase().replace(/^\[|\]$/g,""),o=n==="localhost"||n==="127.0.0.1"||n==="::1";if(r.protocol!=="https:"&&!(r.protocol==="http:"&&o)||r.username||r.password||r.search||r.hash)throw new Error("custom base URL must use HTTPS or loopback HTTP without credentials, query, or fragment");return r.toString().replace(/\/+$/,"")}function Oe({provider:e,model:t,baseUrl:r}={},{requireModel:n=!1}={}){let o=_r(e),s=vr(t,{required:n});if(o==="custom")return{provider:o,...s?{model:s}:{},baseUrl:Sr(r)};if($e(r))throw new Error("baseUrl is only supported for the custom provider");return{...o?{provider:o}:{},...s?{model:s}:{}}}var Ar=new Set(["auto","standalone","hermes","remote","arch"]);function Er(){return Ge.join(N(),"model.json")}function ce(e){return String(e||"").trim()||void 0}function $r(e={}){let t=ce(e.backend)?.toLowerCase()||"auto",r=Oe({provider:e.provider,model:e.model,baseUrl:e.baseUrl},{requireModel:t==="standalone"}),n=ce(e.apiKeyEnv),o=Number.parseInt(String(e.contextLength||""),10),s=ce(e.reasoningEffort),i=ce(e.computeHost||e.remoteHost),a=ce(e.computeUser||e.remoteUser),c=ce(e.computePath||e.remotePath);if(!Ar.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&&!/^[A-Z][A-Z0-9_]*$/.test(n))throw new Error("api key env must be an uppercase environment variable name");if(t==="remote"&&!i)throw new Error("remote backend requires computeHost");return{backend:t,...r,...n?{apiKeyEnv:n}:{},...Number.isFinite(o)&&o>0?{contextLength:o}:{},...s?{reasoningEffort:s}:{},...i?{computeHost:i}:{},...a?{computeUser:a}:{},...c?{computePath:c}:{}}}function Te(e){let t=$r(e),r=Er();D(Ge.dirname(r)),process.platform!=="win32"&&Me.chmodSync(Ge.dirname(r),448);let n=`${r}.${process.pid}.tmp`;return Me.writeFileSync(n,`${JSON.stringify(t,null,2)}
8
+ `,{mode:384}),Me.renameSync(n,r),process.platform!=="win32"&&Me.chmodSync(r,384),t}var gt=Object.freeze({openrouter:{model:"openrouter/auto"},openai:{model:"gpt-4.1-mini"},anthropic:{model:"claude-sonnet-4-6"},xai:{model:"grok-4.6"},deepseek:{model:"deepseek-chat"},gemini:{model:"gemini-2.5-flash"},kimi:{model:"kimi-k3"},mistral:{model:"mistral-large-latest"},nous:{model:"moonshotai/kimi-k3"},qwen:{model:"qwen-plus"},glm:{model:"glm-4.5"},custom:{model:""}});function Ve(e,t){let r=e.indexOf(t);return r>=0&&e[r+1]?e[r+1]:""}async function Or(){let e="";for await(let t of process.stdin)e+=t;return e.trim()}function Mr(e="API key: "){if(!process.stdin.isTTY||!process.stdin.setRawMode)throw new Error("non-interactive API-key input requires --stdin");return process.stdout.write(e),new Promise((t,r)=>{let n="",o=()=>{process.stdin.off("data",s),process.stdin.setRawMode(!1),process.stdin.pause(),process.stdout.write(`
9
+ `)},s=i=>{let a=String(i);for(let c of a){if(c==="\r"||c===`
10
+ `){o(),t(n.trim());return}if(c===""){o(),r(new Error("cancelled"));return}c==="\x7F"||c==="\b"?n=n.slice(0,-1):n+=c}};process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",s)})}function Je(e,t,{baseUrl:r=""}={}){if(e==="custom"&&!String(r||"").trim())throw new Error("custom provider requires --base-url");return{backend:"standalone",...Oe({provider:e,model:t,baseUrl:r},{requireModel:!0})}}function yt(e,t,r={}){return Te(Je(e,t,r))}function Tr(e){process.stdout.write(`storage: ${e.storage}
11
11
  `);let t=Object.entries(e.providers||{}),r=Object.entries(e.apiKeys||{});if(!t.length&&!r.length){process.stdout.write(`no credentials configured
12
12
  `);return}for(let[n,o]of t){let s=o.expiresAt?new Date(o.expiresAt).toISOString():"unknown";process.stdout.write(`${n}: ${o.loggedIn?"logged in":"missing"}, expires ${s}
13
13
  `)}for(let[n,o]of r)process.stdout.write(`${n}: API key ${o.configured?"configured":"missing"}
14
14
  `)}function Rr(){return["oracle auth, configure OAuth or API-key authentication",""," oracle auth login claude|codex|grok [--model MODEL] [--no-browser]"," oracle auth api-key PROVIDER [--model MODEL] [--base-url URL]"," PROVIDER: openrouter|openai|anthropic|xai|deepseek|gemini|kimi|mistral|nous|qwen|glm|custom",` printf '%s\\n' "$KEY" | oracle auth api-key PROVIDER --stdin`," oracle auth status [--json]"," oracle auth logout PROVIDER","","OAuth and API keys are additive. Select any compatible model with oracle model --provider PROVIDER --model MODEL."].join(`
15
15
  `)}var ue={name:"auth",summary:"login with Claude, Codex, or Grok OAuth; store provider API keys",group:"read",usage:Rr(),async run(e){let t=[...e.argv],r=t.shift()||"status",n=U();try{if(r==="status"){let o=n.status();return t.includes("--json")?process.stdout.write(`${JSON.stringify(o,null,2)}
16
- `):Tr(o),0}if(r==="login"){let o=t.find(a=>!a.startsWith("-"));if(!o)throw new Error("usage: oracle auth login claude|codex|grok");let s=W(o),i=ze(t,"--model")||s.model;We(s.id,i);let c=await mt(s.id,{openFn:t.includes("--no-browser")?()=>!1:void 0});return await n.withLock(async()=>{let a=n.get(s.id);n.set(s.id,c);try{yt(s.id,i)}catch(l){throw a?n.set(s.id,a):n.remove(s.id),l}}),process.stdout.write(`${s.id}: logged in, stored in ${n.storage}
17
- `),0}if(r==="api-key"){let o=String(t.find(a=>!a.startsWith("-"))||"").trim().toLowerCase();if(!o)throw new Error("usage: oracle auth api-key PROVIDER [--stdin]");if(!Object.hasOwn(gt,o))throw new Error(`unsupported API-key provider: ${o}`);let s=ze(t,"--model")||gt[o].model,i=ze(t,"--base-url");We(o,s,{baseUrl:i});let c=t.includes("--stdin")?await Or():await Mr();return await n.withLock(async()=>{let a=n.getApiKey(o);n.setApiKey(o,c);try{yt(o,s,{baseUrl:i})}catch(l){throw a?n.setApiKey(o,a):n.removeApiKey(o),l}}),process.stdout.write(`${o}: API key configured in ${n.storage}
18
- `),0}if(r==="logout"){let o=String(t.find(c=>!c.startsWith("-"))||"").trim().toLowerCase();if(!o)throw new Error("usage: oracle auth logout PROVIDER");let s=!1;try{s=n.remove(X(o))}catch{}let i=n.removeApiKey(o);if(!s&&!i)throw new Error(`${o}: no local credential found`);return process.stdout.write(`${o}: local credential removed
16
+ `):Tr(o),0}if(r==="login"){let o=t.find(c=>!c.startsWith("-"));if(!o)throw new Error("usage: oracle auth login claude|codex|grok");let s=W(o),i=Ve(t,"--model")||s.model;Je(s.id,i);let a=await ht(s.id,{openFn:t.includes("--no-browser")?()=>!1:void 0});return await n.withLock(async()=>{let c=n.get(s.id);n.set(s.id,a);try{yt(s.id,i)}catch(l){throw c?n.set(s.id,c):n.remove(s.id),l}}),process.stdout.write(`${s.id}: logged in, stored in ${n.storage}
17
+ `),0}if(r==="api-key"){let o=String(t.find(c=>!c.startsWith("-"))||"").trim().toLowerCase();if(!o)throw new Error("usage: oracle auth api-key PROVIDER [--stdin]");if(!Object.hasOwn(gt,o))throw new Error(`unsupported API-key provider: ${o}`);let s=Ve(t,"--model")||gt[o].model,i=Ve(t,"--base-url");Je(o,s,{baseUrl:i});let a=t.includes("--stdin")?await Or():await Mr();return await n.withLock(async()=>{let c=n.getApiKey(o);n.setApiKey(o,a);try{yt(o,s,{baseUrl:i})}catch(l){throw c?n.setApiKey(o,c):n.removeApiKey(o),l}}),process.stdout.write(`${o}: API key configured in ${n.storage}
18
+ `),0}if(r==="logout"){let o=String(t.find(a=>!a.startsWith("-"))||"").trim().toLowerCase();if(!o)throw new Error("usage: oracle auth logout PROVIDER");let s=!1;try{s=n.remove(X(o))}catch{}let i=n.removeApiKey(o);if(!s&&!i)throw new Error(`${o}: no local credential found`);return process.stdout.write(`${o}: local credential removed
19
19
  `),0}throw new Error(`unknown auth action: ${r}`)}catch(o){return process.stderr.write(`oracle auth: ${o.message}
20
- `),1}}};var Pr=Object.freeze([["#EAF7FF"," \u2584\u2584\u2584\u2588\u2588\u2588\u2588\u2584\u2584\u2584"],["#D8F2FF"," \u2584\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2584"],["#B8F0FF"," \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588"],["#ACDEEF","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588"],["#A5D9EB","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588"],["#9FCBDD","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588"],["#91C2D7","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588"],["#7FA9BE"," \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588"],["#60717F"," \u2580\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2580"],["#4A5A66"," \u2580\u2580\u2580\u2588\u2588\u2588\u2588\u2580\u2580\u2580"]]);var jn=Object.freeze([" \u2588\u2588\u2588\u2593\u2593"," \u2588\u2588\u2588\u2588\u2588\u2593\u2593\u2592","\u2588\u2588\u2588\u2588\u2588\u2588\u2593\u2593\u2592\u2592"," \u2593\u2593\u2593\u2593\u2592\u2592\u2592\u2591"," \u2592\u2592\u2592\u2591\u2591\u2591"]);var Oe=Object.freeze([[" \u2588\u2588\u2588\u2593\u2593"," \u2588\u2588\u2588\u2588\u2588\u2593\u2593\u2592","\u2588\u2588\u2588\u2588\u2588\u2588\u2593\u2593\u2592\u2592"," \u2593\u2593\u2593\u2593\u2592\u2592\u2592\u2591"," \u2592\u2592\u2592\u2591\u2591\u2591"],[" \u2593\u2588\u2588\u2588\u2593"," \u2592\u2593\u2593\u2588\u2588\u2588\u2588\u2588","\u2592\u2592\u2593\u2593\u2588\u2588\u2588\u2588\u2588\u2588"," \u2591\u2592\u2592\u2593\u2593\u2593\u2593\u2593"," \u2591\u2591\u2592\u2592\u2592\u2592"],[" \u2593\u2593\u2588\u2588\u2588"," \u2592\u2593\u2593\u2593\u2588\u2588\u2588\u2588","\u2592\u2592\u2593\u2593\u2593\u2588\u2588\u2588\u2588\u2588"," \u2591\u2592\u2592\u2592\u2593\u2593\u2593\u2593"," \u2591\u2591\u2591\u2592\u2592\u2592"],[" \u2591\u2592\u2592\u2593\u2593"," \u2591\u2592\u2592\u2593\u2593\u2593\u2593\u2593","\u2591\u2591\u2592\u2592\u2593\u2593\u2588\u2588\u2588\u2588"," \u2593\u2593\u2593\u2588\u2588\u2588\u2588\u2588\u2588"," \u2588\u2588\u2588\u2588\u2588\u2593"]]),Ir=Object.freeze([["#EAF7FF"," __ "],["#D8F2FF"," ____ _________ ______/ /__ "],["#B8F0FF"," / __ \\/ ___/ __ `/ ___/ / _ \\"],["#ACDEEF","/ /_/ / / / /_/ / /__/ / __/"],["#91C2D7","\\____/_/ \\__,_/\\___/_/\\___/ "]]);var $=Object.freeze({accent:"#B8F0FF",prompt:"#B8F0FF",banner_title:"#B8F0FF",banner_accent:"#91C2D7",ui_label:"#A5D9EB",banner_text:"#EAF2F8",status_bar_strong:"#EAF2F8",banner_border:"#6A8496",input_rule:"#6A8496",session_border:"#6A8496",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:"#1A2A35",tab_active:"#B8F0FF",tab_idle:"#91A2B1",gauge_fill:"#5CB8FF",gauge_track:"#455867",gauge_hot:"#F0C674",gauge_warn:"#FF9B71"});function Lr(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 r=t.length===3?[...t].map(n=>n.repeat(2)).join(""):t;return{r:Number.parseInt(r.slice(0,2),16),g:Number.parseInt(r.slice(2,4),16),b:Number.parseInt(r.slice(4,6),16)}}function wt(e,t,r){let n=Lr(t);return n?`\x1B[${e};2;${n.r};${n.g};${n.b}m${String(r)}\x1B[0m`:String(r)}function Ye({color:e=!0}={}){return e&&!Object.hasOwn(process.env,"NO_COLOR")?Object.freeze({fg:(r,n)=>wt(38,r,n),bg:(r,n)=>wt(48,r,n),bold:r=>`\x1B[1m${String(r)}\x1B[0m`,dim:r=>`\x1B[2m${String(r)}\x1B[0m`}):Object.freeze({fg:(r,n)=>String(n),bg:(r,n)=>String(n),bold:r=>String(r),dim:r=>String(r)})}var Bn=Ye();function bt(e){return String(e).replace(/\u001B\[[0-9;]*m/g,"")}import{spawnSync as zr}from"node:child_process";var he=Buffer.alloc(0);var Cr={A:"up",B:"down",C:"right",D:"left",H:"home",F:"end",P:"f1",Q:"f2",R:"f3",S:"f4"},Nr={1:"home",2:"insert",3:"delete",4:"end",5:"pageup",6:"pagedown",7:"home",8:"end"};function I({name:e=null,ctrl:t=!1,meta:r=!1,shift:n=!1,sequence:o=""}){return{name:e,ctrl:t,meta:r,shift:n,sequence:o}}function vt(e){return e<128?1:e>=240?4:e>=224?3:e>=192?2:1}function Dr(e){return e>=64&&e<=126}function kt(e){let t=e.toLowerCase();return I({name:t,shift:e!==t,sequence:e})}function Fr(e){return e===13?I({name:"return",sequence:"\r"}):e===10?I({name:"return",sequence:`
21
- `}):e===9?I({name:"tab",sequence:" "}):e===127?I({name:"backspace",sequence:"\x7F"}):e===8?I({name:"backspace",sequence:"\b"}):e>=1&&e<=26?I({name:String.fromCharCode(e+96),ctrl:!0,sequence:String.fromCharCode(e)}):I({name:"unknown",sequence:String.fromCharCode(e)})}function jr(e){let t=/^\u001b[\[O](\d*)(?:;(\d+))?(.)$/s.exec(e);if(!t)return I({name:"unknown",sequence:e});let r=t[1]===""?null:Number(t[1]),n=t[2]===void 0?null:Number(t[2]),o=t[3],s=null,i=n;if(o==="~"?s=Nr[r]??null:(s=Cr[o]??null,i===null&&r!==null&&r>1&&(i=r)),!s)return I({name:"unknown",sequence:e});let c=i===null?0:Math.max(0,i-1);return I({name:s,shift:(c&1)!==0,meta:(c&2)!==0,ctrl:(c&4)!==0,sequence:e})}function Ur(e,t,r,n){let o=()=>(r.push(I({name:"escape",sequence:"\x1B"})),1);if(t+1>=e.length)return n?o():0;let s=e[t+1];if(s===91||s===79){let l=t+2;for(;l<e.length&&!Dr(e[l]);)l+=1;return l>=e.length?n?o():0:(r.push(jr(e.toString("utf8",t,l+1))),l+1-t)}if(s===27)return o();let i=vt(s);if(t+1+i>e.length)return n?o():0;let c=e.toString("utf8",t+1,t+1+i),a=c.toLowerCase();return r.push(I({name:a,meta:!0,shift:c!==a,sequence:`\x1B${c}`})),1+i}function xt(e,t){let r=[],n=0;for(;n<e.length;){let o=e[n];if(o===27){let i=Ur(e,n,r,t);if(i===0)return{keys:r,rest:Buffer.from(e.subarray(n))};n+=i;continue}if(o<32||o===127){r.push(Fr(o)),n+=1;continue}let s=vt(o);if(n+s>e.length)return t?(r.push(kt(e.toString("utf8",n))),{keys:r,rest:he}):{keys:r,rest:Buffer.from(e.subarray(n))};r.push(kt(e.toString("utf8",n,n+s))),n+=s}return{keys:r,rest:he}}function _t(e){return Buffer.isBuffer(e)?e:e==null?he:typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}function St(){let e=he;return{push(t){let r=e.length===0?_t(t):Buffer.concat([e,_t(t)]),{keys:n,rest:o}=xt(r,!1);return e=o,n},flush(){if(e.length===0)return[];let{keys:t}=xt(e,!0);return e=he,t},get pending(){return e.length}}}var Ge=/\u001B\[[0-9;]*m/g;function At(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 Br(e){return[...bt(e)].reduce((t,r)=>t+At(r),0)}function Kr(e,t){if(t<=0)return"";let r=String(e).split(/(\u001B\[[0-9;]*m)/g),n="",o=0,s=!1;for(let i of r)if(i){if(Ge.test(i)){Ge.lastIndex=0,n+=i,s=i!=="\x1B[0m";continue}Ge.lastIndex=0;for(let c of i){let a=At(c);if(o+a>t)return s?`${n}\x1B[0m`:n;n+=c,o+=a}}return n}function Me(e,t,r="left"){let n=Math.max(0,Math.floor(Number(t)||0)),o=Kr(String(e),n),s=Math.max(0,n-Br(o));if(r==="right")return`${" ".repeat(s)}${o}`;if(r==="center"){let i=Math.floor(s/2);return`${" ".repeat(i)}${o}${" ".repeat(s-i)}`}return`${o}${" ".repeat(s)}`}async function Et(e,{headers:t={}}={}){let r=new AbortController,n=setTimeout(()=>r.abort(),6e3);try{let o=await fetch(e,{headers:t,signal:r.signal}),s=null;try{s=await o.json()}catch{s=null}return{status:o.status,body:s}}finally{clearTimeout(n)}}async function Hr(e){let t=String(e||"").trim();if(!/^\d+:[\w-]{20,}$/.test(t))return{ok:!1,definitive:!0,error:"that does not look like a telegram bot token (123456:ABC\u2026)"};try{let{status:r,body:n}=await Et(`https://api.telegram.org/bot${t}/getMe`);return r===200&&n?.ok&&n.result?.username?{ok:!0,definitive:!0,username:`@${n.result.username}`}:r===401||r===404?{ok:!1,definitive:!0,error:"telegram rejected this token (check BotFather)"}:{ok:!1,definitive:!1,error:`telegram returned ${r} \u2014 saved anyway, verify later`}}catch{return{ok:!1,definitive:!1,error:"network unreachable \u2014 saved anyway, verify later"}}}async function qr(e){let t=String(e||"").trim();if(t.length<50)return{ok:!1,definitive:!0,error:"that does not look like a discord bot token"};try{let{status:r,body:n}=await Et("https://discord.com/api/v10/users/@me",{headers:{Authorization:`Bot ${t}`}});return r===200&&n?.username?{ok:!0,definitive:!0,username:n.username}:r===401?{ok:!1,definitive:!0,error:"discord rejected this token (reset it in the developer portal)"}:{ok:!1,definitive:!1,error:`discord returned ${r} \u2014 saved anyway, verify later`}}catch{return{ok:!1,definitive:!1,error:"network unreachable \u2014 saved anyway, verify later"}}}async function Te(e,t){let r=String(e||"").toLowerCase();return r==="telegram"?Hr(t):r==="discord"?qr(t):{ok:!1,definitive:!1}}var Wr=Object.freeze(["telegram","discord","whatsapp","slack","signal"]),Rt=Object.freeze([{id:"claude",label:"Claude",hint:"Anthropic OAuth",kind:"oauth"},{id:"codex",label:"Codex",hint:"OpenAI OAuth",kind:"oauth"},{id:"grok",label:"Grok",hint:"xAI OAuth",kind:"oauth"}]),Pt=Object.freeze([{id:"openrouter",label:"OpenRouter",hint:"API key",kind:"api-key"},{id:"openai",label:"OpenAI",hint:"API key",kind:"api-key"},{id:"anthropic",label:"Anthropic",hint:"API key",kind:"api-key"},{id:"deepseek",label:"DeepSeek",hint:"API key",kind:"api-key"},{id:"gemini",label:"Gemini",hint:"API key",kind:"api-key"},{id:"kimi",label:"Kimi",hint:"API key",kind:"api-key"},{id:"mistral",label:"Mistral",hint:"API key",kind:"api-key"},{id:"nous",label:"Nous Portal",hint:"API key",kind:"api-key"},{id:"qwen",label:"Qwen",hint:"API key",kind:"api-key"},{id:"glm",label:"GLM",hint:"API key",kind:"api-key"}]);function Yr(e,t){let r=String(t||"unset");return r==="ready"||r==="connected"||r==="configured"?e.fg($.ok,r):r==="manual"?e.fg($.warn,r):e.fg($.banner_dim,r||"unset")}function $t({profile:e="oracle",statuses:t=null,oauthStatus:r=null,runtime:n=null}={}){let o=t;if(!o)try{o=re(e).statuses||{}}catch{o={}}let s=r;if(!s)try{s=U().status()}catch{s={providers:{},apiKeys:{}}}let i=n;if(!i)try{i=se()}catch{i={ok:!1}}let c=Rt.some(y=>{let m=W(y.id);return s.providers?.[m.id]?.loggedIn===!0}),a=Pt.some(y=>s.apiKeys?.[y.id]?.configured===!0),l=[{id:"model",label:"model / sign-in",note:"Claude \xB7 Codex \xB7 Grok \xB7 API keys",status:c||a?"ready":"unset",action:"model"}];i.ok||l.push({id:"runtime",label:"messaging runtime",note:"one-time install \u2014 powers telegram/discord bridge",status:"missing",action:"bootstrap"});let u=new Map(Q().map(y=>[y.key,y]));for(let y of Wr){let m=u.get(y);if(!m)continue;let O=o[m.key]||(m.required?.length?"unset":"manual"),_=!i.ok&&O==="ready"?"token set":O;l.push({id:m.key,label:m.name,note:m.note||"",status:_,action:m.required?.length?"token":"hermes",platform:m})}return l.push({id:"gateway",label:"restart gateway",note:"apply channel config",status:"",action:"gateway"},{id:"gateway-install",label:"start on boot",note:"keep the bot alive after reboot",status:"",action:"gateway-install"},{id:"done",label:"done",note:"back to oracle",status:"",action:"done",skip:!0}),l}function Ot(e=null){let t=e;if(!t)try{t=U().status()}catch{t={providers:{},apiKeys:{}}}let r=[];for(let n of Rt){let o=W(n.id),s=t.providers?.[o.id]?.loggedIn===!0;r.push({id:n.id,label:n.label,note:n.hint,status:s?"connected":"OAuth",action:"oauth",kind:"oauth"})}for(let n of Pt){let o=t.apiKeys?.[n.id]?.configured===!0;r.push({id:n.id,label:n.label,note:n.hint,status:o?"configured":"API key",action:"api-key",kind:"api-key"})}return r.push({id:"back",label:"back",note:"setup menu",status:"",action:"back",skip:!0}),r}function Re({width:e,palette:t,title:r,subtitle:n="",rows:o=[],index:s=0,footer:i="\u2191/\u2193 move enter select esc back"}={}){let c=Math.max(40,Math.floor(Number(e)||80)),a=Math.max(36,Math.min(c-4,72)),l=Math.max(0,Math.floor((c-a)/2)),u=Math.max(0,a-4),y=" ".repeat(l),m=A=>t.fg($.banner_border,A),O=A=>`${y}${A}`,_=(A="")=>O(`${m("\u2502")} ${Me(A,u)} ${m("\u2502")}`),M="\u2500".repeat(Math.max(0,a-2)),k=[O(`${m("\u256D")}${m(M)}${m("\u256E")}`),_(t.bold(t.fg($.accent,r||"oracle setup"))),_(m("\u2500".repeat(u)))];return n&&(k.push(_(t.fg($.banner_dim,n))),k.push(_(""))),o.forEach((A,B)=>{let w=B===s,g=w?"\u203A":" ",p=String(A.label||A.id||""),f=String(A.note||""),h=A.status?Yr(t,A.status):"",x=` ${g} ${p}`,v=[h,f?t.fg($.banner_dim,f):""].filter(Boolean).join(" "),C=Math.max(1,u-Mt(x)-Mt(It(v))-1),K=`${x}${" ".repeat(C)}${v}`;w?k.push(_(t.bg($.selection_bg,t.bold(t.fg($.banner_text,Me(K,u)))))):k.push(_(K))}),k.push(_("")),k.push(_(t.fg($.banner_dim,i))),k.push(O(`${m("\u2570")}${m(M)}${m("\u256F")}`)),k}function Gr({width:e,palette:t,platformKey:r="telegram",tokenLength:n=0,error:o=""}={}){let s=Math.max(40,Math.floor(Number(e)||80)),i=Math.max(36,Math.min(s-4,72)),c=Math.max(0,Math.floor((s-i)/2)),a=Math.max(0,i-4),l=" ".repeat(c),u=k=>t.fg($.banner_border,k),y=k=>`${l}${k}`,m=(k="")=>y(`${u("\u2502")} ${Me(k,a)} ${u("\u2502")}`),O="\u2500".repeat(Math.max(0,i-2)),_=n>0?"\u2022".repeat(Math.min(n,40)):t.fg($.banner_dim,"paste token here (hidden)");return[y(`${u("\u256D")}${u(O)}${u("\u256E")}`),m(t.bold(t.fg($.accent,`setup \xB7 ${r}`))),m(u("\u2500".repeat(a))),m(t.fg($.banner_dim,"token stays local \xB7 never echoed \xB7 never sent to chat")),m(""),m(`${t.fg($.banner_dim,"token")} ${_}`),m(n?t.fg($.banner_dim,` ${n} characters`):""),m(o?t.fg($.warn,o):""),m(t.fg($.banner_dim,"type or paste backspace enter save esc cancel")),y(`${u("\u2570")}${u(O)}${u("\u256F")}`)]}function Vr({width:e,palette:t,title:r,subtitle:n,index:o=0,yesLabel:s="yes",noLabel:i="not now"}={}){return Re({width:e,palette:t,title:r,subtitle:n,rows:[{id:"yes",label:s,note:"",status:""},{id:"no",label:i,note:"",status:""}],index:o,footer:"\u2191/\u2193 move enter select esc skip"})}function It(e){return String(e||"").replace(/\u001b\[[0-9;]*m/g,"")}function Mt(e){return It(e).length}function le(e){e.write("\x1B[2J\x1B[H")}function ge(e,t){le(e),e.write(`${t.join(`
20
+ `),1}}};var Pr=Object.freeze([["#EAF7FF"," \u2584\u2584\u2584\u2588\u2588\u2588\u2588\u2584\u2584\u2584"],["#D8F2FF"," \u2584\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2584"],["#B8F0FF"," \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588"],["#ACDEEF","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588"],["#A5D9EB","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588"],["#9FCBDD","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588"],["#91C2D7","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588"],["#7FA9BE"," \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588"],["#60717F"," \u2580\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2580"],["#4A5A66"," \u2580\u2580\u2580\u2588\u2588\u2588\u2588\u2580\u2580\u2580"]]);var jn=Object.freeze([" \u2588\u2588\u2588\u2593\u2593"," \u2588\u2588\u2588\u2588\u2588\u2593\u2593\u2592","\u2588\u2588\u2588\u2588\u2588\u2588\u2593\u2593\u2592\u2592"," \u2593\u2593\u2593\u2593\u2592\u2592\u2592\u2591"," \u2592\u2592\u2592\u2591\u2591\u2591"]);var Re=Object.freeze([[" \u2588\u2588\u2588\u2593\u2593"," \u2588\u2588\u2588\u2588\u2588\u2593\u2593\u2592","\u2588\u2588\u2588\u2588\u2588\u2588\u2593\u2593\u2592\u2592"," \u2593\u2593\u2593\u2593\u2592\u2592\u2592\u2591"," \u2592\u2592\u2592\u2591\u2591\u2591"],[" \u2593\u2588\u2588\u2588\u2593"," \u2592\u2593\u2593\u2588\u2588\u2588\u2588\u2588","\u2592\u2592\u2593\u2593\u2588\u2588\u2588\u2588\u2588\u2588"," \u2591\u2592\u2592\u2593\u2593\u2593\u2593\u2593"," \u2591\u2591\u2592\u2592\u2592\u2592"],[" \u2593\u2593\u2588\u2588\u2588"," \u2592\u2593\u2593\u2593\u2588\u2588\u2588\u2588","\u2592\u2592\u2593\u2593\u2593\u2588\u2588\u2588\u2588\u2588"," \u2591\u2592\u2592\u2592\u2593\u2593\u2593\u2593"," \u2591\u2591\u2591\u2592\u2592\u2592"],[" \u2591\u2592\u2592\u2593\u2593"," \u2591\u2592\u2592\u2593\u2593\u2593\u2593\u2593","\u2591\u2591\u2592\u2592\u2593\u2593\u2588\u2588\u2588\u2588"," \u2593\u2593\u2593\u2588\u2588\u2588\u2588\u2588\u2588"," \u2588\u2588\u2588\u2588\u2588\u2593"]]),Ir=Object.freeze([["#EAF7FF"," __ "],["#D8F2FF"," ____ _________ ______/ /__ "],["#B8F0FF"," / __ \\/ ___/ __ `/ ___/ / _ \\"],["#ACDEEF","/ /_/ / / / /_/ / /__/ / __/"],["#91C2D7","\\____/_/ \\__,_/\\___/_/\\___/ "]]);var $=Object.freeze({accent:"#B8F0FF",prompt:"#B8F0FF",banner_title:"#B8F0FF",banner_accent:"#91C2D7",ui_label:"#A5D9EB",banner_text:"#EAF2F8",status_bar_strong:"#EAF2F8",banner_border:"#6A8496",input_rule:"#6A8496",session_border:"#6A8496",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:"#1A2A35",tab_active:"#B8F0FF",tab_idle:"#91A2B1",gauge_fill:"#5CB8FF",gauge_track:"#455867",gauge_hot:"#F0C674",gauge_warn:"#FF9B71"});function Lr(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 r=t.length===3?[...t].map(n=>n.repeat(2)).join(""):t;return{r:Number.parseInt(r.slice(0,2),16),g:Number.parseInt(r.slice(2,4),16),b:Number.parseInt(r.slice(4,6),16)}}function wt(e,t,r){let n=Lr(t);return n?`\x1B[${e};2;${n.r};${n.g};${n.b}m${String(r)}\x1B[0m`:String(r)}function Xe({color:e=!0}={}){return e&&!Object.hasOwn(process.env,"NO_COLOR")?Object.freeze({fg:(r,n)=>wt(38,r,n),bg:(r,n)=>wt(48,r,n),bold:r=>`\x1B[1m${String(r)}\x1B[0m`,dim:r=>`\x1B[2m${String(r)}\x1B[0m`}):Object.freeze({fg:(r,n)=>String(n),bg:(r,n)=>String(n),bold:r=>String(r),dim:r=>String(r)})}var Bn=Xe();function bt(e){return String(e).replace(/\u001B\[[0-9;]*m/g,"")}import{spawnSync as zr}from"node:child_process";var he=Buffer.alloc(0);var Cr={A:"up",B:"down",C:"right",D:"left",H:"home",F:"end",P:"f1",Q:"f2",R:"f3",S:"f4"},Nr={1:"home",2:"insert",3:"delete",4:"end",5:"pageup",6:"pagedown",7:"home",8:"end"};function I({name:e=null,ctrl:t=!1,meta:r=!1,shift:n=!1,sequence:o=""}){return{name:e,ctrl:t,meta:r,shift:n,sequence:o}}function vt(e){return e<128?1:e>=240?4:e>=224?3:e>=192?2:1}function Dr(e){return e>=64&&e<=126}function kt(e){let t=e.toLowerCase();return I({name:t,shift:e!==t,sequence:e})}function Fr(e){return e===13?I({name:"return",sequence:"\r"}):e===10?I({name:"return",sequence:`
21
+ `}):e===9?I({name:"tab",sequence:" "}):e===127?I({name:"backspace",sequence:"\x7F"}):e===8?I({name:"backspace",sequence:"\b"}):e>=1&&e<=26?I({name:String.fromCharCode(e+96),ctrl:!0,sequence:String.fromCharCode(e)}):I({name:"unknown",sequence:String.fromCharCode(e)})}function jr(e){let t=/^\u001b[\[O](\d*)(?:;(\d+))?(.)$/s.exec(e);if(!t)return I({name:"unknown",sequence:e});let r=t[1]===""?null:Number(t[1]),n=t[2]===void 0?null:Number(t[2]),o=t[3],s=null,i=n;if(o==="~"?s=Nr[r]??null:(s=Cr[o]??null,i===null&&r!==null&&r>1&&(i=r)),!s)return I({name:"unknown",sequence:e});let a=i===null?0:Math.max(0,i-1);return I({name:s,shift:(a&1)!==0,meta:(a&2)!==0,ctrl:(a&4)!==0,sequence:e})}function Ur(e,t,r,n){let o=()=>(r.push(I({name:"escape",sequence:"\x1B"})),1);if(t+1>=e.length)return n?o():0;let s=e[t+1];if(s===91||s===79){let l=t+2;for(;l<e.length&&!Dr(e[l]);)l+=1;return l>=e.length?n?o():0:(r.push(jr(e.toString("utf8",t,l+1))),l+1-t)}if(s===27)return o();let i=vt(s);if(t+1+i>e.length)return n?o():0;let a=e.toString("utf8",t+1,t+1+i),c=a.toLowerCase();return r.push(I({name:c,meta:!0,shift:a!==c,sequence:`\x1B${a}`})),1+i}function xt(e,t){let r=[],n=0;for(;n<e.length;){let o=e[n];if(o===27){let i=Ur(e,n,r,t);if(i===0)return{keys:r,rest:Buffer.from(e.subarray(n))};n+=i;continue}if(o<32||o===127){r.push(Fr(o)),n+=1;continue}let s=vt(o);if(n+s>e.length)return t?(r.push(kt(e.toString("utf8",n))),{keys:r,rest:he}):{keys:r,rest:Buffer.from(e.subarray(n))};r.push(kt(e.toString("utf8",n,n+s))),n+=s}return{keys:r,rest:he}}function _t(e){return Buffer.isBuffer(e)?e:e==null?he:typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}function St(){let e=he;return{push(t){let r=e.length===0?_t(t):Buffer.concat([e,_t(t)]),{keys:n,rest:o}=xt(r,!1);return e=o,n},flush(){if(e.length===0)return[];let{keys:t}=xt(e,!0);return e=he,t},get pending(){return e.length}}}var Ze=/\u001B\[[0-9;]*m/g;function At(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 Br(e){return[...bt(e)].reduce((t,r)=>t+At(r),0)}function Kr(e,t){if(t<=0)return"";let r=String(e).split(/(\u001B\[[0-9;]*m)/g),n="",o=0,s=!1;for(let i of r)if(i){if(Ze.test(i)){Ze.lastIndex=0,n+=i,s=i!=="\x1B[0m";continue}Ze.lastIndex=0;for(let a of i){let c=At(a);if(o+c>t)return s?`${n}\x1B[0m`:n;n+=a,o+=c}}return n}function Pe(e,t,r="left"){let n=Math.max(0,Math.floor(Number(t)||0)),o=Kr(String(e),n),s=Math.max(0,n-Br(o));if(r==="right")return`${" ".repeat(s)}${o}`;if(r==="center"){let i=Math.floor(s/2);return`${" ".repeat(i)}${o}${" ".repeat(s-i)}`}return`${o}${" ".repeat(s)}`}async function Et(e,{headers:t={}}={}){let r=new AbortController,n=setTimeout(()=>r.abort(),6e3);try{let o=await fetch(e,{headers:t,signal:r.signal}),s=null;try{s=await o.json()}catch{s=null}return{status:o.status,body:s}}finally{clearTimeout(n)}}async function Hr(e){let t=String(e||"").trim();if(!/^\d+:[\w-]{20,}$/.test(t))return{ok:!1,definitive:!0,error:"that does not look like a telegram bot token (123456:ABC\u2026)"};try{let{status:r,body:n}=await Et(`https://api.telegram.org/bot${t}/getMe`);return r===200&&n?.ok&&n.result?.username?{ok:!0,definitive:!0,username:`@${n.result.username}`}:r===401||r===404?{ok:!1,definitive:!0,error:"telegram rejected this token (check BotFather)"}:{ok:!1,definitive:!1,error:`telegram returned ${r} \u2014 saved anyway, verify later`}}catch{return{ok:!1,definitive:!1,error:"network unreachable \u2014 saved anyway, verify later"}}}async function qr(e){let t=String(e||"").trim();if(t.length<50)return{ok:!1,definitive:!0,error:"that does not look like a discord bot token"};try{let{status:r,body:n}=await Et("https://discord.com/api/v10/users/@me",{headers:{Authorization:`Bot ${t}`}});return r===200&&n?.username?{ok:!0,definitive:!0,username:n.username}:r===401?{ok:!1,definitive:!0,error:"discord rejected this token (reset it in the developer portal)"}:{ok:!1,definitive:!1,error:`discord returned ${r} \u2014 saved anyway, verify later`}}catch{return{ok:!1,definitive:!1,error:"network unreachable \u2014 saved anyway, verify later"}}}async function Ie(e,t){let r=String(e||"").toLowerCase();return r==="telegram"?Hr(t):r==="discord"?qr(t):{ok:!1,definitive:!1}}var Wr=Object.freeze(["telegram","discord","whatsapp","slack","signal"]),Rt=Object.freeze([{id:"claude",label:"Claude",hint:"Anthropic OAuth",kind:"oauth"},{id:"codex",label:"Codex",hint:"OpenAI OAuth",kind:"oauth"},{id:"grok",label:"Grok",hint:"xAI OAuth",kind:"oauth"}]),Pt=Object.freeze([{id:"openrouter",label:"OpenRouter",hint:"API key",kind:"api-key"},{id:"openai",label:"OpenAI",hint:"API key",kind:"api-key"},{id:"anthropic",label:"Anthropic",hint:"API key",kind:"api-key"},{id:"deepseek",label:"DeepSeek",hint:"API key",kind:"api-key"},{id:"gemini",label:"Gemini",hint:"API key",kind:"api-key"},{id:"kimi",label:"Kimi",hint:"API key",kind:"api-key"},{id:"mistral",label:"Mistral",hint:"API key",kind:"api-key"},{id:"nous",label:"Nous Portal",hint:"API key",kind:"api-key"},{id:"qwen",label:"Qwen",hint:"API key",kind:"api-key"},{id:"glm",label:"GLM",hint:"API key",kind:"api-key"}]);function Yr(e,t){let r=String(t||"unset");return r==="ready"||r==="connected"||r==="configured"?e.fg($.ok,r):r==="manual"?e.fg($.warn,r):e.fg($.banner_dim,r||"unset")}function $t({profile:e="oracle",statuses:t=null,oauthStatus:r=null,runtime:n=null}={}){let o=t;if(!o)try{o=re(e).statuses||{}}catch{o={}}let s=r;if(!s)try{s=U().status()}catch{s={providers:{},apiKeys:{}}}let i=n;if(!i)try{i=se()}catch{i={ok:!1}}let a=Rt.some(y=>{let m=W(y.id);return s.providers?.[m.id]?.loggedIn===!0}),c=Pt.some(y=>s.apiKeys?.[y.id]?.configured===!0),l=[{id:"model",label:"model / sign-in",note:"Claude \xB7 Codex \xB7 Grok \xB7 API keys",status:a||c?"ready":"unset",action:"model"}];i.ok||l.push({id:"runtime",label:"messaging runtime",note:"one-time install \u2014 powers telegram/discord bridge",status:"missing",action:"bootstrap"});let u=new Map(Q().map(y=>[y.key,y]));for(let y of Wr){let m=u.get(y);if(!m)continue;let O=o[m.key]||(m.required?.length?"unset":"manual"),_=!i.ok&&O==="ready"?"token set":O;l.push({id:m.key,label:m.name,note:m.note||"",status:_,action:m.required?.length?"token":"hermes",platform:m})}return l.push({id:"gateway",label:"restart gateway",note:"apply channel config",status:"",action:"gateway"},{id:"gateway-install",label:"start on boot",note:"keep the bot alive after reboot",status:"",action:"gateway-install"},{id:"done",label:"done",note:"back to oracle",status:"",action:"done",skip:!0}),l}function Ot(e=null){let t=e;if(!t)try{t=U().status()}catch{t={providers:{},apiKeys:{}}}let r=[];for(let n of Rt){let o=W(n.id),s=t.providers?.[o.id]?.loggedIn===!0;r.push({id:n.id,label:n.label,note:n.hint,status:s?"connected":"OAuth",action:"oauth",kind:"oauth"})}for(let n of Pt){let o=t.apiKeys?.[n.id]?.configured===!0;r.push({id:n.id,label:n.label,note:n.hint,status:o?"configured":"API key",action:"api-key",kind:"api-key"})}return r.push({id:"back",label:"back",note:"setup menu",status:"",action:"back",skip:!0}),r}function Le({width:e,palette:t,title:r,subtitle:n="",rows:o=[],index:s=0,footer:i="\u2191/\u2193 move enter select esc back"}={}){let a=Math.max(40,Math.floor(Number(e)||80)),c=Math.max(36,Math.min(a-4,72)),l=Math.max(0,Math.floor((a-c)/2)),u=Math.max(0,c-4),y=" ".repeat(l),m=A=>t.fg($.banner_border,A),O=A=>`${y}${A}`,_=(A="")=>O(`${m("\u2502")} ${Pe(A,u)} ${m("\u2502")}`),M="\u2500".repeat(Math.max(0,c-2)),k=[O(`${m("\u256D")}${m(M)}${m("\u256E")}`),_(t.bold(t.fg($.accent,r||"oracle setup"))),_(m("\u2500".repeat(u)))];return n&&(k.push(_(t.fg($.banner_dim,n))),k.push(_(""))),o.forEach((A,B)=>{let w=B===s,g=w?"\u203A":" ",p=String(A.label||A.id||""),f=String(A.note||""),h=A.status?Yr(t,A.status):"",x=` ${g} ${p}`,v=[h,f?t.fg($.banner_dim,f):""].filter(Boolean).join(" "),C=Math.max(1,u-Mt(x)-Mt(It(v))-1),K=`${x}${" ".repeat(C)}${v}`;w?k.push(_(t.bg($.selection_bg,t.bold(t.fg($.banner_text,Pe(K,u)))))):k.push(_(K))}),k.push(_("")),k.push(_(t.fg($.banner_dim,i))),k.push(O(`${m("\u2570")}${m(M)}${m("\u256F")}`)),k}function Gr({width:e,palette:t,platformKey:r="telegram",tokenLength:n=0,error:o=""}={}){let s=Math.max(40,Math.floor(Number(e)||80)),i=Math.max(36,Math.min(s-4,72)),a=Math.max(0,Math.floor((s-i)/2)),c=Math.max(0,i-4),l=" ".repeat(a),u=k=>t.fg($.banner_border,k),y=k=>`${l}${k}`,m=(k="")=>y(`${u("\u2502")} ${Pe(k,c)} ${u("\u2502")}`),O="\u2500".repeat(Math.max(0,i-2)),_=n>0?"\u2022".repeat(Math.min(n,40)):t.fg($.banner_dim,"paste token here (hidden)");return[y(`${u("\u256D")}${u(O)}${u("\u256E")}`),m(t.bold(t.fg($.accent,`setup \xB7 ${r}`))),m(u("\u2500".repeat(c))),m(t.fg($.banner_dim,"token stays local \xB7 never echoed \xB7 never sent to chat")),m(""),m(`${t.fg($.banner_dim,"token")} ${_}`),m(n?t.fg($.banner_dim,` ${n} characters`):""),m(o?t.fg($.warn,o):""),m(t.fg($.banner_dim,"type or paste backspace enter save esc cancel")),y(`${u("\u2570")}${u(O)}${u("\u256F")}`)]}function Vr({width:e,palette:t,title:r,subtitle:n,index:o=0,yesLabel:s="yes",noLabel:i="not now"}={}){return Le({width:e,palette:t,title:r,subtitle:n,rows:[{id:"yes",label:s,note:"",status:""},{id:"no",label:i,note:"",status:""}],index:o,footer:"\u2191/\u2193 move enter select esc skip"})}function It(e){return String(e||"").replace(/\u001b\[[0-9;]*m/g,"")}function Mt(e){return It(e).length}function le(e){e.write("\x1B[2J\x1B[H")}function ge(e,t){le(e),e.write(`${t.join(`
22
22
  `)}
23
- `)}function Tt(e){let t=se();if(!t?.bin)return{code:1,error:"hermes not found \u2014 install hermes or run oracle bootstrap"};let r=zr(t.bin,e,{stdio:"inherit",env:process.env});return{code:typeof r.status=="number"?r.status:1}}async function Lt({stdin:e=process.stdin,stdout:t=process.stdout,env:r=process.env,palette:n,profile:o="oracle",startAt:s="menu",runAuth:i=a=>ue.run({argv:a}),restartGateway:c=!0}={}){if(e?.isTTY!==!0||t?.isTTY!==!0)return{completed:!1,actions:[],reason:"non-tty"};let a=Math.max(40,Number(t.columns||80)),l=[],u="menu",y=0,m=0,O=0,_="",M="",k="",A=null,B=$t({profile:o}),w=Ot();String(s).startsWith("token:")?(k=String(s).slice(6),u="token"):s==="model"&&(u="model");let g=St(),p=e.isRaw===!0;typeof e.setRawMode=="function"&&e.setRawMode(!0),e.resume();let f=()=>{u==="menu"?ge(t,Re({width:a,palette:n,title:"oracle setup",subtitle:"\u2191\u2193 enter \xB7 model + telegram/discord/whatsapp",rows:B,index:y})):u==="model"?ge(t,Re({width:a,palette:n,title:"sign in",subtitle:"subscription OAuth or API key",rows:w,index:m})):u==="token"?ge(t,Gr({width:a,palette:n,platformKey:k,tokenLength:_.length,error:M})):u==="confirm-gateway"?ge(t,Vr({width:a,palette:n,title:A?.title||"restart gateway?",subtitle:A?.subtitle||"applies bot tokens to the live bridge",index:O,yesLabel:"restart gateway now",noLabel:"later \u2014 oracle setup gateway restart"})):u==="notice"&&ge(t,Re({width:a,palette:n,title:A?.title||"setup",subtitle:A?.subtitle||"",rows:[{id:"ok",label:"continue",note:"",status:""}],index:0,footer:"enter continue esc menu"}))};f();let h=async x=>(typeof e.setRawMode=="function"&&e.setRawMode(p),e.pause(),le(t),x);return new Promise(x=>{let v=null,C=!1,K=b=>{C||(C=!0,v&&clearTimeout(v),e.off("data",rt),Promise.resolve(h(b)).then(x))},H=()=>{B=$t({profile:o}),w=Ot()},Pe=async()=>{let b=_.trim();if(!b){M="empty token",f();return}M="checking token\u2026",f();let d={ok:!1,definitive:!1};try{d=await Te(k,b)}catch{d={ok:!1,definitive:!1}}if(!d.ok&&d.definitive){_="",M=d.error||"platform rejected this token",f();return}try{let S=ke(o,k,b);V({lastPlatform:k,profile:o,ready:!0}),l.push(`token:${k}${d.ok?":verified":""}`),_="",M="";let E=!1;try{E=se().ok===!0}catch{E=!1}let nt=d.username?` \xB7 bot ${d.username}`:"";E?(A={title:`${k} saved${nt}`,subtitle:d.ok?`token verified live \xB7 ${S.path}`:`wrote credentials \xB7 ${S.path}`},O=0,u=c?"confirm-gateway":"menu"):(A={title:`${k} token saved${nt}`,subtitle:"next: install the messaging runtime (menu row) so the bot can answer"},O=0,u="notice"),H(),f()}catch(S){M=S?.message||"save failed",_="",f()}},et=async b=>{if(!b||b.action==="done"){K({completed:!0,actions:l});return}if(b.action==="model"){u="model",m=0,f();return}if(b.action==="token"){k=b.id,_="",M="",u="token",f();return}if(b.action==="bootstrap"){typeof e.setRawMode=="function"&&e.setRawMode(p),e.pause(),le(t),t.write(`installing messaging runtime (one-time, a few minutes)\u2026
23
+ `)}function Tt(e){let t=se();if(!t?.bin)return{code:1,error:"hermes not found \u2014 install hermes or run oracle bootstrap"};let r=zr(t.bin,e,{stdio:"inherit",env:process.env});return{code:typeof r.status=="number"?r.status:1}}async function Lt({stdin:e=process.stdin,stdout:t=process.stdout,env:r=process.env,palette:n,profile:o="oracle",startAt:s="menu",runAuth:i=c=>ue.run({argv:c}),restartGateway:a=!0}={}){if(e?.isTTY!==!0||t?.isTTY!==!0)return{completed:!1,actions:[],reason:"non-tty"};let c=Math.max(40,Number(t.columns||80)),l=[],u="menu",y=0,m=0,O=0,_="",M="",k="",A=null,B=$t({profile:o}),w=Ot();String(s).startsWith("token:")?(k=String(s).slice(6),u="token"):s==="model"&&(u="model");let g=St(),p=e.isRaw===!0;typeof e.setRawMode=="function"&&e.setRawMode(!0),e.resume();let f=()=>{u==="menu"?ge(t,Le({width:c,palette:n,title:"oracle setup",subtitle:"\u2191\u2193 enter \xB7 model + telegram/discord/whatsapp",rows:B,index:y})):u==="model"?ge(t,Le({width:c,palette:n,title:"sign in",subtitle:"subscription OAuth or API key",rows:w,index:m})):u==="token"?ge(t,Gr({width:c,palette:n,platformKey:k,tokenLength:_.length,error:M})):u==="confirm-gateway"?ge(t,Vr({width:c,palette:n,title:A?.title||"restart gateway?",subtitle:A?.subtitle||"applies bot tokens to the live bridge",index:O,yesLabel:"restart gateway now",noLabel:"later \u2014 oracle setup gateway restart"})):u==="notice"&&ge(t,Le({width:c,palette:n,title:A?.title||"setup",subtitle:A?.subtitle||"",rows:[{id:"ok",label:"continue",note:"",status:""}],index:0,footer:"enter continue esc menu"}))};f();let h=async x=>(typeof e.setRawMode=="function"&&e.setRawMode(p),e.pause(),le(t),x);return new Promise(x=>{let v=null,C=!1,K=b=>{C||(C=!0,v&&clearTimeout(v),e.off("data",nt),Promise.resolve(h(b)).then(x))},H=()=>{B=$t({profile:o}),w=Ot()},Ne=async()=>{let b=_.trim();if(!b){M="empty token",f();return}M="checking token\u2026",f();let d={ok:!1,definitive:!1};try{d=await Ie(k,b)}catch{d={ok:!1,definitive:!1}}if(!d.ok&&d.definitive){_="",M=d.error||"platform rejected this token",f();return}try{let S=_e(o,k,b);V({lastPlatform:k,profile:o,ready:!0}),l.push(`token:${k}${d.ok?":verified":""}`),_="",M="";let E=!1;try{E=se().ok===!0}catch{E=!1}let ot=d.username?` \xB7 bot ${d.username}`:"";E?(A={title:`${k} saved${ot}`,subtitle:d.ok?`token verified live \xB7 ${S.path}`:`wrote credentials \xB7 ${S.path}`},O=0,u=a?"confirm-gateway":"menu"):(A={title:`${k} token saved${ot}`,subtitle:"next: install the messaging runtime (menu row) so the bot can answer"},O=0,u="notice"),H(),f()}catch(S){M=S?.message||"save failed",_="",f()}},tt=async b=>{if(!b||b.action==="done"){K({completed:!0,actions:l});return}if(b.action==="model"){u="model",m=0,f();return}if(b.action==="token"){k=b.id,_="",M="",u="token",f();return}if(b.action==="bootstrap"){typeof e.setRawMode=="function"&&e.setRawMode(p),e.pause(),le(t),t.write(`installing messaging runtime (one-time, a few minutes)\u2026
24
24
 
25
- `);let d={ok:!1,reason:"unknown"};try{d=ft({})}catch(S){d={ok:!1,reason:S?.message||"install failed"}}l.push(`bootstrap:${d.ok?"ok":"fail"}`),typeof e.setRawMode=="function"&&e.setRawMode(!0),e.resume(),H(),A={title:d.ok?"messaging runtime ready":"runtime install failed",subtitle:d.ok?"pick telegram / discord next":d.reason||"see oracle bootstrap"},u="notice",f();return}if(b.action==="hermes"){typeof e.setRawMode=="function"&&e.setRawMode(p),e.pause(),le(t),t.write(`opening ${b.id} setup\u2026
26
- `);let S=G(b.id)?.hermes||["gateway","setup"],E=Tt(["-p",o,...S]);l.push(`hermes:${b.id}:${E.code}`),V({lastPlatform:b.id,profile:o}),typeof e.setRawMode=="function"&&e.setRawMode(!0),e.resume(),H(),A={title:`${b.id} setup finished`,subtitle:E.code===0?"restart gateway to apply":E.error||`exit ${E.code}`},O=0,u=c?"confirm-gateway":"menu",f();return}if(b.action==="gateway"||b.action==="gateway-install"){let d=b.action==="gateway-install"?"install":"restart";typeof e.setRawMode=="function"&&e.setRawMode(p),e.pause(),le(t),t.write(d==="install"?`installing boot service\u2026
25
+ `);let d={ok:!1,reason:"unknown"};try{d=dt({})}catch(S){d={ok:!1,reason:S?.message||"install failed"}}l.push(`bootstrap:${d.ok?"ok":"fail"}`),typeof e.setRawMode=="function"&&e.setRawMode(!0),e.resume(),H(),A={title:d.ok?"messaging runtime ready":"runtime install failed",subtitle:d.ok?"pick telegram / discord next":d.reason||"see oracle bootstrap"},u="notice",f();return}if(b.action==="hermes"){typeof e.setRawMode=="function"&&e.setRawMode(p),e.pause(),le(t),t.write(`opening ${b.id} setup\u2026
26
+ `);let S=G(b.id)?.hermes||["gateway","setup"],E=Tt(["-p",o,...S]);l.push(`hermes:${b.id}:${E.code}`),V({lastPlatform:b.id,profile:o}),typeof e.setRawMode=="function"&&e.setRawMode(!0),e.resume(),H(),A={title:`${b.id} setup finished`,subtitle:E.code===0?"restart gateway to apply":E.error||`exit ${E.code}`},O=0,u=a?"confirm-gateway":"menu",f();return}if(b.action==="gateway"||b.action==="gateway-install"){let d=b.action==="gateway-install"?"install":"restart";typeof e.setRawMode=="function"&&e.setRawMode(p),e.pause(),le(t),t.write(d==="install"?`installing boot service\u2026
27
27
  `:`restarting gateway\u2026
28
28
  `);let S=Tt(["-p",o,"gateway",d]);l.push(`gateway:${d}:${S.code}`),typeof e.setRawMode=="function"&&e.setRawMode(!0),e.resume(),A={title:S.code===0?d==="install"?"boot service installed":"gateway restarted":`gateway ${d} failed`,subtitle:S.code===0?d==="install"?"bot survives reboots now":"channels should be live":S.error||`exit ${S.code}`},u="notice",f()}},Ft=async b=>{if(!b||b.action==="back"){u="menu",f();return}typeof e.setRawMode=="function"&&e.setRawMode(p),e.pause(),le(t);let d=b.kind==="oauth"?["login",b.id]:["api-key",b.id];t.write(`connecting ${b.label}\u2026
29
29
  `);let S=1;try{S=await i(d)}catch(E){t.write(`${E?.message||E}
30
- `),S=1}l.push(`model:${b.id}:${S}`),typeof e.setRawMode=="function"&&e.setRawMode(!0),e.resume(),H(),u="menu",f()},tt=b=>{for(let d of b){if(d.ctrl&&d.name==="c"){K({completed:!1,actions:l,reason:"cancel"});return}if(u==="token"){if(d.name==="escape"){_="",M="",u="menu",f();continue}if(d.name==="return"){Pe();continue}if(d.name==="backspace"||d.sequence==="\x7F"||d.sequence==="\b"){_=_.slice(0,-1),M="",f();continue}let E=d.sequence||"";if(E&&!d.ctrl&&!d.meta&&E!=="\x1B"){if(E.startsWith("\x1B"))continue;_+=E,M="",f()}continue}if(u==="confirm-gateway"){if(d.name==="up"||d.name==="down"){O=O===0?1:0,f();continue}if(d.name==="escape"){u="menu",f();continue}d.name==="return"&&(O===0?et({action:"gateway",id:"gateway"}):(u="menu",f()));continue}if(u==="notice"){(d.name==="return"||d.name==="escape")&&(u="menu",f());continue}if(u==="model"){let E=w.length;if(d.name==="up"){m=E?(m-1+E)%E:0,f();continue}if(d.name==="down"){m=E?(m+1)%E:0,f();continue}if(d.name==="escape"){u="menu",f();continue}d.name==="return"&&Ft(w[m]);continue}let S=B.length;if(d.name==="up"){y=S?(y-1+S)%S:0,f();continue}if(d.name==="down"){y=S?(y+1)%S:0,f();continue}if(d.name==="escape"){K({completed:!0,actions:l,reason:"esc"});continue}d.name==="return"&&et(B[y])}},rt=b=>{tt(g.push(b)),v&&(clearTimeout(v),v=null),g.pending>0&&(v=setTimeout(()=>{v=null,tt(g.flush())},30),typeof v.unref=="function"&&v.unref())};e.on("data",rt)})}var Ve=Object.freeze([{alias:"claude",label:"Claude",hint:"Anthropic subscription"},{alias:"codex",label:"Codex",hint:"OpenAI subscription"},{alias:"grok",label:"Grok",hint:"xAI subscription"}]),Xe=Object.freeze([{id:"openrouter",label:"OpenRouter"},{id:"openai",label:"OpenAI"},{id:"anthropic",label:"Anthropic"},{id:"xai",label:"xAI"},{id:"deepseek",label:"DeepSeek"},{id:"gemini",label:"Gemini"},{id:"kimi",label:"Kimi"},{id:"mistral",label:"Mistral"},{id:"nous",label:"Nous Portal"},{id:"qwen",label:"Qwen"},{id:"glm",label:"GLM"}]),Ze=Object.freeze([...Ve.map((e,t)=>({n:t+1,id:e.alias,label:e.label,kind:"oauth",hint:e.hint})),...Xe.map((e,t)=>({n:Ve.length+t+1,id:e.id,label:e.label,kind:"api-key",hint:"API key"})),{n:Ve.length+Xe.length+1,id:"custom",label:"Custom",kind:"api-key",hint:"OpenAI-compatible"}]);function Xr(e){let t=String(e||"").trim().toLowerCase();if(!t||t==="skip")return{skip:!0};let r=Ze.find(n=>String(n.n)===t||n.id===t);return r||{unknown:!0,choice:t}}function Dt(e="sign in",t=0){let r=Oe[t]||Oe[0];return["",`${r[0]} oracle`,`${r[1]} ${e}`,r[2],r[3],r[4],""].join(`
31
- `)}async function Zr(e){if(e.isTTY!==!0||process.env.NODE_TEST_CONTEXT||process.env.ORACLE_INSTALL_PLAIN==="1")return;let t=r=>new Promise(n=>setTimeout(n,r));for(let r=0;r<Oe.length;r+=1)r>0&&e.write("\x1B[7A"),e.write(`${Dt("sign in",r)}
32
- `),await t(90)}async function Po({stdin:e=process.stdin,stdout:t=process.stdout,readLine:r,runAuth:n=o=>ue.run({argv:o})}={}){if(await Zr(t),t.write(`${ye()}
30
+ `),S=1}l.push(`model:${b.id}:${S}`),typeof e.setRawMode=="function"&&e.setRawMode(!0),e.resume(),H(),u="menu",f()},rt=b=>{for(let d of b){if(d.ctrl&&d.name==="c"){K({completed:!1,actions:l,reason:"cancel"});return}if(u==="token"){if(d.name==="escape"){_="",M="",u="menu",f();continue}if(d.name==="return"){Ne();continue}if(d.name==="backspace"||d.sequence==="\x7F"||d.sequence==="\b"){_=_.slice(0,-1),M="",f();continue}let E=d.sequence||"";if(E&&!d.ctrl&&!d.meta&&E!=="\x1B"){if(E.startsWith("\x1B"))continue;_+=E,M="",f()}continue}if(u==="confirm-gateway"){if(d.name==="up"||d.name==="down"){O=O===0?1:0,f();continue}if(d.name==="escape"){u="menu",f();continue}d.name==="return"&&(O===0?tt({action:"gateway",id:"gateway"}):(u="menu",f()));continue}if(u==="notice"){(d.name==="return"||d.name==="escape")&&(u="menu",f());continue}if(u==="model"){let E=w.length;if(d.name==="up"){m=E?(m-1+E)%E:0,f();continue}if(d.name==="down"){m=E?(m+1)%E:0,f();continue}if(d.name==="escape"){u="menu",f();continue}d.name==="return"&&Ft(w[m]);continue}let S=B.length;if(d.name==="up"){y=S?(y-1+S)%S:0,f();continue}if(d.name==="down"){y=S?(y+1)%S:0,f();continue}if(d.name==="escape"){K({completed:!0,actions:l,reason:"esc"});continue}d.name==="return"&&tt(B[y])}},nt=b=>{rt(g.push(b)),v&&(clearTimeout(v),v=null),g.pending>0&&(v=setTimeout(()=>{v=null,rt(g.flush())},30),typeof v.unref=="function"&&v.unref())};e.on("data",nt)})}var ye=Object.freeze([{alias:"claude",label:"Claude",hint:"Anthropic subscription"},{alias:"codex",label:"Codex",hint:"OpenAI subscription"},{alias:"grok",label:"Grok",hint:"xAI subscription"}]),we=Object.freeze([{id:"openrouter",label:"OpenRouter"},{id:"openai",label:"OpenAI"},{id:"anthropic",label:"Anthropic"},{id:"xai",label:"xAI"},{id:"deepseek",label:"DeepSeek"},{id:"gemini",label:"Gemini"},{id:"kimi",label:"Kimi"},{id:"mistral",label:"Mistral"},{id:"nous",label:"Nous Portal"},{id:"qwen",label:"Qwen"},{id:"glm",label:"GLM"}]),Ce=Object.freeze([...ye.map((e,t)=>({n:t+1,id:e.alias,label:e.label,kind:"oauth",hint:e.hint})),...we.map((e,t)=>({n:ye.length+t+1,id:e.id,label:e.label,kind:"api-key",hint:"API key"})),{n:ye.length+we.length+1,id:"custom",label:"Custom",kind:"api-key",hint:"OpenAI-compatible"},{n:ye.length+we.length+2,id:"local",label:"Local",kind:"local",hint:"llama.cpp :8080"},{n:ye.length+we.length+3,id:"ollama",label:"Ollama",kind:"local",hint:"ollama :11434"}]);function Xr(e){let t=String(e||"").trim().toLowerCase();if(!t||t==="skip")return{skip:!0};let r=Ce.find(n=>String(n.n)===t||n.id===t);return r||{unknown:!0,choice:t}}function Dt(e="sign in",t=0){let r=Re[t]||Re[0];return["",`${r[0]} oracle`,`${r[1]} ${e}`,r[2],r[3],r[4],""].join(`
31
+ `)}async function Zr(e){if(e.isTTY!==!0||process.env.NODE_TEST_CONTEXT||process.env.ORACLE_INSTALL_PLAIN==="1")return;let t=r=>new Promise(n=>setTimeout(n,r));for(let r=0;r<Re.length;r+=1)r>0&&e.write("\x1B[7A"),e.write(`${Dt("sign in",r)}
32
+ `),await t(90)}async function Io({stdin:e=process.stdin,stdout:t=process.stdout,readLine:r,runAuth:n=o=>ue.run({argv:o})}={}){if(await Zr(t),t.write(`${be()}
33
33
  `),t.write(`number or name \xB7 enter skips
34
- `),e.isTTY!==!0||t.isTTY!==!0)return{skipped:!0,reason:"non-tty"};t.write("> ");let o=r?await r():await new Promise(a=>{let l="",u=y=>{l+=String(y),(l.includes(`
35
- `)||l.includes("\r"))&&(e.off("data",u),a(l.trim()))};e.on("data",u)}),s=Xr(o);if(s.skip)return{skipped:!0,reason:"skipped"};if(s.unknown)return t.write(`unknown choice '${s.choice}'
36
- `),{skipped:!0,reason:"unknown"};let i=s.kind==="oauth"?["login",s.id]:["api-key",s.id],c=await n(i);return{skipped:!1,choice:s.id,code:c}}function ye(e=U().status()){let t=[Dt("sign in"),"sign in with a subscription",""];for(let r of Ze.filter(n=>n.kind==="oauth")){let n=W(r.id),o=e.providers?.[n.id]?.loggedIn===!0;t.push(` ${String(r.n).padStart(2)} ${r.label.padEnd(12)} ${o?"connected":"OAuth"}`)}t.push("","or use an API key","");for(let r of Ze.filter(n=>n.kind==="api-key")){let n=r.id==="custom"?!1:e.apiKeys?.[r.id]?.configured===!0;t.push(` ${String(r.n).padStart(2)} ${r.label.padEnd(12)} ${n?"configured":"not configured"}`)}return t.push("","Your key stays on this machine. Nothing is uploaded by Oracle.",""),t.join(`
37
- `)}function Je(){return["oracle setup, configure standalone OAuth, messaging, and the local agent surface",""," oracle setup menu + platform status"," oracle setup status same, machine-friendly with --json"," oracle setup model show Claude, Codex, Grok, OpenRouter, Qwen, GLM, Nous Portal, ..."," oracle setup model claude connect Anthropic OAuth + select standalone"," oracle setup model codex connect OpenAI OAuth + select standalone"," oracle setup model grok connect xAI OAuth + select standalone"," oracle setup model deepseek securely add a provider API key"," oracle setup model kimi securely add a Kimi API key"," oracle setup model qwen securely add a Qwen / DashScope API key"," oracle setup model glm securely add a GLM / Zhipu API key"," oracle setup model openrouter securely add an OpenRouter API key"," oracle setup model nous securely add a Nous Portal API key"," oracle setup messaging open hermes gateway setup wizard"," oracle setup telegram set TELEGRAM_BOT_TOKEN for profile"," oracle setup discord set DISCORD_BOT_TOKEN for profile"," oracle setup slack set slack tokens"," oracle setup <platform> any supported hermes platform"," oracle setup gateway [status|restart|start|stop]"," oracle setup profile [name] default: oracle","","chat:"," /setup arrow-key setup wizard (model + channels)"," /setup telegram jump to telegram token entry"," /setup status ready/unset (no secrets)","","model credentials stay in the OS keychain or private ~/.config/oracle storage.","messaging tokens stay local in ~/.hermes/profiles/<profile>/.env","oracle never prints secrets.","TTY default: oracle setup opens an \u2191\u2193 enter menu (ORACLE_SETUP_PLAIN=1 for text)."].join(`
38
- `)}function Qr(e){let t=e.indexOf("--profile");if(t>=0&&e[t+1])return e[t+1];let r=e.indexOf("-p");return r>=0&&e[r+1]?e[r+1]:process.env.ORACLE_PROFILE||"oracle"}function en(e){let t=[];for(let r=0;r<e.length;r++){if(e[r]==="--profile"||e[r]==="-p"){r+=1;continue}t.push(e[r])}return t}function Qe(e,{inherit:t=!0,env:r=process.env}={}){let n=se();if(!n.ok)return process.stderr.write(`oracle setup: Hermes not detected (opt-in only).
34
+ `),e.isTTY!==!0||t.isTTY!==!0)return{skipped:!0,reason:"non-tty"};t.write("> ");let o=r?await r():await new Promise(c=>{let l="",u=y=>{l+=String(y),(l.includes(`
35
+ `)||l.includes("\r"))&&(e.off("data",u),c(l.trim()))};e.on("data",u)}),s=Xr(o);if(s.skip)return{skipped:!0,reason:"skipped"};if(s.unknown)return t.write(`unknown choice '${s.choice}'
36
+ `),{skipped:!0,reason:"unknown"};let i=s.kind==="oauth"?["login",s.id]:["api-key",s.id],a=await n(i);return{skipped:!1,choice:s.id,code:a}}function be(e=U().status()){let t=[Dt("sign in"),"sign in with a subscription",""];for(let r of Ce.filter(n=>n.kind==="oauth")){let n=W(r.id),o=e.providers?.[n.id]?.loggedIn===!0;t.push(` ${String(r.n).padStart(2)} ${r.label.padEnd(12)} ${o?"connected":"OAuth"}`)}t.push("","or use an API key","");for(let r of Ce.filter(n=>n.kind==="api-key")){let n=r.id==="custom"?!1:e.apiKeys?.[r.id]?.configured===!0;t.push(` ${String(r.n).padStart(2)} ${r.label.padEnd(12)} ${n?"configured":"not configured"}`)}t.push("","or a local loopback model","");for(let r of Ce.filter(n=>n.kind==="local"))t.push(` ${String(r.n).padStart(2)} ${r.label.padEnd(12)} loopback`);return t.push("","Your key stays on this machine. Nothing is uploaded by Oracle.",""),t.join(`
37
+ `)}function Qe(){return["oracle setup, configure standalone OAuth, messaging, and the local agent surface",""," oracle setup menu + platform status"," oracle setup status same, machine-friendly with --json"," oracle setup model show Claude, Codex, Grok, OpenRouter, Qwen, GLM, Nous Portal, ..."," oracle setup model claude connect Anthropic OAuth + select standalone"," oracle setup model codex connect OpenAI OAuth + select standalone"," oracle setup model grok connect xAI OAuth + select standalone"," oracle setup model deepseek securely add a provider API key"," oracle setup model kimi securely add a Kimi API key"," oracle setup model qwen securely add a Qwen / DashScope API key"," oracle setup model glm securely add a GLM / Zhipu API key"," oracle setup model local select llama.cpp on 127.0.0.1:8080 (no key)"," oracle setup model ollama select Ollama on 127.0.0.1:11434 (no key)"," oracle setup model openrouter securely add an OpenRouter API key"," oracle setup model nous securely add a Nous Portal API key"," oracle setup messaging open hermes gateway setup wizard"," oracle setup telegram set TELEGRAM_BOT_TOKEN for profile"," oracle setup discord set DISCORD_BOT_TOKEN for profile"," oracle setup slack set slack tokens"," oracle setup <platform> any supported hermes platform"," oracle setup gateway [status|restart|start|stop]"," oracle setup profile [name] default: oracle","","chat:"," /setup arrow-key setup wizard (model + channels)"," /setup telegram jump to telegram token entry"," /setup status ready/unset (no secrets)","","model credentials stay in the OS keychain or private ~/.config/oracle storage.","messaging tokens stay local in ~/.hermes/profiles/<profile>/.env","oracle never prints secrets.","TTY default: oracle setup opens an \u2191\u2193 enter menu (ORACLE_SETUP_PLAIN=1 for text)."].join(`
38
+ `)}function Qr(e){let t=e.indexOf("--profile");if(t>=0&&e[t+1])return e[t+1];let r=e.indexOf("-p");return r>=0&&e[r+1]?e[r+1]:process.env.ORACLE_PROFILE||"oracle"}function en(e){let t=[];for(let r=0;r<e.length;r++){if(e[r]==="--profile"||e[r]==="-p"){r+=1;continue}t.push(e[r])}return t}function et(e,{inherit:t=!0,env:r=process.env}={}){let n=se();if(!n.ok)return process.stderr.write(`oracle setup: Hermes not detected (opt-in only).
39
39
  Native Oracle does not need Hermes.
40
40
  To use Hermes messaging/gateway: install Hermes, or run \`oracle bootstrap\`, then retry.
41
41
  Detect: oracle harness detect
42
42
  `),1;let o=Jr(n.bin,e,{stdio:t?"inherit":"pipe",encoding:"utf8",env:r});return o.error?(process.stderr.write(`oracle setup: failed to run hermes: ${o.error.message}
43
43
  `),1):(t||(o.stdout&&process.stdout.write(o.stdout),o.stderr&&process.stderr.write(o.stderr)),typeof o.status=="number"?o.status:1)}async function Nt(e){if(!Y.isTTY||typeof Y.setRawMode!="function"){let t=new Error("interactive token entry requires a tty");throw t.code="NO_TTY",t}return Ct.write(`${e}: `),new Promise((t,r)=>{let n="",o=()=>{Y.off("data",s),Y.setRawMode(!1),Y.pause(),Ct.write(`
44
- `)},s=i=>{for(let c of String(i)){if(c==="\r"||c===`
45
- `){o(),t(n.trim());return}if(c===""){o(),r(new Error("cancelled"));return}c==="\x7F"||c==="\b"?n=n.slice(0,-1):n+=c}};Y.setRawMode(!0),Y.resume(),Y.on("data",s)})}async function tn(e,t,r=[]){let n=G(t);if(!n)return process.stderr.write(`oracle setup: unknown platform '${t}'
46
- `),process.stderr.write(`known: ${Q().map(a=>a.key).join(", ")}
44
+ `)},s=i=>{for(let a of String(i)){if(a==="\r"||a===`
45
+ `){o(),t(n.trim());return}if(a===""){o(),r(new Error("cancelled"));return}a==="\x7F"||a==="\b"?n=n.slice(0,-1):n+=a}};Y.setRawMode(!0),Y.resume(),Y.on("data",s)})}async function tn(e,t,r=[]){let n=G(t);if(!n)return process.stderr.write(`oracle setup: unknown platform '${t}'
46
+ `),process.stderr.write(`known: ${Q().map(c=>c.key).join(", ")}
47
47
  `),1;if(!n.required.length)return process.stdout.write(`opening hermes setup for ${n.key} (interactive)
48
- `),V({lastPlatform:n.key,profile:e}),Qe(["-p",e,...n.hermes||["gateway","setup"]]);let o={},s=[];for(let a=0;a<r.length;a++){let l=r[a];if(l==="--token"&&r[a+1]){o.token=r[++a];continue}if(l==="--allowed-users"&&r[a+1]){o.allowedUsers=r[++a];continue}if(l==="--app-token"&&r[a+1]){o.appToken=r[++a];continue}if(l.startsWith("-"))return process.stderr.write(`oracle setup: unknown flag ${l}
49
- `),1;s.push(l)}let i=o.token||s[0]||"";if(!i&&!process.stdin.isTTY&&(i=await readStdinSecret()),!i)try{i=await Nt(`${n.key} bot token`)}catch(a){if(a?.code==="NO_TTY")return process.stderr.write(`oracle setup ${n.key}: pipe the token on stdin (echo "$TOKEN" | oracle setup ${n.key}) or pass --token <value>
50
- `),1;throw a}if(!i)return process.stderr.write(`aborted: empty token
51
- `),1;let c={};if(o.allowedUsers&&(n.key==="telegram"&&(c.TELEGRAM_ALLOWED_USERS=o.allowedUsers),n.key==="discord"&&(c.DISCORD_ALLOWED_USERS=o.allowedUsers),n.key==="slack"&&(c.SLACK_ALLOWED_USERS=o.allowedUsers)),o.appToken&&n.key==="slack"&&(c.SLACK_APP_TOKEN=o.appToken),n.key==="slack"&&!c.SLACK_APP_TOKEN){let a=o.appToken||s[1]||"";if(!a&&process.stdin.isTTY&&(a=await Nt("slack app token (xapp-...)")),!a)return process.stderr.write(`slack needs bot token + app token
52
- `),1;c.SLACK_APP_TOKEN=a}try{let a=await Te(n.key,i).catch(()=>({ok:!1,definitive:!1}));if(!a.ok&&a.definitive)return process.stderr.write(`oracle setup ${n.key}: ${a.error||"platform rejected this token"}
53
- `),1;let l=ke(e,n.key,i,c);V({lastPlatform:n.key,profile:e,ready:!0});let u=a.ok&&a.username?`bot: ${a.username} (token verified live)
54
- `:"",y=!a.ok&&a.error?`note: ${a.error}
48
+ `),V({lastPlatform:n.key,profile:e}),et(["-p",e,...n.hermes||["gateway","setup"]]);let o={},s=[];for(let c=0;c<r.length;c++){let l=r[c];if(l==="--token"&&r[c+1]){o.token=r[++c];continue}if(l==="--allowed-users"&&r[c+1]){o.allowedUsers=r[++c];continue}if(l==="--app-token"&&r[c+1]){o.appToken=r[++c];continue}if(l.startsWith("-"))return process.stderr.write(`oracle setup: unknown flag ${l}
49
+ `),1;s.push(l)}let i=o.token||s[0]||"";if(!i&&!process.stdin.isTTY&&(i=await readStdinSecret()),!i)try{i=await Nt(`${n.key} bot token`)}catch(c){if(c?.code==="NO_TTY")return process.stderr.write(`oracle setup ${n.key}: pipe the token on stdin (echo "$TOKEN" | oracle setup ${n.key}) or pass --token <value>
50
+ `),1;throw c}if(!i)return process.stderr.write(`aborted: empty token
51
+ `),1;let a={};if(o.allowedUsers&&(n.key==="telegram"&&(a.TELEGRAM_ALLOWED_USERS=o.allowedUsers),n.key==="discord"&&(a.DISCORD_ALLOWED_USERS=o.allowedUsers),n.key==="slack"&&(a.SLACK_ALLOWED_USERS=o.allowedUsers)),o.appToken&&n.key==="slack"&&(a.SLACK_APP_TOKEN=o.appToken),n.key==="slack"&&!a.SLACK_APP_TOKEN){let c=o.appToken||s[1]||"";if(!c&&process.stdin.isTTY&&(c=await Nt("slack app token (xapp-...)")),!c)return process.stderr.write(`slack needs bot token + app token
52
+ `),1;a.SLACK_APP_TOKEN=c}try{let c=await Ie(n.key,i).catch(()=>({ok:!1,definitive:!1}));if(!c.ok&&c.definitive)return process.stderr.write(`oracle setup ${n.key}: ${c.error||"platform rejected this token"}
53
+ `),1;let l=_e(e,n.key,i,a);V({lastPlatform:n.key,profile:e,ready:!0});let u=c.ok&&c.username?`bot: ${c.username} (token verified live)
54
+ `:"",y=!c.ok&&c.error?`note: ${c.error}
55
55
  `:"";return process.stdout.write(`saved ${n.key} credentials for profile '${e}'
56
56
  `+u+y+`path: ${l.path}
57
57
  next: oracle setup gateway restart
58
- `),0}catch(a){return process.stderr.write(`oracle setup: ${a.message}
59
- `),1}}var Io={name:"setup",summary:"configure standalone OAuth and messaging platforms",group:"read",usage:Je(),async run(e){let t=[...e.argv],r=t.includes("--json"),n=Qr(t),o=en(t).filter(c=>c!=="--json"),s=(o[0]||"menu").toLowerCase(),i=o.slice(1);if(["-h","--help","help"].includes(s))return process.stdout.write(Je()+`
58
+ `),0}catch(c){return process.stderr.write(`oracle setup: ${c.message}
59
+ `),1}}var Lo={name:"setup",summary:"configure standalone OAuth and messaging platforms",group:"read",usage:Qe(),async run(e){let t=[...e.argv],r=t.includes("--json"),n=Qr(t),o=en(t).filter(a=>a!=="--json"),s=(o[0]||"menu").toLowerCase(),i=o.slice(1);if(["-h","--help","help"].includes(s))return process.stdout.write(Qe()+`
60
60
  `),0;if(["menu","list","ls"].includes(s)){if(r)return process.stdout.write(JSON.stringify({...re(n),modelAuth:U().status()},null,2)+`
61
- `),0;if(process.stdin.isTTY===!0&&process.stdout.isTTY===!0&&!process.env.ORACLE_SETUP_PLAIN){let c=await Lt({profile:n,palette:Ye({color:process.stdout.isTTY!==!1})});return c?.completed===!1&&c?.reason==="non-tty"?1:0}return process.stdout.write(ye()),process.stdout.write(be(n)),0}if(["status","show"].includes(s)){let c=re(n);return r?process.stdout.write(JSON.stringify({...c,modelAuth:U().status()},null,2)+`
62
- `):(process.stdout.write(ye()),process.stdout.write(be(n)),process.stdout.write(`hermes root: ${de()}
63
- `)),0}if(["model","oauth"].includes(s)){let c=String(i[0]||"").trim().toLowerCase();if(!c||["list","status","show"].includes(c))return process.stdout.write(ye()),0;if(Xe.some(a=>a.id===c)||c==="custom")return ue.run({...e,argv:["api-key",c,...i.slice(1)]});try{return W(c),ue.run({...e,argv:["login",c,...i.slice(1)]})}catch(a){return process.stderr.write(`oracle setup model: ${a.message}
64
- `),process.stderr.write(ye()),1}}if(["messaging","gateway-setup","platforms"].includes(s))return V({lastAction:"messaging",profile:n}),process.stdout.write(`opening hermes gateway setup wizard...
65
- `),Qe(["-p",n,"gateway","setup"]);if(s==="gateway"){let c=(i[0]||"status").toLowerCase();return["status","start","stop","restart","run","install"].includes(c)?Qe(["-p",n,"gateway",c]):(process.stderr.write(`usage: oracle setup gateway [status|start|stop|restart|run|install]
66
- `),1)}if(s==="profile"){let c=i[0]||n;return process.stdout.write(`profile: ${c}
67
- hermes: ${de()}/profiles/${c}
68
- `),process.stdout.write(be(c)),0}return G(s)?tn(n,s,i):(process.stderr.write(`oracle setup: unknown verb '${s}'
69
- ${Je()}
70
- `),1)}};export{Ze as SETUP_CHOICES,Io as default,ye as renderModelSetup,Xr as resolveSetupChoice,Po as runFirstRunModelSetup};
61
+ `),0;if(process.stdin.isTTY===!0&&process.stdout.isTTY===!0&&!process.env.ORACLE_SETUP_PLAIN){let a=await Lt({profile:n,palette:Xe({color:process.stdout.isTTY!==!1})});return a?.completed===!1&&a?.reason==="non-tty"?1:0}return process.stdout.write(be()),process.stdout.write(xe(n)),0}if(["status","show"].includes(s)){let a=re(n);return r?process.stdout.write(JSON.stringify({...a,modelAuth:U().status()},null,2)+`
62
+ `):(process.stdout.write(be()),process.stdout.write(xe(n)),process.stdout.write(`hermes root: ${de()}
63
+ `)),0}if(["model","oauth"].includes(s)){let a=String(i[0]||"").trim().toLowerCase();if(!a||["list","status","show"].includes(a))return process.stdout.write(be()),0;if(a==="local"||a==="ollama"){let l=Te({backend:"standalone",provider:a,model:a==="local"?"Qwen3-8B-Q4_K_M":"llama3.2",contextLength:a==="local"?65536:131072});return process.stdout.write(`oracle model: ${l.backend} / ${l.provider} / ${l.model}
64
+ loopback, no API key
65
+ `),0}if(we.some(c=>c.id===a)||a==="custom")return ue.run({...e,argv:["api-key",a,...i.slice(1)]});try{return W(a),ue.run({...e,argv:["login",a,...i.slice(1)]})}catch(c){return process.stderr.write(`oracle setup model: ${c.message}
66
+ `),process.stderr.write(be()),1}}if(["messaging","gateway-setup","platforms"].includes(s))return V({lastAction:"messaging",profile:n}),process.stdout.write(`opening hermes gateway setup wizard...
67
+ `),et(["-p",n,"gateway","setup"]);if(s==="gateway"){let a=(i[0]||"status").toLowerCase();return["status","start","stop","restart","run","install"].includes(a)?et(["-p",n,"gateway",a]):(process.stderr.write(`usage: oracle setup gateway [status|start|stop|restart|run|install]
68
+ `),1)}if(s==="profile"){let a=i[0]||n;return process.stdout.write(`profile: ${a}
69
+ hermes: ${de()}/profiles/${a}
70
+ `),process.stdout.write(xe(a)),0}return G(s)?tn(n,s,i):(process.stderr.write(`oracle setup: unknown verb '${s}'
71
+ ${Qe()}
72
+ `),1)}};export{Ce as SETUP_CHOICES,Lo as default,be as renderModelSetup,Xr as resolveSetupChoice,Io as runFirstRunModelSetup};
@@ -0,0 +1,20 @@
1
+ import{createHash as be,randomBytes as ke}from"node:crypto";import{mkdirSync as ye,readFileSync as $e,writeFileSync as xe}from"node:fs";import{homedir as we}from"node:os";import{dirname as Se,join as H}from"node:path";var ee={robinhood:{chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC"],evm:!0},ethereum:{chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],evm:!0},polygon:{chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],evm:!0},arbitrum:{chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],evm:!0},base:{chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],evm:!0},hyperevm:{chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],evm:!0},bsc:{chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],evm:!0},avalanche:{chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],evm:!0},optimism:{chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],evm:!0},abstract:{chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],evm:!0},stable:{chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],evm:!0}},te=new Map(Object.values(ee).map(t=>[t.chainId,t]));function U(t){return te.get(Number(t))||null}var c="UNKNOWN",ve=Object.freeze(["token","launch","hip3","hip4","polymarket","twap","bridge","swap","approve"]),re=/[_*[\]`]/g;function n(t){return u(t)?String(t).replace(re,e=>`\\${e}`):c}function u(t){return t==null?!1:typeof t=="number"?Number.isFinite(t):typeof t=="string"?t.trim()!=="":!0}function m(t){if(!u(t))return c;let e=String(t).replace(/`/g,"");return e===""?c:`\`${e}\``}function $(t,{decimals:e=2}={}){if(!u(t))return c;let r=Number(t);return Number.isFinite(r)?r.toLocaleString("en-US",{minimumFractionDigits:0,maximumFractionDigits:e}):c}function p(t,{decimals:e=2}={}){let r=$(t,{decimals:e});return r===c?c:`${r} USD`}function E(t,{decimals:e=2}={}){let r=$(t,{decimals:e});return r===c?c:`${r}%`}function _(t){let e=$(t,{decimals:0});return e===c?c:`${e} bps`}function x(t,e){if(!u(t))return c;let r=Number(e);if(!Number.isInteger(r)||r<0||r>77)return c;let i;try{i=BigInt(typeof t=="string"?t.trim():t)}catch{return c}let a=i<0n,s=a?-i:i,o=10n**BigInt(r),l=(s/o).toString(),d=(s%o).toString().padStart(r,"0").replace(/0+$/,"");return`${a?"-":""}${l}${d?`.${d}`:""}`}function N(t){if(typeof t=="number"&&Number.isFinite(t))return t<0||t>1?c:t>=.75?"HIGH":t>=.4?"MEDIUM":"LOW";if(typeof t=="string"){let e=t.trim().toUpperCase();if(e==="HIGH"||e==="MEDIUM"||e==="LOW")return e}return c}function k(t={}){let e=t.chainId;if(!u(e)||!Number.isFinite(Number(e)))return u(t.chain)?n(t.chain):c;let i=U(e)?.name||(u(t.chain)?String(t.chain):c);return`${n(i)} (chainId ${Number(e)})`}function D(t={}){return n(t.venue??t.dex??t.pool?.venue)}function ne(t){return t==null?"NONE (text card only)":typeof t=="string"?t.trim()?m(t):"NONE (text card only)":t.error||t.ok===!1||t.available===!1?`UNAVAILABLE${u(t.error)?` \u2014 ${n(t.error)}`:""} (text card stands)`:u(t.url)?m(t.url):"NONE (text card only)"}function C(t={},{now:e=Date.now()}={}){let r=t.grant??t.session??null;if(!r||typeof r!="object")return{allowed:!1,reason:"no local grant/session",actions:[]};if(r.local===!1)return{allowed:!1,reason:"grant is not local",actions:[]};if(r.revoked===!0)return{allowed:!1,reason:"grant revoked",actions:[]};let i=r.expiresAt??r.expiry;if(u(i)){let s=typeof i=="number"?i:Date.parse(i);if(!Number.isFinite(s))return{allowed:!1,reason:"grant expiry unreadable",actions:[]};if(s<=e)return{allowed:!1,reason:"grant expired",actions:[]}}return{allowed:!0,reason:"valid local grant",actions:Array.isArray(r.actions)&&r.actions.length?r.actions.slice():["BUY","SELL"]}}function ie(t){let e=C(t);return e.allowed?`${e.actions.map(r=>n(r)).join(" / ")} (${n(e.reason)})`:`prepare-only \u2014 ${n(e.reason)}`}function g(t,e,r={}){let i=[`*${t}*`];for(let[a,s]of e)i.push(`${a}: ${s==null||s===""?c:s}`);return i.push(`Chart: ${ne(r.chart)}`),i.push(`Actions: ${ie(r)}`),Array.isArray(r.warnings)&&r.warnings.length&&i.push(`Warnings: ${r.warnings.map(a=>n(a)).join("; ")}`),(u(r.source)||u(r.fetchedAt))&&i.push(`Source: ${n(r.source)} at ${n(r.fetchedAt)}`),i.join(`
2
+ `)}function b(t){return["Confidence",N(t.confidence)]}function oe(t){let e=t.quote;if(!e||typeof e!="object")return[];let r=u(e.decimals)?x(e.amountOutRaw??e.out??e.raw,e.decimals):c;return[["Quote out (raw)",m(e.amountOutRaw??e.out??e.raw)],["Quote out",r===c?c:`${n(r)} ${n(e.symbol??"")}`.trim()]]}function M(t){let e=t.autoSlippage;if(!e||typeof e!="object")return["Auto-slippage",c];let r=_(e.selectedBps),i=_(e.capBps);return["Auto-slippage",r===c&&i===c?c:`${r} selected, cap ${i}`]}function ae(t={}){let e=t||{};return g(`ORACLE TOKEN \u2014 ${n(e.symbol??e.token??e.name)}`,[["Chain",k(e)],["Venue",D(e)],["Name",n(e.name)],["Address",m(e.address??e.mint??e.contract)],["Price",p(e.priceUsd,{decimals:8})],["Market cap",p(e.marketCapUsd)],["Liquidity",p(e.liquidityUsd)],["Volume 24h",p(e.volume24hUsd)],["Change 24h",E(e.priceChange24h)],["Fee tier",u(e.feeTier)?`${_(Number(e.feeTier)/100)} (${$(e.feeTier,{decimals:0})})`:c],["Age",n(e.age)],...oe(e),M(e),b(e)],e)}function se(t={}){let e=t||{};return g(`ORACLE LAUNCH \u2014 ${n(e.symbol??e.token??e.name)}`,[["Chain",k(e)],["Venue",D(e)],["Address",m(e.address??e.mint??e.contract)],["Pool",m(e.pool?.address??e.poolAddress??e.pool)],["Liquidity",p(e.liquidityUsd)],["Route ready",n(e.routeReady)],["Sellable",n(e.sellable)],["Sell sim",n(e.sellSimulation??e.sellSim)],["Smart wallets",n(e.smartWalletOverlap)],["Risk",n(e.risk??e.riskStatus)],["Prepared ticket",n(e.preparedTicket??e.ticketStatus)],M(e),b(e)],e)}function ce(t={}){let e=t||{};return g(`ORACLE HIP-3 \u2014 ${n(e.market??e.coin??e.name)}`,[["Venue",`Hyperliquid builder-dex ${n(e.dex)}`],["Market",n(e.market??e.coin)],["Mark",p(e.markPx,{decimals:6})],["Oracle",p(e.oraclePx,{decimals:6})],["Funding",E(e.funding,{decimals:6})],["Open interest",p(e.openInterestUsd)],["Depth",n(e.depth)],["Liquidation notes",n(e.liquidationNotes??e.riskNotes)],["Account context",n(e.accountContext)],b(e)],e)}function le(t={}){let e=t||{};return g(`ORACLE HIP-4 \u2014 ${n(e.event??e.market??e.name)}`,[["Venue",`Hyperliquid HIP-4 ${n(e.dex??"outcome")}`],["Event",n(e.event)],["Outcome",n(e.outcome)],["Market id",m(e.marketId??e.market)],["Bid",p(e.bid,{decimals:6})],["Ask",p(e.ask,{decimals:6})],["Depth",n(e.depth)],["Edge",E(e.edge)],["Position",n(e.position)],b(e)],e)}function ue(t={}){let e=t||{};return g(`ORACLE POLYMARKET \u2014 ${n(e.event??e.market??e.name)}`,[["Venue","Polymarket CLOB"],["Event",n(e.event)],["Market",n(e.market)],["Market id",m(e.marketId??e.conditionId??e.tokenId)],["Yes",p(e.yesPrice,{decimals:4})],["No",p(e.noPrice,{decimals:4})],["Best bid / ask",`${p(e.bestBid,{decimals:4})} / ${p(e.bestAsk,{decimals:4})}`],["Volume",p(e.volumeUsd)],["Resolution risk",n(e.resolutionRisk)],["Order intent",n(e.orderIntent)],b(e)],e)}function de(t={}){let e=t||{},r=u(e.completedSplits)&&u(e.totalSplits)?`${$(e.completedSplits,{decimals:0})} / ${$(e.totalSplits,{decimals:0})}`:c;return g(`ORACLE TWAP \u2014 ${n(e.pair??e.symbol??e.name)}`,[["Chain",k(e)],["Side",n(e.side??e.direction)],["Amount",`${n(x(e.amountTotal??e.amount,e.decimals??18))} ${n(e.symbol??"")}`.trim()],["Splits",`${$(e.totalSplits,{decimals:0})} over ${n(e.window)}`],["Progress",r],["Avg price",p(e.averagePrice,{decimals:6})],["Next split",n(e.nextSplitAt)],["Slippage cap",_(e.slippageBps)],["Status",n(e.status)],b(e)],e)}function pe(t={}){let e=t||{},r=e.approval??e.revokeCheck??{},i=r.needsRevoke&&r.spender?`revoke.cash \u2014 ${n(r.spender)}`:r.needsRevoke===!1?"revoke.cash \u2014 clean":"revoke.cash \u2014 unchecked";return g(`ORACLE BRIDGE \u2014 ${n(e.pair??e.fromSymbol)} \u2192 ${n(e.toSymbol??"")}`.replace(/→ $/,""),[["Bridging","deBridge \xB7 LI.FI \u2014 best route wins"],["From chain",k({chainId:e.fromChainId,chain:e.fromChain})],["To chain",k({chainId:e.toChainId,chain:e.toChain})],["Amount",`${n(x(e.amount,e.fromDecimals??18))} ${n(e.fromSymbol??"")}`.trim()],["Best route",n(e.bestRoute??e.winner)],["Est. received",`${n(x(e.amountOut,e.toDecimals??18))} ${n(e.toSymbol??"")}`.trim()],["Fee",p(e.feeUsd)],["Est. time",n(e.estimatedTime)],["Revoke check",i],["All providers",n(e.providers?.join(", "))],["Preparable",n(e.preparable)],b(e)],e)}function fe(t){let r=(Array.isArray(t)?t:[]).slice(1,4).map(i=>{let a=n(i.source??i.venue??i.name),s=i.improvementBps==null&&i.deltaBps==null?null:Number(i.improvementBps??i.deltaBps),o=Number.isFinite(s)?`${Math.abs(s).toFixed(0)} bps behind`:"spread UNKNOWN";return`${a} (${o})`});return r.length?r.join("; "):c}function me(t){let e=t.rankedOn??t.swap?.rankedOn??t.best?.rankedOn;return u(e)?n(e):c}function he(t={}){let e=t||{},r=e.swap&&typeof e.swap=="object"?e.swap:e,i=e.bridge&&typeof e.bridge=="object"?e.bridge:null,a=r.best??r.winner??{},s=`${n(e.tokenInSymbol??e.fromSymbol??"IN")} \u2192 ${n(e.tokenOutSymbol??e.toSymbol??"OUT")}`,o=[["Intent",n(e.intent??"swap")],["Chain",k({chainId:e.chainId??r.chainId,chain:e.chain??r.chain})],["Pair",s],["Amount in",`${n(x(e.amountIn??r.amountIn,e.decimalsIn??18))} ${n(e.tokenInSymbol??"")}`.trim()],["Best swap",n(a.source??a.venue??r.bestRoute??e.bestRoute)],["Net out",`${n(x(a.netOut??a.amountOut??r.amountOut,e.decimalsOut??18))} ${n(e.tokenOutSymbol??"")}`.trim()],["Ranked on",me(r)],["Gas accounted",n(a.costAccounted===!0?"yes":a.costAccounted===!1?"no \u2014 gross ranking may flatter this route":null)],["Spread vs next",u(r.improvementBps)?`${n(r.improvementBps)} bps`:c],["Runners-up",fe(r.routes??e.routes)]];if(i){let l=i.best??i.winner??{};o.push(["Best bridge",n(l.source??i.bestRoute??e.bestBridge)],["Bridge out",`${n(x(l.netOut??l.amountOut??i.amountOut,e.bridgeDecimalsOut??e.decimalsOut??18))} ${n(e.bridgeOutSymbol??e.tokenOutSymbol??"")}`.trim()],["Bridge to",k({chainId:i.toChainId??e.toChainId,chain:i.toChain??e.toChain})],["Est. time",n(i.estimatedTime??l.meta?.durationSeconds)])}else o.push(["Best bridge","same-chain \u2014 use Best swap"]);return o.push(["Preparable",n(e.preparable??a.executionReady)],b(e)),g(`ORACLE SWAP \u2014 ${s}`,o,e)}function ge(t={}){let e=t||{};return g("ORACLE APPROVE \u2014 local signer",[["Pending id",m(e.id??(typeof e.digest=="string"?e.digest.slice(0,8):null))],["Surface",n(e.surface)],["Action",n(e.action)],["Chain",k({chainId:e.chain??e.chainId,chain:e.chainName})],["To",m(e.to??e.destination)],["Value",u(e.value)?n(e.value):c],["Signer",n(e.armed===!0?"running + armed":e.armed===!1?"running, disarmed":"not running")],b({confidence:e.confidence??(e.armed===!0?"high":"low")})],e)}var Le=Object.freeze({token:ae,launch:se,hip3:ce,hip4:le,polymarket:ue,twap:de,bridge:pe,swap:he,approve:ge});var Ce=Object.freeze(["deepen","refresh","prepare"]),Ae=new Set(Ce),v=/^[a-z0-9-]{4,40}$/i,j=/^[0-9a-f]{32}$/,F=/^\d+$/;function L(t=process.env){return H(t.ORACLE_CONFIG_DIR||H(we(),".config","oracle"),"telegram-cards.json")}function w(){return{links:{},artifacts:{},threads:{}}}var A=w();function P(){return A}function q(t,{readFile:e=$e}={}){try{let r=JSON.parse(String(e(t)));A={links:r.links&&typeof r.links=="object"?r.links:{},artifacts:r.artifacts&&typeof r.artifacts=="object"?r.artifacts:{},threads:r.threads&&typeof r.threads=="object"?r.threads:{}}}catch{A=w()}return A}function V(t,e=A,{writeFile:r=xe,mkdir:i=ye}={}){i(Se(t),{recursive:!0,mode:448}),r(t,JSON.stringify(e),{mode:384})}function y(t){return t==null?!1:typeof t=="string"?t.trim()!=="":!0}function W(t){return be("sha256").update(String(t)).digest("hex")}function O(t){if(Array.isArray(t))return t.map(O);if(!t||typeof t!="object")return t;let e={};for(let[r,i]of Object.entries(t))/(secret|token|key|seed|private|password|mnemonic|auth)/i.test(r)||(e[r]=O(i));return e}function Re(t){let r=String(t||"").trim().match(/^oracle:card:(deepen|refresh|prepare):([a-z0-9-]{4,40})$/i);return r?{action:r[1].toLowerCase(),artifactId:r[2].toLowerCase()}:null}function K({platform:t="telegram",artifactId:e,openUrl:r,hasGrant:i=!1}={}){let a=String(e||"").trim().toLowerCase();if(!v.test(a))return{kind:"text_menu",text:"no artifact to continue",cancelHint:""};let s=[];y(r)&&s.push({text:"Open",url:String(r)});let o=[{text:"Deepen",callback_data:`oracle:card:deepen:${a}`},{text:"Refresh",callback_data:`oracle:card:refresh:${a}`}];if(i&&o.push({text:"Prepare",callback_data:`oracle:card:prepare:${a}`}),String(t)==="telegram")return{kind:"inline_keyboard",replyMarkup:{inline_keyboard:[s,o].filter(h=>h.length>0)},cancelHint:i?"Prepare queues an unsigned artifact. Allow/Deny still required to sign.":"prepare-only \u2014 Deepen and Refresh stay read-only."};let l=[],d=0;for(let h of[...s,...o])d+=1,l.push(h.url?`${d}. ${h.text}: ${h.url}`:`${d}. ${h.text} (reply ${d})`);return{kind:"text_menu",text:l.join(`
3
+ `),cancelHint:""}}function Y(t={}){let r=[`*${y(t.title)?n(t.title):"Oracle artifact"}*`,`Kind: ${y(t.kind)?n(t.kind):c}`,`Id: ${y(t.id)?`\`${String(t.id).replace(/`/g,"")}\``:c}`,`Summary: ${y(t.summary)?n(t.summary):c}`,`Confidence: ${N(t.confidence)}`];(y(t.source)||y(t.fetchedAt))&&r.push(`Source: ${n(t.source)} at ${n(t.fetchedAt)}`),Array.isArray(t.warnings)&&t.warnings.length&&r.push(`Warnings: ${t.warnings.map(a=>n(a)).join("; ")}`);let i=C(t);return r.push(i.allowed?"Actions: Deepen / Refresh / Prepare (unsigned)":`Actions: Deepen / Refresh \u2014 ${n(i.reason)}`),r.join(`
4
+ `)}function _e(t,e={},{now:r=Date.now()}={}){let i=t||w(),a=String(e.id||"").trim().toLowerCase();if(!v.test(a))throw new TypeError("artifact id required");let s={id:a,kind:String(e.kind||"thesis"),title:String(e.title||"Oracle artifact"),summary:String(e.summary||""),openUrl:y(e.openUrl)?String(e.openUrl):null,confidence:e.confidence,source:e.source||"oracle",fetchedAt:e.fetchedAt||new Date(r).toISOString(),warnings:Array.isArray(e.warnings)?e.warnings.map(String):[],payload:O(e.payload||{}),createdAt:new Date(r).toISOString()};return i.artifacts[a]=s,s}function B(t,{chatId:e,artifactId:r,now:i=Date.now()}={}){let a=t||w(),s=String(e||"").trim(),o=String(r||"").trim().toLowerCase();if(!s)throw new TypeError("chat id required");if(!v.test(o))throw new TypeError("artifact id required");return a.threads[s]={artifactId:o,updatedAt:i},a.threads[s]}function z(t,{chatId:e,text:r}={}){let i=String(e||"").trim(),a=String(r||"").trim();if(!i||!a||/^\//.test(a))return null;let s=t?.threads?.[i];if(!s?.artifactId)return null;let o=t.artifacts?.[s.artifactId];return o?`Continue artifact ${o.id} (${o.kind}). Prior: ${o.summary||o.title}. User: ${a}`:null}function J(t,{ownerId:e,botUsername:r,now:i=Date.now(),ttlMs:a=600*1e3,token:s,randomBytes:o=ke}={}){let l=t||w(),d=String(e||"").trim(),h=String(r||"").replace(/^@/,"").trim();if(!F.test(d))throw new TypeError("owner Telegram id required");if(!/^[A-Za-z0-9_]{5,32}$/.test(h))throw new TypeError("bot username required");let R=s||o(16).toString("hex");if(!j.test(R))throw new TypeError("link token must be 32 hex chars");return l.links[W(R)]={ownerId:d,expiresAt:i+Number(a)},{token:R,url:`https://t.me/${h}?start=${R}`,expiresAt:i+Number(a)}}function Q(t,{token:e,telegramUserId:r,now:i=Date.now()}={}){let a=t||w(),s=String(e||"").trim(),o=String(r||"").trim();if(!j.test(s))return{ok:!1,error:"invalid start token"};if(!F.test(o))return{ok:!1,error:"invalid telegram user"};let l=W(s),d=a.links[l];return d?(delete a.links[l],Number(d.expiresAt)<=i?{ok:!1,error:"start token expired"}:String(d.ownerId)!==o?{ok:!1,error:"start token is bound to a different owner"}:{ok:!0,ownerId:o}):{ok:!1,error:"unknown or already used start token"}}function G(t,{data:e,chatId:r,grant:i=null,now:a=Date.now()}={}){let s=Re(e);if(!s)return null;if(!Ae.has(s.action))return{text:"That card action is not available.",buttons:null};let o=t?.artifacts?.[s.artifactId];if(!o)return{text:"That artifact is gone. Ask again and I will issue a new card.",buttons:null};r&&B(t,{chatId:r,artifactId:o.id,now:a});let l=C({grant:i},{now:a}),d=K({artifactId:o.id,openUrl:o.openUrl,hasGrant:l.allowed});return s.action==="refresh"?{text:Y(o),buttons:d,prompt:null}:s.action==="deepen"?{text:null,buttons:null,prompt:`Deepen artifact ${o.id} (${o.kind}). Prior: ${o.summary||o.title}. Be terse. Do not sign or broadcast.`}:l.allowed?{text:`Queued unsigned prepare for ${o.id}. Nothing signed. Allow/Deny still required.`,buttons:d,prompt:null,prepare:{artifactId:o.id,unsigned:!0,broadcast:!1}}:{text:`Prepare blocked \u2014 ${l.reason}. Deepen and Refresh still work.`,buttons:d,prompt:null}}function X(t={},{grant:e=null,now:r=Date.now(),state:i}={}){let a=i||P(),s=String(t.id||`art-${Math.abs(Number(r)).toString(36)}`).toLowerCase().slice(0,40),o=_e(a,{...t,id:s},{now:r}),l=C({grant:e},{now:r});return{text:Y({...o,grant:e}),replyMarkup:K({artifactId:o.id,openUrl:o.openUrl,hasGrant:l.allowed}).replyMarkup,artifact:o,state:a}}var T=`oracle telegram \u2014 TrueNorth-style interactive cards (native, no Hermes)
5
+
6
+ oracle telegram link --owner <tg-id> --bot <username>
7
+ oracle telegram redeem --token <32hex> --user <tg-id>
8
+ oracle telegram wrap --id <id> --title <t> --summary <s> [--kind thesis] [--grant]
9
+ oracle telegram callback --data oracle:card:<action>:<id> --chat <tg-id> [--grant]
10
+ oracle telegram continue --chat <tg-id> --text <message>
11
+
12
+ Native oracle-gateway uses the same module. Hermes is an optional adapter that
13
+ must call this CLI instead of owning card state. Prepare is unsigned. Execute
14
+ stays on Allow/Deny.`;function f(t,e){let r=t.indexOf(e);return r<0||r+1>=t.length?null:t[r+1]}function Z(t,e){return t.includes(e)}function Ie(){return q(L()),P()}function I(t){V(L(),t)}function S(t,e){t.write(JSON.stringify(e)+`
15
+ `)}async function Ee(t=[],e={}){let r=e.out??process.stdout,i=e.err??process.stderr,a=t[0];if(!a||a==="--help"||a==="-h"||a==="help")return r.write(T+`
16
+ `),0;let s=Ie();if(a==="link")try{let o=J(s,{ownerId:f(t,"--owner"),botUsername:f(t,"--bot")});return I(s),S(r,{ok:!0,...o}),0}catch(o){return i.write(String(o.message||o)+`
17
+ `),1}if(a==="redeem"){let o=Q(s,{token:f(t,"--token"),telegramUserId:f(t,"--user")});return I(s),S(r,o),o.ok?0:1}if(a==="wrap")try{let o=X({id:f(t,"--id"),kind:f(t,"--kind")||"thesis",title:f(t,"--title")||"Oracle artifact",summary:f(t,"--summary")||"",openUrl:f(t,"--url"),source:"oracle-telegram"},{grant:Z(t,"--grant")?{local:!0}:null,state:s}),l=f(t,"--chat");return l&&B(s,{chatId:l,artifactId:o.artifact.id}),I(s),S(r,{ok:!0,text:o.text,replyMarkup:o.replyMarkup||null,artifactId:o.artifact.id,fallback:`Reply: deepen ${o.artifact.id} | refresh ${o.artifact.id}`}),0}catch(o){return i.write(String(o.message||o)+`
18
+ `),1}if(a==="callback"){let o=G(s,{data:f(t,"--data"),chatId:f(t,"--chat"),grant:Z(t,"--grant")?{local:!0}:null});return I(s),o?(S(r,{ok:!0,...o}),0):(S(r,{ok:!1,error:"not an interactive card callback"}),1)}if(a==="continue"){let o=z(s,{chatId:f(t,"--chat"),text:f(t,"--text")});return S(r,{ok:!0,prompt:o}),0}return i.write(`unknown telegram verb '${a}'
19
+ ${T}
20
+ `),1}var Fe={name:"telegram",summary:"native interactive Telegram cards (TrueNorth-style, no Hermes)",group:"system",usage:T,run:t=>Ee(t.argv||[])};export{Fe as default,Ee as run};