@oracle-agent/oracle 0.35.31 → 0.35.34
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.
- package/README.md +19 -1
- package/dist/agent-lifecycle.mjs +3 -3
- package/dist/agent-sessions.mjs +7 -7
- package/dist/assets/skills/oracle-desk-product/SKILL.md +1 -1
- package/dist/bin/desk-server.mjs +37 -37
- package/dist/bin/oracle-data-mcp.mjs +17 -17
- package/dist/bin/oracle-gateway.mjs +16 -16
- package/dist/bin/oracle-investigate.mjs +11 -0
- package/dist/bin/oracle-launch-radar-shadow.mjs +6 -6
- package/dist/bin/oracle-mev-arb-shadow.mjs +6 -6
- package/dist/bin/oracle-mev-shadow.mjs +6 -6
- package/dist/bin/oracle-public-server.mjs +5 -5
- package/dist/bin/oracle-route.mjs +22 -22
- package/dist/bin/oracle-scan.mjs +15 -15
- package/dist/cli/commands/agent-session.mjs +7 -7
- package/dist/cli/commands/auth.mjs +17 -16
- package/dist/cli/commands/chat.mjs +208 -198
- package/dist/cli/commands/context.mjs +6 -6
- package/dist/cli/commands/doctor.mjs +9 -9
- package/dist/cli/commands/eval.mjs +104 -95
- package/dist/cli/commands/farm.mjs +22 -22
- package/dist/cli/commands/follow.mjs +16 -16
- package/dist/cli/commands/harness.mjs +1 -1
- package/dist/cli/commands/lifecycle.mjs +6 -6
- package/dist/cli/commands/model.mjs +212 -202
- package/dist/cli/commands/quickstart.mjs +7 -7
- package/dist/cli/commands/receipt.mjs +12 -12
- package/dist/cli/commands/resolve.mjs +12 -12
- package/dist/cli/commands/setup.mjs +57 -56
- package/dist/cli/commands/sign.mjs +15 -13
- package/dist/cli/commands/signer.mjs +19 -19
- package/dist/cli/commands/snipe.mjs +11 -11
- package/dist/cli/commands/strategy.mjs +5 -5
- package/dist/cli/commands/swap.mjs +31 -31
- package/dist/cli/commands/venues.mjs +2 -2
- package/dist/context-graph.mjs +3 -3
- package/dist/data/desk-data.mjs +35 -35
- package/dist/data/names.mjs +3 -3
- package/dist/data/providers/farming.mjs +2 -2
- package/dist/data/providers/lp-destination-discovery.mjs +4 -4
- package/dist/index.mjs +49 -49
- package/dist/investigator/index.mjs +2 -0
- package/dist/launch-radar/index.mjs +5 -5
- package/dist/local-signer/anvil-attestation-worker.mjs +1 -1
- package/dist/local-signer/index.mjs +3 -3
- package/dist/local-signer/runtime.mjs +19 -19
- package/dist/nft/universal-mint-router.mjs +4 -4
- package/dist/router/index.mjs +3 -3
- package/dist/router/prepare-bridge.mjs +2 -2
- package/dist/scanner/index.mjs +4 -4
- package/dist/strategy/index.mjs +3 -3
- package/dist/tui/standalone-client.mjs +77 -68
- package/package.json +3 -1
- package/public/eval-report.json +2 -2
- package/public/oracle-splash/index.html +2 -2
- package/server.json +2 -2
|
@@ -1,72 +1,73 @@
|
|
|
1
|
-
import{spawnSync as
|
|
1
|
+
var Yt=Object.defineProperty;var Vt=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Jt=(e,t)=>{for(var n in t)Yt(e,n,{get:t[n],enumerable:!0})};var vt={};Jt(vt,{OAUTH_USAGE_PROVIDERS:()=>Bn,collectOAuthUsage:()=>Hn,parseAnthropicUsage:()=>kt,parseCodexUsage:()=>xt});function bt(e){let t=Number(e);return Number.isFinite(t)?t:null}function Kn(e){let t=bt(e);if(t==null)return null;let n=t<=1?t*100:t;return Math.max(0,Math.min(100,n))}function kt(e){let t=[["five_hour","5h"],["seven_day","7d"],["seven_day_opus","Opus 7d"],["seven_day_sonnet","Sonnet 7d"]],n=[];for(let[r,o]of t){let s=e?.[r]||{},i=Kn(s.utilization);i!=null&&n.push({label:o,usedPercent:i,resetAt:s.resets_at||s.reset_at||null})}return{source:"oauth_usage_api",windows:n}}function xt(e){let t=e?.rate_limit||{},n=[["primary_window","5h"],["secondary_window","wk"]],r=[];for(let[o,s]of n){let i=t[o]||{},a=bt(i.used_percent);a!=null&&r.push({label:s,usedPercent:Math.max(0,Math.min(100,a)),resetAt:i.reset_at||i.resets_at||null})}return{source:"usage_api",windows:r}}function Q({id:e,label:t,connected:n,windows:r=[],unavailable:o=null}){let s=r[0]||null;return{id:e,label:t,connected:n,usedPercent:s?s.usedPercent:null,windowLabel:s?s.label:null,resetAt:s?s.resetAt:null,windows:r,unavailable:o}}function Je(e,t){try{return String(e?.get?.(t)?.accessToken||"").trim()}catch{return""}}async function wt(e,t,n){let r=await e(t,{headers:n});if(!r?.ok)throw new Error(`HTTP ${r?.status||0}`);return r.json()}async function Hn(e,{fetchFn:t=globalThis.fetch}={}){let n=new Date().toISOString(),r=[],o=Je(e,"anthropic-oauth");if(!o)r.push(Q({id:"anthropic-oauth",label:"Claude",connected:!1,unavailable:"not connected"}));else try{let a=await wt(t,"https://api.anthropic.com/api/oauth/usage",{Authorization:`Bearer ${o}`,Accept:"application/json","anthropic-beta":"oauth-2025-04-20","User-Agent":"claude-code/2.1.0"}),c=kt(a);r.push(Q({id:"anthropic-oauth",label:"Claude",connected:!0,windows:c.windows,unavailable:c.windows.length?null:"quota unavailable"}))}catch{r.push(Q({id:"anthropic-oauth",label:"Claude",connected:!0,unavailable:"quota unavailable"}))}let s=Je(e,"openai-codex");if(!s)r.push(Q({id:"openai-codex",label:"Codex",connected:!1,unavailable:"not connected"}));else try{let a=await wt(t,"https://chatgpt.com/backend-api/wham/usage",{Authorization:`Bearer ${s}`,Accept:"application/json","User-Agent":"codex-cli"}),c=xt(a);r.push(Q({id:"openai-codex",label:"Codex",connected:!0,windows:c.windows,unavailable:c.windows.length?null:"quota unavailable"}))}catch{r.push(Q({id:"openai-codex",label:"Codex",connected:!0,unavailable:"quota unavailable"}))}let i=Je(e,"xai-oauth");return r.push(Q({id:"xai-oauth",label:"Grok",connected:!!i,unavailable:i?"quota not published":"not connected"})),{fetchedAt:n,providers:r}}var Bn,St=Vt(()=>{Bn=Object.freeze([{id:"anthropic-oauth",label:"Claude"},{id:"openai-codex",label:"Codex"},{id:"xai-oauth",label:"Grok"}])});import{spawnSync as pr}from"node:child_process";import{stdin as G,stdout as qt}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 at(e){return String(e||"").trim().toLowerCase().replace(/^\/+/,"").replace(/\s+/g,"-")}function ee(){return De.slice()}function Y(e){let t=at(e);if(!t)return null;for(let n of De)if(n.key===t||at(n.name)===t)return n;return null}function ct({profile:e="oracle",statuses:t={}}={}){let n=["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 r of De){let o=t[r.key]||"unset";n.push(` ${r.key.padEnd(16)} ${String(o).padEnd(8)} ${r.note}`)}return n.push(""),n.push("commands:"),n.push(" oracle setup this menu"),n.push(" oracle setup model standalone OAuth / API keys"),n.push(" oracle setup messaging open hermes gateway setup wizard"),n.push(" oracle setup telegram set TELEGRAM_BOT_TOKEN (stdin or --token)"),n.push(" oracle setup discord set DISCORD_BOT_TOKEN"),n.push(" oracle setup whatsapp qr link via hermes"),n.push(" oracle setup slack bot + app tokens"),n.push(" oracle setup status show configured platforms (no secrets)"),n.push(" oracle setup gateway start/status/restart hermes gateway"),n.push(" /setup same menu inside the tui"),n.push(" /setup telegram|discord|whatsapp channel how-to (no secrets)"),n.push(""),n.push("notes:"),n.push(" tokens stay in the hermes profile .env on this machine"),n.push(" oracle never prints bot tokens or app secrets"),n.push(' pipe tokens: echo "$TOKEN" | oracle setup telegram'),n.push(" after token setup: oracle setup gateway restart"),n.join(`
|
|
2
2
|
`)+`
|
|
3
|
-
`}import D from"node:fs";import
|
|
4
|
-
`),{mode:384});try{D.chmodSync(
|
|
5
|
-
`,{mode:384}),
|
|
6
|
-
`,{mode:384}),L.renameSync(r,e),process.platform!=="win32"&&L.chmodSync(e,384)}function pr(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 mr(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||lr,i=e.keychain!==!1&&process.env.ORACLE_AUTH_FILE_STORE!=="1"&&pr(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 S=x.credential_pool&&typeof x.credential_pool=="object"?x.credential_pool:null;if(S){let C=S[w]||S[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()+fr)||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 S=P(r,{providers:{}});return S.providers||={},S.providers[p]={expiresAt:f.expiresAt,source:f.source},z(r,S),f}let h=P(t,{providers:{}});return h.providers||={},h.providers[p]=f,z(t,h),f}function v(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 S=P(r,{providers:{},apiKeys:{}});return S.apiKeys||={},S.apiKeys[p]={configured:!0},z(r,S),!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:v,getApiKey:M,setApiKey:k,removeApiKey:A,status:B,withLock:l})}var pt;function U(){return pt||=mr(),pt}function qe(e){return Buffer.from(e).toString("base64url")}function hr(){let e=qe(ze(32));return{verifier:e,challenge:qe(ir("sha256").update(e).digest()),state:qe(ze(24))}}function gr(e,t){let r=Buffer.from(String(e||"")),n=Buffer.from(String(t||""));return r.length===n.length&&ar(r,n)}function yr(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 ur(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 wr(e){if(e)return String(await e()).trim();let t=cr.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:dr(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 br(e){let t=ae["anthropic-oauth"],r=e.pkce||hr(),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 wr(e.inputFn),[i,a]=s.split("#",2);if(!i||!gr(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 kr(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 xr(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||yr,output:t.output||(o=>process.stdout.write(`${o}
|
|
7
|
-
`)),now:t.now,pkce:t.pkce};return
|
|
8
|
-
`,{mode:384}),Me.renameSync(n
|
|
3
|
+
`}import D from"node:fs";import rn from"node:os";import je from"node:path";import fe from"node:fs";import Xt from"node:os";import q from"node:path";import{fileURLToPath as Zt}from"node:url";var Qt=q.dirname(Zt(import.meta.url)),Ar=q.resolve(Qt,"../..");function ne(){return process.env.ORACLE_FAKE_HOME||Xt.homedir()}function en(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function N(){return en()?process.env.ORACLE_CONFIG_DIR||q.join(ne(),".config","oracle"):q.join(ne(),".config","oracle")}function tn(){return q.join(N(),"desk.json")}function nn(){return q.join(N(),"env")}function te({force:e=!1}={}){if(te._done&&!e)return te._result||null;te._done=!0;let t={},n=(o,s)=>{if(s==null)return;let i=String(s).trim();i&&(process.env[o]!=null&&String(process.env[o]).trim()!==""||(process.env[o]=i,t[o]=i))};try{let o=nn();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)),n(i[1],a)}}catch{}try{let o=tn();if(fe.existsSync(o)){let s=JSON.parse(fe.readFileSync(o,"utf8"));s&&typeof s=="object"&&(n("ORACLE_DESK_URL",s.deskUrl||s.dataUrl||s.url),n("ORACLE_DATA_URL",s.dataUrl||s.deskUrl||s.url),n("ORACLE_API_URL",s.apiUrl||s.dataUrl||s.deskUrl),n("ORACLE_PUBLIC_URL",s.publicUrl||s.deskUrl||s.dataUrl),n("ORACLE_EXEC_URL",s.execUrl),n("MAD_DESK_URL",s.deskUrl||s.dataUrl))}}catch{}let r=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return r&&(n("ORACLE_DESK_URL",r),n("ORACLE_DATA_URL",r),n("ORACLE_API_URL",r),n("ORACLE_PUBLIC_URL",r),n("MAD_DESK_URL",r)),te._result=Object.keys(t).length?t:null,te._result}try{te()}catch{}function pe(){return process.env.HERMES_HOME?q.resolve(process.env.HERMES_HOME):q.join(ne(),".hermes")}function F(e){return fe.mkdirSync(e,{recursive:!0}),e}var on=/(TOKEN|SECRET|PASSWORD|KEY|AUTH|PRIVATE|MNEMONIC|SEED)/i;function xe(e="oracle"){return je.join(pe(),"profiles",e,".env")}function sn(e){let t={};for(let n of String(e||"").split(/\r?\n/)){let r=n.trim();if(!r||r.startsWith("#"))continue;let o=r.indexOf("=");if(o<=0)continue;let s=r.slice(0,o).trim(),i=r.slice(o+1).trim();(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),t[s]=i}return t}function lt(e="oracle"){let t=xe(e);return D.existsSync(t)?sn(D.readFileSync(t,"utf8")):{}}function ut(e,t,n){if(!t||on.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(n==null||String(n).trim()===""){let l=new Error(`empty value for ${t}`);throw l.code="EMPTY",l}let r=xe(e);F(je.dirname(r));let o=D.existsSync(r)?D.readFileSync(r,"utf8"):"",s=o?o.split(/\r?\n/):[],i=[],a=!1,c=`${t}=${String(n)}`;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(""),D.writeFileSync(r,i.join(`
|
|
4
|
+
`),{mode:384});try{D.chmodSync(r,384)}catch{}return{path:r,key:t,set:!0}}function re(e="oracle"){let t=lt(e),n={};for(let r of ee()){if(!r.required.length){n[r.key]="manual";continue}let o=r.required.filter(s=>!String(t[s]||"").trim());n[r.key]=o.length?"unset":"ready"}return{profile:e,statuses:n,envPath:xe(e)}}function ve(e="oracle"){let{statuses:t}=re(e);return ct({profile:e,statuses:t})}function Se(e,t,n,r={}){let o=Y(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(r||{}).filter(u=>r[u]!=null&&String(r[u]).trim())]),c=lt(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}ut(e,i,n);for(let[u,y]of Object.entries(r||{}))y!=null&&String(y).trim()&&ut(e,u,y);return{platform:o.key,set:o.required,profile:e,path:xe(e)}}function an(){return je.join(N(),"setup-state.json")}function V(e={}){F(N());let t=an(),n={};if(D.existsSync(t))try{n=JSON.parse(D.readFileSync(t,"utf8"))}catch{n={}}let r={...n,...e,updatedAt:new Date().toISOString(),host:rn.hostname()};return D.writeFileSync(t,JSON.stringify(r,null,2)+`
|
|
5
|
+
`,{mode:384}),r}import R from"node:fs";import M from"node:path";import{createHash as cn}from"node:crypto";import{spawnSync as se}from"node:child_process";var un="0.19.0",dt=`hermes-agent==${un}`,Ue=[3,11],Be=[3,14],he="3.13",Ae="0.12.1",Ee=Object.freeze({posix:Object.freeze({url:`https://github.com/astral-sh/uv/releases/download/${Ae}/uv-installer.sh`,sha256:"d3f5412d38c99f9d024901843bf98206f0d2c6dbe64df40d0b740e2751ca62c1"}),windows:Object.freeze({url:`https://github.com/astral-sh/uv/releases/download/${Ae}/uv-installer.ps1`,sha256:"b9ec035151bfbb11d616dbd69886498d885551489eddf095ea3c0ad59f640eb0"})});function ln(e,{windows:t=process.platform==="win32"}={}){let n=Buffer.isBuffer(e)?e:Buffer.from(e),r=t?Ee.windows:Ee.posix,o=cn("sha256").update(n).digest("hex"),s=n.toString("utf8");return o===r.sha256&&s.length>=1e3&&s.includes(Ae)}function J(){return M.join(N(),"runtime")}function pt(){return M.join(J(),"venv")}function He(e){let t=process.platform==="win32"?"Scripts":"bin",n=process.platform==="win32"?`${e}.exe`:e;return M.join(pt(),t,n)}function _e(){return He("hermes")}function dn(){let e=He("python3");return R.existsSync(e)?e:He("python")}function me(){return M.join(J(),"uv",process.platform==="win32"?"uv.exe":"uv")}function oe(e){let t=process.platform==="win32"&&!M.extname(e)?["",".exe",".cmd",".bat"]:[""];for(let n of(process.env.PATH||"").split(M.delimiter))if(n)for(let r of t){let o=M.join(n,`${e}${r}`);try{if(R.existsSync(o))return o}catch{}}return null}function fn(e){let t=/Python (\d+)\.(\d+)\.(\d+)/.exec(e||"");return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function pn(e){if(!e)return!1;let[t,n]=e;return!(t<Ue[0]||t===Ue[0]&&n<Ue[1]||t>Be[0]||t===Be[0]&&n>=Be[1])}function hn(){let e=[process.env.ORACLE_PYTHON,"python3.13","python3.12","python3.11","python3","python"].filter(Boolean);for(let t of e){let n=M.isAbsolute(t)?R.existsSync(t)?t:null:oe(t);if(!n)continue;let r=se(n,["--version"],{encoding:"utf8",timeout:15e3}),o=fn(`${r.stdout||""}${r.stderr||""}`);if(pn(o))return{bin:n,version:o.join("."),source:"host"}}return null}function mn(){return process.env.ORACLE_UV_BIN||oe("uv")||(R.existsSync(M.join(ne(),".local","bin","uv"))?M.join(ne(),".local","bin","uv"):null)||(R.existsSync(me())?me():null)}function gn(e,t){let n=["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 se(process.execPath,["-e",n,e,t],{encoding:"utf8",timeout:2*6e4})}function yn({quiet:e=!1}={}){let t=mn();if(t)return{ok:!0,bin:t,reused:!0};F(J());let n=process.platform==="win32",r=M.join(J(),n?"uv-install.ps1":"uv-install.sh"),o=n?Ee.windows:Ee.posix,s=gn(o.url,r);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(r);if(!ln(i,{windows:n}))return{ok:!1,reason:`uv ${Ae} installer checksum mismatch`};let a=M.dirname(me());F(a);let c=n?oe("powershell.exe")||oe("powershell"):oe("sh")||"/bin/sh";if(!c)return{ok:!1,reason:n?"PowerShell not found":"sh not found"};let u=se(c,n?["-NoProfile","-ExecutionPolicy","Bypass","-File",r]:[r],{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 ft({quiet:e=!1}={}){let t=yn({quiet:e});if(!t.ok)return t;let n=t.bin,r={...process.env,UV_PYTHON_INSTALL_DIR:M.join(J(),"python"),UV_CACHE_DIR:M.join(J(),"cache")},o=se(n,["python","install","--no-bin",he],{stdio:e?"pipe":"inherit",encoding:"utf8",timeout:15*6e4,env:r});if(o.status!==0)return{ok:!1,reason:`uv python install ${he} failed (${o.status})`,stderr:(o.stderr||"").slice(-800)};let s=se(n,["python","find",he],{encoding:"utf8",timeout:6e4,env:r}),i=(s.stdout||"").trim().split(/\r?\n/)[0];return s.status!==0||!i||!R.existsSync(i)?{ok:!1,reason:`uv could not locate python ${he}`}:{ok:!0,bin:i,version:he,source:"uv"}}function ie(){if(process.env.ORACLE_HERMES_BIN)return{ok:!0,bin:process.env.ORACLE_HERMES_BIN,source:"env"};let e=_e();if(R.existsSync(e))return{ok:!0,bin:e,source:"managed"};let t=oe("hermes");return t?{ok:!0,bin:t,source:"path"}:{ok:!1,bin:null,source:null}}function Ke(e,t,{quiet:n}){return se(e,t,{stdio:n?"pipe":"inherit",encoding:"utf8",timeout:20*6e4})}function ht({quiet:e=!1,upgrade:t=!1}={}){let n=hn();if(!n){let l=ft({quiet:e});if(l.ok)n={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'`}}F(J());let r=pt();if(R.existsSync(_e())&&!t)return{ok:!0,bin:_e(),reused:!0};if(!R.existsSync(M.join(r,"pyvenv.cfg"))){let l=Ke(n.bin,["-m","venv",r],{quiet:e});if(l.status!==0&&n.source!=="uv"){R.rmSync(r,{recursive:!0,force:!0});let u=ft({quiet:e});if(u.ok)n={bin:u.bin,version:u.version,source:"uv"},l=Ke(n.bin,["-m","venv",r],{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=dn();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(dt);let a=Ke(s,i,{quiet:e});if(a.status!==0)return{ok:!1,reason:`pip install ${dt} failed (${a.status})`,stderr:(a.stderr||"").slice(-1200)};let c=_e();return R.existsSync(c)?{ok:!0,bin:c,reused:!1,python:n.version}:{ok:!1,reason:`hermes entrypoint not found after install (${c})`}}import{createHash as wn,randomBytes as We,timingSafeEqual as bn}from"node:crypto";import L from"node:fs";import j from"node:path";import kn from"node:readline/promises";import{spawn as xn,spawnSync as vn}from"node:child_process";var ce=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"}}),Sn=12e4;function _n(e={}){return typeof e.now=="function"?Number(e.now()):Date.now()}function X(e){let t=String(e||"").trim().toLowerCase();for(let[n,r]of Object.entries(ce))if(r.aliases.includes(t))return n;throw new Error(`unsupported OAuth provider: ${e||"(empty)"}`)}function W(e){let t=X(e);return{id:t,...ce[t]}}function P(e,t={}){if(!L.existsSync(e))return t;try{let n=JSON.parse(L.readFileSync(e,"utf8"));if(!n||typeof n!="object"||Array.isArray(n))throw new Error("invalid object");return n}catch{throw new Error(`credential store is unreadable or corrupt: ${j.basename(e)}`)}}function gt(e){F(e),process.platform!=="win32"&&L.chmodSync(e,448)}function z(e,t){gt(j.dirname(e));let n=`${e}.${process.pid}.${We(4).toString("hex")}.tmp`;L.writeFileSync(n,`${JSON.stringify(t,null,2)}
|
|
6
|
+
`,{mode:384}),L.renameSync(n,e),process.platform!=="win32"&&L.chmodSync(e,384)}function An(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 qe(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 ae(e={}){let t=String(e.accessToken||e.access_token||"").trim(),n=String(e.refreshToken||e.refresh_token||"").trim(),r=Number(e.expiresAt||e.expires_at||0);if(Number.isFinite(r)&&r>=1e9&&r<1e12&&(r=r*1e3),!t)throw new Error("OAuth credential is missing access token");return{accessToken:t,refreshToken:n,expiresAt:Number.isFinite(r)?r:0,tokenType:String(e.tokenType||e.token_type||"Bearer"),source:String(e.source||"oracle"),...e.discovery?{discovery:e.discovery}:{},...e.scope?{scope:e.scope}:{},...e.idToken||e.id_token?{idToken:String(e.idToken||e.id_token)}:{}}}function En(e={}){let t=e.file||j.join(N(),"oauth.json"),n=e.metadataFile||j.join(j.dirname(t),"oauth-meta.json"),r=e.linksFile||j.join(j.dirname(t),"oauth-links.json"),o=()=>typeof e.now=="function"?Number(e.now()):Date.now(),s=e.spawnFn||vn,i=e.keychain!==!1&&process.env.ORACLE_AUTH_FILE_STORE!=="1"&&An(s),a=i?"linux-secret-service":"private-file",c=`${t}.lock`;async function l(w){gt(j.dirname(c));let g;for(let p=0;p<400;p+=1)try{g=L.openSync(c,"wx",384);break}catch(d){if(d?.code!=="EEXIST")throw d;try{Date.now()-L.statSync(c).mtimeMs>3e5&&L.unlinkSync(c)}catch{}await new Promise(m=>setTimeout(m,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(r))return null;let p=P(r,{providers:{}}).providers?.[w];if(!Array.isArray(p))return null;let d=[];for(let m of p)if(j.isAbsolute(String(m||"")))try{let x=P(m,{});if(w==="anthropic-oauth"&&x.claudeAiOauth){let C=ae(x.claudeAiOauth);d.push({...C,refreshToken:"",source:"external-access-only"});continue}let S=x.credential_pool&&typeof x.credential_pool=="object"?x.credential_pool:null;if(S){let C=S[w]||S[w.replace(/-oauth$/,"")]||[],K=Array.isArray(C)?C:C?[C]:[];for(let H of K)if(!(!H||typeof H!="object"))try{let Fe=ae(H);d.push({...Fe,refreshToken:"",source:"external-access-only"})}catch{}}}catch{}return d.length?d.find(m=>!m.expiresAt||m.expiresAt>o()+Sn)||d[0]:null}function h(w){let g=X(w);if(i){let m=s("secret-tool",["lookup",...u(g)],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(!m.error&&m.status===0&&String(m.stdout||"").trim())try{return ae(JSON.parse(String(m.stdout).trim()))}catch{}return y(g)}let d=P(t,{providers:{}}).providers?.[g];if(d)try{return ae(d)}catch{}return y(g)}function O(w,g){let p=X(w),d=ae(g);if(i){let x=s("secret-tool",["store",`--label=Oracle ${p} OAuth`,...u(p)],{input:JSON.stringify(d),encoding:"utf8",stdio:["pipe","ignore","pipe"]});if(x.error||x.status!==0)throw new Error("OS credential store rejected OAuth credential");let S=P(n,{providers:{}});return S.providers||={},S.providers[p]={expiresAt:d.expiresAt,source:d.source},z(n,S),d}let m=P(t,{providers:{}});return m.providers||={},m.providers[p]=d,z(t,m),d}function v(w){let g=X(w);if(i){let m=s("secret-tool",["clear",...u(g)],{encoding:"utf8",stdio:["ignore","ignore","pipe"]}),x=P(n,{providers:{}});return x.providers&&delete x.providers[g],z(n,x),!m.error&&m.status===0}let p=P(t,{providers:{}}),d=!!p.providers?.[g];return p.providers&&delete p.providers[g],z(t,p),d}function T(w){let g=qe(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=qe(w),d=String(g||"").trim();if(!d)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:d,encoding:"utf8",stdio:["pipe","ignore","pipe"]});if(x.error||x.status!==0)throw new Error("OS credential store rejected API key");let S=P(n,{providers:{},apiKeys:{}});return S.apiKeys||={},S.apiKeys[p]={configured:!0},z(n,S),!0}let m=P(t,{providers:{},apiKeys:{}});return m.apiKeys||={},m.apiKeys[p]=d,z(t,m),!0}function A(w){let g=qe(w);if(i){let m=s("secret-tool",["clear",...u(g,"api-key")],{encoding:"utf8",stdio:["ignore","ignore","pipe"]}),x=P(n,{providers:{},apiKeys:{}});return x.apiKeys&&delete x.apiKeys[g],z(n,x),!m.error&&m.status===0}let p=P(t,{providers:{},apiKeys:{}}),d=!!p.apiKeys?.[g];return p.apiKeys&&delete p.apiKeys[g],z(t,p),d}function B(){let w={},g={};if(i){let p=P(n,{providers:{},apiKeys:{}});for(let[d,m]of Object.entries(p.providers||{}))w[d]={loggedIn:!!h(d),expiresAt:Number(m.expiresAt||0),source:String(m.source||"oracle"),storage:a};for(let d of Object.keys(p.apiKeys||{}))g[d]={configured:!!T(d),storage:a}}else{let p=P(t,{providers:{},apiKeys:{}});for(let[d,m]of Object.entries(p.providers||{}))w[d]={loggedIn:!!m?.accessToken,expiresAt:Number(m?.expiresAt||0),source:String(m?.source||"oracle"),storage:a};for(let[d,m]of Object.entries(p.apiKeys||{}))g[d]={configured:!!m,storage:a}}for(let p of Object.keys(ce)){if(w[p])continue;let d=y(p);d&&(w[p]={loggedIn:!0,expiresAt:d.expiresAt,source:d.source,storage:"external-access-source"})}return{storage:a,providers:w,apiKeys:g}}return Object.freeze({file:t,storage:a,get:h,set:O,remove:v,getApiKey:T,setApiKey:k,removeApiKey:A,status:B,withLock:l})}var mt;function U(){return mt||=En(),mt}function ze(e){return Buffer.from(e).toString("base64url")}function $n(){let e=ze(We(32));return{verifier:e,challenge:ze(wn("sha256").update(e).digest()),state:ze(We(24))}}function On(e,t){let n=Buffer.from(String(e||"")),r=Buffer.from(String(t||""));return n.length===r.length&&bn(n,r)}function Tn(e){let t=String(e),n=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd.exe",["/d","/s","/c","start","",t]]:["xdg-open",[t]];try{return xn(n[0],n[1],{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function Ge(e){return new URLSearchParams(e).toString()}async function Z(e,t){if(!e?.ok){let r="";try{r=String((await e.json())?.error||"")}catch{}throw new Error(`${t} failed (HTTP ${e?.status||"unknown"}${r?`, ${r}`:""})`)}let n=await e.json();if(!n||typeof n!="object")throw new Error(`${t} returned invalid JSON`);return n}async function Mn(e){if(e)return String(await e()).trim();let t=kn.createInterface({input:process.stdin,output:process.stdout});try{return String(await t.question("Authorization code: ")).trim()}finally{t.close()}}function Ye(e,t={}){let n=String(e.access_token||"").trim(),r=String(e.refresh_token||t.refreshToken||"").trim();if(!n)throw new Error("OAuth token response is missing access token");let o=Number(e.expires_in||3600);return ae({accessToken:n,refreshToken:r,expiresAt:_n(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 Rn(e){let t=ce["anthropic-oauth"],n=e.pkce||$n(),r=new URLSearchParams({code:"true",client_id:t.clientId,response_type:"code",redirect_uri:t.redirectUri,scope:t.scope,code_challenge:n.challenge,code_challenge_method:"S256",state:n.state}),o=`${t.authorizeUrl}?${r}`;e.output(`Open: ${o}`),e.openFn(o);let s=await Mn(e.inputFn),[i,a]=s.split("#",2);if(!i||!On(a,n.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:n.verifier})});return Ye(await Z(c,"Claude OAuth token exchange"),e)}async function Pn(e){let t=ce["openai-codex"],n=await Z(await e.fetchFn(`${t.issuer}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({client_id:t.clientId})}),"Codex device authorization");if(!n.user_code||!n.device_auth_id)throw new Error("Codex device authorization returned incomplete data");let r=`${t.issuer}/codex/device`;e.output(`Open: ${r}`),e.output(`Code: ${n.user_code}`),e.openFn(r);let o=Math.max(3,Number(n.interval||5)),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:n.device_auth_id,user_code:n.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:Ge({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 $e(e){let t=new URL(String(e)),n=t.hostname.toLowerCase();if(t.protocol!=="https:"||n!=="x.ai"&&!n.endsWith(".x.ai"))throw new Error("xAI OAuth discovery returned an untrusted endpoint");return t.toString()}async function In(e){let t=ce["xai-oauth"],n=await Z(await e.fetchFn(t.discoveryUrl,{headers:{accept:"application/json"}}),"xAI OAuth discovery");$e(n.authorization_endpoint);let r=$e(n.token_endpoint),o=await Z(await e.fetchFn(t.deviceUrl,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:Ge({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=$e(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(r,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:Ge({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:$e(n.authorization_endpoint),token_endpoint:r}})}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 yt(e,t={}){let n=X(e),r={fetchFn:t.fetchFn||globalThis.fetch,inputFn:t.inputFn,sleepFn:t.sleepFn||(o=>new Promise(s=>setTimeout(s,o))),openFn:t.openFn||Tn,output:t.output||(o=>process.stdout.write(`${o}
|
|
7
|
+
`)),now:t.now,pkce:t.pkce};return n==="anthropic-oauth"?Rn(r):n==="openai-codex"?Pn(r):In(r)}import Me from"node:fs";import Ve from"node:path";var Ln=new Set(["openrouter","openai","anthropic","xai","deepseek","gemini","kimi","mistral","nous","qwen","glm","local","ollama","custom","anthropic-oauth","openai-codex","xai-oauth"]);function Oe(e){return String(e||"").trim()||void 0}function Cn(e,{required:t=!1}={}){let n=Oe(e)?.toLowerCase();if(!n){if(t)throw new Error("model provider is required");return}if(!Ln.has(n))throw new Error(`unsupported provider: ${n}`);return n}function Nn(e,{required:t=!1}={}){let n=Oe(e);if(!n){if(t)throw new Error("model is required");return}if(n.includes("..")||n.startsWith("/")||!/^[a-zA-Z0-9._:/-]{1,200}$/.test(n))throw new Error("invalid model id");return n}function Fn(e){let t=Oe(e);if(!t||t.length>2048)throw new Error("invalid custom base URL");let n;try{n=new URL(t)}catch{throw new Error("invalid custom base URL")}let r=n.hostname.toLowerCase().replace(/^\[|\]$/g,""),o=r==="localhost"||r==="127.0.0.1"||r==="::1";if(n.protocol!=="https:"&&!(n.protocol==="http:"&&o)||n.username||n.password||n.search||n.hash)throw new Error("custom base URL must use HTTPS or loopback HTTP without credentials, query, or fragment");return n.toString().replace(/\/+$/,"")}function Te({provider:e,model:t,baseUrl:n}={},{requireModel:r=!1}={}){let o=Cn(e),s=Nn(t,{required:r});if(o==="custom")return{provider:o,...s?{model:s}:{},baseUrl:Fn(n)};if(Oe(n))throw new Error("baseUrl is only supported for the custom provider");return{...o?{provider:o}:{},...s?{model:s}:{}}}var Dn=new Set(["auto","standalone","hermes","remote","arch"]);function jn(){return Ve.join(N(),"model.json")}function ue(e){return String(e||"").trim()||void 0}function Un(e={}){let t=ue(e.backend)?.toLowerCase()||"auto",n=Te({provider:e.provider,model:e.model,baseUrl:e.baseUrl},{requireModel:t==="standalone"}),r=ue(e.apiKeyEnv),o=Number.parseInt(String(e.contextLength||""),10),s=ue(e.reasoningEffort),i=ue(e.computeHost||e.remoteHost),a=ue(e.computeUser||e.remoteUser),c=ue(e.computePath||e.remotePath);if(!Dn.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(r&&!/^[A-Z][A-Z0-9_]*$/.test(r))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,...n,...r?{apiKeyEnv:r}:{},...Number.isFinite(o)&&o>0?{contextLength:o}:{},...s?{reasoningEffort:s}:{},...i?{computeHost:i}:{},...a?{computeUser:a}:{},...c?{computePath:c}:{}}}function Re(e){let t=Un(e),n=jn();F(Ve.dirname(n)),process.platform!=="win32"&&Me.chmodSync(Ve.dirname(n),448);let r=`${n}.${process.pid}.tmp`;return Me.writeFileSync(r,`${JSON.stringify(t,null,2)}
|
|
8
|
+
`,{mode:384}),Me.renameSync(r,n),process.platform!=="win32"&&Me.chmodSync(n,384),t}var _t=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 Xe(e,t){let n=e.indexOf(t);return n>=0&&e[n+1]?e[n+1]:""}async function qn(){let e="";for await(let t of process.stdin)e+=t;return e.trim()}function zn(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,n)=>{let r="",o=()=>{process.stdin.off("data",s),process.stdin.setRawMode(!1),process.stdin.pause(),process.stdout.write(`
|
|
9
9
|
`)},s=i=>{let a=String(i);for(let c of a){if(c==="\r"||c===`
|
|
10
|
-
`){o(),t(
|
|
11
|
-
`);let t=Object.entries(e.providers||{}),
|
|
12
|
-
`);return}for(let[
|
|
13
|
-
`)}for(let[
|
|
14
|
-
`)}function
|
|
15
|
-
`)}var
|
|
16
|
-
`):
|
|
17
|
-
`),0}if(
|
|
18
|
-
`),0}if(
|
|
19
|
-
`),0}throw new Error(
|
|
20
|
-
`),
|
|
21
|
-
`
|
|
10
|
+
`){o(),t(r.trim());return}if(c===""){o(),n(new Error("cancelled"));return}c==="\x7F"||c==="\b"?r=r.slice(0,-1):r+=c}};process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",s)})}function Ze(e,t,{baseUrl:n=""}={}){if(e==="custom"&&!String(n||"").trim())throw new Error("custom provider requires --base-url");return{backend:"standalone",...Te({provider:e,model:t,baseUrl:n},{requireModel:!0})}}function At(e,t,n={}){return Re(Ze(e,t,n))}function Wn(e){process.stdout.write(`storage: ${e.storage}
|
|
11
|
+
`);let t=Object.entries(e.providers||{}),n=Object.entries(e.apiKeys||{});if(!t.length&&!n.length){process.stdout.write(`no credentials configured
|
|
12
|
+
`);return}for(let[r,o]of t){let s=o.expiresAt?new Date(o.expiresAt).toISOString():"unknown";process.stdout.write(`${r}: ${o.loggedIn?"logged in":"missing"}, expires ${s}
|
|
13
|
+
`)}for(let[r,o]of n)process.stdout.write(`${r}: API key ${o.configured?"configured":"missing"}
|
|
14
|
+
`)}function Gn(){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 usage [--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 le={name:"auth",summary:"login with Claude, Codex, or Grok OAuth; store provider API keys",group:"read",usage:Gn(),async run(e){let t=[...e.argv],n=t.shift()||"status",r=U();try{if(n==="status"){let o=r.status();return t.includes("--json")?process.stdout.write(`${JSON.stringify(o,null,2)}
|
|
16
|
+
`):Wn(o),0}if(n==="usage"){let{collectOAuthUsage:o}=await Promise.resolve().then(()=>(St(),vt)),s=await o(r);return process.stdout.write(`${JSON.stringify(s)}
|
|
17
|
+
`),0}if(n==="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=Xe(t,"--model")||s.model;Ze(s.id,i);let a=await yt(s.id,{openFn:t.includes("--no-browser")?()=>!1:void 0});return await r.withLock(async()=>{let c=r.get(s.id);r.set(s.id,a);try{At(s.id,i)}catch(l){throw c?r.set(s.id,c):r.remove(s.id),l}}),process.stdout.write(`${s.id}: logged in, stored in ${r.storage}
|
|
18
|
+
`),0}if(n==="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(_t,o))throw new Error(`unsupported API-key provider: ${o}`);let s=Xe(t,"--model")||_t[o].model,i=Xe(t,"--base-url");Ze(o,s,{baseUrl:i});let a=t.includes("--stdin")?await qn():await zn();return await r.withLock(async()=>{let c=r.getApiKey(o);r.setApiKey(o,a);try{At(o,s,{baseUrl:i})}catch(l){throw c?r.setApiKey(o,c):r.removeApiKey(o),l}}),process.stdout.write(`${o}: API key configured in ${r.storage}
|
|
19
|
+
`),0}if(n==="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=r.remove(X(o))}catch{}let i=r.removeApiKey(o);if(!s&&!i)throw new Error(`${o}: no local credential found`);return process.stdout.write(`${o}: local credential removed
|
|
20
|
+
`),0}throw new Error(`unknown auth action: ${n}`)}catch(o){return process.stderr.write(`oracle auth: ${o.message}
|
|
21
|
+
`),1}}};var Yn=Object.freeze([["#D7F4FF"," \u2584\u2584\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2584\u2584 "],["#9CE7FF"," \u2584\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2584 "],["#5BCBFF"," \u2584\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2584 "],["#BDEEFF"," \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 "],["#369BFF"," \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 "],["#2577D8"," \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 "],["#79D7FF"," \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 "],["#1E5CA8"," \u2580\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2580 "],["#64BFFF"," \u2580\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2580 "],["#B8EAFF"," \u2580\u2580\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2580\u2580 "]]);var no=Object.freeze([" \xB7\u2500\u2500\u2550\u2550\u2500\u2500\xB7 "," \u2571 \xB7\u2500\u2500\u2500\u2500\xB7 \u2572 ","\u2502 (\u2588\u2588) \u2502"," \u2572 \xB7\u2500\u2500\u2500\u2500\xB7 \u2571 "," \xB7\u2500\u2500\u2550\u2550\u2500\u2500\xB7 "]);var Pe=Object.freeze([[" \xB7\u2500\u2500\u2550\u2550\u2500\u2500\xB7 "," \u2571 \xB7\u2500\u2500\u2500\u2500\xB7 \u2572 ","\u2502 (\u2588\u2588) \u2502"," \u2572 \xB7\u2500\u2500\u2500\u2500\xB7 \u2571 "," \xB7\u2500\u2500\u2550\u2550\u2500\u2500\xB7 "],[" \xB7\u2500\u2500\u2550\u2550\u2500\u2500\xB7 "," \u2571 \xB7\u2500\u2500\xB7 \u2572 ","\u2502 \xB7(\u2588\u2588)\xB7 \u2502"," \u2572 \xB7\u2500\u2500\xB7 \u2571 "," \xB7\u2500\u2500\u2550\u2550\u2500\u2500\xB7 "],[" \xB7\u2500\u2500\u2550\u2550\u2500\u2500\xB7 "," \u2571 \xB7\u2500\u2500\u2500\u2500\xB7 \u2572 ","\u2502 \xB7 (\u2588\u2588) \xB7 \u2502"," \u2572 \xB7\u2500\u2500\u2500\u2500\xB7 \u2571 "," \xB7\u2500\u2500\u2550\u2550\u2500\u2500\xB7 "],[" \xB7\u2500\u2500\u2550\u2550\u2500\u2500\xB7 "," \u2571\xB7 \u2500\u2500\u2500\u2500 \xB7\u2572 ","\u2502 (\u2588\u2588) \u2502"," \u2572\xB7 \u2500\u2500\u2500\u2500 \xB7\u2571 "," \xB7\u2500\u2500\u2550\u2550\u2500\u2500\xB7 "]]),Vn=Object.freeze([["#EAF7FF"," \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 "],["#D8F2FF"," \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 "],["#B8F0FF"," \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 "],["#ACDEEF"," \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 "],["#7FA9BE"," \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 Et=Object.freeze([[" * + . ' * "," . * * + ' "],[" + . * + ' "," * ' + . + "],[" . * + * + "," + + . * * "],[" + ' * . * "," * * + ' . "]]),Jn=Object.freeze(Et[0]);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 Xn(e){if(typeof e!="string")return null;let t=e.startsWith("#")?e.slice(1):e;if(!/^(?:[\da-f]{3}|[\da-f]{6})$/i.test(t))return null;let n=t.length===3?[...t].map(r=>r.repeat(2)).join(""):t;return{r:Number.parseInt(n.slice(0,2),16),g:Number.parseInt(n.slice(2,4),16),b:Number.parseInt(n.slice(4,6),16)}}function $t(e,t,n){let r=Xn(t);return r?`\x1B[${e};2;${r.r};${r.g};${r.b}m${String(n)}\x1B[0m`:String(n)}function Qe({color:e=!0}={}){return e&&!Object.hasOwn(process.env,"NO_COLOR")?Object.freeze({fg:(n,r)=>$t(38,n,r),bg:(n,r)=>$t(48,n,r),bold:n=>`\x1B[1m${String(n)}\x1B[0m`,dim:n=>`\x1B[2m${String(n)}\x1B[0m`}):Object.freeze({fg:(n,r)=>String(r),bg:(n,r)=>String(r),bold:n=>String(n),dim:n=>String(n)})}var oo=Qe();function Ot(e){return String(e).replace(/\u001B\[[0-9;]*m/g,"")}import{spawnSync as cr}from"node:child_process";var ge=Buffer.alloc(0);var Zn={A:"up",B:"down",C:"right",D:"left",H:"home",F:"end",P:"f1",Q:"f2",R:"f3",S:"f4"},Qn={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:n=!1,shift:r=!1,sequence:o=""}){return{name:e,ctrl:t,meta:n,shift:r,sequence:o}}function Pt(e){return e<128?1:e>=240?4:e>=224?3:e>=192?2:1}function er(e){return e>=64&&e<=126}function Tt(e){let t=e.toLowerCase();return I({name:t,shift:e!==t,sequence:e})}function tr(e){return e===13?I({name:"return",sequence:"\r"}):e===10?I({name:"return",sequence:`
|
|
22
|
+
`}):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 nr(e){let t=/^\u001b[\[O](\d*)(?:;(\d+))?(.)$/s.exec(e);if(!t)return I({name:"unknown",sequence:e});let n=t[1]===""?null:Number(t[1]),r=t[2]===void 0?null:Number(t[2]),o=t[3],s=null,i=r;if(o==="~"?s=Qn[n]??null:(s=Zn[o]??null,i===null&&n!==null&&n>1&&(i=n)),!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 rr(e,t,n,r){let o=()=>(n.push(I({name:"escape",sequence:"\x1B"})),1);if(t+1>=e.length)return r?o():0;let s=e[t+1];if(s===91||s===79){let l=t+2;for(;l<e.length&&!er(e[l]);)l+=1;return l>=e.length?r?o():0:(n.push(nr(e.toString("utf8",t,l+1))),l+1-t)}if(s===27)return o();let i=Pt(s);if(t+1+i>e.length)return r?o():0;let a=e.toString("utf8",t+1,t+1+i),c=a.toLowerCase();return n.push(I({name:c,meta:!0,shift:a!==c,sequence:`\x1B${a}`})),1+i}function Mt(e,t){let n=[],r=0;for(;r<e.length;){let o=e[r];if(o===27){let i=rr(e,r,n,t);if(i===0)return{keys:n,rest:Buffer.from(e.subarray(r))};r+=i;continue}if(o<32||o===127){n.push(tr(o)),r+=1;continue}let s=Pt(o);if(r+s>e.length)return t?(n.push(Tt(e.toString("utf8",r))),{keys:n,rest:ge}):{keys:n,rest:Buffer.from(e.subarray(r))};n.push(Tt(e.toString("utf8",r,r+s))),r+=s}return{keys:n,rest:ge}}function Rt(e){return Buffer.isBuffer(e)?e:e==null?ge:typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}function It(){let e=ge;return{push(t){let n=e.length===0?Rt(t):Buffer.concat([e,Rt(t)]),{keys:r,rest:o}=Mt(n,!1);return e=o,r},flush(){if(e.length===0)return[];let{keys:t}=Mt(e,!0);return e=ge,t},get pending(){return e.length}}}var et=/\u001B\[[0-9;]*m/g;function Lt(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 or(e){return[...Ot(e)].reduce((t,n)=>t+Lt(n),0)}function sr(e,t){if(t<=0)return"";let n=String(e).split(/(\u001B\[[0-9;]*m)/g),r="",o=0,s=!1;for(let i of n)if(i){if(et.test(i)){et.lastIndex=0,r+=i,s=i!=="\x1B[0m";continue}et.lastIndex=0;for(let a of i){let c=Lt(a);if(o+c>t)return s?`${r}\x1B[0m`:r;r+=a,o+=c}}return r}function Ie(e,t,n="left"){let r=Math.max(0,Math.floor(Number(t)||0)),o=sr(String(e),r),s=Math.max(0,r-or(o));if(n==="right")return`${" ".repeat(s)}${o}`;if(n==="center"){let i=Math.floor(s/2);return`${" ".repeat(i)}${o}${" ".repeat(s-i)}`}return`${o}${" ".repeat(s)}`}var So=Object.freeze(["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"]),_o=Object.freeze({thinking:"Thinking",writing:"Writing",executing:"Executing",waiting:"Waiting"});async function Ct(e,{headers:t={}}={}){let n=new AbortController,r=setTimeout(()=>n.abort(),6e3);try{let o=await fetch(e,{headers:t,signal:n.signal}),s=null;try{s=await o.json()}catch{s=null}return{status:o.status,body:s}}finally{clearTimeout(r)}}async function ir(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:n,body:r}=await Ct(`https://api.telegram.org/bot${t}/getMe`);return n===200&&r?.ok&&r.result?.username?{ok:!0,definitive:!0,username:`@${r.result.username}`}:n===401||n===404?{ok:!1,definitive:!0,error:"telegram rejected this token (check BotFather)"}:{ok:!1,definitive:!1,error:`telegram returned ${n} \u2014 saved anyway, verify later`}}catch{return{ok:!1,definitive:!1,error:"network unreachable \u2014 saved anyway, verify later"}}}async function ar(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:n,body:r}=await Ct("https://discord.com/api/v10/users/@me",{headers:{Authorization:`Bot ${t}`}});return n===200&&r?.username?{ok:!0,definitive:!0,username:r.username}:n===401?{ok:!1,definitive:!0,error:"discord rejected this token (reset it in the developer portal)"}:{ok:!1,definitive:!1,error:`discord returned ${n} \u2014 saved anyway, verify later`}}catch{return{ok:!1,definitive:!1,error:"network unreachable \u2014 saved anyway, verify later"}}}async function Le(e,t){let n=String(e||"").toLowerCase();return n==="telegram"?ir(t):n==="discord"?ar(t):{ok:!1,definitive:!1}}var ur=Object.freeze(["telegram","discord","whatsapp","slack","signal"]),Ut=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"}]),Bt=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 lr(e,t){let n=String(t||"unset");return n==="ready"||n==="connected"||n==="configured"?e.fg($.ok,n):n==="manual"?e.fg($.warn,n):e.fg($.banner_dim,n||"unset")}function Nt({profile:e="oracle",statuses:t=null,oauthStatus:n=null,runtime:r=null}={}){let o=t;if(!o)try{o=re(e).statuses||{}}catch{o={}}let s=n;if(!s)try{s=U().status()}catch{s={providers:{},apiKeys:{}}}let i=r;if(!i)try{i=ie()}catch{i={ok:!1}}let a=Ut.some(y=>{let h=W(y.id);return s.providers?.[h.id]?.loggedIn===!0}),c=Bt.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(ee().map(y=>[y.key,y]));for(let y of ur){let h=u.get(y);if(!h)continue;let O=o[h.key]||(h.required?.length?"unset":"manual"),v=!i.ok&&O==="ready"?"token set":O;l.push({id:h.key,label:h.name,note:h.note||"",status:v,action:h.required?.length?"token":"hermes",platform:h})}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 Ft(e=null){let t=e;if(!t)try{t=U().status()}catch{t={providers:{},apiKeys:{}}}let n=[];for(let r of Ut){let o=W(r.id),s=t.providers?.[o.id]?.loggedIn===!0;n.push({id:r.id,label:r.label,note:r.hint,status:s?"connected":"OAuth",action:"oauth",kind:"oauth"})}for(let r of Bt){let o=t.apiKeys?.[r.id]?.configured===!0;n.push({id:r.id,label:r.label,note:r.hint,status:o?"configured":"API key",action:"api-key",kind:"api-key"})}return n.push({id:"back",label:"back",note:"setup menu",status:"",action:"back",skip:!0}),n}function Ce({width:e,palette:t,title:n,subtitle:r="",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),h=A=>t.fg($.banner_border,A),O=A=>`${y}${A}`,v=(A="")=>O(`${h("\u2502")} ${Ie(A,u)} ${h("\u2502")}`),T="\u2500".repeat(Math.max(0,c-2)),k=[O(`${h("\u256D")}${h(T)}${h("\u256E")}`),v(t.bold(t.fg($.accent,n||"oracle setup"))),v(h("\u2500".repeat(u)))];return r&&(k.push(v(t.fg($.banner_dim,r))),k.push(v(""))),o.forEach((A,B)=>{let w=B===s,g=w?"\u203A":" ",p=String(A.label||A.id||""),d=String(A.note||""),m=A.status?lr(t,A.status):"",x=` ${g} ${p}`,S=[m,d?t.fg($.banner_dim,d):""].filter(Boolean).join(" "),C=Math.max(1,u-Dt(x)-Dt(Kt(S))-1),K=`${x}${" ".repeat(C)}${S}`;w?k.push(v(t.bg($.selection_bg,t.bold(t.fg($.banner_text,Ie(K,u)))))):k.push(v(K))}),k.push(v("")),k.push(v(t.fg($.banner_dim,i))),k.push(O(`${h("\u2570")}${h(T)}${h("\u256F")}`)),k}function dr({width:e,palette:t,platformKey:n="telegram",tokenLength:r=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}`,h=(k="")=>y(`${u("\u2502")} ${Ie(k,c)} ${u("\u2502")}`),O="\u2500".repeat(Math.max(0,i-2)),v=r>0?"\u2022".repeat(Math.min(r,40)):t.fg($.banner_dim,"paste token here (hidden)");return[y(`${u("\u256D")}${u(O)}${u("\u256E")}`),h(t.bold(t.fg($.accent,`setup \xB7 ${n}`))),h(u("\u2500".repeat(c))),h(t.fg($.banner_dim,"token stays local \xB7 never echoed \xB7 never sent to chat")),h(""),h(`${t.fg($.banner_dim,"token")} ${v}`),h(r?t.fg($.banner_dim,` ${r} characters`):""),h(o?t.fg($.warn,o):""),h(t.fg($.banner_dim,"type or paste backspace enter save esc cancel")),y(`${u("\u2570")}${u(O)}${u("\u256F")}`)]}function fr({width:e,palette:t,title:n,subtitle:r,index:o=0,yesLabel:s="yes",noLabel:i="not now"}={}){return Ce({width:e,palette:t,title:n,subtitle:r,rows:[{id:"yes",label:s,note:"",status:""},{id:"no",label:i,note:"",status:""}],index:o,footer:"\u2191/\u2193 move enter select esc skip"})}function Kt(e){return String(e||"").replace(/\u001b\[[0-9;]*m/g,"")}function Dt(e){return Kt(e).length}function de(e){e.write("\x1B[2J\x1B[H")}function ye(e,t){de(e),e.write(`${t.join(`
|
|
22
23
|
`)}
|
|
23
|
-
`)}function
|
|
24
|
+
`)}function jt(e){let t=ie();if(!t?.bin)return{code:1,error:"hermes not found \u2014 install hermes or run oracle bootstrap"};let n=cr(t.bin,e,{stdio:"inherit",env:process.env});return{code:typeof n.status=="number"?n.status:1}}async function Ht({stdin:e=process.stdin,stdout:t=process.stdout,env:n=process.env,palette:r,profile:o="oracle",startAt:s="menu",runAuth:i=c=>le.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,h=0,O=0,v="",T="",k="",A=null,B=Nt({profile:o}),w=Ft();String(s).startsWith("token:")?(k=String(s).slice(6),u="token"):s==="model"&&(u="model");let g=It(),p=e.isRaw===!0;typeof e.setRawMode=="function"&&e.setRawMode(!0),e.resume();let d=()=>{u==="menu"?ye(t,Ce({width:c,palette:r,title:"oracle setup",subtitle:"\u2191\u2193 enter \xB7 model + telegram/discord/whatsapp",rows:B,index:y})):u==="model"?ye(t,Ce({width:c,palette:r,title:"sign in",subtitle:"subscription OAuth or API key",rows:w,index:h})):u==="token"?ye(t,dr({width:c,palette:r,platformKey:k,tokenLength:v.length,error:T})):u==="confirm-gateway"?ye(t,fr({width:c,palette:r,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"&&ye(t,Ce({width:c,palette:r,title:A?.title||"setup",subtitle:A?.subtitle||"",rows:[{id:"ok",label:"continue",note:"",status:""}],index:0,footer:"enter continue esc menu"}))};d();let m=async x=>(typeof e.setRawMode=="function"&&e.setRawMode(p),e.pause(),de(t),x);return new Promise(x=>{let S=null,C=!1,K=b=>{C||(C=!0,S&&clearTimeout(S),e.off("data",st),Promise.resolve(m(b)).then(x))},H=()=>{B=Nt({profile:o}),w=Ft()},Fe=async()=>{let b=v.trim();if(!b){T="empty token",d();return}T="checking token\u2026",d();let f={ok:!1,definitive:!1};try{f=await Le(k,b)}catch{f={ok:!1,definitive:!1}}if(!f.ok&&f.definitive){v="",T=f.error||"platform rejected this token",d();return}try{let _=Se(o,k,b);V({lastPlatform:k,profile:o,ready:!0}),l.push(`token:${k}${f.ok?":verified":""}`),v="",T="";let E=!1;try{E=ie().ok===!0}catch{E=!1}let it=f.username?` \xB7 bot ${f.username}`:"";E?(A={title:`${k} saved${it}`,subtitle:f.ok?`token verified live \xB7 ${_.path}`:`wrote credentials \xB7 ${_.path}`},O=0,u=a?"confirm-gateway":"menu"):(A={title:`${k} token saved${it}`,subtitle:"next: install the messaging runtime (menu row) so the bot can answer"},O=0,u="notice"),H(),d()}catch(_){T=_?.message||"save failed",v="",d()}},rt=async b=>{if(!b||b.action==="done"){K({completed:!0,actions:l});return}if(b.action==="model"){u="model",h=0,d();return}if(b.action==="token"){k=b.id,v="",T="",u="token",d();return}if(b.action==="bootstrap"){typeof e.setRawMode=="function"&&e.setRawMode(p),e.pause(),de(t),t.write(`installing messaging runtime (one-time, a few minutes)\u2026
|
|
24
25
|
|
|
25
|
-
`);let
|
|
26
|
-
`);let _=
|
|
26
|
+
`);let f={ok:!1,reason:"unknown"};try{f=ht({})}catch(_){f={ok:!1,reason:_?.message||"install failed"}}l.push(`bootstrap:${f.ok?"ok":"fail"}`),typeof e.setRawMode=="function"&&e.setRawMode(!0),e.resume(),H(),A={title:f.ok?"messaging runtime ready":"runtime install failed",subtitle:f.ok?"pick telegram / discord next":f.reason||"see oracle bootstrap"},u="notice",d();return}if(b.action==="hermes"){typeof e.setRawMode=="function"&&e.setRawMode(p),e.pause(),de(t),t.write(`opening ${b.id} setup\u2026
|
|
27
|
+
`);let _=Y(b.id)?.hermes||["gateway","setup"],E=jt(["-p",o,..._]);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",d();return}if(b.action==="gateway"||b.action==="gateway-install"){let f=b.action==="gateway-install"?"install":"restart";typeof e.setRawMode=="function"&&e.setRawMode(p),e.pause(),de(t),t.write(f==="install"?`installing boot service\u2026
|
|
27
28
|
`:`restarting gateway\u2026
|
|
28
|
-
`);let _=
|
|
29
|
-
`);let _=1;try{_=await i(
|
|
30
|
-
`),_=1}l.push(`model:${b.id}:${_}`),typeof e.setRawMode=="function"&&e.setRawMode(!0),e.resume(),H(),u="menu",
|
|
31
|
-
`)}async function
|
|
32
|
-
`),await t(90)}async function
|
|
29
|
+
`);let _=jt(["-p",o,"gateway",f]);l.push(`gateway:${f}:${_.code}`),typeof e.setRawMode=="function"&&e.setRawMode(!0),e.resume(),A={title:_.code===0?f==="install"?"boot service installed":"gateway restarted":`gateway ${f} failed`,subtitle:_.code===0?f==="install"?"bot survives reboots now":"channels should be live":_.error||`exit ${_.code}`},u="notice",d()}},Gt=async b=>{if(!b||b.action==="back"){u="menu",d();return}typeof e.setRawMode=="function"&&e.setRawMode(p),e.pause(),de(t);let f=b.kind==="oauth"?["login",b.id]:["api-key",b.id];t.write(`connecting ${b.label}\u2026
|
|
30
|
+
`);let _=1;try{_=await i(f)}catch(E){t.write(`${E?.message||E}
|
|
31
|
+
`),_=1}l.push(`model:${b.id}:${_}`),typeof e.setRawMode=="function"&&e.setRawMode(!0),e.resume(),H(),u="menu",d()},ot=b=>{for(let f of b){if(f.ctrl&&f.name==="c"){K({completed:!1,actions:l,reason:"cancel"});return}if(u==="token"){if(f.name==="escape"){v="",T="",u="menu",d();continue}if(f.name==="return"){Fe();continue}if(f.name==="backspace"||f.sequence==="\x7F"||f.sequence==="\b"){v=v.slice(0,-1),T="",d();continue}let E=f.sequence||"";if(E&&!f.ctrl&&!f.meta&&E!=="\x1B"){if(E.startsWith("\x1B"))continue;v+=E,T="",d()}continue}if(u==="confirm-gateway"){if(f.name==="up"||f.name==="down"){O=O===0?1:0,d();continue}if(f.name==="escape"){u="menu",d();continue}f.name==="return"&&(O===0?rt({action:"gateway",id:"gateway"}):(u="menu",d()));continue}if(u==="notice"){(f.name==="return"||f.name==="escape")&&(u="menu",d());continue}if(u==="model"){let E=w.length;if(f.name==="up"){h=E?(h-1+E)%E:0,d();continue}if(f.name==="down"){h=E?(h+1)%E:0,d();continue}if(f.name==="escape"){u="menu",d();continue}f.name==="return"&&Gt(w[h]);continue}let _=B.length;if(f.name==="up"){y=_?(y-1+_)%_:0,d();continue}if(f.name==="down"){y=_?(y+1)%_:0,d();continue}if(f.name==="escape"){K({completed:!0,actions:l,reason:"esc"});continue}f.name==="return"&&rt(B[y])}},st=b=>{ot(g.push(b)),S&&(clearTimeout(S),S=null),g.pending>0&&(S=setTimeout(()=>{S=null,ot(g.flush())},30),typeof S.unref=="function"&&S.unref())};e.on("data",st)})}var we=Object.freeze([{alias:"claude",label:"Claude",hint:"Anthropic subscription"},{alias:"codex",label:"Codex",hint:"OpenAI subscription"},{alias:"grok",label:"Grok",hint:"xAI subscription"}]),be=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"}]),Ne=Object.freeze([...we.map((e,t)=>({n:t+1,id:e.alias,label:e.label,kind:"oauth",hint:e.hint})),...be.map((e,t)=>({n:we.length+t+1,id:e.id,label:e.label,kind:"api-key",hint:"API key"})),{n:we.length+be.length+1,id:"custom",label:"Custom",kind:"api-key",hint:"OpenAI-compatible"},{n:we.length+be.length+2,id:"local",label:"Local",kind:"local",hint:"llama.cpp :8080"},{n:we.length+be.length+3,id:"ollama",label:"Ollama",kind:"local",hint:"ollama :11434"}]);function hr(e){let t=String(e||"").trim().toLowerCase();if(!t||t==="skip")return{skip:!0};let n=Ne.find(r=>String(r.n)===t||r.id===t);return n||{unknown:!0,choice:t}}function Wt(e="sign in",t=0){let n=Pe[t]||Pe[0];return["",`${n[0]} oracle`,`${n[1]} ${e}`,n[2],n[3],n[4],""].join(`
|
|
32
|
+
`)}async function mr(e){if(e.isTTY!==!0||process.env.NODE_TEST_CONTEXT||process.env.ORACLE_INSTALL_PLAIN==="1")return;let t=n=>new Promise(r=>setTimeout(r,n));for(let n=0;n<Pe.length;n+=1)n>0&&e.write("\x1B[7A"),e.write(`${Wt("sign in",n)}
|
|
33
|
+
`),await t(90)}async function Zo({stdin:e=process.stdin,stdout:t=process.stdout,readLine:n,runAuth:r=o=>le.run({argv:o})}={}){if(await mr(t),t.write(`${ke()}
|
|
33
34
|
`),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=
|
|
35
|
-
`)||l.includes("\r"))&&(e.off("data",u),c(l.trim()))};e.on("data",u)}),s=
|
|
36
|
-
`),{skipped:!0,reason:"unknown"};let i=s.kind==="oauth"?["login",s.id]:["api-key",s.id],a=await
|
|
37
|
-
`)}function
|
|
38
|
-
`)}function
|
|
35
|
+
`),e.isTTY!==!0||t.isTTY!==!0)return{skipped:!0,reason:"non-tty"};t.write("> ");let o=n?await n():await new Promise(c=>{let l="",u=y=>{l+=String(y),(l.includes(`
|
|
36
|
+
`)||l.includes("\r"))&&(e.off("data",u),c(l.trim()))};e.on("data",u)}),s=hr(o);if(s.skip)return{skipped:!0,reason:"skipped"};if(s.unknown)return t.write(`unknown choice '${s.choice}'
|
|
37
|
+
`),{skipped:!0,reason:"unknown"};let i=s.kind==="oauth"?["login",s.id]:["api-key",s.id],a=await r(i);return{skipped:!1,choice:s.id,code:a}}function ke(e=U().status()){let t=[Wt("sign in"),"sign in with a subscription",""];for(let n of Ne.filter(r=>r.kind==="oauth")){let r=W(n.id),o=e.providers?.[r.id]?.loggedIn===!0;t.push(` ${String(n.n).padStart(2)} ${n.label.padEnd(12)} ${o?"connected":"OAuth"}`)}t.push("","or use an API key","");for(let n of Ne.filter(r=>r.kind==="api-key")){let r=n.id==="custom"?!1:e.apiKeys?.[n.id]?.configured===!0;t.push(` ${String(n.n).padStart(2)} ${n.label.padEnd(12)} ${r?"configured":"not configured"}`)}t.push("","or a local loopback model","");for(let n of Ne.filter(r=>r.kind==="local"))t.push(` ${String(n.n).padStart(2)} ${n.label.padEnd(12)} loopback`);return t.push("","Your key stays on this machine. Nothing is uploaded by Oracle.",""),t.join(`
|
|
38
|
+
`)}function tt(){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(`
|
|
39
|
+
`)}function gr(e){let t=e.indexOf("--profile");if(t>=0&&e[t+1])return e[t+1];let n=e.indexOf("-p");return n>=0&&e[n+1]?e[n+1]:process.env.ORACLE_PROFILE||"oracle"}function yr(e){let t=[];for(let n=0;n<e.length;n++){if(e[n]==="--profile"||e[n]==="-p"){n+=1;continue}t.push(e[n])}return t}function nt(e,{inherit:t=!0,env:n=process.env}={}){let r=ie();if(!r.ok)return process.stderr.write(`oracle setup: Hermes not detected (opt-in only).
|
|
39
40
|
Native Oracle does not need Hermes.
|
|
40
41
|
To use Hermes messaging/gateway: install Hermes, or run \`oracle bootstrap\`, then retry.
|
|
41
42
|
Detect: oracle harness detect
|
|
42
|
-
`),1;let o=
|
|
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
|
|
43
|
+
`),1;let o=pr(r.bin,e,{stdio:t?"inherit":"pipe",encoding:"utf8",env:n});return o.error?(process.stderr.write(`oracle setup: failed to run hermes: ${o.error.message}
|
|
44
|
+
`),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 zt(e){if(!G.isTTY||typeof G.setRawMode!="function"){let t=new Error("interactive token entry requires a tty");throw t.code="NO_TTY",t}return qt.write(`${e}: `),new Promise((t,n)=>{let r="",o=()=>{G.off("data",s),G.setRawMode(!1),G.pause(),qt.write(`
|
|
44
45
|
`)},s=i=>{for(let a of String(i)){if(a==="\r"||a===`
|
|
45
|
-
`){o(),t(
|
|
46
|
-
`),process.stderr.write(`known: ${
|
|
47
|
-
`),1;if(!
|
|
48
|
-
`),V({lastPlatform:
|
|
49
|
-
`),1;s.push(l)}let i=o.token||s[0]||"";if(!i&&!process.stdin.isTTY&&(i=await readStdinSecret()),!i)try{i=await
|
|
46
|
+
`){o(),t(r.trim());return}if(a===""){o(),n(new Error("cancelled"));return}a==="\x7F"||a==="\b"?r=r.slice(0,-1):r+=a}};G.setRawMode(!0),G.resume(),G.on("data",s)})}async function wr(e,t,n=[]){let r=Y(t);if(!r)return process.stderr.write(`oracle setup: unknown platform '${t}'
|
|
47
|
+
`),process.stderr.write(`known: ${ee().map(c=>c.key).join(", ")}
|
|
48
|
+
`),1;if(!r.required.length)return process.stdout.write(`opening hermes setup for ${r.key} (interactive)
|
|
49
|
+
`),V({lastPlatform:r.key,profile:e}),nt(["-p",e,...r.hermes||["gateway","setup"]]);let o={},s=[];for(let c=0;c<n.length;c++){let l=n[c];if(l==="--token"&&n[c+1]){o.token=n[++c];continue}if(l==="--allowed-users"&&n[c+1]){o.allowedUsers=n[++c];continue}if(l==="--app-token"&&n[c+1]){o.appToken=n[++c];continue}if(l.startsWith("-"))return process.stderr.write(`oracle setup: unknown flag ${l}
|
|
50
|
+
`),1;s.push(l)}let i=o.token||s[0]||"";if(!i&&!process.stdin.isTTY&&(i=await readStdinSecret()),!i)try{i=await zt(`${r.key} bot token`)}catch(c){if(c?.code==="NO_TTY")return process.stderr.write(`oracle setup ${r.key}: pipe the token on stdin (echo "$TOKEN" | oracle setup ${r.key}) or pass --token <value>
|
|
50
51
|
`),1;throw c}if(!i)return process.stderr.write(`aborted: empty token
|
|
51
|
-
`),1;let a={};if(o.allowedUsers&&(
|
|
52
|
-
`),1;a.SLACK_APP_TOKEN=c}try{let c=await
|
|
53
|
-
`),1;let l=
|
|
52
|
+
`),1;let a={};if(o.allowedUsers&&(r.key==="telegram"&&(a.TELEGRAM_ALLOWED_USERS=o.allowedUsers),r.key==="discord"&&(a.DISCORD_ALLOWED_USERS=o.allowedUsers),r.key==="slack"&&(a.SLACK_ALLOWED_USERS=o.allowedUsers)),o.appToken&&r.key==="slack"&&(a.SLACK_APP_TOKEN=o.appToken),r.key==="slack"&&!a.SLACK_APP_TOKEN){let c=o.appToken||s[1]||"";if(!c&&process.stdin.isTTY&&(c=await zt("slack app token (xapp-...)")),!c)return process.stderr.write(`slack needs bot token + app token
|
|
53
|
+
`),1;a.SLACK_APP_TOKEN=c}try{let c=await Le(r.key,i).catch(()=>({ok:!1,definitive:!1}));if(!c.ok&&c.definitive)return process.stderr.write(`oracle setup ${r.key}: ${c.error||"platform rejected this token"}
|
|
54
|
+
`),1;let l=Se(e,r.key,i,a);V({lastPlatform:r.key,profile:e,ready:!0});let u=c.ok&&c.username?`bot: ${c.username} (token verified live)
|
|
54
55
|
`:"",y=!c.ok&&c.error?`note: ${c.error}
|
|
55
|
-
`:"";return process.stdout.write(`saved ${
|
|
56
|
+
`:"";return process.stdout.write(`saved ${r.key} credentials for profile '${e}'
|
|
56
57
|
`+u+y+`path: ${l.path}
|
|
57
58
|
next: oracle setup gateway restart
|
|
58
59
|
`),0}catch(c){return process.stderr.write(`oracle setup: ${c.message}
|
|
59
|
-
`),1}}var
|
|
60
|
-
`),0;if(["menu","list","ls"].includes(s)){if(
|
|
61
|
-
`),0;if(process.stdin.isTTY===!0&&process.stdout.isTTY===!0&&!process.env.ORACLE_SETUP_PLAIN){let a=await
|
|
62
|
-
`):(process.stdout.write(
|
|
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(
|
|
60
|
+
`),1}}var Qo={name:"setup",summary:"configure standalone OAuth and messaging platforms",group:"read",usage:tt(),async run(e){let t=[...e.argv],n=t.includes("--json"),r=gr(t),o=yr(t).filter(a=>a!=="--json"),s=(o[0]||"menu").toLowerCase(),i=o.slice(1);if(["-h","--help","help"].includes(s))return process.stdout.write(tt()+`
|
|
61
|
+
`),0;if(["menu","list","ls"].includes(s)){if(n)return process.stdout.write(JSON.stringify({...re(r),modelAuth:U().status()},null,2)+`
|
|
62
|
+
`),0;if(process.stdin.isTTY===!0&&process.stdout.isTTY===!0&&!process.env.ORACLE_SETUP_PLAIN){let a=await Ht({profile:r,palette:Qe({color:process.stdout.isTTY!==!1})});return a?.completed===!1&&a?.reason==="non-tty"?1:0}return process.stdout.write(ke()),process.stdout.write(ve(r)),0}if(["status","show"].includes(s)){let a=re(r);return n?process.stdout.write(JSON.stringify({...a,modelAuth:U().status()},null,2)+`
|
|
63
|
+
`):(process.stdout.write(ke()),process.stdout.write(ve(r)),process.stdout.write(`hermes root: ${pe()}
|
|
64
|
+
`)),0}if(["model","oauth"].includes(s)){let a=String(i[0]||"").trim().toLowerCase();if(!a||["list","status","show"].includes(a))return process.stdout.write(ke()),0;if(a==="local"||a==="ollama"){let l=Re({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
65
|
loopback, no API key
|
|
65
|
-
`),0}if(
|
|
66
|
-
`),process.stderr.write(
|
|
67
|
-
`),
|
|
68
|
-
`),1)}if(s==="profile"){let a=i[0]||
|
|
69
|
-
hermes: ${
|
|
70
|
-
`),process.stdout.write(
|
|
71
|
-
${
|
|
72
|
-
`),1)}};export{
|
|
66
|
+
`),0}if(be.some(c=>c.id===a)||a==="custom")return le.run({...e,argv:["api-key",a,...i.slice(1)]});try{return W(a),le.run({...e,argv:["login",a,...i.slice(1)]})}catch(c){return process.stderr.write(`oracle setup model: ${c.message}
|
|
67
|
+
`),process.stderr.write(ke()),1}}if(["messaging","gateway-setup","platforms"].includes(s))return V({lastAction:"messaging",profile:r}),process.stdout.write(`opening hermes gateway setup wizard...
|
|
68
|
+
`),nt(["-p",r,"gateway","setup"]);if(s==="gateway"){let a=(i[0]||"status").toLowerCase();return["status","start","stop","restart","run","install"].includes(a)?nt(["-p",r,"gateway",a]):(process.stderr.write(`usage: oracle setup gateway [status|start|stop|restart|run|install]
|
|
69
|
+
`),1)}if(s==="profile"){let a=i[0]||r;return process.stdout.write(`profile: ${a}
|
|
70
|
+
hermes: ${pe()}/profiles/${a}
|
|
71
|
+
`),process.stdout.write(ve(a)),0}return Y(s)?wr(r,s,i):(process.stderr.write(`oracle setup: unknown verb '${s}'
|
|
72
|
+
${tt()}
|
|
73
|
+
`),1)}};export{Ne as SETUP_CHOICES,Qo as default,ke as renderModelSetup,hr as resolveSetupChoice,Zo as runFirstRunModelSetup};
|