@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 CHANGED
@@ -27,12 +27,18 @@ The private operator configuration, approval flow, wire units, and holder waiver
27
27
  Specialist agent profiles, real protocol intents, self-custody by default,
28
28
  receipts or it didn't happen.
29
29
 
30
- Built for [Hermes](https://github.com/NousResearch/hermes-agent), the
31
- open-source agent runtime from [Nous Research](https://nousresearch.com).
32
- Oracle runs native chat directly — no external agent required.
33
- `oracle chat` starts the Oracle-native agent loop directly.
30
+ Oracle runs its own agent loop. `oracle chat` starts the Oracle-native agent
31
+ directly — no external agent runtime required.
34
32
 
35
- Hermes remains available as an optional delegate: `ORACLE_CHAT_BACKEND=hermes oracle chat`.
33
+ Any MCP-capable harness can drive it instead: run `oracle mcp install <target>`
34
+ for Claude Code, Claude Desktop, Codex, ChatGPT, Cursor, VS Code, or Copilot, or
35
+ install it as an [Agent Plugin](https://agent-plugins.org/). In that direction
36
+ the harness calls Oracle as a tool and Oracle's native loop stays in charge.
37
+ Run `oracle harness detect` to see what is installed and how to wire it.
38
+
39
+ [Hermes](https://github.com/NousResearch/hermes-agent) is one such harness, and
40
+ also remains available as a legacy delegate that takes over the model loop
41
+ entirely: `ORACLE_CHAT_BACKEND=hermes oracle chat`.
36
42
 
37
43
  Oracle can run standalone model auth directly with API keys or Claude, Codex,
38
44
  and Grok OAuth. OAuth credentials use the OS keychain when available, with a
@@ -349,12 +355,13 @@ npx oracle-data # local read plane on 127.0.0.1:8787
349
355
  npx oracle-data-mcp # MCP stdio server (any MCP client); needs oracle-data up
350
356
  ```
351
357
 
352
- It is better under [Hermes](https://hermes-agent.nousresearch.com/docs), because
353
- a trading stack is several workloads with opposite needs and **per-profile
354
- routing** gives each its own model, tools, and key scope: cheap wide context for
355
- research, a fast model for execution where latency is money, the strongest model
356
- for risk review, something small for unattended crons. The research profile can
357
- hold no signing key at all.
358
+ Per-profile routing is worth setting up under a multi-profile harness such as
359
+ [Hermes](https://hermes-agent.nousresearch.com/docs), because a trading stack is
360
+ several workloads with opposite needs and **per-profile routing** gives each its
361
+ own model, tools, and key scope: cheap wide context for research, a fast model
362
+ for execution where latency is money, the strongest model for risk review,
363
+ something small for unattended crons. The research profile can hold no signing
364
+ key at all. Oracle's native loop covers the single-agent case on its own.
358
365
 
359
366
  Oracle's own pre-release audit ran four model lineages — Grok 4.5, Opus 5,
360
367
  Fable 5, GPT-5.6 — and **each found a critical bug the others missed**. One
@@ -392,14 +399,15 @@ can't pass review quietly. An existing `SOUL.md` is never overwritten without
392
399
  `--force`, and `--force` writes a timestamped backup first.
393
400
 
394
401
  Oracle does not issue its own model credential. Standalone chat uses the OAuth
395
- login or API key the user configured; Hermes mode uses whichever provider that
396
- Hermes installation already supports.
397
-
398
- **Why "built for Hermes" and not just "works anywhere":** Oracle's read plane is
399
- an MCP server, so any MCP client can call it. But the *mesh* — per-lane memory,
400
- skills, sessions, and separate model choice per specialist — is Hermes profile
401
- machinery. You can use Oracle from any agent; you get the architecture in the
402
- diagram above from Hermes.
402
+ login or API key the user configured; a delegate harness uses whichever provider
403
+ that installation already supports.
404
+
405
+ **What you get where:** Oracle's read plane is an MCP server, so any MCP client
406
+ can call it, and the native loop brings its own memory, skills, scheduler, and
407
+ bounded tools. The multi-lane *mesh* in the diagram above — per-lane memory,
408
+ skills, sessions, and a separate model choice per specialist — is profile
409
+ machinery from a multi-profile harness such as Hermes. Use Oracle from any
410
+ agent, or on its own; add a profile mesh only if you want that topology.
403
411
 
404
412
  ## Best-execution routing
405
413
 
@@ -0,0 +1,21 @@
1
+ #!/usr/bin/env node
2
+ var K=Object.defineProperty;var E=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(r,t)=>(typeof require<"u"?require:r)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var u=(e,r,t)=>()=>{if(t)throw t[0];try{return e&&(r=e(e=0)),r}catch(n){throw t=[n],n}};var g=(e,r)=>{for(var t in r)K(e,t,{get:r[t],enumerable:!0})};import y from"node:fs";import H from"node:os";import m from"node:path";import{fileURLToPath as W}from"node:url";function R(){return process.env.ORACLE_FAKE_HOME||H.homedir()}function J(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function _(){return J()?process.env.ORACLE_CONFIG_DIR||m.join(R(),".config","oracle"):m.join(R(),".config","oracle")}function z(){return m.join(_(),"desk.json")}function Y(){return m.join(_(),"env")}function f({force:e=!1}={}){if(f._done&&!e)return f._result||null;f._done=!0;let r={},t=(a,o)=>{if(o==null)return;let s=String(o).trim();s&&(process.env[a]!=null&&String(process.env[a]).trim()!==""||(process.env[a]=s,r[a]=s))};try{let a=Y();if(y.existsSync(a))for(let o of y.readFileSync(a,"utf8").split(/\r?\n/)){let s=o.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!s||s[2].startsWith("#"))continue;let i=s[2];(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),t(s[1],i)}}catch{}try{let a=z();if(y.existsSync(a)){let o=JSON.parse(y.readFileSync(a,"utf8"));o&&typeof o=="object"&&(t("ORACLE_DESK_URL",o.deskUrl||o.dataUrl||o.url),t("ORACLE_DATA_URL",o.dataUrl||o.deskUrl||o.url),t("ORACLE_API_URL",o.apiUrl||o.dataUrl||o.deskUrl),t("ORACLE_PUBLIC_URL",o.publicUrl||o.deskUrl||o.dataUrl),t("ORACLE_EXEC_URL",o.execUrl),t("MAD_DESK_URL",o.deskUrl||o.dataUrl))}}catch{}let n=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return n&&(t("ORACLE_DESK_URL",n),t("ORACLE_DATA_URL",n),t("ORACLE_API_URL",n),t("ORACLE_PUBLIC_URL",n),t("MAD_DESK_URL",n)),f._result=Object.keys(r).length?r:null,f._result}var B,ve,A=u(()=>{B=m.dirname(W(import.meta.url)),ve=m.resolve(B,"../..");try{f()}catch{}});import S from"node:fs";import Z from"node:path";function X(){return Z.join(_(),"model.json")}function l(e){return String(e||"").trim()||void 0}function ee(e={}){let r=l(e.backend)?.toLowerCase()||"auto",t=l(e.provider)?.toLowerCase(),n=l(e.model),a=l(e.baseUrl)?.replace(/\/+$/,""),o=l(e.apiKeyEnv),s=Number.parseInt(String(e.contextLength||""),10),i=l(e.reasoningEffort),c=l(e.computeHost||e.remoteHost),p=l(e.computeUser||e.remoteUser),d=l(e.computePath||e.remotePath);if(!Q.has(r))throw new Error(`unsupported backend: ${r}`);if(process.env.ORACLE_PUBLIC_DESKTOP==="1"&&["remote","arch"].includes(r))throw new Error("remote compute backends are disabled in the public desktop");if(t&&!V.has(t))throw new Error(`unsupported provider: ${t}`);if(a&&t!=="custom")throw new Error("baseUrl is only supported for the custom provider");if(o&&!/^[A-Z][A-Z0-9_]*$/.test(o))throw new Error("api key env must be an uppercase environment variable name");if(t==="custom"&&!a)throw new Error("custom provider requires baseUrl");if(r==="standalone"&&!n)throw new Error("standalone backend requires a model");if(r==="remote"&&!c)throw new Error("remote backend requires computeHost");return{backend:r,...t?{provider:t}:{},...n?{model:n}:{},...a?{baseUrl:a}:{},...o?{apiKeyEnv:o}:{},...Number.isFinite(s)&&s>0?{contextLength:s}:{},...i?{reasoningEffort:i}:{},...c?{computeHost:c}:{},...p?{computeUser:p}:{},...d?{computePath:d}:{}}}function b(){let e=X();if(!S.existsSync(e))return null;try{return ee(JSON.parse(S.readFileSync(e,"utf8")))}catch{return null}}var Q,V,L=u(()=>{A();Q=new Set(["auto","standalone","hermes","remote","arch"]),V=new Set(["openrouter","openai","xai","deepseek","gemini","custom","anthropic-oauth","openai-codex","xai-oauth"])});import{spawn as te}from"node:child_process";import{join as v}from"node:path";import{homedir as x}from"node:os";function ne({readConfig:e=b}={}){let r=e();return r?r.backend==="hermes"?{ok:!1,error:"model config delegates to hermes; the gateway runs Oracle's native loop. Set a standalone backend: oracle model --backend standalone"}:r.model?{ok:!0,provider:r.provider,model:r.model}:{ok:!1,error:"model config has no model \u2014 run: oracle model --backend standalone --provider <p> --model <m>"}:{ok:!1,error:"gateway has no model configured \u2014 run: oracle model --backend standalone --provider <p> --model <m>"}}async function h({platform:e,chatId:r,senderId:t,text:n,userName:a}){let o=n.toLowerCase().trim();return/\b(buy|sell|swap|bridge|send|transfer|balance|portfolio|watch|quote|price)\b/.test(o)?ae({platform:e,chatId:r,senderId:t,text:n,userName:a}):se({platform:e,chatId:r,senderId:t,text:n,userName:a})}function j(e,{timeout:r=12e4}={}){return new Promise(t=>{let n=te(process.execPath,[oe,...e],{stdio:["ignore","pipe","pipe"],timeout:r,env:{...process.env,ORACLE_CONFIG_DIR:re}}),a="",o="";n.stdout.on("data",s=>a+=s.toString()),n.stderr.on("data",s=>o+=s.toString()),n.on("close",s=>t({code:s,out:a.trim(),err:o.trim()}))})}async function ae({text:e}){let r=await j(["route","swap","--text",e],{timeout:3e4});if(r.code===0&&r.out)try{return ie(JSON.parse(r.out))}catch{return r.out}return`Trade routing failed. Try: \`${e}\` again.`}async function se({text:e}){let r=ne();if(!r.ok)return`Oracle is not configured yet: ${r.error}`;let t=await j(["chat","-q",e]);return t.code===0&&t.out?t.out:t.err||"Oracle could not answer that. Try again."}function ie(e){return e.error?`\u274C ${e.error}`:e.tx?`\u2705 Trade prepared: \`${e.tx.slice(0,20)}...\`
3
+ Sign and broadcast from your own wallet.`:e.quote?`\u{1F4B1} ${e.quote}`:e.portfolio?`\u{1F4CA} ${e.portfolio}`:JSON.stringify(e,null,2)}var re,oe,w=u(()=>{L();re=process.env.ORACLE_CONFIG_DIR||v(x(),".config","oracle"),oe=process.env.ORACLE_CLI_ENTRY||v(x(),".local","share","oracle-stable","node_modules","@oracle-agent","oracle","bin","oracle.mjs")});var k={};g(k,{telegram:()=>ce});async function ce(e){let{Bot:r}=await import("grammy"),t=new r(e.token);return t.command("start",n=>n.reply("Oracle ready. Ask me anything \u2014 swap, bridge, portfolio, watch.")),t.on("message:text",async n=>{let a=String(n.chat.id),o=String(n.from?.id||a),s=n.message.text;try{n.replyWithChatAction("typing").catch(()=>{});let i=await h({platform:"telegram",chatId:a,senderId:o,text:s,userName:n.from?.username||n.from?.first_name||"user"});i&&await n.reply(i,{parse_mode:"Markdown"})}catch(i){process.stderr.write(`telegram-gateway: ${i.message}
4
+ `),await n.reply("Something went wrong. Try again.").catch(()=>{})}}),t.start(),{platform:"telegram",bot:t}}var U=u(()=>{w()});var D={};g(D,{discord:()=>pe});async function pe(e){let{Client:r,GatewayIntentBits:t}=await import("discord.js"),n=new r({intents:[t.Guilds,t.GuildMessages,t.MessageContent,t.DirectMessages]});return n.on("messageCreate",async a=>{if(a.author.bot)return;let o=a.channel.id,s=a.author.id,i=a.content;try{let c=!a.guild,p=a.mentions.has(n.user.id);if(!c&&!p)return;a.channel.sendTyping().catch(()=>{});let d=await h({platform:"discord",chatId:o,senderId:s,text:i.replace(`<@${n.user.id}>`,"").trim(),userName:a.author.username});d&&await a.reply(d).catch(()=>{})}catch(c){process.stderr.write(`discord-gateway: ${c.message}
5
+ `)}}),await n.login(e.token),{platform:"discord",client:n}}var P=u(()=>{w()});var T={};g(T,{whatsapp:()=>fe});import{join as O}from"node:path";import{homedir as le}from"node:os";import{spawnSync as de}from"node:child_process";function ue(){try{return E.resolve("whatsapp-web.js"),E.resolve("qrcode-terminal"),!0}catch{return process.stderr.write(`whatsapp-gateway: installing dependencies...
6
+ `),de("npm",["install","whatsapp-web.js","qrcode-terminal"],{cwd:O(I,"gateway"),stdio:"inherit",timeout:6e4}).status===0}}async function fe(e){if(!ue())return process.stderr.write(`whatsapp-gateway: failed to install dependencies
7
+ `),{platform:"whatsapp",status:"failed"};let{Client:r,LocalAuth:t}=await import("whatsapp-web.js"),{generate:n}=await import("qrcode-terminal"),a=new r({authStrategy:new t({dataPath:O(I,".wwebjs_auth")}),puppeteer:{headless:!0,args:["--no-sandbox"]}});return a.on("qr",o=>{process.stderr.write(`
8
+ WhatsApp: scan this QR code in WhatsApp \u2192 Linked Devices:
9
+
10
+ `),n(o,{small:!0}),process.stderr.write(`
11
+ `)}),a.on("ready",()=>{process.stderr.write(`whatsapp-gateway: connected
12
+ `)}),a.on("message",async o=>{if(o.fromMe)return;let s=o.from,i=o.author||o.from,c=o.body;try{let p=await h({platform:"whatsapp",chatId:s,senderId:i,text:c,userName:o._data?.notifyName||"user"});if(p){let d=p.replace(/\*\*/g,"*").replace(/```[\s\S]*?```/g,"[code]").replace(/`/g,"");await o.reply(d)}}catch(p){process.stderr.write(`whatsapp-gateway: ${p.message}
13
+ `)}}),await a.initialize(),{platform:"whatsapp",client:a}}var I,N=u(()=>{w();I=process.env.ORACLE_CONFIG_DIR||O(le(),".config","oracle")});var $={};g($,{signal_:()=>me});async function me(e){return process.stderr.write(`signal-gateway: requires signal-cli binary
14
+ `),process.stderr.write(`signal-gateway: not built yet \u2014 use Telegram or Discord for now
15
+ `),{platform:"signal",status:"stub"}}var M=u(()=>{w()});import{createServer as he}from"node:http";import{env as G}from"node:process";import{join as q}from"node:path";import{homedir as we}from"node:os";import{readFileSync as ge,existsSync as ye}from"node:fs";var _e=G.ORACLE_CONFIG_DIR||q(we(),".config","oracle"),F=q(_e,"gateway.json");function Ce(){return ye(F)?JSON.parse(ge(F,"utf8")):{platforms:{}}}var Ee=Object.freeze({telegram:"grammy",discord:"discord.js",whatsapp:"whatsapp-web.js"});async function C(e,r,t,n){try{n.push(await r(t))}catch(a){let o=Ee[e];if(o&&/Cannot find (module|package)|ERR_MODULE_NOT_FOUND/.test(String(a.message))){process.stderr.write(`oracle-gateway: ${e} needs an optional dependency. Install it first:
16
+ npm install -g ${o}
17
+ `);return}process.stderr.write(`oracle-gateway: ${e} failed to start: ${a.message}
18
+ `)}}async function Oe(){let e=Ce(),r=[];e.platforms?.telegram&&await C("telegram",async t=>(await Promise.resolve().then(()=>(U(),k))).telegram(t.platforms.telegram),e,r),e.platforms?.discord&&await C("discord",async t=>(await Promise.resolve().then(()=>(P(),D))).discord(t.platforms.discord),e,r),e.platforms?.whatsapp&&await C("whatsapp",async t=>(await Promise.resolve().then(()=>(N(),T))).whatsapp(t.platforms.whatsapp),e,r),e.platforms?.signal&&await C("signal",async t=>(await Promise.resolve().then(()=>(M(),$))).signal_(t.platforms.signal),e,r),r.length===0&&process.stderr.write(`oracle-gateway: no platforms configured. Run 'oracle setup telegram' first.
19
+ `),process.stderr.write(`oracle-gateway: ${r.length} platform(s) connected
20
+ `),he((t,n)=>{n.writeHead(200,{"Content-Type":"application/json"}),n.end(JSON.stringify({status:"ok",platforms:Object.keys(e.platforms||{})}))}).listen(G.ORACLE_GATEWAY_PORT||9270,"127.0.0.1")}Oe().catch(e=>{process.stderr.write(`oracle-gateway: ${e.message}
21
+ `),process.exit(1)});
@@ -1,16 +1,16 @@
1
- import R from"node:fs";import L from"node:path";import P from"node:fs";import re from"node:os";import E from"node:path";import{fileURLToPath as oe}from"node:url";var ne=E.dirname(oe(import.meta.url)),Le=E.resolve(ne,"../..");function H(){return process.env.ORACLE_FAKE_HOME||re.homedir()}function ie(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function O(){return ie()?process.env.ORACLE_CONFIG_DIR||E.join(H(),".config","oracle"):E.join(H(),".config","oracle")}function se(){return E.join(O(),"desk.json")}function ce(){return E.join(O(),"env")}function S({force:e=!1}={}){if(S._done&&!e)return S._result||null;S._done=!0;let t={},r=(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=ce();if(P.existsSync(o))for(let i of P.readFileSync(o,"utf8").split(/\r?\n/)){let s=i.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!s||s[2].startsWith("#"))continue;let l=s[2];(l.startsWith('"')&&l.endsWith('"')||l.startsWith("'")&&l.endsWith("'"))&&(l=l.slice(1,-1)),r(s[1],l)}}catch{}try{let o=se();if(P.existsSync(o)){let i=JSON.parse(P.readFileSync(o,"utf8"));i&&typeof i=="object"&&(r("ORACLE_DESK_URL",i.deskUrl||i.dataUrl||i.url),r("ORACLE_DATA_URL",i.dataUrl||i.deskUrl||i.url),r("ORACLE_API_URL",i.apiUrl||i.dataUrl||i.deskUrl),r("ORACLE_PUBLIC_URL",i.publicUrl||i.deskUrl||i.dataUrl),r("ORACLE_EXEC_URL",i.execUrl),r("MAD_DESK_URL",i.deskUrl||i.dataUrl))}}catch{}let n=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return n&&(r("ORACLE_DESK_URL",n),r("ORACLE_DATA_URL",n),r("ORACLE_API_URL",n),r("ORACLE_PUBLIC_URL",n),r("MAD_DESK_URL",n)),S._result=Object.keys(t).length?t:null,S._result}try{S()}catch{}function U(e){return P.mkdirSync(e,{recursive:!0}),e}var ae=new Set(["auto","standalone","hermes","remote","arch"]),ue=new Set(["openrouter","openai","xai","deepseek","gemini","custom","anthropic-oauth","openai-codex","xai-oauth"]);function de(){return L.join(O(),"model.json")}function v(e){return String(e||"").trim()||void 0}function pe(e={}){let t=v(e.backend)?.toLowerCase()||"auto",r=v(e.provider)?.toLowerCase(),n=v(e.model),o=v(e.baseUrl)?.replace(/\/+$/,""),i=v(e.apiKeyEnv),s=Number.parseInt(String(e.contextLength||""),10),l=v(e.reasoningEffort),c=v(e.computeHost||e.remoteHost),h=v(e.computeUser||e.remoteUser),y=v(e.computePath||e.remotePath);if(!ae.has(t))throw new Error(`unsupported backend: ${t}`);if(process.env.ORACLE_PUBLIC_DESKTOP==="1"&&["remote","arch"].includes(t))throw new Error("remote compute backends are disabled in the public desktop");if(r&&!ue.has(r))throw new Error(`unsupported provider: ${r}`);if(o&&r!=="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(r==="custom"&&!o)throw new Error("custom provider requires baseUrl");if(t==="standalone"&&!n)throw new Error("standalone backend requires a model");if(t==="remote"&&!c)throw new Error("remote backend requires computeHost");return{backend:t,...r?{provider:r}:{},...n?{model:n}:{},...o?{baseUrl:o}:{},...i?{apiKeyEnv:i}:{},...Number.isFinite(s)&&s>0?{contextLength:s}:{},...l?{reasoningEffort:l}:{},...c?{computeHost:c}:{},...h?{computeUser:h}:{},...y?{computePath:y}:{}}}function J(e){let t=pe(e),r=de();U(L.dirname(r)),process.platform!=="win32"&&R.chmodSync(L.dirname(r),448);let n=`${r}.${process.pid}.tmp`;return R.writeFileSync(n,`${JSON.stringify(t,null,2)}
2
- `,{mode:384}),R.renameSync(n,r),process.platform!=="win32"&&R.chmodSync(r,384),t}import{createHash as le,randomBytes as D,timingSafeEqual as fe}from"node:crypto";import g from"node:fs";import b from"node:path";import he from"node:readline/promises";import{spawn as me,spawnSync as we}from"node:child_process";var C=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"}});function ge(e={}){return typeof e.now=="function"?Number(e.now()):Date.now()}function _(e){let t=String(e||"").trim().toLowerCase();for(let[r,n]of Object.entries(C))if(n.aliases.includes(t))return r;throw new Error(`unsupported OAuth provider: ${e||"(empty)"}`)}function q(e){let t=_(e);return{id:t,...C[t]}}function w(e,t={}){if(!g.existsSync(e))return t;try{let r=JSON.parse(g.readFileSync(e,"utf8"));if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid object");return r}catch{throw new Error(`credential store is unreadable or corrupt: ${b.basename(e)}`)}}function V(e){U(e),process.platform!=="win32"&&g.chmodSync(e,448)}function k(e,t){V(b.dirname(e));let r=`${e}.${process.pid}.${D(4).toString("hex")}.tmp`;g.writeFileSync(r,`${JSON.stringify(t,null,2)}
3
- `,{mode:384}),g.renameSync(r,e),process.platform!=="win32"&&g.chmodSync(e,384)}function ye(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 T(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 j(e={}){let t=String(e.accessToken||e.access_token||"").trim(),r=String(e.refreshToken||e.refresh_token||"").trim(),n=Number(e.expiresAt||e.expires_at||0);if(!t)throw new Error("OAuth credential is missing access token");return{accessToken:t,refreshToken:r,expiresAt:Number.isFinite(n)?n:0,tokenType:String(e.tokenType||e.token_type||"Bearer"),source:String(e.source||"oracle"),...e.discovery?{discovery:e.discovery}:{},...e.scope?{scope:e.scope}:{},...e.idToken||e.id_token?{idToken:String(e.idToken||e.id_token)}:{}}}function ve(e={}){let t=e.file||b.join(O(),"oauth.json"),r=e.metadataFile||b.join(b.dirname(t),"oauth-meta.json"),n=e.spawnFn||we,o=e.keychain!==!1&&process.env.ORACLE_AUTH_FILE_STORE!=="1"&&ye(n),i=o?"linux-secret-service":"private-file",s=`${t}.lock`;async function l(f){V(b.dirname(s));let d;for(let a=0;a<400;a+=1)try{d=g.openSync(s,"wx",384);break}catch(u){if(u?.code!=="EEXIST")throw u;try{Date.now()-g.statSync(s).mtimeMs>3e5&&g.unlinkSync(s)}catch{}await new Promise(p=>setTimeout(p,25))}if(d===void 0)throw new Error("timed out waiting for OAuth credential lock");try{return await f()}finally{try{g.closeSync(d)}catch{}try{g.unlinkSync(s)}catch{}}}function c(f,d="oauth"){return["application","oracle","kind",d,"provider",f]}function h(f){let d=_(f);if(o){let p=n("secret-tool",["lookup",...c(d)],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(p.error||p.status!==0||!String(p.stdout||"").trim())return null;try{return j(JSON.parse(String(p.stdout).trim()))}catch{return null}}let u=w(t,{providers:{}}).providers?.[d];if(!u)return null;try{return j(u)}catch{return null}}function y(f,d){let a=_(f),u=j(d);if(o){let m=n("secret-tool",["store",`--label=Oracle ${a} OAuth`,...c(a)],{input:JSON.stringify(u),encoding:"utf8",stdio:["pipe","ignore","pipe"]});if(m.error||m.status!==0)throw new Error("OS credential store rejected OAuth credential");let x=w(r,{providers:{}});return x.providers||={},x.providers[a]={expiresAt:u.expiresAt,source:u.source},k(r,x),u}let p=w(t,{providers:{}});return p.providers||={},p.providers[a]=u,k(t,p),u}function I(f){let d=_(f);if(o){let p=n("secret-tool",["clear",...c(d)],{encoding:"utf8",stdio:["ignore","ignore","pipe"]}),m=w(r,{providers:{}});return m.providers&&delete m.providers[d],k(r,m),!p.error&&p.status===0}let a=w(t,{providers:{}}),u=!!a.providers?.[d];return a.providers&&delete a.providers[d],k(t,a),u}function B(f){let d=T(f);if(o){let a=n("secret-tool",["lookup",...c(d,"api-key")],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return a.error||a.status!==0?"":String(a.stdout||"").trim()}return String(w(t,{apiKeys:{}}).apiKeys?.[d]||"").trim()}function Q(f,d){let a=T(f),u=String(d||"").trim();if(!u)throw new Error("API key is empty");if(o){let m=n("secret-tool",["store",`--label=Oracle ${a} API key`,...c(a,"api-key")],{input:u,encoding:"utf8",stdio:["pipe","ignore","pipe"]});if(m.error||m.status!==0)throw new Error("OS credential store rejected API key");let x=w(r,{providers:{},apiKeys:{}});return x.apiKeys||={},x.apiKeys[a]={configured:!0},k(r,x),!0}let p=w(t,{providers:{},apiKeys:{}});return p.apiKeys||={},p.apiKeys[a]=u,k(t,p),!0}function ee(f){let d=T(f);if(o){let p=n("secret-tool",["clear",...c(d,"api-key")],{encoding:"utf8",stdio:["ignore","ignore","pipe"]}),m=w(r,{providers:{},apiKeys:{}});return m.apiKeys&&delete m.apiKeys[d],k(r,m),!p.error&&p.status===0}let a=w(t,{providers:{},apiKeys:{}}),u=!!a.apiKeys?.[d];return a.apiKeys&&delete a.apiKeys[d],k(t,a),u}function te(){let f={},d={};if(o){let a=w(r,{providers:{},apiKeys:{}});for(let[u,p]of Object.entries(a.providers||{}))f[u]={loggedIn:!!h(u),expiresAt:Number(p.expiresAt||0),source:String(p.source||"oracle"),storage:i};for(let u of Object.keys(a.apiKeys||{}))d[u]={configured:!!B(u),storage:i}}else{let a=w(t,{providers:{},apiKeys:{}});for(let[u,p]of Object.entries(a.providers||{}))f[u]={loggedIn:!!p?.accessToken,expiresAt:Number(p?.expiresAt||0),source:String(p?.source||"oracle"),storage:i};for(let[u,p]of Object.entries(a.apiKeys||{}))d[u]={configured:!!p,storage:i}}return{storage:i,providers:f,apiKeys:d}}return Object.freeze({file:t,storage:i,get:h,set:y,remove:I,getApiKey:B,setApiKey:Q,removeApiKey:ee,status:te,withLock:l})}var W;function X(){return W||=ve(),W}function K(e){return Buffer.from(e).toString("base64url")}function ke(){let e=K(D(32));return{verifier:e,challenge:K(le("sha256").update(e).digest()),state:K(D(24))}}function xe(e,t){let r=Buffer.from(String(e||"")),n=Buffer.from(String(t||""));return r.length===n.length&&fe(r,n)}function _e(e){let t=String(e),r=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd.exe",["/d","/s","/c","start","",t]]:["xdg-open",[t]];try{return me(r[0],r[1],{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function F(e){return new URLSearchParams(e).toString()}async function A(e,t){if(!e?.ok){let n="";try{n=String((await e.json())?.error||"")}catch{}throw new Error(`${t} failed (HTTP ${e?.status||"unknown"}${n?`, ${n}`:""})`)}let r=await e.json();if(!r||typeof r!="object")throw new Error(`${t} returned invalid JSON`);return r}async function Ae(e){if(e)return String(await e()).trim();let t=he.createInterface({input:process.stdin,output:process.stdout});try{return String(await t.question("Authorization code: ")).trim()}finally{t.close()}}function z(e,t={}){let r=String(e.access_token||"").trim(),n=String(e.refresh_token||t.refreshToken||"").trim();if(!r)throw new Error("OAuth token response is missing access token");let o=Number(e.expires_in||3600);return j({accessToken:r,refreshToken:n,expiresAt:ge(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 Se(e){let t=C["anthropic-oauth"],r=e.pkce||ke(),n=new URLSearchParams({code:"true",client_id:t.clientId,response_type:"code",redirect_uri:t.redirectUri,scope:t.scope,code_challenge:r.challenge,code_challenge_method:"S256",state:r.state}),o=`${t.authorizeUrl}?${n}`;e.output(`Open: ${o}`),e.openFn(o);let i=await Ae(e.inputFn),[s,l]=i.split("#",2);if(!s||!xe(l,r.state))throw new Error("Claude OAuth state mismatch");let c=await e.fetchFn(t.tokenUrl,{method:"POST",headers:{"content-type":"application/json","user-agent":"axios/1.7.9"},body:JSON.stringify({grant_type:"authorization_code",client_id:t.clientId,code:s,state:l,redirect_uri:t.redirectUri,code_verifier:r.verifier})});return z(await A(c,"Claude OAuth token exchange"),e)}async function Ee(e){let t=C["openai-codex"],r=await A(await e.fetchFn(`${t.issuer}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({client_id:t.clientId})}),"Codex device authorization");if(!r.user_code||!r.device_auth_id)throw new Error("Codex device authorization returned incomplete data");let n=`${t.issuer}/codex/device`;e.output(`Open: ${n}`),e.output(`Code: ${r.user_code}`),e.openFn(n);let o=Math.max(3,Number(r.interval||5)),i;for(let l=0;l<Math.ceil(900/o);l+=1){await e.sleepFn(o*1e3);let c=await e.fetchFn(`${t.issuer}/api/accounts/deviceauth/token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({device_auth_id:r.device_auth_id,user_code:r.user_code})});if(c.ok){i=await A(c,"Codex device authorization");break}if(![403,404].includes(c.status))throw new Error(`Codex device authorization failed (HTTP ${c.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:F({grant_type:"authorization_code",code:i.authorization_code,redirect_uri:`${t.issuer}/deviceauth/callback`,client_id:t.clientId,code_verifier:i.code_verifier})});return z(await A(s,"Codex OAuth token exchange"),e)}function $(e){let t=new URL(String(e)),r=t.hostname.toLowerCase();if(t.protocol!=="https:"||r!=="x.ai"&&!r.endsWith(".x.ai"))throw new Error("xAI OAuth discovery returned an untrusted endpoint");return t.toString()}async function Oe(e){let t=C["xai-oauth"],r=await A(await e.fetchFn(t.discoveryUrl,{headers:{accept:"application/json"}}),"xAI OAuth discovery");$(r.authorization_endpoint);let n=$(r.token_endpoint),o=await A(await e.fetchFn(t.deviceUrl,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:F({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=$(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)),l=Math.ceil(Math.max(1,Number(o.expires_in||600))/s);for(let c=0;c<l;c+=1){let h=await e.fetchFn(n,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:F({grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:t.clientId,device_code:o.device_code})});if(h.ok){let I=await A(h,"xAI OAuth token exchange");return z(I,{...e,discovery:{authorization_endpoint:$(r.authorization_endpoint),token_endpoint:n}})}let y="";try{y=String((await h.json())?.error||"")}catch{}if(y==="slow_down")await e.sleepFn((s+1)*1e3);else if(y==="authorization_pending")await e.sleepFn(s*1e3);else throw new Error(`xAI OAuth token exchange failed (HTTP ${h.status}${y?`, ${y}`:""})`)}throw new Error("xAI device authorization timed out")}async function G(e,t={}){let r=_(e),n={fetchFn:t.fetchFn||globalThis.fetch,inputFn:t.inputFn,sleepFn:t.sleepFn||(o=>new Promise(i=>setTimeout(i,o))),openFn:t.openFn||_e,output:t.output||(o=>process.stdout.write(`${o}
4
- `)),now:t.now,pkce:t.pkce};return r==="anthropic-oauth"?Se(n):r==="openai-codex"?Ee(n):Oe(n)}var Z=Object.freeze({openrouter:{model:"openrouter/auto"},openai:{model:"gpt-4.1-mini"},xai:{model:"grok-4.5"},deepseek:{model:"deepseek-chat"},gemini:{model:"gemini-2.5-flash"},custom:{model:""}});function M(e,t){let r=e.indexOf(t);return r>=0&&e[r+1]?e[r+1]:""}async function be(){let e="";for await(let t of process.stdin)e+=t;return e.trim()}function Pe(e="API key: "){if(!process.stdin.isTTY||!process.stdin.setRawMode)throw new Error("non-interactive API-key input requires --stdin");return process.stdout.write(e),new Promise((t,r)=>{let n="",o=()=>{process.stdin.off("data",i),process.stdin.setRawMode(!1),process.stdin.pause(),process.stdout.write(`
5
- `)},i=s=>{let l=String(s);for(let c of l){if(c==="\r"||c===`
6
- `){o(),t(n.trim());return}if(c===""){o(),r(new Error("cancelled"));return}c==="\x7F"||c==="\b"?n=n.slice(0,-1):n+=c}};process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",i)})}function N(e,t,{baseUrl:r=""}={}){if(!t)throw new Error(`${e} provider requires --model`);let n={backend:"standalone",provider:e,model:t};if(e==="custom"){if(!r)throw new Error("custom provider requires --base-url");n.baseUrl=r}return n}function Y(e,t,r={}){return J(N(e,t,r))}function Ce(e){process.stdout.write(`storage: ${e.storage}
1
+ import $ from"node:fs";import L from"node:path";import U from"node:fs";import se from"node:os";import O from"node:path";import{fileURLToPath as ce}from"node:url";var ae=O.dirname(ce(import.meta.url)),ze=O.resolve(ae,"../..");function J(){return process.env.ORACLE_FAKE_HOME||se.homedir()}function ue(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function b(){return ue()?process.env.ORACLE_CONFIG_DIR||O.join(J(),".config","oracle"):O.join(J(),".config","oracle")}function de(){return O.join(b(),"desk.json")}function pe(){return O.join(b(),"env")}function E({force:e=!1}={}){if(E._done&&!e)return E._result||null;E._done=!0;let t={},r=(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=pe();if(U.existsSync(o))for(let i of U.readFileSync(o,"utf8").split(/\r?\n/)){let s=i.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!s||s[2].startsWith("#"))continue;let p=s[2];(p.startsWith('"')&&p.endsWith('"')||p.startsWith("'")&&p.endsWith("'"))&&(p=p.slice(1,-1)),r(s[1],p)}}catch{}try{let o=de();if(U.existsSync(o)){let i=JSON.parse(U.readFileSync(o,"utf8"));i&&typeof i=="object"&&(r("ORACLE_DESK_URL",i.deskUrl||i.dataUrl||i.url),r("ORACLE_DATA_URL",i.dataUrl||i.deskUrl||i.url),r("ORACLE_API_URL",i.apiUrl||i.dataUrl||i.deskUrl),r("ORACLE_PUBLIC_URL",i.publicUrl||i.deskUrl||i.dataUrl),r("ORACLE_EXEC_URL",i.execUrl),r("MAD_DESK_URL",i.deskUrl||i.dataUrl))}}catch{}let n=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return n&&(r("ORACLE_DESK_URL",n),r("ORACLE_DATA_URL",n),r("ORACLE_API_URL",n),r("ORACLE_PUBLIC_URL",n),r("MAD_DESK_URL",n)),E._result=Object.keys(t).length?t:null,E._result}try{E()}catch{}function j(e){return U.mkdirSync(e,{recursive:!0}),e}var le=new Set(["auto","standalone","hermes","remote","arch"]),fe=new Set(["openrouter","openai","xai","deepseek","gemini","custom","anthropic-oauth","openai-codex","xai-oauth"]);function he(){return L.join(b(),"model.json")}function k(e){return String(e||"").trim()||void 0}function me(e={}){let t=k(e.backend)?.toLowerCase()||"auto",r=k(e.provider)?.toLowerCase(),n=k(e.model),o=k(e.baseUrl)?.replace(/\/+$/,""),i=k(e.apiKeyEnv),s=Number.parseInt(String(e.contextLength||""),10),p=k(e.reasoningEffort),u=k(e.computeHost||e.remoteHost),g=k(e.computeUser||e.remoteUser),h=k(e.computePath||e.remotePath);if(!le.has(t))throw new Error(`unsupported backend: ${t}`);if(process.env.ORACLE_PUBLIC_DESKTOP==="1"&&["remote","arch"].includes(t))throw new Error("remote compute backends are disabled in the public desktop");if(r&&!fe.has(r))throw new Error(`unsupported provider: ${r}`);if(o&&r!=="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(r==="custom"&&!o)throw new Error("custom provider requires baseUrl");if(t==="standalone"&&!n)throw new Error("standalone backend requires a model");if(t==="remote"&&!u)throw new Error("remote backend requires computeHost");return{backend:t,...r?{provider:r}:{},...n?{model:n}:{},...o?{baseUrl:o}:{},...i?{apiKeyEnv:i}:{},...Number.isFinite(s)&&s>0?{contextLength:s}:{},...p?{reasoningEffort:p}:{},...u?{computeHost:u}:{},...g?{computeUser:g}:{},...h?{computePath:h}:{}}}function W(e){let t=me(e),r=he();j(L.dirname(r)),process.platform!=="win32"&&$.chmodSync(L.dirname(r),448);let n=`${r}.${process.pid}.tmp`;return $.writeFileSync(n,`${JSON.stringify(t,null,2)}
2
+ `,{mode:384}),$.renameSync(n,r),process.platform!=="win32"&&$.chmodSync(r,384),t}import{createHash as we,randomBytes as F,timingSafeEqual as ge}from"node:crypto";import y from"node:fs";import x from"node:path";import ye from"node:readline/promises";import{spawn as ve,spawnSync as ke}from"node:child_process";var C=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"}}),xe=12e4;function _e(e={}){return typeof e.now=="function"?Number(e.now()):Date.now()}function A(e){let t=String(e||"").trim().toLowerCase();for(let[r,n]of Object.entries(C))if(n.aliases.includes(t))return r;throw new Error(`unsupported OAuth provider: ${e||"(empty)"}`)}function V(e){let t=A(e);return{id:t,...C[t]}}function w(e,t={}){if(!y.existsSync(e))return t;try{let r=JSON.parse(y.readFileSync(e,"utf8"));if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid object");return r}catch{throw new Error(`credential store is unreadable or corrupt: ${x.basename(e)}`)}}function X(e){j(e),process.platform!=="win32"&&y.chmodSync(e,448)}function _(e,t){X(x.dirname(e));let r=`${e}.${process.pid}.${F(4).toString("hex")}.tmp`;y.writeFileSync(r,`${JSON.stringify(t,null,2)}
3
+ `,{mode:384}),y.renameSync(r,e),process.platform!=="win32"&&y.chmodSync(e,384)}function Ae(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 T(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 R(e={}){let t=String(e.accessToken||e.access_token||"").trim(),r=String(e.refreshToken||e.refresh_token||"").trim(),n=Number(e.expiresAt||e.expires_at||0);if(!t)throw new Error("OAuth credential is missing access token");return{accessToken:t,refreshToken:r,expiresAt:Number.isFinite(n)?n:0,tokenType:String(e.tokenType||e.token_type||"Bearer"),source:String(e.source||"oracle"),...e.discovery?{discovery:e.discovery}:{},...e.scope?{scope:e.scope}:{},...e.idToken||e.id_token?{idToken:String(e.idToken||e.id_token)}:{}}}function Se(e={}){let t=e.file||x.join(b(),"oauth.json"),r=e.metadataFile||x.join(x.dirname(t),"oauth-meta.json"),n=e.linksFile||x.join(x.dirname(t),"oauth-links.json"),o=()=>typeof e.now=="function"?Number(e.now()):Date.now(),i=e.spawnFn||ke,s=e.keychain!==!1&&process.env.ORACLE_AUTH_FILE_STORE!=="1"&&Ae(i),p=s?"linux-secret-service":"private-file",u=`${t}.lock`;async function g(f){X(x.dirname(u));let l;for(let c=0;c<400;c+=1)try{l=y.openSync(u,"wx",384);break}catch(a){if(a?.code!=="EEXIST")throw a;try{Date.now()-y.statSync(u).mtimeMs>3e5&&y.unlinkSync(u)}catch{}await new Promise(d=>setTimeout(d,25))}if(l===void 0)throw new Error("timed out waiting for OAuth credential lock");try{return await f()}finally{try{y.closeSync(l)}catch{}try{y.unlinkSync(u)}catch{}}}function h(f,l="oauth"){return["application","oracle","kind",l,"provider",f]}function P(f){if(!y.existsSync(n))return null;let c=w(n,{providers:{}}).providers?.[f];if(!Array.isArray(c))return null;let a=[];for(let d of c)if(x.isAbsolute(String(d||"")))try{let m=w(d,{}),v=f==="anthropic-oauth"?m.claudeAiOauth:null;if(!v)continue;let ie=R(v);a.push({...ie,refreshToken:"",source:"external-access-only"})}catch{}return a.length?a.find(d=>!d.expiresAt||d.expiresAt>o()+xe)||a[0]:null}function B(f){let l=A(f);if(s){let d=i("secret-tool",["lookup",...h(l)],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});if(!d.error&&d.status===0&&String(d.stdout||"").trim())try{return R(JSON.parse(String(d.stdout).trim()))}catch{}return P(l)}let a=w(t,{providers:{}}).providers?.[l];if(a)try{return R(a)}catch{}return P(l)}function ee(f,l){let c=A(f),a=R(l);if(s){let m=i("secret-tool",["store",`--label=Oracle ${c} OAuth`,...h(c)],{input:JSON.stringify(a),encoding:"utf8",stdio:["pipe","ignore","pipe"]});if(m.error||m.status!==0)throw new Error("OS credential store rejected OAuth credential");let v=w(r,{providers:{}});return v.providers||={},v.providers[c]={expiresAt:a.expiresAt,source:a.source},_(r,v),a}let d=w(t,{providers:{}});return d.providers||={},d.providers[c]=a,_(t,d),a}function te(f){let l=A(f);if(s){let d=i("secret-tool",["clear",...h(l)],{encoding:"utf8",stdio:["ignore","ignore","pipe"]}),m=w(r,{providers:{}});return m.providers&&delete m.providers[l],_(r,m),!d.error&&d.status===0}let c=w(t,{providers:{}}),a=!!c.providers?.[l];return c.providers&&delete c.providers[l],_(t,c),a}function H(f){let l=T(f);if(s){let c=i("secret-tool",["lookup",...h(l,"api-key")],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return c.error||c.status!==0?"":String(c.stdout||"").trim()}return String(w(t,{apiKeys:{}}).apiKeys?.[l]||"").trim()}function re(f,l){let c=T(f),a=String(l||"").trim();if(!a)throw new Error("API key is empty");if(s){let m=i("secret-tool",["store",`--label=Oracle ${c} API key`,...h(c,"api-key")],{input:a,encoding:"utf8",stdio:["pipe","ignore","pipe"]});if(m.error||m.status!==0)throw new Error("OS credential store rejected API key");let v=w(r,{providers:{},apiKeys:{}});return v.apiKeys||={},v.apiKeys[c]={configured:!0},_(r,v),!0}let d=w(t,{providers:{},apiKeys:{}});return d.apiKeys||={},d.apiKeys[c]=a,_(t,d),!0}function oe(f){let l=T(f);if(s){let d=i("secret-tool",["clear",...h(l,"api-key")],{encoding:"utf8",stdio:["ignore","ignore","pipe"]}),m=w(r,{providers:{},apiKeys:{}});return m.apiKeys&&delete m.apiKeys[l],_(r,m),!d.error&&d.status===0}let c=w(t,{providers:{},apiKeys:{}}),a=!!c.apiKeys?.[l];return c.apiKeys&&delete c.apiKeys[l],_(t,c),a}function ne(){let f={},l={};if(s){let c=w(r,{providers:{},apiKeys:{}});for(let[a,d]of Object.entries(c.providers||{}))f[a]={loggedIn:!!B(a),expiresAt:Number(d.expiresAt||0),source:String(d.source||"oracle"),storage:p};for(let a of Object.keys(c.apiKeys||{}))l[a]={configured:!!H(a),storage:p}}else{let c=w(t,{providers:{},apiKeys:{}});for(let[a,d]of Object.entries(c.providers||{}))f[a]={loggedIn:!!d?.accessToken,expiresAt:Number(d?.expiresAt||0),source:String(d?.source||"oracle"),storage:p};for(let[a,d]of Object.entries(c.apiKeys||{}))l[a]={configured:!!d,storage:p}}for(let c of Object.keys(C)){if(f[c])continue;let a=P(c);a&&(f[c]={loggedIn:!0,expiresAt:a.expiresAt,source:a.source,storage:"external-access-source"})}return{storage:p,providers:f,apiKeys:l}}return Object.freeze({file:t,storage:p,get:B,set:ee,remove:te,getApiKey:H,setApiKey:re,removeApiKey:oe,status:ne,withLock:g})}var q;function G(){return q||=Se(),q}function K(e){return Buffer.from(e).toString("base64url")}function Ee(){let e=K(F(32));return{verifier:e,challenge:K(we("sha256").update(e).digest()),state:K(F(24))}}function Oe(e,t){let r=Buffer.from(String(e||"")),n=Buffer.from(String(t||""));return r.length===n.length&&ge(r,n)}function be(e){let t=String(e),r=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd.exe",["/d","/s","/c","start","",t]]:["xdg-open",[t]];try{return ve(r[0],r[1],{detached:!0,stdio:"ignore"}).unref(),!0}catch{return!1}}function D(e){return new URLSearchParams(e).toString()}async function S(e,t){if(!e?.ok){let n="";try{n=String((await e.json())?.error||"")}catch{}throw new Error(`${t} failed (HTTP ${e?.status||"unknown"}${n?`, ${n}`:""})`)}let r=await e.json();if(!r||typeof r!="object")throw new Error(`${t} returned invalid JSON`);return r}async function Ce(e){if(e)return String(await e()).trim();let t=ye.createInterface({input:process.stdin,output:process.stdout});try{return String(await t.question("Authorization code: ")).trim()}finally{t.close()}}function z(e,t={}){let r=String(e.access_token||"").trim(),n=String(e.refresh_token||t.refreshToken||"").trim();if(!r)throw new Error("OAuth token response is missing access token");let o=Number(e.expires_in||3600);return R({accessToken:r,refreshToken:n,expiresAt:_e(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 Pe(e){let t=C["anthropic-oauth"],r=e.pkce||Ee(),n=new URLSearchParams({code:"true",client_id:t.clientId,response_type:"code",redirect_uri:t.redirectUri,scope:t.scope,code_challenge:r.challenge,code_challenge_method:"S256",state:r.state}),o=`${t.authorizeUrl}?${n}`;e.output(`Open: ${o}`),e.openFn(o);let i=await Ce(e.inputFn),[s,p]=i.split("#",2);if(!s||!Oe(p,r.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:p,redirect_uri:t.redirectUri,code_verifier:r.verifier})});return z(await S(u,"Claude OAuth token exchange"),e)}async function Ue(e){let t=C["openai-codex"],r=await S(await e.fetchFn(`${t.issuer}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({client_id:t.clientId})}),"Codex device authorization");if(!r.user_code||!r.device_auth_id)throw new Error("Codex device authorization returned incomplete data");let n=`${t.issuer}/codex/device`;e.output(`Open: ${n}`),e.output(`Code: ${r.user_code}`),e.openFn(n);let o=Math.max(3,Number(r.interval||5)),i;for(let p=0;p<Math.ceil(900/o);p+=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:r.device_auth_id,user_code:r.user_code})});if(u.ok){i=await S(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:D({grant_type:"authorization_code",code:i.authorization_code,redirect_uri:`${t.issuer}/deviceauth/callback`,client_id:t.clientId,code_verifier:i.code_verifier})});return z(await S(s,"Codex OAuth token exchange"),e)}function I(e){let t=new URL(String(e)),r=t.hostname.toLowerCase();if(t.protocol!=="https:"||r!=="x.ai"&&!r.endsWith(".x.ai"))throw new Error("xAI OAuth discovery returned an untrusted endpoint");return t.toString()}async function Re(e){let t=C["xai-oauth"],r=await S(await e.fetchFn(t.discoveryUrl,{headers:{accept:"application/json"}}),"xAI OAuth discovery");I(r.authorization_endpoint);let n=I(r.token_endpoint),o=await S(await e.fetchFn(t.deviceUrl,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:D({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=I(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)),p=Math.ceil(Math.max(1,Number(o.expires_in||600))/s);for(let u=0;u<p;u+=1){let g=await e.fetchFn(n,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:D({grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:t.clientId,device_code:o.device_code})});if(g.ok){let P=await S(g,"xAI OAuth token exchange");return z(P,{...e,discovery:{authorization_endpoint:I(r.authorization_endpoint),token_endpoint:n}})}let h="";try{h=String((await g.json())?.error||"")}catch{}if(h==="slow_down")await e.sleepFn((s+1)*1e3);else if(h==="authorization_pending")await e.sleepFn(s*1e3);else throw new Error(`xAI OAuth token exchange failed (HTTP ${g.status}${h?`, ${h}`:""})`)}throw new Error("xAI device authorization timed out")}async function Z(e,t={}){let r=A(e),n={fetchFn:t.fetchFn||globalThis.fetch,inputFn:t.inputFn,sleepFn:t.sleepFn||(o=>new Promise(i=>setTimeout(i,o))),openFn:t.openFn||be,output:t.output||(o=>process.stdout.write(`${o}
4
+ `)),now:t.now,pkce:t.pkce};return r==="anthropic-oauth"?Pe(n):r==="openai-codex"?Ue(n):Re(n)}var Y=Object.freeze({openrouter:{model:"openrouter/auto"},openai:{model:"gpt-4.1-mini"},xai:{model:"grok-4.5"},deepseek:{model:"deepseek-chat"},gemini:{model:"gemini-2.5-flash"},custom:{model:""}});function M(e,t){let r=e.indexOf(t);return r>=0&&e[r+1]?e[r+1]:""}async function je(){let e="";for await(let t of process.stdin)e+=t;return e.trim()}function $e(e="API key: "){if(!process.stdin.isTTY||!process.stdin.setRawMode)throw new Error("non-interactive API-key input requires --stdin");return process.stdout.write(e),new Promise((t,r)=>{let n="",o=()=>{process.stdin.off("data",i),process.stdin.setRawMode(!1),process.stdin.pause(),process.stdout.write(`
5
+ `)},i=s=>{let p=String(s);for(let u of p){if(u==="\r"||u===`
6
+ `){o(),t(n.trim());return}if(u===""){o(),r(new Error("cancelled"));return}u==="\x7F"||u==="\b"?n=n.slice(0,-1):n+=u}};process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",i)})}function N(e,t,{baseUrl:r=""}={}){if(!t)throw new Error(`${e} provider requires --model`);let n={backend:"standalone",provider:e,model:t};if(e==="custom"){if(!r)throw new Error("custom provider requires --base-url");n.baseUrl=r}return n}function Q(e,t,r={}){return W(N(e,t,r))}function Ie(e){process.stdout.write(`storage: ${e.storage}
7
7
  `);let t=Object.entries(e.providers||{}),r=Object.entries(e.apiKeys||{});if(!t.length&&!r.length){process.stdout.write(`no credentials configured
8
8
  `);return}for(let[n,o]of t){let i=o.expiresAt?new Date(o.expiresAt).toISOString():"unknown";process.stdout.write(`${n}: ${o.loggedIn?"logged in":"missing"}, expires ${i}
9
9
  `)}for(let[n,o]of r)process.stdout.write(`${n}: API key ${o.configured?"configured":"missing"}
10
- `)}function Ue(){return["oracle auth, configure OAuth or API-key authentication",""," oracle auth login claude|codex|grok [--model MODEL] [--no-browser]"," oracle auth api-key PROVIDER [--model MODEL] [--base-url URL]",` printf '%s\\n' "$KEY" | oracle auth api-key PROVIDER --stdin`," oracle auth status [--json]"," oracle auth logout PROVIDER","","OAuth and API keys are additive. Select any compatible model with oracle model --provider PROVIDER --model MODEL."].join(`
11
- `)}var Ge={name:"auth",summary:"login with Claude, Codex, or Grok OAuth; store provider API keys",group:"read",usage:Ue(),async run(e){let t=[...e.argv],r=t.shift()||"status",n=X();try{if(r==="status"){let o=n.status();return t.includes("--json")?process.stdout.write(`${JSON.stringify(o,null,2)}
12
- `):Ce(o),0}if(r==="login"){let o=t.find(c=>!c.startsWith("-"));if(!o)throw new Error("usage: oracle auth login claude|codex|grok");let i=q(o),s=M(t,"--model")||i.model;N(i.id,s);let l=await G(i.id,{openFn:t.includes("--no-browser")?()=>!1:void 0});return await n.withLock(async()=>{let c=n.get(i.id);n.set(i.id,l);try{Y(i.id,s)}catch(h){throw c?n.set(i.id,c):n.remove(i.id),h}}),process.stdout.write(`${i.id}: logged in, stored in ${n.storage}
13
- `),0}if(r==="api-key"){let o=String(t.find(c=>!c.startsWith("-"))||"").trim().toLowerCase();if(!o)throw new Error("usage: oracle auth api-key PROVIDER [--stdin]");if(!Object.hasOwn(Z,o))throw new Error(`unsupported API-key provider: ${o}`);let i=M(t,"--model")||Z[o].model,s=M(t,"--base-url");N(o,i,{baseUrl:s});let l=t.includes("--stdin")?await be():await Pe();return await n.withLock(async()=>{let c=n.getApiKey(o);n.setApiKey(o,l);try{Y(o,i,{baseUrl:s})}catch(h){throw c?n.setApiKey(o,c):n.removeApiKey(o),h}}),process.stdout.write(`${o}: API key configured in ${n.storage}
14
- `),0}if(r==="logout"){let o=String(t.find(l=>!l.startsWith("-"))||"").trim().toLowerCase();if(!o)throw new Error("usage: oracle auth logout PROVIDER");let i=!1;try{i=n.remove(_(o))}catch{}let s=n.removeApiKey(o);if(!i&&!s)throw new Error(`${o}: no local credential found`);return process.stdout.write(`${o}: local credential removed
10
+ `)}function Le(){return["oracle auth, configure OAuth or API-key authentication",""," oracle auth login claude|codex|grok [--model MODEL] [--no-browser]"," oracle auth api-key PROVIDER [--model MODEL] [--base-url URL]",` printf '%s\\n' "$KEY" | oracle auth api-key PROVIDER --stdin`," oracle auth status [--json]"," oracle auth logout PROVIDER","","OAuth and API keys are additive. Select any compatible model with oracle model --provider PROVIDER --model MODEL."].join(`
11
+ `)}var tt={name:"auth",summary:"login with Claude, Codex, or Grok OAuth; store provider API keys",group:"read",usage:Le(),async run(e){let t=[...e.argv],r=t.shift()||"status",n=G();try{if(r==="status"){let o=n.status();return t.includes("--json")?process.stdout.write(`${JSON.stringify(o,null,2)}
12
+ `):Ie(o),0}if(r==="login"){let o=t.find(u=>!u.startsWith("-"));if(!o)throw new Error("usage: oracle auth login claude|codex|grok");let i=V(o),s=M(t,"--model")||i.model;N(i.id,s);let p=await Z(i.id,{openFn:t.includes("--no-browser")?()=>!1:void 0});return await n.withLock(async()=>{let u=n.get(i.id);n.set(i.id,p);try{Q(i.id,s)}catch(g){throw u?n.set(i.id,u):n.remove(i.id),g}}),process.stdout.write(`${i.id}: logged in, stored in ${n.storage}
13
+ `),0}if(r==="api-key"){let o=String(t.find(u=>!u.startsWith("-"))||"").trim().toLowerCase();if(!o)throw new Error("usage: oracle auth api-key PROVIDER [--stdin]");if(!Object.hasOwn(Y,o))throw new Error(`unsupported API-key provider: ${o}`);let i=M(t,"--model")||Y[o].model,s=M(t,"--base-url");N(o,i,{baseUrl:s});let p=t.includes("--stdin")?await je():await $e();return await n.withLock(async()=>{let u=n.getApiKey(o);n.setApiKey(o,p);try{Q(o,i,{baseUrl:s})}catch(g){throw u?n.setApiKey(o,u):n.removeApiKey(o),g}}),process.stdout.write(`${o}: API key configured in ${n.storage}
14
+ `),0}if(r==="logout"){let o=String(t.find(p=>!p.startsWith("-"))||"").trim().toLowerCase();if(!o)throw new Error("usage: oracle auth logout PROVIDER");let i=!1;try{i=n.remove(A(o))}catch{}let s=n.removeApiKey(o);if(!i&&!s)throw new Error(`${o}: no local credential found`);return process.stdout.write(`${o}: local credential removed
15
15
  `),0}throw new Error(`unknown auth action: ${r}`)}catch(o){return process.stderr.write(`oracle auth: ${o.message}
16
- `),1}}};export{Ge as default};
16
+ `),1}}};export{tt as default};