import{t as e}from"./rolldown-runtime-CNxR59P3.js";import{Us as t,c as n}from"./model-selection-R1b_J3k7.js";import r from"node:fs";import i from"node:path";import*as a from"@mariozechner/pi-coding-agent";function o(e){if(e.type===`api_key`){let t=typeof e.key==`string`?e.key.trim():``;return t?{type:`api_key`,key:t}:null}if(e.type===`token`){let t=typeof e.token==`string`?e.token.trim():``;return!t||typeof e.expires==`number`&&Number.isFinite(e.expires)&&Date.now()>=e.expires?null:{type:`api_key`,key:t}}if(e.type===`oauth`){let t=typeof e.access==`string`?e.access.trim():``,n=typeof e.refresh==`string`?e.refresh.trim():``;return!t||!n||!Number.isFinite(e.expires)||e.expires<=0?null:{type:`oauth`,access:t,refresh:n,expires:e.expires}}return null}function s(e){let t={};for(let r of Object.values(e.profiles)){let e=n(String(r.provider??``)).trim();if(!e||t[e])continue;let i=o(r);i&&(t[e]=i)}return t}var c=e({AuthStorage:()=>l,ModelRegistry:()=>u,discoverAuthStorage:()=>g,discoverModels:()=>_});const l=a.AuthStorage,u=a.ModelRegistry;function d(e){let t=JSON.stringify(e,null,2);return{withLock(e){let{result:n,next:r}=e(t);return typeof r==`string`&&(t=r),n}}}function f(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function p(e){if(process.env.OPENCLAW_AUTH_STORE_READONLY===`1`||!r.existsSync(e))return;let t;try{t=JSON.parse(r.readFileSync(e,`utf8`))}catch{return}if(!f(t))return;let n=!1;for(let[e,r]of Object.entries(t))f(r)&&r.type===`api_key`&&(delete t[e],n=!0);if(n){if(Object.keys(t).length===0){r.rmSync(e,{force:!0});return}r.writeFileSync(e,`${JSON.stringify(t,null,2)}\n`,`utf8`),r.chmodSync(e,384)}}function m(e,t,n){let r=e;if(typeof r.inMemory==`function`)return r.inMemory(n);let i=e;if(typeof i.fromStorage==`function`){let e=a.InMemoryAuthStorageBackend,t=typeof e==`function`?new e:d(n);return t.withLock(()=>({result:void 0,next:JSON.stringify(n,null,2)})),i.fromStorage(t)}let o=e,s=typeof o.create==`function`?o.create(t):new e(t);if(typeof s.setRuntimeApiKey==`function`)for(let[e,t]of Object.entries(n)){if(t.type===`api_key`){s.setRuntimeApiKey(e,t.key);continue}s.setRuntimeApiKey(e,t.access)}return s}function h(e){return s(t(e,{allowKeychainPrompt:!1}))}function g(e){let t=h(e),n=i.join(e,`auth.json`);return p(n),m(l,n,t)}function _(e,t){return new u(e,i.join(t,`models.json`))}export{_ as n,c as r,g as t};
