import{n as e}from"./auth-Bz5dmZgR.js";import{fileURLToPath as t}from"node:url";import{spawn as n}from"node:child_process";import{createInterface as r}from"node:readline";const i={input:process.stdin,output:process.stdout,error:process.stderr,fetchImpl:globalThis.fetch,spawnImpl:n,readTokenImpl:e,sleep:e=>new Promise(t=>setTimeout(t,e))};async function a(e={},t={}){let n={...i,...t},a=s(e.port),c=`http://127.0.0.1:${a}`,h=await o(c,n.fetchImpl);if(!h&&e.autoStart!==!1)try{l(a,n),await u(c,3e4,n),h=!0}catch(e){n.error.write(`[aikit-proxy] ${m(e)}\n`)}else h||n.error.write(`[aikit-proxy] Daemon not running and autoStart=false
`);let g=n.readTokenImpl();if(!g){n.error.write(`[aikit-proxy] No token found at ~/.aikit/token
`);return}let _=r({input:n.input,crlfDelay:1/0}),v;for await(let e of _)if(e.trim())try{let t=await n.fetchImpl(`${c}/mcp`,{method:`POST`,headers:d(g,v),body:e}),r=t.headers.get(`mcp-session-id`);r&&(v=r);let i=await t.text();i&&f(n.output,i)}catch(t){f(n.output,p(e,t))}}async function o(e,t=globalThis.fetch){try{return(await t(`${e}/health`,{method:`GET`,signal:AbortSignal.timeout(2e3)})).ok}catch{return!1}}function s(e){if(typeof e==`number`&&Number.isFinite(e)&&e>0)return e;let t=Number.parseInt(process.env.AIKIT_PORT??``,10);return Number.isFinite(t)&&t>0?t:3210}function c(){return t(new URL(`./bin.js`,import.meta.url))}function l(e,t){let n=t.spawnImpl(process.execPath,[c(),`--transport`,`http`,`--port`,String(e)],{env:{...process.env,AIKIT_TRANSPORT:`http`,AIKIT_PORT:String(e)},detached:!0,stdio:[`ignore`,`ignore`,`pipe`]});n.stderr?.pipe(t.error),n.unref()}async function u(e,t,n){let r=Date.now();for(;Date.now()-r<t;){if(await o(e,n.fetchImpl))return;await n.sleep(200)}throw Error(`Daemon did not start within ${t}ms`)}function d(e,t){return{"Content-Type":`application/json`,Authorization:`Bearer ${e}`,...t?{"Mcp-Session-Id":t}:{}}}function f(e,t){e.write(t.endsWith(`
`)?t:`${t}\n`)}function p(e,t){let n=null;try{n=JSON.parse(e).id??null}catch{n=null}return JSON.stringify({jsonrpc:`2.0`,id:n,error:{code:-32603,message:`Proxy error: ${m(t)}`}})}function m(e){return e instanceof Error?e.message:`Unknown error`}export{o as isDaemonAlive,a as runProxy};