stably 4.10.3 → 4.10.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 m}from"child_process";import g from"process";import*as y from"fs";import b,{existsSync as v,statSync as w,realpathSync as _,createReadStream as I,readFileSync as E,mkdirSync as T,writeFileSync as S,appendFileSync as x,openSync as A,readSync as C,closeSync as R,rmSync as P}from"fs";import{fileURLToPath as k,URL as U}from"url";import L,{tmpdir as D,constants as O}from"os";import"timers/promises";import $ from"stream";import{debuglog as N,promisify as B,TextDecoder as j,TextEncoder as M}from"util";import{createSdkMcpServer as H,tool as F,query as G}from"@anthropic-ai/claude-agent-sdk";import{match as W}from"ts-pattern";import Y from"net";import{createInterface as V}from"readline/promises";import z from"picocolors";import{simpleGit as K}from"simple-git";import q,{randomUUID as J}from"crypto";import{readFile as Q,mkdir as X,writeFile as Z,unlink as ee,access as te,readdir as ne,stat as re,rm as se,appendFile as oe}from"fs/promises";import{log as ie,outro as ae,spinner as ce,intro as le,select as ue,isCancel as de}from"@clack/prompts";import pe,{z as fe}from"zod";import he from"open";import me from"http";import ge from"pino";import ye from"sonic-boom";import{z as be}from"zod/v3";import ve from"ws";import{useState as we,useRef as _e,useEffect as Ie,useCallback as Ee,useMemo as Te}from"react";import{jsx as Se,jsxs as xe}from"react/jsx-runtime";import{createRequire as Ae}from"module";import{parseDocument as Ce}from"yaml";import{startTunnel as Re}from"@stablyhq/runner-sdk";var Pe={cwdChanged:!1,newCwd:void 0,envFilesLoaded:[],envFileErrors:[],remoteEnvName:void 0},ke=process.argv.findIndex(e=>"-C"===e||"--cwd"===e);if(-1!==ke&&process.argv[ke+1]){const e=process.argv[ke+1];process.chdir(e),Pe.cwdChanged=!0,Pe.newCwd=e,process.argv.splice(ke,2)}for(var Ue=[],Le=0;Le<process.argv.length;)if("--env-file"===process.argv[Le]){const e=process.argv[Le+1];e&&!e.startsWith("-")?(Ue.push(e),process.argv.splice(Le,2)):Le++}else Le++;var De=process.argv.findIndex(e=>"--env"===e);-1!==De&&process.argv[De+1]&&!process.argv[De+1].startsWith("-")&&(Pe.remoteEnvName=process.argv[De+1],process.argv.splice(De,2));for(const t of Ue){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})`;Pe.envFileErrors.push(e),process.stderr.write(`${e}\n`)}else Pe.envFilesLoaded.push(n)}var Oe={detect:({env:e})=>Boolean(e.APPVEYOR),configuration({env:e}){const t=e.APPVEYOR_PULL_REQUEST_NUMBER,n=Boolean(t);return{name:"Appveyor",service:"appveyor",commit:e.APPVEYOR_REPO_COMMIT,tag:e.APPVEYOR_REPO_TAG_NAME,build:e.APPVEYOR_BUILD_NUMBER,buildUrl:`https://ci.appveyor.com/project/${e.APPVEYOR_PROJECT_SLUG}/build/${e.APPVEYOR_BUILD_VERSION}`,branch:e.APPVEYOR_REPO_BRANCH,job:e.APPVEYOR_JOB_NUMBER,jobUrl:`https://ci.appveyor.com/project/${e.APPVEYOR_PROJECT_SLUG}/build/job/${e.APPVEYOR_JOB_ID}`,pr:t,isPr:n,prBranch:e.APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH,slug:e.APPVEYOR_REPO_NAME,root:e.APPVEYOR_BUILD_FOLDER}}};function $e(e){return(/\d+(?!.*\d+)/.exec(e)||[])[0]}function Ne(e){return e?/^(?:refs\/heads\/)?(?<branch>.+)$/i.exec(e)[1]:void 0}var Be={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:Ne(n?e.SYSTEM_PULLREQUEST_TARGETBRANCH:e.BUILD_SOURCEBRANCH),pr:t,isPr:n,prBranch:Ne(n?e.SYSTEM_PULLREQUEST_SOURCEBRANCH:void 0),root:e.BUILD_REPOSITORY_LOCALPATH}}},je={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})},Me={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})},He={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}}},Fe={detect:({env:e})=>Boolean(e.BUDDY_WORKSPACE_ID),configuration({env:e}){const t=$e(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}}},Ge="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function We(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ye,Ve,ze,Ke,qe,Je,Qe,Xe,Ze={exports:{}};var et,tt,nt,rt,st,ot,it,at,ct,lt,ut,dt,pt,ft,ht,mt={exports:{}},gt={};function yt(){if(dt)return ut;dt=1;const e=r,t=function(){if(nt)return tt;nt=1;const e=r,t=function(){if(Xe)return Qe;Xe=1;const e="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,t=r,n=e?";":":",s=function(){if(Je)return qe;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 Je=1,e="win32"===process.platform||Ge.TESTING_WINDOWS?function(){if(Ve)return Ye;Ve=1,Ye=n,n.sync=function(n,r){return t(e.statSync(n),n,r)};var e=b;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 Ye}():function(){if(Ke)return ze;Ke=1,ze=t,t.sync=function(t,r){return n(e.statSync(t),r)};var e=b;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 ze}(),qe=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}},qe}(),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 Qe=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)},Qe}(),n=function(){if(et)return mt.exports;et=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 mt.exports=e,mt.exports.default=e,mt.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 tt=function(e){return s(e)||s(e,!0)}}(),n=function(){if(rt)return gt;rt=1;const e=/([()\][%!^"`<>&|;, *?])/g;return gt.command=function(t){return t.replace(e,"^$1")},gt.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},gt}(),s=function(){if(lt)return ct;lt=1;const e=b,t=function(){if(at)return it;at=1;const e=ot?st:(ot=1,st=/^#!(.*)/);return it=(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 ct=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 ut=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 bt=We(function(){if(ht)return Ze.exports;ht=1;const e=p,t=yt(),n=function(){if(ft)return pt;ft=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 pt={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},pt}();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 Ze.exports=r,Ze.exports.spawn=r,Ze.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},Ze.exports._parse=t,Ze.exports._enoent=n,Ze.exports}());function vt(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 wt=(e,t)=>({name:`SIGRT${t+1}`,number:_t+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),_t=34,It=[{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"}],Et=()=>{const e=(()=>{const e=64-_t+1;return Array.from({length:e},wt)})();return[...It,...e].map(Tt)},Tt=({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}},St=({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}],xt=(()=>{const e=Et();return Object.fromEntries(e.map(St))})();(()=>{const e=Et(),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 At=({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=g.cwd()}}})=>{o=null===o?void 0:o;const f=void 0===(s=null===s?void 0:s)?void 0:xt[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}),m=`Command ${h}: ${i}`,y="[object Error]"===Object.prototype.toString.call(r),b=y?`${m}\n${r.message}`:m,v=[b,t,e].filter(Boolean).join("\n");return y?(r.originalMessage=r.message,r.message=v):r=new Error(v),r.shortMessage=b,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},Ct=["stdin","stdout","stderr"],Rt=[];Rt.push("SIGHUP","SIGINT","SIGTERM"),"win32"!==process.platform&&Rt.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),"linux"===process.platform&&Rt.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var Pt,kt,Ut=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,Lt=Symbol.for("signal-exit emitter"),Dt=globalThis,Ot=Object.defineProperty.bind(Object),$t=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(Dt[Lt])return Dt[Lt];Ot(Dt,Lt,{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}},Nt=class{},Bt=globalThis.process;Ut(Bt)?new class extends Nt{#e="win32"===Bt.platform?"SIGINT":"SIGHUP";#t=new $t;#n;#r;#s;#o={};#i=!1;constructor(e){super(),this.#n=e,this.#o={};for(const t of Rt)this.#o[t]=()=>{const n=this.#n.listeners(t);let{count:r}=this.#t;const s=e;if("object"==typeof s.__signal_exit_emitter__&&"number"==typeof s.__signal_exit_emitter__.count&&(r+=s.__signal_exit_emitter__.count),n.length===r){this.unload();const n=this.#t.emit("exit",null,t),r="SIGHUP"===t?this.#e:t;n||e.kill(e.pid,r)}};this.#s=e.reallyExit,this.#r=e.emit}onExit(e,t){if(!Ut(this.#n))return()=>{};!1===this.#i&&this.load();const n=t?.alwaysLast?"afterExit":"exit";return this.#t.on(n,e),()=>{this.#t.removeListener(n,e),0===this.#t.listeners.exit.length&&0===this.#t.listeners.afterExit.length&&this.unload()}}load(){if(!this.#i){this.#i=!0,this.#t.count+=1;for(const e of Rt)try{const t=this.#o[e];t&&this.#n.on(e,t)}catch(e){}this.#n.emit=(e,...t)=>this.#a(e,...t),this.#n.reallyExit=e=>this.#c(e)}}unload(){this.#i&&(this.#i=!1,Rt.forEach(e=>{const t=this.#o[e];if(!t)throw new Error("Listener not defined for signal: "+e);try{this.#n.removeListener(e,t)}catch(e){}}),this.#n.emit=this.#r,this.#n.reallyExit=this.#s,this.#t.count-=1)}#c(e){return Ut(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&&Ut(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)}}(Bt):new class extends Nt{onExit(){return()=>{}}load(){}unload(){}},new TextEncoder,function(){if(kt)return Pt;kt=1;const{PassThrough:e}=$;Pt=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 jt=(async()=>{})().constructor.prototype;["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(jt,e)]);var Mt=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],Ht=/^[\w.-]+$/,Ft=N("execa").enabled,Gt=(e,t)=>String(e).padStart(t,"0"),Wt=(e,t,n={})=>{const s=bt._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||g.cwd(),execPath:g.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:Ft,...n}).env=(({env:e,extendEnv:t,preferLocal:n,localDir:s,execPath:o})=>{const i=t?{...g.env,...e}:e;return n?(({env:e=g.env,...t}={})=>{const n=vt({env:e={...e}});return t.path=e[n],e[n]=(({cwd:e=g.cwd(),path:t=g.env[vt()],preferLocal:n=!0,execPath:s=g.execPath,addExecPath:o=!0}={})=>{const i=e instanceof URL?k(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?k(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 Ct.map(t=>e[t]);if((e=>Ct.some(t=>void 0!==e[t]))(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${Ct.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,Ct.length);return Array.from({length:n},(e,n)=>t[n])})(n),"win32"===g.platform&&"cmd"===r.basename(e,".exe")&&t.unshift("/q"),{file:e,args:t,options:n,parsed:s}},Yt=(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 Vt(e,t,n){const r=Wt(e,t,n),s=((e,t)=>Mt(e,t).join(" "))(e,t),o=((e,t)=>Mt(e,t).map(e=>(e=>"string"!=typeof e||Ht.test(e)?e:`"${e.replaceAll('"','\\"')}"`)(e)).join(" "))(e,t);((e,{verbose:t})=>{t&&g.stderr.write(`[${(()=>{const e=new Date;return`${Gt(e.getHours(),2)}:${Gt(e.getMinutes(),2)}:${Gt(e.getSeconds(),2)}.${Gt(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),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 At({error:e,stdout:"",stderr:"",all:"",command:s,escapedCommand:o,parsed:r,timedOut:!1,isCanceled:!1,killed:!1})}const c=Yt(r.options,a.stdout,a.error),l=Yt(r.options,a.stderr,a.error);if(a.error||0!==a.status||null!==a.signal){const e=At({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 zt(e){try{return Vt("git",["rev-parse","HEAD"],e).stdout}catch{return}}function Kt(e){try{const t=Vt("git",["rev-parse","--abbrev-ref","HEAD"],e).stdout;if("HEAD"===t){const t=Vt("git",["show","-s","--pretty=%d","HEAD"],e).stdout.replace(/^\(|\)$/g,"").split(", ").find(e=>e.startsWith("origin/"));return t?t.match(/^origin\/(?<branch>.+)/)[1]:void 0}return t}catch{return}}var qt=/^(?:.*)@(?:.*):(?:\d+\/)?(.*)\.git$/,Jt=/^\/(.*)\.git$/;function Qt(e){if(e){if(e.match(qt))return e.replace(qt,"$1");try{return new URL(e).pathname.replace(Jt,"$1")}catch{return}}}var Xt,Zt={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:Qt(e.BUILDKITE_REPO),pr:t,isPr:n,prBranch:n?e.BUILDKITE_BRANCH:void 0,root:e.BUILDKITE_BUILD_CHECKOUT_PATH}}},en={detect:({env:e})=>Boolean(e.CIRCLECI),configuration({env:e}){const t=e.CIRCLE_PR_NUMBER||$e(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}`}}},tn="https://cirrus-ci.com",nn={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:`${tn}/build/${e.CIRRUS_BUILD_ID}`,job:e.CIRRUS_TASK_ID,jobUrl:`${tn}/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}}},rn={detect:({env:e})=>Boolean(e.CODEBUILD_BUILD_ID),configuration:({env:e,cwd:t})=>({name:"AWS CodeBuild",service:"codebuild",commit:zt({env:e,cwd:t}),build:e.CODEBUILD_BUILD_ID,branch:Kt({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})},sn={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}}},on={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}}},an=({env:e})=>{try{const t=e.GITHUB_EVENT_PATH?JSON.parse(E(e.GITHUB_EVENT_PATH,"utf-8")):void 0;if(t&&t.pull_request)return{branch:t.pull_request.base?Ne(t.pull_request.base.ref):void 0,pr:t.pull_request.number}}catch{}return{pr:void 0,branch:void 0}},cn={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=Ne("pull_request_target"===e.GITHUB_EVENT_NAME?`refs/pull/${(e=>{const t=e.GITHUB_EVENT_PATH?JSON.parse(E(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?an({env:e}):void 0}}},ln={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}}},un={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||zt({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}}},dn={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}}},pn={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})},fn={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}}},hn={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}}},mn={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}}},gn={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||zt({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}}},yn={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}}},bn={};function vn(){if(Xt)return bn;Xt=1,Object.defineProperty(bn,"__esModule",{value:!0}),bn.of=bn.PropertiesFile=void 0;var e,t=(e=b)&&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 bn.PropertiesFile=n,bn.of=function(...e){let t=new n;return t.of.apply(t,e),t},bn}var wn=We(vn()),_n={root:"teamcity.build.workingDir",branch:"teamcity.build.branch"},In=e=>{try{return wn.of(e)}catch{return}},En=({env:e,cwd:t})=>{const n=e.TEAMCITY_BUILD_PROPERTIES_FILE?In(e.TEAMCITY_BUILD_PROPERTIES_FILE):void 0,r=n?n.get("teamcity.configuration.properties.file"):void 0,s=r?In(r):r;return Object.fromEntries(Object.keys(_n).map(r=>[r,(n?n.get(_n[r]):void 0)||(s?s.get(_n[r]):void 0)||("branch"===r?Kt({env:e,cwd:t}):void 0)]))},Tn={appveyor:Oe,azurePipelines:Be,bamboo:je,bitbucket:Me,bitrise:He,buddy:Fe,buildkite:Zt,circleci:en,cirrus:nn,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:rn,codefresh:sn,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:on,github:cn,gitlab:ln,jenkins:un,netlify:dn,puppet:pn,sail:fn,screwdriver:hn,scrutinizer:mn,semaphore:gn,shippable:yn,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,...En({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:Ne(e.JB_SPACE_GIT_BRANCH),slug:t&&n?`${t.toLowerCase()}/${n}`:void 0}}}},Sn=class e{git;config;snapshotTreeHash;snapshotIndexPath;constructor(e){this.config=e,this.git=K({baseDir:e.workingDir,maxConcurrentProcesses:1})}static createLocal({workingDir:t}){return new e({mode:"local",workingDir:t})}static createCloud({workingDir:t,baseBranch:n}){return new e({mode:"cloud",workingDir:t,baseBranch:n})}async captureSnapshot(){if("local"!==this.config.mode)return;this.snapshotIndexPath=i(D(),`git-diff-tracker-${J()}.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(D(),`git-diff-tracker-${J()}.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 xn(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 xn(this.snapshotIndexPath),this.snapshotIndexPath=void 0),this.snapshotTreeHash=void 0}};async function xn(e){try{await ee(e)}catch{}}var An="x-stably-org-id",Cn={bodySerializer:e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t)},Rn=({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):Pn({allowReserved:e,name:n,value:t})).join(o);return"label"===r||"matrix"===r?o+i:i},Pn=({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)}`},kn=({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])=>Pn({allowReserved:e,name:"deepObject"===r?`${n}[${t}]`:t,value:s})).join(i);return"label"===r||"matrix"===r?i+a:a},Un=/\{[^{}]+\}/g;function Ln(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 Dn,On=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},$n=({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=Rn({allowReserved:i.allowReserved,explode:!0,name:s,style:"form",value:o,...i.array});e&&r.push(e)}else if("object"==typeof o){const e=kn({allowReserved:i.allowReserved,explode:!0,name:s,style:"deepObject",value:o,...i.object});e&&r.push(e)}else{const e=Pn({allowReserved:i.allowReserved,name:s,value:o});e&&r.push(e)}}return r.join("&")},Nn=(e,t)=>!!t&&!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`)),Bn=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(Un);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,Rn({explode:r,name:s,style:o,value:i}));continue}if("object"==typeof i){n=n.replace(t,kn({explode:r,name:s,style:o,value:i,valueOnly:!0}));continue}if("matrix"===o){n=n.replace(t,`;${Pn({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:$n(e.querySerializer),url:e.url}),jn=(e,t)=>{const n={...e,...t};return n.baseUrl?.endsWith("/")&&(n.baseUrl=n.baseUrl.substring(0,n.baseUrl.length-1)),n.headers=Hn(e.headers,t.headers),n},Mn=e=>{const t=[];return e.forEach((e,n)=>{t.push([n,e])}),t},Hn=(...e)=>{const t=new Headers;for(const n of e){if(!n)continue;const e=n instanceof Headers?Mn(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},Fn=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}},Gn=$n({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Wn={"Content-Type":"application/json"},Yn=(e={})=>({...Cn,headers:Wn,parseAs:"auto",querySerializer:Gn,...e}),Vn=(e={})=>{let t=jn(Yn(),e);const n=()=>({...t}),r={error:new Fn,request:new Fn,response:new Fn},s=async e=>{const n={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:Hn(t.headers,e.headers),serializedBody:void 0};return n.security&&await(async({security:e,...t})=>{for(const n of e){if(Nn(t,n.name))continue;const e=await On(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:Bn(n)}},o=async e=>{const{opts:t,url:n}=await s(e),o={redirect:"follow",...t,body:Ln(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 m="";const g=()=>{try{f.cancel()}catch{}};h.addEventListener("abort",g);try{for(;;){const{done:e,value:t}=await f.read();if(e)break;m+=t;const o=m.split("\n\n");m=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",g),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:Bn,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=jn(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")}},zn=Vn(Yn({baseUrl:"https://api.stably.ai"})),Kn=e=>(e.client??zn).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs",...e}),qn=e=>(e.client??zn).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}",...e}),Jn="4.10.3",Qn=process.env.STABLY_API_URL||"https://api.stably.ai",Xn=e=>{const t=new URL(e);return t.protocol="http:"===t.protocol?"ws:":"wss:",t},Zn=process.env.AUTH_URL||"https://auth.stably.ai",er=process.env.AUTH_CLIENT_ID||"288007877071cce81f269428ea78653a",tr=process.env.AI_PROXY_URL||"https://ai-proxy.stably.ai",nr=process.env.STABLY_AUTOHEAL_WS_URL||new URL("/autoheal",Xn(Qn)).toString(),rr=process.env.STABLY_CREATE_PROGRESS_WS_URL||new URL("/create-progress",Xn(Qn)).toString(),sr="http://localhost:9876/auth/callback",or=()=>Dn||(Dn=Vn(Yn({baseUrl:Qn,headers:{"X-STABLY-CLI-VERSION":Jn,"X-STABLY-SOURCE":"cli"}}))),ir=async(e,t)=>{const n=await(r={body:{accessToken:e,orgId:t},client:or()},(r.client??zn).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},ar=fe.object({org_id:fe.string(),org_name:fe.string()}),cr=fe.object({email:fe.string(),org_id_to_org_member_info:fe.record(fe.string(),ar).optional(),org_member_info:ar.optional(),user_id:fe.string()});fe.object({email:fe.string(),firstName:fe.string().optional(),lastName:fe.string().optional(),organizations:fe.array(fe.object({id:fe.string(),name:fe.string()})),userId:fe.string()});var lr,ur=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)},dr=e=>{try{const t=cr.parse(ur(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"}`)}},pr=async(e,t)=>{let n=e;const{root:s}=r.parse(n);for(;n!==s;){const e=r.join(n,t);try{return await te(e),e}catch{n=r.dirname(n)}}},fr=r.join(L.homedir(),".stably"),hr=r.join(fr,"auth.json"),mr=".stably",gr="project.json",yr=pe.object({accessToken:pe.string(),expiresAt:pe.number(),idToken:pe.string().optional(),refreshToken:pe.string()}),br=pe.object({orgId:pe.string(),orgName:pe.string(),projectId:pe.string(),projectName:pe.string()}),vr=async()=>{try{const e=await Q(hr,"utf-8");return yr.parse(JSON.parse(e))}catch{return}},wr=async e=>{await X(fr,{recursive:!0}),await Z(hr,JSON.stringify(e,null,2),{mode:384})},_r=async()=>{try{await ee(hr)}catch{}},Ir=async()=>{try{const e=await pr(process.cwd(),mr);if(!e)return;const t=r.join(e,gr),n=await Q(t,"utf-8");return br.parse(JSON.parse(n))}catch{return}},Er=async()=>{try{const e=await pr(process.cwd(),mr);e&&await ee(r.join(e,gr))}catch{}},Tr=e=>Date.now()>=e.expiresAt-3e5,Sr=async e=>{const t=new URLSearchParams({client_id:er,grant_type:"refresh_token",refresh_token:e}),n=await fetch(`${Zn}/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}},xr=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`,Ar=(e,t,n)=>{e.writeHead(t,{"Content-Type":"text/html"}),e.end(n)},Cr=(e,t)=>{const n=new URLSearchParams({client_id:er,code_challenge:e,code_challenge_method:"S256",redirect_uri:sr,response_type:"code",state:t});return`${Zn}/propelauth/oauth/authorize?${n.toString()}`},Rr=async e=>{const t=ce();let n;t.start("Loading user info...");try{n=dr(e.accessToken),t.stop(z.green(`✓ Logged in as ${z.cyan(n.email)}`))}catch(e){t.stop(z.red("✗ Failed to load user info"));const n=e instanceof Error?e.message:"Unknown error";return ie.error(n),{success:!1}}const s=await(async e=>{if(0===e.length)return void ie.error("You don't belong to any organizations.");if(1===e.length)return ie.info(`Using organization: ${z.cyan(e[0].name)}`),e[0];if(!process.stdin.isTTY)return ie.info(`Auto-selecting organization: ${z.cyan(e[0].name)}`),e[0];const t=await ue({message:"Select an organization",options:[...e].sort((e,t)=>e.name.localeCompare(t.name)).map(e=>({label:e.name,value:e.id}))});return de(t)?void 0:e.find(e=>e.id===t)})(n.organizations);if(!s)return ie.warn("Organization selection cancelled."),{success:!1};let o;t.start("Getting org credentials...");try{const n=await ir(e.accessToken,s.id);o={accessToken:n.accessToken,expiresAt:Date.now()+1e3*n.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken},t.stop(z.green("✓ Credentials obtained"))}catch(e){t.stop(z.red("✗ Failed to get org credentials"));const n=e instanceof Error?e.message:"Unknown error";return ie.error(n),{success:!1}}const i=await(async(e,t)=>{const n=ce();let r;n.start("Loading projects...");try{r=await(async({accessToken:e,orgId:t})=>{const n=await(r={auth:e,client:or(),path:{orgId:t}},(r.client??zn).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(z.green("✓ Projects loaded"))}catch(e){n.stop(z.red("✗ Failed to load projects"));const t=e instanceof Error?e.message:"Unknown error";return void ie.error(t)}if(0===r.length)return ie.error("No projects found in this organization."),void ie.info(`Create a project at ${z.underline(z.cyan("https://app.stably.ai"))}`);if(1===r.length)return ie.info(`Using project: ${z.cyan(r[0].name)}`),r[0];if(!process.stdin.isTTY)return ie.info(`Auto-selecting project: ${z.cyan(r[0].name)}`),r[0];const s=await ue({message:"Select a project",options:r.map(e=>({label:e.name,value:e.id}))});return de(s)?void 0:r.find(e=>e.id===s)})(o.accessToken,s.id);return i?(await(async e=>{const t=r.join(process.cwd(),mr),n=r.join(t,gr);await X(t,{recursive:!0}),await Z(n,JSON.stringify(e,null,2)),await(async e=>{const t=r.join(e,".gitignore"),n="# Stably CLI (only docs/ are tracked)\n.stably/*\n!.stably/docs/";try{const e=await Q(t,"utf-8"),r=e.split("\n").map(e=>e.trim());if(r.includes(".stably/*")&&r.includes("!.stably/docs/"))return;const s=/^# Stably CLI\n\.stably\/?$/m,o=/^\.stably\/?$/m;if(s.test(e)){const r=e.replace(s,`\n${n}\n`);await Z(t,r)}else if(o.test(e)){const r=e.replace(o,`\n${n}\n`);await Z(t,r)}else await oe(t,`\n${n}\n`)}catch{await Z(t,`${n}\n`)}})(process.cwd())})({orgId:s.id,orgName:s.name,projectId:i.id,projectName:i.name}),ie.info(z.dim("Linked this directory to your Stably project.")),{scopedTokens:o,success:!0}):(ie.warn("Project selection cancelled."),{success:!1})},Pr=async()=>{if(qr())return ie.warn(`Environment variables ${z.cyan("STABLY_API_KEY")} and ${z.cyan("STABLY_PROJECT_ID")} are set.`),ie.warn("These will be used for authentication instead of OAuth login."),ie.warn("To use OAuth login, unset these environment variables first."),void ae(z.yellow("Login skipped - using environment variable authentication."));const e=await vr();if(e){if(!Tr(e)){if(await Ir())return void ae(z.yellow("You are already logged in. Run `stably logout` first to log out."));ie.info("You are logged in but haven't selected a project yet.");const t=await Rr(e);return void(t.success?(await wr(t.scopedTokens),ae(z.green("Setup complete! You can now use Stably CLI."))):ae(z.yellow("Setup incomplete. Run `stably login` to try again.")))}const t=ce();t.start("Refreshing session...");try{const n=await Sr(e.refreshToken);t.stop(z.green("✓ Session refreshed"));const r=await Ir();if(r){t.start("Getting org credentials...");try{const e=await ir(n.accessToken,r.orgId),s={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:n.idToken,refreshToken:n.refreshToken};await wr(s),t.stop(z.green("✓ Credentials obtained")),ae(z.green("Login successful"))}catch{await wr(n),t.stop(z.yellow("Using full credentials")),ae(z.green("Login successful"))}}else{const e=await Rr(n);e.success?(await wr(e.scopedTokens),ae(z.green("Setup complete! You can now use Stably CLI."))):ae(z.yellow("Setup incomplete. Run `stably login` to try again."))}return}catch{t.stop(z.yellow("Session expired, proceeding with fresh login...")),await _r(),await Er()}}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:Cr(t,r),codeVerifier:e,state:r}})(),{ready:r,result:s}=(e=>{let t,n;return{ready:new Promise((e,r)=>{t=e,n=r}),result:new Promise((r,s)=>{const o=setTimeout(()=>{a.close(),r({error:"Login timed out",success:!1})},3e5),i=()=>{clearTimeout(o)},a=me.createServer((t,n)=>{const s=new U(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?(Ar(n,400,xr(l)),i(),a.close(),void r({error:l,success:!1})):o&&c?c!==e?(Ar(n,400,xr("Invalid state parameter (possible CSRF attack)")),i(),a.close(),void r({error:"State mismatch",success:!1})):(Ar(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})):(Ar(n,400,xr("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:er,code:e,code_verifier:t,grant_type:"authorization_code",redirect_uri:sr}),r=await fetch(`${Zn}/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,ie.info("Opening browser for authentication..."),ie.info(z.dim("If browser doesn't open, visit:")),ie.info(`]8;;${t}${z.underline(z.cyan(t))}]8;;`);try{await he(t)}catch{ie.warn("Could not open browser automatically. Please open the URL above manually.")}const s=ce();let o;s.start("Waiting for authentication...");try{o=await r(),s.stop(z.green("✓ Authentication successful"))}catch(e){s.stop(z.red("✗ Authentication failed"));const t=e instanceof Error?e.message:"Unknown error";ae(z.red(`Login failed: ${t}`)),process.exit(1)}const i=await Rr(o);i.success?(await wr(i.scopedTokens),ae(z.green("Setup complete! You can now use Stably CLI."))):(ae(z.yellow("Setup incomplete. Run `stably login` to try again.")),process.exit(1))},kr={fatal:60,error:50,warn:40,info:30,debug:20,trace:10},Ur=new Set(["help","login","logout","whoami","tunnel","create","fix","init","upgrade","test","show-report","codegen"]),Lr=(new Date).toISOString().split("T")[0],Dr=(()=>{const e=[r.join(L.tmpdir(),"stably-logs",Lr),r.join(L.homedir(),".stably","logs",Lr)];for(const t of e)try{return b.mkdirSync(t,{recursive:!0}),t}catch{}return null})(),Or=process.argv.includes("--verbose")||process.argv.includes("-v"),$r=process.env.STABLY_LOG_LEVEL?.toLowerCase(),Nr=Or?"debug":void 0!==(lr=$r)&&lr in kr?$r:"warn",Br=kr[Nr],jr=null,Mr=null,Hr=null,Fr=[],Gr=!1,Wr=e=>{if(!Gr){if(!(jr=(e=>{if(!Dr)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(Dr,`${t}-${n}.log`)})(e)))return Fr=[],void(Gr=!0);(e=>{const t=["","=".repeat(60),"Stably CLI Debug Log",`Version: ${Jn}`,`Generated: ${(new Date).toISOString()}`,`Node: ${process.version}`,`Platform: ${process.platform} ${L.release()}`,`CWD: ${process.cwd()}`,`Args: ${process.argv.slice(2).join(" ")}`,`Log Level (console): ${Nr}`,"=".repeat(60),""].join("\n");e.write(t)})(Mr=new ye({dest:jr,minLength:4096,sync:!1,append:!0})),Hr=ge({level:"debug",timestamp:ge.stdTimeFunctions.isoTime,base:{version:Jn}},Mr);for(const{level:e,msg:t,context:n}of Fr)n?Hr[e](n,t):Hr[e](t);Fr=[],Gr=!0,Or&&process.stderr.write(`${z.dim(`Debug log: ${jr}`)}\n\n`)}},Yr=(()=>{const e=process.argv.slice(2).find(e=>!e.startsWith("-"));return e&&Ur.has(e)?e:null})();Yr&&Wr(Yr);var Vr=e=>(t,n)=>{if(Hr?n?Hr[e](n,t):Hr[e](t):Gr||Fr.push({level:e,msg:t,context:n}),(e=>kr[e]>=Br)(e)){const n=((e,t)=>`${{fatal:z.bgRed(z.white(" FATAL ")),error:z.red("error"),warn:z.yellow("warn"),info:z.cyan("info"),debug:z.dim("debug"),trace:z.dim("trace")}[e]} ${t}`)(e,t);process.stderr.write(`${n}\n`)}},zr={fatal:Vr("fatal"),error:Vr("error"),warn:Vr("warn"),info:Vr("info"),debug:Vr("debug"),trace:Vr("trace"),initSession:e=>{Gr||Wr(e)},getLogFilePath:()=>jr,flush:()=>{if(Mr)try{Mr.flushSync()}catch{}},printLogFileInfo:()=>{jr&&(process.stderr.write(`\n${z.dim("Debug log written to:")}\n`),process.stderr.write(` ${z.cyan(jr)}\n`),process.stderr.write(`${z.dim("Share this file with support for assistance.")}\n`))},getPinoLogger:()=>Hr};setInterval(()=>{zr.flush()},3e4).unref(),process.on("beforeExit",()=>{zr.flush()});var Kr=e=>{const t=()=>{zr.flush(),Or&&zr.printLogFileInfo(),process.removeListener(e,t),process.kill(process.pid,e)};return t};process.on("SIGINT",Kr("SIGINT")),process.on("SIGTERM",Kr("SIGTERM"));var qr=()=>{const e=process.env.STABLY_API_KEY?.trim(),t=process.env.STABLY_PROJECT_ID?.trim();if(e&&t)return zr.debug("Environment auth detected",{hasApiKey:!0,hasProjectId:!0}),{apiKey:e,projectId:t};zr.debug("Environment auth not set",{hasApiKey:!!e,hasProjectId:!!t})},Jr=async()=>{zr.debug("Checking for stored auth tokens");const e=await vr();if(!e)return void zr.debug("No stored auth tokens found");const t=Tr(e);if(zr.debug("Auth tokens status",{expired:t}),!t){const t=await Ir(),n=(e=>{try{const t=cr.parse(ur(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(zr.debug("Token scope check",{scope:n,hasContext:!!t}),t&&"full"===n)try{zr.debug("Exchanging full token for org-scoped token",{orgId:t.orgId});const n=await ir(e.accessToken,t.orgId),r={accessToken:n.accessToken,expiresAt:Date.now()+1e3*n.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken};return await wr(r),zr.debug("Token exchange successful"),r}catch(t){return zr.debug("Token exchange failed, using existing token",{error:t instanceof Error?t.message:String(t)}),e}return e}try{zr.debug("Attempting token refresh");const t=await Sr(e.refreshToken);zr.debug("Token refresh successful");const n=await Ir();if(n)try{zr.debug("Exchanging refreshed token for org-scoped token");const e=await ir(t.accessToken,n.orgId),r={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:t.idToken,refreshToken:t.refreshToken};return await wr(r),r}catch{return await wr(t),t}return await wr(t),t}catch(e){return void zr.warn("Token refresh failed",{error:e instanceof Error?e.message:String(e)})}},Qr=async(e={})=>{zr.debug("Requiring authentication",{autoLogin:e.autoLogin});const t=qr();if(t)return zr.info("Using environment variable authentication"),{auth:t,type:"env"};let n=await Jr(),r=n?await Ir():void 0;const s=process.stdin.isTTY&&process.stdout.isTTY;if(zr.debug("OAuth auth check",{hasTokens:!!n,hasContext:!!r,canPrompt:s}),(!n||!r)&&e.autoLogin&&s){zr.info("Prompting user to login"),n?ie.info("You are logged in but need to select an organization and project."):ie.info("You are not logged in."),ie.info("Press Enter to log in."),process.stdout.write(`${z.dim("Alternatively, set environment variables for an org API key:")}\n${z.dim(" STABLY_API_KEY=... STABLY_PROJECT_ID=... stably")}\n`),process.stdout.write("\n");const e=V({input:process.stdin,output:process.stdout});try{await e.question(z.dim("Press Enter to continue... "))}finally{e.close()}await Pr(),n=await Jr(),r=n?await Ir():void 0}return n||(zr.warn("Authentication required but no tokens available"),ae(z.red("You are not logged in. Run `stably login` to authenticate.")),process.exit(1)),r||(zr.warn("Authentication succeeded but no project context selected"),ae(z.red("You haven't selected an organization and project. Run `stably login` to complete setup.")),process.exit(1)),zr.info("OAuth authentication successful",{orgId:r.orgId,projectId:r.projectId}),{auth:{accessToken:n.accessToken,context:r},type:"oauth"}},Xr=e=>"env"===e.type?e.auth.projectId:e.auth.context.projectId,Zr=e=>"env"===e.type?e.auth.apiKey:e.auth.accessToken,es=e=>e?{...process.env,...e}:process.env,ts=async()=>{zr.info("[test] Resolving Stably test env");const e=(()=>{if(process.env.STABLY_WS_URL)return;if("https://api.stably.ai"===Qn)return;const e=Qn.startsWith("http://")?"ws://":"wss://";return`${Qn.replace(/^https?:\/\//,e).replace(/\/$/,"")}/reporter`})();zr.debug("[test] WebSocket URL resolved",{wsUrl:e??"(default)"});const t=qr();if(t)return zr.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}};zr.info("[test] No env var auth, attempting OAuth auth");const n=Date.now(),r=await(async()=>{const e=qr();if(e)return{auth:e,type:"env"};const t=await Jr(),n=t?await Ir():void 0;return t&&n?{auth:{accessToken:t.accessToken,context:n},type:"oauth"}:void 0})();if(zr.info("[test] OAuth auth resolved",{durationMs:Date.now()-n,hasAuth:!!r,authType:r?.type}),!r||"env"===r.type)return void zr.info("[test] No usable auth found");const s=process.env.STABLY_PROJECT_ID?.trim(),o=s||Xr(r);if(!o)return void zr.warn("[test] No project ID available");zr.info("[test] Fetching JWT API key",{projectId:o});const i=Date.now(),a=await(async(e,t)=>{try{zr.debug("Requesting JWT API key",{projectId:t,apiUrl:Qn});const n=await(async({accessToken:e,projectId:t})=>{const n=await(r={auth:e,client:or(),path:{projectId:t}},(r.client??zn).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 zr.debug("JWT API key obtained",{keyPrefix:n.apiKey.substring(0,10)}),n.apiKey}catch(e){return void zr.warn("Failed to get JWT API key for test reporter",{error:e instanceof Error?e.message:String(e)})}})(r.auth.accessToken,o);zr.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 zr.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},ns=async()=>{const e=Pe.remoteEnvName;if(!e)return;const t=await Qr(),n=Xr(t),r=Zr(t);zr.debug("Fetching remote environment variables",{envName:e,projectId:n});const s=await(o={auth:r,client:or(),path:{projectId:n,environment:e}},(o.client??zn).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/environments/{environment}/variables",...o}));var o;404===s.response.status&&(ae(z.red(`Environment "${e}" not found. Check the name on your Stably dashboard.`)),process.exit(1)),401!==s.response.status&&403!==s.response.status||(ae(z.red(`Access denied to environment "${e}".`)),process.exit(1)),s.error&&(ae(z.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(`${z.cyan(`Loaded ${c} variable${1!==c?"s":""} from "${e}"`)}${l>0?z.dim(` (${l} sensitive)`):""}\n`),{variables:i,sensitiveValues:a}},rs=e=>e?{[An]:e}:void 0,ss=fe.object({context:fe.string().min(1),autohealReportUrl:fe.string(),skippedTests:fe.array(fe.object({testIdentifier:fe.string(),testTitle:fe.string(),consecutiveUnfixedCount:fe.number()})).optional()}),os=be.object({bucket:be.string(),key:be.string()}),is=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})`)},as=be.object({diffBucketPath:os,expiresInSeconds:be.number(),key:be.string(),uploadUrl:be.string()}),cs=be.object({traceBucketPath:os,expiresInSeconds:be.number(),key:be.string(),uploadUrl:be.string(),sensitiveValues:be.array(be.string())}),ls=async({authHeader:e,contentType:t="text/plain",orgId:n,runId:r})=>{const s=await(o={auth:e,body:{contentType:t},client:or(),headers:rs(n),path:{runId:r}},(o.client??zn).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=as.parse(s.data);return{diffBucketPath:i.diffBucketPath,expiresInSeconds:i.expiresInSeconds,key:i.key,uploadUrl:i.uploadUrl}},us=async({authHeader:e,diffBucketPath:t,orgId:n,runId:r})=>{const s=await(o={auth:e,body:t,client:or(),headers:rs(n),path:{runId:r}},(o.client??zn).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})`)},ds=class{socket;url;authHeader;orgId;runId;pendingEvent=null;reconnectAttempts=0;reconnectTimer;debounceTimer;_isClosed=!1;isAuthenticated=!1;authenticationFailed=!1;onUserMessage;maxReconnectAttempts=3;reconnectDelay=2e3;debounceMs=500;get isClosed(){return this._isClosed}constructor({authHeader:e,orgId:t,runId:n,url:r=nr,onUserMessage:s}){this.authHeader=e,this.orgId=t,this.runId=n,this.url=r,this.onUserMessage=s,zr.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)}`;zr.info("[ws] Connecting",{url:t,attempt:this.reconnectAttempts}),this.socket=new ve(t,{headers:e}),this.socket.on("open",()=>{zr.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);zr.debug("[ws] Received message",{type:n?.type}),"connected"===n?.type&&(zr.info("[ws] Authenticated successfully"),this.isAuthenticated=!0,this.authenticationFailed=!1,this.flushPending()),"user_message"===n?.type&&"string"==typeof n.content&&(zr.info("[ws] Received user message from web UI"),this.onUserMessage?.(n.content))}catch{}}),this.socket.on("close",(e,t)=>{zr.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=>{zr.warn("[ws] Connection error",{error:e.message})})}catch(e){zr.warn("[ws] Failed to create WebSocket",{error:e instanceof Error?e.message:String(e)}),this.scheduleReconnect()}}scheduleReconnect(){this._isClosed||this.reconnectTimer||(this.reconnectAttempts++,zr.info("[ws] Scheduling reconnect",{attempt:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts,delayMs:this.reconnectDelay}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect()},this.reconnectDelay))}isConnected(){return!!this.socket&&this.socket.readyState===ve.OPEN&&this.isAuthenticated}sendProgress(e){if(this._isClosed)return void zr.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?(zr.info("[ws] sendProgress: flushing terminal state immediately"),void this.flushPending()):void(this.debounceTimer||(this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.flushPending()},this.debounceMs))):(zr.debug("[ws] sendProgress: not connected, queuing event",{phase:e.phase,socketState:this.socket?.readyState,isAuthenticated:this.isAuthenticated,reconnectAttempts:this.reconnectAttempts}),void(this.socket?.readyState===ve.CLOSED&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()))}flushPending(){if(this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),!this.pendingEvent)return;const e=this.pendingEvent;if(this.pendingEvent=null,!this.isConnected())return zr.debug("[ws] flushPending: not connected, re-queuing event",{phase:e.payload.phase}),void(this.pendingEvent=e);try{zr.debug("[ws] flushPending: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),t=>{t&&(zr.warn("[ws] flushPending: send failed",{error:t.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e))})}catch(t){zr.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{zr.debug("[ws] flushPendingAndWait: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),n=>{n&&(zr.warn("[ws] flushPendingAndWait: send failed",{error:n.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e)),t()})}catch(n){zr.warn("[ws] flushPendingAndWait: send threw",{error:n instanceof Error?n.message:String(n)}),this.pendingEvent=e,t()}}):(zr.debug("[ws] flushPendingAndWait: not connected, re-queuing event",{phase:e.payload.phase}),this.pendingEvent=e,Promise.resolve())}close(){if(this._isClosed)return;zr.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;zr.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())}},ps=class{socket;url;authHeader;orgId;sessionId;pendingEvent=null;reconnectAttempts=0;reconnectTimer;debounceTimer;_isClosed=!1;isAuthenticated=!1;authenticationFailed=!1;onUserMessage;maxReconnectAttempts=3;reconnectDelay=2e3;debounceMs=500;get isClosed(){return this._isClosed}constructor({authHeader:e,orgId:t,sessionId:n,url:r=rr,onUserMessage:s}){this.authHeader=e,this.orgId=t,this.sessionId=n,this.url=r,this.onUserMessage=s,zr.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)}`;zr.info("[ws] Connecting",{url:t,attempt:this.reconnectAttempts}),this.socket=new ve(t,{headers:e}),this.socket.on("open",()=>{zr.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);zr.debug("[ws] Received message",{type:n?.type}),"connected"===n?.type&&(zr.info("[ws] Authenticated successfully"),this.isAuthenticated=!0,this.authenticationFailed=!1,this.flushPending()),"user_message"===n?.type&&"string"==typeof n.content&&(zr.info("[ws] Received user message from web UI"),this.onUserMessage?.(n.content))}catch{}}),this.socket.on("close",(e,t)=>{zr.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=>{zr.warn("[ws] Connection error",{error:e.message})})}catch(e){zr.warn("[ws] Failed to create WebSocket",{error:e instanceof Error?e.message:String(e)}),this.scheduleReconnect()}}scheduleReconnect(){this._isClosed||this.reconnectTimer||(this.reconnectAttempts++,zr.info("[ws] Scheduling reconnect",{attempt:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts,delayMs:this.reconnectDelay}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect()},this.reconnectDelay))}isConnected(){return!!this.socket&&this.socket.readyState===ve.OPEN&&this.isAuthenticated}sendProgress(e){if(this._isClosed)return void zr.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?(zr.info("[ws] sendProgress: flushing terminal state immediately"),void this.flushPending()):void(this.debounceTimer||(this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.flushPending()},this.debounceMs))):(zr.debug("[ws] sendProgress: not connected, queuing event",{phase:e.phase,socketState:this.socket?.readyState,isAuthenticated:this.isAuthenticated,reconnectAttempts:this.reconnectAttempts}),void(this.socket?.readyState===ve.CLOSED&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()))}flushPending(){if(this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),!this.pendingEvent)return;const e=this.pendingEvent;if(this.pendingEvent=null,!this.isConnected())return zr.debug("[ws] flushPending: not connected, re-queuing event",{phase:e.payload.phase}),void(this.pendingEvent=e);try{zr.debug("[ws] flushPending: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),t=>{t&&(zr.warn("[ws] flushPending: send failed",{error:t.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e))})}catch(t){zr.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{zr.debug("[ws] flushPendingAndWait: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),n=>{n&&(zr.warn("[ws] flushPendingAndWait: send failed",{error:n.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e)),t()})}catch(n){zr.warn("[ws] flushPendingAndWait: send threw",{error:n instanceof Error?n.message:String(n)}),this.pendingEvent=e,t()}}):(zr.debug("[ws] flushPendingAndWait: not connected, re-queuing event",{phase:e.payload.phase}),this.pendingEvent=e,Promise.resolve())}close(){if(this._isClosed)return;zr.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;zr.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())}},fs=be.object({bucketPath:os,expiresInSeconds:be.number(),key:be.string(),uploadUrl:be.string()}),hs=fe.object({uploadUrl:fe.string(),key:fe.string(),bucketPath:fe.object({bucket:fe.string(),key:fe.string()}),expiresInSeconds:fe.number()});async function ms({authHeader:e,orgId:t,sessionId:n,projectId:r,history:s}){if(0===s.length)return zr.debug("[session-history] No history to upload"),{success:!0};try{zr.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`,Qn),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 hs.parse(await i.json())}({authHeader:e,orgId:t,sessionId:n,projectId:r}),a=s.map(e=>JSON.stringify(e)).join("\n");zr.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 zr.info("[session-history] History uploaded successfully",{key:i}),{success:!0,key:i}}catch(e){const t=e instanceof Error?e.message:String(e);return zr.warn("[session-history] Failed to upload history",{error:t}),{success:!1,error:t}}}var gs=["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 ys(e){return/^\.env(\..*)?$/.test(e)||".stably-agent.env"===e}function bs(e){return Boolean(e&&"object"==typeof e&&"tool_input"in e&&e.tool_input&&"object"==typeof e.tool_input)}function vs({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(!bs(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:ys,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 ws=["rm","mv","git","gh","npx","npm","yarn","pnpm","bun"],_s=["stably"],Is=["push","fetch","pull","clone","ls-remote"];function Es(e){return e.trim().split(/\s+/).filter(e=>e.length>0)}function Ts(e){let t=0;for(;t<e.length&&/^\S+=\S+$/.test(e[t]??"");)t+=1;return e.slice(t)}function Ss(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 xs({onBeforeGitHubCommand:e,workspaceBoundary:t}){return async n=>{if(!bs(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().match(/^(?:\S+=\S+\s+)*(\S+)/);return t?.[1]}(i);if(!c)return{decision:"block",reason:"Invalid Bash command: could not parse command.",systemMessage:"Tool call blocked due to unparseable command"};if(!function(e){return"string"==typeof e&&ws.includes(e)}(c))return{decision:"block",reason:`The command "${c}" is not allowed. Only the following commands are permitted: ${ws.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=function(e){const t=Ts(Es(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}}}(e);if(!t)return{valid:!1,reason:"Invalid npx command: unable to determine which binary is being executed."};if(!new Set(_s).has(t))return{valid:!1,reason:`The npx binary "${t}" is not allowed. Only ${_s.join(", ")} are permitted.`};const n=function({command:e,binary:t}){const n=Ts(Es(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:e,binary:t});return"test"!==n?{valid:!1,reason:`The npx ${t} command must run the "test" subcommand.`}:{valid:!0}}(i);if(!e.valid)return{decision:"block",reason:e.reason,systemMessage:"Tool call blocked due to disallowed npx command"}}if("rm"===c){const e=function(e){const t=e.trim().match(/^rm\s+(?:-[a-zA-Z]+\s+|--[a-zA-Z-]+\s+)*(.+)$/),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(v(e))return _.native(e);let t=e;const n=[];for(;!v(t);){const r=o(t);if(r===t)return s(e);n.unshift(t.slice(r.length+1)),t=r}const r=_.native(t);return n.length>0?s(r,...n):r}(e),r=_.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=>!(Ss(e,"tests")||Ss(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 ")&&Is.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 gs.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 As=e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"text"===t.type&&"string"==typeof t.text},Cs=e=>null!=e&&"object"==typeof e&&"tool_response"in e,Rs=e=>{if(!e||"object"!=typeof e)return;const t=e;return Array.isArray(t.tool_response)?t.tool_response:void 0},Ps=e=>{const t=Rs(e);if(t)return t.filter(As).map(e=>e.text).join("\n")||void 0},ks=/\u001b\[[0-9;]*m/g,Us=e=>e.replace(ks,""),Ls=/\$\{process\.env\.([A-Z_][A-Z0-9_]*)\}/g;function Ds(e,t){return e.replace(Ls,(e,n)=>{const r=t[n];return null!=r?r:e})}function Os({envVars:e}){return async t=>{if(!bs(t))return{decision:"approve"};const n=t.tool_input,r={...n};let s=!1;if("string"==typeof n.text){const t=Ds(n.text,e);t!==n.text&&(r.text=t,s=!0)}if("string"==typeof n.url){const t=Ds(n.url,e);t!==n.url&&(r.url=t,s=!0)}if("string"==typeof n.function){const t=Ds(n.function,e);t!==n.function&&(r.function=t,s=!0)}if(Array.isArray(n.fields)){const t=n.fields.map(t=>{if("string"==typeof t.value){const n=Ds(t.value,e);if(n!==t.value)return s=!0,{...t,value:n}}return t});s&&(r.fields=t)}return s?{decision:"approve",hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",reason:"Evaluated environment variable placeholders in browser tool input.",updatedInput:r}}:{decision:"approve"}}}function $s({onResult:e}){return async t=>{if(!Cs(t))return{decision:"approve"};const n=Ps(t);if(!n)return{decision:"approve"};const r=function(e){const t=Us(e),n=t.split(/Running \d+ tests? using \d+ workers?/).at(-1)??t,r=parseInt(n.match(/(\d+)\s+passed/g)?.at(-1)?.match(/(\d+)/)?.[1]??"0"),s=parseInt(n.match(/(\d+)\s+failed/g)?.at(-1)?.match(/(\d+)/)?.[1]??"0");if(0===r&&0===s)return;const o=[r>0?`${r} test${1===r?"":"s"} passed ✓`:void 0,s>0?`${s} test${1===s?"":"s"} failed ✗`:void 0].filter(e=>void 0!==e).join(", ");if(0===s)return o;const i=n.split(/\n\s+\d+\)\s+\[id=/).slice(1).map(e=>e.match(/\n\s{4}((?:TimeoutError|Error|AssertionError):\s*[^\n]+)/)?.[1]?.trim()).filter(e=>void 0!==e);return 0===i.length?o:`${o}\n${i.map(e=>` - ${e}`).join("\n")}`}(n);return r&&e(r),{decision:"approve"}}}function Ns({onResult:e}){return async t=>{if(!Cs(t))return{decision:"approve"};const n=Ps(t);if(!n)return{decision:"approve"};const r=function(e){const t=Us(e);if(t.match(/### Paused on error:/)){const e=t.match(/### Paused on error:\s*\n((?:TimeoutError|Error|AssertionError):\s*[^\n]+)/);return e?`Test paused on error - ${e[1].trim()}`:"Test paused on error"}const n=t.match(/(\d+)\s+passed/);if(n){const e=parseInt(n[1]);return`${e} test${1===e?"":"s"} passed ✓`}}(n);return r&&e(r),{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=B(f);async function Hs(){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 Fs=class{queue=[];pendingResolve=void 0;done=!1;canSend=!0;[Symbol.asyncIterator](){return this}pushText(e){const t=e.trim();t&&!this.done&&(this.queue.push(t),this.maybeFlush())}allowNextTurn(){this.done||(this.canSend=!0,this.maybeFlush())}hasQueuedMessages(){return this.queue.length>0}finish(){this.done=!0,this.pendingResolve&&(this.pendingResolve({done:!0,value:void 0}),this.pendingResolve=void 0)}maybeFlush(){if(!this.pendingResolve)return;if(!this.canSend)return;const e=this.queue.shift();if(void 0===e)return;const t={message:{content:[{text:e,type:"text"}],role:"user"},parent_tool_use_id:null,type:"user",session_id:""};this.canSend=!1,this.pendingResolve({done:!1,value:t}),this.pendingResolve=void 0}next(){return this.done?Promise.resolve({done:!0,value:void 0}):new Promise(e=>{this.pendingResolve=e,this.maybeFlush()})}};function 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 re(n)).size,r=await Q(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 ne(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=or(),a=Gs(n.absolutePath);zr.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??zn).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 zr.warn("System prompt fetch failed: unauthorized (401)"),await _r(),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 zr.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){zr.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 _r(),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 zr.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(v(t))for(const e of Qs){const n=i(t,`playwright.config${e}`);if(v(n))return n}}var Zs=["tests","e2e","__tests__","test"];function eo(e){try{return v(e)&&w(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(z.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={"mcp__stably-agent-control__restart_mcp_servers":"Restarting Browser Tools","mcp__session-control__restart_mcp_servers":"Restarting Browser Tools",Skill:"Invoking Skill"},io=(e,t)=>{const n=t.find(t=>e.startsWith(t));return n?e.slice(n.length):e},ao=(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},co=e=>"mcp__auto-heal-report__capture-trace-proof"===e?"Verify Test Run":"mcp__auto-heal-report__generate-report"===e?"Generate Report":(e=>{const t=oo[e];if(t)return t;const n=io(e,ro);return io(n,so).split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")})(e),lo=["test","bug","flake","ui_change","other"],uo={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."},po=e=>uo[e],fo=/[^a-zA-Z0-9-_]/g,ho=e=>{const t=e.trim().replace(fo,"_");return t.length>0?t.slice(0,80):void 0},mo=e=>"string"==typeof e?ho(e):void 0,go=Ae("/");try{no=go("worker_threads").Worker}catch(e){}var yo=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}},bo=Uint8Array,vo=Uint16Array,wo=Int32Array,_o=new bo([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]),Io=new bo([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]),Eo=new bo([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),To=function(e,t){for(var n=new vo(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];var s=new wo(n[30]);for(r=1;r<30;++r)for(var o=n[r];o<n[r+1];++o)s[o]=o-n[r]<<5|r;return{b:n,r:s}},So=To(_o,2),xo=So.b,Ao=So.r;xo[28]=258,Ao[258]=28;var Co,Ro=To(Io,0),Po=Ro.b,ko=Ro.r,Uo=new vo(32768);for(Oo=0;Oo<32768;++Oo)Co=(61680&(Co=(52428&(Co=(43690&Oo)>>1|(21845&Oo)<<1))>>2|(13107&Co)<<2))>>4|(3855&Co)<<4,Uo[Oo]=((65280&Co)>>8|(255&Co)<<8)>>1;var Lo=function(e,t,n){for(var r=e.length,s=0,o=new vo(t);s<r;++s)e[s]&&++o[e[s]-1];var i,a=new vo(t);for(s=1;s<t;++s)a[s]=a[s-1]+o[s-1]<<1;if(n){i=new vo(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[Uo[d]>>c]=l}else for(i=new vo(r),s=0;s<r;++s)e[s]&&(i[s]=Uo[a[e[s]-1]++]>>15-e[s]);return i},Do=new bo(288);for(Oo=0;Oo<144;++Oo)Do[Oo]=8;for(Oo=144;Oo<256;++Oo)Do[Oo]=9;for(Oo=256;Oo<280;++Oo)Do[Oo]=7;for(Oo=280;Oo<288;++Oo)Do[Oo]=8;var Oo,$o=new bo(32);for(Oo=0;Oo<32;++Oo)$o[Oo]=5;var No=Lo(Do,9,0),Bo=Lo(Do,9,1),jo=Lo($o,5,0),Mo=Lo($o,5,1),Ho=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},Fo=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(7&t)&n},Go=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(7&t)},Wo=function(e){return(e+7)/8|0},Yo=function(e,t,n){return(null==t||t<0)&&(t=0),(null==n||n>e.length)&&(n=e.length),new bo(e.subarray(t,n))},Vo=["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"],zo=function(e,t,n){var r=new Error(t||Vo[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,zo),!n)throw r;return r},Ko=function(e,t,n,r){var s=e.length,o=r?r.length:0;if(!s||t.f&&!t.l)return n||new bo(0);var i=!n,a=i||2!=t.i,c=t.i;i&&(n=new bo(3*s));var l=function(e){var t=n.length;if(e>t){var r=new bo(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,m=t.m,g=t.n,y=8*s;do{if(!f){u=Fo(e,d,1);var b=Fo(e,d+1,3);if(d+=3,!b){var v=e[(P=Wo(d)+4)-4]|e[P-3]<<8,w=P+v;if(w>s){c&&zo(0);break}a&&l(p+v),n.set(e.subarray(P,w),p),t.b=p+=v,t.p=d=8*w,t.f=u;continue}if(1==b)f=Bo,h=Mo,m=9,g=5;else if(2==b){var _=Fo(e,d,31)+257,I=Fo(e,d+10,15)+4,E=_+Fo(e,d+5,31)+1;d+=14;for(var T=new bo(E),S=new bo(19),x=0;x<I;++x)S[Eo[x]]=Fo(e,d+3*x,7);d+=3*I;var A=Ho(S),C=(1<<A)-1,R=Lo(S,A,1);for(x=0;x<E;){var P,k=R[Fo(e,d,C)];if(d+=15&k,(P=k>>4)<16)T[x++]=P;else{var U=0,L=0;for(16==P?(L=3+Fo(e,d,3),d+=2,U=T[x-1]):17==P?(L=3+Fo(e,d,7),d+=3):18==P&&(L=11+Fo(e,d,127),d+=7);L--;)T[x++]=U}}var D=T.subarray(0,_),O=T.subarray(_);m=Ho(D),g=Ho(O),f=Lo(D,m,1),h=Lo(O,g,1)}else zo(1);if(d>y){c&&zo(0);break}}a&&l(p+131072);for(var $=(1<<m)-1,N=(1<<g)-1,B=d;;B=d){var j=(U=f[Go(e,d)&$])>>4;if((d+=15&U)>y){c&&zo(0);break}if(U||zo(2),j<256)n[p++]=j;else{if(256==j){B=d,f=null;break}var M=j-254;if(j>264){var H=_o[x=j-257];M=Fo(e,d,(1<<H)-1)+xo[x],d+=H}var F=h[Go(e,d)&N],G=F>>4;if(F||zo(3),d+=15&F,O=Po[G],G>3&&(H=Io[G],O+=Go(e,d)&(1<<H)-1,d+=H),d>y){c&&zo(0);break}a&&l(p+131072);var W=p+M;if(p<O){var Y=o-O,V=Math.min(O,W);for(Y+p<0&&zo(3);p<V;++p)n[p]=r[Y+p]}for(;p<W;++p)n[p]=n[p-O]}}t.l=f,t.p=B,t.b=p,t.f=u,f&&(u=1,t.m=m,t.d=h,t.n=g)}while(!u);return p!=n.length&&i?Yo(n,0,p):n.subarray(0,p)},qo=function(e,t,n){n<<=7&t;var r=t/8|0;e[r]|=n,e[r+1]|=n>>8},Jo=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},Qo=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:si,l:0};if(1==s){var i=new bo(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 vo(p+1),h=Xo(n[u-1],f,0);if(h>t){r=0;var m=0,g=h-t,y=1<<g;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;m+=y-(1<<h-f[b]),f[b]=t}for(m>>=g;m>0;){var v=o[r].s;f[v]<t?m-=1<<t-f[v]++-1:++r}for(;r>=0&&m;--r){var w=o[r].s;f[w]==t&&(--f[w],++m)}h=t}return{t:new bo(f),l:h}},Xo=function(e,t,n){return-1==e.s?Math.max(Xo(e.l,t,n+1),Xo(e.r,t,n+1)):t[e.s]=n},Zo=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new vo(++t),r=0,s=e[0],o=1,i=function(e){n[r++]=e},a=1;a<=t;++a)if(e[a]==s&&a!=t)++o;else{if(!s&&o>2){for(;o>138;o-=138)i(32754);o>2&&(i(o>10?o-11<<5|28690:o-3<<5|12305),o=0)}else if(o>3){for(i(s),--o;o>6;o-=6)i(8304);o>2&&(i(o-3<<5|8208),o=0)}for(;o--;)i(s);o=1,s=e[a]}return{c:n.subarray(0,r),n:t}},ei=function(e,t){for(var n=0,r=0;r<t.length;++r)n+=e[r]*t[r];return n},ti=function(e,t,n){var r=n.length,s=Wo(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)},ni=function(e,t,n,r,s,o,i,a,c,l,u){qo(t,u++,n),++s[256];for(var d=Qo(s,15),p=d.t,f=d.l,h=Qo(o,15),m=h.t,g=h.l,y=Zo(p),b=y.c,v=y.n,w=Zo(m),_=w.c,I=w.n,E=new vo(19),T=0;T<b.length;++T)++E[31&b[T]];for(T=0;T<_.length;++T)++E[31&_[T]];for(var S=Qo(E,7),x=S.t,A=S.l,C=19;C>4&&!x[Eo[C-1]];--C);var R,P,k,U,L=l+5<<3,D=ei(s,Do)+ei(o,$o)+i,O=ei(s,p)+ei(o,m)+i+14+3*C+ei(E,x)+2*E[16]+3*E[17]+7*E[18];if(c>=0&&L<=D&&L<=O)return ti(t,u,e.subarray(c,c+l));if(qo(t,u,1+(O<D)),u+=2,O<D){R=Lo(p,f,0),P=p,k=Lo(m,g,0),U=m;var $=Lo(x,A,0);for(qo(t,u,v-257),qo(t,u+5,I-1),qo(t,u+10,C-4),u+=14,T=0;T<C;++T)qo(t,u+3*T,x[Eo[T]]);u+=3*C;for(var N=[b,_],B=0;B<2;++B){var j=N[B];for(T=0;T<j.length;++T){var M=31&j[T];qo(t,u,$[M]),u+=x[M],M>15&&(qo(t,u,j[T]>>5&127),u+=j[T]>>12)}}}else R=No,P=Do,k=jo,U=$o;for(T=0;T<a;++T){var H=r[T];if(H>255){Jo(t,u,R[257+(M=H>>18&31)]),u+=P[M+257],M>7&&(qo(t,u,H>>23&31),u+=_o[M]);var F=31&H;Jo(t,u,k[F]),u+=U[F],F>3&&(Jo(t,u,H>>5&8191),u+=Io[F])}else Jo(t,u,R[H]),u+=P[H]}return Jo(t,u,R[256]),u+P[256]},ri=new wo([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),si=new bo(0),oi=function(e,t,n,r,s,o){var i=o.z||e.length,a=new bo(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=ri[t-1],p=d>>13,f=8191&d,h=(1<<n)-1,m=o.p||new vo(32768),g=o.h||new vo(h+1),y=Math.ceil(n/3),b=2*y,v=function(t){return(e[t]^e[t+1]<<y^e[t+2]<<b)&h},w=new wo(25e3),_=new vo(288),I=new vo(32),E=0,T=0,S=o.i||0,x=0,A=o.w||0,C=0;S+2<i;++S){var R=v(S),P=32767&S,k=g[R];if(m[P]=k,g[R]=P,A<=S){var U=i-S;if((E>7e3||x>24576)&&(U>423||!l)){u=ni(e,c,0,w,_,I,T,x,C,S-C,u),x=E=T=0,C=S;for(var L=0;L<286;++L)_[L]=0;for(L=0;L<30;++L)I[L]=0}var D=2,O=0,$=f,N=P-k&32767;if(U>2&&R==v(S-N))for(var B=Math.min(p,U)-1,j=Math.min(32767,S),M=Math.min(258,U);N<=j&&--$&&P!=k;){if(e[S+D]==e[S+D-N]){for(var H=0;H<M&&e[S+H]==e[S+H-N];++H);if(H>D){if(D=H,O=N,H>B)break;var F=Math.min(N,H-2),G=0;for(L=0;L<F;++L){var W=S-N+L&32767,Y=W-m[W]&32767;Y>G&&(G=Y,k=W)}}}N+=(P=k)-(k=m[P])&32767}if(O){w[x++]=268435456|Ao[D]<<18|ko[O];var V=31&Ao[D],z=31&ko[O];T+=_o[V]+Io[z],++_[257+V],++I[z],A=S+D,++E}else w[x++]=e[S],++_[e[S]]}}for(S=Math.max(S,A);S<i;++S)w[x++]=e[S],++_[e[S]];u=ni(e,c,l,w,_,I,T,x,C,S-C,u),l||(o.r=7&u|c[u/8|0]<<3,u-=7,o.h=g,o.p=m,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=ti(c,u+1,e.subarray(S,K))}o.i=i}return Yo(a,0,r+Wo(u)+s)},ii=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}(),ai=function(e,t,n,r,s){if(!s&&(s={l:1},t.dictionary)){var o=t.dictionary.subarray(-32768),i=new bo(o.length+e.length);i.set(o),i.set(e,o.length),e=i,s.w=o.length}return oi(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)},ci=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},li=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},ui=[],di=function(){return[bo,vo,wo,_o,Io,Eo,xo,Po,Bo,Mo,Uo,Vo,Lo,Ho,Fo,Go,Wo,Yo,zo,Ko,_i,fi,hi]},pi=function(){return[bo,vo,wo,_o,Io,Eo,Ao,ko,No,Do,jo,$o,Uo,ri,si,Lo,qo,Jo,Qo,Xo,Zo,ei,ti,ni,Wo,Yo,oi,ai,wi,fi]},fi=function(e){return postMessage(e,[e.buffer])},hi=function(e){return e&&{out:e.size&&new bo(e.size),dictionary:e.dictionary}},mi=function(e,t,n,r,s,o){var i=function(e,t,n,r){if(!ui[n]){for(var s="",o={},i=e.length-1,a=0;a<i;++a)s=li(e[a],s,o);ui[n]={c:li(e[i],s,o),e:o}}var c=ci({},ui[n].e);return yo(ui[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()}},gi=function(e,t){return e[t]|e[t+1]<<8},yi=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},bi=function(e,t){return yi(e,t)+4294967296*yi(e,t+4)},vi=function(e,t,n){for(;n;++t)e[t]=n,n>>>=8};function wi(e,t){return ai(e,t||{},0,0)}function _i(e,t){return Ko(e,{i:2},t&&t.out,t&&t.dictionary)}var Ii=function(e,t,n,r){for(var s in e){var o=e[s],i=t+s,a=r;Array.isArray(o)&&(a=ci(r,o[1]),o=o[0]),o instanceof bo?n[i]=[o,a]:(n[i+="/"]=[new bo(0),a],Ii(o,i,n,r))}},Ei="undefined"!=typeof TextEncoder&&new TextEncoder,Ti="undefined"!=typeof TextDecoder&&new TextDecoder;try{Ti.decode(si,{stream:!0})}catch(e){}function Si(e,t){if(Ei)return Ei.encode(e);for(var n=e.length,r=new bo(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 bo(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 Yo(r,0,s)}var xi=function(e){var t=0;if(e)for(var n in e){var r=e[n].length;r>65535&&zo(9),t+=r+4}return t},Ai=function(e,t,n,r,s,o,i,a){var c=r.length,l=n.extra,u=a&&a.length,d=xi(l);vi(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)&&zo(10),vi(e,t,f<<25|p.getMonth()+1<<21|p.getDate()<<16|p.getHours()<<11|p.getMinutes()<<5|p.getSeconds()>>1),t+=4,-1!=o&&(vi(e,t,n.crc),vi(e,t+4,o<0?-o-2:o),vi(e,t+8,n.size)),vi(e,t+12,c),vi(e,t+14,d),t+=16,null!=i&&(vi(e,t,u),vi(e,t+6,n.attrs),vi(e,t+10,i),t+=14),e.set(r,t),t+=c,d)for(var h in l){var m=l[h],g=m.length;vi(e,t,+h),vi(e,t+2,g),e.set(m,t+4),t+=4+g}return u&&(e.set(a,t),t+=u),t},Ci="function"==typeof queueMicrotask?queueMicrotask:"function"==typeof setTimeout?setTimeout:function(e){e()};function Ri(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 Pi=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 ki(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 Ui(e){switch(7&ki(e)){case 0:return ki(e),!0;case 1:return e.next(8),!0;case 2:const t=ki(e);return e.next(t),!0;case 5:return e.next(4),!0}return!1}function Li(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!Ri(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!Ri(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 Pi(e,t);let r=0;for(;;){if(!Ui(n)&&!n.hasError())return!1;if(n.hasError())break;r++}return r>0}(e,o))}var Di=[/^\/$/,/^\*+$/,/^[0-9]+$/],Oi=["/artifact/","https://","http://","*********"],$i=new Set(["sha1","_sha1","pageref","downloadsPath","tracesDir","pageId"]);function Ni({sensitiveValues:e,str:t}){return e.reduce((e,t)=>e.replaceAll(t,"[REDACTED]"),t)}function Bi({sensitiveValues:e,value:t}){return"string"==typeof t?Ni({sensitiveValues:e,str:t}):Array.isArray(t)?t.map(t=>Bi({sensitiveValues:e,value:t})):function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(t)?Mi({obj:t,sensitiveValues:e}):t}function ji(e){return!!$i.has(e)||e.toLowerCase().endsWith("sha1")}function Mi({obj:e,sensitiveValues:t}){return Object.fromEntries(Object.entries(e).map(([e,n])=>[e,ji(e)?n:Bi({sensitiveValues:t,value:n})]))}function Hi({error:e,sensitiveValues:t}){return e?{...e,message:Ni({sensitiveValues:t,str:e.message})}:void 0}function Fi({content:e,sensitiveValues:t}){const n=new j,r=new M,s=Ni({sensitiveValues:t,str:n.decode(e)});return r.encode(s)}var Gi=B(function(e,t,n){n||(n=t,t={}),"function"!=typeof n&&zo(7);var r=[],s=function(){for(var e=0;e<r.length;++e)r[e]()},o={},i=function(e,t){Ci(function(){n(e,t)})};Ci(function(){i=n});for(var a=e.length-22;101010256!=yi(e,a);--a)if(!a||e.length-a>65558)return i(zo(13,0,1),null),s;var c=gi(e,a+8);if(c){var l=c,u=yi(e,a+16),d=4294967295==u||65535==l;if(d){var p=yi(e,a-12);(d=101075792==yi(e,p))&&(l=c=yi(e,p+32),u=yi(e,p+48))}for(var f=t&&t.filter,h=function(t){var n=function(e,t,n){var r=gi(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(Ti)return Ti.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:Yo(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&&zo(8),o}(e.subarray(t+46,t+46+r),!(2048&gi(e,t+8))),o=t+46+r,i=yi(e,t+20),a=n&&4294967295==i?function(e,t){for(;1!=gi(e,t);t+=4+gi(e,t+2));return[bi(e,t+12),bi(e,t+4),bi(e,t+20)]}(e,o):[i,yi(e,t+24),yi(e,t+42)],c=a[0],l=a[1],u=a[2];return[gi(e,t+10),c,l,s,o+gi(e,t+30)+gi(e,t+32),u]}(e,u,d),a=n[0],l=n[1],p=n[2],h=n[3],m=n[4],g=n[5],y=function(e,t){return t+30+gi(e,t+26)+gi(e,t+28)}(e,g);u=m;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 v=e.subarray(y,y+l);if(p<524288||l>.8*p)try{b(null,_i(v,{out:new bo(p)}))}catch(e){b(e,null)}else r.push(function(e,t,n){return n||(n=t,t={}),"function"!=typeof n&&zo(7),mi(e,t,[di],function(e){return fi(_i(e.data[0],hi(e.data[1])))},1,n)}(v,{size:p},b))}else b(zo(14,"unknown compression type "+a,1),null);else b(null,Yo(e,y,y+l));else b(null,null)},m=0;m<l;++m)h()}else i(null,{});return s}),Wi=B(function(e,t,n){n||(n=t,t={}),"function"!=typeof n&&zo(7);var r={};Ii(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){Ci(function(){n(e,t)})};Ci(function(){p=n});var f=function(){var e=new bo(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;Ai(e,a,s,s.f,s.u,o);var u=30+s.f.length+xi(s.extra),d=a+u;e.set(s.c,d),Ai(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){vi(e,t,101010256),vi(e,t+8,n),vi(e,t+10,n),vi(e,t+12,r),vi(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],m=function(){var e=-1;return{p:function(t){for(var n=e,r=0;r<t.length;++r)n=ii[255&n^t[r]]^n>>>8;e=n},d:function(){return~e}}}(),g=c.length;m.p(c);var y=Si(t),b=y.length,v=h.comment,w=v&&Si(v),_=w&&w.length,I=xi(h.extra),E=0==h.level?0:8,T=function(n,r){if(n)d(),p(n,null);else{var s=r.length;l[e]=ci(h,{size:g,crc:m.d(),c:r,f:y,m:w,u:b!=t.length||w&&v.length!=_,compression:E}),i+=30+b+I+s,a+=76+2*(b+I)+(_||0)+s,--o||f()}};if(b>65535&&T(zo(11,0,1),null),E)if(g<16e4)try{T(null,wi(c,h))}catch(e){T(e,null)}else u.push(function(e,t,n){return n||(n=t,t={}),"function"!=typeof n&&zo(7),mi(e,t,[pi],function(e){return fi(wi(e.data[0],e.data[1]))},0,n)}(c,h,T));else T(null,c)},m=0;m<c;++m)h(m);return d});async function Yi({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 j,r=new M,s=n.decode(e).split("\n").map(e=>{if(!e.trim())return e;try{const n=function({event:e,sensitiveValues:t}){return W(e).with({type:"console"},e=>({...e,args:e.args?.map(e=>({...e,preview:Ni({sensitiveValues:t,str:e.preview}),value:Bi({sensitiveValues:t,value:e.value})})),text:Ni({sensitiveValues:t,str:e.text})})).with({type:"before"},e=>({...e,params:Mi({obj:e.params,sensitiveValues:t}),title:e.title?Ni({sensitiveValues:t,str:e.title}):void 0})).with({type:"after"},e=>({...e,error:Hi({error:e.error,sensitiveValues:t}),result:void 0!==e.result?Bi({sensitiveValues:t,value:e.result}):void 0})).with({type:"action"},e=>({...e,error:Hi({error:e.error,sensitiveValues:t}),params:Mi({obj:e.params,sensitiveValues:t}),result:void 0!==e.result?Bi({sensitiveValues:t,value:e.result}):void 0,title:e.title?Ni({sensitiveValues:t,str:e.title}):void 0})).with({type:"event"},e=>({...e,params:Mi({obj:e.params,sensitiveValues:t})})).with({type:"stdout"},{type:"stderr"},e=>({...e,text:void 0!==e.text?Ni({sensitiveValues:t,str:e.text}):void 0})).with({type:"error"},e=>({...e,message:Ni({sensitiveValues:t,str:e.message})})).with({type:"log"},e=>({...e,message:Ni({sensitiveValues:t,str:e.message})})).with({type:"context-options"},e=>({...e,options:Mi({obj:e.options,sensitiveValues:t}),title:e.title?Ni({sensitiveValues:t,str:e.title}):void 0})).with({type:"frame-snapshot"},e=>({...e,snapshot:Mi({obj:e.snapshot,sensitiveValues:t})})).with({type:"resource-snapshot"},e=>({...e,snapshot:Mi({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 Ni({sensitiveValues:t,str:e})}});return r.encode(s.join("\n"))}({content:e,sensitiveValues:n}):r.endsWith(".html")||r.endsWith(".dat")||r.endsWith(".json")?Fi({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!")}(w(e));const n=A(e,"r"),r=Buffer.alloc(515),s=C(n,r,0,515,0);return R(n),Li(r,s,t)}return Li(e,void 0!==t?.size?t.size:e.length,t)}(Buffer.from(e),{size:e.length})}(e)?e:Fi({content:e,sensitiveValues:t})}({content:e,sensitiveValues:n}):e}function Vi(e=process.cwd()){let t=s(e);for(;;){const e=zi(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=Ki(t);let n=!1,s=t;for(;;){const e=i(s,"node_modules"),t=i(e,r);if(v(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 zi(e){const t=i(e,"package.json");let n;try{n=E(t,"utf-8")}catch{return}try{return JSON.parse(n)}catch{return}}function Ki(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(v(i(n,r)))return e;const e=o(n);if(e===n)return;n=e}}function qi(e){if("npm"===e||"pnpm"===e)return["npx","playwright"];if("yarn"===e)return["yarn","playwright"];throw new Error("Package manager not supported")}var Ji=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Qi=e=>(e instanceof Error?e.message:String(e)).slice(0,400),Xi=({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",Ji(t.testTitle)):t.testIdentifier&&n.push("--grep",`^${Ji(t.testIdentifier)}$`),n},Zi=async e=>{const t=await ne(e,{withFileTypes:!0}),n=[];for(const s of t){const t=r.join(e,s.name);if(s.isDirectory())n.push(...await Zi(t));else if(s.isFile()&&"trace.zip"===s.name){const e=await re(t);n.push({path:t,mtimeMs:e.mtimeMs})}}return n},ea=async e=>{try{const t=await ne(e,{withFileTypes:!0});for(const n of t){const t=r.join(e,n.name);n.isDirectory()?await ea(t):n.isFile()&&".last-run.json"===n.name&&await se(t,{force:!0})}}catch{}},{zMarkdownAutoHealReport:ta,zRepresentativeTest:na}=function(e){const t=e.enum(lo),n=["Classification of the root cause:","",`- test: ${po("test")}`,`- bug: ${po("bug")}`,`- flake: ${po("flake")}`,`- ui_change: ${po("ui_change")}`,`- other: ${po("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()}),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.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.")});return{zAutoHealReport:a,zIssueCategory:t,zMarkdownAutoHealReport:l,zRepresentativeTest:r,zSuiteAutoHealReport:c,zStoredAutoHealReport:e.union([c,l]),zTraceProof:s,zTraceProofByTest:o}}(be),ra=({authHeader:e,diffTracker:t,orgId:n,runId:s,workingDir:o})=>H({name:"auto-heal-report",tools:[F("capture-trace-proof",["Capture and upload a Playwright trace proof for a test case.","","MANDATORY: Call for EVERY testCaseId in your issue, whether fixed or unfixed.","- Fixed: Trace proves the fix works","- Unfixed: Trace shows the failure state for auditability","","Pass testCaseId and call once per test case.","testCaseId is for per-test mapping/storage metadata; representativeTest selects the runnable test."].join("\n"),{issueId:be.string().min(1).describe("Issue identifier for deterministic output paths and storage key naming."),proofId:be.string().min(1).optional().describe("Optional id for deterministic proof naming and deduplication."),representativeTest:na.optional().default({}),testCaseId:be.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=be.string().min(1).parse(t),u=null==i?void 0:be.string().min(1).parse(i),d=null==c?void 0:be.string().min(1).parse(c),p=await(async({authHeader:e,issueId:t,orgId:n,proofId:s,representativeTest:o,runId:i,testCaseId:a,workingDir:c})=>{if(!(e=>null!=e.filePath||null!=e.testTitle||null!=e.testIdentifier)(o))return{status:"capture_failed",representativeTest:o,error:"Representative test info is missing (need filePath, testTitle, or testIdentifier)."};const l=Vi(c);if(!l.installed||!l.inNodeModules||!l.packageManager)return{status:"capture_failed",representativeTest:o,error:"Playwright is not installed in the current workspace."};const u=(e=>ho(e)??"issue")(t),d=(({proofId:e,testCaseId:t})=>mo(t)??mo(e))({testCaseId:a,proofId:s}),p=r.join(c,".stably","autoheal-proof",u,d??"issue"),[f,...h]=qi(l.packageManager),g=[...h,...Xi({outputDir:p,representativeTest:o})];try{await se(p,{force:!0,recursive:!0}),await X(p,{recursive:!0});const{code:r,stderr:l,timedOut:u}=await(async({args:e,command:t,cwd:n,env:r,timeoutMs:s})=>await new Promise((o,i)=>{const a=m(t,e,{cwd:n,env:r??process.env,stdio:["ignore","ignore","pipe"],shell:"win32"===process.platform});let c="",l=!1;a.stderr.on("data",e=>{c+=e.toString()});const u=setTimeout(()=>{l=!0,a.kill("SIGTERM")},s);a.on("error",e=>{clearTimeout(u),i(e)}),a.on("close",e=>{clearTimeout(u),o({code:e,stderr:c,timedOut:l})})}))({args:g,command:f,cwd:c,env:{...process.env,STABLY_INTERNAL_DISABLE_REPORTING:"1"},timeoutMs:3e5});if(u)return{status:"capture_failed",representativeTest:o,error:"Trace proof run timed out while executing Playwright verification."};const d=await(async e=>{const t=await Zi(e);if(0!==t.length)return t.sort((e,t)=>t.mtimeMs-e.mtimeMs),t[0]?.path})(p);if(!d)return{status:"capture_failed",representativeTest:o,error:`No trace.zip was produced${0!==r?` (test exit code ${r??"unknown"})`:""}: ${l.trim().slice(0,280)}`.trim()};await ea(p);const{traceBucketPath:h,uploadUrl:y,sensitiveValues:b}=await(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:or(),headers:rs(o),path:{runId:i}},(c.client??zn).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=cs.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}),v=await async function({tracePath:e,sensitiveValues:t}){const n=[],r=I(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||Di.some(t=>t.test(e))||Oi.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 Gi(new Uint8Array(t)),o=Object.entries(s),i=await Promise.all(o.map(async([e,t])=>[e,await Yi({content:t,filename:e,sensitiveValues:r})])),a=Object.fromEntries(i);return Wi(a)}({traceBuffer:new Uint8Array(Buffer.concat(n)),sensitiveValues:t})}({tracePath:d,sensitiveValues:b});try{await is({body:v,contentType:"application/zip",uploadUrl:y,errorContext:"trace"})}catch(e){return{status:"upload_failed",representativeTest:o,error:Qi(e)}}return{status:"captured",representativeTest:o,storage:h}}catch(e){return{status:"capture_failed",representativeTest:o,error:Qi(e)}}})({authHeader:e,issueId:l,orgId:n,proofId:u,representativeTest:na.parse(a??{}),runId:s,testCaseId:d,workingDir:o}),f="string"==typeof d?{testCaseId:d,...p}:p;return{content:[{text:JSON.stringify(f),type:"text"}]}}),F("generate-report",["After attempting to fix all broken tests (skip only those truly infeasible), generate a flexible markdown auto-heal report.","","Use markdown headings, bullets, and code fences as needed. Include all important findings, fixes, unfixed items, and evidence.","Write for readability: start with a short summary, group related items under clear section headings, 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."].join("\n"),{markdown:ta.shape.markdown},async({markdown:r})=>{const o=await t.computeDiff(),i=ta.parse({format:"markdown",markdown:r});try{await(async({authHeader:e,orgId:t,report:n,runId:r})=>{const s=await(o={auth:e,body:{report:JSON.stringify(n)},client:or(),headers:rs(t),path:{runId:r}},(o.client??zn).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:i,runId:s});const{diffBucketPath:t,uploadUrl:r}=await ls({authHeader:e,contentType:"text/plain",orgId:n,runId:s});await is({body:o,contentType:"text/plain",uploadUrl:r,errorContext:"diff"}),await us({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"}),sa=({onComplete:e,onRestartRequested:t})=>H(e?{name:"session-control",tools:[F("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:be.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}`)})]}:{name:"stably-agent-control",version:"1.0.0",tools:[F("restart_mcp_servers",'Restart the MCP servers to reinitialize browser tools after dependency changes.\n\nWHEN TO USE:\n- After installing or updating @playwright/test to version 1.56.x\n- When browser tools fail due to version mismatch errors\n- When the user has fixed a dependency issue and you need to reinitialize\n\nIMPORTANT: The restart happens at the END of your current turn.\n- Do NOT call any browser tools (setup_page, navigate, etc.) after this tool in the same turn - they will use the OLD servers\n- After calling this tool, END your turn naturally (no more tool calls)\n- The system will automatically continue in a new turn once the tools are restarted\n- Do NOT ask the user to reply again just to resume (only ask if you truly need additional input)\n\nEnd your turn briefly. You may say something like:\n- "Restarting browser tools now…"\n- "Tools are restarting to pick up the dependency changes…"',{},()=>(t(),Promise.resolve({content:[{type:"text",text:'MCP restart SCHEDULED for end of this turn.\n\nCRITICAL: END YOUR TURN NOW. Do not call any more tools.\nThe restart only happens AFTER your turn completes.\n\nAny tools called in this turn will use the OLD servers and fail.\n\nThe system will automatically continue with "[SYSTEM] MCP servers were restarted successfully" once ready.'}]})))]}),oa=be.object({commentUrl:be.string()}),ia=({prContext:e,authHeader:t,orgId:n,onReportPosted:r})=>H({name:"create-report",tools:[F("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:be.string().describe("A summary of the tests created. Include what features/flows are tested and any important notes."),filesCreated:be.array(be.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:[];zr.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",Qn).toString(),a={Authorization:e,"Content-Type":"application/json"};t&&(a["x-stably-org-id"]=t),zr.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 zr.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=oa.parse(await c.json());return zr.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),zr.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 zr.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}}})]}),aa=["QUEUED","RUNNING","PASSED","FAILED","TIMEDOUT","CANCELLED","INTERRUPTED"],ca=["LOCAL","CI","WEB"],la=["MANUAL","SCHEDULED","UI","API","GITHUB_ACTION","SUITE_RUN"],ua=({authHeader:e,orgId:t,projectId:n})=>H({name:"run-history",tools:[F("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:be.string().optional().describe("Filter by branch name"),status:be.enum(aa).optional().describe("Filter by status: QUEUED|RUNNING|PASSED|FAILED|TIMEDOUT|CANCELLED|INTERRUPTED"),limit:be.number().min(1).max(100).optional().describe("Max results (1-100, default 20)"),source:be.enum(ca).optional().describe("Filter by source: LOCAL|CI|WEB"),trigger:be.enum(la).optional().describe("Filter by trigger: MANUAL|SCHEDULED|UI|API|GITHUB_ACTION|SUITE_RUN"),suite:be.string().optional().describe("Filter by suite name"),after:be.string().optional().describe("Pagination: return runs after this runId"),before:be.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,m="string"==typeof a?a:void 0,g="string"==typeof c?c:void 0,y="string"==typeof l?l:void 0,b="string"==typeof u?u:void 0;zr.info("[run-history] list_runs called",{branch:d,status:p,limit:f});try{const r=await Kn({auth:e,client:or(),headers:rs(t),query:{projectId:n,branchName:d,status:p,limit:f,source:h,trigger:m,suiteName:g,afterRunId:y,beforeRunId:b}});if(r.error||!r.data){const e=r.response?`API error: ${r.response.status}`:`API error: ${String(r.error)}`;return zr.error("[run-history] list_runs failed",{error:e}),{content:[{type:"text",text:`Error: ${e}`}],isError:!0}}return zr.info("[run-history] list_runs success",{runCount:r.data.runs?.length??0,hasMore:r.data.hasMore}),{content:[{type:"text",text:JSON.stringify(r.data,null,2)}]}}catch(e){const t=e instanceof Error?e.message:String(e);return zr.error("[run-history] list_runs exception",{error:t}),{content:[{type:"text",text:`Error: ${t}`}],isError:!0}}}),F("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:be.string().min(1).describe("The run ID to view (required)")},async({runId:n})=>{const r="string"==typeof n?n:String(n);zr.info("[run-history] view_run called",{runId:r});try{const n=await qn({auth:e,client:or(),headers:rs(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 zr.error("[run-history] view_run failed",{error:e,runId:r}),{content:[{type:"text",text:`Error: ${e}`}],isError:!0}}return zr.info("[run-history] view_run success",{runId:r}),{content:[{type:"text",text:JSON.stringify(n.data,null,2)}]}}catch(e){const t=e instanceof Error?e.message:String(e);return zr.error("[run-history] view_run exception",{error:t,runId:r}),{content:[{type:"text",text:`Error: ${t}`}],isError:!0}}})]}),da=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]"),pa=(e,t)=>({message:da(e),status:t?.status,statusText:t?.statusText}),fa=new Set(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_CUSTOM_HEADERS","ANTHROPIC_DEFAULT_HAIKU_MODEL","ANTHROPIC_DEFAULT_OPUS_MODEL","ANTHROPIC_DEFAULT_SONNET_MODEL","ANTHROPIC_FOUNDRY_API_KEY","ANTHROPIC_MODEL","ANTHROPIC_SMALL_FAST_MODEL","ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION","AWS_BEARER_TOKEN_BEDROCK","BASH_DEFAULT_TIMEOUT_MS","BASH_MAX_OUTPUT_LENGTH","BASH_MAX_TIMEOUT_MS","CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR","CLAUDE_CODE_API_KEY_HELPER_TTL_MS","CLAUDE_CODE_CLIENT_CERT","CLAUDE_CODE_CLIENT_KEY_PASSPHRASE","CLAUDE_CODE_CLIENT_KEY","CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS","CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC","CLAUDE_CODE_DISABLE_TERMINAL_TITLE","CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL","CLAUDE_CODE_MAX_OUTPUT_TOKENS","CLAUDE_CODE_SHELL_PREFIX","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SUBAGENT_MODEL","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_VERTEX","CLAUDE_CONFIG_DIR","DISABLE_AUTOUPDATER","DISABLE_BUG_COMMAND","DISABLE_COST_WARNINGS","DISABLE_ERROR_REPORTING","DISABLE_NON_ESSENTIAL_MODEL_CALLS","DISABLE_PROMPT_CACHING","DISABLE_PROMPT_CACHING_HAIKU","DISABLE_PROMPT_CACHING_OPUS","DISABLE_PROMPT_CACHING_SONNET","DISABLE_TELEMETRY","HTTP_PROXY","HTTPS_PROXY","MAX_MCP_OUTPUT_TOKENS","MAX_THINKING_TOKENS","MCP_TIMEOUT","MCP_TOOL_TIMEOUT","NO_PROXY","SLASH_COMMAND_TOOL_CHAR_BUDGET","USE_BUILTIN_RIPGREP","VERTEX_REGION_CLAUDE_3_5_HAIKU","VERTEX_REGION_CLAUDE_3_7_SONNET","VERTEX_REGION_CLAUDE_4_0_OPUS","VERTEX_REGION_CLAUDE_4_0_SONNET","VERTEX_REGION_CLAUDE_4_1_OPUS"]),ha=async({authHeader:e,mode:t,maxTurnsOverride:n})=>{const r=or();zr.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??zn).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 zr.warn("Subagent definitions fetch failed: unauthorized (401)"),await _r(),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 zr.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 zr.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 zr.debug("Subagent definitions received",{count:Object.keys(i).length}),i},ma=r.dirname(k(import.meta.url)),ga=r.join(".claude-plugin","plugin.json"),ya=[r.join("packages","agent-plugin","stably-plugin-cli"),r.join("agent-plugin","stably-plugin-cli")];function ba(e){return v(r.join(e,ga))}var{zStablyYaml:va}=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}}(fe),wa=async(e,t)=>{try{const n=await pr(e,t);if(!n)return void zr.debug(`No ${t} found`);const r=await Q(n,"utf-8");if(!r.trim())return;return r.length>1e4?(zr.warn(`${t} exceeds max length (${r.length} > 10000), truncating`,{path:n}),{content:r.slice(0,1e4),path:n}):(zr.debug(`Loaded ${t} rules`,{path:n,contentLength:r.length}),{content:r,path:n})}catch(e){return void zr.warn(`Failed to read ${t}`,{error:e})}},_a=fe.object({verdict:fe.enum(["PASS","FAIL","INCONCLUSIVE"]),steps:fe.array(fe.string()).min(1),reason:fe.string().nullable(),evidence:fe.array(fe.string())}).superRefine((e,t)=>{"PASS"===e.verdict||e.reason&&0!==e.reason.trim().length||t.addIssue({code:fe.ZodIssueCode.custom,path:["reason"],message:"reason is required for FAIL and INCONCLUSIVE verdicts"})}),Ia=/\bmcp__playwright-mcp__[a-z0-9_]+\b/gi,Ea=/\.playwright-mcp(?:\/[^\s"'`)\]]*)?/gi,Ta=/\bplaywright[\s_-]?mcp\b/gi;function Sa(e){return e.replace(Ia,"browser_tool").replace(Ea,"verification-artifact").replace(Ta,"browser automation")}function xa(e){return{...e,steps:e.steps.map(e=>Sa(e)),reason:e.reason?Sa(e.reason):null,evidence:e.evidence.map(e=>Sa(e))}}function Aa(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=_a.parse(t)}catch{}return n}var Ca=["Bash","Read","Write","Edit","Glob","Grep","Task","Skill"],Ra=["Task","mcp__playwright-test","Skill"],Pa=["Bash","Read","Write","Edit","Glob","Grep","mcp__session-control"],ka=e=>{if("EPIPE"!==e.code)throw e},Ua="__main__",La=[3e3,5173,4173,8080,4200,8e3],Da=/\b(TEST_EMAIL|TEST_PASSWORD|auth|authentication|credentials|login|log in|sign in)\b/i,Oa=/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/i,$a=/playwright[\s_-]?mcp/i,Na=e=>"mcp__auto-heal-report__generate-report"===e;async function Ba(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 ja(e){return new Promise(t=>{const n=new Y.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 Ma=async(e,t,n)=>{const r=n?"[Y/n]":"[y/N]",s=(await e.question(`${z.cyan("?")} ${t} ${z.gray(r)} `)).trim().toLowerCase();return s?"y"===s||"yes"===s:n},Ha=async e=>{if("single"===e.mode){const t=Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt;zr.initSession(t||"create-from-diff")}else if("verify"===e.mode){const t=Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt;zr.initSession(t||"verify")}else"fix"===e.mode&&zr.initSession(`fix-${e.runId}`);zr.info("Agent session starting",{mode:e.mode}),process.stdout.on("error",ka),process.stderr.on("error",ka);const a=e=>{if("EPIPE"!==e.code)throw e};process.on("uncaughtException",a),zr.debug("Checking authentication");const c=await Qr({autoLogin:"chat"===e.mode||"init"===e.mode}),l=Zr(c);zr.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"),m=p&&b.existsSync(f)&&b.statSync(f).isFile(),g=m?t(b.readFileSync(f,"utf8")):{};zr.debug("Environment file",{path:f,exists:m,variableCount:Object.keys(g).length});const w="chat"!==e.mode&&"init"!==e.mode,_="chat"===e.mode,I="chat"===e.mode||"init"===e.mode,E="single"===e.mode,T="verify"===e.mode,S=E||T;let x,A=new Fs;"init"===e.mode&&(x=e.initPreferences??await async function(){if(!process.stdin.isTTY||!process.stdout.isTTY)return{googleAuth:!0,emailPackage:!1};const e=V({input:process.stdin,output:process.stdout});try{return{googleAuth:await Ma(e,"Include Google Auth test helper guidance? (recommended)",!0),emailPackage:await Ma(e,"Install @stablyai/email for inbox testing?",!1)}}finally{e.close()}}());const C="chat"===e.mode?e.getHelpText:void 0,R="verify"===e.mode?(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt).trim():"";let P="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&&P&&zr.info("[verify] Using URL extracted from prompt",{url:P}),"verify"!==e.mode||P||(P=await async function(){for(const e of La)if(await ja(e))return`http://localhost:${e}`}(),P?zr.info("[verify] Detected local application URL",{url:P}):zr.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=b.existsSync(i),c=a?await b.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&&Da.test(e))(r))({envEmail:process.env.TEST_EMAIL??t.TEST_EMAIL,envPassword:process.env.TEST_PASSWORD??t.TEST_PASSWORD,promptIncludesEmail:Oa.test(s),stablyMdContent:c}),p=!a;if(!u&&!d&&!p)return{resolvedUrl:l};const f=V({input:process.stdin,output:process.stdout}),h=async(n,r)=>{const s=b.existsSync(e)?await b.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 b.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 Ma(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 Ma(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 b.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 b.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 b.promises.writeFile(i,n,"utf8")}}return{resolvedUrl:l}}finally{f.close()}}({envFilePath:f,envFromFile:g,initialUrl:P,verifyPromptText:R,workingDir:d});P=e.resolvedUrl?.trim()||P}"verify"!==e.mode||P||zr.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 k={log:[],promptDisplay:W(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 U,L,D,O,$=w,N=!1,B=!1,j=0,M=0,H=!1;const F=[];let Y,K,J=[],X=!1,Z=!1,ee=0;const te=new Map,ne=[],re=e=>{ne.push(e)},se=new Map;let oe=null,ie=!1,ae=!1;const ce=Date.now();let le,ue="fix"===e.mode?{suiteId:e.runId,phase:"initializing",totalTests:null,fixedTests:0,failedTests:0,currentTestDescription:null,lastTestDescription:null,startedAt:ce,endedAt:null,isError:!1,updatedAt:ce,recentActivity:[],workers:[{id:Ua,testDescription:"Orchestrator",workerType:"main",status:"running",summary:null,startedAt:ce,endedAt:null,activity:[]}]}:null;const de=new Set,pe=(e,t)=>{if(!ue)return;const n=ue.workers.map(n=>{if(n.id!==e)return n;const r=[...n.activity,{...t,timestamp:Date.now()}].slice(-15);return{...n,activity:r}});me({workers:n})},fe=e=>{if(!ue)return;const t=[...ue.recentActivity,{...e,timestamp:Date.now()}].slice(-10);me({recentActivity:t})},he=e=>(ue?.workers??[]).map(t=>t.id===Ua?{...t,status:e?"failed":"succeeded",endedAt:t.endedAt??Date.now()}:"running"===t.status?{...t,status:"failed",endedAt:Date.now()}:t),me=e=>{ue&&!le?.isClosed&&(ue={...ue,...e,updatedAt:Date.now()},le?.sendProgress(ue))},ge=async t=>{if("fix"===e.mode){if("STARTED"===t){if(ie)return;ie=!0}else{if(ae)return;ae=!0}try{await(async({authHeader:e,orgId:t,runId:n,status:r})=>{const s=await(o={auth:e,body:{status:r},client:or(),headers:rs(t),path:{runId:n}},(o.client??zn).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{}}},ye=Date.now();let be,ve=null;const Ae=e=>{ve&&!be?.isClosed&&(ve={...ve,...e,updatedAt:Date.now()},be?.sendProgress(ve))},Re=e=>{if(!ve)return;const t=[...ve.recentActivity,{...e,timestamp:Date.now()}].slice(-10);Ae({recentActivity:t})};let Pe;const ke=(e.mode,!0);zr.info("[session] Checking session creation",{mode:e.mode,shouldCreateSession:ke});try{zr.info("[session] Creating progress session",{mode:e.mode,projectId:Xr(c)});const t=await async function({agentMode:e,authHeader:t,orgId:n,projectId:r,runId:s,fetchImpl:o=fetch,apiUrl:i=Qn}){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:Xr(c),..."fix"===e.mode?{runId:e.runId}:{}}),{sessionId:n,sessionMode:r}=t;if(Pe=n,S){const t="single"===e.mode||"verify"===e.mode?Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt:null,r=Gs(d);ve={sessionId:n,phase:"initializing",startedAt:ye,endedAt:null,isError:!1,updatedAt:ye,currentActivity:null,filesCreated:[],recentActivity:[],prompt:t||null,environment:{gitBranch:r?.branch??null,workingDirectory:d,nodeVersion:process.version,cliVersion:Jn}},be=new ps({authHeader:l,orgId:u,sessionId:n,onUserMessage:e=>{A&&(zr.info("[ws] Injecting web UI message into agent",{contentLength:e.length}),Re({type:"user_message",summary:e}),Me({text:`[Web] ${e}`}),A.pushText(`[Message from web UI user]: ${e}`),$||($=!0,Ke({status:"running"})))}}),be.start(),Ae({phase:"initializing"})}zr.info(`[${r}] Progress session created`,{sessionId:n})}catch(e){const t=e instanceof Error?e.message:String(e);zr.warn(`[progress] Session creation failed (non-fatal): ${t}`)}const Ue={current:e=>{}},Le={current:async()=>{}};let De;const{addSubagentActivity:Oe,addSubagentStart:$e,addTool:Ne,addToolResult:Be,appendText:je,appendUserMessage:Me,cleanup:He,setExiting:Fe,setRunningLabel:Ge,setStatus:We,setSubagentStatus:Ye,updateFixProgress:Ve}=await(async(e,t)=>{const{Box:n,Static:r,Text:s,render:o,useInput:i}=await import("ink"),a=!!process.stdin.isTTY,c=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],l=()=>Se(s,{inverse:!0,children:" "}),u=(({Box:e,Text:t,useInput:n},r,s)=>function({onChoice:o,prompt:i}){const[a,c]=we(0),[l,u]=we(!1),[d,p]=we(""),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=co(i.toolName),m=ao(i.toolName,i.input);return xe(e,{borderColor:"yellow",borderStyle:"round",flexDirection:"column",marginTop:1,paddingX:1,paddingY:0,children:[Se(t,{bold:!0,color:"yellow",children:"Permission Required"}),xe(e,{flexDirection:"column",marginTop:1,children:[Se(t,{color:"gray",dimColor:!0,children:h}),null!=m&&xe(t,{color:"gray",children:[" ",m]})]}),null!=i.decisionReason&&Se(e,{marginTop:1,children:xe(t,{color:"gray",children:["Reason: ",i.decisionReason]})}),xe(e,l?{flexDirection:"column",marginTop:1,children:[Se(t,{color:"gray",children:"Enter message for AI (press Enter to submit, Esc to cancel):"}),xe(t,{children:[Se(t,{color:"yellow",children:">"})," ",d,Se(r,{})]})]}:{flexDirection:"column",marginTop:1,children:[Se(t,{color:"gray",children:"Use ↑↓ arrows or number keys to select:"}),f.map((e,n)=>Se(t,{children:xe(t,{color:n===a?"cyan":void 0,children:[n===a?"❯":" "," ",n+1,". ",e.label]})},e.value))]})]})})({Box:n,Text:s,useInput:i},l,a),d=(({Cursor:e,inkComponents:{Box:t,Static:n,Text:r,useInput:s},isInitMode:o,isRawModeSupported:i,PermissionPrompt:a,Spinner:c})=>{const l=({progress:e})=>{const[n,s]=we(Date.now());Ie(()=>{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),c=i%60,l=a>0?`${a}m ${c.toString().padStart(2,"0")}s`:`${c}s`,{label:u,color:d}={initializing:{label:"Fetching test results",color:"gray"},triage:{label:"Triaging failures",color:"yellow"},fixing:{label:"Fixing tests",color:"cyan"},debugging:{label:"Debugging tests",color:"magenta"},validation:{label:"Validating fixes",color:"blue"},complete:{label:"Complete",color:"green"}}[e.phase],p=e.fixedTests+e.failedTests,f=("fixing"===e.phase||"debugging"===e.phase)&&p>0?null!==e.totalTests?` (fixed ${e.fixedTests}/${e.totalTests}${e.failedTests>0?`, failed ${e.failedTests}`:""})`:` (fixed ${e.fixedTests}${e.failedTests>0?`, failed ${e.failedTests}`:""})`:"";return Se(t,{flexDirection:"column",children:xe(r,{children:[Se(r,{color:d,bold:!0,children:u}),Se(r,{color:"gray",children:f}),xe(r,{color:"gray",children:[" [",l,"]"]})]})})},u=({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?"yellow":"green",l=e.isError?"Fix stopped":"Fix complete";return xe(t,{flexDirection:"column",children:[xe(r,{color:c,bold:!0,children:[l," in ",a]}),null!==e.totalTests&&xe(r,{color:"gray",children:[e.fixedTests,"/",e.totalTests," tests fixed",e.failedTests>0?`, ${e.failedTests} failed`:""]})]})},d=e=>{if("tool"===e.kind)return xe(r,{color:"gray",dimColor:!0,children:["• ",e.content]},e.id);if("text"===e.kind){const t=e.content.indexOf("Summary:");if(-1===t)return null;const n=e.content.slice(t).trimEnd();return Se(r,{children:n},e.id)}return"user"===e.kind?xe(r,{color:"cyan",children:["You: ",e.content]},e.id):null},p=e=>{if("subagent"===e.kind&&e.subagent){const{subagent:n}=e,s="complete"===n.status?"green":"error"===n.status?"red":"yellow";return xe(t,{flexDirection:"column",marginTop:1,children:[xe(r,{children:[Se(r,{color:s,bold:!0,children:"Agent"}),n.description?xe(r,{color:"gray",children:[" (",n.description,")"]}):null]}),n.activities.length>0&&Se(t,{flexDirection:"column",marginLeft:2,children:n.activities.map(e=>(e=>"tool"===e.kind?xe(r,{color:"gray",dimColor:!0,children:["• ",e.content]},e.id):"tool_result"===e.kind||"text"===e.kind?Se(r,{color:"gray",children:e.content},e.id):null)(e))})]},e.id)}return"tool"===e.kind?xe(r,{color:"gray",dimColor:!0,children:["• ",e.content]},e.id):"tool_result"===e.kind?Se(r,{color:"gray",children:e.content},e.id):"user"===e.kind?xe(r,{color:"cyan",children:["You: ",e.content]},e.id):Se(r,{children:e.content},e.id)},f="vscode"===process.env.TERM_PROGRAM,h=(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},m=(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},y=(e,t)=>{const n=e.indexOf("\n",t);return-1===n?e.length:n};return function({onExit:b,onPermissionChoice:v,onSend:w,showSpinnerImmediately:_,state:I}){const[E,T]=we({value:"",cursor:0}),S=E.value,x=E.cursor,A=_e(!1),C=_e(void 0),[R,P]=we(!1),k=_e(0),U=_e(!1),L=I.log.at(-1),D="text"===L?.kind&&"running"===I.status,O=I.log.findIndex(e=>"subagent"===e.kind&&"running"===e.subagent?.status),$=f?0:-1!==O?O:D?I.log.length-1:I.log.length;Ie(()=>{I.log.length<k.current&&(k.current=0),$>k.current&&(k.current=$)},[I.log.length,$]);const N=I.log.slice(0,k.current),B=I.log.slice(k.current),j=!!I.permissionPrompt,M=Ee(async()=>{A.current?(C.current&&clearTimeout(C.current),await(b?.()),process.exit(0)):(A.current=!0,P(!0),C.current=setTimeout(()=>{A.current=!1,P(!1)},2e3))},[b]);s((e,t)=>{t.ctrl&&"c"===e&&M().catch(()=>process.exit(1))},{isActive:i}),Ie(()=>{if(j||!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&&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~")){U.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&&(U.current=!1),void e(s)}if(n.includes("[201~")){const t=n.slice(0,n.indexOf("[201~"));return e(t),void(U.current=!1)}U.current?e(n):""!==n&&"[1;5~"!==n?""!==n&&"[4;5~"!==n?""!==n&&"[1~"!==n&&"OH"!==n&&"[7~"!==n?""!==n&&"[4~"!==n&&"OF"!==n&&"[8~"!==n||T(e=>({...e,cursor:y(e.value,e.cursor)})):T(e=>({...e,cursor:g(e.value,e.cursor)})):T(e=>({...e,cursor:e.value.length})):T(e=>({...e,cursor:0}))};return process.stdin.on("data",t),()=>{process.stdin.off("data",t),process.stdout.isTTY&&process.stdout.write("[?2004l")}},[j,w]),s((e,t)=>{if(!t.ctrl||"c"!==e){if(t.return){if(U.current)return;const e=S.trim();return e&&w?.(e),void T({value:"",cursor:0})}t.ctrl&&"w"===e||t.ctrl&&t.backspace?T(e=>{const t=h(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?T(e=>({...e,cursor:h(e.value,e.cursor)})):t.ctrl&&t.rightArrow||t.meta&&"f"===e?T(e=>({...e,cursor:m(e.value,e.cursor)})):t.leftArrow?T(e=>({...e,cursor:Math.max(0,e.cursor-1)})):t.rightArrow?T(e=>({...e,cursor:Math.min(e.value.length,e.cursor+1)})):t.ctrl&&"a"===e?T(e=>({...e,cursor:0})):t.ctrl&&"e"===e?T(e=>({...e,cursor:e.value.length})):!e||t.ctrl||t.meta||t.escape||e.includes("")||/^\[./.test(e)||/^O[A-D]$/.test(e)||T(t=>({value:t.value.slice(0,t.cursor)+e+t.value.slice(t.cursor),cursor:t.cursor+e.length})):T(e=>e.cursor>0?{value:e.value.slice(0,e.cursor-1)+e.value.slice(e.cursor),cursor:e.cursor-1}:e)}},{isActive:i&&!!w&&!j});const H=Te(()=>"running"===I.status?Se(c,{label:I.runningLabel??"Working"}):"success"!==I.status?Se(r,{color:"red",children:"✖ Failed"}):void 0,[I.runningLabel,I.status]),F=!(_||!w||"running"!==I.status||0!==I.log.length||I.resultText||I.errorText),G="running"===I.status&&!F||I.log.length>0||I.resultText||I.errorText||"running"!==I.status;return xe(t,{flexDirection:"column",children:[Se(n,{items:["header"],children:()=>xe(t,{flexDirection:"column",flexShrink:0,children:[Se(r,{color:"cyan",bold:!0,children:"Stably Agent"}),Se(t,{flexDirection:"column",marginTop:1,children:Se(r,{color:"gray",children:I.promptDisplay})})]},"header")}),N.length>0&&Se(n,{items:N,children:e=>o?d(e):p(e)}),B.length>0&&Se(t,{flexDirection:"column",children:B.map(e=>o?d(e):p(e))}),"error"===I.status&&I.errorText&&Se(t,{marginTop:1,children:Se(r,{color:"red",children:I.errorText})}),"success"===I.status&&I.resultText&&Se(t,{marginTop:1,children:Se(r,{children:I.resultText})}),G&&Se(t,{flexDirection:"column",flexShrink:0,marginTop:1,children:"running"===I.status&&I.fixProgress?xe(t,{flexDirection:"column",children:[xe(t,{children:[Se(c,{}),Se(r,{children:" "}),Se(l,{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),a=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 xe(t,{flexDirection:"column",children:[xe(r,{children:[" ",Se(c,{}),xe(r,{color:"gray",children:[n.description||n.subagentType||"worker",o>0?` (${o} ${1===o?"cycle":"cycles"})`:""]})]}),a&&xe(r,{color:"gray",dimColor:!0,children:[" • ",a.content]}),l&&xe(r,{color:"gray",dimColor:!0,children:[" ",l]})]},e.id)})]}):"success"!==I.status&&"error"!==I.status||!I.fixProgress?H:Se(u,{progress:I.fixProgress})}),null!=I.permissionPrompt&&null!=v&&Se(a,{onChoice:v,prompt:I.permissionPrompt}),null!=w&&null==I.permissionPrompt&&!I.isExiting&&xe(t,{borderColor:"gray",borderStyle:"round",flexDirection:"column",flexShrink:0,marginTop:1,paddingX:1,paddingY:0,children:[Se(r,{color:"gray",children:"Type a message and press Enter. Press Ctrl+C to exit."}),xe(r,{children:[Se(r,{color:"yellow",children:">"})," ",S.slice(0,x),Se(e,{}),S.slice(x)]})]}),R&&xe(t,{marginTop:1,flexDirection:"column",children:[Se(r,{color:"yellow",children:"Press Ctrl+C again to exit"}),Or&&xe(r,{color:"gray",children:["Debug log: ",jr]})]})]})}})({Cursor:l,inkComponents:{Box:n,Static:r,Text:s,useInput:i},isInitMode:t?.isInitMode,isRawModeSupported:a,PermissionPrompt:u,Spinner:({label:e})=>{const[t,n]=we(0);return Ie(()=>{const e=setInterval(()=>n(e=>(e+1)%c.length),80);return()=>clearInterval(e)},[]),xe(s,{color:"yellow",children:[c[t]," ",e]})}});let p=e;t?.isFixMode&&(p.fixProgress={phase:"initializing",totalTests:null,fixedTests:0,failedTests:0,currentTestDescription:null,lastTestDescription:null,startedAt:Date.now(),endedAt:null,isError:!1});const f={current:(e,t)=>{}},h=o(Se(d,{onExit:t?.onExit,onPermissionChoice:(e,t)=>f.current(e,t),onSend:t?.onSend,showSpinnerImmediately:t?.showSpinnerImmediately,state:p}),{exitOnCtrlC:!1}),m=()=>{p={...p},h.rerender(Se(d,{onExit:t?.onExit,onPermissionChoice:(e,t)=>f.current(e,t),onSend:t?.onSend,showSpinnerImmediately:t?.showSpinnerImmediately,state:p}))},g=({text:e})=>{e&&(p.log=[...p.log,{content:e,id:p.log.length,kind:"user"}],m())},y=new Map;return{addSubagentActivity:({toolUseId:e,kind:t,content:n})=>{const r=y.get(e);if(void 0===r)return void console.error("[addSubagentActivity] No entry index for toolUseId:",e);const s=p.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});p.log=[...p.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=p.log.length;if(y.set(e,r),p.log=[...p.log,{content:"",id:r,kind:"subagent",subagent:{toolUseId:e,subagentType:t,description:n,status:"running",activities:[]}}],p.fixProgress)if("triage"===t&&"initializing"===p.fixProgress.phase)p.fixProgress={...p.fixProgress,phase:"triage"};else if("code-worker"===t){const e=(p.fixProgress.totalTests??0)+1,t=n||null;p.fixProgress={...p.fixProgress,phase:"fixing",totalTests:e,currentTestDescription:t,lastTestDescription:t??p.fixProgress.lastTestDescription}}else if("browser-worker"===t){const e=(p.fixProgress.totalTests??0)+1,t=n||null;p.fixProgress={...p.fixProgress,phase:"debugging",totalTests:e,currentTestDescription:t,lastTestDescription:t??p.fixProgress.lastTestDescription}}else"validation"===t?p.fixProgress={...p.fixProgress,phase:"validation",currentTestDescription:null}:"context"===t&&(p.fixProgress={...p.fixProgress,currentTestDescription:n||p.fixProgress.currentTestDescription});m()},addTool:({rawName:e,toolInput:t})=>{const n=co(e),r=ao(e,t),s=r?`${n} (${r})`:n;p.log=[...p.log,{content:s,id:p.log.length,kind:"tool"}],m()},addToolResult:({message:e})=>{p.log=[...p.log,{content:e,id:p.log.length,kind:"tool_result"}],m()},appendText:({text:e})=>{if(!e)return;const t=p.log.at(-1),n="text"!==t?.kind?e.replace(/^\s*\n+/,""):e;p.log="text"===t?.kind?[...p.log.slice(0,-1),{...t,content:`${t.content}${n}`}]:[...p.log,{content:n,id:p.log.length,kind:"text"}],m()},appendUserMessage:g,cleanup:async()=>{const e=h.waitUntilExit();h.unmount(),await e},setExiting:()=>{p.isExiting=!0,m()},setRunningLabel:({label:e})=>{p.runningLabel=e,m()},setStatus:({error:e,result:t,status:n})=>{p.errorText=e,p.resultText=t,p.status=n,m()},setSubagentStatus:({toolUseId:e,status:t})=>{const n=y.get(e);if(void 0===n)return;const r=p.log[n];"subagent"===r?.kind&&r.subagent&&(r.subagent.status=t,!p.fixProgress||"code-worker"!==r.subagent.subagentType&&"browser-worker"!==r.subagent.subagentType||("complete"===t?p.fixProgress={...p.fixProgress,fixedTests:p.fixProgress.fixedTests+1,currentTestDescription:null}:"error"===t&&(p.fixProgress={...p.fixProgress,failedTests:p.fixProgress.failedTests+1,currentTestDescription:null})),p.log=[...p.log],m(),"complete"!==t&&"error"!==t||y.delete(e))},showPermissionPrompt:e=>new Promise(t=>{f.current=(n,r)=>{if(p.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";g({text:e}),t({behavior:"deny",message:e,interrupt:!1})}},p.permissionPrompt={...e,resolve:t},m()}),updateFixProgress:t?.isFixMode?e=>{p.fixProgress&&(p.fixProgress={...p.fixProgress,...e},m())}:void 0}})(k,"init"===e.mode?{onExit:()=>Le.current(),onSend:e=>Ue.current(e),showSpinnerImmediately:!0,isInitMode:!0}:"chat"===e.mode?{onExit:()=>Le.current(),onSend:e=>Ue.current(e)}:"fix"===e.mode?{onExit:()=>Le.current(),isFixMode:!0}:{onExit:()=>Le.current()});let ze=k.status;const Ke=({error:e,result:t,status:n})=>{ze=n,We({error:e,result:t,status:n})};let qe;T&&(je({text:"Starting verification...\n"}),je(P?{text:`Target URL: ${P}\n`}:{text:"Target URL: auto-detect (agent may infer from project config)\n"}),Ge({label:"Calibrating verification flow..."})),Ue.current=e=>{const t=e.trim();if(_&&!zr.getLogFilePath()&&zr.initSession(t||"chat"),zr.debug("User message",{text:t}),"/help"===t){$&&A&&(N=!0,U?.interrupt?.(),A.allowNextTurn(),$=!1),"running"===ze&&Ke({status:"success"}),Me({text:e});const t=C?.();return void je({text:t??"Help is not available in this session."})}const n=D||B&&$;if(_&&(j+=1,O=void 0,n||(H=!1,Ge({label:void 0}))),A){if(n)return Ke({status:"running"}),Me({text:e}),void F.push(e);if(!B||$||D||(B=!1),$)return Ke({status:"running"}),Me({text:e}),A.pushText(e),void(M+=1);Ke({status:"running"}),Me({text:e}),re({role:"user",content:e,timestamp:(new Date).toISOString()}),A.pushText(e),$=!0}};let Je="",Qe="";const Xe=[],Ze=[],et=[];let tt;const nt=await(async e=>{try{const t=await pr(e,"stably.yaml");if(!t)return void zr.debug("No stably.yaml found");const n=await Q(t,"utf-8");if(!n.trim())return;const r=Ce(n),s=va.parse(r.toJS()),o=s.agent?.fix?.maxTurnsPerIssue,i=s.agent?.fix?.maxParallelWorkers,a=!!s.agent?.fix?.rules;return zr.debug(`Loaded stably.yaml: maxTurnsPerIssue=${o??"default"}, maxParallelWorkers=${i??"default"}, hasRules=${a}`,{path:t,config:s.agent}),s}catch(e){return void zr.warn("Failed to parse stably.yaml",{error:e})}})(d),rt=nt?.agent?.fix?.skipAfterConsecutiveUnfixed,st=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 Q(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 tt=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: ${tt}]`}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,P);if("fix"===e.mode)try{zr.info("[fix] Fetching autoheal context",{runId:e.runId,skipAfterConsecutiveUnfixed:rt});const t=Date.now(),{context:n,autohealReportUrl:r,skippedTests:s}=await(async({authHeader:e,orgId:t,runId:n,skipAfterConsecutiveUnfixed:r})=>{zr.debug("Fetching autoheal context",{runId:n,skipAfterConsecutiveUnfixed:r});const s=await(o={auth:e,client:or(),headers:rs(t),path:{runId:n},query:null!=r?{skipAfterConsecutiveUnfixed:r}:{}},(o.client??zn).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-context",...o}));var o;if(404===s.response.status)throw zr.warn("Autoheal context not found",{runId:n,status:404}),new Error(`Run ID "${n}" was not found.`);if(401===s.response.status)throw zr.warn("Autoheal context fetch unauthorized",{runId:n,status:401}),new Error("Unauthorized: failed to fetch autoheal context (401).");if(422===s.response.status)throw zr.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=ss.safeParse(s.data);if(e.success)return zr.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??[]};throw zr.warn("Autoheal context response invalid",{runId:n}),new Error("Autoheal context response missing or invalid context.")}throw zr.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:rt});if(zr.info("[fix] Autoheal context fetched",{runId:e.runId,durationMs:Date.now()-t,contextLength:n.length,skippedTestCount:s.length}),qe=r,s.length>0){zr.info(`[fix] Skipping ${s.length} test(s) that failed to be fixed ${rt}+ consecutive times`);for(const e of s)zr.info(`[fix] Skipped: ${e.testIdentifier} — ${e.testTitle} (unfixed ${e.consecutiveUnfixedCount}x)`)}return n.includes("No failing tests to fix (all were skipped).")&&(zr.info("[fix] All failing tests were skipped — nothing to fix"),Ke({status:"success",result:`All failing tests skipped (unfixed ${rt}+ consecutive times). Nothing to fix.`}),await He(),process.exit(0)),le||(zr.info("[fix] Creating WebSocket progress reporter"),le=new ds({authHeader:l,orgId:u,runId:e.runId,onUserMessage:e=>{if(zr.info("[ws] Injecting web UI message into fix agent",{contentLength:e.length}),pe(Ua,{type:"user_message",summary:e}),fe({type:"user_message",summary:e}),Me({text:`[Web] ${e}`}),!$)return A.pushText(`[Message from web UI user]: ${e}`),$=!0,void A.allowNextTurn();X||Date.now()-ee<2e3?A.pushText(`[Message from web UI user]: ${e}`):(J.push(e),Y&&clearTimeout(Y),Y=setTimeout(()=>{Y=void 0;const e=[...J];J=[],ee=Date.now(),on(e)},500))}}),le.start(),me({phase:"initializing"})),ge("STARTED"),n}catch(e){const t=e instanceof Error?e.message:"Failed to fetch autoheal context.";zr.error("[fix] Failed to fetch autoheal context",{error:t}),Ke({error:t,status:"error"}),await He(),process.exit(1)}if("init"===e.mode){const e=x??{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""})(),ot=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(v(t))for(const e of Ws){const n=r.join(t,`playwright.config${e}`);if(v(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),it="fix"===e.mode?nt?.agent?.fix?.maxTurnsPerIssue:void 0,at="fix"===e.mode?nt?.agent?.fix?.maxParallelWorkers:void 0,ct="fix"===e.mode?nt?.agent?.fix?.rules:void 0,lt=nt?.agent?.fix?.maxBudgetUsd??50,ut="verify"===e.mode?e.maxBudgetUsd??5:void 0,dt="fix"===e.mode?lt:T?ut:void 0,pt="init"!==e.mode,ft="single"===e.mode?await(async e=>{const t=await wa(e,"STABLY-CREATE.md");return t?.content})(d):void 0,ht=await(e=>wa(e,"STABLY.md"))(d),mt=ht?.content;T&&(Ge({label:"Assembling verification context..."}),je({text:"Assembling workspace context...\n"})),zr.info("[fix] Fetching system prompt and subagent definitions",{mode:e.mode,maxTurnsOverride:it,maxBudgetUsd:dt,hasCustomRules:!!ct,hasCreateRules:!!ft,hasStablyMd:!!mt,stablyMdPath:ht?.path}),ht&&zr.info(`STABLY.md loaded (${ht.content.length} chars)`,{path:ht.path});const gt=await ns(),yt=gt?Object.keys(gt.variables):[],bt=[...new Set([...Object.keys(g),...yt])],vt=Date.now(),[{systemPrompt:wt,prContext:_t},It]=await Promise.all([Ks({allowedEnvVars:bt,mode:e.mode,workspaceInfo:ot,authHeader:l,customHeader:"single"===e.mode?e.customHeader:void 0,maxParallelWorkers:at}),pt?ha({authHeader:l,mode:e.mode,maxTurnsOverride:it}):Promise.resolve({})]);zr.info("[fix] System prompt and subagents fetched",{durationMs:Date.now()-vt,systemPromptSize:wt.length,subagentCount:Object.keys(It).length,maxTurnsOverride:it??"default",hasPrContext:!!_t});const Et={...g,...process.env},Tt={};for(const[e,t]of Object.entries(Et))fa.has(e)||void 0===t||(Tt[e]=t);const St=!0;zr.debug("AI proxy configuration",{useStablyAiProxy:St,wantsBypassProxy:!1,wantsUseOllama:!1}),zr.info("[fix] Acquiring AI proxy key",{useStablyAiProxy:St});const xt=Date.now(),At=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??zn).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:pa(e,a)}}return i.data?{key:i.data.key}:{error:pa("No data in response",a)}}catch(e){const t=e instanceof Error?e.message:"Unknown error";return{error:pa(t)}}var o}({auth:l,client:or(),source:"cli"}),Ct=At?.key;if(zr.info("[fix] AI proxy key acquired",{durationMs:Date.now()-xt,success:!!Ct,hasError:!!At?.error}),!Ct){const e=At?.error?.message?`Unable to make AI calls: ${At.error.message}`:"Unable to make AI calls. Check if you are authenticated.";zr.warn("Failed to get proxy API key",{error:At?.error?.message}),Ke({error:e,status:"error"}),await He(),zr.flush(),zr.printLogFileInfo(),process.exit(1)}zr.debug("Proxy API key acquired",{success:!!Ct});const Rt=await ts(),Pt=gt?.sensitiveValues.length?{STABLY_SENSITIVE_VALUES:Buffer.from(JSON.stringify(gt.sensitiveValues)).toString("base64")}:{},kt=Rt?Object.fromEntries(Object.entries(es({...gt?.variables,...Pt,...Rt})).filter(e=>null!=e[1])):gt?Object.fromEntries(Object.entries(es({...gt.variables,...Pt})).filter(e=>null!=e[1])):void 0,Ut="init"===e.mode,Lt="fix"===e.mode,Dt=Lt?Sn.createLocal({workingDir:d}):void 0;Dt&&await Dt.captureSnapshot();const Ot=()=>{Ut&&function({workingDir:e,options:t={}}){try{!function(e){const t=n.join(e,"package.json");if(!y.existsSync(t))return;const r=JSON.parse(y.readFileSync(t,"utf-8"));if({...r.dependencies,...r.devDependencies}.stably)return void zr.debug("stably package already present in dependencies");zr.info("stably package missing from devDependencies, installing...");const s=function(e){let t=e;for(let e=0;e<5;e++){if(y.existsSync(n.join(t,"pnpm-lock.yaml")))return"pnpm";if(y.existsSync(n.join(t,"yarn.lock")))return"yarn";if(y.existsSync(n.join(t,"bun.lockb"))||y.existsSync(n.join(t,"bun.lock")))return"bun";if(y.existsSync(n.join(t,"package-lock.json"))||y.existsSync(n.join(t,"npm-shrinkwrap.json")))return"npm";const e=n.dirname(t);if(e===t)break;t=e}return"npm"}(e),o="pnpm"===s?"pnpm add -D stably":"yarn"===s?"yarn add -D stably":"bun"===s?"bun add -d stably":"npm install -D stably";try{h(o,{cwd:e,stdio:"pipe",timeout:6e4}),zr.info("stably package installed successfully")}catch(e){zr.warn("Failed to install stably package",{error:String(e)})}}(e)}catch(e){zr.warn("Post-init: ensureStablyDependency failed",{error:String(e)})}try{!function(e,t){const r=["Use Stably CLI for Playwright test runs (better reporting, auto-fix); import from @stablyai/playwright-test for agent.act(), aiAssert, page.extract(), page.getLocatorsByAI()"];t.googleAuth&&r.push(", and use Google Auth methods"),t.emailPackage&&r.push(", and use @stablyai/email Inbox methods for email verification flows");const s=`${r.join("")}.`,o=function(e){const t=["CLAUDE.md","AGENTS.md","AGENT.md","agent.md"];for(const r of t){const t=n.join(e,r);if(!y.existsSync(t))continue;const s=y.readFileSync(t,"utf-8");return/Stably CLI/i.test(s)&&s.includes("@stablyai/playwright-test")?void zr.debug("Agent guidance already present",{file:r}):t}return n.join(e,"AGENTS.md")}(e);if(o){zr.info("Appending Stably guidance",{file:n.basename(o)});try{const e=y.existsSync(o)?y.readFileSync(o,"utf-8"):"",t=e.length>0&&!e.endsWith("\n")?"\n\n":e.length>0?"\n":"";y.writeFileSync(o,`${e}${t}${s}\n`,"utf-8"),zr.info("Agent guidance appended successfully")}catch(e){zr.warn("Failed to update agent guidance file",{error:String(e)})}}}(e,t)}catch(e){zr.warn("Post-init: ensureAgentGuidance failed",{error:String(e)})}}({workingDir:d,options:{googleAuth:x?.googleAuth,emailPackage:x?.emailPackage}})},$t=Ut?sa({onComplete:()=>{Ot(),Ke({status:"success"}),Fe(),A?.finish(),process.exit(0)}}):_?sa({onRestartRequested:()=>{_&&(B=!0,Ke({status:"running"}),Ge({label:"Restarting browser tools..."}),O={createdAtUserMessageSeq:j,attempts:0})}}):void 0,Nt=$t?_?{"stably-agent-control":$t}:{"session-control":$t}:{},Bt=E&&_t?["mcp__create-report"]:[],jt=Ut?Pa:T?Ca:[...Ca,...Lt?["mcp__auto-heal-report"]:[],...Bt],Mt=Ut?Pa:_?[...Ra,"mcp__stably-agent-control"]:T?Ra:[...Ra,...Bt],Ht=E&&_t?{"create-report":ia({prContext:_t,authHeader:l,orgId:u,onReportPosted:e=>{Ae({githubComment:{url:e.commentUrl,prNumber:_t.prNumber}})}})}:{},Ft=Ut?Nt:Lt&&Dt?{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:kt},"auto-heal-report":ra({authHeader:l,diffTracker:Dt,orgId:u,runId:e.runId,workingDir:d}),"run-history":ua({authHeader:l,orgId:u,projectId:Xr(c)}),...Nt}:T?{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:kt},...Nt}:{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:kt},...Nt,...Ht},Gt="single"===e.mode,Wt=Ut?[]:[{hooks:[async e=>{const t=Rs(e);if(!t)return{decision:"approve"};let n=!1;const r=t.map(e=>As(e)?e.text.length<=4e4?e:(n=!0,{...e,text:`${e.text.slice(0,4e4)}...[truncated to 40000 characters]`}):e);return n?{decision:"approve",hookSpecificOutput:{hookEventName:"PostToolUse",updatedMCPToolOutput:r}}:{decision:"approve"}}],matcher:"mcp__playwright-test__.*"},{matcher:"mcp__playwright-test__test_run",hooks:[$s({onResult:e=>Be({message:e})})]},{matcher:"mcp__playwright-test__test_debug",hooks:[Ns({onResult:e=>Be({message:e})})]},...Gt?[{matcher:"Write",hooks:[js({onFileCreated:e=>{if(Xe.includes(e)||Xe.push(e),ve){if(ve.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}=ve,o=(async()=>{try{const r=await b.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:or(),headers:rs(s),path:{sessionId:o}},(a.client??zn).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=fs.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 is({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:or(),headers:rs(s),path:{sessionId:o}},(a.client??zn).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 zr.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};Ze.push(i),Ae({filesCreated:[...Ze]})}catch(t){zr.warn("Failed to upload created file",{filePath:e,error:t instanceof Error?t.message:String(t)});const r={path:e,filename:n,bucketPath:null};Ze.push(r),Ae({filesCreated:[...Ze]})}})();et.push(o)}}})]}]:[]],Yt=Ut?[]:[{matcher:"mcp__playwright-test__.*",hooks:[async()=>B?{decision:"block",reason:'MCP restart is pending. This tool cannot be used until the restart completes. End your turn now - the restart only happens AFTER your turn ends. The system will send "[SYSTEM] MCP servers were restarted successfully" when ready.',systemMessage:"Tool call blocked: MCP restart pending"}:{decision:"approve"}]},...Lt?[{matcher:"Read",hooks:[vs({action:"reading",pathKey:"file_path"})]},{matcher:"Write",hooks:[vs({action:"writing",pathKey:"file_path"})]},{matcher:"Edit",hooks:[vs({action:"editing",pathKey:"file_path"})]},{matcher:"Grep",hooks:[vs({action:"searching",pathKey:"path"})]},{matcher:"Glob",hooks:[vs({action:"searching",pathKey:"path"})]},{matcher:"Bash",hooks:[xs({workspaceBoundary:d})]}]:[],{matcher:"mcp__playwright-test__browser_(type|navigate|evaluate|fill_form)",hooks:[Os({envVars:{...g,...gt?.variables}})]}],Vt=Object.keys(It).length>0?It:void 0,zt={...Tt};zt.MCP_TOOL_TIMEOUT=String(6e5),Ct&&(zt.ANTHROPIC_API_KEY=Ct,zt.ANTHROPIC_BASE_URL=tr,zt.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS="1",zt.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC="1");const Kt=process.env.STABLY_AGENT_MODEL??"claude-opus-4-6",qt=Lt?"env"===c.type?c.auth.apiKey:c.auth.accessToken:void 0,Jt=Lt?Xr(c):void 0;Lt&&qt&&Jt&&(zt.STABLY_API_KEY=qt,zt.STABLY_PROJECT_ID=Jt);const Qt=ct?`\n\n## Custom Rules\n${ct}`:"",Xt=ft?`\n\n## Custom Test Generation Rules\n${ft}`:"",Zt=mt?`\n\n## Project Rules (STABLY.md)\n${mt}`:"",en=wt+Qt+Xt+Zt;zr.debug("[fix] Final system prompt assembled",{baseSize:wt.length,fixRulesSize:Qt.length,createRulesSize:Xt.length,stablyMdSize:Zt.length,finalSize:en.length});const tn=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 ba(t)?t:void 0}();if(e)return e;const t=r.join(ma,"stably-plugin-cli");if(ba(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}}(ma))for(const t of ya){const n=r.join(e,t);if(ba(n))return n}}();if(e)return{type:"local",path:e}}(),nn=()=>(zr.info("[fix] Starting SDK query",{model:Kt,tools:jt,mcpServers:Object.keys(Ft),resumeSessionId:L??null,subagentsEnabled:!!Vt,subagentCount:Object.keys(It).length,useStablyAiProxy:St,aiProxyUrl:tr,anthropicBaseUrl:void 0,stablyPluginPath:tn?.path,stablyPluginExists:!!tn}),G({options:{executableArgs:["--max-old-space-size=4096"],tools:jt,allowedTools:Mt,...null!=dt?{maxBudgetUsd:dt}:{},betas:[],canUseTool:(e,t)=>(zr.debug("[fix] canUseTool called",{toolName:e}),Promise.resolve({behavior:"allow",updatedInput:t})),cwd:d,env:zt,hooks:{PostToolUse:Wt,PreToolUse:Yt},includePartialMessages:!0,agents:Vt,mcpServers:Ft,model:Kt,permissionMode:"default",plugins:tn?[tn]:void 0,systemPrompt:en,...L?{resume:L}:{}},prompt:A??st})),rn=()=>{if(A&&0!==F.length){for(const e of F)A.pushText(e);F.length=0,$=!0,Ke({status:"running"})}},sn=async()=>{_&&(D||(D=(async()=>{zr.info("Restarting MCP servers for chat mode"),Ke({status:"running"}),Ge({label:"Restarting browser tools..."});try{await(U?.interrupt?.())}catch(e){zr.warn("Failed to interrupt response during MCP restart",{error:e instanceof Error?e.message:String(e)})}await Hs(),A?.finish(),A=new Fs,M=0,$=!1,N=!1,te.clear(),U=nn(),H=!0,Ge({label:"Restarting browser tools..."}),_&&A&&O&&(O.createdAtUserMessageSeq===j?O.attempts>=1||F.length>0?O=void 0:(O.attempts+=1,A.pushText(["[SYSTEM] MCP servers were restarted successfully.","Continue the task using existing conversation context.","Do not ask the user to resend their message unless new input is required."].join("\n")),O=void 0,$=!0,Ke({status:"running"})):O=void 0),rn()})().finally(()=>{D=void 0,rn()})),await D)},on=async e=>{if(w&&$&&!X&&!K)K=(async()=>{zr.info("[fix] Interrupting for user message",{messageCount:e.length,phase:ue?.phase});try{await(U?.interrupt?.())}catch(e){zr.warn("[fix] Failed to interrupt response for user message",{error:e instanceof Error?e.message:String(e)})}await Hs(),A?.finish(),A=new Fs,te.clear(),U=nn();const t=e.map(e=>`[Message from web UI user]: ${e}`).join("\n\n");A.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}`),Z=!0,$=!0})().finally(()=>{K=void 0}),await K;else for(const t of e)A?.pushText(`[Message from web UI user]: ${t}`)};if(Ct){T&&Ge({label:"Checking AI connectivity..."});const e=tr,t=`${e.replace(/\/$/,"")}/v1/messages`;zr.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":Ct,"anthropic-version":"2023-06-01","content-type":"application/json"},body:"{}"}),s=await e.text().catch(()=>""),o=Date.now()-n;zr.debug(`[fix] Pre-flight: ${e.status} in ${o}ms — ${s.slice(0,300)}`),401===e.status||403===e.status?(zr.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."):zr.info("[fix] Pre-flight: AI proxy key valid",{status:e.status,durationMs:o})}catch(t){zr.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{T&&"running"===ze&&Ge({label:void 0})}r&&(je({text:`[stably] ${r}\n`}),Ke({error:r,status:"error"}),await He(),zr.flush(),zr.printLogFileInfo(),process.exit(1))}zr.info("[fix] Creating initial agent query"),T&&(Ge({label:"Initializing verification session..."}),je({text:"Initializing verification session...\n"})),zr.flush(),U=nn(),zr.info("[fix] Agent query created, entering message loop"),"chat"!==e.mode&&(A.pushText(st),ne.push({role:"user",content:st,timestamp:(new Date).toISOString()}));const an=async t=>{De||(De=(async()=>{zr.info("[session] Interrupt requested",{source:t,mode:e.mode}),oe="CANCELED",await ge("CANCELED"),me({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:he(!0)}),await(le?.closeAndWait()),await Promise.allSettled(et),Ae({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0}),await(be?.closeAndWait()),Y&&(clearTimeout(Y),Y=void 0),Fe(),await Hs();try{await(U?.interrupt?.())}catch{}A?.finish(),ne.length>0&&Pe&&await ms({authHeader:l,orgId:u,sessionId:Pe,projectId:Xr(c),history:ne}).catch(e=>{zr.warn("[exit] Failed to upload session history",{error:e instanceof Error?e.message:String(e)})}),He(),zr.flush()})()),await De};Le.current=async()=>{await an("ctrl-c")};let cn=()=>{};cn=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 an("signal"),process.exit(function(e){return"SIGINT"===e?130:143}(e))})()}});let ln=0,un=null,dn=!1;const pn=T?setTimeout(()=>{if(un||"running"!==ze)return;const e="This is taking longer than expected. Please try again.";je({text:`[stably] ${e}\n`}),Ke({error:e,status:"error"});try{U?.interrupt?.()}catch{}A?.finish(),He(),zr.flush(),zr.printLogFileInfo(),process.exit(1)},9e4):void 0;pn?.unref();const fn=setInterval(()=>{const e=Date.now()-ce;un?zr.info("[fix] Watchdog: message loop active",{messageCount:ln,elapsed:e}):(zr.info("[fix] Watchdog: waiting for first SDK message",{elapsed:e}),T&&!dn&&e>=15e3&&(je({text:"Still preparing verification. This can take a bit...\n"}),dn=!0)),zr.flush()},15e3);fn.unref();try{let t=!1;for(;;){if(!U){zr.info("[fix] No response object, exiting message loop");break}t=!1,zr.info("[fix] Entering for-await on SDK response");for await(const n of U){ln++,un||(un=Date.now(),pn&&clearTimeout(pn),T&&Ge({label:void 0}),zr.info("[fix] First SDK message received",{waitDurationMs:un-ce,messageType:n.type,messageSubtype:"subtype"in n?n.subtype:void 0}));const r="session_id"in n&&"string"==typeof n.session_id?n.session_id:void 0;if(r&&r!==L&&(L=r,zr.debug("Captured Claude session id",{sessionId:L})),"stream_event"===n.type){const{event:e}=n;(ln<=5||ln%200==0)&&zr.debug("[fix] Stream event",{msgNum:ln,eventType:e?.type});const t=e&&"object"==typeof e&&"parent_tool_use_id"in e&&"string"==typeof e.parent_tool_use_id?e.parent_tool_use_id:void 0;if("content_block_delta"===e?.type){const{delta:n}=e;if("text_delta"===n?.type&&n.text){if(_&&B&&!t)continue;H&&(H=!1,Ge({label:void 0}));const e=t&&te.has(t)?t:1===te.size?Array.from(te.keys())[0]:void 0;e?Oe({toolUseId:e,kind:"text",content:n.text}):T||je({text:n.text})}}"message_stop"===e?.type&&A&&(X=!1,A.allowNextTurn());continue}if("assistant"===n.type){const t="parent_tool_use_id"in n&&"string"==typeof n.parent_tool_use_id?n.parent_tool_use_id:void 0,{content:r}=n.message??{};if(Array.isArray(r)&&!t){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&&(Je=t,T&&(Qe=Qe?`${Qe}\n\n${t}`:t),zr.debug("Assistant message",{text:T?Sa(t):t}),"fix"===e.mode&&(pe(Ua,{type:"ai_message",summary:t.slice(0,200)}),fe({type:"ai_message",summary:t.slice(0,200)})),S&&Re({type:"ai_message",summary:t.slice(0,200)}),re({role:"assistant",content:t,timestamp:(new Date).toISOString()}))}if(te.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):[];zr.debug("Assistant message with active subagents",{hasParentToolUseId:!!t,parentToolUseId:t,activeSubagentIds:Array.from(te.keys()),toolNames:e,fullMessageKeys:Object.keys(n),rawMessage:JSON.stringify(n).slice(0,500)})}if(Array.isArray(r))for(const n of r){if("tool_use"===n?.type){if("mcp__auto-heal-report__generate-report"===n.name&&(X=!0),"mcp__session-control__restart_mcp_servers"===n.name||"mcp__stably-agent-control__restart_mcp_servers"===n.name){Ne({rawName:n.name,toolInput:n.input});continue}if(n.name.startsWith("mcp__session-control__")||n.name.startsWith("mcp__stably-agent-control__"))continue;if(Na(n.name))continue;if(T&&$a.test(n.name))continue;if(te.size>0&&zr.debug("Tool use detected with active subagents",{toolName:n.name,hasParentToolUseId:!!t,parentToolUseId:t,wouldRouteToSubagent:!!t&&te.has(t),activeSubagentIds:Array.from(te.keys())}),"Task"===n.name){const t=n.input,r=t&&"object"==typeof t?t: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(zr.info("[fix] Subagent started",{subagentType:s,description:o,toolUseId:n.id,activeSubagentCount:te.size+1}),te.set(n.id,{subagentType:s,description:o}),$e({toolUseId:n.id,subagentType:s,description:o}),"fix"===e.mode){if("triage"===s){Ve?.({phase:"triage"});const e={id:n.id,testDescription:"Triage",workerType:"triage",status:"running",summary:null,startedAt:Date.now(),endedAt:null,activity:[]};me({phase:"triage",workers:[...ue?.workers??[],e]})}else if("code-worker"===s){de.add(o||n.id);const e={id:n.id,testDescription:o||n.id,workerType:"code-worker",status:"running",summary:null,startedAt:Date.now(),endedAt:null,activity:[]};Ve?.({phase:"fixing",totalTests:de.size,currentTestDescription:o||null}),me({phase:"fixing",totalTests:de.size,currentTestDescription:o||null,lastTestDescription:o||ue?.lastTestDescription||null,workers:[...ue?.workers??[],e]})}else if("browser-worker"===s){de.add(o||n.id);const e={id:n.id,testDescription:o||n.id,workerType:"browser-worker",status:"running",summary:null,startedAt:Date.now(),endedAt:null,activity:[]};Ve?.({phase:"debugging",totalTests:de.size,currentTestDescription:o||null}),me({phase:"debugging",totalTests:de.size,currentTestDescription:o||null,lastTestDescription:o||ue?.lastTestDescription||null,workers:[...ue?.workers??[],e]})}else"validation"===s?(Ve?.({phase:"validation",currentTestDescription:null}),me({phase:"validation",currentTestDescription:null})):"context"===s&&me({currentTestDescription:o||null});fe({type:"tool_call",summary:`[${s}] ${o}`.trim()})}continue}if(t&&te.has(t)){const r=co(n.name),s=ao(n.name,n.input),o=s?`${r} (${s})`:r;if(zr.debug("Subagent tool called",{tool:n.name,parentToolUseId:t}),Oe({toolUseId:t,kind:"tool",content:o}),"fix"===e.mode){fe({type:"tool_call",summary:o});const e=te.get(t);"code-worker"!==e?.subagentType&&"browser-worker"!==e?.subagentType&&"triage"!==e?.subagentType||pe(t,{type:"tool_call",summary:o})}continue}if(t&&zr.debug("Tool with parent_tool_use_id but no matching subagent",{tool:n.name,parentToolUseId:t,activeSubagentIds:Array.from(te.keys())}),zr.debug("Tool called",{tool:n.name,input:n.input}),Ne({rawName:n.name,toolInput:n.input}),n.id&&se.set(n.id,n.name),re({role:"tool",content:"",timestamp:(new Date).toISOString(),toolName:n.name,toolInput:n.input}),"fix"===e.mode){const e=co(n.name),t=ao(n.name,n.input),r=t?`${e} (${t})`:e;pe(Ua,{type:"tool_call",summary:r}),fe({type:"tool_call",summary:r})}if(E){const e=co(n.name),t=ao(n.name,n.input),r=t?`${e} (${t})`:e;"initializing"===ve?.phase?Ae({phase:"generating",currentActivity:r}):"mcp__playwright-test__test_run"===n.name&&"generating"===ve?.phase?Ae({phase:"testing",currentActivity:r}):Ae({currentActivity:r}),Re({type:"tool_call",summary:r})}if(T){const e=co(n.name),t=ao(n.name,n.input),r=Sa(t?`${e} (${t})`:e);Ae("initializing"===ve?.phase?{phase:"verifying",currentActivity:r}:{currentActivity:r}),Re({type:"tool_call",summary:r})}}if("text"===n?.type){const r="string"==typeof n.text?n.text:"",s=t&&te.has(t)?t:1===te.size?Array.from(te.keys())[0]:void 0;if(s&&r&&(Oe({toolUseId:s,kind:"text",content:r}),"fix"===e.mode)){const e=te.get(s);"code-worker"!==e?.subagentType&&"browser-worker"!==e?.subagentType&&"triage"!==e?.subagentType||pe(s,{type:"ai_message",summary:r.slice(0,200)})}}}continue}if("user"===n.type){const t="message"in n&&n.message&&"object"==typeof n.message&&"content"in n.message?n.message.content:void 0,r="tool_use_result"in n&&n.tool_use_result&&"object"==typeof n.tool_use_result?n.tool_use_result:void 0;if(Array.isArray(t))for(const n of t)if(n&&"object"==typeof n&&"type"in n&&"tool_result"===n.type&&"tool_use_id"in n){const t="string"==typeof n.tool_use_id?n.tool_use_id:void 0,s="is_error"in n&&!0===n.is_error||"error"===r?.status;let o;const i=r?.content??("content"in n?n.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("")),zr.debug("Tool result",{toolUseId:t,isError:s,output:o?.slice(0,500)});const a=5e4,c=t?se.get(t):void 0;if(re({role:"tool_result",content:"",timestamp:(new Date).toISOString(),toolName:c,toolOutput:o?.slice(0,a),isError:s}),t&&te.has(t)){const n=te.get(t);if(zr.info("[fix] Subagent completed",{toolUseId:t,isError:s,subagentType:n?.subagentType,description:n?.description,activeSubagentCount:te.size-1}),o&&Oe({toolUseId:t,kind:"text",content:o}),Ye({toolUseId:t,status:s?"error":"complete"}),"fix"===e.mode&&"triage"===n?.subagentType){const e=s?"failed":"succeeded",n=o?o.slice(0,500):null,r=(ue?.workers??[]).map(r=>r.id===t?{...r,status:e,summary:n,endedAt:Date.now()}:r);me({workers:r})}if("fix"===e.mode&&("code-worker"===n?.subagentType||"browser-worker"===n?.subagentType)){const e=s?"failed":"succeeded",n=o?o.slice(0,500):null,r=(ue?.workers??[]).map(r=>r.id===t?{...r,status:e,summary:n,endedAt:Date.now()}:r);s?(Ve?.({failedTests:(ue?.failedTests??0)+1,currentTestDescription:null}),me({failedTests:(ue?.failedTests??0)+1,currentTestDescription:null,workers:r})):(Ve?.({fixedTests:(ue?.fixedTests??0)+1,currentTestDescription:null}),me({fixedTests:(ue?.fixedTests??0)+1,currentTestDescription:null,workers:r}))}te.delete(t)}}continue}if("result"===n.type){if(zr.info("[fix] Agent result received",{subtype:n.subtype,messageCount:ln,elapsed:Date.now()-ce,activeSubagents:te.size,fixedTests:ue?.fixedTests,failedTests:ue?.failedTests,phase:ue?.phase}),w){if("success"===n.subtype){Y&&(clearTimeout(Y),Y=void 0);for(const e of J)A?.pushText(`[Message from web UI user]: ${e}`);if(J=[],(S||"fix"===e.mode)&&A){if(A.hasQueuedMessages()){zr.info("[ws] Queued web UI messages found, continuing agent"),$=!0,A.allowNextTurn();continue}if(await Ba(A,3e3)){zr.info("[ws] Web UI message received during grace period, continuing agent"),$=!0,A.allowNextTurn();continue}A.finish()}if(Ve?.({phase:"complete",currentTestDescription:null,endedAt:Date.now()}),me({phase:"complete",currentTestDescription:null,endedAt:Date.now(),isError:!1,workers:he(!1)}),await Promise.allSettled(et),"verify"===e.mode){(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt).trim();const t=Qe||Je,n=/```verdict\s*\r?\n/.test(t),r=Aa(t)??{verdict:"INCONCLUSIVE",steps:["Agent finished without a parseable verdict block."],reason:n?"Failed to parse verdict.":"The agent completed without reporting a verdict.",evidence:[]},s=xa(r);"PASS"===r.verdict?z.green("VERIFICATION PASSED"):"FAIL"===r.verdict?z.red("VERIFICATION FAILED"):z.yellow("VERIFICATION INCONCLUSIVE"),s.steps.length>0&&s.steps.forEach((e,t)=>{}),s.reason&&(r.verdict,s.reason),s.evidence.length>0&&s.evidence.forEach(e=>{}),Ae({phase:"complete",endedAt:Date.now(),isError:"PASS"!==r.verdict,currentActivity:null}),process.exitCode="PASS"===r.verdict?0:"FAIL"===r.verdict?1:2,Ke({status:"success"})}else{if(Ae({phase:"complete",endedAt:Date.now(),isError:!1,currentActivity:null}),Gt&&Xe.length>0){z.green("Created files:");for(const e of Xe)z.green(`- ${e}`)}const e=(e,t)=>`]8;;${e}${t}]8;;`,t=qe?z.cyan(`📊 View Autoheal Report:\n ${e(qe,z.cyan(z.bold(z.underline(qe))))}`):void 0;Ke({status:"success",result:t}),oe="COMPLETED"}}else if(K||Z)zr.info("[fix] Suppressing error status: user-message interrupt in progress");else if(N)oe="CANCELED",me({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:he(!0)}),await Promise.allSettled(et),Ae({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0});else if(T){let e="Execution error before verification completed.";"error_max_budget_usd"===n.subtype?e="Budget limit exceeded before verification completed.":"error_max_turns"===n.subtype&&(e="Maximum turns exceeded before verification completed."),z.yellow("VERIFICATION INCONCLUSIVE"),await Promise.allSettled(et),Ae({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),Ke({status:"success"}),process.exitCode=2}else{let e,t="unknown",r="Run failed.";"error_max_budget_usd"===n.subtype?(t="budget_exceeded",e="total_cost_usd"in n?n.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.`,zr.warn("[fix] Budget limit exceeded",{subtype:n.subtype,totalCostUsd:e})):"error_max_turns"===n.subtype?(t="max_turns",r="Maximum turns exceeded. The fix session was stopped."):"error_during_execution"===n.subtype&&(t="execution_error"),Ve?.({endedAt:Date.now(),isError:!0}),me({phase:"complete",endedAt:Date.now(),isError:!0,errorReason:t,errorMessage:r,totalCostUsd:e,currentTestDescription:null,workers:he(!0)}),await Promise.allSettled(et),Ae({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),Ke({error:r,status:"error"}),process.exitCode=1,oe="FAILED"}N=!1;break}const r=_&&B;if("success"!==n.subtype){if(!N){let e="Run failed.";"error_max_budget_usd"===n.subtype?(e=`Budget limit exceeded (${"total_cost_usd"in n?`$${n.total_cost_usd.toFixed(2)}`:"unknown"} spent). The fix session was stopped to prevent runaway costs.`,zr.warn("[fix] Budget limit exceeded",{subtype:n.subtype,totalCostUsd:"total_cost_usd"in n?n.total_cost_usd:void 0})):"error_max_turns"===n.subtype&&(e="Maximum turns exceeded. The fix session was stopped."),Ke({error:e,status:"error"}),process.exitCode=1}}else Ke(r?{status:"running"}:{status:"success"});if($=!1,N=!1,r){B=!1,zr.info("Processing deferred MCP restart request in chat mode"),await sn(),t=!0;break}H=!1,Ge({label:void 0}),A?.allowNextTurn(),I&&M>0&&(M-=1,$=!0,Ke({status:"running"}));continue}}if(K&&await K,Z&&(Z=!1,t=!0,Ke({status:"running"}),zr.info("[fix] Resuming after user-message interrupt")),!t)break}}catch(e){N?(oe="CANCELED",me({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:he(!0)}),await Promise.allSettled(et),Ae({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0})):(zr.error("[fix] Agent encountered an error",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0,elapsed:Date.now()-ce}),Ke({error:`Agent encountered an error: ${e}`,status:"error"}),process.exitCode=1,oe="FAILED",me({phase:"complete",endedAt:Date.now(),isError:!0,currentTestDescription:null,workers:he(!0)}),await Promise.allSettled(et),Ae({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),zr.flush(),zr.printLogFileInfo())}finally{if(pn&&clearTimeout(pn),clearInterval(fn),Y&&(clearTimeout(Y),Y=void 0),zr.info("[fix] Agent session ending",{finalStatus:oe,elapsed:Date.now()-ce,totalMessages:ln}),Ot(),$=!1,N=!1,cn(),process.off("uncaughtException",a),A?.finish(),oe){zr.info("[fix] Reporting final autoheal status",{status:oe});const e=Date.now();await ge(oe),zr.info("[fix] Final autoheal status reported",{durationMs:Date.now()-e})}if(zr.info("[fix] Closing WebSocket progress reporter"),await(le?.closeAndWait()),await Promise.allSettled(et),await(be?.closeAndWait()),!Lt&&ne.length>0&&Pe&&(zr.info("[session] Uploading session history",{messageCount:ne.length}),await ms({authHeader:l,orgId:u,sessionId:Pe,projectId:Xr(c),history:ne}).catch(e=>{zr.warn("[session] Failed to upload session history",{error:e instanceof Error?e.message:String(e)})})),Lt&&Dt){const t=Date.now();try{zr.info("[fix] Computing diff...");const n=await Dt.computeDiff();if(n&&n.trim().length>0){zr.info("[fix] Uploading diff...",{diffLength:n.length});const{diffBucketPath:r,uploadUrl:s}=await ls({authHeader:l,contentType:"text/plain",orgId:u,runId:e.runId});await is({body:n,contentType:"text/plain",uploadUrl:s,errorContext:"diff"}),await us({authHeader:l,diffBucketPath:r,orgId:u,runId:e.runId}),zr.info("[fix] Diff uploaded",{durationMs:Date.now()-t})}else zr.info("[fix] No diff to upload (empty or no changes)")}catch(e){zr.warn("[fix] Failed to upload diff",{error:e instanceof Error?e.message:String(e),durationMs:Date.now()-t})}}zr.info("[fix] Cleaning up diff tracker"),await(Dt?.cleanup()),Lt&&ne.length>0&&Pe&&(zr.info("[fix] Uploading session history",{messageCount:ne.length}),await ms({authHeader:l,orgId:u,sessionId:Pe,projectId:Xr(c),history:ne}).catch(e=>{zr.warn("[fix] Failed to upload session history",{error:e instanceof Error?e.message:String(e)})})),zr.info("[fix] Running final cleanup"),await He(),zr.info("[fix] Cleanup complete")}},Fa=pe.object({runId:pe.string(),timestamp:pe.number()}),Ga=[{args:["--trace=on"],description:"Run Playwright tests",name:"test"},{args:[],description:"Install browser dependencies",name:"install"}],Wa=["You have two different versions of @playwright/test"];function Ya(e){const[t,...n]=qi(e),r=[t,...n.slice(0,-1)].join(" ");return(t,n)=>{let s=t.toString();for(const e of Ga)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 Va({overrideArgs:e,subcommand:t}){zr.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=Ga.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 [file] Auto-fix failing tests using AI"),n(" stably create <url> Generate new tests from a URL using AI"),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=Vi();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]=qi(s),a=Ya(s);return new Promise(t=>{const n=m(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 g=[t,...d,...f];zr.info("[test] Forwarded args computed",{forwardedArgs:g}),zr.info("[test] Resolving Stably test environment");const y=Date.now(),b="test"===t?await ts():void 0;zr.info("[test] Stably test environment resolved",{durationMs:Date.now()-y,hasCredentials:null!=b,hasWsUrl:!!b?.STABLY_WS_URL}),zr.info("[test] Loading remote environment variables");const w=await ns();zr.info("[test] Remote environment loaded",{hasRemoteEnv:!!w,variableCount:w?Object.keys(w.variables).length:0});const _={...w?.variables,...w?.sensitiveValues.length?{STABLY_SENSITIVE_VALUES:Buffer.from(JSON.stringify(w.sensitiveValues)).toString("base64")}:{}};zr.info("[test] Setting up Stably reporter injection");const I="test"===t?function({forwardedArgs:e,hasCredentials:t}){if(!t)return console.warn("⚠️ Stably credentials not found. Test results will not be reported to Stably."),console.warn(" To enable reporting, either:"),console.warn(" • Run `npx stably login` to authenticate"),void console.warn(" • Or set STABLY_API_KEY and STABLY_PROJECT_ID environment variables\n");const 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=>v(e)))return!0;const e=o(t);if(e===t)return!1;t=e}}(e);return t||(console.warn("⚠️ @stablyai/playwright-test is not installed. Stably reporter will not be injected."),console.warn(" Install it with: npm install @stablyai/playwright-test"),console.warn(" Reference: ]8;;https://docs.stably.ai/getting-started/sdk-setup-guidehttps://docs.stably.ai/getting-started/sdk-setup-guide]8;;\n")),t},a=(e,t)=>{try{return function({baseConfigPath:e,projectDir:t}){const 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: '${Jn}',\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: '${Jn}',\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 v(a)||T(a,{recursive:!0}),S(u,d,"utf-8"),function(e){const t=i(e,".gitignore");try{if(v(t)){const e=E(t,"utf-8");if(e.split("\n").map(e=>e.trim()).includes(Js))return;const n=e.length>0&&!e.endsWith("\n");x(t,`${n?"\n":""}${Js}\n`)}else S(t,`${Js}\n`)}catch{}}(a),u}({baseConfigPath:e,projectDir:t})}catch{return void console.warn("⚠️ Could not create Stably wrapper config. Reporter injection skipped.")}};if(e.some(e=>"--config"===e||"-c"===e||e.startsWith("--config=")||e.startsWith("-c="))){const t=e.findIndex(e=>"--config"===e||"-c"===e);if(-1!==t&&e[t+1]){const 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:g,hasCredentials:null!=b}):void 0;zr.info("[test] Reporter injection setup complete",{hasWrapperConfig:!!I}),zr.info("[test] Spawning Playwright process"),await function(e,t={}){zr.info("[test] Detecting Playwright installation");const n=Vi();zr.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]=qi(r),i=es(t.env),a=[s,...o,...e];zr.info("[test] Spawning Playwright process",{command:a.join(" "),pid:process.pid});const c=Date.now(),l=m(s,[...o,...e],{stdio:["inherit","pipe","pipe"],shell:"win32"===process.platform,env:{...i,...process.env.CI?{}:{FORCE_COLOR:"1"}}});zr.info("[test] Playwright process spawned",{childPid:l.pid});const u=Ya(r),d=function(){let e=!1,t="";return(n,r)=>{if(!e){t+=n,t.length>1024&&(t=t.slice(-1024));for(const n of Wa)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)}}}();l.stdout?.on("data",e=>{u(e,process.stdout)}),l.stderr?.on("data",e=>{const t=e.toString();u(e,process.stderr),d(t,process.stderr)});const p=new AbortController,f=()=>!p.signal.aborted&&(p.abort(),t.onClose?.(),process.removeListener("SIGINT",h),process.removeListener("SIGTERM",h),!0),h=e=>{zr.info("[test] Signal received, killing Playwright process",{signal:e,childPid:l.pid}),f(),l.kill(e);const t="SIGINT"===e?130:143;process.exit(t)};return process.on("SIGINT",h),process.on("SIGTERM",h),new Promise((e,t)=>{l.on("error",e=>{f()&&(zr.error("[test] Playwright process error",{error:e.message,childPid:l.pid}),t(e))}),l.on("close",t=>{if(!f())return;zr.info("[test] Playwright process exited",{exitCode:t,durationMs:Date.now()-c});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)})})})}(g,{env:{..._,...b},onClose:()=>{var e;zr.info("[test] Playwright process closed, cleaning up wrapper config"),(e=I)&&v(e)&&P(e)}})}function za(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 Ka={PASSED:z.green,FAILED:z.red,TIMEDOUT:z.red,CANCELLED:z.yellow,INTERRUPTED:z.yellow,RUNNING:z.cyan,QUEUED:z.dim},qa=(e,t)=>e?e.length>t?`${e.slice(0,t-1)}…`:e:"-",Ja=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")}`},Qa=e=>(Ka[e]??(e=>e))(e),Xa=/\x1b\[[0-9;]*m/g,Za=(e,t)=>{const n=e.replace(Xa,"").length,r=Math.max(0,t-n);return e+" ".repeat(r)},ec=e=>`${JSON.stringify(e,null,2)}\n`,tc=e=>"oauth"===e.type?e.auth.context.orgId:void 0,nc=(e,t,n)=>{if(!e)return;const r=e.toUpperCase();if(t.includes(r))return r;ae(z.red(`Invalid ${n} value "${e}". Must be one of: ${t.join(", ").toLowerCase()}`)),process.exit(1)},rc=(e,t,n)=>{if(401!==e.response.status&&403!==e.response.status||(ae(z.red("Access denied.")),process.exit(1)),404===e.response.status&&n&&(ae(z.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";ae(z.red(t)),process.exit(1)}e.error&&(ae(z.red(`Failed to ${t}: ${e.response.status}`)),process.exit(1))},sc="stably",oc=`https://registry.npmjs.org/${sc}/latest`;function ic(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 ac(e,t){const n=ic(e),r=ic(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 cc=r.join(L.homedir(),".stably"),lc=r.join(cc,"update-check.json"),uc="1"===process.env.STABLY_DISABLE_UPDATE_CHECK,dc=fe.object({lastCheck:fe.number(),latestVersion:fe.string()}),pc=!1;function fc(e=""){process.stdout.write(`${e}\n`)}function hc(...e){process.stderr.write(`${e.join(" ")}\n`)}var mc=fe.object({version:fe.string()});var gc=!1,yc=async()=>{if(gc)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{}},bc=e=>{const t=e.toLowerCase();return t.startsWith("npm_config_")||"node_options"===t};!function(){if(uc||function(e=process.argv.slice(2)){return e.includes("upgrade")}())return;const e=function(){try{const e=b.readFileSync(lc,"utf-8");return dc.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 = '${oc}';\n const cacheFile = ${JSON.stringify(lc)};\n const cacheDir = ${JSON.stringify(cc)};\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{m(process.execPath,["--input-type=module","-e",e],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()}catch{}}(),null!=e&&ac(Jn,e.latestVersion)){if(pc)return;pc=!0;let t=!1;const n=()=>{if(t)return;t=!0;const n=`${z.yellow(`update available (${Jn} → ${e.latestVersion})`)} - run \`${sc} upgrade\` to get the latest version\n`;try{b.writeSync(2,n)}catch{}};process.once("beforeExit",n),process.once("exit",n)}}(),Pe.cwdChanged&&zr.debug("Changed working directory",{cwd:Pe.newCwd});for(const e of Pe.envFilesLoaded)zr.debug("Loaded env file",{path:e});for(const e of Pe.envFileErrors)zr.warn(e);var vc=process.argv.findIndex(e=>"-v"===e||"--verbose"===e);-1!==vc&&process.argv.splice(vc,1);var wc=process.argv.findIndex(e=>"--no-telemetry"===e);-1!==wc&&process.argv.splice(wc,1),zr.info("CLI starting",{version:Jn,args:process.argv.slice(2),cwd:process.cwd()}),process.on("unhandledRejection",(e,t)=>{zr.error("Unhandled promise rejection",{reason:e instanceof Error?{message:e.message,stack:e.stack}:e,promise:String(t)}),zr.flush(),zr.printLogFileInfo()}),process.on("uncaughtException",(e,t)=>{"EPIPE"!==e.code&&(zr.error("Uncaught exception",{error:{message:e.message,stack:e.stack,name:e.name},origin:t}),zr.flush(),zr.printLogFileInfo())});var _c=new u;_c.name("stably").description("AI-assisted Playwright testing CLI").version(Jn),_c.enablePositionalOptions(),_c.showHelpAfterError(),_c.exitOverride(),_c.configureHelp({subcommandTerm:e=>{const t=e.registeredArguments.map(e=>e.required?`<${e.name()}>`:`[${e.name()}]`).join(" ");return t?`${e.name()} ${t}`:e.name()}});var Ic=[];_c.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>{Ic.push(e)}});var Ec=()=>{const e=_c.helpInformation().trimEnd();return e?`${e}\n`:""},Tc=(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},Sc=()=>{process.stdout.write(Ec())};_c.command("help [command...]").description("Show help for a command (e.g. stably help create)").action(e=>{if(!e||0===e.length)return void Sc();const t=Tc(_c,e);if(!t)return process.stderr.write(`Unknown command: ${e.join(" ")}\n`),Sc(),void(process.exitCode=1);var n;n=t,process.stdout.write((e=>{const t=e.helpInformation().trimEnd();return t?`${t}\n`:""})(n))}),_c.action(()=>Ha({mode:"chat",getHelpText:Ec})),_c.command("login").description("Authenticate with Stably in your browser").action(Pr),_c.command("logout").description("Clear stored Stably credentials").action(async()=>{const e=qr();e&&(ie.warn(`Environment variables ${z.cyan("STABLY_API_KEY")} and ${z.cyan("STABLY_PROJECT_ID")} are set.`),ie.warn("They will continue to be used for authentication even after logout."),ie.warn("Unset them if you want to fully de-authenticate this shell/session."));const t=await vr();if(!t)return void ae(e?z.yellow("No stored OAuth login found to clear."):z.yellow("You are not logged in."));const n=ce();n.start("Logging out..."),await(async e=>{try{await fetch(`${Zn}/api/backend/v1/logout`,{body:JSON.stringify({refresh_token:e}),headers:{"Content-Type":"application/json"},method:"POST"})}catch{}})(t.refreshToken),await _r(),await Er(),n.stop(z.green("✓ Logged out")),ae(z.green("You have been logged out successfully."))}),_c.command("whoami").description("Show auth status and current project").action(async()=>{ie.info(`${z.bold("CLI Version:")} ${z.cyan(Jn)}`);const e=qr();if(e){ie.info(z.dim("Authentication: Environment variables")),ie.info(` ${z.bold("API Key:")} ${z.cyan(e.apiKey.slice(0,8))}...`),ie.info(` ${z.bold("Project ID:")} ${z.cyan(e.projectId)}`);const t=await vr();if(t){let e;try{e=dr(t.accessToken).email}catch{e=void 0}ie.warn("Stored OAuth login detected but will be ignored (env auth takes precedence)."),e&&ie.info(` ${z.bold("OAuth Email:")} ${z.cyan(e)}`),ie.info(` ${z.bold("Tip:")} Unset env vars to use OAuth`)}return void ae(z.green("Authenticated via environment variables"))}const t=await vr();if(!t)return void ae(z.yellow("Not logged in. Run `stably login` to authenticate."));let n;try{n=dr(t.accessToken).email}catch{n=void 0}const s=await Ir();if(!s)return ie.info(z.dim("Authentication: OAuth (not linked to a project)")),n&&ie.info(` ${z.bold("Email:")} ${z.cyan(n)}`),void ae(z.yellow("Logged in but this directory is not linked to a project. Run `stably login` to link."));const o=await(async()=>pr(process.cwd(),mr))(),i=o?r.dirname(o):process.cwd(),a=r.relative(process.cwd(),i)||".";ie.info(z.dim("Authentication: OAuth")),n&&ie.info(` ${z.bold("Email:")} ${z.cyan(n)}`),ie.info(` ${z.bold("Organization:")} ${z.cyan(s.orgName)}`),ie.info(` ${z.bold("Project:")} ${z.cyan(s.projectName)}`),ie.info(` ${z.bold("Linked at:")} ${z.dim(a)}`),ae(z.green("Authenticated"))}),_c.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=>{le(`Starting development server for port ${e.port}...`);const t=await Qr(),n="oauth"===t.type?`${t.auth.context.orgName}-${t.auth.context.projectName}`.toLowerCase().replace(/[^a-z0-9-]/g,""):`project-${t.auth.projectId}`.toLowerCase(),r=ce();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}${z.underline(z.cyan(s.url))}]8;;`)}),_c.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 Ha({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)=>Ha({mode:"single",prompt:e,outputDir:t.output})),_c.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 Ha({mode:"verify",prompt:e,url:t.url,maxBudgetUsd:t.maxBudget,interactive:t.interactive})}),_c.command("internal-fix-run <runId>",{hidden:!0}).description("Internal: run fix session in subprocess").action(async e=>Ha({mode:"fix",runId:e})),_c.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())||(zr.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 zr.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(Tn))if(Tn[n].detect({env:e,cwd:t}))return{isCi:!0,...Tn[n].configuration({env:e,cwd:t})};return{isCi:Boolean(e.CI),...(n={env:e,cwd:t},{commit:zt(n),branch:Kt(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 zr.debug("Run ID detected from CI environment",{runId:n}),t(n);zr.debug("No explicit run ID or CI environment detected, checking last-run.json");const r=await(async()=>{try{const e=await pr(process.cwd(),".stably/last-run.json");if(!e)return;const t=await Q(e,"utf-8");return{...Fa.parse(JSON.parse(t)),filePath:e}}catch{return}})();if(r){const e=(Date.now()-r.timestamp)/36e5;return zr.debug("Run ID found in last-run.json",{runId:r.runId,timestamp:r.timestamp,filePath:r.filePath,ageHours:Math.round(e)}),e>24&&zr.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)}zr.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 Qr(),n=Zr(t),r=Xr(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})=>m(e,t,n)})=>{const u=(({baseEnv:e,stablyApiKey:t,stablyProjectId:n})=>{const r={...e};for(const e of Object.keys(r))bc(e)&&delete r[e];return{...r,STABLY_API_KEY:t,STABLY_PROJECT_ID:n}})({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)}),_c.command("init").description("Initialize Playwright and Stably SDK in your project").action(async()=>Ha({mode:"init"})),_c.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;fc(z.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(oc,{signal:e.signal});if(!t.ok)throw new Error(`Failed to fetch latest version: ${t.statusText}`);return mc.parse(await t.json()).version}finally{clearTimeout(t)}}();return{current:Jn,latest:e,isOutdated:ac(Jn,e)}}()}catch(e){return hc(z.red("Failed to check for updates:"),e instanceof Error?e.message:e),void(process.exitCode=1)}if(fc(`Current version: ${z.yellow(n.current)}`),fc(`Latest version: ${z.green(n.latest)}`),fc(),!n.isOutdated)return void fc(z.green("✓ You are already on the latest version!"));if(fc(z.yellow(`⚠ A new version is available: ${n.current} → ${n.latest}`)),fc(),t)return fc(z.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",`${sc}@latest`],description:`npm install -g ${sc}@latest`};case"global-pnpm":return{command:"pnpm",args:["add","-g",`${sc}@latest`],description:`pnpm add -g ${sc}@latest`};case"global-yarn-classic":return{command:"yarn",args:["global","add",`${sc}@latest`],description:`yarn global add ${sc}@latest`};case"npx":return{command:"npx",args:[`${sc}@latest`],description:`npx ${sc}@latest (always uses latest)`}}}(r);if("npx"===r)return fc(z.dim("You are running via npx, which always fetches the latest version.")),void fc(z.dim(`Simply run: ${z.white("npx stably")} to use the latest version.`));"unknown"===r?(fc(z.yellow("Could not detect installation method. Falling back to npm.")),fc()):"global-yarn-berry"===r&&(fc(z.yellow("Yarn Berry does not support global packages. Falling back to npm.")),fc()),fc(`Upgrade command: ${z.cyan(s.description)}`),fc(),fc(z.cyan("Upgrading...")),fc();try{await(o=s.command,i=s.args,new Promise((e,t)=>{const n=m(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{b.unlinkSync(lc)}catch{}}(),fc(),fc(z.green("✓ Upgrade complete!")),fc(z.dim(`Run ${z.white("stably --version")} to verify.`))}catch(e){hc(z.red("Upgrade failed:"),e instanceof Error?e.message:e),fc(),fc(z.dim("You can try manually running:")),fc(z.cyan(` ${s.description}`)),process.exitCode=1}var o,i}(e));var xc=_c.command("env").description("Manage remote environments");xc.command("list").description("List available environments").action(async()=>{const e=await Qr(),t=Xr(e),n=Zr(e);zr.debug("Listing environments",{projectId:t});const r=await(s={auth:n,client:or(),path:{projectId:t}},(s.client??zn).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/environments",...s}));var s;401!==r.response.status&&403!==r.response.status||(ae(z.red("Access denied.")),process.exit(1)),r.error&&(ae(z.red(`Failed to list environments: ${r.response.status}`)),process.exit(1));const{environments:o}=r.data;if(0!==o.length){process.stdout.write(`${z.bold("Environments")}\n\n`);for(const e of o){const t=e.isDefault?z.green(" (default)"):"",n=z.dim(` ${e.variableCount} variable${1!==e.variableCount?"s":""}`);process.stdout.write(` ${z.cyan(e.name)}${t}${n}\n`),e.description&&process.stdout.write(` ${z.dim(e.description)}\n`)}process.stdout.write("\n")}else process.stdout.write(z.dim("No environments found. Create one on your Stably dashboard.\n"))}),xc.command("inspect <name>").description("Show variable metadata (name, sensitive flag, updated timestamp)").action(e=>(async e=>{const t=await Qr(),n=Xr(t),r=Zr(t);zr.debug("Inspecting environment",{name:e,projectId:n});const s=await(o={auth:r,client:or(),path:{projectId:n,environmentName:e}},(o.client??zn).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/environments/{environmentName}/inspect",...o}));var o;404===s.response.status&&(ae(z.red(`Environment "${e}" not found. Run ${z.bold("stably env list")} to see available environments.`)),process.exit(1)),401!==s.response.status&&403!==s.response.status||(ae(z.red("Access denied.")),process.exit(1)),s.error&&(ae(z.red(`Failed to inspect environment: ${s.response.status}`)),process.exit(1));const{variables:i}=s.data;if(0!==i.length){process.stdout.write(`${z.bold(e)} ${z.dim(`(${i.length} variable${1!==i.length?"s":""})`)}\n\n`);for(const e of i){const t=z.dim(` [updated ${za(e.updatedAt)}]`);e.sensitive?process.stdout.write(` ${z.cyan(e.name)} ${z.yellow("[sensitive]")}${t}\n`):process.stdout.write(` ${z.cyan(e.name)}${t}\n`)}process.stdout.write("\n")}else process.stdout.write(z.dim(`Environment "${e}" has no variables.\n`))})(e));var Ac=_c.command("runs").description("View test run history");Ac.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 Qr(),n=Xr(t),r=Zr(t),s=tc(t);let o;e.limit&&(o=parseInt(e.limit,10),(Number.isNaN(o)||o<1||o>100)&&(ae(z.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");zr.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 Kn({auth:r,client:or(),headers:rs(s),query:{projectId:n,branchName:e.branch,limit:o,afterRunId:e.after,beforeRunId:e.before,source:i,status:a,suiteName:e.suite,trigger:c}});rc(l,"list runs");const{runs:u,hasMore:d}=l.data;e.json?process.stdout.write(ec(l.data)):process.stdout.write(((e,t)=>{if(0===e.length)return z.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=`${Za("Run ID",r.runId.w)}${Za("Status",r.status.w)}${Za("Branch",r.branch.w)}${Za("Started",r.started.w)}Tests`;s.push(z.bold(o));for(const t of e){const e=qa(t.runId,r.runId.t),n=Qa(t.status),o=qa(t.branchName,r.branch.t),i=Ja(t.startedAt),a=t.totalCount.toString();s.push(`${Za(e,r.runId.w)}${Za(n,r.status.w)}${Za(o,r.branch.w)}${Za(i,r.started.w)}${a}`)}if(t&&e.length>0){const t=e.at(-1)?.runId;t&&(s.push(""),s.push(z.dim(`Next page: stably runs list --before ${t}`)))}return s.push(""),s.join("\n")})(u,d))}),Ac.command("view <runId>").description("Show details for a specific run").option("--json","Output as JSON").action(async(e,t)=>{const n=await Qr(),r=Zr(n),s=tc(n);zr.debug("Viewing run",{runId:e});const o=await qn({auth:r,client:or(),headers:rs(s),path:{runId:e},query:{detail:"full"}});if(rc(o,"get run details",`Run "${e}" not found.`),t.json)process.stdout.write(ec(o.data));else{const e=o.data;process.stdout.write((e=>{const t=[];if(t.push(z.bold(`Run ${e.runId}`)),t.push(` ${z.dim("Status:")} ${Qa(e.status)}`),e.branchName&&t.push(` ${z.dim("Branch:")} ${e.branchName}`),e.commitSha&&t.push(` ${z.dim("Commit:")} ${e.commitSha.slice(0,7)}`),e.startedAt&&t.push(` ${z.dim("Started:")} ${Ja(e.startedAt)}`),null!==e.durationMs&&t.push(` ${z.dim("Duration:")} ${(e=>{if(null===e)return"-";const t=Math.floor(e/1e3);if(t<60)return`${t}s`;const 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(` ${z.dim("Source:")} ${e.source.toLowerCase()}`),e.projectId){const n=`https://app.stably.ai/project/${e.projectId}/playwright/history/${e.runId}`;t.push(` ${z.dim("URL:")} ${z.cyan(z.underline(n))}`)}t.push("");const n=[];e.passedCount>0&&n.push(z.green(`${e.passedCount} passed`)),e.failedCount>0&&n.push(z.red(`${e.failedCount} failed`)),e.flakyCount>0&&n.push(z.yellow(`${e.flakyCount} flaky`)),e.timedoutCount>0&&n.push(z.red(`${e.timedoutCount} timedout`)),e.skippedCount>0&&n.push(z.dim(`${e.skippedCount} skipped`)),e.interruptedCount>0&&n.push(z.yellow(`${e.interruptedCount} interrupted`)),t.push(`${z.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(z.bold("Failed/Flaky Tests:"));for(const e of r){const n=e.status??"UNKNOWN",r=Ka[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}${z.dim(c)}`);const u=i?.at(-1);if(u?.errorMessage){const e=u.errorMessage.split("\n")[0]?.slice(0,100)??"";t.push(` ${z.dim(e)}`)}}}return t.push(""),t.join("\n")})(e))}}),_c.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)}),Ga.forEach(({args:e,description:t,name:n})=>{_c.command(n).description(t).helpOption(!1).helpCommand(!1).allowUnknownOption(!0).allowExcessArguments(!0).passThroughOptions().action(()=>Va({overrideArgs:e,subcommand:n}))});var Cc=()=>{0!==Ic.length&&(process.stderr.write(Ic.join("")),Ic=[])};(async()=>{await(async()=>{if(!gc&&"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":Jn,"node.version":process.version,"os.platform":process.platform}}),gc=!0}catch{}})();try{await _c.parseAsync(process.argv),zr.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 zr.error(t,{stack:e instanceof Error?e.stack:void 0}),Cc(),zr.flush(),zr.printLogFileInfo(),await yc(),void(process.exitCode=1)}const t="number"==typeof e.exitCode?e.exitCode:1,n=process.argv.slice(2).find(e=>!e.startsWith("-")),r=!!n&&!!Tc(_c,[n]);if(("commander.excessArguments"===e.code||"commander.unknownCommand"===e.code)&&n&&!r)return Ic=[],zr.warn("Unknown command",{command:n}),process.stderr.write(`command '${n}' not found\n`),Sc(),void(process.exitCode=t);zr.debug("Commander error",{code:e.code,exitCode:t}),Cc(),process.exitCode=t}finally{zr.flush(),await yc()}})();
2
+ import{config as e,parse as t}from"dotenv";import*as n from"path";import r,{resolve as o,dirname as s,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 m}from"child_process";import g from"process";import*as y from"fs";import b,{existsSync as v,statSync as w,realpathSync as _,createReadStream as I,readFileSync as E,mkdirSync as T,writeFileSync as S,appendFileSync as x,openSync as A,readSync as C,closeSync as R,rmSync as P}from"fs";import{fileURLToPath as k,URL as U}from"url";import L,{tmpdir as D,constants as O}from"os";import"timers/promises";import $ from"stream";import{debuglog as N,promisify as B,TextDecoder as j,TextEncoder as M}from"util";import{createSdkMcpServer as H,tool as F,query as G}from"@anthropic-ai/claude-agent-sdk";import{match as W}from"ts-pattern";import Y from"net";import{createInterface as V}from"readline/promises";import z from"picocolors";import{simpleGit as K}from"simple-git";import q,{randomUUID as J}from"crypto";import{readFile as Q,mkdir as X,writeFile as Z,unlink as ee,access as te,readdir as ne,stat as re,rm as oe,appendFile as se}from"fs/promises";import{log as ie,outro as ae,spinner as ce,intro as le,select as ue,isCancel as de}from"@clack/prompts";import pe,{z as fe}from"zod";import he from"open";import me from"http";import ge from"pino";import ye from"sonic-boom";import{z as be}from"zod/v3";import ve from"ws";import{useState as we,useRef as _e,useEffect as Ie,useCallback as Ee,useMemo as Te}from"react";import{jsx as Se,jsxs as xe}from"react/jsx-runtime";import{createRequire as Ae}from"module";import{parseDocument as Ce}from"yaml";import{startTunnel as Re}from"@stablyhq/runner-sdk";var Pe={cwdChanged:!1,newCwd:void 0,envFilesLoaded:[],envFileErrors:[],remoteEnvName:void 0},ke=process.argv.findIndex(e=>"-C"===e||"--cwd"===e);if(-1!==ke&&process.argv[ke+1]){const e=process.argv[ke+1];process.chdir(e),Pe.cwdChanged=!0,Pe.newCwd=e,process.argv.splice(ke,2)}for(var Ue=[],Le=0;Le<process.argv.length;)if("--env-file"===process.argv[Le]){const e=process.argv[Le+1];e&&!e.startsWith("-")?(Ue.push(e),process.argv.splice(Le,2)):Le++}else Le++;var De=process.argv.findIndex(e=>"--env"===e);-1!==De&&process.argv[De+1]&&!process.argv[De+1].startsWith("-")&&(Pe.remoteEnvName=process.argv[De+1],process.argv.splice(De,2));for(const t of Ue){const n=r.resolve(process.cwd(),t),o=e({path:n,override:!0,quiet:!0});if(o.error){const e=`warning: could not load env file: ${n} (${o.error.message})`;Pe.envFileErrors.push(e),process.stderr.write(`${e}\n`)}else Pe.envFilesLoaded.push(n)}var Oe={detect:({env:e})=>Boolean(e.APPVEYOR),configuration({env:e}){const t=e.APPVEYOR_PULL_REQUEST_NUMBER,n=Boolean(t);return{name:"Appveyor",service:"appveyor",commit:e.APPVEYOR_REPO_COMMIT,tag:e.APPVEYOR_REPO_TAG_NAME,build:e.APPVEYOR_BUILD_NUMBER,buildUrl:`https://ci.appveyor.com/project/${e.APPVEYOR_PROJECT_SLUG}/build/${e.APPVEYOR_BUILD_VERSION}`,branch:e.APPVEYOR_REPO_BRANCH,job:e.APPVEYOR_JOB_NUMBER,jobUrl:`https://ci.appveyor.com/project/${e.APPVEYOR_PROJECT_SLUG}/build/job/${e.APPVEYOR_JOB_ID}`,pr:t,isPr:n,prBranch:e.APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH,slug:e.APPVEYOR_REPO_NAME,root:e.APPVEYOR_BUILD_FOLDER}}};function $e(e){return(/\d+(?!.*\d+)/.exec(e)||[])[0]}function Ne(e){return e?/^(?:refs\/heads\/)?(?<branch>.+)$/i.exec(e)[1]:void 0}var Be={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:Ne(n?e.SYSTEM_PULLREQUEST_TARGETBRANCH:e.BUILD_SOURCEBRANCH),pr:t,isPr:n,prBranch:Ne(n?e.SYSTEM_PULLREQUEST_SOURCEBRANCH:void 0),root:e.BUILD_REPOSITORY_LOCALPATH}}},je={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})},Me={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})},He={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}}},Fe={detect:({env:e})=>Boolean(e.BUDDY_WORKSPACE_ID),configuration({env:e}){const t=$e(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}}},Ge="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function We(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ye,Ve,ze,Ke,qe,Je,Qe,Xe,Ze={exports:{}};var et,tt,nt,rt,ot,st,it,at,ct,lt,ut,dt,pt,ft,ht,mt={exports:{}},gt={};function yt(){if(dt)return ut;dt=1;const e=r,t=function(){if(nt)return tt;nt=1;const e=r,t=function(){if(Xe)return Qe;Xe=1;const e="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,t=r,n=e?";":":",o=function(){if(Je)return qe;var e;function t(n,r,o){if("function"==typeof r&&(o=r,r={}),!o){if("function"!=typeof Promise)throw new TypeError("callback not provided");return new Promise(function(e,o){t(n,r||{},function(t,n){t?o(t):e(n)})})}e(n,r||{},function(e,t){e&&("EACCES"===e.code||r&&r.ignoreErrors)&&(e=null,t=!1),o(e,t)})}return Je=1,e="win32"===process.platform||Ge.TESTING_WINDOWS?function(){if(Ve)return Ye;Ve=1,Ye=n,n.sync=function(n,r){return t(e.statSync(n),n,r)};var e=b;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 o=n[r].toLowerCase();if(o&&e.substr(-o.length).toLowerCase()===o)return!0}return!1}(t,n)}function n(n,r,o){e.stat(n,function(e,s){o(e,!e&&t(s,n,r))})}return Ye}():function(){if(Ke)return ze;Ke=1,ze=t,t.sync=function(t,r){return n(e.statSync(t),r)};var e=b;function t(t,r,o){e.stat(t,function(e,t){o(e,!e&&n(t,r))})}function n(e,t){return e.isFile()&&function(e,t){var n=e.mode,r=e.uid,o=e.gid,s=void 0!==t.uid?t.uid:process.getuid&&process.getuid(),i=void 0!==t.gid?t.gid:process.getgid&&process.getgid(),a=parseInt("100",8),c=parseInt("010",8);return n&parseInt("001",8)||n&c&&o===i||n&a&&r===s||n&(a|c)&&0===s}(e,t)}return ze}(),qe=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}},qe}(),s=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),i=(t,r)=>{const o=r.colon||n,s=t.match(/\//)||e&&t.match(/\\/)?[""]:[...e?[process.cwd()]:[],...(r.path||process.env.PATH||"").split(o)],i=e?r.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",a=e?i.split(o):[""];return e&&-1!==t.indexOf(".")&&""!==a[0]&&a.unshift(""),{pathEnv:s,pathExt:a,pathExtExe:i}},a=(e,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((o,i)=>{if(r===a.length)return n.all&&u.length?o(u):i(s(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;o(p(f,r,0))}),p=(e,t,r)=>new Promise((s,i)=>{if(r===c.length)return s(d(t+1));const a=c[r];o(e+a,{pathExt:l},(o,i)=>{if(!o&&i){if(!n.all)return s(e+a);u.push(e+a)}return s(p(e,t,r+1))})});return r?d(0).then(e=>r(null,e),r):d(0)};return Qe=a,a.sync=(e,n)=>{n=n||{};const{pathEnv:r,pathExt:a,pathExtExe:c}=i(e,n),l=[];for(let s=0;s<r.length;s++){const i=r[s],u=/^".*"$/.test(i)?i.slice(1,-1):i,d=t.join(u,e),p=!u&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d;for(let e=0;e<a.length;e++){const t=p+a[e];try{if(o.sync(t,{pathExt:c})){if(!n.all)return t;l.push(t)}}catch(e){}}}if(n.all&&l.length)return l;if(n.nothrow)return null;throw s(e)},Qe}(),n=function(){if(et)return mt.exports;et=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 mt.exports=e,mt.exports.default=e,mt.exports}();function o(r,o){const s=r.options.env||process.env,i=process.cwd(),a=null!=r.options.cwd,c=a&&void 0!==process.chdir&&!process.chdir.disabled;if(c)try{process.chdir(r.options.cwd)}catch(e){}let l;try{l=t.sync(r.command,{path:s[n({env:s})],pathExt:o?e.delimiter:void 0})}catch(e){}finally{c&&process.chdir(i)}return l&&(l=e.resolve(a?r.options.cwd:"",l)),l}return tt=function(e){return o(e)||o(e,!0)}}(),n=function(){if(rt)return gt;rt=1;const e=/([()\][%!^"`<>&|;, *?])/g;return gt.command=function(t){return t.replace(e,"^$1")},gt.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},gt}(),o=function(){if(lt)return ct;lt=1;const e=b,t=function(){if(at)return it;at=1;const e=st?ot:(st=1,ot=/^#!(.*)/);return it=(t="")=>{const n=t.match(e);if(!n)return null;const[r,o]=n[0].replace(/#! ?/,"").split(" "),s=r.split("/").pop();return"env"===s?o:o?`${s} ${o}`:s}}();return ct=function(n){const r=Buffer.alloc(150);let o;try{o=e.openSync(n,"r"),e.readSync(o,r,0,150,0),e.closeSync(o)}catch(e){}return t(r.toString())}}(),s="win32"===process.platform,i=/\.(?:com|exe)$/i,a=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;return ut=function(r,c,l){c&&!Array.isArray(c)&&(l=c,c=null);const u={command:r,args:c=c?c.slice(0):[],options:l=Object.assign({},l),file:void 0,original:{command:r,args:c}};return l.shell?u:function(r){if(!s)return r;const c=function(e){e.file=t(e);const n=e.file&&o(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 o=[r.command].concat(r.args).join(" ");r.args=["/d","/s","/c",`"${o}"`],r.command=process.env.comspec||"cmd.exe",r.options.windowsVerbatimArguments=!0}return r}(u)}}var bt=We(function(){if(ht)return Ze.exports;ht=1;const e=p,t=yt(),n=function(){if(ft)return pt;ft=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 pt={hookChildProcess:function(t,r){if(!e)return;const o=t.emit;t.emit=function(e,s){if("exit"===e){const e=n(s,r);if(e)return o.call(t,"error",e)}return o.apply(t,arguments)}},verifyENOENT:n,verifyENOENTSync:function(n,r){return e&&1===n&&!r.file?t(r.original,"spawnSync"):null},notFoundError:t},pt}();function r(r,o,s){const i=t(r,o,s),a=e.spawn(i.command,i.args,i.options);return n.hookChildProcess(a,i),a}return Ze.exports=r,Ze.exports.spawn=r,Ze.exports.sync=function(r,o,s){const i=t(r,o,s),a=e.spawnSync(i.command,i.args,i.options);return a.error=a.error||n.verifyENOENTSync(a.status,i),a},Ze.exports._parse=t,Ze.exports._enoent=n,Ze.exports}());function vt(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 wt=(e,t)=>({name:`SIGRT${t+1}`,number:_t+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),_t=34,It=[{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"}],Et=()=>{const e=(()=>{const e=64-_t+1;return Array.from({length:e},wt)})();return[...It,...e].map(Tt)},Tt=({name:e,number:t,description:n,action:r,forced:o=!1,standard:s})=>{const{signals:{[e]:i}}=O,a=void 0!==i;return{name:e,number:a?i:t,description:n,supported:a,action:r,forced:o,standard:s}},St=({name:e,number:t,description:n,supported:r,action:o,forced:s,standard:i})=>[e,{name:e,number:t,description:n,supported:r,action:o,forced:s,standard:i}],xt=(()=>{const e=Et();return Object.fromEntries(e.map(St))})();(()=>{const e=Et(),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:o,supported:s,action:i,forced:a,standard:c}=n;return{[e]:{name:r,number:e,description:o,supported:s,action:i,forced:a,standard:c}}})(n,e));Object.assign({},...t)})();var At=({stdout:e,stderr:t,all:n,error:r,signal:o,exitCode:s,command:i,escapedCommand:a,timedOut:c,isCanceled:l,killed:u,parsed:{options:{timeout:d,cwd:p=g.cwd()}}})=>{s=null===s?void 0:s;const f=void 0===(o=null===o?void 0:o)?void 0:xt[o].description,h=(({timedOut:e,timeout:t,errorCode:n,signal:r,signalDescription:o,exitCode:s,isCanceled:i})=>e?`timed out after ${t} milliseconds`:void 0!==n?`failed with ${n}`:void 0!==r?`was killed with ${r} (${o})`:void 0!==s?`failed with exit code ${s}`:"failed")({timedOut:c,timeout:d,errorCode:r&&r.code,signal:o,signalDescription:f,exitCode:s,isCanceled:l}),m=`Command ${h}: ${i}`,y="[object Error]"===Object.prototype.toString.call(r),b=y?`${m}\n${r.message}`:m,v=[b,t,e].filter(Boolean).join("\n");return y?(r.originalMessage=r.message,r.message=v):r=new Error(v),r.shortMessage=b,r.command=i,r.escapedCommand=a,r.exitCode=s,r.signal=o,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},Ct=["stdin","stdout","stderr"],Rt=[];Rt.push("SIGHUP","SIGINT","SIGTERM"),"win32"!==process.platform&&Rt.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),"linux"===process.platform&&Rt.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var Pt,kt,Ut=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,Lt=Symbol.for("signal-exit emitter"),Dt=globalThis,Ot=Object.defineProperty.bind(Object),$t=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(Dt[Lt])return Dt[Lt];Ot(Dt,Lt,{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 o of this.listeners[e])r=!0===o(t,n)||r;return"exit"===e&&(r=this.emit("afterExit",t,n)||r),r}},Nt=class{},Bt=globalThis.process;Ut(Bt)?new class extends Nt{#e="win32"===Bt.platform?"SIGINT":"SIGHUP";#t=new $t;#n;#r;#o;#s={};#i=!1;constructor(e){super(),this.#n=e,this.#s={};for(const t of Rt)this.#s[t]=()=>{const n=this.#n.listeners(t);let{count:r}=this.#t;const o=e;if("object"==typeof o.__signal_exit_emitter__&&"number"==typeof o.__signal_exit_emitter__.count&&(r+=o.__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.#o=e.reallyExit,this.#r=e.emit}onExit(e,t){if(!Ut(this.#n))return()=>{};!1===this.#i&&this.load();const n=t?.alwaysLast?"afterExit":"exit";return this.#t.on(n,e),()=>{this.#t.removeListener(n,e),0===this.#t.listeners.exit.length&&0===this.#t.listeners.afterExit.length&&this.unload()}}load(){if(!this.#i){this.#i=!0,this.#t.count+=1;for(const e of Rt)try{const t=this.#s[e];t&&this.#n.on(e,t)}catch(e){}this.#n.emit=(e,...t)=>this.#a(e,...t),this.#n.reallyExit=e=>this.#c(e)}}unload(){this.#i&&(this.#i=!1,Rt.forEach(e=>{const t=this.#s[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.#o,this.#t.count-=1)}#c(e){return Ut(this.#n)?(this.#n.exitCode=e||0,this.#t.emit("exit",this.#n.exitCode,null),this.#o.call(this.#n,this.#n.exitCode)):0}#a(e,...t){const n=this.#r;if("exit"===e&&Ut(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)}}(Bt):new class extends Nt{onExit(){return()=>{}}load(){}unload(){}},new TextEncoder,function(){if(kt)return Pt;kt=1;const{PassThrough:e}=$;Pt=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",o),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",o.bind(null,e)),e.once("error",n.emit.bind(n,"error")),e.pipe(n,{end:!1}),this)}function o(e){!(t=t.filter(function(t){return t!==e})).length&&n.readable&&n.end()}}}();var jt=(async()=>{})().constructor.prototype;["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(jt,e)]);var Mt=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],Ht=/^[\w.-]+$/,Ft=N("execa").enabled,Gt=(e,t)=>String(e).padStart(t,"0"),Wt=(e,t,n={})=>{const o=bt._parse(e,t,n);return e=o.command,t=o.args,(n={maxBuffer:1e8,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:(n=o.options).cwd||g.cwd(),execPath:g.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:Ft,...n}).env=(({env:e,extendEnv:t,preferLocal:n,localDir:o,execPath:s})=>{const i=t?{...g.env,...e}:e;return n?(({env:e=g.env,...t}={})=>{const n=vt({env:e={...e}});return t.path=e[n],e[n]=(({cwd:e=g.cwd(),path:t=g.env[vt()],preferLocal:n=!0,execPath:o=g.execPath,addExecPath:s=!0}={})=>{const i=e instanceof URL?k(e):e,a=r.resolve(i),c=[];return n&&((e,t)=>{let n;for(;n!==t;)e.push(r.join(t,"node_modules/.bin")),n=t,t=r.resolve(t,"..")})(c,a),s&&((e,t,n)=>{const o=t instanceof URL?k(t):t;e.push(r.resolve(n,o,".."))})(c,o,a),[...c,t].join(r.delimiter)})(t),e})({env:i,cwd:o,execPath:s}):i})(n),n.stdio=(e=>{if(!e)return;const{stdio:t}=e;if(void 0===t)return Ct.map(t=>e[t]);if((e=>Ct.some(t=>void 0!==e[t]))(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${Ct.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,Ct.length);return Array.from({length:n},(e,n)=>t[n])})(n),"win32"===g.platform&&"cmd"===r.basename(e,".exe")&&t.unshift("/q"),{file:e,args:t,options:n,parsed:o}},Yt=(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 Vt(e,t,n){const r=Wt(e,t,n),o=((e,t)=>Mt(e,t).join(" "))(e,t),s=((e,t)=>Mt(e,t).map(e=>(e=>"string"!=typeof e||Ht.test(e)?e:`"${e.replaceAll('"','\\"')}"`)(e)).join(" "))(e,t);((e,{verbose:t})=>{t&&g.stderr.write(`[${(()=>{const e=new Date;return`${Gt(e.getHours(),2)}:${Gt(e.getMinutes(),2)}:${Gt(e.getSeconds(),2)}.${Gt(e.getMilliseconds(),3)}`})()}] ${e}\n`)})(s,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),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 At({error:e,stdout:"",stderr:"",all:"",command:o,escapedCommand:s,parsed:r,timedOut:!1,isCanceled:!1,killed:!1})}const c=Yt(r.options,a.stdout,a.error),l=Yt(r.options,a.stderr,a.error);if(a.error||0!==a.status||null!==a.signal){const e=At({stdout:c,stderr:l,error:a.error,signal:a.signal,exitCode:a.status,command:o,escapedCommand:s,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:o,escapedCommand:s,exitCode:0,stdout:c,stderr:l,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}}function zt(e){try{return Vt("git",["rev-parse","HEAD"],e).stdout}catch{return}}function Kt(e){try{const t=Vt("git",["rev-parse","--abbrev-ref","HEAD"],e).stdout;if("HEAD"===t){const t=Vt("git",["show","-s","--pretty=%d","HEAD"],e).stdout.replace(/^\(|\)$/g,"").split(", ").find(e=>e.startsWith("origin/"));return t?t.match(/^origin\/(?<branch>.+)/)[1]:void 0}return t}catch{return}}var qt=/^(?:.*)@(?:.*):(?:\d+\/)?(.*)\.git$/,Jt=/^\/(.*)\.git$/;function Qt(e){if(e){if(e.match(qt))return e.replace(qt,"$1");try{return new URL(e).pathname.replace(Jt,"$1")}catch{return}}}var Xt,Zt={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:Qt(e.BUILDKITE_REPO),pr:t,isPr:n,prBranch:n?e.BUILDKITE_BRANCH:void 0,root:e.BUILDKITE_BUILD_CHECKOUT_PATH}}},en={detect:({env:e})=>Boolean(e.CIRCLECI),configuration({env:e}){const t=e.CIRCLE_PR_NUMBER||$e(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}`}}},tn="https://cirrus-ci.com",nn={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:`${tn}/build/${e.CIRRUS_BUILD_ID}`,job:e.CIRRUS_TASK_ID,jobUrl:`${tn}/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}}},rn={detect:({env:e})=>Boolean(e.CODEBUILD_BUILD_ID),configuration:({env:e,cwd:t})=>({name:"AWS CodeBuild",service:"codebuild",commit:zt({env:e,cwd:t}),build:e.CODEBUILD_BUILD_ID,branch:Kt({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})},on={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}}},sn={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}}},an=({env:e})=>{try{const t=e.GITHUB_EVENT_PATH?JSON.parse(E(e.GITHUB_EVENT_PATH,"utf-8")):void 0;if(t&&t.pull_request)return{branch:t.pull_request.base?Ne(t.pull_request.base.ref):void 0,pr:t.pull_request.number}}catch{}return{pr:void 0,branch:void 0}},cn={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=Ne("pull_request_target"===e.GITHUB_EVENT_NAME?`refs/pull/${(e=>{const t=e.GITHUB_EVENT_PATH?JSON.parse(E(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?an({env:e}):void 0}}},ln={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}}},un={detect:({env:e})=>Boolean(e.JENKINS_URL),configuration({env:e,cwd:t}){const n=e.ghprbPullId||e.gitlabMergeRequestId||e.CHANGE_ID,r=Boolean(n),o=e.GIT_LOCAL_BRANCH||e.GIT_BRANCH||e.gitlabBranch||e.BRANCH_NAME;return{name:"Jenkins",service:"jenkins",commit:e.ghprbActualCommit||e.GIT_COMMIT||zt({env:e,cwd:t}),branch:r?e.ghprbTargetBranch||e.gitlabTargetBranch:o,build:e.BUILD_NUMBER,buildUrl:e.BUILD_URL,root:e.WORKSPACE,pr:n,isPr:r,prBranch:r?e.ghprbSourceBranch||e.gitlabSourceBranch||o:void 0}}},dn={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}}},pn={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})},fn={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}}},hn={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}}},mn={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}}},gn={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||zt({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}}},yn={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}}},bn={};function vn(){if(Xt)return bn;Xt=1,Object.defineProperty(bn,"__esModule",{value:!0}),bn.of=bn.PropertiesFile=void 0;var e,t=(e=b)&&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(),o=e.substring(n+1).trim();if(this.objs.hasOwnProperty(r))if(Array.isArray(this.objs[r]))this.objs[r].push(o);else{let e=this.objs[r];this.objs[r]=[e,o]}else{const e=o.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 bn.PropertiesFile=n,bn.of=function(...e){let t=new n;return t.of.apply(t,e),t},bn}var wn=We(vn()),_n={root:"teamcity.build.workingDir",branch:"teamcity.build.branch"},In=e=>{try{return wn.of(e)}catch{return}},En=({env:e,cwd:t})=>{const n=e.TEAMCITY_BUILD_PROPERTIES_FILE?In(e.TEAMCITY_BUILD_PROPERTIES_FILE):void 0,r=n?n.get("teamcity.configuration.properties.file"):void 0,o=r?In(r):r;return Object.fromEntries(Object.keys(_n).map(r=>[r,(n?n.get(_n[r]):void 0)||(o?o.get(_n[r]):void 0)||("branch"===r?Kt({env:e,cwd:t}):void 0)]))},Tn={appveyor:Oe,azurePipelines:Be,bamboo:je,bitbucket:Me,bitrise:He,buddy:Fe,buildkite:Zt,circleci:en,cirrus:nn,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:rn,codefresh:on,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:sn,github:cn,gitlab:ln,jenkins:un,netlify:dn,puppet:pn,sail:fn,screwdriver:hn,scrutinizer:mn,semaphore:gn,shippable:yn,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,...En({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:Ne(e.JB_SPACE_GIT_BRANCH),slug:t&&n?`${t.toLowerCase()}/${n}`:void 0}}}},Sn=class e{git;config;snapshotTreeHash;snapshotIndexPath;constructor(e){this.config=e,this.git=K({baseDir:e.workingDir,maxConcurrentProcesses:1})}static createLocal({workingDir:t}){return new e({mode:"local",workingDir:t})}static createCloud({workingDir:t,baseBranch:n}){return new e({mode:"cloud",workingDir:t,baseBranch:n})}async captureSnapshot(){if("local"!==this.config.mode)return;this.snapshotIndexPath=i(D(),`git-diff-tracker-${J()}.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(D(),`git-diff-tracker-${J()}.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 xn(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 xn(this.snapshotIndexPath),this.snapshotIndexPath=void 0),this.snapshotTreeHash=void 0}};async function xn(e){try{await ee(e)}catch{}}var An="x-stably-org-id",Cn={bodySerializer:e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t)},Rn=({allowReserved:e,explode:t,name:n,style:r,value:o})=>{if(!t){const t=(e?o:o.map(e=>encodeURIComponent(e))).join((e=>{switch(e){case"form":default:return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20"}})(r));switch(r){case"label":return`.${t}`;case"matrix":return`;${n}=${t}`;case"simple":return t;default:return`${n}=${t}`}}const s=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(r),i=o.map(t=>"label"===r||"simple"===r?e?t:encodeURIComponent(t):Pn({allowReserved:e,name:n,value:t})).join(s);return"label"===r||"matrix"===r?s+i:i},Pn=({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)}`},kn=({allowReserved:e,explode:t,name:n,style:r,value:o,valueOnly:s})=>{if(o instanceof Date)return s?o.toISOString():`${n}=${o.toISOString()}`;if("deepObject"!==r&&!t){let t=[];Object.entries(o).forEach(([n,r])=>{t=[...t,n,e?r:encodeURIComponent(r)]});const s=t.join(",");switch(r){case"form":return`${n}=${s}`;case"label":return`.${s}`;case"matrix":return`;${n}=${s}`;default:return s}}const i=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(r),a=Object.entries(o).map(([t,o])=>Pn({allowReserved:e,name:"deepObject"===r?`${n}[${t}]`:t,value:o})).join(i);return"label"===r||"matrix"===r?i+a:a},Un=/\{[^{}]+\}/g;function Ln(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 Dn,On=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},$n=({parameters:e={},...t}={})=>n=>{const r=[];if(n&&"object"==typeof n)for(const o in n){const s=n[o];if(null==s)continue;const i=e[o]||t;if(Array.isArray(s)){const e=Rn({allowReserved:i.allowReserved,explode:!0,name:o,style:"form",value:s,...i.array});e&&r.push(e)}else if("object"==typeof s){const e=kn({allowReserved:i.allowReserved,explode:!0,name:o,style:"deepObject",value:s,...i.object});e&&r.push(e)}else{const e=Pn({allowReserved:i.allowReserved,name:o,value:s});e&&r.push(e)}}return r.join("&")},Nn=(e,t)=>!!t&&!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`)),Bn=e=>(({baseUrl:e,path:t,query:n,querySerializer:r,url:o})=>{let s=(e??"")+(o.startsWith("/")?o:`/${o}`);t&&(s=(({path:e,url:t})=>{let n=t;const r=t.match(Un);if(r)for(const t of r){let r=!1,o=t.substring(1,t.length-1),s="simple";o.endsWith("*")&&(r=!0,o=o.substring(0,o.length-1)),o.startsWith(".")?(o=o.substring(1),s="label"):o.startsWith(";")&&(o=o.substring(1),s="matrix");const i=e[o];if(null==i)continue;if(Array.isArray(i)){n=n.replace(t,Rn({explode:r,name:o,style:s,value:i}));continue}if("object"==typeof i){n=n.replace(t,kn({explode:r,name:o,style:s,value:i,valueOnly:!0}));continue}if("matrix"===s){n=n.replace(t,`;${Pn({name:o,value:i})}`);continue}const a=encodeURIComponent("label"===s?`.${i}`:i);n=n.replace(t,a)}return n})({path:t,url:s}));let i=n?r(n):"";return i.startsWith("?")&&(i=i.substring(1)),i&&(s+=`?${i}`),s})({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:"function"==typeof e.querySerializer?e.querySerializer:$n(e.querySerializer),url:e.url}),jn=(e,t)=>{const n={...e,...t};return n.baseUrl?.endsWith("/")&&(n.baseUrl=n.baseUrl.substring(0,n.baseUrl.length-1)),n.headers=Hn(e.headers,t.headers),n},Mn=e=>{const t=[];return e.forEach((e,n)=>{t.push([n,e])}),t},Hn=(...e)=>{const t=new Headers;for(const n of e){if(!n)continue;const e=n instanceof Headers?Mn(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},Fn=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}},Gn=$n({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Wn={"Content-Type":"application/json"},Yn=(e={})=>({...Cn,headers:Wn,parseAs:"auto",querySerializer:Gn,...e}),Vn=(e={})=>{let t=jn(Yn(),e);const n=()=>({...t}),r={error:new Fn,request:new Fn,response:new Fn},o=async e=>{const n={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:Hn(t.headers,e.headers),serializedBody:void 0};return n.security&&await(async({security:e,...t})=>{for(const n of e){if(Nn(t,n.name))continue;const e=await On(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:Bn(n)}},s=async e=>{const{opts:t,url:n}=await o(e),s={redirect:"follow",...t,body:Ln(t)};let i=new Request(n,s);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=>s({...t,method:e}),a=e=>async t=>{const{opts:n,url:s}=await o(t);return(({onRequest:e,onSseError:t,onSseEvent:n,responseTransformer:r,responseValidator:o,sseDefaultRetryDelay:s,sseMaxRetryAttempts:i,sseMaxRetryDelay:a,sseSleepFn:c,url:l,...u})=>{let d;const p=c??(e=>new Promise(t=>setTimeout(t,e)));return{stream:async function*(){let c=s??3e3,f=0;const h=u.signal??(new AbortController).signal;for(;!h.aborted;){f++;const s=u.headers instanceof Headers?u.headers:new Headers(u.headers);void 0!==d&&s.set("Last-Event-ID",d);try{const t={redirect:"follow",...u,body:u.serializedBody,headers:s,signal:h};let i=new Request(l,t);e&&(i=await e(l,t));const a=u.fetch??globalThis.fetch,p=await a(i);if(!p.ok)throw new Error(`SSE failed: ${p.status} ${p.statusText}`);if(!p.body)throw new Error("No body in SSE response");const f=p.body.pipeThrough(new TextDecoderStream).getReader();let m="";const g=()=>{try{f.cancel()}catch{}};h.addEventListener("abort",g);try{for(;;){const{done:e,value:t}=await f.read();if(e)break;m+=t;const s=m.split("\n\n");m=s.pop()??"";for(const e of s){const t=e.split("\n"),s=[];let i,a;for(const e of t)if(e.startsWith("data:"))s.push(e.replace(/^data:\s*/,""));else if(e.startsWith("event:"))i=e.replace(/^event:\s*/,"");else if(e.startsWith("id:"))d=e.replace(/^id:\s*/,"");else if(e.startsWith("retry:")){const t=Number.parseInt(e.replace(/^retry:\s*/,""),10);Number.isNaN(t)||(c=t)}let l=!1;if(s.length){const e=s.join("\n");try{a=JSON.parse(e),l=!0}catch{a=e}}l&&(o&&await o(a),r&&(a=await r(a))),n?.({data:a,event:i,id:d,retry:c}),s.length&&(yield a)}}}finally{h.removeEventListener("abort",g),f.releaseLock()}break}catch(e){if(t?.(e),void 0!==i&&f>=i)break;const 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 o=new Request(e,t);for(const e of r.request.fns)e&&(o=await e(o,n));return o},url:s})};return{buildUrl:Bn,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:s,setConfig:e=>(t=jn(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")}},zn=Vn(Yn({baseUrl:"https://api.stably.ai"})),Kn=e=>(e.client??zn).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs",...e}),qn=e=>(e.client??zn).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}",...e}),Jn="4.10.4",Qn=process.env.STABLY_API_URL||"https://api.stably.ai",Xn=e=>{const t=new URL(e);return t.protocol="http:"===t.protocol?"ws:":"wss:",t},Zn=process.env.AUTH_URL||"https://auth.stably.ai",er=process.env.AUTH_CLIENT_ID||"288007877071cce81f269428ea78653a",tr=process.env.AI_PROXY_URL||"https://ai-proxy.stably.ai",nr=process.env.STABLY_AUTOHEAL_WS_URL||new URL("/autoheal",Xn(Qn)).toString(),rr=process.env.STABLY_CREATE_PROGRESS_WS_URL||new URL("/create-progress",Xn(Qn)).toString(),or="http://localhost:9876/auth/callback",sr=()=>Dn||(Dn=Vn(Yn({baseUrl:Qn,headers:{"X-STABLY-CLI-VERSION":Jn,"X-STABLY-SOURCE":"cli"}}))),ir=async(e,t)=>{const n=await(r={body:{accessToken:e,orgId:t},client:sr()},(r.client??zn).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},ar=fe.object({org_id:fe.string(),org_name:fe.string()}),cr=fe.object({email:fe.string(),org_id_to_org_member_info:fe.record(fe.string(),ar).optional(),org_member_info:ar.optional(),user_id:fe.string()});fe.object({email:fe.string(),firstName:fe.string().optional(),lastName:fe.string().optional(),organizations:fe.array(fe.object({id:fe.string(),name:fe.string()})),userId:fe.string()});var lr,ur=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)},dr=e=>{try{const t=cr.parse(ur(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"}`)}},pr=async(e,t)=>{let n=e;const{root:o}=r.parse(n);for(;n!==o;){const e=r.join(n,t);try{return await te(e),e}catch{n=r.dirname(n)}}},fr=r.join(L.homedir(),".stably"),hr=r.join(fr,"auth.json"),mr=".stably",gr="project.json",yr=pe.object({accessToken:pe.string(),expiresAt:pe.number(),idToken:pe.string().optional(),refreshToken:pe.string()}),br=pe.object({orgId:pe.string(),orgName:pe.string(),projectId:pe.string(),projectName:pe.string()}),vr=async()=>{try{const e=await Q(hr,"utf-8");return yr.parse(JSON.parse(e))}catch{return}},wr=async e=>{await X(fr,{recursive:!0}),await Z(hr,JSON.stringify(e,null,2),{mode:384})},_r=async()=>{try{await ee(hr)}catch{}},Ir=async()=>{try{const e=await pr(process.cwd(),mr);if(!e)return;const t=r.join(e,gr),n=await Q(t,"utf-8");return br.parse(JSON.parse(n))}catch{return}},Er=async()=>{try{const e=await pr(process.cwd(),mr);e&&await ee(r.join(e,gr))}catch{}},Tr=e=>Date.now()>=e.expiresAt-3e5,Sr=async e=>{const t=new URLSearchParams({client_id:er,grant_type:"refresh_token",refresh_token:e}),n=await fetch(`${Zn}/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}},xr=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`,Ar=(e,t,n)=>{e.writeHead(t,{"Content-Type":"text/html"}),e.end(n)},Cr=(e,t)=>{const n=new URLSearchParams({client_id:er,code_challenge:e,code_challenge_method:"S256",redirect_uri:or,response_type:"code",state:t});return`${Zn}/propelauth/oauth/authorize?${n.toString()}`},Rr=async e=>{const t=ce();let n;t.start("Loading user info...");try{n=dr(e.accessToken),t.stop(z.green(`✓ Logged in as ${z.cyan(n.email)}`))}catch(e){t.stop(z.red("✗ Failed to load user info"));const n=e instanceof Error?e.message:"Unknown error";return ie.error(n),{success:!1}}const o=await(async e=>{if(0===e.length)return void ie.error("You don't belong to any organizations.");if(1===e.length)return ie.info(`Using organization: ${z.cyan(e[0].name)}`),e[0];if(!process.stdin.isTTY)return ie.info(`Auto-selecting organization: ${z.cyan(e[0].name)}`),e[0];const t=await ue({message:"Select an organization",options:[...e].sort((e,t)=>e.name.localeCompare(t.name)).map(e=>({label:e.name,value:e.id}))});return de(t)?void 0:e.find(e=>e.id===t)})(n.organizations);if(!o)return ie.warn("Organization selection cancelled."),{success:!1};let s;t.start("Getting org credentials...");try{const n=await ir(e.accessToken,o.id);s={accessToken:n.accessToken,expiresAt:Date.now()+1e3*n.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken},t.stop(z.green("✓ Credentials obtained"))}catch(e){t.stop(z.red("✗ Failed to get org credentials"));const n=e instanceof Error?e.message:"Unknown error";return ie.error(n),{success:!1}}const i=await(async(e,t)=>{const n=ce();let r;n.start("Loading projects...");try{r=await(async({accessToken:e,orgId:t})=>{const n=await(r={auth:e,client:sr(),path:{orgId:t}},(r.client??zn).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(z.green("✓ Projects loaded"))}catch(e){n.stop(z.red("✗ Failed to load projects"));const t=e instanceof Error?e.message:"Unknown error";return void ie.error(t)}if(0===r.length)return ie.error("No projects found in this organization."),void ie.info(`Create a project at ${z.underline(z.cyan("https://app.stably.ai"))}`);if(1===r.length)return ie.info(`Using project: ${z.cyan(r[0].name)}`),r[0];if(!process.stdin.isTTY)return ie.info(`Auto-selecting project: ${z.cyan(r[0].name)}`),r[0];const o=await ue({message:"Select a project",options:r.map(e=>({label:e.name,value:e.id}))});return de(o)?void 0:r.find(e=>e.id===o)})(s.accessToken,o.id);return i?(await(async e=>{const t=r.join(process.cwd(),mr),n=r.join(t,gr);await X(t,{recursive:!0}),await Z(n,JSON.stringify(e,null,2)),await(async e=>{const t=r.join(e,".gitignore"),n="# Stably CLI (only docs/ are tracked)\n.stably/*\n!.stably/docs/";try{const e=await Q(t,"utf-8"),r=e.split("\n").map(e=>e.trim());if(r.includes(".stably/*")&&r.includes("!.stably/docs/"))return;const o=/^# Stably CLI\n\.stably\/?$/m,s=/^\.stably\/?$/m;if(o.test(e)){const r=e.replace(o,`\n${n}\n`);await Z(t,r)}else if(s.test(e)){const r=e.replace(s,`\n${n}\n`);await Z(t,r)}else await se(t,`\n${n}\n`)}catch{await Z(t,`${n}\n`)}})(process.cwd())})({orgId:o.id,orgName:o.name,projectId:i.id,projectName:i.name}),ie.info(z.dim("Linked this directory to your Stably project.")),{scopedTokens:s,success:!0}):(ie.warn("Project selection cancelled."),{success:!1})},Pr=async()=>{if(qr())return ie.warn(`Environment variables ${z.cyan("STABLY_API_KEY")} and ${z.cyan("STABLY_PROJECT_ID")} are set.`),ie.warn("These will be used for authentication instead of OAuth login."),ie.warn("To use OAuth login, unset these environment variables first."),void ae(z.yellow("Login skipped - using environment variable authentication."));const e=await vr();if(e){if(!Tr(e)){if(await Ir())return void ae(z.yellow("You are already logged in. Run `stably logout` first to log out."));ie.info("You are logged in but haven't selected a project yet.");const t=await Rr(e);return void(t.success?(await wr(t.scopedTokens),ae(z.green("Setup complete! You can now use Stably CLI."))):ae(z.yellow("Setup incomplete. Run `stably login` to try again.")))}const t=ce();t.start("Refreshing session...");try{const n=await Sr(e.refreshToken);t.stop(z.green("✓ Session refreshed"));const r=await Ir();if(r){t.start("Getting org credentials...");try{const e=await ir(n.accessToken,r.orgId),o={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:n.idToken,refreshToken:n.refreshToken};await wr(o),t.stop(z.green("✓ Credentials obtained")),ae(z.green("Login successful"))}catch{await wr(n),t.stop(z.yellow("Using full credentials")),ae(z.green("Login successful"))}}else{const e=await Rr(n);e.success?(await wr(e.scopedTokens),ae(z.green("Setup complete! You can now use Stably CLI."))):ae(z.yellow("Setup incomplete. Run `stably login` to try again."))}return}catch{t.stop(z.yellow("Session expired, proceeding with fresh login...")),await _r(),await Er()}}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:Cr(t,r),codeVerifier:e,state:r}})(),{ready:r,result:o}=(e=>{let t,n;return{ready:new Promise((e,r)=>{t=e,n=r}),result:new Promise((r,o)=>{const s=setTimeout(()=>{a.close(),r({error:"Login timed out",success:!1})},3e5),i=()=>{clearTimeout(s)},a=me.createServer((t,n)=>{const o=new U(t.url||"","http://localhost:9876");if("/auth/callback"!==o.pathname)return n.writeHead(404),void n.end("Not found");const s=o.searchParams.get("code"),c=o.searchParams.get("state"),l=o.searchParams.get("error");return l?(Ar(n,400,xr(l)),i(),a.close(),void r({error:l,success:!1})):s&&c?c!==e?(Ar(n,400,xr("Invalid state parameter (possible CSRF attack)")),i(),a.close(),void r({error:"State mismatch",success:!1})):(Ar(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:s,state:c,success:!0})):(Ar(n,400,xr("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 o(e)}const t=new Error(`Failed to start callback server: ${e.message}`);n(t),o(t)}),a.listen(9876,()=>{t()})})}})(n);return{authorizeUrl:e,serverReady:r,waitForCallback:async()=>{const e=await o;if(!e.success)throw new Error(e.error);return(async(e,t)=>{const n=new URLSearchParams({client_id:er,code:e,code_verifier:t,grant_type:"authorization_code",redirect_uri:or}),r=await fetch(`${Zn}/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 o=await r.json();return{accessToken:o.access_token,expiresAt:Date.now()+1e3*o.expires_in,idToken:o.id_token,refreshToken:o.refresh_token}})(e.code,t)}}})();await n,ie.info("Opening browser for authentication..."),ie.info(z.dim("If browser doesn't open, visit:")),ie.info(`]8;;${t}${z.underline(z.cyan(t))}]8;;`);try{await he(t)}catch{ie.warn("Could not open browser automatically. Please open the URL above manually.")}const o=ce();let s;o.start("Waiting for authentication...");try{s=await r(),o.stop(z.green("✓ Authentication successful"))}catch(e){o.stop(z.red("✗ Authentication failed"));const t=e instanceof Error?e.message:"Unknown error";ae(z.red(`Login failed: ${t}`)),process.exit(1)}const i=await Rr(s);i.success?(await wr(i.scopedTokens),ae(z.green("Setup complete! You can now use Stably CLI."))):(ae(z.yellow("Setup incomplete. Run `stably login` to try again.")),process.exit(1))},kr={fatal:60,error:50,warn:40,info:30,debug:20,trace:10},Ur=new Set(["help","login","logout","whoami","tunnel","create","fix","init","upgrade","test","show-report","codegen"]),Lr=(new Date).toISOString().split("T")[0],Dr=(()=>{const e=[r.join(L.tmpdir(),"stably-logs",Lr),r.join(L.homedir(),".stably","logs",Lr)];for(const t of e)try{return b.mkdirSync(t,{recursive:!0}),t}catch{}return null})(),Or=process.argv.includes("--verbose")||process.argv.includes("-v"),$r=process.env.STABLY_LOG_LEVEL?.toLowerCase(),Nr=Or?"debug":void 0!==(lr=$r)&&lr in kr?$r:"warn",Br=kr[Nr],jr=null,Mr=null,Hr=null,Fr=[],Gr=!1,Wr=e=>{if(!Gr){if(!(jr=(e=>{if(!Dr)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(Dr,`${t}-${n}.log`)})(e)))return Fr=[],void(Gr=!0);(e=>{const t=["","=".repeat(60),"Stably CLI Debug Log",`Version: ${Jn}`,`Generated: ${(new Date).toISOString()}`,`Node: ${process.version}`,`Platform: ${process.platform} ${L.release()}`,`CWD: ${process.cwd()}`,`Args: ${process.argv.slice(2).join(" ")}`,`Log Level (console): ${Nr}`,"=".repeat(60),""].join("\n");e.write(t)})(Mr=new ye({dest:jr,minLength:4096,sync:!1,append:!0})),Hr=ge({level:"debug",timestamp:ge.stdTimeFunctions.isoTime,base:{version:Jn}},Mr);for(const{level:e,msg:t,context:n}of Fr)n?Hr[e](n,t):Hr[e](t);Fr=[],Gr=!0,Or&&process.stderr.write(`${z.dim(`Debug log: ${jr}`)}\n\n`)}},Yr=(()=>{const e=process.argv.slice(2).find(e=>!e.startsWith("-"));return e&&Ur.has(e)?e:null})();Yr&&Wr(Yr);var Vr=e=>(t,n)=>{if(Hr?n?Hr[e](n,t):Hr[e](t):Gr||Fr.push({level:e,msg:t,context:n}),(e=>kr[e]>=Br)(e)){const n=((e,t)=>`${{fatal:z.bgRed(z.white(" FATAL ")),error:z.red("error"),warn:z.yellow("warn"),info:z.cyan("info"),debug:z.dim("debug"),trace:z.dim("trace")}[e]} ${t}`)(e,t);process.stderr.write(`${n}\n`)}},zr={fatal:Vr("fatal"),error:Vr("error"),warn:Vr("warn"),info:Vr("info"),debug:Vr("debug"),trace:Vr("trace"),initSession:e=>{Gr||Wr(e)},getLogFilePath:()=>jr,flush:()=>{if(Mr)try{Mr.flushSync()}catch{}},printLogFileInfo:()=>{jr&&(process.stderr.write(`\n${z.dim("Debug log written to:")}\n`),process.stderr.write(` ${z.cyan(jr)}\n`),process.stderr.write(`${z.dim("Share this file with support for assistance.")}\n`))},getPinoLogger:()=>Hr};setInterval(()=>{zr.flush()},3e4).unref(),process.on("beforeExit",()=>{zr.flush()});var Kr=e=>{const t=()=>{zr.flush(),Or&&zr.printLogFileInfo(),process.removeListener(e,t),process.kill(process.pid,e)};return t};process.on("SIGINT",Kr("SIGINT")),process.on("SIGTERM",Kr("SIGTERM"));var qr=()=>{const e=process.env.STABLY_API_KEY?.trim(),t=process.env.STABLY_PROJECT_ID?.trim();if(e&&t)return zr.debug("Environment auth detected",{hasApiKey:!0,hasProjectId:!0}),{apiKey:e,projectId:t};zr.debug("Environment auth not set",{hasApiKey:!!e,hasProjectId:!!t})},Jr=async()=>{zr.debug("Checking for stored auth tokens");const e=await vr();if(!e)return void zr.debug("No stored auth tokens found");const t=Tr(e);if(zr.debug("Auth tokens status",{expired:t}),!t){const t=await Ir(),n=(e=>{try{const t=cr.parse(ur(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(zr.debug("Token scope check",{scope:n,hasContext:!!t}),t&&"full"===n)try{zr.debug("Exchanging full token for org-scoped token",{orgId:t.orgId});const n=await ir(e.accessToken,t.orgId),r={accessToken:n.accessToken,expiresAt:Date.now()+1e3*n.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken};return await wr(r),zr.debug("Token exchange successful"),r}catch(t){return zr.debug("Token exchange failed, using existing token",{error:t instanceof Error?t.message:String(t)}),e}return e}try{zr.debug("Attempting token refresh");const t=await Sr(e.refreshToken);zr.debug("Token refresh successful");const n=await Ir();if(n)try{zr.debug("Exchanging refreshed token for org-scoped token");const e=await ir(t.accessToken,n.orgId),r={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:t.idToken,refreshToken:t.refreshToken};return await wr(r),r}catch{return await wr(t),t}return await wr(t),t}catch(e){return void zr.warn("Token refresh failed",{error:e instanceof Error?e.message:String(e)})}},Qr=async(e={})=>{zr.debug("Requiring authentication",{autoLogin:e.autoLogin});const t=qr();if(t)return zr.info("Using environment variable authentication"),{auth:t,type:"env"};let n=await Jr(),r=n?await Ir():void 0;const o=process.stdin.isTTY&&process.stdout.isTTY;if(zr.debug("OAuth auth check",{hasTokens:!!n,hasContext:!!r,canPrompt:o}),(!n||!r)&&e.autoLogin&&o){zr.info("Prompting user to login"),n?ie.info("You are logged in but need to select an organization and project."):ie.info("You are not logged in."),ie.info("Press Enter to log in."),process.stdout.write(`${z.dim("Alternatively, set environment variables for an org API key:")}\n${z.dim(" STABLY_API_KEY=... STABLY_PROJECT_ID=... stably")}\n`),process.stdout.write("\n");const e=V({input:process.stdin,output:process.stdout});try{await e.question(z.dim("Press Enter to continue... "))}finally{e.close()}await Pr(),n=await Jr(),r=n?await Ir():void 0}return n||(zr.warn("Authentication required but no tokens available"),ae(z.red("You are not logged in. Run `stably login` to authenticate.")),process.exit(1)),r||(zr.warn("Authentication succeeded but no project context selected"),ae(z.red("You haven't selected an organization and project. Run `stably login` to complete setup.")),process.exit(1)),zr.info("OAuth authentication successful",{orgId:r.orgId,projectId:r.projectId}),{auth:{accessToken:n.accessToken,context:r},type:"oauth"}},Xr=e=>"env"===e.type?e.auth.projectId:e.auth.context.projectId,Zr=e=>"env"===e.type?e.auth.apiKey:e.auth.accessToken,eo=e=>e?{...process.env,...e}:process.env,to=async()=>{zr.info("[test] Resolving Stably test env");const e=(()=>{if(process.env.STABLY_WS_URL)return;if("https://api.stably.ai"===Qn)return;const e=Qn.startsWith("http://")?"ws://":"wss://";return`${Qn.replace(/^https?:\/\//,e).replace(/\/$/,"")}/reporter`})();zr.debug("[test] WebSocket URL resolved",{wsUrl:e??"(default)"});const t=qr();if(t)return zr.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}};zr.info("[test] No env var auth, attempting OAuth auth");const n=Date.now(),r=await(async()=>{const e=qr();if(e)return{auth:e,type:"env"};const t=await Jr(),n=t?await Ir():void 0;return t&&n?{auth:{accessToken:t.accessToken,context:n},type:"oauth"}:void 0})();if(zr.info("[test] OAuth auth resolved",{durationMs:Date.now()-n,hasAuth:!!r,authType:r?.type}),!r||"env"===r.type)return void zr.info("[test] No usable auth found");const o=process.env.STABLY_PROJECT_ID?.trim(),s=o||Xr(r);if(!s)return void zr.warn("[test] No project ID available");zr.info("[test] Fetching JWT API key",{projectId:s});const i=Date.now(),a=await(async(e,t)=>{try{zr.debug("Requesting JWT API key",{projectId:t,apiUrl:Qn});const n=await(async({accessToken:e,projectId:t})=>{const n=await(r={auth:e,client:sr(),path:{projectId:t}},(r.client??zn).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 zr.debug("JWT API key obtained",{keyPrefix:n.apiKey.substring(0,10)}),n.apiKey}catch(e){return void zr.warn("Failed to get JWT API key for test reporter",{error:e instanceof Error?e.message:String(e)})}})(r.auth.accessToken,s);zr.info("[test] JWT API key fetch complete",{durationMs:Date.now()-i,success:!!a});const c=a?{STABLY_API_KEY:a,STABLY_PROJECT_ID:s,...e&&{STABLY_WS_URL:e}}:void 0;return zr.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},no=async()=>{const e=Pe.remoteEnvName;if(!e)return;const t=await Qr(),n=Xr(t),r=Zr(t);zr.debug("Fetching remote environment variables",{envName:e,projectId:n});const o=await(s={auth:r,client:sr(),path:{projectId:n,environment:e}},(s.client??zn).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/environments/{environment}/variables",...s}));var s;404===o.response.status&&(ae(z.red(`Environment "${e}" not found. Check the name on your Stably dashboard.`)),process.exit(1)),401!==o.response.status&&403!==o.response.status||(ae(z.red(`Access denied to environment "${e}".`)),process.exit(1)),o.error&&(ae(z.red(`Failed to fetch environment "${e}": ${o.response.status}`)),process.exit(1));const i={},a=[];for(const e of o.data.variables)i[e.name]=e.value,e.sensitive&&e.value.length>0&&a.push(e.value);const c=o.data.variables.length,l=a.length;return process.stderr.write(`${z.cyan(`Loaded ${c} variable${1!==c?"s":""} from "${e}"`)}${l>0?z.dim(` (${l} sensitive)`):""}\n`),{variables:i,sensitiveValues:a}},ro=e=>e?{[An]:e}:void 0,oo=fe.object({context:fe.string().min(1),autohealReportUrl:fe.string(),skippedTests:fe.array(fe.object({testIdentifier:fe.string(),testTitle:fe.string(),consecutiveUnfixedCount:fe.number()})).optional()}),so=be.object({bucket:be.string(),key:be.string()}),io=async({body:e,contentType:t,uploadUrl:n,errorContext:r="content"})=>{const o=await fetch(n,{body:e instanceof Uint8Array?Buffer.from(e):e,headers:{"Content-Type":t},method:"PUT"});if(!o.ok)throw new Error(`Failed to upload ${r} (${o.status})`)},ao=be.object({diffBucketPath:so,expiresInSeconds:be.number(),key:be.string(),uploadUrl:be.string()}),co=be.object({traceBucketPath:so,expiresInSeconds:be.number(),key:be.string(),uploadUrl:be.string(),sensitiveValues:be.array(be.string())}),lo=async({authHeader:e,contentType:t="text/plain",orgId:n,runId:r})=>{const o=await(s={auth:e,body:{contentType:t},client:sr(),headers:ro(n),path:{runId:r}},(s.client??zn).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-diff/upload-url",...s,headers:{"Content-Type":"application/json",...s.headers}}));var s;if(o.error)throw new Error(`Failed to presign diff upload (${o.response.status})`);const i=ao.parse(o.data);return{diffBucketPath:i.diffBucketPath,expiresInSeconds:i.expiresInSeconds,key:i.key,uploadUrl:i.uploadUrl}},uo=async({authHeader:e,diffBucketPath:t,orgId:n,runId:r})=>{const o=await(s={auth:e,body:t,client:sr(),headers:ro(n),path:{runId:r}},(s.client??zn).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-diff/confirm-upload",...s,headers:{"Content-Type":"application/json",...s.headers}}));var s;if(o.error)throw new Error(`Failed to confirm diff upload (${o.response.status})`)},po=class{socket;url;authHeader;orgId;runId;pendingEvent=null;reconnectAttempts=0;reconnectTimer;debounceTimer;_isClosed=!1;isAuthenticated=!1;authenticationFailed=!1;onUserMessage;maxReconnectAttempts=3;reconnectDelay=2e3;debounceMs=500;get isClosed(){return this._isClosed}constructor({authHeader:e,orgId:t,runId:n,url:r=nr,onUserMessage:o}){this.authHeader=e,this.orgId=t,this.runId=n,this.url=r,this.onUserMessage=o,zr.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)}`;zr.info("[ws] Connecting",{url:t,attempt:this.reconnectAttempts}),this.socket=new ve(t,{headers:e}),this.socket.on("open",()=>{zr.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);zr.debug("[ws] Received message",{type:n?.type}),"connected"===n?.type&&(zr.info("[ws] Authenticated successfully"),this.isAuthenticated=!0,this.authenticationFailed=!1,this.flushPending()),"user_message"===n?.type&&"string"==typeof n.content&&(zr.info("[ws] Received user message from web UI"),this.onUserMessage?.(n.content))}catch{}}),this.socket.on("close",(e,t)=>{zr.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=>{zr.warn("[ws] Connection error",{error:e.message})})}catch(e){zr.warn("[ws] Failed to create WebSocket",{error:e instanceof Error?e.message:String(e)}),this.scheduleReconnect()}}scheduleReconnect(){this._isClosed||this.reconnectTimer||(this.reconnectAttempts++,zr.info("[ws] Scheduling reconnect",{attempt:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts,delayMs:this.reconnectDelay}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect()},this.reconnectDelay))}isConnected(){return!!this.socket&&this.socket.readyState===ve.OPEN&&this.isAuthenticated}sendProgress(e){if(this._isClosed)return void zr.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?(zr.info("[ws] sendProgress: flushing terminal state immediately"),void this.flushPending()):void(this.debounceTimer||(this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.flushPending()},this.debounceMs))):(zr.debug("[ws] sendProgress: not connected, queuing event",{phase:e.phase,socketState:this.socket?.readyState,isAuthenticated:this.isAuthenticated,reconnectAttempts:this.reconnectAttempts}),void(this.socket?.readyState===ve.CLOSED&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()))}flushPending(){if(this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),!this.pendingEvent)return;const e=this.pendingEvent;if(this.pendingEvent=null,!this.isConnected())return zr.debug("[ws] flushPending: not connected, re-queuing event",{phase:e.payload.phase}),void(this.pendingEvent=e);try{zr.debug("[ws] flushPending: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),t=>{t&&(zr.warn("[ws] flushPending: send failed",{error:t.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e))})}catch(t){zr.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{zr.debug("[ws] flushPendingAndWait: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),n=>{n&&(zr.warn("[ws] flushPendingAndWait: send failed",{error:n.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e)),t()})}catch(n){zr.warn("[ws] flushPendingAndWait: send threw",{error:n instanceof Error?n.message:String(n)}),this.pendingEvent=e,t()}}):(zr.debug("[ws] flushPendingAndWait: not connected, re-queuing event",{phase:e.payload.phase}),this.pendingEvent=e,Promise.resolve())}close(){if(this._isClosed)return;zr.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;zr.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())}},fo=class{socket;url;authHeader;orgId;sessionId;pendingEvent=null;reconnectAttempts=0;reconnectTimer;debounceTimer;_isClosed=!1;isAuthenticated=!1;authenticationFailed=!1;onUserMessage;maxReconnectAttempts=3;reconnectDelay=2e3;debounceMs=500;get isClosed(){return this._isClosed}constructor({authHeader:e,orgId:t,sessionId:n,url:r=rr,onUserMessage:o}){this.authHeader=e,this.orgId=t,this.sessionId=n,this.url=r,this.onUserMessage=o,zr.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)}`;zr.info("[ws] Connecting",{url:t,attempt:this.reconnectAttempts}),this.socket=new ve(t,{headers:e}),this.socket.on("open",()=>{zr.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);zr.debug("[ws] Received message",{type:n?.type}),"connected"===n?.type&&(zr.info("[ws] Authenticated successfully"),this.isAuthenticated=!0,this.authenticationFailed=!1,this.flushPending()),"user_message"===n?.type&&"string"==typeof n.content&&(zr.info("[ws] Received user message from web UI"),this.onUserMessage?.(n.content))}catch{}}),this.socket.on("close",(e,t)=>{zr.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=>{zr.warn("[ws] Connection error",{error:e.message})})}catch(e){zr.warn("[ws] Failed to create WebSocket",{error:e instanceof Error?e.message:String(e)}),this.scheduleReconnect()}}scheduleReconnect(){this._isClosed||this.reconnectTimer||(this.reconnectAttempts++,zr.info("[ws] Scheduling reconnect",{attempt:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts,delayMs:this.reconnectDelay}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect()},this.reconnectDelay))}isConnected(){return!!this.socket&&this.socket.readyState===ve.OPEN&&this.isAuthenticated}sendProgress(e){if(this._isClosed)return void zr.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?(zr.info("[ws] sendProgress: flushing terminal state immediately"),void this.flushPending()):void(this.debounceTimer||(this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.flushPending()},this.debounceMs))):(zr.debug("[ws] sendProgress: not connected, queuing event",{phase:e.phase,socketState:this.socket?.readyState,isAuthenticated:this.isAuthenticated,reconnectAttempts:this.reconnectAttempts}),void(this.socket?.readyState===ve.CLOSED&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()))}flushPending(){if(this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),!this.pendingEvent)return;const e=this.pendingEvent;if(this.pendingEvent=null,!this.isConnected())return zr.debug("[ws] flushPending: not connected, re-queuing event",{phase:e.payload.phase}),void(this.pendingEvent=e);try{zr.debug("[ws] flushPending: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),t=>{t&&(zr.warn("[ws] flushPending: send failed",{error:t.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e))})}catch(t){zr.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{zr.debug("[ws] flushPendingAndWait: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),n=>{n&&(zr.warn("[ws] flushPendingAndWait: send failed",{error:n.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e)),t()})}catch(n){zr.warn("[ws] flushPendingAndWait: send threw",{error:n instanceof Error?n.message:String(n)}),this.pendingEvent=e,t()}}):(zr.debug("[ws] flushPendingAndWait: not connected, re-queuing event",{phase:e.payload.phase}),this.pendingEvent=e,Promise.resolve())}close(){if(this._isClosed)return;zr.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;zr.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())}},ho=be.object({bucketPath:so,expiresInSeconds:be.number(),key:be.string(),uploadUrl:be.string()}),mo=fe.object({uploadUrl:fe.string(),key:fe.string(),bucketPath:fe.object({bucket:fe.string(),key:fe.string()}),expiresInSeconds:fe.number()});async function go({authHeader:e,orgId:t,sessionId:n,projectId:r,history:o}){if(0===o.length)return zr.debug("[session-history] No history to upload"),{success:!0};try{zr.info("[session-history] Requesting upload URL",{sessionId:n,messageCount:o.length});const{uploadUrl:s,key:i}=await async function({authHeader:e,orgId:t,sessionId:n,projectId:r}){const o=new URL(`/internal/v1/cli/sessions/${n}/history/upload-url`,Qn),s={Authorization:e,"Content-Type":"application/json"};t&&(s["x-stably-org-id"]=t);const i=await fetch(o,{method:"POST",headers:s,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 mo.parse(await i.json())}({authHeader:e,orgId:t,sessionId:n,projectId:r}),a=o.map(e=>JSON.stringify(e)).join("\n");zr.info("[session-history] Uploading history",{key:i,messageCount:o.length,sizeBytes:a.length});const c=await fetch(s,{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 zr.info("[session-history] History uploaded successfully",{key:i}),{success:!0,key:i}}catch(e){const t=e instanceof Error?e.message:String(e);return zr.warn("[session-history] Failed to upload history",{error:t}),{success:!1,error:t}}}var yo=["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 bo(e){return/^\.env(\..*)?$/.test(e)||".stably-agent.env"===e}function vo(e){return Boolean(e&&"object"==typeof e&&"tool_input"in e&&e.tool_input&&"object"==typeof e.tool_input)}function wo({action:e,pathKey:t}){return function({action:e,fileCheck:t,getBlockMessage:n,pathKey:r}){return async o=>{const s=function({input:e,pathKey:t}){if(!vo(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:o,pathKey:r});if(!s.success)return s;const i=s.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:bo,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 _o=["rm","mv","git","gh","npx","stably","npm","yarn","pnpm","bun"],Io=["stably"],Eo=["create","fix","verify"],To=["push","fetch","pull","clone","ls-remote"];function So(e){return e.trim().split(/\s+/).filter(e=>e.length>0)}function xo(e){return So(e).find(e=>Eo.includes(e))}function Ao(e,t){const n=c(e).replace(/\\/g,"/"),r=t.replace(/\\/g,"/"),o=r.endsWith("/")?r:`${r}/`;if(n.startsWith(o))return!0;const s=n.lastIndexOf(`/${o}`);if(-1===s)return!1;const i=n.slice(s+`/${o}`.length);return i.length>0&&!i.startsWith("../")}function Co({onBeforeGitHubCommand:e,workspaceBoundary:t}){return async n=>{if(!vo(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().match(/^(?:\S+=\S+\s+)*(\S+)/);return t?.[1]}(i);if(!c)return{decision:"block",reason:"Invalid Bash command: could not parse command.",systemMessage:"Tool call blocked due to unparseable command"};if(!function(e){return"string"==typeof e&&_o.includes(e)}(c))return{decision:"block",reason:`The command "${c}" is not allowed. Only the following commands are permitted: ${_o.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=function(e){const t=function(e){let t=0;for(;t<e.length&&/^\S+=\S+$/.test(e[t]??"");)t+=1;return e.slice(t)}(So(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}}}(e);if(!t)return{valid:!1,reason:"Invalid npx command: unable to determine which binary is being executed."};if(!new Set(Io).has(t))return{valid:!1,reason:`The npx binary "${t}" is not allowed. Only ${Io.join(", ")} are permitted.`};const n=xo(e);return n?{valid:!1,reason:`The npx ${t} subcommand "${n}" is not allowed. The commands ${Eo.join(", ")} are AI-powered and blocked to prevent recursion.`}:{valid:!0}}(i);if(!e.valid)return{decision:"block",reason:e.reason,systemMessage:"Tool call blocked due to disallowed npx command"}}if("stably"===c){const e=xo(i);if(e)return{decision:"block",reason:`The stably subcommand "${e}" is not allowed. The commands ${Eo.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(v(e))return _.native(e);let t=e;const n=[];for(;!v(t);){const r=s(t);if(r===t)return o(e);n.unshift(t.slice(r.length+1)),t=r}const r=_.native(t);return n.length>0?o(r,...n):r}(e),r=_.native(t),i=n.endsWith(a)?n:n+a,c=r.endsWith(a)?r:r+a;return i.startsWith(c)||n===r}({targetPath:o(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=>!(Ao(e,"tests")||Ao(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 ")&&To.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 yo.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 Ro=e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"text"===t.type&&"string"==typeof t.text},Po=e=>null!=e&&"object"==typeof e&&"tool_response"in e,ko=e=>{if(!e||"object"!=typeof e)return;const t=e;return Array.isArray(t.tool_response)?t.tool_response:void 0},Uo=e=>{const t=ko(e);if(t)return t.filter(Ro).map(e=>e.text).join("\n")||void 0},Lo=/\u001b\[[0-9;]*m/g,Do=e=>e.replace(Lo,""),Oo=/\$\{process\.env\.([A-Z_][A-Z0-9_]*)\}/g;function $o(e,t){return e.replace(Oo,(e,n)=>{const r=t[n];return null!=r?r:e})}function No({envVars:e}){return async t=>{if(!vo(t))return{decision:"approve"};const n=t.tool_input,r={...n};let o=!1;if("string"==typeof n.text){const t=$o(n.text,e);t!==n.text&&(r.text=t,o=!0)}if("string"==typeof n.url){const t=$o(n.url,e);t!==n.url&&(r.url=t,o=!0)}if("string"==typeof n.function){const t=$o(n.function,e);t!==n.function&&(r.function=t,o=!0)}if(Array.isArray(n.fields)){const t=n.fields.map(t=>{if("string"==typeof t.value){const n=$o(t.value,e);if(n!==t.value)return o=!0,{...t,value:n}}return t});o&&(r.fields=t)}return o?{decision:"approve",hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",reason:"Evaluated environment variable placeholders in browser tool input.",updatedInput:r}}:{decision:"approve"}}}function Bo({onResult:e}){return async t=>{if(!Po(t))return{decision:"approve"};const n=Uo(t);if(!n)return{decision:"approve"};const r=function(e){const t=Do(e),n=t.split(/Running \d+ tests? using \d+ workers?/).at(-1)??t,r=parseInt(n.match(/(\d+)\s+passed/g)?.at(-1)?.match(/(\d+)/)?.[1]??"0"),o=parseInt(n.match(/(\d+)\s+failed/g)?.at(-1)?.match(/(\d+)/)?.[1]??"0");if(0===r&&0===o)return;const s=[r>0?`${r} test${1===r?"":"s"} passed ✓`:void 0,o>0?`${o} test${1===o?"":"s"} failed ✗`:void 0].filter(e=>void 0!==e).join(", ");if(0===o)return s;const i=n.split(/\n\s+\d+\)\s+\[id=/).slice(1).map(e=>e.match(/\n\s{4}((?:TimeoutError|Error|AssertionError):\s*[^\n]+)/)?.[1]?.trim()).filter(e=>void 0!==e);return 0===i.length?s:`${s}\n${i.map(e=>` - ${e}`).join("\n")}`}(n);return r&&e(r),{decision:"approve"}}}function jo({onResult:e}){return async t=>{if(!Po(t))return{decision:"approve"};const n=Uo(t);if(!n)return{decision:"approve"};const r=function(e){const t=Do(e);if(t.match(/### Paused on error:/)){const e=t.match(/### Paused on error:\s*\n((?:TimeoutError|Error|AssertionError):\s*[^\n]+)/);return e?`Test paused on error - ${e[1].trim()}`:"Test paused on error"}const n=t.match(/(\d+)\s+passed/);if(n){const e=parseInt(n[1]);return`${e} test${1===e?"":"s"} passed ✓`}}(n);return r&&e(r),{decision:"approve"}}}var Mo=/\.(spec|test)\.(ts|tsx|js|jsx|mts|mjs)$/;function Ho({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&&Mo.test(r)&&e(r),{decision:"approve"}}}var Fo=B(f);async function Go(){try{const{stdout:e}=await Fo('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 Fo(`pkill -KILL -P ${e} '.*' 2>/dev/null || true`)}))}catch{}}var Wo=class{queue=[];pendingResolve=void 0;done=!1;canSend=!0;[Symbol.asyncIterator](){return this}pushText(e){const t=e.trim();t&&!this.done&&(this.queue.push(t),this.maybeFlush())}allowNextTurn(){this.done||(this.canSend=!0,this.maybeFlush())}hasQueuedMessages(){return this.queue.length>0}finish(){this.done=!0,this.pendingResolve&&(this.pendingResolve({done:!0,value:void 0}),this.pendingResolve=void 0)}maybeFlush(){if(!this.pendingResolve)return;if(!this.canSend)return;const e=this.queue.shift();if(void 0===e)return;const t={message:{content:[{text:e,type:"text"}],role:"user"},parent_tool_use_id:null,type:"user",session_id:""};this.canSend=!1,this.pendingResolve({done:!1,value:t}),this.pendingResolve=void 0}next(){return this.done?Promise.resolve({done:!0,value:void 0}):new Promise(e=>{this.pendingResolve=e,this.maybeFlush()})}};function Yo(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 Vo=[".ts",".js",".mts",".mjs",".cts",".cjs"],zo=10240,Ko=async({defaultContent:e,fileName:t,filePath:n})=>{try{const e=(await re(n)).size,r=await Q(n,"utf-8"),o=Buffer.byteLength(r,"utf-8");if(o<=zo)return r;const s=(e=>{const t=e.split("\n"),n=[];let r=!1,o=!1,s=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),o=!0,s=(a.match(/{/g)||[]).length-(a.match(/}/g)||[]).length,0===s&&(c.endsWith(";")||c.endsWith(","))&&(o=!1)):o?(s+=(a.match(/{/g)||[]).length,s-=(a.match(/}/g)||[]).length,0===s&&c.includes("}")?(n.push(a),o=!1):s>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(s,"utf-8");return i<=zo?s:s.slice(0,zo)+`\n\n... [TRUNCATED: File "${t}" at ${n} was ${e} bytes (${o} 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}},qo=async({defaultContent:e,dirName:t,dirPath:n})=>{try{const e=await ne(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}},Jo=async({allowedEnvVars:e,mode:t,workspaceInfo:n,authHeader:r,customHeader:o,maxParallelWorkers:s})=>{const i=sr(),a=Yo(n.absolutePath);zr.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:s}},(l.client??zn).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 zr.warn("System prompt fetch failed: unauthorized (401)"),await _r(),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 zr.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){zr.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 _r(),new Error("Your session has expired or been revoked. Credentials have been cleared. Please run `stably login` to re-authenticate.");throw new Error("Failed to fetch system prompt. Please check your network connection and try again. If this persists, run `stably login` to re-authenticate.")}const u=function({customHeader:e,systemPrompt:t}){return e?`${t}\n\nWhen writing or updating the generated test file, prepend this exact header at the top of the file without modification:\n\`\`\`ts\n${e}\n\`\`\``:t}({systemPrompt:c.data.systemPrompt,customHeader:o});return zr.debug("System prompt received",{size:u.length,appendedCustomHeader:!!o,hasPrContext:!!c.data.prContext}),{systemPrompt:u,prContext:c.data.prContext}},Qo={chat:"chat",single:"create",fix:"fix",init:"init",verify:"verify"},Xo=".stably-playwright-wrapper.config.*",Zo=[".ts",".js",".mts",".mjs",".cts",".cjs"];function es(e){const t=o(e);if(v(t))for(const e of Zo){const n=i(t,`playwright.config${e}`);if(v(n))return n}}var ts=["tests","e2e","__tests__","test"];function ns(e){try{return v(e)&&w(e).isDirectory()}catch{return!1}}function rs(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(z.dim(`Using output directory: ${e} (from ${n})`))}var os,ss=["mcp__playwright-test__","mcp__auto-heal-report__","mcp__stably-agent-control__"],is=["planner_","generator_"],as={"mcp__stably-agent-control__restart_mcp_servers":"Restarting Browser Tools","mcp__session-control__restart_mcp_servers":"Restarting Browser Tools",Skill:"Invoking Skill"},cs=(e,t)=>{const n=t.find(t=>e.startsWith(t));return n?e.slice(n.length):e},ls=(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},us=e=>"mcp__auto-heal-report__capture-trace-proof"===e?"Verify Test Run":"mcp__auto-heal-report__generate-report"===e?"Generate Report":(e=>{const t=as[e];if(t)return t;const n=cs(e,ss);return cs(n,is).split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")})(e),ds=["test","bug","flake","ui_change","other"],ps={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."},fs=e=>ps[e],hs=/[^a-zA-Z0-9-_]/g,ms=e=>{const t=e.trim().replace(hs,"_");return t.length>0?t.slice(0,80):void 0},gs=e=>"string"==typeof e?ms(e):void 0,ys=Ae("/");try{os=ys("worker_threads").Worker}catch(e){}var bs=os?function(e,t,n,r,o){var s=!1,i=new os(e+";var __w=require('worker_threads');__w.parentPort.on('message',function(m){onmessage({data:m})}),postMessage=function(m,t){__w.parentPort.postMessage(m,t)},close=process.exit;self=global",{eval:!0}).on("error",function(e){return o(e,null)}).on("message",function(e){return o(null,e)}).on("exit",function(e){e&&!s&&o(new Error("exited with code "+e),null)});return i.postMessage(n,r),i.terminate=function(){return s=!0,os.prototype.terminate.call(i)},i}:function(e,t,n,r,o){setImmediate(function(){return o(new Error("async operations unsupported - update to Node 12+ (or Node 10-11 with the --experimental-worker CLI flag)"),null)});var s=function(){};return{terminate:s,postMessage:s}},vs=Uint8Array,ws=Uint16Array,_s=Int32Array,Is=new vs([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]),Es=new vs([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]),Ts=new vs([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ss=function(e,t){for(var n=new ws(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];var o=new _s(n[30]);for(r=1;r<30;++r)for(var s=n[r];s<n[r+1];++s)o[s]=s-n[r]<<5|r;return{b:n,r:o}},xs=Ss(Is,2),As=xs.b,Cs=xs.r;As[28]=258,Cs[258]=28;var Rs,Ps=Ss(Es,0),ks=Ps.b,Us=Ps.r,Ls=new ws(32768);for($s=0;$s<32768;++$s)Rs=(61680&(Rs=(52428&(Rs=(43690&$s)>>1|(21845&$s)<<1))>>2|(13107&Rs)<<2))>>4|(3855&Rs)<<4,Ls[$s]=((65280&Rs)>>8|(255&Rs)<<8)>>1;var Ds=function(e,t,n){for(var r=e.length,o=0,s=new ws(t);o<r;++o)e[o]&&++s[e[o]-1];var i,a=new ws(t);for(o=1;o<t;++o)a[o]=a[o-1]+s[o-1]<<1;if(n){i=new ws(1<<t);var c=15-t;for(o=0;o<r;++o)if(e[o])for(var l=o<<4|e[o],u=t-e[o],d=a[e[o]-1]++<<u,p=d|(1<<u)-1;d<=p;++d)i[Ls[d]>>c]=l}else for(i=new ws(r),o=0;o<r;++o)e[o]&&(i[o]=Ls[a[e[o]-1]++]>>15-e[o]);return i},Os=new vs(288);for($s=0;$s<144;++$s)Os[$s]=8;for($s=144;$s<256;++$s)Os[$s]=9;for($s=256;$s<280;++$s)Os[$s]=7;for($s=280;$s<288;++$s)Os[$s]=8;var $s,Ns=new vs(32);for($s=0;$s<32;++$s)Ns[$s]=5;var Bs=Ds(Os,9,0),js=Ds(Os,9,1),Ms=Ds(Ns,5,0),Hs=Ds(Ns,5,1),Fs=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},Gs=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(7&t)&n},Ws=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(7&t)},Ys=function(e){return(e+7)/8|0},Vs=function(e,t,n){return(null==t||t<0)&&(t=0),(null==n||n>e.length)&&(n=e.length),new vs(e.subarray(t,n))},zs=["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"],Ks=function(e,t,n){var r=new Error(t||zs[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,Ks),!n)throw r;return r},qs=function(e,t,n,r){var o=e.length,s=r?r.length:0;if(!o||t.f&&!t.l)return n||new vs(0);var i=!n,a=i||2!=t.i,c=t.i;i&&(n=new vs(3*o));var l=function(e){var t=n.length;if(e>t){var r=new vs(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,m=t.m,g=t.n,y=8*o;do{if(!f){u=Gs(e,d,1);var b=Gs(e,d+1,3);if(d+=3,!b){var v=e[(P=Ys(d)+4)-4]|e[P-3]<<8,w=P+v;if(w>o){c&&Ks(0);break}a&&l(p+v),n.set(e.subarray(P,w),p),t.b=p+=v,t.p=d=8*w,t.f=u;continue}if(1==b)f=js,h=Hs,m=9,g=5;else if(2==b){var _=Gs(e,d,31)+257,I=Gs(e,d+10,15)+4,E=_+Gs(e,d+5,31)+1;d+=14;for(var T=new vs(E),S=new vs(19),x=0;x<I;++x)S[Ts[x]]=Gs(e,d+3*x,7);d+=3*I;var A=Fs(S),C=(1<<A)-1,R=Ds(S,A,1);for(x=0;x<E;){var P,k=R[Gs(e,d,C)];if(d+=15&k,(P=k>>4)<16)T[x++]=P;else{var U=0,L=0;for(16==P?(L=3+Gs(e,d,3),d+=2,U=T[x-1]):17==P?(L=3+Gs(e,d,7),d+=3):18==P&&(L=11+Gs(e,d,127),d+=7);L--;)T[x++]=U}}var D=T.subarray(0,_),O=T.subarray(_);m=Fs(D),g=Fs(O),f=Ds(D,m,1),h=Ds(O,g,1)}else Ks(1);if(d>y){c&&Ks(0);break}}a&&l(p+131072);for(var $=(1<<m)-1,N=(1<<g)-1,B=d;;B=d){var j=(U=f[Ws(e,d)&$])>>4;if((d+=15&U)>y){c&&Ks(0);break}if(U||Ks(2),j<256)n[p++]=j;else{if(256==j){B=d,f=null;break}var M=j-254;if(j>264){var H=Is[x=j-257];M=Gs(e,d,(1<<H)-1)+As[x],d+=H}var F=h[Ws(e,d)&N],G=F>>4;if(F||Ks(3),d+=15&F,O=ks[G],G>3&&(H=Es[G],O+=Ws(e,d)&(1<<H)-1,d+=H),d>y){c&&Ks(0);break}a&&l(p+131072);var W=p+M;if(p<O){var Y=s-O,V=Math.min(O,W);for(Y+p<0&&Ks(3);p<V;++p)n[p]=r[Y+p]}for(;p<W;++p)n[p]=n[p-O]}}t.l=f,t.p=B,t.b=p,t.f=u,f&&(u=1,t.m=m,t.d=h,t.n=g)}while(!u);return p!=n.length&&i?Vs(n,0,p):n.subarray(0,p)},Js=function(e,t,n){n<<=7&t;var r=t/8|0;e[r]|=n,e[r+1]|=n>>8},Qs=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},Xs=function(e,t){for(var n=[],r=0;r<e.length;++r)e[r]&&n.push({s:r,f:e[r]});var o=n.length,s=n.slice();if(!o)return{t:si,l:0};if(1==o){var i=new vs(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!=o-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=s[0].s;for(r=1;r<o;++r)s[r].s>p&&(p=s[r].s);var f=new ws(p+1),h=Zs(n[u-1],f,0);if(h>t){r=0;var m=0,g=h-t,y=1<<g;for(s.sort(function(e,t){return f[t.s]-f[e.s]||e.f-t.f});r<o;++r){var b=s[r].s;if(!(f[b]>t))break;m+=y-(1<<h-f[b]),f[b]=t}for(m>>=g;m>0;){var v=s[r].s;f[v]<t?m-=1<<t-f[v]++-1:++r}for(;r>=0&&m;--r){var w=s[r].s;f[w]==t&&(--f[w],++m)}h=t}return{t:new vs(f),l:h}},Zs=function(e,t,n){return-1==e.s?Math.max(Zs(e.l,t,n+1),Zs(e.r,t,n+1)):t[e.s]=n},ei=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new ws(++t),r=0,o=e[0],s=1,i=function(e){n[r++]=e},a=1;a<=t;++a)if(e[a]==o&&a!=t)++s;else{if(!o&&s>2){for(;s>138;s-=138)i(32754);s>2&&(i(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(i(o),--s;s>6;s-=6)i(8304);s>2&&(i(s-3<<5|8208),s=0)}for(;s--;)i(o);s=1,o=e[a]}return{c:n.subarray(0,r),n:t}},ti=function(e,t){for(var n=0,r=0;r<t.length;++r)n+=e[r]*t[r];return n},ni=function(e,t,n){var r=n.length,o=Ys(t+2);e[o]=255&r,e[o+1]=r>>8,e[o+2]=255^e[o],e[o+3]=255^e[o+1];for(var s=0;s<r;++s)e[o+s+4]=n[s];return 8*(o+4+r)},ri=function(e,t,n,r,o,s,i,a,c,l,u){Js(t,u++,n),++o[256];for(var d=Xs(o,15),p=d.t,f=d.l,h=Xs(s,15),m=h.t,g=h.l,y=ei(p),b=y.c,v=y.n,w=ei(m),_=w.c,I=w.n,E=new ws(19),T=0;T<b.length;++T)++E[31&b[T]];for(T=0;T<_.length;++T)++E[31&_[T]];for(var S=Xs(E,7),x=S.t,A=S.l,C=19;C>4&&!x[Ts[C-1]];--C);var R,P,k,U,L=l+5<<3,D=ti(o,Os)+ti(s,Ns)+i,O=ti(o,p)+ti(s,m)+i+14+3*C+ti(E,x)+2*E[16]+3*E[17]+7*E[18];if(c>=0&&L<=D&&L<=O)return ni(t,u,e.subarray(c,c+l));if(Js(t,u,1+(O<D)),u+=2,O<D){R=Ds(p,f,0),P=p,k=Ds(m,g,0),U=m;var $=Ds(x,A,0);for(Js(t,u,v-257),Js(t,u+5,I-1),Js(t,u+10,C-4),u+=14,T=0;T<C;++T)Js(t,u+3*T,x[Ts[T]]);u+=3*C;for(var N=[b,_],B=0;B<2;++B){var j=N[B];for(T=0;T<j.length;++T){var M=31&j[T];Js(t,u,$[M]),u+=x[M],M>15&&(Js(t,u,j[T]>>5&127),u+=j[T]>>12)}}}else R=Bs,P=Os,k=Ms,U=Ns;for(T=0;T<a;++T){var H=r[T];if(H>255){Qs(t,u,R[257+(M=H>>18&31)]),u+=P[M+257],M>7&&(Js(t,u,H>>23&31),u+=Is[M]);var F=31&H;Qs(t,u,k[F]),u+=U[F],F>3&&(Qs(t,u,H>>5&8191),u+=Es[F])}else Qs(t,u,R[H]),u+=P[H]}return Qs(t,u,R[256]),u+P[256]},oi=new _s([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),si=new vs(0),ii=function(e,t,n,r,o,s){var i=s.z||e.length,a=new vs(r+i+5*(1+Math.ceil(i/7e3))+o),c=a.subarray(r,a.length-o),l=s.l,u=7&(s.r||0);if(t){u&&(c[0]=s.r>>3);for(var d=oi[t-1],p=d>>13,f=8191&d,h=(1<<n)-1,m=s.p||new ws(32768),g=s.h||new ws(h+1),y=Math.ceil(n/3),b=2*y,v=function(t){return(e[t]^e[t+1]<<y^e[t+2]<<b)&h},w=new _s(25e3),_=new ws(288),I=new ws(32),E=0,T=0,S=s.i||0,x=0,A=s.w||0,C=0;S+2<i;++S){var R=v(S),P=32767&S,k=g[R];if(m[P]=k,g[R]=P,A<=S){var U=i-S;if((E>7e3||x>24576)&&(U>423||!l)){u=ri(e,c,0,w,_,I,T,x,C,S-C,u),x=E=T=0,C=S;for(var L=0;L<286;++L)_[L]=0;for(L=0;L<30;++L)I[L]=0}var D=2,O=0,$=f,N=P-k&32767;if(U>2&&R==v(S-N))for(var B=Math.min(p,U)-1,j=Math.min(32767,S),M=Math.min(258,U);N<=j&&--$&&P!=k;){if(e[S+D]==e[S+D-N]){for(var H=0;H<M&&e[S+H]==e[S+H-N];++H);if(H>D){if(D=H,O=N,H>B)break;var F=Math.min(N,H-2),G=0;for(L=0;L<F;++L){var W=S-N+L&32767,Y=W-m[W]&32767;Y>G&&(G=Y,k=W)}}}N+=(P=k)-(k=m[P])&32767}if(O){w[x++]=268435456|Cs[D]<<18|Us[O];var V=31&Cs[D],z=31&Us[O];T+=Is[V]+Es[z],++_[257+V],++I[z],A=S+D,++E}else w[x++]=e[S],++_[e[S]]}}for(S=Math.max(S,A);S<i;++S)w[x++]=e[S],++_[e[S]];u=ri(e,c,l,w,_,I,T,x,C,S-C,u),l||(s.r=7&u|c[u/8|0]<<3,u-=7,s.h=g,s.p=m,s.i=S,s.w=A)}else{for(S=s.w||0;S<i+l;S+=65535){var K=S+65535;K>=i&&(c[u/8|0]=l,K=i),u=ni(c,u+1,e.subarray(S,K))}s.i=i}return Vs(a,0,r+Ys(u)+o)},ai=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}(),ci=function(e,t,n,r,o){if(!o&&(o={l:1},t.dictionary)){var s=t.dictionary.subarray(-32768),i=new vs(s.length+e.length);i.set(s),i.set(e,s.length),e=i,o.w=s.length}return ii(e,null==t.level?6:t.level,null==t.mem?o.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(e.length)))):20:12+t.mem,n,r,o)},li=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},ui=function(e,t,n){for(var r=e(),o=e.toString(),s=o.slice(o.indexOf("[")+1,o.lastIndexOf("]")).replace(/\s+/g,"").split(","),i=0;i<r.length;++i){var a=r[i],c=s[i];if("function"==typeof a){t+=";"+c+"=";var l=a.toString();if(a.prototype)if(-1!=l.indexOf("[native code]")){var u=l.indexOf(" ",8)+1;t+=l.slice(u,l.indexOf("(",u))}else for(var d in t+=l,a.prototype)t+=";"+c+".prototype."+d+"="+a.prototype[d].toString();else t+=l}else n[c]=a}return t},di=[],pi=function(){return[vs,ws,_s,Is,Es,Ts,As,ks,js,Hs,Ls,zs,Ds,Fs,Gs,Ws,Ys,Vs,Ks,qs,Ii,hi,mi]},fi=function(){return[vs,ws,_s,Is,Es,Ts,Cs,Us,Bs,Os,Ms,Ns,Ls,oi,si,Ds,Js,Qs,Xs,Zs,ei,ti,ni,ri,Ys,Vs,ii,ci,_i,hi]},hi=function(e){return postMessage(e,[e.buffer])},mi=function(e){return e&&{out:e.size&&new vs(e.size),dictionary:e.dictionary}},gi=function(e,t,n,r,o,s){var i=function(e,t,n,r){if(!di[n]){for(var o="",s={},i=e.length-1,a=0;a<i;++a)o=ui(e[a],o,s);di[n]={c:ui(e[i],o,s),e:s}}var c=li({},di[n].e);return bs(di[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,o,function(e,t){i.terminate(),s(e,t)});return i.postMessage([e,t],t.consume?[e.buffer]:[]),function(){i.terminate()}},yi=function(e,t){return e[t]|e[t+1]<<8},bi=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},vi=function(e,t){return bi(e,t)+4294967296*bi(e,t+4)},wi=function(e,t,n){for(;n;++t)e[t]=n,n>>>=8};function _i(e,t){return ci(e,t||{},0,0)}function Ii(e,t){return qs(e,{i:2},t&&t.out,t&&t.dictionary)}var Ei=function(e,t,n,r){for(var o in e){var s=e[o],i=t+o,a=r;Array.isArray(s)&&(a=li(r,s[1]),s=s[0]),s instanceof vs?n[i]=[s,a]:(n[i+="/"]=[new vs(0),a],Ei(s,i,n,r))}},Ti="undefined"!=typeof TextEncoder&&new TextEncoder,Si="undefined"!=typeof TextDecoder&&new TextDecoder;try{Si.decode(si,{stream:!0})}catch(e){}function xi(e,t){if(Ti)return Ti.encode(e);for(var n=e.length,r=new vs(e.length+(e.length>>1)),o=0,s=function(e){r[o++]=e},i=0;i<n;++i){if(o+5>r.length){var a=new vs(o+8+(n-i<<1));a.set(r),r=a}var c=e.charCodeAt(i);c<128||t?s(c):c<2048?(s(192|c>>6),s(128|63&c)):c>55295&&c<57344?(s(240|(c=65536+(1047552&c)|1023&e.charCodeAt(++i))>>18),s(128|c>>12&63),s(128|c>>6&63),s(128|63&c)):(s(224|c>>12),s(128|c>>6&63),s(128|63&c))}return Vs(r,0,o)}var Ai=function(e){var t=0;if(e)for(var n in e){var r=e[n].length;r>65535&&Ks(9),t+=r+4}return t},Ci=function(e,t,n,r,o,s,i,a){var c=r.length,l=n.extra,u=a&&a.length,d=Ai(l);wi(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|(s<0&&8),e[t++]=o&&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)&&Ks(10),wi(e,t,f<<25|p.getMonth()+1<<21|p.getDate()<<16|p.getHours()<<11|p.getMinutes()<<5|p.getSeconds()>>1),t+=4,-1!=s&&(wi(e,t,n.crc),wi(e,t+4,s<0?-s-2:s),wi(e,t+8,n.size)),wi(e,t+12,c),wi(e,t+14,d),t+=16,null!=i&&(wi(e,t,u),wi(e,t+6,n.attrs),wi(e,t+10,i),t+=14),e.set(r,t),t+=c,d)for(var h in l){var m=l[h],g=m.length;wi(e,t,+h),wi(e,t+2,g),e.set(m,t+4),t+=4+g}return u&&(e.set(a,t),t+=u),t},Ri="function"==typeof queueMicrotask?queueMicrotask:"function"==typeof setTimeout?setTimeout:function(e){e()};function Pi(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 o=e[t],s=t+1<r?e[t+1]:0;if(("utf-16le"===n||"utf-16"===n)&&0===s&&o<32&&9!==o&&10!==o&&13!==o&&0!==o)return!1;if(("utf-16be"===n||"utf-16"===n)&&0===o&&s<32&&9!==s&&10!==s&&13!==s&&0!==s)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 ki=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 Ui(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 Li(e){switch(7&Ui(e)){case 0:return Ui(e),!0;case 1:return e.next(8),!0;case 2:const t=Ui(e);return e.next(t),!0;case 5:return e.next(4),!0}return!1}function Di(e,t,n){if(0===t)return!1;let r=0;const o=Math.min(t,515),s=Math.min(o,512);if(t>=3&&239===e[0]&&187===e[1]&&191===e[2])return!1;if(t>=4&&0===e[0]&&0===e[1]&&254===e[2]&&255===e[3])return!1;if(t>=4&&255===e[0]&&254===e[1]&&0===e[2]&&0===e[3])return!1;if(t>=4&&132===e[0]&&49===e[1]&&149===e[2]&&51===e[3])return!1;if(o>=5&&"%PDF-"===e.slice(0,5).toString())return!0;if(t>=2&&254===e[0]&&255===e[1])return!1;if(t>=2&&255===e[0]&&254===e[1])return!1;if(n?.encoding)return!Pi(e,t,n.encoding);const i=function(e,t){if(t<4)return null;const n=Math.min(t,512);let r=0,o=0;for(let t=0;t<n;t++)0===e[t]&&(t%2==0?r++:o++);const s=r+o;if(s>.3*n&&s<.7*n){if(o>3*r)return"utf-16le";if(r>3*o)return"utf-16be"}return null}(e,t);if(i)return!Pi(e,t,i);for(let t=0;t<s;t++){if(0===e[t])return!0;if((e[t]<7||e[t]>14)&&(e[t]<32||e[t]>127)){if(e[t]>=192&&e[t]<=223&&t+1<o){if(t++,e[t]>=128&&e[t]<=191)continue}else if(e[t]>=224&&e[t]<=239&&t+2<o){if(t++,e[t]>=128&&e[t]<=191&&e[t+1]>=128&&e[t+1]<=191){t++;continue}}else if(e[t]>=240&&e[t]<=247&&t+3<o&&(t++,e[t]>=128&&e[t]<=191&&e[t+1]>=128&&e[t+1]<=191&&e[t+2]>=128&&e[t+2]<=191)){t+=2;continue}if(r++,t>=32&&100*r/s>10)return!0}}return 100*r/s>10||!!(r>1&&function(e,t){const n=new ki(e,t);let r=0;for(;;){if(!Li(n)&&!n.hasError())return!1;if(n.hasError())break;r++}return r>0}(e,s))}var Oi=[/^\/$/,/^\*+$/,/^[0-9]+$/],$i=["/artifact/","https://","http://","*********"],Ni=new Set(["sha1","_sha1","pageref","downloadsPath","tracesDir","pageId"]);function Bi({sensitiveValues:e,str:t}){return e.reduce((e,t)=>e.replaceAll(t,"[REDACTED]"),t)}function ji({sensitiveValues:e,value:t}){return"string"==typeof t?Bi({sensitiveValues:e,str:t}):Array.isArray(t)?t.map(t=>ji({sensitiveValues:e,value:t})):function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(t)?Hi({obj:t,sensitiveValues:e}):t}function Mi(e){return!!Ni.has(e)||e.toLowerCase().endsWith("sha1")}function Hi({obj:e,sensitiveValues:t}){return Object.fromEntries(Object.entries(e).map(([e,n])=>[e,Mi(e)?n:ji({sensitiveValues:t,value:n})]))}function Fi({error:e,sensitiveValues:t}){return e?{...e,message:Bi({sensitiveValues:t,str:e.message})}:void 0}function Gi({content:e,sensitiveValues:t}){const n=new j,r=new M,o=Bi({sensitiveValues:t,str:n.decode(e)});return r.encode(o)}var Wi=B(function(e,t,n){n||(n=t,t={}),"function"!=typeof n&&Ks(7);var r=[],o=function(){for(var e=0;e<r.length;++e)r[e]()},s={},i=function(e,t){Ri(function(){n(e,t)})};Ri(function(){i=n});for(var a=e.length-22;101010256!=bi(e,a);--a)if(!a||e.length-a>65558)return i(Ks(13,0,1),null),o;var c=yi(e,a+8);if(c){var l=c,u=bi(e,a+16),d=4294967295==u||65535==l;if(d){var p=bi(e,a-12);(d=101075792==bi(e,p))&&(l=c=bi(e,p+32),u=bi(e,p+48))}for(var f=t&&t.filter,h=function(t){var n=function(e,t,n){var r=yi(e,t+28),o=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(Si)return Si.decode(e);var o=function(e){for(var t="",n=0;;){var r=e[n++],o=(r>127)+(r>223)+(r>239);if(n+o>e.length)return{s:t,r:Vs(e,n-1)};o?3==o?(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&o?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),s=o.s;return(n=o.r).length&&Ks(8),s}(e.subarray(t+46,t+46+r),!(2048&yi(e,t+8))),s=t+46+r,i=bi(e,t+20),a=n&&4294967295==i?function(e,t){for(;1!=yi(e,t);t+=4+yi(e,t+2));return[vi(e,t+12),vi(e,t+4),vi(e,t+20)]}(e,s):[i,bi(e,t+24),bi(e,t+42)],c=a[0],l=a[1],u=a[2];return[yi(e,t+10),c,l,o,s+yi(e,t+30)+yi(e,t+32),u]}(e,u,d),a=n[0],l=n[1],p=n[2],h=n[3],m=n[4],g=n[5],y=function(e,t){return t+30+yi(e,t+26)+yi(e,t+28)}(e,g);u=m;var b=function(e,t){e?(o(),i(e,null)):(t&&(s[h]=t),--c||i(null,s))};if(!f||f({name:h,size:l,originalSize:p,compression:a}))if(a)if(8==a){var v=e.subarray(y,y+l);if(p<524288||l>.8*p)try{b(null,Ii(v,{out:new vs(p)}))}catch(e){b(e,null)}else r.push(function(e,t,n){return n||(n=t,t={}),"function"!=typeof n&&Ks(7),gi(e,t,[pi],function(e){return hi(Ii(e.data[0],mi(e.data[1])))},1,n)}(v,{size:p},b))}else b(Ks(14,"unknown compression type "+a,1),null);else b(null,Vs(e,y,y+l));else b(null,null)},m=0;m<l;++m)h()}else i(null,{});return o}),Yi=B(function(e,t,n){n||(n=t,t={}),"function"!=typeof n&&Ks(7);var r={};Ei(e,"",r,t);var o=Object.keys(r),s=o.length,i=0,a=0,c=s,l=new Array(s),u=[],d=function(){for(var e=0;e<u.length;++e)u[e]()},p=function(e,t){Ri(function(){n(e,t)})};Ri(function(){p=n});var f=function(){var e=new vs(a+22),t=i,n=a-i;a=0;for(var r=0;r<c;++r){var o=l[r];try{var s=o.c.length;Ci(e,a,o,o.f,o.u,s);var u=30+o.f.length+Ai(o.extra),d=a+u;e.set(o.c,d),Ci(e,i,o,o.f,o.u,s,a,o.m),i+=16+u+(o.m?o.m.length:0),a=d+s}catch(e){return p(e,null)}}!function(e,t,n,r,o){wi(e,t,101010256),wi(e,t+8,n),wi(e,t+10,n),wi(e,t+12,r),wi(e,t+16,o)}(e,i,l.length,n,t),p(null,e)};s||f();for(var h=function(e){var t=o[e],n=r[t],c=n[0],h=n[1],m=function(){var e=-1;return{p:function(t){for(var n=e,r=0;r<t.length;++r)n=ai[255&n^t[r]]^n>>>8;e=n},d:function(){return~e}}}(),g=c.length;m.p(c);var y=xi(t),b=y.length,v=h.comment,w=v&&xi(v),_=w&&w.length,I=Ai(h.extra),E=0==h.level?0:8,T=function(n,r){if(n)d(),p(n,null);else{var o=r.length;l[e]=li(h,{size:g,crc:m.d(),c:r,f:y,m:w,u:b!=t.length||w&&v.length!=_,compression:E}),i+=30+b+I+o,a+=76+2*(b+I)+(_||0)+o,--s||f()}};if(b>65535&&T(Ks(11,0,1),null),E)if(g<16e4)try{T(null,_i(c,h))}catch(e){T(e,null)}else u.push(function(e,t,n){return n||(n=t,t={}),"function"!=typeof n&&Ks(7),gi(e,t,[fi],function(e){return hi(_i(e.data[0],e.data[1]))},0,n)}(c,h,T));else T(null,c)},m=0;m<c;++m)h(m);return d});async function Vi({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 j,r=new M,o=n.decode(e).split("\n").map(e=>{if(!e.trim())return e;try{const n=function({event:e,sensitiveValues:t}){return W(e).with({type:"console"},e=>({...e,args:e.args?.map(e=>({...e,preview:Bi({sensitiveValues:t,str:e.preview}),value:ji({sensitiveValues:t,value:e.value})})),text:Bi({sensitiveValues:t,str:e.text})})).with({type:"before"},e=>({...e,params:Hi({obj:e.params,sensitiveValues:t}),title:e.title?Bi({sensitiveValues:t,str:e.title}):void 0})).with({type:"after"},e=>({...e,error:Fi({error:e.error,sensitiveValues:t}),result:void 0!==e.result?ji({sensitiveValues:t,value:e.result}):void 0})).with({type:"action"},e=>({...e,error:Fi({error:e.error,sensitiveValues:t}),params:Hi({obj:e.params,sensitiveValues:t}),result:void 0!==e.result?ji({sensitiveValues:t,value:e.result}):void 0,title:e.title?Bi({sensitiveValues:t,str:e.title}):void 0})).with({type:"event"},e=>({...e,params:Hi({obj:e.params,sensitiveValues:t})})).with({type:"stdout"},{type:"stderr"},e=>({...e,text:void 0!==e.text?Bi({sensitiveValues:t,str:e.text}):void 0})).with({type:"error"},e=>({...e,message:Bi({sensitiveValues:t,str:e.message})})).with({type:"log"},e=>({...e,message:Bi({sensitiveValues:t,str:e.message})})).with({type:"context-options"},e=>({...e,options:Hi({obj:e.options,sensitiveValues:t}),title:e.title?Bi({sensitiveValues:t,str:e.title}):void 0})).with({type:"frame-snapshot"},e=>({...e,snapshot:Hi({obj:e.snapshot,sensitiveValues:t})})).with({type:"resource-snapshot"},e=>({...e,snapshot:Hi({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 Bi({sensitiveValues:t,str:e})}});return r.encode(o.join("\n"))}({content:e,sensitiveValues:n}):r.endsWith(".html")||r.endsWith(".dat")||r.endsWith(".json")?Gi({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!")}(w(e));const n=A(e,"r"),r=Buffer.alloc(515),o=C(n,r,0,515,0);return R(n),Di(r,o,t)}return Di(e,void 0!==t?.size?t.size:e.length,t)}(Buffer.from(e),{size:e.length})}(e)?e:Gi({content:e,sensitiveValues:t})}({content:e,sensitiveValues:n}):e}function zi(e=process.cwd()){let t=o(e);for(;;){const e=Ki(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=qi(t);let n=!1,o=t;for(;;){const e=i(o,"node_modules"),t=i(e,r);if(v(t)){n=!0;break}const a=s(o);if(a===o)break;o=a}return{inNodeModules:n,installed:!0,packageManager:e,packageName:r}}}const n=s(t);if(n===t)return{inNodeModules:!1,installed:!1,packageManager:void 0};t=n}}function Ki(e){const t=i(e,"package.json");let n;try{n=E(t,"utf-8")}catch{return}try{return JSON.parse(n)}catch{return}}function qi(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(v(i(n,r)))return e;const e=s(n);if(e===n)return;n=e}}function Ji(e){if("npm"===e||"pnpm"===e)return["npx","playwright"];if("yarn"===e)return["yarn","playwright"];throw new Error("Package manager not supported")}var Qi=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Xi=e=>(e instanceof Error?e.message:String(e)).slice(0,400),Zi=({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",Qi(t.testTitle)):t.testIdentifier&&n.push("--grep",`^${Qi(t.testIdentifier)}$`),n},ea=async e=>{const t=await ne(e,{withFileTypes:!0}),n=[];for(const o of t){const t=r.join(e,o.name);if(o.isDirectory())n.push(...await ea(t));else if(o.isFile()&&"trace.zip"===o.name){const e=await re(t);n.push({path:t,mtimeMs:e.mtimeMs})}}return n},ta=async e=>{try{const t=await ne(e,{withFileTypes:!0});for(const n of t){const t=r.join(e,n.name);n.isDirectory()?await ta(t):n.isFile()&&".last-run.json"===n.name&&await oe(t,{force:!0})}}catch{}},{zMarkdownAutoHealReport:na,zRepresentativeTest:ra}=function(e){const t=e.enum(ds),n=["Classification of the root cause:","",`- test: ${fs("test")}`,`- bug: ${fs("bug")}`,`- flake: ${fs("flake")}`,`- ui_change: ${fs("ui_change")}`,`- other: ${fs("other")}`].join("\n"),r=e.object({filePath:e.string().optional(),testIdentifier:e.string().optional(),testTitle:e.string().optional()}),o=e.object({status:e.enum(["captured","capture_failed","upload_failed"]),representativeTest:r,storage:e.object({bucket:e.string(),key:e.string()}).optional(),signedUrl:e.string().optional(),error:e.string().optional()}),s=o.extend({testCaseId:e.string().min(1).describe("Test case ID this trace proof corresponds to.")}),i=e.object({erroredUrl:e.string().optional(),issueType:t.describe(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(s).min(1).optional().describe("Per-test trace proofs for each testCaseId in this issue.")}),a=e.discriminatedUnion("result",[i.extend({fixApplied:e.string().describe("What fix was applied (brief, specific). Include file:line references (e.g., `src/tests/login.spec.ts:42`) showing where changes were made."),result:e.literal("fixed"),traceProof:o.optional()}),i.extend({followUpActions:e.string().optional().describe("Optional list of follow-up actions for any unfixed issues or missing data."),reasonNotFixed:e.string().describe("Why it could not be auto-fixed (brief). Include file:line references (e.g., `src/tests/login.spec.ts:42`) pointing to the problematic code."),result:e.literal("unfixed")})]),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.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.")});return{zAutoHealReport:a,zIssueCategory:t,zMarkdownAutoHealReport:l,zRepresentativeTest:r,zSuiteAutoHealReport:c,zStoredAutoHealReport:e.union([c,l]),zTraceProof:o,zTraceProofByTest:s}}(be),oa=({authHeader:e,diffTracker:t,orgId:n,runId:o,workingDir:s})=>H({name:"auto-heal-report",tools:[F("capture-trace-proof",["Capture and upload a Playwright trace proof for a test case.","","MANDATORY: Call for EVERY testCaseId in your issue, whether fixed or unfixed.","- Fixed: Trace proves the fix works","- Unfixed: Trace shows the failure state for auditability","","Pass testCaseId and call once per test case.","testCaseId is for per-test mapping/storage metadata; representativeTest selects the runnable test."].join("\n"),{issueId:be.string().min(1).describe("Issue identifier for deterministic output paths and storage key naming."),proofId:be.string().min(1).optional().describe("Optional id for deterministic proof naming and deduplication."),representativeTest:ra.optional().default({}),testCaseId:be.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=be.string().min(1).parse(t),u=null==i?void 0:be.string().min(1).parse(i),d=null==c?void 0:be.string().min(1).parse(c),p=await(async({authHeader:e,issueId:t,orgId:n,proofId:o,representativeTest:s,runId:i,testCaseId:a,workingDir:c})=>{if(!(e=>null!=e.filePath||null!=e.testTitle||null!=e.testIdentifier)(s))return{status:"capture_failed",representativeTest:s,error:"Representative test info is missing (need filePath, testTitle, or testIdentifier)."};const l=zi(c);if(!l.installed||!l.inNodeModules||!l.packageManager)return{status:"capture_failed",representativeTest:s,error:"Playwright is not installed in the current workspace."};const u=(e=>ms(e)??"issue")(t),d=(({proofId:e,testCaseId:t})=>gs(t)??gs(e))({testCaseId:a,proofId:o}),p=r.join(c,".stably","autoheal-proof",u,d??"issue"),[f,...h]=Ji(l.packageManager),g=[...h,...Zi({outputDir:p,representativeTest:s})];try{await oe(p,{force:!0,recursive:!0}),await X(p,{recursive:!0});const{code:r,stderr:l,timedOut:u}=await(async({args:e,command:t,cwd:n,env:r,timeoutMs:o})=>await new Promise((s,i)=>{const a=m(t,e,{cwd:n,env:r??process.env,stdio:["ignore","ignore","pipe"],shell:"win32"===process.platform});let c="",l=!1;a.stderr.on("data",e=>{c+=e.toString()});const u=setTimeout(()=>{l=!0,a.kill("SIGTERM")},o);a.on("error",e=>{clearTimeout(u),i(e)}),a.on("close",e=>{clearTimeout(u),s({code:e,stderr:c,timedOut:l})})}))({args:g,command:f,cwd:c,env:{...process.env,STABLY_INTERNAL_DISABLE_REPORTING:"1"},timeoutMs:3e5});if(u)return{status:"capture_failed",representativeTest:s,error:"Trace proof run timed out while executing Playwright verification."};const d=await(async e=>{const t=await ea(e);if(0!==t.length)return t.sort((e,t)=>t.mtimeMs-e.mtimeMs),t[0]?.path})(p);if(!d)return{status:"capture_failed",representativeTest:s,error:`No trace.zip was produced${0!==r?` (test exit code ${r??"unknown"})`:""}: ${l.trim().slice(0,280)}`.trim()};await ta(p);const{traceBucketPath:h,uploadUrl:y,sensitiveValues:b}=await(async({authHeader:e,issueId:t,proofId:n,testCaseId:r,contentType:o="application/zip",orgId:s,runId:i})=>{const a=await(c={auth:e,body:{contentType:o,issueId:t,proofId:n,testCaseId:r},client:sr(),headers:ro(s),path:{runId:i}},(c.client??zn).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=co.parse(a.data);return{traceBucketPath:l.traceBucketPath,expiresInSeconds:l.expiresInSeconds,key:l.key,uploadUrl:l.uploadUrl,sensitiveValues:l.sensitiveValues}})({authHeader:e,issueId:t,proofId:o,orgId:n,runId:i,testCaseId:a}),v=await async function({tracePath:e,sensitiveValues:t}){const n=[],r=I(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||Oi.some(t=>t.test(e))||$i.some(t=>e.includes(t))));if(0===n.length)return new Uint8Array(t);const r=[...n].sort((e,t)=>t.length-e.length),o=await Wi(new Uint8Array(t)),s=Object.entries(o),i=await Promise.all(s.map(async([e,t])=>[e,await Vi({content:t,filename:e,sensitiveValues:r})])),a=Object.fromEntries(i);return Yi(a)}({traceBuffer:new Uint8Array(Buffer.concat(n)),sensitiveValues:t})}({tracePath:d,sensitiveValues:b});try{await io({body:v,contentType:"application/zip",uploadUrl:y,errorContext:"trace"})}catch(e){return{status:"upload_failed",representativeTest:s,error:Xi(e)}}return{status:"captured",representativeTest:s,storage:h}}catch(e){return{status:"capture_failed",representativeTest:s,error:Xi(e)}}})({authHeader:e,issueId:l,orgId:n,proofId:u,representativeTest:ra.parse(a??{}),runId:o,testCaseId:d,workingDir:s}),f="string"==typeof d?{testCaseId:d,...p}:p;return{content:[{text:JSON.stringify(f),type:"text"}]}}),F("generate-report",["After attempting to fix all broken tests (skip only those truly infeasible), generate a flexible markdown auto-heal report.","","Use markdown headings, bullets, and code fences as needed. Include all important findings, fixes, unfixed items, and evidence.","Write for readability: start with a short summary, group related items under clear section headings, 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."].join("\n"),{markdown:na.shape.markdown},async({markdown:r})=>{const s=await t.computeDiff(),i=na.parse({format:"markdown",markdown:r});try{await(async({authHeader:e,orgId:t,report:n,runId:r})=>{const o=await(s={auth:e,body:{report:JSON.stringify(n)},client:sr(),headers:ro(t),path:{runId:r}},(s.client??zn).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-report",...s,headers:{"Content-Type":"application/json",...s.headers}}));var s;if(o.error)throw new Error(`Failed to upload auto-heal report (${o.response.status})`)})({authHeader:e,orgId:n,report:i,runId:o});const{diffBucketPath:t,uploadUrl:r}=await lo({authHeader:e,contentType:"text/plain",orgId:n,runId:o});await io({body:s,contentType:"text/plain",uploadUrl:r,errorContext:"diff"}),await uo({authHeader:e,diffBucketPath:t,orgId:n,runId:o})}catch(e){return console.error("[auto-heal-report] Failed to upload report or diff:",e),{content:[{text:`Error: Failed to upload auto-heal report or diff. ${e instanceof Error?e.message:String(e)} Please surface this to the user, and terminate the session.`,type:"text"}]}}return{content:[{text:"Auto-heal report generated. You may terminate this session now.",type:"text"}]}})],version:"0.0.1"}),sa=({onComplete:e,onRestartRequested:t})=>H(e?{name:"session-control",tools:[F("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:be.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}`)})]}:{name:"stably-agent-control",version:"1.0.0",tools:[F("restart_mcp_servers",'Restart the MCP servers to reinitialize browser tools after dependency changes.\n\nWHEN TO USE:\n- After installing or updating @playwright/test to version 1.56.x\n- When browser tools fail due to version mismatch errors\n- When the user has fixed a dependency issue and you need to reinitialize\n\nIMPORTANT: The restart happens at the END of your current turn.\n- Do NOT call any browser tools (setup_page, navigate, etc.) after this tool in the same turn - they will use the OLD servers\n- After calling this tool, END your turn naturally (no more tool calls)\n- The system will automatically continue in a new turn once the tools are restarted\n- Do NOT ask the user to reply again just to resume (only ask if you truly need additional input)\n\nEnd your turn briefly. You may say something like:\n- "Restarting browser tools now…"\n- "Tools are restarting to pick up the dependency changes…"',{},()=>(t(),Promise.resolve({content:[{type:"text",text:'MCP restart SCHEDULED for end of this turn.\n\nCRITICAL: END YOUR TURN NOW. Do not call any more tools.\nThe restart only happens AFTER your turn completes.\n\nAny tools called in this turn will use the OLD servers and fail.\n\nThe system will automatically continue with "[SYSTEM] MCP servers were restarted successfully" once ready.'}]})))]}),ia=be.object({commentUrl:be.string()}),aa=({prContext:e,authHeader:t,orgId:n,onReportPosted:r})=>H({name:"create-report",tools:[F("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:be.string().describe("A summary of the tests created. Include what features/flows are tested and any important notes."),filesCreated:be.array(be.string()).describe("List of test file paths that were created (relative to workspace root)")},async({summary:o,filesCreated:s})=>{const i=Array.isArray(s)?s:[];zr.info("[create-report] Posting report to GitHub PR",{prNumber:e.prNumber,filesCount:i.length});try{const s={summary:"string"==typeof o?o:String(o),filesCreated:i.map(String)},a=await async function({authHeader:e,orgId:t,prNumber:n,owner:r,repo:o,report:s}){const i=new URL("/internal/v1/cli/create-report",Qn).toString(),a={Authorization:e,"Content-Type":"application/json"};t&&(a["x-stably-org-id"]=t),zr.debug("Posting create report to GitHub",{prNumber:n,owner:r,repo:o,filesCount:s.filesCreated.length});const c=await fetch(i,{method:"POST",headers:a,body:JSON.stringify({prNumber:n,owner:r,repo:o,report:s}),signal:AbortSignal.timeout(3e4)});if(!c.ok){const e=await c.text().catch(()=>"");throw zr.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=ia.parse(await c.json());return zr.info("Create report posted successfully",{commentUrl:l.commentUrl}),l}({authHeader:t,orgId:n,prNumber:e.prNumber,owner:e.owner,repo:e.repo,report:s});return r?.(a),zr.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 zr.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}}})]}),ca=["QUEUED","RUNNING","PASSED","FAILED","TIMEDOUT","CANCELLED","INTERRUPTED"],la=["LOCAL","CI","WEB"],ua=["MANUAL","SCHEDULED","UI","API","GITHUB_ACTION","SUITE_RUN"],da=({authHeader:e,orgId:t,projectId:n})=>H({name:"run-history",tools:[F("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:be.string().optional().describe("Filter by branch name"),status:be.enum(ca).optional().describe("Filter by status: QUEUED|RUNNING|PASSED|FAILED|TIMEDOUT|CANCELLED|INTERRUPTED"),limit:be.number().min(1).max(100).optional().describe("Max results (1-100, default 20)"),source:be.enum(la).optional().describe("Filter by source: LOCAL|CI|WEB"),trigger:be.enum(ua).optional().describe("Filter by trigger: MANUAL|SCHEDULED|UI|API|GITHUB_ACTION|SUITE_RUN"),suite:be.string().optional().describe("Filter by suite name"),after:be.string().optional().describe("Pagination: return runs after this runId"),before:be.string().optional().describe("Pagination: return runs before this runId")},async({branch:r,status:o,limit:s,source:i,trigger:a,suite:c,after:l,before:u})=>{const d="string"==typeof r?r:void 0,p="string"==typeof o?o:void 0,f="number"==typeof s?s:void 0,h="string"==typeof i?i:void 0,m="string"==typeof a?a:void 0,g="string"==typeof c?c:void 0,y="string"==typeof l?l:void 0,b="string"==typeof u?u:void 0;zr.info("[run-history] list_runs called",{branch:d,status:p,limit:f});try{const r=await Kn({auth:e,client:sr(),headers:ro(t),query:{projectId:n,branchName:d,status:p,limit:f,source:h,trigger:m,suiteName:g,afterRunId:y,beforeRunId:b}});if(r.error||!r.data){const e=r.response?`API error: ${r.response.status}`:`API error: ${String(r.error)}`;return zr.error("[run-history] list_runs failed",{error:e}),{content:[{type:"text",text:`Error: ${e}`}],isError:!0}}return zr.info("[run-history] list_runs success",{runCount:r.data.runs?.length??0,hasMore:r.data.hasMore}),{content:[{type:"text",text:JSON.stringify(r.data,null,2)}]}}catch(e){const t=e instanceof Error?e.message:String(e);return zr.error("[run-history] list_runs exception",{error:t}),{content:[{type:"text",text:`Error: ${t}`}],isError:!0}}}),F("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:be.string().min(1).describe("The run ID to view (required)")},async({runId:n})=>{const r="string"==typeof n?n:String(n);zr.info("[run-history] view_run called",{runId:r});try{const n=await qn({auth:e,client:sr(),headers:ro(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 zr.error("[run-history] view_run failed",{error:e,runId:r}),{content:[{type:"text",text:`Error: ${e}`}],isError:!0}}return zr.info("[run-history] view_run success",{runId:r}),{content:[{type:"text",text:JSON.stringify(n.data,null,2)}]}}catch(e){const t=e instanceof Error?e.message:String(e);return zr.error("[run-history] view_run exception",{error:t,runId:r}),{content:[{type:"text",text:`Error: ${t}`}],isError:!0}}})]}),pa=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]"),fa=(e,t)=>({message:pa(e),status:t?.status,statusText:t?.statusText}),ha=new Set(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_CUSTOM_HEADERS","ANTHROPIC_DEFAULT_HAIKU_MODEL","ANTHROPIC_DEFAULT_OPUS_MODEL","ANTHROPIC_DEFAULT_SONNET_MODEL","ANTHROPIC_FOUNDRY_API_KEY","ANTHROPIC_MODEL","ANTHROPIC_SMALL_FAST_MODEL","ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION","AWS_BEARER_TOKEN_BEDROCK","BASH_DEFAULT_TIMEOUT_MS","BASH_MAX_OUTPUT_LENGTH","BASH_MAX_TIMEOUT_MS","CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR","CLAUDE_CODE_API_KEY_HELPER_TTL_MS","CLAUDE_CODE_CLIENT_CERT","CLAUDE_CODE_CLIENT_KEY_PASSPHRASE","CLAUDE_CODE_CLIENT_KEY","CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS","CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC","CLAUDE_CODE_DISABLE_TERMINAL_TITLE","CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL","CLAUDE_CODE_MAX_OUTPUT_TOKENS","CLAUDE_CODE_SHELL_PREFIX","CLAUDE_CODE_SKIP_BEDROCK_AUTH","CLAUDE_CODE_SKIP_FOUNDRY_AUTH","CLAUDE_CODE_SKIP_VERTEX_AUTH","CLAUDE_CODE_SUBAGENT_MODEL","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_FOUNDRY","CLAUDE_CODE_USE_VERTEX","CLAUDE_CONFIG_DIR","DISABLE_AUTOUPDATER","DISABLE_BUG_COMMAND","DISABLE_COST_WARNINGS","DISABLE_ERROR_REPORTING","DISABLE_NON_ESSENTIAL_MODEL_CALLS","DISABLE_PROMPT_CACHING","DISABLE_PROMPT_CACHING_HAIKU","DISABLE_PROMPT_CACHING_OPUS","DISABLE_PROMPT_CACHING_SONNET","DISABLE_TELEMETRY","HTTP_PROXY","HTTPS_PROXY","MAX_MCP_OUTPUT_TOKENS","MAX_THINKING_TOKENS","MCP_TIMEOUT","MCP_TOOL_TIMEOUT","NO_PROXY","SLASH_COMMAND_TOOL_CHAR_BUDGET","USE_BUILTIN_RIPGREP","VERTEX_REGION_CLAUDE_3_5_HAIKU","VERTEX_REGION_CLAUDE_3_7_SONNET","VERTEX_REGION_CLAUDE_4_0_OPUS","VERTEX_REGION_CLAUDE_4_0_SONNET","VERTEX_REGION_CLAUDE_4_1_OPUS"]),ma=async({authHeader:e,mode:t,maxTurnsOverride:n})=>{const r=sr();zr.debug("Requesting subagent definitions from API",{mode:t,maxTurnsOverride:n});const o=await(s={client:r,auth:e,body:{mode:t,maxTurnsOverride:n}},(s.client??zn).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/prompts/subagents",...s,headers:{"Content-Type":"application/json",...s.headers}}));var s;if(401===o.response.status)throw zr.warn("Subagent definitions fetch failed: unauthorized (401)"),await _r(),new Error("Your session has expired or been revoked. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(403===o.response.status)throw zr.debug("Subagent definitions fetch failed: forbidden (403)"),new Error("Your organization does not have an active subscription. Manage your subscription at https://app.stably.ai or contact your organization admin.");if(o.error)throw zr.warn("Subagent definitions fetch failed",{error:o.error}),new Error("Failed to fetch subagent definitions. Please check your network connection and try again. If this persists, run `stably login` to re-authenticate.");const{subagents:i}=o.data;return zr.debug("Subagent definitions received",{count:Object.keys(i).length}),i},ga=r.dirname(k(import.meta.url)),ya=r.join(".claude-plugin","plugin.json"),ba=[r.join("packages","agent-plugin","stably-plugin-cli"),r.join("agent-plugin","stably-plugin-cli")];function va(e){return v(r.join(e,ya))}var{zStablyYaml:wa}=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()}),o=e.object({setupScript:e.string().optional()});return{zStablyYaml:e.object({schedules:e.record(e.string(),t).optional(),agent:r.optional(),cloud:o.optional()}),zAgentConfig:r,zAgentFixConfig:n,zScheduleEntry:t,zCloudConfig:o}}(fe),_a=async(e,t)=>{try{const n=await pr(e,t);if(!n)return void zr.debug(`No ${t} found`);const r=await Q(n,"utf-8");if(!r.trim())return;return r.length>1e4?(zr.warn(`${t} exceeds max length (${r.length} > 10000), truncating`,{path:n}),{content:r.slice(0,1e4),path:n}):(zr.debug(`Loaded ${t} rules`,{path:n,contentLength:r.length}),{content:r,path:n})}catch(e){return void zr.warn(`Failed to read ${t}`,{error:e})}},Ia=fe.object({verdict:fe.enum(["PASS","FAIL","INCONCLUSIVE"]),steps:fe.array(fe.string()).min(1),reason:fe.string().nullable(),evidence:fe.array(fe.string())}).superRefine((e,t)=>{"PASS"===e.verdict||e.reason&&0!==e.reason.trim().length||t.addIssue({code:fe.ZodIssueCode.custom,path:["reason"],message:"reason is required for FAIL and INCONCLUSIVE verdicts"})}),Ea=/\bmcp__playwright-mcp__[a-z0-9_]+\b/gi,Ta=/\.playwright-mcp(?:\/[^\s"'`)\]]*)?/gi,Sa=/\bplaywright[\s_-]?mcp\b/gi;function xa(e){return e.replace(Ea,"browser_tool").replace(Ta,"verification-artifact").replace(Sa,"browser automation")}function Aa(e){return{...e,steps:e.steps.map(e=>xa(e)),reason:e.reason?xa(e.reason):null,evidence:e.evidence.map(e=>xa(e))}}function Ca(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=Ia.parse(t)}catch{}return n}var Ra=["Bash","Read","Write","Edit","Glob","Grep","Task","Skill"],Pa=["Task","mcp__playwright-test","Skill"],ka=["Bash","Read","Write","Edit","Glob","Grep","mcp__session-control"],Ua=e=>{if("EPIPE"!==e.code)throw e},La="__main__",Da=[3e3,5173,4173,8080,4200,8e3],Oa=/\b(TEST_EMAIL|TEST_PASSWORD|auth|authentication|credentials|login|log in|sign in)\b/i,$a=/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/i,Na=/playwright[\s_-]?mcp/i,Ba=e=>"mcp__auto-heal-report__generate-report"===e;async function ja(e,t){return!!e&&(!!e.hasQueuedMessages()||new Promise(n=>{const r=setTimeout(()=>{clearInterval(o),n(!1)},t),o=setInterval(()=>{e.hasQueuedMessages()&&(clearTimeout(r),clearInterval(o),n(!0))},200)}))}async function Ma(e){return new Promise(t=>{const n=new Y.Socket;let r=!1;const o=e=>{r||(r=!0,n.destroy(),t(e))};n.setTimeout(700),n.once("connect",()=>o(!0)),n.once("timeout",()=>o(!1)),n.once("error",()=>o(!1)),n.connect(e,"127.0.0.1")})}var Ha=async(e,t,n)=>{const r=n?"[Y/n]":"[y/N]",o=(await e.question(`${z.cyan("?")} ${t} ${z.gray(r)} `)).trim().toLowerCase();return o?"y"===o||"yes"===o:n},Fa=async e=>{if("single"===e.mode){const t=Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt;zr.initSession(t||"create-from-diff")}else if("verify"===e.mode){const t=Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt;zr.initSession(t||"verify")}else"fix"===e.mode&&zr.initSession(`fix-${e.runId}`);zr.info("Agent session starting",{mode:e.mode}),process.stdout.on("error",Ua),process.stderr.on("error",Ua);const a=e=>{if("EPIPE"!==e.code)throw e};process.on("uncaughtException",a),zr.debug("Checking authentication");const c=await Qr({autoLogin:"chat"===e.mode||"init"===e.mode}),l=Zr(c);zr.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"),m=p&&b.existsSync(f)&&b.statSync(f).isFile(),g=m?t(b.readFileSync(f,"utf8")):{};zr.debug("Environment file",{path:f,exists:m,variableCount:Object.keys(g).length});const w="chat"!==e.mode&&"init"!==e.mode,_="chat"===e.mode,I="chat"===e.mode||"init"===e.mode,E="single"===e.mode,T="verify"===e.mode,S=E||T;let x,A=new Wo;"init"===e.mode&&(x=e.initPreferences??await async function(){if(!process.stdin.isTTY||!process.stdout.isTTY)return{googleAuth:!0,emailPackage:!1};const e=V({input:process.stdin,output:process.stdout});try{return{googleAuth:await Ha(e,"Include Google Auth test helper guidance? (recommended)",!0),emailPackage:await Ha(e,"Install @stablyai/email for inbox testing?",!1)}}finally{e.close()}}());const C="chat"===e.mode?e.getHelpText:void 0,R="verify"===e.mode?(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt).trim():"";let P="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}},o=t.match(/https?:\/\/[^\s"'`<>]+/i);if(o)return r(o[0]);const s=t.match(/(?<!@)\b(?:localhost|(?:\d{1,3}\.){3}\d{1,3}|(?:[a-z0-9-]+\.)+[a-z]{2,63})(?::\d{2,5})?(?:\/[^\s"'`<>]*)?/i);if(!s)return;const i=n(s[0]),a=i.split("/")[0]??i,c=a.split(":")[0]?.toLowerCase()??"",l=c.includes(".")?c.split(".").at(-1)??"":"";return new Set(["ts","tsx","js","jsx","md","json","yaml","yml","txt","css"]).has(l)?void 0:r(`${"localhost"===c||"127.0.0.1"===c?"http":"https"}://${i}`)}(e.prompt):void 0;if("verify"===e.mode&&!e.url&&P&&zr.info("[verify] Using URL extracted from prompt",{url:P}),"verify"!==e.mode||P||(P=await async function(){for(const e of Da)if(await Ma(e))return`http://localhost:${e}`}(),P?zr.info("[verify] Detected local application URL",{url:P}):zr.info("[verify] No common localhost dev server detected")),"verify"===e.mode&&!1!==e.interactive){const e=await async function({envFilePath:e,envFromFile:t,initialUrl:n,verifyPromptText:o,workingDir:s}){if(!process.stdin.isTTY||!process.stdout.isTTY)return{resolvedUrl:n};const i=r.join(s,"STABLY.md"),a=b.existsSync(i),c=a?await b.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&&Oa.test(e))(r))({envEmail:process.env.TEST_EMAIL??t.TEST_EMAIL,envPassword:process.env.TEST_PASSWORD??t.TEST_PASSWORD,promptIncludesEmail:$a.test(o),stablyMdContent:c}),p=!a;if(!u&&!d&&!p)return{resolvedUrl:l};const f=V({input:process.stdin,output:process.stdout}),h=async(n,r)=>{const o=b.existsSync(e)?await b.promises.readFile(e,"utf8"):"",s=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=s.test(o)?o.replace(s,a):`${o}${o&&!o.endsWith("\n")?"\n":""}${a}\n`;await b.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 Ha(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 Ha(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 b.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 b.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 b.promises.writeFile(i,n,"utf8")}}return{resolvedUrl:l}}finally{f.close()}}({envFilePath:f,envFromFile:g,initialUrl:P,verifyPromptText:R,workingDir:d});P=e.resolvedUrl?.trim()||P}"verify"!==e.mode||P||zr.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 k={log:[],promptDisplay:W(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 U,L,D,O,$=w,N=!1,B=!1,j=0,M=0,H=!1;const F=[];let Y,K,J=[],X=!1,Z=!1,ee=0;const te=new Map,ne=[],re=e=>{ne.push(e)},oe=new Map;let se=null,ie=!1,ae=!1;const ce=Date.now();let le,ue="fix"===e.mode?{suiteId:e.runId,phase:"initializing",totalTests:null,fixedTests:0,failedTests:0,currentTestDescription:null,lastTestDescription:null,startedAt:ce,endedAt:null,isError:!1,updatedAt:ce,recentActivity:[],workers:[{id:La,testDescription:"Orchestrator",workerType:"main",status:"running",summary:null,startedAt:ce,endedAt:null,activity:[]}]}:null;const de=new Set,pe=(e,t)=>{if(!ue)return;const n=ue.workers.map(n=>{if(n.id!==e)return n;const r=[...n.activity,{...t,timestamp:Date.now()}].slice(-15);return{...n,activity:r}});me({workers:n})},fe=e=>{if(!ue)return;const t=[...ue.recentActivity,{...e,timestamp:Date.now()}].slice(-10);me({recentActivity:t})},he=e=>(ue?.workers??[]).map(t=>t.id===La?{...t,status:e?"failed":"succeeded",endedAt:t.endedAt??Date.now()}:"running"===t.status?{...t,status:"failed",endedAt:Date.now()}:t),me=e=>{ue&&!le?.isClosed&&(ue={...ue,...e,updatedAt:Date.now()},le?.sendProgress(ue))},ge=async t=>{if("fix"===e.mode){if("STARTED"===t){if(ie)return;ie=!0}else{if(ae)return;ae=!0}try{await(async({authHeader:e,orgId:t,runId:n,status:r})=>{const o=await(s={auth:e,body:{status:r},client:sr(),headers:ro(t),path:{runId:n}},(s.client??zn).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-status",...s,headers:{"Content-Type":"application/json",...s.headers}}));var s;if(o.error)throw new Error(`Failed to update autoheal status (${o.response.status})`)})({authHeader:l,orgId:u,runId:e.runId,status:t})}catch{}}},ye=Date.now();let be,ve=null;const Ae=e=>{ve&&!be?.isClosed&&(ve={...ve,...e,updatedAt:Date.now()},be?.sendProgress(ve))},Re=e=>{if(!ve)return;const t=[...ve.recentActivity,{...e,timestamp:Date.now()}].slice(-10);Ae({recentActivity:t})};let Pe;const ke=(e.mode,!0);zr.info("[session] Checking session creation",{mode:e.mode,shouldCreateSession:ke});try{zr.info("[session] Creating progress session",{mode:e.mode,projectId:Xr(c)});const t=await async function({agentMode:e,authHeader:t,orgId:n,projectId:r,runId:o,fetchImpl:s=fetch,apiUrl:i=Qn}){const a=Qo[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 s(c,{method:"POST",headers:l,body:JSON.stringify({mode:a,projectId:r,agentId:q.randomUUID(),..."fix"===a&&o?{playwrightSuiteRunId:o}:{}}),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:Xr(c),..."fix"===e.mode?{runId:e.runId}:{}}),{sessionId:n,sessionMode:r}=t;if(Pe=n,S){const t="single"===e.mode||"verify"===e.mode?Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt:null,r=Yo(d);ve={sessionId:n,phase:"initializing",startedAt:ye,endedAt:null,isError:!1,updatedAt:ye,currentActivity:null,filesCreated:[],recentActivity:[],prompt:t||null,environment:{gitBranch:r?.branch??null,workingDirectory:d,nodeVersion:process.version,cliVersion:Jn}},be=new fo({authHeader:l,orgId:u,sessionId:n,onUserMessage:e=>{A&&(zr.info("[ws] Injecting web UI message into agent",{contentLength:e.length}),Re({type:"user_message",summary:e}),Me({text:`[Web] ${e}`}),A.pushText(`[Message from web UI user]: ${e}`),$||($=!0,Ke({status:"running"})))}}),be.start(),Ae({phase:"initializing"})}zr.info(`[${r}] Progress session created`,{sessionId:n})}catch(e){const t=e instanceof Error?e.message:String(e);zr.warn(`[progress] Session creation failed (non-fatal): ${t}`)}const Ue={current:e=>{}},Le={current:async()=>{}};let De;const{addSubagentActivity:Oe,addSubagentStart:$e,addTool:Ne,addToolResult:Be,appendText:je,appendUserMessage:Me,cleanup:He,setExiting:Fe,setRunningLabel:Ge,setStatus:We,setSubagentStatus:Ye,updateFixProgress:Ve}=await(async(e,t)=>{const{Box:n,Static:r,Text:o,render:s,useInput:i}=await import("ink"),a=!!process.stdin.isTTY,c="vscode"!==process.env.TERM_PROGRAM,l=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],u=()=>Se(o,{inverse:!0,children:" "}),d=(({Box:e,Text:t,useInput:n},r,o)=>function({onChoice:s,prompt:i}){const[a,c]=we(0),[l,u]=we(!1),[d,p]=we(""),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 s("deny_with_message",d||"User denied this action"):t.escape?(u(!1),void p("")):t.backspace||t.delete?void p(e=>e.slice(0,-1)):void(t.ctrl||t.meta||p(t=>`${t}${e}`));if(t.upArrow)return void c(e=>e>0?e-1:f.length-1);if(t.downArrow)return void c(e=>e<f.length-1?e+1:0);if(t.return){const e=f[a];return"deny_with_message"===e.value?void u(!0):void s(e.value)}const 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);s(e.value)}},{isActive:o});const h=us(i.toolName),m=ls(i.toolName,i.input);return xe(e,{borderColor:"yellow",borderStyle:"round",flexDirection:"column",marginTop:1,paddingX:1,paddingY:0,children:[Se(t,{bold:!0,color:"yellow",children:"Permission Required"}),xe(e,{flexDirection:"column",marginTop:1,children:[Se(t,{color:"gray",dimColor:!0,children:h}),null!=m&&xe(t,{color:"gray",children:[" ",m]})]}),null!=i.decisionReason&&Se(e,{marginTop:1,children:xe(t,{color:"gray",children:["Reason: ",i.decisionReason]})}),xe(e,l?{flexDirection:"column",marginTop:1,children:[Se(t,{color:"gray",children:"Enter message for AI (press Enter to submit, Esc to cancel):"}),xe(t,{children:[Se(t,{color:"yellow",children:">"})," ",d,Se(r,{})]})]}:{flexDirection:"column",marginTop:1,children:[Se(t,{color:"gray",children:"Use ↑↓ arrows or number keys to select:"}),f.map((e,n)=>Se(t,{children:xe(t,{color:n===a?"cyan":void 0,children:[n===a?"❯":" "," ",n+1,". ",e.label]})},e.value))]})]})})({Box:n,Text:o,useInput:i},u,a),p=(({Cursor:e,inkComponents:{Box:t,Static:n,Text:r,useInput:o},isRawModeSupported:s,PermissionPrompt:i,Spinner:a})=>{const c="vscode"!==process.env.TERM_PROGRAM,l=e=>"tool"===e.kind?xe(r,{color:"gray",dimColor:!0,children:["• ",e.content]},e.id):"tool_result"===e.kind||"text"===e.kind?Se(r,{color:"gray",children:e.content},e.id):null,u=({progress:e})=>{const[n,o]=we(Date.now());Ie(()=>{if(!c)return;const e=setInterval(()=>o(Date.now()),1e3);return()=>clearInterval(e)},[]);const s=n-e.startedAt,i=Math.floor(s/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:"yellow"},fixing:{label:"Fixing tests",color:"cyan"},debugging:{label:"Debugging tests",color:"magenta"},validation:{label:"Validating fixes",color:"blue"},complete:{label:"Complete",color:"green"}}[e.phase],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 Se(t,{flexDirection:"column",children:xe(r,{children:[Se(r,{color:p,bold:!0,children:d}),Se(r,{color:"gray",children:h}),xe(r,{color:"gray",children:[" [",u,"]"]})]})})},d=({progress:e})=>{const n=e.endedAt??Date.now(),o=Math.floor((n-e.startedAt)/1e3),s=Math.floor(o/60),i=o%60,a=s>0?`${s}m ${i.toString().padStart(2,"0")}s`:`${i}s`,c=e.isError?"yellow":"green",l=e.isError?"Fix stopped":"Fix complete";return xe(t,{flexDirection:"column",children:[xe(r,{color:c,bold:!0,children:[l," in ",a]}),null!==e.totalTests&&xe(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:o}=e,s="complete"===o.status?"green":"error"===o.status?"red":"yellow";return xe(t,{flexDirection:"column",marginTop:1,children:[xe(r,{children:[Se(r,{color:s,bold:!0,children:"Agent"}),o.description?xe(r,{color:"gray",children:[" (",o.description,")"]}):null]}),o.activities.length>0&&Se(t,{flexDirection:"column",marginLeft:2,children:(()=>{if(!n)return o.activities.map(e=>l(e));let e=0;const t=[];for(let n=o.activities.length-1;n>=0;n--){const r=o.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)}return"tool"===e.kind?xe(r,{color:"gray",dimColor:!0,children:["• ",e.content]},e.id):"tool_result"===e.kind?Se(r,{color:"gray",children:e.content},e.id):"user"===e.kind?xe(r,{color:"cyan",children:["You: ",e.content]},e.id):Se(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},m=(e,t)=>{if(t<=0)return 0;const n=e.lastIndexOf("\n",t-1);return-1===n?0:n+1},g=(e,t)=>{const n=e.indexOf("\n",t);return-1===n?e.length:n},y=3;return function({onExit:c,onPermissionChoice:l,onSend:b,showSpinnerImmediately:v,state:w}){const[_,I]=we({value:"",cursor:0}),E=_.value,T=_.cursor,S=_e(!1),x=_e(void 0),[A,C]=we(!1),[R,P]=we(!1),k=_e(0),U=_e(!1),L=!!w.permissionPrompt,D=(({hasPermissionPrompt:e,inputValue:t,showExitMessage:n,termProgram:r})=>"vscode"===r&&(e||t.length>0||n))({hasPermissionPrompt:L,inputValue:E,showExitMessage:A,termProgram:process.env.TERM_PROGRAM}),O=w.log.at(-1),$="text"===O?.kind&&"running"===w.status,N=w.log.findIndex(e=>"subagent"===e.kind&&"running"===e.subagent?.status),B=s&&!R,j=D?0:-1!==N?N:$?w.log.length-1:w.log.length,M=B&&"running"===w.status?Math.min(j,k.current):j;Ie(()=>{w.log.length<k.current&&(k.current=0),M>k.current&&(k.current=M)},[w.log.length,M]);const H=w.log.slice(0,k.current),F=w.log.slice(k.current),G=B?H.filter(e=>"tool"!==e.kind&&"tool_result"!==e.kind):H,W=(()=>{if(!B)return F;let e=0;const t=[];for(let n=F.length-1;n>=0;n--){const r=F[n];"tool"===r.kind||"tool_result"===r.kind?("tool"===r.kind&&e++,e<=y&&t.unshift(r)):t.unshift(r)}return t})(),Y=Ee(async()=>{S.current?(x.current&&clearTimeout(x.current),await(c?.()),process.exit(0)):(S.current=!0,C(!0),x.current=setTimeout(()=>{S.current=!1,C(!1)},2e3))},[c]);o((e,t)=>{t.ctrl&&"c"===e&&Y().catch(()=>process.exit(1)),t.ctrl&&"o"===e&&P(e=>!e)},{isActive:s}),Ie(()=>{if(L||!b)return;process.stdout.isTTY&&process.stdout.write("[?2004h");const e=e=>{const t=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n");t&&I(e=>({value:e.value.slice(0,e.cursor)+t+e.value.slice(e.cursor),cursor:e.cursor+t.length}))},t=t=>{const n=t.toString();if(n.includes("[200~")){U.current=!0;const t=n.slice(n.indexOf("[200~")+6),r=t.includes("[201~"),o=r?t.slice(0,t.indexOf("[201~")):t;return r&&(U.current=!1),void e(o)}if(n.includes("[201~")){const t=n.slice(0,n.indexOf("[201~"));return e(t),void(U.current=!1)}U.current?e(n):""!==n&&"[1;5~"!==n?""!==n&&"[4;5~"!==n?""!==n&&"[1~"!==n&&"OH"!==n&&"[7~"!==n?""!==n&&"[4~"!==n&&"OF"!==n&&"[8~"!==n||I(e=>({...e,cursor:g(e.value,e.cursor)})):I(e=>({...e,cursor:m(e.value,e.cursor)})):I(e=>({...e,cursor:e.value.length})):I(e=>({...e,cursor:0}))};return process.stdin.on("data",t),()=>{process.stdin.off("data",t),process.stdout.isTTY&&process.stdout.write("[?2004l")}},[L,b]),o((e,t)=>{if(!t.ctrl||"c"!==e){if(t.return){if(U.current)return;const e=E.trim();return e&&b?.(e),void I({value:"",cursor:0})}t.ctrl&&"w"===e||t.ctrl&&t.backspace?I(e=>{const t=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?I(e=>({...e,cursor:f(e.value,e.cursor)})):t.ctrl&&t.rightArrow||t.meta&&"f"===e?I(e=>({...e,cursor:h(e.value,e.cursor)})):t.leftArrow?I(e=>({...e,cursor:Math.max(0,e.cursor-1)})):t.rightArrow?I(e=>({...e,cursor:Math.min(e.value.length,e.cursor+1)})):t.ctrl&&"a"===e?I(e=>({...e,cursor:0})):t.ctrl&&"e"===e?I(e=>({...e,cursor:e.value.length})):!e||t.ctrl||t.meta||t.escape||e.includes("")||/^\[./.test(e)||/^O[A-D]$/.test(e)||I(t=>({value:t.value.slice(0,t.cursor)+e+t.value.slice(t.cursor),cursor:t.cursor+e.length})):I(e=>e.cursor>0?{value:e.value.slice(0,e.cursor-1)+e.value.slice(e.cursor),cursor:e.cursor-1}:e)}},{isActive:s&&!!b&&!L});const V=Te(()=>"running"===w.status?Se(a,{label:w.runningLabel??"Working"}):"success"!==w.status?Se(r,{color:"red",children:"✖ Failed"}):void 0,[w.runningLabel,w.status]),z=!(v||!b||"running"!==w.status||0!==w.log.length||w.resultText||w.errorText),K="running"===w.status&&!z||w.log.length>0||w.resultText||w.errorText||"running"!==w.status;return xe(t,{flexDirection:"column",children:[D?xe(t,{flexDirection:"column",flexShrink:0,children:[Se(r,{color:"cyan",bold:!0,children:"Stably Agent"}),Se(t,{flexDirection:"column",marginTop:1,children:Se(r,{color:"gray",children:w.promptDisplay})})]}):Se(n,{items:["header"],children:()=>xe(t,{flexDirection:"column",flexShrink:0,children:[Se(r,{color:"cyan",bold:!0,children:"Stably Agent"}),Se(t,{flexDirection:"column",marginTop:1,children:Se(r,{color:"gray",children:w.promptDisplay})})]},"header")}),G.length>0&&Se(n,{items:G,children:e=>p(e,B)}),W.length>0&&Se(t,{flexDirection:"column",children:W.map(e=>p(e,B))}),B&&F.length>W.length&&xe(r,{color:"gray",dimColor:!0,children:["↕ ",F.length-W.length," tool calls hidden (Ctrl+O to expand)"]}),R&&s&&"running"===w.status&&Se(r,{color:"gray",dimColor:!0,children:"↕ Showing all tool calls (Ctrl+O to collapse)"}),"error"===w.status&&w.errorText&&Se(t,{marginTop:1,children:Se(r,{color:"red",children:w.errorText})}),"success"===w.status&&w.resultText&&Se(t,{marginTop:1,children:Se(r,{children:w.resultText})}),K&&Se(t,{flexDirection:"column",flexShrink:0,marginTop:1,children:"running"===w.status&&w.fixProgress?xe(t,{flexDirection:"column",children:[xe(t,{children:[Se(a,{}),Se(r,{children:" "}),Se(u,{progress:w.fixProgress})]}),("fixing"===w.fixProgress.phase||"debugging"===w.fixProgress.phase)&&w.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:o}=n,s=o.filter(e=>"tool"===e.kind).length,i=o.at(-1),c=o.filter(e=>"tool"===e.kind).at(-1),l=(()=>{if(!i)return null;if("tool"===i.kind)return null;if("text"===i.kind){const e=i.content.trim().split("\n").at(-1)?.trim();return e?e.length>80?`${e.slice(0,80)}…`:e:null}if("tool_result"===i.kind){const e=i.content.trim().split("\n")[0]?.trim();return e?e.length>80?`${e.slice(0,80)}…`:e:null}return null})();return xe(t,{flexDirection:"column",children:[xe(r,{children:[" ",Se(a,{}),xe(r,{color:"gray",children:[n.description||n.subagentType||"worker",s>0?` (${s} ${1===s?"cycle":"cycles"})`:""]})]}),c&&xe(r,{color:"gray",dimColor:!0,children:[" • ",c.content]}),l&&xe(r,{color:"gray",dimColor:!0,children:[" ",l]})]},e.id)})]}):"success"!==w.status&&"error"!==w.status||!w.fixProgress?V:Se(d,{progress:w.fixProgress})}),null!=w.permissionPrompt&&null!=l&&Se(i,{onChoice:l,prompt:w.permissionPrompt}),null!=b&&null==w.permissionPrompt&&!w.isExiting&&xe(t,{borderColor:"gray",borderStyle:"round",flexDirection:"column",flexShrink:0,marginTop:1,paddingX:1,paddingY:0,children:[Se(r,{color:"gray",children:"Type a message and press Enter. Press Ctrl+C to exit."}),xe(r,{children:[Se(r,{color:"yellow",children:">"})," ",E.slice(0,T),Se(e,{}),E.slice(T)]})]}),A&&xe(t,{marginTop:1,flexDirection:"column",children:[Se(r,{color:"yellow",children:"Press Ctrl+C again to exit"}),Or&&xe(r,{color:"gray",children:["Debug log: ",jr]})]})]})}})({Cursor:u,inkComponents:{Box:n,Static:r,Text:o,useInput:i},isRawModeSupported:a,PermissionPrompt:d,Spinner:({label:e})=>{const[t,n]=we(0);return Ie(()=>{if(!c)return;const e=setInterval(()=>n(e=>(e+1)%l.length),80);return()=>clearInterval(e)},[]),xe(o,{color:"yellow",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)=>{}},m=s(Se(p,{onExit:t?.onExit,onPermissionChoice:(e,t)=>h.current(e,t),onSend:t?.onSend,showSpinnerImmediately:t?.showSpinnerImmediately,state:f}),{exitOnCtrlC:!1}),g=()=>{f={...f},m.rerender(Se(p,{onExit:t?.onExit,onPermissionChoice:(e,t)=>h.current(e,t),onSend:t?.onSend,showSpinnerImmediately:t?.showSpinnerImmediately,state:f}))},y=({text:e})=>{e&&(f.log=[...f.log,{content:e,id:f.log.length,kind:"user"}],g())},b=new Map;return{addSubagentActivity:({toolUseId:e,kind:t,content:n})=>{const r=b.get(e);if(void 0===r)return void console.error("[addSubagentActivity] No entry index for toolUseId:",e);const o=f.log[r];if("subagent"===o?.kind&&o.subagent){if("text"===t){const e=o.subagent.activities.at(-1);"text"===e?.kind?e.content+=n:o.subagent.activities.push({id:o.subagent.activities.length,kind:"text",content:n.replace(/^\s*\n+/,"")})}else o.subagent.activities.push({id:o.subagent.activities.length,kind:t,content:n});f.log=[...f.log],g()}else console.error("[addSubagentActivity] Entry not found or not subagent:",{entryIndex:r,entryKind:o?.kind})},addSubagentStart:({toolUseId:e,subagentType:t,description:n})=>{const r=f.log.length;if(b.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});g()},addTool:({rawName:e,toolInput:t})=>{const n=us(e),r=ls(e,t),o=r?`${n} (${r})`:n;f.log=[...f.log,{content:o,id:f.log.length,kind:"tool"}],g()},addToolResult:({message:e})=>{f.log=[...f.log,{content:e,id:f.log.length,kind:"tool_result"}],g()},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"}],g()},appendUserMessage:y,cleanup:async()=>{const e=m.waitUntilExit();m.unmount(),await e},setExiting:()=>{f.isExiting=!0,g()},setRunningLabel:({label:e})=>{f.runningLabel=e,g()},setStatus:({error:e,result:t,status:n})=>{f.errorText=e,f.resultText=t,f.status=n,g()},setSubagentStatus:({toolUseId:e,status:t})=>{const n=b.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],g(),"complete"!==t&&"error"!==t||b.delete(e))},showPermissionPrompt:e=>new Promise(t=>{h.current=(n,r)=>{if(f.permissionPrompt=void 0,g(),"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";y({text:e}),t({behavior:"deny",message:e,interrupt:!1})}},f.permissionPrompt={...e,resolve:t},g()}),updateFixProgress:t?.isFixMode?e=>{f.fixProgress&&(f.fixProgress={...f.fixProgress,...e},g())}:void 0}})(k,"init"===e.mode?{onExit:()=>Le.current(),onSend:e=>Ue.current(e),showSpinnerImmediately:!0}:"chat"===e.mode?{onExit:()=>Le.current(),onSend:e=>Ue.current(e)}:"fix"===e.mode?{onExit:()=>Le.current(),isFixMode:!0}:{onExit:()=>Le.current()});let ze=k.status;const Ke=({error:e,result:t,status:n})=>{ze=n,We({error:e,result:t,status:n})};let qe;T&&(je({text:"Starting verification...\n"}),je(P?{text:`Target URL: ${P}\n`}:{text:"Target URL: auto-detect (agent may infer from project config)\n"}),Ge({label:"Calibrating verification flow..."})),Ue.current=e=>{const t=e.trim();if(_&&!zr.getLogFilePath()&&zr.initSession(t||"chat"),zr.debug("User message",{text:t}),"/help"===t){$&&A&&(N=!0,U?.interrupt?.(),A.allowNextTurn(),$=!1),"running"===ze&&Ke({status:"success"}),Me({text:e});const t=C?.();return void je({text:t??"Help is not available in this session."})}const n=D||B&&$;if(_&&(j+=1,O=void 0,n||(H=!1,Ge({label:void 0}))),A){if(n)return Ke({status:"running"}),Me({text:e}),void F.push(e);if(!B||$||D||(B=!1),$)return Ke({status:"running"}),Me({text:e}),A.pushText(e),void(M+=1);Ke({status:"running"}),Me({text:e}),re({role:"user",content:e,timestamp:(new Date).toISOString()}),A.pushText(e),$=!0}};let Je="",Qe="";const Xe=[],Ze=[],et=[];let tt;const nt=await(async e=>{try{const t=await pr(e,"stably.yaml");if(!t)return void zr.debug("No stably.yaml found");const n=await Q(t,"utf-8");if(!n.trim())return;const r=Ce(n),o=wa.parse(r.toJS()),s=o.agent?.fix?.maxTurnsPerIssue,i=o.agent?.fix?.maxParallelWorkers,a=!!o.agent?.fix?.rules;return zr.debug(`Loaded stably.yaml: maxTurnsPerIssue=${s??"default"}, maxParallelWorkers=${i??"default"}, hasRules=${a}`,{path:t,config:o.agent}),o}catch(e){return void zr.warn("Failed to parse stably.yaml",{error:e})}})(d),rt=nt?.agent?.fix?.skipAfterConsecutiveUnfixed,ot=await(async()=>{if("single"===e.mode){const n=await async function(e,t){const n=o(e);if(t){const e=o(n,t);return rs(e,"output-flag"),{path:e,source:"output-flag"}}const r=es(n);if(r){const e=await async function(e){try{const t=(await Q(e,"utf-8")).match(/testDir:\s*['"]([^'"]+)['"]/);return t?.[1]}catch{return}}(r);if(e){const t=o(s(r),e);if(ns(t))return rs(t,"playwright.config.ts"),{path:t,source:"playwright.config.ts"}}}for(const e of ts){const t=i(n,e);if(ns(t))return rs(t,"auto-detected"),{path:t,source:"auto-detected"}}return rs(n,"cwd-fallback"),{path:n,source:"cwd-fallback"}}(d,e.outputDir);return tt=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: ${tt}]`}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,P);if("fix"===e.mode)try{zr.info("[fix] Fetching autoheal context",{runId:e.runId,skipAfterConsecutiveUnfixed:rt});const t=Date.now(),{context:n,autohealReportUrl:r,skippedTests:o}=await(async({authHeader:e,orgId:t,runId:n,skipAfterConsecutiveUnfixed:r})=>{zr.debug("Fetching autoheal context",{runId:n,skipAfterConsecutiveUnfixed:r});const o=await(s={auth:e,client:sr(),headers:ro(t),path:{runId:n},query:null!=r?{skipAfterConsecutiveUnfixed:r}:{}},(s.client??zn).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-context",...s}));var s;if(404===o.response.status)throw zr.warn("Autoheal context not found",{runId:n,status:404}),new Error(`Run ID "${n}" was not found.`);if(401===o.response.status)throw zr.warn("Autoheal context fetch unauthorized",{runId:n,status:401}),new Error("Unauthorized: failed to fetch autoheal context (401).");if(422===o.response.status)throw zr.warn("Autoheal context fetch invalid request",{runId:n,status:422,error:o.error?.error}),new Error(o.error?.error??"Failed to fetch autoheal context (422).");if(!o.error){const e=oo.safeParse(o.data);if(e.success)return zr.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??[]};throw zr.warn("Autoheal context response invalid",{runId:n}),new Error("Autoheal context response missing or invalid context.")}throw zr.warn("Autoheal context fetch failed",{runId:n,error:o.error}),new Error("Failed to fetch autoheal context")})({authHeader:l,orgId:u,runId:e.runId,skipAfterConsecutiveUnfixed:rt});if(zr.info("[fix] Autoheal context fetched",{runId:e.runId,durationMs:Date.now()-t,contextLength:n.length,skippedTestCount:o.length}),qe=r,o.length>0){zr.info(`[fix] Skipping ${o.length} test(s) that failed to be fixed ${rt}+ consecutive times`);for(const e of o)zr.info(`[fix] Skipped: ${e.testIdentifier} — ${e.testTitle} (unfixed ${e.consecutiveUnfixedCount}x)`)}return n.includes("No failing tests to fix (all were skipped).")&&(zr.info("[fix] All failing tests were skipped — nothing to fix"),Ke({status:"success",result:`All failing tests skipped (unfixed ${rt}+ consecutive times). Nothing to fix.`}),await He(),process.exit(0)),le||(zr.info("[fix] Creating WebSocket progress reporter"),le=new po({authHeader:l,orgId:u,runId:e.runId,onUserMessage:e=>{if(zr.info("[ws] Injecting web UI message into fix agent",{contentLength:e.length}),pe(La,{type:"user_message",summary:e}),fe({type:"user_message",summary:e}),Me({text:`[Web] ${e}`}),!$)return A.pushText(`[Message from web UI user]: ${e}`),$=!0,void A.allowNextTurn();X||Date.now()-ee<2e3?A.pushText(`[Message from web UI user]: ${e}`):(J.push(e),Y&&clearTimeout(Y),Y=setTimeout(()=>{Y=void 0;const e=[...J];J=[],ee=Date.now(),sn(e)},500))}}),le.start(),me({phase:"initializing"})),ge("STARTED"),n}catch(e){const t=e instanceof Error?e.message:"Failed to fetch autoheal context.";zr.error("[fix] Failed to fetch autoheal context",{error:t}),Ke({error:t,status:"error"}),await He(),process.exit(1)}if("init"===e.mode){const e=x??{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""})(),st=await async function(e){const t=r.resolve(e),n=r.join(t,"tests"),o=r.join(n,"helpers"),s=r.join(n,"assets"),i=function(e){const t=r.resolve(e);if(v(t))for(const e of Vo){const n=r.join(t,`playwright.config${e}`);if(v(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([qo({defaultContent:"Unable to read directory",dirName:"working directory",dirPath:t}),qo({defaultContent:"Unable to read directory",dirName:"tests directory",dirPath:n}),qo({defaultContent:"Directory does not exist yet",dirName:"helpers directory",dirPath:o}),qo({defaultContent:"Directory does not exist yet",dirName:"assets directory",dirPath:s}),Ko({defaultContent:"File does not exist or could not be read",fileName:a,filePath:i}),Ko({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),it="fix"===e.mode?nt?.agent?.fix?.maxTurnsPerIssue:void 0,at="fix"===e.mode?nt?.agent?.fix?.maxParallelWorkers:void 0,ct="fix"===e.mode?nt?.agent?.fix?.rules:void 0,lt=nt?.agent?.fix?.maxBudgetUsd??50,ut="verify"===e.mode?e.maxBudgetUsd??5:void 0,dt="fix"===e.mode?lt:T?ut:void 0,pt="init"!==e.mode,ft="single"===e.mode?await(async e=>{const t=await _a(e,"STABLY-CREATE.md");return t?.content})(d):void 0,ht=await(e=>_a(e,"STABLY.md"))(d),mt=ht?.content;T&&(Ge({label:"Assembling verification context..."}),je({text:"Assembling workspace context...\n"})),zr.info("[fix] Fetching system prompt and subagent definitions",{mode:e.mode,maxTurnsOverride:it,maxBudgetUsd:dt,hasCustomRules:!!ct,hasCreateRules:!!ft,hasStablyMd:!!mt,stablyMdPath:ht?.path}),ht&&zr.info(`STABLY.md loaded (${ht.content.length} chars)`,{path:ht.path});const gt=await no(),yt=gt?Object.keys(gt.variables):[],bt=[...new Set([...Object.keys(g),...yt])],vt=Date.now(),[{systemPrompt:wt,prContext:_t},It]=await Promise.all([Jo({allowedEnvVars:bt,mode:e.mode,workspaceInfo:st,authHeader:l,customHeader:"single"===e.mode?e.customHeader:void 0,maxParallelWorkers:at}),pt?ma({authHeader:l,mode:e.mode,maxTurnsOverride:it}):Promise.resolve({})]);zr.info("[fix] System prompt and subagents fetched",{durationMs:Date.now()-vt,systemPromptSize:wt.length,subagentCount:Object.keys(It).length,maxTurnsOverride:it??"default",hasPrContext:!!_t});const Et={...g,...process.env},Tt={};for(const[e,t]of Object.entries(Et))ha.has(e)||void 0===t||(Tt[e]=t);const St=!0;zr.debug("AI proxy configuration",{useStablyAiProxy:St,wantsBypassProxy:!1,wantsUseOllama:!1}),zr.info("[fix] Acquiring AI proxy key",{useStablyAiProxy:St});const xt=Date.now(),At=await async function({auth:e,client:t,source:n,metadata:r,duration:o}){try{const i=await(s={auth:e,client:t,body:{source:n,metadata:r??{},duration:o}},(s.client??zn).post({security:[{scheme:"bearer",type:"http"}],url:"/v1/proxy/api-key",...s,headers:{"Content-Type":"application/json",...s.headers}})),a=i.response;if(i.error){const e="object"==typeof i.error&&"error"in i.error?i.error.error:"Unknown error";return{error:fa(e,a)}}return i.data?{key:i.data.key}:{error:fa("No data in response",a)}}catch(e){const t=e instanceof Error?e.message:"Unknown error";return{error:fa(t)}}var s}({auth:l,client:sr(),source:"cli"}),Ct=At?.key;if(zr.info("[fix] AI proxy key acquired",{durationMs:Date.now()-xt,success:!!Ct,hasError:!!At?.error}),!Ct){const e=At?.error?.message?`Unable to make AI calls: ${At.error.message}`:"Unable to make AI calls. Check if you are authenticated.";zr.warn("Failed to get proxy API key",{error:At?.error?.message}),Ke({error:e,status:"error"}),await He(),zr.flush(),zr.printLogFileInfo(),process.exit(1)}zr.debug("Proxy API key acquired",{success:!!Ct});const Rt=await to(),Pt=gt?.sensitiveValues.length?{STABLY_SENSITIVE_VALUES:Buffer.from(JSON.stringify(gt.sensitiveValues)).toString("base64")}:{},kt=Rt?Object.fromEntries(Object.entries(eo({...gt?.variables,...Pt,...Rt})).filter(e=>null!=e[1])):gt?Object.fromEntries(Object.entries(eo({...gt.variables,...Pt})).filter(e=>null!=e[1])):void 0,Ut="init"===e.mode,Lt="fix"===e.mode,Dt=Lt?Sn.createLocal({workingDir:d}):void 0;Dt&&await Dt.captureSnapshot();const Ot=()=>{Ut&&function({workingDir:e,options:t={}}){try{!function(e){const t=n.join(e,"package.json");if(!y.existsSync(t))return;const r=JSON.parse(y.readFileSync(t,"utf-8"));if({...r.dependencies,...r.devDependencies}.stably)return void zr.debug("stably package already present in dependencies");zr.info("stably package missing from devDependencies, installing...");const o=function(e){let t=e;for(let e=0;e<5;e++){if(y.existsSync(n.join(t,"pnpm-lock.yaml")))return"pnpm";if(y.existsSync(n.join(t,"yarn.lock")))return"yarn";if(y.existsSync(n.join(t,"bun.lockb"))||y.existsSync(n.join(t,"bun.lock")))return"bun";if(y.existsSync(n.join(t,"package-lock.json"))||y.existsSync(n.join(t,"npm-shrinkwrap.json")))return"npm";const e=n.dirname(t);if(e===t)break;t=e}return"npm"}(e),s="pnpm"===o?"pnpm add -D stably":"yarn"===o?"yarn add -D stably":"bun"===o?"bun add -d stably":"npm install -D stably";try{h(s,{cwd:e,stdio:"pipe",timeout:6e4}),zr.info("stably package installed successfully")}catch(e){zr.warn("Failed to install stably package",{error:String(e)})}}(e)}catch(e){zr.warn("Post-init: ensureStablyDependency failed",{error:String(e)})}try{!function(e,t){const r=["Use Stably CLI for Playwright test runs (better reporting, auto-fix); import from @stablyai/playwright-test for agent.act(), aiAssert, page.extract(), page.getLocatorsByAI()"];t.googleAuth&&r.push(", and use Google Auth methods"),t.emailPackage&&r.push(", and use @stablyai/email Inbox methods for email verification flows");const o=`${r.join("")}.`,s=function(e){const t=["CLAUDE.md","AGENTS.md","AGENT.md","agent.md"];for(const r of t){const t=n.join(e,r);if(!y.existsSync(t))continue;const o=y.readFileSync(t,"utf-8");return/Stably CLI/i.test(o)&&o.includes("@stablyai/playwright-test")?void zr.debug("Agent guidance already present",{file:r}):t}return n.join(e,"AGENTS.md")}(e);if(s){zr.info("Appending Stably guidance",{file:n.basename(s)});try{const e=y.existsSync(s)?y.readFileSync(s,"utf-8"):"",t=e.length>0&&!e.endsWith("\n")?"\n\n":e.length>0?"\n":"";y.writeFileSync(s,`${e}${t}${o}\n`,"utf-8"),zr.info("Agent guidance appended successfully")}catch(e){zr.warn("Failed to update agent guidance file",{error:String(e)})}}}(e,t)}catch(e){zr.warn("Post-init: ensureAgentGuidance failed",{error:String(e)})}}({workingDir:d,options:{googleAuth:x?.googleAuth,emailPackage:x?.emailPackage}})},$t=Ut?sa({onComplete:()=>{Ot(),Ke({status:"success"}),Fe(),A?.finish(),process.exit(0)}}):_?sa({onRestartRequested:()=>{_&&(B=!0,Ke({status:"running"}),Ge({label:"Restarting browser tools..."}),O={createdAtUserMessageSeq:j,attempts:0})}}):void 0,Nt=$t?_?{"stably-agent-control":$t}:{"session-control":$t}:{},Bt=E&&_t?["mcp__create-report"]:[],jt=Ut?ka:T?Ra:[...Ra,...Lt?["mcp__auto-heal-report"]:[],...Bt],Mt=Ut?ka:_?[...Pa,"mcp__stably-agent-control"]:T?Pa:[...Pa,...Bt],Ht=E&&_t?{"create-report":aa({prContext:_t,authHeader:l,orgId:u,onReportPosted:e=>{Ae({githubComment:{url:e.commentUrl,prNumber:_t.prNumber}})}})}:{},Ft=Ut?Nt:Lt&&Dt?{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:kt},"auto-heal-report":oa({authHeader:l,diffTracker:Dt,orgId:u,runId:e.runId,workingDir:d}),"run-history":da({authHeader:l,orgId:u,projectId:Xr(c)}),...Nt}:T?{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:kt},...Nt}:{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:kt},...Nt,...Ht},Gt="single"===e.mode,Wt=Ut?[]:[{hooks:[async e=>{const t=ko(e);if(!t)return{decision:"approve"};let n=!1;const r=t.map(e=>Ro(e)?e.text.length<=4e4?e:(n=!0,{...e,text:`${e.text.slice(0,4e4)}...[truncated to 40000 characters]`}):e);return n?{decision:"approve",hookSpecificOutput:{hookEventName:"PostToolUse",updatedMCPToolOutput:r}}:{decision:"approve"}}],matcher:"mcp__playwright-test__.*"},{matcher:"mcp__playwright-test__test_run",hooks:[Bo({onResult:e=>Be({message:e})})]},{matcher:"mcp__playwright-test__test_debug",hooks:[jo({onResult:e=>Be({message:e})})]},...Gt?[{matcher:"Write",hooks:[Ho({onFileCreated:e=>{if(Xe.includes(e)||Xe.push(e),ve){if(ve.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:o}=ve,s=(async()=>{try{const r=await b.promises.readFile(t,"utf8"),s=await(async({authHeader:e,content:t,contentType:n="text/plain",filename:r,filePath:o,orgId:s,sessionId:i})=>{try{const{bucketPath:a,uploadUrl:c}=await(async({authHeader:e,contentType:t="text/plain",filename:n,filePath:r,orgId:o,sessionId:s})=>{const i=await(a={auth:e,body:{filename:n,filePath:r,contentType:t},client:sr(),headers:ro(o),path:{sessionId:s}},(a.client??zn).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=ho.parse(i.data);return{bucketPath:c.bucketPath,expiresInSeconds:c.expiresInSeconds,key:c.key,uploadUrl:c.uploadUrl}})({authHeader:e,contentType:n,filename:r,filePath:o,orgId:s,sessionId:i});return await io({body:t,contentType:n,uploadUrl:c,errorContext:"file"}),await(async({authHeader:e,bucketPath:t,filename:n,filePath:r,orgId:o,sessionId:s})=>{const i=await(a={auth:e,body:{filename:n,filePath:r,bucketPath:t},client:sr(),headers:ro(o),path:{sessionId:s}},(a.client??zn).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:o,orgId:s,sessionId:i}),a}catch(e){return zr.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:o}),i={path:e,filename:n,bucketPath:s};Ze.push(i),Ae({filesCreated:[...Ze]})}catch(t){zr.warn("Failed to upload created file",{filePath:e,error:t instanceof Error?t.message:String(t)});const r={path:e,filename:n,bucketPath:null};Ze.push(r),Ae({filesCreated:[...Ze]})}})();et.push(s)}}})]}]:[]],Yt=Ut?[]:[{matcher:"mcp__playwright-test__.*",hooks:[async()=>B?{decision:"block",reason:'MCP restart is pending. This tool cannot be used until the restart completes. End your turn now - the restart only happens AFTER your turn ends. The system will send "[SYSTEM] MCP servers were restarted successfully" when ready.',systemMessage:"Tool call blocked: MCP restart pending"}:{decision:"approve"}]},...Lt?[{matcher:"Read",hooks:[wo({action:"reading",pathKey:"file_path"})]},{matcher:"Write",hooks:[wo({action:"writing",pathKey:"file_path"})]},{matcher:"Edit",hooks:[wo({action:"editing",pathKey:"file_path"})]},{matcher:"Grep",hooks:[wo({action:"searching",pathKey:"path"})]},{matcher:"Glob",hooks:[wo({action:"searching",pathKey:"path"})]},{matcher:"Bash",hooks:[Co({workspaceBoundary:d})]}]:[],{matcher:"mcp__playwright-test__browser_(type|navigate|evaluate|fill_form)",hooks:[No({envVars:{...g,...gt?.variables}})]}],Vt=Object.keys(It).length>0?It:void 0,zt={...Tt};zt.MCP_TOOL_TIMEOUT=String(6e5),Ct&&(zt.ANTHROPIC_API_KEY=Ct,zt.ANTHROPIC_BASE_URL=tr,zt.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS="1",zt.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC="1");const Kt=process.env.STABLY_AGENT_MODEL??"claude-opus-4-6",qt=Lt?"env"===c.type?c.auth.apiKey:c.auth.accessToken:void 0,Jt=Lt?Xr(c):void 0;Lt&&qt&&Jt&&(zt.STABLY_API_KEY=qt,zt.STABLY_PROJECT_ID=Jt);const Qt=ct?`\n\n## Custom Rules\n${ct}`:"",Xt=ft?`\n\n## Custom Test Generation Rules\n${ft}`:"",Zt=mt?`\n\n## Project Rules (STABLY.md)\n${mt}`:"",en=wt+Qt+Xt+Zt;zr.debug("[fix] Final system prompt assembled",{baseSize:wt.length,fixRulesSize:Qt.length,createRulesSize:Xt.length,stablyMdSize:Zt.length,finalSize:en.length});const tn=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 va(t)?t:void 0}();if(e)return e;const t=r.join(ga,"stably-plugin-cli");if(va(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}}(ga))for(const t of ba){const n=r.join(e,t);if(va(n))return n}}();if(e)return{type:"local",path:e}}(),nn=()=>(zr.info("[fix] Starting SDK query",{model:Kt,tools:jt,mcpServers:Object.keys(Ft),resumeSessionId:L??null,subagentsEnabled:!!Vt,subagentCount:Object.keys(It).length,useStablyAiProxy:St,aiProxyUrl:tr,anthropicBaseUrl:void 0,stablyPluginPath:tn?.path,stablyPluginExists:!!tn}),G({options:{executableArgs:["--max-old-space-size=4096"],tools:jt,allowedTools:Mt,...null!=dt?{maxBudgetUsd:dt}:{},betas:[],canUseTool:(e,t)=>(zr.debug("[fix] canUseTool called",{toolName:e}),Promise.resolve({behavior:"allow",updatedInput:t})),cwd:d,env:zt,hooks:{PostToolUse:Wt,PreToolUse:Yt},includePartialMessages:!0,agents:Vt,mcpServers:Ft,model:Kt,permissionMode:"default",plugins:tn?[tn]:void 0,systemPrompt:en,...L?{resume:L}:{}},prompt:A??ot})),rn=()=>{if(A&&0!==F.length){for(const e of F)A.pushText(e);F.length=0,$=!0,Ke({status:"running"})}},on=async()=>{_&&(D||(D=(async()=>{zr.info("Restarting MCP servers for chat mode"),Ke({status:"running"}),Ge({label:"Restarting browser tools..."});try{await(U?.interrupt?.())}catch(e){zr.warn("Failed to interrupt response during MCP restart",{error:e instanceof Error?e.message:String(e)})}await Go(),A?.finish(),A=new Wo,M=0,$=!1,N=!1,te.clear(),U=nn(),H=!0,Ge({label:"Restarting browser tools..."}),_&&A&&O&&(O.createdAtUserMessageSeq===j?O.attempts>=1||F.length>0?O=void 0:(O.attempts+=1,A.pushText(["[SYSTEM] MCP servers were restarted successfully.","Continue the task using existing conversation context.","Do not ask the user to resend their message unless new input is required."].join("\n")),O=void 0,$=!0,Ke({status:"running"})):O=void 0),rn()})().finally(()=>{D=void 0,rn()})),await D)},sn=async e=>{if(w&&$&&!X&&!K)K=(async()=>{zr.info("[fix] Interrupting for user message",{messageCount:e.length,phase:ue?.phase});try{await(U?.interrupt?.())}catch(e){zr.warn("[fix] Failed to interrupt response for user message",{error:e instanceof Error?e.message:String(e)})}await Go(),A?.finish(),A=new Wo,te.clear(),U=nn();const t=e.map(e=>`[Message from web UI user]: ${e}`).join("\n\n");A.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}`),Z=!0,$=!0})().finally(()=>{K=void 0}),await K;else for(const t of e)A?.pushText(`[Message from web UI user]: ${t}`)};if(Ct){T&&Ge({label:"Checking AI connectivity..."});const e=tr,t=`${e.replace(/\/$/,"")}/v1/messages`;zr.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":Ct,"anthropic-version":"2023-06-01","content-type":"application/json"},body:"{}"}),o=await e.text().catch(()=>""),s=Date.now()-n;zr.debug(`[fix] Pre-flight: ${e.status} in ${s}ms — ${o.slice(0,300)}`),401===e.status||403===e.status?(zr.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."):zr.info("[fix] Pre-flight: AI proxy key valid",{status:e.status,durationMs:s})}catch(t){zr.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{T&&"running"===ze&&Ge({label:void 0})}r&&(je({text:`[stably] ${r}\n`}),Ke({error:r,status:"error"}),await He(),zr.flush(),zr.printLogFileInfo(),process.exit(1))}zr.info("[fix] Creating initial agent query"),T&&(Ge({label:"Initializing verification session..."}),je({text:"Initializing verification session...\n"})),zr.flush(),U=nn(),zr.info("[fix] Agent query created, entering message loop"),"chat"!==e.mode&&(A.pushText(ot),ne.push({role:"user",content:ot,timestamp:(new Date).toISOString()}));const an=async t=>{De||(De=(async()=>{zr.info("[session] Interrupt requested",{source:t,mode:e.mode}),se="CANCELED",await ge("CANCELED"),me({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:he(!0)}),await(le?.closeAndWait()),await Promise.allSettled(et),Ae({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0}),await(be?.closeAndWait()),Y&&(clearTimeout(Y),Y=void 0),Fe(),await Go();try{await(U?.interrupt?.())}catch{}A?.finish(),ne.length>0&&Pe&&await go({authHeader:l,orgId:u,sessionId:Pe,projectId:Xr(c),history:ne}).catch(e=>{zr.warn("[exit] Failed to upload session history",{error:e instanceof Error?e.message:String(e)})}),He(),zr.flush()})()),await De};Le.current=async()=>{await an("ctrl-c")};let cn=()=>{};cn=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 an("signal"),process.exit(function(e){return"SIGINT"===e?130:143}(e))})()}});let ln=0,un=null,dn=!1;const pn=T?setTimeout(()=>{if(un||"running"!==ze)return;const e="This is taking longer than expected. Please try again.";je({text:`[stably] ${e}\n`}),Ke({error:e,status:"error"});try{U?.interrupt?.()}catch{}A?.finish(),He(),zr.flush(),zr.printLogFileInfo(),process.exit(1)},9e4):void 0;pn?.unref();const fn=setInterval(()=>{const e=Date.now()-ce;un?zr.info("[fix] Watchdog: message loop active",{messageCount:ln,elapsed:e}):(zr.info("[fix] Watchdog: waiting for first SDK message",{elapsed:e}),T&&!dn&&e>=15e3&&(je({text:"Still preparing verification. This can take a bit...\n"}),dn=!0)),zr.flush()},15e3);fn.unref();try{let t=!1;for(;;){if(!U){zr.info("[fix] No response object, exiting message loop");break}t=!1,zr.info("[fix] Entering for-await on SDK response");for await(const n of U){ln++,un||(un=Date.now(),pn&&clearTimeout(pn),T&&Ge({label:void 0}),zr.info("[fix] First SDK message received",{waitDurationMs:un-ce,messageType:n.type,messageSubtype:"subtype"in n?n.subtype:void 0}));const r="session_id"in n&&"string"==typeof n.session_id?n.session_id:void 0;if(r&&r!==L&&(L=r,zr.debug("Captured Claude session id",{sessionId:L})),"stream_event"===n.type){const{event:e}=n;(ln<=5||ln%200==0)&&zr.debug("[fix] Stream event",{msgNum:ln,eventType:e?.type});const t=e&&"object"==typeof e&&"parent_tool_use_id"in e&&"string"==typeof e.parent_tool_use_id?e.parent_tool_use_id:void 0;if("content_block_delta"===e?.type){const{delta:n}=e;if("text_delta"===n?.type&&n.text){if(_&&B&&!t)continue;H&&(H=!1,Ge({label:void 0}));const e=t&&te.has(t)?t:1===te.size?Array.from(te.keys())[0]:void 0;e?Oe({toolUseId:e,kind:"text",content:n.text}):T||je({text:n.text})}}"message_stop"===e?.type&&A&&(X=!1,A.allowNextTurn());continue}if("assistant"===n.type){const t="parent_tool_use_id"in n&&"string"==typeof n.parent_tool_use_id?n.parent_tool_use_id:void 0,{content:r}=n.message??{};if(Array.isArray(r)&&!t){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&&(Je=t,T&&(Qe=Qe?`${Qe}\n\n${t}`:t),zr.debug("Assistant message",{text:T?xa(t):t}),"fix"===e.mode&&(pe(La,{type:"ai_message",summary:t.slice(0,200)}),fe({type:"ai_message",summary:t.slice(0,200)})),S&&Re({type:"ai_message",summary:t.slice(0,200)}),re({role:"assistant",content:t,timestamp:(new Date).toISOString()}))}if(te.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):[];zr.debug("Assistant message with active subagents",{hasParentToolUseId:!!t,parentToolUseId:t,activeSubagentIds:Array.from(te.keys()),toolNames:e,fullMessageKeys:Object.keys(n),rawMessage:JSON.stringify(n).slice(0,500)})}if(Array.isArray(r))for(const n of r){if("tool_use"===n?.type){if("mcp__auto-heal-report__generate-report"===n.name&&(X=!0),"mcp__session-control__restart_mcp_servers"===n.name||"mcp__stably-agent-control__restart_mcp_servers"===n.name){Ne({rawName:n.name,toolInput:n.input});continue}if(n.name.startsWith("mcp__session-control__")||n.name.startsWith("mcp__stably-agent-control__"))continue;if(Ba(n.name))continue;if(T&&Na.test(n.name))continue;if(te.size>0&&zr.debug("Tool use detected with active subagents",{toolName:n.name,hasParentToolUseId:!!t,parentToolUseId:t,wouldRouteToSubagent:!!t&&te.has(t),activeSubagentIds:Array.from(te.keys())}),"Task"===n.name){const t=n.input,r=t&&"object"==typeof t?t:void 0,o=r&&"subagent_type"in r&&"string"==typeof r.subagent_type?r.subagent_type:"subagent",s=r&&"description"in r&&"string"==typeof r.description?r.description.trim():"";if(zr.info("[fix] Subagent started",{subagentType:o,description:s,toolUseId:n.id,activeSubagentCount:te.size+1}),te.set(n.id,{subagentType:o,description:s}),$e({toolUseId:n.id,subagentType:o,description:s}),"fix"===e.mode){if("triage"===o){Ve?.({phase:"triage"});const e={id:n.id,testDescription:"Triage",workerType:"triage",status:"running",summary:null,startedAt:Date.now(),endedAt:null,activity:[]};me({phase:"triage",workers:[...ue?.workers??[],e]})}else if("code-worker"===o){de.add(s||n.id);const e={id:n.id,testDescription:s||n.id,workerType:"code-worker",status:"running",summary:null,startedAt:Date.now(),endedAt:null,activity:[]};Ve?.({phase:"fixing",totalTests:de.size,currentTestDescription:s||null}),me({phase:"fixing",totalTests:de.size,currentTestDescription:s||null,lastTestDescription:s||ue?.lastTestDescription||null,workers:[...ue?.workers??[],e]})}else if("browser-worker"===o){de.add(s||n.id);const e={id:n.id,testDescription:s||n.id,workerType:"browser-worker",status:"running",summary:null,startedAt:Date.now(),endedAt:null,activity:[]};Ve?.({phase:"debugging",totalTests:de.size,currentTestDescription:s||null}),me({phase:"debugging",totalTests:de.size,currentTestDescription:s||null,lastTestDescription:s||ue?.lastTestDescription||null,workers:[...ue?.workers??[],e]})}else"validation"===o?(Ve?.({phase:"validation",currentTestDescription:null}),me({phase:"validation",currentTestDescription:null})):"context"===o&&me({currentTestDescription:s||null});fe({type:"tool_call",summary:`[${o}] ${s}`.trim()})}continue}if(t&&te.has(t)){const r=us(n.name),o=ls(n.name,n.input),s=o?`${r} (${o})`:r;if(zr.debug("Subagent tool called",{tool:n.name,parentToolUseId:t}),Oe({toolUseId:t,kind:"tool",content:s}),"fix"===e.mode){fe({type:"tool_call",summary:s});const e=te.get(t);"code-worker"!==e?.subagentType&&"browser-worker"!==e?.subagentType&&"triage"!==e?.subagentType||pe(t,{type:"tool_call",summary:s})}continue}if(t&&zr.debug("Tool with parent_tool_use_id but no matching subagent",{tool:n.name,parentToolUseId:t,activeSubagentIds:Array.from(te.keys())}),zr.debug("Tool called",{tool:n.name,input:n.input}),Ne({rawName:n.name,toolInput:n.input}),n.id&&oe.set(n.id,n.name),re({role:"tool",content:"",timestamp:(new Date).toISOString(),toolName:n.name,toolInput:n.input}),"fix"===e.mode){const e=us(n.name),t=ls(n.name,n.input),r=t?`${e} (${t})`:e;pe(La,{type:"tool_call",summary:r}),fe({type:"tool_call",summary:r})}if(E){const e=us(n.name),t=ls(n.name,n.input),r=t?`${e} (${t})`:e;"initializing"===ve?.phase?Ae({phase:"generating",currentActivity:r}):"mcp__playwright-test__test_run"===n.name&&"generating"===ve?.phase?Ae({phase:"testing",currentActivity:r}):Ae({currentActivity:r}),Re({type:"tool_call",summary:r})}if(T){const e=us(n.name),t=ls(n.name,n.input),r=xa(t?`${e} (${t})`:e);Ae("initializing"===ve?.phase?{phase:"verifying",currentActivity:r}:{currentActivity:r}),Re({type:"tool_call",summary:r})}}if("text"===n?.type){const r="string"==typeof n.text?n.text:"",o=t&&te.has(t)?t:1===te.size?Array.from(te.keys())[0]:void 0;if(o&&r&&(Oe({toolUseId:o,kind:"text",content:r}),"fix"===e.mode)){const e=te.get(o);"code-worker"!==e?.subagentType&&"browser-worker"!==e?.subagentType&&"triage"!==e?.subagentType||pe(o,{type:"ai_message",summary:r.slice(0,200)})}}}continue}if("user"===n.type){const t="message"in n&&n.message&&"object"==typeof n.message&&"content"in n.message?n.message.content:void 0,r="tool_use_result"in n&&n.tool_use_result&&"object"==typeof n.tool_use_result?n.tool_use_result:void 0;if(Array.isArray(t))for(const n of t)if(n&&"object"==typeof n&&"type"in n&&"tool_result"===n.type&&"tool_use_id"in n){const t="string"==typeof n.tool_use_id?n.tool_use_id:void 0,o="is_error"in n&&!0===n.is_error||"error"===r?.status;let s;const i=r?.content??("content"in n?n.content:void 0);"string"==typeof i?s=i:Array.isArray(i)&&(s=i.filter(e=>e&&"object"==typeof e&&"text"===e.type).map(e=>e.text||"").join("")),zr.debug("Tool result",{toolUseId:t,isError:o,output:s?.slice(0,500)});const a=5e4,c=t?oe.get(t):void 0;if(re({role:"tool_result",content:"",timestamp:(new Date).toISOString(),toolName:c,toolOutput:s?.slice(0,a),isError:o}),t&&te.has(t)){const n=te.get(t);if(zr.info("[fix] Subagent completed",{toolUseId:t,isError:o,subagentType:n?.subagentType,description:n?.description,activeSubagentCount:te.size-1}),s&&Oe({toolUseId:t,kind:"text",content:s}),Ye({toolUseId:t,status:o?"error":"complete"}),"fix"===e.mode&&"triage"===n?.subagentType){const e=o?"failed":"succeeded",n=s?s.slice(0,500):null,r=(ue?.workers??[]).map(r=>r.id===t?{...r,status:e,summary:n,endedAt:Date.now()}:r);me({workers:r})}if("fix"===e.mode&&("code-worker"===n?.subagentType||"browser-worker"===n?.subagentType)){const e=o?"failed":"succeeded",n=s?s.slice(0,500):null,r=(ue?.workers??[]).map(r=>r.id===t?{...r,status:e,summary:n,endedAt:Date.now()}:r);o?(Ve?.({failedTests:(ue?.failedTests??0)+1,currentTestDescription:null}),me({failedTests:(ue?.failedTests??0)+1,currentTestDescription:null,workers:r})):(Ve?.({fixedTests:(ue?.fixedTests??0)+1,currentTestDescription:null}),me({fixedTests:(ue?.fixedTests??0)+1,currentTestDescription:null,workers:r}))}te.delete(t)}}continue}if("result"===n.type){if(zr.info("[fix] Agent result received",{subtype:n.subtype,messageCount:ln,elapsed:Date.now()-ce,activeSubagents:te.size,fixedTests:ue?.fixedTests,failedTests:ue?.failedTests,phase:ue?.phase}),w){if("success"===n.subtype){Y&&(clearTimeout(Y),Y=void 0);for(const e of J)A?.pushText(`[Message from web UI user]: ${e}`);if(J=[],(S||"fix"===e.mode)&&A){if(A.hasQueuedMessages()){zr.info("[ws] Queued web UI messages found, continuing agent"),$=!0,A.allowNextTurn();continue}if(await ja(A,3e3)){zr.info("[ws] Web UI message received during grace period, continuing agent"),$=!0,A.allowNextTurn();continue}A.finish()}if(Ve?.({phase:"complete",currentTestDescription:null,endedAt:Date.now()}),me({phase:"complete",currentTestDescription:null,endedAt:Date.now(),isError:!1,workers:he(!1)}),await Promise.allSettled(et),"verify"===e.mode){(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt).trim();const t=Qe||Je,n=/```verdict\s*\r?\n/.test(t),r=Ca(t)??{verdict:"INCONCLUSIVE",steps:["Agent finished without a parseable verdict block."],reason:n?"Failed to parse verdict.":"The agent completed without reporting a verdict.",evidence:[]},o=Aa(r);"PASS"===r.verdict?z.green("VERIFICATION PASSED"):"FAIL"===r.verdict?z.red("VERIFICATION FAILED"):z.yellow("VERIFICATION INCONCLUSIVE"),o.steps.length>0&&o.steps.forEach((e,t)=>{}),o.reason&&(r.verdict,o.reason),o.evidence.length>0&&o.evidence.forEach(e=>{}),Ae({phase:"complete",endedAt:Date.now(),isError:"PASS"!==r.verdict,currentActivity:null}),process.exitCode="PASS"===r.verdict?0:"FAIL"===r.verdict?1:2,Ke({status:"success"})}else{if(Ae({phase:"complete",endedAt:Date.now(),isError:!1,currentActivity:null}),Gt&&Xe.length>0){z.green("Created files:");for(const e of Xe)z.green(`- ${e}`)}const e=(e,t)=>`]8;;${e}${t}]8;;`,t=qe?z.cyan(`📊 View Autoheal Report:\n ${e(qe,z.cyan(z.bold(z.underline(qe))))}`):void 0;Ke({status:"success",result:t}),se="COMPLETED"}}else if(K||Z)zr.info("[fix] Suppressing error status: user-message interrupt in progress");else if(N)se="CANCELED",me({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:he(!0)}),await Promise.allSettled(et),Ae({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0});else if(T){let e="Execution error before verification completed.";"error_max_budget_usd"===n.subtype?e="Budget limit exceeded before verification completed.":"error_max_turns"===n.subtype&&(e="Maximum turns exceeded before verification completed."),z.yellow("VERIFICATION INCONCLUSIVE"),await Promise.allSettled(et),Ae({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),Ke({status:"success"}),process.exitCode=2}else{let e,t="unknown",r="Run failed.";"error_max_budget_usd"===n.subtype?(t="budget_exceeded",e="total_cost_usd"in n?n.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.`,zr.warn("[fix] Budget limit exceeded",{subtype:n.subtype,totalCostUsd:e})):"error_max_turns"===n.subtype?(t="max_turns",r="Maximum turns exceeded. The fix session was stopped."):"error_during_execution"===n.subtype&&(t="execution_error"),Ve?.({endedAt:Date.now(),isError:!0}),me({phase:"complete",endedAt:Date.now(),isError:!0,errorReason:t,errorMessage:r,totalCostUsd:e,currentTestDescription:null,workers:he(!0)}),await Promise.allSettled(et),Ae({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),Ke({error:r,status:"error"}),process.exitCode=1,se="FAILED"}N=!1;break}const r=_&&B;if("success"!==n.subtype){if(!N){let e="Run failed.";"error_max_budget_usd"===n.subtype?(e=`Budget limit exceeded (${"total_cost_usd"in n?`$${n.total_cost_usd.toFixed(2)}`:"unknown"} spent). The fix session was stopped to prevent runaway costs.`,zr.warn("[fix] Budget limit exceeded",{subtype:n.subtype,totalCostUsd:"total_cost_usd"in n?n.total_cost_usd:void 0})):"error_max_turns"===n.subtype&&(e="Maximum turns exceeded. The fix session was stopped."),Ke({error:e,status:"error"}),process.exitCode=1}}else Ke(r?{status:"running"}:{status:"success"});if($=!1,N=!1,r){B=!1,zr.info("Processing deferred MCP restart request in chat mode"),await on(),t=!0;break}H=!1,Ge({label:void 0}),A?.allowNextTurn(),I&&M>0&&(M-=1,$=!0,Ke({status:"running"}));continue}}if(K&&await K,Z&&(Z=!1,t=!0,Ke({status:"running"}),zr.info("[fix] Resuming after user-message interrupt")),!t)break}}catch(e){N?(se="CANCELED",me({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:he(!0)}),await Promise.allSettled(et),Ae({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0})):(zr.error("[fix] Agent encountered an error",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0,elapsed:Date.now()-ce}),Ke({error:`Agent encountered an error: ${e}`,status:"error"}),process.exitCode=1,se="FAILED",me({phase:"complete",endedAt:Date.now(),isError:!0,currentTestDescription:null,workers:he(!0)}),await Promise.allSettled(et),Ae({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),zr.flush(),zr.printLogFileInfo())}finally{if(pn&&clearTimeout(pn),clearInterval(fn),Y&&(clearTimeout(Y),Y=void 0),zr.info("[fix] Agent session ending",{finalStatus:se,elapsed:Date.now()-ce,totalMessages:ln}),Ot(),$=!1,N=!1,cn(),process.off("uncaughtException",a),A?.finish(),se){zr.info("[fix] Reporting final autoheal status",{status:se});const e=Date.now();await ge(se),zr.info("[fix] Final autoheal status reported",{durationMs:Date.now()-e})}if(zr.info("[fix] Closing WebSocket progress reporter"),await(le?.closeAndWait()),await Promise.allSettled(et),await(be?.closeAndWait()),!Lt&&ne.length>0&&Pe&&(zr.info("[session] Uploading session history",{messageCount:ne.length}),await go({authHeader:l,orgId:u,sessionId:Pe,projectId:Xr(c),history:ne}).catch(e=>{zr.warn("[session] Failed to upload session history",{error:e instanceof Error?e.message:String(e)})})),Lt&&Dt){const t=Date.now();try{zr.info("[fix] Computing diff...");const n=await Dt.computeDiff();if(n&&n.trim().length>0){zr.info("[fix] Uploading diff...",{diffLength:n.length});const{diffBucketPath:r,uploadUrl:o}=await lo({authHeader:l,contentType:"text/plain",orgId:u,runId:e.runId});await io({body:n,contentType:"text/plain",uploadUrl:o,errorContext:"diff"}),await uo({authHeader:l,diffBucketPath:r,orgId:u,runId:e.runId}),zr.info("[fix] Diff uploaded",{durationMs:Date.now()-t})}else zr.info("[fix] No diff to upload (empty or no changes)")}catch(e){zr.warn("[fix] Failed to upload diff",{error:e instanceof Error?e.message:String(e),durationMs:Date.now()-t})}}zr.info("[fix] Cleaning up diff tracker"),await(Dt?.cleanup()),Lt&&ne.length>0&&Pe&&(zr.info("[fix] Uploading session history",{messageCount:ne.length}),await go({authHeader:l,orgId:u,sessionId:Pe,projectId:Xr(c),history:ne}).catch(e=>{zr.warn("[fix] Failed to upload session history",{error:e instanceof Error?e.message:String(e)})})),zr.info("[fix] Running final cleanup"),await He(),zr.info("[fix] Cleanup complete")}},Ga=pe.object({runId:pe.string(),timestamp:pe.number()}),Wa=[{args:["--trace=on"],description:"Run Playwright tests",name:"test"},{args:[],description:"Install browser dependencies",name:"install"}],Ya=["You have two different versions of @playwright/test"];function Va(e){const[t,...n]=Ji(e),r=[t,...n.slice(0,-1)].join(" ");return(t,n)=>{let o=t.toString();for(const e of Wa)o=o.replaceAll(`${r} playwright ${e.name}`,`${r} stably ${e.name}`).replaceAll(`npx playwright ${e.name}`,`npx stably ${e.name}`);if("yarn"===e){const e=o.split("\n");return e.length>0&&(e[0].includes("/.bin/playwright")||e[0].includes("\\.bin\\playwright"))&&e.shift(),void n.write(e.join("\n"))}n.write(o)}}async function za({overrideArgs:e,subcommand:t}){zr.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=Wa.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 [file] Auto-fix failing tests using AI"),n(" stably create <url> Generate new tests from a URL using AI"),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=zi();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:o}=r;if(!o)return void n("Could not determine package manager.");n("Playwright options:"),n("");const[s,...i]=Ji(o),a=Va(o);return new Promise(t=>{const n=m(s,[...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 g=[t,...d,...f];zr.info("[test] Forwarded args computed",{forwardedArgs:g}),zr.info("[test] Resolving Stably test environment");const y=Date.now(),b="test"===t?await to():void 0;zr.info("[test] Stably test environment resolved",{durationMs:Date.now()-y,hasCredentials:null!=b,hasWsUrl:!!b?.STABLY_WS_URL}),zr.info("[test] Loading remote environment variables");const w=await no();zr.info("[test] Remote environment loaded",{hasRemoteEnv:!!w,variableCount:w?Object.keys(w.variables).length:0});const _={...w?.variables,...w?.sensitiveValues.length?{STABLY_SENSITIVE_VALUES:Buffer.from(JSON.stringify(w.sensitiveValues)).toString("base64")}:{}};zr.info("[test] Setting up Stably reporter injection");const I="test"===t?function({forwardedArgs:e,hasCredentials:t}){if(!t)return console.warn("⚠️ Stably credentials not found. Test results will not be reported to Stably."),console.warn(" To enable reporting, either:"),console.warn(" • Run `npx stably login` to authenticate"),void console.warn(" • Or set STABLY_API_KEY and STABLY_PROJECT_ID environment variables\n");const n=process.cwd(),r=e=>{const t=function(e){let t=o(e);for(;;){if([i(t,"node_modules","@stablyai","playwright-test"),i(t,"node_modules",".pnpm","@stablyai+playwright-test")].some(e=>v(e)))return!0;const e=s(t);if(e===t)return!1;t=e}}(e);return t||(console.warn("⚠️ @stablyai/playwright-test is not installed. Stably reporter will not be injected."),console.warn(" Install it with: npm install @stablyai/playwright-test"),console.warn(" Reference: ]8;;https://docs.stably.ai/getting-started/sdk-setup-guidehttps://docs.stably.ai/getting-started/sdk-setup-guide]8;;\n")),t},a=(e,t)=>{try{return function({baseConfigPath:e,projectDir:t}){const 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=s(o(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: '${Jn}',\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: '${Jn}',\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 v(a)||T(a,{recursive:!0}),S(u,d,"utf-8"),function(e){const t=i(e,".gitignore");try{if(v(t)){const e=E(t,"utf-8");if(e.split("\n").map(e=>e.trim()).includes(Xo))return;const n=e.length>0&&!e.endsWith("\n");x(t,`${n?"\n":""}${Xo}\n`)}else S(t,`${Xo}\n`)}catch{}}(a),u}({baseConfigPath:e,projectDir:t})}catch{return void console.warn("⚠️ Could not create Stably wrapper config. Reporter injection skipped.")}};if(e.some(e=>"--config"===e||"-c"===e||e.startsWith("--config=")||e.startsWith("-c="))){const t=e.findIndex(e=>"--config"===e||"-c"===e);if(-1!==t&&e[t+1]){const i=o(n,e[t+1]),c=s(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=o(n,e[i].split("=")[1]),c=s(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=es(n);if(!c)return;const u=s(c);if(!r(u))return;const d=a(c,u);return d?(e.push("--config",d),d):void 0}({forwardedArgs:g,hasCredentials:null!=b}):void 0;zr.info("[test] Reporter injection setup complete",{hasWrapperConfig:!!I}),zr.info("[test] Spawning Playwright process"),await function(e,t={}){zr.info("[test] Detecting Playwright installation");const n=zi();zr.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[o,...s]=Ji(r),i=eo(t.env),a=[o,...s,...e];zr.info("[test] Spawning Playwright process",{command:a.join(" "),pid:process.pid});const c=Date.now(),l=m(o,[...s,...e],{stdio:["inherit","pipe","pipe"],shell:"win32"===process.platform,env:{...i,...process.env.CI?{}:{FORCE_COLOR:"1"}}});zr.info("[test] Playwright process spawned",{childPid:l.pid});const u=Va(r),d=function(){let e=!1,t="";return(n,r)=>{if(!e){t+=n,t.length>1024&&(t=t.slice(-1024));for(const n of Ya)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)}}}();l.stdout?.on("data",e=>{u(e,process.stdout)}),l.stderr?.on("data",e=>{const t=e.toString();u(e,process.stderr),d(t,process.stderr)});const p=new AbortController,f=()=>!p.signal.aborted&&(p.abort(),t.onClose?.(),process.removeListener("SIGINT",h),process.removeListener("SIGTERM",h),!0),h=e=>{zr.info("[test] Signal received, killing Playwright process",{signal:e,childPid:l.pid}),f(),l.kill(e);const t="SIGINT"===e?130:143;process.exit(t)};return process.on("SIGINT",h),process.on("SIGTERM",h),new Promise((e,t)=>{l.on("error",e=>{f()&&(zr.error("[test] Playwright process error",{error:e.message,childPid:l.pid}),t(e))}),l.on("close",t=>{if(!f())return;zr.info("[test] Playwright process exited",{exitCode:t,durationMs:Date.now()-c});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)})})})}(g,{env:{..._,...b},onClose:()=>{var e;zr.info("[test] Playwright process closed, cleaning up wrapper config"),(e=I)&&v(e)&&P(e)}})}function Ka(e){const t=new Date(e),n=new Date,r=n.getTime()-t.getTime(),o=Math.floor(r/1e3),s=Math.floor(o/60),i=Math.floor(s/60),a=Math.floor(i/24);if(o<60)return"just now";if(s<60)return`${s}m ago`;if(i<24)return`${i}h ago`;if(a<=7)return`${a}d ago`;const c=t.toLocaleString("en-US",{month:"short"}),l=t.getDate();return t.getFullYear()===n.getFullYear()?`${c} ${l}`:`${c} ${l}, ${t.getFullYear()}`}var qa={PASSED:z.green,FAILED:z.red,TIMEDOUT:z.red,CANCELLED:z.yellow,INTERRUPTED:z.yellow,RUNNING:z.cyan,QUEUED:z.dim},Ja=(e,t)=>e?e.length>t?`${e.slice(0,t-1)}…`:e:"-",Qa=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")}`},Xa=e=>(qa[e]??(e=>e))(e),Za=/\x1b\[[0-9;]*m/g,ec=(e,t)=>{const n=e.replace(Za,"").length,r=Math.max(0,t-n);return e+" ".repeat(r)},tc=e=>`${JSON.stringify(e,null,2)}\n`,nc=e=>"oauth"===e.type?e.auth.context.orgId:void 0,rc=(e,t,n)=>{if(!e)return;const r=e.toUpperCase();if(t.includes(r))return r;ae(z.red(`Invalid ${n} value "${e}". Must be one of: ${t.join(", ").toLowerCase()}`)),process.exit(1)},oc=(e,t,n)=>{if(401!==e.response.status&&403!==e.response.status||(ae(z.red("Access denied.")),process.exit(1)),404===e.response.status&&n&&(ae(z.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";ae(z.red(t)),process.exit(1)}e.error&&(ae(z.red(`Failed to ${t}: ${e.response.status}`)),process.exit(1))},sc="stably",ic=`https://registry.npmjs.org/${sc}/latest`;function ac(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 cc(e,t){const n=ac(e),r=ac(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 lc=r.join(L.homedir(),".stably"),uc=r.join(lc,"update-check.json"),dc="1"===process.env.STABLY_DISABLE_UPDATE_CHECK,pc=fe.object({lastCheck:fe.number(),latestVersion:fe.string()}),fc=!1;function hc(e=""){process.stdout.write(`${e}\n`)}function mc(...e){process.stderr.write(`${e.join(" ")}\n`)}var gc=fe.object({version:fe.string()});var yc=!1,bc=async()=>{if(yc)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{}},vc=e=>{const t=e.toLowerCase();return t.startsWith("npm_config_")||"node_options"===t};!function(){if(dc||function(e=process.argv.slice(2)){return e.includes("upgrade")}())return;const e=function(){try{const e=b.readFileSync(uc,"utf-8");return pc.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 = '${ic}';\n const cacheFile = ${JSON.stringify(uc)};\n const cacheDir = ${JSON.stringify(lc)};\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{m(process.execPath,["--input-type=module","-e",e],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()}catch{}}(),null!=e&&cc(Jn,e.latestVersion)){if(fc)return;fc=!0;let t=!1;const n=()=>{if(t)return;t=!0;const n=`${z.yellow(`update available (${Jn} → ${e.latestVersion})`)} - run \`${sc} upgrade\` to get the latest version\n`;try{b.writeSync(2,n)}catch{}};process.once("beforeExit",n),process.once("exit",n)}}(),Pe.cwdChanged&&zr.debug("Changed working directory",{cwd:Pe.newCwd});for(const e of Pe.envFilesLoaded)zr.debug("Loaded env file",{path:e});for(const e of Pe.envFileErrors)zr.warn(e);var wc=process.argv.findIndex(e=>"-v"===e||"--verbose"===e);-1!==wc&&process.argv.splice(wc,1);var _c=process.argv.findIndex(e=>"--no-telemetry"===e);-1!==_c&&process.argv.splice(_c,1),zr.info("CLI starting",{version:Jn,args:process.argv.slice(2),cwd:process.cwd()}),process.on("unhandledRejection",(e,t)=>{zr.error("Unhandled promise rejection",{reason:e instanceof Error?{message:e.message,stack:e.stack}:e,promise:String(t)}),zr.flush(),zr.printLogFileInfo()}),process.on("uncaughtException",(e,t)=>{"EPIPE"!==e.code&&(zr.error("Uncaught exception",{error:{message:e.message,stack:e.stack,name:e.name},origin:t}),zr.flush(),zr.printLogFileInfo())});var Ic=new u;Ic.name("stably").description("AI-assisted Playwright testing CLI").version(Jn),Ic.enablePositionalOptions(),Ic.showHelpAfterError(),Ic.exitOverride(),Ic.configureHelp({subcommandTerm:e=>{const t=e.registeredArguments.map(e=>e.required?`<${e.name()}>`:`[${e.name()}]`).join(" ");return t?`${e.name()} ${t}`:e.name()}});var Ec=[];Ic.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>{Ec.push(e)}});var Tc=()=>{const e=Ic.helpInformation().trimEnd();return e?`${e}\n`:""},Sc=(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},xc=()=>{process.stdout.write(Tc())};Ic.command("help [command...]").description("Show help for a command (e.g. stably help create)").action(e=>{if(!e||0===e.length)return void xc();const t=Sc(Ic,e);if(!t)return process.stderr.write(`Unknown command: ${e.join(" ")}\n`),xc(),void(process.exitCode=1);var n;n=t,process.stdout.write((e=>{const t=e.helpInformation().trimEnd();return t?`${t}\n`:""})(n))}),Ic.action(()=>Fa({mode:"chat",getHelpText:Tc})),Ic.command("login").description("Authenticate with Stably in your browser").action(Pr),Ic.command("logout").description("Clear stored Stably credentials").action(async()=>{const e=qr();e&&(ie.warn(`Environment variables ${z.cyan("STABLY_API_KEY")} and ${z.cyan("STABLY_PROJECT_ID")} are set.`),ie.warn("They will continue to be used for authentication even after logout."),ie.warn("Unset them if you want to fully de-authenticate this shell/session."));const t=await vr();if(!t)return void ae(e?z.yellow("No stored OAuth login found to clear."):z.yellow("You are not logged in."));const n=ce();n.start("Logging out..."),await(async e=>{try{await fetch(`${Zn}/api/backend/v1/logout`,{body:JSON.stringify({refresh_token:e}),headers:{"Content-Type":"application/json"},method:"POST"})}catch{}})(t.refreshToken),await _r(),await Er(),n.stop(z.green("✓ Logged out")),ae(z.green("You have been logged out successfully."))}),Ic.command("whoami").description("Show auth status and current project").action(async()=>{ie.info(`${z.bold("CLI Version:")} ${z.cyan(Jn)}`);const e=qr();if(e){ie.info(z.dim("Authentication: Environment variables")),ie.info(` ${z.bold("API Key:")} ${z.cyan(e.apiKey.slice(0,8))}...`),ie.info(` ${z.bold("Project ID:")} ${z.cyan(e.projectId)}`);const t=await vr();if(t){let e;try{e=dr(t.accessToken).email}catch{e=void 0}ie.warn("Stored OAuth login detected but will be ignored (env auth takes precedence)."),e&&ie.info(` ${z.bold("OAuth Email:")} ${z.cyan(e)}`),ie.info(` ${z.bold("Tip:")} Unset env vars to use OAuth`)}return void ae(z.green("Authenticated via environment variables"))}const t=await vr();if(!t)return void ae(z.yellow("Not logged in. Run `stably login` to authenticate."));let n;try{n=dr(t.accessToken).email}catch{n=void 0}const o=await Ir();if(!o)return ie.info(z.dim("Authentication: OAuth (not linked to a project)")),n&&ie.info(` ${z.bold("Email:")} ${z.cyan(n)}`),void ae(z.yellow("Logged in but this directory is not linked to a project. Run `stably login` to link."));const s=await(async()=>pr(process.cwd(),mr))(),i=s?r.dirname(s):process.cwd(),a=r.relative(process.cwd(),i)||".";ie.info(z.dim("Authentication: OAuth")),n&&ie.info(` ${z.bold("Email:")} ${z.cyan(n)}`),ie.info(` ${z.bold("Organization:")} ${z.cyan(o.orgName)}`),ie.info(` ${z.bold("Project:")} ${z.cyan(o.projectName)}`),ie.info(` ${z.bold("Linked at:")} ${z.dim(a)}`),ae(z.green("Authenticated"))}),Ic.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=>{le(`Starting development server for port ${e.port}...`);const t=await Qr(),n="oauth"===t.type?`${t.auth.context.orgName}-${t.auth.context.projectName}`.toLowerCase().replace(/[^a-z0-9-]/g,""):`project-${t.auth.projectId}`.toLowerCase(),r=ce();r.start("Starting development server...");const o=await Re(`http://localhost:${e.port}`,{subdomain:n});r.stop(`Your local environment is available at: ]8;;${o.url}${z.underline(z.cyan(o.url))}]8;;`)}),Ic.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 Fa({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)=>Fa({mode:"single",prompt:e,outputDir:t.output})),Ic.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 Fa({mode:"verify",prompt:e,url:t.url,maxBudgetUsd:t.maxBudget,interactive:t.interactive})}),Ic.command("internal-fix-run <runId>",{hidden:!0}).description("Internal: run fix session in subprocess").action(async e=>Fa({mode:"fix",runId:e})),Ic.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())||(zr.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 zr.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(Tn))if(Tn[n].detect({env:e,cwd:t}))return{isCi:!0,...Tn[n].configuration({env:e,cwd:t})};return{isCi:Boolean(e.CI),...(n={env:e,cwd:t},{commit:zt(n),branch:Kt(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 zr.debug("Run ID detected from CI environment",{runId:n}),t(n);zr.debug("No explicit run ID or CI environment detected, checking last-run.json");const r=await(async()=>{try{const e=await pr(process.cwd(),".stably/last-run.json");if(!e)return;const t=await Q(e,"utf-8");return{...Ga.parse(JSON.parse(t)),filePath:e}}catch{return}})();if(r){const e=(Date.now()-r.timestamp)/36e5;return zr.debug("Run ID found in last-run.json",{runId:r.runId,timestamp:r.timestamp,filePath:r.filePath,ageHours:Math.round(e)}),e>24&&zr.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)}zr.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 Qr(),n=Zr(t),r=Xr(t),[,o]=process.argv;if(!o)throw new Error("Unable to determine CLI entrypoint for fix subprocess.");return await(async({runId:e,cliEntry:t,stablyApiKey:n,stablyProjectId:r,baseEnv:o=process.env,cwd:s=process.cwd(),execPath:i=process.execPath,execArgv:a=process.execArgv,stdio:c="inherit",spawnImpl:l=({command:e,args:t,options:n})=>m(e,t,n)})=>{const u=(({baseEnv:e,stablyApiKey:t,stablyProjectId:n})=>{const r={...e};for(const e of Object.keys(r))vc(e)&&delete r[e];return{...r,STABLY_API_KEY:t,STABLY_PROJECT_ID:n}})({baseEnv:o,stablyApiKey:n,stablyProjectId:r});return await new Promise((n,r)=>{const o=l({args:[...a,t,"internal-fix-run",e],command:i,options:{cwd:s,stdio:c,env:u}});o.once("error",r),o.once("exit",(e,t)=>{n(t?1:e??1)})})})({cliEntry:o,runId:e,stablyApiKey:n,stablyProjectId:r,cwd:process.cwd(),stdio:"inherit"})})(t);0!==n&&process.exit(n)}),Ic.command("init").description("Initialize Playwright and Stably SDK in your project").action(async()=>Fa({mode:"init"})),Ic.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;hc(z.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(ic,{signal:e.signal});if(!t.ok)throw new Error(`Failed to fetch latest version: ${t.statusText}`);return gc.parse(await t.json()).version}finally{clearTimeout(t)}}();return{current:Jn,latest:e,isOutdated:cc(Jn,e)}}()}catch(e){return mc(z.red("Failed to check for updates:"),e instanceof Error?e.message:e),void(process.exitCode=1)}if(hc(`Current version: ${z.yellow(n.current)}`),hc(`Latest version: ${z.green(n.latest)}`),hc(),!n.isOutdated)return void hc(z.green("✓ You are already on the latest version!"));if(hc(z.yellow(`⚠ A new version is available: ${n.current} → ${n.latest}`)),hc(),t)return hc(z.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"}(),o=function(e){switch(e){case"global-npm":case"global-yarn-berry":case"unknown":return{command:"npm",args:["install","-g",`${sc}@latest`],description:`npm install -g ${sc}@latest`};case"global-pnpm":return{command:"pnpm",args:["add","-g",`${sc}@latest`],description:`pnpm add -g ${sc}@latest`};case"global-yarn-classic":return{command:"yarn",args:["global","add",`${sc}@latest`],description:`yarn global add ${sc}@latest`};case"npx":return{command:"npx",args:[`${sc}@latest`],description:`npx ${sc}@latest (always uses latest)`}}}(r);if("npx"===r)return hc(z.dim("You are running via npx, which always fetches the latest version.")),void hc(z.dim(`Simply run: ${z.white("npx stably")} to use the latest version.`));"unknown"===r?(hc(z.yellow("Could not detect installation method. Falling back to npm.")),hc()):"global-yarn-berry"===r&&(hc(z.yellow("Yarn Berry does not support global packages. Falling back to npm.")),hc()),hc(`Upgrade command: ${z.cyan(o.description)}`),hc(),hc(z.cyan("Upgrading...")),hc();try{await(s=o.command,i=o.args,new Promise((e,t)=>{const n=m(s,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{b.unlinkSync(uc)}catch{}}(),hc(),hc(z.green("✓ Upgrade complete!")),hc(z.dim(`Run ${z.white("stably --version")} to verify.`))}catch(e){mc(z.red("Upgrade failed:"),e instanceof Error?e.message:e),hc(),hc(z.dim("You can try manually running:")),hc(z.cyan(` ${o.description}`)),process.exitCode=1}var s,i}(e));var Ac=Ic.command("env").description("Manage remote environments");Ac.command("list").description("List available environments").action(async()=>{const e=await Qr(),t=Xr(e),n=Zr(e);zr.debug("Listing environments",{projectId:t});const r=await(o={auth:n,client:sr(),path:{projectId:t}},(o.client??zn).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/environments",...o}));var o;401!==r.response.status&&403!==r.response.status||(ae(z.red("Access denied.")),process.exit(1)),r.error&&(ae(z.red(`Failed to list environments: ${r.response.status}`)),process.exit(1));const{environments:s}=r.data;if(0!==s.length){process.stdout.write(`${z.bold("Environments")}\n\n`);for(const e of s){const t=e.isDefault?z.green(" (default)"):"",n=z.dim(` ${e.variableCount} variable${1!==e.variableCount?"s":""}`);process.stdout.write(` ${z.cyan(e.name)}${t}${n}\n`),e.description&&process.stdout.write(` ${z.dim(e.description)}\n`)}process.stdout.write("\n")}else process.stdout.write(z.dim("No environments found. Create one on your Stably dashboard.\n"))}),Ac.command("inspect <name>").description("Show variable metadata (name, sensitive flag, updated timestamp)").action(e=>(async e=>{const t=await Qr(),n=Xr(t),r=Zr(t);zr.debug("Inspecting environment",{name:e,projectId:n});const o=await(s={auth:r,client:sr(),path:{projectId:n,environmentName:e}},(s.client??zn).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/environments/{environmentName}/inspect",...s}));var s;404===o.response.status&&(ae(z.red(`Environment "${e}" not found. Run ${z.bold("stably env list")} to see available environments.`)),process.exit(1)),401!==o.response.status&&403!==o.response.status||(ae(z.red("Access denied.")),process.exit(1)),o.error&&(ae(z.red(`Failed to inspect environment: ${o.response.status}`)),process.exit(1));const{variables:i}=o.data;if(0!==i.length){process.stdout.write(`${z.bold(e)} ${z.dim(`(${i.length} variable${1!==i.length?"s":""})`)}\n\n`);for(const e of i){const t=z.dim(` [updated ${Ka(e.updatedAt)}]`);e.sensitive?process.stdout.write(` ${z.cyan(e.name)} ${z.yellow("[sensitive]")}${t}\n`):process.stdout.write(` ${z.cyan(e.name)}${t}\n`)}process.stdout.write("\n")}else process.stdout.write(z.dim(`Environment "${e}" has no variables.\n`))})(e));var Cc=Ic.command("runs").description("View test run history");Cc.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 Qr(),n=Xr(t),r=Zr(t),o=nc(t);let s;e.limit&&(s=parseInt(e.limit,10),(Number.isNaN(s)||s<1||s>100)&&(ae(z.red("--limit must be an integer between 1 and 100")),process.exit(1)));const i=rc(e.source,["LOCAL","CI","WEB"],"--source"),a=rc(e.status,["QUEUED","RUNNING","PASSED","FAILED","TIMEDOUT","CANCELLED","INTERRUPTED"],"--status"),c=rc(e.trigger,["MANUAL","SCHEDULED","UI","API","GITHUB_ACTION","SUITE_RUN"],"--trigger");zr.debug("Listing runs",{projectId:n,branch:e.branch,limit:s,after:e.after,before:e.before,source:i,status:a,suite:e.suite,trigger:c});const l=await Kn({auth:r,client:sr(),headers:ro(o),query:{projectId:n,branchName:e.branch,limit:s,afterRunId:e.after,beforeRunId:e.before,source:i,status:a,suiteName:e.suite,trigger:c}});oc(l,"list runs");const{runs:u,hasMore:d}=l.data;e.json?process.stdout.write(tc(l.data)):process.stdout.write(((e,t)=>{if(0===e.length)return z.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}},o=[],s=`${ec("Run ID",r.runId.w)}${ec("Status",r.status.w)}${ec("Branch",r.branch.w)}${ec("Started",r.started.w)}Tests`;o.push(z.bold(s));for(const t of e){const e=Ja(t.runId,r.runId.t),n=Xa(t.status),s=Ja(t.branchName,r.branch.t),i=Qa(t.startedAt),a=t.totalCount.toString();o.push(`${ec(e,r.runId.w)}${ec(n,r.status.w)}${ec(s,r.branch.w)}${ec(i,r.started.w)}${a}`)}if(t&&e.length>0){const t=e.at(-1)?.runId;t&&(o.push(""),o.push(z.dim(`Next page: stably runs list --before ${t}`)))}return o.push(""),o.join("\n")})(u,d))}),Cc.command("view <runId>").description("Show details for a specific run").option("--json","Output as JSON").action(async(e,t)=>{const n=await Qr(),r=Zr(n),o=nc(n);zr.debug("Viewing run",{runId:e});const s=await qn({auth:r,client:sr(),headers:ro(o),path:{runId:e},query:{detail:"full"}});if(oc(s,"get run details",`Run "${e}" not found.`),t.json)process.stdout.write(tc(s.data));else{const e=s.data;process.stdout.write((e=>{const t=[];if(t.push(z.bold(`Run ${e.runId}`)),t.push(` ${z.dim("Status:")} ${Xa(e.status)}`),e.branchName&&t.push(` ${z.dim("Branch:")} ${e.branchName}`),e.commitSha&&t.push(` ${z.dim("Commit:")} ${e.commitSha.slice(0,7)}`),e.startedAt&&t.push(` ${z.dim("Started:")} ${Qa(e.startedAt)}`),null!==e.durationMs&&t.push(` ${z.dim("Duration:")} ${(e=>{if(null===e)return"-";const t=Math.floor(e/1e3);if(t<60)return`${t}s`;const 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(` ${z.dim("Source:")} ${e.source.toLowerCase()}`),e.projectId){const n=`https://app.stably.ai/project/${e.projectId}/playwright/history/${e.runId}`;t.push(` ${z.dim("URL:")} ${z.cyan(z.underline(n))}`)}t.push("");const n=[];e.passedCount>0&&n.push(z.green(`${e.passedCount} passed`)),e.failedCount>0&&n.push(z.red(`${e.failedCount} failed`)),e.flakyCount>0&&n.push(z.yellow(`${e.flakyCount} flaky`)),e.timedoutCount>0&&n.push(z.red(`${e.timedoutCount} timedout`)),e.skippedCount>0&&n.push(z.dim(`${e.skippedCount} skipped`)),e.interruptedCount>0&&n.push(z.yellow(`${e.interruptedCount} interrupted`)),t.push(`${z.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(z.bold("Failed/Flaky Tests:"));for(const e of r){const n=e.status??"UNKNOWN",r=qa[n]??(e=>e),o=e.location??"",s=e.title??e.testIdentifier,{attempts:i}=e,a=i?.length??0,c=a>1?` (${a} attempts)`:"",l=o?`${o} - `:"";t.push(` ${r(n)} ${l}${s}${z.dim(c)}`);const u=i?.at(-1);if(u?.errorMessage){const e=u.errorMessage.split("\n")[0]?.slice(0,100)??"";t.push(` ${z.dim(e)}`)}}}return t.push(""),t.join("\n")})(e))}}),Ic.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)}),Wa.forEach(({args:e,description:t,name:n})=>{Ic.command(n).description(t).helpOption(!1).helpCommand(!1).allowUnknownOption(!0).allowExcessArguments(!0).passThroughOptions().action(()=>za({overrideArgs:e,subcommand:n}))});var Rc=()=>{0!==Ec.length&&(process.stderr.write(Ec.join("")),Ec=[])};(async()=>{await(async()=>{if(!yc&&"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":Jn,"node.version":process.version,"os.platform":process.platform}}),yc=!0}catch{}})();try{await Ic.parseAsync(process.argv),zr.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 zr.error(t,{stack:e instanceof Error?e.stack:void 0}),Rc(),zr.flush(),zr.printLogFileInfo(),await bc(),void(process.exitCode=1)}const t="number"==typeof e.exitCode?e.exitCode:1,n=process.argv.slice(2).find(e=>!e.startsWith("-")),r=!!n&&!!Sc(Ic,[n]);if(("commander.excessArguments"===e.code||"commander.unknownCommand"===e.code)&&n&&!r)return Ec=[],zr.warn("Unknown command",{command:n}),process.stderr.write(`command '${n}' not found\n`),xc(),void(process.exitCode=t);zr.debug("Commander error",{code:e.code,exitCode:t}),Rc(),process.exitCode=t}finally{zr.flush(),await bc()}})();