#!/usr/bin/env node

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

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

`),g.question("Save crash report? [y/N] ",a=>{g.close(),u(a.trim().toLowerCase()==="y")})})},b=function(t,p){try{let u=fe(t);return u.startsWith(p+R)?le(u).isFile():!1}catch{return!1}},S=function(t,p){let u=J?t:[...process.execArgv,X(import.meta.url),...t],g=pe(process.execPath,u,{stdio:"inherit",cwd:p,env:x({COPILOT_RUN_APP:"1",COPILOT_LOADER_PID:e})}),a=l=>{try{g.kill(l)}catch{}},O=()=>a("SIGINT"),m=()=>a("SIGTERM"),T=()=>a("SIGHUP"),w=()=>a("SIGQUIT");process.on("SIGINT",O),process.on("SIGTERM",m),process.on("SIGHUP",T),process.on("SIGQUIT",w),g.on("error",l=>{process.off("SIGINT",O),process.off("SIGTERM",m),process.off("SIGHUP",T),process.off("SIGQUIT",w),s(),process.stderr.write(`Failed to start: ${l.message}
`),process.exit(1)}),g.on("exit",(l,L)=>{if(process.off("SIGINT",O),process.off("SIGTERM",m),process.off("SIGHUP",T),process.off("SIGQUIT",w),l===he){let h=n();if(h){let E=[...h.argv,"--resume",h.sessionId];S(E,h.cwd||p)}else S(t,p);return}if(s(),L)o(),W(),process.kill(process.pid,L);else if(l!==0){W();let h=r();h&&process.stdin.isTTY?A(l??1,h.lastError).then(async E=>{E&&await Z(h,l??1),o(),process.exit(l??1)}).catch(()=>{o(),process.exit(l??1)}):(o(),process.exit(l??1))}else o(),process.exit(0)})};Oe=c,ve=n,Se=s,Pe=i,Ie=r,be=o,Te=A,we=b,Ee=S;let e=String(process.pid);async function Z(t,p){try{let u=new Date().toISOString().replace(/[:.]/g,"-"),g=process.env.COPILOT_HOME||d(process.env.HOME||process.env.USERPROFILE||"",".copilot"),a=d(g,"crash-reports",`crash-${t.sessionId}-${u}`);de(a,{recursive:!0,mode:448}),k(d(a,"crash-context.json"),JSON.stringify(t,null,2),{mode:384});let O=["# Crash Report","",`**Exit code**: ${p}`,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(k(d(a,"feedback.md"),O,{mode:384}),t.sessionFilePath&&b(t.sessionFilePath,g))try{let m=d(a,"events.jsonl");j(t.sessionFilePath,m),M(m,384)}catch{}if(t.logFilePath&&b(t.logFilePath,g))try{let m=d(a,"process.log");j(t.logFilePath,m),M(m,384)}catch{}process.stdout.write(`
Crash report saved to: ${a}${R}
`)}catch(u){process.stderr.write(`Failed to create crash report: ${String(u)}
`)}}S(process.argv.slice(2),process.cwd())}var Oe,ve,Se,Pe,Ie,be,Te,we,Ee;
