#!/usr/bin/env node

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *--------------------------------------------------------------------------------------------*/

import ue from"node:module";import{spawn as ge}from"node:child_process";import{chmodSync as W,copyFileSync as k,mkdirSync as me,readFileSync as B,realpathSync as he,rmSync as y,statSync as ve,writeFileSync as J,writeSync as Oe}from"node:fs";import{basename as x,dirname as Se,join as p,resolve as X,sep as R}from"node:path";import{createInterface as Pe}from"node:readline";import*as z from"node:sea";import{fileURLToPath as Z,pathToFileURL as _}from"node:url";var te=new Set;function U(e,o){let n=Object.create(null);if(e)for(let[i,r]of Object.entries(e))n[i]=r;let c=o??te;return new Proxy(process.env,{get(i,r){if(typeof r=="string"){if(Object.hasOwn(n,r))return n[r];if(!c.has(r))return process.env[r]}},set(i,r,s){return n[r]=s,!0},has(i,r){return typeof r!="string"?!1:Object.hasOwn(n,r)?n[r]!==void 0:c.has(r)?!1:r in process.env},ownKeys(i){let r=new Set(Object.keys(process.env));for(let s of c)r.delete(s);for(let s of Object.keys(n))n[s]!==void 0?r.add(s):r.delete(s);return[...r]},getOwnPropertyDescriptor(i,r){if(typeof r!="string")return;let s;if(Object.hasOwn(n,r))s=n[r];else{if(c.has(r))return;s=process.env[r]}if(s!==void 0)return{value:s,writable:!0,enumerable:!0,configurable:!0}},deleteProperty(i,r){return n[r]=void 0,!0}})}var ne=new Set(["--server","--headless","--acp"]);function se(e){return e==="--prompt"||e.startsWith("--prompt=")||e==="-p"||e.startsWith("-p")&&e.length>2}function oe(e){return e.some(o=>ne.has(o)||se(o))}function H(e){return oe(e)}import{readdir as ie,access as ce,constants as ae}from"node:fs/promises";import{join as f,basename as N}from"node:path";import{homedir as P}from"node:os";var F=process.env.XDG_CACHE_HOME||f(P(),".cache");function D(){if(process.argv.includes("--no-auto-update")||process.argv.includes("--prefer-version"))return!1;let e=process.env.COPILOT_AUTO_UPDATE;return!(e&&e.toLowerCase()==="false")}function M(){let e=process.argv.indexOf("--prefer-version");if(!(e===-1||e+1>=process.argv.length))return process.argv[e+1]}function pe(){if(process.platform==="darwin")return f(P(),"Library","Caches","copilot");if(process.platform==="win32"){let e=process.env.LOCALAPPDATA||f(P(),".cache");return f(e,"copilot")}return f(F,"copilot")}function G(){let e=[];return process.env.COPILOT_CACHE_HOME&&e.push(f(process.env.COPILOT_CACHE_HOME,"pkg")),e.push(f(pe(),"pkg")),e.push(f(F,"copilot","pkg")),process.env.COPILOT_HOME&&e.push(f(process.env.COPILOT_HOME,"pkg")),e.push(f(P(),".copilot","pkg")),[...new Set(e)]}function C(e){let o=e.match(/^(\d+)\.(\d+)\.(\d+)/);if(o)return[Number(o[1]),Number(o[2]),Number(o[3])]}function de(e,o){let n=C(e),c=C(o);if(!n&&!c)return 0;if(!n)return-1;if(!c)return 1;for(let s=0;s<3;s++)if(n[s]!==c[s])return n[s]-c[s];let i=e.includes("-"),r=o.includes("-");return i!==r?i?-1:1:e.localeCompare(o)}async function $(e,...o){let n=[];for(let c of o){let i;try{i=await ie(c)}catch{continue}for(let r of i){let s=f(c,r);try{await ce(f(s,e),ae.R_OK),n.push(s)}catch{continue}}}return n.sort((c,i)=>{let r=de(N(i),N(c));return r!==0?r:c.localeCompare(i)}),n}import{createRequire as fe}from"node:module";import{fileURLToPath as le}from"node:url";var O;function j(){if(process.platform!=="win32")return;if(O!==void 0)return O??void 0;let e=fe(import.meta.url),o=[new URL(`./prebuilds/win32-${process.arch}/win32.node`,import.meta.url),new URL(`../native/win32/prebuilds/win32-${process.arch}/win32.node`,import.meta.url)];for(let n of o){let c=le(n);try{return O=e(c),O}catch(i){if(i.code!=="MODULE_NOT_FOUND")throw i}}O=null}try{ue.enableCompileCache?.()}catch{}var be=75;function K(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode=="function")try{process.stdin.setRawMode(!1)}catch{}if(process.stdout.isTTY)try{Oe(1,"\x1B[<u\x1B[?1049h\x1B[?1049l\x1B[?1006l\x1B[?1003l\x1B[?1002l\x1B[?2004l\x1B[?1004l\x1B[?25h\x1B[?2026l"+(process.env.TERM!=="dumb"?"\x1B[23;2t":""))}catch{}}var ee=Se(Z(import.meta.url)),V=z.isSea();process.report.reportOnFatalError=!0;process.report.excludeEnv=!0;if(process.platform==="win32")try{let e=j();if(!e)throw new Error("Win32 native addon is unavailable");e.enableCrashReporting(),e.installExceptionFilter()}catch{}var b=process.argv.find(e=>x(e).startsWith("conpty_console_list_agent")),Q=process.argv.find(e=>x(e)==="extension_bootstrap.mjs"),Y=Q?X(Q):void 0,q=Y?.startsWith(X(ee,"preloads")+R)?Y:void 0;if(b){let e=b.endsWith(".js")?b:b+".js";await import(_(e).href)}else if(q)await import(_(q).href);else if(process.env.COPILOT_SHUTDOWN_FLUSH){try{let{url:e,headers:o,body:n}=JSON.parse(process.env.COPILOT_SHUTDOWN_FLUSH);await fetch(e,{method:"POST",headers:o,body:n,signal:AbortSignal.timeout(3e4)})}catch{}process.exit(0)}else if(process.env.COPILOT_RUN_APP==="1"||H(process.argv.slice(2))){let e=p(ee,"app.js"),o=M();if(V&&(D()||o)){let n=G().map(i=>p(i,"universal")),c=await $("app.js",...n);if(o){let i=c.find(r=>x(r)===o);i?e=p(i,"app.js"):process.stderr.write(`Warning: preferred version ${o} not found in package cache, using built-in version
`)}else c.length>0&&(e=p(c[0],"app.js"))}await import(_(e).href)}else{let o=function(){let t=process.env.COPILOT_HOME||p(process.env.HOME||process.env.USERPROFILE||"",".copilot");return p(t,"restart",`${e}.json`)},n=function(){let t=o();try{let a=B(t,"utf-8");return y(t,{force:!0}),JSON.parse(a)}catch{return}},c=function(){try{y(o(),{force:!0})}catch{}},i=function(){let t=process.env.COPILOT_HOME||p(process.env.HOME||process.env.USERPROFILE||"",".copilot");return p(t,"crash-context",`${e}.json`)},r=function(){try{let t=B(i(),"utf-8");return JSON.parse(t)}catch{return}},s=function(){try{y(i(),{force:!0})}catch{}},A=function(t,a){return new Promise(g=>{let l=Pe({input:process.stdin,output:process.stdout}),d=t.toString(16).toUpperCase();if(process.stdout.write(`
*** Copilot exited unexpectedly (exit code ${t} = 0x${d}) ***
`),a){let m=a.length>200?a.slice(0,200)+"\u2026":a;process.stdout.write(`Error: ${m}
`)}process.stdout.write(`
A crash report can be saved locally.
It will include session events, process logs, and error details.
The report may contain file paths and conversation context.

`),l.question("Save crash report? [y/N] ",m=>{l.close(),g(m.trim().toLowerCase()==="y")})})},I=function(t,a){try{let g=he(t);return g.startsWith(a+R)?ve(g).isFile():!1}catch{return!1}},S=function(t,a){let g=V?t:[...process.execArgv,Z(import.meta.url),...t],l=ge(process.execPath,g,{stdio:"inherit",cwd:a,env:U({COPILOT_RUN_APP:"1",COPILOT_LOADER_PID:e})});process.env.COPILOT_LOADER_DEBUG&&process.stderr.write(`[loader] spawned app child: pid=${l.pid} (loader pid=${e})
`);let d=u=>{try{l.kill(u)}catch{}},m=()=>d("SIGINT"),h=()=>d("SIGTERM"),T=()=>d("SIGHUP"),w=()=>d("SIGQUIT");process.on("SIGINT",m),process.on("SIGTERM",h),process.on("SIGHUP",T),process.on("SIGQUIT",w),l.on("error",u=>{process.off("SIGINT",m),process.off("SIGTERM",h),process.off("SIGHUP",T),process.off("SIGQUIT",w),c(),process.stderr.write(`Failed to start: ${u.message}
`),process.exit(1)}),l.on("exit",(u,L)=>{if(process.off("SIGINT",m),process.off("SIGTERM",h),process.off("SIGHUP",T),process.off("SIGQUIT",w),u===be){let v=n();if(v){let E=[...v.argv,"--resume",v.sessionId];S(E,v.cwd||a)}else S(t,a);return}if(c(),L)s(),K(),process.kill(process.pid,L);else if(u!==0){K();let v=r();v&&process.stdin.isTTY?A(u??1,v.lastError).then(async E=>{E&&await re(v,u??1),s(),process.exit(u??1)}).catch(()=>{s(),process.exit(u??1)}):(s(),process.exit(u??1))}else s(),process.exit(0)})};Ie=o,Te=n,we=c,Ee=i,ye=r,_e=s,Re=A,xe=I,Ae=S;let e=String(process.pid);async function re(t,a){try{let g=new Date().toISOString().replace(/[:.]/g,"-"),l=process.env.COPILOT_HOME||p(process.env.HOME||process.env.USERPROFILE||"",".copilot"),d=p(l,"crash-reports",`crash-${t.sessionId}-${g}`);me(d,{recursive:!0,mode:448}),J(p(d,"crash-context.json"),JSON.stringify(t,null,2),{mode:384});let m=["# Crash Report","",`**Exit code**: ${a}`,t.errorType?`**Error type**: ${t.errorType}`:"",t.lastError?`**Error**: ${t.lastError}`:"",`**Timestamp**: ${new Date().toISOString()}`,`**Session ID**: ${t.sessionId}`,`**Working directory**: ${t.cwd}`,t.stackTrace?`
## Stack Trace

\`\`\`
${t.stackTrace}
\`\`\``:"",""].filter(Boolean).join(`
`);if(J(p(d,"feedback.md"),m,{mode:384}),t.sessionFilePath&&I(t.sessionFilePath,l))try{let h=p(d,"events.jsonl");k(t.sessionFilePath,h),W(h,384)}catch{}if(t.logFilePath&&I(t.logFilePath,l))try{let h=p(d,"process.log");k(t.logFilePath,h),W(h,384)}catch{}process.stdout.write(`
Crash report saved to: ${d}${R}
`)}catch(g){process.stderr.write(`Failed to create crash report: ${String(g)}
`)}}S(process.argv.slice(2),process.cwd())}var Ie,Te,we,Ee,ye,_e,Re,xe,Ae;
