stably 4.12.23 β 4.12.24
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.
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*as r from"path";import n,{resolve as s,dirname as o,join as i,sep as a,normalize as c,basename as l}from"path";import{Command as u}from"commander";import{Buffer as d}from"buffer";import p,{exec as f,execSync as h,spawn as g,execFile as m,execFileSync as y}from"child_process";import b from"process";import*as w from"fs";import v,{mkdirSync as I,writeFileSync as T,rmSync as _,existsSync as E,statSync as S,readFileSync as x,appendFileSync as A,realpathSync as k,createReadStream as P,openSync as C,readSync as R,closeSync as U}from"fs";import{fileURLToPath as $,URL as L}from"url";import D,{tmpdir as N,constants as O}from"os";import"timers/promises";import B from"stream";import{debuglog as j,promisify as M,TextDecoder as F,TextEncoder as H}from"util";import{createSdkMcpServer as G,tool as W,query as V}from"@anthropic-ai/claude-agent-sdk";import{match as Y}from"ts-pattern";import{rm as z,readFile as q,mkdir as K,writeFile as J,unlink as Q,access as X,readdir as Z,stat as ee,appendFile as te}from"fs/promises";import re from"net";import{createInterface as ne}from"readline/promises";import se from"picocolors";import{simpleGit as oe}from"simple-git";import ie,{randomUUID as ae}from"crypto";import{log as ce,outro as le,spinner as ue,intro as de,select as pe,isCancel as fe}from"@clack/prompts";import he,{z as ge}from"zod";import me from"open";import ye from"http";import be from"pino";import we from"sonic-boom";import{z as ve}from"zod/v3";import Ie from"ws";import{useState as Te,useRef as _e,useEffect as Ee,useCallback as Se,useMemo as xe}from"react";import{jsx as Ae,jsxs as ke}from"react/jsx-runtime";import{createRequire as Pe}from"module";import{parseDocument as Ce}from"yaml";import{startTunnel as Re}from"@stablyhq/runner-sdk";var Ue=(e=>"undefined"!=typeof require?require:"undefined"!=typeof Proxy?new Proxy(e,{get:(e,t)=>("undefined"!=typeof require?require:e)[t]}):e)(function(e){if("undefined"!=typeof require)return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),$e={cwdChanged:!1,newCwd:void 0,envFilesLoaded:[],envFileErrors:[],remoteEnvName:void 0},Le=process.argv.findIndex(e=>"-C"===e||"--cwd"===e);if(-1!==Le&&process.argv[Le+1]){const e=process.argv[Le+1];process.chdir(e),$e.cwdChanged=!0,$e.newCwd=e,process.argv.splice(Le,2)}for(var De=[],Ne=0;Ne<process.argv.length;)if("--env-file"===process.argv[Ne]){const e=process.argv[Ne+1];e&&!e.startsWith("-")?(De.push(e),process.argv.splice(Ne,2)):Ne++}else Ne++;var Oe=process.argv.findIndex(e=>"--env"===e);-1!==Oe&&process.argv[Oe+1]&&!process.argv[Oe+1].startsWith("-")&&($e.remoteEnvName=process.argv[Oe+1],process.argv.splice(Oe,2));for(const t of De){const r=n.resolve(process.cwd(),t),s=e({path:r,override:!0,quiet:!0});if(s.error){const e=`warning: could not load env file: ${r} (${s.error.message})`;$e.envFileErrors.push(e),process.stderr.write(`${e}\n`)}else $e.envFilesLoaded.push(r)}var Be={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 je(e){return(/\d+(?!.*\d+)/.exec(e)||[])[0]}function Me(e){return e?/^(?:refs\/heads\/)?(?<branch>.+)$/i.exec(e)[1]:void 0}var Fe={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:Me(r?e.SYSTEM_PULLREQUEST_TARGETBRANCH:e.BUILD_SOURCEBRANCH),pr:t,isPr:r,prBranch:Me(r?e.SYSTEM_PULLREQUEST_SOURCEBRANCH:void 0),root:e.BUILD_REPOSITORY_LOCALPATH}}},He={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})},Ge={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})},We={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}}},Ve={detect:({env:e})=>Boolean(e.BUDDY_WORKSPACE_ID),configuration({env:e}){const t=je(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}}},Ye="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function ze(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var qe,Ke,Je,Qe,Xe,Ze,et,tt,rt={exports:{}};var nt,st,ot,it,at,ct,lt,ut,dt,pt,ft,ht,gt,mt,yt,bt={exports:{}},wt={};function vt(){if(ht)return ft;ht=1;const e=n,t=function(){if(ot)return st;ot=1;const e=n,t=function(){if(tt)return et;tt=1;const e="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,t=n,r=e?";":":",s=function(){if(Ze)return Xe;var e;function t(r,n,s){if("function"==typeof n&&(s=n,n={}),!s){if("function"!=typeof Promise)throw new TypeError("callback not provided");return new Promise(function(e,s){t(r,n||{},function(t,r){t?s(t):e(r)})})}e(r,n||{},function(e,t){e&&("EACCES"===e.code||n&&n.ignoreErrors)&&(e=null,t=!1),s(e,t)})}return Ze=1,e="win32"===process.platform||Ye.TESTING_WINDOWS?function(){if(Ke)return qe;Ke=1,qe=r,r.sync=function(r,n){return t(e.statSync(r),r,n)};var e=v;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 s=r[n].toLowerCase();if(s&&e.substr(-s.length).toLowerCase()===s)return!0}return!1}(t,r)}function r(r,n,s){e.stat(r,function(e,o){s(e,!e&&t(o,r,n))})}return qe}():function(){if(Qe)return Je;Qe=1,Je=t,t.sync=function(t,n){return r(e.statSync(t),n)};var e=v;function t(t,n,s){e.stat(t,function(e,t){s(e,!e&&r(t,n))})}function r(e,t){return e.isFile()&&function(e,t){var r=e.mode,n=e.uid,s=e.gid,o=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&&s===i||r&a&&n===o||r&(a|c)&&0===o}(e,t)}return Je}(),Xe=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}},Xe}(),o=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),i=(t,n)=>{const s=n.colon||r,o=t.match(/\//)||e&&t.match(/\\/)?[""]:[...e?[process.cwd()]:[],...(n.path||process.env.PATH||"").split(s)],i=e?n.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",a=e?i.split(s):[""];return e&&-1!==t.indexOf(".")&&""!==a[0]&&a.unshift(""),{pathEnv:o,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((s,i)=>{if(n===a.length)return r.all&&u.length?s(u):i(o(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;s(p(f,n,0))}),p=(e,t,n)=>new Promise((o,i)=>{if(n===c.length)return o(d(t+1));const a=c[n];s(e+a,{pathExt:l},(s,i)=>{if(!s&&i){if(!r.all)return o(e+a);u.push(e+a)}return o(p(e,t,n+1))})});return n?d(0).then(e=>n(null,e),n):d(0)};return et=a,a.sync=(e,r)=>{r=r||{};const{pathEnv:n,pathExt:a,pathExtExe:c}=i(e,r),l=[];for(let o=0;o<n.length;o++){const i=n[o],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(s.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 o(e)},et}(),r=function(){if(nt)return bt.exports;nt=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 bt.exports=e,bt.exports.default=e,bt.exports}();function s(n,s){const o=n.options.env||process.env,i=process.cwd(),a=null!=n.options.cwd,c=a&&void 0!==process.chdir&&!process.chdir.disabled;if(c)try{process.chdir(n.options.cwd)}catch(e){}let l;try{l=t.sync(n.command,{path:o[r({env:o})],pathExt:s?e.delimiter:void 0})}catch(e){}finally{c&&process.chdir(i)}return l&&(l=e.resolve(a?n.options.cwd:"",l)),l}return st=function(e){return s(e)||s(e,!0)}}(),r=function(){if(it)return wt;it=1;const e=/([()\][%!^"`<>&|;, *?])/g;return wt.command=function(t){return t.replace(e,"^$1")},wt.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},wt}(),s=function(){if(pt)return dt;pt=1;const e=v,t=function(){if(ut)return lt;ut=1;const e=ct?at:(ct=1,at=/^#!(.*)/);return lt=(t="")=>{const r=t.match(e);if(!r)return null;const[n,s]=r[0].replace(/#! ?/,"").split(" "),o=n.split("/").pop();return"env"===o?s:s?`${o} ${s}`:o}}();return dt=function(r){const n=Buffer.alloc(150);let s;try{s=e.openSync(r,"r"),e.readSync(s,n,0,150,0),e.closeSync(s)}catch(e){}return t(n.toString())}}(),o="win32"===process.platform,i=/\.(?:com|exe)$/i,a=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;return ft=function(n,c,l){c&&!Array.isArray(c)&&(l=c,c=null);const u={command:n,args:c=c?c.slice(0):[],options:l=Object.assign({},l),file:void 0,original:{command:n,args:c}};return l.shell?u:function(n){if(!o)return n;const c=function(e){e.file=t(e);const r=e.file&&s(e.file);return r?(e.args.unshift(e.file),e.command=r,t(e)):e.file}(n),l=!i.test(c);if(n.options.forceShell||l){const t=a.test(c);n.command=e.normalize(n.command),n.command=r.command(n.command),n.args=n.args.map(e=>r.argument(e,t));const s=[n.command].concat(n.args).join(" ");n.args=["/d","/s","/c",`"${s}"`],n.command=process.env.comspec||"cmd.exe",n.options.windowsVerbatimArguments=!0}return n}(u)}}var It=ze(function(){if(yt)return rt.exports;yt=1;const e=p,t=vt(),r=function(){if(mt)return gt;mt=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 gt={hookChildProcess:function(t,n){if(!e)return;const s=t.emit;t.emit=function(e,o){if("exit"===e){const e=r(o,n);if(e)return s.call(t,"error",e)}return s.apply(t,arguments)}},verifyENOENT:r,verifyENOENTSync:function(r,n){return e&&1===r&&!n.file?t(n.original,"spawnSync"):null},notFoundError:t},gt}();function n(n,s,o){const i=t(n,s,o),a=e.spawn(i.command,i.args,i.options);return r.hookChildProcess(a,i),a}return rt.exports=n,rt.exports.spawn=n,rt.exports.sync=function(n,s,o){const i=t(n,s,o),a=e.spawnSync(i.command,i.args,i.options);return a.error=a.error||r.verifyENOENTSync(a.status,i),a},rt.exports._parse=t,rt.exports._enoent=r,rt.exports}());function Tt(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 _t=(e,t)=>({name:`SIGRT${t+1}`,number:Et+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),Et=34,St=[{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"}],xt=()=>{const e=(()=>{const e=64-Et+1;return Array.from({length:e},_t)})();return[...St,...e].map(At)},At=({name:e,number:t,description:r,action:n,forced:s=!1,standard:o})=>{const{signals:{[e]:i}}=O,a=void 0!==i;return{name:e,number:a?i:t,description:r,supported:a,action:n,forced:s,standard:o}},kt=({name:e,number:t,description:r,supported:n,action:s,forced:o,standard:i})=>[e,{name:e,number:t,description:r,supported:n,action:s,forced:o,standard:i}],Pt=(()=>{const e=xt();return Object.fromEntries(e.map(kt))})();(()=>{const e=xt(),t=Array.from({length:65},(t,r)=>((e,t)=>{const r=((e,t)=>{const r=t.find(({name:t})=>O.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:s,supported:o,action:i,forced:a,standard:c}=r;return{[e]:{name:n,number:e,description:s,supported:o,action:i,forced:a,standard:c}}})(r,e));Object.assign({},...t)})();var Ct=({stdout:e,stderr:t,all:r,error:n,signal:s,exitCode:o,command:i,escapedCommand:a,timedOut:c,isCanceled:l,killed:u,parsed:{options:{timeout:d,cwd:p=b.cwd()}}})=>{o=null===o?void 0:o;const f=void 0===(s=null===s?void 0:s)?void 0:Pt[s].description,h=(({timedOut:e,timeout:t,errorCode:r,signal:n,signalDescription:s,exitCode:o,isCanceled:i})=>e?`timed out after ${t} milliseconds`:void 0!==r?`failed with ${r}`:void 0!==n?`was killed with ${n} (${s})`:void 0!==o?`failed with exit code ${o}`:"failed")({timedOut:c,timeout:d,errorCode:n&&n.code,signal:s,signalDescription:f,exitCode:o,isCanceled:l}),g=`Command ${h}: ${i}`,m="[object Error]"===Object.prototype.toString.call(n),y=m?`${g}\n${n.message}`:g,w=[y,t,e].filter(Boolean).join("\n");return m?(n.originalMessage=n.message,n.message=w):n=new Error(w),n.shortMessage=y,n.command=i,n.escapedCommand=a,n.exitCode=o,n.signal=s,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},Rt=["stdin","stdout","stderr"],Ut=[];Ut.push("SIGHUP","SIGINT","SIGTERM"),"win32"!==process.platform&&Ut.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),"linux"===process.platform&&Ut.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var $t,Lt,Dt=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,Nt=Symbol.for("signal-exit emitter"),Ot=globalThis,Bt=Object.defineProperty.bind(Object),jt=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(Ot[Nt])return Ot[Nt];Bt(Ot,Nt,{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 s of this.listeners[e])n=!0===s(t,r)||n;return"exit"===e&&(n=this.emit("afterExit",t,r)||n),n}},Mt=class{},Ft=globalThis.process;Dt(Ft)?new class extends Mt{#e="win32"===Ft.platform?"SIGINT":"SIGHUP";#t=new jt;#r;#n;#s;#o={};#i=!1;constructor(e){super(),this.#r=e,this.#o={};for(const t of Ut)this.#o[t]=()=>{const r=this.#r.listeners(t);let{count:n}=this.#t;const s=e;if("object"==typeof s.__signal_exit_emitter__&&"number"==typeof s.__signal_exit_emitter__.count&&(n+=s.__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.#s=e.reallyExit,this.#n=e.emit}onExit(e,t){if(!Dt(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 Ut)try{const t=this.#o[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,Ut.forEach(e=>{const t=this.#o[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.#s,this.#t.count-=1)}#c(e){return Dt(this.#r)?(this.#r.exitCode=e||0,this.#t.emit("exit",this.#r.exitCode,null),this.#s.call(this.#r,this.#r.exitCode)):0}#a(e,...t){const r=this.#n;if("exit"===e&&Dt(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)}}(Ft):new class extends Mt{onExit(){return()=>{}}load(){}unload(){}},new TextEncoder,function(){if(Lt)return $t;Lt=1;const{PassThrough:e}=B;$t=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",s),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",s.bind(null,e)),e.once("error",r.emit.bind(r,"error")),e.pipe(r,{end:!1}),this)}function s(e){!(t=t.filter(function(t){return t!==e})).length&&r.readable&&r.end()}}}();var Ht=(async()=>{})().constructor.prototype;["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(Ht,e)]);var Gt=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],Wt=/^[\w.-]+$/,Vt=j("execa").enabled,Yt=(e,t)=>String(e).padStart(t,"0"),zt=(e,t,r={})=>{const s=It._parse(e,t,r);return e=s.command,t=s.args,(r={maxBuffer:1e8,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:(r=s.options).cwd||b.cwd(),execPath:b.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:Vt,...r}).env=(({env:e,extendEnv:t,preferLocal:r,localDir:s,execPath:o})=>{const i=t?{...b.env,...e}:e;return r?(({env:e=b.env,...t}={})=>{const r=Tt({env:e={...e}});return t.path=e[r],e[r]=(({cwd:e=b.cwd(),path:t=b.env[Tt()],preferLocal:r=!0,execPath:s=b.execPath,addExecPath:o=!0}={})=>{const i=e instanceof URL?$(e):e,a=n.resolve(i),c=[];return r&&((e,t)=>{let r;for(;r!==t;)e.push(n.join(t,"node_modules/.bin")),r=t,t=n.resolve(t,"..")})(c,a),o&&((e,t,r)=>{const s=t instanceof URL?$(t):t;e.push(n.resolve(r,s,".."))})(c,s,a),[...c,t].join(n.delimiter)})(t),e})({env:i,cwd:s,execPath:o}):i})(r),r.stdio=(e=>{if(!e)return;const{stdio:t}=e;if(void 0===t)return Rt.map(t=>e[t]);if((e=>Rt.some(t=>void 0!==e[t]))(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${Rt.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,Rt.length);return Array.from({length:r},(e,r)=>t[r])})(r),"win32"===b.platform&&"cmd"===n.basename(e,".exe")&&t.unshift("/q"),{file:e,args:t,options:r,parsed:s}},qt=(e,t,r)=>"string"==typeof t||d.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 Kt(e,t,r){const n=zt(e,t,r),s=((e,t)=>Gt(e,t).join(" "))(e,t),o=((e,t)=>Gt(e,t).map(e=>(e=>"string"!=typeof e||Wt.test(e)?e:`"${e.replaceAll('"','\\"')}"`)(e)).join(" "))(e,t);((e,{verbose:t})=>{t&&b.stderr.write(`[${(()=>{const e=new Date;return`${Yt(e.getHours(),2)}:${Yt(e.getMinutes(),2)}:${Yt(e.getSeconds(),2)}.${Yt(e.getMilliseconds(),3)}`})()}] ${e}\n`)})(o,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),x(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=p.spawnSync(n.file,n.args,{...n.options,input:i})}catch(e){throw Ct({error:e,stdout:"",stderr:"",all:"",command:s,escapedCommand:o,parsed:n,timedOut:!1,isCanceled:!1,killed:!1})}const c=qt(n.options,a.stdout,a.error),l=qt(n.options,a.stderr,a.error);if(a.error||0!==a.status||null!==a.signal){const e=Ct({stdout:c,stderr:l,error:a.error,signal:a.signal,exitCode:a.status,command:s,escapedCommand:o,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:s,escapedCommand:o,exitCode:0,stdout:c,stderr:l,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}}function Jt(e){try{return Kt("git",["rev-parse","HEAD"],e).stdout}catch{return}}function Qt(e){try{const t=Kt("git",["rev-parse","--abbrev-ref","HEAD"],e).stdout;if("HEAD"===t){const t=Kt("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 Xt=/^(?:.*)@(?:.*):(?:\d+\/)?(.*)\.git$/,Zt=/^\/(.*)\.git$/;function er(e){if(e){if(e.match(Xt))return e.replace(Xt,"$1");try{return new URL(e).pathname.replace(Zt,"$1")}catch{return}}}var tr,rr={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:er(e.BUILDKITE_REPO),pr:t,isPr:r,prBranch:r?e.BUILDKITE_BRANCH:void 0,root:e.BUILDKITE_BUILD_CHECKOUT_PATH}}},nr={detect:({env:e})=>Boolean(e.CIRCLECI),configuration({env:e}){const t=e.CIRCLE_PR_NUMBER||je(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}`}}},sr="https://cirrus-ci.com",or={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:`${sr}/build/${e.CIRRUS_BUILD_ID}`,job:e.CIRRUS_TASK_ID,jobUrl:`${sr}/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}}},ir={detect:({env:e})=>Boolean(e.CODEBUILD_BUILD_ID),configuration:({env:e,cwd:t})=>({name:"AWS CodeBuild",service:"codebuild",commit:Jt({env:e,cwd:t}),build:e.CODEBUILD_BUILD_ID,branch:Qt({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})},ar={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}}},cr={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}}},lr=e=>({commit:Jt(e),branch:Qt(e)}),ur=({env:e})=>{try{const t=e.GITHUB_EVENT_PATH?JSON.parse(x(e.GITHUB_EVENT_PATH,"utf-8")):void 0;if(t&&t.pull_request)return{branch:t.pull_request.base?Me(t.pull_request.base.ref):void 0,pr:t.pull_request.number}}catch{}return{pr:void 0,branch:void 0}},dr={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=Me("pull_request_target"===e.GITHUB_EVENT_NAME?`refs/pull/${(e=>{const t=e.GITHUB_EVENT_PATH?JSON.parse(x(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?ur({env:e}):void 0}}},pr={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}}},fr={detect:({env:e})=>Boolean(e.JENKINS_URL),configuration({env:e,cwd:t}){const r=e.ghprbPullId||e.gitlabMergeRequestId||e.CHANGE_ID,n=Boolean(r),s=e.GIT_LOCAL_BRANCH||e.GIT_BRANCH||e.gitlabBranch||e.BRANCH_NAME;return{name:"Jenkins",service:"jenkins",commit:e.ghprbActualCommit||e.GIT_COMMIT||Jt({env:e,cwd:t}),branch:n?e.ghprbTargetBranch||e.gitlabTargetBranch:s,build:e.BUILD_NUMBER,buildUrl:e.BUILD_URL,root:e.WORKSPACE,pr:r,isPr:n,prBranch:n?e.ghprbSourceBranch||e.gitlabSourceBranch||s:void 0}}},hr={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}}},gr={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})},mr={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}}},yr={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}}},br={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}}},wr={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||Jt({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}}},vr={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}}},Ir={};function Tr(){if(tr)return Ir;tr=1,Object.defineProperty(Ir,"__esModule",{value:!0}),Ir.of=Ir.PropertiesFile=void 0;var e,t=(e=v)&&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(),s=e.substring(r+1).trim();if(this.objs.hasOwnProperty(n))if(Array.isArray(this.objs[n]))this.objs[n].push(s);else{let e=this.objs[n];this.objs[n]=[e,s]}else{const e=s.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 Ir.PropertiesFile=r,Ir.of=function(...e){let t=new r;return t.of.apply(t,e),t},Ir}var _r=ze(Tr()),Er={root:"teamcity.build.workingDir",branch:"teamcity.build.branch"},Sr=e=>{try{return _r.of(e)}catch{return}},xr=({env:e,cwd:t})=>{const r=e.TEAMCITY_BUILD_PROPERTIES_FILE?Sr(e.TEAMCITY_BUILD_PROPERTIES_FILE):void 0,n=r?r.get("teamcity.configuration.properties.file"):void 0,s=n?Sr(n):n;return Object.fromEntries(Object.keys(Er).map(n=>[n,(r?r.get(Er[n]):void 0)||(s?s.get(Er[n]):void 0)||("branch"===n?Qt({env:e,cwd:t}):void 0)]))},Ar={appveyor:Be,azurePipelines:Fe,bamboo:He,bitbucket:Ge,bitrise:We,buddy:Ve,buildkite:rr,circleci:nr,cirrus:or,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:ir,codefresh:ar,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:cr,github:dr,gitlab:pr,jenkins:fr,netlify:hr,puppet:gr,sail:mr,screwdriver:yr,scrutinizer:br,semaphore:wr,shippable:vr,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,...xr({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:Me(e.JB_SPACE_GIT_BRANCH),slug:t&&r?`${t.toLowerCase()}/${r}`:void 0}}}},kr=["test","bug","flake","ui_change","other"],Pr={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."},Cr=e=>Pr[e],Rr=class e{git;config;snapshotTreeHash;snapshotIndexPath;constructor(e){this.config=e,this.git=oe({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=i(N(),`git-diff-tracker-${ae()}.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=i(N(),`git-diff-tracker-${ae()}.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 Ur(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 Ur(this.snapshotIndexPath),this.snapshotIndexPath=void 0),this.snapshotTreeHash=void 0}};async function Ur(e){try{await Q(e)}catch{}}var $r="x-stably-org-id",Lr={bodySerializer:e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t)},Dr=({allowReserved:e,explode:t,name:r,style:n,value:s})=>{if(!t){const t=(e?s:s.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 o=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(n),i=s.map(t=>"label"===n||"simple"===n?e?t:encodeURIComponent(t):Nr({allowReserved:e,name:r,value:t})).join(o);return"label"===n||"matrix"===n?o+i:i},Nr=({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)}`},Or=({allowReserved:e,explode:t,name:r,style:n,value:s,valueOnly:o})=>{if(s instanceof Date)return o?s.toISOString():`${r}=${s.toISOString()}`;if("deepObject"!==n&&!t){let t=[];Object.entries(s).forEach(([r,n])=>{t=[...t,r,e?n:encodeURIComponent(n)]});const o=t.join(",");switch(n){case"form":return`${r}=${o}`;case"label":return`.${o}`;case"matrix":return`;${r}=${o}`;default:return o}}const i=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(n),a=Object.entries(s).map(([t,s])=>Nr({allowReserved:e,name:"deepObject"===n?`${r}[${t}]`:t,value:s})).join(i);return"label"===n||"matrix"===n?i+a:a},Br=/\{[^{}]+\}/g;function jr(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 Mr,Fr=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},Hr=({parameters:e={},...t}={})=>r=>{const n=[];if(r&&"object"==typeof r)for(const s in r){const o=r[s];if(null==o)continue;const i=e[s]||t;if(Array.isArray(o)){const e=Dr({allowReserved:i.allowReserved,explode:!0,name:s,style:"form",value:o,...i.array});e&&n.push(e)}else if("object"==typeof o){const e=Or({allowReserved:i.allowReserved,explode:!0,name:s,style:"deepObject",value:o,...i.object});e&&n.push(e)}else{const e=Nr({allowReserved:i.allowReserved,name:s,value:o});e&&n.push(e)}}return n.join("&")},Gr=(e,t)=>!!t&&!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`)),Wr=e=>(({baseUrl:e,path:t,query:r,querySerializer:n,url:s})=>{let o=(e??"")+(s.startsWith("/")?s:`/${s}`);t&&(o=(({path:e,url:t})=>{let r=t;const n=t.match(Br);if(n)for(const t of n){let n=!1,s=t.substring(1,t.length-1),o="simple";s.endsWith("*")&&(n=!0,s=s.substring(0,s.length-1)),s.startsWith(".")?(s=s.substring(1),o="label"):s.startsWith(";")&&(s=s.substring(1),o="matrix");const i=e[s];if(null==i)continue;if(Array.isArray(i)){r=r.replace(t,Dr({explode:n,name:s,style:o,value:i}));continue}if("object"==typeof i){r=r.replace(t,Or({explode:n,name:s,style:o,value:i,valueOnly:!0}));continue}if("matrix"===o){r=r.replace(t,`;${Nr({name:s,value:i})}`);continue}const a=encodeURIComponent("label"===o?`.${i}`:i);r=r.replace(t,a)}return r})({path:t,url:o}));let i=r?n(r):"";return i.startsWith("?")&&(i=i.substring(1)),i&&(o+=`?${i}`),o})({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:"function"==typeof e.querySerializer?e.querySerializer:Hr(e.querySerializer),url:e.url}),Vr=(e,t)=>{const r={...e,...t};return r.baseUrl?.endsWith("/")&&(r.baseUrl=r.baseUrl.substring(0,r.baseUrl.length-1)),r.headers=zr(e.headers,t.headers),r},Yr=e=>{const t=[];return e.forEach((e,r)=>{t.push([r,e])}),t},zr=(...e)=>{const t=new Headers;for(const r of e){if(!r)continue;const e=r instanceof Headers?Yr(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},qr=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}},Kr=Hr({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Jr={"Content-Type":"application/json"},Qr=(e={})=>({...Lr,headers:Jr,parseAs:"auto",querySerializer:Kr,...e}),Xr=(e={})=>{let t=Vr(Qr(),e);const r=()=>({...t}),n={error:new qr,request:new qr,response:new qr},s=async e=>{const r={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:zr(t.headers,e.headers),serializedBody:void 0};return r.security&&await(async({security:e,...t})=>{for(const r of e){if(Gr(t,r.name))continue;const e=await Fr(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:Wr(r)}},o=async e=>{const{opts:t,url:r}=await s(e),o={redirect:"follow",...t,body:jr(t)};let i=new Request(r,o);for(const e of n.request.fns)e&&(i=await e(i,t));const a=t.fetch;let c=await a(i);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=>o({...t,method:e}),a=e=>async t=>{const{opts:r,url:o}=await s(t);return(({onRequest:e,onSseError:t,onSseEvent:r,responseTransformer:n,responseValidator:s,sseDefaultRetryDelay:o,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=o??3e3,f=0;const h=u.signal??(new AbortController).signal;for(;!h.aborted;){f++;const o=u.headers instanceof Headers?u.headers:new Headers(u.headers);void 0!==d&&o.set("Last-Event-ID",d);try{const t={redirect:"follow",...u,body:u.serializedBody,headers:o,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 g="";const m=()=>{try{f.cancel()}catch{}};h.addEventListener("abort",m);try{for(;;){const{done:e,value:t}=await f.read();if(e)break;g+=t;const o=g.split("\n\n");g=o.pop()??"";for(const e of o){const t=e.split("\n"),o=[];let i,a;for(const e of t)if(e.startsWith("data:"))o.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(o.length){const e=o.join("\n");try{a=JSON.parse(e),l=!0}catch{a=e}}l&&(s&&await s(a),n&&(a=await n(a))),r?.({data:a,event:i,id:d,retry:c}),o.length&&(yield a)}}}finally{h.removeEventListener("abort",m),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 s=new Request(e,t);for(const e of n.request.fns)e&&(s=await e(s,r));return s},url:o})};return{buildUrl:Wr,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:o,setConfig:e=>(t=Vr(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")}},Zr=Xr(Qr({baseUrl:"https://api.stably.ai"})),en=e=>(e.client??Zr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs",...e}),tn=e=>(e.client??Zr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}",...e}),rn="4.12.23",nn=process.env.STABLY_API_URL||"https://api.stably.ai",sn=e=>{const t=new URL(e);return t.protocol="http:"===t.protocol?"ws:":"wss:",t},on=process.env.AUTH_URL||"https://auth.stably.ai",an=process.env.AUTH_CLIENT_ID||"288007877071cce81f269428ea78653a",cn=process.env.AI_PROXY_URL||"https://ai-proxy.stably.ai",ln=process.env.STABLY_AUTOHEAL_WS_URL||new URL("/autoheal",sn(nn)).toString(),un=process.env.STABLY_CREATE_PROGRESS_WS_URL||new URL("/create-progress",sn(nn)).toString(),dn="http://localhost:9876/auth/callback",pn=()=>Mr||(Mr=Xr(Qr({baseUrl:nn,headers:{"X-STABLY-CLI-VERSION":rn,"X-STABLY-SOURCE":"cli"}}))),fn=async(e,t)=>{const r=await(n={body:{accessToken:e,orgId:t},client:pn()},(n.client??Zr).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},hn=ge.object({org_id:ge.string(),org_name:ge.string()}),gn=ge.object({email:ge.string(),org_id_to_org_member_info:ge.record(ge.string(),hn).optional(),org_member_info:hn.optional(),user_id:ge.string()});ge.object({email:ge.string(),firstName:ge.string().optional(),lastName:ge.string().optional(),organizations:ge.array(ge.object({id:ge.string(),name:ge.string()})),userId:ge.string()});var mn,yn=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)},bn=e=>{try{const t=gn.parse(yn(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"}`)}},wn=async(e,t)=>{let r=e;const{root:s}=n.parse(r);for(;r!==s;){const e=n.join(r,t);try{return await X(e),e}catch{r=n.dirname(r)}}},vn=n.join(D.homedir(),".stably"),In=n.join(vn,"auth.json"),Tn=".stably",_n="project.json",En=he.object({accessToken:he.string(),expiresAt:he.number(),idToken:he.string().optional(),refreshToken:he.string()}),Sn=he.object({orgId:he.string(),orgName:he.string(),projectId:he.string(),projectName:he.string()}),xn=async()=>{try{const e=await q(In,"utf-8");return En.parse(JSON.parse(e))}catch{return}},An=async e=>{await K(vn,{recursive:!0}),await J(In,JSON.stringify(e,null,2),{mode:384})},kn=async()=>{try{await Q(In)}catch{}},Pn=async()=>{try{const e=await wn(process.cwd(),Tn);if(!e)return;const t=n.join(e,_n),r=await q(t,"utf-8");return Sn.parse(JSON.parse(r))}catch{return}},Cn=async()=>{try{const e=await wn(process.cwd(),Tn);e&&await Q(n.join(e,_n))}catch{}},Rn=e=>Date.now()>=e.expiresAt-3e5,Un=async e=>{const t=new URLSearchParams({client_id:an,grant_type:"refresh_token",refresh_token:e}),r=await fetch(`${on}/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}},$n=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`,Ln=(e,t,r)=>{e.writeHead(t,{"Content-Type":"text/html"}),e.end(r)},Dn=(e,t)=>{const r=new URLSearchParams({client_id:an,code_challenge:e,code_challenge_method:"S256",redirect_uri:dn,response_type:"code",state:t});return`${on}/propelauth/oauth/authorize?${r.toString()}`},Nn=async e=>{const t=ue();let r;t.start("Loading user info...");try{r=bn(e.accessToken),t.stop(se.green(`β Logged in as ${se.cyan(r.email)}`))}catch(e){t.stop(se.red("β Failed to load user info"));const r=e instanceof Error?e.message:"Unknown error";return ce.error(r),{success:!1}}const s=await(async e=>{if(0===e.length)return void ce.error("You don't belong to any organizations.");if(1===e.length)return ce.info(`Using organization: ${se.cyan(e[0].name)}`),e[0];if(!process.stdin.isTTY)return ce.info(`Auto-selecting organization: ${se.cyan(e[0].name)}`),e[0];const t=await pe({message:"Select an organization",options:[...e].sort((e,t)=>e.name.localeCompare(t.name)).map(e=>({label:e.name,value:e.id}))});return fe(t)?void 0:e.find(e=>e.id===t)})(r.organizations);if(!s)return ce.warn("Organization selection cancelled."),{success:!1};let o;t.start("Getting org credentials...");try{const r=await fn(e.accessToken,s.id);o={accessToken:r.accessToken,expiresAt:Date.now()+1e3*r.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken},t.stop(se.green("β Credentials obtained"))}catch(e){t.stop(se.red("β Failed to get org credentials"));const r=e instanceof Error?e.message:"Unknown error";return ce.error(r),{success:!1}}const i=await(async(e,t)=>{const r=ue();let n;r.start("Loading projects...");try{n=await(async({accessToken:e,orgId:t})=>{const r=await(n={auth:e,client:pn(),path:{orgId:t}},(n.client??Zr).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(se.green("β Projects loaded"))}catch(e){r.stop(se.red("β Failed to load projects"));const t=e instanceof Error?e.message:"Unknown error";return void ce.error(t)}if(0===n.length)return ce.error("No projects found in this organization."),void ce.info(`Create a project at ${se.underline(se.cyan("https://app.stably.ai"))}`);if(1===n.length)return ce.info(`Using project: ${se.cyan(n[0].name)}`),n[0];if(!process.stdin.isTTY)return ce.info(`Auto-selecting project: ${se.cyan(n[0].name)}`),n[0];const s=await pe({message:"Select a project",options:n.map(e=>({label:e.name,value:e.id}))});return fe(s)?void 0:n.find(e=>e.id===s)})(o.accessToken,s.id);return i?(await(async e=>{const t=n.join(process.cwd(),Tn),r=n.join(t,_n);await K(t,{recursive:!0}),await J(r,JSON.stringify(e,null,2)),await(async e=>{const t=n.join(e,".gitignore"),r="# Stably CLI (only docs/ are tracked)\n.stably/*\n!.stably/docs/";try{const e=await q(t,"utf-8"),n=e.split("\n").map(e=>e.trim());if(n.includes(".stably/*")&&n.includes("!.stably/docs/"))return;const s=/^# Stably CLI\n\.stably\/?$/m,o=/^\.stably\/?$/m;if(s.test(e)){const n=e.replace(s,`\n${r}\n`);await J(t,n)}else if(o.test(e)){const n=e.replace(o,`\n${r}\n`);await J(t,n)}else await te(t,`\n${r}\n`)}catch{await J(t,`${r}\n`)}})(process.cwd())})({orgId:s.id,orgName:s.name,projectId:i.id,projectName:i.name}),ce.info(se.dim("Linked this directory to your Stably project.")),{scopedTokens:o,success:!0}):(ce.warn("Project selection cancelled."),{success:!1})},On=async()=>{if(is())return ce.warn(`Environment variables ${se.cyan("STABLY_API_KEY")} and ${se.cyan("STABLY_PROJECT_ID")} are set.`),ce.warn("These will be used for authentication instead of OAuth login."),ce.warn("To use OAuth login, unset these environment variables first."),void le(se.yellow("Login skipped - using environment variable authentication."));const e=await xn();if(e){if(!Rn(e)){if(await Pn())return void le(se.yellow("You are already logged in. Run `stably logout` first to log out."));ce.info("You are logged in but haven't selected a project yet.");const t=await Nn(e);return void(t.success?(await An(t.scopedTokens),le(se.green("Setup complete! You can now use Stably CLI."))):le(se.yellow("Setup incomplete. Run `stably login` to try again.")))}const t=ue();t.start("Refreshing session...");try{const r=await Un(e.refreshToken);t.stop(se.green("β Session refreshed"));const n=await Pn();if(n){t.start("Getting org credentials...");try{const e=await fn(r.accessToken,n.orgId),s={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:r.idToken,refreshToken:r.refreshToken};await An(s),t.stop(se.green("β Credentials obtained")),le(se.green("Login successful"))}catch{await An(r),t.stop(se.yellow("Using full credentials")),le(se.green("Login successful"))}}else{const e=await Nn(r);e.success?(await An(e.scopedTokens),le(se.green("Setup complete! You can now use Stably CLI."))):le(se.yellow("Setup incomplete. Run `stably login` to try again."))}return}catch{t.stop(se.yellow("Session expired, proceeding with fresh login...")),await kn(),await Cn()}}const{authorizeUrl:t,serverReady:r,waitForCallback:n}=(()=>{const{authorizeUrl:e,codeVerifier:t,state:r}=(()=>{const e=ie.randomBytes(32).toString("base64url"),t=(r=e,ie.createHash("sha256").update(r).digest("base64url"));var r;const n=ie.randomBytes(16).toString("base64url");return{authorizeUrl:Dn(t,n),codeVerifier:e,state:n}})(),{ready:n,result:s}=(e=>{let t,r;return{ready:new Promise((e,n)=>{t=e,r=n}),result:new Promise((n,s)=>{const o=setTimeout(()=>{a.close(),n({error:"Login timed out",success:!1})},3e5),i=()=>{clearTimeout(o)},a=ye.createServer((t,r)=>{const s=new L(t.url||"","http://localhost:9876");if("/auth/callback"!==s.pathname)return r.writeHead(404),void r.end("Not found");const o=s.searchParams.get("code"),c=s.searchParams.get("state"),l=s.searchParams.get("error");return l?(Ln(r,400,$n(l)),i(),a.close(),void n({error:l,success:!1})):o&&c?c!==e?(Ln(r,400,$n("Invalid state parameter (possible CSRF attack)")),i(),a.close(),void n({error:"State mismatch",success:!1})):(Ln(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:o,state:c,success:!0})):(Ln(r,400,$n("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 s(e)}const t=new Error(`Failed to start callback server: ${e.message}`);r(t),s(t)}),a.listen(9876,()=>{t()})})}})(r);return{authorizeUrl:e,serverReady:n,waitForCallback:async()=>{const e=await s;if(!e.success)throw new Error(e.error);return(async(e,t)=>{const r=new URLSearchParams({client_id:an,code:e,code_verifier:t,grant_type:"authorization_code",redirect_uri:dn}),n=await fetch(`${on}/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 s=await n.json();return{accessToken:s.access_token,expiresAt:Date.now()+1e3*s.expires_in,idToken:s.id_token,refreshToken:s.refresh_token}})(e.code,t)}}})();await r,ce.info("Opening browser for authentication..."),ce.info(se.dim("If browser doesn't open, visit:")),ce.info(`]8;;${t}${se.underline(se.cyan(t))}]8;;`);try{await me(t)}catch{ce.warn("Could not open browser automatically. Please open the URL above manually.")}const s=ue();let o;s.start("Waiting for authentication...");try{o=await n(),s.stop(se.green("β Authentication successful"))}catch(e){s.stop(se.red("β Authentication failed"));const t=e instanceof Error?e.message:"Unknown error";le(se.red(`Login failed: ${t}`)),process.exit(1)}const i=await Nn(o);i.success?(await An(i.scopedTokens),le(se.green("Setup complete! You can now use Stably CLI."))):(le(se.yellow("Setup incomplete. Run `stably login` to try again.")),process.exit(1))},Bn={fatal:60,error:50,warn:40,info:30,debug:20,trace:10},jn=new Set(["help","login","logout","whoami","tunnel","create","fix","internal-fix-run","init","upgrade","test","show-report","codegen"]),Mn=(new Date).toISOString().split("T")[0],Fn=(()=>{const e=[n.join(D.tmpdir(),"stably-logs",Mn),n.join(D.homedir(),".stably","logs",Mn)];for(const t of e)try{return v.mkdirSync(t,{recursive:!0}),t}catch{}return null})(),Hn=process.argv.includes("--verbose")||process.argv.includes("-v"),Gn=process.env.STABLY_LOG_LEVEL?.toLowerCase(),Wn=Hn?"debug":void 0!==(mn=Gn)&&mn in Bn?Gn:"warn",Vn=Bn[Wn],Yn=null,zn=null,qn=null,Kn=[],Jn=!1,Qn=e=>{if(!Jn){if(!(Yn=(e=>{if(!Fn)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("-")})(),r=((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 n.join(Fn,`${t}-${r}.log`)})(e)))return Kn=[],void(Jn=!0);(e=>{const t=["","=".repeat(60),"Stably CLI Debug Log",`Version: ${rn}`,`Generated: ${(new Date).toISOString()}`,`Node: ${process.version}`,`Platform: ${process.platform} ${D.release()}`,`CWD: ${process.cwd()}`,`Args: ${process.argv.slice(2).join(" ")}`,`Log Level (console): ${Wn}`,"=".repeat(60),""].join("\n");e.write(t)})(zn=new we({dest:Yn,minLength:4096,sync:!1,append:!0})),qn=be({level:"debug",timestamp:be.stdTimeFunctions.isoTime,base:{version:rn}},zn);for(const{level:e,msg:t,context:r}of Kn)r?qn[e](r,t):qn[e](t);Kn=[],Jn=!0,Hn&&process.stderr.write(`${se.dim(`Debug log: ${Yn}`)}\n\n`)}},Xn=(()=>{const e=process.argv.slice(2).find(e=>!e.startsWith("-"));return e&&jn.has(e)?e:null})();Xn&&Qn(Xn);var Zn=e=>(t,r)=>{if(qn?r?qn[e](r,t):qn[e](t):Jn||Kn.push({level:e,msg:t,context:r}),(e=>Bn[e]>=Vn)(e)){const r=((e,t)=>`${{fatal:se.bgRed(se.white(" FATAL ")),error:se.red("error"),warn:se.yellow("warn"),info:se.cyan("info"),debug:se.dim("debug"),trace:se.dim("trace")}[e]} ${t}`)(e,t);process.stderr.write(`${r}\n`)}},es={fatal:Zn("fatal"),error:Zn("error"),warn:Zn("warn"),info:Zn("info"),debug:Zn("debug"),trace:Zn("trace"),initSession:e=>{Jn||Qn(e)},getLogFilePath:()=>Yn,flush:()=>{if(zn)try{zn.flushSync()}catch{}},printLogFileInfo:()=>{Yn&&(process.stderr.write(`\n${se.dim("Debug log written to:")}\n`),process.stderr.write(` ${se.cyan(Yn)}\n`),process.stderr.write(`${se.dim("Share this file with support for assistance.")}\n`))},getPinoLogger:()=>qn};setInterval(()=>{es.flush()},3e4).unref(),process.on("beforeExit",()=>{es.flush()});var ts=e=>{const t=()=>{es.flush(),Hn&&es.printLogFileInfo(),process.removeListener(e,t),process.kill(process.pid,e)};return t};process.on("SIGINT",ts("SIGINT")),process.on("SIGTERM",ts("SIGTERM"));var rs=()=>"true"===process.env.GITHUB_ACTIONS?"github-actions":"true"===process.env.GITLAB_CI?"gitlab-ci":"true"===process.env.CIRCLECI?"circleci":process.env.JENKINS_URL?"jenkins":process.env.CI?"generic-ci":"local",ns=()=>"local"!==rs(),ss=e=>{switch(e){case"github-actions":return"GitHub secrets";case"gitlab-ci":return"GitLab CI/CD variables";case"circleci":return"CircleCI environment variables";case"jenkins":return"Jenkins credentials";case"generic-ci":return"CI secrets/environment variables";case"local":return"environment variables"}},os=()=>{const e=rs();return[`Authentication failed. In CI, add the following to your ${ss(e)}:`," STABLY_API_KEY β https://app.stably.ai/settings?tab=api-key"," STABLY_PROJECT_ID β https://app.stably.ai/settings?tab=project-id"].join("\n")},is=()=>{const e=process.env.STABLY_API_KEY?.trim(),t=process.env.STABLY_PROJECT_ID?.trim();if(e&&t)return es.debug("Environment auth detected",{hasApiKey:!0,hasProjectId:!0}),{apiKey:e,projectId:t};es.debug("Environment auth not set",{hasApiKey:!!e,hasProjectId:!!t})},as=async()=>{es.debug("Checking for stored auth tokens");const e=await xn();if(!e)return void es.debug("No stored auth tokens found");const t=Rn(e);if(es.debug("Auth tokens status",{expired:t}),!t){const t=await Pn(),r=(e=>{try{const t=gn.parse(yn(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(es.debug("Token scope check",{scope:r,hasContext:!!t}),t&&"full"===r)try{es.debug("Exchanging full token for org-scoped token",{orgId:t.orgId});const r=await fn(e.accessToken,t.orgId),n={accessToken:r.accessToken,expiresAt:Date.now()+1e3*r.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken};return await An(n),es.debug("Token exchange successful"),n}catch(t){return es.debug("Token exchange failed, using existing token",{error:t instanceof Error?t.message:String(t)}),e}return e}try{es.debug("Attempting token refresh");const t=await Un(e.refreshToken);es.debug("Token refresh successful");const r=await Pn();if(r)try{es.debug("Exchanging refreshed token for org-scoped token");const e=await fn(t.accessToken,r.orgId),n={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:t.idToken,refreshToken:t.refreshToken};return await An(n),n}catch{return await An(t),t}return await An(t),t}catch(e){return void es.warn("Token refresh failed",{error:e instanceof Error?e.message:String(e)})}},cs=async(e={})=>{es.debug("Requiring authentication",{autoLogin:e.autoLogin});const t=is();if(t)return es.info("Using environment variable authentication"),{auth:t,type:"env"};let r=await as(),n=r?await Pn():void 0;const s=process.stdin.isTTY&&process.stdout.isTTY;if(es.debug("OAuth auth check",{hasTokens:!!r,hasContext:!!n,canPrompt:s}),(!r||!n)&&e.autoLogin&&s){es.info("Prompting user to login"),r?ce.info("You are logged in but need to select an organization and project."):ce.info("You are not logged in."),ce.info("Press Enter to log in."),process.stdout.write(`${se.dim("Alternatively, set environment variables for an org API key:")}\n${se.dim(" STABLY_API_KEY=... STABLY_PROJECT_ID=... stably")}\n`),process.stdout.write("\n");const e=ne({input:process.stdin,output:process.stdout});try{await e.question(se.dim("Press Enter to continue... "))}finally{e.close()}await On(),r=await as(),n=r?await Pn():void 0}return r||(es.warn("Authentication required but no tokens available"),ns()?le(se.red(os())):le(se.red("You are not logged in. Run `stably login` to authenticate.")),process.exit(1)),n||(es.warn("Authentication succeeded but no project context selected"),ns()?le(se.red(os())):le(se.red("You haven't selected an organization and project. Run `stably login` to complete setup.")),process.exit(1)),es.info("OAuth authentication successful",{orgId:n.orgId,projectId:n.projectId}),{auth:{accessToken:r.accessToken,context:n},type:"oauth"}},ls=e=>"env"===e.type?e.auth.projectId:e.auth.context.projectId,us=e=>"env"===e.type?e.auth.apiKey:e.auth.accessToken,ds=class e{static TOKEN_REFRESH_BUFFER_MS=3e5;initialAuth;refreshPromise=null;cachedToken=null;cachedExpiresAt=0;constructor(e){this.initialAuth=e}async getAuthHeader(){return"env"===this.initialAuth.type?this.initialAuth.auth.apiKey:this.cachedToken&&Date.now()<this.cachedExpiresAt-e.TOKEN_REFRESH_BUFFER_MS?this.cachedToken:(this.refreshPromise||(this.refreshPromise=(async()=>{try{const e=await as();if(!e)throw new Error("Authentication expired and refresh failed. Please re-run `stably login`.");return this.cachedToken=e.accessToken,this.cachedExpiresAt=e.expiresAt,e.accessToken}finally{this.refreshPromise=null}})()),this.refreshPromise)}getOrgId(){return"oauth"===this.initialAuth.type?this.initialAuth.auth.context.orgId:void 0}getProjectId(){return"env"===this.initialAuth.type?this.initialAuth.auth.projectId:this.initialAuth.auth.context.projectId}},ps=async e=>{const t=await cs(),r=ls(t),n=us(t);es.debug("Fetching remote environment variables",{envName:e,projectId:r});const s=await(o={auth:n,client:pn(),path:{projectId:r,environment:e}},(o.client??Zr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/environments/{environment}/variables",...o}));var o;if(404===s.response.status)return{ok:!1,error:`Environment "${e}" not found. Check the name on your Stably dashboard.`};if(401===s.response.status||403===s.response.status)return{ok:!1,error:`Access denied to environment "${e}".`};if(s.error)return{ok:!1,error:`Failed to fetch environment "${e}": ${s.response.status}`};const i={},a=[];for(const e of s.data.variables)i[e.name]=e.value,e.sensitive&&e.value.length>0&&a.push(e.value);const c=s.data.variables.length,l=a.length;return process.stderr.write(`${se.cyan(`Loaded ${c} variable${1!==c?"s":""} from "${e}"`)}${l>0?se.dim(` (${l} sensitive)`):""}\n`),{ok:!0,result:{variables:i,sensitiveValues:a}}},fs=async()=>{const e=$e.remoteEnvName;if(!e)return;const t=await ps(e);return t.ok||(le(se.red(t.error)),process.exit(1)),t.result},hs=e=>e?{[$r]:e}:void 0,gs=ge.object({context:ge.string().min(1),autohealReportUrl:ge.string(),skippedTests:ge.array(ge.object({testIdentifier:ge.string(),testTitle:ge.string(),consecutiveUnfixedCount:ge.number()})).optional(),newerPassingSuiteId:ge.string().optional(),envName:ge.string().optional()}),ms=ve.object({bucket:ve.string(),key:ve.string()}),ys=async({body:e,contentType:t,uploadUrl:r,errorContext:n="content"})=>{const s=await fetch(r,{body:e instanceof Uint8Array?Buffer.from(e):e,headers:{"Content-Type":t},method:"PUT"});if(!s.ok)throw new Error(`Failed to upload ${n} (${s.status})`)},bs=ve.object({diffBucketPath:ms,expiresInSeconds:ve.number(),key:ve.string(),uploadUrl:ve.string()}),ws=ve.object({traceBucketPath:ms,expiresInSeconds:ve.number(),key:ve.string(),uploadUrl:ve.string(),sensitiveValues:ve.array(ve.string())}),vs=async({authHeader:e,contentType:t="text/plain",orgId:r,runId:n})=>{const s=await(o={auth:e,body:{contentType:t},client:pn(),headers:hs(r),path:{runId:n}},(o.client??Zr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-diff/upload-url",...o,headers:{"Content-Type":"application/json",...o.headers}}));var o;if(s.error)throw new Error(`Failed to presign diff upload (${s.response.status})`);const i=bs.parse(s.data);return{diffBucketPath:i.diffBucketPath,expiresInSeconds:i.expiresInSeconds,key:i.key,uploadUrl:i.uploadUrl}},Is=async({authHeader:e,diffBucketPath:t,orgId:r,runId:n})=>{const s=await(o={auth:e,body:t,client:pn(),headers:hs(r),path:{runId:n}},(o.client??Zr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-diff/confirm-upload",...o,headers:{"Content-Type":"application/json",...o.headers}}));var o;if(s.error)throw new Error(`Failed to confirm diff upload (${s.response.status})`)},Ts=class e{socket;url;authProvider;orgId;runId;pendingEvent=null;reconnectAttempts=0;reconnectTimer;flushPromise=null;debounceTimer;_isClosed=!1;isAuthenticated=!1;authenticationFailed=!1;onUserMessage;maxReconnectAttempts=10;baseReconnectDelay=2e3;maxReconnectDelay=3e4;debounceMs=500;get isClosed(){return this._isClosed}constructor({authProvider:e,orgId:t,runId:r,url:n=ln,onUserMessage:s}){this.authProvider=e,this.orgId=t,this.runId=r,this.url=n,this.onUserMessage=s,es.info("[ws] Constructing AutohealWebSocketClient",{url:this.url,runId:r})}async start(){await this.connect()}async connect(){if(!this._isClosed)try{const e=await this.authProvider.getAuthHeader();if(this._isClosed)return;const t={Authorization:e};this.orgId&&(t["x-stably-org-id"]=this.orgId);const r=`${this.url}?runId=${encodeURIComponent(this.runId)}`;es.info("[ws] Connecting",{url:r,attempt:this.reconnectAttempts}),this.socket=new Ie(r,{headers:t}),this.socket.on("open",()=>{es.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);es.debug("[ws] Received message",{type:r?.type}),"connected"===r?.type&&(es.info("[ws] Authenticated successfully"),this.isAuthenticated=!0,this.authenticationFailed=!1,this.flushPending()),"user_message"===r?.type&&"string"==typeof r.content&&(es.info("[ws] Received user message from web UI"),this.onUserMessage?.(r.content))}catch{}}),this.socket.on("close",(e,t)=>{es.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=>{es.warn("[ws] Connection error",{error:e.message})})}catch(e){es.warn("[ws] Failed to create WebSocket",{error:e instanceof Error?e.message:String(e)}),this.scheduleReconnect()}}scheduleReconnect(){if(this._isClosed||this.reconnectTimer)return;this.reconnectAttempts++;const e=Math.min(this.baseReconnectDelay*Math.pow(2,this.reconnectAttempts-1),this.maxReconnectDelay);es.info("[ws] Scheduling reconnect",{attempt:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts,delayMs:e}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect().catch(e=>{es.warn("[ws] Reconnect failed",{error:e instanceof Error?e.message:String(e)})})},e)}isConnected(){return!!this.socket&&this.socket.readyState===Ie.OPEN&&this.isAuthenticated}sendProgress(e){if(this._isClosed)return void es.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?(es.info("[ws] sendProgress: flushing terminal state immediately"),void this.flushPending()):void(this.debounceTimer||(this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.flushPending()},this.debounceMs))):(es.debug("[ws] sendProgress: not connected, queuing event",{phase:e.phase,socketState:this.socket?.readyState,isAuthenticated:this.isAuthenticated,reconnectAttempts:this.reconnectAttempts}),void(this.socket?.readyState===Ie.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 es.debug("[ws] flushPending: not connected, re-queuing event",{phase:e.payload.phase}),void(this.pendingEvent=e);es.debug("[ws] flushPending: sending event",{phase:e.payload.phase});const t=new Promise(t=>{try{this.socket?.send(JSON.stringify(e),r=>{r&&(es.warn("[ws] flushPending: send failed",{error:r.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e)),t()})}catch(r){es.warn("[ws] flushPending: send threw",{error:r instanceof Error?r.message:String(r)}),this.pendingEvent=e,t()}}).finally(()=>{this.flushPromise===t&&(this.flushPromise=null)});this.flushPromise=t}static FLUSH_TIMEOUT_MS=5e3;async flushPendingAndWait(){if(this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.flushPromise&&await Promise.race([this.flushPromise,new Promise(t=>setTimeout(t,e.FLUSH_TIMEOUT_MS).unref())]),!this.pendingEvent)return Promise.resolve();const t=this.pendingEvent;if(this.pendingEvent=null,!this.isConnected())return es.warn("[ws] flushPendingAndWait: not connected, event will be dropped",{phase:t.payload.phase}),this.pendingEvent=t,Promise.resolve();const r=new Promise(e=>{try{es.debug("[ws] flushPendingAndWait: sending event",{phase:t.payload.phase}),this.socket?.send(JSON.stringify(t),r=>{r&&(es.warn("[ws] flushPendingAndWait: send failed",{error:r.message,phase:t.payload.phase}),this.pendingEvent||(this.pendingEvent=t)),e()})}catch(r){es.warn("[ws] flushPendingAndWait: send threw",{error:r instanceof Error?r.message:String(r)}),this.pendingEvent=t,e()}});await Promise.race([r,new Promise(t=>setTimeout(t,e.FLUSH_TIMEOUT_MS).unref())])}close(){if(this._isClosed)return;es.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)}async closeAndWait(){if(this._isClosed)return;es.info("[ws] Closing WebSocket client and waiting for pending send"),this._isClosed=!0,this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),await this.flushPendingAndWait();const{socket:e}=this;this.socket=void 0,e&&(await new Promise(e=>setTimeout(e,200)),e.close())}},_s=class e{socket;url;authProvider;orgId;sessionId;pendingEvent=null;reconnectAttempts=0;reconnectTimer;flushPromise=null;debounceTimer;_isClosed=!1;isAuthenticated=!1;authenticationFailed=!1;onUserMessage;maxReconnectAttempts=10;baseReconnectDelay=2e3;maxReconnectDelay=3e4;debounceMs=500;get isClosed(){return this._isClosed}constructor({authProvider:e,orgId:t,sessionId:r,url:n=un,onUserMessage:s}){this.authProvider=e,this.orgId=t,this.sessionId=r,this.url=n,this.onUserMessage=s,es.info("[ws] Constructing CreateProgressWebSocketClient",{url:this.url,sessionId:r})}async start(){await this.connect()}async connect(){if(!this._isClosed)try{const e=await this.authProvider.getAuthHeader();if(this._isClosed)return;const t={Authorization:e};this.orgId&&(t["x-stably-org-id"]=this.orgId);const r=`${this.url}?sessionId=${encodeURIComponent(this.sessionId)}`;es.info("[ws] Connecting",{url:r,attempt:this.reconnectAttempts}),this.socket=new Ie(r,{headers:t}),this.socket.on("open",()=>{es.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);es.debug("[ws] Received message",{type:r?.type}),"connected"===r?.type&&(es.info("[ws] Authenticated successfully"),this.isAuthenticated=!0,this.authenticationFailed=!1,this.flushPending()),"user_message"===r?.type&&"string"==typeof r.content&&(es.info("[ws] Received user message from web UI"),this.onUserMessage?.(r.content))}catch{}}),this.socket.on("close",(e,t)=>{es.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=>{es.warn("[ws] Connection error",{error:e.message})})}catch(e){es.warn("[ws] Failed to create WebSocket",{error:e instanceof Error?e.message:String(e)}),this.scheduleReconnect()}}scheduleReconnect(){if(this._isClosed||this.reconnectTimer)return;this.reconnectAttempts++;const e=Math.min(this.baseReconnectDelay*Math.pow(2,this.reconnectAttempts-1),this.maxReconnectDelay);es.info("[ws] Scheduling reconnect",{attempt:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts,delayMs:e}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect().catch(e=>{es.warn("[ws] Reconnect failed",{error:e instanceof Error?e.message:String(e)})})},e)}isConnected(){return!!this.socket&&this.socket.readyState===Ie.OPEN&&this.isAuthenticated}sendProgress(e){if(this._isClosed)return void es.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?(es.info("[ws] sendProgress: flushing terminal state immediately"),void this.flushPending()):void(this.debounceTimer||(this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.flushPending()},this.debounceMs))):(es.debug("[ws] sendProgress: not connected, queuing event",{phase:e.phase,socketState:this.socket?.readyState,isAuthenticated:this.isAuthenticated,reconnectAttempts:this.reconnectAttempts}),void(this.socket?.readyState===Ie.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 es.debug("[ws] flushPending: not connected, re-queuing event",{phase:e.payload.phase}),void(this.pendingEvent=e);es.debug("[ws] flushPending: sending event",{phase:e.payload.phase});const t=new Promise(t=>{try{this.socket?.send(JSON.stringify(e),r=>{r&&(es.warn("[ws] flushPending: send failed",{error:r.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e)),t()})}catch(r){es.warn("[ws] flushPending: send threw",{error:r instanceof Error?r.message:String(r)}),this.pendingEvent=e,t()}}).finally(()=>{this.flushPromise===t&&(this.flushPromise=null)});this.flushPromise=t}static FLUSH_TIMEOUT_MS=5e3;async flushPendingAndWait(){if(this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.flushPromise&&await Promise.race([this.flushPromise,new Promise(t=>setTimeout(t,e.FLUSH_TIMEOUT_MS).unref())]),!this.pendingEvent)return Promise.resolve();const t=this.pendingEvent;if(this.pendingEvent=null,!this.isConnected())return es.warn("[ws] flushPendingAndWait: not connected, event will be dropped",{phase:t.payload.phase}),this.pendingEvent=t,Promise.resolve();const r=new Promise(e=>{try{es.debug("[ws] flushPendingAndWait: sending event",{phase:t.payload.phase}),this.socket?.send(JSON.stringify(t),r=>{r&&(es.warn("[ws] flushPendingAndWait: send failed",{error:r.message,phase:t.payload.phase}),this.pendingEvent||(this.pendingEvent=t)),e()})}catch(r){es.warn("[ws] flushPendingAndWait: send threw",{error:r instanceof Error?r.message:String(r)}),this.pendingEvent=t,e()}});await Promise.race([r,new Promise(t=>setTimeout(t,e.FLUSH_TIMEOUT_MS).unref())])}close(){if(this._isClosed)return;es.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)}async closeAndWait(){if(this._isClosed)return;es.info("[ws] Closing WebSocket client and waiting for pending send"),this._isClosed=!0,this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),await this.flushPendingAndWait();const{socket:e}=this;this.socket=void 0,e&&(await new Promise(e=>setTimeout(e,200)),e.close())}},Es=ve.object({bucketPath:ms,expiresInSeconds:ve.number(),key:ve.string(),uploadUrl:ve.string()}),Ss=ge.object({uploadUrl:ge.string(),key:ge.string(),bucketPath:ge.object({bucket:ge.string(),key:ge.string()}),expiresInSeconds:ge.number()});async function xs({authHeader:e,orgId:t,sessionId:r,projectId:n,history:s}){if(0===s.length)return es.debug("[session-history] No history to upload"),{success:!0};try{es.info("[session-history] Requesting upload URL",{sessionId:r,messageCount:s.length});const{uploadUrl:o,key:i}=await async function({authHeader:e,orgId:t,sessionId:r,projectId:n}){const s=new URL(`/internal/v1/cli/sessions/${r}/history/upload-url`,nn),o={Authorization:e,"Content-Type":"application/json"};t&&(o["x-stably-org-id"]=t);const i=await fetch(s,{method:"POST",headers:o,body:JSON.stringify({contentType:"application/x-ndjson",...n?{projectId:n}:{}}),signal:AbortSignal.timeout(3e4)});if(!i.ok){const e=await i.text().catch(()=>"");throw new Error(`Failed to get history upload URL (${i.status}): ${e.slice(0,200)}`)}return Ss.parse(await i.json())}({authHeader:e,orgId:t,sessionId:r,projectId:n}),a=s.map(e=>JSON.stringify(e)).join("\n");es.info("[session-history] Uploading history",{key:i,messageCount:s.length,sizeBytes:a.length});const c=await fetch(o,{method:"PUT",body:a,headers:{"Content-Type":"application/x-ndjson"},signal:AbortSignal.timeout(6e4)});if(!c.ok)throw new Error(`Upload failed with status ${c.status}`);return es.info("[session-history] History uploaded successfully",{key:i}),{success:!0,key:i}}catch(e){const t=e instanceof Error?e.message:String(e);return es.warn("[session-history] Failed to upload history",{error:t}),{success:!1,error:t}}}var As="1.58.0",ks=["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 Ps(e){return/^\.env(\..*)?$/.test(e)||".stably-agent.env"===e}function Cs(e){return Boolean(e&&"object"==typeof e&&"tool_input"in e&&e.tool_input&&"object"==typeof e.tool_input)}function Rs({action:e,pathKey:t}){return function({action:e,fileCheck:t,getBlockMessage:r,pathKey:n}){return async s=>{const o=function({input:e,pathKey:t}){if(!Cs(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:s,pathKey:n});if(!o.success)return o;const i=o.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:Ps,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 Us=["rm","mv","git","gh","npx","stably","stably-browser","pwtrace","npm","yarn","pnpm","bun"],$s=["stably","playwright","stably-browser","pwtrace"],Ls=["create","fix","verify"],Ds=["upload"],Ns=["push","fetch","pull","clone","ls-remote"],Os=/\S+=(?:\"[^\"\\]*(?:\\.[^\"\\]*)*\"|'[^']*(?:'\\''[^']*)*'|\S+)/;function Bs(e){let t="",r=!1,n=!1,s=!1;for(let o=0;o<e.length;o++){const i=e[o];s?(t+=i,s=!1):"\\"!==i||n?'"'!==i||n?"'"!==i||r?t+=i:n=!n:r=!r:s=!0}return t}function js(e){const t=[],r=e.trim(),n=/(?:[^\s"']+|"[^"\\]*(?:\\.[^"\\]*)*"|'[^']*(?:'\\''[^']*)*')+/g;let s;for(;null!==(s=n.exec(r));)t.push(s[0]);return t}function Ms(e){let t=0;const r=new RegExp(`^${Os.source}$`);for(;t<e.length&&r.test(e[t]??"");)t+=1;return e.slice(t)}function Fs(e){const t=Ms(js(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 Bs(r)}}}function Hs(e){return js(e).map(Bs).find(e=>Ls.includes(e))}function Gs(e,t){const r=c(e).replace(/\\/g,"/"),n=t.replace(/\\/g,"/"),s=n.endsWith("/")?n:`${n}/`;if(r.startsWith(s))return!0;const o=r.lastIndexOf(`/${s}`);if(-1===o)return!1;const i=r.slice(o+`/${s}`.length);return i.length>0&&!i.startsWith("../")}function Ws({onBeforeGitHubCommand:e,workspaceBoundary:t,allowBackgroundRunTest:r=!1}){return async n=>{if(!Cs(n))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 i=n.tool_input,{command:c}=i;if("string"!=typeof c)return{decision:"block",reason:"Invalid Bash command: command must be a string.",systemMessage:"Tool call blocked due to invalid command type"};const l=function(e){const t=e.trim(),r=new RegExp(`^(?:${Os.source}\\s+)*(\\S+)`),n=t.match(r);return n?.[1]}(c);if(!l)return{decision:"block",reason:"Invalid Bash command: could not parse command.",systemMessage:"Tool call blocked due to unparseable command"};if(!r&&"run_in_background"in i&&!0===i.run_in_background&&/\bstably-browser\s+(?:(?:-\w+=?\S*|--\w+=?\S*|-s\s+\S+|--session\s+\S+)\s+)*run-test\b/.test(c))return{decision:"block",reason:"Running `stably-browser run-test` with `run_in_background: true` is not allowed. Test runs must execute in the foreground so their output can be captured and parsed. Remove the `run_in_background` parameter and run the test normally.",systemMessage:"Tool call blocked due to run-test in background"};if(!function(e){return"string"==typeof e&&Us.includes(e)}(l))return{decision:"block",reason:`The command "${l}" is not allowed. Only the following commands are permitted: ${Us.join(", ")}. Use the appropriate tools (Read, Write, Edit, Glob, Grep) for file operations instead.`,systemMessage:"Tool call blocked due to disallowed command"};if("npx"===l){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 ...`."};const t=Fs(e);if(!t)return{valid:!1,reason:"Invalid npx command: unable to determine which binary is being executed."};if(!new Set($s).has(t))return{valid:!1,reason:`The npx binary "${t}" is not allowed. Only ${$s.join(", ")} are permitted.`};if("stably"===t){const r=Hs(e);if(r)return{valid:!1,reason:`The npx ${t} subcommand "${r}" is not allowed. The commands ${Ls.join(", ")} are AI-powered and blocked to prevent recursion.`}}return{valid:!0}}(c);if(!e.valid)return{decision:"block",reason:e.reason,systemMessage:"Tool call blocked due to disallowed npx command"}}if("stably-browser"===l||"npx"===l&&"stably-browser"===Fs(c)){const e=function({command:e,binary:t}){const r=Ms(js(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 Bs(t)}}({command:c,binary:"stably-browser"});if(e&&Ds.includes(e))return{decision:"block",reason:`The stably-browser subcommand "${e}" is not allowed. The "upload" command can read arbitrary files and is blocked for security.`,systemMessage:"Tool call blocked due to disallowed stably-browser subcommand"}}if("stably"===l){const e=Hs(c);if(e)return{decision:"block",reason:`The stably subcommand "${e}" is not allowed. The commands ${Ls.join(", ")} are AI-powered and blocked to prevent recursion.`,systemMessage:"Tool call blocked due to disallowed stably command"}}if("rm"===l){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):[]}(c);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(E(e))return k.native(e);let t=e;const r=[];for(;!E(t);){const n=o(t);if(n===t)return s(e);r.unshift(t.slice(n.length+1)),t=n}const n=k.native(t);return r.length>0?s(n,...r):n}(e),n=k.native(t),i=r.endsWith(a)?r:r+a,c=n.endsWith(a)?n:n+a;return i.startsWith(c)||r===n}({targetPath:s(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=>!(Gs(e,"tests")||Gs(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"===l&&["-c","--config","--config-env"].some(e=>c.includes(` ${e} `)||c.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"===l&&function(e){const t=e.trim();return!!t.startsWith("git ")&&Ns.some(e=>t.includes(` ${e}`)||t.includes(`git ${e}`))}(c)&&e)try{await e()}catch(e){console.error("[BashSecurityHook] Failed to refresh git token:",e)}if("gh"===l){const t=function(e){const t=e.toLowerCase();return ks.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}}(c);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 Vs=/\.(spec|test)\.(ts|tsx|js|jsx|mts|mjs)$/;function Ys({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&&Vs.test(n)&&e(n),{decision:"approve"}}}var zs=M(f);async function qs(){try{const{stdout:e}=await zs('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 zs(`pkill -KILL -P ${e} '.*' 2>/dev/null || true`)}))}catch{}}var Ks=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}drainQueue(){return this.queue.splice(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 Js(e){try{const t=h("git branch --show-current",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(!t)return;return{branch:t}}catch{return}}var Qs=[".ts",".js",".mts",".mjs",".cts",".cjs"],Xs=10240,Zs=async({defaultContent:e,fileName:t,filePath:r})=>{try{const e=(await ee(r)).size,n=await q(r,"utf-8"),s=Buffer.byteLength(n,"utf-8");if(s<=Xs)return n;const o=(e=>{const t=e.split("\n"),r=[];let n=!1,s=!1,o=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),s=!0,o=(a.match(/{/g)||[]).length-(a.match(/}/g)||[]).length,0===o&&(c.endsWith(";")||c.endsWith(","))&&(s=!1)):s?(o+=(a.match(/{/g)||[]).length,o-=(a.match(/}/g)||[]).length,0===o&&c.includes("}")?(r.push(a),s=!1):o>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(o,"utf-8");return i<=Xs?o:o.slice(0,Xs)+`\n\n... [TRUNCATED: File "${t}" at ${r} was ${e} bytes (${s} 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}},eo=async({defaultContent:e,dirName:t,dirPath:r})=>{try{const e=await Z(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}},to=async({allowedEnvVars:e,mode:t,workspaceInfo:r,authHeader:n,customHeader:s,maxParallelWorkers:o,isCloudBrowser:i})=>{const a=pn(),c=Js(r.absolutePath);es.debug("Requesting system prompt from API",{mode:t,hasGitContext:!!c,envVarCount:e.length});const l=await(u={client:a,auth:n,body:{mode:t,workspaceInfo:r,allowedEnvVars:e,gitContext:c,maxParallelWorkers:o,isCloudBrowser:i}},(u.client??Zr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/prompts/system",...u,headers:{"Content-Type":"application/json",...u.headers}}));var u;if(401===l.response.status)throw es.warn("System prompt fetch failed: unauthorized (401)"),await kn(),new Error("Your session has expired or been revoked. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(403===l.response.status)throw es.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(l.error){es.warn("System prompt fetch failed",{error:l.error});const e=JSON.stringify(l.error);if(e.toLowerCase().includes("unauthorized")||e.toLowerCase().includes("unauthenticated"))throw await kn(),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 d=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:l.data.systemPrompt,customHeader:s});return es.debug("System prompt received",{size:d.length,appendedCustomHeader:!!s,hasPrContext:!!l.data.prContext}),{systemPrompt:d,prContext:l.data.prContext}},ro={chat:"chat",single:"create",fix:"fix",init:"init",verify:"verify",plan:"plan"};async function no({agentMode:e,authHeader:t,orgId:r,projectId:n,runId:s,fetchImpl:o=fetch,apiUrl:i=nn}){const a=ro[e],c=new URL("/internal/v1/cli/progress",i).toString(),l={Authorization:t,"Content-Type":"application/json","X-STABLY-CLI-VERSION":rn};r&&(l["x-stably-org-id"]=r);const u=await o(c,{method:"POST",headers:l,body:JSON.stringify({mode:a,projectId:n,agentId:ie.randomUUID(),..."fix"===a&&s?{playwrightSuiteRunId:s}:{}}),signal:AbortSignal.timeout(1e4)});if(!u.ok){const e=await u.text().catch(()=>"");throw new Error(`Failed to create progress session: ${u.status} ${c} β ${e.slice(0,300)}`)}const{sessionId:d}=await u.json();return{sessionId:d,sessionMode:a}}var so=".stably-internal.playwright",oo=`${so}-wrapper.config.*`,io="STABLY_INTERNAL_EXECUTION",ao=[".ts",".js",".mts",".mjs",".cts",".cjs"];function co(e){const t=s(e);if(E(t))for(const e of ao){const r=i(t,`playwright.config${e}`);if(E(r))return r}}var lo=["tests","e2e","__tests__","test"];function uo(e){try{return E(e)&&S(e).isDirectory()}catch{return!1}}function po(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(se.dim(`Using output directory: ${e} (from ${r})`))}var fo,ho=["mcp__playwright-test__","mcp__auto-heal-report__","mcp__stably-agent-control__"],go=["planner_","generator_"],mo={open:e=>e?`Open ${e}`:"Open browser",close:()=>"Close browser",snapshot:()=>"Page snapshot",screenshot:()=>"Screenshot",click:e=>`Click ${e}`,fill:e=>`Fill ${e.split(/\s+/)[0]||""}`.trim(),type:e=>`Type into ${e.split(/\s+/)[0]||""}`.trim(),hover:e=>`Hover ${e}`,goto:e=>`Navigate to ${e}`,select:e=>`Select option in ${e.split(/\s+/)[0]||""}`.trim(),check:e=>`Check ${e}`,uncheck:e=>`Uncheck ${e}`,back:()=>"Go back",forward:()=>"Go forward","run-test":e=>`Run test ${e}`,"run-code":()=>"Run code","run-file":e=>`Run file ${e}`,"tab-list":()=>"List tabs","tab-new":e=>e?`New tab ${e}`:"New tab","tab-select":e=>`Select tab ${e}`,"tab-close":()=>"Close tab",eval:()=>"Evaluate JavaScript",upload:()=>"Upload file","state-save":()=>"Save browser state","state-load":()=>"Load browser state"},yo={"stably-browser":"Loading browser command reference","stably-cli":"Loading CLI reference","browser-interaction-guide":"Loading browser interaction guide","playwright-config-auth":"Loading project configuration","playwright-cli":"Loading browser command reference","bash-commands":"Loading command reference","stably-sdk-reference":"Loading SDK reference","test-creation-workflow":"Loading test creation guide","bulk-test-handling":"Loading bulk test guide","debugging-test-failures":"Loading debugging guide","recorded-actions-handling":"Loading recorded actions guide","playwright-best-practices":"Loading best practices","pwtrace-debugging":"Loading trace debugging guide","ai-to-programmatic-migration":"Loading migration guide"},bo={Skill:"Preparing for task",ToolSearch:"Searching tools"},wo=(e,t)=>{const r=t.find(t=>e.startsWith(t));return r?e.slice(r.length):e},vo=e=>e.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" "),Io=(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},To=(e,t)=>{if(!t||"object"!=typeof t)return null;const r=t;if("Skill"===e){const e="string"==typeof r.skill?r.skill:void 0;if(e){const t=e.includes(":")?e.split(":").pop():e;return yo[t]?yo[t]:`Loading ${t.replace(/-/g," ")}`}return"Preparing for task"}if("Bash"===e&&"string"==typeof r.description&&r.description.trim())return r.description.trim();if("Bash"===e&&"string"==typeof r.command){const e=r.command.match(/(?:^|\s)(?:[\w/.-]*\/)?stably-browser\s+(?:--\S+\s+)*(\S+)(.*)/);if(!e)return null;const[,t,n]=e,s=n.trim().replace(/--\S+=?\S*\s*/g,"").trim(),o=mo[t];return o?o(s):`${vo(t)}${s?` ${s.split(/\s+/)[0]}`:""}`.trim()}return"Read"===e&&"string"==typeof r.file_path&&(r.file_path.includes(".stably-browser/")||r.file_path.includes(".playwright-cli/"))&&r.file_path.endsWith(".yml")?"Page snapshot":"TaskOutput"===e?!0===r.block?"Waiting for background task":"Checking background task":null},_o=e=>"mcp__auto-heal-report__upload-trace-proof"===e||"mcp__upload-trace-proof__upload-trace-proof"===e?"Upload Trace":"mcp__auto-heal-report__generate-report"===e?"Generate Report":(e=>{const t=bo[e];if(t)return t;const r=wo(e,ho),n=wo(r,go);return vo(n)})(e),Eo=(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},So=(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},xo=(e,t)=>{if(t<=0)return 0;const r=e.lastIndexOf("\n",t-1);return-1===r?0:r+1},Ao=(e,t)=>{const r=e.indexOf("\n",t);return-1===r?e.length:r},ko=Pe("/");try{fo=ko("worker_threads").Worker}catch(e){}var Po=fo?function(e,t,r,n,s){var o=!1,i=new fo(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 s(e,null)}).on("message",function(e){return s(null,e)}).on("exit",function(e){e&&!o&&s(new Error("exited with code "+e),null)});return i.postMessage(r,n),i.terminate=function(){return o=!0,fo.prototype.terminate.call(i)},i}:function(e,t,r,n,s){setImmediate(function(){return s(new Error("async operations unsupported - update to Node 12+ (or Node 10-11 with the --experimental-worker CLI flag)"),null)});var o=function(){};return{terminate:o,postMessage:o}},Co=Uint8Array,Ro=Uint16Array,Uo=Int32Array,$o=new Co([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]),Lo=new Co([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]),Do=new Co([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),No=function(e,t){for(var r=new Ro(31),n=0;n<31;++n)r[n]=t+=1<<e[n-1];var s=new Uo(r[30]);for(n=1;n<30;++n)for(var o=r[n];o<r[n+1];++o)s[o]=o-r[n]<<5|n;return{b:r,r:s}},Oo=No($o,2),Bo=Oo.b,jo=Oo.r;Bo[28]=258,jo[258]=28;var Mo,Fo=No(Lo,0),Ho=Fo.b,Go=Fo.r,Wo=new Ro(32768);for(zo=0;zo<32768;++zo)Mo=(61680&(Mo=(52428&(Mo=(43690&zo)>>1|(21845&zo)<<1))>>2|(13107&Mo)<<2))>>4|(3855&Mo)<<4,Wo[zo]=((65280&Mo)>>8|(255&Mo)<<8)>>1;var Vo=function(e,t,r){for(var n=e.length,s=0,o=new Ro(t);s<n;++s)e[s]&&++o[e[s]-1];var i,a=new Ro(t);for(s=1;s<t;++s)a[s]=a[s-1]+o[s-1]<<1;if(r){i=new Ro(1<<t);var c=15-t;for(s=0;s<n;++s)if(e[s])for(var l=s<<4|e[s],u=t-e[s],d=a[e[s]-1]++<<u,p=d|(1<<u)-1;d<=p;++d)i[Wo[d]>>c]=l}else for(i=new Ro(n),s=0;s<n;++s)e[s]&&(i[s]=Wo[a[e[s]-1]++]>>15-e[s]);return i},Yo=new Co(288);for(zo=0;zo<144;++zo)Yo[zo]=8;for(zo=144;zo<256;++zo)Yo[zo]=9;for(zo=256;zo<280;++zo)Yo[zo]=7;for(zo=280;zo<288;++zo)Yo[zo]=8;var zo,qo=new Co(32);for(zo=0;zo<32;++zo)qo[zo]=5;var Ko=Vo(Yo,9,0),Jo=Vo(Yo,9,1),Qo=Vo(qo,5,0),Xo=Vo(qo,5,1),Zo=function(e){for(var t=e[0],r=1;r<e.length;++r)e[r]>t&&(t=e[r]);return t},ei=function(e,t,r){var n=t/8|0;return(e[n]|e[n+1]<<8)>>(7&t)&r},ti=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(7&t)},ri=function(e){return(e+7)/8|0},ni=function(e,t,r){return(null==t||t<0)&&(t=0),(null==r||r>e.length)&&(r=e.length),new Co(e.subarray(t,r))},si=["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"],oi=function(e,t,r){var n=new Error(t||si[e]);if(n.code=e,Error.captureStackTrace&&Error.captureStackTrace(n,oi),!r)throw n;return n},ii=function(e,t,r,n){var s=e.length,o=n?n.length:0;if(!s||t.f&&!t.l)return r||new Co(0);var i=!r,a=i||2!=t.i,c=t.i;i&&(r=new Co(3*s));var l=function(e){var t=r.length;if(e>t){var n=new Co(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,g=t.m,m=t.n,y=8*s;do{if(!f){u=ei(e,d,1);var b=ei(e,d+1,3);if(d+=3,!b){var w=e[(C=ri(d)+4)-4]|e[C-3]<<8,v=C+w;if(v>s){c&&oi(0);break}a&&l(p+w),r.set(e.subarray(C,v),p),t.b=p+=w,t.p=d=8*v,t.f=u;continue}if(1==b)f=Jo,h=Xo,g=9,m=5;else if(2==b){var I=ei(e,d,31)+257,T=ei(e,d+10,15)+4,_=I+ei(e,d+5,31)+1;d+=14;for(var E=new Co(_),S=new Co(19),x=0;x<T;++x)S[Do[x]]=ei(e,d+3*x,7);d+=3*T;var A=Zo(S),k=(1<<A)-1,P=Vo(S,A,1);for(x=0;x<_;){var C,R=P[ei(e,d,k)];if(d+=15&R,(C=R>>4)<16)E[x++]=C;else{var U=0,$=0;for(16==C?($=3+ei(e,d,3),d+=2,U=E[x-1]):17==C?($=3+ei(e,d,7),d+=3):18==C&&($=11+ei(e,d,127),d+=7);$--;)E[x++]=U}}var L=E.subarray(0,I),D=E.subarray(I);g=Zo(L),m=Zo(D),f=Vo(L,g,1),h=Vo(D,m,1)}else oi(1);if(d>y){c&&oi(0);break}}a&&l(p+131072);for(var N=(1<<g)-1,O=(1<<m)-1,B=d;;B=d){var j=(U=f[ti(e,d)&N])>>4;if((d+=15&U)>y){c&&oi(0);break}if(U||oi(2),j<256)r[p++]=j;else{if(256==j){B=d,f=null;break}var M=j-254;if(j>264){var F=$o[x=j-257];M=ei(e,d,(1<<F)-1)+Bo[x],d+=F}var H=h[ti(e,d)&O],G=H>>4;if(H||oi(3),d+=15&H,D=Ho[G],G>3&&(F=Lo[G],D+=ti(e,d)&(1<<F)-1,d+=F),d>y){c&&oi(0);break}a&&l(p+131072);var W=p+M;if(p<D){var V=o-D,Y=Math.min(D,W);for(V+p<0&&oi(3);p<Y;++p)r[p]=n[V+p]}for(;p<W;++p)r[p]=r[p-D]}}t.l=f,t.p=B,t.b=p,t.f=u,f&&(u=1,t.m=g,t.d=h,t.n=m)}while(!u);return p!=r.length&&i?ni(r,0,p):r.subarray(0,p)},ai=function(e,t,r){r<<=7&t;var n=t/8|0;e[n]|=r,e[n+1]|=r>>8},ci=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},li=function(e,t){for(var r=[],n=0;n<e.length;++n)e[n]&&r.push({s:n,f:e[n]});var s=r.length,o=r.slice();if(!s)return{t:mi,l:0};if(1==s){var i=new Co(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!=s-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=o[0].s;for(n=1;n<s;++n)o[n].s>p&&(p=o[n].s);var f=new Ro(p+1),h=ui(r[u-1],f,0);if(h>t){n=0;var g=0,m=h-t,y=1<<m;for(o.sort(function(e,t){return f[t.s]-f[e.s]||e.f-t.f});n<s;++n){var b=o[n].s;if(!(f[b]>t))break;g+=y-(1<<h-f[b]),f[b]=t}for(g>>=m;g>0;){var w=o[n].s;f[w]<t?g-=1<<t-f[w]++-1:++n}for(;n>=0&&g;--n){var v=o[n].s;f[v]==t&&(--f[v],++g)}h=t}return{t:new Co(f),l:h}},ui=function(e,t,r){return-1==e.s?Math.max(ui(e.l,t,r+1),ui(e.r,t,r+1)):t[e.s]=r},di=function(e){for(var t=e.length;t&&!e[--t];);for(var r=new Ro(++t),n=0,s=e[0],o=1,i=function(e){r[n++]=e},a=1;a<=t;++a)if(e[a]==s&&a!=t)++o;else{if(!s&&o>2){for(;o>138;o-=138)i(32754);o>2&&(i(o>10?o-11<<5|28690:o-3<<5|12305),o=0)}else if(o>3){for(i(s),--o;o>6;o-=6)i(8304);o>2&&(i(o-3<<5|8208),o=0)}for(;o--;)i(s);o=1,s=e[a]}return{c:r.subarray(0,n),n:t}},pi=function(e,t){for(var r=0,n=0;n<t.length;++n)r+=e[n]*t[n];return r},fi=function(e,t,r){var n=r.length,s=ri(t+2);e[s]=255&n,e[s+1]=n>>8,e[s+2]=255^e[s],e[s+3]=255^e[s+1];for(var o=0;o<n;++o)e[s+o+4]=r[o];return 8*(s+4+n)},hi=function(e,t,r,n,s,o,i,a,c,l,u){ai(t,u++,r),++s[256];for(var d=li(s,15),p=d.t,f=d.l,h=li(o,15),g=h.t,m=h.l,y=di(p),b=y.c,w=y.n,v=di(g),I=v.c,T=v.n,_=new Ro(19),E=0;E<b.length;++E)++_[31&b[E]];for(E=0;E<I.length;++E)++_[31&I[E]];for(var S=li(_,7),x=S.t,A=S.l,k=19;k>4&&!x[Do[k-1]];--k);var P,C,R,U,$=l+5<<3,L=pi(s,Yo)+pi(o,qo)+i,D=pi(s,p)+pi(o,g)+i+14+3*k+pi(_,x)+2*_[16]+3*_[17]+7*_[18];if(c>=0&&$<=L&&$<=D)return fi(t,u,e.subarray(c,c+l));if(ai(t,u,1+(D<L)),u+=2,D<L){P=Vo(p,f,0),C=p,R=Vo(g,m,0),U=g;var N=Vo(x,A,0);for(ai(t,u,w-257),ai(t,u+5,T-1),ai(t,u+10,k-4),u+=14,E=0;E<k;++E)ai(t,u+3*E,x[Do[E]]);u+=3*k;for(var O=[b,I],B=0;B<2;++B){var j=O[B];for(E=0;E<j.length;++E){var M=31&j[E];ai(t,u,N[M]),u+=x[M],M>15&&(ai(t,u,j[E]>>5&127),u+=j[E]>>12)}}}else P=Ko,C=Yo,R=Qo,U=qo;for(E=0;E<a;++E){var F=n[E];if(F>255){ci(t,u,P[257+(M=F>>18&31)]),u+=C[M+257],M>7&&(ai(t,u,F>>23&31),u+=$o[M]);var H=31&F;ci(t,u,R[H]),u+=U[H],H>3&&(ci(t,u,F>>5&8191),u+=Lo[H])}else ci(t,u,P[F]),u+=C[F]}return ci(t,u,P[256]),u+C[256]},gi=new Uo([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),mi=new Co(0),yi=function(e,t,r,n,s,o){var i=o.z||e.length,a=new Co(n+i+5*(1+Math.ceil(i/7e3))+s),c=a.subarray(n,a.length-s),l=o.l,u=7&(o.r||0);if(t){u&&(c[0]=o.r>>3);for(var d=gi[t-1],p=d>>13,f=8191&d,h=(1<<r)-1,g=o.p||new Ro(32768),m=o.h||new Ro(h+1),y=Math.ceil(r/3),b=2*y,w=function(t){return(e[t]^e[t+1]<<y^e[t+2]<<b)&h},v=new Uo(25e3),I=new Ro(288),T=new Ro(32),_=0,E=0,S=o.i||0,x=0,A=o.w||0,k=0;S+2<i;++S){var P=w(S),C=32767&S,R=m[P];if(g[C]=R,m[P]=C,A<=S){var U=i-S;if((_>7e3||x>24576)&&(U>423||!l)){u=hi(e,c,0,v,I,T,E,x,k,S-k,u),x=_=E=0,k=S;for(var $=0;$<286;++$)I[$]=0;for($=0;$<30;++$)T[$]=0}var L=2,D=0,N=f,O=C-R&32767;if(U>2&&P==w(S-O))for(var B=Math.min(p,U)-1,j=Math.min(32767,S),M=Math.min(258,U);O<=j&&--N&&C!=R;){if(e[S+L]==e[S+L-O]){for(var F=0;F<M&&e[S+F]==e[S+F-O];++F);if(F>L){if(L=F,D=O,F>B)break;var H=Math.min(O,F-2),G=0;for($=0;$<H;++$){var W=S-O+$&32767,V=W-g[W]&32767;V>G&&(G=V,R=W)}}}O+=(C=R)-(R=g[C])&32767}if(D){v[x++]=268435456|jo[L]<<18|Go[D];var Y=31&jo[L],z=31&Go[D];E+=$o[Y]+Lo[z],++I[257+Y],++T[z],A=S+L,++_}else v[x++]=e[S],++I[e[S]]}}for(S=Math.max(S,A);S<i;++S)v[x++]=e[S],++I[e[S]];u=hi(e,c,l,v,I,T,E,x,k,S-k,u),l||(o.r=7&u|c[u/8|0]<<3,u-=7,o.h=m,o.p=g,o.i=S,o.w=A)}else{for(S=o.w||0;S<i+l;S+=65535){var q=S+65535;q>=i&&(c[u/8|0]=l,q=i),u=fi(c,u+1,e.subarray(S,q))}o.i=i}return ni(a,0,n+ri(u)+s)},bi=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}(),wi=function(e,t,r,n,s){if(!s&&(s={l:1},t.dictionary)){var o=t.dictionary.subarray(-32768),i=new Co(o.length+e.length);i.set(o),i.set(e,o.length),e=i,s.w=o.length}return yi(e,null==t.level?6:t.level,null==t.mem?s.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(e.length)))):20:12+t.mem,r,n,s)},vi=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},Ii=function(e,t,r){for(var n=e(),s=e.toString(),o=s.slice(s.indexOf("[")+1,s.lastIndexOf("]")).replace(/\s+/g,"").split(","),i=0;i<n.length;++i){var a=n[i],c=o[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},Ti=[],_i=function(){return[Co,Ro,Uo,$o,Lo,Do,Bo,Ho,Jo,Xo,Wo,si,Vo,Zo,ei,ti,ri,ni,oi,ii,$i,Si,xi]},Ei=function(){return[Co,Ro,Uo,$o,Lo,Do,jo,Go,Ko,Yo,Qo,qo,Wo,gi,mi,Vo,ai,ci,li,ui,di,pi,fi,hi,ri,ni,yi,wi,Ui,Si]},Si=function(e){return postMessage(e,[e.buffer])},xi=function(e){return e&&{out:e.size&&new Co(e.size),dictionary:e.dictionary}},Ai=function(e,t,r,n,s,o){var i=function(e,t,r,n){if(!Ti[r]){for(var s="",o={},i=e.length-1,a=0;a<i;++a)s=Ii(e[a],s,o);Ti[r]={c:Ii(e[i],s,o),e:o}}var c=vi({},Ti[r].e);return Po(Ti[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,s,function(e,t){i.terminate(),o(e,t)});return i.postMessage([e,t],t.consume?[e.buffer]:[]),function(){i.terminate()}},ki=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},Ci=function(e,t){return Pi(e,t)+4294967296*Pi(e,t+4)},Ri=function(e,t,r){for(;r;++t)e[t]=r,r>>>=8};function Ui(e,t){return wi(e,t||{},0,0)}function $i(e,t){return ii(e,{i:2},t&&t.out,t&&t.dictionary)}var Li=function(e,t,r,n){for(var s in e){var o=e[s],i=t+s,a=n;Array.isArray(o)&&(a=vi(n,o[1]),o=o[0]),o instanceof Co?r[i]=[o,a]:(r[i+="/"]=[new Co(0),a],Li(o,i,r,n))}},Di="undefined"!=typeof TextEncoder&&new TextEncoder,Ni="undefined"!=typeof TextDecoder&&new TextDecoder;try{Ni.decode(mi,{stream:!0})}catch(e){}function Oi(e,t){if(Di)return Di.encode(e);for(var r=e.length,n=new Co(e.length+(e.length>>1)),s=0,o=function(e){n[s++]=e},i=0;i<r;++i){if(s+5>n.length){var a=new Co(s+8+(r-i<<1));a.set(n),n=a}var c=e.charCodeAt(i);c<128||t?o(c):c<2048?(o(192|c>>6),o(128|63&c)):c>55295&&c<57344?(o(240|(c=65536+(1047552&c)|1023&e.charCodeAt(++i))>>18),o(128|c>>12&63),o(128|c>>6&63),o(128|63&c)):(o(224|c>>12),o(128|c>>6&63),o(128|63&c))}return ni(n,0,s)}var Bi=function(e){var t=0;if(e)for(var r in e){var n=e[r].length;n>65535&&oi(9),t+=n+4}return t},ji=function(e,t,r,n,s,o,i,a){var c=n.length,l=r.extra,u=a&&a.length,d=Bi(l);Ri(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|(o<0&&8),e[t++]=s&&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)&&oi(10),Ri(e,t,f<<25|p.getMonth()+1<<21|p.getDate()<<16|p.getHours()<<11|p.getMinutes()<<5|p.getSeconds()>>1),t+=4,-1!=o&&(Ri(e,t,r.crc),Ri(e,t+4,o<0?-o-2:o),Ri(e,t+8,r.size)),Ri(e,t+12,c),Ri(e,t+14,d),t+=16,null!=i&&(Ri(e,t,u),Ri(e,t+6,r.attrs),Ri(e,t+10,i),t+=14),e.set(n,t),t+=c,d)for(var h in l){var g=l[h],m=g.length;Ri(e,t,+h),Ri(e,t+2,m),e.set(g,t+4),t+=4+m}return u&&(e.set(a,t),t+=u),t},Mi="function"==typeof queueMicrotask?queueMicrotask:"function"==typeof setTimeout?setTimeout:function(e){e()};function Fi(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 s=e[t],o=t+1<n?e[t+1]:0;if(("utf-16le"===r||"utf-16"===r)&&0===o&&s<32&&9!==s&&10!==s&&13!==s&&0!==s)return!1;if(("utf-16be"===r||"utf-16"===r)&&0===s&&o<32&&9!==o&&10!==o&&13!==o&&0!==o)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 Hi=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 Gi(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 Wi(e){switch(7&Gi(e)){case 0:return Gi(e),!0;case 1:return e.next(8),!0;case 2:const t=Gi(e);return e.next(t),!0;case 5:return e.next(4),!0}return!1}function Vi(e,t,r){if(0===t)return!1;let n=0;const s=Math.min(t,515),o=Math.min(s,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(s>=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!Fi(e,t,r.encoding);const i=function(e,t){if(t<4)return null;const r=Math.min(t,512);let n=0,s=0;for(let t=0;t<r;t++)0===e[t]&&(t%2==0?n++:s++);const o=n+s;if(o>.3*r&&o<.7*r){if(s>3*n)return"utf-16le";if(n>3*s)return"utf-16be"}return null}(e,t);if(i)return!Fi(e,t,i);for(let t=0;t<o;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<s){if(t++,e[t]>=128&&e[t]<=191)continue}else if(e[t]>=224&&e[t]<=239&&t+2<s){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<s&&(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/o>10)return!0}}return 100*n/o>10||!!(n>1&&function(e,t){const r=new Hi(e,t);let n=0;for(;;){if(!Wi(r)&&!r.hasError())return!1;if(r.hasError())break;n++}return n>0}(e,o))}var Yi=[/^\/$/,/^\*+$/,/^[0-9]+$/],zi=["/artifact/","https://","http://","*********"],qi=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 Ji({sensitiveValues:e,value:t}){return"string"==typeof t?Ki({sensitiveValues:e,str:t}):Array.isArray(t)?t.map(t=>Ji({sensitiveValues:e,value:t})):function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(t)?Xi({obj:t,sensitiveValues:e}):t}function Qi(e){return!!qi.has(e)||e.toLowerCase().endsWith("sha1")}function Xi({obj:e,sensitiveValues:t}){return Object.fromEntries(Object.entries(e).map(([e,r])=>[e,Qi(e)?r:Ji({sensitiveValues:t,value:r})]))}function Zi({error:e,sensitiveValues:t}){return e?{...e,message:Ki({sensitiveValues:t,str:e.message})}:void 0}function ea({content:e,sensitiveValues:t}){const r=new F,n=new H,s=Ki({sensitiveValues:t,str:r.decode(e)});return n.encode(s)}var ta=M(function(e,t,r){r||(r=t,t={}),"function"!=typeof r&&oi(7);var n=[],s=function(){for(var e=0;e<n.length;++e)n[e]()},o={},i=function(e,t){Mi(function(){r(e,t)})};Mi(function(){i=r});for(var a=e.length-22;101010256!=Pi(e,a);--a)if(!a||e.length-a>65558)return i(oi(13,0,1),null),s;var c=ki(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=ki(e,t+28),s=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(Ni)return Ni.decode(e);var s=function(e){for(var t="",r=0;;){var n=e[r++],s=(n>127)+(n>223)+(n>239);if(r+s>e.length)return{s:t,r:ni(e,r-1)};s?3==s?(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&s?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),o=s.s;return(r=s.r).length&&oi(8),o}(e.subarray(t+46,t+46+n),!(2048&ki(e,t+8))),o=t+46+n,i=Pi(e,t+20),a=r&&4294967295==i?function(e,t){for(;1!=ki(e,t);t+=4+ki(e,t+2));return[Ci(e,t+12),Ci(e,t+4),Ci(e,t+20)]}(e,o):[i,Pi(e,t+24),Pi(e,t+42)],c=a[0],l=a[1],u=a[2];return[ki(e,t+10),c,l,s,o+ki(e,t+30)+ki(e,t+32),u]}(e,u,d),a=r[0],l=r[1],p=r[2],h=r[3],g=r[4],m=r[5],y=function(e,t){return t+30+ki(e,t+26)+ki(e,t+28)}(e,m);u=g;var b=function(e,t){e?(s(),i(e,null)):(t&&(o[h]=t),--c||i(null,o))};if(!f||f({name:h,size:l,originalSize:p,compression:a}))if(a)if(8==a){var w=e.subarray(y,y+l);if(p<524288||l>.8*p)try{b(null,$i(w,{out:new Co(p)}))}catch(e){b(e,null)}else n.push(function(e,t,r){return r||(r=t,t={}),"function"!=typeof r&&oi(7),Ai(e,t,[_i],function(e){return Si($i(e.data[0],xi(e.data[1])))},1,r)}(w,{size:p},b))}else b(oi(14,"unknown compression type "+a,1),null);else b(null,ni(e,y,y+l));else b(null,null)},g=0;g<l;++g)h()}else i(null,{});return s}),ra=M(function(e,t,r){r||(r=t,t={}),"function"!=typeof r&&oi(7);var n={};Li(e,"",n,t);var s=Object.keys(n),o=s.length,i=0,a=0,c=o,l=new Array(o),u=[],d=function(){for(var e=0;e<u.length;++e)u[e]()},p=function(e,t){Mi(function(){r(e,t)})};Mi(function(){p=r});var f=function(){var e=new Co(a+22),t=i,r=a-i;a=0;for(var n=0;n<c;++n){var s=l[n];try{var o=s.c.length;ji(e,a,s,s.f,s.u,o);var u=30+s.f.length+Bi(s.extra),d=a+u;e.set(s.c,d),ji(e,i,s,s.f,s.u,o,a,s.m),i+=16+u+(s.m?s.m.length:0),a=d+o}catch(e){return p(e,null)}}!function(e,t,r,n,s){Ri(e,t,101010256),Ri(e,t+8,r),Ri(e,t+10,r),Ri(e,t+12,n),Ri(e,t+16,s)}(e,i,l.length,r,t),p(null,e)};o||f();for(var h=function(e){var t=s[e],r=n[t],c=r[0],h=r[1],g=function(){var e=-1;return{p:function(t){for(var r=e,n=0;n<t.length;++n)r=bi[255&r^t[n]]^r>>>8;e=r},d:function(){return~e}}}(),m=c.length;g.p(c);var y=Oi(t),b=y.length,w=h.comment,v=w&&Oi(w),I=v&&v.length,T=Bi(h.extra),_=0==h.level?0:8,E=function(r,n){if(r)d(),p(r,null);else{var s=n.length;l[e]=vi(h,{size:m,crc:g.d(),c:n,f:y,m:v,u:b!=t.length||v&&w.length!=I,compression:_}),i+=30+b+T+s,a+=76+2*(b+T)+(I||0)+s,--o||f()}};if(b>65535&&E(oi(11,0,1),null),_)if(m<16e4)try{E(null,Ui(c,h))}catch(e){E(e,null)}else u.push(function(e,t,r){return r||(r=t,t={}),"function"!=typeof r&&oi(7),Ai(e,t,[Ei],function(e){return Si(Ui(e.data[0],e.data[1]))},0,r)}(c,h,E));else E(null,c)},g=0;g<c;++g)h(g);return d});async function na({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 F,n=new H,s=r.decode(e).split("\n").map(e=>{if(!e.trim())return e;try{const r=function({event:e,sensitiveValues:t}){return Y(e).with({type:"console"},e=>({...e,args:e.args?.map(e=>({...e,preview:Ki({sensitiveValues:t,str:e.preview}),value:Ji({sensitiveValues:t,value:e.value})})),text:Ki({sensitiveValues:t,str:e.text})})).with({type:"before"},e=>({...e,params:Xi({obj:e.params,sensitiveValues:t}),title:e.title?Ki({sensitiveValues:t,str:e.title}):void 0})).with({type:"after"},e=>({...e,error:Zi({error:e.error,sensitiveValues:t}),result:void 0!==e.result?Ji({sensitiveValues:t,value:e.result}):void 0})).with({type:"action"},e=>({...e,error:Zi({error:e.error,sensitiveValues:t}),params:Xi({obj:e.params,sensitiveValues:t}),result:void 0!==e.result?Ji({sensitiveValues:t,value:e.result}):void 0,title:e.title?Ki({sensitiveValues:t,str:e.title}):void 0})).with({type:"event"},e=>({...e,params:Xi({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:Xi({obj:e.options,sensitiveValues:t}),title:e.title?Ki({sensitiveValues:t,str:e.title}):void 0})).with({type:"frame-snapshot"},e=>({...e,snapshot:Xi({obj:e.snapshot,sensitiveValues:t})})).with({type:"resource-snapshot"},e=>({...e,snapshot:Xi({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(s.join("\n"))}({content:e,sensitiveValues:r}):n.endsWith(".html")||n.endsWith(".dat")||n.endsWith(".json")?ea({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!")}(S(e));const r=C(e,"r"),n=Buffer.alloc(515),s=R(r,n,0,515,0);return U(r),Vi(n,s,t)}return Vi(e,void 0!==t?.size?t.size:e.length,t)}(Buffer.from(e),{size:e.length})}(e)?e:ea({content:e,sensitiveValues:t})}({content:e,sensitiveValues:r}):e}var sa=e=>(e instanceof Error?e.message:String(e)).slice(0,400),oa=async e=>{const t=await Z(e,{withFileTypes:!0}),r=[];for(const s of t){const t=n.join(e,s.name);if(s.isDirectory())r.push(...await oa(t));else if(s.isFile()&&"trace.zip"===s.name){const e=await ee(t);r.push({path:t,mtimeMs:e.mtimeMs})}}return r},ia=async({tracePath:e,outputDir:t,requestUploadUrl:r})=>{try{let n=e;if(!n){if(!t)return{status:"capture_failed",error:"Either tracePath or outputDir must be provided."};if(!E(t))return{status:"capture_failed",error:`Output directory does not exist: ${t}`};n=await(async e=>{const t=await oa(e);if(0!==t.length)return t.sort((e,t)=>t.mtimeMs-e.mtimeMs),t[0]?.path})(t)}if(!n)return{status:"capture_failed",error:"No trace.zip found in the output directory."};const{traceBucketPath:s,uploadUrl:o,sensitiveValues:i}=await r(),a=await async function({tracePath:e,sensitiveValues:t}){const r=[],n=P(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||Yi.some(t=>t.test(e))||zi.some(t=>e.includes(t))));if(0===r.length)return new Uint8Array(t);const n=[...r].sort((e,t)=>t.length-e.length),s=await ta(new Uint8Array(t)),o=Object.entries(s),i=await Promise.all(o.map(async([e,t])=>[e,await na({content:t,filename:e,sensitiveValues:n})])),a=Object.fromEntries(i);return ra(a)}({traceBuffer:new Uint8Array(Buffer.concat(r)),sensitiveValues:t})}({tracePath:n,sensitiveValues:i});try{await ys({body:a,contentType:"application/zip",uploadUrl:o,errorContext:"trace"})}catch(e){return{status:"upload_failed",error:sa(e)}}return{status:"captured",storage:s}}catch(e){return{status:"upload_failed",error:sa(e)}}},{zMarkdownAutoHealReport:aa,zRepresentativeTest:ca}=function(e){const t=e.enum(kr),r=["Classification of the root cause:","",`- test: ${Cr("test")}`,`- bug: ${Cr("bug")}`,`- flake: ${Cr("flake")}`,`- ui_change: ${Cr("ui_change")}`,`- other: ${Cr("other")}`].join("\n"),n=e.object({filePath:e.string().optional(),testIdentifier:e.string().optional(),testTitle:e.string().optional()}),s=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(),testPassed:e.boolean().optional(),testExitCode:e.number().nullable().optional(),testStderr:e.string().optional()}),o=s.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(o).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:s.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")})]),c=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.")}),l=e.discriminatedUnion("result",[e.object({result:e.literal("fixed"),issueType:t,issueId:e.string().optional().describe("Issue ID from triage, used for deterministic fingerprinting across re-uploads."),rootCause:e.string().min(1),fixApplied:e.string().min(1).describe("What fix was applied (brief, specific). Include file:line references."),relatedTestCaseIds:e.array(e.string()).min(1)}),e.object({result:e.literal("unfixed"),issueType:t,issueId:e.string().optional().describe("Issue ID from triage, used for deterministic fingerprinting across re-uploads."),rootCause:e.string().min(1),reasonNotFixed:e.string().min(1).describe("Why it could not be auto-fixed (brief). Include file:line references."),relatedTestCaseIds:e.array(e.string()).min(1)})]),u=e.object({format:e.literal("markdown"),markdown:e.string().min(1).describe("Flexible markdown report content for the auto-heal run. Use headings, bullets, and code fences as needed."),summary:e.string().optional().describe('One-liner summary of the auto-heal run (e.g., "Fixed 2 of 3 issues: stale locators and timing"). Used in notifications, API responses, and triage agent context.'),issues:e.array(l).optional().describe("Structured issue metadata for database tracking. Each issue links a root cause to affected test case IDs.")});return{zAutoHealReport:a,zIssueCategory:t,zMarkdownAutoHealReport:u,zMarkdownAutoHealReportIssue:l,zRepresentativeTest:n,zSuiteAutoHealReport:c,zStoredAutoHealReport:e.union([u,c]),zTraceProof:s,zTraceProofByTest:o}}(ve),la=({authProvider:e,diffTracker:t,orgId:r,runId:n,workingDir:s})=>G({name:"auto-heal-report",tools:[W("upload-trace-proof",["Upload a Playwright trace proof for a test case.","","IMPORTANT: This tool does NOT run tests. You must run the test yourself first","using Playwright with --trace=on and --output <dir>, then call this tool to upload the trace.","","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 the outputDir that was used as the --output flag in your test run.","Optionally pass tracePath if you know the exact path to the trace.zip file."].join("\n"),{outputDir:ve.string().min(1).optional().describe("The --output directory from the Playwright test run containing trace.zip. Required if tracePath is not provided."),tracePath:ve.string().min(1).optional().describe("Optional direct path to trace.zip. If omitted, the newest trace in outputDir is used."),issueId:ve.string().min(1).describe("Issue identifier for deterministic output paths and storage key naming."),proofId:ve.string().min(1).optional().describe("Optional id for deterministic proof naming and deduplication."),testCaseId:ve.string().min(1).optional().describe("Optional test case ID when uploading per-test trace proofs."),testPassed:ve.boolean().describe("Whether the test run passed (exit code 0). You MUST check the exit code of stably-browser run-test before calling this tool. Exit code 0 = passed, non-zero = failed."),representativeTest:ca.optional().default({})},async({outputDir:t,tracePath:s,issueId:o,proofId:i,representativeTest:a,testCaseId:c,testPassed:l})=>{const u=await e.getAuthHeader(),d=ve.string().min(1).parse(o),p=null==i?void 0:ve.string().min(1).parse(i),f=null==c?void 0:ve.string().min(1).parse(c),h=ca.parse(a??{}),g=await ia({tracePath:s,outputDir:t,requestUploadUrl:()=>(async({authHeader:e,issueId:t,proofId:r,testCaseId:n,contentType:s="application/zip",orgId:o,runId:i})=>{const a=await(c={auth:e,body:{contentType:s,issueId:t,proofId:r,testCaseId:n},client:pn(),headers:hs(o),path:{runId:i}},(c.client??Zr).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=ws.parse(a.data);return{traceBucketPath:l.traceBucketPath,expiresInSeconds:l.expiresInSeconds,key:l.key,uploadUrl:l.uploadUrl,sensitiveValues:l.sensitiveValues}})({authHeader:u,issueId:d,proofId:p,orgId:r,runId:n,testCaseId:f})}),m=h.testTitle||h.filePath,y="captured"===g.status&&g.storage?`@[trace:${Buffer.from(JSON.stringify({...g.storage,...m?{label:m}:{}})).toString("base64url")}]`:void 0,b={...g,testPassed:!!l,tracePlaceholder:y},w="string"==typeof f?{testCaseId:f,...b}:{...b},v=l?"":'\n\nWARNING: testPassed=false β this trace documents a FAILURE, not a successful fix. Do NOT report result:"fixed" for this test. If you applied a fix but the verification run failed (e.g., auth setup error, missing env vars), the fix is NOT proven. Report result:"unfixed" with the failure reason.';return{content:[{text:JSON.stringify(w)+v,type:"text"}]}}),W("generate-report",["After attempting to fix all broken tests (skip only those truly infeasible), generate a markdown auto-heal report.","","The UI renders this markdown into structured cards based on ## and ### headings. Follow the heading structure from the MARKDOWN REPORT STRUCTURE section in your instructions:","- ## Summary, ## Fixed Issues (with ### per issue), ## Unfixed Issues (with ### per issue)",'- Each ### must be a short descriptive slug (e.g. "invite-member-flaky-timeouts")',"- Use **bold labels:** for fields (Tests, Flaky signal, Root cause, Fix applied, Why not fixed, Proof of fixed tests)","- Include **Flaky signal:** inside an issue card only when triage flagged that test as flaky β do NOT create a separate ## section for flaky signals","","Write for readability: keep bullets concise, use tables only when they genuinely improve scanability, and wrap file paths, commands, selectors, and code in backticks.","Prefer short sections over long paragraphs. Call out important outcomes first, then supporting evidence.","","ENTITY REFERENCES: When referencing entities by ID, use placeholder syntax so the UI can render clickable links:","- Test cases: @[test-case:<id>] (e.g., @[test-case:fp8f0yzdqqut6bg7cy5euzer])","- Suite runs: @[suite-run:<id>] (e.g., @[suite-run:cm6i7o6ti0000l40350wys0u1])","- Tests: @[test:<id>] (e.g., @[test:wty0g1v58cwrrd8jj6et8nmx])","- Traces: use the tracePlaceholder value returned by upload-trace-proof (e.g., @[trace:eyJi...])","These placeholders will be automatically resolved to clickable links with human-readable labels in the UI.","NEVER show raw entity IDs without wrapping them in @[type:id] syntax."].join("\n"),{markdown:aa.shape.markdown,summary:aa.shape.summary,issues:aa.shape.issues},async({markdown:s,summary:o,issues:i})=>{const a=await e.getAuthHeader(),c=await t.computeDiff(),l=aa.parse({format:"markdown",markdown:s,summary:o,issues:i});try{await(async({authHeader:e,orgId:t,report:r,runId:n})=>{const s=await(o={auth:e,body:{report:JSON.stringify(r)},client:pn(),headers:hs(t),path:{runId:n}},(o.client??Zr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-report",...o,headers:{"Content-Type":"application/json",...o.headers}}));var o;if(s.error)throw new Error(`Failed to upload auto-heal report (${s.response.status})`)})({authHeader:a,orgId:r,report:l,runId:n});const{diffBucketPath:e,uploadUrl:t}=await vs({authHeader:a,contentType:"text/plain",orgId:r,runId:n});await ys({body:c,contentType:"text/plain",uploadUrl:t,errorContext:"diff"}),await Is({authHeader:a,diffBucketPath:e,orgId:r,runId:n})}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"});function ua({workingDir:e,packageManager:t,packageSpec:r,targetSection:n}){const{command:s,args:o}=function(e,t,r){const n="npm"===e?"npm":e;return{command:n,args:["npm"===e?"install":"add",..."devDependencies"===r?["bun"===e?"-d":"-D"]:[],..."npm"===n?["--no-fund"]:[],t]}}(t,r,n);y(s,o,{cwd:e,stdio:"pipe",timeout:6e4})}function da(e){const t=r.join(e,"package.json");return w.existsSync(t)?{path:t,contents:JSON.parse(w.readFileSync(t,"utf-8"))}:null}var pa=["playwright.config.ts","playwright.config.js","playwright.config.mts","playwright.config.mjs","playwright.config.cjs"];function fa(e){return pa.some(t=>w.existsSync(r.join(e,t)))}function ha(e,t){const n=w.readdirSync(e,{withFileTypes:!0}),s=[];for(const o of n){if("node_modules"===o.name||".git"===o.name)continue;const n=r.join(e,o.name);o.isDirectory()?s.push(...ha(n,t)):t.test(o.name)&&s.push(n)}return s}function ga(e){let t=r.resolve(e);for(;;){if(fa(t))return t;const n=r.dirname(t);if(n===t)return e;t=n}}function ma(e){const t=Array.from(new Set(e.map(e=>r.resolve(e)))).sort((e,t)=>e.length-t.length),n=[];for(const e of t)n.some(t=>e===t||e.startsWith(`${t}${r.sep}`))||n.push(e);return n}function ya(e){return/\b(test|testing|playwright|e2e|stably)\b/i.test(e)}function ba(e,t){for(const n of wa(e,t))if(w.existsSync(r.join(n,"package.json")))return n}function wa(e,t){const n=[];let s=r.resolve(e);const o=r.resolve(t);for(;n.push(s),s!==o;){const e=r.dirname(s);if(e===s)break;s=e}return n}function va(e){return e?.replace(/^[~^>=<]+/,"")}function Ia(e){let t=e;for(let e=0;e<5;e++){if(w.existsSync(r.join(t,"pnpm-lock.yaml")))return"pnpm";if(w.existsSync(r.join(t,"yarn.lock")))return"yarn";if(w.existsSync(r.join(t,"bun.lockb"))||w.existsSync(r.join(t,"bun.lock")))return"bun";if(w.existsSync(r.join(t,"package-lock.json"))||w.existsSync(r.join(t,"npm-shrinkwrap.json")))return"npm";const e=r.dirname(t);if(e===t)break;t=e}return"npm"}var Ta=ve.object({commentUrl:ve.string()}),_a=({prContext:e,authProvider:t,orgId:r,onReportPosted:n})=>G({name:"create-report",tools:[W("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:ve.string().describe("A summary of the tests created. Include what features/flows are tested and any important notes."),filesCreated:ve.array(ve.string()).describe("List of test file paths that were created (relative to workspace root)")},async({summary:s,filesCreated:o})=>{const i=await t.getAuthHeader(),a=Array.isArray(o)?o:[];es.info("[create-report] Posting report to GitHub PR",{prNumber:e.prNumber,filesCount:a.length});try{const t={summary:"string"==typeof s?s:String(s),filesCreated:a.map(String)},o=await async function({authHeader:e,orgId:t,prNumber:r,owner:n,repo:s,report:o}){const i=new URL("/internal/v1/cli/create-report",nn).toString(),a={Authorization:e,"Content-Type":"application/json"};t&&(a["x-stably-org-id"]=t),es.debug("Posting create report to GitHub",{prNumber:r,owner:n,repo:s,filesCount:o.filesCreated.length});const c=await fetch(i,{method:"POST",headers:a,body:JSON.stringify({prNumber:r,owner:n,repo:s,report:o}),signal:AbortSignal.timeout(3e4)});if(!c.ok){const e=await c.text().catch(()=>"");throw es.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=Ta.parse(await c.json());return es.info("Create report posted successfully",{commentUrl:l.commentUrl}),l}({authHeader:i,orgId:r,prNumber:e.prNumber,owner:e.owner,repo:e.repo,report:t});return n?.(o),es.info("[create-report] Report posted successfully",{commentUrl:o.commentUrl}),{content:[{type:"text",text:`β
Test creation report posted to PR #${e.prNumber}\n\nView the comment: ${o.commentUrl}`}]}}catch(e){const t=e instanceof Error?e.message:String(e);return es.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}}})]}),Ea=ve.object({traceBucketPath:ms,expiresInSeconds:ve.number(),key:ve.string(),uploadUrl:ve.string(),sensitiveValues:ve.array(ve.string())}),Sa=({authProvider:e,sessionId:t,orgId:r,workingDir:n,onTraceProofCaptured:s})=>G({name:"upload-trace-proof",tools:[W("upload-trace-proof",["Upload a Playwright trace proof for a created test file.","","IMPORTANT: This tool does NOT run tests. You must run the test yourself first","using Playwright with --trace=on and --output <dir>, then call this tool to upload the trace.","","Call this after running a created test file with tracing enabled.","The trace proves the test works and is viewable in the Stably web UI.","","Pass the testFilePath of the created test file and the outputDir from the --output flag.","Optionally pass tracePath if you know the exact path to the trace.zip file.","Optionally pass representativeTest to provide metadata for trace labeling."].join("\n"),{testFilePath:ve.string().min(1).describe("Path to the created test file (relative to workspace root)."),outputDir:ve.string().min(1).optional().describe("The --output directory from the Playwright test run containing trace.zip. Required if tracePath is not provided."),tracePath:ve.string().min(1).optional().describe("Optional direct path to trace.zip. If omitted, the newest trace in outputDir is used."),representativeTest:ca.optional().default({})},async({testFilePath:n,outputDir:o,tracePath:i,representativeTest:a})=>{const c=await e.getAuthHeader(),l=ve.string().min(1).parse(n);ca.parse(a??{}),es.info("[upload-trace-proof] Uploading trace",{testFilePath:l,outputDir:o});const u=await ia({tracePath:i,outputDir:o,requestUploadUrl:()=>(async({authHeader:e,sessionId:t,testFilePath:r,orgId:n,contentType:s="application/zip"})=>{const o=await(i={auth:e,body:{testFilePath:r,contentType:s},client:pn(),headers:hs(n),path:{sessionId:t}},(i.client??Zr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/sessions/{sessionId}/trace/upload-url",...i,headers:{"Content-Type":"application/json",...i.headers}}));var i;if(o.error)throw new Error(`Failed to presign session trace upload (${o.response.status})`);const a=Ea.parse(o.data);return{traceBucketPath:a.traceBucketPath,expiresInSeconds:a.expiresInSeconds,key:a.key,uploadUrl:a.uploadUrl,sensitiveValues:a.sensitiveValues}})({authHeader:c,sessionId:t,testFilePath:l,orgId:r})});"captured"===u.status?es.info("[upload-trace-proof] Upload succeeded",{testFilePath:l,traceBucketPath:u.storage}):es.error("[upload-trace-proof] Failed",{testFilePath:l,error:u.error});const d={testFilePath:l,status:u.status,storage:"captured"===u.status?u.storage:null,..."error"in u?{error:u.error}:{}};return s?.(d),{content:[{type:"text",text:JSON.stringify(d)}]}})]}),xa=["QUEUED","RUNNING","PASSED","FAILED","TIMEDOUT","CANCELLED","INTERRUPTED"],Aa=["LOCAL","CI","WEB"],ka=["MANUAL","SCHEDULED","UI","API","GITHUB_ACTION","SUITE_RUN"],Pa=({authProvider:e,orgId:t,projectId:r})=>G({name:"run-history",tools:[W("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- Find the most recent run: { "limit": 1 }\n\nIf the user asks about test failures without specifying a run, use this to discover recent failed runs.\n\nReturns an array of runs with their runId, status, autoHealStatus, branch, and timestamps.',{branch:ve.string().optional().describe("Filter by branch name"),status:ve.enum(xa).optional().describe("Filter by status: QUEUED|RUNNING|PASSED|FAILED|TIMEDOUT|CANCELLED|INTERRUPTED"),limit:ve.number().min(1).max(100).optional().describe("Max results (1-100, default 20)"),source:ve.enum(Aa).optional().describe("Filter by source: LOCAL|CI|WEB"),trigger:ve.enum(ka).optional().describe("Filter by trigger: MANUAL|SCHEDULED|UI|API|GITHUB_ACTION|SUITE_RUN"),suite:ve.string().optional().describe("Filter by suite name"),after:ve.string().optional().describe("Pagination: return runs after this runId"),before:ve.string().optional().describe("Pagination: return runs before this runId")},async({branch:n,status:s,limit:o,source:i,trigger:a,suite:c,after:l,before:u})=>{const d=await e.getAuthHeader(),p="string"==typeof n?n:void 0,f="string"==typeof s?s:void 0,h="number"==typeof o?o:void 0,g="string"==typeof i?i:void 0,m="string"==typeof a?a:void 0,y="string"==typeof c?c:void 0,b="string"==typeof l?l:void 0,w="string"==typeof u?u:void 0;es.info("[run-history] list_runs called",{branch:p,status:f,limit:h});try{const e=await en({auth:d,client:pn(),headers:hs(t),query:{projectId:r,branchName:p,status:f,limit:h,source:g,trigger:m,suiteName:y,afterRunId:b,beforeRunId:w}});if(e.error||!e.data){const t=e.response?`API error: ${e.response.status}`:`API error: ${String(e.error)}`;return es.error("[run-history] list_runs failed",{error:t}),{content:[{type:"text",text:`Error: ${t}`}],isError:!0}}return es.info("[run-history] list_runs success",{runCount:e.data.runs?.length??0,hasMore:e.data.hasMore}),{content:[{type:"text",text:JSON.stringify(e.data)}]}}catch(e){const t=e instanceof Error?e.message:String(e);return es.error("[run-history] list_runs exception",{error:t}),{content:[{type:"text",text:`Error: ${t}`}],isError:!0}}}),W("view_run",'Get detailed information about a specific run including issues and test results.\n\nThe response includes:\n- Run metadata (status, branch, timestamps, envName)\n- Issues array with result ("fixed"/"unfixed"), rootCause, and relatedTestIdentifiers\n- Test results with their outcomes\n- envName: the remote environment used (e.g., "staging") β if present, call load_environment with this name before rerunning tests\n\nUse this to examine run details and determine which tests failed or were previously fixed.',{runId:ve.string().min(1).describe("The run ID to view (required)")},async({runId:r})=>{const n=await e.getAuthHeader(),s="string"==typeof r?r:String(r);es.info("[run-history] view_run called",{runId:s});try{const e=await tn({auth:n,client:pn(),headers:hs(t),path:{runId:s},query:{detail:"full"}});if(e.error||!e.data){const t=e.response?404===e.response.status?`Run "${s}" not found`:`API error: ${e.response.status}`:`API error: ${String(e.error)}`;return es.error("[run-history] view_run failed",{error:t,runId:s}),{content:[{type:"text",text:`Error: ${t}`}],isError:!0}}return es.info("[run-history] view_run success",{runId:s}),{content:[{type:"text",text:JSON.stringify(e.data)}]}}catch(e){const t=e instanceof Error?e.message:String(e);return es.error("[run-history] view_run exception",{error:t,runId:s}),{content:[{type:"text",text:`Error: ${t}`}],isError:!0}}})]}),Ca=({hookEnvVars:e,initialRemoteKeys:t,localEnvSnapshot:r})=>{const n=r?new Set(Object.keys(r)):void 0;let s=t;return G({name:"environment",tools:[W("load_environment",'Load remote environment variables by name (e.g., "staging", "production").\nUse this when you discover a run was executed with a specific --env and need\nthose variables for rerunning tests.\n\nAfter loading, all subsequent stably-browser run-test commands will automatically\nhave these environment variables injected. Use process.env.VARNAME syntax in test\ncode for these variables.\n\nReturns the list of variable names loaded (never values, for security).',{envName:ve.string().min(1).describe('Environment name to load (e.g., "staging")')},async({envName:t})=>{const o="string"==typeof t?t:String(t);es.info("[load-environment] Loading environment",{envName:o});try{const t=await ps(o);if(!t.ok)return es.warn("[load-environment] Failed to load environment",{envName:o,error:t.error}),{content:[{type:"text",text:`Error: ${t.error}`}],isError:!0};if(s)for(const t of s)n?.has(t)&&r?e[t]=r[t]:delete e[t];delete e.STABLY_SENSITIVE_VALUES,Object.assign(e,t.result.variables),s=new Set(Object.keys(t.result.variables)),t.result.sensitiveValues.length>0&&(e.STABLY_SENSITIVE_VALUES=Buffer.from(JSON.stringify(t.result.sensitiveValues)).toString("base64"));const i=Object.keys(t.result.variables);return es.info("[load-environment] Environment loaded",{envName:o,variableCount:i.length}),{content:[{type:"text",text:`Successfully loaded ${i.length} variable(s) from "${o}" environment.\n\nVariable names: ${i.join(", ")}\n\nThese are now available for stably-browser run-test commands. Use \`process.env.VARNAME\` syntax in test code for these variables.`}]}}catch(e){const t=e instanceof Error?e.message:String(e);return es.error("[load-environment] Exception loading environment",{envName:o,error:t}),{content:[{type:"text",text:`Error: ${t}`}],isError:!0}}})]})},Ra=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]"),Ua=(e,t)=>({message:Ra(e),status:t?.status,statusText:t?.statusText}),$a=["ANTHROPIC_","CLAUDE"],La=new Set(["AWS_BEARER_TOKEN_BEDROCK","BASH_DEFAULT_TIMEOUT_MS","BASH_MAX_OUTPUT_LENGTH","BASH_MAX_TIMEOUT_MS","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"]),Da=async({authHeader:e,mode:t,maxTurnsOverride:r})=>{const n=pn();es.debug("Requesting subagent definitions from API",{mode:t,maxTurnsOverride:r});const s=await(o={client:n,auth:e,body:{mode:t,maxTurnsOverride:r}},(o.client??Zr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/prompts/subagents",...o,headers:{"Content-Type":"application/json",...o.headers}}));var o;if(401===s.response.status)throw es.warn("Subagent definitions fetch failed: unauthorized (401)"),await kn(),new Error("Your session has expired or been revoked. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(403===s.response.status)throw es.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(s.error)throw es.warn("Subagent definitions fetch failed",{error:s.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}=s.data;return es.debug("Subagent definitions received",{count:Object.keys(i).length}),i},Na=n.dirname($(import.meta.url)),Oa=n.join(".claude-plugin","plugin.json"),Ba=[n.join("packages","agent-plugin","stably-plugin-cli"),n.join("agent-plugin","stably-plugin-cli")];function ja(e){return E(n.join(e,Oa))}var{zStablyYaml:Ma}=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().default(50),maxParallelWorkers:e.number().int().positive().default(3),rules:e.string().optional(),skipAfterConsecutiveUnfixed:e.number().int().positive().default(2),maxBudgetUsd:e.number().positive().default(50)}),n=e.object({maxTurnsPerTestFile:e.number().int().positive().default(200),maxBudgetUsd:e.number().positive().default(50)}),s=e.object({fix:r.optional(),create:n.optional()}),o=e.object({setupScript:e.string().optional()});return{zStablyYaml:e.object({schedules:e.record(e.string(),t).optional(),agent:s.optional(),cloud:o.optional()}),zAgentConfig:s,zAgentFixConfig:r,zAgentCreateConfig:n,zScheduleEntry:t,zCloudConfig:o}}(ge),Fa=async(e,t)=>{try{const r=await wn(e,t);if(!r)return void es.debug(`No ${t} found`);const n=await q(r,"utf-8");if(!n.trim())return;return n.length>1e4?(es.warn(`${t} exceeds max length (${n.length} > 10000), truncating`,{path:r}),{content:n.slice(0,1e4),path:r}):(es.debug(`Loaded ${t} rules`,{path:r,contentLength:n.length}),{content:n,path:r})}catch(e){return void es.warn(`Failed to read ${t}`,{error:e})}},Ha=/\bstably-browser\b/,Ga=/\bpwtrace\b/,Wa="(?:(?:-\\w+=?\\S*|--\\w+=?\\S*|-s\\s+\\S+|--session\\s+\\S+)\\s+)*",Va=new RegExp(`\\bstably-browser\\s+${Wa}run-test\\b`),Ya=/\$\{process\.env\.([a-zA-Z_][a-zA-Z0-9_]*)\}/g,za=e=>/^[A-Za-z0-9_./:@=-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`,qa=".stably-browser";async function Ka(){const e=i(o($(import.meta.url)),"stably-browser.js");if(E(e))return e;es.debug("[stably-browser-hook] Bundled binary not found",{checkedPath:e});try{return Ue.resolve("@stablyai-internal/playwright-cli/playwright-cli.js")}catch{es.debug("[stably-browser-hook] @stablyai-internal/playwright-cli not resolvable from node_modules")}return new Promise((e,t)=>{m("which",["stably-browser"],(r,n)=>{if(r||!n.trim())return es.warn("[stably-browser-hook] stably-browser not found on PATH",{error:r?.message}),void t(new Error("stably-browser not found. Ensure @stablyai-internal/playwright-cli is installed or stably-browser is on PATH."));e(n.trim())})})}async function Ja(){const e=i(o($(import.meta.url)),"pwtrace.js");if(E(e))return e;try{return Ue.resolve("@stablyai-internal/pwtrace/bin/cli.js")}catch{}return new Promise((e,t)=>{m("which",["pwtrace"],(r,n)=>{!r&&n.trim()?e(n.trim()):t(new Error("pwtrace not found. Ensure @stablyai-internal/pwtrace is installed or pwtrace is on PATH."))})})}function Qa(e,t,r=!1){const n=`${e}\n${t}`;return n.includes("spawn")&&n.includes("ENOENT")&&!n.includes("Executable doesn't exist")?{reason:"Browser binary exists but cannot be executed (likely Alpine Linux / musl libc incompatibility).",guidance:"The Chromium binary was downloaded but the OS cannot execute it. This usually happens on Alpine Linux containers because Chromium is compiled for glibc, not musl. Ask the user to either: (1) switch to a glibc-based image like node:20-slim instead of node:20-alpine, (2) install glibc compatibility with `apk add gcompat`, or (3) use the official Playwright Docker image (mcr.microsoft.com/playwright). Do not attempt to install browsers β they are already installed, the issue is OS-level."}:n.includes("is not installed")||n.includes("Executable doesn't exist")?{reason:"Browser is not installed in this environment.",guidance:"The Playwright browser binary is missing. Ask the user to run `npx playwright install chromium` in their environment (or add it to their Dockerfile/CI setup). Do not attempt to install browsers yourself. You can still analyze test code, make fixes, and use upload-trace-proof (it only uploads existing traces, no browser needed), but cannot run tests locally until browsers are installed."}:n.includes("Missing system dependencies")||n.includes("cannot open shared object file")?{reason:"Browser system dependencies are missing.",guidance:"The browser binary exists but required system libraries are missing. Ask the user to run `npx playwright install-deps chromium` (requires apt/sudo) or use a Playwright Docker image. Do not attempt to install system packages yourself."}:n.includes("already in use")?{reason:"Browser profile is locked by another process.",guidance:"Another browser session is using the same profile. Try closing the existing session with `stably-browser close` first, or use a different session name."}:n.includes("sandboxing failed")||n.includes("--no-sandbox")?{reason:"Browser sandboxing failed (likely running as root in a container).",guidance:"Chrome cannot create a sandbox when running as root. Ask the user to either: (1) add `chromiumSandbox: false` to their Playwright launch options, (2) add `--no-sandbox` to their Chrome args, or (3) run the container as a non-root user. Do not attempt to fix this yourself β it requires changes to the user's Playwright config or Docker setup."}:r||e.includes("ETIMEDOUT")||e.includes("timed out")?{reason:"Daemon startup timed out.",guidance:"The browser daemon did not start within 30 seconds. This may be caused by slow browser download, resource constraints, or a hung process. Retry once, and if it fails again, ask the user to check their environment."}:{reason:n.slice(0,500).trim(),guidance:"An unexpected error occurred starting the browser daemon. Share the error with the user."}}async function Xa(e,t,r,n,s="chromium"){const o=["open",`-s=${t}`];r&&o.push("--headed"),n?o.push(`--config=${n}`):o.push(`--browser=${s}`),es.info("[stably-browser-hook] Starting daemon",{bin:e,args:o});const i=process.env.CHROME_BIN?{...process.env,PLAYWRIGHT_MCP_EXECUTABLE_PATH:process.env.CHROME_BIN}:void 0;return new Promise(t=>{m(process.execPath,[e,...o],{timeout:3e4,env:i},(e,r,n)=>{if(e)return es.error("[stably-browser-hook] Failed to start daemon",{error:e.message,stderr:n}),void t({ok:!1,...Qa(e.message,n??"",e.killed??!1)});es.info("[stably-browser-hook] Daemon started",{stdout:r.trim()}),t({ok:!0})})})}function Za(e,t){return t?`${e}-${t}`:e}function ec(e){if(e&&"object"==typeof e&&"agent_id"in e){const t=e.agent_id;return"string"==typeof t?t:void 0}}async function tc(e,t,r){const n=new URL(`/internal/v1/browser/request/${t}`,nn);n.searchParams.set("projectId",r);const s=await fetch(n.toString(),{method:"GET",headers:{Authorization:`Bearer ${e}`}});if(!s.ok)throw new Error(`Poll failed: HTTP ${s.status}`);return s.json()}async function rc(e,t,r){const n=new URL(`/internal/v1/browser/request/${t}/acquire`,nn).toString(),s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({projectId:r})});if(!s.ok)throw new Error(`Acquire failed: HTTP ${s.status}`);return s.json()}async function nc(e,t,r){const n=new URL(`/internal/v1/cli/browser/kernelsh/${r}/health`,nn);n.searchParams.set("projectId",t);const s=n.toString();try{const t=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${e}`}});return!!t.ok&&(await t.json()).alive}catch{return!1}}var sc=2e3,oc=class{authProvider;projectId;sessions=new Map;healthCheckTimer=null;released=!1;configDir=null;constructor(e){this.authProvider=e.authProvider,this.projectId=e.projectId}async acquire(e,t){const r=this.sessions.get(e);if(r&&!r.needsRecreation)return r.session;r?.needsRecreation&&await this.releaseSession(e),this.released=!1;const n=await this.acquireViaQueue(t);es.info("[cloud-browser] Waiting for CDP endpoint to be ready...",{sessionName:e,sessionId:n.sessionId}),await async function(e){const t=Date.now()+3e4;for(;Date.now()<t;)try{return void await new Promise((t,r)=>{const n=new Ie(e),s=setTimeout(()=>{n.close(),r(new Error("CDP connection timeout"))},5e3);n.on("open",()=>{n.send(JSON.stringify({id:1,method:"Browser.getVersion",params:{}}))}),n.on("message",e=>{try{const o=JSON.parse(e.toString());1===o.id&&(clearTimeout(s),n.close(),o.error?r(new Error(`CDP error: ${o.error.message}`)):t())}catch{}}),n.on("error",e=>{clearTimeout(s),n.close(),r(e)})})}catch(e){const r=t-Date.now();if(r<=500)throw new Error(`CDP endpoint not ready after 30000ms: ${e instanceof Error?e.message:String(e)}`);es.debug("[cloud-browser] CDP not ready, retrying...",{error:e instanceof Error?e.message:String(e),remainingMs:r}),await ic(500)}throw new Error("CDP endpoint not ready after 30000ms")}(n.cdpUrl),es.info("[cloud-browser] CDP endpoint ready",{sessionName:e,sessionId:n.sessionId});const s=this.writeConfig(e,n.cdpUrl);return this.sessions.set(e,{session:n,configPath:s,needsRecreation:!1}),this.ensureHealthCheck(),n}async release(){if(this.released)return;this.released=!0,this.stopHealthCheck();const e=Array.from(this.sessions.keys()).map(e=>this.releaseSession(e));await Promise.all(e),this.cleanupConfigDir()}needsRecreation(e){return this.sessions.get(e)?.needsRecreation??!1}getConfigPath(e){return this.sessions.get(e)?.configPath??null}getAnyConfigPath(){for(const e of this.sessions.values())if(!e.needsRecreation)return e.configPath;return null}isActive(){return this.sessions.size>0&&!this.released}removeSession(e){this.sessions.delete(e)}async acquireViaQueue(e){const t=await this.authProvider.getAuthHeader(),r=await async function(e,t){const r=new URL("/internal/v1/browser/request",nn).toString();try{const n=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({projectId:t,source:"cli-browser-session"})});if(n.ok||202===n.status){const e=await n.json();return{ok:!0,browserRequestId:e.browserRequestId,initialStatus:e.status}}if(403===n.status)return{ok:!1,status:"forbidden",message:(await n.json().catch(()=>({error:"Forbidden"}))).error??"Cloud browsers not available on your plan."};const s=await n.text().catch(()=>"");return{ok:!1,status:"error",message:`HTTP ${n.status}: ${s.slice(0,200)}`}}catch(e){return{ok:!1,status:"error",message:e instanceof Error?e.message:String(e)}}}(t,this.projectId);if(!r.ok){if("forbidden"===r.status)throw new Error(`Cloud browsers not available on your plan. ${r.message}`);throw new Error(`Cloud browser unavailable: ${r.message}`)}const{browserRequestId:n,initialStatus:s}=r;"queued"===s&&e?.();const o=Date.now()+3e5;for(;Date.now()<o;){const t=await this.authProvider.getAuthHeader(),r=await tc(t,n,this.projectId);switch(r.status){case"pending":await ic(sc);continue;case"queued":e?.(),await ic(sc);continue;case"provisioning":es.debug("[cloud-browser] Browser is starting up..."),await ic(sc);continue;case"ready":try{const e=await this.authProvider.getAuthHeader(),t=await rc(e,n,this.projectId);return{sessionId:t.sessionId,browserRequestId:n,cdpUrl:t.cdpUrl,liveViewUrl:t.liveViewUrl??""}}catch{es.debug("[cloud-browser] Acquire failed, re-polling status"),await ic(sc);continue}case"failed":throw new Error(r.error??"Browser provisioning failed. Please try again.");case"cancelled":case"stopped":throw new Error("Browser request was cancelled.");default:throw new Error(`Unexpected browser request status: ${r.status}`)}}const i=await this.authProvider.getAuthHeader();throw await async function(e,t,r){const n=new URL(`/internal/v1/browser/request/${t}/cancel`,nn).toString();try{const s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({projectId:r})});s.ok||es.warn("[cloud-browser] Failed to cancel browser request",{browserRequestId:t,status:s.status})}catch(e){es.warn("[cloud-browser] Error cancelling browser request",{browserRequestId:t,error:e instanceof Error?e.message:String(e)})}}(i,n,this.projectId).catch(()=>{}),new Error("Cloud browser unavailable: timed out waiting for provisioning. Remove --browser=cloud to use a local browser, or wait for a browser to free up.")}writeConfig(e,t){this.configDir||(this.configDir=i(N(),`stably-cloud-browser-${process.pid}`),I(this.configDir,{recursive:!0}));const r=e.replace(/[^a-zA-Z0-9_-]/g,"_"),n=i(this.configDir,`config-${r}.json`),s={browser:{cdpEndpoint:t,isolated:!1},saveSession:!1,outputDir:i(process.cwd(),".stably-browser")};return T(n,JSON.stringify(s,null,2),"utf-8"),es.debug("[cloud-browser] Wrote config file",{sessionName:e,path:n}),n}cleanupConfigDir(){if(this.configDir){try{_(this.configDir,{recursive:!0,force:!0})}catch{}this.configDir=null}}async releaseSession(e){const t=this.sessions.get(e);if(!t)return;const{sessionId:r,browserRequestId:n}=t.session;es.info("[cloud-browser] Releasing session",{sessionName:e,sessionId:r,browserRequestId:n});try{const e=await this.authProvider.getAuthHeader();await async function(e,t,r){const n=new URL(`/internal/v1/browser/request/${t}/release`,nn).toString();try{const s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({projectId:r})});s.ok||es.warn("[cloud-browser] Failed to release browser",{browserRequestId:t,status:s.status})}catch(e){es.warn("[cloud-browser] Error releasing browser",{browserRequestId:t,error:e instanceof Error?e.message:String(e)})}}(e,n,this.projectId)}catch(t){es.warn("[cloud-browser] Error releasing session",{sessionName:e,sessionId:r,error:t instanceof Error?t.message:String(t)})}this.sessions.delete(e)}ensureHealthCheck(){this.healthCheckTimer||(this.healthCheckTimer=setInterval(async()=>{if(0===this.sessions.size||this.released)this.stopHealthCheck();else for(const[e,t]of this.sessions)if(!t.needsRecreation)try{const r=await this.authProvider.getAuthHeader();await nc(r,this.projectId,t.session.sessionId)||(es.warn("[cloud-browser] Browser session is dead, marking for recreation",{sessionName:e,sessionId:t.session.sessionId}),t.needsRecreation=!0)}catch(r){es.warn("[cloud-browser] Health check failed",{sessionName:e,sessionId:t.session.sessionId,error:r instanceof Error?r.message:String(r)})}},3e4),this.healthCheckTimer.unref&&this.healthCheckTimer.unref())}stopHealthCheck(){this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null)}};function ic(e){return new Promise(t=>setTimeout(t,e))}function ac({configuredSessionName:e,isFixMode:t,useCloudBrowser:r}){return e??(t||r?"auto":"default")}var cc=ge.object({verdict:ge.enum(["PASS","FAIL","INCONCLUSIVE"]),steps:ge.array(ge.string()).min(1),reason:ge.string().nullable(),evidence:ge.array(ge.string())}).superRefine((e,t)=>{"PASS"===e.verdict||e.reason&&0!==e.reason.trim().length||t.addIssue({code:ge.ZodIssueCode.custom,path:["reason"],message:"reason is required for FAIL and INCONCLUSIVE verdicts"})}),lc=/\bmcp__playwright-mcp__[a-z0-9_]+\b/gi,uc=/\.playwright-mcp(?:\/[^\s"'`)\]]*)?/gi,dc=/\bplaywright[\s_-]?mcp\b/gi;function pc(e){return e.replace(lc,"browser_tool").replace(uc,"verification-artifact").replace(dc,"browser automation")}function fc(e){return{...e,steps:e.steps.map(e=>pc(e)),reason:e.reason?pc(e.reason):null,evidence:e.evidence.map(e=>pc(e))}}function hc(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=cc.parse(t)}catch{}return r}function gc({mode:e,lastAssistantText:t,maxLength:r=1e4}){const n="verify"===e&&t?pc(t):t;return n?n.slice(0,r):null}var mc=e=>`[38;5;208m${e}[39m`,yc=["Bash","Read","Write","Edit","Glob","Grep","Task","Skill"],bc=["Task","Skill"],wc=["Bash","Read","Write","Edit","Glob","Grep","mcp__session-control"],vc=e=>{if("EPIPE"!==e.code)throw e},Ic="__main__",Tc=[3e3,5173,4173,8080,4200,8e3],_c=/\b(TEST_EMAIL|TEST_PASSWORD|auth|authentication|credentials|login|log in|sign in)\b/i,Ec=/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/i,Sc=/playwright[\s_-]?mcp/i,xc=e=>"mcp__auto-heal-report__generate-report"===e;async function Ac(e,t){return!!e&&(!!e.hasQueuedMessages()||new Promise(r=>{const n=setTimeout(()=>{clearInterval(s),r(!1)},t),s=setInterval(()=>{e.hasQueuedMessages()&&(clearTimeout(n),clearInterval(s),r(!0))},200)}))}async function kc(e){return new Promise(t=>{const r=new re.Socket;let n=!1;const s=e=>{n||(n=!0,r.destroy(),t(e))};r.setTimeout(700),r.once("connect",()=>s(!0)),r.once("timeout",()=>s(!1)),r.once("error",()=>s(!1)),r.connect(e,"127.0.0.1")})}var Pc=async(e,t,r)=>{const n=r?"[Y/n]":"[y/N]",s=(await e.question(`${se.cyan("?")} ${t} ${se.gray(n)} `)).trim().toLowerCase();return s?"y"===s||"yes"===s:r},Cc=async e=>{if("single"===e.mode){const t=Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt;es.initSession(t||"create-from-diff")}else if("verify"===e.mode){const t=Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt;es.initSession(t||"verify")}else if("fix"===e.mode)es.initSession(`fix-${e.runId}`);else if("plan"===e.mode){const t=Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt;es.initSession(t||"plan")}es.info("Agent session starting",{mode:e.mode}),process.stdout.on("error",vc),process.stderr.on("error",vc);const a=e=>{if("EPIPE"!==e.code)throw e};process.on("uncaughtException",a),es.debug("Checking authentication");const c=await cs({autoLogin:"chat"===e.mode||"init"===e.mode}),l=new ds(c);es.debug("Authentication resolved",{authType:c.type});const u="oauth"===c.type?c.auth.context.orgId:void 0,d=n.resolve(process.cwd()),p="fix"!==e.mode,f=n.join(d,".env"),h=p&&v.existsSync(f)&&v.statSync(f).isFile(),g=h?t(v.readFileSync(f,"utf8")):{};es.debug("Environment file",{path:f,exists:h,variableCount:Object.keys(g).length});const y="chat"!==e.mode&&"init"!==e.mode,b="chat"===e.mode,I="chat"===e.mode||"init"===e.mode,T="single"===e.mode,_="verify"===e.mode,S=T||_;let k,P=new Ks;"init"===e.mode&&(k=e.initPreferences??await async function(){if(!process.stdin.isTTY||!process.stdout.isTTY)return{googleAuth:!0,emailPackage:!1};const e=ne({input:process.stdin,output:process.stdout});try{return{googleAuth:await Pc(e,"Include Google Auth test helper guidance? (recommended)",!0),emailPackage:await Pc(e,"Install @stablyai/email for inbox testing?",!1)}}finally{e.close()}}());const C="chat"===e.mode?e.getHelpText:void 0,R="verify"===e.mode?(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt).trim():"";let U="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}},s=t.match(/https?:\/\/[^\s"'`<>]+/i);if(s)return n(s[0]);const o=t.match(/(?<!@)\b(?:localhost|(?:\d{1,3}\.){3}\d{1,3}|(?:[a-z0-9-]+\.)+[a-z]{2,63})(?::\d{2,5})?(?:\/[^\s"'`<>]*)?/i);if(!o)return;const i=r(o[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&&U&&es.info("[verify] Using URL extracted from prompt",{url:U}),"verify"!==e.mode||U||(U=await async function(){for(const e of Tc)if(await kc(e))return`http://localhost:${e}`}(),U?es.info("[verify] Detected local application URL",{url:U}):es.info("[verify] No common localhost dev server detected")),"verify"===e.mode&&!1!==e.interactive){const e=await async function({envFilePath:e,envFromFile:t,initialUrl:r,verifyPromptText:s,workingDir:o}){if(!process.stdin.isTTY||!process.stdout.isTTY)return{resolvedUrl:r};const i=n.join(o,"STABLY.md"),a=v.existsSync(i),c=a?await v.promises.readFile(i,"utf8").catch(()=>{}):void 0;let l=r?.trim()||void 0;const u=!l,d=(({envEmail:e,envPassword:t,promptIncludesEmail:r,stablyMdContent:n})=>!Boolean(e?.trim()&&t?.trim())&&!r&&!(e=>!!e&&_c.test(e))(n))({envEmail:process.env.TEST_EMAIL??t.TEST_EMAIL,envPassword:process.env.TEST_PASSWORD??t.TEST_PASSWORD,promptIncludesEmail:Ec.test(s),stablyMdContent:c}),p=!a;if(!u&&!d&&!p)return{resolvedUrl:l};const f=ne({input:process.stdin,output:process.stdout}),h=async(r,n)=>{const s=v.existsSync(e)?await v.promises.readFile(e,"utf8"):"",o=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=o.test(s)?s.replace(o,a):`${s}${s&&!s.endsWith("\n")?"\n":""}${a}\n`;await v.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 Pc(f,"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 h("TEST_EMAIL",e),await h("TEST_PASSWORD",t),process.env.TEST_EMAIL||(process.env.TEST_EMAIL=e),process.env.TEST_PASSWORD||(process.env.TEST_PASSWORD=t))}if(p&&await Pc(f,"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 v.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 v.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 v.promises.writeFile(i,r,"utf8")}}return{resolvedUrl:l}}finally{f.close()}}({envFilePath:f,envFromFile:g,initialUrl:U,verifyPromptText:R,workingDir:d});U=e.resolvedUrl?.trim()||U}"verify"!==e.mode||U||es.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 $={log:[],promptDisplay:Y(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"}).with({mode:"plan"},e=>{const t=(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt)?.trim();return t||"Planning test coverage"}).exhaustive(),status:"running"};let L,D,N,O,B=y,j=!1,M=0,F=[],H=!1,K=!1,J=0;const Q=new Map,X=[],Z=e=>{X.push(e)},ee=new Map;let te=null,re=!1,oe=!1;const ie=Date.now();let ae,ce="fix"===e.mode?{suiteId:e.runId,phase:"initializing",totalTests:null,fixedTests:0,failedTests:0,currentTestDescription:null,lastTestDescription:null,startedAt:ie,endedAt:null,isError:!1,updatedAt:ie,recentActivity:[],workers:[{id:Ic,testDescription:"Orchestrator",workerType:"main",status:"running",summary:null,startedAt:ie,endedAt:null,activity:[]}]}:null;const le=new Set,ue=new Map,de=(e,t)=>{const r=ue.get(e);if(!r)return;const n={...r,...t};ue.set(e,n),Ie({workers:Array.from(ue.values())})},pe=(e,t)=>{if(!ce)return;const r=ce.workers.map(r=>{if(r.id!==e)return r;const n=[...r.activity,{...t,timestamp:Date.now()}].slice(-15);return{...r,activity:n}});ge({workers:r})},fe=e=>{if(!ce)return;const t=[...ce.recentActivity,{...e,timestamp:Date.now()}].slice(-10);ge({recentActivity:t})},he=e=>(ce?.workers??[]).map(t=>t.id===Ic?{...t,status:e?"failed":"succeeded",endedAt:t.endedAt??Date.now()}:"running"===t.status?{...t,status:"failed",endedAt:Date.now()}:t),ge=e=>{ce&&!ae?.isClosed&&(ce={...ce,...e,updatedAt:Date.now()},ae?.sendProgress(ce))},me=async t=>{if("fix"===e.mode){if("STARTED"===t){if(re)return;re=!0}else{if(oe)return;oe=!0}try{await(async({authHeader:e,orgId:t,runId:r,status:n})=>{const s=await(o={auth:e,body:{status:n},client:pn(),headers:hs(t),path:{runId:r}},(o.client??Zr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-status",...o,headers:{"Content-Type":"application/json",...o.headers}}));var o;if(s.error)throw new Error(`Failed to update autoheal status (${s.response.status})`)})({authHeader:await l.getAuthHeader(),orgId:u,runId:e.runId,status:t})}catch{}}},ye=Date.now();let be,we=null;const Ie=e=>{we&&!be?.isClosed&&(we={...we,...e,updatedAt:Date.now()},be?.sendProgress(we))},Pe=e=>{if(!we)return;const t=[...we.recentActivity,{...e,timestamp:Date.now()}].slice(-10);Ie({recentActivity:t})};let Re;const Ue=(e.mode,!0);if(es.info("[session] Checking session creation",{mode:e.mode,shouldCreateSession:Ue}),"fix"===e.mode)es.info("[session] Deferring fix-mode session creation until after early-exit checks");else try{es.info("[session] Creating progress session",{mode:e.mode,projectId:ls(c)});const t=await no({agentMode:e.mode,authHeader:await l.getAuthHeader(),orgId:u,projectId:ls(c)}),{sessionId:r,sessionMode:n}=t;if(Re=r,S){const t="single"===e.mode||"verify"===e.mode?Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt:null,n=Js(d);we={sessionId:r,phase:"initializing",startedAt:ye,endedAt:null,isError:!1,updatedAt:ye,currentActivity:null,filesCreated:[],traceProofs:[],recentActivity:[],prompt:t||null,environment:{gitBranch:n?.branch??null,workingDirectory:d,nodeVersion:process.version,cliVersion:rn}},be=new _s({authProvider:l,orgId:u,sessionId:r,onUserMessage:e=>{P&&(es.info("[ws] Injecting web UI message into agent",{contentLength:e.length}),Pe({type:"user_message",summary:e}),Ye({text:`[Web] ${e}`}),P.pushText(`[Message from web UI user]: ${e}`),B||(B=!0,st({status:"running"})))}}),await be.start(),Ie({phase:"initializing"})}es.info(`[${n}] Progress session created`,{sessionId:r})}catch(e){const t=e instanceof Error?e.message:String(e);es.warn(`[progress] Session creation failed (non-fatal): ${t}`)}const Le={current:e=>{}},De={current:async()=>{}};let Ne;const Oe={current:()=>{}};let Be=!1,je=!1;const{addSubagentActivity:Me,addSubagentStart:Fe,addTool:He,appendCancelled:Ge,appendText:We,appendThinking:Ve,appendUserMessage:Ye,cancelThinkingRender:ze,cleanup:qe,dismissPermissionPrompt:Ke,flushThinkingRender:Je,resetThinkingLogIndex:Qe,setExiting:Xe,setRunningLabel:Ze,setStatus:et,setSubagentStatus:tt,updateFixProgress:rt}=await(async(e,t)=>{const{Box:r,Static:n,Text:s,render:o,useInput:i}=await import("ink"),a=!!process.stdin.isTTY,c="vscode"!==process.env.TERM_PROGRAM,l=["β ","β ","β Ή","β Έ","β Ό","β ΄","β ¦","β §","β ","β "],u=()=>Ae(s,{inverse:!0,children:" "}),d=(({Box:e,Text:t,useInput:r},n,s)=>function({onChoice:o,prompt:i}){const[a,c]=Te(0),[l,u]=Te(!1),[d,p]=Te(""),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 o("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 o(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);o(e.value)}},{isActive:s});const h=_o(i.toolName),g=Io(i.toolName,i.input);return ke(e,{borderColor:"#FFA500",borderStyle:"round",flexDirection:"column",marginTop:1,paddingX:1,paddingY:0,children:[Ae(t,{bold:!0,color:"#FFA500",children:"Permission Required"}),ke(e,{flexDirection:"column",marginTop:1,children:[Ae(t,{color:"gray",dimColor:!0,children:h}),null!=g&&ke(t,{color:"gray",children:[" ",g]})]}),null!=i.decisionReason&&Ae(e,{marginTop:1,children:ke(t,{color:"gray",children:["Reason: ",i.decisionReason]})}),ke(e,l?{flexDirection:"column",marginTop:1,children:[Ae(t,{color:"gray",children:"Enter message for AI (press Enter to submit, Esc to cancel):"}),ke(t,{children:[Ae(t,{color:"#FFA500",children:">"})," ",d,Ae(n,{})]})]}:{flexDirection:"column",marginTop:1,children:[Ae(t,{color:"gray",children:"Use ββ arrows or number keys to select:"}),f.map((e,r)=>Ae(t,{children:ke(t,{color:r===a?"cyan":void 0,children:[r===a?"β―":" "," ",r+1,". ",e.label]})},e.value))]})]})})({Box:r,Text:s,useInput:i},u,a),p=(({Cursor:e,inkComponents:{Box:t,Static:r,Text:n,useInput:s},isRawModeSupported:o,PermissionPrompt:i,Spinner:a})=>{const c="vscode"!==process.env.TERM_PROGRAM,l=e=>"tool"===e.kind?ke(n,{color:"gray",dimColor:!0,children:["β’ ",e.content]},e.id):"tool_result"===e.kind||"text"===e.kind?Ae(n,{color:"gray",children:e.content},e.id):null,u=({progress:e})=>{const[r,s]=Te(Date.now());Ee(()=>{if(!c)return;const e=setInterval(()=>s(Date.now()),1e3);return()=>clearInterval(e)},[]);const o=r-e.startedAt,i=Math.floor(o/1e3),a=Math.floor(i/60),l=i%60,u=a>0?`${a}m ${l.toString().padStart(2,"0")}s`:`${l}s`,{label:d,color:p}={initializing:{label:"Fetching test results",color:"gray"},triage:{label:"Triaging failures",color:"#FFA500"},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],f=e.fixedTests+e.failedTests,h=("fixing"===e.phase||"debugging"===e.phase)&&f>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 Ae(t,{flexDirection:"column",children:ke(n,{children:[Ae(n,{color:p,bold:!0,children:d}),Ae(n,{color:"gray",children:h}),ke(n,{color:"gray",children:[" [",u,"]"]})]})})},d=({progress:e})=>{const r=e.endedAt??Date.now(),s=Math.floor((r-e.startedAt)/1e3),o=Math.floor(s/60),i=s%60,a=o>0?`${o}m ${i.toString().padStart(2,"0")}s`:`${i}s`,c=e.isError?"#FFA500":"green",l=e.isError?"Fix stopped":"Fix complete";return ke(t,{flexDirection:"column",children:[ke(n,{color:c,bold:!0,children:[l," in ",a]}),null!==e.totalTests&&ke(n,{color:"gray",children:[e.fixedTests,"/",e.totalTests," tests fixed",e.failedTests>0?`, ${e.failedTests} failed`:""]})]})},p=(e,r=!1)=>{if("subagent"===e.kind&&e.subagent){const{subagent:s}=e,o="complete"===s.status?"green":"error"===s.status?"red":"#FFA500";return ke(t,{flexDirection:"column",marginTop:1,children:[ke(n,{children:[Ae(n,{color:o,bold:!0,children:"Agent"}),s.description?ke(n,{color:"gray",children:[" (",s.description,")"]}):null]}),s.activities.length>0&&Ae(t,{flexDirection:"column",marginLeft:2,children:(()=>{if(!r)return s.activities.map(e=>l(e));let e=0;const t=[];for(let r=s.activities.length-1;r>=0;r--){const n=s.activities[r];"tool"!==n.kind&&"tool_result"!==n.kind||("tool"===n.kind&&e++,e<=f&&t.unshift(n))}return t.map(e=>l(e))})()})]},e.id)}if("tool"===e.kind)return ke(n,{color:"gray",dimColor:!0,children:["β’ ",e.content]},e.id);if("tool_result"===e.kind)return Ae(n,{color:"gray",children:e.content},e.id);if("user"===e.kind)return ke(n,{color:"cyan",children:["You: ",e.content]},e.id);if("thinking"===e.kind){const r=e.content.split("\n"),s=10,o=r.length>s?r.slice(-s):r;return Ae(t,{flexDirection:"column",children:Ae(n,{color:"gray",dimColor:!0,children:o.join("\n")})},e.id)}return"cancelled"===e.kind?Ae(n,{color:"gray",dimColor:!0,children:e.content},e.id):Ae(n,{children:e.content},e.id)},f=3;return function({onCancel:c,onExit:l,onPermissionChoice:h,onSend:g,showSpinnerImmediately:m,state:y}){const[b,w]=Te({value:"",cursor:0}),v=b.value,I=b.cursor,T=_e(!1),_=_e(void 0),[E,S]=Te(!1),[x,A]=Te(!1),k=_e(0),P=_e(!1),C=!!y.permissionPrompt,R=(({termProgram:e})=>"vscode"===e)({termProgram:process.env.TERM_PROGRAM}),U=y.log.at(-1),$=("text"===U?.kind||"thinking"===U?.kind)&&"running"===y.status,L=y.log.findIndex(e=>"subagent"===e.kind&&"running"===e.subagent?.status),D=-1!==L,N=y.activeThinkingLogIndex??-1,O=N>=0&&N<y.log.length-1,B=o&&!x,j=R?0:D?L:O?N:$?y.log.length-1:y.log.length,M=B&&"running"===y.status?Math.min(j,k.current):j;Ee(()=>{y.log.length<k.current&&(k.current=0),M>k.current&&(k.current=M)},[y.log.length,M]);const F=y.log.slice(0,k.current),H=y.log.slice(k.current),G=B?F.filter(e=>"tool"!==e.kind&&"tool_result"!==e.kind&&"thinking"!==e.kind):F,W=(()=>{if(!B)return H;let e=0;const t=[];for(let r=H.length-1;r>=0;r--){const n=H[r];"tool"===n.kind||"tool_result"===n.kind||"thinking"===n.kind?("tool"===n.kind&&e++,e<=f&&t.unshift(n)):t.unshift(n)}return t})(),V=Se(async()=>{T.current?(_.current&&clearTimeout(_.current),await(l?.()),process.exit(0)):(T.current=!0,S(!0),_.current=setTimeout(()=>{T.current=!1,S(!1)},2e3))},[l]);s((e,t)=>{t.ctrl&&"c"===e&&V().catch(()=>process.exit(1)),t.ctrl&&"o"===e&&A(e=>!e),t.escape&&"running"===y.status&&!C&&0===v.length&&c?.()},{isActive:o}),Ee(()=>{if(C||!g)return;process.stdout.isTTY&&process.stdout.write("[?2004h");const e=e=>{const t=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n");t&&w(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~"),s=n?t.slice(0,t.indexOf("[201~")):t;return e(s),void(n&&setTimeout(()=>{P.current=!1},0))}if(r.includes("[201~")){const t=r.slice(0,r.indexOf("[201~"));return e(t),void setTimeout(()=>{P.current=!1},0)}P.current?e(r):"[1;5H"!==r&&"[1;5~"!==r?"[1;5F"!==r&&"[4;5~"!==r?"[H"!==r&&"[1~"!==r&&"OH"!==r&&"[7~"!==r?"[F"!==r&&"[4~"!==r&&"OF"!==r&&"[8~"!==r||w(e=>({...e,cursor:Ao(e.value,e.cursor)})):w(e=>({...e,cursor:xo(e.value,e.cursor)})):w(e=>({...e,cursor:e.value.length})):w(e=>({...e,cursor:0}))};return process.stdin.on("data",t),()=>{process.stdin.off("data",t),process.stdout.isTTY&&process.stdout.write("[?2004l")}},[C,g]),s((e,t)=>{if(!t.ctrl||"c"!==e){if(t.return){if(P.current)return;const e=v.trim();return e&&g?.(e),void w({value:"",cursor:0})}t.ctrl&&"w"===e||t.ctrl&&t.backspace?w(e=>{const t=Eo(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?w(e=>({...e,cursor:Eo(e.value,e.cursor)})):t.ctrl&&t.rightArrow||t.meta&&"f"===e?w(e=>({...e,cursor:So(e.value,e.cursor)})):t.leftArrow?w(e=>({...e,cursor:Math.max(0,e.cursor-1)})):t.rightArrow?w(e=>({...e,cursor:Math.min(e.value.length,e.cursor+1)})):t.ctrl&&"a"===e?w(e=>({...e,cursor:xo(e.value,e.cursor)})):t.ctrl&&"e"===e?w(e=>({...e,cursor:Ao(e.value,e.cursor)})):t.escape&&v.length>0?w({value:"",cursor:0}):!e||t.ctrl||t.meta||t.escape||e.includes("")||/^\[./.test(e)||/^O[A-D]$/.test(e)||P.current||w(t=>({value:t.value.slice(0,t.cursor)+e+t.value.slice(t.cursor),cursor:t.cursor+e.length})):w(e=>e.cursor>0?{value:e.value.slice(0,e.cursor-1)+e.value.slice(e.cursor),cursor:e.cursor-1}:e)}},{isActive:o&&!!g&&!C});const Y=xe(()=>"running"===y.status?Ae(a,{label:y.runningLabel??"Working"}):"success"!==y.status?Ae(n,{color:"red",children:"β Failed"}):void 0,[y.runningLabel,y.status]),z=!(m||!g||"running"!==y.status||0!==y.log.length||y.resultText||y.errorText),q="running"===y.status&&!z||y.log.length>0||y.resultText||y.errorText||"running"!==y.status;return ke(t,{flexDirection:"column",children:[R?ke(t,{flexDirection:"column",flexShrink:0,children:[Ae(n,{color:"cyan",bold:!0,children:"Stably Agent"}),Ae(t,{flexDirection:"column",marginTop:1,children:Ae(n,{color:"gray",children:y.promptDisplay})})]}):Ae(r,{items:["header"],children:()=>ke(t,{flexDirection:"column",flexShrink:0,children:[Ae(n,{color:"cyan",bold:!0,children:"Stably Agent"}),Ae(t,{flexDirection:"column",marginTop:1,children:Ae(n,{color:"gray",children:y.promptDisplay})})]},"header")}),G.length>0&&Ae(r,{items:G,children:e=>p(e,B)}),W.length>0&&Ae(t,{flexDirection:"column",children:W.map(e=>p(e,B))}),B&&H.length>W.length&&ke(n,{color:"gray",dimColor:!0,children:["β ",H.length-W.length," tool calls hidden (Ctrl+O to expand)"]}),x&&o&&Ae(n,{color:"gray",dimColor:!0,children:"β Showing all tool calls (Ctrl+O to collapse)"}),"error"===y.status&&y.errorText&&Ae(t,{marginTop:1,children:Ae(n,{color:"red",children:y.errorText})}),"success"===y.status&&y.resultText&&Ae(t,{marginTop:1,children:Ae(n,{children:y.resultText})}),q&&Ae(t,{flexDirection:"column",flexShrink:0,marginTop:1,children:"running"===y.status&&y.fixProgress?ke(t,{flexDirection:"column",children:[ke(t,{children:[Ae(a,{}),Ae(n,{children:" "}),Ae(u,{progress:y.fixProgress})]}),("fixing"===y.fixProgress.phase||"debugging"===y.fixProgress.phase)&&y.log.flatMap(e=>{const{subagent:r}=e;if("subagent"!==e.kind||"code-worker"!==r?.subagentType&&"browser-worker"!==r?.subagentType||"running"!==r.status)return[];const{activities:s}=r,o=s.filter(e=>"tool"===e.kind).length,i=s.at(-1),c=s.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 ke(t,{flexDirection:"column",children:[ke(n,{children:[" ",Ae(a,{}),ke(n,{color:"gray",children:[r.description||r.subagentType||"worker",o>0?` (${o} ${1===o?"cycle":"cycles"})`:""]})]}),c&&ke(n,{color:"gray",dimColor:!0,children:[" β’ ",c.content]}),l&&ke(n,{color:"gray",dimColor:!0,children:[" ",l]})]},e.id)})]}):"success"!==y.status&&"error"!==y.status||!y.fixProgress?Y:Ae(d,{progress:y.fixProgress})}),null!=y.permissionPrompt&&null!=h&&Ae(i,{onChoice:h,prompt:y.permissionPrompt}),null!=g&&null==y.permissionPrompt&&!y.isExiting&&ke(t,{borderColor:"gray",borderStyle:"round",flexDirection:"column",flexShrink:0,marginTop:1,paddingX:1,paddingY:0,children:[Ae(n,{color:"gray",children:"Type a message and press Enter. Press Escape to interrupt. Press Ctrl+C to exit."}),ke(n,{children:[Ae(n,{color:"#FFA500",children:">"})," ",v.slice(0,I),Ae(e,{}),v.slice(I)]})]}),E&&ke(t,{marginTop:1,flexDirection:"column",children:[Ae(n,{color:"#FFA500",children:"Press Ctrl+C again to exit"}),Hn&&ke(n,{color:"gray",children:["Debug log: ",Yn]})]})]})}})({Cursor:u,inkComponents:{Box:r,Static:n,Text:s,useInput:i},isRawModeSupported:a,PermissionPrompt:d,Spinner:({label:e})=>{const[t,r]=Te(0);return Ee(()=>{if(!c)return;const e=setInterval(()=>r(e=>(e+1)%l.length),80);return()=>clearInterval(e)},[]),ke(s,{color:"#FFA500",children:[l[t]," ",e]})}});let f=e;t?.isFixMode&&(f.fixProgress={phase:"initializing",totalTests:null,fixedTests:0,failedTests:0,currentTestDescription:null,lastTestDescription:null,startedAt:Date.now(),endedAt:null,isError:!1});const h={current:(e,t)=>{}},g=o(Ae(p,{onCancel:t?.onCancel,onExit:t?.onExit,onPermissionChoice:(e,t)=>h.current(e,t),onSend:t?.onSend,showSpinnerImmediately:t?.showSpinnerImmediately,state:f}),{exitOnCtrlC:!1}),m=()=>{f={...f},g.rerender(Ae(p,{onCancel:t?.onCancel,onExit:t?.onExit,onPermissionChoice:(e,t)=>h.current(e,t),onSend:t?.onSend,showSpinnerImmediately:t?.showSpinnerImmediately,state:f}))};let y=null;const b=()=>{y&&(clearTimeout(y),y=null),f.log=[...f.log],m()};let w=null;const v=({text:e})=>{e&&(f.log=[...f.log,{content:e,id:f.log.length,kind:"user"}],m())},I=new Map;return{addSubagentActivity:({toolUseId:e,kind:t,content:r})=>{const n=I.get(e);if(void 0===n)return void console.error("[addSubagentActivity] No entry index for toolUseId:",e);const s=f.log[n];if("subagent"===s?.kind&&s.subagent){if("text"===t){const e=s.subagent.activities.at(-1);"text"===e?.kind?e.content+=r:s.subagent.activities.push({id:s.subagent.activities.length,kind:"text",content:r.replace(/^\s*\n+/,"")})}else s.subagent.activities.push({id:s.subagent.activities.length,kind:t,content:r});f.log=[...f.log],m()}else console.error("[addSubagentActivity] Entry not found or not subagent:",{entryIndex:n,entryKind:s?.kind})},addSubagentStart:({toolUseId:e,subagentType:t,description:r})=>{const n=f.log.length;if(I.set(e,n),f.log=[...f.log,{content:"",id:n,kind:"subagent",subagent:{toolUseId:e,subagentType:t,description:r,status:"running",activities:[]}}],f.fixProgress)if("triage"===t&&"initializing"===f.fixProgress.phase)f.fixProgress={...f.fixProgress,phase:"triage"};else if("code-worker"===t){const e=(f.fixProgress.totalTests??0)+1,t=r||null;f.fixProgress={...f.fixProgress,phase:"fixing",totalTests:e,currentTestDescription:t,lastTestDescription:t??f.fixProgress.lastTestDescription}}else if("browser-worker"===t){const e=(f.fixProgress.totalTests??0)+1,t=r||null;f.fixProgress={...f.fixProgress,phase:"debugging",totalTests:e,currentTestDescription:t,lastTestDescription:t??f.fixProgress.lastTestDescription}}else"validation"===t?f.fixProgress={...f.fixProgress,phase:"validation",currentTestDescription:null}:"context"===t&&(f.fixProgress={...f.fixProgress,currentTestDescription:r||f.fixProgress.currentTestDescription});m()},addTool:({rawName:e,toolInput:t})=>{const r=To(e,t),n=r??_o(e),s=r?void 0:Io(e,t),o=s?`${n} (${s})`:n;f.log=[...f.log,{content:o,id:f.log.length,kind:"tool"}],m()},addToolResult:({message:e})=>{f.log=[...f.log,{content:e,id:f.log.length,kind:"tool_result"}],m()},appendCancelled:()=>{f.log=[...f.log,{content:"[Cancelled]",id:f.log.length,kind:"cancelled"}],m()},appendText:({text:e})=>{if(!e)return;const t=f.log.at(-1),r="text"!==t?.kind?e.replace(/^\s*\n+/,""):e;f.log="text"===t?.kind?[...f.log.slice(0,-1),{...t,content:`${t.content}${r}`}]:[...f.log,{content:r,id:f.log.length,kind:"text"}],m()},appendThinking:({text:e,forceNewBlock:t})=>{if(!e)return;const r=null!==w?f.log[w]:null;"thinking"!==r?.kind||t?(w=f.log.length,f.log=[...f.log,{content:e,id:f.log.length,kind:"thinking"}]):r.content+=e,f.activeThinkingLogIndex=w,y||(y=setTimeout(b,50))},appendUserMessage:v,cancelThinkingRender:()=>{y&&(clearTimeout(y),y=null)},cleanup:async()=>{const e=g.waitUntilExit();g.unmount(),await e},dismissPermissionPrompt:()=>{f.permissionPrompt&&(f.permissionPrompt.resolve({behavior:"deny",message:"Cancelled by user",interrupt:!0}),f.permissionPrompt=void 0,m())},flushThinkingRender:b,resetThinkingLogIndex:()=>{w=null,f.activeThinkingLogIndex=null},setExiting:()=>{f.isExiting=!0,m()},setRunningLabel:({label:e})=>{f.runningLabel=e,m()},setStatus:({error:e,result:t,status:r})=>{f.errorText=e,f.resultText=t,f.status=r,m()},setSubagentStatus:({toolUseId:e,status:t})=>{const r=I.get(e);if(void 0===r)return;const n=f.log[r];"subagent"===n?.kind&&n.subagent&&(n.subagent.status=t,!f.fixProgress||"code-worker"!==n.subagent.subagentType&&"browser-worker"!==n.subagent.subagentType||("complete"===t?f.fixProgress={...f.fixProgress,fixedTests:f.fixProgress.fixedTests+1,currentTestDescription:null}:"error"===t&&(f.fixProgress={...f.fixProgress,failedTests:f.fixProgress.failedTests+1,currentTestDescription:null})),f.log=[...f.log],m(),"complete"!==t&&"error"!==t||I.delete(e))},showPermissionPrompt:e=>new Promise(t=>{h.current=(r,n)=>{if(f.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";v({text:e}),t({behavior:"deny",message:e,interrupt:!1})}},f.permissionPrompt={...e,resolve:t},m()}),updateFixProgress:t?.isFixMode?e=>{f.fixProgress&&(f.fixProgress={...f.fixProgress,...e},m())}:void 0}})($,"init"===e.mode?{onCancel:()=>Oe.current(),onExit:()=>De.current(),onSend:e=>Le.current(e),showSpinnerImmediately:!0}:"chat"===e.mode?{onCancel:()=>Oe.current(),onExit:()=>De.current(),onSend:e=>Le.current(e)}:"fix"===e.mode?{onExit:()=>De.current(),isFixMode:!0}:{onExit:()=>De.current()});let nt=$.status;const st=({error:e,result:t,status:r})=>{nt=r,et({error:e,result:t,status:r})};let ot,it;_&&(We({text:"Starting verification...\n"}),We(U?{text:`Target URL: ${U}\n`}:{text:"Target URL: auto-detect (agent may infer from project config)\n"}),Ze({label:"Calibrating verification flow..."})),Le.current=e=>{const t=e.trim();if(b&&!es.getLogFilePath()&&es.initSession(t||"chat"),es.debug("User message",{text:t}),"/help"===t){B&&P&&(j=!0,L?.interrupt?.(),P.allowNextTurn(),B=!1),"running"===nt&&st({status:"success"}),Ye({text:e});const t=C?.();return void We({text:t??"Help is not available in this session."})}if(b&&Ze({label:void 0}),P){if(B)return st({status:"running"}),Ye({text:e}),P.pushText(e),void(M+=1);st({status:"running"}),Ye({text:e}),Z({role:"user",content:e,timestamp:(new Date).toISOString()}),P.pushText(e),B=!0}};let at="",ct="";const lt=[],ut=[],dt=[];let pt;const ft=await(async e=>{try{const t=await wn(e,"stably.yaml");if(!t)return void es.debug("No stably.yaml found");const r=await q(t,"utf-8");if(!r.trim())return;const n=Ce(r),s=Ma.parse(n.toJS()),o=s.agent?.fix?.maxTurnsPerIssue,i=s.agent?.fix?.maxParallelWorkers,a=!!s.agent?.fix?.rules;return es.debug(`Loaded stably.yaml: maxTurnsPerIssue=${o??"default"}, maxParallelWorkers=${i??"default"}, hasRules=${a}`,{path:t,config:s.agent}),s}catch(e){return void es.warn("Failed to parse stably.yaml",{error:e})}})(d),ht=ft?.agent?.fix?.skipAfterConsecutiveUnfixed,gt=await(async()=>{if("single"===e.mode){const r=await async function(e,t){const r=s(e);if(t){const e=s(r,t);return po(e,"output-flag"),{path:e,source:"output-flag"}}const n=co(r);if(n){const e=await async function(e){try{const t=(await q(e,"utf-8")).match(/testDir:\s*['"]([^'"]+)['"]/);return t?.[1]}catch{return}}(n);if(e){const t=s(o(n),e);if(uo(t))return po(t,"playwright.config.ts"),{path:t,source:"playwright.config.ts"}}}for(const e of lo){const t=i(r,e);if(uo(t))return po(t,"auto-detected"),{path:t,source:"auto-detected"}}return po(r,"cwd-fallback"),{path:r,source:"cwd-fallback"}}(d,e.outputDir);return pt=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: ${pt}]`}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,U);if("fix"===e.mode)try{es.info("[fix] Fetching autoheal context",{runId:e.runId,skipAfterConsecutiveUnfixed:ht});const t=Date.now(),{context:r,autohealReportUrl:n,skippedTests:s,newerPassingSuiteId:o,envName:i}=await(async({authHeader:e,orgId:t,runId:r,skipAfterConsecutiveUnfixed:n})=>{es.debug("Fetching autoheal context",{runId:r,skipAfterConsecutiveUnfixed:n});const s=await(o={auth:e,client:pn(),headers:hs(t),path:{runId:r},query:null!=n?{skipAfterConsecutiveUnfixed:n}:{}},(o.client??Zr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-context",...o}));var o;if(404===s.response.status)throw es.warn("Autoheal context not found",{runId:r,status:404}),new Error(`Run ID "${r}" was not found.`);if(401===s.response.status)throw es.warn("Autoheal context fetch unauthorized",{runId:r,status:401}),new Error("Unauthorized: failed to fetch autoheal context (401).");if(422===s.response.status)throw es.warn("Autoheal context fetch invalid request",{runId:r,status:422,error:s.error?.error}),new Error(s.error?.error??"Failed to fetch autoheal context (422).");if(!s.error){const e=gs.safeParse(s.data);if(e.success)return es.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??[],newerPassingSuiteId:e.data.newerPassingSuiteId,envName:e.data.envName};throw es.warn("Autoheal context response invalid",{runId:r}),new Error("Autoheal context response missing or invalid context.")}throw es.warn("Autoheal context fetch failed",{runId:r,error:s.error}),new Error("Failed to fetch autoheal context")})({authHeader:await l.getAuthHeader(),orgId:u,runId:e.runId,skipAfterConsecutiveUnfixed:ht});if(i&&!$e.remoteEnvName&&(es.info("[fix] Auto-loaded remote env from run metadata",{envName:i}),$e.remoteEnvName=i,it=i),es.info("[fix] Autoheal context fetched",{runId:e.runId,durationMs:Date.now()-t,contextLength:r.length,skippedTestCount:s.length}),ot=n,s.length>0){es.info(`[fix] Skipping ${s.length} test(s) that failed to be fixed ${ht}+ consecutive times`);for(const e of s)es.info(`[fix] Skipped: ${e.testIdentifier} β ${e.testTitle} (unfixed ${e.consecutiveUnfixedCount}x)`)}if(o&&(es.info("[fix] Tests already passing in a newer run β no session created",{newerPassingSuiteId:o}),st({status:"success",result:`Tests already passing in a newer run (${o}). Nothing to fix.`}),await qe(),process.exit(0)),r.includes("No failing tests to fix (all were skipped).")&&(es.info("[fix] All failing tests were skipped β creating skipped session"),Ue&&await async function({authHeader:e,orgId:t,projectId:r,runId:n,reason:s,skippedTests:o,fetchImpl:i=fetch,apiUrl:a=nn}){const c=new URL("/internal/v1/cli/sessions/skipped",a).toString(),l={Authorization:e,"Content-Type":"application/json","X-STABLY-CLI-VERSION":rn};t&&(l["x-stably-org-id"]=t),await i(c,{method:"POST",headers:l,body:JSON.stringify({mode:"fix",projectId:r,...n?{playwrightSuiteRunId:n}:{},progress:{phase:"skipped",isError:!1,reason:s,skippedTests:o,endedAt:Date.now()}}),signal:AbortSignal.timeout(5e3)}).then(e=>{e.ok||console.warn(`[session] Failed to create skipped session: ${e.status} ${e.statusText}`)}).catch(e=>{console.warn(`[session] Failed to create skipped session: ${e instanceof Error?e.message:String(e)}`)})}({authHeader:await l.getAuthHeader(),orgId:u,projectId:ls(c),runId:e.runId,reason:`All ${s.length} failing test(s) skipped β each was unfixed ${ht??2}+ consecutive runs`,skippedTests:s}),st({status:"success",result:`All failing tests skipped (unfixed ${ht}+ consecutive times). Nothing to fix.`}),await qe(),process.exit(0)),Ue)try{es.info("[session] Creating fix-mode progress session (post early-exit checks)");const t=await no({agentMode:e.mode,authHeader:await l.getAuthHeader(),orgId:u,projectId:ls(c),runId:e.runId});Re=t.sessionId,es.info("[fix] Progress session created",{sessionId:Re})}catch(e){const t=e instanceof Error?e.message:String(e);es.warn(`[progress] Fix session creation failed (non-fatal): ${t}`)}return ae||(es.info("[fix] Creating WebSocket progress reporter"),ae=new Ts({authProvider:l,orgId:u,runId:e.runId,onUserMessage:e=>{if(es.info("[ws] Injecting web UI message into fix agent",{contentLength:e.length}),pe(Ic,{type:"user_message",summary:e}),fe({type:"user_message",summary:e}),Ye({text:`[Web] ${e}`}),!B)return P.pushText(`[Message from web UI user]: ${e}`),B=!0,void P.allowNextTurn();H||Date.now()-J<2e3?P.pushText(`[Message from web UI user]: ${e}`):(F.push(e),N&&clearTimeout(N),N=setTimeout(()=>{N=void 0;const e=[...F];F=[],J=Date.now(),_r(e)},500))}}),await ae.start(),ge({phase:"initializing"})),me("STARTED"),r}catch(e){const t=e instanceof Error?e.message:"Failed to fetch autoheal context.";es.error("[fix] Failed to fetch autoheal context",{error:t}),st({error:t,status:"error"}),await qe(),process.exit(1)}if("plan"===e.mode){const t=(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt)?.trim();return t||"Analyze this repository and generate a comprehensive test coverage plan."}if("init"===e.mode){const e=k??{googleAuth:!0,emailPackage:!1};return["Set up Playwright with the Stably SDK.",`Preferences: Google Auth guidance: ${e.googleAuth?"yes":"no"}, @stablyai/email: ${e.emailPackage?"install":"skip"}.`].join(" ")}return""})(),mt=await async function(e){const t=n.resolve(e),r=n.join(t,"tests"),s=n.join(r,"helpers"),o=n.join(r,"assets"),i=function(e){const t=n.resolve(e);if(E(t))for(const e of Qs){const r=n.join(t,`playwright.config${e}`);if(E(r))return r}}(t)??n.join(t,"playwright.config.ts"),a=n.basename(i),c=n.join(r,"seed.spec.ts"),[l,u,d,p,f,h]=await Promise.all([eo({defaultContent:"Unable to read directory",dirName:"working directory",dirPath:t}),eo({defaultContent:"Unable to read directory",dirName:"tests directory",dirPath:r}),eo({defaultContent:"Directory does not exist yet",dirName:"helpers directory",dirPath:s}),eo({defaultContent:"Directory does not exist yet",dirName:"assets directory",dirPath:o}),Zs({defaultContent:"File does not exist or could not be read",fileName:a,filePath:i}),Zs({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}}}(d),yt="fix"===e.mode?ft?.agent?.fix?.maxTurnsPerIssue:"single"===e.mode?ft?.agent?.create?.maxTurnsPerTestFile:void 0,bt="cloudBrowser"in e&&e.cloudBrowser,wt=ft?.agent?.fix?.maxParallelWorkers??3,vt="fix"===e.mode?await(async e=>{const t=await Fa(e,"STABLY-FIX.md");return t?.content})(d):void 0,It="fix"===e.mode?ft?.agent?.fix?.rules:void 0;vt&&It&&es.warn("Both STABLY-FIX.md and stably.yaml agent.fix.rules found; using STABLY-FIX.md");const Tt=vt??It,_t=ft?.agent?.fix?.maxBudgetUsd??50,Et="verify"===e.mode?e.maxBudgetUsd??5:void 0,St="single"===e.mode?ft?.agent?.create?.maxBudgetUsd??50:void 0,xt="fix"===e.mode?_t:_?Et:St,At="init"!==e.mode,kt="single"===e.mode?await(async e=>{const t=await Fa(e,"STABLY-CREATE.md");return t?.content})(d):void 0,Pt=await(e=>Fa(e,"STABLY.md"))(d),Ct=Pt?.content;let Rt;if(_&&(Ze({label:"Assembling verification context..."}),We({text:"Assembling workspace context...\n"})),es.info("[fix] Fetching system prompt and subagent definitions",{mode:e.mode,isCloudBrowser:bt,maxParallelWorkers:wt,maxTurnsOverride:yt,maxBudgetUsd:xt,hasCustomRules:!!Tt,hasCreateRules:!!kt,hasStablyMd:!!Ct,stablyMdPath:Pt?.path}),Pt&&es.info(`STABLY.md loaded (${Pt.content.length} chars)`,{path:Pt.path}),"fix"===e.mode&&it){const e=await ps(it);e.ok?Rt=e.result:es.warn("[fix] Failed to load auto-detected remote env, continuing without it",{envName:it,error:e.error})}else Rt=await fs();const Ut=Rt?Object.keys(Rt.variables):[],$t=[...new Set([...Object.keys(g),...Ut])],Lt=Date.now(),Dt=await l.getAuthHeader(),[{systemPrompt:Nt,prContext:Ot},Bt]=await Promise.all([to({allowedEnvVars:$t,mode:e.mode,workspaceInfo:mt,authHeader:Dt,customHeader:"single"===e.mode?e.customHeader:void 0,maxParallelWorkers:wt,isCloudBrowser:bt}),At?Da({authHeader:Dt,mode:e.mode,maxTurnsOverride:yt}):Promise.resolve({})]);es.info("[fix] System prompt and subagents fetched",{durationMs:Date.now()-Lt,systemPromptSize:Nt.length,subagentCount:Object.keys(Bt).length,maxTurnsOverride:yt??"default",hasPrContext:!!Ot});const jt=function(e){const t={};for(const[r,n]of Object.entries(e))void 0!==n&&(La.has(r)||$a.some(e=>r.startsWith(e))||(t[r]=n));return t}({...g,...process.env}),Mt=!0;es.debug("AI proxy configuration",{useStablyAiProxy:Mt,wantsBypassProxy:!1,wantsUseOllama:!1}),es.info("[fix] Acquiring AI proxy key",{useStablyAiProxy:Mt});const Ft=Date.now(),Ht=await async function({auth:e,client:t,source:r,metadata:n,duration:s}){try{const i=await(o={auth:e,client:t,body:{source:r,metadata:n??{},duration:s}},(o.client??Zr).post({security:[{scheme:"bearer",type:"http"}],url:"/v1/proxy/api-key",...o,headers:{"Content-Type":"application/json",...o.headers}})),a=i.response;if(i.error){const e="object"==typeof i.error&&"error"in i.error?i.error.error:"Unknown error";return{error:Ua(e,a)}}return i.data?{key:i.data.key}:{error:Ua("No data in response",a)}}catch(e){const t=e instanceof Error?e.message:"Unknown error";return{error:Ua(t)}}var o}({auth:Dt,client:pn(),source:"cli"}),Gt=Ht?.key;if(es.info("[fix] AI proxy key acquired",{durationMs:Date.now()-Ft,success:!!Gt,hasError:!!Ht?.error}),!Gt){const e=Ht?.error?.message?`Unable to make AI calls: ${Ht.error.message}`:"Unable to make AI calls. Check if you are authenticated.";es.warn("Failed to get proxy API key",{error:Ht?.error?.message}),st({error:e,status:"error"}),await qe(),es.flush(),es.printLogFileInfo(),process.exit(1)}es.debug("Proxy API key acquired",{success:!!Gt});const Wt="init"===e.mode,Vt="fix"===e.mode,Yt="plan"===e.mode,zt=!!bt,qt=zt?new oc({authProvider:l,projectId:ls(c)}):void 0,Kt={...g,...Rt?.variables,...Rt?.sensitiveValues.length?{STABLY_SENSITIVE_VALUES:Buffer.from(JSON.stringify(Rt.sensitiveValues)).toString("base64")}:{}},Jt=Wt||Yt?void 0:function(e){let t,r;!function(e){const t=i(e,".gitignore");try{if(E(t)){const e=x(t,"utf-8"),r=e.split("\n").map(e=>e.trim());if(r.includes(qa)||r.includes(`/${qa}`))return;const n=e.length>0&&!e.endsWith("\n");A(t,`${n?"\n":""}${qa}\n`)}}catch{}}(process.cwd());const n=new Set;let s;const o=()=>{var t;return s||(t=e.sessionName,s="auto"!==t?t:`stably-${process.pid}`),s};return{hook:async s=>{const i=s&&"object"==typeof s&&"tool_input"in s&&s.tool_input&&"object"==typeof s.tool_input&&"command"in s.tool_input&&"string"==typeof s.tool_input.command?s.tool_input.command:"";if(!Ha.test(i)&&!Ga.test(i))return{decision:"approve"};if(Ga.test(i)&&!Ha.test(i)){if(!r)try{r=await Ja(),es.info("[pwtrace-hook] Resolved binary",{path:r})}catch(e){const t=e instanceof Error?e.message:String(e);return{decision:"block",reason:t,systemMessage:`pwtrace binary not found: ${t}`}}const e=`${process.execPath} ${r}`;return{decision:"approve",hookSpecificOutput:{hookEventName:"PreToolUse",updatedInput:{command:i.replace(/\b(?:npx\s+)?pwtrace\b/g,e)}}}}if(Ga.test(i)&&!r)try{r=await Ja(),es.info("[pwtrace-hook] Resolved binary (mixed command)",{path:r})}catch{}const a=!!e.cloudBrowserManager,c=new RegExp(`\\bstably-browser\\s+${Wa}close\\b(?!-)`).test(i),l=new RegExp(`\\bstably-browser\\s+${Wa}close-all\\b`).test(i),u=new RegExp(`\\bstably-browser\\s+${Wa}(?!close(?:-all)?\\b)\\w`).test(i);if(l){if(!u&&0===n.size)return{decision:"approve"};if(a){const t=e.cloudBrowserManager;await Promise.all(Array.from(n).map(e=>t.releaseSession(e)))}if(n.clear(),!u){if(!t)try{t=await Ka()}catch(e){const t=e instanceof Error?e.message:String(e);return{decision:"block",reason:t,systemMessage:`stably-browser binary not found: ${t}`}}const e=`${process.execPath} ${t}`;let n=i.replace(/((?:npx\s+)?stably-browser\b[^;&|]*?)\s+(?:-s[= ]|--session[= ])[^\s;&|]+/g,"$1").replace(/\b(?:npx\s+)?stably-browser\b/g,e);if(Ga.test(n)&&r){const e=`${process.execPath} ${r}`;n=n.replace(/\b(?:npx\s+)?pwtrace\b/g,e)}return{hookSpecificOutput:{hookEventName:"PreToolUse",updatedInput:{command:n}}}}}if(c){if(!u&&0===n.size)return{decision:"approve"};const t=ec(s),r=Za(o(),t);n.delete(r),a&&e.cloudBrowserManager.getConfigPath(r)&&e.cloudBrowserManager.releaseSession(r)}if(!t)try{t=await Ka(),es.info("[stably-browser-hook] Resolved binary",{path:t})}catch(e){const t=e instanceof Error?e.message:String(e);return{decision:"block",reason:t,systemMessage:a?`stably-browser binary not found: ${t}. The stably-browser tool is unavailable. upload-trace-proof only uploads existing traces and does not depend on stably-browser, so it still works regardless. Report this issue to the user and suggest running locally instead.`:`stably-browser binary not found: ${t}. The stably-browser tool is unavailable. upload-trace-proof only uploads existing traces and does not depend on stably-browser, so it still works.`}}const d=ec(s),p=Za(o(),d);a&&e.cloudBrowserManager.needsRecreation(p)&&n.has(p)&&(es.info("[stably-browser-hook] Cloud browser needs recreation, clearing session",{sessionName:p}),n.delete(p),e.cloudBrowserManager.releaseSession(p));const f=new RegExp(`\\bstably-browser\\s+${Wa}open\\b`).test(i);if((!c&&!l||u)&&!n.has(p))if(a){n.add(p),es.info("[stably-browser-hook] Provisioning cloud browser...",{sessionName:p});try{let r=!1;const s=await e.cloudBrowserManager.acquire(p,()=>{r||(r=!0,e.onStatusLabel?.("Waiting for a browser to become available..."))});if(r&&e.onStatusLabel?.(void 0),s.liveViewUrl&&process.stderr.write(`Live view: ${s.liveViewUrl}\n`),!f){const r=e.cloudBrowserManager.getConfigPath(p),s=await Xa(t,p,e.headed,r??void 0);if(!s.ok)return n.delete(p),{decision:"block",reason:`Failed to start stably-browser daemon with cloud browser: ${s.reason}`,systemMessage:s.guidance}}}catch(e){n.delete(p);const t=e instanceof Error?e.message:String(e);return{decision:"block",reason:`Cloud browser unavailable: ${t}`,systemMessage:`Failed to provision cloud browser: ${t}. Remove --browser=cloud to use a local browser instead.`}}}else if(f)n.add(p);else{n.add(p),es.info("[stably-browser-hook] First browser command, starting daemon...",{sessionName:p,agentId:d});let r=await Xa(t,p,e.headed,void 0,"chromium");if(!r.ok&&r.reason.includes("not installed")&&(es.info("[stably-browser-hook] Chromium not found, falling back to system Chrome..."),r=await Xa(t,p,e.headed,void 0,"chrome")),!r.ok)return n.delete(p),{decision:"block",reason:`Failed to start stably-browser daemon: ${r.reason}`,systemMessage:r.guidance}}const h=`${process.execPath} ${t}`;let g=i.replace(/\b(?:npx\s+)?stably-browser\b/g,h);if(Ga.test(g)&&r){const e=`${process.execPath} ${r}`;g=g.replace(/\b(?:npx\s+)?pwtrace\b/g,e)}const m=[];if(g.includes("-s=")||g.includes("--session=")||m.push(`-s=${p}`),a){const t=e.cloudBrowserManager.getConfigPath(p);t&&!g.includes("--config=")&&m.push(`--config=${t}`),g=g.replace(/\s*--browser[= ]\S+/g,"")}e.headed&&!g.includes("--headed")&&m.push("--headed"),m.length>0&&(g=g.replaceAll(h,`${h} ${m.join(" ")}`)),l&&(g=g.replace(/([^;&|]*?\bclose-all\b)/g,e=>e.replace(/\s+(?:-s[= ]|--session[= ]|--config[= ])[^\s;&|]+/g,""))),Va.test(i)&&!g.includes("--trace")&&(g=g.replaceAll(/\brun-test\b/g,"run-test --trace=on")),e.envVars&&(g=g.replace(Ya,(t,r)=>{const n=e.envVars[r];return null!=n?n:t}));const y=[];if(Va.test(i)&&e.envVars)for(const[t,r]of Object.entries(e.envVars))y.push(`${t}=${za(r)}`);return y.length>0&&(g=`${y.join(" ")} ${g}`),es.debug("[stably-browser-hook] Rewritten command",{original:i.slice(0,100),sessionName:p,agentId:d,envVarCount:y.length}),{hookSpecificOutput:{hookEventName:"PreToolUse",updatedInput:{command:g}}}},cleanup:async()=>{t&&n.size>0&&(await Promise.all(Array.from(n).map(e=>{return r=t,n=e,new Promise(e=>{m(process.execPath,[r,"close",`-s=${n}`],{timeout:1e4},t=>{t&&es.debug("[stably-browser-hook] Failed to stop daemon",{error:t.message,sessionName:n}),e()})});var r,n})),n.clear()),e.cloudBrowserManager?.isActive()&&await e.cloudBrowserManager.release()}}}({sessionName:ac({configuredSessionName:process.env.STABLY_PLAYWRIGHT_SESSION,isFixMode:Vt,useCloudBrowser:zt}),headed:!("chat"!==e.mode||process.env.CI||"linux"===process.platform&&!process.env.DISPLAY),envVars:Kt,cloudBrowserManager:qt,onStatusLabel:e=>Ze({label:e})}),Qt=Vt?Rr.createLocal({workingDir:d}):void 0;Qt&&await Qt.captureSnapshot();const Xt=()=>{Wt&&function({workingDir:e,options:t={}}){const n=function(e){const t=function(e){let t=r.resolve(e);for(;;){if(w.existsSync(r.join(t,".git")))return t;const n=r.dirname(t);if(n===t)return r.resolve(e);t=n}}(e),n=function(e,t){for(const r of wa(e,t))if(fa(r))return r}(e,t),s=ma(ha(e,/playwright\.config\.(ts|js|mts|mjs|cjs)$/).map(e=>r.dirname(e))),o=function(e){const t=new Set;for(const n of e)t.add(ga(r.dirname(n)));return ma(Array.from(t))}(ha(e,/\.(spec|test)\.(ts|js)$/)),i=s.length>0?s:o,a=n??(1===i.length?i[0]:void 0)??e,c=ba(a,t);if(!c)return{repoRoot:t,projectRoot:a,targetDir:void 0};if(!n&&c===r.resolve(e)&&function(e,t,r){const n=new Set;for(const s of e){const e=ba(s,r);e&&e!==t&&n.add(e)}return n.size>1}(i,c,t))return{repoRoot:t,projectRoot:a,targetDir:void 0};const l=da(c);if(!l||!("workspaces"in l.contents))return{repoRoot:t,projectRoot:a,targetDir:c};const u=function(e,t){let n=r.resolve(e);const s=r.resolve(t);for(;n!==s;){if(w.existsSync(r.join(n,"package.json")))return n;const e=r.dirname(n);if(e===n)break;n=e}}(a,c);return{repoRoot:t,projectRoot:a,targetDir:u??c}}(e);if(n.targetDir){try{!function(e){const t=r.join(e,"package.json");if(!w.existsSync(t))return;const n=JSON.parse(w.readFileSync(t,"utf-8"));if({...n.dependencies,...n.devDependencies}.stably)es.debug("stably package already present in dependencies");else{es.info("stably package missing from devDependencies, installing...");try{ua({workingDir:e,packageManager:Ia(e),packageSpec:"stably",targetSection:"devDependencies"}),es.info("stably package installed successfully")}catch(e){es.warn("Failed to install stably package",{error:String(e)})}}}(n.targetDir)}catch(e){es.warn("Post-init: ensureStablyDependency failed",{error:String(e)})}try{!function(e){const t=da(e);if(!t)return;const r=t.contents.devDependencies?.playwright??t.contents.dependencies?.playwright;if(r)if(va(r)!==As)try{ua({workingDir:e,packageManager:Ia(e),packageSpec:`playwright@${As}`,targetSection:t.contents.devDependencies?.playwright?"devDependencies":"dependencies"}),es.info("standalone playwright version aligned successfully",{version:As})}catch(e){es.warn("Failed to align standalone playwright version",{error:String(e)})}else es.debug("standalone playwright already at supported version",{version:As});else es.debug("standalone playwright package not present")}(n.targetDir)}catch(e){es.warn("Post-init: alignStandalonePlaywrightVersion failed",{error:String(e)})}try{!function(e){const t=da(e);if(t)if(va(t.contents.devDependencies?.["@playwright/test"]??t.contents.dependencies?.["@playwright/test"])!==As)try{es.info(`Updating @playwright/test to supported version ${As}...`),ua({workingDir:e,packageManager:Ia(e),packageSpec:`@playwright/test@${As}`,targetSection:t.contents.dependencies?.["@playwright/test"]?"dependencies":"devDependencies"}),es.info("@playwright/test updated successfully")}catch(e){es.warn("Failed to update @playwright/test",{error:String(e)})}else es.debug("@playwright/test already at supported version",{version:As});else es.debug("No package.json found, skipping @playwright/test update")}(n.targetDir)}catch(e){es.warn("Post-init: updatePlaywrightTest failed",{error:String(e)})}try{!function(e,t,n){const s=[];n.googleAuth&&s.push("Google Auth methods"),n.emailPackage&&s.push("@stablyai/email Inbox methods for email verification flows");const o=`Use Stably CLI for Playwright test runs (better reporting, auto-fix); import from @stablyai/playwright-test for agent.act(), aiAssert, page.extract(), page.getLocatorsByAI()${s.length>0?`; also use ${s.join(" and ")}`:""}.`,i=function(e,t){const n=["CLAUDE.md","AGENTS.md","AGENT.md","agent.md"];for(const s of wa(e,t)){let t;for(const o of n){const n=r.join(s,o);if(!w.existsSync(n))continue;t??=n;const i=w.readFileSync(n,"utf-8");if(/Stably CLI/i.test(i)&&i.includes("@stablyai/playwright-test"))return void es.debug("Agent guidance already present",{file:r.relative(e,n)||o});if(ya(i))return n}if(t)return t}return r.join(e,"AGENTS.md")}(e,t);if(i){es.info("Appending Stably guidance",{file:r.basename(i)});try{const e=w.existsSync(i)?w.readFileSync(i,"utf-8"):"",t=e.length>0&&!e.endsWith("\n")?"\n\n":e.length>0?"\n":"";w.writeFileSync(i,`${e}${t}${o}\n`,"utf-8"),es.info("Agent guidance appended successfully")}catch(e){es.warn("Failed to update agent guidance file",{error:String(e)})}}}(n.targetDir,n.repoRoot,t)}catch(e){es.warn("Post-init: ensureAgentGuidance failed",{error:String(e)})}}else es.warn("Post-init: could not resolve target package directory; skipping verification",{workingDir:e})}({workingDir:d,options:{googleAuth:k?.googleAuth,emailPackage:k?.emailPackage}})},Zt=Wt?(({onComplete:e})=>G({name:"session-control",tools:[W("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:ve.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}`)})]}))({onComplete:()=>{Xt(),st({status:"success"}),Xe(),P?.finish(),qt?(setTimeout(()=>process.exit(0),5e3).unref(),qt.release().finally(()=>process.exit(0))):process.exit(0)}}):void 0,er=Zt?{"session-control":Zt}:{},tr=T&&Ot?["mcp__create-report"]:[],rr=T&&Re?["mcp__upload-trace-proof"]:[],nr=Wt?wc:_?yc:[...yc,...Vt?["mcp__auto-heal-report"]:[],...tr,...rr],sr=Wt?wc:b?[...bc,"mcp__stably-agent-control"]:_?bc:[...bc,...tr,...rr],or=T&&Ot?{"create-report":_a({prContext:Ot,authProvider:l,orgId:u,onReportPosted:e=>{Ie({githubComment:{url:e.commentUrl,prNumber:Ot.prNumber}})}})}:{},ir=T&&Re?{"upload-trace-proof":Sa({authProvider:l,sessionId:Re,orgId:u,workingDir:d,onTraceProofCaptured:e=>{Ie({traceProofs:[...we?.traceProofs??[],e]})}})}:{},ar=Wt?er:Yt?{}:Vt&&Qt?{"auto-heal-report":la({authProvider:l,diffTracker:Qt,orgId:u,runId:e.runId,workingDir:d}),"run-history":Pa({authProvider:l,orgId:u,projectId:ls(c)}),...er}:{...er,...or,...ir,"run-history":Pa({authProvider:l,orgId:u,projectId:ls(c)}),environment:Ca({hookEnvVars:Kt,initialRemoteKeys:Rt?new Set(Object.keys(Rt.variables)):void 0,localEnvSnapshot:{...g}})},cr="single"===e.mode,lr=Wt?[]:cr?[{matcher:"Write",hooks:[Ys({onFileCreated:e=>{if(lt.includes(e)||lt.push(e),we){if(we.filesCreated.some(t=>"string"==typeof t?t===e:t.path===e))return;const t=n.isAbsolute(e)?e:n.join(d,e),r=n.basename(e),{sessionId:s}=we,o=(async()=>{try{const n=await v.promises.readFile(t,"utf8"),o=await(async({authHeader:e,content:t,contentType:r="text/plain",filename:n,filePath:s,orgId:o,sessionId:i})=>{try{const{bucketPath:a,uploadUrl:c}=await(async({authHeader:e,contentType:t="text/plain",filename:r,filePath:n,orgId:s,sessionId:o})=>{const i=await(a={auth:e,body:{filename:r,filePath:n,contentType:t},client:pn(),headers:hs(s),path:{sessionId:o}},(a.client??Zr).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=Es.parse(i.data);return{bucketPath:c.bucketPath,expiresInSeconds:c.expiresInSeconds,key:c.key,uploadUrl:c.uploadUrl}})({authHeader:e,contentType:r,filename:n,filePath:s,orgId:o,sessionId:i});return await ys({body:t,contentType:r,uploadUrl:c,errorContext:"file"}),await(async({authHeader:e,bucketPath:t,filename:r,filePath:n,orgId:s,sessionId:o})=>{const i=await(a={auth:e,body:{filename:r,filePath:n,bucketPath:t},client:pn(),headers:hs(s),path:{sessionId:o}},(a.client??Zr).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:s,orgId:o,sessionId:i}),a}catch(e){return es.warn("Failed to upload automation file",{error:e instanceof Error?e.message:String(e)}),null}})({authHeader:await l.getAuthHeader(),content:n,contentType:"text/plain",filename:r,filePath:e,orgId:u,sessionId:s}),i={path:e,filename:r,bucketPath:o};ut.push(i),Ie({filesCreated:[...ut]})}catch(t){es.warn("Failed to upload created file",{filePath:e,error:t instanceof Error?t.message:String(t)});const n={path:e,filename:r,bucketPath:null};ut.push(n),Ie({filesCreated:[...ut]})}})();dt.push(o)}}})]}]:[],ur=Wt?[]:[...Vt?[{matcher:"Read",hooks:[Rs({action:"reading",pathKey:"file_path"})]},{matcher:"Write",hooks:[Rs({action:"writing",pathKey:"file_path"})]},{matcher:"Edit",hooks:[Rs({action:"editing",pathKey:"file_path"})]},{matcher:"Grep",hooks:[Rs({action:"searching",pathKey:"path"})]},{matcher:"Glob",hooks:[Rs({action:"searching",pathKey:"path"})]},{matcher:"Bash",hooks:[Ws({workspaceBoundary:d})]}]:[],...Jt?[{matcher:"Bash",hooks:[Jt.hook]}]:[],{hooks:[async e=>(e&&"object"==typeof e&&"tool_name"in e?e.tool_name:"").startsWith("mcp__plugin_playwright_playwright__browser_")?{decision:"block",reason:"Use stably-browser commands instead of the built-in Playwright MCP tools.",systemMessage:'Do NOT use mcp__plugin_playwright_playwright tools. Use stably-browser bash commands for all browser interaction:\n- `stably-browser open` / `stably-browser open <url>`\n- `stably-browser goto <url>`, `stably-browser click <ref>`, `stably-browser fill <ref> "text"`\n- `stably-browser snapshot`, `stably-browser screenshot`\n- `stably-browser run-test <file>`\n- `stably-browser close`'}:{decision:"approve"}]}],dr=Object.keys(Bt).length>0?Bt:void 0,pr={...jt};pr.MCP_TOOL_TIMEOUT=String(6e5),Gt&&(pr.ANTHROPIC_API_KEY=Gt,pr.ANTHROPIC_BASE_URL=cn,pr.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS="1",pr.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC="1");const fr=process.env.STABLY_AGENT_MODEL??"claude-opus-4-6",hr=Vt?"env"===c.type?c.auth.apiKey:c.auth.accessToken:void 0,gr=Vt?ls(c):void 0;Vt&&hr&&gr&&(pr.STABLY_API_KEY=hr,pr.STABLY_PROJECT_ID=gr);const mr=Tt?`\n\n## Authoritative Fix Rules (STABLY-FIX.md / stably.yaml)\nThese repository-specific fix instructions take precedence over generic fix guidance when they conflict.\n${Tt}`:"",yr=kt?`\n\n## Authoritative Test Generation Rules (STABLY-CREATE.md)\nThese repository-specific create instructions take precedence over generic create guidance when they conflict.\n${kt}`:"",br=Ct?`\n\n## Authoritative Project Rules (STABLY.md)\nThese repository-specific project instructions take precedence over generic guidance when they conflict. If STABLY-CREATE.md is also present, use it for create-specific conflicts.\n${Ct}`:"",wr=bt?"\n\n## Cloud Browser Mode\nYou are running in cloud browser mode. Cloud browsers are remote VMs β there is no local resource cost.\n\n**Each subagent MUST use its own isolated browser session.** Do NOT reuse or share browser sessions between subagents. Session isolation is automatic β each subagent simply calls `stably-browser open` and gets its own browser.\n\nWhen running tests with `stably-browser run-test`, each subagent also gets its own browser automatically.":"",vr=Nt+mr+yr+br+wr;es.debug("[fix] Final system prompt assembled",{baseSize:Nt.length,fixRulesSize:mr.length,createRulesSize:yr.length,stablyMdSize:br.length,cloudBrowserSize:wr.length,finalSize:vr.length});const Ir=function(){const e=function(){const e=function(){const e=process.env.STABLY_PLUGIN_PATH?.trim();if(!e)return;const t=n.isAbsolute(e)?e:n.resolve(process.cwd(),e);return ja(t)?t:void 0}();if(e)return e;const t=n.join(Na,"stably-plugin-cli");if(ja(t))return t;for(const e of function*(e){let t=n.resolve(e);for(;;){yield t;const e=n.dirname(t);if(e===t)return;t=e}}(Na))for(const t of Ba){const r=n.join(e,t);if(ja(r))return r}}();if(e)return{type:"local",path:e}}(),Tr=()=>(es.info("[fix] Starting SDK query",{model:fr,tools:nr,mcpServers:Object.keys(ar),resumeSessionId:D??null,subagentsEnabled:!!dr,subagentCount:Object.keys(Bt).length,useStablyAiProxy:Mt,aiProxyUrl:cn,anthropicBaseUrl:void 0,stablyPluginPath:Ir?.path,stablyPluginExists:!!Ir}),V({options:{executableArgs:["--max-old-space-size=4096"],tools:nr,allowedTools:sr,...null!=xt?{maxBudgetUsd:xt}:{},betas:[],canUseTool:(e,t)=>(es.debug("[fix] canUseTool called",{toolName:e}),Promise.resolve({behavior:"allow",updatedInput:t})),cwd:d,env:pr,hooks:{PostToolUse:lr,PreToolUse:ur},includePartialMessages:!0,agents:dr,mcpServers:ar,model:fr,permissionMode:"default",plugins:Ir?[Ir]:void 0,systemPrompt:vr,...D?{resume:D}:{}},prompt:P??gt})),_r=async e=>{if(y&&B&&!H&&!O)O=(async()=>{es.info("[fix] Interrupting for user message",{messageCount:e.length,phase:ce?.phase});try{await(L?.interrupt?.())}catch(e){es.warn("[fix] Failed to interrupt response for user message",{error:e instanceof Error?e.message:String(e)})}await qs(),P?.finish(),P=new Ks,Q.clear(),L=Tr();const t=e.map(e=>`[Message from web UI user]: ${e}`).join("\n\n");P.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}`),K=!0,B=!0})().finally(()=>{O=void 0}),await O;else for(const t of e)P?.pushText(`[Message from web UI user]: ${t}`)};if(Gt){_&&Ze({label:"Checking AI connectivity..."});const e=cn,t=`${e.replace(/\/$/,"")}/v1/messages`;es.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":Gt,"anthropic-version":"2023-06-01","content-type":"application/json"},body:"{}"}),s=await e.text().catch(()=>""),o=Date.now()-r;es.debug(`[fix] Pre-flight: ${e.status} in ${o}ms β ${s.slice(0,300)}`),401===e.status||403===e.status?(es.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."):es.info("[fix] Pre-flight: AI proxy key valid",{status:e.status,durationMs:o})}catch(t){es.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{_&&"running"===nt&&Ze({label:void 0})}n&&(We({text:`[stably] ${n}\n`}),st({error:n,status:"error"}),await qe(),es.flush(),es.printLogFileInfo(),process.exit(1))}es.info("[fix] Creating initial agent query"),_&&(Ze({label:"Initializing verification session..."}),We({text:"Initializing verification session...\n"})),es.flush(),L=Tr(),es.info("[fix] Agent query created, entering message loop"),"chat"!==e.mode&&(P.pushText(gt),X.push({role:"user",content:gt,timestamp:(new Date).toISOString()}));const Er=async t=>{Ne||(Ne=(async()=>{es.info("[session] Interrupt requested",{source:t,mode:e.mode}),te="CANCELED",await me("CANCELED"),ge({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:he(!0)}),await(ae?.closeAndWait()),await Promise.allSettled(dt),Ie({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0}),await(be?.closeAndWait()),N&&(clearTimeout(N),N=void 0),Xe(),await qs(),await(Jt?.cleanup());try{await(L?.interrupt?.())}catch{}if(P?.finish(),X.length>0&&Re)try{await xs({authHeader:await l.getAuthHeader(),orgId:u,sessionId:Re,projectId:ls(c),history:X})}catch(e){es.warn("[exit] Failed to upload session history",{error:e instanceof Error?e.message:String(e)})}qe(),es.flush()})()),await Ne};De.current=async()=>{await Er("ctrl-c")};let Sr=()=>{};Sr=function({enabled:e,onSignal:t}){const r=()=>{t("SIGINT")},n=()=>{t("SIGTERM")};return process.prependOnceListener("SIGINT",r),process.prependOnceListener("SIGTERM",n),()=>{process.removeListener("SIGINT",r),process.removeListener("SIGTERM",n)}}({enabled:!0,onSignal:e=>{(async()=>{await Er("signal"),process.exit(function(e){return"SIGINT"===e?130:143}(e))})()}});let xr=null,Ar=null,kr="";Oe.current=async()=>{if(!Be&&B&&P){Be=!0;try{es.info("[chat] User pressed Escape to cancel generation"),Ke(),Je(),j=!0,je=!0;try{await(L?.interrupt?.())}catch(e){es.warn("[chat] Failed to interrupt response on Escape",{error:e instanceof Error?e.message:String(e)})}await qs();const e=P.drainQueue();P.finish(),P=new Ks;for(const t of e)P.pushText(t);M=e.length,L=Tr();for(const e of Q.keys())tt({toolUseId:e,status:"error"});Ge()}finally{Be=!1}}};let Pr=0,Cr=null,Ur=!1;const $r=b?void 0:_?9e4:18e4;let Lr=!1;const Dr=null!=$r?setTimeout(()=>{Cr||"running"!==nt||(t=>{if(!Lr){if(Lr=!0,clearTimeout(Dr),clearInterval(Nr),setTimeout(()=>process.exit(1),6e4).unref(),es.error("[session] Session timeout",{reason:t,mode:e.mode,elapsed:Date.now()-ie}),te="FAILED",_||b){const e="This is taking longer than expected. Please try again.";We({text:`[stably] ${e}\n`}),st({error:e,status:"error"})}else ge({phase:"complete",endedAt:Date.now(),isError:!0,errorReason:"execution_error",errorMessage:`Session timed out: ${t}`,workers:he(!0)});Ie({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:`Timed out: ${t}`});try{L?.interrupt?.()}catch{}P?.finish()}})("no response from AI service")},$r):void 0;Dr?.unref();const Nr=setInterval(()=>{const e=Date.now()-ie;Cr?es.info("[fix] Watchdog: message loop active",{messageCount:Pr,elapsed:e}):(es.info("[fix] Watchdog: waiting for first SDK message",{elapsed:e}),_&&!Ur&&e>=15e3&&(We({text:"Still preparing verification. This can take a bit...\n"}),Ur=!0)),es.flush()},15e3);Nr.unref();try{let t=!1,r=!1;for(;;){if(!L){es.info("[fix] No response object, exiting message loop");break}t=!1,r=!1,es.info("[fix] Entering for-await on SDK response");try{for await(const t of L){if(Lr)break;Pr++,Cr||(Cr=Date.now(),clearTimeout(Dr),_&&Ze({label:void 0}),es.info("[fix] First SDK message received",{waitDurationMs:Cr-ie,messageType:t.type,messageSubtype:"subtype"in t?t.subtype:void 0}));const n="session_id"in t&&"string"==typeof t.session_id?t.session_id:void 0;if(n&&n!==D&&(D=n,es.debug("Captured Claude session id",{sessionId:D})),"stream_event"===t.type){const{event:e}=t;(Pr<=5||Pr%200==0)&&es.debug("[fix] Stream event",{msgNum:Pr,eventType:e?.type});const r=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_start"===e?.type){const t=e.content_block;"thinking"===t?.type&&(xr=e.index??null)}if("content_block_delta"===e?.type){const{delta:t}=e;if("text_delta"===t?.type&&t.text){kr&&(Z({role:"thinking",content:kr,timestamp:(new Date).toISOString()}),kr="");const e=r&&Q.has(r)?r:1===Q.size?Array.from(Q.keys())[0]:void 0;e?Me({toolUseId:e,kind:"text",content:t.text}):_||We({text:t.text})}const n=t;if("thinking_delta"===n?.type&&n.thinking){if(r&&Q.has(r))continue;if(kr+=n.thinking,!_){const e=null!==xr&&xr!==Ar;Ve({text:n.thinking,forceNewBlock:e}),e&&(Ar=xr)}continue}}if("content_block_stop"===e?.type){const t=e.index;null!==xr&&xr===t&&(Je(),kr&&(Z({role:"thinking",content:kr,timestamp:(new Date).toISOString()}),kr=""),xr=null,Qe())}"message_stop"===e?.type&&P&&(H=!1,P.allowNextTurn());continue}if("assistant"===t.type){const r="parent_tool_use_id"in t&&"string"==typeof t.parent_tool_use_id?t.parent_tool_use_id:void 0,{content:n}=t.message??{};if(Array.isArray(n)&&!r){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&&(at=t,_&&(ct=ct?`${ct}\n\n${t}`:t),es.debug("Assistant message",{text:_?pc(t):t}),"fix"===e.mode&&(pe(Ic,{type:"ai_message",summary:t.slice(0,200)}),fe({type:"ai_message",summary:t.slice(0,200)})),S&&Pe({type:"ai_message",summary:t.slice(0,200)}),Z({role:"assistant",content:t,timestamp:(new Date).toISOString()}))}if(Q.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):[];es.debug("Assistant message with active subagents",{hasParentToolUseId:!!r,parentToolUseId:r,activeSubagentIds:Array.from(Q.keys()),toolNames:e,fullMessageKeys:Object.keys(t),rawMessage:JSON.stringify(t).slice(0,500)})}if(Array.isArray(n))for(const t of n){if("tool_use"===t?.type){if("mcp__auto-heal-report__generate-report"===t.name&&(H=!0),t.name.startsWith("mcp__session-control__")||t.name.startsWith("mcp__stably-agent-control__"))continue;if(xc(t.name))continue;if(_&&Sc.test(t.name))continue;if(Q.size>0&&es.debug("Tool use detected with active subagents",{toolName:t.name,hasParentToolUseId:!!r,parentToolUseId:r,wouldRouteToSubagent:!!r&&Q.has(r),activeSubagentIds:Array.from(Q.keys())}),"Task"===t.name){const r=t.input,n=r&&"object"==typeof r?r:void 0,s=n&&"subagent_type"in n&&"string"==typeof n.subagent_type?n.subagent_type:"subagent",o=n&&"description"in n&&"string"==typeof n.description?n.description.trim():"";if(es.info("[fix] Subagent started",{subagentType:s,description:o,toolUseId:t.id,activeSubagentCount:Q.size+1}),Q.set(t.id,{subagentType:s,description:o}),Fe({toolUseId:t.id,subagentType:s,description:o}),"fix"===e.mode){if("triage"===s){rt?.({phase:"triage"});const e={id:t.id,testDescription:"Triage",workerType:"triage",status:"running",summary:null,startedAt:Date.now(),endedAt:null,activity:[]};ge({phase:"triage",workers:[...ce?.workers??[],e]})}else if("code-worker"===s){le.add(o||t.id);const e={id:t.id,testDescription:o||t.id,workerType:"code-worker",status:"running",summary:null,startedAt:Date.now(),endedAt:null,activity:[]};rt?.({phase:"fixing",totalTests:le.size,currentTestDescription:o||null}),ge({phase:"fixing",totalTests:le.size,currentTestDescription:o||null,lastTestDescription:o||ce?.lastTestDescription||null,workers:[...ce?.workers??[],e]})}else if("browser-worker"===s){le.add(o||t.id);const e={id:t.id,testDescription:o||t.id,workerType:"browser-worker",status:"running",summary:null,startedAt:Date.now(),endedAt:null,activity:[]};rt?.({phase:"debugging",totalTests:le.size,currentTestDescription:o||null}),ge({phase:"debugging",totalTests:le.size,currentTestDescription:o||null,lastTestDescription:o||ce?.lastTestDescription||null,workers:[...ce?.workers??[],e]})}else"validation"===s?(rt?.({phase:"validation",currentTestDescription:null}),ge({phase:"validation",currentTestDescription:null})):"context"===s&&ge({currentTestDescription:o||null});fe({type:"tool_call",summary:`[${s}] ${o}`.trim()})}if(T)if("create-planner"===s)Ie({phase:"planning",currentActivity:"Analyzing test plan..."}),Pe({type:"tool_call",summary:`[create-planner] ${o}`.trim()});else if("create-worker"===s){const e=o.match(/(?:route|page)[:\s]+([^\s,]+)/i),r=(e?.[1]??o.slice(0,50))||t.id,n=o.match(/(\d+)\s*test/i),s=n?parseInt(n[1],10):1,i={pageGroupId:t.id,route:r,status:"exploring",testsCreated:0,testsTotal:s};ue.set(t.id,i),Ie({phase:"generating",currentActivity:`Worker exploring ${r}...`,workers:Array.from(ue.values())}),Pe({type:"tool_call",summary:`[create-worker] ${o}`.trim()})}continue}if(r&&Q.has(r)){const n=To(t.name,t.input),s=n??_o(t.name),o=n?void 0:Io(t.name,t.input),i=o?`${s} (${o})`:s;if(es.debug("Subagent tool called",{tool:t.name,parentToolUseId:r}),Me({toolUseId:r,kind:"tool",content:i}),"fix"===e.mode){fe({type:"tool_call",summary:i});const e=Q.get(r);"code-worker"!==e?.subagentType&&"browser-worker"!==e?.subagentType&&"triage"!==e?.subagentType||pe(r,{type:"tool_call",summary:i})}if(T){const e=Q.get(r);if(("create-planner"===e?.subagentType||"create-worker"===e?.subagentType)&&(Pe({type:"tool_call",summary:i}),"create-worker"===e.subagentType&&ue.has(r))){const e="Bash"===t.name&&t.input&&"object"==typeof t.input?t.input.command:void 0;t.name.includes("run-test")||t.name.includes("run_test")||"string"==typeof e&&e.includes("run-test")?de(r,{status:"validating"}):"Write"!==t.name&&"Edit"!==t.name||de(r,{status:"writing"})}}continue}if(r&&es.debug("Tool with parent_tool_use_id but no matching subagent",{tool:t.name,parentToolUseId:r,activeSubagentIds:Array.from(Q.keys())}),es.debug("Tool called",{tool:t.name,input:t.input}),He({rawName:t.name,toolInput:t.input}),t.id&&ee.set(t.id,t.name),Z({role:"tool",content:"",timestamp:(new Date).toISOString(),toolName:t.name,toolInput:t.input}),"fix"===e.mode){const e=To(t.name,t.input),r=e??_o(t.name),n=e?void 0:Io(t.name,t.input),s=n?`${r} (${n})`:r;pe(Ic,{type:"tool_call",summary:s}),fe({type:"tool_call",summary:s})}if(T){const e=To(t.name,t.input),r=e??_o(t.name),n=e?void 0:Io(t.name,t.input),s=n?`${r} (${n})`:r;"initializing"===we?.phase?Ie({phase:"generating",currentActivity:s}):"mcp__playwright-test__test_run"===t.name&&"generating"===we?.phase?Ie({phase:"testing",currentActivity:s}):Ie({currentActivity:s}),Pe({type:"tool_call",summary:s})}if(_){const e=To(t.name,t.input),r=e??_o(t.name),n=e?void 0:Io(t.name,t.input),s=pc(n?`${r} (${n})`:r);Ie("initializing"===we?.phase?{phase:"verifying",currentActivity:s}:{currentActivity:s}),Pe({type:"tool_call",summary:s})}}if("text"===t?.type){const n="string"==typeof t.text?t.text:"",s=r&&Q.has(r)?r:1===Q.size?Array.from(Q.keys())[0]:void 0;if(s&&n){if(Me({toolUseId:s,kind:"text",content:n}),"fix"===e.mode){const e=Q.get(s);"code-worker"!==e?.subagentType&&"browser-worker"!==e?.subagentType&&"triage"!==e?.subagentType||pe(s,{type:"ai_message",summary:n.slice(0,200)})}if(T){const e=Q.get(s);"create-planner"!==e?.subagentType&&"create-worker"!==e?.subagentType||Pe({type:"ai_message",summary:n.slice(0,200)})}}}}continue}if("user"===t.type){const r="message"in t&&t.message&&"object"==typeof t.message&&"content"in t.message?t.message.content:void 0,n="tool_use_result"in t&&t.tool_use_result&&"object"==typeof t.tool_use_result?t.tool_use_result:void 0;if(Array.isArray(r))for(const t of r)if(t&&"object"==typeof t&&"type"in t&&"tool_result"===t.type&&"tool_use_id"in t){const r="string"==typeof t.tool_use_id?t.tool_use_id:void 0,s="is_error"in t&&!0===t.is_error||"error"===n?.status;let o;const i=n?.content??("content"in t?t.content:void 0);"string"==typeof i?o=i:Array.isArray(i)&&(o=i.filter(e=>e&&"object"==typeof e&&"text"===e.type).map(e=>e.text||"").join("")),es.debug("Tool result",{toolUseId:r,isError:s,output:o?.slice(0,500)});const a=5e4,c=r?ee.get(r):void 0;if(Z({role:"tool_result",content:"",timestamp:(new Date).toISOString(),toolName:c,toolOutput:o?.slice(0,a),isError:s}),r&&Q.has(r)){const t=Q.get(r);if(es.info("[fix] Subagent completed",{toolUseId:r,isError:s,subagentType:t?.subagentType,description:t?.description,activeSubagentCount:Q.size-1}),o&&Me({toolUseId:r,kind:"text",content:o}),tt({toolUseId:r,status:s?"error":"complete"}),"fix"===e.mode&&"triage"===t?.subagentType){const e=s?"failed":"succeeded",t=o?o.slice(0,500):null,n=(ce?.workers??[]).map(n=>n.id===r?{...n,status:e,summary:t,endedAt:Date.now()}:n);ge({workers:n})}if("fix"===e.mode&&("code-worker"===t?.subagentType||"browser-worker"===t?.subagentType)){const e=s?"failed":"succeeded",t=o?o.slice(0,500):null,n=(ce?.workers??[]).map(n=>n.id===r?{...n,status:e,summary:t,endedAt:Date.now()}:n);s?(rt?.({failedTests:(ce?.failedTests??0)+1,currentTestDescription:null}),ge({failedTests:(ce?.failedTests??0)+1,currentTestDescription:null,workers:n})):(rt?.({fixedTests:(ce?.fixedTests??0)+1,currentTestDescription:null}),ge({fixedTests:(ce?.fixedTests??0)+1,currentTestDescription:null,workers:n}))}if(T&&t)if("create-planner"===t.subagentType)Pe({type:"ai_message",summary:s?"Planner failed":"Test plan analyzed, launching workers..."}),s||Ie({phase:"generating",currentActivity:"Launching workers..."});else if("create-worker"===t.subagentType){if(ue.has(r)){const e=o?.match(/\*\*Created:\*\*\s*(\d+)/i),t=e?parseInt(e[1],10):0;de(r,{status:s?"failed":"complete",testsCreated:t})}Pe({type:"ai_message",summary:s?`Worker failed: ${t.description?.slice(0,100)}`:`Worker complete: ${t.description?.slice(0,100)}`})}Q.delete(r)}}continue}if("result"!==t.type);else{if(r=!0,es.info("[fix] Agent result received",{subtype:t.subtype,messageCount:Pr,elapsed:Date.now()-ie,activeSubagents:Q.size,fixedTests:ce?.fixedTests,failedTests:ce?.failedTests,phase:ce?.phase}),y){if("success"===t.subtype){N&&(clearTimeout(N),N=void 0);for(const e of F)P?.pushText(`[Message from web UI user]: ${e}`);if(F=[],(S||"fix"===e.mode)&&P){if(P.hasQueuedMessages()){es.info("[ws] Queued web UI messages found, continuing agent"),B=!0,P.allowNextTurn();continue}if(await Ac(P,3e3)){es.info("[ws] Web UI message received during grace period, continuing agent"),B=!0,P.allowNextTurn();continue}P.finish()}rt?.({phase:"complete",currentTestDescription:null,endedAt:Date.now()}),ge({phase:"complete",currentTestDescription:null,endedAt:Date.now(),isError:!1,workers:he(!1)}),await Promise.allSettled(dt);const t=gc({mode:e.mode,lastAssistantText:at});if("verify"===e.mode){(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt).trim();const r=ct||at,n=/```verdict\s*\r?\n/.test(r),s=hc(r)??{verdict:"INCONCLUSIVE",steps:["Agent finished without a parseable verdict block."],reason:n?"Failed to parse verdict.":"The agent completed without reporting a verdict.",evidence:[]},o=fc(s);"PASS"===s.verdict?se.green("VERIFICATION PASSED"):"FAIL"===s.verdict?se.red("VERIFICATION FAILED"):mc("VERIFICATION INCONCLUSIVE"),o.steps.length>0&&o.steps.forEach((e,t)=>{}),o.reason&&(s.verdict,o.reason),o.evidence.length>0&&o.evidence.forEach(e=>{}),Ie({phase:"complete",endedAt:Date.now(),isError:"PASS"!==s.verdict,currentActivity:null,resultSummary:t}),process.exitCode="PASS"===s.verdict?0:"FAIL"===s.verdict?1:2,st({status:"success"})}else{if(Ie({phase:"complete",endedAt:Date.now(),isError:!1,currentActivity:null,resultSummary:t}),cr&<.length>0){se.green("Created files:");for(const e of lt)se.green(`- ${e}`)}const e=(e,t)=>`]8;;${e}${t}]8;;`,r=ot?se.cyan(`π View Autoheal Report:\n ${e(ot,se.cyan(se.bold(se.underline(ot))))}`):void 0;st({status:"success",result:r}),te="COMPLETED"}}else if(O||K)es.info("[fix] Suppressing error status: user-message interrupt in progress");else if(j)te="CANCELED",ge({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:he(!0)}),await Promise.allSettled(dt),Ie({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0});else if(_){let e="Execution error before verification completed.";"error_max_budget_usd"===t.subtype?e="Budget limit exceeded before verification completed.":"error_max_turns"===t.subtype&&(e="Maximum turns exceeded before verification completed."),mc("VERIFICATION INCONCLUSIVE"),await Promise.allSettled(dt),Ie({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),st({status:"success"}),process.exitCode=2}else{let e,r="unknown",n="Run failed.";"error_max_budget_usd"===t.subtype?(r="budget_exceeded",e="total_cost_usd"in t?t.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.`,es.warn("[fix] Budget limit exceeded",{subtype:t.subtype,totalCostUsd:e})):"error_max_turns"===t.subtype?(r="max_turns",n="Maximum turns exceeded. The fix session was stopped."):"error_during_execution"===t.subtype&&(r="execution_error"),rt?.({endedAt:Date.now(),isError:!0}),ge({phase:"complete",endedAt:Date.now(),isError:!0,errorReason:r,errorMessage:n,totalCostUsd:e,currentTestDescription:null,workers:he(!0)}),await Promise.allSettled(dt),Ie({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),st({error:n,status:"error"}),process.exitCode=1,te="FAILED"}j=!1;break}if("success"!==t.subtype){if(!j){let e="Run failed.";"error_max_budget_usd"===t.subtype?(e=`Budget limit exceeded (${"total_cost_usd"in t?`$${t.total_cost_usd.toFixed(2)}`:"unknown"} spent). The fix session was stopped to prevent runaway costs.`,es.warn("[fix] Budget limit exceeded",{subtype:t.subtype,totalCostUsd:"total_cost_usd"in t?t.total_cost_usd:void 0})):"error_max_turns"===t.subtype&&(e="Maximum turns exceeded. The fix session was stopped."),st({error:e,status:"error"}),process.exitCode=1}}else st({status:"success"});B=!1,j=!1,Ze({label:void 0}),P?.allowNextTurn(),I&&M>0&&(M-=1,B=!0,st({status:"running"}))}}}catch(e){if(je){je=!1,j=!1,Q.clear(),ze(),kr&&Z({role:"thinking",content:kr,timestamp:(new Date).toISOString()}),xr=null,Ar=null,kr="",Qe(),M>0?(B=!0,st({status:"running"})):(B=!1,st({status:"success"})),t=!0;continue}const n=e instanceof Error&&"Claude Code process exited with code 1"===e.message;if(n&&r){es.info("[fix] Claude Code process exited with code 1 (normal exit after result)",{inFlight:B,interrupted:j});break}if(n&&(K||O||j)){es.info("[fix] Claude Code process exited with code 1 (interrupted)",{inFlight:B,interrupted:j,userMessageInterruptTriggered:!!K,interruptInProgress:!!O});break}throw e}if(je)je=!1,j=!1,Q.clear(),ze(),kr&&Z({role:"thinking",content:kr,timestamp:(new Date).toISOString()}),xr=null,Ar=null,kr="",Qe(),M>0?(B=!0,st({status:"running"})):(B=!1,st({status:"success"})),t=!0;else if(O&&await O,K&&(K=!1,t=!0,st({status:"running"}),es.info("[fix] Resuming after user-message interrupt")),!t)break}}catch(e){j?(te="CANCELED",ge({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:he(!0)}),await Promise.allSettled(dt),Ie({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0})):(es.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()-ie}),st({error:`Agent encountered an error: ${e}`,status:"error"}),process.exitCode=1,te="FAILED",ge({phase:"complete",endedAt:Date.now(),isError:!0,currentTestDescription:null,workers:he(!0)}),await Promise.allSettled(dt),Ie({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),es.flush(),es.printLogFileInfo())}finally{if(Dr&&clearTimeout(Dr),clearInterval(Nr),N&&(clearTimeout(N),N=void 0),es.info("[fix] Agent session ending",{finalStatus:te,elapsed:Date.now()-ie,totalMessages:Pr}),Xt(),B=!1,j=!1,Sr(),process.off("uncaughtException",a),P?.finish(),te){es.info("[fix] Reporting final autoheal status",{status:te});const e=Date.now();await me(te),es.info("[fix] Final autoheal status reported",{durationMs:Date.now()-e})}if(es.info("[fix] Closing WebSocket progress reporter"),await(ae?.closeAndWait()),await Promise.allSettled(dt),await(be?.closeAndWait()),!Vt&&X.length>0&&Re){es.info("[session] Uploading session history",{messageCount:X.length});try{await xs({authHeader:await l.getAuthHeader(),orgId:u,sessionId:Re,projectId:ls(c),history:X})}catch(e){es.warn("[session] Failed to upload session history",{error:e instanceof Error?e.message:String(e)})}}if(Vt&&Qt){const t=Date.now();try{es.info("[fix] Computing diff...");const r=await Qt.computeDiff();if(r&&r.trim().length>0){es.info("[fix] Uploading diff...",{diffLength:r.length});const n=await l.getAuthHeader(),{diffBucketPath:s,uploadUrl:o}=await vs({authHeader:n,contentType:"text/plain",orgId:u,runId:e.runId});await ys({body:r,contentType:"text/plain",uploadUrl:o,errorContext:"diff"}),await Is({authHeader:n,diffBucketPath:s,orgId:u,runId:e.runId}),es.info("[fix] Diff uploaded",{durationMs:Date.now()-t})}else es.info("[fix] No diff to upload (empty or no changes)")}catch(e){es.warn("[fix] Failed to upload diff",{error:e instanceof Error?e.message:String(e),durationMs:Date.now()-t})}}if(es.info("[fix] Cleaning up diff tracker"),await(Qt?.cleanup()),Vt&&X.length>0&&Re){es.info("[fix] Uploading session history",{messageCount:X.length});try{await xs({authHeader:await l.getAuthHeader(),orgId:u,sessionId:Re,projectId:ls(c),history:X})}catch(e){es.warn("[fix] Failed to upload session history",{error:e instanceof Error?e.message:String(e)})}}const t=n.join(d,".stably","traces");await z(t,{recursive:!0,force:!0}).catch(()=>{}),es.info("[fix] Running final cleanup"),await(Jt?.cleanup()),await qe(),es.info("[fix] Cleanup complete"),Lr&&(es.flush(),es.printLogFileInfo(),process.exit(1))}},Rc=he.object({runId:he.string(),timestamp:he.number()}),Uc=async()=>{try{const e=await wn(process.cwd(),".stably/last-run.json");if(!e)return;const t=await q(e,"utf-8");return{...Rc.parse(JSON.parse(t)),filePath:e}}catch{return}};function $c(e=process.cwd()){let t=s(e);for(;;){const e=Lc(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=Dc(t);let r=!1,s=t;for(;;){const e=i(s,"node_modules"),t=i(e,n);if(E(t)){r=!0;break}const a=o(s);if(a===s)break;s=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 Lc(e){const t=i(e,"package.json");let r;try{r=x(t,"utf-8")}catch{return}try{return JSON.parse(r)}catch{return}}function Dc(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(E(i(r,n)))return e;const e=o(r);if(e===r)return;r=e}}function Nc(e){if("npm"===e||"pnpm"===e)return["npx","playwright"];if("yarn"===e)return["yarn","playwright"];throw new Error("Package manager not supported")}var Oc=[{args:["--trace=on"],description:"Run Playwright tests",name:"test"},{args:[],description:"Install browser dependencies",name:"install"}],Bc=["You have two different versions of @playwright/test"];function jc(e){const[t,...r]=Nc(e),n=[t,...r.slice(0,-1)].join(" ");return(t,r)=>{let s=t.toString();for(const e of Oc)s=s.replaceAll(`${n} playwright ${e.name}`,`${n} stably ${e.name}`).replaceAll(`npx playwright ${e.name}`,`npx stably ${e.name}`);if("yarn"===e){const e=s.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(s)}}async function Mc({overrideArgs:e,subcommand:t}){es.info("[test] forwardToPlaywright starting",{subcommand:t,overrideArgs:e});const r=process.argv,n=r.findIndex((e,r)=>r>1&&e===t),a=-1===n?[]:r.slice(n+1),c="--"===a[0],u=c?a.slice(1):a;if(!c&&("--help"===u[0]||"-h"===u[0]))return async function({subcommand:e}){const t=Oc.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 [runId] Auto-fix failing tests using AI"),r(" stably create [prompt] Generate new tests from a prompt or branch diff"),r(""),r("Stably options:"),r(" --env <name> Load environment variables from a remote Stably environment"),r(" --env-file <path> Load environment variables from a local .env file (repeatable)"),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=$c();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:s}=n;if(!s)return void r("Could not determine package manager.");r("Playwright options:"),r("");const[o,...i]=Nc(s),a=jc(s);return new Promise(t=>{const r=g(o,[...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})),f=[];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++:f.push(t)}const m=[t,...d,...f];es.info("[test] Forwarded args computed",{forwardedArgs:m}),es.info("[test] Resolving Stably test environment");const y=Date.now(),b="test"===t?await(async()=>{es.info("[test] Resolving Stably test env");const e=(()=>{if(process.env.STABLY_WS_URL)return;if("https://api.stably.ai"===nn)return;const e=nn.startsWith("http://")?"ws://":"wss://";return`${nn.replace(/^https?:\/\//,e).replace(/\/$/,"")}/reporter`})();es.debug("[test] WebSocket URL resolved",{wsUrl:e??"(default)"});const t=is();if(t)return es.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}};es.info("[test] No env var auth, attempting OAuth auth");const r=Date.now(),n=await(async()=>{const e=is();if(e)return{auth:e,type:"env"};const t=await as(),r=t?await Pn():void 0;return t&&r?{auth:{accessToken:t.accessToken,context:r},type:"oauth"}:void 0})();if(es.info("[test] OAuth auth resolved",{durationMs:Date.now()-r,hasAuth:!!n,authType:n?.type}),!n||"env"===n.type)return void es.info("[test] No usable auth found");const s=process.env.STABLY_PROJECT_ID?.trim(),o=s||ls(n);if(!o)return void es.warn("[test] No project ID available");es.info("[test] Fetching JWT API key",{projectId:o});const i=Date.now(),a=await(async(e,t)=>{try{es.debug("Requesting JWT API key",{projectId:t,apiUrl:nn});const r=await(async({accessToken:e,projectId:t})=>{const r=await(n={auth:e,client:pn(),path:{projectId:t}},(n.client??Zr).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 es.debug("JWT API key obtained",{keyPrefix:r.apiKey.substring(0,10)}),r.apiKey}catch(e){return void es.warn("Failed to get JWT API key for test reporter",{error:e instanceof Error?e.message:String(e)})}})(n.auth.accessToken,o);es.info("[test] JWT API key fetch complete",{durationMs:Date.now()-i,success:!!a});const c=a?{STABLY_API_KEY:a,STABLY_PROJECT_ID:o,...e&&{STABLY_WS_URL:e}}:void 0;return es.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})():void 0;es.info("[test] Stably test environment resolved",{durationMs:Date.now()-y,hasCredentials:null!=b,hasWsUrl:!!b?.STABLY_WS_URL}),es.info("[test] Loading remote environment variables");const w=await fs();es.info("[test] Remote environment loaded",{hasRemoteEnv:!!w,variableCount:w?Object.keys(w.variables).length:0});const v={...w?.variables,...w?.sensitiveValues.length?{STABLY_SENSITIVE_VALUES:Buffer.from(JSON.stringify(w.sensitiveValues)).toString("base64")}:{}};es.info("[test] Setting up Stably reporter injection");const S="test"===t?function({forwardedArgs:e,hasCredentials:t}){if(!t){console.warn("[33mβ οΈ Stably credentials not found. Test results will not be reported to Stably.[0m");const e=rs();if("local"!==e){const t=ss(e);console.warn(`[33m To enable reporting, add the following to your ${t}:[0m`),console.warn("[33m β’ STABLY_API_KEY β https://app.stably.ai/settings?tab=api-key[0m"),console.warn("[33m β’ STABLY_PROJECT_ID β https://app.stably.ai/settings?tab=project-id[0m\n")}else console.warn("[33m To enable reporting, either:[0m"),console.warn("[33m β’ Run `npx stably login` to authenticate[0m"),console.warn("[33m β’ Or set STABLY_API_KEY and STABLY_PROJECT_ID environment variables[0m\n");return}const r=process.cwd(),n=e=>{const t=function(e){let t=s(e);for(;;){if([i(t,"node_modules","@stablyai","playwright-test"),i(t,"node_modules",".pnpm","@stablyai+playwright-test")].some(e=>E(e)))return!0;const e=o(t);if(e===t)return!1;t=e}}(e);return t||(console.warn("[33mβ οΈ @stablyai/playwright-test is not installed. Stably reporter will not be injected.[0m"),console.warn("[33m Install it with: npm install @stablyai/playwright-test[0m"),console.warn("[33m Reference: ]8;;https://docs.stably.ai/getting-started/sdk-setup-guidehttps://docs.stably.ai/getting-started/sdk-setup-guide]8;;[0m\n")),t},a=(e,t)=>{try{return function({baseConfigPath:e,projectDir:t}){const r=function(e){try{const t=h("npm pkg get type",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return"module"===JSON.parse(t.trim())}catch{return!1}}(t),n=r?"mts":"ts",a=o(s(e)),c=l(e),u=i(a,function(e){return"1"===process.env[io]?`${so}-wrapper.config.${e}`:`.stably-playwright-wrapper.config.${e}`}(n)),d=`\n// Auto-generated wrapper config by Stably CLI\n// This file injects the Stably reporter and ensures trace is enabled\nimport baseConfig from './${c}';\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: '${rn}',\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: '${rn}',\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 E(a)||I(a,{recursive:!0}),T(u,d,"utf-8"),function(e,t){const r=i(e,".gitignore");try{if(E(r)){const e=x(r,"utf-8");if(e.split("\n").map(e=>e.trim()).includes(t))return;const n=e.length>0&&!e.endsWith("\n");A(r,`${n?"\n":""}${t}\n`)}else T(r,`${t}\n`)}catch{}}(a,"1"===process.env[io]?oo:".stably-playwright-wrapper.config.*"),u}({baseConfigPath:e,projectDir:t})}catch{return void console.warn("[33mβ οΈ Could not create Stably wrapper config. Reporter injection skipped.[0m")}};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 i=s(r,e[t+1]),c=o(i);if(!n(c))return;const l=a(i,c);if(!l)return;return e[t+1]=l,l}const i=e.findIndex(e=>e.startsWith("--config=")||e.startsWith("-c="));if(-1!==i){const t=s(r,e[i].split("=")[1]),c=o(t);if(!n(c))return;const l=a(t,c);if(!l)return;const u=e[i].startsWith("--config=")?"--config=":"-c=";return e[i]=`${u}${l}`,l}}const c=co(r);if(!c)return;const u=o(c);if(!n(u))return;const d=a(c,u);return d?(e.push("--config",d),d):void 0}({forwardedArgs:m,hasCredentials:null!=b}):void 0;es.info("[test] Reporter injection setup complete",{hasWrapperConfig:!!S}),es.info("[test] Spawning Playwright process");const k=Date.now();if(await function(e,t={}){es.info("[test] Detecting Playwright installation");const r=$c();es.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[s,...o]=Nc(n),i=(a=t.env)?{...process.env,...a}:process.env;var a;const c=[s,...o,...e];es.info("[test] Spawning Playwright process",{command:c.join(" "),pid:process.pid});const l=Date.now(),u=g(s,[...o,...e],{stdio:["inherit","pipe","pipe"],shell:"win32"===process.platform,env:{...i,...process.env.CI?{}:{FORCE_COLOR:"1"}}});es.info("[test] Playwright process spawned",{childPid:u.pid});const d=jc(n),p=function(){let e=!1,t="";return(r,n)=>{if(!e){t+=r,t.length>1024&&(t=t.slice(-1024));for(const r of Bc)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)}}}();u.stdout?.on("data",e=>{d(e,process.stdout)}),u.stderr?.on("data",e=>{const t=e.toString();d(e,process.stderr),p(t,process.stderr)});const f=new AbortController,h=()=>!f.signal.aborted&&(f.abort(),t.onClose?.(),process.removeListener("SIGINT",m),process.removeListener("SIGTERM",m),!0),m=e=>{es.info("[test] Signal received, killing Playwright process",{signal:e,childPid:u.pid}),h(),u.kill(e);const t="SIGINT"===e?130:143;process.exit(t)};return process.on("SIGINT",m),process.on("SIGTERM",m),new Promise((e,t)=>{u.on("error",e=>{h()&&(es.error("[test] Playwright process error",{error:e.message,childPid:u.pid}),t(e))}),u.on("close",t=>{if(!h())return;es.info("[test] Playwright process exited",{exitCode:t,durationMs:Date.now()-l});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)})})})}(m,{env:{...v,...b},onClose:()=>{var e;es.info("[test] Playwright process closed, cleaning up wrapper config"),(e=S)&&E(e)&&_(e)}}),$e.remoteEnvName&&b){const e=await Uc(),t=e&&e.timestamp>=k;if(e&&t){const t=await cs();await(async({authHeader:e,orgId:t,runId:r,envName:n,timeoutMs:s=3e3})=>{es.debug("Tagging run with envName",{runId:r,envName:n});try{let i;const a=new Promise(e=>{i=setTimeout(()=>e("timeout"),s)}),c=await Promise.race([(o={auth:e,client:pn(),headers:hs(t),path:{runId:r},body:{envName:n}},(o.client??Zr).patch({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/metadata",...o,headers:{"Content-Type":"application/json",...o.headers}})),a]);if(clearTimeout(i),"timeout"===c)return void es.warn("Timed out tagging run with envName",{runId:r,envName:n,timeoutMs:s});if(c.error)return void es.warn("Failed to tag run with envName",{runId:r,envName:n,status:c.response?.status});es.debug("Successfully tagged run with envName",{runId:r,envName:n})}catch(e){es.warn("Error tagging run with envName",{runId:r,envName:n,error:e instanceof Error?e.message:String(e)})}var o})({authHeader:us(t),orgId:"oauth"===t.type?t.auth.context.orgId:void 0,runId:e.runId,envName:$e.remoteEnvName})}else e&&!t?es.debug("[test] last-run.json predates this test invocation, skipping envName tagging",{runId:e.runId,fileTimestamp:e.timestamp,testStartTime:k}):es.debug("[test] No last-run.json found, skipping envName tagging")}}function Fc(e){const t=new Date(e),r=new Date,n=r.getTime()-t.getTime(),s=Math.floor(n/1e3),o=Math.floor(s/60),i=Math.floor(o/60),a=Math.floor(i/24);if(s<60)return"just now";if(o<60)return`${o}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 Hc=e=>"oauth"===e.type?e.auth.context.orgId:void 0,Gc=(e,t,r)=>{if(401!==e.response.status&&403!==e.response.status||(le(se.red("Access denied.")),process.exit(1)),404===e.response.status&&r&&(le(se.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";le(se.red(t)),process.exit(1)}e.error&&(le(se.red(`Failed to ${t}: ${e.response.status}`)),process.exit(1))},Wc={PASSED:se.green,FAILED:se.red,TIMEDOUT:se.red,CANCELLED:se.yellow,INTERRUPTED:se.yellow,RUNNING:se.cyan,QUEUED:se.dim},Vc=(e,t)=>e?e.length>t?`${e.slice(0,t-1)}β¦`:e:"-",Yc=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")}`},zc=e=>(Wc[e]??(e=>e))(e),qc=/\x1b\[[0-9;]*m/g,Kc=(e,t)=>{const r=e.replace(qc,"").length,n=Math.max(0,t-r);return e+" ".repeat(n)},Jc=e=>`${JSON.stringify(e,null,2)}\n`,Qc=(e,t,r)=>{if(!e)return;const n=e.toUpperCase();if(t.includes(n))return n;le(se.red(`Invalid ${r} value "${e}". Must be one of: ${t.join(", ").toLowerCase()}`)),process.exit(1)},Xc=/\x1b\[[0-9;]*m/g,Zc=(e,t)=>{const r=e.replace(Xc,"").length,n=Math.max(0,t-r);return e+" ".repeat(n)},el=(e,t)=>e?e.length>t?`${e.slice(0,t-1)}β¦`:e:"-",tl=e=>e?e.split("T")[0]??"-":"-",rl=e=>`${(100*e).toFixed(1)}%`,nl=e=>`${JSON.stringify(e,null,2)}\n`,sl=e=>{if(!e)return;const t=parseInt(e,10);return(Number.isNaN(t)||t<1||t>90)&&(le(se.red("--days must be an integer between 1 and 90")),process.exit(1)),t},ol=e=>{if(!e)return;const t=parseInt(e,10);return(Number.isNaN(t)||t<1||t>100)&&(le(se.red("--limit must be an integer between 1 and 100")),process.exit(1)),t},il="stably",al=`https://registry.npmjs.org/${il}/latest`;function cl(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 ll(e,t){const r=cl(e),n=cl(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 ul=n.join(D.homedir(),".stably"),dl=n.join(ul,"update-check.json"),pl="1"===process.env.STABLY_DISABLE_UPDATE_CHECK,fl=ge.object({lastCheck:ge.number(),latestVersion:ge.string()}),hl=Symbol.for("stably.updateNotifier.registered");function gl(e=""){process.stdout.write(`${e}\n`)}function ml(...e){process.stderr.write(`${e.join(" ")}\n`)}var yl=ge.object({version:ge.string()});var bl=!1,wl=async()=>{if(bl)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{}},vl=e=>{const t=e.toLowerCase();return t.startsWith("npm_config_")||"node_options"===t};!function(){if(pl||function(e=process.argv.slice(2)){return e.includes("upgrade")}())return;const e=function(){try{const e=v.readFileSync(dl,"utf-8");return fl.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 = '${al}';\n const cacheFile = ${JSON.stringify(dl)};\n const cacheDir = ${JSON.stringify(ul)};\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{g(process.execPath,["--input-type=module","-e",e],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()}catch{}}(),null!=e&&ll(rn,e.latestVersion)){if(!0===process[hl])return;process[hl]=!0;let t=!1;const r=()=>{if(t)return;t=!0;const r=`${se.yellow(`update available (${rn} β ${e.latestVersion})`)} - run \`${il} upgrade\` to get the latest version\n`;try{v.writeSync(2,r)}catch{}};process.once("beforeExit",r),process.once("exit",r)}}(),$e.cwdChanged&&es.debug("Changed working directory",{cwd:$e.newCwd});for(const e of $e.envFilesLoaded)es.debug("Loaded env file",{path:e});for(const e of $e.envFileErrors)es.warn(e);var Il=process.argv.findIndex(e=>"-v"===e||"--verbose"===e);-1!==Il&&process.argv.splice(Il,1);var Tl=process.argv.findIndex(e=>"--no-telemetry"===e);-1!==Tl&&process.argv.splice(Tl,1),es.info("CLI starting",{version:rn,args:process.argv.slice(2),cwd:process.cwd()}),process.on("unhandledRejection",(e,t)=>{es.error("Unhandled promise rejection",{reason:e instanceof Error?{message:e.message,stack:e.stack}:e,promise:String(t)}),es.flush(),es.printLogFileInfo()}),process.on("uncaughtException",(e,t)=>{"EPIPE"!==e.code&&(es.error("Uncaught exception",{error:{message:e.message,stack:e.stack,name:e.name},origin:t}),es.flush(),es.printLogFileInfo())});var _l=new u;_l.name("stably").description("AI-assisted Playwright testing CLI").version(rn),_l.enablePositionalOptions();var El=(e,t)=>"cloud"===t.browser||"cloud"===e.parent?.opts().browser||"1"===process.env.STABLY_CLOUD_BROWSER;_l.showHelpAfterError(),_l.exitOverride(),_l.configureHelp({subcommandTerm:e=>{const t=e.registeredArguments.map(e=>e.required?`<${e.name()}>`:`[${e.name()}]`).join(" ");return t?`${e.name()} ${t}`:e.name()}}),_l.addHelpText("after","\nGlobal options (available for all commands):\n -C, --cwd <path> Change working directory before running\n --browser <type> Browser type: local or cloud (default: local)\n --env <name> Load environment variables from a remote Stably environment\n --env-file <path> Load environment variables from a local .env file (repeatable)\n -v, --verbose Enable debug-level logging\n --no-telemetry Disable error telemetry");var Sl=[];_l.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>{Sl.push(e)}});var xl=()=>{const e=_l.helpInformation().trimEnd();return e?`${e}\n`:""},Al=(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},kl=()=>{process.stdout.write(xl())};_l.command("help [command...]").description("Show help for a command (e.g. stably help create)").action(e=>{if(!e||0===e.length)return void kl();const t=Al(_l,e);if(!t)return process.stderr.write(`Unknown command: ${e.join(" ")}\n`),kl(),void(process.exitCode=1);var r;r=t,process.stdout.write((e=>{const t=e.helpInformation().trimEnd();return t?`${t}\n`:""})(r))}),_l.option("--browser <type>","Browser type: local or cloud (default: local)").action((e,t)=>Cc({mode:"chat",getHelpText:xl,cloudBrowser:El(t,e)})),_l.command("login").description("Authenticate with Stably in your browser").action(On),_l.command("logout").description("Clear stored Stably credentials").action(async()=>{const e=is();e&&(ce.warn(`Environment variables ${se.cyan("STABLY_API_KEY")} and ${se.cyan("STABLY_PROJECT_ID")} are set.`),ce.warn("They will continue to be used for authentication even after logout."),ce.warn("Unset them if you want to fully de-authenticate this shell/session."));const t=await xn();if(!t)return void le(e?se.yellow("No stored OAuth login found to clear."):se.yellow("You are not logged in."));const r=ue();r.start("Logging out..."),await(async e=>{try{await fetch(`${on}/api/backend/v1/logout`,{body:JSON.stringify({refresh_token:e}),headers:{"Content-Type":"application/json"},method:"POST"})}catch{}})(t.refreshToken),await kn(),await Cn(),r.stop(se.green("β Logged out")),le(se.green("You have been logged out successfully."))}),_l.command("whoami").description("Show auth status and current project").action(async()=>{ce.info(`${se.bold("CLI Version:")} ${se.cyan(rn)}`);const e=is();if(e){ce.info(se.dim("Authentication: Environment variables")),ce.info(` ${se.bold("API Key:")} ${se.cyan(e.apiKey.slice(0,8))}...`),ce.info(` ${se.bold("Project ID:")} ${se.cyan(e.projectId)}`);const t=await xn();if(t){let e;try{e=bn(t.accessToken).email}catch{e=void 0}ce.warn("Stored OAuth login detected but will be ignored (env auth takes precedence)."),e&&ce.info(` ${se.bold("OAuth Email:")} ${se.cyan(e)}`),ce.info(` ${se.bold("Tip:")} Unset env vars to use OAuth`)}return void le(se.green("Authenticated via environment variables"))}const t=await xn();if(!t)return void le(se.yellow("Not logged in. Run `stably login` to authenticate."));let r;try{r=bn(t.accessToken).email}catch{r=void 0}const s=await Pn();if(!s)return ce.info(se.dim("Authentication: OAuth (not linked to a project)")),r&&ce.info(` ${se.bold("Email:")} ${se.cyan(r)}`),void le(se.yellow("Logged in but this directory is not linked to a project. Run `stably login` to link."));const o=await(async()=>wn(process.cwd(),Tn))(),i=o?n.dirname(o):process.cwd(),a=n.relative(process.cwd(),i)||".";ce.info(se.dim("Authentication: OAuth")),r&&ce.info(` ${se.bold("Email:")} ${se.cyan(r)}`),ce.info(` ${se.bold("Organization:")} ${se.cyan(s.orgName)}`),ce.info(` ${se.bold("Project:")} ${se.cyan(s.projectName)}`),ce.info(` ${se.bold("Linked at:")} ${se.dim(a)}`),le(se.green("Authenticated"))}),_l.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=>{de(`Starting development server for port ${e.port}...`);const t=await cs(),r="oauth"===t.type?`${t.auth.context.orgName}-${t.auth.context.projectName}`.toLowerCase().replace(/[^a-z0-9-]/g,""):`project-${t.auth.projectId}`.toLowerCase(),n=ue();n.start("Starting development server...");const s=await Re(`http://localhost:${e.port}`,{subdomain:r});n.stop(`Your local environment is available at: ]8;;${s.url}${se.underline(se.cyan(s.url))}]8;;`)}),_l.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").option("--browser <type>","Browser type: local or cloud (default: local)").action(async(e,t,r)=>{const n=e.length>0&&"test"===e[0]?e.slice(1):e;return Cc({mode:"single",prompt:n,outputDir:t.output,cloudBrowser:El(r,t)})}).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").option("--browser <type>","Browser type: local or cloud (default: local)").action(async(e,t,r)=>Cc({mode:"single",prompt:e,outputDir:t.output,cloudBrowser:El(r,t)})),_l.command("plan [prompt...]").description("Discover coverage gaps and generate test.fixme() plan files").action(async e=>Cc({mode:"plan",prompt:e??[]})),_l.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").option("--browser <type>","Browser type: local or cloud (default: local)").action(async(e,t,r)=>{if(void 0!==t.maxBudget&&(!Number.isFinite(t.maxBudget)||t.maxBudget<=0))throw new Error("--max-budget must be a positive number");return Cc({mode:"verify",prompt:e,url:t.url,maxBudgetUsd:t.maxBudget,interactive:t.interactive,cloudBrowser:El(r,t)})}),_l.command("internal-fix-run <runId>",{hidden:!0}).description("Internal: run fix session in subprocess").action(async e=>Cc({mode:"fix",runId:e,cloudBrowser:"1"===process.env.STABLY_CLOUD_BROWSER})),_l.command("fix [runId]").description("Fix failing tests from a run (auto-detects from last test run or CI)").option("--browser <type>","Browser type: local or cloud (default: local)").action(async(e,t,r)=>{El(r,t)&&(process.env.STABLY_CLOUD_BROWSER="1"),function(e){try{return h("git rev-parse --is-inside-work-tree",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}(process.cwd())||(es.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 n=await(async e=>{const t=e=>e.replace(/\//g,"_");if(e)return es.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(Ar))if(Ar[r].detect({env:e,cwd:t}))return{isCi:!0,...Ar[r].configuration({env:e,cwd:t})};return{isCi:Boolean(e.CI),...lr({env:e,cwd:t})}})();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 es.debug("Run ID detected from CI environment",{runId:r}),t(r);es.debug("No explicit run ID or CI environment detected, checking last-run.json");const n=await Uc();if(n){const e=(Date.now()-n.timestamp)/36e5;return es.debug("Run ID found in last-run.json",{runId:n.runId,timestamp:n.timestamp,filePath:n.filePath,ageHours:Math.round(e)}),e>24&&es.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)}es.debug("No run ID found in last-run.json")})(e);n||(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 s=await(async e=>{const t=await cs(),r=us(t),n=ls(t),[,s]=process.argv;if(!s)throw new Error("Unable to determine CLI entrypoint for fix subprocess.");return await(async({runId:e,cliEntry:t,stablyApiKey:r,stablyProjectId:n,baseEnv:s=process.env,cwd:o=process.cwd(),execPath:i=process.execPath,execArgv:a=process.execArgv,stdio:c="inherit",spawnImpl:l=({command:e,args:t,options:r})=>g(e,t,r)})=>{const u=(({baseEnv:e,stablyApiKey:t,stablyProjectId:r,playwrightSession:n})=>{const s={...e};for(const e of Object.keys(s))vl(e)&&delete s[e];return{...s,STABLY_API_KEY:t,STABLY_PROJECT_ID:r,...n?{STABLY_PLAYWRIGHT_SESSION:n}:{}}})({baseEnv:s,stablyApiKey:r,stablyProjectId:n});return await new Promise((r,n)=>{const s=l({args:[...a,t,"internal-fix-run",e],command:i,options:{cwd:o,stdio:c,env:u}});s.once("error",n),s.once("exit",(e,t)=>{r(t?1:e??1)})})})({cliEntry:s,runId:e,stablyApiKey:r,stablyProjectId:n,cwd:process.cwd(),stdio:"inherit"})})(n);0!==s&&process.exit(s)}),_l.command("init").description("Initialize Playwright and Stably SDK in your project").action(async()=>Cc({mode:"init"})),_l.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;gl(se.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(al,{signal:e.signal});if(!t.ok)throw new Error(`Failed to fetch latest version: ${t.statusText}`);return yl.parse(await t.json()).version}finally{clearTimeout(t)}}();return{current:rn,latest:e,isOutdated:ll(rn,e)}}()}catch(e){return ml(se.red("Failed to check for updates:"),e instanceof Error?e.message:e),void(process.exitCode=1)}if(gl(`Current version: ${se.yellow(r.current)}`),gl(`Latest version: ${se.green(r.latest)}`),gl(),!r.isOutdated)return void gl(se.green("β You are already on the latest version!"));if(gl(se.yellow(`β A new version is available: ${r.current} β ${r.latest}`)),gl(),t)return gl(se.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=h("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=h("pnpm root -g",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-pnpm"}catch{}try{const t=h("yarn global dir",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-yarn-classic"}catch{}try{const t=h("yarn config get globalFolder",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-yarn-berry"}catch{}return"unknown"}(),s=function(e){switch(e){case"global-npm":case"global-yarn-berry":case"unknown":return{command:"npm",args:["install","-g","--no-fund",`${il}@latest`],description:`npm install -g ${il}@latest`};case"global-pnpm":return{command:"pnpm",args:["add","-g",`${il}@latest`],description:`pnpm add -g ${il}@latest`};case"global-yarn-classic":return{command:"yarn",args:["global","add",`${il}@latest`],description:`yarn global add ${il}@latest`};case"npx":return{command:"npx",args:[`${il}@latest`],description:`npx ${il}@latest (always uses latest)`}}}(n);if("npx"===n)return gl(se.dim("You are running via npx, which always fetches the latest version.")),void gl(se.dim(`Simply run: ${se.white("npx stably")} to use the latest version.`));"unknown"===n?(gl(se.yellow("Could not detect installation method. Falling back to npm.")),gl()):"global-yarn-berry"===n&&(gl(se.yellow("Yarn Berry does not support global packages. Falling back to npm.")),gl()),gl(`Upgrade command: ${se.cyan(s.description)}`),gl(),gl(se.cyan("Upgrading...")),gl();try{await(o=s.command,i=s.args,new Promise((e,t)=>{const r=g(o,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)})})),function(){try{v.unlinkSync(dl)}catch{}}(),gl(),gl(se.green("β Upgrade complete!")),gl(se.dim(`Run ${se.white("stably --version")} to verify.`))}catch(e){ml(se.red("Upgrade failed:"),e instanceof Error?e.message:e),gl(),gl(se.dim("You can try manually running:")),gl(se.cyan(` ${s.description}`)),process.exitCode=1}var o,i}(e));var Pl=_l.command("env").description("Manage remote environments");Pl.command("list").description("List available environments").action(async()=>{const e=await cs(),t=ls(e),r=us(e);es.debug("Listing environments",{projectId:t});const n=await(s={auth:r,client:pn(),path:{projectId:t}},(s.client??Zr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/environments",...s}));var s;401!==n.response.status&&403!==n.response.status||(le(se.red("Access denied.")),process.exit(1)),n.error&&(le(se.red(`Failed to list environments: ${n.response.status}`)),process.exit(1));const{environments:o}=n.data;if(0!==o.length){process.stdout.write(`${se.bold("Environments")}\n\n`);for(const e of o){const t=e.isDefault?se.green(" (default)"):"",r=se.dim(` ${e.variableCount} variable${1!==e.variableCount?"s":""}`);process.stdout.write(` ${se.cyan(e.name)}${t}${r}\n`),e.description&&process.stdout.write(` ${se.dim(e.description)}\n`)}process.stdout.write("\n")}else process.stdout.write(se.dim("No environments found. Create one on your Stably dashboard.\n"))}),Pl.command("inspect <name>").description("Show variable metadata (name, sensitive flag, updated timestamp)").action(e=>(async e=>{const t=await cs(),r=ls(t),n=us(t);es.debug("Inspecting environment",{name:e,projectId:r});const s=await(o={auth:n,client:pn(),path:{projectId:r,environmentName:e}},(o.client??Zr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/environments/{environmentName}/inspect",...o}));var o;404===s.response.status&&(le(se.red(`Environment "${e}" not found. Run ${se.bold("stably env list")} to see available environments.`)),process.exit(1)),401!==s.response.status&&403!==s.response.status||(le(se.red("Access denied.")),process.exit(1)),s.error&&(le(se.red(`Failed to inspect environment: ${s.response.status}`)),process.exit(1));const{variables:i}=s.data;if(0!==i.length){process.stdout.write(`${se.bold(e)} ${se.dim(`(${i.length} variable${1!==i.length?"s":""})`)}\n\n`);for(const e of i){const t=se.dim(` [updated ${Fc(e.updatedAt)}]`);e.sensitive?process.stdout.write(` ${se.cyan(e.name)} ${se.yellow("[sensitive]")}${t}\n`):process.stdout.write(` ${se.cyan(e.name)}${t}\n`)}process.stdout.write("\n")}else process.stdout.write(se.dim(`Environment "${e}" has no variables.\n`))})(e));var Cl=_l.command("analytics").description("View test health analytics");Cl.command("flaky").description("Show most flaky tests ranked by flaky rate").option("--days <n>","Look-back window in days (1-90, default: 7)").option("-b, --branch <name>","Filter by branch name").option("-n, --limit <n>","Max rows returned (1-100, default: 10)").option("--json","Output as JSON").action(async e=>{const t=await cs(),r=ls(t),n=us(t),s=Hc(t),o=sl(e.days),i=ol(e.limit);es.debug("Listing flaky tests",{projectId:r,days:o,branch:e.branch,limit:i});const a=pn(),c=await a.get({url:"/internal/v1/cli/analytics/flaky",security:[{scheme:"bearer",type:"http"}],auth:n,headers:{...hs(s)},query:{projectId:r,days:o,branchName:e.branch,limit:i}});Gc(c,"list flaky tests");const l=c.data;e.json?process.stdout.write(nl(l)):process.stdout.write(((e,t)=>{const r=[],n=e.filters.branch?`branch: ${e.filters.branch}`:"all branches";if(r.push(se.bold(`Most Flaky Tests (last ${e.period.days} days, ${n})`)),r.push(""),0===e.tests.length)return r.push(se.dim(" No flaky tests found.")),r.push(""),r.join("\n");const s=` ${Zc("REF",14)}${Zc("TEST",20)}${Zc("LOCATION",30)}${Zc("FLAKY",8)}${Zc("RUNS",7)}${Zc("RATE",9)}LAST FLAKY`;r.push(se.dim(s));for(const t of e.tests){const e=t.testRef,n=el(t.title,18),s=el(t.location,28),o=String(t.flakyCount),i=String(t.nonSkippedRuns),a=rl(t.flakyRate),c=tl(t.lastFlakyAt);r.push(` ${Zc(e,14)}${Zc(n,20)}${Zc(s,30)}${Zc(o,8)}${Zc(i,7)}${Zc(a,9)}${c}`)}r.push("");const o=e.summary.totalNonSkippedRuns;return r.push(` ${e.summary.totalFlakyTests} flaky tests found across ${o} runs.`),r.push(` Dashboard: ${se.cyan(se.underline(`https://app.stably.ai/p/${t}/analytics`))}`),r.push(""),r.join("\n")})(l,r))}),Cl.command("failures").description("Show most failing tests ranked by failure rate").option("--days <n>","Look-back window in days (1-90, default: 7)").option("-b, --branch <name>","Filter by branch name").option("-n, --limit <n>","Max rows returned (1-100, default: 10)").option("--json","Output as JSON").action(async e=>{const t=await cs(),r=ls(t),n=us(t),s=Hc(t),o=sl(e.days),i=ol(e.limit);es.debug("Listing failing tests",{projectId:r,days:o,branch:e.branch,limit:i});const a=pn(),c=await a.get({url:"/internal/v1/cli/analytics/failures",security:[{scheme:"bearer",type:"http"}],auth:n,headers:{...hs(s)},query:{projectId:r,days:o,branchName:e.branch,limit:i}});Gc(c,"list failing tests");const l=c.data;e.json?process.stdout.write(nl(l)):process.stdout.write(((e,t)=>{const r=[],n=e.filters.branch?`branch: ${e.filters.branch}`:"all branches";if(r.push(se.bold(`Most Failed Tests (last ${e.period.days} days, ${n})`)),r.push(""),0===e.tests.length)return r.push(se.dim(" No failing tests found.")),r.push(""),r.join("\n");const s=` ${Zc("REF",14)}${Zc("TEST",20)}${Zc("LOCATION",30)}${Zc("FAILED",8)}${Zc("RUNS",7)}${Zc("RATE",9)}LAST FAILED`;r.push(se.dim(s));for(const t of e.tests){const e=t.testRef,n=el(t.title,18),s=el(t.location,28),o=String(t.failedCount),i=String(t.nonSkippedRuns),a=rl(t.failureRate),c=tl(t.lastFailedAt);r.push(` ${Zc(e,14)}${Zc(n,20)}${Zc(s,30)}${Zc(o,8)}${Zc(i,7)}${Zc(a,9)}${c}`)}r.push("");const o=e.summary.totalNonSkippedRuns;return r.push(` ${e.summary.totalFailingTests} failing tests found across ${o} runs.`),r.push(` Dashboard: ${se.cyan(se.underline(`https://app.stably.ai/p/${t}/analytics`))}`),r.push(""),r.join("\n")})(l,r))});var Rl=_l.command("runs").description("View test run history");Rl.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 cs(),r=ls(t),n=us(t),s=Hc(t);let o;e.limit&&(o=parseInt(e.limit,10),(Number.isNaN(o)||o<1||o>100)&&(le(se.red("--limit must be an integer between 1 and 100")),process.exit(1)));const i=Qc(e.source,["LOCAL","CI","WEB"],"--source"),a=Qc(e.status,["QUEUED","RUNNING","PASSED","FAILED","TIMEDOUT","CANCELLED","INTERRUPTED"],"--status"),c=Qc(e.trigger,["MANUAL","SCHEDULED","UI","API","GITHUB_ACTION","SUITE_RUN"],"--trigger");es.debug("Listing runs",{projectId:r,branch:e.branch,limit:o,after:e.after,before:e.before,source:i,status:a,suite:e.suite,trigger:c});const l=await en({auth:n,client:pn(),headers:hs(s),query:{projectId:r,branchName:e.branch,limit:o,afterRunId:e.after,beforeRunId:e.before,source:i,status:a,suiteName:e.suite,trigger:c}});Gc(l,"list runs");const{runs:u,hasMore:d}=l.data;e.json?process.stdout.write(Jc(l.data)):process.stdout.write(((e,t)=>{if(0===e.length)return se.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}},s=[],o=`${Kc("Run ID",n.runId.w)}${Kc("Status",n.status.w)}${Kc("Branch",n.branch.w)}${Kc("Started",n.started.w)}Tests`;s.push(se.bold(o));for(const t of e){const e=Vc(t.runId,n.runId.t),r=zc(t.status),o=Vc(t.branchName,n.branch.t),i=Yc(t.startedAt),a=t.totalCount.toString();s.push(`${Kc(e,n.runId.w)}${Kc(r,n.status.w)}${Kc(o,n.branch.w)}${Kc(i,n.started.w)}${a}`)}if(t&&e.length>0){const t=e.at(-1)?.runId;t&&(s.push(""),s.push(se.dim(`Next page: stably runs list --before ${t}`)))}return s.push(""),s.join("\n")})(u,d))}),Rl.command("view <runId>").description("Show details for a specific run").option("--json","Output as JSON").action(async(e,t)=>{const r=await cs(),n=us(r),s=Hc(r);es.debug("Viewing run",{runId:e});const o=await tn({auth:n,client:pn(),headers:hs(s),path:{runId:e},query:{detail:"full"}});if(Gc(o,"get run details",`Run "${e}" not found.`),t.json)process.stdout.write(Jc(o.data));else{const e=o.data;process.stdout.write((e=>{const t=[];if(t.push(se.bold(`Run ${e.runId}`)),t.push(` ${se.dim("Status:")} ${zc(e.status)}`),e.branchName&&t.push(` ${se.dim("Branch:")} ${e.branchName}`),e.commitSha&&t.push(` ${se.dim("Commit:")} ${e.commitSha.slice(0,7)}`),e.startedAt&&t.push(` ${se.dim("Started:")} ${Yc(e.startedAt)}`),null!==e.durationMs&&t.push(` ${se.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(` ${se.dim("Source:")} ${e.source.toLowerCase()}`),e.projectId){const r=`https://app.stably.ai/project/${e.projectId}/playwright/history/${e.runId}`;t.push(` ${se.dim("URL:")} ${se.cyan(se.underline(r))}`)}t.push("");const r=[];e.passedCount>0&&r.push(se.green(`${e.passedCount} passed`)),e.failedCount>0&&r.push(se.red(`${e.failedCount} failed`)),e.flakyCount>0&&r.push(se.yellow(`${e.flakyCount} flaky`)),e.timedoutCount>0&&r.push(se.red(`${e.timedoutCount} timedout`)),e.skippedCount>0&&r.push(se.dim(`${e.skippedCount} skipped`)),e.interruptedCount>0&&r.push(se.yellow(`${e.interruptedCount} interrupted`)),t.push(`${se.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(se.bold("Failed/Flaky Tests:"));for(const e of n){const r=e.status??"UNKNOWN",n=Wc[r]??(e=>e),s=e.location??"",o=e.title??e.testIdentifier,{attempts:i}=e,a=i?.length??0,c=a>1?` (${a} attempts)`:"",l=s?`${s} - `:"";t.push(` ${n(r)} ${l}${o}${se.dim(c)}`);const u=i?.at(-1);if(u?.errorMessage){const e=u.errorMessage.split("\n")[0]?.slice(0,100)??"";t.push(` ${se.dim(e)}`)}}}return t.push(""),t.join("\n")})(e))}}),_l.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)}),Oc.forEach(({args:e,description:t,name:r})=>{_l.command(r).description(t).helpOption(!1).helpCommand(!1).allowUnknownOption(!0).allowExcessArguments(!0).passThroughOptions().action(()=>Mc({overrideArgs:e,subcommand:r}))});var Ul=()=>{0!==Sl.length&&(process.stderr.write(Sl.join("")),Sl=[])};(async()=>{await(async()=>{if(!bl&&"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":rn,"node.version":process.version,"os.platform":process.platform}}),bl=!0}catch{}})();try{await _l.parseAsync(process.argv),es.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 es.error(t,{stack:e instanceof Error?e.stack:void 0}),Ul(),es.flush(),es.printLogFileInfo(),await wl(),void(process.exitCode=1)}const t="number"==typeof e.exitCode?e.exitCode:1,r=process.argv.slice(2).find(e=>!e.startsWith("-")),n=!!r&&!!Al(_l,[r]);if(("commander.excessArguments"===e.code||"commander.unknownCommand"===e.code)&&r&&!n)return Sl=[],es.warn("Unknown command",{command:r}),process.stderr.write(`command '${r}' not found\n`),kl(),void(process.exitCode=t);es.debug("Commander error",{code:e.code,exitCode:t}),Ul(),process.exitCode=t}finally{es.flush(),await wl()}})();
|
|
2
|
+
import{config as e,parse as t}from"dotenv";import*as n from"path";import r,{resolve as s,dirname as o,join as i,sep as a,normalize as c,basename as l}from"path";import{Command as u}from"commander";import{Buffer as d}from"buffer";import p,{exec as f,execSync as h,spawn as g,execFile as m,execFileSync as y}from"child_process";import b from"process";import*as w from"fs";import v,{mkdirSync as I,writeFileSync as T,rmSync as _,existsSync as E,statSync as S,readFileSync as x,appendFileSync as A,realpathSync as k,createReadStream as C,openSync as P,readSync as R,closeSync as U}from"fs";import{fileURLToPath as $,URL as L}from"url";import D,{tmpdir as N,constants as O}from"os";import"timers/promises";import B from"stream";import{debuglog as j,promisify as M,TextDecoder as F,TextEncoder as H}from"util";import{createSdkMcpServer as G,tool as W,query as V}from"@anthropic-ai/claude-agent-sdk";import{rm as Y,readFile as z,mkdir as q,writeFile as K,unlink as J,access as X,readdir as Q,stat as Z,appendFile as ee}from"fs/promises";import te from"net";import{createInterface as ne}from"readline/promises";import re from"picocolors";import{simpleGit as se}from"simple-git";import oe,{randomUUID as ie}from"crypto";import{log as ae,outro as ce,spinner as le,intro as ue,select as de,isCancel as pe}from"@clack/prompts";import fe,{z as he}from"zod";import ge from"open";import me from"http";import ye from"pino";import be from"sonic-boom";import{z as we}from"zod/v3";import ve from"ws";import{useState as Ie,useRef as Te,useEffect as _e,useCallback as Ee,useMemo as Se}from"react";import{jsx as xe,jsxs as Ae}from"react/jsx-runtime";import{createRequire as ke}from"module";import{parseDocument as Ce}from"yaml";import{startTunnel as Pe}from"@stablyhq/runner-sdk";var Re=(e=>"undefined"!=typeof require?require:"undefined"!=typeof Proxy?new Proxy(e,{get:(e,t)=>("undefined"!=typeof require?require:e)[t]}):e)(function(e){if("undefined"!=typeof require)return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),Ue={cwdChanged:!1,newCwd:void 0,envFilesLoaded:[],envFileErrors:[],remoteEnvName:void 0},$e=process.argv.findIndex(e=>"-C"===e||"--cwd"===e);if(-1!==$e&&process.argv[$e+1]){const e=process.argv[$e+1];process.chdir(e),Ue.cwdChanged=!0,Ue.newCwd=e,process.argv.splice($e,2)}for(var Le=[],De=0;De<process.argv.length;)if("--env-file"===process.argv[De]){const e=process.argv[De+1];e&&!e.startsWith("-")?(Le.push(e),process.argv.splice(De,2)):De++}else De++;var Ne=process.argv.findIndex(e=>"--env"===e);-1!==Ne&&process.argv[Ne+1]&&!process.argv[Ne+1].startsWith("-")&&(Ue.remoteEnvName=process.argv[Ne+1],process.argv.splice(Ne,2));for(const t of[...Le].reverse()){const n=r.resolve(process.cwd(),t),s=e({path:n,override:!1,quiet:!0});if(s.error){const e=`warning: could not load env file: ${n} (${s.error.message})`;Ue.envFileErrors.push(e),process.stderr.write(`${e}\n`)}else Ue.envFilesLoaded.unshift(n)}var Oe={detect:({env:e})=>Boolean(e.APPVEYOR),configuration({env:e}){const t=e.APPVEYOR_PULL_REQUEST_NUMBER,n=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:n,prBranch:e.APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH,slug:e.APPVEYOR_REPO_NAME,root:e.APPVEYOR_BUILD_FOLDER}}};function Be(e){return(/\d+(?!.*\d+)/.exec(e)||[])[0]}function je(e){return e?/^(?:refs\/heads\/)?(?<branch>.+)$/i.exec(e)[1]:void 0}var Me={detect:({env:e})=>Boolean(e.BUILD_BUILDURI),configuration({env:e}){const t=e.SYSTEM_PULLREQUEST_PULLREQUESTID,n=Boolean(t);return{name:"Azure Pipelines",service:"azurePipelines",commit:e.BUILD_SOURCEVERSION,build:e.BUILD_BUILDNUMBER,branch:je(n?e.SYSTEM_PULLREQUEST_TARGETBRANCH:e.BUILD_SOURCEBRANCH),pr:t,isPr:n,prBranch:je(n?e.SYSTEM_PULLREQUEST_SOURCEBRANCH:void 0),root:e.BUILD_REPOSITORY_LOCALPATH}}},Fe={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})},He={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})},Ge={detect:({env:e})=>Boolean(e.BITRISE_IO),configuration({env:e}){const t="false"===e.BITRISE_PULL_REQUEST?void 0:e.BITRISE_PULL_REQUEST,n=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:n?e.BITRISEIO_GIT_BRANCH_DEST:e.BITRISE_GIT_BRANCH,pr:t,isPr:n,prBranch:n?e.BITRISE_GIT_BRANCH:void 0,slug:e.BITRISE_APP_SLUG}}},We={detect:({env:e})=>Boolean(e.BUDDY_WORKSPACE_ID),configuration({env:e}){const t=Be(e.BUDDY_EXECUTION_PULL_REQUEST_ID),n=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:n?e.BUDDY_EXECUTION_PULL_REQUEST_HEAD_BRANCH:e.BUDDY_EXECUTION_BRANCH,pr:t,isPr:n,slug:e.BUDDY_REPO_SLUG}}},Ve="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Ye(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ze,qe,Ke,Je,Xe,Qe,Ze,et,tt={exports:{}};var nt,rt,st,ot,it,at,ct,lt,ut,dt,pt,ft,ht,gt,mt,yt={exports:{}},bt={};function wt(){if(ft)return pt;ft=1;const e=r,t=function(){if(st)return rt;st=1;const e=r,t=function(){if(et)return Ze;et=1;const e="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,t=r,n=e?";":":",s=function(){if(Qe)return Xe;var e;function t(n,r,s){if("function"==typeof r&&(s=r,r={}),!s){if("function"!=typeof Promise)throw new TypeError("callback not provided");return new Promise(function(e,s){t(n,r||{},function(t,n){t?s(t):e(n)})})}e(n,r||{},function(e,t){e&&("EACCES"===e.code||r&&r.ignoreErrors)&&(e=null,t=!1),s(e,t)})}return Qe=1,e="win32"===process.platform||Ve.TESTING_WINDOWS?function(){if(qe)return ze;qe=1,ze=n,n.sync=function(n,r){return t(e.statSync(n),n,r)};var e=v;function t(e,t,n){return!(!e.isSymbolicLink()&&!e.isFile())&&function(e,t){var n=void 0!==t.pathExt?t.pathExt:process.env.PATHEXT;if(!n)return!0;if(-1!==(n=n.split(";")).indexOf(""))return!0;for(var r=0;r<n.length;r++){var s=n[r].toLowerCase();if(s&&e.substr(-s.length).toLowerCase()===s)return!0}return!1}(t,n)}function n(n,r,s){e.stat(n,function(e,o){s(e,!e&&t(o,n,r))})}return ze}():function(){if(Je)return Ke;Je=1,Ke=t,t.sync=function(t,r){return n(e.statSync(t),r)};var e=v;function t(t,r,s){e.stat(t,function(e,t){s(e,!e&&n(t,r))})}function n(e,t){return e.isFile()&&function(e,t){var n=e.mode,r=e.uid,s=e.gid,o=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 n&parseInt("001",8)||n&c&&s===i||n&a&&r===o||n&(a|c)&&0===o}(e,t)}return Ke}(),Xe=t,t.sync=function(t,n){try{return e.sync(t,n||{})}catch(e){if(n&&n.ignoreErrors||"EACCES"===e.code)return!1;throw e}},Xe}(),o=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),i=(t,r)=>{const s=r.colon||n,o=t.match(/\//)||e&&t.match(/\\/)?[""]:[...e?[process.cwd()]:[],...(r.path||process.env.PATH||"").split(s)],i=e?r.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",a=e?i.split(s):[""];return e&&-1!==t.indexOf(".")&&""!==a[0]&&a.unshift(""),{pathEnv:o,pathExt:a,pathExtExe:i}},a=(e,n,r)=>{"function"==typeof n&&(r=n,n={}),n||(n={});const{pathEnv:a,pathExt:c,pathExtExe:l}=i(e,n),u=[],d=r=>new Promise((s,i)=>{if(r===a.length)return n.all&&u.length?s(u):i(o(e));const c=a[r],l=/^".*"$/.test(c)?c.slice(1,-1):c,d=t.join(l,e),f=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d;s(p(f,r,0))}),p=(e,t,r)=>new Promise((o,i)=>{if(r===c.length)return o(d(t+1));const a=c[r];s(e+a,{pathExt:l},(s,i)=>{if(!s&&i){if(!n.all)return o(e+a);u.push(e+a)}return o(p(e,t,r+1))})});return r?d(0).then(e=>r(null,e),r):d(0)};return Ze=a,a.sync=(e,n)=>{n=n||{};const{pathEnv:r,pathExt:a,pathExtExe:c}=i(e,n),l=[];for(let o=0;o<r.length;o++){const i=r[o],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(s.sync(t,{pathExt:c})){if(!n.all)return t;l.push(t)}}catch(e){}}}if(n.all&&l.length)return l;if(n.nothrow)return null;throw o(e)},Ze}(),n=function(){if(nt)return yt.exports;nt=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 yt.exports=e,yt.exports.default=e,yt.exports}();function s(r,s){const o=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:o[n({env:o})],pathExt:s?e.delimiter:void 0})}catch(e){}finally{c&&process.chdir(i)}return l&&(l=e.resolve(a?r.options.cwd:"",l)),l}return rt=function(e){return s(e)||s(e,!0)}}(),n=function(){if(ot)return bt;ot=1;const e=/([()\][%!^"`<>&|;, *?])/g;return bt.command=function(t){return t.replace(e,"^$1")},bt.argument=function(t,n){return t=(t=`"${t=(t=(t=`${t}`).replace(/(?=(\\+?)?)\1"/g,'$1$1\\"')).replace(/(?=(\\+?)?)\1$/,"$1$1")}"`).replace(e,"^$1"),n&&(t=t.replace(e,"^$1")),t},bt}(),s=function(){if(dt)return ut;dt=1;const e=v,t=function(){if(lt)return ct;lt=1;const e=at?it:(at=1,it=/^#!(.*)/);return ct=(t="")=>{const n=t.match(e);if(!n)return null;const[r,s]=n[0].replace(/#! ?/,"").split(" "),o=r.split("/").pop();return"env"===o?s:s?`${o} ${s}`:o}}();return ut=function(n){const r=Buffer.alloc(150);let s;try{s=e.openSync(n,"r"),e.readSync(s,r,0,150,0),e.closeSync(s)}catch(e){}return t(r.toString())}}(),o="win32"===process.platform,i=/\.(?:com|exe)$/i,a=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;return pt=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(!o)return r;const c=function(e){e.file=t(e);const n=e.file&&s(e.file);return n?(e.args.unshift(e.file),e.command=n,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 s=[r.command].concat(r.args).join(" ");r.args=["/d","/s","/c",`"${s}"`],r.command=process.env.comspec||"cmd.exe",r.options.windowsVerbatimArguments=!0}return r}(u)}}var vt=Ye(function(){if(mt)return tt.exports;mt=1;const e=p,t=wt(),n=function(){if(gt)return ht;gt=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 n(n,r){return e&&1===n&&!r.file?t(r.original,"spawn"):null}return ht={hookChildProcess:function(t,r){if(!e)return;const s=t.emit;t.emit=function(e,o){if("exit"===e){const e=n(o,r);if(e)return s.call(t,"error",e)}return s.apply(t,arguments)}},verifyENOENT:n,verifyENOENTSync:function(n,r){return e&&1===n&&!r.file?t(r.original,"spawnSync"):null},notFoundError:t},ht}();function r(r,s,o){const i=t(r,s,o),a=e.spawn(i.command,i.args,i.options);return n.hookChildProcess(a,i),a}return tt.exports=r,tt.exports.spawn=r,tt.exports.sync=function(r,s,o){const i=t(r,s,o),a=e.spawnSync(i.command,i.args,i.options);return a.error=a.error||n.verifyENOENTSync(a.status,i),a},tt.exports._parse=t,tt.exports._enoent=n,tt.exports}());function It(e={}){const{env:t=process.env,platform:n=process.platform}=e;return"win32"!==n?"PATH":Object.keys(t).reverse().find(e=>"PATH"===e.toUpperCase())||"Path"}var Tt=(e,t)=>({name:`SIGRT${t+1}`,number:_t+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),_t=34,Et=[{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"}],St=()=>{const e=(()=>{const e=64-_t+1;return Array.from({length:e},Tt)})();return[...Et,...e].map(xt)},xt=({name:e,number:t,description:n,action:r,forced:s=!1,standard:o})=>{const{signals:{[e]:i}}=O,a=void 0!==i;return{name:e,number:a?i:t,description:n,supported:a,action:r,forced:s,standard:o}},At=({name:e,number:t,description:n,supported:r,action:s,forced:o,standard:i})=>[e,{name:e,number:t,description:n,supported:r,action:s,forced:o,standard:i}],kt=(()=>{const e=St();return Object.fromEntries(e.map(At))})();(()=>{const e=St(),t=Array.from({length:65},(t,n)=>((e,t)=>{const n=((e,t)=>{const n=t.find(({name:t})=>O.signals[t]===e);return void 0!==n?n:t.find(t=>t.number===e)})(e,t);if(void 0===n)return{};const{name:r,description:s,supported:o,action:i,forced:a,standard:c}=n;return{[e]:{name:r,number:e,description:s,supported:o,action:i,forced:a,standard:c}}})(n,e));Object.assign({},...t)})();var Ct=({stdout:e,stderr:t,all:n,error:r,signal:s,exitCode:o,command:i,escapedCommand:a,timedOut:c,isCanceled:l,killed:u,parsed:{options:{timeout:d,cwd:p=b.cwd()}}})=>{o=null===o?void 0:o;const f=void 0===(s=null===s?void 0:s)?void 0:kt[s].description,h=(({timedOut:e,timeout:t,errorCode:n,signal:r,signalDescription:s,exitCode:o,isCanceled:i})=>e?`timed out after ${t} milliseconds`:void 0!==n?`failed with ${n}`:void 0!==r?`was killed with ${r} (${s})`:void 0!==o?`failed with exit code ${o}`:"failed")({timedOut:c,timeout:d,errorCode:r&&r.code,signal:s,signalDescription:f,exitCode:o,isCanceled:l}),g=`Command ${h}: ${i}`,m="[object Error]"===Object.prototype.toString.call(r),y=m?`${g}\n${r.message}`:g,w=[y,t,e].filter(Boolean).join("\n");return m?(r.originalMessage=r.message,r.message=w):r=new Error(w),r.shortMessage=y,r.command=i,r.escapedCommand=a,r.exitCode=o,r.signal=s,r.signalDescription=f,r.stdout=e,r.stderr=t,r.cwd=p,void 0!==n&&(r.all=n),"bufferedData"in r&&delete r.bufferedData,r.failed=!0,r.timedOut=Boolean(c),r.isCanceled=l,r.killed=u&&!c,r},Pt=["stdin","stdout","stderr"],Rt=[];Rt.push("SIGHUP","SIGINT","SIGTERM"),"win32"!==process.platform&&Rt.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),"linux"===process.platform&&Rt.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var Ut,$t,Lt=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,Dt=Symbol.for("signal-exit emitter"),Nt=globalThis,Ot=Object.defineProperty.bind(Object),Bt=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(Nt[Dt])return Nt[Dt];Ot(Nt,Dt,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,t){this.listeners[e].push(t)}removeListener(e,t){const n=this.listeners[e],r=n.indexOf(t);-1!==r&&(0===r&&1===n.length?n.length=0:n.splice(r,1))}emit(e,t,n){if(this.emitted[e])return!1;this.emitted[e]=!0;let r=!1;for(const s of this.listeners[e])r=!0===s(t,n)||r;return"exit"===e&&(r=this.emit("afterExit",t,n)||r),r}},jt=class{},Mt=globalThis.process;Lt(Mt)?new class extends jt{#e="win32"===Mt.platform?"SIGINT":"SIGHUP";#t=new Bt;#n;#r;#s;#o={};#i=!1;constructor(e){super(),this.#n=e,this.#o={};for(const t of Rt)this.#o[t]=()=>{const n=this.#n.listeners(t);let{count:r}=this.#t;const s=e;if("object"==typeof s.__signal_exit_emitter__&&"number"==typeof s.__signal_exit_emitter__.count&&(r+=s.__signal_exit_emitter__.count),n.length===r){this.unload();const n=this.#t.emit("exit",null,t),r="SIGHUP"===t?this.#e:t;n||e.kill(e.pid,r)}};this.#s=e.reallyExit,this.#r=e.emit}onExit(e,t){if(!Lt(this.#n))return()=>{};!1===this.#i&&this.load();const n=t?.alwaysLast?"afterExit":"exit";return this.#t.on(n,e),()=>{this.#t.removeListener(n,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 Rt)try{const t=this.#o[e];t&&this.#n.on(e,t)}catch(e){}this.#n.emit=(e,...t)=>this.#a(e,...t),this.#n.reallyExit=e=>this.#c(e)}}unload(){this.#i&&(this.#i=!1,Rt.forEach(e=>{const t=this.#o[e];if(!t)throw new Error("Listener not defined for signal: "+e);try{this.#n.removeListener(e,t)}catch(e){}}),this.#n.emit=this.#r,this.#n.reallyExit=this.#s,this.#t.count-=1)}#c(e){return Lt(this.#n)?(this.#n.exitCode=e||0,this.#t.emit("exit",this.#n.exitCode,null),this.#s.call(this.#n,this.#n.exitCode)):0}#a(e,...t){const n=this.#r;if("exit"===e&&Lt(this.#n)){"number"==typeof t[0]&&(this.#n.exitCode=t[0]);const r=n.call(this.#n,e,...t);return this.#t.emit("exit",this.#n.exitCode,null),r}return n.call(this.#n,e,...t)}}(Mt):new class extends jt{onExit(){return()=>{}}load(){}unload(){}},new TextEncoder,function(){if($t)return Ut;$t=1;const{PassThrough:e}=B;Ut=function(){var t=[],n=new e({objectMode:!0});return n.setMaxListeners(0),n.add=r,n.isEmpty=function(){return 0==t.length},n.on("unpipe",s),Array.prototype.slice.call(arguments).forEach(r),n;function r(e){return Array.isArray(e)?(e.forEach(r),this):(t.push(e),e.once("end",s.bind(null,e)),e.once("error",n.emit.bind(n,"error")),e.pipe(n,{end:!1}),this)}function s(e){!(t=t.filter(function(t){return t!==e})).length&&n.readable&&n.end()}}}();var Ft=(async()=>{})().constructor.prototype;["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(Ft,e)]);var Ht=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],Gt=/^[\w.-]+$/,Wt=j("execa").enabled,Vt=(e,t)=>String(e).padStart(t,"0"),Yt=(e,t,n={})=>{const s=vt._parse(e,t,n);return e=s.command,t=s.args,(n={maxBuffer:1e8,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:(n=s.options).cwd||b.cwd(),execPath:b.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:Wt,...n}).env=(({env:e,extendEnv:t,preferLocal:n,localDir:s,execPath:o})=>{const i=t?{...b.env,...e}:e;return n?(({env:e=b.env,...t}={})=>{const n=It({env:e={...e}});return t.path=e[n],e[n]=(({cwd:e=b.cwd(),path:t=b.env[It()],preferLocal:n=!0,execPath:s=b.execPath,addExecPath:o=!0}={})=>{const i=e instanceof URL?$(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),o&&((e,t,n)=>{const s=t instanceof URL?$(t):t;e.push(r.resolve(n,s,".."))})(c,s,a),[...c,t].join(r.delimiter)})(t),e})({env:i,cwd:s,execPath:o}):i})(n),n.stdio=(e=>{if(!e)return;const{stdio:t}=e;if(void 0===t)return Pt.map(t=>e[t]);if((e=>Pt.some(t=>void 0!==e[t]))(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${Pt.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 n=Math.max(t.length,Pt.length);return Array.from({length:n},(e,n)=>t[n])})(n),"win32"===b.platform&&"cmd"===r.basename(e,".exe")&&t.unshift("/q"),{file:e,args:t,options:n,parsed:s}},zt=(e,t,n)=>"string"==typeof t||d.isBuffer(t)?e.stripFinalNewline?function(e){const t="string"==typeof e?"\n":"\n".charCodeAt(),n="string"==typeof e?"\r":"\r".charCodeAt();return e[e.length-1]===t&&(e=e.slice(0,-1)),e[e.length-1]===n&&(e=e.slice(0,-1)),e}(t):t:void 0===n?void 0:"";function qt(e,t,n){const r=Yt(e,t,n),s=((e,t)=>Ht(e,t).join(" "))(e,t),o=((e,t)=>Ht(e,t).map(e=>(e=>"string"!=typeof e||Gt.test(e)?e:`"${e.replaceAll('"','\\"')}"`)(e)).join(" "))(e,t);((e,{verbose:t})=>{t&&b.stderr.write(`[${(()=>{const e=new Date;return`${Vt(e.getHours(),2)}:${Vt(e.getMinutes(),2)}:${Vt(e.getSeconds(),2)}.${Vt(e.getMilliseconds(),3)}`})()}] ${e}\n`)})(o,r.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),x(t)))(e);if(null!==(n=t)&&"object"==typeof n&&"function"==typeof n.pipe)throw new TypeError("The `input` option cannot be a stream in sync mode");var n;return t})(r.options);let a;try{a=p.spawnSync(r.file,r.args,{...r.options,input:i})}catch(e){throw Ct({error:e,stdout:"",stderr:"",all:"",command:s,escapedCommand:o,parsed:r,timedOut:!1,isCanceled:!1,killed:!1})}const c=zt(r.options,a.stdout,a.error),l=zt(r.options,a.stderr,a.error);if(a.error||0!==a.status||null!==a.signal){const e=Ct({stdout:c,stderr:l,error:a.error,signal:a.signal,exitCode:a.status,command:s,escapedCommand:o,parsed:r,timedOut:a.error&&"ETIMEDOUT"===a.error.code,isCanceled:!1,killed:null!==a.signal});if(!r.options.reject)return e;throw e}return{command:s,escapedCommand:o,exitCode:0,stdout:c,stderr:l,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}}function Kt(e){try{return qt("git",["rev-parse","HEAD"],e).stdout}catch{return}}function Jt(e){try{const t=qt("git",["rev-parse","--abbrev-ref","HEAD"],e).stdout;if("HEAD"===t){const t=qt("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 Xt=/^(?:.*)@(?:.*):(?:\d+\/)?(.*)\.git$/,Qt=/^\/(.*)\.git$/;function Zt(e){if(e){if(e.match(Xt))return e.replace(Xt,"$1");try{return new URL(e).pathname.replace(Qt,"$1")}catch{return}}}var en,tn={detect:({env:e})=>Boolean(e.BUILDKITE),configuration({env:e}){const t="false"===e.BUILDKITE_PULL_REQUEST?void 0:e.BUILDKITE_PULL_REQUEST,n=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:n?e.BUILDKITE_PULL_REQUEST_BASE_BRANCH:e.BUILDKITE_BRANCH,slug:Zt(e.BUILDKITE_REPO),pr:t,isPr:n,prBranch:n?e.BUILDKITE_BRANCH:void 0,root:e.BUILDKITE_BUILD_CHECKOUT_PATH}}},nn={detect:({env:e})=>Boolean(e.CIRCLECI),configuration({env:e}){const t=e.CIRCLE_PR_NUMBER||Be(e.CIRCLE_PULL_REQUEST||e.CI_PULL_REQUEST),n=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:n?void 0:e.CIRCLE_BRANCH,pr:t,isPr:n,prBranch:n?e.CIRCLE_BRANCH:void 0,slug:`${e.CIRCLE_PROJECT_USERNAME}/${e.CIRCLE_PROJECT_REPONAME}`}}},rn="https://cirrus-ci.com",sn={detect:({env:e})=>Boolean(e.CIRRUS_CI),configuration({env:e}){const t=e.CIRRUS_PR,n=Boolean(t);return{name:"Cirrus CI",service:"cirrus",commit:e.CIRRUS_CHANGE_IN_REPO,tag:e.CIRRUS_TAG,build:e.CIRRUS_BUILD_ID,buildUrl:`${rn}/build/${e.CIRRUS_BUILD_ID}`,job:e.CIRRUS_TASK_ID,jobUrl:`${rn}/task/${e.CIRRUS_TASK_ID}`,branch:n?e.CIRRUS_BASE_BRANCH:e.CIRRUS_BRANCH,pr:t,isPr:n,prBranch:n?e.CIRRUS_BRANCH:void 0,slug:e.CIRRUS_REPO_FULL_NAME,root:e.CIRRUS_WORKING_DIR}}},on={detect:({env:e})=>Boolean(e.CODEBUILD_BUILD_ID),configuration:({env:e,cwd:t})=>({name:"AWS CodeBuild",service:"codebuild",commit:Kt({env:e,cwd:t}),build:e.CODEBUILD_BUILD_ID,branch:Jt({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})},an={detect:({env:e})=>Boolean(e.CF_BUILD_ID),configuration({env:e}){const t=e.CF_PULL_REQUEST_NUMBER,n=Boolean(t);return{name:"Codefresh",service:"codefresh",commit:e.CF_REVISION,build:e.CF_BUILD_ID,buildUrl:e.CF_BUILD_URL,branch:n?e.CF_PULL_REQUEST_TARGET:e.CF_BRANCH,pr:t,isPr:n,prBranch:n?e.CF_BRANCH:void 0,slug:`${e.CF_REPO_OWNER}/${e.CF_REPO_NAME}`,root:e.CF_VOLUME_PATH}}},cn={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}}},ln=e=>({commit:Kt(e),branch:Jt(e)}),un=({env:e})=>{try{const t=e.GITHUB_EVENT_PATH?JSON.parse(x(e.GITHUB_EVENT_PATH,"utf-8")):void 0;if(t&&t.pull_request)return{branch:t.pull_request.base?je(t.pull_request.base.ref):void 0,pr:t.pull_request.number}}catch{}return{pr:void 0,branch:void 0}},dn={detect:({env:e})=>Boolean(e.GITHUB_ACTIONS),configuration({env:e,cwd:t}){const n="pull_request"===e.GITHUB_EVENT_NAME||"pull_request_target"===e.GITHUB_EVENT_NAME,r=je("pull_request_target"===e.GITHUB_EVENT_NAME?`refs/pull/${(e=>{const t=e.GITHUB_EVENT_PATH?JSON.parse(x(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:n,branch:r,prBranch:n?r:void 0,slug:e.GITHUB_REPOSITORY,root:e.GITHUB_WORKSPACE,...n?un({env:e}):void 0}}},pn={detect:({env:e})=>Boolean(e.GITLAB_CI),configuration({env:e}){const t=e.CI_MERGE_REQUEST_ID,n=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:n?e.CI_MERGE_REQUEST_TARGET_BRANCH_NAME:e.CI_COMMIT_REF_NAME,pr:t,isPr:n,prBranch:e.CI_MERGE_REQUEST_SOURCE_BRANCH_NAME,slug:e.CI_PROJECT_PATH,root:e.CI_PROJECT_DIR}}},fn={detect:({env:e})=>Boolean(e.JENKINS_URL),configuration({env:e,cwd:t}){const n=e.ghprbPullId||e.gitlabMergeRequestId||e.CHANGE_ID,r=Boolean(n),s=e.GIT_LOCAL_BRANCH||e.GIT_BRANCH||e.gitlabBranch||e.BRANCH_NAME;return{name:"Jenkins",service:"jenkins",commit:e.ghprbActualCommit||e.GIT_COMMIT||Kt({env:e,cwd:t}),branch:r?e.ghprbTargetBranch||e.gitlabTargetBranch:s,build:e.BUILD_NUMBER,buildUrl:e.BUILD_URL,root:e.WORKSPACE,pr:n,isPr:r,prBranch:r?e.ghprbSourceBranch||e.gitlabSourceBranch||s:void 0}}},hn={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}}},gn={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})},mn={detect:({env:e})=>Boolean(e.SAILCI),configuration({env:e}){const t=e.SAIL_PULL_REQUEST_NUMBER,n=Boolean(t);return{name:"Sail CI",service:"sail",commit:e.SAIL_COMMIT_SHA,branch:n?void 0:e.SAIL_COMMIT_BRANCH,pr:t,isPr:n,slug:`${e.SAIL_REPO_OWNER}/${e.SAIL_REPO_NAME}`,root:e.SAIL_CLONE_DIR}}},yn={detect:({env:e})=>Boolean(e.SCREWDRIVER),configuration({env:e}){const t=e.SD_PULL_REQUEST,n=Boolean(t);return{name:"Screwdriver.cd",service:"screwdriver",branch:n?e.PR_BASE_BRANCH_NAME:e.GIT_BRANCH,prBranch:n?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:n,slug:e.SD_PIPELINE_NAME,root:e.SD_ROOT_DIR}}},bn={detect:({env:e})=>Boolean(e.SCRUTINIZER),configuration({env:e}){const t=e.SCRUTINIZER_PR_NUMBER,n=Boolean(t);return{name:"Scrutinizer",service:"scrutinizer",commit:e.SCRUTINIZER_SHA1,build:e.SCRUTINIZER_INSPECTION_UUID,branch:e.SCRUTINIZER_BRANCH,pr:t,isPr:n,prBranch:e.SCRUTINIZER_PR_SOURCE_BRANCH}}},wn={detect:({env:e})=>Boolean(e.SEMAPHORE),configuration({env:e,cwd:t}){const n=e.SEMAPHORE_GIT_PR_NUMBER||e.PULL_REQUEST_NUMBER,r=Boolean(n);return{name:"Semaphore",service:"semaphore",commit:e.SEMAPHORE_GIT_SHA||Kt({env:e,cwd:t}),tag:e.SEMAPHORE_GIT_TAG_NAME,build:e.SEMAPHORE_JOB_ID||e.SEMAPHORE_BUILD_NUMBER,branch:e.SEMAPHORE_GIT_BRANCH||(r?void 0:e.BRANCH_NAME),pr:n,isPr:r,prBranch:e.SEMAPHORE_GIT_PR_BRANCH||(r?e.BRANCH_NAME:void 0),slug:e.SEMAPHORE_GIT_REPO_SLUG||e.SEMAPHORE_REPO_SLUG,root:e.SEMAPHORE_GIT_DIR||e.SEMAPHORE_PROJECT_DIR}}},vn={detect:({env:e})=>Boolean(e.SHIPPABLE),configuration({env:e}){const t="true"===e.IS_PULL_REQUEST?e.PULL_REQUEST:void 0,n=Boolean(t);return{name:"Shippable",service:"shippable",commit:e.COMMIT,tag:e.GIT_TAG_NAME,build:e.BUILD_NUMBER,buildUrl:e.BUILD_URL,branch:n?e.BASE_BRANCH:e.BRANCH,job:e.JOB_NUMBER,pr:t,isPr:n,prBranch:n?e.HEAD_BRANCH:void 0,slug:e.SHIPPABLE_REPO_SLUG,root:e.SHIPPABLE_BUILD_DIR}}},In={};function Tn(){if(en)return In;en=1,Object.defineProperty(In,"__esModule",{value:!0}),In.of=In.PropertiesFile=void 0;var e,t=(e=v)&&e.__esModule?e:{default:e};class n{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),n=Math.min(...t),r=e.substring(0,n).trim(),s=e.substring(n+1).trim();if(this.objs.hasOwnProperty(r))if(Array.isArray(this.objs[r]))this.objs[r].push(s);else{let e=this.objs[r];this.objs[r]=[e,s]}else{const e=s.replace(/"/g,'\\"').replace(/\\:/g,":").replace(/\\=/g,"=");this.objs[r]=unescape(JSON.parse('"'+e+'"'))}}}addFile(e){let n=t.default.readFileSync(e,"utf-8").split(/\r?\n/),r=this;for(let e=0;e<n.length;e++){let t=n[e];for(;"\\"===t.substring(t.length-1);)t=t.slice(0,-1),t+=n[e+1].trim(),e++;r.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 n=0;n<this.objs[e].length;n++)t[n]=this.interpolate(this.objs[e][n]);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 n=this.objs[e].length;return this.interpolate(this.objs[e][n-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 n=this.getLast(e);return n?parseInt(n,10):t}getFloat(e,t){let n=this.getLast(e);return n?parseFloat(n):t}getBoolean(e,t){let n=this.getLast(e);return n?!/^(false|0)$/i.test(r=n)&&!!r:t||!1;var r}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 n in this.objs)-1!==n.search(e)&&t.push(n);return t}reset(){this.objs={}}}return In.PropertiesFile=n,In.of=function(...e){let t=new n;return t.of.apply(t,e),t},In}var _n=Ye(Tn()),En={root:"teamcity.build.workingDir",branch:"teamcity.build.branch"},Sn=e=>{try{return _n.of(e)}catch{return}},xn=({env:e,cwd:t})=>{const n=e.TEAMCITY_BUILD_PROPERTIES_FILE?Sn(e.TEAMCITY_BUILD_PROPERTIES_FILE):void 0,r=n?n.get("teamcity.configuration.properties.file"):void 0,s=r?Sn(r):r;return Object.fromEntries(Object.keys(En).map(r=>[r,(n?n.get(En[r]):void 0)||(s?s.get(En[r]):void 0)||("branch"===r?Jt({env:e,cwd:t}):void 0)]))},An={appveyor:Oe,azurePipelines:Me,bamboo:Fe,bitbucket:He,bitrise:Ge,buddy:We,buildkite:tn,circleci:nn,cirrus:sn,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:on,codefresh:an,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:cn,github:dn,gitlab:pn,jenkins:fn,netlify:hn,puppet:gn,sail:mn,screwdriver:yn,scrutinizer:bn,semaphore:wn,shippable:vn,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,...xn({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,n=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:n,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",n="vercel";return e.VERCEL?{name:t,service:n,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:n,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,n=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:je(e.JB_SPACE_GIT_BRANCH),slug:t&&n?`${t.toLowerCase()}/${n}`:void 0}}}},kn=["test","bug","flake","ui_change","other"],Cn={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."},Pn=e=>Cn[e],Rn=function(){const e=process.env.STABLY_THEME;if("light"===e||"dark"===e)return e;const t=process.env.COLORFGBG;if(t){const e=t.split(";").at(-1);if(void 0!==e&&""!==e){const t=Number(e);if(Number.isInteger(t)&&t>=0&&t<=15)return t<=6||8===t?"dark":"light"}}return"dark"}(),Un=function(){const e=process.env.FORCE_COLOR;if(void 0!==e){if("false"===e||"0"===e)return 0;if("true"===e||""===e)return 1;const t=Number(e);return Number.isNaN(t)?1:0===t?0:1===t?1:2===t?2:t>=3?3:1}if(void 0!==process.env.NO_COLOR)return 0;if(!process.stdout.isTTY)return 0;const t=process.env.COLORTERM?.toLowerCase(),n=process.env.TERM_PROGRAM?.toLowerCase(),r=process.env.TERM?.toLowerCase()??"";return"truecolor"===t||"24bit"===t||n&&["iterm.app","iterm2","hyper","wezterm","ghostty","kitty","alacritty","warp","rio"].some(e=>n.includes(e))||"vscode"===n?3:r.startsWith("screen")||r.startsWith("tmux")||r.includes("256color")||r.includes("256colours")||"apple_terminal"===n?2:1}(),$n="dark"===Rn?{brand:{hex:"#2DD4BF",ansi256:86,ansi:"cyan"},userPrompt:{hex:"#67E8F9",ansi256:87,ansi:"cyan"},muted:{hex:"#D1D5DB",ansi256:252,ansi:"white"},subtle:{hex:"#9CA3AF",ansi256:248,ansi:"gray"},success:{hex:"#4ADE80",ansi256:78,ansi:"green"},error:{hex:"#F87171",ansi256:210,ansi:"red"},warning:{hex:"#FBBF24",ansi256:220,ansi:"yellow"},info:{hex:"#38BDF8",ansi256:75,ansi:"cyan"},accent:{hex:"#A78BFA",ansi256:141,ansi:"magenta"},link:{hex:"#38BDF8",ansi256:75,ansi:"cyan"},inlineCode:{hex:"#A78BFA",ansi256:141,ansi:"magenta"},codeBlock:{hex:"#D1D5DB",ansi256:252,ansi:"white"},fixTriage:{hex:"#FB923C",ansi256:215,ansi:"yellow"},fixDebug:{hex:"#C084FC",ansi256:177,ansi:"magenta"},fixValidation:{hex:"#60A5FA",ansi256:75,ansi:"blue"},fatalBg:{hex:"#991B1B",ansi256:88,ansi:"red"}}:{brand:{hex:"#0D9488",ansi256:30,ansi:"cyan"},userPrompt:{hex:"#0E7490",ansi256:30,ansi:"cyan"},muted:{hex:"#4B5563",ansi256:240,ansi:"gray"},subtle:{hex:"#808896",ansi256:244,ansi:"gray"},success:{hex:"#15803D",ansi256:28,ansi:"green"},error:{hex:"#B91C1C",ansi256:124,ansi:"red"},warning:{hex:"#B45309",ansi256:130,ansi:"yellow"},info:{hex:"#0369A1",ansi256:25,ansi:"blue"},accent:{hex:"#7C3AED",ansi256:98,ansi:"magenta"},link:{hex:"#0369A1",ansi256:25,ansi:"blue"},inlineCode:{hex:"#7C3AED",ansi256:98,ansi:"magenta"},codeBlock:{hex:"#374151",ansi256:239,ansi:"gray"},fixTriage:{hex:"#C2410C",ansi256:166,ansi:"red"},fixDebug:{hex:"#7E22CE",ansi256:91,ansi:"magenta"},fixValidation:{hex:"#1D4ED8",ansi256:26,ansi:"blue"},fatalBg:{hex:"#991B1B",ansi256:88,ansi:"red"}};function Ln(e){const t=$n[e];if(0!==Un)return 1===Un?t.ansi:t.hex}function Dn(e,t){if(0===Un)return t;const n=$n[e];if(Un>=3){const[e,r,s]=On(n.hex);return`[38;2;${e};${r};${s}m${t}[39m`}return 2===Un?`[38;5;${n.ansi256}m${t}[39m`:function(e,t){const n=Bn[e];return n?n(t):t}(n.ansi,t)}function Nn(e,t){if(0===Un)return t;const n=$n[e];if(Un>=3){const[e,r,s]=On(n.hex);return`[48;2;${e};${r};${s}m${t}[49m`}return 2===Un?`[48;5;${n.ansi256}m${t}[49m`:function(e,t){const n=jn[e];return n?n(t):t}(n.ansi,t)}function On(e){const t=e.startsWith("#")?e.slice(1):e;return[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16)]}var Bn={red:re.red,green:re.green,yellow:re.yellow,blue:re.blue,magenta:re.magenta,cyan:re.cyan,white:re.white,gray:re.gray},jn={red:re.bgRed,green:re.bgGreen,yellow:re.bgYellow,blue:re.bgBlue,magenta:re.bgMagenta,cyan:re.bgCyan,white:re.bgWhite},Mn=class e{git;config;snapshotTreeHash;snapshotIndexPath;constructor(e){this.config=e,this.git=se({baseDir:e.workingDir,maxConcurrentProcesses:1})}static createLocal({workingDir:t}){return new e({mode:"local",workingDir:t})}static createCloud({workingDir:t,baseBranch:n}){return new e({mode:"cloud",workingDir:t,baseBranch:n})}async captureSnapshot(){if("local"!==this.config.mode)return;this.snapshotIndexPath=i(N(),`git-diff-tracker-${ie()}.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=i(N(),`git-diff-tracker-${ie()}.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 Fn(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 Fn(this.snapshotIndexPath),this.snapshotIndexPath=void 0),this.snapshotTreeHash=void 0}};async function Fn(e){try{await J(e)}catch{}}var Hn="x-stably-org-id",Gn={bodySerializer:e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t)},Wn=({allowReserved:e,explode:t,name:n,style:r,value:s})=>{if(!t){const t=(e?s:s.map(e=>encodeURIComponent(e))).join((e=>{switch(e){case"form":default:return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20"}})(r));switch(r){case"label":return`.${t}`;case"matrix":return`;${n}=${t}`;case"simple":return t;default:return`${n}=${t}`}}const o=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(r),i=s.map(t=>"label"===r||"simple"===r?e?t:encodeURIComponent(t):Vn({allowReserved:e,name:n,value:t})).join(o);return"label"===r||"matrix"===r?o+i:i},Vn=({allowReserved:e,name:t,value:n})=>{if(null==n)return"";if("object"==typeof n)throw new Error("Deeply-nested arrays/objects arenβt supported. Provide your own `querySerializer()` to handle these.");return`${t}=${e?n:encodeURIComponent(n)}`},Yn=({allowReserved:e,explode:t,name:n,style:r,value:s,valueOnly:o})=>{if(s instanceof Date)return o?s.toISOString():`${n}=${s.toISOString()}`;if("deepObject"!==r&&!t){let t=[];Object.entries(s).forEach(([n,r])=>{t=[...t,n,e?r:encodeURIComponent(r)]});const o=t.join(",");switch(r){case"form":return`${n}=${o}`;case"label":return`.${o}`;case"matrix":return`;${n}=${o}`;default:return o}}const i=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(r),a=Object.entries(s).map(([t,s])=>Vn({allowReserved:e,name:"deepObject"===r?`${n}[${t}]`:t,value:s})).join(i);return"label"===r||"matrix"===r?i+a:a},zn=/\{[^{}]+\}/g;function qn(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 Kn,Jn=async(e,t)=>{const n="function"==typeof t?await t(e):t;if(n)return"bearer"===e.scheme?`Bearer ${n}`:"basic"===e.scheme?`Basic ${btoa(n)}`:n},Xn=({parameters:e={},...t}={})=>n=>{const r=[];if(n&&"object"==typeof n)for(const s in n){const o=n[s];if(null==o)continue;const i=e[s]||t;if(Array.isArray(o)){const e=Wn({allowReserved:i.allowReserved,explode:!0,name:s,style:"form",value:o,...i.array});e&&r.push(e)}else if("object"==typeof o){const e=Yn({allowReserved:i.allowReserved,explode:!0,name:s,style:"deepObject",value:o,...i.object});e&&r.push(e)}else{const e=Vn({allowReserved:i.allowReserved,name:s,value:o});e&&r.push(e)}}return r.join("&")},Qn=(e,t)=>!!t&&!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`)),Zn=e=>(({baseUrl:e,path:t,query:n,querySerializer:r,url:s})=>{let o=(e??"")+(s.startsWith("/")?s:`/${s}`);t&&(o=(({path:e,url:t})=>{let n=t;const r=t.match(zn);if(r)for(const t of r){let r=!1,s=t.substring(1,t.length-1),o="simple";s.endsWith("*")&&(r=!0,s=s.substring(0,s.length-1)),s.startsWith(".")?(s=s.substring(1),o="label"):s.startsWith(";")&&(s=s.substring(1),o="matrix");const i=e[s];if(null==i)continue;if(Array.isArray(i)){n=n.replace(t,Wn({explode:r,name:s,style:o,value:i}));continue}if("object"==typeof i){n=n.replace(t,Yn({explode:r,name:s,style:o,value:i,valueOnly:!0}));continue}if("matrix"===o){n=n.replace(t,`;${Vn({name:s,value:i})}`);continue}const a=encodeURIComponent("label"===o?`.${i}`:i);n=n.replace(t,a)}return n})({path:t,url:o}));let i=n?r(n):"";return i.startsWith("?")&&(i=i.substring(1)),i&&(o+=`?${i}`),o})({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:"function"==typeof e.querySerializer?e.querySerializer:Xn(e.querySerializer),url:e.url}),er=(e,t)=>{const n={...e,...t};return n.baseUrl?.endsWith("/")&&(n.baseUrl=n.baseUrl.substring(0,n.baseUrl.length-1)),n.headers=nr(e.headers,t.headers),n},tr=e=>{const t=[];return e.forEach((e,n)=>{t.push([n,e])}),t},nr=(...e)=>{const t=new Headers;for(const n of e){if(!n)continue;const e=n instanceof Headers?tr(n):Object.entries(n);for(const[n,r]of e)if(null===r)t.delete(n);else if(Array.isArray(r))for(const e of r)t.append(n,e);else void 0!==r&&t.set(n,"object"==typeof r?JSON.stringify(r):r)}return t},rr=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 n=this.getInterceptorIndex(e);return!!this.fns[n]&&(this.fns[n]=t,e)}use(e){return this.fns.push(e),this.fns.length-1}},sr=Xn({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),or={"Content-Type":"application/json"},ir=(e={})=>({...Gn,headers:or,parseAs:"auto",querySerializer:sr,...e}),ar=(e={})=>{let t=er(ir(),e);const n=()=>({...t}),r={error:new rr,request:new rr,response:new rr},s=async e=>{const n={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:nr(t.headers,e.headers),serializedBody:void 0};return n.security&&await(async({security:e,...t})=>{for(const n of e){if(Qn(t,n.name))continue;const e=await Jn(n,t.auth);if(!e)continue;const r=n.name??"Authorization";switch(n.in){case"query":t.query||(t.query={}),t.query[r]=e;break;case"cookie":t.headers.append("Cookie",`${r}=${e}`);break;default:t.headers.set(r,e)}}})({...n,security:n.security}),n.requestValidator&&await n.requestValidator(n),void 0!==n.body&&n.bodySerializer&&(n.serializedBody=n.bodySerializer(n.body)),void 0!==n.body&&""!==n.serializedBody||n.headers.delete("Content-Type"),{opts:n,url:Zn(n)}},o=async e=>{const{opts:t,url:n}=await s(e),o={redirect:"follow",...t,body:qn(t)};let i=new Request(n,o);for(const e of r.request.fns)e&&(i=await e(i,t));const a=t.fetch;let c=await a(i);for(const e of r.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 n;switch(e){case"arrayBuffer":case"blob":case"text":n=await c[e]();break;case"formData":n=new FormData;break;case"stream":n=c.body;break;default:n={}}return"data"===t.responseStyle?n:{data:n,...l}}let n;switch(e){case"arrayBuffer":case"blob":case"formData":case"json":case"text":n=await c[e]();break;case"stream":return"data"===t.responseStyle?c.body:{data:c.body,...l}}return"json"===e&&(t.responseValidator&&await t.responseValidator(n),t.responseTransformer&&(n=await t.responseTransformer(n))),"data"===t.responseStyle?n:{data:n,...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 r.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=>o({...t,method:e}),a=e=>async t=>{const{opts:n,url:o}=await s(t);return(({onRequest:e,onSseError:t,onSseEvent:n,responseTransformer:r,responseValidator:s,sseDefaultRetryDelay:o,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=o??3e3,f=0;const h=u.signal??(new AbortController).signal;for(;!h.aborted;){f++;const o=u.headers instanceof Headers?u.headers:new Headers(u.headers);void 0!==d&&o.set("Last-Event-ID",d);try{const t={redirect:"follow",...u,body:u.serializedBody,headers:o,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 g="";const m=()=>{try{f.cancel()}catch{}};h.addEventListener("abort",m);try{for(;;){const{done:e,value:t}=await f.read();if(e)break;g+=t;const o=g.split("\n\n");g=o.pop()??"";for(const e of o){const t=e.split("\n"),o=[];let i,a;for(const e of t)if(e.startsWith("data:"))o.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(o.length){const e=o.join("\n");try{a=JSON.parse(e),l=!0}catch{a=e}}l&&(s&&await s(a),r&&(a=await r(a))),n?.({data:a,event:i,id:d,retry:c}),o.length&&(yield a)}}}finally{h.removeEventListener("abort",m),f.releaseLock()}break}catch(e){if(t?.(e),void 0!==i&&f>=i)break;const n=Math.min(c*2**(f-1),a??3e4);await p(n)}}}()}})({...n,body:n.body,headers:n.headers,method:e,onRequest:async(e,t)=>{let s=new Request(e,t);for(const e of r.request.fns)e&&(s=await e(s,n));return s},url:o})};return{buildUrl:Zn,connect:i("CONNECT"),delete:i("DELETE"),get:i("GET"),getConfig:n,head:i("HEAD"),interceptors:r,options:i("OPTIONS"),patch:i("PATCH"),post:i("POST"),put:i("PUT"),request:o,setConfig:e=>(t=er(t,e),n()),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")}},cr=ar(ir({baseUrl:"https://api.stably.ai"})),lr=e=>(e.client??cr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs",...e}),ur=e=>(e.client??cr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}",...e}),dr="4.12.24",pr=process.env.STABLY_API_URL||"https://api.stably.ai",fr=e=>{const t=new URL(e);return t.protocol="http:"===t.protocol?"ws:":"wss:",t},hr=process.env.AUTH_URL||"https://auth.stably.ai",gr=process.env.AUTH_CLIENT_ID||"288007877071cce81f269428ea78653a",mr=process.env.AI_PROXY_URL||"https://ai-proxy.stably.ai",yr=process.env.STABLY_AUTOHEAL_WS_URL||new URL("/autoheal",fr(pr)).toString(),br=process.env.STABLY_CREATE_PROGRESS_WS_URL||new URL("/create-progress",fr(pr)).toString(),wr="http://localhost:9876/auth/callback",vr=()=>Kn||(Kn=ar(ir({baseUrl:pr,headers:{"X-STABLY-CLI-VERSION":dr,"X-STABLY-SOURCE":"cli"}}))),Ir=async(e,t)=>{const n=await(r={body:{accessToken:e,orgId:t},client:vr()},(r.client??cr).post({url:"/internal/v1/cli/exchange-token",...r,headers:{"Content-Type":"application/json",...r.headers}}));var r;if(401===n.response.status)throw new Error("Invalid or expired access token");if(403===n.response.status)throw new Error("You do not have access to this organization");if(n.error)throw new Error(`Failed to exchange token: ${n.response.status}`);return n.data},Tr=he.object({org_id:he.string(),org_name:he.string()}),_r=he.object({email:he.string(),org_id_to_org_member_info:he.record(he.string(),Tr).optional(),org_member_info:Tr.optional(),user_id:he.string()});he.object({email:he.string(),firstName:he.string().optional(),lastName:he.string().optional(),organizations:he.array(he.object({id:he.string(),name:he.string()})),userId:he.string()});var Er,Sr=e=>{const t=e.split(".");if(3!==t.length)throw new Error("Invalid JWT format");const n=t[1].replace(/-/g,"+").replace(/_/g,"/"),r=Buffer.from(n,"base64").toString("utf-8");return JSON.parse(r)},xr=e=>{try{const t=_r.parse(Sr(e)),n=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:n,userId:t.user_id}}catch(e){throw new Error(`Failed to decode token: ${e instanceof Error?e.message:"Unknown error"}`)}},Ar=async(e,t)=>{let n=e;const{root:s}=r.parse(n);for(;n!==s;){const e=r.join(n,t);try{return await X(e),e}catch{n=r.dirname(n)}}},kr=r.join(D.homedir(),".stably"),Cr=r.join(kr,"auth.json"),Pr=".stably",Rr="project.json",Ur=fe.object({accessToken:fe.string(),expiresAt:fe.number(),idToken:fe.string().optional(),refreshToken:fe.string()}),$r=fe.object({orgId:fe.string(),orgName:fe.string(),projectId:fe.string(),projectName:fe.string()}),Lr=async()=>{try{const e=await z(Cr,"utf-8");return Ur.parse(JSON.parse(e))}catch{return}},Dr=async e=>{await q(kr,{recursive:!0}),await K(Cr,JSON.stringify(e,null,2),{mode:384})},Nr=async()=>{try{await J(Cr)}catch{}},Or=async()=>{try{const e=await Ar(process.cwd(),Pr);if(!e)return;const t=r.join(e,Rr),n=await z(t,"utf-8");return $r.parse(JSON.parse(n))}catch{return}},Br=async()=>{try{const e=await Ar(process.cwd(),Pr);e&&await J(r.join(e,Rr))}catch{}},jr=e=>Date.now()>=e.expiresAt-3e5,Mr=async e=>{const t=new URLSearchParams({client_id:gr,grant_type:"refresh_token",refresh_token:e}),n=await fetch(`${hr}/propelauth/oauth/token`,{body:t.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},method:"POST"});if(!n.ok)throw new Error(`Token refresh failed: ${n.status}`);const r=await n.json();return{accessToken:r.access_token,expiresAt:Date.now()+1e3*r.expires_in,refreshToken:r.refresh_token}},Fr=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`,Hr=(e,t,n)=>{e.writeHead(t,{"Content-Type":"text/html"}),e.end(n)},Gr=(e,t)=>{const n=new URLSearchParams({client_id:gr,code_challenge:e,code_challenge_method:"S256",redirect_uri:wr,response_type:"code",state:t});return`${hr}/propelauth/oauth/authorize?${n.toString()}`},Wr=async e=>{const t=le();let n;t.start("Loading user info...");try{n=xr(e.accessToken),t.stop(Dn("success",`β Logged in as ${Dn("info",n.email)}`))}catch(e){t.stop(Dn("error","β Failed to load user info"));const n=e instanceof Error?e.message:"Unknown error";return ae.error(n),{success:!1}}const s=await(async e=>{if(0===e.length)return void ae.error("You don't belong to any organizations.");if(1===e.length)return ae.info(`Using organization: ${Dn("info",e[0].name)}`),e[0];if(!process.stdin.isTTY)return ae.info(`Auto-selecting organization: ${Dn("info",e[0].name)}`),e[0];const t=await de({message:"Select an organization",options:[...e].sort((e,t)=>e.name.localeCompare(t.name)).map(e=>({label:e.name,value:e.id}))});return pe(t)?void 0:e.find(e=>e.id===t)})(n.organizations);if(!s)return ae.warn("Organization selection cancelled."),{success:!1};let o;t.start("Getting org credentials...");try{const n=await Ir(e.accessToken,s.id);o={accessToken:n.accessToken,expiresAt:Date.now()+1e3*n.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken},t.stop(Dn("success","β Credentials obtained"))}catch(e){t.stop(Dn("error","β Failed to get org credentials"));const n=e instanceof Error?e.message:"Unknown error";return ae.error(n),{success:!1}}const i=await(async(e,t)=>{const n=le();let r;n.start("Loading projects...");try{r=await(async({accessToken:e,orgId:t})=>{const n=await(r={auth:e,client:vr(),path:{orgId:t}},(r.client??cr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/orgs/{orgId}/projects",...r}));var r;if(401===n.response.status)throw new Error("Invalid or expired access token");if(403===n.response.status)throw new Error("You do not have access to this organization");if(n.error)throw new Error(`Failed to list projects: ${n.response.status}`);return n.data.projects})({accessToken:e,orgId:t}),n.stop(Dn("success","β Projects loaded"))}catch(e){n.stop(Dn("error","β Failed to load projects"));const t=e instanceof Error?e.message:"Unknown error";return void ae.error(t)}if(0===r.length)return ae.error("No projects found in this organization."),void ae.info(`Create a project at ${re.underline(Dn("link","https://app.stably.ai"))}`);if(1===r.length)return ae.info(`Using project: ${Dn("info",r[0].name)}`),r[0];if(!process.stdin.isTTY)return ae.info(`Auto-selecting project: ${Dn("info",r[0].name)}`),r[0];const s=await de({message:"Select a project",options:r.map(e=>({label:e.name,value:e.id}))});return pe(s)?void 0:r.find(e=>e.id===s)})(o.accessToken,s.id);return i?(await(async e=>{const t=r.join(process.cwd(),Pr),n=r.join(t,Rr);await q(t,{recursive:!0}),await K(n,JSON.stringify(e,null,2)),await(async e=>{const t=r.join(e,".gitignore"),n="# Stably CLI (only docs/ are tracked)\n.stably/*\n!.stably/docs/";try{const e=await z(t,"utf-8"),r=e.split("\n").map(e=>e.trim());if(r.includes(".stably/*")&&r.includes("!.stably/docs/"))return;const s=/^# Stably CLI\n\.stably\/?$/m,o=/^\.stably\/?$/m;if(s.test(e)){const r=e.replace(s,`\n${n}\n`);await K(t,r)}else if(o.test(e)){const r=e.replace(o,`\n${n}\n`);await K(t,r)}else await ee(t,`\n${n}\n`)}catch{await K(t,`${n}\n`)}})(process.cwd())})({orgId:s.id,orgName:s.name,projectId:i.id,projectName:i.name}),ae.info(re.dim("Linked this directory to your Stably project.")),{scopedTokens:o,success:!0}):(ae.warn("Project selection cancelled."),{success:!1})},Vr=async()=>{if(hs())return ae.warn(`Environment variables ${Dn("info","STABLY_API_KEY")} and ${Dn("info","STABLY_PROJECT_ID")} are set.`),ae.warn("These will be used for authentication instead of OAuth login."),ae.warn("To use OAuth login, unset these environment variables first."),void ce(Dn("warning","Login skipped - using environment variable authentication."));const e=await Lr();if(e){if(!jr(e)){if(await Or())return void ce(Dn("warning","You are already logged in. Run `stably logout` first to log out."));ae.info("You are logged in but haven't selected a project yet.");const t=await Wr(e);return void(t.success?(await Dr(t.scopedTokens),ce(Dn("success","Setup complete! You can now use Stably CLI."))):ce(Dn("warning","Setup incomplete. Run `stably login` to try again.")))}const t=le();t.start("Refreshing session...");try{const n=await Mr(e.refreshToken);t.stop(Dn("success","β Session refreshed"));const r=await Or();if(r){t.start("Getting org credentials...");try{const e=await Ir(n.accessToken,r.orgId),s={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:n.idToken,refreshToken:n.refreshToken};await Dr(s),t.stop(Dn("success","β Credentials obtained")),ce(Dn("success","Login successful"))}catch{await Dr(n),t.stop(Dn("warning","Using full credentials")),ce(Dn("success","Login successful"))}}else{const e=await Wr(n);e.success?(await Dr(e.scopedTokens),ce(Dn("success","Setup complete! You can now use Stably CLI."))):ce(Dn("warning","Setup incomplete. Run `stably login` to try again."))}return}catch{t.stop(Dn("warning","Session expired, proceeding with fresh login...")),await Nr(),await Br()}}const{authorizeUrl:t,serverReady:n,waitForCallback:r}=(()=>{const{authorizeUrl:e,codeVerifier:t,state:n}=(()=>{const e=oe.randomBytes(32).toString("base64url"),t=(n=e,oe.createHash("sha256").update(n).digest("base64url"));var n;const r=oe.randomBytes(16).toString("base64url");return{authorizeUrl:Gr(t,r),codeVerifier:e,state:r}})(),{ready:r,result:s}=(e=>{let t,n;return{ready:new Promise((e,r)=>{t=e,n=r}),result:new Promise((r,s)=>{const o=setTimeout(()=>{a.close(),r({error:"Login timed out",success:!1})},3e5),i=()=>{clearTimeout(o)},a=me.createServer((t,n)=>{const s=new L(t.url||"","http://localhost:9876");if("/auth/callback"!==s.pathname)return n.writeHead(404),void n.end("Not found");const o=s.searchParams.get("code"),c=s.searchParams.get("state"),l=s.searchParams.get("error");return l?(Hr(n,400,Fr(l)),i(),a.close(),void r({error:l,success:!1})):o&&c?c!==e?(Hr(n,400,Fr("Invalid state parameter (possible CSRF attack)")),i(),a.close(),void r({error:"State mismatch",success:!1})):(Hr(n,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 r({code:o,state:c,success:!0})):(Hr(n,400,Fr("Missing code or state parameter")),i(),a.close(),void r({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 n(e),void s(e)}const t=new Error(`Failed to start callback server: ${e.message}`);n(t),s(t)}),a.listen(9876,()=>{t()})})}})(n);return{authorizeUrl:e,serverReady:r,waitForCallback:async()=>{const e=await s;if(!e.success)throw new Error(e.error);return(async(e,t)=>{const n=new URLSearchParams({client_id:gr,code:e,code_verifier:t,grant_type:"authorization_code",redirect_uri:wr}),r=await fetch(`${hr}/propelauth/oauth/token`,{body:n.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},method:"POST"});if(!r.ok){const e=await r.text();throw new Error(`Token exchange failed: ${r.status} ${e}`)}const s=await r.json();return{accessToken:s.access_token,expiresAt:Date.now()+1e3*s.expires_in,idToken:s.id_token,refreshToken:s.refresh_token}})(e.code,t)}}})();await n,ae.info("Opening browser for authentication..."),ae.info(re.dim("If browser doesn't open, visit:")),ae.info(`]8;;${t}${re.underline(Dn("link",t))}]8;;`);try{await ge(t)}catch{ae.warn("Could not open browser automatically. Please open the URL above manually.")}const s=le();let o;s.start("Waiting for authentication...");try{o=await r(),s.stop(Dn("success","β Authentication successful"))}catch(e){s.stop(Dn("error","β Authentication failed"));const t=e instanceof Error?e.message:"Unknown error";ce(Dn("error",`Login failed: ${t}`)),process.exit(1)}const i=await Wr(o);i.success?(await Dr(i.scopedTokens),ce(Dn("success","Setup complete! You can now use Stably CLI."))):(ce(Dn("warning","Setup incomplete. Run `stably login` to try again.")),process.exit(1))},Yr={fatal:60,error:50,warn:40,info:30,debug:20,trace:10},zr=new Set(["help","login","logout","whoami","tunnel","create","fix","internal-fix-run","init","upgrade","test","show-report","codegen"]),qr=(new Date).toISOString().split("T")[0],Kr=(()=>{const e=[r.join(D.tmpdir(),"stably-logs",qr),r.join(D.homedir(),".stably","logs",qr)];for(const t of e)try{return v.mkdirSync(t,{recursive:!0}),t}catch{}return null})(),Jr=process.argv.includes("--verbose")||process.argv.includes("-v"),Xr=process.env.STABLY_LOG_LEVEL?.toLowerCase(),Qr=Jr?"debug":void 0!==(Er=Xr)&&Er in Yr?Xr:"warn",Zr=Yr[Qr],es=null,ts=null,ns=null,rs=[],ss=!1,os=e=>{if(!ss){if(!(es=(e=>{if(!Kr)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(Kr,`${t}-${n}.log`)})(e)))return rs=[],void(ss=!0);(e=>{const t=["","=".repeat(60),"Stably CLI Debug Log",`Version: ${dr}`,`Generated: ${(new Date).toISOString()}`,`Node: ${process.version}`,`Platform: ${process.platform} ${D.release()}`,`CWD: ${process.cwd()}`,`Args: ${process.argv.slice(2).join(" ")}`,`Log Level (console): ${Qr}`,"=".repeat(60),""].join("\n");e.write(t)})(ts=new be({dest:es,minLength:4096,sync:!1,append:!0})),ns=ye({level:"debug",timestamp:ye.stdTimeFunctions.isoTime,base:{version:dr}},ts);for(const{level:e,msg:t,context:n}of rs)n?ns[e](n,t):ns[e](t);rs=[],ss=!0,Jr&&process.stderr.write(`${re.dim(`Debug log: ${es}`)}\n\n`)}},is=(()=>{const e=process.argv.slice(2).find(e=>!e.startsWith("-"));return e&&zr.has(e)?e:null})();is&&os(is);var as=e=>(t,n)=>{if(ns?n?ns[e](n,t):ns[e](t):ss||rs.push({level:e,msg:t,context:n}),(e=>Yr[e]>=Zr)(e)){const n=((e,t)=>`${{fatal:Nn("fatalBg",re.white(re.bold(" FATAL "))),error:Dn("error","error"),warn:Dn("warning","warn"),info:Dn("info","info"),debug:re.dim("debug"),trace:re.dim("trace")}[e]} ${t}`)(e,t);process.stderr.write(`${n}\n`)}},cs={fatal:as("fatal"),error:as("error"),warn:as("warn"),info:as("info"),debug:as("debug"),trace:as("trace"),initSession:e=>{ss||os(e)},getLogFilePath:()=>es,flush:()=>{if(ts)try{ts.flushSync()}catch{}},printLogFileInfo:()=>{es&&(process.stderr.write(`\n${re.dim("Debug log written to:")}\n`),process.stderr.write(` ${Dn("info",es)}\n`),process.stderr.write(`${re.dim("Share this file with support for assistance.")}\n`))},getPinoLogger:()=>ns};setInterval(()=>{cs.flush()},3e4).unref(),process.on("beforeExit",()=>{cs.flush()});var ls=e=>{const t=()=>{cs.flush(),Jr&&cs.printLogFileInfo(),process.removeListener(e,t),process.kill(process.pid,e)};return t};process.on("SIGINT",ls("SIGINT")),process.on("SIGTERM",ls("SIGTERM"));var us=()=>"true"===process.env.GITHUB_ACTIONS?"github-actions":"true"===process.env.GITLAB_CI?"gitlab-ci":"true"===process.env.CIRCLECI?"circleci":process.env.JENKINS_URL?"jenkins":process.env.CI?"generic-ci":"local",ds=()=>"local"!==us(),ps=e=>{switch(e){case"github-actions":return"GitHub secrets";case"gitlab-ci":return"GitLab CI/CD variables";case"circleci":return"CircleCI environment variables";case"jenkins":return"Jenkins credentials";case"generic-ci":return"CI secrets/environment variables";case"local":return"environment variables"}},fs=()=>{const e=us();return[`Authentication failed. In CI, add the following to your ${ps(e)}:`," STABLY_API_KEY β https://app.stably.ai/settings?tab=api-key"," STABLY_PROJECT_ID β https://app.stably.ai/settings?tab=project-id"].join("\n")},hs=()=>{const e=process.env.STABLY_API_KEY?.trim(),t=process.env.STABLY_PROJECT_ID?.trim();if(e&&t)return cs.debug("Environment auth detected",{hasApiKey:!0,hasProjectId:!0}),{apiKey:e,projectId:t};cs.debug("Environment auth not set",{hasApiKey:!!e,hasProjectId:!!t})},gs=async()=>{cs.debug("Checking for stored auth tokens");const e=await Lr();if(!e)return void cs.debug("No stored auth tokens found");const t=jr(e);if(cs.debug("Auth tokens status",{expired:t}),!t){const t=await Or(),n=(e=>{try{const t=_r.parse(Sr(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(cs.debug("Token scope check",{scope:n,hasContext:!!t}),t&&"full"===n)try{cs.debug("Exchanging full token for org-scoped token",{orgId:t.orgId});const n=await Ir(e.accessToken,t.orgId),r={accessToken:n.accessToken,expiresAt:Date.now()+1e3*n.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken};return await Dr(r),cs.debug("Token exchange successful"),r}catch(t){return cs.debug("Token exchange failed, using existing token",{error:t instanceof Error?t.message:String(t)}),e}return e}try{cs.debug("Attempting token refresh");const t=await Mr(e.refreshToken);cs.debug("Token refresh successful");const n=await Or();if(n)try{cs.debug("Exchanging refreshed token for org-scoped token");const e=await Ir(t.accessToken,n.orgId),r={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:t.idToken,refreshToken:t.refreshToken};return await Dr(r),r}catch{return await Dr(t),t}return await Dr(t),t}catch(e){return void cs.warn("Token refresh failed",{error:e instanceof Error?e.message:String(e)})}},ms=async(e={})=>{cs.debug("Requiring authentication",{autoLogin:e.autoLogin});const t=hs();if(t)return cs.info("Using environment variable authentication"),{auth:t,type:"env"};const n=await Lr();let r=await gs(),s=r?await Or():void 0;const o=process.stdin.isTTY&&process.stdout.isTTY;if(cs.debug("OAuth auth check",{hasTokens:!!r,hasStoredTokens:!!n,hasContext:!!s,canPrompt:o}),(!r||!s)&&e.autoLogin&&o){cs.info("Prompting user to login"),r?ae.info("You are logged in but need to select an organization and project."):ae.info("You are not logged in."),ae.info("Press Enter to log in."),process.stdout.write(`${re.dim("Alternatively, set environment variables for an org API key:")}\n${re.dim(" STABLY_API_KEY=... STABLY_PROJECT_ID=... stably")}\n`),process.stdout.write("\n");const e=ne({input:process.stdin,output:process.stdout});try{await e.question(re.dim("Press Enter to continue... "))}finally{e.close()}await Vr(),r=await gs(),s=r?await Or():void 0}return r||(cs.warn("Authentication required but no tokens available",{hadStoredTokens:!!n}),ds()?ce(Dn("error",fs())):ce(Dn("error",n?"Your session has expired. Run `stably login` to re-authenticate.":"You are not logged in. Run `stably login` to authenticate.")),process.exit(1)),s||(cs.warn("Authentication succeeded but no project context selected"),ds()?ce(Dn("error",fs())):ce(Dn("error","You haven't selected an organization and project. Run `stably login` to complete setup.")),process.exit(1)),cs.info("OAuth authentication successful",{orgId:s.orgId,projectId:s.projectId}),{auth:{accessToken:r.accessToken,context:s},type:"oauth"}},ys=e=>"env"===e.type?e.auth.projectId:e.auth.context.projectId,bs=e=>"env"===e.type?e.auth.apiKey:e.auth.accessToken,ws=class e{static TOKEN_REFRESH_BUFFER_MS=3e5;initialAuth;refreshPromise=null;cachedToken=null;cachedExpiresAt=0;constructor(e){this.initialAuth=e}async getAuthHeader(){return"env"===this.initialAuth.type?this.initialAuth.auth.apiKey:this.cachedToken&&Date.now()<this.cachedExpiresAt-e.TOKEN_REFRESH_BUFFER_MS?this.cachedToken:(this.refreshPromise||(this.refreshPromise=(async()=>{try{const e=await gs();if(!e)throw new Error("Authentication expired and refresh failed. Please re-run `stably login`.");return this.cachedToken=e.accessToken,this.cachedExpiresAt=e.expiresAt,e.accessToken}finally{this.refreshPromise=null}})()),this.refreshPromise)}getOrgId(){return"oauth"===this.initialAuth.type?this.initialAuth.auth.context.orgId:void 0}getProjectId(){return"env"===this.initialAuth.type?this.initialAuth.auth.projectId:this.initialAuth.auth.context.projectId}},vs=async e=>{const t=await ms(),n=ys(t),r=bs(t);cs.debug("Fetching remote environment variables",{envName:e,projectId:n});const s=await(o={auth:r,client:vr(),path:{projectId:n,environment:e}},(o.client??cr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/environments/{environment}/variables",...o}));var o;if(404===s.response.status)return{ok:!1,error:`Environment "${e}" not found. Check the name on your Stably dashboard.`};if(401===s.response.status||403===s.response.status)return{ok:!1,error:`Access denied to environment "${e}".`};if(s.error)return{ok:!1,error:`Failed to fetch environment "${e}": ${s.response.status}`};const i={},a=[];for(const e of s.data.variables)i[e.name]=e.value,e.sensitive&&e.value.length>0&&a.push(e.value);const c=s.data.variables.length,l=a.length;return process.stderr.write(`${Dn("info",`Loaded ${c} variable${1!==c?"s":""} from "${e}"`)}${l>0?re.dim(` (${l} sensitive)`):""}\n`),{ok:!0,result:{variables:i,sensitiveValues:a}}},Is=async()=>{const e=Ue.remoteEnvName;if(!e)return;const t=await vs(e);return t.ok||(ce(Dn("error",t.error)),process.exit(1)),t.result},Ts=e=>e?{[Hn]:e}:void 0,_s=he.object({context:he.string().min(1),autohealReportUrl:he.string(),skippedTests:he.array(he.object({testIdentifier:he.string(),testTitle:he.string(),consecutiveUnfixedCount:he.number()})).optional(),newerPassingSuiteId:he.string().optional(),envName:he.string().optional()}),Es=we.object({bucket:we.string(),key:we.string()}),Ss=async({body:e,contentType:t,uploadUrl:n,errorContext:r="content"})=>{const s=await fetch(n,{body:e instanceof Uint8Array?Buffer.from(e):e,headers:{"Content-Type":t},method:"PUT"});if(!s.ok)throw new Error(`Failed to upload ${r} (${s.status})`)},xs=we.object({diffBucketPath:Es,expiresInSeconds:we.number(),key:we.string(),uploadUrl:we.string()}),As=we.object({traceBucketPath:Es,expiresInSeconds:we.number(),key:we.string(),uploadUrl:we.string(),sensitiveValues:we.array(we.string())}),ks=async({authHeader:e,contentType:t="text/plain",orgId:n,runId:r})=>{const s=await(o={auth:e,body:{contentType:t},client:vr(),headers:Ts(n),path:{runId:r}},(o.client??cr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-diff/upload-url",...o,headers:{"Content-Type":"application/json",...o.headers}}));var o;if(s.error)throw new Error(`Failed to presign diff upload (${s.response.status})`);const i=xs.parse(s.data);return{diffBucketPath:i.diffBucketPath,expiresInSeconds:i.expiresInSeconds,key:i.key,uploadUrl:i.uploadUrl}},Cs=async({authHeader:e,diffBucketPath:t,orgId:n,runId:r})=>{const s=await(o={auth:e,body:t,client:vr(),headers:Ts(n),path:{runId:r}},(o.client??cr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-diff/confirm-upload",...o,headers:{"Content-Type":"application/json",...o.headers}}));var o;if(s.error)throw new Error(`Failed to confirm diff upload (${s.response.status})`)},Ps=class e{socket;url;authProvider;orgId;runId;pendingEvent=null;reconnectAttempts=0;reconnectTimer;flushPromise=null;debounceTimer;_isClosed=!1;isAuthenticated=!1;authenticationFailed=!1;onUserMessage;maxReconnectAttempts=10;baseReconnectDelay=2e3;maxReconnectDelay=3e4;debounceMs=500;get isClosed(){return this._isClosed}constructor({authProvider:e,orgId:t,runId:n,url:r=yr,onUserMessage:s}){this.authProvider=e,this.orgId=t,this.runId=n,this.url=r,this.onUserMessage=s,cs.info("[ws] Constructing AutohealWebSocketClient",{url:this.url,runId:n})}async start(){await this.connect()}async connect(){if(!this._isClosed)try{const e=await this.authProvider.getAuthHeader();if(this._isClosed)return;const t={Authorization:e};this.orgId&&(t["x-stably-org-id"]=this.orgId);const n=`${this.url}?runId=${encodeURIComponent(this.runId)}`;cs.info("[ws] Connecting",{url:n,attempt:this.reconnectAttempts}),this.socket=new ve(n,{headers:t}),this.socket.on("open",()=>{cs.info("[ws] Connection opened"),this.reconnectAttempts=0}),this.socket.on("message",e=>{try{const t="string"==typeof e?e:e.toString(),n=JSON.parse(t);cs.debug("[ws] Received message",{type:n?.type}),"connected"===n?.type&&(cs.info("[ws] Authenticated successfully"),this.isAuthenticated=!0,this.authenticationFailed=!1,this.flushPending()),"user_message"===n?.type&&"string"==typeof n.content&&(cs.info("[ws] Received user message from web UI"),this.onUserMessage?.(n.content))}catch{}}),this.socket.on("close",(e,t)=>{cs.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=>{cs.warn("[ws] Connection error",{error:e.message})})}catch(e){cs.warn("[ws] Failed to create WebSocket",{error:e instanceof Error?e.message:String(e)}),this.scheduleReconnect()}}scheduleReconnect(){if(this._isClosed||this.reconnectTimer)return;this.reconnectAttempts++;const e=Math.min(this.baseReconnectDelay*Math.pow(2,this.reconnectAttempts-1),this.maxReconnectDelay);cs.info("[ws] Scheduling reconnect",{attempt:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts,delayMs:e}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect().catch(e=>{cs.warn("[ws] Reconnect failed",{error:e instanceof Error?e.message:String(e)})})},e)}isConnected(){return!!this.socket&&this.socket.readyState===ve.OPEN&&this.isAuthenticated}sendProgress(e){if(this._isClosed)return void cs.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?(cs.info("[ws] sendProgress: flushing terminal state immediately"),void this.flushPending()):void(this.debounceTimer||(this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.flushPending()},this.debounceMs))):(cs.debug("[ws] sendProgress: not connected, queuing event",{phase:e.phase,socketState:this.socket?.readyState,isAuthenticated:this.isAuthenticated,reconnectAttempts:this.reconnectAttempts}),void(this.socket?.readyState===ve.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 cs.debug("[ws] flushPending: not connected, re-queuing event",{phase:e.payload.phase}),void(this.pendingEvent=e);cs.debug("[ws] flushPending: sending event",{phase:e.payload.phase});const t=new Promise(t=>{try{this.socket?.send(JSON.stringify(e),n=>{n&&(cs.warn("[ws] flushPending: send failed",{error:n.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e)),t()})}catch(n){cs.warn("[ws] flushPending: send threw",{error:n instanceof Error?n.message:String(n)}),this.pendingEvent=e,t()}}).finally(()=>{this.flushPromise===t&&(this.flushPromise=null)});this.flushPromise=t}static FLUSH_TIMEOUT_MS=5e3;async flushPendingAndWait(){if(this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.flushPromise&&await Promise.race([this.flushPromise,new Promise(t=>setTimeout(t,e.FLUSH_TIMEOUT_MS).unref())]),!this.pendingEvent)return;const t=this.pendingEvent;if(this.pendingEvent=null,!this.isConnected())return cs.warn("[ws] flushPendingAndWait: not connected, event will be dropped",{phase:t.payload.phase}),void(this.pendingEvent=t);const n=new Promise(e=>{try{cs.debug("[ws] flushPendingAndWait: sending event",{phase:t.payload.phase}),this.socket?.send(JSON.stringify(t),n=>{n&&(cs.warn("[ws] flushPendingAndWait: send failed",{error:n.message,phase:t.payload.phase}),this.pendingEvent||(this.pendingEvent=t)),e()})}catch(n){cs.warn("[ws] flushPendingAndWait: send threw",{error:n instanceof Error?n.message:String(n)}),this.pendingEvent=t,e()}});await Promise.race([n,new Promise(t=>setTimeout(t,e.FLUSH_TIMEOUT_MS).unref())])}close(){if(this._isClosed)return;cs.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)}async closeAndWait(){if(this._isClosed)return;cs.info("[ws] Closing WebSocket client and waiting for pending send"),this._isClosed=!0,this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),await this.flushPendingAndWait();const{socket:e}=this;this.socket=void 0,e&&(await new Promise(e=>setTimeout(e,200)),e.close())}},Rs=class e{socket;url;authProvider;orgId;sessionId;pendingEvent=null;reconnectAttempts=0;reconnectTimer;flushPromise=null;debounceTimer;_isClosed=!1;isAuthenticated=!1;authenticationFailed=!1;onUserMessage;maxReconnectAttempts=10;baseReconnectDelay=2e3;maxReconnectDelay=3e4;debounceMs=500;get isClosed(){return this._isClosed}constructor({authProvider:e,orgId:t,sessionId:n,url:r=br,onUserMessage:s}){this.authProvider=e,this.orgId=t,this.sessionId=n,this.url=r,this.onUserMessage=s,cs.info("[ws] Constructing CreateProgressWebSocketClient",{url:this.url,sessionId:n})}async start(){await this.connect()}async connect(){if(!this._isClosed)try{const e=await this.authProvider.getAuthHeader();if(this._isClosed)return;const t={Authorization:e};this.orgId&&(t["x-stably-org-id"]=this.orgId);const n=`${this.url}?sessionId=${encodeURIComponent(this.sessionId)}`;cs.info("[ws] Connecting",{url:n,attempt:this.reconnectAttempts}),this.socket=new ve(n,{headers:t}),this.socket.on("open",()=>{cs.info("[ws] Connection opened"),this.reconnectAttempts=0}),this.socket.on("message",e=>{try{const t="string"==typeof e?e:e.toString(),n=JSON.parse(t);cs.debug("[ws] Received message",{type:n?.type}),"connected"===n?.type&&(cs.info("[ws] Authenticated successfully"),this.isAuthenticated=!0,this.authenticationFailed=!1,this.flushPending()),"user_message"===n?.type&&"string"==typeof n.content&&(cs.info("[ws] Received user message from web UI"),this.onUserMessage?.(n.content))}catch{}}),this.socket.on("close",(e,t)=>{cs.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=>{cs.warn("[ws] Connection error",{error:e.message})})}catch(e){cs.warn("[ws] Failed to create WebSocket",{error:e instanceof Error?e.message:String(e)}),this.scheduleReconnect()}}scheduleReconnect(){if(this._isClosed||this.reconnectTimer)return;this.reconnectAttempts++;const e=Math.min(this.baseReconnectDelay*Math.pow(2,this.reconnectAttempts-1),this.maxReconnectDelay);cs.info("[ws] Scheduling reconnect",{attempt:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts,delayMs:e}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect().catch(e=>{cs.warn("[ws] Reconnect failed",{error:e instanceof Error?e.message:String(e)})})},e)}isConnected(){return!!this.socket&&this.socket.readyState===ve.OPEN&&this.isAuthenticated}sendProgress(e){if(this._isClosed)return void cs.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?(cs.info("[ws] sendProgress: flushing terminal state immediately"),void this.flushPending()):void(this.debounceTimer||(this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.flushPending()},this.debounceMs))):(cs.debug("[ws] sendProgress: not connected, queuing event",{phase:e.phase,socketState:this.socket?.readyState,isAuthenticated:this.isAuthenticated,reconnectAttempts:this.reconnectAttempts}),void(this.socket?.readyState===ve.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 cs.debug("[ws] flushPending: not connected, re-queuing event",{phase:e.payload.phase}),void(this.pendingEvent=e);cs.debug("[ws] flushPending: sending event",{phase:e.payload.phase});const t=new Promise(t=>{try{this.socket?.send(JSON.stringify(e),n=>{n&&(cs.warn("[ws] flushPending: send failed",{error:n.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e)),t()})}catch(n){cs.warn("[ws] flushPending: send threw",{error:n instanceof Error?n.message:String(n)}),this.pendingEvent=e,t()}}).finally(()=>{this.flushPromise===t&&(this.flushPromise=null)});this.flushPromise=t}static FLUSH_TIMEOUT_MS=5e3;async flushPendingAndWait(){if(this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.flushPromise&&await Promise.race([this.flushPromise,new Promise(t=>setTimeout(t,e.FLUSH_TIMEOUT_MS).unref())]),!this.pendingEvent)return;const t=this.pendingEvent;if(this.pendingEvent=null,!this.isConnected())return cs.warn("[ws] flushPendingAndWait: not connected, event will be dropped",{phase:t.payload.phase}),void(this.pendingEvent=t);const n=new Promise(e=>{try{cs.debug("[ws] flushPendingAndWait: sending event",{phase:t.payload.phase}),this.socket?.send(JSON.stringify(t),n=>{n&&(cs.warn("[ws] flushPendingAndWait: send failed",{error:n.message,phase:t.payload.phase}),this.pendingEvent||(this.pendingEvent=t)),e()})}catch(n){cs.warn("[ws] flushPendingAndWait: send threw",{error:n instanceof Error?n.message:String(n)}),this.pendingEvent=t,e()}});await Promise.race([n,new Promise(t=>setTimeout(t,e.FLUSH_TIMEOUT_MS).unref())])}close(){if(this._isClosed)return;cs.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)}async closeAndWait(){if(this._isClosed)return;cs.info("[ws] Closing WebSocket client and waiting for pending send"),this._isClosed=!0,this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),await this.flushPendingAndWait();const{socket:e}=this;this.socket=void 0,e&&(await new Promise(e=>setTimeout(e,200)),e.close())}},Us=we.object({bucketPath:Es,expiresInSeconds:we.number(),key:we.string(),uploadUrl:we.string()}),$s=we.object({uploadUrl:we.string(),key:we.string(),bucketPath:we.object({bucket:we.string(),key:we.string()}),expiresInSeconds:we.number()}),Ls=we.object({success:we.boolean()});async function Ds({authHeader:e,orgId:t,sessionId:n,projectId:r,history:s}){if(0===s.length)return cs.debug("[session-history] No history to upload"),{success:!0};try{(async()=>{const o=await(i={auth:e,body:{history:s,...r?{projectId:r}:{}},client:vr(),headers:Ts(t),path:{sessionId:n},signal:AbortSignal.timeout(3e4)},(i.client??cr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/sessions/{sessionId}/history/hot-store",...i,headers:{"Content-Type":"application/json",...i.headers}}));var i;if(o.error)throw new Error(`Hot store mirror failed (${o.response.status})`);Ls.parse(o.data)})().catch(e=>{cs.warn("[session-history] Failed to mirror history to hot store",{error:e instanceof Error?e.message:String(e)})}),cs.info("[session-history] Requesting upload URL",{sessionId:n,messageCount:s.length});const{uploadUrl:o,key:i}=await async function({authHeader:e,orgId:t,sessionId:n,projectId:r}){const s=await(o={auth:e,body:{contentType:"application/x-ndjson",...r?{projectId:r}:{}},client:vr(),headers:Ts(t),path:{sessionId:n},signal:AbortSignal.timeout(3e4)},(o.client??cr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/sessions/{sessionId}/history/upload-url",...o,headers:{"Content-Type":"application/json",...o.headers}}));var o;if(s.error)throw new Error(`Failed to get history upload URL (${s.response.status})`);return $s.parse(s.data)}({authHeader:e,orgId:t,sessionId:n,projectId:r}),a=s.map(e=>JSON.stringify(e)).join("\n");cs.info("[session-history] Uploading history",{key:i,messageCount:s.length,sizeBytes:a.length});const c=await fetch(o,{method:"PUT",body:a,headers:{"Content-Type":"application/x-ndjson"},signal:AbortSignal.timeout(6e4)});if(!c.ok)throw new Error(`Upload failed with status ${c.status}`);return cs.info("[session-history] History uploaded successfully",{key:i}),{success:!0,key:i}}catch(e){const t=e instanceof Error?e.message:String(e);return cs.warn("[session-history] Failed to upload history",{error:t}),{success:!1,error:t}}}var Ns="1.58.0",Os=["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 Bs(e){return/^\.env(\..*)?$/.test(e)||".stably-agent.env"===e}function js(e){return Boolean(e&&"object"==typeof e&&"tool_input"in e&&e.tool_input&&"object"==typeof e.tool_input)}function Ms({action:e,pathKey:t}){return function({action:e,fileCheck:t,getBlockMessage:n,pathKey:r}){return async s=>{const o=function({input:e,pathKey:t}){if(!js(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 n=e.tool_input;return t in n?"string"==typeof n[t]?{path:n[t],success:!0}:{decision:"block",reason:`Invalid tool call format: The '${t}' parameter must be a string containing the file path, but received ${typeof n[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:s,pathKey:r});if(!o.success)return o;const i=o.path.replace(/\\/g,"/"),a=i.split("/").pop()||i;return t(a)?{decision:"block",reason:n("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:Bs,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 Fs=["rm","mv","git","gh","npx","stably","stably-browser","pwtrace","npm","yarn","pnpm","bun"],Hs=["stably","playwright","stably-browser","pwtrace"],Gs=["create","fix","verify"],Ws=["upload"],Vs=["push","fetch","pull","clone","ls-remote"],Ys=/\S+=(?:\"[^\"\\]*(?:\\.[^\"\\]*)*\"|'[^']*(?:'\\''[^']*)*'|\S+)/;function zs(e){let t="",n=!1,r=!1,s=!1;for(let o=0;o<e.length;o++){const i=e[o];s?(t+=i,s=!1):"\\"!==i||r?'"'!==i||r?"'"!==i||n?t+=i:r=!r:n=!n:s=!0}return t}function qs(e){const t=[],n=e.trim(),r=/(?:[^\s"']+|"[^"\\]*(?:\\.[^"\\]*)*"|'[^']*(?:'\\''[^']*)*')+/g;let s;for(;null!==(s=r.exec(n));)t.push(s[0]);return t}function Ks(e){let t=0;const n=new RegExp(`^${Ys.source}$`);for(;t<e.length&&n.test(e[t]??"");)t+=1;return e.slice(t)}function Js(e){const t=Ks(qs(e));if("npx"===t[0])for(let e=1;e<t.length;e+=1){const n=t[e];if(n){if("--"===n)return t[e+1];if(!n.startsWith("-"))return zs(n)}}}function Xs(e){return qs(e).map(zs).find(e=>Gs.includes(e))}function Qs(e,t){const n=c(e).replace(/\\/g,"/"),r=t.replace(/\\/g,"/"),s=r.endsWith("/")?r:`${r}/`;if(n.startsWith(s))return!0;const o=n.lastIndexOf(`/${s}`);if(-1===o)return!1;const i=n.slice(o+`/${s}`.length);return i.length>0&&!i.startsWith("../")}function Zs({onBeforeGitHubCommand:e,workspaceBoundary:t,allowBackgroundRunTest:n=!1}){return async r=>{if(!js(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 i=r.tool_input,{command:c}=i;if("string"!=typeof c)return{decision:"block",reason:"Invalid Bash command: command must be a string.",systemMessage:"Tool call blocked due to invalid command type"};const l=function(e){const t=e.trim(),n=new RegExp(`^(?:${Ys.source}\\s+)*(\\S+)`),r=t.match(n);return r?.[1]}(c);if(!l)return{decision:"block",reason:"Invalid Bash command: could not parse command.",systemMessage:"Tool call blocked due to unparseable command"};if(!n&&"run_in_background"in i&&!0===i.run_in_background&&/\bstably-browser\s+(?:(?:-\w+=?\S*|--\w+=?\S*|-s\s+\S+|--session\s+\S+)\s+)*run-test\b/.test(c))return{decision:"block",reason:"Running `stably-browser run-test` with `run_in_background: true` is not allowed. Test runs must execute in the foreground so their output can be captured and parsed. Remove the `run_in_background` parameter and run the test normally.",systemMessage:"Tool call blocked due to run-test in background"};if(!function(e){return"string"==typeof e&&Fs.includes(e)}(l))return{decision:"block",reason:`The command "${l}" is not allowed. Only the following commands are permitted: ${Fs.join(", ")}. Use the appropriate tools (Read, Write, Edit, Glob, Grep) for file operations instead.`,systemMessage:"Tool call blocked due to disallowed command"};if("npx"===l){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 ...`."};const t=Js(e);if(!t)return{valid:!1,reason:"Invalid npx command: unable to determine which binary is being executed."};if(!new Set(Hs).has(t))return{valid:!1,reason:`The npx binary "${t}" is not allowed. Only ${Hs.join(", ")} are permitted.`};if("stably"===t){const n=Xs(e);if(n)return{valid:!1,reason:`The npx ${t} subcommand "${n}" is not allowed. The commands ${Gs.join(", ")} are AI-powered and blocked to prevent recursion.`}}return{valid:!0}}(c);if(!e.valid)return{decision:"block",reason:e.reason,systemMessage:"Tool call blocked due to disallowed npx command"}}if("stably-browser"===l||"npx"===l&&"stably-browser"===Js(c)){const e=function({command:e,binary:t}){const n=Ks(qs(e)),r=n.findIndex(e=>e===t);if(-1!==r)for(let e=r+1;e<n.length;e+=1){const t=n[e];if(t&&!t.startsWith("-"))return zs(t)}}({command:c,binary:"stably-browser"});if(e&&Ws.includes(e))return{decision:"block",reason:`The stably-browser subcommand "${e}" is not allowed. The "upload" command can read arbitrary files and is blocked for security.`,systemMessage:"Tool call blocked due to disallowed stably-browser subcommand"}}if("stably"===l){const e=Xs(c);if(e)return{decision:"block",reason:`The stably subcommand "${e}" is not allowed. The commands ${Gs.join(", ")} are AI-powered and blocked to prevent recursion.`,systemMessage:"Tool call blocked due to disallowed stably command"}}if("rm"===l){const e=function(e){const t=e.trim().match(/^rm\s+(?:-[a-zA-Z]+\s+|--[a-zA-Z-]+\s+)*(.+)$/),n=t?.[1]?.trim();return n?n.split(/\s+/).filter(e=>e.length>0):[]}(c);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 n=e.filter(e=>!function({targetPath:e,boundaryDir:t}){const n=function(e){if(E(e))return k.native(e);let t=e;const n=[];for(;!E(t);){const r=o(t);if(r===t)return s(e);n.unshift(t.slice(r.length+1)),t=r}const r=k.native(t);return n.length>0?s(r,...n):r}(e),r=k.native(t),i=n.endsWith(a)?n:n+a,c=r.endsWith(a)?r:r+a;return i.startsWith(c)||n===r}({targetPath:s(t,e),boundaryDir:t}));if(n.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: ${n.join(", ")}.`,systemMessage:"Tool call blocked due to rm outside workspace"}}else{const t=e.filter(e=>!(Qs(e,"tests")||Qs(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"===l&&["-c","--config","--config-env"].some(e=>c.includes(` ${e} `)||c.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"===l&&function(e){const t=e.trim();return!!t.startsWith("git ")&&Vs.some(e=>t.includes(` ${e}`)||t.includes(`git ${e}`))}(c)&&e)try{await e()}catch(e){console.error("[BashSecurityHook] Failed to refresh git token:",e)}if("gh"===l){const t=function(e){const t=e.toLowerCase();return Os.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}}(c);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 eo=/\.(spec|test)\.(ts|tsx|js|jsx|mts|mjs)$/;function to({onFileCreated:e}){return async t=>{const n=(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),r=n?.file_path;return"string"==typeof r&&eo.test(r)&&e(r),{decision:"approve"}}}var no=M(f);async function ro(){try{const{stdout:e}=await no('pgrep -f "playwright run-test-mcp-server" 2>/dev/null || true'),t=e.trim();if(!t)return;const n=t.split("\n").filter(Boolean);await Promise.allSettled(n.map(async e=>{await no(`pkill -KILL -P ${e} '.*' 2>/dev/null || true`)}))}catch{}}var so=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}drainQueue(){return this.queue.splice(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 oo(e){try{const t=h("git branch --show-current",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(!t)return;return{branch:t}}catch{return}}var io=[".ts",".js",".mts",".mjs",".cts",".cjs"],ao=10240,co=async({defaultContent:e,fileName:t,filePath:n})=>{try{const e=(await Z(n)).size,r=await z(n,"utf-8"),s=Buffer.byteLength(r,"utf-8");if(s<=ao)return r;const o=(e=>{const t=e.split("\n"),n=[];let r=!1,s=!1,o=0,i=!1;for(let e=0;e<t.length;e++){const a=t[e],c=a.trim();c.startsWith("/*")&&(r=!0),c.includes("*/")?r=!1:r||c.startsWith("//")&&!c.startsWith("///")||(c.startsWith("import ")||c.startsWith("export ")?(n.push(a),i=!0):i&&""===c?(n.push(a),i=!1):(i=!1,c.startsWith("type ")||c.startsWith("interface ")?n.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(")?(n.push(a),s=!0,o=(a.match(/{/g)||[]).length-(a.match(/}/g)||[]).length,0===o&&(c.endsWith(";")||c.endsWith(","))&&(s=!1)):s?(o+=(a.match(/{/g)||[]).length,o-=(a.match(/}/g)||[]).length,0===o&&c.includes("}")?(n.push(a),s=!1):o>0&&" // ... implementation omitted ..."!==n.at(-1)&&n.push(" // ... implementation omitted ...")):c.match(/^[a-zA-Z_]+:/)&&n.push(a)))}return n.join("\n")})(r),i=Buffer.byteLength(o,"utf-8");return i<=ao?o:o.slice(0,ao)+`\n\n... [TRUNCATED: File "${t}" at ${n} was ${e} bytes (${s} bytes as UTF-8), reduced to ~${i} bytes of essential content, then truncated to 10240 bytes] ...`}catch(n){let r;if(n&&"object"==typeof n&&"code"in n){const e=n.code;"string"==typeof e&&(r=e)}return"ENOENT"!==r&&console.warn(`Failed to read ${t}: ${n}`),e}},lo=async({defaultContent:e,dirName:t,dirPath:n})=>{try{const e=await Q(n);return e.length>0?e.join("\n"):"(empty)"}catch(n){let r;if(n&&"object"==typeof n&&"code"in n){const e=n.code;"string"==typeof e&&(r=e)}return"ENOENT"!==r&&console.warn(`Failed to read ${t}: ${n}`),e}},uo=async({allowedEnvVars:e,mode:t,workspaceInfo:n,authHeader:r,customHeader:s,maxParallelWorkers:o,isCloudBrowser:i})=>{const a=vr(),c=oo(n.absolutePath);cs.debug("Requesting system prompt from API",{mode:t,hasGitContext:!!c,envVarCount:e.length});const l=await(u={client:a,auth:r,body:{mode:t,workspaceInfo:n,allowedEnvVars:e,gitContext:c,maxParallelWorkers:o,isCloudBrowser:i}},(u.client??cr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/prompts/system",...u,headers:{"Content-Type":"application/json",...u.headers}}));var u;if(401===l.response.status)throw cs.warn("System prompt fetch failed: unauthorized (401)"),await Nr(),new Error("Your session has expired or been revoked. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(403===l.response.status)throw cs.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(l.error){cs.warn("System prompt fetch failed",{error:l.error});const e=JSON.stringify(l.error);if(e.toLowerCase().includes("unauthorized")||e.toLowerCase().includes("unauthenticated"))throw await Nr(),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 d=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:l.data.systemPrompt,customHeader:s});return cs.debug("System prompt received",{size:d.length,appendedCustomHeader:!!s,hasPrContext:!!l.data.prContext}),{systemPrompt:d,prContext:l.data.prContext}},po={chat:"chat",single:"create",fix:"fix",init:"init",verify:"verify",plan:"plan"};async function fo({agentMode:e,authHeader:t,orgId:n,projectId:r,runId:s,fetchImpl:o=fetch,apiUrl:i=pr}){const a=po[e],c=new URL("/internal/v1/cli/progress",i).toString(),l={Authorization:t,"Content-Type":"application/json","X-STABLY-CLI-VERSION":dr};n&&(l["x-stably-org-id"]=n);const u=await o(c,{method:"POST",headers:l,body:JSON.stringify({mode:a,projectId:r,agentId:oe.randomUUID(),..."fix"===a&&s?{playwrightSuiteRunId:s}:{}}),signal:AbortSignal.timeout(1e4)});if(!u.ok){const e=await u.text().catch(()=>"");throw new Error(`Failed to create progress session: ${u.status} ${c} β ${e.slice(0,300)}`)}const{sessionId:d}=await u.json();return{sessionId:d,sessionMode:a}}var ho=".stably-internal.playwright",go=`${ho}-wrapper.config.*`,mo="STABLY_INTERNAL_EXECUTION",yo=[".ts",".js",".mts",".mjs",".cts",".cjs"];function bo(e){const t=s(e);if(E(t))for(const e of yo){const n=i(t,`playwright.config${e}`);if(E(n))return n}}var wo=["tests","e2e","__tests__","test"];function vo(e){try{return E(e)&&S(e).isDirectory()}catch{return!1}}function Io(e,t){const n="output-flag"===t?"--output flag":"playwright.config.ts"===t?"playwright.config.ts":"auto-detected"===t?"auto-detected":"cwd fallback";console.error(re.dim(`Using output directory: ${e} (from ${n})`))}var To=["mcp__playwright-test__","mcp__auto-heal-report__","mcp__stably-agent-control__"],_o=["planner_","generator_"],Eo={open:e=>e?`Open ${e}`:"Open browser",close:()=>"Close browser",snapshot:()=>"Page snapshot",screenshot:()=>"Screenshot",click:e=>`Click ${e}`,fill:e=>`Fill ${e.split(/\s+/)[0]||""}`.trim(),type:e=>`Type into ${e.split(/\s+/)[0]||""}`.trim(),hover:e=>`Hover ${e}`,goto:e=>`Navigate to ${e}`,select:e=>`Select option in ${e.split(/\s+/)[0]||""}`.trim(),check:e=>`Check ${e}`,uncheck:e=>`Uncheck ${e}`,back:()=>"Go back",forward:()=>"Go forward","run-test":e=>`Run test ${e}`,"run-code":()=>"Run code","run-file":e=>`Run file ${e}`,"tab-list":()=>"List tabs","tab-new":e=>e?`New tab ${e}`:"New tab","tab-select":e=>`Select tab ${e}`,"tab-close":()=>"Close tab",eval:()=>"Evaluate JavaScript",upload:()=>"Upload file","state-save":()=>"Save browser state","state-load":()=>"Load browser state"},So={"stably-browser":"Loading browser command reference","stably-cli":"Loading CLI reference","browser-interaction-guide":"Loading browser interaction guide","playwright-config-auth":"Loading project configuration","playwright-cli":"Loading browser command reference","bash-commands":"Loading command reference","stably-sdk-reference":"Loading SDK reference","test-creation-workflow":"Loading test creation guide","bulk-test-handling":"Loading bulk test guide","debugging-test-failures":"Loading debugging guide","recorded-actions-handling":"Loading recorded actions guide","playwright-best-practices":"Loading best practices","pwtrace-debugging":"Loading trace debugging guide","ai-to-programmatic-migration":"Loading migration guide"},xo={Skill:"Preparing for task",ToolSearch:"Searching tools"},Ao=(e,t)=>{const n=t.find(t=>e.startsWith(t));return n?e.slice(n.length):e},ko=e=>e.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" "),Co=(e,t)=>{if(!t||"object"!=typeof t)return;const n=t,r="string"==typeof n.intent?n.intent:void 0;if("Read"!==e&&"Write"!==e&&"Edit"!==e){if("Glob"===e||"Grep"===e)return"string"==typeof n.pattern?n.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=n.test;return"string"==typeof e?.title?e.title:void 0}return"mcp__playwright-test__generator_setup_page"===e||"generator_setup_page"===e?"string"==typeof n.seedFile?n.seedFile:"tests/seed.spec.ts":"mcp__playwright-test__generator_write_test"===e||"generator_write_test"===e?"string"==typeof n.fileName?n.fileName:void 0:"Bash"===e?"string"==typeof n.command?n.command.length>50?`${n.command.slice(0,50)}...`:n.command:void 0:e.includes("browser_navigate")&&!e.includes("back")?"string"==typeof n.url?n.url:r:e.includes("browser_type")?("string"==typeof n.text?`"${n.text}"`:void 0)??r:e.includes("browser_click")?"string"==typeof n.element?n.element:r:e.includes("browser_wait_for")?"string"==typeof n.text?`text: "${n.text}"`:"number"==typeof n.time?`${n.time}ms`:r:e.includes("verify_text")?"string"==typeof n.text?`"${n.text}"`:r:e.includes("verify_element")?"string"==typeof n.accessibleName?n.accessibleName:r:e.includes("screenshot")&&"string"==typeof n.filename?n.filename:r}if(Array.isArray(n.locations)){const e=n.locations.filter(e=>"string"==typeof e);return e.length>0?e.join(", "):void 0}}else if("string"==typeof n.file_path)return n.file_path.split("/").at(-1)??void 0},Po=(e,t)=>{if(!t||"object"!=typeof t)return null;const n=t;if("Skill"===e){const e="string"==typeof n.skill?n.skill:void 0;if(e){const t=e.includes(":")?e.split(":").pop():e;return So[t]?So[t]:`Loading ${t.replace(/-/g," ")}`}return"Preparing for task"}if("Bash"===e&&"string"==typeof n.description&&n.description.trim())return n.description.trim();if("Bash"===e&&"string"==typeof n.command){const e=n.command.match(/(?:^|\s)(?:[\w/.-]*\/)?stably-browser\s+(?:--\S+\s+)*(\S+)(.*)/);if(!e)return null;const[,t,r]=e,s=r.trim().replace(/--\S+=?\S*\s*/g,"").trim(),o=Eo[t];return o?o(s):`${ko(t)}${s?` ${s.split(/\s+/)[0]}`:""}`.trim()}return"Read"===e&&"string"==typeof n.file_path&&(n.file_path.includes(".stably-browser/")||n.file_path.includes(".playwright-cli/"))&&n.file_path.endsWith(".yml")?"Page snapshot":"TaskOutput"===e?!0===n.block?"Waiting for background task":"Checking background task":null},Ro=e=>"mcp__auto-heal-report__upload-trace-proof"===e||"mcp__upload-trace-proof__upload-trace-proof"===e?"Upload Trace":"mcp__auto-heal-report__generate-report"===e?"Generate Report":(e=>{const t=xo[e];if(t)return t;const n=Ao(e,To),r=Ao(n,_o);return ko(r)})(e),Uo=(e,t)=>{if(t<=0)return 0;let n=t-1;for(;n>0&&/\s/.test(e[n]);)n--;for(;n>0&&!/\s/.test(e[n-1]);)n--;return n},$o=(e,t)=>{if(t>=e.length)return e.length;let n=t;for(;n<e.length&&!/\s/.test(e[n]);)n++;for(;n<e.length&&/\s/.test(e[n]);)n++;return n},Lo=(e,t)=>{if(t<=0)return 0;const n=e.lastIndexOf("\n",t-1);return-1===n?0:n+1},Do=(e,t)=>{const n=e.indexOf("\n",t);return-1===n?e.length:n};function No(e){const t=e.split("\n");let n=!1;const r=[];for(const e of t){const t=e.trimStart();if(/^`{3,}[^`]*$/.test(t)){n=!n,r.push(Dn("muted",` ${"β".repeat(Math.max(0,Math.min((process.stdout.columns||80)-4,76)))}`));continue}if(n){r.push(`${Dn("muted"," β")} ${Dn("codeBlock",e)}`);continue}if(/^-{3,}\s*$/.test(t)){r.push(re.dim("β".repeat(Math.min(process.stdout.columns||80,80))));continue}const s=e.match(/^(#{1,6})\s+(.+)$/);if(s){const e=s[1].length,t=Oo(s[2]);1===e?r.push(re.bold(Dn("brand",t))):2===e?r.push(re.bold(t)):r.push(re.bold(re.dim(t)));continue}const o=e.match(/^>\s*(.*)$/);if(o){r.push(re.dim(`β ${Oo(o[1])}`));continue}const i=e.match(/^(\s*)[-*]\s+(.+)$/);if(i){const e=i[1]||"";r.push(`${e} β ${Oo(i[2])}`);continue}const a=e.match(/^(\s*)(\d+)\.\s+(.+)$/);if(a){const e=a[1]||"";r.push(`${e} ${a[2]}. ${Oo(a[3])}`);continue}r.push(Oo(e))}return r.join("\n")}function Oo(e){return(e=(e=(e=e.replace(/\*\*(.+?)\*\*/g,(e,t)=>re.bold(t))).replace(/__(.+?)__/g,(e,t)=>re.bold(t))).replace(/(?<!\*)\*([^*]+?)\*(?!\*)/g,(e,t)=>re.italic(t))).replace(/`([^`]+)`/g,(e,t)=>Dn("inlineCode",t))}var Bo,jo=async(e,t)=>{const{Box:n,Static:r,Text:s,render:o,useInput:i}=await import("ink"),a=!!process.stdin.isTTY,c="vscode"!==process.env.TERM_PROGRAM,l=["β ","β ","β Ή","β Έ","β Ό","β ΄","β ¦","β §","β ","β "],u=()=>xe(s,{inverse:!0,children:" "}),d=(({Box:e,Text:t,useInput:n},r,s)=>function({onChoice:o,prompt:i}){const[a,c]=Ie(0),[l,u]=Ie(!1),[d,p]=Ie(""),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"}];n((e,t)=>{if(l)return t.return?void o("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 o(e.value)}const n=parseInt(e,10);if(n>=1&&n<=f.length){const e=f[n-1];if("deny_with_message"===e.value)return void u(!0);o(e.value)}},{isActive:s});const h=Ro(i.toolName),g=Co(i.toolName,i.input);return Ae(e,{borderColor:Ln("accent"),borderStyle:"round",flexDirection:"column",marginTop:1,paddingX:1,paddingY:0,children:[xe(t,{bold:!0,color:Ln("accent"),children:"Permission Required"}),Ae(e,{flexDirection:"column",marginTop:1,children:[xe(t,{color:Ln("muted"),dimColor:!0,children:h}),null!=g&&Ae(t,{color:Ln("muted"),children:[" ",g]})]}),null!=i.decisionReason&&xe(e,{marginTop:1,children:Ae(t,{color:Ln("muted"),children:["Reason: ",i.decisionReason]})}),Ae(e,l?{flexDirection:"column",marginTop:1,children:[xe(t,{color:Ln("muted"),children:"Enter message for AI (press Enter to submit, Esc to cancel):"}),Ae(t,{children:[xe(t,{color:Ln("accent"),children:"β―"})," ",d,xe(r,{})]})]}:{flexDirection:"column",marginTop:1,children:[xe(t,{color:Ln("muted"),children:"Use ββ arrows or number keys to select:"}),f.map((e,n)=>xe(t,{children:Ae(t,{color:n===a?Ln("accent"):void 0,children:[n===a?"β―":" "," ",n+1,". ",e.label]})},e.value))]})]})})({Box:n,Text:s,useInput:i},u,a),p=(({Cursor:e,inkComponents:{Box:t,Static:n,Text:r,useInput:s},isRawModeSupported:o,PermissionPrompt:i,Spinner:a})=>{const c="vscode"!==process.env.TERM_PROGRAM,l=e=>"tool"===e.kind?Ae(r,{color:Ln("subtle"),children:["β¦ ",e.content]},e.id):"tool_result"===e.kind||"text"===e.kind?xe(r,{color:Ln("muted"),children:e.content},e.id):null,u=({progress:e})=>{const[n,s]=Ie(Date.now());_e(()=>{if(!c)return;const e=setInterval(()=>s(Date.now()),1e3);return()=>clearInterval(e)},[]);const o=n-e.startedAt,i=Math.floor(o/1e3),a=Math.floor(i/60),l=i%60,u=a>0?`${a}m ${l.toString().padStart(2,"0")}s`:`${l}s`,d={initializing:{label:"Fetching test results",color:Ln("muted")},triage:{label:"Triaging failures",color:Ln("fixTriage")},fixing:{label:"Fixing tests",color:Ln("brand")},debugging:{label:"Debugging tests",color:Ln("fixDebug")},validation:{label:"Validating fixes",color:Ln("fixValidation")},complete:{label:"Complete",color:Ln("success")}},{label:p,color:f}=d[e.phase],h=e.fixedTests+e.failedTests,g=("fixing"===e.phase||"debugging"===e.phase)&&h>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 xe(t,{flexDirection:"column",children:Ae(r,{children:[xe(r,{color:f,bold:!0,children:p}),xe(r,{color:Ln("muted"),children:g}),Ae(r,{color:Ln("muted"),children:[" [",u,"]"]})]})})},d=({progress:e})=>{const n=e.endedAt??Date.now(),s=Math.floor((n-e.startedAt)/1e3),o=Math.floor(s/60),i=s%60,a=o>0?`${o}m ${i.toString().padStart(2,"0")}s`:`${i}s`,c=e.isError?Ln("accent"):Ln("success"),l=e.isError?"Fix stopped":"Fix complete";return Ae(t,{flexDirection:"column",children:[Ae(r,{color:c,bold:!0,children:[l," in ",a]}),null!==e.totalTests&&Ae(r,{color:Ln("muted"),children:[e.fixedTests,"/",e.totalTests," tests fixed",e.failedTests>0?`, ${e.failedTests} failed`:""]})]})},p=(e,n=!1,s)=>{if("subagent"===e.kind&&e.subagent){const{subagent:s}=e,o="complete"===s.status?Ln("success"):"error"===s.status?Ln("error"):Ln("accent");return Ae(t,{flexDirection:"column",marginTop:1,children:[Ae(r,{children:[xe(r,{color:o,bold:!0,children:"Agent"}),s.description?Ae(r,{color:Ln("muted"),children:[" (",s.description,")"]}):null]}),s.activities.length>0&&xe(t,{flexDirection:"column",marginLeft:2,children:(()=>{if(!n)return s.activities.map(e=>l(e));let e=0;const t=[];for(let n=s.activities.length-1;n>=0;n--){const r=s.activities[n];"tool"!==r.kind&&"tool_result"!==r.kind||("tool"===r.kind&&e++,e<=f&&t.unshift(r))}return t.map(e=>l(e))})()})]},e.id)}if("tool"===e.kind)return Ae(r,{color:Ln("subtle"),children:["β¦ ",e.content]},e.id);if("tool_result"===e.kind)return xe(r,{color:Ln("muted"),children:e.content},e.id);if("user"===e.kind)return xe(t,{marginTop:1,children:Ae(r,{color:Ln("userPrompt"),children:["You: ",e.content]})},e.id);const o="text"===e.kind&&("tool"===s||"tool_result"===s);if("thinking"===e.kind){const n=e.content.split("\n"),s=10,o=n.length>s?n.slice(-s):n;return xe(t,{flexDirection:"column",children:xe(r,{color:Ln("subtle"),children:o.join("\n")})},e.id)}return"cancelled"===e.kind?xe(r,{color:Ln("subtle"),children:e.content},e.id):"text"===e.kind?xe(t,{marginTop:o?1:0,children:xe(r,{children:No(e.content)})},e.id):xe(t,{children:xe(r,{children:e.content})},e.id)},f=3;return function({onCancel:c,onExit:l,onPermissionChoice:h,onSend:g,showSpinnerImmediately:m,state:y}){const[b,w]=Ie({value:"",cursor:0}),v=b.value,I=b.cursor,T=Te(!1),_=Te(void 0),[E,S]=Ie(!1),[x,A]=Ie(!1),k=Te(0),C=Te(!1),P=!!y.permissionPrompt,R=(({termProgram:e})=>"vscode"===e)({termProgram:process.env.TERM_PROGRAM}),U=y.log.at(-1),$=("text"===U?.kind||"thinking"===U?.kind)&&"running"===y.status,L=y.log.findIndex(e=>"subagent"===e.kind&&"running"===e.subagent?.status),D=-1!==L,N=y.activeThinkingLogIndex??-1,O=N>=0&&N<y.log.length-1,B=o&&!x,j=R?0:D?L:O?N:$?y.log.length-1:y.log.length,M=B&&"running"===y.status?Math.min(j,k.current):j;_e(()=>{y.log.length<k.current&&(k.current=0),M>k.current&&(k.current=M)},[y.log.length,M]);const F=y.log.slice(0,k.current),H=y.log.slice(k.current),G=B?F.filter(e=>"tool"!==e.kind&&"tool_result"!==e.kind&&"thinking"!==e.kind):F,W=(()=>{if(!B)return H;let e=0;const t=[];for(let n=H.length-1;n>=0;n--){const r=H[n];"tool"===r.kind||"tool_result"===r.kind||"thinking"===r.kind?("tool"===r.kind&&e++,e<=f&&t.unshift(r)):t.unshift(r)}return t})(),V=Ee(async()=>{T.current?(_.current&&clearTimeout(_.current),await(l?.()),process.exit(0)):(T.current=!0,S(!0),_.current=setTimeout(()=>{T.current=!1,S(!1)},2e3))},[l]);s((e,t)=>{t.ctrl&&"c"===e&&V().catch(()=>process.exit(1)),t.ctrl&&"o"===e&&A(e=>!e),t.escape&&"running"===y.status&&!P&&0===v.length&&c?.()},{isActive:o}),_e(()=>{if(P||!g)return;process.stdout.isTTY&&process.stdout.write("[?2004h");const e=e=>{const t=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n");t&&w(e=>({value:e.value.slice(0,e.cursor)+t+e.value.slice(e.cursor),cursor:e.cursor+t.length}))},t=t=>{const n=t.toString();if(n.includes("[200~")){C.current=!0;const t=n.slice(n.indexOf("[200~")+6),r=t.includes("[201~"),s=r?t.slice(0,t.indexOf("[201~")):t;return e(s),void(r&&setTimeout(()=>{C.current=!1},0))}if(n.includes("[201~")){const t=n.slice(0,n.indexOf("[201~"));return e(t),void setTimeout(()=>{C.current=!1},0)}C.current?e(n):"[1;5H"!==n&&"[1;5~"!==n?"[1;5F"!==n&&"[4;5~"!==n?"[H"!==n&&"[1~"!==n&&"OH"!==n&&"[7~"!==n?"[F"!==n&&"[4~"!==n&&"OF"!==n&&"[8~"!==n||w(e=>({...e,cursor:Do(e.value,e.cursor)})):w(e=>({...e,cursor:Lo(e.value,e.cursor)})):w(e=>({...e,cursor:e.value.length})):w(e=>({...e,cursor:0}))};return process.stdin.on("data",t),()=>{process.stdin.off("data",t),process.stdout.isTTY&&process.stdout.write("[?2004l")}},[P,g]),s((e,t)=>{if(!t.ctrl||"c"!==e){if(t.return){if(C.current)return;const e=v.trim();return e&&g?.(e),void w({value:"",cursor:0})}t.ctrl&&"w"===e||t.ctrl&&t.backspace?w(e=>{const t=Uo(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?w(e=>({...e,cursor:Uo(e.value,e.cursor)})):t.ctrl&&t.rightArrow||t.meta&&"f"===e?w(e=>({...e,cursor:$o(e.value,e.cursor)})):t.leftArrow?w(e=>({...e,cursor:Math.max(0,e.cursor-1)})):t.rightArrow?w(e=>({...e,cursor:Math.min(e.value.length,e.cursor+1)})):t.ctrl&&"a"===e?w(e=>({...e,cursor:Lo(e.value,e.cursor)})):t.ctrl&&"e"===e?w(e=>({...e,cursor:Do(e.value,e.cursor)})):t.escape&&v.length>0?w({value:"",cursor:0}):!e||t.ctrl||t.meta||t.escape||e.includes("")||/^\[./.test(e)||/^O[A-D]$/.test(e)||C.current||w(t=>({value:t.value.slice(0,t.cursor)+e+t.value.slice(t.cursor),cursor:t.cursor+e.length})):w(e=>e.cursor>0?{value:e.value.slice(0,e.cursor-1)+e.value.slice(e.cursor),cursor:e.cursor-1}:e)}},{isActive:o&&!!g&&!P});const Y=Se(()=>"running"===y.status?xe(a,{label:y.runningLabel??"Working"}):"success"!==y.status?xe(r,{color:Ln("error"),children:"β Failed"}):void 0,[y.runningLabel,y.status]),z=!(m||!g||"running"!==y.status||0!==y.log.length||y.resultText||y.errorText),q="running"===y.status&&!z||y.log.length>0||y.resultText||y.errorText||"running"!==y.status;return Ae(t,{flexDirection:"column",children:[R?Ae(t,{flexDirection:"column",flexShrink:0,children:[xe(r,{color:Ln("brand"),bold:!0,children:"Stably Agent"}),xe(t,{flexDirection:"column",marginTop:1,children:xe(r,{color:Ln("muted"),children:y.promptDisplay})})]}):xe(n,{items:["header"],children:()=>Ae(t,{flexDirection:"column",flexShrink:0,children:[xe(r,{color:Ln("brand"),bold:!0,children:"Stably Agent"}),xe(t,{flexDirection:"column",marginTop:1,children:xe(r,{color:Ln("muted"),children:y.promptDisplay})})]},"header")}),G.length>0&&xe(n,{items:G,children:(e,t)=>p(e,B,G[t-1]?.kind)}),W.length>0&&xe(t,{flexDirection:"column",children:W.map((e,t)=>{const n=t>0?W[t-1]?.kind:G.at(-1)?.kind;return p(e,B,n)})}),B&&H.length>W.length&&Ae(r,{color:Ln("subtle"),dimColor:!0,children:["β ",H.length-W.length," tool calls hidden (Ctrl+O to expand)"]}),x&&o&&xe(r,{color:Ln("subtle"),dimColor:!0,children:"β Showing all tool calls (Ctrl+O to collapse)"}),"error"===y.status&&y.errorText&&xe(t,{marginTop:1,children:xe(r,{color:Ln("error"),children:y.errorText})}),"success"===y.status&&y.resultText&&xe(t,{marginTop:1,children:xe(r,{children:y.resultText})}),q&&xe(t,{flexDirection:"column",flexShrink:0,marginTop:1,children:"running"===y.status&&y.fixProgress?Ae(t,{flexDirection:"column",children:[Ae(t,{children:[xe(a,{}),xe(r,{children:" "}),xe(u,{progress:y.fixProgress})]}),("fixing"===y.fixProgress.phase||"debugging"===y.fixProgress.phase)&&y.log.flatMap(e=>{const{subagent:n}=e;if("subagent"!==e.kind||"code-worker"!==n?.subagentType&&"browser-worker"!==n?.subagentType||"running"!==n.status)return[];const{activities:s}=n,o=s.filter(e=>"tool"===e.kind).length,i=s.at(-1),c=s.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 Ae(t,{flexDirection:"column",children:[Ae(r,{children:[" ",xe(a,{}),Ae(r,{color:Ln("muted"),children:[n.description||n.subagentType||"worker",o>0?` (${o} ${1===o?"cycle":"cycles"})`:""]})]}),c&&Ae(r,{color:Ln("subtle"),children:[" β¦ ",c.content]}),l&&Ae(r,{color:Ln("subtle"),children:[" ",l]})]},e.id)})]}):"success"!==y.status&&"error"!==y.status||!y.fixProgress?Y:xe(d,{progress:y.fixProgress})}),null!=y.permissionPrompt&&null!=h&&xe(i,{onChoice:h,prompt:y.permissionPrompt}),null!=g&&null==y.permissionPrompt&&!y.isExiting&&Ae(t,{borderColor:"gray",borderStyle:"round",flexDirection:"column",flexShrink:0,marginTop:1,paddingX:1,paddingY:0,children:[xe(r,{color:Ln("subtle"),children:"Type a message and press Enter. Press Escape to interrupt. Press Ctrl+C to exit."}),Ae(r,{children:[xe(r,{color:Ln("accent"),children:"β―"})," ",v.slice(0,I),xe(e,{}),v.slice(I)]})]}),E&&Ae(t,{marginTop:1,flexDirection:"column",children:[xe(r,{color:Ln("accent"),children:"Press Ctrl+C again to exit"}),Jr&&Ae(r,{color:Ln("subtle"),children:["Debug log: ",es]})]})]})}})({Cursor:u,inkComponents:{Box:n,Static:r,Text:s,useInput:i},isInitMode:t?.isInitMode,isRawModeSupported:a,PermissionPrompt:d,Spinner:({label:e})=>{const[t,n]=Ie(0);return _e(()=>{if(!c)return;const e=setInterval(()=>n(e=>(e+1)%l.length),80);return()=>clearInterval(e)},[]),Ae(s,{color:Ln("accent"),children:[l[t]," ",e]})}});let f=e;t?.isFixMode&&(f.fixProgress={phase:"initializing",totalTests:null,fixedTests:0,failedTests:0,currentTestDescription:null,lastTestDescription:null,startedAt:Date.now(),endedAt:null,isError:!1});const h={current:(e,t)=>{}},g=o(xe(p,{onCancel:t?.onCancel,onExit:t?.onExit,onPermissionChoice:(e,t)=>h.current(e,t),onSend:t?.onSend,showSpinnerImmediately:t?.showSpinnerImmediately,state:f}),{exitOnCtrlC:!1}),m=()=>{f={...f},g.rerender(xe(p,{onCancel:t?.onCancel,onExit:t?.onExit,onPermissionChoice:(e,t)=>h.current(e,t),onSend:t?.onSend,showSpinnerImmediately:t?.showSpinnerImmediately,state:f}))};let y=null;const b=()=>{y&&(clearTimeout(y),y=null),f.log=[...f.log],m()};let w=null;const v=({text:e})=>{e&&(f.log=[...f.log,{content:e,id:f.log.length,kind:"user"}],m())},I=new Map;return{addSubagentActivity:({toolUseId:e,kind:t,content:n})=>{const r=I.get(e);if(void 0===r)return void console.error("[addSubagentActivity] No entry index for toolUseId:",e);const s=f.log[r];if("subagent"===s?.kind&&s.subagent){if("text"===t){const e=s.subagent.activities.at(-1);"text"===e?.kind?e.content+=n:s.subagent.activities.push({id:s.subagent.activities.length,kind:"text",content:n.replace(/^\s*\n+/,"")})}else s.subagent.activities.push({id:s.subagent.activities.length,kind:t,content:n});f.log=[...f.log],m()}else console.error("[addSubagentActivity] Entry not found or not subagent:",{entryIndex:r,entryKind:s?.kind})},addSubagentStart:({toolUseId:e,subagentType:t,description:n})=>{const r=f.log.length;if(I.set(e,r),f.log=[...f.log,{content:"",id:r,kind:"subagent",subagent:{toolUseId:e,subagentType:t,description:n,status:"running",activities:[]}}],f.fixProgress)if("triage"===t&&"initializing"===f.fixProgress.phase)f.fixProgress={...f.fixProgress,phase:"triage"};else if("code-worker"===t){const e=(f.fixProgress.totalTests??0)+1,t=n||null;f.fixProgress={...f.fixProgress,phase:"fixing",totalTests:e,currentTestDescription:t,lastTestDescription:t??f.fixProgress.lastTestDescription}}else if("browser-worker"===t){const e=(f.fixProgress.totalTests??0)+1,t=n||null;f.fixProgress={...f.fixProgress,phase:"debugging",totalTests:e,currentTestDescription:t,lastTestDescription:t??f.fixProgress.lastTestDescription}}else"validation"===t?f.fixProgress={...f.fixProgress,phase:"validation",currentTestDescription:null}:"context"===t&&(f.fixProgress={...f.fixProgress,currentTestDescription:n||f.fixProgress.currentTestDescription});m()},addTool:({rawName:e,toolInput:t})=>{const n=Po(e,t),r=n??Ro(e),s=n?void 0:Co(e,t),o=s?`${r} (${s})`:r;f.log=[...f.log,{content:o,id:f.log.length,kind:"tool"}],m()},addToolResult:({message:e})=>{f.log=[...f.log,{content:e,id:f.log.length,kind:"tool_result"}],m()},appendCancelled:()=>{f.log=[...f.log,{content:"[Cancelled]",id:f.log.length,kind:"cancelled"}],m()},appendText:({text:e})=>{if(!e)return;const t=f.log.at(-1),n="text"!==t?.kind?e.replace(/^\s*\n+/,""):e;f.log="text"===t?.kind?[...f.log.slice(0,-1),{...t,content:`${t.content}${n}`}]:[...f.log,{content:n,id:f.log.length,kind:"text"}],m()},appendThinking:({text:e,forceNewBlock:t})=>{if(!e)return;const n=null!==w?f.log[w]:null;"thinking"!==n?.kind||t?(w=f.log.length,f.log=[...f.log,{content:e,id:f.log.length,kind:"thinking"}]):n.content+=e,f.activeThinkingLogIndex=w,y||(y=setTimeout(b,50))},appendUserMessage:v,cancelThinkingRender:()=>{y&&(clearTimeout(y),y=null)},cleanup:async()=>{const e=g.waitUntilExit();g.unmount(),await e},dismissPermissionPrompt:()=>{f.permissionPrompt&&(f.permissionPrompt.resolve({behavior:"deny",message:"Cancelled by user",interrupt:!0}),f.permissionPrompt=void 0,m())},flushThinkingRender:b,resetThinkingLogIndex:()=>{w=null,f.activeThinkingLogIndex=null},setExiting:()=>{f.isExiting=!0,m()},setRunningLabel:({label:e})=>{f.runningLabel=e,m()},setStatus:({error:e,result:t,status:n})=>{f.errorText=e,f.resultText=t,f.status=n,m()},setSubagentStatus:({toolUseId:e,status:t})=>{const n=I.get(e);if(void 0===n)return;const r=f.log[n];"subagent"===r?.kind&&r.subagent&&(r.subagent.status=t,!f.fixProgress||"code-worker"!==r.subagent.subagentType&&"browser-worker"!==r.subagent.subagentType||("complete"===t?f.fixProgress={...f.fixProgress,fixedTests:f.fixProgress.fixedTests+1,currentTestDescription:null}:"error"===t&&(f.fixProgress={...f.fixProgress,failedTests:f.fixProgress.failedTests+1,currentTestDescription:null})),f.log=[...f.log],m(),"complete"!==t&&"error"!==t||I.delete(e))},showPermissionPrompt:e=>new Promise(t=>{h.current=(n,r)=>{if(f.permissionPrompt=void 0,m(),"allow"===n)t({behavior:"allow",updatedInput:e.input});else if("always"===n)t({behavior:"allow",updatedInput:e.input,updatedPermissions:e.suggestions});else{const e=r??"User denied this action";v({text:e}),t({behavior:"deny",message:e,interrupt:!1})}},f.permissionPrompt={...e,resolve:t},m()}),updateFixProgress:t?.isFixMode?e=>{f.fixProgress&&(f.fixProgress={...f.fixProgress,...e},m())}:void 0}},Mo=ke("/");try{Bo=Mo("worker_threads").Worker}catch(e){}var Fo=Bo?function(e,t,n,r,s){var o=!1,i=new Bo(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 s(e,null)}).on("message",function(e){return s(null,e)}).on("exit",function(e){e&&!o&&s(new Error("exited with code "+e),null)});return i.postMessage(n,r),i.terminate=function(){return o=!0,Bo.prototype.terminate.call(i)},i}:function(e,t,n,r,s){setImmediate(function(){return s(new Error("async operations unsupported - update to Node 12+ (or Node 10-11 with the --experimental-worker CLI flag)"),null)});var o=function(){};return{terminate:o,postMessage:o}},Ho=Uint8Array,Go=Uint16Array,Wo=Int32Array,Vo=new Ho([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]),Yo=new Ho([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]),zo=new Ho([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),qo=function(e,t){for(var n=new Go(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];var s=new Wo(n[30]);for(r=1;r<30;++r)for(var o=n[r];o<n[r+1];++o)s[o]=o-n[r]<<5|r;return{b:n,r:s}},Ko=qo(Vo,2),Jo=Ko.b,Xo=Ko.r;Jo[28]=258,Xo[258]=28;var Qo,Zo=qo(Yo,0),ei=Zo.b,ti=Zo.r,ni=new Go(32768);for(oi=0;oi<32768;++oi)Qo=(61680&(Qo=(52428&(Qo=(43690&oi)>>1|(21845&oi)<<1))>>2|(13107&Qo)<<2))>>4|(3855&Qo)<<4,ni[oi]=((65280&Qo)>>8|(255&Qo)<<8)>>1;var ri=function(e,t,n){for(var r=e.length,s=0,o=new Go(t);s<r;++s)e[s]&&++o[e[s]-1];var i,a=new Go(t);for(s=1;s<t;++s)a[s]=a[s-1]+o[s-1]<<1;if(n){i=new Go(1<<t);var c=15-t;for(s=0;s<r;++s)if(e[s])for(var l=s<<4|e[s],u=t-e[s],d=a[e[s]-1]++<<u,p=d|(1<<u)-1;d<=p;++d)i[ni[d]>>c]=l}else for(i=new Go(r),s=0;s<r;++s)e[s]&&(i[s]=ni[a[e[s]-1]++]>>15-e[s]);return i},si=new Ho(288);for(oi=0;oi<144;++oi)si[oi]=8;for(oi=144;oi<256;++oi)si[oi]=9;for(oi=256;oi<280;++oi)si[oi]=7;for(oi=280;oi<288;++oi)si[oi]=8;var oi,ii=new Ho(32);for(oi=0;oi<32;++oi)ii[oi]=5;var ai=ri(si,9,0),ci=ri(si,9,1),li=ri(ii,5,0),ui=ri(ii,5,1),di=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},pi=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(7&t)&n},fi=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(7&t)},hi=function(e){return(e+7)/8|0},gi=function(e,t,n){return(null==t||t<0)&&(t=0),(null==n||n>e.length)&&(n=e.length),new Ho(e.subarray(t,n))},mi=["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"],yi=function(e,t,n){var r=new Error(t||mi[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,yi),!n)throw r;return r},bi=function(e,t,n,r){var s=e.length,o=r?r.length:0;if(!s||t.f&&!t.l)return n||new Ho(0);var i=!n,a=i||2!=t.i,c=t.i;i&&(n=new Ho(3*s));var l=function(e){var t=n.length;if(e>t){var r=new Ho(Math.max(2*t,e));r.set(n),n=r}},u=t.f||0,d=t.p||0,p=t.b||0,f=t.l,h=t.d,g=t.m,m=t.n,y=8*s;do{if(!f){u=pi(e,d,1);var b=pi(e,d+1,3);if(d+=3,!b){var w=e[(P=hi(d)+4)-4]|e[P-3]<<8,v=P+w;if(v>s){c&&yi(0);break}a&&l(p+w),n.set(e.subarray(P,v),p),t.b=p+=w,t.p=d=8*v,t.f=u;continue}if(1==b)f=ci,h=ui,g=9,m=5;else if(2==b){var I=pi(e,d,31)+257,T=pi(e,d+10,15)+4,_=I+pi(e,d+5,31)+1;d+=14;for(var E=new Ho(_),S=new Ho(19),x=0;x<T;++x)S[zo[x]]=pi(e,d+3*x,7);d+=3*T;var A=di(S),k=(1<<A)-1,C=ri(S,A,1);for(x=0;x<_;){var P,R=C[pi(e,d,k)];if(d+=15&R,(P=R>>4)<16)E[x++]=P;else{var U=0,$=0;for(16==P?($=3+pi(e,d,3),d+=2,U=E[x-1]):17==P?($=3+pi(e,d,7),d+=3):18==P&&($=11+pi(e,d,127),d+=7);$--;)E[x++]=U}}var L=E.subarray(0,I),D=E.subarray(I);g=di(L),m=di(D),f=ri(L,g,1),h=ri(D,m,1)}else yi(1);if(d>y){c&&yi(0);break}}a&&l(p+131072);for(var N=(1<<g)-1,O=(1<<m)-1,B=d;;B=d){var j=(U=f[fi(e,d)&N])>>4;if((d+=15&U)>y){c&&yi(0);break}if(U||yi(2),j<256)n[p++]=j;else{if(256==j){B=d,f=null;break}var M=j-254;if(j>264){var F=Vo[x=j-257];M=pi(e,d,(1<<F)-1)+Jo[x],d+=F}var H=h[fi(e,d)&O],G=H>>4;if(H||yi(3),d+=15&H,D=ei[G],G>3&&(F=Yo[G],D+=fi(e,d)&(1<<F)-1,d+=F),d>y){c&&yi(0);break}a&&l(p+131072);var W=p+M;if(p<D){var V=o-D,Y=Math.min(D,W);for(V+p<0&&yi(3);p<Y;++p)n[p]=r[V+p]}for(;p<W;++p)n[p]=n[p-D]}}t.l=f,t.p=B,t.b=p,t.f=u,f&&(u=1,t.m=g,t.d=h,t.n=m)}while(!u);return p!=n.length&&i?gi(n,0,p):n.subarray(0,p)},wi=function(e,t,n){n<<=7&t;var r=t/8|0;e[r]|=n,e[r+1]|=n>>8},vi=function(e,t,n){n<<=7&t;var r=t/8|0;e[r]|=n,e[r+1]|=n>>8,e[r+2]|=n>>16},Ii=function(e,t){for(var n=[],r=0;r<e.length;++r)e[r]&&n.push({s:r,f:e[r]});var s=n.length,o=n.slice();if(!s)return{t:ki,l:0};if(1==s){var i=new Ho(n[0].s+1);return i[n[0].s]=1,{t:i,l:1}}n.sort(function(e,t){return e.f-t.f}),n.push({s:-1,f:25001});var a=n[0],c=n[1],l=0,u=1,d=2;for(n[0]={s:-1,f:a.f+c.f,l:a,r:c};u!=s-1;)a=n[n[l].f<n[d].f?l++:d++],c=n[l!=u&&n[l].f<n[d].f?l++:d++],n[u++]={s:-1,f:a.f+c.f,l:a,r:c};var p=o[0].s;for(r=1;r<s;++r)o[r].s>p&&(p=o[r].s);var f=new Go(p+1),h=Ti(n[u-1],f,0);if(h>t){r=0;var g=0,m=h-t,y=1<<m;for(o.sort(function(e,t){return f[t.s]-f[e.s]||e.f-t.f});r<s;++r){var b=o[r].s;if(!(f[b]>t))break;g+=y-(1<<h-f[b]),f[b]=t}for(g>>=m;g>0;){var w=o[r].s;f[w]<t?g-=1<<t-f[w]++-1:++r}for(;r>=0&&g;--r){var v=o[r].s;f[v]==t&&(--f[v],++g)}h=t}return{t:new Ho(f),l:h}},Ti=function(e,t,n){return-1==e.s?Math.max(Ti(e.l,t,n+1),Ti(e.r,t,n+1)):t[e.s]=n},_i=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new Go(++t),r=0,s=e[0],o=1,i=function(e){n[r++]=e},a=1;a<=t;++a)if(e[a]==s&&a!=t)++o;else{if(!s&&o>2){for(;o>138;o-=138)i(32754);o>2&&(i(o>10?o-11<<5|28690:o-3<<5|12305),o=0)}else if(o>3){for(i(s),--o;o>6;o-=6)i(8304);o>2&&(i(o-3<<5|8208),o=0)}for(;o--;)i(s);o=1,s=e[a]}return{c:n.subarray(0,r),n:t}},Ei=function(e,t){for(var n=0,r=0;r<t.length;++r)n+=e[r]*t[r];return n},Si=function(e,t,n){var r=n.length,s=hi(t+2);e[s]=255&r,e[s+1]=r>>8,e[s+2]=255^e[s],e[s+3]=255^e[s+1];for(var o=0;o<r;++o)e[s+o+4]=n[o];return 8*(s+4+r)},xi=function(e,t,n,r,s,o,i,a,c,l,u){wi(t,u++,n),++s[256];for(var d=Ii(s,15),p=d.t,f=d.l,h=Ii(o,15),g=h.t,m=h.l,y=_i(p),b=y.c,w=y.n,v=_i(g),I=v.c,T=v.n,_=new Go(19),E=0;E<b.length;++E)++_[31&b[E]];for(E=0;E<I.length;++E)++_[31&I[E]];for(var S=Ii(_,7),x=S.t,A=S.l,k=19;k>4&&!x[zo[k-1]];--k);var C,P,R,U,$=l+5<<3,L=Ei(s,si)+Ei(o,ii)+i,D=Ei(s,p)+Ei(o,g)+i+14+3*k+Ei(_,x)+2*_[16]+3*_[17]+7*_[18];if(c>=0&&$<=L&&$<=D)return Si(t,u,e.subarray(c,c+l));if(wi(t,u,1+(D<L)),u+=2,D<L){C=ri(p,f,0),P=p,R=ri(g,m,0),U=g;var N=ri(x,A,0);for(wi(t,u,w-257),wi(t,u+5,T-1),wi(t,u+10,k-4),u+=14,E=0;E<k;++E)wi(t,u+3*E,x[zo[E]]);u+=3*k;for(var O=[b,I],B=0;B<2;++B){var j=O[B];for(E=0;E<j.length;++E){var M=31&j[E];wi(t,u,N[M]),u+=x[M],M>15&&(wi(t,u,j[E]>>5&127),u+=j[E]>>12)}}}else C=ai,P=si,R=li,U=ii;for(E=0;E<a;++E){var F=r[E];if(F>255){vi(t,u,C[257+(M=F>>18&31)]),u+=P[M+257],M>7&&(wi(t,u,F>>23&31),u+=Vo[M]);var H=31&F;vi(t,u,R[H]),u+=U[H],H>3&&(vi(t,u,F>>5&8191),u+=Yo[H])}else vi(t,u,C[F]),u+=P[F]}return vi(t,u,C[256]),u+P[256]},Ai=new Wo([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),ki=new Ho(0),Ci=function(e,t,n,r,s,o){var i=o.z||e.length,a=new Ho(r+i+5*(1+Math.ceil(i/7e3))+s),c=a.subarray(r,a.length-s),l=o.l,u=7&(o.r||0);if(t){u&&(c[0]=o.r>>3);for(var d=Ai[t-1],p=d>>13,f=8191&d,h=(1<<n)-1,g=o.p||new Go(32768),m=o.h||new Go(h+1),y=Math.ceil(n/3),b=2*y,w=function(t){return(e[t]^e[t+1]<<y^e[t+2]<<b)&h},v=new Wo(25e3),I=new Go(288),T=new Go(32),_=0,E=0,S=o.i||0,x=0,A=o.w||0,k=0;S+2<i;++S){var C=w(S),P=32767&S,R=m[C];if(g[P]=R,m[C]=P,A<=S){var U=i-S;if((_>7e3||x>24576)&&(U>423||!l)){u=xi(e,c,0,v,I,T,E,x,k,S-k,u),x=_=E=0,k=S;for(var $=0;$<286;++$)I[$]=0;for($=0;$<30;++$)T[$]=0}var L=2,D=0,N=f,O=P-R&32767;if(U>2&&C==w(S-O))for(var B=Math.min(p,U)-1,j=Math.min(32767,S),M=Math.min(258,U);O<=j&&--N&&P!=R;){if(e[S+L]==e[S+L-O]){for(var F=0;F<M&&e[S+F]==e[S+F-O];++F);if(F>L){if(L=F,D=O,F>B)break;var H=Math.min(O,F-2),G=0;for($=0;$<H;++$){var W=S-O+$&32767,V=W-g[W]&32767;V>G&&(G=V,R=W)}}}O+=(P=R)-(R=g[P])&32767}if(D){v[x++]=268435456|Xo[L]<<18|ti[D];var Y=31&Xo[L],z=31&ti[D];E+=Vo[Y]+Yo[z],++I[257+Y],++T[z],A=S+L,++_}else v[x++]=e[S],++I[e[S]]}}for(S=Math.max(S,A);S<i;++S)v[x++]=e[S],++I[e[S]];u=xi(e,c,l,v,I,T,E,x,k,S-k,u),l||(o.r=7&u|c[u/8|0]<<3,u-=7,o.h=m,o.p=g,o.i=S,o.w=A)}else{for(S=o.w||0;S<i+l;S+=65535){var q=S+65535;q>=i&&(c[u/8|0]=l,q=i),u=Si(c,u+1,e.subarray(S,q))}o.i=i}return gi(a,0,r+hi(u)+s)},Pi=function(){for(var e=new Int32Array(256),t=0;t<256;++t){for(var n=t,r=9;--r;)n=(1&n&&-306674912)^n>>>1;e[t]=n}return e}(),Ri=function(e,t,n,r,s){if(!s&&(s={l:1},t.dictionary)){var o=t.dictionary.subarray(-32768),i=new Ho(o.length+e.length);i.set(o),i.set(e,o.length),e=i,s.w=o.length}return Ci(e,null==t.level?6:t.level,null==t.mem?s.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(e.length)))):20:12+t.mem,n,r,s)},Ui=function(e,t){var n={};for(var r in e)n[r]=e[r];for(var r in t)n[r]=t[r];return n},$i=function(e,t,n){for(var r=e(),s=e.toString(),o=s.slice(s.indexOf("[")+1,s.lastIndexOf("]")).replace(/\s+/g,"").split(","),i=0;i<r.length;++i){var a=r[i],c=o[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 n[c]=a}return t},Li=[],Di=function(){return[Ho,Go,Wo,Vo,Yo,zo,Jo,ei,ci,ui,ni,mi,ri,di,pi,fi,hi,gi,yi,bi,Vi,Oi,Bi]},Ni=function(){return[Ho,Go,Wo,Vo,Yo,zo,Xo,ti,ai,si,li,ii,ni,Ai,ki,ri,wi,vi,Ii,Ti,_i,Ei,Si,xi,hi,gi,Ci,Ri,Wi,Oi]},Oi=function(e){return postMessage(e,[e.buffer])},Bi=function(e){return e&&{out:e.size&&new Ho(e.size),dictionary:e.dictionary}},ji=function(e,t,n,r,s,o){var i=function(e,t,n,r){if(!Li[n]){for(var s="",o={},i=e.length-1,a=0;a<i;++a)s=$i(e[a],s,o);Li[n]={c:$i(e[i],s,o),e:o}}var c=Ui({},Li[n].e);return Fo(Li[n].c+";onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage="+t.toString()+"}",n,c,function(e){var t=[];for(var n in e)e[n].buffer&&t.push((e[n]=new e[n].constructor(e[n])).buffer);return t}(c),r)}(n,r,s,function(e,t){i.terminate(),o(e,t)});return i.postMessage([e,t],t.consume?[e.buffer]:[]),function(){i.terminate()}},Mi=function(e,t){return e[t]|e[t+1]<<8},Fi=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},Hi=function(e,t){return Fi(e,t)+4294967296*Fi(e,t+4)},Gi=function(e,t,n){for(;n;++t)e[t]=n,n>>>=8};function Wi(e,t){return Ri(e,t||{},0,0)}function Vi(e,t){return bi(e,{i:2},t&&t.out,t&&t.dictionary)}var Yi=function(e,t,n,r){for(var s in e){var o=e[s],i=t+s,a=r;Array.isArray(o)&&(a=Ui(r,o[1]),o=o[0]),o instanceof Ho?n[i]=[o,a]:(n[i+="/"]=[new Ho(0),a],Yi(o,i,n,r))}},zi="undefined"!=typeof TextEncoder&&new TextEncoder,qi="undefined"!=typeof TextDecoder&&new TextDecoder;try{qi.decode(ki,{stream:!0})}catch(e){}function Ki(e,t){if(zi)return zi.encode(e);for(var n=e.length,r=new Ho(e.length+(e.length>>1)),s=0,o=function(e){r[s++]=e},i=0;i<n;++i){if(s+5>r.length){var a=new Ho(s+8+(n-i<<1));a.set(r),r=a}var c=e.charCodeAt(i);c<128||t?o(c):c<2048?(o(192|c>>6),o(128|63&c)):c>55295&&c<57344?(o(240|(c=65536+(1047552&c)|1023&e.charCodeAt(++i))>>18),o(128|c>>12&63),o(128|c>>6&63),o(128|63&c)):(o(224|c>>12),o(128|c>>6&63),o(128|63&c))}return gi(r,0,s)}var Ji=function(e){var t=0;if(e)for(var n in e){var r=e[n].length;r>65535&&yi(9),t+=r+4}return t},Xi=function(e,t,n,r,s,o,i,a){var c=r.length,l=n.extra,u=a&&a.length,d=Ji(l);Gi(e,t,null!=i?33639248:67324752),t+=4,null!=i&&(e[t++]=20,e[t++]=n.os),e[t]=20,t+=2,e[t++]=n.flag<<1|(o<0&&8),e[t++]=s&&8,e[t++]=255&n.compression,e[t++]=n.compression>>8;var p=new Date(null==n.mtime?Date.now():n.mtime),f=p.getFullYear()-1980;if((f<0||f>119)&&yi(10),Gi(e,t,f<<25|p.getMonth()+1<<21|p.getDate()<<16|p.getHours()<<11|p.getMinutes()<<5|p.getSeconds()>>1),t+=4,-1!=o&&(Gi(e,t,n.crc),Gi(e,t+4,o<0?-o-2:o),Gi(e,t+8,n.size)),Gi(e,t+12,c),Gi(e,t+14,d),t+=16,null!=i&&(Gi(e,t,u),Gi(e,t+6,n.attrs),Gi(e,t+10,i),t+=14),e.set(r,t),t+=c,d)for(var h in l){var g=l[h],m=g.length;Gi(e,t,+h),Gi(e,t+2,m),e.set(g,t+4),t+=4+m}return u&&(e.set(a,t),t+=u),t},Qi="function"==typeof queueMicrotask?queueMicrotask:"function"==typeof setTimeout?setTimeout:function(e){e()};function Zi(e,t,n){const r=Math.min(t,512);if("utf-16"===n||"utf-16le"===n||"utf-16be"===n){for(let t=0;t<r;t+=2){const s=e[t],o=t+1<r?e[t+1]:0;if(("utf-16le"===n||"utf-16"===n)&&0===o&&s<32&&9!==s&&10!==s&&13!==s&&0!==s)return!1;if(("utf-16be"===n||"utf-16"===n)&&0===s&&o<32&&9!==o&&10!==o&&13!==o&&0!==o)return!1}return!0}if("latin1"===n||"iso-8859-1"===n){for(let t=0;t<r;t++){const n=e[t];if(0===n)return!1;if(n<32&&9!==n&&10!==n&&13!==n)return!1}return!0}if("cjk"===n||"big5"===n||"gb2312"===n||"gbk"===n||"euc-kr"===n||"shift-jis"===n){for(let t=0;t<r;t++){const n=e[t];if(0===n)return!1;if(n<32&&9!==n&&10!==n&&13!==n)return!1}return!0}return!1}var ea=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 n=0;n<e;n++){if(this.error)return t;t[n]=this.nextByte()}return t}};function ta(e){let t=0,n=0;for(;!e.hasError();){const r=e.nextByte();if(n|=(127&r)<<7*t,!(128&r))break;if(t>=10){e.error=!0;break}t++}return n}function na(e){switch(7&ta(e)){case 0:return ta(e),!0;case 1:return e.next(8),!0;case 2:const t=ta(e);return e.next(t),!0;case 5:return e.next(4),!0}return!1}function ra(e,t,n){if(0===t)return!1;let r=0;const s=Math.min(t,515),o=Math.min(s,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(s>=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(n?.encoding)return!Zi(e,t,n.encoding);const i=function(e,t){if(t<4)return null;const n=Math.min(t,512);let r=0,s=0;for(let t=0;t<n;t++)0===e[t]&&(t%2==0?r++:s++);const o=r+s;if(o>.3*n&&o<.7*n){if(s>3*r)return"utf-16le";if(r>3*s)return"utf-16be"}return null}(e,t);if(i)return!Zi(e,t,i);for(let t=0;t<o;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<s){if(t++,e[t]>=128&&e[t]<=191)continue}else if(e[t]>=224&&e[t]<=239&&t+2<s){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<s&&(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(r++,t>=32&&100*r/o>10)return!0}}return 100*r/o>10||!!(r>1&&function(e,t){const n=new ea(e,t);let r=0;for(;;){if(!na(n)&&!n.hasError())return!1;if(n.hasError())break;r++}return r>0}(e,o))}var sa=[/^\/$/,/^\*+$/,/^[0-9]+$/],oa=["/artifact/","https://","http://","*********"],ia=Symbol.for("@ts-pattern/matcher"),aa=Symbol.for("@ts-pattern/isVariadic"),ca="@ts-pattern/anonymous-select-key",la=e=>Boolean(e&&"object"==typeof e),ua=e=>e&&!!e[ia],da=(e,t,n)=>{if(ua(e)){const r=e[ia](),{matched:s,selections:o}=r.match(t);return s&&o&&Object.keys(o).forEach(e=>n(e,o[e])),s}if(la(e)){if(!la(t))return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let r=[],s=[],o=[];for(const t of e.keys()){const n=e[t];ua(n)&&n[aa]?o.push(n):o.length?s.push(n):r.push(n)}if(o.length){if(o.length>1)throw new Error("Pattern error: Using `...P.array(...)` several times in a single pattern is not allowed.");if(t.length<r.length+s.length)return!1;const e=t.slice(0,r.length),i=0===s.length?[]:t.slice(-s.length),a=t.slice(r.length,0===s.length?1/0:-s.length);return r.every((t,r)=>da(t,e[r],n))&&s.every((e,t)=>da(e,i[t],n))&&(0===o.length||da(o[0],a,n))}return e.length===t.length&&e.every((e,r)=>da(e,t[r],n))}return Reflect.ownKeys(e).every(r=>{const s=e[r];return(r in t||ua(o=s)&&"optional"===o[ia]().matcherType)&&da(s,t[r],n);var o})}return Object.is(t,e)},pa=e=>{var t,n,r;return la(e)?ua(e)?null!=(t=null==(n=(r=e[ia]()).getSelectionKeys)?void 0:n.call(r))?t:[]:Array.isArray(e)?fa(e,pa):fa(Object.values(e),pa):[]},fa=(e,t)=>e.reduce((e,n)=>e.concat(t(n)),[]);function ha(e){return Object.assign(e,{optional:()=>{return t=e,ha({[ia]:()=>({match:e=>{let n={};const r=(e,t)=>{n[e]=t};return void 0===e?(pa(t).forEach(e=>r(e,void 0)),{matched:!0,selections:n}):{matched:da(t,e,r),selections:n}},getSelectionKeys:()=>pa(t),matcherType:"optional"})});var t},and:t=>ga(e,t),or:t=>function(...e){return ha({[ia]:()=>({match:t=>{let n={};const r=(e,t)=>{n[e]=t};return fa(e,pa).forEach(e=>r(e,void 0)),{matched:e.some(e=>da(e,t,r)),selections:n}},getSelectionKeys:()=>fa(e,pa),matcherType:"or"})})}(e,t),select:t=>void 0===t?ya(e):ya(t,e)})}function ga(...e){return ha({[ia]:()=>({match:t=>{let n={};const r=(e,t)=>{n[e]=t};return{matched:e.every(e=>da(e,t,r)),selections:n}},getSelectionKeys:()=>fa(e,pa),matcherType:"and"})})}function ma(e){return{[ia]:()=>({match:t=>({matched:Boolean(e(t))})})}}function ya(...e){const t="string"==typeof e[0]?e[0]:void 0,n=2===e.length?e[1]:"string"==typeof e[0]?void 0:e[0];return ha({[ia]:()=>({match:e=>{let r={[null!=t?t:ca]:e};return{matched:void 0===n||da(n,e,(e,t)=>{r[e]=t}),selections:r}},getSelectionKeys:()=>[null!=t?t:ca].concat(void 0===n?[]:pa(n))})})}function ba(e){return!0}function wa(e){return"number"==typeof e}function va(e){return"string"==typeof e}function Ia(e){return"bigint"==typeof e}ha(ma(ba)),ha(ma(ba));var Ta=e=>Object.assign(ha(e),{startsWith:t=>{return Ta(ga(e,(n=t,ma(e=>va(e)&&e.startsWith(n)))));var n},endsWith:t=>{return Ta(ga(e,(n=t,ma(e=>va(e)&&e.endsWith(n)))));var n},minLength:t=>{return Ta(ga(e,(n=t,ma(e=>va(e)&&e.length>=n))));var n},length:t=>{return Ta(ga(e,(n=t,ma(e=>va(e)&&e.length===n))));var n},maxLength:t=>{return Ta(ga(e,(n=t,ma(e=>va(e)&&e.length<=n))));var n},includes:t=>{return Ta(ga(e,(n=t,ma(e=>va(e)&&e.includes(n)))));var n},regex:t=>{return Ta(ga(e,(n=t,ma(e=>va(e)&&Boolean(e.match(n))))));var n}});Ta(ma(va));var _a=e=>Object.assign(ha(e),{between:(t,n)=>{return _a(ga(e,(r=t,s=n,ma(e=>wa(e)&&r<=e&&s>=e))));var r,s},lt:t=>{return _a(ga(e,(n=t,ma(e=>wa(e)&&e<n))));var n},gt:t=>{return _a(ga(e,(n=t,ma(e=>wa(e)&&e>n))));var n},lte:t=>{return _a(ga(e,(n=t,ma(e=>wa(e)&&e<=n))));var n},gte:t=>{return _a(ga(e,(n=t,ma(e=>wa(e)&&e>=n))));var n},int:()=>_a(ga(e,ma(e=>wa(e)&&Number.isInteger(e)))),finite:()=>_a(ga(e,ma(e=>wa(e)&&Number.isFinite(e)))),positive:()=>_a(ga(e,ma(e=>wa(e)&&e>0))),negative:()=>_a(ga(e,ma(e=>wa(e)&&e<0)))});_a(ma(wa));var Ea=e=>Object.assign(ha(e),{between:(t,n)=>{return Ea(ga(e,(r=t,s=n,ma(e=>Ia(e)&&r<=e&&s>=e))));var r,s},lt:t=>{return Ea(ga(e,(n=t,ma(e=>Ia(e)&&e<n))));var n},gt:t=>{return Ea(ga(e,(n=t,ma(e=>Ia(e)&&e>n))));var n},lte:t=>{return Ea(ga(e,(n=t,ma(e=>Ia(e)&&e<=n))));var n},gte:t=>{return Ea(ga(e,(n=t,ma(e=>Ia(e)&&e>=n))));var n},positive:()=>Ea(ga(e,ma(e=>Ia(e)&&e>0))),negative:()=>Ea(ga(e,ma(e=>Ia(e)&&e<0)))});Ea(ma(Ia)),ha(ma(function(e){return"boolean"==typeof e})),ha(ma(function(e){return"symbol"==typeof e})),ha(ma(function(e){return null==e})),ha(ma(function(e){return null!=e}));var Sa=class extends Error{constructor(e){let t;try{t=JSON.stringify(e)}catch(n){t=e}super(`Pattern matching error: no pattern matches value ${t}`),this.input=void 0,this.input=e}},xa={matched:!1,value:void 0},Aa=class e{constructor(e,t){this.input=void 0,this.state=void 0,this.input=e,this.state=t}with(...t){if(this.state.matched)return this;const n=t[t.length-1],r=[t[0]];let s;3===t.length&&"function"==typeof t[1]?s=t[1]:t.length>2&&r.push(...t.slice(1,t.length-1));let o=!1,i={};const a=(e,t)=>{o=!0,i[e]=t},c=!r.some(e=>da(e,this.input,a))||s&&!Boolean(s(this.input))?xa:{matched:!0,value:n(o?ca in i?i[ca]:i:this.input,this.input)};return new e(this.input,c)}when(t,n){if(this.state.matched)return this;const r=Boolean(t(this.input));return new e(this.input,r?{matched:!0,value:n(this.input,this.input)}:xa)}otherwise(e){return this.state.matched?this.state.value:e(this.input)}exhaustive(e=ka){return this.state.matched?this.state.value:e(this.input)}run(){return this.exhaustive()}returnType(){return this}narrow(){return this}};function ka(e){throw new Sa(e)}var Ca=new Set(["sha1","_sha1","pageref","downloadsPath","tracesDir","pageId"]);function Pa({sensitiveValues:e,str:t}){return e.reduce((e,t)=>e.replaceAll(t,"[REDACTED]"),t)}function Ra({sensitiveValues:e,value:t}){return"string"==typeof t?Pa({sensitiveValues:e,str:t}):Array.isArray(t)?t.map(t=>Ra({sensitiveValues:e,value:t})):function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(t)?$a({obj:t,sensitiveValues:e}):t}function Ua(e){return!!Ca.has(e)||e.toLowerCase().endsWith("sha1")}function $a({obj:e,sensitiveValues:t}){return Object.fromEntries(Object.entries(e).map(([e,n])=>[e,Ua(e)?n:Ra({sensitiveValues:t,value:n})]))}function La({error:e,sensitiveValues:t}){return e?{...e,message:Pa({sensitiveValues:t,str:e.message})}:void 0}function Da({content:e,sensitiveValues:t}){const n=new F,r=new H,s=Pa({sensitiveValues:t,str:n.decode(e)});return r.encode(s)}var Na=M(function(e,t,n){n||(n=t,t={}),"function"!=typeof n&&yi(7);var r=[],s=function(){for(var e=0;e<r.length;++e)r[e]()},o={},i=function(e,t){Qi(function(){n(e,t)})};Qi(function(){i=n});for(var a=e.length-22;101010256!=Fi(e,a);--a)if(!a||e.length-a>65558)return i(yi(13,0,1),null),s;var c=Mi(e,a+8);if(c){var l=c,u=Fi(e,a+16),d=4294967295==u||65535==l;if(d){var p=Fi(e,a-12);(d=101075792==Fi(e,p))&&(l=c=Fi(e,p+32),u=Fi(e,p+48))}for(var f=t&&t.filter,h=function(t){var n=function(e,t,n){var r=Mi(e,t+28),s=function(e,t){if(t){for(var n="",r=0;r<e.length;r+=16384)n+=String.fromCharCode.apply(null,e.subarray(r,r+16384));return n}if(qi)return qi.decode(e);var s=function(e){for(var t="",n=0;;){var r=e[n++],s=(r>127)+(r>223)+(r>239);if(n+s>e.length)return{s:t,r:gi(e,n-1)};s?3==s?(r=((15&r)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536,t+=String.fromCharCode(55296|r>>10,56320|1023&r)):t+=1&s?String.fromCharCode((31&r)<<6|63&e[n++]):String.fromCharCode((15&r)<<12|(63&e[n++])<<6|63&e[n++]):t+=String.fromCharCode(r)}}(e),o=s.s;return(n=s.r).length&&yi(8),o}(e.subarray(t+46,t+46+r),!(2048&Mi(e,t+8))),o=t+46+r,i=Fi(e,t+20),a=n&&4294967295==i?function(e,t){for(;1!=Mi(e,t);t+=4+Mi(e,t+2));return[Hi(e,t+12),Hi(e,t+4),Hi(e,t+20)]}(e,o):[i,Fi(e,t+24),Fi(e,t+42)],c=a[0],l=a[1],u=a[2];return[Mi(e,t+10),c,l,s,o+Mi(e,t+30)+Mi(e,t+32),u]}(e,u,d),a=n[0],l=n[1],p=n[2],h=n[3],g=n[4],m=n[5],y=function(e,t){return t+30+Mi(e,t+26)+Mi(e,t+28)}(e,m);u=g;var b=function(e,t){e?(s(),i(e,null)):(t&&(o[h]=t),--c||i(null,o))};if(!f||f({name:h,size:l,originalSize:p,compression:a}))if(a)if(8==a){var w=e.subarray(y,y+l);if(p<524288||l>.8*p)try{b(null,Vi(w,{out:new Ho(p)}))}catch(e){b(e,null)}else r.push(function(e,t,n){return n||(n=t,t={}),"function"!=typeof n&&yi(7),ji(e,t,[Di],function(e){return Oi(Vi(e.data[0],Bi(e.data[1])))},1,n)}(w,{size:p},b))}else b(yi(14,"unknown compression type "+a,1),null);else b(null,gi(e,y,y+l));else b(null,null)},g=0;g<l;++g)h()}else i(null,{});return s}),Oa=M(function(e,t,n){n||(n=t,t={}),"function"!=typeof n&&yi(7);var r={};Yi(e,"",r,t);var s=Object.keys(r),o=s.length,i=0,a=0,c=o,l=new Array(o),u=[],d=function(){for(var e=0;e<u.length;++e)u[e]()},p=function(e,t){Qi(function(){n(e,t)})};Qi(function(){p=n});var f=function(){var e=new Ho(a+22),t=i,n=a-i;a=0;for(var r=0;r<c;++r){var s=l[r];try{var o=s.c.length;Xi(e,a,s,s.f,s.u,o);var u=30+s.f.length+Ji(s.extra),d=a+u;e.set(s.c,d),Xi(e,i,s,s.f,s.u,o,a,s.m),i+=16+u+(s.m?s.m.length:0),a=d+o}catch(e){return p(e,null)}}!function(e,t,n,r,s){Gi(e,t,101010256),Gi(e,t+8,n),Gi(e,t+10,n),Gi(e,t+12,r),Gi(e,t+16,s)}(e,i,l.length,n,t),p(null,e)};o||f();for(var h=function(e){var t=s[e],n=r[t],c=n[0],h=n[1],g=function(){var e=-1;return{p:function(t){for(var n=e,r=0;r<t.length;++r)n=Pi[255&n^t[r]]^n>>>8;e=n},d:function(){return~e}}}(),m=c.length;g.p(c);var y=Ki(t),b=y.length,w=h.comment,v=w&&Ki(w),I=v&&v.length,T=Ji(h.extra),_=0==h.level?0:8,E=function(n,r){if(n)d(),p(n,null);else{var s=r.length;l[e]=Ui(h,{size:m,crc:g.d(),c:r,f:y,m:v,u:b!=t.length||v&&w.length!=I,compression:_}),i+=30+b+T+s,a+=76+2*(b+T)+(I||0)+s,--o||f()}};if(b>65535&&E(yi(11,0,1),null),_)if(m<16e4)try{E(null,Wi(c,h))}catch(e){E(e,null)}else u.push(function(e,t,n){return n||(n=t,t={}),"function"!=typeof n&&yi(7),ji(e,t,[Ni],function(e){return Oi(Wi(e.data[0],e.data[1]))},0,n)}(c,h,E));else E(null,c)},g=0;g<c;++g)h(g);return d});async function Ba({content:e,filename:t,sensitiveValues:n}){const r=t.toLowerCase();return r.endsWith(".trace")||r.endsWith(".network")?function({content:e,sensitiveValues:t}){const n=new F,r=new H,s=n.decode(e).split("\n").map(e=>{if(!e.trim())return e;try{const n=function({event:e,sensitiveValues:t}){return(n=e,new Aa(n,xa)).with({type:"console"},e=>({...e,args:e.args?.map(e=>({...e,preview:Pa({sensitiveValues:t,str:e.preview}),value:Ra({sensitiveValues:t,value:e.value})})),text:Pa({sensitiveValues:t,str:e.text})})).with({type:"before"},e=>({...e,params:$a({obj:e.params,sensitiveValues:t}),title:e.title?Pa({sensitiveValues:t,str:e.title}):void 0})).with({type:"after"},e=>({...e,error:La({error:e.error,sensitiveValues:t}),result:void 0!==e.result?Ra({sensitiveValues:t,value:e.result}):void 0})).with({type:"action"},e=>({...e,error:La({error:e.error,sensitiveValues:t}),params:$a({obj:e.params,sensitiveValues:t}),result:void 0!==e.result?Ra({sensitiveValues:t,value:e.result}):void 0,title:e.title?Pa({sensitiveValues:t,str:e.title}):void 0})).with({type:"event"},e=>({...e,params:$a({obj:e.params,sensitiveValues:t})})).with({type:"stdout"},{type:"stderr"},e=>({...e,text:void 0!==e.text?Pa({sensitiveValues:t,str:e.text}):void 0})).with({type:"error"},e=>({...e,message:Pa({sensitiveValues:t,str:e.message})})).with({type:"log"},e=>({...e,message:Pa({sensitiveValues:t,str:e.message})})).with({type:"context-options"},e=>({...e,options:$a({obj:e.options,sensitiveValues:t}),title:e.title?Pa({sensitiveValues:t,str:e.title}):void 0})).with({type:"frame-snapshot"},e=>({...e,snapshot:$a({obj:e.snapshot,sensitiveValues:t})})).with({type:"resource-snapshot"},e=>({...e,snapshot:$a({obj:e.snapshot,sensitiveValues:t})})).with({type:"screencast-frame"},{type:"input"},e=>e).exhaustive();var n}({event:JSON.parse(e),sensitiveValues:t});return JSON.stringify(n)}catch{return Pa({sensitiveValues:t,str:e})}});return r.encode(s.join("\n"))}({content:e,sensitiveValues:n}):r.endsWith(".html")||r.endsWith(".dat")||r.endsWith(".json")?Da({content:e,sensitiveValues:n}):r.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!")}(S(e));const n=P(e,"r"),r=Buffer.alloc(515),s=R(n,r,0,515,0);return U(n),ra(r,s,t)}return ra(e,void 0!==t?.size?t.size:e.length,t)}(Buffer.from(e),{size:e.length})}(e)?e:Da({content:e,sensitiveValues:t})}({content:e,sensitiveValues:n}):e}var ja=e=>(e instanceof Error?e.message:String(e)).slice(0,400),Ma=async e=>{const t=await Q(e,{withFileTypes:!0}),n=[];for(const s of t){const t=r.join(e,s.name);if(s.isDirectory())n.push(...await Ma(t));else if(s.isFile()&&"trace.zip"===s.name){const e=await Z(t);n.push({path:t,mtimeMs:e.mtimeMs})}}return n},Fa=async({tracePath:e,outputDir:t,requestUploadUrl:n})=>{try{let r=e;if(!r){if(!t)return{status:"capture_failed",error:"Either tracePath or outputDir must be provided."};if(!E(t))return{status:"capture_failed",error:`Output directory does not exist: ${t}`};r=await(async e=>{const t=await Ma(e);if(0!==t.length)return t.sort((e,t)=>t.mtimeMs-e.mtimeMs),t[0]?.path})(t)}if(!r)return{status:"capture_failed",error:"No trace.zip found in the output directory."};const{traceBucketPath:s,uploadUrl:o,sensitiveValues:i}=await n(),a=await async function({tracePath:e,sensitiveValues:t}){const n=[],r=C(e);for await(const e of r)n.push(e);return async function({sensitiveValues:e,traceBuffer:t}){const n=e.filter(e=>!(e.length<3||sa.some(t=>t.test(e))||oa.some(t=>e.includes(t))));if(0===n.length)return new Uint8Array(t);const r=[...n].sort((e,t)=>t.length-e.length),s=await Na(new Uint8Array(t)),o=Object.entries(s),i=await Promise.all(o.map(async([e,t])=>[e,await Ba({content:t,filename:e,sensitiveValues:r})])),a=Object.fromEntries(i);return Oa(a)}({traceBuffer:new Uint8Array(Buffer.concat(n)),sensitiveValues:t})}({tracePath:r,sensitiveValues:i});try{await Ss({body:a,contentType:"application/zip",uploadUrl:o,errorContext:"trace"})}catch(e){return{status:"upload_failed",error:ja(e)}}return{status:"captured",storage:s}}catch(e){return{status:"upload_failed",error:ja(e)}}},{zMarkdownAutoHealReport:Ha,zRepresentativeTest:Ga}=function(e){const t=e.enum(kn),n=["Classification of the root cause:","",`- test: ${Pn("test")}`,`- bug: ${Pn("bug")}`,`- flake: ${Pn("flake")}`,`- ui_change: ${Pn("ui_change")}`,`- other: ${Pn("other")}`].join("\n"),r=e.object({filePath:e.string().optional(),testIdentifier:e.string().optional(),testTitle:e.string().optional()}),s=e.object({status:e.enum(["captured","capture_failed","upload_failed"]),representativeTest:r,storage:e.object({bucket:e.string(),key:e.string()}).optional(),signedUrl:e.string().optional(),error:e.string().optional(),testPassed:e.boolean().optional(),testExitCode:e.number().nullable().optional(),testStderr:e.string().optional()}),o=s.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(n),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(o).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:s.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")})]),c=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.")}),l=e.discriminatedUnion("result",[e.object({result:e.literal("fixed"),issueType:t,issueId:e.string().optional().describe("Issue ID from triage, used for deterministic fingerprinting across re-uploads."),rootCause:e.string().min(1),fixApplied:e.string().min(1).describe("What fix was applied (brief, specific). Include file:line references."),relatedTestCaseIds:e.array(e.string()).min(1)}),e.object({result:e.literal("unfixed"),issueType:t,issueId:e.string().optional().describe("Issue ID from triage, used for deterministic fingerprinting across re-uploads."),rootCause:e.string().min(1),reasonNotFixed:e.string().min(1).describe("Why it could not be auto-fixed (brief). Include file:line references."),relatedTestCaseIds:e.array(e.string()).min(1)})]),u=e.object({format:e.literal("markdown"),markdown:e.string().min(1).describe("Flexible markdown report content for the auto-heal run. Use headings, bullets, and code fences as needed."),summary:e.string().optional().describe('One-liner summary of the auto-heal run (e.g., "Fixed 2 of 3 issues: stale locators and timing"). Used in notifications, API responses, and triage agent context.'),issues:e.array(l).optional().describe("Structured issue metadata for database tracking. Each issue links a root cause to affected test case IDs.")});return{zAutoHealReport:a,zIssueCategory:t,zMarkdownAutoHealReport:u,zMarkdownAutoHealReportIssue:l,zRepresentativeTest:r,zSuiteAutoHealReport:c,zStoredAutoHealReport:e.union([u,c]),zTraceProof:s,zTraceProofByTest:o}}(we),Wa=({authProvider:e,diffTracker:t,orgId:n,runId:r,workingDir:s})=>G({name:"auto-heal-report",tools:[W("upload-trace-proof",["Upload a Playwright trace proof for a test case.","","IMPORTANT: This tool does NOT run tests. You must run the test yourself first","using Playwright with --trace=on and --output <dir>, then call this tool to upload the trace.","","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 the outputDir that was used as the --output flag in your test run.","Optionally pass tracePath if you know the exact path to the trace.zip file."].join("\n"),{outputDir:we.string().min(1).optional().describe("The --output directory from the Playwright test run containing trace.zip. Required if tracePath is not provided."),tracePath:we.string().min(1).optional().describe("Optional direct path to trace.zip. If omitted, the newest trace in outputDir is used."),issueId:we.string().min(1).describe("Issue identifier for deterministic output paths and storage key naming."),proofId:we.string().min(1).optional().describe("Optional id for deterministic proof naming and deduplication."),testCaseId:we.string().min(1).optional().describe("Optional test case ID when uploading per-test trace proofs."),testPassed:we.boolean().describe("Whether the test run passed (exit code 0). You MUST check the exit code of stably-browser run-test before calling this tool. Exit code 0 = passed, non-zero = failed."),representativeTest:Ga.optional().default({})},async({outputDir:t,tracePath:s,issueId:o,proofId:i,representativeTest:a,testCaseId:c,testPassed:l})=>{const u=await e.getAuthHeader(),d=we.string().min(1).parse(o),p=null==i?void 0:we.string().min(1).parse(i),f=null==c?void 0:we.string().min(1).parse(c),h=Ga.parse(a??{}),g=await Fa({tracePath:s,outputDir:t,requestUploadUrl:()=>(async({authHeader:e,issueId:t,proofId:n,testCaseId:r,contentType:s="application/zip",orgId:o,runId:i})=>{const a=await(c={auth:e,body:{contentType:s,issueId:t,proofId:n,testCaseId:r},client:vr(),headers:Ts(o),path:{runId:i}},(c.client??cr).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=As.parse(a.data);return{traceBucketPath:l.traceBucketPath,expiresInSeconds:l.expiresInSeconds,key:l.key,uploadUrl:l.uploadUrl,sensitiveValues:l.sensitiveValues}})({authHeader:u,issueId:d,proofId:p,orgId:n,runId:r,testCaseId:f})}),m=h.testTitle||h.filePath,y="captured"===g.status&&g.storage?`@[trace:${Buffer.from(JSON.stringify({...g.storage,...m?{label:m}:{}})).toString("base64url")}]`:void 0,b={...g,testPassed:!!l,tracePlaceholder:y},w="string"==typeof f?{testCaseId:f,...b}:{...b},v=l?"":'\n\nWARNING: testPassed=false β this trace documents a FAILURE, not a successful fix. Do NOT report result:"fixed" for this test. If you applied a fix but the verification run failed (e.g., auth setup error, missing env vars), the fix is NOT proven. Report result:"unfixed" with the failure reason.';return{content:[{text:JSON.stringify(w)+v,type:"text"}]}}),W("generate-report",["After attempting to fix all broken tests (skip only those truly infeasible), generate a markdown auto-heal report.","","The UI renders this markdown into structured cards based on ## and ### headings. Follow the heading structure from the MARKDOWN REPORT STRUCTURE section in your instructions:","- ## Summary, ## Fixed Issues (with ### per issue), ## Unfixed Issues (with ### per issue)",'- Each ### must be a short descriptive slug (e.g. "invite-member-flaky-timeouts")',"- Use **bold labels:** for fields (Tests, Flaky signal, Root cause, Fix applied, Why not fixed, Proof of fixed tests)","- Include **Flaky signal:** inside an issue card only when triage flagged that test as flaky β do NOT create a separate ## section for flaky signals","","Write for readability: keep bullets concise, use tables only when they genuinely improve scanability, and wrap file paths, commands, selectors, and code in backticks.","Prefer short sections over long paragraphs. Call out important outcomes first, then supporting evidence.","","ENTITY REFERENCES: When referencing entities by ID, use placeholder syntax so the UI can render clickable links:","- Test cases: @[test-case:<id>] (e.g., @[test-case:fp8f0yzdqqut6bg7cy5euzer])","- Suite runs: @[suite-run:<id>] (e.g., @[suite-run:cm6i7o6ti0000l40350wys0u1])","- Tests: @[test:<id>] (e.g., @[test:wty0g1v58cwrrd8jj6et8nmx])","- Traces: use the tracePlaceholder value returned by upload-trace-proof (e.g., @[trace:eyJi...])","These placeholders will be automatically resolved to clickable links with human-readable labels in the UI.","NEVER show raw entity IDs without wrapping them in @[type:id] syntax."].join("\n"),{markdown:Ha.shape.markdown,summary:Ha.shape.summary,issues:Ha.shape.issues},async({markdown:s,summary:o,issues:i})=>{const a=await e.getAuthHeader(),c=await t.computeDiff(),l=Ha.parse({format:"markdown",markdown:s,summary:o,issues:i});try{await(async({authHeader:e,orgId:t,report:n,runId:r})=>{const s=await(o={auth:e,body:{report:JSON.stringify(n)},client:vr(),headers:Ts(t),path:{runId:r}},(o.client??cr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-report",...o,headers:{"Content-Type":"application/json",...o.headers}}));var o;if(s.error)throw new Error(`Failed to upload auto-heal report (${s.response.status})`)})({authHeader:a,orgId:n,report:l,runId:r});const{diffBucketPath:e,uploadUrl:t}=await ks({authHeader:a,contentType:"text/plain",orgId:n,runId:r});await Ss({body:c,contentType:"text/plain",uploadUrl:t,errorContext:"diff"}),await Cs({authHeader:a,diffBucketPath:e,orgId:n,runId:r})}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"});function Va({workingDir:e,packageManager:t,packageSpec:n,targetSection:r}){const{command:s,args:o}=function(e,t,n){const r="npm"===e?"npm":e;return{command:r,args:["npm"===e?"install":"add",..."devDependencies"===n?["bun"===e?"-d":"-D"]:[],..."npm"===r?["--no-fund"]:[],t]}}(t,n,r);y(s,o,{cwd:e,stdio:"pipe",timeout:6e4})}function Ya(e){const t=n.join(e,"package.json");return w.existsSync(t)?{path:t,contents:JSON.parse(w.readFileSync(t,"utf-8"))}:null}var za=["playwright.config.ts","playwright.config.js","playwright.config.mts","playwright.config.mjs","playwright.config.cjs"];function qa(e){return za.some(t=>w.existsSync(n.join(e,t)))}function Ka(e,t){const r=w.readdirSync(e,{withFileTypes:!0}),s=[];for(const o of r){if("node_modules"===o.name||".git"===o.name)continue;const r=n.join(e,o.name);o.isDirectory()?s.push(...Ka(r,t)):t.test(o.name)&&s.push(r)}return s}function Ja(e){let t=n.resolve(e);for(;;){if(qa(t))return t;const r=n.dirname(t);if(r===t)return e;t=r}}function Xa(e){const t=Array.from(new Set(e.map(e=>n.resolve(e)))).sort((e,t)=>e.length-t.length),r=[];for(const e of t)r.some(t=>e===t||e.startsWith(`${t}${n.sep}`))||r.push(e);return r}function Qa(e){return/\b(test|testing|playwright|e2e|stably)\b/i.test(e)}function Za(e,t){for(const r of ec(e,t))if(w.existsSync(n.join(r,"package.json")))return r}function ec(e,t){const r=[];let s=n.resolve(e);const o=n.resolve(t);for(;r.push(s),s!==o;){const e=n.dirname(s);if(e===s)break;s=e}return r}function tc(e){return e?.replace(/^[~^>=<]+/,"")}function nc(e){let t=e;for(let e=0;e<5;e++){if(w.existsSync(n.join(t,"pnpm-lock.yaml")))return"pnpm";if(w.existsSync(n.join(t,"yarn.lock")))return"yarn";if(w.existsSync(n.join(t,"bun.lockb"))||w.existsSync(n.join(t,"bun.lock")))return"bun";if(w.existsSync(n.join(t,"package-lock.json"))||w.existsSync(n.join(t,"npm-shrinkwrap.json")))return"npm";const e=n.dirname(t);if(e===t)break;t=e}return"npm"}var rc=we.object({commentUrl:we.string()}),sc=({prContext:e,authProvider:t,orgId:n,onReportPosted:r})=>G({name:"create-report",tools:[W("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:we.string().describe("A summary of the tests created. Include what features/flows are tested and any important notes."),filesCreated:we.array(we.string()).describe("List of test file paths that were created (relative to workspace root)")},async({summary:s,filesCreated:o})=>{const i=await t.getAuthHeader(),a=Array.isArray(o)?o:[];cs.info("[create-report] Posting report to GitHub PR",{prNumber:e.prNumber,filesCount:a.length});try{const t={summary:"string"==typeof s?s:String(s),filesCreated:a.map(String)},o=await async function({authHeader:e,orgId:t,prNumber:n,owner:r,repo:s,report:o}){const i=new URL("/internal/v1/cli/create-report",pr).toString(),a={Authorization:e,"Content-Type":"application/json"};t&&(a["x-stably-org-id"]=t),cs.debug("Posting create report to GitHub",{prNumber:n,owner:r,repo:s,filesCount:o.filesCreated.length});const c=await fetch(i,{method:"POST",headers:a,body:JSON.stringify({prNumber:n,owner:r,repo:s,report:o}),signal:AbortSignal.timeout(3e4)});if(!c.ok){const e=await c.text().catch(()=>"");throw cs.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=rc.parse(await c.json());return cs.info("Create report posted successfully",{commentUrl:l.commentUrl}),l}({authHeader:i,orgId:n,prNumber:e.prNumber,owner:e.owner,repo:e.repo,report:t});return r?.(o),cs.info("[create-report] Report posted successfully",{commentUrl:o.commentUrl}),{content:[{type:"text",text:`β
Test creation report posted to PR #${e.prNumber}\n\nView the comment: ${o.commentUrl}`}]}}catch(e){const t=e instanceof Error?e.message:String(e);return cs.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}}})]}),oc=we.object({traceBucketPath:Es,expiresInSeconds:we.number(),key:we.string(),uploadUrl:we.string(),sensitiveValues:we.array(we.string())}),ic=({authProvider:e,sessionId:t,orgId:n,workingDir:r,onTraceProofCaptured:s})=>G({name:"upload-trace-proof",tools:[W("upload-trace-proof",["Upload a Playwright trace proof for a created test file.","","IMPORTANT: This tool does NOT run tests. You must run the test yourself first","using Playwright with --trace=on and --output <dir>, then call this tool to upload the trace.","","Call this after running a created test file with tracing enabled.","The trace proves the test works and is viewable in the Stably web UI.","","Pass the testFilePath of the created test file and the outputDir from the --output flag.","Optionally pass tracePath if you know the exact path to the trace.zip file.","Optionally pass representativeTest to provide metadata for trace labeling."].join("\n"),{testFilePath:we.string().min(1).describe("Path to the created test file (relative to workspace root)."),outputDir:we.string().min(1).optional().describe("The --output directory from the Playwright test run containing trace.zip. Required if tracePath is not provided."),tracePath:we.string().min(1).optional().describe("Optional direct path to trace.zip. If omitted, the newest trace in outputDir is used."),representativeTest:Ga.optional().default({})},async({testFilePath:r,outputDir:o,tracePath:i,representativeTest:a})=>{const c=await e.getAuthHeader(),l=we.string().min(1).parse(r);Ga.parse(a??{}),cs.info("[upload-trace-proof] Uploading trace",{testFilePath:l,outputDir:o});const u=await Fa({tracePath:i,outputDir:o,requestUploadUrl:()=>(async({authHeader:e,sessionId:t,testFilePath:n,orgId:r,contentType:s="application/zip"})=>{const o=await(i={auth:e,body:{testFilePath:n,contentType:s},client:vr(),headers:Ts(r),path:{sessionId:t}},(i.client??cr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/sessions/{sessionId}/trace/upload-url",...i,headers:{"Content-Type":"application/json",...i.headers}}));var i;if(o.error)throw new Error(`Failed to presign session trace upload (${o.response.status})`);const a=oc.parse(o.data);return{traceBucketPath:a.traceBucketPath,expiresInSeconds:a.expiresInSeconds,key:a.key,uploadUrl:a.uploadUrl,sensitiveValues:a.sensitiveValues}})({authHeader:c,sessionId:t,testFilePath:l,orgId:n})});"captured"===u.status?cs.info("[upload-trace-proof] Upload succeeded",{testFilePath:l,traceBucketPath:u.storage}):cs.error("[upload-trace-proof] Failed",{testFilePath:l,error:u.error});const d={testFilePath:l,status:u.status,storage:"captured"===u.status?u.storage:null,..."error"in u?{error:u.error}:{}};return s?.(d),{content:[{type:"text",text:JSON.stringify(d)}]}})]}),ac=["QUEUED","RUNNING","PASSED","FAILED","TIMEDOUT","CANCELLED","INTERRUPTED"],cc=["LOCAL","CI","WEB"],lc=["MANUAL","SCHEDULED","UI","API","GITHUB_ACTION","SUITE_RUN"],uc=({authProvider:e,orgId:t,projectId:n})=>G({name:"run-history",tools:[W("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- Find the most recent run: { "limit": 1 }\n\nIf the user asks about test failures without specifying a run, use this to discover recent failed runs.\n\nReturns an array of runs with their runId, status, autoHealStatus, branch, and timestamps.',{branch:we.string().optional().describe("Filter by branch name"),status:we.enum(ac).optional().describe("Filter by status: QUEUED|RUNNING|PASSED|FAILED|TIMEDOUT|CANCELLED|INTERRUPTED"),limit:we.number().min(1).max(100).optional().describe("Max results (1-100, default 20)"),source:we.enum(cc).optional().describe("Filter by source: LOCAL|CI|WEB"),trigger:we.enum(lc).optional().describe("Filter by trigger: MANUAL|SCHEDULED|UI|API|GITHUB_ACTION|SUITE_RUN"),suite:we.string().optional().describe("Filter by suite name"),after:we.string().optional().describe("Pagination: return runs after this runId"),before:we.string().optional().describe("Pagination: return runs before this runId")},async({branch:r,status:s,limit:o,source:i,trigger:a,suite:c,after:l,before:u})=>{const d=await e.getAuthHeader(),p="string"==typeof r?r:void 0,f="string"==typeof s?s:void 0,h="number"==typeof o?o:void 0,g="string"==typeof i?i:void 0,m="string"==typeof a?a:void 0,y="string"==typeof c?c:void 0,b="string"==typeof l?l:void 0,w="string"==typeof u?u:void 0;cs.info("[run-history] list_runs called",{branch:p,status:f,limit:h});try{const e=await lr({auth:d,client:vr(),headers:Ts(t),query:{projectId:n,branchName:p,status:f,limit:h,source:g,trigger:m,suiteName:y,afterRunId:b,beforeRunId:w}});if(e.error||!e.data){const t=e.response?`API error: ${e.response.status}`:`API error: ${String(e.error)}`;return cs.error("[run-history] list_runs failed",{error:t}),{content:[{type:"text",text:`Error: ${t}`}],isError:!0}}return cs.info("[run-history] list_runs success",{runCount:e.data.runs?.length??0,hasMore:e.data.hasMore}),{content:[{type:"text",text:JSON.stringify(e.data)}]}}catch(e){const t=e instanceof Error?e.message:String(e);return cs.error("[run-history] list_runs exception",{error:t}),{content:[{type:"text",text:`Error: ${t}`}],isError:!0}}}),W("view_run",'Get detailed information about a specific run including issues and test results.\n\nThe response includes:\n- Run metadata (status, branch, timestamps, envName)\n- Issues array with result ("fixed"/"unfixed"), rootCause, and relatedTestIdentifiers\n- Test results with their outcomes\n- envName: the remote environment used (e.g., "staging") β if present, call load_environment with this name before rerunning tests\n\nUse this to examine run details and determine which tests failed or were previously fixed.',{runId:we.string().min(1).describe("The run ID to view (required)")},async({runId:n})=>{const r=await e.getAuthHeader(),s="string"==typeof n?n:String(n);cs.info("[run-history] view_run called",{runId:s});try{const e=await ur({auth:r,client:vr(),headers:Ts(t),path:{runId:s},query:{detail:"full"}});if(e.error||!e.data){const t=e.response?404===e.response.status?`Run "${s}" not found`:`API error: ${e.response.status}`:`API error: ${String(e.error)}`;return cs.error("[run-history] view_run failed",{error:t,runId:s}),{content:[{type:"text",text:`Error: ${t}`}],isError:!0}}return cs.info("[run-history] view_run success",{runId:s}),{content:[{type:"text",text:JSON.stringify(e.data)}]}}catch(e){const t=e instanceof Error?e.message:String(e);return cs.error("[run-history] view_run exception",{error:t,runId:s}),{content:[{type:"text",text:`Error: ${t}`}],isError:!0}}})]});function dc({localEnv:e,remoteEnv:t,remoteSensitiveValues:n,processEnv:r=process.env}){const s={};for(const[t,n]of Object.entries(e))void 0===r[t]&&(s[t]=n);if(t)for(const[n,o]of Object.entries(t))void 0===r[n]&&void 0===e[n]&&(s[n]=o);return n?.length&&void 0===r.STABLY_SENSITIVE_VALUES&&(s.STABLY_SENSITIVE_VALUES=Buffer.from(JSON.stringify(n)).toString("base64")),s}var pc=({hookEnvVars:e,localEnvSnapshot:t})=>G({name:"environment",tools:[W("load_environment",'Load remote environment variables by name (e.g., "staging", "production").\nUse this when you discover a run was executed with a specific --env and need\nthose variables for rerunning tests.\n\nAfter loading, all subsequent stably-browser run-test commands will automatically\nhave these environment variables injected. Use process.env.VARNAME syntax in test\ncode for these variables.\n\nReturns the list of variable names loaded (never values, for security).',{envName:we.string().min(1).describe('Environment name to load (e.g., "staging")')},async({envName:n})=>{const r="string"==typeof n?n:String(n);cs.info("[load-environment] Loading environment",{envName:r});try{const n=await vs(r);if(!n.ok)return cs.warn("[load-environment] Failed to load environment",{envName:r,error:n.error}),{content:[{type:"text",text:`Error: ${n.error}`}],isError:!0};const s=dc({localEnv:t??{},remoteEnv:n.result.variables,remoteSensitiveValues:n.result.sensitiveValues});for(const t of Object.keys(e))delete e[t];Object.assign(e,s);const o=Object.keys(n.result.variables);return cs.info("[load-environment] Environment loaded",{envName:r,variableCount:o.length}),{content:[{type:"text",text:`Successfully loaded ${o.length} variable(s) from "${r}" environment.\n\nVariable names: ${o.join(", ")}\n\nThese are now available for stably-browser run-test commands. Use \`process.env.VARNAME\` syntax in test code for these variables.`}]}}catch(e){const t=e instanceof Error?e.message:String(e);return cs.error("[load-environment] Exception loading environment",{envName:r,error:t}),{content:[{type:"text",text:`Error: ${t}`}],isError:!0}}})]}),fc=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]"),hc=(e,t)=>({message:fc(e),status:t?.status,statusText:t?.statusText}),gc=["ANTHROPIC_","CLAUDE"],mc=new Set(["AWS_BEARER_TOKEN_BEDROCK","BASH_DEFAULT_TIMEOUT_MS","BASH_MAX_OUTPUT_LENGTH","BASH_MAX_TIMEOUT_MS","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"]),yc=async({authHeader:e,mode:t,maxTurnsOverride:n})=>{const r=vr();cs.debug("Requesting subagent definitions from API",{mode:t,maxTurnsOverride:n});const s=await(o={client:r,auth:e,body:{mode:t,maxTurnsOverride:n}},(o.client??cr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/prompts/subagents",...o,headers:{"Content-Type":"application/json",...o.headers}}));var o;if(401===s.response.status)throw cs.warn("Subagent definitions fetch failed: unauthorized (401)"),await Nr(),new Error("Your session has expired or been revoked. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(403===s.response.status)throw cs.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(s.error)throw cs.warn("Subagent definitions fetch failed",{error:s.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}=s.data;return cs.debug("Subagent definitions received",{count:Object.keys(i).length}),i},bc=r.dirname($(import.meta.url)),wc=r.join(".claude-plugin","plugin.json"),vc=[r.join("packages","agent-plugin","stably-plugin-cli"),r.join("agent-plugin","stably-plugin-cli")];function Ic(e){return E(r.join(e,wc))}var{zStablyYaml:Tc}=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()}),n=e.object({maxTurnsPerIssue:e.number().int().positive().default(200),maxParallelWorkers:e.number().int().positive().default(3),rules:e.string().optional(),skipAfterConsecutiveUnfixed:e.number().int().positive().default(3),maxBudgetUsd:e.number().positive().default(50)}),r=e.object({maxTurnsPerTestFile:e.number().int().positive().default(200),maxBudgetUsd:e.number().positive().default(50)}),s=e.object({fix:n.optional(),create:r.optional()}),o=e.object({setupScript:e.string().optional()});return{zStablyYaml:e.object({schedules:e.record(e.string(),t).optional(),agent:s.optional(),cloud:o.optional()}),zAgentConfig:s,zAgentFixConfig:n,zAgentCreateConfig:r,zScheduleEntry:t,zCloudConfig:o}}(he),_c=async(e,t)=>{try{const n=await Ar(e,t);if(!n)return void cs.debug(`No ${t} found`);const r=await z(n,"utf-8");if(!r.trim())return;return r.length>1e4?(cs.warn(`${t} exceeds max length (${r.length} > 10000), truncating`,{path:n}),{content:r.slice(0,1e4),path:n}):(cs.debug(`Loaded ${t} rules`,{path:n,contentLength:r.length}),{content:r,path:n})}catch(e){return void cs.warn(`Failed to read ${t}`,{error:e})}},Ec=/\bstably-browser\b/,Sc=/\bpwtrace\b/,xc="(?:(?:-\\w+=?\\S*|--\\w+=?\\S*|-s\\s+\\S+|--session\\s+\\S+)\\s+)*",Ac=new RegExp(`\\bstably-browser\\s+${xc}run-test\\b`),kc=/\$\{process\.env\.([a-zA-Z_][a-zA-Z0-9_]*)\}/g,Cc=e=>/^[A-Za-z0-9_./:@=-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`,Pc=".stably-browser";async function Rc(){const e=i(o($(import.meta.url)),"stably-browser.js");if(E(e))return e;cs.debug("[stably-browser-hook] Bundled binary not found",{checkedPath:e});try{return Re.resolve("@stablyai-internal/playwright-cli/playwright-cli.js")}catch{cs.debug("[stably-browser-hook] @stablyai-internal/playwright-cli not resolvable from node_modules")}return new Promise((e,t)=>{m("which",["stably-browser"],(n,r)=>{if(n||!r.trim())return cs.warn("[stably-browser-hook] stably-browser not found on PATH",{error:n?.message}),void t(new Error("stably-browser not found. Ensure @stablyai-internal/playwright-cli is installed or stably-browser is on PATH."));e(r.trim())})})}async function Uc(){const e=i(o($(import.meta.url)),"pwtrace.js");if(E(e))return e;try{return Re.resolve("@stablyai-internal/pwtrace/bin/cli.js")}catch{}return new Promise((e,t)=>{m("which",["pwtrace"],(n,r)=>{!n&&r.trim()?e(r.trim()):t(new Error("pwtrace not found. Ensure @stablyai-internal/pwtrace is installed or pwtrace is on PATH."))})})}function $c(e,t,n=!1){const r=`${e}\n${t}`;return r.includes("spawn")&&r.includes("ENOENT")&&!r.includes("Executable doesn't exist")?{permanent:!0,reason:"Browser binary exists but cannot be executed (likely Alpine Linux / musl libc incompatibility).",guidance:"The Chromium binary was downloaded but the OS cannot execute it. This usually happens on Alpine Linux containers because Chromium is compiled for glibc, not musl. Ask the user to either: (1) switch to a glibc-based image like node:20-slim instead of node:20-alpine, (2) install glibc compatibility with `apk add gcompat`, or (3) use the official Playwright Docker image (mcr.microsoft.com/playwright). Do not attempt to install browsers β they are already installed, the issue is OS-level. Do not retry stably-browser commands β they will all fail for the same reason."}:r.includes("is not installed")||r.includes("Executable doesn't exist")?{permanent:!0,reason:"Browser is not installed in this environment.",guidance:"The Playwright browser binary is missing. Ask the user to run `npx playwright install chromium` in their environment (or add it to their Dockerfile/CI setup). Do not attempt to install browsers yourself. You can still analyze test code, make fixes, and use upload-trace-proof (it only uploads existing traces, no browser needed), but cannot run tests locally until browsers are installed. Do not retry stably-browser commands β they will all fail for the same reason."}:r.includes("Missing system dependencies")||r.includes("cannot open shared object file")?{permanent:!0,reason:"Browser system dependencies are missing.",guidance:"The browser binary exists but required system libraries are missing. Ask the user to run `npx playwright install-deps chromium` (requires apt/sudo) or use a Playwright Docker image. Do not attempt to install system packages yourself. Do not retry stably-browser commands β they will all fail for the same reason."}:r.includes("already in use")?{permanent:!1,reason:"Browser profile is locked by another process.",guidance:"Another browser session is using the same profile. Try closing the existing session with `stably-browser close` first, or use a different session name."}:r.includes("sandboxing failed")||r.includes("--no-sandbox")?{permanent:!0,reason:"Browser sandboxing failed (likely running as root in a container).",guidance:"Chrome cannot create a sandbox when running as root. Ask the user to either: (1) add `chromiumSandbox: false` to their Playwright launch options, (2) add `--no-sandbox` to their Chrome args, or (3) run the container as a non-root user. Do not attempt to fix this yourself β it requires changes to the user's Playwright config or Docker setup. Do not retry stably-browser commands β they will all fail for the same reason."}:n||e.includes("ETIMEDOUT")||e.includes("timed out")?{permanent:!1,reason:"Daemon startup timed out.",guidance:"The browser daemon did not start within 30 seconds. This may be caused by slow browser download, resource constraints, or a hung process. Retry once, and if it fails again, ask the user to check their environment."}:{permanent:!1,reason:r.slice(0,500).trim(),guidance:"An unexpected error occurred starting the browser daemon. Share the error with the user."}}async function Lc(e,t,n,r,s="chromium"){const o=["open",`-s=${t}`];let i;return n&&o.push("--headed"),r?o.push(`--config=${r}`):o.push(`--browser=${s}`),cs.info("[stably-browser-hook] Starting daemon",{bin:e,args:o}),process.env.CHROME_BIN&&(i={...process.env,PLAYWRIGHT_MCP_EXECUTABLE_PATH:process.env.CHROME_BIN}),"linux"===process.platform&&"function"==typeof process.getuid&&0===process.getuid()&&(i={...i??process.env,PLAYWRIGHT_MCP_SANDBOX:"false"},cs.info("[stably-browser-hook] Running as root on Linux, disabling Chromium sandbox")),new Promise(t=>{m(process.execPath,[e,...o],{timeout:3e4,env:i},(e,n,r)=>{if(e)return cs.error("[stably-browser-hook] Failed to start daemon",{error:e.message,stderr:r}),void t({ok:!1,...$c(e.message,r??"",e.killed??!1)});cs.info("[stably-browser-hook] Daemon started",{stdout:n.trim()}),t({ok:!0})})})}function Dc(e,t){return t?`${e}-${t}`:e}function Nc(e){if(e&&"object"==typeof e&&"agent_id"in e){const t=e.agent_id;return"string"==typeof t?t:void 0}}async function Oc(e,t,n){const r=new URL(`/internal/v1/browser/request/${t}`,pr);r.searchParams.set("projectId",n);const s=await fetch(r.toString(),{method:"GET",headers:{Authorization:`Bearer ${e}`}});if(!s.ok)throw new Error(`Poll failed: HTTP ${s.status}`);return s.json()}async function Bc(e,t,n){const r=new URL(`/internal/v1/browser/request/${t}/acquire`,pr).toString(),s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({projectId:n})});if(!s.ok)throw new Error(`Acquire failed: HTTP ${s.status}`);return s.json()}async function jc(e,t,n){const r=new URL(`/internal/v1/cli/browser/kernelsh/${n}/health`,pr);r.searchParams.set("projectId",t);const s=r.toString();try{const t=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${e}`}});return!!t.ok&&(await t.json()).alive}catch{return!1}}var Mc=2e3,Fc=class{authProvider;projectId;sessions=new Map;healthCheckTimer=null;released=!1;configDir=null;constructor(e){this.authProvider=e.authProvider,this.projectId=e.projectId}async acquire(e,t){const n=this.sessions.get(e);if(n&&!n.needsRecreation)return n.session;n?.needsRecreation&&await this.releaseSession(e),this.released=!1;const r=await this.acquireViaQueue(t);cs.info("[cloud-browser] Waiting for CDP endpoint to be ready...",{sessionName:e,sessionId:r.sessionId}),await async function(e){const t=Date.now()+3e4;for(;Date.now()<t;)try{return void await new Promise((t,n)=>{const r=new ve(e),s=setTimeout(()=>{r.close(),n(new Error("CDP connection timeout"))},5e3);r.on("open",()=>{r.send(JSON.stringify({id:1,method:"Browser.getVersion",params:{}}))}),r.on("message",e=>{try{const o=JSON.parse(e.toString());1===o.id&&(clearTimeout(s),r.close(),o.error?n(new Error(`CDP error: ${o.error.message}`)):t())}catch{}}),r.on("error",e=>{clearTimeout(s),r.close(),n(e)})})}catch(e){const n=t-Date.now();if(n<=500)throw new Error(`CDP endpoint not ready after 30000ms: ${e instanceof Error?e.message:String(e)}`);cs.debug("[cloud-browser] CDP not ready, retrying...",{error:e instanceof Error?e.message:String(e),remainingMs:n}),await Hc(500)}throw new Error("CDP endpoint not ready after 30000ms")}(r.cdpUrl),cs.info("[cloud-browser] CDP endpoint ready",{sessionName:e,sessionId:r.sessionId});const s=this.writeConfig(e,r.cdpUrl);return this.sessions.set(e,{session:r,configPath:s,needsRecreation:!1}),this.ensureHealthCheck(),r}async release(){if(this.released)return;this.released=!0,this.stopHealthCheck();const e=Array.from(this.sessions.keys()).map(e=>this.releaseSession(e));await Promise.all(e),this.cleanupConfigDir()}needsRecreation(e){return this.sessions.get(e)?.needsRecreation??!1}getConfigPath(e){return this.sessions.get(e)?.configPath??null}getAnyConfigPath(){for(const e of this.sessions.values())if(!e.needsRecreation)return e.configPath;return null}isActive(){return this.sessions.size>0&&!this.released}removeSession(e){this.sessions.delete(e)}async acquireViaQueue(e){const t=await this.authProvider.getAuthHeader(),n=await async function(e,t){const n=new URL("/internal/v1/browser/request",pr).toString();try{const r=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({projectId:t,source:"cli-browser-session"})});if(r.ok||202===r.status){const e=await r.json();return{ok:!0,browserRequestId:e.browserRequestId,initialStatus:e.status}}if(403===r.status)return{ok:!1,status:"forbidden",message:(await r.json().catch(()=>({error:"Forbidden"}))).error??"Cloud browsers not available on your plan."};const s=await r.text().catch(()=>"");return{ok:!1,status:"error",message:`HTTP ${r.status}: ${s.slice(0,200)}`}}catch(e){return{ok:!1,status:"error",message:e instanceof Error?e.message:String(e)}}}(t,this.projectId);if(!n.ok){if("forbidden"===n.status)throw new Error(`Cloud browsers not available on your plan. ${n.message}`);throw new Error(`Cloud browser unavailable: ${n.message}`)}const{browserRequestId:r,initialStatus:s}=n;"queued"===s&&e?.();const o=Date.now()+3e5;for(;Date.now()<o;){const t=await this.authProvider.getAuthHeader(),n=await Oc(t,r,this.projectId);switch(n.status){case"pending":await Hc(Mc);continue;case"queued":e?.(),await Hc(Mc);continue;case"provisioning":cs.debug("[cloud-browser] Browser is starting up..."),await Hc(Mc);continue;case"ready":try{const e=await this.authProvider.getAuthHeader(),t=await Bc(e,r,this.projectId);return{sessionId:t.sessionId,browserRequestId:r,cdpUrl:t.cdpUrl,liveViewUrl:t.liveViewUrl??""}}catch{cs.debug("[cloud-browser] Acquire failed, re-polling status"),await Hc(Mc);continue}case"failed":throw new Error(n.error??"Browser provisioning failed. Please try again.");case"cancelled":case"stopped":throw new Error("Browser request was cancelled.");default:throw new Error(`Unexpected browser request status: ${n.status}`)}}const i=await this.authProvider.getAuthHeader();throw await async function(e,t,n){const r=new URL(`/internal/v1/browser/request/${t}/cancel`,pr).toString();try{const s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({projectId:n})});s.ok||cs.warn("[cloud-browser] Failed to cancel browser request",{browserRequestId:t,status:s.status})}catch(e){cs.warn("[cloud-browser] Error cancelling browser request",{browserRequestId:t,error:e instanceof Error?e.message:String(e)})}}(i,r,this.projectId).catch(()=>{}),new Error("Cloud browser unavailable: timed out waiting for provisioning. Remove --browser=cloud to use a local browser, or wait for a browser to free up.")}writeConfig(e,t){this.configDir||(this.configDir=i(N(),`stably-cloud-browser-${process.pid}`),I(this.configDir,{recursive:!0}));const n=e.replace(/[^a-zA-Z0-9_-]/g,"_"),r=i(this.configDir,`config-${n}.json`),s={browser:{cdpEndpoint:t,isolated:!1},saveSession:!1,outputDir:i(process.cwd(),".stably-browser")};return T(r,JSON.stringify(s,null,2),"utf-8"),cs.debug("[cloud-browser] Wrote config file",{sessionName:e,path:r}),r}cleanupConfigDir(){if(this.configDir){try{_(this.configDir,{recursive:!0,force:!0})}catch{}this.configDir=null}}async releaseSession(e){const t=this.sessions.get(e);if(!t)return;const{sessionId:n,browserRequestId:r}=t.session;cs.info("[cloud-browser] Releasing session",{sessionName:e,sessionId:n,browserRequestId:r});try{const e=await this.authProvider.getAuthHeader();await async function(e,t,n){const r=new URL(`/internal/v1/browser/request/${t}/release`,pr).toString();try{const s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({projectId:n})});s.ok||cs.warn("[cloud-browser] Failed to release browser",{browserRequestId:t,status:s.status})}catch(e){cs.warn("[cloud-browser] Error releasing browser",{browserRequestId:t,error:e instanceof Error?e.message:String(e)})}}(e,r,this.projectId)}catch(t){cs.warn("[cloud-browser] Error releasing session",{sessionName:e,sessionId:n,error:t instanceof Error?t.message:String(t)})}this.sessions.delete(e)}ensureHealthCheck(){this.healthCheckTimer||(this.healthCheckTimer=setInterval(async()=>{if(0===this.sessions.size||this.released)this.stopHealthCheck();else for(const[e,t]of this.sessions)if(!t.needsRecreation)try{const n=await this.authProvider.getAuthHeader();await jc(n,this.projectId,t.session.sessionId)||(cs.warn("[cloud-browser] Browser session is dead, marking for recreation",{sessionName:e,sessionId:t.session.sessionId}),t.needsRecreation=!0)}catch(n){cs.warn("[cloud-browser] Health check failed",{sessionName:e,sessionId:t.session.sessionId,error:n instanceof Error?n.message:String(n)})}},3e4),this.healthCheckTimer.unref&&this.healthCheckTimer.unref())}stopHealthCheck(){this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null)}};function Hc(e){return new Promise(t=>setTimeout(t,e))}function Gc({configuredSessionName:e,isFixMode:t,useCloudBrowser:n}){return e??(t||n?"auto":"default")}var Wc=he.object({verdict:he.enum(["PASS","FAIL","INCONCLUSIVE"]),steps:he.array(he.string()).min(1),reason:he.string().nullable(),evidence:he.array(he.string())}).superRefine((e,t)=>{"PASS"===e.verdict||e.reason&&0!==e.reason.trim().length||t.addIssue({code:he.ZodIssueCode.custom,path:["reason"],message:"reason is required for FAIL and INCONCLUSIVE verdicts"})}),Vc=/\bmcp__playwright-mcp__[a-z0-9_]+\b/gi,Yc=/\.playwright-mcp(?:\/[^\s"'`)\]]*)?/gi,zc=/\bplaywright[\s_-]?mcp\b/gi;function qc(e){return e.replace(Vc,"browser_tool").replace(Yc,"verification-artifact").replace(zc,"browser automation")}function Kc(e){return{...e,steps:e.steps.map(e=>qc(e)),reason:e.reason?qc(e.reason):null,evidence:e.evidence.map(e=>qc(e))}}function Jc(e){const t=e.matchAll(/```verdict\s*\r?\n([\s\S]*?)\r?\n```/g);let n=null;for(const e of t)try{const t=JSON.parse(e[1]??"");n=Wc.parse(t)}catch{}return n}function Xc({mode:e,lastAssistantText:t,maxLength:n=1e4}){const r="verify"===e&&t?qc(t):t;return r?r.slice(0,n):null}var Qc=e=>{const t=e.prompt;return(Array.isArray(t)?t.join(" "):t)?.trim()||void 0},Zc=e=>new Promise(t=>setTimeout(t,e)),el=["Bash","Read","Write","Edit","Glob","Grep","Task","Skill"],tl=["Task","Skill"],nl=["Bash","Read","Write","Edit","Glob","Grep","mcp__session-control"],rl=e=>{if("EPIPE"!==e.code)throw e},sl="__main__",ol=[3e3,5173,4173,8080,4200,8e3],il=/\b(TEST_EMAIL|TEST_PASSWORD|auth|authentication|credentials|login|log in|sign in)\b/i,al=/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/i,cl=/playwright[\s_-]?mcp/i,ll=e=>"mcp__auto-heal-report__generate-report"===e;async function ul(e,t){return!!e&&(!!e.hasQueuedMessages()||new Promise(n=>{const r=setTimeout(()=>{clearInterval(s),n(!1)},t),s=setInterval(()=>{e.hasQueuedMessages()&&(clearTimeout(r),clearInterval(s),n(!0))},200)}))}async function dl(e){return new Promise(t=>{const n=new te.Socket;let r=!1;const s=e=>{r||(r=!0,n.destroy(),t(e))};n.setTimeout(700),n.once("connect",()=>s(!0)),n.once("timeout",()=>s(!1)),n.once("error",()=>s(!1)),n.connect(e,"127.0.0.1")})}var pl=async(e,t,n)=>{const r=n?"[Y/n]":"[y/N]",s=(await e.question(`${Dn("info","?")} ${t} ${re.gray(r)} `)).trim().toLowerCase();return s?"y"===s||"yes"===s:n},fl=async e=>{if("single"===e.mode){const t=Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt;cs.initSession(t||"create-from-diff")}else if("verify"===e.mode){const t=Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt;cs.initSession(t||"verify")}else if("fix"===e.mode)cs.initSession(`fix-${e.runId}`);else if("plan"===e.mode){const t=Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt;cs.initSession(t||"plan")}cs.info("Agent session starting",{mode:e.mode});const a=(e=>{switch(e.mode){case"chat":return"Ask Stably to build tests for you";case"init":return"Setting up Playwright and Stably SDK";case"fix":return"Fixing broken tests";case"single":return Qc(e)||"Creating tests from PR/branch changes";case"verify":return Qc(e)||"Verifying application";case"plan":return Qc(e)||"Planning test coverage"}})(e),c=((e,t)=>{const n=e?.trim().toLowerCase();return n?"1"===n||"true"===n||"yes"===n?t:"chat"===n||"single"===n||"fix"===n||"init"===n||"verify"===n||"plan"===n||"error"===n?n:null:null})(process.env.STABLY_CLI_VISUAL_MOCK,e.mode);if(process.env.STABLY_CLI_VISUAL_MOCK&&!c)throw new Error("Invalid STABLY_CLI_VISUAL_MOCK value. Expected one of: 1, true, chat, single, fix, init, verify, plan, error.");if(c){if(cs.info("Running CLI visual mock session",{requestedMode:e.mode,scenario:c}),"error"===c){const e={log:[{content:"Visual mock mode enabled. Simulating a failed AI run without contacting the backend.",id:0,kind:"text"}],promptDisplay:a,status:"running"},t=await jo(e);return t.setRunningLabel({label:"Simulating upstream failure..."}),await new Promise(e=>setTimeout(e,220)),t.setStatus({status:"error",error:"Mocked AI provider failure for CLI visual testing."}),await new Promise(e=>setTimeout(e,220)),void await t.cleanup()}return void await(async({mode:e,promptDisplay:t})=>{const n={log:[],promptDisplay:t,status:"running"},r=await jo(n,"init"===e?{showSpinnerImmediately:!0,isInitMode:!0}:"fix"===e?{isFixMode:!0}:void 0),s=async(e,t=180)=>{e(),await Zc(t)};try{if("chat"===e)return await s(()=>r.appendText({text:"Visual mock mode enabled. No real AI calls will be made.\n\n"})),await s(()=>r.appendUserMessage({text:"Create a login test for the dashboard."})),await s(()=>r.appendThinking({text:"Scanning the repository for auth flows and existing test patterns..."})),await s(()=>r.flushThinkingRender(),120),await s(()=>r.addTool({rawName:"Glob",toolInput:{pattern:"**/*login*"}})),await s(()=>r.addToolResult({message:"Found 4 matching files"})),await s(()=>r.appendText({text:"I found the existing auth helpers and would generate a Playwright test next.\n"})),void await s(()=>r.setStatus({status:"success",result:"Mock chat transcript complete."}),260);if("single"===e)return await s(()=>r.setRunningLabel({label:"Analyzing app structure..."})),await s(()=>r.appendThinking({text:"Reviewing routes, existing tests, and the requested flow..."})),await s(()=>r.flushThinkingRender(),120),await s(()=>r.addTool({rawName:"Read",toolInput:{file_path:"app/page.tsx"}})),await s(()=>r.addToolResult({message:"Read homepage and CTA structure"})),await s(()=>r.addTool({rawName:"Write",toolInput:{file_path:"tests/auth/login.spec.ts"}})),await s(()=>r.addToolResult({message:"Created tests/auth/login.spec.ts"})),await s(()=>r.appendText({text:"Generated a focused login flow test with stable selectors and assertions.\n"})),void await s(()=>r.setStatus({status:"success",result:"Created 1 mock test file: tests/auth/login.spec.ts"}),260);if("verify"===e)return await s(()=>r.appendText({text:"Starting verification...\nTarget URL: http://localhost:3000\n"})),await s(()=>r.setRunningLabel({label:"Calibrating verification flow..."})),await s(()=>r.appendThinking({text:"Planning a short verification pass for the requested path..."})),await s(()=>r.flushThinkingRender(),120),await s(()=>r.addTool({rawName:"mcp__playwright__browser_navigate",toolInput:{url:"http://localhost:3000"}})),await s(()=>r.addToolResult({message:"Opened application homepage"})),await s(()=>r.addTool({rawName:"mcp__playwright__browser_click",toolInput:{element:"Sign in button"}})),await s(()=>r.addToolResult({message:"Reached login form successfully"})),await s(()=>r.appendText({text:"Verification passed for the main sign-in path.\n"})),void await s(()=>r.setStatus({status:"success",result:"Verified requested behavior in visual mock mode."}),260);if("fix"===e)return await s(()=>r.setRunningLabel({label:"Triaging failing tests..."})),await s(()=>r.addSubagentStart({toolUseId:"triage-1",subagentType:"triage",description:"Analyze failing selectors and isolate the root cause"})),await s(()=>r.addSubagentActivity({toolUseId:"triage-1",kind:"text",content:'Selector drift detected after the button label changed from "Log in" to "Sign in".'})),await s(()=>r.setSubagentStatus({toolUseId:"triage-1",status:"complete"})),await s(()=>r.addSubagentStart({toolUseId:"code-1",subagentType:"code-worker",description:"Fix login test selectors"})),await s(()=>r.addSubagentActivity({toolUseId:"code-1",kind:"tool",content:"Edit tests/auth/login.spec.ts"})),await s(()=>r.addSubagentActivity({toolUseId:"code-1",kind:"tool_result",content:"Updated role-based button locator"})),await s(()=>r.setSubagentStatus({toolUseId:"code-1",status:"complete"})),await s(()=>r.addSubagentStart({toolUseId:"validation-1",subagentType:"validation",description:"Re-run impacted tests"})),await s(()=>r.addSubagentActivity({toolUseId:"validation-1",kind:"text",content:"Validation run passed for 3/3 affected tests."})),await s(()=>r.setSubagentStatus({toolUseId:"validation-1",status:"complete"})),void await s(()=>r.setStatus({status:"success",result:"Mock fix flow complete. 1 test fixed, 0 failed."}),260);if("init"===e)return await s(()=>r.addTool({rawName:"Bash",toolInput:{command:"npm install -D @playwright/test @stablyai/playwright"}})),await s(()=>r.addToolResult({message:"Installed Playwright and Stably SDK dependencies"})),await s(()=>r.addTool({rawName:"Write",toolInput:{file_path:"playwright.config.ts"}})),await s(()=>r.addToolResult({message:"Configured Playwright reporter and base settings"})),await s(()=>r.appendText({text:"Playwright and the Stably SDK are configured. You can run `stably test` next.\n"})),void await s(()=>r.setStatus({status:"success",result:"Initialization mock complete."}),260);await s(()=>r.setRunningLabel({label:"Building coverage plan..."})),await s(()=>r.appendThinking({text:"Comparing routes, existing tests, and high-risk gaps..."})),await s(()=>r.flushThinkingRender(),120),await s(()=>r.addTool({rawName:"Read",toolInput:{file_path:"tests/"}})),await s(()=>r.addToolResult({message:"Mapped existing coverage across auth, billing, and onboarding"})),await s(()=>r.appendText({text:"Planned three new `test.fixme()` specs for the highest-risk uncovered flows.\n"})),await s(()=>r.setStatus({status:"success",result:"Planning mock complete."}),260)}finally{await Zc(120),await r.cleanup()}})({mode:c,promptDisplay:a})}process.stdout.on("error",rl),process.stderr.on("error",rl);const l=e=>{if("EPIPE"!==e.code)throw e};process.on("uncaughtException",l),cs.debug("Checking authentication");const u=await ms({autoLogin:"chat"===e.mode||"init"===e.mode}),d=new ws(u);cs.debug("Authentication resolved",{authType:u.type});const p="oauth"===u.type?u.auth.context.orgId:void 0,f=r.resolve(process.cwd()),h="fix"!==e.mode,g=r.join(f,".env"),y=h&&v.existsSync(g)&&v.statSync(g).isFile(),b=y?t(v.readFileSync(g,"utf8")):{};cs.debug("Environment file",{path:g,exists:y,variableCount:Object.keys(b).length});const I="chat"!==e.mode&&"init"!==e.mode,T="chat"===e.mode,_="chat"===e.mode||"init"===e.mode,S="single"===e.mode,k="verify"===e.mode,C="plan"===e.mode,P=S||k||C;let R,U=new so;"init"===e.mode&&(R=e.initPreferences??await async function(){if(!process.stdin.isTTY||!process.stdout.isTTY)return{googleAuth:!0,emailPackage:!1};const e=ne({input:process.stdin,output:process.stdout});try{return{googleAuth:await pl(e,"Include Google Auth test helper guidance? (recommended)",!0),emailPackage:await pl(e,"Install @stablyai/email for inbox testing?",!1)}}finally{e.close()}}());const $="chat"===e.mode?e.getHelpText:void 0,L="verify"===e.mode?(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt).trim():"";let D="verify"===e.mode?e.url?.trim()||function(e){const t=Array.isArray(e)?e.join(" "):e,n=e=>e.replace(/[),.;!?]+$/,""),r=e=>{const t=n(e);try{return new URL(t).toString()}catch{return}},s=t.match(/https?:\/\/[^\s"'`<>]+/i);if(s)return r(s[0]);const o=t.match(/(?<!@)\b(?:localhost|(?:\d{1,3}\.){3}\d{1,3}|(?:[a-z0-9-]+\.)+[a-z]{2,63})(?::\d{2,5})?(?:\/[^\s"'`<>]*)?/i);if(!o)return;const i=n(o[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:r(`${"localhost"===c||"127.0.0.1"===c?"http":"https"}://${i}`)}(e.prompt):void 0;if("verify"===e.mode&&!e.url&&D&&cs.info("[verify] Using URL extracted from prompt",{url:D}),"verify"!==e.mode||D||(D=await async function(){for(const e of ol)if(await dl(e))return`http://localhost:${e}`}(),D?cs.info("[verify] Detected local application URL",{url:D}):cs.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:s,workingDir:o}){if(!process.stdin.isTTY||!process.stdout.isTTY)return{resolvedUrl:n};const i=r.join(o,"STABLY.md"),a=v.existsSync(i),c=a?await v.promises.readFile(i,"utf8").catch(()=>{}):void 0;let l=n?.trim()||void 0;const u=!l,d=(({envEmail:e,envPassword:t,promptIncludesEmail:n,stablyMdContent:r})=>!Boolean(e?.trim()&&t?.trim())&&!n&&!(e=>!!e&&il.test(e))(r))({envEmail:process.env.TEST_EMAIL??t.TEST_EMAIL,envPassword:process.env.TEST_PASSWORD??t.TEST_PASSWORD,promptIncludesEmail:al.test(s),stablyMdContent:c}),p=!a;if(!u&&!d&&!p)return{resolvedUrl:l};const f=ne({input:process.stdin,output:process.stdout}),h=async(n,r)=>{const s=v.existsSync(e)?await v.promises.readFile(e,"utf8"):"",o=new RegExp(`^${i=n,i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}=.*$`,"m");var i;const a=`${n}=${(e=>/^[A-Za-z0-9_./:@-]+$/.test(e)?e:`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)(r)}`,c=o.test(s)?s.replace(o,a):`${s}${s&&!s.endsWith("\n")?"\n":""}${a}\n`;await v.promises.writeFile(e,c,"utf8"),t[n]=r};try{if(u){const e=(await f.question("Starting URL (optional, Enter to auto-infer): ")).trim();e&&(l=e)}if(d&&await pl(f,"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 h("TEST_EMAIL",e),await h("TEST_PASSWORD",t),process.env.TEST_EMAIL||(process.env.TEST_EMAIL=e),process.env.TEST_PASSWORD||(process.env.TEST_PASSWORD=t))}if(p&&await pl(f,"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 v.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 v.promises.readFile(i,"utf8"),n=/(^|\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 v.promises.writeFile(i,n,"utf8")}}return{resolvedUrl:l}}finally{f.close()}}({envFilePath:g,envFromFile:b,initialUrl:D,verifyPromptText:L,workingDir:f});D=e.resolvedUrl?.trim()||D}"verify"!==e.mode||D||cs.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 N={log:[],promptDisplay:a,status:"running"};let O,B,j,M,F=I,H=!1,q=0,K=[],J=!1,X=!1,Q=0;const Z=new Map,ee=[],te=e=>{ee.push(e)},se=new Map;let oe=null,ie=!1,ae=!1;const ce=Date.now();let le,ue="fix"===e.mode?{suiteId:e.runId,phase:"initializing",totalTests:null,fixedTests:0,failedTests:0,currentTestDescription:null,lastTestDescription:null,startedAt:ce,endedAt:null,isError:!1,updatedAt:ce,recentActivity:[],workers:[{id:sl,testDescription:"Orchestrator",workerType:"main",status:"running",summary:null,startedAt:ce,endedAt:null,activity:[]}]}:null;const de=new Set,pe=new Map,fe=(e,t)=>{const n=pe.get(e);if(!n)return;const r={...n,...t};pe.set(e,r),_e({workers:Array.from(pe.values())})},he=(e,t)=>{if(!ue)return;const n=ue.workers.map(n=>{if(n.id!==e)return n;const r=[...n.activity,{...t,timestamp:Date.now()}].slice(-15);return{...n,activity:r}});ye({workers:n})},ge=e=>{if(!ue)return;const t=[...ue.recentActivity,{...e,timestamp:Date.now()}].slice(-10);ye({recentActivity:t})},me=e=>(ue?.workers??[]).map(t=>t.id===sl?{...t,status:e?"failed":"succeeded",endedAt:t.endedAt??Date.now()}:"running"===t.status?{...t,status:"failed",endedAt:Date.now()}:t),ye=e=>{ue&&!le?.isClosed&&(ue={...ue,...e,updatedAt:Date.now()},le?.sendProgress(ue))},be=async t=>{if("fix"===e.mode){if("STARTED"===t){if(ie)return;ie=!0}else{if(ae)return;ae=!0}try{await(async({authHeader:e,orgId:t,runId:n,status:r})=>{const s=await(o={auth:e,body:{status:r},client:vr(),headers:Ts(t),path:{runId:n}},(o.client??cr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-status",...o,headers:{"Content-Type":"application/json",...o.headers}}));var o;if(s.error)throw new Error(`Failed to update autoheal status (${s.response.status})`)})({authHeader:await d.getAuthHeader(),orgId:p,runId:e.runId,status:t})}catch{}}},ve=Date.now();let Ie,Te=null;const _e=e=>{Te&&!Ie?.isClosed&&(Te={...Te,...e,updatedAt:Date.now()},Ie?.sendProgress(Te))},Ee=e=>{if(!Te)return;const t=[...Te.recentActivity,{...e,timestamp:Date.now()}].slice(-10);_e({recentActivity:t})};let Se;const xe=(e.mode,!0);if(cs.info("[session] Checking session creation",{mode:e.mode,shouldCreateSession:xe}),"fix"===e.mode)cs.info("[session] Deferring fix-mode session creation until after early-exit checks");else try{cs.info("[session] Creating progress session",{mode:e.mode,projectId:ys(u)});const t=await fo({agentMode:e.mode,authHeader:await d.getAuthHeader(),orgId:p,projectId:ys(u)}),{sessionId:n,sessionMode:r}=t;if(Se=n,P){const t="single"===e.mode||"verify"===e.mode||"plan"===e.mode?Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt:null,r=oo(f);Te={sessionId:n,phase:"initializing",startedAt:ve,endedAt:null,isError:!1,updatedAt:ve,currentActivity:null,filesCreated:[],traceProofs:[],recentActivity:[],prompt:t||null,environment:{gitBranch:r?.branch??null,workingDirectory:f,nodeVersion:process.version,cliVersion:dr}},Ie=new Rs({authProvider:d,orgId:p,sessionId:n,onUserMessage:e=>{U&&(cs.info("[ws] Injecting web UI message into agent",{contentLength:e.length}),Ee({type:"user_message",summary:e}),Fe({text:`[Web] ${e}`}),U.pushText(`[Message from web UI user]: ${e}`),F||(F=!0,Ze({status:"running"})))}}),await Ie.start(),_e({phase:"initializing"})}cs.info(`[${r}] Progress session created`,{sessionId:n})}catch(e){const t=e instanceof Error?e.message:String(e);cs.warn(`[progress] Session creation failed (non-fatal): ${t}`)}const Ae={current:e=>{}},ke={current:async()=>{}};let Pe;const Re={current:()=>{}};let $e=!1,Le=!1;const{addSubagentActivity:De,addSubagentStart:Ne,addTool:Oe,appendCancelled:Be,appendText:je,appendThinking:Me,appendUserMessage:Fe,cancelThinkingRender:He,cleanup:Ge,dismissPermissionPrompt:We,flushThinkingRender:Ve,resetThinkingLogIndex:Ye,setExiting:ze,setRunningLabel:qe,setStatus:Ke,setSubagentStatus:Je,updateFixProgress:Xe}=await jo(N,"init"===e.mode?{onCancel:()=>Re.current(),onExit:()=>ke.current(),onSend:e=>Ae.current(e),showSpinnerImmediately:!0,isInitMode:!0}:"chat"===e.mode?{onCancel:()=>Re.current(),onExit:()=>ke.current(),onSend:e=>Ae.current(e)}:"fix"===e.mode?{onExit:()=>ke.current(),isFixMode:!0}:{onExit:()=>ke.current()});let Qe=N.status;const Ze=({error:e,result:t,status:n})=>{Qe=n,Ke({error:e,result:t,status:n})};let et,tt;k&&(je({text:"Starting verification...\n"}),je(D?{text:`Target URL: ${D}\n`}:{text:"Target URL: auto-detect (agent may infer from project config)\n"}),qe({label:"Calibrating verification flow..."})),Ae.current=e=>{const t=e.trim();if(T&&!cs.getLogFilePath()&&cs.initSession(t||"chat"),cs.debug("User message",{text:t}),"/help"===t){F&&U&&(H=!0,O?.interrupt?.(),U.allowNextTurn(),F=!1),"running"===Qe&&Ze({status:"success"}),Fe({text:e});const t=$?.();return void je({text:t??"Help is not available in this session."})}if(T&&qe({label:void 0}),U){if(F)return Ze({status:"running"}),Fe({text:e}),U.pushText(e),void(q+=1);Ze({status:"running"}),Fe({text:e}),te({role:"user",content:e,timestamp:(new Date).toISOString()}),U.pushText(e),F=!0}};let nt="",rt="";const st=[],ot=[],it=[];let at;const ct=await(async e=>{try{const t=await Ar(e,"stably.yaml");if(!t)return void cs.debug("No stably.yaml found");const n=await z(t,"utf-8");if(!n.trim())return;const r=Ce(n),s=Tc.parse(r.toJS()),o=s.agent?.fix?.maxTurnsPerIssue,i=s.agent?.fix?.maxParallelWorkers,a=!!s.agent?.fix?.rules;return cs.debug(`Loaded stably.yaml: maxTurnsPerIssue=${o??"default"}, maxParallelWorkers=${i??"default"}, hasRules=${a}`,{path:t,config:s.agent}),s}catch(e){return void cs.warn("Failed to parse stably.yaml",{error:e})}})(f),lt=ct?.agent?.fix?.skipAfterConsecutiveUnfixed,ut=await(async()=>{if("single"===e.mode){const n=await async function(e,t){const n=s(e);if(t){const e=s(n,t);return Io(e,"output-flag"),{path:e,source:"output-flag"}}const r=bo(n);if(r){const e=await async function(e){try{const t=(await z(e,"utf-8")).match(/testDir:\s*['"]([^'"]+)['"]/);return t?.[1]}catch{return}}(r);if(e){const t=s(o(r),e);if(vo(t))return Io(t,"playwright.config.ts"),{path:t,source:"playwright.config.ts"}}}for(const e of wo){const t=i(n,e);if(vo(t))return Io(t,"auto-detected"),{path:t,source:"auto-detected"}}return Io(n,"cwd-fallback"),{path:n,source:"cwd-fallback"}}(f,e.outputDir);return at=n.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: ${at}]`}var t;if("verify"===e.mode)return function(e,t){const n=(Array.isArray(e)?e.join(" "):e).trim()||"Verify the application behavior.",r=t?.trim();return r?`Starting URL: ${r}\nURL policy: treat this as the source of truth and do not switch domains unless the user explicitly asks.\n\nVerification prompt: ${n}`:n}(e.prompt,D);if("fix"===e.mode)try{cs.info("[fix] Fetching autoheal context",{runId:e.runId,skipAfterConsecutiveUnfixed:lt});const t=Date.now(),{context:n,autohealReportUrl:r,skippedTests:s,newerPassingSuiteId:o,envName:i}=await(async({authHeader:e,orgId:t,runId:n,skipAfterConsecutiveUnfixed:r})=>{cs.debug("Fetching autoheal context",{runId:n,skipAfterConsecutiveUnfixed:r});const s=await(o={auth:e,client:vr(),headers:Ts(t),path:{runId:n},query:null!=r?{skipAfterConsecutiveUnfixed:r}:{}},(o.client??cr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-context",...o}));var o;if(404===s.response.status)throw cs.warn("Autoheal context not found",{runId:n,status:404}),new Error(`Run ID "${n}" was not found.`);if(401===s.response.status)throw cs.warn("Autoheal context fetch unauthorized",{runId:n,status:401}),new Error("Unauthorized: failed to fetch autoheal context (401).");if(422===s.response.status)throw cs.warn("Autoheal context fetch invalid request",{runId:n,status:422,error:s.error?.error}),new Error(s.error?.error??"Failed to fetch autoheal context (422).");if(!s.error){const e=_s.safeParse(s.data);if(e.success)return cs.debug("Autoheal context fetched successfully",{runId:n,contextSize:e.data.context.length,skippedTestCount:e.data.skippedTests?.length??0}),{context:e.data.context,autohealReportUrl:e.data.autohealReportUrl,skippedTests:e.data.skippedTests??[],newerPassingSuiteId:e.data.newerPassingSuiteId,envName:e.data.envName};throw cs.warn("Autoheal context response invalid",{runId:n}),new Error("Autoheal context response missing or invalid context.")}throw cs.warn("Autoheal context fetch failed",{runId:n,error:s.error}),new Error("Failed to fetch autoheal context")})({authHeader:await d.getAuthHeader(),orgId:p,runId:e.runId,skipAfterConsecutiveUnfixed:lt});if(i&&!Ue.remoteEnvName&&(cs.info("[fix] Auto-loaded remote env from run metadata",{envName:i}),Ue.remoteEnvName=i,tt=i),cs.info("[fix] Autoheal context fetched",{runId:e.runId,durationMs:Date.now()-t,contextLength:n.length,skippedTestCount:s.length}),et=r,s.length>0){cs.info(`[fix] Skipping ${s.length} test(s) that failed to be fixed ${lt}+ consecutive times`);for(const e of s)cs.info(`[fix] Skipped: ${e.testIdentifier} β ${e.testTitle} (unfixed ${e.consecutiveUnfixedCount}x)`)}if(o&&(cs.info("[fix] Tests already passing in a newer run β no session created",{newerPassingSuiteId:o}),Ze({status:"success",result:`Tests already passing in a newer run (${o}). Nothing to fix.`}),await Ge(),process.exit(0)),n.includes("No failing tests to fix (all were skipped).")&&(cs.info("[fix] All failing tests were skipped β creating skipped session"),xe&&await async function({authHeader:e,orgId:t,projectId:n,runId:r,reason:s,skippedTests:o,fetchImpl:i=fetch,apiUrl:a=pr}){const c=new URL("/internal/v1/cli/sessions/skipped",a).toString(),l={Authorization:e,"Content-Type":"application/json","X-STABLY-CLI-VERSION":dr};t&&(l["x-stably-org-id"]=t),await i(c,{method:"POST",headers:l,body:JSON.stringify({mode:"fix",projectId:n,...r?{playwrightSuiteRunId:r}:{},progress:{phase:"skipped",isError:!1,reason:s,skippedTests:o,endedAt:Date.now()}}),signal:AbortSignal.timeout(5e3)}).then(e=>{e.ok||console.warn(`[session] Failed to create skipped session: ${e.status} ${e.statusText}`)}).catch(e=>{console.warn(`[session] Failed to create skipped session: ${e instanceof Error?e.message:String(e)}`)})}({authHeader:await d.getAuthHeader(),orgId:p,projectId:ys(u),runId:e.runId,reason:`All ${s.length} failing test(s) skipped β each was unfixed ${lt??3}+ consecutive runs`,skippedTests:s}),Ze({status:"success",result:`All failing tests skipped (unfixed ${lt}+ consecutive times). Nothing to fix.`}),await Ge(),process.exit(0)),xe)try{cs.info("[session] Creating fix-mode progress session (post early-exit checks)");const t=await fo({agentMode:e.mode,authHeader:await d.getAuthHeader(),orgId:p,projectId:ys(u),runId:e.runId});Se=t.sessionId,cs.info("[fix] Progress session created",{sessionId:Se})}catch(e){const t=e instanceof Error?e.message:String(e);cs.warn(`[progress] Fix session creation failed (non-fatal): ${t}`)}return le||(cs.info("[fix] Creating WebSocket progress reporter"),le=new Ps({authProvider:d,orgId:p,runId:e.runId,onUserMessage:e=>{if(cs.info("[ws] Injecting web UI message into fix agent",{contentLength:e.length}),he(sl,{type:"user_message",summary:e}),ge({type:"user_message",summary:e}),Fe({text:`[Web] ${e}`}),!F)return U.pushText(`[Message from web UI user]: ${e}`),F=!0,void U.allowNextTurn();J||Date.now()-Q<2e3?U.pushText(`[Message from web UI user]: ${e}`):(K.push(e),j&&clearTimeout(j),j=setTimeout(()=>{j=void 0;const e=[...K];K=[],Q=Date.now(),mn(e)},500))}}),await le.start(),ye({phase:"initializing"})),be("STARTED"),n}catch(e){const t=e instanceof Error?e.message:"Failed to fetch autoheal context.";cs.error("[fix] Failed to fetch autoheal context",{error:t}),Ze({error:t,status:"error"}),await Ge(),process.exit(1)}if("plan"===e.mode){const t=(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt)?.trim();return t||"Analyze this repository and generate a comprehensive test coverage plan."}if("init"===e.mode){const e=R??{googleAuth:!0,emailPackage:!1};return["Set up Playwright with the Stably SDK.",`Preferences: Google Auth guidance: ${e.googleAuth?"yes":"no"}, @stablyai/email: ${e.emailPackage?"install":"skip"}.`].join(" ")}return""})(),dt=await async function(e){const t=r.resolve(e),n=r.join(t,"tests"),s=r.join(n,"helpers"),o=r.join(n,"assets"),i=function(e){const t=r.resolve(e);if(E(t))for(const e of io){const n=r.join(t,`playwright.config${e}`);if(E(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([lo({defaultContent:"Unable to read directory",dirName:"working directory",dirPath:t}),lo({defaultContent:"Unable to read directory",dirName:"tests directory",dirPath:n}),lo({defaultContent:"Directory does not exist yet",dirName:"helpers directory",dirPath:s}),lo({defaultContent:"Directory does not exist yet",dirName:"assets directory",dirPath:o}),co({defaultContent:"File does not exist or could not be read",fileName:a,filePath:i}),co({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}}}(f),pt="fix"===e.mode?ct?.agent?.fix?.maxTurnsPerIssue:"single"===e.mode?ct?.agent?.create?.maxTurnsPerTestFile:void 0,ft="cloudBrowser"in e&&e.cloudBrowser,ht=ct?.agent?.fix?.maxParallelWorkers??3,gt="fix"===e.mode?await(async e=>{const t=await _c(e,"STABLY-FIX.md");return t?.content})(f):void 0,mt="fix"===e.mode?ct?.agent?.fix?.rules:void 0;gt&&mt&&cs.warn("Both STABLY-FIX.md and stably.yaml agent.fix.rules found; using STABLY-FIX.md");const yt=gt??mt,bt=ct?.agent?.fix?.maxBudgetUsd??50,wt="verify"===e.mode?e.maxBudgetUsd??5:void 0,vt="single"===e.mode?ct?.agent?.create?.maxBudgetUsd??50:void 0,It="fix"===e.mode?bt:k?wt:vt,Tt="init"!==e.mode,_t="single"===e.mode?await(async e=>{const t=await _c(e,"STABLY-CREATE.md");return t?.content})(f):void 0,Et=await(e=>_c(e,"STABLY.md"))(f),St=Et?.content;let xt;if(k&&(qe({label:"Assembling verification context..."}),je({text:"Assembling workspace context...\n"})),cs.info("[fix] Fetching system prompt and subagent definitions",{mode:e.mode,isCloudBrowser:ft,maxParallelWorkers:ht,maxTurnsOverride:pt,maxBudgetUsd:It,hasCustomRules:!!yt,hasCreateRules:!!_t,hasStablyMd:!!St,stablyMdPath:Et?.path}),Et&&cs.info(`STABLY.md loaded (${Et.content.length} chars)`,{path:Et.path}),"fix"===e.mode&&tt){const e=await vs(tt);e.ok?xt=e.result:cs.warn("[fix] Failed to load auto-detected remote env, continuing without it",{envName:tt,error:e.error})}else xt=await Is();const At=xt?Object.keys(xt.variables):[],kt=[...new Set([...Object.keys(b),...At])],Ct=Date.now(),Pt=await d.getAuthHeader(),[{systemPrompt:Rt,prContext:Ut},$t]=await Promise.all([uo({allowedEnvVars:kt,mode:e.mode,workspaceInfo:dt,authHeader:Pt,customHeader:"single"===e.mode?e.customHeader:void 0,maxParallelWorkers:ht,isCloudBrowser:ft}),Tt?yc({authHeader:Pt,mode:e.mode,maxTurnsOverride:pt}):Promise.resolve({})]);cs.info("[fix] System prompt and subagents fetched",{durationMs:Date.now()-Ct,systemPromptSize:Rt.length,subagentCount:Object.keys($t).length,maxTurnsOverride:pt??"default",hasPrContext:!!Ut});const Lt=function(e){const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(mc.has(n)||gc.some(e=>n.startsWith(e))||(t[n]=r));return t}({...b,...process.env}),Dt=!0;cs.debug("AI proxy configuration",{useStablyAiProxy:Dt,wantsBypassProxy:!1,wantsUseOllama:!1}),cs.info("[fix] Acquiring AI proxy key",{useStablyAiProxy:Dt});const Nt=Date.now(),Ot=await async function({auth:e,client:t,source:n,metadata:r,duration:s}){try{const i=await(o={auth:e,client:t,body:{source:n,metadata:r??{},duration:s}},(o.client??cr).post({security:[{scheme:"bearer",type:"http"}],url:"/v1/proxy/api-key",...o,headers:{"Content-Type":"application/json",...o.headers}})),a=i.response;if(i.error){const e="object"==typeof i.error&&"error"in i.error?i.error.error:"Unknown error";return{error:hc(e,a)}}return i.data?{key:i.data.key}:{error:hc("No data in response",a)}}catch(e){const t=e instanceof Error?e.message:"Unknown error";return{error:hc(t)}}var o}({auth:Pt,client:vr(),source:"cli"}),Bt=Ot?.key;if(cs.info("[fix] AI proxy key acquired",{durationMs:Date.now()-Nt,success:!!Bt,hasError:!!Ot?.error}),!Bt){const e=Ot?.error?.message?`Unable to make AI calls: ${Ot.error.message}`:"Unable to make AI calls. Check if you are authenticated.";cs.warn("Failed to get proxy API key",{error:Ot?.error?.message}),Ze({error:e,status:"error"}),await Ge(),cs.flush(),cs.printLogFileInfo(),process.exit(1)}cs.debug("Proxy API key acquired",{success:!!Bt});const jt="init"===e.mode,Mt="fix"===e.mode,Ft=!!ft,Ht=Ft?new Fc({authProvider:d,projectId:ys(u)}):void 0,Gt=dc({localEnv:b,remoteEnv:xt?.variables,remoteSensitiveValues:xt?.sensitiveValues}),Wt=jt||C?void 0:function(e){let t,n;!function(e){const t=i(e,".gitignore");try{if(E(t)){const e=x(t,"utf-8"),n=e.split("\n").map(e=>e.trim());if(n.includes(Pc)||n.includes(`/${Pc}`))return;const r=e.length>0&&!e.endsWith("\n");A(t,`${r?"\n":""}${Pc}\n`)}}catch{}}(process.cwd());const r=new Set;let s,o;const a=()=>{var t;return o||(t=e.sessionName,o="auto"!==t?t:`stably-${process.pid}`),o};return{hook:async o=>{const i=o&&"object"==typeof o&&"tool_input"in o&&o.tool_input&&"object"==typeof o.tool_input&&"command"in o.tool_input&&"string"==typeof o.tool_input.command?o.tool_input.command:"";if(!Ec.test(i)&&!Sc.test(i))return{decision:"approve"};if(Sc.test(i)&&!Ec.test(i)){if(!n)try{n=await Uc(),cs.info("[pwtrace-hook] Resolved binary",{path:n})}catch(e){const t=e instanceof Error?e.message:String(e);return{decision:"block",reason:t,systemMessage:`pwtrace binary not found: ${t}`}}const e=`${process.execPath} ${n}`;return{decision:"approve",hookSpecificOutput:{hookEventName:"PreToolUse",updatedInput:{command:i.replace(/\b(?:npx\s+)?pwtrace\b/g,e)}}}}if(Sc.test(i)&&!n)try{n=await Uc(),cs.info("[pwtrace-hook] Resolved binary (mixed command)",{path:n})}catch{}const c=!!e.cloudBrowserManager,l=new RegExp(`\\bstably-browser\\s+${xc}close\\b(?!-)`).test(i),u=new RegExp(`\\bstably-browser\\s+${xc}close-all\\b`).test(i),d=new RegExp(`\\bstably-browser\\s+${xc}(?!close(?:-all)?\\b)\\w`).test(i);if(u){if(s&&(cs.info("[stably-browser-hook] Clearing cached permanent daemon failure via close-all",{reason:s.reason}),s=void 0),!d&&0===r.size)return{decision:"approve"};if(c){const t=e.cloudBrowserManager;await Promise.all(Array.from(r).map(e=>t.releaseSession(e)))}if(r.clear(),!d){if(!t)try{t=await Rc()}catch(e){const t=e instanceof Error?e.message:String(e);return{decision:"block",reason:t,systemMessage:`stably-browser binary not found: ${t}`}}const e=`${process.execPath} ${t}`;let r=i.replace(/((?:npx\s+)?stably-browser\b[^;&|]*?)\s+(?:-s[= ]|--session[= ])[^\s;&|]+/g,"$1").replace(/\b(?:npx\s+)?stably-browser\b/g,e);if(Sc.test(r)&&n){const e=`${process.execPath} ${n}`;r=r.replace(/\b(?:npx\s+)?pwtrace\b/g,e)}return{hookSpecificOutput:{hookEventName:"PreToolUse",updatedInput:{command:r}}}}}if(l){if(s&&(cs.info("[stably-browser-hook] Clearing cached permanent daemon failure via close",{reason:s.reason}),s=void 0),!d&&0===r.size)return{decision:"approve"};const t=Nc(o),n=Dc(a(),t);r.delete(n),c&&e.cloudBrowserManager.getConfigPath(n)&&e.cloudBrowserManager.releaseSession(n)}if(!t)try{t=await Rc(),cs.info("[stably-browser-hook] Resolved binary",{path:t})}catch(e){const t=e instanceof Error?e.message:String(e);return{decision:"block",reason:t,systemMessage:c?`stably-browser binary not found: ${t}. The stably-browser tool is unavailable. upload-trace-proof only uploads existing traces and does not depend on stably-browser, so it still works regardless. Report this issue to the user and suggest running locally instead.`:`stably-browser binary not found: ${t}. The stably-browser tool is unavailable. upload-trace-proof only uploads existing traces and does not depend on stably-browser, so it still works.`}}const p=Nc(o),f=Dc(a(),p),h=new RegExp(`\\bstably-browser\\s+${xc}open\\b`).test(i);if(h&&s&&(cs.info("[stably-browser-hook] Clearing cached permanent daemon failure",{sessionName:f,reason:s.reason}),s=void 0),s)return{decision:"block",reason:`Browser unavailable: ${s.reason}`,systemMessage:s.guidance};if(c&&e.cloudBrowserManager.needsRecreation(f)&&r.has(f)&&(cs.info("[stably-browser-hook] Cloud browser needs recreation, clearing session",{sessionName:f}),r.delete(f),e.cloudBrowserManager.releaseSession(f)),(!l&&!u||d)&&!r.has(f))if(c){r.add(f),cs.info("[stably-browser-hook] Provisioning cloud browser...",{sessionName:f});try{let n=!1;const o=await e.cloudBrowserManager.acquire(f,()=>{n||(n=!0,e.onStatusLabel?.("Waiting for a browser to become available..."))});if(n&&e.onStatusLabel?.(void 0),o.liveViewUrl&&process.stderr.write(`Live view: ${o.liveViewUrl}\n`),!h){const n=e.cloudBrowserManager.getConfigPath(f),o=await Lc(t,f,e.headed,n??void 0);if(!o.ok)return r.delete(f),o.permanent&&(s={reason:o.reason,guidance:o.guidance}),{decision:"block",reason:`Failed to start stably-browser daemon with cloud browser: ${o.reason}`,systemMessage:o.guidance}}}catch(e){r.delete(f);const t=e instanceof Error?e.message:String(e);return{decision:"block",reason:`Cloud browser unavailable: ${t}`,systemMessage:`Failed to provision cloud browser: ${t}. Remove --browser=cloud to use a local browser instead.`}}}else if(h)r.add(f);else{r.add(f),cs.info("[stably-browser-hook] First browser command, starting daemon...",{sessionName:f,agentId:p});let n=await Lc(t,f,e.headed,void 0,"chromium");if(!n.ok&&n.reason.includes("not installed")&&(cs.info("[stably-browser-hook] Chromium not found, falling back to system Chrome..."),n=await Lc(t,f,e.headed,void 0,"chrome")),!n.ok)return r.delete(f),n.permanent&&(s={reason:n.reason,guidance:n.guidance}),{decision:"block",reason:`Failed to start stably-browser daemon: ${n.reason}`,systemMessage:n.guidance}}const g=`${process.execPath} ${t}`;let m=i.replace(/\b(?:npx\s+)?stably-browser\b/g,g);if(Sc.test(m)&&n){const e=`${process.execPath} ${n}`;m=m.replace(/\b(?:npx\s+)?pwtrace\b/g,e)}const y=[];if(m.includes("-s=")||m.includes("--session=")||y.push(`-s=${f}`),c){const t=e.cloudBrowserManager.getConfigPath(f);t&&!m.includes("--config=")&&y.push(`--config=${t}`),m=m.replace(/\s*--browser[= ]\S+/g,"")}e.headed&&!m.includes("--headed")&&y.push("--headed"),y.length>0&&(m=m.replaceAll(g,`${g} ${y.join(" ")}`)),u&&(m=m.replace(/([^;&|]*?\bclose-all\b)/g,e=>e.replace(/\s+(?:-s[= ]|--session[= ]|--config[= ])[^\s;&|]+/g,""))),Ac.test(i)&&!m.includes("--trace")&&(m=m.replaceAll(/\brun-test\b/g,"run-test --trace=on")),Ac.test(i)&&f!==a()&&!m.includes("--output")&&(m=m.replaceAll(/\brun-test\b/g,`run-test --output=.stably-browser/${f}/test-results`)),e.envVars&&(m=m.replace(kc,(t,n)=>{const r=e.envVars[n];return null!=r?r:t}));const b=[];if("linux"===process.platform&&"function"==typeof process.getuid&&0===process.getuid()&&b.push("PLAYWRIGHT_MCP_SANDBOX=false"),Ac.test(i)&&e.envVars)for(const[t,n]of Object.entries(e.envVars))b.push(`${t}=${Cc(n)}`);return b.length>0&&(m=`${b.join(" ")} ${m}`),cs.debug("[stably-browser-hook] Rewritten command",{original:i.slice(0,100),sessionName:f,agentId:p,envVarCount:b.length}),{hookSpecificOutput:{hookEventName:"PreToolUse",updatedInput:{command:m}}}},cleanup:async()=>{t&&r.size>0&&(await Promise.all(Array.from(r).map(e=>{return n=t,r=e,new Promise(e=>{m(process.execPath,[n,"close",`-s=${r}`],{timeout:1e4},t=>{t&&cs.debug("[stably-browser-hook] Failed to stop daemon",{error:t.message,sessionName:r}),e()})});var n,r})),r.clear()),e.cloudBrowserManager?.isActive()&&await e.cloudBrowserManager.release()}}}({sessionName:Gc({configuredSessionName:process.env.STABLY_PLAYWRIGHT_SESSION,isFixMode:Mt,useCloudBrowser:Ft}),headed:!("chat"!==e.mode||process.env.CI||"linux"===process.platform&&!process.env.DISPLAY),envVars:Gt,cloudBrowserManager:Ht,onStatusLabel:e=>qe({label:e})}),Vt=Mt?Mn.createLocal({workingDir:f}):void 0;Vt&&await Vt.captureSnapshot();const Yt=()=>{jt&&function({workingDir:e,options:t={}}){const r=function(e){const t=function(e){let t=n.resolve(e);for(;;){if(w.existsSync(n.join(t,".git")))return t;const r=n.dirname(t);if(r===t)return n.resolve(e);t=r}}(e),r=function(e,t){for(const n of ec(e,t))if(qa(n))return n}(e,t),s=Xa(Ka(e,/playwright\.config\.(ts|js|mts|mjs|cjs)$/).map(e=>n.dirname(e))),o=function(e){const t=new Set;for(const r of e)t.add(Ja(n.dirname(r)));return Xa(Array.from(t))}(Ka(e,/\.(spec|test)\.(ts|js)$/)),i=s.length>0?s:o,a=r??(1===i.length?i[0]:void 0)??e,c=Za(a,t);if(!c)return{repoRoot:t,projectRoot:a,targetDir:void 0};if(!r&&c===n.resolve(e)&&function(e,t,n){const r=new Set;for(const s of e){const e=Za(s,n);e&&e!==t&&r.add(e)}return r.size>1}(i,c,t))return{repoRoot:t,projectRoot:a,targetDir:void 0};const l=Ya(c);if(!l||!("workspaces"in l.contents))return{repoRoot:t,projectRoot:a,targetDir:c};const u=function(e,t){let r=n.resolve(e);const s=n.resolve(t);for(;r!==s;){if(w.existsSync(n.join(r,"package.json")))return r;const e=n.dirname(r);if(e===r)break;r=e}}(a,c);return{repoRoot:t,projectRoot:a,targetDir:u??c}}(e);if(r.targetDir){try{!function(e){const t=n.join(e,"package.json");if(!w.existsSync(t))return;const r=JSON.parse(w.readFileSync(t,"utf-8"));if({...r.dependencies,...r.devDependencies}.stably)cs.debug("stably package already present in dependencies");else{cs.info("stably package missing from devDependencies, installing...");try{Va({workingDir:e,packageManager:nc(e),packageSpec:"stably",targetSection:"devDependencies"}),cs.info("stably package installed successfully")}catch(e){cs.warn("Failed to install stably package",{error:String(e)})}}}(r.targetDir)}catch(e){cs.warn("Post-init: ensureStablyDependency failed",{error:String(e)})}try{!function(e){const t=Ya(e);if(!t)return;const n=t.contents.devDependencies?.playwright??t.contents.dependencies?.playwright;if(n)if(tc(n)!==Ns)try{Va({workingDir:e,packageManager:nc(e),packageSpec:`playwright@${Ns}`,targetSection:t.contents.devDependencies?.playwright?"devDependencies":"dependencies"}),cs.info("standalone playwright version aligned successfully",{version:Ns})}catch(e){cs.warn("Failed to align standalone playwright version",{error:String(e)})}else cs.debug("standalone playwright already at supported version",{version:Ns});else cs.debug("standalone playwright package not present")}(r.targetDir)}catch(e){cs.warn("Post-init: alignStandalonePlaywrightVersion failed",{error:String(e)})}try{!function(e){const t=Ya(e);if(t)if(tc(t.contents.devDependencies?.["@playwright/test"]??t.contents.dependencies?.["@playwright/test"])!==Ns)try{cs.info(`Updating @playwright/test to supported version ${Ns}...`),Va({workingDir:e,packageManager:nc(e),packageSpec:`@playwright/test@${Ns}`,targetSection:t.contents.dependencies?.["@playwright/test"]?"dependencies":"devDependencies"}),cs.info("@playwright/test updated successfully")}catch(e){cs.warn("Failed to update @playwright/test",{error:String(e)})}else cs.debug("@playwright/test already at supported version",{version:Ns});else cs.debug("No package.json found, skipping @playwright/test update")}(r.targetDir)}catch(e){cs.warn("Post-init: updatePlaywrightTest failed",{error:String(e)})}try{!function(e,t,r){const s=[];r.googleAuth&&s.push("Google Auth methods"),r.emailPackage&&s.push("@stablyai/email Inbox methods for email verification flows");const o=`Use Stably CLI for Playwright test runs (better reporting, auto-fix); import from @stablyai/playwright-test for agent.act(), aiAssert, page.extract(), page.getLocatorsByAI()${s.length>0?`; also use ${s.join(" and ")}`:""}.`,i=function(e,t){const r=["CLAUDE.md","AGENTS.md","AGENT.md","agent.md"];for(const s of ec(e,t)){let t;for(const o of r){const r=n.join(s,o);if(!w.existsSync(r))continue;t??=r;const i=w.readFileSync(r,"utf-8");if(/Stably CLI/i.test(i)&&i.includes("@stablyai/playwright-test"))return void cs.debug("Agent guidance already present",{file:n.relative(e,r)||o});if(Qa(i))return r}if(t)return t}return n.join(e,"AGENTS.md")}(e,t);if(i){cs.info("Appending Stably guidance",{file:n.basename(i)});try{const e=w.existsSync(i)?w.readFileSync(i,"utf-8"):"",t=e.length>0&&!e.endsWith("\n")?"\n\n":e.length>0?"\n":"";w.writeFileSync(i,`${e}${t}${o}\n`,"utf-8"),cs.info("Agent guidance appended successfully")}catch(e){cs.warn("Failed to update agent guidance file",{error:String(e)})}}}(r.targetDir,r.repoRoot,t)}catch(e){cs.warn("Post-init: ensureAgentGuidance failed",{error:String(e)})}}else cs.warn("Post-init: could not resolve target package directory; skipping verification",{workingDir:e})}({workingDir:f,options:{googleAuth:R?.googleAuth,emailPackage:R?.emailPackage}})},zt=jt?(({onComplete:e})=>G({name:"session-control",tools:[W("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:we.string().describe("A brief summary of what was accomplished")},({summary:t})=>{const n="string"==typeof t?t:String(t);return e(),Promise.resolve(`Session complete: ${n}`)})]}))({onComplete:()=>{Yt(),Ze({status:"success"}),ze(),U?.finish(),Ht?(setTimeout(()=>process.exit(0),5e3).unref(),Ht.release().finally(()=>process.exit(0))):process.exit(0)}}):void 0,qt=zt?{"session-control":zt}:{},Kt=S&&Ut?["mcp__create-report"]:[],Jt=S&&Se?["mcp__upload-trace-proof"]:[],Xt=jt?nl:k?el:[...el,...Mt?["mcp__auto-heal-report"]:[],...Kt,...Jt],Qt=jt?nl:T?[...tl,"mcp__stably-agent-control"]:k?tl:[...tl,...Kt,...Jt],Zt=S&&Ut?{"create-report":sc({prContext:Ut,authProvider:d,orgId:p,onReportPosted:e=>{_e({githubComment:{url:e.commentUrl,prNumber:Ut.prNumber}})}})}:{},en=S&&Se?{"upload-trace-proof":ic({authProvider:d,sessionId:Se,orgId:p,workingDir:f,onTraceProofCaptured:e=>{_e({traceProofs:[...Te?.traceProofs??[],e]})}})}:{},tn=jt?qt:C?{}:Mt&&Vt?{"auto-heal-report":Wa({authProvider:d,diffTracker:Vt,orgId:p,runId:e.runId,workingDir:f}),"run-history":uc({authProvider:d,orgId:p,projectId:ys(u)}),...qt}:{...qt,...Zt,...en,"run-history":uc({authProvider:d,orgId:p,projectId:ys(u)}),environment:pc({hookEnvVars:Gt,localEnvSnapshot:{...b}})},nn="single"===e.mode,rn=jt?[]:nn?[{matcher:"Write",hooks:[to({onFileCreated:e=>{if(st.includes(e)||st.push(e),Te){if(Te.filesCreated.some(t=>"string"==typeof t?t===e:t.path===e))return;const t=r.isAbsolute(e)?e:r.join(f,e),n=r.basename(e),{sessionId:s}=Te,o=(async()=>{try{const r=await v.promises.readFile(t,"utf8"),o=await(async({authHeader:e,content:t,contentType:n="text/plain",filename:r,filePath:s,orgId:o,sessionId:i})=>{try{const{bucketPath:a,uploadUrl:c}=await(async({authHeader:e,contentType:t="text/plain",filename:n,filePath:r,orgId:s,sessionId:o})=>{const i=await(a={auth:e,body:{filename:n,filePath:r,contentType:t},client:vr(),headers:Ts(s),path:{sessionId:o}},(a.client??cr).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=Us.parse(i.data);return{bucketPath:c.bucketPath,expiresInSeconds:c.expiresInSeconds,key:c.key,uploadUrl:c.uploadUrl}})({authHeader:e,contentType:n,filename:r,filePath:s,orgId:o,sessionId:i});return await Ss({body:t,contentType:n,uploadUrl:c,errorContext:"file"}),await(async({authHeader:e,bucketPath:t,filename:n,filePath:r,orgId:s,sessionId:o})=>{const i=await(a={auth:e,body:{filename:n,filePath:r,bucketPath:t},client:vr(),headers:Ts(s),path:{sessionId:o}},(a.client??cr).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:r,filePath:s,orgId:o,sessionId:i}),a}catch(e){return cs.warn("Failed to upload automation file",{error:e instanceof Error?e.message:String(e)}),null}})({authHeader:await d.getAuthHeader(),content:r,contentType:"text/plain",filename:n,filePath:e,orgId:p,sessionId:s}),i={path:e,filename:n,bucketPath:o};ot.push(i),_e({filesCreated:[...ot]})}catch(t){cs.warn("Failed to upload created file",{filePath:e,error:t instanceof Error?t.message:String(t)});const r={path:e,filename:n,bucketPath:null};ot.push(r),_e({filesCreated:[...ot]})}})();it.push(o)}}})]}]:[],sn=jt?[]:[...Mt?[{matcher:"Read",hooks:[Ms({action:"reading",pathKey:"file_path"})]},{matcher:"Write",hooks:[Ms({action:"writing",pathKey:"file_path"})]},{matcher:"Edit",hooks:[Ms({action:"editing",pathKey:"file_path"})]},{matcher:"Grep",hooks:[Ms({action:"searching",pathKey:"path"})]},{matcher:"Glob",hooks:[Ms({action:"searching",pathKey:"path"})]},{matcher:"Bash",hooks:[Zs({workspaceBoundary:f})]}]:[],...Wt?[{matcher:"Bash",hooks:[Wt.hook]}]:[],{hooks:[async e=>(e&&"object"==typeof e&&"tool_name"in e?e.tool_name:"").startsWith("mcp__plugin_playwright_playwright__browser_")?{decision:"block",reason:"Use stably-browser commands instead of the built-in Playwright MCP tools.",systemMessage:'Do NOT use mcp__plugin_playwright_playwright tools. Use stably-browser bash commands for all browser interaction:\n- `stably-browser open` / `stably-browser open <url>`\n- `stably-browser goto <url>`, `stably-browser click <ref>`, `stably-browser fill <ref> "text"`\n- `stably-browser snapshot`, `stably-browser screenshot`\n- `stably-browser run-test <file>`\n- `stably-browser close`'}:{decision:"approve"}]}],on=Object.keys($t).length>0?$t:void 0,an={...Lt};an.MCP_TOOL_TIMEOUT=String(6e5),Bt&&(an.ANTHROPIC_API_KEY=Bt,an.ANTHROPIC_BASE_URL=mr,an.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS="1",an.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC="1");const cn=process.env.STABLY_AGENT_MODEL??"claude-opus-4-6";!function(e,t){"env"===t.type&&(e.STABLY_API_KEY=t.auth.apiKey,e.STABLY_PROJECT_ID=t.auth.projectId)}(an,u);const ln=yt?`\n\n## Authoritative Fix Rules (STABLY-FIX.md / stably.yaml)\nThese repository-specific fix instructions take precedence over generic fix guidance when they conflict.\n${yt}`:"",un=_t?`\n\n## Authoritative Test Generation Rules (STABLY-CREATE.md)\nThese repository-specific create instructions take precedence over generic create guidance when they conflict.\n${_t}`:"",dn=St?`\n\n## Authoritative Project Rules (STABLY.md)\nThese repository-specific project instructions take precedence over generic guidance when they conflict. If STABLY-CREATE.md is also present, use it for create-specific conflicts.\n${St}`:"",pn=ft?"\n\n## Cloud Browser Mode\nYou are running in cloud browser mode. Cloud browsers are remote VMs β there is no local resource cost.\n\n**Each subagent MUST use its own isolated browser session.** Do NOT reuse or share browser sessions between subagents. Session isolation is automatic β each subagent simply calls `stably-browser open` and gets its own browser.\n\nWhen running tests with `stably-browser run-test`, each subagent also gets its own browser automatically.":"",fn=Rt+ln+un+dn+pn;cs.debug("[fix] Final system prompt assembled",{baseSize:Rt.length,fixRulesSize:ln.length,createRulesSize:un.length,stablyMdSize:dn.length,cloudBrowserSize:pn.length,finalSize:fn.length});const hn=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 Ic(t)?t:void 0}();if(e)return e;const t=r.join(bc,"stably-plugin-cli");if(Ic(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}}(bc))for(const t of vc){const n=r.join(e,t);if(Ic(n))return n}}();if(e)return{type:"local",path:e}}(),gn=()=>(cs.info("[fix] Starting SDK query",{model:cn,tools:Xt,mcpServers:Object.keys(tn),resumeSessionId:B??null,subagentsEnabled:!!on,subagentCount:Object.keys($t).length,useStablyAiProxy:Dt,aiProxyUrl:mr,anthropicBaseUrl:void 0,stablyPluginPath:hn?.path,stablyPluginExists:!!hn}),V({options:{executableArgs:["--max-old-space-size=4096"],tools:Xt,allowedTools:Qt,...null!=It?{maxBudgetUsd:It}:{},betas:[],canUseTool:(e,t)=>(cs.debug("[fix] canUseTool called",{toolName:e}),Promise.resolve({behavior:"allow",updatedInput:t})),cwd:f,env:an,hooks:{PostToolUse:rn,PreToolUse:sn},includePartialMessages:!0,agents:on,mcpServers:tn,model:cn,permissionMode:"default",plugins:hn?[hn]:void 0,systemPrompt:fn,...B?{resume:B}:{}},prompt:U??ut})),mn=async e=>{if(I&&F&&!J&&!M)M=(async()=>{cs.info("[fix] Interrupting for user message",{messageCount:e.length,phase:ue?.phase});try{await(O?.interrupt?.())}catch(e){cs.warn("[fix] Failed to interrupt response for user message",{error:e instanceof Error?e.message:String(e)})}await ro(),U?.finish(),U=new so,Z.clear(),O=gn();const t=e.map(e=>`[Message from web UI user]: ${e}`).join("\n\n");U.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}`),X=!0,F=!0})().finally(()=>{M=void 0}),await M;else for(const t of e)U?.pushText(`[Message from web UI user]: ${t}`)};if(Bt){k&&qe({label:"Checking AI connectivity..."});const e=mr,t=`${e.replace(/\/$/,"")}/v1/messages`;cs.debug(`[fix] Pre-flight: POST ${t}`);const n=Date.now();let r;try{const e=await fetch(t,{method:"POST",signal:AbortSignal.timeout(1e4),headers:{"x-api-key":Bt,"anthropic-version":"2023-06-01","content-type":"application/json"},body:"{}"}),s=await e.text().catch(()=>""),o=Date.now()-n;cs.debug(`[fix] Pre-flight: ${e.status} in ${o}ms β ${s.slice(0,300)}`),401===e.status||403===e.status?(cs.error(`[fix] Pre-flight: AI proxy key rejected (${e.status}) at ${t}`),r="Unable to start verification: AI proxy credentials were rejected. Please run `stably login` and try again."):cs.info("[fix] Pre-flight: AI proxy key valid",{status:e.status,durationMs:o})}catch(t){cs.error("[fix] Pre-flight: AI proxy unreachable",{error:t instanceof Error?t.message:String(t),durationMs:Date.now()-n,url:e}),r="Unable to start verification: cannot reach the AI proxy. Please check your network/VPN and try again."}finally{k&&"running"===Qe&&qe({label:void 0})}r&&(je({text:`[stably] ${r}\n`}),Ze({error:r,status:"error"}),await Ge(),cs.flush(),cs.printLogFileInfo(),process.exit(1))}cs.info("[fix] Creating initial agent query"),k&&(qe({label:"Initializing verification session..."}),je({text:"Initializing verification session...\n"})),cs.flush(),O=gn(),cs.info("[fix] Agent query created, entering message loop"),"chat"!==e.mode&&(U.pushText(ut),ee.push({role:"user",content:ut,timestamp:(new Date).toISOString()}));const yn=async t=>{Pe||(Pe=(async()=>{cs.info("[session] Interrupt requested",{source:t,mode:e.mode}),oe="CANCELED",await be("CANCELED"),ye({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:me(!0)}),await(le?.closeAndWait()),await Promise.allSettled(it),_e({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0}),await(Ie?.closeAndWait()),j&&(clearTimeout(j),j=void 0),ze(),await ro(),await(Wt?.cleanup());try{await(O?.interrupt?.())}catch{}if(U?.finish(),ee.length>0&&Se)try{await Ds({authHeader:await d.getAuthHeader(),orgId:p,sessionId:Se,projectId:ys(u),history:ee})}catch(e){cs.warn("[exit] Failed to upload session history",{error:e instanceof Error?e.message:String(e)})}Ge(),cs.flush()})()),await Pe};ke.current=async()=>{await yn("ctrl-c")};let bn=()=>{};bn=function({enabled:e,onSignal:t}){const n=()=>{t("SIGINT")},r=()=>{t("SIGTERM")};return process.prependOnceListener("SIGINT",n),process.prependOnceListener("SIGTERM",r),()=>{process.removeListener("SIGINT",n),process.removeListener("SIGTERM",r)}}({enabled:!0,onSignal:e=>{(async()=>{await yn("signal"),process.exit(function(e){return"SIGINT"===e?130:143}(e))})()}});let wn=null,vn=null,In="";Re.current=async()=>{if(!$e&&F&&U){$e=!0;try{cs.info("[chat] User pressed Escape to cancel generation"),We(),Ve(),H=!0,Le=!0;try{await(O?.interrupt?.())}catch(e){cs.warn("[chat] Failed to interrupt response on Escape",{error:e instanceof Error?e.message:String(e)})}await ro();const e=U.drainQueue();U.finish(),U=new so;for(const t of e)U.pushText(t);q=e.length,O=gn();for(const e of Z.keys())Je({toolUseId:e,status:"error"});Be()}finally{$e=!1}}};let Tn=0,_n=null,En=!1;const Sn=T?void 0:k?9e4:18e4;let xn=!1;const An=null!=Sn?setTimeout(()=>{_n||"running"!==Qe||(t=>{if(!xn){if(xn=!0,clearTimeout(An),clearInterval(kn),setTimeout(()=>process.exit(1),6e4).unref(),cs.error("[session] Session timeout",{reason:t,mode:e.mode,elapsed:Date.now()-ce}),oe="FAILED",k||T){const e="This is taking longer than expected. Please try again.";je({text:`[stably] ${e}\n`}),Ze({error:e,status:"error"})}else ye({phase:"complete",endedAt:Date.now(),isError:!0,errorReason:"execution_error",errorMessage:`Session timed out: ${t}`,workers:me(!0)});_e({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:`Timed out: ${t}`});try{O?.interrupt?.()}catch{}U?.finish()}})("no response from AI service")},Sn):void 0;An?.unref();const kn=setInterval(()=>{const e=Date.now()-ce;_n?cs.info("[fix] Watchdog: message loop active",{messageCount:Tn,elapsed:e}):(cs.info("[fix] Watchdog: waiting for first SDK message",{elapsed:e}),k&&!En&&e>=15e3&&(je({text:"Still preparing verification. This can take a bit...\n"}),En=!0)),cs.flush()},15e3);kn.unref();try{let t=!1,n=!1;for(;;){if(!O){cs.info("[fix] No response object, exiting message loop");break}t=!1,n=!1,cs.info("[fix] Entering for-await on SDK response");try{for await(const t of O){if(xn)break;Tn++,_n||(_n=Date.now(),clearTimeout(An),k&&qe({label:void 0}),cs.info("[fix] First SDK message received",{waitDurationMs:_n-ce,messageType:t.type,messageSubtype:"subtype"in t?t.subtype:void 0}));const r="session_id"in t&&"string"==typeof t.session_id?t.session_id:void 0;if(r&&r!==B&&(B=r,cs.debug("Captured Claude session id",{sessionId:B})),"stream_event"===t.type){const{event:e}=t;(Tn<=5||Tn%200==0)&&cs.debug("[fix] Stream event",{msgNum:Tn,eventType:e?.type});const n=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_start"===e?.type){const t=e.content_block;"thinking"===t?.type&&(wn=e.index??null)}if("content_block_delta"===e?.type){const{delta:t}=e;if("text_delta"===t?.type&&t.text){In&&(te({role:"thinking",content:In,timestamp:(new Date).toISOString()}),In="");const e=n&&Z.has(n)?n:1===Z.size?Array.from(Z.keys())[0]:void 0;e?De({toolUseId:e,kind:"text",content:t.text}):k||je({text:t.text})}const r=t;if("thinking_delta"===r?.type&&r.thinking){if(n&&Z.has(n))continue;if(In+=r.thinking,!k){const e=null!==wn&&wn!==vn;Me({text:r.thinking,forceNewBlock:e}),e&&(vn=wn)}continue}}if("content_block_stop"===e?.type){const t=e.index;null!==wn&&wn===t&&(Ve(),In&&(te({role:"thinking",content:In,timestamp:(new Date).toISOString()}),In=""),wn=null,Ye())}"message_stop"===e?.type&&U&&(J=!1,U.allowNextTurn());continue}if("assistant"===t.type){const n="parent_tool_use_id"in t&&"string"==typeof t.parent_tool_use_id?t.parent_tool_use_id:void 0,{content:r}=t.message??{};if(Array.isArray(r)&&!n){const t=r.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&&(nt=t,k&&(rt=rt?`${rt}\n\n${t}`:t),cs.debug("Assistant message",{text:k?qc(t):t}),"fix"===e.mode&&(he(sl,{type:"ai_message",summary:t.slice(0,200)}),ge({type:"ai_message",summary:t.slice(0,200)})),P&&Ee({type:"ai_message",summary:t.slice(0,200)}),te({role:"assistant",content:t,timestamp:(new Date).toISOString()}))}if(Z.size>0){const e=Array.isArray(r)?r.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):[];cs.debug("Assistant message with active subagents",{hasParentToolUseId:!!n,parentToolUseId:n,activeSubagentIds:Array.from(Z.keys()),toolNames:e,fullMessageKeys:Object.keys(t),rawMessage:JSON.stringify(t).slice(0,500)})}if(Array.isArray(r))for(const t of r){if("tool_use"===t?.type){if("mcp__auto-heal-report__generate-report"===t.name&&(J=!0),t.name.startsWith("mcp__session-control__")||t.name.startsWith("mcp__stably-agent-control__"))continue;if(ll(t.name))continue;if(k&&cl.test(t.name))continue;if(Z.size>0&&cs.debug("Tool use detected with active subagents",{toolName:t.name,hasParentToolUseId:!!n,parentToolUseId:n,wouldRouteToSubagent:!!n&&Z.has(n),activeSubagentIds:Array.from(Z.keys())}),"Task"===t.name){const n=t.input,r=n&&"object"==typeof n?n:void 0,s=r&&"subagent_type"in r&&"string"==typeof r.subagent_type?r.subagent_type:"subagent",o=r&&"description"in r&&"string"==typeof r.description?r.description.trim():"";if(cs.info("[fix] Subagent started",{subagentType:s,description:o,toolUseId:t.id,activeSubagentCount:Z.size+1}),Z.set(t.id,{subagentType:s,description:o}),Ne({toolUseId:t.id,subagentType:s,description:o}),"fix"===e.mode){if("triage"===s){Xe?.({phase:"triage"});const e={id:t.id,testDescription:"Triage",workerType:"triage",status:"running",summary:null,startedAt:Date.now(),endedAt:null,activity:[]};ye({phase:"triage",workers:[...ue?.workers??[],e]})}else if("code-worker"===s){de.add(o||t.id);const e={id:t.id,testDescription:o||t.id,workerType:"code-worker",status:"running",summary:null,startedAt:Date.now(),endedAt:null,activity:[]};Xe?.({phase:"fixing",totalTests:de.size,currentTestDescription:o||null}),ye({phase:"fixing",totalTests:de.size,currentTestDescription:o||null,lastTestDescription:o||ue?.lastTestDescription||null,workers:[...ue?.workers??[],e]})}else if("browser-worker"===s){de.add(o||t.id);const e={id:t.id,testDescription:o||t.id,workerType:"browser-worker",status:"running",summary:null,startedAt:Date.now(),endedAt:null,activity:[]};Xe?.({phase:"debugging",totalTests:de.size,currentTestDescription:o||null}),ye({phase:"debugging",totalTests:de.size,currentTestDescription:o||null,lastTestDescription:o||ue?.lastTestDescription||null,workers:[...ue?.workers??[],e]})}else"validation"===s?(Xe?.({phase:"validation",currentTestDescription:null}),ye({phase:"validation",currentTestDescription:null})):"context"===s&&ye({currentTestDescription:o||null});ge({type:"tool_call",summary:`[${s}] ${o}`.trim()})}if(S)if("create-planner"===s)_e({phase:"planning",currentActivity:"Analyzing test plan..."}),Ee({type:"tool_call",summary:`[create-planner] ${o}`.trim()});else if("create-worker"===s){const e=o.match(/(?:route|page)[:\s]+([^\s,]+)/i),n=(e?.[1]??o.slice(0,50))||t.id,r=o.match(/(\d+)\s*test/i),s=r?parseInt(r[1],10):1,i={pageGroupId:t.id,route:n,status:"exploring",testsCreated:0,testsTotal:s};pe.set(t.id,i),_e({phase:"generating",currentActivity:`Worker exploring ${n}...`,workers:Array.from(pe.values())}),Ee({type:"tool_call",summary:`[create-worker] ${o}`.trim()})}continue}if(n&&Z.has(n)){const r=Po(t.name,t.input),s=r??Ro(t.name),o=r?void 0:Co(t.name,t.input),i=o?`${s} (${o})`:s;if(cs.debug("Subagent tool called",{tool:t.name,parentToolUseId:n}),De({toolUseId:n,kind:"tool",content:i}),"fix"===e.mode){ge({type:"tool_call",summary:i});const e=Z.get(n);"code-worker"!==e?.subagentType&&"browser-worker"!==e?.subagentType&&"triage"!==e?.subagentType||he(n,{type:"tool_call",summary:i})}if(S){const e=Z.get(n);if(("create-planner"===e?.subagentType||"create-worker"===e?.subagentType)&&(Ee({type:"tool_call",summary:i}),"create-worker"===e.subagentType&&pe.has(n))){const e="Bash"===t.name&&t.input&&"object"==typeof t.input?t.input.command:void 0;t.name.includes("run-test")||t.name.includes("run_test")||"string"==typeof e&&e.includes("run-test")?fe(n,{status:"validating"}):"Write"!==t.name&&"Edit"!==t.name||fe(n,{status:"writing"})}}continue}if(n&&cs.debug("Tool with parent_tool_use_id but no matching subagent",{tool:t.name,parentToolUseId:n,activeSubagentIds:Array.from(Z.keys())}),cs.debug("Tool called",{tool:t.name,input:t.input}),Oe({rawName:t.name,toolInput:t.input}),t.id&&se.set(t.id,t.name),te({role:"tool",content:"",timestamp:(new Date).toISOString(),toolName:t.name,toolInput:t.input}),"fix"===e.mode){const e=Po(t.name,t.input),n=e??Ro(t.name),r=e?void 0:Co(t.name,t.input),s=r?`${n} (${r})`:n;he(sl,{type:"tool_call",summary:s}),ge({type:"tool_call",summary:s})}if(S){const e=Po(t.name,t.input),n=e??Ro(t.name),r=e?void 0:Co(t.name,t.input),s=r?`${n} (${r})`:n;"initializing"===Te?.phase?_e({phase:"generating",currentActivity:s}):"mcp__playwright-test__test_run"===t.name&&"generating"===Te?.phase?_e({phase:"testing",currentActivity:s}):_e({currentActivity:s}),Ee({type:"tool_call",summary:s})}if(k){const e=Po(t.name,t.input),n=e??Ro(t.name),r=e?void 0:Co(t.name,t.input),s=qc(r?`${n} (${r})`:n);_e("initializing"===Te?.phase?{phase:"verifying",currentActivity:s}:{currentActivity:s}),Ee({type:"tool_call",summary:s})}}if("text"===t?.type){const r="string"==typeof t.text?t.text:"",s=n&&Z.has(n)?n:1===Z.size?Array.from(Z.keys())[0]:void 0;if(s&&r){if(De({toolUseId:s,kind:"text",content:r}),"fix"===e.mode){const e=Z.get(s);"code-worker"!==e?.subagentType&&"browser-worker"!==e?.subagentType&&"triage"!==e?.subagentType||he(s,{type:"ai_message",summary:r.slice(0,200)})}if(S){const e=Z.get(s);"create-planner"!==e?.subagentType&&"create-worker"!==e?.subagentType||Ee({type:"ai_message",summary:r.slice(0,200)})}}}}continue}if("user"===t.type){const n="message"in t&&t.message&&"object"==typeof t.message&&"content"in t.message?t.message.content:void 0,r="tool_use_result"in t&&t.tool_use_result&&"object"==typeof t.tool_use_result?t.tool_use_result:void 0;if(Array.isArray(n))for(const t of n)if(t&&"object"==typeof t&&"type"in t&&"tool_result"===t.type&&"tool_use_id"in t){const n="string"==typeof t.tool_use_id?t.tool_use_id:void 0,s="is_error"in t&&!0===t.is_error||"error"===r?.status;let o;const i=r?.content??("content"in t?t.content:void 0);"string"==typeof i?o=i:Array.isArray(i)&&(o=i.filter(e=>e&&"object"==typeof e&&"text"===e.type).map(e=>e.text||"").join("")),cs.debug("Tool result",{toolUseId:n,isError:s,output:o?.slice(0,500)});const a=5e4,c=n?se.get(n):void 0;if(te({role:"tool_result",content:"",timestamp:(new Date).toISOString(),toolName:c,toolOutput:o?.slice(0,a),isError:s}),n&&Z.has(n)){const t=Z.get(n);if(cs.info("[fix] Subagent completed",{toolUseId:n,isError:s,subagentType:t?.subagentType,description:t?.description,activeSubagentCount:Z.size-1}),o&&De({toolUseId:n,kind:"text",content:o}),Je({toolUseId:n,status:s?"error":"complete"}),"fix"===e.mode&&"triage"===t?.subagentType){const e=s?"failed":"succeeded",t=o?o.slice(0,500):null,r=(ue?.workers??[]).map(r=>r.id===n?{...r,status:e,summary:t,endedAt:Date.now()}:r);ye({workers:r})}if("fix"===e.mode&&("code-worker"===t?.subagentType||"browser-worker"===t?.subagentType)){const e=s?"failed":"succeeded",t=o?o.slice(0,500):null,r=(ue?.workers??[]).map(r=>r.id===n?{...r,status:e,summary:t,endedAt:Date.now()}:r);s?(Xe?.({failedTests:(ue?.failedTests??0)+1,currentTestDescription:null}),ye({failedTests:(ue?.failedTests??0)+1,currentTestDescription:null,workers:r})):(Xe?.({fixedTests:(ue?.fixedTests??0)+1,currentTestDescription:null}),ye({fixedTests:(ue?.fixedTests??0)+1,currentTestDescription:null,workers:r}))}if(S&&t)if("create-planner"===t.subagentType)Ee({type:"ai_message",summary:s?"Planner failed":"Test plan analyzed, launching workers..."}),s||_e({phase:"generating",currentActivity:"Launching workers..."});else if("create-worker"===t.subagentType){if(pe.has(n)){const e=o?.match(/\*\*Created:\*\*\s*(\d+)/i),t=e?parseInt(e[1],10):0;fe(n,{status:s?"failed":"complete",testsCreated:t})}Ee({type:"ai_message",summary:s?`Worker failed: ${t.description?.slice(0,100)}`:`Worker complete: ${t.description?.slice(0,100)}`})}Z.delete(n)}}continue}if("result"!==t.type);else{if(n=!0,cs.info("[fix] Agent result received",{subtype:t.subtype,messageCount:Tn,elapsed:Date.now()-ce,activeSubagents:Z.size,fixedTests:ue?.fixedTests,failedTests:ue?.failedTests,phase:ue?.phase}),I){if("success"===t.subtype){j&&(clearTimeout(j),j=void 0);for(const e of K)U?.pushText(`[Message from web UI user]: ${e}`);if(K=[],(P||"fix"===e.mode)&&U){if(U.hasQueuedMessages()){cs.info("[ws] Queued web UI messages found, continuing agent"),F=!0,U.allowNextTurn();continue}if(await ul(U,3e3)){cs.info("[ws] Web UI message received during grace period, continuing agent"),F=!0,U.allowNextTurn();continue}U.finish()}Xe?.({phase:"complete",currentTestDescription:null,endedAt:Date.now()}),ye({phase:"complete",currentTestDescription:null,endedAt:Date.now(),isError:!1,workers:me(!1)}),await Promise.allSettled(it);const t=Xc({mode:e.mode,lastAssistantText:nt});if("verify"===e.mode){(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt).trim();const n=rt||nt,r=/```verdict\s*\r?\n/.test(n),s=Jc(n)??{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=Kc(s);"PASS"===s.verdict?Dn("success","VERIFICATION PASSED"):"FAIL"===s.verdict?Dn("error","VERIFICATION FAILED"):Dn("warning","VERIFICATION INCONCLUSIVE"),o.steps.length>0&&o.steps.forEach((e,t)=>{}),o.reason&&(s.verdict,o.reason),o.evidence.length>0&&o.evidence.forEach(e=>{}),_e({phase:"complete",endedAt:Date.now(),isError:"PASS"!==s.verdict,currentActivity:null,resultSummary:t}),process.exitCode="PASS"===s.verdict?0:"FAIL"===s.verdict?1:2,Ze({status:"success"})}else{if(_e({phase:"complete",endedAt:Date.now(),isError:!1,currentActivity:null,resultSummary:t}),nn&&st.length>0){Dn("success","Created files:");for(const e of st)Dn("success",`- ${e}`)}const e=et?Dn("info",`π View Autoheal Report:\n ${((e,t)=>`]8;;${e}${t}]8;;`)(et,re.bold(re.underline(Dn("link",et))))}`):void 0;Ze({status:"success",result:e}),oe="COMPLETED"}}else if(M||X)cs.info("[fix] Suppressing error status: user-message interrupt in progress");else if(H)oe="CANCELED",ye({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:me(!0)}),await Promise.allSettled(it),_e({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0});else if(k){let e="Execution error before verification completed.";"error_max_budget_usd"===t.subtype?e="Budget limit exceeded before verification completed.":"error_max_turns"===t.subtype&&(e="Maximum turns exceeded before verification completed."),Dn("warning","VERIFICATION INCONCLUSIVE"),await Promise.allSettled(it),_e({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),Ze({status:"success"}),process.exitCode=2}else{let e,n="unknown",r="Run failed.";"error_max_budget_usd"===t.subtype?(n="budget_exceeded",e="total_cost_usd"in t?t.total_cost_usd:void 0,r=`Budget limit exceeded (${void 0!==e?`$${e.toFixed(2)}`:"unknown"} spent). The fix session was stopped to prevent runaway costs.`,cs.warn("[fix] Budget limit exceeded",{subtype:t.subtype,totalCostUsd:e})):"error_max_turns"===t.subtype?(n="max_turns",r="Maximum turns exceeded. The fix session was stopped."):"error_during_execution"===t.subtype&&(n="execution_error"),Xe?.({endedAt:Date.now(),isError:!0}),ye({phase:"complete",endedAt:Date.now(),isError:!0,errorReason:n,errorMessage:r,totalCostUsd:e,currentTestDescription:null,workers:me(!0)}),await Promise.allSettled(it),_e({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),Ze({error:r,status:"error"}),process.exitCode=1,oe="FAILED"}H=!1;break}if("success"!==t.subtype){if(!H){let e="Run failed.";"error_max_budget_usd"===t.subtype?(e=`Budget limit exceeded (${"total_cost_usd"in t?`$${t.total_cost_usd.toFixed(2)}`:"unknown"} spent). The fix session was stopped to prevent runaway costs.`,cs.warn("[fix] Budget limit exceeded",{subtype:t.subtype,totalCostUsd:"total_cost_usd"in t?t.total_cost_usd:void 0})):"error_max_turns"===t.subtype&&(e="Maximum turns exceeded. The fix session was stopped."),Ze({error:e,status:"error"}),process.exitCode=1}}else Ze({status:"success"});F=!1,H=!1,qe({label:void 0}),U?.allowNextTurn(),_&&q>0&&(q-=1,F=!0,Ze({status:"running"}))}}}catch(e){if(Le){Le=!1,H=!1,Z.clear(),He(),In&&te({role:"thinking",content:In,timestamp:(new Date).toISOString()}),wn=null,vn=null,In="",Ye(),q>0?(F=!0,Ze({status:"running"})):(F=!1,Ze({status:"success"})),t=!0;continue}const r=e instanceof Error&&"Claude Code process exited with code 1"===e.message;if(r&&n){cs.info("[fix] Claude Code process exited with code 1 (normal exit after result)",{inFlight:F,interrupted:H});break}if(r&&(X||M||H)){cs.info("[fix] Claude Code process exited with code 1 (interrupted)",{inFlight:F,interrupted:H,userMessageInterruptTriggered:!!X,interruptInProgress:!!M});break}throw e}if(Le)Le=!1,H=!1,Z.clear(),He(),In&&te({role:"thinking",content:In,timestamp:(new Date).toISOString()}),wn=null,vn=null,In="",Ye(),q>0?(F=!0,Ze({status:"running"})):(F=!1,Ze({status:"success"})),t=!0;else if(M&&await M,X&&(X=!1,t=!0,Ze({status:"running"}),cs.info("[fix] Resuming after user-message interrupt")),!t)break}}catch(e){H?(oe="CANCELED",ye({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:me(!0)}),await Promise.allSettled(it),_e({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0})):(cs.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()-ce}),Ze({error:`Agent encountered an error: ${e}`,status:"error"}),process.exitCode=1,oe="FAILED",ye({phase:"complete",endedAt:Date.now(),isError:!0,currentTestDescription:null,workers:me(!0)}),await Promise.allSettled(it),_e({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),cs.flush(),cs.printLogFileInfo())}finally{if(An&&clearTimeout(An),clearInterval(kn),j&&(clearTimeout(j),j=void 0),cs.info("[fix] Agent session ending",{finalStatus:oe,elapsed:Date.now()-ce,totalMessages:Tn}),Yt(),F=!1,H=!1,bn(),process.off("uncaughtException",l),U?.finish(),oe){cs.info("[fix] Reporting final autoheal status",{status:oe});const e=Date.now();await be(oe),cs.info("[fix] Final autoheal status reported",{durationMs:Date.now()-e})}if(cs.info("[fix] Closing WebSocket progress reporter"),await(le?.closeAndWait()),await Promise.allSettled(it),await(Ie?.closeAndWait()),!Mt&&ee.length>0&&Se){cs.info("[session] Uploading session history",{messageCount:ee.length});try{await Ds({authHeader:await d.getAuthHeader(),orgId:p,sessionId:Se,projectId:ys(u),history:ee})}catch(e){cs.warn("[session] Failed to upload session history",{error:e instanceof Error?e.message:String(e)})}}if(Mt&&Vt){const t=Date.now();try{cs.info("[fix] Computing diff...");const n=await Vt.computeDiff();if(n&&n.trim().length>0){cs.info("[fix] Uploading diff...",{diffLength:n.length});const r=await d.getAuthHeader(),{diffBucketPath:s,uploadUrl:o}=await ks({authHeader:r,contentType:"text/plain",orgId:p,runId:e.runId});await Ss({body:n,contentType:"text/plain",uploadUrl:o,errorContext:"diff"}),await Cs({authHeader:r,diffBucketPath:s,orgId:p,runId:e.runId}),cs.info("[fix] Diff uploaded",{durationMs:Date.now()-t})}else cs.info("[fix] No diff to upload (empty or no changes)")}catch(e){cs.warn("[fix] Failed to upload diff",{error:e instanceof Error?e.message:String(e),durationMs:Date.now()-t})}}if(cs.info("[fix] Cleaning up diff tracker"),await(Vt?.cleanup()),Mt&&ee.length>0&&Se){cs.info("[fix] Uploading session history",{messageCount:ee.length});try{await Ds({authHeader:await d.getAuthHeader(),orgId:p,sessionId:Se,projectId:ys(u),history:ee})}catch(e){cs.warn("[fix] Failed to upload session history",{error:e instanceof Error?e.message:String(e)})}}const t=r.join(f,".stably","traces");await Y(t,{recursive:!0,force:!0}).catch(()=>{}),cs.info("[fix] Running final cleanup"),await(Wt?.cleanup()),await Ge(),cs.info("[fix] Cleanup complete"),xn&&(cs.flush(),cs.printLogFileInfo(),process.exit(1))}},hl=fe.object({runId:fe.string(),timestamp:fe.number()}),gl=async()=>{try{const e=await Ar(process.cwd(),".stably/last-run.json");if(!e)return;const t=await z(e,"utf-8");return{...hl.parse(JSON.parse(t)),filePath:e}}catch{return}};function ml(e=process.cwd()){let t=s(e);for(;;){const e=yl(t);if(e){const n={...e.dependencies,...e.devDependencies},r="@playwright/test"in n?"@playwright/test":"playwright"in n?"playwright":void 0;if(r){const e=bl(t);let n=!1,s=t;for(;;){const e=i(s,"node_modules"),t=i(e,r);if(E(t)){n=!0;break}const a=o(s);if(a===s)break;s=a}return{inNodeModules:n,installed:!0,packageManager:e,packageName:r}}}const n=o(t);if(n===t)return{inNodeModules:!1,installed:!1,packageManager:void 0};t=n}}function yl(e){const t=i(e,"package.json");let n;try{n=x(t,"utf-8")}catch{return}try{return JSON.parse(n)}catch{return}}function bl(e){const t=[["npm","package-lock.json"],["pnpm","pnpm-lock.yaml"],["yarn","yarn.lock"]];let n=e;for(;;){for(const[e,r]of t)if(E(i(n,r)))return e;const e=o(n);if(e===n)return;n=e}}function wl(e){if("npm"===e||"pnpm"===e)return["npx","playwright"];if("yarn"===e)return["yarn","playwright"];throw new Error("Package manager not supported")}var vl=[{args:["--trace=on"],description:"Run Playwright tests",name:"test"},{args:[],description:"Install browser dependencies",name:"install"}],Il=["You have two different versions of @playwright/test"];function Tl(e){const[t,...n]=wl(e),r=[t,...n.slice(0,-1)].join(" ");return(t,n)=>{let s=t.toString();for(const e of vl)s=s.replaceAll(`${r} playwright ${e.name}`,`${r} stably ${e.name}`).replaceAll(`npx playwright ${e.name}`,`npx stably ${e.name}`);if("yarn"===e){const e=s.split("\n");return e.length>0&&(e[0].includes("/.bin/playwright")||e[0].includes("\\.bin\\playwright"))&&e.shift(),void n.write(e.join("\n"))}n.write(s)}}async function _l({overrideArgs:e,subcommand:t}){cs.info("[test] forwardToPlaywright starting",{subcommand:t,overrideArgs:e});const n=process.argv,r=n.findIndex((e,n)=>n>1&&e===t),a=-1===r?[]:n.slice(r+1),c="--"===a[0],u=c?a.slice(1):a;if(!c&&("--help"===u[0]||"-h"===u[0]))return async function({subcommand:e}){const t=vl.find(t=>t.name===e),n=e=>process.stdout.write(`${e}\n`);n(`stably ${e} - ${t?.description??""}`),n(""),"test"===e&&(n('IMPORTANT: Always use "stably" commands instead of "playwright" directly.'),n(""),n("Stably commands:"),n(" stably test [file] Run tests (auto-enables tracing and analytics)"),n(" stably fix [runId] Auto-fix failing tests using AI"),n(" stably create [prompt] Generate new tests from a prompt or branch diff"),n(""),n("Stably options:"),n(" --env <name> Load environment variables from a remote Stably environment"),n(" --env-file <path> Load environment variables from a local .env file (repeatable)"),n(""),n("Why use Stably?"),n(' - "stably fix" automatically repairs broken tests'),n(' - "stably test" enables --trace=on and test analytics'),n(' - "stably create" generates tests from prompt'),n(""));const r=ml();if(!r.installed||!r.inNodeModules)return void n('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:s}=r;if(!s)return void n("Could not determine package manager.");n("Playwright options:"),n("");const[o,...i]=wl(s),a=Tl(s);return new Promise(t=>{const n=g(o,[...i,e,"--help"],{stdio:["inherit","pipe","pipe"],shell:"win32"===process.platform,env:{...process.env,...process.env.CI?{}:{FORCE_COLOR:"1"}}});n.stdout?.on("data",e=>{a(e,process.stdout)}),n.stderr?.on("data",e=>{a(e,process.stderr)}),n.on("close",()=>{t()})})}({subcommand:t});const d=e??[],p=new Set(d.map(e=>{const[t]=e.split("=");return t})),f=[];for(let e=0;e<u.length;e++){const t=u[e],[n]=t.split("=");p.has(n)?!t.includes("=")&&e+1<u.length&&!u[e+1].startsWith("-")&&e++:f.push(t)}const m=[t,...d,...f];cs.info("[test] Forwarded args computed",{forwardedArgs:m}),cs.info("[test] Resolving Stably test environment");const y=Date.now(),b="test"===t?await(async()=>{cs.info("[test] Resolving Stably test env");const e=(()=>{if(process.env.STABLY_WS_URL)return;if("https://api.stably.ai"===pr)return;const e=pr.startsWith("http://")?"ws://":"wss://";return`${pr.replace(/^https?:\/\//,e).replace(/\/$/,"")}/reporter`})();cs.debug("[test] WebSocket URL resolved",{wsUrl:e??"(default)"});const t=hs();if(t)return cs.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}};cs.info("[test] No env var auth, attempting OAuth auth");const n=Date.now(),r=await(async()=>{const e=hs();if(e)return{auth:e,type:"env"};const t=await gs(),n=t?await Or():void 0;return t&&n?{auth:{accessToken:t.accessToken,context:n},type:"oauth"}:void 0})();if(cs.info("[test] OAuth auth resolved",{durationMs:Date.now()-n,hasAuth:!!r,authType:r?.type}),!r||"env"===r.type)return void cs.info("[test] No usable auth found");const s=process.env.STABLY_PROJECT_ID?.trim(),o=s||ys(r);if(!o)return void cs.warn("[test] No project ID available");cs.info("[test] Fetching JWT API key",{projectId:o});const i=Date.now(),a=await(async(e,t)=>{try{cs.debug("Requesting JWT API key",{projectId:t,apiUrl:pr});const n=await(async({accessToken:e,projectId:t})=>{const n=await(r={auth:e,client:vr(),path:{projectId:t}},(r.client??cr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/api-key",...r}));var r;if(n.error){const e=n.error?.error,{status:t}=n.response;throw new Error(e??`Failed to get API key: ${t}`)}return n.data})({accessToken:e,projectId:t});return cs.debug("JWT API key obtained",{keyPrefix:n.apiKey.substring(0,10)}),n.apiKey}catch(e){return void cs.warn("Failed to get JWT API key for test reporter",{error:e instanceof Error?e.message:String(e)})}})(r.auth.accessToken,o);cs.info("[test] JWT API key fetch complete",{durationMs:Date.now()-i,success:!!a});const c=a?{STABLY_API_KEY:a,STABLY_PROJECT_ID:o,...e&&{STABLY_WS_URL:e}}:void 0;return cs.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})():void 0;cs.info("[test] Stably test environment resolved",{durationMs:Date.now()-y,hasCredentials:null!=b,hasWsUrl:!!b?.STABLY_WS_URL}),cs.info("[test] Loading remote environment variables");const w=await Is();cs.info("[test] Remote environment loaded",{hasRemoteEnv:!!w,variableCount:w?Object.keys(w.variables).length:0});const v={};if(w){const e=[];for(const[t,n]of Object.entries(w.variables))void 0===process.env[t]?v[t]=n:process.env[t]!==n&&e.push(t);e.length>0&&cs.warn(`[test] π‘ Local environment variables overriding remote: ${e.join(", ")}`),w.sensitiveValues.length&&void 0===process.env.STABLY_SENSITIVE_VALUES&&(v.STABLY_SENSITIVE_VALUES=Buffer.from(JSON.stringify(w.sensitiveValues)).toString("base64"))}cs.info("[test] Setting up Stably reporter injection");const S="test"===t?function({forwardedArgs:e,hasCredentials:t}){if(!t){console.warn("[33mβ οΈ Stably credentials not found. Test results will not be reported to Stably.[0m");const e=us();if("local"!==e){const t=ps(e);console.warn(`[33m To enable reporting, add the following to your ${t}:[0m`),console.warn("[33m β’ STABLY_API_KEY β https://app.stably.ai/settings?tab=api-key[0m"),console.warn("[33m β’ STABLY_PROJECT_ID β https://app.stably.ai/settings?tab=project-id[0m\n")}else console.warn("[33m To enable reporting, either:[0m"),console.warn("[33m β’ Run `npx stably login` to authenticate[0m"),console.warn("[33m β’ Or set STABLY_API_KEY and STABLY_PROJECT_ID environment variables[0m\n");return}const n=process.cwd(),r=e=>{const t=function(e){let t=s(e);for(;;){if([i(t,"node_modules","@stablyai","playwright-test"),i(t,"node_modules",".pnpm","@stablyai+playwright-test")].some(e=>E(e)))return!0;const e=o(t);if(e===t)return!1;t=e}}(e);return t||(console.warn("[33mβ οΈ @stablyai/playwright-test is not installed. Stably reporter will not be injected.[0m"),console.warn("[33m Install it with: npm install @stablyai/playwright-test[0m"),console.warn("[33m Reference: ]8;;https://docs.stably.ai/getting-started/sdk-setup-guidehttps://docs.stably.ai/getting-started/sdk-setup-guide]8;;[0m\n")),t},a=(e,t)=>{try{return function({baseConfigPath:e,projectDir:t}){const n=function(e){try{const t=h("npm pkg get type",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return"module"===JSON.parse(t.trim())}catch{return!1}}(t),r=n?"mts":"ts",a=o(s(e)),c=l(e),u=i(a,function(e){return"1"===process.env[mo]?`${ho}-wrapper.config.${e}`:`.stably-playwright-wrapper.config.${e}`}(r)),d=`\n// Auto-generated wrapper config by Stably CLI\n// This file injects the Stably reporter and ensures trace is enabled\nimport baseConfig from './${c}';\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: '${dr}',\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: '${dr}',\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 E(a)||I(a,{recursive:!0}),T(u,d,"utf-8"),function(e,t){const n=i(e,".gitignore");try{if(E(n)){const e=x(n,"utf-8");if(e.split("\n").map(e=>e.trim()).includes(t))return;const r=e.length>0&&!e.endsWith("\n");A(n,`${r?"\n":""}${t}\n`)}else T(n,`${t}\n`)}catch{}}(a,"1"===process.env[mo]?go:".stably-playwright-wrapper.config.*"),u}({baseConfigPath:e,projectDir:t})}catch{return void console.warn("[33mβ οΈ Could not create Stably wrapper config. Reporter injection skipped.[0m")}};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 i=s(n,e[t+1]),c=o(i);if(!r(c))return;const l=a(i,c);if(!l)return;return e[t+1]=l,l}const i=e.findIndex(e=>e.startsWith("--config=")||e.startsWith("-c="));if(-1!==i){const t=s(n,e[i].split("=")[1]),c=o(t);if(!r(c))return;const l=a(t,c);if(!l)return;const u=e[i].startsWith("--config=")?"--config=":"-c=";return e[i]=`${u}${l}`,l}}const c=bo(n);if(!c)return;const u=o(c);if(!r(u))return;const d=a(c,u);return d?(e.push("--config",d),d):void 0}({forwardedArgs:m,hasCredentials:null!=b}):void 0;cs.info("[test] Reporter injection setup complete",{hasWrapperConfig:!!S}),cs.info("[test] Spawning Playwright process");const k=Date.now();if(await function(e,t={}){cs.info("[test] Detecting Playwright installation");const n=ml();cs.info("[test] Playwright installation check",{installed:n.installed,inNodeModules:n.inNodeModules,packageManager:n.packageManager,packageName:n.packageName}),n.installed||(console.error('Playwright is not installed. Please run "stably init" to install it.'),process.exit(1)),n.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:r}=n;r||(console.error("Playwright installation not found. Could not determine your package manager (tried pnpm, yarn, and npm)."),process.exit(1));const[s,...o]=wl(r),i=(a=t.env)?{...process.env,...a}:process.env;var a;const c=[s,...o,...e];cs.info("[test] Spawning Playwright process",{command:c.join(" "),pid:process.pid});const l=Date.now(),u=g(s,[...o,...e],{stdio:["inherit","pipe","pipe"],shell:"win32"===process.platform,env:{...i,...process.env.CI?{}:{FORCE_COLOR:"1"}}});cs.info("[test] Playwright process spawned",{childPid:u.pid});const d=Tl(r),p=function(){let e=!1,t="";return(n,r)=>{if(!e){t+=n,t.length>1024&&(t=t.slice(-1024));for(const n of Il)if(t.includes(n))return r.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)}}}();u.stdout?.on("data",e=>{d(e,process.stdout)}),u.stderr?.on("data",e=>{const t=e.toString();d(e,process.stderr),p(t,process.stderr)});const f=new AbortController,h=()=>!f.signal.aborted&&(f.abort(),t.onClose?.(),process.removeListener("SIGINT",m),process.removeListener("SIGTERM",m),!0),m=e=>{cs.info("[test] Signal received, killing Playwright process",{signal:e,childPid:u.pid}),h(),u.kill(e);const t="SIGINT"===e?130:143;process.exit(t)};return process.on("SIGINT",m),process.on("SIGTERM",m),new Promise((e,t)=>{u.on("error",e=>{h()&&(cs.error("[test] Playwright process error",{error:e.message,childPid:u.pid}),t(e))}),u.on("close",t=>{if(!h())return;cs.info("[test] Playwright process exited",{exitCode:t,durationMs:Date.now()-l});const n=[process.stdout,process.stderr].filter(e=>e.writableNeedDrain).map(e=>new Promise(t=>e.once("drain",t)));Promise.race([Promise.all(n),new Promise(e=>setTimeout(e,5e3))]).then(()=>{process.exitCode=t??0,e(t??0)})})})}(m,{env:{...v,...b},onClose:()=>{var e;cs.info("[test] Playwright process closed, cleaning up wrapper config"),(e=S)&&E(e)&&_(e)}}),Ue.remoteEnvName&&b){const e=await gl(),t=e&&e.timestamp>=k;if(e&&t){const t=await ms();await(async({authHeader:e,orgId:t,runId:n,envName:r,timeoutMs:s=3e3})=>{cs.debug("Tagging run with envName",{runId:n,envName:r});try{let i;const a=new Promise(e=>{i=setTimeout(()=>e("timeout"),s)}),c=await Promise.race([(o={auth:e,client:vr(),headers:Ts(t),path:{runId:n},body:{envName:r}},(o.client??cr).patch({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/metadata",...o,headers:{"Content-Type":"application/json",...o.headers}})),a]);if(clearTimeout(i),"timeout"===c)return void cs.warn("Timed out tagging run with envName",{runId:n,envName:r,timeoutMs:s});if(c.error)return void cs.warn("Failed to tag run with envName",{runId:n,envName:r,status:c.response?.status});cs.debug("Successfully tagged run with envName",{runId:n,envName:r})}catch(e){cs.warn("Error tagging run with envName",{runId:n,envName:r,error:e instanceof Error?e.message:String(e)})}var o})({authHeader:bs(t),orgId:"oauth"===t.type?t.auth.context.orgId:void 0,runId:e.runId,envName:Ue.remoteEnvName})}else e&&!t?cs.debug("[test] last-run.json predates this test invocation, skipping envName tagging",{runId:e.runId,fileTimestamp:e.timestamp,testStartTime:k}):cs.debug("[test] No last-run.json found, skipping envName tagging")}}function El(e){const t=new Date(e),n=new Date,r=n.getTime()-t.getTime(),s=Math.floor(r/1e3),o=Math.floor(s/60),i=Math.floor(o/60),a=Math.floor(i/24);if(s<60)return"just now";if(o<60)return`${o}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()===n.getFullYear()?`${c} ${l}`:`${c} ${l}, ${t.getFullYear()}`}var Sl=e=>"oauth"===e.type?e.auth.context.orgId:void 0,xl=(e,t,n)=>{if(401!==e.response.status&&403!==e.response.status||(ce(Dn("error","Access denied.")),process.exit(1)),404===e.response.status&&n&&(ce(Dn("error",n)),process.exit(1)),400===e.response.status){const t=e.error&&"object"==typeof e.error&&"error"in e.error?e.error.error:"Bad request";ce(Dn("error",t)),process.exit(1)}e.error&&(ce(Dn("error",`Failed to ${t}: ${e.response.status}`)),process.exit(1))},Al={PASSED:e=>Dn("success",e),FAILED:e=>Dn("error",e),TIMEDOUT:e=>Dn("error",e),CANCELLED:e=>Dn("warning",e),INTERRUPTED:e=>Dn("warning",e),RUNNING:e=>Dn("info",e),QUEUED:e=>Dn("muted",e)},kl=(e,t)=>e?e.length>t?`${e.slice(0,t-1)}β¦`:e:"-",Cl=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")}`},Pl=e=>(Al[e]??(e=>e))(e),Rl=/\x1b\[[0-9;]*m/g,Ul=(e,t)=>{const n=e.replace(Rl,"").length,r=Math.max(0,t-n);return e+" ".repeat(r)},$l=e=>`${JSON.stringify(e,null,2)}\n`,Ll=(e,t,n)=>{if(!e)return;const r=e.toUpperCase();if(t.includes(r))return r;ce(Dn("error",`Invalid ${n} value "${e}". Must be one of: ${t.join(", ").toLowerCase()}`)),process.exit(1)},Dl=/\x1b\[[0-9;]*m/g,Nl=(e,t)=>{const n=e.replace(Dl,"").length,r=Math.max(0,t-n);return e+" ".repeat(r)},Ol=(e,t)=>e?e.length>t?`${e.slice(0,t-1)}β¦`:e:"-",Bl=e=>e?e.split("T")[0]??"-":"-",jl=e=>`${(100*e).toFixed(1)}%`,Ml=e=>`${JSON.stringify(e,null,2)}\n`,Fl=e=>{if(!e)return;const t=parseInt(e,10);return(Number.isNaN(t)||t<1||t>90)&&(ce(Dn("error","--days must be an integer between 1 and 90")),process.exit(1)),t},Hl=e=>{if(!e)return;const t=parseInt(e,10);return(Number.isNaN(t)||t<1||t>100)&&(ce(Dn("error","--limit must be an integer between 1 and 100")),process.exit(1)),t},Gl="stably",Wl=`https://registry.npmjs.org/${Gl}/latest`;function Vl(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 Yl(e,t){const n=Vl(e),r=Vl(t);return!(!n||!r)&&(r.major>n.major||!(r.major<n.major)&&(r.minor>n.minor||!(r.minor<n.minor)&&r.patch>n.patch))}var zl=r.join(D.homedir(),".stably"),ql=r.join(zl,"update-check.json"),Kl="1"===process.env.STABLY_DISABLE_UPDATE_CHECK,Jl=he.object({lastCheck:he.number(),latestVersion:he.string()}),Xl=Symbol.for("stably.updateNotifier.registered");function Ql(e=""){process.stdout.write(`${e}\n`)}function Zl(...e){process.stderr.write(`${e.join(" ")}\n`)}var eu=he.object({version:he.string()});var tu=!1,nu=async()=>{if(tu)try{const{shutdown:e}=await import("@hyperdx/node-opentelemetry"),t=process.stderr.write.bind(process.stderr),n=process.stdout.write.bind(process.stdout),r=(e,...t)=>{const n=t[0];return!("string"!=typeof n||!n.includes("OpenTelemetry"))||!(!Buffer.isBuffer(n)||!n.toString().includes("OpenTelemetry"))||e(...t)};process.stderr.write=(...e)=>r(t,...e),process.stdout.write=(...e)=>r(n,...e);try{await e()}finally{process.stderr.write=t,process.stdout.write=n}}catch{}},ru=e=>{const t=e.toLowerCase();return t.startsWith("npm_config_")||"node_options"===t};!function(){if(Kl||function(e=process.argv.slice(2)){return e.includes("upgrade")}())return;const e=function(){try{const e=v.readFileSync(ql,"utf-8");return Jl.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 = '${Wl}';\n const cacheFile = ${JSON.stringify(ql)};\n const cacheDir = ${JSON.stringify(zl)};\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{g(process.execPath,["--input-type=module","-e",e],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()}catch{}}(),null!=e&&Yl(dr,e.latestVersion)){if(!0===process[Xl])return;process[Xl]=!0;let t=!1;const n=()=>{if(t)return;t=!0;const n=`${Dn("warning",`update available (${dr} β ${e.latestVersion})`)} - run \`${Gl} upgrade\` to get the latest version\n`;try{v.writeSync(2,n)}catch{}};process.once("beforeExit",n),process.once("exit",n)}}(),Ue.cwdChanged&&cs.debug("Changed working directory",{cwd:Ue.newCwd});for(const e of Ue.envFilesLoaded)cs.debug("Loaded env file",{path:e});for(const e of Ue.envFileErrors)cs.warn(e);var su=process.argv.findIndex(e=>"-v"===e||"--verbose"===e);-1!==su&&process.argv.splice(su,1);var ou=process.argv.findIndex(e=>"--no-telemetry"===e);-1!==ou&&process.argv.splice(ou,1),cs.info("CLI starting",{version:dr,args:process.argv.slice(2),cwd:process.cwd()}),process.on("unhandledRejection",(e,t)=>{cs.error("Unhandled promise rejection",{reason:e instanceof Error?{message:e.message,stack:e.stack}:e,promise:String(t)}),cs.flush(),cs.printLogFileInfo()}),process.on("uncaughtException",(e,t)=>{"EPIPE"!==e.code&&(cs.error("Uncaught exception",{error:{message:e.message,stack:e.stack,name:e.name},origin:t}),cs.flush(),cs.printLogFileInfo())});var iu=new u;iu.name("stably").description("AI-assisted Playwright testing CLI").version(dr),iu.enablePositionalOptions();var au=(e,t)=>"cloud"===t.browser||"cloud"===e.parent?.opts().browser||"1"===process.env.STABLY_CLOUD_BROWSER;iu.showHelpAfterError(),iu.exitOverride(),iu.configureHelp({subcommandTerm:e=>{const t=e.registeredArguments.map(e=>e.required?`<${e.name()}>`:`[${e.name()}]`).join(" ");return t?`${e.name()} ${t}`:e.name()}}),iu.addHelpText("after","\nGlobal options (available for all commands):\n -C, --cwd <path> Change working directory before running\n --browser <type> Browser type: local or cloud (default: local)\n --env <name> Load environment variables from a remote Stably environment\n --env-file <path> Load environment variables from a local .env file (repeatable)\n -v, --verbose Enable debug-level logging\n --no-telemetry Disable error telemetry");var cu=[];iu.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>{cu.push(e)}});var lu=()=>{const e=iu.helpInformation().trimEnd();return e?`${e}\n`:""},uu=(e,t)=>{let n=e;for(const e of t){const t=n.commands.find(t=>t.name()===e||t.aliases().includes(e));if(!t)return;n=t}return n},du=()=>{process.stdout.write(lu())};iu.command("help [command...]").description("Show help for a command (e.g. stably help create)").action(e=>{if(!e||0===e.length)return void du();const t=uu(iu,e);if(!t)return process.stderr.write(`Unknown command: ${e.join(" ")}\n`),du(),void(process.exitCode=1);var n;n=t,process.stdout.write((e=>{const t=e.helpInformation().trimEnd();return t?`${t}\n`:""})(n))}),iu.option("--browser <type>","Browser type: local or cloud (default: local)").action((e,t)=>fl({mode:"chat",getHelpText:lu,cloudBrowser:au(t,e)})),iu.command("login").description("Authenticate with Stably in your browser").action(Vr),iu.command("logout").description("Clear stored Stably credentials").action(async()=>{const e=hs();e&&(ae.warn(`Environment variables ${Dn("info","STABLY_API_KEY")} and ${Dn("info","STABLY_PROJECT_ID")} are set.`),ae.warn("They will continue to be used for authentication even after logout."),ae.warn("Unset them if you want to fully de-authenticate this shell/session."));const t=await Lr();if(!t)return void ce(Dn("warning",e?"No stored OAuth login found to clear.":"You are not logged in."));const n=le();n.start("Logging out..."),await(async e=>{try{await fetch(`${hr}/api/backend/v1/logout`,{body:JSON.stringify({refresh_token:e}),headers:{"Content-Type":"application/json"},method:"POST"})}catch{}})(t.refreshToken),await Nr(),await Br(),n.stop(Dn("success","β Logged out")),ce(Dn("success","You have been logged out successfully."))}),iu.command("whoami").description("Show auth status and current project").action(async()=>{ae.info(`${re.bold("CLI Version:")} ${Dn("info",dr)}`);const e=hs();if(e){ae.info(re.dim("Authentication: Environment variables")),ae.info(` ${re.bold("API Key:")} ${Dn("info",e.apiKey.slice(0,8))}...`),ae.info(` ${re.bold("Project ID:")} ${Dn("info",e.projectId)}`);const t=await Lr();if(t){let e;try{e=xr(t.accessToken).email}catch{e=void 0}ae.warn("Stored OAuth login detected but will be ignored (env auth takes precedence)."),e&&ae.info(` ${re.bold("OAuth Email:")} ${Dn("info",e)}`),ae.info(` ${re.bold("Tip:")} Unset env vars to use OAuth`)}return void ce(Dn("success","Authenticated via environment variables"))}const t=await Lr();if(!t)return void ce(Dn("warning","Not logged in. Run `stably login` to authenticate."));let n;try{n=xr(t.accessToken).email}catch{n=void 0}const s=await Or();if(!s)return ae.info(re.dim("Authentication: OAuth (not linked to a project)")),n&&ae.info(` ${re.bold("Email:")} ${Dn("info",n)}`),void ce(Dn("warning","Logged in but this directory is not linked to a project. Run `stably login` to link."));const o=await(async()=>Ar(process.cwd(),Pr))(),i=o?r.dirname(o):process.cwd(),a=r.relative(process.cwd(),i)||".";ae.info(re.dim("Authentication: OAuth")),n&&ae.info(` ${re.bold("Email:")} ${Dn("info",n)}`),ae.info(` ${re.bold("Organization:")} ${Dn("info",s.orgName)}`),ae.info(` ${re.bold("Project:")} ${Dn("info",s.projectName)}`),ae.info(` ${re.bold("Linked at:")} ${re.dim(a)}`),ce(Dn("success","Authenticated"))}),iu.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=>{ue(`Starting development server for port ${e.port}...`);const t=await ms(),n="oauth"===t.type?`${t.auth.context.orgName}-${t.auth.context.projectName}`.toLowerCase().replace(/[^a-z0-9-]/g,""):`project-${t.auth.projectId}`.toLowerCase(),r=le();r.start("Starting development server...");const s=await Pe(`http://localhost:${e.port}`,{subdomain:n});r.stop(`Your local environment is available at: ]8;;${s.url}${re.underline(Dn("link",s.url))}]8;;`)}),iu.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").option("--browser <type>","Browser type: local or cloud (default: local)").action(async(e,t,n)=>{const r=e.length>0&&"test"===e[0]?e.slice(1):e;return fl({mode:"single",prompt:r,outputDir:t.output,cloudBrowser:au(n,t)})}).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").option("--browser <type>","Browser type: local or cloud (default: local)").action(async(e,t,n)=>fl({mode:"single",prompt:e,outputDir:t.output,cloudBrowser:au(n,t)})),iu.command("plan [prompt...]").description("Discover coverage gaps and generate test.fixme() plan files").action(async e=>fl({mode:"plan",prompt:e??[]})),iu.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").option("--browser <type>","Browser type: local or cloud (default: local)").action(async(e,t,n)=>{if(void 0!==t.maxBudget&&(!Number.isFinite(t.maxBudget)||t.maxBudget<=0))throw new Error("--max-budget must be a positive number");return fl({mode:"verify",prompt:e,url:t.url,maxBudgetUsd:t.maxBudget,interactive:t.interactive,cloudBrowser:au(n,t)})}),iu.command("internal-fix-run <runId>",{hidden:!0}).description("Internal: run fix session in subprocess").action(async e=>fl({mode:"fix",runId:e,cloudBrowser:"1"===process.env.STABLY_CLOUD_BROWSER})),iu.command("fix [runId]").description("Fix failing tests from a run (auto-detects from last test run or CI)").option("--browser <type>","Browser type: local or cloud (default: local)").action(async(e,t,n)=>{const r=Boolean(process.env.STABLY_CLI_VISUAL_MOCK);au(n,t)&&(process.env.STABLY_CLOUD_BROWSER="1"),r||function(e){try{return h("git rev-parse --is-inside-work-tree",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}}(process.cwd())||(cs.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 s=await(async e=>{const t=e=>e.replace(/\//g,"_");if(e)return cs.debug("Run ID provided explicitly",{runId:e}),t(e);const n=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 n of Object.keys(An))if(An[n].detect({env:e,cwd:t}))return{isCi:!0,...An[n].configuration({env:e,cwd:t})};return{isCi:Boolean(e.CI),...ln({env:e,cwd:t})}})();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),n=[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 n.length>0?n.join("-"):void 0}();if(n)return cs.debug("Run ID detected from CI environment",{runId:n}),t(n);cs.debug("No explicit run ID or CI environment detected, checking last-run.json");const r=await gl();if(r){const e=(Date.now()-r.timestamp)/36e5;return cs.debug("Run ID found in last-run.json",{runId:r.runId,timestamp:r.timestamp,filePath:r.filePath,ageHours:Math.round(e)}),e>24&&cs.warn(`Using run ID from ${Math.round(e)} hours ago (${r.filePath}). Provide an explicit run ID if this is not the run you want to fix.`),t(r.runId)}cs.debug("No run ID found in last-run.json")})(e)??(r?"visual-mock-run":void 0);if(s||(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)),r)return fl({mode:"fix",runId:s,cloudBrowser:"1"===process.env.STABLY_CLOUD_BROWSER});const o=await(async e=>{const t=await ms(),n=bs(t),r=ys(t),[,s]=process.argv;if(!s)throw new Error("Unable to determine CLI entrypoint for fix subprocess.");return await(async({runId:e,cliEntry:t,stablyApiKey:n,stablyProjectId:r,baseEnv:s=process.env,cwd:o=process.cwd(),execPath:i=process.execPath,execArgv:a=process.execArgv,stdio:c="inherit",spawnImpl:l=({command:e,args:t,options:n})=>g(e,t,n)})=>{const u=(({baseEnv:e,stablyApiKey:t,stablyProjectId:n,playwrightSession:r})=>{const s={...e};for(const e of Object.keys(s))ru(e)&&delete s[e];return{...s,STABLY_API_KEY:t,STABLY_PROJECT_ID:n,...r?{STABLY_PLAYWRIGHT_SESSION:r}:{}}})({baseEnv:s,stablyApiKey:n,stablyProjectId:r});return await new Promise((n,r)=>{const s=l({args:[...a,t,"internal-fix-run",e],command:i,options:{cwd:o,stdio:c,env:u}});s.once("error",r),s.once("exit",(e,t)=>{n(t?1:e??1)})})})({cliEntry:s,runId:e,stablyApiKey:n,stablyProjectId:r,cwd:process.cwd(),stdio:"inherit"})})(s);0!==o&&process.exit(o)}),iu.command("init").description("Initialize Playwright and Stably SDK in your project").action(async()=>fl({mode:"init"})),iu.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 n;Ql(Dn("info","Checking for updates...\n"));try{n=await async function(){const e=await async function(){const e=new AbortController,t=setTimeout(()=>e.abort(),1e4);t.unref();try{const t=await fetch(Wl,{signal:e.signal});if(!t.ok)throw new Error(`Failed to fetch latest version: ${t.statusText}`);return eu.parse(await t.json()).version}finally{clearTimeout(t)}}();return{current:dr,latest:e,isOutdated:Yl(dr,e)}}()}catch(e){return Zl(Dn("error","Failed to check for updates:"),e instanceof Error?e.message:e),void(process.exitCode=1)}if(Ql(`Current version: ${Dn("warning",n.current)}`),Ql(`Latest version: ${Dn("success",n.latest)}`),Ql(),!n.isOutdated)return void Ql(Dn("success","β You are already on the latest version!"));if(Ql(Dn("warning",`β A new version is available: ${n.current} β ${n.latest}`)),Ql(),t)return Ql(re.dim("Exiting with code 1 to indicate update available (useful for CI).")),void(process.exitCode=1);const r=function(){const e=process.argv[1]||"";if(e.includes("_npx")||e.includes(".npm/_cacache")||e.includes(".npm\\_cacache"))return"npx";try{const t=h("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=h("pnpm root -g",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-pnpm"}catch{}try{const t=h("yarn global dir",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-yarn-classic"}catch{}try{const t=h("yarn config get globalFolder",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-yarn-berry"}catch{}return"unknown"}(),s=function(e){switch(e){case"global-npm":case"global-yarn-berry":case"unknown":return{command:"npm",args:["install","-g","--no-fund",`${Gl}@latest`],description:`npm install -g ${Gl}@latest`};case"global-pnpm":return{command:"pnpm",args:["add","-g",`${Gl}@latest`],description:`pnpm add -g ${Gl}@latest`};case"global-yarn-classic":return{command:"yarn",args:["global","add",`${Gl}@latest`],description:`yarn global add ${Gl}@latest`};case"npx":return{command:"npx",args:[`${Gl}@latest`],description:`npx ${Gl}@latest (always uses latest)`}}}(r);if("npx"===r)return Ql(re.dim("You are running via npx, which always fetches the latest version.")),void Ql(re.dim(`Simply run: ${re.white("npx stably")} to use the latest version.`));"unknown"===r?(Ql(Dn("warning","Could not detect installation method. Falling back to npm.")),Ql()):"global-yarn-berry"===r&&(Ql(Dn("warning","Yarn Berry does not support global packages. Falling back to npm.")),Ql()),Ql(`Upgrade command: ${Dn("info",s.description)}`),Ql(),Ql(Dn("info","Upgrading...")),Ql();try{await(o=s.command,i=s.args,new Promise((e,t)=>{const n=g(o,i,{stdio:"inherit",shell:"win32"===process.platform});n.on("close",n=>{0===n?e():t(new Error(`Upgrade command exited with code ${n}`))}),n.on("error",e=>{t(e)})})),function(){try{v.unlinkSync(ql)}catch{}}(),Ql(),Ql(Dn("success","β Upgrade complete!")),Ql(re.dim(`Run ${re.white("stably --version")} to verify.`))}catch(e){Zl(Dn("error","Upgrade failed:"),e instanceof Error?e.message:e),Ql(),Ql(re.dim("You can try manually running:")),Ql(Dn("info",` ${s.description}`)),process.exitCode=1}var o,i}(e));var pu=iu.command("env").description("Manage remote environments");pu.command("list").description("List available environments").action(async()=>{const e=await ms(),t=ys(e),n=bs(e);cs.debug("Listing environments",{projectId:t});const r=await(s={auth:n,client:vr(),path:{projectId:t}},(s.client??cr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/environments",...s}));var s;401!==r.response.status&&403!==r.response.status||(ce(Dn("error","Access denied.")),process.exit(1)),r.error&&(ce(Dn("error",`Failed to list environments: ${r.response.status}`)),process.exit(1));const{environments:o}=r.data;if(0!==o.length){process.stdout.write(`${re.bold("Environments")}\n\n`);for(const e of o){const t=e.isDefault?Dn("success"," (default)"):"",n=re.dim(` ${e.variableCount} variable${1!==e.variableCount?"s":""}`);process.stdout.write(` ${Dn("info",e.name)}${t}${n}\n`),e.description&&process.stdout.write(` ${re.dim(e.description)}\n`)}process.stdout.write("\n")}else process.stdout.write(re.dim("No environments found. Create one on your Stably dashboard.\n"))}),pu.command("inspect <name>").description("Show variable metadata (name, sensitive flag, updated timestamp)").action(e=>(async e=>{const t=await ms(),n=ys(t),r=bs(t);cs.debug("Inspecting environment",{name:e,projectId:n});const s=await(o={auth:r,client:vr(),path:{projectId:n,environmentName:e}},(o.client??cr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/environments/{environmentName}/inspect",...o}));var o;404===s.response.status&&(ce(Dn("error",`Environment "${e}" not found. Run ${re.bold("stably env list")} to see available environments.`)),process.exit(1)),401!==s.response.status&&403!==s.response.status||(ce(Dn("error","Access denied.")),process.exit(1)),s.error&&(ce(Dn("error",`Failed to inspect environment: ${s.response.status}`)),process.exit(1));const{variables:i}=s.data;if(0!==i.length){process.stdout.write(`${re.bold(e)} ${re.dim(`(${i.length} variable${1!==i.length?"s":""})`)}\n\n`);for(const e of i){const t=re.dim(` [updated ${El(e.updatedAt)}]`);e.sensitive?process.stdout.write(` ${Dn("info",e.name)} ${Dn("warning","[sensitive]")}${t}\n`):process.stdout.write(` ${Dn("info",e.name)}${t}\n`)}process.stdout.write("\n")}else process.stdout.write(re.dim(`Environment "${e}" has no variables.\n`))})(e));var fu=iu.command("analytics").description("View test health analytics");fu.command("flaky").description("Show most flaky tests ranked by flaky rate").option("--days <n>","Look-back window in days (1-90, default: 7)").option("-b, --branch <name>","Filter by branch name").option("-n, --limit <n>","Max rows returned (1-100, default: 10)").option("--json","Output as JSON").action(async e=>{const t=await ms(),n=ys(t),r=bs(t),s=Sl(t),o=Fl(e.days),i=Hl(e.limit);cs.debug("Listing flaky tests",{projectId:n,days:o,branch:e.branch,limit:i});const a=vr(),c=await a.get({url:"/internal/v1/cli/analytics/flaky",security:[{scheme:"bearer",type:"http"}],auth:r,headers:{...Ts(s)},query:{projectId:n,days:o,branchName:e.branch,limit:i}});xl(c,"list flaky tests");const l=c.data;e.json?process.stdout.write(Ml(l)):process.stdout.write(((e,t)=>{const n=[],r=e.filters.branch?`branch: ${e.filters.branch}`:"all branches";if(n.push(re.bold(`Most Flaky Tests (last ${e.period.days} days, ${r})`)),n.push(""),0===e.tests.length)return n.push(re.dim(" No flaky tests found.")),n.push(""),n.join("\n");const s=` ${Nl("REF",14)}${Nl("TEST",20)}${Nl("LOCATION",30)}${Nl("FLAKY",8)}${Nl("RUNS",7)}${Nl("RATE",9)}LAST FLAKY`;n.push(re.dim(s));for(const t of e.tests){const e=t.testRef,r=Ol(t.title,18),s=Ol(t.location,28),o=String(t.flakyCount),i=String(t.nonSkippedRuns),a=jl(t.flakyRate),c=Bl(t.lastFlakyAt);n.push(` ${Nl(e,14)}${Nl(r,20)}${Nl(s,30)}${Nl(o,8)}${Nl(i,7)}${Nl(a,9)}${c}`)}n.push("");const o=e.summary.totalNonSkippedRuns;return n.push(` ${e.summary.totalFlakyTests} flaky tests found across ${o} runs.`),n.push(` Dashboard: ${re.underline(Dn("link",`https://app.stably.ai/p/${t}/analytics`))}`),n.push(""),n.join("\n")})(l,n))}),fu.command("failures").description("Show most failing tests ranked by failure rate").option("--days <n>","Look-back window in days (1-90, default: 7)").option("-b, --branch <name>","Filter by branch name").option("-n, --limit <n>","Max rows returned (1-100, default: 10)").option("--json","Output as JSON").action(async e=>{const t=await ms(),n=ys(t),r=bs(t),s=Sl(t),o=Fl(e.days),i=Hl(e.limit);cs.debug("Listing failing tests",{projectId:n,days:o,branch:e.branch,limit:i});const a=vr(),c=await a.get({url:"/internal/v1/cli/analytics/failures",security:[{scheme:"bearer",type:"http"}],auth:r,headers:{...Ts(s)},query:{projectId:n,days:o,branchName:e.branch,limit:i}});xl(c,"list failing tests");const l=c.data;e.json?process.stdout.write(Ml(l)):process.stdout.write(((e,t)=>{const n=[],r=e.filters.branch?`branch: ${e.filters.branch}`:"all branches";if(n.push(re.bold(`Most Failed Tests (last ${e.period.days} days, ${r})`)),n.push(""),0===e.tests.length)return n.push(re.dim(" No failing tests found.")),n.push(""),n.join("\n");const s=` ${Nl("REF",14)}${Nl("TEST",20)}${Nl("LOCATION",30)}${Nl("FAILED",8)}${Nl("RUNS",7)}${Nl("RATE",9)}LAST FAILED`;n.push(re.dim(s));for(const t of e.tests){const e=t.testRef,r=Ol(t.title,18),s=Ol(t.location,28),o=String(t.failedCount),i=String(t.nonSkippedRuns),a=jl(t.failureRate),c=Bl(t.lastFailedAt);n.push(` ${Nl(e,14)}${Nl(r,20)}${Nl(s,30)}${Nl(o,8)}${Nl(i,7)}${Nl(a,9)}${c}`)}n.push("");const o=e.summary.totalNonSkippedRuns;return n.push(` ${e.summary.totalFailingTests} failing tests found across ${o} runs.`),n.push(` Dashboard: ${re.underline(Dn("link",`https://app.stably.ai/p/${t}/analytics`))}`),n.push(""),n.join("\n")})(l,n))});var hu=iu.command("runs").description("View test run history");hu.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 ms(),n=ys(t),r=bs(t),s=Sl(t);let o;e.limit&&(o=parseInt(e.limit,10),(Number.isNaN(o)||o<1||o>100)&&(ce(Dn("error","--limit must be an integer between 1 and 100")),process.exit(1)));const i=Ll(e.source,["LOCAL","CI","WEB"],"--source"),a=Ll(e.status,["QUEUED","RUNNING","PASSED","FAILED","TIMEDOUT","CANCELLED","INTERRUPTED"],"--status"),c=Ll(e.trigger,["MANUAL","SCHEDULED","UI","API","GITHUB_ACTION","SUITE_RUN"],"--trigger");cs.debug("Listing runs",{projectId:n,branch:e.branch,limit:o,after:e.after,before:e.before,source:i,status:a,suite:e.suite,trigger:c});const l=await lr({auth:r,client:vr(),headers:Ts(s),query:{projectId:n,branchName:e.branch,limit:o,afterRunId:e.after,beforeRunId:e.before,source:i,status:a,suiteName:e.suite,trigger:c}});xl(l,"list runs");const{runs:u,hasMore:d}=l.data;e.json?process.stdout.write($l(l.data)):process.stdout.write(((e,t)=>{if(0===e.length)return re.dim("No runs found matching the specified filters.\n");const n=Math.min(40,Math.max(10,...e.map(e=>e.runId.length))),r={runId:{w:n+2,t:n},status:{w:14},branch:{w:32,t:30},started:{w:18}},s=[],o=`${Ul("Run ID",r.runId.w)}${Ul("Status",r.status.w)}${Ul("Branch",r.branch.w)}${Ul("Started",r.started.w)}Tests`;s.push(re.bold(o));for(const t of e){const e=kl(t.runId,r.runId.t),n=Pl(t.status),o=kl(t.branchName,r.branch.t),i=Cl(t.startedAt),a=t.totalCount.toString();s.push(`${Ul(e,r.runId.w)}${Ul(n,r.status.w)}${Ul(o,r.branch.w)}${Ul(i,r.started.w)}${a}`)}if(t&&e.length>0){const t=e.at(-1)?.runId;t&&(s.push(""),s.push(re.dim(`Next page: stably runs list --before ${t}`)))}return s.push(""),s.join("\n")})(u,d))}),hu.command("view <runId>").description("Show details for a specific run").option("--json","Output as JSON").action(async(e,t)=>{const n=await ms(),r=bs(n),s=Sl(n);cs.debug("Viewing run",{runId:e});const o=await ur({auth:r,client:vr(),headers:Ts(s),path:{runId:e},query:{detail:"full"}});if(xl(o,"get run details",`Run "${e}" not found.`),t.json)process.stdout.write($l(o.data));else{const e=o.data;process.stdout.write((e=>{const t=[];if(t.push(re.bold(`Run ${e.runId}`)),t.push(` ${re.dim("Status:")} ${Pl(e.status)}`),e.branchName&&t.push(` ${re.dim("Branch:")} ${e.branchName}`),e.commitSha&&t.push(` ${re.dim("Commit:")} ${e.commitSha.slice(0,7)}`),e.startedAt&&t.push(` ${re.dim("Started:")} ${Cl(e.startedAt)}`),null!==e.durationMs&&t.push(` ${re.dim("Duration:")} ${(e=>{if(null===e)return"-";const t=Math.floor(e/1e3);if(t<60)return`${t}s`;const n=Math.floor(t/60);return n<60?`${n}m ${t%60}s`:`${Math.floor(n/60)}h ${n%60}m`})(e.durationMs)}`),e.source&&t.push(` ${re.dim("Source:")} ${e.source.toLowerCase()}`),e.projectId){const n=`https://app.stably.ai/project/${e.projectId}/playwright/history/${e.runId}`;t.push(` ${re.dim("URL:")} ${re.underline(Dn("link",n))}`)}t.push("");const n=[];e.passedCount>0&&n.push(Dn("success",`${e.passedCount} passed`)),e.failedCount>0&&n.push(Dn("error",`${e.failedCount} failed`)),e.flakyCount>0&&n.push(Dn("warning",`${e.flakyCount} flaky`)),e.timedoutCount>0&&n.push(Dn("error",`${e.timedoutCount} timedout`)),e.skippedCount>0&&n.push(Dn("muted",`${e.skippedCount} skipped`)),e.interruptedCount>0&&n.push(Dn("warning",`${e.interruptedCount} interrupted`)),t.push(`${re.bold("Test Results:")} ${n.join(", ")}`);const r=e.testCases.filter(e=>"FAILED"===e.status||"TIMEDOUT"===e.status||"INTERRUPTED"===e.status||"FLAKY"===e.status);if(r.length>0){t.push(""),t.push(re.bold("Failed/Flaky Tests:"));for(const e of r){const n=e.status??"UNKNOWN",r=Al[n]??(e=>e),s=e.location??"",o=e.title??e.testIdentifier,{attempts:i}=e,a=i?.length??0,c=a>1?` (${a} attempts)`:"",l=s?`${s} - `:"";t.push(` ${r(n)} ${l}${o}${re.dim(c)}`);const u=i?.at(-1);if(u?.errorMessage){const e=u.errorMessage.split("\n")[0]?.slice(0,100)??"";t.push(` ${re.dim(e)}`)}}}return t.push(""),t.join("\n")})(e))}}),iu.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)}),vl.forEach(({args:e,description:t,name:n})=>{iu.command(n).description(t).helpOption(!1).helpCommand(!1).allowUnknownOption(!0).allowExcessArguments(!0).passThroughOptions().action(()=>_l({overrideArgs:e,subcommand:n}))});var gu=()=>{0!==cu.length&&(process.stderr.write(cu.join("")),cu=[])};(async()=>{await(async()=>{if(!tu&&"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":dr,"node.version":process.version,"os.platform":process.platform}}),tu=!0}catch{}})();try{await iu.parseAsync(process.argv),cs.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 cs.error(t,{stack:e instanceof Error?e.stack:void 0}),gu(),cs.flush(),cs.printLogFileInfo(),await nu(),void(process.exitCode=1)}const t="number"==typeof e.exitCode?e.exitCode:1,n=process.argv.slice(2).find(e=>!e.startsWith("-")),r=!!n&&!!uu(iu,[n]);if(("commander.excessArguments"===e.code||"commander.unknownCommand"===e.code)&&n&&!r)return cu=[],cs.warn("Unknown command",{command:n}),process.stderr.write(`command '${n}' not found\n`),du(),void(process.exitCode=t);cs.debug("Commander error",{code:e.code,exitCode:t}),gu(),process.exitCode=t}finally{cs.flush(),await nu()}})();
|