@oracle-agent/oracle 0.35.1 → 0.35.2
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/dist/assets/skills/oracle-desk-product/SKILL.md +1 -1
- package/dist/cli/commands/chat.mjs +183 -181
- package/dist/cli/commands/model.mjs +186 -184
- package/dist/cli/commands/setup.mjs +32 -32
- package/package.json +1 -1
- package/public/oracle-splash/assets/oracle-cli-v035-poster.jpg +0 -0
- package/public/oracle-splash/assets/oracle-cli-v035.gif +0 -0
- package/public/oracle-splash/index.html +101 -54
|
@@ -1,54 +1,54 @@
|
|
|
1
|
-
import{spawnSync as
|
|
1
|
+
import{spawnSync as Zr}from"node:child_process";import{stdin as Y,stdout as Nt}from"node:process";var De=Object.freeze([{key:"telegram",name:"telegram",hermes:["gateway","setup"],required:["TELEGRAM_BOT_TOKEN"],optional:["TELEGRAM_ALLOWED_USERS","TELEGRAM_PROXY"],note:"dms \xB7 groups \xB7 topics"},{key:"discord",name:"discord",hermes:["gateway","setup"],required:["DISCORD_BOT_TOKEN"],optional:["DISCORD_ALLOWED_USERS"],note:"dms \xB7 channels \xB7 threads"},{key:"slack",name:"slack",hermes:["gateway","setup"],required:["SLACK_BOT_TOKEN","SLACK_APP_TOKEN"],optional:["SLACK_ALLOWED_USERS"],note:"socket mode"},{key:"whatsapp",name:"whatsapp",hermes:["whatsapp"],required:[],optional:["WHATSAPP_ALLOWED_USERS","WHATSAPP_MODE"],note:"qr bridge"},{key:"whatsapp-cloud",name:"whatsapp cloud",hermes:["whatsapp-cloud"],required:[],optional:[],note:"business cloud api"},{key:"signal",name:"signal",hermes:["gateway","setup"],required:["SIGNAL_HTTP_URL","SIGNAL_ACCOUNT"],optional:["SIGNAL_ALLOWED_USERS"],note:"signal-cli rest bridge"},{key:"matrix",name:"matrix",hermes:["gateway","setup"],required:["MATRIX_HOMESERVER","MATRIX_ACCESS_TOKEN","MATRIX_USER_ID"],optional:["MATRIX_ALLOWED_USERS"],note:"rooms \xB7 dms"},{key:"mattermost",name:"mattermost",hermes:["gateway","setup"],required:["MATTERMOST_URL","MATTERMOST_TOKEN"],optional:["MATTERMOST_ALLOWED_USERS"],note:"channels \xB7 dms"},{key:"email",name:"email",hermes:["gateway","setup"],required:["EMAIL_ADDRESS","EMAIL_PASSWORD","EMAIL_IMAP_HOST","EMAIL_SMTP_HOST"],optional:[],note:"imap/smtp mailbox"},{key:"bluebubbles",name:"bluebubbles",hermes:["gateway","setup"],required:[],optional:[],note:"imessage via bluebubbles"},{key:"photon",name:"photon",hermes:["photon"],required:["PHOTON_PROJECT_ID","PHOTON_PROJECT_SECRET"],optional:["PHOTON_ALLOWED_USERS","PHOTON_HOME_CHANNEL"],note:"imessage via spectrum (no mac)"},{key:"homeassistant",name:"homeassistant",hermes:["gateway","setup"],required:["HASS_URL","HASS_TOKEN"],optional:[],note:"smart home"},{key:"webhook",name:"webhook",hermes:["gateway","setup"],required:[],optional:[],note:"http ingress"},{key:"api-server",name:"api server",hermes:["gateway","setup"],required:[],optional:[],note:"local http api"},{key:"dingtalk",name:"dingtalk",hermes:["gateway","setup"],required:[],optional:[],note:"dingtalk bot"},{key:"feishu",name:"feishu",hermes:["gateway","setup"],required:[],optional:[],note:"feishu / lark"},{key:"wecom",name:"wecom",hermes:["gateway","setup"],required:[],optional:[],note:"wecom"},{key:"weixin",name:"weixin",hermes:["gateway","setup"],required:[],optional:[],note:"weixin"},{key:"qqbot",name:"qqbot",hermes:["gateway","setup"],required:[],optional:[],note:"qq bot"}]);function st(e){return String(e||"").trim().toLowerCase().replace(/^\/+/,"").replace(/\s+/g,"-")}function Q(){return De.slice()}function G(e){let t=st(e);if(!t)return null;for(let r of De)if(r.key===t||st(r.name)===t)return r;return null}function it({profile:e="oracle",statuses:t={}}={}){let r=["oracle setup","","one oracle. many models. every connected channel.",`profile: ${e}`,"","start here (most people):"," 1. oracle setup model connect Claude / Codex / Grok / API key"," 2. oracle setup telegram bot token \u2192 dm your bot"," oracle setup discord bot token \u2192 channels / dms"," oracle setup whatsapp qr bridge (or whatsapp-cloud)"," 3. oracle setup gateway restart apply channel config","","messaging platforms:",""];for(let n of De){let o=t[n.key]||"unset";r.push(` ${n.key.padEnd(16)} ${String(o).padEnd(8)} ${n.note}`)}return r.push(""),r.push("commands:"),r.push(" oracle setup this menu"),r.push(" oracle setup model standalone OAuth / API keys"),r.push(" oracle setup messaging open hermes gateway setup wizard"),r.push(" oracle setup telegram set TELEGRAM_BOT_TOKEN (stdin or --token)"),r.push(" oracle setup discord set DISCORD_BOT_TOKEN"),r.push(" oracle setup whatsapp qr link via hermes"),r.push(" oracle setup slack bot + app tokens"),r.push(" oracle setup status show configured platforms (no secrets)"),r.push(" oracle setup gateway start/status/restart hermes gateway"),r.push(" /setup same menu inside the tui"),r.push(" /setup telegram|discord|whatsapp channel how-to (no secrets)"),r.push(""),r.push("notes:"),r.push(" tokens stay in the hermes profile .env on this machine"),r.push(" oracle never prints bot tokens or app secrets"),r.push(' pipe tokens: echo "$TOKEN" | oracle setup telegram'),r.push(" after token setup: oracle setup gateway restart"),r.join(`
|
|
2
2
|
`)+`
|
|
3
|
-
`}import F from"node:fs";import
|
|
4
|
-
`),{mode:384});try{F.chmodSync(n,384)}catch{}return{path:n,key:t,set:!0}}function re(e="oracle"){let t=ct(e),r={};for(let n of Q()){if(!n.required.length){r[n.key]="manual";continue}let o=n.required.filter(s=>!String(t[s]||"").trim());r[n.key]=o.length?"unset":"ready"}return{profile:e,statuses:r,envPath:ke(e)}}function xe(e="oracle"){let{statuses:t}=re(e);return it({profile:e,statuses:t})}function ve(e,t,r,n={}){let o=G(t);if(!o){let u=new Error(`unknown platform '${t}'`);throw u.code="UNKNOWN_PLATFORM",u}if(!o.required.length){let u=new Error(`${o.key} uses hermes interactive setup (oracle setup messaging)`);throw u.code="NEEDS_INTERACTIVE",u}let i=o.required.filter(u=>/(TOKEN|PASSWORD|SECRET)$/i.test(u))[0]||(o.required.length===1?o.required[0]:null);if(!i){let u=new Error(`${o.key} has no single token field; provide each of [${o.required.join(", ")}] explicitly`);throw u.code="NEEDS_EXPLICIT_KEYS",u}let a=new Set([i,...Object.keys(n||{}).filter(u=>n[u]!=null&&String(n[u]).trim())]),c=ct(e),l=o.required.filter(u=>!a.has(u)&&!String(c[u]||"").trim());if(l.length){let u=new Error(`${o.key} also requires [${l.join(", ")}]; pass them explicitly (setup would otherwise be marked ready while unusable)`);throw u.code="MISSING_REQUIRED",u}at(e,i,r);for(let[u,y]of Object.entries(n||{}))y!=null&&String(y).trim()&&at(e,u,y);return{platform:o.key,set:o.required,profile:e,path:ke(e)}}function
|
|
5
|
-
`,{mode:384}),n}import R from"node:fs";import T from"node:path";import{createHash as
|
|
6
|
-
`,{mode:384}),L.renameSync(r,e),process.platform!=="win32"&&L.chmodSync(e,384)}function dr(e){if(process.platform!=="linux")return!1;let t=e("secret-tool",["--version"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return!t.error&&t.status===0}function He(e){let t=String(e||"").trim().toLowerCase();if(!/^[a-z0-9][a-z0-9._-]*$/.test(t))throw new Error(`invalid API-key provider: ${e||"(empty)"}`);return t}function ie(e={}){let t=String(e.accessToken||e.access_token||"").trim(),r=String(e.refreshToken||e.refresh_token||"").trim(),n=Number(e.expiresAt||e.expires_at||0);if(Number.isFinite(n)&&n>=1e9&&n<1e12&&(n=n*1e3),!t)throw new Error("OAuth credential is missing access token");return{accessToken:t,refreshToken:r,expiresAt:Number.isFinite(n)?n:0,tokenType:String(e.tokenType||e.token_type||"Bearer"),source:String(e.source||"oracle"),...e.discovery?{discovery:e.discovery}:{},...e.scope?{scope:e.scope}:{},...e.idToken||e.id_token?{idToken:String(e.idToken||e.id_token)}:{}}}function pr(e={}){let t=e.file||j.join(N(),"oauth.json"),r=e.metadataFile||j.join(j.dirname(t),"oauth-meta.json"),n=e.linksFile||j.join(j.dirname(t),"oauth-links.json"),o=()=>typeof e.now=="function"?Number(e.now()):Date.now(),s=e.spawnFn||ur,i=e.keychain!==!1&&process.env.ORACLE_AUTH_FILE_STORE!=="1"&&dr(s),a=i?"linux-secret-service":"private-file",c=`${t}.lock`;async function l(w){mt(j.dirname(c));let g;for(let p=0;p<400;p+=1)try{g=L.openSync(c,"wx",384);break}catch(f){if(f?.code!=="EEXIST")throw f;try{Date.now()-L.statSync(c).mtimeMs>3e5&&L.unlinkSync(c)}catch{}await new Promise(h=>setTimeout(h,25))}if(g===void 0)throw new Error("timed out waiting for OAuth credential lock");try{return await w()}finally{try{L.closeSync(g)}catch{}try{L.unlinkSync(c)}catch{}}}function u(w,g="oauth"){return["application","oracle","kind",g,"provider",w]}function y(w){if(!L.existsSync(n))return null;let p=P(n,{providers:{}}).providers?.[w];if(!Array.isArray(p))return null;let f=[];for(let h of p)if(j.isAbsolute(String(h||"")))try{let x=P(h,{});if(w==="anthropic-oauth"&&x.claudeAiOauth){let C=ie(x.claudeAiOauth);f.push({...C,refreshToken:"",source:"external-access-only"});continue}let 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()+lr)||f[0]:null}function m(w){let g=X(w);if(i){let h=s("secret-tool",["lookup",...u(g)],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(!h.error&&h.status===0&&String(h.stdout||"").trim())try{return ie(JSON.parse(String(h.stdout).trim()))}catch{}return y(g)}let f=P(t,{providers:{}}).providers?.[g];if(f)try{return ie(f)}catch{}return y(g)}function O(w,g){let p=X(w),f=ie(g);if(i){let x=s("secret-tool",["store",`--label=Oracle ${p} OAuth`,...u(p)],{input:JSON.stringify(f),encoding:"utf8",stdio:["pipe","ignore","pipe"]});if(x.error||x.status!==0)throw new Error("OS credential store rejected OAuth credential");let 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||=pr(),pt}function qe(e){return Buffer.from(e).toString("base64url")}function mr(){let e=qe(ze(32));return{verifier:e,challenge:qe(sr("sha256").update(e).digest()),state:qe(ze(24))}}function hr(e,t){let r=Buffer.from(String(e||"")),n=Buffer.from(String(t||""));return r.length===n.length&&ir(r,n)}function gr(e){let t=String(e),r=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd.exe",["/d","/s","/c","start","",t]]:["xdg-open",[t]];try{return cr(r[0],r[1],{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function We(e){return new URLSearchParams(e).toString()}async function Z(e,t){if(!e?.ok){let n="";try{n=String((await e.json())?.error||"")}catch{}throw new Error(`${t} failed (HTTP ${e?.status||"unknown"}${n?`, ${n}`:""})`)}let r=await e.json();if(!r||typeof r!="object")throw new Error(`${t} returned invalid JSON`);return r}async function yr(e){if(e)return String(await e()).trim();let t=ar.createInterface({input:process.stdin,output:process.stdout});try{return String(await t.question("Authorization code: ")).trim()}finally{t.close()}}function Ye(e,t={}){let r=String(e.access_token||"").trim(),n=String(e.refresh_token||t.refreshToken||"").trim();if(!r)throw new Error("OAuth token response is missing access token");let o=Number(e.expires_in||3600);return ie({accessToken:r,refreshToken:n,expiresAt:fr(t)+Math.max(1,o)*1e3,tokenType:e.token_type||"Bearer",idToken:e.id_token,source:"oracle",...t.discovery?{discovery:t.discovery}:{},...e.scope?{scope:e.scope}:{}})}async function wr(e){let t=ae["anthropic-oauth"],r=e.pkce||mr(),n=new URLSearchParams({code:"true",client_id:t.clientId,response_type:"code",redirect_uri:t.redirectUri,scope:t.scope,code_challenge:r.challenge,code_challenge_method:"S256",state:r.state}),o=`${t.authorizeUrl}?${n}`;e.output(`Open: ${o}`),e.openFn(o);let s=await yr(e.inputFn),[i,a]=s.split("#",2);if(!i||!hr(a,r.state))throw new Error("Claude OAuth state mismatch");let c=await e.fetchFn(t.tokenUrl,{method:"POST",headers:{"content-type":"application/json","user-agent":"axios/1.7.9"},body:JSON.stringify({grant_type:"authorization_code",client_id:t.clientId,code:i,state:a,redirect_uri:t.redirectUri,code_verifier:r.verifier})});return Ye(await Z(c,"Claude OAuth token exchange"),e)}async function br(e){let t=ae["openai-codex"],r=await Z(await e.fetchFn(`${t.issuer}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({client_id:t.clientId})}),"Codex device authorization");if(!r.user_code||!r.device_auth_id)throw new Error("Codex device authorization returned incomplete data");let n=`${t.issuer}/codex/device`;e.output(`Open: ${n}`),e.output(`Code: ${r.user_code}`),e.openFn(n);let o=Math.max(3,Number(r.interval||5)),s;for(let a=0;a<Math.ceil(900/o);a+=1){await e.sleepFn(o*1e3);let c=await e.fetchFn(`${t.issuer}/api/accounts/deviceauth/token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({device_auth_id:r.device_auth_id,user_code:r.user_code})});if(c.ok){s=await Z(c,"Codex device authorization");break}if(![403,404].includes(c.status))throw new Error(`Codex device authorization failed (HTTP ${c.status})`)}if(!s)throw new Error("Codex device authorization timed out");let i=await e.fetchFn(t.tokenUrl,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:We({grant_type:"authorization_code",code:s.authorization_code,redirect_uri:`${t.issuer}/deviceauth/callback`,client_id:t.clientId,code_verifier:s.code_verifier})});return Ye(await Z(i,"Codex OAuth token exchange"),e)}function Ee(e){let t=new URL(String(e)),r=t.hostname.toLowerCase();if(t.protocol!=="https:"||r!=="x.ai"&&!r.endsWith(".x.ai"))throw new Error("xAI OAuth discovery returned an untrusted endpoint");return t.toString()}async function kr(e){let t=ae["xai-oauth"],r=await Z(await e.fetchFn(t.discoveryUrl,{headers:{accept:"application/json"}}),"xAI OAuth discovery");Ee(r.authorization_endpoint);let n=Ee(r.token_endpoint),o=await Z(await e.fetchFn(t.deviceUrl,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:We({client_id:t.clientId,scope:t.scope})}),"xAI device authorization");if(!o.device_code||!o.user_code||!o.verification_uri)throw new Error("xAI device authorization returned incomplete data");let s=Ee(o.verification_uri_complete||o.verification_uri);e.output(`Open: ${s}`),e.output(`Code: ${o.user_code}`),e.openFn(s);let i=Math.max(1,Number(o.interval||5)),a=Math.ceil(Math.max(1,Number(o.expires_in||600))/i);for(let c=0;c<a;c+=1){let l=await e.fetchFn(n,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:We({grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:t.clientId,device_code:o.device_code})});if(l.ok){let y=await Z(l,"xAI OAuth token exchange");return Ye(y,{...e,discovery:{authorization_endpoint:Ee(r.authorization_endpoint),token_endpoint:n}})}let u="";try{u=String((await l.json())?.error||"")}catch{}if(u==="slow_down")await e.sleepFn((i+1)*1e3);else if(u==="authorization_pending")await e.sleepFn(i*1e3);else throw new Error(`xAI OAuth token exchange failed (HTTP ${l.status}${u?`, ${u}`:""})`)}throw new Error("xAI device authorization timed out")}async function ht(e,t={}){let r=X(e),n={fetchFn:t.fetchFn||globalThis.fetch,inputFn:t.inputFn,sleepFn:t.sleepFn||(o=>new Promise(s=>setTimeout(s,o))),openFn:t.openFn||gr,output:t.output||(o=>process.stdout.write(`${o}
|
|
7
|
-
`)),now:t.now,pkce:t.pkce};return r==="anthropic-oauth"?
|
|
8
|
-
`,{mode:384}),Me.renameSync(n,r),process.platform!=="win32"&&Me.chmodSync(r,384),t}var gt=Object.freeze({openrouter:{model:"openrouter/auto"},openai:{model:"gpt-4.1-mini"},anthropic:{model:"claude-sonnet-4-6"},xai:{model:"grok-4.6"},deepseek:{model:"deepseek-chat"},gemini:{model:"gemini-2.5-flash"},kimi:{model:"kimi-k3"},mistral:{model:"mistral-large-latest"},nous:{model:"moonshotai/kimi-k3"},qwen:{model:"qwen-plus"},glm:{model:"glm-4.5"},custom:{model:""}});function Ve(e,t){let r=e.indexOf(t);return r>=0&&e[r+1]?e[r+1]:""}async function
|
|
3
|
+
`}import F from"node:fs";import Wt from"node:os";import Fe from"node:path";import fe from"node:fs";import Ut from"node:os";import q from"node:path";import{fileURLToPath as Bt}from"node:url";var Kt=q.dirname(Bt(import.meta.url)),ln=q.resolve(Kt,"../..");function te(){return process.env.ORACLE_FAKE_HOME||Ut.homedir()}function Ht(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function N(){return Ht()?process.env.ORACLE_CONFIG_DIR||q.join(te(),".config","oracle"):q.join(te(),".config","oracle")}function qt(){return q.join(N(),"desk.json")}function zt(){return q.join(N(),"env")}function ee({force:e=!1}={}){if(ee._done&&!e)return ee._result||null;ee._done=!0;let t={},r=(o,s)=>{if(s==null)return;let i=String(s).trim();i&&(process.env[o]!=null&&String(process.env[o]).trim()!==""||(process.env[o]=i,t[o]=i))};try{let o=zt();if(fe.existsSync(o))for(let s of fe.readFileSync(o,"utf8").split(/\r?\n/)){let i=s.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!i||i[2].startsWith("#"))continue;let a=i[2];(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),r(i[1],a)}}catch{}try{let o=qt();if(fe.existsSync(o)){let s=JSON.parse(fe.readFileSync(o,"utf8"));s&&typeof s=="object"&&(r("ORACLE_DESK_URL",s.deskUrl||s.dataUrl||s.url),r("ORACLE_DATA_URL",s.dataUrl||s.deskUrl||s.url),r("ORACLE_API_URL",s.apiUrl||s.dataUrl||s.deskUrl),r("ORACLE_PUBLIC_URL",s.publicUrl||s.deskUrl||s.dataUrl),r("ORACLE_EXEC_URL",s.execUrl),r("MAD_DESK_URL",s.deskUrl||s.dataUrl))}}catch{}let n=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return n&&(r("ORACLE_DESK_URL",n),r("ORACLE_DATA_URL",n),r("ORACLE_API_URL",n),r("ORACLE_PUBLIC_URL",n),r("MAD_DESK_URL",n)),ee._result=Object.keys(t).length?t:null,ee._result}try{ee()}catch{}function de(){return process.env.HERMES_HOME?q.resolve(process.env.HERMES_HOME):q.join(te(),".hermes")}function D(e){return fe.mkdirSync(e,{recursive:!0}),e}var Yt=/(TOKEN|SECRET|PASSWORD|KEY|AUTH|PRIVATE|MNEMONIC|SEED)/i;function ke(e="oracle"){return Fe.join(de(),"profiles",e,".env")}function Gt(e){let t={};for(let r of String(e||"").split(/\r?\n/)){let n=r.trim();if(!n||n.startsWith("#"))continue;let o=n.indexOf("=");if(o<=0)continue;let s=n.slice(0,o).trim(),i=n.slice(o+1).trim();(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),t[s]=i}return t}function ct(e="oracle"){let t=ke(e);return F.existsSync(t)?Gt(F.readFileSync(t,"utf8")):{}}function at(e,t,r){if(!t||Yt.test(t)===!1&&/[^A-Z0-9_]/.test(t),!/^[A-Z][A-Z0-9_]*$/.test(t)){let l=new Error(`invalid env key '${t}'`);throw l.code="BAD_KEY",l}if(r==null||String(r).trim()===""){let l=new Error(`empty value for ${t}`);throw l.code="EMPTY",l}let n=ke(e);D(Fe.dirname(n));let o=F.existsSync(n)?F.readFileSync(n,"utf8"):"",s=o?o.split(/\r?\n/):[],i=[],a=!1,c=`${t}=${String(r)}`;for(let l of s)l.startsWith(`${t}=`)?(i.push(c),a=!0):(l.length||i.length)&&i.push(l);for(a||(i.length&&i[i.length-1]!==""&&i.push(""),i.push(c));i.length&&i[i.length-1]==="";)i.pop();i.push(""),F.writeFileSync(n,i.join(`
|
|
4
|
+
`),{mode:384});try{F.chmodSync(n,384)}catch{}return{path:n,key:t,set:!0}}function re(e="oracle"){let t=ct(e),r={};for(let n of Q()){if(!n.required.length){r[n.key]="manual";continue}let o=n.required.filter(s=>!String(t[s]||"").trim());r[n.key]=o.length?"unset":"ready"}return{profile:e,statuses:r,envPath:ke(e)}}function xe(e="oracle"){let{statuses:t}=re(e);return it({profile:e,statuses:t})}function ve(e,t,r,n={}){let o=G(t);if(!o){let u=new Error(`unknown platform '${t}'`);throw u.code="UNKNOWN_PLATFORM",u}if(!o.required.length){let u=new Error(`${o.key} uses hermes interactive setup (oracle setup messaging)`);throw u.code="NEEDS_INTERACTIVE",u}let i=o.required.filter(u=>/(TOKEN|PASSWORD|SECRET)$/i.test(u))[0]||(o.required.length===1?o.required[0]:null);if(!i){let u=new Error(`${o.key} has no single token field; provide each of [${o.required.join(", ")}] explicitly`);throw u.code="NEEDS_EXPLICIT_KEYS",u}let a=new Set([i,...Object.keys(n||{}).filter(u=>n[u]!=null&&String(n[u]).trim())]),c=ct(e),l=o.required.filter(u=>!a.has(u)&&!String(c[u]||"").trim());if(l.length){let u=new Error(`${o.key} also requires [${l.join(", ")}]; pass them explicitly (setup would otherwise be marked ready while unusable)`);throw u.code="MISSING_REQUIRED",u}at(e,i,r);for(let[u,y]of Object.entries(n||{}))y!=null&&String(y).trim()&&at(e,u,y);return{platform:o.key,set:o.required,profile:e,path:ke(e)}}function Vt(){return Fe.join(N(),"setup-state.json")}function V(e={}){D(N());let t=Vt(),r={};if(F.existsSync(t))try{r=JSON.parse(F.readFileSync(t,"utf8"))}catch{r={}}let n={...r,...e,updatedAt:new Date().toISOString(),host:Wt.hostname()};return F.writeFileSync(t,JSON.stringify(n,null,2)+`
|
|
5
|
+
`,{mode:384}),n}import R from"node:fs";import T from"node:path";import{createHash as Jt}from"node:crypto";import{spawnSync as oe}from"node:child_process";var Xt="0.19.0",ut=`hermes-agent==${Xt}`,je=[3,11],Ue=[3,14],pe="3.13",_e="0.12.1",Ae=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 Zt(e,{windows:t=process.platform==="win32"}={}){let r=Buffer.isBuffer(e)?e:Buffer.from(e),n=t?Ae.windows:Ae.posix,o=Jt("sha256").update(r).digest("hex"),s=r.toString("utf8");return o===n.sha256&&s.length>=1e3&&s.includes(_e)}function J(){return T.join(N(),"runtime")}function ft(){return T.join(J(),"venv")}function Ke(e){let t=process.platform==="win32"?"Scripts":"bin",r=process.platform==="win32"?`${e}.exe`:e;return T.join(ft(),t,r)}function Se(){return Ke("hermes")}function Qt(){let e=Ke("python3");return R.existsSync(e)?e:Ke("python")}function me(){return T.join(J(),"uv",process.platform==="win32"?"uv.exe":"uv")}function ne(e){let t=process.platform==="win32"&&!T.extname(e)?["",".exe",".cmd",".bat"]:[""];for(let r of(process.env.PATH||"").split(T.delimiter))if(r)for(let n of t){let o=T.join(r,`${e}${n}`);try{if(R.existsSync(o))return o}catch{}}return null}function er(e){let t=/Python (\d+)\.(\d+)\.(\d+)/.exec(e||"");return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function tr(e){if(!e)return!1;let[t,r]=e;return!(t<je[0]||t===je[0]&&r<je[1]||t>Ue[0]||t===Ue[0]&&r>=Ue[1])}function rr(){let e=[process.env.ORACLE_PYTHON,"python3.13","python3.12","python3.11","python3","python"].filter(Boolean);for(let t of e){let r=T.isAbsolute(t)?R.existsSync(t)?t:null:ne(t);if(!r)continue;let n=oe(r,["--version"],{encoding:"utf8",timeout:15e3}),o=er(`${n.stdout||""}${n.stderr||""}`);if(tr(o))return{bin:r,version:o.join("."),source:"host"}}return null}function nr(){return process.env.ORACLE_UV_BIN||ne("uv")||(R.existsSync(T.join(te(),".local","bin","uv"))?T.join(te(),".local","bin","uv"):null)||(R.existsSync(me())?me():null)}function or(e,t){let r=["const fs=require('node:fs');","const [url,dest]=process.argv.slice(1);","fetch(url).then(r=>{if(!r.ok)throw new Error('http '+r.status);return r.arrayBuffer()})",".then(b=>fs.writeFileSync(dest,Buffer.from(b)))",".catch(e=>{console.error(e.message);process.exit(1)});"].join("");return oe(process.execPath,["-e",r,e,t],{encoding:"utf8",timeout:2*6e4})}function sr({quiet:e=!1}={}){let t=nr();if(t)return{ok:!0,bin:t,reused:!0};D(J());let r=process.platform==="win32",n=T.join(J(),r?"uv-install.ps1":"uv-install.sh"),o=r?Ae.windows:Ae.posix,s=or(o.url,n);if(s.status!==0)return{ok:!1,reason:`could not download the uv installer (${s.status})`,stderr:(s.stderr||"").slice(-800)};let i=R.readFileSync(n);if(!Zt(i,{windows:r}))return{ok:!1,reason:`uv ${_e} installer checksum mismatch`};let a=T.dirname(me());D(a);let c=r?ne("powershell.exe")||ne("powershell"):ne("sh")||"/bin/sh";if(!c)return{ok:!1,reason:r?"PowerShell not found":"sh not found"};let u=oe(c,r?["-NoProfile","-ExecutionPolicy","Bypass","-File",n]:[n],{stdio:e?"pipe":"inherit",encoding:"utf8",timeout:5*6e4,env:{...process.env,UV_INSTALL_DIR:a,UV_NO_MODIFY_PATH:"1"}});return u.status!==0||!R.existsSync(me())?{ok:!1,reason:`uv install failed (${u.status})`,stderr:(u.stderr||"").slice(-800)}:{ok:!0,bin:me(),reused:!1}}function lt({quiet:e=!1}={}){let t=sr({quiet:e});if(!t.ok)return t;let r=t.bin,n={...process.env,UV_PYTHON_INSTALL_DIR:T.join(J(),"python"),UV_CACHE_DIR:T.join(J(),"cache")},o=oe(r,["python","install","--no-bin",pe],{stdio:e?"pipe":"inherit",encoding:"utf8",timeout:15*6e4,env:n});if(o.status!==0)return{ok:!1,reason:`uv python install ${pe} failed (${o.status})`,stderr:(o.stderr||"").slice(-800)};let s=oe(r,["python","find",pe],{encoding:"utf8",timeout:6e4,env:n}),i=(s.stdout||"").trim().split(/\r?\n/)[0];return s.status!==0||!i||!R.existsSync(i)?{ok:!1,reason:`uv could not locate python ${pe}`}:{ok:!0,bin:i,version:pe,source:"uv"}}function se(){if(process.env.ORACLE_HERMES_BIN)return{ok:!0,bin:process.env.ORACLE_HERMES_BIN,source:"env"};let e=Se();if(R.existsSync(e))return{ok:!0,bin:e,source:"managed"};let t=ne("hermes");return t?{ok:!0,bin:t,source:"path"}:{ok:!1,bin:null,source:null}}function Be(e,t,{quiet:r}){return oe(e,t,{stdio:r?"pipe":"inherit",encoding:"utf8",timeout:20*6e4})}function dt({quiet:e=!1,upgrade:t=!1}={}){let r=rr();if(!r){let l=lt({quiet:e});if(l.ok)r={bin:l.bin,version:l.version,source:"uv"};else return{ok:!1,reason:`no supported python found (need 3.11-3.13) and uv could not provide one: ${l.reason}. install uv (https://docs.astral.sh/uv) or python 3.13, then re-run 'oracle bootstrap'`}}D(J());let n=ft();if(R.existsSync(Se())&&!t)return{ok:!0,bin:Se(),reused:!0};if(!R.existsSync(T.join(n,"pyvenv.cfg"))){let l=Be(r.bin,["-m","venv",n],{quiet:e});if(l.status!==0&&r.source!=="uv"){R.rmSync(n,{recursive:!0,force:!0});let u=lt({quiet:e});if(u.ok)r={bin:u.bin,version:u.version,source:"uv"},l=Be(r.bin,["-m","venv",n],{quiet:e});else return{ok:!1,reason:`python -m venv failed (${l.status}) and uv fallback failed: ${u.reason}`,stderr:(l.stderr||"").slice(-800)}}if(l.status!==0)return{ok:!1,reason:`isolated python -m venv failed (${l.status})`,stderr:(l.stderr||"").slice(-800)}}let s=Qt();if(!R.existsSync(s))return{ok:!1,reason:`venv python missing at ${s}`};let i=["-m","pip","install","--disable-pip-version-check"];t&&i.push("--upgrade"),i.push(ut);let a=Be(s,i,{quiet:e});if(a.status!==0)return{ok:!1,reason:`pip install ${ut} failed (${a.status})`,stderr:(a.stderr||"").slice(-1200)};let c=Se();return R.existsSync(c)?{ok:!0,bin:c,reused:!1,python:r.version}:{ok:!1,reason:`hermes entrypoint not found after install (${c})`}}import{createHash as ir,randomBytes as ze,timingSafeEqual as ar}from"node:crypto";import L from"node:fs";import j from"node:path";import cr from"node:readline/promises";import{spawn as ur,spawnSync as lr}from"node:child_process";var ae=Object.freeze({"anthropic-oauth":{aliases:["anthropic-oauth","anthropic","claude","claude-oauth"],clientId:"9d1c250a-e61b-44d9-88ed-5944d1962f5e",authorizeUrl:"https://claude.ai/oauth/authorize",tokenUrl:"https://platform.claude.com/v1/oauth/token",redirectUri:"https://console.anthropic.com/oauth/code/callback",scope:"org:create_api_key user:profile user:inference",baseUrl:"https://api.anthropic.com/v1",model:"claude-sonnet-4-6",protocol:"anthropic-messages"},"openai-codex":{aliases:["openai-codex","openai-oauth","codex","codex-oauth"],clientId:"app_EMoamEEZ73f0CkXaXp7hrann",issuer:"https://auth.openai.com",tokenUrl:"https://auth.openai.com/oauth/token",baseUrl:"https://chatgpt.com/backend-api/codex",model:"gpt-5.6-sol",protocol:"responses"},"xai-oauth":{aliases:["xai-oauth","xai","grok","grok-oauth"],clientId:"b1a00492-073a-47ea-816f-4c329264a828",issuer:"https://auth.x.ai",discoveryUrl:"https://auth.x.ai/.well-known/openid-configuration",deviceUrl:"https://auth.x.ai/oauth2/device/code",scope:"openid profile email offline_access grok-cli:access api:access",baseUrl:"https://api.x.ai/v1",model:"grok-4.6",protocol:"responses"}}),fr=12e4;function dr(e={}){return typeof e.now=="function"?Number(e.now()):Date.now()}function X(e){let t=String(e||"").trim().toLowerCase();for(let[r,n]of Object.entries(ae))if(n.aliases.includes(t))return r;throw new Error(`unsupported OAuth provider: ${e||"(empty)"}`)}function W(e){let t=X(e);return{id:t,...ae[t]}}function P(e,t={}){if(!L.existsSync(e))return t;try{let r=JSON.parse(L.readFileSync(e,"utf8"));if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid object");return r}catch{throw new Error(`credential store is unreadable or corrupt: ${j.basename(e)}`)}}function mt(e){D(e),process.platform!=="win32"&&L.chmodSync(e,448)}function z(e,t){mt(j.dirname(e));let r=`${e}.${process.pid}.${ze(4).toString("hex")}.tmp`;L.writeFileSync(r,`${JSON.stringify(t,null,2)}
|
|
6
|
+
`,{mode:384}),L.renameSync(r,e),process.platform!=="win32"&&L.chmodSync(e,384)}function 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 r==="anthropic-oauth"?br(n):r==="openai-codex"?kr(n):xr(n)}import Me from"node:fs";import Ge from"node:path";var vr=new Set(["openrouter","openai","anthropic","xai","deepseek","gemini","kimi","mistral","nous","qwen","glm","local","ollama","custom","anthropic-oauth","openai-codex","xai-oauth"]);function $e(e){return String(e||"").trim()||void 0}function Sr(e,{required:t=!1}={}){let r=$e(e)?.toLowerCase();if(!r){if(t)throw new Error("model provider is required");return}if(!vr.has(r))throw new Error(`unsupported provider: ${r}`);return r}function _r(e,{required:t=!1}={}){let r=$e(e);if(!r){if(t)throw new Error("model is required");return}if(r.includes("..")||r.startsWith("/")||!/^[a-zA-Z0-9._:/-]{1,200}$/.test(r))throw new Error("invalid model id");return r}function Ar(e){let t=$e(e);if(!t||t.length>2048)throw new Error("invalid custom base URL");let r;try{r=new URL(t)}catch{throw new Error("invalid custom base URL")}let n=r.hostname.toLowerCase().replace(/^\[|\]$/g,""),o=n==="localhost"||n==="127.0.0.1"||n==="::1";if(r.protocol!=="https:"&&!(r.protocol==="http:"&&o)||r.username||r.password||r.search||r.hash)throw new Error("custom base URL must use HTTPS or loopback HTTP without credentials, query, or fragment");return r.toString().replace(/\/+$/,"")}function Oe({provider:e,model:t,baseUrl:r}={},{requireModel:n=!1}={}){let o=Sr(e),s=_r(t,{required:n});if(o==="custom")return{provider:o,...s?{model:s}:{},baseUrl:Ar(r)};if($e(r))throw new Error("baseUrl is only supported for the custom provider");return{...o?{provider:o}:{},...s?{model:s}:{}}}var Er=new Set(["auto","standalone","hermes","remote","arch"]);function $r(){return Ge.join(N(),"model.json")}function ce(e){return String(e||"").trim()||void 0}function Or(e={}){let t=ce(e.backend)?.toLowerCase()||"auto",r=Oe({provider:e.provider,model:e.model,baseUrl:e.baseUrl},{requireModel:t==="standalone"}),n=ce(e.apiKeyEnv),o=Number.parseInt(String(e.contextLength||""),10),s=ce(e.reasoningEffort),i=ce(e.computeHost||e.remoteHost),a=ce(e.computeUser||e.remoteUser),c=ce(e.computePath||e.remotePath);if(!Er.has(t))throw new Error(`unsupported backend: ${t}`);if(process.env.ORACLE_PUBLIC_DESKTOP==="1"&&["remote","arch"].includes(t))throw new Error("remote compute backends are disabled in the public desktop");if(n&&!/^[A-Z][A-Z0-9_]*$/.test(n))throw new Error("api key env must be an uppercase environment variable name");if(t==="remote"&&!i)throw new Error("remote backend requires computeHost");return{backend:t,...r,...n?{apiKeyEnv:n}:{},...Number.isFinite(o)&&o>0?{contextLength:o}:{},...s?{reasoningEffort:s}:{},...i?{computeHost:i}:{},...a?{computeUser:a}:{},...c?{computePath:c}:{}}}function Te(e){let t=Or(e),r=$r();D(Ge.dirname(r)),process.platform!=="win32"&&Me.chmodSync(Ge.dirname(r),448);let n=`${r}.${process.pid}.tmp`;return Me.writeFileSync(n,`${JSON.stringify(t,null,2)}
|
|
8
|
+
`,{mode:384}),Me.renameSync(n,r),process.platform!=="win32"&&Me.chmodSync(r,384),t}var gt=Object.freeze({openrouter:{model:"openrouter/auto"},openai:{model:"gpt-4.1-mini"},anthropic:{model:"claude-sonnet-4-6"},xai:{model:"grok-4.6"},deepseek:{model:"deepseek-chat"},gemini:{model:"gemini-2.5-flash"},kimi:{model:"kimi-k3"},mistral:{model:"mistral-large-latest"},nous:{model:"moonshotai/kimi-k3"},qwen:{model:"qwen-plus"},glm:{model:"glm-4.5"},custom:{model:""}});function Ve(e,t){let r=e.indexOf(t);return r>=0&&e[r+1]?e[r+1]:""}async function Mr(){let e="";for await(let t of process.stdin)e+=t;return e.trim()}function Tr(e="API key: "){if(!process.stdin.isTTY||!process.stdin.setRawMode)throw new Error("non-interactive API-key input requires --stdin");return process.stdout.write(e),new Promise((t,r)=>{let n="",o=()=>{process.stdin.off("data",s),process.stdin.setRawMode(!1),process.stdin.pause(),process.stdout.write(`
|
|
9
9
|
`)},s=i=>{let a=String(i);for(let c of a){if(c==="\r"||c===`
|
|
10
|
-
`){o(),t(n.trim());return}if(c===""){o(),r(new Error("cancelled"));return}c==="\x7F"||c==="\b"?n=n.slice(0,-1):n+=c}};process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",s)})}function Je(e,t,{baseUrl:r=""}={}){if(e==="custom"&&!String(r||"").trim())throw new Error("custom provider requires --base-url");return{backend:"standalone",...Oe({provider:e,model:t,baseUrl:r},{requireModel:!0})}}function yt(e,t,r={}){return Te(Je(e,t,r))}function
|
|
10
|
+
`){o(),t(n.trim());return}if(c===""){o(),r(new Error("cancelled"));return}c==="\x7F"||c==="\b"?n=n.slice(0,-1):n+=c}};process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",s)})}function Je(e,t,{baseUrl:r=""}={}){if(e==="custom"&&!String(r||"").trim())throw new Error("custom provider requires --base-url");return{backend:"standalone",...Oe({provider:e,model:t,baseUrl:r},{requireModel:!0})}}function yt(e,t,r={}){return Te(Je(e,t,r))}function Rr(e){process.stdout.write(`storage: ${e.storage}
|
|
11
11
|
`);let t=Object.entries(e.providers||{}),r=Object.entries(e.apiKeys||{});if(!t.length&&!r.length){process.stdout.write(`no credentials configured
|
|
12
12
|
`);return}for(let[n,o]of t){let s=o.expiresAt?new Date(o.expiresAt).toISOString():"unknown";process.stdout.write(`${n}: ${o.loggedIn?"logged in":"missing"}, expires ${s}
|
|
13
13
|
`)}for(let[n,o]of r)process.stdout.write(`${n}: API key ${o.configured?"configured":"missing"}
|
|
14
|
-
`)}function
|
|
15
|
-
`)}var ue={name:"auth",summary:"login with Claude, Codex, or Grok OAuth; store provider API keys",group:"read",usage:
|
|
16
|
-
`):
|
|
17
|
-
`),0}if(r==="api-key"){let o=String(t.find(c=>!c.startsWith("-"))||"").trim().toLowerCase();if(!o)throw new Error("usage: oracle auth api-key PROVIDER [--stdin]");if(!Object.hasOwn(gt,o))throw new Error(`unsupported API-key provider: ${o}`);let s=Ve(t,"--model")||gt[o].model,i=Ve(t,"--base-url");Je(o,s,{baseUrl:i});let a=t.includes("--stdin")?await
|
|
14
|
+
`)}function Pr(){return["oracle auth, configure OAuth or API-key authentication",""," oracle auth login claude|codex|grok [--model MODEL] [--no-browser]"," oracle auth api-key PROVIDER [--model MODEL] [--base-url URL]"," PROVIDER: openrouter|openai|anthropic|xai|deepseek|gemini|kimi|mistral|nous|qwen|glm|custom",` printf '%s\\n' "$KEY" | oracle auth api-key PROVIDER --stdin`," oracle auth status [--json]"," oracle auth logout PROVIDER","","OAuth and API keys are additive. Select any compatible model with oracle model --provider PROVIDER --model MODEL."].join(`
|
|
15
|
+
`)}var ue={name:"auth",summary:"login with Claude, Codex, or Grok OAuth; store provider API keys",group:"read",usage:Pr(),async run(e){let t=[...e.argv],r=t.shift()||"status",n=U();try{if(r==="status"){let o=n.status();return t.includes("--json")?process.stdout.write(`${JSON.stringify(o,null,2)}
|
|
16
|
+
`):Rr(o),0}if(r==="login"){let o=t.find(c=>!c.startsWith("-"));if(!o)throw new Error("usage: oracle auth login claude|codex|grok");let s=W(o),i=Ve(t,"--model")||s.model;Je(s.id,i);let a=await ht(s.id,{openFn:t.includes("--no-browser")?()=>!1:void 0});return await n.withLock(async()=>{let c=n.get(s.id);n.set(s.id,a);try{yt(s.id,i)}catch(l){throw c?n.set(s.id,c):n.remove(s.id),l}}),process.stdout.write(`${s.id}: logged in, stored in ${n.storage}
|
|
17
|
+
`),0}if(r==="api-key"){let o=String(t.find(c=>!c.startsWith("-"))||"").trim().toLowerCase();if(!o)throw new Error("usage: oracle auth api-key PROVIDER [--stdin]");if(!Object.hasOwn(gt,o))throw new Error(`unsupported API-key provider: ${o}`);let s=Ve(t,"--model")||gt[o].model,i=Ve(t,"--base-url");Je(o,s,{baseUrl:i});let a=t.includes("--stdin")?await Mr():await Tr();return await n.withLock(async()=>{let c=n.getApiKey(o);n.setApiKey(o,a);try{yt(o,s,{baseUrl:i})}catch(l){throw c?n.setApiKey(o,c):n.removeApiKey(o),l}}),process.stdout.write(`${o}: API key configured in ${n.storage}
|
|
18
18
|
`),0}if(r==="logout"){let o=String(t.find(a=>!a.startsWith("-"))||"").trim().toLowerCase();if(!o)throw new Error("usage: oracle auth logout PROVIDER");let s=!1;try{s=n.remove(X(o))}catch{}let i=n.removeApiKey(o);if(!s&&!i)throw new Error(`${o}: no local credential found`);return process.stdout.write(`${o}: local credential removed
|
|
19
19
|
`),0}throw new Error(`unknown auth action: ${r}`)}catch(o){return process.stderr.write(`oracle auth: ${o.message}
|
|
20
|
-
`),1}}};var
|
|
21
|
-
`}):e===9?I({name:"tab",sequence:" "}):e===127?I({name:"backspace",sequence:"\x7F"}):e===8?I({name:"backspace",sequence:"\b"}):e>=1&&e<=26?I({name:String.fromCharCode(e+96),ctrl:!0,sequence:String.fromCharCode(e)}):I({name:"unknown",sequence:String.fromCharCode(e)})}function
|
|
20
|
+
`),1}}};var Ir=Object.freeze([["#F3E2C5"," \u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2584 "],["#E4C89D"," \u2584\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2584 "],["#B77A4F"," \u2584\u2588\u2588\u2580\u2580\u2588\u2588\u2588\u2588\u2588\u2588\u2580\u2580\u2588\u2588\u2584 "],["#F1D7B7"," \u2584\u2588\u2588\u2588\u2588\u2584\u2584\u2588\u2588\u2588\u2588\u2584\u2584\u2588\u2588\u2588\u2588\u2584 "],["#B86F45","\u2588\u2588\u2588\u2588\u2580\u2580\u2580\u2580\u2588\u2588\u2588\u2588\u2580\u2580\u2580\u2580\u2588\u2588\u2588\u2588"],["#F4E5CC","\u2588\u2588\u2588\u2588\u2584\u2584\u2584\u2584\u2588\u2588\u2588\u2588\u2584\u2584\u2584\u2584\u2588\u2588\u2588\u2588"],["#C85B37","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2580\u2588\u2588\u2580\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588"],["#A86B45"," \u2580\u2588\u2588\u2588\u2588\u2580\u2580\u2588\u2588\u2588\u2588\u2580\u2580\u2588\u2588\u2588\u2588\u2580 "],["#D8B98D"," \u2580\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2580 "],["#E8D7BA"," \u2580\u2580\u2580\u2580\u2580\u2580\u2580\u2580 "]]);var Bn=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 Re=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 "]]),Lr=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 wt=Object.freeze([[" * + . ' * "," . * * + ' "],[" + . * + ' "," * ' + . + "],[" . * + * + "," + + . * * "],[" + ' * . * "," * * + ' . "]]),Cr=Object.freeze(wt[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 Nr(e){if(typeof e!="string")return null;let t=e.startsWith("#")?e.slice(1):e;if(!/^(?:[\da-f]{3}|[\da-f]{6})$/i.test(t))return null;let r=t.length===3?[...t].map(n=>n.repeat(2)).join(""):t;return{r:Number.parseInt(r.slice(0,2),16),g:Number.parseInt(r.slice(2,4),16),b:Number.parseInt(r.slice(4,6),16)}}function bt(e,t,r){let n=Nr(t);return n?`\x1B[${e};2;${n.r};${n.g};${n.b}m${String(r)}\x1B[0m`:String(r)}function Xe({color:e=!0}={}){return e&&!Object.hasOwn(process.env,"NO_COLOR")?Object.freeze({fg:(r,n)=>bt(38,r,n),bg:(r,n)=>bt(48,r,n),bold:r=>`\x1B[1m${String(r)}\x1B[0m`,dim:r=>`\x1B[2m${String(r)}\x1B[0m`}):Object.freeze({fg:(r,n)=>String(n),bg:(r,n)=>String(n),bold:r=>String(r),dim:r=>String(r)})}var Hn=Xe();function kt(e){return String(e).replace(/\u001B\[[0-9;]*m/g,"")}import{spawnSync as Yr}from"node:child_process";var he=Buffer.alloc(0);var Dr={A:"up",B:"down",C:"right",D:"left",H:"home",F:"end",P:"f1",Q:"f2",R:"f3",S:"f4"},Fr={1:"home",2:"insert",3:"delete",4:"end",5:"pageup",6:"pagedown",7:"home",8:"end"};function I({name:e=null,ctrl:t=!1,meta:r=!1,shift:n=!1,sequence:o=""}){return{name:e,ctrl:t,meta:r,shift:n,sequence:o}}function _t(e){return e<128?1:e>=240?4:e>=224?3:e>=192?2:1}function jr(e){return e>=64&&e<=126}function xt(e){let t=e.toLowerCase();return I({name:t,shift:e!==t,sequence:e})}function Ur(e){return e===13?I({name:"return",sequence:"\r"}):e===10?I({name:"return",sequence:`
|
|
21
|
+
`}):e===9?I({name:"tab",sequence:" "}):e===127?I({name:"backspace",sequence:"\x7F"}):e===8?I({name:"backspace",sequence:"\b"}):e>=1&&e<=26?I({name:String.fromCharCode(e+96),ctrl:!0,sequence:String.fromCharCode(e)}):I({name:"unknown",sequence:String.fromCharCode(e)})}function Br(e){let t=/^\u001b[\[O](\d*)(?:;(\d+))?(.)$/s.exec(e);if(!t)return I({name:"unknown",sequence:e});let r=t[1]===""?null:Number(t[1]),n=t[2]===void 0?null:Number(t[2]),o=t[3],s=null,i=n;if(o==="~"?s=Fr[r]??null:(s=Dr[o]??null,i===null&&r!==null&&r>1&&(i=r)),!s)return I({name:"unknown",sequence:e});let a=i===null?0:Math.max(0,i-1);return I({name:s,shift:(a&1)!==0,meta:(a&2)!==0,ctrl:(a&4)!==0,sequence:e})}function Kr(e,t,r,n){let o=()=>(r.push(I({name:"escape",sequence:"\x1B"})),1);if(t+1>=e.length)return n?o():0;let s=e[t+1];if(s===91||s===79){let l=t+2;for(;l<e.length&&!jr(e[l]);)l+=1;return l>=e.length?n?o():0:(r.push(Br(e.toString("utf8",t,l+1))),l+1-t)}if(s===27)return o();let i=_t(s);if(t+1+i>e.length)return n?o():0;let a=e.toString("utf8",t+1,t+1+i),c=a.toLowerCase();return r.push(I({name:c,meta:!0,shift:a!==c,sequence:`\x1B${a}`})),1+i}function vt(e,t){let r=[],n=0;for(;n<e.length;){let o=e[n];if(o===27){let i=Kr(e,n,r,t);if(i===0)return{keys:r,rest:Buffer.from(e.subarray(n))};n+=i;continue}if(o<32||o===127){r.push(Ur(o)),n+=1;continue}let s=_t(o);if(n+s>e.length)return t?(r.push(xt(e.toString("utf8",n))),{keys:r,rest:he}):{keys:r,rest:Buffer.from(e.subarray(n))};r.push(xt(e.toString("utf8",n,n+s))),n+=s}return{keys:r,rest:he}}function St(e){return Buffer.isBuffer(e)?e:e==null?he:typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}function At(){let e=he;return{push(t){let r=e.length===0?St(t):Buffer.concat([e,St(t)]),{keys:n,rest:o}=vt(r,!1);return e=o,n},flush(){if(e.length===0)return[];let{keys:t}=vt(e,!0);return e=he,t},get pending(){return e.length}}}var Ze=/\u001B\[[0-9;]*m/g;function Et(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 Hr(e){return[...kt(e)].reduce((t,r)=>t+Et(r),0)}function qr(e,t){if(t<=0)return"";let r=String(e).split(/(\u001B\[[0-9;]*m)/g),n="",o=0,s=!1;for(let i of r)if(i){if(Ze.test(i)){Ze.lastIndex=0,n+=i,s=i!=="\x1B[0m";continue}Ze.lastIndex=0;for(let a of i){let c=Et(a);if(o+c>t)return s?`${n}\x1B[0m`:n;n+=a,o+=c}}return n}function Pe(e,t,r="left"){let n=Math.max(0,Math.floor(Number(t)||0)),o=qr(String(e),n),s=Math.max(0,n-Hr(o));if(r==="right")return`${" ".repeat(s)}${o}`;if(r==="center"){let i=Math.floor(s/2);return`${" ".repeat(i)}${o}${" ".repeat(s-i)}`}return`${o}${" ".repeat(s)}`}async function $t(e,{headers:t={}}={}){let r=new AbortController,n=setTimeout(()=>r.abort(),6e3);try{let o=await fetch(e,{headers:t,signal:r.signal}),s=null;try{s=await o.json()}catch{s=null}return{status:o.status,body:s}}finally{clearTimeout(n)}}async function zr(e){let t=String(e||"").trim();if(!/^\d+:[\w-]{20,}$/.test(t))return{ok:!1,definitive:!0,error:"that does not look like a telegram bot token (123456:ABC\u2026)"};try{let{status:r,body:n}=await $t(`https://api.telegram.org/bot${t}/getMe`);return r===200&&n?.ok&&n.result?.username?{ok:!0,definitive:!0,username:`@${n.result.username}`}:r===401||r===404?{ok:!1,definitive:!0,error:"telegram rejected this token (check BotFather)"}:{ok:!1,definitive:!1,error:`telegram returned ${r} \u2014 saved anyway, verify later`}}catch{return{ok:!1,definitive:!1,error:"network unreachable \u2014 saved anyway, verify later"}}}async function Wr(e){let t=String(e||"").trim();if(t.length<50)return{ok:!1,definitive:!0,error:"that does not look like a discord bot token"};try{let{status:r,body:n}=await $t("https://discord.com/api/v10/users/@me",{headers:{Authorization:`Bot ${t}`}});return r===200&&n?.username?{ok:!0,definitive:!0,username:n.username}:r===401?{ok:!1,definitive:!0,error:"discord rejected this token (reset it in the developer portal)"}:{ok:!1,definitive:!1,error:`discord returned ${r} \u2014 saved anyway, verify later`}}catch{return{ok:!1,definitive:!1,error:"network unreachable \u2014 saved anyway, verify later"}}}async function Ie(e,t){let r=String(e||"").toLowerCase();return r==="telegram"?zr(t):r==="discord"?Wr(t):{ok:!1,definitive:!1}}var Gr=Object.freeze(["telegram","discord","whatsapp","slack","signal"]),Pt=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"}]),It=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 Vr(e,t){let r=String(t||"unset");return r==="ready"||r==="connected"||r==="configured"?e.fg($.ok,r):r==="manual"?e.fg($.warn,r):e.fg($.banner_dim,r||"unset")}function Ot({profile:e="oracle",statuses:t=null,oauthStatus:r=null,runtime:n=null}={}){let o=t;if(!o)try{o=re(e).statuses||{}}catch{o={}}let s=r;if(!s)try{s=U().status()}catch{s={providers:{},apiKeys:{}}}let i=n;if(!i)try{i=se()}catch{i={ok:!1}}let a=Pt.some(y=>{let m=W(y.id);return s.providers?.[m.id]?.loggedIn===!0}),c=It.some(y=>s.apiKeys?.[y.id]?.configured===!0),l=[{id:"model",label:"model / sign-in",note:"Claude \xB7 Codex \xB7 Grok \xB7 API keys",status:a||c?"ready":"unset",action:"model"}];i.ok||l.push({id:"runtime",label:"messaging runtime",note:"one-time install \u2014 powers telegram/discord bridge",status:"missing",action:"bootstrap"});let u=new Map(Q().map(y=>[y.key,y]));for(let y of Gr){let m=u.get(y);if(!m)continue;let O=o[m.key]||(m.required?.length?"unset":"manual"),v=!i.ok&&O==="ready"?"token set":O;l.push({id:m.key,label:m.name,note:m.note||"",status:v,action:m.required?.length?"token":"hermes",platform:m})}return l.push({id:"gateway",label:"restart gateway",note:"apply channel config",status:"",action:"gateway"},{id:"gateway-install",label:"start on boot",note:"keep the bot alive after reboot",status:"",action:"gateway-install"},{id:"done",label:"done",note:"back to oracle",status:"",action:"done",skip:!0}),l}function Mt(e=null){let t=e;if(!t)try{t=U().status()}catch{t={providers:{},apiKeys:{}}}let r=[];for(let n of Pt){let o=W(n.id),s=t.providers?.[o.id]?.loggedIn===!0;r.push({id:n.id,label:n.label,note:n.hint,status:s?"connected":"OAuth",action:"oauth",kind:"oauth"})}for(let n of It){let o=t.apiKeys?.[n.id]?.configured===!0;r.push({id:n.id,label:n.label,note:n.hint,status:o?"configured":"API key",action:"api-key",kind:"api-key"})}return r.push({id:"back",label:"back",note:"setup menu",status:"",action:"back",skip:!0}),r}function Le({width:e,palette:t,title:r,subtitle:n="",rows:o=[],index:s=0,footer:i="\u2191/\u2193 move enter select esc back"}={}){let a=Math.max(40,Math.floor(Number(e)||80)),c=Math.max(36,Math.min(a-4,72)),l=Math.max(0,Math.floor((a-c)/2)),u=Math.max(0,c-4),y=" ".repeat(l),m=A=>t.fg($.banner_border,A),O=A=>`${y}${A}`,v=(A="")=>O(`${m("\u2502")} ${Pe(A,u)} ${m("\u2502")}`),M="\u2500".repeat(Math.max(0,c-2)),k=[O(`${m("\u256D")}${m(M)}${m("\u256E")}`),v(t.bold(t.fg($.accent,r||"oracle setup"))),v(m("\u2500".repeat(u)))];return n&&(k.push(v(t.fg($.banner_dim,n))),k.push(v(""))),o.forEach((A,B)=>{let w=B===s,g=w?"\u203A":" ",p=String(A.label||A.id||""),f=String(A.note||""),h=A.status?Vr(t,A.status):"",x=` ${g} ${p}`,S=[h,f?t.fg($.banner_dim,f):""].filter(Boolean).join(" "),C=Math.max(1,u-Tt(x)-Tt(Lt(S))-1),K=`${x}${" ".repeat(C)}${S}`;w?k.push(v(t.bg($.selection_bg,t.bold(t.fg($.banner_text,Pe(K,u)))))):k.push(v(K))}),k.push(v("")),k.push(v(t.fg($.banner_dim,i))),k.push(O(`${m("\u2570")}${m(M)}${m("\u256F")}`)),k}function Jr({width:e,palette:t,platformKey:r="telegram",tokenLength:n=0,error:o=""}={}){let s=Math.max(40,Math.floor(Number(e)||80)),i=Math.max(36,Math.min(s-4,72)),a=Math.max(0,Math.floor((s-i)/2)),c=Math.max(0,i-4),l=" ".repeat(a),u=k=>t.fg($.banner_border,k),y=k=>`${l}${k}`,m=(k="")=>y(`${u("\u2502")} ${Pe(k,c)} ${u("\u2502")}`),O="\u2500".repeat(Math.max(0,i-2)),v=n>0?"\u2022".repeat(Math.min(n,40)):t.fg($.banner_dim,"paste token here (hidden)");return[y(`${u("\u256D")}${u(O)}${u("\u256E")}`),m(t.bold(t.fg($.accent,`setup \xB7 ${r}`))),m(u("\u2500".repeat(c))),m(t.fg($.banner_dim,"token stays local \xB7 never echoed \xB7 never sent to chat")),m(""),m(`${t.fg($.banner_dim,"token")} ${v}`),m(n?t.fg($.banner_dim,` ${n} characters`):""),m(o?t.fg($.warn,o):""),m(t.fg($.banner_dim,"type or paste backspace enter save esc cancel")),y(`${u("\u2570")}${u(O)}${u("\u256F")}`)]}function Xr({width:e,palette:t,title:r,subtitle:n,index:o=0,yesLabel:s="yes",noLabel:i="not now"}={}){return Le({width:e,palette:t,title:r,subtitle:n,rows:[{id:"yes",label:s,note:"",status:""},{id:"no",label:i,note:"",status:""}],index:o,footer:"\u2191/\u2193 move enter select esc skip"})}function Lt(e){return String(e||"").replace(/\u001b\[[0-9;]*m/g,"")}function Tt(e){return Lt(e).length}function le(e){e.write("\x1B[2J\x1B[H")}function ge(e,t){le(e),e.write(`${t.join(`
|
|
22
22
|
`)}
|
|
23
|
-
`)}function
|
|
23
|
+
`)}function Rt(e){let t=se();if(!t?.bin)return{code:1,error:"hermes not found \u2014 install hermes or run oracle bootstrap"};let r=Yr(t.bin,e,{stdio:"inherit",env:process.env});return{code:typeof r.status=="number"?r.status:1}}async function Ct({stdin:e=process.stdin,stdout:t=process.stdout,env:r=process.env,palette:n,profile:o="oracle",startAt:s="menu",runAuth:i=c=>ue.run({argv:c}),restartGateway:a=!0}={}){if(e?.isTTY!==!0||t?.isTTY!==!0)return{completed:!1,actions:[],reason:"non-tty"};let c=Math.max(40,Number(t.columns||80)),l=[],u="menu",y=0,m=0,O=0,v="",M="",k="",A=null,B=Ot({profile:o}),w=Mt();String(s).startsWith("token:")?(k=String(s).slice(6),u="token"):s==="model"&&(u="model");let g=At(),p=e.isRaw===!0;typeof e.setRawMode=="function"&&e.setRawMode(!0),e.resume();let f=()=>{u==="menu"?ge(t,Le({width:c,palette:n,title:"oracle setup",subtitle:"\u2191\u2193 enter \xB7 model + telegram/discord/whatsapp",rows:B,index:y})):u==="model"?ge(t,Le({width:c,palette:n,title:"sign in",subtitle:"subscription OAuth or API key",rows:w,index:m})):u==="token"?ge(t,Jr({width:c,palette:n,platformKey:k,tokenLength:v.length,error:M})):u==="confirm-gateway"?ge(t,Xr({width:c,palette:n,title:A?.title||"restart gateway?",subtitle:A?.subtitle||"applies bot tokens to the live bridge",index:O,yesLabel:"restart gateway now",noLabel:"later \u2014 oracle setup gateway restart"})):u==="notice"&&ge(t,Le({width:c,palette:n,title:A?.title||"setup",subtitle:A?.subtitle||"",rows:[{id:"ok",label:"continue",note:"",status:""}],index:0,footer:"enter continue esc menu"}))};f();let h=async x=>(typeof e.setRawMode=="function"&&e.setRawMode(p),e.pause(),le(t),x);return new Promise(x=>{let S=null,C=!1,K=b=>{C||(C=!0,S&&clearTimeout(S),e.off("data",nt),Promise.resolve(h(b)).then(x))},H=()=>{B=Ot({profile:o}),w=Mt()},Ne=async()=>{let b=v.trim();if(!b){M="empty token",f();return}M="checking token\u2026",f();let d={ok:!1,definitive:!1};try{d=await Ie(k,b)}catch{d={ok:!1,definitive:!1}}if(!d.ok&&d.definitive){v="",M=d.error||"platform rejected this token",f();return}try{let _=ve(o,k,b);V({lastPlatform:k,profile:o,ready:!0}),l.push(`token:${k}${d.ok?":verified":""}`),v="",M="";let E=!1;try{E=se().ok===!0}catch{E=!1}let ot=d.username?` \xB7 bot ${d.username}`:"";E?(A={title:`${k} saved${ot}`,subtitle:d.ok?`token verified live \xB7 ${_.path}`:`wrote credentials \xB7 ${_.path}`},O=0,u=a?"confirm-gateway":"menu"):(A={title:`${k} token saved${ot}`,subtitle:"next: install the messaging runtime (menu row) so the bot can answer"},O=0,u="notice"),H(),f()}catch(_){M=_?.message||"save failed",v="",f()}},tt=async b=>{if(!b||b.action==="done"){K({completed:!0,actions:l});return}if(b.action==="model"){u="model",m=0,f();return}if(b.action==="token"){k=b.id,v="",M="",u="token",f();return}if(b.action==="bootstrap"){typeof e.setRawMode=="function"&&e.setRawMode(p),e.pause(),le(t),t.write(`installing messaging runtime (one-time, a few minutes)\u2026
|
|
24
24
|
|
|
25
25
|
`);let d={ok:!1,reason:"unknown"};try{d=dt({})}catch(_){d={ok:!1,reason:_?.message||"install failed"}}l.push(`bootstrap:${d.ok?"ok":"fail"}`),typeof e.setRawMode=="function"&&e.setRawMode(!0),e.resume(),H(),A={title:d.ok?"messaging runtime ready":"runtime install failed",subtitle:d.ok?"pick telegram / discord next":d.reason||"see oracle bootstrap"},u="notice",f();return}if(b.action==="hermes"){typeof e.setRawMode=="function"&&e.setRawMode(p),e.pause(),le(t),t.write(`opening ${b.id} setup\u2026
|
|
26
|
-
`);let _=G(b.id)?.hermes||["gateway","setup"],E=
|
|
26
|
+
`);let _=G(b.id)?.hermes||["gateway","setup"],E=Rt(["-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",f();return}if(b.action==="gateway"||b.action==="gateway-install"){let d=b.action==="gateway-install"?"install":"restart";typeof e.setRawMode=="function"&&e.setRawMode(p),e.pause(),le(t),t.write(d==="install"?`installing boot service\u2026
|
|
27
27
|
`:`restarting gateway\u2026
|
|
28
|
-
`);let _=
|
|
28
|
+
`);let _=Rt(["-p",o,"gateway",d]);l.push(`gateway:${d}:${_.code}`),typeof e.setRawMode=="function"&&e.setRawMode(!0),e.resume(),A={title:_.code===0?d==="install"?"boot service installed":"gateway restarted":`gateway ${d} failed`,subtitle:_.code===0?d==="install"?"bot survives reboots now":"channels should be live":_.error||`exit ${_.code}`},u="notice",f()}},jt=async b=>{if(!b||b.action==="back"){u="menu",f();return}typeof e.setRawMode=="function"&&e.setRawMode(p),e.pause(),le(t);let d=b.kind==="oauth"?["login",b.id]:["api-key",b.id];t.write(`connecting ${b.label}\u2026
|
|
29
29
|
`);let _=1;try{_=await i(d)}catch(E){t.write(`${E?.message||E}
|
|
30
|
-
`),_=1}l.push(`model:${b.id}:${_}`),typeof e.setRawMode=="function"&&e.setRawMode(!0),e.resume(),H(),u="menu",f()},rt=b=>{for(let d of b){if(d.ctrl&&d.name==="c"){K({completed:!1,actions:l,reason:"cancel"});return}if(u==="token"){if(d.name==="escape"){v="",M="",u="menu",f();continue}if(d.name==="return"){Ne();continue}if(d.name==="backspace"||d.sequence==="\x7F"||d.sequence==="\b"){v=v.slice(0,-1),M="",f();continue}let E=d.sequence||"";if(E&&!d.ctrl&&!d.meta&&E!=="\x1B"){if(E.startsWith("\x1B"))continue;v+=E,M="",f()}continue}if(u==="confirm-gateway"){if(d.name==="up"||d.name==="down"){O=O===0?1:0,f();continue}if(d.name==="escape"){u="menu",f();continue}d.name==="return"&&(O===0?tt({action:"gateway",id:"gateway"}):(u="menu",f()));continue}if(u==="notice"){(d.name==="return"||d.name==="escape")&&(u="menu",f());continue}if(u==="model"){let E=w.length;if(d.name==="up"){m=E?(m-1+E)%E:0,f();continue}if(d.name==="down"){m=E?(m+1)%E:0,f();continue}if(d.name==="escape"){u="menu",f();continue}d.name==="return"&&
|
|
31
|
-
`)}async function
|
|
32
|
-
`),await t(90)}async function
|
|
30
|
+
`),_=1}l.push(`model:${b.id}:${_}`),typeof e.setRawMode=="function"&&e.setRawMode(!0),e.resume(),H(),u="menu",f()},rt=b=>{for(let d of b){if(d.ctrl&&d.name==="c"){K({completed:!1,actions:l,reason:"cancel"});return}if(u==="token"){if(d.name==="escape"){v="",M="",u="menu",f();continue}if(d.name==="return"){Ne();continue}if(d.name==="backspace"||d.sequence==="\x7F"||d.sequence==="\b"){v=v.slice(0,-1),M="",f();continue}let E=d.sequence||"";if(E&&!d.ctrl&&!d.meta&&E!=="\x1B"){if(E.startsWith("\x1B"))continue;v+=E,M="",f()}continue}if(u==="confirm-gateway"){if(d.name==="up"||d.name==="down"){O=O===0?1:0,f();continue}if(d.name==="escape"){u="menu",f();continue}d.name==="return"&&(O===0?tt({action:"gateway",id:"gateway"}):(u="menu",f()));continue}if(u==="notice"){(d.name==="return"||d.name==="escape")&&(u="menu",f());continue}if(u==="model"){let E=w.length;if(d.name==="up"){m=E?(m-1+E)%E:0,f();continue}if(d.name==="down"){m=E?(m+1)%E:0,f();continue}if(d.name==="escape"){u="menu",f();continue}d.name==="return"&&jt(w[m]);continue}let _=B.length;if(d.name==="up"){y=_?(y-1+_)%_:0,f();continue}if(d.name==="down"){y=_?(y+1)%_:0,f();continue}if(d.name==="escape"){K({completed:!0,actions:l,reason:"esc"});continue}d.name==="return"&&tt(B[y])}},nt=b=>{rt(g.push(b)),S&&(clearTimeout(S),S=null),g.pending>0&&(S=setTimeout(()=>{S=null,rt(g.flush())},30),typeof S.unref=="function"&&S.unref())};e.on("data",nt)})}var ye=Object.freeze([{alias:"claude",label:"Claude",hint:"Anthropic subscription"},{alias:"codex",label:"Codex",hint:"OpenAI subscription"},{alias:"grok",label:"Grok",hint:"xAI subscription"}]),we=Object.freeze([{id:"openrouter",label:"OpenRouter"},{id:"openai",label:"OpenAI"},{id:"anthropic",label:"Anthropic"},{id:"xai",label:"xAI"},{id:"deepseek",label:"DeepSeek"},{id:"gemini",label:"Gemini"},{id:"kimi",label:"Kimi"},{id:"mistral",label:"Mistral"},{id:"nous",label:"Nous Portal"},{id:"qwen",label:"Qwen"},{id:"glm",label:"GLM"}]),Ce=Object.freeze([...ye.map((e,t)=>({n:t+1,id:e.alias,label:e.label,kind:"oauth",hint:e.hint})),...we.map((e,t)=>({n:ye.length+t+1,id:e.id,label:e.label,kind:"api-key",hint:"API key"})),{n:ye.length+we.length+1,id:"custom",label:"Custom",kind:"api-key",hint:"OpenAI-compatible"},{n:ye.length+we.length+2,id:"local",label:"Local",kind:"local",hint:"llama.cpp :8080"},{n:ye.length+we.length+3,id:"ollama",label:"Ollama",kind:"local",hint:"ollama :11434"}]);function Qr(e){let t=String(e||"").trim().toLowerCase();if(!t||t==="skip")return{skip:!0};let r=Ce.find(n=>String(n.n)===t||n.id===t);return r||{unknown:!0,choice:t}}function Ft(e="sign in",t=0){let r=Re[t]||Re[0];return["",`${r[0]} oracle`,`${r[1]} ${e}`,r[2],r[3],r[4],""].join(`
|
|
31
|
+
`)}async function en(e){if(e.isTTY!==!0||process.env.NODE_TEST_CONTEXT||process.env.ORACLE_INSTALL_PLAIN==="1")return;let t=r=>new Promise(n=>setTimeout(n,r));for(let r=0;r<Re.length;r+=1)r>0&&e.write("\x1B[7A"),e.write(`${Ft("sign in",r)}
|
|
32
|
+
`),await t(90)}async function Co({stdin:e=process.stdin,stdout:t=process.stdout,readLine:r,runAuth:n=o=>ue.run({argv:o})}={}){if(await en(t),t.write(`${be()}
|
|
33
33
|
`),t.write(`number or name \xB7 enter skips
|
|
34
34
|
`),e.isTTY!==!0||t.isTTY!==!0)return{skipped:!0,reason:"non-tty"};t.write("> ");let o=r?await r():await new Promise(c=>{let l="",u=y=>{l+=String(y),(l.includes(`
|
|
35
|
-
`)||l.includes("\r"))&&(e.off("data",u),c(l.trim()))};e.on("data",u)}),s=
|
|
36
|
-
`),{skipped:!0,reason:"unknown"};let i=s.kind==="oauth"?["login",s.id]:["api-key",s.id],a=await n(i);return{skipped:!1,choice:s.id,code:a}}function be(e=U().status()){let t=[
|
|
35
|
+
`)||l.includes("\r"))&&(e.off("data",u),c(l.trim()))};e.on("data",u)}),s=Qr(o);if(s.skip)return{skipped:!0,reason:"skipped"};if(s.unknown)return t.write(`unknown choice '${s.choice}'
|
|
36
|
+
`),{skipped:!0,reason:"unknown"};let i=s.kind==="oauth"?["login",s.id]:["api-key",s.id],a=await n(i);return{skipped:!1,choice:s.id,code:a}}function be(e=U().status()){let t=[Ft("sign in"),"sign in with a subscription",""];for(let r of Ce.filter(n=>n.kind==="oauth")){let n=W(r.id),o=e.providers?.[n.id]?.loggedIn===!0;t.push(` ${String(r.n).padStart(2)} ${r.label.padEnd(12)} ${o?"connected":"OAuth"}`)}t.push("","or use an API key","");for(let r of Ce.filter(n=>n.kind==="api-key")){let n=r.id==="custom"?!1:e.apiKeys?.[r.id]?.configured===!0;t.push(` ${String(r.n).padStart(2)} ${r.label.padEnd(12)} ${n?"configured":"not configured"}`)}t.push("","or a local loopback model","");for(let r of Ce.filter(n=>n.kind==="local"))t.push(` ${String(r.n).padStart(2)} ${r.label.padEnd(12)} loopback`);return t.push("","Your key stays on this machine. Nothing is uploaded by Oracle.",""),t.join(`
|
|
37
37
|
`)}function Qe(){return["oracle setup, configure standalone OAuth, messaging, and the local agent surface",""," oracle setup menu + platform status"," oracle setup status same, machine-friendly with --json"," oracle setup model show Claude, Codex, Grok, OpenRouter, Qwen, GLM, Nous Portal, ..."," oracle setup model claude connect Anthropic OAuth + select standalone"," oracle setup model codex connect OpenAI OAuth + select standalone"," oracle setup model grok connect xAI OAuth + select standalone"," oracle setup model deepseek securely add a provider API key"," oracle setup model kimi securely add a Kimi API key"," oracle setup model qwen securely add a Qwen / DashScope API key"," oracle setup model glm securely add a GLM / Zhipu API key"," oracle setup model local select llama.cpp on 127.0.0.1:8080 (no key)"," oracle setup model ollama select Ollama on 127.0.0.1:11434 (no key)"," oracle setup model openrouter securely add an OpenRouter API key"," oracle setup model nous securely add a Nous Portal API key"," oracle setup messaging open hermes gateway setup wizard"," oracle setup telegram set TELEGRAM_BOT_TOKEN for profile"," oracle setup discord set DISCORD_BOT_TOKEN for profile"," oracle setup slack set slack tokens"," oracle setup <platform> any supported hermes platform"," oracle setup gateway [status|restart|start|stop]"," oracle setup profile [name] default: oracle","","chat:"," /setup arrow-key setup wizard (model + channels)"," /setup telegram jump to telegram token entry"," /setup status ready/unset (no secrets)","","model credentials stay in the OS keychain or private ~/.config/oracle storage.","messaging tokens stay local in ~/.hermes/profiles/<profile>/.env","oracle never prints secrets.","TTY default: oracle setup opens an \u2191\u2193 enter menu (ORACLE_SETUP_PLAIN=1 for text)."].join(`
|
|
38
|
-
`)}function
|
|
38
|
+
`)}function tn(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 rn(e){let t=[];for(let r=0;r<e.length;r++){if(e[r]==="--profile"||e[r]==="-p"){r+=1;continue}t.push(e[r])}return t}function et(e,{inherit:t=!0,env:r=process.env}={}){let n=se();if(!n.ok)return process.stderr.write(`oracle setup: Hermes not detected (opt-in only).
|
|
39
39
|
Native Oracle does not need Hermes.
|
|
40
40
|
To use Hermes messaging/gateway: install Hermes, or run \`oracle bootstrap\`, then retry.
|
|
41
41
|
Detect: oracle harness detect
|
|
42
|
-
`),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
|
|
42
|
+
`),1;let o=Zr(n.bin,e,{stdio:t?"inherit":"pipe",encoding:"utf8",env:r});return o.error?(process.stderr.write(`oracle setup: failed to run hermes: ${o.error.message}
|
|
43
|
+
`),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 Dt(e){if(!Y.isTTY||typeof Y.setRawMode!="function"){let t=new Error("interactive token entry requires a tty");throw t.code="NO_TTY",t}return Nt.write(`${e}: `),new Promise((t,r)=>{let n="",o=()=>{Y.off("data",s),Y.setRawMode(!1),Y.pause(),Nt.write(`
|
|
44
44
|
`)},s=i=>{for(let a of String(i)){if(a==="\r"||a===`
|
|
45
|
-
`){o(),t(n.trim());return}if(a===""){o(),r(new Error("cancelled"));return}a==="\x7F"||a==="\b"?n=n.slice(0,-1):n+=a}};Y.setRawMode(!0),Y.resume(),Y.on("data",s)})}async function
|
|
45
|
+
`){o(),t(n.trim());return}if(a===""){o(),r(new Error("cancelled"));return}a==="\x7F"||a==="\b"?n=n.slice(0,-1):n+=a}};Y.setRawMode(!0),Y.resume(),Y.on("data",s)})}async function nn(e,t,r=[]){let n=G(t);if(!n)return process.stderr.write(`oracle setup: unknown platform '${t}'
|
|
46
46
|
`),process.stderr.write(`known: ${Q().map(c=>c.key).join(", ")}
|
|
47
47
|
`),1;if(!n.required.length)return process.stdout.write(`opening hermes setup for ${n.key} (interactive)
|
|
48
48
|
`),V({lastPlatform:n.key,profile:e}),et(["-p",e,...n.hermes||["gateway","setup"]]);let o={},s=[];for(let c=0;c<r.length;c++){let l=r[c];if(l==="--token"&&r[c+1]){o.token=r[++c];continue}if(l==="--allowed-users"&&r[c+1]){o.allowedUsers=r[++c];continue}if(l==="--app-token"&&r[c+1]){o.appToken=r[++c];continue}if(l.startsWith("-"))return process.stderr.write(`oracle setup: unknown flag ${l}
|
|
49
|
-
`),1;s.push(l)}let i=o.token||s[0]||"";if(!i&&!process.stdin.isTTY&&(i=await readStdinSecret()),!i)try{i=await
|
|
49
|
+
`),1;s.push(l)}let i=o.token||s[0]||"";if(!i&&!process.stdin.isTTY&&(i=await readStdinSecret()),!i)try{i=await Dt(`${n.key} bot token`)}catch(c){if(c?.code==="NO_TTY")return process.stderr.write(`oracle setup ${n.key}: pipe the token on stdin (echo "$TOKEN" | oracle setup ${n.key}) or pass --token <value>
|
|
50
50
|
`),1;throw c}if(!i)return process.stderr.write(`aborted: empty token
|
|
51
|
-
`),1;let a={};if(o.allowedUsers&&(n.key==="telegram"&&(a.TELEGRAM_ALLOWED_USERS=o.allowedUsers),n.key==="discord"&&(a.DISCORD_ALLOWED_USERS=o.allowedUsers),n.key==="slack"&&(a.SLACK_ALLOWED_USERS=o.allowedUsers)),o.appToken&&n.key==="slack"&&(a.SLACK_APP_TOKEN=o.appToken),n.key==="slack"&&!a.SLACK_APP_TOKEN){let c=o.appToken||s[1]||"";if(!c&&process.stdin.isTTY&&(c=await
|
|
51
|
+
`),1;let a={};if(o.allowedUsers&&(n.key==="telegram"&&(a.TELEGRAM_ALLOWED_USERS=o.allowedUsers),n.key==="discord"&&(a.DISCORD_ALLOWED_USERS=o.allowedUsers),n.key==="slack"&&(a.SLACK_ALLOWED_USERS=o.allowedUsers)),o.appToken&&n.key==="slack"&&(a.SLACK_APP_TOKEN=o.appToken),n.key==="slack"&&!a.SLACK_APP_TOKEN){let c=o.appToken||s[1]||"";if(!c&&process.stdin.isTTY&&(c=await Dt("slack app token (xapp-...)")),!c)return process.stderr.write(`slack needs bot token + app token
|
|
52
52
|
`),1;a.SLACK_APP_TOKEN=c}try{let c=await Ie(n.key,i).catch(()=>({ok:!1,definitive:!1}));if(!c.ok&&c.definitive)return process.stderr.write(`oracle setup ${n.key}: ${c.error||"platform rejected this token"}
|
|
53
53
|
`),1;let l=ve(e,n.key,i,a);V({lastPlatform:n.key,profile:e,ready:!0});let u=c.ok&&c.username?`bot: ${c.username} (token verified live)
|
|
54
54
|
`:"",y=!c.ok&&c.error?`note: ${c.error}
|
|
@@ -56,9 +56,9 @@ Detect: oracle harness detect
|
|
|
56
56
|
`+u+y+`path: ${l.path}
|
|
57
57
|
next: oracle setup gateway restart
|
|
58
58
|
`),0}catch(c){return process.stderr.write(`oracle setup: ${c.message}
|
|
59
|
-
`),1}}var
|
|
59
|
+
`),1}}var No={name:"setup",summary:"configure standalone OAuth and messaging platforms",group:"read",usage:Qe(),async run(e){let t=[...e.argv],r=t.includes("--json"),n=tn(t),o=rn(t).filter(a=>a!=="--json"),s=(o[0]||"menu").toLowerCase(),i=o.slice(1);if(["-h","--help","help"].includes(s))return process.stdout.write(Qe()+`
|
|
60
60
|
`),0;if(["menu","list","ls"].includes(s)){if(r)return process.stdout.write(JSON.stringify({...re(n),modelAuth:U().status()},null,2)+`
|
|
61
|
-
`),0;if(process.stdin.isTTY===!0&&process.stdout.isTTY===!0&&!process.env.ORACLE_SETUP_PLAIN){let a=await
|
|
61
|
+
`),0;if(process.stdin.isTTY===!0&&process.stdout.isTTY===!0&&!process.env.ORACLE_SETUP_PLAIN){let a=await Ct({profile:n,palette:Xe({color:process.stdout.isTTY!==!1})});return a?.completed===!1&&a?.reason==="non-tty"?1:0}return process.stdout.write(be()),process.stdout.write(xe(n)),0}if(["status","show"].includes(s)){let a=re(n);return r?process.stdout.write(JSON.stringify({...a,modelAuth:U().status()},null,2)+`
|
|
62
62
|
`):(process.stdout.write(be()),process.stdout.write(xe(n)),process.stdout.write(`hermes root: ${de()}
|
|
63
63
|
`)),0}if(["model","oauth"].includes(s)){let a=String(i[0]||"").trim().toLowerCase();if(!a||["list","status","show"].includes(a))return process.stdout.write(be()),0;if(a==="local"||a==="ollama"){let l=Te({backend:"standalone",provider:a,model:a==="local"?"Qwen3-8B-Q4_K_M":"llama3.2",contextLength:a==="local"?65536:131072});return process.stdout.write(`oracle model: ${l.backend} / ${l.provider} / ${l.model}
|
|
64
64
|
loopback, no API key
|
|
@@ -67,6 +67,6 @@ loopback, no API key
|
|
|
67
67
|
`),et(["-p",n,"gateway","setup"]);if(s==="gateway"){let a=(i[0]||"status").toLowerCase();return["status","start","stop","restart","run","install"].includes(a)?et(["-p",n,"gateway",a]):(process.stderr.write(`usage: oracle setup gateway [status|start|stop|restart|run|install]
|
|
68
68
|
`),1)}if(s==="profile"){let a=i[0]||n;return process.stdout.write(`profile: ${a}
|
|
69
69
|
hermes: ${de()}/profiles/${a}
|
|
70
|
-
`),process.stdout.write(xe(a)),0}return G(s)?
|
|
70
|
+
`),process.stdout.write(xe(a)),0}return G(s)?nn(n,s,i):(process.stderr.write(`oracle setup: unknown verb '${s}'
|
|
71
71
|
${Qe()}
|
|
72
|
-
`),1)}};export{Ce as SETUP_CHOICES,
|
|
72
|
+
`),1)}};export{Ce as SETUP_CHOICES,No as default,be as renderModelSetup,Qr as resolveSetupChoice,Co as runFirstRunModelSetup};
|
package/package.json
CHANGED
|
Binary file
|
|
Binary file
|