import{t as e}from"./subsystem-BQ1073Mu.js";import{Kl as t,Yl as n,d as r}from"./model-selection-p21GBPS6.js";import{at as i,ot as a}from"./reply-SaDCHPDQ.js";import{r as o}from"./prompt-style-DpAh867d.js";import{m as s}from"./openai-codex-model-default-B5TBE2IR.js";import{h as c}from"./auth-token-KE_i2bMo.js";import{n as l}from"./logging-DZNwCl5f.js";import{r as u,t as d}from"./oauth-tls-preflight-OT_XKQho.js";import{loginOpenAICodex as f}from"@mariozechner/pi-ai/oauth";import{intro as p,note as m,outro as h,spinner as g}from"@clack/prompts";const _=`Iv1.b507a08c87ecfe98`;function v(e){if(!e||typeof e!=`object`)throw Error(`Unexpected response from GitHub`);return e}async function y(e){let t=new URLSearchParams({client_id:_,scope:e.scope}),n=await fetch(`https://github.com/login/device/code`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/x-www-form-urlencoded`},body:t});if(!n.ok)throw Error(`GitHub device code failed: HTTP ${n.status}`);let r=v(await n.json());if(!r.device_code||!r.user_code||!r.verification_uri)throw Error(`GitHub device code response missing fields`);return r}async function b(e){let t=new URLSearchParams({client_id:_,device_code:e.deviceCode,grant_type:`urn:ietf:params:oauth:grant-type:device_code`});for(;Date.now()<e.expiresAt;){let n=await fetch(`https://github.com/login/oauth/access_token`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/x-www-form-urlencoded`},body:t});if(!n.ok)throw Error(`GitHub device token failed: HTTP ${n.status}`);let r=v(await n.json());if(`access_token`in r&&typeof r.access_token==`string`)return r.access_token;let i=`error`in r?r.error:`unknown`;if(i===`authorization_pending`){await new Promise(t=>setTimeout(t,e.intervalMs));continue}if(i===`slow_down`){await new Promise(t=>setTimeout(t,e.intervalMs+2e3));continue}throw i===`expired_token`?Error(`GitHub device code expired; run login again`):i===`access_denied`?Error(`GitHub login cancelled`):Error(`GitHub device flow error: ${i}`)}throw Error(`GitHub device code expired; run login again`)}async function x(e,r){if(!process.stdin.isTTY)throw Error(`github-copilot login requires an interactive TTY.`);p(o(`GitHub Copilot login`));let i=e.profileId?.trim()||`github-copilot:github`;n(void 0,{allowKeychainPrompt:!1}).profiles[i]&&!e.yes&&m(`Auth profile already exists: ${i}\nRe-running will overwrite it.`,o(`Existing credentials`));let a=g();a.start(`Requesting device code from GitHub...`);let u=await y({scope:`read:user`});a.stop(`Device code ready`),m([`Visit: ${u.verification_uri}`,`Code: ${u.user_code}`].join(`
`),o(`Authorize`));let d=Date.now()+u.expires_in*1e3,f=Math.max(1e3,u.interval*1e3),_=g();_.start(`Waiting for GitHub authorization...`);let v=await b({deviceCode:u.device_code,intervalMs:f,expiresAt:d});_.stop(`GitHub access token acquired`),t({profileId:i,credential:{type:`token`,provider:`github-copilot`,token:v}}),await s(e=>c(e,{provider:`github-copilot`,profileId:i,mode:`token`})),l(r),r.log(`Auth profile: ${i} (github-copilot/token)`),h(`Done`)}const S=e(`plugins`);function C(e){return a({config:e.config,workspaceDir:e.workspaceDir,logger:i(S)}).providers.map(e=>e.provider)}const w=e=>e.trim().length>0?void 0:`Required`;function T(e){let t=e.manualPromptMessage??`Paste the redirect URL`,n;return{onAuth:async({url:r})=>{if(e.isRemote){e.spin.stop(`OAuth URL ready`),e.runtime.log(`\nOpen this URL in your LOCAL browser:\n\n${r}\n`),n=e.prompter.text({message:t,validate:w}).then(e=>String(e));return}e.spin.update(e.localBrowserMessage),await e.openUrl(r),e.runtime.log(`Open: ${r}`)},onPrompt:async t=>{if(n)return n;let r=await e.prompter.text({message:t.message,placeholder:t.placeholder,validate:w});return String(r)}}}async function E(e){let{prompter:t,runtime:n,isRemote:r,openUrl:i,localBrowserMessage:a}=e,o=await u();if(!o.ok&&o.kind===`tls-cert`){let e=d(o);throw n.error(e),await t.note(e,`OAuth prerequisites`),Error(o.message)}await t.note(r?[`You are running in a remote/VPS environment.`,`A URL will be shown for you to open in your LOCAL browser.`,`After signing in, paste the redirect URL back here.`].join(`
`):[`Browser will open for OpenAI authentication.`,`If the callback doesn't auto-complete, paste the redirect URL.`,`OpenAI OAuth uses localhost:1455 for the callback.`].join(`
`),`OpenAI Codex OAuth`);let s=t.progress(`Starting OAuth flow…`);try{let{onAuth:e,onPrompt:o}=T({isRemote:r,prompter:t,runtime:n,spin:s,openUrl:i,localBrowserMessage:a??`Complete sign-in in browser…`}),c=await f({onAuth:e,onPrompt:o,onProgress:e=>s.update(e)});return s.stop(`OpenAI OAuth complete`),c??null}catch(e){throw s.stop(`OpenAI OAuth failed`),n.error(String(e)),await t.note(`Trouble with OAuth? See https://docs.openclaw.ai/start/faq`,`OAuth help`),e}}function D(e,t){let n=t?.trim();if(!n)return null;let i=r(n);return e.find(e=>r(e.id)===i)??e.find(e=>e.aliases?.some(e=>r(e)===i)??!1)??null}function O(e,t){let n=t?.trim();if(!n)return null;let r=n.toLowerCase();return e.auth.find(e=>e.id.toLowerCase()===r)??e.auth.find(e=>e.label.toLowerCase()===r)??null}function k(e){return!!(e&&typeof e==`object`&&!Array.isArray(e))}function A(e,t){if(!k(e)||!k(t))return t;let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];k(t)&&k(r)?n[e]=A(t,r):n[e]=r}return n}function j(e,t){let n={...e.agents?.defaults?.models};n[t]=n[t]??{};let r=e.agents?.defaults?.model;return{...e,agents:{...e.agents,defaults:{...e.agents?.defaults,models:n,model:{...r&&typeof r==`object`&&`fallbacks`in r?{fallbacks:r.fallbacks}:void 0,primary:t}}}}}export{E as a,x as c,D as i,A as n,T as o,O as r,C as s,j as t};
