stably 4.8.7 → 4.8.9

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,normalize as a,basename as c}from"path";import{Command as l}from"commander";import{Buffer as u}from"buffer";import d,{exec as p,execSync as f,spawn as h}from"child_process";import m from"process";import g,{existsSync as y,statSync as b,realpathSync as v,createReadStream as w,readFileSync as _,mkdirSync as I,writeFileSync as E,appendFileSync as T,openSync as x,readSync as S,closeSync as A,rmSync as C}from"fs";import{fileURLToPath as R,URL as P}from"url";import U,{tmpdir as k,constants as L}from"os";import"timers/promises";import D from"stream";import{debuglog as O,promisify as $,TextDecoder as N,TextEncoder as B}from"util";import{createSdkMcpServer as M,tool as j,query as H}from"@anthropic-ai/claude-agent-sdk";import{match as F}from"ts-pattern";import G,{randomUUID as V}from"crypto";import Y from"net";import{createInterface as W}from"readline/promises";import z from"picocolors";import{simpleGit as K}from"simple-git";import{readFile as q,mkdir as J,writeFile as Q,unlink as X,access as Z,readdir as ee,stat as te,rm as re,appendFile as ne}from"fs/promises";import{log as oe,outro as se,spinner as ie,intro as ae,select as ce,isCancel as le}from"@clack/prompts";import ue,{z as de}from"zod";import pe from"open";import fe from"http";import he from"pino";import me from"sonic-boom";import{z as ge}from"zod/v3";import ye from"ws";import{useState as be,useRef as ve,useEffect as we,useCallback as _e,useMemo as Ie}from"react";import{jsx as Ee,jsxs as Te}from"react/jsx-runtime";import{createRequire as xe}from"module";import{parseDocument as Se}from"yaml";import{startTunnel as Ae}from"@stablyhq/runner-sdk";var Ce={cwdChanged:!1,newCwd:void 0,envFilesLoaded:[],envFileErrors:[],remoteEnvName:void 0},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++;var ke=process.argv.findIndex(e=>"--env"===e);-1!==ke&&process.argv[ke+1]&&!process.argv[ke+1].startsWith("-")&&(Ce.remoteEnvName=process.argv[ke+1],process.argv.splice(ke,2));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 Le={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 De(e){return(/\d+(?!.*\d+)/.exec(e)||[])[0]}function Oe(e){return e?/^(?:refs\/heads\/)?(?<branch>.+)$/i.exec(e)[1]:void 0}var $e={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:Oe(r?e.SYSTEM_PULLREQUEST_TARGETBRANCH:e.BUILD_SOURCEBRANCH),pr:t,isPr:r,prBranch:Oe(r?e.SYSTEM_PULLREQUEST_SOURCEBRANCH:void 0),root:e.BUILD_REPOSITORY_LOCALPATH}}},Ne={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})},Be={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})},Me={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}}},je={detect:({env:e})=>Boolean(e.BUDDY_WORKSPACE_ID),configuration({env:e}){const t=De(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}}},He="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Fe(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ge,Ve,Ye,We,ze,Ke,qe,Je,Qe={exports:{}};var Xe,Ze,et,tt,rt,nt,ot,st,it,at,ct,lt,ut,dt,pt,ft={exports:{}},ht={};function mt(){if(lt)return ct;lt=1;const e=r,t=function(){if(et)return Ze;et=1;const e=r,t=function(){if(Je)return qe;Je=1;const e="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,t=r,n=e?";":":",o=function(){if(Ke)return ze;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 Ke=1,e="win32"===process.platform||He.TESTING_WINDOWS?function(){if(Ve)return Ge;Ve=1,Ge=r,r.sync=function(r,n){return t(e.statSync(r),r,n)};var e=g;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 Ge}():function(){if(We)return Ye;We=1,Ye=t,t.sync=function(t,n){return r(e.statSync(t),n)};var e=g;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}(),ze=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}},ze}(),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 qe=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)},qe}(),n=function(){if(Xe)return ft.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 ft.exports=e,ft.exports.default=e,ft.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 Ze=function(e){return o(e)||o(e,!0)}}(),n=function(){if(tt)return ht;tt=1;const e=/([()\][%!^"`<>&|;, *?])/g;return ht.command=function(t){return t.replace(e,"^$1")},ht.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},ht}(),o=function(){if(at)return it;at=1;const e=g,t=function(){if(st)return ot;st=1;const e=nt?rt:(nt=1,rt=/^#!(.*)/);return ot=(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 it=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 ct=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 gt=Fe(function(){if(pt)return Qe.exports;pt=1;const e=d,t=mt(),r=function(){if(dt)return ut;dt=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 ut={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},ut}();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 Qe.exports=n,Qe.exports.spawn=n,Qe.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},Qe.exports._parse=t,Qe.exports._enoent=r,Qe.exports}());function yt(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 bt=(e,t)=>({name:`SIGRT${t+1}`,number:vt+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),vt=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"}],_t=()=>{const e=(()=>{const e=64-vt+1;return Array.from({length:e},bt)})();return[...wt,...e].map(It)},It=({name:e,number:t,description:r,action:n,forced:o=!1,standard:s})=>{const{signals:{[e]:i}}=L,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}],Tt=(()=>{const e=_t();return Object.fromEntries(e.map(Et))})();(()=>{const e=_t(),t=Array.from({length:65},(t,r)=>((e,t)=>{const r=((e,t)=>{const r=t.find(({name:t})=>L.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 xt=({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=m.cwd()}}})=>{s=null===s?void 0:s;const f=void 0===(o=null===o?void 0:o)?void 0:Tt[o].description,h=(({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 ${h}: ${i}`,y="[object Error]"===Object.prototype.toString.call(n),b=y?`${g}\n${n.message}`:g,v=[b,t,e].filter(Boolean).join("\n");return y?(n.originalMessage=n.message,n.message=v):n=new Error(v),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},St=["stdin","stdout","stderr"],At=[];At.push("SIGHUP","SIGINT","SIGTERM"),"win32"!==process.platform&&At.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),"linux"===process.platform&&At.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var Ct,Rt,Pt=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,Ut=Symbol.for("signal-exit emitter"),kt=globalThis,Lt=Object.defineProperty.bind(Object),Dt=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(kt[Ut])return kt[Ut];Lt(kt,Ut,{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}},Ot=class{},$t=globalThis.process;Pt($t)?new class extends Ot{#e="win32"===$t.platform?"SIGINT":"SIGHUP";#t=new Dt;#r;#n;#o;#s={};#i=!1;constructor(e){super(),this.#r=e,this.#s={};for(const t of At)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(!Pt(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 At)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,At.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 Pt(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&&Pt(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)}}($t):new class extends Ot{onExit(){return()=>{}}load(){}unload(){}},new TextEncoder,function(){if(Rt)return Ct;Rt=1;const{PassThrough:e}=D;Ct=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 Nt=(async()=>{})().constructor.prototype;["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(Nt,e)]);var Bt=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],Mt=/^[\w.-]+$/,jt=O("execa").enabled,Ht=(e,t)=>String(e).padStart(t,"0"),Ft=(e,t,n={})=>{const o=gt._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||m.cwd(),execPath:m.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:jt,...n}).env=(({env:e,extendEnv:t,preferLocal:n,localDir:o,execPath:s})=>{const i=t?{...m.env,...e}:e;return n?(({env:e=m.env,...t}={})=>{const n=yt({env:e={...e}});return t.path=e[n],e[n]=(({cwd:e=m.cwd(),path:t=m.env[yt()],preferLocal:n=!0,execPath:o=m.execPath,addExecPath:s=!0}={})=>{const i=e instanceof URL?R(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?R(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 St.map(t=>e[t]);if((e=>St.some(t=>void 0!==e[t]))(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${St.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,St.length);return Array.from({length:r},(e,r)=>t[r])})(n),"win32"===m.platform&&"cmd"===r.basename(e,".exe")&&t.unshift("/q"),{file:e,args:t,options:n,parsed:o}},Gt=(e,t,r)=>"string"==typeof t||u.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 Vt(e,t,r){const n=Ft(e,t,r),o=((e,t)=>Bt(e,t).join(" "))(e,t),s=((e,t)=>Bt(e,t).map(e=>(e=>"string"!=typeof e||Mt.test(e)?e:`"${e.replaceAll('"','\\"')}"`)(e)).join(" "))(e,t);((e,{verbose:t})=>{t&&m.stderr.write(`[${(()=>{const e=new Date;return`${Ht(e.getHours(),2)}:${Ht(e.getMinutes(),2)}:${Ht(e.getSeconds(),2)}.${Ht(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),_(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=d.spawnSync(n.file,n.args,{...n.options,input:i})}catch(e){throw xt({error:e,stdout:"",stderr:"",all:"",command:o,escapedCommand:s,parsed:n,timedOut:!1,isCanceled:!1,killed:!1})}const c=Gt(n.options,a.stdout,a.error),l=Gt(n.options,a.stderr,a.error);if(a.error||0!==a.status||null!==a.signal){const e=xt({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 Vt("git",["rev-parse","HEAD"],e).stdout}catch{return}}function Wt(e){try{const t=Vt("git",["rev-parse","--abbrev-ref","HEAD"],e).stdout;if("HEAD"===t){const t=Vt("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 zt=/^(?:.*)@(?:.*):(?:\d+\/)?(.*)\.git$/,Kt=/^\/(.*)\.git$/;function qt(e){if(e){if(e.match(zt))return e.replace(zt,"$1");try{return new URL(e).pathname.replace(Kt,"$1")}catch{return}}}var Jt,Qt={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:qt(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||De(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}`}}},Zt="https://cirrus-ci.com",er={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:`${Zt}/build/${e.CIRRUS_BUILD_ID}`,job:e.CIRRUS_TASK_ID,jobUrl:`${Zt}/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}}},tr={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})},rr={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}}},nr={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}}},or=({env:e})=>{try{const t=e.GITHUB_EVENT_PATH?JSON.parse(_(e.GITHUB_EVENT_PATH,"utf-8")):void 0;if(t&&t.pull_request)return{branch:t.pull_request.base?Oe(t.pull_request.base.ref):void 0,pr:t.pull_request.number}}catch{}return{pr:void 0,branch:void 0}},sr={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=Oe("pull_request_target"===e.GITHUB_EVENT_NAME?`refs/pull/${(e=>{const t=e.GITHUB_EVENT_PATH?JSON.parse(_(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?or({env:e}):void 0}}},ir={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}}},ar={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}}},cr={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}}},lr={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})},ur={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}}},dr={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}}},pr={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}}},fr={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}}},hr={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}}},mr={};function gr(){if(Jt)return mr;Jt=1,Object.defineProperty(mr,"__esModule",{value:!0}),mr.of=mr.PropertiesFile=void 0;var e,t=(e=g)&&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 mr.PropertiesFile=r,mr.of=function(...e){let t=new r;return t.of.apply(t,e),t},mr}var yr=Fe(gr()),br={root:"teamcity.build.workingDir",branch:"teamcity.build.branch"},vr=e=>{try{return yr.of(e)}catch{return}},wr=({env:e,cwd:t})=>{const r=e.TEAMCITY_BUILD_PROPERTIES_FILE?vr(e.TEAMCITY_BUILD_PROPERTIES_FILE):void 0,n=r?r.get("teamcity.configuration.properties.file"):void 0,o=n?vr(n):n;return Object.fromEntries(Object.keys(br).map(n=>[n,(r?r.get(br[n]):void 0)||(o?o.get(br[n]):void 0)||("branch"===n?Wt({env:e,cwd:t}):void 0)]))},_r={appveyor:Le,azurePipelines:$e,bamboo:Ne,bitbucket:Be,bitrise:Me,buddy:je,buildkite:Qt,circleci:Xt,cirrus:er,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:tr,codefresh:rr,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:nr,github:sr,gitlab:ir,jenkins:ar,netlify:cr,puppet:lr,sail:ur,screwdriver:dr,scrutinizer:pr,semaphore:fr,shippable:hr,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:Oe(e.JB_SPACE_GIT_BRANCH),slug:t&&r?`${t.toLowerCase()}/${r}`:void 0}}}},Ir=class e{git;config;snapshotTreeHash;snapshotIndexPath;constructor(e){this.config=e,this.git=K({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(k(),`git-diff-tracker-${V()}.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(k(),`git-diff-tracker-${V()}.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 X(e)}catch{}}var Tr="x-stably-org-id",xr={bodySerializer:e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t)},Sr=({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):Ar({allowReserved:e,name:r,value:t})).join(s);return"label"===n||"matrix"===n?s+i:i},Ar=({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)}`},Cr=({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])=>Ar({allowReserved:e,name:"deepObject"===n?`${r}[${t}]`:t,value:o})).join(i);return"label"===n||"matrix"===n?i+a:a},Rr=/\{[^{}]+\}/g;function Pr(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 Ur,kr=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},Lr=({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=Sr({allowReserved:i.allowReserved,explode:!0,name:o,style:"form",value:s,...i.array});e&&n.push(e)}else if("object"==typeof s){const e=Cr({allowReserved:i.allowReserved,explode:!0,name:o,style:"deepObject",value:s,...i.object});e&&n.push(e)}else{const e=Ar({allowReserved:i.allowReserved,name:o,value:s});e&&n.push(e)}}return n.join("&")},Dr=(e,t)=>!!t&&!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`)),Or=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(Rr);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,Sr({explode:n,name:o,style:s,value:i}));continue}if("object"==typeof i){r=r.replace(t,Cr({explode:n,name:o,style:s,value:i,valueOnly:!0}));continue}if("matrix"===s){r=r.replace(t,`;${Ar({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:Lr(e.querySerializer),url:e.url}),$r=(e,t)=>{const r={...e,...t};return r.baseUrl?.endsWith("/")&&(r.baseUrl=r.baseUrl.substring(0,r.baseUrl.length-1)),r.headers=Br(e.headers,t.headers),r},Nr=e=>{const t=[];return e.forEach((e,r)=>{t.push([r,e])}),t},Br=(...e)=>{const t=new Headers;for(const r of e){if(!r)continue;const e=r instanceof Headers?Nr(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},Mr=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}},jr=Lr({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Hr={"Content-Type":"application/json"},Fr=(e={})=>({...xr,headers:Hr,parseAs:"auto",querySerializer:jr,...e}),Gr=(e={})=>{let t=$r(Fr(),e);const r=()=>({...t}),n={error:new Mr,request:new Mr,response:new Mr},o=async e=>{const r={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:Br(t.headers,e.headers),serializedBody:void 0};return r.security&&await(async({security:e,...t})=>{for(const r of e){if(Dr(t,r.name))continue;const e=await kr(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:Or(r)}},s=async e=>{const{opts:t,url:r}=await o(e),s={redirect:"follow",...t,body:Pr(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:Or,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=$r(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")}},Vr=Gr(Fr({baseUrl:"https://api.stably.ai"})),Yr=e=>(e.client??Vr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs",...e}),Wr=e=>(e.client??Vr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}",...e}),zr="4.8.7",Kr=process.env.STABLY_API_URL||"https://api.stably.ai",qr=e=>{const t=new URL(e);return t.protocol="http:"===t.protocol?"ws:":"wss:",t},Jr=process.env.AUTH_URL||"https://auth.stably.ai",Qr=process.env.AUTH_CLIENT_ID||"288007877071cce81f269428ea78653a",Xr=process.env.AI_PROXY_URL||"https://ai-proxy.stably.ai",Zr=process.env.STABLY_AUTOHEAL_WS_URL||new URL("/autoheal",qr(Kr)).toString(),en=process.env.STABLY_CREATE_PROGRESS_WS_URL||new URL("/create-progress",qr(Kr)).toString(),tn="http://localhost:9876/auth/callback",rn=()=>Ur||(Ur=Gr(Fr({baseUrl:Kr,headers:{"X-STABLY-CLI-VERSION":zr,"X-STABLY-SOURCE":"cli"}}))),nn=async(e,t)=>{const r=await(n={body:{accessToken:e,orgId:t},client:rn()},(n.client??Vr).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},on=de.object({org_id:de.string(),org_name:de.string()}),sn=de.object({email:de.string(),org_id_to_org_member_info:de.record(de.string(),on).optional(),org_member_info:on.optional(),user_id:de.string()});de.object({email:de.string(),firstName:de.string().optional(),lastName:de.string().optional(),organizations:de.array(de.object({id:de.string(),name:de.string()})),userId:de.string()});var an=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)},cn=e=>{try{const t=sn.parse(an(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"}`)}},ln=async(e,t)=>{let n=e;const{root:o}=r.parse(n);for(;n!==o;){const e=r.join(n,t);try{return await Z(e),e}catch{n=r.dirname(n)}}},un=r.join(U.homedir(),".stably"),dn=r.join(un,"auth.json"),pn=".stably",fn="project.json",hn=ue.object({accessToken:ue.string(),expiresAt:ue.number(),idToken:ue.string().optional(),refreshToken:ue.string()}),mn=ue.object({orgId:ue.string(),orgName:ue.string(),projectId:ue.string(),projectName:ue.string()}),gn=async()=>{try{const e=await q(dn,"utf-8");return hn.parse(JSON.parse(e))}catch{return}},yn=async e=>{await J(un,{recursive:!0}),await Q(dn,JSON.stringify(e,null,2),{mode:384})},bn=async()=>{try{await X(dn)}catch{}},vn=async()=>{try{const e=await ln(process.cwd(),pn);if(!e)return;const t=r.join(e,fn),n=await q(t,"utf-8");return mn.parse(JSON.parse(n))}catch{return}},wn=async()=>{try{const e=await ln(process.cwd(),pn);e&&await X(r.join(e,fn))}catch{}},_n=e=>Date.now()>=e.expiresAt-3e5,In=async e=>{const t=new URLSearchParams({client_id:Qr,grant_type:"refresh_token",refresh_token:e}),r=await fetch(`${Jr}/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}},En=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`,Tn=(e,t,r)=>{e.writeHead(t,{"Content-Type":"text/html"}),e.end(r)},xn=(e,t)=>{const r=new URLSearchParams({client_id:Qr,code_challenge:e,code_challenge_method:"S256",redirect_uri:tn,response_type:"code",state:t});return`${Jr}/propelauth/oauth/authorize?${r.toString()}`},Sn=async e=>{const t=ie();let n;t.start("Loading user info...");try{n=cn(e.accessToken),t.stop(z.green(`✓ Logged in as ${z.cyan(n.email)}`))}catch(e){t.stop(z.red("✗ Failed to load user info"));const r=e instanceof Error?e.message:"Unknown error";return oe.error(r),{success:!1}}const o=await(async e=>{if(0===e.length)return void oe.error("You don't belong to any organizations.");if(1===e.length)return oe.info(`Using organization: ${z.cyan(e[0].name)}`),e[0];if(!process.stdin.isTTY)return oe.info(`Auto-selecting organization: ${z.cyan(e[0].name)}`),e[0];const t=await ce({message:"Select an organization",options:[...e].sort((e,t)=>e.name.localeCompare(t.name)).map(e=>({label:e.name,value:e.id}))});return le(t)?void 0:e.find(e=>e.id===t)})(n.organizations);if(!o)return oe.warn("Organization selection cancelled."),{success:!1};let s;t.start("Getting org credentials...");try{const r=await nn(e.accessToken,o.id);s={accessToken:r.accessToken,expiresAt:Date.now()+1e3*r.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken},t.stop(z.green("✓ Credentials obtained"))}catch(e){t.stop(z.red("✗ Failed to get org credentials"));const r=e instanceof Error?e.message:"Unknown error";return oe.error(r),{success:!1}}const i=await(async(e,t)=>{const r=ie();let n;r.start("Loading projects...");try{n=await(async({accessToken:e,orgId:t})=>{const r=await(n={auth:e,client:rn(),path:{orgId:t}},(n.client??Vr).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(z.green("✓ Projects loaded"))}catch(e){r.stop(z.red("✗ Failed to load projects"));const t=e instanceof Error?e.message:"Unknown error";return void oe.error(t)}if(0===n.length)return oe.error("No projects found in this organization."),void oe.info(`Create a project at ${z.underline(z.cyan("https://app.stably.ai"))}`);if(1===n.length)return oe.info(`Using project: ${z.cyan(n[0].name)}`),n[0];if(!process.stdin.isTTY)return oe.info(`Auto-selecting project: ${z.cyan(n[0].name)}`),n[0];const o=await ce({message:"Select a project",options:n.map(e=>({label:e.name,value:e.id}))});return le(o)?void 0:n.find(e=>e.id===o)})(s.accessToken,o.id);return i?(await(async e=>{const t=r.join(process.cwd(),pn),n=r.join(t,fn);await J(t,{recursive:!0}),await Q(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 q(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 Q(t,r)}else if(s.test(e)){const r=e.replace(s,`\n${n}\n`);await Q(t,r)}else await ne(t,`\n${n}\n`)}catch{await Q(t,`${n}\n`)}})(process.cwd())})({orgId:o.id,orgName:o.name,projectId:i.id,projectName:i.name}),oe.info(z.dim("Linked this directory to your Stably project.")),{scopedTokens:s,success:!0}):(oe.warn("Project selection cancelled."),{success:!1})},An=async()=>{if(zn())return oe.warn(`Environment variables ${z.cyan("STABLY_API_KEY")} and ${z.cyan("STABLY_PROJECT_ID")} are set.`),oe.warn("These will be used for authentication instead of OAuth login."),oe.warn("To use OAuth login, unset these environment variables first."),void se(z.yellow("Login skipped - using environment variable authentication."));const e=await gn();if(e){if(!_n(e)){if(await vn())return void se(z.yellow("You are already logged in. Run `stably logout` first to log out."));oe.info("You are logged in but haven't selected a project yet.");const t=await Sn(e);return void(t.success?(await yn(t.scopedTokens),se(z.green("Setup complete! You can now use Stably CLI."))):se(z.yellow("Setup incomplete. Run `stably login` to try again.")))}const t=ie();t.start("Refreshing session...");try{const r=await In(e.refreshToken);t.stop(z.green("✓ Session refreshed"));const n=await vn();if(n){t.start("Getting org credentials...");try{const e=await nn(r.accessToken,n.orgId),o={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:r.idToken,refreshToken:r.refreshToken};await yn(o),t.stop(z.green("✓ Credentials obtained")),se(z.green("Login successful"))}catch{await yn(r),t.stop(z.yellow("Using full credentials")),se(z.green("Login successful"))}}else{const e=await Sn(r);e.success?(await yn(e.scopedTokens),se(z.green("Setup complete! You can now use Stably CLI."))):se(z.yellow("Setup incomplete. Run `stably login` to try again."))}return}catch{t.stop(z.yellow("Session expired, proceeding with fresh login...")),await bn(),await wn()}}const{authorizeUrl:t,serverReady:r,waitForCallback:n}=(()=>{const{authorizeUrl:e,codeVerifier:t,state:r}=(()=>{const e=G.randomBytes(32).toString("base64url"),t=(r=e,G.createHash("sha256").update(r).digest("base64url"));var r;const n=G.randomBytes(16).toString("base64url");return{authorizeUrl:xn(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=fe.createServer((t,r)=>{const o=new P(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?(Tn(r,400,En(l)),i(),a.close(),void n({error:l,success:!1})):s&&c?c!==e?(Tn(r,400,En("Invalid state parameter (possible CSRF attack)")),i(),a.close(),void n({error:"State mismatch",success:!1})):(Tn(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})):(Tn(r,400,En("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:Qr,code:e,code_verifier:t,grant_type:"authorization_code",redirect_uri:tn}),n=await fetch(`${Jr}/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,oe.info("Opening browser for authentication..."),oe.info(z.dim("If browser doesn't open, visit:")),oe.info(`]8;;${t}${z.underline(z.cyan(t))}]8;;`);try{await pe(t)}catch{oe.warn("Could not open browser automatically. Please open the URL above manually.")}const o=ie();let s;o.start("Waiting for authentication...");try{s=await n(),o.stop(z.green("✓ Authentication successful"))}catch(e){o.stop(z.red("✗ Authentication failed"));const t=e instanceof Error?e.message:"Unknown error";se(z.red(`Login failed: ${t}`)),process.exit(1)}const i=await Sn(s);i.success?(await yn(i.scopedTokens),se(z.green("Setup complete! You can now use Stably CLI."))):(se(z.yellow("Setup incomplete. Run `stably login` to try again.")),process.exit(1))},Cn={fatal:60,error:50,warn:40,info:30,debug:20,trace:10},Rn=new Set(["help","login","logout","whoami","tunnel","create","fix","init","upgrade","test","show-report","codegen"]),Pn=(new Date).toISOString().split("T")[0],Un=r.join(U.tmpdir(),"stably-logs",Pn);g.mkdirSync(Un,{recursive:!0});var kn,Ln=process.argv.includes("--verbose")||process.argv.includes("-v"),Dn=process.env.STABLY_LOG_LEVEL?.toLowerCase(),On=Ln?"debug":void 0!==(kn=Dn)&&kn in Cn?Dn:"warn",$n=Cn[On],Nn=null,Bn=null,Mn=null,jn=[],Hn=!1,Fn=e=>{if(!Hn){Nn=(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(Un,`${t}-${n}.log`)})(e),(e=>{const t=["","=".repeat(60),"Stably CLI Debug Log",`Version: ${zr}`,`Generated: ${(new Date).toISOString()}`,`Node: ${process.version}`,`Platform: ${process.platform} ${U.release()}`,`CWD: ${process.cwd()}`,`Args: ${process.argv.slice(2).join(" ")}`,`Log Level (console): ${On}`,"=".repeat(60),""].join("\n");e.write(t)})(Bn=new me({dest:Nn,minLength:4096,sync:!1,append:!0})),Mn=he({level:"debug",timestamp:he.stdTimeFunctions.isoTime,base:{version:zr}},Bn);for(const{level:e,msg:t,context:r}of jn)r?Mn[e](r,t):Mn[e](t);jn=[],Hn=!0,Ln&&process.stderr.write(`${z.dim(`Debug log: ${Nn}`)}\n\n`)}},Gn=(()=>{const e=process.argv.slice(2).find(e=>!e.startsWith("-"));return e&&Rn.has(e)?e:null})();Gn&&Fn(Gn);var Vn=e=>(t,r)=>{if(Mn?r?Mn[e](r,t):Mn[e](t):jn.push({level:e,msg:t,context:r}),(e=>Cn[e]>=$n)(e)){const r=((e,t)=>`${{fatal:z.bgRed(z.white(" FATAL ")),error:z.red("error"),warn:z.yellow("warn"),info:z.cyan("info"),debug:z.dim("debug"),trace:z.dim("trace")}[e]} ${t}`)(e,t);process.stderr.write(`${r}\n`)}},Yn={fatal:Vn("fatal"),error:Vn("error"),warn:Vn("warn"),info:Vn("info"),debug:Vn("debug"),trace:Vn("trace"),initSession:e=>{Hn||Fn(e)},getLogFilePath:()=>Nn,flush:()=>{if(Bn)try{Bn.flushSync()}catch{}},printLogFileInfo:()=>{Nn&&(process.stderr.write(`\n${z.dim("Debug log written to:")}\n`),process.stderr.write(` ${z.cyan(Nn)}\n`),process.stderr.write(`${z.dim("Share this file with support for assistance.")}\n`))},getPinoLogger:()=>Mn};setInterval(()=>{Yn.flush()},3e4).unref(),process.on("beforeExit",()=>{Yn.flush()});var Wn=e=>{const t=()=>{Yn.flush(),Ln&&Yn.printLogFileInfo(),process.removeListener(e,t),process.kill(process.pid,e)};return t};process.on("SIGINT",Wn("SIGINT")),process.on("SIGTERM",Wn("SIGTERM"));var zn=()=>{const e=process.env.STABLY_API_KEY?.trim(),t=process.env.STABLY_PROJECT_ID?.trim();if(e&&t)return Yn.debug("Environment auth detected",{hasApiKey:!0,hasProjectId:!0}),{apiKey:e,projectId:t};Yn.debug("Environment auth not set",{hasApiKey:!!e,hasProjectId:!!t})},Kn=async()=>{Yn.debug("Checking for stored auth tokens");const e=await gn();if(!e)return void Yn.debug("No stored auth tokens found");const t=_n(e);if(Yn.debug("Auth tokens status",{expired:t}),!t){const t=await vn(),r=(e=>{try{const t=sn.parse(an(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(Yn.debug("Token scope check",{scope:r,hasContext:!!t}),t&&"full"===r)try{Yn.debug("Exchanging full token for org-scoped token",{orgId:t.orgId});const r=await nn(e.accessToken,t.orgId),n={accessToken:r.accessToken,expiresAt:Date.now()+1e3*r.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken};return await yn(n),Yn.debug("Token exchange successful"),n}catch(t){return Yn.debug("Token exchange failed, using existing token",{error:t instanceof Error?t.message:String(t)}),e}return e}try{Yn.debug("Attempting token refresh");const t=await In(e.refreshToken);Yn.debug("Token refresh successful");const r=await vn();if(r)try{Yn.debug("Exchanging refreshed token for org-scoped token");const e=await nn(t.accessToken,r.orgId),n={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:t.idToken,refreshToken:t.refreshToken};return await yn(n),n}catch{return await yn(t),t}return await yn(t),t}catch(e){return void Yn.warn("Token refresh failed",{error:e instanceof Error?e.message:String(e)})}},qn=async(e={})=>{Yn.debug("Requiring authentication",{autoLogin:e.autoLogin});const t=zn();if(t)return Yn.info("Using environment variable authentication"),{auth:t,type:"env"};let r=await Kn(),n=r?await vn():void 0;const o=process.stdin.isTTY&&process.stdout.isTTY;if(Yn.debug("OAuth auth check",{hasTokens:!!r,hasContext:!!n,canPrompt:o}),(!r||!n)&&e.autoLogin&&o){Yn.info("Prompting user to login"),r?oe.info("You are logged in but need to select an organization and project."):oe.info("You are not logged in."),oe.info("Press Enter to log in."),process.stdout.write(`${z.dim("Alternatively, set environment variables for an org API key:")}\n${z.dim(" STABLY_API_KEY=... STABLY_PROJECT_ID=... stably")}\n`),process.stdout.write("\n");const e=W({input:process.stdin,output:process.stdout});try{await e.question(z.dim("Press Enter to continue... "))}finally{e.close()}await An(),r=await Kn(),n=r?await vn():void 0}return r||(Yn.warn("Authentication required but no tokens available"),se(z.red("You are not logged in. Run `stably login` to authenticate.")),process.exit(1)),n||(Yn.warn("Authentication succeeded but no project context selected"),se(z.red("You haven't selected an organization and project. Run `stably login` to complete setup.")),process.exit(1)),Yn.info("OAuth authentication successful",{orgId:n.orgId,projectId:n.projectId}),{auth:{accessToken:r.accessToken,context:n},type:"oauth"}},Jn=e=>"env"===e.type?e.auth.projectId:e.auth.context.projectId,Qn=e=>"env"===e.type?e.auth.apiKey:e.auth.accessToken,Xn=e=>e?{...process.env,...e}:process.env,Zn=async()=>{Yn.info("[test] Resolving Stably test env");const e=(()=>{if(process.env.STABLY_WS_URL)return;if("https://api.stably.ai"===Kr)return;const e=Kr.startsWith("http://")?"ws://":"wss://";return`${Kr.replace(/^https?:\/\//,e).replace(/\/$/,"")}/reporter`})();Yn.debug("[test] WebSocket URL resolved",{wsUrl:e??"(default)"});const t=zn();if(t)return Yn.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}};Yn.info("[test] No env var auth, attempting OAuth auth");const r=Date.now(),n=await(async()=>{const e=zn();if(e)return{auth:e,type:"env"};const t=await Kn(),r=t?await vn():void 0;return t&&r?{auth:{accessToken:t.accessToken,context:r},type:"oauth"}:void 0})();if(Yn.info("[test] OAuth auth resolved",{durationMs:Date.now()-r,hasAuth:!!n,authType:n?.type}),!n||"env"===n.type)return void Yn.info("[test] No usable auth found");const o=process.env.STABLY_PROJECT_ID?.trim(),s=o||Jn(n);if(!s)return void Yn.warn("[test] No project ID available");Yn.info("[test] Fetching JWT API key",{projectId:s});const i=Date.now(),a=await(async(e,t)=>{try{Yn.debug("Requesting JWT API key",{projectId:t,apiUrl:Kr});const r=await(async({accessToken:e,projectId:t})=>{const r=await(n={auth:e,client:rn(),path:{projectId:t}},(n.client??Vr).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 Yn.debug("JWT API key obtained",{keyPrefix:r.apiKey.substring(0,10)}),r.apiKey}catch(e){return void Yn.warn("Failed to get JWT API key for test reporter",{error:e instanceof Error?e.message:String(e)})}})(n.auth.accessToken,s);Yn.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 Yn.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},eo=async()=>{const e=Ce.remoteEnvName;if(!e)return;const t=await qn(),r=Jn(t),n=Qn(t);Yn.debug("Fetching remote environment variables",{envName:e,projectId:r});const o=await(s={auth:n,client:rn(),path:{projectId:r,environment:e}},(s.client??Vr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/environments/{environment}/variables",...s}));var s;404===o.response.status&&(se(z.red(`Environment "${e}" not found. Check the name on your Stably dashboard.`)),process.exit(1)),401!==o.response.status&&403!==o.response.status||(se(z.red(`Access denied to environment "${e}".`)),process.exit(1)),o.error&&(se(z.red(`Failed to fetch environment "${e}": ${o.response.status}`)),process.exit(1));const i={},a=[];for(const e of o.data.variables)i[e.name]=e.value,e.sensitive&&e.value.length>0&&a.push(e.value);const c=o.data.variables.length,l=a.length;return process.stderr.write(`${z.cyan(`Loaded ${c} variable${1!==c?"s":""} from "${e}"`)}${l>0?z.dim(` (${l} sensitive)`):""}\n`),{variables:i,sensitiveValues:a}},to=e=>e?{[Tr]:e}:void 0,ro=de.object({context:de.string().min(1),autohealReportUrl:de.string(),skippedTests:de.array(de.object({testIdentifier:de.string(),testTitle:de.string(),consecutiveUnfixedCount:de.number()})).optional()}),no=ge.object({bucket:ge.string(),key:ge.string()}),oo=async({body:e,contentType:t,uploadUrl:r,errorContext:n="content"})=>{const o=await fetch(r,{body:e instanceof Uint8Array?Buffer.from(e):e,headers:{"Content-Type":t},method:"PUT"});if(!o.ok)throw new Error(`Failed to upload ${n} (${o.status})`)},so=ge.object({diffBucketPath:no,expiresInSeconds:ge.number(),key:ge.string(),uploadUrl:ge.string()}),io=ge.object({traceBucketPath:no,expiresInSeconds:ge.number(),key:ge.string(),uploadUrl:ge.string(),sensitiveValues:ge.array(ge.string())}),ao=async({authHeader:e,contentType:t="text/plain",orgId:r,runId:n})=>{const o=await(s={auth:e,body:{contentType:t},client:rn(),headers:to(r),path:{runId:n}},(s.client??Vr).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=so.parse(o.data);return{diffBucketPath:i.diffBucketPath,expiresInSeconds:i.expiresInSeconds,key:i.key,uploadUrl:i.uploadUrl}},co=async({authHeader:e,diffBucketPath:t,orgId:r,runId:n})=>{const o=await(s={auth:e,body:t,client:rn(),headers:to(r),path:{runId:n}},(s.client??Vr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-diff/confirm-upload",...s,headers:{"Content-Type":"application/json",...s.headers}}));var s;if(o.error)throw new Error(`Failed to confirm diff upload (${o.response.status})`)},lo=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=Zr,onUserMessage:o}){this.authHeader=e,this.orgId=t,this.runId=r,this.url=n,this.onUserMessage=o,Yn.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)}`;Yn.info("[ws] Connecting",{url:t,attempt:this.reconnectAttempts}),this.socket=new ye(t,{headers:e}),this.socket.on("open",()=>{Yn.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);Yn.debug("[ws] Received message",{type:r?.type}),"connected"===r?.type&&(Yn.info("[ws] Authenticated successfully"),this.isAuthenticated=!0,this.authenticationFailed=!1,this.flushPending()),"user_message"===r?.type&&"string"==typeof r.content&&(Yn.info("[ws] Received user message from web UI"),this.onUserMessage?.(r.content))}catch{}}),this.socket.on("close",(e,t)=>{Yn.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=>{Yn.warn("[ws] Connection error",{error:e.message})})}catch(e){Yn.warn("[ws] Failed to create WebSocket",{error:e instanceof Error?e.message:String(e)}),this.scheduleReconnect()}}scheduleReconnect(){this._isClosed||this.reconnectTimer||(this.reconnectAttempts++,Yn.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===ye.OPEN&&this.isAuthenticated}sendProgress(e){if(this._isClosed)return void Yn.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?(Yn.info("[ws] sendProgress: flushing terminal state immediately"),void this.flushPending()):void(this.debounceTimer||(this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.flushPending()},this.debounceMs))):(Yn.debug("[ws] sendProgress: not connected, queuing event",{phase:e.phase,socketState:this.socket?.readyState,isAuthenticated:this.isAuthenticated,reconnectAttempts:this.reconnectAttempts}),void(this.socket?.readyState===ye.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 Yn.debug("[ws] flushPending: not connected, re-queuing event",{phase:e.payload.phase}),void(this.pendingEvent=e);try{Yn.debug("[ws] flushPending: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),t=>{t&&(Yn.warn("[ws] flushPending: send failed",{error:t.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e))})}catch(t){Yn.warn("[ws] flushPending: send threw",{error:t instanceof Error?t.message:String(t)}),this.pendingEvent=e}}close(){if(this._isClosed)return;Yn.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)}},uo=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=en,onUserMessage:o}){this.authHeader=e,this.orgId=t,this.sessionId=r,this.url=n,this.onUserMessage=o,Yn.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)}`;Yn.info("[ws] Connecting",{url:t,attempt:this.reconnectAttempts}),this.socket=new ye(t,{headers:e}),this.socket.on("open",()=>{Yn.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);Yn.debug("[ws] Received message",{type:r?.type}),"connected"===r?.type&&(Yn.info("[ws] Authenticated successfully"),this.isAuthenticated=!0,this.authenticationFailed=!1,this.flushPending()),"user_message"===r?.type&&"string"==typeof r.content&&(Yn.info("[ws] Received user message from web UI"),this.onUserMessage?.(r.content))}catch{}}),this.socket.on("close",(e,t)=>{Yn.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=>{Yn.warn("[ws] Connection error",{error:e.message})})}catch(e){Yn.warn("[ws] Failed to create WebSocket",{error:e instanceof Error?e.message:String(e)}),this.scheduleReconnect()}}scheduleReconnect(){this._isClosed||this.reconnectTimer||(this.reconnectAttempts++,Yn.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===ye.OPEN&&this.isAuthenticated}sendProgress(e){if(this._isClosed)return void Yn.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?(Yn.info("[ws] sendProgress: flushing terminal state immediately"),void this.flushPending()):void(this.debounceTimer||(this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.flushPending()},this.debounceMs))):(Yn.debug("[ws] sendProgress: not connected, queuing event",{phase:e.phase,socketState:this.socket?.readyState,isAuthenticated:this.isAuthenticated,reconnectAttempts:this.reconnectAttempts}),void(this.socket?.readyState===ye.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 Yn.debug("[ws] flushPending: not connected, re-queuing event",{phase:e.payload.phase}),void(this.pendingEvent=e);try{Yn.debug("[ws] flushPending: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),t=>{t&&(Yn.warn("[ws] flushPending: send failed",{error:t.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e))})}catch(t){Yn.warn("[ws] flushPending: send threw",{error:t instanceof Error?t.message:String(t)}),this.pendingEvent=e}}close(){if(this._isClosed)return;Yn.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)}},po=ge.object({bucketPath:no,expiresInSeconds:ge.number(),key:ge.string(),uploadUrl:ge.string()}),fo=["auth login","auth logout","auth setup-git","auth switch","config set","secret set","secret delete","variable set","variable delete","repo delete","repo edit","repo rename","repo archive"];function ho(e){return/^\.env(\..*)?$/.test(e)||".stably-agent.env"===e}function mo(e){return Boolean(e&&"object"==typeof e&&"tool_input"in e&&e.tool_input&&"object"==typeof e.tool_input)}function go({action:e,pathKey:t}){return function({action:e,fileCheck:t,getBlockMessage:r,pathKey:n}){return async o=>{const s=function({input:e,pathKey:t}){if(!mo(e))return{decision:"block",reason:`Invalid tool call format: Expected an object with 'tool_input' property. Please ensure the tool call follows the correct structure: { tool_input: { ${t}: "path/to/file" } }`,success:!1,systemMessage:"Tool call blocked due to invalid input format"};const r=e.tool_input;return t in r?"string"==typeof r[t]?{path:r[t],success:!0}:{decision:"block",reason:`Invalid tool call format: The '${t}' parameter must be a string containing the file path, but received ${typeof r[t]}. Please provide a valid file path as a string. Example: { tool_input: { ${t}: "src/example.ts" } }`,success:!1,systemMessage:"Tool call blocked due to invalid parameter type"}:{decision:"block",reason:`Invalid tool call format: Missing required parameter '${t}'. Please provide the file path using the '${t}' parameter. Example: { tool_input: { ${t}: "path/to/file" } }`,success:!1,systemMessage:"Tool call blocked due to missing required parameters"}}({input:o,pathKey:n});if(!s.success)return s;const i=s.path.replace(/\\/g,"/"),a=i.split("/").pop()||i;return t(a)?{decision:"block",reason:r("reading"===e?"Access to":"writing"===e?"Writing to":"editing"===e?"Editing":"Searching in"),systemMessage:"AI blocked due to accessing sensitive content"}:{decision:"approve"}}}({action:e,fileCheck:ho,getBlockMessage:e=>`${e} .env files is not allowed. Environment variables and secrets should be managed in Stably's Test Data section instead. You can access these values using process.env in your test code.`,pathKey:t})}var yo=["rm","mv","git","gh","npx","npm","yarn","pnpm","bun"],bo=["stably","playwright"],vo=["push","fetch","pull","clone","ls-remote"];function wo(e){return e.trim().split(/\s+/).filter(e=>e.length>0)}function _o(e){let t=0;for(;t<e.length&&/^\S+=\S+$/.test(e[t]??"");)t+=1;return e.slice(t)}function Io(e,t){const r=a(e).replace(/\\/g,"/"),n=t.replace(/\\/g,"/"),o=n.endsWith("/")?n:`${n}/`;if(r.startsWith(o))return!0;const s=r.lastIndexOf(`/${o}`);if(-1===s)return!1;const i=r.slice(s+`/${o}`.length);return i.length>0&&!i.startsWith("../")}function Eo({onBeforeGitHubCommand:e,workspaceBoundary:t}){return async r=>{if(!mo(r))return{decision:"block",reason:"Invalid tool call format: Expected an object with tool_input property.",systemMessage:"Tool call blocked due to invalid input format"};const s=r.tool_input,{command:a}=s;if("string"!=typeof a)return{decision:"block",reason:"Invalid Bash command: command must be a string.",systemMessage:"Tool call blocked due to invalid command type"};const c=function(e){const t=e.trim().match(/^(?:\S+=\S+\s+)*(\S+)/);return t?.[1]}(a);if(!c)return{decision:"block",reason:"Invalid Bash command: could not parse command.",systemMessage:"Tool call blocked due to unparseable command"};if(!function(e){return"string"==typeof e&&yo.includes(e)}(c))return{decision:"block",reason:`The command "${c}" is not allowed. Only the following commands are permitted: ${yo.join(", ")}. Use the appropriate tools (Read, Write, Edit, Glob, Grep) for file operations instead.`,systemMessage:"Tool call blocked due to disallowed command"};if("npx"===c){const e=function(e){if(/(\s|^)npx\s+.*(\s|^)(-c|--call)(\s|=)/.test(e.trim()))return{valid:!1,reason:"The npx -c/--call form is not allowed. Use direct commands like `npx stably test ...` or `npx playwright test ...`."};const t=function(e){const t=_o(wo(e));if("npx"===t[0])for(let e=1;e<t.length;e+=1){const r=t[e];if(r){if("--"===r)return t[e+1];if(!r.startsWith("-"))return r}}}(e);if(!t)return{valid:!1,reason:"Invalid npx command: unable to determine which binary is being executed."};if(!new Set(bo).has(t))return{valid:!1,reason:`The npx binary "${t}" is not allowed. Only ${bo.join(", ")} are permitted.`};const r=function({command:e,binary:t}){const r=_o(wo(e)),n=r.findIndex(e=>e===t);if(-1!==n)for(let e=n+1;e<r.length;e+=1){const t=r[e];if(t&&!t.startsWith("-"))return t}}({command:e,binary:t});return"test"!==r?{valid:!1,reason:`The npx ${t} command must run the "test" subcommand.`}:{valid:!0}}(a);if(!e.valid)return{decision:"block",reason:e.reason,systemMessage:"Tool call blocked due to disallowed npx command"}}if("rm"===c){const e=function(e){const t=e.trim().match(/^rm\s+(?:-[a-zA-Z]+\s+|--[a-zA-Z-]+\s+)*(.+)$/),r=t?.[1]?.trim();return r?r.split(/\s+/).filter(e=>e.length>0):[]}(a);if(0===e.length)return{decision:"block",reason:"Invalid rm command: could not determine the file path(s) to remove.",systemMessage:"Tool call blocked due to invalid rm command"};if(t){const r=e.filter(e=>!function({targetPath:e,boundaryDir:t}){const r=function(e){if(y(e))return v.native(e);let t=e;const r=[];for(;!y(t);){const s=o(t);if(s===t)return n(e);r.unshift(t.slice(s.length+1)),t=s}const s=v.native(t);return r.length>0?n(s,...r):s}(e),s=v.native(t),a=r.endsWith(i)?r:r+i,c=s.endsWith(i)?s:s+i;return a.startsWith(c)||r===s}({targetPath:n(t,e),boundaryDir:t}));if(r.length>0)return{decision:"block",reason:`The rm command can only remove files within the workspace. The following path(s) are outside the workspace boundary: ${r.join(", ")}.`,systemMessage:"Tool call blocked due to rm outside workspace"}}else{const t=e.filter(e=>!(Io(e,"tests")||Io(e,".stably")));if(t.length>0)return{decision:"block",reason:`The rm command can only remove files in the tests/ directory or .stably/ directory. The following path(s) are not allowed: ${t.join(", ")}.`,systemMessage:"Tool call blocked due to rm outside allowed directories"}}}if("git"===c&&["-c","--config","--config-env"].some(e=>a.includes(` ${e} `)||a.includes(` ${e}=`)))return{decision:"block",reason:"Git config flags (-c, --config, --config-env) are not allowed for security reasons.",systemMessage:"Tool call blocked due to git config injection attempt"};if("git"===c&&function(e){const t=e.trim();return!!t.startsWith("git ")&&vo.some(e=>t.includes(` ${e}`)||t.includes(`git ${e}`))}(a)&&e)try{await e()}catch(e){console.error("[BashSecurityHook] Failed to refresh git token:",e)}if("gh"===c){const t=function(e){const t=e.toLowerCase();return fo.some(e=>t.includes(`gh ${e}`))?{allowed:!1,reason:"This gh subcommand is not allowed for security reasons. Only read operations and PR/issue management are permitted. Blocked subcommands include: auth, config set, secret/variable management, and destructive repo operations.",systemMessage:"Tool call blocked due to dangerous gh subcommand"}:t.includes("gh api")&&(/--method\s+(delete|put|patch)/i.test(e)||/-X\s+(DELETE|PUT|PATCH)/i.test(e))?{allowed:!1,reason:"The gh api command with destructive HTTP methods (DELETE, PUT, PATCH) is not allowed for security reasons. Only GET requests are permitted for raw API access.",systemMessage:"Tool call blocked due to destructive gh api method"}:{allowed:!0}}(a);if(!t.allowed)return{decision:"block",reason:t.reason,systemMessage:t.systemMessage};if(e)try{await e()}catch(e){console.error("[BashSecurityHook] Failed to refresh GitHub token for gh command:",e)}}return{decision:"approve"}}}var To=e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"text"===t.type&&"string"==typeof t.text},xo=e=>null!=e&&"object"==typeof e&&"tool_response"in e,So=e=>{if(!e||"object"!=typeof e)return;const t=e;return Array.isArray(t.tool_response)?t.tool_response:void 0},Ao=e=>{const t=So(e);if(t)return t.filter(To).map(e=>e.text).join("\n")||void 0},Co=/\u001b\[[0-9;]*m/g,Ro=e=>e.replace(Co,""),Po=/\$\{process\.env\.([A-Z_][A-Z0-9_]*)\}/g;function Uo(e,t){return e.replace(Po,(e,r)=>{const n=t[r];return null!=n?n:e})}function ko({envVars:e}){return async t=>{if(!mo(t))return{decision:"approve"};const r=t.tool_input,n={...r};let o=!1;if("string"==typeof r.text){const t=Uo(r.text,e);t!==r.text&&(n.text=t,o=!0)}if("string"==typeof r.url){const t=Uo(r.url,e);t!==r.url&&(n.url=t,o=!0)}if("string"==typeof r.function){const t=Uo(r.function,e);t!==r.function&&(n.function=t,o=!0)}if(Array.isArray(r.fields)){const t=r.fields.map(t=>{if("string"==typeof t.value){const r=Uo(t.value,e);if(r!==t.value)return o=!0,{...t,value:r}}return t});o&&(n.fields=t)}return o?{decision:"approve",hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",reason:"Evaluated environment variable placeholders in browser tool input.",updatedInput:n}}:{decision:"approve"}}}function Lo({onResult:e}){return async t=>{if(!xo(t))return{decision:"approve"};const r=Ao(t);if(!r)return{decision:"approve"};const n=function(e){const t=Ro(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 Do({onResult:e}){return async t=>{if(!xo(t))return{decision:"approve"};const r=Ao(t);if(!r)return{decision:"approve"};const n=function(e){const t=Ro(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 Oo=/\.(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&&Oo.test(n)&&e(n),{decision:"approve"}}}var No=$(p);async function Bo(){try{const{stdout:e}=await No('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 No(`pkill -KILL -P ${e} '.*' 2>/dev/null || true`)}))}catch{}}var Mo=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 jo(e){try{const t=f("git branch --show-current",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(!t)return;return{branch:t}}catch{return}}var Ho=[".ts",".js",".mts",".mjs",".cts",".cjs"],Fo=10240,Go=async({defaultContent:e,fileName:t,filePath:r})=>{try{const e=(await te(r)).size,n=await q(r,"utf-8"),o=Buffer.byteLength(n,"utf-8");if(o<=Fo)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<=Fo?s:s.slice(0,Fo)+`\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}},Vo=async({defaultContent:e,dirName:t,dirPath:r})=>{try{const e=await ee(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}},Yo=async({allowedEnvVars:e,mode:t,workspaceInfo:r,authHeader:n,customHeader:o,maxParallelWorkers:s})=>{const i=rn(),a=jo(r.absolutePath);Yn.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??Vr).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 Yn.warn("System prompt fetch failed: unauthorized (401)"),await bn(),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 Yn.debug("System prompt fetch failed: forbidden (403)"),new Error("Your organization does not have an active subscription. Manage your subscription at https://app.stably.ai or contact your organization admin.");if(c.error){Yn.warn("System prompt fetch failed",{error:c.error});const e=JSON.stringify(c.error);if(e.toLowerCase().includes("unauthorized")||e.toLowerCase().includes("unauthenticated"))throw await bn(),new Error("Your session has expired or been revoked. Credentials have been cleared. Please run `stably login` to re-authenticate.");throw new Error("Failed to fetch system prompt. Please check your network connection and try again. If this persists, run `stably login` to re-authenticate.")}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 Yn.debug("System prompt received",{size:u.length,appendedCustomHeader:!!o,hasPrContext:!!c.data.prContext}),{systemPrompt:u,prContext:c.data.prContext}},Wo=".stably-playwright-wrapper.config.*",zo=[".ts",".js",".mts",".mjs",".cts",".cjs"];function Ko(e){const t=n(e);if(y(t))for(const e of zo){const r=s(t,`playwright.config${e}`);if(y(r))return r}}var qo=["tests","e2e","__tests__","test"];function Jo(e){try{return y(e)&&b(e).isDirectory()}catch{return!1}}function Qo(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(z.dim(`Using output directory: ${e} (from ${r})`))}var Xo,Zo=["mcp__playwright-test__","mcp__auto-heal-report__","mcp__stably-agent-control__"],es=["planner_","generator_"],ts={"mcp__stably-agent-control__restart_mcp_servers":"Restarting Browser Tools","mcp__session-control__restart_mcp_servers":"Restarting Browser Tools"},rs=(e,t)=>{const r=t.find(t=>e.startsWith(t));return r?e.slice(r.length):e},ns=(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},os=e=>"mcp__auto-heal-report__capture-trace-proof"===e?"Verify Test Run":"mcp__auto-heal-report__generate-report"===e?"Generate Report":(e=>{const t=ts[e];if(t)return t;const r=rs(e,Zo);return rs(r,es).split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")})(e),ss=["test","bug","flake","ui_change","other"],is={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."},as=e=>is[e],cs=/[^a-zA-Z0-9-_]/g,ls=e=>{const t=e.trim().replace(cs,"_");return t.length>0?t.slice(0,80):void 0},us=e=>"string"==typeof e?ls(e):void 0,ds=xe("/");try{Xo=ds("worker_threads").Worker}catch(e){}var ps=Xo?function(e,t,r,n,o){var s=!1,i=new Xo(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,Xo.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}},fs=Uint8Array,hs=Uint16Array,ms=Int32Array,gs=new fs([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]),ys=new fs([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]),bs=new fs([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),vs=function(e,t){for(var r=new hs(31),n=0;n<31;++n)r[n]=t+=1<<e[n-1];var o=new ms(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}},ws=vs(gs,2),_s=ws.b,Is=ws.r;_s[28]=258,Is[258]=28;var Es,Ts=vs(ys,0),xs=Ts.b,Ss=Ts.r,As=new hs(32768);for(Ps=0;Ps<32768;++Ps)Es=(61680&(Es=(52428&(Es=(43690&Ps)>>1|(21845&Ps)<<1))>>2|(13107&Es)<<2))>>4|(3855&Es)<<4,As[Ps]=((65280&Es)>>8|(255&Es)<<8)>>1;var Cs=function(e,t,r){for(var n=e.length,o=0,s=new hs(t);o<n;++o)e[o]&&++s[e[o]-1];var i,a=new hs(t);for(o=1;o<t;++o)a[o]=a[o-1]+s[o-1]<<1;if(r){i=new hs(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[As[d]>>c]=l}else for(i=new hs(n),o=0;o<n;++o)e[o]&&(i[o]=As[a[e[o]-1]++]>>15-e[o]);return i},Rs=new fs(288);for(Ps=0;Ps<144;++Ps)Rs[Ps]=8;for(Ps=144;Ps<256;++Ps)Rs[Ps]=9;for(Ps=256;Ps<280;++Ps)Rs[Ps]=7;for(Ps=280;Ps<288;++Ps)Rs[Ps]=8;var Ps,Us=new fs(32);for(Ps=0;Ps<32;++Ps)Us[Ps]=5;var ks=Cs(Rs,9,0),Ls=Cs(Rs,9,1),Ds=Cs(Us,5,0),Os=Cs(Us,5,1),$s=function(e){for(var t=e[0],r=1;r<e.length;++r)e[r]>t&&(t=e[r]);return t},Ns=function(e,t,r){var n=t/8|0;return(e[n]|e[n+1]<<8)>>(7&t)&r},Bs=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(7&t)},Ms=function(e){return(e+7)/8|0},js=function(e,t,r){return(null==t||t<0)&&(t=0),(null==r||r>e.length)&&(r=e.length),new fs(e.subarray(t,r))},Hs=["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"],Fs=function(e,t,r){var n=new Error(t||Hs[e]);if(n.code=e,Error.captureStackTrace&&Error.captureStackTrace(n,Fs),!r)throw n;return n},Gs=function(e,t,r,n){var o=e.length,s=n?n.length:0;if(!o||t.f&&!t.l)return r||new fs(0);var i=!r,a=i||2!=t.i,c=t.i;i&&(r=new fs(3*o));var l=function(e){var t=r.length;if(e>t){var n=new fs(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=Ns(e,d,1);var b=Ns(e,d+1,3);if(d+=3,!b){var v=e[(P=Ms(d)+4)-4]|e[P-3]<<8,w=P+v;if(w>o){c&&Fs(0);break}a&&l(p+v),r.set(e.subarray(P,w),p),t.b=p+=v,t.p=d=8*w,t.f=u;continue}if(1==b)f=Ls,h=Os,m=9,g=5;else if(2==b){var _=Ns(e,d,31)+257,I=Ns(e,d+10,15)+4,E=_+Ns(e,d+5,31)+1;d+=14;for(var T=new fs(E),x=new fs(19),S=0;S<I;++S)x[bs[S]]=Ns(e,d+3*S,7);d+=3*I;var A=$s(x),C=(1<<A)-1,R=Cs(x,A,1);for(S=0;S<E;){var P,U=R[Ns(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+Ns(e,d,3),d+=2,k=T[S-1]):17==P?(L=3+Ns(e,d,7),d+=3):18==P&&(L=11+Ns(e,d,127),d+=7);L--;)T[S++]=k}}var D=T.subarray(0,_),O=T.subarray(_);m=$s(D),g=$s(O),f=Cs(D,m,1),h=Cs(O,g,1)}else Fs(1);if(d>y){c&&Fs(0);break}}a&&l(p+131072);for(var $=(1<<m)-1,N=(1<<g)-1,B=d;;B=d){var M=(k=f[Bs(e,d)&$])>>4;if((d+=15&k)>y){c&&Fs(0);break}if(k||Fs(2),M<256)r[p++]=M;else{if(256==M){B=d,f=null;break}var j=M-254;if(M>264){var H=gs[S=M-257];j=Ns(e,d,(1<<H)-1)+_s[S],d+=H}var F=h[Bs(e,d)&N],G=F>>4;if(F||Fs(3),d+=15&F,O=xs[G],G>3&&(H=ys[G],O+=Bs(e,d)&(1<<H)-1,d+=H),d>y){c&&Fs(0);break}a&&l(p+131072);var V=p+j;if(p<O){var Y=s-O,W=Math.min(O,V);for(Y+p<0&&Fs(3);p<W;++p)r[p]=n[Y+p]}for(;p<V;++p)r[p]=r[p-O]}}t.l=f,t.p=B,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?js(r,0,p):r.subarray(0,p)},Vs=function(e,t,r){r<<=7&t;var n=t/8|0;e[n]|=r,e[n+1]|=r>>8},Ys=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},Ws=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:Zs,l:0};if(1==o){var i=new fs(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 hs(p+1),h=zs(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 v=s[n].s;f[v]<t?m-=1<<t-f[v]++-1:++n}for(;n>=0&&m;--n){var w=s[n].s;f[w]==t&&(--f[w],++m)}h=t}return{t:new fs(f),l:h}},zs=function(e,t,r){return-1==e.s?Math.max(zs(e.l,t,r+1),zs(e.r,t,r+1)):t[e.s]=r},Ks=function(e){for(var t=e.length;t&&!e[--t];);for(var r=new hs(++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}},qs=function(e,t){for(var r=0,n=0;n<t.length;++n)r+=e[n]*t[n];return r},Js=function(e,t,r){var n=r.length,o=Ms(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)},Qs=function(e,t,r,n,o,s,i,a,c,l,u){Vs(t,u++,r),++o[256];for(var d=Ws(o,15),p=d.t,f=d.l,h=Ws(s,15),m=h.t,g=h.l,y=Ks(p),b=y.c,v=y.n,w=Ks(m),_=w.c,I=w.n,E=new hs(19),T=0;T<b.length;++T)++E[31&b[T]];for(T=0;T<_.length;++T)++E[31&_[T]];for(var x=Ws(E,7),S=x.t,A=x.l,C=19;C>4&&!S[bs[C-1]];--C);var R,P,U,k,L=l+5<<3,D=qs(o,Rs)+qs(s,Us)+i,O=qs(o,p)+qs(s,m)+i+14+3*C+qs(E,S)+2*E[16]+3*E[17]+7*E[18];if(c>=0&&L<=D&&L<=O)return Js(t,u,e.subarray(c,c+l));if(Vs(t,u,1+(O<D)),u+=2,O<D){R=Cs(p,f,0),P=p,U=Cs(m,g,0),k=m;var $=Cs(S,A,0);for(Vs(t,u,v-257),Vs(t,u+5,I-1),Vs(t,u+10,C-4),u+=14,T=0;T<C;++T)Vs(t,u+3*T,S[bs[T]]);u+=3*C;for(var N=[b,_],B=0;B<2;++B){var M=N[B];for(T=0;T<M.length;++T){var j=31&M[T];Vs(t,u,$[j]),u+=S[j],j>15&&(Vs(t,u,M[T]>>5&127),u+=M[T]>>12)}}}else R=ks,P=Rs,U=Ds,k=Us;for(T=0;T<a;++T){var H=n[T];if(H>255){Ys(t,u,R[257+(j=H>>18&31)]),u+=P[j+257],j>7&&(Vs(t,u,H>>23&31),u+=gs[j]);var F=31&H;Ys(t,u,U[F]),u+=k[F],F>3&&(Ys(t,u,H>>5&8191),u+=ys[F])}else Ys(t,u,R[H]),u+=P[H]}return Ys(t,u,R[256]),u+P[256]},Xs=new ms([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Zs=new fs(0),ei=function(e,t,r,n,o,s){var i=s.z||e.length,a=new fs(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=Xs[t-1],p=d>>13,f=8191&d,h=(1<<r)-1,m=s.p||new hs(32768),g=s.h||new hs(h+1),y=Math.ceil(r/3),b=2*y,v=function(t){return(e[t]^e[t+1]<<y^e[t+2]<<b)&h},w=new ms(25e3),_=new hs(288),I=new hs(32),E=0,T=0,x=s.i||0,S=0,A=s.w||0,C=0;x+2<i;++x){var R=v(x),P=32767&x,U=g[R];if(m[P]=U,g[R]=P,A<=x){var k=i-x;if((E>7e3||S>24576)&&(k>423||!l)){u=Qs(e,c,0,w,_,I,T,S,C,x-C,u),S=E=T=0,C=x;for(var L=0;L<286;++L)_[L]=0;for(L=0;L<30;++L)I[L]=0}var D=2,O=0,$=f,N=P-U&32767;if(k>2&&R==v(x-N))for(var B=Math.min(p,k)-1,M=Math.min(32767,x),j=Math.min(258,k);N<=M&&--$&&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>B)break;var F=Math.min(N,H-2),G=0;for(L=0;L<F;++L){var V=x-N+L&32767,Y=V-m[V]&32767;Y>G&&(G=Y,U=V)}}}N+=(P=U)-(U=m[P])&32767}if(O){w[S++]=268435456|Is[D]<<18|Ss[O];var W=31&Is[D],z=31&Ss[O];T+=gs[W]+ys[z],++_[257+W],++I[z],A=x+D,++E}else w[S++]=e[x],++_[e[x]]}}for(x=Math.max(x,A);x<i;++x)w[S++]=e[x],++_[e[x]];u=Qs(e,c,l,w,_,I,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=Js(c,u+1,e.subarray(x,K))}s.i=i}return js(a,0,n+Ms(u)+o)},ti=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}(),ri=function(e,t,r,n,o){if(!o&&(o={l:1},t.dictionary)){var s=t.dictionary.subarray(-32768),i=new fs(s.length+e.length);i.set(s),i.set(e,s.length),e=i,o.w=s.length}return ei(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)},ni=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},oi=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},si=[],ii=function(){return[fs,hs,ms,gs,ys,bs,_s,xs,Ls,Os,As,Hs,Cs,$s,Ns,Bs,Ms,js,Fs,Gs,gi,ci,li]},ai=function(){return[fs,hs,ms,gs,ys,bs,Is,Ss,ks,Rs,Ds,Us,As,Xs,Zs,Cs,Vs,Ys,Ws,zs,Ks,qs,Js,Qs,Ms,js,ei,ri,mi,ci]},ci=function(e){return postMessage(e,[e.buffer])},li=function(e){return e&&{out:e.size&&new fs(e.size),dictionary:e.dictionary}},ui=function(e,t,r,n,o,s){var i=function(e,t,r,n){if(!si[r]){for(var o="",s={},i=e.length-1,a=0;a<i;++a)o=oi(e[a],o,s);si[r]={c:oi(e[i],o,s),e:s}}var c=ni({},si[r].e);return ps(si[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()}},di=function(e,t){return e[t]|e[t+1]<<8},pi=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},fi=function(e,t){return pi(e,t)+4294967296*pi(e,t+4)},hi=function(e,t,r){for(;r;++t)e[t]=r,r>>>=8};function mi(e,t){return ri(e,t||{},0,0)}function gi(e,t){return Gs(e,{i:2},t&&t.out,t&&t.dictionary)}var yi=function(e,t,r,n){for(var o in e){var s=e[o],i=t+o,a=n;Array.isArray(s)&&(a=ni(n,s[1]),s=s[0]),s instanceof fs?r[i]=[s,a]:(r[i+="/"]=[new fs(0),a],yi(s,i,r,n))}},bi="undefined"!=typeof TextEncoder&&new TextEncoder,vi="undefined"!=typeof TextDecoder&&new TextDecoder;try{vi.decode(Zs,{stream:!0})}catch(e){}function wi(e,t){if(bi)return bi.encode(e);for(var r=e.length,n=new fs(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 fs(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 js(n,0,o)}var _i=function(e){var t=0;if(e)for(var r in e){var n=e[r].length;n>65535&&Fs(9),t+=n+4}return t},Ii=function(e,t,r,n,o,s,i,a){var c=n.length,l=r.extra,u=a&&a.length,d=_i(l);hi(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)&&Fs(10),hi(e,t,f<<25|p.getMonth()+1<<21|p.getDate()<<16|p.getHours()<<11|p.getMinutes()<<5|p.getSeconds()>>1),t+=4,-1!=s&&(hi(e,t,r.crc),hi(e,t+4,s<0?-s-2:s),hi(e,t+8,r.size)),hi(e,t+12,c),hi(e,t+14,d),t+=16,null!=i&&(hi(e,t,u),hi(e,t+6,r.attrs),hi(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;hi(e,t,+h),hi(e,t+2,g),e.set(m,t+4),t+=4+g}return u&&(e.set(a,t),t+=u),t},Ei="function"==typeof queueMicrotask?queueMicrotask:"function"==typeof setTimeout?setTimeout:function(e){e()};function Ti(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 xi=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 Si(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 Ai(e){switch(7&Si(e)){case 0:return Si(e),!0;case 1:return e.next(8),!0;case 2:const t=Si(e);return e.next(t),!0;case 5:return e.next(4),!0}return!1}function Ci(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!Ti(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!Ti(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 xi(e,t);let n=0;for(;;){if(!Ai(r)&&!r.hasError())return!1;if(r.hasError())break;n++}return n>0}(e,s))}var Ri=[/^\/$/,/^\*+$/,/^[0-9]+$/],Pi=["/artifact/","https://","http://","*********"],Ui=new Set(["sha1","_sha1","pageref","downloadsPath","tracesDir","pageId"]);function ki({sensitiveValues:e,str:t}){return e.reduce((e,t)=>e.replaceAll(t,"[REDACTED]"),t)}function Li({sensitiveValues:e,value:t}){return"string"==typeof t?ki({sensitiveValues:e,str:t}):Array.isArray(t)?t.map(t=>Li({sensitiveValues:e,value:t})):function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(t)?Oi({obj:t,sensitiveValues:e}):t}function Di(e){return!!Ui.has(e)||e.toLowerCase().endsWith("sha1")}function Oi({obj:e,sensitiveValues:t}){return Object.fromEntries(Object.entries(e).map(([e,r])=>[e,Di(e)?r:Li({sensitiveValues:t,value:r})]))}function $i({error:e,sensitiveValues:t}){return e?{...e,message:ki({sensitiveValues:t,str:e.message})}:void 0}function Ni({content:e,sensitiveValues:t}){const r=new N,n=new B,o=ki({sensitiveValues:t,str:r.decode(e)});return n.encode(o)}var Bi=$(function(e,t,r){r||(r=t,t={}),"function"!=typeof r&&Fs(7);var n=[],o=function(){for(var e=0;e<n.length;++e)n[e]()},s={},i=function(e,t){Ei(function(){r(e,t)})};Ei(function(){i=r});for(var a=e.length-22;101010256!=pi(e,a);--a)if(!a||e.length-a>65558)return i(Fs(13,0,1),null),o;var c=di(e,a+8);if(c){var l=c,u=pi(e,a+16),d=4294967295==u||65535==l;if(d){var p=pi(e,a-12);(d=101075792==pi(e,p))&&(l=c=pi(e,p+32),u=pi(e,p+48))}for(var f=t&&t.filter,h=function(t){var r=function(e,t,r){var n=di(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(vi)return vi.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:js(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&&Fs(8),s}(e.subarray(t+46,t+46+n),!(2048&di(e,t+8))),s=t+46+n,i=pi(e,t+20),a=r&&4294967295==i?function(e,t){for(;1!=di(e,t);t+=4+di(e,t+2));return[fi(e,t+12),fi(e,t+4),fi(e,t+20)]}(e,s):[i,pi(e,t+24),pi(e,t+42)],c=a[0],l=a[1],u=a[2];return[di(e,t+10),c,l,o,s+di(e,t+30)+di(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+di(e,t+26)+di(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 v=e.subarray(y,y+l);if(p<524288||l>.8*p)try{b(null,gi(v,{out:new fs(p)}))}catch(e){b(e,null)}else n.push(function(e,t,r){return r||(r=t,t={}),"function"!=typeof r&&Fs(7),ui(e,t,[ii],function(e){return ci(gi(e.data[0],li(e.data[1])))},1,r)}(v,{size:p},b))}else b(Fs(14,"unknown compression type "+a,1),null);else b(null,js(e,y,y+l));else b(null,null)},m=0;m<l;++m)h()}else i(null,{});return o}),Mi=$(function(e,t,r){r||(r=t,t={}),"function"!=typeof r&&Fs(7);var n={};yi(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){Ei(function(){r(e,t)})};Ei(function(){p=r});var f=function(){var e=new fs(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;Ii(e,a,o,o.f,o.u,s);var u=30+o.f.length+_i(o.extra),d=a+u;e.set(o.c,d),Ii(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){hi(e,t,101010256),hi(e,t+8,r),hi(e,t+10,r),hi(e,t+12,n),hi(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=ti[255&r^t[n]]^r>>>8;e=r},d:function(){return~e}}}(),g=c.length;m.p(c);var y=wi(t),b=y.length,v=h.comment,w=v&&wi(v),_=w&&w.length,I=_i(h.extra),E=0==h.level?0:8,T=function(r,n){if(r)d(),p(r,null);else{var o=n.length;l[e]=ni(h,{size:g,crc:m.d(),c:n,f:y,m:w,u:b!=t.length||w&&v.length!=_,compression:E}),i+=30+b+I+o,a+=76+2*(b+I)+(_||0)+o,--s||f()}};if(b>65535&&T(Fs(11,0,1),null),E)if(g<16e4)try{T(null,mi(c,h))}catch(e){T(e,null)}else u.push(function(e,t,r){return r||(r=t,t={}),"function"!=typeof r&&Fs(7),ui(e,t,[ai],function(e){return ci(mi(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 ji({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 N,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 F(e).with({type:"console"},e=>({...e,args:e.args?.map(e=>({...e,preview:ki({sensitiveValues:t,str:e.preview}),value:Li({sensitiveValues:t,value:e.value})})),text:ki({sensitiveValues:t,str:e.text})})).with({type:"before"},e=>({...e,params:Oi({obj:e.params,sensitiveValues:t}),title:e.title?ki({sensitiveValues:t,str:e.title}):void 0})).with({type:"after"},e=>({...e,error:$i({error:e.error,sensitiveValues:t}),result:void 0!==e.result?Li({sensitiveValues:t,value:e.result}):void 0})).with({type:"action"},e=>({...e,error:$i({error:e.error,sensitiveValues:t}),params:Oi({obj:e.params,sensitiveValues:t}),result:void 0!==e.result?Li({sensitiveValues:t,value:e.result}):void 0,title:e.title?ki({sensitiveValues:t,str:e.title}):void 0})).with({type:"event"},e=>({...e,params:Oi({obj:e.params,sensitiveValues:t})})).with({type:"stdout"},{type:"stderr"},e=>({...e,text:void 0!==e.text?ki({sensitiveValues:t,str:e.text}):void 0})).with({type:"error"},e=>({...e,message:ki({sensitiveValues:t,str:e.message})})).with({type:"log"},e=>({...e,message:ki({sensitiveValues:t,str:e.message})})).with({type:"context-options"},e=>({...e,options:Oi({obj:e.options,sensitiveValues:t}),title:e.title?ki({sensitiveValues:t,str:e.title}):void 0})).with({type:"frame-snapshot"},e=>({...e,snapshot:Oi({obj:e.snapshot,sensitiveValues:t})})).with({type:"resource-snapshot"},e=>({...e,snapshot:Oi({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 ki({sensitiveValues:t,str:e})}});return n.encode(o.join("\n"))}({content:e,sensitiveValues:r}):n.endsWith(".html")||n.endsWith(".dat")||n.endsWith(".json")?Ni({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!")}(b(e));const r=x(e,"r"),n=Buffer.alloc(515),o=S(r,n,0,515,0);return A(r),Ci(n,o,t)}return Ci(e,void 0!==t?.size?t.size:e.length,t)}(Buffer.from(e),{size:e.length})}(e)?e:Ni({content:e,sensitiveValues:t})}({content:e,sensitiveValues:r}):e}function Hi(e=process.cwd()){let t=n(e);for(;;){const e=Fi(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=Gi(t);let r=!1,i=t;for(;;){const e=s(i,"node_modules"),t=s(e,n);if(y(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 Fi(e){const t=s(e,"package.json");let r;try{r=_(t,"utf-8")}catch{return}try{return JSON.parse(r)}catch{return}}function Gi(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(y(s(r,n)))return e;const e=o(r);if(e===r)return;r=e}}function Vi(e){if("npm"===e||"pnpm"===e)return["npx","playwright"];if("yarn"===e)return["yarn","playwright"];throw new Error("Package manager not supported")}var Yi=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Wi=e=>(e instanceof Error?e.message:String(e)).slice(0,400),zi=({outputDir:e,representativeTest:t})=>{const r=["test","--trace=on","--workers=1","--retries=0","--reporter=list","--output",e];return t.filePath&&r.push(t.filePath),t.testTitle?r.push("--grep",Yi(t.testTitle)):t.testIdentifier&&r.push("--grep",`^${Yi(t.testIdentifier)}$`),r},Ki=async e=>{const t=await ee(e,{withFileTypes:!0}),n=[];for(const o of t){const t=r.join(e,o.name);if(o.isDirectory())n.push(...await Ki(t));else if(o.isFile()&&"trace.zip"===o.name){const e=await te(t);n.push({path:t,mtimeMs:e.mtimeMs})}}return n},qi=async e=>{try{const t=await ee(e,{withFileTypes:!0});for(const n of t){const t=r.join(e,n.name);n.isDirectory()?await qi(t):n.isFile()&&".last-run.json"===n.name&&await re(t,{force:!0})}}catch{}},{zSuiteAutoHealReport:Ji,zRepresentativeTest:Qi}=function(e){const t=e.enum(ss),r=["Classification of the root cause:","",`- test: ${as("test")}`,`- bug: ${as("bug")}`,`- flake: ${as("flake")}`,`- ui_change: ${as("ui_change")}`,`- other: ${as("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). Include file:line references (e.g., `src/tests/login.spec.ts:42`) to back up your claim."),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). Include file:line references (e.g., `src/tests/login.spec.ts:42`) showing where changes were made."),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). Include file:line references (e.g., `src/tests/login.spec.ts:42`) pointing to the problematic code."),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}}(ge),Xi=({authHeader:e,diffTracker:t,orgId:n,runId:o,workingDir:s})=>M({name:"auto-heal-report",tools:[j("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:ge.string().min(1).describe("Issue identifier for deterministic output paths and storage key naming."),proofId:ge.string().min(1).optional().describe("Optional id for deterministic proof naming and deduplication."),representativeTest:Qi.optional().default({}),testCaseId:ge.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=ge.string().min(1).parse(t),u=null==i?void 0:ge.string().min(1).parse(i),d=null==c?void 0:ge.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=Hi(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=>ls(e)??"issue")(t),d=(({proofId:e,testCaseId:t})=>us(t)??us(e))({testCaseId:a,proofId:o}),p=r.join(c,".stably","autoheal-proof",u,d??"issue"),[f,...m]=Vi(l.packageManager),g=[...m,...zi({outputDir:p,representativeTest:s})];try{await re(p,{force:!0,recursive:!0}),await J(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=h(t,e,{cwd:r,env:n??process.env,stdio:["ignore","ignore","pipe"],shell:"win32"===process.platform});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:f,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."};const d=await(async e=>{const t=await Ki(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:`No trace.zip was produced${0!==r?` (test exit code ${r??"unknown"})`:""}: ${l.trim().slice(0,280)}`.trim()};await qi(p);const{traceBucketPath:m,uploadUrl:y,sensitiveValues:b}=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:rn(),headers:to(s),path:{runId:i}},(c.client??Vr).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=io.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=w(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||Ri.some(t=>t.test(e))||Pi.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 Bi(new Uint8Array(t)),s=Object.entries(o),i=await Promise.all(s.map(async([e,t])=>[e,await ji({content:t,filename:e,sensitiveValues:n})])),a=Object.fromEntries(i);return Mi(a)}({traceBuffer:new Uint8Array(Buffer.concat(r)),sensitiveValues:t})}({tracePath:d,sensitiveValues:b});try{await oo({body:v,contentType:"application/zip",uploadUrl:y,errorContext:"trace"})}catch(e){return{status:"upload_failed",representativeTest:s,error:Wi(e)}}return{status:"captured",representativeTest:s,storage:m}}catch(e){return{status:"capture_failed",representativeTest:s,error:Wi(e)}}})({authHeader:e,issueId:l,orgId:n,proofId:u,representativeTest:Qi.parse(a??{}),runId:o,testCaseId:d,workingDir:s}),f="string"==typeof d?{testCaseId:d,...p}:p;return{content:[{text:JSON.stringify(f),type:"text"}]}}),j("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:rn(),headers:to(t),path:{runId:n}},(s.client??Vr).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 ao({authHeader:e,contentType:"text/plain",orgId:n,runId:o});await oo({body:s,contentType:"text/plain",uploadUrl:r,errorContext:"diff"}),await co({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"}),Zi=({onComplete:e,onRestartRequested:t})=>M(e?{name:"session-control",tools:[j("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:ge.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:[j("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 restart SCHEDULED for end of this turn.\n\nCRITICAL: END YOUR TURN NOW. Do not call any more tools.\nThe restart only happens AFTER your turn completes.\n\nAny tools called in this turn will use the OLD servers and fail.\n\nThe system will automatically continue with "[SYSTEM] MCP servers were restarted successfully" once ready.'}]})))]}),ea=ge.object({commentUrl:ge.string()}),ta=({prContext:e,authHeader:t,orgId:r,onReportPosted:n})=>M({name:"create-report",tools:[j("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:ge.string().describe("A summary of the tests created. Include what features/flows are tested and any important notes."),filesCreated:ge.array(ge.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:[];Yn.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",Kr).toString(),a={Authorization:e,"Content-Type":"application/json"};t&&(a["x-stably-org-id"]=t),Yn.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 Yn.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=ea.parse(await c.json());return Yn.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),Yn.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 Yn.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}}})]}),ra=["QUEUED","RUNNING","PASSED","FAILED","TIMEDOUT","CANCELLED","INTERRUPTED"],na=["LOCAL","CI","WEB"],oa=["MANUAL","SCHEDULED","UI","API","GITHUB_ACTION","SUITE_RUN"],sa=({authHeader:e,orgId:t,projectId:r})=>M({name:"run-history",tools:[j("list_runs",'List test runs with optional filters for the current project.\nUse this to find runs with autoheal status on specific branches.\n\nCommon use cases:\n- Find failed runs on the current branch: { "branch": "feature-x", "status": "FAILED", "limit": 10 }\n- Find failed runs on master/main: { "branch": "master", "status": "FAILED", "limit": 10 }\n\nReturns an array of runs with their runId, status, autoHealStatus, branch, and timestamps.',{branch:ge.string().optional().describe("Filter by branch name"),status:ge.enum(ra).optional().describe("Filter by status: QUEUED|RUNNING|PASSED|FAILED|TIMEDOUT|CANCELLED|INTERRUPTED"),limit:ge.number().min(1).max(100).optional().describe("Max results (1-100, default 20)"),source:ge.enum(na).optional().describe("Filter by source: LOCAL|CI|WEB"),trigger:ge.enum(oa).optional().describe("Filter by trigger: MANUAL|SCHEDULED|UI|API|GITHUB_ACTION|SUITE_RUN"),suite:ge.string().optional().describe("Filter by suite name"),after:ge.string().optional().describe("Pagination: return runs after this runId"),before:ge.string().optional().describe("Pagination: return runs before this runId")},async({branch:n,status:o,limit:s,source:i,trigger:a,suite:c,after:l,before:u})=>{const d="string"==typeof n?n:void 0,p="string"==typeof o?o:void 0,f="number"==typeof s?s:void 0,h="string"==typeof i?i:void 0,m="string"==typeof a?a:void 0,g="string"==typeof c?c:void 0,y="string"==typeof l?l:void 0,b="string"==typeof u?u:void 0;Yn.info("[run-history] list_runs called",{branch:d,status:p,limit:f});try{const n=await Yr({auth:e,client:rn(),headers:to(t),query:{projectId:r,branchName:d,status:p,limit:f,source:h,trigger:m,suiteName:g,afterRunId:y,beforeRunId:b}});if(n.error||!n.data){const e=n.response?`API error: ${n.response.status}`:`API error: ${String(n.error)}`;return Yn.error("[run-history] list_runs failed",{error:e}),{content:[{type:"text",text:`Error: ${e}`}],isError:!0}}return Yn.info("[run-history] list_runs success",{runCount:n.data.runs?.length??0,hasMore:n.data.hasMore}),{content:[{type:"text",text:JSON.stringify(n.data,null,2)}]}}catch(e){const t=e instanceof Error?e.message:String(e);return Yn.error("[run-history] list_runs exception",{error:t}),{content:[{type:"text",text:`Error: ${t}`}],isError:!0}}}),j("view_run",'Get detailed information about a specific run including issues and test results.\nUse this after list_runs to examine runs where autoHealStatus is "COMPLETED".\n\nThe response includes:\n- Run metadata (status, branch, timestamps)\n- Issues array with result ("fixed"/"unfixed"), rootCause, and relatedTestIdentifiers\n- Test results with their outcomes\n\nUse this to determine which tests were previously fixed and why.',{runId:ge.string().min(1).describe("The run ID to view (required)")},async({runId:r})=>{const n="string"==typeof r?r:String(r);Yn.info("[run-history] view_run called",{runId:n});try{const r=await Wr({auth:e,client:rn(),headers:to(t),path:{runId:n},query:{detail:"full"}});if(r.error||!r.data){const e=r.response?404===r.response.status?`Run "${n}" not found`:`API error: ${r.response.status}`:`API error: ${String(r.error)}`;return Yn.error("[run-history] view_run failed",{error:e,runId:n}),{content:[{type:"text",text:`Error: ${e}`}],isError:!0}}return Yn.info("[run-history] view_run success",{runId:n}),{content:[{type:"text",text:JSON.stringify(r.data,null,2)}]}}catch(e){const t=e instanceof Error?e.message:String(e);return Yn.error("[run-history] view_run exception",{error:t,runId:n}),{content:[{type:"text",text:`Error: ${t}`}],isError:!0}}})]}),ia=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]"),aa=(e,t)=>({message:ia(e),status:t?.status,statusText:t?.statusText}),ca=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"]),la=async({authHeader:e,mode:t,maxTurnsOverride:r})=>{const n=rn();Yn.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??Vr).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 Yn.warn("Subagent definitions fetch failed: unauthorized (401)"),await bn(),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 Yn.debug("Subagent definitions fetch failed: forbidden (403)"),new Error("Your organization does not have an active subscription. Manage your subscription at https://app.stably.ai or contact your organization admin.");if(o.error)throw Yn.warn("Subagent definitions fetch failed",{error:o.error}),new Error("Failed to fetch subagent definitions. Please check your network connection and try again. If this persists, run `stably login` to re-authenticate.");const{subagents:i}=o.data;return Yn.debug("Subagent definitions received",{count:Object.keys(i).length}),i},ua=r.dirname(R(import.meta.url)),da=r.join(".claude-plugin","plugin.json"),pa=[r.join("packages","agent-plugin","stably-plugin"),r.join("agent-plugin","stably-plugin")];function fa(e){return y(r.join(e,da))}var{zStablyYaml:ha}=function(e){const t=e.object({cron:e.string(),stablyTestArgs:e.string().optional(),timezone:e.string().optional(),command:e.string().optional(),autofix:e.boolean().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(),maxBudgetUsd:e.number().positive().optional()}),n=e.object({fix:r.optional()}),o=e.object({setupScript:e.string().optional()});return{zStablyYaml:e.object({schedules:e.record(e.string(),t).optional(),agent:n.optional(),cloud:o.optional()}),zAgentConfig:n,zAgentFixConfig:r,zScheduleEntry:t,zCloudConfig:o}}(de),ma=async(e,t)=>{try{const r=await ln(e,t);if(!r)return void Yn.debug(`No ${t} found`);const n=await q(r,"utf-8");if(!n.trim())return;return n.length>1e4?(Yn.warn(`${t} exceeds max length (${n.length} > 10000), truncating`,{path:r}),{content:n.slice(0,1e4),path:r}):(Yn.debug(`Loaded ${t} rules`,{path:r,contentLength:n.length}),{content:n,path:r})}catch(e){return void Yn.warn(`Failed to read ${t}`,{error:e})}},ga=de.object({verdict:de.enum(["PASS","FAIL","INCONCLUSIVE"]),steps:de.array(de.string()).min(1),reason:de.string().nullable(),evidence:de.array(de.string())}).superRefine((e,t)=>{"PASS"===e.verdict||e.reason&&0!==e.reason.trim().length||t.addIssue({code:de.ZodIssueCode.custom,path:["reason"],message:"reason is required for FAIL and INCONCLUSIVE verdicts"})}),ya=/\bmcp__playwright-mcp__[a-z0-9_]+\b/gi,ba=/\.playwright-mcp(?:\/[^\s"'`)\]]*)?/gi,va=/\bplaywright[\s_-]?mcp\b/gi;function wa(e){return e.replace(ya,"browser_tool").replace(ba,"verification-artifact").replace(va,"browser automation")}function _a(e){return{...e,steps:e.steps.map(e=>wa(e)),reason:e.reason?wa(e.reason):null,evidence:e.evidence.map(e=>wa(e))}}function Ia(e){const t=e.matchAll(/```verdict\s*\r?\n([\s\S]*?)\r?\n```/g);let r=null;for(const e of t)try{const t=JSON.parse(e[1]??"");r=ga.parse(t)}catch{}return r}var Ea=["Bash","Read","Write","Edit","Glob","Grep","Task","Skill"],Ta=["Task","mcp__playwright-test","Skill"],xa=["Bash","Read","Write","Edit","Glob","Grep","mcp__session-control"],Sa=e=>{if("EPIPE"!==e.code)throw e},Aa="__main__",Ca=[3e3,5173,4173,8080,4200,8e3],Ra=/\b(TEST_EMAIL|TEST_PASSWORD|auth|authentication|credentials|login|log in|sign in)\b/i,Pa=/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/i,Ua=/playwright[\s_-]?mcp/i,ka=e=>"mcp__auto-heal-report__generate-report"===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)}))}async function Da(e){return new Promise(t=>{const r=new Y.Socket;let n=!1;const o=e=>{n||(n=!0,r.destroy(),t(e))};r.setTimeout(700),r.once("connect",()=>o(!0)),r.once("timeout",()=>o(!1)),r.once("error",()=>o(!1)),r.connect(e,"127.0.0.1")})}var Oa=async e=>{if("single"===e.mode){const t=Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt;Yn.initSession(t||"create-from-diff")}else if("verify"===e.mode){const t=Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt;Yn.initSession(t||"verify")}else"fix"===e.mode&&Yn.initSession(`fix-${e.runId}`);Yn.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),Yn.debug("Checking authentication");const a=await qn({autoLogin:"chat"===e.mode||"init"===e.mode}),c=Qn(a);Yn.debug("Authentication resolved",{authType:a.type});const l="oauth"===a.type?a.auth.context.orgId:void 0,u=r.resolve(process.cwd()),d="fix"!==e.mode,p=r.join(u,".env"),f=d&&g.existsSync(p)&&g.statSync(p).isFile(),h=f?t(g.readFileSync(p,"utf8")):{};Yn.debug("Environment file",{path:p,exists:f,variableCount:Object.keys(h).length});const m="chat"!==e.mode&&"init"!==e.mode,b="chat"===e.mode,v="single"===e.mode,w="verify"===e.mode,_=v||w;let I=new Mo;const E="chat"===e.mode?e.getHelpText:void 0,T="verify"===e.mode?(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt).trim():"";let x="verify"===e.mode?e.url?.trim()||function(e){const t=Array.isArray(e)?e.join(" "):e,r=e=>e.replace(/[),.;!?]+$/,""),n=e=>{const t=r(e);try{return new URL(t).toString()}catch{return}},o=t.match(/https?:\/\/[^\s"'`<>]+/i);if(o)return n(o[0]);const s=t.match(/(?<!@)\b(?:localhost|(?:\d{1,3}\.){3}\d{1,3}|(?:[a-z0-9-]+\.)+[a-z]{2,63})(?::\d{2,5})?(?:\/[^\s"'`<>]*)?/i);if(!s)return;const i=r(s[0]),a=i.split("/")[0]??i,c=a.split(":")[0]?.toLowerCase()??"",l=c.includes(".")?c.split(".").at(-1)??"":"";return new Set(["ts","tsx","js","jsx","md","json","yaml","yml","txt","css"]).has(l)?void 0:n(`${"localhost"===c||"127.0.0.1"===c?"http":"https"}://${i}`)}(e.prompt):void 0;if("verify"===e.mode&&!e.url&&x&&Yn.info("[verify] Using URL extracted from prompt",{url:x}),"verify"!==e.mode||x||(x=await async function(){for(const e of Ca)if(await Da(e))return`http://localhost:${e}`}(),x?Yn.info("[verify] Detected local application URL",{url:x}):Yn.info("[verify] No common localhost dev server detected")),"verify"===e.mode&&!1!==e.interactive){const e=await async function({envFilePath:e,envFromFile:t,initialUrl:n,verifyPromptText:o,workingDir:s}){if(!process.stdin.isTTY||!process.stdout.isTTY)return{resolvedUrl:n};const i=r.join(s,"STABLY.md"),a=g.existsSync(i),c=a?await g.promises.readFile(i,"utf8").catch(()=>{}):void 0;let l=n?.trim()||void 0;const u=!l,d=(({envEmail:e,envPassword:t,promptIncludesEmail:r,stablyMdContent:n})=>!Boolean(e?.trim()&&t?.trim())&&!r&&!(e=>!!e&&Ra.test(e))(n))({envEmail:process.env.TEST_EMAIL??t.TEST_EMAIL,envPassword:process.env.TEST_PASSWORD??t.TEST_PASSWORD,promptIncludesEmail:Pa.test(o),stablyMdContent:c}),p=!a;if(!u&&!d&&!p)return{resolvedUrl:l};const f=W({input:process.stdin,output:process.stdout}),h=async(e,t=!0)=>{const r=t?" [Y/n] ":" [y/N] ",n=(await f.question(`${e}${r}`)).trim().toLowerCase();return n?"y"===n||"yes"===n:t},m=async(r,n)=>{const o=g.existsSync(e)?await g.promises.readFile(e,"utf8"):"",s=new RegExp(`^${i=r,i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}=.*$`,"m");var i;const a=`${r}=${(e=>/^[A-Za-z0-9_./:@-]+$/.test(e)?e:`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)(n)}`,c=s.test(o)?o.replace(s,a):`${o}${o&&!o.endsWith("\n")?"\n":""}${a}\n`;await g.promises.writeFile(e,c,"utf8"),t[r]=n};try{if(u){const e=(await f.question("Starting URL (optional, Enter to auto-infer): ")).trim();e&&(l=e)}if(d&&await h("No TEST_EMAIL/TEST_PASSWORD found in .env and no auth guidance found in STABLY.md. Configure credentials in .env now?",!0)){const e=(await f.question("TEST_EMAIL: ")).trim(),t=(await f.question("TEST_PASSWORD: ")).trim();e&&t&&(await m("TEST_EMAIL",e),await m("TEST_PASSWORD",t),process.env.TEST_EMAIL||(process.env.TEST_EMAIL=e),process.env.TEST_PASSWORD||(process.env.TEST_PASSWORD=t))}if(p&&await h("No STABLY.md found. Create one at repository root for project instructions?",!0)){const e=["# STABLY.md","","Project instructions for Stably agent runs.","","## Verify Notes","- Keep verification scope to requested behavior only.","- Use TEST_EMAIL and TEST_PASSWORD env vars for authenticated flows.","","## Special Instructions","- Add project-specific constraints here.",""].join("\n");await g.promises.writeFile(i,e,"utf8");const t=(await f.question("Special verify instruction to append to STABLY.md (optional): ")).trim();if(t){const e=await g.promises.readFile(i,"utf8"),r=/(^|\n)## Special Instructions\s*$/m.test(e)?`${e}${e.endsWith("\n")?"":"\n"}- ${t}\n`:`${e}${e.endsWith("\n")?"":"\n"}\n## Special Instructions\n- ${t}\n`;await g.promises.writeFile(i,r,"utf8")}}return{resolvedUrl:l}}finally{f.close()}}({envFilePath:p,envFromFile:h,initialUrl:x,verifyPromptText:T,workingDir:u});x=e.resolvedUrl?.trim()||x}"verify"!==e.mode||x||Yn.warn("No verify URL provided and no local app detected on common ports. The agent will try to infer a URL from code/config.");const S={log:[],promptDisplay:F(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:"single"},e=>{const t=(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt)?.trim();return t||"Creating tests from PR/branch changes"}).with({mode:"verify"},e=>{const t=(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt)?.trim();return t||"Verifying application"}).exhaustive(),status:"running"};let A,C,R,P,U=m,k=!1,L=!1,D=0,O=0,$=!1;const N=[];let B,M,j=[],V=!1,Y=!1,K=0;const J=new Map;let Q=null,X=!1,Z=!1;const ee=Date.now();let te,re="fix"===e.mode?{suiteId:e.runId,phase:"initializing",totalTests:null,fixedTests:0,failedTests:0,currentTestDescription:null,lastTestDescription:null,startedAt:ee,endedAt:null,isError:!1,updatedAt:ee,recentActivity:[],workers:[{id:Aa,testDescription:"Orchestrator",workerType:"main",status:"running",summary:null,startedAt:ee,endedAt:null,activity:[]}]}:null;const ne=new Set,oe=(e,t)=>{if(!re)return;const r=re.workers.map(r=>{if(r.id!==e)return r;const n=[...r.activity,{...t,timestamp:Date.now()}].slice(-15);return{...r,activity:n}});ae({workers:r})},se=e=>{if(!re)return;const t=[...re.recentActivity,{...e,timestamp:Date.now()}].slice(-10);ae({recentActivity:t})},ie=e=>(re?.workers??[]).map(t=>t.id===Aa?{...t,status:e?"failed":"succeeded",endedAt:t.endedAt??Date.now()}:"running"===t.status?{...t,status:"failed",endedAt:Date.now()}:t),ae=e=>{re&&!te?.isClosed&&(re={...re,...e,updatedAt:Date.now()},te?.sendProgress(re))},ce=async t=>{if("fix"===e.mode){if("STARTED"===t){if(X)return;X=!0}else{if(Z)return;Z=!0}try{await(async({authHeader:e,orgId:t,runId:r,status:n})=>{const o=await(s={auth:e,body:{status:n},client:rn(),headers:to(t),path:{runId:r}},(s.client??Vr).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{}}},le=Date.now();let ue,de=null;const pe=e=>{de&&!ue?.isClosed&&(de={...de,...e,updatedAt:Date.now()},ue?.sendProgress(de))},fe=e=>{if(!de)return;const t=[...de.recentActivity,{...e,timestamp:Date.now()}].slice(-10);pe({recentActivity:t})};if(_||"fix"===e.mode)try{const t=new URL("/internal/v1/cli/progress",Kr).toString(),r={Authorization:c,"Content-Type":"application/json"};l&&(r["x-stably-org-id"]=l);const n="single"===e.mode?"create":"verify"===e.mode?"verify":"fix",o=await fetch(t,{method:"POST",headers:r,body:JSON.stringify({mode:n,projectId:Jn(a),agentId:G.randomUUID(),..."fix"===e.mode?{playwrightSuiteRunId:e.runId}:{}}),signal:AbortSignal.timeout(1e4)});if(o.ok){const{sessionId:t}=await o.json();if(_){const r="single"===e.mode||"verify"===e.mode?Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt:null,n=jo(u);de={sessionId:t,phase:"initializing",startedAt:le,endedAt:null,isError:!1,updatedAt:le,currentActivity:null,filesCreated:[],recentActivity:[],prompt:r||null,environment:{gitBranch:n?.branch??null,workingDirectory:u,nodeVersion:process.version,cliVersion:zr}},ue=new uo({authHeader:c,orgId:l,sessionId:t,onUserMessage:e=>{I&&(Yn.info("[ws] Injecting web UI message into agent",{contentLength:e.length}),fe({type:"user_message",summary:e}),Re({text:`[Web] ${e}`}),I.pushText(`[Message from web UI user]: ${e}`),U||(U=!0,Ne({status:"running"})))}}),ue.start(),pe({phase:"initializing"})}Yn.info(`[${n}] Progress session created`,{sessionId:t})}else{const e=await o.text().catch(()=>"");Yn.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);Yn.warn(`[progress] Session creation failed (non-fatal): ${t}`)}const he={current:e=>{}},me={current:async()=>{}},{addSubagentActivity:ge,addSubagentStart:ye,addTool:xe,addToolResult:Ae,appendText:Ce,appendUserMessage:Re,cleanup:Pe,setExiting:Ue,setRunningLabel:ke,setStatus:Le,setSubagentStatus:De,updateFixProgress:Oe}=await(async(e,t)=>{const{Box:r,Static:n,Text:o,render:s,useInput:i}=await import("ink"),a=!!process.stdin.isTTY,c=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],l=()=>Ee(o,{inverse:!0,children:" "}),u=(({Box:e,Text:t,useInput:r},n,o)=>function({onChoice:s,prompt:i}){const[a,c]=be(0),[l,u]=be(!1),[d,p]=be(""),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=os(i.toolName),m=ns(i.toolName,i.input);return Te(e,{borderColor:"yellow",borderStyle:"round",flexDirection:"column",marginTop:1,paddingX:1,paddingY:0,children:[Ee(t,{bold:!0,color:"yellow",children:"Permission Required"}),Te(e,{flexDirection:"column",marginTop:1,children:[Ee(t,{color:"gray",dimColor:!0,children:h}),null!=m&&Te(t,{color:"gray",children:[" ",m]})]}),null!=i.decisionReason&&Ee(e,{marginTop:1,children:Te(t,{color:"gray",children:["Reason: ",i.decisionReason]})}),Te(e,l?{flexDirection:"column",marginTop:1,children:[Ee(t,{color:"gray",children:"Enter message for AI (press Enter to submit, Esc to cancel):"}),Te(t,{children:[Ee(t,{color:"yellow",children:">"})," ",d,Ee(n,{})]})]}:{flexDirection:"column",marginTop:1,children:[Ee(t,{color:"gray",children:"Use ↑↓ arrows or number keys to select:"}),f.map((e,r)=>Ee(t,{children:Te(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]=be(Date.now());we(()=>{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"},debugging:{label:"Debugging tests",color:"magenta"},validation:{label:"Validating fixes",color:"blue"},complete:{label:"Complete",color:"green"}}[e.phase],p=e.fixedTests+e.failedTests,f=("fixing"===e.phase||"debugging"===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 Ee(t,{flexDirection:"column",children:Te(n,{children:[Ee(n,{color:d,bold:!0,children:u}),Ee(n,{color:"gray",children:f}),Te(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 Te(t,{flexDirection:"column",children:[Te(n,{color:c,bold:!0,children:[l," in ",a]}),null!==e.totalTests&&Te(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 Te(t,{flexDirection:"column",marginTop:1,children:[Te(n,{children:[Ee(n,{color:o,bold:!0,children:"Agent"}),r.description?Te(n,{color:"gray",children:[" (",r.description,")"]}):null]}),r.activities.length>0&&Ee(t,{flexDirection:"column",marginLeft:2,children:r.activities.map(e=>(e=>"tool"===e.kind?Te(n,{color:"gray",dimColor:!0,children:["• ",e.content]},e.id):"tool_result"===e.kind||"text"===e.kind?Ee(n,{color:"gray",children:e.content},e.id):null)(e))})]},e.id)}return"tool"===e.kind?Te(n,{color:"gray",dimColor:!0,children:["• ",e.content]},e.id):"tool_result"===e.kind?Ee(n,{color:"gray",children:e.content},e.id):"user"===e.kind?Te(n,{color:"cyan",children:["You: ",e.content]},e.id):Ee(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:v,state:w}){const[_,I]=be({value:"",cursor:0}),E=_.value,T=_.cursor,x=ve(!1),S=ve(void 0),[A,C]=be(!1),R=ve(0),P=ve(!1),U=w.log.at(-1),k="text"===U?.kind&&"running"===w.status,L=w.log.findIndex(e=>"subagent"===e.kind&&"running"===e.subagent?.status),D=d?0:-1!==L?L:k?w.log.length-1:w.log.length;we(()=>{w.log.length<R.current&&(R.current=0),D>R.current&&(R.current=D)},[w.log.length,D]);const O=w.log.slice(0,R.current),$=w.log.slice(R.current),N=!!w.permissionPrompt,B=_e(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&&B().catch(()=>process.exit(1))},{isActive:s}),we(()=>{if(N||!b)return;process.stdout.isTTY&&process.stdout.write("[?2004h");const e=e=>{const t=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n");t&&I(e=>({value:e.value.slice(0,e.cursor)+t+e.value.slice(e.cursor),cursor:e.cursor+t.length}))},t=t=>{const r=t.toString();if(r.includes("[200~")){P.current=!0;const t=r.slice(r.indexOf("[200~")+6),n=t.includes("[201~"),o=n?t.slice(0,t.indexOf("[201~")):t;return n&&(P.current=!1),void e(o)}if(r.includes("[201~")){const t=r.slice(0,r.indexOf("[201~"));return e(t),void(P.current=!1)}P.current?e(r):""!==r&&"[1;5~"!==r?""!==r&&"[4;5~"!==r?""!==r&&"[1~"!==r&&"OH"!==r&&"[7~"!==r?""!==r&&"[4~"!==r&&"OF"!==r&&"[8~"!==r||I(e=>({...e,cursor:m(e.value,e.cursor)})):I(e=>({...e,cursor:h(e.value,e.cursor)})):I(e=>({...e,cursor:e.value.length})):I(e=>({...e,cursor:0}))};return process.stdin.on("data",t),()=>{process.stdin.off("data",t),process.stdout.isTTY&&process.stdout.write("[?2004l")}},[N,b]),o((e,t)=>{if(!t.ctrl||"c"!==e){if(t.return){if(P.current)return;const e=E.trim();return e&&b?.(e),void I({value:"",cursor:0})}t.ctrl&&"w"===e||t.ctrl&&t.backspace?I(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?I(e=>({...e,cursor:p(e.value,e.cursor)})):t.ctrl&&t.rightArrow||t.meta&&"f"===e?I(e=>({...e,cursor:f(e.value,e.cursor)})):t.leftArrow?I(e=>({...e,cursor:Math.max(0,e.cursor-1)})):t.rightArrow?I(e=>({...e,cursor:Math.min(e.value.length,e.cursor+1)})):t.ctrl&&"a"===e?I(e=>({...e,cursor:0})):t.ctrl&&"e"===e?I(e=>({...e,cursor:e.value.length})):!e||t.ctrl||t.meta||t.escape||e.includes("")||/^\[./.test(e)||/^O[A-D]$/.test(e)||I(t=>({value:t.value.slice(0,t.cursor)+e+t.value.slice(t.cursor),cursor:t.cursor+e.length})):I(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&&!N});const M=Ie(()=>"running"===w.status?Ee(a,{label:w.runningLabel??"Working"}):"success"!==w.status?Ee(n,{color:"red",children:"✖ Failed"}):void 0,[w.runningLabel,w.status]),j=!(v||!b||"running"!==w.status||0!==w.log.length||w.resultText||w.errorText),H="running"===w.status&&!j||w.log.length>0||w.resultText||w.errorText||"running"!==w.status;return Te(t,{flexDirection:"column",children:[Ee(r,{items:["header"],children:()=>Te(t,{flexDirection:"column",flexShrink:0,children:[Ee(n,{color:"cyan",bold:!0,children:"Stably Agent"}),Ee(t,{flexDirection:"column",marginTop:1,children:Ee(n,{color:"gray",children:w.promptDisplay})})]},"header")}),O.length>0&&Ee(r,{items:O,children:e=>u(e)}),$.length>0&&Ee(t,{flexDirection:"column",children:$.map(e=>u(e))}),"error"===w.status&&w.errorText&&Ee(t,{marginTop:1,children:Ee(n,{color:"red",children:w.errorText})}),"success"===w.status&&w.resultText&&Ee(t,{marginTop:1,children:Ee(n,{children:w.resultText})}),H&&Ee(t,{flexDirection:"column",flexShrink:0,marginTop:1,children:"running"===w.status&&w.fixProgress?Te(t,{flexDirection:"column",children:[Te(t,{children:[Ee(a,{}),Ee(n,{children:" "}),Ee(c,{progress:w.fixProgress})]}),("fixing"===w.fixProgress.phase||"debugging"===w.fixProgress.phase)&&w.log.flatMap(e=>{const{subagent:r}=e;if("subagent"!==e.kind||"fix-worker"!==r?.subagentType&&"debug-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 Te(t,{flexDirection:"column",children:[Te(n,{children:[" ",Ee(a,{}),Te(n,{color:"gray",children:[r.description||r.subagentType||"worker",s>0?` (${s} ${1===s?"cycle":"cycles"})`:""]})]}),c&&Te(n,{color:"gray",dimColor:!0,children:[" • ",c.content]}),l&&Te(n,{color:"gray",dimColor:!0,children:[" ",l]})]},e.id)})]}):"success"!==w.status&&"error"!==w.status||!w.fixProgress?M:Ee(l,{progress:w.fixProgress})}),null!=w.permissionPrompt&&null!=y&&Ee(i,{onChoice:y,prompt:w.permissionPrompt}),null!=b&&null==w.permissionPrompt&&!w.isExiting&&Te(t,{borderColor:"gray",borderStyle:"round",flexDirection:"column",flexShrink:0,marginTop:1,paddingX:1,paddingY:0,children:[Ee(n,{color:"gray",children:"Type a message and press Enter. Press Ctrl+C to exit."}),Te(n,{children:[Ee(n,{color:"yellow",children:">"})," ",E.slice(0,T),Ee(e,{}),E.slice(T)]})]}),A&&Te(t,{marginTop:1,flexDirection:"column",children:[Ee(n,{color:"yellow",children:"Press Ctrl+C again to exit"}),Ln&&Te(n,{color:"gray",children:["Debug log: ",Nn]})]})]})}})({Cursor:l,inkComponents:{Box:r,Static:n,Text:o,useInput:i},isRawModeSupported:a,PermissionPrompt:u,Spinner:({label:e})=>{const[t,r]=be(0);return we(()=>{const e=setInterval(()=>r(e=>(e+1)%c.length),80);return()=>clearInterval(e)},[]),Te(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(Ee(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(Ee(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("subagent"===o?.kind&&o.subagent){if("text"===t){const e=o.subagent.activities.at(-1);"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 if("debug-worker"===t){const e=(p.fixProgress.totalTests??0)+1,t=r||null;p.fixProgress={...p.fixProgress,phase:"debugging",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=os(e),n=ns(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="text"!==t?.kind?e.replace(/^\s*\n+/,""):e;p.log="text"===t?.kind?[...p.log.slice(0,-1),{...t,content:`${t.content}${r}`}]:[...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];"subagent"===n?.kind&&n.subagent&&(n.subagent.status=t,!p.fixProgress||"fix-worker"!==n.subagent.subagentType&&"debug-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}})(S,"chat"===e.mode||"init"===e.mode?{onExit:()=>me.current(),onSend:e=>he.current(e),showSpinnerImmediately:"init"===e.mode}:"fix"===e.mode?{onExit:()=>me.current(),isFixMode:!0}:void 0);let $e=S.status;const Ne=({error:e,result:t,status:r})=>{$e=r,Le({error:e,result:t,status:r})};let Be;w&&(Ce({text:"Starting verification...\n"}),Ce(x?{text:`Target URL: ${x}\n`}:{text:"Target URL: auto-detect (agent may infer from project config)\n"}),ke({label:"Calibrating verification flow..."})),he.current=e=>{const t=e.trim();if(b&&!Yn.getLogFilePath()&&Yn.initSession(t||"chat"),Yn.debug("User message",{text:t}),"/help"===t){U&&I&&(k=!0,A?.interrupt?.(),I.allowNextTurn(),U=!1),"running"===$e&&Ne({status:"success"}),Re({text:e});const t=E?.();return void Ce({text:t??"Help is not available in this session."})}const r=R||L&&U;if(b&&(D+=1,P=void 0,r||($=!1,ke({label:void 0}))),I){if(r)return Ne({status:"running"}),Re({text:e}),void N.push(e);if(!L||U||R||(L=!1),U)return Ne({status:"running"}),Re({text:e}),I.pushText(e),void(O+=1);Ne({status:"running"}),Re({text:e}),I.pushText(e),U=!0}};let Me="",je="";const He=[],Fe=[],Ge=[];let Ve;const Ye=await(async e=>{try{const t=await ln(e,"stably.yaml");if(!t)return void Yn.debug("No stably.yaml found");const r=await q(t,"utf-8");if(!r.trim())return;const n=Se(r),o=ha.parse(n.toJS()),s=o.agent?.fix?.maxTurnsPerIssue,i=o.agent?.fix?.maxParallelWorkers,a=!!o.agent?.fix?.rules;return Yn.debug(`Loaded stably.yaml: maxTurnsPerIssue=${s??"default"}, maxParallelWorkers=${i??"default"}, hasRules=${a}`,{path:t,config:o.agent}),o}catch(e){return void Yn.warn("Failed to parse stably.yaml",{error:e})}})(u),We=Ye?.agent?.fix?.skipAfterConsecutiveUnfixed,ze=await(async()=>{if("single"===e.mode){const r=await async function(e,t){const r=n(e);if(t){const e=n(r,t);return Qo(e,"output-flag"),{path:e,source:"output-flag"}}const i=Ko(r);if(i){const e=await async function(e){try{const t=(await q(e,"utf-8")).match(/testDir:\s*['"]([^'"]+)['"]/);return t?.[1]}catch{return}}(i);if(e){const t=n(o(i),e);if(Jo(t))return Qo(t,"playwright.config.ts"),{path:t,source:"playwright.config.ts"}}}for(const e of qo){const t=s(r,e);if(Jo(t))return Qo(t,"auto-detected"),{path:t,source:"auto-detected"}}return Qo(r,"cwd-fallback"),{path:r,source:"cwd-fallback"}}(u,e.outputDir);return Ve=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: ${Ve}]`}var t;if("verify"===e.mode)return function(e,t){const r=(Array.isArray(e)?e.join(" "):e).trim()||"Verify the application behavior.",n=t?.trim();return n?`Starting URL: ${n}\nURL policy: treat this as the source of truth and do not switch domains unless the user explicitly asks.\n\nVerification prompt: ${r}`:r}(e.prompt,x);if("fix"===e.mode)try{Yn.info("[fix] Fetching autoheal context",{runId:e.runId,skipAfterConsecutiveUnfixed:We});const t=Date.now(),{context:r,autohealReportUrl:n,skippedTests:o}=await(async({authHeader:e,orgId:t,runId:r,skipAfterConsecutiveUnfixed:n})=>{Yn.debug("Fetching autoheal context",{runId:r,skipAfterConsecutiveUnfixed:n});const o=await(s={auth:e,client:rn(),headers:to(t),path:{runId:r},query:null!=n?{skipAfterConsecutiveUnfixed:n}:{}},(s.client??Vr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-context",...s}));var s;if(404===o.response.status)throw Yn.warn("Autoheal context not found",{runId:r,status:404}),new Error(`Run ID "${r}" was not found.`);if(401===o.response.status)throw Yn.warn("Autoheal context fetch unauthorized",{runId:r,status:401}),new Error("Unauthorized: failed to fetch autoheal context (401).");if(422===o.response.status)throw Yn.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=ro.safeParse(o.data);if(e.success)return Yn.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 Yn.warn("Autoheal context response invalid",{runId:r}),new Error("Autoheal context response missing or invalid context.")}throw Yn.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:We});if(Yn.info("[fix] Autoheal context fetched",{runId:e.runId,durationMs:Date.now()-t,contextLength:r.length,skippedTestCount:o.length}),Be=n,o.length>0){Yn.info(`[fix] Skipping ${o.length} test(s) that failed to be fixed ${We}+ consecutive times`);for(const e of o)Yn.info(`[fix] Skipped: ${e.testIdentifier} — ${e.testTitle} (unfixed ${e.consecutiveUnfixedCount}x)`)}return r.includes("No failing tests to fix (all were skipped).")&&(Yn.info("[fix] All failing tests were skipped — nothing to fix"),Ne({status:"success",result:`All failing tests skipped (unfixed ${We}+ consecutive times). Nothing to fix.`}),await Pe(),process.exit(0)),te||(Yn.info("[fix] Creating WebSocket progress reporter"),te=new lo({authHeader:c,orgId:l,runId:e.runId,onUserMessage:e=>{if(Yn.info("[ws] Injecting web UI message into fix agent",{contentLength:e.length}),oe(Aa,{type:"user_message",summary:e}),se({type:"user_message",summary:e}),Re({text:`[Web] ${e}`}),!U)return I.pushText(`[Message from web UI user]: ${e}`),U=!0,void I.allowNextTurn();V||Date.now()-K<2e3?I.pushText(`[Message from web UI user]: ${e}`):(j.push(e),B&&clearTimeout(B),B=setTimeout(()=>{B=void 0;const e=[...j];j=[],K=Date.now(),Yt(e)},500))}}),te.start(),ae({phase:"initializing"})),ce("STARTED"),r}catch(e){const t=e instanceof Error?e.message:"Failed to fetch autoheal context.";Yn.error("[fix] Failed to fetch autoheal context",{error:t}),Ne({error:t,status:"error"}),await Pe(),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.":""})(),Ke=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(y(t))for(const e of Ho){const n=r.join(t,`playwright.config${e}`);if(y(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([Vo({defaultContent:"Unable to read directory",dirName:"working directory",dirPath:t}),Vo({defaultContent:"Unable to read directory",dirName:"tests directory",dirPath:n}),Vo({defaultContent:"Directory does not exist yet",dirName:"helpers directory",dirPath:o}),Vo({defaultContent:"Directory does not exist yet",dirName:"assets directory",dirPath:s}),Go({defaultContent:"File does not exist or could not be read",fileName:a,filePath:i}),Go({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),qe="fix"===e.mode?Ye?.agent?.fix?.maxTurnsPerIssue:void 0,Je="fix"===e.mode?Ye?.agent?.fix?.maxParallelWorkers:void 0,Qe="fix"===e.mode?Ye?.agent?.fix?.rules:void 0,Xe=Ye?.agent?.fix?.maxBudgetUsd??50,Ze="verify"===e.mode?e.maxBudgetUsd??5:void 0,et="fix"===e.mode?Xe:w?Ze:void 0,tt="fix"===e.mode||"single"===e.mode||"verify"===e.mode,rt="single"===e.mode?await(async e=>{const t=await ma(e,"STABLY-CREATE.md");return t?.content})(u):void 0,nt=await(e=>ma(e,"STABLY.md"))(u),ot=nt?.content;w&&(ke({label:"Assembling verification context..."}),Ce({text:"Assembling workspace context...\n"})),Yn.info("[fix] Fetching system prompt and subagent definitions",{mode:e.mode,maxTurnsOverride:qe,maxBudgetUsd:et,hasCustomRules:!!Qe,hasCreateRules:!!rt,hasStablyMd:!!ot,stablyMdPath:nt?.path}),nt&&Yn.info(`STABLY.md loaded (${nt.content.length} chars)`,{path:nt.path});const st=await eo(),it=st?Object.keys(st.variables):[],at=[...new Set([...Object.keys(h),...it])],ct=Date.now(),[{systemPrompt:lt,prContext:ut},dt]=await Promise.all([Yo({allowedEnvVars:at,mode:e.mode,workspaceInfo:Ke,authHeader:c,customHeader:"single"===e.mode?e.customHeader:void 0,maxParallelWorkers:Je}),tt?la({authHeader:c,mode:e.mode,maxTurnsOverride:qe}):Promise.resolve({})]);Yn.info("[fix] System prompt and subagents fetched",{durationMs:Date.now()-ct,systemPromptSize:lt.length,subagentCount:Object.keys(dt).length,maxTurnsOverride:qe??"default",hasPrContext:!!ut});const pt={...h,...process.env},ft={};for(const[e,t]of Object.entries(pt))ca.has(e)||void 0===t||(ft[e]=t);const ht=!0;Yn.debug("AI proxy configuration",{useStablyAiProxy:ht,wantsBypassProxy:!1,wantsUseOllama:!1}),Yn.info("[fix] Acquiring AI proxy key",{useStablyAiProxy:ht});const mt=Date.now(),gt=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??Vr).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:aa(e,a)}}return i.data?{key:i.data.key}:{error:aa("No data in response",a)}}catch(e){const t=e instanceof Error?e.message:"Unknown error";return{error:aa(t)}}var s}({auth:c,client:rn(),source:"cli"}),yt=gt?.key;if(Yn.info("[fix] AI proxy key acquired",{durationMs:Date.now()-mt,success:!!yt,hasError:!!gt?.error}),!yt){const e=gt?.error?.message?`Unable to make AI calls: ${gt.error.message}`:"Unable to make AI calls. Check if you are authenticated.";Yn.warn("Failed to get proxy API key",{error:gt?.error?.message}),Ne({error:e,status:"error"}),await Pe(),Yn.flush(),Yn.printLogFileInfo(),process.exit(1)}Yn.debug("Proxy API key acquired",{success:!!yt});const bt=await Zn(),vt=st?.sensitiveValues.length?{STABLY_SENSITIVE_VALUES:Buffer.from(JSON.stringify(st.sensitiveValues)).toString("base64")}:{},wt=bt?Object.fromEntries(Object.entries(Xn({...st?.variables,...vt,...bt})).filter(e=>null!=e[1])):st?Object.fromEntries(Object.entries(Xn({...st.variables,...vt})).filter(e=>null!=e[1])):void 0,_t="init"===e.mode,It="fix"===e.mode,Et=It?Ir.createLocal({workingDir:u}):void 0;Et&&await Et.captureSnapshot();const Tt=_t?Zi({onComplete:()=>{Ne({status:"success"}),Ue(),I?.finish(),process.exit(0)}}):b?Zi({onRestartRequested:()=>{b&&(L=!0,Ne({status:"running"}),ke({label:"Restarting browser tools..."}),P={createdAtUserMessageSeq:D,attempts:0})}}):void 0,xt=Tt?b?{"stably-agent-control":Tt}:{"session-control":Tt}:{},St=v&&ut?["mcp__create-report"]:[],At=_t?xa:w?Ea:[...Ea,...It?["mcp__auto-heal-report"]:[],...St],Ct=_t?xa:b?[...Ta,"mcp__stably-agent-control"]:w?Ta:[...Ta,...St],Rt=v&&ut?{"create-report":ta({prContext:ut,authHeader:c,orgId:l,onReportPosted:e=>{pe({githubComment:{url:e.commentUrl,prNumber:ut.prNumber}})}})}:{},Pt=_t?xt:It&&Et?{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:wt},"auto-heal-report":Xi({authHeader:c,diffTracker:Et,orgId:l,runId:e.runId,workingDir:u}),"run-history":sa({authHeader:c,orgId:l,projectId:Jn(a)}),...xt}:w?{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:wt},...xt}:{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:wt},...xt,...Rt},Ut="single"===e.mode,kt=_t?[]:[{hooks:[async e=>{const t=So(e);if(!t)return{decision:"approve"};let r=!1;const n=t.map(e=>To(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:[Lo({onResult:e=>Ae({message:e})})]},{matcher:"mcp__playwright-test__test_debug",hooks:[Do({onResult:e=>Ae({message:e})})]},...Ut?[{matcher:"Write",hooks:[$o({onFileCreated:e=>{if(He.includes(e)||He.push(e),de){if(de.filesCreated.some(t=>"string"==typeof t?t===e:t.path===e))return;const t=r.isAbsolute(e)?e:r.join(u,e),n=r.basename(e),{sessionId:o}=de,s=(async()=>{try{const r=await g.promises.readFile(t,"utf8"),s=await(async({authHeader:e,content:t,contentType:r="text/plain",filename:n,filePath:o,orgId:s,sessionId:i})=>{try{const{bucketPath:a,uploadUrl:c}=await(async({authHeader:e,contentType:t="text/plain",filename:r,filePath:n,orgId:o,sessionId:s})=>{const i=await(a={auth:e,body:{filename:r,filePath:n,contentType:t},client:rn(),headers:to(o),path:{sessionId:s}},(a.client??Vr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/sessions/{sessionId}/files/upload-url",...a,headers:{"Content-Type":"application/json",...a.headers}}));var a;if(i.error)throw new Error(`Failed to presign file upload (${i.response.status})`);const c=po.parse(i.data);return{bucketPath:c.bucketPath,expiresInSeconds:c.expiresInSeconds,key:c.key,uploadUrl:c.uploadUrl}})({authHeader:e,contentType:r,filename:n,filePath:o,orgId:s,sessionId:i});return await oo({body:t,contentType:r,uploadUrl:c,errorContext:"file"}),await(async({authHeader:e,bucketPath:t,filename:r,filePath:n,orgId:o,sessionId:s})=>{const i=await(a={auth:e,body:{filename:r,filePath:n,bucketPath:t},client:rn(),headers:to(o),path:{sessionId:s}},(a.client??Vr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/sessions/{sessionId}/files/confirm",...a,headers:{"Content-Type":"application/json",...a.headers}}));var a;if(i.error)throw new Error(`Failed to confirm file upload (${i.response.status})`)})({authHeader:e,bucketPath:a,filename:n,filePath:o,orgId:s,sessionId:i}),a}catch(e){return Yn.warn("Failed to upload automation file",{error:e instanceof Error?e.message:String(e)}),null}})({authHeader:c,content:r,contentType:"text/plain",filename:n,filePath:e,orgId:l,sessionId:o}),i={path:e,filename:n,bucketPath:s};Fe.push(i),pe({filesCreated:[...Fe]})}catch(t){Yn.warn("Failed to upload created file",{filePath:e,error:t instanceof Error?t.message:String(t)});const r={path:e,filename:n,bucketPath:null};Fe.push(r),pe({filesCreated:[...Fe]})}})();Ge.push(s)}}})]}]:[]],Lt=_t?[]:[{matcher:"mcp__playwright-test__.*",hooks:[async()=>L?{decision:"block",reason:'MCP restart is pending. This tool cannot be used until the restart completes. End your turn now - the restart only happens AFTER your turn ends. The system will send "[SYSTEM] MCP servers were restarted successfully" when ready.',systemMessage:"Tool call blocked: MCP restart pending"}:{decision:"approve"}]},...It?[{matcher:"Read",hooks:[go({action:"reading",pathKey:"file_path"})]},{matcher:"Write",hooks:[go({action:"writing",pathKey:"file_path"})]},{matcher:"Edit",hooks:[go({action:"editing",pathKey:"file_path"})]},{matcher:"Grep",hooks:[go({action:"searching",pathKey:"path"})]},{matcher:"Glob",hooks:[go({action:"searching",pathKey:"path"})]},{matcher:"Bash",hooks:[Eo({workspaceBoundary:u})]}]:[],{matcher:"mcp__playwright-test__browser_(type|navigate|evaluate|fill_form)",hooks:[ko({envVars:{...h,...st?.variables}})]}],Dt=Object.keys(dt).length>0?dt:void 0,Ot={...ft};Ot.MCP_TOOL_TIMEOUT=String(6e5),yt&&(Ot.ANTHROPIC_API_KEY=yt,Ot.ANTHROPIC_BASE_URL=Xr,Ot.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS="1");const $t=process.env.STABLY_AGENT_MODEL??"claude-opus-4-6";if(It){const e="env"===a.type?a.auth.apiKey:a.auth.accessToken,t=Jn(a);e&&t&&(Ot.STABLY_API_KEY=e,Ot.STABLY_PROJECT_ID=t)}const Nt=Qe?`\n\n## Custom Rules\n${Qe}`:"",Bt=rt?`\n\n## Custom Test Generation Rules\n${rt}`:"",Mt=ot?`\n\n## Project Rules (STABLY.md)\n${ot}`:"",jt=lt+Nt+Bt+Mt;Yn.debug("[fix] Final system prompt assembled",{baseSize:lt.length,fixRulesSize:Nt.length,createRulesSize:Bt.length,stablyMdSize:Mt.length,finalSize:jt.length});const Ht=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 fa(t)?t:void 0}();if(e)return e;const t=r.join(ua,"stably-plugin");if(fa(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}}(ua))for(const t of pa){const n=r.join(e,t);if(fa(n))return n}}();if(e)return{type:"local",path:e}}(),Ft=()=>(Yn.info("[fix] Starting SDK query",{model:$t,tools:At,mcpServers:Object.keys(Pt),resumeSessionId:C??null,subagentsEnabled:!!Dt,subagentCount:Object.keys(dt).length,useStablyAiProxy:ht,aiProxyUrl:Xr,anthropicBaseUrl:void 0,stablyPluginPath:Ht?.path,stablyPluginExists:!!Ht}),H({options:{executableArgs:["--max-old-space-size=4096"],tools:At,allowedTools:Ct,...null!=et?{maxBudgetUsd:et}:{},betas:[],canUseTool:(e,t)=>(Yn.debug("[fix] canUseTool called",{toolName:e}),Promise.resolve({behavior:"allow",updatedInput:t})),cwd:u,env:Ot,hooks:{PostToolUse:kt,PreToolUse:Lt},includePartialMessages:!0,agents:Dt,mcpServers:Pt,model:$t,permissionMode:"default",plugins:Ht?[Ht]:void 0,systemPrompt:jt,...C?{resume:C}:{}},prompt:I??ze})),Gt=()=>{if(I&&0!==N.length){for(const e of N)I.pushText(e);N.length=0,U=!0,Ne({status:"running"})}},Vt=async()=>{b&&(R||(R=(async()=>{Yn.info("Restarting MCP servers for chat mode"),Ne({status:"running"}),ke({label:"Restarting browser tools..."});try{await(A?.interrupt?.())}catch(e){Yn.warn("Failed to interrupt response during MCP restart",{error:e instanceof Error?e.message:String(e)})}await Bo(),I?.finish(),I=new Mo,O=0,U=!1,k=!1,J.clear(),A=Ft(),$=!0,ke({label:"Restarting browser tools..."}),b&&I&&P&&(P.createdAtUserMessageSeq===D?P.attempts>=1||N.length>0?P=void 0:(P.attempts+=1,I.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")),P=void 0,U=!0,Ne({status:"running"})):P=void 0),Gt()})().finally(()=>{R=void 0,Gt()})),await R)},Yt=async e=>{if(m&&U&&!V&&!M)M=(async()=>{Yn.info("[fix] Interrupting for user message",{messageCount:e.length,phase:re?.phase});try{await(A?.interrupt?.())}catch(e){Yn.warn("[fix] Failed to interrupt response for user message",{error:e instanceof Error?e.message:String(e)})}await Bo(),I?.finish(),I=new Mo,J.clear(),A=Ft();const t=e.map(e=>`[Message from web UI user]: ${e}`).join("\n\n");I.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}`),Y=!0,U=!0})().finally(()=>{M=void 0}),await M;else for(const t of e)I?.pushText(`[Message from web UI user]: ${t}`)};if(yt){w&&ke({label:"Checking AI connectivity..."});const e=Xr,t=`${e.replace(/\/$/,"")}/v1/messages`;Yn.debug(`[fix] Pre-flight: POST ${t}`);const r=Date.now();let n;try{const e=await fetch(t,{method:"POST",signal:AbortSignal.timeout(1e4),headers:{"x-api-key":yt,"anthropic-version":"2023-06-01","content-type":"application/json"},body:"{}"}),o=await e.text().catch(()=>""),s=Date.now()-r;Yn.debug(`[fix] Pre-flight: ${e.status} in ${s}ms — ${o.slice(0,300)}`),401===e.status||403===e.status?(Yn.error(`[fix] Pre-flight: AI proxy key rejected (${e.status}) at ${t}`),n="Unable to start verification: AI proxy credentials were rejected. Please run `stably login` and try again."):Yn.info("[fix] Pre-flight: AI proxy key valid",{status:e.status,durationMs:s})}catch(t){Yn.error("[fix] Pre-flight: AI proxy unreachable",{error:t instanceof Error?t.message:String(t),durationMs:Date.now()-r,url:e}),n="Unable to start verification: cannot reach the AI proxy. Please check your network/VPN and try again."}finally{w&&"running"===$e&&ke({label:void 0})}n&&(Ce({text:`[stably] ${n}\n`}),Ne({error:n,status:"error"}),await Pe(),Yn.flush(),Yn.printLogFileInfo(),process.exit(1))}Yn.info("[fix] Creating initial agent query"),w&&(ke({label:"Initializing verification session..."}),Ce({text:"Initializing verification session...\n"})),Yn.flush(),A=Ft(),Yn.info("[fix] Agent query created, entering message loop"),"chat"!==e.mode&&I.pushText(ze),me.current=async()=>{Q="CANCELED",await ce("CANCELED"),ae({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:ie(!0)}),te?.close(),await Promise.allSettled(Ge),pe({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0}),ue?.close(),B&&(clearTimeout(B),B=void 0),Yn.flush(),Ue();try{await(A?.interrupt?.())}catch{}I?.finish(),Pe()};let Wt=0,zt=null,Kt=!1;const qt=w?setTimeout(()=>{if(zt||"running"!==$e)return;const e="This is taking longer than expected. Please try again.";Ce({text:`[stably] ${e}\n`}),Ne({error:e,status:"error"});try{A?.interrupt?.()}catch{}I?.finish(),Pe(),Yn.flush(),Yn.printLogFileInfo(),process.exit(1)},9e4):void 0;qt?.unref();const Jt=setInterval(()=>{const e=Date.now()-ee;zt?Yn.info("[fix] Watchdog: message loop active",{messageCount:Wt,elapsed:e}):(Yn.info("[fix] Watchdog: waiting for first SDK message",{elapsed:e}),w&&!Kt&&e>=15e3&&(Ce({text:"Still preparing verification. This can take a bit...\n"}),Kt=!0)),Yn.flush()},15e3);Jt.unref();try{let t=!1;for(;;){if(!A){Yn.info("[fix] No response object, exiting message loop");break}t=!1,Yn.info("[fix] Entering for-await on SDK response");for await(const r of A){Wt++,zt||(zt=Date.now(),qt&&clearTimeout(qt),w&&ke({label:void 0}),Yn.info("[fix] First SDK message received",{waitDurationMs:zt-ee,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!==C&&(C=n,Yn.debug("Captured Claude session id",{sessionId:C})),"stream_event"===r.type){const{event:e}=r;(Wt<=5||Wt%200==0)&&Yn.debug("[fix] Stream event",{msgNum:Wt,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(b&&L&&!t)continue;$&&($=!1,ke({label:void 0}));const e=t&&J.has(t)?t:1===J.size?Array.from(J.keys())[0]:void 0;e?ge({toolUseId:e,kind:"text",content:r.text}):w||Ce({text:r.text})}}"message_stop"===e?.type&&I&&(V=!1,I.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("\n");t&&(Me=t,w&&(je=je?`${je}\n\n${t}`:t),Yn.debug("Assistant message",{text:w?wa(t):t}),"fix"===e.mode&&(oe(Aa,{type:"ai_message",summary:t.slice(0,200)}),se({type:"ai_message",summary:t.slice(0,200)})),_&&fe({type:"ai_message",summary:t.slice(0,200)}))}if(J.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):[];Yn.debug("Assistant message with active subagents",{hasParentToolUseId:!!t,parentToolUseId:t,activeSubagentIds:Array.from(J.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&&(V=!0),"mcp__session-control__restart_mcp_servers"===r.name||"mcp__stably-agent-control__restart_mcp_servers"===r.name){xe({rawName:r.name,toolInput:r.input});continue}if(r.name.startsWith("mcp__session-control__")||r.name.startsWith("mcp__stably-agent-control__"))continue;if(ka(r.name))continue;if(w&&Ua.test(r.name))continue;if(J.size>0&&Yn.debug("Tool use detected with active subagents",{toolName:r.name,hasParentToolUseId:!!t,parentToolUseId:t,wouldRouteToSubagent:!!t&&J.has(t),activeSubagentIds:Array.from(J.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(Yn.info("[fix] Subagent started",{subagentType:o,description:s,toolUseId:r.id,activeSubagentCount:J.size+1}),J.set(r.id,{subagentType:o,description:s}),ye({toolUseId:r.id,subagentType:o,description:s}),"fix"===e.mode){if("triage"===o){Oe?.({phase:"triage"});const e={id:r.id,testDescription:"Triage",workerType:"triage",status:"running",summary:null,startedAt:Date.now(),endedAt:null,activity:[]};ae({phase:"triage",workers:[...re?.workers??[],e]})}else if("fix-worker"===o){ne.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:[]};Oe?.({phase:"fixing",totalTests:ne.size,currentTestDescription:s||null}),ae({phase:"fixing",totalTests:ne.size,currentTestDescription:s||null,lastTestDescription:s||re?.lastTestDescription||null,workers:[...re?.workers??[],e]})}else if("debug-worker"===o){ne.add(s||r.id);const e={id:r.id,testDescription:s||r.id,workerType:"debug-worker",status:"running",summary:null,startedAt:Date.now(),endedAt:null,activity:[]};Oe?.({phase:"debugging",totalTests:ne.size,currentTestDescription:s||null}),ae({phase:"debugging",totalTests:ne.size,currentTestDescription:s||null,lastTestDescription:s||re?.lastTestDescription||null,workers:[...re?.workers??[],e]})}else"validation"===o?(Oe?.({phase:"validation",currentTestDescription:null}),ae({phase:"validation",currentTestDescription:null})):"context"===o&&ae({currentTestDescription:s||null});se({type:"tool_call",summary:`[${o}] ${s}`.trim()})}continue}if(t&&J.has(t)){const n=os(r.name),o=ns(r.name,r.input),s=o?`${n} (${o})`:n;if(Yn.debug("Subagent tool called",{tool:r.name,parentToolUseId:t}),ge({toolUseId:t,kind:"tool",content:s}),"fix"===e.mode){se({type:"tool_call",summary:s});const e=J.get(t);"fix-worker"!==e?.subagentType&&"debug-worker"!==e?.subagentType&&"triage"!==e?.subagentType||oe(t,{type:"tool_call",summary:s})}continue}if(t&&Yn.debug("Tool with parent_tool_use_id but no matching subagent",{tool:r.name,parentToolUseId:t,activeSubagentIds:Array.from(J.keys())}),Yn.debug("Tool called",{tool:r.name,input:r.input}),xe({rawName:r.name,toolInput:r.input}),"fix"===e.mode){const e=os(r.name),t=ns(r.name,r.input),n=t?`${e} (${t})`:e;oe(Aa,{type:"tool_call",summary:n}),se({type:"tool_call",summary:n})}if(v){const e=os(r.name),t=ns(r.name,r.input),n=t?`${e} (${t})`:e;"initializing"===de?.phase?pe({phase:"generating",currentActivity:n}):"mcp__playwright-test__test_run"===r.name&&"generating"===de?.phase?pe({phase:"testing",currentActivity:n}):pe({currentActivity:n}),fe({type:"tool_call",summary:n})}if(w){const e=os(r.name),t=ns(r.name,r.input),n=wa(t?`${e} (${t})`:e);pe("initializing"===de?.phase?{phase:"verifying",currentActivity:n}:{currentActivity:n}),fe({type:"tool_call",summary:n})}}if("text"===r?.type){const n="string"==typeof r.text?r.text:"",o=t&&J.has(t)?t:1===J.size?Array.from(J.keys())[0]:void 0;if(o&&n&&(ge({toolUseId:o,kind:"text",content:n}),"fix"===e.mode)){const e=J.get(o);"fix-worker"!==e?.subagentType&&"debug-worker"!==e?.subagentType&&"triage"!==e?.subagentType||oe(o,{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,n="tool_use_result"in r&&r.tool_use_result&&"object"==typeof r.tool_use_result?r.tool_use_result: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,o="is_error"in r&&!0===r.is_error||"error"===n?.status;let s;const i=n?.content??("content"in r?r.content:void 0);if("string"==typeof i?s=i:Array.isArray(i)&&(s=i.filter(e=>e&&"object"==typeof e&&"text"===e.type).map(e=>e.text||"").join("")),Yn.debug("Tool result",{toolUseId:t,isError:o,output:s?.slice(0,500)}),t&&J.has(t)){const r=J.get(t);if(Yn.info("[fix] Subagent completed",{toolUseId:t,isError:o,subagentType:r?.subagentType,description:r?.description,activeSubagentCount:J.size-1}),s&&ge({toolUseId:t,kind:"text",content:s}),De({toolUseId:t,status:o?"error":"complete"}),"fix"===e.mode&&"triage"===r?.subagentType){const e=o?"failed":"succeeded",r=s?s.slice(0,500):null,n=(re?.workers??[]).map(n=>n.id===t?{...n,status:e,summary:r,endedAt:Date.now()}:n);ae({workers:n})}if("fix"===e.mode&&("fix-worker"===r?.subagentType||"debug-worker"===r?.subagentType)){const e=o?"failed":"succeeded",r=s?s.slice(0,500):null,n=(re?.workers??[]).map(n=>n.id===t?{...n,status:e,summary:r,endedAt:Date.now()}:n);o?(Oe?.({failedTests:(re?.failedTests??0)+1,currentTestDescription:null}),ae({failedTests:(re?.failedTests??0)+1,currentTestDescription:null,workers:n})):(Oe?.({fixedTests:(re?.fixedTests??0)+1,currentTestDescription:null}),ae({fixedTests:(re?.fixedTests??0)+1,currentTestDescription:null,workers:n}))}J.delete(t)}}continue}if("result"===r.type){if(Yn.info("[fix] Agent result received",{subtype:r.subtype,messageCount:Wt,elapsed:Date.now()-ee,activeSubagents:J.size,fixedTests:re?.fixedTests,failedTests:re?.failedTests,phase:re?.phase}),m){if("success"===r.subtype){B&&(clearTimeout(B),B=void 0);for(const e of j)I?.pushText(`[Message from web UI user]: ${e}`);if(j=[],(_||"fix"===e.mode)&&I){if(I.hasQueuedMessages()){Yn.info("[ws] Queued web UI messages found, continuing agent"),U=!0,I.allowNextTurn();continue}if(await La(I,3e3)){Yn.info("[ws] Web UI message received during grace period, continuing agent"),U=!0,I.allowNextTurn();continue}I.finish()}if(Oe?.({phase:"complete",currentTestDescription:null,endedAt:Date.now()}),ae({phase:"complete",currentTestDescription:null,endedAt:Date.now(),isError:!1,workers:ie(!1)}),await Promise.allSettled(Ge),"verify"===e.mode){(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt).trim();const t=je||Me,r=/```verdict\s*\r?\n/.test(t),n=Ia(t)??{verdict:"INCONCLUSIVE",steps:["Agent finished without a parseable verdict block."],reason:r?"Failed to parse verdict.":"The agent completed without reporting a verdict.",evidence:[]},o=_a(n);"PASS"===n.verdict?z.green("VERIFICATION PASSED"):"FAIL"===n.verdict?z.red("VERIFICATION FAILED"):z.yellow("VERIFICATION INCONCLUSIVE"),o.steps.length>0&&o.steps.forEach((e,t)=>{}),o.reason&&(n.verdict,o.reason),o.evidence.length>0&&o.evidence.forEach(e=>{}),pe({phase:"complete",endedAt:Date.now(),isError:"PASS"!==n.verdict,currentActivity:null}),process.exitCode="PASS"===n.verdict?0:"FAIL"===n.verdict?1:2,Ne({status:"success"})}else{if(pe({phase:"complete",endedAt:Date.now(),isError:!1,currentActivity:null}),Ut&&He.length>0){z.green("Created files:");for(const e of He)z.green(`- ${e}`)}const e=(e,t)=>`]8;;${e}${t}]8;;`,t=Be?z.cyan(`📊 View Autoheal Report:\n ${e(Be,z.cyan(z.bold(z.underline(Be))))}`):void 0;Ne({status:"success",result:t}),Q="COMPLETED"}}else if(M||Y)Yn.info("[fix] Suppressing error status: user-message interrupt in progress");else if(k)Q="CANCELED",ae({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:ie(!0)}),await Promise.allSettled(Ge),pe({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0});else if(w){let e="Execution error before verification completed.";"error_max_budget_usd"===r.subtype?e="Budget limit exceeded before verification completed.":"error_max_turns"===r.subtype&&(e="Maximum turns exceeded before verification completed."),z.yellow("VERIFICATION INCONCLUSIVE"),await Promise.allSettled(Ge),pe({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),Ne({status:"success"}),process.exitCode=2}else{let e,t="unknown",n="Run failed.";"error_max_budget_usd"===r.subtype?(t="budget_exceeded",e="total_cost_usd"in r?r.total_cost_usd:void 0,n=`Budget limit exceeded (${void 0!==e?`$${e.toFixed(2)}`:"unknown"} spent). The fix session was stopped to prevent runaway costs.`,Yn.warn("[fix] Budget limit exceeded",{subtype:r.subtype,totalCostUsd:e})):"error_max_turns"===r.subtype?(t="max_turns",n="Maximum turns exceeded. The fix session was stopped."):"error_during_execution"===r.subtype&&(t="execution_error"),Oe?.({endedAt:Date.now(),isError:!0}),ae({phase:"complete",endedAt:Date.now(),isError:!0,errorReason:t,errorMessage:n,totalCostUsd:e,currentTestDescription:null,workers:ie(!0)}),await Promise.allSettled(Ge),pe({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),Ne({error:n,status:"error"}),process.exitCode=1,Q="FAILED"}k=!1;break}const n=b&&L;if("success"!==r.subtype){if(!k){let e="Run failed.";"error_max_budget_usd"===r.subtype?(e=`Budget limit exceeded (${"total_cost_usd"in r?`$${r.total_cost_usd.toFixed(2)}`:"unknown"} spent). The fix session was stopped to prevent runaway costs.`,Yn.warn("[fix] Budget limit exceeded",{subtype:r.subtype,totalCostUsd:"total_cost_usd"in r?r.total_cost_usd:void 0})):"error_max_turns"===r.subtype&&(e="Maximum turns exceeded. The fix session was stopped."),Ne({error:e,status:"error"}),process.exitCode=1}}else Ne(n?{status:"running"}:{status:"success"});if(U=!1,k=!1,n){L=!1,Yn.info("Processing deferred MCP restart request in chat mode"),await Vt(),t=!0;break}$=!1,ke({label:void 0}),I?.allowNextTurn(),b&&O>0&&(O-=1,U=!0,Ne({status:"running"}));continue}}if(M&&await M,Y&&(Y=!1,t=!0,Ne({status:"running"}),Yn.info("[fix] Resuming after user-message interrupt")),!t)break}}catch(e){k?(Q="CANCELED",ae({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:ie(!0)}),await Promise.allSettled(Ge),pe({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0})):(Yn.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()-ee}),Ne({error:`Agent encountered an error: ${e}`,status:"error"}),process.exitCode=1,Q="FAILED",ae({phase:"complete",endedAt:Date.now(),isError:!0,currentTestDescription:null,workers:ie(!0)}),await Promise.allSettled(Ge),pe({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),Yn.flush(),Yn.printLogFileInfo())}finally{if(qt&&clearTimeout(qt),clearInterval(Jt),B&&(clearTimeout(B),B=void 0),Yn.info("[fix] Agent session ending",{finalStatus:Q,elapsed:Date.now()-ee,totalMessages:Wt}),U=!1,k=!1,process.off("uncaughtException",i),I?.finish(),Q){Yn.info("[fix] Reporting final autoheal status",{status:Q});const e=Date.now();await ce(Q),Yn.info("[fix] Final autoheal status reported",{durationMs:Date.now()-e})}if(Yn.info("[fix] Closing WebSocket progress reporter"),te?.close(),await Promise.allSettled(Ge),ue?.close(),It&&Et){const t=Date.now();try{Yn.info("[fix] Computing diff...");const r=await Et.computeDiff();if(r&&r.trim().length>0){Yn.info("[fix] Uploading diff...",{diffLength:r.length});const{diffBucketPath:n,uploadUrl:o}=await ao({authHeader:c,contentType:"text/plain",orgId:l,runId:e.runId});await oo({body:r,contentType:"text/plain",uploadUrl:o,errorContext:"diff"}),await co({authHeader:c,diffBucketPath:n,orgId:l,runId:e.runId}),Yn.info("[fix] Diff uploaded",{durationMs:Date.now()-t})}else Yn.info("[fix] No diff to upload (empty or no changes)")}catch(e){Yn.warn("[fix] Failed to upload diff",{error:e instanceof Error?e.message:String(e),durationMs:Date.now()-t})}}Yn.info("[fix] Cleaning up diff tracker"),await(Et?.cleanup()),Yn.info("[fix] Running final cleanup"),await Pe(),Yn.info("[fix] Cleanup complete")}},$a=ue.object({runId:ue.string(),timestamp:ue.number()}),Na=[{args:["--trace=on"],description:"Run Playwright tests",name:"test"},{args:[],description:"Install browser dependencies",name:"install"}],Ba=["You have two different versions of @playwright/test"];function Ma(e){const[t,...r]=Vi(e),n=[t,...r.slice(0,-1)].join(" ");return(t,r)=>{let o=t.toString();for(const e of Na)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[0].includes("\\.bin\\playwright"))&&e.shift(),void r.write(e.join("\n"))}r.write(o)}}async function ja({overrideArgs:e,subcommand:t}){Yn.info("[test] forwardToPlaywright starting",{subcommand:t,overrideArgs:e});const r=process.argv,i=r.findIndex((e,r)=>r>1&&e===t),a=-1===i?[]:r.slice(i+1),l="--"===a[0],u=l?a.slice(1):a;if(!l&&("--help"===u[0]||"-h"===u[0]))return async function({subcommand:e}){const t=Na.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=Hi();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]=Vi(o),a=Ma(o);return new Promise(t=>{const r=h(s,[...i,e,"--help"],{stdio:["inherit","pipe","pipe"],shell:"win32"===process.platform,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??[],p=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("=");p.has(r)?!t.includes("=")&&e+1<u.length&&!u[e+1].startsWith("-")&&e++:m.push(t)}const g=[t,...d,...m];Yn.info("[test] Forwarded args computed",{forwardedArgs:g}),Yn.info("[test] Resolving Stably test environment");const b=Date.now(),v="test"===t?await Zn():void 0;Yn.info("[test] Stably test environment resolved",{durationMs:Date.now()-b,hasCredentials:null!=v,hasWsUrl:!!v?.STABLY_WS_URL}),Yn.info("[test] Loading remote environment variables");const w=await eo();Yn.info("[test] Remote environment loaded",{hasRemoteEnv:!!w,variableCount:w?Object.keys(w.variables).length:0});const x={...w?.variables,...w?.sensitiveValues.length?{STABLY_SENSITIVE_VALUES:Buffer.from(JSON.stringify(w.sensitiveValues)).toString("base64")}:{}};Yn.info("[test] Setting up Stably reporter injection");const S="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=>y(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},a=(e,t)=>{try{return function({baseConfigPath:e,projectDir:t}){const r=function(e){try{const t=f("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",a=o(n(e)),l=c(e),u=s(a,`.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\n// Decode sensitive values from env var (set by CLI --env flag)\nconst decodeSensitiveValues = (): string[] | undefined => {\n const encoded = process.env.STABLY_SENSITIVE_VALUES;\n if (!encoded) return undefined;\n try {\n const decoded: unknown = JSON.parse(Buffer.from(encoded, 'base64').toString('utf-8'));\n return Array.isArray(decoded) ? decoded.filter((v): v is string => typeof v === 'string') : undefined;\n } catch {\n return undefined;\n }\n};\n\nconst buildReporterList = () => {\n const existingReporters = baseConfig.reporter;\n const sensitiveValues = decodeSensitiveValues();\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 cliVersion: '${zr}',\n projectId: process.env.STABLY_PROJECT_ID,\n source: 'cli',\n notificationConfigs: extractNotificationConfigs(),\n errorSummary: resolveErrorSummary(),\n ...(sensitiveValues && { sensitiveValues }),\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 cliVersion: '${zr}',\n projectId: process.env.STABLY_PROJECT_ID,\n source: 'cli',\n notificationConfigs: extractNotificationConfigs(),\n errorSummary: resolveErrorSummary(existingOptions?.errorSummary),\n ...(sensitiveValues && { sensitiveValues }),\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 y(a)||I(a,{recursive:!0}),E(u,d,"utf-8"),function(e){const t=s(e,".gitignore");try{if(y(t)){const e=_(t,"utf-8");if(e.split("\n").map(e=>e.trim()).includes(Wo))return;const r=e.length>0&&!e.endsWith("\n");T(t,`${r?"\n":""}${Wo}\n`)}else E(t,`${Wo}\n`)}catch{}}(a),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]),c=o(s);if(!i(c))return;const l=a(s,c);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]),c=o(t);if(!i(c))return;const l=a(t,c);if(!l)return;const u=e[s].startsWith("--config=")?"--config=":"-c=";return e[s]=`${u}${l}`,l}}const l=Ko(r);if(!l)return;const u=o(l);if(!i(u))return;const d=a(l,u);return d?(e.push("--config",d),d):void 0}({forwardedArgs:g,hasCredentials:null!=v}):void 0;Yn.info("[test] Reporter injection setup complete",{hasWrapperConfig:!!S}),Yn.info("[test] Spawning Playwright process"),await function(e,t={}){Yn.info("[test] Detecting Playwright installation");const r=Hi();Yn.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]=Vi(n),i=Xn(t.env),a=[o,...s,...e];Yn.info("[test] Spawning Playwright process",{command:a.join(" "),pid:process.pid});const c=Date.now(),l=h(o,[...s,...e],{stdio:["inherit","pipe","pipe"],shell:"win32"===process.platform,env:{...i,...process.env.CI?{}:{FORCE_COLOR:"1"}}});Yn.info("[test] Playwright process spawned",{childPid:l.pid});const u=Ma(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 Ba)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,f=()=>!p.signal.aborted&&(p.abort(),t.onClose?.(),process.removeListener("SIGINT",m),process.removeListener("SIGTERM",m),!0),m=e=>{Yn.info("[test] Signal received, killing Playwright process",{signal:e,childPid:l.pid}),f(),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=>{f()&&(Yn.error("[test] Playwright process error",{error:e.message,childPid:l.pid}),t(e))}),l.on("close",t=>{if(!f())return;Yn.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)})})})}(g,{env:{...x,...v},onClose:()=>{var e;Yn.info("[test] Playwright process closed, cleaning up wrapper config"),(e=S)&&y(e)&&C(e)}})}function Ha(e){const t=new Date(e),r=new Date,n=r.getTime()-t.getTime(),o=Math.floor(n/1e3),s=Math.floor(o/60),i=Math.floor(s/60),a=Math.floor(i/24);if(o<60)return"just now";if(s<60)return`${s}m ago`;if(i<24)return`${i}h ago`;if(a<=7)return`${a}d ago`;const c=t.toLocaleString("en-US",{month:"short"}),l=t.getDate();return t.getFullYear()===r.getFullYear()?`${c} ${l}`:`${c} ${l}, ${t.getFullYear()}`}var Fa={PASSED:z.green,FAILED:z.red,TIMEDOUT:z.red,CANCELLED:z.yellow,INTERRUPTED:z.yellow,RUNNING:z.cyan,QUEUED:z.dim},Ga=(e,t)=>e?e.length>t?`${e.slice(0,t-1)}…`:e:"-",Va=e=>{if(!e)return"-";const t=new Date(e);return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")} ${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`},Ya=e=>(Fa[e]??(e=>e))(e),Wa=/\x1b\[[0-9;]*m/g,za=(e,t)=>{const r=e.replace(Wa,"").length,n=Math.max(0,t-r);return e+" ".repeat(n)},Ka=e=>`${JSON.stringify(e,null,2)}\n`,qa=e=>"oauth"===e.type?e.auth.context.orgId:void 0,Ja=(e,t,r)=>{if(!e)return;const n=e.toUpperCase();if(t.includes(n))return n;se(z.red(`Invalid ${r} value "${e}". Must be one of: ${t.join(", ").toLowerCase()}`)),process.exit(1)},Qa=(e,t,r)=>{if(401!==e.response.status&&403!==e.response.status||(se(z.red("Access denied.")),process.exit(1)),404===e.response.status&&r&&(se(z.red(r)),process.exit(1)),400===e.response.status){const t=e.error&&"object"==typeof e.error&&"error"in e.error?e.error.error:"Bad request";se(z.red(t)),process.exit(1)}e.error&&(se(z.red(`Failed to ${t}: ${e.response.status}`)),process.exit(1))};function Xa(e=""){process.stdout.write(`${e}\n`)}function Za(...e){process.stderr.write(`${e.join(" ")}\n`)}var ec="stably",tc=`https://registry.npmjs.org/${ec}/latest`,rc=de.object({version:de.string()});function nc(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 oc(e,t){const r=nc(e),n=nc(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 sc=r.join(U.homedir(),".stably"),ic=r.join(sc,"update-check.json"),ac=`https://registry.npmjs.org/${ec}/latest`,cc="1"===process.env.STABLY_DISABLE_UPDATE_CHECK,lc=de.object({lastCheck:de.number(),latestVersion:de.string()}),uc=!1,dc=!1,pc=async()=>{if(dc)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(cc||function(e=process.argv.slice(2)){return e.includes("upgrade")}())return;const e=function(){try{const e=g.readFileSync(ic,"utf-8");return lc.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 = '${ac}';\n const cacheFile = ${JSON.stringify(ic)};\n const cacheDir = ${JSON.stringify(sc)};\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{h(process.execPath,["--input-type=module","-e",e],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()}catch{}}(),null!=e&&oc(zr,e.latestVersion)){if(uc)return;uc=!0;let t=!1;const r=()=>{if(t)return;t=!0;const r=`${z.yellow(`update available (${zr} → ${e.latestVersion})`)} - run \`${ec} upgrade\` to get the latest version\n`;try{g.writeSync(2,r)}catch{}};process.once("beforeExit",r),process.once("exit",r)}}(),Ce.cwdChanged&&Yn.debug("Changed working directory",{cwd:Ce.newCwd});for(const e of Ce.envFilesLoaded)Yn.debug("Loaded env file",{path:e});for(const e of Ce.envFileErrors)Yn.warn(e);var fc=process.argv.findIndex(e=>"-v"===e||"--verbose"===e);-1!==fc&&process.argv.splice(fc,1);var hc=process.argv.findIndex(e=>"--no-telemetry"===e);-1!==hc&&process.argv.splice(hc,1),Yn.info("CLI starting",{version:zr,args:process.argv.slice(2),cwd:process.cwd()}),process.on("unhandledRejection",(e,t)=>{Yn.error("Unhandled promise rejection",{reason:e instanceof Error?{message:e.message,stack:e.stack}:e,promise:String(t)}),Yn.flush(),Yn.printLogFileInfo()}),process.on("uncaughtException",(e,t)=>{"EPIPE"!==e.code&&(Yn.error("Uncaught exception",{error:{message:e.message,stack:e.stack,name:e.name},origin:t}),Yn.flush(),Yn.printLogFileInfo())});var mc=new l;mc.name("stably").description("AI-assisted Playwright testing CLI").version(zr),mc.enablePositionalOptions(),mc.showHelpAfterError(),mc.exitOverride(),mc.configureHelp({subcommandTerm:e=>{const t=e.registeredArguments.map(e=>e.required?`<${e.name()}>`:`[${e.name()}]`).join(" ");return t?`${e.name()} ${t}`:e.name()}});var gc=[];mc.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>{gc.push(e)}});var yc=()=>{const e=mc.helpInformation().trimEnd();return e?`${e}\n`:""},bc=(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},vc=()=>{process.stdout.write(yc())};mc.command("help [command...]").description("Show help for a command (e.g. stably help create)").action(e=>{if(!e||0===e.length)return void vc();const t=bc(mc,e);if(!t)return process.stderr.write(`Unknown command: ${e.join(" ")}\n`),vc(),void(process.exitCode=1);var r;r=t,process.stdout.write((e=>{const t=e.helpInformation().trimEnd();return t?`${t}\n`:""})(r))}),mc.action(()=>Oa({mode:"chat",getHelpText:yc})),mc.command("login").description("Authenticate with Stably in your browser").action(An),mc.command("logout").description("Clear stored Stably credentials").action(async()=>{const e=zn();e&&(oe.warn(`Environment variables ${z.cyan("STABLY_API_KEY")} and ${z.cyan("STABLY_PROJECT_ID")} are set.`),oe.warn("They will continue to be used for authentication even after logout."),oe.warn("Unset them if you want to fully de-authenticate this shell/session."));const t=await gn();if(!t)return void se(e?z.yellow("No stored OAuth login found to clear."):z.yellow("You are not logged in."));const r=ie();r.start("Logging out..."),await(async e=>{try{await fetch(`${Jr}/api/backend/v1/logout`,{body:JSON.stringify({refresh_token:e}),headers:{"Content-Type":"application/json"},method:"POST"})}catch{}})(t.refreshToken),await bn(),await wn(),r.stop(z.green("✓ Logged out")),se(z.green("You have been logged out successfully."))}),mc.command("whoami").description("Show auth status and current project").action(async()=>{oe.info(`${z.bold("CLI Version:")} ${z.cyan(zr)}`);const e=zn();if(e){oe.info(z.dim("Authentication: Environment variables")),oe.info(` ${z.bold("API Key:")} ${z.cyan(e.apiKey.slice(0,8))}...`),oe.info(` ${z.bold("Project ID:")} ${z.cyan(e.projectId)}`);const t=await gn();if(t){let e;try{e=cn(t.accessToken).email}catch{e=void 0}oe.warn("Stored OAuth login detected but will be ignored (env auth takes precedence)."),e&&oe.info(` ${z.bold("OAuth Email:")} ${z.cyan(e)}`),oe.info(` ${z.bold("Tip:")} Unset env vars to use OAuth`)}return void se(z.green("Authenticated via environment variables"))}const t=await gn();if(!t)return void se(z.yellow("Not logged in. Run `stably login` to authenticate."));let n;try{n=cn(t.accessToken).email}catch{n=void 0}const o=await vn();if(!o)return oe.info(z.dim("Authentication: OAuth (not linked to a project)")),n&&oe.info(` ${z.bold("Email:")} ${z.cyan(n)}`),void se(z.yellow("Logged in but this directory is not linked to a project. Run `stably login` to link."));const s=await(async()=>ln(process.cwd(),pn))(),i=s?r.dirname(s):process.cwd(),a=r.relative(process.cwd(),i)||".";oe.info(z.dim("Authentication: OAuth")),n&&oe.info(` ${z.bold("Email:")} ${z.cyan(n)}`),oe.info(` ${z.bold("Organization:")} ${z.cyan(o.orgName)}`),oe.info(` ${z.bold("Project:")} ${z.cyan(o.projectName)}`),oe.info(` ${z.bold("Linked at:")} ${z.dim(a)}`),se(z.green("Authenticated"))}),mc.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=>{ae(`Starting development server for port ${e.port}...`);const t=await qn(),r="oauth"===t.type?`${t.auth.context.orgName}-${t.auth.context.projectName}`.toLowerCase().replace(/[^a-z0-9-]/g,""):`project-${t.auth.projectId}`.toLowerCase(),n=ie();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}${z.underline(z.cyan(o.url))}]8;;`)}),mc.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 Oa({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)=>Oa({mode:"single",prompt:e,outputDir:t.output})),mc.command("verify <prompt...>").description("Verify your app works correctly against a prompt").option("-u, --url <url>","Starting URL to verify against").option("--max-budget <dollars>","Maximum budget in USD (default: 5)",Number.parseFloat).option("--no-interactive","Disable interactive verify preflight setup").action(async(e,t)=>{if(void 0!==t.maxBudget&&(!Number.isFinite(t.maxBudget)||t.maxBudget<=0))throw new Error("--max-budget must be a positive number");return Oa({mode:"verify",prompt:e,url:t.url,maxBudgetUsd:t.maxBudget,interactive:t.interactive})}),mc.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 f("git rev-parse --is-inside-work-tree",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}})(process.cwd())||(Yn.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 Yn.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(_r))if(_r[r].detect({env:e,cwd:t}))return{isCi:!0,..._r[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 Yn.debug("Run ID detected from CI environment",{runId:r}),t(r);Yn.debug("No explicit run ID or CI environment detected, checking last-run.json");const n=await(async()=>{try{const e=await ln(process.cwd(),".stably/last-run.json");if(!e)return;const t=await q(e,"utf-8");return{...$a.parse(JSON.parse(t)),filePath:e}}catch{return}})();if(n){const e=(Date.now()-n.timestamp)/36e5;return Yn.debug("Run ID found in last-run.json",{runId:n.runId,timestamp:n.timestamp,filePath:n.filePath,ageHours:Math.round(e)}),e>24&&Yn.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)}Yn.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)),Oa({mode:"fix",runId:t})}),mc.command("init").description("Initialize Playwright and Stably SDK in your project").action(async()=>Oa({mode:"init"})),mc.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;Xa(z.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(tc,{signal:e.signal});if(!t.ok)throw new Error(`Failed to fetch latest version: ${t.statusText}`);return rc.parse(await t.json()).version}finally{clearTimeout(t)}}();return{current:zr,latest:e,isOutdated:oc(zr,e)}}()}catch(e){return Za(z.red("Failed to check for updates:"),e instanceof Error?e.message:e),void(process.exitCode=1)}if(Xa(`Current version: ${z.yellow(r.current)}`),Xa(`Latest version: ${z.green(r.latest)}`),Xa(),!r.isOutdated)return void Xa(z.green("✓ You are already on the latest version!"));if(Xa(z.yellow(`⚠ A new version is available: ${r.current} → ${r.latest}`)),Xa(),t)return Xa(z.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")||e.includes(".npm\\_cacache"))return"npx";try{const t=f("npm root -g",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-npm"}catch{}if(e.includes("node_modules/stably")||e.includes("node_modules\\stably"))return"global-npm";try{const t=f("pnpm root -g",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-pnpm"}catch{}try{const t=f("yarn global dir",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-yarn-classic"}catch{}try{const t=f("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",`${ec}@latest`],description:`npm install -g ${ec}@latest`};case"global-pnpm":return{command:"pnpm",args:["add","-g",`${ec}@latest`],description:`pnpm add -g ${ec}@latest`};case"global-yarn-classic":return{command:"yarn",args:["global","add",`${ec}@latest`],description:`yarn global add ${ec}@latest`};case"npx":return{command:"npx",args:[`${ec}@latest`],description:`npx ${ec}@latest (always uses latest)`}}}(n);if("npx"===n)return Xa(z.dim("You are running via npx, which always fetches the latest version.")),void Xa(z.dim(`Simply run: ${z.white("npx stably")} to use the latest version.`));"unknown"===n?(Xa(z.yellow("Could not detect installation method. Falling back to npm.")),Xa()):"global-yarn-berry"===n&&(Xa(z.yellow("Yarn Berry does not support global packages. Falling back to npm.")),Xa()),Xa(`Upgrade command: ${z.cyan(o.description)}`),Xa(),Xa(z.cyan("Upgrading...")),Xa();try{await(s=o.command,i=o.args,new Promise((e,t)=>{const r=h(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)})})),Xa(),Xa(z.green("✓ Upgrade complete!")),Xa(z.dim(`Run ${z.white("stably --version")} to verify.`))}catch(e){Za(z.red("Upgrade failed:"),e instanceof Error?e.message:e),Xa(),Xa(z.dim("You can try manually running:")),Xa(z.cyan(` ${o.description}`)),process.exitCode=1}var s,i}(e));var wc=mc.command("env").description("Manage remote environments");wc.command("list").description("List available environments").action(async()=>{const e=await qn(),t=Jn(e),r=Qn(e);Yn.debug("Listing environments",{projectId:t});const n=await(o={auth:r,client:rn(),path:{projectId:t}},(o.client??Vr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/environments",...o}));var o;401!==n.response.status&&403!==n.response.status||(se(z.red("Access denied.")),process.exit(1)),n.error&&(se(z.red(`Failed to list environments: ${n.response.status}`)),process.exit(1));const{environments:s}=n.data;if(0!==s.length){process.stdout.write(`${z.bold("Environments")}\n\n`);for(const e of s){const t=e.isDefault?z.green(" (default)"):"",r=z.dim(` ${e.variableCount} variable${1!==e.variableCount?"s":""}`);process.stdout.write(` ${z.cyan(e.name)}${t}${r}\n`),e.description&&process.stdout.write(` ${z.dim(e.description)}\n`)}process.stdout.write("\n")}else process.stdout.write(z.dim("No environments found. Create one on your Stably dashboard.\n"))}),wc.command("inspect <name>").description("Show variable metadata (name, sensitive flag, updated timestamp)").action(e=>(async e=>{const t=await qn(),r=Jn(t),n=Qn(t);Yn.debug("Inspecting environment",{name:e,projectId:r});const o=await(s={auth:n,client:rn(),path:{projectId:r,environmentName:e}},(s.client??Vr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/environments/{environmentName}/inspect",...s}));var s;404===o.response.status&&(se(z.red(`Environment "${e}" not found. Run ${z.bold("stably env list")} to see available environments.`)),process.exit(1)),401!==o.response.status&&403!==o.response.status||(se(z.red("Access denied.")),process.exit(1)),o.error&&(se(z.red(`Failed to inspect environment: ${o.response.status}`)),process.exit(1));const{variables:i}=o.data;if(0!==i.length){process.stdout.write(`${z.bold(e)} ${z.dim(`(${i.length} variable${1!==i.length?"s":""})`)}\n\n`);for(const e of i){const t=z.dim(` [updated ${Ha(e.updatedAt)}]`);e.sensitive?process.stdout.write(` ${z.cyan(e.name)} ${z.yellow("[sensitive]")}${t}\n`):process.stdout.write(` ${z.cyan(e.name)}${t}\n`)}process.stdout.write("\n")}else process.stdout.write(z.dim(`Environment "${e}" has no variables.\n`))})(e));var _c=mc.command("runs").description("View test run history");_c.command("list").description("List recent test runs").option("-b, --branch <name>","Filter by branch name").option("-n, --limit <number>","Number of runs (default: 20, max: 100)").option("--after <runId>","Show runs newer than this runId").option("--before <runId>","Show runs older than this runId").option("--source <type>","Filter by source: local, ci, web").option("-s, --status <type>","Filter by status: queued, running, passed, failed, timedout, cancelled, interrupted").option("--suite <name>","Filter by suite name").option("--trigger <type>","Filter by trigger: manual, scheduled, ui, api, github_action, suite_run").option("--json","Output as JSON").action(async e=>{const t=await qn(),r=Jn(t),n=Qn(t),o=qa(t);let s;e.limit&&(s=parseInt(e.limit,10),(Number.isNaN(s)||s<1||s>100)&&(se(z.red("--limit must be an integer between 1 and 100")),process.exit(1)));const i=Ja(e.source,["LOCAL","CI","WEB"],"--source"),a=Ja(e.status,["QUEUED","RUNNING","PASSED","FAILED","TIMEDOUT","CANCELLED","INTERRUPTED"],"--status"),c=Ja(e.trigger,["MANUAL","SCHEDULED","UI","API","GITHUB_ACTION","SUITE_RUN"],"--trigger");Yn.debug("Listing runs",{projectId:r,branch:e.branch,limit:s,after:e.after,before:e.before,source:i,status:a,suite:e.suite,trigger:c});const l=await Yr({auth:n,client:rn(),headers:to(o),query:{projectId:r,branchName:e.branch,limit:s,afterRunId:e.after,beforeRunId:e.before,source:i,status:a,suiteName:e.suite,trigger:c}});Qa(l,"list runs");const{runs:u,hasMore:d}=l.data;e.json?process.stdout.write(Ka(l.data)):process.stdout.write(((e,t)=>{if(0===e.length)return z.dim("No runs found matching the specified filters.\n");const r=Math.min(40,Math.max(10,...e.map(e=>e.runId.length))),n={runId:{w:r+2,t:r},status:{w:14},branch:{w:32,t:30},started:{w:18}},o=[],s=`${za("Run ID",n.runId.w)}${za("Status",n.status.w)}${za("Branch",n.branch.w)}${za("Started",n.started.w)}Tests`;o.push(z.bold(s));for(const t of e){const e=Ga(t.runId,n.runId.t),r=Ya(t.status),s=Ga(t.branchName,n.branch.t),i=Va(t.startedAt),a=t.totalCount.toString();o.push(`${za(e,n.runId.w)}${za(r,n.status.w)}${za(s,n.branch.w)}${za(i,n.started.w)}${a}`)}if(t&&e.length>0){const t=e.at(-1)?.runId;t&&(o.push(""),o.push(z.dim(`Next page: stably runs list --before ${t}`)))}return o.push(""),o.join("\n")})(u,d))}),_c.command("view <runId>").description("Show details for a specific run").option("--json","Output as JSON").action(async(e,t)=>{const r=await qn(),n=Qn(r),o=qa(r);Yn.debug("Viewing run",{runId:e});const s=await Wr({auth:n,client:rn(),headers:to(o),path:{runId:e},query:{detail:"full"}});if(Qa(s,"get run details",`Run "${e}" not found.`),t.json)process.stdout.write(Ka(s.data));else{const e=s.data;process.stdout.write((e=>{const t=[];if(t.push(z.bold(`Run ${e.runId}`)),t.push(` ${z.dim("Status:")} ${Ya(e.status)}`),e.branchName&&t.push(` ${z.dim("Branch:")} ${e.branchName}`),e.commitSha&&t.push(` ${z.dim("Commit:")} ${e.commitSha.slice(0,7)}`),e.startedAt&&t.push(` ${z.dim("Started:")} ${Va(e.startedAt)}`),null!==e.durationMs&&t.push(` ${z.dim("Duration:")} ${(e=>{if(null===e)return"-";const t=Math.floor(e/1e3);if(t<60)return`${t}s`;const r=Math.floor(t/60);return r<60?`${r}m ${t%60}s`:`${Math.floor(r/60)}h ${r%60}m`})(e.durationMs)}`),e.source&&t.push(` ${z.dim("Source:")} ${e.source.toLowerCase()}`),e.projectId){const r=`https://app.stably.ai/project/${e.projectId}/playwright/history/${e.runId}`;t.push(` ${z.dim("URL:")} ${z.cyan(z.underline(r))}`)}t.push("");const r=[];e.passedCount>0&&r.push(z.green(`${e.passedCount} passed`)),e.failedCount>0&&r.push(z.red(`${e.failedCount} failed`)),e.flakyCount>0&&r.push(z.yellow(`${e.flakyCount} flaky`)),e.timedoutCount>0&&r.push(z.red(`${e.timedoutCount} timedout`)),e.skippedCount>0&&r.push(z.dim(`${e.skippedCount} skipped`)),e.interruptedCount>0&&r.push(z.yellow(`${e.interruptedCount} interrupted`)),t.push(`${z.bold("Test Results:")} ${r.join(", ")}`);const n=e.testCases.filter(e=>"FAILED"===e.status||"TIMEDOUT"===e.status||"INTERRUPTED"===e.status||"FLAKY"===e.status);if(n.length>0){t.push(""),t.push(z.bold("Failed/Flaky Tests:"));for(const e of n){const r=e.status??"UNKNOWN",n=Fa[r]??(e=>e),o=e.location??"",s=e.title??e.testIdentifier,{attempts:i}=e,a=i?.length??0,c=a>1?` (${a} attempts)`:"",l=o?`${o} - `:"";t.push(` ${n(r)} ${l}${s}${z.dim(c)}`);const u=i?.at(-1);if(u?.errorMessage){const e=u.errorMessage.split("\n")[0]?.slice(0,100)??"";t.push(` ${z.dim(e)}`)}}}return t.push(""),t.join("\n")})(e))}}),mc.command("build",{hidden:!0}).description('(Deprecated) Use "stably create" instead').allowUnknownOption(!0).allowExcessArguments(!0).action(()=>{process.stderr.write('\n👋 "stably build" has moved! Use "stably create" instead:\n\n stably create "Read the .md files in /tests directory and then create playwright tests"\n\n'),process.exit(1)}),Na.forEach(({args:e,description:t,name:r})=>{mc.command(r).description(t).helpOption(!1).helpCommand(!1).allowUnknownOption(!0).allowExcessArguments(!0).passThroughOptions().action(()=>ja({overrideArgs:e,subcommand:r}))});var Ic=()=>{0!==gc.length&&(process.stderr.write(gc.join("")),gc=[])};(async()=>{await(async()=>{if(!dc&&"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":zr,"node.version":process.version,"os.platform":process.platform}}),dc=!0}catch{}})();try{await mc.parseAsync(process.argv),Yn.info("CLI completed successfully")}catch(e){if(!(e=>!!e&&"object"==typeof e&&"code"in e)(e)){const t=e instanceof Error?e.message:String(e);return Yn.error(t,{stack:e instanceof Error?e.stack:void 0}),Ic(),Yn.flush(),Yn.printLogFileInfo(),await pc(),void(process.exitCode=1)}const t="number"==typeof e.exitCode?e.exitCode:1,r=process.argv.slice(2).find(e=>!e.startsWith("-")),n=!!r&&!!bc(mc,[r]);if(("commander.excessArguments"===e.code||"commander.unknownCommand"===e.code)&&r&&!n)return gc=[],Yn.warn("Unknown command",{command:r}),process.stderr.write(`command '${r}' not found\n`),vc(),void(process.exitCode=t);Yn.debug("Commander error",{code:e.code,exitCode:t}),Ic(),process.exitCode=t}finally{Yn.flush(),await pc()}})();
2
+ import{config as e,parse as t}from"dotenv";import r,{resolve as n,dirname as o,join as s,sep as i,normalize as a,basename as c}from"path";import{Command as l}from"commander";import{Buffer as u}from"buffer";import d,{exec as p,execSync as f,spawn as h}from"child_process";import m from"process";import g,{existsSync as y,statSync as b,realpathSync as v,createReadStream as w,readFileSync as _,mkdirSync as I,writeFileSync as E,appendFileSync as T,openSync as x,readSync as S,closeSync as A,rmSync as C}from"fs";import{fileURLToPath as R,URL as P}from"url";import U,{tmpdir as k,constants as L}from"os";import"timers/promises";import D from"stream";import{debuglog as O,promisify as $,TextDecoder as N,TextEncoder as B}from"util";import{createSdkMcpServer as j,tool as M,query as H}from"@anthropic-ai/claude-agent-sdk";import{match as F}from"ts-pattern";import G,{randomUUID as Y}from"crypto";import V from"net";import{createInterface as W}from"readline/promises";import z from"picocolors";import{simpleGit as K}from"simple-git";import{readFile as q,mkdir as J,writeFile as Q,unlink as X,access as Z,readdir as ee,stat as te,rm as re,appendFile as ne}from"fs/promises";import{log as oe,outro as se,spinner as ie,intro as ae,select as ce,isCancel as le}from"@clack/prompts";import ue,{z as de}from"zod";import pe from"open";import fe from"http";import he from"pino";import me from"sonic-boom";import{z as ge}from"zod/v3";import ye from"ws";import{useState as be,useRef as ve,useEffect as we,useCallback as _e,useMemo as Ie}from"react";import{jsx as Ee,jsxs as Te}from"react/jsx-runtime";import{createRequire as xe}from"module";import{parseDocument as Se}from"yaml";import{startTunnel as Ae}from"@stablyhq/runner-sdk";var Ce={cwdChanged:!1,newCwd:void 0,envFilesLoaded:[],envFileErrors:[],remoteEnvName:void 0},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++;var ke=process.argv.findIndex(e=>"--env"===e);-1!==ke&&process.argv[ke+1]&&!process.argv[ke+1].startsWith("-")&&(Ce.remoteEnvName=process.argv[ke+1],process.argv.splice(ke,2));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 Le={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 De(e){return(/\d+(?!.*\d+)/.exec(e)||[])[0]}function Oe(e){return e?/^(?:refs\/heads\/)?(?<branch>.+)$/i.exec(e)[1]:void 0}var $e={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:Oe(r?e.SYSTEM_PULLREQUEST_TARGETBRANCH:e.BUILD_SOURCEBRANCH),pr:t,isPr:r,prBranch:Oe(r?e.SYSTEM_PULLREQUEST_SOURCEBRANCH:void 0),root:e.BUILD_REPOSITORY_LOCALPATH}}},Ne={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})},Be={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})},je={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=De(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}}},He="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Fe(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ge,Ye,Ve,We,ze,Ke,qe,Je,Qe={exports:{}};var Xe,Ze,et,tt,rt,nt,ot,st,it,at,ct,lt,ut,dt,pt,ft={exports:{}},ht={};function mt(){if(lt)return ct;lt=1;const e=r,t=function(){if(et)return Ze;et=1;const e=r,t=function(){if(Je)return qe;Je=1;const e="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,t=r,n=e?";":":",o=function(){if(Ke)return ze;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 Ke=1,e="win32"===process.platform||He.TESTING_WINDOWS?function(){if(Ye)return Ge;Ye=1,Ge=r,r.sync=function(r,n){return t(e.statSync(r),r,n)};var e=g;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 Ge}():function(){if(We)return Ve;We=1,Ve=t,t.sync=function(t,n){return r(e.statSync(t),n)};var e=g;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 Ve}(),ze=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}},ze}(),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 qe=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)},qe}(),n=function(){if(Xe)return ft.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 ft.exports=e,ft.exports.default=e,ft.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 Ze=function(e){return o(e)||o(e,!0)}}(),n=function(){if(tt)return ht;tt=1;const e=/([()\][%!^"`<>&|;, *?])/g;return ht.command=function(t){return t.replace(e,"^$1")},ht.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},ht}(),o=function(){if(at)return it;at=1;const e=g,t=function(){if(st)return ot;st=1;const e=nt?rt:(nt=1,rt=/^#!(.*)/);return ot=(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 it=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 ct=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 gt=Fe(function(){if(pt)return Qe.exports;pt=1;const e=d,t=mt(),r=function(){if(dt)return ut;dt=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 ut={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},ut}();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 Qe.exports=n,Qe.exports.spawn=n,Qe.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},Qe.exports._parse=t,Qe.exports._enoent=r,Qe.exports}());function yt(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 bt=(e,t)=>({name:`SIGRT${t+1}`,number:vt+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),vt=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"}],_t=()=>{const e=(()=>{const e=64-vt+1;return Array.from({length:e},bt)})();return[...wt,...e].map(It)},It=({name:e,number:t,description:r,action:n,forced:o=!1,standard:s})=>{const{signals:{[e]:i}}=L,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}],Tt=(()=>{const e=_t();return Object.fromEntries(e.map(Et))})();(()=>{const e=_t(),t=Array.from({length:65},(t,r)=>((e,t)=>{const r=((e,t)=>{const r=t.find(({name:t})=>L.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 xt=({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=m.cwd()}}})=>{s=null===s?void 0:s;const f=void 0===(o=null===o?void 0:o)?void 0:Tt[o].description,h=(({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 ${h}: ${i}`,y="[object Error]"===Object.prototype.toString.call(n),b=y?`${g}\n${n.message}`:g,v=[b,t,e].filter(Boolean).join("\n");return y?(n.originalMessage=n.message,n.message=v):n=new Error(v),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},St=["stdin","stdout","stderr"],At=[];At.push("SIGHUP","SIGINT","SIGTERM"),"win32"!==process.platform&&At.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),"linux"===process.platform&&At.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var Ct,Rt,Pt=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,Ut=Symbol.for("signal-exit emitter"),kt=globalThis,Lt=Object.defineProperty.bind(Object),Dt=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(kt[Ut])return kt[Ut];Lt(kt,Ut,{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}},Ot=class{},$t=globalThis.process;Pt($t)?new class extends Ot{#e="win32"===$t.platform?"SIGINT":"SIGHUP";#t=new Dt;#r;#n;#o;#s={};#i=!1;constructor(e){super(),this.#r=e,this.#s={};for(const t of At)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(!Pt(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 At)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,At.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 Pt(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&&Pt(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)}}($t):new class extends Ot{onExit(){return()=>{}}load(){}unload(){}},new TextEncoder,function(){if(Rt)return Ct;Rt=1;const{PassThrough:e}=D;Ct=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 Nt=(async()=>{})().constructor.prototype;["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(Nt,e)]);var Bt=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],jt=/^[\w.-]+$/,Mt=O("execa").enabled,Ht=(e,t)=>String(e).padStart(t,"0"),Ft=(e,t,n={})=>{const o=gt._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||m.cwd(),execPath:m.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?{...m.env,...e}:e;return n?(({env:e=m.env,...t}={})=>{const n=yt({env:e={...e}});return t.path=e[n],e[n]=(({cwd:e=m.cwd(),path:t=m.env[yt()],preferLocal:n=!0,execPath:o=m.execPath,addExecPath:s=!0}={})=>{const i=e instanceof URL?R(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?R(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 St.map(t=>e[t]);if((e=>St.some(t=>void 0!==e[t]))(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${St.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,St.length);return Array.from({length:r},(e,r)=>t[r])})(n),"win32"===m.platform&&"cmd"===r.basename(e,".exe")&&t.unshift("/q"),{file:e,args:t,options:n,parsed:o}},Gt=(e,t,r)=>"string"==typeof t||u.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 Yt(e,t,r){const n=Ft(e,t,r),o=((e,t)=>Bt(e,t).join(" "))(e,t),s=((e,t)=>Bt(e,t).map(e=>(e=>"string"!=typeof e||jt.test(e)?e:`"${e.replaceAll('"','\\"')}"`)(e)).join(" "))(e,t);((e,{verbose:t})=>{t&&m.stderr.write(`[${(()=>{const e=new Date;return`${Ht(e.getHours(),2)}:${Ht(e.getMinutes(),2)}:${Ht(e.getSeconds(),2)}.${Ht(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),_(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=d.spawnSync(n.file,n.args,{...n.options,input:i})}catch(e){throw xt({error:e,stdout:"",stderr:"",all:"",command:o,escapedCommand:s,parsed:n,timedOut:!1,isCanceled:!1,killed:!1})}const c=Gt(n.options,a.stdout,a.error),l=Gt(n.options,a.stderr,a.error);if(a.error||0!==a.status||null!==a.signal){const e=xt({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 Vt(e){try{return Yt("git",["rev-parse","HEAD"],e).stdout}catch{return}}function Wt(e){try{const t=Yt("git",["rev-parse","--abbrev-ref","HEAD"],e).stdout;if("HEAD"===t){const t=Yt("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 zt=/^(?:.*)@(?:.*):(?:\d+\/)?(.*)\.git$/,Kt=/^\/(.*)\.git$/;function qt(e){if(e){if(e.match(zt))return e.replace(zt,"$1");try{return new URL(e).pathname.replace(Kt,"$1")}catch{return}}}var Jt,Qt={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:qt(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||De(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}`}}},Zt="https://cirrus-ci.com",er={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:`${Zt}/build/${e.CIRRUS_BUILD_ID}`,job:e.CIRRUS_TASK_ID,jobUrl:`${Zt}/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}}},tr={detect:({env:e})=>Boolean(e.CODEBUILD_BUILD_ID),configuration:({env:e,cwd:t})=>({name:"AWS CodeBuild",service:"codebuild",commit:Vt({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})},rr={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}}},nr={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}}},or=({env:e})=>{try{const t=e.GITHUB_EVENT_PATH?JSON.parse(_(e.GITHUB_EVENT_PATH,"utf-8")):void 0;if(t&&t.pull_request)return{branch:t.pull_request.base?Oe(t.pull_request.base.ref):void 0,pr:t.pull_request.number}}catch{}return{pr:void 0,branch:void 0}},sr={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=Oe("pull_request_target"===e.GITHUB_EVENT_NAME?`refs/pull/${(e=>{const t=e.GITHUB_EVENT_PATH?JSON.parse(_(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?or({env:e}):void 0}}},ir={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}}},ar={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||Vt({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}}},cr={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}}},lr={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})},ur={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}}},dr={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}}},pr={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}}},fr={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||Vt({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}}},hr={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}}},mr={};function gr(){if(Jt)return mr;Jt=1,Object.defineProperty(mr,"__esModule",{value:!0}),mr.of=mr.PropertiesFile=void 0;var e,t=(e=g)&&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 mr.PropertiesFile=r,mr.of=function(...e){let t=new r;return t.of.apply(t,e),t},mr}var yr=Fe(gr()),br={root:"teamcity.build.workingDir",branch:"teamcity.build.branch"},vr=e=>{try{return yr.of(e)}catch{return}},wr=({env:e,cwd:t})=>{const r=e.TEAMCITY_BUILD_PROPERTIES_FILE?vr(e.TEAMCITY_BUILD_PROPERTIES_FILE):void 0,n=r?r.get("teamcity.configuration.properties.file"):void 0,o=n?vr(n):n;return Object.fromEntries(Object.keys(br).map(n=>[n,(r?r.get(br[n]):void 0)||(o?o.get(br[n]):void 0)||("branch"===n?Wt({env:e,cwd:t}):void 0)]))},_r={appveyor:Le,azurePipelines:$e,bamboo:Ne,bitbucket:Be,bitrise:je,buddy:Me,buildkite:Qt,circleci:Xt,cirrus:er,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:tr,codefresh:rr,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:nr,github:sr,gitlab:ir,jenkins:ar,netlify:cr,puppet:lr,sail:ur,screwdriver:dr,scrutinizer:pr,semaphore:fr,shippable:hr,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:Oe(e.JB_SPACE_GIT_BRANCH),slug:t&&r?`${t.toLowerCase()}/${r}`:void 0}}}},Ir=class e{git;config;snapshotTreeHash;snapshotIndexPath;constructor(e){this.config=e,this.git=K({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(k(),`git-diff-tracker-${Y()}.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(k(),`git-diff-tracker-${Y()}.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 X(e)}catch{}}var Tr="x-stably-org-id",xr={bodySerializer:e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t)},Sr=({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):Ar({allowReserved:e,name:r,value:t})).join(s);return"label"===n||"matrix"===n?s+i:i},Ar=({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)}`},Cr=({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])=>Ar({allowReserved:e,name:"deepObject"===n?`${r}[${t}]`:t,value:o})).join(i);return"label"===n||"matrix"===n?i+a:a},Rr=/\{[^{}]+\}/g;function Pr(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 Ur,kr=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},Lr=({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=Sr({allowReserved:i.allowReserved,explode:!0,name:o,style:"form",value:s,...i.array});e&&n.push(e)}else if("object"==typeof s){const e=Cr({allowReserved:i.allowReserved,explode:!0,name:o,style:"deepObject",value:s,...i.object});e&&n.push(e)}else{const e=Ar({allowReserved:i.allowReserved,name:o,value:s});e&&n.push(e)}}return n.join("&")},Dr=(e,t)=>!!t&&!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`)),Or=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(Rr);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,Sr({explode:n,name:o,style:s,value:i}));continue}if("object"==typeof i){r=r.replace(t,Cr({explode:n,name:o,style:s,value:i,valueOnly:!0}));continue}if("matrix"===s){r=r.replace(t,`;${Ar({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:Lr(e.querySerializer),url:e.url}),$r=(e,t)=>{const r={...e,...t};return r.baseUrl?.endsWith("/")&&(r.baseUrl=r.baseUrl.substring(0,r.baseUrl.length-1)),r.headers=Br(e.headers,t.headers),r},Nr=e=>{const t=[];return e.forEach((e,r)=>{t.push([r,e])}),t},Br=(...e)=>{const t=new Headers;for(const r of e){if(!r)continue;const e=r instanceof Headers?Nr(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},jr=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=Lr({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Hr={"Content-Type":"application/json"},Fr=(e={})=>({...xr,headers:Hr,parseAs:"auto",querySerializer:Mr,...e}),Gr=(e={})=>{let t=$r(Fr(),e);const r=()=>({...t}),n={error:new jr,request:new jr,response:new jr},o=async e=>{const r={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:Br(t.headers,e.headers),serializedBody:void 0};return r.security&&await(async({security:e,...t})=>{for(const r of e){if(Dr(t,r.name))continue;const e=await kr(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:Or(r)}},s=async e=>{const{opts:t,url:r}=await o(e),s={redirect:"follow",...t,body:Pr(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:Or,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=$r(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")}},Yr=Gr(Fr({baseUrl:"https://api.stably.ai"})),Vr=e=>(e.client??Yr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs",...e}),Wr=e=>(e.client??Yr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}",...e}),zr="4.8.9",Kr=process.env.STABLY_API_URL||"https://api.stably.ai",qr=e=>{const t=new URL(e);return t.protocol="http:"===t.protocol?"ws:":"wss:",t},Jr=process.env.AUTH_URL||"https://auth.stably.ai",Qr=process.env.AUTH_CLIENT_ID||"288007877071cce81f269428ea78653a",Xr=process.env.AI_PROXY_URL||"https://ai-proxy.stably.ai",Zr=process.env.STABLY_AUTOHEAL_WS_URL||new URL("/autoheal",qr(Kr)).toString(),en=process.env.STABLY_CREATE_PROGRESS_WS_URL||new URL("/create-progress",qr(Kr)).toString(),tn="http://localhost:9876/auth/callback",rn=()=>Ur||(Ur=Gr(Fr({baseUrl:Kr,headers:{"X-STABLY-CLI-VERSION":zr,"X-STABLY-SOURCE":"cli"}}))),nn=async(e,t)=>{const r=await(n={body:{accessToken:e,orgId:t},client:rn()},(n.client??Yr).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},on=de.object({org_id:de.string(),org_name:de.string()}),sn=de.object({email:de.string(),org_id_to_org_member_info:de.record(de.string(),on).optional(),org_member_info:on.optional(),user_id:de.string()});de.object({email:de.string(),firstName:de.string().optional(),lastName:de.string().optional(),organizations:de.array(de.object({id:de.string(),name:de.string()})),userId:de.string()});var an,cn=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)},ln=e=>{try{const t=sn.parse(cn(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"}`)}},un=async(e,t)=>{let n=e;const{root:o}=r.parse(n);for(;n!==o;){const e=r.join(n,t);try{return await Z(e),e}catch{n=r.dirname(n)}}},dn=r.join(U.homedir(),".stably"),pn=r.join(dn,"auth.json"),fn=".stably",hn="project.json",mn=ue.object({accessToken:ue.string(),expiresAt:ue.number(),idToken:ue.string().optional(),refreshToken:ue.string()}),gn=ue.object({orgId:ue.string(),orgName:ue.string(),projectId:ue.string(),projectName:ue.string()}),yn=async()=>{try{const e=await q(pn,"utf-8");return mn.parse(JSON.parse(e))}catch{return}},bn=async e=>{await J(dn,{recursive:!0}),await Q(pn,JSON.stringify(e,null,2),{mode:384})},vn=async()=>{try{await X(pn)}catch{}},wn=async()=>{try{const e=await un(process.cwd(),fn);if(!e)return;const t=r.join(e,hn),n=await q(t,"utf-8");return gn.parse(JSON.parse(n))}catch{return}},_n=async()=>{try{const e=await un(process.cwd(),fn);e&&await X(r.join(e,hn))}catch{}},In=e=>Date.now()>=e.expiresAt-3e5,En=async e=>{const t=new URLSearchParams({client_id:Qr,grant_type:"refresh_token",refresh_token:e}),r=await fetch(`${Jr}/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}},Tn=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`,xn=(e,t,r)=>{e.writeHead(t,{"Content-Type":"text/html"}),e.end(r)},Sn=(e,t)=>{const r=new URLSearchParams({client_id:Qr,code_challenge:e,code_challenge_method:"S256",redirect_uri:tn,response_type:"code",state:t});return`${Jr}/propelauth/oauth/authorize?${r.toString()}`},An=async e=>{const t=ie();let n;t.start("Loading user info...");try{n=ln(e.accessToken),t.stop(z.green(`✓ Logged in as ${z.cyan(n.email)}`))}catch(e){t.stop(z.red("✗ Failed to load user info"));const r=e instanceof Error?e.message:"Unknown error";return oe.error(r),{success:!1}}const o=await(async e=>{if(0===e.length)return void oe.error("You don't belong to any organizations.");if(1===e.length)return oe.info(`Using organization: ${z.cyan(e[0].name)}`),e[0];if(!process.stdin.isTTY)return oe.info(`Auto-selecting organization: ${z.cyan(e[0].name)}`),e[0];const t=await ce({message:"Select an organization",options:[...e].sort((e,t)=>e.name.localeCompare(t.name)).map(e=>({label:e.name,value:e.id}))});return le(t)?void 0:e.find(e=>e.id===t)})(n.organizations);if(!o)return oe.warn("Organization selection cancelled."),{success:!1};let s;t.start("Getting org credentials...");try{const r=await nn(e.accessToken,o.id);s={accessToken:r.accessToken,expiresAt:Date.now()+1e3*r.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken},t.stop(z.green("✓ Credentials obtained"))}catch(e){t.stop(z.red("✗ Failed to get org credentials"));const r=e instanceof Error?e.message:"Unknown error";return oe.error(r),{success:!1}}const i=await(async(e,t)=>{const r=ie();let n;r.start("Loading projects...");try{n=await(async({accessToken:e,orgId:t})=>{const r=await(n={auth:e,client:rn(),path:{orgId:t}},(n.client??Yr).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(z.green("✓ Projects loaded"))}catch(e){r.stop(z.red("✗ Failed to load projects"));const t=e instanceof Error?e.message:"Unknown error";return void oe.error(t)}if(0===n.length)return oe.error("No projects found in this organization."),void oe.info(`Create a project at ${z.underline(z.cyan("https://app.stably.ai"))}`);if(1===n.length)return oe.info(`Using project: ${z.cyan(n[0].name)}`),n[0];if(!process.stdin.isTTY)return oe.info(`Auto-selecting project: ${z.cyan(n[0].name)}`),n[0];const o=await ce({message:"Select a project",options:n.map(e=>({label:e.name,value:e.id}))});return le(o)?void 0:n.find(e=>e.id===o)})(s.accessToken,o.id);return i?(await(async e=>{const t=r.join(process.cwd(),fn),n=r.join(t,hn);await J(t,{recursive:!0}),await Q(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 q(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 Q(t,r)}else if(s.test(e)){const r=e.replace(s,`\n${n}\n`);await Q(t,r)}else await ne(t,`\n${n}\n`)}catch{await Q(t,`${n}\n`)}})(process.cwd())})({orgId:o.id,orgName:o.name,projectId:i.id,projectName:i.name}),oe.info(z.dim("Linked this directory to your Stably project.")),{scopedTokens:s,success:!0}):(oe.warn("Project selection cancelled."),{success:!1})},Cn=async()=>{if(zn())return oe.warn(`Environment variables ${z.cyan("STABLY_API_KEY")} and ${z.cyan("STABLY_PROJECT_ID")} are set.`),oe.warn("These will be used for authentication instead of OAuth login."),oe.warn("To use OAuth login, unset these environment variables first."),void se(z.yellow("Login skipped - using environment variable authentication."));const e=await yn();if(e){if(!In(e)){if(await wn())return void se(z.yellow("You are already logged in. Run `stably logout` first to log out."));oe.info("You are logged in but haven't selected a project yet.");const t=await An(e);return void(t.success?(await bn(t.scopedTokens),se(z.green("Setup complete! You can now use Stably CLI."))):se(z.yellow("Setup incomplete. Run `stably login` to try again.")))}const t=ie();t.start("Refreshing session...");try{const r=await En(e.refreshToken);t.stop(z.green("✓ Session refreshed"));const n=await wn();if(n){t.start("Getting org credentials...");try{const e=await nn(r.accessToken,n.orgId),o={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:r.idToken,refreshToken:r.refreshToken};await bn(o),t.stop(z.green("✓ Credentials obtained")),se(z.green("Login successful"))}catch{await bn(r),t.stop(z.yellow("Using full credentials")),se(z.green("Login successful"))}}else{const e=await An(r);e.success?(await bn(e.scopedTokens),se(z.green("Setup complete! You can now use Stably CLI."))):se(z.yellow("Setup incomplete. Run `stably login` to try again."))}return}catch{t.stop(z.yellow("Session expired, proceeding with fresh login...")),await vn(),await _n()}}const{authorizeUrl:t,serverReady:r,waitForCallback:n}=(()=>{const{authorizeUrl:e,codeVerifier:t,state:r}=(()=>{const e=G.randomBytes(32).toString("base64url"),t=(r=e,G.createHash("sha256").update(r).digest("base64url"));var r;const n=G.randomBytes(16).toString("base64url");return{authorizeUrl:Sn(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=fe.createServer((t,r)=>{const o=new P(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?(xn(r,400,Tn(l)),i(),a.close(),void n({error:l,success:!1})):s&&c?c!==e?(xn(r,400,Tn("Invalid state parameter (possible CSRF attack)")),i(),a.close(),void n({error:"State mismatch",success:!1})):(xn(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})):(xn(r,400,Tn("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:Qr,code:e,code_verifier:t,grant_type:"authorization_code",redirect_uri:tn}),n=await fetch(`${Jr}/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,oe.info("Opening browser for authentication..."),oe.info(z.dim("If browser doesn't open, visit:")),oe.info(`]8;;${t}${z.underline(z.cyan(t))}]8;;`);try{await pe(t)}catch{oe.warn("Could not open browser automatically. Please open the URL above manually.")}const o=ie();let s;o.start("Waiting for authentication...");try{s=await n(),o.stop(z.green("✓ Authentication successful"))}catch(e){o.stop(z.red("✗ Authentication failed"));const t=e instanceof Error?e.message:"Unknown error";se(z.red(`Login failed: ${t}`)),process.exit(1)}const i=await An(s);i.success?(await bn(i.scopedTokens),se(z.green("Setup complete! You can now use Stably CLI."))):(se(z.yellow("Setup incomplete. Run `stably login` to try again.")),process.exit(1))},Rn={fatal:60,error:50,warn:40,info:30,debug:20,trace:10},Pn=new Set(["help","login","logout","whoami","tunnel","create","fix","init","upgrade","test","show-report","codegen"]),Un=(new Date).toISOString().split("T")[0],kn=(()=>{const e=[r.join(U.tmpdir(),"stably-logs",Un),r.join(U.homedir(),".stably","logs",Un)];for(const t of e)try{return g.mkdirSync(t,{recursive:!0}),t}catch{}return null})(),Ln=process.argv.includes("--verbose")||process.argv.includes("-v"),Dn=process.env.STABLY_LOG_LEVEL?.toLowerCase(),On=Ln?"debug":void 0!==(an=Dn)&&an in Rn?Dn:"warn",$n=Rn[On],Nn=null,Bn=null,jn=null,Mn=[],Hn=!1,Fn=e=>{if(!Hn){if(!(Nn=(e=>{if(!kn)return null;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(kn,`${t}-${n}.log`)})(e)))return Mn=[],void(Hn=!0);(e=>{const t=["","=".repeat(60),"Stably CLI Debug Log",`Version: ${zr}`,`Generated: ${(new Date).toISOString()}`,`Node: ${process.version}`,`Platform: ${process.platform} ${U.release()}`,`CWD: ${process.cwd()}`,`Args: ${process.argv.slice(2).join(" ")}`,`Log Level (console): ${On}`,"=".repeat(60),""].join("\n");e.write(t)})(Bn=new me({dest:Nn,minLength:4096,sync:!1,append:!0})),jn=he({level:"debug",timestamp:he.stdTimeFunctions.isoTime,base:{version:zr}},Bn);for(const{level:e,msg:t,context:r}of Mn)r?jn[e](r,t):jn[e](t);Mn=[],Hn=!0,Ln&&process.stderr.write(`${z.dim(`Debug log: ${Nn}`)}\n\n`)}},Gn=(()=>{const e=process.argv.slice(2).find(e=>!e.startsWith("-"));return e&&Pn.has(e)?e:null})();Gn&&Fn(Gn);var Yn=e=>(t,r)=>{if(jn?r?jn[e](r,t):jn[e](t):Hn||Mn.push({level:e,msg:t,context:r}),(e=>Rn[e]>=$n)(e)){const r=((e,t)=>`${{fatal:z.bgRed(z.white(" FATAL ")),error:z.red("error"),warn:z.yellow("warn"),info:z.cyan("info"),debug:z.dim("debug"),trace:z.dim("trace")}[e]} ${t}`)(e,t);process.stderr.write(`${r}\n`)}},Vn={fatal:Yn("fatal"),error:Yn("error"),warn:Yn("warn"),info:Yn("info"),debug:Yn("debug"),trace:Yn("trace"),initSession:e=>{Hn||Fn(e)},getLogFilePath:()=>Nn,flush:()=>{if(Bn)try{Bn.flushSync()}catch{}},printLogFileInfo:()=>{Nn&&(process.stderr.write(`\n${z.dim("Debug log written to:")}\n`),process.stderr.write(` ${z.cyan(Nn)}\n`),process.stderr.write(`${z.dim("Share this file with support for assistance.")}\n`))},getPinoLogger:()=>jn};setInterval(()=>{Vn.flush()},3e4).unref(),process.on("beforeExit",()=>{Vn.flush()});var Wn=e=>{const t=()=>{Vn.flush(),Ln&&Vn.printLogFileInfo(),process.removeListener(e,t),process.kill(process.pid,e)};return t};process.on("SIGINT",Wn("SIGINT")),process.on("SIGTERM",Wn("SIGTERM"));var zn=()=>{const e=process.env.STABLY_API_KEY?.trim(),t=process.env.STABLY_PROJECT_ID?.trim();if(e&&t)return Vn.debug("Environment auth detected",{hasApiKey:!0,hasProjectId:!0}),{apiKey:e,projectId:t};Vn.debug("Environment auth not set",{hasApiKey:!!e,hasProjectId:!!t})},Kn=async()=>{Vn.debug("Checking for stored auth tokens");const e=await yn();if(!e)return void Vn.debug("No stored auth tokens found");const t=In(e);if(Vn.debug("Auth tokens status",{expired:t}),!t){const t=await wn(),r=(e=>{try{const t=sn.parse(cn(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(Vn.debug("Token scope check",{scope:r,hasContext:!!t}),t&&"full"===r)try{Vn.debug("Exchanging full token for org-scoped token",{orgId:t.orgId});const r=await nn(e.accessToken,t.orgId),n={accessToken:r.accessToken,expiresAt:Date.now()+1e3*r.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken};return await bn(n),Vn.debug("Token exchange successful"),n}catch(t){return Vn.debug("Token exchange failed, using existing token",{error:t instanceof Error?t.message:String(t)}),e}return e}try{Vn.debug("Attempting token refresh");const t=await En(e.refreshToken);Vn.debug("Token refresh successful");const r=await wn();if(r)try{Vn.debug("Exchanging refreshed token for org-scoped token");const e=await nn(t.accessToken,r.orgId),n={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:t.idToken,refreshToken:t.refreshToken};return await bn(n),n}catch{return await bn(t),t}return await bn(t),t}catch(e){return void Vn.warn("Token refresh failed",{error:e instanceof Error?e.message:String(e)})}},qn=async(e={})=>{Vn.debug("Requiring authentication",{autoLogin:e.autoLogin});const t=zn();if(t)return Vn.info("Using environment variable authentication"),{auth:t,type:"env"};let r=await Kn(),n=r?await wn():void 0;const o=process.stdin.isTTY&&process.stdout.isTTY;if(Vn.debug("OAuth auth check",{hasTokens:!!r,hasContext:!!n,canPrompt:o}),(!r||!n)&&e.autoLogin&&o){Vn.info("Prompting user to login"),r?oe.info("You are logged in but need to select an organization and project."):oe.info("You are not logged in."),oe.info("Press Enter to log in."),process.stdout.write(`${z.dim("Alternatively, set environment variables for an org API key:")}\n${z.dim(" STABLY_API_KEY=... STABLY_PROJECT_ID=... stably")}\n`),process.stdout.write("\n");const e=W({input:process.stdin,output:process.stdout});try{await e.question(z.dim("Press Enter to continue... "))}finally{e.close()}await Cn(),r=await Kn(),n=r?await wn():void 0}return r||(Vn.warn("Authentication required but no tokens available"),se(z.red("You are not logged in. Run `stably login` to authenticate.")),process.exit(1)),n||(Vn.warn("Authentication succeeded but no project context selected"),se(z.red("You haven't selected an organization and project. Run `stably login` to complete setup.")),process.exit(1)),Vn.info("OAuth authentication successful",{orgId:n.orgId,projectId:n.projectId}),{auth:{accessToken:r.accessToken,context:n},type:"oauth"}},Jn=e=>"env"===e.type?e.auth.projectId:e.auth.context.projectId,Qn=e=>"env"===e.type?e.auth.apiKey:e.auth.accessToken,Xn=e=>e?{...process.env,...e}:process.env,Zn=async()=>{Vn.info("[test] Resolving Stably test env");const e=(()=>{if(process.env.STABLY_WS_URL)return;if("https://api.stably.ai"===Kr)return;const e=Kr.startsWith("http://")?"ws://":"wss://";return`${Kr.replace(/^https?:\/\//,e).replace(/\/$/,"")}/reporter`})();Vn.debug("[test] WebSocket URL resolved",{wsUrl:e??"(default)"});const t=zn();if(t)return Vn.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}};Vn.info("[test] No env var auth, attempting OAuth auth");const r=Date.now(),n=await(async()=>{const e=zn();if(e)return{auth:e,type:"env"};const t=await Kn(),r=t?await wn():void 0;return t&&r?{auth:{accessToken:t.accessToken,context:r},type:"oauth"}:void 0})();if(Vn.info("[test] OAuth auth resolved",{durationMs:Date.now()-r,hasAuth:!!n,authType:n?.type}),!n||"env"===n.type)return void Vn.info("[test] No usable auth found");const o=process.env.STABLY_PROJECT_ID?.trim(),s=o||Jn(n);if(!s)return void Vn.warn("[test] No project ID available");Vn.info("[test] Fetching JWT API key",{projectId:s});const i=Date.now(),a=await(async(e,t)=>{try{Vn.debug("Requesting JWT API key",{projectId:t,apiUrl:Kr});const r=await(async({accessToken:e,projectId:t})=>{const r=await(n={auth:e,client:rn(),path:{projectId:t}},(n.client??Yr).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 Vn.debug("JWT API key obtained",{keyPrefix:r.apiKey.substring(0,10)}),r.apiKey}catch(e){return void Vn.warn("Failed to get JWT API key for test reporter",{error:e instanceof Error?e.message:String(e)})}})(n.auth.accessToken,s);Vn.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 Vn.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},eo=async()=>{const e=Ce.remoteEnvName;if(!e)return;const t=await qn(),r=Jn(t),n=Qn(t);Vn.debug("Fetching remote environment variables",{envName:e,projectId:r});const o=await(s={auth:n,client:rn(),path:{projectId:r,environment:e}},(s.client??Yr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/environments/{environment}/variables",...s}));var s;404===o.response.status&&(se(z.red(`Environment "${e}" not found. Check the name on your Stably dashboard.`)),process.exit(1)),401!==o.response.status&&403!==o.response.status||(se(z.red(`Access denied to environment "${e}".`)),process.exit(1)),o.error&&(se(z.red(`Failed to fetch environment "${e}": ${o.response.status}`)),process.exit(1));const i={},a=[];for(const e of o.data.variables)i[e.name]=e.value,e.sensitive&&e.value.length>0&&a.push(e.value);const c=o.data.variables.length,l=a.length;return process.stderr.write(`${z.cyan(`Loaded ${c} variable${1!==c?"s":""} from "${e}"`)}${l>0?z.dim(` (${l} sensitive)`):""}\n`),{variables:i,sensitiveValues:a}},to=e=>e?{[Tr]:e}:void 0,ro=de.object({context:de.string().min(1),autohealReportUrl:de.string(),skippedTests:de.array(de.object({testIdentifier:de.string(),testTitle:de.string(),consecutiveUnfixedCount:de.number()})).optional()}),no=ge.object({bucket:ge.string(),key:ge.string()}),oo=async({body:e,contentType:t,uploadUrl:r,errorContext:n="content"})=>{const o=await fetch(r,{body:e instanceof Uint8Array?Buffer.from(e):e,headers:{"Content-Type":t},method:"PUT"});if(!o.ok)throw new Error(`Failed to upload ${n} (${o.status})`)},so=ge.object({diffBucketPath:no,expiresInSeconds:ge.number(),key:ge.string(),uploadUrl:ge.string()}),io=ge.object({traceBucketPath:no,expiresInSeconds:ge.number(),key:ge.string(),uploadUrl:ge.string(),sensitiveValues:ge.array(ge.string())}),ao=async({authHeader:e,contentType:t="text/plain",orgId:r,runId:n})=>{const o=await(s={auth:e,body:{contentType:t},client:rn(),headers:to(r),path:{runId:n}},(s.client??Yr).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=so.parse(o.data);return{diffBucketPath:i.diffBucketPath,expiresInSeconds:i.expiresInSeconds,key:i.key,uploadUrl:i.uploadUrl}},co=async({authHeader:e,diffBucketPath:t,orgId:r,runId:n})=>{const o=await(s={auth:e,body:t,client:rn(),headers:to(r),path:{runId:n}},(s.client??Yr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-diff/confirm-upload",...s,headers:{"Content-Type":"application/json",...s.headers}}));var s;if(o.error)throw new Error(`Failed to confirm diff upload (${o.response.status})`)},lo=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=Zr,onUserMessage:o}){this.authHeader=e,this.orgId=t,this.runId=r,this.url=n,this.onUserMessage=o,Vn.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)}`;Vn.info("[ws] Connecting",{url:t,attempt:this.reconnectAttempts}),this.socket=new ye(t,{headers:e}),this.socket.on("open",()=>{Vn.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);Vn.debug("[ws] Received message",{type:r?.type}),"connected"===r?.type&&(Vn.info("[ws] Authenticated successfully"),this.isAuthenticated=!0,this.authenticationFailed=!1,this.flushPending()),"user_message"===r?.type&&"string"==typeof r.content&&(Vn.info("[ws] Received user message from web UI"),this.onUserMessage?.(r.content))}catch{}}),this.socket.on("close",(e,t)=>{Vn.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=>{Vn.warn("[ws] Connection error",{error:e.message})})}catch(e){Vn.warn("[ws] Failed to create WebSocket",{error:e instanceof Error?e.message:String(e)}),this.scheduleReconnect()}}scheduleReconnect(){this._isClosed||this.reconnectTimer||(this.reconnectAttempts++,Vn.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===ye.OPEN&&this.isAuthenticated}sendProgress(e){if(this._isClosed)return void Vn.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?(Vn.info("[ws] sendProgress: flushing terminal state immediately"),void this.flushPending()):void(this.debounceTimer||(this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.flushPending()},this.debounceMs))):(Vn.debug("[ws] sendProgress: not connected, queuing event",{phase:e.phase,socketState:this.socket?.readyState,isAuthenticated:this.isAuthenticated,reconnectAttempts:this.reconnectAttempts}),void(this.socket?.readyState===ye.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 Vn.debug("[ws] flushPending: not connected, re-queuing event",{phase:e.payload.phase}),void(this.pendingEvent=e);try{Vn.debug("[ws] flushPending: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),t=>{t&&(Vn.warn("[ws] flushPending: send failed",{error:t.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e))})}catch(t){Vn.warn("[ws] flushPending: send threw",{error:t instanceof Error?t.message:String(t)}),this.pendingEvent=e}}close(){if(this._isClosed)return;Vn.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)}},uo=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=en,onUserMessage:o}){this.authHeader=e,this.orgId=t,this.sessionId=r,this.url=n,this.onUserMessage=o,Vn.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)}`;Vn.info("[ws] Connecting",{url:t,attempt:this.reconnectAttempts}),this.socket=new ye(t,{headers:e}),this.socket.on("open",()=>{Vn.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);Vn.debug("[ws] Received message",{type:r?.type}),"connected"===r?.type&&(Vn.info("[ws] Authenticated successfully"),this.isAuthenticated=!0,this.authenticationFailed=!1,this.flushPending()),"user_message"===r?.type&&"string"==typeof r.content&&(Vn.info("[ws] Received user message from web UI"),this.onUserMessage?.(r.content))}catch{}}),this.socket.on("close",(e,t)=>{Vn.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=>{Vn.warn("[ws] Connection error",{error:e.message})})}catch(e){Vn.warn("[ws] Failed to create WebSocket",{error:e instanceof Error?e.message:String(e)}),this.scheduleReconnect()}}scheduleReconnect(){this._isClosed||this.reconnectTimer||(this.reconnectAttempts++,Vn.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===ye.OPEN&&this.isAuthenticated}sendProgress(e){if(this._isClosed)return void Vn.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?(Vn.info("[ws] sendProgress: flushing terminal state immediately"),void this.flushPending()):void(this.debounceTimer||(this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.flushPending()},this.debounceMs))):(Vn.debug("[ws] sendProgress: not connected, queuing event",{phase:e.phase,socketState:this.socket?.readyState,isAuthenticated:this.isAuthenticated,reconnectAttempts:this.reconnectAttempts}),void(this.socket?.readyState===ye.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 Vn.debug("[ws] flushPending: not connected, re-queuing event",{phase:e.payload.phase}),void(this.pendingEvent=e);try{Vn.debug("[ws] flushPending: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),t=>{t&&(Vn.warn("[ws] flushPending: send failed",{error:t.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e))})}catch(t){Vn.warn("[ws] flushPending: send threw",{error:t instanceof Error?t.message:String(t)}),this.pendingEvent=e}}close(){if(this._isClosed)return;Vn.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)}},po=ge.object({bucketPath:no,expiresInSeconds:ge.number(),key:ge.string(),uploadUrl:ge.string()}),fo=["auth login","auth logout","auth setup-git","auth switch","config set","secret set","secret delete","variable set","variable delete","repo delete","repo edit","repo rename","repo archive"];function ho(e){return/^\.env(\..*)?$/.test(e)||".stably-agent.env"===e}function mo(e){return Boolean(e&&"object"==typeof e&&"tool_input"in e&&e.tool_input&&"object"==typeof e.tool_input)}function go({action:e,pathKey:t}){return function({action:e,fileCheck:t,getBlockMessage:r,pathKey:n}){return async o=>{const s=function({input:e,pathKey:t}){if(!mo(e))return{decision:"block",reason:`Invalid tool call format: Expected an object with 'tool_input' property. Please ensure the tool call follows the correct structure: { tool_input: { ${t}: "path/to/file" } }`,success:!1,systemMessage:"Tool call blocked due to invalid input format"};const r=e.tool_input;return t in r?"string"==typeof r[t]?{path:r[t],success:!0}:{decision:"block",reason:`Invalid tool call format: The '${t}' parameter must be a string containing the file path, but received ${typeof r[t]}. Please provide a valid file path as a string. Example: { tool_input: { ${t}: "src/example.ts" } }`,success:!1,systemMessage:"Tool call blocked due to invalid parameter type"}:{decision:"block",reason:`Invalid tool call format: Missing required parameter '${t}'. Please provide the file path using the '${t}' parameter. Example: { tool_input: { ${t}: "path/to/file" } }`,success:!1,systemMessage:"Tool call blocked due to missing required parameters"}}({input:o,pathKey:n});if(!s.success)return s;const i=s.path.replace(/\\/g,"/"),a=i.split("/").pop()||i;return t(a)?{decision:"block",reason:r("reading"===e?"Access to":"writing"===e?"Writing to":"editing"===e?"Editing":"Searching in"),systemMessage:"AI blocked due to accessing sensitive content"}:{decision:"approve"}}}({action:e,fileCheck:ho,getBlockMessage:e=>`${e} .env files is not allowed. Environment variables and secrets should be managed in Stably's Test Data section instead. You can access these values using process.env in your test code.`,pathKey:t})}var yo=["rm","mv","git","gh","npx","npm","yarn","pnpm","bun"],bo=["stably","playwright"],vo=["push","fetch","pull","clone","ls-remote"];function wo(e){return e.trim().split(/\s+/).filter(e=>e.length>0)}function _o(e){let t=0;for(;t<e.length&&/^\S+=\S+$/.test(e[t]??"");)t+=1;return e.slice(t)}function Io(e,t){const r=a(e).replace(/\\/g,"/"),n=t.replace(/\\/g,"/"),o=n.endsWith("/")?n:`${n}/`;if(r.startsWith(o))return!0;const s=r.lastIndexOf(`/${o}`);if(-1===s)return!1;const i=r.slice(s+`/${o}`.length);return i.length>0&&!i.startsWith("../")}function Eo({onBeforeGitHubCommand:e,workspaceBoundary:t}){return async r=>{if(!mo(r))return{decision:"block",reason:"Invalid tool call format: Expected an object with tool_input property.",systemMessage:"Tool call blocked due to invalid input format"};const s=r.tool_input,{command:a}=s;if("string"!=typeof a)return{decision:"block",reason:"Invalid Bash command: command must be a string.",systemMessage:"Tool call blocked due to invalid command type"};const c=function(e){const t=e.trim().match(/^(?:\S+=\S+\s+)*(\S+)/);return t?.[1]}(a);if(!c)return{decision:"block",reason:"Invalid Bash command: could not parse command.",systemMessage:"Tool call blocked due to unparseable command"};if(!function(e){return"string"==typeof e&&yo.includes(e)}(c))return{decision:"block",reason:`The command "${c}" is not allowed. Only the following commands are permitted: ${yo.join(", ")}. Use the appropriate tools (Read, Write, Edit, Glob, Grep) for file operations instead.`,systemMessage:"Tool call blocked due to disallowed command"};if("npx"===c){const e=function(e){if(/(\s|^)npx\s+.*(\s|^)(-c|--call)(\s|=)/.test(e.trim()))return{valid:!1,reason:"The npx -c/--call form is not allowed. Use direct commands like `npx stably test ...` or `npx playwright test ...`."};const t=function(e){const t=_o(wo(e));if("npx"===t[0])for(let e=1;e<t.length;e+=1){const r=t[e];if(r){if("--"===r)return t[e+1];if(!r.startsWith("-"))return r}}}(e);if(!t)return{valid:!1,reason:"Invalid npx command: unable to determine which binary is being executed."};if(!new Set(bo).has(t))return{valid:!1,reason:`The npx binary "${t}" is not allowed. Only ${bo.join(", ")} are permitted.`};const r=function({command:e,binary:t}){const r=_o(wo(e)),n=r.findIndex(e=>e===t);if(-1!==n)for(let e=n+1;e<r.length;e+=1){const t=r[e];if(t&&!t.startsWith("-"))return t}}({command:e,binary:t});return"test"!==r?{valid:!1,reason:`The npx ${t} command must run the "test" subcommand.`}:{valid:!0}}(a);if(!e.valid)return{decision:"block",reason:e.reason,systemMessage:"Tool call blocked due to disallowed npx command"}}if("rm"===c){const e=function(e){const t=e.trim().match(/^rm\s+(?:-[a-zA-Z]+\s+|--[a-zA-Z-]+\s+)*(.+)$/),r=t?.[1]?.trim();return r?r.split(/\s+/).filter(e=>e.length>0):[]}(a);if(0===e.length)return{decision:"block",reason:"Invalid rm command: could not determine the file path(s) to remove.",systemMessage:"Tool call blocked due to invalid rm command"};if(t){const r=e.filter(e=>!function({targetPath:e,boundaryDir:t}){const r=function(e){if(y(e))return v.native(e);let t=e;const r=[];for(;!y(t);){const s=o(t);if(s===t)return n(e);r.unshift(t.slice(s.length+1)),t=s}const s=v.native(t);return r.length>0?n(s,...r):s}(e),s=v.native(t),a=r.endsWith(i)?r:r+i,c=s.endsWith(i)?s:s+i;return a.startsWith(c)||r===s}({targetPath:n(t,e),boundaryDir:t}));if(r.length>0)return{decision:"block",reason:`The rm command can only remove files within the workspace. The following path(s) are outside the workspace boundary: ${r.join(", ")}.`,systemMessage:"Tool call blocked due to rm outside workspace"}}else{const t=e.filter(e=>!(Io(e,"tests")||Io(e,".stably")));if(t.length>0)return{decision:"block",reason:`The rm command can only remove files in the tests/ directory or .stably/ directory. The following path(s) are not allowed: ${t.join(", ")}.`,systemMessage:"Tool call blocked due to rm outside allowed directories"}}}if("git"===c&&["-c","--config","--config-env"].some(e=>a.includes(` ${e} `)||a.includes(` ${e}=`)))return{decision:"block",reason:"Git config flags (-c, --config, --config-env) are not allowed for security reasons.",systemMessage:"Tool call blocked due to git config injection attempt"};if("git"===c&&function(e){const t=e.trim();return!!t.startsWith("git ")&&vo.some(e=>t.includes(` ${e}`)||t.includes(`git ${e}`))}(a)&&e)try{await e()}catch(e){console.error("[BashSecurityHook] Failed to refresh git token:",e)}if("gh"===c){const t=function(e){const t=e.toLowerCase();return fo.some(e=>t.includes(`gh ${e}`))?{allowed:!1,reason:"This gh subcommand is not allowed for security reasons. Only read operations and PR/issue management are permitted. Blocked subcommands include: auth, config set, secret/variable management, and destructive repo operations.",systemMessage:"Tool call blocked due to dangerous gh subcommand"}:t.includes("gh api")&&(/--method\s+(delete|put|patch)/i.test(e)||/-X\s+(DELETE|PUT|PATCH)/i.test(e))?{allowed:!1,reason:"The gh api command with destructive HTTP methods (DELETE, PUT, PATCH) is not allowed for security reasons. Only GET requests are permitted for raw API access.",systemMessage:"Tool call blocked due to destructive gh api method"}:{allowed:!0}}(a);if(!t.allowed)return{decision:"block",reason:t.reason,systemMessage:t.systemMessage};if(e)try{await e()}catch(e){console.error("[BashSecurityHook] Failed to refresh GitHub token for gh command:",e)}}return{decision:"approve"}}}var To=e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"text"===t.type&&"string"==typeof t.text},xo=e=>null!=e&&"object"==typeof e&&"tool_response"in e,So=e=>{if(!e||"object"!=typeof e)return;const t=e;return Array.isArray(t.tool_response)?t.tool_response:void 0},Ao=e=>{const t=So(e);if(t)return t.filter(To).map(e=>e.text).join("\n")||void 0},Co=/\u001b\[[0-9;]*m/g,Ro=e=>e.replace(Co,""),Po=/\$\{process\.env\.([A-Z_][A-Z0-9_]*)\}/g;function Uo(e,t){return e.replace(Po,(e,r)=>{const n=t[r];return null!=n?n:e})}function ko({envVars:e}){return async t=>{if(!mo(t))return{decision:"approve"};const r=t.tool_input,n={...r};let o=!1;if("string"==typeof r.text){const t=Uo(r.text,e);t!==r.text&&(n.text=t,o=!0)}if("string"==typeof r.url){const t=Uo(r.url,e);t!==r.url&&(n.url=t,o=!0)}if("string"==typeof r.function){const t=Uo(r.function,e);t!==r.function&&(n.function=t,o=!0)}if(Array.isArray(r.fields)){const t=r.fields.map(t=>{if("string"==typeof t.value){const r=Uo(t.value,e);if(r!==t.value)return o=!0,{...t,value:r}}return t});o&&(n.fields=t)}return o?{decision:"approve",hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",reason:"Evaluated environment variable placeholders in browser tool input.",updatedInput:n}}:{decision:"approve"}}}function Lo({onResult:e}){return async t=>{if(!xo(t))return{decision:"approve"};const r=Ao(t);if(!r)return{decision:"approve"};const n=function(e){const t=Ro(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 Do({onResult:e}){return async t=>{if(!xo(t))return{decision:"approve"};const r=Ao(t);if(!r)return{decision:"approve"};const n=function(e){const t=Ro(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 Oo=/\.(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&&Oo.test(n)&&e(n),{decision:"approve"}}}var No=$(p);async function Bo(){try{const{stdout:e}=await No('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 No(`pkill -KILL -P ${e} '.*' 2>/dev/null || true`)}))}catch{}}var jo=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 Mo(e){try{const t=f("git branch --show-current",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(!t)return;return{branch:t}}catch{return}}var Ho=[".ts",".js",".mts",".mjs",".cts",".cjs"],Fo=10240,Go=async({defaultContent:e,fileName:t,filePath:r})=>{try{const e=(await te(r)).size,n=await q(r,"utf-8"),o=Buffer.byteLength(n,"utf-8");if(o<=Fo)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<=Fo?s:s.slice(0,Fo)+`\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}},Yo=async({defaultContent:e,dirName:t,dirPath:r})=>{try{const e=await ee(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}},Vo=async({allowedEnvVars:e,mode:t,workspaceInfo:r,authHeader:n,customHeader:o,maxParallelWorkers:s})=>{const i=rn(),a=Mo(r.absolutePath);Vn.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??Yr).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 Vn.warn("System prompt fetch failed: unauthorized (401)"),await vn(),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 Vn.debug("System prompt fetch failed: forbidden (403)"),new Error("Your organization does not have an active subscription. Manage your subscription at https://app.stably.ai or contact your organization admin.");if(c.error){Vn.warn("System prompt fetch failed",{error:c.error});const e=JSON.stringify(c.error);if(e.toLowerCase().includes("unauthorized")||e.toLowerCase().includes("unauthenticated"))throw await vn(),new Error("Your session has expired or been revoked. Credentials have been cleared. Please run `stably login` to re-authenticate.");throw new Error("Failed to fetch system prompt. Please check your network connection and try again. If this persists, run `stably login` to re-authenticate.")}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 Vn.debug("System prompt received",{size:u.length,appendedCustomHeader:!!o,hasPrContext:!!c.data.prContext}),{systemPrompt:u,prContext:c.data.prContext}},Wo=".stably-playwright-wrapper.config.*",zo=[".ts",".js",".mts",".mjs",".cts",".cjs"];function Ko(e){const t=n(e);if(y(t))for(const e of zo){const r=s(t,`playwright.config${e}`);if(y(r))return r}}var qo=["tests","e2e","__tests__","test"];function Jo(e){try{return y(e)&&b(e).isDirectory()}catch{return!1}}function Qo(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(z.dim(`Using output directory: ${e} (from ${r})`))}var Xo,Zo=["mcp__playwright-test__","mcp__auto-heal-report__","mcp__stably-agent-control__"],es=["planner_","generator_"],ts={"mcp__stably-agent-control__restart_mcp_servers":"Restarting Browser Tools","mcp__session-control__restart_mcp_servers":"Restarting Browser Tools"},rs=(e,t)=>{const r=t.find(t=>e.startsWith(t));return r?e.slice(r.length):e},ns=(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},os=e=>"mcp__auto-heal-report__capture-trace-proof"===e?"Verify Test Run":"mcp__auto-heal-report__generate-report"===e?"Generate Report":(e=>{const t=ts[e];if(t)return t;const r=rs(e,Zo);return rs(r,es).split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")})(e),ss=["test","bug","flake","ui_change","other"],is={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."},as=e=>is[e],cs=/[^a-zA-Z0-9-_]/g,ls=e=>{const t=e.trim().replace(cs,"_");return t.length>0?t.slice(0,80):void 0},us=e=>"string"==typeof e?ls(e):void 0,ds=xe("/");try{Xo=ds("worker_threads").Worker}catch(e){}var ps=Xo?function(e,t,r,n,o){var s=!1,i=new Xo(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,Xo.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}},fs=Uint8Array,hs=Uint16Array,ms=Int32Array,gs=new fs([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]),ys=new fs([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]),bs=new fs([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),vs=function(e,t){for(var r=new hs(31),n=0;n<31;++n)r[n]=t+=1<<e[n-1];var o=new ms(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}},ws=vs(gs,2),_s=ws.b,Is=ws.r;_s[28]=258,Is[258]=28;var Es,Ts=vs(ys,0),xs=Ts.b,Ss=Ts.r,As=new hs(32768);for(Ps=0;Ps<32768;++Ps)Es=(61680&(Es=(52428&(Es=(43690&Ps)>>1|(21845&Ps)<<1))>>2|(13107&Es)<<2))>>4|(3855&Es)<<4,As[Ps]=((65280&Es)>>8|(255&Es)<<8)>>1;var Cs=function(e,t,r){for(var n=e.length,o=0,s=new hs(t);o<n;++o)e[o]&&++s[e[o]-1];var i,a=new hs(t);for(o=1;o<t;++o)a[o]=a[o-1]+s[o-1]<<1;if(r){i=new hs(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[As[d]>>c]=l}else for(i=new hs(n),o=0;o<n;++o)e[o]&&(i[o]=As[a[e[o]-1]++]>>15-e[o]);return i},Rs=new fs(288);for(Ps=0;Ps<144;++Ps)Rs[Ps]=8;for(Ps=144;Ps<256;++Ps)Rs[Ps]=9;for(Ps=256;Ps<280;++Ps)Rs[Ps]=7;for(Ps=280;Ps<288;++Ps)Rs[Ps]=8;var Ps,Us=new fs(32);for(Ps=0;Ps<32;++Ps)Us[Ps]=5;var ks=Cs(Rs,9,0),Ls=Cs(Rs,9,1),Ds=Cs(Us,5,0),Os=Cs(Us,5,1),$s=function(e){for(var t=e[0],r=1;r<e.length;++r)e[r]>t&&(t=e[r]);return t},Ns=function(e,t,r){var n=t/8|0;return(e[n]|e[n+1]<<8)>>(7&t)&r},Bs=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(7&t)},js=function(e){return(e+7)/8|0},Ms=function(e,t,r){return(null==t||t<0)&&(t=0),(null==r||r>e.length)&&(r=e.length),new fs(e.subarray(t,r))},Hs=["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"],Fs=function(e,t,r){var n=new Error(t||Hs[e]);if(n.code=e,Error.captureStackTrace&&Error.captureStackTrace(n,Fs),!r)throw n;return n},Gs=function(e,t,r,n){var o=e.length,s=n?n.length:0;if(!o||t.f&&!t.l)return r||new fs(0);var i=!r,a=i||2!=t.i,c=t.i;i&&(r=new fs(3*o));var l=function(e){var t=r.length;if(e>t){var n=new fs(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=Ns(e,d,1);var b=Ns(e,d+1,3);if(d+=3,!b){var v=e[(P=js(d)+4)-4]|e[P-3]<<8,w=P+v;if(w>o){c&&Fs(0);break}a&&l(p+v),r.set(e.subarray(P,w),p),t.b=p+=v,t.p=d=8*w,t.f=u;continue}if(1==b)f=Ls,h=Os,m=9,g=5;else if(2==b){var _=Ns(e,d,31)+257,I=Ns(e,d+10,15)+4,E=_+Ns(e,d+5,31)+1;d+=14;for(var T=new fs(E),x=new fs(19),S=0;S<I;++S)x[bs[S]]=Ns(e,d+3*S,7);d+=3*I;var A=$s(x),C=(1<<A)-1,R=Cs(x,A,1);for(S=0;S<E;){var P,U=R[Ns(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+Ns(e,d,3),d+=2,k=T[S-1]):17==P?(L=3+Ns(e,d,7),d+=3):18==P&&(L=11+Ns(e,d,127),d+=7);L--;)T[S++]=k}}var D=T.subarray(0,_),O=T.subarray(_);m=$s(D),g=$s(O),f=Cs(D,m,1),h=Cs(O,g,1)}else Fs(1);if(d>y){c&&Fs(0);break}}a&&l(p+131072);for(var $=(1<<m)-1,N=(1<<g)-1,B=d;;B=d){var j=(k=f[Bs(e,d)&$])>>4;if((d+=15&k)>y){c&&Fs(0);break}if(k||Fs(2),j<256)r[p++]=j;else{if(256==j){B=d,f=null;break}var M=j-254;if(j>264){var H=gs[S=j-257];M=Ns(e,d,(1<<H)-1)+_s[S],d+=H}var F=h[Bs(e,d)&N],G=F>>4;if(F||Fs(3),d+=15&F,O=xs[G],G>3&&(H=ys[G],O+=Bs(e,d)&(1<<H)-1,d+=H),d>y){c&&Fs(0);break}a&&l(p+131072);var Y=p+M;if(p<O){var V=s-O,W=Math.min(O,Y);for(V+p<0&&Fs(3);p<W;++p)r[p]=n[V+p]}for(;p<Y;++p)r[p]=r[p-O]}}t.l=f,t.p=B,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?Ms(r,0,p):r.subarray(0,p)},Ys=function(e,t,r){r<<=7&t;var n=t/8|0;e[n]|=r,e[n+1]|=r>>8},Vs=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},Ws=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:Zs,l:0};if(1==o){var i=new fs(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 hs(p+1),h=zs(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 v=s[n].s;f[v]<t?m-=1<<t-f[v]++-1:++n}for(;n>=0&&m;--n){var w=s[n].s;f[w]==t&&(--f[w],++m)}h=t}return{t:new fs(f),l:h}},zs=function(e,t,r){return-1==e.s?Math.max(zs(e.l,t,r+1),zs(e.r,t,r+1)):t[e.s]=r},Ks=function(e){for(var t=e.length;t&&!e[--t];);for(var r=new hs(++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}},qs=function(e,t){for(var r=0,n=0;n<t.length;++n)r+=e[n]*t[n];return r},Js=function(e,t,r){var n=r.length,o=js(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)},Qs=function(e,t,r,n,o,s,i,a,c,l,u){Ys(t,u++,r),++o[256];for(var d=Ws(o,15),p=d.t,f=d.l,h=Ws(s,15),m=h.t,g=h.l,y=Ks(p),b=y.c,v=y.n,w=Ks(m),_=w.c,I=w.n,E=new hs(19),T=0;T<b.length;++T)++E[31&b[T]];for(T=0;T<_.length;++T)++E[31&_[T]];for(var x=Ws(E,7),S=x.t,A=x.l,C=19;C>4&&!S[bs[C-1]];--C);var R,P,U,k,L=l+5<<3,D=qs(o,Rs)+qs(s,Us)+i,O=qs(o,p)+qs(s,m)+i+14+3*C+qs(E,S)+2*E[16]+3*E[17]+7*E[18];if(c>=0&&L<=D&&L<=O)return Js(t,u,e.subarray(c,c+l));if(Ys(t,u,1+(O<D)),u+=2,O<D){R=Cs(p,f,0),P=p,U=Cs(m,g,0),k=m;var $=Cs(S,A,0);for(Ys(t,u,v-257),Ys(t,u+5,I-1),Ys(t,u+10,C-4),u+=14,T=0;T<C;++T)Ys(t,u+3*T,S[bs[T]]);u+=3*C;for(var N=[b,_],B=0;B<2;++B){var j=N[B];for(T=0;T<j.length;++T){var M=31&j[T];Ys(t,u,$[M]),u+=S[M],M>15&&(Ys(t,u,j[T]>>5&127),u+=j[T]>>12)}}}else R=ks,P=Rs,U=Ds,k=Us;for(T=0;T<a;++T){var H=n[T];if(H>255){Vs(t,u,R[257+(M=H>>18&31)]),u+=P[M+257],M>7&&(Ys(t,u,H>>23&31),u+=gs[M]);var F=31&H;Vs(t,u,U[F]),u+=k[F],F>3&&(Vs(t,u,H>>5&8191),u+=ys[F])}else Vs(t,u,R[H]),u+=P[H]}return Vs(t,u,R[256]),u+P[256]},Xs=new ms([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Zs=new fs(0),ei=function(e,t,r,n,o,s){var i=s.z||e.length,a=new fs(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=Xs[t-1],p=d>>13,f=8191&d,h=(1<<r)-1,m=s.p||new hs(32768),g=s.h||new hs(h+1),y=Math.ceil(r/3),b=2*y,v=function(t){return(e[t]^e[t+1]<<y^e[t+2]<<b)&h},w=new ms(25e3),_=new hs(288),I=new hs(32),E=0,T=0,x=s.i||0,S=0,A=s.w||0,C=0;x+2<i;++x){var R=v(x),P=32767&x,U=g[R];if(m[P]=U,g[R]=P,A<=x){var k=i-x;if((E>7e3||S>24576)&&(k>423||!l)){u=Qs(e,c,0,w,_,I,T,S,C,x-C,u),S=E=T=0,C=x;for(var L=0;L<286;++L)_[L]=0;for(L=0;L<30;++L)I[L]=0}var D=2,O=0,$=f,N=P-U&32767;if(k>2&&R==v(x-N))for(var B=Math.min(p,k)-1,j=Math.min(32767,x),M=Math.min(258,k);N<=j&&--$&&P!=U;){if(e[x+D]==e[x+D-N]){for(var H=0;H<M&&e[x+H]==e[x+H-N];++H);if(H>D){if(D=H,O=N,H>B)break;var F=Math.min(N,H-2),G=0;for(L=0;L<F;++L){var Y=x-N+L&32767,V=Y-m[Y]&32767;V>G&&(G=V,U=Y)}}}N+=(P=U)-(U=m[P])&32767}if(O){w[S++]=268435456|Is[D]<<18|Ss[O];var W=31&Is[D],z=31&Ss[O];T+=gs[W]+ys[z],++_[257+W],++I[z],A=x+D,++E}else w[S++]=e[x],++_[e[x]]}}for(x=Math.max(x,A);x<i;++x)w[S++]=e[x],++_[e[x]];u=Qs(e,c,l,w,_,I,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=Js(c,u+1,e.subarray(x,K))}s.i=i}return Ms(a,0,n+js(u)+o)},ti=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}(),ri=function(e,t,r,n,o){if(!o&&(o={l:1},t.dictionary)){var s=t.dictionary.subarray(-32768),i=new fs(s.length+e.length);i.set(s),i.set(e,s.length),e=i,o.w=s.length}return ei(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)},ni=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},oi=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},si=[],ii=function(){return[fs,hs,ms,gs,ys,bs,_s,xs,Ls,Os,As,Hs,Cs,$s,Ns,Bs,js,Ms,Fs,Gs,gi,ci,li]},ai=function(){return[fs,hs,ms,gs,ys,bs,Is,Ss,ks,Rs,Ds,Us,As,Xs,Zs,Cs,Ys,Vs,Ws,zs,Ks,qs,Js,Qs,js,Ms,ei,ri,mi,ci]},ci=function(e){return postMessage(e,[e.buffer])},li=function(e){return e&&{out:e.size&&new fs(e.size),dictionary:e.dictionary}},ui=function(e,t,r,n,o,s){var i=function(e,t,r,n){if(!si[r]){for(var o="",s={},i=e.length-1,a=0;a<i;++a)o=oi(e[a],o,s);si[r]={c:oi(e[i],o,s),e:s}}var c=ni({},si[r].e);return ps(si[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()}},di=function(e,t){return e[t]|e[t+1]<<8},pi=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},fi=function(e,t){return pi(e,t)+4294967296*pi(e,t+4)},hi=function(e,t,r){for(;r;++t)e[t]=r,r>>>=8};function mi(e,t){return ri(e,t||{},0,0)}function gi(e,t){return Gs(e,{i:2},t&&t.out,t&&t.dictionary)}var yi=function(e,t,r,n){for(var o in e){var s=e[o],i=t+o,a=n;Array.isArray(s)&&(a=ni(n,s[1]),s=s[0]),s instanceof fs?r[i]=[s,a]:(r[i+="/"]=[new fs(0),a],yi(s,i,r,n))}},bi="undefined"!=typeof TextEncoder&&new TextEncoder,vi="undefined"!=typeof TextDecoder&&new TextDecoder;try{vi.decode(Zs,{stream:!0})}catch(e){}function wi(e,t){if(bi)return bi.encode(e);for(var r=e.length,n=new fs(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 fs(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 Ms(n,0,o)}var _i=function(e){var t=0;if(e)for(var r in e){var n=e[r].length;n>65535&&Fs(9),t+=n+4}return t},Ii=function(e,t,r,n,o,s,i,a){var c=n.length,l=r.extra,u=a&&a.length,d=_i(l);hi(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)&&Fs(10),hi(e,t,f<<25|p.getMonth()+1<<21|p.getDate()<<16|p.getHours()<<11|p.getMinutes()<<5|p.getSeconds()>>1),t+=4,-1!=s&&(hi(e,t,r.crc),hi(e,t+4,s<0?-s-2:s),hi(e,t+8,r.size)),hi(e,t+12,c),hi(e,t+14,d),t+=16,null!=i&&(hi(e,t,u),hi(e,t+6,r.attrs),hi(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;hi(e,t,+h),hi(e,t+2,g),e.set(m,t+4),t+=4+g}return u&&(e.set(a,t),t+=u),t},Ei="function"==typeof queueMicrotask?queueMicrotask:"function"==typeof setTimeout?setTimeout:function(e){e()};function Ti(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 xi=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 Si(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 Ai(e){switch(7&Si(e)){case 0:return Si(e),!0;case 1:return e.next(8),!0;case 2:const t=Si(e);return e.next(t),!0;case 5:return e.next(4),!0}return!1}function Ci(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!Ti(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!Ti(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 xi(e,t);let n=0;for(;;){if(!Ai(r)&&!r.hasError())return!1;if(r.hasError())break;n++}return n>0}(e,s))}var Ri=[/^\/$/,/^\*+$/,/^[0-9]+$/],Pi=["/artifact/","https://","http://","*********"],Ui=new Set(["sha1","_sha1","pageref","downloadsPath","tracesDir","pageId"]);function ki({sensitiveValues:e,str:t}){return e.reduce((e,t)=>e.replaceAll(t,"[REDACTED]"),t)}function Li({sensitiveValues:e,value:t}){return"string"==typeof t?ki({sensitiveValues:e,str:t}):Array.isArray(t)?t.map(t=>Li({sensitiveValues:e,value:t})):function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(t)?Oi({obj:t,sensitiveValues:e}):t}function Di(e){return!!Ui.has(e)||e.toLowerCase().endsWith("sha1")}function Oi({obj:e,sensitiveValues:t}){return Object.fromEntries(Object.entries(e).map(([e,r])=>[e,Di(e)?r:Li({sensitiveValues:t,value:r})]))}function $i({error:e,sensitiveValues:t}){return e?{...e,message:ki({sensitiveValues:t,str:e.message})}:void 0}function Ni({content:e,sensitiveValues:t}){const r=new N,n=new B,o=ki({sensitiveValues:t,str:r.decode(e)});return n.encode(o)}var Bi=$(function(e,t,r){r||(r=t,t={}),"function"!=typeof r&&Fs(7);var n=[],o=function(){for(var e=0;e<n.length;++e)n[e]()},s={},i=function(e,t){Ei(function(){r(e,t)})};Ei(function(){i=r});for(var a=e.length-22;101010256!=pi(e,a);--a)if(!a||e.length-a>65558)return i(Fs(13,0,1),null),o;var c=di(e,a+8);if(c){var l=c,u=pi(e,a+16),d=4294967295==u||65535==l;if(d){var p=pi(e,a-12);(d=101075792==pi(e,p))&&(l=c=pi(e,p+32),u=pi(e,p+48))}for(var f=t&&t.filter,h=function(t){var r=function(e,t,r){var n=di(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(vi)return vi.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:Ms(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&&Fs(8),s}(e.subarray(t+46,t+46+n),!(2048&di(e,t+8))),s=t+46+n,i=pi(e,t+20),a=r&&4294967295==i?function(e,t){for(;1!=di(e,t);t+=4+di(e,t+2));return[fi(e,t+12),fi(e,t+4),fi(e,t+20)]}(e,s):[i,pi(e,t+24),pi(e,t+42)],c=a[0],l=a[1],u=a[2];return[di(e,t+10),c,l,o,s+di(e,t+30)+di(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+di(e,t+26)+di(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 v=e.subarray(y,y+l);if(p<524288||l>.8*p)try{b(null,gi(v,{out:new fs(p)}))}catch(e){b(e,null)}else n.push(function(e,t,r){return r||(r=t,t={}),"function"!=typeof r&&Fs(7),ui(e,t,[ii],function(e){return ci(gi(e.data[0],li(e.data[1])))},1,r)}(v,{size:p},b))}else b(Fs(14,"unknown compression type "+a,1),null);else b(null,Ms(e,y,y+l));else b(null,null)},m=0;m<l;++m)h()}else i(null,{});return o}),ji=$(function(e,t,r){r||(r=t,t={}),"function"!=typeof r&&Fs(7);var n={};yi(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){Ei(function(){r(e,t)})};Ei(function(){p=r});var f=function(){var e=new fs(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;Ii(e,a,o,o.f,o.u,s);var u=30+o.f.length+_i(o.extra),d=a+u;e.set(o.c,d),Ii(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){hi(e,t,101010256),hi(e,t+8,r),hi(e,t+10,r),hi(e,t+12,n),hi(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=ti[255&r^t[n]]^r>>>8;e=r},d:function(){return~e}}}(),g=c.length;m.p(c);var y=wi(t),b=y.length,v=h.comment,w=v&&wi(v),_=w&&w.length,I=_i(h.extra),E=0==h.level?0:8,T=function(r,n){if(r)d(),p(r,null);else{var o=n.length;l[e]=ni(h,{size:g,crc:m.d(),c:n,f:y,m:w,u:b!=t.length||w&&v.length!=_,compression:E}),i+=30+b+I+o,a+=76+2*(b+I)+(_||0)+o,--s||f()}};if(b>65535&&T(Fs(11,0,1),null),E)if(g<16e4)try{T(null,mi(c,h))}catch(e){T(e,null)}else u.push(function(e,t,r){return r||(r=t,t={}),"function"!=typeof r&&Fs(7),ui(e,t,[ai],function(e){return ci(mi(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 Mi({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 N,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 F(e).with({type:"console"},e=>({...e,args:e.args?.map(e=>({...e,preview:ki({sensitiveValues:t,str:e.preview}),value:Li({sensitiveValues:t,value:e.value})})),text:ki({sensitiveValues:t,str:e.text})})).with({type:"before"},e=>({...e,params:Oi({obj:e.params,sensitiveValues:t}),title:e.title?ki({sensitiveValues:t,str:e.title}):void 0})).with({type:"after"},e=>({...e,error:$i({error:e.error,sensitiveValues:t}),result:void 0!==e.result?Li({sensitiveValues:t,value:e.result}):void 0})).with({type:"action"},e=>({...e,error:$i({error:e.error,sensitiveValues:t}),params:Oi({obj:e.params,sensitiveValues:t}),result:void 0!==e.result?Li({sensitiveValues:t,value:e.result}):void 0,title:e.title?ki({sensitiveValues:t,str:e.title}):void 0})).with({type:"event"},e=>({...e,params:Oi({obj:e.params,sensitiveValues:t})})).with({type:"stdout"},{type:"stderr"},e=>({...e,text:void 0!==e.text?ki({sensitiveValues:t,str:e.text}):void 0})).with({type:"error"},e=>({...e,message:ki({sensitiveValues:t,str:e.message})})).with({type:"log"},e=>({...e,message:ki({sensitiveValues:t,str:e.message})})).with({type:"context-options"},e=>({...e,options:Oi({obj:e.options,sensitiveValues:t}),title:e.title?ki({sensitiveValues:t,str:e.title}):void 0})).with({type:"frame-snapshot"},e=>({...e,snapshot:Oi({obj:e.snapshot,sensitiveValues:t})})).with({type:"resource-snapshot"},e=>({...e,snapshot:Oi({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 ki({sensitiveValues:t,str:e})}});return n.encode(o.join("\n"))}({content:e,sensitiveValues:r}):n.endsWith(".html")||n.endsWith(".dat")||n.endsWith(".json")?Ni({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!")}(b(e));const r=x(e,"r"),n=Buffer.alloc(515),o=S(r,n,0,515,0);return A(r),Ci(n,o,t)}return Ci(e,void 0!==t?.size?t.size:e.length,t)}(Buffer.from(e),{size:e.length})}(e)?e:Ni({content:e,sensitiveValues:t})}({content:e,sensitiveValues:r}):e}function Hi(e=process.cwd()){let t=n(e);for(;;){const e=Fi(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=Gi(t);let r=!1,i=t;for(;;){const e=s(i,"node_modules"),t=s(e,n);if(y(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 Fi(e){const t=s(e,"package.json");let r;try{r=_(t,"utf-8")}catch{return}try{return JSON.parse(r)}catch{return}}function Gi(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(y(s(r,n)))return e;const e=o(r);if(e===r)return;r=e}}function Yi(e){if("npm"===e||"pnpm"===e)return["npx","playwright"];if("yarn"===e)return["yarn","playwright"];throw new Error("Package manager not supported")}var Vi=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Wi=e=>(e instanceof Error?e.message:String(e)).slice(0,400),zi=({outputDir:e,representativeTest:t})=>{const r=["test","--trace=on","--workers=1","--retries=0","--reporter=list","--output",e];return t.filePath&&r.push(t.filePath),t.testTitle?r.push("--grep",Vi(t.testTitle)):t.testIdentifier&&r.push("--grep",`^${Vi(t.testIdentifier)}$`),r},Ki=async e=>{const t=await ee(e,{withFileTypes:!0}),n=[];for(const o of t){const t=r.join(e,o.name);if(o.isDirectory())n.push(...await Ki(t));else if(o.isFile()&&"trace.zip"===o.name){const e=await te(t);n.push({path:t,mtimeMs:e.mtimeMs})}}return n},qi=async e=>{try{const t=await ee(e,{withFileTypes:!0});for(const n of t){const t=r.join(e,n.name);n.isDirectory()?await qi(t):n.isFile()&&".last-run.json"===n.name&&await re(t,{force:!0})}}catch{}},{zSuiteAutoHealReport:Ji,zRepresentativeTest:Qi}=function(e){const t=e.enum(ss),r=["Classification of the root cause:","",`- test: ${as("test")}`,`- bug: ${as("bug")}`,`- flake: ${as("flake")}`,`- ui_change: ${as("ui_change")}`,`- other: ${as("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). Include file:line references (e.g., `src/tests/login.spec.ts:42`) to back up your claim."),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). Include file:line references (e.g., `src/tests/login.spec.ts:42`) showing where changes were made."),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). Include file:line references (e.g., `src/tests/login.spec.ts:42`) pointing to the problematic code."),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}}(ge),Xi=({authHeader:e,diffTracker:t,orgId:n,runId:o,workingDir:s})=>j({name:"auto-heal-report",tools:[M("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:ge.string().min(1).describe("Issue identifier for deterministic output paths and storage key naming."),proofId:ge.string().min(1).optional().describe("Optional id for deterministic proof naming and deduplication."),representativeTest:Qi.optional().default({}),testCaseId:ge.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=ge.string().min(1).parse(t),u=null==i?void 0:ge.string().min(1).parse(i),d=null==c?void 0:ge.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=Hi(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=>ls(e)??"issue")(t),d=(({proofId:e,testCaseId:t})=>us(t)??us(e))({testCaseId:a,proofId:o}),p=r.join(c,".stably","autoheal-proof",u,d??"issue"),[f,...m]=Yi(l.packageManager),g=[...m,...zi({outputDir:p,representativeTest:s})];try{await re(p,{force:!0,recursive:!0}),await J(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=h(t,e,{cwd:r,env:n??process.env,stdio:["ignore","ignore","pipe"],shell:"win32"===process.platform});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:f,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."};const d=await(async e=>{const t=await Ki(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:`No trace.zip was produced${0!==r?` (test exit code ${r??"unknown"})`:""}: ${l.trim().slice(0,280)}`.trim()};await qi(p);const{traceBucketPath:m,uploadUrl:y,sensitiveValues:b}=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:rn(),headers:to(s),path:{runId:i}},(c.client??Yr).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=io.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=w(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||Ri.some(t=>t.test(e))||Pi.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 Bi(new Uint8Array(t)),s=Object.entries(o),i=await Promise.all(s.map(async([e,t])=>[e,await Mi({content:t,filename:e,sensitiveValues:n})])),a=Object.fromEntries(i);return ji(a)}({traceBuffer:new Uint8Array(Buffer.concat(r)),sensitiveValues:t})}({tracePath:d,sensitiveValues:b});try{await oo({body:v,contentType:"application/zip",uploadUrl:y,errorContext:"trace"})}catch(e){return{status:"upload_failed",representativeTest:s,error:Wi(e)}}return{status:"captured",representativeTest:s,storage:m}}catch(e){return{status:"capture_failed",representativeTest:s,error:Wi(e)}}})({authHeader:e,issueId:l,orgId:n,proofId:u,representativeTest:Qi.parse(a??{}),runId:o,testCaseId:d,workingDir:s}),f="string"==typeof d?{testCaseId:d,...p}:p;return{content:[{text:JSON.stringify(f),type:"text"}]}}),M("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:rn(),headers:to(t),path:{runId:n}},(s.client??Yr).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 ao({authHeader:e,contentType:"text/plain",orgId:n,runId:o});await oo({body:s,contentType:"text/plain",uploadUrl:r,errorContext:"diff"}),await co({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"}),Zi=({onComplete:e,onRestartRequested:t})=>j(e?{name:"session-control",tools:[M("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:ge.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:[M("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 restart SCHEDULED for end of this turn.\n\nCRITICAL: END YOUR TURN NOW. Do not call any more tools.\nThe restart only happens AFTER your turn completes.\n\nAny tools called in this turn will use the OLD servers and fail.\n\nThe system will automatically continue with "[SYSTEM] MCP servers were restarted successfully" once ready.'}]})))]}),ea=ge.object({commentUrl:ge.string()}),ta=({prContext:e,authHeader:t,orgId:r,onReportPosted:n})=>j({name:"create-report",tools:[M("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:ge.string().describe("A summary of the tests created. Include what features/flows are tested and any important notes."),filesCreated:ge.array(ge.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:[];Vn.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",Kr).toString(),a={Authorization:e,"Content-Type":"application/json"};t&&(a["x-stably-org-id"]=t),Vn.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 Vn.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=ea.parse(await c.json());return Vn.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),Vn.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 Vn.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}}})]}),ra=["QUEUED","RUNNING","PASSED","FAILED","TIMEDOUT","CANCELLED","INTERRUPTED"],na=["LOCAL","CI","WEB"],oa=["MANUAL","SCHEDULED","UI","API","GITHUB_ACTION","SUITE_RUN"],sa=({authHeader:e,orgId:t,projectId:r})=>j({name:"run-history",tools:[M("list_runs",'List test runs with optional filters for the current project.\nUse this to find runs with autoheal status on specific branches.\n\nCommon use cases:\n- Find failed runs on the current branch: { "branch": "feature-x", "status": "FAILED", "limit": 10 }\n- Find failed runs on master/main: { "branch": "master", "status": "FAILED", "limit": 10 }\n\nReturns an array of runs with their runId, status, autoHealStatus, branch, and timestamps.',{branch:ge.string().optional().describe("Filter by branch name"),status:ge.enum(ra).optional().describe("Filter by status: QUEUED|RUNNING|PASSED|FAILED|TIMEDOUT|CANCELLED|INTERRUPTED"),limit:ge.number().min(1).max(100).optional().describe("Max results (1-100, default 20)"),source:ge.enum(na).optional().describe("Filter by source: LOCAL|CI|WEB"),trigger:ge.enum(oa).optional().describe("Filter by trigger: MANUAL|SCHEDULED|UI|API|GITHUB_ACTION|SUITE_RUN"),suite:ge.string().optional().describe("Filter by suite name"),after:ge.string().optional().describe("Pagination: return runs after this runId"),before:ge.string().optional().describe("Pagination: return runs before this runId")},async({branch:n,status:o,limit:s,source:i,trigger:a,suite:c,after:l,before:u})=>{const d="string"==typeof n?n:void 0,p="string"==typeof o?o:void 0,f="number"==typeof s?s:void 0,h="string"==typeof i?i:void 0,m="string"==typeof a?a:void 0,g="string"==typeof c?c:void 0,y="string"==typeof l?l:void 0,b="string"==typeof u?u:void 0;Vn.info("[run-history] list_runs called",{branch:d,status:p,limit:f});try{const n=await Vr({auth:e,client:rn(),headers:to(t),query:{projectId:r,branchName:d,status:p,limit:f,source:h,trigger:m,suiteName:g,afterRunId:y,beforeRunId:b}});if(n.error||!n.data){const e=n.response?`API error: ${n.response.status}`:`API error: ${String(n.error)}`;return Vn.error("[run-history] list_runs failed",{error:e}),{content:[{type:"text",text:`Error: ${e}`}],isError:!0}}return Vn.info("[run-history] list_runs success",{runCount:n.data.runs?.length??0,hasMore:n.data.hasMore}),{content:[{type:"text",text:JSON.stringify(n.data,null,2)}]}}catch(e){const t=e instanceof Error?e.message:String(e);return Vn.error("[run-history] list_runs exception",{error:t}),{content:[{type:"text",text:`Error: ${t}`}],isError:!0}}}),M("view_run",'Get detailed information about a specific run including issues and test results.\nUse this after list_runs to examine runs where autoHealStatus is "COMPLETED".\n\nThe response includes:\n- Run metadata (status, branch, timestamps)\n- Issues array with result ("fixed"/"unfixed"), rootCause, and relatedTestIdentifiers\n- Test results with their outcomes\n\nUse this to determine which tests were previously fixed and why.',{runId:ge.string().min(1).describe("The run ID to view (required)")},async({runId:r})=>{const n="string"==typeof r?r:String(r);Vn.info("[run-history] view_run called",{runId:n});try{const r=await Wr({auth:e,client:rn(),headers:to(t),path:{runId:n},query:{detail:"full"}});if(r.error||!r.data){const e=r.response?404===r.response.status?`Run "${n}" not found`:`API error: ${r.response.status}`:`API error: ${String(r.error)}`;return Vn.error("[run-history] view_run failed",{error:e,runId:n}),{content:[{type:"text",text:`Error: ${e}`}],isError:!0}}return Vn.info("[run-history] view_run success",{runId:n}),{content:[{type:"text",text:JSON.stringify(r.data,null,2)}]}}catch(e){const t=e instanceof Error?e.message:String(e);return Vn.error("[run-history] view_run exception",{error:t,runId:n}),{content:[{type:"text",text:`Error: ${t}`}],isError:!0}}})]}),ia=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]"),aa=(e,t)=>({message:ia(e),status:t?.status,statusText:t?.statusText}),ca=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"]),la=async({authHeader:e,mode:t,maxTurnsOverride:r})=>{const n=rn();Vn.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??Yr).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 Vn.warn("Subagent definitions fetch failed: unauthorized (401)"),await vn(),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 Vn.debug("Subagent definitions fetch failed: forbidden (403)"),new Error("Your organization does not have an active subscription. Manage your subscription at https://app.stably.ai or contact your organization admin.");if(o.error)throw Vn.warn("Subagent definitions fetch failed",{error:o.error}),new Error("Failed to fetch subagent definitions. Please check your network connection and try again. If this persists, run `stably login` to re-authenticate.");const{subagents:i}=o.data;return Vn.debug("Subagent definitions received",{count:Object.keys(i).length}),i},ua=r.dirname(R(import.meta.url)),da=r.join(".claude-plugin","plugin.json"),pa=[r.join("packages","agent-plugin","stably-plugin"),r.join("agent-plugin","stably-plugin")];function fa(e){return y(r.join(e,da))}var{zStablyYaml:ha}=function(e){const t=e.object({cron:e.string(),stablyTestArgs:e.string().optional(),timezone:e.string().optional(),command:e.string().optional(),autofix:e.boolean().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(),maxBudgetUsd:e.number().positive().optional()}),n=e.object({fix:r.optional()}),o=e.object({setupScript:e.string().optional()});return{zStablyYaml:e.object({schedules:e.record(e.string(),t).optional(),agent:n.optional(),cloud:o.optional()}),zAgentConfig:n,zAgentFixConfig:r,zScheduleEntry:t,zCloudConfig:o}}(de),ma=async(e,t)=>{try{const r=await un(e,t);if(!r)return void Vn.debug(`No ${t} found`);const n=await q(r,"utf-8");if(!n.trim())return;return n.length>1e4?(Vn.warn(`${t} exceeds max length (${n.length} > 10000), truncating`,{path:r}),{content:n.slice(0,1e4),path:r}):(Vn.debug(`Loaded ${t} rules`,{path:r,contentLength:n.length}),{content:n,path:r})}catch(e){return void Vn.warn(`Failed to read ${t}`,{error:e})}},ga=de.object({verdict:de.enum(["PASS","FAIL","INCONCLUSIVE"]),steps:de.array(de.string()).min(1),reason:de.string().nullable(),evidence:de.array(de.string())}).superRefine((e,t)=>{"PASS"===e.verdict||e.reason&&0!==e.reason.trim().length||t.addIssue({code:de.ZodIssueCode.custom,path:["reason"],message:"reason is required for FAIL and INCONCLUSIVE verdicts"})}),ya=/\bmcp__playwright-mcp__[a-z0-9_]+\b/gi,ba=/\.playwright-mcp(?:\/[^\s"'`)\]]*)?/gi,va=/\bplaywright[\s_-]?mcp\b/gi;function wa(e){return e.replace(ya,"browser_tool").replace(ba,"verification-artifact").replace(va,"browser automation")}function _a(e){return{...e,steps:e.steps.map(e=>wa(e)),reason:e.reason?wa(e.reason):null,evidence:e.evidence.map(e=>wa(e))}}function Ia(e){const t=e.matchAll(/```verdict\s*\r?\n([\s\S]*?)\r?\n```/g);let r=null;for(const e of t)try{const t=JSON.parse(e[1]??"");r=ga.parse(t)}catch{}return r}var Ea=["Bash","Read","Write","Edit","Glob","Grep","Task","Skill"],Ta=["Task","mcp__playwright-test","Skill"],xa=["Bash","Read","Write","Edit","Glob","Grep","mcp__session-control"],Sa=e=>{if("EPIPE"!==e.code)throw e},Aa="__main__",Ca=[3e3,5173,4173,8080,4200,8e3],Ra=/\b(TEST_EMAIL|TEST_PASSWORD|auth|authentication|credentials|login|log in|sign in)\b/i,Pa=/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/i,Ua=/playwright[\s_-]?mcp/i,ka=e=>"mcp__auto-heal-report__generate-report"===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)}))}async function Da(e){return new Promise(t=>{const r=new V.Socket;let n=!1;const o=e=>{n||(n=!0,r.destroy(),t(e))};r.setTimeout(700),r.once("connect",()=>o(!0)),r.once("timeout",()=>o(!1)),r.once("error",()=>o(!1)),r.connect(e,"127.0.0.1")})}var Oa=async e=>{if("single"===e.mode){const t=Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt;Vn.initSession(t||"create-from-diff")}else if("verify"===e.mode){const t=Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt;Vn.initSession(t||"verify")}else"fix"===e.mode&&Vn.initSession(`fix-${e.runId}`);Vn.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),Vn.debug("Checking authentication");const a=await qn({autoLogin:"chat"===e.mode||"init"===e.mode}),c=Qn(a);Vn.debug("Authentication resolved",{authType:a.type});const l="oauth"===a.type?a.auth.context.orgId:void 0,u=r.resolve(process.cwd()),d="fix"!==e.mode,p=r.join(u,".env"),f=d&&g.existsSync(p)&&g.statSync(p).isFile(),h=f?t(g.readFileSync(p,"utf8")):{};Vn.debug("Environment file",{path:p,exists:f,variableCount:Object.keys(h).length});const m="chat"!==e.mode&&"init"!==e.mode,b="chat"===e.mode,v="single"===e.mode,w="verify"===e.mode,_=v||w;let I=new jo;const E="chat"===e.mode?e.getHelpText:void 0,T="verify"===e.mode?(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt).trim():"";let x="verify"===e.mode?e.url?.trim()||function(e){const t=Array.isArray(e)?e.join(" "):e,r=e=>e.replace(/[),.;!?]+$/,""),n=e=>{const t=r(e);try{return new URL(t).toString()}catch{return}},o=t.match(/https?:\/\/[^\s"'`<>]+/i);if(o)return n(o[0]);const s=t.match(/(?<!@)\b(?:localhost|(?:\d{1,3}\.){3}\d{1,3}|(?:[a-z0-9-]+\.)+[a-z]{2,63})(?::\d{2,5})?(?:\/[^\s"'`<>]*)?/i);if(!s)return;const i=r(s[0]),a=i.split("/")[0]??i,c=a.split(":")[0]?.toLowerCase()??"",l=c.includes(".")?c.split(".").at(-1)??"":"";return new Set(["ts","tsx","js","jsx","md","json","yaml","yml","txt","css"]).has(l)?void 0:n(`${"localhost"===c||"127.0.0.1"===c?"http":"https"}://${i}`)}(e.prompt):void 0;if("verify"===e.mode&&!e.url&&x&&Vn.info("[verify] Using URL extracted from prompt",{url:x}),"verify"!==e.mode||x||(x=await async function(){for(const e of Ca)if(await Da(e))return`http://localhost:${e}`}(),x?Vn.info("[verify] Detected local application URL",{url:x}):Vn.info("[verify] No common localhost dev server detected")),"verify"===e.mode&&!1!==e.interactive){const e=await async function({envFilePath:e,envFromFile:t,initialUrl:n,verifyPromptText:o,workingDir:s}){if(!process.stdin.isTTY||!process.stdout.isTTY)return{resolvedUrl:n};const i=r.join(s,"STABLY.md"),a=g.existsSync(i),c=a?await g.promises.readFile(i,"utf8").catch(()=>{}):void 0;let l=n?.trim()||void 0;const u=!l,d=(({envEmail:e,envPassword:t,promptIncludesEmail:r,stablyMdContent:n})=>!Boolean(e?.trim()&&t?.trim())&&!r&&!(e=>!!e&&Ra.test(e))(n))({envEmail:process.env.TEST_EMAIL??t.TEST_EMAIL,envPassword:process.env.TEST_PASSWORD??t.TEST_PASSWORD,promptIncludesEmail:Pa.test(o),stablyMdContent:c}),p=!a;if(!u&&!d&&!p)return{resolvedUrl:l};const f=W({input:process.stdin,output:process.stdout}),h=async(e,t=!0)=>{const r=t?" [Y/n] ":" [y/N] ",n=(await f.question(`${e}${r}`)).trim().toLowerCase();return n?"y"===n||"yes"===n:t},m=async(r,n)=>{const o=g.existsSync(e)?await g.promises.readFile(e,"utf8"):"",s=new RegExp(`^${i=r,i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}=.*$`,"m");var i;const a=`${r}=${(e=>/^[A-Za-z0-9_./:@-]+$/.test(e)?e:`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)(n)}`,c=s.test(o)?o.replace(s,a):`${o}${o&&!o.endsWith("\n")?"\n":""}${a}\n`;await g.promises.writeFile(e,c,"utf8"),t[r]=n};try{if(u){const e=(await f.question("Starting URL (optional, Enter to auto-infer): ")).trim();e&&(l=e)}if(d&&await h("No TEST_EMAIL/TEST_PASSWORD found in .env and no auth guidance found in STABLY.md. Configure credentials in .env now?",!0)){const e=(await f.question("TEST_EMAIL: ")).trim(),t=(await f.question("TEST_PASSWORD: ")).trim();e&&t&&(await m("TEST_EMAIL",e),await m("TEST_PASSWORD",t),process.env.TEST_EMAIL||(process.env.TEST_EMAIL=e),process.env.TEST_PASSWORD||(process.env.TEST_PASSWORD=t))}if(p&&await h("No STABLY.md found. Create one at repository root for project instructions?",!0)){const e=["# STABLY.md","","Project instructions for Stably agent runs.","","## Verify Notes","- Keep verification scope to requested behavior only.","- Use TEST_EMAIL and TEST_PASSWORD env vars for authenticated flows.","","## Special Instructions","- Add project-specific constraints here.",""].join("\n");await g.promises.writeFile(i,e,"utf8");const t=(await f.question("Special verify instruction to append to STABLY.md (optional): ")).trim();if(t){const e=await g.promises.readFile(i,"utf8"),r=/(^|\n)## Special Instructions\s*$/m.test(e)?`${e}${e.endsWith("\n")?"":"\n"}- ${t}\n`:`${e}${e.endsWith("\n")?"":"\n"}\n## Special Instructions\n- ${t}\n`;await g.promises.writeFile(i,r,"utf8")}}return{resolvedUrl:l}}finally{f.close()}}({envFilePath:p,envFromFile:h,initialUrl:x,verifyPromptText:T,workingDir:u});x=e.resolvedUrl?.trim()||x}"verify"!==e.mode||x||Vn.warn("No verify URL provided and no local app detected on common ports. The agent will try to infer a URL from code/config.");const S={log:[],promptDisplay:F(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:"single"},e=>{const t=(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt)?.trim();return t||"Creating tests from PR/branch changes"}).with({mode:"verify"},e=>{const t=(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt)?.trim();return t||"Verifying application"}).exhaustive(),status:"running"};let A,C,R,P,U=m,k=!1,L=!1,D=0,O=0,$=!1;const N=[];let B,j,M=[],Y=!1,V=!1,K=0;const J=new Map;let Q=null,X=!1,Z=!1;const ee=Date.now();let te,re="fix"===e.mode?{suiteId:e.runId,phase:"initializing",totalTests:null,fixedTests:0,failedTests:0,currentTestDescription:null,lastTestDescription:null,startedAt:ee,endedAt:null,isError:!1,updatedAt:ee,recentActivity:[],workers:[{id:Aa,testDescription:"Orchestrator",workerType:"main",status:"running",summary:null,startedAt:ee,endedAt:null,activity:[]}]}:null;const ne=new Set,oe=(e,t)=>{if(!re)return;const r=re.workers.map(r=>{if(r.id!==e)return r;const n=[...r.activity,{...t,timestamp:Date.now()}].slice(-15);return{...r,activity:n}});ae({workers:r})},se=e=>{if(!re)return;const t=[...re.recentActivity,{...e,timestamp:Date.now()}].slice(-10);ae({recentActivity:t})},ie=e=>(re?.workers??[]).map(t=>t.id===Aa?{...t,status:e?"failed":"succeeded",endedAt:t.endedAt??Date.now()}:"running"===t.status?{...t,status:"failed",endedAt:Date.now()}:t),ae=e=>{re&&!te?.isClosed&&(re={...re,...e,updatedAt:Date.now()},te?.sendProgress(re))},ce=async t=>{if("fix"===e.mode){if("STARTED"===t){if(X)return;X=!0}else{if(Z)return;Z=!0}try{await(async({authHeader:e,orgId:t,runId:r,status:n})=>{const o=await(s={auth:e,body:{status:n},client:rn(),headers:to(t),path:{runId:r}},(s.client??Yr).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{}}},le=Date.now();let ue,de=null;const pe=e=>{de&&!ue?.isClosed&&(de={...de,...e,updatedAt:Date.now()},ue?.sendProgress(de))},fe=e=>{if(!de)return;const t=[...de.recentActivity,{...e,timestamp:Date.now()}].slice(-10);pe({recentActivity:t})};if(_||"fix"===e.mode)try{const t=new URL("/internal/v1/cli/progress",Kr).toString(),r={Authorization:c,"Content-Type":"application/json"};l&&(r["x-stably-org-id"]=l);const n="single"===e.mode?"create":"verify"===e.mode?"verify":"fix",o=await fetch(t,{method:"POST",headers:r,body:JSON.stringify({mode:n,projectId:Jn(a),agentId:G.randomUUID(),..."fix"===e.mode?{playwrightSuiteRunId:e.runId}:{}}),signal:AbortSignal.timeout(1e4)});if(o.ok){const{sessionId:t}=await o.json();if(_){const r="single"===e.mode||"verify"===e.mode?Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt:null,n=Mo(u);de={sessionId:t,phase:"initializing",startedAt:le,endedAt:null,isError:!1,updatedAt:le,currentActivity:null,filesCreated:[],recentActivity:[],prompt:r||null,environment:{gitBranch:n?.branch??null,workingDirectory:u,nodeVersion:process.version,cliVersion:zr}},ue=new uo({authHeader:c,orgId:l,sessionId:t,onUserMessage:e=>{I&&(Vn.info("[ws] Injecting web UI message into agent",{contentLength:e.length}),fe({type:"user_message",summary:e}),Re({text:`[Web] ${e}`}),I.pushText(`[Message from web UI user]: ${e}`),U||(U=!0,Ne({status:"running"})))}}),ue.start(),pe({phase:"initializing"})}Vn.info(`[${n}] Progress session created`,{sessionId:t})}else{const e=await o.text().catch(()=>"");Vn.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);Vn.warn(`[progress] Session creation failed (non-fatal): ${t}`)}const he={current:e=>{}},me={current:async()=>{}},{addSubagentActivity:ge,addSubagentStart:ye,addTool:xe,addToolResult:Ae,appendText:Ce,appendUserMessage:Re,cleanup:Pe,setExiting:Ue,setRunningLabel:ke,setStatus:Le,setSubagentStatus:De,updateFixProgress:Oe}=await(async(e,t)=>{const{Box:r,Static:n,Text:o,render:s,useInput:i}=await import("ink"),a=!!process.stdin.isTTY,c=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],l=()=>Ee(o,{inverse:!0,children:" "}),u=(({Box:e,Text:t,useInput:r},n,o)=>function({onChoice:s,prompt:i}){const[a,c]=be(0),[l,u]=be(!1),[d,p]=be(""),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=os(i.toolName),m=ns(i.toolName,i.input);return Te(e,{borderColor:"yellow",borderStyle:"round",flexDirection:"column",marginTop:1,paddingX:1,paddingY:0,children:[Ee(t,{bold:!0,color:"yellow",children:"Permission Required"}),Te(e,{flexDirection:"column",marginTop:1,children:[Ee(t,{color:"gray",dimColor:!0,children:h}),null!=m&&Te(t,{color:"gray",children:[" ",m]})]}),null!=i.decisionReason&&Ee(e,{marginTop:1,children:Te(t,{color:"gray",children:["Reason: ",i.decisionReason]})}),Te(e,l?{flexDirection:"column",marginTop:1,children:[Ee(t,{color:"gray",children:"Enter message for AI (press Enter to submit, Esc to cancel):"}),Te(t,{children:[Ee(t,{color:"yellow",children:">"})," ",d,Ee(n,{})]})]}:{flexDirection:"column",marginTop:1,children:[Ee(t,{color:"gray",children:"Use ↑↓ arrows or number keys to select:"}),f.map((e,r)=>Ee(t,{children:Te(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]=be(Date.now());we(()=>{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"},debugging:{label:"Debugging tests",color:"magenta"},validation:{label:"Validating fixes",color:"blue"},complete:{label:"Complete",color:"green"}}[e.phase],p=e.fixedTests+e.failedTests,f=("fixing"===e.phase||"debugging"===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 Ee(t,{flexDirection:"column",children:Te(n,{children:[Ee(n,{color:d,bold:!0,children:u}),Ee(n,{color:"gray",children:f}),Te(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 Te(t,{flexDirection:"column",children:[Te(n,{color:c,bold:!0,children:[l," in ",a]}),null!==e.totalTests&&Te(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 Te(t,{flexDirection:"column",marginTop:1,children:[Te(n,{children:[Ee(n,{color:o,bold:!0,children:"Agent"}),r.description?Te(n,{color:"gray",children:[" (",r.description,")"]}):null]}),r.activities.length>0&&Ee(t,{flexDirection:"column",marginLeft:2,children:r.activities.map(e=>(e=>"tool"===e.kind?Te(n,{color:"gray",dimColor:!0,children:["• ",e.content]},e.id):"tool_result"===e.kind||"text"===e.kind?Ee(n,{color:"gray",children:e.content},e.id):null)(e))})]},e.id)}return"tool"===e.kind?Te(n,{color:"gray",dimColor:!0,children:["• ",e.content]},e.id):"tool_result"===e.kind?Ee(n,{color:"gray",children:e.content},e.id):"user"===e.kind?Te(n,{color:"cyan",children:["You: ",e.content]},e.id):Ee(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:v,state:w}){const[_,I]=be({value:"",cursor:0}),E=_.value,T=_.cursor,x=ve(!1),S=ve(void 0),[A,C]=be(!1),R=ve(0),P=ve(!1),U=w.log.at(-1),k="text"===U?.kind&&"running"===w.status,L=w.log.findIndex(e=>"subagent"===e.kind&&"running"===e.subagent?.status),D=d?0:-1!==L?L:k?w.log.length-1:w.log.length;we(()=>{w.log.length<R.current&&(R.current=0),D>R.current&&(R.current=D)},[w.log.length,D]);const O=w.log.slice(0,R.current),$=w.log.slice(R.current),N=!!w.permissionPrompt,B=_e(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&&B().catch(()=>process.exit(1))},{isActive:s}),we(()=>{if(N||!b)return;process.stdout.isTTY&&process.stdout.write("[?2004h");const e=e=>{const t=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n");t&&I(e=>({value:e.value.slice(0,e.cursor)+t+e.value.slice(e.cursor),cursor:e.cursor+t.length}))},t=t=>{const r=t.toString();if(r.includes("[200~")){P.current=!0;const t=r.slice(r.indexOf("[200~")+6),n=t.includes("[201~"),o=n?t.slice(0,t.indexOf("[201~")):t;return n&&(P.current=!1),void e(o)}if(r.includes("[201~")){const t=r.slice(0,r.indexOf("[201~"));return e(t),void(P.current=!1)}P.current?e(r):""!==r&&"[1;5~"!==r?""!==r&&"[4;5~"!==r?""!==r&&"[1~"!==r&&"OH"!==r&&"[7~"!==r?""!==r&&"[4~"!==r&&"OF"!==r&&"[8~"!==r||I(e=>({...e,cursor:m(e.value,e.cursor)})):I(e=>({...e,cursor:h(e.value,e.cursor)})):I(e=>({...e,cursor:e.value.length})):I(e=>({...e,cursor:0}))};return process.stdin.on("data",t),()=>{process.stdin.off("data",t),process.stdout.isTTY&&process.stdout.write("[?2004l")}},[N,b]),o((e,t)=>{if(!t.ctrl||"c"!==e){if(t.return){if(P.current)return;const e=E.trim();return e&&b?.(e),void I({value:"",cursor:0})}t.ctrl&&"w"===e||t.ctrl&&t.backspace?I(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?I(e=>({...e,cursor:p(e.value,e.cursor)})):t.ctrl&&t.rightArrow||t.meta&&"f"===e?I(e=>({...e,cursor:f(e.value,e.cursor)})):t.leftArrow?I(e=>({...e,cursor:Math.max(0,e.cursor-1)})):t.rightArrow?I(e=>({...e,cursor:Math.min(e.value.length,e.cursor+1)})):t.ctrl&&"a"===e?I(e=>({...e,cursor:0})):t.ctrl&&"e"===e?I(e=>({...e,cursor:e.value.length})):!e||t.ctrl||t.meta||t.escape||e.includes("")||/^\[./.test(e)||/^O[A-D]$/.test(e)||I(t=>({value:t.value.slice(0,t.cursor)+e+t.value.slice(t.cursor),cursor:t.cursor+e.length})):I(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&&!N});const j=Ie(()=>"running"===w.status?Ee(a,{label:w.runningLabel??"Working"}):"success"!==w.status?Ee(n,{color:"red",children:"✖ Failed"}):void 0,[w.runningLabel,w.status]),M=!(v||!b||"running"!==w.status||0!==w.log.length||w.resultText||w.errorText),H="running"===w.status&&!M||w.log.length>0||w.resultText||w.errorText||"running"!==w.status;return Te(t,{flexDirection:"column",children:[Ee(r,{items:["header"],children:()=>Te(t,{flexDirection:"column",flexShrink:0,children:[Ee(n,{color:"cyan",bold:!0,children:"Stably Agent"}),Ee(t,{flexDirection:"column",marginTop:1,children:Ee(n,{color:"gray",children:w.promptDisplay})})]},"header")}),O.length>0&&Ee(r,{items:O,children:e=>u(e)}),$.length>0&&Ee(t,{flexDirection:"column",children:$.map(e=>u(e))}),"error"===w.status&&w.errorText&&Ee(t,{marginTop:1,children:Ee(n,{color:"red",children:w.errorText})}),"success"===w.status&&w.resultText&&Ee(t,{marginTop:1,children:Ee(n,{children:w.resultText})}),H&&Ee(t,{flexDirection:"column",flexShrink:0,marginTop:1,children:"running"===w.status&&w.fixProgress?Te(t,{flexDirection:"column",children:[Te(t,{children:[Ee(a,{}),Ee(n,{children:" "}),Ee(c,{progress:w.fixProgress})]}),("fixing"===w.fixProgress.phase||"debugging"===w.fixProgress.phase)&&w.log.flatMap(e=>{const{subagent:r}=e;if("subagent"!==e.kind||"fix-worker"!==r?.subagentType&&"debug-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 Te(t,{flexDirection:"column",children:[Te(n,{children:[" ",Ee(a,{}),Te(n,{color:"gray",children:[r.description||r.subagentType||"worker",s>0?` (${s} ${1===s?"cycle":"cycles"})`:""]})]}),c&&Te(n,{color:"gray",dimColor:!0,children:[" • ",c.content]}),l&&Te(n,{color:"gray",dimColor:!0,children:[" ",l]})]},e.id)})]}):"success"!==w.status&&"error"!==w.status||!w.fixProgress?j:Ee(l,{progress:w.fixProgress})}),null!=w.permissionPrompt&&null!=y&&Ee(i,{onChoice:y,prompt:w.permissionPrompt}),null!=b&&null==w.permissionPrompt&&!w.isExiting&&Te(t,{borderColor:"gray",borderStyle:"round",flexDirection:"column",flexShrink:0,marginTop:1,paddingX:1,paddingY:0,children:[Ee(n,{color:"gray",children:"Type a message and press Enter. Press Ctrl+C to exit."}),Te(n,{children:[Ee(n,{color:"yellow",children:">"})," ",E.slice(0,T),Ee(e,{}),E.slice(T)]})]}),A&&Te(t,{marginTop:1,flexDirection:"column",children:[Ee(n,{color:"yellow",children:"Press Ctrl+C again to exit"}),Ln&&Te(n,{color:"gray",children:["Debug log: ",Nn]})]})]})}})({Cursor:l,inkComponents:{Box:r,Static:n,Text:o,useInput:i},isRawModeSupported:a,PermissionPrompt:u,Spinner:({label:e})=>{const[t,r]=be(0);return we(()=>{const e=setInterval(()=>r(e=>(e+1)%c.length),80);return()=>clearInterval(e)},[]),Te(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(Ee(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(Ee(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("subagent"===o?.kind&&o.subagent){if("text"===t){const e=o.subagent.activities.at(-1);"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 if("debug-worker"===t){const e=(p.fixProgress.totalTests??0)+1,t=r||null;p.fixProgress={...p.fixProgress,phase:"debugging",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=os(e),n=ns(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="text"!==t?.kind?e.replace(/^\s*\n+/,""):e;p.log="text"===t?.kind?[...p.log.slice(0,-1),{...t,content:`${t.content}${r}`}]:[...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];"subagent"===n?.kind&&n.subagent&&(n.subagent.status=t,!p.fixProgress||"fix-worker"!==n.subagent.subagentType&&"debug-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}})(S,"chat"===e.mode||"init"===e.mode?{onExit:()=>me.current(),onSend:e=>he.current(e),showSpinnerImmediately:"init"===e.mode}:"fix"===e.mode?{onExit:()=>me.current(),isFixMode:!0}:void 0);let $e=S.status;const Ne=({error:e,result:t,status:r})=>{$e=r,Le({error:e,result:t,status:r})};let Be;w&&(Ce({text:"Starting verification...\n"}),Ce(x?{text:`Target URL: ${x}\n`}:{text:"Target URL: auto-detect (agent may infer from project config)\n"}),ke({label:"Calibrating verification flow..."})),he.current=e=>{const t=e.trim();if(b&&!Vn.getLogFilePath()&&Vn.initSession(t||"chat"),Vn.debug("User message",{text:t}),"/help"===t){U&&I&&(k=!0,A?.interrupt?.(),I.allowNextTurn(),U=!1),"running"===$e&&Ne({status:"success"}),Re({text:e});const t=E?.();return void Ce({text:t??"Help is not available in this session."})}const r=R||L&&U;if(b&&(D+=1,P=void 0,r||($=!1,ke({label:void 0}))),I){if(r)return Ne({status:"running"}),Re({text:e}),void N.push(e);if(!L||U||R||(L=!1),U)return Ne({status:"running"}),Re({text:e}),I.pushText(e),void(O+=1);Ne({status:"running"}),Re({text:e}),I.pushText(e),U=!0}};let je="",Me="";const He=[],Fe=[],Ge=[];let Ye;const Ve=await(async e=>{try{const t=await un(e,"stably.yaml");if(!t)return void Vn.debug("No stably.yaml found");const r=await q(t,"utf-8");if(!r.trim())return;const n=Se(r),o=ha.parse(n.toJS()),s=o.agent?.fix?.maxTurnsPerIssue,i=o.agent?.fix?.maxParallelWorkers,a=!!o.agent?.fix?.rules;return Vn.debug(`Loaded stably.yaml: maxTurnsPerIssue=${s??"default"}, maxParallelWorkers=${i??"default"}, hasRules=${a}`,{path:t,config:o.agent}),o}catch(e){return void Vn.warn("Failed to parse stably.yaml",{error:e})}})(u),We=Ve?.agent?.fix?.skipAfterConsecutiveUnfixed,ze=await(async()=>{if("single"===e.mode){const r=await async function(e,t){const r=n(e);if(t){const e=n(r,t);return Qo(e,"output-flag"),{path:e,source:"output-flag"}}const i=Ko(r);if(i){const e=await async function(e){try{const t=(await q(e,"utf-8")).match(/testDir:\s*['"]([^'"]+)['"]/);return t?.[1]}catch{return}}(i);if(e){const t=n(o(i),e);if(Jo(t))return Qo(t,"playwright.config.ts"),{path:t,source:"playwright.config.ts"}}}for(const e of qo){const t=s(r,e);if(Jo(t))return Qo(t,"auto-detected"),{path:t,source:"auto-detected"}}return Qo(r,"cwd-fallback"),{path:r,source:"cwd-fallback"}}(u,e.outputDir);return Ye=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: ${Ye}]`}var t;if("verify"===e.mode)return function(e,t){const r=(Array.isArray(e)?e.join(" "):e).trim()||"Verify the application behavior.",n=t?.trim();return n?`Starting URL: ${n}\nURL policy: treat this as the source of truth and do not switch domains unless the user explicitly asks.\n\nVerification prompt: ${r}`:r}(e.prompt,x);if("fix"===e.mode)try{Vn.info("[fix] Fetching autoheal context",{runId:e.runId,skipAfterConsecutiveUnfixed:We});const t=Date.now(),{context:r,autohealReportUrl:n,skippedTests:o}=await(async({authHeader:e,orgId:t,runId:r,skipAfterConsecutiveUnfixed:n})=>{Vn.debug("Fetching autoheal context",{runId:r,skipAfterConsecutiveUnfixed:n});const o=await(s={auth:e,client:rn(),headers:to(t),path:{runId:r},query:null!=n?{skipAfterConsecutiveUnfixed:n}:{}},(s.client??Yr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-context",...s}));var s;if(404===o.response.status)throw Vn.warn("Autoheal context not found",{runId:r,status:404}),new Error(`Run ID "${r}" was not found.`);if(401===o.response.status)throw Vn.warn("Autoheal context fetch unauthorized",{runId:r,status:401}),new Error("Unauthorized: failed to fetch autoheal context (401).");if(422===o.response.status)throw Vn.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=ro.safeParse(o.data);if(e.success)return Vn.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 Vn.warn("Autoheal context response invalid",{runId:r}),new Error("Autoheal context response missing or invalid context.")}throw Vn.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:We});if(Vn.info("[fix] Autoheal context fetched",{runId:e.runId,durationMs:Date.now()-t,contextLength:r.length,skippedTestCount:o.length}),Be=n,o.length>0){Vn.info(`[fix] Skipping ${o.length} test(s) that failed to be fixed ${We}+ consecutive times`);for(const e of o)Vn.info(`[fix] Skipped: ${e.testIdentifier} — ${e.testTitle} (unfixed ${e.consecutiveUnfixedCount}x)`)}return r.includes("No failing tests to fix (all were skipped).")&&(Vn.info("[fix] All failing tests were skipped — nothing to fix"),Ne({status:"success",result:`All failing tests skipped (unfixed ${We}+ consecutive times). Nothing to fix.`}),await Pe(),process.exit(0)),te||(Vn.info("[fix] Creating WebSocket progress reporter"),te=new lo({authHeader:c,orgId:l,runId:e.runId,onUserMessage:e=>{if(Vn.info("[ws] Injecting web UI message into fix agent",{contentLength:e.length}),oe(Aa,{type:"user_message",summary:e}),se({type:"user_message",summary:e}),Re({text:`[Web] ${e}`}),!U)return I.pushText(`[Message from web UI user]: ${e}`),U=!0,void I.allowNextTurn();Y||Date.now()-K<2e3?I.pushText(`[Message from web UI user]: ${e}`):(M.push(e),B&&clearTimeout(B),B=setTimeout(()=>{B=void 0;const e=[...M];M=[],K=Date.now(),zt(e)},500))}}),te.start(),ae({phase:"initializing"})),ce("STARTED"),r}catch(e){const t=e instanceof Error?e.message:"Failed to fetch autoheal context.";Vn.error("[fix] Failed to fetch autoheal context",{error:t}),Ne({error:t,status:"error"}),await Pe(),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.":""})(),Ke=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(y(t))for(const e of Ho){const n=r.join(t,`playwright.config${e}`);if(y(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([Yo({defaultContent:"Unable to read directory",dirName:"working directory",dirPath:t}),Yo({defaultContent:"Unable to read directory",dirName:"tests directory",dirPath:n}),Yo({defaultContent:"Directory does not exist yet",dirName:"helpers directory",dirPath:o}),Yo({defaultContent:"Directory does not exist yet",dirName:"assets directory",dirPath:s}),Go({defaultContent:"File does not exist or could not be read",fileName:a,filePath:i}),Go({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),qe="fix"===e.mode?Ve?.agent?.fix?.maxTurnsPerIssue:void 0,Je="fix"===e.mode?Ve?.agent?.fix?.maxParallelWorkers:void 0,Qe="fix"===e.mode?Ve?.agent?.fix?.rules:void 0,Xe=Ve?.agent?.fix?.maxBudgetUsd??50,Ze="verify"===e.mode?e.maxBudgetUsd??5:void 0,et="fix"===e.mode?Xe:w?Ze:void 0,tt="fix"===e.mode||"single"===e.mode||"verify"===e.mode,rt="single"===e.mode?await(async e=>{const t=await ma(e,"STABLY-CREATE.md");return t?.content})(u):void 0,nt=await(e=>ma(e,"STABLY.md"))(u),ot=nt?.content;w&&(ke({label:"Assembling verification context..."}),Ce({text:"Assembling workspace context...\n"})),Vn.info("[fix] Fetching system prompt and subagent definitions",{mode:e.mode,maxTurnsOverride:qe,maxBudgetUsd:et,hasCustomRules:!!Qe,hasCreateRules:!!rt,hasStablyMd:!!ot,stablyMdPath:nt?.path}),nt&&Vn.info(`STABLY.md loaded (${nt.content.length} chars)`,{path:nt.path});const st=await eo(),it=st?Object.keys(st.variables):[],at=[...new Set([...Object.keys(h),...it])],ct=Date.now(),[{systemPrompt:lt,prContext:ut},dt]=await Promise.all([Vo({allowedEnvVars:at,mode:e.mode,workspaceInfo:Ke,authHeader:c,customHeader:"single"===e.mode?e.customHeader:void 0,maxParallelWorkers:Je}),tt?la({authHeader:c,mode:e.mode,maxTurnsOverride:qe}):Promise.resolve({})]);Vn.info("[fix] System prompt and subagents fetched",{durationMs:Date.now()-ct,systemPromptSize:lt.length,subagentCount:Object.keys(dt).length,maxTurnsOverride:qe??"default",hasPrContext:!!ut});const pt={...h,...process.env},ft={};for(const[e,t]of Object.entries(pt))ca.has(e)||void 0===t||(ft[e]=t);const ht=!0;Vn.debug("AI proxy configuration",{useStablyAiProxy:ht,wantsBypassProxy:!1,wantsUseOllama:!1}),Vn.info("[fix] Acquiring AI proxy key",{useStablyAiProxy:ht});const mt=Date.now(),gt=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??Yr).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:aa(e,a)}}return i.data?{key:i.data.key}:{error:aa("No data in response",a)}}catch(e){const t=e instanceof Error?e.message:"Unknown error";return{error:aa(t)}}var s}({auth:c,client:rn(),source:"cli"}),yt=gt?.key;if(Vn.info("[fix] AI proxy key acquired",{durationMs:Date.now()-mt,success:!!yt,hasError:!!gt?.error}),!yt){const e=gt?.error?.message?`Unable to make AI calls: ${gt.error.message}`:"Unable to make AI calls. Check if you are authenticated.";Vn.warn("Failed to get proxy API key",{error:gt?.error?.message}),Ne({error:e,status:"error"}),await Pe(),Vn.flush(),Vn.printLogFileInfo(),process.exit(1)}Vn.debug("Proxy API key acquired",{success:!!yt});const bt=await Zn(),vt=st?.sensitiveValues.length?{STABLY_SENSITIVE_VALUES:Buffer.from(JSON.stringify(st.sensitiveValues)).toString("base64")}:{},wt=bt?Object.fromEntries(Object.entries(Xn({...st?.variables,...vt,...bt})).filter(e=>null!=e[1])):st?Object.fromEntries(Object.entries(Xn({...st.variables,...vt})).filter(e=>null!=e[1])):void 0,_t="init"===e.mode,It="fix"===e.mode,Et=It?Ir.createLocal({workingDir:u}):void 0;Et&&await Et.captureSnapshot();const Tt=_t?Zi({onComplete:()=>{Ne({status:"success"}),Ue(),I?.finish(),process.exit(0)}}):b?Zi({onRestartRequested:()=>{b&&(L=!0,Ne({status:"running"}),ke({label:"Restarting browser tools..."}),P={createdAtUserMessageSeq:D,attempts:0})}}):void 0,xt=Tt?b?{"stably-agent-control":Tt}:{"session-control":Tt}:{},St=v&&ut?["mcp__create-report"]:[],At=_t?xa:w?Ea:[...Ea,...It?["mcp__auto-heal-report"]:[],...St],Ct=_t?xa:b?[...Ta,"mcp__stably-agent-control"]:w?Ta:[...Ta,...St],Rt=v&&ut?{"create-report":ta({prContext:ut,authHeader:c,orgId:l,onReportPosted:e=>{pe({githubComment:{url:e.commentUrl,prNumber:ut.prNumber}})}})}:{},Pt=_t?xt:It&&Et?{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:wt},"auto-heal-report":Xi({authHeader:c,diffTracker:Et,orgId:l,runId:e.runId,workingDir:u}),"run-history":sa({authHeader:c,orgId:l,projectId:Jn(a)}),...xt}:w?{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:wt},...xt}:{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:wt},...xt,...Rt},Ut="single"===e.mode,kt=_t?[]:[{hooks:[async e=>{const t=So(e);if(!t)return{decision:"approve"};let r=!1;const n=t.map(e=>To(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:[Lo({onResult:e=>Ae({message:e})})]},{matcher:"mcp__playwright-test__test_debug",hooks:[Do({onResult:e=>Ae({message:e})})]},...Ut?[{matcher:"Write",hooks:[$o({onFileCreated:e=>{if(He.includes(e)||He.push(e),de){if(de.filesCreated.some(t=>"string"==typeof t?t===e:t.path===e))return;const t=r.isAbsolute(e)?e:r.join(u,e),n=r.basename(e),{sessionId:o}=de,s=(async()=>{try{const r=await g.promises.readFile(t,"utf8"),s=await(async({authHeader:e,content:t,contentType:r="text/plain",filename:n,filePath:o,orgId:s,sessionId:i})=>{try{const{bucketPath:a,uploadUrl:c}=await(async({authHeader:e,contentType:t="text/plain",filename:r,filePath:n,orgId:o,sessionId:s})=>{const i=await(a={auth:e,body:{filename:r,filePath:n,contentType:t},client:rn(),headers:to(o),path:{sessionId:s}},(a.client??Yr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/sessions/{sessionId}/files/upload-url",...a,headers:{"Content-Type":"application/json",...a.headers}}));var a;if(i.error)throw new Error(`Failed to presign file upload (${i.response.status})`);const c=po.parse(i.data);return{bucketPath:c.bucketPath,expiresInSeconds:c.expiresInSeconds,key:c.key,uploadUrl:c.uploadUrl}})({authHeader:e,contentType:r,filename:n,filePath:o,orgId:s,sessionId:i});return await oo({body:t,contentType:r,uploadUrl:c,errorContext:"file"}),await(async({authHeader:e,bucketPath:t,filename:r,filePath:n,orgId:o,sessionId:s})=>{const i=await(a={auth:e,body:{filename:r,filePath:n,bucketPath:t},client:rn(),headers:to(o),path:{sessionId:s}},(a.client??Yr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/sessions/{sessionId}/files/confirm",...a,headers:{"Content-Type":"application/json",...a.headers}}));var a;if(i.error)throw new Error(`Failed to confirm file upload (${i.response.status})`)})({authHeader:e,bucketPath:a,filename:n,filePath:o,orgId:s,sessionId:i}),a}catch(e){return Vn.warn("Failed to upload automation file",{error:e instanceof Error?e.message:String(e)}),null}})({authHeader:c,content:r,contentType:"text/plain",filename:n,filePath:e,orgId:l,sessionId:o}),i={path:e,filename:n,bucketPath:s};Fe.push(i),pe({filesCreated:[...Fe]})}catch(t){Vn.warn("Failed to upload created file",{filePath:e,error:t instanceof Error?t.message:String(t)});const r={path:e,filename:n,bucketPath:null};Fe.push(r),pe({filesCreated:[...Fe]})}})();Ge.push(s)}}})]}]:[]],Lt=_t?[]:[{matcher:"mcp__playwright-test__.*",hooks:[async()=>L?{decision:"block",reason:'MCP restart is pending. This tool cannot be used until the restart completes. End your turn now - the restart only happens AFTER your turn ends. The system will send "[SYSTEM] MCP servers were restarted successfully" when ready.',systemMessage:"Tool call blocked: MCP restart pending"}:{decision:"approve"}]},...It?[{matcher:"Read",hooks:[go({action:"reading",pathKey:"file_path"})]},{matcher:"Write",hooks:[go({action:"writing",pathKey:"file_path"})]},{matcher:"Edit",hooks:[go({action:"editing",pathKey:"file_path"})]},{matcher:"Grep",hooks:[go({action:"searching",pathKey:"path"})]},{matcher:"Glob",hooks:[go({action:"searching",pathKey:"path"})]},{matcher:"Bash",hooks:[Eo({workspaceBoundary:u})]}]:[],{matcher:"mcp__playwright-test__browser_(type|navigate|evaluate|fill_form)",hooks:[ko({envVars:{...h,...st?.variables}})]}],Dt=Object.keys(dt).length>0?dt:void 0,Ot={...ft};Ot.MCP_TOOL_TIMEOUT=String(6e5),yt&&(Ot.ANTHROPIC_API_KEY=yt,Ot.ANTHROPIC_BASE_URL=Xr,Ot.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS="1");const $t=process.env.STABLY_AGENT_MODEL??"claude-opus-4-6",Nt=It?"env"===a.type?a.auth.apiKey:a.auth.accessToken:void 0,Bt=It?Jn(a):void 0;It&&Nt&&Bt&&(Ot.STABLY_API_KEY=Nt,Ot.STABLY_PROJECT_ID=Bt);const jt=Qe?`\n\n## Custom Rules\n${Qe}`:"",Mt=rt?`\n\n## Custom Test Generation Rules\n${rt}`:"",Ht=ot?`\n\n## Project Rules (STABLY.md)\n${ot}`:"",Ft=lt+jt+Mt+Ht;Vn.debug("[fix] Final system prompt assembled",{baseSize:lt.length,fixRulesSize:jt.length,createRulesSize:Mt.length,stablyMdSize:Ht.length,finalSize:Ft.length});const Gt=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 fa(t)?t:void 0}();if(e)return e;const t=r.join(ua,"stably-plugin");if(fa(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}}(ua))for(const t of pa){const n=r.join(e,t);if(fa(n))return n}}();if(e)return{type:"local",path:e}}(),Yt=()=>(Vn.info("[fix] Starting SDK query",{model:$t,tools:At,mcpServers:Object.keys(Pt),resumeSessionId:C??null,subagentsEnabled:!!Dt,subagentCount:Object.keys(dt).length,useStablyAiProxy:ht,aiProxyUrl:Xr,anthropicBaseUrl:void 0,stablyPluginPath:Gt?.path,stablyPluginExists:!!Gt}),H({options:{executableArgs:["--max-old-space-size=4096"],tools:At,allowedTools:Ct,...null!=et?{maxBudgetUsd:et}:{},betas:[],canUseTool:(e,t)=>(Vn.debug("[fix] canUseTool called",{toolName:e}),Promise.resolve({behavior:"allow",updatedInput:t})),cwd:u,env:Ot,hooks:{PostToolUse:kt,PreToolUse:Lt},includePartialMessages:!0,agents:Dt,mcpServers:Pt,model:$t,permissionMode:"default",plugins:Gt?[Gt]:void 0,systemPrompt:Ft,...C?{resume:C}:{}},prompt:I??ze})),Vt=()=>{if(I&&0!==N.length){for(const e of N)I.pushText(e);N.length=0,U=!0,Ne({status:"running"})}},Wt=async()=>{b&&(R||(R=(async()=>{Vn.info("Restarting MCP servers for chat mode"),Ne({status:"running"}),ke({label:"Restarting browser tools..."});try{await(A?.interrupt?.())}catch(e){Vn.warn("Failed to interrupt response during MCP restart",{error:e instanceof Error?e.message:String(e)})}await Bo(),I?.finish(),I=new jo,O=0,U=!1,k=!1,J.clear(),A=Yt(),$=!0,ke({label:"Restarting browser tools..."}),b&&I&&P&&(P.createdAtUserMessageSeq===D?P.attempts>=1||N.length>0?P=void 0:(P.attempts+=1,I.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")),P=void 0,U=!0,Ne({status:"running"})):P=void 0),Vt()})().finally(()=>{R=void 0,Vt()})),await R)},zt=async e=>{if(m&&U&&!Y&&!j)j=(async()=>{Vn.info("[fix] Interrupting for user message",{messageCount:e.length,phase:re?.phase});try{await(A?.interrupt?.())}catch(e){Vn.warn("[fix] Failed to interrupt response for user message",{error:e instanceof Error?e.message:String(e)})}await Bo(),I?.finish(),I=new jo,J.clear(),A=Yt();const t=e.map(e=>`[Message from web UI user]: ${e}`).join("\n\n");I.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}`),V=!0,U=!0})().finally(()=>{j=void 0}),await j;else for(const t of e)I?.pushText(`[Message from web UI user]: ${t}`)};if(yt){w&&ke({label:"Checking AI connectivity..."});const e=Xr,t=`${e.replace(/\/$/,"")}/v1/messages`;Vn.debug(`[fix] Pre-flight: POST ${t}`);const r=Date.now();let n;try{const e=await fetch(t,{method:"POST",signal:AbortSignal.timeout(1e4),headers:{"x-api-key":yt,"anthropic-version":"2023-06-01","content-type":"application/json"},body:"{}"}),o=await e.text().catch(()=>""),s=Date.now()-r;Vn.debug(`[fix] Pre-flight: ${e.status} in ${s}ms — ${o.slice(0,300)}`),401===e.status||403===e.status?(Vn.error(`[fix] Pre-flight: AI proxy key rejected (${e.status}) at ${t}`),n="Unable to start verification: AI proxy credentials were rejected. Please run `stably login` and try again."):Vn.info("[fix] Pre-flight: AI proxy key valid",{status:e.status,durationMs:s})}catch(t){Vn.error("[fix] Pre-flight: AI proxy unreachable",{error:t instanceof Error?t.message:String(t),durationMs:Date.now()-r,url:e}),n="Unable to start verification: cannot reach the AI proxy. Please check your network/VPN and try again."}finally{w&&"running"===$e&&ke({label:void 0})}n&&(Ce({text:`[stably] ${n}\n`}),Ne({error:n,status:"error"}),await Pe(),Vn.flush(),Vn.printLogFileInfo(),process.exit(1))}Vn.info("[fix] Creating initial agent query"),w&&(ke({label:"Initializing verification session..."}),Ce({text:"Initializing verification session...\n"})),Vn.flush(),A=Yt(),Vn.info("[fix] Agent query created, entering message loop"),"chat"!==e.mode&&I.pushText(ze),me.current=async()=>{Q="CANCELED",await ce("CANCELED"),ae({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:ie(!0)}),te?.close(),await Promise.allSettled(Ge),pe({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0}),ue?.close(),B&&(clearTimeout(B),B=void 0),Vn.flush(),Ue();try{await(A?.interrupt?.())}catch{}I?.finish(),Pe()};let Kt=0,qt=null,Jt=!1;const Qt=w?setTimeout(()=>{if(qt||"running"!==$e)return;const e="This is taking longer than expected. Please try again.";Ce({text:`[stably] ${e}\n`}),Ne({error:e,status:"error"});try{A?.interrupt?.()}catch{}I?.finish(),Pe(),Vn.flush(),Vn.printLogFileInfo(),process.exit(1)},9e4):void 0;Qt?.unref();const Xt=setInterval(()=>{const e=Date.now()-ee;qt?Vn.info("[fix] Watchdog: message loop active",{messageCount:Kt,elapsed:e}):(Vn.info("[fix] Watchdog: waiting for first SDK message",{elapsed:e}),w&&!Jt&&e>=15e3&&(Ce({text:"Still preparing verification. This can take a bit...\n"}),Jt=!0)),Vn.flush()},15e3);Xt.unref();try{let t=!1;for(;;){if(!A){Vn.info("[fix] No response object, exiting message loop");break}t=!1,Vn.info("[fix] Entering for-await on SDK response");for await(const r of A){Kt++,qt||(qt=Date.now(),Qt&&clearTimeout(Qt),w&&ke({label:void 0}),Vn.info("[fix] First SDK message received",{waitDurationMs:qt-ee,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!==C&&(C=n,Vn.debug("Captured Claude session id",{sessionId:C})),"stream_event"===r.type){const{event:e}=r;(Kt<=5||Kt%200==0)&&Vn.debug("[fix] Stream event",{msgNum:Kt,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(b&&L&&!t)continue;$&&($=!1,ke({label:void 0}));const e=t&&J.has(t)?t:1===J.size?Array.from(J.keys())[0]:void 0;e?ge({toolUseId:e,kind:"text",content:r.text}):w||Ce({text:r.text})}}"message_stop"===e?.type&&I&&(Y=!1,I.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("\n");t&&(je=t,w&&(Me=Me?`${Me}\n\n${t}`:t),Vn.debug("Assistant message",{text:w?wa(t):t}),"fix"===e.mode&&(oe(Aa,{type:"ai_message",summary:t.slice(0,200)}),se({type:"ai_message",summary:t.slice(0,200)})),_&&fe({type:"ai_message",summary:t.slice(0,200)}))}if(J.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):[];Vn.debug("Assistant message with active subagents",{hasParentToolUseId:!!t,parentToolUseId:t,activeSubagentIds:Array.from(J.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&&(Y=!0),"mcp__session-control__restart_mcp_servers"===r.name||"mcp__stably-agent-control__restart_mcp_servers"===r.name){xe({rawName:r.name,toolInput:r.input});continue}if(r.name.startsWith("mcp__session-control__")||r.name.startsWith("mcp__stably-agent-control__"))continue;if(ka(r.name))continue;if(w&&Ua.test(r.name))continue;if(J.size>0&&Vn.debug("Tool use detected with active subagents",{toolName:r.name,hasParentToolUseId:!!t,parentToolUseId:t,wouldRouteToSubagent:!!t&&J.has(t),activeSubagentIds:Array.from(J.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(Vn.info("[fix] Subagent started",{subagentType:o,description:s,toolUseId:r.id,activeSubagentCount:J.size+1}),J.set(r.id,{subagentType:o,description:s}),ye({toolUseId:r.id,subagentType:o,description:s}),"fix"===e.mode){if("triage"===o){Oe?.({phase:"triage"});const e={id:r.id,testDescription:"Triage",workerType:"triage",status:"running",summary:null,startedAt:Date.now(),endedAt:null,activity:[]};ae({phase:"triage",workers:[...re?.workers??[],e]})}else if("fix-worker"===o){ne.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:[]};Oe?.({phase:"fixing",totalTests:ne.size,currentTestDescription:s||null}),ae({phase:"fixing",totalTests:ne.size,currentTestDescription:s||null,lastTestDescription:s||re?.lastTestDescription||null,workers:[...re?.workers??[],e]})}else if("debug-worker"===o){ne.add(s||r.id);const e={id:r.id,testDescription:s||r.id,workerType:"debug-worker",status:"running",summary:null,startedAt:Date.now(),endedAt:null,activity:[]};Oe?.({phase:"debugging",totalTests:ne.size,currentTestDescription:s||null}),ae({phase:"debugging",totalTests:ne.size,currentTestDescription:s||null,lastTestDescription:s||re?.lastTestDescription||null,workers:[...re?.workers??[],e]})}else"validation"===o?(Oe?.({phase:"validation",currentTestDescription:null}),ae({phase:"validation",currentTestDescription:null})):"context"===o&&ae({currentTestDescription:s||null});se({type:"tool_call",summary:`[${o}] ${s}`.trim()})}continue}if(t&&J.has(t)){const n=os(r.name),o=ns(r.name,r.input),s=o?`${n} (${o})`:n;if(Vn.debug("Subagent tool called",{tool:r.name,parentToolUseId:t}),ge({toolUseId:t,kind:"tool",content:s}),"fix"===e.mode){se({type:"tool_call",summary:s});const e=J.get(t);"fix-worker"!==e?.subagentType&&"debug-worker"!==e?.subagentType&&"triage"!==e?.subagentType||oe(t,{type:"tool_call",summary:s})}continue}if(t&&Vn.debug("Tool with parent_tool_use_id but no matching subagent",{tool:r.name,parentToolUseId:t,activeSubagentIds:Array.from(J.keys())}),Vn.debug("Tool called",{tool:r.name,input:r.input}),xe({rawName:r.name,toolInput:r.input}),"fix"===e.mode){const e=os(r.name),t=ns(r.name,r.input),n=t?`${e} (${t})`:e;oe(Aa,{type:"tool_call",summary:n}),se({type:"tool_call",summary:n})}if(v){const e=os(r.name),t=ns(r.name,r.input),n=t?`${e} (${t})`:e;"initializing"===de?.phase?pe({phase:"generating",currentActivity:n}):"mcp__playwright-test__test_run"===r.name&&"generating"===de?.phase?pe({phase:"testing",currentActivity:n}):pe({currentActivity:n}),fe({type:"tool_call",summary:n})}if(w){const e=os(r.name),t=ns(r.name,r.input),n=wa(t?`${e} (${t})`:e);pe("initializing"===de?.phase?{phase:"verifying",currentActivity:n}:{currentActivity:n}),fe({type:"tool_call",summary:n})}}if("text"===r?.type){const n="string"==typeof r.text?r.text:"",o=t&&J.has(t)?t:1===J.size?Array.from(J.keys())[0]:void 0;if(o&&n&&(ge({toolUseId:o,kind:"text",content:n}),"fix"===e.mode)){const e=J.get(o);"fix-worker"!==e?.subagentType&&"debug-worker"!==e?.subagentType&&"triage"!==e?.subagentType||oe(o,{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,n="tool_use_result"in r&&r.tool_use_result&&"object"==typeof r.tool_use_result?r.tool_use_result: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,o="is_error"in r&&!0===r.is_error||"error"===n?.status;let s;const i=n?.content??("content"in r?r.content:void 0);if("string"==typeof i?s=i:Array.isArray(i)&&(s=i.filter(e=>e&&"object"==typeof e&&"text"===e.type).map(e=>e.text||"").join("")),Vn.debug("Tool result",{toolUseId:t,isError:o,output:s?.slice(0,500)}),t&&J.has(t)){const r=J.get(t);if(Vn.info("[fix] Subagent completed",{toolUseId:t,isError:o,subagentType:r?.subagentType,description:r?.description,activeSubagentCount:J.size-1}),s&&ge({toolUseId:t,kind:"text",content:s}),De({toolUseId:t,status:o?"error":"complete"}),"fix"===e.mode&&"triage"===r?.subagentType){const e=o?"failed":"succeeded",r=s?s.slice(0,500):null,n=(re?.workers??[]).map(n=>n.id===t?{...n,status:e,summary:r,endedAt:Date.now()}:n);ae({workers:n})}if("fix"===e.mode&&("fix-worker"===r?.subagentType||"debug-worker"===r?.subagentType)){const e=o?"failed":"succeeded",r=s?s.slice(0,500):null,n=(re?.workers??[]).map(n=>n.id===t?{...n,status:e,summary:r,endedAt:Date.now()}:n);o?(Oe?.({failedTests:(re?.failedTests??0)+1,currentTestDescription:null}),ae({failedTests:(re?.failedTests??0)+1,currentTestDescription:null,workers:n})):(Oe?.({fixedTests:(re?.fixedTests??0)+1,currentTestDescription:null}),ae({fixedTests:(re?.fixedTests??0)+1,currentTestDescription:null,workers:n}))}J.delete(t)}}continue}if("result"===r.type){if(Vn.info("[fix] Agent result received",{subtype:r.subtype,messageCount:Kt,elapsed:Date.now()-ee,activeSubagents:J.size,fixedTests:re?.fixedTests,failedTests:re?.failedTests,phase:re?.phase}),m){if("success"===r.subtype){B&&(clearTimeout(B),B=void 0);for(const e of M)I?.pushText(`[Message from web UI user]: ${e}`);if(M=[],(_||"fix"===e.mode)&&I){if(I.hasQueuedMessages()){Vn.info("[ws] Queued web UI messages found, continuing agent"),U=!0,I.allowNextTurn();continue}if(await La(I,3e3)){Vn.info("[ws] Web UI message received during grace period, continuing agent"),U=!0,I.allowNextTurn();continue}I.finish()}if(Oe?.({phase:"complete",currentTestDescription:null,endedAt:Date.now()}),ae({phase:"complete",currentTestDescription:null,endedAt:Date.now(),isError:!1,workers:ie(!1)}),await Promise.allSettled(Ge),"verify"===e.mode){(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt).trim();const t=Me||je,r=/```verdict\s*\r?\n/.test(t),n=Ia(t)??{verdict:"INCONCLUSIVE",steps:["Agent finished without a parseable verdict block."],reason:r?"Failed to parse verdict.":"The agent completed without reporting a verdict.",evidence:[]},o=_a(n);"PASS"===n.verdict?z.green("VERIFICATION PASSED"):"FAIL"===n.verdict?z.red("VERIFICATION FAILED"):z.yellow("VERIFICATION INCONCLUSIVE"),o.steps.length>0&&o.steps.forEach((e,t)=>{}),o.reason&&(n.verdict,o.reason),o.evidence.length>0&&o.evidence.forEach(e=>{}),pe({phase:"complete",endedAt:Date.now(),isError:"PASS"!==n.verdict,currentActivity:null}),process.exitCode="PASS"===n.verdict?0:"FAIL"===n.verdict?1:2,Ne({status:"success"})}else{if(pe({phase:"complete",endedAt:Date.now(),isError:!1,currentActivity:null}),Ut&&He.length>0){z.green("Created files:");for(const e of He)z.green(`- ${e}`)}const e=(e,t)=>`]8;;${e}${t}]8;;`,t=Be?z.cyan(`📊 View Autoheal Report:\n ${e(Be,z.cyan(z.bold(z.underline(Be))))}`):void 0;Ne({status:"success",result:t}),Q="COMPLETED"}}else if(j||V)Vn.info("[fix] Suppressing error status: user-message interrupt in progress");else if(k)Q="CANCELED",ae({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:ie(!0)}),await Promise.allSettled(Ge),pe({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0});else if(w){let e="Execution error before verification completed.";"error_max_budget_usd"===r.subtype?e="Budget limit exceeded before verification completed.":"error_max_turns"===r.subtype&&(e="Maximum turns exceeded before verification completed."),z.yellow("VERIFICATION INCONCLUSIVE"),await Promise.allSettled(Ge),pe({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),Ne({status:"success"}),process.exitCode=2}else{let e,t="unknown",n="Run failed.";"error_max_budget_usd"===r.subtype?(t="budget_exceeded",e="total_cost_usd"in r?r.total_cost_usd:void 0,n=`Budget limit exceeded (${void 0!==e?`$${e.toFixed(2)}`:"unknown"} spent). The fix session was stopped to prevent runaway costs.`,Vn.warn("[fix] Budget limit exceeded",{subtype:r.subtype,totalCostUsd:e})):"error_max_turns"===r.subtype?(t="max_turns",n="Maximum turns exceeded. The fix session was stopped."):"error_during_execution"===r.subtype&&(t="execution_error"),Oe?.({endedAt:Date.now(),isError:!0}),ae({phase:"complete",endedAt:Date.now(),isError:!0,errorReason:t,errorMessage:n,totalCostUsd:e,currentTestDescription:null,workers:ie(!0)}),await Promise.allSettled(Ge),pe({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),Ne({error:n,status:"error"}),process.exitCode=1,Q="FAILED"}k=!1;break}const n=b&&L;if("success"!==r.subtype){if(!k){let e="Run failed.";"error_max_budget_usd"===r.subtype?(e=`Budget limit exceeded (${"total_cost_usd"in r?`$${r.total_cost_usd.toFixed(2)}`:"unknown"} spent). The fix session was stopped to prevent runaway costs.`,Vn.warn("[fix] Budget limit exceeded",{subtype:r.subtype,totalCostUsd:"total_cost_usd"in r?r.total_cost_usd:void 0})):"error_max_turns"===r.subtype&&(e="Maximum turns exceeded. The fix session was stopped."),Ne({error:e,status:"error"}),process.exitCode=1}}else Ne(n?{status:"running"}:{status:"success"});if(U=!1,k=!1,n){L=!1,Vn.info("Processing deferred MCP restart request in chat mode"),await Wt(),t=!0;break}$=!1,ke({label:void 0}),I?.allowNextTurn(),b&&O>0&&(O-=1,U=!0,Ne({status:"running"}));continue}}if(j&&await j,V&&(V=!1,t=!0,Ne({status:"running"}),Vn.info("[fix] Resuming after user-message interrupt")),!t)break}}catch(e){k?(Q="CANCELED",ae({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:ie(!0)}),await Promise.allSettled(Ge),pe({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0})):(Vn.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()-ee}),Ne({error:`Agent encountered an error: ${e}`,status:"error"}),process.exitCode=1,Q="FAILED",ae({phase:"complete",endedAt:Date.now(),isError:!0,currentTestDescription:null,workers:ie(!0)}),await Promise.allSettled(Ge),pe({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),Vn.flush(),Vn.printLogFileInfo())}finally{if(Qt&&clearTimeout(Qt),clearInterval(Xt),B&&(clearTimeout(B),B=void 0),Vn.info("[fix] Agent session ending",{finalStatus:Q,elapsed:Date.now()-ee,totalMessages:Kt}),U=!1,k=!1,process.off("uncaughtException",i),I?.finish(),Q){Vn.info("[fix] Reporting final autoheal status",{status:Q});const e=Date.now();await ce(Q),Vn.info("[fix] Final autoheal status reported",{durationMs:Date.now()-e})}if(Vn.info("[fix] Closing WebSocket progress reporter"),te?.close(),await Promise.allSettled(Ge),ue?.close(),It&&Et){const t=Date.now();try{Vn.info("[fix] Computing diff...");const r=await Et.computeDiff();if(r&&r.trim().length>0){Vn.info("[fix] Uploading diff...",{diffLength:r.length});const{diffBucketPath:n,uploadUrl:o}=await ao({authHeader:c,contentType:"text/plain",orgId:l,runId:e.runId});await oo({body:r,contentType:"text/plain",uploadUrl:o,errorContext:"diff"}),await co({authHeader:c,diffBucketPath:n,orgId:l,runId:e.runId}),Vn.info("[fix] Diff uploaded",{durationMs:Date.now()-t})}else Vn.info("[fix] No diff to upload (empty or no changes)")}catch(e){Vn.warn("[fix] Failed to upload diff",{error:e instanceof Error?e.message:String(e),durationMs:Date.now()-t})}}Vn.info("[fix] Cleaning up diff tracker"),await(Et?.cleanup()),Vn.info("[fix] Running final cleanup"),await Pe(),Vn.info("[fix] Cleanup complete")}},$a=ue.object({runId:ue.string(),timestamp:ue.number()}),Na=[{args:["--trace=on"],description:"Run Playwright tests",name:"test"},{args:[],description:"Install browser dependencies",name:"install"}],Ba=["You have two different versions of @playwright/test"];function ja(e){const[t,...r]=Yi(e),n=[t,...r.slice(0,-1)].join(" ");return(t,r)=>{let o=t.toString();for(const e of Na)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[0].includes("\\.bin\\playwright"))&&e.shift(),void r.write(e.join("\n"))}r.write(o)}}async function Ma({overrideArgs:e,subcommand:t}){Vn.info("[test] forwardToPlaywright starting",{subcommand:t,overrideArgs:e});const r=process.argv,i=r.findIndex((e,r)=>r>1&&e===t),a=-1===i?[]:r.slice(i+1),l="--"===a[0],u=l?a.slice(1):a;if(!l&&("--help"===u[0]||"-h"===u[0]))return async function({subcommand:e}){const t=Na.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=Hi();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]=Yi(o),a=ja(o);return new Promise(t=>{const r=h(s,[...i,e,"--help"],{stdio:["inherit","pipe","pipe"],shell:"win32"===process.platform,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??[],p=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("=");p.has(r)?!t.includes("=")&&e+1<u.length&&!u[e+1].startsWith("-")&&e++:m.push(t)}const g=[t,...d,...m];Vn.info("[test] Forwarded args computed",{forwardedArgs:g}),Vn.info("[test] Resolving Stably test environment");const b=Date.now(),v="test"===t?await Zn():void 0;Vn.info("[test] Stably test environment resolved",{durationMs:Date.now()-b,hasCredentials:null!=v,hasWsUrl:!!v?.STABLY_WS_URL}),Vn.info("[test] Loading remote environment variables");const w=await eo();Vn.info("[test] Remote environment loaded",{hasRemoteEnv:!!w,variableCount:w?Object.keys(w.variables).length:0});const x={...w?.variables,...w?.sensitiveValues.length?{STABLY_SENSITIVE_VALUES:Buffer.from(JSON.stringify(w.sensitiveValues)).toString("base64")}:{}};Vn.info("[test] Setting up Stably reporter injection");const S="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=>y(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},a=(e,t)=>{try{return function({baseConfigPath:e,projectDir:t}){const r=function(e){try{const t=f("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",a=o(n(e)),l=c(e),u=s(a,`.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\n// Decode sensitive values from env var (set by CLI --env flag)\nconst decodeSensitiveValues = (): string[] | undefined => {\n const encoded = process.env.STABLY_SENSITIVE_VALUES;\n if (!encoded) return undefined;\n try {\n const decoded: unknown = JSON.parse(Buffer.from(encoded, 'base64').toString('utf-8'));\n return Array.isArray(decoded) ? decoded.filter((v): v is string => typeof v === 'string') : undefined;\n } catch {\n return undefined;\n }\n};\n\nconst buildReporterList = () => {\n const existingReporters = baseConfig.reporter;\n const sensitiveValues = decodeSensitiveValues();\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 cliVersion: '${zr}',\n projectId: process.env.STABLY_PROJECT_ID,\n source: 'cli',\n notificationConfigs: extractNotificationConfigs(),\n errorSummary: resolveErrorSummary(),\n ...(sensitiveValues && { sensitiveValues }),\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 cliVersion: '${zr}',\n projectId: process.env.STABLY_PROJECT_ID,\n source: 'cli',\n notificationConfigs: extractNotificationConfigs(),\n errorSummary: resolveErrorSummary(existingOptions?.errorSummary),\n ...(sensitiveValues && { sensitiveValues }),\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 y(a)||I(a,{recursive:!0}),E(u,d,"utf-8"),function(e){const t=s(e,".gitignore");try{if(y(t)){const e=_(t,"utf-8");if(e.split("\n").map(e=>e.trim()).includes(Wo))return;const r=e.length>0&&!e.endsWith("\n");T(t,`${r?"\n":""}${Wo}\n`)}else E(t,`${Wo}\n`)}catch{}}(a),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]),c=o(s);if(!i(c))return;const l=a(s,c);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]),c=o(t);if(!i(c))return;const l=a(t,c);if(!l)return;const u=e[s].startsWith("--config=")?"--config=":"-c=";return e[s]=`${u}${l}`,l}}const l=Ko(r);if(!l)return;const u=o(l);if(!i(u))return;const d=a(l,u);return d?(e.push("--config",d),d):void 0}({forwardedArgs:g,hasCredentials:null!=v}):void 0;Vn.info("[test] Reporter injection setup complete",{hasWrapperConfig:!!S}),Vn.info("[test] Spawning Playwright process"),await function(e,t={}){Vn.info("[test] Detecting Playwright installation");const r=Hi();Vn.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]=Yi(n),i=Xn(t.env),a=[o,...s,...e];Vn.info("[test] Spawning Playwright process",{command:a.join(" "),pid:process.pid});const c=Date.now(),l=h(o,[...s,...e],{stdio:["inherit","pipe","pipe"],shell:"win32"===process.platform,env:{...i,...process.env.CI?{}:{FORCE_COLOR:"1"}}});Vn.info("[test] Playwright process spawned",{childPid:l.pid});const u=ja(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 Ba)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,f=()=>!p.signal.aborted&&(p.abort(),t.onClose?.(),process.removeListener("SIGINT",m),process.removeListener("SIGTERM",m),!0),m=e=>{Vn.info("[test] Signal received, killing Playwright process",{signal:e,childPid:l.pid}),f(),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=>{f()&&(Vn.error("[test] Playwright process error",{error:e.message,childPid:l.pid}),t(e))}),l.on("close",t=>{if(!f())return;Vn.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)})})})}(g,{env:{...x,...v},onClose:()=>{var e;Vn.info("[test] Playwright process closed, cleaning up wrapper config"),(e=S)&&y(e)&&C(e)}})}function Ha(e){const t=new Date(e),r=new Date,n=r.getTime()-t.getTime(),o=Math.floor(n/1e3),s=Math.floor(o/60),i=Math.floor(s/60),a=Math.floor(i/24);if(o<60)return"just now";if(s<60)return`${s}m ago`;if(i<24)return`${i}h ago`;if(a<=7)return`${a}d ago`;const c=t.toLocaleString("en-US",{month:"short"}),l=t.getDate();return t.getFullYear()===r.getFullYear()?`${c} ${l}`:`${c} ${l}, ${t.getFullYear()}`}var Fa={PASSED:z.green,FAILED:z.red,TIMEDOUT:z.red,CANCELLED:z.yellow,INTERRUPTED:z.yellow,RUNNING:z.cyan,QUEUED:z.dim},Ga=(e,t)=>e?e.length>t?`${e.slice(0,t-1)}…`:e:"-",Ya=e=>{if(!e)return"-";const t=new Date(e);return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")} ${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`},Va=e=>(Fa[e]??(e=>e))(e),Wa=/\x1b\[[0-9;]*m/g,za=(e,t)=>{const r=e.replace(Wa,"").length,n=Math.max(0,t-r);return e+" ".repeat(n)},Ka=e=>`${JSON.stringify(e,null,2)}\n`,qa=e=>"oauth"===e.type?e.auth.context.orgId:void 0,Ja=(e,t,r)=>{if(!e)return;const n=e.toUpperCase();if(t.includes(n))return n;se(z.red(`Invalid ${r} value "${e}". Must be one of: ${t.join(", ").toLowerCase()}`)),process.exit(1)},Qa=(e,t,r)=>{if(401!==e.response.status&&403!==e.response.status||(se(z.red("Access denied.")),process.exit(1)),404===e.response.status&&r&&(se(z.red(r)),process.exit(1)),400===e.response.status){const t=e.error&&"object"==typeof e.error&&"error"in e.error?e.error.error:"Bad request";se(z.red(t)),process.exit(1)}e.error&&(se(z.red(`Failed to ${t}: ${e.response.status}`)),process.exit(1))};function Xa(e=""){process.stdout.write(`${e}\n`)}function Za(...e){process.stderr.write(`${e.join(" ")}\n`)}var ec="stably",tc=`https://registry.npmjs.org/${ec}/latest`,rc=de.object({version:de.string()});function nc(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 oc(e,t){const r=nc(e),n=nc(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 sc=r.join(U.homedir(),".stably"),ic=r.join(sc,"update-check.json"),ac=`https://registry.npmjs.org/${ec}/latest`,cc="1"===process.env.STABLY_DISABLE_UPDATE_CHECK,lc=de.object({lastCheck:de.number(),latestVersion:de.string()}),uc=!1,dc=!1,pc=async()=>{if(dc)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{}},fc=e=>{const t=e.toLowerCase();return t.startsWith("npm_config_")||"node_options"===t};!function(){if(cc||function(e=process.argv.slice(2)){return e.includes("upgrade")}())return;const e=function(){try{const e=g.readFileSync(ic,"utf-8");return lc.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 = '${ac}';\n const cacheFile = ${JSON.stringify(ic)};\n const cacheDir = ${JSON.stringify(sc)};\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{h(process.execPath,["--input-type=module","-e",e],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()}catch{}}(),null!=e&&oc(zr,e.latestVersion)){if(uc)return;uc=!0;let t=!1;const r=()=>{if(t)return;t=!0;const r=`${z.yellow(`update available (${zr} → ${e.latestVersion})`)} - run \`${ec} upgrade\` to get the latest version\n`;try{g.writeSync(2,r)}catch{}};process.once("beforeExit",r),process.once("exit",r)}}(),Ce.cwdChanged&&Vn.debug("Changed working directory",{cwd:Ce.newCwd});for(const e of Ce.envFilesLoaded)Vn.debug("Loaded env file",{path:e});for(const e of Ce.envFileErrors)Vn.warn(e);var hc=process.argv.findIndex(e=>"-v"===e||"--verbose"===e);-1!==hc&&process.argv.splice(hc,1);var mc=process.argv.findIndex(e=>"--no-telemetry"===e);-1!==mc&&process.argv.splice(mc,1),Vn.info("CLI starting",{version:zr,args:process.argv.slice(2),cwd:process.cwd()}),process.on("unhandledRejection",(e,t)=>{Vn.error("Unhandled promise rejection",{reason:e instanceof Error?{message:e.message,stack:e.stack}:e,promise:String(t)}),Vn.flush(),Vn.printLogFileInfo()}),process.on("uncaughtException",(e,t)=>{"EPIPE"!==e.code&&(Vn.error("Uncaught exception",{error:{message:e.message,stack:e.stack,name:e.name},origin:t}),Vn.flush(),Vn.printLogFileInfo())});var gc=new l;gc.name("stably").description("AI-assisted Playwright testing CLI").version(zr),gc.enablePositionalOptions(),gc.showHelpAfterError(),gc.exitOverride(),gc.configureHelp({subcommandTerm:e=>{const t=e.registeredArguments.map(e=>e.required?`<${e.name()}>`:`[${e.name()}]`).join(" ");return t?`${e.name()} ${t}`:e.name()}});var yc=[];gc.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>{yc.push(e)}});var bc=()=>{const e=gc.helpInformation().trimEnd();return e?`${e}\n`:""},vc=(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},wc=()=>{process.stdout.write(bc())};gc.command("help [command...]").description("Show help for a command (e.g. stably help create)").action(e=>{if(!e||0===e.length)return void wc();const t=vc(gc,e);if(!t)return process.stderr.write(`Unknown command: ${e.join(" ")}\n`),wc(),void(process.exitCode=1);var r;r=t,process.stdout.write((e=>{const t=e.helpInformation().trimEnd();return t?`${t}\n`:""})(r))}),gc.action(()=>Oa({mode:"chat",getHelpText:bc})),gc.command("login").description("Authenticate with Stably in your browser").action(Cn),gc.command("logout").description("Clear stored Stably credentials").action(async()=>{const e=zn();e&&(oe.warn(`Environment variables ${z.cyan("STABLY_API_KEY")} and ${z.cyan("STABLY_PROJECT_ID")} are set.`),oe.warn("They will continue to be used for authentication even after logout."),oe.warn("Unset them if you want to fully de-authenticate this shell/session."));const t=await yn();if(!t)return void se(e?z.yellow("No stored OAuth login found to clear."):z.yellow("You are not logged in."));const r=ie();r.start("Logging out..."),await(async e=>{try{await fetch(`${Jr}/api/backend/v1/logout`,{body:JSON.stringify({refresh_token:e}),headers:{"Content-Type":"application/json"},method:"POST"})}catch{}})(t.refreshToken),await vn(),await _n(),r.stop(z.green("✓ Logged out")),se(z.green("You have been logged out successfully."))}),gc.command("whoami").description("Show auth status and current project").action(async()=>{oe.info(`${z.bold("CLI Version:")} ${z.cyan(zr)}`);const e=zn();if(e){oe.info(z.dim("Authentication: Environment variables")),oe.info(` ${z.bold("API Key:")} ${z.cyan(e.apiKey.slice(0,8))}...`),oe.info(` ${z.bold("Project ID:")} ${z.cyan(e.projectId)}`);const t=await yn();if(t){let e;try{e=ln(t.accessToken).email}catch{e=void 0}oe.warn("Stored OAuth login detected but will be ignored (env auth takes precedence)."),e&&oe.info(` ${z.bold("OAuth Email:")} ${z.cyan(e)}`),oe.info(` ${z.bold("Tip:")} Unset env vars to use OAuth`)}return void se(z.green("Authenticated via environment variables"))}const t=await yn();if(!t)return void se(z.yellow("Not logged in. Run `stably login` to authenticate."));let n;try{n=ln(t.accessToken).email}catch{n=void 0}const o=await wn();if(!o)return oe.info(z.dim("Authentication: OAuth (not linked to a project)")),n&&oe.info(` ${z.bold("Email:")} ${z.cyan(n)}`),void se(z.yellow("Logged in but this directory is not linked to a project. Run `stably login` to link."));const s=await(async()=>un(process.cwd(),fn))(),i=s?r.dirname(s):process.cwd(),a=r.relative(process.cwd(),i)||".";oe.info(z.dim("Authentication: OAuth")),n&&oe.info(` ${z.bold("Email:")} ${z.cyan(n)}`),oe.info(` ${z.bold("Organization:")} ${z.cyan(o.orgName)}`),oe.info(` ${z.bold("Project:")} ${z.cyan(o.projectName)}`),oe.info(` ${z.bold("Linked at:")} ${z.dim(a)}`),se(z.green("Authenticated"))}),gc.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=>{ae(`Starting development server for port ${e.port}...`);const t=await qn(),r="oauth"===t.type?`${t.auth.context.orgName}-${t.auth.context.projectName}`.toLowerCase().replace(/[^a-z0-9-]/g,""):`project-${t.auth.projectId}`.toLowerCase(),n=ie();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}${z.underline(z.cyan(o.url))}]8;;`)}),gc.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 Oa({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)=>Oa({mode:"single",prompt:e,outputDir:t.output})),gc.command("verify <prompt...>").description("Verify your app works correctly against a prompt").option("-u, --url <url>","Starting URL to verify against").option("--max-budget <dollars>","Maximum budget in USD (default: 5)",Number.parseFloat).option("--no-interactive","Disable interactive verify preflight setup").action(async(e,t)=>{if(void 0!==t.maxBudget&&(!Number.isFinite(t.maxBudget)||t.maxBudget<=0))throw new Error("--max-budget must be a positive number");return Oa({mode:"verify",prompt:e,url:t.url,maxBudgetUsd:t.maxBudget,interactive:t.interactive})}),gc.command("internal-fix-run <runId>",{hidden:!0}).description("Internal: run fix session in subprocess").action(async e=>Oa({mode:"fix",runId:e})),gc.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 f("git rev-parse --is-inside-work-tree",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}})(process.cwd())||(Vn.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 Vn.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(_r))if(_r[r].detect({env:e,cwd:t}))return{isCi:!0,..._r[r].configuration({env:e,cwd:t})};return{isCi:Boolean(e.CI),...(r={env:e,cwd:t},{commit:Vt(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 Vn.debug("Run ID detected from CI environment",{runId:r}),t(r);Vn.debug("No explicit run ID or CI environment detected, checking last-run.json");const n=await(async()=>{try{const e=await un(process.cwd(),".stably/last-run.json");if(!e)return;const t=await q(e,"utf-8");return{...$a.parse(JSON.parse(t)),filePath:e}}catch{return}})();if(n){const e=(Date.now()-n.timestamp)/36e5;return Vn.debug("Run ID found in last-run.json",{runId:n.runId,timestamp:n.timestamp,filePath:n.filePath,ageHours:Math.round(e)}),e>24&&Vn.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)}Vn.debug("No run ID found in last-run.json")})(e);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));const r=await(async e=>{const t=await qn(),r=Qn(t),n=Jn(t),[,o]=process.argv;if(!o)throw new Error("Unable to determine CLI entrypoint for fix subprocess.");return await(async({runId:e,cliEntry:t,stablyApiKey:r,stablyProjectId:n,baseEnv:o=process.env,cwd:s=process.cwd(),execPath:i=process.execPath,execArgv:a=process.execArgv,stdio:c="inherit",spawnImpl:l=({command:e,args:t,options:r})=>h(e,t,r)})=>{const u=(({baseEnv:e,stablyApiKey:t,stablyProjectId:r})=>{const n={...e};for(const e of Object.keys(n))fc(e)&&delete n[e];return{...n,STABLY_API_KEY:t,STABLY_PROJECT_ID:r}})({baseEnv:o,stablyApiKey:r,stablyProjectId:n});return await new Promise((r,n)=>{const o=l({args:[...a,t,"internal-fix-run",e],command:i,options:{cwd:s,stdio:c,env:u}});o.once("error",n),o.once("exit",(e,t)=>{r(t?1:e??1)})})})({cliEntry:o,runId:e,stablyApiKey:r,stablyProjectId:n,cwd:process.cwd(),stdio:"inherit"})})(t);0!==r&&process.exit(r)}),gc.command("init").description("Initialize Playwright and Stably SDK in your project").action(async()=>Oa({mode:"init"})),gc.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;Xa(z.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(tc,{signal:e.signal});if(!t.ok)throw new Error(`Failed to fetch latest version: ${t.statusText}`);return rc.parse(await t.json()).version}finally{clearTimeout(t)}}();return{current:zr,latest:e,isOutdated:oc(zr,e)}}()}catch(e){return Za(z.red("Failed to check for updates:"),e instanceof Error?e.message:e),void(process.exitCode=1)}if(Xa(`Current version: ${z.yellow(r.current)}`),Xa(`Latest version: ${z.green(r.latest)}`),Xa(),!r.isOutdated)return void Xa(z.green("✓ You are already on the latest version!"));if(Xa(z.yellow(`⚠ A new version is available: ${r.current} → ${r.latest}`)),Xa(),t)return Xa(z.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")||e.includes(".npm\\_cacache"))return"npx";try{const t=f("npm root -g",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-npm"}catch{}if(e.includes("node_modules/stably")||e.includes("node_modules\\stably"))return"global-npm";try{const t=f("pnpm root -g",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-pnpm"}catch{}try{const t=f("yarn global dir",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-yarn-classic"}catch{}try{const t=f("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",`${ec}@latest`],description:`npm install -g ${ec}@latest`};case"global-pnpm":return{command:"pnpm",args:["add","-g",`${ec}@latest`],description:`pnpm add -g ${ec}@latest`};case"global-yarn-classic":return{command:"yarn",args:["global","add",`${ec}@latest`],description:`yarn global add ${ec}@latest`};case"npx":return{command:"npx",args:[`${ec}@latest`],description:`npx ${ec}@latest (always uses latest)`}}}(n);if("npx"===n)return Xa(z.dim("You are running via npx, which always fetches the latest version.")),void Xa(z.dim(`Simply run: ${z.white("npx stably")} to use the latest version.`));"unknown"===n?(Xa(z.yellow("Could not detect installation method. Falling back to npm.")),Xa()):"global-yarn-berry"===n&&(Xa(z.yellow("Yarn Berry does not support global packages. Falling back to npm.")),Xa()),Xa(`Upgrade command: ${z.cyan(o.description)}`),Xa(),Xa(z.cyan("Upgrading...")),Xa();try{await(s=o.command,i=o.args,new Promise((e,t)=>{const r=h(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)})})),Xa(),Xa(z.green("✓ Upgrade complete!")),Xa(z.dim(`Run ${z.white("stably --version")} to verify.`))}catch(e){Za(z.red("Upgrade failed:"),e instanceof Error?e.message:e),Xa(),Xa(z.dim("You can try manually running:")),Xa(z.cyan(` ${o.description}`)),process.exitCode=1}var s,i}(e));var _c=gc.command("env").description("Manage remote environments");_c.command("list").description("List available environments").action(async()=>{const e=await qn(),t=Jn(e),r=Qn(e);Vn.debug("Listing environments",{projectId:t});const n=await(o={auth:r,client:rn(),path:{projectId:t}},(o.client??Yr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/environments",...o}));var o;401!==n.response.status&&403!==n.response.status||(se(z.red("Access denied.")),process.exit(1)),n.error&&(se(z.red(`Failed to list environments: ${n.response.status}`)),process.exit(1));const{environments:s}=n.data;if(0!==s.length){process.stdout.write(`${z.bold("Environments")}\n\n`);for(const e of s){const t=e.isDefault?z.green(" (default)"):"",r=z.dim(` ${e.variableCount} variable${1!==e.variableCount?"s":""}`);process.stdout.write(` ${z.cyan(e.name)}${t}${r}\n`),e.description&&process.stdout.write(` ${z.dim(e.description)}\n`)}process.stdout.write("\n")}else process.stdout.write(z.dim("No environments found. Create one on your Stably dashboard.\n"))}),_c.command("inspect <name>").description("Show variable metadata (name, sensitive flag, updated timestamp)").action(e=>(async e=>{const t=await qn(),r=Jn(t),n=Qn(t);Vn.debug("Inspecting environment",{name:e,projectId:r});const o=await(s={auth:n,client:rn(),path:{projectId:r,environmentName:e}},(s.client??Yr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/environments/{environmentName}/inspect",...s}));var s;404===o.response.status&&(se(z.red(`Environment "${e}" not found. Run ${z.bold("stably env list")} to see available environments.`)),process.exit(1)),401!==o.response.status&&403!==o.response.status||(se(z.red("Access denied.")),process.exit(1)),o.error&&(se(z.red(`Failed to inspect environment: ${o.response.status}`)),process.exit(1));const{variables:i}=o.data;if(0!==i.length){process.stdout.write(`${z.bold(e)} ${z.dim(`(${i.length} variable${1!==i.length?"s":""})`)}\n\n`);for(const e of i){const t=z.dim(` [updated ${Ha(e.updatedAt)}]`);e.sensitive?process.stdout.write(` ${z.cyan(e.name)} ${z.yellow("[sensitive]")}${t}\n`):process.stdout.write(` ${z.cyan(e.name)}${t}\n`)}process.stdout.write("\n")}else process.stdout.write(z.dim(`Environment "${e}" has no variables.\n`))})(e));var Ic=gc.command("runs").description("View test run history");Ic.command("list").description("List recent test runs").option("-b, --branch <name>","Filter by branch name").option("-n, --limit <number>","Number of runs (default: 20, max: 100)").option("--after <runId>","Show runs newer than this runId").option("--before <runId>","Show runs older than this runId").option("--source <type>","Filter by source: local, ci, web").option("-s, --status <type>","Filter by status: queued, running, passed, failed, timedout, cancelled, interrupted").option("--suite <name>","Filter by suite name").option("--trigger <type>","Filter by trigger: manual, scheduled, ui, api, github_action, suite_run").option("--json","Output as JSON").action(async e=>{const t=await qn(),r=Jn(t),n=Qn(t),o=qa(t);let s;e.limit&&(s=parseInt(e.limit,10),(Number.isNaN(s)||s<1||s>100)&&(se(z.red("--limit must be an integer between 1 and 100")),process.exit(1)));const i=Ja(e.source,["LOCAL","CI","WEB"],"--source"),a=Ja(e.status,["QUEUED","RUNNING","PASSED","FAILED","TIMEDOUT","CANCELLED","INTERRUPTED"],"--status"),c=Ja(e.trigger,["MANUAL","SCHEDULED","UI","API","GITHUB_ACTION","SUITE_RUN"],"--trigger");Vn.debug("Listing runs",{projectId:r,branch:e.branch,limit:s,after:e.after,before:e.before,source:i,status:a,suite:e.suite,trigger:c});const l=await Vr({auth:n,client:rn(),headers:to(o),query:{projectId:r,branchName:e.branch,limit:s,afterRunId:e.after,beforeRunId:e.before,source:i,status:a,suiteName:e.suite,trigger:c}});Qa(l,"list runs");const{runs:u,hasMore:d}=l.data;e.json?process.stdout.write(Ka(l.data)):process.stdout.write(((e,t)=>{if(0===e.length)return z.dim("No runs found matching the specified filters.\n");const r=Math.min(40,Math.max(10,...e.map(e=>e.runId.length))),n={runId:{w:r+2,t:r},status:{w:14},branch:{w:32,t:30},started:{w:18}},o=[],s=`${za("Run ID",n.runId.w)}${za("Status",n.status.w)}${za("Branch",n.branch.w)}${za("Started",n.started.w)}Tests`;o.push(z.bold(s));for(const t of e){const e=Ga(t.runId,n.runId.t),r=Va(t.status),s=Ga(t.branchName,n.branch.t),i=Ya(t.startedAt),a=t.totalCount.toString();o.push(`${za(e,n.runId.w)}${za(r,n.status.w)}${za(s,n.branch.w)}${za(i,n.started.w)}${a}`)}if(t&&e.length>0){const t=e.at(-1)?.runId;t&&(o.push(""),o.push(z.dim(`Next page: stably runs list --before ${t}`)))}return o.push(""),o.join("\n")})(u,d))}),Ic.command("view <runId>").description("Show details for a specific run").option("--json","Output as JSON").action(async(e,t)=>{const r=await qn(),n=Qn(r),o=qa(r);Vn.debug("Viewing run",{runId:e});const s=await Wr({auth:n,client:rn(),headers:to(o),path:{runId:e},query:{detail:"full"}});if(Qa(s,"get run details",`Run "${e}" not found.`),t.json)process.stdout.write(Ka(s.data));else{const e=s.data;process.stdout.write((e=>{const t=[];if(t.push(z.bold(`Run ${e.runId}`)),t.push(` ${z.dim("Status:")} ${Va(e.status)}`),e.branchName&&t.push(` ${z.dim("Branch:")} ${e.branchName}`),e.commitSha&&t.push(` ${z.dim("Commit:")} ${e.commitSha.slice(0,7)}`),e.startedAt&&t.push(` ${z.dim("Started:")} ${Ya(e.startedAt)}`),null!==e.durationMs&&t.push(` ${z.dim("Duration:")} ${(e=>{if(null===e)return"-";const t=Math.floor(e/1e3);if(t<60)return`${t}s`;const r=Math.floor(t/60);return r<60?`${r}m ${t%60}s`:`${Math.floor(r/60)}h ${r%60}m`})(e.durationMs)}`),e.source&&t.push(` ${z.dim("Source:")} ${e.source.toLowerCase()}`),e.projectId){const r=`https://app.stably.ai/project/${e.projectId}/playwright/history/${e.runId}`;t.push(` ${z.dim("URL:")} ${z.cyan(z.underline(r))}`)}t.push("");const r=[];e.passedCount>0&&r.push(z.green(`${e.passedCount} passed`)),e.failedCount>0&&r.push(z.red(`${e.failedCount} failed`)),e.flakyCount>0&&r.push(z.yellow(`${e.flakyCount} flaky`)),e.timedoutCount>0&&r.push(z.red(`${e.timedoutCount} timedout`)),e.skippedCount>0&&r.push(z.dim(`${e.skippedCount} skipped`)),e.interruptedCount>0&&r.push(z.yellow(`${e.interruptedCount} interrupted`)),t.push(`${z.bold("Test Results:")} ${r.join(", ")}`);const n=e.testCases.filter(e=>"FAILED"===e.status||"TIMEDOUT"===e.status||"INTERRUPTED"===e.status||"FLAKY"===e.status);if(n.length>0){t.push(""),t.push(z.bold("Failed/Flaky Tests:"));for(const e of n){const r=e.status??"UNKNOWN",n=Fa[r]??(e=>e),o=e.location??"",s=e.title??e.testIdentifier,{attempts:i}=e,a=i?.length??0,c=a>1?` (${a} attempts)`:"",l=o?`${o} - `:"";t.push(` ${n(r)} ${l}${s}${z.dim(c)}`);const u=i?.at(-1);if(u?.errorMessage){const e=u.errorMessage.split("\n")[0]?.slice(0,100)??"";t.push(` ${z.dim(e)}`)}}}return t.push(""),t.join("\n")})(e))}}),gc.command("build",{hidden:!0}).description('(Deprecated) Use "stably create" instead').allowUnknownOption(!0).allowExcessArguments(!0).action(()=>{process.stderr.write('\n👋 "stably build" has moved! Use "stably create" instead:\n\n stably create "Read the .md files in /tests directory and then create playwright tests"\n\n'),process.exit(1)}),Na.forEach(({args:e,description:t,name:r})=>{gc.command(r).description(t).helpOption(!1).helpCommand(!1).allowUnknownOption(!0).allowExcessArguments(!0).passThroughOptions().action(()=>Ma({overrideArgs:e,subcommand:r}))});var Ec=()=>{0!==yc.length&&(process.stderr.write(yc.join("")),yc=[])};(async()=>{await(async()=>{if(!dc&&"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":zr,"node.version":process.version,"os.platform":process.platform}}),dc=!0}catch{}})();try{await gc.parseAsync(process.argv),Vn.info("CLI completed successfully")}catch(e){if(!(e=>!!e&&"object"==typeof e&&"code"in e)(e)){const t=e instanceof Error?e.message:String(e);return Vn.error(t,{stack:e instanceof Error?e.stack:void 0}),Ec(),Vn.flush(),Vn.printLogFileInfo(),await pc(),void(process.exitCode=1)}const t="number"==typeof e.exitCode?e.exitCode:1,r=process.argv.slice(2).find(e=>!e.startsWith("-")),n=!!r&&!!vc(gc,[r]);if(("commander.excessArguments"===e.code||"commander.unknownCommand"===e.code)&&r&&!n)return yc=[],Vn.warn("Unknown command",{command:r}),process.stderr.write(`command '${r}' not found\n`),wc(),void(process.exitCode=t);Vn.debug("Commander error",{code:e.code,exitCode:t}),Ec(),process.exitCode=t}finally{Vn.flush(),await pc()}})();