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