@oracle-agent/oracle 0.28.1 → 0.28.3

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,55 +1,57 @@
1
- import{spawnSync as Pt}from"node:child_process";import{stdin as b,stdout as Te}from"node:process";var ee=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 me(e){return String(e||"").trim().toLowerCase().replace(/^\/+/,"").replace(/\s+/g,"-")}function H(){return ee.slice()}function D(e){let t=me(e);if(!t)return null;for(let r of ee)if(r.key===t||me(r.name)===t)return r;return null}function we({profile:e="oracle",statuses:t={}}={}){let r=["oracle setup","","one oracle. many models. every connected channel.",`profile: ${e}`,"","messaging platforms:",""];for(let o of ee){let n=t[o.key]||"unset";r.push(` ${o.key.padEnd(16)} ${String(n).padEnd(8)} ${o.note}`)}return r.push(""),r.push("commands:"),r.push(" oracle setup this menu"),r.push(" oracle setup messaging open hermes gateway setup"),r.push(" oracle setup telegram configure telegram bot token"),r.push(" oracle setup discord configure discord bot token"),r.push(" oracle setup status show configured platforms (no secrets)"),r.push(" oracle setup gateway start/status hermes gateway"),r.push(" /setup same menu inside chat"),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(" after setup: hermes -p oracle gateway restart"),r.join(`
1
+ import{spawnSync as Lt}from"node:child_process";import{stdin as b,stdout as Ie}from"node:process";var te=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 ye(e){return String(e||"").trim().toLowerCase().replace(/^\/+/,"").replace(/\s+/g,"-")}function H(){return te.slice()}function j(e){let t=ye(e);if(!t)return null;for(let r of te)if(r.key===t||ye(r.name)===t)return r;return null}function ke({profile:e="oracle",statuses:t={}}={}){let r=["oracle setup","","one oracle. many models. every connected channel.",`profile: ${e}`,"","messaging platforms:",""];for(let o of te){let n=t[o.key]||"unset";r.push(` ${o.key.padEnd(16)} ${String(n).padEnd(8)} ${o.note}`)}return r.push(""),r.push("commands:"),r.push(" oracle setup this menu"),r.push(" oracle setup messaging open hermes gateway setup"),r.push(" oracle setup telegram configure telegram bot token"),r.push(" oracle setup discord configure discord bot token"),r.push(" oracle setup status show configured platforms (no secrets)"),r.push(" oracle setup gateway start/status hermes gateway"),r.push(" /setup same menu inside chat"),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(" after setup: hermes -p oracle gateway restart"),r.join(`
2
2
  `)+`
3
- `}import x from"node:fs";import Be from"node:os";import te from"node:path";import N from"node:fs";import Me from"node:os";import _ from"node:path";import{fileURLToPath as Ke}from"node:url";var Fe=_.dirname(Ke(import.meta.url)),Dt=_.resolve(Fe,"../..");function z(){return process.env.ORACLE_FAKE_HOME||Me.homedir()}function He(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function S(){return He()?process.env.ORACLE_CONFIG_DIR||_.join(z(),".config","oracle"):_.join(z(),".config","oracle")}function ze(){return _.join(S(),"desk.json")}function qe(){return _.join(S(),"env")}function $({force:e=!1}={}){if($._done&&!e)return $._result||null;$._done=!0;let t={},r=(n,s)=>{if(s==null)return;let i=String(s).trim();i&&(process.env[n]!=null&&String(process.env[n]).trim()!==""||(process.env[n]=i,t[n]=i))};try{let n=qe();if(N.existsSync(n))for(let s of N.readFileSync(n,"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 n=ze();if(N.existsSync(n)){let s=JSON.parse(N.readFileSync(n,"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 o=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return o&&(r("ORACLE_DESK_URL",o),r("ORACLE_DATA_URL",o),r("ORACLE_API_URL",o),r("ORACLE_PUBLIC_URL",o),r("MAD_DESK_URL",o)),$._result=Object.keys(t).length?t:null,$._result}try{$()}catch{}function M(){return process.env.HERMES_HOME?_.resolve(process.env.HERMES_HOME):_.join(z(),".hermes")}function A(e){return N.mkdirSync(e,{recursive:!0}),e}var We=/(TOKEN|SECRET|PASSWORD|KEY|AUTH|PRIVATE|MNEMONIC|SEED)/i;function q(e="oracle"){return te.join(M(),"profiles",e,".env")}function Ve(e){let t={};for(let r of String(e||"").split(/\r?\n/)){let o=r.trim();if(!o||o.startsWith("#"))continue;let n=o.indexOf("=");if(n<=0)continue;let s=o.slice(0,n).trim(),i=o.slice(n+1).trim();(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),t[s]=i}return t}function ye(e="oracle"){let t=q(e);return x.existsSync(t)?Ve(x.readFileSync(t,"utf8")):{}}function ge(e,t,r){if(!t||We.test(t)===!1&&/[^A-Z0-9_]/.test(t),!/^[A-Z][A-Z0-9_]*$/.test(t)){let d=new Error(`invalid env key '${t}'`);throw d.code="BAD_KEY",d}if(r==null||String(r).trim()===""){let d=new Error(`empty value for ${t}`);throw d.code="EMPTY",d}let o=q(e);A(te.dirname(o));let n=x.existsSync(o)?x.readFileSync(o,"utf8"):"",s=n?n.split(/\r?\n/):[],i=[],c=!1,a=`${t}=${String(r)}`;for(let d of s)d.startsWith(`${t}=`)?(i.push(a),c=!0):(d.length||i.length)&&i.push(d);for(c||(i.length&&i[i.length-1]!==""&&i.push(""),i.push(a));i.length&&i[i.length-1]==="";)i.pop();i.push(""),x.writeFileSync(o,i.join(`
4
- `),{mode:384});try{x.chmodSync(o,384)}catch{}return{path:o,key:t,set:!0}}function B(e="oracle"){let t=ye(e),r={};for(let o of H()){if(!o.required.length){r[o.key]="manual";continue}let n=o.required.filter(s=>!String(t[s]||"").trim());r[o.key]=n.length?"unset":"ready"}return{profile:e,statuses:r,envPath:q(e)}}function W(e="oracle"){let{statuses:t}=B(e);return we({profile:e,statuses:t})}function ve(e,t,r,o={}){let n=D(t);if(!n){let p=new Error(`unknown platform '${t}'`);throw p.code="UNKNOWN_PLATFORM",p}if(!n.required.length){let p=new Error(`${n.key} uses hermes interactive setup (oracle setup messaging)`);throw p.code="NEEDS_INTERACTIVE",p}let i=n.required.filter(p=>/(TOKEN|PASSWORD|SECRET)$/i.test(p))[0]||(n.required.length===1?n.required[0]:null);if(!i){let p=new Error(`${n.key} has no single token field; provide each of [${n.required.join(", ")}] explicitly`);throw p.code="NEEDS_EXPLICIT_KEYS",p}let c=new Set([i,...Object.keys(o||{}).filter(p=>o[p]!=null&&String(o[p]).trim())]),a=ye(e),d=n.required.filter(p=>!c.has(p)&&!String(a[p]||"").trim());if(d.length){let p=new Error(`${n.key} also requires [${d.join(", ")}]; pass them explicitly (setup would otherwise be marked ready while unusable)`);throw p.code="MISSING_REQUIRED",p}ge(e,i,r);for(let[p,v]of Object.entries(o||{}))v!=null&&String(v).trim()&&ge(e,p,v);return{platform:n.key,set:n.required,profile:e,path:q(e)}}function Je(){return te.join(S(),"setup-state.json")}function V(e={}){A(S());let t=Je(),r={};if(x.existsSync(t))try{r=JSON.parse(x.readFileSync(t,"utf8"))}catch{r={}}let o={...r,...e,updatedAt:new Date().toISOString(),host:Be.hostname()};return x.writeFileSync(t,JSON.stringify(o,null,2)+`
5
- `,{mode:384}),o}import Se from"node:fs";import L from"node:path";var Ye="0.19.0",Jt=`hermes-agent==${Ye}`;var ke="0.12.1",Yt=Object.freeze({posix:Object.freeze({url:`https://github.com/astral-sh/uv/releases/download/${ke}/uv-installer.sh`,sha256:"d3f5412d38c99f9d024901843bf98206f0d2c6dbe64df40d0b740e2751ca62c1"}),windows:Object.freeze({url:`https://github.com/astral-sh/uv/releases/download/${ke}/uv-installer.ps1`,sha256:"b9ec035151bfbb11d616dbd69886498d885551489eddf095ea3c0ad59f640eb0"})});function Ge(){return L.join(S(),"runtime")}function Xe(){return L.join(Ge(),"venv")}function Ze(e){let t=process.platform==="win32"?"Scripts":"bin",r=process.platform==="win32"?`${e}.exe`:e;return L.join(Xe(),t,r)}function Qe(){return Ze("hermes")}function et(e){let t=process.platform==="win32"&&!L.extname(e)?["",".exe",".cmd",".bat"]:[""];for(let r of(process.env.PATH||"").split(L.delimiter))if(r)for(let o of t){let n=L.join(r,`${e}${o}`);try{if(Se.existsSync(n))return n}catch{}}return null}function xe(){if(process.env.ORACLE_HERMES_BIN)return{ok:!0,bin:process.env.ORACLE_HERMES_BIN,source:"env"};let e=Qe();if(Se.existsSync(e))return{ok:!0,bin:e,source:"managed"};let t=et("hermes");return t?{ok:!0,bin:t,source:"path"}:{ok:!1,bin:null,source:null}}import{createHash as tt,randomBytes as ne,timingSafeEqual as rt}from"node:crypto";import y from"node:fs";import E from"node:path";import ot from"node:readline/promises";import{spawn as nt,spawnSync as st}from"node:child_process";var C=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"}}),it=12e4;function at(e={}){return typeof e.now=="function"?Number(e.now()):Date.now()}function P(e){let t=String(e||"").trim().toLowerCase();for(let[r,o]of Object.entries(C))if(o.aliases.includes(t))return r;throw new Error(`unsupported OAuth provider: ${e||"(empty)"}`)}function K(e){let t=P(e);return{id:t,...C[t]}}function g(e,t={}){if(!y.existsSync(e))return t;try{let r=JSON.parse(y.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: ${E.basename(e)}`)}}function _e(e){A(e),process.platform!=="win32"&&y.chmodSync(e,448)}function O(e,t){_e(E.dirname(e));let r=`${e}.${process.pid}.${ne(4).toString("hex")}.tmp`;y.writeFileSync(r,`${JSON.stringify(t,null,2)}
6
- `,{mode:384}),y.renameSync(r,e),process.platform!=="win32"&&y.chmodSync(e,384)}function ct(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 re(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 I(e={}){let t=String(e.accessToken||e.access_token||"").trim(),r=String(e.refreshToken||e.refresh_token||"").trim(),o=Number(e.expiresAt||e.expires_at||0);if(Number.isFinite(o)&&o>=1e9&&o<1e12&&(o=o*1e3),!t)throw new Error("OAuth credential is missing access token");return{accessToken:t,refreshToken:r,expiresAt:Number.isFinite(o)?o: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 ut(e={}){let t=e.file||E.join(S(),"oauth.json"),r=e.metadataFile||E.join(E.dirname(t),"oauth-meta.json"),o=e.linksFile||E.join(E.dirname(t),"oauth-links.json"),n=()=>typeof e.now=="function"?Number(e.now()):Date.now(),s=e.spawnFn||st,i=e.keychain!==!1&&process.env.ORACLE_AUTH_FILE_STORE!=="1"&&ct(s),c=i?"linux-secret-service":"private-file",a=`${t}.lock`;async function d(m){_e(E.dirname(a));let h;for(let u=0;u<400;u+=1)try{h=y.openSync(a,"wx",384);break}catch(l){if(l?.code!=="EEXIST")throw l;try{Date.now()-y.statSync(a).mtimeMs>3e5&&y.unlinkSync(a)}catch{}await new Promise(f=>setTimeout(f,25))}if(h===void 0)throw new Error("timed out waiting for OAuth credential lock");try{return await m()}finally{try{y.closeSync(h)}catch{}try{y.unlinkSync(a)}catch{}}}function p(m,h="oauth"){return["application","oracle","kind",h,"provider",m]}function v(m){if(!y.existsSync(o))return null;let u=g(o,{providers:{}}).providers?.[m];if(!Array.isArray(u))return null;let l=[];for(let f of u)if(E.isAbsolute(String(f||"")))try{let w=g(f,{});if(m==="anthropic-oauth"&&w.claudeAiOauth){let R=I(w.claudeAiOauth);l.push({...R,refreshToken:"",source:"external-access-only"});continue}let k=w.credential_pool&&typeof w.credential_pool=="object"?w.credential_pool:null;if(k){let R=k[m]||k[m.replace(/-oauth$/,"")]||[],De=Array.isArray(R)?R:R?[R]:[];for(let Q of De)if(!(!Q||typeof Q!="object"))try{let Ne=I(Q);l.push({...Ne,refreshToken:"",source:"external-access-only"})}catch{}}}catch{}return l.length?l.find(f=>!f.expiresAt||f.expiresAt>n()+it)||l[0]:null}function fe(m){let h=P(m);if(i){let f=s("secret-tool",["lookup",...p(h)],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(!f.error&&f.status===0&&String(f.stdout||"").trim())try{return I(JSON.parse(String(f.stdout).trim()))}catch{}return v(h)}let l=g(t,{providers:{}}).providers?.[h];if(l)try{return I(l)}catch{}return v(h)}function Le(m,h){let u=P(m),l=I(h);if(i){let w=s("secret-tool",["store",`--label=Oracle ${u} OAuth`,...p(u)],{input:JSON.stringify(l),encoding:"utf8",stdio:["pipe","ignore","pipe"]});if(w.error||w.status!==0)throw new Error("OS credential store rejected OAuth credential");let k=g(r,{providers:{}});return k.providers||={},k.providers[u]={expiresAt:l.expiresAt,source:l.source},O(r,k),l}let f=g(t,{providers:{}});return f.providers||={},f.providers[u]=l,O(t,f),l}function Ie(m){let h=P(m);if(i){let f=s("secret-tool",["clear",...p(h)],{encoding:"utf8",stdio:["ignore","ignore","pipe"]}),w=g(r,{providers:{}});return w.providers&&delete w.providers[h],O(r,w),!f.error&&f.status===0}let u=g(t,{providers:{}}),l=!!u.providers?.[h];return u.providers&&delete u.providers[h],O(t,u),l}function he(m){let h=re(m);if(i){let u=s("secret-tool",["lookup",...p(h,"api-key")],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return u.error||u.status!==0?"":String(u.stdout||"").trim()}return String(g(t,{apiKeys:{}}).apiKeys?.[h]||"").trim()}function Ce(m,h){let u=re(m),l=String(h||"").trim();if(!l)throw new Error("API key is empty");if(i){let w=s("secret-tool",["store",`--label=Oracle ${u} API key`,...p(u,"api-key")],{input:l,encoding:"utf8",stdio:["pipe","ignore","pipe"]});if(w.error||w.status!==0)throw new Error("OS credential store rejected API key");let k=g(r,{providers:{},apiKeys:{}});return k.apiKeys||={},k.apiKeys[u]={configured:!0},O(r,k),!0}let f=g(t,{providers:{},apiKeys:{}});return f.apiKeys||={},f.apiKeys[u]=l,O(t,f),!0}function Ue(m){let h=re(m);if(i){let f=s("secret-tool",["clear",...p(h,"api-key")],{encoding:"utf8",stdio:["ignore","ignore","pipe"]}),w=g(r,{providers:{},apiKeys:{}});return w.apiKeys&&delete w.apiKeys[h],O(r,w),!f.error&&f.status===0}let u=g(t,{providers:{},apiKeys:{}}),l=!!u.apiKeys?.[h];return u.apiKeys&&delete u.apiKeys[h],O(t,u),l}function je(){let m={},h={};if(i){let u=g(r,{providers:{},apiKeys:{}});for(let[l,f]of Object.entries(u.providers||{}))m[l]={loggedIn:!!fe(l),expiresAt:Number(f.expiresAt||0),source:String(f.source||"oracle"),storage:c};for(let l of Object.keys(u.apiKeys||{}))h[l]={configured:!!he(l),storage:c}}else{let u=g(t,{providers:{},apiKeys:{}});for(let[l,f]of Object.entries(u.providers||{}))m[l]={loggedIn:!!f?.accessToken,expiresAt:Number(f?.expiresAt||0),source:String(f?.source||"oracle"),storage:c};for(let[l,f]of Object.entries(u.apiKeys||{}))h[l]={configured:!!f,storage:c}}for(let u of Object.keys(C)){if(m[u])continue;let l=v(u);l&&(m[u]={loggedIn:!0,expiresAt:l.expiresAt,source:l.source,storage:"external-access-source"})}return{storage:c,providers:m,apiKeys:h}}return Object.freeze({file:t,storage:c,get:fe,set:Le,remove:Ie,getApiKey:he,setApiKey:Ce,removeApiKey:Ue,status:je,withLock:d})}var Ee;function U(){return Ee||=ut(),Ee}function oe(e){return Buffer.from(e).toString("base64url")}function lt(){let e=oe(ne(32));return{verifier:e,challenge:oe(tt("sha256").update(e).digest()),state:oe(ne(24))}}function pt(e,t){let r=Buffer.from(String(e||"")),o=Buffer.from(String(t||""));return r.length===o.length&&rt(r,o)}function dt(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 nt(r[0],r[1],{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function se(e){return new URLSearchParams(e).toString()}async function T(e,t){if(!e?.ok){let o="";try{o=String((await e.json())?.error||"")}catch{}throw new Error(`${t} failed (HTTP ${e?.status||"unknown"}${o?`, ${o}`:""})`)}let r=await e.json();if(!r||typeof r!="object")throw new Error(`${t} returned invalid JSON`);return r}async function ft(e){if(e)return String(await e()).trim();let t=ot.createInterface({input:process.stdin,output:process.stdout});try{return String(await t.question("Authorization code: ")).trim()}finally{t.close()}}function ie(e,t={}){let r=String(e.access_token||"").trim(),o=String(e.refresh_token||t.refreshToken||"").trim();if(!r)throw new Error("OAuth token response is missing access token");let n=Number(e.expires_in||3600);return I({accessToken:r,refreshToken:o,expiresAt:at(t)+Math.max(1,n)*1e3,tokenType:e.token_type||"Bearer",idToken:e.id_token,source:"oracle",...t.discovery?{discovery:t.discovery}:{},...e.scope?{scope:e.scope}:{}})}async function ht(e){let t=C["anthropic-oauth"],r=e.pkce||lt(),o=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}),n=`${t.authorizeUrl}?${o}`;e.output(`Open: ${n}`),e.openFn(n);let s=await ft(e.inputFn),[i,c]=s.split("#",2);if(!i||!pt(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 ie(await T(a,"Claude OAuth token exchange"),e)}async function mt(e){let t=C["openai-codex"],r=await T(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 o=`${t.issuer}/codex/device`;e.output(`Open: ${o}`),e.output(`Code: ${r.user_code}`),e.openFn(o);let n=Math.max(3,Number(r.interval||5)),s;for(let c=0;c<Math.ceil(900/n);c+=1){await e.sleepFn(n*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 T(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:se({grant_type:"authorization_code",code:s.authorization_code,redirect_uri:`${t.issuer}/deviceauth/callback`,client_id:t.clientId,code_verifier:s.code_verifier})});return ie(await T(i,"Codex OAuth token exchange"),e)}function J(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 wt(e){let t=C["xai-oauth"],r=await T(await e.fetchFn(t.discoveryUrl,{headers:{accept:"application/json"}}),"xAI OAuth discovery");J(r.authorization_endpoint);let o=J(r.token_endpoint),n=await T(await e.fetchFn(t.deviceUrl,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:se({client_id:t.clientId,scope:t.scope})}),"xAI device authorization");if(!n.device_code||!n.user_code||!n.verification_uri)throw new Error("xAI device authorization returned incomplete data");let s=J(n.verification_uri_complete||n.verification_uri);e.output(`Open: ${s}`),e.output(`Code: ${n.user_code}`),e.openFn(s);let i=Math.max(1,Number(n.interval||5)),c=Math.ceil(Math.max(1,Number(n.expires_in||600))/i);for(let a=0;a<c;a+=1){let d=await e.fetchFn(o,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:se({grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:t.clientId,device_code:n.device_code})});if(d.ok){let v=await T(d,"xAI OAuth token exchange");return ie(v,{...e,discovery:{authorization_endpoint:J(r.authorization_endpoint),token_endpoint:o}})}let p="";try{p=String((await d.json())?.error||"")}catch{}if(p==="slow_down")await e.sleepFn((i+1)*1e3);else if(p==="authorization_pending")await e.sleepFn(i*1e3);else throw new Error(`xAI OAuth token exchange failed (HTTP ${d.status}${p?`, ${p}`:""})`)}throw new Error("xAI device authorization timed out")}async function Ae(e,t={}){let r=P(e),o={fetchFn:t.fetchFn||globalThis.fetch,inputFn:t.inputFn,sleepFn:t.sleepFn||(n=>new Promise(s=>setTimeout(s,n))),openFn:t.openFn||dt,output:t.output||(n=>process.stdout.write(`${n}
7
- `)),now:t.now,pkce:t.pkce};return r==="anthropic-oauth"?ht(o):r==="openai-codex"?mt(o):wt(o)}import X from"node:fs";import ae from"node:path";var gt=new Set(["openrouter","openai","anthropic","xai","deepseek","gemini","kimi","mistral","nous","custom","anthropic-oauth","openai-codex","xai-oauth"]);function Y(e){return String(e||"").trim()||void 0}function yt(e,{required:t=!1}={}){let r=Y(e)?.toLowerCase();if(!r){if(t)throw new Error("model provider is required");return}if(!gt.has(r))throw new Error(`unsupported provider: ${r}`);return r}function vt(e,{required:t=!1}={}){let r=Y(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 kt(e){let t=Y(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 o=r.hostname.toLowerCase().replace(/^\[|\]$/g,""),n=o==="localhost"||o==="127.0.0.1"||o==="::1";if(r.protocol!=="https:"&&!(r.protocol==="http:"&&n)||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 G({provider:e,model:t,baseUrl:r}={},{requireModel:o=!1}={}){let n=yt(e),s=vt(t,{required:o});if(n==="custom")return{provider:n,...s?{model:s}:{},baseUrl:kt(r)};if(Y(r))throw new Error("baseUrl is only supported for the custom provider");return{...n?{provider:n}:{},...s?{model:s}:{}}}var St=new Set(["auto","standalone","hermes","remote","arch"]);function xt(){return ae.join(S(),"model.json")}function j(e){return String(e||"").trim()||void 0}function Et(e={}){let t=j(e.backend)?.toLowerCase()||"auto",r=G({provider:e.provider,model:e.model,baseUrl:e.baseUrl},{requireModel:t==="standalone"}),o=j(e.apiKeyEnv),n=Number.parseInt(String(e.contextLength||""),10),s=j(e.reasoningEffort),i=j(e.computeHost||e.remoteHost),c=j(e.computeUser||e.remoteUser),a=j(e.computePath||e.remotePath);if(!St.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(o&&!/^[A-Z][A-Z0-9_]*$/.test(o))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,...o?{apiKeyEnv:o}:{},...Number.isFinite(n)&&n>0?{contextLength:n}:{},...s?{reasoningEffort:s}:{},...i?{computeHost:i}:{},...c?{computeUser:c}:{},...a?{computePath:a}:{}}}function Oe(e){let t=Et(e),r=xt();A(ae.dirname(r)),process.platform!=="win32"&&X.chmodSync(ae.dirname(r),448);let o=`${r}.${process.pid}.tmp`;return X.writeFileSync(o,`${JSON.stringify(t,null,2)}
8
- `,{mode:384}),X.renameSync(o,r),process.platform!=="win32"&&X.chmodSync(r,384),t}var be=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"},custom:{model:""}});function ce(e,t){let r=e.indexOf(t);return r>=0&&e[r+1]?e[r+1]:""}async function _t(){let e="";for await(let t of process.stdin)e+=t;return e.trim()}function At(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 o="",n=()=>{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
- `){n(),t(o.trim());return}if(a===""){n(),r(new Error("cancelled"));return}a==="\x7F"||a==="\b"?o=o.slice(0,-1):o+=a}};process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",s)})}function ue(e,t,{baseUrl:r=""}={}){if(e==="custom"&&!String(r||"").trim())throw new Error("custom provider requires --base-url");return{backend:"standalone",...G({provider:e,model:t,baseUrl:r},{requireModel:!0})}}function Pe(e,t,r={}){return Oe(ue(e,t,r))}function Ot(e){process.stdout.write(`storage: ${e.storage}
3
+ `}import E from"node:fs";import Ye from"node:os";import re from"node:path";import N from"node:fs";import He from"node:os";import x from"node:path";import{fileURLToPath as ze}from"node:url";var Be=x.dirname(ze(import.meta.url)),Ht=x.resolve(Be,"../..");function z(){return process.env.ORACLE_FAKE_HOME||He.homedir()}function qe(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function S(){return qe()?process.env.ORACLE_CONFIG_DIR||x.join(z(),".config","oracle"):x.join(z(),".config","oracle")}function We(){return x.join(S(),"desk.json")}function Ve(){return x.join(S(),"env")}function L({force:e=!1}={}){if(L._done&&!e)return L._result||null;L._done=!0;let t={},r=(n,s)=>{if(s==null)return;let i=String(s).trim();i&&(process.env[n]!=null&&String(process.env[n]).trim()!==""||(process.env[n]=i,t[n]=i))};try{let n=Ve();if(N.existsSync(n))for(let s of N.readFileSync(n,"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 n=We();if(N.existsSync(n)){let s=JSON.parse(N.readFileSync(n,"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 o=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return o&&(r("ORACLE_DESK_URL",o),r("ORACLE_DATA_URL",o),r("ORACLE_API_URL",o),r("ORACLE_PUBLIC_URL",o),r("MAD_DESK_URL",o)),L._result=Object.keys(t).length?t:null,L._result}try{L()}catch{}function M(){return process.env.HERMES_HOME?x.resolve(process.env.HERMES_HOME):x.join(z(),".hermes")}function A(e){return N.mkdirSync(e,{recursive:!0}),e}var Je=/(TOKEN|SECRET|PASSWORD|KEY|AUTH|PRIVATE|MNEMONIC|SEED)/i;function B(e="oracle"){return re.join(M(),"profiles",e,".env")}function Ge(e){let t={};for(let r of String(e||"").split(/\r?\n/)){let o=r.trim();if(!o||o.startsWith("#"))continue;let n=o.indexOf("=");if(n<=0)continue;let s=o.slice(0,n).trim(),i=o.slice(n+1).trim();(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),t[s]=i}return t}function Se(e="oracle"){let t=B(e);return E.existsSync(t)?Ge(E.readFileSync(t,"utf8")):{}}function ve(e,t,r){if(!t||Je.test(t)===!1&&/[^A-Z0-9_]/.test(t),!/^[A-Z][A-Z0-9_]*$/.test(t)){let d=new Error(`invalid env key '${t}'`);throw d.code="BAD_KEY",d}if(r==null||String(r).trim()===""){let d=new Error(`empty value for ${t}`);throw d.code="EMPTY",d}let o=B(e);A(re.dirname(o));let n=E.existsSync(o)?E.readFileSync(o,"utf8"):"",s=n?n.split(/\r?\n/):[],i=[],a=!1,c=`${t}=${String(r)}`;for(let d of s)d.startsWith(`${t}=`)?(i.push(c),a=!0):(d.length||i.length)&&i.push(d);for(a||(i.length&&i[i.length-1]!==""&&i.push(""),i.push(c));i.length&&i[i.length-1]==="";)i.pop();i.push(""),E.writeFileSync(o,i.join(`
4
+ `),{mode:384});try{E.chmodSync(o,384)}catch{}return{path:o,key:t,set:!0}}function q(e="oracle"){let t=Se(e),r={};for(let o of H()){if(!o.required.length){r[o.key]="manual";continue}let n=o.required.filter(s=>!String(t[s]||"").trim());r[o.key]=n.length?"unset":"ready"}return{profile:e,statuses:r,envPath:B(e)}}function W(e="oracle"){let{statuses:t}=q(e);return ke({profile:e,statuses:t})}function Ee(e,t,r,o={}){let n=j(t);if(!n){let p=new Error(`unknown platform '${t}'`);throw p.code="UNKNOWN_PLATFORM",p}if(!n.required.length){let p=new Error(`${n.key} uses hermes interactive setup (oracle setup messaging)`);throw p.code="NEEDS_INTERACTIVE",p}let i=n.required.filter(p=>/(TOKEN|PASSWORD|SECRET)$/i.test(p))[0]||(n.required.length===1?n.required[0]:null);if(!i){let p=new Error(`${n.key} has no single token field; provide each of [${n.required.join(", ")}] explicitly`);throw p.code="NEEDS_EXPLICIT_KEYS",p}let a=new Set([i,...Object.keys(o||{}).filter(p=>o[p]!=null&&String(o[p]).trim())]),c=Se(e),d=n.required.filter(p=>!a.has(p)&&!String(c[p]||"").trim());if(d.length){let p=new Error(`${n.key} also requires [${d.join(", ")}]; pass them explicitly (setup would otherwise be marked ready while unusable)`);throw p.code="MISSING_REQUIRED",p}ve(e,i,r);for(let[p,k]of Object.entries(o||{}))k!=null&&String(k).trim()&&ve(e,p,k);return{platform:n.key,set:n.required,profile:e,path:B(e)}}function Xe(){return re.join(S(),"setup-state.json")}function V(e={}){A(S());let t=Xe(),r={};if(E.existsSync(t))try{r=JSON.parse(E.readFileSync(t,"utf8"))}catch{r={}}let o={...r,...e,updatedAt:new Date().toISOString(),host:Ye.hostname()};return E.writeFileSync(t,JSON.stringify(o,null,2)+`
5
+ `,{mode:384}),o}import xe from"node:fs";import I from"node:path";var Ze="0.19.0",Qt=`hermes-agent==${Ze}`;var _e="0.12.1",er=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 Qe(){return I.join(S(),"runtime")}function et(){return I.join(Qe(),"venv")}function tt(e){let t=process.platform==="win32"?"Scripts":"bin",r=process.platform==="win32"?`${e}.exe`:e;return I.join(et(),t,r)}function rt(){return tt("hermes")}function ot(e){let t=process.platform==="win32"&&!I.extname(e)?["",".exe",".cmd",".bat"]:[""];for(let r of(process.env.PATH||"").split(I.delimiter))if(r)for(let o of t){let n=I.join(r,`${e}${o}`);try{if(xe.existsSync(n))return n}catch{}}return null}function Ae(){if(process.env.ORACLE_HERMES_BIN)return{ok:!0,bin:process.env.ORACLE_HERMES_BIN,source:"env"};let e=rt();if(xe.existsSync(e))return{ok:!0,bin:e,source:"managed"};let t=ot("hermes");return t?{ok:!0,bin:t,source:"path"}:{ok:!1,bin:null,source:null}}import{createHash as nt,randomBytes as se,timingSafeEqual as st}from"node:crypto";import y from"node:fs";import _ from"node:path";import it from"node:readline/promises";import{spawn as at,spawnSync as ct}from"node:child_process";var C=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"}}),ut=12e4;function lt(e={}){return typeof e.now=="function"?Number(e.now()):Date.now()}function T(e){let t=String(e||"").trim().toLowerCase();for(let[r,o]of Object.entries(C))if(o.aliases.includes(t))return r;throw new Error(`unsupported OAuth provider: ${e||"(empty)"}`)}function F(e){let t=T(e);return{id:t,...C[t]}}function w(e,t={}){if(!y.existsSync(e))return t;try{let r=JSON.parse(y.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: ${_.basename(e)}`)}}function be(e){A(e),process.platform!=="win32"&&y.chmodSync(e,448)}function O(e,t){be(_.dirname(e));let r=`${e}.${process.pid}.${se(4).toString("hex")}.tmp`;y.writeFileSync(r,`${JSON.stringify(t,null,2)}
6
+ `,{mode:384}),y.renameSync(r,e),process.platform!=="win32"&&y.chmodSync(e,384)}function pt(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 oe(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 $(e={}){let t=String(e.accessToken||e.access_token||"").trim(),r=String(e.refreshToken||e.refresh_token||"").trim(),o=Number(e.expiresAt||e.expires_at||0);if(Number.isFinite(o)&&o>=1e9&&o<1e12&&(o=o*1e3),!t)throw new Error("OAuth credential is missing access token");return{accessToken:t,refreshToken:r,expiresAt:Number.isFinite(o)?o:0,tokenType:String(e.tokenType||e.token_type||"Bearer"),source:String(e.source||"oracle"),...e.discovery?{discovery:e.discovery}:{},...e.scope?{scope:e.scope}:{},...e.idToken||e.id_token?{idToken:String(e.idToken||e.id_token)}:{}}}function dt(e={}){let t=e.file||_.join(S(),"oauth.json"),r=e.metadataFile||_.join(_.dirname(t),"oauth-meta.json"),o=e.linksFile||_.join(_.dirname(t),"oauth-links.json"),n=()=>typeof e.now=="function"?Number(e.now()):Date.now(),s=e.spawnFn||ct,i=e.keychain!==!1&&process.env.ORACLE_AUTH_FILE_STORE!=="1"&&pt(s),a=i?"linux-secret-service":"private-file",c=`${t}.lock`;async function d(m){be(_.dirname(c));let h;for(let u=0;u<400;u+=1)try{h=y.openSync(c,"wx",384);break}catch(l){if(l?.code!=="EEXIST")throw l;try{Date.now()-y.statSync(c).mtimeMs>3e5&&y.unlinkSync(c)}catch{}await new Promise(f=>setTimeout(f,25))}if(h===void 0)throw new Error("timed out waiting for OAuth credential lock");try{return await m()}finally{try{y.closeSync(h)}catch{}try{y.unlinkSync(c)}catch{}}}function p(m,h="oauth"){return["application","oracle","kind",h,"provider",m]}function k(m){if(!y.existsSync(o))return null;let u=w(o,{providers:{}}).providers?.[m];if(!Array.isArray(u))return null;let l=[];for(let f of u)if(_.isAbsolute(String(f||"")))try{let g=w(f,{});if(m==="anthropic-oauth"&&g.claudeAiOauth){let P=$(g.claudeAiOauth);l.push({...P,refreshToken:"",source:"external-access-only"});continue}let v=g.credential_pool&&typeof g.credential_pool=="object"?g.credential_pool:null;if(v){let P=v[m]||v[m.replace(/-oauth$/,"")]||[],Fe=Array.isArray(P)?P:P?[P]:[];for(let ee of Fe)if(!(!ee||typeof ee!="object"))try{let Ke=$(ee);l.push({...Ke,refreshToken:"",source:"external-access-only"})}catch{}}}catch{}return l.length?l.find(f=>!f.expiresAt||f.expiresAt>n()+ut)||l[0]:null}function ge(m){let h=T(m);if(i){let f=s("secret-tool",["lookup",...p(h)],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(!f.error&&f.status===0&&String(f.stdout||"").trim())try{return $(JSON.parse(String(f.stdout).trim()))}catch{}return k(h)}let l=w(t,{providers:{}}).providers?.[h];if(l)try{return $(l)}catch{}return k(h)}function De(m,h){let u=T(m),l=$(h);if(i){let g=s("secret-tool",["store",`--label=Oracle ${u} OAuth`,...p(u)],{input:JSON.stringify(l),encoding:"utf8",stdio:["pipe","ignore","pipe"]});if(g.error||g.status!==0)throw new Error("OS credential store rejected OAuth credential");let v=w(r,{providers:{}});return v.providers||={},v.providers[u]={expiresAt:l.expiresAt,source:l.source},O(r,v),l}let f=w(t,{providers:{}});return f.providers||={},f.providers[u]=l,O(t,f),l}function Ue(m){let h=T(m);if(i){let f=s("secret-tool",["clear",...p(h)],{encoding:"utf8",stdio:["ignore","ignore","pipe"]}),g=w(r,{providers:{}});return g.providers&&delete g.providers[h],O(r,g),!f.error&&f.status===0}let u=w(t,{providers:{}}),l=!!u.providers?.[h];return u.providers&&delete u.providers[h],O(t,u),l}function we(m){let h=oe(m);if(i){let u=s("secret-tool",["lookup",...p(h,"api-key")],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return u.error||u.status!==0?"":String(u.stdout||"").trim()}return String(w(t,{apiKeys:{}}).apiKeys?.[h]||"").trim()}function je(m,h){let u=oe(m),l=String(h||"").trim();if(!l)throw new Error("API key is empty");if(i){let g=s("secret-tool",["store",`--label=Oracle ${u} API key`,...p(u,"api-key")],{input:l,encoding:"utf8",stdio:["pipe","ignore","pipe"]});if(g.error||g.status!==0)throw new Error("OS credential store rejected API key");let v=w(r,{providers:{},apiKeys:{}});return v.apiKeys||={},v.apiKeys[u]={configured:!0},O(r,v),!0}let f=w(t,{providers:{},apiKeys:{}});return f.apiKeys||={},f.apiKeys[u]=l,O(t,f),!0}function Ne(m){let h=oe(m);if(i){let f=s("secret-tool",["clear",...p(h,"api-key")],{encoding:"utf8",stdio:["ignore","ignore","pipe"]}),g=w(r,{providers:{},apiKeys:{}});return g.apiKeys&&delete g.apiKeys[h],O(r,g),!f.error&&f.status===0}let u=w(t,{providers:{},apiKeys:{}}),l=!!u.apiKeys?.[h];return u.apiKeys&&delete u.apiKeys[h],O(t,u),l}function Me(){let m={},h={};if(i){let u=w(r,{providers:{},apiKeys:{}});for(let[l,f]of Object.entries(u.providers||{}))m[l]={loggedIn:!!ge(l),expiresAt:Number(f.expiresAt||0),source:String(f.source||"oracle"),storage:a};for(let l of Object.keys(u.apiKeys||{}))h[l]={configured:!!we(l),storage:a}}else{let u=w(t,{providers:{},apiKeys:{}});for(let[l,f]of Object.entries(u.providers||{}))m[l]={loggedIn:!!f?.accessToken,expiresAt:Number(f?.expiresAt||0),source:String(f?.source||"oracle"),storage:a};for(let[l,f]of Object.entries(u.apiKeys||{}))h[l]={configured:!!f,storage:a}}for(let u of Object.keys(C)){if(m[u])continue;let l=k(u);l&&(m[u]={loggedIn:!0,expiresAt:l.expiresAt,source:l.source,storage:"external-access-source"})}return{storage:a,providers:m,apiKeys:h}}return Object.freeze({file:t,storage:a,get:ge,set:De,remove:Ue,getApiKey:we,setApiKey:je,removeApiKey:Ne,status:Me,withLock:d})}var Oe;function D(){return Oe||=dt(),Oe}function ne(e){return Buffer.from(e).toString("base64url")}function ft(){let e=ne(se(32));return{verifier:e,challenge:ne(nt("sha256").update(e).digest()),state:ne(se(24))}}function ht(e,t){let r=Buffer.from(String(e||"")),o=Buffer.from(String(t||""));return r.length===o.length&&st(r,o)}function mt(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 at(r[0],r[1],{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function ie(e){return new URLSearchParams(e).toString()}async function R(e,t){if(!e?.ok){let o="";try{o=String((await e.json())?.error||"")}catch{}throw new Error(`${t} failed (HTTP ${e?.status||"unknown"}${o?`, ${o}`:""})`)}let r=await e.json();if(!r||typeof r!="object")throw new Error(`${t} returned invalid JSON`);return r}async function gt(e){if(e)return String(await e()).trim();let t=it.createInterface({input:process.stdin,output:process.stdout});try{return String(await t.question("Authorization code: ")).trim()}finally{t.close()}}function ae(e,t={}){let r=String(e.access_token||"").trim(),o=String(e.refresh_token||t.refreshToken||"").trim();if(!r)throw new Error("OAuth token response is missing access token");let n=Number(e.expires_in||3600);return $({accessToken:r,refreshToken:o,expiresAt:lt(t)+Math.max(1,n)*1e3,tokenType:e.token_type||"Bearer",idToken:e.id_token,source:"oracle",...t.discovery?{discovery:t.discovery}:{},...e.scope?{scope:e.scope}:{}})}async function wt(e){let t=C["anthropic-oauth"],r=e.pkce||ft(),o=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}),n=`${t.authorizeUrl}?${o}`;e.output(`Open: ${n}`),e.openFn(n);let s=await gt(e.inputFn),[i,a]=s.split("#",2);if(!i||!ht(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 ae(await R(c,"Claude OAuth token exchange"),e)}async function yt(e){let t=C["openai-codex"],r=await R(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 o=`${t.issuer}/codex/device`;e.output(`Open: ${o}`),e.output(`Code: ${r.user_code}`),e.openFn(o);let n=Math.max(3,Number(r.interval||5)),s;for(let a=0;a<Math.ceil(900/n);a+=1){await e.sleepFn(n*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 R(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:ie({grant_type:"authorization_code",code:s.authorization_code,redirect_uri:`${t.issuer}/deviceauth/callback`,client_id:t.clientId,code_verifier:s.code_verifier})});return ae(await R(i,"Codex OAuth token exchange"),e)}function Y(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 kt(e){let t=C["xai-oauth"],r=await R(await e.fetchFn(t.discoveryUrl,{headers:{accept:"application/json"}}),"xAI OAuth discovery");Y(r.authorization_endpoint);let o=Y(r.token_endpoint),n=await R(await e.fetchFn(t.deviceUrl,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:ie({client_id:t.clientId,scope:t.scope})}),"xAI device authorization");if(!n.device_code||!n.user_code||!n.verification_uri)throw new Error("xAI device authorization returned incomplete data");let s=Y(n.verification_uri_complete||n.verification_uri);e.output(`Open: ${s}`),e.output(`Code: ${n.user_code}`),e.openFn(s);let i=Math.max(1,Number(n.interval||5)),a=Math.ceil(Math.max(1,Number(n.expires_in||600))/i);for(let c=0;c<a;c+=1){let d=await e.fetchFn(o,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:ie({grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:t.clientId,device_code:n.device_code})});if(d.ok){let k=await R(d,"xAI OAuth token exchange");return ae(k,{...e,discovery:{authorization_endpoint:Y(r.authorization_endpoint),token_endpoint:o}})}let p="";try{p=String((await d.json())?.error||"")}catch{}if(p==="slow_down")await e.sleepFn((i+1)*1e3);else if(p==="authorization_pending")await e.sleepFn(i*1e3);else throw new Error(`xAI OAuth token exchange failed (HTTP ${d.status}${p?`, ${p}`:""})`)}throw new Error("xAI device authorization timed out")}async function Te(e,t={}){let r=T(e),o={fetchFn:t.fetchFn||globalThis.fetch,inputFn:t.inputFn,sleepFn:t.sleepFn||(n=>new Promise(s=>setTimeout(s,n))),openFn:t.openFn||mt,output:t.output||(n=>process.stdout.write(`${n}
7
+ `)),now:t.now,pkce:t.pkce};return r==="anthropic-oauth"?wt(o):r==="openai-codex"?yt(o):kt(o)}import X from"node:fs";import ce from"node:path";var vt=new Set(["openrouter","openai","anthropic","xai","deepseek","gemini","kimi","mistral","nous","custom","anthropic-oauth","openai-codex","xai-oauth"]);function J(e){return String(e||"").trim()||void 0}function St(e,{required:t=!1}={}){let r=J(e)?.toLowerCase();if(!r){if(t)throw new Error("model provider is required");return}if(!vt.has(r))throw new Error(`unsupported provider: ${r}`);return r}function Et(e,{required:t=!1}={}){let r=J(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 _t(e){let t=J(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 o=r.hostname.toLowerCase().replace(/^\[|\]$/g,""),n=o==="localhost"||o==="127.0.0.1"||o==="::1";if(r.protocol!=="https:"&&!(r.protocol==="http:"&&n)||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 G({provider:e,model:t,baseUrl:r}={},{requireModel:o=!1}={}){let n=St(e),s=Et(t,{required:o});if(n==="custom")return{provider:n,...s?{model:s}:{},baseUrl:_t(r)};if(J(r))throw new Error("baseUrl is only supported for the custom provider");return{...n?{provider:n}:{},...s?{model:s}:{}}}var xt=new Set(["auto","standalone","hermes","remote","arch"]);function At(){return ce.join(S(),"model.json")}function U(e){return String(e||"").trim()||void 0}function Ot(e={}){let t=U(e.backend)?.toLowerCase()||"auto",r=G({provider:e.provider,model:e.model,baseUrl:e.baseUrl},{requireModel:t==="standalone"}),o=U(e.apiKeyEnv),n=Number.parseInt(String(e.contextLength||""),10),s=U(e.reasoningEffort),i=U(e.computeHost||e.remoteHost),a=U(e.computeUser||e.remoteUser),c=U(e.computePath||e.remotePath);if(!xt.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(o&&!/^[A-Z][A-Z0-9_]*$/.test(o))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,...o?{apiKeyEnv:o}:{},...Number.isFinite(n)&&n>0?{contextLength:n}:{},...s?{reasoningEffort:s}:{},...i?{computeHost:i}:{},...a?{computeUser:a}:{},...c?{computePath:c}:{}}}function Re(e){let t=Ot(e),r=At();A(ce.dirname(r)),process.platform!=="win32"&&X.chmodSync(ce.dirname(r),448);let o=`${r}.${process.pid}.tmp`;return X.writeFileSync(o,`${JSON.stringify(t,null,2)}
8
+ `,{mode:384}),X.renameSync(o,r),process.platform!=="win32"&&X.chmodSync(r,384),t}var Pe=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"},custom:{model:""}});function ue(e,t){let r=e.indexOf(t);return r>=0&&e[r+1]?e[r+1]:""}async function bt(){let e="";for await(let t of process.stdin)e+=t;return e.trim()}function Tt(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 o="",n=()=>{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
+ `){n(),t(o.trim());return}if(c===""){n(),r(new Error("cancelled"));return}c==="\x7F"||c==="\b"?o=o.slice(0,-1):o+=c}};process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",s)})}function le(e,t,{baseUrl:r=""}={}){if(e==="custom"&&!String(r||"").trim())throw new Error("custom provider requires --base-url");return{backend:"standalone",...G({provider:e,model:t,baseUrl:r},{requireModel:!0})}}function Le(e,t,r={}){return Re(le(e,t,r))}function Rt(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[o,n]of t){let s=n.expiresAt?new Date(n.expiresAt).toISOString():"unknown";process.stdout.write(`${o}: ${n.loggedIn?"logged in":"missing"}, expires ${s}
13
13
  `)}for(let[o,n]of r)process.stdout.write(`${o}: API key ${n.configured?"configured":"missing"}
14
- `)}function bt(){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|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
- `)}var Z={name:"auth",summary:"login with Claude, Codex, or Grok OAuth; store provider API keys",group:"read",usage:bt(),async run(e){let t=[...e.argv],r=t.shift()||"status",o=U();try{if(r==="status"){let n=o.status();return t.includes("--json")?process.stdout.write(`${JSON.stringify(n,null,2)}
16
- `):Ot(n),0}if(r==="login"){let n=t.find(a=>!a.startsWith("-"));if(!n)throw new Error("usage: oracle auth login claude|codex|grok");let s=K(n),i=ce(t,"--model")||s.model;ue(s.id,i);let c=await Ae(s.id,{openFn:t.includes("--no-browser")?()=>!1:void 0});return await o.withLock(async()=>{let a=o.get(s.id);o.set(s.id,c);try{Pe(s.id,i)}catch(d){throw a?o.set(s.id,a):o.remove(s.id),d}}),process.stdout.write(`${s.id}: logged in, stored in ${o.storage}
17
- `),0}if(r==="api-key"){let n=String(t.find(a=>!a.startsWith("-"))||"").trim().toLowerCase();if(!n)throw new Error("usage: oracle auth api-key PROVIDER [--stdin]");if(!Object.hasOwn(be,n))throw new Error(`unsupported API-key provider: ${n}`);let s=ce(t,"--model")||be[n].model,i=ce(t,"--base-url");ue(n,s,{baseUrl:i});let c=t.includes("--stdin")?await _t():await At();return await o.withLock(async()=>{let a=o.getApiKey(n);o.setApiKey(n,c);try{Pe(n,s,{baseUrl:i})}catch(d){throw a?o.setApiKey(n,a):o.removeApiKey(n),d}}),process.stdout.write(`${n}: API key configured in ${o.storage}
18
- `),0}if(r==="logout"){let n=String(t.find(c=>!c.startsWith("-"))||"").trim().toLowerCase();if(!n)throw new Error("usage: oracle auth logout PROVIDER");let s=!1;try{s=o.remove(P(n))}catch{}let i=o.removeApiKey(n);if(!s&&!i)throw new Error(`${n}: no local credential found`);return process.stdout.write(`${n}: local credential removed
14
+ `)}function Pt(){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|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
+ `)}var Z={name:"auth",summary:"login with Claude, Codex, or Grok OAuth; store provider API keys",group:"read",usage:Pt(),async run(e){let t=[...e.argv],r=t.shift()||"status",o=D();try{if(r==="status"){let n=o.status();return t.includes("--json")?process.stdout.write(`${JSON.stringify(n,null,2)}
16
+ `):Rt(n),0}if(r==="login"){let n=t.find(c=>!c.startsWith("-"));if(!n)throw new Error("usage: oracle auth login claude|codex|grok");let s=F(n),i=ue(t,"--model")||s.model;le(s.id,i);let a=await Te(s.id,{openFn:t.includes("--no-browser")?()=>!1:void 0});return await o.withLock(async()=>{let c=o.get(s.id);o.set(s.id,a);try{Le(s.id,i)}catch(d){throw c?o.set(s.id,c):o.remove(s.id),d}}),process.stdout.write(`${s.id}: logged in, stored in ${o.storage}
17
+ `),0}if(r==="api-key"){let n=String(t.find(c=>!c.startsWith("-"))||"").trim().toLowerCase();if(!n)throw new Error("usage: oracle auth api-key PROVIDER [--stdin]");if(!Object.hasOwn(Pe,n))throw new Error(`unsupported API-key provider: ${n}`);let s=ue(t,"--model")||Pe[n].model,i=ue(t,"--base-url");le(n,s,{baseUrl:i});let a=t.includes("--stdin")?await bt():await Tt();return await o.withLock(async()=>{let c=o.getApiKey(n);o.setApiKey(n,a);try{Le(n,s,{baseUrl:i})}catch(d){throw c?o.setApiKey(n,c):o.removeApiKey(n),d}}),process.stdout.write(`${n}: API key configured in ${o.storage}
18
+ `),0}if(r==="logout"){let n=String(t.find(a=>!a.startsWith("-"))||"").trim().toLowerCase();if(!n)throw new Error("usage: oracle auth logout PROVIDER");let s=!1;try{s=o.remove(T(n))}catch{}let i=o.removeApiKey(n);if(!s&&!i)throw new Error(`${n}: no local credential found`);return process.stdout.write(`${n}: local credential removed
19
19
  `),0}throw new Error(`unknown auth action: ${r}`)}catch(n){return process.stderr.write(`oracle auth: ${n.message}
20
- `),1}}};var $e=Object.freeze([{alias:"claude",label:"Anthropic OAuth"},{alias:"codex",label:"OpenAI Codex OAuth"},{alias:"grok",label:"Grok / xAI OAuth"}]),de=Object.freeze([{id:"openrouter",label:"OpenRouter"},{id:"openai",label:"OpenAI API"},{id:"anthropic",label:"Anthropic API"},{id:"xai",label:"xAI API"},{id:"deepseek",label:"DeepSeek"},{id:"gemini",label:"Google Gemini"},{id:"kimi",label:"Kimi"},{id:"mistral",label:"Mistral"},{id:"nous",label:"Nous"}]);async function Er({stdin:e=process.stdin,stdout:t=process.stdout,readLine:r,runAuth:o=n=>Z.run({argv:n})}={}){if(t.write(`${F()}
21
- `),t.write(`choose oauth: claude | codex | grok (enter skips)
22
- `),e.isTTY!==!0||t.isTTY!==!0)return{skipped:!0,reason:"non-tty"};t.write("> ");let n=r?await r():await new Promise(a=>{let d="",p=v=>{d+=String(v),(d.includes(`
23
- `)||d.includes("\r"))&&(e.off("data",p),a(d.trim()))};e.on("data",p)}),s=String(n||"").trim().toLowerCase();if(!s||s==="skip")return{skipped:!0,reason:"skipped"};let i=$e.find(a=>a.alias===s);if(i){let a=await o(["login",i.alias]);return{skipped:!1,choice:i.alias,code:a}}if(de.find(a=>a.id===s)||s==="custom"){let a=await o(["api-key",s]);return{skipped:!1,choice:s,code:a}}return t.write(`unknown choice '${s}'
24
- `),{skipped:!0,reason:"unknown"}}function F(e=U().status()){let t=["standalone model OAuth (choose one)",""];for(let r of $e){let o=K(r.alias),n=e.providers?.[o.id]?.loggedIn===!0;t.push(` ${r.label.padEnd(18)} ${n?"connected":"not connected"}`,` oracle setup model ${r.alias}`)}t.push("","OAuth uses your provider subscription. No API key is required.","","standalone API keys","");for(let r of de){let o=e.apiKeys?.[r.id]?.configured===!0;t.push(` ${r.label.padEnd(18)} ${o?"configured":"not configured"}`,` oracle setup model ${r.id}`)}return t.push("","Any other OpenAI-compatible provider:"," oracle auth api-key custom --model MODEL --base-url https://provider.example/v1","","The selected provider is saved as backend=standalone in model.json.",""),t.join(`
25
- `)}function le(){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 OAuth choices"," 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 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"," /setup telegram"," /setup status","","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."].join(`
26
- `)}function Tt(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 Rt(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 pe(e,{inherit:t=!0,env:r=process.env}={}){let o=xe();if(!o.ok)return process.stderr.write(`oracle setup: Hermes not detected (opt-in only).
20
+ `),1}}};var kr=Object.freeze([["#EAF7FF"," \u2588\u2588\u2588\u2593\u2593\u2593"],["#D8F2FF"," \u2588\u2588\u2588\u2588\u2588\u2588\u2593\u2593\u2593\u2592"],["#B8F0FF"," \u2588\u2588\u2588\u2588\u2588\u2588\u2593\u2593\u2593\u2593\u2592\u2592"],["#ACDEEF","\u2593\u2588\u2588\u2588\u2588\u2588\u2593\u2593\u2593\u2593\u2592\u2592\u2592\u2591"],["#A5D9EB","\u2593\u2593\u2593\u2593\u2593\u2593\u2593\u2593\u2592\u2592\u2592\u2592\u2591\u2591"],["#9FCBDD"," \u2592\u2593\u2593\u2593\u2593\u2592\u2592\u2592\u2592\u2592\u2591\u2591"],["#91C2D7"," \u2592\u2592\u2592\u2592\u2592\u2592\u2591\u2591\u2591\u2591"],["#60717F"," \u2591\u2591\u2591\u2591\u2591\u2591"]]);var vr=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 Q=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"]]),Sr=Object.freeze([["#EAF7FF"," \u2588\u2588\u2588\u2588"],["#D8F2FF"," \u2591\u2591\u2588\u2588\u2588"],["#B8F0FF"," \u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588"],["#ACDEEF"," \u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588 \u2591\u2591\u2591\u2591\u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588"],["#A5D9EB","\u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2591\u2591 \u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2591\u2591 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2588"],["#9FCBDD","\u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588\u2591\u2591\u2591"],["#91C2D7","\u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588"],["#60717F"," \u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591"]]);var pe=Object.freeze([{alias:"claude",label:"Claude",hint:"Anthropic subscription"},{alias:"codex",label:"Codex",hint:"OpenAI subscription"},{alias:"grok",label:"Grok",hint:"xAI subscription"}]),fe=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"}]),he=Object.freeze([...pe.map((e,t)=>({n:t+1,id:e.alias,label:e.label,kind:"oauth",hint:e.hint})),...fe.map((e,t)=>({n:pe.length+t+1,id:e.id,label:e.label,kind:"api-key",hint:"API key"})),{n:pe.length+fe.length+1,id:"custom",label:"Custom",kind:"api-key",hint:"OpenAI-compatible"}]);function It(e){let t=String(e||"").trim().toLowerCase();if(!t||t==="skip")return{skip:!0};let r=he.find(o=>String(o.n)===t||o.id===t);return r||{unknown:!0,choice:t}}function Ce(e="sign in",t=0){let r=Q[t]||Q[0];return["",`${r[0]} oracle`,`${r[1]} ${e}`,r[2],r[3],r[4],""].join(`
21
+ `)}async function $t(e){if(e.isTTY!==!0||process.env.NODE_TEST_CONTEXT||process.env.ORACLE_INSTALL_PLAIN==="1")return;let t=r=>new Promise(o=>setTimeout(o,r));for(let r=0;r<Q.length;r+=1)r>0&&e.write("\x1B[7A"),e.write(`${Ce("sign in",r)}
22
+ `),await t(90)}async function $r({stdin:e=process.stdin,stdout:t=process.stdout,readLine:r,runAuth:o=n=>Z.run({argv:n})}={}){if(await $t(t),t.write(`${K()}
23
+ `),t.write(`number or name \xB7 enter skips
24
+ `),e.isTTY!==!0||t.isTTY!==!0)return{skipped:!0,reason:"non-tty"};t.write("> ");let n=r?await r():await new Promise(c=>{let d="",p=k=>{d+=String(k),(d.includes(`
25
+ `)||d.includes("\r"))&&(e.off("data",p),c(d.trim()))};e.on("data",p)}),s=It(n);if(s.skip)return{skipped:!0,reason:"skipped"};if(s.unknown)return t.write(`unknown choice '${s.choice}'
26
+ `),{skipped:!0,reason:"unknown"};let i=s.kind==="oauth"?["login",s.id]:["api-key",s.id],a=await o(i);return{skipped:!1,choice:s.id,code:a}}function K(e=D().status()){let t=[Ce("sign in"),"sign in with a subscription",""];for(let r of he.filter(o=>o.kind==="oauth")){let o=F(r.id),n=e.providers?.[o.id]?.loggedIn===!0;t.push(` ${String(r.n).padStart(2)} ${r.label.padEnd(12)} ${n?"connected":"OAuth"}`)}t.push("","or use an API key","");for(let r of he.filter(o=>o.kind==="api-key")){let o=r.id==="custom"?!1:e.apiKeys?.[r.id]?.configured===!0;t.push(` ${String(r.n).padStart(2)} ${r.label.padEnd(12)} ${o?"configured":"not configured"}`)}return t.push("","Your key stays on this machine. Nothing is uploaded by Oracle.",""),t.join(`
27
+ `)}function de(){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, DeepSeek, Nous, ..."," 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 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"," /setup telegram"," /setup status","","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."].join(`
28
+ `)}function Ct(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 Dt(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 me(e,{inherit:t=!0,env:r=process.env}={}){let o=Ae();if(!o.ok)return process.stderr.write(`oracle setup: Hermes not detected (opt-in only).
27
29
  Native Oracle does not need Hermes.
28
30
  To use Hermes messaging/gateway: install Hermes, or run \`oracle bootstrap\`, then retry.
29
31
  Detect: oracle harness detect
30
- `),1;let n=Pt(o.bin,e,{stdio:t?"inherit":"pipe",encoding:"utf8",env:r});return n.error?(process.stderr.write(`oracle setup: failed to run hermes: ${n.error.message}
31
- `),1):(t||(n.stdout&&process.stdout.write(n.stdout),n.stderr&&process.stderr.write(n.stderr)),typeof n.status=="number"?n.status:1)}async function Re(e){if(!b.isTTY||typeof b.setRawMode!="function"){let t=new Error("interactive token entry requires a tty");throw t.code="NO_TTY",t}return Te.write(`${e}: `),new Promise((t,r)=>{let o="",n=()=>{b.off("data",s),b.setRawMode(!1),b.pause(),Te.write(`
32
- `)},s=i=>{for(let c of String(i)){if(c==="\r"||c===`
33
- `){n(),t(o.trim());return}if(c===""){n(),r(new Error("cancelled"));return}c==="\x7F"||c==="\b"?o=o.slice(0,-1):o+=c}};b.setRawMode(!0),b.resume(),b.on("data",s)})}async function $t(e,t,r=[]){let o=D(t);if(!o)return process.stderr.write(`oracle setup: unknown platform '${t}'
34
- `),process.stderr.write(`known: ${H().map(a=>a.key).join(", ")}
32
+ `),1;let n=Lt(o.bin,e,{stdio:t?"inherit":"pipe",encoding:"utf8",env:r});return n.error?(process.stderr.write(`oracle setup: failed to run hermes: ${n.error.message}
33
+ `),1):(t||(n.stdout&&process.stdout.write(n.stdout),n.stderr&&process.stderr.write(n.stderr)),typeof n.status=="number"?n.status:1)}async function $e(e){if(!b.isTTY||typeof b.setRawMode!="function"){let t=new Error("interactive token entry requires a tty");throw t.code="NO_TTY",t}return Ie.write(`${e}: `),new Promise((t,r)=>{let o="",n=()=>{b.off("data",s),b.setRawMode(!1),b.pause(),Ie.write(`
34
+ `)},s=i=>{for(let a of String(i)){if(a==="\r"||a===`
35
+ `){n(),t(o.trim());return}if(a===""){n(),r(new Error("cancelled"));return}a==="\x7F"||a==="\b"?o=o.slice(0,-1):o+=a}};b.setRawMode(!0),b.resume(),b.on("data",s)})}async function Ut(e,t,r=[]){let o=j(t);if(!o)return process.stderr.write(`oracle setup: unknown platform '${t}'
36
+ `),process.stderr.write(`known: ${H().map(c=>c.key).join(", ")}
35
37
  `),1;if(!o.required.length)return process.stdout.write(`opening hermes setup for ${o.key} (interactive)
36
- `),V({lastPlatform:o.key,profile:e}),pe(["-p",e,...o.hermes||["gateway","setup"]]);let n={},s=[];for(let a=0;a<r.length;a++){let d=r[a];if(d==="--token"&&r[a+1]){n.token=r[++a];continue}if(d==="--allowed-users"&&r[a+1]){n.allowedUsers=r[++a];continue}if(d==="--app-token"&&r[a+1]){n.appToken=r[++a];continue}if(d.startsWith("-"))return process.stderr.write(`oracle setup: unknown flag ${d}
37
- `),1;s.push(d)}let i=n.token||s[0]||"";if(!i&&!process.stdin.isTTY&&(i=await readStdinSecret()),!i)try{i=await Re(`${o.key} bot token`)}catch(a){if(a?.code==="NO_TTY")return process.stderr.write(`oracle setup ${o.key}: pipe the token on stdin (echo "$TOKEN" | oracle setup ${o.key}) or pass --token <value>
38
- `),1;throw a}if(!i)return process.stderr.write(`aborted: empty token
39
- `),1;let c={};if(n.allowedUsers&&(o.key==="telegram"&&(c.TELEGRAM_ALLOWED_USERS=n.allowedUsers),o.key==="discord"&&(c.DISCORD_ALLOWED_USERS=n.allowedUsers),o.key==="slack"&&(c.SLACK_ALLOWED_USERS=n.allowedUsers)),n.appToken&&o.key==="slack"&&(c.SLACK_APP_TOKEN=n.appToken),o.key==="slack"&&!c.SLACK_APP_TOKEN){let a=n.appToken||s[1]||"";if(!a&&process.stdin.isTTY&&(a=await Re("slack app token (xapp-...)")),!a)return process.stderr.write(`slack needs bot token + app token
40
- `),1;c.SLACK_APP_TOKEN=a}try{let a=ve(e,o.key,i,c);return V({lastPlatform:o.key,profile:e,ready:!0}),process.stdout.write(`saved ${o.key} credentials for profile '${e}'
41
- path: ${a.path}
38
+ `),V({lastPlatform:o.key,profile:e}),me(["-p",e,...o.hermes||["gateway","setup"]]);let n={},s=[];for(let c=0;c<r.length;c++){let d=r[c];if(d==="--token"&&r[c+1]){n.token=r[++c];continue}if(d==="--allowed-users"&&r[c+1]){n.allowedUsers=r[++c];continue}if(d==="--app-token"&&r[c+1]){n.appToken=r[++c];continue}if(d.startsWith("-"))return process.stderr.write(`oracle setup: unknown flag ${d}
39
+ `),1;s.push(d)}let i=n.token||s[0]||"";if(!i&&!process.stdin.isTTY&&(i=await readStdinSecret()),!i)try{i=await $e(`${o.key} bot token`)}catch(c){if(c?.code==="NO_TTY")return process.stderr.write(`oracle setup ${o.key}: pipe the token on stdin (echo "$TOKEN" | oracle setup ${o.key}) or pass --token <value>
40
+ `),1;throw c}if(!i)return process.stderr.write(`aborted: empty token
41
+ `),1;let a={};if(n.allowedUsers&&(o.key==="telegram"&&(a.TELEGRAM_ALLOWED_USERS=n.allowedUsers),o.key==="discord"&&(a.DISCORD_ALLOWED_USERS=n.allowedUsers),o.key==="slack"&&(a.SLACK_ALLOWED_USERS=n.allowedUsers)),n.appToken&&o.key==="slack"&&(a.SLACK_APP_TOKEN=n.appToken),o.key==="slack"&&!a.SLACK_APP_TOKEN){let c=n.appToken||s[1]||"";if(!c&&process.stdin.isTTY&&(c=await $e("slack app token (xapp-...)")),!c)return process.stderr.write(`slack needs bot token + app token
42
+ `),1;a.SLACK_APP_TOKEN=c}try{let c=Ee(e,o.key,i,a);return V({lastPlatform:o.key,profile:e,ready:!0}),process.stdout.write(`saved ${o.key} credentials for profile '${e}'
43
+ path: ${c.path}
42
44
  next: oracle setup gateway restart
43
- `),0}catch(a){return process.stderr.write(`oracle setup: ${a.message}
44
- `),1}}var _r={name:"setup",summary:"configure standalone OAuth and messaging platforms",group:"read",usage:le(),async run(e){let t=[...e.argv],r=t.includes("--json"),o=Tt(t),n=Rt(t).filter(c=>c!=="--json"),s=(n[0]||"menu").toLowerCase(),i=n.slice(1);if(["-h","--help","help"].includes(s))return process.stdout.write(le()+`
45
- `),0;if(["menu","list","ls"].includes(s))return r?process.stdout.write(JSON.stringify({...B(o),modelAuth:U().status()},null,2)+`
46
- `):(process.stdout.write(F()),process.stdout.write(W(o))),0;if(["status","show"].includes(s)){let c=B(o);return r?process.stdout.write(JSON.stringify({...c,modelAuth:U().status()},null,2)+`
47
- `):(process.stdout.write(F()),process.stdout.write(W(o)),process.stdout.write(`hermes root: ${M()}
48
- `)),0}if(["model","oauth"].includes(s)){let c=String(i[0]||"").trim().toLowerCase();if(!c||["list","status","show"].includes(c))return process.stdout.write(F()),0;if(de.some(a=>a.id===c)||c==="custom")return Z.run({...e,argv:["api-key",c,...i.slice(1)]});try{return K(c),Z.run({...e,argv:["login",c,...i.slice(1)]})}catch(a){return process.stderr.write(`oracle setup model: ${a.message}
49
- `),process.stderr.write(F()),1}}if(["messaging","gateway-setup","platforms"].includes(s))return V({lastAction:"messaging",profile:o}),process.stdout.write(`opening hermes gateway setup wizard...
50
- `),pe(["-p",o,"gateway","setup"]);if(s==="gateway"){let c=(i[0]||"status").toLowerCase();return["status","start","stop","restart","run","install"].includes(c)?pe(["-p",o,"gateway",c]):(process.stderr.write(`usage: oracle setup gateway [status|start|stop|restart|run|install]
51
- `),1)}if(s==="profile"){let c=i[0]||o;return process.stdout.write(`profile: ${c}
52
- hermes: ${M()}/profiles/${c}
53
- `),process.stdout.write(W(c)),0}return D(s)?$t(o,s,i):(process.stderr.write(`oracle setup: unknown verb '${s}'
54
- ${le()}
55
- `),1)}};export{_r as default,F as renderModelSetup,Er as runFirstRunModelSetup};
45
+ `),0}catch(c){return process.stderr.write(`oracle setup: ${c.message}
46
+ `),1}}var Cr={name:"setup",summary:"configure standalone OAuth and messaging platforms",group:"read",usage:de(),async run(e){let t=[...e.argv],r=t.includes("--json"),o=Ct(t),n=Dt(t).filter(a=>a!=="--json"),s=(n[0]||"menu").toLowerCase(),i=n.slice(1);if(["-h","--help","help"].includes(s))return process.stdout.write(de()+`
47
+ `),0;if(["menu","list","ls"].includes(s))return r?process.stdout.write(JSON.stringify({...q(o),modelAuth:D().status()},null,2)+`
48
+ `):(process.stdout.write(K()),process.stdout.write(W(o))),0;if(["status","show"].includes(s)){let a=q(o);return r?process.stdout.write(JSON.stringify({...a,modelAuth:D().status()},null,2)+`
49
+ `):(process.stdout.write(K()),process.stdout.write(W(o)),process.stdout.write(`hermes root: ${M()}
50
+ `)),0}if(["model","oauth"].includes(s)){let a=String(i[0]||"").trim().toLowerCase();if(!a||["list","status","show"].includes(a))return process.stdout.write(K()),0;if(fe.some(c=>c.id===a)||a==="custom")return Z.run({...e,argv:["api-key",a,...i.slice(1)]});try{return F(a),Z.run({...e,argv:["login",a,...i.slice(1)]})}catch(c){return process.stderr.write(`oracle setup model: ${c.message}
51
+ `),process.stderr.write(K()),1}}if(["messaging","gateway-setup","platforms"].includes(s))return V({lastAction:"messaging",profile:o}),process.stdout.write(`opening hermes gateway setup wizard...
52
+ `),me(["-p",o,"gateway","setup"]);if(s==="gateway"){let a=(i[0]||"status").toLowerCase();return["status","start","stop","restart","run","install"].includes(a)?me(["-p",o,"gateway",a]):(process.stderr.write(`usage: oracle setup gateway [status|start|stop|restart|run|install]
53
+ `),1)}if(s==="profile"){let a=i[0]||o;return process.stdout.write(`profile: ${a}
54
+ hermes: ${M()}/profiles/${a}
55
+ `),process.stdout.write(W(a)),0}return j(s)?Ut(o,s,i):(process.stderr.write(`oracle setup: unknown verb '${s}'
56
+ ${de()}
57
+ `),1)}};export{he as SETUP_CHOICES,Cr as default,K as renderModelSetup,It as resolveSetupChoice,$r as runFirstRunModelSetup};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oracle-agent/oracle",
3
- "version": "0.28.1",
3
+ "version": "0.28.3",
4
4
  "description": "Oracle: standalone multichain agent control plane with an optional encrypted, loopback-only self-hosted signer.",
5
5
  "license": "BUSL-1.1",
6
6
  "type": "module",
package/public/install.sh CHANGED
@@ -13,7 +13,7 @@
13
13
  # What this installer never does:
14
14
  # - sign or broadcast transactions
15
15
  # - start a signer or import a key
16
- # - require Hermes or any other agent harness
16
+ # - never starts an external agent runtime
17
17
  # An explicit later `oracle signer` setup is a separate operator step.
18
18
  set -euo pipefail
19
19
 
@@ -33,23 +33,95 @@ err() { printf 'oracle-install: ERROR: %s\n' "$*" >&2; }
33
33
  die() { err "$*"; exit 1; }
34
34
  have() { command -v "$1" >/dev/null 2>&1; }
35
35
 
36
- # Mirror packages/oracle/src/tui/brand.mjs SPLASH_ORB. Hardcoded because
36
+ # Mirror packages/oracle/src/tui/brand.mjs SPLASH_ORB_FRAMES. Hardcoded because
37
37
  # this script runs before the package exists on disk.
38
38
  want_globe() {
39
39
  [ -t 1 ] && [ "${TERM:-}" != "dumb" ] && [ -z "${NO_COLOR:-}" ] && [ "${ORACLE_INSTALL_PLAIN:-0}" != 1 ]
40
40
  }
41
41
 
42
- print_globe() {
43
- want_globe || return 0
44
- cat <<'EOF'
45
-
42
+ print_globe_frame() {
43
+ local n="${1:-0}"
44
+ local status="${2:-installing}"
45
+ case "$n" in
46
+ 1)
47
+ cat <<EOF
48
+ ▓███▓ oracle
49
+ ▒▓▓█████ ${status}
50
+ ▒▒▓▓██████
51
+ ░▒▒▓▓▓▓▓
52
+ ░░▒▒▒▒
53
+ EOF
54
+ ;;
55
+ 2)
56
+ cat <<EOF
57
+ ▓▓███ oracle
58
+ ▒▓▓▓████ ${status}
59
+ ▒▒▓▓▓█████
60
+ ░▒▒▒▓▓▓▓
61
+ ░░░▒▒▒
62
+ EOF
63
+ ;;
64
+ 3)
65
+ cat <<EOF
66
+ ░▒▒▓▓ oracle
67
+ ░▒▒▓▓▓▓▓ ${status}
68
+ ░░▒▒▓▓████
69
+ ▓▓▓██████
70
+ █████▓
71
+ EOF
72
+ ;;
73
+ *)
74
+ cat <<EOF
46
75
  ███▓▓ oracle
47
- █████▓▓▒ installing
76
+ █████▓▓▒ ${status}
48
77
  ██████▓▓▒▒
49
78
  ▓▓▓▓▒▒▒░
50
79
  ▒▒▒░░░
51
-
52
80
  EOF
81
+ ;;
82
+ esac
83
+ }
84
+
85
+ print_globe() {
86
+ want_globe || return 0
87
+ printf '\n'
88
+ print_globe_frame 0 "installing"
89
+ printf '\n'
90
+ }
91
+
92
+ animate_while() {
93
+ local status="$1"
94
+ shift
95
+ if ! want_globe; then
96
+ "$@"
97
+ return $?
98
+ fi
99
+ local log rc pid i
100
+ log="$(mktemp)"
101
+ "$@" >"$log" 2>&1 &
102
+ pid=$!
103
+ i=0
104
+ printf '\033[?25l' || true
105
+ printf '\n'
106
+ print_globe_frame 0 "$status"
107
+ while kill -0 "$pid" 2>/dev/null; do
108
+ sleep 0.12
109
+ printf '\033[5A'
110
+ print_globe_frame "$((i % 4))" "$status"
111
+ i=$((i + 1))
112
+ done
113
+ set +e
114
+ wait "$pid"
115
+ rc=$?
116
+ set -e
117
+ printf '\033[5A'
118
+ print_globe_frame 0 "ready"
119
+ printf '\n\033[?25h' || true
120
+ if [ "$rc" -ne 0 ]; then
121
+ cat "$log" >&2
122
+ fi
123
+ rm -f "$log"
124
+ return "$rc"
53
125
  }
54
126
 
55
127
  usage() {
@@ -279,13 +351,12 @@ verify() {
279
351
  print_next() {
280
352
  cat <<EOF
281
353
 
282
- Oracle ready (hosted/default prepare-only · your wallet signs).
354
+ Oracle ready.
355
+
356
+ oracle
283
357
 
284
- oracle --version
285
- oracle setup model
286
- oracle chat
287
- oracle doctor --agentic
288
- oracle harness detect
358
+ That command opens sign-in: Claude, Codex, Grok, or an API key
359
+ (OpenRouter, DeepSeek, Nous, and the rest).
289
360
 
290
361
  Upgrade later:
291
362
  curl -fsSL https://oracle.demi.la/install.sh | bash
@@ -309,7 +380,7 @@ main() {
309
380
  ensure_node
310
381
  ensure_npm
311
382
  resolve_version
312
- install_package
383
+ animate_while installing install_package
313
384
  verify
314
385
  if [ "$DO_SETUP" = 1 ]; then
315
386
  export PATH="$BIN_DIR:$PATH"
@@ -29,10 +29,10 @@ section{padding-top:72px;scroll-margin-top:90px}.sub{color:var(--muted);line-hei
29
29
  <aside class="policy"><h2>Locals Only means 0% Oracle fees</h2><p>A Locals Only NFT waives the <b>Oracle integrator fee</b>. It does not unlock the product, waive provider or network costs, or change the hosted/keyless custody boundary. Self-host execution uses the local signer.</p></aside>
30
30
  <section id="cli"><p class="eyebrow">Oracle CLI</p><h2>Install with curl</h2><p class="sub">One line. Linux and macOS. Requires Node 20.19+ (the script checks and tells you how to get it). Installs into <code>~/.local</code> — no sudo, no global npm.</p><div class="install"><div class="cmd"><code id="cmd">curl -fsSL https://oracle.demi.la/install.sh | bash</code><button class="copy" id="copy" type="button">Copy</button></div><div class="meta"><span>curl install</span><span>hosted keyless</span><span>hosted wallet signs</span><span>user prefix</span></div></div><p class="sub" style="margin-top:18px">npm still works if you prefer: <code>npm i -g @oracle-agent/oracle</code></p></section>
31
31
  <section id="windows"><p class="eyebrow">Oracle app · Windows</p><h2>Install with PowerShell</h2><p class="sub">Same shape as Hermes: one line. Installs the CLI (<code>npm i -g @oracle-agent/oracle</code>) and the desktop NSIS build. SHA-256 checked. Never asks for a key or seed.</p><div class="install"><div class="cmd"><code id="cmd-win">iex (irm https://oracle.demi.la/install.ps1)</code><button class="copy" id="copy-win" type="button">Copy</button></div><div class="meta"><span>irm | iex</span><span>desktop app</span><span>SHA-256 checked</span></div></div></section>
32
- <section id="desktop"><p class="eyebrow">Desktop beta</p><h2>Native installers</h2><p class="sub">macOS, Linux, and Windows 0.4.6 bundle Oracle 0.25.2. These beta installers are not CA-signed, so platform warnings are expected. Download directly, then verify against the published SHA-256 manifest.</p><div class="artifacts">
33
- <div class="artifact" data-artifact="Oracle-0.4.6.AppImage"><div><h3>Linux</h3><small>AppImage · x64</small></div><div class="artifact-meta"><span class="build">Oracle 0.4.6 beta · runtime 0.25.2</span></div><code class="hash" data-hash>checksum loading</code><a class="dl-btn" href="/downloads/artifacts/Oracle-0.4.6.AppImage" download>Download</a></div>
34
- <div class="artifact" data-artifact="Oracle-0.4.6-arm64.dmg"><div><h3>macOS</h3><small>DMG · Apple silicon</small></div><div class="artifact-meta"><span class="build">Oracle 0.4.6 beta · runtime 0.25.2</span></div><code class="hash" data-hash>checksum loading</code><a class="dl-btn" href="/downloads/artifacts/Oracle-0.4.6-arm64.dmg" download>Download</a></div>
35
- <div class="artifact" data-artifact="Oracle-Setup-0.4.6.exe"><div><h3>Windows</h3><small>NSIS installer · x64</small></div><div class="artifact-meta"><span class="build">Oracle 0.4.6 beta · runtime 0.25.2</span></div><code class="hash" data-hash>checksum loading</code><a class="dl-btn" href="/downloads/artifacts/Oracle-Setup-0.4.6.exe" download>Download</a></div>
32
+ <section id="desktop"><p class="eyebrow">Desktop beta</p><h2>Native installers</h2><p class="sub">macOS, Linux, and Windows 0.4.8 bundle Oracle 0.28.1. These beta installers are not CA-signed, so platform warnings are expected. Download directly, then verify against the published SHA-256 manifest.</p><div class="artifacts">
33
+ <div class="artifact" data-artifact="Oracle-0.4.8.AppImage"><div><h3>Linux</h3><small>AppImage · x64</small></div><div class="artifact-meta"><span class="build">Oracle 0.4.8 beta · runtime 0.28.1</span></div><code class="hash" data-hash>checksum loading</code><a class="dl-btn" href="/downloads/artifacts/Oracle-0.4.8.AppImage" download>Download</a></div>
34
+ <div class="artifact" data-artifact="Oracle-0.4.8-arm64.dmg"><div><h3>macOS</h3><small>DMG · Apple silicon</small></div><div class="artifact-meta"><span class="build">Oracle 0.4.8 beta · runtime 0.28.1</span></div><code class="hash" data-hash>checksum loading</code><a class="dl-btn" href="/downloads/artifacts/Oracle-0.4.8-arm64.dmg" download>Download</a></div>
35
+ <div class="artifact" data-artifact="Oracle-Setup-0.4.8.exe"><div><h3>Windows</h3><small>NSIS installer · x64</small></div><div class="artifact-meta"><span class="build">Oracle 0.4.8 beta · runtime 0.28.1</span></div><code class="hash" data-hash>checksum loading</code><a class="dl-btn" href="/downloads/artifacts/Oracle-Setup-0.4.8.exe" download>Download</a></div>
36
36
  </div><p class="platform-note">Checksums: <a class="checksum" href="/downloads/artifacts/SHA256SUMS.txt">SHA256SUMS.txt</a>. Beta installers may trigger macOS Gatekeeper or Windows SmartScreen when a build is not notarized or CA-signed. The installer never asks for a private key or seed. Hosted/keyless cannot hold keys. Self-host signer setup is a separate command.</p></section>
37
37
  </main>
38
38
  <footer><div class="nav-inner"><span>oracle · locals only labs</span><span>public / self-custody / local signer</span></div></footer>
@@ -1798,7 +1798,7 @@ footer{margin-top:clamp(72px,12vh,120px);border-top:1px solid var(--line);paddin
1798
1798
  <img src="assets/desktop-app.jpg" width="1736" height="959" loading="lazy" decoding="async" alt="Oracle desktop app showing the specialist mesh, with Portfolio, Approvals, Prepare, CLI, Farming Methods, Agent Connect, Receipts, Campaigns and Routes panes.">
1799
1799
  <figcaption>Portfolio, approvals, prepare, farming, receipts and routes in one pane.</figcaption>
1800
1800
  </figure>
1801
- <div class="os-dl"><a class="os-link" href="/downloads/artifacts/Oracle-0.4.6-arm64.dmg">macOS</a><a class="os-link" href="/downloads/artifacts/Oracle-0.4.6.AppImage">Linux</a><a class="os-link" href="/downloads/artifacts/Oracle-Setup-0.4.6.exe">Windows</a></div>
1801
+ <div class="os-dl"><a class="os-link" href="/downloads/artifacts/Oracle-0.4.8-arm64.dmg">macOS</a><a class="os-link" href="/downloads/artifacts/Oracle-0.4.8.AppImage">Linux</a><a class="os-link" href="/downloads/artifacts/Oracle-Setup-0.4.8.exe">Windows</a></div>
1802
1802
  <div class="cli-install-cmd" style="margin-top:14px"><code>iex (irm https://oracle.demi.la/install.ps1)</code> <span class="cli-install-hint">Windows · CLI + Oracle app</span></div>
1803
1803
  </div>
1804
1804
  </div>