module.exports=[874533,(e,t,r)=>{t.exports=e.x("node:child_process",()=>require("node:child_process"))},902157,(e,t,r)=>{t.exports=e.x("node:fs",()=>require("node:fs"))},912714,(e,t,r)=>{t.exports=e.x("node:fs/promises",()=>require("node:fs/promises"))},81111,(e,t,r)=>{t.exports=e.x("node:stream",()=>require("node:stream"))},660526,(e,t,r)=>{t.exports=e.x("node:os",()=>require("node:os"))},761095,(e,t,r)=>{t.exports=e.x("node:net",()=>require("node:net"))},601457,(e,t,r)=>{t.exports=e.x("node:readline",()=>require("node:readline"))},828727,e=>{"use strict";var t=e.i(747909),r=e.i(174017),i=e.i(996250),n=e.i(759756),s=e.i(561916),a=e.i(174677),o=e.i(869741),l=e.i(316795),u=e.i(487718),d=e.i(995169),c=e.i(47587),h=e.i(666012),p=e.i(570101),f=e.i(626937),m=e.i(670909),g=e.i(193695);e.i(52474);var w=e.i(600220),y=e.i(666680),v=e.i(874533),b=e.i(902157),E=e.i(912714),x=e.i(750227),S=e.i(81111);let A=["on-request","untrusted"],C=["on-request","untrusted","on-failure","never"],O=["read-only","workspace-write"],P=["read-only","workspace-write","danger-full-access"];function R(){let e=_("CODEX_WEB_UI_UNSAFE_PERMISSIONS",!1),t=e?C:A,r=e?P:O,i=k(process.env.CODEX_WEB_UI_APPROVAL_POLICY)??"on-request",n=T(process.env.CODEX_WEB_UI_SANDBOX)??"workspace-write";if(!t.includes(i))throw I(500,`Configured approval policy requires unsafe permissions: ${i}`);if(!r.includes(n))throw I(500,`Configured sandbox requires unsafe permissions: ${n}`);return{defaultApprovalPolicy:i,defaultSandbox:n,locked:_("CODEX_WEB_UI_LOCK_PERMISSIONS",!1),unsafePermissions:e,allowedApprovalPolicies:t,allowedSandboxes:r}}function k(e){return"on-request"===e||"untrusted"===e||"on-failure"===e||"never"===e?e:null}function T(e){return"read-only"===e||"workspace-write"===e||"danger-full-access"===e?e:!e||"object"!=typeof e||Array.isArray(e)?null:"readOnly"===e.type?"read-only":"workspaceWrite"===e.type?"workspace-write":"dangerFullAccess"===e.type?"danger-full-access":null}function _(e,t){let r=process.env[e];return void 0===r?t:!!["1","true","yes","on"].includes(r.toLowerCase())||!["0","false","no","off"].includes(r.toLowerCase())&&t}function I(e,t){return Object.assign(Error(t),{statusCode:e})}let D="password",N="codex-web-ui",j=process.env.CODEX_WEB_UI_PASSWORD||"",$=process.env.CODEX_WEB_UI_AUTH_SECRET||j,q=j?null:"Set CODEX_WEB_UI_PASSWORD before exposing this server.",U={id:"password",email:null,name:"Password user",role:"admin"},L={authenticated:!1,mode:D,warning:q,user:null,tokenExpiresAt:null,get permissionPolicy(){return R()}};function M(e){let t,r,i=(t=e.headers.get("authorization")||"",r=/^Bearer\s+(.+)$/i.exec(t.trim()),r?.[1]?.trim()||"");if(!i)return null;let n=function(e){if(!$)return null;let t=e.split(".");if(3!==t.length)return null;let[r,i,n]=t;if(!X(n,H(`${r}.${i}`)))return null;let s=F(r),a=F(i);if("HS256"!==s.alg||"JWT"!==s.typ)return null;let o=G(a.exp);return a.iss!==N||a.sub!==U.id||!o||Date.now()>=1e3*o?null:{iss:N,sub:U.id,role:"string"==typeof a.role?a.role:U.role,iat:G(a.iat)??0,exp:o}}(i);return n?{expiresAt:1e3*n.exp,mode:D,user:{...U,role:n.role||U.role}}:null}function B(e){return{authenticated:!0,mode:e.mode,warning:q,user:e.user,tokenExpiresAt:e.expiresAt,permissionPolicy:R()}}function W(e){return Buffer.from(JSON.stringify(e),"utf8").toString("base64url")}function F(e){try{let t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return t&&"object"==typeof t&&!Array.isArray(t)?t:{}}catch{return{}}}function H(e){return y.default.createHmac("sha256",$).update(e).digest("base64url")}function X(e,t){let r=Buffer.from(e),i=Buffer.from(t);return r.length===i.length&&y.default.timingSafeEqual(r,i)}function G(e){let t="number"==typeof e?e:"string"==typeof e?Number(e):NaN;return Number.isFinite(t)?t:null}function z(e,t){return Object.assign(Error(t),{statusCode:e})}let J="/api/mcp/oauth/callback",K=new Map;function V(){let e=Number(process.env.CODEX_WEB_UI_MCP_OAUTH_CALLBACK_PORT||process.env.MCP_OAUTH_CALLBACK_PORT||String(33420));return!Number.isInteger(e)||e<1||e>65535?33420:e}function Q(e){return e===J||e.startsWith(`${J}/`)}async function Y(e){var t,r;let i,n=new URL(e.url);if(!Q(n.pathname))return Response.json({ok:!1,error:"Not found"},{status:404,headers:et()});if("GET"!==e.method)return Response.json({ok:!1,error:"Method not allowed"},{status:405,headers:et()});Z();let s=n.searchParams.get("state")||"",a=(t=n.pathname,r=s,`${t}
${r}`),o=K.get(a);if(K.delete(a),!o)return ee("MCP OAuth callback expired or was already used.",403);if(o.expiresAt<Date.now())return ee("MCP OAuth callback expired.",403);let l=new URL(o.localUrl);l.search=n.search;try{i=await fetch(l,{method:"GET",redirect:"manual",cache:"no-store"})}catch(t){let e=t instanceof Error?t.message:String(t);return ee(`Could not reach local Codex OAuth listener for ${o.serverName}: ${e.replace(/[&<>"']/g,e=>{switch(e){case"&":return"&amp;";case"<":return"&lt;";case">":return"&gt;";case'"':return"&quot;";default:return"&#39;"}})}`,502)}let u=et(),d=i.headers.get("content-type");d&&u.set("Content-Type",d);let c=i.headers.get("location");return c&&u.set("Location",c),new Response(await i.arrayBuffer(),{status:i.status,statusText:i.statusText,headers:u})}function Z(){let e=Date.now();for(let[t,r]of K)r.expiresAt<e&&K.delete(t)}function ee(e,t){return new Response(`<!doctype html><meta name="viewport" content="width=device-width, initial-scale=1"><title>MCP OAuth</title><body style="font-family: system-ui, sans-serif; padding: 2rem;"><h1>MCP OAuth</h1><p>${e}</p></body>`,{status:t,headers:{...Object.fromEntries(et()),"Content-Type":"text/html; charset=utf-8"}})}function et(){return new Headers({"Cache-Control":"no-store"})}var er=e.i(660526),ei=e.i(761095),en=e.i(601457);class es{socket;handlers;pid;closed;closeSent;buffer;fragmentedText;constructor(e,t){this.socket=e,this.handlers=t,this.pid=null,this.closed=!1,this.closeSent=!1,this.buffer=Buffer.alloc(0),this.fragmentedText=""}static connect(e){return new Promise((t,r)=>{let i=ei.default.createConnection(e.path),n=y.default.randomBytes(16).toString("base64"),s=y.default.createHash("sha1").update(`${n}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`).digest("base64"),a=Buffer.alloc(0),o=!1,l=null,u=t=>{if(!o){o=!0,i.destroy(),r(t);return}e.onError(t)};i.once("connect",()=>{i.write(`GET / HTTP/1.1\r
Host: localhost\r
Upgrade: websocket\r
Connection: Upgrade\r
Sec-WebSocket-Key: ${n}\r
Sec-WebSocket-Version: 13\r
\r
`)}),i.on("data",r=>{let n=Buffer.isBuffer(r)?r:Buffer.from(r);if(o)return void l?.receive(n);let d=(a=Buffer.concat([a,n])).indexOf("\r\n\r\n");if(-1===d)return;let c=a.subarray(0,d).toString("utf8"),h=function(e){let t={};for(let r of e.split("\r\n").slice(1)){let e=r.indexOf(":");-1!==e&&(t[r.slice(0,e).trim().toLowerCase()]=r.slice(e+1).trim())}return t}(c);if(!c.startsWith("HTTP/1.1 101")||h["sec-websocket-accept"]!==s)return void u(Error("Codex app-server Unix socket did not accept WebSocket upgrade"));o=!0,t(l=new es(i,e));let p=a.subarray(d+4);p.length>0&&l.receive(p)}),i.once("error",u),i.once("close",()=>{o?l?.markClosed():u(Error("Codex app-server Unix socket closed before WebSocket upgrade"))})})}async close(){this.closed||(this.sendFrame(8,Buffer.alloc(0)),this.closeSent=!0,await new Promise(e=>{let t=setTimeout(()=>{this.socket.destroy(),e()},1e3);this.socket.once("close",()=>{clearTimeout(t),e()})}))}isWritable(){return!this.closed&&this.socket.writable}write(e){this.sendFrame(1,Buffer.from(JSON.stringify(e),"utf8"))}receive(e){this.buffer=Buffer.concat([this.buffer,e]),this.parseFrames()}parseFrames(){for(;this.buffer.length>=2;){let e=this.buffer[0],t=this.buffer[1],r=!!(128&e),i=15&e,n=!!(128&t),s=127&t,a=2;if(126===s){if(this.buffer.length<4)return;s=this.buffer.readUInt16BE(2),a=4}else if(127===s){if(this.buffer.length<10)return;let e=this.buffer.readBigUInt64BE(2);if(e>BigInt(Number.MAX_SAFE_INTEGER)){this.handlers.onError(Error("Codex app-server WebSocket frame is too large")),this.socket.destroy();return}s=Number(e),a=10}let o=null;if(n){if(this.buffer.length<a+4)return;o=this.buffer.subarray(a,a+4),a+=4}if(this.buffer.length<a+s)return;let l=this.buffer.subarray(a,a+s);if(this.buffer=this.buffer.subarray(a+s),o){let e=Buffer.alloc(l.length);for(let t=0;t<l.length;t+=1)e[t]=l[t]^o[t%4];l=e}if(8===i){this.closeSent||this.sendFrame(8,Buffer.alloc(0)),this.socket.end();continue}if(9===i){this.sendFrame(10,l);continue}if(10!==i&&(1===i||0===i)&&(this.fragmentedText+=l.toString("utf8"),r)){let e=this.fragmentedText;this.fragmentedText="",this.handlers.onMessage(e)}}}sendFrame(e,t){let r=function(e,t){if(t<126)return Buffer.from([128|e,128|t]);if(t<65536){let r=Buffer.alloc(4);return r[0]=128|e,r[1]=254,r.writeUInt16BE(t,2),r}let r=Buffer.alloc(10);return r[0]=128|e,r[1]=255,r.writeBigUInt64BE(BigInt(t),2),r}(e,t.length),i=y.default.randomBytes(4),n=Buffer.alloc(t.length);for(let e=0;e<t.length;e+=1)n[e]=t[e]^i[e%4];this.socket.write(Buffer.concat([r,i,n]))}markClosed(){this.closed||(this.closed=!0,this.handlers.onClose())}}class ea{limit;items;constructor(e){this.limit=e,this.items=[]}push(e){this.items.push(e),this.items.length>this.limit&&this.items.splice(0,this.items.length-this.limit)}snapshot(){return[...this.items]}}class eo{clients=new Set;history=new ea(300);add(e,t){t.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}),t.write("\n");let r={close:()=>void 0,send:(e,r)=>{t.write(`event: ${e}
`),t.write(`data: ${JSON.stringify(r)}

`)}};this.clients.add(r),r.send("hello",{serverTime:new Date().toISOString(),history:this.history.snapshot()});let i=setInterval(()=>{t.destroyed||t.write(": keepalive\n\n")},25e3);e.on("close",()=>{clearInterval(i),this.clients.delete(r)})}stream(e){let t=new TextEncoder,r=null,i=null,n=()=>{i&&(clearInterval(i),i=null),r&&(this.clients.delete(r),r=null)};return new ReadableStream({start:s=>{r={close:n,send:(e,r)=>{s.enqueue(t.encode(`event: ${e}
`)),s.enqueue(t.encode(`data: ${JSON.stringify(r)}

`))}},this.clients.add(r),r.send("hello",{serverTime:new Date().toISOString(),history:this.history.snapshot()}),i=setInterval(()=>{s.enqueue(t.encode(": keepalive\n\n"))},25e3),e?.addEventListener("abort",n,{once:!0})},cancel:n})}broadcast(e,t){let r={type:e,payload:t,at:Date.now()};for(let e of(this.history.push(r),this.clients))e.send("message",r)}}class el{rootDir;sessionsDir;globalLogPath;indexPath;index=null;indexQueue=Promise.resolve();constructor(e){this.rootDir=e,this.sessionsDir=x.default.join(e,"sessions"),this.globalLogPath=x.default.join(e,"server.jsonl"),this.indexPath=x.default.join(e,"sessions.json")}async ensure(){await (0,E.mkdir)(this.sessionsDir,{recursive:!0}),await this.loadIndex()}async append(e){let t={at:new Date().toISOString(),...e};for(let e of(await this.ensure(),await (0,E.appendFile)(this.globalLogPath,`${JSON.stringify(t)}
`,"utf8"),function(e){let t=new Set,r=e.payload;if(e.threadId&&t.add(e.threadId),r&&"object"==typeof r&&!Array.isArray(r)){if(Array.isArray(r.threadIds))for(let e of r.threadIds)"string"==typeof e&&t.add(e);ep(r.params,t),ep(r.result,t)}return[...t]}(t)))await (0,E.appendFile)(this.threadLogPath(e),`${JSON.stringify({...t,threadId:e})}
`,"utf8")}async recordRpcRequest(e,t,r){await this.append({type:"rpc-request",id:t,method:e,payload:em({threadIds:eu(r),params:ed(r)})})}async recordRpcResponse(e,t,r,i){void 0!==r&&await this.recordThreadsFromResult(r),await this.append({type:"rpc-response",id:t,method:e,payload:em({threadIds:eu(r),result:ed(r),error:i})})}async recordNotification(e,t){if(t&&"object"==typeof t&&!Array.isArray(t)){let e=t.thread;ef(e)&&await this.recordThread(e)}await this.append({type:"notification",method:e,payload:em({params:t})})}async recordThreadsFromResult(e){if(!(!e||"object"!=typeof e||Array.isArray(e))&&(ef(e.thread)&&await this.recordThread(e.thread),Array.isArray(e.data)))for(let t of e.data)ef(t)&&await this.recordThread(t)}async recordThread(e){await this.ensure();let t=await this.loadIndex(),r=t.get(e.id),i={id:e.id,name:"string"==typeof e.name?e.name:r?.name??null,preview:"string"==typeof e.preview?e.preview:r?.preview??"",cwd:"string"==typeof e.cwd?e.cwd:r?.cwd??"",sessionId:"string"==typeof e.sessionId?e.sessionId:r?.sessionId??"",createdAt:"number"==typeof e.createdAt?e.createdAt:r?.createdAt??null,updatedAt:"number"==typeof e.updatedAt?e.updatedAt:r?.updatedAt??null,status:e.status??r?.status??null,logPath:this.threadLogPath(e.id),lastLoggedAt:new Date().toISOString()};if(t.set(e.id,i),!(0,b.existsSync)(this.threadLogPath(e.id))){let t={at:new Date().toISOString(),type:"server",threadId:e.id,method:"thread/indexed",payload:JSON.parse(JSON.stringify({thread:i}))};await (0,E.appendFile)(this.threadLogPath(e.id),`${JSON.stringify(t)}
`,"utf8")}await this.saveIndexQueued()}async deleteThreadLog(e){await this.ensure(),(await this.loadIndex()).delete(e),await this.saveIndexQueued();let t=this.threadLogPath(e);return!!(0,b.existsSync)(t)&&(await (0,E.unlink)(t),!0)}threadLogPath(e){return x.default.join(this.sessionsDir,`${e.replace(/[^a-zA-Z0-9._-]/g,"_")}.jsonl`)}async loadIndex(){if(this.index)return this.index;if(await (0,E.mkdir)(this.sessionsDir,{recursive:!0}),!(0,b.existsSync)(this.indexPath))return this.index=new Map,this.index;let e=JSON.parse(await (0,E.readFile)(this.indexPath,"utf8")||"{}");return this.index=new Map(Object.entries(e)),this.index}async saveIndexQueued(){this.indexQueue=this.indexQueue.then(async()=>{if(!this.index)return;let e=Object.fromEntries([...this.index.entries()]);await (0,E.writeFile)(this.indexPath,`${JSON.stringify(e,null,2)}
`,"utf8")}),await this.indexQueue}}function eu(e){let t=new Set;return function e(t,r,i){if(t&&"object"==typeof t&&!(i>8)){if(Array.isArray(t)){for(let n of t)e(n,r,i+1);return}for(let n of("string"==typeof t.threadId&&r.add(t.threadId),ef(t.thread)&&r.add(t.thread.id),Object.values(t)))e(n,r,i+1)}}(e,t,0),[...t]}function ed(e){return void 0===e?null:e&&"object"==typeof e?Array.isArray(e)?{type:"array",length:e.length,sample:ec(e)}:ef(e.thread)?{type:"object",keys:Object.keys(e),thread:eh(e.thread)}:Array.isArray(e.data)?{type:"object",keys:Object.keys(e),data:{type:"array",length:e.data.length,sample:ec(e.data)}}:{type:"object",keys:Object.keys(e).slice(0,30),threadId:"string"==typeof e.threadId?e.threadId:null}:e}function ec(e){return e.slice(0,5).map(e=>ef(e)?eh(e):e&&"object"==typeof e?Array.isArray(e)?{type:"array",length:e.length}:{type:"object",keys:Object.keys(e).slice(0,20)}:e)}function eh(e){return{id:e.id,name:"string"==typeof e.name?e.name:null,preview:"string"==typeof e.preview?e.preview:"",cwd:"string"==typeof e.cwd?e.cwd:"",sessionId:"string"==typeof e.sessionId?e.sessionId:"",createdAt:"number"==typeof e.createdAt?e.createdAt:null,updatedAt:"number"==typeof e.updatedAt?e.updatedAt:null,status:e.status??null,turnCount:Array.isArray(e.turns)?e.turns.length:null}}function ep(e,t){if(!(!e||"object"!=typeof e||Array.isArray(e))&&("string"==typeof e.threadId&&t.add(e.threadId),ef(e.thread)&&t.add(e.thread.id),Array.isArray(e.data)))for(let r of e.data)ef(r)&&t.add(r.id)}function ef(e){return!!(e&&"object"==typeof e&&!Array.isArray(e)&&"string"==typeof e.id)}function em(e){return JSON.parse(JSON.stringify(e??null))}let eg=x.default.resolve(process.cwd()),ew=er.default.homedir(),ey=new el(process.env.CODEX_WEB_UI_DATA_DIR||x.default.join(eg,"data")),ev=new eo,eb=new class{config;hub;logs;connection;nextId;pending;clientRequests;startPromise;stderrLines;status;constructor(e,t,r){this.config=e,this.hub=t,this.logs=r,this.connection=null,this.nextId=1,this.pending=new Map,this.clientRequests=new Map,this.startPromise=null,this.stderrLines=[],this.status={state:"stopped",command:e.command,cwd:e.cwd,pid:null,startedAt:null,exitedAt:null,exitCode:null,signal:null,error:null}}summary(){return{...this.status,stderr:[...this.stderrLines],config:this.config}}async start(){if(!this.connection||"running"!==this.status.state){if(this.startPromise)return this.startPromise;this.startPromise=this.startFresh();try{await this.startPromise}finally{this.startPromise=null}}}async restart(){await this.stop(),await this.start()}async stop(){this.connection&&await this.connection.close()}async request(e,t={},r={}){try{return await this.requestOnce(e,t,r)}catch(s){var i;let n;if(r.skipStart||(n=(i=s)instanceof Error?i.message:String(i),!/\b(ENOENT|ECONNREFUSED|EPIPE|socket closed|connection is unavailable|app-server is not running)\b/i.test(n)))throw s;return this.connection=null,await new Promise(e=>setTimeout(e,350)),this.requestOnce(e,t,r)}}async requestOnce(e,t={},r={}){if(r.skipStart||await this.start(),!this.connection?.isWritable())throw Error("codex app-server is not running");let i=this.nextId++,n=r.timeoutMs??12e4,s={id:i,method:e,params:t};return this.logs.recordRpcRequest(e,i,t),new Promise((t,r)=>{let a=setTimeout(()=>{this.pending.delete(String(i)),r(Error(`JSON-RPC request timed out: ${e}`))},n);this.pending.set(String(i),{method:e,resolve:t,reject:r,timer:a});try{this.write(s)}catch(e){clearTimeout(a),this.pending.delete(String(i)),r(e instanceof Error?e:Error(String(e)))}})}notify(e,t){this.write(void 0===t?{method:e}:{method:e,params:t})}pendingClientRequests(){return[...this.clientRequests.values()].sort((e,t)=>e.receivedAt-t.receivedAt)}respondClientRequest(e,t){let r=String(e),i=this.clientRequests.get(r);if(!i)throw Error("Client request is not pending");this.clientRequests.delete(r),this.write({jsonrpc:"2.0",id:i.id,result:t}),this.hub.broadcast("client-request-resolved",{id:i.id,method:i.method,result:t})}async startFresh(){this.setStatus({state:"starting",pid:null,startedAt:new Date().toISOString(),exitedAt:null,exitCode:null,signal:null,error:null});try{let e=this.config.appServerSocketPath?await this.connectUnixSocketAppServer():this.spawnOwnedAppServer();this.connection=e,this.setStatus({state:"starting",pid:e.pid}),await this.request("initialize",{clientInfo:{name:"codex-web-ui",version:"0.1.0"},capabilities:{experimentalApi:!0}},{skipStart:!0,timeoutMs:3e4}),this.notify("initialized"),this.setStatus({state:"running"})}catch(t){let e=t instanceof Error?t:Error(String(t));throw this.connection=null,this.setStatus({state:"error",pid:null,error:e.message}),e}}spawnOwnedAppServer(){let e=(0,v.spawn)(this.config.command,["app-server",...this.configArgs(),"--listen","stdio://"],{cwd:this.config.cwd,env:process.env,stdio:["pipe","pipe","pipe"]});return e.once("error",e=>this.handleConnectionError(e)),e.once("exit",(e,t)=>this.handleConnectionExit(0===e?null:`codex app-server exited with code ${e??"unknown"}`,e,t)),en.default.createInterface({input:e.stdout}).on("line",e=>this.handleMessageText(e)),en.default.createInterface({input:e.stderr}).on("line",e=>this.handleStderr(e)),{pid:e.pid??null,close:async()=>{null!==e.exitCode||e.killed||(e.kill("SIGTERM"),await new Promise(t=>{let r=setTimeout(()=>{null!==e.exitCode||e.killed||e.kill("SIGKILL"),t()},5e3);e.once("exit",()=>{clearTimeout(r),t()})}))},isWritable:()=>e.stdin.writable,write:t=>{e.stdin.write(`${JSON.stringify(t)}
`)}}}async connectUnixSocketAppServer(){return es.connect({path:this.config.appServerSocketPath,onClose:()=>this.handleConnectionExit("codex app-server socket closed",null,null),onError:e=>this.handleConnectionError(e),onMessage:e=>this.handleMessageText(e)})}configArgs(){let e=[];return this.config.model&&e.push("-c",`model="${this.config.model}"`),this.config.reasoningEffort&&e.push("-c",`model_reasoning_effort="${this.config.reasoningEffort}"`),this.config.fastMode||e.push("--disable","fast_mode"),e}write(e){if(!this.connection?.isWritable())throw Error("codex app-server connection is unavailable");this.connection.write(e)}handleMessageText(e){let t;try{t=JSON.parse(e)}catch{this.logs.append({type:"stdout",payload:e}),this.hub.broadcast("stdout",{line:e});return}if(!t||"object"!=typeof t)return void this.hub.broadcast("json",t);let r=t;if(Object.prototype.hasOwnProperty.call(r,"id")){let e=String(r.id),t=this.pending.get(e);if(t){if(clearTimeout(t.timer),this.pending.delete(e),this.logs.recordRpcResponse(t.method,r.id,r.result,r.error),this.hub.broadcast("rpc-response",{method:t.method,id:r.id,ok:!r.error}),r.error){let e=Error(r.error.message);e.data=r.error,t.reject(e)}else t.resolve(r.result);return}if(r.method){let e={id:r.id,method:r.method,params:r.params??{},receivedAt:Date.now()};this.clientRequests.set(String(r.id),e),this.logs.append({type:"client-request",id:r.id,method:r.method,payload:r.params}),this.hub.broadcast("client-request",e);return}}if(r.method){this.logs.recordNotification(r.method,r.params),this.hub.broadcast("notification",r);return}this.hub.broadcast("json",r)}handleStderr(e){let t={at:Date.now(),line:e};this.stderrLines.push(t),this.stderrLines.length>150&&this.stderrLines.splice(0,this.stderrLines.length-150),this.logs.append({type:"stderr",payload:e}),this.hub.broadcast("stderr",t)}rejectPending(e){for(let t of this.pending.values())clearTimeout(t.timer),t.reject(e);this.pending.clear()}setStatus(e){this.status={...this.status,...e},this.hub.broadcast("server-status",this.summary()),this.logs.append({type:"server",payload:this.summary()})}handleConnectionError(e){for(let t of(this.connection=null,this.setStatus({state:"error",error:e.message}),this.rejectPending(e),this.clientRequests.values()))this.hub.broadcast("client-request-resolved",{id:t.id,method:t.method,error:e.message});this.clientRequests.clear()}handleConnectionExit(e,t,r){for(let i of(this.setStatus({state:"exited",pid:null,exitedAt:new Date().toISOString(),exitCode:t,signal:r,error:e}),this.connection=null,this.rejectPending(Error(e??"codex app-server exited")),this.clientRequests.values()))this.hub.broadcast("client-request-resolved",{id:i.id,method:i.method,error:e??"codex app-server exited"});this.clientRequests.clear()}}({command:process.env.CODEX_COMMAND||"codex",cwd:process.env.CODEX_CWD||eg,model:process.env.CODEX_MODEL||"gpt-5.5",reasoningEffort:process.env.CODEX_REASONING_EFFORT||"high",fastMode:"0"!==process.env.CODEX_FAST_MODE,appServerSocketPath:process.env.CODEX_APP_SERVER_SOCKET||""},ev,ey),eE=null;async function ex(){return eE??=ey.ensure(),await eE,{bridge:eb,hub:ev,logs:ey}}function eS(){return process.env.CODEX_CONFIG_PATH?x.default.resolve(process.env.CODEX_CONFIG_PATH):x.default.join(process.env.CODEX_HOME||x.default.join(ew,".codex"),"config.toml")}async function eA(e){let t=function(e){let t="string"==typeof e?e.trim():"";if(!/^[A-Za-z0-9_-]{1,80}$/.test(t))throw Error("MCP server name must be 1-80 letters, numbers, dashes, or underscores");return t}(e.name),r=function(e){let t,r,i="string"==typeof e?e.trim():"";try{r=new URL(i)}catch{throw Error("Enter a valid MCP server URL")}if("http:"!==r.protocol&&"https:"!==r.protocol)throw Error("MCP server URL must use http or https");if(r.username||r.password)throw Error("Put MCP credentials in the bearer token field, not the URL");if("http:"===r.protocol&&!("localhost"===(t=r.hostname.toLowerCase().replace(/^\[|\]$/g,""))||"0.0.0.0"===t||"::1"===t||t.startsWith("127.")))throw Error("Plain HTTP MCP servers must be localhost or loopback");return r.toString()}(e.url),i=eS(),{text:n}=function(e,t){let r=e.split(/\r?\n/),i=[],n=[],s=!1;for(let e of r){var a;a=e,/^\s*\[[^\]]+\]\s*$/.test(a)&&(s=e.trim().replace(/^\[|\]$/g,"").replace(/"([^"]+)"/g,"$1")===`mcp_servers.${t}`),s?n.push(e):i.push(e)}return{text:i.join("\n"),block:n.length?n.join("\n"):null}}(await (0,E.readFile)(i,"utf8").catch(e=>{if("ENOENT"===e.code)return"";throw e}),t),s=`[mcp_servers.${t}]
url = "${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`,a=`${n.trimEnd()}${n.trimEnd()?"\n\n":""}${s}
`;return await (0,E.mkdir)(x.default.dirname(i),{recursive:!0}),await (0,E.writeFile)(i,a,"utf8"),{configPath:i}}let eC={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".svg":"image/svg+xml",".ico":"image/x-icon",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".avif":"image/avif",".pdf":"application/pdf",".mp4":"video/mp4",".m4v":"video/x-m4v",".webm":"video/webm",".mov":"video/quicktime",".ogv":"video/ogg",".ogg":"video/ogg",".avi":"video/x-msvideo",".mkv":"video/x-matroska",".3gp":"video/3gpp"};async function eO(e){var t;let r,i,n=new URL(e.url);if(Q(n.pathname))return Y(e);let s=(r=new Headers,(i=e.headers.get("origin")?.trim()||"")?function(e,t){try{let r=new URL(e.url),i=new URL(t),n=e.headers.get("x-forwarded-proto")||r.protocol.replace(":",""),s=e.headers.get("x-forwarded-host")||e.headers.get("host")||r.host;return i.protocol===`${n}:`&&i.host===s}catch{return!1}}(e,t=i)||(process.env.CODEX_WEB_UI_ALLOWED_ORIGINS||"").split(",").map(e=>e.trim()).filter(Boolean).some(e=>(function(e,t){try{let r=new URL(e),i=/^(https?):\/\/([^/:]+|\*)(?::(\*|\d+))?$/.exec(t.trim());if(!i)return e===t;let[,n,s,a]=i;if(r.protocol!==`${n}:`||"*"!==s&&s.toLowerCase()!==r.hostname.toLowerCase())return!1;return"*"===a||(a?a===r.port:!r.port)}catch{return e===t}})(t,e))?(r.set("Access-Control-Allow-Origin",i),r.set("Access-Control-Allow-Methods","GET, HEAD, POST, DELETE, OPTIONS"),r.set("Access-Control-Allow-Headers","Authorization, Content-Type, X-File-Name"),r.set("Access-Control-Max-Age","600"),r.set("Vary","Origin"),{allowed:!0,headers:r}):{allowed:!1,headers:r}:{allowed:!0,headers:r});if("OPTIONS"===e.method)return s.allowed?e7(new Response(null,{status:204,headers:e8()}),s.headers):e5({ok:!1,error:"Origin is not allowed"},403,s.headers);if(!s.allowed)return e5({ok:!1,error:"Origin is not allowed"},403,s.headers);let a=Date.now(),{logs:o}=await ex();try{let t=await eP(e,n,s.headers);return o.append({type:"server",method:"http/request",payload:{method:e.method,path:n.pathname,statusCode:t.status,durationMs:Date.now()-a}}),t}catch(r){let t=e5({ok:!1,error:r.message||"Internal server error",data:r.data},r.statusCode||500,s.headers);return o.append({type:"server",method:"http/request",payload:{method:e.method,path:n.pathname,statusCode:t.status,durationMs:Date.now()-a}}),t}}async function eP(e,t,r){let{bridge:i,hub:n,logs:s}=await ex(),a=t.pathname;if("/api/login"===a&&"POST"===e.method)return e5({ok:!0,...function(e){var t;if(t="string"==typeof e?e:"",!(j&&X(t,j)))throw z(401,"Invalid password");let{token:r,expiresAt:i}=function(e){var t;let r,i,n;if(!$)throw z(500,"CODEX_WEB_UI_PASSWORD is required before login is available.");let s=Math.floor(Date.now()/1e3),a=s+Math.floor(14400);return{token:(t={iss:N,sub:e.id,role:e.role,iat:s,exp:a},r=W({alg:"HS256",typ:"JWT"}),i=W(t),n=H(`${r}.${i}`),`${r}.${i}.${n}`),expiresAt:1e3*a}}(U);return{token:r,expiresAt:i,...B({expiresAt:i,mode:D,user:U})}}((await e1(e)).password)},200,r);if("/api/logout"===a&&"POST"===e.method)return e5({ok:!0},200,r);if("/api/auth"===a&&"GET"===e.method){let t;return e5({ok:!0,...(t=M(e))?B(t):L},200,r)}if(!M(e))return e5({ok:!1,error:"Unauthorized"},401,r);if("/api/status"===a&&"GET"===e.method)return e5({ok:!0,status:i.summary()},200,r);if("/api/events"===a&&"GET"===e.method)return i.start().catch(e=>{n.broadcast("server-status",i.summary()),n.broadcast("stderr",{at:Date.now(),line:e.message})}),e7(new Response(n.stream(e.signal),{status:200,headers:{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}}),r);if("/api/rpc"===a&&"POST"===e.method){let t=await e1(e);if("string"!=typeof t.method)return e5({ok:!1,error:"Missing JSON-RPC method"},400,r);let n=function(e,t){var r,i;if(!t||"object"!=typeof t||Array.isArray(t)||"thread/start"!==(r=e)&&"thread/resume"!==r&&"thread/fork"!==r&&"turn/start"!==r)return t;let n=R(),s={...t},a=k(s.approvalPolicy),o=T(s.sandbox)??T(s.sandboxPolicy),l=n.locked?n.defaultApprovalPolicy:function(e,t){if(!t.allowedApprovalPolicies.includes(e))throw I(403,`Approval policy requires unsafe permissions: ${e}`);return e}(a??n.defaultApprovalPolicy,n),u=n.locked?n.defaultSandbox:function(e,t){if(!t.allowedSandboxes.includes(e))throw I(403,`Sandbox requires --unsafe-permissions: ${e}`);return e}(o??n.defaultSandbox,n);return("turn/start"===e||"thread/start"===e)&&(s.approvalPolicy=l),"turn/start"===e?(s.sandboxPolicy="danger-full-access"===(i=u)?{type:"dangerFullAccess"}:"read-only"===i?{type:"readOnly"}:{type:"workspaceWrite"},delete s.sandbox):(s.sandbox=u,delete s.sandboxPolicy),s}(t.method,t.params??{});return e5({ok:!0,result:await i.request(t.method,n)},200,r)}if("/api/mcp/servers"===a&&"GET"===e.method)return e5({ok:!0,mcp:await eI()},200,r);if("/api/mcp/servers"===a&&"POST"===e.method){let t=await e1(e);return await eA({name:t.name,url:t.url}),e5({ok:!0,mcp:await eT()},200,r)}if("/api/mcp/servers/oauth/login"===a&&"POST"===e.method){let t=await e1(e),n="string"==typeof t.name?t.name.trim():"";if(!n)return e5({ok:!1,error:"Missing MCP server name"},400,r);await e_(e);let s=e4(await i.request("mcpServer/oauth/login",{name:n})),a="string"==typeof s.authorization_url?s.authorization_url:"string"==typeof s.authorizationUrl?s.authorizationUrl:"";return a?(!function(e,t){var r,i;Z();let n=new URL(t),s=n.searchParams.get("redirect_uri"),a=n.searchParams.get("state");if(!s||!a)throw Error("Codex MCP OAuth authorization URL is missing redirect_uri or state");let o=new URL(s);if(!o.pathname.startsWith(`${J}/`))throw Error("Codex MCP OAuth callback URL was not configured for the Web UI relay");let l=V();K.set((r=o.pathname,i=a,`${r}
${i}`),{serverName:e,path:o.pathname,state:a,localUrl:`http://127.0.0.1:${l}${o.pathname}`,expiresAt:Date.now()+6e5})}(n,a),e5({ok:!0,authorizationUrl:a},200,r)):e5({ok:!1,error:"Codex did not return an MCP OAuth authorization URL"},502,r)}if("/api/mcp/servers/reload"===a&&"POST"===e.method)return e5({ok:!0,mcp:await eT()},200,r);if("/api/client-requests"===a&&"GET"===e.method)return e5({ok:!0,requests:i.pendingClientRequests()},200,r);if("/api/client-requests/respond"===a&&"POST"===e.method){let t=await e1(e),n="string"==typeof t.id||"number"==typeof t.id?t.id:null;return null===n?e5({ok:!1,error:"Missing client request id"},400,r):(i.respondClientRequest(n,t.result??{}),e5({ok:!0},200,r))}if("/api/uploads"===a&&"POST"===e.method)return e5({ok:!0,attachment:await eN(e)},200,r);if("/api/transcribe"===a&&"POST"===e.method)return e5({ok:!0,transcript:await ej(e)},200,r);if("/api/files/view"===a&&"GET"===e.method)return e5({ok:!0,file:await eB(t.searchParams)},200,r);if("/api/files/download"===a&&("GET"===e.method||"HEAD"===e.method))return e7(await eW(t.searchParams,"HEAD"===e.method,!1,e.headers.get("range")),r);if("/api/files/raw"===a&&("GET"===e.method||"HEAD"===e.method))return e7(await eW(t.searchParams,"HEAD"===e.method,!0,e.headers.get("range")),r);if("/api/files/explore"===a&&"GET"===e.method)return e5({ok:!0,explorer:await e$(t.searchParams)},200,r);if("/api/skills"===a&&"GET"===e.method){let e=i.summary();return e5({ok:!0,skills:await eU("string"==typeof e.cwd?e.cwd:null)},200,r)}if("/api/server/restart"===a&&"POST"===e.method)return await i.restart(),e5({ok:!0,status:i.summary()},200,r);if("/api/app-server/recover"===a&&"POST"===e.method){let e=await e6();return await i.restart(),e5({ok:!0,output:e,status:i.summary()},200,r)}if("/api/server/stop"===a&&"POST"===e.method)return await i.stop(),e5({ok:!0,status:i.summary()},200,r);if("/api/repositories/browse"===a&&"GET"===e.method)return e5({ok:!0,browser:await eR(t.searchParams.get("path"))},200,r);if("/api/repositories/create"===a&&"POST"===e.method){let t=await e1(e);return e5({ok:!0,browser:await ek(t.parentPath,t.name)},200,r)}if(a.startsWith("/api/logs/")&&"DELETE"===e.method){let e=decodeURIComponent(a.slice(10));return e5({ok:!0,threadId:e,deleted:await s.deleteThreadLog(e)},200,r)}return e5({ok:!1,error:"Not found"},404,r)}async function eR(e){let t=ez(e);if(!(0,b.statSync)(t).isDirectory())throw Error("Path is not a directory");let r=(await (0,E.readdir)(t,{withFileTypes:!0})).filter(e=>e.isDirectory()||e.isSymbolicLink()).map(e=>{let r=x.default.join(t,e.name),i=e.isDirectory();try{i=(0,b.statSync)(r).isDirectory()}catch{i=!1}return i?{name:e.name,path:r,displayPath:eY(r),isGitRepo:eZ(r),hidden:e.name.startsWith(".")}:null}).filter(e=>!!e).sort((e,t)=>Number(e.hidden)-Number(t.hidden)||Number(t.isGitRepo)-Number(e.isGitRepo)||e.name.localeCompare(t.name));return{path:t,displayPath:eY(t),parentPath:x.default.dirname(t)===t?null:x.default.dirname(t),homePath:ew,isGitRepo:eZ(t),entries:r}}async function ek(e,t){let r=ez(e);if(!(0,b.statSync)(r).isDirectory())throw Error("Parent path is not a directory");let i="string"==typeof t?t.trim():"";if(!i||"."===i||".."===i||i.includes("/")||i.includes("\\"))throw Error("Enter a single folder name for the new repository");let n=x.default.join(r,i);if((0,b.existsSync)(n))throw Error("A folder already exists with that name");return await (0,E.mkdir)(n,{recursive:!1}),await e0(n),eR(n)}async function eT(){let{bridge:e}=await ex();return await e.request("config/mcpServer/reload",{}),eI()}async function e_(e){let t,{bridge:r}=await ex();await r.request("config/batchWrite",{edits:[{keyPath:"mcp_oauth_callback_port",value:V(),mergeStrategy:"replace"},{keyPath:"mcp_oauth_callback_url",value:(function(e){let t,r=new URL(e);if("https:"===r.protocol||"http:"===r.protocol&&("localhost"===(t=r.hostname.toLowerCase().replace(/^\[|\]$/g,""))||t.endsWith(".localhost")||"::1"===t||t.startsWith("127.")))return;let i=Error("MCP OAuth requires an HTTPS Web UI origin for remote or LAN browsers. Open the UI through an HTTPS tunnel/reverse proxy, or set CODEX_WEB_UI_PUBLIC_ORIGIN to that HTTPS origin.");throw i.statusCode=400,i}(t=function(e){let t=process.env.CODEX_WEB_UI_PUBLIC_ORIGIN?.trim();if(t)return t.replace(/\/+$/,"");let r=new URL(e.url),i=e.headers.get("x-forwarded-proto")||r.protocol.replace(":",""),n=e.headers.get("x-forwarded-host")||e.headers.get("host")||r.host;return`${i}://${n}`}(e)),`${t}${J}`),mergeStrategy:"replace"}],reloadUserConfig:!0})}async function eI(){let{bridge:e}=await ex(),t=e4(await e.request("mcpServerStatus/list",{detail:"toolsAndAuthOnly"})),r=Array.isArray(t.data)?t.data.map(eD):[];return{configPath:eS(),servers:r,nextCursor:"string"==typeof t.nextCursor?t.nextCursor:null}}function eD(e){let t=e4(e),r=e4(t.tools);return{name:"string"==typeof t.name?t.name:"unknown",authStatus:"string"==typeof t.authStatus?t.authStatus:"unsupported",tools:Object.keys(r).sort(),resources:Array.isArray(t.resources)?t.resources.length:0,resourceTemplates:Array.isArray(t.resourceTemplates)?t.resourceTemplates.length:0}}async function eN(e){let t=e.headers.get("x-file-name")||"",r=t?decodeURIComponent(t):"upload",i=eG(r),n=x.default.resolve(process.env.CODEX_WEB_UI_UPLOAD_DIR||x.default.join(eg,"data/uploads")),s=await e2(e,0x3200000);if(0===s.length)throw Error("Uploaded file is empty");await (0,E.mkdir)(n,{recursive:!0});let a=x.default.join(n,`${Date.now()}-${y.default.randomUUID()}-${i}`);return await (0,E.writeFile)(a,s,{flag:"wx"}),{path:a,displayPath:eY(a),name:r,size:s.length}}async function ej(e){let t=process.env.OPENAI_API_KEY||process.env.CODEX_WEB_UI_OPENAI_API_KEY||"";if(!t)throw Error("OPENAI_API_KEY is required for audio transcription.");let r=e.headers.get("x-file-name")||"",i=r?decodeURIComponent(r):"recording.webm",n=await e2(e,0x1900000);if(0===n.length)throw Error("Audio recording is empty.");let s=new FormData;s.set("model",process.env.CODEX_WEB_UI_TRANSCRIPTION_MODEL||"gpt-4o-mini-transcribe"),s.set("response_format","json"),s.set("file",new Blob([new Uint8Array(n)],{type:e.headers.get("content-type")||"audio/webm"}),eG(i));let a=await fetch("https://api.openai.com/v1/audio/transcriptions",{method:"POST",headers:{Authorization:`Bearer ${t}`},body:s}),o=e4(await a.json().catch(()=>({})));if(!a.ok){let e=e4(o.error);throw Error("string"==typeof e.message?e.message:`Transcription failed: ${a.status}`)}return"string"==typeof o.text?o.text.trim():""}async function e$(e){let t=await eJ(e.get("cwd")),r=function(e,t){var r,i;let n,s=t?.trim();if(!s)return e;let a=x.default.resolve(x.default.isAbsolute(s)?s:x.default.join(e,s));if(r=e,i=a,(n=x.default.relative(r,i))&&(n.startsWith("..")||x.default.isAbsolute(n)))throw Error("Explorer path must stay within the working directory");return a}(t,e.get("path"));if(!(0,b.statSync)(r).isDirectory())throw Error("Explorer path is not a directory");let i=await eK(t),n=new Map,s=eV(x.default.relative(t,r)),a=s?`${s}/`:"";for(let e of i){let i=eV(e);if(!i||i.split("/").some(eQ)||a&&!i.startsWith(a))continue;let s=a?i.slice(a.length):i;if(!s||s.includes("../"))continue;let[o,...l]=s.split("/");if(!o||eQ(o))continue;let u=x.default.join(r,o),d=0===l.length;n.set(o,eq(u,t,d?"file":"directory",!0))}for(let e of(await (0,E.readdir)(r,{withFileTypes:!0}))){if(eQ(e.name))continue;let i=x.default.join(r,e.name),s=e.isDirectory()?"directory":e.isFile()?"file":null;if(!s&&e.isSymbolicLink())try{let e=(0,b.statSync)(i);s=e.isDirectory()?"directory":e.isFile()?"file":null}catch{s=null}if(!s)continue;let a=n.get(e.name);n.set(e.name,{...eq(i,t,s,!!a?.tracked),tracked:!!a?.tracked})}let o=[...n.values()].sort((e,t)=>("directory"!==e.type)-("directory"!==t.type)||String(e.name).localeCompare(String(t.name),void 0,{sensitivity:"base"}));return{cwd:t,path:r,relativePath:eV(x.default.relative(t,r)),displayPath:eY(r),parentPath:r===t?null:x.default.dirname(r),trackedCount:i.length,entries:o}}function eq(e,t,r,i){let n=null,s=null;try{let t=(0,b.statSync)(e);n=t.isFile()?t.size:null,s=Math.round(t.mtimeMs)}catch{n=null,s=null}let a="file"===r?eX(e):null;return{name:x.default.basename(e),path:e,relativePath:eV(x.default.relative(t,e)),displayPath:eY(e),type:r,tracked:i,size:n,modifiedAt:s,kind:a||null,previewable:"file"===r&&!!a}}async function eU(e){let t=process.env.CODEX_HOME?x.default.resolve(process.env.CODEX_HOME):x.default.join(ew,".codex"),r=[{source:"workspace",path:e?x.default.join(e,".codex","skills"):""},{source:"project",path:x.default.join(eg,".codex","skills")},{source:"user",path:x.default.join(t,"skills")}].filter(e=>e.path),i=new Map;for(let e of r)for(let t of(await eL(e.path,e.source))){let e=String(t.name);i.has(e)||i.set(e,t)}return[...i.values()].sort((e,t)=>String(e.name).localeCompare(String(t.name),void 0,{sensitivity:"base"}))}async function eL(e,t){if(!(0,b.existsSync)(e))return[];let r=[];for(let i of(await (0,E.readdir)(e,{withFileTypes:!0}).catch(()=>[]))){if(!i.isDirectory())continue;let n=x.default.join(e,i.name);if(".system"===i.name){r.push(...await eL(n,"system"));continue}let s=x.default.join(n,"SKILL.md");(0,b.existsSync)(s)&&r.push({name:i.name,path:n,source:t,description:await eM(s)})}return r}async function eM(e){var t;let r=(await (0,E.readFile)(e,"utf8").catch(()=>"")).split(/\r?\n/).map(e=>e.trim()).find(e=>e&&!e.startsWith("#")&&!e.startsWith("---"));return r?(t=r.replace(/^description:\s*/i,"").replace(/^["']|["']$/g,"")).length<=220?t:`${t.slice(0,219)}...`:null}async function eB(e){let t=await eF(e.get("path"),e.get("cwd")),r=(0,b.statSync)(t);if(!r.isFile())throw Error("Referenced path is not a file");let i=eX(t);if("image"===i||"pdf"===i||"video"===i)return eH(t,r.size,i,!0);if(!i||r.size>2097152)return eH(t,r.size,i,!1);let n=await (0,E.readFile)(t,"utf8");return{...eH(t,r.size,i,!0),content:n}}async function eW(e,t,r=!1,i){let n=await eF(e.get("path"),e.get("cwd")),s=(0,b.statSync)(n);if(!s.isFile())return e5({ok:!1,error:"Referenced path is not a file"},404);let a=x.default.basename(n),o=x.default.extname(n).toLowerCase(),l=function(e,t){let r=/^bytes=(\d*)-(\d*)$/.exec(e.trim());if(!r||t<=0)return null;let[,i,n]=r;if(!i&&!n)return null;if(!i){let e=Number(n);return!Number.isSafeInteger(e)||e<=0?null:{start:Math.max(t-e,0),end:t-1}}let s=Number(i),a=n?Number(n):t-1;return!Number.isSafeInteger(s)||!Number.isSafeInteger(a)||s>a||s>=t?null:{start:s,end:Math.min(a,t-1)}}(i||"",s.size);if(i&&!l)return new Response(null,{status:416,headers:{"Content-Range":`bytes */${s.size}`,"Accept-Ranges":"bytes"}});let u=l?.start??0,d=l?.end??s.size-1,c=d-u+1,h=new Headers({"Content-Type":eC[o]||"application/octet-stream","Content-Length":String(c),"Content-Disposition":`${r?"inline":"attachment"}; filename="${a.replace(/"/g,"")}"; filename*=UTF-8''${encodeURIComponent(a)}`,"Cache-Control":"private, max-age=60","Accept-Ranges":"bytes",...l?{"Content-Range":`bytes ${u}-${d}/${s.size}`}:{}});return new Response(t?null:S.Readable.toWeb((0,b.createReadStream)(n,{start:u,end:d})),{status:l?206:200,headers:h})}async function eF(e,t){let r=e?.trim();if(!r)throw Error("Missing file path");if("~"===r)return ew;if(r.startsWith("~/"))return x.default.resolve(ew,r.slice(2));if(x.default.isAbsolute(r))return x.default.resolve(r);let{bridge:i}=await ex(),n=i.summary(),s=t?.trim()?x.default.resolve(t):n.cwd;return x.default.resolve("string"==typeof s?s:eg,r)}function eH(e,t,r,i){return{path:e,displayPath:eY(e),name:x.default.basename(e),extension:x.default.extname(e).slice(1).toLowerCase(),mimeType:eC[x.default.extname(e).toLowerCase()]||"application/octet-stream",size:t,kind:r||"download",previewable:i}}function eX(e){let t=x.default.extname(e).slice(1).toLowerCase();return["png","jpg","jpeg","gif","webp","bmp","avif","svg"].includes(t)?"image":"pdf"===t?"pdf":["mp4","m4v","webm","mov","ogv","ogg","avi","mkv","3gp"].includes(t)?"video":"json"===t?"json":["md","markdown","mdx"].includes(t)?"markdown":["txt","log","csv","yaml","yml","toml","ini","env"].includes(t)?"text":["js","jsx","ts","tsx","py","rs","go","java","kt","swift","c","h","cpp","hpp","cs","rb","php","sh","bash","zsh","fish","sql","css","scss","html","xml","vue","svelte","dockerfile"].includes(t)?"code":null}function eG(e){return x.default.basename(e||"upload").replace(/[^A-Za-z0-9._-]+/g,"_").replace(/^_+|_+$/g,"")||"upload"}function ez(e){let t="string"==typeof e&&e.trim()?e.trim():ew;return"~"===t?ew:t.startsWith("~/")?x.default.resolve(ew,t.slice(2)):x.default.resolve(x.default.isAbsolute(t)?t:x.default.join(ew,t))}async function eJ(e){let{bridge:t}=await ex(),r=t.summary(),i="string"==typeof r.cwd&&r.cwd?r.cwd:eg;return eF(e?.trim()||i,null)}async function eK(e){return new Promise(t=>{(0,v.execFile)("git",["-C",e,"ls-files","-z"],{maxBuffer:0xa00000},(e,r)=>{e?t([]):t(r.split("\0").filter(Boolean))})})}function eV(e){return e.split(x.default.sep).join("/").replace(/^\.\//,"")}function eQ(e){return e.startsWith(".")}function eY(e){let t=x.default.relative(ew,e);return t?t.startsWith("..")||x.default.isAbsolute(t)?e:`~/${t}`:"~"}function eZ(e){return(0,b.existsSync)(x.default.join(e,".git"))}async function e0(e){await new Promise((t,r)=>{(0,v.execFile)("git",["init","--",e],e=>{e?r(e):t()})})}async function e1(e){let t=(await e2(e,1e6)).toString("utf8").trim();return t?JSON.parse(t):{}}async function e2(e,t){let r=Number(e.headers.get("content-length")||"0");if(Number.isFinite(r)&&r>t)throw Error("Request body is too large");let i=Buffer.from(await e.arrayBuffer());if(i.length>t)throw Error("Request body is too large");return i}function e4(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function e5(e,t=200,r){return e7(Response.json(e,{status:t,headers:e8()}),r)}async function e6(){let e=process.env.CODEX_APP_SERVER_SOCKET;if(!e)throw Error("CODEX_APP_SERVER_SOCKET is not configured; this server owns its app-server connection.");let t=x.default.join(eg,"bin","codex-web-ui.js");return new Promise((r,i)=>{(0,v.execFile)(process.execPath,[t,"app-server","recover","--socket",e],{cwd:eg,env:process.env,timeout:12e3},(e,t,n)=>{let s=[t,n].filter(Boolean).join("\n").trim();e?i(Error(s||e.message)):r(s)})})}function e8(){return new Headers({"Cache-Control":"no-store"})}function e7(e,t){for(let[r,i]of t??[])e.headers.set(r,i);return e}e.s(["DELETE",0,function(e){return eO(e)},"GET",0,function(e){return eO(e)},"HEAD",0,function(e){return eO(e)},"OPTIONS",0,function(e){return eO(e)},"POST",0,function(e){return eO(e)},"dynamic",0,"force-dynamic","fetchCache",0,"force-no-store","revalidate",0,0,"runtime",0,"nodejs"],231658);var e3=e.i(231658);let e9=new t.AppRouteRouteModule({definition:{kind:r.RouteKind.APP_ROUTE,page:"/api/[[...path]]/route",pathname:"/api/[[...path]]",filename:"route",bundlePath:""},distDir:".next",relativeProjectDir:"",resolvedPagePath:"[project]/app/api/[[...path]]/route.ts",nextConfigOutput:"",userland:e3,...{}}),{workAsyncStorage:te,workUnitAsyncStorage:tt,serverHooks:tr}=e9;async function ti(e,t,i){i.requestMeta&&(0,n.setRequestMeta)(e,i.requestMeta),e9.isDev&&(0,n.addRequestMeta)(e,"devRequestTimingInternalsEnd",process.hrtime.bigint());let y="/api/[[...path]]/route";y=y.replace(/\/index$/,"")||"/";let v=await e9.prepare(e,t,{srcPage:y,multiZoneDraftMode:!1});if(!v)return t.statusCode=400,t.end("Bad Request"),null==i.waitUntil||i.waitUntil.call(i,Promise.resolve()),null;let{buildId:b,deploymentId:E,params:x,nextConfig:S,parsedUrl:A,isDraftMode:C,prerenderManifest:O,routerServerContext:P,isOnDemandRevalidate:R,revalidateOnlyGenerated:k,resolvedPathname:T,clientReferenceManifest:_,serverActionsManifest:I}=v,D=(0,o.normalizeAppPath)(y),N=!!(O.dynamicRoutes[D]||O.routes[T]),j=async()=>((null==P?void 0:P.render404)?await P.render404(e,t,A,!1):t.end("This page could not be found"),null);if(N&&!C){let e=!!O.routes[T],t=O.dynamicRoutes[D];if(t&&!1===t.fallback&&!e){if(S.adapterPath)return await j();throw new g.NoFallbackError}}let $=null;!N||e9.isDev||C||($="/index"===($=T)?"/":$);let q=!0===e9.isDev||!N,U=N&&!q;I&&_&&(0,a.setManifestsSingleton)({page:y,clientReferenceManifest:_,serverActionsManifest:I});let L=e.method||"GET",M=(0,s.getTracer)(),B=M.getActiveScopeSpan(),W=!!(null==P?void 0:P.isWrappedByNextServer),F=!!(0,n.getRequestMeta)(e,"minimalMode"),H=(0,n.getRequestMeta)(e,"incrementalCache")||await e9.getIncrementalCache(e,S,O,F);null==H||H.resetRequestCache(),globalThis.__incrementalCache=H;let X={params:x,previewProps:O.preview,renderOpts:{experimental:{authInterrupts:!!S.experimental.authInterrupts},cacheComponents:!!S.cacheComponents,supportsDynamicResponse:q,incrementalCache:H,cacheLifeProfiles:S.cacheLife,waitUntil:i.waitUntil,onClose:e=>{t.on("close",e)},onAfterTaskError:void 0,onInstrumentationRequestError:(t,r,i,n)=>e9.onRequestError(e,t,i,n,P)},sharedContext:{buildId:b,deploymentId:E}},G=new l.NodeNextRequest(e),z=new l.NodeNextResponse(t),J=u.NextRequestAdapter.fromNodeNextRequest(G,(0,u.signalFromNodeResponse)(t));try{let n,a=async e=>e9.handle(J,X).finally(()=>{if(!e)return;e.setAttributes({"http.status_code":t.statusCode,"next.rsc":!1});let r=M.getRootSpanAttributes();if(!r)return;if(r.get("next.span_type")!==d.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${r.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let i=r.get("next.route");if(i){let t=`${L} ${i}`;e.setAttributes({"next.route":i,"http.route":i,"next.span_name":t}),e.updateName(t),n&&n!==e&&(n.setAttribute("http.route",i),n.updateName(t))}else e.updateName(`${L} ${y}`)}),o=async n=>{var s,o;let l=async({previousCacheEntry:r})=>{try{if(!F&&R&&k&&!r)return t.statusCode=404,t.setHeader("x-nextjs-cache","REVALIDATED"),t.end("This page could not be found"),null;let s=await a(n);e.fetchMetrics=X.renderOpts.fetchMetrics;let o=X.renderOpts.pendingWaitUntil;o&&i.waitUntil&&(i.waitUntil(o),o=void 0);let l=X.renderOpts.collectedTags;if(!N)return await (0,h.sendResponse)(G,z,s,X.renderOpts.pendingWaitUntil),null;{let e=await s.blob(),t=(0,p.toNodeOutgoingHttpHeaders)(s.headers);l&&(t[m.NEXT_CACHE_TAGS_HEADER]=l),!t["content-type"]&&e.type&&(t["content-type"]=e.type);let r=void 0!==X.renderOpts.collectedRevalidate&&!(X.renderOpts.collectedRevalidate>=m.INFINITE_CACHE)&&X.renderOpts.collectedRevalidate,i=void 0===X.renderOpts.collectedExpire||X.renderOpts.collectedExpire>=m.INFINITE_CACHE?void 0:X.renderOpts.collectedExpire;return{value:{kind:w.CachedRouteKind.APP_ROUTE,status:s.status,body:Buffer.from(await e.arrayBuffer()),headers:t},cacheControl:{revalidate:r,expire:i}}}}catch(t){throw(null==r?void 0:r.isStale)&&await e9.onRequestError(e,t,{routerKind:"App Router",routePath:y,routeType:"route",revalidateReason:(0,c.getRevalidateReason)({isStaticGeneration:U,isOnDemandRevalidate:R})},!1,P),t}},u=await e9.handleResponse({req:e,nextConfig:S,cacheKey:$,routeKind:r.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:O,isRoutePPREnabled:!1,isOnDemandRevalidate:R,revalidateOnlyGenerated:k,responseGenerator:l,waitUntil:i.waitUntil,isMinimalMode:F});if(!N)return null;if((null==u||null==(s=u.value)?void 0:s.kind)!==w.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==u||null==(o=u.value)?void 0:o.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});F||t.setHeader("x-nextjs-cache",R?"REVALIDATED":u.isMiss?"MISS":u.isStale?"STALE":"HIT"),C&&t.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let d=(0,p.fromNodeOutgoingHttpHeaders)(u.value.headers);return F&&N||d.delete(m.NEXT_CACHE_TAGS_HEADER),!u.cacheControl||t.getHeader("Cache-Control")||d.get("Cache-Control")||d.set("Cache-Control",(0,f.getCacheControlHeader)(u.cacheControl)),await (0,h.sendResponse)(G,z,new Response(u.value.body,{headers:d,status:u.value.status||200})),null};W&&B?await o(B):(n=M.getActiveScopeSpan(),await M.withPropagatedContext(e.headers,()=>M.trace(d.BaseServerSpan.handleRequest,{spanName:`${L} ${y}`,kind:s.SpanKind.SERVER,attributes:{"http.method":L,"http.target":e.url}},o),void 0,!W))}catch(t){if(t instanceof g.NoFallbackError||await e9.onRequestError(e,t,{routerKind:"App Router",routePath:D,routeType:"route",revalidateReason:(0,c.getRevalidateReason)({isStaticGeneration:U,isOnDemandRevalidate:R})},!1,P),N)throw t;return await (0,h.sendResponse)(G,z,new Response(null,{status:500})),null}}e.s(["handler",0,ti,"patchFetch",0,function(){return(0,i.patchFetch)({workAsyncStorage:te,workUnitAsyncStorage:tt})},"routeModule",0,e9,"serverHooks",0,tr,"workAsyncStorage",0,te,"workUnitAsyncStorage",0,tt],828727)}];

//# sourceMappingURL=%5Broot-of-the-server%5D__0pym12l._.js.map