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