#!/usr/bin/env node

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *--------------------------------------------------------------------------------------------*/
import __module from "module";
import __path from "path";
import __fs from "fs";
const __rootRequire = __module.createRequire(import.meta.url);
const __appPath = __fs.realpathSync(import.meta.dirname);
const __koffiEntrypoint = __path.join(__appPath, "koffi", "index.js");
const __koffiRequire = __fs.existsSync(__koffiEntrypoint)
    ? __module.createRequire(__koffiEntrypoint)
    : __rootRequire;
const require = (module) => {
    if (module === "koffi" && __fs.existsSync(__koffiEntrypoint)) {
        return __koffiRequire(__koffiEntrypoint);
    }
    return __rootRequire(module);
};
var ie=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});import Oe from"node:module";import{spawn as we}from"node:child_process";import{chmodSync as J,copyFileSync as Y,mkdirSync as Pe,readFileSync as B,realpathSync as Se,rmSync as R,statSync as ye,writeFileSync as V,writeSync as Le}from"node:fs";import{basename as C,dirname as Te,join as l,resolve as te,sep as k}from"node:path";import{createInterface as _e}from"node:readline";import*as re from"node:sea";import{fileURLToPath as ne,pathToFileURL as A}from"node:url";var ce=new Set;function M(e,t){let r=Object.create(null);if(e)for(let[i,n]of Object.entries(e))r[i]=n;let c=t??ce;return new Proxy(process.env,{get(i,n){if(typeof n=="string"){if(Object.hasOwn(r,n))return r[n];if(!c.has(n))return process.env[n]}},set(i,n,o){return r[n]=o,!0},has(i,n){return typeof n!="string"?!1:Object.hasOwn(r,n)?r[n]!==void 0:c.has(n)?!1:n in process.env},ownKeys(i){let n=new Set(Object.keys(process.env));for(let o of c)n.delete(o);for(let o of Object.keys(r))r[o]!==void 0?n.add(o):n.delete(o);return[...n]},getOwnPropertyDescriptor(i,n){if(typeof n!="string")return;let o;if(Object.hasOwn(r,n))o=r[n];else{if(c.has(n))return;o=process.env[n]}if(o!==void 0)return{value:o,writable:!0,enumerable:!0,configurable:!0}},deleteProperty(i,n){return r[n]=void 0,!0}})}var ae=new Set(["--server","--headless","--acp"]);function le(e){return e==="--prompt"||e.startsWith("--prompt=")||e==="-p"||e.startsWith("-p")&&e.length>2}function ue(e){return e.some(t=>ae.has(t)||le(t))}function H(e){return ue(e)}import{readdir as pe,access as fe,constants as de}from"node:fs/promises";import{join as p,basename as D}from"node:path";import{homedir as P}from"node:os";function N(){return process.env.XDG_CACHE_HOME||p(P(),".cache")}function F(){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 j(){let e=process.argv.indexOf("--prefer-version");if(!(e===-1||e+1>=process.argv.length))return process.argv[e+1]}function ge(){if(process.platform==="darwin")return p(P(),"Library","Caches","copilot");if(process.platform==="win32"){let e=process.env.LOCALAPPDATA||p(P(),".cache");return p(e,"copilot")}return p(N(),"copilot")}function W(){let e=[];return process.env.COPILOT_CACHE_HOME&&e.push(p(process.env.COPILOT_CACHE_HOME,"pkg")),e.push(p(ge(),"pkg")),e.push(p(N(),"copilot","pkg")),process.env.COPILOT_HOME&&e.push(p(process.env.COPILOT_HOME,"pkg")),e.push(p(P(),".copilot","pkg")),[...new Set(e)]}function U(e){let t=e.match(/^(\d+)\.(\d+)\.(\d+)/);if(t)return[Number(t[1]),Number(t[2]),Number(t[3])]}function me(e,t){let r=U(e),c=U(t);if(!r&&!c)return 0;if(!r)return-1;if(!c)return 1;for(let o=0;o<3;o++)if(r[o]!==c[o])return r[o]-c[o];let i=e.includes("-"),n=t.includes("-");return i!==n?i?-1:1:e.localeCompare(t)}async function G(e,...t){let r=[];for(let c of t){let i;try{i=await pe(c)}catch{continue}for(let n of i){let o=p(c,n);try{await fe(p(o,e),de.R_OK),r.push(o)}catch{continue}}}return r.sort((c,i)=>{let n=me(D(i),D(c));return n!==0?n:c.localeCompare(i)}),r}import{existsSync as ve}from"node:fs";import{fileURLToPath as be}from"node:url";function he(e){if(e.includes("<!DOCTYPE")||e.includes("<html")){let t=Math.min(e.indexOf("<!DOCTYPE")!==-1?e.indexOf("<!DOCTYPE"):1/0,e.indexOf("<html")!==-1?e.indexOf("<html"):1/0),r=e.substring(0,t).trim();return r?`${r} [HTML error page omitted]`:"[HTML error page omitted]"}return e}function K(e){let t;if(e instanceof Error)t=String(e);else if(typeof e=="object"&&e!==null)try{t=JSON.stringify(e)??"[object]"}catch{return"[object with circular reference]"}else t=String(e);return he(t)}var _=class{initialQueue=[];initialQueueResolvers=Promise.withResolvers();logWriter=null;writePromise=this.initialQueueResolvers.promise;setLogWriter(t){this.logWriter=t;for(let r of this.initialQueue)this.writePromise=this.logWriter.writeLog(r.method,r.message);this.initialQueue=[],this.initialQueueResolvers.resolve()}async flush(){await this.writePromise}async dispose(){await this.flush()}outputPath(){return this.logWriter?.outputPath()}logToLevel(t,r){this.logWriter?this.writePromise=this.logWriter.writeLog(t,r):this.initialQueue.push({method:t,message:r})}info(t){this.logToLevel("info",t)}debug(t){this.logToLevel("debug",t)}warning(t){this.logToLevel("warning",t)}error(t){this.logToLevel("error",t instanceof Error?t.message:t)}log(t){this.error(t)}isDebug(){return!1}shouldLog(t){return!0}notice(t){this.info(t instanceof Error?t.message:t)}startGroup(t,r){this.info(`--- Start of group: ${t} ---`)}endGroup(t){this.info("--- End of group ---")}},I=new _;var x="win32_native.dll",b;function Ee(){let e=[new URL(`./prebuilds/win32-${process.arch}/${x}`,import.meta.url),new URL(`../native/win32/prebuilds/win32-${process.arch}/${x}`,import.meta.url)];for(let t of e){let r=be(t);if(ve(r))return r}}function Q(){if(process.platform!=="win32")return;if(b!==void 0)return b??void 0;let e=Ee();if(!e){I.error(`Win32 native addon DLL not found at expected locations (prebuilds/win32-${process.arch}/${x}). Rebuild the CLI to include the prebuild.`),b=null;return}try{let r=ie("koffi").load(e),c=r.func("int enable_crash_reporting()"),i=r.func("int install_exception_filter()"),n=r.func("uint32_t get_error_mode()"),o=r.func("int enable_keep_alive()"),O=r.func("int disable_keep_alive()"),E=r.func("int is_keep_alive_enabled()");return b={enableCrashReporting:()=>c()!==0,installExceptionFilter:()=>i()!==0,getErrorMode:()=>n(),enableKeepAlive:()=>o()!==0,disableKeepAlive:()=>O()!==0,isKeepAliveEnabled:()=>E()!==0},b}catch(t){I.error(`Failed to load Win32 native addon: ${K(t)}`),b=null;return}}try{Oe.enableCompileCache?.()}catch{}var Ie=75;function q(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode=="function")try{process.stdin.setRawMode(!1)}catch{}if(process.stdout.isTTY)try{Le(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 se=Te(ne(import.meta.url)),X=re.isSea();process.report.reportOnFatalError=!0;process.report.excludeEnv=!0;if(process.platform==="win32")try{let e=Q();if(!e)throw new Error("Win32 native addon is unavailable");e.enableCrashReporting(),e.installExceptionFilter()}catch{}var S=process.argv.find(e=>C(e).startsWith("conpty_console_list_agent")),z=process.argv.find(e=>C(e)==="extension_bootstrap.mjs"),Z=z?te(z):void 0,ee=Z?.startsWith(te(se,"preloads")+k)?Z:void 0;if(S){let e=S.endsWith(".js")?S:S+".js";await import(A(e).href)}else if(ee)await import(A(ee).href);else if(process.env.COPILOT_SHUTDOWN_FLUSH){try{let{url:e,headers:t,body:r}=JSON.parse(process.env.COPILOT_SHUTDOWN_FLUSH);await fetch(e,{method:"POST",headers:t,body:r,signal:AbortSignal.timeout(3e4)})}catch{}process.exit(0)}else if(process.env.COPILOT_RUN_APP==="1"||H(process.argv.slice(2))){let e=l(se,"app.js"),t=j();if(X&&(F()||t)){let r=W().map(i=>l(i,"universal")),c=await G("app.js",...r);if(t){let i=c.find(n=>C(n)===t);i?e=l(i,"app.js"):process.stderr.write(`Warning: preferred version ${t} not found in package cache, using built-in version
`)}else c.length>0&&(e=l(c[0],"app.js"))}await import(A(e).href)}else{let t=function(){let s=process.env.COPILOT_HOME||l(process.env.HOME||process.env.USERPROFILE||"",".copilot");return l(s,"restart",`${e}.json`)},r=function(){let s=t();try{let a=B(s,"utf-8");return R(s,{force:!0}),JSON.parse(a)}catch{return}},c=function(){try{R(t(),{force:!0})}catch{}},i=function(){let s=process.env.COPILOT_HOME||l(process.env.HOME||process.env.USERPROFILE||"",".copilot");return l(s,"crash-context",`${e}.json`)},n=function(){try{let s=B(i(),"utf-8");return JSON.parse(s)}catch{return}},o=function(){try{R(i(),{force:!0})}catch{}},O=function(s,a){return new Promise(g=>{let f=_e({input:process.stdin,output:process.stdout}),u=s.toString(16).toUpperCase();if(process.stdout.write(`
*** Copilot exited unexpectedly (exit code ${s} = 0x${u}) ***
`),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.

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

\`\`\`
${s.stackTrace}
\`\`\``:"",""].filter(Boolean).join(`
`);if(V(l(u,"feedback.md"),m,{mode:384}),s.sessionFilePath&&E(s.sessionFilePath,f))try{let h=l(u,"events.jsonl");Y(s.sessionFilePath,h),J(h,384)}catch{}if(s.logFilePath&&E(s.logFilePath,f))try{let h=l(u,"process.log");Y(s.logFilePath,h),J(h,384)}catch{}process.stdout.write(`
Crash report saved to: ${u}${k}
`)}catch(g){process.stderr.write(`Failed to create crash report: ${String(g)}
`)}}w(process.argv.slice(2),process.cwd())}var xe,Re,Ae,ke,Ce,$e,Me,He,De;
