stably 4.6.3 → 4.6.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.mjs +1 -1
  2. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{config as e,parse as t}from"dotenv";import r,{resolve as n,dirname as o,join as s,sep as i,basename as a}from"path";import{Command as c}from"commander";import{Buffer as l}from"buffer";import u,{exec as d,execSync as p,spawn as f}from"child_process";import h from"process";import m,{existsSync as g,statSync as y,createReadStream as b,readFileSync as w,mkdirSync as v,writeFileSync as _,appendFileSync as E,openSync as I,readSync as T,closeSync as x,rmSync as S}from"fs";import{fileURLToPath as A,URL as C}from"url";import R,{tmpdir as P,constants as U}from"os";import"timers/promises";import k from"stream";import{debuglog as L,promisify as D,TextDecoder as O,TextEncoder as B}from"util";import{createSdkMcpServer as N,tool as $,query as M}from"@anthropic-ai/claude-agent-sdk";import{match as j}from"ts-pattern";import H,{randomUUID as F}from"crypto";import G from"picocolors";import{simpleGit as Y}from"simple-git";import W,{readFile as V,mkdir as z,writeFile as K,unlink as q,access as J,readdir as X,stat as Q,rm as Z,appendFile as ee}from"fs/promises";import{log as te,outro as re,spinner as ne,intro as oe,select as se,isCancel as ie}from"@clack/prompts";import{createInterface as ae}from"readline/promises";import ce,{z as le}from"zod";import ue from"open";import de from"http";import pe from"pino";import fe from"sonic-boom";import{z as he}from"zod/v3";import me from"ws";import{useState as ge,useRef as ye,useEffect as be,useCallback as we,useMemo as ve}from"react";import{jsx as _e,jsxs as Ee}from"react/jsx-runtime";import{createRequire as Ie}from"module";import{parseDocument as Te,parse as xe,stringify as Se}from"yaml";import{startTunnel as Ae}from"@stablyhq/runner-sdk";var Ce={cwdChanged:!1,newCwd:void 0,envFilesLoaded:[],envFileErrors:[]},Re=process.argv.findIndex(e=>"-C"===e||"--cwd"===e);if(-1!==Re&&process.argv[Re+1]){const e=process.argv[Re+1];process.chdir(e),Ce.cwdChanged=!0,Ce.newCwd=e,process.argv.splice(Re,2)}for(var Pe=[],Ue=0;Ue<process.argv.length;)if("--env-file"===process.argv[Ue]){const e=process.argv[Ue+1];e&&!e.startsWith("-")?(Pe.push(e),process.argv.splice(Ue,2)):Ue++}else Ue++;for(const t of Pe){const n=r.resolve(process.cwd(),t),o=e({path:n,override:!0,quiet:!0});if(o.error){const e=`warning: could not load env file: ${n} (${o.error.message})`;Ce.envFileErrors.push(e),process.stderr.write(`${e}\n`)}else Ce.envFilesLoaded.push(n)}var ke={detect:({env:e})=>Boolean(e.APPVEYOR),configuration({env:e}){const t=e.APPVEYOR_PULL_REQUEST_NUMBER,r=Boolean(t);return{name:"Appveyor",service:"appveyor",commit:e.APPVEYOR_REPO_COMMIT,tag:e.APPVEYOR_REPO_TAG_NAME,build:e.APPVEYOR_BUILD_NUMBER,buildUrl:`https://ci.appveyor.com/project/${e.APPVEYOR_PROJECT_SLUG}/build/${e.APPVEYOR_BUILD_VERSION}`,branch:e.APPVEYOR_REPO_BRANCH,job:e.APPVEYOR_JOB_NUMBER,jobUrl:`https://ci.appveyor.com/project/${e.APPVEYOR_PROJECT_SLUG}/build/job/${e.APPVEYOR_JOB_ID}`,pr:t,isPr:r,prBranch:e.APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH,slug:e.APPVEYOR_REPO_NAME,root:e.APPVEYOR_BUILD_FOLDER}}};function Le(e){return(/\d+(?!.*\d+)/.exec(e)||[])[0]}function De(e){return e?/^(?:refs\/heads\/)?(?<branch>.+)$/i.exec(e)[1]:void 0}var Oe={detect:({env:e})=>Boolean(e.BUILD_BUILDURI),configuration({env:e}){const t=e.SYSTEM_PULLREQUEST_PULLREQUESTID,r=Boolean(t);return{name:"Azure Pipelines",service:"azurePipelines",commit:e.BUILD_SOURCEVERSION,build:e.BUILD_BUILDNUMBER,branch:De(r?e.SYSTEM_PULLREQUEST_TARGETBRANCH:e.BUILD_SOURCEBRANCH),pr:t,isPr:r,prBranch:De(r?e.SYSTEM_PULLREQUEST_SOURCEBRANCH:void 0),root:e.BUILD_REPOSITORY_LOCALPATH}}},Be={detect:({env:e})=>Boolean(e.bamboo_agentId),configuration:({env:e})=>({name:"Bamboo",service:"bamboo",commit:e.bamboo_planRepository_1_revision,build:e.bamboo_buildNumber,buildUrl:e.bamboo_buildResultsUrl,branch:e.bamboo_planRepository_1_branchName,job:e.bamboo_buildKey,root:e.bamboo_build_working_directory})},Ne={detect:({env:e})=>Boolean(e.BITBUCKET_BUILD_NUMBER),configuration:({env:e})=>({name:"Bitbucket Pipelines",service:"bitbucket",commit:e.BITBUCKET_COMMIT,tag:e.BITBUCKET_TAG,build:e.BITBUCKET_BUILD_NUMBER,buildUrl:`https://bitbucket.org/${e.BITBUCKET_REPO_FULL_NAME}/addon/pipelines/home#!/results/${e.BITBUCKET_BUILD_NUMBER}`,branch:e.BITBUCKET_BRANCH,slug:e.BITBUCKET_REPO_FULL_NAME,root:e.BITBUCKET_CLONE_DIR})},$e={detect:({env:e})=>Boolean(e.BITRISE_IO),configuration({env:e}){const t="false"===e.BITRISE_PULL_REQUEST?void 0:e.BITRISE_PULL_REQUEST,r=Boolean(t);return{name:"Bitrise",service:"bitrise",commit:e.BITRISE_GIT_COMMIT,tag:e.BITRISE_GIT_TAG,build:e.BITRISE_BUILD_NUMBER,buildUrl:e.BITRISE_BUILD_URL,branch:r?e.BITRISEIO_GIT_BRANCH_DEST:e.BITRISE_GIT_BRANCH,pr:t,isPr:r,prBranch:r?e.BITRISE_GIT_BRANCH:void 0,slug:e.BITRISE_APP_SLUG}}},Me={detect:({env:e})=>Boolean(e.BUDDY_WORKSPACE_ID),configuration({env:e}){const t=Le(e.BUDDY_EXECUTION_PULL_REQUEST_ID),r=Boolean(t);return{name:"Buddy",service:"buddy",commit:e.BUDDY_EXECUTION_REVISION,tag:e.BUDDY_EXECUTION_TAG,build:e.BUDDY_EXECUTION_ID,buildUrl:e.BUDDY_EXECUTION_URL,branch:r?e.BUDDY_EXECUTION_PULL_REQUEST_HEAD_BRANCH:e.BUDDY_EXECUTION_BRANCH,pr:t,isPr:r,slug:e.BUDDY_REPO_SLUG}}},je="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function He(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Fe,Ge,Ye,We,Ve,ze,Ke,qe,Je={exports:{}};var Xe,Qe,Ze,et,tt,rt,nt,ot,st,it,at,ct,lt,ut,dt,pt={exports:{}},ft={};function ht(){if(ct)return at;ct=1;const e=r,t=function(){if(Ze)return Qe;Ze=1;const e=r,t=function(){if(qe)return Ke;qe=1;const e="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,t=r,n=e?";":":",o=function(){if(ze)return Ve;var e;function t(r,n,o){if("function"==typeof n&&(o=n,n={}),!o){if("function"!=typeof Promise)throw new TypeError("callback not provided");return new Promise(function(e,o){t(r,n||{},function(t,r){t?o(t):e(r)})})}e(r,n||{},function(e,t){e&&("EACCES"===e.code||n&&n.ignoreErrors)&&(e=null,t=!1),o(e,t)})}return ze=1,e="win32"===process.platform||je.TESTING_WINDOWS?function(){if(Ge)return Fe;Ge=1,Fe=r,r.sync=function(r,n){return t(e.statSync(r),r,n)};var e=m;function t(e,t,r){return!(!e.isSymbolicLink()&&!e.isFile())&&function(e,t){var r=void 0!==t.pathExt?t.pathExt:process.env.PATHEXT;if(!r)return!0;if(-1!==(r=r.split(";")).indexOf(""))return!0;for(var n=0;n<r.length;n++){var o=r[n].toLowerCase();if(o&&e.substr(-o.length).toLowerCase()===o)return!0}return!1}(t,r)}function r(r,n,o){e.stat(r,function(e,s){o(e,!e&&t(s,r,n))})}return Fe}():function(){if(We)return Ye;We=1,Ye=t,t.sync=function(t,n){return r(e.statSync(t),n)};var e=m;function t(t,n,o){e.stat(t,function(e,t){o(e,!e&&r(t,n))})}function r(e,t){return e.isFile()&&function(e,t){var r=e.mode,n=e.uid,o=e.gid,s=void 0!==t.uid?t.uid:process.getuid&&process.getuid(),i=void 0!==t.gid?t.gid:process.getgid&&process.getgid(),a=parseInt("100",8),c=parseInt("010",8);return r&parseInt("001",8)||r&c&&o===i||r&a&&n===s||r&(a|c)&&0===s}(e,t)}return Ye}(),Ve=t,t.sync=function(t,r){try{return e.sync(t,r||{})}catch(e){if(r&&r.ignoreErrors||"EACCES"===e.code)return!1;throw e}},Ve}(),s=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),i=(t,r)=>{const o=r.colon||n,s=t.match(/\//)||e&&t.match(/\\/)?[""]:[...e?[process.cwd()]:[],...(r.path||process.env.PATH||"").split(o)],i=e?r.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",a=e?i.split(o):[""];return e&&-1!==t.indexOf(".")&&""!==a[0]&&a.unshift(""),{pathEnv:s,pathExt:a,pathExtExe:i}},a=(e,r,n)=>{"function"==typeof r&&(n=r,r={}),r||(r={});const{pathEnv:a,pathExt:c,pathExtExe:l}=i(e,r),u=[],d=n=>new Promise((o,i)=>{if(n===a.length)return r.all&&u.length?o(u):i(s(e));const c=a[n],l=/^".*"$/.test(c)?c.slice(1,-1):c,d=t.join(l,e),f=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d;o(p(f,n,0))}),p=(e,t,n)=>new Promise((s,i)=>{if(n===c.length)return s(d(t+1));const a=c[n];o(e+a,{pathExt:l},(o,i)=>{if(!o&&i){if(!r.all)return s(e+a);u.push(e+a)}return s(p(e,t,n+1))})});return n?d(0).then(e=>n(null,e),n):d(0)};return Ke=a,a.sync=(e,r)=>{r=r||{};const{pathEnv:n,pathExt:a,pathExtExe:c}=i(e,r),l=[];for(let s=0;s<n.length;s++){const i=n[s],u=/^".*"$/.test(i)?i.slice(1,-1):i,d=t.join(u,e),p=!u&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d;for(let e=0;e<a.length;e++){const t=p+a[e];try{if(o.sync(t,{pathExt:c})){if(!r.all)return t;l.push(t)}}catch(e){}}}if(r.all&&l.length)return l;if(r.nothrow)return null;throw s(e)},Ke}(),n=function(){if(Xe)return pt.exports;Xe=1;const e=(e={})=>{const t=e.env||process.env;return"win32"!==(e.platform||process.platform)?"PATH":Object.keys(t).reverse().find(e=>"PATH"===e.toUpperCase())||"Path"};return pt.exports=e,pt.exports.default=e,pt.exports}();function o(r,o){const s=r.options.env||process.env,i=process.cwd(),a=null!=r.options.cwd,c=a&&void 0!==process.chdir&&!process.chdir.disabled;if(c)try{process.chdir(r.options.cwd)}catch(e){}let l;try{l=t.sync(r.command,{path:s[n({env:s})],pathExt:o?e.delimiter:void 0})}catch(e){}finally{c&&process.chdir(i)}return l&&(l=e.resolve(a?r.options.cwd:"",l)),l}return Qe=function(e){return o(e)||o(e,!0)}}(),n=function(){if(et)return ft;et=1;const e=/([()\][%!^"`<>&|;, *?])/g;return ft.command=function(t){return t.replace(e,"^$1")},ft.argument=function(t,r){return t=(t=`"${t=(t=(t=`${t}`).replace(/(?=(\\+?)?)\1"/g,'$1$1\\"')).replace(/(?=(\\+?)?)\1$/,"$1$1")}"`).replace(e,"^$1"),r&&(t=t.replace(e,"^$1")),t},ft}(),o=function(){if(it)return st;it=1;const e=m,t=function(){if(ot)return nt;ot=1;const e=rt?tt:(rt=1,tt=/^#!(.*)/);return nt=(t="")=>{const r=t.match(e);if(!r)return null;const[n,o]=r[0].replace(/#! ?/,"").split(" "),s=n.split("/").pop();return"env"===s?o:o?`${s} ${o}`:s}}();return st=function(r){const n=Buffer.alloc(150);let o;try{o=e.openSync(r,"r"),e.readSync(o,n,0,150,0),e.closeSync(o)}catch(e){}return t(n.toString())}}(),s="win32"===process.platform,i=/\.(?:com|exe)$/i,a=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;return at=function(r,c,l){c&&!Array.isArray(c)&&(l=c,c=null);const u={command:r,args:c=c?c.slice(0):[],options:l=Object.assign({},l),file:void 0,original:{command:r,args:c}};return l.shell?u:function(r){if(!s)return r;const c=function(e){e.file=t(e);const r=e.file&&o(e.file);return r?(e.args.unshift(e.file),e.command=r,t(e)):e.file}(r),l=!i.test(c);if(r.options.forceShell||l){const t=a.test(c);r.command=e.normalize(r.command),r.command=n.command(r.command),r.args=r.args.map(e=>n.argument(e,t));const o=[r.command].concat(r.args).join(" ");r.args=["/d","/s","/c",`"${o}"`],r.command=process.env.comspec||"cmd.exe",r.options.windowsVerbatimArguments=!0}return r}(u)}}var mt=He(function(){if(dt)return Je.exports;dt=1;const e=u,t=ht(),r=function(){if(ut)return lt;ut=1;const e="win32"===process.platform;function t(e,t){return Object.assign(new Error(`${t} ${e.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}function r(r,n){return e&&1===r&&!n.file?t(n.original,"spawn"):null}return lt={hookChildProcess:function(t,n){if(!e)return;const o=t.emit;t.emit=function(e,s){if("exit"===e){const e=r(s,n);if(e)return o.call(t,"error",e)}return o.apply(t,arguments)}},verifyENOENT:r,verifyENOENTSync:function(r,n){return e&&1===r&&!n.file?t(n.original,"spawnSync"):null},notFoundError:t},lt}();function n(n,o,s){const i=t(n,o,s),a=e.spawn(i.command,i.args,i.options);return r.hookChildProcess(a,i),a}return Je.exports=n,Je.exports.spawn=n,Je.exports.sync=function(n,o,s){const i=t(n,o,s),a=e.spawnSync(i.command,i.args,i.options);return a.error=a.error||r.verifyENOENTSync(a.status,i),a},Je.exports._parse=t,Je.exports._enoent=r,Je.exports}());function gt(e={}){const{env:t=process.env,platform:r=process.platform}=e;return"win32"!==r?"PATH":Object.keys(t).reverse().find(e=>"PATH"===e.toUpperCase())||"Path"}var yt=(e,t)=>({name:`SIGRT${t+1}`,number:bt+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),bt=34,wt=[{name:"SIGHUP",number:1,action:"terminate",description:"Terminal closed",standard:"posix"},{name:"SIGINT",number:2,action:"terminate",description:"User interruption with CTRL-C",standard:"ansi"},{name:"SIGQUIT",number:3,action:"core",description:"User interruption with CTRL-\\",standard:"posix"},{name:"SIGILL",number:4,action:"core",description:"Invalid machine instruction",standard:"ansi"},{name:"SIGTRAP",number:5,action:"core",description:"Debugger breakpoint",standard:"posix"},{name:"SIGABRT",number:6,action:"core",description:"Aborted",standard:"ansi"},{name:"SIGIOT",number:6,action:"core",description:"Aborted",standard:"bsd"},{name:"SIGBUS",number:7,action:"core",description:"Bus error due to misaligned, non-existing address or paging error",standard:"bsd"},{name:"SIGEMT",number:7,action:"terminate",description:"Command should be emulated but is not implemented",standard:"other"},{name:"SIGFPE",number:8,action:"core",description:"Floating point arithmetic error",standard:"ansi"},{name:"SIGKILL",number:9,action:"terminate",description:"Forced termination",standard:"posix",forced:!0},{name:"SIGUSR1",number:10,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGSEGV",number:11,action:"core",description:"Segmentation fault",standard:"ansi"},{name:"SIGUSR2",number:12,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGPIPE",number:13,action:"terminate",description:"Broken pipe or socket",standard:"posix"},{name:"SIGALRM",number:14,action:"terminate",description:"Timeout or timer",standard:"posix"},{name:"SIGTERM",number:15,action:"terminate",description:"Termination",standard:"ansi"},{name:"SIGSTKFLT",number:16,action:"terminate",description:"Stack is empty or overflowed",standard:"other"},{name:"SIGCHLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"posix"},{name:"SIGCLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"other"},{name:"SIGCONT",number:18,action:"unpause",description:"Unpaused",standard:"posix",forced:!0},{name:"SIGSTOP",number:19,action:"pause",description:"Paused",standard:"posix",forced:!0},{name:"SIGTSTP",number:20,action:"pause",description:'Paused using CTRL-Z or "suspend"',standard:"posix"},{name:"SIGTTIN",number:21,action:"pause",description:"Background process cannot read terminal input",standard:"posix"},{name:"SIGBREAK",number:21,action:"terminate",description:"User interruption with CTRL-BREAK",standard:"other"},{name:"SIGTTOU",number:22,action:"pause",description:"Background process cannot write to terminal output",standard:"posix"},{name:"SIGURG",number:23,action:"ignore",description:"Socket received out-of-band data",standard:"bsd"},{name:"SIGXCPU",number:24,action:"core",description:"Process timed out",standard:"bsd"},{name:"SIGXFSZ",number:25,action:"core",description:"File too big",standard:"bsd"},{name:"SIGVTALRM",number:26,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGPROF",number:27,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGWINCH",number:28,action:"ignore",description:"Terminal window size changed",standard:"bsd"},{name:"SIGIO",number:29,action:"terminate",description:"I/O is available",standard:"other"},{name:"SIGPOLL",number:29,action:"terminate",description:"Watched event",standard:"other"},{name:"SIGINFO",number:29,action:"ignore",description:"Request for process information",standard:"other"},{name:"SIGPWR",number:30,action:"terminate",description:"Device running out of power",standard:"systemv"},{name:"SIGSYS",number:31,action:"core",description:"Invalid system call",standard:"other"},{name:"SIGUNUSED",number:31,action:"terminate",description:"Invalid system call",standard:"other"}],vt=()=>{const e=(()=>{const e=64-bt+1;return Array.from({length:e},yt)})();return[...wt,...e].map(_t)},_t=({name:e,number:t,description:r,action:n,forced:o=!1,standard:s})=>{const{signals:{[e]:i}}=U,a=void 0!==i;return{name:e,number:a?i:t,description:r,supported:a,action:n,forced:o,standard:s}},Et=({name:e,number:t,description:r,supported:n,action:o,forced:s,standard:i})=>[e,{name:e,number:t,description:r,supported:n,action:o,forced:s,standard:i}],It=(()=>{const e=vt();return Object.fromEntries(e.map(Et))})();(()=>{const e=vt(),t=Array.from({length:65},(t,r)=>((e,t)=>{const r=((e,t)=>{const r=t.find(({name:t})=>U.signals[t]===e);return void 0!==r?r:t.find(t=>t.number===e)})(e,t);if(void 0===r)return{};const{name:n,description:o,supported:s,action:i,forced:a,standard:c}=r;return{[e]:{name:n,number:e,description:o,supported:s,action:i,forced:a,standard:c}}})(r,e));Object.assign({},...t)})();var Tt=({stdout:e,stderr:t,all:r,error:n,signal:o,exitCode:s,command:i,escapedCommand:a,timedOut:c,isCanceled:l,killed:u,parsed:{options:{timeout:d,cwd:p=h.cwd()}}})=>{s=null===s?void 0:s;const f=void 0===(o=null===o?void 0:o)?void 0:It[o].description,m=(({timedOut:e,timeout:t,errorCode:r,signal:n,signalDescription:o,exitCode:s,isCanceled:i})=>e?`timed out after ${t} milliseconds`:void 0!==r?`failed with ${r}`:void 0!==n?`was killed with ${n} (${o})`:void 0!==s?`failed with exit code ${s}`:"failed")({timedOut:c,timeout:d,errorCode:n&&n.code,signal:o,signalDescription:f,exitCode:s,isCanceled:l}),g=`Command ${m}: ${i}`,y="[object Error]"===Object.prototype.toString.call(n),b=y?`${g}\n${n.message}`:g,w=[b,t,e].filter(Boolean).join("\n");return y?(n.originalMessage=n.message,n.message=w):n=new Error(w),n.shortMessage=b,n.command=i,n.escapedCommand=a,n.exitCode=s,n.signal=o,n.signalDescription=f,n.stdout=e,n.stderr=t,n.cwd=p,void 0!==r&&(n.all=r),"bufferedData"in n&&delete n.bufferedData,n.failed=!0,n.timedOut=Boolean(c),n.isCanceled=l,n.killed=u&&!c,n},xt=["stdin","stdout","stderr"],St=[];St.push("SIGHUP","SIGINT","SIGTERM"),"win32"!==process.platform&&St.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),"linux"===process.platform&&St.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var At,Ct,Rt=e=>!!e&&"object"==typeof e&&"function"==typeof e.removeListener&&"function"==typeof e.emit&&"function"==typeof e.reallyExit&&"function"==typeof e.listeners&&"function"==typeof e.kill&&"number"==typeof e.pid&&"function"==typeof e.on,Pt=Symbol.for("signal-exit emitter"),Ut=globalThis,kt=Object.defineProperty.bind(Object),Lt=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(Ut[Pt])return Ut[Pt];kt(Ut,Pt,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,t){this.listeners[e].push(t)}removeListener(e,t){const r=this.listeners[e],n=r.indexOf(t);-1!==n&&(0===n&&1===r.length?r.length=0:r.splice(n,1))}emit(e,t,r){if(this.emitted[e])return!1;this.emitted[e]=!0;let n=!1;for(const o of this.listeners[e])n=!0===o(t,r)||n;return"exit"===e&&(n=this.emit("afterExit",t,r)||n),n}},Dt=class{},Ot=globalThis.process;Rt(Ot)?new class extends Dt{#e="win32"===Ot.platform?"SIGINT":"SIGHUP";#t=new Lt;#r;#n;#o;#s={};#i=!1;constructor(e){super(),this.#r=e,this.#s={};for(const t of St)this.#s[t]=()=>{const r=this.#r.listeners(t);let{count:n}=this.#t;const o=e;if("object"==typeof o.__signal_exit_emitter__&&"number"==typeof o.__signal_exit_emitter__.count&&(n+=o.__signal_exit_emitter__.count),r.length===n){this.unload();const r=this.#t.emit("exit",null,t),n="SIGHUP"===t?this.#e:t;r||e.kill(e.pid,n)}};this.#o=e.reallyExit,this.#n=e.emit}onExit(e,t){if(!Rt(this.#r))return()=>{};!1===this.#i&&this.load();const r=t?.alwaysLast?"afterExit":"exit";return this.#t.on(r,e),()=>{this.#t.removeListener(r,e),0===this.#t.listeners.exit.length&&0===this.#t.listeners.afterExit.length&&this.unload()}}load(){if(!this.#i){this.#i=!0,this.#t.count+=1;for(const e of St)try{const t=this.#s[e];t&&this.#r.on(e,t)}catch(e){}this.#r.emit=(e,...t)=>this.#a(e,...t),this.#r.reallyExit=e=>this.#c(e)}}unload(){this.#i&&(this.#i=!1,St.forEach(e=>{const t=this.#s[e];if(!t)throw new Error("Listener not defined for signal: "+e);try{this.#r.removeListener(e,t)}catch(e){}}),this.#r.emit=this.#n,this.#r.reallyExit=this.#o,this.#t.count-=1)}#c(e){return Rt(this.#r)?(this.#r.exitCode=e||0,this.#t.emit("exit",this.#r.exitCode,null),this.#o.call(this.#r,this.#r.exitCode)):0}#a(e,...t){const r=this.#n;if("exit"===e&&Rt(this.#r)){"number"==typeof t[0]&&(this.#r.exitCode=t[0]);const n=r.call(this.#r,e,...t);return this.#t.emit("exit",this.#r.exitCode,null),n}return r.call(this.#r,e,...t)}}(Ot):new class extends Dt{onExit(){return()=>{}}load(){}unload(){}},new TextEncoder,function(){if(Ct)return At;Ct=1;const{PassThrough:e}=k;At=function(){var t=[],r=new e({objectMode:!0});return r.setMaxListeners(0),r.add=n,r.isEmpty=function(){return 0==t.length},r.on("unpipe",o),Array.prototype.slice.call(arguments).forEach(n),r;function n(e){return Array.isArray(e)?(e.forEach(n),this):(t.push(e),e.once("end",o.bind(null,e)),e.once("error",r.emit.bind(r,"error")),e.pipe(r,{end:!1}),this)}function o(e){!(t=t.filter(function(t){return t!==e})).length&&r.readable&&r.end()}}}();var Bt=(async()=>{})().constructor.prototype;["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(Bt,e)]);var Nt=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],$t=/^[\w.-]+$/,Mt=L("execa").enabled,jt=(e,t)=>String(e).padStart(t,"0"),Ht=(e,t,n={})=>{const o=mt._parse(e,t,n);return e=o.command,t=o.args,(n={maxBuffer:1e8,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:(n=o.options).cwd||h.cwd(),execPath:h.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:Mt,...n}).env=(({env:e,extendEnv:t,preferLocal:n,localDir:o,execPath:s})=>{const i=t?{...h.env,...e}:e;return n?(({env:e=h.env,...t}={})=>{const n=gt({env:e={...e}});return t.path=e[n],e[n]=(({cwd:e=h.cwd(),path:t=h.env[gt()],preferLocal:n=!0,execPath:o=h.execPath,addExecPath:s=!0}={})=>{const i=e instanceof URL?A(e):e,a=r.resolve(i),c=[];return n&&((e,t)=>{let n;for(;n!==t;)e.push(r.join(t,"node_modules/.bin")),n=t,t=r.resolve(t,"..")})(c,a),s&&((e,t,n)=>{const o=t instanceof URL?A(t):t;e.push(r.resolve(n,o,".."))})(c,o,a),[...c,t].join(r.delimiter)})(t),e})({env:i,cwd:o,execPath:s}):i})(n),n.stdio=(e=>{if(!e)return;const{stdio:t}=e;if(void 0===t)return xt.map(t=>e[t]);if((e=>xt.some(t=>void 0!==e[t]))(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${xt.map(e=>`\`${e}\``).join(", ")}`);if("string"==typeof t)return t;if(!Array.isArray(t))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof t}\``);const r=Math.max(t.length,xt.length);return Array.from({length:r},(e,r)=>t[r])})(n),"win32"===h.platform&&"cmd"===r.basename(e,".exe")&&t.unshift("/q"),{file:e,args:t,options:n,parsed:o}},Ft=(e,t,r)=>"string"==typeof t||l.isBuffer(t)?e.stripFinalNewline?function(e){const t="string"==typeof e?"\n":"\n".charCodeAt(),r="string"==typeof e?"\r":"\r".charCodeAt();return e[e.length-1]===t&&(e=e.slice(0,-1)),e[e.length-1]===r&&(e=e.slice(0,-1)),e}(t):t:void 0===r?void 0:"";function Gt(e,t,r){const n=Ht(e,t,r),o=((e,t)=>Nt(e,t).join(" "))(e,t),s=((e,t)=>Nt(e,t).map(e=>(e=>"string"!=typeof e||$t.test(e)?e:`"${e.replaceAll('"','\\"')}"`)(e)).join(" "))(e,t);((e,{verbose:t})=>{t&&h.stderr.write(`[${(()=>{const e=new Date;return`${jt(e.getHours(),2)}:${jt(e.getMinutes(),2)}:${jt(e.getSeconds(),2)}.${jt(e.getMilliseconds(),3)}`})()}] ${e}\n`)})(s,n.options);const i=(e=>{const t=(({input:e,inputFile:t})=>"string"!=typeof t?e:((e=>{if(void 0!==e)throw new TypeError("The `input` and `inputFile` options cannot be both set.")})(e),w(t)))(e);if(null!==(r=t)&&"object"==typeof r&&"function"==typeof r.pipe)throw new TypeError("The `input` option cannot be a stream in sync mode");var r;return t})(n.options);let a;try{a=u.spawnSync(n.file,n.args,{...n.options,input:i})}catch(e){throw Tt({error:e,stdout:"",stderr:"",all:"",command:o,escapedCommand:s,parsed:n,timedOut:!1,isCanceled:!1,killed:!1})}const c=Ft(n.options,a.stdout,a.error),l=Ft(n.options,a.stderr,a.error);if(a.error||0!==a.status||null!==a.signal){const e=Tt({stdout:c,stderr:l,error:a.error,signal:a.signal,exitCode:a.status,command:o,escapedCommand:s,parsed:n,timedOut:a.error&&"ETIMEDOUT"===a.error.code,isCanceled:!1,killed:null!==a.signal});if(!n.options.reject)return e;throw e}return{command:o,escapedCommand:s,exitCode:0,stdout:c,stderr:l,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}}function Yt(e){try{return Gt("git",["rev-parse","HEAD"],e).stdout}catch{return}}function Wt(e){try{const t=Gt("git",["rev-parse","--abbrev-ref","HEAD"],e).stdout;if("HEAD"===t){const t=Gt("git",["show","-s","--pretty=%d","HEAD"],e).stdout.replace(/^\(|\)$/g,"").split(", ").find(e=>e.startsWith("origin/"));return t?t.match(/^origin\/(?<branch>.+)/)[1]:void 0}return t}catch{return}}var Vt=/^(?:.*)@(?:.*):(?:\d+\/)?(.*)\.git$/,zt=/^\/(.*)\.git$/;function Kt(e){if(e){if(e.match(Vt))return e.replace(Vt,"$1");try{return new URL(e).pathname.replace(zt,"$1")}catch{return}}}var qt,Jt={detect:({env:e})=>Boolean(e.BUILDKITE),configuration({env:e}){const t="false"===e.BUILDKITE_PULL_REQUEST?void 0:e.BUILDKITE_PULL_REQUEST,r=Boolean(t);return{name:"Buildkite",service:"buildkite",build:e.BUILDKITE_BUILD_NUMBER,buildUrl:e.BUILDKITE_BUILD_URL,commit:e.BUILDKITE_COMMIT,tag:e.BUILDKITE_TAG,branch:r?e.BUILDKITE_PULL_REQUEST_BASE_BRANCH:e.BUILDKITE_BRANCH,slug:Kt(e.BUILDKITE_REPO),pr:t,isPr:r,prBranch:r?e.BUILDKITE_BRANCH:void 0,root:e.BUILDKITE_BUILD_CHECKOUT_PATH}}},Xt={detect:({env:e})=>Boolean(e.CIRCLECI),configuration({env:e}){const t=e.CIRCLE_PR_NUMBER||Le(e.CIRCLE_PULL_REQUEST||e.CI_PULL_REQUEST),r=Boolean(t);return{name:"CircleCI",service:"circleci",build:e.CIRCLE_BUILD_NUM,buildUrl:e.CIRCLE_BUILD_URL,job:`${e.CIRCLE_BUILD_NUM}.${e.CIRCLE_NODE_INDEX}`,commit:e.CIRCLE_SHA1,tag:e.CIRCLE_TAG,branch:r?void 0:e.CIRCLE_BRANCH,pr:t,isPr:r,prBranch:r?e.CIRCLE_BRANCH:void 0,slug:`${e.CIRCLE_PROJECT_USERNAME}/${e.CIRCLE_PROJECT_REPONAME}`}}},Qt="https://cirrus-ci.com",Zt={detect:({env:e})=>Boolean(e.CIRRUS_CI),configuration({env:e}){const t=e.CIRRUS_PR,r=Boolean(t);return{name:"Cirrus CI",service:"cirrus",commit:e.CIRRUS_CHANGE_IN_REPO,tag:e.CIRRUS_TAG,build:e.CIRRUS_BUILD_ID,buildUrl:`${Qt}/build/${e.CIRRUS_BUILD_ID}`,job:e.CIRRUS_TASK_ID,jobUrl:`${Qt}/task/${e.CIRRUS_TASK_ID}`,branch:r?e.CIRRUS_BASE_BRANCH:e.CIRRUS_BRANCH,pr:t,isPr:r,prBranch:r?e.CIRRUS_BRANCH:void 0,slug:e.CIRRUS_REPO_FULL_NAME,root:e.CIRRUS_WORKING_DIR}}},er={detect:({env:e})=>Boolean(e.CODEBUILD_BUILD_ID),configuration:({env:e,cwd:t})=>({name:"AWS CodeBuild",service:"codebuild",commit:Yt({env:e,cwd:t}),build:e.CODEBUILD_BUILD_ID,branch:Wt({env:e,cwd:t}),buildUrl:`https://console.aws.amazon.com/codebuild/home?region=${e.AWS_REGION}#/builds/${e.CODEBUILD_BUILD_ID}/view/new`,root:e.PWD})},tr={detect:({env:e})=>Boolean(e.CF_BUILD_ID),configuration({env:e}){const t=e.CF_PULL_REQUEST_NUMBER,r=Boolean(t);return{name:"Codefresh",service:"codefresh",commit:e.CF_REVISION,build:e.CF_BUILD_ID,buildUrl:e.CF_BUILD_URL,branch:r?e.CF_PULL_REQUEST_TARGET:e.CF_BRANCH,pr:t,isPr:r,prBranch:r?e.CF_BRANCH:void 0,slug:`${e.CF_REPO_OWNER}/${e.CF_REPO_NAME}`,root:e.CF_VOLUME_PATH}}},rr={detect:({env:e})=>Boolean(e.DRONE),configuration({env:e}){const t="pull_request"===e.DRONE_BUILD_EVENT;return{name:"Drone",service:"drone",commit:e.DRONE_COMMIT_SHA,tag:e.DRONE_TAG,build:e.DRONE_BUILD_NUMBER,buildUrl:e.DRONE_BUILD_LINK,branch:t?e.DRONE_TARGET_BRANCH:e.DRONE_BRANCH,job:e.DRONE_JOB_NUMBER,jobUrl:e.DRONE_BUILD_LINK,pr:e.DRONE_PULL_REQUEST,isPr:t,prBranch:t?e.DRONE_SOURCE_BRANCH:void 0,slug:`${e.DRONE_REPO_OWNER}/${e.DRONE_REPO_NAME}`,root:e.DRONE_WORKSPACE}}},nr=({env:e})=>{try{const t=e.GITHUB_EVENT_PATH?JSON.parse(w(e.GITHUB_EVENT_PATH,"utf-8")):void 0;if(t&&t.pull_request)return{branch:t.pull_request.base?De(t.pull_request.base.ref):void 0,pr:t.pull_request.number}}catch{}return{pr:void 0,branch:void 0}},or={detect:({env:e})=>Boolean(e.GITHUB_ACTIONS),configuration({env:e,cwd:t}){const r="pull_request"===e.GITHUB_EVENT_NAME||"pull_request_target"===e.GITHUB_EVENT_NAME,n=De("pull_request_target"===e.GITHUB_EVENT_NAME?`refs/pull/${(e=>{const t=e.GITHUB_EVENT_PATH?JSON.parse(w(e.GITHUB_EVENT_PATH,"utf-8")):void 0;return t&&t.pull_request?t.pull_request.number:void 0})(e)}/merge`:e.GITHUB_REF);return{name:"GitHub Actions",service:"github",commit:e.GITHUB_SHA,build:e.GITHUB_RUN_ID,buildUrl:`${e.GITHUB_SERVER_URL}/${e.GITHUB_REPOSITORY}/actions/runs/${e.GITHUB_RUN_ID}`,isPr:r,branch:n,prBranch:r?n:void 0,slug:e.GITHUB_REPOSITORY,root:e.GITHUB_WORKSPACE,...r?nr({env:e}):void 0}}},sr={detect:({env:e})=>Boolean(e.GITLAB_CI),configuration({env:e}){const t=e.CI_MERGE_REQUEST_ID,r=Boolean(t);return{name:"GitLab CI/CD",service:"gitlab",commit:e.CI_COMMIT_SHA,tag:e.CI_COMMIT_TAG,build:e.CI_PIPELINE_ID,buildUrl:`${e.CI_PROJECT_URL}/pipelines/${e.CI_PIPELINE_ID}`,job:e.CI_JOB_ID,jobUrl:`${e.CI_PROJECT_URL}/-/jobs/${e.CI_JOB_ID}`,branch:r?e.CI_MERGE_REQUEST_TARGET_BRANCH_NAME:e.CI_COMMIT_REF_NAME,pr:t,isPr:r,prBranch:e.CI_MERGE_REQUEST_SOURCE_BRANCH_NAME,slug:e.CI_PROJECT_PATH,root:e.CI_PROJECT_DIR}}},ir={detect:({env:e})=>Boolean(e.JENKINS_URL),configuration({env:e,cwd:t}){const r=e.ghprbPullId||e.gitlabMergeRequestId||e.CHANGE_ID,n=Boolean(r),o=e.GIT_LOCAL_BRANCH||e.GIT_BRANCH||e.gitlabBranch||e.BRANCH_NAME;return{name:"Jenkins",service:"jenkins",commit:e.ghprbActualCommit||e.GIT_COMMIT||Yt({env:e,cwd:t}),branch:n?e.ghprbTargetBranch||e.gitlabTargetBranch:o,build:e.BUILD_NUMBER,buildUrl:e.BUILD_URL,root:e.WORKSPACE,pr:r,isPr:n,prBranch:n?e.ghprbSourceBranch||e.gitlabSourceBranch||o:void 0}}},ar={detect:({env:e})=>"true"===e.NETLIFY,configuration({env:e}){const t="true"===e.PULL_REQUEST;return{name:"Netlify",service:"netlify",commit:e.COMMIT_REF,build:e.DEPLOY_ID,buildUrl:`https://app.netlify.com/sites/${e.SITE_NAME}/deploys/${e.DEPLOY_ID}`,branch:t?void 0:e.HEAD,pr:e.REVIEW_ID,isPr:t,prBranch:t?e.HEAD:void 0,slug:e.REPOSITORY_URL.match(/[^/:]+\/[^/]+?$/)[0],root:e.PWD}}},cr={detect:({env:e})=>Boolean(e.DISTELLI_APPNAME),configuration:({env:e})=>({name:"Puppet",service:"puppet",build:e.DISTELLI_BUILDNUM,buildUrl:e.DISTELLI_RELEASE,commit:e.DISTELLI_RELREVISION,branch:e.DISTELLI_RELBRANCH,root:e.DISTELLI_INSTALLHOME})},lr={detect:({env:e})=>Boolean(e.SAILCI),configuration({env:e}){const t=e.SAIL_PULL_REQUEST_NUMBER,r=Boolean(t);return{name:"Sail CI",service:"sail",commit:e.SAIL_COMMIT_SHA,branch:r?void 0:e.SAIL_COMMIT_BRANCH,pr:t,isPr:r,slug:`${e.SAIL_REPO_OWNER}/${e.SAIL_REPO_NAME}`,root:e.SAIL_CLONE_DIR}}},ur={detect:({env:e})=>Boolean(e.SCREWDRIVER),configuration({env:e}){const t=e.SD_PULL_REQUEST,r=Boolean(t);return{name:"Screwdriver.cd",service:"screwdriver",branch:r?e.PR_BASE_BRANCH_NAME:e.GIT_BRANCH,prBranch:r?e.PR_BRANCH_NAME:void 0,commit:e.SD_BUILD_SHA,build:e.SD_BUILD_ID,buildUrl:e.SD_UI_BUILD_URL,job:e.SD_JOB_ID,pr:t,isPr:r,slug:e.SD_PIPELINE_NAME,root:e.SD_ROOT_DIR}}},dr={detect:({env:e})=>Boolean(e.SCRUTINIZER),configuration({env:e}){const t=e.SCRUTINIZER_PR_NUMBER,r=Boolean(t);return{name:"Scrutinizer",service:"scrutinizer",commit:e.SCRUTINIZER_SHA1,build:e.SCRUTINIZER_INSPECTION_UUID,branch:e.SCRUTINIZER_BRANCH,pr:t,isPr:r,prBranch:e.SCRUTINIZER_PR_SOURCE_BRANCH}}},pr={detect:({env:e})=>Boolean(e.SEMAPHORE),configuration({env:e,cwd:t}){const r=e.SEMAPHORE_GIT_PR_NUMBER||e.PULL_REQUEST_NUMBER,n=Boolean(r);return{name:"Semaphore",service:"semaphore",commit:e.SEMAPHORE_GIT_SHA||Yt({env:e,cwd:t}),tag:e.SEMAPHORE_GIT_TAG_NAME,build:e.SEMAPHORE_JOB_ID||e.SEMAPHORE_BUILD_NUMBER,branch:e.SEMAPHORE_GIT_BRANCH||(n?void 0:e.BRANCH_NAME),pr:r,isPr:n,prBranch:e.SEMAPHORE_GIT_PR_BRANCH||(n?e.BRANCH_NAME:void 0),slug:e.SEMAPHORE_GIT_REPO_SLUG||e.SEMAPHORE_REPO_SLUG,root:e.SEMAPHORE_GIT_DIR||e.SEMAPHORE_PROJECT_DIR}}},fr={detect:({env:e})=>Boolean(e.SHIPPABLE),configuration({env:e}){const t="true"===e.IS_PULL_REQUEST?e.PULL_REQUEST:void 0,r=Boolean(t);return{name:"Shippable",service:"shippable",commit:e.COMMIT,tag:e.GIT_TAG_NAME,build:e.BUILD_NUMBER,buildUrl:e.BUILD_URL,branch:r?e.BASE_BRANCH:e.BRANCH,job:e.JOB_NUMBER,pr:t,isPr:r,prBranch:r?e.HEAD_BRANCH:void 0,slug:e.SHIPPABLE_REPO_SLUG,root:e.SHIPPABLE_BUILD_DIR}}},hr={};function mr(){if(qt)return hr;qt=1,Object.defineProperty(hr,"__esModule",{value:!0}),hr.of=hr.PropertiesFile=void 0;var e,t=(e=m)&&e.__esModule?e:{default:e};class r{constructor(...e){this.objs={},e.length&&this.of.apply(this,e)}makeKeys(e){if(e&&0!==e.indexOf("#")){let t=["=",":"].map(t=>e.indexOf(t)).filter(e=>e>-1),r=Math.min(...t),n=e.substring(0,r).trim(),o=e.substring(r+1).trim();if(this.objs.hasOwnProperty(n))if(Array.isArray(this.objs[n]))this.objs[n].push(o);else{let e=this.objs[n];this.objs[n]=[e,o]}else{const e=o.replace(/"/g,'\\"').replace(/\\:/g,":").replace(/\\=/g,"=");this.objs[n]=unescape(JSON.parse('"'+e+'"'))}}}addFile(e){let r=t.default.readFileSync(e,"utf-8").split(/\r?\n/),n=this;for(let e=0;e<r.length;e++){let t=r[e];for(;"\\"===t.substring(t.length-1);)t=t.slice(0,-1),t+=r[e+1].trim(),e++;n.makeKeys(t)}}of(...e){for(let t=0;t<e.length;t++)this.addFile(e[t])}get(e,t){if(this.objs.hasOwnProperty(e)){if(Array.isArray(this.objs[e])){let t=[];for(let r=0;r<this.objs[e].length;r++)t[r]=this.interpolate(this.objs[e][r]);return t}return void 0===this.objs[e]?"":this.interpolate(this.objs[e])}return t}getLast(e,t){if(this.objs.hasOwnProperty(e)){if(Array.isArray(this.objs[e])){var r=this.objs[e].length;return this.interpolate(this.objs[e][r-1])}return void 0===this.objs[e]?"":this.interpolate(this.objs[e])}return t}getFirst(e,t){return this.objs.hasOwnProperty(e)?Array.isArray(this.objs[e])?this.interpolate(this.objs[e][0]):void 0===this.objs[e]?"":this.interpolate(this.objs[e]):t}getInt(e,t){let r=this.getLast(e);return r?parseInt(r,10):t}getFloat(e,t){let r=this.getLast(e);return r?parseFloat(r):t}getBoolean(e,t){let r=this.getLast(e);return r?!/^(false|0)$/i.test(n=r)&&!!n:t||!1;var n}set(e,t){this.objs[e]=t}interpolate(e){let t=this;return e.replace(/\\\\/g,"\\").replace(/\$\{([A-Za-z0-9\.\-\_]*)\}/g,function(e){return t.getLast(e.substring(2,e.length-1))})}getKeys(){let e=[];for(let t in this.objs)e.push(t);return e}getMatchingKeys(e){let t=[];for(let r in this.objs)-1!==r.search(e)&&t.push(r);return t}reset(){this.objs={}}}return hr.PropertiesFile=r,hr.of=function(...e){let t=new r;return t.of.apply(t,e),t},hr}var gr=He(mr()),yr={root:"teamcity.build.workingDir",branch:"teamcity.build.branch"},br=e=>{try{return gr.of(e)}catch{return}},wr=({env:e,cwd:t})=>{const r=e.TEAMCITY_BUILD_PROPERTIES_FILE?br(e.TEAMCITY_BUILD_PROPERTIES_FILE):void 0,n=r?r.get("teamcity.configuration.properties.file"):void 0,o=n?br(n):n;return Object.fromEntries(Object.keys(yr).map(n=>[n,(r?r.get(yr[n]):void 0)||(o?o.get(yr[n]):void 0)||("branch"===n?Wt({env:e,cwd:t}):void 0)]))},vr={appveyor:ke,azurePipelines:Oe,bamboo:Be,bitbucket:Ne,bitrise:$e,buddy:Me,buildkite:Jt,circleci:Xt,cirrus:Zt,cloudflarePages:{detect:({env:e})=>"1"===e.CF_PAGES,configuration:({env:e})=>({name:"Cloudflare Pages",service:"cloudflarePages",commit:e.CF_PAGES_COMMIT_SHA,branch:e.CF_PAGES_BRANCH,root:e.PWD})},codebuild:er,codefresh:tr,codeship:{detect:({env:e})=>e.CI_NAME&&"codeship"===e.CI_NAME,configuration:({env:e})=>({name:"Codeship",service:"codeship",build:e.CI_BUILD_NUMBER,buildUrl:e.CI_BUILD_URL,commit:e.CI_COMMIT_ID,branch:e.CI_BRANCH,slug:e.CI_REPO_NAME})},drone:rr,github:or,gitlab:sr,jenkins:ir,netlify:ar,puppet:cr,sail:lr,screwdriver:ur,scrutinizer:dr,semaphore:pr,shippable:fr,teamcity:{detect:({env:e})=>Boolean(e.TEAMCITY_VERSION),configuration:({env:e,cwd:t})=>({name:"TeamCity",service:"teamcity",commit:e.BUILD_VCS_NUMBER,build:e.BUILD_NUMBER,slug:e.TEAMCITY_BUILDCONF_NAME,...wr({env:e,cwd:t})})},travis:{detect:({env:e})=>Boolean(e.TRAVIS),configuration({env:e}){const t="false"===e.TRAVIS_PULL_REQUEST?void 0:e.TRAVIS_PULL_REQUEST,r=Boolean(t);return{name:"Travis CI",service:"travis",commit:e.TRAVIS_COMMIT,tag:e.TRAVIS_TAG,build:e.TRAVIS_BUILD_NUMBER,buildUrl:e.TRAVIS_BUILD_WEB_URL,branch:e.TRAVIS_BRANCH,job:e.TRAVIS_JOB_NUMBER,jobUrl:e.TRAVIS_JOB_WEB_URL,pr:t,isPr:r,prBranch:e.TRAVIS_PULL_REQUEST_BRANCH,slug:e.TRAVIS_REPO_SLUG,root:e.TRAVIS_BUILD_DIR}}},vela:{detect:({env:e})=>Boolean(e.VELA),configuration({env:e}){const t="pull_request"===e.VELA_BUILD_EVENT;return{name:"Vela",service:"vela",branch:t?e.VELA_PULL_REQUEST_TARGET:e.VELA_BUILD_BRANCH,commit:e.VELA_BUILD_COMMIT,tag:e.VELA_BUILD_TAG,build:e.VELA_BUILD_NUMBER,buildUrl:e.VELA_BUILD_LINK,job:void 0,jobUrl:void 0,isPr:t,pr:e.VELA_BUILD_PULL_REQUEST,prBranch:e.VELA_PULL_REQUEST_SOURCE,slug:e.VELA_REPO_FULL_NAME,root:e.VELA_BUILD_WORKSPACE}}},vercel:{detect:({env:e})=>Boolean(e.VERCEL)||Boolean(e.NOW_GITHUB_DEPLOYMENT),configuration({env:e}){const t="Vercel",r="vercel";return e.VERCEL?{name:t,service:r,commit:e.VERCEL_GIT_COMMIT_SHA,branch:e.VERCEL_GIT_COMMIT_REF,slug:`${e.VERCEL_GIT_REPO_OWNER}/${e.VERCEL_GIT_REPO_SLUG}`}:{name:t,service:r,commit:e.NOW_GITHUB_COMMIT_SHA,branch:e.NOW_GITHUB_COMMIT_REF,slug:`${e.NOW_GITHUB_ORG}/${e.NOW_GITHUB_REPO}`}}},wercker:{detect:({env:e})=>Boolean(e.WERCKER_MAIN_PIPELINE_STARTED),configuration:({env:e})=>({name:"Wercker",service:"wercker",commit:e.WERCKER_GIT_COMMIT,build:e.WERCKER_MAIN_PIPELINE_STARTED,buildUrl:e.WERCKER_RUN_URL,branch:e.WERCKER_GIT_BRANCH,slug:`${e.WERCKER_GIT_OWNER}/${e.WERCKER_GIT_REPOSITORY}`,root:e.WERCKER_ROOT})},woodpecker:{detect:({env:e})=>e.CI&&"woodpecker"===e.CI,configuration({env:e}){const t="pull_request"===e.CI_PIPELINE_EVENT;return{name:"Woodpecker CI",service:"woodpecker",commit:e.CI_COMMIT_SHA,tag:e.CI_COMMIT_TAG,build:e.CI_PIPELINE_NUMBER,buildUrl:e.CI_PIPELINE_URL,branch:t?e.CI_COMMIT_TARGET_BRANCH:e.CI_COMMIT_BRANCH,job:e.CI_STEP_NUMBER,jobUrl:e.CI_STEP_URL,pr:e.CI_COMMIT_PULL_REQUEST,isPr:t,prBranch:t?e.CI_COMMIT_SOURCE_BRANCH:void 0,slug:`${e.CI_REPO_OWNER}/${e.CI_REPO_NAME}`,root:e.CI_WORKSPACE}}},jetbrainsSpace:{detect:({env:e})=>Boolean(e.JB_SPACE_EXECUTION_NUMBER),configuration({env:e}){const t=e.JB_SPACE_PROJECT_KEY,r=e.JB_SPACE_GIT_REPOSITORY_NAME;return{name:"JetBrains Space",service:"jetbrainsSpace",commit:e.JB_SPACE_GIT_REVISION,build:e.JB_SPACE_EXECUTION_NUMBER,branch:De(e.JB_SPACE_GIT_BRANCH),slug:t&&r?`${t.toLowerCase()}/${r}`:void 0}}}},_r=class e{git;config;snapshotTreeHash;snapshotIndexPath;constructor(e){this.config=e,this.git=Y({baseDir:e.workingDir,maxConcurrentProcesses:1})}static createLocal({workingDir:t}){return new e({mode:"local",workingDir:t})}static createCloud({workingDir:t,baseBranch:r}){return new e({mode:"cloud",workingDir:t,baseBranch:r})}async captureSnapshot(){if("local"!==this.config.mode)return;this.snapshotIndexPath=s(P(),`git-diff-tracker-${F()}.index`),await this.git.env("GIT_INDEX_FILE",this.snapshotIndexPath).add(["-A"]);const e=await this.git.env("GIT_INDEX_FILE",this.snapshotIndexPath).raw(["write-tree"]);this.snapshotTreeHash=e.trim()}async computeDiff(){return"local"===this.config.mode?this.computeLocalDiff():this.computeCloudDiff()}async computeLocalDiff(){if(!this.snapshotTreeHash)throw new Error("No snapshot captured. Call captureSnapshot() first.");const e=s(P(),`git-diff-tracker-${F()}.index`);try{await this.git.env("GIT_INDEX_FILE",e).add(["-A"]);const t=(await this.git.env("GIT_INDEX_FILE",e).raw(["write-tree"])).trim();return await this.git.raw(["diff-tree","-p","--no-color",this.snapshotTreeHash,t])}finally{await Er(e)}}async computeCloudDiff(){if("cloud"!==this.config.mode)throw new Error("computeCloudDiff called but mode is not cloud");const{baseBranch:e}=this.config;return await this.git.revparse([`origin/${e}`]).then(()=>!0).catch(()=>!1)||await this.git.fetch(["origin",`+${e}:refs/remotes/origin/${e}`,"--depth","1","--quiet"]).catch(e=>{console.error("[git-diff-tracker] Failed to fetch base branch:",e)}),await this.git.diff([`origin/${e}`])}async cleanup(){this.snapshotIndexPath&&(await Er(this.snapshotIndexPath),this.snapshotIndexPath=void 0),this.snapshotTreeHash=void 0}};async function Er(e){try{await q(e)}catch{}}var Ir="x-stably-org-id",Tr={bodySerializer:e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t)},xr=({allowReserved:e,explode:t,name:r,style:n,value:o})=>{if(!t){const t=(e?o:o.map(e=>encodeURIComponent(e))).join((e=>{switch(e){case"form":default:return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20"}})(n));switch(n){case"label":return`.${t}`;case"matrix":return`;${r}=${t}`;case"simple":return t;default:return`${r}=${t}`}}const s=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(n),i=o.map(t=>"label"===n||"simple"===n?e?t:encodeURIComponent(t):Sr({allowReserved:e,name:r,value:t})).join(s);return"label"===n||"matrix"===n?s+i:i},Sr=({allowReserved:e,name:t,value:r})=>{if(null==r)return"";if("object"==typeof r)throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${t}=${e?r:encodeURIComponent(r)}`},Ar=({allowReserved:e,explode:t,name:r,style:n,value:o,valueOnly:s})=>{if(o instanceof Date)return s?o.toISOString():`${r}=${o.toISOString()}`;if("deepObject"!==n&&!t){let t=[];Object.entries(o).forEach(([r,n])=>{t=[...t,r,e?n:encodeURIComponent(n)]});const s=t.join(",");switch(n){case"form":return`${r}=${s}`;case"label":return`.${s}`;case"matrix":return`;${r}=${s}`;default:return s}}const i=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(n),a=Object.entries(o).map(([t,o])=>Sr({allowReserved:e,name:"deepObject"===n?`${r}[${t}]`:t,value:o})).join(i);return"label"===n||"matrix"===n?i+a:a},Cr=/\{[^{}]+\}/g;function Rr(e){const t=void 0!==e.body;return t&&e.bodySerializer?"serializedBody"in e?void 0!==e.serializedBody&&""!==e.serializedBody?e.serializedBody:null:""!==e.body?e.body:null:t?e.body:void 0}var Pr,Ur=async(e,t)=>{const r="function"==typeof t?await t(e):t;if(r)return"bearer"===e.scheme?`Bearer ${r}`:"basic"===e.scheme?`Basic ${btoa(r)}`:r},kr=({parameters:e={},...t}={})=>r=>{const n=[];if(r&&"object"==typeof r)for(const o in r){const s=r[o];if(null==s)continue;const i=e[o]||t;if(Array.isArray(s)){const e=xr({allowReserved:i.allowReserved,explode:!0,name:o,style:"form",value:s,...i.array});e&&n.push(e)}else if("object"==typeof s){const e=Ar({allowReserved:i.allowReserved,explode:!0,name:o,style:"deepObject",value:s,...i.object});e&&n.push(e)}else{const e=Sr({allowReserved:i.allowReserved,name:o,value:s});e&&n.push(e)}}return n.join("&")},Lr=(e,t)=>!!t&&!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`)),Dr=e=>(({baseUrl:e,path:t,query:r,querySerializer:n,url:o})=>{let s=(e??"")+(o.startsWith("/")?o:`/${o}`);t&&(s=(({path:e,url:t})=>{let r=t;const n=t.match(Cr);if(n)for(const t of n){let n=!1,o=t.substring(1,t.length-1),s="simple";o.endsWith("*")&&(n=!0,o=o.substring(0,o.length-1)),o.startsWith(".")?(o=o.substring(1),s="label"):o.startsWith(";")&&(o=o.substring(1),s="matrix");const i=e[o];if(null==i)continue;if(Array.isArray(i)){r=r.replace(t,xr({explode:n,name:o,style:s,value:i}));continue}if("object"==typeof i){r=r.replace(t,Ar({explode:n,name:o,style:s,value:i,valueOnly:!0}));continue}if("matrix"===s){r=r.replace(t,`;${Sr({name:o,value:i})}`);continue}const a=encodeURIComponent("label"===s?`.${i}`:i);r=r.replace(t,a)}return r})({path:t,url:s}));let i=r?n(r):"";return i.startsWith("?")&&(i=i.substring(1)),i&&(s+=`?${i}`),s})({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:"function"==typeof e.querySerializer?e.querySerializer:kr(e.querySerializer),url:e.url}),Or=(e,t)=>{const r={...e,...t};return r.baseUrl?.endsWith("/")&&(r.baseUrl=r.baseUrl.substring(0,r.baseUrl.length-1)),r.headers=Nr(e.headers,t.headers),r},Br=e=>{const t=[];return e.forEach((e,r)=>{t.push([r,e])}),t},Nr=(...e)=>{const t=new Headers;for(const r of e){if(!r)continue;const e=r instanceof Headers?Br(r):Object.entries(r);for(const[r,n]of e)if(null===n)t.delete(r);else if(Array.isArray(n))for(const e of n)t.append(r,e);else void 0!==n&&t.set(r,"object"==typeof n?JSON.stringify(n):n)}return t},$r=class{fns=[];clear(){this.fns=[]}eject(e){const t=this.getInterceptorIndex(e);this.fns[t]&&(this.fns[t]=null)}exists(e){const t=this.getInterceptorIndex(e);return Boolean(this.fns[t])}getInterceptorIndex(e){return"number"==typeof e?this.fns[e]?e:-1:this.fns.indexOf(e)}update(e,t){const r=this.getInterceptorIndex(e);return!!this.fns[r]&&(this.fns[r]=t,e)}use(e){return this.fns.push(e),this.fns.length-1}},Mr=kr({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),jr={"Content-Type":"application/json"},Hr=(e={})=>({...Tr,headers:jr,parseAs:"auto",querySerializer:Mr,...e}),Fr=(e={})=>{let t=Or(Hr(),e);const r=()=>({...t}),n={error:new $r,request:new $r,response:new $r},o=async e=>{const r={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:Nr(t.headers,e.headers),serializedBody:void 0};return r.security&&await(async({security:e,...t})=>{for(const r of e){if(Lr(t,r.name))continue;const e=await Ur(r,t.auth);if(!e)continue;const n=r.name??"Authorization";switch(r.in){case"query":t.query||(t.query={}),t.query[n]=e;break;case"cookie":t.headers.append("Cookie",`${n}=${e}`);break;default:t.headers.set(n,e)}}})({...r,security:r.security}),r.requestValidator&&await r.requestValidator(r),void 0!==r.body&&r.bodySerializer&&(r.serializedBody=r.bodySerializer(r.body)),void 0!==r.body&&""!==r.serializedBody||r.headers.delete("Content-Type"),{opts:r,url:Dr(r)}},s=async e=>{const{opts:t,url:r}=await o(e),s={redirect:"follow",...t,body:Rr(t)};let i=new Request(r,s);for(const e of n.request.fns)e&&(i=await e(i,t));const a=t.fetch;let c;try{c=await a(i)}catch(e){let r=e;for(const o of n.error.fns)o&&(r=await o(e,void 0,i,t));if(r=r||{},t.throwOnError)throw r;return"data"===t.responseStyle?void 0:{error:r,request:i,response:void 0}}for(const e of n.response.fns)e&&(c=await e(c,i,t));const l={request:i,response:c};if(c.ok){const e=("auto"===t.parseAs?(e=>{if(!e)return"stream";const t=e.split(";")[0]?.trim();return t?t.startsWith("application/json")||t.endsWith("+json")?"json":"multipart/form-data"===t?"formData":["application/","audio/","image/","video/"].some(e=>t.startsWith(e))?"blob":t.startsWith("text/")?"text":void 0:void 0})(c.headers.get("Content-Type")):t.parseAs)??"json";if(204===c.status||"0"===c.headers.get("Content-Length")){let r;switch(e){case"arrayBuffer":case"blob":case"text":r=await c[e]();break;case"formData":r=new FormData;break;case"stream":r=c.body;break;default:r={}}return"data"===t.responseStyle?r:{data:r,...l}}let r;switch(e){case"arrayBuffer":case"blob":case"formData":case"json":case"text":r=await c[e]();break;case"stream":return"data"===t.responseStyle?c.body:{data:c.body,...l}}return"json"===e&&(t.responseValidator&&await t.responseValidator(r),t.responseTransformer&&(r=await t.responseTransformer(r))),"data"===t.responseStyle?r:{data:r,...l}}const u=await c.text();let d;try{d=JSON.parse(u)}catch{}const p=d??u;let f=p;for(const e of n.error.fns)e&&(f=await e(p,c,i,t));if(f=f||{},t.throwOnError)throw f;return"data"===t.responseStyle?void 0:{error:f,...l}},i=e=>t=>s({...t,method:e}),a=e=>async t=>{const{opts:r,url:s}=await o(t);return(({onRequest:e,onSseError:t,onSseEvent:r,responseTransformer:n,responseValidator:o,sseDefaultRetryDelay:s,sseMaxRetryAttempts:i,sseMaxRetryDelay:a,sseSleepFn:c,url:l,...u})=>{let d;const p=c??(e=>new Promise(t=>setTimeout(t,e)));return{stream:async function*(){let c=s??3e3,f=0;const h=u.signal??(new AbortController).signal;for(;!h.aborted;){f++;const s=u.headers instanceof Headers?u.headers:new Headers(u.headers);void 0!==d&&s.set("Last-Event-ID",d);try{const t={redirect:"follow",...u,body:u.serializedBody,headers:s,signal:h};let i=new Request(l,t);e&&(i=await e(l,t));const a=u.fetch??globalThis.fetch,p=await a(i);if(!p.ok)throw new Error(`SSE failed: ${p.status} ${p.statusText}`);if(!p.body)throw new Error("No body in SSE response");const f=p.body.pipeThrough(new TextDecoderStream).getReader();let m="";const g=()=>{try{f.cancel()}catch{}};h.addEventListener("abort",g);try{for(;;){const{done:e,value:t}=await f.read();if(e)break;m+=t;const s=m.split("\n\n");m=s.pop()??"";for(const e of s){const t=e.split("\n"),s=[];let i,a;for(const e of t)if(e.startsWith("data:"))s.push(e.replace(/^data:\s*/,""));else if(e.startsWith("event:"))i=e.replace(/^event:\s*/,"");else if(e.startsWith("id:"))d=e.replace(/^id:\s*/,"");else if(e.startsWith("retry:")){const t=Number.parseInt(e.replace(/^retry:\s*/,""),10);Number.isNaN(t)||(c=t)}let l=!1;if(s.length){const e=s.join("\n");try{a=JSON.parse(e),l=!0}catch{a=e}}l&&(o&&await o(a),n&&(a=await n(a))),r?.({data:a,event:i,id:d,retry:c}),s.length&&(yield a)}}}finally{h.removeEventListener("abort",g),f.releaseLock()}break}catch(e){if(t?.(e),void 0!==i&&f>=i)break;const r=Math.min(c*2**(f-1),a??3e4);await p(r)}}}()}})({...r,body:r.body,headers:r.headers,method:e,onRequest:async(e,t)=>{let o=new Request(e,t);for(const e of n.request.fns)e&&(o=await e(o,r));return o},url:s})};return{buildUrl:Dr,connect:i("CONNECT"),delete:i("DELETE"),get:i("GET"),getConfig:r,head:i("HEAD"),interceptors:n,options:i("OPTIONS"),patch:i("PATCH"),post:i("POST"),put:i("PUT"),request:s,setConfig:e=>(t=Or(t,e),r()),sse:{connect:a("CONNECT"),delete:a("DELETE"),get:a("GET"),head:a("HEAD"),options:a("OPTIONS"),patch:a("PATCH"),post:a("POST"),put:a("PUT"),trace:a("TRACE")},trace:i("TRACE")}},Gr=Fr(Hr({baseUrl:"https://api.stably.ai"})),Yr="4.6.3",Wr=process.env.STABLY_API_URL||"https://api.stably.ai",Vr=e=>{const t=new URL(e);return t.protocol="http:"===t.protocol?"ws:":"wss:",t},zr=process.env.AUTH_URL||"https://auth.stably.ai",Kr=process.env.AUTH_CLIENT_ID||"288007877071cce81f269428ea78653a",qr=process.env.AI_PROXY_URL||"https://ai-proxy.stably.ai",Jr=process.env.STABLY_AUTOHEAL_WS_URL||new URL("/autoheal",Vr(Wr)).toString(),Xr=process.env.STABLY_CREATE_PROGRESS_WS_URL||new URL("/create-progress",Vr(Wr)).toString(),Qr="http://localhost:9876/auth/callback",Zr=()=>Pr||(Pr=Fr(Hr({baseUrl:Wr,headers:{"X-STABLY-CLI-VERSION":Yr,"X-STABLY-SOURCE":"cli"}}))),en=async(e,t)=>{const r=await(n={body:{accessToken:e,orgId:t},client:Zr()},(n.client??Gr).post({url:"/internal/v1/cli/exchange-token",...n,headers:{"Content-Type":"application/json",...n.headers}}));var n;if(401===r.response.status)throw new Error("Invalid or expired access token");if(403===r.response.status)throw new Error("You do not have access to this organization");if(r.error)throw new Error(`Failed to exchange token: ${r.response.status}`);return r.data},tn=le.object({org_id:le.string(),org_name:le.string()}),rn=le.object({email:le.string(),org_id_to_org_member_info:le.record(le.string(),tn).optional(),org_member_info:tn.optional(),user_id:le.string()});le.object({email:le.string(),firstName:le.string().optional(),lastName:le.string().optional(),organizations:le.array(le.object({id:le.string(),name:le.string()})),userId:le.string()});var nn=e=>{const t=e.split(".");if(3!==t.length)throw new Error("Invalid JWT format");const r=t[1].replace(/-/g,"+").replace(/_/g,"/"),n=Buffer.from(r,"base64").toString("utf-8");return JSON.parse(n)},on=e=>{try{const t=rn.parse(nn(e)),r=t.org_id_to_org_member_info?Object.entries(t.org_id_to_org_member_info).map(([e,t])=>({id:e,name:t.org_name})):t.org_member_info?[{id:t.org_member_info.org_id,name:t.org_member_info.org_name}]:[];return{email:t.email,organizations:r,userId:t.user_id}}catch(e){throw new Error(`Failed to decode token: ${e instanceof Error?e.message:"Unknown error"}`)}},sn=async(e,t)=>{let n=e;const{root:o}=r.parse(n);for(;n!==o;){const e=r.join(n,t);try{return await J(e),e}catch{n=r.dirname(n)}}},an=r.join(R.homedir(),".stably"),cn=r.join(an,"auth.json"),ln=".stably",un="project.json",dn=ce.object({accessToken:ce.string(),expiresAt:ce.number(),idToken:ce.string().optional(),refreshToken:ce.string()}),pn=ce.object({orgId:ce.string(),orgName:ce.string(),projectId:ce.string(),projectName:ce.string()}),fn=async()=>{try{const e=await V(cn,"utf-8");return dn.parse(JSON.parse(e))}catch{return}},hn=async e=>{await z(an,{recursive:!0}),await K(cn,JSON.stringify(e,null,2),{mode:384})},mn=async()=>{try{await q(cn)}catch{}},gn=async()=>{try{const e=await sn(process.cwd(),ln);if(!e)return;const t=r.join(e,un),n=await V(t,"utf-8");return pn.parse(JSON.parse(n))}catch{return}},yn=async()=>{try{const e=await sn(process.cwd(),ln);e&&await q(r.join(e,un))}catch{}},bn=e=>Date.now()>=e.expiresAt-3e5,wn=async e=>{const t=new URLSearchParams({client_id:Kr,grant_type:"refresh_token",refresh_token:e}),r=await fetch(`${zr}/propelauth/oauth/token`,{body:t.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},method:"POST"});if(!r.ok)throw new Error(`Token refresh failed: ${r.status}`);const n=await r.json();return{accessToken:n.access_token,expiresAt:Date.now()+1e3*n.expires_in,refreshToken:n.refresh_token}},vn=e=>`\n<!DOCTYPE html>\n<html>\n<head>\n <title>Authentication Failed Stably CLI</title>\n <style>\n * { box-sizing: border-box; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n display: flex;\n justify-content: center;\n align-items: center;\n min-height: 100vh;\n margin: 0;\n background: #000;\n color: #fafafa;\n }\n .container {\n text-align: center;\n padding: 48px;\n max-width: 400px;\n }\n .icon {\n width: 48px;\n height: 48px;\n border-radius: 50%;\n background: #ef4444;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 24px;\n }\n .icon svg { width: 24px; height: 24px; }\n .title {\n font-size: 24px;\n font-weight: 600;\n margin: 0 0 8px;\n letter-spacing: -0.5px;\n }\n .subtitle {\n color: #888;\n font-size: 14px;\n margin: 0 0 32px;\n line-height: 1.5;\n }\n .error-box {\n background: rgba(239, 68, 68, 0.1);\n border: 1px solid rgba(239, 68, 68, 0.3);\n border-radius: 8px;\n padding: 16px;\n margin-bottom: 24px;\n }\n .error-label {\n font-size: 11px;\n font-weight: 600;\n color: #ef4444;\n text-transform: uppercase;\n letter-spacing: 0.5px;\n margin-bottom: 8px;\n }\n .error-message {\n font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace;\n font-size: 13px;\n color: #fafafa;\n word-break: break-word;\n }\n .hint {\n color: #666;\n font-size: 13px;\n }\n .hint code {\n background: #111;\n border: 1px solid #333;\n border-radius: 4px;\n padding: 2px 6px;\n font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace;\n font-size: 12px;\n color: #888;\n }\n .brand {\n margin-top: 32px;\n font-size: 12px;\n color: #444;\n letter-spacing: 0.5px;\n }\n </style>\n</head>\n<body>\n <div class="container">\n <div class="icon">\n <svg fill="none" stroke="#000" stroke-width="3" viewBox="0 0 24 24">\n <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/>\n </svg>\n </div>\n <h1 class="title">Authentication Failed</h1>\n <p class="subtitle">Something went wrong during login.</p>\n <div class="error-box">\n <div class="error-label">Error</div>\n <div class="error-message">${e}</div>\n </div>\n <p class="hint">Run <code>stably login</code> to try again.</p>\n <div class="brand">STABLY</div>\n </div>\n</body>\n</html>\n`,_n=(e,t,r)=>{e.writeHead(t,{"Content-Type":"text/html"}),e.end(r)},En=(e,t)=>{const r=new URLSearchParams({client_id:Kr,code_challenge:e,code_challenge_method:"S256",redirect_uri:Qr,response_type:"code",state:t});return`${zr}/propelauth/oauth/authorize?${r.toString()}`},In=async e=>{const t=ne();let n;t.start("Loading user info...");try{n=on(e.accessToken),t.stop(G.green(`✓ Logged in as ${G.cyan(n.email)}`))}catch(e){t.stop(G.red("✗ Failed to load user info"));const r=e instanceof Error?e.message:"Unknown error";return te.error(r),{success:!1}}const o=await(async e=>{if(0===e.length)return void te.error("You don't belong to any organizations.");if(1===e.length)return te.info(`Using organization: ${G.cyan(e[0].name)}`),e[0];if(!process.stdin.isTTY)return te.info(`Auto-selecting organization: ${G.cyan(e[0].name)}`),e[0];const t=await se({message:"Select an organization",options:[...e].sort((e,t)=>e.name.localeCompare(t.name)).map(e=>({label:e.name,value:e.id}))});return ie(t)?void 0:e.find(e=>e.id===t)})(n.organizations);if(!o)return te.warn("Organization selection cancelled."),{success:!1};let s;t.start("Getting org credentials...");try{const r=await en(e.accessToken,o.id);s={accessToken:r.accessToken,expiresAt:Date.now()+1e3*r.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken},t.stop(G.green("✓ Credentials obtained"))}catch(e){t.stop(G.red("✗ Failed to get org credentials"));const r=e instanceof Error?e.message:"Unknown error";return te.error(r),{success:!1}}const i=await(async(e,t)=>{const r=ne();let n;r.start("Loading projects...");try{n=await(async({accessToken:e,orgId:t})=>{const r=await(n={auth:e,client:Zr(),path:{orgId:t}},(n.client??Gr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/orgs/{orgId}/projects",...n}));var n;if(401===r.response.status)throw new Error("Invalid or expired access token");if(403===r.response.status)throw new Error("You do not have access to this organization");if(r.error)throw new Error(`Failed to list projects: ${r.response.status}`);return r.data.projects})({accessToken:e,orgId:t}),r.stop(G.green("✓ Projects loaded"))}catch(e){r.stop(G.red("✗ Failed to load projects"));const t=e instanceof Error?e.message:"Unknown error";return void te.error(t)}if(0===n.length)return te.error("No projects found in this organization."),void te.info(`Create a project at ${G.underline(G.cyan("https://app.stably.ai"))}`);if(1===n.length)return te.info(`Using project: ${G.cyan(n[0].name)}`),n[0];if(!process.stdin.isTTY)return te.info(`Auto-selecting project: ${G.cyan(n[0].name)}`),n[0];const o=await se({message:"Select a project",options:n.map(e=>({label:e.name,value:e.id}))});return ie(o)?void 0:n.find(e=>e.id===o)})(s.accessToken,o.id);return i?(await(async e=>{const t=r.join(process.cwd(),ln),n=r.join(t,un);await z(t,{recursive:!0}),await K(n,JSON.stringify(e,null,2)),await(async e=>{const t=r.join(e,".gitignore"),n="# Stably CLI (only docs/ are tracked)\n.stably/*\n!.stably/docs/";try{const e=await V(t,"utf-8"),r=e.split("\n").map(e=>e.trim());if(r.includes(".stably/*")&&r.includes("!.stably/docs/"))return;const o=/^# Stably CLI\n\.stably\/?$/m,s=/^\.stably\/?$/m;if(o.test(e)){const r=e.replace(o,`\n${n}\n`);await K(t,r)}else if(s.test(e)){const r=e.replace(s,`\n${n}\n`);await K(t,r)}else await ee(t,`\n${n}\n`)}catch{await K(t,`${n}\n`)}})(process.cwd())})({orgId:o.id,orgName:o.name,projectId:i.id,projectName:i.name}),te.info(G.dim("Linked this directory to your Stably project.")),{scopedTokens:s,success:!0}):(te.warn("Project selection cancelled."),{success:!1})},Tn=async()=>{if(Yn())return te.warn(`Environment variables ${G.cyan("STABLY_API_KEY")} and ${G.cyan("STABLY_PROJECT_ID")} are set.`),te.warn("These will be used for authentication instead of OAuth login."),te.warn("To use OAuth login, unset these environment variables first."),void re(G.yellow("Login skipped - using environment variable authentication."));const e=await fn();if(e){if(!bn(e)){if(await gn())return void re(G.yellow("You are already logged in. Run `stably logout` first to log out."));te.info("You are logged in but haven't selected a project yet.");const t=await In(e);return void(t.success?(await hn(t.scopedTokens),re(G.green("Setup complete! You can now use Stably CLI."))):re(G.yellow("Setup incomplete. Run `stably login` to try again.")))}const t=ne();t.start("Refreshing session...");try{const r=await wn(e.refreshToken);t.stop(G.green("✓ Session refreshed"));const n=await gn();if(n){t.start("Getting org credentials...");try{const e=await en(r.accessToken,n.orgId),o={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:r.idToken,refreshToken:r.refreshToken};await hn(o),t.stop(G.green("✓ Credentials obtained")),re(G.green("Login successful"))}catch{await hn(r),t.stop(G.yellow("Using full credentials")),re(G.green("Login successful"))}}else{const e=await In(r);e.success?(await hn(e.scopedTokens),re(G.green("Setup complete! You can now use Stably CLI."))):re(G.yellow("Setup incomplete. Run `stably login` to try again."))}return}catch{t.stop(G.yellow("Session expired, proceeding with fresh login...")),await mn(),await yn()}}const{authorizeUrl:t,serverReady:r,waitForCallback:n}=(()=>{const{authorizeUrl:e,codeVerifier:t,state:r}=(()=>{const e=H.randomBytes(32).toString("base64url"),t=(r=e,H.createHash("sha256").update(r).digest("base64url"));var r;const n=H.randomBytes(16).toString("base64url");return{authorizeUrl:En(t,n),codeVerifier:e,state:n}})(),{ready:n,result:o}=(e=>{let t,r;return{ready:new Promise((e,n)=>{t=e,r=n}),result:new Promise((n,o)=>{const s=setTimeout(()=>{a.close(),n({error:"Login timed out",success:!1})},3e5),i=()=>{clearTimeout(s)},a=de.createServer((t,r)=>{const o=new C(t.url||"","http://localhost:9876");if("/auth/callback"!==o.pathname)return r.writeHead(404),void r.end("Not found");const s=o.searchParams.get("code"),c=o.searchParams.get("state"),l=o.searchParams.get("error");return l?(_n(r,400,vn(l)),i(),a.close(),void n({error:l,success:!1})):s&&c?c!==e?(_n(r,400,vn("Invalid state parameter (possible CSRF attack)")),i(),a.close(),void n({error:"State mismatch",success:!1})):(_n(r,200,'\n<!DOCTYPE html>\n<html>\n<head>\n <title>Authenticated Stably CLI</title>\n <style>\n * { box-sizing: border-box; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, sans-serif;\n display: flex;\n justify-content: center;\n align-items: center;\n min-height: 100vh;\n margin: 0;\n background: #000;\n color: #fafafa;\n }\n .container {\n text-align: center;\n padding: 48px;\n max-width: 400px;\n }\n .icon {\n width: 48px;\n height: 48px;\n border-radius: 50%;\n background: #22c55e;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 24px;\n }\n .icon svg { width: 24px; height: 24px; }\n .title {\n font-size: 24px;\n font-weight: 600;\n margin: 0 0 8px;\n letter-spacing: -0.5px;\n }\n .subtitle {\n color: #888;\n font-size: 14px;\n margin: 0 0 32px;\n line-height: 1.5;\n }\n .terminal {\n background: #111;\n border: 1px solid #333;\n border-radius: 8px;\n padding: 16px;\n text-align: left;\n font-family: \'SF Mono\', \'Fira Code\', \'Consolas\', monospace;\n font-size: 13px;\n }\n .terminal-header {\n display: flex;\n gap: 6px;\n margin-bottom: 12px;\n }\n .terminal-dot {\n width: 10px;\n height: 10px;\n border-radius: 50%;\n background: #333;\n }\n .terminal-line {\n color: #888;\n }\n .terminal-line .prompt { color: #888; }\n .terminal-line .cmd { color: #fafafa; }\n .terminal-line.success { color: #22c55e; }\n .brand {\n margin-top: 32px;\n font-size: 12px;\n color: #444;\n letter-spacing: 0.5px;\n }\n </style>\n</head>\n<body>\n <div class="container">\n <div class="icon">\n <svg fill="none" stroke="#000" stroke-width="3" viewBox="0 0 24 24">\n <path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/>\n </svg>\n </div>\n <h1 class="title">Authenticated</h1>\n <p class="subtitle">You can close this tab and return to your terminal.</p>\n <div class="terminal">\n <div class="terminal-header">\n <div class="terminal-dot"></div>\n <div class="terminal-dot"></div>\n <div class="terminal-dot"></div>\n </div>\n <div class="terminal-line"><span class="prompt">$</span> <span class="cmd">stably login</span></div>\n <div class="terminal-line success">Logged in successfully</div>\n </div>\n <div class="brand">STABLY</div>\n </div>\n</body>\n</html>\n'),i(),a.close(),void n({code:s,state:c,success:!0})):(_n(r,400,vn("Missing code or state parameter")),i(),a.close(),void n({error:"Missing code or state parameter",success:!1}))});a.on("error",e=>{if(i(),"EADDRINUSE"===e.code){const e=new Error("Port 9876 is already in use. Please close the application using it and try again.");return r(e),void o(e)}const t=new Error(`Failed to start callback server: ${e.message}`);r(t),o(t)}),a.listen(9876,()=>{t()})})}})(r);return{authorizeUrl:e,serverReady:n,waitForCallback:async()=>{const e=await o;if(!e.success)throw new Error(e.error);return(async(e,t)=>{const r=new URLSearchParams({client_id:Kr,code:e,code_verifier:t,grant_type:"authorization_code",redirect_uri:Qr}),n=await fetch(`${zr}/propelauth/oauth/token`,{body:r.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},method:"POST"});if(!n.ok){const e=await n.text();throw new Error(`Token exchange failed: ${n.status} ${e}`)}const o=await n.json();return{accessToken:o.access_token,expiresAt:Date.now()+1e3*o.expires_in,idToken:o.id_token,refreshToken:o.refresh_token}})(e.code,t)}}})();await r,te.info("Opening browser for authentication..."),te.info(G.dim("If browser doesn't open, visit:")),te.info(`]8;;${t}${G.underline(G.cyan(t))}]8;;`);try{await ue(t)}catch{te.warn("Could not open browser automatically. Please open the URL above manually.")}const o=ne();let s;o.start("Waiting for authentication...");try{s=await n(),o.stop(G.green("✓ Authentication successful"))}catch(e){o.stop(G.red("✗ Authentication failed"));const t=e instanceof Error?e.message:"Unknown error";re(G.red(`Login failed: ${t}`)),process.exit(1)}const i=await In(s);i.success?(await hn(i.scopedTokens),re(G.green("Setup complete! You can now use Stably CLI."))):(re(G.yellow("Setup incomplete. Run `stably login` to try again.")),process.exit(1))},xn={fatal:60,error:50,warn:40,info:30,debug:20,trace:10},Sn=new Set(["help","login","logout","whoami","tunnel","create","fix","init","upgrade","test","show-report","codegen"]),An=(new Date).toISOString().split("T")[0],Cn=r.join(R.tmpdir(),"stably-logs",An);m.mkdirSync(Cn,{recursive:!0});var Rn,Pn=process.argv.includes("--verbose")||process.argv.includes("-v"),Un=process.env.STABLY_LOG_LEVEL?.toLowerCase(),kn=Pn?"debug":void 0!==(Rn=Un)&&Rn in xn?Un:"warn",Ln=xn[kn],Dn=null,On=null,Bn=null,Nn=[],$n=!1,Mn=e=>{if(!$n){Dn=(e=>{const t=(()=>{const e=new Date;return[e.getHours().toString().padStart(2,"0"),e.getMinutes().toString().padStart(2,"0"),e.getSeconds().toString().padStart(2,"0")].join("-")})(),n=((e,t=100)=>e.replace(/[/\\:*?"<>|]/g,"-").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9\-_]/g,"").replace(/-+/g,"-").replace(/^-+|-+$/g,"").slice(0,t).toLowerCase()||"session")(e);return r.join(Cn,`${t}-${n}.log`)})(e),(e=>{const t=["","=".repeat(60),"Stably CLI Debug Log",`Version: ${Yr}`,`Generated: ${(new Date).toISOString()}`,`Node: ${process.version}`,`Platform: ${process.platform} ${R.release()}`,`CWD: ${process.cwd()}`,`Args: ${process.argv.slice(2).join(" ")}`,`Log Level (console): ${kn}`,"=".repeat(60),""].join("\n");e.write(t)})(On=new fe({dest:Dn,minLength:4096,sync:!1,append:!0})),Bn=pe({level:"debug",timestamp:pe.stdTimeFunctions.isoTime,base:{version:Yr}},On);for(const{level:e,msg:t,context:r}of Nn)r?Bn[e](r,t):Bn[e](t);Nn=[],$n=!0,Pn&&process.stderr.write(`${G.dim(`Debug log: ${Dn}`)}\n\n`)}},jn=(()=>{const e=process.argv.slice(2).find(e=>!e.startsWith("-"));return e&&Sn.has(e)?e:null})();jn&&Mn(jn);var Hn=e=>(t,r)=>{if(Bn?r?Bn[e](r,t):Bn[e](t):Nn.push({level:e,msg:t,context:r}),(e=>xn[e]>=Ln)(e)){const r=((e,t)=>`${{fatal:G.bgRed(G.white(" FATAL ")),error:G.red("error"),warn:G.yellow("warn"),info:G.cyan("info"),debug:G.dim("debug"),trace:G.dim("trace")}[e]} ${t}`)(e,t);process.stderr.write(`${r}\n`)}},Fn={fatal:Hn("fatal"),error:Hn("error"),warn:Hn("warn"),info:Hn("info"),debug:Hn("debug"),trace:Hn("trace"),initSession:e=>{$n||Mn(e)},getLogFilePath:()=>Dn,flush:()=>{if(On)try{On.flushSync()}catch{}},printLogFileInfo:()=>{Dn&&(process.stderr.write(`\n${G.dim("Debug log written to:")}\n`),process.stderr.write(` ${G.cyan(Dn)}\n`),process.stderr.write(`${G.dim("Share this file with support for assistance.")}\n`))},getPinoLogger:()=>Bn};setInterval(()=>{Fn.flush()},3e4).unref(),process.on("beforeExit",()=>{Fn.flush()});var Gn=e=>{const t=()=>{Fn.flush(),Pn&&Fn.printLogFileInfo(),process.removeListener(e,t),process.kill(process.pid,e)};return t};process.on("SIGINT",Gn("SIGINT")),process.on("SIGTERM",Gn("SIGTERM"));var Yn=()=>{const e=process.env.STABLY_API_KEY?.trim(),t=process.env.STABLY_PROJECT_ID?.trim();if(e&&t)return Fn.debug("Environment auth detected",{hasApiKey:!0,hasProjectId:!0}),{apiKey:e,projectId:t};Fn.debug("Environment auth not set",{hasApiKey:!!e,hasProjectId:!!t})},Wn=!1,Vn=()=>{Wn||(Wn=!0,te.warn("Both environment variable auth and stored OAuth login were detected."),te.warn(`Honoring environment variables (${G.cyan("STABLY_API_KEY")} + ${G.cyan("STABLY_PROJECT_ID")}).`),te.warn("To use OAuth login instead, unset those environment variables."))},zn=async()=>{Fn.debug("Checking for stored auth tokens");const e=await fn();if(!e)return void Fn.debug("No stored auth tokens found");const t=bn(e);if(Fn.debug("Auth tokens status",{expired:t}),!t){const t=await gn(),r=(e=>{try{const t=rn.parse(nn(e));if(t.org_id_to_org_member_info)return"full";if(t.org_member_info)return"org"}catch{return"unknown"}return"unknown"})(e.accessToken);if(Fn.debug("Token scope check",{scope:r,hasContext:!!t}),t&&"full"===r)try{Fn.debug("Exchanging full token for org-scoped token",{orgId:t.orgId});const r=await en(e.accessToken,t.orgId),n={accessToken:r.accessToken,expiresAt:Date.now()+1e3*r.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken};return await hn(n),Fn.debug("Token exchange successful"),n}catch(t){return Fn.debug("Token exchange failed, using existing token",{error:t instanceof Error?t.message:String(t)}),e}return e}try{Fn.debug("Attempting token refresh");const t=await wn(e.refreshToken);Fn.debug("Token refresh successful");const r=await gn();if(r)try{Fn.debug("Exchanging refreshed token for org-scoped token");const e=await en(t.accessToken,r.orgId),n={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:t.idToken,refreshToken:t.refreshToken};return await hn(n),n}catch{return await hn(t),t}return await hn(t),t}catch(e){return void Fn.warn("Token refresh failed",{error:e instanceof Error?e.message:String(e)})}},Kn=async(e={})=>{Fn.debug("Requiring authentication",{autoLogin:e.autoLogin});const t=Yn();if(t){Fn.info("Using environment variable authentication");try{await fn()&&Vn()}catch{}return{auth:t,type:"env"}}let r=await zn(),n=r?await gn():void 0;const o=process.stdin.isTTY&&process.stdout.isTTY;if(Fn.debug("OAuth auth check",{hasTokens:!!r,hasContext:!!n,canPrompt:o}),(!r||!n)&&e.autoLogin&&o){Fn.info("Prompting user to login"),r?te.info("You are logged in but need to select an organization and project."):te.info("You are not logged in."),te.info("Press Enter to log in."),process.stdout.write(`${G.dim("Alternatively, set environment variables for an org API key:")}\n${G.dim(" STABLY_API_KEY=... STABLY_PROJECT_ID=... stably")}\n`),process.stdout.write("\n");const e=ae({input:process.stdin,output:process.stdout});try{await e.question(G.dim("Press Enter to continue... "))}finally{e.close()}await Tn(),r=await zn(),n=r?await gn():void 0}return r||(Fn.warn("Authentication required but no tokens available"),re(G.red("You are not logged in. Run `stably login` to authenticate.")),process.exit(1)),n||(Fn.warn("Authentication succeeded but no project context selected"),re(G.red("You haven't selected an organization and project. Run `stably login` to complete setup.")),process.exit(1)),Fn.info("OAuth authentication successful",{orgId:n.orgId,projectId:n.projectId}),{auth:{accessToken:r.accessToken,context:n},type:"oauth"}},qn=e=>"env"===e.type?e.auth.projectId:e.auth.context.projectId,Jn=e=>e?{...process.env,...e}:process.env,Xn=async()=>{Fn.info("[test] Resolving Stably test env");const e=(()=>{if(process.env.STABLY_WS_URL)return;if("https://api.stably.ai"===Wr)return;const e=Wr.startsWith("http://")?"ws://":"wss://";return`${Wr.replace(/^https?:\/\//,e).replace(/\/$/,"")}/reporter`})();Fn.debug("[test] WebSocket URL resolved",{wsUrl:e??"(default)"});const t=Yn();if(t)return Fn.info("[test] Using env var auth (STABLY_API_KEY + STABLY_PROJECT_ID)"),{STABLY_API_KEY:t.apiKey,STABLY_PROJECT_ID:t.projectId,...e&&{STABLY_WS_URL:e}};Fn.info("[test] No env var auth, attempting OAuth auth");const r=Date.now(),n=await(async()=>{const e=Yn();if(e){try{await fn()&&Vn()}catch{}return{auth:e,type:"env"}}const t=await zn(),r=t?await gn():void 0;if(t&&r)return{auth:{accessToken:t.accessToken,context:r},type:"oauth"}})();if(Fn.info("[test] OAuth auth resolved",{durationMs:Date.now()-r,hasAuth:!!n,authType:n?.type}),!n||"env"===n.type)return void Fn.info("[test] No usable auth found");const o=process.env.STABLY_PROJECT_ID?.trim(),s=o||qn(n);if(!s)return void Fn.warn("[test] No project ID available");Fn.info("[test] Fetching JWT API key",{projectId:s});const i=Date.now(),a=await(async(e,t)=>{try{Fn.debug("Requesting JWT API key",{projectId:t,apiUrl:Wr});const r=await(async({accessToken:e,projectId:t})=>{const r=await(n={auth:e,client:Zr(),path:{projectId:t}},(n.client??Gr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/api-key",...n}));var n;if(r.error){const e=r.error?.error,{status:t}=r.response;throw new Error(e??`Failed to get API key: ${t}`)}return r.data})({accessToken:e,projectId:t});return Fn.debug("JWT API key obtained",{keyPrefix:r.apiKey.substring(0,10)}),r.apiKey}catch(e){return void Fn.warn("Failed to get JWT API key for test reporter",{error:e instanceof Error?e.message:String(e)})}})(n.auth.accessToken,s);Fn.info("[test] JWT API key fetch complete",{durationMs:Date.now()-i,success:!!a});const c=a?{STABLY_API_KEY:a,STABLY_PROJECT_ID:s,...e&&{STABLY_WS_URL:e}}:void 0;return Fn.info("[test] Stably test env resolved",{hasApiKey:!!c?.STABLY_API_KEY,projectId:c?.STABLY_PROJECT_ID,wsUrl:c?.STABLY_WS_URL??process.env.STABLY_WS_URL??"(default)"}),c},Qn=e=>e?{[Ir]:e}:void 0,Zn=le.object({context:le.string().min(1),autohealReportUrl:le.string(),skippedTests:le.array(le.object({testIdentifier:le.string(),testTitle:le.string(),consecutiveUnfixedCount:le.number()})).optional()}),eo=he.object({bucket:he.string(),key:he.string()}),to=he.object({diffBucketPath:eo,expiresInSeconds:he.number(),key:he.string(),uploadUrl:he.string()}),ro=he.object({traceBucketPath:eo,expiresInSeconds:he.number(),key:he.string(),uploadUrl:he.string(),sensitiveValues:he.array(he.string())}),no=async({authHeader:e,contentType:t="text/plain",orgId:r,runId:n})=>{const o=await(s={auth:e,body:{contentType:t},client:Zr(),headers:Qn(r),path:{runId:n}},(s.client??Gr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-diff/upload-url",...s,headers:{"Content-Type":"application/json",...s.headers}}));var s;if(o.error)throw new Error(`Failed to presign diff upload (${o.response.status})`);const i=to.parse(o.data);return{diffBucketPath:i.diffBucketPath,expiresInSeconds:i.expiresInSeconds,key:i.key,uploadUrl:i.uploadUrl}},oo=async({contentType:e="text/plain",diff:t,uploadUrl:r})=>{const n=await fetch(r,{body:t,headers:{"Content-Type":e},method:"PUT"});if(!n.ok)throw new Error(`Failed to upload diff (${n.status})`)},so=async({authHeader:e,diffBucketPath:t,orgId:r,runId:n})=>{const o=(Zr().getConfig().baseUrl??"").replace(/\/$/,""),s=await fetch(`${o}/internal/v1/cli/runs/${encodeURIComponent(n)}/autoheal-diff/confirm-upload`,{method:"POST",headers:{"Content-Type":"application/json",...Qn(r),authorization:e},body:JSON.stringify(t)});if(!s.ok)throw new Error(`Failed to confirm diff upload (${s.status})`)},io=class{socket;url;authHeader;orgId;runId;pendingEvent=null;reconnectAttempts=0;reconnectTimer;debounceTimer;_isClosed=!1;isAuthenticated=!1;authenticationFailed=!1;onUserMessage;maxReconnectAttempts=3;reconnectDelay=2e3;debounceMs=500;get isClosed(){return this._isClosed}constructor({authHeader:e,orgId:t,runId:r,url:n=Jr,onUserMessage:o}){this.authHeader=e,this.orgId=t,this.runId=r,this.url=n,this.onUserMessage=o,Fn.info("[ws] Constructing AutohealWebSocketClient",{url:this.url,runId:r})}start(){this.connect()}connect(){if(!this._isClosed)try{const e={Authorization:this.authHeader};this.orgId&&(e["x-stably-org-id"]=this.orgId);const t=`${this.url}?runId=${encodeURIComponent(this.runId)}`;Fn.info("[ws] Connecting",{url:t,attempt:this.reconnectAttempts}),this.socket=new me(t,{headers:e}),this.socket.on("open",()=>{Fn.info("[ws] Connection opened"),this.reconnectAttempts=0}),this.socket.on("message",e=>{try{const t="string"==typeof e?e:e.toString(),r=JSON.parse(t);Fn.debug("[ws] Received message",{type:r?.type}),"connected"===r?.type&&(Fn.info("[ws] Authenticated successfully"),this.isAuthenticated=!0,this.authenticationFailed=!1,this.flushPending()),"user_message"===r?.type&&"string"==typeof r.content&&(Fn.info("[ws] Received user message from web UI"),this.onUserMessage?.(r.content))}catch{}}),this.socket.on("close",(e,t)=>{Fn.info("[ws] Connection closed",{code:e,authFailed:1008===e,reconnectAttempts:this.reconnectAttempts,maxReconnect:this.maxReconnectAttempts,isClosed:this._isClosed}),this.isAuthenticated=!1,1008===e&&(this.authenticationFailed=!0),!this._isClosed&&!this.authenticationFailed&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()}),this.socket.on("error",e=>{Fn.warn("[ws] Connection error",{error:e.message})})}catch(e){Fn.warn("[ws] Failed to create WebSocket",{error:e instanceof Error?e.message:String(e)}),this.scheduleReconnect()}}scheduleReconnect(){this._isClosed||this.reconnectTimer||(this.reconnectAttempts++,Fn.info("[ws] Scheduling reconnect",{attempt:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts,delayMs:this.reconnectDelay}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect()},this.reconnectDelay))}isConnected(){return!!this.socket&&this.socket.readyState===me.OPEN&&this.isAuthenticated}sendProgress(e){if(this._isClosed)return void Fn.debug("[ws] sendProgress called but client is closed",{phase:e.phase});const t={type:"autoheal_progress",payload:e};return this.pendingEvent=t,this.isConnected()?"complete"===e.phase?(Fn.info("[ws] sendProgress: flushing terminal state immediately"),void this.flushPending()):void(this.debounceTimer||(this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.flushPending()},this.debounceMs))):(Fn.debug("[ws] sendProgress: not connected, queuing event",{phase:e.phase,socketState:this.socket?.readyState,isAuthenticated:this.isAuthenticated,reconnectAttempts:this.reconnectAttempts}),void(this.socket?.readyState===me.CLOSED&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()))}flushPending(){if(this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),!this.pendingEvent)return;const e=this.pendingEvent;if(this.pendingEvent=null,!this.isConnected())return Fn.debug("[ws] flushPending: not connected, re-queuing event",{phase:e.payload.phase}),void(this.pendingEvent=e);try{Fn.debug("[ws] flushPending: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),t=>{t&&(Fn.warn("[ws] flushPending: send failed",{error:t.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e))})}catch(t){Fn.warn("[ws] flushPending: send threw",{error:t instanceof Error?t.message:String(t)}),this.pendingEvent=e}}close(){if(this._isClosed)return;Fn.info("[ws] Closing WebSocket client"),this._isClosed=!0,this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.flushPending();const{socket:e}=this;this.socket=void 0,e&&setTimeout(()=>{e.close()},200)}},ao=class{socket;url;authHeader;orgId;sessionId;pendingEvent=null;reconnectAttempts=0;reconnectTimer;debounceTimer;_isClosed=!1;isAuthenticated=!1;authenticationFailed=!1;onUserMessage;maxReconnectAttempts=3;reconnectDelay=2e3;debounceMs=500;get isClosed(){return this._isClosed}constructor({authHeader:e,orgId:t,sessionId:r,url:n=Xr,onUserMessage:o}){this.authHeader=e,this.orgId=t,this.sessionId=r,this.url=n,this.onUserMessage=o,Fn.info("[ws] Constructing CreateProgressWebSocketClient",{url:this.url,sessionId:r})}start(){this.connect()}connect(){if(!this._isClosed)try{const e={Authorization:this.authHeader};this.orgId&&(e["x-stably-org-id"]=this.orgId);const t=`${this.url}?sessionId=${encodeURIComponent(this.sessionId)}`;Fn.info("[ws] Connecting",{url:t,attempt:this.reconnectAttempts}),this.socket=new me(t,{headers:e}),this.socket.on("open",()=>{Fn.info("[ws] Connection opened"),this.reconnectAttempts=0}),this.socket.on("message",e=>{try{const t="string"==typeof e?e:e.toString(),r=JSON.parse(t);Fn.debug("[ws] Received message",{type:r?.type}),"connected"===r?.type&&(Fn.info("[ws] Authenticated successfully"),this.isAuthenticated=!0,this.authenticationFailed=!1,this.flushPending()),"user_message"===r?.type&&"string"==typeof r.content&&(Fn.info("[ws] Received user message from web UI"),this.onUserMessage?.(r.content))}catch{}}),this.socket.on("close",(e,t)=>{Fn.info("[ws] Connection closed",{code:e,authFailed:1008===e,reconnectAttempts:this.reconnectAttempts,maxReconnect:this.maxReconnectAttempts,isClosed:this._isClosed}),this.isAuthenticated=!1,1008===e&&(this.authenticationFailed=!0),!this._isClosed&&!this.authenticationFailed&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()}),this.socket.on("error",e=>{Fn.warn("[ws] Connection error",{error:e.message})})}catch(e){Fn.warn("[ws] Failed to create WebSocket",{error:e instanceof Error?e.message:String(e)}),this.scheduleReconnect()}}scheduleReconnect(){this._isClosed||this.reconnectTimer||(this.reconnectAttempts++,Fn.info("[ws] Scheduling reconnect",{attempt:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts,delayMs:this.reconnectDelay}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect()},this.reconnectDelay))}isConnected(){return!!this.socket&&this.socket.readyState===me.OPEN&&this.isAuthenticated}sendProgress(e){if(this._isClosed)return void Fn.debug("[ws] sendProgress called but client is closed",{phase:e.phase});const t={type:"create_progress",payload:e};return this.pendingEvent=t,this.isConnected()?"complete"===e.phase?(Fn.info("[ws] sendProgress: flushing terminal state immediately"),void this.flushPending()):void(this.debounceTimer||(this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.flushPending()},this.debounceMs))):(Fn.debug("[ws] sendProgress: not connected, queuing event",{phase:e.phase,socketState:this.socket?.readyState,isAuthenticated:this.isAuthenticated,reconnectAttempts:this.reconnectAttempts}),void(this.socket?.readyState===me.CLOSED&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()))}flushPending(){if(this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),!this.pendingEvent)return;const e=this.pendingEvent;if(this.pendingEvent=null,!this.isConnected())return Fn.debug("[ws] flushPending: not connected, re-queuing event",{phase:e.payload.phase}),void(this.pendingEvent=e);try{Fn.debug("[ws] flushPending: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),t=>{t&&(Fn.warn("[ws] flushPending: send failed",{error:t.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e))})}catch(t){Fn.warn("[ws] flushPending: send threw",{error:t instanceof Error?t.message:String(t)}),this.pendingEvent=e}}close(){if(this._isClosed)return;Fn.info("[ws] Closing WebSocket client"),this._isClosed=!0,this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.flushPending();const{socket:e}=this;this.socket=void 0,e&&setTimeout(()=>{e.close()},200)}},co=/\.(spec|test)\.(c|m)?[jt]sx?$/,lo=e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"text"===t.type&&"string"==typeof t.text},uo=e=>null!=e&&"object"==typeof e&&"tool_response"in e,po=e=>{if(!e||"object"!=typeof e)return;const t=e;return Array.isArray(t.tool_response)?t.tool_response:void 0},fo=e=>{const t=po(e);if(t)return t.filter(lo).map(e=>e.text).join("\n")||void 0},ho=/\u001b\[[0-9;]*m/g,mo=e=>e.replace(ho,""),go=/\$\{process\.env\.([A-Z_][A-Z0-9_]*)\}/g;function yo({envVars:e}){return async t=>{if(!function(e){return Boolean(e&&"object"==typeof e&&"tool_input"in e&&e.tool_input&&"object"==typeof e.tool_input)}(t))return{decision:"approve"};const r=t.tool_input,n="string"==typeof r.text?r.text:void 0;if(!n)return{decision:"approve"};const o=n.replace(go,(t,r)=>{const n=e[r];return null!=n?n:t});return o===n?{decision:"approve"}:{decision:"approve",hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",reason:"Evaluated environment variable placeholders in browser text input.",updatedInput:{...r,text:o}}}}}function bo({onResult:e}){return async t=>{if(!uo(t))return{decision:"approve"};const r=fo(t);if(!r)return{decision:"approve"};const n=function(e){const t=mo(e),r=t.split(/Running \d+ tests? using \d+ workers?/).at(-1)??t,n=parseInt(r.match(/(\d+)\s+passed/g)?.at(-1)?.match(/(\d+)/)?.[1]??"0"),o=parseInt(r.match(/(\d+)\s+failed/g)?.at(-1)?.match(/(\d+)/)?.[1]??"0");if(0===n&&0===o)return;const s=[n>0?`${n} test${1===n?"":"s"} passed ✓`:void 0,o>0?`${o} test${1===o?"":"s"} failed ✗`:void 0].filter(e=>void 0!==e).join(", ");if(0===o)return s;const i=r.split(/\n\s+\d+\)\s+\[id=/).slice(1).map(e=>e.match(/\n\s{4}((?:TimeoutError|Error|AssertionError):\s*[^\n]+)/)?.[1]?.trim()).filter(e=>void 0!==e);return 0===i.length?s:`${s}\n${i.map(e=>` - ${e}`).join("\n")}`}(r);return n&&e(n),{decision:"approve"}}}function wo({onResult:e}){return async t=>{if(!uo(t))return{decision:"approve"};const r=fo(t);if(!r)return{decision:"approve"};const n=function(e){const t=mo(e);if(t.match(/### Paused on error:/)){const e=t.match(/### Paused on error:\s*\n((?:TimeoutError|Error|AssertionError):\s*[^\n]+)/);return e?`Test paused on error - ${e[1].trim()}`:"Test paused on error"}const r=t.match(/(\d+)\s+passed/);if(r){const e=parseInt(r[1]);return`${e} test${1===e?"":"s"} passed ✓`}}(r);return n&&e(n),{decision:"approve"}}}var vo=/\.(spec|test)\.(ts|tsx|js|jsx|mts|mjs)$/;function _o({onFileCreated:e}){return async t=>{const r=(e=>{if(!e||"object"!=typeof e)return;const t=e;return t.tool_input&&"object"==typeof t.tool_input&&!Array.isArray(t.tool_input)?t.tool_input:void 0})(t),n=r?.file_path;return"string"==typeof n&&vo.test(n)&&e(n),{decision:"approve"}}}var Eo=D(d);async function Io(){try{const{stdout:e}=await Eo('pgrep -f "playwright run-test-mcp-server" 2>/dev/null || true'),t=e.trim();if(!t)return;const r=t.split("\n").filter(Boolean);await Promise.allSettled(r.map(async e=>{await Eo(`pkill -KILL -P ${e} '.*' 2>/dev/null || true`)}))}catch{}}var To="sha256",xo=/^---\r?\n([\s\S]*?)\r?\n---/;function So(e){const t=e.replace(xo,"").replace(/^(\r?\n)+/,""),r=H.createHash(To).update(t,"utf8").digest("hex");return`${To}:${r}`}function Ao(e){const t=e.match(/^\/\*\*[\s\S]*?@prompt-hash\s+(sha256:[a-f0-9]{64})[\s\S]*?\*\//);return t?.[1]}function Co({builtAt:e=new Date,promptFile:t,promptHash:r}){const n=Array.isArray(t)?t:[t],o=n[0]??"unknown",s=e.toISOString();return["/**"," * @generated by stably build",` * @prompt-hash ${r}`,...n.map(e=>` * @prompt-file ${e}`),` * @built-at ${s}`," *",` * DO NOT EDIT MANUALLY - regenerate with: stably build ${o} --force`," */"].join("\n")}function Ro({workDir:e}){return async t=>{if(null==(r=t)||"object"!=typeof r||!("file_path"in r)||"string"!=typeof r.file_path)return{};var r;const o=t.file_path;if(!/\.(spec|test)\.[jt]sx?$/.test(o))return{};const s=n(e,o);if(!s.startsWith(n(e)+i))return console.error(`[PromptHash Hook] Path traversal attempt blocked: ${o}`),{};let a;try{a=await V(s,"utf-8")}catch(e){return console.error(`[PromptHash Hook] Error reading ${o}:`,e),{}}const c=function(e){const t=e.match(/\/\/\s*@stably\.spec\s+(\S+)/);return t?.[1]}(a);if(!c)return{};const l=n(e,c);if(!l.startsWith(n(e)+i))return console.error(`[PromptHash Hook] Path traversal attempt blocked: ${c}`),{};let u;try{u=await V(l,"utf-8")}catch{return{}}const d=So(u);if(Ao(a)===d)return{};const p=Co({promptHash:d,promptFile:c});let f;const h=a.match(/\/\*\*[\s\S]*?@prompt-hash[\s\S]*?\*\/\n?/);f=h?a.replace(h[0],`${p}\n`):`${p}\n${a}`;try{await K(s,f,"utf-8")}catch(e){console.error(`[PromptHash Hook] Error writing ${o}:`,e)}return{}}}var Po=class{queue=[];pendingResolve=void 0;done=!1;canSend=!0;[Symbol.asyncIterator](){return this}pushText(e){const t=e.trim();t&&!this.done&&(this.queue.push(t),this.maybeFlush())}allowNextTurn(){this.done||(this.canSend=!0,this.maybeFlush())}hasQueuedMessages(){return this.queue.length>0}finish(){this.done=!0,this.pendingResolve&&(this.pendingResolve({done:!0,value:void 0}),this.pendingResolve=void 0)}maybeFlush(){if(!this.pendingResolve)return;if(!this.canSend)return;const e=this.queue.shift();if(void 0===e)return;const t={message:{content:[{text:e,type:"text"}],role:"user"},parent_tool_use_id:null,type:"user",session_id:""};this.canSend=!1,this.pendingResolve({done:!1,value:t}),this.pendingResolve=void 0}next(){return this.done?Promise.resolve({done:!0,value:void 0}):new Promise(e=>{this.pendingResolve=e,this.maybeFlush()})}};function Uo(e){try{const t=p("git branch --show-current",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(!t)return;return{branch:t}}catch{return}}var ko=[".ts",".js",".mts",".mjs",".cts",".cjs"],Lo=10240,Do=async({defaultContent:e,fileName:t,filePath:r})=>{try{const e=(await Q(r)).size,n=await V(r,"utf-8"),o=Buffer.byteLength(n,"utf-8");if(o<=Lo)return n;const s=(e=>{const t=e.split("\n"),r=[];let n=!1,o=!1,s=0,i=!1;for(let e=0;e<t.length;e++){const a=t[e],c=a.trim();c.startsWith("/*")&&(n=!0),c.includes("*/")?n=!1:n||c.startsWith("//")&&!c.startsWith("///")||(c.startsWith("import ")||c.startsWith("export ")?(r.push(a),i=!0):i&&""===c?(r.push(a),i=!1):(i=!1,c.startsWith("type ")||c.startsWith("interface ")?r.push(a):c.startsWith("function ")||c.startsWith("const ")||c.startsWith("async function ")||c.startsWith("export function ")||c.startsWith("export const ")||c.startsWith("test.describe(")||c.startsWith("test(")?(r.push(a),o=!0,s=(a.match(/{/g)||[]).length-(a.match(/}/g)||[]).length,0===s&&(c.endsWith(";")||c.endsWith(","))&&(o=!1)):o?(s+=(a.match(/{/g)||[]).length,s-=(a.match(/}/g)||[]).length,0===s&&c.includes("}")?(r.push(a),o=!1):s>0&&" // ... implementation omitted ..."!==r.at(-1)&&r.push(" // ... implementation omitted ...")):c.match(/^[a-zA-Z_]+:/)&&r.push(a)))}return r.join("\n")})(n),i=Buffer.byteLength(s,"utf-8");return i<=Lo?s:s.slice(0,Lo)+`\n\n... [TRUNCATED: File "${t}" at ${r} was ${e} bytes (${o} bytes as UTF-8), reduced to ~${i} bytes of essential content, then truncated to 10240 bytes] ...`}catch(r){let n;if(r&&"object"==typeof r&&"code"in r){const e=r.code;"string"==typeof e&&(n=e)}return"ENOENT"!==n&&console.warn(`Failed to read ${t}: ${r}`),e}},Oo=async({defaultContent:e,dirName:t,dirPath:r})=>{try{const e=await X(r);return e.length>0?e.join("\n"):"(empty)"}catch(r){let n;if(r&&"object"==typeof r&&"code"in r){const e=r.code;"string"==typeof e&&(n=e)}return"ENOENT"!==n&&console.warn(`Failed to read ${t}: ${r}`),e}},Bo=async({allowedEnvVars:e,mode:t,workspaceInfo:r,authHeader:n,customHeader:o,maxParallelWorkers:s})=>{const i=Zr(),a=Uo(r.absolutePath);Fn.debug("Requesting system prompt from API",{mode:t,hasGitContext:!!a,envVarCount:e.length});const c=await(l={client:i,auth:n,body:{mode:t,workspaceInfo:r,allowedEnvVars:e,gitContext:a,maxParallelWorkers:s}},(l.client??Gr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/prompts/system",...l,headers:{"Content-Type":"application/json",...l.headers}}));var l;if(401===c.response.status)throw Fn.warn("System prompt fetch failed: unauthorized (401)"),await mn(),new Error("Your session has expired or been revoked. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(403===c.response.status)throw Fn.warn("System prompt fetch failed: forbidden (403)"),await mn(),new Error("You no longer have access to this organization. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(c.error)throw Fn.warn("System prompt fetch failed",{error:c.error}),new Error(`Failed to fetch system prompt: ${JSON.stringify(c.error)}`);const u=function({customHeader:e,systemPrompt:t}){return e?`${t}\n\nWhen writing or updating the generated test file, prepend this exact header at the top of the file without modification:\n\`\`\`ts\n${e}\n\`\`\``:t}({systemPrompt:c.data.systemPrompt,customHeader:o});return Fn.debug("System prompt received",{size:u.length,appendedCustomHeader:!!o,hasPrContext:!!c.data.prContext}),{systemPrompt:u,prContext:c.data.prContext}},No=".stably-playwright-wrapper.config.*",$o=[".ts",".js",".mts",".mjs",".cts",".cjs"];function Mo(e){const t=n(e);if(g(t))for(const e of $o){const r=s(t,`playwright.config${e}`);if(g(r))return r}}var jo=["tests","e2e","__tests__","test"];function Ho(e){try{return g(e)&&y(e).isDirectory()}catch{return!1}}function Fo(e,t){const r="output-flag"===t?"--output flag":"playwright.config.ts"===t?"playwright.config.ts":"auto-detected"===t?"auto-detected":"cwd fallback";console.error(G.dim(`Using output directory: ${e} (from ${r})`))}var Go,Yo=["mcp__playwright-test__","mcp__auto-heal-report__","mcp__test-doc-sync__","mcp__stably-agent-control__"],Wo=["planner_","generator_"],Vo={"mcp__stably-agent-control__restart_mcp_servers":"Restarting Browser Tools","mcp__session-control__restart_mcp_servers":"Restarting Browser Tools"},zo=(e,t)=>{const r=t.find(t=>e.startsWith(t));return r?e.slice(r.length):e},Ko=e=>{const t=Vo[e];if(t)return t;const r=zo(e,Yo);return zo(r,Wo).split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")},qo=(e,t)=>{if(!t||"object"!=typeof t)return;const r=t,n="string"==typeof r.intent?r.intent:void 0;if("Read"!==e&&"Write"!==e&&"Edit"!==e){if("Glob"===e||"Grep"===e)return"string"==typeof r.pattern?r.pattern:void 0;if("mcp__playwright-test__test_run"!==e&&"test_run"!==e){if("mcp__playwright-test__test_debug"===e||"test_debug"===e){const e=r.test;return"string"==typeof e?.title?e.title:void 0}return"mcp__playwright-test__generator_setup_page"===e||"generator_setup_page"===e?"string"==typeof r.seedFile?r.seedFile:"tests/seed.spec.ts":"mcp__playwright-test__generator_write_test"===e||"generator_write_test"===e?"string"==typeof r.fileName?r.fileName:void 0:"Bash"===e?"string"==typeof r.command?r.command.length>50?`${r.command.slice(0,50)}...`:r.command:void 0:e.includes("browser_navigate")&&!e.includes("back")?"string"==typeof r.url?r.url:n:e.includes("browser_type")?("string"==typeof r.text?`"${r.text}"`:void 0)??n:e.includes("browser_click")?"string"==typeof r.element?r.element:n:e.includes("browser_wait_for")?"string"==typeof r.text?`text: "${r.text}"`:"number"==typeof r.time?`${r.time}ms`:n:e.includes("verify_text")?"string"==typeof r.text?`"${r.text}"`:n:e.includes("verify_element")?"string"==typeof r.accessibleName?r.accessibleName:n:e.includes("screenshot")&&"string"==typeof r.filename?r.filename:n}if(Array.isArray(r.locations)){const e=r.locations.filter(e=>"string"==typeof e);return e.length>0?e.join(", "):void 0}}else if("string"==typeof r.file_path)return r.file_path.split("/").at(-1)??void 0},Jo=["test","bug","flake","ui_change","other"],Xo={bug:"Application code defect; behavior diverges from expected requirements.",flake:"Non-deterministic failure; timing, race conditions, or environmental variance causes inconsistent test results.",other:"External dependencies, environment, or infra issues outside test/app code.",test:"Test code is incorrect, out-of-date, or missing necessary setup.",ui_change:"Application UI intentionally changed; test expectations (screenshots, selectors, text assertions) are stale and need updating."},Qo=e=>Xo[e],Zo=/[^a-zA-Z0-9-_]/g,es=e=>{const t=e.trim().replace(Zo,"_");return t.length>0?t.slice(0,80):void 0},ts=e=>"string"==typeof e?es(e):void 0,rs=Ie("/");try{Go=rs("worker_threads").Worker}catch(e){}var ns=Go?function(e,t,r,n,o){var s=!1,i=new Go(e+";var __w=require('worker_threads');__w.parentPort.on('message',function(m){onmessage({data:m})}),postMessage=function(m,t){__w.parentPort.postMessage(m,t)},close=process.exit;self=global",{eval:!0}).on("error",function(e){return o(e,null)}).on("message",function(e){return o(null,e)}).on("exit",function(e){e&&!s&&o(new Error("exited with code "+e),null)});return i.postMessage(r,n),i.terminate=function(){return s=!0,Go.prototype.terminate.call(i)},i}:function(e,t,r,n,o){setImmediate(function(){return o(new Error("async operations unsupported - update to Node 12+ (or Node 10-11 with the --experimental-worker CLI flag)"),null)});var s=function(){};return{terminate:s,postMessage:s}},os=Uint8Array,ss=Uint16Array,is=Int32Array,as=new os([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),cs=new os([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),ls=new os([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),us=function(e,t){for(var r=new ss(31),n=0;n<31;++n)r[n]=t+=1<<e[n-1];var o=new is(r[30]);for(n=1;n<30;++n)for(var s=r[n];s<r[n+1];++s)o[s]=s-r[n]<<5|n;return{b:r,r:o}},ds=us(as,2),ps=ds.b,fs=ds.r;ps[28]=258,fs[258]=28;var hs,ms=us(cs,0),gs=ms.b,ys=ms.r,bs=new ss(32768);for(_s=0;_s<32768;++_s)hs=(61680&(hs=(52428&(hs=(43690&_s)>>1|(21845&_s)<<1))>>2|(13107&hs)<<2))>>4|(3855&hs)<<4,bs[_s]=((65280&hs)>>8|(255&hs)<<8)>>1;var ws=function(e,t,r){for(var n=e.length,o=0,s=new ss(t);o<n;++o)e[o]&&++s[e[o]-1];var i,a=new ss(t);for(o=1;o<t;++o)a[o]=a[o-1]+s[o-1]<<1;if(r){i=new ss(1<<t);var c=15-t;for(o=0;o<n;++o)if(e[o])for(var l=o<<4|e[o],u=t-e[o],d=a[e[o]-1]++<<u,p=d|(1<<u)-1;d<=p;++d)i[bs[d]>>c]=l}else for(i=new ss(n),o=0;o<n;++o)e[o]&&(i[o]=bs[a[e[o]-1]++]>>15-e[o]);return i},vs=new os(288);for(_s=0;_s<144;++_s)vs[_s]=8;for(_s=144;_s<256;++_s)vs[_s]=9;for(_s=256;_s<280;++_s)vs[_s]=7;for(_s=280;_s<288;++_s)vs[_s]=8;var _s,Es=new os(32);for(_s=0;_s<32;++_s)Es[_s]=5;var Is=ws(vs,9,0),Ts=ws(vs,9,1),xs=ws(Es,5,0),Ss=ws(Es,5,1),As=function(e){for(var t=e[0],r=1;r<e.length;++r)e[r]>t&&(t=e[r]);return t},Cs=function(e,t,r){var n=t/8|0;return(e[n]|e[n+1]<<8)>>(7&t)&r},Rs=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(7&t)},Ps=function(e){return(e+7)/8|0},Us=function(e,t,r){return(null==t||t<0)&&(t=0),(null==r||r>e.length)&&(r=e.length),new os(e.subarray(t,r))},ks=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Ls=function(e,t,r){var n=new Error(t||ks[e]);if(n.code=e,Error.captureStackTrace&&Error.captureStackTrace(n,Ls),!r)throw n;return n},Ds=function(e,t,r,n){var o=e.length,s=n?n.length:0;if(!o||t.f&&!t.l)return r||new os(0);var i=!r,a=i||2!=t.i,c=t.i;i&&(r=new os(3*o));var l=function(e){var t=r.length;if(e>t){var n=new os(Math.max(2*t,e));n.set(r),r=n}},u=t.f||0,d=t.p||0,p=t.b||0,f=t.l,h=t.d,m=t.m,g=t.n,y=8*o;do{if(!f){u=Cs(e,d,1);var b=Cs(e,d+1,3);if(d+=3,!b){var w=e[(P=Ps(d)+4)-4]|e[P-3]<<8,v=P+w;if(v>o){c&&Ls(0);break}a&&l(p+w),r.set(e.subarray(P,v),p),t.b=p+=w,t.p=d=8*v,t.f=u;continue}if(1==b)f=Ts,h=Ss,m=9,g=5;else if(2==b){var _=Cs(e,d,31)+257,E=Cs(e,d+10,15)+4,I=_+Cs(e,d+5,31)+1;d+=14;for(var T=new os(I),x=new os(19),S=0;S<E;++S)x[ls[S]]=Cs(e,d+3*S,7);d+=3*E;var A=As(x),C=(1<<A)-1,R=ws(x,A,1);for(S=0;S<I;){var P,U=R[Cs(e,d,C)];if(d+=15&U,(P=U>>4)<16)T[S++]=P;else{var k=0,L=0;for(16==P?(L=3+Cs(e,d,3),d+=2,k=T[S-1]):17==P?(L=3+Cs(e,d,7),d+=3):18==P&&(L=11+Cs(e,d,127),d+=7);L--;)T[S++]=k}}var D=T.subarray(0,_),O=T.subarray(_);m=As(D),g=As(O),f=ws(D,m,1),h=ws(O,g,1)}else Ls(1);if(d>y){c&&Ls(0);break}}a&&l(p+131072);for(var B=(1<<m)-1,N=(1<<g)-1,$=d;;$=d){var M=(k=f[Rs(e,d)&B])>>4;if((d+=15&k)>y){c&&Ls(0);break}if(k||Ls(2),M<256)r[p++]=M;else{if(256==M){$=d,f=null;break}var j=M-254;if(M>264){var H=as[S=M-257];j=Cs(e,d,(1<<H)-1)+ps[S],d+=H}var F=h[Rs(e,d)&N],G=F>>4;if(F||Ls(3),d+=15&F,O=gs[G],G>3&&(H=cs[G],O+=Rs(e,d)&(1<<H)-1,d+=H),d>y){c&&Ls(0);break}a&&l(p+131072);var Y=p+j;if(p<O){var W=s-O,V=Math.min(O,Y);for(W+p<0&&Ls(3);p<V;++p)r[p]=n[W+p]}for(;p<Y;++p)r[p]=r[p-O]}}t.l=f,t.p=$,t.b=p,t.f=u,f&&(u=1,t.m=m,t.d=h,t.n=g)}while(!u);return p!=r.length&&i?Us(r,0,p):r.subarray(0,p)},Os=function(e,t,r){r<<=7&t;var n=t/8|0;e[n]|=r,e[n+1]|=r>>8},Bs=function(e,t,r){r<<=7&t;var n=t/8|0;e[n]|=r,e[n+1]|=r>>8,e[n+2]|=r>>16},Ns=function(e,t){for(var r=[],n=0;n<e.length;++n)e[n]&&r.push({s:n,f:e[n]});var o=r.length,s=r.slice();if(!o)return{t:Ys,l:0};if(1==o){var i=new os(r[0].s+1);return i[r[0].s]=1,{t:i,l:1}}r.sort(function(e,t){return e.f-t.f}),r.push({s:-1,f:25001});var a=r[0],c=r[1],l=0,u=1,d=2;for(r[0]={s:-1,f:a.f+c.f,l:a,r:c};u!=o-1;)a=r[r[l].f<r[d].f?l++:d++],c=r[l!=u&&r[l].f<r[d].f?l++:d++],r[u++]={s:-1,f:a.f+c.f,l:a,r:c};var p=s[0].s;for(n=1;n<o;++n)s[n].s>p&&(p=s[n].s);var f=new ss(p+1),h=$s(r[u-1],f,0);if(h>t){n=0;var m=0,g=h-t,y=1<<g;for(s.sort(function(e,t){return f[t.s]-f[e.s]||e.f-t.f});n<o;++n){var b=s[n].s;if(!(f[b]>t))break;m+=y-(1<<h-f[b]),f[b]=t}for(m>>=g;m>0;){var w=s[n].s;f[w]<t?m-=1<<t-f[w]++-1:++n}for(;n>=0&&m;--n){var v=s[n].s;f[v]==t&&(--f[v],++m)}h=t}return{t:new os(f),l:h}},$s=function(e,t,r){return-1==e.s?Math.max($s(e.l,t,r+1),$s(e.r,t,r+1)):t[e.s]=r},Ms=function(e){for(var t=e.length;t&&!e[--t];);for(var r=new ss(++t),n=0,o=e[0],s=1,i=function(e){r[n++]=e},a=1;a<=t;++a)if(e[a]==o&&a!=t)++s;else{if(!o&&s>2){for(;s>138;s-=138)i(32754);s>2&&(i(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(i(o),--s;s>6;s-=6)i(8304);s>2&&(i(s-3<<5|8208),s=0)}for(;s--;)i(o);s=1,o=e[a]}return{c:r.subarray(0,n),n:t}},js=function(e,t){for(var r=0,n=0;n<t.length;++n)r+=e[n]*t[n];return r},Hs=function(e,t,r){var n=r.length,o=Ps(t+2);e[o]=255&n,e[o+1]=n>>8,e[o+2]=255^e[o],e[o+3]=255^e[o+1];for(var s=0;s<n;++s)e[o+s+4]=r[s];return 8*(o+4+n)},Fs=function(e,t,r,n,o,s,i,a,c,l,u){Os(t,u++,r),++o[256];for(var d=Ns(o,15),p=d.t,f=d.l,h=Ns(s,15),m=h.t,g=h.l,y=Ms(p),b=y.c,w=y.n,v=Ms(m),_=v.c,E=v.n,I=new ss(19),T=0;T<b.length;++T)++I[31&b[T]];for(T=0;T<_.length;++T)++I[31&_[T]];for(var x=Ns(I,7),S=x.t,A=x.l,C=19;C>4&&!S[ls[C-1]];--C);var R,P,U,k,L=l+5<<3,D=js(o,vs)+js(s,Es)+i,O=js(o,p)+js(s,m)+i+14+3*C+js(I,S)+2*I[16]+3*I[17]+7*I[18];if(c>=0&&L<=D&&L<=O)return Hs(t,u,e.subarray(c,c+l));if(Os(t,u,1+(O<D)),u+=2,O<D){R=ws(p,f,0),P=p,U=ws(m,g,0),k=m;var B=ws(S,A,0);for(Os(t,u,w-257),Os(t,u+5,E-1),Os(t,u+10,C-4),u+=14,T=0;T<C;++T)Os(t,u+3*T,S[ls[T]]);u+=3*C;for(var N=[b,_],$=0;$<2;++$){var M=N[$];for(T=0;T<M.length;++T){var j=31&M[T];Os(t,u,B[j]),u+=S[j],j>15&&(Os(t,u,M[T]>>5&127),u+=M[T]>>12)}}}else R=Is,P=vs,U=xs,k=Es;for(T=0;T<a;++T){var H=n[T];if(H>255){Bs(t,u,R[257+(j=H>>18&31)]),u+=P[j+257],j>7&&(Os(t,u,H>>23&31),u+=as[j]);var F=31&H;Bs(t,u,U[F]),u+=k[F],F>3&&(Bs(t,u,H>>5&8191),u+=cs[F])}else Bs(t,u,R[H]),u+=P[H]}return Bs(t,u,R[256]),u+P[256]},Gs=new is([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Ys=new os(0),Ws=function(e,t,r,n,o,s){var i=s.z||e.length,a=new os(n+i+5*(1+Math.ceil(i/7e3))+o),c=a.subarray(n,a.length-o),l=s.l,u=7&(s.r||0);if(t){u&&(c[0]=s.r>>3);for(var d=Gs[t-1],p=d>>13,f=8191&d,h=(1<<r)-1,m=s.p||new ss(32768),g=s.h||new ss(h+1),y=Math.ceil(r/3),b=2*y,w=function(t){return(e[t]^e[t+1]<<y^e[t+2]<<b)&h},v=new is(25e3),_=new ss(288),E=new ss(32),I=0,T=0,x=s.i||0,S=0,A=s.w||0,C=0;x+2<i;++x){var R=w(x),P=32767&x,U=g[R];if(m[P]=U,g[R]=P,A<=x){var k=i-x;if((I>7e3||S>24576)&&(k>423||!l)){u=Fs(e,c,0,v,_,E,T,S,C,x-C,u),S=I=T=0,C=x;for(var L=0;L<286;++L)_[L]=0;for(L=0;L<30;++L)E[L]=0}var D=2,O=0,B=f,N=P-U&32767;if(k>2&&R==w(x-N))for(var $=Math.min(p,k)-1,M=Math.min(32767,x),j=Math.min(258,k);N<=M&&--B&&P!=U;){if(e[x+D]==e[x+D-N]){for(var H=0;H<j&&e[x+H]==e[x+H-N];++H);if(H>D){if(D=H,O=N,H>$)break;var F=Math.min(N,H-2),G=0;for(L=0;L<F;++L){var Y=x-N+L&32767,W=Y-m[Y]&32767;W>G&&(G=W,U=Y)}}}N+=(P=U)-(U=m[P])&32767}if(O){v[S++]=268435456|fs[D]<<18|ys[O];var V=31&fs[D],z=31&ys[O];T+=as[V]+cs[z],++_[257+V],++E[z],A=x+D,++I}else v[S++]=e[x],++_[e[x]]}}for(x=Math.max(x,A);x<i;++x)v[S++]=e[x],++_[e[x]];u=Fs(e,c,l,v,_,E,T,S,C,x-C,u),l||(s.r=7&u|c[u/8|0]<<3,u-=7,s.h=g,s.p=m,s.i=x,s.w=A)}else{for(x=s.w||0;x<i+l;x+=65535){var K=x+65535;K>=i&&(c[u/8|0]=l,K=i),u=Hs(c,u+1,e.subarray(x,K))}s.i=i}return Us(a,0,n+Ps(u)+o)},Vs=function(){for(var e=new Int32Array(256),t=0;t<256;++t){for(var r=t,n=9;--n;)r=(1&r&&-306674912)^r>>>1;e[t]=r}return e}(),zs=function(e,t,r,n,o){if(!o&&(o={l:1},t.dictionary)){var s=t.dictionary.subarray(-32768),i=new os(s.length+e.length);i.set(s),i.set(e,s.length),e=i,o.w=s.length}return Ws(e,null==t.level?6:t.level,null==t.mem?o.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(e.length)))):20:12+t.mem,r,n,o)},Ks=function(e,t){var r={};for(var n in e)r[n]=e[n];for(var n in t)r[n]=t[n];return r},qs=function(e,t,r){for(var n=e(),o=e.toString(),s=o.slice(o.indexOf("[")+1,o.lastIndexOf("]")).replace(/\s+/g,"").split(","),i=0;i<n.length;++i){var a=n[i],c=s[i];if("function"==typeof a){t+=";"+c+"=";var l=a.toString();if(a.prototype)if(-1!=l.indexOf("[native code]")){var u=l.indexOf(" ",8)+1;t+=l.slice(u,l.indexOf("(",u))}else for(var d in t+=l,a.prototype)t+=";"+c+".prototype."+d+"="+a.prototype[d].toString();else t+=l}else r[c]=a}return t},Js=[],Xs=function(){return[os,ss,is,as,cs,ls,ps,gs,Ts,Ss,bs,ks,ws,As,Cs,Rs,Ps,Us,Ls,Ds,ai,Zs,ei]},Qs=function(){return[os,ss,is,as,cs,ls,fs,ys,Is,vs,xs,Es,bs,Gs,Ys,ws,Os,Bs,Ns,$s,Ms,js,Hs,Fs,Ps,Us,Ws,zs,ii,Zs]},Zs=function(e){return postMessage(e,[e.buffer])},ei=function(e){return e&&{out:e.size&&new os(e.size),dictionary:e.dictionary}},ti=function(e,t,r,n,o,s){var i=function(e,t,r,n){if(!Js[r]){for(var o="",s={},i=e.length-1,a=0;a<i;++a)o=qs(e[a],o,s);Js[r]={c:qs(e[i],o,s),e:s}}var c=Ks({},Js[r].e);return ns(Js[r].c+";onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage="+t.toString()+"}",r,c,function(e){var t=[];for(var r in e)e[r].buffer&&t.push((e[r]=new e[r].constructor(e[r])).buffer);return t}(c),n)}(r,n,o,function(e,t){i.terminate(),s(e,t)});return i.postMessage([e,t],t.consume?[e.buffer]:[]),function(){i.terminate()}},ri=function(e,t){return e[t]|e[t+1]<<8},ni=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},oi=function(e,t){return ni(e,t)+4294967296*ni(e,t+4)},si=function(e,t,r){for(;r;++t)e[t]=r,r>>>=8};function ii(e,t){return zs(e,t||{},0,0)}function ai(e,t){return Ds(e,{i:2},t&&t.out,t&&t.dictionary)}var ci=function(e,t,r,n){for(var o in e){var s=e[o],i=t+o,a=n;Array.isArray(s)&&(a=Ks(n,s[1]),s=s[0]),s instanceof os?r[i]=[s,a]:(r[i+="/"]=[new os(0),a],ci(s,i,r,n))}},li="undefined"!=typeof TextEncoder&&new TextEncoder,ui="undefined"!=typeof TextDecoder&&new TextDecoder;try{ui.decode(Ys,{stream:!0})}catch(e){}function di(e,t){if(li)return li.encode(e);for(var r=e.length,n=new os(e.length+(e.length>>1)),o=0,s=function(e){n[o++]=e},i=0;i<r;++i){if(o+5>n.length){var a=new os(o+8+(r-i<<1));a.set(n),n=a}var c=e.charCodeAt(i);c<128||t?s(c):c<2048?(s(192|c>>6),s(128|63&c)):c>55295&&c<57344?(s(240|(c=65536+(1047552&c)|1023&e.charCodeAt(++i))>>18),s(128|c>>12&63),s(128|c>>6&63),s(128|63&c)):(s(224|c>>12),s(128|c>>6&63),s(128|63&c))}return Us(n,0,o)}var pi=function(e){var t=0;if(e)for(var r in e){var n=e[r].length;n>65535&&Ls(9),t+=n+4}return t},fi=function(e,t,r,n,o,s,i,a){var c=n.length,l=r.extra,u=a&&a.length,d=pi(l);si(e,t,null!=i?33639248:67324752),t+=4,null!=i&&(e[t++]=20,e[t++]=r.os),e[t]=20,t+=2,e[t++]=r.flag<<1|(s<0&&8),e[t++]=o&&8,e[t++]=255&r.compression,e[t++]=r.compression>>8;var p=new Date(null==r.mtime?Date.now():r.mtime),f=p.getFullYear()-1980;if((f<0||f>119)&&Ls(10),si(e,t,f<<25|p.getMonth()+1<<21|p.getDate()<<16|p.getHours()<<11|p.getMinutes()<<5|p.getSeconds()>>1),t+=4,-1!=s&&(si(e,t,r.crc),si(e,t+4,s<0?-s-2:s),si(e,t+8,r.size)),si(e,t+12,c),si(e,t+14,d),t+=16,null!=i&&(si(e,t,u),si(e,t+6,r.attrs),si(e,t+10,i),t+=14),e.set(n,t),t+=c,d)for(var h in l){var m=l[h],g=m.length;si(e,t,+h),si(e,t+2,g),e.set(m,t+4),t+=4+g}return u&&(e.set(a,t),t+=u),t},hi="function"==typeof queueMicrotask?queueMicrotask:"function"==typeof setTimeout?setTimeout:function(e){e()};function mi(e,t,r){const n=Math.min(t,512);if("utf-16"===r||"utf-16le"===r||"utf-16be"===r){for(let t=0;t<n;t+=2){const o=e[t],s=t+1<n?e[t+1]:0;if(("utf-16le"===r||"utf-16"===r)&&0===s&&o<32&&9!==o&&10!==o&&13!==o&&0!==o)return!1;if(("utf-16be"===r||"utf-16"===r)&&0===o&&s<32&&9!==s&&10!==s&&13!==s&&0!==s)return!1}return!0}if("latin1"===r||"iso-8859-1"===r){for(let t=0;t<n;t++){const r=e[t];if(0===r)return!1;if(r<32&&9!==r&&10!==r&&13!==r)return!1}return!0}if("cjk"===r||"big5"===r||"gb2312"===r||"gbk"===r||"euc-kr"===r||"shift-jis"===r){for(let t=0;t<n;t++){const r=e[t];if(0===r)return!1;if(r<32&&9!==r&&10!==r&&13!==r)return!1}return!0}return!1}var gi=class{fileBuffer;size;offset;error;constructor(e,t){this.fileBuffer=e,this.size=t,this.offset=0,this.error=!1}hasError(){return this.error}nextByte(){return this.offset===this.size||this.hasError()?(this.error=!0,255):this.fileBuffer[this.offset++]}next(e){if(e<0||e>this.size-this.offset)return this.error=!0,[];const t=new Array;for(let r=0;r<e;r++){if(this.error)return t;t[r]=this.nextByte()}return t}};function yi(e){let t=0,r=0;for(;!e.hasError();){const n=e.nextByte();if(r|=(127&n)<<7*t,!(128&n))break;if(t>=10){e.error=!0;break}t++}return r}function bi(e){switch(7&yi(e)){case 0:return yi(e),!0;case 1:return e.next(8),!0;case 2:const t=yi(e);return e.next(t),!0;case 5:return e.next(4),!0}return!1}function wi(e,t,r){if(0===t)return!1;let n=0;const o=Math.min(t,515),s=Math.min(o,512);if(t>=3&&239===e[0]&&187===e[1]&&191===e[2])return!1;if(t>=4&&0===e[0]&&0===e[1]&&254===e[2]&&255===e[3])return!1;if(t>=4&&255===e[0]&&254===e[1]&&0===e[2]&&0===e[3])return!1;if(t>=4&&132===e[0]&&49===e[1]&&149===e[2]&&51===e[3])return!1;if(o>=5&&"%PDF-"===e.slice(0,5).toString())return!0;if(t>=2&&254===e[0]&&255===e[1])return!1;if(t>=2&&255===e[0]&&254===e[1])return!1;if(r?.encoding)return!mi(e,t,r.encoding);const i=function(e,t){if(t<4)return null;const r=Math.min(t,512);let n=0,o=0;for(let t=0;t<r;t++)0===e[t]&&(t%2==0?n++:o++);const s=n+o;if(s>.3*r&&s<.7*r){if(o>3*n)return"utf-16le";if(n>3*o)return"utf-16be"}return null}(e,t);if(i)return!mi(e,t,i);for(let t=0;t<s;t++){if(0===e[t])return!0;if((e[t]<7||e[t]>14)&&(e[t]<32||e[t]>127)){if(e[t]>=192&&e[t]<=223&&t+1<o){if(t++,e[t]>=128&&e[t]<=191)continue}else if(e[t]>=224&&e[t]<=239&&t+2<o){if(t++,e[t]>=128&&e[t]<=191&&e[t+1]>=128&&e[t+1]<=191){t++;continue}}else if(e[t]>=240&&e[t]<=247&&t+3<o&&(t++,e[t]>=128&&e[t]<=191&&e[t+1]>=128&&e[t+1]<=191&&e[t+2]>=128&&e[t+2]<=191)){t+=2;continue}if(n++,t>=32&&100*n/s>10)return!0}}return 100*n/s>10||!!(n>1&&function(e,t){const r=new gi(e,t);let n=0;for(;;){if(!bi(r)&&!r.hasError())return!1;if(r.hasError())break;n++}return n>0}(e,s))}var vi=[/^\/$/,/^\*+$/,/^[0-9]+$/],_i=["/artifact/","https://","http://","*********"],Ei=new Set(["sha1","_sha1","pageref","downloadsPath","tracesDir","pageId"]);function Ii({sensitiveValues:e,str:t}){return e.reduce((e,t)=>e.replaceAll(t,"[REDACTED]"),t)}function Ti({sensitiveValues:e,value:t}){return"string"==typeof t?Ii({sensitiveValues:e,str:t}):Array.isArray(t)?t.map(t=>Ti({sensitiveValues:e,value:t})):function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(t)?Si({obj:t,sensitiveValues:e}):t}function xi(e){return!!Ei.has(e)||e.toLowerCase().endsWith("sha1")}function Si({obj:e,sensitiveValues:t}){return Object.fromEntries(Object.entries(e).map(([e,r])=>[e,xi(e)?r:Ti({sensitiveValues:t,value:r})]))}function Ai({error:e,sensitiveValues:t}){return e?{...e,message:Ii({sensitiveValues:t,str:e.message})}:void 0}function Ci({content:e,sensitiveValues:t}){const r=new O,n=new B,o=Ii({sensitiveValues:t,str:r.decode(e)});return n.encode(o)}var Ri=D(function(e,t,r){r||(r=t,t={}),"function"!=typeof r&&Ls(7);var n=[],o=function(){for(var e=0;e<n.length;++e)n[e]()},s={},i=function(e,t){hi(function(){r(e,t)})};hi(function(){i=r});for(var a=e.length-22;101010256!=ni(e,a);--a)if(!a||e.length-a>65558)return i(Ls(13,0,1),null),o;var c=ri(e,a+8);if(c){var l=c,u=ni(e,a+16),d=4294967295==u||65535==l;if(d){var p=ni(e,a-12);(d=101075792==ni(e,p))&&(l=c=ni(e,p+32),u=ni(e,p+48))}for(var f=t&&t.filter,h=function(t){var r=function(e,t,r){var n=ri(e,t+28),o=function(e,t){if(t){for(var r="",n=0;n<e.length;n+=16384)r+=String.fromCharCode.apply(null,e.subarray(n,n+16384));return r}if(ui)return ui.decode(e);var o=function(e){for(var t="",r=0;;){var n=e[r++],o=(n>127)+(n>223)+(n>239);if(r+o>e.length)return{s:t,r:Us(e,r-1)};o?3==o?(n=((15&n)<<18|(63&e[r++])<<12|(63&e[r++])<<6|63&e[r++])-65536,t+=String.fromCharCode(55296|n>>10,56320|1023&n)):t+=1&o?String.fromCharCode((31&n)<<6|63&e[r++]):String.fromCharCode((15&n)<<12|(63&e[r++])<<6|63&e[r++]):t+=String.fromCharCode(n)}}(e),s=o.s;return(r=o.r).length&&Ls(8),s}(e.subarray(t+46,t+46+n),!(2048&ri(e,t+8))),s=t+46+n,i=ni(e,t+20),a=r&&4294967295==i?function(e,t){for(;1!=ri(e,t);t+=4+ri(e,t+2));return[oi(e,t+12),oi(e,t+4),oi(e,t+20)]}(e,s):[i,ni(e,t+24),ni(e,t+42)],c=a[0],l=a[1],u=a[2];return[ri(e,t+10),c,l,o,s+ri(e,t+30)+ri(e,t+32),u]}(e,u,d),a=r[0],l=r[1],p=r[2],h=r[3],m=r[4],g=r[5],y=function(e,t){return t+30+ri(e,t+26)+ri(e,t+28)}(e,g);u=m;var b=function(e,t){e?(o(),i(e,null)):(t&&(s[h]=t),--c||i(null,s))};if(!f||f({name:h,size:l,originalSize:p,compression:a}))if(a)if(8==a){var w=e.subarray(y,y+l);if(p<524288||l>.8*p)try{b(null,ai(w,{out:new os(p)}))}catch(e){b(e,null)}else n.push(function(e,t,r){return r||(r=t,t={}),"function"!=typeof r&&Ls(7),ti(e,t,[Xs],function(e){return Zs(ai(e.data[0],ei(e.data[1])))},1,r)}(w,{size:p},b))}else b(Ls(14,"unknown compression type "+a,1),null);else b(null,Us(e,y,y+l));else b(null,null)},m=0;m<l;++m)h()}else i(null,{});return o}),Pi=D(function(e,t,r){r||(r=t,t={}),"function"!=typeof r&&Ls(7);var n={};ci(e,"",n,t);var o=Object.keys(n),s=o.length,i=0,a=0,c=s,l=new Array(s),u=[],d=function(){for(var e=0;e<u.length;++e)u[e]()},p=function(e,t){hi(function(){r(e,t)})};hi(function(){p=r});var f=function(){var e=new os(a+22),t=i,r=a-i;a=0;for(var n=0;n<c;++n){var o=l[n];try{var s=o.c.length;fi(e,a,o,o.f,o.u,s);var u=30+o.f.length+pi(o.extra),d=a+u;e.set(o.c,d),fi(e,i,o,o.f,o.u,s,a,o.m),i+=16+u+(o.m?o.m.length:0),a=d+s}catch(e){return p(e,null)}}!function(e,t,r,n,o){si(e,t,101010256),si(e,t+8,r),si(e,t+10,r),si(e,t+12,n),si(e,t+16,o)}(e,i,l.length,r,t),p(null,e)};s||f();for(var h=function(e){var t=o[e],r=n[t],c=r[0],h=r[1],m=function(){var e=-1;return{p:function(t){for(var r=e,n=0;n<t.length;++n)r=Vs[255&r^t[n]]^r>>>8;e=r},d:function(){return~e}}}(),g=c.length;m.p(c);var y=di(t),b=y.length,w=h.comment,v=w&&di(w),_=v&&v.length,E=pi(h.extra),I=0==h.level?0:8,T=function(r,n){if(r)d(),p(r,null);else{var o=n.length;l[e]=Ks(h,{size:g,crc:m.d(),c:n,f:y,m:v,u:b!=t.length||v&&w.length!=_,compression:I}),i+=30+b+E+o,a+=76+2*(b+E)+(_||0)+o,--s||f()}};if(b>65535&&T(Ls(11,0,1),null),I)if(g<16e4)try{T(null,ii(c,h))}catch(e){T(e,null)}else u.push(function(e,t,r){return r||(r=t,t={}),"function"!=typeof r&&Ls(7),ti(e,t,[Qs],function(e){return Zs(ii(e.data[0],e.data[1]))},0,r)}(c,h,T));else T(null,c)},m=0;m<c;++m)h(m);return d});async function Ui({content:e,filename:t,sensitiveValues:r}){const n=t.toLowerCase();return n.endsWith(".trace")||n.endsWith(".network")?function({content:e,sensitiveValues:t}){const r=new O,n=new B,o=r.decode(e).split("\n").map(e=>{if(!e.trim())return e;try{const r=function({event:e,sensitiveValues:t}){return j(e).with({type:"console"},e=>({...e,args:e.args?.map(e=>({...e,preview:Ii({sensitiveValues:t,str:e.preview}),value:Ti({sensitiveValues:t,value:e.value})})),text:Ii({sensitiveValues:t,str:e.text})})).with({type:"before"},e=>({...e,params:Si({obj:e.params,sensitiveValues:t}),title:e.title?Ii({sensitiveValues:t,str:e.title}):void 0})).with({type:"after"},e=>({...e,error:Ai({error:e.error,sensitiveValues:t}),result:void 0!==e.result?Ti({sensitiveValues:t,value:e.result}):void 0})).with({type:"action"},e=>({...e,error:Ai({error:e.error,sensitiveValues:t}),params:Si({obj:e.params,sensitiveValues:t}),result:void 0!==e.result?Ti({sensitiveValues:t,value:e.result}):void 0,title:e.title?Ii({sensitiveValues:t,str:e.title}):void 0})).with({type:"event"},e=>({...e,params:Si({obj:e.params,sensitiveValues:t})})).with({type:"stdout"},{type:"stderr"},e=>({...e,text:void 0!==e.text?Ii({sensitiveValues:t,str:e.text}):void 0})).with({type:"error"},e=>({...e,message:Ii({sensitiveValues:t,str:e.message})})).with({type:"log"},e=>({...e,message:Ii({sensitiveValues:t,str:e.message})})).with({type:"context-options"},e=>({...e,options:Si({obj:e.options,sensitiveValues:t}),title:e.title?Ii({sensitiveValues:t,str:e.title}):void 0})).with({type:"frame-snapshot"},e=>({...e,snapshot:Si({obj:e.snapshot,sensitiveValues:t})})).with({type:"resource-snapshot"},e=>({...e,snapshot:Si({obj:e.snapshot,sensitiveValues:t})})).with({type:"screencast-frame"},{type:"input"},e=>e).exhaustive()}({event:JSON.parse(e),sensitiveValues:t});return JSON.stringify(r)}catch{return Ii({sensitiveValues:t,str:e})}});return n.encode(o.join("\n"))}({content:e,sensitiveValues:r}):n.endsWith(".html")||n.endsWith(".dat")||n.endsWith(".json")?Ci({content:e,sensitiveValues:r}):n.startsWith("resources/")?async function({content:e,sensitiveValues:t}){return function(e){return function(e,t){if(function(e){return"string"==typeof e}(e)){!function(e){if(!e.isFile())throw new Error("Path provided was not a file!")}(y(e));const r=I(e,"r"),n=Buffer.alloc(515),o=T(r,n,0,515,0);return x(r),wi(n,o,t)}return wi(e,void 0!==t?.size?t.size:e.length,t)}(Buffer.from(e),{size:e.length})}(e)?e:Ci({content:e,sensitiveValues:t})}({content:e,sensitiveValues:r}):e}function ki(e=process.cwd()){let t=n(e);for(;;){const e=Li(t);if(e){const r={...e.dependencies,...e.devDependencies},n="@playwright/test"in r?"@playwright/test":"playwright"in r?"playwright":void 0;if(n){const e=Di(t);let r=!1,i=t;for(;;){const e=s(i,"node_modules"),t=s(e,n);if(g(t)){r=!0;break}const a=o(i);if(a===i)break;i=a}return{inNodeModules:r,installed:!0,packageManager:e,packageName:n}}}const r=o(t);if(r===t)return{inNodeModules:!1,installed:!1,packageManager:void 0};t=r}}function Li(e){const t=s(e,"package.json");let r;try{r=w(t,"utf-8")}catch{return}try{return JSON.parse(r)}catch{return}}function Di(e){const t=[["npm","package-lock.json"],["pnpm","pnpm-lock.yaml"],["yarn","yarn.lock"]];let r=e;for(;;){for(const[e,n]of t)if(g(s(r,n)))return e;const e=o(r);if(e===r)return;r=e}}function Oi(e){if("npm"===e)return["npx","playwright"];if("pnpm"===e)return["pnpm","exec","playwright"];if("yarn"===e)return["yarn","playwright"];throw new Error("Package manager not supported")}var Bi=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Ni=e=>(e instanceof Error?e.message:String(e)).slice(0,400),$i=({outputDir:e,representativeTest:t})=>{const r=["test","--trace=on","--workers=1","--retries=0","--output",e];return t.filePath&&r.push(t.filePath),t.testIdentifier?r.push("--grep",`^${Bi(t.testIdentifier)}$`):t.testTitle&&r.push("--grep",Bi(t.testTitle)),r},Mi=async e=>{const t=await X(e,{withFileTypes:!0}),n=[];for(const o of t){const t=r.join(e,o.name);if(o.isDirectory())n.push(...await Mi(t));else if(o.isFile()&&"trace.zip"===o.name){const e=await Q(t);n.push({path:t,mtimeMs:e.mtimeMs})}}return n},{zSuiteAutoHealReport:ji,zRepresentativeTest:Hi}=function(e){const t=e.enum(Jo),r=["Classification of the root cause:","",`- test: ${Qo("test")}`,`- bug: ${Qo("bug")}`,`- flake: ${Qo("flake")}`,`- ui_change: ${Qo("ui_change")}`,`- other: ${Qo("other")}`].join("\n"),n=e.object({filePath:e.string().optional(),testIdentifier:e.string().optional(),testTitle:e.string().optional()}),o=e.object({status:e.enum(["captured","capture_failed","upload_failed"]),representativeTest:n,storage:e.object({bucket:e.string(),key:e.string()}).optional(),signedUrl:e.string().optional(),error:e.string().optional()}),s=o.extend({testCaseId:e.string().min(1).describe("Test case ID this trace proof corresponds to.")}),i=e.object({erroredUrl:e.string().optional(),issueType:t.describe(r),relatedTestCaseIds:e.array(e.string()).min(1).describe("List of ALL test case IDs impacted by this root cause and fix (must be existing IDs only)."),rootCause:e.string().describe("Brief explanation of what happened (1-2 sentences).")}),a=e.discriminatedUnion("result",[i.extend({fixApplied:e.string().describe("What fix was applied (brief, specific)."),result:e.literal("fixed"),traceProof:o.optional().describe("Optional trace proof metadata for fixed issues."),traceProofs:e.array(s).min(1).optional().describe("Optional per-test trace proof metadata for fixed issues.")}),i.extend({followUpActions:e.string().optional().describe("Optional list of follow-up actions for any unfixed issues or missing data."),reasonNotFixed:e.string().describe("Why it could not be auto-fixed (brief)."),result:e.literal("unfixed")})]);return{zAutoHealReport:a,zIssueCategory:t,zRepresentativeTest:n,zSuiteAutoHealReport:e.object({issues:e.array(a).min(1).describe("List of all auto-heal issues/outcomes for this suite."),summary:e.string().min(3).describe("High-level summary (2-3 sentences) of the suite auto-heal results.")}),zTraceProof:o,zTraceProofByTest:s}}(he),Fi=({authHeader:e,diffTracker:t,orgId:n,runId:o,workingDir:s})=>N({name:"auto-heal-report",tools:[$("capture-trace-proof",["Capture and upload a Playwright trace proof for a fixed issue or fixed test case.","","Use this only for fixed results. Pass representative test info from the worker.","Pass testCaseId and call once per fixed test case.","testCaseId is for per-test mapping/storage metadata; representativeTest selects the runnable test."].join("\n"),{issueId:he.string().min(1).describe("Issue identifier for deterministic output paths and storage key naming."),proofId:he.string().min(1).optional().describe("Optional id for deterministic proof naming and deduplication."),representativeTest:Hi.optional().default({}),testCaseId:he.string().min(1).optional().describe("Optional test case ID when capturing per-test trace proofs.")},async({issueId:t,proofId:i,representativeTest:a,testCaseId:c})=>{const l=he.string().min(1).parse(t),u=null==i?void 0:he.string().min(1).parse(i),d=null==c?void 0:he.string().min(1).parse(c),p=await(async({authHeader:e,issueId:t,orgId:n,proofId:o,representativeTest:s,runId:i,testCaseId:a,workingDir:c})=>{if(!(e=>null!=e.filePath||null!=e.testTitle||null!=e.testIdentifier)(s))return{status:"capture_failed",representativeTest:s,error:"Representative test info is missing (need filePath, testTitle, or testIdentifier)."};const l=ki(c);if(!l.installed||!l.inNodeModules||!l.packageManager)return{status:"capture_failed",representativeTest:s,error:"Playwright is not installed in the current workspace."};const u=(e=>es(e)??"issue")(t),d=(({proofId:e,testCaseId:t})=>ts(t)??ts(e))({testCaseId:a,proofId:o}),p=r.join(c,".stably","autoheal-proof",u,d??"issue"),[h,...m]=Oi(l.packageManager),g=[...m,...$i({outputDir:p,representativeTest:s})];try{await Z(p,{force:!0,recursive:!0}),await z(p,{recursive:!0});const{code:r,stderr:l,timedOut:u}=await(async({args:e,command:t,cwd:r,env:n,timeoutMs:o})=>await new Promise((s,i)=>{const a=f(t,e,{cwd:r,env:n??process.env,stdio:["ignore","ignore","pipe"]});let c="",l=!1;a.stderr.on("data",e=>{c+=e.toString()});const u=setTimeout(()=>{l=!0,a.kill("SIGTERM")},o);a.on("error",e=>{clearTimeout(u),i(e)}),a.on("close",e=>{clearTimeout(u),s({code:e,stderr:c,timedOut:l})})}))({args:g,command:h,cwd:c,env:{...process.env,STABLY_INTERNAL_DISABLE_REPORTING:"1"},timeoutMs:3e5});if(u)return{status:"capture_failed",representativeTest:s,error:"Trace proof run timed out while executing Playwright verification."};if(0!==r)return{status:"capture_failed",representativeTest:s,error:`Trace proof run failed (exit code ${r??"unknown"}): ${l.trim().slice(0,280)}`};const d=await(async e=>{const t=await Mi(e);if(0!==t.length)return t.sort((e,t)=>t.mtimeMs-e.mtimeMs),t[0]?.path})(p);if(!d)return{status:"capture_failed",representativeTest:s,error:"Trace proof run completed, but no trace.zip was produced."};const{traceBucketPath:m,uploadUrl:y,sensitiveValues:w}=await(async({authHeader:e,issueId:t,proofId:r,testCaseId:n,contentType:o="application/zip",orgId:s,runId:i})=>{const a=await(c={auth:e,body:{contentType:o,issueId:t,proofId:r,testCaseId:n},client:Zr(),headers:Qn(s),path:{runId:i}},(c.client??Gr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-trace/upload-url",...c,headers:{"Content-Type":"application/json",...c.headers}}));var c;if(a.error)throw new Error(`Failed to presign trace upload (${a.response.status})`);const l=ro.parse(a.data);return{traceBucketPath:l.traceBucketPath,expiresInSeconds:l.expiresInSeconds,key:l.key,uploadUrl:l.uploadUrl,sensitiveValues:l.sensitiveValues}})({authHeader:e,issueId:t,proofId:o,orgId:n,runId:i,testCaseId:a}),v=await async function({tracePath:e,sensitiveValues:t}){const r=[],n=b(e);for await(const e of n)r.push(e);return async function({sensitiveValues:e,traceBuffer:t}){const r=e.filter(e=>!(e.length<3||vi.some(t=>t.test(e))||_i.some(t=>e.includes(t))));if(0===r.length)return new Uint8Array(t);const n=[...r].sort((e,t)=>t.length-e.length),o=await Ri(new Uint8Array(t)),s=Object.entries(o),i=await Promise.all(s.map(async([e,t])=>[e,await Ui({content:t,filename:e,sensitiveValues:n})])),a=Object.fromEntries(i);return Pi(a)}({traceBuffer:new Uint8Array(Buffer.concat(r)),sensitiveValues:t})}({tracePath:d,sensitiveValues:w});try{await(async({contentType:e="application/zip",traceBuffer:t,uploadUrl:r})=>{const n=await fetch(r,{body:Buffer.from(t),headers:{"Content-Type":e},method:"PUT"});if(!n.ok)throw new Error(`Failed to upload trace (${n.status})`)})({traceBuffer:v,uploadUrl:y})}catch(e){return{status:"upload_failed",representativeTest:s,error:Ni(e)}}return{status:"captured",representativeTest:s,storage:m}}catch(e){return{status:"capture_failed",representativeTest:s,error:Ni(e)}}})({authHeader:e,issueId:l,orgId:n,proofId:u,representativeTest:Hi.parse(a??{}),runId:o,testCaseId:d,workingDir:s}),h="string"==typeof d?{testCaseId:d,...p}:p;return{content:[{text:JSON.stringify(h),type:"text"}]}}),$("generate-report",["After attempting to fix all broken tests (skip only those truly infeasible), generate and return a suite auto-heal report in the required schema.","","Ensure the payload matches zSuiteAutoHealReport exactly; include every issue discovered."].join("\n"),{report:ji},async({report:r})=>{const s=await t.computeDiff(),i=(e=>{if(!e||"object"!=typeof e)return e;const t=e;if(!Array.isArray(t.issues))return e;const r=t.issues.map(e=>{if(!e||"object"!=typeof e)return e;const t=e;if("fixed"!==t.result||null!=t.traceProof||!Array.isArray(t.traceProofs))return e;const[r]=t.traceProofs;if(!r||"object"!=typeof r)return e;const n={...r};return delete n.testCaseId,{...t,traceProof:n}});return{...t,issues:r}})(r),a=ji.parse(i);try{await(async({authHeader:e,orgId:t,report:r,runId:n})=>{const o=await(s={auth:e,body:{report:JSON.stringify(r)},client:Zr(),headers:Qn(t),path:{runId:n}},(s.client??Gr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-report",...s,headers:{"Content-Type":"application/json",...s.headers}}));var s;if(o.error)throw new Error(`Failed to upload auto-heal report (${o.response.status})`)})({authHeader:e,orgId:n,report:a,runId:o});const{diffBucketPath:t,uploadUrl:r}=await no({authHeader:e,contentType:"text/plain",orgId:n,runId:o});await oo({contentType:"text/plain",diff:s,uploadUrl:r}),await so({authHeader:e,diffBucketPath:t,orgId:n,runId:o})}catch(e){return console.error("[auto-heal-report] Failed to upload report or diff:",e),{content:[{text:`Error: Failed to upload auto-heal report or diff. ${e instanceof Error?e.message:String(e)} Please surface this to the user, and terminate the session.`,type:"text"}]}}return{content:[{text:"Auto-heal report generated. You may terminate this session now.",type:"text"}]}})],version:"0.0.1"}),Gi=({onComplete:e,onRestartRequested:t})=>N(e?{name:"session-control",tools:[$("complete_session",["Call this tool when you have completed your task and the session should end.","Use this instead of waiting for the user to manually terminate.","Only call this when you are confident the task is fully complete."].join("\n"),{summary:he.string().describe("A brief summary of what was accomplished")},({summary:t})=>{const r="string"==typeof t?t:String(t);return e(),Promise.resolve(`Session complete: ${r}`)})]}:{name:"stably-agent-control",version:"1.0.0",tools:[$("restart_mcp_servers",'Restart the MCP servers to reinitialize browser tools after dependency changes.\n\nWHEN TO USE:\n- After installing or updating @playwright/test to version 1.56.x\n- When browser tools fail due to version mismatch errors\n- When the user has fixed a dependency issue and you need to reinitialize\n\nIMPORTANT: The restart happens at the END of your current turn.\n- Do NOT call any browser tools (setup_page, navigate, etc.) after this tool in the same turn - they will use the OLD servers\n- After calling this tool, END your turn naturally (no more tool calls)\n- The system will automatically continue in a new turn once the tools are restarted\n- Do NOT ask the user to reply again just to resume (only ask if you truly need additional input)\n\nEnd your turn briefly. You may say something like:\n- "Restarting browser tools now…"\n- "Tools are restarting to pick up the dependency changes…"',{},()=>(t(),Promise.resolve({content:[{type:"text",text:"MCP servers are being restarted. Browser tools will be reinitialized."}]})))]}),Yi=he.object({commentUrl:he.string()}),Wi=({prContext:e,authHeader:t,orgId:r,onReportPosted:n})=>N({name:"create-report",tools:[$("post_create_report",`Post a test creation report as a GitHub comment on PR #${e.prNumber}.\nCall this tool at the end of test creation to summarize what was created.\nThe report will be posted to: ${e.prUrl}\n\nWHEN TO USE:\n- After you have finished creating test files\n- To provide a summary of the tests created on the PR for visibility\n\nThe report will include:\n- A list of all test files created\n- Your summary of what was tested`,{summary:he.string().describe("A summary of the tests created. Include what features/flows are tested and any important notes."),filesCreated:he.array(he.string()).describe("List of test file paths that were created (relative to workspace root)")},async({summary:o,filesCreated:s})=>{const i=Array.isArray(s)?s:[];Fn.info("[create-report] Posting report to GitHub PR",{prNumber:e.prNumber,filesCount:i.length});try{const s={summary:"string"==typeof o?o:String(o),filesCreated:i.map(String)},a=await async function({authHeader:e,orgId:t,prNumber:r,owner:n,repo:o,report:s}){const i=new URL("/internal/v1/cli/create-report",Wr).toString(),a={Authorization:e,"Content-Type":"application/json"};t&&(a["x-stably-org-id"]=t),Fn.debug("Posting create report to GitHub",{prNumber:r,owner:n,repo:o,filesCount:s.filesCreated.length});const c=await fetch(i,{method:"POST",headers:a,body:JSON.stringify({prNumber:r,owner:n,repo:o,report:s}),signal:AbortSignal.timeout(3e4)});if(!c.ok){const e=await c.text().catch(()=>"");throw Fn.error("Failed to post create report",{status:c.status,error:e.slice(0,500)}),new Error(`Failed to post create report: ${c.status} ${e.slice(0,200)}`)}const l=Yi.parse(await c.json());return Fn.info("Create report posted successfully",{commentUrl:l.commentUrl}),l}({authHeader:t,orgId:r,prNumber:e.prNumber,owner:e.owner,repo:e.repo,report:s});return n?.(a),Fn.info("[create-report] Report posted successfully",{commentUrl:a.commentUrl}),{content:[{type:"text",text:`✅ Test creation report posted to PR #${e.prNumber}\n\nView the comment: ${a.commentUrl}`}]}}catch(e){const t=e instanceof Error?e.message:String(e);return Fn.error("[create-report] Failed to post report",{error:t}),{content:[{type:"text",text:`❌ Failed to post report to GitHub: ${t}\n\nThe tests were still created successfully, but the PR comment could not be posted.`}],isError:!0}}})]}),Vi=e=>e.replace(/Bearer\s+[A-Za-z0-9._-]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{16,}\b/g,"[redacted]").replace(/\bstably_[A-Za-z0-9_-]{16,}\b/g,"[redacted]"),zi=(e,t)=>({message:Vi(e),status:t?.status,statusText:t?.statusText}),Ki=new Set(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_CUSTOM_HEADERS","ANTHROPIC_DEFAULT_HAIKU_MODEL","ANTHROPIC_DEFAULT_OPUS_MODEL","ANTHROPIC_DEFAULT_SONNET_MODEL","ANTHROPIC_FOUNDRY_API_KEY","ANTHROPIC_MODEL","ANTHROPIC_SMALL_FAST_MODEL","ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION","AWS_BEARER_TOKEN_BEDROCK","BASH_DEFAULT_TIMEOUT_MS","BASH_MAX_OUTPUT_LENGTH","BASH_MAX_TIMEOUT_MS","CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR","CLAUDE_CODE_API_KEY_HELPER_TTL_MS","CLAUDE_CODE_CLIENT_CERT","CLAUDE_CODE_CLIENT_KEY_PASSPHRASE","CLAUDE_CODE_CLIENT_KEY","CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS","CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC","CLAUDE_CODE_DISABLE_TERMINAL_TITLE","CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL","CLAUDE_CODE_MAX_OUTPUT_TOKENS","CLAUDE_CODE_SHELL_PREFIX","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SUBAGENT_MODEL","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_VERTEX","CLAUDE_CONFIG_DIR","DISABLE_AUTOUPDATER","DISABLE_BUG_COMMAND","DISABLE_COST_WARNINGS","DISABLE_ERROR_REPORTING","DISABLE_NON_ESSENTIAL_MODEL_CALLS","DISABLE_PROMPT_CACHING","DISABLE_PROMPT_CACHING_HAIKU","DISABLE_PROMPT_CACHING_OPUS","DISABLE_PROMPT_CACHING_SONNET","DISABLE_TELEMETRY","HTTP_PROXY","HTTPS_PROXY","MAX_MCP_OUTPUT_TOKENS","MAX_THINKING_TOKENS","MCP_TIMEOUT","MCP_TOOL_TIMEOUT","NO_PROXY","SLASH_COMMAND_TOOL_CHAR_BUDGET","USE_BUILTIN_RIPGREP","VERTEX_REGION_CLAUDE_3_5_HAIKU","VERTEX_REGION_CLAUDE_3_7_SONNET","VERTEX_REGION_CLAUDE_4_0_OPUS","VERTEX_REGION_CLAUDE_4_0_SONNET","VERTEX_REGION_CLAUDE_4_1_OPUS"]),qi=async({authHeader:e,mode:t,maxTurnsOverride:r})=>{const n=Zr();Fn.debug("Requesting subagent definitions from API",{mode:t,maxTurnsOverride:r});const o=await(s={client:n,auth:e,body:{mode:t,maxTurnsOverride:r}},(s.client??Gr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/prompts/subagents",...s,headers:{"Content-Type":"application/json",...s.headers}}));var s;if(401===o.response.status)throw Fn.warn("Subagent definitions fetch failed: unauthorized (401)"),await mn(),new Error("Your session has expired or been revoked. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(403===o.response.status)throw Fn.warn("Subagent definitions fetch failed: forbidden (403)"),await mn(),new Error("You no longer have access to this organization. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(o.error)throw Fn.warn("Subagent definitions fetch failed",{error:o.error}),new Error(`Failed to fetch subagent definitions: ${JSON.stringify(o.error)}`);const{subagents:i}=o.data;return Fn.debug("Subagent definitions received",{count:Object.keys(i).length}),i},Ji=r.dirname(A(import.meta.url)),Xi=r.join(".claude-plugin","plugin.json"),Qi=[r.join("packages","agent-plugin","stably-plugin"),r.join("agent-plugin","stably-plugin")];function Zi(e){return g(r.join(e,Xi))}var{zStablyYaml:ea}=function(e){const t=e.object({cron:e.string(),stablyTestArgs:e.string().optional(),timezone:e.string().optional()}),r=e.object({maxTurnsPerIssue:e.number().int().positive().optional(),maxParallelWorkers:e.number().int().positive().optional(),rules:e.string().optional(),skipAfterConsecutiveUnfixed:e.number().int().positive().optional()}),n=e.object({fix:r.optional()});return{zStablyYaml:e.object({schedules:e.record(e.string(),t).optional(),agent:n.optional()}),zAgentConfig:n,zAgentFixConfig:r,zScheduleEntry:t}}(le),ta=async(e,t)=>{try{const r=await sn(e,t);if(!r)return void Fn.debug(`No ${t} found`);const n=await V(r,"utf-8");if(!n.trim())return;return n.length>1e4?(Fn.warn(`${t} exceeds max length (${n.length} > 10000), truncating`,{path:r}),{content:n.slice(0,1e4),path:r}):(Fn.debug(`Loaded ${t} rules`,{path:r,contentLength:n.length}),{content:n,path:r})}catch(e){return void Fn.warn(`Failed to read ${t}`,{error:e})}},ra=["Bash","Read","Write","Edit","Glob","Grep","Task","Skill"],na=["Task","mcp__playwright-test","Skill"],oa=["Bash","Read","Write","Edit","Glob","Grep","mcp__session-control"],sa=e=>{if("EPIPE"!==e.code)throw e},ia="__main__",aa=e=>"mcp__auto-heal-report__generate-report"===e,ca=e=>"mcp__auto-heal-report__capture-trace-proof"===e?"Verify Test Run":"mcp__auto-heal-report__generate-report"===e?"Generate Report":Ko(e);async function la(e,t){return!!e&&(!!e.hasQueuedMessages()||new Promise(r=>{const n=setTimeout(()=>{clearInterval(o),r(!1)},t),o=setInterval(()=>{e.hasQueuedMessages()&&(clearTimeout(n),clearInterval(o),r(!0))},200)}))}var ua=async e=>{if("single"===e.mode||"build"===e.mode){const t=Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt;Fn.initSession(t||"create-from-diff")}else"fix"===e.mode&&Fn.initSession(`fix-${e.runId}`);Fn.info("Agent session starting",{mode:e.mode}),process.stdout.on("error",sa),process.stderr.on("error",sa);const i=e=>{if("EPIPE"!==e.code)throw e};process.on("uncaughtException",i),Fn.debug("Checking authentication");const a=await Kn({autoLogin:"chat"===e.mode||"init"===e.mode}),c=(e=>"env"===e.type?e.auth.apiKey:e.auth.accessToken)(a);Fn.debug("Authentication resolved",{authType:a.type});const l="oauth"===a.type?a.auth.context.orgId:void 0,u=r.resolve(process.cwd()),d=r.join(u,".env"),p=m.existsSync(d)&&m.statSync(d).isFile(),f=p?t(m.readFileSync(d,"utf8")):{};Fn.debug("Environment file",{path:d,exists:p,variableCount:Object.keys(f).length});const h="chat"!==e.mode&&"init"!==e.mode,y="chat"===e.mode;let b=new Po;const w="chat"===e.mode?e.getHelpText:void 0,v={log:[],promptDisplay:j(e).with({mode:"chat"},()=>"Ask Stably to build tests for you").with({mode:"init"},()=>"Setting up Playwright and Stably SDK").with({mode:"fix"},()=>"Fixing broken tests").with({mode:"build"},()=>"Building tests from specifications").with({mode:"single"},e=>{const t=(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt)?.trim();return t||"Creating tests from PR/branch changes"}).exhaustive(),status:"running"};let _,E,I,T,x=h,S=!1,A=!1,C=0,R=0,P=!1;const U=[];let k,L,D=[],O=!1,B=!1,N=0;const $=new Map;let F=null,Y=!1,W=!1;const z=Date.now();let K,q="fix"===e.mode?{suiteId:e.runId,phase:"initializing",totalTests:null,fixedTests:0,failedTests:0,currentTestDescription:null,lastTestDescription:null,startedAt:z,endedAt:null,isError:!1,updatedAt:z,recentActivity:[],workers:[{id:ia,testDescription:"Orchestrator",workerType:"main",status:"running",summary:null,startedAt:z,endedAt:null,activity:[]}]}:null;const J=new Set,X=(e,t)=>{if(!q)return;const r=q.workers.map(r=>{if(r.id!==e)return r;const n=[...r.activity,{...t,timestamp:Date.now()}].slice(-15);return{...r,activity:n}});ee({workers:r})},Q=e=>{if(!q)return;const t=[...q.recentActivity,{...e,timestamp:Date.now()}].slice(-10);ee({recentActivity:t})},Z=e=>(q?.workers??[]).map(t=>t.id===ia?{...t,status:e?"failed":"succeeded",endedAt:t.endedAt??Date.now()}:"running"===t.status?{...t,status:"failed",endedAt:Date.now()}:t),ee=e=>{q&&!K?.isClosed&&(q={...q,...e,updatedAt:Date.now()},K?.sendProgress(q))},te=async t=>{if("fix"===e.mode){if("STARTED"===t){if(Y)return;Y=!0}else{if(W)return;W=!0}try{await(async({authHeader:e,orgId:t,runId:r,status:n})=>{const o=await(s={auth:e,body:{status:n},client:Zr(),headers:Qn(t),path:{runId:r}},(s.client??Gr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-status",...s,headers:{"Content-Type":"application/json",...s.headers}}));var s;if(o.error)throw new Error(`Failed to update autoheal status (${o.response.status})`)})({authHeader:c,orgId:l,runId:e.runId,status:t})}catch{}}},re="single"===e.mode||"build"===e.mode,ne=Date.now();let oe,se=null;const ie=e=>{se&&!oe?.isClosed&&(se={...se,...e,updatedAt:Date.now()},oe?.sendProgress(se))},ae=e=>{if(!se)return;const t=[...se.recentActivity,{...e,timestamp:Date.now()}].slice(-10);ie({recentActivity:t})};if(re||"fix"===e.mode)try{const t=new URL("/internal/v1/cli/progress",Wr).toString(),r={Authorization:c,"Content-Type":"application/json"};l&&(r["x-stably-org-id"]=l);const n="single"===e.mode?"create":"build"===e.mode?"build":"fix",o=await fetch(t,{method:"POST",headers:r,body:JSON.stringify({mode:n,projectId:qn(a),agentId:H.randomUUID(),..."fix"===e.mode?{playwrightSuiteRunId:e.runId}:{}}),signal:AbortSignal.timeout(1e4)});if(o.ok){const{sessionId:t}=await o.json();if(re){const r="single"===e.mode||"build"===e.mode?Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt:null,n=Uo(u);se={sessionId:t,phase:"initializing",startedAt:ne,endedAt:null,isError:!1,updatedAt:ne,currentActivity:null,filesCreated:[],recentActivity:[],prompt:r||null,environment:{gitBranch:n?.branch??null,workingDirectory:u,nodeVersion:process.version,cliVersion:Yr}},oe=new ao({authHeader:c,orgId:l,sessionId:t,onUserMessage:e=>{b&&(Fn.info("[ws] Injecting web UI message into agent",{contentLength:e.length}),ae({type:"user_message",summary:e}),me({text:`[Web] ${e}`}),b.pushText(`[Message from web UI user]: ${e}`),x||(x=!0,Ue({status:"running"})))}}),oe.start(),ie({phase:"initializing"})}Fn.info(`[${n}] Progress session created`,{sessionId:t})}else{const e=await o.text().catch(()=>"");Fn.warn(`[${n}] Failed to create progress session: ${o.status} ${t} — ${e.slice(0,300)}`)}}catch(e){const t=e instanceof Error?e.message:String(e);Fn.warn(`[progress] Session creation failed (non-fatal): ${t}`)}const ce={current:e=>{}},le={current:async()=>{}},{addSubagentActivity:ue,addSubagentStart:de,addTool:pe,addToolResult:fe,appendText:he,appendUserMessage:me,cleanup:Ie,setExiting:xe,setRunningLabel:Se,setStatus:Ae,setSubagentStatus:Ce,updateFixProgress:Re}=await(async(e,t)=>{const{Box:r,Static:n,Text:o,render:s,useInput:i}=await import("ink"),a=!!process.stdin.isTTY,c=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],l=()=>_e(o,{inverse:!0,children:" "}),u=(({Box:e,Text:t,useInput:r},n,o)=>function({onChoice:s,prompt:i}){const[a,c]=ge(0),[l,u]=ge(!1),[d,p]=ge(""),f=[{label:"Yes, allow this once",value:"allow"},{label:"Yes, always allow for this session",value:"always"},{label:"No, tell AI what to do differently",value:"deny_with_message"}];r((e,t)=>{if(l)return t.return?void s("deny_with_message",d||"User denied this action"):t.escape?(u(!1),void p("")):t.backspace||t.delete?void p(e=>e.slice(0,-1)):void(t.ctrl||t.meta||p(t=>`${t}${e}`));if(t.upArrow)return void c(e=>e>0?e-1:f.length-1);if(t.downArrow)return void c(e=>e<f.length-1?e+1:0);if(t.return){const e=f[a];return"deny_with_message"===e.value?void u(!0):void s(e.value)}const r=parseInt(e,10);if(r>=1&&r<=f.length){const e=f[r-1];if("deny_with_message"===e.value)return void u(!0);s(e.value)}},{isActive:o});const h=Ko(i.toolName),m=qo(i.toolName,i.input);return Ee(e,{borderColor:"yellow",borderStyle:"round",flexDirection:"column",marginTop:1,paddingX:1,paddingY:0,children:[_e(t,{bold:!0,color:"yellow",children:"Permission Required"}),Ee(e,{flexDirection:"column",marginTop:1,children:[_e(t,{color:"magenta",children:h}),null!=m&&Ee(t,{color:"gray",children:[" ",m]})]}),null!=i.decisionReason&&_e(e,{marginTop:1,children:Ee(t,{color:"gray",children:["Reason: ",i.decisionReason]})}),Ee(e,l?{flexDirection:"column",marginTop:1,children:[_e(t,{color:"gray",children:"Enter message for AI (press Enter to submit, Esc to cancel):"}),Ee(t,{children:[_e(t,{color:"yellow",children:">"})," ",d,_e(n,{})]})]}:{flexDirection:"column",marginTop:1,children:[_e(t,{color:"gray",children:"Use ↑↓ arrows or number keys to select:"}),f.map((e,r)=>_e(t,{children:Ee(t,{color:r===a?"cyan":void 0,children:[r===a?"❯":" "," ",r+1,". ",e.label]})},e.value))]})]})})({Box:r,Text:o,useInput:i},l,a),d=(({Cursor:e,inkComponents:{Box:t,Static:r,Text:n,useInput:o},isRawModeSupported:s,PermissionPrompt:i,Spinner:a})=>{const c=({progress:e})=>{const[r,o]=ge(Date.now());be(()=>{const e=setInterval(()=>o(Date.now()),1e3);return()=>clearInterval(e)},[]);const s=r-e.startedAt,i=Math.floor(s/1e3),a=Math.floor(i/60),c=i%60,l=a>0?`${a}m ${c.toString().padStart(2,"0")}s`:`${c}s`,{label:u,color:d}={initializing:{label:"Fetching test results",color:"gray"},triage:{label:"Triaging failures",color:"yellow"},fixing:{label:"Fixing tests",color:"cyan"},validation:{label:"Validating fixes",color:"blue"},complete:{label:"Complete",color:"green"}}[e.phase],p=e.fixedTests+e.failedTests,f="fixing"===e.phase&&p>0?null!==e.totalTests?` (fixed ${e.fixedTests}/${e.totalTests}${e.failedTests>0?`, failed ${e.failedTests}`:""})`:` (fixed ${e.fixedTests}${e.failedTests>0?`, failed ${e.failedTests}`:""})`:"";return _e(t,{flexDirection:"column",children:Ee(n,{children:[_e(n,{color:d,bold:!0,children:u}),_e(n,{color:"gray",children:f}),Ee(n,{color:"gray",children:[" [",l,"]"]})]})})},l=({progress:e})=>{const r=e.endedAt??Date.now(),o=Math.floor((r-e.startedAt)/1e3),s=Math.floor(o/60),i=o%60,a=s>0?`${s}m ${i.toString().padStart(2,"0")}s`:`${i}s`,c=e.isError?"yellow":"green",l=e.isError?"Fix stopped":"Fix complete";return Ee(t,{flexDirection:"column",children:[Ee(n,{color:c,bold:!0,children:[l," in ",a]}),null!==e.totalTests&&Ee(n,{color:"gray",children:[e.fixedTests,"/",e.totalTests," tests fixed",e.failedTests>0?`, ${e.failedTests} failed`:""]})]})},u=e=>{if("subagent"===e.kind&&e.subagent){const{subagent:r}=e,o="complete"===r.status?"green":"error"===r.status?"red":"yellow";return Ee(t,{flexDirection:"column",marginTop:1,children:[Ee(n,{children:[_e(n,{color:o,bold:!0,children:"Agent"}),r.description?Ee(n,{color:"gray",children:[" (",r.description,")"]}):null]}),r.activities.length>0&&_e(t,{flexDirection:"column",marginLeft:2,children:r.activities.map(e=>(e=>"tool"===e.kind?Ee(n,{color:"magenta",children:["• ",e.content]},e.id):"tool_result"===e.kind?_e(n,{color:"gray",children:e.content},e.id):null)(e))})]},e.id)}return"tool"===e.kind?Ee(n,{color:"magenta",children:["• ",e.content]},e.id):"tool_result"===e.kind?_e(n,{color:"gray",children:e.content},e.id):"user"===e.kind?Ee(n,{color:"cyan",children:["You: ",e.content]},e.id):_e(n,{children:e.content},e.id)},d="vscode"===process.env.TERM_PROGRAM,p=(e,t)=>{if(t<=0)return 0;let r=t-1;for(;r>0&&/\s/.test(e[r]);)r--;for(;r>0&&!/\s/.test(e[r-1]);)r--;return r},f=(e,t)=>{if(t>=e.length)return e.length;let r=t;for(;r<e.length&&!/\s/.test(e[r]);)r++;for(;r<e.length&&/\s/.test(e[r]);)r++;return r},h=(e,t)=>{if(t<=0)return 0;const r=e.lastIndexOf("\n",t-1);return-1===r?0:r+1},m=(e,t)=>{const r=e.indexOf("\n",t);return-1===r?e.length:r};return function({onExit:g,onPermissionChoice:y,onSend:b,showSpinnerImmediately:w,state:v}){const[_,E]=ge({value:"",cursor:0}),I=_.value,T=_.cursor,x=ye(!1),S=ye(void 0),[A,C]=ge(!1),R=ye(0),P=v.log.at(-1),U="text"===P?.kind&&"running"===v.status,k=v.log.findIndex(e=>"subagent"===e.kind&&"running"===e.subagent?.status),L=d?0:-1!==k?k:U?v.log.length-1:v.log.length;be(()=>{v.log.length<R.current&&(R.current=0),L>R.current&&(R.current=L)},[v.log.length,L]);const D=v.log.slice(0,R.current),O=v.log.slice(R.current),B=!!v.permissionPrompt,N=we(async()=>{x.current?(S.current&&clearTimeout(S.current),await(g?.()),process.exit(0)):(x.current=!0,C(!0),S.current=setTimeout(()=>{x.current=!1,C(!1)},2e3))},[g]);o((e,t)=>{t.ctrl&&"c"===e&&N().catch(()=>process.exit(1))},{isActive:s}),be(()=>{if(B||!b)return;const e=e=>{const t=e.toString();""!==t&&"[1;5~"!==t?""!==t&&"[4;5~"!==t?""!==t&&"[1~"!==t&&"OH"!==t&&"[7~"!==t?""!==t&&"[4~"!==t&&"OF"!==t&&"[8~"!==t||E(e=>({...e,cursor:m(e.value,e.cursor)})):E(e=>({...e,cursor:h(e.value,e.cursor)})):E(e=>({...e,cursor:e.value.length})):E(e=>({...e,cursor:0}))};return process.stdin.on("data",e),()=>{process.stdin.off("data",e)}},[B,b,I]),o((e,t)=>{if(!t.ctrl||"c"!==e){if(t.return){const e=I.trim();return e&&b?.(e),void E({value:"",cursor:0})}t.ctrl&&"w"===e||t.ctrl&&t.backspace?E(e=>{const t=p(e.value,e.cursor);return{value:e.value.slice(0,t)+e.value.slice(e.cursor),cursor:t}}):!t.backspace&&!t.delete||t.ctrl?t.ctrl&&t.leftArrow||t.meta&&"b"===e?E(e=>({...e,cursor:p(e.value,e.cursor)})):t.ctrl&&t.rightArrow||t.meta&&"f"===e?E(e=>({...e,cursor:f(e.value,e.cursor)})):t.leftArrow?E(e=>({...e,cursor:Math.max(0,e.cursor-1)})):t.rightArrow?E(e=>({...e,cursor:Math.min(e.value.length,e.cursor+1)})):t.ctrl&&"a"===e?E(e=>({...e,cursor:0})):t.ctrl&&"e"===e?E(e=>({...e,cursor:e.value.length})):!e||t.ctrl||t.meta||t.escape||e.includes("")||/^\[./.test(e)||/^O[A-D]$/.test(e)||E(t=>({value:t.value.slice(0,t.cursor)+e+t.value.slice(t.cursor),cursor:t.cursor+e.length})):E(e=>e.cursor>0?{value:e.value.slice(0,e.cursor-1)+e.value.slice(e.cursor),cursor:e.cursor-1}:e)}},{isActive:s&&!!b&&!B});const $=ve(()=>"running"===v.status?_e(a,{label:v.runningLabel??"Working"}):"success"!==v.status?_e(n,{color:"red",children:"✖ Failed"}):void 0,[v.runningLabel,v.status]),M=!(w||!b||"running"!==v.status||0!==v.log.length||v.resultText||v.errorText),j="running"===v.status&&!M||v.log.length>0||v.resultText||v.errorText||"running"!==v.status;return Ee(t,{flexDirection:"column",children:[_e(r,{items:["header"],children:()=>Ee(t,{flexDirection:"column",flexShrink:0,children:[_e(n,{color:"cyan",bold:!0,children:"Stably Agent"}),_e(t,{flexDirection:"column",marginTop:1,children:_e(n,{color:"gray",children:v.promptDisplay})})]},"header")}),D.length>0&&_e(r,{items:D,children:e=>u(e)}),O.length>0&&_e(t,{flexDirection:"column",children:O.map(e=>u(e))}),"error"===v.status&&v.errorText&&_e(t,{marginTop:1,children:_e(n,{color:"red",children:v.errorText})}),"success"===v.status&&v.resultText&&_e(t,{marginTop:1,children:_e(n,{children:v.resultText})}),j&&_e(t,{flexDirection:"column",flexShrink:0,marginTop:1,children:"running"===v.status&&v.fixProgress?Ee(t,{flexDirection:"column",children:[Ee(t,{children:[_e(a,{}),_e(n,{children:" "}),_e(c,{progress:v.fixProgress})]}),"fixing"===v.fixProgress.phase&&v.log.flatMap(e=>{const{subagent:r}=e;if("subagent"!==e.kind||"fix-worker"!==r?.subagentType||"running"!==r.status)return[];const{activities:o}=r,s=o.filter(e=>"tool"===e.kind).length,i=o.at(-1),c=o.filter(e=>"tool"===e.kind).at(-1),l=(()=>{if(!i)return null;if("tool"===i.kind)return null;if("text"===i.kind){const e=i.content.trim().split("\n").at(-1)?.trim();return e?e.length>80?`${e.slice(0,80)}…`:e:null}if("tool_result"===i.kind){const e=i.content.trim().split("\n")[0]?.trim();return e?e.length>80?`${e.slice(0,80)}…`:e:null}return null})();return Ee(t,{flexDirection:"column",children:[Ee(n,{children:[" ",_e(a,{}),Ee(n,{color:"gray",children:[r.description||"fix-worker",s>0?` (${s} ${1===s?"cycle":"cycles"})`:""]})]}),c&&Ee(n,{color:"gray",dimColor:!0,children:[" • ",c.content]}),l&&Ee(n,{color:"gray",dimColor:!0,children:[" ",l]})]},e.id)})]}):"success"!==v.status&&"error"!==v.status||!v.fixProgress?$:_e(l,{progress:v.fixProgress})}),null!=v.permissionPrompt&&null!=y&&_e(i,{onChoice:y,prompt:v.permissionPrompt}),null!=b&&null==v.permissionPrompt&&!v.isExiting&&Ee(t,{borderColor:"gray",borderStyle:"round",flexDirection:"column",flexShrink:0,marginTop:1,paddingX:1,paddingY:0,children:[_e(n,{color:"gray",children:"Type a message and press Enter. Press Ctrl+C to exit."}),Ee(n,{children:[_e(n,{color:"yellow",children:">"})," ",I.slice(0,T),_e(e,{}),I.slice(T)]})]}),A&&Ee(t,{marginTop:1,flexDirection:"column",children:[_e(n,{color:"yellow",children:"Press Ctrl+C again to exit"}),Pn&&Ee(n,{color:"gray",children:["Debug log: ",Dn]})]})]})}})({Cursor:l,inkComponents:{Box:r,Static:n,Text:o,useInput:i},isRawModeSupported:a,PermissionPrompt:u,Spinner:({label:e})=>{const[t,r]=ge(0);return be(()=>{const e=setInterval(()=>r(e=>(e+1)%c.length),80);return()=>clearInterval(e)},[]),Ee(o,{color:"yellow",children:[c[t]," ",e]})}});let p=e;t?.isFixMode&&(p.fixProgress={phase:"initializing",totalTests:null,fixedTests:0,failedTests:0,currentTestDescription:null,lastTestDescription:null,startedAt:Date.now(),endedAt:null,isError:!1});const f={current:(e,t)=>{}},h=s(_e(d,{onExit:t?.onExit,onPermissionChoice:(e,t)=>f.current(e,t),onSend:t?.onSend,showSpinnerImmediately:t?.showSpinnerImmediately,state:p}),{exitOnCtrlC:!1}),m=()=>{p={...p},h.rerender(_e(d,{onExit:t?.onExit,onPermissionChoice:(e,t)=>f.current(e,t),onSend:t?.onSend,showSpinnerImmediately:t?.showSpinnerImmediately,state:p}))},g=({text:e})=>{e&&(p.log=[...p.log,{content:e,id:p.log.length,kind:"user"}],m())},y=new Map;return{addSubagentActivity:({toolUseId:e,kind:t,content:r})=>{const n=y.get(e);if(void 0===n)return void console.error("[addSubagentActivity] No entry index for toolUseId:",e);const o=p.log[n];if(o&&"subagent"===o.kind&&o.subagent){if("text"===t){const e=o.subagent.activities.at(-1);e&&"text"===e.kind?e.content+=r:o.subagent.activities.push({id:o.subagent.activities.length,kind:"text",content:r.replace(/^\s*\n+/,"")})}else o.subagent.activities.push({id:o.subagent.activities.length,kind:t,content:r});p.log=[...p.log],m()}else console.error("[addSubagentActivity] Entry not found or not subagent:",{entryIndex:n,entryKind:o?.kind})},addSubagentStart:({toolUseId:e,subagentType:t,description:r})=>{const n=p.log.length;if(y.set(e,n),p.log=[...p.log,{content:"",id:n,kind:"subagent",subagent:{toolUseId:e,subagentType:t,description:r,status:"running",activities:[]}}],p.fixProgress)if("triage"===t&&"initializing"===p.fixProgress.phase)p.fixProgress={...p.fixProgress,phase:"triage"};else if("fix-worker"===t){const e=(p.fixProgress.totalTests??0)+1,t=r||null;p.fixProgress={...p.fixProgress,phase:"fixing",totalTests:e,currentTestDescription:t,lastTestDescription:t??p.fixProgress.lastTestDescription}}else"validation"===t?p.fixProgress={...p.fixProgress,phase:"validation",currentTestDescription:null}:"context"===t&&(p.fixProgress={...p.fixProgress,currentTestDescription:r||p.fixProgress.currentTestDescription});m()},addTool:({rawName:e,toolInput:t})=>{const r=Ko(e),n=qo(e,t),o=n?`${r} (${n})`:r;p.log=[...p.log,{content:o,id:p.log.length,kind:"tool"}],m()},addToolResult:({message:e})=>{p.log=[...p.log,{content:e,id:p.log.length,kind:"tool_result"}],m()},appendText:({text:e})=>{if(!e)return;const t=p.log.at(-1),r=t&&"text"===t.kind?e:e.replace(/^\s*\n+/,"");t&&"text"===t.kind?p.log=[...p.log.slice(0,-1),{...t,content:`${t.content}${r}`}]:p.log=[...p.log,{content:r,id:p.log.length,kind:"text"}],m()},appendUserMessage:g,cleanup:async()=>{const e=h.waitUntilExit();h.unmount(),await e},setExiting:()=>{p.isExiting=!0,m()},setRunningLabel:({label:e})=>{p.runningLabel=e,m()},setStatus:({error:e,result:t,status:r})=>{p.errorText=e,p.resultText=t,p.status=r,m()},setSubagentStatus:({toolUseId:e,status:t})=>{const r=y.get(e);if(void 0===r)return;const n=p.log[r];n&&"subagent"===n.kind&&n.subagent&&(n.subagent.status=t,p.fixProgress&&"fix-worker"===n.subagent.subagentType&&("complete"===t?p.fixProgress={...p.fixProgress,fixedTests:p.fixProgress.fixedTests+1,currentTestDescription:null}:"error"===t&&(p.fixProgress={...p.fixProgress,failedTests:p.fixProgress.failedTests+1,currentTestDescription:null})),p.log=[...p.log],m(),"complete"!==t&&"error"!==t||y.delete(e))},showPermissionPrompt:e=>new Promise(t=>{f.current=(r,n)=>{if(p.permissionPrompt=void 0,m(),"allow"===r)t({behavior:"allow",updatedInput:e.input});else if("always"===r)t({behavior:"allow",updatedInput:e.input,updatedPermissions:e.suggestions});else{const e=n??"User denied this action";g({text:e}),t({behavior:"deny",message:e,interrupt:!1})}},p.permissionPrompt={...e,resolve:t},m()}),updateFixProgress:t?.isFixMode?e=>{p.fixProgress&&(p.fixProgress={...p.fixProgress,...e},m())}:void 0}})(v,"chat"===e.mode||"init"===e.mode?{onExit:()=>le.current(),onSend:e=>ce.current(e),showSpinnerImmediately:"init"===e.mode}:"fix"===e.mode?{onExit:()=>le.current(),isFixMode:!0}:void 0);let Pe=v.status;const Ue=({error:e,result:t,status:r})=>{Pe=r,Ae({error:e,result:t,status:r})};let ke;ce.current=e=>{const t=e.trim();if(y&&!Fn.getLogFilePath()&&Fn.initSession(t||"chat"),Fn.debug("User message",{text:t}),"/help"===t){x&&b&&(S=!0,_?.interrupt?.(),b.allowNextTurn(),x=!1),"running"===Pe&&Ue({status:"success"}),me({text:e});const t=w?.();return void he({text:t??"Help is not available in this session."})}const r=I||A&&x;if(y&&(C+=1,T=void 0,r||(P=!1,Se({label:void 0}))),b){if(r)return Ue({status:"running"}),me({text:e}),void U.push(e);if(!A||x||I||(A=!1),x)return Ue({status:"running"}),me({text:e}),b.pushText(e),void(R+=1);Ue({status:"running"}),me({text:e}),b.pushText(e),x=!0}};const Le=[];let De;const Oe=await(async e=>{try{const t=await sn(e,"stably.yaml");if(!t)return void Fn.debug("No stably.yaml found");const r=await V(t,"utf-8");if(!r.trim())return;const n=Te(r),o=ea.parse(n.toJS()),s=o.agent?.fix?.maxTurnsPerIssue,i=o.agent?.fix?.maxParallelWorkers,a=!!o.agent?.fix?.rules;return Fn.debug(`Loaded stably.yaml: maxTurnsPerIssue=${s??"default"}, maxParallelWorkers=${i??"default"}, hasRules=${a}`,{path:t,config:o.agent}),o}catch(e){return void Fn.warn("Failed to parse stably.yaml",{error:e})}})(u),Be=Oe?.agent?.fix?.skipAfterConsecutiveUnfixed,Ne=await(async()=>{if("single"===e.mode||"build"===e.mode){const r=await async function(e,t){const r=n(e);if(t){const e=n(r,t);return Fo(e,"output-flag"),{path:e,source:"output-flag"}}const i=Mo(r);if(i){const e=await async function(e){try{const t=(await V(e,"utf-8")).match(/testDir:\s*['"]([^'"]+)['"]/);return t?.[1]}catch{return}}(i);if(e){const t=n(o(i),e);if(Ho(t))return Fo(t,"playwright.config.ts"),{path:t,source:"playwright.config.ts"}}}for(const e of jo){const t=s(r,e);if(Ho(t))return Fo(t,"auto-detected"),{path:t,source:"auto-detected"}}return Fo(r,"cwd-fallback"),{path:r,source:"cwd-fallback"}}(u,e.outputDir);return De=r.path,t=e.prompt,`${(Array.isArray(t)?t.join(" "):t).trim()||"Create tests based on the changes in the current PR or branch. If the user references a specific PR number or branch name, first checkout that PR/branch using `gh pr checkout <number>` or `git checkout <branch>`. Use the Pull Request Context or Git Branch Context section of the system prompt to understand what code was changed, then create appropriate tests for the new or modified functionality. After generating the tests, run them locally (e.g. `pnpm stably test` or the repo's test command) and iterate until the new tests pass."}\n\n[Output directory: ${De}]`}var t;if("fix"===e.mode)try{Fn.info("[fix] Fetching autoheal context",{runId:e.runId,skipAfterConsecutiveUnfixed:Be});const t=Date.now(),{context:r,autohealReportUrl:n,skippedTests:o}=await(async({authHeader:e,orgId:t,runId:r,skipAfterConsecutiveUnfixed:n})=>{Fn.debug("Fetching autoheal context",{runId:r,skipAfterConsecutiveUnfixed:n});const o=await(s={auth:e,client:Zr(),headers:Qn(t),path:{runId:r},query:null!=n?{skipAfterConsecutiveUnfixed:n}:{}},(s.client??Gr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-context",...s}));var s;if(404===o.response.status)throw Fn.warn("Autoheal context not found",{runId:r,status:404}),new Error(`Run ID "${r}" was not found.`);if(401===o.response.status)throw Fn.warn("Autoheal context fetch unauthorized",{runId:r,status:401}),new Error("Unauthorized: failed to fetch autoheal context (401).");if(422===o.response.status)throw Fn.warn("Autoheal context fetch invalid request",{runId:r,status:422,error:o.error?.error}),new Error(o.error?.error??"Failed to fetch autoheal context (422).");if(!o.error){const e=Zn.safeParse(o.data);if(e.success)return Fn.debug("Autoheal context fetched successfully",{runId:r,contextSize:e.data.context.length,skippedTestCount:e.data.skippedTests?.length??0}),{context:e.data.context,autohealReportUrl:e.data.autohealReportUrl,skippedTests:e.data.skippedTests??[]};throw Fn.warn("Autoheal context response invalid",{runId:r}),new Error("Autoheal context response missing or invalid context.")}throw Fn.warn("Autoheal context fetch failed",{runId:r,error:o.error}),new Error("Failed to fetch autoheal context")})({authHeader:c,orgId:l,runId:e.runId,skipAfterConsecutiveUnfixed:Be});if(Fn.info("[fix] Autoheal context fetched",{runId:e.runId,durationMs:Date.now()-t,contextLength:r.length,skippedTestCount:o.length}),ke=n,o.length>0){Fn.info(`[fix] Skipping ${o.length} test(s) that failed to be fixed ${Be}+ consecutive times`);for(const e of o)Fn.info(`[fix] Skipped: ${e.testIdentifier} — ${e.testTitle} (unfixed ${e.consecutiveUnfixedCount}x)`)}return r.includes("No failing tests to fix (all were skipped).")&&(Fn.info("[fix] All failing tests were skipped — nothing to fix"),Ue({status:"success",result:`All failing tests skipped (unfixed ${Be}+ consecutive times). Nothing to fix.`}),await Ie(),process.exit(0)),K||(Fn.info("[fix] Creating WebSocket progress reporter"),K=new io({authHeader:c,orgId:l,runId:e.runId,onUserMessage:e=>{if(Fn.info("[ws] Injecting web UI message into fix agent",{contentLength:e.length}),X(ia,{type:"user_message",summary:e}),Q({type:"user_message",summary:e}),me({text:`[Web] ${e}`}),!x)return b.pushText(`[Message from web UI user]: ${e}`),x=!0,void b.allowNextTurn();O||Date.now()-N<2e3?b.pushText(`[Message from web UI user]: ${e}`):(D.push(e),k&&clearTimeout(k),k=setTimeout(()=>{k=void 0;const e=[...D];D=[],N=Date.now(),Ct(e)},500))}}),K.start(),ee({phase:"initializing"})),te("STARTED"),r}catch(e){const t=e instanceof Error?e.message:"Failed to fetch autoheal context.";Fn.error("[fix] Failed to fetch autoheal context",{error:t}),Ue({error:t,status:"error"}),await Ie(),process.exit(1)}return"init"===e.mode?"Please analyze this project and set up Playwright with the Stably SDK. Check for existing configurations and install the necessary dependencies.":""})(),$e=await async function(e){const t=r.resolve(e),n=r.join(t,"tests"),o=r.join(n,"helpers"),s=r.join(n,"assets"),i=function(e){const t=r.resolve(e);if(g(t))for(const e of ko){const n=r.join(t,`playwright.config${e}`);if(g(n))return n}}(t)??r.join(t,"playwright.config.ts"),a=r.basename(i),c=r.join(n,"seed.spec.ts"),[l,u,d,p,f,h]=await Promise.all([Oo({defaultContent:"Unable to read directory",dirName:"working directory",dirPath:t}),Oo({defaultContent:"Unable to read directory",dirName:"tests directory",dirPath:n}),Oo({defaultContent:"Directory does not exist yet",dirName:"helpers directory",dirPath:o}),Oo({defaultContent:"Directory does not exist yet",dirName:"assets directory",dirPath:s}),Do({defaultContent:"File does not exist or could not be read",fileName:a,filePath:i}),Do({defaultContent:"File does not exist or could not be read",fileName:"seed.spec.ts",filePath:c})]);return{absolutePath:t,directories:{assets:p,helpers:d,root:l,tests:u},files:{playwrightConfig:f,playwrightConfigFilename:a,seedSpec:h}}}(u),Me=Oe?.agent?.fix?.maxTurnsPerIssue,je=Oe?.agent?.fix?.maxParallelWorkers,He=Oe?.agent?.fix?.rules,Fe="fix"===e.mode||"single"===e.mode||"build"===e.mode,Ge="single"===e.mode||"build"===e.mode?await(async e=>{const t=await ta(e,"STABLY-CREATE.md");return t?.content})(u):void 0,Ye=await(e=>ta(e,"STABLY.md"))(u),We=Ye?.content;Fn.info("[fix] Fetching system prompt and subagent definitions",{mode:e.mode,maxTurnsOverride:Me,hasCustomRules:!!He,hasCreateRules:!!Ge,hasStablyMd:!!We,stablyMdPath:Ye?.path}),Ye&&Fn.info(`STABLY.md loaded (${Ye.content.length} chars)`,{path:Ye.path});const Ve=Date.now(),[{systemPrompt:ze,prContext:Ke},qe]=await Promise.all([Bo({allowedEnvVars:Object.keys(f),mode:e.mode,workspaceInfo:$e,authHeader:c,customHeader:"single"===e.mode||"build"===e.mode?e.customHeader:void 0,maxParallelWorkers:"fix"===e.mode?je:void 0}),Fe?qi({authHeader:c,mode:e.mode,maxTurnsOverride:Me}):Promise.resolve({})]);Fn.info("[fix] System prompt and subagents fetched",{durationMs:Date.now()-Ve,systemPromptSize:ze.length,subagentCount:Object.keys(qe).length,maxTurnsOverride:Me??"default",hasPrContext:!!Ke});const Je={...f,...process.env},Xe={};for(const[e,t]of Object.entries(Je))Ki.has(e)||void 0===t||(Xe[e]=t);const Qe=!0;Fn.debug("AI proxy configuration",{useStablyAiProxy:Qe,wantsBypassProxy:!1,wantsUseOllama:!1}),Fn.info("[fix] Acquiring AI proxy key",{useStablyAiProxy:Qe});const Ze=Date.now(),et=await async function({auth:e,client:t,source:r,metadata:n,duration:o}){try{const i=await(s={auth:e,client:t,body:{source:r,metadata:n??{},duration:o}},(s.client??Gr).post({security:[{scheme:"bearer",type:"http"}],url:"/v1/proxy/api-key",...s,headers:{"Content-Type":"application/json",...s.headers}})),a=i.response;if(i.error){const e="object"==typeof i.error&&"error"in i.error?i.error.error:"Unknown error";return{error:zi(e,a)}}return i.data?{key:i.data.key}:{error:zi("No data in response",a)}}catch(e){const t=e instanceof Error?e.message:"Unknown error";return{error:zi(t)}}var s}({auth:c,client:Zr(),source:"cli"}),tt=et?.key;if(Fn.info("[fix] AI proxy key acquired",{durationMs:Date.now()-Ze,success:!!tt,hasError:!!et?.error}),!tt){const e=et?.error?.message?`Unable to make AI calls: ${et.error.message}`:"Unable to make AI calls. Check if you are authenticated.";Fn.warn("Failed to get proxy API key",{error:et?.error?.message}),Ue({error:e,status:"error"}),await Ie(),Fn.flush(),Fn.printLogFileInfo(),process.exit(1)}Fn.debug("Proxy API key acquired",{success:!!tt});const rt=await Xn(),nt=rt?Object.fromEntries(Object.entries(Jn(rt)).filter(e=>null!=e[1])):void 0,ot="init"===e.mode,st="fix"===e.mode,it=st?_r.createLocal({workingDir:u}):void 0;it&&await it.captureSnapshot();const at=ot?Gi({onComplete:()=>{Ue({status:"success"}),xe(),b?.finish(),process.exit(0)}}):y?Gi({onRestartRequested:()=>{y&&(A=!0,Ue({status:"running"}),Se({label:"Restarting browser tools..."}),T={createdAtUserMessageSeq:C,attempts:0})}}):void 0,ct=at?y?{"stably-agent-control":at}:{"session-control":at}:{},lt=re&&Ke?["mcp__create-report"]:[],ut=ot?oa:[...ra,...st?["mcp__auto-heal-report"]:[],...lt],dt=ot?oa:y?[...na,"mcp__stably-agent-control"]:[...na,...lt],pt=re&&Ke?{"create-report":Wi({prContext:Ke,authHeader:c,orgId:l,onReportPosted:e=>{ie({githubComment:{url:e.commentUrl,prNumber:Ke.prNumber}})}})}:{},ft=ot?ct:st&&it?{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:nt},"auto-heal-report":Fi({authHeader:c,diffTracker:it,orgId:l,runId:e.runId,workingDir:u}),...ct}:{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:nt},...ct,...pt},ht="single"===e.mode||"build"===e.mode,mt=ot?[]:[{hooks:[async e=>{const t=po(e);if(!t)return{decision:"approve"};let r=!1;const n=t.map(e=>lo(e)?e.text.length<=4e4?e:(r=!0,{...e,text:`${e.text.slice(0,4e4)}...[truncated to 40000 characters]`}):e);return r?{decision:"approve",hookSpecificOutput:{hookEventName:"PostToolUse",updatedMCPToolOutput:n}}:{decision:"approve"}}],matcher:"mcp__playwright-test__.*"},{matcher:"mcp__playwright-test__test_run",hooks:[bo({onResult:e=>fe({message:e})})]},{matcher:"mcp__playwright-test__test_debug",hooks:[wo({onResult:e=>fe({message:e})})]},...ht?[{matcher:"Write",hooks:[_o({onFileCreated:e=>{Le.push(e),se&&ie({filesCreated:[...se.filesCreated,e]})}})]}]:[],{matcher:"Write",hooks:[Ro({workDir:u})]},{matcher:"Edit",hooks:[Ro({workDir:u})]}],gt=ot?[]:[{matcher:"mcp__playwright-test__browser_type",hooks:[yo({envVars:f})]}],yt=Object.keys(qe).length>0?qe:void 0,bt={...Xe};bt.MCP_TOOL_TIMEOUT=String(6e5),tt&&(bt.ANTHROPIC_API_KEY=tt,bt.ANTHROPIC_BASE_URL=qr,bt.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS="1");const wt=process.env.STABLY_AGENT_MODEL??"claude-opus-4-6",vt=He?`\n\n## Custom Rules\n${He}`:"",_t=Ge?`\n\n## Custom Test Generation Rules\n${Ge}`:"",Et=We?`\n\n## Project Rules (STABLY.md)\n${We}`:"",It=ze+vt+_t+Et;Fn.debug("[fix] Final system prompt assembled",{baseSize:ze.length,fixRulesSize:vt.length,createRulesSize:_t.length,stablyMdSize:Et.length,finalSize:It.length});const Tt=function(){const e=function(){const e=function(){const e=process.env.STABLY_PLUGIN_PATH?.trim();if(!e)return;const t=r.isAbsolute(e)?e:r.resolve(process.cwd(),e);return Zi(t)?t:void 0}();if(e)return e;const t=r.join(Ji,"stably-plugin");if(Zi(t))return t;for(const e of function*(e){let t=r.resolve(e);for(;;){yield t;const e=r.dirname(t);if(e===t)return;t=e}}(Ji))for(const t of Qi){const n=r.join(e,t);if(Zi(n))return n}}();if(e)return{type:"local",path:e}}(),xt=()=>(Fn.info("[fix] Starting SDK query",{model:wt,tools:ut,mcpServers:Object.keys(ft),resumeSessionId:E??null,subagentsEnabled:!!yt,subagentCount:Object.keys(qe).length,useStablyAiProxy:Qe,aiProxyUrl:qr,anthropicBaseUrl:void 0,stablyPluginPath:Tt?.path,stablyPluginExists:!!Tt}),M({options:{executableArgs:["--max-old-space-size=4096"],tools:ut,allowedTools:dt,betas:[],canUseTool:(e,t)=>(Fn.debug("[fix] canUseTool called",{toolName:e}),Promise.resolve({behavior:"allow",updatedInput:t})),cwd:u,env:bt,hooks:{PostToolUse:mt,PreToolUse:gt},includePartialMessages:!0,agents:yt,mcpServers:ft,model:wt,permissionMode:"default",plugins:Tt?[Tt]:void 0,systemPrompt:It,...E?{resume:E}:{}},prompt:b??Ne})),St=()=>{if(b&&0!==U.length){for(const e of U)b.pushText(e);U.length=0,x=!0,Ue({status:"running"})}},At=async()=>{y&&(I||(I=(async()=>{Fn.info("Restarting MCP servers for chat mode"),Ue({status:"running"}),Se({label:"Restarting browser tools..."});try{await(_?.interrupt?.())}catch(e){Fn.warn("Failed to interrupt response during MCP restart",{error:e instanceof Error?e.message:String(e)})}await Io(),b?.finish(),b=new Po,R=0,x=!1,S=!1,$.clear(),_=xt(),P=!0,Se({label:"Restarting browser tools..."}),y&&b&&T&&(T.createdAtUserMessageSeq===C?T.attempts>=1||U.length>0?T=void 0:(T.attempts+=1,b.pushText(["[SYSTEM] MCP servers were restarted successfully.","Continue the task using existing conversation context.","Do not ask the user to resend their message unless new input is required."].join("\n")),T=void 0,x=!0,Ue({status:"running"})):T=void 0),St()})().finally(()=>{I=void 0,St()})),await I)},Ct=async e=>{if(h&&x&&!O&&!L)L=(async()=>{Fn.info("[fix] Interrupting for user message",{messageCount:e.length,phase:q?.phase});try{await(_?.interrupt?.())}catch(e){Fn.warn("[fix] Failed to interrupt response for user message",{error:e instanceof Error?e.message:String(e)})}await Io(),b?.finish(),b=new Po,$.clear(),_=xt();const t=e.map(e=>`[Message from web UI user]: ${e}`).join("\n\n");b.pushText(`[SYSTEM] The user sent a message while you were working. Read their message below, incorporate their feedback, and continue your task. Do not restart from scratch unless the user explicitly asks.\n\n${t}`),B=!0,x=!0})().finally(()=>{L=void 0}),await L;else for(const t of e)b?.pushText(`[Message from web UI user]: ${t}`)};if(tt){const e=qr,t=`${e.replace(/\/$/,"")}/v1/messages`;Fn.debug(`[fix] Pre-flight: POST ${t}`);const r=Date.now();try{const e=await fetch(t,{method:"POST",signal:AbortSignal.timeout(1e4),headers:{"x-api-key":tt,"anthropic-version":"2023-06-01","content-type":"application/json"},body:"{}"}),n=await e.text().catch(()=>""),o=Date.now()-r;Fn.debug(`[fix] Pre-flight: ${e.status} in ${o}ms — ${n.slice(0,300)}`),401===e.status||403===e.status?Fn.error(`[fix] Pre-flight: AI proxy key rejected (${e.status}) at ${t}`):Fn.info("[fix] Pre-flight: AI proxy key valid",{status:e.status,durationMs:o})}catch(t){Fn.error("[fix] Pre-flight: AI proxy unreachable",{error:t instanceof Error?t.message:String(t),durationMs:Date.now()-r,url:e})}}Fn.info("[fix] Creating initial agent query"),Fn.flush(),_=xt(),Fn.info("[fix] Agent query created, entering message loop"),"chat"!==e.mode&&b.pushText(Ne),le.current=async()=>{F="CANCELED",await te("CANCELED"),ee({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:Z(!0)}),K?.close(),ie({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0}),oe?.close(),k&&(clearTimeout(k),k=void 0),Fn.flush(),xe();try{await(_?.interrupt?.())}catch{}b?.finish(),Ie()};let Rt=0,Pt=null;const Ut=setInterval(()=>{const e=Date.now()-z;Pt?Fn.info("[fix] Watchdog: message loop active",{messageCount:Rt,elapsed:e}):Fn.info("[fix] Watchdog: waiting for first SDK message",{elapsed:e}),Fn.flush()},15e3);Ut.unref();try{let t=!1;for(;;){if(!_){Fn.info("[fix] No response object, exiting message loop");break}t=!1,Fn.info("[fix] Entering for-await on SDK response");for await(const r of _){Rt++,Pt||(Pt=Date.now(),Fn.info("[fix] First SDK message received",{waitDurationMs:Pt-z,messageType:r.type,messageSubtype:"subtype"in r?r.subtype:void 0}));const n="session_id"in r&&"string"==typeof r.session_id?r.session_id:void 0;if(n&&n!==E&&(E=n,Fn.debug("Captured Claude session id",{sessionId:E})),"stream_event"===r.type){const{event:e}=r;(Rt<=5||Rt%200==0)&&Fn.debug("[fix] Stream event",{msgNum:Rt,eventType:e?.type});const t=e&&"object"==typeof e&&"parent_tool_use_id"in e&&"string"==typeof e.parent_tool_use_id?e.parent_tool_use_id:void 0;if("content_block_delta"===e?.type){const{delta:r}=e;if("text_delta"===r?.type&&r.text){if(y&&A&&!t)continue;P&&(P=!1,Se({label:void 0})),t&&$.has(t)?ue({toolUseId:t,kind:"text",content:r.text}):he({text:r.text})}}"message_stop"===e?.type&&b&&(O=!1,b.allowNextTurn());continue}if("assistant"===r.type){const t="parent_tool_use_id"in r&&"string"==typeof r.parent_tool_use_id?r.parent_tool_use_id:void 0,{content:n}=r.message??{};if(Array.isArray(n)&&!t){const t=n.filter(e=>e&&"object"==typeof e&&"type"in e&&"text"===e.type).map(e=>e&&"object"==typeof e&&"text"in e&&"string"==typeof e.text?e.text:void 0).filter(Boolean).join("");t&&(Fn.debug("Assistant message",{text:t}),"fix"===e.mode&&(X(ia,{type:"ai_message",summary:t.slice(0,200)}),Q({type:"ai_message",summary:t.slice(0,200)})),re&&ae({type:"ai_message",summary:t.slice(0,200)}))}if($.size>0){const e=Array.isArray(n)?n.filter(e=>e&&"object"==typeof e&&"type"in e&&"tool_use"===e.type).map(e=>e&&"object"==typeof e&&"name"in e&&"string"==typeof e.name?e.name:void 0):[];Fn.debug("Assistant message with active subagents",{hasParentToolUseId:!!t,parentToolUseId:t,activeSubagentIds:Array.from($.keys()),toolNames:e,fullMessageKeys:Object.keys(r),rawMessage:JSON.stringify(r).slice(0,500)})}if(Array.isArray(n))for(const r of n){if("tool_use"===r?.type){if("mcp__auto-heal-report__generate-report"===r.name&&(O=!0),"mcp__session-control__restart_mcp_servers"===r.name||"mcp__stably-agent-control__restart_mcp_servers"===r.name){pe({rawName:r.name,toolInput:r.input});continue}if(r.name.startsWith("mcp__session-control__")||r.name.startsWith("mcp__stably-agent-control__"))continue;if(aa(r.name))continue;if($.size>0&&Fn.debug("Tool use detected with active subagents",{toolName:r.name,hasParentToolUseId:!!t,parentToolUseId:t,wouldRouteToSubagent:!!t&&$.has(t),activeSubagentIds:Array.from($.keys())}),"Task"===r.name){const t=r.input,n=t&&"object"==typeof t?t:void 0,o=n&&"subagent_type"in n&&"string"==typeof n.subagent_type?n.subagent_type:"subagent",s=n&&"description"in n&&"string"==typeof n.description?n.description.trim():"";if(Fn.info("[fix] Subagent started",{subagentType:o,description:s,toolUseId:r.id,activeSubagentCount:$.size+1}),$.set(r.id,{subagentType:o,description:s}),de({toolUseId:r.id,subagentType:o,description:s}),"fix"===e.mode){if("triage"===o){Re?.({phase:"triage"});const e={id:r.id,testDescription:"Triage",workerType:"triage",status:"running",summary:null,startedAt:Date.now(),endedAt:null,activity:[]};ee({phase:"triage",workers:[...q?.workers??[],e]})}else if("fix-worker"===o){J.add(s||r.id);const e={id:r.id,testDescription:s||r.id,workerType:"fix-worker",status:"running",summary:null,startedAt:Date.now(),endedAt:null,activity:[]};Re?.({phase:"fixing",totalTests:J.size,currentTestDescription:s||null}),ee({phase:"fixing",totalTests:J.size,currentTestDescription:s||null,lastTestDescription:s||q?.lastTestDescription||null,workers:[...q?.workers??[],e]})}else"validation"===o?(Re?.({phase:"validation",currentTestDescription:null}),ee({phase:"validation",currentTestDescription:null})):"context"===o&&ee({currentTestDescription:s||null});Q({type:"tool_call",summary:`[${o}] ${s}`.trim()})}continue}if(t&&$.has(t)){const n=ca(r.name),o=qo(r.name,r.input),s=o?`${n} (${o})`:n;if(Fn.debug("Subagent tool called",{tool:r.name,parentToolUseId:t}),ue({toolUseId:t,kind:"tool",content:s}),"fix"===e.mode){Q({type:"tool_call",summary:s});const e=$.get(t);"fix-worker"!==e?.subagentType&&"triage"!==e?.subagentType||X(t,{type:"tool_call",summary:s})}continue}if(t&&Fn.debug("Tool with parent_tool_use_id but no matching subagent",{tool:r.name,parentToolUseId:t,activeSubagentIds:Array.from($.keys())}),Fn.debug("Tool called",{tool:r.name,input:r.input}),pe({rawName:r.name,toolInput:r.input}),"fix"===e.mode){const e=ca(r.name),t=qo(r.name,r.input),n=t?`${e} (${t})`:e;X(ia,{type:"tool_call",summary:n}),Q({type:"tool_call",summary:n})}if(re){const e=ca(r.name),t=qo(r.name,r.input),n=t?`${e} (${t})`:e;"initializing"===se?.phase?ie({phase:"generating",currentActivity:n}):"mcp__playwright-test__test_run"===r.name&&"generating"===se?.phase?ie({phase:"testing",currentActivity:n}):ie({currentActivity:n}),ae({type:"tool_call",summary:n})}}if("text"===r?.type&&t&&$.has(t)){const n="string"==typeof r.text?r.text:"";if(n&&(ue({toolUseId:t,kind:"text",content:n}),"fix"===e.mode)){const e=$.get(t);"fix-worker"!==e?.subagentType&&"triage"!==e?.subagentType||X(t,{type:"ai_message",summary:n.slice(0,200)})}}}continue}if("user"===r.type){const t="message"in r&&r.message&&"object"==typeof r.message&&"content"in r.message?r.message.content:void 0;if(Array.isArray(t))for(const r of t)if(r&&"object"==typeof r&&"type"in r&&"tool_result"===r.type&&"tool_use_id"in r){const t="string"==typeof r.tool_use_id?r.tool_use_id:void 0,n="is_error"in r&&!0===r.is_error,o="content"in r&&"string"==typeof r.content?r.content:void 0;if(Fn.debug("Tool result",{toolUseId:t,isError:n,output:o?.slice(0,500)}),t&&$.has(t)){const r=$.get(t);if(Fn.info("[fix] Subagent completed",{toolUseId:t,isError:n,subagentType:r?.subagentType,description:r?.description,activeSubagentCount:$.size-1}),Ce({toolUseId:t,status:n?"error":"complete"}),"fix"===e.mode&&"triage"===r?.subagentType){const e=n?"failed":"succeeded",r=o?o.slice(0,500):null,s=(q?.workers??[]).map(n=>n.id===t?{...n,status:e,summary:r,endedAt:Date.now()}:n);ee({workers:s})}if("fix"===e.mode&&"fix-worker"===r?.subagentType){const e=n?"failed":"succeeded",r=o?o.slice(0,500):null,s=(q?.workers??[]).map(n=>n.id===t?{...n,status:e,summary:r,endedAt:Date.now()}:n);n?(Re?.({failedTests:(q?.failedTests??0)+1,currentTestDescription:null}),ee({failedTests:(q?.failedTests??0)+1,currentTestDescription:null,workers:s})):(Re?.({fixedTests:(q?.fixedTests??0)+1,currentTestDescription:null}),ee({fixedTests:(q?.fixedTests??0)+1,currentTestDescription:null,workers:s}))}$.delete(t)}}continue}if("result"===r.type){if(Fn.info("[fix] Agent result received",{subtype:r.subtype,messageCount:Rt,elapsed:Date.now()-z,activeSubagents:$.size,fixedTests:q?.fixedTests,failedTests:q?.failedTests,phase:q?.phase}),h){if("success"===r.subtype){k&&(clearTimeout(k),k=void 0);for(const e of D)b?.pushText(`[Message from web UI user]: ${e}`);if(D=[],(re||"fix"===e.mode)&&b){if(b.hasQueuedMessages()){Fn.info("[ws] Queued web UI messages found, continuing agent"),x=!0,b.allowNextTurn();continue}if(await la(b,3e3)){Fn.info("[ws] Web UI message received during grace period, continuing agent"),x=!0,b.allowNextTurn();continue}b.finish()}if(Re?.({phase:"complete",currentTestDescription:null,endedAt:Date.now()}),ee({phase:"complete",currentTestDescription:null,endedAt:Date.now(),isError:!1,workers:Z(!1)}),ie({phase:"complete",endedAt:Date.now(),isError:!1,currentActivity:null}),ht&&Le.length>0){G.green("Created files:");for(const e of Le)G.green(`- ${e}`)}const t=(e,t)=>`]8;;${e}${t}]8;;`,r=ke?G.cyan(`📊 View Autoheal Report:\n ${t(ke,G.cyan(G.bold(G.underline(ke))))}`):void 0;Ue({status:"success",result:r}),F="COMPLETED"}else L||B?Fn.info("[fix] Suppressing error status: user-message interrupt in progress"):S?(F="CANCELED",ee({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:Z(!0)}),ie({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0})):(Re?.({endedAt:Date.now(),isError:!0}),ee({phase:"complete",endedAt:Date.now(),isError:!0,currentTestDescription:null,workers:Z(!0)}),ie({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),Ue({error:"Run failed.",status:"error"}),process.exitCode=1,F="FAILED");S=!1;break}const n=y&&A;if("success"!==r.subtype?S||(Ue({error:"Run failed.",status:"error"}),process.exitCode=1):Ue(n?{status:"running"}:{status:"success"}),x=!1,S=!1,n){A=!1,Fn.info("Processing deferred MCP restart request in chat mode"),await At(),t=!0;break}P=!1,Se({label:void 0}),b?.allowNextTurn(),y&&R>0&&(R-=1,x=!0,Ue({status:"running"}));continue}}if(L&&await L,B&&(B=!1,t=!0,Ue({status:"running"}),Fn.info("[fix] Resuming after user-message interrupt")),!t)break}}catch(e){S?(F="CANCELED",ee({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:Z(!0)}),ie({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0})):(Fn.error("[fix] Agent encountered an error",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0,elapsed:Date.now()-z}),Ue({error:`Agent encountered an error: ${e}`,status:"error"}),process.exitCode=1,F="FAILED",ee({phase:"complete",endedAt:Date.now(),isError:!0,currentTestDescription:null,workers:Z(!0)}),ie({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),Fn.flush(),Fn.printLogFileInfo())}finally{if(clearInterval(Ut),k&&(clearTimeout(k),k=void 0),Fn.info("[fix] Agent session ending",{finalStatus:F,elapsed:Date.now()-z,totalMessages:Rt}),x=!1,S=!1,process.off("uncaughtException",i),b?.finish(),F){Fn.info("[fix] Reporting final autoheal status",{status:F});const e=Date.now();await te(F),Fn.info("[fix] Final autoheal status reported",{durationMs:Date.now()-e})}if(Fn.info("[fix] Closing WebSocket progress reporter"),K?.close(),oe?.close(),st&&it){const t=Date.now();try{Fn.info("[fix] Computing diff...");const r=await it.computeDiff();if(r&&r.trim().length>0){Fn.info("[fix] Uploading diff...",{diffLength:r.length});const{diffBucketPath:n,uploadUrl:o}=await no({authHeader:c,contentType:"text/plain",orgId:l,runId:e.runId});await oo({contentType:"text/plain",diff:r,uploadUrl:o}),await so({authHeader:c,diffBucketPath:n,orgId:l,runId:e.runId}),Fn.info("[fix] Diff uploaded",{durationMs:Date.now()-t})}else Fn.info("[fix] No diff to upload (empty or no changes)")}catch(e){Fn.warn("[fix] Failed to upload diff",{error:e instanceof Error?e.message:String(e),durationMs:Date.now()-t})}}Fn.info("[fix] Cleaning up diff tracker"),await(it?.cleanup()),Fn.info("[fix] Running final cleanup"),await Ie(),Fn.info("[fix] Cleanup complete")}},da=ce.object({runId:ce.string(),timestamp:ce.number()}),pa=class{entries=[];warnings=[];runId;command;executionMode;constructor(e){this.runId=e.runId,this.command=e.command,this.executionMode=e.executionMode}phaseStart(e,t){this.addEntry({phase:e,level:"info",message:t}),te.info(function(e,t){return`${G.bold(G.cyan(`[${e}]`))} ${t}`}(e,t))}phaseEnd(e,t){this.addEntry({phase:e,level:"info",message:t})}info(e){this.addEntry({phase:e.phase,level:"info",message:e.message,fields:e.fields})}warn(e){this.addEntry({phase:e.phase,level:"warn",message:e.message,fields:e.fields}),te.warn(G.yellow(` warn: ${e.message}`))}error(e){this.addEntry({phase:e.phase,level:"error",message:e.message,fields:e.fields}),te.error(G.red(` error: ${e.message}`))}emitWarning(e){this.warnings.push(e),this.addEntry({phase:"summary",level:"warn",message:e.message,fields:{warningCode:e.code,...e.details}}),te.warn(function(e){return G.yellow(` warning: ${e.code} - ${e.message}`)}(e))}getEntries(){return[...this.entries]}getWarnings(){return[...this.warnings]}getRunId(){return this.runId}getCommand(){return this.command}getExecutionMode(){return this.executionMode}addEntry(e){this.entries.push({runId:this.runId,command:this.command,executionMode:this.executionMode,phase:e.phase,timestamp:(new Date).toISOString(),level:e.level,message:e.message,...e.fields?{fields:e.fields}:{}})}};function fa(e){return 0===e.length?[]:[G.yellow(G.bold("Warnings:")),...e.map(e=>G.yellow(` ${e.code}: ${e.message}`)),""]}function ha(e){return e?[G.dim(`Next action: ${e}`),""]:[]}function ma(e){const t=[],r="fix"===e.command?"Fix":"Build";if(t.push(""),"success"===e.status){const n=e.changedPaths.length;t.push(G.green(G.bold(`${r} succeeded`))+(n>0?G.green(` (${n} path${1!==n?"s":""} changed)`):"")),t.push(""),t.push(...fa(e.warnings))}else if("failure"===e.status)t.push(G.red(G.bold(`${r} failed`))),e.errorCode&&t.push(G.red(` Error: ${e.errorCode}`)),t.push(""),t.push(...fa(e.warnings)),t.push(...ha(e.nextAction));else{const n=e.changedPaths.length,o=e.failedPaths.length,s=e.partialPaths.length;t.push(G.yellow(G.bold(`${r} partially succeeded`))+G.yellow(` (${n} changed, ${o} failed, ${s} partial)`)),t.push(""),t.push(...fa(e.warnings)),t.push(...ha(e.nextAction))}return t.push(G.dim(`Run ID: ${e.runId}`)),t.join("\n")}var ga=/^\/\*\*\r?\n \* @generated by stably build[\s\S]*?\*\/(?:\r?\n)*/;function ya(e){return!!e&&"object"==typeof e&&"code"in e}async function ba({errorMessage:e,filePath:t}){try{return await W.readFile(t,"utf8")}catch(t){if(ya(t)&&"ENOENT"===t.code)throw new Error(e);throw t}}function wa(e){return e.split(r.sep).join("/")}async function va(e){const t=[];return await async function e(n){let o;try{o=await W.readdir(n,{withFileTypes:!0})}catch{return}for(const s of o){const o=r.join(n,s.name);s.isDirectory()&&!s.isSymbolicLink()?await e(o):s.isFile()&&s.name.endsWith(".stably.md")&&t.push(o)}}(e),t.sort()}var _a=/^---\r?\n([\s\S]*?)\r?\n---/;function Ea(e,t){const n=[],o=_a.exec(e);let s,i={};if(o){try{const e=xe(o[1]??"");i=e&&"object"==typeof e&&!Array.isArray(e)?e:{}}catch{te.warn(`Warning: Failed to parse YAML frontmatter in ${t}, treating as empty`),i={}}s=e.slice(o[0].length).replace(/^(\r?\n)+/,"")}else s=e;if(!s.trim())return{updated:e,addedFields:n};if(!i.name){const e=s.slice(0,1e4).replace(/```[\s\S]*?```/g,""),o=/^#\s+(.+)$/m.exec(e),a=r.basename(t).replace(/\.stably\.md$/,"").replace(/\.md$/,"");i.name=o?.[1]?.trim()??a,n.push("name")}return i.priority||(i.priority="medium",n.push("priority")),0===n.length?{updated:e,addedFields:n}:{updated:`---\n${Se(i).trimEnd()}\n---\n\n${s}`,addedFields:n}}async function Ia(e){try{return(await W.readdir(e)).filter(e=>co.test(e)).map(t=>r.join(e,t))}catch(e){if(ya(e)&&"ENOENT"===e.code)return[];throw e}}function Ta({runId:e,warnings:t,changedPaths:r=[],failedPaths:n=[],...o}){return{runId:e,command:"build",executionMode:"cli",warnings:t,changedPaths:r,failedPaths:n,partialPaths:[],...o}}async function xa({force:e,inputFilePath:t}){const n=`build-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,o=new pa({runId:n,command:"build",executionMode:"cli"});o.phaseStart("preflight","Validating workspace and arguments");const s=process.cwd();o.info({phase:"preflight",message:"Input resolved",fields:{input:t}}),o.phaseEnd("preflight","Preflight complete"),o.phaseStart("scope","Resolving scope");const i=await ba({filePath:t,errorMessage:`Prompt file not found: ${t}`});if(!i.trim())throw new Error(`Prompt file is empty: ${t}`);const a=So(i),c=wa(r.relative(s,t)),l=r.dirname(t),u=(d=t,r.basename(d).replace(/\.stably\.md$/,"").replace(/\.md$/,"").replace(/\.txt$/,""));var d;const p=await async function(e,t){return(await Ia(e)).find(e=>{const n=r.basename(e);return n.startsWith(`${t}.spec`)||n.startsWith(`${t}.test`)})}(l,u);if(!e&&p&&await async function({outputFilePath:e,promptHash:t}){try{return Ao(await W.readFile(e,"utf8"))===t}catch(e){if(ya(e)&&"ENOENT"===e.code)return!1;throw e}}({outputFilePath:p,promptHash:a})){o.info({phase:"scope",message:"Hash unchanged, skipping build"});const e={code:"STABLY_WARNING_NO_CHANGES",message:"Test code is up to date (hash unchanged)"};o.emitWarning(e);const t=Ta({runId:n,status:"success",warnings:[e]});return o.phaseStart("summary","Build summary"),te.info(ma(t)),o.phaseEnd("summary","Done"),te.success(G.green(`Skipped build: ${c} (hash unchanged)`)),"skipped"}o.info({phase:"scope",message:"Scope resolved",fields:{promptFile:c,promptHash:a,resolvedScopeCount:1,unmappedPaths:[],baseSource:"prompt-file",baseRef:c}}),o.phaseEnd("scope","Scope complete"),o.phaseStart("plan","Preparing prompt");const f=new Set(await Ia(l));await W.mkdir(l,{recursive:!0});const h=Co({promptFile:c,promptHash:a}),m=wa(r.relative(s,l)||l),g=function({outputDir:e,promptContent:t,sourceSpecFile:r}){return["Compile this test specification into a Playwright test file.","",`Output directory: ${e}`,"","Choose output filename:",`- Look at existing test files in ${e} to determine the naming convention.`,"- Use the same extension pattern as existing tests (e.g., .test.ts or .spec.ts).","- If no existing tests, default to .spec.ts.","- Base the filename on the prompt content (e.g., login.spec.ts for login tests).","","File creation rules:","- Create your test file in the output directory with your chosen filename.","- You MAY create shared helper files (e.g., lib/auth.ts) if the prompt explicitly requests reusable components.","- Prefer single-file output unless shared helpers would significantly improve maintainability.","- Never modify unrelated existing files.","","Sync workflow for existing files:","1. Examine existing test files in the workspace and preserve hand edits where possible.","2. If a matching test file already exists, read it first and compare against the prompt specification.","3. Apply sync rules:"," - If file does not exist: CREATE from scratch."," - If file exists and already satisfies the prompt: KEEP behavior and make minimal edits only when needed."," - If file exists but only partially matches: UPDATE only changed scenarios so code aligns with prompt."," - If file structure conflicts heavily with prompt: REGENERATE the file content completely.","4. Prompt specification is the source of truth for final test behavior.","","Test verification:","After generating the test file, run the tests locally to verify they work correctly.","Use the appropriate test command (e.g., `pnpm stably test` or the repository's test command).","If tests fail, analyze the errors and iterate on the test code until all tests pass.","","Spec file linking:",`- Add \`// @stably.spec ${r}\` after the import statements.`,"- This links the test back to its source .md specification.","- If different test.describe()/test() blocks come from different .md files, add per-block @stably.spec instead.","","Prompt specification:",t].join("\n")}({outputDir:m,promptContent:i,sourceSpecFile:c});o.info({phase:"plan",message:"Agent prompt assembled",fields:{outputTarget:m,plannedPathCount:1,plannedPaths:[m],mode:"directory"}}),o.phaseEnd("plan","Plan complete"),o.phaseStart("execute","Running agent session"),process.exitCode=void 0;const y=Date.now();await ua({mode:"build",prompt:g,outputDir:l,customHeader:h});const b=Date.now()-y,w=process.exitCode;if("number"==typeof w&&0!==w){o.error({phase:"execute",message:`Build generation failed for: ${c}`,fields:{toolName:"runAgentSession",durationMs:b}});const e=Ta({runId:n,status:"failure",warnings:o.getWarnings(),failedPaths:[c],nextAction:"open_agent_session",errorCode:"STABLY_WRITE_FAILED"});throw o.phaseStart("summary","Build summary"),o.info({phase:"summary",message:"Run failed",fields:{errorCode:e.errorCode,nextAction:e.nextAction}}),te.info(ma(e)),o.phaseEnd("summary","Done"),new Error(`Build generation failed for: ${c}`)}o.info({phase:"execute",message:"Agent session completed",fields:{toolName:"runAgentSession",durationMs:b}}),o.phaseEnd("execute","Agent session complete"),o.phaseStart("finalize","Applying results");const v=[];let _=p;if(!_&&(_=(await Ia(l)).find(e=>!f.has(e)),!_)){const e={path:c,status:"failed",error:"No new test file created"};v.push(e),o.info({phase:"finalize",message:"Write failed",fields:{path:e.path,writeStatus:e.status,error:e.error}});const t=Ta({runId:n,status:"failure",warnings:o.getWarnings(),failedPaths:[c],nextAction:"open_agent_session",errorCode:"STABLY_WRITE_FAILED"});throw o.phaseStart("summary","Build summary"),o.info({phase:"summary",message:"Run failed",fields:{errorCode:t.errorCode,nextAction:t.nextAction}}),te.info(ma(t)),o.phaseEnd("summary","Done"),new Error(`Build finished but no new test file was created for: ${c}`)}const E=await ba({filePath:_,errorMessage:`Build finished but output file was not created for: ${c}`}),I=function(e){return e.replace(ga,"")}(E),T=E.startsWith(h)?E:`${h}\n\n${I}`;T!==E&&await W.writeFile(_,T,"utf8");const x=wa(r.relative(s,_)),S={path:x,status:"success"};v.push(S),o.info({phase:"finalize",message:"Write succeeded",fields:{path:S.path,writeStatus:S.status}}),o.phaseEnd("finalize","Finalize complete"),o.phaseStart("summary","Build summary");const A=v.filter(e=>"success"===e.status).map(e=>e.path),C=v.filter(e=>"failed"===e.status).map(e=>e.path);let R;R=C.length>0?A.length>0?"partial":"failure":"success";const P=C.length>0,U=Ta({runId:n,status:R,warnings:o.getWarnings(),changedPaths:A,failedPaths:C,nextAction:P?"inspect_failed_paths":void 0,errorCode:P?"STABLY_WRITE_FAILED":void 0});return o.info({phase:"summary",message:"Run completed",fields:{status:U.status,changedPathCount:A.length,failedPathCount:C.length,...U.errorCode?{errorCode:U.errorCode}:{},...U.nextAction?{nextAction:U.nextAction}:{}}}),te.info(ma(U)),o.phaseEnd("summary","Done"),te.success(G.green(`Built: ${x}`)),"built"}var Sa=[{args:["--trace=on"],description:"Run Playwright tests",name:"test"},{args:[],description:"Install browser dependencies",name:"install"}],Aa=["You have two different versions of @playwright/test"];function Ca(e){const[t,...r]=Oi(e),n=[t,...r.slice(0,-1)].join(" ");return(t,r)=>{let o=t.toString();for(const e of Sa)o=o.replaceAll(`${n} playwright ${e.name}`,`${n} stably ${e.name}`).replaceAll(`npx playwright ${e.name}`,`npx stably ${e.name}`);if("yarn"===e){const e=o.split("\n");return e.length>0&&e[0].includes("/.bin/playwright")&&e.shift(),void r.write(e.join("\n"))}r.write(o)}}async function Ra({overrideArgs:e,subcommand:t}){Fn.info("[test] forwardToPlaywright starting",{subcommand:t,overrideArgs:e});const r=process.argv,i=r.findIndex((e,r)=>r>1&&e===t),c=-1===i?[]:r.slice(i+1),l="--"===c[0],u=l?c.slice(1):c;if(!l&&("--help"===u[0]||"-h"===u[0]))return async function({subcommand:e}){const t=Sa.find(t=>t.name===e),r=e=>process.stdout.write(`${e}\n`);r(`stably ${e} - ${t?.description??""}`),r(""),"test"===e&&(r('IMPORTANT: Always use "stably" commands instead of "playwright" directly.'),r(""),r("Stably commands:"),r(" stably test [file] Run tests (auto-enables tracing and analytics)"),r(" stably fix [file] Auto-fix failing tests using AI"),r(" stably create <url> Generate new tests from a URL using AI"),r(""),r("Why use Stably?"),r(' - "stably fix" automatically repairs broken tests'),r(' - "stably test" enables --trace=on and test analytics'),r(' - "stably create" generates tests from prompt'),r(""));const n=ki();if(!n.installed||!n.inNodeModules)return void r('No Playwright project found in this directory or its parents.\nMake sure you\'re in a directory within your Playwright project, or run "stably init" to create a new playwright directory.');const{packageManager:o}=n;if(!o)return void r("Could not determine package manager.");r("Playwright options:"),r("");const[s,...i]=Oi(o),a=Ca(o);return new Promise(t=>{const r=f(s,[...i,e,"--help"],{stdio:["inherit","pipe","pipe"],env:{...process.env,...process.env.CI?{}:{FORCE_COLOR:"1"}}});r.stdout?.on("data",e=>{a(e,process.stdout)}),r.stderr?.on("data",e=>{a(e,process.stderr)}),r.on("close",()=>{t()})})}({subcommand:t});const d=e??[],h=new Set(d.map(e=>{const[t]=e.split("=");return t})),m=[];for(let e=0;e<u.length;e++){const t=u[e],[r]=t.split("=");h.has(r)?!t.includes("=")&&e+1<u.length&&!u[e+1].startsWith("-")&&e++:m.push(t)}const y=[t,...d,...m];Fn.info("[test] Forwarded args computed",{forwardedArgs:y}),Fn.info("[test] Resolving Stably test environment");const b=Date.now(),I="test"===t?await Xn():void 0;Fn.info("[test] Stably test environment resolved",{durationMs:Date.now()-b,hasCredentials:null!=I,hasWsUrl:!!I?.STABLY_WS_URL}),Fn.info("[test] Setting up Stably reporter injection");const T="test"===t?function({forwardedArgs:e,hasCredentials:t}){if(!t)return console.warn("⚠️ Stably credentials not found. Test results will not be reported to Stably."),console.warn(" To enable reporting, either:"),console.warn(" • Run `npx stably login` to authenticate"),void console.warn(" • Or set STABLY_API_KEY and STABLY_PROJECT_ID environment variables\n");const r=process.cwd(),i=e=>{const t=function(e){let t=n(e);for(;;){if([s(t,"node_modules","@stablyai","playwright-test"),s(t,"node_modules",".pnpm","@stablyai+playwright-test")].some(e=>g(e)))return!0;const e=o(t);if(e===t)return!1;t=e}}(e);return t||(console.warn("⚠️ @stablyai/playwright-test is not installed. Stably reporter will not be injected."),console.warn(" Install it with: npm install @stablyai/playwright-test"),console.warn(" Reference: ]8;;https://docs.stably.ai/getting-started/sdk-setup-guidehttps://docs.stably.ai/getting-started/sdk-setup-guide]8;;\n")),t},c=(e,t)=>{try{return function({baseConfigPath:e,projectDir:t}){const r=function(e){try{const t=p("npm pkg get type",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return"module"===JSON.parse(t.trim())}catch{return!1}}(t),i=r?"mts":"ts",c=o(n(e)),l=a(e),u=s(c,`.stably-playwright-wrapper.config.${i}`),d=`\n// Auto-generated wrapper config by Stably CLI\n// This file injects the Stably reporter and ensures trace is enabled\nimport baseConfig from './${l}';\nimport { defineConfig, stablyReporter } from '@stablyai/playwright-test';\n\n// Inline type definitions to avoid import failures when @stablyai/playwright-test is not installed\ntype StablyNotificationConfig = {\n email?: { to: string[]; notifyOnStart?: boolean; notifyOnResult?: 'all' | 'failures-only' | null } | null;\n slack?: { channelName: string; notifyOnStart?: boolean; notifyOnResult?: 'all' | 'failures-only' } | null;\n};\n\ntype ProjectNotificationConfig = {\n projectName: string;\n notifications: StablyNotificationConfig;\n};\n\n// Extract notification configs from projects that have stably.notifications defined\n// This runs at config-load time before Playwright strips custom properties\nconst extractNotificationConfigs = (): ProjectNotificationConfig[] | undefined => {\n const projects = baseConfig.projects;\n if (!projects || !Array.isArray(projects)) return undefined;\n\n const configs = projects\n .map((p: { name?: string; stably?: { notifications?: StablyNotificationConfig } }) => {\n const notifications = p.stably?.notifications;\n return notifications ? { projectName: p.name ?? '', notifications } : undefined;\n })\n .filter((config): config is ProjectNotificationConfig => config != null);\n\n return configs.length > 0 ? configs : undefined;\n};\n\nconst isStablyReporter = (reporter: unknown): boolean => {\n // Only match @stablyai npm scope to avoid false positives on unrelated reporters\n // that might contain "stably" substring (e.g., "unstably-runner")\n if (typeof reporter === 'string') {\n return reporter.includes('@stablyai');\n }\n if (Array.isArray(reporter) && typeof reporter[0] === 'string') {\n return reporter[0].includes('@stablyai');\n }\n return false;\n};\n\nconst getStablyReporterOptions = (reporters: unknown[]): Record<string, unknown> | undefined => {\n for (const reporter of reporters) {\n if (Array.isArray(reporter) && typeof reporter[0] === 'string' && reporter[0].includes('@stablyai')) {\n return (reporter[1] as Record<string, unknown>) ?? {};\n }\n }\n return undefined;\n};\n\nconst filterOutStablyReporter = (reporters: unknown[]): unknown[] => {\n return reporters.filter((reporter) => !isStablyReporter(reporter));\n};\n\nconst buildReporterList = () => {\n const existingReporters = baseConfig.reporter;\n\n // Resolve errorSummary: env var STABLY_ERROR_SUMMARY=0 disables it\n const resolveErrorSummary = (existingValue?: unknown): boolean | undefined => {\n if (process.env.STABLY_ERROR_SUMMARY === '0') return false;\n if (typeof existingValue === 'boolean') return existingValue;\n return undefined; // let the reporter default (true)\n };\n\n // No existing reporters - create fresh stably reporter\n if (!existingReporters) {\n return [stablyReporter({\n apiKey: process.env.STABLY_API_KEY,\n projectId: process.env.STABLY_PROJECT_ID,\n notificationConfigs: extractNotificationConfigs(),\n errorSummary: resolveErrorSummary(),\n })];\n }\n\n // Normalize to array\n const reportersArray: unknown[] = Array.isArray(existingReporters)\n ? existingReporters\n : [[existingReporters, {}]];\n\n // If user has a stably reporter, take their options but override credentials\n const existingOptions = getStablyReporterOptions(reportersArray);\n const stablyReporterEntry = stablyReporter({\n ...existingOptions,\n apiKey: process.env.STABLY_API_KEY,\n projectId: process.env.STABLY_PROJECT_ID,\n notificationConfigs: extractNotificationConfigs(),\n errorSummary: resolveErrorSummary(existingOptions?.errorSummary),\n });\n\n // Keep all non-stably reporters, add our (merged or fresh) stably reporter\n const otherReporters = filterOutStablyReporter(reportersArray);\n return [...otherReporters, stablyReporterEntry];\n};\n\nexport default defineConfig({\n ...baseConfig,\n use: {\n ...baseConfig.use,\n trace: 'on',\n },\n reporter: buildReporterList(),\n});\n`.trim();return g(c)||v(c,{recursive:!0}),_(u,d,"utf-8"),function(e){const t=s(e,".gitignore");try{if(g(t)){const e=w(t,"utf-8");if(e.split("\n").map(e=>e.trim()).includes(No))return;const r=e.length>0&&!e.endsWith("\n");E(t,`${r?"\n":""}${No}\n`)}else _(t,`${No}\n`)}catch{}}(c),u}({baseConfigPath:e,projectDir:t})}catch{return void console.warn("⚠️ Could not create Stably wrapper config. Reporter injection skipped.")}};if(e.some(e=>"--config"===e||"-c"===e||e.startsWith("--config=")||e.startsWith("-c="))){const t=e.findIndex(e=>"--config"===e||"-c"===e);if(-1!==t&&e[t+1]){const s=n(r,e[t+1]),a=o(s);if(!i(a))return;const l=c(s,a);if(!l)return;return e[t+1]=l,l}const s=e.findIndex(e=>e.startsWith("--config=")||e.startsWith("-c="));if(-1!==s){const t=n(r,e[s].split("=")[1]),a=o(t);if(!i(a))return;const l=c(t,a);if(!l)return;const u=e[s].startsWith("--config=")?"--config=":"-c=";return e[s]=`${u}${l}`,l}}const l=Mo(r);if(!l)return;const u=o(l);if(!i(u))return;const d=c(l,u);return d?(e.push("--config",d),d):void 0}({forwardedArgs:y,hasCredentials:null!=I}):void 0;Fn.info("[test] Reporter injection setup complete",{hasWrapperConfig:!!T}),Fn.info("[test] Spawning Playwright process"),await function(e,t={}){Fn.info("[test] Detecting Playwright installation");const r=ki();Fn.info("[test] Playwright installation check",{installed:r.installed,inNodeModules:r.inNodeModules,packageManager:r.packageManager,packageName:r.packageName}),r.installed||(console.error('Playwright is not installed. Please run "stably init" to install it.'),process.exit(1)),r.inNodeModules||(console.error("Playwright is present in your project, but not in node_modules. Please install your dependencies before proceeding."),process.exit(1));const{packageManager:n}=r;n||(console.error("Playwright installation not found. Could not determine your package manager (tried pnpm, yarn, and npm)."),process.exit(1));const[o,...s]=Oi(n),i=Jn(t.env),a=[o,...s,...e];Fn.info("[test] Spawning Playwright process",{command:a.join(" "),pid:process.pid});const c=Date.now(),l=f(o,[...s,...e],{stdio:["inherit","pipe","pipe"],env:{...i,...process.env.CI?{}:{FORCE_COLOR:"1"}}});Fn.info("[test] Playwright process spawned",{childPid:l.pid});const u=Ca(n),d=function(){let e=!1,t="";return(r,n)=>{if(!e){t+=r,t.length>1024&&(t=t.slice(-1024));for(const r of Aa)if(t.includes(r))return n.write("\n[stably] Hint: This is a Playwright error, not caused by @stablyai/playwright-test.\n Common causes: running from the wrong directory (especially in monorepos),\n or a dependency pulling in a conflicting @playwright/test version.\n"),void(e=!0)}}}();l.stdout?.on("data",e=>{u(e,process.stdout)}),l.stderr?.on("data",e=>{const t=e.toString();u(e,process.stderr),d(t,process.stderr)});const p=new AbortController,h=()=>!p.signal.aborted&&(p.abort(),t.onClose?.(),process.removeListener("SIGINT",m),process.removeListener("SIGTERM",m),!0),m=e=>{Fn.info("[test] Signal received, killing Playwright process",{signal:e,childPid:l.pid}),h(),l.kill(e);const t="SIGINT"===e?130:143;process.exit(t)};return process.on("SIGINT",m),process.on("SIGTERM",m),new Promise((e,t)=>{l.on("error",e=>{h()&&(Fn.error("[test] Playwright process error",{error:e.message,childPid:l.pid}),t(e))}),l.on("close",t=>{if(!h())return;Fn.info("[test] Playwright process exited",{exitCode:t,durationMs:Date.now()-c});const r=[process.stdout,process.stderr].filter(e=>e.writableNeedDrain).map(e=>new Promise(t=>e.once("drain",t)));Promise.race([Promise.all(r),new Promise(e=>setTimeout(e,5e3))]).then(()=>{process.exitCode=t??0,e(t??0)})})})}(y,{env:I,onClose:()=>{var e;Fn.info("[test] Playwright process closed, cleaning up wrapper config"),(e=T)&&g(e)&&S(e)}})}function Pa(e=""){process.stdout.write(`${e}\n`)}function Ua(...e){process.stderr.write(`${e.join(" ")}\n`)}var ka="stably",La=`https://registry.npmjs.org/${ka}/latest`,Da=le.object({version:le.string()});function Oa(e){const t=e.match(/^(\d+)\.(\d+)\.(\d+)/);return t?{major:parseInt(t[1],10),minor:parseInt(t[2],10),patch:parseInt(t[3],10)}:null}function Ba(e,t){const r=Oa(e),n=Oa(t);return!(!r||!n)&&(n.major>r.major||!(n.major<r.major)&&(n.minor>r.minor||!(n.minor<r.minor)&&n.patch>r.patch))}var Na=r.join(R.homedir(),".stably"),$a=r.join(Na,"update-check.json"),Ma=`https://registry.npmjs.org/${ka}/latest`,ja="1"===process.env.STABLY_DISABLE_UPDATE_CHECK,Ha=le.object({lastCheck:le.number(),latestVersion:le.string()}),Fa=!1,Ga=!1,Ya=async()=>{if(Ga)try{const{shutdown:e}=await import("@hyperdx/node-opentelemetry"),t=process.stderr.write.bind(process.stderr),r=process.stdout.write.bind(process.stdout),n=(e,...t)=>{const r=t[0];return!("string"!=typeof r||!r.includes("OpenTelemetry"))||!(!Buffer.isBuffer(r)||!r.toString().includes("OpenTelemetry"))||e(...t)};process.stderr.write=(...e)=>n(t,...e),process.stdout.write=(...e)=>n(r,...e);try{await e()}finally{process.stderr.write=t,process.stdout.write=r}}catch{}};!function(){if(ja)return;const e=function(){try{const e=m.readFileSync($a,"utf-8");return Ha.parse(JSON.parse(e))}catch{return null}}(),t=Date.now();if((null==e||t-e.lastCheck>=18e5)&&function(){const e=`\n import { get } from 'node:https';\n import fs from 'node:fs';\n const url = '${Ma}';\n const cacheFile = ${JSON.stringify($a)};\n const cacheDir = ${JSON.stringify(Na)};\n\n const req = get(url, { timeout: 5000 }, (res) => {\n if (res.statusCode !== 200) process.exit(1);\n let data = '';\n res.on('data', (chunk) => data += chunk);\n res.on('end', () => {\n try {\n const version = JSON.parse(data).version;\n if (!fs.existsSync(cacheDir)) fs.mkdirSync(cacheDir, { recursive: true });\n fs.writeFileSync(cacheFile, JSON.stringify({ lastCheck: Date.now(), latestVersion: version }));\n } catch {}\n process.exit(0);\n });\n });\n req.on('error', () => process.exit(1));\n req.on('timeout', () => { req.destroy(); process.exit(1); });\n `;try{f(process.execPath,["--input-type=module","-e",e],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()}catch{}}(),null!=e&&Ba(Yr,e.latestVersion)){if(Fa)return;Fa=!0;let t=!1;const r=()=>{if(t)return;t=!0;const r=`${G.yellow(`update available (${Yr} → ${e.latestVersion})`)} - run \`${ka} upgrade\` to get the latest version\n`;try{m.writeSync(2,r)}catch{}};process.once("beforeExit",r),process.once("exit",r)}}(),Ce.cwdChanged&&Fn.debug("Changed working directory",{cwd:Ce.newCwd});for(const e of Ce.envFilesLoaded)Fn.debug("Loaded env file",{path:e});for(const e of Ce.envFileErrors)Fn.warn(e);var Wa=process.argv.findIndex(e=>"-v"===e||"--verbose"===e);-1!==Wa&&process.argv.splice(Wa,1);var Va=process.argv.findIndex(e=>"--no-telemetry"===e);-1!==Va&&process.argv.splice(Va,1),Fn.info("CLI starting",{version:Yr,args:process.argv.slice(2),cwd:process.cwd()}),process.on("unhandledRejection",(e,t)=>{Fn.error("Unhandled promise rejection",{reason:e instanceof Error?{message:e.message,stack:e.stack}:e,promise:String(t)}),Fn.flush(),Fn.printLogFileInfo()}),process.on("uncaughtException",(e,t)=>{"EPIPE"!==e.code&&(Fn.error("Uncaught exception",{error:{message:e.message,stack:e.stack,name:e.name},origin:t}),Fn.flush(),Fn.printLogFileInfo())});var za=new c;za.name("stably").description("AI-assisted Playwright testing CLI").version(Yr),za.enablePositionalOptions(),za.showHelpAfterError(),za.exitOverride(),za.configureHelp({subcommandTerm:e=>{const t=e.registeredArguments.map(e=>e.required?`<${e.name()}>`:`[${e.name()}]`).join(" ");return t?`${e.name()} ${t}`:e.name()}});var Ka=[];za.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>{Ka.push(e)}});var qa=()=>{const e=za.helpInformation().trimEnd();return e?`${e}\n`:""},Ja=(e,t)=>{let r=e;for(const e of t){const t=r.commands.find(t=>t.name()===e||t.aliases().includes(e));if(!t)return;r=t}return r},Xa=()=>{process.stdout.write(qa())};za.command("help [command...]").description("Show help for a command (e.g. stably help create)").action(e=>{if(!e||0===e.length)return void Xa();const t=Ja(za,e);if(!t)return process.stderr.write(`Unknown command: ${e.join(" ")}\n`),Xa(),void(process.exitCode=1);var r;r=t,process.stdout.write((e=>{const t=e.helpInformation().trimEnd();return t?`${t}\n`:""})(r))}),za.action(()=>ua({mode:"chat",getHelpText:qa})),za.command("login").description("Authenticate with Stably in your browser").action(Tn),za.command("logout").description("Clear stored Stably credentials").action(async()=>{const e=Yn();e&&(te.warn(`Environment variables ${G.cyan("STABLY_API_KEY")} and ${G.cyan("STABLY_PROJECT_ID")} are set.`),te.warn("They will continue to be used for authentication even after logout."),te.warn("Unset them if you want to fully de-authenticate this shell/session."));const t=await fn();if(!t)return void re(e?G.yellow("No stored OAuth login found to clear."):G.yellow("You are not logged in."));const r=ne();r.start("Logging out..."),await(async e=>{try{await fetch(`${zr}/api/backend/v1/logout`,{body:JSON.stringify({refresh_token:e}),headers:{"Content-Type":"application/json"},method:"POST"})}catch{}})(t.refreshToken),await mn(),await yn(),r.stop(G.green("✓ Logged out")),re(G.green("You have been logged out successfully."))}),za.command("whoami").description("Show auth status and current project").action(async()=>{te.info(`${G.bold("CLI Version:")} ${G.cyan(Yr)}`);const e=Yn();if(e){te.info(G.dim("Authentication: Environment variables")),te.info(` ${G.bold("API Key:")} ${G.cyan(e.apiKey.slice(0,8))}...`),te.info(` ${G.bold("Project ID:")} ${G.cyan(e.projectId)}`);const t=await fn();if(t){let e;try{e=on(t.accessToken).email}catch{e=void 0}te.warn("Stored OAuth login detected but will be ignored (env auth takes precedence)."),e&&te.info(` ${G.bold("OAuth Email:")} ${G.cyan(e)}`),te.info(` ${G.bold("Tip:")} Unset env vars to use OAuth`)}return void re(G.green("Authenticated via environment variables"))}const t=await fn();if(!t)return void re(G.yellow("Not logged in. Run `stably login` to authenticate."));let n;try{n=on(t.accessToken).email}catch{n=void 0}const o=await gn();if(!o)return te.info(G.dim("Authentication: OAuth (not linked to a project)")),n&&te.info(` ${G.bold("Email:")} ${G.cyan(n)}`),void re(G.yellow("Logged in but this directory is not linked to a project. Run `stably login` to link."));const s=await(async()=>sn(process.cwd(),ln))(),i=s?r.dirname(s):process.cwd(),a=r.relative(process.cwd(),i)||".";te.info(G.dim("Authentication: OAuth")),n&&te.info(` ${G.bold("Email:")} ${G.cyan(n)}`),te.info(` ${G.bold("Organization:")} ${G.cyan(o.orgName)}`),te.info(` ${G.bold("Project:")} ${G.cyan(o.projectName)}`),te.info(` ${G.bold("Linked at:")} ${G.dim(a)}`),re(G.green("Authenticated"))}),za.command("build [input...]").description("Compile test specification files (.stably.md) into Playwright tests").option("--force","Force regeneration even if prompt is unchanged").action(async(e,t)=>{try{await async function(e){const{inputs:t,force:n}=e,o=process.cwd();let s;if(0===t.length){const e=function(e){try{return p('git ls-files --cached --others --exclude-standard "*.stably.md"',{cwd:e,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).split("\n").map(e=>e.trim()).filter(Boolean)}catch{return[]}}(o);s=e.map(e=>r.resolve(o,e))}else s=await async function(e,t){const n=[];for(const o of e){const e=r.resolve(t,o);let s;try{s=await W.stat(e)}catch{n.push(e);continue}if(s.isDirectory()){const t=await va(e);n.push(...t)}else n.push(e)}const o=new Set,s=[];for(const e of n){const t=r.resolve(e);o.has(t)||(o.add(t),s.push(t))}return s}(t,o);if(0===s.length)throw new Error("No .stably.md files found. Create a test specification file (e.g., login.stably.md) and try again.");const{fixedFiles:i}=await async function(e,t){const n=[],o=[];for(const s of e){let e=s;try{await W.stat(e)}catch{o.push(e);continue}if(e.endsWith(".md")&&!e.endsWith(".stably.md")){const o=e.replace(/\.md$/,".stably.md");try{await W.rename(e,o);const s=wa(r.relative(t,e)),i=wa(r.relative(t,o)),a={code:"STABLY_WARNING_FILE_RENAMED",message:`Renamed ${s} → ${i} (test specs must use .stably.md extension)`,details:{oldPath:s,newPath:i}};n.push(a),te.warn(G.yellow(` ⚠ ${a.message}`)),e=o}catch(t){if(!(t instanceof Error&&"code"in t)||"EEXIST"!==t.code&&"ENOTEMPTY"!==t.code)throw t;te.warn(G.yellow(` ⚠ Skipping rename: ${o} already exists`)),e=o}}if(!e.endsWith(".stably.md")){o.push(e);continue}const i=await W.readFile(e,"utf8"),{updated:a,addedFields:c}=Ea(i,e);if(c.length>0){await W.writeFile(e,a,"utf8");const o=wa(r.relative(t,e)),s={code:"STABLY_WARNING_FRONTMATTER_ADDED",message:`Added missing frontmatter fields to ${o}: ${c.join(", ")}`,details:{path:o,addedFields:c}};n.push(s),te.warn(G.yellow(` ⚠ ${s.message}`))}o.push(e)}return{fixedFiles:o,warnings:n}}(s,o);s=i,te.info(G.bold(`Found ${s.length} test specification${1!==s.length?"s":""}`));for(const e of s){const t=wa(r.relative(o,e));te.info(G.dim(` ${t}`))}te.info("");const a={built:[],skipped:[],failed:[]};for(const e of s){const t=wa(r.relative(o,e));try{"built"===await xa({force:n,inputFilePath:e})?a.built.push(t):a.skipped.push(t)}catch(e){const r=e instanceof Error?e.message:String(e);te.error(G.red(`Failed to build ${t}: ${r}`)),a.failed.push(t)}}return function(e){if(te.info(""),te.info(G.bold("Build Summary")),te.info(` ${G.green(`${e.built.length} built`)} ${G.dim(`${e.skipped.length} skipped (unchanged)`)} ${e.failed.length>0?G.red(`${e.failed.length} failed`):G.dim("0 failed")}`),e.failed.length>0){te.info(""),te.error(G.red("Failed files:"));for(const t of e.failed)te.error(G.red(` - ${t}`))}}(a),a.failed.length>0&&(process.exitCode=1),a}({inputs:e,force:t.force??!1})}catch(e){const t=e instanceof Error?e.message:String(e);process.stderr.write(`${t}\n`),process.exitCode=1}}),za.command("tunnel",{hidden:!0}).description("Expose a local server with a secure tunnel URL").option("-p, --port <number>","Local port to expose","3000").action(async e=>{oe(`Starting development server for port ${e.port}...`);const t=await Kn(),r="oauth"===t.type?`${t.auth.context.orgName}-${t.auth.context.projectName}`.toLowerCase().replace(/[^a-z0-9-]/g,""):`project-${t.auth.projectId}`.toLowerCase(),n=ne();n.start("Starting development server...");const o=await Ae(`http://localhost:${e.port}`,{subdomain:r});n.stop(`Your local environment is available at: ]8;;${o.url}${G.underline(G.cyan(o.url))}]8;;`)}),za.command("create [prompt...]").description("Generate a test from prompt (omit prompt to infer from branch diff)").option("-o, --output <dir>","Output directory for generated test files").action(async(e,t)=>{const r=e.length>0&&"test"===e[0]?e.slice(1):e;return ua({mode:"single",prompt:r,outputDir:t.output})}).command("test",{hidden:!0}).description("Generate a Playwright test from a prompt (deprecated: use `stably create <prompt>` directly)").argument("<prompt...>","Prompt describing the test to generate").option("-o, --output <dir>","Output directory for generated test files").action(async(e,t)=>ua({mode:"single",prompt:e,outputDir:t.output})),za.command("fix [runId]").description("Fix failing tests from a run (auto-detects from last test run or CI)").action(async e=>{(function(e){try{return p("git rev-parse --is-inside-work-tree",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}})(process.cwd())||(Fn.error('Not a git repository. The "stably fix" command requires a git repository to track changes made during the fix. Please run this command from inside a git repository.'),process.stderr.write('Error: Not a git repository.\nThe "stably fix" command requires a git repository to track changes made during the fix.\nPlease run this command from inside a git repository.\n'),process.exit(1));const t=await(async e=>{const t=e=>e.replace(/\//g,"_");if(e)return Fn.debug("Run ID provided explicitly",{runId:e}),t(e);const r=function(){if(process.env.CI_BUILD_ID)return process.env.CI_BUILD_ID;const e=(({env:e=process.env,cwd:t=process.cwd()}={})=>{for(const r of Object.keys(vr))if(vr[r].detect({env:e,cwd:t}))return{isCi:!0,...vr[r].configuration({env:e,cwd:t})};return{isCi:Boolean(e.CI),...(r={env:e,cwd:t},{commit:Yt(r),branch:Wt(r)})};var r})();if(!e.isCi)return;const t=function(e){switch(e){case"github":return process.env.GITHUB_RUN_ATTEMPT;case"azure-devops":return process.env.SYSTEM_JOBATTEMPT;case"bitbucket":return process.env.BITBUCKET_STEP_RUN_NUMBER;default:return}}(e.service),r=[e.service,"slug"in e?e.slug?.replace(/\//g,"_"):void 0,"build"in e?String(e.build):void 0,"job"in e?String(e.job):void 0,t&&String(t)].filter(Boolean);return r.length>0?r.join("-"):void 0}();if(r)return Fn.debug("Run ID detected from CI environment",{runId:r}),t(r);Fn.debug("No explicit run ID or CI environment detected, checking last-run.json");const n=await(async()=>{try{const e=await sn(process.cwd(),".stably/last-run.json");if(!e)return;const t=await V(e,"utf-8");return{...da.parse(JSON.parse(t)),filePath:e}}catch{return}})();if(n){const e=(Date.now()-n.timestamp)/36e5;return Fn.debug("Run ID found in last-run.json",{runId:n.runId,timestamp:n.timestamp,filePath:n.filePath,ageHours:Math.round(e)}),e>24&&Fn.warn(`Using run ID from ${Math.round(e)} hours ago (${n.filePath}). Provide an explicit run ID if this is not the run you want to fix.`),t(n.runId)}Fn.debug("No run ID found in last-run.json")})(e);return t||(process.stderr.write('Run ID is required. Either:\n 1. Run "stably test" first (run ID will be auto-detected)\n 2. Provide a run ID: stably fix <runId>\n 3. Run in CI (auto-detected from environment)\n'),process.exit(1)),ua({mode:"fix",runId:t})}),za.command("init").description("Initialize Playwright and Stably SDK in your project").action(async()=>ua({mode:"init"})),za.command("upgrade").description("Upgrade to latest version (use --check to only check)").option("-c, --check","Only check for updates without upgrading").action(e=>async function(e){const{check:t=!1}=e;let r;Pa(G.cyan("Checking for updates...\n"));try{r=await async function(){const e=await async function(){const e=new AbortController,t=setTimeout(()=>e.abort(),1e4);t.unref();try{const t=await fetch(La,{signal:e.signal});if(!t.ok)throw new Error(`Failed to fetch latest version: ${t.statusText}`);return Da.parse(await t.json()).version}finally{clearTimeout(t)}}();return{current:Yr,latest:e,isOutdated:Ba(Yr,e)}}()}catch(e){return Ua(G.red("Failed to check for updates:"),e instanceof Error?e.message:e),void(process.exitCode=1)}if(Pa(`Current version: ${G.yellow(r.current)}`),Pa(`Latest version: ${G.green(r.latest)}`),Pa(),!r.isOutdated)return void Pa(G.green("✓ You are already on the latest version!"));if(Pa(G.yellow(`⚠ A new version is available: ${r.current} → ${r.latest}`)),Pa(),t)return Pa(G.dim("Exiting with code 1 to indicate update available (useful for CI).")),void(process.exitCode=1);const n=function(){const e=process.argv[1]||"";if(e.includes("_npx")||e.includes(".npm/_cacache"))return"npx";try{const t=p("npm root -g",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-npm"}catch{}if(e.includes("node_modules/stably"))return"global-npm";try{const t=p("pnpm root -g",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-pnpm"}catch{}try{const t=p("yarn global dir",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-yarn-classic"}catch{}try{const t=p("yarn config get globalFolder",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-yarn-berry"}catch{}return"unknown"}(),o=function(e){switch(e){case"global-npm":case"global-yarn-berry":case"unknown":return{command:"npm",args:["install","-g",`${ka}@latest`],description:`npm install -g ${ka}@latest`};case"global-pnpm":return{command:"pnpm",args:["add","-g",`${ka}@latest`],description:`pnpm add -g ${ka}@latest`};case"global-yarn-classic":return{command:"yarn",args:["global","add",`${ka}@latest`],description:`yarn global add ${ka}@latest`};case"npx":return{command:"npx",args:[`${ka}@latest`],description:`npx ${ka}@latest (always uses latest)`}}}(n);if("npx"===n)return Pa(G.dim("You are running via npx, which always fetches the latest version.")),void Pa(G.dim(`Simply run: ${G.white("npx stably")} to use the latest version.`));"unknown"===n?(Pa(G.yellow("Could not detect installation method. Falling back to npm.")),Pa()):"global-yarn-berry"===n&&(Pa(G.yellow("Yarn Berry does not support global packages. Falling back to npm.")),Pa()),Pa(`Upgrade command: ${G.cyan(o.description)}`),Pa(),Pa(G.cyan("Upgrading...")),Pa();try{await(s=o.command,i=o.args,new Promise((e,t)=>{const r=f(s,i,{stdio:"inherit",shell:"win32"===process.platform});r.on("close",r=>{0===r?e():t(new Error(`Upgrade command exited with code ${r}`))}),r.on("error",e=>{t(e)})})),Pa(),Pa(G.green("✓ Upgrade complete!")),Pa(G.dim(`Run ${G.white("stably --version")} to verify.`))}catch(e){Ua(G.red("Upgrade failed:"),e instanceof Error?e.message:e),Pa(),Pa(G.dim("You can try manually running:")),Pa(G.cyan(` ${o.description}`)),process.exitCode=1}var s,i}(e)),Sa.forEach(({args:e,description:t,name:r})=>{za.command(r).description(t).helpOption(!1).helpCommand(!1).allowUnknownOption(!0).allowExcessArguments(!0).passThroughOptions().action(()=>Ra({overrideArgs:e,subcommand:r}))});var Qa=()=>{0!==Ka.length&&(process.stderr.write(Ka.join("")),Ka=[])};(async()=>{await(async()=>{if(!Ga&&"1"!==process.env.STABLY_DISABLE_TELEMETRY&&"1"!==process.env.DO_NOT_TRACK&&!process.argv.includes("--no-telemetry"))try{const{init:e}=await import("@hyperdx/node-opentelemetry");e({apiKey:"61d10b50-9534-47be-a732-95bfe461adb7",service:"stably-cli",consoleCapture:!0,disableTracing:!0,disableMetrics:!0,disableStartupLogs:!0,additionalResourceAttributes:{"cli.version":Yr,"node.version":process.version,"os.platform":process.platform}}),Ga=!0}catch{}})();try{await za.parseAsync(process.argv),Fn.info("CLI completed successfully")}catch(e){if(!(e=>!!e&&"object"==typeof e&&"code"in e)(e))throw Fn.error("Unexpected CLI error",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),Qa(),Fn.flush(),Fn.printLogFileInfo(),await Ya(),e;const t="number"==typeof e.exitCode?e.exitCode:1,r=process.argv.slice(2).find(e=>!e.startsWith("-")),n=!!r&&!!Ja(za,[r]);if(("commander.excessArguments"===e.code||"commander.unknownCommand"===e.code)&&r&&!n)return Ka=[],Fn.warn("Unknown command",{command:r}),process.stderr.write(`command '${r}' not found\n`),Xa(),void(process.exitCode=t);Fn.debug("Commander error",{code:e.code,exitCode:t}),Qa(),process.exitCode=t}finally{Fn.flush(),await Ya()}})();
2
+ import{config as e,parse as t}from"dotenv";import r,{resolve as n,dirname as o,join as s,sep as i,basename as a}from"path";import{Command as c}from"commander";import{Buffer as l}from"buffer";import u,{exec as d,execSync as p,spawn as f}from"child_process";import h from"process";import m,{existsSync as g,statSync as y,createReadStream as b,readFileSync as w,mkdirSync as v,writeFileSync as _,appendFileSync as E,openSync as I,readSync as T,closeSync as x,rmSync as S}from"fs";import{fileURLToPath as A,URL as C}from"url";import R,{tmpdir as P,constants as U}from"os";import"timers/promises";import k from"stream";import{debuglog as L,promisify as D,TextDecoder as O,TextEncoder as B}from"util";import{createSdkMcpServer as N,tool as $,query as M}from"@anthropic-ai/claude-agent-sdk";import{match as j}from"ts-pattern";import H,{randomUUID as F}from"crypto";import G from"picocolors";import{simpleGit as Y}from"simple-git";import W,{readFile as V,mkdir as z,writeFile as K,unlink as q,access as J,readdir as X,stat as Q,rm as Z,appendFile as ee}from"fs/promises";import{log as te,outro as re,spinner as ne,intro as oe,select as se,isCancel as ie}from"@clack/prompts";import{createInterface as ae}from"readline/promises";import ce,{z as le}from"zod";import ue from"open";import de from"http";import pe from"pino";import fe from"sonic-boom";import{z as he}from"zod/v3";import me from"ws";import{useState as ge,useRef as ye,useEffect as be,useCallback as we,useMemo as ve}from"react";import{jsx as _e,jsxs as Ee}from"react/jsx-runtime";import{createRequire as Ie}from"module";import{parseDocument as Te,parse as xe,stringify as Se}from"yaml";import{startTunnel as Ae}from"@stablyhq/runner-sdk";var Ce={cwdChanged:!1,newCwd:void 0,envFilesLoaded:[],envFileErrors:[]},Re=process.argv.findIndex(e=>"-C"===e||"--cwd"===e);if(-1!==Re&&process.argv[Re+1]){const e=process.argv[Re+1];process.chdir(e),Ce.cwdChanged=!0,Ce.newCwd=e,process.argv.splice(Re,2)}for(var Pe=[],Ue=0;Ue<process.argv.length;)if("--env-file"===process.argv[Ue]){const e=process.argv[Ue+1];e&&!e.startsWith("-")?(Pe.push(e),process.argv.splice(Ue,2)):Ue++}else Ue++;for(const t of Pe){const n=r.resolve(process.cwd(),t),o=e({path:n,override:!0,quiet:!0});if(o.error){const e=`warning: could not load env file: ${n} (${o.error.message})`;Ce.envFileErrors.push(e),process.stderr.write(`${e}\n`)}else Ce.envFilesLoaded.push(n)}var ke={detect:({env:e})=>Boolean(e.APPVEYOR),configuration({env:e}){const t=e.APPVEYOR_PULL_REQUEST_NUMBER,r=Boolean(t);return{name:"Appveyor",service:"appveyor",commit:e.APPVEYOR_REPO_COMMIT,tag:e.APPVEYOR_REPO_TAG_NAME,build:e.APPVEYOR_BUILD_NUMBER,buildUrl:`https://ci.appveyor.com/project/${e.APPVEYOR_PROJECT_SLUG}/build/${e.APPVEYOR_BUILD_VERSION}`,branch:e.APPVEYOR_REPO_BRANCH,job:e.APPVEYOR_JOB_NUMBER,jobUrl:`https://ci.appveyor.com/project/${e.APPVEYOR_PROJECT_SLUG}/build/job/${e.APPVEYOR_JOB_ID}`,pr:t,isPr:r,prBranch:e.APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH,slug:e.APPVEYOR_REPO_NAME,root:e.APPVEYOR_BUILD_FOLDER}}};function Le(e){return(/\d+(?!.*\d+)/.exec(e)||[])[0]}function De(e){return e?/^(?:refs\/heads\/)?(?<branch>.+)$/i.exec(e)[1]:void 0}var Oe={detect:({env:e})=>Boolean(e.BUILD_BUILDURI),configuration({env:e}){const t=e.SYSTEM_PULLREQUEST_PULLREQUESTID,r=Boolean(t);return{name:"Azure Pipelines",service:"azurePipelines",commit:e.BUILD_SOURCEVERSION,build:e.BUILD_BUILDNUMBER,branch:De(r?e.SYSTEM_PULLREQUEST_TARGETBRANCH:e.BUILD_SOURCEBRANCH),pr:t,isPr:r,prBranch:De(r?e.SYSTEM_PULLREQUEST_SOURCEBRANCH:void 0),root:e.BUILD_REPOSITORY_LOCALPATH}}},Be={detect:({env:e})=>Boolean(e.bamboo_agentId),configuration:({env:e})=>({name:"Bamboo",service:"bamboo",commit:e.bamboo_planRepository_1_revision,build:e.bamboo_buildNumber,buildUrl:e.bamboo_buildResultsUrl,branch:e.bamboo_planRepository_1_branchName,job:e.bamboo_buildKey,root:e.bamboo_build_working_directory})},Ne={detect:({env:e})=>Boolean(e.BITBUCKET_BUILD_NUMBER),configuration:({env:e})=>({name:"Bitbucket Pipelines",service:"bitbucket",commit:e.BITBUCKET_COMMIT,tag:e.BITBUCKET_TAG,build:e.BITBUCKET_BUILD_NUMBER,buildUrl:`https://bitbucket.org/${e.BITBUCKET_REPO_FULL_NAME}/addon/pipelines/home#!/results/${e.BITBUCKET_BUILD_NUMBER}`,branch:e.BITBUCKET_BRANCH,slug:e.BITBUCKET_REPO_FULL_NAME,root:e.BITBUCKET_CLONE_DIR})},$e={detect:({env:e})=>Boolean(e.BITRISE_IO),configuration({env:e}){const t="false"===e.BITRISE_PULL_REQUEST?void 0:e.BITRISE_PULL_REQUEST,r=Boolean(t);return{name:"Bitrise",service:"bitrise",commit:e.BITRISE_GIT_COMMIT,tag:e.BITRISE_GIT_TAG,build:e.BITRISE_BUILD_NUMBER,buildUrl:e.BITRISE_BUILD_URL,branch:r?e.BITRISEIO_GIT_BRANCH_DEST:e.BITRISE_GIT_BRANCH,pr:t,isPr:r,prBranch:r?e.BITRISE_GIT_BRANCH:void 0,slug:e.BITRISE_APP_SLUG}}},Me={detect:({env:e})=>Boolean(e.BUDDY_WORKSPACE_ID),configuration({env:e}){const t=Le(e.BUDDY_EXECUTION_PULL_REQUEST_ID),r=Boolean(t);return{name:"Buddy",service:"buddy",commit:e.BUDDY_EXECUTION_REVISION,tag:e.BUDDY_EXECUTION_TAG,build:e.BUDDY_EXECUTION_ID,buildUrl:e.BUDDY_EXECUTION_URL,branch:r?e.BUDDY_EXECUTION_PULL_REQUEST_HEAD_BRANCH:e.BUDDY_EXECUTION_BRANCH,pr:t,isPr:r,slug:e.BUDDY_REPO_SLUG}}},je="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function He(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Fe,Ge,Ye,We,Ve,ze,Ke,qe,Je={exports:{}};var Xe,Qe,Ze,et,tt,rt,nt,ot,st,it,at,ct,lt,ut,dt,pt={exports:{}},ft={};function ht(){if(ct)return at;ct=1;const e=r,t=function(){if(Ze)return Qe;Ze=1;const e=r,t=function(){if(qe)return Ke;qe=1;const e="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,t=r,n=e?";":":",o=function(){if(ze)return Ve;var e;function t(r,n,o){if("function"==typeof n&&(o=n,n={}),!o){if("function"!=typeof Promise)throw new TypeError("callback not provided");return new Promise(function(e,o){t(r,n||{},function(t,r){t?o(t):e(r)})})}e(r,n||{},function(e,t){e&&("EACCES"===e.code||n&&n.ignoreErrors)&&(e=null,t=!1),o(e,t)})}return ze=1,e="win32"===process.platform||je.TESTING_WINDOWS?function(){if(Ge)return Fe;Ge=1,Fe=r,r.sync=function(r,n){return t(e.statSync(r),r,n)};var e=m;function t(e,t,r){return!(!e.isSymbolicLink()&&!e.isFile())&&function(e,t){var r=void 0!==t.pathExt?t.pathExt:process.env.PATHEXT;if(!r)return!0;if(-1!==(r=r.split(";")).indexOf(""))return!0;for(var n=0;n<r.length;n++){var o=r[n].toLowerCase();if(o&&e.substr(-o.length).toLowerCase()===o)return!0}return!1}(t,r)}function r(r,n,o){e.stat(r,function(e,s){o(e,!e&&t(s,r,n))})}return Fe}():function(){if(We)return Ye;We=1,Ye=t,t.sync=function(t,n){return r(e.statSync(t),n)};var e=m;function t(t,n,o){e.stat(t,function(e,t){o(e,!e&&r(t,n))})}function r(e,t){return e.isFile()&&function(e,t){var r=e.mode,n=e.uid,o=e.gid,s=void 0!==t.uid?t.uid:process.getuid&&process.getuid(),i=void 0!==t.gid?t.gid:process.getgid&&process.getgid(),a=parseInt("100",8),c=parseInt("010",8);return r&parseInt("001",8)||r&c&&o===i||r&a&&n===s||r&(a|c)&&0===s}(e,t)}return Ye}(),Ve=t,t.sync=function(t,r){try{return e.sync(t,r||{})}catch(e){if(r&&r.ignoreErrors||"EACCES"===e.code)return!1;throw e}},Ve}(),s=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),i=(t,r)=>{const o=r.colon||n,s=t.match(/\//)||e&&t.match(/\\/)?[""]:[...e?[process.cwd()]:[],...(r.path||process.env.PATH||"").split(o)],i=e?r.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",a=e?i.split(o):[""];return e&&-1!==t.indexOf(".")&&""!==a[0]&&a.unshift(""),{pathEnv:s,pathExt:a,pathExtExe:i}},a=(e,r,n)=>{"function"==typeof r&&(n=r,r={}),r||(r={});const{pathEnv:a,pathExt:c,pathExtExe:l}=i(e,r),u=[],d=n=>new Promise((o,i)=>{if(n===a.length)return r.all&&u.length?o(u):i(s(e));const c=a[n],l=/^".*"$/.test(c)?c.slice(1,-1):c,d=t.join(l,e),f=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d;o(p(f,n,0))}),p=(e,t,n)=>new Promise((s,i)=>{if(n===c.length)return s(d(t+1));const a=c[n];o(e+a,{pathExt:l},(o,i)=>{if(!o&&i){if(!r.all)return s(e+a);u.push(e+a)}return s(p(e,t,n+1))})});return n?d(0).then(e=>n(null,e),n):d(0)};return Ke=a,a.sync=(e,r)=>{r=r||{};const{pathEnv:n,pathExt:a,pathExtExe:c}=i(e,r),l=[];for(let s=0;s<n.length;s++){const i=n[s],u=/^".*"$/.test(i)?i.slice(1,-1):i,d=t.join(u,e),p=!u&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d;for(let e=0;e<a.length;e++){const t=p+a[e];try{if(o.sync(t,{pathExt:c})){if(!r.all)return t;l.push(t)}}catch(e){}}}if(r.all&&l.length)return l;if(r.nothrow)return null;throw s(e)},Ke}(),n=function(){if(Xe)return pt.exports;Xe=1;const e=(e={})=>{const t=e.env||process.env;return"win32"!==(e.platform||process.platform)?"PATH":Object.keys(t).reverse().find(e=>"PATH"===e.toUpperCase())||"Path"};return pt.exports=e,pt.exports.default=e,pt.exports}();function o(r,o){const s=r.options.env||process.env,i=process.cwd(),a=null!=r.options.cwd,c=a&&void 0!==process.chdir&&!process.chdir.disabled;if(c)try{process.chdir(r.options.cwd)}catch(e){}let l;try{l=t.sync(r.command,{path:s[n({env:s})],pathExt:o?e.delimiter:void 0})}catch(e){}finally{c&&process.chdir(i)}return l&&(l=e.resolve(a?r.options.cwd:"",l)),l}return Qe=function(e){return o(e)||o(e,!0)}}(),n=function(){if(et)return ft;et=1;const e=/([()\][%!^"`<>&|;, *?])/g;return ft.command=function(t){return t.replace(e,"^$1")},ft.argument=function(t,r){return t=(t=`"${t=(t=(t=`${t}`).replace(/(?=(\\+?)?)\1"/g,'$1$1\\"')).replace(/(?=(\\+?)?)\1$/,"$1$1")}"`).replace(e,"^$1"),r&&(t=t.replace(e,"^$1")),t},ft}(),o=function(){if(it)return st;it=1;const e=m,t=function(){if(ot)return nt;ot=1;const e=rt?tt:(rt=1,tt=/^#!(.*)/);return nt=(t="")=>{const r=t.match(e);if(!r)return null;const[n,o]=r[0].replace(/#! ?/,"").split(" "),s=n.split("/").pop();return"env"===s?o:o?`${s} ${o}`:s}}();return st=function(r){const n=Buffer.alloc(150);let o;try{o=e.openSync(r,"r"),e.readSync(o,n,0,150,0),e.closeSync(o)}catch(e){}return t(n.toString())}}(),s="win32"===process.platform,i=/\.(?:com|exe)$/i,a=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;return at=function(r,c,l){c&&!Array.isArray(c)&&(l=c,c=null);const u={command:r,args:c=c?c.slice(0):[],options:l=Object.assign({},l),file:void 0,original:{command:r,args:c}};return l.shell?u:function(r){if(!s)return r;const c=function(e){e.file=t(e);const r=e.file&&o(e.file);return r?(e.args.unshift(e.file),e.command=r,t(e)):e.file}(r),l=!i.test(c);if(r.options.forceShell||l){const t=a.test(c);r.command=e.normalize(r.command),r.command=n.command(r.command),r.args=r.args.map(e=>n.argument(e,t));const o=[r.command].concat(r.args).join(" ");r.args=["/d","/s","/c",`"${o}"`],r.command=process.env.comspec||"cmd.exe",r.options.windowsVerbatimArguments=!0}return r}(u)}}var mt=He(function(){if(dt)return Je.exports;dt=1;const e=u,t=ht(),r=function(){if(ut)return lt;ut=1;const e="win32"===process.platform;function t(e,t){return Object.assign(new Error(`${t} ${e.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}function r(r,n){return e&&1===r&&!n.file?t(n.original,"spawn"):null}return lt={hookChildProcess:function(t,n){if(!e)return;const o=t.emit;t.emit=function(e,s){if("exit"===e){const e=r(s,n);if(e)return o.call(t,"error",e)}return o.apply(t,arguments)}},verifyENOENT:r,verifyENOENTSync:function(r,n){return e&&1===r&&!n.file?t(n.original,"spawnSync"):null},notFoundError:t},lt}();function n(n,o,s){const i=t(n,o,s),a=e.spawn(i.command,i.args,i.options);return r.hookChildProcess(a,i),a}return Je.exports=n,Je.exports.spawn=n,Je.exports.sync=function(n,o,s){const i=t(n,o,s),a=e.spawnSync(i.command,i.args,i.options);return a.error=a.error||r.verifyENOENTSync(a.status,i),a},Je.exports._parse=t,Je.exports._enoent=r,Je.exports}());function gt(e={}){const{env:t=process.env,platform:r=process.platform}=e;return"win32"!==r?"PATH":Object.keys(t).reverse().find(e=>"PATH"===e.toUpperCase())||"Path"}var yt=(e,t)=>({name:`SIGRT${t+1}`,number:bt+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),bt=34,wt=[{name:"SIGHUP",number:1,action:"terminate",description:"Terminal closed",standard:"posix"},{name:"SIGINT",number:2,action:"terminate",description:"User interruption with CTRL-C",standard:"ansi"},{name:"SIGQUIT",number:3,action:"core",description:"User interruption with CTRL-\\",standard:"posix"},{name:"SIGILL",number:4,action:"core",description:"Invalid machine instruction",standard:"ansi"},{name:"SIGTRAP",number:5,action:"core",description:"Debugger breakpoint",standard:"posix"},{name:"SIGABRT",number:6,action:"core",description:"Aborted",standard:"ansi"},{name:"SIGIOT",number:6,action:"core",description:"Aborted",standard:"bsd"},{name:"SIGBUS",number:7,action:"core",description:"Bus error due to misaligned, non-existing address or paging error",standard:"bsd"},{name:"SIGEMT",number:7,action:"terminate",description:"Command should be emulated but is not implemented",standard:"other"},{name:"SIGFPE",number:8,action:"core",description:"Floating point arithmetic error",standard:"ansi"},{name:"SIGKILL",number:9,action:"terminate",description:"Forced termination",standard:"posix",forced:!0},{name:"SIGUSR1",number:10,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGSEGV",number:11,action:"core",description:"Segmentation fault",standard:"ansi"},{name:"SIGUSR2",number:12,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGPIPE",number:13,action:"terminate",description:"Broken pipe or socket",standard:"posix"},{name:"SIGALRM",number:14,action:"terminate",description:"Timeout or timer",standard:"posix"},{name:"SIGTERM",number:15,action:"terminate",description:"Termination",standard:"ansi"},{name:"SIGSTKFLT",number:16,action:"terminate",description:"Stack is empty or overflowed",standard:"other"},{name:"SIGCHLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"posix"},{name:"SIGCLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"other"},{name:"SIGCONT",number:18,action:"unpause",description:"Unpaused",standard:"posix",forced:!0},{name:"SIGSTOP",number:19,action:"pause",description:"Paused",standard:"posix",forced:!0},{name:"SIGTSTP",number:20,action:"pause",description:'Paused using CTRL-Z or "suspend"',standard:"posix"},{name:"SIGTTIN",number:21,action:"pause",description:"Background process cannot read terminal input",standard:"posix"},{name:"SIGBREAK",number:21,action:"terminate",description:"User interruption with CTRL-BREAK",standard:"other"},{name:"SIGTTOU",number:22,action:"pause",description:"Background process cannot write to terminal output",standard:"posix"},{name:"SIGURG",number:23,action:"ignore",description:"Socket received out-of-band data",standard:"bsd"},{name:"SIGXCPU",number:24,action:"core",description:"Process timed out",standard:"bsd"},{name:"SIGXFSZ",number:25,action:"core",description:"File too big",standard:"bsd"},{name:"SIGVTALRM",number:26,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGPROF",number:27,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGWINCH",number:28,action:"ignore",description:"Terminal window size changed",standard:"bsd"},{name:"SIGIO",number:29,action:"terminate",description:"I/O is available",standard:"other"},{name:"SIGPOLL",number:29,action:"terminate",description:"Watched event",standard:"other"},{name:"SIGINFO",number:29,action:"ignore",description:"Request for process information",standard:"other"},{name:"SIGPWR",number:30,action:"terminate",description:"Device running out of power",standard:"systemv"},{name:"SIGSYS",number:31,action:"core",description:"Invalid system call",standard:"other"},{name:"SIGUNUSED",number:31,action:"terminate",description:"Invalid system call",standard:"other"}],vt=()=>{const e=(()=>{const e=64-bt+1;return Array.from({length:e},yt)})();return[...wt,...e].map(_t)},_t=({name:e,number:t,description:r,action:n,forced:o=!1,standard:s})=>{const{signals:{[e]:i}}=U,a=void 0!==i;return{name:e,number:a?i:t,description:r,supported:a,action:n,forced:o,standard:s}},Et=({name:e,number:t,description:r,supported:n,action:o,forced:s,standard:i})=>[e,{name:e,number:t,description:r,supported:n,action:o,forced:s,standard:i}],It=(()=>{const e=vt();return Object.fromEntries(e.map(Et))})();(()=>{const e=vt(),t=Array.from({length:65},(t,r)=>((e,t)=>{const r=((e,t)=>{const r=t.find(({name:t})=>U.signals[t]===e);return void 0!==r?r:t.find(t=>t.number===e)})(e,t);if(void 0===r)return{};const{name:n,description:o,supported:s,action:i,forced:a,standard:c}=r;return{[e]:{name:n,number:e,description:o,supported:s,action:i,forced:a,standard:c}}})(r,e));Object.assign({},...t)})();var Tt=({stdout:e,stderr:t,all:r,error:n,signal:o,exitCode:s,command:i,escapedCommand:a,timedOut:c,isCanceled:l,killed:u,parsed:{options:{timeout:d,cwd:p=h.cwd()}}})=>{s=null===s?void 0:s;const f=void 0===(o=null===o?void 0:o)?void 0:It[o].description,m=(({timedOut:e,timeout:t,errorCode:r,signal:n,signalDescription:o,exitCode:s,isCanceled:i})=>e?`timed out after ${t} milliseconds`:void 0!==r?`failed with ${r}`:void 0!==n?`was killed with ${n} (${o})`:void 0!==s?`failed with exit code ${s}`:"failed")({timedOut:c,timeout:d,errorCode:n&&n.code,signal:o,signalDescription:f,exitCode:s,isCanceled:l}),g=`Command ${m}: ${i}`,y="[object Error]"===Object.prototype.toString.call(n),b=y?`${g}\n${n.message}`:g,w=[b,t,e].filter(Boolean).join("\n");return y?(n.originalMessage=n.message,n.message=w):n=new Error(w),n.shortMessage=b,n.command=i,n.escapedCommand=a,n.exitCode=s,n.signal=o,n.signalDescription=f,n.stdout=e,n.stderr=t,n.cwd=p,void 0!==r&&(n.all=r),"bufferedData"in n&&delete n.bufferedData,n.failed=!0,n.timedOut=Boolean(c),n.isCanceled=l,n.killed=u&&!c,n},xt=["stdin","stdout","stderr"],St=[];St.push("SIGHUP","SIGINT","SIGTERM"),"win32"!==process.platform&&St.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),"linux"===process.platform&&St.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var At,Ct,Rt=e=>!!e&&"object"==typeof e&&"function"==typeof e.removeListener&&"function"==typeof e.emit&&"function"==typeof e.reallyExit&&"function"==typeof e.listeners&&"function"==typeof e.kill&&"number"==typeof e.pid&&"function"==typeof e.on,Pt=Symbol.for("signal-exit emitter"),Ut=globalThis,kt=Object.defineProperty.bind(Object),Lt=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(Ut[Pt])return Ut[Pt];kt(Ut,Pt,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,t){this.listeners[e].push(t)}removeListener(e,t){const r=this.listeners[e],n=r.indexOf(t);-1!==n&&(0===n&&1===r.length?r.length=0:r.splice(n,1))}emit(e,t,r){if(this.emitted[e])return!1;this.emitted[e]=!0;let n=!1;for(const o of this.listeners[e])n=!0===o(t,r)||n;return"exit"===e&&(n=this.emit("afterExit",t,r)||n),n}},Dt=class{},Ot=globalThis.process;Rt(Ot)?new class extends Dt{#e="win32"===Ot.platform?"SIGINT":"SIGHUP";#t=new Lt;#r;#n;#o;#s={};#i=!1;constructor(e){super(),this.#r=e,this.#s={};for(const t of St)this.#s[t]=()=>{const r=this.#r.listeners(t);let{count:n}=this.#t;const o=e;if("object"==typeof o.__signal_exit_emitter__&&"number"==typeof o.__signal_exit_emitter__.count&&(n+=o.__signal_exit_emitter__.count),r.length===n){this.unload();const r=this.#t.emit("exit",null,t),n="SIGHUP"===t?this.#e:t;r||e.kill(e.pid,n)}};this.#o=e.reallyExit,this.#n=e.emit}onExit(e,t){if(!Rt(this.#r))return()=>{};!1===this.#i&&this.load();const r=t?.alwaysLast?"afterExit":"exit";return this.#t.on(r,e),()=>{this.#t.removeListener(r,e),0===this.#t.listeners.exit.length&&0===this.#t.listeners.afterExit.length&&this.unload()}}load(){if(!this.#i){this.#i=!0,this.#t.count+=1;for(const e of St)try{const t=this.#s[e];t&&this.#r.on(e,t)}catch(e){}this.#r.emit=(e,...t)=>this.#a(e,...t),this.#r.reallyExit=e=>this.#c(e)}}unload(){this.#i&&(this.#i=!1,St.forEach(e=>{const t=this.#s[e];if(!t)throw new Error("Listener not defined for signal: "+e);try{this.#r.removeListener(e,t)}catch(e){}}),this.#r.emit=this.#n,this.#r.reallyExit=this.#o,this.#t.count-=1)}#c(e){return Rt(this.#r)?(this.#r.exitCode=e||0,this.#t.emit("exit",this.#r.exitCode,null),this.#o.call(this.#r,this.#r.exitCode)):0}#a(e,...t){const r=this.#n;if("exit"===e&&Rt(this.#r)){"number"==typeof t[0]&&(this.#r.exitCode=t[0]);const n=r.call(this.#r,e,...t);return this.#t.emit("exit",this.#r.exitCode,null),n}return r.call(this.#r,e,...t)}}(Ot):new class extends Dt{onExit(){return()=>{}}load(){}unload(){}},new TextEncoder,function(){if(Ct)return At;Ct=1;const{PassThrough:e}=k;At=function(){var t=[],r=new e({objectMode:!0});return r.setMaxListeners(0),r.add=n,r.isEmpty=function(){return 0==t.length},r.on("unpipe",o),Array.prototype.slice.call(arguments).forEach(n),r;function n(e){return Array.isArray(e)?(e.forEach(n),this):(t.push(e),e.once("end",o.bind(null,e)),e.once("error",r.emit.bind(r,"error")),e.pipe(r,{end:!1}),this)}function o(e){!(t=t.filter(function(t){return t!==e})).length&&r.readable&&r.end()}}}();var Bt=(async()=>{})().constructor.prototype;["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(Bt,e)]);var Nt=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],$t=/^[\w.-]+$/,Mt=L("execa").enabled,jt=(e,t)=>String(e).padStart(t,"0"),Ht=(e,t,n={})=>{const o=mt._parse(e,t,n);return e=o.command,t=o.args,(n={maxBuffer:1e8,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:(n=o.options).cwd||h.cwd(),execPath:h.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:Mt,...n}).env=(({env:e,extendEnv:t,preferLocal:n,localDir:o,execPath:s})=>{const i=t?{...h.env,...e}:e;return n?(({env:e=h.env,...t}={})=>{const n=gt({env:e={...e}});return t.path=e[n],e[n]=(({cwd:e=h.cwd(),path:t=h.env[gt()],preferLocal:n=!0,execPath:o=h.execPath,addExecPath:s=!0}={})=>{const i=e instanceof URL?A(e):e,a=r.resolve(i),c=[];return n&&((e,t)=>{let n;for(;n!==t;)e.push(r.join(t,"node_modules/.bin")),n=t,t=r.resolve(t,"..")})(c,a),s&&((e,t,n)=>{const o=t instanceof URL?A(t):t;e.push(r.resolve(n,o,".."))})(c,o,a),[...c,t].join(r.delimiter)})(t),e})({env:i,cwd:o,execPath:s}):i})(n),n.stdio=(e=>{if(!e)return;const{stdio:t}=e;if(void 0===t)return xt.map(t=>e[t]);if((e=>xt.some(t=>void 0!==e[t]))(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${xt.map(e=>`\`${e}\``).join(", ")}`);if("string"==typeof t)return t;if(!Array.isArray(t))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof t}\``);const r=Math.max(t.length,xt.length);return Array.from({length:r},(e,r)=>t[r])})(n),"win32"===h.platform&&"cmd"===r.basename(e,".exe")&&t.unshift("/q"),{file:e,args:t,options:n,parsed:o}},Ft=(e,t,r)=>"string"==typeof t||l.isBuffer(t)?e.stripFinalNewline?function(e){const t="string"==typeof e?"\n":"\n".charCodeAt(),r="string"==typeof e?"\r":"\r".charCodeAt();return e[e.length-1]===t&&(e=e.slice(0,-1)),e[e.length-1]===r&&(e=e.slice(0,-1)),e}(t):t:void 0===r?void 0:"";function Gt(e,t,r){const n=Ht(e,t,r),o=((e,t)=>Nt(e,t).join(" "))(e,t),s=((e,t)=>Nt(e,t).map(e=>(e=>"string"!=typeof e||$t.test(e)?e:`"${e.replaceAll('"','\\"')}"`)(e)).join(" "))(e,t);((e,{verbose:t})=>{t&&h.stderr.write(`[${(()=>{const e=new Date;return`${jt(e.getHours(),2)}:${jt(e.getMinutes(),2)}:${jt(e.getSeconds(),2)}.${jt(e.getMilliseconds(),3)}`})()}] ${e}\n`)})(s,n.options);const i=(e=>{const t=(({input:e,inputFile:t})=>"string"!=typeof t?e:((e=>{if(void 0!==e)throw new TypeError("The `input` and `inputFile` options cannot be both set.")})(e),w(t)))(e);if(null!==(r=t)&&"object"==typeof r&&"function"==typeof r.pipe)throw new TypeError("The `input` option cannot be a stream in sync mode");var r;return t})(n.options);let a;try{a=u.spawnSync(n.file,n.args,{...n.options,input:i})}catch(e){throw Tt({error:e,stdout:"",stderr:"",all:"",command:o,escapedCommand:s,parsed:n,timedOut:!1,isCanceled:!1,killed:!1})}const c=Ft(n.options,a.stdout,a.error),l=Ft(n.options,a.stderr,a.error);if(a.error||0!==a.status||null!==a.signal){const e=Tt({stdout:c,stderr:l,error:a.error,signal:a.signal,exitCode:a.status,command:o,escapedCommand:s,parsed:n,timedOut:a.error&&"ETIMEDOUT"===a.error.code,isCanceled:!1,killed:null!==a.signal});if(!n.options.reject)return e;throw e}return{command:o,escapedCommand:s,exitCode:0,stdout:c,stderr:l,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}}function Yt(e){try{return Gt("git",["rev-parse","HEAD"],e).stdout}catch{return}}function Wt(e){try{const t=Gt("git",["rev-parse","--abbrev-ref","HEAD"],e).stdout;if("HEAD"===t){const t=Gt("git",["show","-s","--pretty=%d","HEAD"],e).stdout.replace(/^\(|\)$/g,"").split(", ").find(e=>e.startsWith("origin/"));return t?t.match(/^origin\/(?<branch>.+)/)[1]:void 0}return t}catch{return}}var Vt=/^(?:.*)@(?:.*):(?:\d+\/)?(.*)\.git$/,zt=/^\/(.*)\.git$/;function Kt(e){if(e){if(e.match(Vt))return e.replace(Vt,"$1");try{return new URL(e).pathname.replace(zt,"$1")}catch{return}}}var qt,Jt={detect:({env:e})=>Boolean(e.BUILDKITE),configuration({env:e}){const t="false"===e.BUILDKITE_PULL_REQUEST?void 0:e.BUILDKITE_PULL_REQUEST,r=Boolean(t);return{name:"Buildkite",service:"buildkite",build:e.BUILDKITE_BUILD_NUMBER,buildUrl:e.BUILDKITE_BUILD_URL,commit:e.BUILDKITE_COMMIT,tag:e.BUILDKITE_TAG,branch:r?e.BUILDKITE_PULL_REQUEST_BASE_BRANCH:e.BUILDKITE_BRANCH,slug:Kt(e.BUILDKITE_REPO),pr:t,isPr:r,prBranch:r?e.BUILDKITE_BRANCH:void 0,root:e.BUILDKITE_BUILD_CHECKOUT_PATH}}},Xt={detect:({env:e})=>Boolean(e.CIRCLECI),configuration({env:e}){const t=e.CIRCLE_PR_NUMBER||Le(e.CIRCLE_PULL_REQUEST||e.CI_PULL_REQUEST),r=Boolean(t);return{name:"CircleCI",service:"circleci",build:e.CIRCLE_BUILD_NUM,buildUrl:e.CIRCLE_BUILD_URL,job:`${e.CIRCLE_BUILD_NUM}.${e.CIRCLE_NODE_INDEX}`,commit:e.CIRCLE_SHA1,tag:e.CIRCLE_TAG,branch:r?void 0:e.CIRCLE_BRANCH,pr:t,isPr:r,prBranch:r?e.CIRCLE_BRANCH:void 0,slug:`${e.CIRCLE_PROJECT_USERNAME}/${e.CIRCLE_PROJECT_REPONAME}`}}},Qt="https://cirrus-ci.com",Zt={detect:({env:e})=>Boolean(e.CIRRUS_CI),configuration({env:e}){const t=e.CIRRUS_PR,r=Boolean(t);return{name:"Cirrus CI",service:"cirrus",commit:e.CIRRUS_CHANGE_IN_REPO,tag:e.CIRRUS_TAG,build:e.CIRRUS_BUILD_ID,buildUrl:`${Qt}/build/${e.CIRRUS_BUILD_ID}`,job:e.CIRRUS_TASK_ID,jobUrl:`${Qt}/task/${e.CIRRUS_TASK_ID}`,branch:r?e.CIRRUS_BASE_BRANCH:e.CIRRUS_BRANCH,pr:t,isPr:r,prBranch:r?e.CIRRUS_BRANCH:void 0,slug:e.CIRRUS_REPO_FULL_NAME,root:e.CIRRUS_WORKING_DIR}}},er={detect:({env:e})=>Boolean(e.CODEBUILD_BUILD_ID),configuration:({env:e,cwd:t})=>({name:"AWS CodeBuild",service:"codebuild",commit:Yt({env:e,cwd:t}),build:e.CODEBUILD_BUILD_ID,branch:Wt({env:e,cwd:t}),buildUrl:`https://console.aws.amazon.com/codebuild/home?region=${e.AWS_REGION}#/builds/${e.CODEBUILD_BUILD_ID}/view/new`,root:e.PWD})},tr={detect:({env:e})=>Boolean(e.CF_BUILD_ID),configuration({env:e}){const t=e.CF_PULL_REQUEST_NUMBER,r=Boolean(t);return{name:"Codefresh",service:"codefresh",commit:e.CF_REVISION,build:e.CF_BUILD_ID,buildUrl:e.CF_BUILD_URL,branch:r?e.CF_PULL_REQUEST_TARGET:e.CF_BRANCH,pr:t,isPr:r,prBranch:r?e.CF_BRANCH:void 0,slug:`${e.CF_REPO_OWNER}/${e.CF_REPO_NAME}`,root:e.CF_VOLUME_PATH}}},rr={detect:({env:e})=>Boolean(e.DRONE),configuration({env:e}){const t="pull_request"===e.DRONE_BUILD_EVENT;return{name:"Drone",service:"drone",commit:e.DRONE_COMMIT_SHA,tag:e.DRONE_TAG,build:e.DRONE_BUILD_NUMBER,buildUrl:e.DRONE_BUILD_LINK,branch:t?e.DRONE_TARGET_BRANCH:e.DRONE_BRANCH,job:e.DRONE_JOB_NUMBER,jobUrl:e.DRONE_BUILD_LINK,pr:e.DRONE_PULL_REQUEST,isPr:t,prBranch:t?e.DRONE_SOURCE_BRANCH:void 0,slug:`${e.DRONE_REPO_OWNER}/${e.DRONE_REPO_NAME}`,root:e.DRONE_WORKSPACE}}},nr=({env:e})=>{try{const t=e.GITHUB_EVENT_PATH?JSON.parse(w(e.GITHUB_EVENT_PATH,"utf-8")):void 0;if(t&&t.pull_request)return{branch:t.pull_request.base?De(t.pull_request.base.ref):void 0,pr:t.pull_request.number}}catch{}return{pr:void 0,branch:void 0}},or={detect:({env:e})=>Boolean(e.GITHUB_ACTIONS),configuration({env:e,cwd:t}){const r="pull_request"===e.GITHUB_EVENT_NAME||"pull_request_target"===e.GITHUB_EVENT_NAME,n=De("pull_request_target"===e.GITHUB_EVENT_NAME?`refs/pull/${(e=>{const t=e.GITHUB_EVENT_PATH?JSON.parse(w(e.GITHUB_EVENT_PATH,"utf-8")):void 0;return t&&t.pull_request?t.pull_request.number:void 0})(e)}/merge`:e.GITHUB_REF);return{name:"GitHub Actions",service:"github",commit:e.GITHUB_SHA,build:e.GITHUB_RUN_ID,buildUrl:`${e.GITHUB_SERVER_URL}/${e.GITHUB_REPOSITORY}/actions/runs/${e.GITHUB_RUN_ID}`,isPr:r,branch:n,prBranch:r?n:void 0,slug:e.GITHUB_REPOSITORY,root:e.GITHUB_WORKSPACE,...r?nr({env:e}):void 0}}},sr={detect:({env:e})=>Boolean(e.GITLAB_CI),configuration({env:e}){const t=e.CI_MERGE_REQUEST_ID,r=Boolean(t);return{name:"GitLab CI/CD",service:"gitlab",commit:e.CI_COMMIT_SHA,tag:e.CI_COMMIT_TAG,build:e.CI_PIPELINE_ID,buildUrl:`${e.CI_PROJECT_URL}/pipelines/${e.CI_PIPELINE_ID}`,job:e.CI_JOB_ID,jobUrl:`${e.CI_PROJECT_URL}/-/jobs/${e.CI_JOB_ID}`,branch:r?e.CI_MERGE_REQUEST_TARGET_BRANCH_NAME:e.CI_COMMIT_REF_NAME,pr:t,isPr:r,prBranch:e.CI_MERGE_REQUEST_SOURCE_BRANCH_NAME,slug:e.CI_PROJECT_PATH,root:e.CI_PROJECT_DIR}}},ir={detect:({env:e})=>Boolean(e.JENKINS_URL),configuration({env:e,cwd:t}){const r=e.ghprbPullId||e.gitlabMergeRequestId||e.CHANGE_ID,n=Boolean(r),o=e.GIT_LOCAL_BRANCH||e.GIT_BRANCH||e.gitlabBranch||e.BRANCH_NAME;return{name:"Jenkins",service:"jenkins",commit:e.ghprbActualCommit||e.GIT_COMMIT||Yt({env:e,cwd:t}),branch:n?e.ghprbTargetBranch||e.gitlabTargetBranch:o,build:e.BUILD_NUMBER,buildUrl:e.BUILD_URL,root:e.WORKSPACE,pr:r,isPr:n,prBranch:n?e.ghprbSourceBranch||e.gitlabSourceBranch||o:void 0}}},ar={detect:({env:e})=>"true"===e.NETLIFY,configuration({env:e}){const t="true"===e.PULL_REQUEST;return{name:"Netlify",service:"netlify",commit:e.COMMIT_REF,build:e.DEPLOY_ID,buildUrl:`https://app.netlify.com/sites/${e.SITE_NAME}/deploys/${e.DEPLOY_ID}`,branch:t?void 0:e.HEAD,pr:e.REVIEW_ID,isPr:t,prBranch:t?e.HEAD:void 0,slug:e.REPOSITORY_URL.match(/[^/:]+\/[^/]+?$/)[0],root:e.PWD}}},cr={detect:({env:e})=>Boolean(e.DISTELLI_APPNAME),configuration:({env:e})=>({name:"Puppet",service:"puppet",build:e.DISTELLI_BUILDNUM,buildUrl:e.DISTELLI_RELEASE,commit:e.DISTELLI_RELREVISION,branch:e.DISTELLI_RELBRANCH,root:e.DISTELLI_INSTALLHOME})},lr={detect:({env:e})=>Boolean(e.SAILCI),configuration({env:e}){const t=e.SAIL_PULL_REQUEST_NUMBER,r=Boolean(t);return{name:"Sail CI",service:"sail",commit:e.SAIL_COMMIT_SHA,branch:r?void 0:e.SAIL_COMMIT_BRANCH,pr:t,isPr:r,slug:`${e.SAIL_REPO_OWNER}/${e.SAIL_REPO_NAME}`,root:e.SAIL_CLONE_DIR}}},ur={detect:({env:e})=>Boolean(e.SCREWDRIVER),configuration({env:e}){const t=e.SD_PULL_REQUEST,r=Boolean(t);return{name:"Screwdriver.cd",service:"screwdriver",branch:r?e.PR_BASE_BRANCH_NAME:e.GIT_BRANCH,prBranch:r?e.PR_BRANCH_NAME:void 0,commit:e.SD_BUILD_SHA,build:e.SD_BUILD_ID,buildUrl:e.SD_UI_BUILD_URL,job:e.SD_JOB_ID,pr:t,isPr:r,slug:e.SD_PIPELINE_NAME,root:e.SD_ROOT_DIR}}},dr={detect:({env:e})=>Boolean(e.SCRUTINIZER),configuration({env:e}){const t=e.SCRUTINIZER_PR_NUMBER,r=Boolean(t);return{name:"Scrutinizer",service:"scrutinizer",commit:e.SCRUTINIZER_SHA1,build:e.SCRUTINIZER_INSPECTION_UUID,branch:e.SCRUTINIZER_BRANCH,pr:t,isPr:r,prBranch:e.SCRUTINIZER_PR_SOURCE_BRANCH}}},pr={detect:({env:e})=>Boolean(e.SEMAPHORE),configuration({env:e,cwd:t}){const r=e.SEMAPHORE_GIT_PR_NUMBER||e.PULL_REQUEST_NUMBER,n=Boolean(r);return{name:"Semaphore",service:"semaphore",commit:e.SEMAPHORE_GIT_SHA||Yt({env:e,cwd:t}),tag:e.SEMAPHORE_GIT_TAG_NAME,build:e.SEMAPHORE_JOB_ID||e.SEMAPHORE_BUILD_NUMBER,branch:e.SEMAPHORE_GIT_BRANCH||(n?void 0:e.BRANCH_NAME),pr:r,isPr:n,prBranch:e.SEMAPHORE_GIT_PR_BRANCH||(n?e.BRANCH_NAME:void 0),slug:e.SEMAPHORE_GIT_REPO_SLUG||e.SEMAPHORE_REPO_SLUG,root:e.SEMAPHORE_GIT_DIR||e.SEMAPHORE_PROJECT_DIR}}},fr={detect:({env:e})=>Boolean(e.SHIPPABLE),configuration({env:e}){const t="true"===e.IS_PULL_REQUEST?e.PULL_REQUEST:void 0,r=Boolean(t);return{name:"Shippable",service:"shippable",commit:e.COMMIT,tag:e.GIT_TAG_NAME,build:e.BUILD_NUMBER,buildUrl:e.BUILD_URL,branch:r?e.BASE_BRANCH:e.BRANCH,job:e.JOB_NUMBER,pr:t,isPr:r,prBranch:r?e.HEAD_BRANCH:void 0,slug:e.SHIPPABLE_REPO_SLUG,root:e.SHIPPABLE_BUILD_DIR}}},hr={};function mr(){if(qt)return hr;qt=1,Object.defineProperty(hr,"__esModule",{value:!0}),hr.of=hr.PropertiesFile=void 0;var e,t=(e=m)&&e.__esModule?e:{default:e};class r{constructor(...e){this.objs={},e.length&&this.of.apply(this,e)}makeKeys(e){if(e&&0!==e.indexOf("#")){let t=["=",":"].map(t=>e.indexOf(t)).filter(e=>e>-1),r=Math.min(...t),n=e.substring(0,r).trim(),o=e.substring(r+1).trim();if(this.objs.hasOwnProperty(n))if(Array.isArray(this.objs[n]))this.objs[n].push(o);else{let e=this.objs[n];this.objs[n]=[e,o]}else{const e=o.replace(/"/g,'\\"').replace(/\\:/g,":").replace(/\\=/g,"=");this.objs[n]=unescape(JSON.parse('"'+e+'"'))}}}addFile(e){let r=t.default.readFileSync(e,"utf-8").split(/\r?\n/),n=this;for(let e=0;e<r.length;e++){let t=r[e];for(;"\\"===t.substring(t.length-1);)t=t.slice(0,-1),t+=r[e+1].trim(),e++;n.makeKeys(t)}}of(...e){for(let t=0;t<e.length;t++)this.addFile(e[t])}get(e,t){if(this.objs.hasOwnProperty(e)){if(Array.isArray(this.objs[e])){let t=[];for(let r=0;r<this.objs[e].length;r++)t[r]=this.interpolate(this.objs[e][r]);return t}return void 0===this.objs[e]?"":this.interpolate(this.objs[e])}return t}getLast(e,t){if(this.objs.hasOwnProperty(e)){if(Array.isArray(this.objs[e])){var r=this.objs[e].length;return this.interpolate(this.objs[e][r-1])}return void 0===this.objs[e]?"":this.interpolate(this.objs[e])}return t}getFirst(e,t){return this.objs.hasOwnProperty(e)?Array.isArray(this.objs[e])?this.interpolate(this.objs[e][0]):void 0===this.objs[e]?"":this.interpolate(this.objs[e]):t}getInt(e,t){let r=this.getLast(e);return r?parseInt(r,10):t}getFloat(e,t){let r=this.getLast(e);return r?parseFloat(r):t}getBoolean(e,t){let r=this.getLast(e);return r?!/^(false|0)$/i.test(n=r)&&!!n:t||!1;var n}set(e,t){this.objs[e]=t}interpolate(e){let t=this;return e.replace(/\\\\/g,"\\").replace(/\$\{([A-Za-z0-9\.\-\_]*)\}/g,function(e){return t.getLast(e.substring(2,e.length-1))})}getKeys(){let e=[];for(let t in this.objs)e.push(t);return e}getMatchingKeys(e){let t=[];for(let r in this.objs)-1!==r.search(e)&&t.push(r);return t}reset(){this.objs={}}}return hr.PropertiesFile=r,hr.of=function(...e){let t=new r;return t.of.apply(t,e),t},hr}var gr=He(mr()),yr={root:"teamcity.build.workingDir",branch:"teamcity.build.branch"},br=e=>{try{return gr.of(e)}catch{return}},wr=({env:e,cwd:t})=>{const r=e.TEAMCITY_BUILD_PROPERTIES_FILE?br(e.TEAMCITY_BUILD_PROPERTIES_FILE):void 0,n=r?r.get("teamcity.configuration.properties.file"):void 0,o=n?br(n):n;return Object.fromEntries(Object.keys(yr).map(n=>[n,(r?r.get(yr[n]):void 0)||(o?o.get(yr[n]):void 0)||("branch"===n?Wt({env:e,cwd:t}):void 0)]))},vr={appveyor:ke,azurePipelines:Oe,bamboo:Be,bitbucket:Ne,bitrise:$e,buddy:Me,buildkite:Jt,circleci:Xt,cirrus:Zt,cloudflarePages:{detect:({env:e})=>"1"===e.CF_PAGES,configuration:({env:e})=>({name:"Cloudflare Pages",service:"cloudflarePages",commit:e.CF_PAGES_COMMIT_SHA,branch:e.CF_PAGES_BRANCH,root:e.PWD})},codebuild:er,codefresh:tr,codeship:{detect:({env:e})=>e.CI_NAME&&"codeship"===e.CI_NAME,configuration:({env:e})=>({name:"Codeship",service:"codeship",build:e.CI_BUILD_NUMBER,buildUrl:e.CI_BUILD_URL,commit:e.CI_COMMIT_ID,branch:e.CI_BRANCH,slug:e.CI_REPO_NAME})},drone:rr,github:or,gitlab:sr,jenkins:ir,netlify:ar,puppet:cr,sail:lr,screwdriver:ur,scrutinizer:dr,semaphore:pr,shippable:fr,teamcity:{detect:({env:e})=>Boolean(e.TEAMCITY_VERSION),configuration:({env:e,cwd:t})=>({name:"TeamCity",service:"teamcity",commit:e.BUILD_VCS_NUMBER,build:e.BUILD_NUMBER,slug:e.TEAMCITY_BUILDCONF_NAME,...wr({env:e,cwd:t})})},travis:{detect:({env:e})=>Boolean(e.TRAVIS),configuration({env:e}){const t="false"===e.TRAVIS_PULL_REQUEST?void 0:e.TRAVIS_PULL_REQUEST,r=Boolean(t);return{name:"Travis CI",service:"travis",commit:e.TRAVIS_COMMIT,tag:e.TRAVIS_TAG,build:e.TRAVIS_BUILD_NUMBER,buildUrl:e.TRAVIS_BUILD_WEB_URL,branch:e.TRAVIS_BRANCH,job:e.TRAVIS_JOB_NUMBER,jobUrl:e.TRAVIS_JOB_WEB_URL,pr:t,isPr:r,prBranch:e.TRAVIS_PULL_REQUEST_BRANCH,slug:e.TRAVIS_REPO_SLUG,root:e.TRAVIS_BUILD_DIR}}},vela:{detect:({env:e})=>Boolean(e.VELA),configuration({env:e}){const t="pull_request"===e.VELA_BUILD_EVENT;return{name:"Vela",service:"vela",branch:t?e.VELA_PULL_REQUEST_TARGET:e.VELA_BUILD_BRANCH,commit:e.VELA_BUILD_COMMIT,tag:e.VELA_BUILD_TAG,build:e.VELA_BUILD_NUMBER,buildUrl:e.VELA_BUILD_LINK,job:void 0,jobUrl:void 0,isPr:t,pr:e.VELA_BUILD_PULL_REQUEST,prBranch:e.VELA_PULL_REQUEST_SOURCE,slug:e.VELA_REPO_FULL_NAME,root:e.VELA_BUILD_WORKSPACE}}},vercel:{detect:({env:e})=>Boolean(e.VERCEL)||Boolean(e.NOW_GITHUB_DEPLOYMENT),configuration({env:e}){const t="Vercel",r="vercel";return e.VERCEL?{name:t,service:r,commit:e.VERCEL_GIT_COMMIT_SHA,branch:e.VERCEL_GIT_COMMIT_REF,slug:`${e.VERCEL_GIT_REPO_OWNER}/${e.VERCEL_GIT_REPO_SLUG}`}:{name:t,service:r,commit:e.NOW_GITHUB_COMMIT_SHA,branch:e.NOW_GITHUB_COMMIT_REF,slug:`${e.NOW_GITHUB_ORG}/${e.NOW_GITHUB_REPO}`}}},wercker:{detect:({env:e})=>Boolean(e.WERCKER_MAIN_PIPELINE_STARTED),configuration:({env:e})=>({name:"Wercker",service:"wercker",commit:e.WERCKER_GIT_COMMIT,build:e.WERCKER_MAIN_PIPELINE_STARTED,buildUrl:e.WERCKER_RUN_URL,branch:e.WERCKER_GIT_BRANCH,slug:`${e.WERCKER_GIT_OWNER}/${e.WERCKER_GIT_REPOSITORY}`,root:e.WERCKER_ROOT})},woodpecker:{detect:({env:e})=>e.CI&&"woodpecker"===e.CI,configuration({env:e}){const t="pull_request"===e.CI_PIPELINE_EVENT;return{name:"Woodpecker CI",service:"woodpecker",commit:e.CI_COMMIT_SHA,tag:e.CI_COMMIT_TAG,build:e.CI_PIPELINE_NUMBER,buildUrl:e.CI_PIPELINE_URL,branch:t?e.CI_COMMIT_TARGET_BRANCH:e.CI_COMMIT_BRANCH,job:e.CI_STEP_NUMBER,jobUrl:e.CI_STEP_URL,pr:e.CI_COMMIT_PULL_REQUEST,isPr:t,prBranch:t?e.CI_COMMIT_SOURCE_BRANCH:void 0,slug:`${e.CI_REPO_OWNER}/${e.CI_REPO_NAME}`,root:e.CI_WORKSPACE}}},jetbrainsSpace:{detect:({env:e})=>Boolean(e.JB_SPACE_EXECUTION_NUMBER),configuration({env:e}){const t=e.JB_SPACE_PROJECT_KEY,r=e.JB_SPACE_GIT_REPOSITORY_NAME;return{name:"JetBrains Space",service:"jetbrainsSpace",commit:e.JB_SPACE_GIT_REVISION,build:e.JB_SPACE_EXECUTION_NUMBER,branch:De(e.JB_SPACE_GIT_BRANCH),slug:t&&r?`${t.toLowerCase()}/${r}`:void 0}}}},_r=class e{git;config;snapshotTreeHash;snapshotIndexPath;constructor(e){this.config=e,this.git=Y({baseDir:e.workingDir,maxConcurrentProcesses:1})}static createLocal({workingDir:t}){return new e({mode:"local",workingDir:t})}static createCloud({workingDir:t,baseBranch:r}){return new e({mode:"cloud",workingDir:t,baseBranch:r})}async captureSnapshot(){if("local"!==this.config.mode)return;this.snapshotIndexPath=s(P(),`git-diff-tracker-${F()}.index`),await this.git.env("GIT_INDEX_FILE",this.snapshotIndexPath).add(["-A"]);const e=await this.git.env("GIT_INDEX_FILE",this.snapshotIndexPath).raw(["write-tree"]);this.snapshotTreeHash=e.trim()}async computeDiff(){return"local"===this.config.mode?this.computeLocalDiff():this.computeCloudDiff()}async computeLocalDiff(){if(!this.snapshotTreeHash)throw new Error("No snapshot captured. Call captureSnapshot() first.");const e=s(P(),`git-diff-tracker-${F()}.index`);try{await this.git.env("GIT_INDEX_FILE",e).add(["-A"]);const t=(await this.git.env("GIT_INDEX_FILE",e).raw(["write-tree"])).trim();return await this.git.raw(["diff-tree","-p","--no-color",this.snapshotTreeHash,t])}finally{await Er(e)}}async computeCloudDiff(){if("cloud"!==this.config.mode)throw new Error("computeCloudDiff called but mode is not cloud");const{baseBranch:e}=this.config;return await this.git.revparse([`origin/${e}`]).then(()=>!0).catch(()=>!1)||await this.git.fetch(["origin",`+${e}:refs/remotes/origin/${e}`,"--depth","1","--quiet"]).catch(e=>{console.error("[git-diff-tracker] Failed to fetch base branch:",e)}),await this.git.diff([`origin/${e}`])}async cleanup(){this.snapshotIndexPath&&(await Er(this.snapshotIndexPath),this.snapshotIndexPath=void 0),this.snapshotTreeHash=void 0}};async function Er(e){try{await q(e)}catch{}}var Ir="x-stably-org-id",Tr={bodySerializer:e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t)},xr=({allowReserved:e,explode:t,name:r,style:n,value:o})=>{if(!t){const t=(e?o:o.map(e=>encodeURIComponent(e))).join((e=>{switch(e){case"form":default:return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20"}})(n));switch(n){case"label":return`.${t}`;case"matrix":return`;${r}=${t}`;case"simple":return t;default:return`${r}=${t}`}}const s=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(n),i=o.map(t=>"label"===n||"simple"===n?e?t:encodeURIComponent(t):Sr({allowReserved:e,name:r,value:t})).join(s);return"label"===n||"matrix"===n?s+i:i},Sr=({allowReserved:e,name:t,value:r})=>{if(null==r)return"";if("object"==typeof r)throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${t}=${e?r:encodeURIComponent(r)}`},Ar=({allowReserved:e,explode:t,name:r,style:n,value:o,valueOnly:s})=>{if(o instanceof Date)return s?o.toISOString():`${r}=${o.toISOString()}`;if("deepObject"!==n&&!t){let t=[];Object.entries(o).forEach(([r,n])=>{t=[...t,r,e?n:encodeURIComponent(n)]});const s=t.join(",");switch(n){case"form":return`${r}=${s}`;case"label":return`.${s}`;case"matrix":return`;${r}=${s}`;default:return s}}const i=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(n),a=Object.entries(o).map(([t,o])=>Sr({allowReserved:e,name:"deepObject"===n?`${r}[${t}]`:t,value:o})).join(i);return"label"===n||"matrix"===n?i+a:a},Cr=/\{[^{}]+\}/g;function Rr(e){const t=void 0!==e.body;return t&&e.bodySerializer?"serializedBody"in e?void 0!==e.serializedBody&&""!==e.serializedBody?e.serializedBody:null:""!==e.body?e.body:null:t?e.body:void 0}var Pr,Ur=async(e,t)=>{const r="function"==typeof t?await t(e):t;if(r)return"bearer"===e.scheme?`Bearer ${r}`:"basic"===e.scheme?`Basic ${btoa(r)}`:r},kr=({parameters:e={},...t}={})=>r=>{const n=[];if(r&&"object"==typeof r)for(const o in r){const s=r[o];if(null==s)continue;const i=e[o]||t;if(Array.isArray(s)){const e=xr({allowReserved:i.allowReserved,explode:!0,name:o,style:"form",value:s,...i.array});e&&n.push(e)}else if("object"==typeof s){const e=Ar({allowReserved:i.allowReserved,explode:!0,name:o,style:"deepObject",value:s,...i.object});e&&n.push(e)}else{const e=Sr({allowReserved:i.allowReserved,name:o,value:s});e&&n.push(e)}}return n.join("&")},Lr=(e,t)=>!!t&&!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`)),Dr=e=>(({baseUrl:e,path:t,query:r,querySerializer:n,url:o})=>{let s=(e??"")+(o.startsWith("/")?o:`/${o}`);t&&(s=(({path:e,url:t})=>{let r=t;const n=t.match(Cr);if(n)for(const t of n){let n=!1,o=t.substring(1,t.length-1),s="simple";o.endsWith("*")&&(n=!0,o=o.substring(0,o.length-1)),o.startsWith(".")?(o=o.substring(1),s="label"):o.startsWith(";")&&(o=o.substring(1),s="matrix");const i=e[o];if(null==i)continue;if(Array.isArray(i)){r=r.replace(t,xr({explode:n,name:o,style:s,value:i}));continue}if("object"==typeof i){r=r.replace(t,Ar({explode:n,name:o,style:s,value:i,valueOnly:!0}));continue}if("matrix"===s){r=r.replace(t,`;${Sr({name:o,value:i})}`);continue}const a=encodeURIComponent("label"===s?`.${i}`:i);r=r.replace(t,a)}return r})({path:t,url:s}));let i=r?n(r):"";return i.startsWith("?")&&(i=i.substring(1)),i&&(s+=`?${i}`),s})({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:"function"==typeof e.querySerializer?e.querySerializer:kr(e.querySerializer),url:e.url}),Or=(e,t)=>{const r={...e,...t};return r.baseUrl?.endsWith("/")&&(r.baseUrl=r.baseUrl.substring(0,r.baseUrl.length-1)),r.headers=Nr(e.headers,t.headers),r},Br=e=>{const t=[];return e.forEach((e,r)=>{t.push([r,e])}),t},Nr=(...e)=>{const t=new Headers;for(const r of e){if(!r)continue;const e=r instanceof Headers?Br(r):Object.entries(r);for(const[r,n]of e)if(null===n)t.delete(r);else if(Array.isArray(n))for(const e of n)t.append(r,e);else void 0!==n&&t.set(r,"object"==typeof n?JSON.stringify(n):n)}return t},$r=class{fns=[];clear(){this.fns=[]}eject(e){const t=this.getInterceptorIndex(e);this.fns[t]&&(this.fns[t]=null)}exists(e){const t=this.getInterceptorIndex(e);return Boolean(this.fns[t])}getInterceptorIndex(e){return"number"==typeof e?this.fns[e]?e:-1:this.fns.indexOf(e)}update(e,t){const r=this.getInterceptorIndex(e);return!!this.fns[r]&&(this.fns[r]=t,e)}use(e){return this.fns.push(e),this.fns.length-1}},Mr=kr({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),jr={"Content-Type":"application/json"},Hr=(e={})=>({...Tr,headers:jr,parseAs:"auto",querySerializer:Mr,...e}),Fr=(e={})=>{let t=Or(Hr(),e);const r=()=>({...t}),n={error:new $r,request:new $r,response:new $r},o=async e=>{const r={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:Nr(t.headers,e.headers),serializedBody:void 0};return r.security&&await(async({security:e,...t})=>{for(const r of e){if(Lr(t,r.name))continue;const e=await Ur(r,t.auth);if(!e)continue;const n=r.name??"Authorization";switch(r.in){case"query":t.query||(t.query={}),t.query[n]=e;break;case"cookie":t.headers.append("Cookie",`${n}=${e}`);break;default:t.headers.set(n,e)}}})({...r,security:r.security}),r.requestValidator&&await r.requestValidator(r),void 0!==r.body&&r.bodySerializer&&(r.serializedBody=r.bodySerializer(r.body)),void 0!==r.body&&""!==r.serializedBody||r.headers.delete("Content-Type"),{opts:r,url:Dr(r)}},s=async e=>{const{opts:t,url:r}=await o(e),s={redirect:"follow",...t,body:Rr(t)};let i=new Request(r,s);for(const e of n.request.fns)e&&(i=await e(i,t));const a=t.fetch;let c;try{c=await a(i)}catch(e){let r=e;for(const o of n.error.fns)o&&(r=await o(e,void 0,i,t));if(r=r||{},t.throwOnError)throw r;return"data"===t.responseStyle?void 0:{error:r,request:i,response:void 0}}for(const e of n.response.fns)e&&(c=await e(c,i,t));const l={request:i,response:c};if(c.ok){const e=("auto"===t.parseAs?(e=>{if(!e)return"stream";const t=e.split(";")[0]?.trim();return t?t.startsWith("application/json")||t.endsWith("+json")?"json":"multipart/form-data"===t?"formData":["application/","audio/","image/","video/"].some(e=>t.startsWith(e))?"blob":t.startsWith("text/")?"text":void 0:void 0})(c.headers.get("Content-Type")):t.parseAs)??"json";if(204===c.status||"0"===c.headers.get("Content-Length")){let r;switch(e){case"arrayBuffer":case"blob":case"text":r=await c[e]();break;case"formData":r=new FormData;break;case"stream":r=c.body;break;default:r={}}return"data"===t.responseStyle?r:{data:r,...l}}let r;switch(e){case"arrayBuffer":case"blob":case"formData":case"json":case"text":r=await c[e]();break;case"stream":return"data"===t.responseStyle?c.body:{data:c.body,...l}}return"json"===e&&(t.responseValidator&&await t.responseValidator(r),t.responseTransformer&&(r=await t.responseTransformer(r))),"data"===t.responseStyle?r:{data:r,...l}}const u=await c.text();let d;try{d=JSON.parse(u)}catch{}const p=d??u;let f=p;for(const e of n.error.fns)e&&(f=await e(p,c,i,t));if(f=f||{},t.throwOnError)throw f;return"data"===t.responseStyle?void 0:{error:f,...l}},i=e=>t=>s({...t,method:e}),a=e=>async t=>{const{opts:r,url:s}=await o(t);return(({onRequest:e,onSseError:t,onSseEvent:r,responseTransformer:n,responseValidator:o,sseDefaultRetryDelay:s,sseMaxRetryAttempts:i,sseMaxRetryDelay:a,sseSleepFn:c,url:l,...u})=>{let d;const p=c??(e=>new Promise(t=>setTimeout(t,e)));return{stream:async function*(){let c=s??3e3,f=0;const h=u.signal??(new AbortController).signal;for(;!h.aborted;){f++;const s=u.headers instanceof Headers?u.headers:new Headers(u.headers);void 0!==d&&s.set("Last-Event-ID",d);try{const t={redirect:"follow",...u,body:u.serializedBody,headers:s,signal:h};let i=new Request(l,t);e&&(i=await e(l,t));const a=u.fetch??globalThis.fetch,p=await a(i);if(!p.ok)throw new Error(`SSE failed: ${p.status} ${p.statusText}`);if(!p.body)throw new Error("No body in SSE response");const f=p.body.pipeThrough(new TextDecoderStream).getReader();let m="";const g=()=>{try{f.cancel()}catch{}};h.addEventListener("abort",g);try{for(;;){const{done:e,value:t}=await f.read();if(e)break;m+=t;const s=m.split("\n\n");m=s.pop()??"";for(const e of s){const t=e.split("\n"),s=[];let i,a;for(const e of t)if(e.startsWith("data:"))s.push(e.replace(/^data:\s*/,""));else if(e.startsWith("event:"))i=e.replace(/^event:\s*/,"");else if(e.startsWith("id:"))d=e.replace(/^id:\s*/,"");else if(e.startsWith("retry:")){const t=Number.parseInt(e.replace(/^retry:\s*/,""),10);Number.isNaN(t)||(c=t)}let l=!1;if(s.length){const e=s.join("\n");try{a=JSON.parse(e),l=!0}catch{a=e}}l&&(o&&await o(a),n&&(a=await n(a))),r?.({data:a,event:i,id:d,retry:c}),s.length&&(yield a)}}}finally{h.removeEventListener("abort",g),f.releaseLock()}break}catch(e){if(t?.(e),void 0!==i&&f>=i)break;const r=Math.min(c*2**(f-1),a??3e4);await p(r)}}}()}})({...r,body:r.body,headers:r.headers,method:e,onRequest:async(e,t)=>{let o=new Request(e,t);for(const e of n.request.fns)e&&(o=await e(o,r));return o},url:s})};return{buildUrl:Dr,connect:i("CONNECT"),delete:i("DELETE"),get:i("GET"),getConfig:r,head:i("HEAD"),interceptors:n,options:i("OPTIONS"),patch:i("PATCH"),post:i("POST"),put:i("PUT"),request:s,setConfig:e=>(t=Or(t,e),r()),sse:{connect:a("CONNECT"),delete:a("DELETE"),get:a("GET"),head:a("HEAD"),options:a("OPTIONS"),patch:a("PATCH"),post:a("POST"),put:a("PUT"),trace:a("TRACE")},trace:i("TRACE")}},Gr=Fr(Hr({baseUrl:"https://api.stably.ai"})),Yr="4.6.4",Wr=process.env.STABLY_API_URL||"https://api.stably.ai",Vr=e=>{const t=new URL(e);return t.protocol="http:"===t.protocol?"ws:":"wss:",t},zr=process.env.AUTH_URL||"https://auth.stably.ai",Kr=process.env.AUTH_CLIENT_ID||"288007877071cce81f269428ea78653a",qr=process.env.AI_PROXY_URL||"https://ai-proxy.stably.ai",Jr=process.env.STABLY_AUTOHEAL_WS_URL||new URL("/autoheal",Vr(Wr)).toString(),Xr=process.env.STABLY_CREATE_PROGRESS_WS_URL||new URL("/create-progress",Vr(Wr)).toString(),Qr="http://localhost:9876/auth/callback",Zr=()=>Pr||(Pr=Fr(Hr({baseUrl:Wr,headers:{"X-STABLY-CLI-VERSION":Yr,"X-STABLY-SOURCE":"cli"}}))),en=async(e,t)=>{const r=await(n={body:{accessToken:e,orgId:t},client:Zr()},(n.client??Gr).post({url:"/internal/v1/cli/exchange-token",...n,headers:{"Content-Type":"application/json",...n.headers}}));var n;if(401===r.response.status)throw new Error("Invalid or expired access token");if(403===r.response.status)throw new Error("You do not have access to this organization");if(r.error)throw new Error(`Failed to exchange token: ${r.response.status}`);return r.data},tn=le.object({org_id:le.string(),org_name:le.string()}),rn=le.object({email:le.string(),org_id_to_org_member_info:le.record(le.string(),tn).optional(),org_member_info:tn.optional(),user_id:le.string()});le.object({email:le.string(),firstName:le.string().optional(),lastName:le.string().optional(),organizations:le.array(le.object({id:le.string(),name:le.string()})),userId:le.string()});var nn=e=>{const t=e.split(".");if(3!==t.length)throw new Error("Invalid JWT format");const r=t[1].replace(/-/g,"+").replace(/_/g,"/"),n=Buffer.from(r,"base64").toString("utf-8");return JSON.parse(n)},on=e=>{try{const t=rn.parse(nn(e)),r=t.org_id_to_org_member_info?Object.entries(t.org_id_to_org_member_info).map(([e,t])=>({id:e,name:t.org_name})):t.org_member_info?[{id:t.org_member_info.org_id,name:t.org_member_info.org_name}]:[];return{email:t.email,organizations:r,userId:t.user_id}}catch(e){throw new Error(`Failed to decode token: ${e instanceof Error?e.message:"Unknown error"}`)}},sn=async(e,t)=>{let n=e;const{root:o}=r.parse(n);for(;n!==o;){const e=r.join(n,t);try{return await J(e),e}catch{n=r.dirname(n)}}},an=r.join(R.homedir(),".stably"),cn=r.join(an,"auth.json"),ln=".stably",un="project.json",dn=ce.object({accessToken:ce.string(),expiresAt:ce.number(),idToken:ce.string().optional(),refreshToken:ce.string()}),pn=ce.object({orgId:ce.string(),orgName:ce.string(),projectId:ce.string(),projectName:ce.string()}),fn=async()=>{try{const e=await V(cn,"utf-8");return dn.parse(JSON.parse(e))}catch{return}},hn=async e=>{await z(an,{recursive:!0}),await K(cn,JSON.stringify(e,null,2),{mode:384})},mn=async()=>{try{await q(cn)}catch{}},gn=async()=>{try{const e=await sn(process.cwd(),ln);if(!e)return;const t=r.join(e,un),n=await V(t,"utf-8");return pn.parse(JSON.parse(n))}catch{return}},yn=async()=>{try{const e=await sn(process.cwd(),ln);e&&await q(r.join(e,un))}catch{}},bn=e=>Date.now()>=e.expiresAt-3e5,wn=async e=>{const t=new URLSearchParams({client_id:Kr,grant_type:"refresh_token",refresh_token:e}),r=await fetch(`${zr}/propelauth/oauth/token`,{body:t.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},method:"POST"});if(!r.ok)throw new Error(`Token refresh failed: ${r.status}`);const n=await r.json();return{accessToken:n.access_token,expiresAt:Date.now()+1e3*n.expires_in,refreshToken:n.refresh_token}},vn=e=>`\n<!DOCTYPE html>\n<html>\n<head>\n <title>Authentication Failed Stably CLI</title>\n <style>\n * { box-sizing: border-box; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n display: flex;\n justify-content: center;\n align-items: center;\n min-height: 100vh;\n margin: 0;\n background: #000;\n color: #fafafa;\n }\n .container {\n text-align: center;\n padding: 48px;\n max-width: 400px;\n }\n .icon {\n width: 48px;\n height: 48px;\n border-radius: 50%;\n background: #ef4444;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 24px;\n }\n .icon svg { width: 24px; height: 24px; }\n .title {\n font-size: 24px;\n font-weight: 600;\n margin: 0 0 8px;\n letter-spacing: -0.5px;\n }\n .subtitle {\n color: #888;\n font-size: 14px;\n margin: 0 0 32px;\n line-height: 1.5;\n }\n .error-box {\n background: rgba(239, 68, 68, 0.1);\n border: 1px solid rgba(239, 68, 68, 0.3);\n border-radius: 8px;\n padding: 16px;\n margin-bottom: 24px;\n }\n .error-label {\n font-size: 11px;\n font-weight: 600;\n color: #ef4444;\n text-transform: uppercase;\n letter-spacing: 0.5px;\n margin-bottom: 8px;\n }\n .error-message {\n font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace;\n font-size: 13px;\n color: #fafafa;\n word-break: break-word;\n }\n .hint {\n color: #666;\n font-size: 13px;\n }\n .hint code {\n background: #111;\n border: 1px solid #333;\n border-radius: 4px;\n padding: 2px 6px;\n font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace;\n font-size: 12px;\n color: #888;\n }\n .brand {\n margin-top: 32px;\n font-size: 12px;\n color: #444;\n letter-spacing: 0.5px;\n }\n </style>\n</head>\n<body>\n <div class="container">\n <div class="icon">\n <svg fill="none" stroke="#000" stroke-width="3" viewBox="0 0 24 24">\n <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/>\n </svg>\n </div>\n <h1 class="title">Authentication Failed</h1>\n <p class="subtitle">Something went wrong during login.</p>\n <div class="error-box">\n <div class="error-label">Error</div>\n <div class="error-message">${e}</div>\n </div>\n <p class="hint">Run <code>stably login</code> to try again.</p>\n <div class="brand">STABLY</div>\n </div>\n</body>\n</html>\n`,_n=(e,t,r)=>{e.writeHead(t,{"Content-Type":"text/html"}),e.end(r)},En=(e,t)=>{const r=new URLSearchParams({client_id:Kr,code_challenge:e,code_challenge_method:"S256",redirect_uri:Qr,response_type:"code",state:t});return`${zr}/propelauth/oauth/authorize?${r.toString()}`},In=async e=>{const t=ne();let n;t.start("Loading user info...");try{n=on(e.accessToken),t.stop(G.green(`✓ Logged in as ${G.cyan(n.email)}`))}catch(e){t.stop(G.red("✗ Failed to load user info"));const r=e instanceof Error?e.message:"Unknown error";return te.error(r),{success:!1}}const o=await(async e=>{if(0===e.length)return void te.error("You don't belong to any organizations.");if(1===e.length)return te.info(`Using organization: ${G.cyan(e[0].name)}`),e[0];if(!process.stdin.isTTY)return te.info(`Auto-selecting organization: ${G.cyan(e[0].name)}`),e[0];const t=await se({message:"Select an organization",options:[...e].sort((e,t)=>e.name.localeCompare(t.name)).map(e=>({label:e.name,value:e.id}))});return ie(t)?void 0:e.find(e=>e.id===t)})(n.organizations);if(!o)return te.warn("Organization selection cancelled."),{success:!1};let s;t.start("Getting org credentials...");try{const r=await en(e.accessToken,o.id);s={accessToken:r.accessToken,expiresAt:Date.now()+1e3*r.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken},t.stop(G.green("✓ Credentials obtained"))}catch(e){t.stop(G.red("✗ Failed to get org credentials"));const r=e instanceof Error?e.message:"Unknown error";return te.error(r),{success:!1}}const i=await(async(e,t)=>{const r=ne();let n;r.start("Loading projects...");try{n=await(async({accessToken:e,orgId:t})=>{const r=await(n={auth:e,client:Zr(),path:{orgId:t}},(n.client??Gr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/orgs/{orgId}/projects",...n}));var n;if(401===r.response.status)throw new Error("Invalid or expired access token");if(403===r.response.status)throw new Error("You do not have access to this organization");if(r.error)throw new Error(`Failed to list projects: ${r.response.status}`);return r.data.projects})({accessToken:e,orgId:t}),r.stop(G.green("✓ Projects loaded"))}catch(e){r.stop(G.red("✗ Failed to load projects"));const t=e instanceof Error?e.message:"Unknown error";return void te.error(t)}if(0===n.length)return te.error("No projects found in this organization."),void te.info(`Create a project at ${G.underline(G.cyan("https://app.stably.ai"))}`);if(1===n.length)return te.info(`Using project: ${G.cyan(n[0].name)}`),n[0];if(!process.stdin.isTTY)return te.info(`Auto-selecting project: ${G.cyan(n[0].name)}`),n[0];const o=await se({message:"Select a project",options:n.map(e=>({label:e.name,value:e.id}))});return ie(o)?void 0:n.find(e=>e.id===o)})(s.accessToken,o.id);return i?(await(async e=>{const t=r.join(process.cwd(),ln),n=r.join(t,un);await z(t,{recursive:!0}),await K(n,JSON.stringify(e,null,2)),await(async e=>{const t=r.join(e,".gitignore"),n="# Stably CLI (only docs/ are tracked)\n.stably/*\n!.stably/docs/";try{const e=await V(t,"utf-8"),r=e.split("\n").map(e=>e.trim());if(r.includes(".stably/*")&&r.includes("!.stably/docs/"))return;const o=/^# Stably CLI\n\.stably\/?$/m,s=/^\.stably\/?$/m;if(o.test(e)){const r=e.replace(o,`\n${n}\n`);await K(t,r)}else if(s.test(e)){const r=e.replace(s,`\n${n}\n`);await K(t,r)}else await ee(t,`\n${n}\n`)}catch{await K(t,`${n}\n`)}})(process.cwd())})({orgId:o.id,orgName:o.name,projectId:i.id,projectName:i.name}),te.info(G.dim("Linked this directory to your Stably project.")),{scopedTokens:s,success:!0}):(te.warn("Project selection cancelled."),{success:!1})},Tn=async()=>{if(Yn())return te.warn(`Environment variables ${G.cyan("STABLY_API_KEY")} and ${G.cyan("STABLY_PROJECT_ID")} are set.`),te.warn("These will be used for authentication instead of OAuth login."),te.warn("To use OAuth login, unset these environment variables first."),void re(G.yellow("Login skipped - using environment variable authentication."));const e=await fn();if(e){if(!bn(e)){if(await gn())return void re(G.yellow("You are already logged in. Run `stably logout` first to log out."));te.info("You are logged in but haven't selected a project yet.");const t=await In(e);return void(t.success?(await hn(t.scopedTokens),re(G.green("Setup complete! You can now use Stably CLI."))):re(G.yellow("Setup incomplete. Run `stably login` to try again.")))}const t=ne();t.start("Refreshing session...");try{const r=await wn(e.refreshToken);t.stop(G.green("✓ Session refreshed"));const n=await gn();if(n){t.start("Getting org credentials...");try{const e=await en(r.accessToken,n.orgId),o={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:r.idToken,refreshToken:r.refreshToken};await hn(o),t.stop(G.green("✓ Credentials obtained")),re(G.green("Login successful"))}catch{await hn(r),t.stop(G.yellow("Using full credentials")),re(G.green("Login successful"))}}else{const e=await In(r);e.success?(await hn(e.scopedTokens),re(G.green("Setup complete! You can now use Stably CLI."))):re(G.yellow("Setup incomplete. Run `stably login` to try again."))}return}catch{t.stop(G.yellow("Session expired, proceeding with fresh login...")),await mn(),await yn()}}const{authorizeUrl:t,serverReady:r,waitForCallback:n}=(()=>{const{authorizeUrl:e,codeVerifier:t,state:r}=(()=>{const e=H.randomBytes(32).toString("base64url"),t=(r=e,H.createHash("sha256").update(r).digest("base64url"));var r;const n=H.randomBytes(16).toString("base64url");return{authorizeUrl:En(t,n),codeVerifier:e,state:n}})(),{ready:n,result:o}=(e=>{let t,r;return{ready:new Promise((e,n)=>{t=e,r=n}),result:new Promise((n,o)=>{const s=setTimeout(()=>{a.close(),n({error:"Login timed out",success:!1})},3e5),i=()=>{clearTimeout(s)},a=de.createServer((t,r)=>{const o=new C(t.url||"","http://localhost:9876");if("/auth/callback"!==o.pathname)return r.writeHead(404),void r.end("Not found");const s=o.searchParams.get("code"),c=o.searchParams.get("state"),l=o.searchParams.get("error");return l?(_n(r,400,vn(l)),i(),a.close(),void n({error:l,success:!1})):s&&c?c!==e?(_n(r,400,vn("Invalid state parameter (possible CSRF attack)")),i(),a.close(),void n({error:"State mismatch",success:!1})):(_n(r,200,'\n<!DOCTYPE html>\n<html>\n<head>\n <title>Authenticated Stably CLI</title>\n <style>\n * { box-sizing: border-box; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, sans-serif;\n display: flex;\n justify-content: center;\n align-items: center;\n min-height: 100vh;\n margin: 0;\n background: #000;\n color: #fafafa;\n }\n .container {\n text-align: center;\n padding: 48px;\n max-width: 400px;\n }\n .icon {\n width: 48px;\n height: 48px;\n border-radius: 50%;\n background: #22c55e;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 24px;\n }\n .icon svg { width: 24px; height: 24px; }\n .title {\n font-size: 24px;\n font-weight: 600;\n margin: 0 0 8px;\n letter-spacing: -0.5px;\n }\n .subtitle {\n color: #888;\n font-size: 14px;\n margin: 0 0 32px;\n line-height: 1.5;\n }\n .terminal {\n background: #111;\n border: 1px solid #333;\n border-radius: 8px;\n padding: 16px;\n text-align: left;\n font-family: \'SF Mono\', \'Fira Code\', \'Consolas\', monospace;\n font-size: 13px;\n }\n .terminal-header {\n display: flex;\n gap: 6px;\n margin-bottom: 12px;\n }\n .terminal-dot {\n width: 10px;\n height: 10px;\n border-radius: 50%;\n background: #333;\n }\n .terminal-line {\n color: #888;\n }\n .terminal-line .prompt { color: #888; }\n .terminal-line .cmd { color: #fafafa; }\n .terminal-line.success { color: #22c55e; }\n .brand {\n margin-top: 32px;\n font-size: 12px;\n color: #444;\n letter-spacing: 0.5px;\n }\n </style>\n</head>\n<body>\n <div class="container">\n <div class="icon">\n <svg fill="none" stroke="#000" stroke-width="3" viewBox="0 0 24 24">\n <path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/>\n </svg>\n </div>\n <h1 class="title">Authenticated</h1>\n <p class="subtitle">You can close this tab and return to your terminal.</p>\n <div class="terminal">\n <div class="terminal-header">\n <div class="terminal-dot"></div>\n <div class="terminal-dot"></div>\n <div class="terminal-dot"></div>\n </div>\n <div class="terminal-line"><span class="prompt">$</span> <span class="cmd">stably login</span></div>\n <div class="terminal-line success">Logged in successfully</div>\n </div>\n <div class="brand">STABLY</div>\n </div>\n</body>\n</html>\n'),i(),a.close(),void n({code:s,state:c,success:!0})):(_n(r,400,vn("Missing code or state parameter")),i(),a.close(),void n({error:"Missing code or state parameter",success:!1}))});a.on("error",e=>{if(i(),"EADDRINUSE"===e.code){const e=new Error("Port 9876 is already in use. Please close the application using it and try again.");return r(e),void o(e)}const t=new Error(`Failed to start callback server: ${e.message}`);r(t),o(t)}),a.listen(9876,()=>{t()})})}})(r);return{authorizeUrl:e,serverReady:n,waitForCallback:async()=>{const e=await o;if(!e.success)throw new Error(e.error);return(async(e,t)=>{const r=new URLSearchParams({client_id:Kr,code:e,code_verifier:t,grant_type:"authorization_code",redirect_uri:Qr}),n=await fetch(`${zr}/propelauth/oauth/token`,{body:r.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},method:"POST"});if(!n.ok){const e=await n.text();throw new Error(`Token exchange failed: ${n.status} ${e}`)}const o=await n.json();return{accessToken:o.access_token,expiresAt:Date.now()+1e3*o.expires_in,idToken:o.id_token,refreshToken:o.refresh_token}})(e.code,t)}}})();await r,te.info("Opening browser for authentication..."),te.info(G.dim("If browser doesn't open, visit:")),te.info(`]8;;${t}${G.underline(G.cyan(t))}]8;;`);try{await ue(t)}catch{te.warn("Could not open browser automatically. Please open the URL above manually.")}const o=ne();let s;o.start("Waiting for authentication...");try{s=await n(),o.stop(G.green("✓ Authentication successful"))}catch(e){o.stop(G.red("✗ Authentication failed"));const t=e instanceof Error?e.message:"Unknown error";re(G.red(`Login failed: ${t}`)),process.exit(1)}const i=await In(s);i.success?(await hn(i.scopedTokens),re(G.green("Setup complete! You can now use Stably CLI."))):(re(G.yellow("Setup incomplete. Run `stably login` to try again.")),process.exit(1))},xn={fatal:60,error:50,warn:40,info:30,debug:20,trace:10},Sn=new Set(["help","login","logout","whoami","tunnel","create","fix","init","upgrade","test","show-report","codegen"]),An=(new Date).toISOString().split("T")[0],Cn=r.join(R.tmpdir(),"stably-logs",An);m.mkdirSync(Cn,{recursive:!0});var Rn,Pn=process.argv.includes("--verbose")||process.argv.includes("-v"),Un=process.env.STABLY_LOG_LEVEL?.toLowerCase(),kn=Pn?"debug":void 0!==(Rn=Un)&&Rn in xn?Un:"warn",Ln=xn[kn],Dn=null,On=null,Bn=null,Nn=[],$n=!1,Mn=e=>{if(!$n){Dn=(e=>{const t=(()=>{const e=new Date;return[e.getHours().toString().padStart(2,"0"),e.getMinutes().toString().padStart(2,"0"),e.getSeconds().toString().padStart(2,"0")].join("-")})(),n=((e,t=100)=>e.replace(/[/\\:*?"<>|]/g,"-").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9\-_]/g,"").replace(/-+/g,"-").replace(/^-+|-+$/g,"").slice(0,t).toLowerCase()||"session")(e);return r.join(Cn,`${t}-${n}.log`)})(e),(e=>{const t=["","=".repeat(60),"Stably CLI Debug Log",`Version: ${Yr}`,`Generated: ${(new Date).toISOString()}`,`Node: ${process.version}`,`Platform: ${process.platform} ${R.release()}`,`CWD: ${process.cwd()}`,`Args: ${process.argv.slice(2).join(" ")}`,`Log Level (console): ${kn}`,"=".repeat(60),""].join("\n");e.write(t)})(On=new fe({dest:Dn,minLength:4096,sync:!1,append:!0})),Bn=pe({level:"debug",timestamp:pe.stdTimeFunctions.isoTime,base:{version:Yr}},On);for(const{level:e,msg:t,context:r}of Nn)r?Bn[e](r,t):Bn[e](t);Nn=[],$n=!0,Pn&&process.stderr.write(`${G.dim(`Debug log: ${Dn}`)}\n\n`)}},jn=(()=>{const e=process.argv.slice(2).find(e=>!e.startsWith("-"));return e&&Sn.has(e)?e:null})();jn&&Mn(jn);var Hn=e=>(t,r)=>{if(Bn?r?Bn[e](r,t):Bn[e](t):Nn.push({level:e,msg:t,context:r}),(e=>xn[e]>=Ln)(e)){const r=((e,t)=>`${{fatal:G.bgRed(G.white(" FATAL ")),error:G.red("error"),warn:G.yellow("warn"),info:G.cyan("info"),debug:G.dim("debug"),trace:G.dim("trace")}[e]} ${t}`)(e,t);process.stderr.write(`${r}\n`)}},Fn={fatal:Hn("fatal"),error:Hn("error"),warn:Hn("warn"),info:Hn("info"),debug:Hn("debug"),trace:Hn("trace"),initSession:e=>{$n||Mn(e)},getLogFilePath:()=>Dn,flush:()=>{if(On)try{On.flushSync()}catch{}},printLogFileInfo:()=>{Dn&&(process.stderr.write(`\n${G.dim("Debug log written to:")}\n`),process.stderr.write(` ${G.cyan(Dn)}\n`),process.stderr.write(`${G.dim("Share this file with support for assistance.")}\n`))},getPinoLogger:()=>Bn};setInterval(()=>{Fn.flush()},3e4).unref(),process.on("beforeExit",()=>{Fn.flush()});var Gn=e=>{const t=()=>{Fn.flush(),Pn&&Fn.printLogFileInfo(),process.removeListener(e,t),process.kill(process.pid,e)};return t};process.on("SIGINT",Gn("SIGINT")),process.on("SIGTERM",Gn("SIGTERM"));var Yn=()=>{const e=process.env.STABLY_API_KEY?.trim(),t=process.env.STABLY_PROJECT_ID?.trim();if(e&&t)return Fn.debug("Environment auth detected",{hasApiKey:!0,hasProjectId:!0}),{apiKey:e,projectId:t};Fn.debug("Environment auth not set",{hasApiKey:!!e,hasProjectId:!!t})},Wn=!1,Vn=()=>{Wn||(Wn=!0,te.warn("Both environment variable auth and stored OAuth login were detected."),te.warn(`Honoring environment variables (${G.cyan("STABLY_API_KEY")} + ${G.cyan("STABLY_PROJECT_ID")}).`),te.warn("To use OAuth login instead, unset those environment variables."))},zn=async()=>{Fn.debug("Checking for stored auth tokens");const e=await fn();if(!e)return void Fn.debug("No stored auth tokens found");const t=bn(e);if(Fn.debug("Auth tokens status",{expired:t}),!t){const t=await gn(),r=(e=>{try{const t=rn.parse(nn(e));if(t.org_id_to_org_member_info)return"full";if(t.org_member_info)return"org"}catch{return"unknown"}return"unknown"})(e.accessToken);if(Fn.debug("Token scope check",{scope:r,hasContext:!!t}),t&&"full"===r)try{Fn.debug("Exchanging full token for org-scoped token",{orgId:t.orgId});const r=await en(e.accessToken,t.orgId),n={accessToken:r.accessToken,expiresAt:Date.now()+1e3*r.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken};return await hn(n),Fn.debug("Token exchange successful"),n}catch(t){return Fn.debug("Token exchange failed, using existing token",{error:t instanceof Error?t.message:String(t)}),e}return e}try{Fn.debug("Attempting token refresh");const t=await wn(e.refreshToken);Fn.debug("Token refresh successful");const r=await gn();if(r)try{Fn.debug("Exchanging refreshed token for org-scoped token");const e=await en(t.accessToken,r.orgId),n={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:t.idToken,refreshToken:t.refreshToken};return await hn(n),n}catch{return await hn(t),t}return await hn(t),t}catch(e){return void Fn.warn("Token refresh failed",{error:e instanceof Error?e.message:String(e)})}},Kn=async(e={})=>{Fn.debug("Requiring authentication",{autoLogin:e.autoLogin});const t=Yn();if(t){Fn.info("Using environment variable authentication");try{await fn()&&Vn()}catch{}return{auth:t,type:"env"}}let r=await zn(),n=r?await gn():void 0;const o=process.stdin.isTTY&&process.stdout.isTTY;if(Fn.debug("OAuth auth check",{hasTokens:!!r,hasContext:!!n,canPrompt:o}),(!r||!n)&&e.autoLogin&&o){Fn.info("Prompting user to login"),r?te.info("You are logged in but need to select an organization and project."):te.info("You are not logged in."),te.info("Press Enter to log in."),process.stdout.write(`${G.dim("Alternatively, set environment variables for an org API key:")}\n${G.dim(" STABLY_API_KEY=... STABLY_PROJECT_ID=... stably")}\n`),process.stdout.write("\n");const e=ae({input:process.stdin,output:process.stdout});try{await e.question(G.dim("Press Enter to continue... "))}finally{e.close()}await Tn(),r=await zn(),n=r?await gn():void 0}return r||(Fn.warn("Authentication required but no tokens available"),re(G.red("You are not logged in. Run `stably login` to authenticate.")),process.exit(1)),n||(Fn.warn("Authentication succeeded but no project context selected"),re(G.red("You haven't selected an organization and project. Run `stably login` to complete setup.")),process.exit(1)),Fn.info("OAuth authentication successful",{orgId:n.orgId,projectId:n.projectId}),{auth:{accessToken:r.accessToken,context:n},type:"oauth"}},qn=e=>"env"===e.type?e.auth.projectId:e.auth.context.projectId,Jn=e=>e?{...process.env,...e}:process.env,Xn=async()=>{Fn.info("[test] Resolving Stably test env");const e=(()=>{if(process.env.STABLY_WS_URL)return;if("https://api.stably.ai"===Wr)return;const e=Wr.startsWith("http://")?"ws://":"wss://";return`${Wr.replace(/^https?:\/\//,e).replace(/\/$/,"")}/reporter`})();Fn.debug("[test] WebSocket URL resolved",{wsUrl:e??"(default)"});const t=Yn();if(t)return Fn.info("[test] Using env var auth (STABLY_API_KEY + STABLY_PROJECT_ID)"),{STABLY_API_KEY:t.apiKey,STABLY_PROJECT_ID:t.projectId,...e&&{STABLY_WS_URL:e}};Fn.info("[test] No env var auth, attempting OAuth auth");const r=Date.now(),n=await(async()=>{const e=Yn();if(e){try{await fn()&&Vn()}catch{}return{auth:e,type:"env"}}const t=await zn(),r=t?await gn():void 0;if(t&&r)return{auth:{accessToken:t.accessToken,context:r},type:"oauth"}})();if(Fn.info("[test] OAuth auth resolved",{durationMs:Date.now()-r,hasAuth:!!n,authType:n?.type}),!n||"env"===n.type)return void Fn.info("[test] No usable auth found");const o=process.env.STABLY_PROJECT_ID?.trim(),s=o||qn(n);if(!s)return void Fn.warn("[test] No project ID available");Fn.info("[test] Fetching JWT API key",{projectId:s});const i=Date.now(),a=await(async(e,t)=>{try{Fn.debug("Requesting JWT API key",{projectId:t,apiUrl:Wr});const r=await(async({accessToken:e,projectId:t})=>{const r=await(n={auth:e,client:Zr(),path:{projectId:t}},(n.client??Gr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/api-key",...n}));var n;if(r.error){const e=r.error?.error,{status:t}=r.response;throw new Error(e??`Failed to get API key: ${t}`)}return r.data})({accessToken:e,projectId:t});return Fn.debug("JWT API key obtained",{keyPrefix:r.apiKey.substring(0,10)}),r.apiKey}catch(e){return void Fn.warn("Failed to get JWT API key for test reporter",{error:e instanceof Error?e.message:String(e)})}})(n.auth.accessToken,s);Fn.info("[test] JWT API key fetch complete",{durationMs:Date.now()-i,success:!!a});const c=a?{STABLY_API_KEY:a,STABLY_PROJECT_ID:s,...e&&{STABLY_WS_URL:e}}:void 0;return Fn.info("[test] Stably test env resolved",{hasApiKey:!!c?.STABLY_API_KEY,projectId:c?.STABLY_PROJECT_ID,wsUrl:c?.STABLY_WS_URL??process.env.STABLY_WS_URL??"(default)"}),c},Qn=e=>e?{[Ir]:e}:void 0,Zn=le.object({context:le.string().min(1),autohealReportUrl:le.string(),skippedTests:le.array(le.object({testIdentifier:le.string(),testTitle:le.string(),consecutiveUnfixedCount:le.number()})).optional()}),eo=he.object({bucket:he.string(),key:he.string()}),to=he.object({diffBucketPath:eo,expiresInSeconds:he.number(),key:he.string(),uploadUrl:he.string()}),ro=he.object({traceBucketPath:eo,expiresInSeconds:he.number(),key:he.string(),uploadUrl:he.string(),sensitiveValues:he.array(he.string())}),no=async({authHeader:e,contentType:t="text/plain",orgId:r,runId:n})=>{const o=await(s={auth:e,body:{contentType:t},client:Zr(),headers:Qn(r),path:{runId:n}},(s.client??Gr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-diff/upload-url",...s,headers:{"Content-Type":"application/json",...s.headers}}));var s;if(o.error)throw new Error(`Failed to presign diff upload (${o.response.status})`);const i=to.parse(o.data);return{diffBucketPath:i.diffBucketPath,expiresInSeconds:i.expiresInSeconds,key:i.key,uploadUrl:i.uploadUrl}},oo=async({contentType:e="text/plain",diff:t,uploadUrl:r})=>{const n=await fetch(r,{body:t,headers:{"Content-Type":e},method:"PUT"});if(!n.ok)throw new Error(`Failed to upload diff (${n.status})`)},so=async({authHeader:e,diffBucketPath:t,orgId:r,runId:n})=>{const o=(Zr().getConfig().baseUrl??"").replace(/\/$/,""),s=await fetch(`${o}/internal/v1/cli/runs/${encodeURIComponent(n)}/autoheal-diff/confirm-upload`,{method:"POST",headers:{"Content-Type":"application/json",...Qn(r),authorization:e},body:JSON.stringify(t)});if(!s.ok)throw new Error(`Failed to confirm diff upload (${s.status})`)},io=class{socket;url;authHeader;orgId;runId;pendingEvent=null;reconnectAttempts=0;reconnectTimer;debounceTimer;_isClosed=!1;isAuthenticated=!1;authenticationFailed=!1;onUserMessage;maxReconnectAttempts=3;reconnectDelay=2e3;debounceMs=500;get isClosed(){return this._isClosed}constructor({authHeader:e,orgId:t,runId:r,url:n=Jr,onUserMessage:o}){this.authHeader=e,this.orgId=t,this.runId=r,this.url=n,this.onUserMessage=o,Fn.info("[ws] Constructing AutohealWebSocketClient",{url:this.url,runId:r})}start(){this.connect()}connect(){if(!this._isClosed)try{const e={Authorization:this.authHeader};this.orgId&&(e["x-stably-org-id"]=this.orgId);const t=`${this.url}?runId=${encodeURIComponent(this.runId)}`;Fn.info("[ws] Connecting",{url:t,attempt:this.reconnectAttempts}),this.socket=new me(t,{headers:e}),this.socket.on("open",()=>{Fn.info("[ws] Connection opened"),this.reconnectAttempts=0}),this.socket.on("message",e=>{try{const t="string"==typeof e?e:e.toString(),r=JSON.parse(t);Fn.debug("[ws] Received message",{type:r?.type}),"connected"===r?.type&&(Fn.info("[ws] Authenticated successfully"),this.isAuthenticated=!0,this.authenticationFailed=!1,this.flushPending()),"user_message"===r?.type&&"string"==typeof r.content&&(Fn.info("[ws] Received user message from web UI"),this.onUserMessage?.(r.content))}catch{}}),this.socket.on("close",(e,t)=>{Fn.info("[ws] Connection closed",{code:e,authFailed:1008===e,reconnectAttempts:this.reconnectAttempts,maxReconnect:this.maxReconnectAttempts,isClosed:this._isClosed}),this.isAuthenticated=!1,1008===e&&(this.authenticationFailed=!0),!this._isClosed&&!this.authenticationFailed&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()}),this.socket.on("error",e=>{Fn.warn("[ws] Connection error",{error:e.message})})}catch(e){Fn.warn("[ws] Failed to create WebSocket",{error:e instanceof Error?e.message:String(e)}),this.scheduleReconnect()}}scheduleReconnect(){this._isClosed||this.reconnectTimer||(this.reconnectAttempts++,Fn.info("[ws] Scheduling reconnect",{attempt:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts,delayMs:this.reconnectDelay}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect()},this.reconnectDelay))}isConnected(){return!!this.socket&&this.socket.readyState===me.OPEN&&this.isAuthenticated}sendProgress(e){if(this._isClosed)return void Fn.debug("[ws] sendProgress called but client is closed",{phase:e.phase});const t={type:"autoheal_progress",payload:e};return this.pendingEvent=t,this.isConnected()?"complete"===e.phase?(Fn.info("[ws] sendProgress: flushing terminal state immediately"),void this.flushPending()):void(this.debounceTimer||(this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.flushPending()},this.debounceMs))):(Fn.debug("[ws] sendProgress: not connected, queuing event",{phase:e.phase,socketState:this.socket?.readyState,isAuthenticated:this.isAuthenticated,reconnectAttempts:this.reconnectAttempts}),void(this.socket?.readyState===me.CLOSED&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()))}flushPending(){if(this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),!this.pendingEvent)return;const e=this.pendingEvent;if(this.pendingEvent=null,!this.isConnected())return Fn.debug("[ws] flushPending: not connected, re-queuing event",{phase:e.payload.phase}),void(this.pendingEvent=e);try{Fn.debug("[ws] flushPending: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),t=>{t&&(Fn.warn("[ws] flushPending: send failed",{error:t.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e))})}catch(t){Fn.warn("[ws] flushPending: send threw",{error:t instanceof Error?t.message:String(t)}),this.pendingEvent=e}}close(){if(this._isClosed)return;Fn.info("[ws] Closing WebSocket client"),this._isClosed=!0,this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.flushPending();const{socket:e}=this;this.socket=void 0,e&&setTimeout(()=>{e.close()},200)}},ao=class{socket;url;authHeader;orgId;sessionId;pendingEvent=null;reconnectAttempts=0;reconnectTimer;debounceTimer;_isClosed=!1;isAuthenticated=!1;authenticationFailed=!1;onUserMessage;maxReconnectAttempts=3;reconnectDelay=2e3;debounceMs=500;get isClosed(){return this._isClosed}constructor({authHeader:e,orgId:t,sessionId:r,url:n=Xr,onUserMessage:o}){this.authHeader=e,this.orgId=t,this.sessionId=r,this.url=n,this.onUserMessage=o,Fn.info("[ws] Constructing CreateProgressWebSocketClient",{url:this.url,sessionId:r})}start(){this.connect()}connect(){if(!this._isClosed)try{const e={Authorization:this.authHeader};this.orgId&&(e["x-stably-org-id"]=this.orgId);const t=`${this.url}?sessionId=${encodeURIComponent(this.sessionId)}`;Fn.info("[ws] Connecting",{url:t,attempt:this.reconnectAttempts}),this.socket=new me(t,{headers:e}),this.socket.on("open",()=>{Fn.info("[ws] Connection opened"),this.reconnectAttempts=0}),this.socket.on("message",e=>{try{const t="string"==typeof e?e:e.toString(),r=JSON.parse(t);Fn.debug("[ws] Received message",{type:r?.type}),"connected"===r?.type&&(Fn.info("[ws] Authenticated successfully"),this.isAuthenticated=!0,this.authenticationFailed=!1,this.flushPending()),"user_message"===r?.type&&"string"==typeof r.content&&(Fn.info("[ws] Received user message from web UI"),this.onUserMessage?.(r.content))}catch{}}),this.socket.on("close",(e,t)=>{Fn.info("[ws] Connection closed",{code:e,authFailed:1008===e,reconnectAttempts:this.reconnectAttempts,maxReconnect:this.maxReconnectAttempts,isClosed:this._isClosed}),this.isAuthenticated=!1,1008===e&&(this.authenticationFailed=!0),!this._isClosed&&!this.authenticationFailed&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()}),this.socket.on("error",e=>{Fn.warn("[ws] Connection error",{error:e.message})})}catch(e){Fn.warn("[ws] Failed to create WebSocket",{error:e instanceof Error?e.message:String(e)}),this.scheduleReconnect()}}scheduleReconnect(){this._isClosed||this.reconnectTimer||(this.reconnectAttempts++,Fn.info("[ws] Scheduling reconnect",{attempt:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts,delayMs:this.reconnectDelay}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect()},this.reconnectDelay))}isConnected(){return!!this.socket&&this.socket.readyState===me.OPEN&&this.isAuthenticated}sendProgress(e){if(this._isClosed)return void Fn.debug("[ws] sendProgress called but client is closed",{phase:e.phase});const t={type:"create_progress",payload:e};return this.pendingEvent=t,this.isConnected()?"complete"===e.phase?(Fn.info("[ws] sendProgress: flushing terminal state immediately"),void this.flushPending()):void(this.debounceTimer||(this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.flushPending()},this.debounceMs))):(Fn.debug("[ws] sendProgress: not connected, queuing event",{phase:e.phase,socketState:this.socket?.readyState,isAuthenticated:this.isAuthenticated,reconnectAttempts:this.reconnectAttempts}),void(this.socket?.readyState===me.CLOSED&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()))}flushPending(){if(this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),!this.pendingEvent)return;const e=this.pendingEvent;if(this.pendingEvent=null,!this.isConnected())return Fn.debug("[ws] flushPending: not connected, re-queuing event",{phase:e.payload.phase}),void(this.pendingEvent=e);try{Fn.debug("[ws] flushPending: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),t=>{t&&(Fn.warn("[ws] flushPending: send failed",{error:t.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e))})}catch(t){Fn.warn("[ws] flushPending: send threw",{error:t instanceof Error?t.message:String(t)}),this.pendingEvent=e}}close(){if(this._isClosed)return;Fn.info("[ws] Closing WebSocket client"),this._isClosed=!0,this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.flushPending();const{socket:e}=this;this.socket=void 0,e&&setTimeout(()=>{e.close()},200)}},co=/\.(spec|test)\.(c|m)?[jt]sx?$/,lo=e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"text"===t.type&&"string"==typeof t.text},uo=e=>null!=e&&"object"==typeof e&&"tool_response"in e,po=e=>{if(!e||"object"!=typeof e)return;const t=e;return Array.isArray(t.tool_response)?t.tool_response:void 0},fo=e=>{const t=po(e);if(t)return t.filter(lo).map(e=>e.text).join("\n")||void 0},ho=/\u001b\[[0-9;]*m/g,mo=e=>e.replace(ho,""),go=/\$\{process\.env\.([A-Z_][A-Z0-9_]*)\}/g;function yo({envVars:e}){return async t=>{if(!function(e){return Boolean(e&&"object"==typeof e&&"tool_input"in e&&e.tool_input&&"object"==typeof e.tool_input)}(t))return{decision:"approve"};const r=t.tool_input,n="string"==typeof r.text?r.text:void 0;if(!n)return{decision:"approve"};const o=n.replace(go,(t,r)=>{const n=e[r];return null!=n?n:t});return o===n?{decision:"approve"}:{decision:"approve",hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",reason:"Evaluated environment variable placeholders in browser text input.",updatedInput:{...r,text:o}}}}}function bo({onResult:e}){return async t=>{if(!uo(t))return{decision:"approve"};const r=fo(t);if(!r)return{decision:"approve"};const n=function(e){const t=mo(e),r=t.split(/Running \d+ tests? using \d+ workers?/).at(-1)??t,n=parseInt(r.match(/(\d+)\s+passed/g)?.at(-1)?.match(/(\d+)/)?.[1]??"0"),o=parseInt(r.match(/(\d+)\s+failed/g)?.at(-1)?.match(/(\d+)/)?.[1]??"0");if(0===n&&0===o)return;const s=[n>0?`${n} test${1===n?"":"s"} passed ✓`:void 0,o>0?`${o} test${1===o?"":"s"} failed ✗`:void 0].filter(e=>void 0!==e).join(", ");if(0===o)return s;const i=r.split(/\n\s+\d+\)\s+\[id=/).slice(1).map(e=>e.match(/\n\s{4}((?:TimeoutError|Error|AssertionError):\s*[^\n]+)/)?.[1]?.trim()).filter(e=>void 0!==e);return 0===i.length?s:`${s}\n${i.map(e=>` - ${e}`).join("\n")}`}(r);return n&&e(n),{decision:"approve"}}}function wo({onResult:e}){return async t=>{if(!uo(t))return{decision:"approve"};const r=fo(t);if(!r)return{decision:"approve"};const n=function(e){const t=mo(e);if(t.match(/### Paused on error:/)){const e=t.match(/### Paused on error:\s*\n((?:TimeoutError|Error|AssertionError):\s*[^\n]+)/);return e?`Test paused on error - ${e[1].trim()}`:"Test paused on error"}const r=t.match(/(\d+)\s+passed/);if(r){const e=parseInt(r[1]);return`${e} test${1===e?"":"s"} passed ✓`}}(r);return n&&e(n),{decision:"approve"}}}var vo=/\.(spec|test)\.(ts|tsx|js|jsx|mts|mjs)$/;function _o({onFileCreated:e}){return async t=>{const r=(e=>{if(!e||"object"!=typeof e)return;const t=e;return t.tool_input&&"object"==typeof t.tool_input&&!Array.isArray(t.tool_input)?t.tool_input:void 0})(t),n=r?.file_path;return"string"==typeof n&&vo.test(n)&&e(n),{decision:"approve"}}}var Eo=D(d);async function Io(){try{const{stdout:e}=await Eo('pgrep -f "playwright run-test-mcp-server" 2>/dev/null || true'),t=e.trim();if(!t)return;const r=t.split("\n").filter(Boolean);await Promise.allSettled(r.map(async e=>{await Eo(`pkill -KILL -P ${e} '.*' 2>/dev/null || true`)}))}catch{}}var To="sha256",xo=/^---\r?\n([\s\S]*?)\r?\n---/;function So(e){const t=e.replace(xo,"").replace(/^(\r?\n)+/,""),r=H.createHash(To).update(t,"utf8").digest("hex");return`${To}:${r}`}function Ao(e){const t=e.match(/^\/\*\*[\s\S]*?@prompt-hash\s+(sha256:[a-f0-9]{64})[\s\S]*?\*\//);return t?.[1]}function Co({builtAt:e=new Date,promptFile:t,promptHash:r}){const n=Array.isArray(t)?t:[t],o=n[0]??"unknown",s=e.toISOString();return["/**"," * @generated by stably build",` * @prompt-hash ${r}`,...n.map(e=>` * @prompt-file ${e}`),` * @built-at ${s}`," *",` * DO NOT EDIT MANUALLY - regenerate with: stably build ${o} --force`," */"].join("\n")}function Ro({workDir:e}){return async t=>{if(null==(r=t)||"object"!=typeof r||!("file_path"in r)||"string"!=typeof r.file_path)return{};var r;const o=t.file_path;if(!/\.(spec|test)\.[jt]sx?$/.test(o))return{};const s=n(e,o);if(!s.startsWith(n(e)+i))return console.error(`[PromptHash Hook] Path traversal attempt blocked: ${o}`),{};let a;try{a=await V(s,"utf-8")}catch(e){return console.error(`[PromptHash Hook] Error reading ${o}:`,e),{}}const c=function(e){const t=e.match(/\/\/\s*@stably\.spec\s+(\S+)/);return t?.[1]}(a);if(!c)return{};const l=n(e,c);if(!l.startsWith(n(e)+i))return console.error(`[PromptHash Hook] Path traversal attempt blocked: ${c}`),{};let u;try{u=await V(l,"utf-8")}catch{return{}}const d=So(u);if(Ao(a)===d)return{};const p=Co({promptHash:d,promptFile:c});let f;const h=a.match(/\/\*\*[\s\S]*?@prompt-hash[\s\S]*?\*\/\n?/);f=h?a.replace(h[0],`${p}\n`):`${p}\n${a}`;try{await K(s,f,"utf-8")}catch(e){console.error(`[PromptHash Hook] Error writing ${o}:`,e)}return{}}}var Po=class{queue=[];pendingResolve=void 0;done=!1;canSend=!0;[Symbol.asyncIterator](){return this}pushText(e){const t=e.trim();t&&!this.done&&(this.queue.push(t),this.maybeFlush())}allowNextTurn(){this.done||(this.canSend=!0,this.maybeFlush())}hasQueuedMessages(){return this.queue.length>0}finish(){this.done=!0,this.pendingResolve&&(this.pendingResolve({done:!0,value:void 0}),this.pendingResolve=void 0)}maybeFlush(){if(!this.pendingResolve)return;if(!this.canSend)return;const e=this.queue.shift();if(void 0===e)return;const t={message:{content:[{text:e,type:"text"}],role:"user"},parent_tool_use_id:null,type:"user",session_id:""};this.canSend=!1,this.pendingResolve({done:!1,value:t}),this.pendingResolve=void 0}next(){return this.done?Promise.resolve({done:!0,value:void 0}):new Promise(e=>{this.pendingResolve=e,this.maybeFlush()})}};function Uo(e){try{const t=p("git branch --show-current",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(!t)return;return{branch:t}}catch{return}}var ko=[".ts",".js",".mts",".mjs",".cts",".cjs"],Lo=10240,Do=async({defaultContent:e,fileName:t,filePath:r})=>{try{const e=(await Q(r)).size,n=await V(r,"utf-8"),o=Buffer.byteLength(n,"utf-8");if(o<=Lo)return n;const s=(e=>{const t=e.split("\n"),r=[];let n=!1,o=!1,s=0,i=!1;for(let e=0;e<t.length;e++){const a=t[e],c=a.trim();c.startsWith("/*")&&(n=!0),c.includes("*/")?n=!1:n||c.startsWith("//")&&!c.startsWith("///")||(c.startsWith("import ")||c.startsWith("export ")?(r.push(a),i=!0):i&&""===c?(r.push(a),i=!1):(i=!1,c.startsWith("type ")||c.startsWith("interface ")?r.push(a):c.startsWith("function ")||c.startsWith("const ")||c.startsWith("async function ")||c.startsWith("export function ")||c.startsWith("export const ")||c.startsWith("test.describe(")||c.startsWith("test(")?(r.push(a),o=!0,s=(a.match(/{/g)||[]).length-(a.match(/}/g)||[]).length,0===s&&(c.endsWith(";")||c.endsWith(","))&&(o=!1)):o?(s+=(a.match(/{/g)||[]).length,s-=(a.match(/}/g)||[]).length,0===s&&c.includes("}")?(r.push(a),o=!1):s>0&&" // ... implementation omitted ..."!==r.at(-1)&&r.push(" // ... implementation omitted ...")):c.match(/^[a-zA-Z_]+:/)&&r.push(a)))}return r.join("\n")})(n),i=Buffer.byteLength(s,"utf-8");return i<=Lo?s:s.slice(0,Lo)+`\n\n... [TRUNCATED: File "${t}" at ${r} was ${e} bytes (${o} bytes as UTF-8), reduced to ~${i} bytes of essential content, then truncated to 10240 bytes] ...`}catch(r){let n;if(r&&"object"==typeof r&&"code"in r){const e=r.code;"string"==typeof e&&(n=e)}return"ENOENT"!==n&&console.warn(`Failed to read ${t}: ${r}`),e}},Oo=async({defaultContent:e,dirName:t,dirPath:r})=>{try{const e=await X(r);return e.length>0?e.join("\n"):"(empty)"}catch(r){let n;if(r&&"object"==typeof r&&"code"in r){const e=r.code;"string"==typeof e&&(n=e)}return"ENOENT"!==n&&console.warn(`Failed to read ${t}: ${r}`),e}},Bo=async({allowedEnvVars:e,mode:t,workspaceInfo:r,authHeader:n,customHeader:o,maxParallelWorkers:s})=>{const i=Zr(),a=Uo(r.absolutePath);Fn.debug("Requesting system prompt from API",{mode:t,hasGitContext:!!a,envVarCount:e.length});const c=await(l={client:i,auth:n,body:{mode:t,workspaceInfo:r,allowedEnvVars:e,gitContext:a,maxParallelWorkers:s}},(l.client??Gr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/prompts/system",...l,headers:{"Content-Type":"application/json",...l.headers}}));var l;if(401===c.response.status)throw Fn.warn("System prompt fetch failed: unauthorized (401)"),await mn(),new Error("Your session has expired or been revoked. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(403===c.response.status)throw Fn.warn("System prompt fetch failed: forbidden (403)"),await mn(),new Error("You no longer have access to this organization. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(c.error)throw Fn.warn("System prompt fetch failed",{error:c.error}),new Error(`Failed to fetch system prompt: ${JSON.stringify(c.error)}`);const u=function({customHeader:e,systemPrompt:t}){return e?`${t}\n\nWhen writing or updating the generated test file, prepend this exact header at the top of the file without modification:\n\`\`\`ts\n${e}\n\`\`\``:t}({systemPrompt:c.data.systemPrompt,customHeader:o});return Fn.debug("System prompt received",{size:u.length,appendedCustomHeader:!!o,hasPrContext:!!c.data.prContext}),{systemPrompt:u,prContext:c.data.prContext}},No=".stably-playwright-wrapper.config.*",$o=[".ts",".js",".mts",".mjs",".cts",".cjs"];function Mo(e){const t=n(e);if(g(t))for(const e of $o){const r=s(t,`playwright.config${e}`);if(g(r))return r}}var jo=["tests","e2e","__tests__","test"];function Ho(e){try{return g(e)&&y(e).isDirectory()}catch{return!1}}function Fo(e,t){const r="output-flag"===t?"--output flag":"playwright.config.ts"===t?"playwright.config.ts":"auto-detected"===t?"auto-detected":"cwd fallback";console.error(G.dim(`Using output directory: ${e} (from ${r})`))}var Go,Yo=["mcp__playwright-test__","mcp__auto-heal-report__","mcp__test-doc-sync__","mcp__stably-agent-control__"],Wo=["planner_","generator_"],Vo={"mcp__stably-agent-control__restart_mcp_servers":"Restarting Browser Tools","mcp__session-control__restart_mcp_servers":"Restarting Browser Tools"},zo=(e,t)=>{const r=t.find(t=>e.startsWith(t));return r?e.slice(r.length):e},Ko=(e,t)=>{if(!t||"object"!=typeof t)return;const r=t,n="string"==typeof r.intent?r.intent:void 0;if("Read"!==e&&"Write"!==e&&"Edit"!==e){if("Glob"===e||"Grep"===e)return"string"==typeof r.pattern?r.pattern:void 0;if("mcp__playwright-test__test_run"!==e&&"test_run"!==e){if("mcp__playwright-test__test_debug"===e||"test_debug"===e){const e=r.test;return"string"==typeof e?.title?e.title:void 0}return"mcp__playwright-test__generator_setup_page"===e||"generator_setup_page"===e?"string"==typeof r.seedFile?r.seedFile:"tests/seed.spec.ts":"mcp__playwright-test__generator_write_test"===e||"generator_write_test"===e?"string"==typeof r.fileName?r.fileName:void 0:"Bash"===e?"string"==typeof r.command?r.command.length>50?`${r.command.slice(0,50)}...`:r.command:void 0:e.includes("browser_navigate")&&!e.includes("back")?"string"==typeof r.url?r.url:n:e.includes("browser_type")?("string"==typeof r.text?`"${r.text}"`:void 0)??n:e.includes("browser_click")?"string"==typeof r.element?r.element:n:e.includes("browser_wait_for")?"string"==typeof r.text?`text: "${r.text}"`:"number"==typeof r.time?`${r.time}ms`:n:e.includes("verify_text")?"string"==typeof r.text?`"${r.text}"`:n:e.includes("verify_element")?"string"==typeof r.accessibleName?r.accessibleName:n:e.includes("screenshot")&&"string"==typeof r.filename?r.filename:n}if(Array.isArray(r.locations)){const e=r.locations.filter(e=>"string"==typeof e);return e.length>0?e.join(", "):void 0}}else if("string"==typeof r.file_path)return r.file_path.split("/").at(-1)??void 0},qo=e=>"mcp__auto-heal-report__capture-trace-proof"===e?"Verify Test Run":"mcp__auto-heal-report__generate-report"===e?"Generate Report":(e=>{const t=Vo[e];if(t)return t;const r=zo(e,Yo);return zo(r,Wo).split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")})(e),Jo=["test","bug","flake","ui_change","other"],Xo={bug:"Application code defect; behavior diverges from expected requirements.",flake:"Non-deterministic failure; timing, race conditions, or environmental variance causes inconsistent test results.",other:"External dependencies, environment, or infra issues outside test/app code.",test:"Test code is incorrect, out-of-date, or missing necessary setup.",ui_change:"Application UI intentionally changed; test expectations (screenshots, selectors, text assertions) are stale and need updating."},Qo=e=>Xo[e],Zo=/[^a-zA-Z0-9-_]/g,es=e=>{const t=e.trim().replace(Zo,"_");return t.length>0?t.slice(0,80):void 0},ts=e=>"string"==typeof e?es(e):void 0,rs=Ie("/");try{Go=rs("worker_threads").Worker}catch(e){}var ns=Go?function(e,t,r,n,o){var s=!1,i=new Go(e+";var __w=require('worker_threads');__w.parentPort.on('message',function(m){onmessage({data:m})}),postMessage=function(m,t){__w.parentPort.postMessage(m,t)},close=process.exit;self=global",{eval:!0}).on("error",function(e){return o(e,null)}).on("message",function(e){return o(null,e)}).on("exit",function(e){e&&!s&&o(new Error("exited with code "+e),null)});return i.postMessage(r,n),i.terminate=function(){return s=!0,Go.prototype.terminate.call(i)},i}:function(e,t,r,n,o){setImmediate(function(){return o(new Error("async operations unsupported - update to Node 12+ (or Node 10-11 with the --experimental-worker CLI flag)"),null)});var s=function(){};return{terminate:s,postMessage:s}},os=Uint8Array,ss=Uint16Array,is=Int32Array,as=new os([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),cs=new os([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),ls=new os([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),us=function(e,t){for(var r=new ss(31),n=0;n<31;++n)r[n]=t+=1<<e[n-1];var o=new is(r[30]);for(n=1;n<30;++n)for(var s=r[n];s<r[n+1];++s)o[s]=s-r[n]<<5|n;return{b:r,r:o}},ds=us(as,2),ps=ds.b,fs=ds.r;ps[28]=258,fs[258]=28;var hs,ms=us(cs,0),gs=ms.b,ys=ms.r,bs=new ss(32768);for(_s=0;_s<32768;++_s)hs=(61680&(hs=(52428&(hs=(43690&_s)>>1|(21845&_s)<<1))>>2|(13107&hs)<<2))>>4|(3855&hs)<<4,bs[_s]=((65280&hs)>>8|(255&hs)<<8)>>1;var ws=function(e,t,r){for(var n=e.length,o=0,s=new ss(t);o<n;++o)e[o]&&++s[e[o]-1];var i,a=new ss(t);for(o=1;o<t;++o)a[o]=a[o-1]+s[o-1]<<1;if(r){i=new ss(1<<t);var c=15-t;for(o=0;o<n;++o)if(e[o])for(var l=o<<4|e[o],u=t-e[o],d=a[e[o]-1]++<<u,p=d|(1<<u)-1;d<=p;++d)i[bs[d]>>c]=l}else for(i=new ss(n),o=0;o<n;++o)e[o]&&(i[o]=bs[a[e[o]-1]++]>>15-e[o]);return i},vs=new os(288);for(_s=0;_s<144;++_s)vs[_s]=8;for(_s=144;_s<256;++_s)vs[_s]=9;for(_s=256;_s<280;++_s)vs[_s]=7;for(_s=280;_s<288;++_s)vs[_s]=8;var _s,Es=new os(32);for(_s=0;_s<32;++_s)Es[_s]=5;var Is=ws(vs,9,0),Ts=ws(vs,9,1),xs=ws(Es,5,0),Ss=ws(Es,5,1),As=function(e){for(var t=e[0],r=1;r<e.length;++r)e[r]>t&&(t=e[r]);return t},Cs=function(e,t,r){var n=t/8|0;return(e[n]|e[n+1]<<8)>>(7&t)&r},Rs=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(7&t)},Ps=function(e){return(e+7)/8|0},Us=function(e,t,r){return(null==t||t<0)&&(t=0),(null==r||r>e.length)&&(r=e.length),new os(e.subarray(t,r))},ks=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Ls=function(e,t,r){var n=new Error(t||ks[e]);if(n.code=e,Error.captureStackTrace&&Error.captureStackTrace(n,Ls),!r)throw n;return n},Ds=function(e,t,r,n){var o=e.length,s=n?n.length:0;if(!o||t.f&&!t.l)return r||new os(0);var i=!r,a=i||2!=t.i,c=t.i;i&&(r=new os(3*o));var l=function(e){var t=r.length;if(e>t){var n=new os(Math.max(2*t,e));n.set(r),r=n}},u=t.f||0,d=t.p||0,p=t.b||0,f=t.l,h=t.d,m=t.m,g=t.n,y=8*o;do{if(!f){u=Cs(e,d,1);var b=Cs(e,d+1,3);if(d+=3,!b){var w=e[(P=Ps(d)+4)-4]|e[P-3]<<8,v=P+w;if(v>o){c&&Ls(0);break}a&&l(p+w),r.set(e.subarray(P,v),p),t.b=p+=w,t.p=d=8*v,t.f=u;continue}if(1==b)f=Ts,h=Ss,m=9,g=5;else if(2==b){var _=Cs(e,d,31)+257,E=Cs(e,d+10,15)+4,I=_+Cs(e,d+5,31)+1;d+=14;for(var T=new os(I),x=new os(19),S=0;S<E;++S)x[ls[S]]=Cs(e,d+3*S,7);d+=3*E;var A=As(x),C=(1<<A)-1,R=ws(x,A,1);for(S=0;S<I;){var P,U=R[Cs(e,d,C)];if(d+=15&U,(P=U>>4)<16)T[S++]=P;else{var k=0,L=0;for(16==P?(L=3+Cs(e,d,3),d+=2,k=T[S-1]):17==P?(L=3+Cs(e,d,7),d+=3):18==P&&(L=11+Cs(e,d,127),d+=7);L--;)T[S++]=k}}var D=T.subarray(0,_),O=T.subarray(_);m=As(D),g=As(O),f=ws(D,m,1),h=ws(O,g,1)}else Ls(1);if(d>y){c&&Ls(0);break}}a&&l(p+131072);for(var B=(1<<m)-1,N=(1<<g)-1,$=d;;$=d){var M=(k=f[Rs(e,d)&B])>>4;if((d+=15&k)>y){c&&Ls(0);break}if(k||Ls(2),M<256)r[p++]=M;else{if(256==M){$=d,f=null;break}var j=M-254;if(M>264){var H=as[S=M-257];j=Cs(e,d,(1<<H)-1)+ps[S],d+=H}var F=h[Rs(e,d)&N],G=F>>4;if(F||Ls(3),d+=15&F,O=gs[G],G>3&&(H=cs[G],O+=Rs(e,d)&(1<<H)-1,d+=H),d>y){c&&Ls(0);break}a&&l(p+131072);var Y=p+j;if(p<O){var W=s-O,V=Math.min(O,Y);for(W+p<0&&Ls(3);p<V;++p)r[p]=n[W+p]}for(;p<Y;++p)r[p]=r[p-O]}}t.l=f,t.p=$,t.b=p,t.f=u,f&&(u=1,t.m=m,t.d=h,t.n=g)}while(!u);return p!=r.length&&i?Us(r,0,p):r.subarray(0,p)},Os=function(e,t,r){r<<=7&t;var n=t/8|0;e[n]|=r,e[n+1]|=r>>8},Bs=function(e,t,r){r<<=7&t;var n=t/8|0;e[n]|=r,e[n+1]|=r>>8,e[n+2]|=r>>16},Ns=function(e,t){for(var r=[],n=0;n<e.length;++n)e[n]&&r.push({s:n,f:e[n]});var o=r.length,s=r.slice();if(!o)return{t:Ys,l:0};if(1==o){var i=new os(r[0].s+1);return i[r[0].s]=1,{t:i,l:1}}r.sort(function(e,t){return e.f-t.f}),r.push({s:-1,f:25001});var a=r[0],c=r[1],l=0,u=1,d=2;for(r[0]={s:-1,f:a.f+c.f,l:a,r:c};u!=o-1;)a=r[r[l].f<r[d].f?l++:d++],c=r[l!=u&&r[l].f<r[d].f?l++:d++],r[u++]={s:-1,f:a.f+c.f,l:a,r:c};var p=s[0].s;for(n=1;n<o;++n)s[n].s>p&&(p=s[n].s);var f=new ss(p+1),h=$s(r[u-1],f,0);if(h>t){n=0;var m=0,g=h-t,y=1<<g;for(s.sort(function(e,t){return f[t.s]-f[e.s]||e.f-t.f});n<o;++n){var b=s[n].s;if(!(f[b]>t))break;m+=y-(1<<h-f[b]),f[b]=t}for(m>>=g;m>0;){var w=s[n].s;f[w]<t?m-=1<<t-f[w]++-1:++n}for(;n>=0&&m;--n){var v=s[n].s;f[v]==t&&(--f[v],++m)}h=t}return{t:new os(f),l:h}},$s=function(e,t,r){return-1==e.s?Math.max($s(e.l,t,r+1),$s(e.r,t,r+1)):t[e.s]=r},Ms=function(e){for(var t=e.length;t&&!e[--t];);for(var r=new ss(++t),n=0,o=e[0],s=1,i=function(e){r[n++]=e},a=1;a<=t;++a)if(e[a]==o&&a!=t)++s;else{if(!o&&s>2){for(;s>138;s-=138)i(32754);s>2&&(i(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(i(o),--s;s>6;s-=6)i(8304);s>2&&(i(s-3<<5|8208),s=0)}for(;s--;)i(o);s=1,o=e[a]}return{c:r.subarray(0,n),n:t}},js=function(e,t){for(var r=0,n=0;n<t.length;++n)r+=e[n]*t[n];return r},Hs=function(e,t,r){var n=r.length,o=Ps(t+2);e[o]=255&n,e[o+1]=n>>8,e[o+2]=255^e[o],e[o+3]=255^e[o+1];for(var s=0;s<n;++s)e[o+s+4]=r[s];return 8*(o+4+n)},Fs=function(e,t,r,n,o,s,i,a,c,l,u){Os(t,u++,r),++o[256];for(var d=Ns(o,15),p=d.t,f=d.l,h=Ns(s,15),m=h.t,g=h.l,y=Ms(p),b=y.c,w=y.n,v=Ms(m),_=v.c,E=v.n,I=new ss(19),T=0;T<b.length;++T)++I[31&b[T]];for(T=0;T<_.length;++T)++I[31&_[T]];for(var x=Ns(I,7),S=x.t,A=x.l,C=19;C>4&&!S[ls[C-1]];--C);var R,P,U,k,L=l+5<<3,D=js(o,vs)+js(s,Es)+i,O=js(o,p)+js(s,m)+i+14+3*C+js(I,S)+2*I[16]+3*I[17]+7*I[18];if(c>=0&&L<=D&&L<=O)return Hs(t,u,e.subarray(c,c+l));if(Os(t,u,1+(O<D)),u+=2,O<D){R=ws(p,f,0),P=p,U=ws(m,g,0),k=m;var B=ws(S,A,0);for(Os(t,u,w-257),Os(t,u+5,E-1),Os(t,u+10,C-4),u+=14,T=0;T<C;++T)Os(t,u+3*T,S[ls[T]]);u+=3*C;for(var N=[b,_],$=0;$<2;++$){var M=N[$];for(T=0;T<M.length;++T){var j=31&M[T];Os(t,u,B[j]),u+=S[j],j>15&&(Os(t,u,M[T]>>5&127),u+=M[T]>>12)}}}else R=Is,P=vs,U=xs,k=Es;for(T=0;T<a;++T){var H=n[T];if(H>255){Bs(t,u,R[257+(j=H>>18&31)]),u+=P[j+257],j>7&&(Os(t,u,H>>23&31),u+=as[j]);var F=31&H;Bs(t,u,U[F]),u+=k[F],F>3&&(Bs(t,u,H>>5&8191),u+=cs[F])}else Bs(t,u,R[H]),u+=P[H]}return Bs(t,u,R[256]),u+P[256]},Gs=new is([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Ys=new os(0),Ws=function(e,t,r,n,o,s){var i=s.z||e.length,a=new os(n+i+5*(1+Math.ceil(i/7e3))+o),c=a.subarray(n,a.length-o),l=s.l,u=7&(s.r||0);if(t){u&&(c[0]=s.r>>3);for(var d=Gs[t-1],p=d>>13,f=8191&d,h=(1<<r)-1,m=s.p||new ss(32768),g=s.h||new ss(h+1),y=Math.ceil(r/3),b=2*y,w=function(t){return(e[t]^e[t+1]<<y^e[t+2]<<b)&h},v=new is(25e3),_=new ss(288),E=new ss(32),I=0,T=0,x=s.i||0,S=0,A=s.w||0,C=0;x+2<i;++x){var R=w(x),P=32767&x,U=g[R];if(m[P]=U,g[R]=P,A<=x){var k=i-x;if((I>7e3||S>24576)&&(k>423||!l)){u=Fs(e,c,0,v,_,E,T,S,C,x-C,u),S=I=T=0,C=x;for(var L=0;L<286;++L)_[L]=0;for(L=0;L<30;++L)E[L]=0}var D=2,O=0,B=f,N=P-U&32767;if(k>2&&R==w(x-N))for(var $=Math.min(p,k)-1,M=Math.min(32767,x),j=Math.min(258,k);N<=M&&--B&&P!=U;){if(e[x+D]==e[x+D-N]){for(var H=0;H<j&&e[x+H]==e[x+H-N];++H);if(H>D){if(D=H,O=N,H>$)break;var F=Math.min(N,H-2),G=0;for(L=0;L<F;++L){var Y=x-N+L&32767,W=Y-m[Y]&32767;W>G&&(G=W,U=Y)}}}N+=(P=U)-(U=m[P])&32767}if(O){v[S++]=268435456|fs[D]<<18|ys[O];var V=31&fs[D],z=31&ys[O];T+=as[V]+cs[z],++_[257+V],++E[z],A=x+D,++I}else v[S++]=e[x],++_[e[x]]}}for(x=Math.max(x,A);x<i;++x)v[S++]=e[x],++_[e[x]];u=Fs(e,c,l,v,_,E,T,S,C,x-C,u),l||(s.r=7&u|c[u/8|0]<<3,u-=7,s.h=g,s.p=m,s.i=x,s.w=A)}else{for(x=s.w||0;x<i+l;x+=65535){var K=x+65535;K>=i&&(c[u/8|0]=l,K=i),u=Hs(c,u+1,e.subarray(x,K))}s.i=i}return Us(a,0,n+Ps(u)+o)},Vs=function(){for(var e=new Int32Array(256),t=0;t<256;++t){for(var r=t,n=9;--n;)r=(1&r&&-306674912)^r>>>1;e[t]=r}return e}(),zs=function(e,t,r,n,o){if(!o&&(o={l:1},t.dictionary)){var s=t.dictionary.subarray(-32768),i=new os(s.length+e.length);i.set(s),i.set(e,s.length),e=i,o.w=s.length}return Ws(e,null==t.level?6:t.level,null==t.mem?o.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(e.length)))):20:12+t.mem,r,n,o)},Ks=function(e,t){var r={};for(var n in e)r[n]=e[n];for(var n in t)r[n]=t[n];return r},qs=function(e,t,r){for(var n=e(),o=e.toString(),s=o.slice(o.indexOf("[")+1,o.lastIndexOf("]")).replace(/\s+/g,"").split(","),i=0;i<n.length;++i){var a=n[i],c=s[i];if("function"==typeof a){t+=";"+c+"=";var l=a.toString();if(a.prototype)if(-1!=l.indexOf("[native code]")){var u=l.indexOf(" ",8)+1;t+=l.slice(u,l.indexOf("(",u))}else for(var d in t+=l,a.prototype)t+=";"+c+".prototype."+d+"="+a.prototype[d].toString();else t+=l}else r[c]=a}return t},Js=[],Xs=function(){return[os,ss,is,as,cs,ls,ps,gs,Ts,Ss,bs,ks,ws,As,Cs,Rs,Ps,Us,Ls,Ds,ai,Zs,ei]},Qs=function(){return[os,ss,is,as,cs,ls,fs,ys,Is,vs,xs,Es,bs,Gs,Ys,ws,Os,Bs,Ns,$s,Ms,js,Hs,Fs,Ps,Us,Ws,zs,ii,Zs]},Zs=function(e){return postMessage(e,[e.buffer])},ei=function(e){return e&&{out:e.size&&new os(e.size),dictionary:e.dictionary}},ti=function(e,t,r,n,o,s){var i=function(e,t,r,n){if(!Js[r]){for(var o="",s={},i=e.length-1,a=0;a<i;++a)o=qs(e[a],o,s);Js[r]={c:qs(e[i],o,s),e:s}}var c=Ks({},Js[r].e);return ns(Js[r].c+";onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage="+t.toString()+"}",r,c,function(e){var t=[];for(var r in e)e[r].buffer&&t.push((e[r]=new e[r].constructor(e[r])).buffer);return t}(c),n)}(r,n,o,function(e,t){i.terminate(),s(e,t)});return i.postMessage([e,t],t.consume?[e.buffer]:[]),function(){i.terminate()}},ri=function(e,t){return e[t]|e[t+1]<<8},ni=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},oi=function(e,t){return ni(e,t)+4294967296*ni(e,t+4)},si=function(e,t,r){for(;r;++t)e[t]=r,r>>>=8};function ii(e,t){return zs(e,t||{},0,0)}function ai(e,t){return Ds(e,{i:2},t&&t.out,t&&t.dictionary)}var ci=function(e,t,r,n){for(var o in e){var s=e[o],i=t+o,a=n;Array.isArray(s)&&(a=Ks(n,s[1]),s=s[0]),s instanceof os?r[i]=[s,a]:(r[i+="/"]=[new os(0),a],ci(s,i,r,n))}},li="undefined"!=typeof TextEncoder&&new TextEncoder,ui="undefined"!=typeof TextDecoder&&new TextDecoder;try{ui.decode(Ys,{stream:!0})}catch(e){}function di(e,t){if(li)return li.encode(e);for(var r=e.length,n=new os(e.length+(e.length>>1)),o=0,s=function(e){n[o++]=e},i=0;i<r;++i){if(o+5>n.length){var a=new os(o+8+(r-i<<1));a.set(n),n=a}var c=e.charCodeAt(i);c<128||t?s(c):c<2048?(s(192|c>>6),s(128|63&c)):c>55295&&c<57344?(s(240|(c=65536+(1047552&c)|1023&e.charCodeAt(++i))>>18),s(128|c>>12&63),s(128|c>>6&63),s(128|63&c)):(s(224|c>>12),s(128|c>>6&63),s(128|63&c))}return Us(n,0,o)}var pi=function(e){var t=0;if(e)for(var r in e){var n=e[r].length;n>65535&&Ls(9),t+=n+4}return t},fi=function(e,t,r,n,o,s,i,a){var c=n.length,l=r.extra,u=a&&a.length,d=pi(l);si(e,t,null!=i?33639248:67324752),t+=4,null!=i&&(e[t++]=20,e[t++]=r.os),e[t]=20,t+=2,e[t++]=r.flag<<1|(s<0&&8),e[t++]=o&&8,e[t++]=255&r.compression,e[t++]=r.compression>>8;var p=new Date(null==r.mtime?Date.now():r.mtime),f=p.getFullYear()-1980;if((f<0||f>119)&&Ls(10),si(e,t,f<<25|p.getMonth()+1<<21|p.getDate()<<16|p.getHours()<<11|p.getMinutes()<<5|p.getSeconds()>>1),t+=4,-1!=s&&(si(e,t,r.crc),si(e,t+4,s<0?-s-2:s),si(e,t+8,r.size)),si(e,t+12,c),si(e,t+14,d),t+=16,null!=i&&(si(e,t,u),si(e,t+6,r.attrs),si(e,t+10,i),t+=14),e.set(n,t),t+=c,d)for(var h in l){var m=l[h],g=m.length;si(e,t,+h),si(e,t+2,g),e.set(m,t+4),t+=4+g}return u&&(e.set(a,t),t+=u),t},hi="function"==typeof queueMicrotask?queueMicrotask:"function"==typeof setTimeout?setTimeout:function(e){e()};function mi(e,t,r){const n=Math.min(t,512);if("utf-16"===r||"utf-16le"===r||"utf-16be"===r){for(let t=0;t<n;t+=2){const o=e[t],s=t+1<n?e[t+1]:0;if(("utf-16le"===r||"utf-16"===r)&&0===s&&o<32&&9!==o&&10!==o&&13!==o&&0!==o)return!1;if(("utf-16be"===r||"utf-16"===r)&&0===o&&s<32&&9!==s&&10!==s&&13!==s&&0!==s)return!1}return!0}if("latin1"===r||"iso-8859-1"===r){for(let t=0;t<n;t++){const r=e[t];if(0===r)return!1;if(r<32&&9!==r&&10!==r&&13!==r)return!1}return!0}if("cjk"===r||"big5"===r||"gb2312"===r||"gbk"===r||"euc-kr"===r||"shift-jis"===r){for(let t=0;t<n;t++){const r=e[t];if(0===r)return!1;if(r<32&&9!==r&&10!==r&&13!==r)return!1}return!0}return!1}var gi=class{fileBuffer;size;offset;error;constructor(e,t){this.fileBuffer=e,this.size=t,this.offset=0,this.error=!1}hasError(){return this.error}nextByte(){return this.offset===this.size||this.hasError()?(this.error=!0,255):this.fileBuffer[this.offset++]}next(e){if(e<0||e>this.size-this.offset)return this.error=!0,[];const t=new Array;for(let r=0;r<e;r++){if(this.error)return t;t[r]=this.nextByte()}return t}};function yi(e){let t=0,r=0;for(;!e.hasError();){const n=e.nextByte();if(r|=(127&n)<<7*t,!(128&n))break;if(t>=10){e.error=!0;break}t++}return r}function bi(e){switch(7&yi(e)){case 0:return yi(e),!0;case 1:return e.next(8),!0;case 2:const t=yi(e);return e.next(t),!0;case 5:return e.next(4),!0}return!1}function wi(e,t,r){if(0===t)return!1;let n=0;const o=Math.min(t,515),s=Math.min(o,512);if(t>=3&&239===e[0]&&187===e[1]&&191===e[2])return!1;if(t>=4&&0===e[0]&&0===e[1]&&254===e[2]&&255===e[3])return!1;if(t>=4&&255===e[0]&&254===e[1]&&0===e[2]&&0===e[3])return!1;if(t>=4&&132===e[0]&&49===e[1]&&149===e[2]&&51===e[3])return!1;if(o>=5&&"%PDF-"===e.slice(0,5).toString())return!0;if(t>=2&&254===e[0]&&255===e[1])return!1;if(t>=2&&255===e[0]&&254===e[1])return!1;if(r?.encoding)return!mi(e,t,r.encoding);const i=function(e,t){if(t<4)return null;const r=Math.min(t,512);let n=0,o=0;for(let t=0;t<r;t++)0===e[t]&&(t%2==0?n++:o++);const s=n+o;if(s>.3*r&&s<.7*r){if(o>3*n)return"utf-16le";if(n>3*o)return"utf-16be"}return null}(e,t);if(i)return!mi(e,t,i);for(let t=0;t<s;t++){if(0===e[t])return!0;if((e[t]<7||e[t]>14)&&(e[t]<32||e[t]>127)){if(e[t]>=192&&e[t]<=223&&t+1<o){if(t++,e[t]>=128&&e[t]<=191)continue}else if(e[t]>=224&&e[t]<=239&&t+2<o){if(t++,e[t]>=128&&e[t]<=191&&e[t+1]>=128&&e[t+1]<=191){t++;continue}}else if(e[t]>=240&&e[t]<=247&&t+3<o&&(t++,e[t]>=128&&e[t]<=191&&e[t+1]>=128&&e[t+1]<=191&&e[t+2]>=128&&e[t+2]<=191)){t+=2;continue}if(n++,t>=32&&100*n/s>10)return!0}}return 100*n/s>10||!!(n>1&&function(e,t){const r=new gi(e,t);let n=0;for(;;){if(!bi(r)&&!r.hasError())return!1;if(r.hasError())break;n++}return n>0}(e,s))}var vi=[/^\/$/,/^\*+$/,/^[0-9]+$/],_i=["/artifact/","https://","http://","*********"],Ei=new Set(["sha1","_sha1","pageref","downloadsPath","tracesDir","pageId"]);function Ii({sensitiveValues:e,str:t}){return e.reduce((e,t)=>e.replaceAll(t,"[REDACTED]"),t)}function Ti({sensitiveValues:e,value:t}){return"string"==typeof t?Ii({sensitiveValues:e,str:t}):Array.isArray(t)?t.map(t=>Ti({sensitiveValues:e,value:t})):function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(t)?Si({obj:t,sensitiveValues:e}):t}function xi(e){return!!Ei.has(e)||e.toLowerCase().endsWith("sha1")}function Si({obj:e,sensitiveValues:t}){return Object.fromEntries(Object.entries(e).map(([e,r])=>[e,xi(e)?r:Ti({sensitiveValues:t,value:r})]))}function Ai({error:e,sensitiveValues:t}){return e?{...e,message:Ii({sensitiveValues:t,str:e.message})}:void 0}function Ci({content:e,sensitiveValues:t}){const r=new O,n=new B,o=Ii({sensitiveValues:t,str:r.decode(e)});return n.encode(o)}var Ri=D(function(e,t,r){r||(r=t,t={}),"function"!=typeof r&&Ls(7);var n=[],o=function(){for(var e=0;e<n.length;++e)n[e]()},s={},i=function(e,t){hi(function(){r(e,t)})};hi(function(){i=r});for(var a=e.length-22;101010256!=ni(e,a);--a)if(!a||e.length-a>65558)return i(Ls(13,0,1),null),o;var c=ri(e,a+8);if(c){var l=c,u=ni(e,a+16),d=4294967295==u||65535==l;if(d){var p=ni(e,a-12);(d=101075792==ni(e,p))&&(l=c=ni(e,p+32),u=ni(e,p+48))}for(var f=t&&t.filter,h=function(t){var r=function(e,t,r){var n=ri(e,t+28),o=function(e,t){if(t){for(var r="",n=0;n<e.length;n+=16384)r+=String.fromCharCode.apply(null,e.subarray(n,n+16384));return r}if(ui)return ui.decode(e);var o=function(e){for(var t="",r=0;;){var n=e[r++],o=(n>127)+(n>223)+(n>239);if(r+o>e.length)return{s:t,r:Us(e,r-1)};o?3==o?(n=((15&n)<<18|(63&e[r++])<<12|(63&e[r++])<<6|63&e[r++])-65536,t+=String.fromCharCode(55296|n>>10,56320|1023&n)):t+=1&o?String.fromCharCode((31&n)<<6|63&e[r++]):String.fromCharCode((15&n)<<12|(63&e[r++])<<6|63&e[r++]):t+=String.fromCharCode(n)}}(e),s=o.s;return(r=o.r).length&&Ls(8),s}(e.subarray(t+46,t+46+n),!(2048&ri(e,t+8))),s=t+46+n,i=ni(e,t+20),a=r&&4294967295==i?function(e,t){for(;1!=ri(e,t);t+=4+ri(e,t+2));return[oi(e,t+12),oi(e,t+4),oi(e,t+20)]}(e,s):[i,ni(e,t+24),ni(e,t+42)],c=a[0],l=a[1],u=a[2];return[ri(e,t+10),c,l,o,s+ri(e,t+30)+ri(e,t+32),u]}(e,u,d),a=r[0],l=r[1],p=r[2],h=r[3],m=r[4],g=r[5],y=function(e,t){return t+30+ri(e,t+26)+ri(e,t+28)}(e,g);u=m;var b=function(e,t){e?(o(),i(e,null)):(t&&(s[h]=t),--c||i(null,s))};if(!f||f({name:h,size:l,originalSize:p,compression:a}))if(a)if(8==a){var w=e.subarray(y,y+l);if(p<524288||l>.8*p)try{b(null,ai(w,{out:new os(p)}))}catch(e){b(e,null)}else n.push(function(e,t,r){return r||(r=t,t={}),"function"!=typeof r&&Ls(7),ti(e,t,[Xs],function(e){return Zs(ai(e.data[0],ei(e.data[1])))},1,r)}(w,{size:p},b))}else b(Ls(14,"unknown compression type "+a,1),null);else b(null,Us(e,y,y+l));else b(null,null)},m=0;m<l;++m)h()}else i(null,{});return o}),Pi=D(function(e,t,r){r||(r=t,t={}),"function"!=typeof r&&Ls(7);var n={};ci(e,"",n,t);var o=Object.keys(n),s=o.length,i=0,a=0,c=s,l=new Array(s),u=[],d=function(){for(var e=0;e<u.length;++e)u[e]()},p=function(e,t){hi(function(){r(e,t)})};hi(function(){p=r});var f=function(){var e=new os(a+22),t=i,r=a-i;a=0;for(var n=0;n<c;++n){var o=l[n];try{var s=o.c.length;fi(e,a,o,o.f,o.u,s);var u=30+o.f.length+pi(o.extra),d=a+u;e.set(o.c,d),fi(e,i,o,o.f,o.u,s,a,o.m),i+=16+u+(o.m?o.m.length:0),a=d+s}catch(e){return p(e,null)}}!function(e,t,r,n,o){si(e,t,101010256),si(e,t+8,r),si(e,t+10,r),si(e,t+12,n),si(e,t+16,o)}(e,i,l.length,r,t),p(null,e)};s||f();for(var h=function(e){var t=o[e],r=n[t],c=r[0],h=r[1],m=function(){var e=-1;return{p:function(t){for(var r=e,n=0;n<t.length;++n)r=Vs[255&r^t[n]]^r>>>8;e=r},d:function(){return~e}}}(),g=c.length;m.p(c);var y=di(t),b=y.length,w=h.comment,v=w&&di(w),_=v&&v.length,E=pi(h.extra),I=0==h.level?0:8,T=function(r,n){if(r)d(),p(r,null);else{var o=n.length;l[e]=Ks(h,{size:g,crc:m.d(),c:n,f:y,m:v,u:b!=t.length||v&&w.length!=_,compression:I}),i+=30+b+E+o,a+=76+2*(b+E)+(_||0)+o,--s||f()}};if(b>65535&&T(Ls(11,0,1),null),I)if(g<16e4)try{T(null,ii(c,h))}catch(e){T(e,null)}else u.push(function(e,t,r){return r||(r=t,t={}),"function"!=typeof r&&Ls(7),ti(e,t,[Qs],function(e){return Zs(ii(e.data[0],e.data[1]))},0,r)}(c,h,T));else T(null,c)},m=0;m<c;++m)h(m);return d});async function Ui({content:e,filename:t,sensitiveValues:r}){const n=t.toLowerCase();return n.endsWith(".trace")||n.endsWith(".network")?function({content:e,sensitiveValues:t}){const r=new O,n=new B,o=r.decode(e).split("\n").map(e=>{if(!e.trim())return e;try{const r=function({event:e,sensitiveValues:t}){return j(e).with({type:"console"},e=>({...e,args:e.args?.map(e=>({...e,preview:Ii({sensitiveValues:t,str:e.preview}),value:Ti({sensitiveValues:t,value:e.value})})),text:Ii({sensitiveValues:t,str:e.text})})).with({type:"before"},e=>({...e,params:Si({obj:e.params,sensitiveValues:t}),title:e.title?Ii({sensitiveValues:t,str:e.title}):void 0})).with({type:"after"},e=>({...e,error:Ai({error:e.error,sensitiveValues:t}),result:void 0!==e.result?Ti({sensitiveValues:t,value:e.result}):void 0})).with({type:"action"},e=>({...e,error:Ai({error:e.error,sensitiveValues:t}),params:Si({obj:e.params,sensitiveValues:t}),result:void 0!==e.result?Ti({sensitiveValues:t,value:e.result}):void 0,title:e.title?Ii({sensitiveValues:t,str:e.title}):void 0})).with({type:"event"},e=>({...e,params:Si({obj:e.params,sensitiveValues:t})})).with({type:"stdout"},{type:"stderr"},e=>({...e,text:void 0!==e.text?Ii({sensitiveValues:t,str:e.text}):void 0})).with({type:"error"},e=>({...e,message:Ii({sensitiveValues:t,str:e.message})})).with({type:"log"},e=>({...e,message:Ii({sensitiveValues:t,str:e.message})})).with({type:"context-options"},e=>({...e,options:Si({obj:e.options,sensitiveValues:t}),title:e.title?Ii({sensitiveValues:t,str:e.title}):void 0})).with({type:"frame-snapshot"},e=>({...e,snapshot:Si({obj:e.snapshot,sensitiveValues:t})})).with({type:"resource-snapshot"},e=>({...e,snapshot:Si({obj:e.snapshot,sensitiveValues:t})})).with({type:"screencast-frame"},{type:"input"},e=>e).exhaustive()}({event:JSON.parse(e),sensitiveValues:t});return JSON.stringify(r)}catch{return Ii({sensitiveValues:t,str:e})}});return n.encode(o.join("\n"))}({content:e,sensitiveValues:r}):n.endsWith(".html")||n.endsWith(".dat")||n.endsWith(".json")?Ci({content:e,sensitiveValues:r}):n.startsWith("resources/")?async function({content:e,sensitiveValues:t}){return function(e){return function(e,t){if(function(e){return"string"==typeof e}(e)){!function(e){if(!e.isFile())throw new Error("Path provided was not a file!")}(y(e));const r=I(e,"r"),n=Buffer.alloc(515),o=T(r,n,0,515,0);return x(r),wi(n,o,t)}return wi(e,void 0!==t?.size?t.size:e.length,t)}(Buffer.from(e),{size:e.length})}(e)?e:Ci({content:e,sensitiveValues:t})}({content:e,sensitiveValues:r}):e}function ki(e=process.cwd()){let t=n(e);for(;;){const e=Li(t);if(e){const r={...e.dependencies,...e.devDependencies},n="@playwright/test"in r?"@playwright/test":"playwright"in r?"playwright":void 0;if(n){const e=Di(t);let r=!1,i=t;for(;;){const e=s(i,"node_modules"),t=s(e,n);if(g(t)){r=!0;break}const a=o(i);if(a===i)break;i=a}return{inNodeModules:r,installed:!0,packageManager:e,packageName:n}}}const r=o(t);if(r===t)return{inNodeModules:!1,installed:!1,packageManager:void 0};t=r}}function Li(e){const t=s(e,"package.json");let r;try{r=w(t,"utf-8")}catch{return}try{return JSON.parse(r)}catch{return}}function Di(e){const t=[["npm","package-lock.json"],["pnpm","pnpm-lock.yaml"],["yarn","yarn.lock"]];let r=e;for(;;){for(const[e,n]of t)if(g(s(r,n)))return e;const e=o(r);if(e===r)return;r=e}}function Oi(e){if("npm"===e||"pnpm"===e)return["npx","playwright"];if("yarn"===e)return["yarn","playwright"];throw new Error("Package manager not supported")}var Bi=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Ni=e=>(e instanceof Error?e.message:String(e)).slice(0,400),$i=({outputDir:e,representativeTest:t})=>{const r=["test","--trace=on","--workers=1","--retries=0","--output",e];return t.filePath&&r.push(t.filePath),t.testTitle?r.push("--grep",Bi(t.testTitle)):t.testIdentifier&&r.push("--grep",`^${Bi(t.testIdentifier)}$`),r},Mi=async e=>{const t=await X(e,{withFileTypes:!0}),n=[];for(const o of t){const t=r.join(e,o.name);if(o.isDirectory())n.push(...await Mi(t));else if(o.isFile()&&"trace.zip"===o.name){const e=await Q(t);n.push({path:t,mtimeMs:e.mtimeMs})}}return n},{zSuiteAutoHealReport:ji,zRepresentativeTest:Hi}=function(e){const t=e.enum(Jo),r=["Classification of the root cause:","",`- test: ${Qo("test")}`,`- bug: ${Qo("bug")}`,`- flake: ${Qo("flake")}`,`- ui_change: ${Qo("ui_change")}`,`- other: ${Qo("other")}`].join("\n"),n=e.object({filePath:e.string().optional(),testIdentifier:e.string().optional(),testTitle:e.string().optional()}),o=e.object({status:e.enum(["captured","capture_failed","upload_failed"]),representativeTest:n,storage:e.object({bucket:e.string(),key:e.string()}).optional(),signedUrl:e.string().optional(),error:e.string().optional()}),s=o.extend({testCaseId:e.string().min(1).describe("Test case ID this trace proof corresponds to.")}),i=e.object({erroredUrl:e.string().optional(),issueType:t.describe(r),relatedTestCaseIds:e.array(e.string()).min(1).describe("List of ALL test case IDs impacted by this root cause (must be existing IDs only)."),rootCause:e.string().describe("Brief explanation of what happened (1-2 sentences)."),traceProofs:e.array(s).min(1).optional().describe("Per-test trace proofs for each testCaseId in this issue.")}),a=e.discriminatedUnion("result",[i.extend({fixApplied:e.string().describe("What fix was applied (brief, specific)."),result:e.literal("fixed"),traceProof:o.optional()}),i.extend({followUpActions:e.string().optional().describe("Optional list of follow-up actions for any unfixed issues or missing data."),reasonNotFixed:e.string().describe("Why it could not be auto-fixed (brief)."),result:e.literal("unfixed")})]);return{zAutoHealReport:a,zIssueCategory:t,zRepresentativeTest:n,zSuiteAutoHealReport:e.object({issues:e.array(a).min(1).describe("List of all auto-heal issues/outcomes for this suite."),summary:e.string().min(3).describe("High-level summary (2-3 sentences) of the suite auto-heal results.")}),zTraceProof:o,zTraceProofByTest:s}}(he),Fi=({authHeader:e,diffTracker:t,orgId:n,runId:o,workingDir:s})=>N({name:"auto-heal-report",tools:[$("capture-trace-proof",["Capture and upload a Playwright trace proof for a test case.","","MANDATORY: Call for EVERY testCaseId in your issue, whether fixed or unfixed.","- Fixed: Trace proves the fix works","- Unfixed: Trace shows the failure state for auditability","","Pass testCaseId and call once per test case.","testCaseId is for per-test mapping/storage metadata; representativeTest selects the runnable test."].join("\n"),{issueId:he.string().min(1).describe("Issue identifier for deterministic output paths and storage key naming."),proofId:he.string().min(1).optional().describe("Optional id for deterministic proof naming and deduplication."),representativeTest:Hi.optional().default({}),testCaseId:he.string().min(1).optional().describe("Optional test case ID when capturing per-test trace proofs.")},async({issueId:t,proofId:i,representativeTest:a,testCaseId:c})=>{const l=he.string().min(1).parse(t),u=null==i?void 0:he.string().min(1).parse(i),d=null==c?void 0:he.string().min(1).parse(c),p=await(async({authHeader:e,issueId:t,orgId:n,proofId:o,representativeTest:s,runId:i,testCaseId:a,workingDir:c})=>{if(!(e=>null!=e.filePath||null!=e.testTitle||null!=e.testIdentifier)(s))return{status:"capture_failed",representativeTest:s,error:"Representative test info is missing (need filePath, testTitle, or testIdentifier)."};const l=ki(c);if(!l.installed||!l.inNodeModules||!l.packageManager)return{status:"capture_failed",representativeTest:s,error:"Playwright is not installed in the current workspace."};const u=(e=>es(e)??"issue")(t),d=(({proofId:e,testCaseId:t})=>ts(t)??ts(e))({testCaseId:a,proofId:o}),p=r.join(c,".stably","autoheal-proof",u,d??"issue"),[h,...m]=Oi(l.packageManager),g=[...m,...$i({outputDir:p,representativeTest:s})];try{await Z(p,{force:!0,recursive:!0}),await z(p,{recursive:!0});const{code:r,stderr:l,timedOut:u}=await(async({args:e,command:t,cwd:r,env:n,timeoutMs:o})=>await new Promise((s,i)=>{const a=f(t,e,{cwd:r,env:n??process.env,stdio:["ignore","ignore","pipe"]});let c="",l=!1;a.stderr.on("data",e=>{c+=e.toString()});const u=setTimeout(()=>{l=!0,a.kill("SIGTERM")},o);a.on("error",e=>{clearTimeout(u),i(e)}),a.on("close",e=>{clearTimeout(u),s({code:e,stderr:c,timedOut:l})})}))({args:g,command:h,cwd:c,env:{...process.env,STABLY_INTERNAL_DISABLE_REPORTING:"1"},timeoutMs:3e5});if(u)return{status:"capture_failed",representativeTest:s,error:"Trace proof run timed out while executing Playwright verification."};if(0!==r)return{status:"capture_failed",representativeTest:s,error:`Trace proof run failed (exit code ${r??"unknown"}): ${l.trim().slice(0,280)}`};const d=await(async e=>{const t=await Mi(e);if(0!==t.length)return t.sort((e,t)=>t.mtimeMs-e.mtimeMs),t[0]?.path})(p);if(!d)return{status:"capture_failed",representativeTest:s,error:"Trace proof run completed, but no trace.zip was produced."};const{traceBucketPath:m,uploadUrl:y,sensitiveValues:w}=await(async({authHeader:e,issueId:t,proofId:r,testCaseId:n,contentType:o="application/zip",orgId:s,runId:i})=>{const a=await(c={auth:e,body:{contentType:o,issueId:t,proofId:r,testCaseId:n},client:Zr(),headers:Qn(s),path:{runId:i}},(c.client??Gr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-trace/upload-url",...c,headers:{"Content-Type":"application/json",...c.headers}}));var c;if(a.error)throw new Error(`Failed to presign trace upload (${a.response.status})`);const l=ro.parse(a.data);return{traceBucketPath:l.traceBucketPath,expiresInSeconds:l.expiresInSeconds,key:l.key,uploadUrl:l.uploadUrl,sensitiveValues:l.sensitiveValues}})({authHeader:e,issueId:t,proofId:o,orgId:n,runId:i,testCaseId:a}),v=await async function({tracePath:e,sensitiveValues:t}){const r=[],n=b(e);for await(const e of n)r.push(e);return async function({sensitiveValues:e,traceBuffer:t}){const r=e.filter(e=>!(e.length<3||vi.some(t=>t.test(e))||_i.some(t=>e.includes(t))));if(0===r.length)return new Uint8Array(t);const n=[...r].sort((e,t)=>t.length-e.length),o=await Ri(new Uint8Array(t)),s=Object.entries(o),i=await Promise.all(s.map(async([e,t])=>[e,await Ui({content:t,filename:e,sensitiveValues:n})])),a=Object.fromEntries(i);return Pi(a)}({traceBuffer:new Uint8Array(Buffer.concat(r)),sensitiveValues:t})}({tracePath:d,sensitiveValues:w});try{await(async({contentType:e="application/zip",traceBuffer:t,uploadUrl:r})=>{const n=await fetch(r,{body:Buffer.from(t),headers:{"Content-Type":e},method:"PUT"});if(!n.ok)throw new Error(`Failed to upload trace (${n.status})`)})({traceBuffer:v,uploadUrl:y})}catch(e){return{status:"upload_failed",representativeTest:s,error:Ni(e)}}return{status:"captured",representativeTest:s,storage:m}}catch(e){return{status:"capture_failed",representativeTest:s,error:Ni(e)}}})({authHeader:e,issueId:l,orgId:n,proofId:u,representativeTest:Hi.parse(a??{}),runId:o,testCaseId:d,workingDir:s}),h="string"==typeof d?{testCaseId:d,...p}:p;return{content:[{text:JSON.stringify(h),type:"text"}]}}),$("generate-report",["After attempting to fix all broken tests (skip only those truly infeasible), generate and return a suite auto-heal report in the required schema.","","Ensure the payload matches zSuiteAutoHealReport exactly; include every issue discovered."].join("\n"),{report:ji},async({report:r})=>{const s=await t.computeDiff(),i=(e=>{if(!e||"object"!=typeof e)return e;const t=e;if(!Array.isArray(t.issues))return e;const r=t.issues.map(e=>{if(!e||"object"!=typeof e)return e;const t=e;if("fixed"!==t.result||null!=t.traceProof||!Array.isArray(t.traceProofs))return e;const[r]=t.traceProofs;if(!r||"object"!=typeof r)return e;const n={...r};return delete n.testCaseId,{...t,traceProof:n}});return{...t,issues:r}})(r),a=ji.parse(i);try{await(async({authHeader:e,orgId:t,report:r,runId:n})=>{const o=await(s={auth:e,body:{report:JSON.stringify(r)},client:Zr(),headers:Qn(t),path:{runId:n}},(s.client??Gr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-report",...s,headers:{"Content-Type":"application/json",...s.headers}}));var s;if(o.error)throw new Error(`Failed to upload auto-heal report (${o.response.status})`)})({authHeader:e,orgId:n,report:a,runId:o});const{diffBucketPath:t,uploadUrl:r}=await no({authHeader:e,contentType:"text/plain",orgId:n,runId:o});await oo({contentType:"text/plain",diff:s,uploadUrl:r}),await so({authHeader:e,diffBucketPath:t,orgId:n,runId:o})}catch(e){return console.error("[auto-heal-report] Failed to upload report or diff:",e),{content:[{text:`Error: Failed to upload auto-heal report or diff. ${e instanceof Error?e.message:String(e)} Please surface this to the user, and terminate the session.`,type:"text"}]}}return{content:[{text:"Auto-heal report generated. You may terminate this session now.",type:"text"}]}})],version:"0.0.1"}),Gi=({onComplete:e,onRestartRequested:t})=>N(e?{name:"session-control",tools:[$("complete_session",["Call this tool when you have completed your task and the session should end.","Use this instead of waiting for the user to manually terminate.","Only call this when you are confident the task is fully complete."].join("\n"),{summary:he.string().describe("A brief summary of what was accomplished")},({summary:t})=>{const r="string"==typeof t?t:String(t);return e(),Promise.resolve(`Session complete: ${r}`)})]}:{name:"stably-agent-control",version:"1.0.0",tools:[$("restart_mcp_servers",'Restart the MCP servers to reinitialize browser tools after dependency changes.\n\nWHEN TO USE:\n- After installing or updating @playwright/test to version 1.56.x\n- When browser tools fail due to version mismatch errors\n- When the user has fixed a dependency issue and you need to reinitialize\n\nIMPORTANT: The restart happens at the END of your current turn.\n- Do NOT call any browser tools (setup_page, navigate, etc.) after this tool in the same turn - they will use the OLD servers\n- After calling this tool, END your turn naturally (no more tool calls)\n- The system will automatically continue in a new turn once the tools are restarted\n- Do NOT ask the user to reply again just to resume (only ask if you truly need additional input)\n\nEnd your turn briefly. You may say something like:\n- "Restarting browser tools now…"\n- "Tools are restarting to pick up the dependency changes…"',{},()=>(t(),Promise.resolve({content:[{type:"text",text:"MCP servers are being restarted. Browser tools will be reinitialized."}]})))]}),Yi=he.object({commentUrl:he.string()}),Wi=({prContext:e,authHeader:t,orgId:r,onReportPosted:n})=>N({name:"create-report",tools:[$("post_create_report",`Post a test creation report as a GitHub comment on PR #${e.prNumber}.\nCall this tool at the end of test creation to summarize what was created.\nThe report will be posted to: ${e.prUrl}\n\nWHEN TO USE:\n- After you have finished creating test files\n- To provide a summary of the tests created on the PR for visibility\n\nThe report will include:\n- A list of all test files created\n- Your summary of what was tested`,{summary:he.string().describe("A summary of the tests created. Include what features/flows are tested and any important notes."),filesCreated:he.array(he.string()).describe("List of test file paths that were created (relative to workspace root)")},async({summary:o,filesCreated:s})=>{const i=Array.isArray(s)?s:[];Fn.info("[create-report] Posting report to GitHub PR",{prNumber:e.prNumber,filesCount:i.length});try{const s={summary:"string"==typeof o?o:String(o),filesCreated:i.map(String)},a=await async function({authHeader:e,orgId:t,prNumber:r,owner:n,repo:o,report:s}){const i=new URL("/internal/v1/cli/create-report",Wr).toString(),a={Authorization:e,"Content-Type":"application/json"};t&&(a["x-stably-org-id"]=t),Fn.debug("Posting create report to GitHub",{prNumber:r,owner:n,repo:o,filesCount:s.filesCreated.length});const c=await fetch(i,{method:"POST",headers:a,body:JSON.stringify({prNumber:r,owner:n,repo:o,report:s}),signal:AbortSignal.timeout(3e4)});if(!c.ok){const e=await c.text().catch(()=>"");throw Fn.error("Failed to post create report",{status:c.status,error:e.slice(0,500)}),new Error(`Failed to post create report: ${c.status} ${e.slice(0,200)}`)}const l=Yi.parse(await c.json());return Fn.info("Create report posted successfully",{commentUrl:l.commentUrl}),l}({authHeader:t,orgId:r,prNumber:e.prNumber,owner:e.owner,repo:e.repo,report:s});return n?.(a),Fn.info("[create-report] Report posted successfully",{commentUrl:a.commentUrl}),{content:[{type:"text",text:`✅ Test creation report posted to PR #${e.prNumber}\n\nView the comment: ${a.commentUrl}`}]}}catch(e){const t=e instanceof Error?e.message:String(e);return Fn.error("[create-report] Failed to post report",{error:t}),{content:[{type:"text",text:`❌ Failed to post report to GitHub: ${t}\n\nThe tests were still created successfully, but the PR comment could not be posted.`}],isError:!0}}})]}),Vi=e=>e.replace(/Bearer\s+[A-Za-z0-9._-]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{16,}\b/g,"[redacted]").replace(/\bstably_[A-Za-z0-9_-]{16,}\b/g,"[redacted]"),zi=(e,t)=>({message:Vi(e),status:t?.status,statusText:t?.statusText}),Ki=new Set(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_CUSTOM_HEADERS","ANTHROPIC_DEFAULT_HAIKU_MODEL","ANTHROPIC_DEFAULT_OPUS_MODEL","ANTHROPIC_DEFAULT_SONNET_MODEL","ANTHROPIC_FOUNDRY_API_KEY","ANTHROPIC_MODEL","ANTHROPIC_SMALL_FAST_MODEL","ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION","AWS_BEARER_TOKEN_BEDROCK","BASH_DEFAULT_TIMEOUT_MS","BASH_MAX_OUTPUT_LENGTH","BASH_MAX_TIMEOUT_MS","CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR","CLAUDE_CODE_API_KEY_HELPER_TTL_MS","CLAUDE_CODE_CLIENT_CERT","CLAUDE_CODE_CLIENT_KEY_PASSPHRASE","CLAUDE_CODE_CLIENT_KEY","CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS","CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC","CLAUDE_CODE_DISABLE_TERMINAL_TITLE","CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL","CLAUDE_CODE_MAX_OUTPUT_TOKENS","CLAUDE_CODE_SHELL_PREFIX","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SUBAGENT_MODEL","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_VERTEX","CLAUDE_CONFIG_DIR","DISABLE_AUTOUPDATER","DISABLE_BUG_COMMAND","DISABLE_COST_WARNINGS","DISABLE_ERROR_REPORTING","DISABLE_NON_ESSENTIAL_MODEL_CALLS","DISABLE_PROMPT_CACHING","DISABLE_PROMPT_CACHING_HAIKU","DISABLE_PROMPT_CACHING_OPUS","DISABLE_PROMPT_CACHING_SONNET","DISABLE_TELEMETRY","HTTP_PROXY","HTTPS_PROXY","MAX_MCP_OUTPUT_TOKENS","MAX_THINKING_TOKENS","MCP_TIMEOUT","MCP_TOOL_TIMEOUT","NO_PROXY","SLASH_COMMAND_TOOL_CHAR_BUDGET","USE_BUILTIN_RIPGREP","VERTEX_REGION_CLAUDE_3_5_HAIKU","VERTEX_REGION_CLAUDE_3_7_SONNET","VERTEX_REGION_CLAUDE_4_0_OPUS","VERTEX_REGION_CLAUDE_4_0_SONNET","VERTEX_REGION_CLAUDE_4_1_OPUS"]),qi=async({authHeader:e,mode:t,maxTurnsOverride:r})=>{const n=Zr();Fn.debug("Requesting subagent definitions from API",{mode:t,maxTurnsOverride:r});const o=await(s={client:n,auth:e,body:{mode:t,maxTurnsOverride:r}},(s.client??Gr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/prompts/subagents",...s,headers:{"Content-Type":"application/json",...s.headers}}));var s;if(401===o.response.status)throw Fn.warn("Subagent definitions fetch failed: unauthorized (401)"),await mn(),new Error("Your session has expired or been revoked. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(403===o.response.status)throw Fn.warn("Subagent definitions fetch failed: forbidden (403)"),await mn(),new Error("You no longer have access to this organization. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(o.error)throw Fn.warn("Subagent definitions fetch failed",{error:o.error}),new Error(`Failed to fetch subagent definitions: ${JSON.stringify(o.error)}`);const{subagents:i}=o.data;return Fn.debug("Subagent definitions received",{count:Object.keys(i).length}),i},Ji=r.dirname(A(import.meta.url)),Xi=r.join(".claude-plugin","plugin.json"),Qi=[r.join("packages","agent-plugin","stably-plugin"),r.join("agent-plugin","stably-plugin")];function Zi(e){return g(r.join(e,Xi))}var{zStablyYaml:ea}=function(e){const t=e.object({cron:e.string(),stablyTestArgs:e.string().optional(),timezone:e.string().optional(),command:e.string().optional()}),r=e.object({maxTurnsPerIssue:e.number().int().positive().optional(),maxParallelWorkers:e.number().int().positive().optional(),rules:e.string().optional(),skipAfterConsecutiveUnfixed:e.number().int().positive().optional()}),n=e.object({fix:r.optional()});return{zStablyYaml:e.object({schedules:e.record(e.string(),t).optional(),agent:n.optional()}),zAgentConfig:n,zAgentFixConfig:r,zScheduleEntry:t}}(le),ta=async(e,t)=>{try{const r=await sn(e,t);if(!r)return void Fn.debug(`No ${t} found`);const n=await V(r,"utf-8");if(!n.trim())return;return n.length>1e4?(Fn.warn(`${t} exceeds max length (${n.length} > 10000), truncating`,{path:r}),{content:n.slice(0,1e4),path:r}):(Fn.debug(`Loaded ${t} rules`,{path:r,contentLength:n.length}),{content:n,path:r})}catch(e){return void Fn.warn(`Failed to read ${t}`,{error:e})}},ra=["Bash","Read","Write","Edit","Glob","Grep","Task","Skill"],na=["Task","mcp__playwright-test","Skill"],oa=["Bash","Read","Write","Edit","Glob","Grep","mcp__session-control"],sa=e=>{if("EPIPE"!==e.code)throw e},ia="__main__",aa=e=>"mcp__auto-heal-report__generate-report"===e;async function ca(e,t){return!!e&&(!!e.hasQueuedMessages()||new Promise(r=>{const n=setTimeout(()=>{clearInterval(o),r(!1)},t),o=setInterval(()=>{e.hasQueuedMessages()&&(clearTimeout(n),clearInterval(o),r(!0))},200)}))}var la=async e=>{if("single"===e.mode||"build"===e.mode){const t=Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt;Fn.initSession(t||"create-from-diff")}else"fix"===e.mode&&Fn.initSession(`fix-${e.runId}`);Fn.info("Agent session starting",{mode:e.mode}),process.stdout.on("error",sa),process.stderr.on("error",sa);const i=e=>{if("EPIPE"!==e.code)throw e};process.on("uncaughtException",i),Fn.debug("Checking authentication");const a=await Kn({autoLogin:"chat"===e.mode||"init"===e.mode}),c=(e=>"env"===e.type?e.auth.apiKey:e.auth.accessToken)(a);Fn.debug("Authentication resolved",{authType:a.type});const l="oauth"===a.type?a.auth.context.orgId:void 0,u=r.resolve(process.cwd()),d=r.join(u,".env"),p=m.existsSync(d)&&m.statSync(d).isFile(),f=p?t(m.readFileSync(d,"utf8")):{};Fn.debug("Environment file",{path:d,exists:p,variableCount:Object.keys(f).length});const h="chat"!==e.mode&&"init"!==e.mode,y="chat"===e.mode;let b=new Po;const w="chat"===e.mode?e.getHelpText:void 0,v={log:[],promptDisplay:j(e).with({mode:"chat"},()=>"Ask Stably to build tests for you").with({mode:"init"},()=>"Setting up Playwright and Stably SDK").with({mode:"fix"},()=>"Fixing broken tests").with({mode:"build"},()=>"Building tests from specifications").with({mode:"single"},e=>{const t=(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt)?.trim();return t||"Creating tests from PR/branch changes"}).exhaustive(),status:"running"};let _,E,I,T,x=h,S=!1,A=!1,C=0,R=0,P=!1;const U=[];let k,L,D=[],O=!1,B=!1,N=0;const $=new Map;let F=null,Y=!1,W=!1;const z=Date.now();let K,q="fix"===e.mode?{suiteId:e.runId,phase:"initializing",totalTests:null,fixedTests:0,failedTests:0,currentTestDescription:null,lastTestDescription:null,startedAt:z,endedAt:null,isError:!1,updatedAt:z,recentActivity:[],workers:[{id:ia,testDescription:"Orchestrator",workerType:"main",status:"running",summary:null,startedAt:z,endedAt:null,activity:[]}]}:null;const J=new Set,X=(e,t)=>{if(!q)return;const r=q.workers.map(r=>{if(r.id!==e)return r;const n=[...r.activity,{...t,timestamp:Date.now()}].slice(-15);return{...r,activity:n}});ee({workers:r})},Q=e=>{if(!q)return;const t=[...q.recentActivity,{...e,timestamp:Date.now()}].slice(-10);ee({recentActivity:t})},Z=e=>(q?.workers??[]).map(t=>t.id===ia?{...t,status:e?"failed":"succeeded",endedAt:t.endedAt??Date.now()}:"running"===t.status?{...t,status:"failed",endedAt:Date.now()}:t),ee=e=>{q&&!K?.isClosed&&(q={...q,...e,updatedAt:Date.now()},K?.sendProgress(q))},te=async t=>{if("fix"===e.mode){if("STARTED"===t){if(Y)return;Y=!0}else{if(W)return;W=!0}try{await(async({authHeader:e,orgId:t,runId:r,status:n})=>{const o=await(s={auth:e,body:{status:n},client:Zr(),headers:Qn(t),path:{runId:r}},(s.client??Gr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-status",...s,headers:{"Content-Type":"application/json",...s.headers}}));var s;if(o.error)throw new Error(`Failed to update autoheal status (${o.response.status})`)})({authHeader:c,orgId:l,runId:e.runId,status:t})}catch{}}},re="single"===e.mode||"build"===e.mode,ne=Date.now();let oe,se=null;const ie=e=>{se&&!oe?.isClosed&&(se={...se,...e,updatedAt:Date.now()},oe?.sendProgress(se))},ae=e=>{if(!se)return;const t=[...se.recentActivity,{...e,timestamp:Date.now()}].slice(-10);ie({recentActivity:t})};if(re||"fix"===e.mode)try{const t=new URL("/internal/v1/cli/progress",Wr).toString(),r={Authorization:c,"Content-Type":"application/json"};l&&(r["x-stably-org-id"]=l);const n="single"===e.mode?"create":"build"===e.mode?"build":"fix",o=await fetch(t,{method:"POST",headers:r,body:JSON.stringify({mode:n,projectId:qn(a),agentId:H.randomUUID(),..."fix"===e.mode?{playwrightSuiteRunId:e.runId}:{}}),signal:AbortSignal.timeout(1e4)});if(o.ok){const{sessionId:t}=await o.json();if(re){const r="single"===e.mode||"build"===e.mode?Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt:null,n=Uo(u);se={sessionId:t,phase:"initializing",startedAt:ne,endedAt:null,isError:!1,updatedAt:ne,currentActivity:null,filesCreated:[],recentActivity:[],prompt:r||null,environment:{gitBranch:n?.branch??null,workingDirectory:u,nodeVersion:process.version,cliVersion:Yr}},oe=new ao({authHeader:c,orgId:l,sessionId:t,onUserMessage:e=>{b&&(Fn.info("[ws] Injecting web UI message into agent",{contentLength:e.length}),ae({type:"user_message",summary:e}),me({text:`[Web] ${e}`}),b.pushText(`[Message from web UI user]: ${e}`),x||(x=!0,Ue({status:"running"})))}}),oe.start(),ie({phase:"initializing"})}Fn.info(`[${n}] Progress session created`,{sessionId:t})}else{const e=await o.text().catch(()=>"");Fn.warn(`[${n}] Failed to create progress session: ${o.status} ${t} — ${e.slice(0,300)}`)}}catch(e){const t=e instanceof Error?e.message:String(e);Fn.warn(`[progress] Session creation failed (non-fatal): ${t}`)}const ce={current:e=>{}},le={current:async()=>{}},{addSubagentActivity:ue,addSubagentStart:de,addTool:pe,addToolResult:fe,appendText:he,appendUserMessage:me,cleanup:Ie,setExiting:xe,setRunningLabel:Se,setStatus:Ae,setSubagentStatus:Ce,updateFixProgress:Re}=await(async(e,t)=>{const{Box:r,Static:n,Text:o,render:s,useInput:i}=await import("ink"),a=!!process.stdin.isTTY,c=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],l=()=>_e(o,{inverse:!0,children:" "}),u=(({Box:e,Text:t,useInput:r},n,o)=>function({onChoice:s,prompt:i}){const[a,c]=ge(0),[l,u]=ge(!1),[d,p]=ge(""),f=[{label:"Yes, allow this once",value:"allow"},{label:"Yes, always allow for this session",value:"always"},{label:"No, tell AI what to do differently",value:"deny_with_message"}];r((e,t)=>{if(l)return t.return?void s("deny_with_message",d||"User denied this action"):t.escape?(u(!1),void p("")):t.backspace||t.delete?void p(e=>e.slice(0,-1)):void(t.ctrl||t.meta||p(t=>`${t}${e}`));if(t.upArrow)return void c(e=>e>0?e-1:f.length-1);if(t.downArrow)return void c(e=>e<f.length-1?e+1:0);if(t.return){const e=f[a];return"deny_with_message"===e.value?void u(!0):void s(e.value)}const r=parseInt(e,10);if(r>=1&&r<=f.length){const e=f[r-1];if("deny_with_message"===e.value)return void u(!0);s(e.value)}},{isActive:o});const h=qo(i.toolName),m=Ko(i.toolName,i.input);return Ee(e,{borderColor:"yellow",borderStyle:"round",flexDirection:"column",marginTop:1,paddingX:1,paddingY:0,children:[_e(t,{bold:!0,color:"yellow",children:"Permission Required"}),Ee(e,{flexDirection:"column",marginTop:1,children:[_e(t,{color:"magenta",children:h}),null!=m&&Ee(t,{color:"gray",children:[" ",m]})]}),null!=i.decisionReason&&_e(e,{marginTop:1,children:Ee(t,{color:"gray",children:["Reason: ",i.decisionReason]})}),Ee(e,l?{flexDirection:"column",marginTop:1,children:[_e(t,{color:"gray",children:"Enter message for AI (press Enter to submit, Esc to cancel):"}),Ee(t,{children:[_e(t,{color:"yellow",children:">"})," ",d,_e(n,{})]})]}:{flexDirection:"column",marginTop:1,children:[_e(t,{color:"gray",children:"Use ↑↓ arrows or number keys to select:"}),f.map((e,r)=>_e(t,{children:Ee(t,{color:r===a?"cyan":void 0,children:[r===a?"❯":" "," ",r+1,". ",e.label]})},e.value))]})]})})({Box:r,Text:o,useInput:i},l,a),d=(({Cursor:e,inkComponents:{Box:t,Static:r,Text:n,useInput:o},isRawModeSupported:s,PermissionPrompt:i,Spinner:a})=>{const c=({progress:e})=>{const[r,o]=ge(Date.now());be(()=>{const e=setInterval(()=>o(Date.now()),1e3);return()=>clearInterval(e)},[]);const s=r-e.startedAt,i=Math.floor(s/1e3),a=Math.floor(i/60),c=i%60,l=a>0?`${a}m ${c.toString().padStart(2,"0")}s`:`${c}s`,{label:u,color:d}={initializing:{label:"Fetching test results",color:"gray"},triage:{label:"Triaging failures",color:"yellow"},fixing:{label:"Fixing tests",color:"cyan"},validation:{label:"Validating fixes",color:"blue"},complete:{label:"Complete",color:"green"}}[e.phase],p=e.fixedTests+e.failedTests,f="fixing"===e.phase&&p>0?null!==e.totalTests?` (fixed ${e.fixedTests}/${e.totalTests}${e.failedTests>0?`, failed ${e.failedTests}`:""})`:` (fixed ${e.fixedTests}${e.failedTests>0?`, failed ${e.failedTests}`:""})`:"";return _e(t,{flexDirection:"column",children:Ee(n,{children:[_e(n,{color:d,bold:!0,children:u}),_e(n,{color:"gray",children:f}),Ee(n,{color:"gray",children:[" [",l,"]"]})]})})},l=({progress:e})=>{const r=e.endedAt??Date.now(),o=Math.floor((r-e.startedAt)/1e3),s=Math.floor(o/60),i=o%60,a=s>0?`${s}m ${i.toString().padStart(2,"0")}s`:`${i}s`,c=e.isError?"yellow":"green",l=e.isError?"Fix stopped":"Fix complete";return Ee(t,{flexDirection:"column",children:[Ee(n,{color:c,bold:!0,children:[l," in ",a]}),null!==e.totalTests&&Ee(n,{color:"gray",children:[e.fixedTests,"/",e.totalTests," tests fixed",e.failedTests>0?`, ${e.failedTests} failed`:""]})]})},u=e=>{if("subagent"===e.kind&&e.subagent){const{subagent:r}=e,o="complete"===r.status?"green":"error"===r.status?"red":"yellow";return Ee(t,{flexDirection:"column",marginTop:1,children:[Ee(n,{children:[_e(n,{color:o,bold:!0,children:"Agent"}),r.description?Ee(n,{color:"gray",children:[" (",r.description,")"]}):null]}),r.activities.length>0&&_e(t,{flexDirection:"column",marginLeft:2,children:r.activities.map(e=>(e=>"tool"===e.kind?Ee(n,{color:"magenta",children:["• ",e.content]},e.id):"tool_result"===e.kind?_e(n,{color:"gray",children:e.content},e.id):null)(e))})]},e.id)}return"tool"===e.kind?Ee(n,{color:"magenta",children:["• ",e.content]},e.id):"tool_result"===e.kind?_e(n,{color:"gray",children:e.content},e.id):"user"===e.kind?Ee(n,{color:"cyan",children:["You: ",e.content]},e.id):_e(n,{children:e.content},e.id)},d="vscode"===process.env.TERM_PROGRAM,p=(e,t)=>{if(t<=0)return 0;let r=t-1;for(;r>0&&/\s/.test(e[r]);)r--;for(;r>0&&!/\s/.test(e[r-1]);)r--;return r},f=(e,t)=>{if(t>=e.length)return e.length;let r=t;for(;r<e.length&&!/\s/.test(e[r]);)r++;for(;r<e.length&&/\s/.test(e[r]);)r++;return r},h=(e,t)=>{if(t<=0)return 0;const r=e.lastIndexOf("\n",t-1);return-1===r?0:r+1},m=(e,t)=>{const r=e.indexOf("\n",t);return-1===r?e.length:r};return function({onExit:g,onPermissionChoice:y,onSend:b,showSpinnerImmediately:w,state:v}){const[_,E]=ge({value:"",cursor:0}),I=_.value,T=_.cursor,x=ye(!1),S=ye(void 0),[A,C]=ge(!1),R=ye(0),P=v.log.at(-1),U="text"===P?.kind&&"running"===v.status,k=v.log.findIndex(e=>"subagent"===e.kind&&"running"===e.subagent?.status),L=d?0:-1!==k?k:U?v.log.length-1:v.log.length;be(()=>{v.log.length<R.current&&(R.current=0),L>R.current&&(R.current=L)},[v.log.length,L]);const D=v.log.slice(0,R.current),O=v.log.slice(R.current),B=!!v.permissionPrompt,N=we(async()=>{x.current?(S.current&&clearTimeout(S.current),await(g?.()),process.exit(0)):(x.current=!0,C(!0),S.current=setTimeout(()=>{x.current=!1,C(!1)},2e3))},[g]);o((e,t)=>{t.ctrl&&"c"===e&&N().catch(()=>process.exit(1))},{isActive:s}),be(()=>{if(B||!b)return;const e=e=>{const t=e.toString();""!==t&&"[1;5~"!==t?""!==t&&"[4;5~"!==t?""!==t&&"[1~"!==t&&"OH"!==t&&"[7~"!==t?""!==t&&"[4~"!==t&&"OF"!==t&&"[8~"!==t||E(e=>({...e,cursor:m(e.value,e.cursor)})):E(e=>({...e,cursor:h(e.value,e.cursor)})):E(e=>({...e,cursor:e.value.length})):E(e=>({...e,cursor:0}))};return process.stdin.on("data",e),()=>{process.stdin.off("data",e)}},[B,b,I]),o((e,t)=>{if(!t.ctrl||"c"!==e){if(t.return){const e=I.trim();return e&&b?.(e),void E({value:"",cursor:0})}t.ctrl&&"w"===e||t.ctrl&&t.backspace?E(e=>{const t=p(e.value,e.cursor);return{value:e.value.slice(0,t)+e.value.slice(e.cursor),cursor:t}}):!t.backspace&&!t.delete||t.ctrl?t.ctrl&&t.leftArrow||t.meta&&"b"===e?E(e=>({...e,cursor:p(e.value,e.cursor)})):t.ctrl&&t.rightArrow||t.meta&&"f"===e?E(e=>({...e,cursor:f(e.value,e.cursor)})):t.leftArrow?E(e=>({...e,cursor:Math.max(0,e.cursor-1)})):t.rightArrow?E(e=>({...e,cursor:Math.min(e.value.length,e.cursor+1)})):t.ctrl&&"a"===e?E(e=>({...e,cursor:0})):t.ctrl&&"e"===e?E(e=>({...e,cursor:e.value.length})):!e||t.ctrl||t.meta||t.escape||e.includes("")||/^\[./.test(e)||/^O[A-D]$/.test(e)||E(t=>({value:t.value.slice(0,t.cursor)+e+t.value.slice(t.cursor),cursor:t.cursor+e.length})):E(e=>e.cursor>0?{value:e.value.slice(0,e.cursor-1)+e.value.slice(e.cursor),cursor:e.cursor-1}:e)}},{isActive:s&&!!b&&!B});const $=ve(()=>"running"===v.status?_e(a,{label:v.runningLabel??"Working"}):"success"!==v.status?_e(n,{color:"red",children:"✖ Failed"}):void 0,[v.runningLabel,v.status]),M=!(w||!b||"running"!==v.status||0!==v.log.length||v.resultText||v.errorText),j="running"===v.status&&!M||v.log.length>0||v.resultText||v.errorText||"running"!==v.status;return Ee(t,{flexDirection:"column",children:[_e(r,{items:["header"],children:()=>Ee(t,{flexDirection:"column",flexShrink:0,children:[_e(n,{color:"cyan",bold:!0,children:"Stably Agent"}),_e(t,{flexDirection:"column",marginTop:1,children:_e(n,{color:"gray",children:v.promptDisplay})})]},"header")}),D.length>0&&_e(r,{items:D,children:e=>u(e)}),O.length>0&&_e(t,{flexDirection:"column",children:O.map(e=>u(e))}),"error"===v.status&&v.errorText&&_e(t,{marginTop:1,children:_e(n,{color:"red",children:v.errorText})}),"success"===v.status&&v.resultText&&_e(t,{marginTop:1,children:_e(n,{children:v.resultText})}),j&&_e(t,{flexDirection:"column",flexShrink:0,marginTop:1,children:"running"===v.status&&v.fixProgress?Ee(t,{flexDirection:"column",children:[Ee(t,{children:[_e(a,{}),_e(n,{children:" "}),_e(c,{progress:v.fixProgress})]}),"fixing"===v.fixProgress.phase&&v.log.flatMap(e=>{const{subagent:r}=e;if("subagent"!==e.kind||"fix-worker"!==r?.subagentType||"running"!==r.status)return[];const{activities:o}=r,s=o.filter(e=>"tool"===e.kind).length,i=o.at(-1),c=o.filter(e=>"tool"===e.kind).at(-1),l=(()=>{if(!i)return null;if("tool"===i.kind)return null;if("text"===i.kind){const e=i.content.trim().split("\n").at(-1)?.trim();return e?e.length>80?`${e.slice(0,80)}…`:e:null}if("tool_result"===i.kind){const e=i.content.trim().split("\n")[0]?.trim();return e?e.length>80?`${e.slice(0,80)}…`:e:null}return null})();return Ee(t,{flexDirection:"column",children:[Ee(n,{children:[" ",_e(a,{}),Ee(n,{color:"gray",children:[r.description||"fix-worker",s>0?` (${s} ${1===s?"cycle":"cycles"})`:""]})]}),c&&Ee(n,{color:"gray",dimColor:!0,children:[" • ",c.content]}),l&&Ee(n,{color:"gray",dimColor:!0,children:[" ",l]})]},e.id)})]}):"success"!==v.status&&"error"!==v.status||!v.fixProgress?$:_e(l,{progress:v.fixProgress})}),null!=v.permissionPrompt&&null!=y&&_e(i,{onChoice:y,prompt:v.permissionPrompt}),null!=b&&null==v.permissionPrompt&&!v.isExiting&&Ee(t,{borderColor:"gray",borderStyle:"round",flexDirection:"column",flexShrink:0,marginTop:1,paddingX:1,paddingY:0,children:[_e(n,{color:"gray",children:"Type a message and press Enter. Press Ctrl+C to exit."}),Ee(n,{children:[_e(n,{color:"yellow",children:">"})," ",I.slice(0,T),_e(e,{}),I.slice(T)]})]}),A&&Ee(t,{marginTop:1,flexDirection:"column",children:[_e(n,{color:"yellow",children:"Press Ctrl+C again to exit"}),Pn&&Ee(n,{color:"gray",children:["Debug log: ",Dn]})]})]})}})({Cursor:l,inkComponents:{Box:r,Static:n,Text:o,useInput:i},isRawModeSupported:a,PermissionPrompt:u,Spinner:({label:e})=>{const[t,r]=ge(0);return be(()=>{const e=setInterval(()=>r(e=>(e+1)%c.length),80);return()=>clearInterval(e)},[]),Ee(o,{color:"yellow",children:[c[t]," ",e]})}});let p=e;t?.isFixMode&&(p.fixProgress={phase:"initializing",totalTests:null,fixedTests:0,failedTests:0,currentTestDescription:null,lastTestDescription:null,startedAt:Date.now(),endedAt:null,isError:!1});const f={current:(e,t)=>{}},h=s(_e(d,{onExit:t?.onExit,onPermissionChoice:(e,t)=>f.current(e,t),onSend:t?.onSend,showSpinnerImmediately:t?.showSpinnerImmediately,state:p}),{exitOnCtrlC:!1}),m=()=>{p={...p},h.rerender(_e(d,{onExit:t?.onExit,onPermissionChoice:(e,t)=>f.current(e,t),onSend:t?.onSend,showSpinnerImmediately:t?.showSpinnerImmediately,state:p}))},g=({text:e})=>{e&&(p.log=[...p.log,{content:e,id:p.log.length,kind:"user"}],m())},y=new Map;return{addSubagentActivity:({toolUseId:e,kind:t,content:r})=>{const n=y.get(e);if(void 0===n)return void console.error("[addSubagentActivity] No entry index for toolUseId:",e);const o=p.log[n];if(o&&"subagent"===o.kind&&o.subagent){if("text"===t){const e=o.subagent.activities.at(-1);e&&"text"===e.kind?e.content+=r:o.subagent.activities.push({id:o.subagent.activities.length,kind:"text",content:r.replace(/^\s*\n+/,"")})}else o.subagent.activities.push({id:o.subagent.activities.length,kind:t,content:r});p.log=[...p.log],m()}else console.error("[addSubagentActivity] Entry not found or not subagent:",{entryIndex:n,entryKind:o?.kind})},addSubagentStart:({toolUseId:e,subagentType:t,description:r})=>{const n=p.log.length;if(y.set(e,n),p.log=[...p.log,{content:"",id:n,kind:"subagent",subagent:{toolUseId:e,subagentType:t,description:r,status:"running",activities:[]}}],p.fixProgress)if("triage"===t&&"initializing"===p.fixProgress.phase)p.fixProgress={...p.fixProgress,phase:"triage"};else if("fix-worker"===t){const e=(p.fixProgress.totalTests??0)+1,t=r||null;p.fixProgress={...p.fixProgress,phase:"fixing",totalTests:e,currentTestDescription:t,lastTestDescription:t??p.fixProgress.lastTestDescription}}else"validation"===t?p.fixProgress={...p.fixProgress,phase:"validation",currentTestDescription:null}:"context"===t&&(p.fixProgress={...p.fixProgress,currentTestDescription:r||p.fixProgress.currentTestDescription});m()},addTool:({rawName:e,toolInput:t})=>{const r=qo(e),n=Ko(e,t),o=n?`${r} (${n})`:r;p.log=[...p.log,{content:o,id:p.log.length,kind:"tool"}],m()},addToolResult:({message:e})=>{p.log=[...p.log,{content:e,id:p.log.length,kind:"tool_result"}],m()},appendText:({text:e})=>{if(!e)return;const t=p.log.at(-1),r=t&&"text"===t.kind?e:e.replace(/^\s*\n+/,"");t&&"text"===t.kind?p.log=[...p.log.slice(0,-1),{...t,content:`${t.content}${r}`}]:p.log=[...p.log,{content:r,id:p.log.length,kind:"text"}],m()},appendUserMessage:g,cleanup:async()=>{const e=h.waitUntilExit();h.unmount(),await e},setExiting:()=>{p.isExiting=!0,m()},setRunningLabel:({label:e})=>{p.runningLabel=e,m()},setStatus:({error:e,result:t,status:r})=>{p.errorText=e,p.resultText=t,p.status=r,m()},setSubagentStatus:({toolUseId:e,status:t})=>{const r=y.get(e);if(void 0===r)return;const n=p.log[r];n&&"subagent"===n.kind&&n.subagent&&(n.subagent.status=t,p.fixProgress&&"fix-worker"===n.subagent.subagentType&&("complete"===t?p.fixProgress={...p.fixProgress,fixedTests:p.fixProgress.fixedTests+1,currentTestDescription:null}:"error"===t&&(p.fixProgress={...p.fixProgress,failedTests:p.fixProgress.failedTests+1,currentTestDescription:null})),p.log=[...p.log],m(),"complete"!==t&&"error"!==t||y.delete(e))},showPermissionPrompt:e=>new Promise(t=>{f.current=(r,n)=>{if(p.permissionPrompt=void 0,m(),"allow"===r)t({behavior:"allow",updatedInput:e.input});else if("always"===r)t({behavior:"allow",updatedInput:e.input,updatedPermissions:e.suggestions});else{const e=n??"User denied this action";g({text:e}),t({behavior:"deny",message:e,interrupt:!1})}},p.permissionPrompt={...e,resolve:t},m()}),updateFixProgress:t?.isFixMode?e=>{p.fixProgress&&(p.fixProgress={...p.fixProgress,...e},m())}:void 0}})(v,"chat"===e.mode||"init"===e.mode?{onExit:()=>le.current(),onSend:e=>ce.current(e),showSpinnerImmediately:"init"===e.mode}:"fix"===e.mode?{onExit:()=>le.current(),isFixMode:!0}:void 0);let Pe=v.status;const Ue=({error:e,result:t,status:r})=>{Pe=r,Ae({error:e,result:t,status:r})};let ke;ce.current=e=>{const t=e.trim();if(y&&!Fn.getLogFilePath()&&Fn.initSession(t||"chat"),Fn.debug("User message",{text:t}),"/help"===t){x&&b&&(S=!0,_?.interrupt?.(),b.allowNextTurn(),x=!1),"running"===Pe&&Ue({status:"success"}),me({text:e});const t=w?.();return void he({text:t??"Help is not available in this session."})}const r=I||A&&x;if(y&&(C+=1,T=void 0,r||(P=!1,Se({label:void 0}))),b){if(r)return Ue({status:"running"}),me({text:e}),void U.push(e);if(!A||x||I||(A=!1),x)return Ue({status:"running"}),me({text:e}),b.pushText(e),void(R+=1);Ue({status:"running"}),me({text:e}),b.pushText(e),x=!0}};const Le=[];let De;const Oe=await(async e=>{try{const t=await sn(e,"stably.yaml");if(!t)return void Fn.debug("No stably.yaml found");const r=await V(t,"utf-8");if(!r.trim())return;const n=Te(r),o=ea.parse(n.toJS()),s=o.agent?.fix?.maxTurnsPerIssue,i=o.agent?.fix?.maxParallelWorkers,a=!!o.agent?.fix?.rules;return Fn.debug(`Loaded stably.yaml: maxTurnsPerIssue=${s??"default"}, maxParallelWorkers=${i??"default"}, hasRules=${a}`,{path:t,config:o.agent}),o}catch(e){return void Fn.warn("Failed to parse stably.yaml",{error:e})}})(u),Be=Oe?.agent?.fix?.skipAfterConsecutiveUnfixed,Ne=await(async()=>{if("single"===e.mode||"build"===e.mode){const r=await async function(e,t){const r=n(e);if(t){const e=n(r,t);return Fo(e,"output-flag"),{path:e,source:"output-flag"}}const i=Mo(r);if(i){const e=await async function(e){try{const t=(await V(e,"utf-8")).match(/testDir:\s*['"]([^'"]+)['"]/);return t?.[1]}catch{return}}(i);if(e){const t=n(o(i),e);if(Ho(t))return Fo(t,"playwright.config.ts"),{path:t,source:"playwright.config.ts"}}}for(const e of jo){const t=s(r,e);if(Ho(t))return Fo(t,"auto-detected"),{path:t,source:"auto-detected"}}return Fo(r,"cwd-fallback"),{path:r,source:"cwd-fallback"}}(u,e.outputDir);return De=r.path,t=e.prompt,`${(Array.isArray(t)?t.join(" "):t).trim()||"Create tests based on the changes in the current PR or branch. If the user references a specific PR number or branch name, first checkout that PR/branch using `gh pr checkout <number>` or `git checkout <branch>`. Use the Pull Request Context or Git Branch Context section of the system prompt to understand what code was changed, then create appropriate tests for the new or modified functionality. After generating the tests, run them locally (e.g. `pnpm stably test` or the repo's test command) and iterate until the new tests pass."}\n\n[Output directory: ${De}]`}var t;if("fix"===e.mode)try{Fn.info("[fix] Fetching autoheal context",{runId:e.runId,skipAfterConsecutiveUnfixed:Be});const t=Date.now(),{context:r,autohealReportUrl:n,skippedTests:o}=await(async({authHeader:e,orgId:t,runId:r,skipAfterConsecutiveUnfixed:n})=>{Fn.debug("Fetching autoheal context",{runId:r,skipAfterConsecutiveUnfixed:n});const o=await(s={auth:e,client:Zr(),headers:Qn(t),path:{runId:r},query:null!=n?{skipAfterConsecutiveUnfixed:n}:{}},(s.client??Gr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-context",...s}));var s;if(404===o.response.status)throw Fn.warn("Autoheal context not found",{runId:r,status:404}),new Error(`Run ID "${r}" was not found.`);if(401===o.response.status)throw Fn.warn("Autoheal context fetch unauthorized",{runId:r,status:401}),new Error("Unauthorized: failed to fetch autoheal context (401).");if(422===o.response.status)throw Fn.warn("Autoheal context fetch invalid request",{runId:r,status:422,error:o.error?.error}),new Error(o.error?.error??"Failed to fetch autoheal context (422).");if(!o.error){const e=Zn.safeParse(o.data);if(e.success)return Fn.debug("Autoheal context fetched successfully",{runId:r,contextSize:e.data.context.length,skippedTestCount:e.data.skippedTests?.length??0}),{context:e.data.context,autohealReportUrl:e.data.autohealReportUrl,skippedTests:e.data.skippedTests??[]};throw Fn.warn("Autoheal context response invalid",{runId:r}),new Error("Autoheal context response missing or invalid context.")}throw Fn.warn("Autoheal context fetch failed",{runId:r,error:o.error}),new Error("Failed to fetch autoheal context")})({authHeader:c,orgId:l,runId:e.runId,skipAfterConsecutiveUnfixed:Be});if(Fn.info("[fix] Autoheal context fetched",{runId:e.runId,durationMs:Date.now()-t,contextLength:r.length,skippedTestCount:o.length}),ke=n,o.length>0){Fn.info(`[fix] Skipping ${o.length} test(s) that failed to be fixed ${Be}+ consecutive times`);for(const e of o)Fn.info(`[fix] Skipped: ${e.testIdentifier} — ${e.testTitle} (unfixed ${e.consecutiveUnfixedCount}x)`)}return r.includes("No failing tests to fix (all were skipped).")&&(Fn.info("[fix] All failing tests were skipped — nothing to fix"),Ue({status:"success",result:`All failing tests skipped (unfixed ${Be}+ consecutive times). Nothing to fix.`}),await Ie(),process.exit(0)),K||(Fn.info("[fix] Creating WebSocket progress reporter"),K=new io({authHeader:c,orgId:l,runId:e.runId,onUserMessage:e=>{if(Fn.info("[ws] Injecting web UI message into fix agent",{contentLength:e.length}),X(ia,{type:"user_message",summary:e}),Q({type:"user_message",summary:e}),me({text:`[Web] ${e}`}),!x)return b.pushText(`[Message from web UI user]: ${e}`),x=!0,void b.allowNextTurn();O||Date.now()-N<2e3?b.pushText(`[Message from web UI user]: ${e}`):(D.push(e),k&&clearTimeout(k),k=setTimeout(()=>{k=void 0;const e=[...D];D=[],N=Date.now(),Ct(e)},500))}}),K.start(),ee({phase:"initializing"})),te("STARTED"),r}catch(e){const t=e instanceof Error?e.message:"Failed to fetch autoheal context.";Fn.error("[fix] Failed to fetch autoheal context",{error:t}),Ue({error:t,status:"error"}),await Ie(),process.exit(1)}return"init"===e.mode?"Please analyze this project and set up Playwright with the Stably SDK. Check for existing configurations and install the necessary dependencies.":""})(),$e=await async function(e){const t=r.resolve(e),n=r.join(t,"tests"),o=r.join(n,"helpers"),s=r.join(n,"assets"),i=function(e){const t=r.resolve(e);if(g(t))for(const e of ko){const n=r.join(t,`playwright.config${e}`);if(g(n))return n}}(t)??r.join(t,"playwright.config.ts"),a=r.basename(i),c=r.join(n,"seed.spec.ts"),[l,u,d,p,f,h]=await Promise.all([Oo({defaultContent:"Unable to read directory",dirName:"working directory",dirPath:t}),Oo({defaultContent:"Unable to read directory",dirName:"tests directory",dirPath:n}),Oo({defaultContent:"Directory does not exist yet",dirName:"helpers directory",dirPath:o}),Oo({defaultContent:"Directory does not exist yet",dirName:"assets directory",dirPath:s}),Do({defaultContent:"File does not exist or could not be read",fileName:a,filePath:i}),Do({defaultContent:"File does not exist or could not be read",fileName:"seed.spec.ts",filePath:c})]);return{absolutePath:t,directories:{assets:p,helpers:d,root:l,tests:u},files:{playwrightConfig:f,playwrightConfigFilename:a,seedSpec:h}}}(u),Me=Oe?.agent?.fix?.maxTurnsPerIssue,je=Oe?.agent?.fix?.maxParallelWorkers,He=Oe?.agent?.fix?.rules,Fe="fix"===e.mode||"single"===e.mode||"build"===e.mode,Ge="single"===e.mode||"build"===e.mode?await(async e=>{const t=await ta(e,"STABLY-CREATE.md");return t?.content})(u):void 0,Ye=await(e=>ta(e,"STABLY.md"))(u),We=Ye?.content;Fn.info("[fix] Fetching system prompt and subagent definitions",{mode:e.mode,maxTurnsOverride:Me,hasCustomRules:!!He,hasCreateRules:!!Ge,hasStablyMd:!!We,stablyMdPath:Ye?.path}),Ye&&Fn.info(`STABLY.md loaded (${Ye.content.length} chars)`,{path:Ye.path});const Ve=Date.now(),[{systemPrompt:ze,prContext:Ke},qe]=await Promise.all([Bo({allowedEnvVars:Object.keys(f),mode:e.mode,workspaceInfo:$e,authHeader:c,customHeader:"single"===e.mode||"build"===e.mode?e.customHeader:void 0,maxParallelWorkers:"fix"===e.mode?je:void 0}),Fe?qi({authHeader:c,mode:e.mode,maxTurnsOverride:Me}):Promise.resolve({})]);Fn.info("[fix] System prompt and subagents fetched",{durationMs:Date.now()-Ve,systemPromptSize:ze.length,subagentCount:Object.keys(qe).length,maxTurnsOverride:Me??"default",hasPrContext:!!Ke});const Je={...f,...process.env},Xe={};for(const[e,t]of Object.entries(Je))Ki.has(e)||void 0===t||(Xe[e]=t);const Qe=!0;Fn.debug("AI proxy configuration",{useStablyAiProxy:Qe,wantsBypassProxy:!1,wantsUseOllama:!1}),Fn.info("[fix] Acquiring AI proxy key",{useStablyAiProxy:Qe});const Ze=Date.now(),et=await async function({auth:e,client:t,source:r,metadata:n,duration:o}){try{const i=await(s={auth:e,client:t,body:{source:r,metadata:n??{},duration:o}},(s.client??Gr).post({security:[{scheme:"bearer",type:"http"}],url:"/v1/proxy/api-key",...s,headers:{"Content-Type":"application/json",...s.headers}})),a=i.response;if(i.error){const e="object"==typeof i.error&&"error"in i.error?i.error.error:"Unknown error";return{error:zi(e,a)}}return i.data?{key:i.data.key}:{error:zi("No data in response",a)}}catch(e){const t=e instanceof Error?e.message:"Unknown error";return{error:zi(t)}}var s}({auth:c,client:Zr(),source:"cli"}),tt=et?.key;if(Fn.info("[fix] AI proxy key acquired",{durationMs:Date.now()-Ze,success:!!tt,hasError:!!et?.error}),!tt){const e=et?.error?.message?`Unable to make AI calls: ${et.error.message}`:"Unable to make AI calls. Check if you are authenticated.";Fn.warn("Failed to get proxy API key",{error:et?.error?.message}),Ue({error:e,status:"error"}),await Ie(),Fn.flush(),Fn.printLogFileInfo(),process.exit(1)}Fn.debug("Proxy API key acquired",{success:!!tt});const rt=await Xn(),nt=rt?Object.fromEntries(Object.entries(Jn(rt)).filter(e=>null!=e[1])):void 0,ot="init"===e.mode,st="fix"===e.mode,it=st?_r.createLocal({workingDir:u}):void 0;it&&await it.captureSnapshot();const at=ot?Gi({onComplete:()=>{Ue({status:"success"}),xe(),b?.finish(),process.exit(0)}}):y?Gi({onRestartRequested:()=>{y&&(A=!0,Ue({status:"running"}),Se({label:"Restarting browser tools..."}),T={createdAtUserMessageSeq:C,attempts:0})}}):void 0,ct=at?y?{"stably-agent-control":at}:{"session-control":at}:{},lt=re&&Ke?["mcp__create-report"]:[],ut=ot?oa:[...ra,...st?["mcp__auto-heal-report"]:[],...lt],dt=ot?oa:y?[...na,"mcp__stably-agent-control"]:[...na,...lt],pt=re&&Ke?{"create-report":Wi({prContext:Ke,authHeader:c,orgId:l,onReportPosted:e=>{ie({githubComment:{url:e.commentUrl,prNumber:Ke.prNumber}})}})}:{},ft=ot?ct:st&&it?{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:nt},"auto-heal-report":Fi({authHeader:c,diffTracker:it,orgId:l,runId:e.runId,workingDir:u}),...ct}:{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:nt},...ct,...pt},ht="single"===e.mode||"build"===e.mode,mt=ot?[]:[{hooks:[async e=>{const t=po(e);if(!t)return{decision:"approve"};let r=!1;const n=t.map(e=>lo(e)?e.text.length<=4e4?e:(r=!0,{...e,text:`${e.text.slice(0,4e4)}...[truncated to 40000 characters]`}):e);return r?{decision:"approve",hookSpecificOutput:{hookEventName:"PostToolUse",updatedMCPToolOutput:n}}:{decision:"approve"}}],matcher:"mcp__playwright-test__.*"},{matcher:"mcp__playwright-test__test_run",hooks:[bo({onResult:e=>fe({message:e})})]},{matcher:"mcp__playwright-test__test_debug",hooks:[wo({onResult:e=>fe({message:e})})]},...ht?[{matcher:"Write",hooks:[_o({onFileCreated:e=>{Le.push(e),se&&ie({filesCreated:[...se.filesCreated,e]})}})]}]:[],{matcher:"Write",hooks:[Ro({workDir:u})]},{matcher:"Edit",hooks:[Ro({workDir:u})]}],gt=ot?[]:[{matcher:"mcp__playwright-test__browser_type",hooks:[yo({envVars:f})]}],yt=Object.keys(qe).length>0?qe:void 0,bt={...Xe};bt.MCP_TOOL_TIMEOUT=String(6e5),tt&&(bt.ANTHROPIC_API_KEY=tt,bt.ANTHROPIC_BASE_URL=qr,bt.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS="1");const wt=process.env.STABLY_AGENT_MODEL??"claude-opus-4-6",vt=He?`\n\n## Custom Rules\n${He}`:"",_t=Ge?`\n\n## Custom Test Generation Rules\n${Ge}`:"",Et=We?`\n\n## Project Rules (STABLY.md)\n${We}`:"",It=ze+vt+_t+Et;Fn.debug("[fix] Final system prompt assembled",{baseSize:ze.length,fixRulesSize:vt.length,createRulesSize:_t.length,stablyMdSize:Et.length,finalSize:It.length});const Tt=function(){const e=function(){const e=function(){const e=process.env.STABLY_PLUGIN_PATH?.trim();if(!e)return;const t=r.isAbsolute(e)?e:r.resolve(process.cwd(),e);return Zi(t)?t:void 0}();if(e)return e;const t=r.join(Ji,"stably-plugin");if(Zi(t))return t;for(const e of function*(e){let t=r.resolve(e);for(;;){yield t;const e=r.dirname(t);if(e===t)return;t=e}}(Ji))for(const t of Qi){const n=r.join(e,t);if(Zi(n))return n}}();if(e)return{type:"local",path:e}}(),xt=()=>(Fn.info("[fix] Starting SDK query",{model:wt,tools:ut,mcpServers:Object.keys(ft),resumeSessionId:E??null,subagentsEnabled:!!yt,subagentCount:Object.keys(qe).length,useStablyAiProxy:Qe,aiProxyUrl:qr,anthropicBaseUrl:void 0,stablyPluginPath:Tt?.path,stablyPluginExists:!!Tt}),M({options:{executableArgs:["--max-old-space-size=4096"],tools:ut,allowedTools:dt,betas:[],canUseTool:(e,t)=>(Fn.debug("[fix] canUseTool called",{toolName:e}),Promise.resolve({behavior:"allow",updatedInput:t})),cwd:u,env:bt,hooks:{PostToolUse:mt,PreToolUse:gt},includePartialMessages:!0,agents:yt,mcpServers:ft,model:wt,permissionMode:"default",plugins:Tt?[Tt]:void 0,systemPrompt:It,...E?{resume:E}:{}},prompt:b??Ne})),St=()=>{if(b&&0!==U.length){for(const e of U)b.pushText(e);U.length=0,x=!0,Ue({status:"running"})}},At=async()=>{y&&(I||(I=(async()=>{Fn.info("Restarting MCP servers for chat mode"),Ue({status:"running"}),Se({label:"Restarting browser tools..."});try{await(_?.interrupt?.())}catch(e){Fn.warn("Failed to interrupt response during MCP restart",{error:e instanceof Error?e.message:String(e)})}await Io(),b?.finish(),b=new Po,R=0,x=!1,S=!1,$.clear(),_=xt(),P=!0,Se({label:"Restarting browser tools..."}),y&&b&&T&&(T.createdAtUserMessageSeq===C?T.attempts>=1||U.length>0?T=void 0:(T.attempts+=1,b.pushText(["[SYSTEM] MCP servers were restarted successfully.","Continue the task using existing conversation context.","Do not ask the user to resend their message unless new input is required."].join("\n")),T=void 0,x=!0,Ue({status:"running"})):T=void 0),St()})().finally(()=>{I=void 0,St()})),await I)},Ct=async e=>{if(h&&x&&!O&&!L)L=(async()=>{Fn.info("[fix] Interrupting for user message",{messageCount:e.length,phase:q?.phase});try{await(_?.interrupt?.())}catch(e){Fn.warn("[fix] Failed to interrupt response for user message",{error:e instanceof Error?e.message:String(e)})}await Io(),b?.finish(),b=new Po,$.clear(),_=xt();const t=e.map(e=>`[Message from web UI user]: ${e}`).join("\n\n");b.pushText(`[SYSTEM] The user sent a message while you were working. Read their message below, incorporate their feedback, and continue your task. Do not restart from scratch unless the user explicitly asks.\n\n${t}`),B=!0,x=!0})().finally(()=>{L=void 0}),await L;else for(const t of e)b?.pushText(`[Message from web UI user]: ${t}`)};if(tt){const e=qr,t=`${e.replace(/\/$/,"")}/v1/messages`;Fn.debug(`[fix] Pre-flight: POST ${t}`);const r=Date.now();try{const e=await fetch(t,{method:"POST",signal:AbortSignal.timeout(1e4),headers:{"x-api-key":tt,"anthropic-version":"2023-06-01","content-type":"application/json"},body:"{}"}),n=await e.text().catch(()=>""),o=Date.now()-r;Fn.debug(`[fix] Pre-flight: ${e.status} in ${o}ms — ${n.slice(0,300)}`),401===e.status||403===e.status?Fn.error(`[fix] Pre-flight: AI proxy key rejected (${e.status}) at ${t}`):Fn.info("[fix] Pre-flight: AI proxy key valid",{status:e.status,durationMs:o})}catch(t){Fn.error("[fix] Pre-flight: AI proxy unreachable",{error:t instanceof Error?t.message:String(t),durationMs:Date.now()-r,url:e})}}Fn.info("[fix] Creating initial agent query"),Fn.flush(),_=xt(),Fn.info("[fix] Agent query created, entering message loop"),"chat"!==e.mode&&b.pushText(Ne),le.current=async()=>{F="CANCELED",await te("CANCELED"),ee({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:Z(!0)}),K?.close(),ie({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0}),oe?.close(),k&&(clearTimeout(k),k=void 0),Fn.flush(),xe();try{await(_?.interrupt?.())}catch{}b?.finish(),Ie()};let Rt=0,Pt=null;const Ut=setInterval(()=>{const e=Date.now()-z;Pt?Fn.info("[fix] Watchdog: message loop active",{messageCount:Rt,elapsed:e}):Fn.info("[fix] Watchdog: waiting for first SDK message",{elapsed:e}),Fn.flush()},15e3);Ut.unref();try{let t=!1;for(;;){if(!_){Fn.info("[fix] No response object, exiting message loop");break}t=!1,Fn.info("[fix] Entering for-await on SDK response");for await(const r of _){Rt++,Pt||(Pt=Date.now(),Fn.info("[fix] First SDK message received",{waitDurationMs:Pt-z,messageType:r.type,messageSubtype:"subtype"in r?r.subtype:void 0}));const n="session_id"in r&&"string"==typeof r.session_id?r.session_id:void 0;if(n&&n!==E&&(E=n,Fn.debug("Captured Claude session id",{sessionId:E})),"stream_event"===r.type){const{event:e}=r;(Rt<=5||Rt%200==0)&&Fn.debug("[fix] Stream event",{msgNum:Rt,eventType:e?.type});const t=e&&"object"==typeof e&&"parent_tool_use_id"in e&&"string"==typeof e.parent_tool_use_id?e.parent_tool_use_id:void 0;if("content_block_delta"===e?.type){const{delta:r}=e;if("text_delta"===r?.type&&r.text){if(y&&A&&!t)continue;P&&(P=!1,Se({label:void 0})),t&&$.has(t)?ue({toolUseId:t,kind:"text",content:r.text}):he({text:r.text})}}"message_stop"===e?.type&&b&&(O=!1,b.allowNextTurn());continue}if("assistant"===r.type){const t="parent_tool_use_id"in r&&"string"==typeof r.parent_tool_use_id?r.parent_tool_use_id:void 0,{content:n}=r.message??{};if(Array.isArray(n)&&!t){const t=n.filter(e=>e&&"object"==typeof e&&"type"in e&&"text"===e.type).map(e=>e&&"object"==typeof e&&"text"in e&&"string"==typeof e.text?e.text:void 0).filter(Boolean).join("");t&&(Fn.debug("Assistant message",{text:t}),"fix"===e.mode&&(X(ia,{type:"ai_message",summary:t.slice(0,200)}),Q({type:"ai_message",summary:t.slice(0,200)})),re&&ae({type:"ai_message",summary:t.slice(0,200)}))}if($.size>0){const e=Array.isArray(n)?n.filter(e=>e&&"object"==typeof e&&"type"in e&&"tool_use"===e.type).map(e=>e&&"object"==typeof e&&"name"in e&&"string"==typeof e.name?e.name:void 0):[];Fn.debug("Assistant message with active subagents",{hasParentToolUseId:!!t,parentToolUseId:t,activeSubagentIds:Array.from($.keys()),toolNames:e,fullMessageKeys:Object.keys(r),rawMessage:JSON.stringify(r).slice(0,500)})}if(Array.isArray(n))for(const r of n){if("tool_use"===r?.type){if("mcp__auto-heal-report__generate-report"===r.name&&(O=!0),"mcp__session-control__restart_mcp_servers"===r.name||"mcp__stably-agent-control__restart_mcp_servers"===r.name){pe({rawName:r.name,toolInput:r.input});continue}if(r.name.startsWith("mcp__session-control__")||r.name.startsWith("mcp__stably-agent-control__"))continue;if(aa(r.name))continue;if($.size>0&&Fn.debug("Tool use detected with active subagents",{toolName:r.name,hasParentToolUseId:!!t,parentToolUseId:t,wouldRouteToSubagent:!!t&&$.has(t),activeSubagentIds:Array.from($.keys())}),"Task"===r.name){const t=r.input,n=t&&"object"==typeof t?t:void 0,o=n&&"subagent_type"in n&&"string"==typeof n.subagent_type?n.subagent_type:"subagent",s=n&&"description"in n&&"string"==typeof n.description?n.description.trim():"";if(Fn.info("[fix] Subagent started",{subagentType:o,description:s,toolUseId:r.id,activeSubagentCount:$.size+1}),$.set(r.id,{subagentType:o,description:s}),de({toolUseId:r.id,subagentType:o,description:s}),"fix"===e.mode){if("triage"===o){Re?.({phase:"triage"});const e={id:r.id,testDescription:"Triage",workerType:"triage",status:"running",summary:null,startedAt:Date.now(),endedAt:null,activity:[]};ee({phase:"triage",workers:[...q?.workers??[],e]})}else if("fix-worker"===o){J.add(s||r.id);const e={id:r.id,testDescription:s||r.id,workerType:"fix-worker",status:"running",summary:null,startedAt:Date.now(),endedAt:null,activity:[]};Re?.({phase:"fixing",totalTests:J.size,currentTestDescription:s||null}),ee({phase:"fixing",totalTests:J.size,currentTestDescription:s||null,lastTestDescription:s||q?.lastTestDescription||null,workers:[...q?.workers??[],e]})}else"validation"===o?(Re?.({phase:"validation",currentTestDescription:null}),ee({phase:"validation",currentTestDescription:null})):"context"===o&&ee({currentTestDescription:s||null});Q({type:"tool_call",summary:`[${o}] ${s}`.trim()})}continue}if(t&&$.has(t)){const n=qo(r.name),o=Ko(r.name,r.input),s=o?`${n} (${o})`:n;if(Fn.debug("Subagent tool called",{tool:r.name,parentToolUseId:t}),ue({toolUseId:t,kind:"tool",content:s}),"fix"===e.mode){Q({type:"tool_call",summary:s});const e=$.get(t);"fix-worker"!==e?.subagentType&&"triage"!==e?.subagentType||X(t,{type:"tool_call",summary:s})}continue}if(t&&Fn.debug("Tool with parent_tool_use_id but no matching subagent",{tool:r.name,parentToolUseId:t,activeSubagentIds:Array.from($.keys())}),Fn.debug("Tool called",{tool:r.name,input:r.input}),pe({rawName:r.name,toolInput:r.input}),"fix"===e.mode){const e=qo(r.name),t=Ko(r.name,r.input),n=t?`${e} (${t})`:e;X(ia,{type:"tool_call",summary:n}),Q({type:"tool_call",summary:n})}if(re){const e=qo(r.name),t=Ko(r.name,r.input),n=t?`${e} (${t})`:e;"initializing"===se?.phase?ie({phase:"generating",currentActivity:n}):"mcp__playwright-test__test_run"===r.name&&"generating"===se?.phase?ie({phase:"testing",currentActivity:n}):ie({currentActivity:n}),ae({type:"tool_call",summary:n})}}if("text"===r?.type&&t&&$.has(t)){const n="string"==typeof r.text?r.text:"";if(n&&(ue({toolUseId:t,kind:"text",content:n}),"fix"===e.mode)){const e=$.get(t);"fix-worker"!==e?.subagentType&&"triage"!==e?.subagentType||X(t,{type:"ai_message",summary:n.slice(0,200)})}}}continue}if("user"===r.type){const t="message"in r&&r.message&&"object"==typeof r.message&&"content"in r.message?r.message.content:void 0;if(Array.isArray(t))for(const r of t)if(r&&"object"==typeof r&&"type"in r&&"tool_result"===r.type&&"tool_use_id"in r){const t="string"==typeof r.tool_use_id?r.tool_use_id:void 0,n="is_error"in r&&!0===r.is_error,o="content"in r&&"string"==typeof r.content?r.content:void 0;if(Fn.debug("Tool result",{toolUseId:t,isError:n,output:o?.slice(0,500)}),t&&$.has(t)){const r=$.get(t);if(Fn.info("[fix] Subagent completed",{toolUseId:t,isError:n,subagentType:r?.subagentType,description:r?.description,activeSubagentCount:$.size-1}),Ce({toolUseId:t,status:n?"error":"complete"}),"fix"===e.mode&&"triage"===r?.subagentType){const e=n?"failed":"succeeded",r=o?o.slice(0,500):null,s=(q?.workers??[]).map(n=>n.id===t?{...n,status:e,summary:r,endedAt:Date.now()}:n);ee({workers:s})}if("fix"===e.mode&&"fix-worker"===r?.subagentType){const e=n?"failed":"succeeded",r=o?o.slice(0,500):null,s=(q?.workers??[]).map(n=>n.id===t?{...n,status:e,summary:r,endedAt:Date.now()}:n);n?(Re?.({failedTests:(q?.failedTests??0)+1,currentTestDescription:null}),ee({failedTests:(q?.failedTests??0)+1,currentTestDescription:null,workers:s})):(Re?.({fixedTests:(q?.fixedTests??0)+1,currentTestDescription:null}),ee({fixedTests:(q?.fixedTests??0)+1,currentTestDescription:null,workers:s}))}$.delete(t)}}continue}if("result"===r.type){if(Fn.info("[fix] Agent result received",{subtype:r.subtype,messageCount:Rt,elapsed:Date.now()-z,activeSubagents:$.size,fixedTests:q?.fixedTests,failedTests:q?.failedTests,phase:q?.phase}),h){if("success"===r.subtype){k&&(clearTimeout(k),k=void 0);for(const e of D)b?.pushText(`[Message from web UI user]: ${e}`);if(D=[],(re||"fix"===e.mode)&&b){if(b.hasQueuedMessages()){Fn.info("[ws] Queued web UI messages found, continuing agent"),x=!0,b.allowNextTurn();continue}if(await ca(b,3e3)){Fn.info("[ws] Web UI message received during grace period, continuing agent"),x=!0,b.allowNextTurn();continue}b.finish()}if(Re?.({phase:"complete",currentTestDescription:null,endedAt:Date.now()}),ee({phase:"complete",currentTestDescription:null,endedAt:Date.now(),isError:!1,workers:Z(!1)}),ie({phase:"complete",endedAt:Date.now(),isError:!1,currentActivity:null}),ht&&Le.length>0){G.green("Created files:");for(const e of Le)G.green(`- ${e}`)}const t=(e,t)=>`]8;;${e}${t}]8;;`,r=ke?G.cyan(`📊 View Autoheal Report:\n ${t(ke,G.cyan(G.bold(G.underline(ke))))}`):void 0;Ue({status:"success",result:r}),F="COMPLETED"}else L||B?Fn.info("[fix] Suppressing error status: user-message interrupt in progress"):S?(F="CANCELED",ee({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:Z(!0)}),ie({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0})):(Re?.({endedAt:Date.now(),isError:!0}),ee({phase:"complete",endedAt:Date.now(),isError:!0,currentTestDescription:null,workers:Z(!0)}),ie({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),Ue({error:"Run failed.",status:"error"}),process.exitCode=1,F="FAILED");S=!1;break}const n=y&&A;if("success"!==r.subtype?S||(Ue({error:"Run failed.",status:"error"}),process.exitCode=1):Ue(n?{status:"running"}:{status:"success"}),x=!1,S=!1,n){A=!1,Fn.info("Processing deferred MCP restart request in chat mode"),await At(),t=!0;break}P=!1,Se({label:void 0}),b?.allowNextTurn(),y&&R>0&&(R-=1,x=!0,Ue({status:"running"}));continue}}if(L&&await L,B&&(B=!1,t=!0,Ue({status:"running"}),Fn.info("[fix] Resuming after user-message interrupt")),!t)break}}catch(e){S?(F="CANCELED",ee({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:Z(!0)}),ie({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0})):(Fn.error("[fix] Agent encountered an error",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0,elapsed:Date.now()-z}),Ue({error:`Agent encountered an error: ${e}`,status:"error"}),process.exitCode=1,F="FAILED",ee({phase:"complete",endedAt:Date.now(),isError:!0,currentTestDescription:null,workers:Z(!0)}),ie({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),Fn.flush(),Fn.printLogFileInfo())}finally{if(clearInterval(Ut),k&&(clearTimeout(k),k=void 0),Fn.info("[fix] Agent session ending",{finalStatus:F,elapsed:Date.now()-z,totalMessages:Rt}),x=!1,S=!1,process.off("uncaughtException",i),b?.finish(),F){Fn.info("[fix] Reporting final autoheal status",{status:F});const e=Date.now();await te(F),Fn.info("[fix] Final autoheal status reported",{durationMs:Date.now()-e})}if(Fn.info("[fix] Closing WebSocket progress reporter"),K?.close(),oe?.close(),st&&it){const t=Date.now();try{Fn.info("[fix] Computing diff...");const r=await it.computeDiff();if(r&&r.trim().length>0){Fn.info("[fix] Uploading diff...",{diffLength:r.length});const{diffBucketPath:n,uploadUrl:o}=await no({authHeader:c,contentType:"text/plain",orgId:l,runId:e.runId});await oo({contentType:"text/plain",diff:r,uploadUrl:o}),await so({authHeader:c,diffBucketPath:n,orgId:l,runId:e.runId}),Fn.info("[fix] Diff uploaded",{durationMs:Date.now()-t})}else Fn.info("[fix] No diff to upload (empty or no changes)")}catch(e){Fn.warn("[fix] Failed to upload diff",{error:e instanceof Error?e.message:String(e),durationMs:Date.now()-t})}}Fn.info("[fix] Cleaning up diff tracker"),await(it?.cleanup()),Fn.info("[fix] Running final cleanup"),await Ie(),Fn.info("[fix] Cleanup complete")}},ua=ce.object({runId:ce.string(),timestamp:ce.number()}),da=class{entries=[];warnings=[];runId;command;executionMode;constructor(e){this.runId=e.runId,this.command=e.command,this.executionMode=e.executionMode}phaseStart(e,t){this.addEntry({phase:e,level:"info",message:t}),te.info(function(e,t){return`${G.bold(G.cyan(`[${e}]`))} ${t}`}(e,t))}phaseEnd(e,t){this.addEntry({phase:e,level:"info",message:t})}info(e){this.addEntry({phase:e.phase,level:"info",message:e.message,fields:e.fields})}warn(e){this.addEntry({phase:e.phase,level:"warn",message:e.message,fields:e.fields}),te.warn(G.yellow(` warn: ${e.message}`))}error(e){this.addEntry({phase:e.phase,level:"error",message:e.message,fields:e.fields}),te.error(G.red(` error: ${e.message}`))}emitWarning(e){this.warnings.push(e),this.addEntry({phase:"summary",level:"warn",message:e.message,fields:{warningCode:e.code,...e.details}}),te.warn(function(e){return G.yellow(` warning: ${e.code} - ${e.message}`)}(e))}getEntries(){return[...this.entries]}getWarnings(){return[...this.warnings]}getRunId(){return this.runId}getCommand(){return this.command}getExecutionMode(){return this.executionMode}addEntry(e){this.entries.push({runId:this.runId,command:this.command,executionMode:this.executionMode,phase:e.phase,timestamp:(new Date).toISOString(),level:e.level,message:e.message,...e.fields?{fields:e.fields}:{}})}};function pa(e){return 0===e.length?[]:[G.yellow(G.bold("Warnings:")),...e.map(e=>G.yellow(` ${e.code}: ${e.message}`)),""]}function fa(e){return e?[G.dim(`Next action: ${e}`),""]:[]}function ha(e){const t=[],r="fix"===e.command?"Fix":"Build";if(t.push(""),"success"===e.status){const n=e.changedPaths.length;t.push(G.green(G.bold(`${r} succeeded`))+(n>0?G.green(` (${n} path${1!==n?"s":""} changed)`):"")),t.push(""),t.push(...pa(e.warnings))}else if("failure"===e.status)t.push(G.red(G.bold(`${r} failed`))),e.errorCode&&t.push(G.red(` Error: ${e.errorCode}`)),t.push(""),t.push(...pa(e.warnings)),t.push(...fa(e.nextAction));else{const n=e.changedPaths.length,o=e.failedPaths.length,s=e.partialPaths.length;t.push(G.yellow(G.bold(`${r} partially succeeded`))+G.yellow(` (${n} changed, ${o} failed, ${s} partial)`)),t.push(""),t.push(...pa(e.warnings)),t.push(...fa(e.nextAction))}return t.push(G.dim(`Run ID: ${e.runId}`)),t.join("\n")}var ma=/^\/\*\*\r?\n \* @generated by stably build[\s\S]*?\*\/(?:\r?\n)*/;function ga(e){return!!e&&"object"==typeof e&&"code"in e}async function ya({errorMessage:e,filePath:t}){try{return await W.readFile(t,"utf8")}catch(t){if(ga(t)&&"ENOENT"===t.code)throw new Error(e);throw t}}function ba(e){return e.split(r.sep).join("/")}async function wa(e){const t=[];return await async function e(n){let o;try{o=await W.readdir(n,{withFileTypes:!0})}catch{return}for(const s of o){const o=r.join(n,s.name);s.isDirectory()&&!s.isSymbolicLink()?await e(o):s.isFile()&&s.name.endsWith(".stably.md")&&t.push(o)}}(e),t.sort()}var va=/^---\r?\n([\s\S]*?)\r?\n---/;function _a(e,t){const n=[],o=va.exec(e);let s,i={};if(o){try{const e=xe(o[1]??"");i=e&&"object"==typeof e&&!Array.isArray(e)?e:{}}catch{te.warn(`Warning: Failed to parse YAML frontmatter in ${t}, treating as empty`),i={}}s=e.slice(o[0].length).replace(/^(\r?\n)+/,"")}else s=e;if(!s.trim())return{updated:e,addedFields:n};if(!i.name){const e=s.slice(0,1e4).replace(/```[\s\S]*?```/g,""),o=/^#\s+(.+)$/m.exec(e),a=r.basename(t).replace(/\.stably\.md$/,"").replace(/\.md$/,"");i.name=o?.[1]?.trim()??a,n.push("name")}return i.priority||(i.priority="medium",n.push("priority")),0===n.length?{updated:e,addedFields:n}:{updated:`---\n${Se(i).trimEnd()}\n---\n\n${s}`,addedFields:n}}async function Ea(e){try{return(await W.readdir(e)).filter(e=>co.test(e)).map(t=>r.join(e,t))}catch(e){if(ga(e)&&"ENOENT"===e.code)return[];throw e}}function Ia({runId:e,warnings:t,changedPaths:r=[],failedPaths:n=[],...o}){return{runId:e,command:"build",executionMode:"cli",warnings:t,changedPaths:r,failedPaths:n,partialPaths:[],...o}}async function Ta({force:e,inputFilePath:t}){const n=`build-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,o=new da({runId:n,command:"build",executionMode:"cli"});o.phaseStart("preflight","Validating workspace and arguments");const s=process.cwd();o.info({phase:"preflight",message:"Input resolved",fields:{input:t}}),o.phaseEnd("preflight","Preflight complete"),o.phaseStart("scope","Resolving scope");const i=await ya({filePath:t,errorMessage:`Prompt file not found: ${t}`});if(!i.trim())throw new Error(`Prompt file is empty: ${t}`);const a=So(i),c=ba(r.relative(s,t)),l=r.dirname(t),u=(d=t,r.basename(d).replace(/\.stably\.md$/,"").replace(/\.md$/,"").replace(/\.txt$/,""));var d;const p=await async function(e,t){return(await Ea(e)).find(e=>{const n=r.basename(e);return n.startsWith(`${t}.spec`)||n.startsWith(`${t}.test`)})}(l,u);if(!e&&p&&await async function({outputFilePath:e,promptHash:t}){try{return Ao(await W.readFile(e,"utf8"))===t}catch(e){if(ga(e)&&"ENOENT"===e.code)return!1;throw e}}({outputFilePath:p,promptHash:a})){o.info({phase:"scope",message:"Hash unchanged, skipping build"});const e={code:"STABLY_WARNING_NO_CHANGES",message:"Test code is up to date (hash unchanged)"};o.emitWarning(e);const t=Ia({runId:n,status:"success",warnings:[e]});return o.phaseStart("summary","Build summary"),te.info(ha(t)),o.phaseEnd("summary","Done"),te.success(G.green(`Skipped build: ${c} (hash unchanged)`)),"skipped"}o.info({phase:"scope",message:"Scope resolved",fields:{promptFile:c,promptHash:a,resolvedScopeCount:1,unmappedPaths:[],baseSource:"prompt-file",baseRef:c}}),o.phaseEnd("scope","Scope complete"),o.phaseStart("plan","Preparing prompt");const f=new Set(await Ea(l));await W.mkdir(l,{recursive:!0});const h=Co({promptFile:c,promptHash:a}),m=ba(r.relative(s,l)||l),g=function({outputDir:e,promptContent:t,sourceSpecFile:r}){return["Compile this test specification into a Playwright test file.","",`Output directory: ${e}`,"","Choose output filename:",`- Look at existing test files in ${e} to determine the naming convention.`,"- Use the same extension pattern as existing tests (e.g., .test.ts or .spec.ts).","- If no existing tests, default to .spec.ts.","- Base the filename on the prompt content (e.g., login.spec.ts for login tests).","","File creation rules:","- Create your test file in the output directory with your chosen filename.","- You MAY create shared helper files (e.g., lib/auth.ts) if the prompt explicitly requests reusable components.","- Prefer single-file output unless shared helpers would significantly improve maintainability.","- Never modify unrelated existing files.","","Sync workflow for existing files:","1. Examine existing test files in the workspace and preserve hand edits where possible.","2. If a matching test file already exists, read it first and compare against the prompt specification.","3. Apply sync rules:"," - If file does not exist: CREATE from scratch."," - If file exists and already satisfies the prompt: KEEP behavior and make minimal edits only when needed."," - If file exists but only partially matches: UPDATE only changed scenarios so code aligns with prompt."," - If file structure conflicts heavily with prompt: REGENERATE the file content completely.","4. Prompt specification is the source of truth for final test behavior.","","Test verification:","After generating the test file, run the tests locally to verify they work correctly.","Use the appropriate test command (e.g., `pnpm stably test` or the repository's test command).","If tests fail, analyze the errors and iterate on the test code until all tests pass.","","Spec file linking:",`- Add \`// @stably.spec ${r}\` after the import statements.`,"- This links the test back to its source .md specification.","- If different test.describe()/test() blocks come from different .md files, add per-block @stably.spec instead.","","Prompt specification:",t].join("\n")}({outputDir:m,promptContent:i,sourceSpecFile:c});o.info({phase:"plan",message:"Agent prompt assembled",fields:{outputTarget:m,plannedPathCount:1,plannedPaths:[m],mode:"directory"}}),o.phaseEnd("plan","Plan complete"),o.phaseStart("execute","Running agent session"),process.exitCode=void 0;const y=Date.now();await la({mode:"build",prompt:g,outputDir:l,customHeader:h});const b=Date.now()-y,w=process.exitCode;if("number"==typeof w&&0!==w){o.error({phase:"execute",message:`Build generation failed for: ${c}`,fields:{toolName:"runAgentSession",durationMs:b}});const e=Ia({runId:n,status:"failure",warnings:o.getWarnings(),failedPaths:[c],nextAction:"open_agent_session",errorCode:"STABLY_WRITE_FAILED"});throw o.phaseStart("summary","Build summary"),o.info({phase:"summary",message:"Run failed",fields:{errorCode:e.errorCode,nextAction:e.nextAction}}),te.info(ha(e)),o.phaseEnd("summary","Done"),new Error(`Build generation failed for: ${c}`)}o.info({phase:"execute",message:"Agent session completed",fields:{toolName:"runAgentSession",durationMs:b}}),o.phaseEnd("execute","Agent session complete"),o.phaseStart("finalize","Applying results");const v=[];let _=p;if(!_&&(_=(await Ea(l)).find(e=>!f.has(e)),!_)){const e={path:c,status:"failed",error:"No new test file created"};v.push(e),o.info({phase:"finalize",message:"Write failed",fields:{path:e.path,writeStatus:e.status,error:e.error}});const t=Ia({runId:n,status:"failure",warnings:o.getWarnings(),failedPaths:[c],nextAction:"open_agent_session",errorCode:"STABLY_WRITE_FAILED"});throw o.phaseStart("summary","Build summary"),o.info({phase:"summary",message:"Run failed",fields:{errorCode:t.errorCode,nextAction:t.nextAction}}),te.info(ha(t)),o.phaseEnd("summary","Done"),new Error(`Build finished but no new test file was created for: ${c}`)}const E=await ya({filePath:_,errorMessage:`Build finished but output file was not created for: ${c}`}),I=function(e){return e.replace(ma,"")}(E),T=E.startsWith(h)?E:`${h}\n\n${I}`;T!==E&&await W.writeFile(_,T,"utf8");const x=ba(r.relative(s,_)),S={path:x,status:"success"};v.push(S),o.info({phase:"finalize",message:"Write succeeded",fields:{path:S.path,writeStatus:S.status}}),o.phaseEnd("finalize","Finalize complete"),o.phaseStart("summary","Build summary");const A=v.filter(e=>"success"===e.status).map(e=>e.path),C=v.filter(e=>"failed"===e.status).map(e=>e.path);let R;R=C.length>0?A.length>0?"partial":"failure":"success";const P=C.length>0,U=Ia({runId:n,status:R,warnings:o.getWarnings(),changedPaths:A,failedPaths:C,nextAction:P?"inspect_failed_paths":void 0,errorCode:P?"STABLY_WRITE_FAILED":void 0});return o.info({phase:"summary",message:"Run completed",fields:{status:U.status,changedPathCount:A.length,failedPathCount:C.length,...U.errorCode?{errorCode:U.errorCode}:{},...U.nextAction?{nextAction:U.nextAction}:{}}}),te.info(ha(U)),o.phaseEnd("summary","Done"),te.success(G.green(`Built: ${x}`)),"built"}var xa=[{args:["--trace=on"],description:"Run Playwright tests",name:"test"},{args:[],description:"Install browser dependencies",name:"install"}],Sa=["You have two different versions of @playwright/test"];function Aa(e){const[t,...r]=Oi(e),n=[t,...r.slice(0,-1)].join(" ");return(t,r)=>{let o=t.toString();for(const e of xa)o=o.replaceAll(`${n} playwright ${e.name}`,`${n} stably ${e.name}`).replaceAll(`npx playwright ${e.name}`,`npx stably ${e.name}`);if("yarn"===e){const e=o.split("\n");return e.length>0&&e[0].includes("/.bin/playwright")&&e.shift(),void r.write(e.join("\n"))}r.write(o)}}async function Ca({overrideArgs:e,subcommand:t}){Fn.info("[test] forwardToPlaywright starting",{subcommand:t,overrideArgs:e});const r=process.argv,i=r.findIndex((e,r)=>r>1&&e===t),c=-1===i?[]:r.slice(i+1),l="--"===c[0],u=l?c.slice(1):c;if(!l&&("--help"===u[0]||"-h"===u[0]))return async function({subcommand:e}){const t=xa.find(t=>t.name===e),r=e=>process.stdout.write(`${e}\n`);r(`stably ${e} - ${t?.description??""}`),r(""),"test"===e&&(r('IMPORTANT: Always use "stably" commands instead of "playwright" directly.'),r(""),r("Stably commands:"),r(" stably test [file] Run tests (auto-enables tracing and analytics)"),r(" stably fix [file] Auto-fix failing tests using AI"),r(" stably create <url> Generate new tests from a URL using AI"),r(""),r("Why use Stably?"),r(' - "stably fix" automatically repairs broken tests'),r(' - "stably test" enables --trace=on and test analytics'),r(' - "stably create" generates tests from prompt'),r(""));const n=ki();if(!n.installed||!n.inNodeModules)return void r('No Playwright project found in this directory or its parents.\nMake sure you\'re in a directory within your Playwright project, or run "stably init" to create a new playwright directory.');const{packageManager:o}=n;if(!o)return void r("Could not determine package manager.");r("Playwright options:"),r("");const[s,...i]=Oi(o),a=Aa(o);return new Promise(t=>{const r=f(s,[...i,e,"--help"],{stdio:["inherit","pipe","pipe"],env:{...process.env,...process.env.CI?{}:{FORCE_COLOR:"1"}}});r.stdout?.on("data",e=>{a(e,process.stdout)}),r.stderr?.on("data",e=>{a(e,process.stderr)}),r.on("close",()=>{t()})})}({subcommand:t});const d=e??[],h=new Set(d.map(e=>{const[t]=e.split("=");return t})),m=[];for(let e=0;e<u.length;e++){const t=u[e],[r]=t.split("=");h.has(r)?!t.includes("=")&&e+1<u.length&&!u[e+1].startsWith("-")&&e++:m.push(t)}const y=[t,...d,...m];Fn.info("[test] Forwarded args computed",{forwardedArgs:y}),Fn.info("[test] Resolving Stably test environment");const b=Date.now(),I="test"===t?await Xn():void 0;Fn.info("[test] Stably test environment resolved",{durationMs:Date.now()-b,hasCredentials:null!=I,hasWsUrl:!!I?.STABLY_WS_URL}),Fn.info("[test] Setting up Stably reporter injection");const T="test"===t?function({forwardedArgs:e,hasCredentials:t}){if(!t)return console.warn("⚠️ Stably credentials not found. Test results will not be reported to Stably."),console.warn(" To enable reporting, either:"),console.warn(" • Run `npx stably login` to authenticate"),void console.warn(" • Or set STABLY_API_KEY and STABLY_PROJECT_ID environment variables\n");const r=process.cwd(),i=e=>{const t=function(e){let t=n(e);for(;;){if([s(t,"node_modules","@stablyai","playwright-test"),s(t,"node_modules",".pnpm","@stablyai+playwright-test")].some(e=>g(e)))return!0;const e=o(t);if(e===t)return!1;t=e}}(e);return t||(console.warn("⚠️ @stablyai/playwright-test is not installed. Stably reporter will not be injected."),console.warn(" Install it with: npm install @stablyai/playwright-test"),console.warn(" Reference: ]8;;https://docs.stably.ai/getting-started/sdk-setup-guidehttps://docs.stably.ai/getting-started/sdk-setup-guide]8;;\n")),t},c=(e,t)=>{try{return function({baseConfigPath:e,projectDir:t}){const r=function(e){try{const t=p("npm pkg get type",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return"module"===JSON.parse(t.trim())}catch{return!1}}(t),i=r?"mts":"ts",c=o(n(e)),l=a(e),u=s(c,`.stably-playwright-wrapper.config.${i}`),d=`\n// Auto-generated wrapper config by Stably CLI\n// This file injects the Stably reporter and ensures trace is enabled\nimport baseConfig from './${l}';\nimport { defineConfig, stablyReporter } from '@stablyai/playwright-test';\n\n// Inline type definitions to avoid import failures when @stablyai/playwright-test is not installed\ntype StablyNotificationConfig = {\n email?: { to: string[]; notifyOnStart?: boolean; notifyOnResult?: 'all' | 'failures-only' | null } | null;\n slack?: { channelName: string; notifyOnStart?: boolean; notifyOnResult?: 'all' | 'failures-only' } | null;\n};\n\ntype ProjectNotificationConfig = {\n projectName: string;\n notifications: StablyNotificationConfig;\n};\n\n// Extract notification configs from projects that have stably.notifications defined\n// This runs at config-load time before Playwright strips custom properties\nconst extractNotificationConfigs = (): ProjectNotificationConfig[] | undefined => {\n const projects = baseConfig.projects;\n if (!projects || !Array.isArray(projects)) return undefined;\n\n const configs = projects\n .map((p: { name?: string; stably?: { notifications?: StablyNotificationConfig } }) => {\n const notifications = p.stably?.notifications;\n return notifications ? { projectName: p.name ?? '', notifications } : undefined;\n })\n .filter((config): config is ProjectNotificationConfig => config != null);\n\n return configs.length > 0 ? configs : undefined;\n};\n\nconst isStablyReporter = (reporter: unknown): boolean => {\n // Only match @stablyai npm scope to avoid false positives on unrelated reporters\n // that might contain "stably" substring (e.g., "unstably-runner")\n if (typeof reporter === 'string') {\n return reporter.includes('@stablyai');\n }\n if (Array.isArray(reporter) && typeof reporter[0] === 'string') {\n return reporter[0].includes('@stablyai');\n }\n return false;\n};\n\nconst getStablyReporterOptions = (reporters: unknown[]): Record<string, unknown> | undefined => {\n for (const reporter of reporters) {\n if (Array.isArray(reporter) && typeof reporter[0] === 'string' && reporter[0].includes('@stablyai')) {\n return (reporter[1] as Record<string, unknown>) ?? {};\n }\n }\n return undefined;\n};\n\nconst filterOutStablyReporter = (reporters: unknown[]): unknown[] => {\n return reporters.filter((reporter) => !isStablyReporter(reporter));\n};\n\nconst buildReporterList = () => {\n const existingReporters = baseConfig.reporter;\n\n // Resolve errorSummary: env var STABLY_ERROR_SUMMARY=0 disables it\n const resolveErrorSummary = (existingValue?: unknown): boolean | undefined => {\n if (process.env.STABLY_ERROR_SUMMARY === '0') return false;\n if (typeof existingValue === 'boolean') return existingValue;\n return undefined; // let the reporter default (true)\n };\n\n // No existing reporters - create fresh stably reporter\n if (!existingReporters) {\n return [stablyReporter({\n apiKey: process.env.STABLY_API_KEY,\n projectId: process.env.STABLY_PROJECT_ID,\n notificationConfigs: extractNotificationConfigs(),\n errorSummary: resolveErrorSummary(),\n })];\n }\n\n // Normalize to array\n const reportersArray: unknown[] = Array.isArray(existingReporters)\n ? existingReporters\n : [[existingReporters, {}]];\n\n // If user has a stably reporter, take their options but override credentials\n const existingOptions = getStablyReporterOptions(reportersArray);\n const stablyReporterEntry = stablyReporter({\n ...existingOptions,\n apiKey: process.env.STABLY_API_KEY,\n projectId: process.env.STABLY_PROJECT_ID,\n notificationConfigs: extractNotificationConfigs(),\n errorSummary: resolveErrorSummary(existingOptions?.errorSummary),\n });\n\n // Keep all non-stably reporters, add our (merged or fresh) stably reporter\n const otherReporters = filterOutStablyReporter(reportersArray);\n return [...otherReporters, stablyReporterEntry];\n};\n\nexport default defineConfig({\n ...baseConfig,\n use: {\n ...baseConfig.use,\n trace: 'on',\n },\n reporter: buildReporterList(),\n});\n`.trim();return g(c)||v(c,{recursive:!0}),_(u,d,"utf-8"),function(e){const t=s(e,".gitignore");try{if(g(t)){const e=w(t,"utf-8");if(e.split("\n").map(e=>e.trim()).includes(No))return;const r=e.length>0&&!e.endsWith("\n");E(t,`${r?"\n":""}${No}\n`)}else _(t,`${No}\n`)}catch{}}(c),u}({baseConfigPath:e,projectDir:t})}catch{return void console.warn("⚠️ Could not create Stably wrapper config. Reporter injection skipped.")}};if(e.some(e=>"--config"===e||"-c"===e||e.startsWith("--config=")||e.startsWith("-c="))){const t=e.findIndex(e=>"--config"===e||"-c"===e);if(-1!==t&&e[t+1]){const s=n(r,e[t+1]),a=o(s);if(!i(a))return;const l=c(s,a);if(!l)return;return e[t+1]=l,l}const s=e.findIndex(e=>e.startsWith("--config=")||e.startsWith("-c="));if(-1!==s){const t=n(r,e[s].split("=")[1]),a=o(t);if(!i(a))return;const l=c(t,a);if(!l)return;const u=e[s].startsWith("--config=")?"--config=":"-c=";return e[s]=`${u}${l}`,l}}const l=Mo(r);if(!l)return;const u=o(l);if(!i(u))return;const d=c(l,u);return d?(e.push("--config",d),d):void 0}({forwardedArgs:y,hasCredentials:null!=I}):void 0;Fn.info("[test] Reporter injection setup complete",{hasWrapperConfig:!!T}),Fn.info("[test] Spawning Playwright process"),await function(e,t={}){Fn.info("[test] Detecting Playwright installation");const r=ki();Fn.info("[test] Playwright installation check",{installed:r.installed,inNodeModules:r.inNodeModules,packageManager:r.packageManager,packageName:r.packageName}),r.installed||(console.error('Playwright is not installed. Please run "stably init" to install it.'),process.exit(1)),r.inNodeModules||(console.error("Playwright is present in your project, but not in node_modules. Please install your dependencies before proceeding."),process.exit(1));const{packageManager:n}=r;n||(console.error("Playwright installation not found. Could not determine your package manager (tried pnpm, yarn, and npm)."),process.exit(1));const[o,...s]=Oi(n),i=Jn(t.env),a=[o,...s,...e];Fn.info("[test] Spawning Playwright process",{command:a.join(" "),pid:process.pid});const c=Date.now(),l=f(o,[...s,...e],{stdio:["inherit","pipe","pipe"],env:{...i,...process.env.CI?{}:{FORCE_COLOR:"1"}}});Fn.info("[test] Playwright process spawned",{childPid:l.pid});const u=Aa(n),d=function(){let e=!1,t="";return(r,n)=>{if(!e){t+=r,t.length>1024&&(t=t.slice(-1024));for(const r of Sa)if(t.includes(r))return n.write("\n[stably] Hint: This is a Playwright error, not caused by @stablyai/playwright-test.\n Common causes: running from the wrong directory (especially in monorepos),\n or a dependency pulling in a conflicting @playwright/test version.\n"),void(e=!0)}}}();l.stdout?.on("data",e=>{u(e,process.stdout)}),l.stderr?.on("data",e=>{const t=e.toString();u(e,process.stderr),d(t,process.stderr)});const p=new AbortController,h=()=>!p.signal.aborted&&(p.abort(),t.onClose?.(),process.removeListener("SIGINT",m),process.removeListener("SIGTERM",m),!0),m=e=>{Fn.info("[test] Signal received, killing Playwright process",{signal:e,childPid:l.pid}),h(),l.kill(e);const t="SIGINT"===e?130:143;process.exit(t)};return process.on("SIGINT",m),process.on("SIGTERM",m),new Promise((e,t)=>{l.on("error",e=>{h()&&(Fn.error("[test] Playwright process error",{error:e.message,childPid:l.pid}),t(e))}),l.on("close",t=>{if(!h())return;Fn.info("[test] Playwright process exited",{exitCode:t,durationMs:Date.now()-c});const r=[process.stdout,process.stderr].filter(e=>e.writableNeedDrain).map(e=>new Promise(t=>e.once("drain",t)));Promise.race([Promise.all(r),new Promise(e=>setTimeout(e,5e3))]).then(()=>{process.exitCode=t??0,e(t??0)})})})}(y,{env:I,onClose:()=>{var e;Fn.info("[test] Playwright process closed, cleaning up wrapper config"),(e=T)&&g(e)&&S(e)}})}function Ra(e=""){process.stdout.write(`${e}\n`)}function Pa(...e){process.stderr.write(`${e.join(" ")}\n`)}var Ua="stably",ka=`https://registry.npmjs.org/${Ua}/latest`,La=le.object({version:le.string()});function Da(e){const t=e.match(/^(\d+)\.(\d+)\.(\d+)/);return t?{major:parseInt(t[1],10),minor:parseInt(t[2],10),patch:parseInt(t[3],10)}:null}function Oa(e,t){const r=Da(e),n=Da(t);return!(!r||!n)&&(n.major>r.major||!(n.major<r.major)&&(n.minor>r.minor||!(n.minor<r.minor)&&n.patch>r.patch))}var Ba=r.join(R.homedir(),".stably"),Na=r.join(Ba,"update-check.json"),$a=`https://registry.npmjs.org/${Ua}/latest`,Ma="1"===process.env.STABLY_DISABLE_UPDATE_CHECK,ja=le.object({lastCheck:le.number(),latestVersion:le.string()}),Ha=!1,Fa=!1,Ga=async()=>{if(Fa)try{const{shutdown:e}=await import("@hyperdx/node-opentelemetry"),t=process.stderr.write.bind(process.stderr),r=process.stdout.write.bind(process.stdout),n=(e,...t)=>{const r=t[0];return!("string"!=typeof r||!r.includes("OpenTelemetry"))||!(!Buffer.isBuffer(r)||!r.toString().includes("OpenTelemetry"))||e(...t)};process.stderr.write=(...e)=>n(t,...e),process.stdout.write=(...e)=>n(r,...e);try{await e()}finally{process.stderr.write=t,process.stdout.write=r}}catch{}};!function(){if(Ma)return;const e=function(){try{const e=m.readFileSync(Na,"utf-8");return ja.parse(JSON.parse(e))}catch{return null}}(),t=Date.now();if((null==e||t-e.lastCheck>=18e5)&&function(){const e=`\n import { get } from 'node:https';\n import fs from 'node:fs';\n const url = '${$a}';\n const cacheFile = ${JSON.stringify(Na)};\n const cacheDir = ${JSON.stringify(Ba)};\n\n const req = get(url, { timeout: 5000 }, (res) => {\n if (res.statusCode !== 200) process.exit(1);\n let data = '';\n res.on('data', (chunk) => data += chunk);\n res.on('end', () => {\n try {\n const version = JSON.parse(data).version;\n if (!fs.existsSync(cacheDir)) fs.mkdirSync(cacheDir, { recursive: true });\n fs.writeFileSync(cacheFile, JSON.stringify({ lastCheck: Date.now(), latestVersion: version }));\n } catch {}\n process.exit(0);\n });\n });\n req.on('error', () => process.exit(1));\n req.on('timeout', () => { req.destroy(); process.exit(1); });\n `;try{f(process.execPath,["--input-type=module","-e",e],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()}catch{}}(),null!=e&&Oa(Yr,e.latestVersion)){if(Ha)return;Ha=!0;let t=!1;const r=()=>{if(t)return;t=!0;const r=`${G.yellow(`update available (${Yr} → ${e.latestVersion})`)} - run \`${Ua} upgrade\` to get the latest version\n`;try{m.writeSync(2,r)}catch{}};process.once("beforeExit",r),process.once("exit",r)}}(),Ce.cwdChanged&&Fn.debug("Changed working directory",{cwd:Ce.newCwd});for(const e of Ce.envFilesLoaded)Fn.debug("Loaded env file",{path:e});for(const e of Ce.envFileErrors)Fn.warn(e);var Ya=process.argv.findIndex(e=>"-v"===e||"--verbose"===e);-1!==Ya&&process.argv.splice(Ya,1);var Wa=process.argv.findIndex(e=>"--no-telemetry"===e);-1!==Wa&&process.argv.splice(Wa,1),Fn.info("CLI starting",{version:Yr,args:process.argv.slice(2),cwd:process.cwd()}),process.on("unhandledRejection",(e,t)=>{Fn.error("Unhandled promise rejection",{reason:e instanceof Error?{message:e.message,stack:e.stack}:e,promise:String(t)}),Fn.flush(),Fn.printLogFileInfo()}),process.on("uncaughtException",(e,t)=>{"EPIPE"!==e.code&&(Fn.error("Uncaught exception",{error:{message:e.message,stack:e.stack,name:e.name},origin:t}),Fn.flush(),Fn.printLogFileInfo())});var Va=new c;Va.name("stably").description("AI-assisted Playwright testing CLI").version(Yr),Va.enablePositionalOptions(),Va.showHelpAfterError(),Va.exitOverride(),Va.configureHelp({subcommandTerm:e=>{const t=e.registeredArguments.map(e=>e.required?`<${e.name()}>`:`[${e.name()}]`).join(" ");return t?`${e.name()} ${t}`:e.name()}});var za=[];Va.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>{za.push(e)}});var Ka=()=>{const e=Va.helpInformation().trimEnd();return e?`${e}\n`:""},qa=(e,t)=>{let r=e;for(const e of t){const t=r.commands.find(t=>t.name()===e||t.aliases().includes(e));if(!t)return;r=t}return r},Ja=()=>{process.stdout.write(Ka())};Va.command("help [command...]").description("Show help for a command (e.g. stably help create)").action(e=>{if(!e||0===e.length)return void Ja();const t=qa(Va,e);if(!t)return process.stderr.write(`Unknown command: ${e.join(" ")}\n`),Ja(),void(process.exitCode=1);var r;r=t,process.stdout.write((e=>{const t=e.helpInformation().trimEnd();return t?`${t}\n`:""})(r))}),Va.action(()=>la({mode:"chat",getHelpText:Ka})),Va.command("login").description("Authenticate with Stably in your browser").action(Tn),Va.command("logout").description("Clear stored Stably credentials").action(async()=>{const e=Yn();e&&(te.warn(`Environment variables ${G.cyan("STABLY_API_KEY")} and ${G.cyan("STABLY_PROJECT_ID")} are set.`),te.warn("They will continue to be used for authentication even after logout."),te.warn("Unset them if you want to fully de-authenticate this shell/session."));const t=await fn();if(!t)return void re(e?G.yellow("No stored OAuth login found to clear."):G.yellow("You are not logged in."));const r=ne();r.start("Logging out..."),await(async e=>{try{await fetch(`${zr}/api/backend/v1/logout`,{body:JSON.stringify({refresh_token:e}),headers:{"Content-Type":"application/json"},method:"POST"})}catch{}})(t.refreshToken),await mn(),await yn(),r.stop(G.green("✓ Logged out")),re(G.green("You have been logged out successfully."))}),Va.command("whoami").description("Show auth status and current project").action(async()=>{te.info(`${G.bold("CLI Version:")} ${G.cyan(Yr)}`);const e=Yn();if(e){te.info(G.dim("Authentication: Environment variables")),te.info(` ${G.bold("API Key:")} ${G.cyan(e.apiKey.slice(0,8))}...`),te.info(` ${G.bold("Project ID:")} ${G.cyan(e.projectId)}`);const t=await fn();if(t){let e;try{e=on(t.accessToken).email}catch{e=void 0}te.warn("Stored OAuth login detected but will be ignored (env auth takes precedence)."),e&&te.info(` ${G.bold("OAuth Email:")} ${G.cyan(e)}`),te.info(` ${G.bold("Tip:")} Unset env vars to use OAuth`)}return void re(G.green("Authenticated via environment variables"))}const t=await fn();if(!t)return void re(G.yellow("Not logged in. Run `stably login` to authenticate."));let n;try{n=on(t.accessToken).email}catch{n=void 0}const o=await gn();if(!o)return te.info(G.dim("Authentication: OAuth (not linked to a project)")),n&&te.info(` ${G.bold("Email:")} ${G.cyan(n)}`),void re(G.yellow("Logged in but this directory is not linked to a project. Run `stably login` to link."));const s=await(async()=>sn(process.cwd(),ln))(),i=s?r.dirname(s):process.cwd(),a=r.relative(process.cwd(),i)||".";te.info(G.dim("Authentication: OAuth")),n&&te.info(` ${G.bold("Email:")} ${G.cyan(n)}`),te.info(` ${G.bold("Organization:")} ${G.cyan(o.orgName)}`),te.info(` ${G.bold("Project:")} ${G.cyan(o.projectName)}`),te.info(` ${G.bold("Linked at:")} ${G.dim(a)}`),re(G.green("Authenticated"))}),Va.command("build [input...]").description("Compile test specification files (.stably.md) into Playwright tests").option("--force","Force regeneration even if prompt is unchanged").action(async(e,t)=>{try{await async function(e){const{inputs:t,force:n}=e,o=process.cwd();let s;if(0===t.length){const e=function(e){try{return p('git ls-files --cached --others --exclude-standard "*.stably.md"',{cwd:e,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).split("\n").map(e=>e.trim()).filter(Boolean)}catch{return[]}}(o);s=e.map(e=>r.resolve(o,e))}else s=await async function(e,t){const n=[];for(const o of e){const e=r.resolve(t,o);let s;try{s=await W.stat(e)}catch{n.push(e);continue}if(s.isDirectory()){const t=await wa(e);n.push(...t)}else n.push(e)}const o=new Set,s=[];for(const e of n){const t=r.resolve(e);o.has(t)||(o.add(t),s.push(t))}return s}(t,o);if(0===s.length)throw new Error("No .stably.md files found. Create a test specification file (e.g., login.stably.md) and try again.");const{fixedFiles:i}=await async function(e,t){const n=[],o=[];for(const s of e){let e=s;try{await W.stat(e)}catch{o.push(e);continue}if(e.endsWith(".md")&&!e.endsWith(".stably.md")){const o=e.replace(/\.md$/,".stably.md");try{await W.rename(e,o);const s=ba(r.relative(t,e)),i=ba(r.relative(t,o)),a={code:"STABLY_WARNING_FILE_RENAMED",message:`Renamed ${s} → ${i} (test specs must use .stably.md extension)`,details:{oldPath:s,newPath:i}};n.push(a),te.warn(G.yellow(` ⚠ ${a.message}`)),e=o}catch(t){if(!(t instanceof Error&&"code"in t)||"EEXIST"!==t.code&&"ENOTEMPTY"!==t.code)throw t;te.warn(G.yellow(` ⚠ Skipping rename: ${o} already exists`)),e=o}}if(!e.endsWith(".stably.md")){o.push(e);continue}const i=await W.readFile(e,"utf8"),{updated:a,addedFields:c}=_a(i,e);if(c.length>0){await W.writeFile(e,a,"utf8");const o=ba(r.relative(t,e)),s={code:"STABLY_WARNING_FRONTMATTER_ADDED",message:`Added missing frontmatter fields to ${o}: ${c.join(", ")}`,details:{path:o,addedFields:c}};n.push(s),te.warn(G.yellow(` ⚠ ${s.message}`))}o.push(e)}return{fixedFiles:o,warnings:n}}(s,o);s=i,te.info(G.bold(`Found ${s.length} test specification${1!==s.length?"s":""}`));for(const e of s){const t=ba(r.relative(o,e));te.info(G.dim(` ${t}`))}te.info("");const a={built:[],skipped:[],failed:[]};for(const e of s){const t=ba(r.relative(o,e));try{"built"===await Ta({force:n,inputFilePath:e})?a.built.push(t):a.skipped.push(t)}catch(e){const r=e instanceof Error?e.message:String(e);te.error(G.red(`Failed to build ${t}: ${r}`)),a.failed.push(t)}}return function(e){if(te.info(""),te.info(G.bold("Build Summary")),te.info(` ${G.green(`${e.built.length} built`)} ${G.dim(`${e.skipped.length} skipped (unchanged)`)} ${e.failed.length>0?G.red(`${e.failed.length} failed`):G.dim("0 failed")}`),e.failed.length>0){te.info(""),te.error(G.red("Failed files:"));for(const t of e.failed)te.error(G.red(` - ${t}`))}}(a),a.failed.length>0&&(process.exitCode=1),a}({inputs:e,force:t.force??!1})}catch(e){const t=e instanceof Error?e.message:String(e);process.stderr.write(`${t}\n`),process.exitCode=1}}),Va.command("tunnel",{hidden:!0}).description("Expose a local server with a secure tunnel URL").option("-p, --port <number>","Local port to expose","3000").action(async e=>{oe(`Starting development server for port ${e.port}...`);const t=await Kn(),r="oauth"===t.type?`${t.auth.context.orgName}-${t.auth.context.projectName}`.toLowerCase().replace(/[^a-z0-9-]/g,""):`project-${t.auth.projectId}`.toLowerCase(),n=ne();n.start("Starting development server...");const o=await Ae(`http://localhost:${e.port}`,{subdomain:r});n.stop(`Your local environment is available at: ]8;;${o.url}${G.underline(G.cyan(o.url))}]8;;`)}),Va.command("create [prompt...]").description("Generate a test from prompt (omit prompt to infer from branch diff)").option("-o, --output <dir>","Output directory for generated test files").action(async(e,t)=>{const r=e.length>0&&"test"===e[0]?e.slice(1):e;return la({mode:"single",prompt:r,outputDir:t.output})}).command("test",{hidden:!0}).description("Generate a Playwright test from a prompt (deprecated: use `stably create <prompt>` directly)").argument("<prompt...>","Prompt describing the test to generate").option("-o, --output <dir>","Output directory for generated test files").action(async(e,t)=>la({mode:"single",prompt:e,outputDir:t.output})),Va.command("fix [runId]").description("Fix failing tests from a run (auto-detects from last test run or CI)").action(async e=>{(function(e){try{return p("git rev-parse --is-inside-work-tree",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}})(process.cwd())||(Fn.error('Not a git repository. The "stably fix" command requires a git repository to track changes made during the fix. Please run this command from inside a git repository.'),process.stderr.write('Error: Not a git repository.\nThe "stably fix" command requires a git repository to track changes made during the fix.\nPlease run this command from inside a git repository.\n'),process.exit(1));const t=await(async e=>{const t=e=>e.replace(/\//g,"_");if(e)return Fn.debug("Run ID provided explicitly",{runId:e}),t(e);const r=function(){if(process.env.CI_BUILD_ID)return process.env.CI_BUILD_ID;const e=(({env:e=process.env,cwd:t=process.cwd()}={})=>{for(const r of Object.keys(vr))if(vr[r].detect({env:e,cwd:t}))return{isCi:!0,...vr[r].configuration({env:e,cwd:t})};return{isCi:Boolean(e.CI),...(r={env:e,cwd:t},{commit:Yt(r),branch:Wt(r)})};var r})();if(!e.isCi)return;const t=function(e){switch(e){case"github":return process.env.GITHUB_RUN_ATTEMPT;case"azure-devops":return process.env.SYSTEM_JOBATTEMPT;case"bitbucket":return process.env.BITBUCKET_STEP_RUN_NUMBER;default:return}}(e.service),r=[e.service,"slug"in e?e.slug?.replace(/\//g,"_"):void 0,"build"in e?String(e.build):void 0,"job"in e?String(e.job):void 0,t&&String(t)].filter(Boolean);return r.length>0?r.join("-"):void 0}();if(r)return Fn.debug("Run ID detected from CI environment",{runId:r}),t(r);Fn.debug("No explicit run ID or CI environment detected, checking last-run.json");const n=await(async()=>{try{const e=await sn(process.cwd(),".stably/last-run.json");if(!e)return;const t=await V(e,"utf-8");return{...ua.parse(JSON.parse(t)),filePath:e}}catch{return}})();if(n){const e=(Date.now()-n.timestamp)/36e5;return Fn.debug("Run ID found in last-run.json",{runId:n.runId,timestamp:n.timestamp,filePath:n.filePath,ageHours:Math.round(e)}),e>24&&Fn.warn(`Using run ID from ${Math.round(e)} hours ago (${n.filePath}). Provide an explicit run ID if this is not the run you want to fix.`),t(n.runId)}Fn.debug("No run ID found in last-run.json")})(e);return t||(process.stderr.write('Run ID is required. Either:\n 1. Run "stably test" first (run ID will be auto-detected)\n 2. Provide a run ID: stably fix <runId>\n 3. Run in CI (auto-detected from environment)\n'),process.exit(1)),la({mode:"fix",runId:t})}),Va.command("init").description("Initialize Playwright and Stably SDK in your project").action(async()=>la({mode:"init"})),Va.command("upgrade").description("Upgrade to latest version (use --check to only check)").option("-c, --check","Only check for updates without upgrading").action(e=>async function(e){const{check:t=!1}=e;let r;Ra(G.cyan("Checking for updates...\n"));try{r=await async function(){const e=await async function(){const e=new AbortController,t=setTimeout(()=>e.abort(),1e4);t.unref();try{const t=await fetch(ka,{signal:e.signal});if(!t.ok)throw new Error(`Failed to fetch latest version: ${t.statusText}`);return La.parse(await t.json()).version}finally{clearTimeout(t)}}();return{current:Yr,latest:e,isOutdated:Oa(Yr,e)}}()}catch(e){return Pa(G.red("Failed to check for updates:"),e instanceof Error?e.message:e),void(process.exitCode=1)}if(Ra(`Current version: ${G.yellow(r.current)}`),Ra(`Latest version: ${G.green(r.latest)}`),Ra(),!r.isOutdated)return void Ra(G.green("✓ You are already on the latest version!"));if(Ra(G.yellow(`⚠ A new version is available: ${r.current} → ${r.latest}`)),Ra(),t)return Ra(G.dim("Exiting with code 1 to indicate update available (useful for CI).")),void(process.exitCode=1);const n=function(){const e=process.argv[1]||"";if(e.includes("_npx")||e.includes(".npm/_cacache"))return"npx";try{const t=p("npm root -g",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-npm"}catch{}if(e.includes("node_modules/stably"))return"global-npm";try{const t=p("pnpm root -g",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-pnpm"}catch{}try{const t=p("yarn global dir",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-yarn-classic"}catch{}try{const t=p("yarn config get globalFolder",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-yarn-berry"}catch{}return"unknown"}(),o=function(e){switch(e){case"global-npm":case"global-yarn-berry":case"unknown":return{command:"npm",args:["install","-g",`${Ua}@latest`],description:`npm install -g ${Ua}@latest`};case"global-pnpm":return{command:"pnpm",args:["add","-g",`${Ua}@latest`],description:`pnpm add -g ${Ua}@latest`};case"global-yarn-classic":return{command:"yarn",args:["global","add",`${Ua}@latest`],description:`yarn global add ${Ua}@latest`};case"npx":return{command:"npx",args:[`${Ua}@latest`],description:`npx ${Ua}@latest (always uses latest)`}}}(n);if("npx"===n)return Ra(G.dim("You are running via npx, which always fetches the latest version.")),void Ra(G.dim(`Simply run: ${G.white("npx stably")} to use the latest version.`));"unknown"===n?(Ra(G.yellow("Could not detect installation method. Falling back to npm.")),Ra()):"global-yarn-berry"===n&&(Ra(G.yellow("Yarn Berry does not support global packages. Falling back to npm.")),Ra()),Ra(`Upgrade command: ${G.cyan(o.description)}`),Ra(),Ra(G.cyan("Upgrading...")),Ra();try{await(s=o.command,i=o.args,new Promise((e,t)=>{const r=f(s,i,{stdio:"inherit",shell:"win32"===process.platform});r.on("close",r=>{0===r?e():t(new Error(`Upgrade command exited with code ${r}`))}),r.on("error",e=>{t(e)})})),Ra(),Ra(G.green("✓ Upgrade complete!")),Ra(G.dim(`Run ${G.white("stably --version")} to verify.`))}catch(e){Pa(G.red("Upgrade failed:"),e instanceof Error?e.message:e),Ra(),Ra(G.dim("You can try manually running:")),Ra(G.cyan(` ${o.description}`)),process.exitCode=1}var s,i}(e)),xa.forEach(({args:e,description:t,name:r})=>{Va.command(r).description(t).helpOption(!1).helpCommand(!1).allowUnknownOption(!0).allowExcessArguments(!0).passThroughOptions().action(()=>Ca({overrideArgs:e,subcommand:r}))});var Xa=()=>{0!==za.length&&(process.stderr.write(za.join("")),za=[])};(async()=>{await(async()=>{if(!Fa&&"1"!==process.env.STABLY_DISABLE_TELEMETRY&&"1"!==process.env.DO_NOT_TRACK&&!process.argv.includes("--no-telemetry"))try{const{init:e}=await import("@hyperdx/node-opentelemetry");e({apiKey:"61d10b50-9534-47be-a732-95bfe461adb7",service:"stably-cli",consoleCapture:!0,disableTracing:!0,disableMetrics:!0,disableStartupLogs:!0,additionalResourceAttributes:{"cli.version":Yr,"node.version":process.version,"os.platform":process.platform}}),Fa=!0}catch{}})();try{await Va.parseAsync(process.argv),Fn.info("CLI completed successfully")}catch(e){if(!(e=>!!e&&"object"==typeof e&&"code"in e)(e))throw Fn.error("Unexpected CLI error",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),Xa(),Fn.flush(),Fn.printLogFileInfo(),await Ga(),e;const t="number"==typeof e.exitCode?e.exitCode:1,r=process.argv.slice(2).find(e=>!e.startsWith("-")),n=!!r&&!!qa(Va,[r]);if(("commander.excessArguments"===e.code||"commander.unknownCommand"===e.code)&&r&&!n)return za=[],Fn.warn("Unknown command",{command:r}),process.stderr.write(`command '${r}' not found\n`),Ja(),void(process.exitCode=t);Fn.debug("Commander error",{code:e.code,exitCode:t}),Xa(),process.exitCode=t}finally{Fn.flush(),await Ga()}})();