stably 4.12.13 β 4.12.14-rc.0
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 +1 -1
- package/dist/node_modules/playwright/lib/cli/daemon/program.js +14 -0
- package/dist/node_modules/playwright/lib/mcp/browser/config.js.rej +11 -0
- package/dist/node_modules/playwright/lib/mcp/browser/sessionLog.js +34 -0
- package/dist/stably-browser.js +156 -29
- package/package.json +2 -2
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 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,{existsSync as I,statSync as T,readFileSync as _,appendFileSync as E,realpathSync as S,createReadStream as x,mkdirSync as A,writeFileSync as k,rmSync 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 Y}from"@anthropic-ai/claude-agent-sdk";import{match as V}from"ts-pattern";import z from"net";import{createInterface as K}from"readline/promises";import q from"picocolors";import{simpleGit as J}from"simple-git";import Q,{randomUUID as X}from"crypto";import{readFile as Z,rm as ee,mkdir as te,writeFile as ne,unlink as re,access as se,readdir as oe,stat as ie,appendFile as ae}from"fs/promises";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 Ce}from"module";import{parseDocument as Pe}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 n=r.resolve(process.cwd(),t),s=e({path:n,override:!0,quiet:!0});if(s.error){const e=`warning: could not load env file: ${n} (${s.error.message})`;$e.envFileErrors.push(e),process.stderr.write(`${e}\n`)}else $e.envFilesLoaded.push(n)}var Be={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 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,n=Boolean(t);return{name:"Azure Pipelines",service:"azurePipelines",commit:e.BUILD_SOURCEVERSION,build:e.BUILD_BUILDNUMBER,branch:Me(n?e.SYSTEM_PULLREQUEST_TARGETBRANCH:e.BUILD_SOURCEBRANCH),pr:t,isPr:n,prBranch:Me(n?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,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}}},Ye={detect:({env:e})=>Boolean(e.BUDDY_WORKSPACE_ID),configuration({env:e}){const t=je(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 ze(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ke,qe,Je,Qe,Xe,Ze,et,tt,nt={exports:{}};var rt,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=r,t=function(){if(ot)return st;ot=1;const e=r,t=function(){if(tt)return et;tt=1;const e="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,t=r,n=e?";":":",s=function(){if(Ze)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 Ze=1,e="win32"===process.platform||Ve.TESTING_WINDOWS?function(){if(qe)return Ke;qe=1,Ke=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 Ke}():function(){if(Qe)return Je;Qe=1,Je=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 Je}(),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 et=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)},et}(),n=function(){if(rt)return bt.exports;rt=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(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 st=function(e){return s(e)||s(e,!0)}}(),n=function(){if(it)return wt;it=1;const e=/([()\][%!^"`<>&|;, *?])/g;return wt.command=function(t){return t.replace(e,"^$1")},wt.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},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 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 dt=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 ft=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 It=ze(function(){if(yt)return nt.exports;yt=1;const e=p,t=vt(),n=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 n(n,r){return e&&1===n&&!r.file?t(r.original,"spawn"):null}return gt={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},gt}();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 nt.exports=r,nt.exports.spawn=r,nt.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},nt.exports._parse=t,nt.exports._enoent=n,nt.exports}());function Tt(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 _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: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}},kt=({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}],Ct=(()=>{const e=xt();return Object.fromEntries(e.map(kt))})();(()=>{const e=xt(),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 Pt=({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:Ct[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},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 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}},Mt=class{},Ft=globalThis.process;Dt(Ft)?new class extends Mt{#e="win32"===Ft.platform?"SIGINT":"SIGHUP";#t=new jt;#n;#r;#s;#o={};#i=!1;constructor(e){super(),this.#n=e,this.#o={};for(const t of Ut)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(!Dt(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 Ut)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,Ut.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 Dt(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&&Dt(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)}}(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=[],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 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.-]+$/,Yt=j("execa").enabled,Vt=(e,t)=>String(e).padStart(t,"0"),zt=(e,t,n={})=>{const s=It._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:Yt,...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=Tt({env:e={...e}});return t.path=e[n],e[n]=(({cwd:e=b.cwd(),path:t=b.env[Tt()],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 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 n=Math.max(t.length,Rt.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}},Kt=(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=zt(e,t,n),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`${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),_(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 Pt({error:e,stdout:"",stderr:"",all:"",command:s,escapedCommand:o,parsed:r,timedOut:!1,isCanceled:!1,killed:!1})}const c=Kt(r.options,a.stdout,a.error),l=Kt(r.options,a.stderr,a.error);if(a.error||0!==a.status||null!==a.signal){const e=Pt({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 Jt(e){try{return qt("git",["rev-parse","HEAD"],e).stdout}catch{return}}function Qt(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$/,Zt=/^\/(.*)\.git$/;function en(e){if(e){if(e.match(Xt))return e.replace(Xt,"$1");try{return new URL(e).pathname.replace(Zt,"$1")}catch{return}}}var tn,nn={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:en(e.BUILDKITE_REPO),pr:t,isPr:n,prBranch:n?e.BUILDKITE_BRANCH:void 0,root:e.BUILDKITE_BUILD_CHECKOUT_PATH}}},rn={detect:({env:e})=>Boolean(e.CIRCLECI),configuration({env:e}){const t=e.CIRCLE_PR_NUMBER||je(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}`}}},sn="https://cirrus-ci.com",on={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:`${sn}/build/${e.CIRRUS_BUILD_ID}`,job:e.CIRRUS_TASK_ID,jobUrl:`${sn}/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}}},an={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})},cn={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}}},ln={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}}},un=({env:e})=>{try{const t=e.GITHUB_EVENT_PATH?JSON.parse(_(e.GITHUB_EVENT_PATH,"utf-8")):void 0;if(t&&t.pull_request)return{branch:t.pull_request.base?Me(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=Me("pull_request_target"===e.GITHUB_EVENT_NAME?`refs/pull/${(e=>{const t=e.GITHUB_EVENT_PATH?JSON.parse(_(e.GITHUB_EVENT_PATH,"utf-8")):void 0;return t&&t.pull_request?t.pull_request.number:void 0})(e)}/merge`:e.GITHUB_REF);return{name:"GitHub Actions",service:"github",commit:e.GITHUB_SHA,build:e.GITHUB_RUN_ID,buildUrl:`${e.GITHUB_SERVER_URL}/${e.GITHUB_REPOSITORY}/actions/runs/${e.GITHUB_RUN_ID}`,isPr: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||Jt({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||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||(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(tn)return In;tn=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=ze(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?Qt({env:e,cwd:t}):void 0)]))},An={appveyor:Be,azurePipelines:Fe,bamboo:He,bitbucket:Ge,bitrise:We,buddy:Ye,buildkite:nn,circleci:rn,cirrus:on,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:an,codefresh:cn,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:ln,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:Me(e.JB_SPACE_GIT_BRANCH),slug:t&&n?`${t.toLowerCase()}/${n}`:void 0}}}},kn=class e{git;config;snapshotTreeHash;snapshotIndexPath;constructor(e){this.config=e,this.git=J({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-${X()}.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-${X()}.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 Cn(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 Cn(this.snapshotIndexPath),this.snapshotIndexPath=void 0),this.snapshotTreeHash=void 0}};async function Cn(e){try{await re(e)}catch{}}var Pn="x-stably-org-id",Rn={bodySerializer:e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t)},Un=({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):$n({allowReserved:e,name:n,value:t})).join(o);return"label"===r||"matrix"===r?o+i:i},$n=({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)}`},Ln=({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])=>$n({allowReserved:e,name:"deepObject"===r?`${n}[${t}]`:t,value:s})).join(i);return"label"===r||"matrix"===r?i+a:a},Dn=/\{[^{}]+\}/g;function Nn(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 On,Bn=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},jn=({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=Un({allowReserved:i.allowReserved,explode:!0,name:s,style:"form",value:o,...i.array});e&&r.push(e)}else if("object"==typeof o){const e=Ln({allowReserved:i.allowReserved,explode:!0,name:s,style:"deepObject",value:o,...i.object});e&&r.push(e)}else{const e=$n({allowReserved:i.allowReserved,name:s,value:o});e&&r.push(e)}}return r.join("&")},Mn=(e,t)=>!!t&&!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`)),Fn=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(Dn);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,Un({explode:r,name:s,style:o,value:i}));continue}if("object"==typeof i){n=n.replace(t,Ln({explode:r,name:s,style:o,value:i,valueOnly:!0}));continue}if("matrix"===o){n=n.replace(t,`;${$n({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:jn(e.querySerializer),url:e.url}),Hn=(e,t)=>{const n={...e,...t};return n.baseUrl?.endsWith("/")&&(n.baseUrl=n.baseUrl.substring(0,n.baseUrl.length-1)),n.headers=Wn(e.headers,t.headers),n},Gn=e=>{const t=[];return e.forEach((e,n)=>{t.push([n,e])}),t},Wn=(...e)=>{const t=new Headers;for(const n of e){if(!n)continue;const e=n instanceof Headers?Gn(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},Yn=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}},Vn=jn({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),zn={"Content-Type":"application/json"},Kn=(e={})=>({...Rn,headers:zn,parseAs:"auto",querySerializer:Vn,...e}),qn=(e={})=>{let t=Hn(Kn(),e);const n=()=>({...t}),r={error:new Yn,request:new Yn,response:new Yn},s=async e=>{const n={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:Wn(t.headers,e.headers),serializedBody:void 0};return n.security&&await(async({security:e,...t})=>{for(const n of e){if(Mn(t,n.name))continue;const e=await Bn(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:Fn(n)}},o=async e=>{const{opts:t,url:n}=await s(e),o={redirect:"follow",...t,body:Nn(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:Fn,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=Hn(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")}},Jn=qn(Kn({baseUrl:"https://api.stably.ai"})),Qn=e=>(e.client??Jn).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs",...e}),Xn=e=>(e.client??Jn).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}",...e}),Zn="4.12.13",er=process.env.STABLY_API_URL||"https://api.stably.ai",tr=e=>{const t=new URL(e);return t.protocol="http:"===t.protocol?"ws:":"wss:",t},nr=process.env.AUTH_URL||"https://auth.stably.ai",rr=process.env.AUTH_CLIENT_ID||"288007877071cce81f269428ea78653a",sr=process.env.AI_PROXY_URL||"https://ai-proxy.stably.ai",or=process.env.STABLY_AUTOHEAL_WS_URL||new URL("/autoheal",tr(er)).toString(),ir=process.env.STABLY_CREATE_PROGRESS_WS_URL||new URL("/create-progress",tr(er)).toString(),ar="http://localhost:9876/auth/callback",cr=()=>On||(On=qn(Kn({baseUrl:er,headers:{"X-STABLY-CLI-VERSION":Zn,"X-STABLY-SOURCE":"cli"}}))),lr=async(e,t)=>{const n=await(r={body:{accessToken:e,orgId:t},client:cr()},(r.client??Jn).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},ur=ge.object({org_id:ge.string(),org_name:ge.string()}),dr=ge.object({email:ge.string(),org_id_to_org_member_info:ge.record(ge.string(),ur).optional(),org_member_info:ur.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 pr,fr=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)},hr=e=>{try{const t=dr.parse(fr(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"}`)}},gr=async(e,t)=>{let n=e;const{root:s}=r.parse(n);for(;n!==s;){const e=r.join(n,t);try{return await se(e),e}catch{n=r.dirname(n)}}},mr=r.join(D.homedir(),".stably"),yr=r.join(mr,"auth.json"),br=".stably",wr="project.json",vr=he.object({accessToken:he.string(),expiresAt:he.number(),idToken:he.string().optional(),refreshToken:he.string()}),Ir=he.object({orgId:he.string(),orgName:he.string(),projectId:he.string(),projectName:he.string()}),Tr=async()=>{try{const e=await Z(yr,"utf-8");return vr.parse(JSON.parse(e))}catch{return}},_r=async e=>{await te(mr,{recursive:!0}),await ne(yr,JSON.stringify(e,null,2),{mode:384})},Er=async()=>{try{await re(yr)}catch{}},Sr=async()=>{try{const e=await gr(process.cwd(),br);if(!e)return;const t=r.join(e,wr),n=await Z(t,"utf-8");return Ir.parse(JSON.parse(n))}catch{return}},xr=async()=>{try{const e=await gr(process.cwd(),br);e&&await re(r.join(e,wr))}catch{}},Ar=e=>Date.now()>=e.expiresAt-3e5,kr=async e=>{const t=new URLSearchParams({client_id:rr,grant_type:"refresh_token",refresh_token:e}),n=await fetch(`${nr}/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}},Cr=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`,Pr=(e,t,n)=>{e.writeHead(t,{"Content-Type":"text/html"}),e.end(n)},Rr=(e,t)=>{const n=new URLSearchParams({client_id:rr,code_challenge:e,code_challenge_method:"S256",redirect_uri:ar,response_type:"code",state:t});return`${nr}/propelauth/oauth/authorize?${n.toString()}`},Ur=async e=>{const t=ue();let n;t.start("Loading user info...");try{n=hr(e.accessToken),t.stop(q.green(`β Logged in as ${q.cyan(n.email)}`))}catch(e){t.stop(q.red("β Failed to load user info"));const n=e instanceof Error?e.message:"Unknown error";return ce.error(n),{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: ${q.cyan(e[0].name)}`),e[0];if(!process.stdin.isTTY)return ce.info(`Auto-selecting organization: ${q.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)})(n.organizations);if(!s)return ce.warn("Organization selection cancelled."),{success:!1};let o;t.start("Getting org credentials...");try{const n=await lr(e.accessToken,s.id);o={accessToken:n.accessToken,expiresAt:Date.now()+1e3*n.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken},t.stop(q.green("β Credentials obtained"))}catch(e){t.stop(q.red("β Failed to get org credentials"));const n=e instanceof Error?e.message:"Unknown error";return ce.error(n),{success:!1}}const i=await(async(e,t)=>{const n=ue();let r;n.start("Loading projects...");try{r=await(async({accessToken:e,orgId:t})=>{const n=await(r={auth:e,client:cr(),path:{orgId:t}},(r.client??Jn).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(q.green("β Projects loaded"))}catch(e){n.stop(q.red("β Failed to load projects"));const t=e instanceof Error?e.message:"Unknown error";return void ce.error(t)}if(0===r.length)return ce.error("No projects found in this organization."),void ce.info(`Create a project at ${q.underline(q.cyan("https://app.stably.ai"))}`);if(1===r.length)return ce.info(`Using project: ${q.cyan(r[0].name)}`),r[0];if(!process.stdin.isTTY)return ce.info(`Auto-selecting project: ${q.cyan(r[0].name)}`),r[0];const s=await pe({message:"Select a project",options:r.map(e=>({label:e.name,value:e.id}))});return fe(s)?void 0:r.find(e=>e.id===s)})(o.accessToken,s.id);return i?(await(async e=>{const t=r.join(process.cwd(),br),n=r.join(t,wr);await te(t,{recursive:!0}),await ne(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 ne(t,r)}else if(o.test(e)){const r=e.replace(o,`\n${n}\n`);await ne(t,r)}else await ae(t,`\n${n}\n`)}catch{await ne(t,`${n}\n`)}})(process.cwd())})({orgId:s.id,orgName:s.name,projectId:i.id,projectName:i.name}),ce.info(q.dim("Linked this directory to your Stably project.")),{scopedTokens:o,success:!0}):(ce.warn("Project selection cancelled."),{success:!1})},$r=async()=>{if(ns())return ce.warn(`Environment variables ${q.cyan("STABLY_API_KEY")} and ${q.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(q.yellow("Login skipped - using environment variable authentication."));const e=await Tr();if(e){if(!Ar(e)){if(await Sr())return void le(q.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 Ur(e);return void(t.success?(await _r(t.scopedTokens),le(q.green("Setup complete! You can now use Stably CLI."))):le(q.yellow("Setup incomplete. Run `stably login` to try again.")))}const t=ue();t.start("Refreshing session...");try{const n=await kr(e.refreshToken);t.stop(q.green("β Session refreshed"));const r=await Sr();if(r){t.start("Getting org credentials...");try{const e=await lr(n.accessToken,r.orgId),s={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:n.idToken,refreshToken:n.refreshToken};await _r(s),t.stop(q.green("β Credentials obtained")),le(q.green("Login successful"))}catch{await _r(n),t.stop(q.yellow("Using full credentials")),le(q.green("Login successful"))}}else{const e=await Ur(n);e.success?(await _r(e.scopedTokens),le(q.green("Setup complete! You can now use Stably CLI."))):le(q.yellow("Setup incomplete. Run `stably login` to try again."))}return}catch{t.stop(q.yellow("Session expired, proceeding with fresh login...")),await Er(),await xr()}}const{authorizeUrl:t,serverReady:n,waitForCallback:r}=(()=>{const{authorizeUrl:e,codeVerifier:t,state:n}=(()=>{const e=Q.randomBytes(32).toString("base64url"),t=(n=e,Q.createHash("sha256").update(n).digest("base64url"));var n;const r=Q.randomBytes(16).toString("base64url");return{authorizeUrl:Rr(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=ye.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?(Pr(n,400,Cr(l)),i(),a.close(),void r({error:l,success:!1})):o&&c?c!==e?(Pr(n,400,Cr("Invalid state parameter (possible CSRF attack)")),i(),a.close(),void r({error:"State mismatch",success:!1})):(Pr(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})):(Pr(n,400,Cr("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:rr,code:e,code_verifier:t,grant_type:"authorization_code",redirect_uri:ar}),r=await fetch(`${nr}/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,ce.info("Opening browser for authentication..."),ce.info(q.dim("If browser doesn't open, visit:")),ce.info(`]8;;${t}${q.underline(q.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 r(),s.stop(q.green("β Authentication successful"))}catch(e){s.stop(q.red("β Authentication failed"));const t=e instanceof Error?e.message:"Unknown error";le(q.red(`Login failed: ${t}`)),process.exit(1)}const i=await Ur(o);i.success?(await _r(i.scopedTokens),le(q.green("Setup complete! You can now use Stably CLI."))):(le(q.yellow("Setup incomplete. Run `stably login` to try again.")),process.exit(1))},Lr={fatal:60,error:50,warn:40,info:30,debug:20,trace:10},Dr=new Set(["help","login","logout","whoami","tunnel","create","fix","init","upgrade","test","show-report","codegen"]),Nr=(new Date).toISOString().split("T")[0],Or=(()=>{const e=[r.join(D.tmpdir(),"stably-logs",Nr),r.join(D.homedir(),".stably","logs",Nr)];for(const t of e)try{return v.mkdirSync(t,{recursive:!0}),t}catch{}return null})(),Br=process.argv.includes("--verbose")||process.argv.includes("-v"),jr=process.env.STABLY_LOG_LEVEL?.toLowerCase(),Mr=Br?"debug":void 0!==(pr=jr)&&pr in Lr?jr:"warn",Fr=Lr[Mr],Hr=null,Gr=null,Wr=null,Yr=[],Vr=!1,zr=e=>{if(!Vr){if(!(Hr=(e=>{if(!Or)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(Or,`${t}-${n}.log`)})(e)))return Yr=[],void(Vr=!0);(e=>{const t=["","=".repeat(60),"Stably CLI Debug Log",`Version: ${Zn}`,`Generated: ${(new Date).toISOString()}`,`Node: ${process.version}`,`Platform: ${process.platform} ${D.release()}`,`CWD: ${process.cwd()}`,`Args: ${process.argv.slice(2).join(" ")}`,`Log Level (console): ${Mr}`,"=".repeat(60),""].join("\n");e.write(t)})(Gr=new we({dest:Hr,minLength:4096,sync:!1,append:!0})),Wr=be({level:"debug",timestamp:be.stdTimeFunctions.isoTime,base:{version:Zn}},Gr);for(const{level:e,msg:t,context:n}of Yr)n?Wr[e](n,t):Wr[e](t);Yr=[],Vr=!0,Br&&process.stderr.write(`${q.dim(`Debug log: ${Hr}`)}\n\n`)}},Kr=(()=>{const e=process.argv.slice(2).find(e=>!e.startsWith("-"));return e&&Dr.has(e)?e:null})();Kr&&zr(Kr);var qr=e=>(t,n)=>{if(Wr?n?Wr[e](n,t):Wr[e](t):Vr||Yr.push({level:e,msg:t,context:n}),(e=>Lr[e]>=Fr)(e)){const n=((e,t)=>`${{fatal:q.bgRed(q.white(" FATAL ")),error:q.red("error"),warn:q.yellow("warn"),info:q.cyan("info"),debug:q.dim("debug"),trace:q.dim("trace")}[e]} ${t}`)(e,t);process.stderr.write(`${n}\n`)}},Jr={fatal:qr("fatal"),error:qr("error"),warn:qr("warn"),info:qr("info"),debug:qr("debug"),trace:qr("trace"),initSession:e=>{Vr||zr(e)},getLogFilePath:()=>Hr,flush:()=>{if(Gr)try{Gr.flushSync()}catch{}},printLogFileInfo:()=>{Hr&&(process.stderr.write(`\n${q.dim("Debug log written to:")}\n`),process.stderr.write(` ${q.cyan(Hr)}\n`),process.stderr.write(`${q.dim("Share this file with support for assistance.")}\n`))},getPinoLogger:()=>Wr};setInterval(()=>{Jr.flush()},3e4).unref(),process.on("beforeExit",()=>{Jr.flush()});var Qr=e=>{const t=()=>{Jr.flush(),Br&&Jr.printLogFileInfo(),process.removeListener(e,t),process.kill(process.pid,e)};return t};process.on("SIGINT",Qr("SIGINT")),process.on("SIGTERM",Qr("SIGTERM"));var Xr=()=>"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",Zr=()=>"local"!==Xr(),es=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"}},ts=()=>{const e=Xr();return[`Authentication failed. In CI, add the following to your ${es(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")},ns=()=>{const e=process.env.STABLY_API_KEY?.trim(),t=process.env.STABLY_PROJECT_ID?.trim();if(e&&t)return Jr.debug("Environment auth detected",{hasApiKey:!0,hasProjectId:!0}),{apiKey:e,projectId:t};Jr.debug("Environment auth not set",{hasApiKey:!!e,hasProjectId:!!t})},rs=async()=>{Jr.debug("Checking for stored auth tokens");const e=await Tr();if(!e)return void Jr.debug("No stored auth tokens found");const t=Ar(e);if(Jr.debug("Auth tokens status",{expired:t}),!t){const t=await Sr(),n=(e=>{try{const t=dr.parse(fr(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(Jr.debug("Token scope check",{scope:n,hasContext:!!t}),t&&"full"===n)try{Jr.debug("Exchanging full token for org-scoped token",{orgId:t.orgId});const n=await lr(e.accessToken,t.orgId),r={accessToken:n.accessToken,expiresAt:Date.now()+1e3*n.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken};return await _r(r),Jr.debug("Token exchange successful"),r}catch(t){return Jr.debug("Token exchange failed, using existing token",{error:t instanceof Error?t.message:String(t)}),e}return e}try{Jr.debug("Attempting token refresh");const t=await kr(e.refreshToken);Jr.debug("Token refresh successful");const n=await Sr();if(n)try{Jr.debug("Exchanging refreshed token for org-scoped token");const e=await lr(t.accessToken,n.orgId),r={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:t.idToken,refreshToken:t.refreshToken};return await _r(r),r}catch{return await _r(t),t}return await _r(t),t}catch(e){return void Jr.warn("Token refresh failed",{error:e instanceof Error?e.message:String(e)})}},ss=async(e={})=>{Jr.debug("Requiring authentication",{autoLogin:e.autoLogin});const t=ns();if(t)return Jr.info("Using environment variable authentication"),{auth:t,type:"env"};let n=await rs(),r=n?await Sr():void 0;const s=process.stdin.isTTY&&process.stdout.isTTY;if(Jr.debug("OAuth auth check",{hasTokens:!!n,hasContext:!!r,canPrompt:s}),(!n||!r)&&e.autoLogin&&s){Jr.info("Prompting user to login"),n?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(`${q.dim("Alternatively, set environment variables for an org API key:")}\n${q.dim(" STABLY_API_KEY=... STABLY_PROJECT_ID=... stably")}\n`),process.stdout.write("\n");const e=K({input:process.stdin,output:process.stdout});try{await e.question(q.dim("Press Enter to continue... "))}finally{e.close()}await $r(),n=await rs(),r=n?await Sr():void 0}return n||(Jr.warn("Authentication required but no tokens available"),Zr()?le(q.red(ts())):le(q.red("You are not logged in. Run `stably login` to authenticate.")),process.exit(1)),r||(Jr.warn("Authentication succeeded but no project context selected"),Zr()?le(q.red(ts())):le(q.red("You haven't selected an organization and project. Run `stably login` to complete setup.")),process.exit(1)),Jr.info("OAuth authentication successful",{orgId:r.orgId,projectId:r.projectId}),{auth:{accessToken:n.accessToken,context:r},type:"oauth"}},os=e=>"env"===e.type?e.auth.projectId:e.auth.context.projectId,is=e=>"env"===e.type?e.auth.apiKey:e.auth.accessToken,as=async()=>{const e=$e.remoteEnvName;if(!e)return;const t=await ss(),n=os(t),r=is(t);Jr.debug("Fetching remote environment variables",{envName:e,projectId:n});const s=await(o={auth:r,client:cr(),path:{projectId:n,environment:e}},(o.client??Jn).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/environments/{environment}/variables",...o}));var o;404===s.response.status&&(le(q.red(`Environment "${e}" not found. Check the name on your Stably dashboard.`)),process.exit(1)),401!==s.response.status&&403!==s.response.status||(le(q.red(`Access denied to environment "${e}".`)),process.exit(1)),s.error&&(le(q.red(`Failed to fetch environment "${e}": ${s.response.status}`)),process.exit(1));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(`${q.cyan(`Loaded ${c} variable${1!==c?"s":""} from "${e}"`)}${l>0?q.dim(` (${l} sensitive)`):""}\n`),{variables:i,sensitiveValues:a}},cs=e=>e?{[Pn]:e}:void 0,ls=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()}),us=ve.object({bucket:ve.string(),key:ve.string()}),ds=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})`)},ps=ve.object({diffBucketPath:us,expiresInSeconds:ve.number(),key:ve.string(),uploadUrl:ve.string()}),fs=ve.object({traceBucketPath:us,expiresInSeconds:ve.number(),key:ve.string(),uploadUrl:ve.string(),sensitiveValues:ve.array(ve.string())}),hs=async({authHeader:e,contentType:t="text/plain",orgId:n,runId:r})=>{const s=await(o={auth:e,body:{contentType:t},client:cr(),headers:cs(n),path:{runId:r}},(o.client??Jn).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=ps.parse(s.data);return{diffBucketPath:i.diffBucketPath,expiresInSeconds:i.expiresInSeconds,key:i.key,uploadUrl:i.uploadUrl}},gs=async({authHeader:e,diffBucketPath:t,orgId:n,runId:r})=>{const s=await(o={auth:e,body:t,client:cr(),headers:cs(n),path:{runId:r}},(o.client??Jn).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})`)},ms=class{socket;url;authHeader;orgId;runId;pendingEvent=null;reconnectAttempts=0;reconnectTimer;debounceTimer;_isClosed=!1;isAuthenticated=!1;authenticationFailed=!1;onUserMessage;maxReconnectAttempts=10;baseReconnectDelay=2e3;maxReconnectDelay=3e4;debounceMs=500;get isClosed(){return this._isClosed}constructor({authHeader:e,orgId:t,runId:n,url:r=or,onUserMessage:s}){this.authHeader=e,this.orgId=t,this.runId=n,this.url=r,this.onUserMessage=s,Jr.info("[ws] Constructing AutohealWebSocketClient",{url:this.url,runId:n})}start(){this.connect()}connect(){if(!this._isClosed)try{const e={Authorization:this.authHeader};this.orgId&&(e["x-stably-org-id"]=this.orgId);const t=`${this.url}?runId=${encodeURIComponent(this.runId)}`;Jr.info("[ws] Connecting",{url:t,attempt:this.reconnectAttempts}),this.socket=new Ie(t,{headers:e}),this.socket.on("open",()=>{Jr.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);Jr.debug("[ws] Received message",{type:n?.type}),"connected"===n?.type&&(Jr.info("[ws] Authenticated successfully"),this.isAuthenticated=!0,this.authenticationFailed=!1,this.flushPending()),"user_message"===n?.type&&"string"==typeof n.content&&(Jr.info("[ws] Received user message from web UI"),this.onUserMessage?.(n.content))}catch{}}),this.socket.on("close",(e,t)=>{Jr.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=>{Jr.warn("[ws] Connection error",{error:e.message})})}catch(e){Jr.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);Jr.info("[ws] Scheduling reconnect",{attempt:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts,delayMs:e}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect()},e)}isConnected(){return!!this.socket&&this.socket.readyState===Ie.OPEN&&this.isAuthenticated}sendProgress(e){if(this._isClosed)return void Jr.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?(Jr.info("[ws] sendProgress: flushing terminal state immediately"),void this.flushPending()):void(this.debounceTimer||(this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.flushPending()},this.debounceMs))):(Jr.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 Jr.debug("[ws] flushPending: not connected, re-queuing event",{phase:e.payload.phase}),void(this.pendingEvent=e);try{Jr.debug("[ws] flushPending: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),t=>{t&&(Jr.warn("[ws] flushPending: send failed",{error:t.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e))})}catch(t){Jr.warn("[ws] flushPending: send threw",{error:t instanceof Error?t.message:String(t)}),this.pendingEvent=e}}flushPendingAndWait(){if(this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),!this.pendingEvent)return Promise.resolve();const e=this.pendingEvent;return this.pendingEvent=null,this.isConnected()?new Promise(t=>{try{Jr.debug("[ws] flushPendingAndWait: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),n=>{n&&(Jr.warn("[ws] flushPendingAndWait: send failed",{error:n.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e)),t()})}catch(n){Jr.warn("[ws] flushPendingAndWait: send threw",{error:n instanceof Error?n.message:String(n)}),this.pendingEvent=e,t()}}):(Jr.warn("[ws] flushPendingAndWait: not connected, event will be dropped",{phase:e.payload.phase}),this.pendingEvent=e,Promise.resolve())}close(){if(this._isClosed)return;Jr.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;Jr.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())}},ys=class{socket;url;authHeader;orgId;sessionId;pendingEvent=null;reconnectAttempts=0;reconnectTimer;debounceTimer;_isClosed=!1;isAuthenticated=!1;authenticationFailed=!1;onUserMessage;maxReconnectAttempts=10;baseReconnectDelay=2e3;maxReconnectDelay=3e4;debounceMs=500;get isClosed(){return this._isClosed}constructor({authHeader:e,orgId:t,sessionId:n,url:r=ir,onUserMessage:s}){this.authHeader=e,this.orgId=t,this.sessionId=n,this.url=r,this.onUserMessage=s,Jr.info("[ws] Constructing CreateProgressWebSocketClient",{url:this.url,sessionId:n})}start(){this.connect()}connect(){if(!this._isClosed)try{const e={Authorization:this.authHeader};this.orgId&&(e["x-stably-org-id"]=this.orgId);const t=`${this.url}?sessionId=${encodeURIComponent(this.sessionId)}`;Jr.info("[ws] Connecting",{url:t,attempt:this.reconnectAttempts}),this.socket=new Ie(t,{headers:e}),this.socket.on("open",()=>{Jr.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);Jr.debug("[ws] Received message",{type:n?.type}),"connected"===n?.type&&(Jr.info("[ws] Authenticated successfully"),this.isAuthenticated=!0,this.authenticationFailed=!1,this.flushPending()),"user_message"===n?.type&&"string"==typeof n.content&&(Jr.info("[ws] Received user message from web UI"),this.onUserMessage?.(n.content))}catch{}}),this.socket.on("close",(e,t)=>{Jr.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=>{Jr.warn("[ws] Connection error",{error:e.message})})}catch(e){Jr.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);Jr.info("[ws] Scheduling reconnect",{attempt:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts,delayMs:e}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect()},e)}isConnected(){return!!this.socket&&this.socket.readyState===Ie.OPEN&&this.isAuthenticated}sendProgress(e){if(this._isClosed)return void Jr.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?(Jr.info("[ws] sendProgress: flushing terminal state immediately"),void this.flushPending()):void(this.debounceTimer||(this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.flushPending()},this.debounceMs))):(Jr.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 Jr.debug("[ws] flushPending: not connected, re-queuing event",{phase:e.payload.phase}),void(this.pendingEvent=e);try{Jr.debug("[ws] flushPending: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),t=>{t&&(Jr.warn("[ws] flushPending: send failed",{error:t.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e))})}catch(t){Jr.warn("[ws] flushPending: send threw",{error:t instanceof Error?t.message:String(t)}),this.pendingEvent=e}}flushPendingAndWait(){if(this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),!this.pendingEvent)return Promise.resolve();const e=this.pendingEvent;return this.pendingEvent=null,this.isConnected()?new Promise(t=>{try{Jr.debug("[ws] flushPendingAndWait: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),n=>{n&&(Jr.warn("[ws] flushPendingAndWait: send failed",{error:n.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e)),t()})}catch(n){Jr.warn("[ws] flushPendingAndWait: send threw",{error:n instanceof Error?n.message:String(n)}),this.pendingEvent=e,t()}}):(Jr.warn("[ws] flushPendingAndWait: not connected, event will be dropped",{phase:e.payload.phase}),this.pendingEvent=e,Promise.resolve())}close(){if(this._isClosed)return;Jr.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;Jr.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())}},bs=ve.object({bucketPath:us,expiresInSeconds:ve.number(),key:ve.string(),uploadUrl:ve.string()}),ws=ge.object({uploadUrl:ge.string(),key:ge.string(),bucketPath:ge.object({bucket:ge.string(),key:ge.string()}),expiresInSeconds:ge.number()});async function vs({authHeader:e,orgId:t,sessionId:n,projectId:r,history:s}){if(0===s.length)return Jr.debug("[session-history] No history to upload"),{success:!0};try{Jr.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=new URL(`/internal/v1/cli/sessions/${n}/history/upload-url`,er),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",...r?{projectId:r}:{}}),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 ws.parse(await i.json())}({authHeader:e,orgId:t,sessionId:n,projectId:r}),a=s.map(e=>JSON.stringify(e)).join("\n");Jr.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 Jr.info("[session-history] History uploaded successfully",{key:i}),{success:!0,key:i}}catch(e){const t=e instanceof Error?e.message:String(e);return Jr.warn("[session-history] Failed to upload history",{error:t}),{success:!1,error:t}}}var Is="1.58.0",Ts=["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 _s(e){return/^\.env(\..*)?$/.test(e)||".stably-agent.env"===e}function Es(e){return Boolean(e&&"object"==typeof e&&"tool_input"in e&&e.tool_input&&"object"==typeof e.tool_input)}function Ss({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(!Es(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:_s,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 xs=["rm","mv","git","gh","npx","stably","stably-browser","pwtrace","npm","yarn","pnpm","bun"],As=["stably","playwright","stably-browser","pwtrace"],ks=["create","fix","verify"],Cs=["upload"],Ps=["push","fetch","pull","clone","ls-remote"],Rs=/\S+=(?:'[^']*(?:'\\''[^']*)*'|\S+)/;function Us(e){const t=[],n=e.trim(),r=/(?:'[^']*(?:'\\''[^']*)*'|\S)+/g;let s;for(;null!==(s=r.exec(n));)t.push(s[0]);return t}function $s(e){let t=0;const n=new RegExp(`^${Rs.source}$`);for(;t<e.length&&n.test(e[t]??"");)t+=1;return e.slice(t)}function Ls(e){const t=$s(Us(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 n}}}function Ds(e){return Us(e).find(e=>ks.includes(e))}function Ns(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 Os({onBeforeGitHubCommand:e,workspaceBoundary:t}){return async n=>{if(!Es(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 r=n.tool_input,{command:i}=r;if("string"!=typeof i)return{decision:"block",reason:"Invalid Bash command: command must be a string.",systemMessage:"Tool call blocked due to invalid command type"};const c=function(e){const t=e.trim(),n=new RegExp(`^(?:${Rs.source}\\s+)*(\\S+)`),r=t.match(n);return r?.[1]}(i);if(!c)return{decision:"block",reason:"Invalid Bash command: could not parse command.",systemMessage:"Tool call blocked due to unparseable command"};if("run_in_background"in r&&!0===r.run_in_background&&/\bstably-browser\s+run-test\b/.test(i))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&&xs.includes(e)}(c))return{decision:"block",reason:`The command "${c}" is not allowed. Only the following commands are permitted: ${xs.join(", ")}. Use the appropriate tools (Read, Write, Edit, Glob, Grep) for file operations instead.`,systemMessage:"Tool call blocked due to disallowed command"};if("npx"===c){const e=function(e){if(/(\s|^)npx\s+.*(\s|^)(-c|--call)(\s|=)/.test(e.trim()))return{valid:!1,reason:"The npx -c/--call form is not allowed. Use direct commands like `npx stably test ...`."};const t=Ls(e);if(!t)return{valid:!1,reason:"Invalid npx command: unable to determine which binary is being executed."};if(!new Set(As).has(t))return{valid:!1,reason:`The npx binary "${t}" is not allowed. Only ${As.join(", ")} are permitted.`};if("stably-browser"!==t){const n=Ds(e);if(n)return{valid:!1,reason:`The npx ${t} subcommand "${n}" is not allowed. The commands ${ks.join(", ")} are AI-powered and blocked to prevent recursion.`}}return{valid:!0}}(i);if(!e.valid)return{decision:"block",reason:e.reason,systemMessage:"Tool call blocked due to disallowed npx command"}}if("stably-browser"===c||"npx"===c&&"stably-browser"===Ls(i)){const e=function({command:e,binary:t}){const n=$s(Us(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 t}}({command:i,binary:"stably-browser"});if(e&&Cs.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"===c){const e=Ds(i);if(e)return{decision:"block",reason:`The stably subcommand "${e}" is not allowed. The commands ${ks.join(", ")} are AI-powered and blocked to prevent recursion.`,systemMessage:"Tool call blocked due to disallowed stably command"}}if("rm"===c){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):[]}(i);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(I(e))return S.native(e);let t=e;const n=[];for(;!I(t);){const r=o(t);if(r===t)return s(e);n.unshift(t.slice(r.length+1)),t=r}const r=S.native(t);return n.length>0?s(r,...n):r}(e),r=S.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=>!(Ns(e,"tests")||Ns(e,".stably")));if(t.length>0)return{decision:"block",reason:`The rm command can only remove files in the tests/ directory or .stably/ directory. The following path(s) are not allowed: ${t.join(", ")}.`,systemMessage:"Tool call blocked due to rm outside allowed directories"}}}if("git"===c&&["-c","--config","--config-env"].some(e=>i.includes(` ${e} `)||i.includes(` ${e}=`)))return{decision:"block",reason:"Git config flags (-c, --config, --config-env) are not allowed for security reasons.",systemMessage:"Tool call blocked due to git config injection attempt"};if("git"===c&&function(e){const t=e.trim();return!!t.startsWith("git ")&&Ps.some(e=>t.includes(` ${e}`)||t.includes(`git ${e}`))}(i)&&e)try{await e()}catch(e){console.error("[BashSecurityHook] Failed to refresh git token:",e)}if("gh"===c){const t=function(e){const t=e.toLowerCase();return Ts.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}}(i);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 Bs=/\.(spec|test)\.(ts|tsx|js|jsx|mts|mjs)$/;function js({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&&Bs.test(r)&&e(r),{decision:"approve"}}}var Ms=M(f);async function Fs(){try{const{stdout:e}=await Ms('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 Ms(`pkill -KILL -P ${e} '.*' 2>/dev/null || true`)}))}catch{}}var Hs=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 Gs(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 Ws=[".ts",".js",".mts",".mjs",".cts",".cjs"],Ys=10240,Vs=async({defaultContent:e,fileName:t,filePath:n})=>{try{const e=(await ie(n)).size,r=await Z(n,"utf-8"),s=Buffer.byteLength(r,"utf-8");if(s<=Ys)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<=Ys?o:o.slice(0,Ys)+`\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}},zs=async({defaultContent:e,dirName:t,dirPath:n})=>{try{const e=await oe(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}},Ks=async({allowedEnvVars:e,mode:t,workspaceInfo:n,authHeader:r,customHeader:s,maxParallelWorkers:o})=>{const i=cr(),a=Gs(n.absolutePath);Jr.debug("Requesting system prompt from API",{mode:t,hasGitContext:!!a,envVarCount:e.length});const c=await(l={client:i,auth:r,body:{mode:t,workspaceInfo:n,allowedEnvVars:e,gitContext:a,maxParallelWorkers:o}},(l.client??Jn).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/prompts/system",...l,headers:{"Content-Type":"application/json",...l.headers}}));var l;if(401===c.response.status)throw Jr.warn("System prompt fetch failed: unauthorized (401)"),await Er(),new Error("Your session has expired or been revoked. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(403===c.response.status)throw Jr.debug("System prompt fetch failed: forbidden (403)"),new Error("Your organization does not have an active subscription. Manage your subscription at https://app.stably.ai or contact your organization admin.");if(c.error){Jr.warn("System prompt fetch failed",{error:c.error});const e=JSON.stringify(c.error);if(e.toLowerCase().includes("unauthorized")||e.toLowerCase().includes("unauthenticated"))throw await Er(),new Error("Your session has expired or been revoked. Credentials have been cleared. Please run `stably login` to re-authenticate.");throw new Error("Failed to fetch system prompt. Please check your network connection and try again. If this persists, run `stably login` to re-authenticate.")}const u=function({customHeader:e,systemPrompt:t}){return e?`${t}\n\nWhen writing or updating the generated test file, prepend this exact header at the top of the file without modification:\n\`\`\`ts\n${e}\n\`\`\``:t}({systemPrompt:c.data.systemPrompt,customHeader:s});return Jr.debug("System prompt received",{size:u.length,appendedCustomHeader:!!s,hasPrContext:!!c.data.prContext}),{systemPrompt:u,prContext:c.data.prContext}},qs={chat:"chat",single:"create",fix:"fix",init:"init",verify:"verify"},Js=".stably-playwright-wrapper.config.*",Qs=[".ts",".js",".mts",".mjs",".cts",".cjs"];function Xs(e){const t=s(e);if(I(t))for(const e of Qs){const n=i(t,`playwright.config${e}`);if(I(n))return n}}var Zs=["tests","e2e","__tests__","test"];function eo(e){try{return I(e)&&T(e).isDirectory()}catch{return!1}}function to(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(q.dim(`Using output directory: ${e} (from ${n})`))}var no,ro=["mcp__playwright-test__","mcp__auto-heal-report__","mcp__stably-agent-control__"],so=["planner_","generator_"],oo={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"},io={"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"},ao={Skill:"Preparing for task",ToolSearch:"Searching tools"},co=(e,t)=>{const n=t.find(t=>e.startsWith(t));return n?e.slice(n.length):e},lo=e=>e.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" "),uo=(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 io[t]?io[t]:`Loading ${t.replace(/-/g," ")}`}return"Preparing for task"}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();if("string"==typeof n.description&&n.description.trim())return n.description.trim();const o=oo[t];return o?o(s):`${lo(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":null},fo=e=>"mcp__auto-heal-report__capture-trace-proof"===e?"Verify Test Run":"mcp__auto-heal-report__generate-report"===e?"Generate Report":(e=>{const t=ao[e];if(t)return t;const n=co(e,ro),r=co(n,so);return lo(r)})(e),ho=["test","bug","flake","ui_change","other"],go={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."},mo=e=>go[e],yo=/[^a-zA-Z0-9-_]/g,bo=e=>{const t=e.trim().replace(yo,"_");return t.length>0?t.slice(0,80):void 0},wo=e=>bo(e)??"issue",vo=e=>"string"==typeof e?bo(e):void 0,Io=Ce("/");try{no=Io("worker_threads").Worker}catch(e){}var To=no?function(e,t,n,r,s){var o=!1,i=new no(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,no.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}},_o=Uint8Array,Eo=Uint16Array,So=Int32Array,xo=new _o([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]),Ao=new _o([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]),ko=new _o([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Co=function(e,t){for(var n=new Eo(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];var s=new So(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}},Po=Co(xo,2),Ro=Po.b,Uo=Po.r;Ro[28]=258,Uo[258]=28;var $o,Lo=Co(Ao,0),Do=Lo.b,No=Lo.r,Oo=new Eo(32768);for(Mo=0;Mo<32768;++Mo)$o=(61680&($o=(52428&($o=(43690&Mo)>>1|(21845&Mo)<<1))>>2|(13107&$o)<<2))>>4|(3855&$o)<<4,Oo[Mo]=((65280&$o)>>8|(255&$o)<<8)>>1;var Bo=function(e,t,n){for(var r=e.length,s=0,o=new Eo(t);s<r;++s)e[s]&&++o[e[s]-1];var i,a=new Eo(t);for(s=1;s<t;++s)a[s]=a[s-1]+o[s-1]<<1;if(n){i=new Eo(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[Oo[d]>>c]=l}else for(i=new Eo(r),s=0;s<r;++s)e[s]&&(i[s]=Oo[a[e[s]-1]++]>>15-e[s]);return i},jo=new _o(288);for(Mo=0;Mo<144;++Mo)jo[Mo]=8;for(Mo=144;Mo<256;++Mo)jo[Mo]=9;for(Mo=256;Mo<280;++Mo)jo[Mo]=7;for(Mo=280;Mo<288;++Mo)jo[Mo]=8;var Mo,Fo=new _o(32);for(Mo=0;Mo<32;++Mo)Fo[Mo]=5;var Ho=Bo(jo,9,0),Go=Bo(jo,9,1),Wo=Bo(Fo,5,0),Yo=Bo(Fo,5,1),Vo=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},zo=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(7&t)&n},Ko=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(7&t)},qo=function(e){return(e+7)/8|0},Jo=function(e,t,n){return(null==t||t<0)&&(t=0),(null==n||n>e.length)&&(n=e.length),new _o(e.subarray(t,n))},Qo=["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"],Xo=function(e,t,n){var r=new Error(t||Qo[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,Xo),!n)throw r;return r},Zo=function(e,t,n,r){var s=e.length,o=r?r.length:0;if(!s||t.f&&!t.l)return n||new _o(0);var i=!n,a=i||2!=t.i,c=t.i;i&&(n=new _o(3*s));var l=function(e){var t=n.length;if(e>t){var r=new _o(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=zo(e,d,1);var b=zo(e,d+1,3);if(d+=3,!b){var w=e[(P=qo(d)+4)-4]|e[P-3]<<8,v=P+w;if(v>s){c&&Xo(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=Go,h=Yo,g=9,m=5;else if(2==b){var I=zo(e,d,31)+257,T=zo(e,d+10,15)+4,_=I+zo(e,d+5,31)+1;d+=14;for(var E=new _o(_),S=new _o(19),x=0;x<T;++x)S[ko[x]]=zo(e,d+3*x,7);d+=3*T;var A=Vo(S),k=(1<<A)-1,C=Bo(S,A,1);for(x=0;x<_;){var P,R=C[zo(e,d,k)];if(d+=15&R,(P=R>>4)<16)E[x++]=P;else{var U=0,$=0;for(16==P?($=3+zo(e,d,3),d+=2,U=E[x-1]):17==P?($=3+zo(e,d,7),d+=3):18==P&&($=11+zo(e,d,127),d+=7);$--;)E[x++]=U}}var L=E.subarray(0,I),D=E.subarray(I);g=Vo(L),m=Vo(D),f=Bo(L,g,1),h=Bo(D,m,1)}else Xo(1);if(d>y){c&&Xo(0);break}}a&&l(p+131072);for(var N=(1<<g)-1,O=(1<<m)-1,B=d;;B=d){var j=(U=f[Ko(e,d)&N])>>4;if((d+=15&U)>y){c&&Xo(0);break}if(U||Xo(2),j<256)n[p++]=j;else{if(256==j){B=d,f=null;break}var M=j-254;if(j>264){var F=xo[x=j-257];M=zo(e,d,(1<<F)-1)+Ro[x],d+=F}var H=h[Ko(e,d)&O],G=H>>4;if(H||Xo(3),d+=15&H,D=Do[G],G>3&&(F=Ao[G],D+=Ko(e,d)&(1<<F)-1,d+=F),d>y){c&&Xo(0);break}a&&l(p+131072);var W=p+M;if(p<D){var Y=o-D,V=Math.min(D,W);for(Y+p<0&&Xo(3);p<V;++p)n[p]=r[Y+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?Jo(n,0,p):n.subarray(0,p)},ei=function(e,t,n){n<<=7&t;var r=t/8|0;e[r]|=n,e[r+1]|=n>>8},ti=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},ni=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:li,l:0};if(1==s){var i=new _o(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 Eo(p+1),h=ri(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 _o(f),l:h}},ri=function(e,t,n){return-1==e.s?Math.max(ri(e.l,t,n+1),ri(e.r,t,n+1)):t[e.s]=n},si=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new Eo(++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}},oi=function(e,t){for(var n=0,r=0;r<t.length;++r)n+=e[r]*t[r];return n},ii=function(e,t,n){var r=n.length,s=qo(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)},ai=function(e,t,n,r,s,o,i,a,c,l,u){ei(t,u++,n),++s[256];for(var d=ni(s,15),p=d.t,f=d.l,h=ni(o,15),g=h.t,m=h.l,y=si(p),b=y.c,w=y.n,v=si(g),I=v.c,T=v.n,_=new Eo(19),E=0;E<b.length;++E)++_[31&b[E]];for(E=0;E<I.length;++E)++_[31&I[E]];for(var S=ni(_,7),x=S.t,A=S.l,k=19;k>4&&!x[ko[k-1]];--k);var C,P,R,U,$=l+5<<3,L=oi(s,jo)+oi(o,Fo)+i,D=oi(s,p)+oi(o,g)+i+14+3*k+oi(_,x)+2*_[16]+3*_[17]+7*_[18];if(c>=0&&$<=L&&$<=D)return ii(t,u,e.subarray(c,c+l));if(ei(t,u,1+(D<L)),u+=2,D<L){C=Bo(p,f,0),P=p,R=Bo(g,m,0),U=g;var N=Bo(x,A,0);for(ei(t,u,w-257),ei(t,u+5,T-1),ei(t,u+10,k-4),u+=14,E=0;E<k;++E)ei(t,u+3*E,x[ko[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];ei(t,u,N[M]),u+=x[M],M>15&&(ei(t,u,j[E]>>5&127),u+=j[E]>>12)}}}else C=Ho,P=jo,R=Wo,U=Fo;for(E=0;E<a;++E){var F=r[E];if(F>255){ti(t,u,C[257+(M=F>>18&31)]),u+=P[M+257],M>7&&(ei(t,u,F>>23&31),u+=xo[M]);var H=31&F;ti(t,u,R[H]),u+=U[H],H>3&&(ti(t,u,F>>5&8191),u+=Ao[H])}else ti(t,u,C[F]),u+=P[F]}return ti(t,u,C[256]),u+P[256]},ci=new So([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),li=new _o(0),ui=function(e,t,n,r,s,o){var i=o.z||e.length,a=new _o(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=ci[t-1],p=d>>13,f=8191&d,h=(1<<n)-1,g=o.p||new Eo(32768),m=o.h||new Eo(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 So(25e3),I=new Eo(288),T=new Eo(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=ai(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,Y=W-g[W]&32767;Y>G&&(G=Y,R=W)}}}O+=(P=R)-(R=g[P])&32767}if(D){v[x++]=268435456|Uo[L]<<18|No[D];var V=31&Uo[L],z=31&No[D];E+=xo[V]+Ao[z],++I[257+V],++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=ai(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 K=S+65535;K>=i&&(c[u/8|0]=l,K=i),u=ii(c,u+1,e.subarray(S,K))}o.i=i}return Jo(a,0,r+qo(u)+s)},di=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}(),pi=function(e,t,n,r,s){if(!s&&(s={l:1},t.dictionary)){var o=t.dictionary.subarray(-32768),i=new _o(o.length+e.length);i.set(o),i.set(e,o.length),e=i,s.w=o.length}return ui(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)},fi=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},hi=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},gi=[],mi=function(){return[_o,Eo,So,xo,Ao,ko,Ro,Do,Go,Yo,Oo,Qo,Bo,Vo,zo,Ko,qo,Jo,Xo,Zo,xi,bi,wi]},yi=function(){return[_o,Eo,So,xo,Ao,ko,Uo,No,Ho,jo,Wo,Fo,Oo,ci,li,Bo,ei,ti,ni,ri,si,oi,ii,ai,qo,Jo,ui,pi,Si,bi]},bi=function(e){return postMessage(e,[e.buffer])},wi=function(e){return e&&{out:e.size&&new _o(e.size),dictionary:e.dictionary}},vi=function(e,t,n,r,s,o){var i=function(e,t,n,r){if(!gi[n]){for(var s="",o={},i=e.length-1,a=0;a<i;++a)s=hi(e[a],s,o);gi[n]={c:hi(e[i],s,o),e:o}}var c=fi({},gi[n].e);return To(gi[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()}},Ii=function(e,t){return e[t]|e[t+1]<<8},Ti=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},_i=function(e,t){return Ti(e,t)+4294967296*Ti(e,t+4)},Ei=function(e,t,n){for(;n;++t)e[t]=n,n>>>=8};function Si(e,t){return pi(e,t||{},0,0)}function xi(e,t){return Zo(e,{i:2},t&&t.out,t&&t.dictionary)}var Ai=function(e,t,n,r){for(var s in e){var o=e[s],i=t+s,a=r;Array.isArray(o)&&(a=fi(r,o[1]),o=o[0]),o instanceof _o?n[i]=[o,a]:(n[i+="/"]=[new _o(0),a],Ai(o,i,n,r))}},ki="undefined"!=typeof TextEncoder&&new TextEncoder,Ci="undefined"!=typeof TextDecoder&&new TextDecoder;try{Ci.decode(li,{stream:!0})}catch(e){}function Pi(e,t){if(ki)return ki.encode(e);for(var n=e.length,r=new _o(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 _o(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 Jo(r,0,s)}var Ri=function(e){var t=0;if(e)for(var n in e){var r=e[n].length;r>65535&&Xo(9),t+=r+4}return t},Ui=function(e,t,n,r,s,o,i,a){var c=r.length,l=n.extra,u=a&&a.length,d=Ri(l);Ei(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)&&Xo(10),Ei(e,t,f<<25|p.getMonth()+1<<21|p.getDate()<<16|p.getHours()<<11|p.getMinutes()<<5|p.getSeconds()>>1),t+=4,-1!=o&&(Ei(e,t,n.crc),Ei(e,t+4,o<0?-o-2:o),Ei(e,t+8,n.size)),Ei(e,t+12,c),Ei(e,t+14,d),t+=16,null!=i&&(Ei(e,t,u),Ei(e,t+6,n.attrs),Ei(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;Ei(e,t,+h),Ei(e,t+2,m),e.set(g,t+4),t+=4+m}return u&&(e.set(a,t),t+=u),t},$i="function"==typeof queueMicrotask?queueMicrotask:"function"==typeof setTimeout?setTimeout:function(e){e()};function Li(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 Di=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 Ni(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 Oi(e){switch(7&Ni(e)){case 0:return Ni(e),!0;case 1:return e.next(8),!0;case 2:const t=Ni(e);return e.next(t),!0;case 5:return e.next(4),!0}return!1}function Bi(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!Li(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!Li(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 Di(e,t);let r=0;for(;;){if(!Oi(n)&&!n.hasError())return!1;if(n.hasError())break;r++}return r>0}(e,o))}var ji=[/^\/$/,/^\*+$/,/^[0-9]+$/],Mi=["/artifact/","https://","http://","*********"],Fi=new Set(["sha1","_sha1","pageref","downloadsPath","tracesDir","pageId"]);function Hi({sensitiveValues:e,str:t}){return e.reduce((e,t)=>e.replaceAll(t,"[REDACTED]"),t)}function Gi({sensitiveValues:e,value:t}){return"string"==typeof t?Hi({sensitiveValues:e,str:t}):Array.isArray(t)?t.map(t=>Gi({sensitiveValues:e,value:t})):function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(t)?Yi({obj:t,sensitiveValues:e}):t}function Wi(e){return!!Fi.has(e)||e.toLowerCase().endsWith("sha1")}function Yi({obj:e,sensitiveValues:t}){return Object.fromEntries(Object.entries(e).map(([e,n])=>[e,Wi(e)?n:Gi({sensitiveValues:t,value:n})]))}function Vi({error:e,sensitiveValues:t}){return e?{...e,message:Hi({sensitiveValues:t,str:e.message})}:void 0}function zi({content:e,sensitiveValues:t}){const n=new F,r=new H,s=Hi({sensitiveValues:t,str:n.decode(e)});return r.encode(s)}var Ki=M(function(e,t,n){n||(n=t,t={}),"function"!=typeof n&&Xo(7);var r=[],s=function(){for(var e=0;e<r.length;++e)r[e]()},o={},i=function(e,t){$i(function(){n(e,t)})};$i(function(){i=n});for(var a=e.length-22;101010256!=Ti(e,a);--a)if(!a||e.length-a>65558)return i(Xo(13,0,1),null),s;var c=Ii(e,a+8);if(c){var l=c,u=Ti(e,a+16),d=4294967295==u||65535==l;if(d){var p=Ti(e,a-12);(d=101075792==Ti(e,p))&&(l=c=Ti(e,p+32),u=Ti(e,p+48))}for(var f=t&&t.filter,h=function(t){var n=function(e,t,n){var r=Ii(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(Ci)return Ci.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:Jo(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&&Xo(8),o}(e.subarray(t+46,t+46+r),!(2048&Ii(e,t+8))),o=t+46+r,i=Ti(e,t+20),a=n&&4294967295==i?function(e,t){for(;1!=Ii(e,t);t+=4+Ii(e,t+2));return[_i(e,t+12),_i(e,t+4),_i(e,t+20)]}(e,o):[i,Ti(e,t+24),Ti(e,t+42)],c=a[0],l=a[1],u=a[2];return[Ii(e,t+10),c,l,s,o+Ii(e,t+30)+Ii(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+Ii(e,t+26)+Ii(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,xi(w,{out:new _o(p)}))}catch(e){b(e,null)}else r.push(function(e,t,n){return n||(n=t,t={}),"function"!=typeof n&&Xo(7),vi(e,t,[mi],function(e){return bi(xi(e.data[0],wi(e.data[1])))},1,n)}(w,{size:p},b))}else b(Xo(14,"unknown compression type "+a,1),null);else b(null,Jo(e,y,y+l));else b(null,null)},g=0;g<l;++g)h()}else i(null,{});return s}),qi=M(function(e,t,n){n||(n=t,t={}),"function"!=typeof n&&Xo(7);var r={};Ai(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){$i(function(){n(e,t)})};$i(function(){p=n});var f=function(){var e=new _o(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;Ui(e,a,s,s.f,s.u,o);var u=30+s.f.length+Ri(s.extra),d=a+u;e.set(s.c,d),Ui(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){Ei(e,t,101010256),Ei(e,t+8,n),Ei(e,t+10,n),Ei(e,t+12,r),Ei(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=di[255&n^t[r]]^n>>>8;e=n},d:function(){return~e}}}(),m=c.length;g.p(c);var y=Pi(t),b=y.length,w=h.comment,v=w&&Pi(w),I=v&&v.length,T=Ri(h.extra),_=0==h.level?0:8,E=function(n,r){if(n)d(),p(n,null);else{var s=r.length;l[e]=fi(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(Xo(11,0,1),null),_)if(m<16e4)try{E(null,Si(c,h))}catch(e){E(e,null)}else u.push(function(e,t,n){return n||(n=t,t={}),"function"!=typeof n&&Xo(7),vi(e,t,[yi],function(e){return bi(Si(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 Ji({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 V(e).with({type:"console"},e=>({...e,args:e.args?.map(e=>({...e,preview:Hi({sensitiveValues:t,str:e.preview}),value:Gi({sensitiveValues:t,value:e.value})})),text:Hi({sensitiveValues:t,str:e.text})})).with({type:"before"},e=>({...e,params:Yi({obj:e.params,sensitiveValues:t}),title:e.title?Hi({sensitiveValues:t,str:e.title}):void 0})).with({type:"after"},e=>({...e,error:Vi({error:e.error,sensitiveValues:t}),result:void 0!==e.result?Gi({sensitiveValues:t,value:e.result}):void 0})).with({type:"action"},e=>({...e,error:Vi({error:e.error,sensitiveValues:t}),params:Yi({obj:e.params,sensitiveValues:t}),result:void 0!==e.result?Gi({sensitiveValues:t,value:e.result}):void 0,title:e.title?Hi({sensitiveValues:t,str:e.title}):void 0})).with({type:"event"},e=>({...e,params:Yi({obj:e.params,sensitiveValues:t})})).with({type:"stdout"},{type:"stderr"},e=>({...e,text:void 0!==e.text?Hi({sensitiveValues:t,str:e.text}):void 0})).with({type:"error"},e=>({...e,message:Hi({sensitiveValues:t,str:e.message})})).with({type:"log"},e=>({...e,message:Hi({sensitiveValues:t,str:e.message})})).with({type:"context-options"},e=>({...e,options:Yi({obj:e.options,sensitiveValues:t}),title:e.title?Hi({sensitiveValues:t,str:e.title}):void 0})).with({type:"frame-snapshot"},e=>({...e,snapshot:Yi({obj:e.snapshot,sensitiveValues:t})})).with({type:"resource-snapshot"},e=>({...e,snapshot:Yi({obj:e.snapshot,sensitiveValues:t})})).with({type:"screencast-frame"},{type:"input"},e=>e).exhaustive()}({event:JSON.parse(e),sensitiveValues:t});return JSON.stringify(n)}catch{return Hi({sensitiveValues:t,str:e})}});return r.encode(s.join("\n"))}({content:e,sensitiveValues:n}):r.endsWith(".html")||r.endsWith(".dat")||r.endsWith(".json")?zi({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!")}(T(e));const n=P(e,"r"),r=Buffer.alloc(515),s=R(n,r,0,515,0);return U(n),Bi(r,s,t)}return Bi(e,void 0!==t?.size?t.size:e.length,t)}(Buffer.from(e),{size:e.length})}(e)?e:zi({content:e,sensitiveValues:t})}({content:e,sensitiveValues:n}):e}function Qi(e=process.cwd()){let t=s(e);for(;;){const e=Xi(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=Zi(t);let n=!1,s=t;for(;;){const e=i(s,"node_modules"),t=i(e,r);if(I(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 Xi(e){const t=i(e,"package.json");let n;try{n=_(t,"utf-8")}catch{return}try{return JSON.parse(n)}catch{return}}function Zi(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(I(i(n,r)))return e;const e=o(n);if(e===n)return;n=e}}function ea(e){if("npm"===e||"pnpm"===e)return["npx","playwright"];if("yarn"===e)return["yarn","playwright"];throw new Error("Package manager not supported")}var ta=[".ts",".js",".mts",".mjs",".cts",".cjs"],na=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),ra=e=>(e instanceof Error?e.message:String(e)).slice(0,400),sa=({outputDir:e,representativeTest:t})=>{const n=["test","--trace=on","--workers=1","--retries=0","--reporter=list","--output",e];return t.filePath&&n.push(t.filePath),t.testTitle?n.push("--grep",na(t.testTitle)):t.testIdentifier&&n.push("--grep",`^${na(t.testIdentifier)}$`),n},oa=async e=>{const t=await oe(e,{withFileTypes:!0}),n=[];for(const s of t){const t=r.join(e,s.name);if(s.isDirectory())n.push(...await oa(t));else if(s.isFile()&&"trace.zip"===s.name){const e=await ie(t);n.push({path:t,mtimeMs:e.mtimeMs})}}return n},ia=async e=>{try{const t=await oe(e,{withFileTypes:!0});for(const n of t){const t=r.join(e,n.name);n.isDirectory()?await ia(t):n.isFile()&&".last-run.json"===n.name&&await ee(t,{force:!0})}}catch{}},aa=async({representativeTest:e,workingDir:t,outputDir:n,requestUploadUrl:s})=>{const o=await(async({representativeTest:e,workingDir:t,outputDir:n})=>{if(!(e=>null!=e.filePath||null!=e.testTitle||null!=e.testIdentifier)(e))return{status:"capture_failed",error:"Representative test info is missing (need filePath, testTitle, or testIdentifier)."};const s=Qi(t);if(!s.installed||!s.inNodeModules||!s.packageManager)return{status:"capture_failed",error:"Playwright is not installed in the current workspace."};const[o,...i]=ea(s.packageManager),a=[...i,...sa({outputDir:n,representativeTest:e})],c=function(e){if(!process.env.CHROME_BIN)return;let t;for(const n of ta){const s=`playwright.config${n}`;if(I(r.join(e,s))){t=s;break}}let n=!1;try{const t=h("npm pkg get type",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});n="module"===JSON.parse(t.trim())}catch{}const s=n?"mts":"ts",o=r.join(e,`.stably-trace-proof-wrapper.config.${s}`),i=`\n// Auto-generated by Stably CLI trace-proof capture.\n// Injects CHROME_BIN as the browser executable path for environments where\n// Playwright's downloaded browsers are unavailable (e.g., Alpine containers).\n${t?`import baseConfig from './${t}';\nconst config = baseConfig;`:"const config = {};"}\n\nexport default {\n ...config,\n use: {\n ...(config as Record<string, unknown>).use as Record<string, unknown> | undefined,\n launchOptions: {\n ...((config as Record<string, unknown>).use as Record<string, unknown> | undefined)?.launchOptions as Record<string, unknown> | undefined,\n executablePath: process.env.CHROME_BIN,\n },\n },\n};\n`.trimStart();return A(r.dirname(o),{recursive:!0}),k(o,i,"utf-8"),{wrapperPath:o,cleanup:()=>{try{C(o,{force:!0})}catch{}}}}(t);c&&a.push("--config",c.wrapperPath);try{await ee(n,{force:!0,recursive:!0}),await te(n,{recursive:!0});const{code:e,output:r,timedOut:s}=await(async({args:e,command:t,cwd:n,env:r,timeoutMs:s})=>await new Promise((o,i)=>{const a=g(t,e,{cwd:n,env:r??process.env,stdio:["ignore","pipe","pipe"],shell:"win32"===process.platform});let c="",l=!1;a.stdout.on("data",e=>{c+=e.toString()}),a.stderr.on("data",e=>{c+=e.toString()});const u=setTimeout(()=>{l=!0,a.kill("SIGTERM")},s);a.on("error",e=>{clearTimeout(u),i(e)}),a.on("close",e=>{clearTimeout(u),o({code:e,output:c,timedOut:l})})}))({args:a,command:o,cwd:t,env:{...process.env,STABLY_INTERNAL_DISABLE_REPORTING:"1"},timeoutMs:3e5});if(s)return{status:"capture_failed",error:"Trace proof run timed out while executing Playwright verification."};const i=(l=r).includes("Executable doesn't exist")&&l.includes("ms-playwright")?'Playwright browsers are not installed. Run "npx playwright install" to install them.':l.includes("browserType.launch")&&l.includes("Executable doesn't exist")?"Browser executable not found. Playwright browsers may not be installed.":l.includes("npx playwright install")?"Playwright browsers need to be installed. The trace cannot verify the fix.":void 0;if(i)return{status:"capture_failed",error:i};const c=await(async e=>{const t=await oa(e);if(0!==t.length)return t.sort((e,t)=>t.mtimeMs-e.mtimeMs),t[0]?.path})(n);if(!c)return{status:"capture_failed",error:`No trace.zip was produced${0!==e?` (test exit code ${e??"unknown"})`:""}: ${r.trim().slice(0,280)}`.trim()};await ia(n);const u=r.replace(/\x1B\[[0-9;]*[a-zA-Z]/g,""),d=4e3;return{status:"captured",tracePath:c,testPassed:0===e,testExitCode:e,testStderr:u.length>d?`...(truncated)\n${u.slice(-d)}`:u}}catch(e){return{status:"capture_failed",error:ra(e)}}finally{c?.cleanup()}var l})({representativeTest:e,workingDir:t,outputDir:n});if("capture_failed"===o.status)return o;const{testPassed:i,testExitCode:a,testStderr:c}=o;try{const{traceBucketPath:e,uploadUrl:t,sensitiveValues:n}=await s(),r=await async function({tracePath:e,sensitiveValues:t}){const n=[],r=x(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||ji.some(t=>t.test(e))||Mi.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 Ki(new Uint8Array(t)),o=Object.entries(s),i=await Promise.all(o.map(async([e,t])=>[e,await Ji({content:t,filename:e,sensitiveValues:r})])),a=Object.fromEntries(i);return qi(a)}({traceBuffer:new Uint8Array(Buffer.concat(n)),sensitiveValues:t})}({tracePath:o.tracePath,sensitiveValues:n});try{await ds({body:r,contentType:"application/zip",uploadUrl:t,errorContext:"trace"})}catch(e){return{status:"upload_failed",error:ra(e),testPassed:i,testExitCode:a,testStderr:c}}return{status:"captured",storage:e,testPassed:i,testExitCode:a,testStderr:c}}catch(e){return{status:"upload_failed",error:ra(e),testPassed:i,testExitCode:a,testStderr:c}}},{zMarkdownAutoHealReport:ca,zRepresentativeTest:la}=function(e){const t=e.enum(ho),n=["Classification of the root cause:","",`- test: ${mo("test")}`,`- bug: ${mo("bug")}`,`- flake: ${mo("flake")}`,`- ui_change: ${mo("ui_change")}`,`- other: ${mo("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}}(ve),ua=({authHeader:e,diffTracker:t,orgId:n,runId:s,workingDir:o})=>G({name:"auto-heal-report",tools:[W("capture-trace-proof",["Capture and upload a Playwright trace proof for a test case.","","MANDATORY: Call for EVERY testCaseId in your issue, whether fixed or unfixed.","- Fixed: Trace proves the fix works","- Unfixed: Trace shows the failure state for auditability","","The response includes testPassed, testExitCode, and testStderr so you can","check whether the test passed and decide whether to retry.","","Pass testCaseId and call once per test case.","testCaseId is for per-test mapping/storage metadata; representativeTest selects the runnable test."].join("\n"),{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."),representativeTest:la.optional().default({}),testCaseId:ve.string().min(1).optional().describe("Optional test case ID when capturing per-test trace proofs.")},async({issueId:t,proofId:i,representativeTest:a,testCaseId:c})=>{const l=ve.string().min(1).parse(t),u=null==i?void 0:ve.string().min(1).parse(i),d=null==c?void 0:ve.string().min(1).parse(c),p=la.parse(a??{}),f=await(async({authHeader:e,issueId:t,orgId:n,proofId:s,representativeTest:o,runId:i,testCaseId:a,workingDir:c})=>{const l=wo(t),u=(({proofId:e,testCaseId:t})=>vo(t)??vo(e))({testCaseId:a,proofId:s}),d=r.join(c,".stably","autoheal-proof",l,u??"issue");return{...await aa({representativeTest:o,workingDir:c,outputDir:d,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:cr(),headers:cs(o),path:{runId:i}},(c.client??Jn).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=fs.parse(a.data);return{traceBucketPath:l.traceBucketPath,expiresInSeconds:l.expiresInSeconds,key:l.key,uploadUrl:l.uploadUrl,sensitiveValues:l.sensitiveValues}})({authHeader:e,issueId:t,proofId:s,orgId:n,runId:i,testCaseId:a})}),representativeTest:o}})({authHeader:e,issueId:l,orgId:n,proofId:u,representativeTest:p,runId:s,testCaseId:d,workingDir:o}),h=p.testTitle||p.filePath,g="captured"===f.status&&f.storage?`@[trace:${Buffer.from(JSON.stringify({...f.storage,...h?{label:h}:{}})).toString("base64url")}]`:void 0,m="string"==typeof d?{testCaseId:d,...f,tracePlaceholder:g}:{...f,tracePlaceholder:g};return{content:[{text:JSON.stringify(m),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 capture-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:ca.shape.markdown,summary:ca.shape.summary,issues:ca.shape.issues},async({markdown:r,summary:o,issues:i})=>{const a=await t.computeDiff(),c=ca.parse({format:"markdown",markdown:r,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:cr(),headers:cs(t),path:{runId:r}},(o.client??Jn).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:e,orgId:n,report:c,runId:s});const{diffBucketPath:t,uploadUrl:r}=await hs({authHeader:e,contentType:"text/plain",orgId:n,runId:s});await ds({body:a,contentType:"text/plain",uploadUrl:r,errorContext:"diff"}),await gs({authHeader:e,diffBucketPath:t,orgId:n,runId:s})}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 da({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 pa(e){const t=n.join(e,"package.json");return w.existsSync(t)?{path:t,contents:JSON.parse(w.readFileSync(t,"utf-8"))}:null}var fa=["playwright.config.ts","playwright.config.js","playwright.config.mts","playwright.config.mjs","playwright.config.cjs"];function ha(e){return fa.some(t=>w.existsSync(n.join(e,t)))}function ga(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(...ga(r,t)):t.test(o.name)&&s.push(r)}return s}function ma(e){let t=n.resolve(e);for(;;){if(ha(t))return t;const r=n.dirname(t);if(r===t)return e;t=r}}function ya(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 ba(e){return/\b(test|testing|playwright|e2e|stably)\b/i.test(e)}function wa(e,t){for(const r of va(e,t))if(w.existsSync(n.join(r,"package.json")))return r}function va(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 Ia(e){return e?.replace(/^[~^>=<]+/,"")}function Ta(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 _a=ve.object({commentUrl:ve.string()}),Ea=({prContext:e,authHeader: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: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=Array.isArray(o)?o:[];Jr.info("[create-report] Posting report to GitHub PR",{prNumber:e.prNumber,filesCount:i.length});try{const o={summary:"string"==typeof s?s:String(s),filesCreated:i.map(String)},a=await async function({authHeader:e,orgId:t,prNumber:n,owner:r,repo:s,report:o}){const i=new URL("/internal/v1/cli/create-report",er).toString(),a={Authorization:e,"Content-Type":"application/json"};t&&(a["x-stably-org-id"]=t),Jr.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 Jr.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=_a.parse(await c.json());return Jr.info("Create report posted successfully",{commentUrl:l.commentUrl}),l}({authHeader:t,orgId:n,prNumber:e.prNumber,owner:e.owner,repo:e.repo,report:o});return r?.(a),Jr.info("[create-report] Report posted successfully",{commentUrl:a.commentUrl}),{content:[{type:"text",text:`β
Test creation report posted to PR #${e.prNumber}\n\nView the comment: ${a.commentUrl}`}]}}catch(e){const t=e instanceof Error?e.message:String(e);return Jr.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}}})]}),Sa=ve.object({traceBucketPath:us,expiresInSeconds:ve.number(),key:ve.string(),uploadUrl:ve.string(),sensitiveValues:ve.array(ve.string())}),xa=({authHeader:e,sessionId:t,orgId:n,workingDir:s,onTraceProofCaptured:o})=>G({name:"create-trace-proof",tools:[W("capture-create-trace-proof",["Capture and upload a Playwright trace proof for a created test file.","","Call this after verifying that a created test file passes.","The trace proves the test works and is viewable in the Stably web UI.","If the trace run fails, the response includes testPassed, testExitCode,","and testStderr so you can inspect the failure, fix the test, and retry.","","Pass the testFilePath of the created test file.","Optionally pass representativeTest to narrow which test to run (useful for files with multiple tests)."].join("\n"),{testFilePath:ve.string().min(1).describe("Path to the created test file (relative to workspace root)."),representativeTest:la.optional().default({})},async({testFilePath:i,representativeTest:a})=>{const c=ve.string().min(1).parse(i),l=la.parse(a??{}),u={...l,filePath:l.filePath??c},d=wo(c),p=r.join(s,".stably","create-proof",d);Jr.info("[create-trace-proof] Capturing trace",{testFilePath:c});const f=await aa({representativeTest:u,workingDir:s,outputDir:p,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:cr(),headers:cs(r),path:{sessionId:t}},(i.client??Jn).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=Sa.parse(o.data);return{traceBucketPath:a.traceBucketPath,expiresInSeconds:a.expiresInSeconds,key:a.key,uploadUrl:a.uploadUrl,sensitiveValues:a.sensitiveValues}})({authHeader:e,sessionId:t,testFilePath:c,orgId:n})});"captured"===f.status?(await ee(p,{recursive:!0,force:!0}).catch(()=>{}),Jr.info("[create-trace-proof] Upload succeeded",{testFilePath:c,testPassed:f.testPassed,traceBucketPath:f.storage})):Jr.error("[create-trace-proof] Failed",{testFilePath:c,error:f.error});const h={testFilePath:c,status:f.status,storage:"captured"===f.status?f.storage:null,testPassed:"capture_failed"!==f.status?f.testPassed:void 0,testExitCode:"capture_failed"!==f.status?f.testExitCode:void 0,testStderr:"capture_failed"!==f.status?f.testStderr:void 0,..."error"in f?{error:f.error}:{}};return o?.(h),{content:[{type:"text",text:JSON.stringify(h)}]}})]}),Aa=["QUEUED","RUNNING","PASSED","FAILED","TIMEDOUT","CANCELLED","INTERRUPTED"],ka=["LOCAL","CI","WEB"],Ca=["MANUAL","SCHEDULED","UI","API","GITHUB_ACTION","SUITE_RUN"],Pa=({authHeader: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\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(Aa).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(ka).optional().describe("Filter by source: LOCAL|CI|WEB"),trigger:ve.enum(Ca).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:r,status:s,limit:o,source:i,trigger:a,suite:c,after:l,before:u})=>{const d="string"==typeof r?r:void 0,p="string"==typeof s?s:void 0,f="number"==typeof o?o:void 0,h="string"==typeof i?i:void 0,g="string"==typeof a?a:void 0,m="string"==typeof c?c:void 0,y="string"==typeof l?l:void 0,b="string"==typeof u?u:void 0;Jr.info("[run-history] list_runs called",{branch:d,status:p,limit:f});try{const r=await Qn({auth:e,client:cr(),headers:cs(t),query:{projectId:n,branchName:d,status:p,limit:f,source:h,trigger:g,suiteName:m,afterRunId:y,beforeRunId:b}});if(r.error||!r.data){const e=r.response?`API error: ${r.response.status}`:`API error: ${String(r.error)}`;return Jr.error("[run-history] list_runs failed",{error:e}),{content:[{type:"text",text:`Error: ${e}`}],isError:!0}}return Jr.info("[run-history] list_runs success",{runCount:r.data.runs?.length??0,hasMore:r.data.hasMore}),{content:[{type:"text",text:JSON.stringify(r.data)}]}}catch(e){const t=e instanceof Error?e.message:String(e);return Jr.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.\nUse this after list_runs to examine runs where autoHealStatus is "COMPLETED".\n\nThe response includes:\n- Run metadata (status, branch, timestamps)\n- Issues array with result ("fixed"/"unfixed"), rootCause, and relatedTestIdentifiers\n- Test results with their outcomes\n\nUse this to determine which tests were previously fixed and why.',{runId:ve.string().min(1).describe("The run ID to view (required)")},async({runId:n})=>{const r="string"==typeof n?n:String(n);Jr.info("[run-history] view_run called",{runId:r});try{const n=await Xn({auth:e,client:cr(),headers:cs(t),path:{runId:r},query:{detail:"full"}});if(n.error||!n.data){const e=n.response?404===n.response.status?`Run "${r}" not found`:`API error: ${n.response.status}`:`API error: ${String(n.error)}`;return Jr.error("[run-history] view_run failed",{error:e,runId:r}),{content:[{type:"text",text:`Error: ${e}`}],isError:!0}}return Jr.info("[run-history] view_run success",{runId:r}),{content:[{type:"text",text:JSON.stringify(n.data)}]}}catch(e){const t=e instanceof Error?e.message:String(e);return Jr.error("[run-history] view_run exception",{error:t,runId:r}),{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:n})=>{const r=cr();Jr.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??Jn).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 Jr.warn("Subagent definitions fetch failed: unauthorized (401)"),await Er(),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 Jr.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 Jr.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 Jr.debug("Subagent definitions received",{count:Object.keys(i).length}),i},Na=r.dirname($(import.meta.url)),Oa=r.join(".claude-plugin","plugin.json"),Ba=[r.join("packages","agent-plugin","stably-plugin-cli"),r.join("agent-plugin","stably-plugin-cli")];function ja(e){return I(r.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()}),n=e.object({maxTurnsPerIssue:e.number().int().positive().optional(),maxParallelWorkers:e.number().int().positive().optional(),rules:e.string().optional(),skipAfterConsecutiveUnfixed:e.number().int().positive().optional(),maxBudgetUsd:e.number().positive().optional()}),r=e.object({fix:n.optional()}),s=e.object({setupScript:e.string().optional()});return{zStablyYaml:e.object({schedules:e.record(e.string(),t).optional(),agent:r.optional(),cloud:s.optional()}),zAgentConfig:r,zAgentFixConfig:n,zScheduleEntry:t,zCloudConfig:s}}(ge),Fa=async(e,t)=>{try{const n=await gr(e,t);if(!n)return void Jr.debug(`No ${t} found`);const r=await Z(n,"utf-8");if(!r.trim())return;return r.length>1e4?(Jr.warn(`${t} exceeds max length (${r.length} > 10000), truncating`,{path:n}),{content:r.slice(0,1e4),path:n}):(Jr.debug(`Loaded ${t} rules`,{path:n,contentLength:r.length}),{content:r,path:n})}catch(e){return void Jr.warn(`Failed to read ${t}`,{error:e})}},Ha=/\bstably-browser\b/,Ga=/\bpwtrace\b/,Wa=/\bstably-browser\s+run-test\b/,Ya=/\$\{process\.env\.([a-zA-Z_][a-zA-Z0-9_]*)\}/g,Va=e=>/^[A-Za-z0-9_./:@=-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`,za=".stably-browser";async function Ka(){const e=i(o($(import.meta.url)),"pwtrace.js");if(I(e))return e;try{return Ue.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 qa(e,t){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 capture-trace-proof, 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."}:e.includes("ETIMEDOUT")||e.includes("timed out")||e.includes("killed")?{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."}}function Ja(e,t){return t?`${e}-${t}`:e}function Qa(e){if(e&&"object"==typeof e&&"agent_id"in e){const t=e.agent_id;return"string"==typeof t?t:void 0}}var Xa=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"})}),Za=/\bmcp__playwright-mcp__[a-z0-9_]+\b/gi,ec=/\.playwright-mcp(?:\/[^\s"'`)\]]*)?/gi,tc=/\bplaywright[\s_-]?mcp\b/gi;function nc(e){return e.replace(Za,"browser_tool").replace(ec,"verification-artifact").replace(tc,"browser automation")}function rc(e){return{...e,steps:e.steps.map(e=>nc(e)),reason:e.reason?nc(e.reason):null,evidence:e.evidence.map(e=>nc(e))}}function sc(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=Xa.parse(t)}catch{}return n}function oc({mode:e,lastAssistantText:t,maxLength:n=1e4}){const r="verify"===e&&t?nc(t):t;return r?r.slice(0,n):null}var ic=e=>`[38;5;208m${e}[39m`,ac=["Bash","Read","Write","Edit","Glob","Grep","Task","Skill"],cc=["Task","Skill"],lc=["Bash","Read","Write","Edit","Glob","Grep","mcp__session-control"],uc=e=>{if("EPIPE"!==e.code)throw e},dc="__main__",pc=[3e3,5173,4173,8080,4200,8e3],fc=/\b(TEST_EMAIL|TEST_PASSWORD|auth|authentication|credentials|login|log in|sign in)\b/i,hc=/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/i,gc=/playwright[\s_-]?mcp/i,mc=e=>"mcp__auto-heal-report__generate-report"===e;async function yc(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 bc(e){return new Promise(t=>{const n=new z.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 wc=async(e,t,n)=>{const r=n?"[Y/n]":"[y/N]",s=(await e.question(`${q.cyan("?")} ${t} ${q.gray(r)} `)).trim().toLowerCase();return s?"y"===s||"yes"===s:n},vc=async e=>{if("single"===e.mode){const t=Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt;Jr.initSession(t||"create-from-diff")}else if("verify"===e.mode){const t=Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt;Jr.initSession(t||"verify")}else"fix"===e.mode&&Jr.initSession(`fix-${e.runId}`);Jr.info("Agent session starting",{mode:e.mode}),process.stdout.on("error",uc),process.stderr.on("error",uc);const a=e=>{if("EPIPE"!==e.code)throw e};process.on("uncaughtException",a),Jr.debug("Checking authentication");const c=await ss({autoLogin:"chat"===e.mode||"init"===e.mode}),l=is(c);Jr.debug("Authentication resolved",{authType:c.type});const u="oauth"===c.type?c.auth.context.orgId:void 0,d=r.resolve(process.cwd()),p="fix"!==e.mode,f=r.join(d,".env"),h=p&&v.existsSync(f)&&v.statSync(f).isFile(),g=h?t(v.readFileSync(f,"utf8")):{};Jr.debug("Environment file",{path:f,exists:h,variableCount:Object.keys(g).length});const y="chat"!==e.mode&&"init"!==e.mode,b="chat"===e.mode,T="chat"===e.mode||"init"===e.mode,S="single"===e.mode,x="verify"===e.mode,A=S||x;let k,C=new Hs;"init"===e.mode&&(k=e.initPreferences??await async function(){if(!process.stdin.isTTY||!process.stdout.isTTY)return{googleAuth:!0,emailPackage:!1};const e=K({input:process.stdin,output:process.stdout});try{return{googleAuth:await wc(e,"Include Google Auth test helper guidance? (recommended)",!0),emailPackage:await wc(e,"Install @stablyai/email for inbox testing?",!1)}}finally{e.close()}}());const P="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,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&&U&&Jr.info("[verify] Using URL extracted from prompt",{url:U}),"verify"!==e.mode||U||(U=await async function(){for(const e of pc)if(await bc(e))return`http://localhost:${e}`}(),U?Jr.info("[verify] Detected local application URL",{url:U}):Jr.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&&fc.test(e))(r))({envEmail:process.env.TEST_EMAIL??t.TEST_EMAIL,envPassword:process.env.TEST_PASSWORD??t.TEST_PASSWORD,promptIncludesEmail:hc.test(s),stablyMdContent:c}),p=!a;if(!u&&!d&&!p)return{resolvedUrl:l};const f=K({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 wc(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 wc(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:f,envFromFile:g,initialUrl:U,verifyPromptText:R,workingDir:d});U=e.resolvedUrl?.trim()||U}"verify"!==e.mode||U||Jr.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 L={log:[],promptDisplay:V(e).with({mode:"chat"},()=>"Ask Stably to build tests for you").with({mode:"init"},()=>"Setting up Playwright and Stably SDK").with({mode:"fix"},()=>"Fixing broken tests").with({mode:"single"},e=>{const t=(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt)?.trim();return t||"Creating tests from PR/branch changes"}).with({mode:"verify"},e=>{const t=(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt)?.trim();return t||"Verifying application"}).exhaustive(),status:"running"};let D,N,O,B,j=y,M=!1,F=0,H=[],z=!1,J=!1,X=0;const ee=new Map,te=[],ne=e=>{te.push(e)},re=new Map;let se=null,oe=!1,ie=!1;const ae=Date.now();let ce,le="fix"===e.mode?{suiteId:e.runId,phase:"initializing",totalTests:null,fixedTests:0,failedTests:0,currentTestDescription:null,lastTestDescription:null,startedAt:ae,endedAt:null,isError:!1,updatedAt:ae,recentActivity:[],workers:[{id:dc,testDescription:"Orchestrator",workerType:"main",status:"running",summary:null,startedAt:ae,endedAt:null,activity:[]}]}:null;const ue=new Set,de=(e,t)=>{if(!le)return;const n=le.workers.map(n=>{if(n.id!==e)return n;const r=[...n.activity,{...t,timestamp:Date.now()}].slice(-15);return{...n,activity:r}});he({workers:n})},pe=e=>{if(!le)return;const t=[...le.recentActivity,{...e,timestamp:Date.now()}].slice(-10);he({recentActivity:t})},fe=e=>(le?.workers??[]).map(t=>t.id===dc?{...t,status:e?"failed":"succeeded",endedAt:t.endedAt??Date.now()}:"running"===t.status?{...t,status:"failed",endedAt:Date.now()}:t),he=e=>{le&&!ce?.isClosed&&(le={...le,...e,updatedAt:Date.now()},ce?.sendProgress(le))},ge=async t=>{if("fix"===e.mode){if("STARTED"===t){if(oe)return;oe=!0}else{if(ie)return;ie=!0}try{await(async({authHeader:e,orgId:t,runId:n,status:r})=>{const s=await(o={auth:e,body:{status:r},client:cr(),headers:cs(t),path:{runId:n}},(o.client??Jn).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:l,orgId:u,runId:e.runId,status:t})}catch{}}},me=Date.now();let ye,be=null;const we=e=>{be&&!ye?.isClosed&&(be={...be,...e,updatedAt:Date.now()},ye?.sendProgress(be))},Ie=e=>{if(!be)return;const t=[...be.recentActivity,{...e,timestamp:Date.now()}].slice(-10);we({recentActivity:t})};let Ce;const Re=(e.mode,!0);Jr.info("[session] Checking session creation",{mode:e.mode,shouldCreateSession:Re});try{Jr.info("[session] Creating progress session",{mode:e.mode,projectId:os(c)});const t=await async function({agentMode:e,authHeader:t,orgId:n,projectId:r,runId:s,fetchImpl:o=fetch,apiUrl:i=er}){const a=qs[e],c=new URL("/internal/v1/cli/progress",i).toString(),l={Authorization:t,"Content-Type":"application/json"};n&&(l["x-stably-org-id"]=n);const u=await o(c,{method:"POST",headers:l,body:JSON.stringify({mode:a,projectId:r,agentId:Q.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}}({agentMode:e.mode,authHeader:l,orgId:u,projectId:os(c),..."fix"===e.mode?{runId:e.runId}:{}}),{sessionId:n,sessionMode:r}=t;if(Ce=n,A){const t="single"===e.mode||"verify"===e.mode?Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt:null,r=Gs(d);be={sessionId:n,phase:"initializing",startedAt:me,endedAt:null,isError:!1,updatedAt:me,currentActivity:null,filesCreated:[],traceProofs:[],recentActivity:[],prompt:t||null,environment:{gitBranch:r?.branch??null,workingDirectory:d,nodeVersion:process.version,cliVersion:Zn}},ye=new ys({authHeader:l,orgId:u,sessionId:n,onUserMessage:e=>{C&&(Jr.info("[ws] Injecting web UI message into agent",{contentLength:e.length}),Ie({type:"user_message",summary:e}),Ye({text:`[Web] ${e}`}),C.pushText(`[Message from web UI user]: ${e}`),j||(j=!0,rt({status:"running"})))}}),ye.start(),we({phase:"initializing"})}Jr.info(`[${r}] Progress session created`,{sessionId:n})}catch(e){const t=e instanceof Error?e.message:String(e);Jr.warn(`[progress] Session creation failed (non-fatal): ${t}`)}const $e={current:e=>{}},Le={current:async()=>{}};let De;const Ne={current:()=>{}};let Oe=!1,Be=!1;const{addSubagentActivity:je,addSubagentStart:Me,addTool:Fe,appendCancelled:He,appendText:Ge,appendThinking:We,appendUserMessage:Ye,cancelThinkingRender:Ve,cleanup:ze,dismissPermissionPrompt:Ke,flushThinkingRender:qe,resetThinkingLogIndex:Je,setExiting:Qe,setRunningLabel:Xe,setStatus:Ze,setSubagentStatus:et,updateFixProgress:tt}=await(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=()=>Ae(s,{inverse:!0,children:" "}),d=(({Box:e,Text:t,useInput:n},r,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"}];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=fo(i.toolName),g=uo(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(r,{})]})]}:{flexDirection:"column",marginTop:1,children:[Ae(t,{color:"gray",children:"Use ββ arrows or number keys to select:"}),f.map((e,n)=>Ae(t,{children:ke(t,{color:n===a?"cyan":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?ke(r,{color:"gray",dimColor:!0,children:["β’ ",e.content]},e.id):"tool_result"===e.kind||"text"===e.kind?Ae(r,{color:"gray",children:e.content},e.id):null,u=({progress:e})=>{const[n,s]=Te(Date.now());Ee(()=>{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`,{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(r,{children:[Ae(r,{color:p,bold:!0,children:d}),Ae(r,{color:"gray",children:h}),ke(r,{color:"gray",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?"#FFA500":"green",l=e.isError?"Fix stopped":"Fix complete";return ke(t,{flexDirection:"column",children:[ke(r,{color:c,bold:!0,children:[l," in ",a]}),null!==e.totalTests&&ke(r,{color:"gray",children:[e.fixedTests,"/",e.totalTests," tests fixed",e.failedTests>0?`, ${e.failedTests} failed`:""]})]})},p=(e,n=!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(r,{children:[Ae(r,{color:o,bold:!0,children:"Agent"}),s.description?ke(r,{color:"gray",children:[" (",s.description,")"]}):null]}),s.activities.length>0&&Ae(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<=y&&t.unshift(r))}return t.map(e=>l(e))})()})]},e.id)}if("tool"===e.kind)return ke(r,{color:"gray",dimColor:!0,children:["β’ ",e.content]},e.id);if("tool_result"===e.kind)return Ae(r,{color:"gray",children:e.content},e.id);if("user"===e.kind)return ke(r,{color:"cyan",children:["You: ",e.content]},e.id);if("thinking"===e.kind){const n=e.content.split("\n"),s=10,o=n.length>s?n.slice(-s):n;return Ae(t,{flexDirection:"column",children:Ae(r,{color:"gray",dimColor:!0,children:o.join("\n")})},e.id)}return"cancelled"===e.kind?Ae(r,{color:"gray",dimColor:!0,children:e.content},e.id):Ae(r,{children:e.content},e.id)},f=(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},h=(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},g=(e,t)=>{if(t<=0)return 0;const n=e.lastIndexOf("\n",t-1);return-1===n?0:n+1},m=(e,t)=>{const n=e.indexOf("\n",t);return-1===n?e.length:n},y=3;return function({onCancel:c,onExit:l,onPermissionChoice:b,onSend:w,showSpinnerImmediately:v,state:I}){const[T,_]=Te({value:"",cursor:0}),E=T.value,S=T.cursor,x=_e(!1),A=_e(void 0),[k,C]=Te(!1),[P,R]=Te(!1),U=_e(0),$=_e(!1),L=!!I.permissionPrompt,D=(({termProgram:e})=>"vscode"===e)({termProgram:process.env.TERM_PROGRAM}),N=I.log.at(-1),O=("text"===N?.kind||"thinking"===N?.kind)&&"running"===I.status,B=I.log.findIndex(e=>"subagent"===e.kind&&"running"===e.subagent?.status),j=-1!==B,M=I.activeThinkingLogIndex??-1,F=M>=0&&M<I.log.length-1,H=o&&!P,G=D?0:j?B:F?M:O?I.log.length-1:I.log.length,W=H&&"running"===I.status?Math.min(G,U.current):G;Ee(()=>{I.log.length<U.current&&(U.current=0),W>U.current&&(U.current=W)},[I.log.length,W]);const Y=I.log.slice(0,U.current),V=I.log.slice(U.current),z=H?Y.filter(e=>"tool"!==e.kind&&"tool_result"!==e.kind&&"thinking"!==e.kind):Y,K=(()=>{if(!H)return V;let e=0;const t=[];for(let n=V.length-1;n>=0;n--){const r=V[n];"tool"===r.kind||"tool_result"===r.kind||"thinking"===r.kind?("tool"===r.kind&&e++,e<=y&&t.unshift(r)):t.unshift(r)}return t})(),q=Se(async()=>{x.current?(A.current&&clearTimeout(A.current),await(l?.()),process.exit(0)):(x.current=!0,C(!0),A.current=setTimeout(()=>{x.current=!1,C(!1)},2e3))},[l]);s((e,t)=>{t.ctrl&&"c"===e&&q().catch(()=>process.exit(1)),t.ctrl&&"o"===e&&R(e=>!e),t.escape&&"running"===I.status&&!L&&0===E.length&&c?.()},{isActive:o}),Ee(()=>{if(L||!w)return;process.stdout.isTTY&&process.stdout.write("[?2004h");const e=e=>{const t=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n");t&&_(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~")){$.current=!0;const t=n.slice(n.indexOf("[200~")+6),r=t.includes("[201~"),s=r?t.slice(0,t.indexOf("[201~")):t;return r&&($.current=!1),void e(s)}if(n.includes("[201~")){const t=n.slice(0,n.indexOf("[201~"));return e(t),void($.current=!1)}$.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||_(e=>({...e,cursor:m(e.value,e.cursor)})):_(e=>({...e,cursor:g(e.value,e.cursor)})):_(e=>({...e,cursor:e.value.length})):_(e=>({...e,cursor:0}))};return process.stdin.on("data",t),()=>{process.stdin.off("data",t),process.stdout.isTTY&&process.stdout.write("[?2004l")}},[L,w]),s((e,t)=>{if(!t.ctrl||"c"!==e){if(t.return){if($.current)return;const e=E.trim();return e&&w?.(e),void _({value:"",cursor:0})}t.ctrl&&"w"===e||t.ctrl&&t.backspace?_(e=>{const t=f(e.value,e.cursor);return{value:e.value.slice(0,t)+e.value.slice(e.cursor),cursor:t}}):!t.backspace&&!t.delete||t.ctrl?t.ctrl&&t.leftArrow||t.meta&&"b"===e?_(e=>({...e,cursor:f(e.value,e.cursor)})):t.ctrl&&t.rightArrow||t.meta&&"f"===e?_(e=>({...e,cursor:h(e.value,e.cursor)})):t.leftArrow?_(e=>({...e,cursor:Math.max(0,e.cursor-1)})):t.rightArrow?_(e=>({...e,cursor:Math.min(e.value.length,e.cursor+1)})):t.ctrl&&"a"===e?_(e=>({...e,cursor:0})):t.ctrl&&"e"===e?_(e=>({...e,cursor:e.value.length})):t.escape&&E.length>0?_({value:"",cursor:0}):!e||t.ctrl||t.meta||t.escape||e.includes("")||/^\[./.test(e)||/^O[A-D]$/.test(e)||_(t=>({value:t.value.slice(0,t.cursor)+e+t.value.slice(t.cursor),cursor:t.cursor+e.length})):_(e=>e.cursor>0?{value:e.value.slice(0,e.cursor-1)+e.value.slice(e.cursor),cursor:e.cursor-1}:e)}},{isActive:o&&!!w&&!L});const J=xe(()=>"running"===I.status?Ae(a,{label:I.runningLabel??"Working"}):"success"!==I.status?Ae(r,{color:"red",children:"β Failed"}):void 0,[I.runningLabel,I.status]),Q=!(v||!w||"running"!==I.status||0!==I.log.length||I.resultText||I.errorText),X="running"===I.status&&!Q||I.log.length>0||I.resultText||I.errorText||"running"!==I.status;return ke(t,{flexDirection:"column",children:[D?ke(t,{flexDirection:"column",flexShrink:0,children:[Ae(r,{color:"cyan",bold:!0,children:"Stably Agent"}),Ae(t,{flexDirection:"column",marginTop:1,children:Ae(r,{color:"gray",children:I.promptDisplay})})]}):Ae(n,{items:["header"],children:()=>ke(t,{flexDirection:"column",flexShrink:0,children:[Ae(r,{color:"cyan",bold:!0,children:"Stably Agent"}),Ae(t,{flexDirection:"column",marginTop:1,children:Ae(r,{color:"gray",children:I.promptDisplay})})]},"header")}),z.length>0&&Ae(n,{items:z,children:e=>p(e,H)}),K.length>0&&Ae(t,{flexDirection:"column",children:K.map(e=>p(e,H))}),H&&V.length>K.length&&ke(r,{color:"gray",dimColor:!0,children:["β ",V.length-K.length," tool calls hidden (Ctrl+O to expand)"]}),P&&o&&"running"===I.status&&Ae(r,{color:"gray",dimColor:!0,children:"β Showing all tool calls (Ctrl+O to collapse)"}),"error"===I.status&&I.errorText&&Ae(t,{marginTop:1,children:Ae(r,{color:"red",children:I.errorText})}),"success"===I.status&&I.resultText&&Ae(t,{marginTop:1,children:Ae(r,{children:I.resultText})}),X&&Ae(t,{flexDirection:"column",flexShrink:0,marginTop:1,children:"running"===I.status&&I.fixProgress?ke(t,{flexDirection:"column",children:[ke(t,{children:[Ae(a,{}),Ae(r,{children:" "}),Ae(u,{progress:I.fixProgress})]}),("fixing"===I.fixProgress.phase||"debugging"===I.fixProgress.phase)&&I.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 ke(t,{flexDirection:"column",children:[ke(r,{children:[" ",Ae(a,{}),ke(r,{color:"gray",children:[n.description||n.subagentType||"worker",o>0?` (${o} ${1===o?"cycle":"cycles"})`:""]})]}),c&&ke(r,{color:"gray",dimColor:!0,children:[" β’ ",c.content]}),l&&ke(r,{color:"gray",dimColor:!0,children:[" ",l]})]},e.id)})]}):"success"!==I.status&&"error"!==I.status||!I.fixProgress?J:Ae(d,{progress:I.fixProgress})}),null!=I.permissionPrompt&&null!=b&&Ae(i,{onChoice:b,prompt:I.permissionPrompt}),null!=w&&null==I.permissionPrompt&&!I.isExiting&&ke(t,{borderColor:"gray",borderStyle:"round",flexDirection:"column",flexShrink:0,marginTop:1,paddingX:1,paddingY:0,children:[Ae(r,{color:"gray",children:"Type a message and press Enter. Press Escape to interrupt. Press Ctrl+C to exit."}),ke(r,{children:[Ae(r,{color:"#FFA500",children:">"})," ",E.slice(0,S),Ae(e,{}),E.slice(S)]})]}),k&&ke(t,{marginTop:1,flexDirection:"column",children:[Ae(r,{color:"#FFA500",children:"Press Ctrl+C again to exit"}),Br&&ke(r,{color:"gray",children:["Debug log: ",Hr]})]})]})}})({Cursor:u,inkComponents:{Box:n,Static:r,Text:s,useInput:i},isRawModeSupported:a,PermissionPrompt:d,Spinner:({label:e})=>{const[t,n]=Te(0);return Ee(()=>{if(!c)return;const e=setInterval(()=>n(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: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??fo(e),s=n?void 0:uo(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}})(L,"init"===e.mode?{onCancel:()=>Ne.current(),onExit:()=>Le.current(),onSend:e=>$e.current(e),showSpinnerImmediately:!0}:"chat"===e.mode?{onCancel:()=>Ne.current(),onExit:()=>Le.current(),onSend:e=>$e.current(e)}:"fix"===e.mode?{onExit:()=>Le.current(),isFixMode:!0}:{onExit:()=>Le.current()});let nt=L.status;const rt=({error:e,result:t,status:n})=>{nt=n,Ze({error:e,result:t,status:n})};let st;x&&(Ge({text:"Starting verification...\n"}),Ge(U?{text:`Target URL: ${U}\n`}:{text:"Target URL: auto-detect (agent may infer from project config)\n"}),Xe({label:"Calibrating verification flow..."})),$e.current=e=>{const t=e.trim();if(b&&!Jr.getLogFilePath()&&Jr.initSession(t||"chat"),Jr.debug("User message",{text:t}),"/help"===t){j&&C&&(M=!0,D?.interrupt?.(),C.allowNextTurn(),j=!1),"running"===nt&&rt({status:"success"}),Ye({text:e});const t=P?.();return void Ge({text:t??"Help is not available in this session."})}if(b&&Xe({label:void 0}),C){if(j)return rt({status:"running"}),Ye({text:e}),C.pushText(e),void(F+=1);rt({status:"running"}),Ye({text:e}),ne({role:"user",content:e,timestamp:(new Date).toISOString()}),C.pushText(e),j=!0}};let ot="",it="";const at=[],ct=[],lt=[];let ut;const dt=await(async e=>{try{const t=await gr(e,"stably.yaml");if(!t)return void Jr.debug("No stably.yaml found");const n=await Z(t,"utf-8");if(!n.trim())return;const r=Pe(n),s=Ma.parse(r.toJS()),o=s.agent?.fix?.maxTurnsPerIssue,i=s.agent?.fix?.maxParallelWorkers,a=!!s.agent?.fix?.rules;return Jr.debug(`Loaded stably.yaml: maxTurnsPerIssue=${o??"default"}, maxParallelWorkers=${i??"default"}, hasRules=${a}`,{path:t,config:s.agent}),s}catch(e){return void Jr.warn("Failed to parse stably.yaml",{error:e})}})(d),pt=dt?.agent?.fix?.skipAfterConsecutiveUnfixed,ft=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 to(e,"output-flag"),{path:e,source:"output-flag"}}const r=Xs(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(eo(t))return to(t,"playwright.config.ts"),{path:t,source:"playwright.config.ts"}}}for(const e of Zs){const t=i(n,e);if(eo(t))return to(t,"auto-detected"),{path:t,source:"auto-detected"}}return to(n,"cwd-fallback"),{path:n,source:"cwd-fallback"}}(d,e.outputDir);return ut=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: ${ut}]`}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,U);if("fix"===e.mode)try{Jr.info("[fix] Fetching autoheal context",{runId:e.runId,skipAfterConsecutiveUnfixed:pt});const t=Date.now(),{context:n,autohealReportUrl:r,skippedTests:s,newerPassingSuiteId:o}=await(async({authHeader:e,orgId:t,runId:n,skipAfterConsecutiveUnfixed:r})=>{Jr.debug("Fetching autoheal context",{runId:n,skipAfterConsecutiveUnfixed:r});const s=await(o={auth:e,client:cr(),headers:cs(t),path:{runId:n},query:null!=r?{skipAfterConsecutiveUnfixed:r}:{}},(o.client??Jn).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-context",...o}));var o;if(404===s.response.status)throw Jr.warn("Autoheal context not found",{runId:n,status:404}),new Error(`Run ID "${n}" was not found.`);if(401===s.response.status)throw Jr.warn("Autoheal context fetch unauthorized",{runId:n,status:401}),new Error("Unauthorized: failed to fetch autoheal context (401).");if(422===s.response.status)throw Jr.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=ls.safeParse(s.data);if(e.success)return Jr.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};throw Jr.warn("Autoheal context response invalid",{runId:n}),new Error("Autoheal context response missing or invalid context.")}throw Jr.warn("Autoheal context fetch failed",{runId:n,error:s.error}),new Error("Failed to fetch autoheal context")})({authHeader:l,orgId:u,runId:e.runId,skipAfterConsecutiveUnfixed:pt});if(Jr.info("[fix] Autoheal context fetched",{runId:e.runId,durationMs:Date.now()-t,contextLength:n.length,skippedTestCount:s.length}),st=r,s.length>0){Jr.info(`[fix] Skipping ${s.length} test(s) that failed to be fixed ${pt}+ consecutive times`);for(const e of s)Jr.info(`[fix] Skipped: ${e.testIdentifier} β ${e.testTitle} (unfixed ${e.consecutiveUnfixedCount}x)`)}return o&&(Jr.info("[fix] Tests already passing in a newer run",{newerPassingSuiteId:o}),rt({status:"success",result:`Tests already passing in a newer run (${o}). Nothing to fix.`}),await ze(),process.exit(0)),n.includes("No failing tests to fix (all were skipped).")&&(Jr.info("[fix] All failing tests were skipped β nothing to fix"),rt({status:"success",result:`All failing tests skipped (unfixed ${pt}+ consecutive times). Nothing to fix.`}),await ze(),process.exit(0)),ce||(Jr.info("[fix] Creating WebSocket progress reporter"),ce=new ms({authHeader:l,orgId:u,runId:e.runId,onUserMessage:e=>{if(Jr.info("[ws] Injecting web UI message into fix agent",{contentLength:e.length}),de(dc,{type:"user_message",summary:e}),pe({type:"user_message",summary:e}),Ye({text:`[Web] ${e}`}),!j)return C.pushText(`[Message from web UI user]: ${e}`),j=!0,void C.allowNextTurn();z||Date.now()-X<2e3?C.pushText(`[Message from web UI user]: ${e}`):(H.push(e),O&&clearTimeout(O),O=setTimeout(()=>{O=void 0;const e=[...H];H=[],X=Date.now(),pn(e)},500))}}),ce.start(),he({phase:"initializing"})),ge("STARTED"),n}catch(e){const t=e instanceof Error?e.message:"Failed to fetch autoheal context.";Jr.error("[fix] Failed to fetch autoheal context",{error:t}),rt({error:t,status:"error"}),await ze(),process.exit(1)}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""})(),ht=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(I(t))for(const e of Ws){const n=r.join(t,`playwright.config${e}`);if(I(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([zs({defaultContent:"Unable to read directory",dirName:"working directory",dirPath:t}),zs({defaultContent:"Unable to read directory",dirName:"tests directory",dirPath:n}),zs({defaultContent:"Directory does not exist yet",dirName:"helpers directory",dirPath:s}),zs({defaultContent:"Directory does not exist yet",dirName:"assets directory",dirPath:o}),Vs({defaultContent:"File does not exist or could not be read",fileName:a,filePath:i}),Vs({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),gt="fix"===e.mode?dt?.agent?.fix?.maxTurnsPerIssue:void 0,mt=dt?.agent?.fix?.maxParallelWorkers??3,yt="fix"===e.mode?dt?.agent?.fix?.rules:void 0,bt=dt?.agent?.fix?.maxBudgetUsd??50,wt="verify"===e.mode?e.maxBudgetUsd??5:void 0,vt="fix"===e.mode?bt:x?wt:void 0,It="init"!==e.mode,Tt="single"===e.mode?await(async e=>{const t=await Fa(e,"STABLY-CREATE.md");return t?.content})(d):void 0,_t=await(e=>Fa(e,"STABLY.md"))(d),Et=_t?.content;x&&(Xe({label:"Assembling verification context..."}),Ge({text:"Assembling workspace context...\n"})),Jr.info("[fix] Fetching system prompt and subagent definitions",{mode:e.mode,maxTurnsOverride:gt,maxBudgetUsd:vt,hasCustomRules:!!yt,hasCreateRules:!!Tt,hasStablyMd:!!Et,stablyMdPath:_t?.path}),_t&&Jr.info(`STABLY.md loaded (${_t.content.length} chars)`,{path:_t.path});const St=await as(),xt=St?Object.keys(St.variables):[],At=[...new Set([...Object.keys(g),...xt])],kt=Date.now(),[{systemPrompt:Ct,prContext:Pt},Rt]=await Promise.all([Ks({allowedEnvVars:At,mode:e.mode,workspaceInfo:ht,authHeader:l,customHeader:"single"===e.mode?e.customHeader:void 0,maxParallelWorkers:mt}),It?Da({authHeader:l,mode:e.mode,maxTurnsOverride:gt}):Promise.resolve({})]);Jr.info("[fix] System prompt and subagents fetched",{durationMs:Date.now()-kt,systemPromptSize:Ct.length,subagentCount:Object.keys(Rt).length,maxTurnsOverride:gt??"default",hasPrContext:!!Pt});const Ut=function(e){const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(La.has(n)||$a.some(e=>n.startsWith(e))||(t[n]=r));return t}({...g,...process.env}),$t=!0;Jr.debug("AI proxy configuration",{useStablyAiProxy:$t,wantsBypassProxy:!1,wantsUseOllama:!1}),Jr.info("[fix] Acquiring AI proxy key",{useStablyAiProxy:$t});const Lt=Date.now(),Dt=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??Jn).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:l,client:cr(),source:"cli"}),Nt=Dt?.key;if(Jr.info("[fix] AI proxy key acquired",{durationMs:Date.now()-Lt,success:!!Nt,hasError:!!Dt?.error}),!Nt){const e=Dt?.error?.message?`Unable to make AI calls: ${Dt.error.message}`:"Unable to make AI calls. Check if you are authenticated.";Jr.warn("Failed to get proxy API key",{error:Dt?.error?.message}),rt({error:e,status:"error"}),await ze(),Jr.flush(),Jr.printLogFileInfo(),process.exit(1)}Jr.debug("Proxy API key acquired",{success:!!Nt});const Ot="init"===e.mode,Bt="fix"===e.mode,jt=Ot?void 0:function(e){let t,n;!function(e){const t=i(e,".gitignore");try{if(I(t)){const e=_(t,"utf-8"),n=e.split("\n").map(e=>e.trim());if(n.includes(za)||n.includes(`/${za}`))return;const r=e.length>0&&!e.endsWith("\n");E(t,`${r?"\n":""}${za}\n`)}}catch{}}(process.cwd());const r=new Set;let s;const a=()=>{var t;return s||(s="auto"!==(t=e.sessionName)?t:`stably-${process.pid}`),s};return{hook:async s=>{const c=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(c)&&!Ga.test(c))return{decision:"approve"};if(Ga.test(c)&&!Ha.test(c)){if(!n)try{n=await Ka(),Jr.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:c.replace(/\b(?:npx\s+)?pwtrace\b/g,e)}}}}if(Ga.test(c)&&!n)try{n=await Ka(),Jr.info("[pwtrace-hook] Resolved binary (mixed command)",{path:n})}catch{}const l=/\bstably-browser\s+close\b/.test(c),u=/\bstably-browser\s+(?!close\b)\w/.test(c);if(l){if(!u&&0===r.size)return{decision:"approve"};const e=Qa(s),t=Ja(a(),e);r.delete(t)}if(!t)try{t=await async function(){const e=i(o($(import.meta.url)),"stably-browser.js");if(I(e))return e;try{return Ue.resolve("@stablyai-internal/playwright-cli/playwright-cli.js")}catch{}return new Promise((e,t)=>{m("which",["stably-browser"],(n,r)=>{!n&&r.trim()?e(r.trim()):t(new Error("stably-browser not found. Ensure @stablyai-internal/playwright-cli is installed or stably-browser is on PATH."))})})}(),Jr.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:`stably-browser binary not found: ${t}`}}const d=Qa(s),p=Ja(a(),d),f=/\bstably-browser\s+open\b/.test(c);if((!l||u)&&!r.has(p))if(f)r.add(p);else{r.add(p),Jr.info("[stably-browser-hook] First browser command, starting daemon...",{sessionName:p,agentId:d});const n=await async function(e,t,n){const r=["open",`-s=${t}`];n&&r.push("--headed"),r.push("--browser=chromium"),Jr.info("[stably-browser-hook] Starting daemon",{bin:e,args:r});const s=process.env.CHROME_BIN?{...process.env,PLAYWRIGHT_MCP_EXECUTABLE_PATH:process.env.CHROME_BIN}:void 0;return new Promise(t=>{m(process.execPath,[e,...r],{timeout:3e4,env:s},(e,n,r)=>{if(e)return Jr.error("[stably-browser-hook] Failed to start daemon",{error:e.message,stderr:r}),void t({ok:!1,...qa(e.message,r??"")});Jr.info("[stably-browser-hook] Daemon started",{stdout:n.trim()}),t({ok:!0})})})}(t,p,e.headed);if(!n.ok)return r.delete(p),{decision:"block",reason:`Failed to start stably-browser daemon: ${n.reason}`,systemMessage:n.guidance}}const h=`${process.execPath} ${t}`;let g=c.replace(/\b(?:npx\s+)?stably-browser\b/g,h);if(Ga.test(g)&&n){const e=`${process.execPath} ${n}`;g=g.replace(/\b(?:npx\s+)?pwtrace\b/g,e)}const y=[];g.includes("-s=")||g.includes("--session=")||y.push(`-s=${p}`),e.headed&&!g.includes("--headed")&&y.push("--headed"),y.length>0&&(g=g.replaceAll(h,`${h} ${y.join(" ")}`)),e.envVars&&(g=g.replace(Ya,(t,n)=>{const r=e.envVars[n];return null!=r?r:t}));const b=[];if(Wa.test(c)&&e.envVars)for(const[t,n]of Object.entries(e.envVars))b.push(`${t}=${Va(n)}`);return b.length>0&&(g=`${b.join(" ")} ${g}`),Jr.debug("[stably-browser-hook] Rewritten command",{original:c.slice(0,100),sessionName:p,agentId:d,envVarCount:b.length}),{decision:"approve",hookSpecificOutput:{hookEventName:"PreToolUse",updatedInput:{command:g}}}},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&&Jr.debug("[stably-browser-hook] Failed to stop daemon",{error:t.message,sessionName:r}),e()})});var n,r})),r.clear())}}}({sessionName:process.env.STABLY_PLAYWRIGHT_SESSION??(Bt?"auto":"default"),headed:!("chat"!==e.mode||process.env.CI||"linux"===process.platform&&!process.env.DISPLAY),envVars:{...g,...St?.variables}}),Mt=Bt?kn.createLocal({workingDir:d}):void 0;Mt&&await Mt.captureSnapshot();const Ft=()=>{Ot&&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 va(e,t))if(ha(n))return n}(e,t),s=ya(ga(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(ma(n.dirname(r)));return ya(Array.from(t))}(ga(e,/\.(spec|test)\.(ts|js)$/)),i=s.length>0?s:o,a=r??(1===i.length?i[0]:void 0)??e,c=wa(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=wa(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=pa(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)Jr.debug("stably package already present in dependencies");else{Jr.info("stably package missing from devDependencies, installing...");try{da({workingDir:e,packageManager:Ta(e),packageSpec:"stably",targetSection:"devDependencies"}),Jr.info("stably package installed successfully")}catch(e){Jr.warn("Failed to install stably package",{error:String(e)})}}}(r.targetDir)}catch(e){Jr.warn("Post-init: ensureStablyDependency failed",{error:String(e)})}try{!function(e){const t=pa(e);if(!t)return;const n=t.contents.devDependencies?.playwright??t.contents.dependencies?.playwright;if(n)if(Ia(n)!==Is)try{da({workingDir:e,packageManager:Ta(e),packageSpec:`playwright@${Is}`,targetSection:t.contents.devDependencies?.playwright?"devDependencies":"dependencies"}),Jr.info("standalone playwright version aligned successfully",{version:Is})}catch(e){Jr.warn("Failed to align standalone playwright version",{error:String(e)})}else Jr.debug("standalone playwright already at supported version",{version:Is});else Jr.debug("standalone playwright package not present")}(r.targetDir)}catch(e){Jr.warn("Post-init: alignStandalonePlaywrightVersion failed",{error:String(e)})}try{!function(e){const t=pa(e);if(t)if(Ia(t.contents.devDependencies?.["@playwright/test"]??t.contents.dependencies?.["@playwright/test"])!==Is)try{Jr.info(`Updating @playwright/test to supported version ${Is}...`),da({workingDir:e,packageManager:Ta(e),packageSpec:`@playwright/test@${Is}`,targetSection:t.contents.dependencies?.["@playwright/test"]?"dependencies":"devDependencies"}),Jr.info("@playwright/test updated successfully")}catch(e){Jr.warn("Failed to update @playwright/test",{error:String(e)})}else Jr.debug("@playwright/test already at supported version",{version:Is});else Jr.debug("No package.json found, skipping @playwright/test update")}(r.targetDir)}catch(e){Jr.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 va(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 Jr.debug("Agent guidance already present",{file:n.relative(e,r)||o});if(ba(i))return r}if(t)return t}return n.join(e,"AGENTS.md")}(e,t);if(i){Jr.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"),Jr.info("Agent guidance appended successfully")}catch(e){Jr.warn("Failed to update agent guidance file",{error:String(e)})}}}(r.targetDir,r.repoRoot,t)}catch(e){Jr.warn("Post-init: ensureAgentGuidance failed",{error:String(e)})}}else Jr.warn("Post-init: could not resolve target package directory; skipping verification",{workingDir:e})}({workingDir:d,options:{googleAuth:k?.googleAuth,emailPackage:k?.emailPackage}})},Ht=Ot?(({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 n="string"==typeof t?t:String(t);return e(),Promise.resolve(`Session complete: ${n}`)})]}))({onComplete:()=>{Ft(),rt({status:"success"}),Qe(),C?.finish(),process.exit(0)}}):void 0,Gt=Ht?{"session-control":Ht}:{},Wt=S&&Pt?["mcp__create-report"]:[],Yt=S&&Ce?["mcp__create-trace-proof"]:[],Vt=Ot?lc:x?ac:[...ac,...Bt?["mcp__auto-heal-report"]:[],...Wt,...Yt],zt=Ot?lc:b?[...cc,"mcp__stably-agent-control"]:x?cc:[...cc,...Wt,...Yt],Kt=S&&Pt?{"create-report":Ea({prContext:Pt,authHeader:l,orgId:u,onReportPosted:e=>{we({githubComment:{url:e.commentUrl,prNumber:Pt.prNumber}})}})}:{},qt=S&&Ce?{"create-trace-proof":xa({authHeader:l,sessionId:Ce,orgId:u,workingDir:d,onTraceProofCaptured:e=>{we({traceProofs:[...be?.traceProofs??[],e]})}})}:{},Jt=Ot?Gt:Bt&&Mt?{"auto-heal-report":ua({authHeader:l,diffTracker:Mt,orgId:u,runId:e.runId,workingDir:d}),"run-history":Pa({authHeader:l,orgId:u,projectId:os(c)}),...Gt}:{...Gt,...Kt,...qt},Qt="single"===e.mode,Xt=Ot?[]:Qt?[{matcher:"Write",hooks:[js({onFileCreated:e=>{if(at.includes(e)||at.push(e),be){if(be.filesCreated.some(t=>"string"==typeof t?t===e:t.path===e))return;const t=r.isAbsolute(e)?e:r.join(d,e),n=r.basename(e),{sessionId:s}=be,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:cr(),headers:cs(s),path:{sessionId:o}},(a.client??Jn).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=bs.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 ds({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:cr(),headers:cs(s),path:{sessionId:o}},(a.client??Jn).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 Jr.warn("Failed to upload automation file",{error:e instanceof Error?e.message:String(e)}),null}})({authHeader:l,content:r,contentType:"text/plain",filename:n,filePath:e,orgId:u,sessionId:s}),i={path:e,filename:n,bucketPath:o};ct.push(i),we({filesCreated:[...ct]})}catch(t){Jr.warn("Failed to upload created file",{filePath:e,error:t instanceof Error?t.message:String(t)});const r={path:e,filename:n,bucketPath:null};ct.push(r),we({filesCreated:[...ct]})}})();lt.push(o)}}})]}]:[],Zt=Ot?[]:[...Bt?[{matcher:"Read",hooks:[Ss({action:"reading",pathKey:"file_path"})]},{matcher:"Write",hooks:[Ss({action:"writing",pathKey:"file_path"})]},{matcher:"Edit",hooks:[Ss({action:"editing",pathKey:"file_path"})]},{matcher:"Grep",hooks:[Ss({action:"searching",pathKey:"path"})]},{matcher:"Glob",hooks:[Ss({action:"searching",pathKey:"path"})]},{matcher:"Bash",hooks:[Os({workspaceBoundary:d})]}]:[],...jt?[{matcher:"Bash",hooks:[jt.hook]}]:[]],en=Object.keys(Rt).length>0?Rt:void 0,tn={...Ut};tn.MCP_TOOL_TIMEOUT=String(6e5),Nt&&(tn.ANTHROPIC_API_KEY=Nt,tn.ANTHROPIC_BASE_URL=sr,tn.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS="1",tn.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC="1");const nn=process.env.STABLY_AGENT_MODEL??"claude-opus-4-6",rn=Bt?"env"===c.type?c.auth.apiKey:c.auth.accessToken:void 0,sn=Bt?os(c):void 0;Bt&&rn&&sn&&(tn.STABLY_API_KEY=rn,tn.STABLY_PROJECT_ID=sn);const on=yt?`\n\n## Custom Rules\n${yt}`:"",an=Tt?`\n\n## Custom Test Generation Rules\n${Tt}`:"",cn=Et?`\n\n## Project Rules (STABLY.md)\n${Et}`:"",ln=Ct+on+an+cn;Jr.debug("[fix] Final system prompt assembled",{baseSize:Ct.length,fixRulesSize:on.length,createRulesSize:an.length,stablyMdSize:cn.length,finalSize:ln.length});const un=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 ja(t)?t:void 0}();if(e)return e;const t=r.join(Na,"stably-plugin-cli");if(ja(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}}(Na))for(const t of Ba){const n=r.join(e,t);if(ja(n))return n}}();if(e)return{type:"local",path:e}}(),dn=()=>(Jr.info("[fix] Starting SDK query",{model:nn,tools:Vt,mcpServers:Object.keys(Jt),resumeSessionId:N??null,subagentsEnabled:!!en,subagentCount:Object.keys(Rt).length,useStablyAiProxy:$t,aiProxyUrl:sr,anthropicBaseUrl:void 0,stablyPluginPath:un?.path,stablyPluginExists:!!un}),Y({options:{executableArgs:["--max-old-space-size=4096"],tools:Vt,allowedTools:zt,...null!=vt?{maxBudgetUsd:vt}:{},betas:[],canUseTool:(e,t)=>(Jr.debug("[fix] canUseTool called",{toolName:e}),Promise.resolve({behavior:"allow",updatedInput:t})),cwd:d,env:tn,hooks:{PostToolUse:Xt,PreToolUse:Zt},includePartialMessages:!0,agents:en,mcpServers:Jt,model:nn,permissionMode:"default",plugins:un?[un]:void 0,systemPrompt:ln,...N?{resume:N}:{}},prompt:C??ft})),pn=async e=>{if(y&&j&&!z&&!B)B=(async()=>{Jr.info("[fix] Interrupting for user message",{messageCount:e.length,phase:le?.phase});try{await(D?.interrupt?.())}catch(e){Jr.warn("[fix] Failed to interrupt response for user message",{error:e instanceof Error?e.message:String(e)})}await Fs(),C?.finish(),C=new Hs,ee.clear(),D=dn();const t=e.map(e=>`[Message from web UI user]: ${e}`).join("\n\n");C.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}`),J=!0,j=!0})().finally(()=>{B=void 0}),await B;else for(const t of e)C?.pushText(`[Message from web UI user]: ${t}`)};if(Nt){x&&Xe({label:"Checking AI connectivity..."});const e=sr,t=`${e.replace(/\/$/,"")}/v1/messages`;Jr.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":Nt,"anthropic-version":"2023-06-01","content-type":"application/json"},body:"{}"}),s=await e.text().catch(()=>""),o=Date.now()-n;Jr.debug(`[fix] Pre-flight: ${e.status} in ${o}ms β ${s.slice(0,300)}`),401===e.status||403===e.status?(Jr.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."):Jr.info("[fix] Pre-flight: AI proxy key valid",{status:e.status,durationMs:o})}catch(t){Jr.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{x&&"running"===nt&&Xe({label:void 0})}r&&(Ge({text:`[stably] ${r}\n`}),rt({error:r,status:"error"}),await ze(),Jr.flush(),Jr.printLogFileInfo(),process.exit(1))}Jr.info("[fix] Creating initial agent query"),x&&(Xe({label:"Initializing verification session..."}),Ge({text:"Initializing verification session...\n"})),Jr.flush(),D=dn(),Jr.info("[fix] Agent query created, entering message loop"),"chat"!==e.mode&&(C.pushText(ft),te.push({role:"user",content:ft,timestamp:(new Date).toISOString()}));const fn=async t=>{De||(De=(async()=>{Jr.info("[session] Interrupt requested",{source:t,mode:e.mode}),se="CANCELED",await ge("CANCELED"),he({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:fe(!0)}),await(ce?.closeAndWait()),await Promise.allSettled(lt),we({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0}),await(ye?.closeAndWait()),O&&(clearTimeout(O),O=void 0),Qe(),await Fs(),await(jt?.cleanup());try{await(D?.interrupt?.())}catch{}C?.finish(),te.length>0&&Ce&&await vs({authHeader:l,orgId:u,sessionId:Ce,projectId:os(c),history:te}).catch(e=>{Jr.warn("[exit] Failed to upload session history",{error:e instanceof Error?e.message:String(e)})}),ze(),Jr.flush()})()),await De};Le.current=async()=>{await fn("ctrl-c")};let hn=()=>{};hn=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 fn("signal"),process.exit(function(e){return"SIGINT"===e?130:143}(e))})()}});let gn=null,mn=null,yn="";Ne.current=async()=>{if(!Oe&&j&&C){Oe=!0;try{Jr.info("[chat] User pressed Escape to cancel generation"),Ke(),qe(),M=!0,Be=!0;try{await(D?.interrupt?.())}catch(e){Jr.warn("[chat] Failed to interrupt response on Escape",{error:e instanceof Error?e.message:String(e)})}await Fs();const e=C.drainQueue();C.finish(),C=new Hs;for(const t of e)C.pushText(t);F=e.length,D=dn();for(const e of ee.keys())et({toolUseId:e,status:"error"});He()}finally{Oe=!1}}};let bn=0,wn=null,vn=!1;const In=b?void 0:x?9e4:18e4;let Tn=!1;const _n=null!=In?setTimeout(()=>{wn||"running"!==nt||(t=>{if(!Tn){if(Tn=!0,clearTimeout(_n),clearInterval(En),setTimeout(()=>process.exit(1),6e4).unref(),Jr.error("[session] Session timeout",{reason:t,mode:e.mode,elapsed:Date.now()-ae}),se="FAILED",x||b){const e="This is taking longer than expected. Please try again.";Ge({text:`[stably] ${e}\n`}),rt({error:e,status:"error"})}else he({phase:"complete",endedAt:Date.now(),isError:!0,errorReason:"execution_error",errorMessage:`Session timed out: ${t}`,workers:fe(!0)});we({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:`Timed out: ${t}`});try{D?.interrupt?.()}catch{}C?.finish()}})("no response from AI service")},In):void 0;_n?.unref();const En=setInterval(()=>{const e=Date.now()-ae;wn?Jr.info("[fix] Watchdog: message loop active",{messageCount:bn,elapsed:e}):(Jr.info("[fix] Watchdog: waiting for first SDK message",{elapsed:e}),x&&!vn&&e>=15e3&&(Ge({text:"Still preparing verification. This can take a bit...\n"}),vn=!0)),Jr.flush()},15e3);En.unref();try{let t=!1;for(;;){if(!D){Jr.info("[fix] No response object, exiting message loop");break}t=!1,Jr.info("[fix] Entering for-await on SDK response");try{for await(const t of D){if(Tn)break;bn++,wn||(wn=Date.now(),clearTimeout(_n),x&&Xe({label:void 0}),Jr.info("[fix] First SDK message received",{waitDurationMs:wn-ae,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!==N&&(N=n,Jr.debug("Captured Claude session id",{sessionId:N})),"stream_event"===t.type){const{event:e}=t;(bn<=5||bn%200==0)&&Jr.debug("[fix] Stream event",{msgNum:bn,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&&(gn=e.index??null)}if("content_block_delta"===e?.type){const{delta:t}=e;if("text_delta"===t?.type&&t.text){yn&&(ne({role:"thinking",content:yn,timestamp:(new Date).toISOString()}),yn="");const e=n&&ee.has(n)?n:1===ee.size?Array.from(ee.keys())[0]:void 0;e?je({toolUseId:e,kind:"text",content:t.text}):x||Ge({text:t.text})}const r=t;if("thinking_delta"===r?.type&&r.thinking){if(n&&ee.has(n))continue;if(yn+=r.thinking,!x){const e=null!==gn&&gn!==mn;We({text:r.thinking,forceNewBlock:e}),e&&(mn=gn)}continue}}if("content_block_stop"===e?.type){const t=e.index;null!==gn&&gn===t&&(qe(),yn&&(ne({role:"thinking",content:yn,timestamp:(new Date).toISOString()}),yn=""),gn=null,Je())}"message_stop"===e?.type&&C&&(z=!1,C.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&&(ot=t,x&&(it=it?`${it}\n\n${t}`:t),Jr.debug("Assistant message",{text:x?nc(t):t}),"fix"===e.mode&&(de(dc,{type:"ai_message",summary:t.slice(0,200)}),pe({type:"ai_message",summary:t.slice(0,200)})),A&&Ie({type:"ai_message",summary:t.slice(0,200)}),ne({role:"assistant",content:t,timestamp:(new Date).toISOString()}))}if(ee.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):[];Jr.debug("Assistant message with active subagents",{hasParentToolUseId:!!n,parentToolUseId:n,activeSubagentIds:Array.from(ee.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&&(z=!0),t.name.startsWith("mcp__session-control__")||t.name.startsWith("mcp__stably-agent-control__"))continue;if(mc(t.name))continue;if(x&&gc.test(t.name))continue;if(ee.size>0&&Jr.debug("Tool use detected with active subagents",{toolName:t.name,hasParentToolUseId:!!n,parentToolUseId:n,wouldRouteToSubagent:!!n&&ee.has(n),activeSubagentIds:Array.from(ee.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(Jr.info("[fix] Subagent started",{subagentType:s,description:o,toolUseId:t.id,activeSubagentCount:ee.size+1}),ee.set(t.id,{subagentType:s,description:o}),Me({toolUseId:t.id,subagentType:s,description:o}),"fix"===e.mode){if("triage"===s){tt?.({phase:"triage"});const e={id:t.id,testDescription:"Triage",workerType:"triage",status:"running",summary:null,startedAt:Date.now(),endedAt:null,activity:[]};he({phase:"triage",workers:[...le?.workers??[],e]})}else if("code-worker"===s){ue.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:[]};tt?.({phase:"fixing",totalTests:ue.size,currentTestDescription:o||null}),he({phase:"fixing",totalTests:ue.size,currentTestDescription:o||null,lastTestDescription:o||le?.lastTestDescription||null,workers:[...le?.workers??[],e]})}else if("browser-worker"===s){ue.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:[]};tt?.({phase:"debugging",totalTests:ue.size,currentTestDescription:o||null}),he({phase:"debugging",totalTests:ue.size,currentTestDescription:o||null,lastTestDescription:o||le?.lastTestDescription||null,workers:[...le?.workers??[],e]})}else"validation"===s?(tt?.({phase:"validation",currentTestDescription:null}),he({phase:"validation",currentTestDescription:null})):"context"===s&&he({currentTestDescription:o||null});pe({type:"tool_call",summary:`[${s}] ${o}`.trim()})}continue}if(n&&ee.has(n)){const r=po(t.name,t.input),s=r??fo(t.name),o=r?void 0:uo(t.name,t.input),i=o?`${s} (${o})`:s;if(Jr.debug("Subagent tool called",{tool:t.name,parentToolUseId:n}),je({toolUseId:n,kind:"tool",content:i}),"fix"===e.mode){pe({type:"tool_call",summary:i});const e=ee.get(n);"code-worker"!==e?.subagentType&&"browser-worker"!==e?.subagentType&&"triage"!==e?.subagentType||de(n,{type:"tool_call",summary:i})}continue}if(n&&Jr.debug("Tool with parent_tool_use_id but no matching subagent",{tool:t.name,parentToolUseId:n,activeSubagentIds:Array.from(ee.keys())}),Jr.debug("Tool called",{tool:t.name,input:t.input}),Fe({rawName:t.name,toolInput:t.input}),t.id&&re.set(t.id,t.name),ne({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??fo(t.name),r=e?void 0:uo(t.name,t.input),s=r?`${n} (${r})`:n;de(dc,{type:"tool_call",summary:s}),pe({type:"tool_call",summary:s})}if(S){const e=po(t.name,t.input),n=e??fo(t.name),r=e?void 0:uo(t.name,t.input),s=r?`${n} (${r})`:n;"initializing"===be?.phase?we({phase:"generating",currentActivity:s}):"mcp__playwright-test__test_run"===t.name&&"generating"===be?.phase?we({phase:"testing",currentActivity:s}):we({currentActivity:s}),Ie({type:"tool_call",summary:s})}if(x){const e=po(t.name,t.input),n=e??fo(t.name),r=e?void 0:uo(t.name,t.input),s=nc(r?`${n} (${r})`:n);we("initializing"===be?.phase?{phase:"verifying",currentActivity:s}:{currentActivity:s}),Ie({type:"tool_call",summary:s})}}if("text"===t?.type){const r="string"==typeof t.text?t.text:"",s=n&&ee.has(n)?n:1===ee.size?Array.from(ee.keys())[0]:void 0;if(s&&r&&(je({toolUseId:s,kind:"text",content:r}),"fix"===e.mode)){const e=ee.get(s);"code-worker"!==e?.subagentType&&"browser-worker"!==e?.subagentType&&"triage"!==e?.subagentType||de(s,{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("")),Jr.debug("Tool result",{toolUseId:n,isError:s,output:o?.slice(0,500)});const a=5e4,c=n?re.get(n):void 0;if(ne({role:"tool_result",content:"",timestamp:(new Date).toISOString(),toolName:c,toolOutput:o?.slice(0,a),isError:s}),n&&ee.has(n)){const t=ee.get(n);if(Jr.info("[fix] Subagent completed",{toolUseId:n,isError:s,subagentType:t?.subagentType,description:t?.description,activeSubagentCount:ee.size-1}),o&&je({toolUseId:n,kind:"text",content:o}),et({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=(le?.workers??[]).map(r=>r.id===n?{...r,status:e,summary:t,endedAt:Date.now()}:r);he({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=(le?.workers??[]).map(r=>r.id===n?{...r,status:e,summary:t,endedAt:Date.now()}:r);s?(tt?.({failedTests:(le?.failedTests??0)+1,currentTestDescription:null}),he({failedTests:(le?.failedTests??0)+1,currentTestDescription:null,workers:r})):(tt?.({fixedTests:(le?.fixedTests??0)+1,currentTestDescription:null}),he({fixedTests:(le?.fixedTests??0)+1,currentTestDescription:null,workers:r}))}ee.delete(n)}}continue}if("result"!==t.type);else{if(Jr.info("[fix] Agent result received",{subtype:t.subtype,messageCount:bn,elapsed:Date.now()-ae,activeSubagents:ee.size,fixedTests:le?.fixedTests,failedTests:le?.failedTests,phase:le?.phase}),y){if("success"===t.subtype){O&&(clearTimeout(O),O=void 0);for(const e of H)C?.pushText(`[Message from web UI user]: ${e}`);if(H=[],(A||"fix"===e.mode)&&C){if(C.hasQueuedMessages()){Jr.info("[ws] Queued web UI messages found, continuing agent"),j=!0,C.allowNextTurn();continue}if(await yc(C,3e3)){Jr.info("[ws] Web UI message received during grace period, continuing agent"),j=!0,C.allowNextTurn();continue}C.finish()}tt?.({phase:"complete",currentTestDescription:null,endedAt:Date.now()}),he({phase:"complete",currentTestDescription:null,endedAt:Date.now(),isError:!1,workers:fe(!1)}),await Promise.allSettled(lt);const t=oc({mode:e.mode,lastAssistantText:ot});if("verify"===e.mode){(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt).trim();const n=it||ot,r=/```verdict\s*\r?\n/.test(n),s=sc(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=rc(s);"PASS"===s.verdict?q.green("VERIFICATION PASSED"):"FAIL"===s.verdict?q.red("VERIFICATION FAILED"):ic("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=>{}),we({phase:"complete",endedAt:Date.now(),isError:"PASS"!==s.verdict,currentActivity:null,resultSummary:t}),process.exitCode="PASS"===s.verdict?0:"FAIL"===s.verdict?1:2,rt({status:"success"})}else{if(we({phase:"complete",endedAt:Date.now(),isError:!1,currentActivity:null,resultSummary:t}),Qt&&at.length>0){q.green("Created files:");for(const e of at)q.green(`- ${e}`)}const e=(e,t)=>`]8;;${e}${t}]8;;`,n=st?q.cyan(`π View Autoheal Report:\n ${e(st,q.cyan(q.bold(q.underline(st))))}`):void 0;rt({status:"success",result:n}),se="COMPLETED"}}else if(B||J)Jr.info("[fix] Suppressing error status: user-message interrupt in progress");else if(M)se="CANCELED",he({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:fe(!0)}),await Promise.allSettled(lt),we({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0});else if(x){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."),ic("VERIFICATION INCONCLUSIVE"),await Promise.allSettled(lt),we({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),rt({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.`,Jr.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"),tt?.({endedAt:Date.now(),isError:!0}),he({phase:"complete",endedAt:Date.now(),isError:!0,errorReason:n,errorMessage:r,totalCostUsd:e,currentTestDescription:null,workers:fe(!0)}),await Promise.allSettled(lt),we({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),rt({error:r,status:"error"}),process.exitCode=1,se="FAILED"}M=!1;break}if("success"!==t.subtype){if(!M){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.`,Jr.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."),rt({error:e,status:"error"}),process.exitCode=1}}else rt({status:"success"});j=!1,M=!1,Xe({label:void 0}),C?.allowNextTurn(),T&&F>0&&(F-=1,j=!0,rt({status:"running"}))}}}catch(e){if(Be){Be=!1,M=!1,ee.clear(),Ve(),yn&&ne({role:"thinking",content:yn,timestamp:(new Date).toISOString()}),gn=null,mn=null,yn="",Je(),F>0?(j=!0,rt({status:"running"})):(j=!1,rt({status:"success"})),t=!0;continue}throw e}if(Be)Be=!1,M=!1,ee.clear(),Ve(),yn&&ne({role:"thinking",content:yn,timestamp:(new Date).toISOString()}),gn=null,mn=null,yn="",Je(),F>0?(j=!0,rt({status:"running"})):(j=!1,rt({status:"success"})),t=!0;else if(B&&await B,J&&(J=!1,t=!0,rt({status:"running"}),Jr.info("[fix] Resuming after user-message interrupt")),!t)break}}catch(e){M?(se="CANCELED",he({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:fe(!0)}),await Promise.allSettled(lt),we({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0})):(Jr.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()-ae}),rt({error:`Agent encountered an error: ${e}`,status:"error"}),process.exitCode=1,se="FAILED",he({phase:"complete",endedAt:Date.now(),isError:!0,currentTestDescription:null,workers:fe(!0)}),await Promise.allSettled(lt),we({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),Jr.flush(),Jr.printLogFileInfo())}finally{if(_n&&clearTimeout(_n),clearInterval(En),O&&(clearTimeout(O),O=void 0),Jr.info("[fix] Agent session ending",{finalStatus:se,elapsed:Date.now()-ae,totalMessages:bn}),Ft(),j=!1,M=!1,hn(),process.off("uncaughtException",a),C?.finish(),se){Jr.info("[fix] Reporting final autoheal status",{status:se});const e=Date.now();await ge(se),Jr.info("[fix] Final autoheal status reported",{durationMs:Date.now()-e})}if(Jr.info("[fix] Closing WebSocket progress reporter"),await(ce?.closeAndWait()),await Promise.allSettled(lt),await(ye?.closeAndWait()),!Bt&&te.length>0&&Ce&&(Jr.info("[session] Uploading session history",{messageCount:te.length}),await vs({authHeader:l,orgId:u,sessionId:Ce,projectId:os(c),history:te}).catch(e=>{Jr.warn("[session] Failed to upload session history",{error:e instanceof Error?e.message:String(e)})})),Bt&&Mt){const t=Date.now();try{Jr.info("[fix] Computing diff...");const n=await Mt.computeDiff();if(n&&n.trim().length>0){Jr.info("[fix] Uploading diff...",{diffLength:n.length});const{diffBucketPath:r,uploadUrl:s}=await hs({authHeader:l,contentType:"text/plain",orgId:u,runId:e.runId});await ds({body:n,contentType:"text/plain",uploadUrl:s,errorContext:"diff"}),await gs({authHeader:l,diffBucketPath:r,orgId:u,runId:e.runId}),Jr.info("[fix] Diff uploaded",{durationMs:Date.now()-t})}else Jr.info("[fix] No diff to upload (empty or no changes)")}catch(e){Jr.warn("[fix] Failed to upload diff",{error:e instanceof Error?e.message:String(e),durationMs:Date.now()-t})}}Jr.info("[fix] Cleaning up diff tracker"),await(Mt?.cleanup()),Bt&&te.length>0&&Ce&&(Jr.info("[fix] Uploading session history",{messageCount:te.length}),await vs({authHeader:l,orgId:u,sessionId:Ce,projectId:os(c),history:te}).catch(e=>{Jr.warn("[fix] Failed to upload session history",{error:e instanceof Error?e.message:String(e)})})),Jr.info("[fix] Running final cleanup"),await(jt?.cleanup()),await ze(),Jr.info("[fix] Cleanup complete"),Tn&&(Jr.flush(),Jr.printLogFileInfo(),process.exit(1))}},Ic=he.object({runId:he.string(),timestamp:he.number()}),Tc=[{args:["--trace=on"],description:"Run Playwright tests",name:"test"},{args:[],description:"Install browser dependencies",name:"install"}],_c=["You have two different versions of @playwright/test"];function Ec(e){const[t,...n]=ea(e),r=[t,...n.slice(0,-1)].join(" ");return(t,n)=>{let s=t.toString();for(const e of Tc)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 Sc({overrideArgs:e,subcommand:t}){Jr.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=Tc.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=Qi();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]=ea(s),a=Ec(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];Jr.info("[test] Forwarded args computed",{forwardedArgs:m}),Jr.info("[test] Resolving Stably test environment");const y=Date.now(),b="test"===t?await(async()=>{Jr.info("[test] Resolving Stably test env");const e=(()=>{if(process.env.STABLY_WS_URL)return;if("https://api.stably.ai"===er)return;const e=er.startsWith("http://")?"ws://":"wss://";return`${er.replace(/^https?:\/\//,e).replace(/\/$/,"")}/reporter`})();Jr.debug("[test] WebSocket URL resolved",{wsUrl:e??"(default)"});const t=ns();if(t)return Jr.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}};Jr.info("[test] No env var auth, attempting OAuth auth");const n=Date.now(),r=await(async()=>{const e=ns();if(e)return{auth:e,type:"env"};const t=await rs(),n=t?await Sr():void 0;return t&&n?{auth:{accessToken:t.accessToken,context:n},type:"oauth"}:void 0})();if(Jr.info("[test] OAuth auth resolved",{durationMs:Date.now()-n,hasAuth:!!r,authType:r?.type}),!r||"env"===r.type)return void Jr.info("[test] No usable auth found");const s=process.env.STABLY_PROJECT_ID?.trim(),o=s||os(r);if(!o)return void Jr.warn("[test] No project ID available");Jr.info("[test] Fetching JWT API key",{projectId:o});const i=Date.now(),a=await(async(e,t)=>{try{Jr.debug("Requesting JWT API key",{projectId:t,apiUrl:er});const n=await(async({accessToken:e,projectId:t})=>{const n=await(r={auth:e,client:cr(),path:{projectId:t}},(r.client??Jn).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 Jr.debug("JWT API key obtained",{keyPrefix:n.apiKey.substring(0,10)}),n.apiKey}catch(e){return void Jr.warn("Failed to get JWT API key for test reporter",{error:e instanceof Error?e.message:String(e)})}})(r.auth.accessToken,o);Jr.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 Jr.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;Jr.info("[test] Stably test environment resolved",{durationMs:Date.now()-y,hasCredentials:null!=b,hasWsUrl:!!b?.STABLY_WS_URL}),Jr.info("[test] Loading remote environment variables");const w=await as();Jr.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")}:{}};Jr.info("[test] Setting up Stably reporter injection");const T="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=Xr();if("local"!==e){const t=es(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=>I(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,`.stably-playwright-wrapper.config.${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: '${Zn}',\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: '${Zn}',\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 I(a)||A(a,{recursive:!0}),k(u,d,"utf-8"),function(e){const t=i(e,".gitignore");try{if(I(t)){const e=_(t,"utf-8");if(e.split("\n").map(e=>e.trim()).includes(Js))return;const n=e.length>0&&!e.endsWith("\n");E(t,`${n?"\n":""}${Js}\n`)}else k(t,`${Js}\n`)}catch{}}(a),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=Xs(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;Jr.info("[test] Reporter injection setup complete",{hasWrapperConfig:!!T}),Jr.info("[test] Spawning Playwright process"),await function(e,t={}){Jr.info("[test] Detecting Playwright installation");const n=Qi();Jr.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]=ea(r),i=(a=t.env)?{...process.env,...a}:process.env;var a;const c=[s,...o,...e];Jr.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"}}});Jr.info("[test] Playwright process spawned",{childPid:u.pid});const d=Ec(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 _c)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=>{Jr.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()&&(Jr.error("[test] Playwright process error",{error:e.message,childPid:u.pid}),t(e))}),u.on("close",t=>{if(!h())return;Jr.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;Jr.info("[test] Playwright process closed, cleaning up wrapper config"),(e=T)&&I(e)&&C(e)}})}function xc(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 Ac=e=>"oauth"===e.type?e.auth.context.orgId:void 0,kc=(e,t,n)=>{if(401!==e.response.status&&403!==e.response.status||(le(q.red("Access denied.")),process.exit(1)),404===e.response.status&&n&&(le(q.red(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";le(q.red(t)),process.exit(1)}e.error&&(le(q.red(`Failed to ${t}: ${e.response.status}`)),process.exit(1))},Cc={PASSED:q.green,FAILED:q.red,TIMEDOUT:q.red,CANCELLED:q.yellow,INTERRUPTED:q.yellow,RUNNING:q.cyan,QUEUED:q.dim},Pc=(e,t)=>e?e.length>t?`${e.slice(0,t-1)}β¦`:e:"-",Rc=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")}`},Uc=e=>(Cc[e]??(e=>e))(e),$c=/\x1b\[[0-9;]*m/g,Lc=(e,t)=>{const n=e.replace($c,"").length,r=Math.max(0,t-n);return e+" ".repeat(r)},Dc=e=>`${JSON.stringify(e,null,2)}\n`,Nc=(e,t,n)=>{if(!e)return;const r=e.toUpperCase();if(t.includes(r))return r;le(q.red(`Invalid ${n} value "${e}". Must be one of: ${t.join(", ").toLowerCase()}`)),process.exit(1)},Oc=/\x1b\[[0-9;]*m/g,Bc=(e,t)=>{const n=e.replace(Oc,"").length,r=Math.max(0,t-n);return e+" ".repeat(r)},jc=(e,t)=>e?e.length>t?`${e.slice(0,t-1)}β¦`:e:"-",Mc=e=>e?e.split("T")[0]??"-":"-",Fc=e=>`${(100*e).toFixed(1)}%`,Hc=e=>`${JSON.stringify(e,null,2)}\n`,Gc=e=>{if(!e)return;const t=parseInt(e,10);return(Number.isNaN(t)||t<1||t>90)&&(le(q.red("--days must be an integer between 1 and 90")),process.exit(1)),t},Wc=e=>{if(!e)return;const t=parseInt(e,10);return(Number.isNaN(t)||t<1||t>100)&&(le(q.red("--limit must be an integer between 1 and 100")),process.exit(1)),t},Yc="stably",Vc=`https://registry.npmjs.org/${Yc}/latest`;function zc(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 Kc(e,t){const n=zc(e),r=zc(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 qc=r.join(D.homedir(),".stably"),Jc=r.join(qc,"update-check.json"),Qc="1"===process.env.STABLY_DISABLE_UPDATE_CHECK,Xc=ge.object({lastCheck:ge.number(),latestVersion:ge.string()}),Zc=Symbol.for("stably.updateNotifier.registered");function el(e=""){process.stdout.write(`${e}\n`)}function tl(...e){process.stderr.write(`${e.join(" ")}\n`)}var nl=ge.object({version:ge.string()});var rl=!1,sl=async()=>{if(rl)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{}},ol=e=>{const t=e.toLowerCase();return t.startsWith("npm_config_")||"node_options"===t};!function(){if(Qc||function(e=process.argv.slice(2)){return e.includes("upgrade")}())return;const e=function(){try{const e=v.readFileSync(Jc,"utf-8");return Xc.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 = '${Vc}';\n const cacheFile = ${JSON.stringify(Jc)};\n const cacheDir = ${JSON.stringify(qc)};\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&&Kc(Zn,e.latestVersion)){if(!0===process[Zc])return;process[Zc]=!0;let t=!1;const n=()=>{if(t)return;t=!0;const n=`${q.yellow(`update available (${Zn} β ${e.latestVersion})`)} - run \`${Yc} upgrade\` to get the latest version\n`;try{v.writeSync(2,n)}catch{}};process.once("beforeExit",n),process.once("exit",n)}}(),$e.cwdChanged&&Jr.debug("Changed working directory",{cwd:$e.newCwd});for(const e of $e.envFilesLoaded)Jr.debug("Loaded env file",{path:e});for(const e of $e.envFileErrors)Jr.warn(e);var il=process.argv.findIndex(e=>"-v"===e||"--verbose"===e);-1!==il&&process.argv.splice(il,1);var al=process.argv.findIndex(e=>"--no-telemetry"===e);-1!==al&&process.argv.splice(al,1),Jr.info("CLI starting",{version:Zn,args:process.argv.slice(2),cwd:process.cwd()}),process.on("unhandledRejection",(e,t)=>{Jr.error("Unhandled promise rejection",{reason:e instanceof Error?{message:e.message,stack:e.stack}:e,promise:String(t)}),Jr.flush(),Jr.printLogFileInfo()}),process.on("uncaughtException",(e,t)=>{"EPIPE"!==e.code&&(Jr.error("Uncaught exception",{error:{message:e.message,stack:e.stack,name:e.name},origin:t}),Jr.flush(),Jr.printLogFileInfo())});var cl=new u;cl.name("stably").description("AI-assisted Playwright testing CLI").version(Zn),cl.enablePositionalOptions(),cl.showHelpAfterError(),cl.exitOverride(),cl.configureHelp({subcommandTerm:e=>{const t=e.registeredArguments.map(e=>e.required?`<${e.name()}>`:`[${e.name()}]`).join(" ");return t?`${e.name()} ${t}`:e.name()}}),cl.addHelpText("after","\nGlobal options (available for all commands):\n -C, --cwd <path> Change working directory before running\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 ll=[];cl.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>{ll.push(e)}});var ul=()=>{const e=cl.helpInformation().trimEnd();return e?`${e}\n`:""},dl=(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},pl=()=>{process.stdout.write(ul())};cl.command("help [command...]").description("Show help for a command (e.g. stably help create)").action(e=>{if(!e||0===e.length)return void pl();const t=dl(cl,e);if(!t)return process.stderr.write(`Unknown command: ${e.join(" ")}\n`),pl(),void(process.exitCode=1);var n;n=t,process.stdout.write((e=>{const t=e.helpInformation().trimEnd();return t?`${t}\n`:""})(n))}),cl.action(()=>vc({mode:"chat",getHelpText:ul})),cl.command("login").description("Authenticate with Stably in your browser").action($r),cl.command("logout").description("Clear stored Stably credentials").action(async()=>{const e=ns();e&&(ce.warn(`Environment variables ${q.cyan("STABLY_API_KEY")} and ${q.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 Tr();if(!t)return void le(e?q.yellow("No stored OAuth login found to clear."):q.yellow("You are not logged in."));const n=ue();n.start("Logging out..."),await(async e=>{try{await fetch(`${nr}/api/backend/v1/logout`,{body:JSON.stringify({refresh_token:e}),headers:{"Content-Type":"application/json"},method:"POST"})}catch{}})(t.refreshToken),await Er(),await xr(),n.stop(q.green("β Logged out")),le(q.green("You have been logged out successfully."))}),cl.command("whoami").description("Show auth status and current project").action(async()=>{ce.info(`${q.bold("CLI Version:")} ${q.cyan(Zn)}`);const e=ns();if(e){ce.info(q.dim("Authentication: Environment variables")),ce.info(` ${q.bold("API Key:")} ${q.cyan(e.apiKey.slice(0,8))}...`),ce.info(` ${q.bold("Project ID:")} ${q.cyan(e.projectId)}`);const t=await Tr();if(t){let e;try{e=hr(t.accessToken).email}catch{e=void 0}ce.warn("Stored OAuth login detected but will be ignored (env auth takes precedence)."),e&&ce.info(` ${q.bold("OAuth Email:")} ${q.cyan(e)}`),ce.info(` ${q.bold("Tip:")} Unset env vars to use OAuth`)}return void le(q.green("Authenticated via environment variables"))}const t=await Tr();if(!t)return void le(q.yellow("Not logged in. Run `stably login` to authenticate."));let n;try{n=hr(t.accessToken).email}catch{n=void 0}const s=await Sr();if(!s)return ce.info(q.dim("Authentication: OAuth (not linked to a project)")),n&&ce.info(` ${q.bold("Email:")} ${q.cyan(n)}`),void le(q.yellow("Logged in but this directory is not linked to a project. Run `stably login` to link."));const o=await(async()=>gr(process.cwd(),br))(),i=o?r.dirname(o):process.cwd(),a=r.relative(process.cwd(),i)||".";ce.info(q.dim("Authentication: OAuth")),n&&ce.info(` ${q.bold("Email:")} ${q.cyan(n)}`),ce.info(` ${q.bold("Organization:")} ${q.cyan(s.orgName)}`),ce.info(` ${q.bold("Project:")} ${q.cyan(s.projectName)}`),ce.info(` ${q.bold("Linked at:")} ${q.dim(a)}`),le(q.green("Authenticated"))}),cl.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 ss(),n="oauth"===t.type?`${t.auth.context.orgName}-${t.auth.context.projectName}`.toLowerCase().replace(/[^a-z0-9-]/g,""):`project-${t.auth.projectId}`.toLowerCase(),r=ue();r.start("Starting development server...");const s=await Re(`http://localhost:${e.port}`,{subdomain:n});r.stop(`Your local environment is available at: ]8;;${s.url}${q.underline(q.cyan(s.url))}]8;;`)}),cl.command("create [prompt...]").description("Generate a test from prompt (omit prompt to infer from branch diff)").option("-o, --output <dir>","Output directory for generated test files").action(async(e,t)=>{const n=e.length>0&&"test"===e[0]?e.slice(1):e;return vc({mode:"single",prompt:n,outputDir:t.output})}).command("test",{hidden:!0}).description("Generate a Playwright test from a prompt (deprecated: use `stably create <prompt>` directly)").argument("<prompt...>","Prompt describing the test to generate").option("-o, --output <dir>","Output directory for generated test files").action(async(e,t)=>vc({mode:"single",prompt:e,outputDir:t.output})),cl.command("verify <prompt...>").description("Verify your app works correctly against a prompt").option("-u, --url <url>","Starting URL to verify against").option("--max-budget <dollars>","Maximum budget in USD (default: 5)",Number.parseFloat).option("--no-interactive","Disable interactive verify preflight setup").action(async(e,t)=>{if(void 0!==t.maxBudget&&(!Number.isFinite(t.maxBudget)||t.maxBudget<=0))throw new Error("--max-budget must be a positive number");return vc({mode:"verify",prompt:e,url:t.url,maxBudgetUsd:t.maxBudget,interactive:t.interactive})}),cl.command("internal-fix-run <runId>",{hidden:!0}).description("Internal: run fix session in subprocess").action(async e=>vc({mode:"fix",runId:e})),cl.command("fix [runId]").description("Fix failing tests from a run (auto-detects from last test run or CI)").action(async e=>{(function(e){try{return h("git rev-parse --is-inside-work-tree",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}})(process.cwd())||(Jr.error('Not a git repository. The "stably fix" command requires a git repository to track changes made during the fix. Please run this command from inside a git repository.'),process.stderr.write('Error: Not a git repository.\nThe "stably fix" command requires a git repository to track changes made during the fix.\nPlease run this command from inside a git repository.\n'),process.exit(1));const t=await(async e=>{const t=e=>e.replace(/\//g,"_");if(e)return Jr.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),...(n={env:e,cwd:t},{commit:Jt(n),branch:Qt(n)})};var n})();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 Jr.debug("Run ID detected from CI environment",{runId:n}),t(n);Jr.debug("No explicit run ID or CI environment detected, checking last-run.json");const r=await(async()=>{try{const e=await gr(process.cwd(),".stably/last-run.json");if(!e)return;const t=await Z(e,"utf-8");return{...Ic.parse(JSON.parse(t)),filePath:e}}catch{return}})();if(r){const e=(Date.now()-r.timestamp)/36e5;return Jr.debug("Run ID found in last-run.json",{runId:r.runId,timestamp:r.timestamp,filePath:r.filePath,ageHours:Math.round(e)}),e>24&&Jr.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)}Jr.debug("No run ID found in last-run.json")})(e);t||(process.stderr.write('Run ID is required. Either:\n 1. Run "stably test" first (run ID will be auto-detected)\n 2. Provide a run ID: stably fix <runId>\n 3. Run in CI (auto-detected from environment)\n'),process.exit(1));const n=await(async e=>{const t=await ss(),n=is(t),r=os(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))ol(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"})})(t);0!==n&&process.exit(n)}),cl.command("init").description("Initialize Playwright and Stably SDK in your project").action(async()=>vc({mode:"init"})),cl.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;el(q.cyan("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(Vc,{signal:e.signal});if(!t.ok)throw new Error(`Failed to fetch latest version: ${t.statusText}`);return nl.parse(await t.json()).version}finally{clearTimeout(t)}}();return{current:Zn,latest:e,isOutdated:Kc(Zn,e)}}()}catch(e){return tl(q.red("Failed to check for updates:"),e instanceof Error?e.message:e),void(process.exitCode=1)}if(el(`Current version: ${q.yellow(n.current)}`),el(`Latest version: ${q.green(n.latest)}`),el(),!n.isOutdated)return void el(q.green("β You are already on the latest version!"));if(el(q.yellow(`β A new version is available: ${n.current} β ${n.latest}`)),el(),t)return el(q.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",`${Yc}@latest`],description:`npm install -g ${Yc}@latest`};case"global-pnpm":return{command:"pnpm",args:["add","-g",`${Yc}@latest`],description:`pnpm add -g ${Yc}@latest`};case"global-yarn-classic":return{command:"yarn",args:["global","add",`${Yc}@latest`],description:`yarn global add ${Yc}@latest`};case"npx":return{command:"npx",args:[`${Yc}@latest`],description:`npx ${Yc}@latest (always uses latest)`}}}(r);if("npx"===r)return el(q.dim("You are running via npx, which always fetches the latest version.")),void el(q.dim(`Simply run: ${q.white("npx stably")} to use the latest version.`));"unknown"===r?(el(q.yellow("Could not detect installation method. Falling back to npm.")),el()):"global-yarn-berry"===r&&(el(q.yellow("Yarn Berry does not support global packages. Falling back to npm.")),el()),el(`Upgrade command: ${q.cyan(s.description)}`),el(),el(q.cyan("Upgrading...")),el();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(Jc)}catch{}}(),el(),el(q.green("β Upgrade complete!")),el(q.dim(`Run ${q.white("stably --version")} to verify.`))}catch(e){tl(q.red("Upgrade failed:"),e instanceof Error?e.message:e),el(),el(q.dim("You can try manually running:")),el(q.cyan(` ${s.description}`)),process.exitCode=1}var o,i}(e));var fl=cl.command("env").description("Manage remote environments");fl.command("list").description("List available environments").action(async()=>{const e=await ss(),t=os(e),n=is(e);Jr.debug("Listing environments",{projectId:t});const r=await(s={auth:n,client:cr(),path:{projectId:t}},(s.client??Jn).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/environments",...s}));var s;401!==r.response.status&&403!==r.response.status||(le(q.red("Access denied.")),process.exit(1)),r.error&&(le(q.red(`Failed to list environments: ${r.response.status}`)),process.exit(1));const{environments:o}=r.data;if(0!==o.length){process.stdout.write(`${q.bold("Environments")}\n\n`);for(const e of o){const t=e.isDefault?q.green(" (default)"):"",n=q.dim(` ${e.variableCount} variable${1!==e.variableCount?"s":""}`);process.stdout.write(` ${q.cyan(e.name)}${t}${n}\n`),e.description&&process.stdout.write(` ${q.dim(e.description)}\n`)}process.stdout.write("\n")}else process.stdout.write(q.dim("No environments found. Create one on your Stably dashboard.\n"))}),fl.command("inspect <name>").description("Show variable metadata (name, sensitive flag, updated timestamp)").action(e=>(async e=>{const t=await ss(),n=os(t),r=is(t);Jr.debug("Inspecting environment",{name:e,projectId:n});const s=await(o={auth:r,client:cr(),path:{projectId:n,environmentName:e}},(o.client??Jn).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/environments/{environmentName}/inspect",...o}));var o;404===s.response.status&&(le(q.red(`Environment "${e}" not found. Run ${q.bold("stably env list")} to see available environments.`)),process.exit(1)),401!==s.response.status&&403!==s.response.status||(le(q.red("Access denied.")),process.exit(1)),s.error&&(le(q.red(`Failed to inspect environment: ${s.response.status}`)),process.exit(1));const{variables:i}=s.data;if(0!==i.length){process.stdout.write(`${q.bold(e)} ${q.dim(`(${i.length} variable${1!==i.length?"s":""})`)}\n\n`);for(const e of i){const t=q.dim(` [updated ${xc(e.updatedAt)}]`);e.sensitive?process.stdout.write(` ${q.cyan(e.name)} ${q.yellow("[sensitive]")}${t}\n`):process.stdout.write(` ${q.cyan(e.name)}${t}\n`)}process.stdout.write("\n")}else process.stdout.write(q.dim(`Environment "${e}" has no variables.\n`))})(e));var hl=cl.command("analytics").description("View test health analytics");hl.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 ss(),n=os(t),r=is(t),s=Ac(t),o=Gc(e.days),i=Wc(e.limit);Jr.debug("Listing flaky tests",{projectId:n,days:o,branch:e.branch,limit:i});const a=cr(),c=await a.get({url:"/internal/v1/cli/analytics/flaky",security:[{scheme:"bearer",type:"http"}],auth:r,headers:{...cs(s)},query:{projectId:n,days:o,branchName:e.branch,limit:i}});kc(c,"list flaky tests");const l=c.data;e.json?process.stdout.write(Hc(l)):process.stdout.write(((e,t)=>{const n=[],r=e.filters.branch?`branch: ${e.filters.branch}`:"all branches";if(n.push(q.bold(`Most Flaky Tests (last ${e.period.days} days, ${r})`)),n.push(""),0===e.tests.length)return n.push(q.dim(" No flaky tests found.")),n.push(""),n.join("\n");const s=` ${Bc("REF",14)}${Bc("TEST",20)}${Bc("LOCATION",30)}${Bc("FLAKY",8)}${Bc("RUNS",7)}${Bc("RATE",9)}LAST FLAKY`;n.push(q.dim(s));for(const t of e.tests){const e=t.testRef,r=jc(t.title,18),s=jc(t.location,28),o=String(t.flakyCount),i=String(t.nonSkippedRuns),a=Fc(t.flakyRate),c=Mc(t.lastFlakyAt);n.push(` ${Bc(e,14)}${Bc(r,20)}${Bc(s,30)}${Bc(o,8)}${Bc(i,7)}${Bc(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: ${q.cyan(q.underline(`https://app.stably.ai/p/${t}/analytics`))}`),n.push(""),n.join("\n")})(l,n))}),hl.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 ss(),n=os(t),r=is(t),s=Ac(t),o=Gc(e.days),i=Wc(e.limit);Jr.debug("Listing failing tests",{projectId:n,days:o,branch:e.branch,limit:i});const a=cr(),c=await a.get({url:"/internal/v1/cli/analytics/failures",security:[{scheme:"bearer",type:"http"}],auth:r,headers:{...cs(s)},query:{projectId:n,days:o,branchName:e.branch,limit:i}});kc(c,"list failing tests");const l=c.data;e.json?process.stdout.write(Hc(l)):process.stdout.write(((e,t)=>{const n=[],r=e.filters.branch?`branch: ${e.filters.branch}`:"all branches";if(n.push(q.bold(`Most Failed Tests (last ${e.period.days} days, ${r})`)),n.push(""),0===e.tests.length)return n.push(q.dim(" No failing tests found.")),n.push(""),n.join("\n");const s=` ${Bc("REF",14)}${Bc("TEST",20)}${Bc("LOCATION",30)}${Bc("FAILED",8)}${Bc("RUNS",7)}${Bc("RATE",9)}LAST FAILED`;n.push(q.dim(s));for(const t of e.tests){const e=t.testRef,r=jc(t.title,18),s=jc(t.location,28),o=String(t.failedCount),i=String(t.nonSkippedRuns),a=Fc(t.failureRate),c=Mc(t.lastFailedAt);n.push(` ${Bc(e,14)}${Bc(r,20)}${Bc(s,30)}${Bc(o,8)}${Bc(i,7)}${Bc(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: ${q.cyan(q.underline(`https://app.stably.ai/p/${t}/analytics`))}`),n.push(""),n.join("\n")})(l,n))});var gl=cl.command("runs").description("View test run history");gl.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 ss(),n=os(t),r=is(t),s=Ac(t);let o;e.limit&&(o=parseInt(e.limit,10),(Number.isNaN(o)||o<1||o>100)&&(le(q.red("--limit must be an integer between 1 and 100")),process.exit(1)));const i=Nc(e.source,["LOCAL","CI","WEB"],"--source"),a=Nc(e.status,["QUEUED","RUNNING","PASSED","FAILED","TIMEDOUT","CANCELLED","INTERRUPTED"],"--status"),c=Nc(e.trigger,["MANUAL","SCHEDULED","UI","API","GITHUB_ACTION","SUITE_RUN"],"--trigger");Jr.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 Qn({auth:r,client:cr(),headers:cs(s),query:{projectId:n,branchName:e.branch,limit:o,afterRunId:e.after,beforeRunId:e.before,source:i,status:a,suiteName:e.suite,trigger:c}});kc(l,"list runs");const{runs:u,hasMore:d}=l.data;e.json?process.stdout.write(Dc(l.data)):process.stdout.write(((e,t)=>{if(0===e.length)return q.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=`${Lc("Run ID",r.runId.w)}${Lc("Status",r.status.w)}${Lc("Branch",r.branch.w)}${Lc("Started",r.started.w)}Tests`;s.push(q.bold(o));for(const t of e){const e=Pc(t.runId,r.runId.t),n=Uc(t.status),o=Pc(t.branchName,r.branch.t),i=Rc(t.startedAt),a=t.totalCount.toString();s.push(`${Lc(e,r.runId.w)}${Lc(n,r.status.w)}${Lc(o,r.branch.w)}${Lc(i,r.started.w)}${a}`)}if(t&&e.length>0){const t=e.at(-1)?.runId;t&&(s.push(""),s.push(q.dim(`Next page: stably runs list --before ${t}`)))}return s.push(""),s.join("\n")})(u,d))}),gl.command("view <runId>").description("Show details for a specific run").option("--json","Output as JSON").action(async(e,t)=>{const n=await ss(),r=is(n),s=Ac(n);Jr.debug("Viewing run",{runId:e});const o=await Xn({auth:r,client:cr(),headers:cs(s),path:{runId:e},query:{detail:"full"}});if(kc(o,"get run details",`Run "${e}" not found.`),t.json)process.stdout.write(Dc(o.data));else{const e=o.data;process.stdout.write((e=>{const t=[];if(t.push(q.bold(`Run ${e.runId}`)),t.push(` ${q.dim("Status:")} ${Uc(e.status)}`),e.branchName&&t.push(` ${q.dim("Branch:")} ${e.branchName}`),e.commitSha&&t.push(` ${q.dim("Commit:")} ${e.commitSha.slice(0,7)}`),e.startedAt&&t.push(` ${q.dim("Started:")} ${Rc(e.startedAt)}`),null!==e.durationMs&&t.push(` ${q.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(` ${q.dim("Source:")} ${e.source.toLowerCase()}`),e.projectId){const n=`https://app.stably.ai/project/${e.projectId}/playwright/history/${e.runId}`;t.push(` ${q.dim("URL:")} ${q.cyan(q.underline(n))}`)}t.push("");const n=[];e.passedCount>0&&n.push(q.green(`${e.passedCount} passed`)),e.failedCount>0&&n.push(q.red(`${e.failedCount} failed`)),e.flakyCount>0&&n.push(q.yellow(`${e.flakyCount} flaky`)),e.timedoutCount>0&&n.push(q.red(`${e.timedoutCount} timedout`)),e.skippedCount>0&&n.push(q.dim(`${e.skippedCount} skipped`)),e.interruptedCount>0&&n.push(q.yellow(`${e.interruptedCount} interrupted`)),t.push(`${q.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(q.bold("Failed/Flaky Tests:"));for(const e of r){const n=e.status??"UNKNOWN",r=Cc[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}${q.dim(c)}`);const u=i?.at(-1);if(u?.errorMessage){const e=u.errorMessage.split("\n")[0]?.slice(0,100)??"";t.push(` ${q.dim(e)}`)}}}return t.push(""),t.join("\n")})(e))}}),cl.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)}),Tc.forEach(({args:e,description:t,name:n})=>{cl.command(n).description(t).helpOption(!1).helpCommand(!1).allowUnknownOption(!0).allowExcessArguments(!0).passThroughOptions().action(()=>Sc({overrideArgs:e,subcommand:n}))});var ml=()=>{0!==ll.length&&(process.stderr.write(ll.join("")),ll=[])};(async()=>{await(async()=>{if(!rl&&"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":Zn,"node.version":process.version,"os.platform":process.platform}}),rl=!0}catch{}})();try{await cl.parseAsync(process.argv),Jr.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 Jr.error(t,{stack:e instanceof Error?e.stack:void 0}),ml(),Jr.flush(),Jr.printLogFileInfo(),await sl(),void(process.exitCode=1)}const t="number"==typeof e.exitCode?e.exitCode:1,n=process.argv.slice(2).find(e=>!e.startsWith("-")),r=!!n&&!!dl(cl,[n]);if(("commander.excessArguments"===e.code||"commander.unknownCommand"===e.code)&&n&&!r)return ll=[],Jr.warn("Unknown command",{command:n}),process.stderr.write(`command '${n}' not found\n`),pl(),void(process.exitCode=t);Jr.debug("Commander error",{code:e.code,exitCode:t}),ml(),process.exitCode=t}finally{Jr.flush(),await sl()}})();
|
|
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,{existsSync as I,statSync as T,readFileSync as _,appendFileSync as E,realpathSync as S,createReadStream as x,mkdirSync as A,writeFileSync as k,rmSync 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 Y}from"@anthropic-ai/claude-agent-sdk";import{match as V}from"ts-pattern";import z from"net";import{createInterface as K}from"readline/promises";import q from"picocolors";import{simpleGit as J}from"simple-git";import Q,{randomUUID as X}from"crypto";import{readFile as Z,rm as ee,mkdir as te,writeFile as ne,unlink as re,access as se,readdir as oe,stat as ie,appendFile as ae}from"fs/promises";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 Ce}from"module";import{parseDocument as Pe}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 n=r.resolve(process.cwd(),t),s=e({path:n,override:!0,quiet:!0});if(s.error){const e=`warning: could not load env file: ${n} (${s.error.message})`;$e.envFileErrors.push(e),process.stderr.write(`${e}\n`)}else $e.envFilesLoaded.push(n)}var Be={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 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,n=Boolean(t);return{name:"Azure Pipelines",service:"azurePipelines",commit:e.BUILD_SOURCEVERSION,build:e.BUILD_BUILDNUMBER,branch:Me(n?e.SYSTEM_PULLREQUEST_TARGETBRANCH:e.BUILD_SOURCEBRANCH),pr:t,isPr:n,prBranch:Me(n?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,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}}},Ye={detect:({env:e})=>Boolean(e.BUDDY_WORKSPACE_ID),configuration({env:e}){const t=je(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 ze(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ke,qe,Je,Qe,Xe,Ze,et,tt,nt={exports:{}};var rt,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=r,t=function(){if(ot)return st;ot=1;const e=r,t=function(){if(tt)return et;tt=1;const e="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,t=r,n=e?";":":",s=function(){if(Ze)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 Ze=1,e="win32"===process.platform||Ve.TESTING_WINDOWS?function(){if(qe)return Ke;qe=1,Ke=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 Ke}():function(){if(Qe)return Je;Qe=1,Je=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 Je}(),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 et=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)},et}(),n=function(){if(rt)return bt.exports;rt=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(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 st=function(e){return s(e)||s(e,!0)}}(),n=function(){if(it)return wt;it=1;const e=/([()\][%!^"`<>&|;, *?])/g;return wt.command=function(t){return t.replace(e,"^$1")},wt.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},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 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 dt=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 ft=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 It=ze(function(){if(yt)return nt.exports;yt=1;const e=p,t=vt(),n=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 n(n,r){return e&&1===n&&!r.file?t(r.original,"spawn"):null}return gt={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},gt}();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 nt.exports=r,nt.exports.spawn=r,nt.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},nt.exports._parse=t,nt.exports._enoent=n,nt.exports}());function Tt(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 _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: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}},kt=({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}],Ct=(()=>{const e=xt();return Object.fromEntries(e.map(kt))})();(()=>{const e=xt(),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 Pt=({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:Ct[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},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 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}},Mt=class{},Ft=globalThis.process;Dt(Ft)?new class extends Mt{#e="win32"===Ft.platform?"SIGINT":"SIGHUP";#t=new jt;#n;#r;#s;#o={};#i=!1;constructor(e){super(),this.#n=e,this.#o={};for(const t of Ut)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(!Dt(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 Ut)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,Ut.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 Dt(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&&Dt(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)}}(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=[],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 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.-]+$/,Yt=j("execa").enabled,Vt=(e,t)=>String(e).padStart(t,"0"),zt=(e,t,n={})=>{const s=It._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:Yt,...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=Tt({env:e={...e}});return t.path=e[n],e[n]=(({cwd:e=b.cwd(),path:t=b.env[Tt()],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 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 n=Math.max(t.length,Rt.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}},Kt=(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=zt(e,t,n),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`${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),_(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 Pt({error:e,stdout:"",stderr:"",all:"",command:s,escapedCommand:o,parsed:r,timedOut:!1,isCanceled:!1,killed:!1})}const c=Kt(r.options,a.stdout,a.error),l=Kt(r.options,a.stderr,a.error);if(a.error||0!==a.status||null!==a.signal){const e=Pt({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 Jt(e){try{return qt("git",["rev-parse","HEAD"],e).stdout}catch{return}}function Qt(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$/,Zt=/^\/(.*)\.git$/;function en(e){if(e){if(e.match(Xt))return e.replace(Xt,"$1");try{return new URL(e).pathname.replace(Zt,"$1")}catch{return}}}var tn,nn={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:en(e.BUILDKITE_REPO),pr:t,isPr:n,prBranch:n?e.BUILDKITE_BRANCH:void 0,root:e.BUILDKITE_BUILD_CHECKOUT_PATH}}},rn={detect:({env:e})=>Boolean(e.CIRCLECI),configuration({env:e}){const t=e.CIRCLE_PR_NUMBER||je(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}`}}},sn="https://cirrus-ci.com",on={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:`${sn}/build/${e.CIRRUS_BUILD_ID}`,job:e.CIRRUS_TASK_ID,jobUrl:`${sn}/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}}},an={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})},cn={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}}},ln={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}}},un=({env:e})=>{try{const t=e.GITHUB_EVENT_PATH?JSON.parse(_(e.GITHUB_EVENT_PATH,"utf-8")):void 0;if(t&&t.pull_request)return{branch:t.pull_request.base?Me(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=Me("pull_request_target"===e.GITHUB_EVENT_NAME?`refs/pull/${(e=>{const t=e.GITHUB_EVENT_PATH?JSON.parse(_(e.GITHUB_EVENT_PATH,"utf-8")):void 0;return t&&t.pull_request?t.pull_request.number:void 0})(e)}/merge`:e.GITHUB_REF);return{name:"GitHub Actions",service:"github",commit:e.GITHUB_SHA,build:e.GITHUB_RUN_ID,buildUrl:`${e.GITHUB_SERVER_URL}/${e.GITHUB_REPOSITORY}/actions/runs/${e.GITHUB_RUN_ID}`,isPr: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||Jt({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||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||(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(tn)return In;tn=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=ze(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?Qt({env:e,cwd:t}):void 0)]))},An={appveyor:Be,azurePipelines:Fe,bamboo:He,bitbucket:Ge,bitrise:We,buddy:Ye,buildkite:nn,circleci:rn,cirrus:on,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:an,codefresh:cn,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:ln,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:Me(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=/[^a-zA-Z0-9-_]/g,Un=e=>{const t=e.trim().replace(Rn,"_");return t.length>0?t.slice(0,80):void 0},$n=e=>Un(e)??"issue",Ln=e=>"string"==typeof e?Un(e):void 0,Dn=class e{git;config;snapshotTreeHash;snapshotIndexPath;constructor(e){this.config=e,this.git=J({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-${X()}.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-${X()}.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 Nn(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 Nn(this.snapshotIndexPath),this.snapshotIndexPath=void 0),this.snapshotTreeHash=void 0}};async function Nn(e){try{await re(e)}catch{}}var On="x-stably-org-id",Bn={bodySerializer:e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t)},jn=({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):Mn({allowReserved:e,name:n,value:t})).join(o);return"label"===r||"matrix"===r?o+i:i},Mn=({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)}`},Fn=({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])=>Mn({allowReserved:e,name:"deepObject"===r?`${n}[${t}]`:t,value:s})).join(i);return"label"===r||"matrix"===r?i+a:a},Hn=/\{[^{}]+\}/g;function Gn(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 Wn,Yn=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},Vn=({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=jn({allowReserved:i.allowReserved,explode:!0,name:s,style:"form",value:o,...i.array});e&&r.push(e)}else if("object"==typeof o){const e=Fn({allowReserved:i.allowReserved,explode:!0,name:s,style:"deepObject",value:o,...i.object});e&&r.push(e)}else{const e=Mn({allowReserved:i.allowReserved,name:s,value:o});e&&r.push(e)}}return r.join("&")},zn=(e,t)=>!!t&&!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`)),Kn=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(Hn);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,jn({explode:r,name:s,style:o,value:i}));continue}if("object"==typeof i){n=n.replace(t,Fn({explode:r,name:s,style:o,value:i,valueOnly:!0}));continue}if("matrix"===o){n=n.replace(t,`;${Mn({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:Vn(e.querySerializer),url:e.url}),qn=(e,t)=>{const n={...e,...t};return n.baseUrl?.endsWith("/")&&(n.baseUrl=n.baseUrl.substring(0,n.baseUrl.length-1)),n.headers=Qn(e.headers,t.headers),n},Jn=e=>{const t=[];return e.forEach((e,n)=>{t.push([n,e])}),t},Qn=(...e)=>{const t=new Headers;for(const n of e){if(!n)continue;const e=n instanceof Headers?Jn(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},Xn=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}},Zn=Vn({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),er={"Content-Type":"application/json"},tr=(e={})=>({...Bn,headers:er,parseAs:"auto",querySerializer:Zn,...e}),nr=(e={})=>{let t=qn(tr(),e);const n=()=>({...t}),r={error:new Xn,request:new Xn,response:new Xn},s=async e=>{const n={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:Qn(t.headers,e.headers),serializedBody:void 0};return n.security&&await(async({security:e,...t})=>{for(const n of e){if(zn(t,n.name))continue;const e=await Yn(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:Kn(n)}},o=async e=>{const{opts:t,url:n}=await s(e),o={redirect:"follow",...t,body:Gn(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:Kn,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=qn(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")}},rr=nr(tr({baseUrl:"https://api.stably.ai"})),sr=e=>(e.client??rr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs",...e}),or=e=>(e.client??rr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}",...e}),ir="4.12.14-rc.0",ar=process.env.STABLY_API_URL||"https://api.stably.ai",cr=e=>{const t=new URL(e);return t.protocol="http:"===t.protocol?"ws:":"wss:",t},lr=process.env.AUTH_URL||"https://auth.stably.ai",ur=process.env.AUTH_CLIENT_ID||"288007877071cce81f269428ea78653a",dr=process.env.AI_PROXY_URL||"https://ai-proxy.stably.ai",pr=process.env.STABLY_AUTOHEAL_WS_URL||new URL("/autoheal",cr(ar)).toString(),fr=process.env.STABLY_CREATE_PROGRESS_WS_URL||new URL("/create-progress",cr(ar)).toString(),hr="http://localhost:9876/auth/callback",gr=()=>Wn||(Wn=nr(tr({baseUrl:ar,headers:{"X-STABLY-CLI-VERSION":ir,"X-STABLY-SOURCE":"cli"}}))),mr=async(e,t)=>{const n=await(r={body:{accessToken:e,orgId:t},client:gr()},(r.client??rr).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},yr=ge.object({org_id:ge.string(),org_name:ge.string()}),br=ge.object({email:ge.string(),org_id_to_org_member_info:ge.record(ge.string(),yr).optional(),org_member_info:yr.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 wr,vr=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)},Ir=e=>{try{const t=br.parse(vr(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"}`)}},Tr=async(e,t)=>{let n=e;const{root:s}=r.parse(n);for(;n!==s;){const e=r.join(n,t);try{return await se(e),e}catch{n=r.dirname(n)}}},_r=r.join(D.homedir(),".stably"),Er=r.join(_r,"auth.json"),Sr=".stably",xr="project.json",Ar=he.object({accessToken:he.string(),expiresAt:he.number(),idToken:he.string().optional(),refreshToken:he.string()}),kr=he.object({orgId:he.string(),orgName:he.string(),projectId:he.string(),projectName:he.string()}),Cr=async()=>{try{const e=await Z(Er,"utf-8");return Ar.parse(JSON.parse(e))}catch{return}},Pr=async e=>{await te(_r,{recursive:!0}),await ne(Er,JSON.stringify(e,null,2),{mode:384})},Rr=async()=>{try{await re(Er)}catch{}},Ur=async()=>{try{const e=await Tr(process.cwd(),Sr);if(!e)return;const t=r.join(e,xr),n=await Z(t,"utf-8");return kr.parse(JSON.parse(n))}catch{return}},$r=async()=>{try{const e=await Tr(process.cwd(),Sr);e&&await re(r.join(e,xr))}catch{}},Lr=e=>Date.now()>=e.expiresAt-3e5,Dr=async e=>{const t=new URLSearchParams({client_id:ur,grant_type:"refresh_token",refresh_token:e}),n=await fetch(`${lr}/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}},Nr=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`,Or=(e,t,n)=>{e.writeHead(t,{"Content-Type":"text/html"}),e.end(n)},Br=(e,t)=>{const n=new URLSearchParams({client_id:ur,code_challenge:e,code_challenge_method:"S256",redirect_uri:hr,response_type:"code",state:t});return`${lr}/propelauth/oauth/authorize?${n.toString()}`},jr=async e=>{const t=ue();let n;t.start("Loading user info...");try{n=Ir(e.accessToken),t.stop(q.green(`β Logged in as ${q.cyan(n.email)}`))}catch(e){t.stop(q.red("β Failed to load user info"));const n=e instanceof Error?e.message:"Unknown error";return ce.error(n),{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: ${q.cyan(e[0].name)}`),e[0];if(!process.stdin.isTTY)return ce.info(`Auto-selecting organization: ${q.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)})(n.organizations);if(!s)return ce.warn("Organization selection cancelled."),{success:!1};let o;t.start("Getting org credentials...");try{const n=await mr(e.accessToken,s.id);o={accessToken:n.accessToken,expiresAt:Date.now()+1e3*n.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken},t.stop(q.green("β Credentials obtained"))}catch(e){t.stop(q.red("β Failed to get org credentials"));const n=e instanceof Error?e.message:"Unknown error";return ce.error(n),{success:!1}}const i=await(async(e,t)=>{const n=ue();let r;n.start("Loading projects...");try{r=await(async({accessToken:e,orgId:t})=>{const n=await(r={auth:e,client:gr(),path:{orgId:t}},(r.client??rr).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(q.green("β Projects loaded"))}catch(e){n.stop(q.red("β Failed to load projects"));const t=e instanceof Error?e.message:"Unknown error";return void ce.error(t)}if(0===r.length)return ce.error("No projects found in this organization."),void ce.info(`Create a project at ${q.underline(q.cyan("https://app.stably.ai"))}`);if(1===r.length)return ce.info(`Using project: ${q.cyan(r[0].name)}`),r[0];if(!process.stdin.isTTY)return ce.info(`Auto-selecting project: ${q.cyan(r[0].name)}`),r[0];const s=await pe({message:"Select a project",options:r.map(e=>({label:e.name,value:e.id}))});return fe(s)?void 0:r.find(e=>e.id===s)})(o.accessToken,s.id);return i?(await(async e=>{const t=r.join(process.cwd(),Sr),n=r.join(t,xr);await te(t,{recursive:!0}),await ne(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 ne(t,r)}else if(o.test(e)){const r=e.replace(o,`\n${n}\n`);await ne(t,r)}else await ae(t,`\n${n}\n`)}catch{await ne(t,`${n}\n`)}})(process.cwd())})({orgId:s.id,orgName:s.name,projectId:i.id,projectName:i.name}),ce.info(q.dim("Linked this directory to your Stably project.")),{scopedTokens:o,success:!0}):(ce.warn("Project selection cancelled."),{success:!1})},Mr=async()=>{if(ls())return ce.warn(`Environment variables ${q.cyan("STABLY_API_KEY")} and ${q.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(q.yellow("Login skipped - using environment variable authentication."));const e=await Cr();if(e){if(!Lr(e)){if(await Ur())return void le(q.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 jr(e);return void(t.success?(await Pr(t.scopedTokens),le(q.green("Setup complete! You can now use Stably CLI."))):le(q.yellow("Setup incomplete. Run `stably login` to try again.")))}const t=ue();t.start("Refreshing session...");try{const n=await Dr(e.refreshToken);t.stop(q.green("β Session refreshed"));const r=await Ur();if(r){t.start("Getting org credentials...");try{const e=await mr(n.accessToken,r.orgId),s={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:n.idToken,refreshToken:n.refreshToken};await Pr(s),t.stop(q.green("β Credentials obtained")),le(q.green("Login successful"))}catch{await Pr(n),t.stop(q.yellow("Using full credentials")),le(q.green("Login successful"))}}else{const e=await jr(n);e.success?(await Pr(e.scopedTokens),le(q.green("Setup complete! You can now use Stably CLI."))):le(q.yellow("Setup incomplete. Run `stably login` to try again."))}return}catch{t.stop(q.yellow("Session expired, proceeding with fresh login...")),await Rr(),await $r()}}const{authorizeUrl:t,serverReady:n,waitForCallback:r}=(()=>{const{authorizeUrl:e,codeVerifier:t,state:n}=(()=>{const e=Q.randomBytes(32).toString("base64url"),t=(n=e,Q.createHash("sha256").update(n).digest("base64url"));var n;const r=Q.randomBytes(16).toString("base64url");return{authorizeUrl:Br(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=ye.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?(Or(n,400,Nr(l)),i(),a.close(),void r({error:l,success:!1})):o&&c?c!==e?(Or(n,400,Nr("Invalid state parameter (possible CSRF attack)")),i(),a.close(),void r({error:"State mismatch",success:!1})):(Or(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})):(Or(n,400,Nr("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:ur,code:e,code_verifier:t,grant_type:"authorization_code",redirect_uri:hr}),r=await fetch(`${lr}/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,ce.info("Opening browser for authentication..."),ce.info(q.dim("If browser doesn't open, visit:")),ce.info(`]8;;${t}${q.underline(q.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 r(),s.stop(q.green("β Authentication successful"))}catch(e){s.stop(q.red("β Authentication failed"));const t=e instanceof Error?e.message:"Unknown error";le(q.red(`Login failed: ${t}`)),process.exit(1)}const i=await jr(o);i.success?(await Pr(i.scopedTokens),le(q.green("Setup complete! You can now use Stably CLI."))):(le(q.yellow("Setup incomplete. Run `stably login` to try again.")),process.exit(1))},Fr={fatal:60,error:50,warn:40,info:30,debug:20,trace:10},Hr=new Set(["help","login","logout","whoami","tunnel","create","fix","init","upgrade","test","show-report","codegen"]),Gr=(new Date).toISOString().split("T")[0],Wr=(()=>{const e=[r.join(D.tmpdir(),"stably-logs",Gr),r.join(D.homedir(),".stably","logs",Gr)];for(const t of e)try{return v.mkdirSync(t,{recursive:!0}),t}catch{}return null})(),Yr=process.argv.includes("--verbose")||process.argv.includes("-v"),Vr=process.env.STABLY_LOG_LEVEL?.toLowerCase(),zr=Yr?"debug":void 0!==(wr=Vr)&&wr in Fr?Vr:"warn",Kr=Fr[zr],qr=null,Jr=null,Qr=null,Xr=[],Zr=!1,es=e=>{if(!Zr){if(!(qr=(e=>{if(!Wr)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(Wr,`${t}-${n}.log`)})(e)))return Xr=[],void(Zr=!0);(e=>{const t=["","=".repeat(60),"Stably CLI Debug Log",`Version: ${ir}`,`Generated: ${(new Date).toISOString()}`,`Node: ${process.version}`,`Platform: ${process.platform} ${D.release()}`,`CWD: ${process.cwd()}`,`Args: ${process.argv.slice(2).join(" ")}`,`Log Level (console): ${zr}`,"=".repeat(60),""].join("\n");e.write(t)})(Jr=new we({dest:qr,minLength:4096,sync:!1,append:!0})),Qr=be({level:"debug",timestamp:be.stdTimeFunctions.isoTime,base:{version:ir}},Jr);for(const{level:e,msg:t,context:n}of Xr)n?Qr[e](n,t):Qr[e](t);Xr=[],Zr=!0,Yr&&process.stderr.write(`${q.dim(`Debug log: ${qr}`)}\n\n`)}},ts=(()=>{const e=process.argv.slice(2).find(e=>!e.startsWith("-"));return e&&Hr.has(e)?e:null})();ts&&es(ts);var ns=e=>(t,n)=>{if(Qr?n?Qr[e](n,t):Qr[e](t):Zr||Xr.push({level:e,msg:t,context:n}),(e=>Fr[e]>=Kr)(e)){const n=((e,t)=>`${{fatal:q.bgRed(q.white(" FATAL ")),error:q.red("error"),warn:q.yellow("warn"),info:q.cyan("info"),debug:q.dim("debug"),trace:q.dim("trace")}[e]} ${t}`)(e,t);process.stderr.write(`${n}\n`)}},rs={fatal:ns("fatal"),error:ns("error"),warn:ns("warn"),info:ns("info"),debug:ns("debug"),trace:ns("trace"),initSession:e=>{Zr||es(e)},getLogFilePath:()=>qr,flush:()=>{if(Jr)try{Jr.flushSync()}catch{}},printLogFileInfo:()=>{qr&&(process.stderr.write(`\n${q.dim("Debug log written to:")}\n`),process.stderr.write(` ${q.cyan(qr)}\n`),process.stderr.write(`${q.dim("Share this file with support for assistance.")}\n`))},getPinoLogger:()=>Qr};setInterval(()=>{rs.flush()},3e4).unref(),process.on("beforeExit",()=>{rs.flush()});var ss=e=>{const t=()=>{rs.flush(),Yr&&rs.printLogFileInfo(),process.removeListener(e,t),process.kill(process.pid,e)};return t};process.on("SIGINT",ss("SIGINT")),process.on("SIGTERM",ss("SIGTERM"));var os=()=>"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",is=()=>"local"!==os(),as=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"}},cs=()=>{const e=os();return[`Authentication failed. In CI, add the following to your ${as(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")},ls=()=>{const e=process.env.STABLY_API_KEY?.trim(),t=process.env.STABLY_PROJECT_ID?.trim();if(e&&t)return rs.debug("Environment auth detected",{hasApiKey:!0,hasProjectId:!0}),{apiKey:e,projectId:t};rs.debug("Environment auth not set",{hasApiKey:!!e,hasProjectId:!!t})},us=async()=>{rs.debug("Checking for stored auth tokens");const e=await Cr();if(!e)return void rs.debug("No stored auth tokens found");const t=Lr(e);if(rs.debug("Auth tokens status",{expired:t}),!t){const t=await Ur(),n=(e=>{try{const t=br.parse(vr(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(rs.debug("Token scope check",{scope:n,hasContext:!!t}),t&&"full"===n)try{rs.debug("Exchanging full token for org-scoped token",{orgId:t.orgId});const n=await mr(e.accessToken,t.orgId),r={accessToken:n.accessToken,expiresAt:Date.now()+1e3*n.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken};return await Pr(r),rs.debug("Token exchange successful"),r}catch(t){return rs.debug("Token exchange failed, using existing token",{error:t instanceof Error?t.message:String(t)}),e}return e}try{rs.debug("Attempting token refresh");const t=await Dr(e.refreshToken);rs.debug("Token refresh successful");const n=await Ur();if(n)try{rs.debug("Exchanging refreshed token for org-scoped token");const e=await mr(t.accessToken,n.orgId),r={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:t.idToken,refreshToken:t.refreshToken};return await Pr(r),r}catch{return await Pr(t),t}return await Pr(t),t}catch(e){return void rs.warn("Token refresh failed",{error:e instanceof Error?e.message:String(e)})}},ds=async(e={})=>{rs.debug("Requiring authentication",{autoLogin:e.autoLogin});const t=ls();if(t)return rs.info("Using environment variable authentication"),{auth:t,type:"env"};let n=await us(),r=n?await Ur():void 0;const s=process.stdin.isTTY&&process.stdout.isTTY;if(rs.debug("OAuth auth check",{hasTokens:!!n,hasContext:!!r,canPrompt:s}),(!n||!r)&&e.autoLogin&&s){rs.info("Prompting user to login"),n?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(`${q.dim("Alternatively, set environment variables for an org API key:")}\n${q.dim(" STABLY_API_KEY=... STABLY_PROJECT_ID=... stably")}\n`),process.stdout.write("\n");const e=K({input:process.stdin,output:process.stdout});try{await e.question(q.dim("Press Enter to continue... "))}finally{e.close()}await Mr(),n=await us(),r=n?await Ur():void 0}return n||(rs.warn("Authentication required but no tokens available"),is()?le(q.red(cs())):le(q.red("You are not logged in. Run `stably login` to authenticate.")),process.exit(1)),r||(rs.warn("Authentication succeeded but no project context selected"),is()?le(q.red(cs())):le(q.red("You haven't selected an organization and project. Run `stably login` to complete setup.")),process.exit(1)),rs.info("OAuth authentication successful",{orgId:r.orgId,projectId:r.projectId}),{auth:{accessToken:n.accessToken,context:r},type:"oauth"}},ps=e=>"env"===e.type?e.auth.projectId:e.auth.context.projectId,fs=e=>"env"===e.type?e.auth.apiKey:e.auth.accessToken,hs=async()=>{const e=$e.remoteEnvName;if(!e)return;const t=await ds(),n=ps(t),r=fs(t);rs.debug("Fetching remote environment variables",{envName:e,projectId:n});const s=await(o={auth:r,client:gr(),path:{projectId:n,environment:e}},(o.client??rr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/environments/{environment}/variables",...o}));var o;404===s.response.status&&(le(q.red(`Environment "${e}" not found. Check the name on your Stably dashboard.`)),process.exit(1)),401!==s.response.status&&403!==s.response.status||(le(q.red(`Access denied to environment "${e}".`)),process.exit(1)),s.error&&(le(q.red(`Failed to fetch environment "${e}": ${s.response.status}`)),process.exit(1));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(`${q.cyan(`Loaded ${c} variable${1!==c?"s":""} from "${e}"`)}${l>0?q.dim(` (${l} sensitive)`):""}\n`),{variables:i,sensitiveValues:a}},gs=e=>e?{[On]:e}:void 0,ms=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()}),ys=ve.object({bucket:ve.string(),key:ve.string()}),bs=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})`)},ws=ve.object({diffBucketPath:ys,expiresInSeconds:ve.number(),key:ve.string(),uploadUrl:ve.string()}),vs=ve.object({traceBucketPath:ys,expiresInSeconds:ve.number(),key:ve.string(),uploadUrl:ve.string(),sensitiveValues:ve.array(ve.string())}),Is=async({authHeader:e,contentType:t="text/plain",orgId:n,runId:r})=>{const s=await(o={auth:e,body:{contentType:t},client:gr(),headers:gs(n),path:{runId:r}},(o.client??rr).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=ws.parse(s.data);return{diffBucketPath:i.diffBucketPath,expiresInSeconds:i.expiresInSeconds,key:i.key,uploadUrl:i.uploadUrl}},Ts=async({authHeader:e,diffBucketPath:t,orgId:n,runId:r})=>{const s=await(o={auth:e,body:t,client:gr(),headers:gs(n),path:{runId:r}},(o.client??rr).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})`)},_s=class{socket;url;authHeader;orgId;runId;pendingEvent=null;reconnectAttempts=0;reconnectTimer;debounceTimer;_isClosed=!1;isAuthenticated=!1;authenticationFailed=!1;onUserMessage;maxReconnectAttempts=10;baseReconnectDelay=2e3;maxReconnectDelay=3e4;debounceMs=500;get isClosed(){return this._isClosed}constructor({authHeader:e,orgId:t,runId:n,url:r=pr,onUserMessage:s}){this.authHeader=e,this.orgId=t,this.runId=n,this.url=r,this.onUserMessage=s,rs.info("[ws] Constructing AutohealWebSocketClient",{url:this.url,runId:n})}start(){this.connect()}connect(){if(!this._isClosed)try{const e={Authorization:this.authHeader};this.orgId&&(e["x-stably-org-id"]=this.orgId);const t=`${this.url}?runId=${encodeURIComponent(this.runId)}`;rs.info("[ws] Connecting",{url:t,attempt:this.reconnectAttempts}),this.socket=new Ie(t,{headers:e}),this.socket.on("open",()=>{rs.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);rs.debug("[ws] Received message",{type:n?.type}),"connected"===n?.type&&(rs.info("[ws] Authenticated successfully"),this.isAuthenticated=!0,this.authenticationFailed=!1,this.flushPending()),"user_message"===n?.type&&"string"==typeof n.content&&(rs.info("[ws] Received user message from web UI"),this.onUserMessage?.(n.content))}catch{}}),this.socket.on("close",(e,t)=>{rs.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=>{rs.warn("[ws] Connection error",{error:e.message})})}catch(e){rs.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);rs.info("[ws] Scheduling reconnect",{attempt:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts,delayMs:e}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect()},e)}isConnected(){return!!this.socket&&this.socket.readyState===Ie.OPEN&&this.isAuthenticated}sendProgress(e){if(this._isClosed)return void rs.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?(rs.info("[ws] sendProgress: flushing terminal state immediately"),void this.flushPending()):void(this.debounceTimer||(this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.flushPending()},this.debounceMs))):(rs.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 rs.debug("[ws] flushPending: not connected, re-queuing event",{phase:e.payload.phase}),void(this.pendingEvent=e);try{rs.debug("[ws] flushPending: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),t=>{t&&(rs.warn("[ws] flushPending: send failed",{error:t.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e))})}catch(t){rs.warn("[ws] flushPending: send threw",{error:t instanceof Error?t.message:String(t)}),this.pendingEvent=e}}flushPendingAndWait(){if(this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),!this.pendingEvent)return Promise.resolve();const e=this.pendingEvent;return this.pendingEvent=null,this.isConnected()?new Promise(t=>{try{rs.debug("[ws] flushPendingAndWait: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),n=>{n&&(rs.warn("[ws] flushPendingAndWait: send failed",{error:n.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e)),t()})}catch(n){rs.warn("[ws] flushPendingAndWait: send threw",{error:n instanceof Error?n.message:String(n)}),this.pendingEvent=e,t()}}):(rs.warn("[ws] flushPendingAndWait: not connected, event will be dropped",{phase:e.payload.phase}),this.pendingEvent=e,Promise.resolve())}close(){if(this._isClosed)return;rs.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;rs.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=class{socket;url;authHeader;orgId;sessionId;pendingEvent=null;reconnectAttempts=0;reconnectTimer;debounceTimer;_isClosed=!1;isAuthenticated=!1;authenticationFailed=!1;onUserMessage;maxReconnectAttempts=10;baseReconnectDelay=2e3;maxReconnectDelay=3e4;debounceMs=500;get isClosed(){return this._isClosed}constructor({authHeader:e,orgId:t,sessionId:n,url:r=fr,onUserMessage:s}){this.authHeader=e,this.orgId=t,this.sessionId=n,this.url=r,this.onUserMessage=s,rs.info("[ws] Constructing CreateProgressWebSocketClient",{url:this.url,sessionId:n})}start(){this.connect()}connect(){if(!this._isClosed)try{const e={Authorization:this.authHeader};this.orgId&&(e["x-stably-org-id"]=this.orgId);const t=`${this.url}?sessionId=${encodeURIComponent(this.sessionId)}`;rs.info("[ws] Connecting",{url:t,attempt:this.reconnectAttempts}),this.socket=new Ie(t,{headers:e}),this.socket.on("open",()=>{rs.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);rs.debug("[ws] Received message",{type:n?.type}),"connected"===n?.type&&(rs.info("[ws] Authenticated successfully"),this.isAuthenticated=!0,this.authenticationFailed=!1,this.flushPending()),"user_message"===n?.type&&"string"==typeof n.content&&(rs.info("[ws] Received user message from web UI"),this.onUserMessage?.(n.content))}catch{}}),this.socket.on("close",(e,t)=>{rs.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=>{rs.warn("[ws] Connection error",{error:e.message})})}catch(e){rs.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);rs.info("[ws] Scheduling reconnect",{attempt:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts,delayMs:e}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect()},e)}isConnected(){return!!this.socket&&this.socket.readyState===Ie.OPEN&&this.isAuthenticated}sendProgress(e){if(this._isClosed)return void rs.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?(rs.info("[ws] sendProgress: flushing terminal state immediately"),void this.flushPending()):void(this.debounceTimer||(this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.flushPending()},this.debounceMs))):(rs.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 rs.debug("[ws] flushPending: not connected, re-queuing event",{phase:e.payload.phase}),void(this.pendingEvent=e);try{rs.debug("[ws] flushPending: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),t=>{t&&(rs.warn("[ws] flushPending: send failed",{error:t.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e))})}catch(t){rs.warn("[ws] flushPending: send threw",{error:t instanceof Error?t.message:String(t)}),this.pendingEvent=e}}flushPendingAndWait(){if(this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),!this.pendingEvent)return Promise.resolve();const e=this.pendingEvent;return this.pendingEvent=null,this.isConnected()?new Promise(t=>{try{rs.debug("[ws] flushPendingAndWait: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),n=>{n&&(rs.warn("[ws] flushPendingAndWait: send failed",{error:n.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e)),t()})}catch(n){rs.warn("[ws] flushPendingAndWait: send threw",{error:n instanceof Error?n.message:String(n)}),this.pendingEvent=e,t()}}):(rs.warn("[ws] flushPendingAndWait: not connected, event will be dropped",{phase:e.payload.phase}),this.pendingEvent=e,Promise.resolve())}close(){if(this._isClosed)return;rs.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;rs.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())}},Ss=ve.object({bucketPath:ys,expiresInSeconds:ve.number(),key:ve.string(),uploadUrl:ve.string()}),xs=ge.object({uploadUrl:ge.string(),key:ge.string(),bucketPath:ge.object({bucket:ge.string(),key:ge.string()}),expiresInSeconds:ge.number()});async function As({authHeader:e,orgId:t,sessionId:n,projectId:r,history:s}){if(0===s.length)return rs.debug("[session-history] No history to upload"),{success:!0};try{rs.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=new URL(`/internal/v1/cli/sessions/${n}/history/upload-url`,ar),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",...r?{projectId:r}:{}}),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 xs.parse(await i.json())}({authHeader:e,orgId:t,sessionId:n,projectId:r}),a=s.map(e=>JSON.stringify(e)).join("\n");rs.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 rs.info("[session-history] History uploaded successfully",{key:i}),{success:!0,key:i}}catch(e){const t=e instanceof Error?e.message:String(e);return rs.warn("[session-history] Failed to upload history",{error:t}),{success:!1,error:t}}}var ks="1.58.0",Cs=["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 Rs(e){return Boolean(e&&"object"==typeof e&&"tool_input"in e&&e.tool_input&&"object"==typeof e.tool_input)}function Us({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(!Rs(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: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 $s=["rm","mv","git","gh","npx","stably","stably-browser","pwtrace","npm","yarn","pnpm","bun"],Ls=["stably","playwright","stably-browser","pwtrace"],Ds=["create","fix","verify"],Ns=["upload"],Os=["push","fetch","pull","clone","ls-remote"],Bs=/\S+=(?:'[^']*(?:'\\''[^']*)*'|\S+)/;function js(e){const t=[],n=e.trim(),r=/(?:'[^']*(?:'\\''[^']*)*'|\S)+/g;let s;for(;null!==(s=r.exec(n));)t.push(s[0]);return t}function Ms(e){let t=0;const n=new RegExp(`^${Bs.source}$`);for(;t<e.length&&n.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 n=t[e];if(n){if("--"===n)return t[e+1];if(!n.startsWith("-"))return n}}}function Hs(e){return js(e).find(e=>Ds.includes(e))}function Gs(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 Ws({onBeforeGitHubCommand:e,workspaceBoundary:t}){return async n=>{if(!Rs(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 r=n.tool_input,{command:i}=r;if("string"!=typeof i)return{decision:"block",reason:"Invalid Bash command: command must be a string.",systemMessage:"Tool call blocked due to invalid command type"};const c=function(e){const t=e.trim(),n=new RegExp(`^(?:${Bs.source}\\s+)*(\\S+)`),r=t.match(n);return r?.[1]}(i);if(!c)return{decision:"block",reason:"Invalid Bash command: could not parse command.",systemMessage:"Tool call blocked due to unparseable command"};if("run_in_background"in r&&!0===r.run_in_background&&/\bstably-browser\s+run-test\b/.test(i))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&&$s.includes(e)}(c))return{decision:"block",reason:`The command "${c}" is not allowed. Only the following commands are permitted: ${$s.join(", ")}. Use the appropriate tools (Read, Write, Edit, Glob, Grep) for file operations instead.`,systemMessage:"Tool call blocked due to disallowed command"};if("npx"===c){const e=function(e){if(/(\s|^)npx\s+.*(\s|^)(-c|--call)(\s|=)/.test(e.trim()))return{valid:!1,reason:"The npx -c/--call form is not allowed. Use direct commands like `npx stably test ...`."};const t=Fs(e);if(!t)return{valid:!1,reason:"Invalid npx command: unable to determine which binary is being executed."};if(!new Set(Ls).has(t))return{valid:!1,reason:`The npx binary "${t}" is not allowed. Only ${Ls.join(", ")} are permitted.`};if("stably-browser"!==t){const n=Hs(e);if(n)return{valid:!1,reason:`The npx ${t} subcommand "${n}" is not allowed. The commands ${Ds.join(", ")} are AI-powered and blocked to prevent recursion.`}}return{valid:!0}}(i);if(!e.valid)return{decision:"block",reason:e.reason,systemMessage:"Tool call blocked due to disallowed npx command"}}if("stably-browser"===c||"npx"===c&&"stably-browser"===Fs(i)){const e=function({command:e,binary:t}){const n=Ms(js(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 t}}({command:i,binary:"stably-browser"});if(e&&Ns.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"===c){const e=Hs(i);if(e)return{decision:"block",reason:`The stably subcommand "${e}" is not allowed. The commands ${Ds.join(", ")} are AI-powered and blocked to prevent recursion.`,systemMessage:"Tool call blocked due to disallowed stably command"}}if("rm"===c){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):[]}(i);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(I(e))return S.native(e);let t=e;const n=[];for(;!I(t);){const r=o(t);if(r===t)return s(e);n.unshift(t.slice(r.length+1)),t=r}const r=S.native(t);return n.length>0?s(r,...n):r}(e),r=S.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=>!(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"===c&&["-c","--config","--config-env"].some(e=>i.includes(` ${e} `)||i.includes(` ${e}=`)))return{decision:"block",reason:"Git config flags (-c, --config, --config-env) are not allowed for security reasons.",systemMessage:"Tool call blocked due to git config injection attempt"};if("git"===c&&function(e){const t=e.trim();return!!t.startsWith("git ")&&Os.some(e=>t.includes(` ${e}`)||t.includes(`git ${e}`))}(i)&&e)try{await e()}catch(e){console.error("[BashSecurityHook] Failed to refresh git token:",e)}if("gh"===c){const t=function(e){const t=e.toLowerCase();return Cs.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}}(i);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 Ys=/\.(spec|test)\.(ts|tsx|js|jsx|mts|mjs)$/;function Vs({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&&Ys.test(r)&&e(r),{decision:"approve"}}}var zs=M(f);async function Ks(){try{const{stdout:e}=await zs('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 zs(`pkill -KILL -P ${e} '.*' 2>/dev/null || true`)}))}catch{}}var qs=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:n})=>{try{const e=(await ie(n)).size,r=await Z(n,"utf-8"),s=Buffer.byteLength(r,"utf-8");if(s<=Xs)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<=Xs?o:o.slice(0,Xs)+`\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}},eo=async({defaultContent:e,dirName:t,dirPath:n})=>{try{const e=await oe(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}},to=async({allowedEnvVars:e,mode:t,workspaceInfo:n,authHeader:r,customHeader:s,maxParallelWorkers:o})=>{const i=gr(),a=Js(n.absolutePath);rs.debug("Requesting system prompt from API",{mode:t,hasGitContext:!!a,envVarCount:e.length});const c=await(l={client:i,auth:r,body:{mode:t,workspaceInfo:n,allowedEnvVars:e,gitContext:a,maxParallelWorkers:o}},(l.client??rr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/prompts/system",...l,headers:{"Content-Type":"application/json",...l.headers}}));var l;if(401===c.response.status)throw rs.warn("System prompt fetch failed: unauthorized (401)"),await Rr(),new Error("Your session has expired or been revoked. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(403===c.response.status)throw rs.debug("System prompt fetch failed: forbidden (403)"),new Error("Your organization does not have an active subscription. Manage your subscription at https://app.stably.ai or contact your organization admin.");if(c.error){rs.warn("System prompt fetch failed",{error:c.error});const e=JSON.stringify(c.error);if(e.toLowerCase().includes("unauthorized")||e.toLowerCase().includes("unauthenticated"))throw await Rr(),new Error("Your session has expired or been revoked. Credentials have been cleared. Please run `stably login` to re-authenticate.");throw new Error("Failed to fetch system prompt. Please check your network connection and try again. If this persists, run `stably login` to re-authenticate.")}const u=function({customHeader:e,systemPrompt:t}){return e?`${t}\n\nWhen writing or updating the generated test file, prepend this exact header at the top of the file without modification:\n\`\`\`ts\n${e}\n\`\`\``:t}({systemPrompt:c.data.systemPrompt,customHeader:s});return rs.debug("System prompt received",{size:u.length,appendedCustomHeader:!!s,hasPrContext:!!c.data.prContext}),{systemPrompt:u,prContext:c.data.prContext}},no={chat:"chat",single:"create",fix:"fix",init:"init",verify:"verify"},ro=".stably-playwright-wrapper.config.*",so=[".ts",".js",".mts",".mjs",".cts",".cjs"];function oo(e){const t=s(e);if(I(t))for(const e of so){const n=i(t,`playwright.config${e}`);if(I(n))return n}}var io=["tests","e2e","__tests__","test"];function ao(e){try{return I(e)&&T(e).isDirectory()}catch{return!1}}function co(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(q.dim(`Using output directory: ${e} (from ${n})`))}var lo,uo=["mcp__playwright-test__","mcp__auto-heal-report__","mcp__stably-agent-control__"],po=["planner_","generator_"],fo={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"},ho={"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"},go={Skill:"Preparing for task",ToolSearch:"Searching tools"},mo=(e,t)=>{const n=t.find(t=>e.startsWith(t));return n?e.slice(n.length):e},yo=e=>e.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" "),bo=(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},wo=(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 ho[t]?ho[t]:`Loading ${t.replace(/-/g," ")}`}return"Preparing for task"}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();if("string"==typeof n.description&&n.description.trim())return n.description.trim();const o=fo[t];return o?o(s):`${yo(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":null},vo=e=>"mcp__auto-heal-report__capture-trace-proof"===e?"Verify Test Run":"mcp__auto-heal-report__generate-report"===e?"Generate Report":(e=>{const t=go[e];if(t)return t;const n=mo(e,uo),r=mo(n,po);return yo(r)})(e),Io=Ce("/");try{lo=Io("worker_threads").Worker}catch(e){}var To=lo?function(e,t,n,r,s){var o=!1,i=new lo(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,lo.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}},_o=Uint8Array,Eo=Uint16Array,So=Int32Array,xo=new _o([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]),Ao=new _o([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]),ko=new _o([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Co=function(e,t){for(var n=new Eo(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];var s=new So(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}},Po=Co(xo,2),Ro=Po.b,Uo=Po.r;Ro[28]=258,Uo[258]=28;var $o,Lo=Co(Ao,0),Do=Lo.b,No=Lo.r,Oo=new Eo(32768);for(Mo=0;Mo<32768;++Mo)$o=(61680&($o=(52428&($o=(43690&Mo)>>1|(21845&Mo)<<1))>>2|(13107&$o)<<2))>>4|(3855&$o)<<4,Oo[Mo]=((65280&$o)>>8|(255&$o)<<8)>>1;var Bo=function(e,t,n){for(var r=e.length,s=0,o=new Eo(t);s<r;++s)e[s]&&++o[e[s]-1];var i,a=new Eo(t);for(s=1;s<t;++s)a[s]=a[s-1]+o[s-1]<<1;if(n){i=new Eo(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[Oo[d]>>c]=l}else for(i=new Eo(r),s=0;s<r;++s)e[s]&&(i[s]=Oo[a[e[s]-1]++]>>15-e[s]);return i},jo=new _o(288);for(Mo=0;Mo<144;++Mo)jo[Mo]=8;for(Mo=144;Mo<256;++Mo)jo[Mo]=9;for(Mo=256;Mo<280;++Mo)jo[Mo]=7;for(Mo=280;Mo<288;++Mo)jo[Mo]=8;var Mo,Fo=new _o(32);for(Mo=0;Mo<32;++Mo)Fo[Mo]=5;var Ho=Bo(jo,9,0),Go=Bo(jo,9,1),Wo=Bo(Fo,5,0),Yo=Bo(Fo,5,1),Vo=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},zo=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(7&t)&n},Ko=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(7&t)},qo=function(e){return(e+7)/8|0},Jo=function(e,t,n){return(null==t||t<0)&&(t=0),(null==n||n>e.length)&&(n=e.length),new _o(e.subarray(t,n))},Qo=["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"],Xo=function(e,t,n){var r=new Error(t||Qo[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,Xo),!n)throw r;return r},Zo=function(e,t,n,r){var s=e.length,o=r?r.length:0;if(!s||t.f&&!t.l)return n||new _o(0);var i=!n,a=i||2!=t.i,c=t.i;i&&(n=new _o(3*s));var l=function(e){var t=n.length;if(e>t){var r=new _o(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=zo(e,d,1);var b=zo(e,d+1,3);if(d+=3,!b){var w=e[(P=qo(d)+4)-4]|e[P-3]<<8,v=P+w;if(v>s){c&&Xo(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=Go,h=Yo,g=9,m=5;else if(2==b){var I=zo(e,d,31)+257,T=zo(e,d+10,15)+4,_=I+zo(e,d+5,31)+1;d+=14;for(var E=new _o(_),S=new _o(19),x=0;x<T;++x)S[ko[x]]=zo(e,d+3*x,7);d+=3*T;var A=Vo(S),k=(1<<A)-1,C=Bo(S,A,1);for(x=0;x<_;){var P,R=C[zo(e,d,k)];if(d+=15&R,(P=R>>4)<16)E[x++]=P;else{var U=0,$=0;for(16==P?($=3+zo(e,d,3),d+=2,U=E[x-1]):17==P?($=3+zo(e,d,7),d+=3):18==P&&($=11+zo(e,d,127),d+=7);$--;)E[x++]=U}}var L=E.subarray(0,I),D=E.subarray(I);g=Vo(L),m=Vo(D),f=Bo(L,g,1),h=Bo(D,m,1)}else Xo(1);if(d>y){c&&Xo(0);break}}a&&l(p+131072);for(var N=(1<<g)-1,O=(1<<m)-1,B=d;;B=d){var j=(U=f[Ko(e,d)&N])>>4;if((d+=15&U)>y){c&&Xo(0);break}if(U||Xo(2),j<256)n[p++]=j;else{if(256==j){B=d,f=null;break}var M=j-254;if(j>264){var F=xo[x=j-257];M=zo(e,d,(1<<F)-1)+Ro[x],d+=F}var H=h[Ko(e,d)&O],G=H>>4;if(H||Xo(3),d+=15&H,D=Do[G],G>3&&(F=Ao[G],D+=Ko(e,d)&(1<<F)-1,d+=F),d>y){c&&Xo(0);break}a&&l(p+131072);var W=p+M;if(p<D){var Y=o-D,V=Math.min(D,W);for(Y+p<0&&Xo(3);p<V;++p)n[p]=r[Y+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?Jo(n,0,p):n.subarray(0,p)},ei=function(e,t,n){n<<=7&t;var r=t/8|0;e[r]|=n,e[r+1]|=n>>8},ti=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},ni=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:li,l:0};if(1==s){var i=new _o(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 Eo(p+1),h=ri(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 _o(f),l:h}},ri=function(e,t,n){return-1==e.s?Math.max(ri(e.l,t,n+1),ri(e.r,t,n+1)):t[e.s]=n},si=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new Eo(++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}},oi=function(e,t){for(var n=0,r=0;r<t.length;++r)n+=e[r]*t[r];return n},ii=function(e,t,n){var r=n.length,s=qo(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)},ai=function(e,t,n,r,s,o,i,a,c,l,u){ei(t,u++,n),++s[256];for(var d=ni(s,15),p=d.t,f=d.l,h=ni(o,15),g=h.t,m=h.l,y=si(p),b=y.c,w=y.n,v=si(g),I=v.c,T=v.n,_=new Eo(19),E=0;E<b.length;++E)++_[31&b[E]];for(E=0;E<I.length;++E)++_[31&I[E]];for(var S=ni(_,7),x=S.t,A=S.l,k=19;k>4&&!x[ko[k-1]];--k);var C,P,R,U,$=l+5<<3,L=oi(s,jo)+oi(o,Fo)+i,D=oi(s,p)+oi(o,g)+i+14+3*k+oi(_,x)+2*_[16]+3*_[17]+7*_[18];if(c>=0&&$<=L&&$<=D)return ii(t,u,e.subarray(c,c+l));if(ei(t,u,1+(D<L)),u+=2,D<L){C=Bo(p,f,0),P=p,R=Bo(g,m,0),U=g;var N=Bo(x,A,0);for(ei(t,u,w-257),ei(t,u+5,T-1),ei(t,u+10,k-4),u+=14,E=0;E<k;++E)ei(t,u+3*E,x[ko[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];ei(t,u,N[M]),u+=x[M],M>15&&(ei(t,u,j[E]>>5&127),u+=j[E]>>12)}}}else C=Ho,P=jo,R=Wo,U=Fo;for(E=0;E<a;++E){var F=r[E];if(F>255){ti(t,u,C[257+(M=F>>18&31)]),u+=P[M+257],M>7&&(ei(t,u,F>>23&31),u+=xo[M]);var H=31&F;ti(t,u,R[H]),u+=U[H],H>3&&(ti(t,u,F>>5&8191),u+=Ao[H])}else ti(t,u,C[F]),u+=P[F]}return ti(t,u,C[256]),u+P[256]},ci=new So([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),li=new _o(0),ui=function(e,t,n,r,s,o){var i=o.z||e.length,a=new _o(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=ci[t-1],p=d>>13,f=8191&d,h=(1<<n)-1,g=o.p||new Eo(32768),m=o.h||new Eo(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 So(25e3),I=new Eo(288),T=new Eo(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=ai(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,Y=W-g[W]&32767;Y>G&&(G=Y,R=W)}}}O+=(P=R)-(R=g[P])&32767}if(D){v[x++]=268435456|Uo[L]<<18|No[D];var V=31&Uo[L],z=31&No[D];E+=xo[V]+Ao[z],++I[257+V],++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=ai(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 K=S+65535;K>=i&&(c[u/8|0]=l,K=i),u=ii(c,u+1,e.subarray(S,K))}o.i=i}return Jo(a,0,r+qo(u)+s)},di=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}(),pi=function(e,t,n,r,s){if(!s&&(s={l:1},t.dictionary)){var o=t.dictionary.subarray(-32768),i=new _o(o.length+e.length);i.set(o),i.set(e,o.length),e=i,s.w=o.length}return ui(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)},fi=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},hi=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},gi=[],mi=function(){return[_o,Eo,So,xo,Ao,ko,Ro,Do,Go,Yo,Oo,Qo,Bo,Vo,zo,Ko,qo,Jo,Xo,Zo,xi,bi,wi]},yi=function(){return[_o,Eo,So,xo,Ao,ko,Uo,No,Ho,jo,Wo,Fo,Oo,ci,li,Bo,ei,ti,ni,ri,si,oi,ii,ai,qo,Jo,ui,pi,Si,bi]},bi=function(e){return postMessage(e,[e.buffer])},wi=function(e){return e&&{out:e.size&&new _o(e.size),dictionary:e.dictionary}},vi=function(e,t,n,r,s,o){var i=function(e,t,n,r){if(!gi[n]){for(var s="",o={},i=e.length-1,a=0;a<i;++a)s=hi(e[a],s,o);gi[n]={c:hi(e[i],s,o),e:o}}var c=fi({},gi[n].e);return To(gi[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()}},Ii=function(e,t){return e[t]|e[t+1]<<8},Ti=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},_i=function(e,t){return Ti(e,t)+4294967296*Ti(e,t+4)},Ei=function(e,t,n){for(;n;++t)e[t]=n,n>>>=8};function Si(e,t){return pi(e,t||{},0,0)}function xi(e,t){return Zo(e,{i:2},t&&t.out,t&&t.dictionary)}var Ai=function(e,t,n,r){for(var s in e){var o=e[s],i=t+s,a=r;Array.isArray(o)&&(a=fi(r,o[1]),o=o[0]),o instanceof _o?n[i]=[o,a]:(n[i+="/"]=[new _o(0),a],Ai(o,i,n,r))}},ki="undefined"!=typeof TextEncoder&&new TextEncoder,Ci="undefined"!=typeof TextDecoder&&new TextDecoder;try{Ci.decode(li,{stream:!0})}catch(e){}function Pi(e,t){if(ki)return ki.encode(e);for(var n=e.length,r=new _o(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 _o(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 Jo(r,0,s)}var Ri=function(e){var t=0;if(e)for(var n in e){var r=e[n].length;r>65535&&Xo(9),t+=r+4}return t},Ui=function(e,t,n,r,s,o,i,a){var c=r.length,l=n.extra,u=a&&a.length,d=Ri(l);Ei(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)&&Xo(10),Ei(e,t,f<<25|p.getMonth()+1<<21|p.getDate()<<16|p.getHours()<<11|p.getMinutes()<<5|p.getSeconds()>>1),t+=4,-1!=o&&(Ei(e,t,n.crc),Ei(e,t+4,o<0?-o-2:o),Ei(e,t+8,n.size)),Ei(e,t+12,c),Ei(e,t+14,d),t+=16,null!=i&&(Ei(e,t,u),Ei(e,t+6,n.attrs),Ei(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;Ei(e,t,+h),Ei(e,t+2,m),e.set(g,t+4),t+=4+m}return u&&(e.set(a,t),t+=u),t},$i="function"==typeof queueMicrotask?queueMicrotask:"function"==typeof setTimeout?setTimeout:function(e){e()};function Li(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 Di=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 Ni(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 Oi(e){switch(7&Ni(e)){case 0:return Ni(e),!0;case 1:return e.next(8),!0;case 2:const t=Ni(e);return e.next(t),!0;case 5:return e.next(4),!0}return!1}function Bi(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!Li(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!Li(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 Di(e,t);let r=0;for(;;){if(!Oi(n)&&!n.hasError())return!1;if(n.hasError())break;r++}return r>0}(e,o))}var ji=[/^\/$/,/^\*+$/,/^[0-9]+$/],Mi=["/artifact/","https://","http://","*********"],Fi=new Set(["sha1","_sha1","pageref","downloadsPath","tracesDir","pageId"]);function Hi({sensitiveValues:e,str:t}){return e.reduce((e,t)=>e.replaceAll(t,"[REDACTED]"),t)}function Gi({sensitiveValues:e,value:t}){return"string"==typeof t?Hi({sensitiveValues:e,str:t}):Array.isArray(t)?t.map(t=>Gi({sensitiveValues:e,value:t})):function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(t)?Yi({obj:t,sensitiveValues:e}):t}function Wi(e){return!!Fi.has(e)||e.toLowerCase().endsWith("sha1")}function Yi({obj:e,sensitiveValues:t}){return Object.fromEntries(Object.entries(e).map(([e,n])=>[e,Wi(e)?n:Gi({sensitiveValues:t,value:n})]))}function Vi({error:e,sensitiveValues:t}){return e?{...e,message:Hi({sensitiveValues:t,str:e.message})}:void 0}function zi({content:e,sensitiveValues:t}){const n=new F,r=new H,s=Hi({sensitiveValues:t,str:n.decode(e)});return r.encode(s)}var Ki=M(function(e,t,n){n||(n=t,t={}),"function"!=typeof n&&Xo(7);var r=[],s=function(){for(var e=0;e<r.length;++e)r[e]()},o={},i=function(e,t){$i(function(){n(e,t)})};$i(function(){i=n});for(var a=e.length-22;101010256!=Ti(e,a);--a)if(!a||e.length-a>65558)return i(Xo(13,0,1),null),s;var c=Ii(e,a+8);if(c){var l=c,u=Ti(e,a+16),d=4294967295==u||65535==l;if(d){var p=Ti(e,a-12);(d=101075792==Ti(e,p))&&(l=c=Ti(e,p+32),u=Ti(e,p+48))}for(var f=t&&t.filter,h=function(t){var n=function(e,t,n){var r=Ii(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(Ci)return Ci.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:Jo(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&&Xo(8),o}(e.subarray(t+46,t+46+r),!(2048&Ii(e,t+8))),o=t+46+r,i=Ti(e,t+20),a=n&&4294967295==i?function(e,t){for(;1!=Ii(e,t);t+=4+Ii(e,t+2));return[_i(e,t+12),_i(e,t+4),_i(e,t+20)]}(e,o):[i,Ti(e,t+24),Ti(e,t+42)],c=a[0],l=a[1],u=a[2];return[Ii(e,t+10),c,l,s,o+Ii(e,t+30)+Ii(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+Ii(e,t+26)+Ii(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,xi(w,{out:new _o(p)}))}catch(e){b(e,null)}else r.push(function(e,t,n){return n||(n=t,t={}),"function"!=typeof n&&Xo(7),vi(e,t,[mi],function(e){return bi(xi(e.data[0],wi(e.data[1])))},1,n)}(w,{size:p},b))}else b(Xo(14,"unknown compression type "+a,1),null);else b(null,Jo(e,y,y+l));else b(null,null)},g=0;g<l;++g)h()}else i(null,{});return s}),qi=M(function(e,t,n){n||(n=t,t={}),"function"!=typeof n&&Xo(7);var r={};Ai(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){$i(function(){n(e,t)})};$i(function(){p=n});var f=function(){var e=new _o(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;Ui(e,a,s,s.f,s.u,o);var u=30+s.f.length+Ri(s.extra),d=a+u;e.set(s.c,d),Ui(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){Ei(e,t,101010256),Ei(e,t+8,n),Ei(e,t+10,n),Ei(e,t+12,r),Ei(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=di[255&n^t[r]]^n>>>8;e=n},d:function(){return~e}}}(),m=c.length;g.p(c);var y=Pi(t),b=y.length,w=h.comment,v=w&&Pi(w),I=v&&v.length,T=Ri(h.extra),_=0==h.level?0:8,E=function(n,r){if(n)d(),p(n,null);else{var s=r.length;l[e]=fi(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(Xo(11,0,1),null),_)if(m<16e4)try{E(null,Si(c,h))}catch(e){E(e,null)}else u.push(function(e,t,n){return n||(n=t,t={}),"function"!=typeof n&&Xo(7),vi(e,t,[yi],function(e){return bi(Si(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 Ji({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 V(e).with({type:"console"},e=>({...e,args:e.args?.map(e=>({...e,preview:Hi({sensitiveValues:t,str:e.preview}),value:Gi({sensitiveValues:t,value:e.value})})),text:Hi({sensitiveValues:t,str:e.text})})).with({type:"before"},e=>({...e,params:Yi({obj:e.params,sensitiveValues:t}),title:e.title?Hi({sensitiveValues:t,str:e.title}):void 0})).with({type:"after"},e=>({...e,error:Vi({error:e.error,sensitiveValues:t}),result:void 0!==e.result?Gi({sensitiveValues:t,value:e.result}):void 0})).with({type:"action"},e=>({...e,error:Vi({error:e.error,sensitiveValues:t}),params:Yi({obj:e.params,sensitiveValues:t}),result:void 0!==e.result?Gi({sensitiveValues:t,value:e.result}):void 0,title:e.title?Hi({sensitiveValues:t,str:e.title}):void 0})).with({type:"event"},e=>({...e,params:Yi({obj:e.params,sensitiveValues:t})})).with({type:"stdout"},{type:"stderr"},e=>({...e,text:void 0!==e.text?Hi({sensitiveValues:t,str:e.text}):void 0})).with({type:"error"},e=>({...e,message:Hi({sensitiveValues:t,str:e.message})})).with({type:"log"},e=>({...e,message:Hi({sensitiveValues:t,str:e.message})})).with({type:"context-options"},e=>({...e,options:Yi({obj:e.options,sensitiveValues:t}),title:e.title?Hi({sensitiveValues:t,str:e.title}):void 0})).with({type:"frame-snapshot"},e=>({...e,snapshot:Yi({obj:e.snapshot,sensitiveValues:t})})).with({type:"resource-snapshot"},e=>({...e,snapshot:Yi({obj:e.snapshot,sensitiveValues:t})})).with({type:"screencast-frame"},{type:"input"},e=>e).exhaustive()}({event:JSON.parse(e),sensitiveValues:t});return JSON.stringify(n)}catch{return Hi({sensitiveValues:t,str:e})}});return r.encode(s.join("\n"))}({content:e,sensitiveValues:n}):r.endsWith(".html")||r.endsWith(".dat")||r.endsWith(".json")?zi({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!")}(T(e));const n=P(e,"r"),r=Buffer.alloc(515),s=R(n,r,0,515,0);return U(n),Bi(r,s,t)}return Bi(e,void 0!==t?.size?t.size:e.length,t)}(Buffer.from(e),{size:e.length})}(e)?e:zi({content:e,sensitiveValues:t})}({content:e,sensitiveValues:n}):e}function Qi(e=process.cwd()){let t=s(e);for(;;){const e=Xi(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=Zi(t);let n=!1,s=t;for(;;){const e=i(s,"node_modules"),t=i(e,r);if(I(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 Xi(e){const t=i(e,"package.json");let n;try{n=_(t,"utf-8")}catch{return}try{return JSON.parse(n)}catch{return}}function Zi(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(I(i(n,r)))return e;const e=o(n);if(e===n)return;n=e}}function ea(e){if("npm"===e||"pnpm"===e)return["npx","playwright"];if("yarn"===e)return["yarn","playwright"];throw new Error("Package manager not supported")}var ta=[".ts",".js",".mts",".mjs",".cts",".cjs"],na=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),ra=e=>(e instanceof Error?e.message:String(e)).slice(0,400),sa=({outputDir:e,representativeTest:t})=>{const n=["test","--trace=on","--workers=1","--retries=0","--reporter=list","--output",e];return t.filePath&&n.push(t.filePath),t.testTitle?n.push("--grep",na(t.testTitle)):t.testIdentifier&&n.push("--grep",`^${na(t.testIdentifier)}$`),n},oa=async e=>{const t=await oe(e,{withFileTypes:!0}),n=[];for(const s of t){const t=r.join(e,s.name);if(s.isDirectory())n.push(...await oa(t));else if(s.isFile()&&"trace.zip"===s.name){const e=await ie(t);n.push({path:t,mtimeMs:e.mtimeMs})}}return n},ia=async e=>{try{const t=await oe(e,{withFileTypes:!0});for(const n of t){const t=r.join(e,n.name);n.isDirectory()?await ia(t):n.isFile()&&".last-run.json"===n.name&&await ee(t,{force:!0})}}catch{}},aa=async({representativeTest:e,workingDir:t,outputDir:n,requestUploadUrl:s})=>{const o=await(async({representativeTest:e,workingDir:t,outputDir:n})=>{if(!(e=>null!=e.filePath||null!=e.testTitle||null!=e.testIdentifier)(e))return{status:"capture_failed",error:"Representative test info is missing (need filePath, testTitle, or testIdentifier)."};const s=Qi(t);if(!s.installed||!s.inNodeModules||!s.packageManager)return{status:"capture_failed",error:"Playwright is not installed in the current workspace."};const[o,...i]=ea(s.packageManager),a=[...i,...sa({outputDir:n,representativeTest:e})],c=function(e){if(!process.env.CHROME_BIN)return;let t;for(const n of ta){const s=`playwright.config${n}`;if(I(r.join(e,s))){t=s;break}}let n=!1;try{const t=h("npm pkg get type",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});n="module"===JSON.parse(t.trim())}catch{}const s=n?"mts":"ts",o=r.join(e,`.stably-trace-proof-wrapper.config.${s}`),i=`\n// Auto-generated by Stably CLI trace-proof capture.\n// Injects CHROME_BIN as the browser executable path for environments where\n// Playwright's downloaded browsers are unavailable (e.g., Alpine containers).\n${t?`import baseConfig from './${t}';\nconst config = baseConfig;`:"const config = {};"}\n\nexport default {\n ...config,\n use: {\n ...(config as Record<string, unknown>).use as Record<string, unknown> | undefined,\n launchOptions: {\n ...((config as Record<string, unknown>).use as Record<string, unknown> | undefined)?.launchOptions as Record<string, unknown> | undefined,\n executablePath: process.env.CHROME_BIN,\n },\n },\n};\n`.trimStart();return A(r.dirname(o),{recursive:!0}),k(o,i,"utf-8"),{wrapperPath:o,cleanup:()=>{try{C(o,{force:!0})}catch{}}}}(t);c&&a.push("--config",c.wrapperPath);try{await ee(n,{force:!0,recursive:!0}),await te(n,{recursive:!0});const{code:e,output:r,timedOut:s}=await(async({args:e,command:t,cwd:n,env:r,timeoutMs:s})=>await new Promise((o,i)=>{const a=g(t,e,{cwd:n,env:r??process.env,stdio:["ignore","pipe","pipe"],shell:"win32"===process.platform});let c="",l=!1;a.stdout.on("data",e=>{c+=e.toString()}),a.stderr.on("data",e=>{c+=e.toString()});const u=setTimeout(()=>{l=!0,a.kill("SIGTERM")},s);a.on("error",e=>{clearTimeout(u),i(e)}),a.on("close",e=>{clearTimeout(u),o({code:e,output:c,timedOut:l})})}))({args:a,command:o,cwd:t,env:{...process.env,STABLY_INTERNAL_DISABLE_REPORTING:"1"},timeoutMs:3e5});if(s)return{status:"capture_failed",error:"Trace proof run timed out while executing Playwright verification."};const i=(l=r).includes("Executable doesn't exist")&&l.includes("ms-playwright")?'Playwright browsers are not installed. Run "npx playwright install" to install them.':l.includes("browserType.launch")&&l.includes("Executable doesn't exist")?"Browser executable not found. Playwright browsers may not be installed.":l.includes("npx playwright install")?"Playwright browsers need to be installed. The trace cannot verify the fix.":void 0;if(i)return{status:"capture_failed",error:i};const c=await(async e=>{const t=await oa(e);if(0!==t.length)return t.sort((e,t)=>t.mtimeMs-e.mtimeMs),t[0]?.path})(n);if(!c)return{status:"capture_failed",error:`No trace.zip was produced${0!==e?` (test exit code ${e??"unknown"})`:""}: ${r.trim().slice(0,280)}`.trim()};await ia(n);const u=r.replace(/\x1B\[[0-9;]*[a-zA-Z]/g,""),d=4e3;return{status:"captured",tracePath:c,testPassed:0===e,testExitCode:e,testStderr:u.length>d?`...(truncated)\n${u.slice(-d)}`:u}}catch(e){return{status:"capture_failed",error:ra(e)}}finally{c?.cleanup()}var l})({representativeTest:e,workingDir:t,outputDir:n});if("capture_failed"===o.status)return o;const{testPassed:i,testExitCode:a,testStderr:c}=o;try{const{traceBucketPath:e,uploadUrl:t,sensitiveValues:n}=await s(),r=await async function({tracePath:e,sensitiveValues:t}){const n=[],r=x(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||ji.some(t=>t.test(e))||Mi.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 Ki(new Uint8Array(t)),o=Object.entries(s),i=await Promise.all(o.map(async([e,t])=>[e,await Ji({content:t,filename:e,sensitiveValues:r})])),a=Object.fromEntries(i);return qi(a)}({traceBuffer:new Uint8Array(Buffer.concat(n)),sensitiveValues:t})}({tracePath:o.tracePath,sensitiveValues:n});try{await bs({body:r,contentType:"application/zip",uploadUrl:t,errorContext:"trace"})}catch(e){return{status:"upload_failed",error:ra(e),testPassed:i,testExitCode:a,testStderr:c}}return{status:"captured",storage:e,testPassed:i,testExitCode:a,testStderr:c}}catch(e){return{status:"upload_failed",error:ra(e),testPassed:i,testExitCode:a,testStderr:c}}},{zMarkdownAutoHealReport:ca,zRepresentativeTest:la}=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}}(ve),ua=({authHeader:e,diffTracker:t,orgId:n,runId:s,workingDir:o})=>G({name:"auto-heal-report",tools:[W("capture-trace-proof",["Capture and upload a Playwright trace proof for a test case.","","MANDATORY: Call for EVERY testCaseId in your issue, whether fixed or unfixed.","- Fixed: Trace proves the fix works","- Unfixed: Trace shows the failure state for auditability","","The response includes testPassed, testExitCode, and testStderr so you can","check whether the test passed and decide whether to retry.","","Pass testCaseId and call once per test case.","testCaseId is for per-test mapping/storage metadata; representativeTest selects the runnable test."].join("\n"),{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."),representativeTest:la.optional().default({}),testCaseId:ve.string().min(1).optional().describe("Optional test case ID when capturing per-test trace proofs.")},async({issueId:t,proofId:i,representativeTest:a,testCaseId:c})=>{const l=ve.string().min(1).parse(t),u=null==i?void 0:ve.string().min(1).parse(i),d=null==c?void 0:ve.string().min(1).parse(c),p=la.parse(a??{}),f=await(async({authHeader:e,issueId:t,orgId:n,proofId:s,representativeTest:o,runId:i,testCaseId:a,workingDir:c})=>{const l=$n(t),u=(({proofId:e,testCaseId:t})=>Ln(t)??Ln(e))({testCaseId:a,proofId:s}),d=r.join(c,".stably","autoheal-proof",l,u??"issue");return{...await aa({representativeTest:o,workingDir:c,outputDir:d,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:gr(),headers:gs(o),path:{runId:i}},(c.client??rr).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=vs.parse(a.data);return{traceBucketPath:l.traceBucketPath,expiresInSeconds:l.expiresInSeconds,key:l.key,uploadUrl:l.uploadUrl,sensitiveValues:l.sensitiveValues}})({authHeader:e,issueId:t,proofId:s,orgId:n,runId:i,testCaseId:a})}),representativeTest:o}})({authHeader:e,issueId:l,orgId:n,proofId:u,representativeTest:p,runId:s,testCaseId:d,workingDir:o}),h=p.testTitle||p.filePath,g="captured"===f.status&&f.storage?`@[trace:${Buffer.from(JSON.stringify({...f.storage,...h?{label:h}:{}})).toString("base64url")}]`:void 0,m="string"==typeof d?{testCaseId:d,...f,tracePlaceholder:g}:{...f,tracePlaceholder:g};return{content:[{text:JSON.stringify(m),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 capture-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:ca.shape.markdown,summary:ca.shape.summary,issues:ca.shape.issues},async({markdown:r,summary:o,issues:i})=>{const a=await t.computeDiff(),c=ca.parse({format:"markdown",markdown:r,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:gr(),headers:gs(t),path:{runId:r}},(o.client??rr).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:e,orgId:n,report:c,runId:s});const{diffBucketPath:t,uploadUrl:r}=await Is({authHeader:e,contentType:"text/plain",orgId:n,runId:s});await bs({body:a,contentType:"text/plain",uploadUrl:r,errorContext:"diff"}),await Ts({authHeader:e,diffBucketPath:t,orgId:n,runId:s})}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 da({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 pa(e){const t=n.join(e,"package.json");return w.existsSync(t)?{path:t,contents:JSON.parse(w.readFileSync(t,"utf-8"))}:null}var fa=["playwright.config.ts","playwright.config.js","playwright.config.mts","playwright.config.mjs","playwright.config.cjs"];function ha(e){return fa.some(t=>w.existsSync(n.join(e,t)))}function ga(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(...ga(r,t)):t.test(o.name)&&s.push(r)}return s}function ma(e){let t=n.resolve(e);for(;;){if(ha(t))return t;const r=n.dirname(t);if(r===t)return e;t=r}}function ya(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 ba(e){return/\b(test|testing|playwright|e2e|stably)\b/i.test(e)}function wa(e,t){for(const r of va(e,t))if(w.existsSync(n.join(r,"package.json")))return r}function va(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 Ia(e){return e?.replace(/^[~^>=<]+/,"")}function Ta(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 _a=ve.object({commentUrl:ve.string()}),Ea=({prContext:e,authHeader: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: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=Array.isArray(o)?o:[];rs.info("[create-report] Posting report to GitHub PR",{prNumber:e.prNumber,filesCount:i.length});try{const o={summary:"string"==typeof s?s:String(s),filesCreated:i.map(String)},a=await async function({authHeader:e,orgId:t,prNumber:n,owner:r,repo:s,report:o}){const i=new URL("/internal/v1/cli/create-report",ar).toString(),a={Authorization:e,"Content-Type":"application/json"};t&&(a["x-stably-org-id"]=t),rs.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 rs.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=_a.parse(await c.json());return rs.info("Create report posted successfully",{commentUrl:l.commentUrl}),l}({authHeader:t,orgId:n,prNumber:e.prNumber,owner:e.owner,repo:e.repo,report:o});return r?.(a),rs.info("[create-report] Report posted successfully",{commentUrl:a.commentUrl}),{content:[{type:"text",text:`β
Test creation report posted to PR #${e.prNumber}\n\nView the comment: ${a.commentUrl}`}]}}catch(e){const t=e instanceof Error?e.message:String(e);return rs.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}}})]}),Sa=ve.object({traceBucketPath:ys,expiresInSeconds:ve.number(),key:ve.string(),uploadUrl:ve.string(),sensitiveValues:ve.array(ve.string())}),xa=({authHeader:e,sessionId:t,orgId:n,workingDir:s,onTraceProofCaptured:o})=>G({name:"create-trace-proof",tools:[W("capture-create-trace-proof",["Capture and upload a Playwright trace proof for a created test file.","","Call this after verifying that a created test file passes.","The trace proves the test works and is viewable in the Stably web UI.","If the trace run fails, the response includes testPassed, testExitCode,","and testStderr so you can inspect the failure, fix the test, and retry.","","Pass the testFilePath of the created test file.","Optionally pass representativeTest to narrow which test to run (useful for files with multiple tests)."].join("\n"),{testFilePath:ve.string().min(1).describe("Path to the created test file (relative to workspace root)."),representativeTest:la.optional().default({})},async({testFilePath:i,representativeTest:a})=>{const c=ve.string().min(1).parse(i),l=la.parse(a??{}),u={...l,filePath:l.filePath??c},d=$n(c),p=r.join(s,".stably","create-proof",d);rs.info("[create-trace-proof] Capturing trace",{testFilePath:c});const f=await aa({representativeTest:u,workingDir:s,outputDir:p,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:gr(),headers:gs(r),path:{sessionId:t}},(i.client??rr).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=Sa.parse(o.data);return{traceBucketPath:a.traceBucketPath,expiresInSeconds:a.expiresInSeconds,key:a.key,uploadUrl:a.uploadUrl,sensitiveValues:a.sensitiveValues}})({authHeader:e,sessionId:t,testFilePath:c,orgId:n})});"captured"===f.status?(await ee(p,{recursive:!0,force:!0}).catch(()=>{}),rs.info("[create-trace-proof] Upload succeeded",{testFilePath:c,testPassed:f.testPassed,traceBucketPath:f.storage})):rs.error("[create-trace-proof] Failed",{testFilePath:c,error:f.error});const h={testFilePath:c,status:f.status,storage:"captured"===f.status?f.storage:null,testPassed:"capture_failed"!==f.status?f.testPassed:void 0,testExitCode:"capture_failed"!==f.status?f.testExitCode:void 0,testStderr:"capture_failed"!==f.status?f.testStderr:void 0,..."error"in f?{error:f.error}:{}};return o?.(h),{content:[{type:"text",text:JSON.stringify(h)}]}})]}),Aa=["QUEUED","RUNNING","PASSED","FAILED","TIMEDOUT","CANCELLED","INTERRUPTED"],ka=["LOCAL","CI","WEB"],Ca=["MANUAL","SCHEDULED","UI","API","GITHUB_ACTION","SUITE_RUN"],Pa=({authHeader: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\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(Aa).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(ka).optional().describe("Filter by source: LOCAL|CI|WEB"),trigger:ve.enum(Ca).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:r,status:s,limit:o,source:i,trigger:a,suite:c,after:l,before:u})=>{const d="string"==typeof r?r:void 0,p="string"==typeof s?s:void 0,f="number"==typeof o?o:void 0,h="string"==typeof i?i:void 0,g="string"==typeof a?a:void 0,m="string"==typeof c?c:void 0,y="string"==typeof l?l:void 0,b="string"==typeof u?u:void 0;rs.info("[run-history] list_runs called",{branch:d,status:p,limit:f});try{const r=await sr({auth:e,client:gr(),headers:gs(t),query:{projectId:n,branchName:d,status:p,limit:f,source:h,trigger:g,suiteName:m,afterRunId:y,beforeRunId:b}});if(r.error||!r.data){const e=r.response?`API error: ${r.response.status}`:`API error: ${String(r.error)}`;return rs.error("[run-history] list_runs failed",{error:e}),{content:[{type:"text",text:`Error: ${e}`}],isError:!0}}return rs.info("[run-history] list_runs success",{runCount:r.data.runs?.length??0,hasMore:r.data.hasMore}),{content:[{type:"text",text:JSON.stringify(r.data)}]}}catch(e){const t=e instanceof Error?e.message:String(e);return rs.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.\nUse this after list_runs to examine runs where autoHealStatus is "COMPLETED".\n\nThe response includes:\n- Run metadata (status, branch, timestamps)\n- Issues array with result ("fixed"/"unfixed"), rootCause, and relatedTestIdentifiers\n- Test results with their outcomes\n\nUse this to determine which tests were previously fixed and why.',{runId:ve.string().min(1).describe("The run ID to view (required)")},async({runId:n})=>{const r="string"==typeof n?n:String(n);rs.info("[run-history] view_run called",{runId:r});try{const n=await or({auth:e,client:gr(),headers:gs(t),path:{runId:r},query:{detail:"full"}});if(n.error||!n.data){const e=n.response?404===n.response.status?`Run "${r}" not found`:`API error: ${n.response.status}`:`API error: ${String(n.error)}`;return rs.error("[run-history] view_run failed",{error:e,runId:r}),{content:[{type:"text",text:`Error: ${e}`}],isError:!0}}return rs.info("[run-history] view_run success",{runId:r}),{content:[{type:"text",text:JSON.stringify(n.data)}]}}catch(e){const t=e instanceof Error?e.message:String(e);return rs.error("[run-history] view_run exception",{error:t,runId:r}),{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:n})=>{const r=gr();rs.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??rr).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 rs.warn("Subagent definitions fetch failed: unauthorized (401)"),await Rr(),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 rs.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 rs.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 rs.debug("Subagent definitions received",{count:Object.keys(i).length}),i},Na=r.dirname($(import.meta.url)),Oa=r.join(".claude-plugin","plugin.json"),Ba=[r.join("packages","agent-plugin","stably-plugin-cli"),r.join("agent-plugin","stably-plugin-cli")];function ja(e){return I(r.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()}),n=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)}),r=e.object({fix:n.optional()}),s=e.object({setupScript:e.string().optional()});return{zStablyYaml:e.object({schedules:e.record(e.string(),t).optional(),agent:r.optional(),cloud:s.optional()}),zAgentConfig:r,zAgentFixConfig:n,zScheduleEntry:t,zCloudConfig:s}}(ge),Fa=async(e,t)=>{try{const n=await Tr(e,t);if(!n)return void rs.debug(`No ${t} found`);const r=await Z(n,"utf-8");if(!r.trim())return;return r.length>1e4?(rs.warn(`${t} exceeds max length (${r.length} > 10000), truncating`,{path:n}),{content:r.slice(0,1e4),path:n}):(rs.debug(`Loaded ${t} rules`,{path:n,contentLength:r.length}),{content:r,path:n})}catch(e){return void rs.warn(`Failed to read ${t}`,{error:e})}},Ha=/\bstably-browser\b/,Ga=/\bpwtrace\b/,Wa=/\bstably-browser\s+run-test\b/,Ya=/\$\{process\.env\.([a-zA-Z_][a-zA-Z0-9_]*)\}/g,Va=e=>/^[A-Za-z0-9_./:@=-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`,za=".stably-browser";async function Ka(){const e=i(o($(import.meta.url)),"pwtrace.js");if(I(e))return e;try{return Ue.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 qa(e,t){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 capture-trace-proof, 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."}:e.includes("ETIMEDOUT")||e.includes("timed out")||e.includes("killed")?{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."}}function Ja(e,t){return t?`${e}-${t}`:e}function Qa(e){if(e&&"object"==typeof e&&"agent_id"in e){const t=e.agent_id;return"string"==typeof t?t:void 0}}var Xa=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"})}),Za=/\bmcp__playwright-mcp__[a-z0-9_]+\b/gi,ec=/\.playwright-mcp(?:\/[^\s"'`)\]]*)?/gi,tc=/\bplaywright[\s_-]?mcp\b/gi;function nc(e){return e.replace(Za,"browser_tool").replace(ec,"verification-artifact").replace(tc,"browser automation")}function rc(e){return{...e,steps:e.steps.map(e=>nc(e)),reason:e.reason?nc(e.reason):null,evidence:e.evidence.map(e=>nc(e))}}function sc(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=Xa.parse(t)}catch{}return n}function oc({mode:e,lastAssistantText:t,maxLength:n=1e4}){const r="verify"===e&&t?nc(t):t;return r?r.slice(0,n):null}var ic=e=>`[38;5;208m${e}[39m`,ac=["Bash","Read","Write","Edit","Glob","Grep","Task","Skill"],cc=["Task","Skill"],lc=["Bash","Read","Write","Edit","Glob","Grep","mcp__session-control"],uc=e=>{if("EPIPE"!==e.code)throw e},dc="__main__",pc=[3e3,5173,4173,8080,4200,8e3],fc=/\b(TEST_EMAIL|TEST_PASSWORD|auth|authentication|credentials|login|log in|sign in)\b/i,hc=/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/i,gc=/playwright[\s_-]?mcp/i,mc=e=>"mcp__auto-heal-report__generate-report"===e;async function yc(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 bc(e){return new Promise(t=>{const n=new z.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 wc=async(e,t,n)=>{const r=n?"[Y/n]":"[y/N]",s=(await e.question(`${q.cyan("?")} ${t} ${q.gray(r)} `)).trim().toLowerCase();return s?"y"===s||"yes"===s:n},vc=async e=>{if("single"===e.mode){const t=Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt;rs.initSession(t||"create-from-diff")}else if("verify"===e.mode){const t=Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt;rs.initSession(t||"verify")}else"fix"===e.mode&&rs.initSession(`fix-${e.runId}`);rs.info("Agent session starting",{mode:e.mode}),process.stdout.on("error",uc),process.stderr.on("error",uc);const a=e=>{if("EPIPE"!==e.code)throw e};process.on("uncaughtException",a),rs.debug("Checking authentication");const c=await ds({autoLogin:"chat"===e.mode||"init"===e.mode}),l=fs(c);rs.debug("Authentication resolved",{authType:c.type});const u="oauth"===c.type?c.auth.context.orgId:void 0,d=r.resolve(process.cwd()),p="fix"!==e.mode,f=r.join(d,".env"),h=p&&v.existsSync(f)&&v.statSync(f).isFile(),g=h?t(v.readFileSync(f,"utf8")):{};rs.debug("Environment file",{path:f,exists:h,variableCount:Object.keys(g).length});const y="chat"!==e.mode&&"init"!==e.mode,b="chat"===e.mode,T="chat"===e.mode||"init"===e.mode,S="single"===e.mode,x="verify"===e.mode,A=S||x;let k,C=new qs;"init"===e.mode&&(k=e.initPreferences??await async function(){if(!process.stdin.isTTY||!process.stdout.isTTY)return{googleAuth:!0,emailPackage:!1};const e=K({input:process.stdin,output:process.stdout});try{return{googleAuth:await wc(e,"Include Google Auth test helper guidance? (recommended)",!0),emailPackage:await wc(e,"Install @stablyai/email for inbox testing?",!1)}}finally{e.close()}}());const P="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,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&&U&&rs.info("[verify] Using URL extracted from prompt",{url:U}),"verify"!==e.mode||U||(U=await async function(){for(const e of pc)if(await bc(e))return`http://localhost:${e}`}(),U?rs.info("[verify] Detected local application URL",{url:U}):rs.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&&fc.test(e))(r))({envEmail:process.env.TEST_EMAIL??t.TEST_EMAIL,envPassword:process.env.TEST_PASSWORD??t.TEST_PASSWORD,promptIncludesEmail:hc.test(s),stablyMdContent:c}),p=!a;if(!u&&!d&&!p)return{resolvedUrl:l};const f=K({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 wc(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 wc(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:f,envFromFile:g,initialUrl:U,verifyPromptText:R,workingDir:d});U=e.resolvedUrl?.trim()||U}"verify"!==e.mode||U||rs.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 L={log:[],promptDisplay:V(e).with({mode:"chat"},()=>"Ask Stably to build tests for you").with({mode:"init"},()=>"Setting up Playwright and Stably SDK").with({mode:"fix"},()=>"Fixing broken tests").with({mode:"single"},e=>{const t=(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt)?.trim();return t||"Creating tests from PR/branch changes"}).with({mode:"verify"},e=>{const t=(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt)?.trim();return t||"Verifying application"}).exhaustive(),status:"running"};let D,N,O,B,j=y,M=!1,F=0,H=[],z=!1,J=!1,X=0;const ee=new Map,te=[],ne=e=>{te.push(e)},re=new Map;let se=null,oe=!1,ie=!1;const ae=Date.now();let ce,le="fix"===e.mode?{suiteId:e.runId,phase:"initializing",totalTests:null,fixedTests:0,failedTests:0,currentTestDescription:null,lastTestDescription:null,startedAt:ae,endedAt:null,isError:!1,updatedAt:ae,recentActivity:[],workers:[{id:dc,testDescription:"Orchestrator",workerType:"main",status:"running",summary:null,startedAt:ae,endedAt:null,activity:[]}]}:null;const ue=new Set,de=(e,t)=>{if(!le)return;const n=le.workers.map(n=>{if(n.id!==e)return n;const r=[...n.activity,{...t,timestamp:Date.now()}].slice(-15);return{...n,activity:r}});he({workers:n})},pe=e=>{if(!le)return;const t=[...le.recentActivity,{...e,timestamp:Date.now()}].slice(-10);he({recentActivity:t})},fe=e=>(le?.workers??[]).map(t=>t.id===dc?{...t,status:e?"failed":"succeeded",endedAt:t.endedAt??Date.now()}:"running"===t.status?{...t,status:"failed",endedAt:Date.now()}:t),he=e=>{le&&!ce?.isClosed&&(le={...le,...e,updatedAt:Date.now()},ce?.sendProgress(le))},ge=async t=>{if("fix"===e.mode){if("STARTED"===t){if(oe)return;oe=!0}else{if(ie)return;ie=!0}try{await(async({authHeader:e,orgId:t,runId:n,status:r})=>{const s=await(o={auth:e,body:{status:r},client:gr(),headers:gs(t),path:{runId:n}},(o.client??rr).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:l,orgId:u,runId:e.runId,status:t})}catch{}}},me=Date.now();let ye,be=null;const we=e=>{be&&!ye?.isClosed&&(be={...be,...e,updatedAt:Date.now()},ye?.sendProgress(be))},Ie=e=>{if(!be)return;const t=[...be.recentActivity,{...e,timestamp:Date.now()}].slice(-10);we({recentActivity:t})};let Ce;const Re=(e.mode,!0);rs.info("[session] Checking session creation",{mode:e.mode,shouldCreateSession:Re});try{rs.info("[session] Creating progress session",{mode:e.mode,projectId:ps(c)});const t=await async function({agentMode:e,authHeader:t,orgId:n,projectId:r,runId:s,fetchImpl:o=fetch,apiUrl:i=ar}){const a=no[e],c=new URL("/internal/v1/cli/progress",i).toString(),l={Authorization:t,"Content-Type":"application/json"};n&&(l["x-stably-org-id"]=n);const u=await o(c,{method:"POST",headers:l,body:JSON.stringify({mode:a,projectId:r,agentId:Q.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}}({agentMode:e.mode,authHeader:l,orgId:u,projectId:ps(c),..."fix"===e.mode?{runId:e.runId}:{}}),{sessionId:n,sessionMode:r}=t;if(Ce=n,A){const t="single"===e.mode||"verify"===e.mode?Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt:null,r=Js(d);be={sessionId:n,phase:"initializing",startedAt:me,endedAt:null,isError:!1,updatedAt:me,currentActivity:null,filesCreated:[],traceProofs:[],recentActivity:[],prompt:t||null,environment:{gitBranch:r?.branch??null,workingDirectory:d,nodeVersion:process.version,cliVersion:ir}},ye=new Es({authHeader:l,orgId:u,sessionId:n,onUserMessage:e=>{C&&(rs.info("[ws] Injecting web UI message into agent",{contentLength:e.length}),Ie({type:"user_message",summary:e}),Ye({text:`[Web] ${e}`}),C.pushText(`[Message from web UI user]: ${e}`),j||(j=!0,rt({status:"running"})))}}),ye.start(),we({phase:"initializing"})}rs.info(`[${r}] Progress session created`,{sessionId:n})}catch(e){const t=e instanceof Error?e.message:String(e);rs.warn(`[progress] Session creation failed (non-fatal): ${t}`)}const $e={current:e=>{}},Le={current:async()=>{}};let De;const Ne={current:()=>{}};let Oe=!1,Be=!1;const{addSubagentActivity:je,addSubagentStart:Me,addTool:Fe,appendCancelled:He,appendText:Ge,appendThinking:We,appendUserMessage:Ye,cancelThinkingRender:Ve,cleanup:ze,dismissPermissionPrompt:Ke,flushThinkingRender:qe,resetThinkingLogIndex:Je,setExiting:Qe,setRunningLabel:Xe,setStatus:Ze,setSubagentStatus:et,updateFixProgress:tt}=await(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=()=>Ae(s,{inverse:!0,children:" "}),d=(({Box:e,Text:t,useInput:n},r,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"}];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=vo(i.toolName),g=bo(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(r,{})]})]}:{flexDirection:"column",marginTop:1,children:[Ae(t,{color:"gray",children:"Use ββ arrows or number keys to select:"}),f.map((e,n)=>Ae(t,{children:ke(t,{color:n===a?"cyan":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?ke(r,{color:"gray",dimColor:!0,children:["β’ ",e.content]},e.id):"tool_result"===e.kind||"text"===e.kind?Ae(r,{color:"gray",children:e.content},e.id):null,u=({progress:e})=>{const[n,s]=Te(Date.now());Ee(()=>{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`,{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(r,{children:[Ae(r,{color:p,bold:!0,children:d}),Ae(r,{color:"gray",children:h}),ke(r,{color:"gray",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?"#FFA500":"green",l=e.isError?"Fix stopped":"Fix complete";return ke(t,{flexDirection:"column",children:[ke(r,{color:c,bold:!0,children:[l," in ",a]}),null!==e.totalTests&&ke(r,{color:"gray",children:[e.fixedTests,"/",e.totalTests," tests fixed",e.failedTests>0?`, ${e.failedTests} failed`:""]})]})},p=(e,n=!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(r,{children:[Ae(r,{color:o,bold:!0,children:"Agent"}),s.description?ke(r,{color:"gray",children:[" (",s.description,")"]}):null]}),s.activities.length>0&&Ae(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<=y&&t.unshift(r))}return t.map(e=>l(e))})()})]},e.id)}if("tool"===e.kind)return ke(r,{color:"gray",dimColor:!0,children:["β’ ",e.content]},e.id);if("tool_result"===e.kind)return Ae(r,{color:"gray",children:e.content},e.id);if("user"===e.kind)return ke(r,{color:"cyan",children:["You: ",e.content]},e.id);if("thinking"===e.kind){const n=e.content.split("\n"),s=10,o=n.length>s?n.slice(-s):n;return Ae(t,{flexDirection:"column",children:Ae(r,{color:"gray",dimColor:!0,children:o.join("\n")})},e.id)}return"cancelled"===e.kind?Ae(r,{color:"gray",dimColor:!0,children:e.content},e.id):Ae(r,{children:e.content},e.id)},f=(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},h=(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},g=(e,t)=>{if(t<=0)return 0;const n=e.lastIndexOf("\n",t-1);return-1===n?0:n+1},m=(e,t)=>{const n=e.indexOf("\n",t);return-1===n?e.length:n},y=3;return function({onCancel:c,onExit:l,onPermissionChoice:b,onSend:w,showSpinnerImmediately:v,state:I}){const[T,_]=Te({value:"",cursor:0}),E=T.value,S=T.cursor,x=_e(!1),A=_e(void 0),[k,C]=Te(!1),[P,R]=Te(!1),U=_e(0),$=_e(!1),L=!!I.permissionPrompt,D=(({termProgram:e})=>"vscode"===e)({termProgram:process.env.TERM_PROGRAM}),N=I.log.at(-1),O=("text"===N?.kind||"thinking"===N?.kind)&&"running"===I.status,B=I.log.findIndex(e=>"subagent"===e.kind&&"running"===e.subagent?.status),j=-1!==B,M=I.activeThinkingLogIndex??-1,F=M>=0&&M<I.log.length-1,H=o&&!P,G=D?0:j?B:F?M:O?I.log.length-1:I.log.length,W=H&&"running"===I.status?Math.min(G,U.current):G;Ee(()=>{I.log.length<U.current&&(U.current=0),W>U.current&&(U.current=W)},[I.log.length,W]);const Y=I.log.slice(0,U.current),V=I.log.slice(U.current),z=H?Y.filter(e=>"tool"!==e.kind&&"tool_result"!==e.kind&&"thinking"!==e.kind):Y,K=(()=>{if(!H)return V;let e=0;const t=[];for(let n=V.length-1;n>=0;n--){const r=V[n];"tool"===r.kind||"tool_result"===r.kind||"thinking"===r.kind?("tool"===r.kind&&e++,e<=y&&t.unshift(r)):t.unshift(r)}return t})(),q=Se(async()=>{x.current?(A.current&&clearTimeout(A.current),await(l?.()),process.exit(0)):(x.current=!0,C(!0),A.current=setTimeout(()=>{x.current=!1,C(!1)},2e3))},[l]);s((e,t)=>{t.ctrl&&"c"===e&&q().catch(()=>process.exit(1)),t.ctrl&&"o"===e&&R(e=>!e),t.escape&&"running"===I.status&&!L&&0===E.length&&c?.()},{isActive:o}),Ee(()=>{if(L||!w)return;process.stdout.isTTY&&process.stdout.write("[?2004h");const e=e=>{const t=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n");t&&_(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~")){$.current=!0;const t=n.slice(n.indexOf("[200~")+6),r=t.includes("[201~"),s=r?t.slice(0,t.indexOf("[201~")):t;return r&&($.current=!1),void e(s)}if(n.includes("[201~")){const t=n.slice(0,n.indexOf("[201~"));return e(t),void($.current=!1)}$.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||_(e=>({...e,cursor:m(e.value,e.cursor)})):_(e=>({...e,cursor:g(e.value,e.cursor)})):_(e=>({...e,cursor:e.value.length})):_(e=>({...e,cursor:0}))};return process.stdin.on("data",t),()=>{process.stdin.off("data",t),process.stdout.isTTY&&process.stdout.write("[?2004l")}},[L,w]),s((e,t)=>{if(!t.ctrl||"c"!==e){if(t.return){if($.current)return;const e=E.trim();return e&&w?.(e),void _({value:"",cursor:0})}t.ctrl&&"w"===e||t.ctrl&&t.backspace?_(e=>{const t=f(e.value,e.cursor);return{value:e.value.slice(0,t)+e.value.slice(e.cursor),cursor:t}}):!t.backspace&&!t.delete||t.ctrl?t.ctrl&&t.leftArrow||t.meta&&"b"===e?_(e=>({...e,cursor:f(e.value,e.cursor)})):t.ctrl&&t.rightArrow||t.meta&&"f"===e?_(e=>({...e,cursor:h(e.value,e.cursor)})):t.leftArrow?_(e=>({...e,cursor:Math.max(0,e.cursor-1)})):t.rightArrow?_(e=>({...e,cursor:Math.min(e.value.length,e.cursor+1)})):t.ctrl&&"a"===e?_(e=>({...e,cursor:0})):t.ctrl&&"e"===e?_(e=>({...e,cursor:e.value.length})):t.escape&&E.length>0?_({value:"",cursor:0}):!e||t.ctrl||t.meta||t.escape||e.includes("")||/^\[./.test(e)||/^O[A-D]$/.test(e)||_(t=>({value:t.value.slice(0,t.cursor)+e+t.value.slice(t.cursor),cursor:t.cursor+e.length})):_(e=>e.cursor>0?{value:e.value.slice(0,e.cursor-1)+e.value.slice(e.cursor),cursor:e.cursor-1}:e)}},{isActive:o&&!!w&&!L});const J=xe(()=>"running"===I.status?Ae(a,{label:I.runningLabel??"Working"}):"success"!==I.status?Ae(r,{color:"red",children:"β Failed"}):void 0,[I.runningLabel,I.status]),Q=!(v||!w||"running"!==I.status||0!==I.log.length||I.resultText||I.errorText),X="running"===I.status&&!Q||I.log.length>0||I.resultText||I.errorText||"running"!==I.status;return ke(t,{flexDirection:"column",children:[D?ke(t,{flexDirection:"column",flexShrink:0,children:[Ae(r,{color:"cyan",bold:!0,children:"Stably Agent"}),Ae(t,{flexDirection:"column",marginTop:1,children:Ae(r,{color:"gray",children:I.promptDisplay})})]}):Ae(n,{items:["header"],children:()=>ke(t,{flexDirection:"column",flexShrink:0,children:[Ae(r,{color:"cyan",bold:!0,children:"Stably Agent"}),Ae(t,{flexDirection:"column",marginTop:1,children:Ae(r,{color:"gray",children:I.promptDisplay})})]},"header")}),z.length>0&&Ae(n,{items:z,children:e=>p(e,H)}),K.length>0&&Ae(t,{flexDirection:"column",children:K.map(e=>p(e,H))}),H&&V.length>K.length&&ke(r,{color:"gray",dimColor:!0,children:["β ",V.length-K.length," tool calls hidden (Ctrl+O to expand)"]}),P&&o&&"running"===I.status&&Ae(r,{color:"gray",dimColor:!0,children:"β Showing all tool calls (Ctrl+O to collapse)"}),"error"===I.status&&I.errorText&&Ae(t,{marginTop:1,children:Ae(r,{color:"red",children:I.errorText})}),"success"===I.status&&I.resultText&&Ae(t,{marginTop:1,children:Ae(r,{children:I.resultText})}),X&&Ae(t,{flexDirection:"column",flexShrink:0,marginTop:1,children:"running"===I.status&&I.fixProgress?ke(t,{flexDirection:"column",children:[ke(t,{children:[Ae(a,{}),Ae(r,{children:" "}),Ae(u,{progress:I.fixProgress})]}),("fixing"===I.fixProgress.phase||"debugging"===I.fixProgress.phase)&&I.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 ke(t,{flexDirection:"column",children:[ke(r,{children:[" ",Ae(a,{}),ke(r,{color:"gray",children:[n.description||n.subagentType||"worker",o>0?` (${o} ${1===o?"cycle":"cycles"})`:""]})]}),c&&ke(r,{color:"gray",dimColor:!0,children:[" β’ ",c.content]}),l&&ke(r,{color:"gray",dimColor:!0,children:[" ",l]})]},e.id)})]}):"success"!==I.status&&"error"!==I.status||!I.fixProgress?J:Ae(d,{progress:I.fixProgress})}),null!=I.permissionPrompt&&null!=b&&Ae(i,{onChoice:b,prompt:I.permissionPrompt}),null!=w&&null==I.permissionPrompt&&!I.isExiting&&ke(t,{borderColor:"gray",borderStyle:"round",flexDirection:"column",flexShrink:0,marginTop:1,paddingX:1,paddingY:0,children:[Ae(r,{color:"gray",children:"Type a message and press Enter. Press Escape to interrupt. Press Ctrl+C to exit."}),ke(r,{children:[Ae(r,{color:"#FFA500",children:">"})," ",E.slice(0,S),Ae(e,{}),E.slice(S)]})]}),k&&ke(t,{marginTop:1,flexDirection:"column",children:[Ae(r,{color:"#FFA500",children:"Press Ctrl+C again to exit"}),Yr&&ke(r,{color:"gray",children:["Debug log: ",qr]})]})]})}})({Cursor:u,inkComponents:{Box:n,Static:r,Text:s,useInput:i},isRawModeSupported:a,PermissionPrompt:d,Spinner:({label:e})=>{const[t,n]=Te(0);return Ee(()=>{if(!c)return;const e=setInterval(()=>n(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: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=wo(e,t),r=n??vo(e),s=n?void 0:bo(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}})(L,"init"===e.mode?{onCancel:()=>Ne.current(),onExit:()=>Le.current(),onSend:e=>$e.current(e),showSpinnerImmediately:!0}:"chat"===e.mode?{onCancel:()=>Ne.current(),onExit:()=>Le.current(),onSend:e=>$e.current(e)}:"fix"===e.mode?{onExit:()=>Le.current(),isFixMode:!0}:{onExit:()=>Le.current()});let nt=L.status;const rt=({error:e,result:t,status:n})=>{nt=n,Ze({error:e,result:t,status:n})};let st;x&&(Ge({text:"Starting verification...\n"}),Ge(U?{text:`Target URL: ${U}\n`}:{text:"Target URL: auto-detect (agent may infer from project config)\n"}),Xe({label:"Calibrating verification flow..."})),$e.current=e=>{const t=e.trim();if(b&&!rs.getLogFilePath()&&rs.initSession(t||"chat"),rs.debug("User message",{text:t}),"/help"===t){j&&C&&(M=!0,D?.interrupt?.(),C.allowNextTurn(),j=!1),"running"===nt&&rt({status:"success"}),Ye({text:e});const t=P?.();return void Ge({text:t??"Help is not available in this session."})}if(b&&Xe({label:void 0}),C){if(j)return rt({status:"running"}),Ye({text:e}),C.pushText(e),void(F+=1);rt({status:"running"}),Ye({text:e}),ne({role:"user",content:e,timestamp:(new Date).toISOString()}),C.pushText(e),j=!0}};let ot="",it="";const at=[],ct=[],lt=[];let ut;const dt=await(async e=>{try{const t=await Tr(e,"stably.yaml");if(!t)return void rs.debug("No stably.yaml found");const n=await Z(t,"utf-8");if(!n.trim())return;const r=Pe(n),s=Ma.parse(r.toJS()),o=s.agent?.fix?.maxTurnsPerIssue,i=s.agent?.fix?.maxParallelWorkers,a=!!s.agent?.fix?.rules;return rs.debug(`Loaded stably.yaml: maxTurnsPerIssue=${o??"default"}, maxParallelWorkers=${i??"default"}, hasRules=${a}`,{path:t,config:s.agent}),s}catch(e){return void rs.warn("Failed to parse stably.yaml",{error:e})}})(d),pt=dt?.agent?.fix?.skipAfterConsecutiveUnfixed,ft=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 co(e,"output-flag"),{path:e,source:"output-flag"}}const r=oo(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(ao(t))return co(t,"playwright.config.ts"),{path:t,source:"playwright.config.ts"}}}for(const e of io){const t=i(n,e);if(ao(t))return co(t,"auto-detected"),{path:t,source:"auto-detected"}}return co(n,"cwd-fallback"),{path:n,source:"cwd-fallback"}}(d,e.outputDir);return ut=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: ${ut}]`}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,U);if("fix"===e.mode)try{rs.info("[fix] Fetching autoheal context",{runId:e.runId,skipAfterConsecutiveUnfixed:pt});const t=Date.now(),{context:n,autohealReportUrl:r,skippedTests:s,newerPassingSuiteId:o}=await(async({authHeader:e,orgId:t,runId:n,skipAfterConsecutiveUnfixed:r})=>{rs.debug("Fetching autoheal context",{runId:n,skipAfterConsecutiveUnfixed:r});const s=await(o={auth:e,client:gr(),headers:gs(t),path:{runId:n},query:null!=r?{skipAfterConsecutiveUnfixed:r}:{}},(o.client??rr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-context",...o}));var o;if(404===s.response.status)throw rs.warn("Autoheal context not found",{runId:n,status:404}),new Error(`Run ID "${n}" was not found.`);if(401===s.response.status)throw rs.warn("Autoheal context fetch unauthorized",{runId:n,status:401}),new Error("Unauthorized: failed to fetch autoheal context (401).");if(422===s.response.status)throw rs.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=ms.safeParse(s.data);if(e.success)return rs.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};throw rs.warn("Autoheal context response invalid",{runId:n}),new Error("Autoheal context response missing or invalid context.")}throw rs.warn("Autoheal context fetch failed",{runId:n,error:s.error}),new Error("Failed to fetch autoheal context")})({authHeader:l,orgId:u,runId:e.runId,skipAfterConsecutiveUnfixed:pt});if(rs.info("[fix] Autoheal context fetched",{runId:e.runId,durationMs:Date.now()-t,contextLength:n.length,skippedTestCount:s.length}),st=r,s.length>0){rs.info(`[fix] Skipping ${s.length} test(s) that failed to be fixed ${pt}+ consecutive times`);for(const e of s)rs.info(`[fix] Skipped: ${e.testIdentifier} β ${e.testTitle} (unfixed ${e.consecutiveUnfixedCount}x)`)}return o&&(rs.info("[fix] Tests already passing in a newer run",{newerPassingSuiteId:o}),rt({status:"success",result:`Tests already passing in a newer run (${o}). Nothing to fix.`}),await ze(),process.exit(0)),n.includes("No failing tests to fix (all were skipped).")&&(rs.info("[fix] All failing tests were skipped β nothing to fix"),rt({status:"success",result:`All failing tests skipped (unfixed ${pt}+ consecutive times). Nothing to fix.`}),await ze(),process.exit(0)),ce||(rs.info("[fix] Creating WebSocket progress reporter"),ce=new _s({authHeader:l,orgId:u,runId:e.runId,onUserMessage:e=>{if(rs.info("[ws] Injecting web UI message into fix agent",{contentLength:e.length}),de(dc,{type:"user_message",summary:e}),pe({type:"user_message",summary:e}),Ye({text:`[Web] ${e}`}),!j)return C.pushText(`[Message from web UI user]: ${e}`),j=!0,void C.allowNextTurn();z||Date.now()-X<2e3?C.pushText(`[Message from web UI user]: ${e}`):(H.push(e),O&&clearTimeout(O),O=setTimeout(()=>{O=void 0;const e=[...H];H=[],X=Date.now(),pn(e)},500))}}),ce.start(),he({phase:"initializing"})),ge("STARTED"),n}catch(e){const t=e instanceof Error?e.message:"Failed to fetch autoheal context.";rs.error("[fix] Failed to fetch autoheal context",{error:t}),rt({error:t,status:"error"}),await ze(),process.exit(1)}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""})(),ht=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(I(t))for(const e of Qs){const n=r.join(t,`playwright.config${e}`);if(I(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([eo({defaultContent:"Unable to read directory",dirName:"working directory",dirPath:t}),eo({defaultContent:"Unable to read directory",dirName:"tests directory",dirPath:n}),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),gt="fix"===e.mode?dt?.agent?.fix?.maxTurnsPerIssue:void 0,mt=dt?.agent?.fix?.maxParallelWorkers??3,yt="fix"===e.mode?dt?.agent?.fix?.rules:void 0,bt=dt?.agent?.fix?.maxBudgetUsd??50,wt="verify"===e.mode?e.maxBudgetUsd??5:void 0,vt="fix"===e.mode?bt:x?wt:void 0,It="init"!==e.mode,Tt="single"===e.mode?await(async e=>{const t=await Fa(e,"STABLY-CREATE.md");return t?.content})(d):void 0,_t=await(e=>Fa(e,"STABLY.md"))(d),Et=_t?.content;x&&(Xe({label:"Assembling verification context..."}),Ge({text:"Assembling workspace context...\n"})),rs.info("[fix] Fetching system prompt and subagent definitions",{mode:e.mode,maxTurnsOverride:gt,maxBudgetUsd:vt,hasCustomRules:!!yt,hasCreateRules:!!Tt,hasStablyMd:!!Et,stablyMdPath:_t?.path}),_t&&rs.info(`STABLY.md loaded (${_t.content.length} chars)`,{path:_t.path});const St=await hs(),xt=St?Object.keys(St.variables):[],At=[...new Set([...Object.keys(g),...xt])],kt=Date.now(),[{systemPrompt:Ct,prContext:Pt},Rt]=await Promise.all([to({allowedEnvVars:At,mode:e.mode,workspaceInfo:ht,authHeader:l,customHeader:"single"===e.mode?e.customHeader:void 0,maxParallelWorkers:mt}),It?Da({authHeader:l,mode:e.mode,maxTurnsOverride:gt}):Promise.resolve({})]);rs.info("[fix] System prompt and subagents fetched",{durationMs:Date.now()-kt,systemPromptSize:Ct.length,subagentCount:Object.keys(Rt).length,maxTurnsOverride:gt??"default",hasPrContext:!!Pt});const Ut=function(e){const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(La.has(n)||$a.some(e=>n.startsWith(e))||(t[n]=r));return t}({...g,...process.env}),$t=!0;rs.debug("AI proxy configuration",{useStablyAiProxy:$t,wantsBypassProxy:!1,wantsUseOllama:!1}),rs.info("[fix] Acquiring AI proxy key",{useStablyAiProxy:$t});const Lt=Date.now(),Dt=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??rr).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:l,client:gr(),source:"cli"}),Nt=Dt?.key;if(rs.info("[fix] AI proxy key acquired",{durationMs:Date.now()-Lt,success:!!Nt,hasError:!!Dt?.error}),!Nt){const e=Dt?.error?.message?`Unable to make AI calls: ${Dt.error.message}`:"Unable to make AI calls. Check if you are authenticated.";rs.warn("Failed to get proxy API key",{error:Dt?.error?.message}),rt({error:e,status:"error"}),await ze(),rs.flush(),rs.printLogFileInfo(),process.exit(1)}rs.debug("Proxy API key acquired",{success:!!Nt});const Ot="init"===e.mode,Bt="fix"===e.mode,jt=Ot?void 0:function(e){let t,n;!function(e){const t=i(e,".gitignore");try{if(I(t)){const e=_(t,"utf-8"),n=e.split("\n").map(e=>e.trim());if(n.includes(za)||n.includes(`/${za}`))return;const r=e.length>0&&!e.endsWith("\n");E(t,`${r?"\n":""}${za}\n`)}}catch{}}(process.cwd());const r=new Set;let s;const a=()=>{var t;return s||(s="auto"!==(t=e.sessionName)?t:`stably-${process.pid}`),s};return{hook:async s=>{const c=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(c)&&!Ga.test(c))return{decision:"approve"};if(Ga.test(c)&&!Ha.test(c)){if(!n)try{n=await Ka(),rs.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:c.replace(/\b(?:npx\s+)?pwtrace\b/g,e)}}}}if(Ga.test(c)&&!n)try{n=await Ka(),rs.info("[pwtrace-hook] Resolved binary (mixed command)",{path:n})}catch{}const l=/\bstably-browser\s+close\b/.test(c),u=/\bstably-browser\s+(?!close\b)\w/.test(c);if(l){if(!u&&0===r.size)return{decision:"approve"};const e=Qa(s),t=Ja(a(),e);r.delete(t)}if(!t)try{t=await async function(){const e=i(o($(import.meta.url)),"stably-browser.js");if(I(e))return e;try{return Ue.resolve("@stablyai-internal/playwright-cli/playwright-cli.js")}catch{}return new Promise((e,t)=>{m("which",["stably-browser"],(n,r)=>{!n&&r.trim()?e(r.trim()):t(new Error("stably-browser not found. Ensure @stablyai-internal/playwright-cli is installed or stably-browser is on PATH."))})})}(),rs.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:`stably-browser binary not found: ${t}`}}const d=Qa(s),p=Ja(a(),d),f=/\bstably-browser\s+open\b/.test(c);if((!l||u)&&!r.has(p))if(f)r.add(p);else{r.add(p),rs.info("[stably-browser-hook] First browser command, starting daemon...",{sessionName:p,agentId:d});const n=await async function(e,t,n){const r=["open",`-s=${t}`];n&&r.push("--headed"),r.push("--browser=chromium"),rs.info("[stably-browser-hook] Starting daemon",{bin:e,args:r});const s=process.env.CHROME_BIN?{...process.env,PLAYWRIGHT_MCP_EXECUTABLE_PATH:process.env.CHROME_BIN}:void 0;return new Promise(t=>{m(process.execPath,[e,...r],{timeout:3e4,env:s},(e,n,r)=>{if(e)return rs.error("[stably-browser-hook] Failed to start daemon",{error:e.message,stderr:r}),void t({ok:!1,...qa(e.message,r??"")});rs.info("[stably-browser-hook] Daemon started",{stdout:n.trim()}),t({ok:!0})})})}(t,p,e.headed);if(!n.ok)return r.delete(p),{decision:"block",reason:`Failed to start stably-browser daemon: ${n.reason}`,systemMessage:n.guidance}}const h=`${process.execPath} ${t}`;let g=c.replace(/\b(?:npx\s+)?stably-browser\b/g,h);if(Ga.test(g)&&n){const e=`${process.execPath} ${n}`;g=g.replace(/\b(?:npx\s+)?pwtrace\b/g,e)}const y=[];g.includes("-s=")||g.includes("--session=")||y.push(`-s=${p}`),e.headed&&!g.includes("--headed")&&y.push("--headed"),y.length>0&&(g=g.replaceAll(h,`${h} ${y.join(" ")}`)),e.envVars&&(g=g.replace(Ya,(t,n)=>{const r=e.envVars[n];return null!=r?r:t}));const b=[];if(Wa.test(c)&&e.envVars)for(const[t,n]of Object.entries(e.envVars))b.push(`${t}=${Va(n)}`);return b.length>0&&(g=`${b.join(" ")} ${g}`),rs.debug("[stably-browser-hook] Rewritten command",{original:c.slice(0,100),sessionName:p,agentId:d,envVarCount:b.length}),{decision:"approve",hookSpecificOutput:{hookEventName:"PreToolUse",updatedInput:{command:g}}}},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&&rs.debug("[stably-browser-hook] Failed to stop daemon",{error:t.message,sessionName:r}),e()})});var n,r})),r.clear())}}}({sessionName:process.env.STABLY_PLAYWRIGHT_SESSION??(Bt?"auto":"default"),headed:!("chat"!==e.mode||process.env.CI||"linux"===process.platform&&!process.env.DISPLAY),envVars:{...g,...St?.variables}}),Mt=Bt?Dn.createLocal({workingDir:d}):void 0;Mt&&await Mt.captureSnapshot();const Ft=()=>{Ot&&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 va(e,t))if(ha(n))return n}(e,t),s=ya(ga(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(ma(n.dirname(r)));return ya(Array.from(t))}(ga(e,/\.(spec|test)\.(ts|js)$/)),i=s.length>0?s:o,a=r??(1===i.length?i[0]:void 0)??e,c=wa(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=wa(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=pa(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)rs.debug("stably package already present in dependencies");else{rs.info("stably package missing from devDependencies, installing...");try{da({workingDir:e,packageManager:Ta(e),packageSpec:"stably",targetSection:"devDependencies"}),rs.info("stably package installed successfully")}catch(e){rs.warn("Failed to install stably package",{error:String(e)})}}}(r.targetDir)}catch(e){rs.warn("Post-init: ensureStablyDependency failed",{error:String(e)})}try{!function(e){const t=pa(e);if(!t)return;const n=t.contents.devDependencies?.playwright??t.contents.dependencies?.playwright;if(n)if(Ia(n)!==ks)try{da({workingDir:e,packageManager:Ta(e),packageSpec:`playwright@${ks}`,targetSection:t.contents.devDependencies?.playwright?"devDependencies":"dependencies"}),rs.info("standalone playwright version aligned successfully",{version:ks})}catch(e){rs.warn("Failed to align standalone playwright version",{error:String(e)})}else rs.debug("standalone playwright already at supported version",{version:ks});else rs.debug("standalone playwright package not present")}(r.targetDir)}catch(e){rs.warn("Post-init: alignStandalonePlaywrightVersion failed",{error:String(e)})}try{!function(e){const t=pa(e);if(t)if(Ia(t.contents.devDependencies?.["@playwright/test"]??t.contents.dependencies?.["@playwright/test"])!==ks)try{rs.info(`Updating @playwright/test to supported version ${ks}...`),da({workingDir:e,packageManager:Ta(e),packageSpec:`@playwright/test@${ks}`,targetSection:t.contents.dependencies?.["@playwright/test"]?"dependencies":"devDependencies"}),rs.info("@playwright/test updated successfully")}catch(e){rs.warn("Failed to update @playwright/test",{error:String(e)})}else rs.debug("@playwright/test already at supported version",{version:ks});else rs.debug("No package.json found, skipping @playwright/test update")}(r.targetDir)}catch(e){rs.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 va(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 rs.debug("Agent guidance already present",{file:n.relative(e,r)||o});if(ba(i))return r}if(t)return t}return n.join(e,"AGENTS.md")}(e,t);if(i){rs.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"),rs.info("Agent guidance appended successfully")}catch(e){rs.warn("Failed to update agent guidance file",{error:String(e)})}}}(r.targetDir,r.repoRoot,t)}catch(e){rs.warn("Post-init: ensureAgentGuidance failed",{error:String(e)})}}else rs.warn("Post-init: could not resolve target package directory; skipping verification",{workingDir:e})}({workingDir:d,options:{googleAuth:k?.googleAuth,emailPackage:k?.emailPackage}})},Ht=Ot?(({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 n="string"==typeof t?t:String(t);return e(),Promise.resolve(`Session complete: ${n}`)})]}))({onComplete:()=>{Ft(),rt({status:"success"}),Qe(),C?.finish(),process.exit(0)}}):void 0,Gt=Ht?{"session-control":Ht}:{},Wt=S&&Pt?["mcp__create-report"]:[],Yt=S&&Ce?["mcp__create-trace-proof"]:[],Vt=Ot?lc:x?ac:[...ac,...Bt?["mcp__auto-heal-report"]:[],...Wt,...Yt],zt=Ot?lc:b?[...cc,"mcp__stably-agent-control"]:x?cc:[...cc,...Wt,...Yt],Kt=S&&Pt?{"create-report":Ea({prContext:Pt,authHeader:l,orgId:u,onReportPosted:e=>{we({githubComment:{url:e.commentUrl,prNumber:Pt.prNumber}})}})}:{},qt=S&&Ce?{"create-trace-proof":xa({authHeader:l,sessionId:Ce,orgId:u,workingDir:d,onTraceProofCaptured:e=>{we({traceProofs:[...be?.traceProofs??[],e]})}})}:{},Jt=Ot?Gt:Bt&&Mt?{"auto-heal-report":ua({authHeader:l,diffTracker:Mt,orgId:u,runId:e.runId,workingDir:d}),"run-history":Pa({authHeader:l,orgId:u,projectId:ps(c)}),...Gt}:{...Gt,...Kt,...qt},Qt="single"===e.mode,Xt=Ot?[]:Qt?[{matcher:"Write",hooks:[Vs({onFileCreated:e=>{if(at.includes(e)||at.push(e),be){if(be.filesCreated.some(t=>"string"==typeof t?t===e:t.path===e))return;const t=r.isAbsolute(e)?e:r.join(d,e),n=r.basename(e),{sessionId:s}=be,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:gr(),headers:gs(s),path:{sessionId:o}},(a.client??rr).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=Ss.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 bs({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:gr(),headers:gs(s),path:{sessionId:o}},(a.client??rr).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 rs.warn("Failed to upload automation file",{error:e instanceof Error?e.message:String(e)}),null}})({authHeader:l,content:r,contentType:"text/plain",filename:n,filePath:e,orgId:u,sessionId:s}),i={path:e,filename:n,bucketPath:o};ct.push(i),we({filesCreated:[...ct]})}catch(t){rs.warn("Failed to upload created file",{filePath:e,error:t instanceof Error?t.message:String(t)});const r={path:e,filename:n,bucketPath:null};ct.push(r),we({filesCreated:[...ct]})}})();lt.push(o)}}})]}]:[],Zt=Ot?[]:[...Bt?[{matcher:"Read",hooks:[Us({action:"reading",pathKey:"file_path"})]},{matcher:"Write",hooks:[Us({action:"writing",pathKey:"file_path"})]},{matcher:"Edit",hooks:[Us({action:"editing",pathKey:"file_path"})]},{matcher:"Grep",hooks:[Us({action:"searching",pathKey:"path"})]},{matcher:"Glob",hooks:[Us({action:"searching",pathKey:"path"})]},{matcher:"Bash",hooks:[Ws({workspaceBoundary:d})]}]:[],...jt?[{matcher:"Bash",hooks:[jt.hook]}]:[]],en=Object.keys(Rt).length>0?Rt:void 0,tn={...Ut};tn.MCP_TOOL_TIMEOUT=String(6e5),Nt&&(tn.ANTHROPIC_API_KEY=Nt,tn.ANTHROPIC_BASE_URL=dr,tn.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS="1",tn.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC="1");const nn=process.env.STABLY_AGENT_MODEL??"claude-opus-4-6",rn=Bt?"env"===c.type?c.auth.apiKey:c.auth.accessToken:void 0,sn=Bt?ps(c):void 0;Bt&&rn&&sn&&(tn.STABLY_API_KEY=rn,tn.STABLY_PROJECT_ID=sn);const on=yt?`\n\n## Custom Rules\n${yt}`:"",an=Tt?`\n\n## Custom Test Generation Rules\n${Tt}`:"",cn=Et?`\n\n## Project Rules (STABLY.md)\n${Et}`:"",ln=Ct+on+an+cn;rs.debug("[fix] Final system prompt assembled",{baseSize:Ct.length,fixRulesSize:on.length,createRulesSize:an.length,stablyMdSize:cn.length,finalSize:ln.length});const un=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 ja(t)?t:void 0}();if(e)return e;const t=r.join(Na,"stably-plugin-cli");if(ja(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}}(Na))for(const t of Ba){const n=r.join(e,t);if(ja(n))return n}}();if(e)return{type:"local",path:e}}(),dn=()=>(rs.info("[fix] Starting SDK query",{model:nn,tools:Vt,mcpServers:Object.keys(Jt),resumeSessionId:N??null,subagentsEnabled:!!en,subagentCount:Object.keys(Rt).length,useStablyAiProxy:$t,aiProxyUrl:dr,anthropicBaseUrl:void 0,stablyPluginPath:un?.path,stablyPluginExists:!!un}),Y({options:{executableArgs:["--max-old-space-size=4096"],tools:Vt,allowedTools:zt,...null!=vt?{maxBudgetUsd:vt}:{},betas:[],canUseTool:(e,t)=>(rs.debug("[fix] canUseTool called",{toolName:e}),Promise.resolve({behavior:"allow",updatedInput:t})),cwd:d,env:tn,hooks:{PostToolUse:Xt,PreToolUse:Zt},includePartialMessages:!0,agents:en,mcpServers:Jt,model:nn,permissionMode:"default",plugins:un?[un]:void 0,systemPrompt:ln,...N?{resume:N}:{}},prompt:C??ft})),pn=async e=>{if(y&&j&&!z&&!B)B=(async()=>{rs.info("[fix] Interrupting for user message",{messageCount:e.length,phase:le?.phase});try{await(D?.interrupt?.())}catch(e){rs.warn("[fix] Failed to interrupt response for user message",{error:e instanceof Error?e.message:String(e)})}await Ks(),C?.finish(),C=new qs,ee.clear(),D=dn();const t=e.map(e=>`[Message from web UI user]: ${e}`).join("\n\n");C.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}`),J=!0,j=!0})().finally(()=>{B=void 0}),await B;else for(const t of e)C?.pushText(`[Message from web UI user]: ${t}`)};if(Nt){x&&Xe({label:"Checking AI connectivity..."});const e=dr,t=`${e.replace(/\/$/,"")}/v1/messages`;rs.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":Nt,"anthropic-version":"2023-06-01","content-type":"application/json"},body:"{}"}),s=await e.text().catch(()=>""),o=Date.now()-n;rs.debug(`[fix] Pre-flight: ${e.status} in ${o}ms β ${s.slice(0,300)}`),401===e.status||403===e.status?(rs.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."):rs.info("[fix] Pre-flight: AI proxy key valid",{status:e.status,durationMs:o})}catch(t){rs.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{x&&"running"===nt&&Xe({label:void 0})}r&&(Ge({text:`[stably] ${r}\n`}),rt({error:r,status:"error"}),await ze(),rs.flush(),rs.printLogFileInfo(),process.exit(1))}rs.info("[fix] Creating initial agent query"),x&&(Xe({label:"Initializing verification session..."}),Ge({text:"Initializing verification session...\n"})),rs.flush(),D=dn(),rs.info("[fix] Agent query created, entering message loop"),"chat"!==e.mode&&(C.pushText(ft),te.push({role:"user",content:ft,timestamp:(new Date).toISOString()}));const fn=async t=>{De||(De=(async()=>{rs.info("[session] Interrupt requested",{source:t,mode:e.mode}),se="CANCELED",await ge("CANCELED"),he({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:fe(!0)}),await(ce?.closeAndWait()),await Promise.allSettled(lt),we({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0}),await(ye?.closeAndWait()),O&&(clearTimeout(O),O=void 0),Qe(),await Ks(),await(jt?.cleanup());try{await(D?.interrupt?.())}catch{}C?.finish(),te.length>0&&Ce&&await As({authHeader:l,orgId:u,sessionId:Ce,projectId:ps(c),history:te}).catch(e=>{rs.warn("[exit] Failed to upload session history",{error:e instanceof Error?e.message:String(e)})}),ze(),rs.flush()})()),await De};Le.current=async()=>{await fn("ctrl-c")};let hn=()=>{};hn=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 fn("signal"),process.exit(function(e){return"SIGINT"===e?130:143}(e))})()}});let gn=null,mn=null,yn="";Ne.current=async()=>{if(!Oe&&j&&C){Oe=!0;try{rs.info("[chat] User pressed Escape to cancel generation"),Ke(),qe(),M=!0,Be=!0;try{await(D?.interrupt?.())}catch(e){rs.warn("[chat] Failed to interrupt response on Escape",{error:e instanceof Error?e.message:String(e)})}await Ks();const e=C.drainQueue();C.finish(),C=new qs;for(const t of e)C.pushText(t);F=e.length,D=dn();for(const e of ee.keys())et({toolUseId:e,status:"error"});He()}finally{Oe=!1}}};let bn=0,wn=null,vn=!1;const In=b?void 0:x?9e4:18e4;let Tn=!1;const _n=null!=In?setTimeout(()=>{wn||"running"!==nt||(t=>{if(!Tn){if(Tn=!0,clearTimeout(_n),clearInterval(En),setTimeout(()=>process.exit(1),6e4).unref(),rs.error("[session] Session timeout",{reason:t,mode:e.mode,elapsed:Date.now()-ae}),se="FAILED",x||b){const e="This is taking longer than expected. Please try again.";Ge({text:`[stably] ${e}\n`}),rt({error:e,status:"error"})}else he({phase:"complete",endedAt:Date.now(),isError:!0,errorReason:"execution_error",errorMessage:`Session timed out: ${t}`,workers:fe(!0)});we({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:`Timed out: ${t}`});try{D?.interrupt?.()}catch{}C?.finish()}})("no response from AI service")},In):void 0;_n?.unref();const En=setInterval(()=>{const e=Date.now()-ae;wn?rs.info("[fix] Watchdog: message loop active",{messageCount:bn,elapsed:e}):(rs.info("[fix] Watchdog: waiting for first SDK message",{elapsed:e}),x&&!vn&&e>=15e3&&(Ge({text:"Still preparing verification. This can take a bit...\n"}),vn=!0)),rs.flush()},15e3);En.unref();try{let t=!1;for(;;){if(!D){rs.info("[fix] No response object, exiting message loop");break}t=!1,rs.info("[fix] Entering for-await on SDK response");try{for await(const t of D){if(Tn)break;bn++,wn||(wn=Date.now(),clearTimeout(_n),x&&Xe({label:void 0}),rs.info("[fix] First SDK message received",{waitDurationMs:wn-ae,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!==N&&(N=n,rs.debug("Captured Claude session id",{sessionId:N})),"stream_event"===t.type){const{event:e}=t;(bn<=5||bn%200==0)&&rs.debug("[fix] Stream event",{msgNum:bn,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&&(gn=e.index??null)}if("content_block_delta"===e?.type){const{delta:t}=e;if("text_delta"===t?.type&&t.text){yn&&(ne({role:"thinking",content:yn,timestamp:(new Date).toISOString()}),yn="");const e=n&&ee.has(n)?n:1===ee.size?Array.from(ee.keys())[0]:void 0;e?je({toolUseId:e,kind:"text",content:t.text}):x||Ge({text:t.text})}const r=t;if("thinking_delta"===r?.type&&r.thinking){if(n&&ee.has(n))continue;if(yn+=r.thinking,!x){const e=null!==gn&&gn!==mn;We({text:r.thinking,forceNewBlock:e}),e&&(mn=gn)}continue}}if("content_block_stop"===e?.type){const t=e.index;null!==gn&&gn===t&&(qe(),yn&&(ne({role:"thinking",content:yn,timestamp:(new Date).toISOString()}),yn=""),gn=null,Je())}"message_stop"===e?.type&&C&&(z=!1,C.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&&(ot=t,x&&(it=it?`${it}\n\n${t}`:t),rs.debug("Assistant message",{text:x?nc(t):t}),"fix"===e.mode&&(de(dc,{type:"ai_message",summary:t.slice(0,200)}),pe({type:"ai_message",summary:t.slice(0,200)})),A&&Ie({type:"ai_message",summary:t.slice(0,200)}),ne({role:"assistant",content:t,timestamp:(new Date).toISOString()}))}if(ee.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):[];rs.debug("Assistant message with active subagents",{hasParentToolUseId:!!n,parentToolUseId:n,activeSubagentIds:Array.from(ee.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&&(z=!0),t.name.startsWith("mcp__session-control__")||t.name.startsWith("mcp__stably-agent-control__"))continue;if(mc(t.name))continue;if(x&&gc.test(t.name))continue;if(ee.size>0&&rs.debug("Tool use detected with active subagents",{toolName:t.name,hasParentToolUseId:!!n,parentToolUseId:n,wouldRouteToSubagent:!!n&&ee.has(n),activeSubagentIds:Array.from(ee.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(rs.info("[fix] Subagent started",{subagentType:s,description:o,toolUseId:t.id,activeSubagentCount:ee.size+1}),ee.set(t.id,{subagentType:s,description:o}),Me({toolUseId:t.id,subagentType:s,description:o}),"fix"===e.mode){if("triage"===s){tt?.({phase:"triage"});const e={id:t.id,testDescription:"Triage",workerType:"triage",status:"running",summary:null,startedAt:Date.now(),endedAt:null,activity:[]};he({phase:"triage",workers:[...le?.workers??[],e]})}else if("code-worker"===s){ue.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:[]};tt?.({phase:"fixing",totalTests:ue.size,currentTestDescription:o||null}),he({phase:"fixing",totalTests:ue.size,currentTestDescription:o||null,lastTestDescription:o||le?.lastTestDescription||null,workers:[...le?.workers??[],e]})}else if("browser-worker"===s){ue.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:[]};tt?.({phase:"debugging",totalTests:ue.size,currentTestDescription:o||null}),he({phase:"debugging",totalTests:ue.size,currentTestDescription:o||null,lastTestDescription:o||le?.lastTestDescription||null,workers:[...le?.workers??[],e]})}else"validation"===s?(tt?.({phase:"validation",currentTestDescription:null}),he({phase:"validation",currentTestDescription:null})):"context"===s&&he({currentTestDescription:o||null});pe({type:"tool_call",summary:`[${s}] ${o}`.trim()})}continue}if(n&&ee.has(n)){const r=wo(t.name,t.input),s=r??vo(t.name),o=r?void 0:bo(t.name,t.input),i=o?`${s} (${o})`:s;if(rs.debug("Subagent tool called",{tool:t.name,parentToolUseId:n}),je({toolUseId:n,kind:"tool",content:i}),"fix"===e.mode){pe({type:"tool_call",summary:i});const e=ee.get(n);"code-worker"!==e?.subagentType&&"browser-worker"!==e?.subagentType&&"triage"!==e?.subagentType||de(n,{type:"tool_call",summary:i})}continue}if(n&&rs.debug("Tool with parent_tool_use_id but no matching subagent",{tool:t.name,parentToolUseId:n,activeSubagentIds:Array.from(ee.keys())}),rs.debug("Tool called",{tool:t.name,input:t.input}),Fe({rawName:t.name,toolInput:t.input}),t.id&&re.set(t.id,t.name),ne({role:"tool",content:"",timestamp:(new Date).toISOString(),toolName:t.name,toolInput:t.input}),"fix"===e.mode){const e=wo(t.name,t.input),n=e??vo(t.name),r=e?void 0:bo(t.name,t.input),s=r?`${n} (${r})`:n;de(dc,{type:"tool_call",summary:s}),pe({type:"tool_call",summary:s})}if(S){const e=wo(t.name,t.input),n=e??vo(t.name),r=e?void 0:bo(t.name,t.input),s=r?`${n} (${r})`:n;"initializing"===be?.phase?we({phase:"generating",currentActivity:s}):"mcp__playwright-test__test_run"===t.name&&"generating"===be?.phase?we({phase:"testing",currentActivity:s}):we({currentActivity:s}),Ie({type:"tool_call",summary:s})}if(x){const e=wo(t.name,t.input),n=e??vo(t.name),r=e?void 0:bo(t.name,t.input),s=nc(r?`${n} (${r})`:n);we("initializing"===be?.phase?{phase:"verifying",currentActivity:s}:{currentActivity:s}),Ie({type:"tool_call",summary:s})}}if("text"===t?.type){const r="string"==typeof t.text?t.text:"",s=n&&ee.has(n)?n:1===ee.size?Array.from(ee.keys())[0]:void 0;if(s&&r&&(je({toolUseId:s,kind:"text",content:r}),"fix"===e.mode)){const e=ee.get(s);"code-worker"!==e?.subagentType&&"browser-worker"!==e?.subagentType&&"triage"!==e?.subagentType||de(s,{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("")),rs.debug("Tool result",{toolUseId:n,isError:s,output:o?.slice(0,500)});const a=5e4,c=n?re.get(n):void 0;if(ne({role:"tool_result",content:"",timestamp:(new Date).toISOString(),toolName:c,toolOutput:o?.slice(0,a),isError:s}),n&&ee.has(n)){const t=ee.get(n);if(rs.info("[fix] Subagent completed",{toolUseId:n,isError:s,subagentType:t?.subagentType,description:t?.description,activeSubagentCount:ee.size-1}),o&&je({toolUseId:n,kind:"text",content:o}),et({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=(le?.workers??[]).map(r=>r.id===n?{...r,status:e,summary:t,endedAt:Date.now()}:r);he({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=(le?.workers??[]).map(r=>r.id===n?{...r,status:e,summary:t,endedAt:Date.now()}:r);s?(tt?.({failedTests:(le?.failedTests??0)+1,currentTestDescription:null}),he({failedTests:(le?.failedTests??0)+1,currentTestDescription:null,workers:r})):(tt?.({fixedTests:(le?.fixedTests??0)+1,currentTestDescription:null}),he({fixedTests:(le?.fixedTests??0)+1,currentTestDescription:null,workers:r}))}ee.delete(n)}}continue}if("result"!==t.type);else{if(rs.info("[fix] Agent result received",{subtype:t.subtype,messageCount:bn,elapsed:Date.now()-ae,activeSubagents:ee.size,fixedTests:le?.fixedTests,failedTests:le?.failedTests,phase:le?.phase}),y){if("success"===t.subtype){O&&(clearTimeout(O),O=void 0);for(const e of H)C?.pushText(`[Message from web UI user]: ${e}`);if(H=[],(A||"fix"===e.mode)&&C){if(C.hasQueuedMessages()){rs.info("[ws] Queued web UI messages found, continuing agent"),j=!0,C.allowNextTurn();continue}if(await yc(C,3e3)){rs.info("[ws] Web UI message received during grace period, continuing agent"),j=!0,C.allowNextTurn();continue}C.finish()}tt?.({phase:"complete",currentTestDescription:null,endedAt:Date.now()}),he({phase:"complete",currentTestDescription:null,endedAt:Date.now(),isError:!1,workers:fe(!1)}),await Promise.allSettled(lt);const t=oc({mode:e.mode,lastAssistantText:ot});if("verify"===e.mode){(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt).trim();const n=it||ot,r=/```verdict\s*\r?\n/.test(n),s=sc(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=rc(s);"PASS"===s.verdict?q.green("VERIFICATION PASSED"):"FAIL"===s.verdict?q.red("VERIFICATION FAILED"):ic("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=>{}),we({phase:"complete",endedAt:Date.now(),isError:"PASS"!==s.verdict,currentActivity:null,resultSummary:t}),process.exitCode="PASS"===s.verdict?0:"FAIL"===s.verdict?1:2,rt({status:"success"})}else{if(we({phase:"complete",endedAt:Date.now(),isError:!1,currentActivity:null,resultSummary:t}),Qt&&at.length>0){q.green("Created files:");for(const e of at)q.green(`- ${e}`)}const e=(e,t)=>`]8;;${e}${t}]8;;`,n=st?q.cyan(`π View Autoheal Report:\n ${e(st,q.cyan(q.bold(q.underline(st))))}`):void 0;rt({status:"success",result:n}),se="COMPLETED"}}else if(B||J)rs.info("[fix] Suppressing error status: user-message interrupt in progress");else if(M)se="CANCELED",he({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:fe(!0)}),await Promise.allSettled(lt),we({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0});else if(x){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."),ic("VERIFICATION INCONCLUSIVE"),await Promise.allSettled(lt),we({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),rt({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.`,rs.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"),tt?.({endedAt:Date.now(),isError:!0}),he({phase:"complete",endedAt:Date.now(),isError:!0,errorReason:n,errorMessage:r,totalCostUsd:e,currentTestDescription:null,workers:fe(!0)}),await Promise.allSettled(lt),we({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),rt({error:r,status:"error"}),process.exitCode=1,se="FAILED"}M=!1;break}if("success"!==t.subtype){if(!M){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.`,rs.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."),rt({error:e,status:"error"}),process.exitCode=1}}else rt({status:"success"});j=!1,M=!1,Xe({label:void 0}),C?.allowNextTurn(),T&&F>0&&(F-=1,j=!0,rt({status:"running"}))}}}catch(e){if(Be){Be=!1,M=!1,ee.clear(),Ve(),yn&&ne({role:"thinking",content:yn,timestamp:(new Date).toISOString()}),gn=null,mn=null,yn="",Je(),F>0?(j=!0,rt({status:"running"})):(j=!1,rt({status:"success"})),t=!0;continue}throw e}if(Be)Be=!1,M=!1,ee.clear(),Ve(),yn&&ne({role:"thinking",content:yn,timestamp:(new Date).toISOString()}),gn=null,mn=null,yn="",Je(),F>0?(j=!0,rt({status:"running"})):(j=!1,rt({status:"success"})),t=!0;else if(B&&await B,J&&(J=!1,t=!0,rt({status:"running"}),rs.info("[fix] Resuming after user-message interrupt")),!t)break}}catch(e){M?(se="CANCELED",he({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:fe(!0)}),await Promise.allSettled(lt),we({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0})):(rs.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()-ae}),rt({error:`Agent encountered an error: ${e}`,status:"error"}),process.exitCode=1,se="FAILED",he({phase:"complete",endedAt:Date.now(),isError:!0,currentTestDescription:null,workers:fe(!0)}),await Promise.allSettled(lt),we({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),rs.flush(),rs.printLogFileInfo())}finally{if(_n&&clearTimeout(_n),clearInterval(En),O&&(clearTimeout(O),O=void 0),rs.info("[fix] Agent session ending",{finalStatus:se,elapsed:Date.now()-ae,totalMessages:bn}),Ft(),j=!1,M=!1,hn(),process.off("uncaughtException",a),C?.finish(),se){rs.info("[fix] Reporting final autoheal status",{status:se});const e=Date.now();await ge(se),rs.info("[fix] Final autoheal status reported",{durationMs:Date.now()-e})}if(rs.info("[fix] Closing WebSocket progress reporter"),await(ce?.closeAndWait()),await Promise.allSettled(lt),await(ye?.closeAndWait()),!Bt&&te.length>0&&Ce&&(rs.info("[session] Uploading session history",{messageCount:te.length}),await As({authHeader:l,orgId:u,sessionId:Ce,projectId:ps(c),history:te}).catch(e=>{rs.warn("[session] Failed to upload session history",{error:e instanceof Error?e.message:String(e)})})),Bt&&Mt){const t=Date.now();try{rs.info("[fix] Computing diff...");const n=await Mt.computeDiff();if(n&&n.trim().length>0){rs.info("[fix] Uploading diff...",{diffLength:n.length});const{diffBucketPath:r,uploadUrl:s}=await Is({authHeader:l,contentType:"text/plain",orgId:u,runId:e.runId});await bs({body:n,contentType:"text/plain",uploadUrl:s,errorContext:"diff"}),await Ts({authHeader:l,diffBucketPath:r,orgId:u,runId:e.runId}),rs.info("[fix] Diff uploaded",{durationMs:Date.now()-t})}else rs.info("[fix] No diff to upload (empty or no changes)")}catch(e){rs.warn("[fix] Failed to upload diff",{error:e instanceof Error?e.message:String(e),durationMs:Date.now()-t})}}rs.info("[fix] Cleaning up diff tracker"),await(Mt?.cleanup()),Bt&&te.length>0&&Ce&&(rs.info("[fix] Uploading session history",{messageCount:te.length}),await As({authHeader:l,orgId:u,sessionId:Ce,projectId:ps(c),history:te}).catch(e=>{rs.warn("[fix] Failed to upload session history",{error:e instanceof Error?e.message:String(e)})})),rs.info("[fix] Running final cleanup"),await(jt?.cleanup()),await ze(),rs.info("[fix] Cleanup complete"),Tn&&(rs.flush(),rs.printLogFileInfo(),process.exit(1))}},Ic=he.object({runId:he.string(),timestamp:he.number()}),Tc=[{args:["--trace=on"],description:"Run Playwright tests",name:"test"},{args:[],description:"Install browser dependencies",name:"install"}],_c=["You have two different versions of @playwright/test"];function Ec(e){const[t,...n]=ea(e),r=[t,...n.slice(0,-1)].join(" ");return(t,n)=>{let s=t.toString();for(const e of Tc)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 Sc({overrideArgs:e,subcommand:t}){rs.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=Tc.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=Qi();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]=ea(s),a=Ec(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];rs.info("[test] Forwarded args computed",{forwardedArgs:m}),rs.info("[test] Resolving Stably test environment");const y=Date.now(),b="test"===t?await(async()=>{rs.info("[test] Resolving Stably test env");const e=(()=>{if(process.env.STABLY_WS_URL)return;if("https://api.stably.ai"===ar)return;const e=ar.startsWith("http://")?"ws://":"wss://";return`${ar.replace(/^https?:\/\//,e).replace(/\/$/,"")}/reporter`})();rs.debug("[test] WebSocket URL resolved",{wsUrl:e??"(default)"});const t=ls();if(t)return rs.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}};rs.info("[test] No env var auth, attempting OAuth auth");const n=Date.now(),r=await(async()=>{const e=ls();if(e)return{auth:e,type:"env"};const t=await us(),n=t?await Ur():void 0;return t&&n?{auth:{accessToken:t.accessToken,context:n},type:"oauth"}:void 0})();if(rs.info("[test] OAuth auth resolved",{durationMs:Date.now()-n,hasAuth:!!r,authType:r?.type}),!r||"env"===r.type)return void rs.info("[test] No usable auth found");const s=process.env.STABLY_PROJECT_ID?.trim(),o=s||ps(r);if(!o)return void rs.warn("[test] No project ID available");rs.info("[test] Fetching JWT API key",{projectId:o});const i=Date.now(),a=await(async(e,t)=>{try{rs.debug("Requesting JWT API key",{projectId:t,apiUrl:ar});const n=await(async({accessToken:e,projectId:t})=>{const n=await(r={auth:e,client:gr(),path:{projectId:t}},(r.client??rr).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 rs.debug("JWT API key obtained",{keyPrefix:n.apiKey.substring(0,10)}),n.apiKey}catch(e){return void rs.warn("Failed to get JWT API key for test reporter",{error:e instanceof Error?e.message:String(e)})}})(r.auth.accessToken,o);rs.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 rs.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;rs.info("[test] Stably test environment resolved",{durationMs:Date.now()-y,hasCredentials:null!=b,hasWsUrl:!!b?.STABLY_WS_URL}),rs.info("[test] Loading remote environment variables");const w=await hs();rs.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")}:{}};rs.info("[test] Setting up Stably reporter injection");const T="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=os();if("local"!==e){const t=as(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=>I(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,`.stably-playwright-wrapper.config.${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: '${ir}',\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: '${ir}',\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 I(a)||A(a,{recursive:!0}),k(u,d,"utf-8"),function(e){const t=i(e,".gitignore");try{if(I(t)){const e=_(t,"utf-8");if(e.split("\n").map(e=>e.trim()).includes(ro))return;const n=e.length>0&&!e.endsWith("\n");E(t,`${n?"\n":""}${ro}\n`)}else k(t,`${ro}\n`)}catch{}}(a),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=oo(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;rs.info("[test] Reporter injection setup complete",{hasWrapperConfig:!!T}),rs.info("[test] Spawning Playwright process"),await function(e,t={}){rs.info("[test] Detecting Playwright installation");const n=Qi();rs.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]=ea(r),i=(a=t.env)?{...process.env,...a}:process.env;var a;const c=[s,...o,...e];rs.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"}}});rs.info("[test] Playwright process spawned",{childPid:u.pid});const d=Ec(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 _c)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=>{rs.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()&&(rs.error("[test] Playwright process error",{error:e.message,childPid:u.pid}),t(e))}),u.on("close",t=>{if(!h())return;rs.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;rs.info("[test] Playwright process closed, cleaning up wrapper config"),(e=T)&&I(e)&&C(e)}})}function xc(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 Ac=e=>"oauth"===e.type?e.auth.context.orgId:void 0,kc=(e,t,n)=>{if(401!==e.response.status&&403!==e.response.status||(le(q.red("Access denied.")),process.exit(1)),404===e.response.status&&n&&(le(q.red(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";le(q.red(t)),process.exit(1)}e.error&&(le(q.red(`Failed to ${t}: ${e.response.status}`)),process.exit(1))},Cc={PASSED:q.green,FAILED:q.red,TIMEDOUT:q.red,CANCELLED:q.yellow,INTERRUPTED:q.yellow,RUNNING:q.cyan,QUEUED:q.dim},Pc=(e,t)=>e?e.length>t?`${e.slice(0,t-1)}β¦`:e:"-",Rc=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")}`},Uc=e=>(Cc[e]??(e=>e))(e),$c=/\x1b\[[0-9;]*m/g,Lc=(e,t)=>{const n=e.replace($c,"").length,r=Math.max(0,t-n);return e+" ".repeat(r)},Dc=e=>`${JSON.stringify(e,null,2)}\n`,Nc=(e,t,n)=>{if(!e)return;const r=e.toUpperCase();if(t.includes(r))return r;le(q.red(`Invalid ${n} value "${e}". Must be one of: ${t.join(", ").toLowerCase()}`)),process.exit(1)},Oc=/\x1b\[[0-9;]*m/g,Bc=(e,t)=>{const n=e.replace(Oc,"").length,r=Math.max(0,t-n);return e+" ".repeat(r)},jc=(e,t)=>e?e.length>t?`${e.slice(0,t-1)}β¦`:e:"-",Mc=e=>e?e.split("T")[0]??"-":"-",Fc=e=>`${(100*e).toFixed(1)}%`,Hc=e=>`${JSON.stringify(e,null,2)}\n`,Gc=e=>{if(!e)return;const t=parseInt(e,10);return(Number.isNaN(t)||t<1||t>90)&&(le(q.red("--days must be an integer between 1 and 90")),process.exit(1)),t},Wc=e=>{if(!e)return;const t=parseInt(e,10);return(Number.isNaN(t)||t<1||t>100)&&(le(q.red("--limit must be an integer between 1 and 100")),process.exit(1)),t},Yc="stably",Vc=`https://registry.npmjs.org/${Yc}/latest`;function zc(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 Kc(e,t){const n=zc(e),r=zc(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 qc=r.join(D.homedir(),".stably"),Jc=r.join(qc,"update-check.json"),Qc="1"===process.env.STABLY_DISABLE_UPDATE_CHECK,Xc=ge.object({lastCheck:ge.number(),latestVersion:ge.string()}),Zc=Symbol.for("stably.updateNotifier.registered");function el(e=""){process.stdout.write(`${e}\n`)}function tl(...e){process.stderr.write(`${e.join(" ")}\n`)}var nl=ge.object({version:ge.string()});var rl=!1,sl=async()=>{if(rl)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{}},ol=e=>{const t=e.toLowerCase();return t.startsWith("npm_config_")||"node_options"===t};!function(){if(Qc||function(e=process.argv.slice(2)){return e.includes("upgrade")}())return;const e=function(){try{const e=v.readFileSync(Jc,"utf-8");return Xc.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 = '${Vc}';\n const cacheFile = ${JSON.stringify(Jc)};\n const cacheDir = ${JSON.stringify(qc)};\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&&Kc(ir,e.latestVersion)){if(!0===process[Zc])return;process[Zc]=!0;let t=!1;const n=()=>{if(t)return;t=!0;const n=`${q.yellow(`update available (${ir} β ${e.latestVersion})`)} - run \`${Yc} upgrade\` to get the latest version\n`;try{v.writeSync(2,n)}catch{}};process.once("beforeExit",n),process.once("exit",n)}}(),$e.cwdChanged&&rs.debug("Changed working directory",{cwd:$e.newCwd});for(const e of $e.envFilesLoaded)rs.debug("Loaded env file",{path:e});for(const e of $e.envFileErrors)rs.warn(e);var il=process.argv.findIndex(e=>"-v"===e||"--verbose"===e);-1!==il&&process.argv.splice(il,1);var al=process.argv.findIndex(e=>"--no-telemetry"===e);-1!==al&&process.argv.splice(al,1),rs.info("CLI starting",{version:ir,args:process.argv.slice(2),cwd:process.cwd()}),process.on("unhandledRejection",(e,t)=>{rs.error("Unhandled promise rejection",{reason:e instanceof Error?{message:e.message,stack:e.stack}:e,promise:String(t)}),rs.flush(),rs.printLogFileInfo()}),process.on("uncaughtException",(e,t)=>{"EPIPE"!==e.code&&(rs.error("Uncaught exception",{error:{message:e.message,stack:e.stack,name:e.name},origin:t}),rs.flush(),rs.printLogFileInfo())});var cl=new u;cl.name("stably").description("AI-assisted Playwright testing CLI").version(ir),cl.enablePositionalOptions(),cl.showHelpAfterError(),cl.exitOverride(),cl.configureHelp({subcommandTerm:e=>{const t=e.registeredArguments.map(e=>e.required?`<${e.name()}>`:`[${e.name()}]`).join(" ");return t?`${e.name()} ${t}`:e.name()}}),cl.addHelpText("after","\nGlobal options (available for all commands):\n -C, --cwd <path> Change working directory before running\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 ll=[];cl.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>{ll.push(e)}});var ul=()=>{const e=cl.helpInformation().trimEnd();return e?`${e}\n`:""},dl=(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},pl=()=>{process.stdout.write(ul())};cl.command("help [command...]").description("Show help for a command (e.g. stably help create)").action(e=>{if(!e||0===e.length)return void pl();const t=dl(cl,e);if(!t)return process.stderr.write(`Unknown command: ${e.join(" ")}\n`),pl(),void(process.exitCode=1);var n;n=t,process.stdout.write((e=>{const t=e.helpInformation().trimEnd();return t?`${t}\n`:""})(n))}),cl.action(()=>vc({mode:"chat",getHelpText:ul})),cl.command("login").description("Authenticate with Stably in your browser").action(Mr),cl.command("logout").description("Clear stored Stably credentials").action(async()=>{const e=ls();e&&(ce.warn(`Environment variables ${q.cyan("STABLY_API_KEY")} and ${q.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 Cr();if(!t)return void le(e?q.yellow("No stored OAuth login found to clear."):q.yellow("You are not logged in."));const n=ue();n.start("Logging out..."),await(async e=>{try{await fetch(`${lr}/api/backend/v1/logout`,{body:JSON.stringify({refresh_token:e}),headers:{"Content-Type":"application/json"},method:"POST"})}catch{}})(t.refreshToken),await Rr(),await $r(),n.stop(q.green("β Logged out")),le(q.green("You have been logged out successfully."))}),cl.command("whoami").description("Show auth status and current project").action(async()=>{ce.info(`${q.bold("CLI Version:")} ${q.cyan(ir)}`);const e=ls();if(e){ce.info(q.dim("Authentication: Environment variables")),ce.info(` ${q.bold("API Key:")} ${q.cyan(e.apiKey.slice(0,8))}...`),ce.info(` ${q.bold("Project ID:")} ${q.cyan(e.projectId)}`);const t=await Cr();if(t){let e;try{e=Ir(t.accessToken).email}catch{e=void 0}ce.warn("Stored OAuth login detected but will be ignored (env auth takes precedence)."),e&&ce.info(` ${q.bold("OAuth Email:")} ${q.cyan(e)}`),ce.info(` ${q.bold("Tip:")} Unset env vars to use OAuth`)}return void le(q.green("Authenticated via environment variables"))}const t=await Cr();if(!t)return void le(q.yellow("Not logged in. Run `stably login` to authenticate."));let n;try{n=Ir(t.accessToken).email}catch{n=void 0}const s=await Ur();if(!s)return ce.info(q.dim("Authentication: OAuth (not linked to a project)")),n&&ce.info(` ${q.bold("Email:")} ${q.cyan(n)}`),void le(q.yellow("Logged in but this directory is not linked to a project. Run `stably login` to link."));const o=await(async()=>Tr(process.cwd(),Sr))(),i=o?r.dirname(o):process.cwd(),a=r.relative(process.cwd(),i)||".";ce.info(q.dim("Authentication: OAuth")),n&&ce.info(` ${q.bold("Email:")} ${q.cyan(n)}`),ce.info(` ${q.bold("Organization:")} ${q.cyan(s.orgName)}`),ce.info(` ${q.bold("Project:")} ${q.cyan(s.projectName)}`),ce.info(` ${q.bold("Linked at:")} ${q.dim(a)}`),le(q.green("Authenticated"))}),cl.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 ds(),n="oauth"===t.type?`${t.auth.context.orgName}-${t.auth.context.projectName}`.toLowerCase().replace(/[^a-z0-9-]/g,""):`project-${t.auth.projectId}`.toLowerCase(),r=ue();r.start("Starting development server...");const s=await Re(`http://localhost:${e.port}`,{subdomain:n});r.stop(`Your local environment is available at: ]8;;${s.url}${q.underline(q.cyan(s.url))}]8;;`)}),cl.command("create [prompt...]").description("Generate a test from prompt (omit prompt to infer from branch diff)").option("-o, --output <dir>","Output directory for generated test files").action(async(e,t)=>{const n=e.length>0&&"test"===e[0]?e.slice(1):e;return vc({mode:"single",prompt:n,outputDir:t.output})}).command("test",{hidden:!0}).description("Generate a Playwright test from a prompt (deprecated: use `stably create <prompt>` directly)").argument("<prompt...>","Prompt describing the test to generate").option("-o, --output <dir>","Output directory for generated test files").action(async(e,t)=>vc({mode:"single",prompt:e,outputDir:t.output})),cl.command("verify <prompt...>").description("Verify your app works correctly against a prompt").option("-u, --url <url>","Starting URL to verify against").option("--max-budget <dollars>","Maximum budget in USD (default: 5)",Number.parseFloat).option("--no-interactive","Disable interactive verify preflight setup").action(async(e,t)=>{if(void 0!==t.maxBudget&&(!Number.isFinite(t.maxBudget)||t.maxBudget<=0))throw new Error("--max-budget must be a positive number");return vc({mode:"verify",prompt:e,url:t.url,maxBudgetUsd:t.maxBudget,interactive:t.interactive})}),cl.command("internal-fix-run <runId>",{hidden:!0}).description("Internal: run fix session in subprocess").action(async e=>vc({mode:"fix",runId:e})),cl.command("fix [runId]").description("Fix failing tests from a run (auto-detects from last test run or CI)").action(async e=>{(function(e){try{return h("git rev-parse --is-inside-work-tree",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}})(process.cwd())||(rs.error('Not a git repository. The "stably fix" command requires a git repository to track changes made during the fix. Please run this command from inside a git repository.'),process.stderr.write('Error: Not a git repository.\nThe "stably fix" command requires a git repository to track changes made during the fix.\nPlease run this command from inside a git repository.\n'),process.exit(1));const t=await(async e=>{const t=e=>e.replace(/\//g,"_");if(e)return rs.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),...(n={env:e,cwd:t},{commit:Jt(n),branch:Qt(n)})};var n})();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 rs.debug("Run ID detected from CI environment",{runId:n}),t(n);rs.debug("No explicit run ID or CI environment detected, checking last-run.json");const r=await(async()=>{try{const e=await Tr(process.cwd(),".stably/last-run.json");if(!e)return;const t=await Z(e,"utf-8");return{...Ic.parse(JSON.parse(t)),filePath:e}}catch{return}})();if(r){const e=(Date.now()-r.timestamp)/36e5;return rs.debug("Run ID found in last-run.json",{runId:r.runId,timestamp:r.timestamp,filePath:r.filePath,ageHours:Math.round(e)}),e>24&&rs.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)}rs.debug("No run ID found in last-run.json")})(e);t||(process.stderr.write('Run ID is required. Either:\n 1. Run "stably test" first (run ID will be auto-detected)\n 2. Provide a run ID: stably fix <runId>\n 3. Run in CI (auto-detected from environment)\n'),process.exit(1));const n=await(async e=>{const t=await ds(),n=fs(t),r=ps(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))ol(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"})})(t);0!==n&&process.exit(n)}),cl.command("init").description("Initialize Playwright and Stably SDK in your project").action(async()=>vc({mode:"init"})),cl.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;el(q.cyan("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(Vc,{signal:e.signal});if(!t.ok)throw new Error(`Failed to fetch latest version: ${t.statusText}`);return nl.parse(await t.json()).version}finally{clearTimeout(t)}}();return{current:ir,latest:e,isOutdated:Kc(ir,e)}}()}catch(e){return tl(q.red("Failed to check for updates:"),e instanceof Error?e.message:e),void(process.exitCode=1)}if(el(`Current version: ${q.yellow(n.current)}`),el(`Latest version: ${q.green(n.latest)}`),el(),!n.isOutdated)return void el(q.green("β You are already on the latest version!"));if(el(q.yellow(`β A new version is available: ${n.current} β ${n.latest}`)),el(),t)return el(q.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",`${Yc}@latest`],description:`npm install -g ${Yc}@latest`};case"global-pnpm":return{command:"pnpm",args:["add","-g",`${Yc}@latest`],description:`pnpm add -g ${Yc}@latest`};case"global-yarn-classic":return{command:"yarn",args:["global","add",`${Yc}@latest`],description:`yarn global add ${Yc}@latest`};case"npx":return{command:"npx",args:[`${Yc}@latest`],description:`npx ${Yc}@latest (always uses latest)`}}}(r);if("npx"===r)return el(q.dim("You are running via npx, which always fetches the latest version.")),void el(q.dim(`Simply run: ${q.white("npx stably")} to use the latest version.`));"unknown"===r?(el(q.yellow("Could not detect installation method. Falling back to npm.")),el()):"global-yarn-berry"===r&&(el(q.yellow("Yarn Berry does not support global packages. Falling back to npm.")),el()),el(`Upgrade command: ${q.cyan(s.description)}`),el(),el(q.cyan("Upgrading...")),el();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(Jc)}catch{}}(),el(),el(q.green("β Upgrade complete!")),el(q.dim(`Run ${q.white("stably --version")} to verify.`))}catch(e){tl(q.red("Upgrade failed:"),e instanceof Error?e.message:e),el(),el(q.dim("You can try manually running:")),el(q.cyan(` ${s.description}`)),process.exitCode=1}var o,i}(e));var fl=cl.command("env").description("Manage remote environments");fl.command("list").description("List available environments").action(async()=>{const e=await ds(),t=ps(e),n=fs(e);rs.debug("Listing environments",{projectId:t});const r=await(s={auth:n,client:gr(),path:{projectId:t}},(s.client??rr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/environments",...s}));var s;401!==r.response.status&&403!==r.response.status||(le(q.red("Access denied.")),process.exit(1)),r.error&&(le(q.red(`Failed to list environments: ${r.response.status}`)),process.exit(1));const{environments:o}=r.data;if(0!==o.length){process.stdout.write(`${q.bold("Environments")}\n\n`);for(const e of o){const t=e.isDefault?q.green(" (default)"):"",n=q.dim(` ${e.variableCount} variable${1!==e.variableCount?"s":""}`);process.stdout.write(` ${q.cyan(e.name)}${t}${n}\n`),e.description&&process.stdout.write(` ${q.dim(e.description)}\n`)}process.stdout.write("\n")}else process.stdout.write(q.dim("No environments found. Create one on your Stably dashboard.\n"))}),fl.command("inspect <name>").description("Show variable metadata (name, sensitive flag, updated timestamp)").action(e=>(async e=>{const t=await ds(),n=ps(t),r=fs(t);rs.debug("Inspecting environment",{name:e,projectId:n});const s=await(o={auth:r,client:gr(),path:{projectId:n,environmentName:e}},(o.client??rr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/environments/{environmentName}/inspect",...o}));var o;404===s.response.status&&(le(q.red(`Environment "${e}" not found. Run ${q.bold("stably env list")} to see available environments.`)),process.exit(1)),401!==s.response.status&&403!==s.response.status||(le(q.red("Access denied.")),process.exit(1)),s.error&&(le(q.red(`Failed to inspect environment: ${s.response.status}`)),process.exit(1));const{variables:i}=s.data;if(0!==i.length){process.stdout.write(`${q.bold(e)} ${q.dim(`(${i.length} variable${1!==i.length?"s":""})`)}\n\n`);for(const e of i){const t=q.dim(` [updated ${xc(e.updatedAt)}]`);e.sensitive?process.stdout.write(` ${q.cyan(e.name)} ${q.yellow("[sensitive]")}${t}\n`):process.stdout.write(` ${q.cyan(e.name)}${t}\n`)}process.stdout.write("\n")}else process.stdout.write(q.dim(`Environment "${e}" has no variables.\n`))})(e));var hl=cl.command("analytics").description("View test health analytics");hl.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 ds(),n=ps(t),r=fs(t),s=Ac(t),o=Gc(e.days),i=Wc(e.limit);rs.debug("Listing flaky tests",{projectId:n,days:o,branch:e.branch,limit:i});const a=gr(),c=await a.get({url:"/internal/v1/cli/analytics/flaky",security:[{scheme:"bearer",type:"http"}],auth:r,headers:{...gs(s)},query:{projectId:n,days:o,branchName:e.branch,limit:i}});kc(c,"list flaky tests");const l=c.data;e.json?process.stdout.write(Hc(l)):process.stdout.write(((e,t)=>{const n=[],r=e.filters.branch?`branch: ${e.filters.branch}`:"all branches";if(n.push(q.bold(`Most Flaky Tests (last ${e.period.days} days, ${r})`)),n.push(""),0===e.tests.length)return n.push(q.dim(" No flaky tests found.")),n.push(""),n.join("\n");const s=` ${Bc("REF",14)}${Bc("TEST",20)}${Bc("LOCATION",30)}${Bc("FLAKY",8)}${Bc("RUNS",7)}${Bc("RATE",9)}LAST FLAKY`;n.push(q.dim(s));for(const t of e.tests){const e=t.testRef,r=jc(t.title,18),s=jc(t.location,28),o=String(t.flakyCount),i=String(t.nonSkippedRuns),a=Fc(t.flakyRate),c=Mc(t.lastFlakyAt);n.push(` ${Bc(e,14)}${Bc(r,20)}${Bc(s,30)}${Bc(o,8)}${Bc(i,7)}${Bc(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: ${q.cyan(q.underline(`https://app.stably.ai/p/${t}/analytics`))}`),n.push(""),n.join("\n")})(l,n))}),hl.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 ds(),n=ps(t),r=fs(t),s=Ac(t),o=Gc(e.days),i=Wc(e.limit);rs.debug("Listing failing tests",{projectId:n,days:o,branch:e.branch,limit:i});const a=gr(),c=await a.get({url:"/internal/v1/cli/analytics/failures",security:[{scheme:"bearer",type:"http"}],auth:r,headers:{...gs(s)},query:{projectId:n,days:o,branchName:e.branch,limit:i}});kc(c,"list failing tests");const l=c.data;e.json?process.stdout.write(Hc(l)):process.stdout.write(((e,t)=>{const n=[],r=e.filters.branch?`branch: ${e.filters.branch}`:"all branches";if(n.push(q.bold(`Most Failed Tests (last ${e.period.days} days, ${r})`)),n.push(""),0===e.tests.length)return n.push(q.dim(" No failing tests found.")),n.push(""),n.join("\n");const s=` ${Bc("REF",14)}${Bc("TEST",20)}${Bc("LOCATION",30)}${Bc("FAILED",8)}${Bc("RUNS",7)}${Bc("RATE",9)}LAST FAILED`;n.push(q.dim(s));for(const t of e.tests){const e=t.testRef,r=jc(t.title,18),s=jc(t.location,28),o=String(t.failedCount),i=String(t.nonSkippedRuns),a=Fc(t.failureRate),c=Mc(t.lastFailedAt);n.push(` ${Bc(e,14)}${Bc(r,20)}${Bc(s,30)}${Bc(o,8)}${Bc(i,7)}${Bc(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: ${q.cyan(q.underline(`https://app.stably.ai/p/${t}/analytics`))}`),n.push(""),n.join("\n")})(l,n))});var gl=cl.command("runs").description("View test run history");gl.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 ds(),n=ps(t),r=fs(t),s=Ac(t);let o;e.limit&&(o=parseInt(e.limit,10),(Number.isNaN(o)||o<1||o>100)&&(le(q.red("--limit must be an integer between 1 and 100")),process.exit(1)));const i=Nc(e.source,["LOCAL","CI","WEB"],"--source"),a=Nc(e.status,["QUEUED","RUNNING","PASSED","FAILED","TIMEDOUT","CANCELLED","INTERRUPTED"],"--status"),c=Nc(e.trigger,["MANUAL","SCHEDULED","UI","API","GITHUB_ACTION","SUITE_RUN"],"--trigger");rs.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 sr({auth:r,client:gr(),headers:gs(s),query:{projectId:n,branchName:e.branch,limit:o,afterRunId:e.after,beforeRunId:e.before,source:i,status:a,suiteName:e.suite,trigger:c}});kc(l,"list runs");const{runs:u,hasMore:d}=l.data;e.json?process.stdout.write(Dc(l.data)):process.stdout.write(((e,t)=>{if(0===e.length)return q.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=`${Lc("Run ID",r.runId.w)}${Lc("Status",r.status.w)}${Lc("Branch",r.branch.w)}${Lc("Started",r.started.w)}Tests`;s.push(q.bold(o));for(const t of e){const e=Pc(t.runId,r.runId.t),n=Uc(t.status),o=Pc(t.branchName,r.branch.t),i=Rc(t.startedAt),a=t.totalCount.toString();s.push(`${Lc(e,r.runId.w)}${Lc(n,r.status.w)}${Lc(o,r.branch.w)}${Lc(i,r.started.w)}${a}`)}if(t&&e.length>0){const t=e.at(-1)?.runId;t&&(s.push(""),s.push(q.dim(`Next page: stably runs list --before ${t}`)))}return s.push(""),s.join("\n")})(u,d))}),gl.command("view <runId>").description("Show details for a specific run").option("--json","Output as JSON").action(async(e,t)=>{const n=await ds(),r=fs(n),s=Ac(n);rs.debug("Viewing run",{runId:e});const o=await or({auth:r,client:gr(),headers:gs(s),path:{runId:e},query:{detail:"full"}});if(kc(o,"get run details",`Run "${e}" not found.`),t.json)process.stdout.write(Dc(o.data));else{const e=o.data;process.stdout.write((e=>{const t=[];if(t.push(q.bold(`Run ${e.runId}`)),t.push(` ${q.dim("Status:")} ${Uc(e.status)}`),e.branchName&&t.push(` ${q.dim("Branch:")} ${e.branchName}`),e.commitSha&&t.push(` ${q.dim("Commit:")} ${e.commitSha.slice(0,7)}`),e.startedAt&&t.push(` ${q.dim("Started:")} ${Rc(e.startedAt)}`),null!==e.durationMs&&t.push(` ${q.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(` ${q.dim("Source:")} ${e.source.toLowerCase()}`),e.projectId){const n=`https://app.stably.ai/project/${e.projectId}/playwright/history/${e.runId}`;t.push(` ${q.dim("URL:")} ${q.cyan(q.underline(n))}`)}t.push("");const n=[];e.passedCount>0&&n.push(q.green(`${e.passedCount} passed`)),e.failedCount>0&&n.push(q.red(`${e.failedCount} failed`)),e.flakyCount>0&&n.push(q.yellow(`${e.flakyCount} flaky`)),e.timedoutCount>0&&n.push(q.red(`${e.timedoutCount} timedout`)),e.skippedCount>0&&n.push(q.dim(`${e.skippedCount} skipped`)),e.interruptedCount>0&&n.push(q.yellow(`${e.interruptedCount} interrupted`)),t.push(`${q.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(q.bold("Failed/Flaky Tests:"));for(const e of r){const n=e.status??"UNKNOWN",r=Cc[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}${q.dim(c)}`);const u=i?.at(-1);if(u?.errorMessage){const e=u.errorMessage.split("\n")[0]?.slice(0,100)??"";t.push(` ${q.dim(e)}`)}}}return t.push(""),t.join("\n")})(e))}}),cl.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)}),Tc.forEach(({args:e,description:t,name:n})=>{cl.command(n).description(t).helpOption(!1).helpCommand(!1).allowUnknownOption(!0).allowExcessArguments(!0).passThroughOptions().action(()=>Sc({overrideArgs:e,subcommand:n}))});var ml=()=>{0!==ll.length&&(process.stderr.write(ll.join("")),ll=[])};(async()=>{await(async()=>{if(!rl&&"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":ir,"node.version":process.version,"os.platform":process.platform}}),rl=!0}catch{}})();try{await cl.parseAsync(process.argv),rs.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 rs.error(t,{stack:e instanceof Error?e.stack:void 0}),ml(),rs.flush(),rs.printLogFileInfo(),await sl(),void(process.exitCode=1)}const t="number"==typeof e.exitCode?e.exitCode:1,n=process.argv.slice(2).find(e=>!e.startsWith("-")),r=!!n&&!!dl(cl,[n]);if(("commander.excessArguments"===e.code||"commander.unknownCommand"===e.code)&&n&&!r)return ll=[],rs.warn("Unknown command",{command:n}),process.stderr.write(`command '${n}' not found\n`),pl(),void(process.exitCode=t);rs.debug("Commander error",{code:e.code,exitCode:t}),ml(),process.exitCode=t}finally{rs.flush(),await sl()}})();
|