@oracle-agent/oracle 0.18.1 → 0.19.1
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/cli/commands/chat.mjs +35 -35
- package/dist/cli/commands/data.mjs +5 -5
- package/dist/cli/commands/model.mjs +39 -39
- package/package.json +1 -1
|
@@ -1,45 +1,45 @@
|
|
|
1
|
-
var
|
|
2
|
-
`,{mode:384}),j.renameSync(n,e),process.platform!=="win32"&&j.chmodSync(e,384)}function Ro(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 ie(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 pt(e={}){let t=e.file||z.join(U(),"oauth.json"),n=e.metadataFile||z.join(z.dirname(t),"oauth-meta.json"),r=e.linksFile||z.join(z.dirname(t),"oauth-links.json"),o=()=>typeof e.now=="function"?Number(e.now()):Date.now(),i=e.spawnFn||To,s=e.keychain!==!1&&process.env.ORACLE_AUTH_FILE_STORE!=="1"&&Ro(i),c=s?"linux-secret-service":"private-file",u=`${t}.lock`;async function a(d){An(z.dirname(u));let l;for(let h=0;h<400;h+=1)try{l=j.openSync(u,"wx",384);break}catch(_){if(_?.code!=="EEXIST")throw _;try{Date.now()-j.statSync(u).mtimeMs>3e5&&j.unlinkSync(u)}catch{}await new Promise(y=>setTimeout(y,25))}if(l===void 0)throw new Error("timed out waiting for OAuth credential lock");try{return await d()}finally{try{j.closeSync(l)}catch{}try{j.unlinkSync(u)}catch{}}}function f(d,l="oauth"){return["application","oracle","kind",l,"provider",d]}function p(d){if(!j.existsSync(r))return null;let h=$(r,{providers:{}}).providers?.[d];if(!Array.isArray(h))return null;let _=[];for(let y of h)if(z.isAbsolute(String(y||"")))try{let m=$(y,{}),A=d==="anthropic-oauth"?m.claudeAiOauth:null;if(!A)continue;let M=ie(A);_.push({...M,refreshToken:"",source:"external-access-only"})}catch{}return _.length?_.find(y=>!y.expiresAt||y.expiresAt>o()+Le)||_[0]:null}function g(d){let l=q(d);if(s){let y=i("secret-tool",["lookup",...f(l)],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(!y.error&&y.status===0&&String(y.stdout||"").trim())try{return ie(JSON.parse(String(y.stdout).trim()))}catch{}return p(l)}let _=$(t,{providers:{}}).providers?.[l];if(_)try{return ie(_)}catch{}return p(l)}function x(d,l){let h=q(d),_=ie(l);if(s){let m=i("secret-tool",["store",`--label=Oracle ${h} OAuth`,...f(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},J(n,A),_}let y=$(t,{providers:{}});return y.providers||={},y.providers[h]=_,J(t,y),_}function w(d){let l=q(d);if(s){let y=i("secret-tool",["clear",...f(l)],{encoding:"utf8",stdio:["ignore","ignore","pipe"]}),m=$(n,{providers:{}});return m.providers&&delete m.providers[l],J(n,m),!y.error&&y.status===0}let h=$(t,{providers:{}}),_=!!h.providers?.[l];return h.providers&&delete h.providers[l],J(t,h),_}function S(d){let l=ct(d);if(s){let h=i("secret-tool",["lookup",...f(l,"api-key")],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return h.error||h.status!==0?"":String(h.stdout||"").trim()}return String($(t,{apiKeys:{}}).apiKeys?.[l]||"").trim()}function k(d,l){let h=ct(d),_=String(l||"").trim();if(!_)throw new Error("API key is empty");if(s){let m=i("secret-tool",["store",`--label=Oracle ${h} API key`,...f(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},J(n,A),!0}let y=$(t,{providers:{},apiKeys:{}});return y.apiKeys||={},y.apiKeys[h]=_,J(t,y),!0}function b(d){let l=ct(d);if(s){let y=i("secret-tool",["clear",...f(l,"api-key")],{encoding:"utf8",stdio:["ignore","ignore","pipe"]}),m=$(n,{providers:{},apiKeys:{}});return m.apiKeys&&delete m.apiKeys[l],J(n,m),!y.error&&y.status===0}let h=$(t,{providers:{},apiKeys:{}}),_=!!h.apiKeys?.[l];return h.apiKeys&&delete h.apiKeys[l],J(t,h),_}function v(){let d={},l={};if(s){let h=$(n,{providers:{},apiKeys:{}});for(let[_,y]of Object.entries(h.providers||{}))d[_]={loggedIn:!!g(_),expiresAt:Number(y.expiresAt||0),source:String(y.source||"oracle"),storage:c};for(let _ of Object.keys(h.apiKeys||{}))l[_]={configured:!!S(_),storage:c}}else{let h=$(t,{providers:{},apiKeys:{}});for(let[_,y]of Object.entries(h.providers||{}))d[_]={loggedIn:!!y?.accessToken,expiresAt:Number(y?.expiresAt||0),source:String(y?.source||"oracle"),storage:c};for(let[_,y]of Object.entries(h.apiKeys||{}))l[_]={configured:!!y,storage:c}}for(let h of Object.keys(Q)){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:l}}return Object.freeze({file:t,storage:c,get:g,set:x,remove:w,getApiKey:S,setApiKey:k,removeApiKey:b,status:v,withLock:a})}function se(){return En||=pt(),En}function ut(e){return Buffer.from(e).toString("base64url")}function $o(){let e=ut(lt(32));return{verifier:e,challenge:ut(Oo("sha256").update(e).digest()),state:ut(lt(24))}}function Po(e,t){let n=Buffer.from(String(e||"")),r=Buffer.from(String(t||""));return n.length===r.length&&Co(n,r)}function No(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 Io(n[0],n[1],{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function Ie(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 jo(e){if(e)return String(await e()).trim();let t=Lo.createInterface({input:process.stdin,output:process.stdout});try{return String(await t.question("Authorization code: ")).trim()}finally{t.close()}}function Te(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 ie({accessToken:n,refreshToken:r,expiresAt:ft(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 Fo(e){let t=Q["anthropic-oauth"],n=e.pkce||$o(),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 jo(e.inputFn),[s,c]=i.split("#",2);if(!s||!Po(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:s,state:c,redirect_uri:t.redirectUri,code_verifier:n.verifier})});return Te(await W(u,"Claude OAuth token exchange"),e)}async function Mo(e){let t=Q["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)),i;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){i=await W(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:Ie({grant_type:"authorization_code",code:i.authorization_code,redirect_uri:`${t.issuer}/deviceauth/callback`,client_id:t.clientId,code_verifier:i.code_verifier})});return Te(await W(s,"Codex OAuth token exchange"),e)}function X(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 Uo(e){let t=Q["xai-oauth"],n=await W(await e.fetchFn(t.discoveryUrl,{headers:{accept:"application/json"}}),"xAI OAuth discovery");X(n.authorization_endpoint);let r=X(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:Ie({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=X(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)),c=Math.ceil(Math.max(1,Number(o.expires_in||600))/s);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:Ie({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 Te(p,{...e,discovery:{authorization_endpoint:X(n.authorization_endpoint),token_endpoint:r}})}let f="";try{f=String((await a.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 ${a.status}${f?`, ${f}`:""})`)}throw new Error("xAI device authorization timed out")}async function On(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||No,output:t.output||(o=>process.stdout.write(`${o}
|
|
3
|
-
`)),now:t.now,pkce:t.pkce};return n==="anthropic-oauth"?
|
|
4
|
-
`),o(1))}),i.once("exit",(f,
|
|
5
|
-
`)}catch(M){clearTimeout(
|
|
6
|
-
`}):e===9?P({name:"tab",sequence:" "}):e===127?P({name:"backspace",sequence:"\x7F"}):e===8?P({name:"backspace",sequence:"\b"}):e>=1&&e<=26?P({name:String.fromCharCode(e+96),ctrl:!0,sequence:String.fromCharCode(e)}):P({name:"unknown",sequence:String.fromCharCode(e)})}function Lr(e){let t=/^\u001b[\[O](\d*)(?:;(\d+))?(.)$/s.exec(e);if(!t)return P({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=Ar[n]??null:(i=Er[o]??null,s===null&&n!==null&&n>1&&(s=n)),!i)return P({name:"unknown",sequence:e});let c=s===null?0:Math.max(0,s-1);return P({name:i,shift:(c&1)!==0,meta:(c&2)!==0,ctrl:(c&4)!==0,sequence:e})}function Ir(e,t,n,r){let o=()=>(n.push(P({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 a=t+2;for(;a<e.length&&!Or(e[a]);)a+=1;return a>=e.length?r?o():0:(n.push(Lr(e.toString("utf8",t,a+1))),a+1-t)}if(i===27)return o();let s=Rt(i);if(t+1+s>e.length)return r?o():0;let c=e.toString("utf8",t+1,t+1+s),u=c.toLowerCase();return n.push(P({name:u,meta:!0,shift:c!==u,sequence:`\x1B${c}`})),1+s}function It(e,t){let n=[],r=0;for(;r<e.length;){let o=e[r];if(o===27){let s=Ir(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(Cr(o)),r+=1;continue}let i=Rt(o);if(r+i>e.length)return t?(n.push(Lt(e.toString("utf8",r))),{keys:n,rest:fe}):{keys:n,rest:Buffer.from(e.subarray(r))};n.push(Lt(e.toString("utf8",r,r+i))),r+=i}return{keys:n,rest:fe}}function Tt(e){return Buffer.isBuffer(e)?e:e==null?fe:typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}function Tr(){let e=fe;return{push(t){let n=e.length===0?Tt(t):Buffer.concat([e,Tt(t)]),{keys:r,rest:o}=It(n,!1);return e=o,r},flush(){if(e.length===0)return[];let{keys:t}=It(e,!0);return e=fe,t},get pending(){return e.length}}}function Rr({history:e=[]}={}){let t=[...e];return{buffer:"",cursor:0,history:t,historyIndex:t.length,draft:""}}function Ne(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 je(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 $t(e,t){return O(e,{...t,historyIndex:e.history.length,draft:""})}function $r(e){if(e.ctrl||e.meta||!e.sequence||Sr.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 Pr(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 Nr(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 jr(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 Fr(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:O(e,{buffer:"",cursor:0,history:n,historyIndex:n.length,draft:""}),action:{type:"submit",value:t}}}function Mr(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:$t(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=Pr(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:Ne(n,r)}),action:null};case"f":return{state:O(e,{cursor:je(n,r)}),action:null};default:return{state:O(e,{}),action:null}}switch(t.name){case"return":return Fr(e);case"left":return{state:O(e,{cursor:Ne(n,r)}),action:null};case"right":return{state:O(e,{cursor:je(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 Nr(e);case"down":return jr(e);case"backspace":{if(r===0)return{state:O(e,{}),action:null};let o=Ne(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=je(n,r);return{state:O(e,{buffer:n.slice(0,r)+n.slice(o)}),action:null}}default:break}if($r(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 Pt(e={}){let{stdin:t,stdout:n,history:r=[],onSubmit:o,onCancel:i,onEof:s,onClear:c,onRender:u}=e,a=t??process.stdin,f=n??process.stdout,p=Tr(),g={submit:o,cancel:i,eof:s,clear:c},x=Rr({history:r}),w=!1,S=!1,k=!1,b=d=>{if(!d)return;let l=g[d.type];typeof l=="function"&&l(d.value,x)},v=d=>{for(let l of p.push(d)){let h=Mr(x,l);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){f&&typeof f.write=="function"&&f.write(d)},get isRunning(){return w}}}var Fe="\x1B[?25l",be="\x1B[?25h",Nt="\x1B[2K",_e="\x1B[0J";var Ur="\x1B\\[[0-9;?]*[a-zA-Z]";function Mt(){return new RegExp(Ur,"g")}function Dr(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 Br(e){let t=0;for(let n of Array.from(e))t+=Ut(n.codePointAt(0));return t}function Kr(e){return Br(Dr(e))}function Hr(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 zr(e,t){let n=String(e??"");if(t<=0)return"";if(Kr(n)<=t)return n;let r=Mt(),o="",i=0,s=!1,c=0,u=r.exec(n);for(;u!==null;){let f=Ft(n.slice(c,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=!Hr(u[0])),c=u.index+u[0].length,u=r.exec(n)}let a=Ft(n.slice(c),t-i);return o+=a.text,s?`${o}\x1B[0m`:o}function qr(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),c=[],u=0,a=null,f=!1,p=!1,g=()=>{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",g);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(l=>zr(String(l??""),s));if(a!==null)for(d.length>a&&(d=d.slice(0,a));d.length<a;)d.push("");return d}function k(b){if(!f&&qr(c,b))return;let v=[Fe];f&&c.length>0&&(v.push(w(0),"\r",_e),c=[],u=0),f=!1;let d=Math.min(c.length,b.length);for(let l=0;l<d;l+=1)c[l]!==b[l]&&v.push(w(l),"\r",Nt,b[l]);if(b.length>c.length){c.length>0&&v.push(w(c.length-1));for(let l=c.length;l<b.length;l+=1)l>0&&v.push(`
|
|
7
|
-
`),
|
|
8
|
-
`)||
|
|
9
|
-
`,e.write(
|
|
10
|
-
`)){if(o===""){r.push("");continue}let i="",s=0;for(let c of o.split(" ")){let u=H(c);if(s>0&&s+1+u>n&&(r.push(i),i="",s=0),u>n){s>0&&(r.push(i),i="",s=0);let a=c;for(;H(a)>n;){let f=Ke(a,n);r.push(f),a=a.slice(f.length)}i=a,s=H(a);continue}i=s===0?c:`${i} ${c}`,s=s===0?u:s+1+u}r.push(i)}return r}function
|
|
11
|
-
`)}function
|
|
12
|
-
`),m=
|
|
13
|
-
`),
|
|
14
|
-
`)}),
|
|
15
|
-
`)}),await
|
|
16
|
-
`)}function
|
|
17
|
-
`)}var
|
|
18
|
-
`)[0].replace(/^#+\s*/,"").trim()||e}function
|
|
1
|
+
var Gn=Object.defineProperty;var wt=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Jn=(e,t)=>{for(var n in t)Gn(e,n,{get:t[n],enumerable:!0})};import ue from"node:fs";import Vn from"node:os";import Y from"node:path";import{fileURLToPath as Xn}from"node:url";function le(){return process.env.ORACLE_FAKE_HOME||Vn.homedir()}function Zn(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function U(){return Zn()?process.env.ORACLE_CONFIG_DIR||Y.join(le(),".config","oracle"):Y.join(le(),".config","oracle")}function er(){return Y.join(U(),"desk.json")}function tr(){return Y.join(U(),"env")}function te({force:e=!1}={}){if(te._done&&!e)return te._result||null;te._done=!0;let t={},n=(o,i)=>{if(i==null)return;let s=String(i).trim();s&&(process.env[o]!=null&&String(process.env[o]).trim()!==""||(process.env[o]=s,t[o]=s))};try{let o=tr();if(ue.existsSync(o))for(let i of ue.readFileSync(o,"utf8").split(/\r?\n/)){let s=i.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!s||s[2].startsWith("#"))continue;let c=s[2];(c.startsWith('"')&&c.endsWith('"')||c.startsWith("'")&&c.endsWith("'"))&&(c=c.slice(1,-1)),n(s[1],c)}}catch{}try{let o=er();if(ue.existsSync(o)){let i=JSON.parse(ue.readFileSync(o,"utf8"));i&&typeof i=="object"&&(n("ORACLE_DESK_URL",i.deskUrl||i.dataUrl||i.url),n("ORACLE_DATA_URL",i.dataUrl||i.deskUrl||i.url),n("ORACLE_API_URL",i.apiUrl||i.dataUrl||i.deskUrl),n("ORACLE_PUBLIC_URL",i.publicUrl||i.deskUrl||i.dataUrl),n("ORACLE_EXEC_URL",i.execUrl),n("MAD_DESK_URL",i.deskUrl||i.dataUrl))}}catch{}let r=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return r&&(n("ORACLE_DESK_URL",r),n("ORACLE_DATA_URL",r),n("ORACLE_API_URL",r),n("ORACLE_PUBLIC_URL",r),n("MAD_DESK_URL",r)),te._result=Object.keys(t).length?t:null,te._result}function D(){return process.env.HERMES_HOME?Y.resolve(process.env.HERMES_HOME):Y.join(le(),".hermes")}function N(e){return ue.mkdirSync(e,{recursive:!0}),e}var Qn,B,V=wt(()=>{Qn=Y.dirname(Xn(import.meta.url)),B=Y.resolve(Qn,"../..");try{te()}catch{}});var Rn={};Jn(Rn,{createOAuthStore:()=>pt,default:()=>Bo,getOAuthStore:()=>ae,hasOAuthCredentials:()=>In,loginOAuth:()=>Cn,oauthProviderConfig:()=>dt,oauthProviderId:()=>q,oauthRuntimeConfig:()=>Tn,refreshOAuthCredentials:()=>mt,resolveOAuthCredentials:()=>Ln});import{createHash as Co,randomBytes as lt,timingSafeEqual as Lo}from"node:crypto";import j from"node:fs";import z from"node:path";import Io from"node:readline/promises";import{spawn as To,spawnSync as Ro}from"node:child_process";function ft(e={}){return typeof e.now=="function"?Number(e.now()):Date.now()}function q(e){let t=String(e||"").trim().toLowerCase();for(let[n,r]of Object.entries(Q))if(r.aliases.includes(t))return n;throw new Error(`unsupported OAuth provider: ${e||"(empty)"}`)}function dt(e){let t=q(e);return{id:t,...Q[t]}}function $(e,t={}){if(!j.existsSync(e))return t;try{let n=JSON.parse(j.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: ${z.basename(e)}`)}}function On(e){N(e),process.platform!=="win32"&&j.chmodSync(e,448)}function J(e,t){On(z.dirname(e));let n=`${e}.${process.pid}.${lt(4).toString("hex")}.tmp`;j.writeFileSync(n,`${JSON.stringify(t,null,2)}
|
|
2
|
+
`,{mode:384}),j.renameSync(n,e),process.platform!=="win32"&&j.chmodSync(e,384)}function $o(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 se(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 pt(e={}){let t=e.file||z.join(U(),"oauth.json"),n=e.metadataFile||z.join(z.dirname(t),"oauth-meta.json"),r=e.linksFile||z.join(z.dirname(t),"oauth-links.json"),o=()=>typeof e.now=="function"?Number(e.now()):Date.now(),i=e.spawnFn||Ro,s=e.keychain!==!1&&process.env.ORACLE_AUTH_FILE_STORE!=="1"&&$o(i),c=s?"linux-secret-service":"private-file",u=`${t}.lock`;async function a(x){On(z.dirname(u));let l;for(let p=0;p<400;p+=1)try{l=j.openSync(u,"wx",384);break}catch(_){if(_?.code!=="EEXIST")throw _;try{Date.now()-j.statSync(u).mtimeMs>3e5&&j.unlinkSync(u)}catch{}await new Promise(b=>setTimeout(b,25))}if(l===void 0)throw new Error("timed out waiting for OAuth credential lock");try{return await x()}finally{try{j.closeSync(l)}catch{}try{j.unlinkSync(u)}catch{}}}function f(x,l="oauth"){return["application","oracle","kind",l,"provider",x]}function d(x){if(!j.existsSync(r))return null;let p=$(r,{providers:{}}).providers?.[x];if(!Array.isArray(p))return null;let _=[];for(let b of p)if(z.isAbsolute(String(b||"")))try{let m=$(b,{}),E=x==="anthropic-oauth"?m.claudeAiOauth:null;if(!E)continue;let M=se(E);_.push({...M,refreshToken:"",source:"external-access-only"})}catch{}return _.length?_.find(b=>!b.expiresAt||b.expiresAt>o()+Le)||_[0]:null}function y(x){let l=q(x);if(s){let b=i("secret-tool",["lookup",...f(l)],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(!b.error&&b.status===0&&String(b.stdout||"").trim())try{return se(JSON.parse(String(b.stdout).trim()))}catch{}return d(l)}let _=$(t,{providers:{}}).providers?.[l];if(_)try{return se(_)}catch{}return d(l)}function h(x,l){let p=q(x),_=se(l);if(s){let m=i("secret-tool",["store",`--label=Oracle ${p} OAuth`,...f(p)],{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 E=$(n,{providers:{}});return E.providers||={},E.providers[p]={expiresAt:_.expiresAt,source:_.source},J(n,E),_}let b=$(t,{providers:{}});return b.providers||={},b.providers[p]=_,J(t,b),_}function g(x){let l=q(x);if(s){let b=i("secret-tool",["clear",...f(l)],{encoding:"utf8",stdio:["ignore","ignore","pipe"]}),m=$(n,{providers:{}});return m.providers&&delete m.providers[l],J(n,m),!b.error&&b.status===0}let p=$(t,{providers:{}}),_=!!p.providers?.[l];return p.providers&&delete p.providers[l],J(t,p),_}function k(x){let l=ct(x);if(s){let p=i("secret-tool",["lookup",...f(l,"api-key")],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return p.error||p.status!==0?"":String(p.stdout||"").trim()}return String($(t,{apiKeys:{}}).apiKeys?.[l]||"").trim()}function v(x,l){let p=ct(x),_=String(l||"").trim();if(!_)throw new Error("API key is empty");if(s){let m=i("secret-tool",["store",`--label=Oracle ${p} API key`,...f(p,"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 E=$(n,{providers:{},apiKeys:{}});return E.apiKeys||={},E.apiKeys[p]={configured:!0},J(n,E),!0}let b=$(t,{providers:{},apiKeys:{}});return b.apiKeys||={},b.apiKeys[p]=_,J(t,b),!0}function w(x){let l=ct(x);if(s){let b=i("secret-tool",["clear",...f(l,"api-key")],{encoding:"utf8",stdio:["ignore","ignore","pipe"]}),m=$(n,{providers:{},apiKeys:{}});return m.apiKeys&&delete m.apiKeys[l],J(n,m),!b.error&&b.status===0}let p=$(t,{providers:{},apiKeys:{}}),_=!!p.apiKeys?.[l];return p.apiKeys&&delete p.apiKeys[l],J(t,p),_}function S(){let x={},l={};if(s){let p=$(n,{providers:{},apiKeys:{}});for(let[_,b]of Object.entries(p.providers||{}))x[_]={loggedIn:!!y(_),expiresAt:Number(b.expiresAt||0),source:String(b.source||"oracle"),storage:c};for(let _ of Object.keys(p.apiKeys||{}))l[_]={configured:!!k(_),storage:c}}else{let p=$(t,{providers:{},apiKeys:{}});for(let[_,b]of Object.entries(p.providers||{}))x[_]={loggedIn:!!b?.accessToken,expiresAt:Number(b?.expiresAt||0),source:String(b?.source||"oracle"),storage:c};for(let[_,b]of Object.entries(p.apiKeys||{}))l[_]={configured:!!b,storage:c}}for(let p of Object.keys(Q)){if(x[p])continue;let _=d(p);_&&(x[p]={loggedIn:!0,expiresAt:_.expiresAt,source:_.source,storage:"external-access-source"})}return{storage:c,providers:x,apiKeys:l}}return Object.freeze({file:t,storage:c,get:y,set:h,remove:g,getApiKey:k,setApiKey:v,removeApiKey:w,status:S,withLock:a})}function ae(){return An||=pt(),An}function ut(e){return Buffer.from(e).toString("base64url")}function Po(){let e=ut(lt(32));return{verifier:e,challenge:ut(Co("sha256").update(e).digest()),state:ut(lt(24))}}function No(e,t){let n=Buffer.from(String(e||"")),r=Buffer.from(String(t||""));return n.length===r.length&&Lo(n,r)}function jo(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 To(n[0],n[1],{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function Ie(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 Fo(e){if(e)return String(await e()).trim();let t=Io.createInterface({input:process.stdin,output:process.stdout});try{return String(await t.question("Authorization code: ")).trim()}finally{t.close()}}function Te(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 se({accessToken:n,refreshToken:r,expiresAt:ft(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 Mo(e){let t=Q["anthropic-oauth"],n=e.pkce||Po(),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 Fo(e.inputFn),[s,c]=i.split("#",2);if(!s||!No(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:s,state:c,redirect_uri:t.redirectUri,code_verifier:n.verifier})});return Te(await W(u,"Claude OAuth token exchange"),e)}async function Uo(e){let t=Q["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)),i;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){i=await W(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:Ie({grant_type:"authorization_code",code:i.authorization_code,redirect_uri:`${t.issuer}/deviceauth/callback`,client_id:t.clientId,code_verifier:i.code_verifier})});return Te(await W(s,"Codex OAuth token exchange"),e)}function X(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 Do(e){let t=Q["xai-oauth"],n=await W(await e.fetchFn(t.discoveryUrl,{headers:{accept:"application/json"}}),"xAI OAuth discovery");X(n.authorization_endpoint);let r=X(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:Ie({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=X(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)),c=Math.ceil(Math.max(1,Number(o.expires_in||600))/s);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:Ie({grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:t.clientId,device_code:o.device_code})});if(a.ok){let d=await W(a,"xAI OAuth token exchange");return Te(d,{...e,discovery:{authorization_endpoint:X(n.authorization_endpoint),token_endpoint:r}})}let f="";try{f=String((await a.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 ${a.status}${f?`, ${f}`:""})`)}throw new Error("xAI device authorization timed out")}async function Cn(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||jo,output:t.output||(o=>process.stdout.write(`${o}
|
|
3
|
+
`)),now:t.now,pkce:t.pkce};return n==="anthropic-oauth"?Mo(r):n==="openai-codex"?Uo(r):Do(r)}async function mt(e,t,n={}){let r=q(e),o=Q[r],i=se(t);if(!i.refreshToken)throw new Error(`${r} OAuth credential cannot refresh; run oracle auth login`);let s=i.discovery,c,u=n.fetchFn||globalThis.fetch;if(r==="xai-oauth"){if(!s?.token_endpoint){let d=await u(o.discoveryUrl),y=await W(d,"xAI OAuth discovery");s={...y.authorization_endpoint?{authorization_endpoint:X(y.authorization_endpoint)}:{},token_endpoint:X(y.token_endpoint)}}c=X(s.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:Ie({grant_type:"refresh_token",refresh_token:i.refreshToken,client_id:o.clientId})}),f=await W(a,`${r} OAuth refresh`);return Te(f,{...n,refreshToken:i.refreshToken,discovery:s})}async function Ln(e,t={}){let n=q(e),r=t.store||ae(),o=r.get(n);if(!o)throw new Error(`${n} OAuth is not logged in; run oracle auth login ${e}`);let i=ft(t);if(o.source==="external-access-only"&&o.expiresAt&&o.expiresAt<=i+Le)throw new Error(`${n} external OAuth access source is expired or near expiry; refresh the source authority`);if(!o.expiresAt||o.expiresAt>i+Le)return o;let s=async()=>{let c=r.get(n);if(!c)throw new Error(`${n} OAuth is not logged in; run oracle auth login ${e}`);let u=ft(t);if(!c.expiresAt||c.expiresAt>u+Le)return c;let a=await mt(n,c,t);return r.set(n,a),a};return typeof r.withLock=="function"?r.withLock(s):s()}function In(e,t={}){try{return!!(t.store||ae()).get(e)?.accessToken}catch{return!1}}function Tn(e){let t=dt(e);return{kind:"standalone",provider:t.id,model:t.model,baseUrl:t.baseUrl,authType:"oauth",protocol:t.protocol}}var Q,Le,An,Bo,ht=wt(()=>{V();Q=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"}}),Le=12e4;Bo={createOAuthStore:pt,getOAuthStore:ae,hasOAuthCredentials:In,loginOAuth:Cn,oauthProviderConfig:dt,oauthProviderId:q,oauthRuntimeConfig:Tn,refreshOAuthCredentials:mt,resolveOAuthCredentials:Ln}});V();import C from"node:fs";import A from"node:path";import{spawnSync as hi}from"node:child_process";import vt from"node:fs";import rr from"node:path";var nr=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 $e(e){return String(e||"").trim().toLowerCase().replace(/^\/+/,"").replace(/\s+/g,"-")}function St(e){let t=$e(e);if(!t)return null;for(let n of nr)if(n.key===t||String(n.chainId).toLowerCase()===t||(n.aliases||[]).map($e).includes(t)||$e(n.name)===t)return n;return null}V();function or(){return rr.join(U(),"active-chain.json")}function ir(){let e=or();if(!vt.existsSync(e))return null;try{let t=JSON.parse(vt.readFileSync(e,"utf8"));if(!t||typeof t!="object"||!t.key)return null;let n=St(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 ge(e={}){let t=ir(),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}V();import kt from"node:fs";import sr from"node:path";var ar=new Set(["auto","standalone","hermes","remote","arch"]),cr=new Set(["openrouter","openai","xai","deepseek","gemini","custom","anthropic-oauth","openai-codex","xai-oauth"]);function ur(){return sr.join(U(),"model.json")}function K(e){return String(e||"").trim()||void 0}function lr(e={}){let t=K(e.backend)?.toLowerCase()||"auto",n=K(e.provider)?.toLowerCase(),r=K(e.model),o=K(e.baseUrl)?.replace(/\/+$/,""),i=K(e.apiKeyEnv),s=Number.parseInt(String(e.contextLength||""),10),c=K(e.reasoningEffort),u=K(e.computeHost||e.remoteHost),a=K(e.computeUser||e.remoteUser),f=K(e.computePath||e.remotePath);if(!ar.has(t))throw new Error(`unsupported backend: ${t}`);if(process.env.ORACLE_PUBLIC_DESKTOP==="1"&&["remote","arch"].includes(t))throw new Error("remote compute backends are disabled in the public desktop");if(n&&!cr.has(n))throw new Error(`unsupported provider: ${n}`);if(o&&n!=="custom")throw new Error("baseUrl is only supported for the custom provider");if(i&&!/^[A-Z][A-Z0-9_]*$/.test(i))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}:{},...i?{apiKeyEnv:i}:{},...Number.isFinite(s)&&s>0?{contextLength:s}:{},...c?{reasoningEffort:c}:{},...u?{computeHost:u}:{},...a?{computeUser:a}:{},...f?{computePath:f}:{}}}function Et(){let e=ur();if(!kt.existsSync(e))return null;try{return lr(JSON.parse(kt.readFileSync(e,"utf8")))}catch{return null}}import{spawn as fr}from"node:child_process";var dr=["SIGINT","SIGTERM","SIGHUP"];function ye(e,t=[],n={},r=e){return new Promise(o=>{let i=fr(e,t,n),s=!1,c=null,u=new Map(dr.map(f=>[f,()=>{c||=f,i.exitCode===null&&i.signalCode===null&&i.kill(f)}]));for(let[f,d]of u)process.on(f,d);let a=()=>{for(let[f,d]of u)process.off(f,d)};i.once("error",f=>{s||(s=!0,a(),process.stderr.write(`oracle: could not start ${r}: ${f.message}
|
|
4
|
+
`),o(1))}),i.once("exit",(f,d)=>{if(s)return;s=!0,a();let y=c||d;if(y){process.kill(process.pid,y);return}o(f??1)})})}import Ot from"node:fs";import ne from"node:path";V();var pr="0.19.0",Qi=`hermes-agent==${pr}`;var At="0.12.1",Zi=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 mr(){return ne.join(U(),"runtime")}function hr(){return ne.join(mr(),"venv")}function xr(e){let t=process.platform==="win32"?"Scripts":"bin",n=process.platform==="win32"?`${e}.exe`:e;return ne.join(hr(),t,n)}function gr(){return xr("hermes")}function yr(e){let t=process.platform==="win32"&&!ne.extname(e)?["",".exe",".cmd",".bat"]:[""];for(let n of(process.env.PATH||"").split(ne.delimiter))if(n)for(let r of t){let o=ne.join(n,`${e}${r}`);try{if(Ot.existsSync(o))return o}catch{}}return null}function Pe(){if(process.env.ORACLE_HERMES_BIN)return{ok:!0,bin:process.env.ORACLE_HERMES_BIN,source:"env"};let e=yr("hermes");if(e)return{ok:!0,bin:e,source:"path"};let t=gr();return Ot.existsSync(t)?{ok:!0,bin:t,source:"managed"}:{ok:!1,bin:null,source:null}}import{EventEmitter as Xr}from"node:events";import{spawn as br}from"node:child_process";import{EventEmitter as _r}from"node:events";import{createInterface as Ct}from"node:readline";var wr=15e3,Sr=12e4;function vr(e){let t=typeof e=="string"?e:e?.message||"Gateway request failed",n=new Error(t);return n.error=e,n}function kr(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 Lt({python:e,pythonArgs:t=[],cwd:n,env:r,spawnFn:o=br,startupTimeoutMs:i=wr,requestTimeoutMs:s=Sr}={}){let c=new _r,u=new Map,a=null,f=1,d=null,y=null,h=!1;function g(l){c.listenerCount("error")>0&&c.emit("error",l)}function k(l){for(let p of u.values())clearTimeout(p.timer),p.reject(l);u.clear()}function v(l){if(!("id"in l)){c.emit("event",l);return}let p=u.get(l.id);p&&(u.delete(l.id),clearTimeout(p.timer),"error"in l?p.reject(vr(l.error)):p.resolve(l.result))}function w(){return d||(d=new Promise((l,p)=>{let _=!1,b,m=I=>{_||(_=!0,clearTimeout(b),I?p(I):l())};try{a=o(e,[...t,"-m","tui_gateway.entry"],{cwd:n,env:r})}catch(I){m(I),g(I);return}let E=Ct({input:a.stdout}),M=Ct({input:a.stderr});E.on("line",I=>{let F;try{F=JSON.parse(I)}catch{c.emit("log",I);return}m(),v(F)}),M.on("line",I=>c.emit("log",kr(I))),a.once("error",I=>{m(I),k(I),g(I)}),a.once("exit",(I,F)=>{h=!0;let Z=new Error(`Gateway exited with code ${I} and signal ${F}`);m(Z),k(Z),c.emit("exit",{code:I,signal:F})}),b=setTimeout(()=>{m(new Error(`Gateway startup timed out after ${i} ms`))},i)}),d)}function S(l,p){if(!a||h)return Promise.reject(new Error("Gateway is not running"));let _=f++;return new Promise((b,m)=>{let E=setTimeout(()=>{u.delete(_),m(new Error(`Gateway request ${_} timed out after ${s} ms`))},s);u.set(_,{resolve:b,reject:m,timer:E});try{a.stdin.write(`${JSON.stringify({id:_,method:l,params:p})}
|
|
5
|
+
`)}catch(M){clearTimeout(E),u.delete(_),m(M)}})}function x(){if(y)return y;if(!a||h)return Promise.resolve();let l=new Error("Gateway stopped while requests were pending");return k(l),y=new Promise(p=>{a.once("exit",p);try{a.kill()}catch{p()}}),y}return{start:w,request:S,stop:x,on(l,p){return c.on(l,p),this},off(l,p){return c.off(l,p),this}}}var fe=Buffer.alloc(0),Er=new Set(["return","backspace","tab","escape","up","down","left","right","home","end","delete","insert","pageup","pagedown","unknown"]),Ar={A:"up",B:"down",C:"right",D:"left",H:"home",F:"end",P:"f1",Q:"f2",R:"f3",S:"f4"},Or={1:"home",2:"insert",3:"delete",4:"end",5:"pageup",6:"pagedown",7:"home",8:"end"};function P({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 $t(e){return e<128?1:e>=240?4:e>=224?3:e>=192?2:1}function Cr(e){return e>=64&&e<=126}function It(e){let t=e.toLowerCase();return P({name:t,shift:e!==t,sequence:e})}function Lr(e){return e===13?P({name:"return",sequence:"\r"}):e===10?P({name:"return",sequence:`
|
|
6
|
+
`}):e===9?P({name:"tab",sequence:" "}):e===127?P({name:"backspace",sequence:"\x7F"}):e===8?P({name:"backspace",sequence:"\b"}):e>=1&&e<=26?P({name:String.fromCharCode(e+96),ctrl:!0,sequence:String.fromCharCode(e)}):P({name:"unknown",sequence:String.fromCharCode(e)})}function Ir(e){let t=/^\u001b[\[O](\d*)(?:;(\d+))?(.)$/s.exec(e);if(!t)return P({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=Or[n]??null:(i=Ar[o]??null,s===null&&n!==null&&n>1&&(s=n)),!i)return P({name:"unknown",sequence:e});let c=s===null?0:Math.max(0,s-1);return P({name:i,shift:(c&1)!==0,meta:(c&2)!==0,ctrl:(c&4)!==0,sequence:e})}function Tr(e,t,n,r){let o=()=>(n.push(P({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 a=t+2;for(;a<e.length&&!Cr(e[a]);)a+=1;return a>=e.length?r?o():0:(n.push(Ir(e.toString("utf8",t,a+1))),a+1-t)}if(i===27)return o();let s=$t(i);if(t+1+s>e.length)return r?o():0;let c=e.toString("utf8",t+1,t+1+s),u=c.toLowerCase();return n.push(P({name:u,meta:!0,shift:c!==u,sequence:`\x1B${c}`})),1+s}function Tt(e,t){let n=[],r=0;for(;r<e.length;){let o=e[r];if(o===27){let s=Tr(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(Lr(o)),r+=1;continue}let i=$t(o);if(r+i>e.length)return t?(n.push(It(e.toString("utf8",r))),{keys:n,rest:fe}):{keys:n,rest:Buffer.from(e.subarray(r))};n.push(It(e.toString("utf8",r,r+i))),r+=i}return{keys:n,rest:fe}}function Rt(e){return Buffer.isBuffer(e)?e:e==null?fe:typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)}function Rr(){let e=fe;return{push(t){let n=e.length===0?Rt(t):Buffer.concat([e,Rt(t)]),{keys:r,rest:o}=Tt(n,!1);return e=o,r},flush(){if(e.length===0)return[];let{keys:t}=Tt(e,!0);return e=fe,t},get pending(){return e.length}}}function $r({history:e=[]}={}){let t=[...e];return{buffer:"",cursor:0,history:t,historyIndex:t.length,draft:""}}function Ne(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 je(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 Pt(e,t){return O(e,{...t,historyIndex:e.history.length,draft:""})}function Pr(e){if(e.ctrl||e.meta||!e.sequence||Er.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 Nr(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 jr(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 Fr(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 Mr(e){let t=e.buffer.trim();if(t==="")return{state:Pt(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 Ur(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:Pt(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=Nr(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:Ne(n,r)}),action:null};case"f":return{state:O(e,{cursor:je(n,r)}),action:null};default:return{state:O(e,{}),action:null}}switch(t.name){case"return":return Mr(e);case"left":return{state:O(e,{cursor:Ne(n,r)}),action:null};case"right":return{state:O(e,{cursor:je(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 jr(e);case"down":return Fr(e);case"backspace":{if(r===0)return{state:O(e,{}),action:null};let o=Ne(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=je(n,r);return{state:O(e,{buffer:n.slice(0,r)+n.slice(o)}),action:null}}default:break}if(Pr(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 Nt(e={}){let{stdin:t,stdout:n,history:r=[],onSubmit:o,onCancel:i,onEof:s,onClear:c,onRender:u}=e,a=t??process.stdin,f=n??process.stdout,d=Rr(),y={submit:o,cancel:i,eof:s,clear:c},h=$r({history:r}),g=!1,k=!1,v=!1,w=x=>{if(!x)return;let l=y[x.type];typeof l=="function"&&l(x.value,h)},S=x=>{for(let l of d.push(x)){let p=Ur(h,l);h=p.state,w(p.action),typeof u=="function"&&u(h)}};return{start(){g||(g=!0,a.isTTY&&typeof a.setRawMode=="function"&&(v=a.isRaw===!0,a.setRawMode(!0),k=!0),typeof a.resume=="function"&&a.resume(),a.on("data",S),typeof u=="function"&&u(h))},stop(){g&&(g=!1,typeof a.off=="function"?a.off("data",S):typeof a.removeListener=="function"&&a.removeListener("data",S),k&&typeof a.setRawMode=="function"&&(a.setRawMode(v),k=!1),typeof a.pause=="function"&&a.pause())},getState(){return h},setState(x){return h=x,h},write(x){f&&typeof f.write=="function"&&f.write(x)},get isRunning(){return g}}}var Fe="\x1B[?25l",be="\x1B[?25h",jt="\x1B[2K",_e="\x1B[0J";var Dr="\x1B\\[[0-9;?]*[a-zA-Z]";function Ut(){return new RegExp(Dr,"g")}function Br(e){return String(e??"").replace(Ut(),"")}function Ft(e,t){return t.some(([n,r])=>e>=n&&e<=r)}function Dt(e){return e===0||e<32||e>=127&&e<160||Ft(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:Ft(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 Kr(e){let t=0;for(let n of Array.from(e))t+=Dt(n.codePointAt(0));return t}function Hr(e){return Kr(Br(e))}function zr(e){return/^\u001b\[0*m$/.test(e)}function Mt(e,t){let n="",r=0;for(let o of Array.from(e)){let i=Dt(o.codePointAt(0));if(r+i>t)break;n+=o,r+=i}return{text:n,width:r}}function qr(e,t){let n=String(e??"");if(t<=0)return"";if(Hr(n)<=t)return n;let r=Ut(),o="",i=0,s=!1,c=0,u=r.exec(n);for(;u!==null;){let f=Mt(n.slice(c,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=!zr(u[0])),c=u.index+u[0].length,u=r.exec(n)}let a=Mt(n.slice(c),t-i);return o+=a.text,s?`${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 Bt({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),c=[],u=0,a=null,f=!1,d=!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},h=typeof e.on=="function";h&&e.on("resize",y);function g(w){let S=w-u;return u=w,S===0?"":S<0?`\x1B[${-S}A`:`\x1B[${S}B`}function k(w){let x=(Array.isArray(w)?w:[]).map(l=>qr(String(l??""),s));if(a!==null)for(x.length>a&&(x=x.slice(0,a));x.length<a;)x.push("");return x}function v(w){if(!f&&Wr(c,w))return;let S=[Fe];f&&c.length>0&&(S.push(g(0),"\r",_e),c=[],u=0),f=!1;let x=Math.min(c.length,w.length);for(let l=0;l<x;l+=1)c[l]!==w[l]&&S.push(g(l),"\r",jt,w[l]);if(w.length>c.length){c.length>0&&S.push(g(c.length-1));for(let l=c.length;l<w.length;l+=1)l>0&&S.push(`
|
|
7
|
+
`),S.push("\r",jt,w[l]),u=l}else w.length<c.length&&S.push(g(w.length),"\r",_e);w.length>0&&S.push(g(w.length-1)),S.push(be),c=w,e.write(S.join(""))}return{render(w){d||v(k(w))},writeAbove(w){if(d)return;let S=String(w??""),x=Fe;c.length>0&&(x+=`${g(0)}\r${_e}`),x+=S.endsWith(`
|
|
8
|
+
`)||S===""?S:`${S}
|
|
9
|
+
`,e.write(x);let l=c;c=[],u=0,l.length>0?v(l):e.write(be)},clear(){if(d)return;let w=Fe;c.length>0&&(w+=`${g(0)}\r${_e}`),w+=be,e.write(w),c=[],u=0,f=!1},setLines(w){a=Number.isFinite(w)&&w>=0?Math.trunc(w):null},getLines(){return c.slice()},getSize(){return{rows:i,columns:s}},dispose(){if(!d){if(d=!0,h){let w=typeof e.off=="function"?e.off:e.removeListener;typeof w=="function"&&w.call(e,"resize",y)}e.write(be)}}}}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 Yr(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 Kt(e,t,n){let r=Yr(t);return r?`\x1B[${e};2;${r.r};${r.g};${r.b}m${String(n)}\x1B[0m`:String(n)}function Me({color:e=!0}={}){return e&&!Object.hasOwn(process.env,"NO_COLOR")?Object.freeze({fg:(n,r)=>Kt(38,n,r),bg:(n,r)=>Kt(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 as=Me();function Ht(e){return String(e).replace(/\u001B\[[0-9;]*m/g,"")}var zt=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 "]]),Ue="THE FUTURE IS AGENTIC / by DEMI",De=/\u001B\[[0-9;]*m/g;function Wt(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 H(e){return[...Ht(e)].reduce((t,n)=>t+Wt(n),0)}function Ke(e,t){if(t<=0)return"";let n=String(e).split(/(\u001B\[[0-9;]*m)/g),r="",o=0,i=!1;for(let s of n)if(s){if(De.test(s)){De.lastIndex=0,r+=s,i=s!=="\x1B[0m";continue}De.lastIndex=0;for(let c of s){let u=Wt(c);if(o+u>t)return i?`${r}\x1B[0m`:r;r+=c,o+=u}}return r}function re(e,t,n="left"){let r=Math.max(0,Math.floor(Number(t)||0)),o=Ke(String(e),r),i=Math.max(0,r-H(o));if(n==="right")return`${" ".repeat(i)}${o}`;if(n==="center"){let s=Math.floor(i/2);return`${" ".repeat(s)}${o}${" ".repeat(i-s)}`}return`${o}${" ".repeat(i)}`}function He(e,t){let n=Math.max(1,Math.floor(Number(t)||1)),r=[];for(let o of String(e??"").split(`
|
|
10
|
+
`)){if(o===""){r.push("");continue}let i="",s=0;for(let c of o.split(" ")){let u=H(c);if(s>0&&s+1+u>n&&(r.push(i),i="",s=0),u>n){s>0&&(r.push(i),i="",s=0);let a=c;for(;H(a)>n;){let f=Ke(a,n);r.push(f),a=a.slice(f.length)}i=a,s=H(a);continue}i=s===0?c:`${i} ${c}`,s=s===0?u:s+1+u}r.push(i)}return r}function Gr(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,i=Math.max(0,n-6);return{target:t,panelWidth:n,panelLeft:r,contentLeft:o,inner:i}}function Jr(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 qt(e,t,n=0){let{target:r,contentLeft:o,inner:i}=e,c=Math.round((r-t)/2)-n-o,u=Math.max(0,i-t-n);return Math.max(0,Math.min(u,c))}function ze({width:e,palette:t}){let n=Gr(e),{target:r,panelWidth:o,panelLeft:i,inner:s}=n;if(r<72||s<=0)return[re(t.bold(t.fg(T.accent,"oracle")),r,"center"),re(t.fg(T.banner_text,Ue),r,"center")];let c=zt.map(([,x])=>x),{offset:u,width:a}=Jr(c),f=" ".repeat(qt(n,a,u)),d=" ".repeat(qt(n,H(Ue))),y=[];for(let[x,l]of zt)y.push(t.bold(t.fg(x,`${f}${l.replace(/\s+$/,"")}`)));y.push(""),y.push(t.bold(t.fg(T.banner_text,`${d}${Ue}`)));let h=x=>t.fg(T.banner_border,x),g=" ".repeat(i),k="\u2500".repeat(Math.max(0,o-2)),v=x=>re(`${g}${x}`,r),w=[v(`${h("\u256D")}${h(k)}${h("\u256E")}`)],S=v(`${h("\u2502")}${" ".repeat(Math.max(0,o-2))}${h("\u2502")}`);w.push(S);for(let x of y)w.push(v(`${h("\u2502")} ${re(x,s)} ${h("\u2502")}`));return w.push(S),w.push(v(`${h("\u2570")}${h(k)}${h("\u256F")}`)),w}function Yt({lines:e,width:t,palette:n,title:r=""}){let o=Math.max(2,Math.floor(Number(t)||0)),i=Math.max(0,o-2),s=Ke(String(r),Math.max(0,i-2)),c=s?` ${s} `:"",u=`${c}${"\u2500".repeat(Math.max(0,i-H(c)))}`,a=f=>n.fg(T.banner_border,f);return[`${a("\u256D")}${a(u)}${a("\u256E")}`,...e.map(f=>`${a("\u2502")}${re(f,i)}${a("\u2502")}`),`${a("\u2570")}${a("\u2500".repeat(i))}${a("\u256F")}`]}function Be(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 Vr(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,i=Math.round(n*o/100);return`${"\u2588".repeat(i)}${"\u2591".repeat(n-i)}`}function we(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 Gt({model:e,contextTokens:t,contextLength:n,percent:r,effort:o,thinking:i,chain:s,width:c,palette:u}){let a=Math.max(0,Math.floor(Number(c)||0)),f=u.fg(T.status_bar_dim," / "),d=a>=120?12:a>=60?8:4,y=Number(n)>0?`${Be(t)}/${Be(n)}`:Be(t),h=Number.isFinite(Number(r))?`${Math.round(Number(r))}%`:"0%",g=[{text:String(e??""),strong:!0}];Number(n)>0&&g.push({text:`ctx ${Vr(r,d)} ${y} ${h}`}),o&&g.push({text:String(o)}),i&&g.push({text:String(i)}),typeof s=="string"&&s.length>0&&g.push({text:s});let k=g,v=S=>S.reduce((x,l,p)=>x+H(l.text)+(p>0?3:0),0);for(;k.length>1&&v(k)>a;)k=k.slice(0,-1);let w=k.map(S=>S.strong?u.fg(T.status_bar_strong,S.text):u.fg(T.status_bar_text,S.text)).join(f);return u.bg(T.status_bar_bg,re(w,a))}var Qr=6;function Zr(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 qe(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 eo(e){let t=e.width,n=`${e.promptLabel} `,r=Math.max(1,t-2-H(n)),o=e.buffer||"",i=Math.max(0,Math.min(e.cursor??o.length,o.length)),s=0;i>r&&(s=i-r);let c=o.slice(s,s+r),u=i-s,a=c.slice(0,u),f=c.slice(u,u+1)||" ",d=c.slice(u+1),y=e.palette;return[`${y.fg(T.accent,n)}${a}${y.bg(T.selection_bg,f)}${d}`]}function to(e){let t=e.width,n=[];if(e.liveLines.length>0){for(let r of e.liveLines.slice(-Qr))n.push(r);n.push("")}return n.push(...Yt({lines:eo(e),width:t,palette:e.palette,title:"Ask Oracle \u203A"})),n.push(Gt({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 no(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 Se(e={}){return typeof e.text=="string"?e.text:typeof e.rendered=="string"?e.rendered:typeof e.message=="string"?e.message:""}function ro(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||Me({color:t.isTTY!==!1}),i=e.renderer||Bt({stdout:t,rows:t.rows,columns:r}),s=e.client||Lt({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 Xr,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},f=null,d=null,y={renderer:i,state:a};function h(){i.render(to(a))}function g(b){i.writeAbove(`${b}
|
|
11
|
+
`)}function k(){let b=a.assistantBuffer.split(`
|
|
12
|
+
`),m=b[b.length-1]||"";a.liveLines=m?He(m,a.width):[]}function v({final:b=!1}={}){let m=a.assistantBuffer.split(`
|
|
13
|
+
`),E=b?m.length:m.length-1,M=!1;for(;a.flushedLines<E;){let I=m[a.flushedLines];for(let F of He(I,a.width))g(F);a.flushedLines+=1,M=!0}return b?a.liveLines=[]:k(),M}function w(){d||(d=setInterval(()=>{a.busy&&(a.thinking=we(u()-a.startedAt),h())},250),typeof d.unref=="function"&&d.unref())}function S(){d&&(clearInterval(d),d=null)}async function x(b){let m=String(b||"").trim();if(m){if(m==="/exit"||m==="/quit"){await _();return}if(m==="/clear"){i.clear();for(let E of ze({width:a.width,palette:o}))g(E);h();return}a.busy=!0,a.assistantBuffer="",a.flushedLines=0,a.liveLines=[],a.startedAt=u(),a.thinking="0s",g(`${o.bold(o.fg(T.prompt,"you"))} ${m}`),g(""),w(),h(),await s.request("prompt.submit",{session_id:a.sessionId,text:m})}}function l(b){let m=no(b);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),qe(a,m.payload.usage),h();return}if(m.type==="message.start"){a.busy=!0,a.cancelled=!1,a.assistantBuffer="",a.flushedLines=0,a.liveLines=[],g(o.bold(o.fg(T.accent,"oracle"))),h();return}if(m.type==="thinking.delta"||m.type==="reasoning.delta"){if(a.cancelled)return;Se(m.payload).trim()&&(a.thinking=`${we(u()-a.startedAt)}`),h();return}if(m.type==="message.delta"){if(a.cancelled)return;a.assistantBuffer+=Se(m.payload),v(),h();return}if(m.type==="message.complete"){if(a.cancelled){a.cancelled=!1;return}let E=Se(m.payload);E&&E.length>=a.assistantBuffer.length&&(a.assistantBuffer=E),v({final:!0}),g(""),a.busy=!1,S(),qe(a,m.payload?.usage||m.payload?.context),a.thinking=we(u()-a.startedAt),h();return}m.type==="error"&&(a.busy=!1,S(),g(o.fg(T.error,`error: ${Se(m.payload)||"unknown"}`)),h())}}async function p(){await s.start(),s.on("event",l),s.on("log",m=>c.emit("log",m)),s.on("error",m=>c.emit("error",m));let b=await s.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=b.session_id,a.model=b.info?.model||a.model,b.info?.reasoning_effort&&(a.effort=b.info.reasoning_effort),qe(a,b.info?.usage);for(let m of ze({width:a.width,palette:o}))g(m);g(""),h(),f=Nt({stdin:n,stdout:t,onSubmit:m=>{x(m).catch(E=>c.emit("error",E))},onCancel:()=>{a.busy&&(a.busy=!1,a.cancelled=!0,S(),v({final:!0}),g(o.fg(T.warn,"interrupted")),g(""),h(),s.request("session.interrupt",{session_id:a.sessionId}).catch(m=>c.emit("error",m)))},onEof:()=>{_().catch(m=>c.emit("error",m))},onClear:()=>{i.clear(),h()},onRender:m=>{a.buffer=m.buffer||"",a.cursor=m.cursor??a.buffer.length,h()}}),f.start()}async function _(){S(),f&&f.stop(),i.dispose(),await s.stop(),c.emit("stop")}return Object.freeze({start:p,stop:_,on:c.on.bind(c),off:c.off.bind(c),state:a,handleEvent:l,submit:x})}async function We({hermesPython:e,client:t,tuiFactory:n=ro,args:r=[],env:o=process.env,cwd:i=process.cwd(),stdout:s=process.stdout,stdin:c=process.stdin}={}){let u=Zr(r);if(u.query)return{native:!1,pass:u.pass};if(!c.isTTY||!s.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 f=ge({...o,ORACLE_CHAT_SURFACE:"1",ORACLE_PROFILE:"oracle",ORACLE_NODE_BIN:process.execPath}),d=n({...t?{client:t}:{},...a?{python:a.command,pythonArgs:a.prefix||[]}:{},cwd:i,env:f,stdin:c,stdout:s,model:u.model,provider:u.provider,profile:"oracle"});return d.on("log",y=>{o.ORACLE_CLI_DEBUG&&process.stderr.write(`${y}
|
|
14
|
+
`)}),d.on("error",y=>{process.stderr.write(`oracle chat: ${y.message}
|
|
15
|
+
`)}),await d.start(),new Promise(y=>{let h=!1,g=async()=>{h||(h=!0,await d.stop(),y({native:!0,code:0}))};d.on("stop",()=>{h||(h=!0,y({native:!0,code:0}))}),process.once("SIGINT",g),process.once("SIGTERM",g)})}import oo from"node:fs";import Jt from"node:path";var Vt=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 so(e,t){let n=Number(e);return Number.isSafeInteger(n)&&n>0?n:t}function ao(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(Vt))if(e[o.key]||o.alternateKey&&e[o.alternateKey])return r;return null}function co(e=process.env,t={},n=()=>!1,r=()=>""){let o=ao(e,t);if(!o)return null;let i=io[o],s=Vt[o]||i,c=String(e.ORACLE_API_KEY_ENV||t.apiKeyEnv||""),u=String(e.ORACLE_API_KEY||c&&e[c]||s&&(e[s.key]||s.alternateKey&&e[s.alternateKey])||r(o)||""),a=String(i?i.baseUrl:o==="custom"?e.ORACLE_BASE_URL||t.baseUrl||"":s?.baseUrl||"").replace(/\/+$/,""),f=String(e.ORACLE_MODEL||t.model||s?.model||"");if(!a||!f)return null;let d=!!(i&&n(o));return i&&!d||!i&&o!=="custom"&&!u?null:{kind:"standalone",provider:o,model:f,baseUrl:a,...d?{authType:"oauth",protocol:i.protocol}:{apiKey:u},contextLength:so(e.ORACLE_CONTEXT_LENGTH||t.contextLength,128e3),reasoningEffort:String(e.ORACLE_REASONING_EFFORT||t.reasoningEffort||"high")}}function oe(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(`
|
|
16
|
+
`)}function uo(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(),i=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:i}}var lo=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 fo(e){for(let t of(process.env.PATH||"").split(Jt.delimiter)){let n=Jt.join(t,e);try{if(oo.existsSync(n))return n}catch{}}return null}function Xt({env:e=process.env,hermes:t={ok:!1},storedConfig:n=null,oauthAvailable:r=()=>!1,apiKeyResolver:o=()=>""}={}){let i=String(e.ORACLE_CHAT_BACKEND||n?.backend||"auto").trim().toLowerCase(),s=uo(e,n||{});if(i==="remote"||i==="arch")return s?{kind:"remote",config:s}:{kind:"unconfigured",reason:oe(`${i} compute backend was requested, but no compute host is configured.`)};let c=co(e,n||{},r,o);if(i==="standalone")return c?{kind:"standalone",config:c}:{kind:"unconfigured",reason:oe("ORACLE_CHAT_BACKEND=standalone was requested, but no standalone model is configured.")};if(i==="hermes")return t?.ok?{kind:"hermes",bin:t.bin}:{kind:"unconfigured",reason:oe("ORACLE_CHAT_BACKEND=hermes was requested, but Hermes was not found.")};if(i!=="auto"){for(let u of lo)if(u.name===i){let a=fo(u.bin);return a?{kind:"harness",harness:{...u,path:a}}:{kind:"unconfigured",reason:oe(`ORACLE_CHAT_BACKEND=${i} was requested, but ${u.bin} was not found on PATH.`)}}return{kind:"unconfigured",reason:oe(`Unknown ORACLE_CHAT_BACKEND value: ${i}`)}}return s?{kind:"remote",config:s}:c?{kind:"standalone",config:c}:t?.ok?{kind:"hermes",bin:t.bin}:{kind:"unconfigured",reason:oe()}}V();import Ko from"node:fs";import jn from"node:path";import{randomUUID as $n}from"node:crypto";import{EventEmitter as Ho}from"node:events";import{spawnSync as zo}from"node:child_process";import{existsSync as Zt,readFileSync as po}from"node:fs";import{dirname as Qt,join as Ye}from"node:path";import{fileURLToPath as mo}from"node:url";function ho(e){let t=Qt(mo(e));for(let n=0;n<8;n+=1){let r=Ye(t,"package.json");if(Zt(r))try{let i=JSON.parse(po(r,"utf8"));if(i&&typeof i.version=="string")return t}catch{}let o=Qt(t);if(o===t)break;t=o}throw new Error(`oracle: could not resolve package root from ${e}`)}function ve(e,t){let n=ho(t),r=Ye(n,"dist","assets",e);return Zt(r)?r:Ye(n,e)}import ke from"node:fs";import en from"node:path";import{homedir as xo}from"node:os";var Je=process.env.ORACLE_CONFIG_DIR||en.join(xo(),".config","oracle"),tn=en.join(Je,"memory.json"),Ge=2200;function nn(e){ke.existsSync(e)||ke.mkdirSync(e,{recursive:!0})}function Ve(){nn(Je);try{let e=ke.readFileSync(tn,"utf8");return JSON.parse(e)}catch{return{version:1,updatedAt:new Date().toISOString(),entries:[]}}}function rn(e){nn(Je),e.updatedAt=new Date().toISOString(),ke.writeFileSync(tn,JSON.stringify(e,null,2),{mode:384})}function on(e,t){let n=Ve(),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>Ge&&n.entries.length>1;)n.entries.shift();rn(n)}function sn(e){let t=Ve(),n=t.entries.length;return t.entries=t.entries.filter(r=>r.key!==e),t.entries.length<n?(rn(t),{ok:!0}):{ok:!1}}function an(){let e=Ve();if(e.entries.length===0)return"";let t=JSON.stringify(e.entries).length,n=Math.round(t/Ge*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}/${Ge} 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(`
|
|
17
|
+
`)}var cn=[{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 L from"node:fs";import G from"node:path";import{homedir as go}from"node:os";var yo=process.env.ORACLE_CONFIG_DIR||G.join(go(),".config","oracle"),ie=G.join(yo,"skills"),de=ve("skills",import.meta.url),Xe=/^[a-z0-9][a-z0-9_-]{0,63}$/;function Qe(e){L.existsSync(e)||L.mkdirSync(e,{recursive:!0,mode:448});let t=L.lstatSync(e);if(t.isSymbolicLink()||!t.isDirectory())throw new Error("skills directory must be a real directory")}function un(){return L.constants.O_NOFOLLOW||0}function Ee(e){let t=L.lstatSync(e);if(t.isSymbolicLink()||!t.isFile())return null;let n=L.openSync(e,L.constants.O_RDONLY|un());try{return L.readFileSync(n,"utf8")}finally{L.closeSync(n)}}function bo(e,t){if(L.existsSync(e)){let r=L.lstatSync(e);if(r.isSymbolicLink()||!r.isFile())throw new Error("skill path must be a regular file")}let n=L.openSync(e,L.constants.O_WRONLY|L.constants.O_CREAT|L.constants.O_TRUNC|un(),384);try{L.writeFileSync(n,t)}finally{L.closeSync(n)}try{L.chmodSync(e,384)}catch{}}function ln(e){let t=String(e??"").trim();if(!Xe.test(t))throw new Error("invalid skill name");return G.join(ie,`${t}.md`)}function fn(e,t){let n=t.match(/^description:\s*(.+)$/m);return n?n[1].trim():t.split(`
|
|
18
|
+
`)[0].replace(/^#+\s*/,"").trim()||e}function _o(){let e=[];for(let t of L.readdirSync(de,{withFileTypes:!0})){let n,r;if(t.isFile()&&t.name.endsWith(".md"))n=t.name.replace(/\.md$/,""),r=G.join(de,t.name);else if(t.isDirectory()&&Xe.test(t.name))n=t.name,r=G.join(de,t.name,"SKILL.md");else continue;if(!Xe.test(n)||!L.existsSync(r))continue;let o=Ee(r);o!==null&&e.push({name:n,description:fn(n,o),path:r,size:o.length})}return e}function Ze(){try{Qe(ie);let e=new Map(_o().map(t=>[t.name,t]));for(let t of L.readdirSync(ie,{withFileTypes:!0})){if(!t.isFile()||!t.name.endsWith(".md"))continue;let n=G.join(ie,t.name),r=Ee(n);if(r===null)continue;let o=t.name.replace(/\.md$/,"");e.set(o,{name:o,description:fn(o,r),path:n,size:r.length})}return[...e.values()].sort((t,n)=>t.name.localeCompare(n.name))}catch{return[]}}function et(e){try{Qe(ie);let t=ln(e);if(L.existsSync(t))return Ee(t);for(let n of[G.join(de,e,"SKILL.md"),G.join(de,`${e}.md`)]){if(!L.existsSync(n))continue;let r=Ee(n);if(r!==null)return r}return null}catch{return null}}function dn(e){let t=Ze();if(t.length===0)return`## Skills
|
|
19
19
|
No skills installed. Use skill_create to save a successful workflow.
|
|
20
20
|
`;let n=t;if(e){let o=e.toLowerCase();n=[...t].sort((i,s)=>{let c=(i.name.toLowerCase().includes(o)?2:0)+(i.description.toLowerCase().includes(o)?1:0);return(s.name.toLowerCase().includes(o)?2:0)+(s.description.toLowerCase().includes(o)?1:0)-c})}return["## Skills","Available (use skill_load <name>):",...n.map(o=>`- **${o.name}**: ${o.description}`)].join(`
|
|
21
|
-
`)}function
|
|
22
|
-
[truncated ${t.length-xt} chars]`}async function
|
|
21
|
+
`)}function pn(e,t){Qe(ie);let n=ln(e);if(L.existsSync(n)&&!L.lstatSync(n).isFile())throw new Error("skill path must be a regular file");bo(n,t)}var mn=[{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 Ae from"node:fs";import xn from"node:path";import{homedir as wo}from"node:os";import{EventEmitter as So}from"node:events";var tt=process.env.ORACLE_CONFIG_DIR||xn.join(wo(),".config","oracle"),gn=xn.join(tt,"cron.json");function yn(e){Ae.existsSync(e)||Ae.mkdirSync(e,{recursive:!0})}function pe(){yn(tt);try{return JSON.parse(Ae.readFileSync(gn,"utf8"))}catch{return{version:1,jobs:[]}}}function nt(e){yn(tt),Ae.writeFileSync(gn,JSON.stringify(e,null,2),{mode:384})}function Oe(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 rt(){return pe().jobs}function ot(e){let t=pe(),n=`cron_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`,r=Oe(e.schedule)||36e5,o={...e,id:n,createdAt:new Date().toISOString(),nextRunAt:new Date(Date.now()+r).toISOString()};return t.jobs.push(o),nt(t),o}function it(e){let t=pe(),n=t.jobs.length;return t.jobs=t.jobs.filter(r=>r.id!==e),t.jobs.length<n?(nt(t),!0):!1}function hn(e){let t=pe(),n=t.jobs.find(i=>i.id===e);if(!n)return;n.lastRunAt=new Date().toISOString();let r=Oe(n.schedule)||36e5,o=n.lastRunAt?new Date(n.lastRunAt).getTime():Date.now();n.nextRunAt=new Date(o+r).toISOString(),nt(t)}function bn(e){let t=new So,n=new Map;function r(){let i=pe();for(let s of i.jobs){if(!s.enabled)continue;let c=Oe(s.schedule);if(!c)continue;let u=setInterval(async()=>{try{t.emit("run",{id:s.id,name:s.name}),await e(s.prompt,s.skills),hn(s.id),t.emit("complete",{id:s.id,name:s.name})}catch(a){t.emit("error",{id:s.id,name:s.name,error:a})}},c);n.set(s.id,u)}t.emit("started",{count:n.size})}function o(){for(let[i,s]of n)clearInterval(s),n.delete(i);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:i=>{let s=ot(i);if(s.enabled){let c=Oe(s.schedule);if(c){let u=setInterval(async()=>{try{t.emit("run",{id:s.id,name:s.name}),await e(s.prompt,s.skills),hn(s.id),t.emit("complete",{id:s.id,name:s.name})}catch(a){t.emit("error",{id:s.id,name:s.name,error:a})}},c);n.set(s.id,u)}}return s},remove:i=>{let s=n.get(i);return s&&(clearInterval(s),n.delete(i)),it(i)},list:rt}}var _n=[{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 Ce=[],vo=5,ko=1;function wn(e){Ce.push(e),Ce.length>20&&Ce.shift()}function Sn(){let e=Ce.slice(-3);if(e.length<1)return null;let t=e[e.length-1];return t.toolCalls>=vo&&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>=ko&&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 vn=[{type:"function",function:{name:"meta_analyze",description:"Analyze recent interactions and suggest skills to create.",parameters:{type:"object",properties:{},additionalProperties:!1}}}];import{homedir as st}from"node:os";import{join as at}from"node:path";var kn=process.env.ORACLE_PUBLIC_DESKTOP==="1",Eo=kn?process.env.ORACLE_CONFIG_DIR||at(st(),".config","oracle"):at(st(),".config","oracle"),Ws=kn?Eo:at(st(),".config","mad-desk");function Ao(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 Oo=["0","false","off","no"];function En(e,t,n=!0){let r=String(Ao(e,t,"")).trim().toLowerCase();return r===""?n:!Oo.includes(r)}var qo=new Set(["chain","data","scan","route","prepare"]),Wo=new Set(["list","show"]),Yo=new Set(["call","catalog","health"]),Go=new Set(["swap","bridge","prepare","prepare-bridge"]),Jo=Object.freeze({"anthropic-oauth":"https://api.anthropic.com/v1","openai-codex":"https://chatgpt.com/backend-api/codex","xai-oauth":"https://api.x.ai/v1"}),xt=2e4,Vo=16,Xo=50;function Qo(e=process.env){let t=Number.parseInt(String(e?.ORACLE_MAX_AGENT_STEPS??"").trim(),10);return!Number.isFinite(t)||t<1?Vo:Math.min(t,Xo)}var Zo=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}}}),yt=Object.freeze([Zo,...cn,...mn,..._n,...vn]);function Pn(e){let t=String(e||"");return t.length<=xt?t:`${t.slice(0,xt)}
|
|
22
|
+
[truncated ${t.length-xt} chars]`}async function ei(e,t,n){switch(e){case"oracle_cli":return n(t.argv);case"memory_add":return on(t.key,t.content),{ok:!0,stored:t.key};case"memory_remove":return sn(t.key);case"skill_load":{let r=et(t.name);return r?{ok:!0,name:t.name,content:r}:{ok:!1,error:`skill not found: ${t.name}`}}case"skill_create":return pn(t.name,t.content),{ok:!0,created:t.name};case"skill_list":return{ok:!0,skills:Ze().map(o=>({name:o.name,description:o.description}))};case"cron_add":return{ok:!0,job:ot({name:t.name,schedule:t.schedule,prompt:t.prompt,skills:t.skills||[],enabled:!0})};case"cron_list":return{ok:!0,jobs:rt()};case"cron_remove":return{ok:it(t.id),removed:t.id};case"meta_analyze":return{ok:!0,...Sn()||{shouldCreate:!1,suggestion:"No skill suggestions yet."}};default:return{ok:!1,error:`unknown tool: ${e}`}}}function ti(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 qo.has(t)?t==="chain"&&!Wo.has(e[1]||"list")?`command not allowed: chain${e[1]?` ${e[1]}`:""}`:t==="data"&&!Yo.has(e[1]||"")?`command not allowed: data${e[1]?` ${e[1]}`:""}`:t==="route"&&!Go.has(e[1]||"")?`command not allowed: route${e[1]?` ${e[1]}`:""}`:null:`command not allowed: ${t}`}async function ni(e,t={}){let n=ti(e);if(n)return{ok:!1,error:n};let r=t.spawnFn||zo,o=t.packageRoot||B,i=r(process.execPath,[jn.join(o,"bin","oracle.mjs"),...e],{encoding:"utf8",timeout:t.timeoutMs||45e3,maxBuffer:1024*1024,env:{...process.env,ORACLE_CHAT_TOOL:"1"}});return i.error?{ok:!1,error:i.error.message}:{ok:i.status===0,status:typeof i.status=="number"?i.status:1,stdout:Pn(i.stdout),stderr:Pn(i.stderr)}}function ri(){let e=jn.join(ve("profiles",import.meta.url),"oracle","SOUL.md"),t=Ko.readFileSync(e,"utf8"),n=an(),r=dn(),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(`
|
|
23
23
|
|
|
24
|
-
`)}function
|
|
25
|
-
`);!a||a==="[DONE]"||(yield JSON.parse(a))}if(s)break}let o=r.trim();if(o.startsWith("data:")){let i=o.slice(5).trim();i&&i!=="[DONE]"&&(yield JSON.parse(i))}}function
|
|
26
|
-
${
|
|
24
|
+
`)}function oi(e,t,n={}){return{method:"event",params:{type:e,session_id:t,payload:n}}}async function ii(e){return new Error(`model request failed (HTTP ${e?.status||"unknown"})`)}async function*bt(e){if(!e?.ok)throw await ii(e);if(!e.body)throw new Error("model response had no body");let t=e.body.getReader(),n=new TextDecoder,r="";for(;;){let{value:i,done:s}=await t.read();r+=n.decode(i||new Uint8Array,{stream:!s});let c=r.split(/\r?\n\r?\n/);r=c.pop()||"";for(let u of c){let a=u.split(/\r?\n/).filter(f=>f.startsWith("data:")).map(f=>f.slice(5).trimStart()).join(`
|
|
25
|
+
`);!a||a==="[DONE]"||(yield JSON.parse(a))}if(s)break}let o=r.trim();if(o.startsWith("data:")){let i=o.slice(5).trim();i&&i!=="[DONE]"&&(yield JSON.parse(i))}}function si(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 Nn(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 ai(){return yt.map(e=>({type:"function",name:e.function.name,description:e.function.description,parameters:e.function.parameters,strict:!1}))}function ci(){return yt.map(e=>({name:e.function.name,description:e.function.description,input_schema:e.function.parameters}))}function gt(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 ui(e){let t=[];for(let n of e)if(n.role!=="system"){if(n.role==="user"){gt(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 i={};try{i=JSON.parse(o.function?.arguments||"{}")}catch{}r.push({type:"tool_use",id:o.id,name:o.function?.name,input:i})}r.length&>(t,"assistant",r);continue}n.role==="tool"&>(t,"user",[{type:"tool_result",tool_use_id:n.tool_call_id,content:String(n.content||"")}])}return t}function li(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 fi(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 di({config:e,messages:t,fetchFn:n,signal:r,onText:o}){let i=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:yt,tool_choice:"auto",stream:!0,stream_options:{include_usage:!0}}),signal:r}),s=new Map,c="",u=null;for await(let a of bt(i)){a.usage&&(u=a.usage);let f=a.choices?.[0]?.delta||{};typeof f.content=="string"&&f.content&&(c+=f.content,o(f.content));for(let d of f.tool_calls||[])si(s,d)}return{text:c,usage:u,toolCalls:[...s.entries()].sort(([a],[f])=>a-f).map(([,a])=>a)}}async function pi({config:e,messages:t,persona:n,credential:r,fetchFn:o,signal:i,onText:s}){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:ui(t),tools:ci(),tool_choice:{type:"auto"},stream:!0}),signal:i}),u=new Map,a="",f=null;for await(let d of bt(c)){if(d.type==="message_start"&&(f={...f||{},...d.message?.usage||{}}),d.type==="message_delta"&&(f={...f||{},...d.usage||{}}),d.type==="content_block_start"&&d.content_block?.type==="tool_use"){let y=d.content_block;u.set(Number(d.index||0),{id:y.id,type:"function",function:{name:y.name,arguments:y.input&&Object.keys(y.input).length?JSON.stringify(y.input):""}})}if(d.type==="content_block_delta"&&d.delta?.type==="text_delta"&&(a+=d.delta.text||"",d.delta.text&&s(d.delta.text)),d.type==="content_block_delta"&&d.delta?.type==="input_json_delta"){let y=Number(d.index||0),h=u.get(y);h&&(h.function.arguments+=d.delta.partial_json||"")}if(d.type==="error")throw new Error(d.error?.message||"Claude stream failed")}return{text:a,usage:f,toolCalls:[...u.entries()].sort(([d],[y])=>d-y).map(([,d])=>(d.function.arguments||(d.function.arguments="{}"),d))}}async function mi({config:e,messages:t,persona:n,sessionId:r,credential:o,fetchFn:i,signal:s,onText:c}){let u=e.provider==="openai-codex",a=u?fi(o.accessToken):"",f={"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}},d={model:e.model,instructions:n,input:li(t),tools:ai(),tool_choice:"auto",parallel_tool_calls:!0,store:!1,stream:!0,...u?{reasoning:{effort:e.reasoningEffort||"high",summary:"auto"}}:{}},y=await i(`${e.baseUrl}/responses`,{method:"POST",headers:f,body:JSON.stringify(d),signal:s}),h=new Map,g="",k=null;for await(let v of bt(y)){v.type==="response.output_text.delta"&&typeof v.delta=="string"&&(g+=v.delta,c(v.delta));let w=v.item;if((v.type==="response.output_item.added"||v.type==="response.output_item.done")&&w?.type==="function_call"){let S=String(w.call_id||w.id||v.output_index||h.size);h.set(S,{id:w.call_id||w.id,response_item_id:w.id,type:"function",function:{name:w.name,arguments:w.arguments||"{}"}})}if(v.type==="response.function_call_arguments.delta"){let S=String(v.call_id||v.item_id||v.output_index||""),x=h.get(S);x&&(x.function.arguments+=v.delta||"")}if(v.type==="response.completed"&&(k=v.response?.usage||k),v.type==="response.failed"||v.type==="error")throw new Error(v.response?.error?.message||v.error?.message||"Responses stream failed")}return{text:g,usage:k,toolCalls:[...h.values()]}}function Fn(e={}){let t=e.config;if(!t?.baseUrl||!t?.model)throw new Error("standalone model configuration is incomplete");if(t.authType==="oauth"){let l=Jo[t.provider],p=String(t.baseUrl).replace(/\/+$/,"");if(!l||p!==l)throw new Error(`${t.provider||"unknown"} OAuth endpoint is not trusted`)}let n=new Ho,r=e.fetchFn||globalThis.fetch,o=e.toolRunner||(l=>ni(l,e)),i=e.credentialProvider||(async l=>{let{resolveOAuthCredentials:p}=await Promise.resolve().then(()=>(ht(),Rn));return p(l)}),s=e.persona||ri(),c=Number.isInteger(e.maxAgentSteps)&&e.maxAgentSteps>0?e.maxAgentSteps:Qo(e.env||process.env),u=e.sessionId||`oracle-${$n()}`,a=[],f=null,d=!1,y=!1,h=bn(async(l,p)=>{if(d)return;let _=(p||[]).map(m=>{let E=et(m);return E?`## Skill: ${m}
|
|
26
|
+
${E}`:null}).filter(Boolean),b=_.length>0?`
|
|
27
27
|
|
|
28
|
-
${
|
|
28
|
+
${_.join(`
|
|
29
29
|
|
|
30
|
-
`)}`:"";await
|
|
31
|
-
`),s=!0,c(0);return}if(
|
|
32
|
-
`),s=!0,u(new Error(
|
|
33
|
-
`,{mode:384}),{ok:!0,marker:o}}function
|
|
34
|
-
`)}function
|
|
30
|
+
`)}`:"";await v(`${l}${b}`)});En("ORACLE_CRON_ENABLED","MAD_CRON_ENABLED",!0)&&(h.on("run",l=>g("cron.run",l)),h.on("complete",l=>g("cron.complete",l)),h.on("error",l=>g("cron.error",l)),h.start());function g(l,p={}){n.emit("event",oi(l,u,p))}function k(l){g("error",{message:l?.message||String(l)}),n.listenerCount("error")>0&&n.emit("error",l)}async function v(l){y=!0,f=new AbortController;let p=[{role:"system",content:s},...a,{role:"user",content:l}],_="",b=null,m=!1;try{for(let E=0;E<c;E+=1){let M=t.authType==="oauth"?await i(t.provider):null,I=ee=>{m||(g("message.start",{}),m=!0),_+=ee,g("message.delta",{text:ee})},F={config:t,messages:p,persona:s,sessionId:u,credential:M,fetchFn:r,signal:f.signal,onText:I},Z=t.protocol==="anthropic-messages"?await pi(F):t.protocol==="responses"?await mi(F):await di(F),_t=Z.text,ce=Z.toolCalls;if(b=Z.usage||b,ce.length===0){p.push({role:"assistant",content:_t}),a=p.slice(1),m||g("message.start",{}),g("message.complete",{text:_,usage:Nn(b,t.contextLength)});return}p.push({role:"assistant",content:_t||null,tool_calls:ce});let Yn=ce.length,he=0;for(let ee of ce){let xe;try{let Re=JSON.parse(ee.function.arguments||"{}");xe=await ei(ee.function.name,Re,o)}catch(Re){xe={ok:!1,error:`invalid tool arguments: ${Re.message}`},he++}xe.ok||he++,p.push({role:"tool",tool_call_id:ee.id||`call_${$n()}`,content:JSON.stringify(xe)})}wn({userMessage:l,toolCalls:Yn,errors:he,recovered:he>0?!!ce.length:!1,durationMs:0})}a=p.slice(1),m||g("message.start",{}),g("message.complete",{text:_,usage:Nn(b,t.contextLength),truncated:!0,stop_reason:"max_steps",note:`Stopped after the ${c}-step tool budget. Results above are complete; anything not yet reported was not attempted. Raise ORACLE_MAX_AGENT_STEPS to continue further in one turn.`});return}catch(E){E?.name!=="AbortError"&&k(E)}finally{y=!1,f=null}}async function w(){if(d)throw new Error("standalone client is stopped")}async function S(l,p={}){if(d)throw new Error("standalone client is stopped");if(l==="session.create")return g("session.info",{model:p.model||t.model,reasoning_effort:t.reasoningEffort,usage:{context_max:t.contextLength},backend:"standalone"}),{session_id:u,info:{model:p.model||t.model,reasoning_effort:t.reasoningEffort,usage:{context_max:t.contextLength},backend:"standalone"}};if(l==="prompt.submit"){if(y)throw new Error("a turn is already active");let _=String(p.text||"").trim();if(!_)throw new Error("prompt text is required");return queueMicrotask(()=>{v(_).catch(k)}),{accepted:!0}}if(l==="session.interrupt"){let _=!!(f&&y);return f?.abort(),{interrupted:_}}if(l==="session.usage")return{calls:0,input:0,output:0,total:0};throw new Error(`unsupported standalone method: ${l}`)}async function x(){d||(d=!0,f?.abort(),h.stop())}return Object.freeze({start:w,request:S,stop:x,on:n.on.bind(n),off:n.off.bind(n)})}async function Mn({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"}),i="",s=!1;try{return await new Promise((c,u)=>{let a=f=>{let d=f?.params?.type,y=f?.params?.payload||{};if(d==="message.delta"&&typeof y.text=="string"){i+=y.text,n.write(y.text);return}if(d==="message.complete"){!i&&y.text&&n.write(String(y.text)),n.write(`
|
|
31
|
+
`),s=!0,c(0);return}if(d==="error"){let h=y.message||y.text||"standalone chat failed";r.write(`oracle chat: ${h}
|
|
32
|
+
`),s=!0,u(new Error(h))}};e.on("event",a),e.request("prompt.submit",{session_id:o.session_id,text:t}).catch(f=>{s||(s=!0,u(f))})})}finally{await e.stop()}}ht();var R="oracle",me="oracle";function qn(e){if(e==="hermes"){let t=Pe();return t.ok?t.bin:null}for(let t of(process.env.PATH||"").split(A.delimiter)){let n=A.join(t,e);try{if(C.existsSync(n))return n}catch{}}return null}function Un(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(A.basename(n[0]||"").startsWith("python"))return{command:n[0],prefix:n.slice(1)}}catch{}return null}function Wn(e){let t=Un(e);if(t)return t;try{let r=C.readFileSync(e,"utf8").match(/["']([^"'\r\n]+\/bin\/hermes)["']/);if(r)return Un(r[1])}catch{}return null}function xi(){return A.join(B,"src","cli","oracle-harness.py")}function Dn(e,t){let n=xi(),r=process.env.ORACLE_PLAIN_HARNESS==="0"?null:Wn(e);return r&&C.existsSync(n)?{command:r.command,args:[...r.prefix,n,...t]}:{command:e,args:t}}function gi(){return A.join(B,"skins","oracle.yaml")}function yi(e=R){let t=A.join(B,"profiles","oracle","SOUL.md");if(!C.existsSync(t))return{ok:!1,reason:"oracle persona missing from package"};let n=A.join(D(),"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(A.dirname(n)),C.copyFileSync(t,n),{ok:!0,reused:!1})}function bi(e=R){let t=gi();if(!C.existsSync(t))return{ok:!1,reason:"skin missing from package"};let n=A.join(D(),"skins"),r=A.join(D(),"profiles",e,"skins");N(n),N(r);let o=C.readFileSync(t,"utf8");return C.writeFileSync(A.join(n,`${me}.yaml`),o),C.writeFileSync(A.join(r,`${me}.yaml`),o),{ok:!0,skin:me}}function _i(e=R){let t=A.join(D(),"profiles",e,"config.yaml");if(!C.existsSync(t))return{ok:!1,reason:"profile config missing"};let n=qn("oracle")||A.join(B,"bin","oracle.mjs"),r=A.join(D(),"profiles",e,"oracle");N(r);let o={profile:e,skin:me,oracleBin:n,commands:{chain:[n,"chain"],setup:[n,"setup"]},updatedAt:new Date().toISOString()};return C.writeFileSync(A.join(r,"chat-surface.json"),JSON.stringify(o,null,2)+`
|
|
33
|
+
`,{mode:384}),{ok:!0,marker:o}}function wi(e=R){let t=A.join(B,"skills","oracle-chat");if(!C.existsSync(t))return{ok:!1,reason:"oracle-chat skill missing"};let n=A.join(D(),"profiles",e,"skills","oracle-chat");N(n);for(let r of C.readdirSync(t)){let o=A.join(t,r),i=A.join(n,r);C.statSync(o).isFile()&&C.copyFileSync(o,i)}for(let r of["chain","setup"]){let o=A.join(D(),"profiles",e,"skills",r);N(o);let i=A.join(t,`${r}.SKILL.md`),s=A.join(t,"SKILL.md"),c=C.existsSync(i)?C.readFileSync(i,"utf8"):C.readFileSync(s,"utf8");C.writeFileSync(A.join(o,"SKILL.md"),c)}return{ok:!0}}function Si(e=R){let t=qn("hermes");if(!t)return{ok:!1,reason:"hermes missing"};let n=hi(t,["-p",e,"config","set","display.skin",me],{encoding:"utf8",timeout:3e4});return n.status!==0?{ok:!1,reason:(n.stderr||n.stdout||"config set failed").trim()}:{ok:!0}}function Bn(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 vi(e=R){let t=D();if(C.existsSync(A.join(t,"auth.json"))||C.existsSync(A.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[A.join(t,".env"),A.join(t,"profiles",e,".env")]){if(!C.existsSync(r))continue;let o=C.readFileSync(r,"utf8");if(n.some(i=>new RegExp(`^${i}=.+`,"m").test(o)))return!0}return!1}function Kn(e=R){let t=D();return Bn(A.join(t,"config.yaml"))||Bn(A.join(t,"profiles",e,"config.yaml"))||vi(e)}function Hn(){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(`
|
|
34
|
+
`)}function ki(){let e=Number(process.stdout?.columns||process.env.COLUMNS||80);return Number.isFinite(e)&&e>0?Math.floor(e):80}function Ei(e){return Array.from(String(e)).length}function Ai(e,t){let n=e.map(s=>s.trimEnd()),r=Math.max(0,...n.map(s=>Ei(s))),o=Math.max(0,Math.floor((t-r)/2)),i=" ".repeat(o);return n.map(s=>s?`${i}${s}`:"")}function zn(e){return`'${String(e).replace(/'/g,"'\\''")}'`}function Oi(e){return e.user?`${e.user}@${e.host}`:e.host}function Ci(e,t){let n=e.path||"$HOME/.local/bin:/usr/local/bin:/usr/bin:/bin:/opt/homebrew/bin",r=["oracle","chat",...t].map(zn).join(" ");return[/^[A-Za-z0-9_:$/.~+-]+$/.test(n)?`export PATH=${n}`:`export PATH=${zn(n)}`,"export ORACLE_REMOTE_COMPUTE_DISABLE=1","export ORACLE_CHAT_BACKEND=auto",r].join("; ")}function Li(){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(Ai(e,ki()).join(`
|
|
35
35
|
`)+`
|
|
36
|
-
`)}function
|
|
37
|
-
`),0;if(t.includes("--print-banner"))return
|
|
38
|
-
`),1;if(i.kind==="remote")return ye("ssh",["-o","BatchMode=yes","-o","ConnectTimeout=12",
|
|
36
|
+
`)}function Ii(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 Ea={name:"chat",summary:"open the one oracle chat surface (telegram-like, multi-model)",group:"read",usage:Hn(),async run(e){let t=[...e.argv];if(t.includes("-h")||t.includes("--help"))return process.stdout.write(Hn()+`
|
|
37
|
+
`),0;if(t.includes("--print-banner"))return Li(),0;let n=Ii(t),r={...process.env,...n.model?{ORACLE_MODEL:n.model}:{},...n.provider?{ORACLE_PROVIDER:n.provider}:{}},o=ae(),i=Xt({env:r,hermes:Pe(),storedConfig:Et(),oauthAvailable:g=>!!o.get(g),apiKeyResolver:g=>o.getApiKey(g)});if(i.kind==="unconfigured")return process.stderr.write(`${i.reason}
|
|
38
|
+
`),1;if(i.kind==="remote")return ye("ssh",["-o","BatchMode=yes","-o","ConnectTimeout=12",Oi(i.config),Ci(i.config,n.pass)],{stdio:"inherit",env:process.env},"oracle-remote-compute");let s=ge({ORACLE_CHAT_SURFACE:"1",ORACLE_PROFILE:R,ORACLE_NODE_BIN:process.execPath,ORACLE_CLI_ENTRY:A.join(B,"bin","oracle.mjs")});if(i.kind==="standalone"){let g=Fn({config:{...i.config,...n.model?{model:n.model}:{}}});if(n.query)try{return await Mn({client:g,text:n.query,stdout:process.stdout,stderr:process.stderr})}catch{return 1}let k=await We({client:g,args:t,env:s,cwd:process.cwd(),stdin:process.stdin,stdout:process.stdout});return k.native?k.code:(process.stderr.write(process.env.ORACLE_NATIVE_TUI==="0"?`oracle standalone chat requires the native TUI; remove ORACLE_NATIVE_TUI=0
|
|
39
39
|
`:`oracle standalone chat requires an interactive TTY or -q <query>
|
|
40
|
-
`),1)}let c=i.bin;
|
|
41
|
-
`);let a=!!(n.model||n.provider);if(!
|
|
40
|
+
`),1)}let c=i.bin;yi(R),bi(R),wi(R);let u=Si(R);_i(R),!u.ok&&process.env.ORACLE_CLI_DEBUG&&process.stderr.write(`oracle chat: skin note: ${u.reason}
|
|
41
|
+
`);let a=!!(n.model||n.provider);if(!Kn(R)&&!a){if(!process.stdin.isTTY||!process.stdout.isTTY)return process.stderr.write(`oracle chat needs a configured model
|
|
42
42
|
run: oracle model
|
|
43
43
|
`),1;process.stdout.write(`choose oracle's model before first chat
|
|
44
44
|
|
|
45
|
-
`);let
|
|
45
|
+
`);let g=Dn(c,["-p",R,"model"]),k=await ye(g.command,g.args,{stdio:"inherit",env:process.env},"oracle-model");if(k!==0||!Kn(R))return k||1}let f=["-p",R,"chat"],d=Wn(c),y=await We({hermesPython:d,args:t,env:s,cwd:process.cwd(),stdin:process.stdin,stdout:process.stdout});if(y.native)return y.code;let h=Dn(c,[...f,...n.pass]);return ye(h.command,h.args,{stdio:"inherit",env:s},"oracle-chat")}};export{Ea as default,xi as harnessSourcePath,Dn as oracleHarnessInvocation,Wn as resolveHermesPython};
|