stably 4.12.2 → 4.12.4-rc.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +1 -1
- package/dist/{playwright-cli.js → stably-browser.js} +77 -44
- package/dist/stably-plugin-cli/skills/browser-interaction-guide/SKILL.md +30 -30
- package/dist/stably-plugin-cli/skills/bulk-test-handling/SKILL.md +1 -1
- package/dist/stably-plugin-cli/skills/debugging-test-failures/SKILL.md +11 -11
- package/dist/stably-plugin-cli/skills/playwright-best-practices/SKILL.md +6 -6
- package/dist/stably-plugin-cli/skills/playwright-config-auth/SKILL.md +8 -8
- package/dist/stably-plugin-cli/skills/{playwright-cli → stably-browser}/SKILL.md +156 -156
- package/dist/stably-plugin-cli/skills/{playwright-cli → stably-browser}/references/request-mocking.md +11 -11
- package/dist/stably-plugin-cli/skills/{playwright-cli → stably-browser}/references/running-code.md +28 -28
- package/dist/stably-plugin-cli/skills/{playwright-cli → stably-browser}/references/session-management.md +40 -40
- package/dist/stably-plugin-cli/skills/{playwright-cli → stably-browser}/references/storage-state.md +41 -41
- package/dist/stably-plugin-cli/skills/{playwright-cli → stably-browser}/references/test-generation.md +10 -10
- package/dist/stably-plugin-cli/skills/{playwright-cli → stably-browser}/references/tracing.md +23 -23
- package/dist/stably-plugin-cli/skills/{playwright-cli → stably-browser}/references/video-recording.md +8 -8
- package/dist/stably-plugin-cli/skills/test-creation-workflow/SKILL.md +15 -15
- package/package.json +2 -2
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{config as e,parse as t}from"dotenv";import*as n from"path";import r,{resolve as 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 g,execFile as m,execFileSync as y}from"child_process";import b from"process";import*as w from"fs";import v,{existsSync as _,statSync as I,readFileSync as T,appendFileSync as E,realpathSync as S,createReadStream as x,mkdirSync as A,writeFileSync as C,openSync as R,readSync as P,closeSync as k,rmSync as U}from"fs";import{fileURLToPath as L,URL as D}from"url";import $,{tmpdir as O,constants as N}from"os";import"timers/promises";import B from"stream";import{debuglog as j,promisify as M,TextDecoder as F,TextEncoder as H}from"util";import{createSdkMcpServer as G,tool as W,query as Y}from"@anthropic-ai/claude-agent-sdk";import{match as V}from"ts-pattern";import z from"net";import{createInterface as K}from"readline/promises";import q from"picocolors";import{simpleGit as J}from"simple-git";import Q,{randomUUID as X}from"crypto";import{readFile as Z,mkdir as ee,writeFile as te,unlink as ne,access as re,readdir as oe,stat as se,rm as ie,appendFile as ae}from"fs/promises";import{log as ce,outro as le,spinner as ue,intro as de,select as pe,isCancel as fe}from"@clack/prompts";import he,{z as ge}from"zod";import me from"open";import ye from"http";import be from"pino";import we from"sonic-boom";import{z as ve}from"zod/v3";import _e from"ws";import{useState as Ie,useRef as Te,useEffect as Ee,useCallback as Se,useMemo as xe}from"react";import{jsx as Ae,jsxs as Ce}from"react/jsx-runtime";import{createRequire as Re}from"module";import{parseDocument as Pe}from"yaml";import{startTunnel as ke}from"@stablyhq/runner-sdk";var Ue=(e=>"undefined"!=typeof require?require:"undefined"!=typeof Proxy?new Proxy(e,{get:(e,t)=>("undefined"!=typeof require?require:e)[t]}):e)(function(e){if("undefined"!=typeof require)return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),Le={cwdChanged:!1,newCwd:void 0,envFilesLoaded:[],envFileErrors:[],remoteEnvName:void 0},De=process.argv.findIndex(e=>"-C"===e||"--cwd"===e);if(-1!==De&&process.argv[De+1]){const e=process.argv[De+1];process.chdir(e),Le.cwdChanged=!0,Le.newCwd=e,process.argv.splice(De,2)}for(var $e=[],Oe=0;Oe<process.argv.length;)if("--env-file"===process.argv[Oe]){const e=process.argv[Oe+1];e&&!e.startsWith("-")?($e.push(e),process.argv.splice(Oe,2)):Oe++}else Oe++;var Ne=process.argv.findIndex(e=>"--env"===e);-1!==Ne&&process.argv[Ne+1]&&!process.argv[Ne+1].startsWith("-")&&(Le.remoteEnvName=process.argv[Ne+1],process.argv.splice(Ne,2));for(const t of $e){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})`;Le.envFileErrors.push(e),process.stderr.write(`${e}\n`)}else Le.envFilesLoaded.push(n)}var Be={detect:({env:e})=>Boolean(e.APPVEYOR),configuration({env:e}){const t=e.APPVEYOR_PULL_REQUEST_NUMBER,n=Boolean(t);return{name:"Appveyor",service:"appveyor",commit:e.APPVEYOR_REPO_COMMIT,tag:e.APPVEYOR_REPO_TAG_NAME,build:e.APPVEYOR_BUILD_NUMBER,buildUrl:`https://ci.appveyor.com/project/${e.APPVEYOR_PROJECT_SLUG}/build/${e.APPVEYOR_BUILD_VERSION}`,branch:e.APPVEYOR_REPO_BRANCH,job:e.APPVEYOR_JOB_NUMBER,jobUrl:`https://ci.appveyor.com/project/${e.APPVEYOR_PROJECT_SLUG}/build/job/${e.APPVEYOR_JOB_ID}`,pr:t,isPr:n,prBranch:e.APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH,slug:e.APPVEYOR_REPO_NAME,root:e.APPVEYOR_BUILD_FOLDER}}};function je(e){return(/\d+(?!.*\d+)/.exec(e)||[])[0]}function Me(e){return e?/^(?:refs\/heads\/)?(?<branch>.+)$/i.exec(e)[1]:void 0}var Fe={detect:({env:e})=>Boolean(e.BUILD_BUILDURI),configuration({env:e}){const t=e.SYSTEM_PULLREQUEST_PULLREQUESTID,n=Boolean(t);return{name:"Azure Pipelines",service:"azurePipelines",commit:e.BUILD_SOURCEVERSION,build:e.BUILD_BUILDNUMBER,branch:Me(n?e.SYSTEM_PULLREQUEST_TARGETBRANCH:e.BUILD_SOURCEBRANCH),pr:t,isPr:n,prBranch:Me(n?e.SYSTEM_PULLREQUEST_SOURCEBRANCH:void 0),root:e.BUILD_REPOSITORY_LOCALPATH}}},He={detect:({env:e})=>Boolean(e.bamboo_agentId),configuration:({env:e})=>({name:"Bamboo",service:"bamboo",commit:e.bamboo_planRepository_1_revision,build:e.bamboo_buildNumber,buildUrl:e.bamboo_buildResultsUrl,branch:e.bamboo_planRepository_1_branchName,job:e.bamboo_buildKey,root:e.bamboo_build_working_directory})},Ge={detect:({env:e})=>Boolean(e.BITBUCKET_BUILD_NUMBER),configuration:({env:e})=>({name:"Bitbucket Pipelines",service:"bitbucket",commit:e.BITBUCKET_COMMIT,tag:e.BITBUCKET_TAG,build:e.BITBUCKET_BUILD_NUMBER,buildUrl:`https://bitbucket.org/${e.BITBUCKET_REPO_FULL_NAME}/addon/pipelines/home#!/results/${e.BITBUCKET_BUILD_NUMBER}`,branch:e.BITBUCKET_BRANCH,slug:e.BITBUCKET_REPO_FULL_NAME,root:e.BITBUCKET_CLONE_DIR})},We={detect:({env:e})=>Boolean(e.BITRISE_IO),configuration({env:e}){const t="false"===e.BITRISE_PULL_REQUEST?void 0:e.BITRISE_PULL_REQUEST,n=Boolean(t);return{name:"Bitrise",service:"bitrise",commit:e.BITRISE_GIT_COMMIT,tag:e.BITRISE_GIT_TAG,build:e.BITRISE_BUILD_NUMBER,buildUrl:e.BITRISE_BUILD_URL,branch:n?e.BITRISEIO_GIT_BRANCH_DEST:e.BITRISE_GIT_BRANCH,pr:t,isPr:n,prBranch:n?e.BITRISE_GIT_BRANCH:void 0,slug:e.BITRISE_APP_SLUG}}},Ye={detect:({env:e})=>Boolean(e.BUDDY_WORKSPACE_ID),configuration({env:e}){const t=je(e.BUDDY_EXECUTION_PULL_REQUEST_ID),n=Boolean(t);return{name:"Buddy",service:"buddy",commit:e.BUDDY_EXECUTION_REVISION,tag:e.BUDDY_EXECUTION_TAG,build:e.BUDDY_EXECUTION_ID,buildUrl:e.BUDDY_EXECUTION_URL,branch:n?e.BUDDY_EXECUTION_PULL_REQUEST_HEAD_BRANCH:e.BUDDY_EXECUTION_BRANCH,pr:t,isPr:n,slug:e.BUDDY_REPO_SLUG}}},Ve="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function ze(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ke,qe,Je,Qe,Xe,Ze,et,tt,nt={exports:{}};var rt,ot,st,it,at,ct,lt,ut,dt,pt,ft,ht,gt,mt,yt,bt={exports:{}},wt={};function vt(){if(ht)return ft;ht=1;const e=r,t=function(){if(st)return ot;st=1;const e=r,t=function(){if(tt)return et;tt=1;const e="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,t=r,n=e?";":":",o=function(){if(Ze)return Xe;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 Ze=1,e="win32"===process.platform||Ve.TESTING_WINDOWS?function(){if(qe)return Ke;qe=1,Ke=n,n.sync=function(n,r){return t(e.statSync(n),n,r)};var e=v;function t(e,t,n){return!(!e.isSymbolicLink()&&!e.isFile())&&function(e,t){var n=void 0!==t.pathExt?t.pathExt:process.env.PATHEXT;if(!n)return!0;if(-1!==(n=n.split(";")).indexOf(""))return!0;for(var r=0;r<n.length;r++){var 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 Ke}():function(){if(Qe)return Je;Qe=1,Je=t,t.sync=function(t,r){return n(e.statSync(t),r)};var e=v;function t(t,r,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 Je}(),Xe=t,t.sync=function(t,n){try{return e.sync(t,n||{})}catch(e){if(n&&n.ignoreErrors||"EACCES"===e.code)return!1;throw e}},Xe}(),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 et=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)},et}(),n=function(){if(rt)return bt.exports;rt=1;const e=(e={})=>{const t=e.env||process.env;return"win32"!==(e.platform||process.platform)?"PATH":Object.keys(t).reverse().find(e=>"PATH"===e.toUpperCase())||"Path"};return bt.exports=e,bt.exports.default=e,bt.exports}();function 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 ot=function(e){return o(e)||o(e,!0)}}(),n=function(){if(it)return wt;it=1;const e=/([()\][%!^"`<>&|;, *?])/g;return wt.command=function(t){return t.replace(e,"^$1")},wt.argument=function(t,n){return t=(t=`"${t=(t=(t=`${t}`).replace(/(?=(\\+?)?)\1"/g,'$1$1\\"')).replace(/(?=(\\+?)?)\1$/,"$1$1")}"`).replace(e,"^$1"),n&&(t=t.replace(e,"^$1")),t},wt}(),o=function(){if(pt)return dt;pt=1;const e=v,t=function(){if(ut)return lt;ut=1;const e=ct?at:(ct=1,at=/^#!(.*)/);return lt=(t="")=>{const n=t.match(e);if(!n)return null;const[r,o]=n[0].replace(/#! ?/,"").split(" "),s=r.split("/").pop();return"env"===s?o:o?`${s} ${o}`:s}}();return dt=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 ft=function(r,c,l){c&&!Array.isArray(c)&&(l=c,c=null);const u={command:r,args:c=c?c.slice(0):[],options:l=Object.assign({},l),file:void 0,original:{command:r,args:c}};return l.shell?u:function(r){if(!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 _t=ze(function(){if(yt)return nt.exports;yt=1;const e=p,t=vt(),n=function(){if(mt)return gt;mt=1;const e="win32"===process.platform;function t(e,t){return Object.assign(new Error(`${t} ${e.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}function n(n,r){return e&&1===n&&!r.file?t(r.original,"spawn"):null}return gt={hookChildProcess:function(t,r){if(!e)return;const 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},gt}();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 nt.exports=r,nt.exports.spawn=r,nt.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},nt.exports._parse=t,nt.exports._enoent=n,nt.exports}());function It(e={}){const{env:t=process.env,platform:n=process.platform}=e;return"win32"!==n?"PATH":Object.keys(t).reverse().find(e=>"PATH"===e.toUpperCase())||"Path"}var Tt=(e,t)=>({name:`SIGRT${t+1}`,number:Et+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),Et=34,St=[{name:"SIGHUP",number:1,action:"terminate",description:"Terminal closed",standard:"posix"},{name:"SIGINT",number:2,action:"terminate",description:"User interruption with CTRL-C",standard:"ansi"},{name:"SIGQUIT",number:3,action:"core",description:"User interruption with CTRL-\\",standard:"posix"},{name:"SIGILL",number:4,action:"core",description:"Invalid machine instruction",standard:"ansi"},{name:"SIGTRAP",number:5,action:"core",description:"Debugger breakpoint",standard:"posix"},{name:"SIGABRT",number:6,action:"core",description:"Aborted",standard:"ansi"},{name:"SIGIOT",number:6,action:"core",description:"Aborted",standard:"bsd"},{name:"SIGBUS",number:7,action:"core",description:"Bus error due to misaligned, non-existing address or paging error",standard:"bsd"},{name:"SIGEMT",number:7,action:"terminate",description:"Command should be emulated but is not implemented",standard:"other"},{name:"SIGFPE",number:8,action:"core",description:"Floating point arithmetic error",standard:"ansi"},{name:"SIGKILL",number:9,action:"terminate",description:"Forced termination",standard:"posix",forced:!0},{name:"SIGUSR1",number:10,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGSEGV",number:11,action:"core",description:"Segmentation fault",standard:"ansi"},{name:"SIGUSR2",number:12,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGPIPE",number:13,action:"terminate",description:"Broken pipe or socket",standard:"posix"},{name:"SIGALRM",number:14,action:"terminate",description:"Timeout or timer",standard:"posix"},{name:"SIGTERM",number:15,action:"terminate",description:"Termination",standard:"ansi"},{name:"SIGSTKFLT",number:16,action:"terminate",description:"Stack is empty or overflowed",standard:"other"},{name:"SIGCHLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"posix"},{name:"SIGCLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"other"},{name:"SIGCONT",number:18,action:"unpause",description:"Unpaused",standard:"posix",forced:!0},{name:"SIGSTOP",number:19,action:"pause",description:"Paused",standard:"posix",forced:!0},{name:"SIGTSTP",number:20,action:"pause",description:'Paused using CTRL-Z or "suspend"',standard:"posix"},{name:"SIGTTIN",number:21,action:"pause",description:"Background process cannot read terminal input",standard:"posix"},{name:"SIGBREAK",number:21,action:"terminate",description:"User interruption with CTRL-BREAK",standard:"other"},{name:"SIGTTOU",number:22,action:"pause",description:"Background process cannot write to terminal output",standard:"posix"},{name:"SIGURG",number:23,action:"ignore",description:"Socket received out-of-band data",standard:"bsd"},{name:"SIGXCPU",number:24,action:"core",description:"Process timed out",standard:"bsd"},{name:"SIGXFSZ",number:25,action:"core",description:"File too big",standard:"bsd"},{name:"SIGVTALRM",number:26,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGPROF",number:27,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGWINCH",number:28,action:"ignore",description:"Terminal window size changed",standard:"bsd"},{name:"SIGIO",number:29,action:"terminate",description:"I/O is available",standard:"other"},{name:"SIGPOLL",number:29,action:"terminate",description:"Watched event",standard:"other"},{name:"SIGINFO",number:29,action:"ignore",description:"Request for process information",standard:"other"},{name:"SIGPWR",number:30,action:"terminate",description:"Device running out of power",standard:"systemv"},{name:"SIGSYS",number:31,action:"core",description:"Invalid system call",standard:"other"},{name:"SIGUNUSED",number:31,action:"terminate",description:"Invalid system call",standard:"other"}],xt=()=>{const e=(()=>{const e=64-Et+1;return Array.from({length:e},Tt)})();return[...St,...e].map(At)},At=({name:e,number:t,description:n,action:r,forced:o=!1,standard:s})=>{const{signals:{[e]:i}}=N,a=void 0!==i;return{name:e,number:a?i:t,description:n,supported:a,action:r,forced:o,standard:s}},Ct=({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}],Rt=(()=>{const e=xt();return Object.fromEntries(e.map(Ct))})();(()=>{const e=xt(),t=Array.from({length:65},(t,n)=>((e,t)=>{const n=((e,t)=>{const n=t.find(({name:t})=>N.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 Pt=({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=b.cwd()}}})=>{s=null===s?void 0:s;const f=void 0===(o=null===o?void 0:o)?void 0:Rt[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}),g=`Command ${h}: ${i}`,m="[object Error]"===Object.prototype.toString.call(r),y=m?`${g}\n${r.message}`:g,w=[y,t,e].filter(Boolean).join("\n");return m?(r.originalMessage=r.message,r.message=w):r=new Error(w),r.shortMessage=y,r.command=i,r.escapedCommand=a,r.exitCode=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},kt=["stdin","stdout","stderr"],Ut=[];Ut.push("SIGHUP","SIGINT","SIGTERM"),"win32"!==process.platform&&Ut.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),"linux"===process.platform&&Ut.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var Lt,Dt,$t=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,Ot=Symbol.for("signal-exit emitter"),Nt=globalThis,Bt=Object.defineProperty.bind(Object),jt=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(Nt[Ot])return Nt[Ot];Bt(Nt,Ot,{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}},Mt=class{},Ft=globalThis.process;$t(Ft)?new class extends Mt{#e="win32"===Ft.platform?"SIGINT":"SIGHUP";#t=new jt;#n;#r;#o;#s={};#i=!1;constructor(e){super(),this.#n=e,this.#s={};for(const t of Ut)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(!$t(this.#n))return()=>{};!1===this.#i&&this.load();const n=t?.alwaysLast?"afterExit":"exit";return this.#t.on(n,e),()=>{this.#t.removeListener(n,e),0===this.#t.listeners.exit.length&&0===this.#t.listeners.afterExit.length&&this.unload()}}load(){if(!this.#i){this.#i=!0,this.#t.count+=1;for(const e of Ut)try{const t=this.#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,Ut.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 $t(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&&$t(this.#n)){"number"==typeof t[0]&&(this.#n.exitCode=t[0]);const r=n.call(this.#n,e,...t);return this.#t.emit("exit",this.#n.exitCode,null),r}return n.call(this.#n,e,...t)}}(Ft):new class extends Mt{onExit(){return()=>{}}load(){}unload(){}},new TextEncoder,function(){if(Dt)return Lt;Dt=1;const{PassThrough:e}=B;Lt=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 Ht=(async()=>{})().constructor.prototype;["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(Ht,e)]);var Gt=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],Wt=/^[\w.-]+$/,Yt=j("execa").enabled,Vt=(e,t)=>String(e).padStart(t,"0"),zt=(e,t,n={})=>{const o=_t._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||b.cwd(),execPath:b.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:Yt,...n}).env=(({env:e,extendEnv:t,preferLocal:n,localDir:o,execPath:s})=>{const i=t?{...b.env,...e}:e;return n?(({env:e=b.env,...t}={})=>{const n=It({env:e={...e}});return t.path=e[n],e[n]=(({cwd:e=b.cwd(),path:t=b.env[It()],preferLocal:n=!0,execPath:o=b.execPath,addExecPath:s=!0}={})=>{const i=e instanceof URL?L(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?L(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 kt.map(t=>e[t]);if((e=>kt.some(t=>void 0!==e[t]))(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${kt.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,kt.length);return Array.from({length:n},(e,n)=>t[n])})(n),"win32"===b.platform&&"cmd"===r.basename(e,".exe")&&t.unshift("/q"),{file:e,args:t,options:n,parsed:o}},Kt=(e,t,n)=>"string"==typeof t||d.isBuffer(t)?e.stripFinalNewline?function(e){const t="string"==typeof e?"\n":"\n".charCodeAt(),n="string"==typeof e?"\r":"\r".charCodeAt();return e[e.length-1]===t&&(e=e.slice(0,-1)),e[e.length-1]===n&&(e=e.slice(0,-1)),e}(t):t:void 0===n?void 0:"";function qt(e,t,n){const r=zt(e,t,n),o=((e,t)=>Gt(e,t).join(" "))(e,t),s=((e,t)=>Gt(e,t).map(e=>(e=>"string"!=typeof e||Wt.test(e)?e:`"${e.replaceAll('"','\\"')}"`)(e)).join(" "))(e,t);((e,{verbose:t})=>{t&&b.stderr.write(`[${(()=>{const e=new Date;return`${Vt(e.getHours(),2)}:${Vt(e.getMinutes(),2)}:${Vt(e.getSeconds(),2)}.${Vt(e.getMilliseconds(),3)}`})()}] ${e}\n`)})(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),T(t)))(e);if(null!==(n=t)&&"object"==typeof n&&"function"==typeof n.pipe)throw new TypeError("The `input` option cannot be a stream in sync mode");var n;return t})(r.options);let a;try{a=p.spawnSync(r.file,r.args,{...r.options,input:i})}catch(e){throw Pt({error:e,stdout:"",stderr:"",all:"",command:o,escapedCommand:s,parsed:r,timedOut:!1,isCanceled:!1,killed:!1})}const c=Kt(r.options,a.stdout,a.error),l=Kt(r.options,a.stderr,a.error);if(a.error||0!==a.status||null!==a.signal){const e=Pt({stdout:c,stderr:l,error:a.error,signal:a.signal,exitCode:a.status,command: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 Jt(e){try{return qt("git",["rev-parse","HEAD"],e).stdout}catch{return}}function Qt(e){try{const t=qt("git",["rev-parse","--abbrev-ref","HEAD"],e).stdout;if("HEAD"===t){const t=qt("git",["show","-s","--pretty=%d","HEAD"],e).stdout.replace(/^\(|\)$/g,"").split(", ").find(e=>e.startsWith("origin/"));return t?t.match(/^origin\/(?<branch>.+)/)[1]:void 0}return t}catch{return}}var Xt=/^(?:.*)@(?:.*):(?:\d+\/)?(.*)\.git$/,Zt=/^\/(.*)\.git$/;function en(e){if(e){if(e.match(Xt))return e.replace(Xt,"$1");try{return new URL(e).pathname.replace(Zt,"$1")}catch{return}}}var tn,nn={detect:({env:e})=>Boolean(e.BUILDKITE),configuration({env:e}){const t="false"===e.BUILDKITE_PULL_REQUEST?void 0:e.BUILDKITE_PULL_REQUEST,n=Boolean(t);return{name:"Buildkite",service:"buildkite",build:e.BUILDKITE_BUILD_NUMBER,buildUrl:e.BUILDKITE_BUILD_URL,commit:e.BUILDKITE_COMMIT,tag:e.BUILDKITE_TAG,branch:n?e.BUILDKITE_PULL_REQUEST_BASE_BRANCH:e.BUILDKITE_BRANCH,slug:en(e.BUILDKITE_REPO),pr:t,isPr:n,prBranch:n?e.BUILDKITE_BRANCH:void 0,root:e.BUILDKITE_BUILD_CHECKOUT_PATH}}},rn={detect:({env:e})=>Boolean(e.CIRCLECI),configuration({env:e}){const t=e.CIRCLE_PR_NUMBER||je(e.CIRCLE_PULL_REQUEST||e.CI_PULL_REQUEST),n=Boolean(t);return{name:"CircleCI",service:"circleci",build:e.CIRCLE_BUILD_NUM,buildUrl:e.CIRCLE_BUILD_URL,job:`${e.CIRCLE_BUILD_NUM}.${e.CIRCLE_NODE_INDEX}`,commit:e.CIRCLE_SHA1,tag:e.CIRCLE_TAG,branch:n?void 0:e.CIRCLE_BRANCH,pr:t,isPr:n,prBranch:n?e.CIRCLE_BRANCH:void 0,slug:`${e.CIRCLE_PROJECT_USERNAME}/${e.CIRCLE_PROJECT_REPONAME}`}}},on="https://cirrus-ci.com",sn={detect:({env:e})=>Boolean(e.CIRRUS_CI),configuration({env:e}){const t=e.CIRRUS_PR,n=Boolean(t);return{name:"Cirrus CI",service:"cirrus",commit:e.CIRRUS_CHANGE_IN_REPO,tag:e.CIRRUS_TAG,build:e.CIRRUS_BUILD_ID,buildUrl:`${on}/build/${e.CIRRUS_BUILD_ID}`,job:e.CIRRUS_TASK_ID,jobUrl:`${on}/task/${e.CIRRUS_TASK_ID}`,branch:n?e.CIRRUS_BASE_BRANCH:e.CIRRUS_BRANCH,pr:t,isPr:n,prBranch:n?e.CIRRUS_BRANCH:void 0,slug:e.CIRRUS_REPO_FULL_NAME,root:e.CIRRUS_WORKING_DIR}}},an={detect:({env:e})=>Boolean(e.CODEBUILD_BUILD_ID),configuration:({env:e,cwd:t})=>({name:"AWS CodeBuild",service:"codebuild",commit:Jt({env:e,cwd:t}),build:e.CODEBUILD_BUILD_ID,branch:Qt({env:e,cwd:t}),buildUrl:`https://console.aws.amazon.com/codebuild/home?region=${e.AWS_REGION}#/builds/${e.CODEBUILD_BUILD_ID}/view/new`,root:e.PWD})},cn={detect:({env:e})=>Boolean(e.CF_BUILD_ID),configuration({env:e}){const t=e.CF_PULL_REQUEST_NUMBER,n=Boolean(t);return{name:"Codefresh",service:"codefresh",commit:e.CF_REVISION,build:e.CF_BUILD_ID,buildUrl:e.CF_BUILD_URL,branch:n?e.CF_PULL_REQUEST_TARGET:e.CF_BRANCH,pr:t,isPr:n,prBranch:n?e.CF_BRANCH:void 0,slug:`${e.CF_REPO_OWNER}/${e.CF_REPO_NAME}`,root:e.CF_VOLUME_PATH}}},ln={detect:({env:e})=>Boolean(e.DRONE),configuration({env:e}){const t="pull_request"===e.DRONE_BUILD_EVENT;return{name:"Drone",service:"drone",commit:e.DRONE_COMMIT_SHA,tag:e.DRONE_TAG,build:e.DRONE_BUILD_NUMBER,buildUrl:e.DRONE_BUILD_LINK,branch:t?e.DRONE_TARGET_BRANCH:e.DRONE_BRANCH,job:e.DRONE_JOB_NUMBER,jobUrl:e.DRONE_BUILD_LINK,pr:e.DRONE_PULL_REQUEST,isPr:t,prBranch:t?e.DRONE_SOURCE_BRANCH:void 0,slug:`${e.DRONE_REPO_OWNER}/${e.DRONE_REPO_NAME}`,root:e.DRONE_WORKSPACE}}},un=({env:e})=>{try{const t=e.GITHUB_EVENT_PATH?JSON.parse(T(e.GITHUB_EVENT_PATH,"utf-8")):void 0;if(t&&t.pull_request)return{branch:t.pull_request.base?Me(t.pull_request.base.ref):void 0,pr:t.pull_request.number}}catch{}return{pr:void 0,branch:void 0}},dn={detect:({env:e})=>Boolean(e.GITHUB_ACTIONS),configuration({env:e,cwd:t}){const n="pull_request"===e.GITHUB_EVENT_NAME||"pull_request_target"===e.GITHUB_EVENT_NAME,r=Me("pull_request_target"===e.GITHUB_EVENT_NAME?`refs/pull/${(e=>{const t=e.GITHUB_EVENT_PATH?JSON.parse(T(e.GITHUB_EVENT_PATH,"utf-8")):void 0;return t&&t.pull_request?t.pull_request.number:void 0})(e)}/merge`:e.GITHUB_REF);return{name:"GitHub Actions",service:"github",commit:e.GITHUB_SHA,build:e.GITHUB_RUN_ID,buildUrl:`${e.GITHUB_SERVER_URL}/${e.GITHUB_REPOSITORY}/actions/runs/${e.GITHUB_RUN_ID}`,isPr:n,branch:r,prBranch:n?r:void 0,slug:e.GITHUB_REPOSITORY,root:e.GITHUB_WORKSPACE,...n?un({env:e}):void 0}}},pn={detect:({env:e})=>Boolean(e.GITLAB_CI),configuration({env:e}){const t=e.CI_MERGE_REQUEST_ID,n=Boolean(t);return{name:"GitLab CI/CD",service:"gitlab",commit:e.CI_COMMIT_SHA,tag:e.CI_COMMIT_TAG,build:e.CI_PIPELINE_ID,buildUrl:`${e.CI_PROJECT_URL}/pipelines/${e.CI_PIPELINE_ID}`,job:e.CI_JOB_ID,jobUrl:`${e.CI_PROJECT_URL}/-/jobs/${e.CI_JOB_ID}`,branch:n?e.CI_MERGE_REQUEST_TARGET_BRANCH_NAME:e.CI_COMMIT_REF_NAME,pr:t,isPr:n,prBranch:e.CI_MERGE_REQUEST_SOURCE_BRANCH_NAME,slug:e.CI_PROJECT_PATH,root:e.CI_PROJECT_DIR}}},fn={detect:({env:e})=>Boolean(e.JENKINS_URL),configuration({env:e,cwd:t}){const n=e.ghprbPullId||e.gitlabMergeRequestId||e.CHANGE_ID,r=Boolean(n),o=e.GIT_LOCAL_BRANCH||e.GIT_BRANCH||e.gitlabBranch||e.BRANCH_NAME;return{name:"Jenkins",service:"jenkins",commit:e.ghprbActualCommit||e.GIT_COMMIT||Jt({env:e,cwd:t}),branch:r?e.ghprbTargetBranch||e.gitlabTargetBranch: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}}},hn={detect:({env:e})=>"true"===e.NETLIFY,configuration({env:e}){const t="true"===e.PULL_REQUEST;return{name:"Netlify",service:"netlify",commit:e.COMMIT_REF,build:e.DEPLOY_ID,buildUrl:`https://app.netlify.com/sites/${e.SITE_NAME}/deploys/${e.DEPLOY_ID}`,branch:t?void 0:e.HEAD,pr:e.REVIEW_ID,isPr:t,prBranch:t?e.HEAD:void 0,slug:e.REPOSITORY_URL.match(/[^/:]+\/[^/]+?$/)[0],root:e.PWD}}},gn={detect:({env:e})=>Boolean(e.DISTELLI_APPNAME),configuration:({env:e})=>({name:"Puppet",service:"puppet",build:e.DISTELLI_BUILDNUM,buildUrl:e.DISTELLI_RELEASE,commit:e.DISTELLI_RELREVISION,branch:e.DISTELLI_RELBRANCH,root:e.DISTELLI_INSTALLHOME})},mn={detect:({env:e})=>Boolean(e.SAILCI),configuration({env:e}){const t=e.SAIL_PULL_REQUEST_NUMBER,n=Boolean(t);return{name:"Sail CI",service:"sail",commit:e.SAIL_COMMIT_SHA,branch:n?void 0:e.SAIL_COMMIT_BRANCH,pr:t,isPr:n,slug:`${e.SAIL_REPO_OWNER}/${e.SAIL_REPO_NAME}`,root:e.SAIL_CLONE_DIR}}},yn={detect:({env:e})=>Boolean(e.SCREWDRIVER),configuration({env:e}){const t=e.SD_PULL_REQUEST,n=Boolean(t);return{name:"Screwdriver.cd",service:"screwdriver",branch:n?e.PR_BASE_BRANCH_NAME:e.GIT_BRANCH,prBranch:n?e.PR_BRANCH_NAME:void 0,commit:e.SD_BUILD_SHA,build:e.SD_BUILD_ID,buildUrl:e.SD_UI_BUILD_URL,job:e.SD_JOB_ID,pr:t,isPr:n,slug:e.SD_PIPELINE_NAME,root:e.SD_ROOT_DIR}}},bn={detect:({env:e})=>Boolean(e.SCRUTINIZER),configuration({env:e}){const t=e.SCRUTINIZER_PR_NUMBER,n=Boolean(t);return{name:"Scrutinizer",service:"scrutinizer",commit:e.SCRUTINIZER_SHA1,build:e.SCRUTINIZER_INSPECTION_UUID,branch:e.SCRUTINIZER_BRANCH,pr:t,isPr:n,prBranch:e.SCRUTINIZER_PR_SOURCE_BRANCH}}},wn={detect:({env:e})=>Boolean(e.SEMAPHORE),configuration({env:e,cwd:t}){const n=e.SEMAPHORE_GIT_PR_NUMBER||e.PULL_REQUEST_NUMBER,r=Boolean(n);return{name:"Semaphore",service:"semaphore",commit:e.SEMAPHORE_GIT_SHA||Jt({env:e,cwd:t}),tag:e.SEMAPHORE_GIT_TAG_NAME,build:e.SEMAPHORE_JOB_ID||e.SEMAPHORE_BUILD_NUMBER,branch:e.SEMAPHORE_GIT_BRANCH||(r?void 0:e.BRANCH_NAME),pr:n,isPr:r,prBranch:e.SEMAPHORE_GIT_PR_BRANCH||(r?e.BRANCH_NAME:void 0),slug:e.SEMAPHORE_GIT_REPO_SLUG||e.SEMAPHORE_REPO_SLUG,root:e.SEMAPHORE_GIT_DIR||e.SEMAPHORE_PROJECT_DIR}}},vn={detect:({env:e})=>Boolean(e.SHIPPABLE),configuration({env:e}){const t="true"===e.IS_PULL_REQUEST?e.PULL_REQUEST:void 0,n=Boolean(t);return{name:"Shippable",service:"shippable",commit:e.COMMIT,tag:e.GIT_TAG_NAME,build:e.BUILD_NUMBER,buildUrl:e.BUILD_URL,branch:n?e.BASE_BRANCH:e.BRANCH,job:e.JOB_NUMBER,pr:t,isPr:n,prBranch:n?e.HEAD_BRANCH:void 0,slug:e.SHIPPABLE_REPO_SLUG,root:e.SHIPPABLE_BUILD_DIR}}},_n={};function In(){if(tn)return _n;tn=1,Object.defineProperty(_n,"__esModule",{value:!0}),_n.of=_n.PropertiesFile=void 0;var e,t=(e=v)&&e.__esModule?e:{default:e};class n{constructor(...e){this.objs={},e.length&&this.of.apply(this,e)}makeKeys(e){if(e&&0!==e.indexOf("#")){let t=["=",":"].map(t=>e.indexOf(t)).filter(e=>e>-1),n=Math.min(...t),r=e.substring(0,n).trim(),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 _n.PropertiesFile=n,_n.of=function(...e){let t=new n;return t.of.apply(t,e),t},_n}var Tn=ze(In()),En={root:"teamcity.build.workingDir",branch:"teamcity.build.branch"},Sn=e=>{try{return Tn.of(e)}catch{return}},xn=({env:e,cwd:t})=>{const n=e.TEAMCITY_BUILD_PROPERTIES_FILE?Sn(e.TEAMCITY_BUILD_PROPERTIES_FILE):void 0,r=n?n.get("teamcity.configuration.properties.file"):void 0,o=r?Sn(r):r;return Object.fromEntries(Object.keys(En).map(r=>[r,(n?n.get(En[r]):void 0)||(o?o.get(En[r]):void 0)||("branch"===r?Qt({env:e,cwd:t}):void 0)]))},An={appveyor:Be,azurePipelines:Fe,bamboo:He,bitbucket:Ge,bitrise:We,buddy:Ye,buildkite:nn,circleci:rn,cirrus:sn,cloudflarePages:{detect:({env:e})=>"1"===e.CF_PAGES,configuration:({env:e})=>({name:"Cloudflare Pages",service:"cloudflarePages",commit:e.CF_PAGES_COMMIT_SHA,branch:e.CF_PAGES_BRANCH,root:e.PWD})},codebuild:an,codefresh:cn,codeship:{detect:({env:e})=>e.CI_NAME&&"codeship"===e.CI_NAME,configuration:({env:e})=>({name:"Codeship",service:"codeship",build:e.CI_BUILD_NUMBER,buildUrl:e.CI_BUILD_URL,commit:e.CI_COMMIT_ID,branch:e.CI_BRANCH,slug:e.CI_REPO_NAME})},drone:ln,github:dn,gitlab:pn,jenkins:fn,netlify:hn,puppet:gn,sail:mn,screwdriver:yn,scrutinizer:bn,semaphore:wn,shippable:vn,teamcity:{detect:({env:e})=>Boolean(e.TEAMCITY_VERSION),configuration:({env:e,cwd:t})=>({name:"TeamCity",service:"teamcity",commit:e.BUILD_VCS_NUMBER,build:e.BUILD_NUMBER,slug:e.TEAMCITY_BUILDCONF_NAME,...xn({env:e,cwd:t})})},travis:{detect:({env:e})=>Boolean(e.TRAVIS),configuration({env:e}){const t="false"===e.TRAVIS_PULL_REQUEST?void 0:e.TRAVIS_PULL_REQUEST,n=Boolean(t);return{name:"Travis CI",service:"travis",commit:e.TRAVIS_COMMIT,tag:e.TRAVIS_TAG,build:e.TRAVIS_BUILD_NUMBER,buildUrl:e.TRAVIS_BUILD_WEB_URL,branch:e.TRAVIS_BRANCH,job:e.TRAVIS_JOB_NUMBER,jobUrl:e.TRAVIS_JOB_WEB_URL,pr:t,isPr:n,prBranch:e.TRAVIS_PULL_REQUEST_BRANCH,slug:e.TRAVIS_REPO_SLUG,root:e.TRAVIS_BUILD_DIR}}},vela:{detect:({env:e})=>Boolean(e.VELA),configuration({env:e}){const t="pull_request"===e.VELA_BUILD_EVENT;return{name:"Vela",service:"vela",branch:t?e.VELA_PULL_REQUEST_TARGET:e.VELA_BUILD_BRANCH,commit:e.VELA_BUILD_COMMIT,tag:e.VELA_BUILD_TAG,build:e.VELA_BUILD_NUMBER,buildUrl:e.VELA_BUILD_LINK,job:void 0,jobUrl:void 0,isPr:t,pr:e.VELA_BUILD_PULL_REQUEST,prBranch:e.VELA_PULL_REQUEST_SOURCE,slug:e.VELA_REPO_FULL_NAME,root:e.VELA_BUILD_WORKSPACE}}},vercel:{detect:({env:e})=>Boolean(e.VERCEL)||Boolean(e.NOW_GITHUB_DEPLOYMENT),configuration({env:e}){const t="Vercel",n="vercel";return e.VERCEL?{name:t,service:n,commit:e.VERCEL_GIT_COMMIT_SHA,branch:e.VERCEL_GIT_COMMIT_REF,slug:`${e.VERCEL_GIT_REPO_OWNER}/${e.VERCEL_GIT_REPO_SLUG}`}:{name:t,service:n,commit:e.NOW_GITHUB_COMMIT_SHA,branch:e.NOW_GITHUB_COMMIT_REF,slug:`${e.NOW_GITHUB_ORG}/${e.NOW_GITHUB_REPO}`}}},wercker:{detect:({env:e})=>Boolean(e.WERCKER_MAIN_PIPELINE_STARTED),configuration:({env:e})=>({name:"Wercker",service:"wercker",commit:e.WERCKER_GIT_COMMIT,build:e.WERCKER_MAIN_PIPELINE_STARTED,buildUrl:e.WERCKER_RUN_URL,branch:e.WERCKER_GIT_BRANCH,slug:`${e.WERCKER_GIT_OWNER}/${e.WERCKER_GIT_REPOSITORY}`,root:e.WERCKER_ROOT})},woodpecker:{detect:({env:e})=>e.CI&&"woodpecker"===e.CI,configuration({env:e}){const t="pull_request"===e.CI_PIPELINE_EVENT;return{name:"Woodpecker CI",service:"woodpecker",commit:e.CI_COMMIT_SHA,tag:e.CI_COMMIT_TAG,build:e.CI_PIPELINE_NUMBER,buildUrl:e.CI_PIPELINE_URL,branch:t?e.CI_COMMIT_TARGET_BRANCH:e.CI_COMMIT_BRANCH,job:e.CI_STEP_NUMBER,jobUrl:e.CI_STEP_URL,pr:e.CI_COMMIT_PULL_REQUEST,isPr:t,prBranch:t?e.CI_COMMIT_SOURCE_BRANCH:void 0,slug:`${e.CI_REPO_OWNER}/${e.CI_REPO_NAME}`,root:e.CI_WORKSPACE}}},jetbrainsSpace:{detect:({env:e})=>Boolean(e.JB_SPACE_EXECUTION_NUMBER),configuration({env:e}){const t=e.JB_SPACE_PROJECT_KEY,n=e.JB_SPACE_GIT_REPOSITORY_NAME;return{name:"JetBrains Space",service:"jetbrainsSpace",commit:e.JB_SPACE_GIT_REVISION,build:e.JB_SPACE_EXECUTION_NUMBER,branch:Me(e.JB_SPACE_GIT_BRANCH),slug:t&&n?`${t.toLowerCase()}/${n}`:void 0}}}},Cn=class e{git;config;snapshotTreeHash;snapshotIndexPath;constructor(e){this.config=e,this.git=J({baseDir:e.workingDir,maxConcurrentProcesses:1})}static createLocal({workingDir:t}){return new e({mode:"local",workingDir:t})}static createCloud({workingDir:t,baseBranch:n}){return new e({mode:"cloud",workingDir:t,baseBranch:n})}async captureSnapshot(){if("local"!==this.config.mode)return;this.snapshotIndexPath=i(O(),`git-diff-tracker-${X()}.index`),await this.git.env("GIT_INDEX_FILE",this.snapshotIndexPath).add(["-A"]);const e=await this.git.env("GIT_INDEX_FILE",this.snapshotIndexPath).raw(["write-tree"]);this.snapshotTreeHash=e.trim()}async computeDiff(){return"local"===this.config.mode?this.computeLocalDiff():this.computeCloudDiff()}async computeLocalDiff(){if(!this.snapshotTreeHash)throw new Error("No snapshot captured. Call captureSnapshot() first.");const e=i(O(),`git-diff-tracker-${X()}.index`);try{await this.git.env("GIT_INDEX_FILE",e).add(["-A"]);const t=(await this.git.env("GIT_INDEX_FILE",e).raw(["write-tree"])).trim();return await this.git.raw(["diff-tree","-p","--no-color",this.snapshotTreeHash,t])}finally{await Rn(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 Rn(this.snapshotIndexPath),this.snapshotIndexPath=void 0),this.snapshotTreeHash=void 0}};async function Rn(e){try{await ne(e)}catch{}}var Pn="x-stably-org-id",kn={bodySerializer:e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t)},Un=({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):Ln({allowReserved:e,name:n,value:t})).join(s);return"label"===r||"matrix"===r?s+i:i},Ln=({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)}`},Dn=({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])=>Ln({allowReserved:e,name:"deepObject"===r?`${n}[${t}]`:t,value:o})).join(i);return"label"===r||"matrix"===r?i+a:a},$n=/\{[^{}]+\}/g;function On(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 Nn,Bn=async(e,t)=>{const n="function"==typeof t?await t(e):t;if(n)return"bearer"===e.scheme?`Bearer ${n}`:"basic"===e.scheme?`Basic ${btoa(n)}`:n},jn=({parameters:e={},...t}={})=>n=>{const r=[];if(n&&"object"==typeof n)for(const o in n){const s=n[o];if(null==s)continue;const i=e[o]||t;if(Array.isArray(s)){const e=Un({allowReserved:i.allowReserved,explode:!0,name:o,style:"form",value:s,...i.array});e&&r.push(e)}else if("object"==typeof s){const e=Dn({allowReserved:i.allowReserved,explode:!0,name:o,style:"deepObject",value:s,...i.object});e&&r.push(e)}else{const e=Ln({allowReserved:i.allowReserved,name:o,value:s});e&&r.push(e)}}return r.join("&")},Mn=(e,t)=>!!t&&!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`)),Fn=e=>(({baseUrl:e,path:t,query:n,querySerializer:r,url:o})=>{let s=(e??"")+(o.startsWith("/")?o:`/${o}`);t&&(s=(({path:e,url:t})=>{let n=t;const r=t.match($n);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,Un({explode:r,name:o,style:s,value:i}));continue}if("object"==typeof i){n=n.replace(t,Dn({explode:r,name:o,style:s,value:i,valueOnly:!0}));continue}if("matrix"===s){n=n.replace(t,`;${Ln({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:jn(e.querySerializer),url:e.url}),Hn=(e,t)=>{const n={...e,...t};return n.baseUrl?.endsWith("/")&&(n.baseUrl=n.baseUrl.substring(0,n.baseUrl.length-1)),n.headers=Wn(e.headers,t.headers),n},Gn=e=>{const t=[];return e.forEach((e,n)=>{t.push([n,e])}),t},Wn=(...e)=>{const t=new Headers;for(const n of e){if(!n)continue;const e=n instanceof Headers?Gn(n):Object.entries(n);for(const[n,r]of e)if(null===r)t.delete(n);else if(Array.isArray(r))for(const e of r)t.append(n,e);else void 0!==r&&t.set(n,"object"==typeof r?JSON.stringify(r):r)}return t},Yn=class{fns=[];clear(){this.fns=[]}eject(e){const t=this.getInterceptorIndex(e);this.fns[t]&&(this.fns[t]=null)}exists(e){const t=this.getInterceptorIndex(e);return Boolean(this.fns[t])}getInterceptorIndex(e){return"number"==typeof e?this.fns[e]?e:-1:this.fns.indexOf(e)}update(e,t){const n=this.getInterceptorIndex(e);return!!this.fns[n]&&(this.fns[n]=t,e)}use(e){return this.fns.push(e),this.fns.length-1}},Vn=jn({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),zn={"Content-Type":"application/json"},Kn=(e={})=>({...kn,headers:zn,parseAs:"auto",querySerializer:Vn,...e}),qn=(e={})=>{let t=Hn(Kn(),e);const n=()=>({...t}),r={error:new Yn,request:new Yn,response:new Yn},o=async e=>{const n={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:Wn(t.headers,e.headers),serializedBody:void 0};return n.security&&await(async({security:e,...t})=>{for(const n of e){if(Mn(t,n.name))continue;const e=await Bn(n,t.auth);if(!e)continue;const r=n.name??"Authorization";switch(n.in){case"query":t.query||(t.query={}),t.query[r]=e;break;case"cookie":t.headers.append("Cookie",`${r}=${e}`);break;default:t.headers.set(r,e)}}})({...n,security:n.security}),n.requestValidator&&await n.requestValidator(n),void 0!==n.body&&n.bodySerializer&&(n.serializedBody=n.bodySerializer(n.body)),void 0!==n.body&&""!==n.serializedBody||n.headers.delete("Content-Type"),{opts:n,url:Fn(n)}},s=async e=>{const{opts:t,url:n}=await o(e),s={redirect:"follow",...t,body:On(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 g="";const m=()=>{try{f.cancel()}catch{}};h.addEventListener("abort",m);try{for(;;){const{done:e,value:t}=await f.read();if(e)break;g+=t;const s=g.split("\n\n");g=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",m),f.releaseLock()}break}catch(e){if(t?.(e),void 0!==i&&f>=i)break;const n=Math.min(c*2**(f-1),a??3e4);await p(n)}}}()}})({...n,body:n.body,headers:n.headers,method:e,onRequest:async(e,t)=>{let o=new Request(e,t);for(const e of r.request.fns)e&&(o=await e(o,n));return o},url:s})};return{buildUrl:Fn,connect:i("CONNECT"),delete:i("DELETE"),get:i("GET"),getConfig:n,head:i("HEAD"),interceptors:r,options:i("OPTIONS"),patch:i("PATCH"),post:i("POST"),put:i("PUT"),request:s,setConfig:e=>(t=Hn(t,e),n()),sse:{connect:a("CONNECT"),delete:a("DELETE"),get:a("GET"),head:a("HEAD"),options:a("OPTIONS"),patch:a("PATCH"),post:a("POST"),put:a("PUT"),trace:a("TRACE")},trace:i("TRACE")}},Jn=qn(Kn({baseUrl:"https://api.stably.ai"})),Qn=e=>(e.client??Jn).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs",...e}),Xn=e=>(e.client??Jn).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}",...e}),Zn="4.12.2",er=process.env.STABLY_API_URL||"https://api.stably.ai",tr=e=>{const t=new URL(e);return t.protocol="http:"===t.protocol?"ws:":"wss:",t},nr=process.env.AUTH_URL||"https://auth.stably.ai",rr=process.env.AUTH_CLIENT_ID||"288007877071cce81f269428ea78653a",or=process.env.AI_PROXY_URL||"https://ai-proxy.stably.ai",sr=process.env.STABLY_AUTOHEAL_WS_URL||new URL("/autoheal",tr(er)).toString(),ir=process.env.STABLY_CREATE_PROGRESS_WS_URL||new URL("/create-progress",tr(er)).toString(),ar="http://localhost:9876/auth/callback",cr=()=>Nn||(Nn=qn(Kn({baseUrl:er,headers:{"X-STABLY-CLI-VERSION":Zn,"X-STABLY-SOURCE":"cli"}}))),lr=async(e,t)=>{const n=await(r={body:{accessToken:e,orgId:t},client:cr()},(r.client??Jn).post({url:"/internal/v1/cli/exchange-token",...r,headers:{"Content-Type":"application/json",...r.headers}}));var r;if(401===n.response.status)throw new Error("Invalid or expired access token");if(403===n.response.status)throw new Error("You do not have access to this organization");if(n.error)throw new Error(`Failed to exchange token: ${n.response.status}`);return n.data},ur=ge.object({org_id:ge.string(),org_name:ge.string()}),dr=ge.object({email:ge.string(),org_id_to_org_member_info:ge.record(ge.string(),ur).optional(),org_member_info:ur.optional(),user_id:ge.string()});ge.object({email:ge.string(),firstName:ge.string().optional(),lastName:ge.string().optional(),organizations:ge.array(ge.object({id:ge.string(),name:ge.string()})),userId:ge.string()});var pr,fr=e=>{const t=e.split(".");if(3!==t.length)throw new Error("Invalid JWT format");const n=t[1].replace(/-/g,"+").replace(/_/g,"/"),r=Buffer.from(n,"base64").toString("utf-8");return JSON.parse(r)},hr=e=>{try{const t=dr.parse(fr(e)),n=t.org_id_to_org_member_info?Object.entries(t.org_id_to_org_member_info).map(([e,t])=>({id:e,name:t.org_name})):t.org_member_info?[{id:t.org_member_info.org_id,name:t.org_member_info.org_name}]:[];return{email:t.email,organizations:n,userId:t.user_id}}catch(e){throw new Error(`Failed to decode token: ${e instanceof Error?e.message:"Unknown error"}`)}},gr=async(e,t)=>{let n=e;const{root:o}=r.parse(n);for(;n!==o;){const e=r.join(n,t);try{return await re(e),e}catch{n=r.dirname(n)}}},mr=r.join($.homedir(),".stably"),yr=r.join(mr,"auth.json"),br=".stably",wr="project.json",vr=he.object({accessToken:he.string(),expiresAt:he.number(),idToken:he.string().optional(),refreshToken:he.string()}),_r=he.object({orgId:he.string(),orgName:he.string(),projectId:he.string(),projectName:he.string()}),Ir=async()=>{try{const e=await Z(yr,"utf-8");return vr.parse(JSON.parse(e))}catch{return}},Tr=async e=>{await ee(mr,{recursive:!0}),await te(yr,JSON.stringify(e,null,2),{mode:384})},Er=async()=>{try{await ne(yr)}catch{}},Sr=async()=>{try{const e=await gr(process.cwd(),br);if(!e)return;const t=r.join(e,wr),n=await Z(t,"utf-8");return _r.parse(JSON.parse(n))}catch{return}},xr=async()=>{try{const e=await gr(process.cwd(),br);e&&await ne(r.join(e,wr))}catch{}},Ar=e=>Date.now()>=e.expiresAt-3e5,Cr=async e=>{const t=new URLSearchParams({client_id:rr,grant_type:"refresh_token",refresh_token:e}),n=await fetch(`${nr}/propelauth/oauth/token`,{body:t.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},method:"POST"});if(!n.ok)throw new Error(`Token refresh failed: ${n.status}`);const r=await n.json();return{accessToken:r.access_token,expiresAt:Date.now()+1e3*r.expires_in,refreshToken:r.refresh_token}},Rr=e=>`\n<!DOCTYPE html>\n<html>\n<head>\n <title>Authentication Failed Stably CLI</title>\n <style>\n * { box-sizing: border-box; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n display: flex;\n justify-content: center;\n align-items: center;\n min-height: 100vh;\n margin: 0;\n background: #000;\n color: #fafafa;\n }\n .container {\n text-align: center;\n padding: 48px;\n max-width: 400px;\n }\n .icon {\n width: 48px;\n height: 48px;\n border-radius: 50%;\n background: #ef4444;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 24px;\n }\n .icon svg { width: 24px; height: 24px; }\n .title {\n font-size: 24px;\n font-weight: 600;\n margin: 0 0 8px;\n letter-spacing: -0.5px;\n }\n .subtitle {\n color: #888;\n font-size: 14px;\n margin: 0 0 32px;\n line-height: 1.5;\n }\n .error-box {\n background: rgba(239, 68, 68, 0.1);\n border: 1px solid rgba(239, 68, 68, 0.3);\n border-radius: 8px;\n padding: 16px;\n margin-bottom: 24px;\n }\n .error-label {\n font-size: 11px;\n font-weight: 600;\n color: #ef4444;\n text-transform: uppercase;\n letter-spacing: 0.5px;\n margin-bottom: 8px;\n }\n .error-message {\n font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace;\n font-size: 13px;\n color: #fafafa;\n word-break: break-word;\n }\n .hint {\n color: #666;\n font-size: 13px;\n }\n .hint code {\n background: #111;\n border: 1px solid #333;\n border-radius: 4px;\n padding: 2px 6px;\n font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace;\n font-size: 12px;\n color: #888;\n }\n .brand {\n margin-top: 32px;\n font-size: 12px;\n color: #444;\n letter-spacing: 0.5px;\n }\n </style>\n</head>\n<body>\n <div class="container">\n <div class="icon">\n <svg fill="none" stroke="#000" stroke-width="3" viewBox="0 0 24 24">\n <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/>\n </svg>\n </div>\n <h1 class="title">Authentication Failed</h1>\n <p class="subtitle">Something went wrong during login.</p>\n <div class="error-box">\n <div class="error-label">Error</div>\n <div class="error-message">${e}</div>\n </div>\n <p class="hint">Run <code>stably login</code> to try again.</p>\n <div class="brand">STABLY</div>\n </div>\n</body>\n</html>\n`,Pr=(e,t,n)=>{e.writeHead(t,{"Content-Type":"text/html"}),e.end(n)},kr=(e,t)=>{const n=new URLSearchParams({client_id:rr,code_challenge:e,code_challenge_method:"S256",redirect_uri:ar,response_type:"code",state:t});return`${nr}/propelauth/oauth/authorize?${n.toString()}`},Ur=async e=>{const t=ue();let n;t.start("Loading user info...");try{n=hr(e.accessToken),t.stop(q.green(`✓ Logged in as ${q.cyan(n.email)}`))}catch(e){t.stop(q.red("✗ Failed to load user info"));const n=e instanceof Error?e.message:"Unknown error";return ce.error(n),{success:!1}}const o=await(async e=>{if(0===e.length)return void ce.error("You don't belong to any organizations.");if(1===e.length)return ce.info(`Using organization: ${q.cyan(e[0].name)}`),e[0];if(!process.stdin.isTTY)return ce.info(`Auto-selecting organization: ${q.cyan(e[0].name)}`),e[0];const t=await pe({message:"Select an organization",options:[...e].sort((e,t)=>e.name.localeCompare(t.name)).map(e=>({label:e.name,value:e.id}))});return fe(t)?void 0:e.find(e=>e.id===t)})(n.organizations);if(!o)return ce.warn("Organization selection cancelled."),{success:!1};let s;t.start("Getting org credentials...");try{const n=await lr(e.accessToken,o.id);s={accessToken:n.accessToken,expiresAt:Date.now()+1e3*n.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken},t.stop(q.green("✓ Credentials obtained"))}catch(e){t.stop(q.red("✗ Failed to get org credentials"));const n=e instanceof Error?e.message:"Unknown error";return ce.error(n),{success:!1}}const i=await(async(e,t)=>{const n=ue();let r;n.start("Loading projects...");try{r=await(async({accessToken:e,orgId:t})=>{const n=await(r={auth:e,client:cr(),path:{orgId:t}},(r.client??Jn).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/orgs/{orgId}/projects",...r}));var r;if(401===n.response.status)throw new Error("Invalid or expired access token");if(403===n.response.status)throw new Error("You do not have access to this organization");if(n.error)throw new Error(`Failed to list projects: ${n.response.status}`);return n.data.projects})({accessToken:e,orgId:t}),n.stop(q.green("✓ Projects loaded"))}catch(e){n.stop(q.red("✗ Failed to load projects"));const t=e instanceof Error?e.message:"Unknown error";return void ce.error(t)}if(0===r.length)return ce.error("No projects found in this organization."),void ce.info(`Create a project at ${q.underline(q.cyan("https://app.stably.ai"))}`);if(1===r.length)return ce.info(`Using project: ${q.cyan(r[0].name)}`),r[0];if(!process.stdin.isTTY)return ce.info(`Auto-selecting project: ${q.cyan(r[0].name)}`),r[0];const o=await pe({message:"Select a project",options:r.map(e=>({label:e.name,value:e.id}))});return fe(o)?void 0:r.find(e=>e.id===o)})(s.accessToken,o.id);return i?(await(async e=>{const t=r.join(process.cwd(),br),n=r.join(t,wr);await ee(t,{recursive:!0}),await te(n,JSON.stringify(e,null,2)),await(async e=>{const t=r.join(e,".gitignore"),n="# Stably CLI (only docs/ are tracked)\n.stably/*\n!.stably/docs/";try{const e=await Z(t,"utf-8"),r=e.split("\n").map(e=>e.trim());if(r.includes(".stably/*")&&r.includes("!.stably/docs/"))return;const o=/^# Stably CLI\n\.stably\/?$/m,s=/^\.stably\/?$/m;if(o.test(e)){const r=e.replace(o,`\n${n}\n`);await te(t,r)}else if(s.test(e)){const r=e.replace(s,`\n${n}\n`);await te(t,r)}else await ae(t,`\n${n}\n`)}catch{await te(t,`${n}\n`)}})(process.cwd())})({orgId:o.id,orgName:o.name,projectId:i.id,projectName:i.name}),ce.info(q.dim("Linked this directory to your Stably project.")),{scopedTokens:s,success:!0}):(ce.warn("Project selection cancelled."),{success:!1})},Lr=async()=>{if(Xr())return ce.warn(`Environment variables ${q.cyan("STABLY_API_KEY")} and ${q.cyan("STABLY_PROJECT_ID")} are set.`),ce.warn("These will be used for authentication instead of OAuth login."),ce.warn("To use OAuth login, unset these environment variables first."),void le(q.yellow("Login skipped - using environment variable authentication."));const e=await Ir();if(e){if(!Ar(e)){if(await Sr())return void le(q.yellow("You are already logged in. Run `stably logout` first to log out."));ce.info("You are logged in but haven't selected a project yet.");const t=await Ur(e);return void(t.success?(await Tr(t.scopedTokens),le(q.green("Setup complete! You can now use Stably CLI."))):le(q.yellow("Setup incomplete. Run `stably login` to try again.")))}const t=ue();t.start("Refreshing session...");try{const n=await Cr(e.refreshToken);t.stop(q.green("✓ Session refreshed"));const r=await Sr();if(r){t.start("Getting org credentials...");try{const e=await lr(n.accessToken,r.orgId),o={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:n.idToken,refreshToken:n.refreshToken};await Tr(o),t.stop(q.green("✓ Credentials obtained")),le(q.green("Login successful"))}catch{await Tr(n),t.stop(q.yellow("Using full credentials")),le(q.green("Login successful"))}}else{const e=await Ur(n);e.success?(await Tr(e.scopedTokens),le(q.green("Setup complete! You can now use Stably CLI."))):le(q.yellow("Setup incomplete. Run `stably login` to try again."))}return}catch{t.stop(q.yellow("Session expired, proceeding with fresh login...")),await Er(),await xr()}}const{authorizeUrl:t,serverReady:n,waitForCallback:r}=(()=>{const{authorizeUrl:e,codeVerifier:t,state:n}=(()=>{const e=Q.randomBytes(32).toString("base64url"),t=(n=e,Q.createHash("sha256").update(n).digest("base64url"));var n;const r=Q.randomBytes(16).toString("base64url");return{authorizeUrl:kr(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=ye.createServer((t,n)=>{const o=new D(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?(Pr(n,400,Rr(l)),i(),a.close(),void r({error:l,success:!1})):s&&c?c!==e?(Pr(n,400,Rr("Invalid state parameter (possible CSRF attack)")),i(),a.close(),void r({error:"State mismatch",success:!1})):(Pr(n,200,'\n<!DOCTYPE html>\n<html>\n<head>\n <title>Authenticated Stably CLI</title>\n <style>\n * { box-sizing: border-box; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, sans-serif;\n display: flex;\n justify-content: center;\n align-items: center;\n min-height: 100vh;\n margin: 0;\n background: #000;\n color: #fafafa;\n }\n .container {\n text-align: center;\n padding: 48px;\n max-width: 400px;\n }\n .icon {\n width: 48px;\n height: 48px;\n border-radius: 50%;\n background: #22c55e;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 24px;\n }\n .icon svg { width: 24px; height: 24px; }\n .title {\n font-size: 24px;\n font-weight: 600;\n margin: 0 0 8px;\n letter-spacing: -0.5px;\n }\n .subtitle {\n color: #888;\n font-size: 14px;\n margin: 0 0 32px;\n line-height: 1.5;\n }\n .terminal {\n background: #111;\n border: 1px solid #333;\n border-radius: 8px;\n padding: 16px;\n text-align: left;\n font-family: \'SF Mono\', \'Fira Code\', \'Consolas\', monospace;\n font-size: 13px;\n }\n .terminal-header {\n display: flex;\n gap: 6px;\n margin-bottom: 12px;\n }\n .terminal-dot {\n width: 10px;\n height: 10px;\n border-radius: 50%;\n background: #333;\n }\n .terminal-line {\n color: #888;\n }\n .terminal-line .prompt { color: #888; }\n .terminal-line .cmd { color: #fafafa; }\n .terminal-line.success { color: #22c55e; }\n .brand {\n margin-top: 32px;\n font-size: 12px;\n color: #444;\n letter-spacing: 0.5px;\n }\n </style>\n</head>\n<body>\n <div class="container">\n <div class="icon">\n <svg fill="none" stroke="#000" stroke-width="3" viewBox="0 0 24 24">\n <path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/>\n </svg>\n </div>\n <h1 class="title">Authenticated</h1>\n <p class="subtitle">You can close this tab and return to your terminal.</p>\n <div class="terminal">\n <div class="terminal-header">\n <div class="terminal-dot"></div>\n <div class="terminal-dot"></div>\n <div class="terminal-dot"></div>\n </div>\n <div class="terminal-line"><span class="prompt">$</span> <span class="cmd">stably login</span></div>\n <div class="terminal-line success">Logged in successfully</div>\n </div>\n <div class="brand">STABLY</div>\n </div>\n</body>\n</html>\n'),i(),a.close(),void r({code:s,state:c,success:!0})):(Pr(n,400,Rr("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:rr,code:e,code_verifier:t,grant_type:"authorization_code",redirect_uri:ar}),r=await fetch(`${nr}/propelauth/oauth/token`,{body:n.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},method:"POST"});if(!r.ok){const e=await r.text();throw new Error(`Token exchange failed: ${r.status} ${e}`)}const 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,ce.info("Opening browser for authentication..."),ce.info(q.dim("If browser doesn't open, visit:")),ce.info(`]8;;${t}${q.underline(q.cyan(t))}]8;;`);try{await me(t)}catch{ce.warn("Could not open browser automatically. Please open the URL above manually.")}const o=ue();let s;o.start("Waiting for authentication...");try{s=await r(),o.stop(q.green("✓ Authentication successful"))}catch(e){o.stop(q.red("✗ Authentication failed"));const t=e instanceof Error?e.message:"Unknown error";le(q.red(`Login failed: ${t}`)),process.exit(1)}const i=await Ur(s);i.success?(await Tr(i.scopedTokens),le(q.green("Setup complete! You can now use Stably CLI."))):(le(q.yellow("Setup incomplete. Run `stably login` to try again.")),process.exit(1))},Dr={fatal:60,error:50,warn:40,info:30,debug:20,trace:10},$r=new Set(["help","login","logout","whoami","tunnel","create","fix","init","upgrade","test","show-report","codegen"]),Or=(new Date).toISOString().split("T")[0],Nr=(()=>{const e=[r.join($.tmpdir(),"stably-logs",Or),r.join($.homedir(),".stably","logs",Or)];for(const t of e)try{return v.mkdirSync(t,{recursive:!0}),t}catch{}return null})(),Br=process.argv.includes("--verbose")||process.argv.includes("-v"),jr=process.env.STABLY_LOG_LEVEL?.toLowerCase(),Mr=Br?"debug":void 0!==(pr=jr)&&pr in Dr?jr:"warn",Fr=Dr[Mr],Hr=null,Gr=null,Wr=null,Yr=[],Vr=!1,zr=e=>{if(!Vr){if(!(Hr=(e=>{if(!Nr)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(Nr,`${t}-${n}.log`)})(e)))return Yr=[],void(Vr=!0);(e=>{const t=["","=".repeat(60),"Stably CLI Debug Log",`Version: ${Zn}`,`Generated: ${(new Date).toISOString()}`,`Node: ${process.version}`,`Platform: ${process.platform} ${$.release()}`,`CWD: ${process.cwd()}`,`Args: ${process.argv.slice(2).join(" ")}`,`Log Level (console): ${Mr}`,"=".repeat(60),""].join("\n");e.write(t)})(Gr=new we({dest:Hr,minLength:4096,sync:!1,append:!0})),Wr=be({level:"debug",timestamp:be.stdTimeFunctions.isoTime,base:{version:Zn}},Gr);for(const{level:e,msg:t,context:n}of Yr)n?Wr[e](n,t):Wr[e](t);Yr=[],Vr=!0,Br&&process.stderr.write(`${q.dim(`Debug log: ${Hr}`)}\n\n`)}},Kr=(()=>{const e=process.argv.slice(2).find(e=>!e.startsWith("-"));return e&&$r.has(e)?e:null})();Kr&&zr(Kr);var qr=e=>(t,n)=>{if(Wr?n?Wr[e](n,t):Wr[e](t):Vr||Yr.push({level:e,msg:t,context:n}),(e=>Dr[e]>=Fr)(e)){const n=((e,t)=>`${{fatal:q.bgRed(q.white(" FATAL ")),error:q.red("error"),warn:q.yellow("warn"),info:q.cyan("info"),debug:q.dim("debug"),trace:q.dim("trace")}[e]} ${t}`)(e,t);process.stderr.write(`${n}\n`)}},Jr={fatal:qr("fatal"),error:qr("error"),warn:qr("warn"),info:qr("info"),debug:qr("debug"),trace:qr("trace"),initSession:e=>{Vr||zr(e)},getLogFilePath:()=>Hr,flush:()=>{if(Gr)try{Gr.flushSync()}catch{}},printLogFileInfo:()=>{Hr&&(process.stderr.write(`\n${q.dim("Debug log written to:")}\n`),process.stderr.write(` ${q.cyan(Hr)}\n`),process.stderr.write(`${q.dim("Share this file with support for assistance.")}\n`))},getPinoLogger:()=>Wr};setInterval(()=>{Jr.flush()},3e4).unref(),process.on("beforeExit",()=>{Jr.flush()});var Qr=e=>{const t=()=>{Jr.flush(),Br&&Jr.printLogFileInfo(),process.removeListener(e,t),process.kill(process.pid,e)};return t};process.on("SIGINT",Qr("SIGINT")),process.on("SIGTERM",Qr("SIGTERM"));var Xr=()=>{const e=process.env.STABLY_API_KEY?.trim(),t=process.env.STABLY_PROJECT_ID?.trim();if(e&&t)return Jr.debug("Environment auth detected",{hasApiKey:!0,hasProjectId:!0}),{apiKey:e,projectId:t};Jr.debug("Environment auth not set",{hasApiKey:!!e,hasProjectId:!!t})},Zr=async()=>{Jr.debug("Checking for stored auth tokens");const e=await Ir();if(!e)return void Jr.debug("No stored auth tokens found");const t=Ar(e);if(Jr.debug("Auth tokens status",{expired:t}),!t){const t=await Sr(),n=(e=>{try{const t=dr.parse(fr(e));if(t.org_id_to_org_member_info)return"full";if(t.org_member_info)return"org"}catch{return"unknown"}return"unknown"})(e.accessToken);if(Jr.debug("Token scope check",{scope:n,hasContext:!!t}),t&&"full"===n)try{Jr.debug("Exchanging full token for org-scoped token",{orgId:t.orgId});const n=await lr(e.accessToken,t.orgId),r={accessToken:n.accessToken,expiresAt:Date.now()+1e3*n.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken};return await Tr(r),Jr.debug("Token exchange successful"),r}catch(t){return Jr.debug("Token exchange failed, using existing token",{error:t instanceof Error?t.message:String(t)}),e}return e}try{Jr.debug("Attempting token refresh");const t=await Cr(e.refreshToken);Jr.debug("Token refresh successful");const n=await Sr();if(n)try{Jr.debug("Exchanging refreshed token for org-scoped token");const e=await lr(t.accessToken,n.orgId),r={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:t.idToken,refreshToken:t.refreshToken};return await Tr(r),r}catch{return await Tr(t),t}return await Tr(t),t}catch(e){return void Jr.warn("Token refresh failed",{error:e instanceof Error?e.message:String(e)})}},eo=async(e={})=>{Jr.debug("Requiring authentication",{autoLogin:e.autoLogin});const t=Xr();if(t)return Jr.info("Using environment variable authentication"),{auth:t,type:"env"};let n=await Zr(),r=n?await Sr():void 0;const o=process.stdin.isTTY&&process.stdout.isTTY;if(Jr.debug("OAuth auth check",{hasTokens:!!n,hasContext:!!r,canPrompt:o}),(!n||!r)&&e.autoLogin&&o){Jr.info("Prompting user to login"),n?ce.info("You are logged in but need to select an organization and project."):ce.info("You are not logged in."),ce.info("Press Enter to log in."),process.stdout.write(`${q.dim("Alternatively, set environment variables for an org API key:")}\n${q.dim(" STABLY_API_KEY=... STABLY_PROJECT_ID=... stably")}\n`),process.stdout.write("\n");const e=K({input:process.stdin,output:process.stdout});try{await e.question(q.dim("Press Enter to continue... "))}finally{e.close()}await Lr(),n=await Zr(),r=n?await Sr():void 0}return n||(Jr.warn("Authentication required but no tokens available"),le(q.red("You are not logged in. Run `stably login` to authenticate.")),process.exit(1)),r||(Jr.warn("Authentication succeeded but no project context selected"),le(q.red("You haven't selected an organization and project. Run `stably login` to complete setup.")),process.exit(1)),Jr.info("OAuth authentication successful",{orgId:r.orgId,projectId:r.projectId}),{auth:{accessToken:n.accessToken,context:r},type:"oauth"}},to=e=>"env"===e.type?e.auth.projectId:e.auth.context.projectId,no=e=>"env"===e.type?e.auth.apiKey:e.auth.accessToken,ro=async()=>{const e=Le.remoteEnvName;if(!e)return;const t=await eo(),n=to(t),r=no(t);Jr.debug("Fetching remote environment variables",{envName:e,projectId:n});const o=await(s={auth:r,client:cr(),path:{projectId:n,environment:e}},(s.client??Jn).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/environments/{environment}/variables",...s}));var s;404===o.response.status&&(le(q.red(`Environment "${e}" not found. Check the name on your Stably dashboard.`)),process.exit(1)),401!==o.response.status&&403!==o.response.status||(le(q.red(`Access denied to environment "${e}".`)),process.exit(1)),o.error&&(le(q.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(`${q.cyan(`Loaded ${c} variable${1!==c?"s":""} from "${e}"`)}${l>0?q.dim(` (${l} sensitive)`):""}\n`),{variables:i,sensitiveValues:a}},oo=e=>e?{[Pn]:e}:void 0,so=ge.object({context:ge.string().min(1),autohealReportUrl:ge.string(),skippedTests:ge.array(ge.object({testIdentifier:ge.string(),testTitle:ge.string(),consecutiveUnfixedCount:ge.number()})).optional()}),io=ve.object({bucket:ve.string(),key:ve.string()}),ao=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})`)},co=ve.object({diffBucketPath:io,expiresInSeconds:ve.number(),key:ve.string(),uploadUrl:ve.string()}),lo=ve.object({traceBucketPath:io,expiresInSeconds:ve.number(),key:ve.string(),uploadUrl:ve.string(),sensitiveValues:ve.array(ve.string())}),uo=async({authHeader:e,contentType:t="text/plain",orgId:n,runId:r})=>{const o=await(s={auth:e,body:{contentType:t},client:cr(),headers:oo(n),path:{runId:r}},(s.client??Jn).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=co.parse(o.data);return{diffBucketPath:i.diffBucketPath,expiresInSeconds:i.expiresInSeconds,key:i.key,uploadUrl:i.uploadUrl}},po=async({authHeader:e,diffBucketPath:t,orgId:n,runId:r})=>{const o=await(s={auth:e,body:t,client:cr(),headers:oo(n),path:{runId:r}},(s.client??Jn).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})`)},fo=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=sr,onUserMessage:o}){this.authHeader=e,this.orgId=t,this.runId=n,this.url=r,this.onUserMessage=o,Jr.info("[ws] Constructing AutohealWebSocketClient",{url:this.url,runId:n})}start(){this.connect()}connect(){if(!this._isClosed)try{const e={Authorization:this.authHeader};this.orgId&&(e["x-stably-org-id"]=this.orgId);const t=`${this.url}?runId=${encodeURIComponent(this.runId)}`;Jr.info("[ws] Connecting",{url:t,attempt:this.reconnectAttempts}),this.socket=new _e(t,{headers:e}),this.socket.on("open",()=>{Jr.info("[ws] Connection opened"),this.reconnectAttempts=0}),this.socket.on("message",e=>{try{const t="string"==typeof e?e:e.toString(),n=JSON.parse(t);Jr.debug("[ws] Received message",{type:n?.type}),"connected"===n?.type&&(Jr.info("[ws] Authenticated successfully"),this.isAuthenticated=!0,this.authenticationFailed=!1,this.flushPending()),"user_message"===n?.type&&"string"==typeof n.content&&(Jr.info("[ws] Received user message from web UI"),this.onUserMessage?.(n.content))}catch{}}),this.socket.on("close",(e,t)=>{Jr.info("[ws] Connection closed",{code:e,authFailed:1008===e,reconnectAttempts:this.reconnectAttempts,maxReconnect:this.maxReconnectAttempts,isClosed:this._isClosed}),this.isAuthenticated=!1,1008===e&&(this.authenticationFailed=!0),!this._isClosed&&!this.authenticationFailed&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()}),this.socket.on("error",e=>{Jr.warn("[ws] Connection error",{error:e.message})})}catch(e){Jr.warn("[ws] Failed to create WebSocket",{error:e instanceof Error?e.message:String(e)}),this.scheduleReconnect()}}scheduleReconnect(){this._isClosed||this.reconnectTimer||(this.reconnectAttempts++,Jr.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===_e.OPEN&&this.isAuthenticated}sendProgress(e){if(this._isClosed)return void Jr.debug("[ws] sendProgress called but client is closed",{phase:e.phase});const t={type:"autoheal_progress",payload:e};return this.pendingEvent=t,this.isConnected()?"complete"===e.phase?(Jr.info("[ws] sendProgress: flushing terminal state immediately"),void this.flushPending()):void(this.debounceTimer||(this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.flushPending()},this.debounceMs))):(Jr.debug("[ws] sendProgress: not connected, queuing event",{phase:e.phase,socketState:this.socket?.readyState,isAuthenticated:this.isAuthenticated,reconnectAttempts:this.reconnectAttempts}),void(this.socket?.readyState===_e.CLOSED&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()))}flushPending(){if(this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),!this.pendingEvent)return;const e=this.pendingEvent;if(this.pendingEvent=null,!this.isConnected())return Jr.debug("[ws] flushPending: not connected, re-queuing event",{phase:e.payload.phase}),void(this.pendingEvent=e);try{Jr.debug("[ws] flushPending: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),t=>{t&&(Jr.warn("[ws] flushPending: send failed",{error:t.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e))})}catch(t){Jr.warn("[ws] flushPending: send threw",{error:t instanceof Error?t.message:String(t)}),this.pendingEvent=e}}flushPendingAndWait(){if(this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),!this.pendingEvent)return Promise.resolve();const e=this.pendingEvent;return this.pendingEvent=null,this.isConnected()?new Promise(t=>{try{Jr.debug("[ws] flushPendingAndWait: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),n=>{n&&(Jr.warn("[ws] flushPendingAndWait: send failed",{error:n.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e)),t()})}catch(n){Jr.warn("[ws] flushPendingAndWait: send threw",{error:n instanceof Error?n.message:String(n)}),this.pendingEvent=e,t()}}):(Jr.debug("[ws] flushPendingAndWait: not connected, re-queuing event",{phase:e.payload.phase}),this.pendingEvent=e,Promise.resolve())}close(){if(this._isClosed)return;Jr.info("[ws] Closing WebSocket client"),this._isClosed=!0,this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.flushPending();const{socket:e}=this;this.socket=void 0,e&&setTimeout(()=>{e.close()},200)}async closeAndWait(){if(this._isClosed)return;Jr.info("[ws] Closing WebSocket client and waiting for pending send"),this._isClosed=!0,this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),await this.flushPendingAndWait();const{socket:e}=this;this.socket=void 0,e&&(await new Promise(e=>setTimeout(e,200)),e.close())}},ho=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=ir,onUserMessage:o}){this.authHeader=e,this.orgId=t,this.sessionId=n,this.url=r,this.onUserMessage=o,Jr.info("[ws] Constructing CreateProgressWebSocketClient",{url:this.url,sessionId:n})}start(){this.connect()}connect(){if(!this._isClosed)try{const e={Authorization:this.authHeader};this.orgId&&(e["x-stably-org-id"]=this.orgId);const t=`${this.url}?sessionId=${encodeURIComponent(this.sessionId)}`;Jr.info("[ws] Connecting",{url:t,attempt:this.reconnectAttempts}),this.socket=new _e(t,{headers:e}),this.socket.on("open",()=>{Jr.info("[ws] Connection opened"),this.reconnectAttempts=0}),this.socket.on("message",e=>{try{const t="string"==typeof e?e:e.toString(),n=JSON.parse(t);Jr.debug("[ws] Received message",{type:n?.type}),"connected"===n?.type&&(Jr.info("[ws] Authenticated successfully"),this.isAuthenticated=!0,this.authenticationFailed=!1,this.flushPending()),"user_message"===n?.type&&"string"==typeof n.content&&(Jr.info("[ws] Received user message from web UI"),this.onUserMessage?.(n.content))}catch{}}),this.socket.on("close",(e,t)=>{Jr.info("[ws] Connection closed",{code:e,authFailed:1008===e,reconnectAttempts:this.reconnectAttempts,maxReconnect:this.maxReconnectAttempts,isClosed:this._isClosed}),this.isAuthenticated=!1,1008===e&&(this.authenticationFailed=!0),!this._isClosed&&!this.authenticationFailed&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()}),this.socket.on("error",e=>{Jr.warn("[ws] Connection error",{error:e.message})})}catch(e){Jr.warn("[ws] Failed to create WebSocket",{error:e instanceof Error?e.message:String(e)}),this.scheduleReconnect()}}scheduleReconnect(){this._isClosed||this.reconnectTimer||(this.reconnectAttempts++,Jr.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===_e.OPEN&&this.isAuthenticated}sendProgress(e){if(this._isClosed)return void Jr.debug("[ws] sendProgress called but client is closed",{phase:e.phase});const t={type:"create_progress",payload:e};return this.pendingEvent=t,this.isConnected()?"complete"===e.phase?(Jr.info("[ws] sendProgress: flushing terminal state immediately"),void this.flushPending()):void(this.debounceTimer||(this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.flushPending()},this.debounceMs))):(Jr.debug("[ws] sendProgress: not connected, queuing event",{phase:e.phase,socketState:this.socket?.readyState,isAuthenticated:this.isAuthenticated,reconnectAttempts:this.reconnectAttempts}),void(this.socket?.readyState===_e.CLOSED&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()))}flushPending(){if(this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),!this.pendingEvent)return;const e=this.pendingEvent;if(this.pendingEvent=null,!this.isConnected())return Jr.debug("[ws] flushPending: not connected, re-queuing event",{phase:e.payload.phase}),void(this.pendingEvent=e);try{Jr.debug("[ws] flushPending: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),t=>{t&&(Jr.warn("[ws] flushPending: send failed",{error:t.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e))})}catch(t){Jr.warn("[ws] flushPending: send threw",{error:t instanceof Error?t.message:String(t)}),this.pendingEvent=e}}flushPendingAndWait(){if(this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),!this.pendingEvent)return Promise.resolve();const e=this.pendingEvent;return this.pendingEvent=null,this.isConnected()?new Promise(t=>{try{Jr.debug("[ws] flushPendingAndWait: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),n=>{n&&(Jr.warn("[ws] flushPendingAndWait: send failed",{error:n.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e)),t()})}catch(n){Jr.warn("[ws] flushPendingAndWait: send threw",{error:n instanceof Error?n.message:String(n)}),this.pendingEvent=e,t()}}):(Jr.debug("[ws] flushPendingAndWait: not connected, re-queuing event",{phase:e.payload.phase}),this.pendingEvent=e,Promise.resolve())}close(){if(this._isClosed)return;Jr.info("[ws] Closing WebSocket client"),this._isClosed=!0,this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.flushPending();const{socket:e}=this;this.socket=void 0,e&&setTimeout(()=>{e.close()},200)}async closeAndWait(){if(this._isClosed)return;Jr.info("[ws] Closing WebSocket client and waiting for pending send"),this._isClosed=!0,this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),await this.flushPendingAndWait();const{socket:e}=this;this.socket=void 0,e&&(await new Promise(e=>setTimeout(e,200)),e.close())}},go=ve.object({bucketPath:io,expiresInSeconds:ve.number(),key:ve.string(),uploadUrl:ve.string()}),mo=ge.object({uploadUrl:ge.string(),key:ge.string(),bucketPath:ge.object({bucket:ge.string(),key:ge.string()}),expiresInSeconds:ge.number()});async function yo({authHeader:e,orgId:t,sessionId:n,projectId:r,history:o}){if(0===o.length)return Jr.debug("[session-history] No history to upload"),{success:!0};try{Jr.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`,er),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");Jr.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 Jr.info("[session-history] History uploaded successfully",{key:i}),{success:!0,key:i}}catch(e){const t=e instanceof Error?e.message:String(e);return Jr.warn("[session-history] Failed to upload history",{error:t}),{success:!1,error:t}}}var bo="1.58.0",wo=["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 vo(e){return/^\.env(\..*)?$/.test(e)||".stably-agent.env"===e}function _o(e){return Boolean(e&&"object"==typeof e&&"tool_input"in e&&e.tool_input&&"object"==typeof e.tool_input)}function Io({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(!_o(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:vo,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 To=["rm","mv","git","gh","npx","stably","playwright-cli","pwtrace","npm","yarn","pnpm","bun"],Eo=["stably","playwright","playwright-cli","pwtrace"],So=["create","fix","verify"],xo=["upload"],Ao=["push","fetch","pull","clone","ls-remote"],Co=/\S+=(?:'[^']*(?:'\\''[^']*)*'|\S+)/;function Ro(e){const t=[],n=e.trim(),r=/(?:'[^']*(?:'\\''[^']*)*'|\S)+/g;let o;for(;null!==(o=r.exec(n));)t.push(o[0]);return t}function Po(e){let t=0;const n=new RegExp(`^${Co.source}$`);for(;t<e.length&&n.test(e[t]??"");)t+=1;return e.slice(t)}function ko(e){const t=Po(Ro(e));if("npx"===t[0])for(let e=1;e<t.length;e+=1){const n=t[e];if(n){if("--"===n)return t[e+1];if(!n.startsWith("-"))return n}}}function Uo(e){return Ro(e).find(e=>So.includes(e))}function Lo(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 Do({onBeforeGitHubCommand:e,workspaceBoundary:t}){return async n=>{if(!_o(n))return{decision:"block",reason:"Invalid tool call format: Expected an object with tool_input property.",systemMessage:"Tool call blocked due to invalid input format"};const r=n.tool_input,{command:i}=r;if("string"!=typeof i)return{decision:"block",reason:"Invalid Bash command: command must be a string.",systemMessage:"Tool call blocked due to invalid command type"};const c=function(e){const t=e.trim(),n=new RegExp(`^(?:${Co.source}\\s+)*(\\S+)`),r=t.match(n);return r?.[1]}(i);if(!c)return{decision:"block",reason:"Invalid Bash command: could not parse command.",systemMessage:"Tool call blocked due to unparseable command"};if("run_in_background"in r&&!0===r.run_in_background&&/\bplaywright-cli\s+run-test\b/.test(i))return{decision:"block",reason:"Running `playwright-cli run-test` with `run_in_background: true` is not allowed. Test runs must execute in the foreground so their output can be captured and parsed. Remove the `run_in_background` parameter and run the test normally.",systemMessage:"Tool call blocked due to run-test in background"};if(!function(e){return"string"==typeof e&&To.includes(e)}(c))return{decision:"block",reason:`The command "${c}" is not allowed. Only the following commands are permitted: ${To.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=ko(e);if(!t)return{valid:!1,reason:"Invalid npx command: unable to determine which binary is being executed."};if(!new Set(Eo).has(t))return{valid:!1,reason:`The npx binary "${t}" is not allowed. Only ${Eo.join(", ")} are permitted.`};if("playwright-cli"!==t){const n=Uo(e);if(n)return{valid:!1,reason:`The npx ${t} subcommand "${n}" is not allowed. The commands ${So.join(", ")} are AI-powered and blocked to prevent recursion.`}}return{valid:!0}}(i);if(!e.valid)return{decision:"block",reason:e.reason,systemMessage:"Tool call blocked due to disallowed npx command"}}if("playwright-cli"===c||"npx"===c&&"playwright-cli"===ko(i)){const e=function({command:e,binary:t}){const n=Po(Ro(e)),r=n.findIndex(e=>e===t);if(-1!==r)for(let e=r+1;e<n.length;e+=1){const t=n[e];if(t&&!t.startsWith("-"))return t}}({command:i,binary:"playwright-cli"});if(e&&xo.includes(e))return{decision:"block",reason:`The playwright-cli subcommand "${e}" is not allowed. The "upload" command can read arbitrary files and is blocked for security.`,systemMessage:"Tool call blocked due to disallowed playwright-cli subcommand"}}if("stably"===c){const e=Uo(i);if(e)return{decision:"block",reason:`The stably subcommand "${e}" is not allowed. The commands ${So.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(_(e))return S.native(e);let t=e;const n=[];for(;!_(t);){const r=s(t);if(r===t)return o(e);n.unshift(t.slice(r.length+1)),t=r}const r=S.native(t);return n.length>0?o(r,...n):r}(e),r=S.native(t),i=n.endsWith(a)?n:n+a,c=r.endsWith(a)?r:r+a;return i.startsWith(c)||n===r}({targetPath: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=>!(Lo(e,"tests")||Lo(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 ")&&Ao.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 wo.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 $o=/\.(spec|test)\.(ts|tsx|js|jsx|mts|mjs)$/;function Oo({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&&$o.test(r)&&e(r),{decision:"approve"}}}var No=M(f);async function Bo(){try{const{stdout:e}=await No('pgrep -f "playwright run-test-mcp-server" 2>/dev/null || true'),t=e.trim();if(!t)return;const n=t.split("\n").filter(Boolean);await Promise.allSettled(n.map(async e=>{await No(`pkill -KILL -P ${e} '.*' 2>/dev/null || true`)}))}catch{}}var jo=class{queue=[];pendingResolve=void 0;done=!1;canSend=!0;[Symbol.asyncIterator](){return this}pushText(e){const t=e.trim();t&&!this.done&&(this.queue.push(t),this.maybeFlush())}allowNextTurn(){this.done||(this.canSend=!0,this.maybeFlush())}hasQueuedMessages(){return this.queue.length>0}finish(){this.done=!0,this.pendingResolve&&(this.pendingResolve({done:!0,value:void 0}),this.pendingResolve=void 0)}maybeFlush(){if(!this.pendingResolve)return;if(!this.canSend)return;const e=this.queue.shift();if(void 0===e)return;const t={message:{content:[{text:e,type:"text"}],role:"user"},parent_tool_use_id:null,type:"user",session_id:""};this.canSend=!1,this.pendingResolve({done:!1,value:t}),this.pendingResolve=void 0}next(){return this.done?Promise.resolve({done:!0,value:void 0}):new Promise(e=>{this.pendingResolve=e,this.maybeFlush()})}};function Mo(e){try{const t=h("git branch --show-current",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(!t)return;return{branch:t}}catch{return}}var Fo=[".ts",".js",".mts",".mjs",".cts",".cjs"],Ho=10240,Go=async({defaultContent:e,fileName:t,filePath:n})=>{try{const e=(await se(n)).size,r=await Z(n,"utf-8"),o=Buffer.byteLength(r,"utf-8");if(o<=Ho)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<=Ho?s:s.slice(0,Ho)+`\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}},Wo=async({defaultContent:e,dirName:t,dirPath:n})=>{try{const e=await oe(n);return e.length>0?e.join("\n"):"(empty)"}catch(n){let r;if(n&&"object"==typeof n&&"code"in n){const e=n.code;"string"==typeof e&&(r=e)}return"ENOENT"!==r&&console.warn(`Failed to read ${t}: ${n}`),e}},Yo=async({allowedEnvVars:e,mode:t,workspaceInfo:n,authHeader:r,customHeader:o,maxParallelWorkers:s})=>{const i=cr(),a=Mo(n.absolutePath);Jr.debug("Requesting system prompt from API",{mode:t,hasGitContext:!!a,envVarCount:e.length});const c=await(l={client:i,auth:r,body:{mode:t,workspaceInfo:n,allowedEnvVars:e,gitContext:a,maxParallelWorkers:s}},(l.client??Jn).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/prompts/system",...l,headers:{"Content-Type":"application/json",...l.headers}}));var l;if(401===c.response.status)throw Jr.warn("System prompt fetch failed: unauthorized (401)"),await Er(),new Error("Your session has expired or been revoked. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(403===c.response.status)throw Jr.debug("System prompt fetch failed: forbidden (403)"),new Error("Your organization does not have an active subscription. Manage your subscription at https://app.stably.ai or contact your organization admin.");if(c.error){Jr.warn("System prompt fetch failed",{error:c.error});const e=JSON.stringify(c.error);if(e.toLowerCase().includes("unauthorized")||e.toLowerCase().includes("unauthenticated"))throw await Er(),new Error("Your session has expired or been revoked. Credentials have been cleared. Please run `stably login` to re-authenticate.");throw new Error("Failed to fetch system prompt. Please check your network connection and try again. If this persists, run `stably login` to re-authenticate.")}const u=function({customHeader:e,systemPrompt:t}){return e?`${t}\n\nWhen writing or updating the generated test file, prepend this exact header at the top of the file without modification:\n\`\`\`ts\n${e}\n\`\`\``:t}({systemPrompt:c.data.systemPrompt,customHeader:o});return Jr.debug("System prompt received",{size:u.length,appendedCustomHeader:!!o,hasPrContext:!!c.data.prContext}),{systemPrompt:u,prContext:c.data.prContext}},Vo={chat:"chat",single:"create",fix:"fix",init:"init",verify:"verify"},zo=".stably-playwright-wrapper.config.*",Ko=[".ts",".js",".mts",".mjs",".cts",".cjs"];function qo(e){const t=o(e);if(_(t))for(const e of Ko){const n=i(t,`playwright.config${e}`);if(_(n))return n}}var Jo=["tests","e2e","__tests__","test"];function Qo(e){try{return _(e)&&I(e).isDirectory()}catch{return!1}}function Xo(e,t){const n="output-flag"===t?"--output flag":"playwright.config.ts"===t?"playwright.config.ts":"auto-detected"===t?"auto-detected":"cwd fallback";console.error(q.dim(`Using output directory: ${e} (from ${n})`))}var Zo,es=["mcp__playwright-test__","mcp__auto-heal-report__","mcp__stably-agent-control__"],ts=["planner_","generator_"],ns={open:e=>e?`Open ${e}`:"Open browser",close:()=>"Close browser",snapshot:()=>"Page snapshot",screenshot:()=>"Screenshot",click:e=>`Click ${e}`,fill:e=>`Fill ${e.split(/\s+/)[0]||""}`.trim(),type:e=>`Type into ${e.split(/\s+/)[0]||""}`.trim(),hover:e=>`Hover ${e}`,goto:e=>`Navigate to ${e}`,select:e=>`Select option in ${e.split(/\s+/)[0]||""}`.trim(),check:e=>`Check ${e}`,uncheck:e=>`Uncheck ${e}`,back:()=>"Go back",forward:()=>"Go forward","run-test":e=>`Run test ${e}`,"run-code":()=>"Run code","run-file":e=>`Run file ${e}`,"tab-list":()=>"List tabs","tab-new":e=>e?`New tab ${e}`:"New tab","tab-select":e=>`Select tab ${e}`,"tab-close":()=>"Close tab",eval:()=>"Evaluate JavaScript",upload:()=>"Upload file","state-save":()=>"Save browser state","state-load":()=>"Load browser state"},rs={"mcp__stably-agent-control__restart_mcp_servers":"Restarting Browser Tools","mcp__session-control__restart_mcp_servers":"Restarting Browser Tools",Skill:"Invoking skill",ToolSearch:"Searching tools"},os=(e,t)=>{const n=t.find(t=>e.startsWith(t));return n?e.slice(n.length):e},ss=e=>e.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" "),is=(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},as=(e,t)=>{if(!t||"object"!=typeof t)return null;const n=t;if("Bash"===e&&"string"==typeof n.command){const e=n.command.match(/(?:^|\s)(?:[\w/.-]*\/)?playwright-cli\s+(?:--\S+\s+)*(\S+)(.*)/);if(!e)return null;const[,t,r]=e,o=r.trim().replace(/--\S+=?\S*\s*/g,"").trim();if("string"==typeof n.description&&n.description.trim())return n.description.trim();const s=ns[t];return s?s(o):`${ss(t)}${o?` ${o.split(/\s+/)[0]}`:""}`.trim()}return"Read"===e&&"string"==typeof n.file_path&&n.file_path.includes(".playwright-cli/")&&n.file_path.endsWith(".yml")?"Page snapshot":null},cs=e=>"mcp__auto-heal-report__capture-trace-proof"===e?"Verify Test Run":"mcp__auto-heal-report__generate-report"===e?"Generate Report":(e=>{const t=rs[e];if(t)return t;const n=os(e,es),r=os(n,ts);return ss(r)})(e),ls=["test","bug","flake","ui_change","other"],us={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."},ds=e=>us[e],ps=/[^a-zA-Z0-9-_]/g,fs=e=>{const t=e.trim().replace(ps,"_");return t.length>0?t.slice(0,80):void 0},hs=e=>"string"==typeof e?fs(e):void 0,gs=Re("/");try{Zo=gs("worker_threads").Worker}catch(e){}var ms=Zo?function(e,t,n,r,o){var s=!1,i=new Zo(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,Zo.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}},ys=Uint8Array,bs=Uint16Array,ws=Int32Array,vs=new ys([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]),_s=new ys([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]),Is=new ys([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ts=function(e,t){for(var n=new bs(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];var o=new ws(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}},Es=Ts(vs,2),Ss=Es.b,xs=Es.r;Ss[28]=258,xs[258]=28;var As,Cs=Ts(_s,0),Rs=Cs.b,Ps=Cs.r,ks=new bs(32768);for(Ds=0;Ds<32768;++Ds)As=(61680&(As=(52428&(As=(43690&Ds)>>1|(21845&Ds)<<1))>>2|(13107&As)<<2))>>4|(3855&As)<<4,ks[Ds]=((65280&As)>>8|(255&As)<<8)>>1;var Us=function(e,t,n){for(var r=e.length,o=0,s=new bs(t);o<r;++o)e[o]&&++s[e[o]-1];var i,a=new bs(t);for(o=1;o<t;++o)a[o]=a[o-1]+s[o-1]<<1;if(n){i=new bs(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[ks[d]>>c]=l}else for(i=new bs(r),o=0;o<r;++o)e[o]&&(i[o]=ks[a[e[o]-1]++]>>15-e[o]);return i},Ls=new ys(288);for(Ds=0;Ds<144;++Ds)Ls[Ds]=8;for(Ds=144;Ds<256;++Ds)Ls[Ds]=9;for(Ds=256;Ds<280;++Ds)Ls[Ds]=7;for(Ds=280;Ds<288;++Ds)Ls[Ds]=8;var Ds,$s=new ys(32);for(Ds=0;Ds<32;++Ds)$s[Ds]=5;var Os=Us(Ls,9,0),Ns=Us(Ls,9,1),Bs=Us($s,5,0),js=Us($s,5,1),Ms=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},Fs=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(7&t)&n},Hs=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(7&t)},Gs=function(e){return(e+7)/8|0},Ws=function(e,t,n){return(null==t||t<0)&&(t=0),(null==n||n>e.length)&&(n=e.length),new ys(e.subarray(t,n))},Ys=["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"],Vs=function(e,t,n){var r=new Error(t||Ys[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,Vs),!n)throw r;return r},zs=function(e,t,n,r){var o=e.length,s=r?r.length:0;if(!o||t.f&&!t.l)return n||new ys(0);var i=!n,a=i||2!=t.i,c=t.i;i&&(n=new ys(3*o));var l=function(e){var t=n.length;if(e>t){var r=new ys(Math.max(2*t,e));r.set(n),n=r}},u=t.f||0,d=t.p||0,p=t.b||0,f=t.l,h=t.d,g=t.m,m=t.n,y=8*o;do{if(!f){u=Fs(e,d,1);var b=Fs(e,d+1,3);if(d+=3,!b){var w=e[(P=Gs(d)+4)-4]|e[P-3]<<8,v=P+w;if(v>o){c&&Vs(0);break}a&&l(p+w),n.set(e.subarray(P,v),p),t.b=p+=w,t.p=d=8*v,t.f=u;continue}if(1==b)f=Ns,h=js,g=9,m=5;else if(2==b){var _=Fs(e,d,31)+257,I=Fs(e,d+10,15)+4,T=_+Fs(e,d+5,31)+1;d+=14;for(var E=new ys(T),S=new ys(19),x=0;x<I;++x)S[Is[x]]=Fs(e,d+3*x,7);d+=3*I;var A=Ms(S),C=(1<<A)-1,R=Us(S,A,1);for(x=0;x<T;){var P,k=R[Fs(e,d,C)];if(d+=15&k,(P=k>>4)<16)E[x++]=P;else{var U=0,L=0;for(16==P?(L=3+Fs(e,d,3),d+=2,U=E[x-1]):17==P?(L=3+Fs(e,d,7),d+=3):18==P&&(L=11+Fs(e,d,127),d+=7);L--;)E[x++]=U}}var D=E.subarray(0,_),$=E.subarray(_);g=Ms(D),m=Ms($),f=Us(D,g,1),h=Us($,m,1)}else Vs(1);if(d>y){c&&Vs(0);break}}a&&l(p+131072);for(var O=(1<<g)-1,N=(1<<m)-1,B=d;;B=d){var j=(U=f[Hs(e,d)&O])>>4;if((d+=15&U)>y){c&&Vs(0);break}if(U||Vs(2),j<256)n[p++]=j;else{if(256==j){B=d,f=null;break}var M=j-254;if(j>264){var F=vs[x=j-257];M=Fs(e,d,(1<<F)-1)+Ss[x],d+=F}var H=h[Hs(e,d)&N],G=H>>4;if(H||Vs(3),d+=15&H,$=Rs[G],G>3&&(F=_s[G],$+=Hs(e,d)&(1<<F)-1,d+=F),d>y){c&&Vs(0);break}a&&l(p+131072);var W=p+M;if(p<$){var Y=s-$,V=Math.min($,W);for(Y+p<0&&Vs(3);p<V;++p)n[p]=r[Y+p]}for(;p<W;++p)n[p]=n[p-$]}}t.l=f,t.p=B,t.b=p,t.f=u,f&&(u=1,t.m=g,t.d=h,t.n=m)}while(!u);return p!=n.length&&i?Ws(n,0,p):n.subarray(0,p)},Ks=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},Js=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:ri,l:0};if(1==o){var i=new ys(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 bs(p+1),h=Qs(n[u-1],f,0);if(h>t){r=0;var g=0,m=h-t,y=1<<m;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;g+=y-(1<<h-f[b]),f[b]=t}for(g>>=m;g>0;){var w=s[r].s;f[w]<t?g-=1<<t-f[w]++-1:++r}for(;r>=0&&g;--r){var v=s[r].s;f[v]==t&&(--f[v],++g)}h=t}return{t:new ys(f),l:h}},Qs=function(e,t,n){return-1==e.s?Math.max(Qs(e.l,t,n+1),Qs(e.r,t,n+1)):t[e.s]=n},Xs=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new bs(++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}},Zs=function(e,t){for(var n=0,r=0;r<t.length;++r)n+=e[r]*t[r];return n},ei=function(e,t,n){var r=n.length,o=Gs(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)},ti=function(e,t,n,r,o,s,i,a,c,l,u){Ks(t,u++,n),++o[256];for(var d=Js(o,15),p=d.t,f=d.l,h=Js(s,15),g=h.t,m=h.l,y=Xs(p),b=y.c,w=y.n,v=Xs(g),_=v.c,I=v.n,T=new bs(19),E=0;E<b.length;++E)++T[31&b[E]];for(E=0;E<_.length;++E)++T[31&_[E]];for(var S=Js(T,7),x=S.t,A=S.l,C=19;C>4&&!x[Is[C-1]];--C);var R,P,k,U,L=l+5<<3,D=Zs(o,Ls)+Zs(s,$s)+i,$=Zs(o,p)+Zs(s,g)+i+14+3*C+Zs(T,x)+2*T[16]+3*T[17]+7*T[18];if(c>=0&&L<=D&&L<=$)return ei(t,u,e.subarray(c,c+l));if(Ks(t,u,1+($<D)),u+=2,$<D){R=Us(p,f,0),P=p,k=Us(g,m,0),U=g;var O=Us(x,A,0);for(Ks(t,u,w-257),Ks(t,u+5,I-1),Ks(t,u+10,C-4),u+=14,E=0;E<C;++E)Ks(t,u+3*E,x[Is[E]]);u+=3*C;for(var N=[b,_],B=0;B<2;++B){var j=N[B];for(E=0;E<j.length;++E){var M=31&j[E];Ks(t,u,O[M]),u+=x[M],M>15&&(Ks(t,u,j[E]>>5&127),u+=j[E]>>12)}}}else R=Os,P=Ls,k=Bs,U=$s;for(E=0;E<a;++E){var F=r[E];if(F>255){qs(t,u,R[257+(M=F>>18&31)]),u+=P[M+257],M>7&&(Ks(t,u,F>>23&31),u+=vs[M]);var H=31&F;qs(t,u,k[H]),u+=U[H],H>3&&(qs(t,u,F>>5&8191),u+=_s[H])}else qs(t,u,R[F]),u+=P[F]}return qs(t,u,R[256]),u+P[256]},ni=new ws([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),ri=new ys(0),oi=function(e,t,n,r,o,s){var i=s.z||e.length,a=new ys(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=ni[t-1],p=d>>13,f=8191&d,h=(1<<n)-1,g=s.p||new bs(32768),m=s.h||new bs(h+1),y=Math.ceil(n/3),b=2*y,w=function(t){return(e[t]^e[t+1]<<y^e[t+2]<<b)&h},v=new ws(25e3),_=new bs(288),I=new bs(32),T=0,E=0,S=s.i||0,x=0,A=s.w||0,C=0;S+2<i;++S){var R=w(S),P=32767&S,k=m[R];if(g[P]=k,m[R]=P,A<=S){var U=i-S;if((T>7e3||x>24576)&&(U>423||!l)){u=ti(e,c,0,v,_,I,E,x,C,S-C,u),x=T=E=0,C=S;for(var L=0;L<286;++L)_[L]=0;for(L=0;L<30;++L)I[L]=0}var D=2,$=0,O=f,N=P-k&32767;if(U>2&&R==w(S-N))for(var B=Math.min(p,U)-1,j=Math.min(32767,S),M=Math.min(258,U);N<=j&&--O&&P!=k;){if(e[S+D]==e[S+D-N]){for(var F=0;F<M&&e[S+F]==e[S+F-N];++F);if(F>D){if(D=F,$=N,F>B)break;var H=Math.min(N,F-2),G=0;for(L=0;L<H;++L){var W=S-N+L&32767,Y=W-g[W]&32767;Y>G&&(G=Y,k=W)}}}N+=(P=k)-(k=g[P])&32767}if($){v[x++]=268435456|xs[D]<<18|Ps[$];var V=31&xs[D],z=31&Ps[$];E+=vs[V]+_s[z],++_[257+V],++I[z],A=S+D,++T}else v[x++]=e[S],++_[e[S]]}}for(S=Math.max(S,A);S<i;++S)v[x++]=e[S],++_[e[S]];u=ti(e,c,l,v,_,I,E,x,C,S-C,u),l||(s.r=7&u|c[u/8|0]<<3,u-=7,s.h=m,s.p=g,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=ei(c,u+1,e.subarray(S,K))}s.i=i}return Ws(a,0,r+Gs(u)+o)},si=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}(),ii=function(e,t,n,r,o){if(!o&&(o={l:1},t.dictionary)){var s=t.dictionary.subarray(-32768),i=new ys(s.length+e.length);i.set(s),i.set(e,s.length),e=i,o.w=s.length}return oi(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)},ai=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},ci=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},li=[],ui=function(){return[ys,bs,ws,vs,_s,Is,Ss,Rs,Ns,js,ks,Ys,Us,Ms,Fs,Hs,Gs,Ws,Vs,zs,vi,pi,fi]},di=function(){return[ys,bs,ws,vs,_s,Is,xs,Ps,Os,Ls,Bs,$s,ks,ni,ri,Us,Ks,qs,Js,Qs,Xs,Zs,ei,ti,Gs,Ws,oi,ii,wi,pi]},pi=function(e){return postMessage(e,[e.buffer])},fi=function(e){return e&&{out:e.size&&new ys(e.size),dictionary:e.dictionary}},hi=function(e,t,n,r,o,s){var i=function(e,t,n,r){if(!li[n]){for(var o="",s={},i=e.length-1,a=0;a<i;++a)o=ci(e[a],o,s);li[n]={c:ci(e[i],o,s),e:s}}var c=ai({},li[n].e);return ms(li[n].c+";onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage="+t.toString()+"}",n,c,function(e){var t=[];for(var n in e)e[n].buffer&&t.push((e[n]=new e[n].constructor(e[n])).buffer);return t}(c),r)}(n,r,o,function(e,t){i.terminate(),s(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},mi=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},yi=function(e,t){return mi(e,t)+4294967296*mi(e,t+4)},bi=function(e,t,n){for(;n;++t)e[t]=n,n>>>=8};function wi(e,t){return ii(e,t||{},0,0)}function vi(e,t){return zs(e,{i:2},t&&t.out,t&&t.dictionary)}var _i=function(e,t,n,r){for(var o in e){var s=e[o],i=t+o,a=r;Array.isArray(s)&&(a=ai(r,s[1]),s=s[0]),s instanceof ys?n[i]=[s,a]:(n[i+="/"]=[new ys(0),a],_i(s,i,n,r))}},Ii="undefined"!=typeof TextEncoder&&new TextEncoder,Ti="undefined"!=typeof TextDecoder&&new TextDecoder;try{Ti.decode(ri,{stream:!0})}catch(e){}function Ei(e,t){if(Ii)return Ii.encode(e);for(var n=e.length,r=new ys(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 ys(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 Ws(r,0,o)}var Si=function(e){var t=0;if(e)for(var n in e){var r=e[n].length;r>65535&&Vs(9),t+=r+4}return t},xi=function(e,t,n,r,o,s,i,a){var c=r.length,l=n.extra,u=a&&a.length,d=Si(l);bi(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)&&Vs(10),bi(e,t,f<<25|p.getMonth()+1<<21|p.getDate()<<16|p.getHours()<<11|p.getMinutes()<<5|p.getSeconds()>>1),t+=4,-1!=s&&(bi(e,t,n.crc),bi(e,t+4,s<0?-s-2:s),bi(e,t+8,n.size)),bi(e,t+12,c),bi(e,t+14,d),t+=16,null!=i&&(bi(e,t,u),bi(e,t+6,n.attrs),bi(e,t+10,i),t+=14),e.set(r,t),t+=c,d)for(var h in l){var g=l[h],m=g.length;bi(e,t,+h),bi(e,t+2,m),e.set(g,t+4),t+=4+m}return u&&(e.set(a,t),t+=u),t},Ai="function"==typeof queueMicrotask?queueMicrotask:"function"==typeof setTimeout?setTimeout:function(e){e()};function Ci(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 Ri=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 Pi(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 ki(e){switch(7&Pi(e)){case 0:return Pi(e),!0;case 1:return e.next(8),!0;case 2:const t=Pi(e);return e.next(t),!0;case 5:return e.next(4),!0}return!1}function Ui(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!Ci(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!Ci(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 Ri(e,t);let r=0;for(;;){if(!ki(n)&&!n.hasError())return!1;if(n.hasError())break;r++}return r>0}(e,s))}var Li=[/^\/$/,/^\*+$/,/^[0-9]+$/],Di=["/artifact/","https://","http://","*********"],$i=new Set(["sha1","_sha1","pageref","downloadsPath","tracesDir","pageId"]);function Oi({sensitiveValues:e,str:t}){return e.reduce((e,t)=>e.replaceAll(t,"[REDACTED]"),t)}function Ni({sensitiveValues:e,value:t}){return"string"==typeof t?Oi({sensitiveValues:e,str:t}):Array.isArray(t)?t.map(t=>Ni({sensitiveValues:e,value:t})):function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(t)?ji({obj:t,sensitiveValues:e}):t}function Bi(e){return!!$i.has(e)||e.toLowerCase().endsWith("sha1")}function ji({obj:e,sensitiveValues:t}){return Object.fromEntries(Object.entries(e).map(([e,n])=>[e,Bi(e)?n:Ni({sensitiveValues:t,value:n})]))}function Mi({error:e,sensitiveValues:t}){return e?{...e,message:Oi({sensitiveValues:t,str:e.message})}:void 0}function Fi({content:e,sensitiveValues:t}){const n=new F,r=new H,o=Oi({sensitiveValues:t,str:n.decode(e)});return r.encode(o)}var Hi=M(function(e,t,n){n||(n=t,t={}),"function"!=typeof n&&Vs(7);var r=[],o=function(){for(var e=0;e<r.length;++e)r[e]()},s={},i=function(e,t){Ai(function(){n(e,t)})};Ai(function(){i=n});for(var a=e.length-22;101010256!=mi(e,a);--a)if(!a||e.length-a>65558)return i(Vs(13,0,1),null),o;var c=gi(e,a+8);if(c){var l=c,u=mi(e,a+16),d=4294967295==u||65535==l;if(d){var p=mi(e,a-12);(d=101075792==mi(e,p))&&(l=c=mi(e,p+32),u=mi(e,p+48))}for(var f=t&&t.filter,h=function(t){var n=function(e,t,n){var r=gi(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(Ti)return Ti.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:Ws(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&&Vs(8),s}(e.subarray(t+46,t+46+r),!(2048&gi(e,t+8))),s=t+46+r,i=mi(e,t+20),a=n&&4294967295==i?function(e,t){for(;1!=gi(e,t);t+=4+gi(e,t+2));return[yi(e,t+12),yi(e,t+4),yi(e,t+20)]}(e,s):[i,mi(e,t+24),mi(e,t+42)],c=a[0],l=a[1],u=a[2];return[gi(e,t+10),c,l,o,s+gi(e,t+30)+gi(e,t+32),u]}(e,u,d),a=n[0],l=n[1],p=n[2],h=n[3],g=n[4],m=n[5],y=function(e,t){return t+30+gi(e,t+26)+gi(e,t+28)}(e,m);u=g;var b=function(e,t){e?(o(),i(e,null)):(t&&(s[h]=t),--c||i(null,s))};if(!f||f({name:h,size:l,originalSize:p,compression:a}))if(a)if(8==a){var w=e.subarray(y,y+l);if(p<524288||l>.8*p)try{b(null,vi(w,{out:new ys(p)}))}catch(e){b(e,null)}else r.push(function(e,t,n){return n||(n=t,t={}),"function"!=typeof n&&Vs(7),hi(e,t,[ui],function(e){return pi(vi(e.data[0],fi(e.data[1])))},1,n)}(w,{size:p},b))}else b(Vs(14,"unknown compression type "+a,1),null);else b(null,Ws(e,y,y+l));else b(null,null)},g=0;g<l;++g)h()}else i(null,{});return o}),Gi=M(function(e,t,n){n||(n=t,t={}),"function"!=typeof n&&Vs(7);var r={};_i(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){Ai(function(){n(e,t)})};Ai(function(){p=n});var f=function(){var e=new ys(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;xi(e,a,o,o.f,o.u,s);var u=30+o.f.length+Si(o.extra),d=a+u;e.set(o.c,d),xi(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){bi(e,t,101010256),bi(e,t+8,n),bi(e,t+10,n),bi(e,t+12,r),bi(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],g=function(){var e=-1;return{p:function(t){for(var n=e,r=0;r<t.length;++r)n=si[255&n^t[r]]^n>>>8;e=n},d:function(){return~e}}}(),m=c.length;g.p(c);var y=Ei(t),b=y.length,w=h.comment,v=w&&Ei(w),_=v&&v.length,I=Si(h.extra),T=0==h.level?0:8,E=function(n,r){if(n)d(),p(n,null);else{var o=r.length;l[e]=ai(h,{size:m,crc:g.d(),c:r,f:y,m:v,u:b!=t.length||v&&w.length!=_,compression:T}),i+=30+b+I+o,a+=76+2*(b+I)+(_||0)+o,--s||f()}};if(b>65535&&E(Vs(11,0,1),null),T)if(m<16e4)try{E(null,wi(c,h))}catch(e){E(e,null)}else u.push(function(e,t,n){return n||(n=t,t={}),"function"!=typeof n&&Vs(7),hi(e,t,[di],function(e){return pi(wi(e.data[0],e.data[1]))},0,n)}(c,h,E));else E(null,c)},g=0;g<c;++g)h(g);return d});async function Wi({content:e,filename:t,sensitiveValues:n}){const r=t.toLowerCase();return r.endsWith(".trace")||r.endsWith(".network")?function({content:e,sensitiveValues:t}){const n=new F,r=new H,o=n.decode(e).split("\n").map(e=>{if(!e.trim())return e;try{const n=function({event:e,sensitiveValues:t}){return V(e).with({type:"console"},e=>({...e,args:e.args?.map(e=>({...e,preview:Oi({sensitiveValues:t,str:e.preview}),value:Ni({sensitiveValues:t,value:e.value})})),text:Oi({sensitiveValues:t,str:e.text})})).with({type:"before"},e=>({...e,params:ji({obj:e.params,sensitiveValues:t}),title:e.title?Oi({sensitiveValues:t,str:e.title}):void 0})).with({type:"after"},e=>({...e,error:Mi({error:e.error,sensitiveValues:t}),result:void 0!==e.result?Ni({sensitiveValues:t,value:e.result}):void 0})).with({type:"action"},e=>({...e,error:Mi({error:e.error,sensitiveValues:t}),params:ji({obj:e.params,sensitiveValues:t}),result:void 0!==e.result?Ni({sensitiveValues:t,value:e.result}):void 0,title:e.title?Oi({sensitiveValues:t,str:e.title}):void 0})).with({type:"event"},e=>({...e,params:ji({obj:e.params,sensitiveValues:t})})).with({type:"stdout"},{type:"stderr"},e=>({...e,text:void 0!==e.text?Oi({sensitiveValues:t,str:e.text}):void 0})).with({type:"error"},e=>({...e,message:Oi({sensitiveValues:t,str:e.message})})).with({type:"log"},e=>({...e,message:Oi({sensitiveValues:t,str:e.message})})).with({type:"context-options"},e=>({...e,options:ji({obj:e.options,sensitiveValues:t}),title:e.title?Oi({sensitiveValues:t,str:e.title}):void 0})).with({type:"frame-snapshot"},e=>({...e,snapshot:ji({obj:e.snapshot,sensitiveValues:t})})).with({type:"resource-snapshot"},e=>({...e,snapshot:ji({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 Oi({sensitiveValues:t,str:e})}});return r.encode(o.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!")}(I(e));const n=R(e,"r"),r=Buffer.alloc(515),o=P(n,r,0,515,0);return k(n),Ui(r,o,t)}return Ui(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 Yi(e=process.cwd()){let t=o(e);for(;;){const e=Vi(t);if(e){const n={...e.dependencies,...e.devDependencies},r="@playwright/test"in n?"@playwright/test":"playwright"in n?"playwright":void 0;if(r){const e=zi(t);let n=!1,o=t;for(;;){const e=i(o,"node_modules"),t=i(e,r);if(_(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 Vi(e){const t=i(e,"package.json");let n;try{n=T(t,"utf-8")}catch{return}try{return JSON.parse(n)}catch{return}}function zi(e){const t=[["npm","package-lock.json"],["pnpm","pnpm-lock.yaml"],["yarn","yarn.lock"]];let n=e;for(;;){for(const[e,r]of t)if(_(i(n,r)))return e;const e=s(n);if(e===n)return;n=e}}function Ki(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,"\\$&"),Ji=e=>(e instanceof Error?e.message:String(e)).slice(0,400),Qi=({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},Xi=async e=>{const t=await oe(e,{withFileTypes:!0}),n=[];for(const o of t){const t=r.join(e,o.name);if(o.isDirectory())n.push(...await Xi(t));else if(o.isFile()&&"trace.zip"===o.name){const e=await se(t);n.push({path:t,mtimeMs:e.mtimeMs})}}return n},Zi=async e=>{try{const t=await oe(e,{withFileTypes:!0});for(const n of t){const t=r.join(e,n.name);n.isDirectory()?await Zi(t):n.isFile()&&".last-run.json"===n.name&&await ie(t,{force:!0})}}catch{}},{zMarkdownAutoHealReport:ea,zRepresentativeTest:ta}=function(e){const t=e.enum(ls),n=["Classification of the root cause:","",`- test: ${ds("test")}`,`- bug: ${ds("bug")}`,`- flake: ${ds("flake")}`,`- ui_change: ${ds("ui_change")}`,`- other: ${ds("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}}(ve),na=({authHeader:e,diffTracker:t,orgId:n,runId:o,workingDir:s})=>G({name:"auto-heal-report",tools:[W("capture-trace-proof",["Capture and upload a Playwright trace proof for a test case.","","MANDATORY: Call for EVERY testCaseId in your issue, whether fixed or unfixed.","- Fixed: Trace proves the fix works","- Unfixed: Trace shows the failure state for auditability","","Pass testCaseId and call once per test case.","testCaseId is for per-test mapping/storage metadata; representativeTest selects the runnable test."].join("\n"),{issueId:ve.string().min(1).describe("Issue identifier for deterministic output paths and storage key naming."),proofId:ve.string().min(1).optional().describe("Optional id for deterministic proof naming and deduplication."),representativeTest:ta.optional().default({}),testCaseId:ve.string().min(1).optional().describe("Optional test case ID when capturing per-test trace proofs.")},async({issueId:t,proofId:i,representativeTest:a,testCaseId:c})=>{const l=ve.string().min(1).parse(t),u=null==i?void 0:ve.string().min(1).parse(i),d=null==c?void 0:ve.string().min(1).parse(c),p=ta.parse(a??{}),f=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=Yi(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=>fs(e)??"issue")(t),d=(({proofId:e,testCaseId:t})=>hs(t)??hs(e))({testCaseId:a,proofId:o}),p=r.join(c,".stably","autoheal-proof",u,d??"issue"),[f,...h]=Ki(l.packageManager),m=[...h,...Qi({outputDir:p,representativeTest:s})];try{await ie(p,{force:!0,recursive:!0}),await ee(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=g(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:m,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=(e=>e.includes("Executable doesn't exist")&&e.includes("ms-playwright")?'Playwright browsers are not installed. Run "npx playwright install" to install them.':e.includes("browserType.launch")&&e.includes("Executable doesn't exist")?"Browser executable not found. Playwright browsers may not be installed.":e.includes("npx playwright install")?"Playwright browsers need to be installed. The trace cannot verify the fix.":void 0)(l);if(d)return{status:"capture_failed",representativeTest:s,error:d};const h=await(async e=>{const t=await Xi(e);if(0!==t.length)return t.sort((e,t)=>t.mtimeMs-e.mtimeMs),t[0]?.path})(p);if(!h)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 Zi(p);const{traceBucketPath:y,uploadUrl:b,sensitiveValues:w}=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:cr(),headers:oo(s),path:{runId:i}},(c.client??Jn).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-trace/upload-url",...c,headers:{"Content-Type":"application/json",...c.headers}}));var c;if(a.error)throw new Error(`Failed to presign trace upload (${a.response.status})`);const l=lo.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=x(e);for await(const e of r)n.push(e);return async function({sensitiveValues:e,traceBuffer:t}){const n=e.filter(e=>!(e.length<3||Li.some(t=>t.test(e))||Di.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 Hi(new Uint8Array(t)),s=Object.entries(o),i=await Promise.all(s.map(async([e,t])=>[e,await Wi({content:t,filename:e,sensitiveValues:r})])),a=Object.fromEntries(i);return Gi(a)}({traceBuffer:new Uint8Array(Buffer.concat(n)),sensitiveValues:t})}({tracePath:h,sensitiveValues:w});try{await ao({body:v,contentType:"application/zip",uploadUrl:b,errorContext:"trace"})}catch(e){return{status:"upload_failed",representativeTest:s,error:Ji(e)}}return{status:"captured",representativeTest:s,storage:y}}catch(e){return{status:"capture_failed",representativeTest:s,error:Ji(e)}}})({authHeader:e,issueId:l,orgId:n,proofId:u,representativeTest:p,runId:o,testCaseId:d,workingDir:s}),h=p.testTitle||p.filePath,m="captured"===f.status&&f.storage?`@[trace:${Buffer.from(JSON.stringify({...f.storage,...h?{label:h}:{}})).toString("base64url")}]`:void 0,y="string"==typeof d?{testCaseId:d,...f,tracePlaceholder:m}:{...f,tracePlaceholder:m};return{content:[{text:JSON.stringify(y),type:"text"}]}}),W("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.","","ENTITY REFERENCES: When referencing entities by ID, use placeholder syntax so the UI can render clickable links:","- Test cases: @[test-case:<id>] (e.g., @[test-case:fp8f0yzdqqut6bg7cy5euzer])","- Suite runs: @[suite-run:<id>] (e.g., @[suite-run:cm6i7o6ti0000l40350wys0u1])","- Tests: @[test:<id>] (e.g., @[test:wty0g1v58cwrrd8jj6et8nmx])","- Traces: use the tracePlaceholder value returned by capture-trace-proof (e.g., @[trace:eyJi...])","These placeholders will be automatically resolved to clickable links with human-readable labels in the UI.","NEVER show raw entity IDs without wrapping them in @[type:id] syntax."].join("\n"),{markdown:ea.shape.markdown},async({markdown:r})=>{const s=await t.computeDiff(),i=ea.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:cr(),headers:oo(t),path:{runId:r}},(s.client??Jn).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 uo({authHeader:e,contentType:"text/plain",orgId:n,runId:o});await ao({body:s,contentType:"text/plain",uploadUrl:r,errorContext:"diff"}),await po({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"}),ra=({onComplete:e,onRestartRequested:t})=>G(e?{name:"session-control",tools:[W("complete_session",["Call this tool when you have completed your task and the session should end.","Use this instead of waiting for the user to manually terminate.","Only call this when you are confident the task is fully complete."].join("\n"),{summary:ve.string().describe("A brief summary of what was accomplished")},({summary:t})=>{const n="string"==typeof t?t:String(t);return e(),Promise.resolve(`Session complete: ${n}`)})]}:{name:"stably-agent-control",version:"1.0.0",tools:[W("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.'}]})))]});function oa({workingDir:e,packageManager:t,packageSpec:n,targetSection:r}){const{command:o,args:s}=function(e,t,n){const r="npm"===e?"npm":e;return{command:r,args:["npm"===e?"install":"add",..."devDependencies"===n?["bun"===e?"-d":"-D"]:[],..."npm"===r?["--no-fund"]:[],t]}}(t,n,r);y(o,s,{cwd:e,stdio:"pipe",timeout:6e4})}function sa(e){const t=n.join(e,"package.json");return w.existsSync(t)?{path:t,contents:JSON.parse(w.readFileSync(t,"utf-8"))}:null}var ia=["playwright.config.ts","playwright.config.js","playwright.config.mts","playwright.config.mjs","playwright.config.cjs"];function aa(e){return ia.some(t=>w.existsSync(n.join(e,t)))}function ca(e,t){const r=w.readdirSync(e,{withFileTypes:!0}),o=[];for(const s of r){if("node_modules"===s.name||".git"===s.name)continue;const r=n.join(e,s.name);s.isDirectory()?o.push(...ca(r,t)):t.test(s.name)&&o.push(r)}return o}function la(e){let t=n.resolve(e);for(;;){if(aa(t))return t;const r=n.dirname(t);if(r===t)return e;t=r}}function ua(e){const t=Array.from(new Set(e.map(e=>n.resolve(e)))).sort((e,t)=>e.length-t.length),r=[];for(const e of t)r.some(t=>e===t||e.startsWith(`${t}${n.sep}`))||r.push(e);return r}function da(e){return/\b(test|testing|playwright|e2e|stably)\b/i.test(e)}function pa(e,t){for(const r of fa(e,t))if(w.existsSync(n.join(r,"package.json")))return r}function fa(e,t){const r=[];let o=n.resolve(e);const s=n.resolve(t);for(;r.push(o),o!==s;){const e=n.dirname(o);if(e===o)break;o=e}return r}function ha(e){return e?.replace(/^[~^>=<]+/,"")}function ga(e){let t=e;for(let e=0;e<5;e++){if(w.existsSync(n.join(t,"pnpm-lock.yaml")))return"pnpm";if(w.existsSync(n.join(t,"yarn.lock")))return"yarn";if(w.existsSync(n.join(t,"bun.lockb"))||w.existsSync(n.join(t,"bun.lock")))return"bun";if(w.existsSync(n.join(t,"package-lock.json"))||w.existsSync(n.join(t,"npm-shrinkwrap.json")))return"npm";const e=n.dirname(t);if(e===t)break;t=e}return"npm"}var ma=ve.object({commentUrl:ve.string()}),ya=({prContext:e,authHeader:t,orgId:n,onReportPosted:r})=>G({name:"create-report",tools:[W("post_create_report",`Post a test creation report as a GitHub comment on PR #${e.prNumber}.\nCall this tool at the end of test creation to summarize what was created.\nThe report will be posted to: ${e.prUrl}\n\nWHEN TO USE:\n- After you have finished creating test files\n- To provide a summary of the tests created on the PR for visibility\n\nThe report will include:\n- A list of all test files created\n- Your summary of what was tested`,{summary:ve.string().describe("A summary of the tests created. Include what features/flows are tested and any important notes."),filesCreated:ve.array(ve.string()).describe("List of test file paths that were created (relative to workspace root)")},async({summary:o,filesCreated:s})=>{const i=Array.isArray(s)?s:[];Jr.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",er).toString(),a={Authorization:e,"Content-Type":"application/json"};t&&(a["x-stably-org-id"]=t),Jr.debug("Posting create report to GitHub",{prNumber:n,owner:r,repo: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 Jr.error("Failed to post create report",{status:c.status,error:e.slice(0,500)}),new Error(`Failed to post create report: ${c.status} ${e.slice(0,200)}`)}const l=ma.parse(await c.json());return Jr.info("Create report posted successfully",{commentUrl:l.commentUrl}),l}({authHeader:t,orgId:n,prNumber:e.prNumber,owner:e.owner,repo:e.repo,report:s});return r?.(a),Jr.info("[create-report] Report posted successfully",{commentUrl:a.commentUrl}),{content:[{type:"text",text:`✅ Test creation report posted to PR #${e.prNumber}\n\nView the comment: ${a.commentUrl}`}]}}catch(e){const t=e instanceof Error?e.message:String(e);return Jr.error("[create-report] Failed to post report",{error:t}),{content:[{type:"text",text:`❌ Failed to post report to GitHub: ${t}\n\nThe tests were still created successfully, but the PR comment could not be posted.`}],isError:!0}}})]}),ba=["QUEUED","RUNNING","PASSED","FAILED","TIMEDOUT","CANCELLED","INTERRUPTED"],wa=["LOCAL","CI","WEB"],va=["MANUAL","SCHEDULED","UI","API","GITHUB_ACTION","SUITE_RUN"],_a=({authHeader:e,orgId:t,projectId:n})=>G({name:"run-history",tools:[W("list_runs",'List test runs with optional filters for the current project.\nUse this to find runs with autoheal status on specific branches.\n\nCommon use cases:\n- Find failed runs on the current branch: { "branch": "feature-x", "status": "FAILED", "limit": 10 }\n- Find failed runs on master/main: { "branch": "master", "status": "FAILED", "limit": 10 }\n\nReturns an array of runs with their runId, status, autoHealStatus, branch, and timestamps.',{branch:ve.string().optional().describe("Filter by branch name"),status:ve.enum(ba).optional().describe("Filter by status: QUEUED|RUNNING|PASSED|FAILED|TIMEDOUT|CANCELLED|INTERRUPTED"),limit:ve.number().min(1).max(100).optional().describe("Max results (1-100, default 20)"),source:ve.enum(wa).optional().describe("Filter by source: LOCAL|CI|WEB"),trigger:ve.enum(va).optional().describe("Filter by trigger: MANUAL|SCHEDULED|UI|API|GITHUB_ACTION|SUITE_RUN"),suite:ve.string().optional().describe("Filter by suite name"),after:ve.string().optional().describe("Pagination: return runs after this runId"),before:ve.string().optional().describe("Pagination: return runs before this runId")},async({branch:r,status: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,g="string"==typeof a?a:void 0,m="string"==typeof c?c:void 0,y="string"==typeof l?l:void 0,b="string"==typeof u?u:void 0;Jr.info("[run-history] list_runs called",{branch:d,status:p,limit:f});try{const r=await Qn({auth:e,client:cr(),headers:oo(t),query:{projectId:n,branchName:d,status:p,limit:f,source:h,trigger:g,suiteName:m,afterRunId:y,beforeRunId:b}});if(r.error||!r.data){const e=r.response?`API error: ${r.response.status}`:`API error: ${String(r.error)}`;return Jr.error("[run-history] list_runs failed",{error:e}),{content:[{type:"text",text:`Error: ${e}`}],isError:!0}}return Jr.info("[run-history] list_runs success",{runCount:r.data.runs?.length??0,hasMore:r.data.hasMore}),{content:[{type:"text",text:JSON.stringify(r.data,null,2)}]}}catch(e){const t=e instanceof Error?e.message:String(e);return Jr.error("[run-history] list_runs exception",{error:t}),{content:[{type:"text",text:`Error: ${t}`}],isError:!0}}}),W("view_run",'Get detailed information about a specific run including issues and test results.\nUse this after list_runs to examine runs where autoHealStatus is "COMPLETED".\n\nThe response includes:\n- Run metadata (status, branch, timestamps)\n- Issues array with result ("fixed"/"unfixed"), rootCause, and relatedTestIdentifiers\n- Test results with their outcomes\n\nUse this to determine which tests were previously fixed and why.',{runId:ve.string().min(1).describe("The run ID to view (required)")},async({runId:n})=>{const r="string"==typeof n?n:String(n);Jr.info("[run-history] view_run called",{runId:r});try{const n=await Xn({auth:e,client:cr(),headers:oo(t),path:{runId:r},query:{detail:"full"}});if(n.error||!n.data){const e=n.response?404===n.response.status?`Run "${r}" not found`:`API error: ${n.response.status}`:`API error: ${String(n.error)}`;return Jr.error("[run-history] view_run failed",{error:e,runId:r}),{content:[{type:"text",text:`Error: ${e}`}],isError:!0}}return Jr.info("[run-history] view_run success",{runId:r}),{content:[{type:"text",text:JSON.stringify(n.data,null,2)}]}}catch(e){const t=e instanceof Error?e.message:String(e);return Jr.error("[run-history] view_run exception",{error:t,runId:r}),{content:[{type:"text",text:`Error: ${t}`}],isError:!0}}})]}),Ia=e=>e.replace(/Bearer\s+[A-Za-z0-9._-]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{16,}\b/g,"[redacted]").replace(/\bstably_[A-Za-z0-9_-]{16,}\b/g,"[redacted]"),Ta=(e,t)=>({message:Ia(e),status:t?.status,statusText:t?.statusText}),Ea=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"]),Sa=async({authHeader:e,mode:t,maxTurnsOverride:n})=>{const r=cr();Jr.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??Jn).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 Jr.warn("Subagent definitions fetch failed: unauthorized (401)"),await Er(),new Error("Your session has expired or been revoked. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(403===o.response.status)throw Jr.debug("Subagent definitions fetch failed: forbidden (403)"),new Error("Your organization does not have an active subscription. Manage your subscription at https://app.stably.ai or contact your organization admin.");if(o.error)throw Jr.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 Jr.debug("Subagent definitions received",{count:Object.keys(i).length}),i},xa=r.dirname(L(import.meta.url)),Aa=r.join(".claude-plugin","plugin.json"),Ca=[r.join("packages","agent-plugin","stably-plugin-cli"),r.join("agent-plugin","stably-plugin-cli")];function Ra(e){return _(r.join(e,Aa))}var{zStablyYaml:Pa}=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}}(ge),ka=async(e,t)=>{try{const n=await gr(e,t);if(!n)return void Jr.debug(`No ${t} found`);const r=await Z(n,"utf-8");if(!r.trim())return;return r.length>1e4?(Jr.warn(`${t} exceeds max length (${r.length} > 10000), truncating`,{path:n}),{content:r.slice(0,1e4),path:n}):(Jr.debug(`Loaded ${t} rules`,{path:n,contentLength:r.length}),{content:r,path:n})}catch(e){return void Jr.warn(`Failed to read ${t}`,{error:e})}},Ua=/\bplaywright-cli\b/,La=/\bplaywright-cli\s+run-test\b/,Da=/\$\{process\.env\.([a-zA-Z_][a-zA-Z0-9_]*)\}/g,$a=e=>/^[A-Za-z0-9_./:@=-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`,Oa=".playwright-cli";function Na(e,t){return t?`${e}-${t}`:e}function Ba(e){if(e&&"object"==typeof e&&"agent_id"in e){const t=e.agent_id;return"string"==typeof t?t:void 0}}var ja=ge.object({verdict:ge.enum(["PASS","FAIL","INCONCLUSIVE"]),steps:ge.array(ge.string()).min(1),reason:ge.string().nullable(),evidence:ge.array(ge.string())}).superRefine((e,t)=>{"PASS"===e.verdict||e.reason&&0!==e.reason.trim().length||t.addIssue({code:ge.ZodIssueCode.custom,path:["reason"],message:"reason is required for FAIL and INCONCLUSIVE verdicts"})}),Ma=/\bmcp__playwright-mcp__[a-z0-9_]+\b/gi,Fa=/\.playwright-mcp(?:\/[^\s"'`)\]]*)?/gi,Ha=/\bplaywright[\s_-]?mcp\b/gi;function Ga(e){return e.replace(Ma,"browser_tool").replace(Fa,"verification-artifact").replace(Ha,"browser automation")}function Wa(e){return{...e,steps:e.steps.map(e=>Ga(e)),reason:e.reason?Ga(e.reason):null,evidence:e.evidence.map(e=>Ga(e))}}function Ya(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=ja.parse(t)}catch{}return n}var Va=["Bash","Read","Write","Edit","Glob","Grep","Task","Skill"],za=["Task","Skill"],Ka=["Bash","Read","Write","Edit","Glob","Grep","mcp__session-control"],qa=e=>{if("EPIPE"!==e.code)throw e},Ja="__main__",Qa=[3e3,5173,4173,8080,4200,8e3],Xa=/\b(TEST_EMAIL|TEST_PASSWORD|auth|authentication|credentials|login|log in|sign in)\b/i,Za=/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/i,ec=/playwright[\s_-]?mcp/i,tc=e=>"mcp__auto-heal-report__generate-report"===e;async function nc(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 rc(e){return new Promise(t=>{const n=new z.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 oc=async(e,t,n)=>{const r=n?"[Y/n]":"[y/N]",o=(await e.question(`${q.cyan("?")} ${t} ${q.gray(r)} `)).trim().toLowerCase();return o?"y"===o||"yes"===o:n},sc=async e=>{if("single"===e.mode){const t=Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt;Jr.initSession(t||"create-from-diff")}else if("verify"===e.mode){const t=Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt;Jr.initSession(t||"verify")}else"fix"===e.mode&&Jr.initSession(`fix-${e.runId}`);Jr.info("Agent session starting",{mode:e.mode}),process.stdout.on("error",qa),process.stderr.on("error",qa);const a=e=>{if("EPIPE"!==e.code)throw e};process.on("uncaughtException",a),Jr.debug("Checking authentication");const c=await eo({autoLogin:"chat"===e.mode||"init"===e.mode}),l=no(c);Jr.debug("Authentication resolved",{authType:c.type});const u="oauth"===c.type?c.auth.context.orgId:void 0,d=r.resolve(process.cwd()),p="fix"!==e.mode,f=r.join(d,".env"),h=p&&v.existsSync(f)&&v.statSync(f).isFile(),g=h?t(v.readFileSync(f,"utf8")):{};Jr.debug("Environment file",{path:f,exists:h,variableCount:Object.keys(g).length});const y="chat"!==e.mode&&"init"!==e.mode,b="chat"===e.mode,I="chat"===e.mode||"init"===e.mode,S="single"===e.mode,x="verify"===e.mode,A=S||x;let C,R=new jo;"init"===e.mode&&(C=e.initPreferences??await async function(){if(!process.stdin.isTTY||!process.stdout.isTTY)return{googleAuth:!0,emailPackage:!1};const e=K({input:process.stdin,output:process.stdout});try{return{googleAuth:await oc(e,"Include Google Auth test helper guidance? (recommended)",!0),emailPackage:await oc(e,"Install @stablyai/email for inbox testing?",!1)}}finally{e.close()}}());const P="chat"===e.mode?e.getHelpText:void 0,k="verify"===e.mode?(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt).trim():"";let U="verify"===e.mode?e.url?.trim()||function(e){const t=Array.isArray(e)?e.join(" "):e,n=e=>e.replace(/[),.;!?]+$/,""),r=e=>{const t=n(e);try{return new URL(t).toString()}catch{return}},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&&U&&Jr.info("[verify] Using URL extracted from prompt",{url:U}),"verify"!==e.mode||U||(U=await async function(){for(const e of Qa)if(await rc(e))return`http://localhost:${e}`}(),U?Jr.info("[verify] Detected local application URL",{url:U}):Jr.info("[verify] No common localhost dev server detected")),"verify"===e.mode&&!1!==e.interactive){const e=await async function({envFilePath:e,envFromFile:t,initialUrl:n,verifyPromptText:o,workingDir:s}){if(!process.stdin.isTTY||!process.stdout.isTTY)return{resolvedUrl:n};const i=r.join(s,"STABLY.md"),a=v.existsSync(i),c=a?await v.promises.readFile(i,"utf8").catch(()=>{}):void 0;let l=n?.trim()||void 0;const u=!l,d=(({envEmail:e,envPassword:t,promptIncludesEmail:n,stablyMdContent:r})=>!Boolean(e?.trim()&&t?.trim())&&!n&&!(e=>!!e&&Xa.test(e))(r))({envEmail:process.env.TEST_EMAIL??t.TEST_EMAIL,envPassword:process.env.TEST_PASSWORD??t.TEST_PASSWORD,promptIncludesEmail:Za.test(o),stablyMdContent:c}),p=!a;if(!u&&!d&&!p)return{resolvedUrl:l};const f=K({input:process.stdin,output:process.stdout}),h=async(n,r)=>{const o=v.existsSync(e)?await v.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 v.promises.writeFile(e,c,"utf8"),t[n]=r};try{if(u){const e=(await f.question("Starting URL (optional, Enter to auto-infer): ")).trim();e&&(l=e)}if(d&&await oc(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 oc(f,"No STABLY.md found. Create one at repository root for project instructions?",!0)){const e=["# STABLY.md","","Project instructions for Stably agent runs.","","## Verify Notes","- Keep verification scope to requested behavior only.","- Use TEST_EMAIL and TEST_PASSWORD env vars for authenticated flows.","","## Special Instructions","- Add project-specific constraints here.",""].join("\n");await v.promises.writeFile(i,e,"utf8");const t=(await f.question("Special verify instruction to append to STABLY.md (optional): ")).trim();if(t){const e=await v.promises.readFile(i,"utf8"),n=/(^|\n)## Special Instructions\s*$/m.test(e)?`${e}${e.endsWith("\n")?"":"\n"}- ${t}\n`:`${e}${e.endsWith("\n")?"":"\n"}\n## Special Instructions\n- ${t}\n`;await v.promises.writeFile(i,n,"utf8")}}return{resolvedUrl:l}}finally{f.close()}}({envFilePath:f,envFromFile:g,initialUrl:U,verifyPromptText:k,workingDir:d});U=e.resolvedUrl?.trim()||U}"verify"!==e.mode||U||Jr.warn("No verify URL provided and no local app detected on common ports. The agent will try to infer a URL from code/config.");const D={log:[],promptDisplay:V(e).with({mode:"chat"},()=>"Ask Stably to build tests for you").with({mode:"init"},()=>"Setting up Playwright and Stably SDK").with({mode:"fix"},()=>"Fixing broken tests").with({mode:"single"},e=>{const t=(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt)?.trim();return t||"Creating tests from PR/branch changes"}).with({mode:"verify"},e=>{const t=(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt)?.trim();return t||"Verifying application"}).exhaustive(),status:"running"};let $,O,N,B,j=y,M=!1,F=!1,H=0,G=0,W=!1;const z=[];let J,X,ee=[],te=!1,ne=!1,re=0;const oe=new Map,se=[],ie=e=>{se.push(e)},ae=new Map;let ce=null,le=!1,ue=!1;const de=Date.now();let pe,fe="fix"===e.mode?{suiteId:e.runId,phase:"initializing",totalTests:null,fixedTests:0,failedTests:0,currentTestDescription:null,lastTestDescription:null,startedAt:de,endedAt:null,isError:!1,updatedAt:de,recentActivity:[],workers:[{id:Ja,testDescription:"Orchestrator",workerType:"main",status:"running",summary:null,startedAt:de,endedAt:null,activity:[]}]}:null;const he=new Set,ge=(e,t)=>{if(!fe)return;const n=fe.workers.map(n=>{if(n.id!==e)return n;const r=[...n.activity,{...t,timestamp:Date.now()}].slice(-15);return{...n,activity:r}});be({workers:n})},me=e=>{if(!fe)return;const t=[...fe.recentActivity,{...e,timestamp:Date.now()}].slice(-10);be({recentActivity:t})},ye=e=>(fe?.workers??[]).map(t=>t.id===Ja?{...t,status:e?"failed":"succeeded",endedAt:t.endedAt??Date.now()}:"running"===t.status?{...t,status:"failed",endedAt:Date.now()}:t),be=e=>{fe&&!pe?.isClosed&&(fe={...fe,...e,updatedAt:Date.now()},pe?.sendProgress(fe))},we=async t=>{if("fix"===e.mode){if("STARTED"===t){if(le)return;le=!0}else{if(ue)return;ue=!0}try{await(async({authHeader:e,orgId:t,runId:n,status:r})=>{const o=await(s={auth:e,body:{status:r},client:cr(),headers:oo(t),path:{runId:n}},(s.client??Jn).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{}}},ve=Date.now();let _e,Re=null;const ke=e=>{Re&&!_e?.isClosed&&(Re={...Re,...e,updatedAt:Date.now()},_e?.sendProgress(Re))},Le=e=>{if(!Re)return;const t=[...Re.recentActivity,{...e,timestamp:Date.now()}].slice(-10);ke({recentActivity:t})};let De;const $e=(e.mode,!0);Jr.info("[session] Checking session creation",{mode:e.mode,shouldCreateSession:$e});try{Jr.info("[session] Creating progress session",{mode:e.mode,projectId:to(c)});const t=await async function({agentMode:e,authHeader:t,orgId:n,projectId:r,runId:o,fetchImpl:s=fetch,apiUrl:i=er}){const a=Vo[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:to(c),..."fix"===e.mode?{runId:e.runId}:{}}),{sessionId:n,sessionMode:r}=t;if(De=n,A){const t="single"===e.mode||"verify"===e.mode?Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt:null,r=Mo(d);Re={sessionId:n,phase:"initializing",startedAt:ve,endedAt:null,isError:!1,updatedAt:ve,currentActivity:null,filesCreated:[],recentActivity:[],prompt:t||null,environment:{gitBranch:r?.branch??null,workingDirectory:d,nodeVersion:process.version,cliVersion:Zn}},_e=new ho({authHeader:l,orgId:u,sessionId:n,onUserMessage:e=>{R&&(Jr.info("[ws] Injecting web UI message into agent",{contentLength:e.length}),Le({type:"user_message",summary:e}),Ge({text:`[Web] ${e}`}),R.pushText(`[Message from web UI user]: ${e}`),j||(j=!0,Qe({status:"running"})))}}),_e.start(),ke({phase:"initializing"})}Jr.info(`[${r}] Progress session created`,{sessionId:n})}catch(e){const t=e instanceof Error?e.message:String(e);Jr.warn(`[progress] Session creation failed (non-fatal): ${t}`)}const Oe={current:e=>{}},Ne={current:async()=>{}};let Be;const{addSubagentActivity:je,addSubagentStart:Me,addTool:Fe,appendText:He,appendUserMessage:Ge,cleanup:We,setExiting:Ye,setRunningLabel:Ve,setStatus:ze,setSubagentStatus:Ke,updateFixProgress:qe}=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=()=>Ae(o,{inverse:!0,children:" "}),d=(({Box:e,Text:t,useInput:n},r,o)=>function({onChoice:s,prompt:i}){const[a,c]=Ie(0),[l,u]=Ie(!1),[d,p]=Ie(""),f=[{label:"Yes, allow this once",value:"allow"},{label:"Yes, always allow for this session",value:"always"},{label:"No, tell AI what to do differently",value:"deny_with_message"}];n((e,t)=>{if(l)return t.return?void 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=cs(i.toolName),g=is(i.toolName,i.input);return Ce(e,{borderColor:"yellow",borderStyle:"round",flexDirection:"column",marginTop:1,paddingX:1,paddingY:0,children:[Ae(t,{bold:!0,color:"yellow",children:"Permission Required"}),Ce(e,{flexDirection:"column",marginTop:1,children:[Ae(t,{color:"gray",dimColor:!0,children:h}),null!=g&&Ce(t,{color:"gray",children:[" ",g]})]}),null!=i.decisionReason&&Ae(e,{marginTop:1,children:Ce(t,{color:"gray",children:["Reason: ",i.decisionReason]})}),Ce(e,l?{flexDirection:"column",marginTop:1,children:[Ae(t,{color:"gray",children:"Enter message for AI (press Enter to submit, Esc to cancel):"}),Ce(t,{children:[Ae(t,{color:"yellow",children:">"})," ",d,Ae(r,{})]})]}:{flexDirection:"column",marginTop:1,children:[Ae(t,{color:"gray",children:"Use ↑↓ arrows or number keys to select:"}),f.map((e,n)=>Ae(t,{children:Ce(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?Ce(r,{color:"gray",dimColor:!0,children:["• ",e.content]},e.id):"tool_result"===e.kind||"text"===e.kind?Ae(r,{color:"gray",children:e.content},e.id):null,u=({progress:e})=>{const[n,o]=Ie(Date.now());Ee(()=>{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 Ae(t,{flexDirection:"column",children:Ce(r,{children:[Ae(r,{color:p,bold:!0,children:d}),Ae(r,{color:"gray",children:h}),Ce(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 Ce(t,{flexDirection:"column",children:[Ce(r,{color:c,bold:!0,children:[l," in ",a]}),null!==e.totalTests&&Ce(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 Ce(t,{flexDirection:"column",marginTop:1,children:[Ce(r,{children:[Ae(r,{color:s,bold:!0,children:"Agent"}),o.description?Ce(r,{color:"gray",children:[" (",o.description,")"]}):null]}),o.activities.length>0&&Ae(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?Ce(r,{color:"gray",dimColor:!0,children:["• ",e.content]},e.id):"tool_result"===e.kind?Ae(r,{color:"gray",children:e.content},e.id):"user"===e.kind?Ce(r,{color:"cyan",children:["You: ",e.content]},e.id):Ae(r,{children:e.content},e.id)},f=(e,t)=>{if(t<=0)return 0;let n=t-1;for(;n>0&&/\s/.test(e[n]);)n--;for(;n>0&&!/\s/.test(e[n-1]);)n--;return n},h=(e,t)=>{if(t>=e.length)return e.length;let n=t;for(;n<e.length&&!/\s/.test(e[n]);)n++;for(;n<e.length&&/\s/.test(e[n]);)n++;return n},g=(e,t)=>{if(t<=0)return 0;const n=e.lastIndexOf("\n",t-1);return-1===n?0:n+1},m=(e,t)=>{const n=e.indexOf("\n",t);return-1===n?e.length:n},y=3;return function({onExit:c,onPermissionChoice:l,onSend:b,showSpinnerImmediately:w,state:v}){const[_,I]=Ie({value:"",cursor:0}),T=_.value,E=_.cursor,S=Te(!1),x=Te(void 0),[A,C]=Ie(!1),[R,P]=Ie(!1),k=Te(0),U=Te(!1),L=!!v.permissionPrompt,D=(({hasPermissionPrompt:e,inputValue:t,showExitMessage:n,termProgram:r})=>"vscode"===r&&(e||t.length>0||n))({hasPermissionPrompt:L,inputValue:T,showExitMessage:A,termProgram:process.env.TERM_PROGRAM}),$=v.log.at(-1),O="text"===$?.kind&&"running"===v.status,N=v.log.findIndex(e=>"subagent"===e.kind&&"running"===e.subagent?.status),B=s&&!R,j=D?0:-1!==N?N:O?v.log.length-1:v.log.length,M=B&&"running"===v.status?Math.min(j,k.current):j;Ee(()=>{v.log.length<k.current&&(k.current=0),M>k.current&&(k.current=M)},[v.log.length,M]);const F=v.log.slice(0,k.current),H=v.log.slice(k.current),G=B?F.filter(e=>"tool"!==e.kind&&"tool_result"!==e.kind):F,W=(()=>{if(!B)return H;let e=0;const t=[];for(let n=H.length-1;n>=0;n--){const r=H[n];"tool"===r.kind||"tool_result"===r.kind?("tool"===r.kind&&e++,e<=y&&t.unshift(r)):t.unshift(r)}return t})(),Y=Se(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}),Ee(()=>{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):"[1;5H"!==n&&"[1;5~"!==n?"[1;5F"!==n&&"[4;5~"!==n?"[H"!==n&&"[1~"!==n&&"OH"!==n&&"[7~"!==n?"[F"!==n&&"[4~"!==n&&"OF"!==n&&"[8~"!==n||I(e=>({...e,cursor:m(e.value,e.cursor)})):I(e=>({...e,cursor:g(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=T.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=xe(()=>"running"===v.status?Ae(a,{label:v.runningLabel??"Working"}):"success"!==v.status?Ae(r,{color:"red",children:"✖ Failed"}):void 0,[v.runningLabel,v.status]),z=!(w||!b||"running"!==v.status||0!==v.log.length||v.resultText||v.errorText),K="running"===v.status&&!z||v.log.length>0||v.resultText||v.errorText||"running"!==v.status;return Ce(t,{flexDirection:"column",children:[D?Ce(t,{flexDirection:"column",flexShrink:0,children:[Ae(r,{color:"cyan",bold:!0,children:"Stably Agent"}),Ae(t,{flexDirection:"column",marginTop:1,children:Ae(r,{color:"gray",children:v.promptDisplay})})]}):Ae(n,{items:["header"],children:()=>Ce(t,{flexDirection:"column",flexShrink:0,children:[Ae(r,{color:"cyan",bold:!0,children:"Stably Agent"}),Ae(t,{flexDirection:"column",marginTop:1,children:Ae(r,{color:"gray",children:v.promptDisplay})})]},"header")}),G.length>0&&Ae(n,{items:G,children:e=>p(e,B)}),W.length>0&&Ae(t,{flexDirection:"column",children:W.map(e=>p(e,B))}),B&&H.length>W.length&&Ce(r,{color:"gray",dimColor:!0,children:["↕ ",H.length-W.length," tool calls hidden (Ctrl+O to expand)"]}),R&&s&&"running"===v.status&&Ae(r,{color:"gray",dimColor:!0,children:"↕ Showing all tool calls (Ctrl+O to collapse)"}),"error"===v.status&&v.errorText&&Ae(t,{marginTop:1,children:Ae(r,{color:"red",children:v.errorText})}),"success"===v.status&&v.resultText&&Ae(t,{marginTop:1,children:Ae(r,{children:v.resultText})}),K&&Ae(t,{flexDirection:"column",flexShrink:0,marginTop:1,children:"running"===v.status&&v.fixProgress?Ce(t,{flexDirection:"column",children:[Ce(t,{children:[Ae(a,{}),Ae(r,{children:" "}),Ae(u,{progress:v.fixProgress})]}),("fixing"===v.fixProgress.phase||"debugging"===v.fixProgress.phase)&&v.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 Ce(t,{flexDirection:"column",children:[Ce(r,{children:[" ",Ae(a,{}),Ce(r,{color:"gray",children:[n.description||n.subagentType||"worker",s>0?` (${s} ${1===s?"cycle":"cycles"})`:""]})]}),c&&Ce(r,{color:"gray",dimColor:!0,children:[" • ",c.content]}),l&&Ce(r,{color:"gray",dimColor:!0,children:[" ",l]})]},e.id)})]}):"success"!==v.status&&"error"!==v.status||!v.fixProgress?V:Ae(d,{progress:v.fixProgress})}),null!=v.permissionPrompt&&null!=l&&Ae(i,{onChoice:l,prompt:v.permissionPrompt}),null!=b&&null==v.permissionPrompt&&!v.isExiting&&Ce(t,{borderColor:"gray",borderStyle:"round",flexDirection:"column",flexShrink:0,marginTop:1,paddingX:1,paddingY:0,children:[Ae(r,{color:"gray",children:"Type a message and press Enter. Press Ctrl+C to exit."}),Ce(r,{children:[Ae(r,{color:"yellow",children:">"})," ",T.slice(0,E),Ae(e,{}),T.slice(E)]})]}),A&&Ce(t,{marginTop:1,flexDirection:"column",children:[Ae(r,{color:"yellow",children:"Press Ctrl+C again to exit"}),Br&&Ce(r,{color:"gray",children:["Debug log: ",Hr]})]})]})}})({Cursor:u,inkComponents:{Box:n,Static:r,Text:o,useInput:i},isRawModeSupported:a,PermissionPrompt:d,Spinner:({label:e})=>{const[t,n]=Ie(0);return Ee(()=>{if(!c)return;const e=setInterval(()=>n(e=>(e+1)%l.length),80);return()=>clearInterval(e)},[]),Ce(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)=>{}},g=s(Ae(p,{onExit:t?.onExit,onPermissionChoice:(e,t)=>h.current(e,t),onSend:t?.onSend,showSpinnerImmediately:t?.showSpinnerImmediately,state:f}),{exitOnCtrlC:!1}),m=()=>{f={...f},g.rerender(Ae(p,{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"}],m())},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],m()}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});m()},addTool:({rawName:e,toolInput:t})=>{const n=as(e,t),r=n??cs(e),o=n?void 0:is(e,t),s=o?`${r} (${o})`:r;f.log=[...f.log,{content:s,id:f.log.length,kind:"tool"}],m()},addToolResult:({message:e})=>{f.log=[...f.log,{content:e,id:f.log.length,kind:"tool_result"}],m()},appendText:({text:e})=>{if(!e)return;const t=f.log.at(-1),n="text"!==t?.kind?e.replace(/^\s*\n+/,""):e;f.log="text"===t?.kind?[...f.log.slice(0,-1),{...t,content:`${t.content}${n}`}]:[...f.log,{content:n,id:f.log.length,kind:"text"}],m()},appendUserMessage:y,cleanup:async()=>{const e=g.waitUntilExit();g.unmount(),await e},setExiting:()=>{f.isExiting=!0,m()},setRunningLabel:({label:e})=>{f.runningLabel=e,m()},setStatus:({error:e,result:t,status:n})=>{f.errorText=e,f.resultText=t,f.status=n,m()},setSubagentStatus:({toolUseId:e,status:t})=>{const n=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],m(),"complete"!==t&&"error"!==t||b.delete(e))},showPermissionPrompt:e=>new Promise(t=>{h.current=(n,r)=>{if(f.permissionPrompt=void 0,m(),"allow"===n)t({behavior:"allow",updatedInput:e.input});else if("always"===n)t({behavior:"allow",updatedInput:e.input,updatedPermissions:e.suggestions});else{const e=r??"User denied this action";y({text:e}),t({behavior:"deny",message:e,interrupt:!1})}},f.permissionPrompt={...e,resolve:t},m()}),updateFixProgress:t?.isFixMode?e=>{f.fixProgress&&(f.fixProgress={...f.fixProgress,...e},m())}:void 0}})(D,"init"===e.mode?{onExit:()=>Ne.current(),onSend:e=>Oe.current(e),showSpinnerImmediately:!0}:"chat"===e.mode?{onExit:()=>Ne.current(),onSend:e=>Oe.current(e)}:"fix"===e.mode?{onExit:()=>Ne.current(),isFixMode:!0}:{onExit:()=>Ne.current()});let Je=D.status;const Qe=({error:e,result:t,status:n})=>{Je=n,ze({error:e,result:t,status:n})};let Xe;x&&(He({text:"Starting verification...\n"}),He(U?{text:`Target URL: ${U}\n`}:{text:"Target URL: auto-detect (agent may infer from project config)\n"}),Ve({label:"Calibrating verification flow..."})),Oe.current=e=>{const t=e.trim();if(b&&!Jr.getLogFilePath()&&Jr.initSession(t||"chat"),Jr.debug("User message",{text:t}),"/help"===t){j&&R&&(M=!0,$?.interrupt?.(),R.allowNextTurn(),j=!1),"running"===Je&&Qe({status:"success"}),Ge({text:e});const t=P?.();return void He({text:t??"Help is not available in this session."})}const n=N||F&&j;if(b&&(H+=1,B=void 0,n||(W=!1,Ve({label:void 0}))),R){if(n)return Qe({status:"running"}),Ge({text:e}),void z.push(e);if(!F||j||N||(F=!1),j)return Qe({status:"running"}),Ge({text:e}),R.pushText(e),void(G+=1);Qe({status:"running"}),Ge({text:e}),ie({role:"user",content:e,timestamp:(new Date).toISOString()}),R.pushText(e),j=!0}};let Ze="",et="";const tt=[],nt=[],rt=[];let ot;const st=await(async e=>{try{const t=await gr(e,"stably.yaml");if(!t)return void Jr.debug("No stably.yaml found");const n=await Z(t,"utf-8");if(!n.trim())return;const r=Pe(n),o=Pa.parse(r.toJS()),s=o.agent?.fix?.maxTurnsPerIssue,i=o.agent?.fix?.maxParallelWorkers,a=!!o.agent?.fix?.rules;return Jr.debug(`Loaded stably.yaml: maxTurnsPerIssue=${s??"default"}, maxParallelWorkers=${i??"default"}, hasRules=${a}`,{path:t,config:o.agent}),o}catch(e){return void Jr.warn("Failed to parse stably.yaml",{error:e})}})(d),it=st?.agent?.fix?.skipAfterConsecutiveUnfixed,at=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 Xo(e,"output-flag"),{path:e,source:"output-flag"}}const r=qo(n);if(r){const e=await async function(e){try{const t=(await Z(e,"utf-8")).match(/testDir:\s*['"]([^'"]+)['"]/);return t?.[1]}catch{return}}(r);if(e){const t=o(s(r),e);if(Qo(t))return Xo(t,"playwright.config.ts"),{path:t,source:"playwright.config.ts"}}}for(const e of Jo){const t=i(n,e);if(Qo(t))return Xo(t,"auto-detected"),{path:t,source:"auto-detected"}}return Xo(n,"cwd-fallback"),{path:n,source:"cwd-fallback"}}(d,e.outputDir);return ot=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: ${ot}]`}var t;if("verify"===e.mode)return function(e,t){const n=(Array.isArray(e)?e.join(" "):e).trim()||"Verify the application behavior.",r=t?.trim();return r?`Starting URL: ${r}\nURL policy: treat this as the source of truth and do not switch domains unless the user explicitly asks.\n\nVerification prompt: ${n}`:n}(e.prompt,U);if("fix"===e.mode)try{Jr.info("[fix] Fetching autoheal context",{runId:e.runId,skipAfterConsecutiveUnfixed:it});const t=Date.now(),{context:n,autohealReportUrl:r,skippedTests:o}=await(async({authHeader:e,orgId:t,runId:n,skipAfterConsecutiveUnfixed:r})=>{Jr.debug("Fetching autoheal context",{runId:n,skipAfterConsecutiveUnfixed:r});const o=await(s={auth:e,client:cr(),headers:oo(t),path:{runId:n},query:null!=r?{skipAfterConsecutiveUnfixed:r}:{}},(s.client??Jn).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-context",...s}));var s;if(404===o.response.status)throw Jr.warn("Autoheal context not found",{runId:n,status:404}),new Error(`Run ID "${n}" was not found.`);if(401===o.response.status)throw Jr.warn("Autoheal context fetch unauthorized",{runId:n,status:401}),new Error("Unauthorized: failed to fetch autoheal context (401).");if(422===o.response.status)throw Jr.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=so.safeParse(o.data);if(e.success)return Jr.debug("Autoheal context fetched successfully",{runId:n,contextSize:e.data.context.length,skippedTestCount:e.data.skippedTests?.length??0}),{context:e.data.context,autohealReportUrl:e.data.autohealReportUrl,skippedTests:e.data.skippedTests??[]};throw Jr.warn("Autoheal context response invalid",{runId:n}),new Error("Autoheal context response missing or invalid context.")}throw Jr.warn("Autoheal context fetch failed",{runId:n,error:o.error}),new Error("Failed to fetch autoheal context")})({authHeader:l,orgId:u,runId:e.runId,skipAfterConsecutiveUnfixed:it});if(Jr.info("[fix] Autoheal context fetched",{runId:e.runId,durationMs:Date.now()-t,contextLength:n.length,skippedTestCount:o.length}),Xe=r,o.length>0){Jr.info(`[fix] Skipping ${o.length} test(s) that failed to be fixed ${it}+ consecutive times`);for(const e of o)Jr.info(`[fix] Skipped: ${e.testIdentifier} — ${e.testTitle} (unfixed ${e.consecutiveUnfixedCount}x)`)}return n.includes("No failing tests to fix (all were skipped).")&&(Jr.info("[fix] All failing tests were skipped — nothing to fix"),Qe({status:"success",result:`All failing tests skipped (unfixed ${it}+ consecutive times). Nothing to fix.`}),await We(),process.exit(0)),pe||(Jr.info("[fix] Creating WebSocket progress reporter"),pe=new fo({authHeader:l,orgId:u,runId:e.runId,onUserMessage:e=>{if(Jr.info("[ws] Injecting web UI message into fix agent",{contentLength:e.length}),ge(Ja,{type:"user_message",summary:e}),me({type:"user_message",summary:e}),Ge({text:`[Web] ${e}`}),!j)return R.pushText(`[Message from web UI user]: ${e}`),j=!0,void R.allowNextTurn();te||Date.now()-re<2e3?R.pushText(`[Message from web UI user]: ${e}`):(ee.push(e),J&&clearTimeout(J),J=setTimeout(()=>{J=void 0;const e=[...ee];ee=[],re=Date.now(),an(e)},500))}}),pe.start(),be({phase:"initializing"})),we("STARTED"),n}catch(e){const t=e instanceof Error?e.message:"Failed to fetch autoheal context.";Jr.error("[fix] Failed to fetch autoheal context",{error:t}),Qe({error:t,status:"error"}),await We(),process.exit(1)}if("init"===e.mode){const e=C??{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""})(),ct=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(_(t))for(const e of Fo){const n=r.join(t,`playwright.config${e}`);if(_(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([Wo({defaultContent:"Unable to read directory",dirName:"working directory",dirPath:t}),Wo({defaultContent:"Unable to read directory",dirName:"tests directory",dirPath:n}),Wo({defaultContent:"Directory does not exist yet",dirName:"helpers directory",dirPath:o}),Wo({defaultContent:"Directory does not exist yet",dirName:"assets directory",dirPath:s}),Go({defaultContent:"File does not exist or could not be read",fileName:a,filePath:i}),Go({defaultContent:"File does not exist or could not be read",fileName:"seed.spec.ts",filePath:c})]);return{absolutePath:t,directories:{assets:p,helpers:d,root:l,tests:u},files:{playwrightConfig:f,playwrightConfigFilename:a,seedSpec:h}}}(d),lt="fix"===e.mode?st?.agent?.fix?.maxTurnsPerIssue:void 0,ut=st?.agent?.fix?.maxParallelWorkers??3,dt="fix"===e.mode?st?.agent?.fix?.rules:void 0,pt=st?.agent?.fix?.maxBudgetUsd??50,ft="verify"===e.mode?e.maxBudgetUsd??5:void 0,ht="fix"===e.mode?pt:x?ft:void 0,gt="init"!==e.mode,mt="single"===e.mode?await(async e=>{const t=await ka(e,"STABLY-CREATE.md");return t?.content})(d):void 0,yt=await(e=>ka(e,"STABLY.md"))(d),bt=yt?.content;x&&(Ve({label:"Assembling verification context..."}),He({text:"Assembling workspace context...\n"})),Jr.info("[fix] Fetching system prompt and subagent definitions",{mode:e.mode,maxTurnsOverride:lt,maxBudgetUsd:ht,hasCustomRules:!!dt,hasCreateRules:!!mt,hasStablyMd:!!bt,stablyMdPath:yt?.path}),yt&&Jr.info(`STABLY.md loaded (${yt.content.length} chars)`,{path:yt.path});const wt=await ro(),vt=wt?Object.keys(wt.variables):[],_t=[...new Set([...Object.keys(g),...vt])],It=Date.now(),[{systemPrompt:Tt,prContext:Et},St]=await Promise.all([Yo({allowedEnvVars:_t,mode:e.mode,workspaceInfo:ct,authHeader:l,customHeader:"single"===e.mode?e.customHeader:void 0,maxParallelWorkers:ut}),gt?Sa({authHeader:l,mode:e.mode,maxTurnsOverride:lt}):Promise.resolve({})]);Jr.info("[fix] System prompt and subagents fetched",{durationMs:Date.now()-It,systemPromptSize:Tt.length,subagentCount:Object.keys(St).length,maxTurnsOverride:lt??"default",hasPrContext:!!Et});const xt={...g,...process.env},At={};for(const[e,t]of Object.entries(xt))Ea.has(e)||void 0===t||(At[e]=t);const Ct=!0;Jr.debug("AI proxy configuration",{useStablyAiProxy:Ct,wantsBypassProxy:!1,wantsUseOllama:!1}),Jr.info("[fix] Acquiring AI proxy key",{useStablyAiProxy:Ct});const Rt=Date.now(),Pt=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??Jn).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:Ta(e,a)}}return i.data?{key:i.data.key}:{error:Ta("No data in response",a)}}catch(e){const t=e instanceof Error?e.message:"Unknown error";return{error:Ta(t)}}var s}({auth:l,client:cr(),source:"cli"}),kt=Pt?.key;if(Jr.info("[fix] AI proxy key acquired",{durationMs:Date.now()-Rt,success:!!kt,hasError:!!Pt?.error}),!kt){const e=Pt?.error?.message?`Unable to make AI calls: ${Pt.error.message}`:"Unable to make AI calls. Check if you are authenticated.";Jr.warn("Failed to get proxy API key",{error:Pt?.error?.message}),Qe({error:e,status:"error"}),await We(),Jr.flush(),Jr.printLogFileInfo(),process.exit(1)}Jr.debug("Proxy API key acquired",{success:!!kt});const Ut="init"===e.mode,Lt="fix"===e.mode,Dt=Ut?void 0:function(e){let t;!function(e){const t=i(e,".gitignore");try{if(_(t)){const e=T(t,"utf-8"),n=e.split("\n").map(e=>e.trim());if(n.includes(Oa)||n.includes(`/${Oa}`))return;const r=e.length>0&&!e.endsWith("\n");E(t,`${r?"\n":""}${Oa}\n`)}}catch{}}(process.cwd());const n=new Set;let r;const o=()=>{var t;return r||(r="auto"!==(t=e.sessionName)?t:`stably-${process.pid}`),r};return{hook:async r=>{const a=r&&"object"==typeof r&&"tool_input"in r&&r.tool_input&&"object"==typeof r.tool_input&&"command"in r.tool_input&&"string"==typeof r.tool_input.command?r.tool_input.command:"";if(!Ua.test(a))return{decision:"approve"};const c=/\bplaywright-cli\s+close\b/.test(a),l=/\bplaywright-cli\s+(?!close\b)\w/.test(a);if(c){if(!l&&0===n.size)return{decision:"approve"};const e=Ba(r),t=Na(o(),e);n.delete(t)}if(!t)try{t=await async function(){const e=i(s(L(import.meta.url)),"playwright-cli.js");if(_(e))return e;try{return Ue.resolve("@stablyai-internal/playwright-cli/playwright-cli.js")}catch{}return new Promise((e,t)=>{m("which",["playwright-cli"],(n,r)=>{!n&&r.trim()?e(r.trim()):t(new Error("playwright-cli not found. Ensure @stablyai-internal/playwright-cli is installed or playwright-cli is on PATH."))})})}(),Jr.info("[playwright-cli-hook] Resolved binary",{path:t})}catch(e){const t=e instanceof Error?e.message:String(e);return{decision:"block",reason:t,systemMessage:`playwright-cli binary not found: ${t}`}}const u=Ba(r),d=Na(o(),u),p=/\bplaywright-cli\s+open\b/.test(a);if((!c||l)&&!n.has(d))if(p)n.add(d);else{n.add(d),Jr.info("[playwright-cli-hook] First browser command, starting daemon...",{sessionName:d,agentId:u});const r=await async function(e,t,n){const r=["open",`-s=${t}`];return n&&r.push("--headed"),r.push("--browser=chrome"),Jr.info("[playwright-cli-hook] Starting daemon",{bin:e,args:r}),new Promise(t=>{m(process.execPath,[e,...r],{timeout:3e4},(e,n,r)=>{if(e)return Jr.error("[playwright-cli-hook] Failed to start daemon",{error:e.message,stderr:r}),void t(!1);Jr.info("[playwright-cli-hook] Daemon started",{stdout:n.trim()}),t(!0)})})}(t,d,e.headed);if(!r)return n.delete(d),{decision:"block",reason:"Failed to start playwright-cli daemon. Check logs for details.",systemMessage:"playwright-cli daemon failed to start"}}const f=`${process.execPath} ${t}`;let h=a.replace(/\b(?:npx\s+)?playwright-cli\b/g,f);const g=[];h.includes("-s=")||h.includes("--session=")||g.push(`-s=${d}`),e.headed&&!h.includes("--headed")&&g.push("--headed"),g.length>0&&(h=h.replaceAll(f,`${f} ${g.join(" ")}`)),e.envVars&&(h=h.replace(Da,(t,n)=>{const r=e.envVars[n];return null!=r?r:t}));const y=[];if(La.test(a)&&e.envVars)for(const[t,n]of Object.entries(e.envVars))y.push(`${t}=${$a(n)}`);return y.length>0&&(h=`${y.join(" ")} ${h}`),Jr.debug("[playwright-cli-hook] Rewritten command",{original:a.slice(0,100),sessionName:d,agentId:u,envVarCount:y.length}),{decision:"approve",hookSpecificOutput:{hookEventName:"PreToolUse",updatedInput:{command:h}}}},cleanup:async()=>{t&&n.size>0&&(await Promise.all(Array.from(n).map(e=>{return n=t,r=e,new Promise(e=>{m(process.execPath,[n,"close",`-s=${r}`],{timeout:1e4},t=>{t&&Jr.warn("[playwright-cli-hook] Failed to stop daemon",{error:t.message,sessionName:r}),e()})});var n,r})),n.clear())}}}({sessionName:process.env.STABLY_PLAYWRIGHT_SESSION??(Lt?"auto":"default"),headed:!Lt&&!process.env.CI,envVars:{...g,...wt?.variables}}),$t=Lt?Cn.createLocal({workingDir:d}):void 0;$t&&await $t.captureSnapshot();const Ot=()=>{Ut&&function({workingDir:e,options:t={}}){const r=function(e){const t=function(e){let t=n.resolve(e);for(;;){if(w.existsSync(n.join(t,".git")))return t;const r=n.dirname(t);if(r===t)return n.resolve(e);t=r}}(e),r=function(e,t){for(const n of fa(e,t))if(aa(n))return n}(e,t),o=ua(ca(e,/playwright\.config\.(ts|js|mts|mjs|cjs)$/).map(e=>n.dirname(e))),s=function(e){const t=new Set;for(const r of e)t.add(la(n.dirname(r)));return ua(Array.from(t))}(ca(e,/\.(spec|test)\.(ts|js)$/)),i=o.length>0?o:s,a=r??(1===i.length?i[0]:void 0)??e,c=pa(a,t);if(!c)return{repoRoot:t,projectRoot:a,targetDir:void 0};if(!r&&c===n.resolve(e)&&function(e,t,n){const r=new Set;for(const o of e){const e=pa(o,n);e&&e!==t&&r.add(e)}return r.size>1}(i,c,t))return{repoRoot:t,projectRoot:a,targetDir:void 0};const l=sa(c);if(!l||!("workspaces"in l.contents))return{repoRoot:t,projectRoot:a,targetDir:c};const u=function(e,t){let r=n.resolve(e);const o=n.resolve(t);for(;r!==o;){if(w.existsSync(n.join(r,"package.json")))return r;const e=n.dirname(r);if(e===r)break;r=e}}(a,c);return{repoRoot:t,projectRoot:a,targetDir:u??c}}(e);if(r.targetDir){try{!function(e){const t=n.join(e,"package.json");if(!w.existsSync(t))return;const r=JSON.parse(w.readFileSync(t,"utf-8"));if({...r.dependencies,...r.devDependencies}.stably)Jr.debug("stably package already present in dependencies");else{Jr.info("stably package missing from devDependencies, installing...");try{oa({workingDir:e,packageManager:ga(e),packageSpec:"stably",targetSection:"devDependencies"}),Jr.info("stably package installed successfully")}catch(e){Jr.warn("Failed to install stably package",{error:String(e)})}}}(r.targetDir)}catch(e){Jr.warn("Post-init: ensureStablyDependency failed",{error:String(e)})}try{!function(e){const t=sa(e);if(!t)return;const n=t.contents.devDependencies?.playwright??t.contents.dependencies?.playwright;if(n)if(ha(n)!==bo)try{oa({workingDir:e,packageManager:ga(e),packageSpec:`playwright@${bo}`,targetSection:t.contents.devDependencies?.playwright?"devDependencies":"dependencies"}),Jr.info("standalone playwright version aligned successfully",{version:bo})}catch(e){Jr.warn("Failed to align standalone playwright version",{error:String(e)})}else Jr.debug("standalone playwright already at supported version",{version:bo});else Jr.debug("standalone playwright package not present")}(r.targetDir)}catch(e){Jr.warn("Post-init: alignStandalonePlaywrightVersion failed",{error:String(e)})}try{!function(e){const t=sa(e);if(t)if(ha(t.contents.devDependencies?.["@playwright/test"]??t.contents.dependencies?.["@playwright/test"])!==bo)try{Jr.info(`Updating @playwright/test to supported version ${bo}...`),oa({workingDir:e,packageManager:ga(e),packageSpec:`@playwright/test@${bo}`,targetSection:t.contents.dependencies?.["@playwright/test"]?"dependencies":"devDependencies"}),Jr.info("@playwright/test updated successfully")}catch(e){Jr.warn("Failed to update @playwright/test",{error:String(e)})}else Jr.debug("@playwright/test already at supported version",{version:bo});else Jr.debug("No package.json found, skipping @playwright/test update")}(r.targetDir)}catch(e){Jr.warn("Post-init: updatePlaywrightTest failed",{error:String(e)})}try{!function(e,t,r){const o=[];r.googleAuth&&o.push("Google Auth methods"),r.emailPackage&&o.push("@stablyai/email Inbox methods for email verification flows");const s=`Use Stably CLI for Playwright test runs (better reporting, auto-fix); import from @stablyai/playwright-test for agent.act(), aiAssert, page.extract(), page.getLocatorsByAI()${o.length>0?`; also use ${o.join(" and ")}`:""}.`,i=function(e,t){const r=["CLAUDE.md","AGENTS.md","AGENT.md","agent.md"];for(const o of fa(e,t)){let t;for(const s of r){const r=n.join(o,s);if(!w.existsSync(r))continue;t??=r;const i=w.readFileSync(r,"utf-8");if(/Stably CLI/i.test(i)&&i.includes("@stablyai/playwright-test"))return void Jr.debug("Agent guidance already present",{file:n.relative(e,r)||s});if(da(i))return r}if(t)return t}return n.join(e,"AGENTS.md")}(e,t);if(i){Jr.info("Appending Stably guidance",{file:n.basename(i)});try{const e=w.existsSync(i)?w.readFileSync(i,"utf-8"):"",t=e.length>0&&!e.endsWith("\n")?"\n\n":e.length>0?"\n":"";w.writeFileSync(i,`${e}${t}${s}\n`,"utf-8"),Jr.info("Agent guidance appended successfully")}catch(e){Jr.warn("Failed to update agent guidance file",{error:String(e)})}}}(r.targetDir,r.repoRoot,t)}catch(e){Jr.warn("Post-init: ensureAgentGuidance failed",{error:String(e)})}}else Jr.warn("Post-init: could not resolve target package directory; skipping verification",{workingDir:e})}({workingDir:d,options:{googleAuth:C?.googleAuth,emailPackage:C?.emailPackage}})},Nt=Ut?ra({onComplete:()=>{Ot(),Qe({status:"success"}),Ye(),R?.finish(),process.exit(0)}}):b?ra({onRestartRequested:()=>{b&&(F=!0,Qe({status:"running"}),Ve({label:"Restarting browser tools..."}),B={createdAtUserMessageSeq:H,attempts:0})}}):void 0,Bt=Nt?b?{"stably-agent-control":Nt}:{"session-control":Nt}:{},jt=S&&Et?["mcp__create-report"]:[],Mt=Ut?Ka:x?Va:[...Va,...Lt?["mcp__auto-heal-report"]:[],...jt],Ft=Ut?Ka:b?[...za,"mcp__stably-agent-control"]:x?za:[...za,...jt],Ht=S&&Et?{"create-report":ya({prContext:Et,authHeader:l,orgId:u,onReportPosted:e=>{ke({githubComment:{url:e.commentUrl,prNumber:Et.prNumber}})}})}:{},Gt=Ut?Bt:Lt&&$t?{"auto-heal-report":na({authHeader:l,diffTracker:$t,orgId:u,runId:e.runId,workingDir:d}),"run-history":_a({authHeader:l,orgId:u,projectId:to(c)}),...Bt}:{...Bt,...Ht},Wt="single"===e.mode,Yt=Ut?[]:Wt?[{matcher:"Write",hooks:[Oo({onFileCreated:e=>{if(tt.includes(e)||tt.push(e),Re){if(Re.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}=Re,s=(async()=>{try{const r=await v.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:cr(),headers:oo(o),path:{sessionId:s}},(a.client??Jn).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/sessions/{sessionId}/files/upload-url",...a,headers:{"Content-Type":"application/json",...a.headers}}));var a;if(i.error)throw new Error(`Failed to presign file upload (${i.response.status})`);const c=go.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 ao({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:cr(),headers:oo(o),path:{sessionId:s}},(a.client??Jn).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/sessions/{sessionId}/files/confirm",...a,headers:{"Content-Type":"application/json",...a.headers}}));var a;if(i.error)throw new Error(`Failed to confirm file upload (${i.response.status})`)})({authHeader:e,bucketPath:a,filename:r,filePath:o,orgId:s,sessionId:i}),a}catch(e){return Jr.warn("Failed to upload automation file",{error:e instanceof Error?e.message:String(e)}),null}})({authHeader:l,content:r,contentType:"text/plain",filename:n,filePath:e,orgId:u,sessionId:o}),i={path:e,filename:n,bucketPath:s};nt.push(i),ke({filesCreated:[...nt]})}catch(t){Jr.warn("Failed to upload created file",{filePath:e,error:t instanceof Error?t.message:String(t)});const r={path:e,filename:n,bucketPath:null};nt.push(r),ke({filesCreated:[...nt]})}})();rt.push(s)}}})]}]:[],Vt=Ut?[]:[...Lt?[{matcher:"Read",hooks:[Io({action:"reading",pathKey:"file_path"})]},{matcher:"Write",hooks:[Io({action:"writing",pathKey:"file_path"})]},{matcher:"Edit",hooks:[Io({action:"editing",pathKey:"file_path"})]},{matcher:"Grep",hooks:[Io({action:"searching",pathKey:"path"})]},{matcher:"Glob",hooks:[Io({action:"searching",pathKey:"path"})]},{matcher:"Bash",hooks:[Do({workspaceBoundary:d})]}]:[],...Dt?[{matcher:"Bash",hooks:[Dt.hook]}]:[]],zt=Object.keys(St).length>0?St:void 0,Kt={...At};Kt.MCP_TOOL_TIMEOUT=String(6e5),kt&&(Kt.ANTHROPIC_API_KEY=kt,Kt.ANTHROPIC_BASE_URL=or,Kt.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS="1",Kt.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC="1");const qt=process.env.STABLY_AGENT_MODEL??"claude-opus-4-6",Jt=Lt?"env"===c.type?c.auth.apiKey:c.auth.accessToken:void 0,Qt=Lt?to(c):void 0;Lt&&Jt&&Qt&&(Kt.STABLY_API_KEY=Jt,Kt.STABLY_PROJECT_ID=Qt);const Xt=dt?`\n\n## Custom Rules\n${dt}`:"",Zt=mt?`\n\n## Custom Test Generation Rules\n${mt}`:"",en=bt?`\n\n## Project Rules (STABLY.md)\n${bt}`:"",tn=Tt+Xt+Zt+en;Jr.debug("[fix] Final system prompt assembled",{baseSize:Tt.length,fixRulesSize:Xt.length,createRulesSize:Zt.length,stablyMdSize:en.length,finalSize:tn.length});const nn=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 Ra(t)?t:void 0}();if(e)return e;const t=r.join(xa,"stably-plugin-cli");if(Ra(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}}(xa))for(const t of Ca){const n=r.join(e,t);if(Ra(n))return n}}();if(e)return{type:"local",path:e}}(),rn=()=>(Jr.info("[fix] Starting SDK query",{model:qt,tools:Mt,mcpServers:Object.keys(Gt),resumeSessionId:O??null,subagentsEnabled:!!zt,subagentCount:Object.keys(St).length,useStablyAiProxy:Ct,aiProxyUrl:or,anthropicBaseUrl:void 0,stablyPluginPath:nn?.path,stablyPluginExists:!!nn}),Y({options:{executableArgs:["--max-old-space-size=4096"],tools:Mt,allowedTools:Ft,...null!=ht?{maxBudgetUsd:ht}:{},betas:[],canUseTool:(e,t)=>(Jr.debug("[fix] canUseTool called",{toolName:e}),Promise.resolve({behavior:"allow",updatedInput:t})),cwd:d,env:Kt,hooks:{PostToolUse:Yt,PreToolUse:Vt},includePartialMessages:!0,agents:zt,mcpServers:Gt,model:qt,permissionMode:"default",plugins:nn?[nn]:void 0,systemPrompt:tn,...O?{resume:O}:{}},prompt:R??at})),on=()=>{if(R&&0!==z.length){for(const e of z)R.pushText(e);z.length=0,j=!0,Qe({status:"running"})}},sn=async()=>{b&&(N||(N=(async()=>{Jr.info("Restarting MCP servers for chat mode"),Qe({status:"running"}),Ve({label:"Restarting browser tools..."});try{await($?.interrupt?.())}catch(e){Jr.warn("Failed to interrupt response during MCP restart",{error:e instanceof Error?e.message:String(e)})}await Bo(),R?.finish(),R=new jo,G=0,j=!1,M=!1,oe.clear(),$=rn(),W=!0,Ve({label:"Restarting browser tools..."}),b&&R&&B&&(B.createdAtUserMessageSeq===H?B.attempts>=1||z.length>0?B=void 0:(B.attempts+=1,R.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")),B=void 0,j=!0,Qe({status:"running"})):B=void 0),on()})().finally(()=>{N=void 0,on()})),await N)},an=async e=>{if(y&&j&&!te&&!X)X=(async()=>{Jr.info("[fix] Interrupting for user message",{messageCount:e.length,phase:fe?.phase});try{await($?.interrupt?.())}catch(e){Jr.warn("[fix] Failed to interrupt response for user message",{error:e instanceof Error?e.message:String(e)})}await Bo(),R?.finish(),R=new jo,oe.clear(),$=rn();const t=e.map(e=>`[Message from web UI user]: ${e}`).join("\n\n");R.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}`),ne=!0,j=!0})().finally(()=>{X=void 0}),await X;else for(const t of e)R?.pushText(`[Message from web UI user]: ${t}`)};if(kt){x&&Ve({label:"Checking AI connectivity..."});const e=or,t=`${e.replace(/\/$/,"")}/v1/messages`;Jr.debug(`[fix] Pre-flight: POST ${t}`);const n=Date.now();let r;try{const e=await fetch(t,{method:"POST",signal:AbortSignal.timeout(1e4),headers:{"x-api-key":kt,"anthropic-version":"2023-06-01","content-type":"application/json"},body:"{}"}),o=await e.text().catch(()=>""),s=Date.now()-n;Jr.debug(`[fix] Pre-flight: ${e.status} in ${s}ms — ${o.slice(0,300)}`),401===e.status||403===e.status?(Jr.error(`[fix] Pre-flight: AI proxy key rejected (${e.status}) at ${t}`),r="Unable to start verification: AI proxy credentials were rejected. Please run `stably login` and try again."):Jr.info("[fix] Pre-flight: AI proxy key valid",{status:e.status,durationMs:s})}catch(t){Jr.error("[fix] Pre-flight: AI proxy unreachable",{error:t instanceof Error?t.message:String(t),durationMs:Date.now()-n,url:e}),r="Unable to start verification: cannot reach the AI proxy. Please check your network/VPN and try again."}finally{x&&"running"===Je&&Ve({label:void 0})}r&&(He({text:`[stably] ${r}\n`}),Qe({error:r,status:"error"}),await We(),Jr.flush(),Jr.printLogFileInfo(),process.exit(1))}Jr.info("[fix] Creating initial agent query"),x&&(Ve({label:"Initializing verification session..."}),He({text:"Initializing verification session...\n"})),Jr.flush(),$=rn(),Jr.info("[fix] Agent query created, entering message loop"),"chat"!==e.mode&&(R.pushText(at),se.push({role:"user",content:at,timestamp:(new Date).toISOString()}));const cn=async t=>{Be||(Be=(async()=>{Jr.info("[session] Interrupt requested",{source:t,mode:e.mode}),ce="CANCELED",await we("CANCELED"),be({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:ye(!0)}),await(pe?.closeAndWait()),await Promise.allSettled(rt),ke({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0}),await(_e?.closeAndWait()),J&&(clearTimeout(J),J=void 0),Ye(),await Bo(),await(Dt?.cleanup());try{await($?.interrupt?.())}catch{}R?.finish(),se.length>0&&De&&await yo({authHeader:l,orgId:u,sessionId:De,projectId:to(c),history:se}).catch(e=>{Jr.warn("[exit] Failed to upload session history",{error:e instanceof Error?e.message:String(e)})}),We(),Jr.flush()})()),await Be};Ne.current=async()=>{await cn("ctrl-c")};let ln=()=>{};ln=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 cn("signal"),process.exit(function(e){return"SIGINT"===e?130:143}(e))})()}});let un=0,dn=null,pn=!1;const fn=x?setTimeout(()=>{if(dn||"running"!==Je)return;const e="This is taking longer than expected. Please try again.";He({text:`[stably] ${e}\n`}),Qe({error:e,status:"error"});try{$?.interrupt?.()}catch{}R?.finish(),We(),Jr.flush(),Jr.printLogFileInfo(),process.exit(1)},9e4):void 0;fn?.unref();const hn=setInterval(()=>{const e=Date.now()-de;dn?Jr.info("[fix] Watchdog: message loop active",{messageCount:un,elapsed:e}):(Jr.info("[fix] Watchdog: waiting for first SDK message",{elapsed:e}),x&&!pn&&e>=15e3&&(He({text:"Still preparing verification. This can take a bit...\n"}),pn=!0)),Jr.flush()},15e3);hn.unref();try{let t=!1;for(;;){if(!$){Jr.info("[fix] No response object, exiting message loop");break}t=!1,Jr.info("[fix] Entering for-await on SDK response");for await(const n of $){un++,dn||(dn=Date.now(),fn&&clearTimeout(fn),x&&Ve({label:void 0}),Jr.info("[fix] First SDK message received",{waitDurationMs:dn-de,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!==O&&(O=r,Jr.debug("Captured Claude session id",{sessionId:O})),"stream_event"===n.type){const{event:e}=n;(un<=5||un%200==0)&&Jr.debug("[fix] Stream event",{msgNum:un,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&&F&&!t)continue;W&&(W=!1,Ve({label:void 0}));const e=t&&oe.has(t)?t:1===oe.size?Array.from(oe.keys())[0]:void 0;e?je({toolUseId:e,kind:"text",content:n.text}):x||He({text:n.text})}}"message_stop"===e?.type&&R&&(te=!1,R.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&&(Ze=t,x&&(et=et?`${et}\n\n${t}`:t),Jr.debug("Assistant message",{text:x?Ga(t):t}),"fix"===e.mode&&(ge(Ja,{type:"ai_message",summary:t.slice(0,200)}),me({type:"ai_message",summary:t.slice(0,200)})),A&&Le({type:"ai_message",summary:t.slice(0,200)}),ie({role:"assistant",content:t,timestamp:(new Date).toISOString()}))}if(oe.size>0){const e=Array.isArray(r)?r.filter(e=>e&&"object"==typeof e&&"type"in e&&"tool_use"===e.type).map(e=>e&&"object"==typeof e&&"name"in e&&"string"==typeof e.name?e.name:void 0):[];Jr.debug("Assistant message with active subagents",{hasParentToolUseId:!!t,parentToolUseId:t,activeSubagentIds:Array.from(oe.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&&(te=!0),"mcp__session-control__restart_mcp_servers"===n.name||"mcp__stably-agent-control__restart_mcp_servers"===n.name){Fe({rawName:n.name,toolInput:n.input});continue}if(n.name.startsWith("mcp__session-control__")||n.name.startsWith("mcp__stably-agent-control__"))continue;if(tc(n.name))continue;if(x&&ec.test(n.name))continue;if(oe.size>0&&Jr.debug("Tool use detected with active subagents",{toolName:n.name,hasParentToolUseId:!!t,parentToolUseId:t,wouldRouteToSubagent:!!t&&oe.has(t),activeSubagentIds:Array.from(oe.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(Jr.info("[fix] Subagent started",{subagentType:o,description:s,toolUseId:n.id,activeSubagentCount:oe.size+1}),oe.set(n.id,{subagentType:o,description:s}),Me({toolUseId:n.id,subagentType:o,description:s}),"fix"===e.mode){if("triage"===o){qe?.({phase:"triage"});const e={id:n.id,testDescription:"Triage",workerType:"triage",status:"running",summary:null,startedAt:Date.now(),endedAt:null,activity:[]};be({phase:"triage",workers:[...fe?.workers??[],e]})}else if("code-worker"===o){he.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:[]};qe?.({phase:"fixing",totalTests:he.size,currentTestDescription:s||null}),be({phase:"fixing",totalTests:he.size,currentTestDescription:s||null,lastTestDescription:s||fe?.lastTestDescription||null,workers:[...fe?.workers??[],e]})}else if("browser-worker"===o){he.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:[]};qe?.({phase:"debugging",totalTests:he.size,currentTestDescription:s||null}),be({phase:"debugging",totalTests:he.size,currentTestDescription:s||null,lastTestDescription:s||fe?.lastTestDescription||null,workers:[...fe?.workers??[],e]})}else"validation"===o?(qe?.({phase:"validation",currentTestDescription:null}),be({phase:"validation",currentTestDescription:null})):"context"===o&&be({currentTestDescription:s||null});me({type:"tool_call",summary:`[${o}] ${s}`.trim()})}continue}if(t&&oe.has(t)){const r=as(n.name,n.input),o=r??cs(n.name),s=r?void 0:is(n.name,n.input),i=s?`${o} (${s})`:o;if(Jr.debug("Subagent tool called",{tool:n.name,parentToolUseId:t}),je({toolUseId:t,kind:"tool",content:i}),"fix"===e.mode){me({type:"tool_call",summary:i});const e=oe.get(t);"code-worker"!==e?.subagentType&&"browser-worker"!==e?.subagentType&&"triage"!==e?.subagentType||ge(t,{type:"tool_call",summary:i})}continue}if(t&&Jr.debug("Tool with parent_tool_use_id but no matching subagent",{tool:n.name,parentToolUseId:t,activeSubagentIds:Array.from(oe.keys())}),Jr.debug("Tool called",{tool:n.name,input:n.input}),Fe({rawName:n.name,toolInput:n.input}),n.id&&ae.set(n.id,n.name),ie({role:"tool",content:"",timestamp:(new Date).toISOString(),toolName:n.name,toolInput:n.input}),"fix"===e.mode){const e=as(n.name,n.input),t=e??cs(n.name),r=e?void 0:is(n.name,n.input),o=r?`${t} (${r})`:t;ge(Ja,{type:"tool_call",summary:o}),me({type:"tool_call",summary:o})}if(S){const e=as(n.name,n.input),t=e??cs(n.name),r=e?void 0:is(n.name,n.input),o=r?`${t} (${r})`:t;"initializing"===Re?.phase?ke({phase:"generating",currentActivity:o}):"mcp__playwright-test__test_run"===n.name&&"generating"===Re?.phase?ke({phase:"testing",currentActivity:o}):ke({currentActivity:o}),Le({type:"tool_call",summary:o})}if(x){const e=as(n.name,n.input),t=e??cs(n.name),r=e?void 0:is(n.name,n.input),o=Ga(r?`${t} (${r})`:t);ke("initializing"===Re?.phase?{phase:"verifying",currentActivity:o}:{currentActivity:o}),Le({type:"tool_call",summary:o})}}if("text"===n?.type){const r="string"==typeof n.text?n.text:"",o=t&&oe.has(t)?t:1===oe.size?Array.from(oe.keys())[0]:void 0;if(o&&r&&(je({toolUseId:o,kind:"text",content:r}),"fix"===e.mode)){const e=oe.get(o);"code-worker"!==e?.subagentType&&"browser-worker"!==e?.subagentType&&"triage"!==e?.subagentType||ge(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("")),Jr.debug("Tool result",{toolUseId:t,isError:o,output:s?.slice(0,500)});const a=5e4,c=t?ae.get(t):void 0;if(ie({role:"tool_result",content:"",timestamp:(new Date).toISOString(),toolName:c,toolOutput:s?.slice(0,a),isError:o}),t&&oe.has(t)){const n=oe.get(t);if(Jr.info("[fix] Subagent completed",{toolUseId:t,isError:o,subagentType:n?.subagentType,description:n?.description,activeSubagentCount:oe.size-1}),s&&je({toolUseId:t,kind:"text",content:s}),Ke({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=(fe?.workers??[]).map(r=>r.id===t?{...r,status:e,summary:n,endedAt:Date.now()}:r);be({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=(fe?.workers??[]).map(r=>r.id===t?{...r,status:e,summary:n,endedAt:Date.now()}:r);o?(qe?.({failedTests:(fe?.failedTests??0)+1,currentTestDescription:null}),be({failedTests:(fe?.failedTests??0)+1,currentTestDescription:null,workers:r})):(qe?.({fixedTests:(fe?.fixedTests??0)+1,currentTestDescription:null}),be({fixedTests:(fe?.fixedTests??0)+1,currentTestDescription:null,workers:r}))}oe.delete(t)}}continue}if("result"===n.type){if(Jr.info("[fix] Agent result received",{subtype:n.subtype,messageCount:un,elapsed:Date.now()-de,activeSubagents:oe.size,fixedTests:fe?.fixedTests,failedTests:fe?.failedTests,phase:fe?.phase}),y){if("success"===n.subtype){J&&(clearTimeout(J),J=void 0);for(const e of ee)R?.pushText(`[Message from web UI user]: ${e}`);if(ee=[],(A||"fix"===e.mode)&&R){if(R.hasQueuedMessages()){Jr.info("[ws] Queued web UI messages found, continuing agent"),j=!0,R.allowNextTurn();continue}if(await nc(R,3e3)){Jr.info("[ws] Web UI message received during grace period, continuing agent"),j=!0,R.allowNextTurn();continue}R.finish()}if(qe?.({phase:"complete",currentTestDescription:null,endedAt:Date.now()}),be({phase:"complete",currentTestDescription:null,endedAt:Date.now(),isError:!1,workers:ye(!1)}),await Promise.allSettled(rt),"verify"===e.mode){(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt).trim();const t=et||Ze,n=/```verdict\s*\r?\n/.test(t),r=Ya(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=Wa(r);"PASS"===r.verdict?q.green("VERIFICATION PASSED"):"FAIL"===r.verdict?q.red("VERIFICATION FAILED"):q.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=>{}),ke({phase:"complete",endedAt:Date.now(),isError:"PASS"!==r.verdict,currentActivity:null}),process.exitCode="PASS"===r.verdict?0:"FAIL"===r.verdict?1:2,Qe({status:"success"})}else{if(ke({phase:"complete",endedAt:Date.now(),isError:!1,currentActivity:null}),Wt&&tt.length>0){q.green("Created files:");for(const e of tt)q.green(`- ${e}`)}const e=(e,t)=>`]8;;${e}${t}]8;;`,t=Xe?q.cyan(`📊 View Autoheal Report:\n ${e(Xe,q.cyan(q.bold(q.underline(Xe))))}`):void 0;Qe({status:"success",result:t}),ce="COMPLETED"}}else if(X||ne)Jr.info("[fix] Suppressing error status: user-message interrupt in progress");else if(M)ce="CANCELED",be({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:ye(!0)}),await Promise.allSettled(rt),ke({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0});else if(x){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."),q.yellow("VERIFICATION INCONCLUSIVE"),await Promise.allSettled(rt),ke({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),Qe({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.`,Jr.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"),qe?.({endedAt:Date.now(),isError:!0}),be({phase:"complete",endedAt:Date.now(),isError:!0,errorReason:t,errorMessage:r,totalCostUsd:e,currentTestDescription:null,workers:ye(!0)}),await Promise.allSettled(rt),ke({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),Qe({error:r,status:"error"}),process.exitCode=1,ce="FAILED"}M=!1;break}const r=b&&F;if("success"!==n.subtype){if(!M){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.`,Jr.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."),Qe({error:e,status:"error"}),process.exitCode=1}}else Qe(r?{status:"running"}:{status:"success"});if(j=!1,M=!1,r){F=!1,Jr.info("Processing deferred MCP restart request in chat mode"),await sn(),t=!0;break}W=!1,Ve({label:void 0}),R?.allowNextTurn(),I&&G>0&&(G-=1,j=!0,Qe({status:"running"}));continue}}if(X&&await X,ne&&(ne=!1,t=!0,Qe({status:"running"}),Jr.info("[fix] Resuming after user-message interrupt")),!t)break}}catch(e){M?(ce="CANCELED",be({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:ye(!0)}),await Promise.allSettled(rt),ke({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0})):(Jr.error("[fix] Agent encountered an error",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0,elapsed:Date.now()-de}),Qe({error:`Agent encountered an error: ${e}`,status:"error"}),process.exitCode=1,ce="FAILED",be({phase:"complete",endedAt:Date.now(),isError:!0,currentTestDescription:null,workers:ye(!0)}),await Promise.allSettled(rt),ke({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),Jr.flush(),Jr.printLogFileInfo())}finally{if(fn&&clearTimeout(fn),clearInterval(hn),J&&(clearTimeout(J),J=void 0),Jr.info("[fix] Agent session ending",{finalStatus:ce,elapsed:Date.now()-de,totalMessages:un}),Ot(),j=!1,M=!1,ln(),process.off("uncaughtException",a),R?.finish(),ce){Jr.info("[fix] Reporting final autoheal status",{status:ce});const e=Date.now();await we(ce),Jr.info("[fix] Final autoheal status reported",{durationMs:Date.now()-e})}if(Jr.info("[fix] Closing WebSocket progress reporter"),await(pe?.closeAndWait()),await Promise.allSettled(rt),await(_e?.closeAndWait()),!Lt&&se.length>0&&De&&(Jr.info("[session] Uploading session history",{messageCount:se.length}),await yo({authHeader:l,orgId:u,sessionId:De,projectId:to(c),history:se}).catch(e=>{Jr.warn("[session] Failed to upload session history",{error:e instanceof Error?e.message:String(e)})})),Lt&&$t){const t=Date.now();try{Jr.info("[fix] Computing diff...");const n=await $t.computeDiff();if(n&&n.trim().length>0){Jr.info("[fix] Uploading diff...",{diffLength:n.length});const{diffBucketPath:r,uploadUrl:o}=await uo({authHeader:l,contentType:"text/plain",orgId:u,runId:e.runId});await ao({body:n,contentType:"text/plain",uploadUrl:o,errorContext:"diff"}),await po({authHeader:l,diffBucketPath:r,orgId:u,runId:e.runId}),Jr.info("[fix] Diff uploaded",{durationMs:Date.now()-t})}else Jr.info("[fix] No diff to upload (empty or no changes)")}catch(e){Jr.warn("[fix] Failed to upload diff",{error:e instanceof Error?e.message:String(e),durationMs:Date.now()-t})}}Jr.info("[fix] Cleaning up diff tracker"),await($t?.cleanup()),Lt&&se.length>0&&De&&(Jr.info("[fix] Uploading session history",{messageCount:se.length}),await yo({authHeader:l,orgId:u,sessionId:De,projectId:to(c),history:se}).catch(e=>{Jr.warn("[fix] Failed to upload session history",{error:e instanceof Error?e.message:String(e)})})),Jr.info("[fix] Running final cleanup"),await(Dt?.cleanup()),await We(),Jr.info("[fix] Cleanup complete")}},ic=he.object({runId:he.string(),timestamp:he.number()}),ac=[{args:["--trace=on"],description:"Run Playwright tests",name:"test"},{args:[],description:"Install browser dependencies",name:"install"}],cc=["You have two different versions of @playwright/test"];function lc(e){const[t,...n]=Ki(e),r=[t,...n.slice(0,-1)].join(" ");return(t,n)=>{let o=t.toString();for(const e of ac)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 uc({overrideArgs:e,subcommand:t}){Jr.info("[test] forwardToPlaywright starting",{subcommand:t,overrideArgs:e});const n=process.argv,r=n.findIndex((e,n)=>n>1&&e===t),a=-1===r?[]:n.slice(r+1),c="--"===a[0],u=c?a.slice(1):a;if(!c&&("--help"===u[0]||"-h"===u[0]))return async function({subcommand:e}){const t=ac.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=Yi();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]=Ki(o),a=lc(o);return new Promise(t=>{const n=g(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 m=[t,...d,...f];Jr.info("[test] Forwarded args computed",{forwardedArgs:m}),Jr.info("[test] Resolving Stably test environment");const y=Date.now(),b="test"===t?await(async()=>{Jr.info("[test] Resolving Stably test env");const e=(()=>{if(process.env.STABLY_WS_URL)return;if("https://api.stably.ai"===er)return;const e=er.startsWith("http://")?"ws://":"wss://";return`${er.replace(/^https?:\/\//,e).replace(/\/$/,"")}/reporter`})();Jr.debug("[test] WebSocket URL resolved",{wsUrl:e??"(default)"});const t=Xr();if(t)return Jr.info("[test] Using env var auth (STABLY_API_KEY + STABLY_PROJECT_ID)"),{STABLY_API_KEY:t.apiKey,STABLY_PROJECT_ID:t.projectId,...e&&{STABLY_WS_URL:e}};Jr.info("[test] No env var auth, attempting OAuth auth");const n=Date.now(),r=await(async()=>{const e=Xr();if(e)return{auth:e,type:"env"};const t=await Zr(),n=t?await Sr():void 0;return t&&n?{auth:{accessToken:t.accessToken,context:n},type:"oauth"}:void 0})();if(Jr.info("[test] OAuth auth resolved",{durationMs:Date.now()-n,hasAuth:!!r,authType:r?.type}),!r||"env"===r.type)return void Jr.info("[test] No usable auth found");const o=process.env.STABLY_PROJECT_ID?.trim(),s=o||to(r);if(!s)return void Jr.warn("[test] No project ID available");Jr.info("[test] Fetching JWT API key",{projectId:s});const i=Date.now(),a=await(async(e,t)=>{try{Jr.debug("Requesting JWT API key",{projectId:t,apiUrl:er});const n=await(async({accessToken:e,projectId:t})=>{const n=await(r={auth:e,client:cr(),path:{projectId:t}},(r.client??Jn).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/api-key",...r}));var r;if(n.error){const e=n.error?.error,{status:t}=n.response;throw new Error(e??`Failed to get API key: ${t}`)}return n.data})({accessToken:e,projectId:t});return Jr.debug("JWT API key obtained",{keyPrefix:n.apiKey.substring(0,10)}),n.apiKey}catch(e){return void Jr.warn("Failed to get JWT API key for test reporter",{error:e instanceof Error?e.message:String(e)})}})(r.auth.accessToken,s);Jr.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 Jr.info("[test] Stably test env resolved",{hasApiKey:!!c?.STABLY_API_KEY,projectId:c?.STABLY_PROJECT_ID,wsUrl:c?.STABLY_WS_URL??process.env.STABLY_WS_URL??"(default)"}),c})():void 0;Jr.info("[test] Stably test environment resolved",{durationMs:Date.now()-y,hasCredentials:null!=b,hasWsUrl:!!b?.STABLY_WS_URL}),Jr.info("[test] Loading remote environment variables");const w=await ro();Jr.info("[test] Remote environment loaded",{hasRemoteEnv:!!w,variableCount:w?Object.keys(w.variables).length:0});const v={...w?.variables,...w?.sensitiveValues.length?{STABLY_SENSITIVE_VALUES:Buffer.from(JSON.stringify(w.sensitiveValues)).toString("base64")}:{}};Jr.info("[test] Setting up Stably reporter injection");const I="test"===t?function({forwardedArgs:e,hasCredentials:t}){if(!t)return console.warn("[33m⚠️ Stably credentials not found. Test results will not be reported to Stably.[0m"),console.warn("[33m To enable reporting, either:[0m"),console.warn("[33m • Run `npx stably login` to authenticate[0m"),void console.warn("[33m • Or set STABLY_API_KEY and STABLY_PROJECT_ID environment variables[0m\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=>_(e)))return!0;const e=s(t);if(e===t)return!1;t=e}}(e);return t||(console.warn("[33m⚠️ @stablyai/playwright-test is not installed. Stably reporter will not be injected.[0m"),console.warn("[33m Install it with: npm install @stablyai/playwright-test[0m"),console.warn("[33m Reference: ]8;;https://docs.stably.ai/getting-started/sdk-setup-guidehttps://docs.stably.ai/getting-started/sdk-setup-guide]8;;[0m\n")),t},a=(e,t)=>{try{return function({baseConfigPath:e,projectDir:t}){const n=function(e){try{const t=h("npm pkg get type",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return"module"===JSON.parse(t.trim())}catch{return!1}}(t),r=n?"mts":"ts",a=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: '${Zn}',\n projectId: process.env.STABLY_PROJECT_ID,\n source: 'cli',\n notificationConfigs: extractNotificationConfigs(),\n errorSummary: resolveErrorSummary(),\n ...(sensitiveValues && { sensitiveValues }),\n })];\n }\n\n // Normalize to array\n const reportersArray: unknown[] = Array.isArray(existingReporters)\n ? existingReporters\n : [[existingReporters, {}]];\n\n // If user has a stably reporter, take their options but override credentials\n const existingOptions = getStablyReporterOptions(reportersArray);\n const stablyReporterEntry = stablyReporter({\n ...existingOptions,\n apiKey: process.env.STABLY_API_KEY,\n cliVersion: '${Zn}',\n projectId: process.env.STABLY_PROJECT_ID,\n source: 'cli',\n notificationConfigs: extractNotificationConfigs(),\n errorSummary: resolveErrorSummary(existingOptions?.errorSummary),\n ...(sensitiveValues && { sensitiveValues }),\n });\n\n // Keep all non-stably reporters, add our (merged or fresh) stably reporter\n const otherReporters = filterOutStablyReporter(reportersArray);\n return [...otherReporters, stablyReporterEntry];\n};\n\nexport default defineConfig({\n ...baseConfig,\n use: {\n ...baseConfig.use,\n trace: 'on',\n },\n reporter: buildReporterList(),\n});\n`.trim();return _(a)||A(a,{recursive:!0}),C(u,d,"utf-8"),function(e){const t=i(e,".gitignore");try{if(_(t)){const e=T(t,"utf-8");if(e.split("\n").map(e=>e.trim()).includes(zo))return;const n=e.length>0&&!e.endsWith("\n");E(t,`${n?"\n":""}${zo}\n`)}else C(t,`${zo}\n`)}catch{}}(a),u}({baseConfigPath:e,projectDir:t})}catch{return void console.warn("[33m⚠️ Could not create Stably wrapper config. Reporter injection skipped.[0m")}};if(e.some(e=>"--config"===e||"-c"===e||e.startsWith("--config=")||e.startsWith("-c="))){const t=e.findIndex(e=>"--config"===e||"-c"===e);if(-1!==t&&e[t+1]){const i=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=qo(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:m,hasCredentials:null!=b}):void 0;Jr.info("[test] Reporter injection setup complete",{hasWrapperConfig:!!I}),Jr.info("[test] Spawning Playwright process"),await function(e,t={}){Jr.info("[test] Detecting Playwright installation");const n=Yi();Jr.info("[test] Playwright installation check",{installed:n.installed,inNodeModules:n.inNodeModules,packageManager:n.packageManager,packageName:n.packageName}),n.installed||(console.error('Playwright is not installed. Please run "stably init" to install it.'),process.exit(1)),n.inNodeModules||(console.error("Playwright is present in your project, but not in node_modules. Please install your dependencies before proceeding."),process.exit(1));const{packageManager:r}=n;r||(console.error("Playwright installation not found. Could not determine your package manager (tried pnpm, yarn, and npm)."),process.exit(1));const[o,...s]=Ki(r),i=(a=t.env)?{...process.env,...a}:process.env;var a;const c=[o,...s,...e];Jr.info("[test] Spawning Playwright process",{command:c.join(" "),pid:process.pid});const l=Date.now(),u=g(o,[...s,...e],{stdio:["inherit","pipe","pipe"],shell:"win32"===process.platform,env:{...i,...process.env.CI?{}:{FORCE_COLOR:"1"}}});Jr.info("[test] Playwright process spawned",{childPid:u.pid});const d=lc(r),p=function(){let e=!1,t="";return(n,r)=>{if(!e){t+=n,t.length>1024&&(t=t.slice(-1024));for(const n of cc)if(t.includes(n))return r.write("\n[stably] Hint: This is a Playwright error, not caused by @stablyai/playwright-test.\n Common causes: running from the wrong directory (especially in monorepos),\n or a dependency pulling in a conflicting @playwright/test version.\n"),void(e=!0)}}}();u.stdout?.on("data",e=>{d(e,process.stdout)}),u.stderr?.on("data",e=>{const t=e.toString();d(e,process.stderr),p(t,process.stderr)});const f=new AbortController,h=()=>!f.signal.aborted&&(f.abort(),t.onClose?.(),process.removeListener("SIGINT",m),process.removeListener("SIGTERM",m),!0),m=e=>{Jr.info("[test] Signal received, killing Playwright process",{signal:e,childPid:u.pid}),h(),u.kill(e);const t="SIGINT"===e?130:143;process.exit(t)};return process.on("SIGINT",m),process.on("SIGTERM",m),new Promise((e,t)=>{u.on("error",e=>{h()&&(Jr.error("[test] Playwright process error",{error:e.message,childPid:u.pid}),t(e))}),u.on("close",t=>{if(!h())return;Jr.info("[test] Playwright process exited",{exitCode:t,durationMs:Date.now()-l});const n=[process.stdout,process.stderr].filter(e=>e.writableNeedDrain).map(e=>new Promise(t=>e.once("drain",t)));Promise.race([Promise.all(n),new Promise(e=>setTimeout(e,5e3))]).then(()=>{process.exitCode=t??0,e(t??0)})})})}(m,{env:{...v,...b},onClose:()=>{var e;Jr.info("[test] Playwright process closed, cleaning up wrapper config"),(e=I)&&_(e)&&U(e)}})}function dc(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 pc={PASSED:q.green,FAILED:q.red,TIMEDOUT:q.red,CANCELLED:q.yellow,INTERRUPTED:q.yellow,RUNNING:q.cyan,QUEUED:q.dim},fc=(e,t)=>e?e.length>t?`${e.slice(0,t-1)}…`:e:"-",hc=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")}`},gc=e=>(pc[e]??(e=>e))(e),mc=/\x1b\[[0-9;]*m/g,yc=(e,t)=>{const n=e.replace(mc,"").length,r=Math.max(0,t-n);return e+" ".repeat(r)},bc=e=>`${JSON.stringify(e,null,2)}\n`,wc=e=>"oauth"===e.type?e.auth.context.orgId:void 0,vc=(e,t,n)=>{if(!e)return;const r=e.toUpperCase();if(t.includes(r))return r;le(q.red(`Invalid ${n} value "${e}". Must be one of: ${t.join(", ").toLowerCase()}`)),process.exit(1)},_c=(e,t,n)=>{if(401!==e.response.status&&403!==e.response.status||(le(q.red("Access denied.")),process.exit(1)),404===e.response.status&&n&&(le(q.red(n)),process.exit(1)),400===e.response.status){const t=e.error&&"object"==typeof e.error&&"error"in e.error?e.error.error:"Bad request";le(q.red(t)),process.exit(1)}e.error&&(le(q.red(`Failed to ${t}: ${e.response.status}`)),process.exit(1))},Ic="stably",Tc=`https://registry.npmjs.org/${Ic}/latest`;function Ec(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 Sc(e,t){const n=Ec(e),r=Ec(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 xc=r.join($.homedir(),".stably"),Ac=r.join(xc,"update-check.json"),Cc="1"===process.env.STABLY_DISABLE_UPDATE_CHECK,Rc=ge.object({lastCheck:ge.number(),latestVersion:ge.string()}),Pc=Symbol.for("stably.updateNotifier.registered");function kc(e=""){process.stdout.write(`${e}\n`)}function Uc(...e){process.stderr.write(`${e.join(" ")}\n`)}var Lc=ge.object({version:ge.string()});var Dc=!1,$c=async()=>{if(Dc)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{}},Oc=e=>{const t=e.toLowerCase();return t.startsWith("npm_config_")||"node_options"===t};!function(){if(Cc||function(e=process.argv.slice(2)){return e.includes("upgrade")}())return;const e=function(){try{const e=v.readFileSync(Ac,"utf-8");return Rc.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 = '${Tc}';\n const cacheFile = ${JSON.stringify(Ac)};\n const cacheDir = ${JSON.stringify(xc)};\n\n const req = get(url, { timeout: 5000 }, (res) => {\n if (res.statusCode !== 200) process.exit(1);\n let data = '';\n res.on('data', (chunk) => data += chunk);\n res.on('end', () => {\n try {\n const version = JSON.parse(data).version;\n if (!fs.existsSync(cacheDir)) fs.mkdirSync(cacheDir, { recursive: true });\n fs.writeFileSync(cacheFile, JSON.stringify({ lastCheck: Date.now(), latestVersion: version }));\n } catch {}\n process.exit(0);\n });\n });\n req.on('error', () => process.exit(1));\n req.on('timeout', () => { req.destroy(); process.exit(1); });\n `;try{g(process.execPath,["--input-type=module","-e",e],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()}catch{}}(),null!=e&&Sc(Zn,e.latestVersion)){if(!0===process[Pc])return;process[Pc]=!0;let t=!1;const n=()=>{if(t)return;t=!0;const n=`${q.yellow(`update available (${Zn} → ${e.latestVersion})`)} - run \`${Ic} upgrade\` to get the latest version\n`;try{v.writeSync(2,n)}catch{}};process.once("beforeExit",n),process.once("exit",n)}}(),Le.cwdChanged&&Jr.debug("Changed working directory",{cwd:Le.newCwd});for(const e of Le.envFilesLoaded)Jr.debug("Loaded env file",{path:e});for(const e of Le.envFileErrors)Jr.warn(e);var Nc=process.argv.findIndex(e=>"-v"===e||"--verbose"===e);-1!==Nc&&process.argv.splice(Nc,1);var Bc=process.argv.findIndex(e=>"--no-telemetry"===e);-1!==Bc&&process.argv.splice(Bc,1),Jr.info("CLI starting",{version:Zn,args:process.argv.slice(2),cwd:process.cwd()}),process.on("unhandledRejection",(e,t)=>{Jr.error("Unhandled promise rejection",{reason:e instanceof Error?{message:e.message,stack:e.stack}:e,promise:String(t)}),Jr.flush(),Jr.printLogFileInfo()}),process.on("uncaughtException",(e,t)=>{"EPIPE"!==e.code&&(Jr.error("Uncaught exception",{error:{message:e.message,stack:e.stack,name:e.name},origin:t}),Jr.flush(),Jr.printLogFileInfo())});var jc=new u;jc.name("stably").description("AI-assisted Playwright testing CLI").version(Zn),jc.enablePositionalOptions(),jc.showHelpAfterError(),jc.exitOverride(),jc.configureHelp({subcommandTerm:e=>{const t=e.registeredArguments.map(e=>e.required?`<${e.name()}>`:`[${e.name()}]`).join(" ");return t?`${e.name()} ${t}`:e.name()}});var Mc=[];jc.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>{Mc.push(e)}});var Fc=()=>{const e=jc.helpInformation().trimEnd();return e?`${e}\n`:""},Hc=(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},Gc=()=>{process.stdout.write(Fc())};jc.command("help [command...]").description("Show help for a command (e.g. stably help create)").action(e=>{if(!e||0===e.length)return void Gc();const t=Hc(jc,e);if(!t)return process.stderr.write(`Unknown command: ${e.join(" ")}\n`),Gc(),void(process.exitCode=1);var n;n=t,process.stdout.write((e=>{const t=e.helpInformation().trimEnd();return t?`${t}\n`:""})(n))}),jc.action(()=>sc({mode:"chat",getHelpText:Fc})),jc.command("login").description("Authenticate with Stably in your browser").action(Lr),jc.command("logout").description("Clear stored Stably credentials").action(async()=>{const e=Xr();e&&(ce.warn(`Environment variables ${q.cyan("STABLY_API_KEY")} and ${q.cyan("STABLY_PROJECT_ID")} are set.`),ce.warn("They will continue to be used for authentication even after logout."),ce.warn("Unset them if you want to fully de-authenticate this shell/session."));const t=await Ir();if(!t)return void le(e?q.yellow("No stored OAuth login found to clear."):q.yellow("You are not logged in."));const n=ue();n.start("Logging out..."),await(async e=>{try{await fetch(`${nr}/api/backend/v1/logout`,{body:JSON.stringify({refresh_token:e}),headers:{"Content-Type":"application/json"},method:"POST"})}catch{}})(t.refreshToken),await Er(),await xr(),n.stop(q.green("✓ Logged out")),le(q.green("You have been logged out successfully."))}),jc.command("whoami").description("Show auth status and current project").action(async()=>{ce.info(`${q.bold("CLI Version:")} ${q.cyan(Zn)}`);const e=Xr();if(e){ce.info(q.dim("Authentication: Environment variables")),ce.info(` ${q.bold("API Key:")} ${q.cyan(e.apiKey.slice(0,8))}...`),ce.info(` ${q.bold("Project ID:")} ${q.cyan(e.projectId)}`);const t=await Ir();if(t){let e;try{e=hr(t.accessToken).email}catch{e=void 0}ce.warn("Stored OAuth login detected but will be ignored (env auth takes precedence)."),e&&ce.info(` ${q.bold("OAuth Email:")} ${q.cyan(e)}`),ce.info(` ${q.bold("Tip:")} Unset env vars to use OAuth`)}return void le(q.green("Authenticated via environment variables"))}const t=await Ir();if(!t)return void le(q.yellow("Not logged in. Run `stably login` to authenticate."));let n;try{n=hr(t.accessToken).email}catch{n=void 0}const o=await Sr();if(!o)return ce.info(q.dim("Authentication: OAuth (not linked to a project)")),n&&ce.info(` ${q.bold("Email:")} ${q.cyan(n)}`),void le(q.yellow("Logged in but this directory is not linked to a project. Run `stably login` to link."));const s=await(async()=>gr(process.cwd(),br))(),i=s?r.dirname(s):process.cwd(),a=r.relative(process.cwd(),i)||".";ce.info(q.dim("Authentication: OAuth")),n&&ce.info(` ${q.bold("Email:")} ${q.cyan(n)}`),ce.info(` ${q.bold("Organization:")} ${q.cyan(o.orgName)}`),ce.info(` ${q.bold("Project:")} ${q.cyan(o.projectName)}`),ce.info(` ${q.bold("Linked at:")} ${q.dim(a)}`),le(q.green("Authenticated"))}),jc.command("tunnel",{hidden:!0}).description("Expose a local server with a secure tunnel URL").option("-p, --port <number>","Local port to expose","3000").action(async e=>{de(`Starting development server for port ${e.port}...`);const t=await eo(),n="oauth"===t.type?`${t.auth.context.orgName}-${t.auth.context.projectName}`.toLowerCase().replace(/[^a-z0-9-]/g,""):`project-${t.auth.projectId}`.toLowerCase(),r=ue();r.start("Starting development server...");const o=await ke(`http://localhost:${e.port}`,{subdomain:n});r.stop(`Your local environment is available at: ]8;;${o.url}${q.underline(q.cyan(o.url))}]8;;`)}),jc.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 sc({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)=>sc({mode:"single",prompt:e,outputDir:t.output})),jc.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 sc({mode:"verify",prompt:e,url:t.url,maxBudgetUsd:t.maxBudget,interactive:t.interactive})}),jc.command("internal-fix-run <runId>",{hidden:!0}).description("Internal: run fix session in subprocess").action(async e=>sc({mode:"fix",runId:e})),jc.command("fix [runId]").description("Fix failing tests from a run (auto-detects from last test run or CI)").action(async e=>{(function(e){try{return h("git rev-parse --is-inside-work-tree",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}})(process.cwd())||(Jr.error('Not a git repository. The "stably fix" command requires a git repository to track changes made during the fix. Please run this command from inside a git repository.'),process.stderr.write('Error: Not a git repository.\nThe "stably fix" command requires a git repository to track changes made during the fix.\nPlease run this command from inside a git repository.\n'),process.exit(1));const t=await(async e=>{const t=e=>e.replace(/\//g,"_");if(e)return Jr.debug("Run ID provided explicitly",{runId:e}),t(e);const n=function(){if(process.env.CI_BUILD_ID)return process.env.CI_BUILD_ID;const e=(({env:e=process.env,cwd:t=process.cwd()}={})=>{for(const n of Object.keys(An))if(An[n].detect({env:e,cwd:t}))return{isCi:!0,...An[n].configuration({env:e,cwd:t})};return{isCi:Boolean(e.CI),...(n={env:e,cwd:t},{commit:Jt(n),branch:Qt(n)})};var n})();if(!e.isCi)return;const t=function(e){switch(e){case"github":return process.env.GITHUB_RUN_ATTEMPT;case"azure-devops":return process.env.SYSTEM_JOBATTEMPT;case"bitbucket":return process.env.BITBUCKET_STEP_RUN_NUMBER;default:return}}(e.service),n=[e.service,"slug"in e?e.slug?.replace(/\//g,"_"):void 0,"build"in e?String(e.build):void 0,"job"in e?String(e.job):void 0,t&&String(t)].filter(Boolean);return n.length>0?n.join("-"):void 0}();if(n)return Jr.debug("Run ID detected from CI environment",{runId:n}),t(n);Jr.debug("No explicit run ID or CI environment detected, checking last-run.json");const r=await(async()=>{try{const e=await gr(process.cwd(),".stably/last-run.json");if(!e)return;const t=await Z(e,"utf-8");return{...ic.parse(JSON.parse(t)),filePath:e}}catch{return}})();if(r){const e=(Date.now()-r.timestamp)/36e5;return Jr.debug("Run ID found in last-run.json",{runId:r.runId,timestamp:r.timestamp,filePath:r.filePath,ageHours:Math.round(e)}),e>24&&Jr.warn(`Using run ID from ${Math.round(e)} hours ago (${r.filePath}). Provide an explicit run ID if this is not the run you want to fix.`),t(r.runId)}Jr.debug("No run ID found in last-run.json")})(e);t||(process.stderr.write('Run ID is required. Either:\n 1. Run "stably test" first (run ID will be auto-detected)\n 2. Provide a run ID: stably fix <runId>\n 3. Run in CI (auto-detected from environment)\n'),process.exit(1));const n=await(async e=>{const t=await eo(),n=no(t),r=to(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})=>g(e,t,n)})=>{const u=(({baseEnv:e,stablyApiKey:t,stablyProjectId:n,playwrightSession:r})=>{const o={...e};for(const e of Object.keys(o))Oc(e)&&delete o[e];return{...o,STABLY_API_KEY:t,STABLY_PROJECT_ID:n,...r?{STABLY_PLAYWRIGHT_SESSION:r}:{}}})({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)}),jc.command("init").description("Initialize Playwright and Stably SDK in your project").action(async()=>sc({mode:"init"})),jc.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;kc(q.cyan("Checking for updates...\n"));try{n=await async function(){const e=await async function(){const e=new AbortController,t=setTimeout(()=>e.abort(),1e4);t.unref();try{const t=await fetch(Tc,{signal:e.signal});if(!t.ok)throw new Error(`Failed to fetch latest version: ${t.statusText}`);return Lc.parse(await t.json()).version}finally{clearTimeout(t)}}();return{current:Zn,latest:e,isOutdated:Sc(Zn,e)}}()}catch(e){return Uc(q.red("Failed to check for updates:"),e instanceof Error?e.message:e),void(process.exitCode=1)}if(kc(`Current version: ${q.yellow(n.current)}`),kc(`Latest version: ${q.green(n.latest)}`),kc(),!n.isOutdated)return void kc(q.green("✓ You are already on the latest version!"));if(kc(q.yellow(`⚠ A new version is available: ${n.current} → ${n.latest}`)),kc(),t)return kc(q.dim("Exiting with code 1 to indicate update available (useful for CI).")),void(process.exitCode=1);const r=function(){const e=process.argv[1]||"";if(e.includes("_npx")||e.includes(".npm/_cacache")||e.includes(".npm\\_cacache"))return"npx";try{const t=h("npm root -g",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-npm"}catch{}if(e.includes("node_modules/stably")||e.includes("node_modules\\stably"))return"global-npm";try{const t=h("pnpm root -g",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-pnpm"}catch{}try{const t=h("yarn global dir",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-yarn-classic"}catch{}try{const t=h("yarn config get globalFolder",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-yarn-berry"}catch{}return"unknown"}(),o=function(e){switch(e){case"global-npm":case"global-yarn-berry":case"unknown":return{command:"npm",args:["install","-g","--no-fund",`${Ic}@latest`],description:`npm install -g ${Ic}@latest`};case"global-pnpm":return{command:"pnpm",args:["add","-g",`${Ic}@latest`],description:`pnpm add -g ${Ic}@latest`};case"global-yarn-classic":return{command:"yarn",args:["global","add",`${Ic}@latest`],description:`yarn global add ${Ic}@latest`};case"npx":return{command:"npx",args:[`${Ic}@latest`],description:`npx ${Ic}@latest (always uses latest)`}}}(r);if("npx"===r)return kc(q.dim("You are running via npx, which always fetches the latest version.")),void kc(q.dim(`Simply run: ${q.white("npx stably")} to use the latest version.`));"unknown"===r?(kc(q.yellow("Could not detect installation method. Falling back to npm.")),kc()):"global-yarn-berry"===r&&(kc(q.yellow("Yarn Berry does not support global packages. Falling back to npm.")),kc()),kc(`Upgrade command: ${q.cyan(o.description)}`),kc(),kc(q.cyan("Upgrading...")),kc();try{await(s=o.command,i=o.args,new Promise((e,t)=>{const n=g(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{v.unlinkSync(Ac)}catch{}}(),kc(),kc(q.green("✓ Upgrade complete!")),kc(q.dim(`Run ${q.white("stably --version")} to verify.`))}catch(e){Uc(q.red("Upgrade failed:"),e instanceof Error?e.message:e),kc(),kc(q.dim("You can try manually running:")),kc(q.cyan(` ${o.description}`)),process.exitCode=1}var s,i}(e));var Wc=jc.command("env").description("Manage remote environments");Wc.command("list").description("List available environments").action(async()=>{const e=await eo(),t=to(e),n=no(e);Jr.debug("Listing environments",{projectId:t});const r=await(o={auth:n,client:cr(),path:{projectId:t}},(o.client??Jn).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/environments",...o}));var o;401!==r.response.status&&403!==r.response.status||(le(q.red("Access denied.")),process.exit(1)),r.error&&(le(q.red(`Failed to list environments: ${r.response.status}`)),process.exit(1));const{environments:s}=r.data;if(0!==s.length){process.stdout.write(`${q.bold("Environments")}\n\n`);for(const e of s){const t=e.isDefault?q.green(" (default)"):"",n=q.dim(` ${e.variableCount} variable${1!==e.variableCount?"s":""}`);process.stdout.write(` ${q.cyan(e.name)}${t}${n}\n`),e.description&&process.stdout.write(` ${q.dim(e.description)}\n`)}process.stdout.write("\n")}else process.stdout.write(q.dim("No environments found. Create one on your Stably dashboard.\n"))}),Wc.command("inspect <name>").description("Show variable metadata (name, sensitive flag, updated timestamp)").action(e=>(async e=>{const t=await eo(),n=to(t),r=no(t);Jr.debug("Inspecting environment",{name:e,projectId:n});const o=await(s={auth:r,client:cr(),path:{projectId:n,environmentName:e}},(s.client??Jn).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/environments/{environmentName}/inspect",...s}));var s;404===o.response.status&&(le(q.red(`Environment "${e}" not found. Run ${q.bold("stably env list")} to see available environments.`)),process.exit(1)),401!==o.response.status&&403!==o.response.status||(le(q.red("Access denied.")),process.exit(1)),o.error&&(le(q.red(`Failed to inspect environment: ${o.response.status}`)),process.exit(1));const{variables:i}=o.data;if(0!==i.length){process.stdout.write(`${q.bold(e)} ${q.dim(`(${i.length} variable${1!==i.length?"s":""})`)}\n\n`);for(const e of i){const t=q.dim(` [updated ${dc(e.updatedAt)}]`);e.sensitive?process.stdout.write(` ${q.cyan(e.name)} ${q.yellow("[sensitive]")}${t}\n`):process.stdout.write(` ${q.cyan(e.name)}${t}\n`)}process.stdout.write("\n")}else process.stdout.write(q.dim(`Environment "${e}" has no variables.\n`))})(e));var Yc=jc.command("runs").description("View test run history");Yc.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 eo(),n=to(t),r=no(t),o=wc(t);let s;e.limit&&(s=parseInt(e.limit,10),(Number.isNaN(s)||s<1||s>100)&&(le(q.red("--limit must be an integer between 1 and 100")),process.exit(1)));const i=vc(e.source,["LOCAL","CI","WEB"],"--source"),a=vc(e.status,["QUEUED","RUNNING","PASSED","FAILED","TIMEDOUT","CANCELLED","INTERRUPTED"],"--status"),c=vc(e.trigger,["MANUAL","SCHEDULED","UI","API","GITHUB_ACTION","SUITE_RUN"],"--trigger");Jr.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 Qn({auth:r,client:cr(),headers:oo(o),query:{projectId:n,branchName:e.branch,limit:s,afterRunId:e.after,beforeRunId:e.before,source:i,status:a,suiteName:e.suite,trigger:c}});_c(l,"list runs");const{runs:u,hasMore:d}=l.data;e.json?process.stdout.write(bc(l.data)):process.stdout.write(((e,t)=>{if(0===e.length)return q.dim("No runs found matching the specified filters.\n");const n=Math.min(40,Math.max(10,...e.map(e=>e.runId.length))),r={runId:{w:n+2,t:n},status:{w:14},branch:{w:32,t:30},started:{w:18}},o=[],s=`${yc("Run ID",r.runId.w)}${yc("Status",r.status.w)}${yc("Branch",r.branch.w)}${yc("Started",r.started.w)}Tests`;o.push(q.bold(s));for(const t of e){const e=fc(t.runId,r.runId.t),n=gc(t.status),s=fc(t.branchName,r.branch.t),i=hc(t.startedAt),a=t.totalCount.toString();o.push(`${yc(e,r.runId.w)}${yc(n,r.status.w)}${yc(s,r.branch.w)}${yc(i,r.started.w)}${a}`)}if(t&&e.length>0){const t=e.at(-1)?.runId;t&&(o.push(""),o.push(q.dim(`Next page: stably runs list --before ${t}`)))}return o.push(""),o.join("\n")})(u,d))}),Yc.command("view <runId>").description("Show details for a specific run").option("--json","Output as JSON").action(async(e,t)=>{const n=await eo(),r=no(n),o=wc(n);Jr.debug("Viewing run",{runId:e});const s=await Xn({auth:r,client:cr(),headers:oo(o),path:{runId:e},query:{detail:"full"}});if(_c(s,"get run details",`Run "${e}" not found.`),t.json)process.stdout.write(bc(s.data));else{const e=s.data;process.stdout.write((e=>{const t=[];if(t.push(q.bold(`Run ${e.runId}`)),t.push(` ${q.dim("Status:")} ${gc(e.status)}`),e.branchName&&t.push(` ${q.dim("Branch:")} ${e.branchName}`),e.commitSha&&t.push(` ${q.dim("Commit:")} ${e.commitSha.slice(0,7)}`),e.startedAt&&t.push(` ${q.dim("Started:")} ${hc(e.startedAt)}`),null!==e.durationMs&&t.push(` ${q.dim("Duration:")} ${(e=>{if(null===e)return"-";const t=Math.floor(e/1e3);if(t<60)return`${t}s`;const n=Math.floor(t/60);return n<60?`${n}m ${t%60}s`:`${Math.floor(n/60)}h ${n%60}m`})(e.durationMs)}`),e.source&&t.push(` ${q.dim("Source:")} ${e.source.toLowerCase()}`),e.projectId){const n=`https://app.stably.ai/project/${e.projectId}/playwright/history/${e.runId}`;t.push(` ${q.dim("URL:")} ${q.cyan(q.underline(n))}`)}t.push("");const n=[];e.passedCount>0&&n.push(q.green(`${e.passedCount} passed`)),e.failedCount>0&&n.push(q.red(`${e.failedCount} failed`)),e.flakyCount>0&&n.push(q.yellow(`${e.flakyCount} flaky`)),e.timedoutCount>0&&n.push(q.red(`${e.timedoutCount} timedout`)),e.skippedCount>0&&n.push(q.dim(`${e.skippedCount} skipped`)),e.interruptedCount>0&&n.push(q.yellow(`${e.interruptedCount} interrupted`)),t.push(`${q.bold("Test Results:")} ${n.join(", ")}`);const r=e.testCases.filter(e=>"FAILED"===e.status||"TIMEDOUT"===e.status||"INTERRUPTED"===e.status||"FLAKY"===e.status);if(r.length>0){t.push(""),t.push(q.bold("Failed/Flaky Tests:"));for(const e of r){const n=e.status??"UNKNOWN",r=pc[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}${q.dim(c)}`);const u=i?.at(-1);if(u?.errorMessage){const e=u.errorMessage.split("\n")[0]?.slice(0,100)??"";t.push(` ${q.dim(e)}`)}}}return t.push(""),t.join("\n")})(e))}}),jc.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)}),ac.forEach(({args:e,description:t,name:n})=>{jc.command(n).description(t).helpOption(!1).helpCommand(!1).allowUnknownOption(!0).allowExcessArguments(!0).passThroughOptions().action(()=>uc({overrideArgs:e,subcommand:n}))});var Vc=()=>{0!==Mc.length&&(process.stderr.write(Mc.join("")),Mc=[])};(async()=>{await(async()=>{if(!Dc&&"1"!==process.env.STABLY_DISABLE_TELEMETRY&&"1"!==process.env.DO_NOT_TRACK&&!process.argv.includes("--no-telemetry"))try{const{init:e}=await import("@hyperdx/node-opentelemetry");e({apiKey:"61d10b50-9534-47be-a732-95bfe461adb7",service:"stably-cli",consoleCapture:!0,disableTracing:!0,disableMetrics:!0,disableStartupLogs:!0,additionalResourceAttributes:{"cli.version":Zn,"node.version":process.version,"os.platform":process.platform}}),Dc=!0}catch{}})();try{await jc.parseAsync(process.argv),Jr.info("CLI completed successfully")}catch(e){if(!(e=>!!e&&"object"==typeof e&&"code"in e)(e)){const t=e instanceof Error?e.message:String(e);return Jr.error(t,{stack:e instanceof Error?e.stack:void 0}),Vc(),Jr.flush(),Jr.printLogFileInfo(),await $c(),void(process.exitCode=1)}const t="number"==typeof e.exitCode?e.exitCode:1,n=process.argv.slice(2).find(e=>!e.startsWith("-")),r=!!n&&!!Hc(jc,[n]);if(("commander.excessArguments"===e.code||"commander.unknownCommand"===e.code)&&n&&!r)return Mc=[],Jr.warn("Unknown command",{command:n}),process.stderr.write(`command '${n}' not found\n`),Gc(),void(process.exitCode=t);Jr.debug("Commander error",{code:e.code,exitCode:t}),Vc(),process.exitCode=t}finally{Jr.flush(),await $c()}})();
|
|
2
|
+
import{config as e,parse as t}from"dotenv";import*as r from"path";import n,{resolve as s,dirname as o,join as i,basename as a,sep as c,normalize as l}from"path";import{simpleGit as u}from"simple-git";import d,{constants as p,tmpdir as f}from"os";import h,{randomUUID as g}from"crypto";import{readFile as m,access as y,rm as b,unlink as w,mkdir as v,stat as I,readdir as _,writeFile as T,appendFile as E}from"fs/promises";import S,{z as x}from"zod";import A from"http";import{fileURLToPath as C,URL as R}from"url";import{log as P,outro as k,intro as U,spinner as L,select as D,isCancel as $}from"@clack/prompts";import O from"open";import N from"picocolors";import B from"pino";import j from"sonic-boom";import*as M from"fs";import F,{existsSync as H,readFileSync as G,mkdirSync as Y,writeFileSync as W,appendFileSync as V,rmSync as z,statSync as K,realpathSync as q,createReadStream as J,openSync as X,readSync as Q,closeSync as Z}from"fs";import{createInterface as ee}from"readline/promises";import{z as te}from"zod/v3";import re from"ws";import ne,{execSync as se,spawn as oe,exec as ie,execFile as ae,execFileSync as ce}from"child_process";import{debuglog as le,promisify as ue,TextDecoder as de,TextEncoder as pe}from"util";import{useState as fe,useEffect as he,useRef as ge,useCallback as me,useMemo as ye}from"react";import{jsx as be,jsxs as we}from"react/jsx-runtime";import{createRequire as ve}from"module";import{match as Ie}from"ts-pattern";import{query as _e,createSdkMcpServer as Te,tool as Ee}from"@anthropic-ai/claude-agent-sdk";import{parseDocument as Se}from"yaml";import xe from"net";import{Command as Ae}from"commander";import{Buffer as Ce}from"buffer";import Re from"process";import"timers/promises";import Pe from"stream";import{startTunnel as ke}from"@stablyhq/runner-sdk";var Ue,Le,De,$e,Oe,Ne,Be=Object.defineProperty,je=Object.getOwnPropertyNames,Me=(e=>"undefined"!=typeof require?require:"undefined"!=typeof Proxy?new Proxy(e,{get:(e,t)=>("undefined"!=typeof require?require:e)[t]}):e)(function(e){if("undefined"!=typeof require)return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),Fe=(e,t)=>function(){return e&&(t=(0,e[je(e)[0]])(e=0)),t},He=(e,t)=>{for(var r in t)Be(e,r,{get:t[r],enumerable:!0})},Ge=Fe({"src/env-loader.ts"(){if(Ue={cwdChanged:!1,newCwd:void 0,envFilesLoaded:[],envFileErrors:[],remoteEnvName:void 0},-1!==(Le=process.argv.findIndex(e=>"-C"===e||"--cwd"===e))&&process.argv[Le+1]){const e=process.argv[Le+1];process.chdir(e),Ue.cwdChanged=!0,Ue.newCwd=e,process.argv.splice(Le,2)}for(De=[],$e=0;$e<process.argv.length;)if("--env-file"===process.argv[$e]){const e=process.argv[$e+1];e&&!e.startsWith("-")?(De.push(e),process.argv.splice($e,2)):$e++}else $e++;-1!==(Oe=process.argv.findIndex(e=>"--env"===e))&&process.argv[Oe+1]&&!process.argv[Oe+1].startsWith("-")&&(Ue.remoteEnvName=process.argv[Oe+1],process.argv.splice(Oe,2));for(const t of De){const r=n.resolve(process.cwd(),t),s=e({path:r,override:!0,quiet:!0});if(s.error){const e=`warning: could not load env file: ${r} (${s.error.message})`;Ue.envFileErrors.push(e),process.stderr.write(`${e}\n`)}else Ue.envFilesLoaded.push(r)}}});async function Ye(e){try{await w(e)}catch{}}var We,Ve,ze,Ke,qe,Je,Xe,Qe,Ze,et,tt,rt,nt,st,ot,it,at,ct,lt,ut,dt,pt,ft,ht,gt,mt,yt,bt,wt,vt,It,_t,Tt,Et,St,xt,At,Ct,Rt,Pt,kt,Ut,Lt,Dt,$t,Ot,Nt,Bt,jt=Fe({"../git-diff-tracker/src/git-diff-tracker.ts"(){Ne=class e{git;config;snapshotTreeHash;snapshotIndexPath;constructor(e){this.config=e,this.git=u({baseDir:e.workingDir,maxConcurrentProcesses:1})}static createLocal({workingDir:t}){return new e({mode:"local",workingDir:t})}static createCloud({workingDir:t,baseBranch:r}){return new e({mode:"cloud",workingDir:t,baseBranch:r})}async captureSnapshot(){if("local"!==this.config.mode)return;this.snapshotIndexPath=i(f(),`git-diff-tracker-${g()}.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(f(),`git-diff-tracker-${g()}.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 Ye(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 Ye(this.snapshotIndexPath),this.snapshotIndexPath=void 0),this.snapshotTreeHash=void 0}}}}),Mt=Fe({"../clients/internal-api-client/dist/chunk-HMKCSECL.js"(){We="x-stably-org-id"}});function Ft(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 Ht,Gt,Yt,Wt,Vt,zt,Kt,qt,Jt,Xt,Qt,Zt,er,tr,rr,nr,sr,or,ir,ar,cr,lr,ur,dr,pr,fr,hr,gr,mr,yr,br,wr,vr,Ir,_r,Tr,Er,Sr,xr,Ar,Cr,Rr,Pr,kr,Ur,Lr,Dr,$r,Or,Nr,Br,jr,Mr,Fr,Hr,Gr,Yr,Wr,Vr,zr,Kr,qr,Jr,Xr,Qr,Zr,en,tn,rn,nn,sn,on,an,cn,ln,un,dn,pn,fn,hn,gn,mn,yn,bn,wn,vn,In,_n,Tn,En,Sn,xn,An,Cn,Rn,Pn,kn=Fe({"../clients/internal-api-client/dist/index.js"(){Ve={bodySerializer:e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t)},ze=({onRequest:e,onSseError:t,onSseEvent:r,responseTransformer:n,responseValidator:s,sseDefaultRetryDelay:o,sseMaxRetryAttempts:i,sseMaxRetryDelay:a,sseSleepFn:c,url:l,...u})=>{let d;const p=c??(e=>new Promise(t=>setTimeout(t,e)));return{stream:async function*(){let c=o??3e3,f=0;const h=u.signal??(new AbortController).signal;for(;!h.aborted;){f++;const o=u.headers instanceof Headers?u.headers:new Headers(u.headers);void 0!==d&&o.set("Last-Event-ID",d);try{const t={redirect:"follow",...u,body:u.serializedBody,headers:o,signal:h};let i=new Request(l,t);e&&(i=await e(l,t));const a=u.fetch??globalThis.fetch,p=await a(i);if(!p.ok)throw new Error(`SSE failed: ${p.status} ${p.statusText}`);if(!p.body)throw new Error("No body in SSE response");const f=p.body.pipeThrough(new TextDecoderStream).getReader();let g="";const m=()=>{try{f.cancel()}catch{}};h.addEventListener("abort",m);try{for(;;){const{done:e,value:t}=await f.read();if(e)break;g+=t;const o=g.split("\n\n");g=o.pop()??"";for(const e of o){const t=e.split("\n"),o=[];let i,a;for(const e of t)if(e.startsWith("data:"))o.push(e.replace(/^data:\s*/,""));else if(e.startsWith("event:"))i=e.replace(/^event:\s*/,"");else if(e.startsWith("id:"))d=e.replace(/^id:\s*/,"");else if(e.startsWith("retry:")){const t=Number.parseInt(e.replace(/^retry:\s*/,""),10);Number.isNaN(t)||(c=t)}let l=!1;if(o.length){const e=o.join("\n");try{a=JSON.parse(e),l=!0}catch{a=e}}l&&(s&&await s(a),n&&(a=await n(a))),r?.({data:a,event:i,id:d,retry:c}),o.length&&(yield a)}}}finally{h.removeEventListener("abort",m),f.releaseLock()}break}catch(e){if(t?.(e),void 0!==i&&f>=i)break;const r=Math.min(c*2**(f-1),a??3e4);await p(r)}}}()}},Ke=e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},qe=e=>{switch(e){case"form":default:return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20"}},Je=e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Xe=({allowReserved:e,explode:t,name:r,style:n,value:s})=>{if(!t){const t=(e?s:s.map(e=>encodeURIComponent(e))).join(qe(n));switch(n){case"label":return`.${t}`;case"matrix":return`;${r}=${t}`;case"simple":return t;default:return`${r}=${t}`}}const o=Ke(n),i=s.map(t=>"label"===n||"simple"===n?e?t:encodeURIComponent(t):Qe({allowReserved:e,name:r,value:t})).join(o);return"label"===n||"matrix"===n?o+i:i},Qe=({allowReserved:e,name:t,value:r})=>{if(null==r)return"";if("object"==typeof r)throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${t}=${e?r:encodeURIComponent(r)}`},Ze=({allowReserved:e,explode:t,name:r,style:n,value:s,valueOnly:o})=>{if(s instanceof Date)return o?s.toISOString():`${r}=${s.toISOString()}`;if("deepObject"!==n&&!t){let t=[];Object.entries(s).forEach(([r,n])=>{t=[...t,r,e?n:encodeURIComponent(n)]});const o=t.join(",");switch(n){case"form":return`${r}=${o}`;case"label":return`.${o}`;case"matrix":return`;${r}=${o}`;default:return o}}const i=Je(n),a=Object.entries(s).map(([t,s])=>Qe({allowReserved:e,name:"deepObject"===n?`${r}[${t}]`:t,value:s})).join(i);return"label"===n||"matrix"===n?i+a:a},et=/\{[^{}]+\}/g,tt=({path:e,url:t})=>{let r=t;const n=t.match(et);if(n)for(const t of n){let n=!1,s=t.substring(1,t.length-1),o="simple";s.endsWith("*")&&(n=!0,s=s.substring(0,s.length-1)),s.startsWith(".")?(s=s.substring(1),o="label"):s.startsWith(";")&&(s=s.substring(1),o="matrix");const i=e[s];if(null==i)continue;if(Array.isArray(i)){r=r.replace(t,Xe({explode:n,name:s,style:o,value:i}));continue}if("object"==typeof i){r=r.replace(t,Ze({explode:n,name:s,style:o,value:i,valueOnly:!0}));continue}if("matrix"===o){r=r.replace(t,`;${Qe({name:s,value:i})}`);continue}const a=encodeURIComponent("label"===o?`.${i}`:i);r=r.replace(t,a)}return r},rt=({baseUrl:e,path:t,query:r,querySerializer:n,url:s})=>{let o=(e??"")+(s.startsWith("/")?s:`/${s}`);t&&(o=tt({path:t,url:o}));let i=r?n(r):"";return i.startsWith("?")&&(i=i.substring(1)),i&&(o+=`?${i}`),o},nt=async(e,t)=>{const r="function"==typeof t?await t(e):t;if(r)return"bearer"===e.scheme?`Bearer ${r}`:"basic"===e.scheme?`Basic ${btoa(r)}`:r},st=({parameters:e={},...t}={})=>r=>{const n=[];if(r&&"object"==typeof r)for(const s in r){const o=r[s];if(null==o)continue;const i=e[s]||t;if(Array.isArray(o)){const e=Xe({allowReserved:i.allowReserved,explode:!0,name:s,style:"form",value:o,...i.array});e&&n.push(e)}else if("object"==typeof o){const e=Ze({allowReserved:i.allowReserved,explode:!0,name:s,style:"deepObject",value:o,...i.object});e&&n.push(e)}else{const e=Qe({allowReserved:i.allowReserved,name:s,value:o});e&&n.push(e)}}return n.join("&")},ot=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},it=(e,t)=>!!t&&!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`)),at=async({security:e,...t})=>{for(const r of e){if(it(t,r.name))continue;const e=await nt(r,t.auth);if(!e)continue;const n=r.name??"Authorization";switch(r.in){case"query":t.query||(t.query={}),t.query[n]=e;break;case"cookie":t.headers.append("Cookie",`${n}=${e}`);break;default:t.headers.set(n,e)}}},ct=e=>rt({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:"function"==typeof e.querySerializer?e.querySerializer:st(e.querySerializer),url:e.url}),lt=(e,t)=>{const r={...e,...t};return r.baseUrl?.endsWith("/")&&(r.baseUrl=r.baseUrl.substring(0,r.baseUrl.length-1)),r.headers=dt(e.headers,t.headers),r},ut=e=>{const t=[];return e.forEach((e,r)=>{t.push([r,e])}),t},dt=(...e)=>{const t=new Headers;for(const r of e){if(!r)continue;const e=r instanceof Headers?ut(r):Object.entries(r);for(const[r,n]of e)if(null===n)t.delete(r);else if(Array.isArray(n))for(const e of n)t.append(r,e);else void 0!==n&&t.set(r,"object"==typeof n?JSON.stringify(n):n)}return t},pt=class{fns=[];clear(){this.fns=[]}eject(e){const t=this.getInterceptorIndex(e);this.fns[t]&&(this.fns[t]=null)}exists(e){const t=this.getInterceptorIndex(e);return Boolean(this.fns[t])}getInterceptorIndex(e){return"number"==typeof e?this.fns[e]?e:-1:this.fns.indexOf(e)}update(e,t){const r=this.getInterceptorIndex(e);return!!this.fns[r]&&(this.fns[r]=t,e)}use(e){return this.fns.push(e),this.fns.length-1}},ft=()=>({error:new pt,request:new pt,response:new pt}),ht=st({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),gt={"Content-Type":"application/json"},yt=(e={})=>{let t=lt(mt(),e);const r=()=>({...t}),n=ft(),s=async e=>{const r={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:dt(t.headers,e.headers),serializedBody:void 0};return r.security&&await at({...r,security:r.security}),r.requestValidator&&await r.requestValidator(r),void 0!==r.body&&r.bodySerializer&&(r.serializedBody=r.bodySerializer(r.body)),void 0!==r.body&&""!==r.serializedBody||r.headers.delete("Content-Type"),{opts:r,url:ct(r)}},o=async e=>{const{opts:t,url:r}=await s(e),o={redirect:"follow",...t,body:Ft(t)};let i=new Request(r,o);for(const e of n.request.fns)e&&(i=await e(i,t));const a=t.fetch;let c=await a(i);for(const e of n.response.fns)e&&(c=await e(c,i,t));const l={request:i,response:c};if(c.ok){const e=("auto"===t.parseAs?ot(c.headers.get("Content-Type")):t.parseAs)??"json";if(204===c.status||"0"===c.headers.get("Content-Length")){let r;switch(e){case"arrayBuffer":case"blob":case"text":r=await c[e]();break;case"formData":r=new FormData;break;case"stream":r=c.body;break;default:r={}}return"data"===t.responseStyle?r:{data:r,...l}}let r;switch(e){case"arrayBuffer":case"blob":case"formData":case"json":case"text":r=await c[e]();break;case"stream":return"data"===t.responseStyle?c.body:{data:c.body,...l}}return"json"===e&&(t.responseValidator&&await t.responseValidator(r),t.responseTransformer&&(r=await t.responseTransformer(r))),"data"===t.responseStyle?r:{data:r,...l}}const u=await c.text();let d;try{d=JSON.parse(u)}catch{}const p=d??u;let f=p;for(const e of n.error.fns)e&&(f=await e(p,c,i,t));if(f=f||{},t.throwOnError)throw f;return"data"===t.responseStyle?void 0:{error:f,...l}},i=e=>t=>o({...t,method:e}),a=e=>async t=>{const{opts:r,url:o}=await s(t);return ze({...r,body:r.body,headers:r.headers,method:e,onRequest:async(e,t)=>{let s=new Request(e,t);for(const e of n.request.fns)e&&(s=await e(s,r));return s},url:o})};return{buildUrl:ct,connect:i("CONNECT"),delete:i("DELETE"),get:i("GET"),getConfig:r,head:i("HEAD"),interceptors:n,options:i("OPTIONS"),patch:i("PATCH"),post:i("POST"),put:i("PUT"),request:o,setConfig:e=>(t=lt(t,e),r()),sse:{connect:a("CONNECT"),delete:a("DELETE"),get:a("GET"),head:a("HEAD"),options:a("OPTIONS"),patch:a("PATCH"),post:a("POST"),put:a("PUT"),trace:a("TRACE")},trace:i("TRACE")}},bt=yt((mt=(e={})=>({...Ve,headers:gt,parseAs:"auto",querySerializer:ht,...e}))({baseUrl:"https://api.stably.ai"})),wt=e=>(e.client??bt).post({security:[{scheme:"bearer",type:"http"}],url:"/v1/proxy/api-key",...e,headers:{"Content-Type":"application/json",...e.headers}}),vt=e=>(e.client??bt).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/orgs/{orgId}/projects",...e}),It=e=>(e.client??bt).post({url:"/internal/v1/cli/exchange-token",...e,headers:{"Content-Type":"application/json",...e.headers}}),_t=e=>(e.client??bt).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/api-key",...e}),Tt=e=>(e.client??bt).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/prompts/system",...e,headers:{"Content-Type":"application/json",...e.headers}}),Et=e=>(e.client??bt).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/prompts/subagents",...e,headers:{"Content-Type":"application/json",...e.headers}}),St=e=>(e.client??bt).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-context",...e}),xt=e=>(e.client??bt).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-report",...e,headers:{"Content-Type":"application/json",...e.headers}}),At=e=>(e.client??bt).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-status",...e,headers:{"Content-Type":"application/json",...e.headers}}),Ct=e=>(e.client??bt).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-diff/upload-url",...e,headers:{"Content-Type":"application/json",...e.headers}}),Rt=e=>(e.client??bt).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-diff/confirm-upload",...e,headers:{"Content-Type":"application/json",...e.headers}}),Pt=e=>(e.client??bt).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-trace/upload-url",...e,headers:{"Content-Type":"application/json",...e.headers}}),kt=e=>(e.client??bt).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/sessions/{sessionId}/trace/upload-url",...e,headers:{"Content-Type":"application/json",...e.headers}}),Ut=e=>(e.client??bt).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/environments",...e}),Lt=e=>(e.client??bt).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/environments/{environment}/variables",...e}),Dt=e=>(e.client??bt).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/environments/{environmentName}/inspect",...e}),$t=e=>(e.client??bt).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/sessions/{sessionId}/files/upload-url",...e,headers:{"Content-Type":"application/json",...e.headers}}),Ot=e=>(e.client??bt).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/sessions/{sessionId}/files/confirm",...e,headers:{"Content-Type":"application/json",...e.headers}}),Nt=e=>(e.client??bt).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs",...e}),Bt=e=>(e.client??bt).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}",...e})}}),Un=Fe({"src/version.ts"(){Ht="4.12.4-rc.0"}}),Ln=Fe({"src/api/stably/constants.ts"(){Gt=process.env.STABLY_API_URL||"https://api.stably.ai",Yt=e=>{const t=new URL(e);return t.protocol="http:"===t.protocol?"ws:":"wss:",t},Wt=process.env.AUTH_URL||"https://auth.stably.ai",Vt=process.env.AUTH_CLIENT_ID||"288007877071cce81f269428ea78653a",zt=process.env.AI_PROXY_URL||"https://ai-proxy.stably.ai",Kt=process.env.STABLY_AUTOHEAL_WS_URL||new URL("/autoheal",Yt(Gt)).toString(),qt=process.env.STABLY_CREATE_PROGRESS_WS_URL||new URL("/create-progress",Yt(Gt)).toString(),Xt=`http://localhost:${Jt=9876}/auth/callback`}}),Dn=Fe({"src/api/stably/internal-api-client.ts"(){kn(),Un(),Ln(),Zt=()=>Qt||(Qt=yt(mt({baseUrl:Gt,headers:{"X-STABLY-CLI-VERSION":Ht,"X-STABLY-SOURCE":"cli"}})))}}),$n=Fe({"src/api/stably/token.ts"(){kn(),Dn(),er=async(e,t)=>{const r=await It({body:{accessToken:e,orgId:t},client:Zt()});if(401===r.response.status)throw new Error("Invalid or expired access token");if(403===r.response.status)throw new Error("You do not have access to this organization");if(r.error)throw new Error(`Failed to exchange token: ${r.response.status}`);return r.data}}}),On=Fe({"src/api/stably/jwt.ts"(){tr=x.object({org_id:x.string(),org_name:x.string()}),rr=x.object({email:x.string(),org_id_to_org_member_info:x.record(x.string(),tr).optional(),org_member_info:tr.optional(),user_id:x.string()}),x.object({email:x.string(),firstName:x.string().optional(),lastName:x.string().optional(),organizations:x.array(x.object({id:x.string(),name:x.string()})),userId:x.string()}),nr=e=>{const t=e.split(".");if(3!==t.length)throw new Error("Invalid JWT format");const r=t[1].replace(/-/g,"+").replace(/_/g,"/"),n=Buffer.from(r,"base64").toString("utf-8");return JSON.parse(n)},sr=e=>{try{const t=rr.parse(nr(e)),r=t.org_id_to_org_member_info?Object.entries(t.org_id_to_org_member_info).map(([e,t])=>({id:e,name:t.org_name})):t.org_member_info?[{id:t.org_member_info.org_id,name:t.org_member_info.org_name}]:[];return{email:t.email,organizations:r,userId:t.user_id}}catch(e){throw new Error(`Failed to decode token: ${e instanceof Error?e.message:"Unknown error"}`)}},or=e=>{try{const t=rr.parse(nr(e));if(t.org_id_to_org_member_info)return"full";if(t.org_member_info)return"org"}catch{return"unknown"}return"unknown"}}}),Nn=Fe({"src/config/find-file-upwards.ts"(){ir=async(e,t)=>{let r=e;const{root:s}=n.parse(r);for(;r!==s;){const e=n.join(r,t);try{return await y(e),e}catch{r=n.dirname(r)}}}}}),Bn=Fe({"src/config/config.ts"(){Nn(),ar=n.join(d.homedir(),".stably"),cr=n.join(ar,"auth.json"),lr=".stably",ur="project.json",dr=S.object({accessToken:S.string(),expiresAt:S.number(),idToken:S.string().optional(),refreshToken:S.string()}),pr=S.object({orgId:S.string(),orgName:S.string(),projectId:S.string(),projectName:S.string()}),fr=async()=>{try{const e=await m(cr,"utf-8");return dr.parse(JSON.parse(e))}catch{return}},hr=async e=>{await v(ar,{recursive:!0}),await T(cr,JSON.stringify(e,null,2),{mode:384})},gr=async()=>{try{await w(cr)}catch{}},mr=async e=>{const t=n.join(e,".gitignore"),r="# Stably CLI (only docs/ are tracked)\n.stably/*\n!.stably/docs/";try{const e=await m(t,"utf-8"),n=e.split("\n").map(e=>e.trim());if(n.includes(".stably/*")&&n.includes("!.stably/docs/"))return;const s=/^# Stably CLI\n\.stably\/?$/m,o=/^\.stably\/?$/m;if(s.test(e)){const n=e.replace(s,`\n${r}\n`);await T(t,n)}else if(o.test(e)){const n=e.replace(o,`\n${r}\n`);await T(t,n)}else await E(t,`\n${r}\n`)}catch{await T(t,`${r}\n`)}},yr=async()=>{try{const e=await ir(process.cwd(),lr);if(!e)return;const t=n.join(e,ur),r=await m(t,"utf-8");return pr.parse(JSON.parse(r))}catch{return}},br=async e=>{const t=n.join(process.cwd(),lr),r=n.join(t,ur);await v(t,{recursive:!0}),await T(r,JSON.stringify(e,null,2)),await mr(process.cwd())},wr=async()=>{try{const e=await ir(process.cwd(),lr);e&&await w(n.join(e,ur))}catch{}},vr=async()=>ir(process.cwd(),lr),Ir=e=>Date.now()>=e.expiresAt-3e5}}),jn=Fe({"src/auth/oauth/tokens.ts"(){Ln(),_r=async(e,t)=>{const r=new URLSearchParams({client_id:Vt,code:e,code_verifier:t,grant_type:"authorization_code",redirect_uri:Xt}),n=await fetch(`${Wt}/propelauth/oauth/token`,{body:r.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},method:"POST"});if(!n.ok){const e=await n.text();throw new Error(`Token exchange failed: ${n.status} ${e}`)}const s=await n.json();return{accessToken:s.access_token,expiresAt:Date.now()+1e3*s.expires_in,idToken:s.id_token,refreshToken:s.refresh_token}},Tr=async e=>{const t=new URLSearchParams({client_id:Vt,grant_type:"refresh_token",refresh_token:e}),r=await fetch(`${Wt}/propelauth/oauth/token`,{body:t.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},method:"POST"});if(!r.ok)throw new Error(`Token refresh failed: ${r.status}`);const n=await r.json();return{accessToken:n.access_token,expiresAt:Date.now()+1e3*n.expires_in,refreshToken:n.refresh_token}},Er=async e=>{try{await fetch(`${Wt}/api/backend/v1/logout`,{body:JSON.stringify({refresh_token:e}),headers:{"Content-Type":"application/json"},method:"POST"})}catch{}}}}),Mn=Fe({"src/api/stably/projects.ts"(){kn(),Dn(),Sr=async({accessToken:e,orgId:t})=>{const r=await vt({auth:e,client:Zt(),path:{orgId:t}});if(401===r.response.status)throw new Error("Invalid or expired access token");if(403===r.response.status)throw new Error("You do not have access to this organization");if(r.error)throw new Error(`Failed to list projects: ${r.response.status}`);return r.data.projects},xr=async({accessToken:e,projectId:t})=>{const r=await _t({auth:e,client:Zt(),path:{projectId:t}});if(r.error){const e=r.error?.error,{status:t}=r.response;throw new Error(e??`Failed to get API key: ${t}`)}return r.data}}}),Fn=Fe({"src/auth/oauth/templates.ts"(){Ar='\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',Cr=e=>`\n<!DOCTYPE html>\n<html>\n<head>\n <title>Authentication Failed Stably CLI</title>\n <style>\n * { box-sizing: border-box; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n display: flex;\n justify-content: center;\n align-items: center;\n min-height: 100vh;\n margin: 0;\n background: #000;\n color: #fafafa;\n }\n .container {\n text-align: center;\n padding: 48px;\n max-width: 400px;\n }\n .icon {\n width: 48px;\n height: 48px;\n border-radius: 50%;\n background: #ef4444;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 24px;\n }\n .icon svg { width: 24px; height: 24px; }\n .title {\n font-size: 24px;\n font-weight: 600;\n margin: 0 0 8px;\n letter-spacing: -0.5px;\n }\n .subtitle {\n color: #888;\n font-size: 14px;\n margin: 0 0 32px;\n line-height: 1.5;\n }\n .error-box {\n background: rgba(239, 68, 68, 0.1);\n border: 1px solid rgba(239, 68, 68, 0.3);\n border-radius: 8px;\n padding: 16px;\n margin-bottom: 24px;\n }\n .error-label {\n font-size: 11px;\n font-weight: 600;\n color: #ef4444;\n text-transform: uppercase;\n letter-spacing: 0.5px;\n margin-bottom: 8px;\n }\n .error-message {\n font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace;\n font-size: 13px;\n color: #fafafa;\n word-break: break-word;\n }\n .hint {\n color: #666;\n font-size: 13px;\n }\n .hint code {\n background: #111;\n border: 1px solid #333;\n border-radius: 4px;\n padding: 2px 6px;\n font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace;\n font-size: 12px;\n color: #888;\n }\n .brand {\n margin-top: 32px;\n font-size: 12px;\n color: #444;\n letter-spacing: 0.5px;\n }\n </style>\n</head>\n<body>\n <div class="container">\n <div class="icon">\n <svg fill="none" stroke="#000" stroke-width="3" viewBox="0 0 24 24">\n <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/>\n </svg>\n </div>\n <h1 class="title">Authentication Failed</h1>\n <p class="subtitle">Something went wrong during login.</p>\n <div class="error-box">\n <div class="error-label">Error</div>\n <div class="error-message">${e}</div>\n </div>\n <p class="hint">Run <code>stably login</code> to try again.</p>\n <div class="brand">STABLY</div>\n </div>\n</body>\n</html>\n`}}),Hn=Fe({"src/auth/oauth/callback-server.ts"(){Ln(),Fn(),Rr=(e,t,r)=>{e.writeHead(t,{"Content-Type":"text/html"}),e.end(r)},Pr=e=>{let t,r;return{ready:new Promise((e,n)=>{t=e,r=n}),result:new Promise((n,s)=>{const o=setTimeout(()=>{a.close(),n({error:"Login timed out",success:!1})},3e5),i=()=>{clearTimeout(o)},a=A.createServer((t,r)=>{const s=new R(t.url||"",`http://localhost:${Jt}`);if("/auth/callback"!==s.pathname)return r.writeHead(404),void r.end("Not found");const o=s.searchParams.get("code"),c=s.searchParams.get("state"),l=s.searchParams.get("error");return l?(Rr(r,400,Cr(l)),i(),a.close(),void n({error:l,success:!1})):o&&c?c!==e?(Rr(r,400,Cr("Invalid state parameter (possible CSRF attack)")),i(),a.close(),void n({error:"State mismatch",success:!1})):(Rr(r,200,Ar),i(),a.close(),void n({code:o,state:c,success:!0})):(Rr(r,400,Cr("Missing code or state parameter")),i(),a.close(),void n({error:"Missing code or state parameter",success:!1}))});a.on("error",e=>{if(i(),"EADDRINUSE"===e.code){const e=new Error(`Port ${Jt} is already in use. Please close the application using it and try again.`);return r(e),void s(e)}const t=new Error(`Failed to start callback server: ${e.message}`);r(t),s(t)}),a.listen(Jt,()=>{t()})})}}}}),Gn=Fe({"src/auth/oauth/pkce.ts"(){Ln(),kr=()=>h.randomBytes(32).toString("base64url"),Ur=e=>h.createHash("sha256").update(e).digest("base64url"),Lr=()=>h.randomBytes(16).toString("base64url"),Dr=(e,t)=>{const r=new URLSearchParams({client_id:Vt,code_challenge:e,code_challenge_method:"S256",redirect_uri:Xt,response_type:"code",state:t});return`${Wt}/propelauth/oauth/authorize?${r.toString()}`}}}),Yn=Fe({"src/auth/oauth/oauth.ts"(){Hn(),Gn(),jn(),$r=()=>{const e=kr(),t=Ur(e),r=Lr();return{authorizeUrl:Dr(t,r),codeVerifier:e,state:r}},Or=()=>{const{authorizeUrl:e,codeVerifier:t,state:r}=$r(),{ready:n,result:s}=Pr(r);return{authorizeUrl:e,serverReady:n,waitForCallback:async()=>{const e=await s;if(!e.success)throw new Error(e.error);return _r(e.code,t)}}}}}),Wn=Fe({"src/auth/login.ts"(){On(),Mn(),$n(),Bn(),Yn(),jn(),Kn(),Nr=async e=>{if(0===e.length)return void P.error("You don't belong to any organizations.");if(1===e.length)return P.info(`Using organization: ${N.cyan(e[0].name)}`),e[0];if(!process.stdin.isTTY)return P.info(`Auto-selecting organization: ${N.cyan(e[0].name)}`),e[0];const t=await D({message:"Select an organization",options:[...e].sort((e,t)=>e.name.localeCompare(t.name)).map(e=>({label:e.name,value:e.id}))});return $(t)?void 0:e.find(e=>e.id===t)},Br=async(e,t)=>{const r=L();let n;r.start("Loading projects...");try{n=await Sr({accessToken:e,orgId:t}),r.stop(N.green("✓ Projects loaded"))}catch(e){r.stop(N.red("✗ Failed to load projects"));const t=e instanceof Error?e.message:"Unknown error";return void P.error(t)}if(0===n.length)return P.error("No projects found in this organization."),void P.info(`Create a project at ${N.underline(N.cyan("https://app.stably.ai"))}`);if(1===n.length)return P.info(`Using project: ${N.cyan(n[0].name)}`),n[0];if(!process.stdin.isTTY)return P.info(`Auto-selecting project: ${N.cyan(n[0].name)}`),n[0];const s=await D({message:"Select a project",options:n.map(e=>({label:e.name,value:e.id}))});return $(s)?void 0:n.find(e=>e.id===s)},jr=async e=>{const t=L();let r;t.start("Loading user info...");try{r=sr(e.accessToken),t.stop(N.green(`✓ Logged in as ${N.cyan(r.email)}`))}catch(e){t.stop(N.red("✗ Failed to load user info"));const r=e instanceof Error?e.message:"Unknown error";return P.error(r),{success:!1}}const n=await Nr(r.organizations);if(!n)return P.warn("Organization selection cancelled."),{success:!1};let s;t.start("Getting org credentials...");try{const r=await er(e.accessToken,n.id);s={accessToken:r.accessToken,expiresAt:Date.now()+1e3*r.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken},t.stop(N.green("✓ Credentials obtained"))}catch(e){t.stop(N.red("✗ Failed to get org credentials"));const r=e instanceof Error?e.message:"Unknown error";return P.error(r),{success:!1}}const o=await Br(s.accessToken,n.id);return o?(await br({orgId:n.id,orgName:n.name,projectId:o.id,projectName:o.name}),P.info(N.dim("Linked this directory to your Stably project.")),{scopedTokens:s,success:!0}):(P.warn("Project selection cancelled."),{success:!1})},Mr=async()=>{if(wn())return P.warn(`Environment variables ${N.cyan("STABLY_API_KEY")} and ${N.cyan("STABLY_PROJECT_ID")} are set.`),P.warn("These will be used for authentication instead of OAuth login."),P.warn("To use OAuth login, unset these environment variables first."),void k(N.yellow("Login skipped - using environment variable authentication."));const e=await fr();if(e){if(!Ir(e)){if(await yr())return void k(N.yellow("You are already logged in. Run `stably logout` first to log out."));P.info("You are logged in but haven't selected a project yet.");const t=await jr(e);return void(t.success?(await hr(t.scopedTokens),k(N.green("Setup complete! You can now use Stably CLI."))):k(N.yellow("Setup incomplete. Run `stably login` to try again.")))}const t=L();t.start("Refreshing session...");try{const r=await Tr(e.refreshToken);t.stop(N.green("✓ Session refreshed"));const n=await yr();if(n){t.start("Getting org credentials...");try{const e=await er(r.accessToken,n.orgId),s={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:r.idToken,refreshToken:r.refreshToken};await hr(s),t.stop(N.green("✓ Credentials obtained")),k(N.green("Login successful"))}catch{await hr(r),t.stop(N.yellow("Using full credentials")),k(N.green("Login successful"))}}else{const e=await jr(r);e.success?(await hr(e.scopedTokens),k(N.green("Setup complete! You can now use Stably CLI."))):k(N.yellow("Setup incomplete. Run `stably login` to try again."))}return}catch{t.stop(N.yellow("Session expired, proceeding with fresh login...")),await gr(),await wr()}}const{authorizeUrl:t,serverReady:r,waitForCallback:n}=Or();await r,P.info("Opening browser for authentication..."),P.info(N.dim("If browser doesn't open, visit:")),P.info(`]8;;${t}${N.underline(N.cyan(t))}]8;;`);try{await O(t)}catch{P.warn("Could not open browser automatically. Please open the URL above manually.")}const s=L();let o;s.start("Waiting for authentication...");try{o=await n(),s.stop(N.green("✓ Authentication successful"))}catch(e){s.stop(N.red("✗ Authentication failed"));const t=e instanceof Error?e.message:"Unknown error";k(N.red(`Login failed: ${t}`)),process.exit(1)}const i=await jr(o);i.success?(await hr(i.scopedTokens),k(N.green("Setup complete! You can now use Stably CLI."))):(k(N.yellow("Setup incomplete. Run `stably login` to try again.")),process.exit(1))},Fr=async()=>{const e=wn();e&&(P.warn(`Environment variables ${N.cyan("STABLY_API_KEY")} and ${N.cyan("STABLY_PROJECT_ID")} are set.`),P.warn("They will continue to be used for authentication even after logout."),P.warn("Unset them if you want to fully de-authenticate this shell/session."));const t=await fr();if(!t)return void k(e?N.yellow("No stored OAuth login found to clear."):N.yellow("You are not logged in."));const r=L();r.start("Logging out..."),await Er(t.refreshToken),await gr(),await wr(),r.stop(N.green("✓ Logged out")),k(N.green("You have been logged out successfully."))}}}),Vn=Fe({"src/logger/index.ts"(){Un(),Hr={fatal:60,error:50,warn:40,info:30,debug:20,trace:10},Gr=new Set(["help","login","logout","whoami","tunnel","create","fix","init","upgrade","test","show-report","codegen"]),Yr=(new Date).toISOString().split("T")[0],Wr=(()=>{const e=[n.join(d.tmpdir(),"stably-logs",Yr),n.join(d.homedir(),".stably","logs",Yr)];for(const t of e)try{return F.mkdirSync(t,{recursive:!0}),t}catch{}return null})(),Vr=()=>{const e=new Date;return[e.getHours().toString().padStart(2,"0"),e.getMinutes().toString().padStart(2,"0"),e.getSeconds().toString().padStart(2,"0")].join("-")},zr=(e,t=100)=>e.replace(/[/\\:*?"<>|]/g,"-").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9\-_]/g,"").replace(/-+/g,"-").replace(/^-+|-+$/g,"").slice(0,t).toLowerCase()||"session",Kr=()=>{const e=process.argv.slice(2).find(e=>!e.startsWith("-"));return e&&Gr.has(e)?e:null},qr=process.argv.includes("--verbose")||process.argv.includes("-v"),Jr=process.env.STABLY_LOG_LEVEL?.toLowerCase(),Xr=e=>void 0!==e&&e in Hr,Qr=qr?"debug":Xr(Jr)?Jr:"warn",Zr=Hr[Qr],en=null,tn=null,rn=null,nn=[],sn=!1,on=e=>{if(!Wr)return null;const t=Vr(),r=zr(e);return n.join(Wr,`${t}-${r}.log`)},an=e=>{const t=["","=".repeat(60),"Stably CLI Debug Log",`Version: ${Ht}`,`Generated: ${(new Date).toISOString()}`,`Node: ${process.version}`,`Platform: ${process.platform} ${d.release()}`,`CWD: ${process.cwd()}`,`Args: ${process.argv.slice(2).join(" ")}`,`Log Level (console): ${Qr}`,"=".repeat(60),""].join("\n");e.write(t)},cn=e=>{if(!sn){if(!(en=on(e)))return nn=[],void(sn=!0);tn=new j({dest:en,minLength:4096,sync:!1,append:!0}),an(tn),rn=B({level:"debug",timestamp:B.stdTimeFunctions.isoTime,base:{version:Ht}},tn);for(const{level:e,msg:t,context:r}of nn)r?rn[e](r,t):rn[e](t);nn=[],sn=!0,qr&&process.stderr.write(`${N.dim(`Debug log: ${en}`)}\n\n`)}},(ln=Kr())&&cn(ln),un=(e,t)=>`${{fatal:N.bgRed(N.white(" FATAL ")),error:N.red("error"),warn:N.yellow("warn"),info:N.cyan("info"),debug:N.dim("debug"),trace:N.dim("trace")}[e]} ${t}`,dn=e=>Hr[e]>=Zr,fn={fatal:(pn=e=>(t,r)=>{if(rn?r?rn[e](r,t):rn[e](t):sn||nn.push({level:e,msg:t,context:r}),dn(e)){const r=un(e,t);process.stderr.write(`${r}\n`)}})("fatal"),error:pn("error"),warn:pn("warn"),info:pn("info"),debug:pn("debug"),trace:pn("trace"),initSession:e=>{sn||cn(e)},getLogFilePath:()=>en,flush:()=>{if(tn)try{tn.flushSync()}catch{}},printLogFileInfo:()=>{en&&(process.stderr.write(`\n${N.dim("Debug log written to:")}\n`),process.stderr.write(` ${N.cyan(en)}\n`),process.stderr.write(`${N.dim("Share this file with support for assistance.")}\n`))},getPinoLogger:()=>rn},setInterval(()=>{fn.flush()},3e4).unref(),process.on("beforeExit",()=>{fn.flush()}),hn=e=>{const t=()=>{fn.flush(),qr&&fn.printLogFileInfo(),process.removeListener(e,t),process.kill(process.pid,e)};return t},process.on("SIGINT",hn("SIGINT")),process.on("SIGTERM",hn("SIGTERM"))}}),zn=Fe({"src/utils/ci-environment.ts"(){gn=()=>"true"===process.env.GITHUB_ACTIONS?"github-actions":"true"===process.env.GITLAB_CI?"gitlab-ci":"true"===process.env.CIRCLECI?"circleci":process.env.JENKINS_URL?"jenkins":process.env.CI?"generic-ci":"local",mn=()=>"local"!==gn(),yn=e=>{switch(e){case"github-actions":return"GitHub secrets";case"gitlab-ci":return"GitLab CI/CD variables";case"circleci":return"CircleCI environment variables";case"jenkins":return"Jenkins credentials";case"generic-ci":return"CI secrets/environment variables";case"local":return"environment variables"}},bn=()=>{const e=gn();return[`Authentication failed. In CI, add the following to your ${yn(e)}:`," STABLY_API_KEY → https://app.stably.ai/settings?tab=api-key"," STABLY_PROJECT_ID → https://app.stably.ai/settings?tab=project-id"].join("\n")}}}),Kn=Fe({"src/auth/require-auth.ts"(){$n(),On(),Bn(),jn(),Wn(),Vn(),zn(),wn=()=>{const e=process.env.STABLY_API_KEY?.trim(),t=process.env.STABLY_PROJECT_ID?.trim();if(e&&t)return fn.debug("Environment auth detected",{hasApiKey:!0,hasProjectId:!0}),{apiKey:e,projectId:t};fn.debug("Environment auth not set",{hasApiKey:!!e,hasProjectId:!!t})},vn=async()=>{fn.debug("Checking for stored auth tokens");const e=await fr();if(!e)return void fn.debug("No stored auth tokens found");const t=Ir(e);if(fn.debug("Auth tokens status",{expired:t}),!t){const t=await yr(),r=or(e.accessToken);if(fn.debug("Token scope check",{scope:r,hasContext:!!t}),t&&"full"===r)try{fn.debug("Exchanging full token for org-scoped token",{orgId:t.orgId});const r=await er(e.accessToken,t.orgId),n={accessToken:r.accessToken,expiresAt:Date.now()+1e3*r.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken};return await hr(n),fn.debug("Token exchange successful"),n}catch(t){return fn.debug("Token exchange failed, using existing token",{error:t instanceof Error?t.message:String(t)}),e}return e}try{fn.debug("Attempting token refresh");const t=await Tr(e.refreshToken);fn.debug("Token refresh successful");const r=await yr();if(r)try{fn.debug("Exchanging refreshed token for org-scoped token");const e=await er(t.accessToken,r.orgId),n={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:t.idToken,refreshToken:t.refreshToken};return await hr(n),n}catch{return await hr(t),t}return await hr(t),t}catch(e){return void fn.warn("Token refresh failed",{error:e instanceof Error?e.message:String(e)})}},In=async(e={})=>{fn.debug("Requiring authentication",{autoLogin:e.autoLogin});const t=wn();if(t)return fn.info("Using environment variable authentication"),{auth:t,type:"env"};let r=await vn(),n=r?await yr():void 0;const s=process.stdin.isTTY&&process.stdout.isTTY;if(fn.debug("OAuth auth check",{hasTokens:!!r,hasContext:!!n,canPrompt:s}),(!r||!n)&&e.autoLogin&&s){fn.info("Prompting user to login"),r?P.info("You are logged in but need to select an organization and project."):P.info("You are not logged in."),P.info("Press Enter to log in."),process.stdout.write(`${N.dim("Alternatively, set environment variables for an org API key:")}\n${N.dim(" STABLY_API_KEY=... STABLY_PROJECT_ID=... stably")}\n`),process.stdout.write("\n");const e=ee({input:process.stdin,output:process.stdout});try{await e.question(N.dim("Press Enter to continue... "))}finally{e.close()}await Mr(),r=await vn(),n=r?await yr():void 0}return r||(fn.warn("Authentication required but no tokens available"),mn()?k(N.red(bn())):k(N.red("You are not logged in. Run `stably login` to authenticate.")),process.exit(1)),n||(fn.warn("Authentication succeeded but no project context selected"),mn()?k(N.red(bn())):k(N.red("You haven't selected an organization and project. Run `stably login` to complete setup.")),process.exit(1)),fn.info("OAuth authentication successful",{orgId:n.orgId,projectId:n.projectId}),{auth:{accessToken:r.accessToken,context:n},type:"oauth"}},_n=async()=>{const e=wn();if(e)return{auth:e,type:"env"};const t=await vn(),r=t?await yr():void 0;return t&&r?{auth:{accessToken:t.accessToken,context:r},type:"oauth"}:void 0},Tn=e=>"env"===e.type?e.auth.projectId:e.auth.context.projectId,En=e=>"env"===e.type?e.auth.apiKey:e.auth.accessToken}}),qn=Fe({"src/api/stably/user-environment.ts"(){kn(),Ge(),Kn(),Vn(),Dn(),Sn=async()=>{const e=Ue.remoteEnvName;if(!e)return;const t=await In(),r=Tn(t),n=En(t);fn.debug("Fetching remote environment variables",{envName:e,projectId:r});const s=await Lt({auth:n,client:Zt(),path:{projectId:r,environment:e}});404===s.response.status&&(k(N.red(`Environment "${e}" not found. Check the name on your Stably dashboard.`)),process.exit(1)),401!==s.response.status&&403!==s.response.status||(k(N.red(`Access denied to environment "${e}".`)),process.exit(1)),s.error&&(k(N.red(`Failed to fetch environment "${e}": ${s.response.status}`)),process.exit(1));const o={},i=[];for(const e of s.data.variables)o[e.name]=e.value,e.sensitive&&e.value.length>0&&i.push(e.value);const a=s.data.variables.length,c=i.length;return process.stderr.write(`${N.cyan(`Loaded ${a} variable${1!==a?"s":""} from "${e}"`)}${c>0?N.dim(` (${c} sensitive)`):""}\n`),{variables:o,sensitiveValues:i}}}}),Jn=Fe({"../clients/internal-api-client/dist/headers.js"(){Mt()}}),Xn=Fe({"src/api/stably/org-headers.ts"(){Jn(),xn=e=>e?{[We]:e}:void 0}}),Qn=Fe({"src/api/stably/debug-info.ts"(){kn(),Dn(),Xn(),Vn(),An=x.object({context:x.string().min(1),autohealReportUrl:x.string(),skippedTests:x.array(x.object({testIdentifier:x.string(),testTitle:x.string(),consecutiveUnfixedCount:x.number()})).optional()}),Cn=async({authHeader:e,orgId:t,runId:r,skipAfterConsecutiveUnfixed:n})=>{fn.debug("Fetching autoheal context",{runId:r,skipAfterConsecutiveUnfixed:n});const s=await St({auth:e,client:Zt(),headers:xn(t),path:{runId:r},query:null!=n?{skipAfterConsecutiveUnfixed:n}:{}});if(404===s.response.status)throw fn.warn("Autoheal context not found",{runId:r,status:404}),new Error(`Run ID "${r}" was not found.`);if(401===s.response.status)throw fn.warn("Autoheal context fetch unauthorized",{runId:r,status:401}),new Error("Unauthorized: failed to fetch autoheal context (401).");if(422===s.response.status)throw fn.warn("Autoheal context fetch invalid request",{runId:r,status:422,error:s.error?.error}),new Error(s.error?.error??"Failed to fetch autoheal context (422).");if(!s.error){const e=An.safeParse(s.data);if(e.success)return fn.debug("Autoheal context fetched successfully",{runId:r,contextSize:e.data.context.length,skippedTestCount:e.data.skippedTests?.length??0}),{context:e.data.context,autohealReportUrl:e.data.autohealReportUrl,skippedTests:e.data.skippedTests??[]};throw fn.warn("Autoheal context response invalid",{runId:r}),new Error("Autoheal context response missing or invalid context.")}throw fn.warn("Autoheal context fetch failed",{runId:r,error:s.error}),new Error("Failed to fetch autoheal context")}}}),Zn={};He(Zn,{uploadToPresignedUrl:()=>Pn,zBucketPath:()=>Rn});var es,ts,rs,ns,ss,os,is,as,cs,ls,us,ds,ps,fs,hs=Fe({"src/api/stably/presigned-upload.ts"(){Rn=te.object({bucket:te.string(),key:te.string()}),Pn=async({body:e,contentType:t,uploadUrl:r,errorContext:n="content"})=>{const s=await fetch(r,{body:e instanceof Uint8Array?Buffer.from(e):e,headers:{"Content-Type":t},method:"PUT"});if(!s.ok)throw new Error(`Failed to upload ${n} (${s.status})`)}}}),gs=Fe({"src/api/stably/autoheal-upload.ts"(){kn(),Dn(),Xn(),hs(),es=te.object({diffBucketPath:Rn,expiresInSeconds:te.number(),key:te.string(),uploadUrl:te.string()}),ts=te.object({traceBucketPath:Rn,expiresInSeconds:te.number(),key:te.string(),uploadUrl:te.string(),sensitiveValues:te.array(te.string())}),rs=async({authHeader:e,orgId:t,report:r,runId:n})=>{const s=await xt({auth:e,body:{report:JSON.stringify(r)},client:Zt(),headers:xn(t),path:{runId:n}});if(s.error)throw new Error(`Failed to upload auto-heal report (${s.response.status})`)},ns=async({authHeader:e,contentType:t="text/plain",orgId:r,runId:n})=>{const s=await Ct({auth:e,body:{contentType:t},client:Zt(),headers:xn(r),path:{runId:n}});if(s.error)throw new Error(`Failed to presign diff upload (${s.response.status})`);const o=es.parse(s.data);return{diffBucketPath:o.diffBucketPath,expiresInSeconds:o.expiresInSeconds,key:o.key,uploadUrl:o.uploadUrl}},ss=async({authHeader:e,diffBucketPath:t,orgId:r,runId:n})=>{const s=await Rt({auth:e,body:t,client:Zt(),headers:xn(r),path:{runId:n}});if(s.error)throw new Error(`Failed to confirm diff upload (${s.response.status})`)},os=async({authHeader:e,issueId:t,proofId:r,testCaseId:n,contentType:s="application/zip",orgId:o,runId:i})=>{const a=await Pt({auth:e,body:{contentType:s,issueId:t,proofId:r,testCaseId:n},client:Zt(),headers:xn(o),path:{runId:i}});if(a.error)throw new Error(`Failed to presign trace upload (${a.response.status})`);const c=ts.parse(a.data);return{traceBucketPath:c.traceBucketPath,expiresInSeconds:c.expiresInSeconds,key:c.key,uploadUrl:c.uploadUrl,sensitiveValues:c.sensitiveValues}},is=async({authHeader:e,orgId:t,runId:r,status:n})=>{const s=await At({auth:e,body:{status:n},client:Zt(),headers:xn(t),path:{runId:r}});if(s.error)throw new Error(`Failed to update autoheal status (${s.response.status})`)}}}),ms=Fe({"src/api/stably/autoheal-progress.ts"(){Ln(),Vn(),as=class{socket;url;authHeader;orgId;runId;pendingEvent=null;reconnectAttempts=0;reconnectTimer;debounceTimer;_isClosed=!1;isAuthenticated=!1;authenticationFailed=!1;onUserMessage;maxReconnectAttempts=3;reconnectDelay=2e3;debounceMs=500;get isClosed(){return this._isClosed}constructor({authHeader:e,orgId:t,runId:r,url:n=Kt,onUserMessage:s}){this.authHeader=e,this.orgId=t,this.runId=r,this.url=n,this.onUserMessage=s,fn.info("[ws] Constructing AutohealWebSocketClient",{url:this.url,runId:r})}start(){this.connect()}connect(){if(!this._isClosed)try{const e={Authorization:this.authHeader};this.orgId&&(e["x-stably-org-id"]=this.orgId);const t=`${this.url}?runId=${encodeURIComponent(this.runId)}`;fn.info("[ws] Connecting",{url:t,attempt:this.reconnectAttempts}),this.socket=new re(t,{headers:e}),this.socket.on("open",()=>{fn.info("[ws] Connection opened"),this.reconnectAttempts=0}),this.socket.on("message",e=>{try{const t="string"==typeof e?e:e.toString(),r=JSON.parse(t);fn.debug("[ws] Received message",{type:r?.type}),"connected"===r?.type&&(fn.info("[ws] Authenticated successfully"),this.isAuthenticated=!0,this.authenticationFailed=!1,this.flushPending()),"user_message"===r?.type&&"string"==typeof r.content&&(fn.info("[ws] Received user message from web UI"),this.onUserMessage?.(r.content))}catch{}}),this.socket.on("close",(e,t)=>{fn.info("[ws] Connection closed",{code:e,authFailed:1008===e,reconnectAttempts:this.reconnectAttempts,maxReconnect:this.maxReconnectAttempts,isClosed:this._isClosed}),this.isAuthenticated=!1,1008===e&&(this.authenticationFailed=!0),!this._isClosed&&!this.authenticationFailed&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()}),this.socket.on("error",e=>{fn.warn("[ws] Connection error",{error:e.message})})}catch(e){fn.warn("[ws] Failed to create WebSocket",{error:e instanceof Error?e.message:String(e)}),this.scheduleReconnect()}}scheduleReconnect(){this._isClosed||this.reconnectTimer||(this.reconnectAttempts++,fn.info("[ws] Scheduling reconnect",{attempt:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts,delayMs:this.reconnectDelay}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect()},this.reconnectDelay))}isConnected(){return!!this.socket&&this.socket.readyState===re.OPEN&&this.isAuthenticated}sendProgress(e){if(this._isClosed)return void fn.debug("[ws] sendProgress called but client is closed",{phase:e.phase});const t={type:"autoheal_progress",payload:e};return this.pendingEvent=t,this.isConnected()?"complete"===e.phase?(fn.info("[ws] sendProgress: flushing terminal state immediately"),void this.flushPending()):void(this.debounceTimer||(this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.flushPending()},this.debounceMs))):(fn.debug("[ws] sendProgress: not connected, queuing event",{phase:e.phase,socketState:this.socket?.readyState,isAuthenticated:this.isAuthenticated,reconnectAttempts:this.reconnectAttempts}),void(this.socket?.readyState===re.CLOSED&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()))}flushPending(){if(this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),!this.pendingEvent)return;const e=this.pendingEvent;if(this.pendingEvent=null,!this.isConnected())return fn.debug("[ws] flushPending: not connected, re-queuing event",{phase:e.payload.phase}),void(this.pendingEvent=e);try{fn.debug("[ws] flushPending: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),t=>{t&&(fn.warn("[ws] flushPending: send failed",{error:t.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e))})}catch(t){fn.warn("[ws] flushPending: send threw",{error:t instanceof Error?t.message:String(t)}),this.pendingEvent=e}}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{fn.debug("[ws] flushPendingAndWait: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),r=>{r&&(fn.warn("[ws] flushPendingAndWait: send failed",{error:r.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e)),t()})}catch(r){fn.warn("[ws] flushPendingAndWait: send threw",{error:r instanceof Error?r.message:String(r)}),this.pendingEvent=e,t()}}):(fn.debug("[ws] flushPendingAndWait: not connected, re-queuing event",{phase:e.payload.phase}),this.pendingEvent=e,Promise.resolve())}close(){if(this._isClosed)return;fn.info("[ws] Closing WebSocket client"),this._isClosed=!0,this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.flushPending();const{socket:e}=this;this.socket=void 0,e&&setTimeout(()=>{e.close()},200)}async closeAndWait(){if(this._isClosed)return;fn.info("[ws] Closing WebSocket client and waiting for pending send"),this._isClosed=!0,this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),await this.flushPendingAndWait();const{socket:e}=this;this.socket=void 0,e&&(await new Promise(e=>setTimeout(e,200)),e.close())}}}}),ys=Fe({"src/api/stably/create-progress.ts"(){Ln(),Vn(),cs=class{socket;url;authHeader;orgId;sessionId;pendingEvent=null;reconnectAttempts=0;reconnectTimer;debounceTimer;_isClosed=!1;isAuthenticated=!1;authenticationFailed=!1;onUserMessage;maxReconnectAttempts=3;reconnectDelay=2e3;debounceMs=500;get isClosed(){return this._isClosed}constructor({authHeader:e,orgId:t,sessionId:r,url:n=qt,onUserMessage:s}){this.authHeader=e,this.orgId=t,this.sessionId=r,this.url=n,this.onUserMessage=s,fn.info("[ws] Constructing CreateProgressWebSocketClient",{url:this.url,sessionId:r})}start(){this.connect()}connect(){if(!this._isClosed)try{const e={Authorization:this.authHeader};this.orgId&&(e["x-stably-org-id"]=this.orgId);const t=`${this.url}?sessionId=${encodeURIComponent(this.sessionId)}`;fn.info("[ws] Connecting",{url:t,attempt:this.reconnectAttempts}),this.socket=new re(t,{headers:e}),this.socket.on("open",()=>{fn.info("[ws] Connection opened"),this.reconnectAttempts=0}),this.socket.on("message",e=>{try{const t="string"==typeof e?e:e.toString(),r=JSON.parse(t);fn.debug("[ws] Received message",{type:r?.type}),"connected"===r?.type&&(fn.info("[ws] Authenticated successfully"),this.isAuthenticated=!0,this.authenticationFailed=!1,this.flushPending()),"user_message"===r?.type&&"string"==typeof r.content&&(fn.info("[ws] Received user message from web UI"),this.onUserMessage?.(r.content))}catch{}}),this.socket.on("close",(e,t)=>{fn.info("[ws] Connection closed",{code:e,authFailed:1008===e,reconnectAttempts:this.reconnectAttempts,maxReconnect:this.maxReconnectAttempts,isClosed:this._isClosed}),this.isAuthenticated=!1,1008===e&&(this.authenticationFailed=!0),!this._isClosed&&!this.authenticationFailed&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()}),this.socket.on("error",e=>{fn.warn("[ws] Connection error",{error:e.message})})}catch(e){fn.warn("[ws] Failed to create WebSocket",{error:e instanceof Error?e.message:String(e)}),this.scheduleReconnect()}}scheduleReconnect(){this._isClosed||this.reconnectTimer||(this.reconnectAttempts++,fn.info("[ws] Scheduling reconnect",{attempt:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts,delayMs:this.reconnectDelay}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect()},this.reconnectDelay))}isConnected(){return!!this.socket&&this.socket.readyState===re.OPEN&&this.isAuthenticated}sendProgress(e){if(this._isClosed)return void fn.debug("[ws] sendProgress called but client is closed",{phase:e.phase});const t={type:"create_progress",payload:e};return this.pendingEvent=t,this.isConnected()?"complete"===e.phase?(fn.info("[ws] sendProgress: flushing terminal state immediately"),void this.flushPending()):void(this.debounceTimer||(this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.flushPending()},this.debounceMs))):(fn.debug("[ws] sendProgress: not connected, queuing event",{phase:e.phase,socketState:this.socket?.readyState,isAuthenticated:this.isAuthenticated,reconnectAttempts:this.reconnectAttempts}),void(this.socket?.readyState===re.CLOSED&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()))}flushPending(){if(this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),!this.pendingEvent)return;const e=this.pendingEvent;if(this.pendingEvent=null,!this.isConnected())return fn.debug("[ws] flushPending: not connected, re-queuing event",{phase:e.payload.phase}),void(this.pendingEvent=e);try{fn.debug("[ws] flushPending: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),t=>{t&&(fn.warn("[ws] flushPending: send failed",{error:t.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e))})}catch(t){fn.warn("[ws] flushPending: send threw",{error:t instanceof Error?t.message:String(t)}),this.pendingEvent=e}}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{fn.debug("[ws] flushPendingAndWait: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),r=>{r&&(fn.warn("[ws] flushPendingAndWait: send failed",{error:r.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e)),t()})}catch(r){fn.warn("[ws] flushPendingAndWait: send threw",{error:r instanceof Error?r.message:String(r)}),this.pendingEvent=e,t()}}):(fn.debug("[ws] flushPendingAndWait: not connected, re-queuing event",{phase:e.payload.phase}),this.pendingEvent=e,Promise.resolve())}close(){if(this._isClosed)return;fn.info("[ws] Closing WebSocket client"),this._isClosed=!0,this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.flushPending();const{socket:e}=this;this.socket=void 0,e&&setTimeout(()=>{e.close()},200)}async closeAndWait(){if(this._isClosed)return;fn.info("[ws] Closing WebSocket client and waiting for pending send"),this._isClosed=!0,this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),await this.flushPendingAndWait();const{socket:e}=this;this.socket=void 0,e&&(await new Promise(e=>setTimeout(e,200)),e.close())}}}}),bs=Fe({"src/api/stably/automation-file-upload.ts"(){kn(),Vn(),Dn(),Xn(),hs(),ls=te.object({bucketPath:Rn,expiresInSeconds:te.number(),key:te.string(),uploadUrl:te.string()}),us=async({authHeader:e,contentType:t="text/plain",filename:r,filePath:n,orgId:s,sessionId:o})=>{const i=await $t({auth:e,body:{filename:r,filePath:n,contentType:t},client:Zt(),headers:xn(s),path:{sessionId:o}});if(i.error)throw new Error(`Failed to presign file upload (${i.response.status})`);const a=ls.parse(i.data);return{bucketPath:a.bucketPath,expiresInSeconds:a.expiresInSeconds,key:a.key,uploadUrl:a.uploadUrl}},ds=async({authHeader:e,bucketPath:t,filename:r,filePath:n,orgId:s,sessionId:o})=>{const i=await Ot({auth:e,body:{filename:r,filePath:n,bucketPath:t},client:Zt(),headers:xn(s),path:{sessionId:o}});if(i.error)throw new Error(`Failed to confirm file upload (${i.response.status})`)},ps=async({authHeader:e,content:t,contentType:r="text/plain",filename:n,filePath:s,orgId:o,sessionId:i})=>{try{const{bucketPath:a,uploadUrl:c}=await us({authHeader:e,contentType:r,filename:n,filePath:s,orgId:o,sessionId:i});return await Pn({body:t,contentType:r,uploadUrl:c,errorContext:"file"}),await ds({authHeader:e,bucketPath:a,filename:n,filePath:s,orgId:o,sessionId:i}),a}catch(e){return fn.warn("Failed to upload automation file",{error:e instanceof Error?e.message:String(e)}),null}}}});async function ws({authHeader:e,orgId:t,sessionId:r,projectId:n,history:s}){if(0===s.length)return fn.debug("[session-history] No history to upload"),{success:!0};try{fn.info("[session-history] Requesting upload URL",{sessionId:r,messageCount:s.length});const{uploadUrl:o,key:i}=await async function({authHeader:e,orgId:t,sessionId:r,projectId:n}){const s=new URL(`/internal/v1/cli/sessions/${r}/history/upload-url`,Gt),o={Authorization:e,"Content-Type":"application/json"};t&&(o["x-stably-org-id"]=t);const i=await fetch(s,{method:"POST",headers:o,body:JSON.stringify({contentType:"application/x-ndjson",...n?{projectId:n}:{}}),signal:AbortSignal.timeout(3e4)});if(!i.ok){const e=await i.text().catch(()=>"");throw new Error(`Failed to get history upload URL (${i.status}): ${e.slice(0,200)}`)}return fs.parse(await i.json())}({authHeader:e,orgId:t,sessionId:r,projectId:n}),a=s.map(e=>JSON.stringify(e)).join("\n");fn.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 fn.info("[session-history] History uploaded successfully",{key:i}),{success:!0,key:i}}catch(e){const t=e instanceof Error?e.message:String(e);return fn.warn("[session-history] Failed to upload history",{error:t}),{success:!1,error:t}}}var vs,Is,_s,Ts,Es,Ss,xs,As,Cs,Rs,Ps=Fe({"src/api/stably/session-history-upload.ts"(){Ln(),Vn(),fs=x.object({uploadUrl:x.string(),key:x.string(),bucketPath:x.object({bucket:x.string(),key:x.string()}),expiresInSeconds:x.number()})}}),ks=Fe({"../agent-hooks/src/snapshot-filter.ts"(){}}),Us=Fe({"../codegen-agent-constants/src/index.ts"(){vs=".stably-agent.env",Is="1.58.0"}}),Ls=Fe({"../playwright-constants/src/index.ts"(){}}),Ds=Fe({"../agent-security-hooks/src/constants.ts"(){}}),$s=Fe({"../agent-security-hooks/src/gh-security.ts"(){_s=["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 Os(e){return/^\.env(\..*)?$/.test(e)||e===vs}function Ns(e){return Boolean(e&&"object"==typeof e&&"tool_input"in e&&e.tool_input&&"object"==typeof e.tool_input)}function Bs({action:e,pathKey:t}){return function({action:e,fileCheck:t,getBlockMessage:r,pathKey:n}){return async s=>{const o=function({input:e,pathKey:t}){if(!Ns(e))return{decision:"block",reason:`Invalid tool call format: Expected an object with 'tool_input' property. Please ensure the tool call follows the correct structure: { tool_input: { ${t}: "path/to/file" } }`,success:!1,systemMessage:"Tool call blocked due to invalid input format"};const r=e.tool_input;return t in r?"string"==typeof r[t]?{path:r[t],success:!0}:{decision:"block",reason:`Invalid tool call format: The '${t}' parameter must be a string containing the file path, but received ${typeof r[t]}. Please provide a valid file path as a string. Example: { tool_input: { ${t}: "src/example.ts" } }`,success:!1,systemMessage:"Tool call blocked due to invalid parameter type"}:{decision:"block",reason:`Invalid tool call format: Missing required parameter '${t}'. Please provide the file path using the '${t}' parameter. Example: { tool_input: { ${t}: "path/to/file" } }`,success:!1,systemMessage:"Tool call blocked due to missing required parameters"}}({input:s,pathKey:n});if(!o.success)return o;const i=o.path.replace(/\\/g,"/"),a=i.split("/").pop()||i;return t(a)?{decision:"block",reason:r("reading"===e?"Access to":"writing"===e?"Writing to":"editing"===e?"Editing":"Searching in"),systemMessage:"AI blocked due to accessing sensitive content"}:{decision:"approve"}}}({action:e,fileCheck:Os,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})}function js(e){const t=[],r=e.trim(),n=/(?:'[^']*(?:'\\''[^']*)*'|\S)+/g;let s;for(;null!==(s=n.exec(r));)t.push(s[0]);return t}function Ms(e){let t=0;const r=new RegExp(`^${Rs.source}$`);for(;t<e.length&&r.test(e[t]??"");)t+=1;return e.slice(t)}function Fs(e){const t=Ms(js(e));if("npx"===t[0])for(let e=1;e<t.length;e+=1){const r=t[e];if(r){if("--"===r)return t[e+1];if(!r.startsWith("-"))return r}}}function Hs(e){return js(e).find(e=>xs.includes(e))}function Gs(e,t){const r=l(e).replace(/\\/g,"/"),n=t.replace(/\\/g,"/"),s=n.endsWith("/")?n:`${n}/`;if(r.startsWith(s))return!0;const o=r.lastIndexOf(`/${s}`);if(-1===o)return!1;const i=r.slice(o+`/${s}`.length);return i.length>0&&!i.startsWith("../")}function Ys({onBeforeGitHubCommand:e,workspaceBoundary:t}){return async r=>{if(!Ns(r))return{decision:"block",reason:"Invalid tool call format: Expected an object with tool_input property.",systemMessage:"Tool call blocked due to invalid input format"};const n=r.tool_input,{command:i}=n;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 a=function(e){const t=e.trim(),r=new RegExp(`^(?:${Rs.source}\\s+)*(\\S+)`),n=t.match(r);return n?.[1]}(i);if(!a)return{decision:"block",reason:"Invalid Bash command: could not parse command.",systemMessage:"Tool call blocked due to unparseable command"};if("run_in_background"in n&&!0===n.run_in_background&&/\bstably-browser\s+run-test\b/.test(i))return{decision:"block",reason:"Running `stably-browser run-test` with `run_in_background: true` is not allowed. Test runs must execute in the foreground so their output can be captured and parsed. Remove the `run_in_background` parameter and run the test normally.",systemMessage:"Tool call blocked due to run-test in background"};if(!function(e){return"string"==typeof e&&Es.includes(e)}(a))return{decision:"block",reason:`The command "${a}" is not allowed. Only the following commands are permitted: ${Es.join(", ")}. Use the appropriate tools (Read, Write, Edit, Glob, Grep) for file operations instead.`,systemMessage:"Tool call blocked due to disallowed command"};if("npx"===a){const e=function(e){if(/(\s|^)npx\s+.*(\s|^)(-c|--call)(\s|=)/.test(e.trim()))return{valid:!1,reason:"The npx -c/--call form is not allowed. Use direct commands like `npx stably test ...`."};const t=Fs(e);if(!t)return{valid:!1,reason:"Invalid npx command: unable to determine which binary is being executed."};if(!new Set(Ss).has(t))return{valid:!1,reason:`The npx binary "${t}" is not allowed. Only ${Ss.join(", ")} are permitted.`};if("stably-browser"!==t){const r=Hs(e);if(r)return{valid:!1,reason:`The npx ${t} subcommand "${r}" is not allowed. The commands ${xs.join(", ")} are AI-powered and blocked to prevent recursion.`}}return{valid:!0}}(i);if(!e.valid)return{decision:"block",reason:e.reason,systemMessage:"Tool call blocked due to disallowed npx command"}}if("stably-browser"===a||"npx"===a&&"stably-browser"===Fs(i)){const e=function({command:e,binary:t}){const r=Ms(js(e)),n=r.findIndex(e=>e===t);if(-1!==n)for(let e=n+1;e<r.length;e+=1){const t=r[e];if(t&&!t.startsWith("-"))return t}}({command:i,binary:"stably-browser"});if(e&&As.includes(e))return{decision:"block",reason:`The stably-browser subcommand "${e}" is not allowed. The "upload" command can read arbitrary files and is blocked for security.`,systemMessage:"Tool call blocked due to disallowed stably-browser subcommand"}}if("stably"===a){const e=Hs(i);if(e)return{decision:"block",reason:`The stably subcommand "${e}" is not allowed. The commands ${xs.join(", ")} are AI-powered and blocked to prevent recursion.`,systemMessage:"Tool call blocked due to disallowed stably command"}}if("rm"===a){const e=function(e){const t=e.trim().match(/^rm\s+(?:-[a-zA-Z]+\s+|--[a-zA-Z-]+\s+)*(.+)$/),r=t?.[1]?.trim();return r?r.split(/\s+/).filter(e=>e.length>0):[]}(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 r=e.filter(e=>!function({targetPath:e,boundaryDir:t}){const r=function(e){if(H(e))return q.native(e);let t=e;const r=[];for(;!H(t);){const n=o(t);if(n===t)return s(e);r.unshift(t.slice(n.length+1)),t=n}const n=q.native(t);return r.length>0?s(n,...r):n}(e),n=q.native(t),i=r.endsWith(c)?r:r+c,a=n.endsWith(c)?n:n+c;return i.startsWith(a)||r===n}({targetPath:s(t,e),boundaryDir:t}));if(r.length>0)return{decision:"block",reason:`The rm command can only remove files within the workspace. The following path(s) are outside the workspace boundary: ${r.join(", ")}.`,systemMessage:"Tool call blocked due to rm outside workspace"}}else{const t=e.filter(e=>!(Gs(e,"tests")||Gs(e,".stably")));if(t.length>0)return{decision:"block",reason:`The rm command can only remove files in the tests/ directory or .stably/ directory. The following path(s) are not allowed: ${t.join(", ")}.`,systemMessage:"Tool call blocked due to rm outside allowed directories"}}}if("git"===a&&["-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"===a&&function(e){const t=e.trim();return!!t.startsWith("git ")&&Cs.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"===a){const t=function(e){const t=e.toLowerCase();return _s.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 Ws,Vs,zs=Fe({"../agent-security-hooks/src/index.ts"(){Us(),Ls(),Ds(),$s(),Ds(),$s(),Ts=["npm","yarn","pnpm","bun"],Es=["rm","mv","git","gh","npx","stably","stably-browser","pwtrace",...Ts],Ss=["stably","playwright","stably-browser","pwtrace"],xs=["create","fix","verify"],As=["upload"],Cs=["push","fetch","pull","clone","ls-remote"],Rs=/\S+=(?:'[^']*(?:'\\''[^']*)*'|\S+)/}}),Ks=Fe({"../agent-hooks/src/tool-response-parser.ts"(){Ws=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}}}),qs=Fe({"../agent-hooks/src/browser-hooks.ts"(){zs(),Ks()}}),Js=Fe({"../agent-hooks/src/test-results.ts"(){Ks()}});function Xs({onFileCreated:e}){return async t=>{const r=Ws(t),n=r?.file_path;return"string"==typeof n&&Vs.test(n)&&e(n),{decision:"approve"}}}var Qs,Zs=Fe({"../agent-hooks/src/write-tracker.ts"(){Ks(),Vs=/\.(spec|test)\.(ts|tsx|js|jsx|mts|mjs)$/}});async function eo(){try{const{stdout:e}=await Qs('pgrep -f "playwright run-test-mcp-server" 2>/dev/null || true'),t=e.trim();if(!t)return;const r=t.split("\n").filter(Boolean);await Promise.allSettled(r.map(async e=>{await Qs(`pkill -KILL -P ${e} '.*' 2>/dev/null || true`)}))}catch{}}var to,ro=Fe({"../agent-hooks/src/kill-playwright-workers.ts"(){Qs=ue(ie)}}),no=Fe({"../agent-hooks/src/mcp-error-transform.ts"(){Ks()}});function so(){to&&(clearTimeout(to),to=null)}var oo,io=Fe({"../agent-hooks/src/playwright-tool-timeout.ts"(){ro(),to=null}}),ao=Fe({"../agent-hooks/src/index.ts"(){ks(),qs(),Js(),Zs(),ro(),no(),io()}}),co=Fe({"src/agent/message-stream.ts"(){oo=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 lo(e){try{const t=se("git branch --show-current",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(!t)return;return{branch:t}}catch{return}}var uo,po,fo,ho,go,mo,yo,bo,wo,vo=Fe({"src/agent/prompts/git-context.ts"(){}}),Io=Fe({"../playwright-constants/src/node.ts"(){uo=[".ts",".js",".mts",".mjs",".cts",".cjs"]}}),_o=Fe({"../agent-workspace-info/src/index.ts"(){Io(),po=10240,fo=e=>{const t=e.split("\n"),r=[];let n=!1,s=!1,o=0,i=!1;for(let e=0;e<t.length;e++){const a=t[e],c=a.trim();c.startsWith("/*")&&(n=!0),c.includes("*/")?n=!1:n||c.startsWith("//")&&!c.startsWith("///")||(c.startsWith("import ")||c.startsWith("export ")?(r.push(a),i=!0):i&&""===c?(r.push(a),i=!1):(i=!1,c.startsWith("type ")||c.startsWith("interface ")?r.push(a):c.startsWith("function ")||c.startsWith("const ")||c.startsWith("async function ")||c.startsWith("export function ")||c.startsWith("export const ")||c.startsWith("test.describe(")||c.startsWith("test(")?(r.push(a),s=!0,o=(a.match(/{/g)||[]).length-(a.match(/}/g)||[]).length,0===o&&(c.endsWith(";")||c.endsWith(","))&&(s=!1)):s?(o+=(a.match(/{/g)||[]).length,o-=(a.match(/}/g)||[]).length,0===o&&c.includes("}")?(r.push(a),s=!1):o>0&&" // ... implementation omitted ..."!==r.at(-1)&&r.push(" // ... implementation omitted ...")):c.match(/^[a-zA-Z_]+:/)&&r.push(a)))}return r.join("\n")},ho=async({defaultContent:e,fileName:t,filePath:r})=>{try{const e=(await I(r)).size,n=await m(r,"utf-8"),s=Buffer.byteLength(n,"utf-8");if(s<=po)return n;const o=fo(n),i=Buffer.byteLength(o,"utf-8");return i<=po?o:o.slice(0,po)+`\n\n... [TRUNCATED: File "${t}" at ${r} was ${e} bytes (${s} bytes as UTF-8), reduced to ~${i} bytes of essential content, then truncated to 10240 bytes] ...`}catch(r){let n;if(r&&"object"==typeof r&&"code"in r){const e=r.code;"string"==typeof e&&(n=e)}return"ENOENT"!==n&&console.warn(`Failed to read ${t}: ${r}`),e}},go=async({defaultContent:e,dirName:t,dirPath:r})=>{try{const e=await _(r);return e.length>0?e.join("\n"):"(empty)"}catch(r){let n;if(r&&"object"==typeof r&&"code"in r){const e=r.code;"string"==typeof e&&(n=e)}return"ENOENT"!==n&&console.warn(`Failed to read ${t}: ${r}`),e}}}}),To=Fe({"src/agent/prompts/workspace-info.ts"(){_o()}}),Eo=Fe({"src/agent/prompts/index.ts"(){kn(),Dn(),Bn(),vo(),Vn(),To(),mo=async({allowedEnvVars:e,mode:t,workspaceInfo:r,authHeader:n,customHeader:s,maxParallelWorkers:o,preAssignedIssues:i})=>{const a=Zt(),c=lo(r.absolutePath);fn.debug("Requesting system prompt from API",{mode:t,hasGitContext:!!c,envVarCount:e.length});const l=await Tt({client:a,auth:n,body:{mode:t,workspaceInfo:r,allowedEnvVars:e,gitContext:c,maxParallelWorkers:o,preAssignedIssues:i}});if(401===l.response.status)throw fn.warn("System prompt fetch failed: unauthorized (401)"),await gr(),new Error("Your session has expired or been revoked. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(403===l.response.status)throw fn.debug("System prompt fetch failed: forbidden (403)"),new Error("Your organization does not have an active subscription. Manage your subscription at https://app.stably.ai or contact your organization admin.");if(l.error){fn.warn("System prompt fetch failed",{error:l.error});const e=JSON.stringify(l.error);if(e.toLowerCase().includes("unauthorized")||e.toLowerCase().includes("unauthenticated"))throw await gr(),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:l.data.systemPrompt,customHeader:s});return fn.debug("System prompt received",{size:u.length,appendedCustomHeader:!!s,hasPrContext:!!l.data.prContext}),{systemPrompt:u,prContext:l.data.prContext}}}}),So=Fe({"src/agent/automation-session-lifecycle.ts"(){Ln(),yo={chat:"chat",single:"create",fix:"fix",init:"init",verify:"verify"}}});function xo(e){const t=s(e);if(H(t))for(const e of wo){const r=i(t,`playwright.config${e}`);if(H(r))return r}}var Ao,Co=Fe({"src/playwright/stably-config-wrapper.ts"(){Un(),zn(),bo=".stably-playwright-wrapper.config.*",wo=[".ts",".js",".mts",".mjs",".cts",".cjs"]}});function Ro(e){try{return H(e)&&K(e).isDirectory()}catch{return!1}}function Po(e,t){const r="output-flag"===t?"--output flag":"playwright.config.ts"===t?"playwright.config.ts":"auto-detected"===t?"auto-detected":"cwd fallback";console.error(N.dim(`Using output directory: ${e} (from ${r})`))}var ko,Uo,Lo,Do,$o,Oo,No,Bo,jo,Mo,Fo,Ho,Go,Yo,Wo,Vo,zo,Ko,qo,Jo,Xo,Qo,Zo,ei,ti,ri,ni,si,oi,ii,ai,ci,li,ui,di,pi,fi,hi,gi,mi,yi,bi,wi,vi,Ii,_i,Ti,Ei,Si,xi,Ai,Ci,Ri,Pi,ki,Ui,Li,Di,$i,Oi,Ni,Bi,ji,Mi,Fi,Hi,Gi,Yi,Wi,Vi,zi,Ki,qi,Ji,Xi,Qi,Zi,ea,ta,ra,na,sa,oa,ia,aa,ca,la,ua,da,pa,fa,ha,ga,ma,ya,ba,wa,va=Fe({"src/playwright/output-dir-resolver.ts"(){Co(),Ao=["tests","e2e","__tests__","test"]}}),Ia=Fe({"../agent-tool-display/src/index.ts"(){ko=["mcp__playwright-test__","mcp__auto-heal-report__","mcp__stably-agent-control__"],Uo=["planner_","generator_"],Lo={open:e=>e?`Open ${e}`:"Open browser",close:()=>"Close browser",snapshot:()=>"Page snapshot",screenshot:()=>"Screenshot",click:e=>`Click ${e}`,fill:e=>`Fill ${e.split(/\s+/)[0]||""}`.trim(),type:e=>`Type into ${e.split(/\s+/)[0]||""}`.trim(),hover:e=>`Hover ${e}`,goto:e=>`Navigate to ${e}`,select:e=>`Select option in ${e.split(/\s+/)[0]||""}`.trim(),check:e=>`Check ${e}`,uncheck:e=>`Uncheck ${e}`,back:()=>"Go back",forward:()=>"Go forward","run-test":e=>`Run test ${e}`,"run-code":()=>"Run code","run-file":e=>`Run file ${e}`,"tab-list":()=>"List tabs","tab-new":e=>e?`New tab ${e}`:"New tab","tab-select":e=>`Select tab ${e}`,"tab-close":()=>"Close tab",eval:()=>"Evaluate JavaScript",upload:()=>"Upload file","state-save":()=>"Save browser state","state-load":()=>"Load browser state"},Do={"stably-browser":"Loading browser command reference","stably-cli":"Loading CLI reference","browser-interaction-guide":"Loading browser interaction guide","playwright-config-auth":"Loading project configuration","playwright-cli":"Loading browser command reference","bash-commands":"Loading command reference","stably-sdk-reference":"Loading SDK reference","test-creation-workflow":"Loading test creation guide","bulk-test-handling":"Loading bulk test guide","debugging-test-failures":"Loading debugging guide","recorded-actions-handling":"Loading recorded actions guide","playwright-best-practices":"Loading best practices","pwtrace-debugging":"Loading trace debugging guide","ai-to-programmatic-migration":"Loading migration guide"},$o={"mcp__stably-agent-control__restart_mcp_servers":"Restarting Browser Tools","mcp__session-control__restart_mcp_servers":"Restarting Browser Tools",Skill:"Preparing for task",ToolSearch:"Searching tools"},Oo=(e,t)=>{const r=t.find(t=>e.startsWith(t));return r?e.slice(r.length):e},No=e=>e.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" "),Bo=e=>{const t=$o[e];if(t)return t;const r=Oo(e,ko),n=Oo(r,Uo);return No(n)},jo=(e,t)=>{if(!t||"object"!=typeof t)return;const r=t,n="string"==typeof r.intent?r.intent:void 0;if("Read"!==e&&"Write"!==e&&"Edit"!==e){if("Glob"===e||"Grep"===e)return"string"==typeof r.pattern?r.pattern:void 0;if("mcp__playwright-test__test_run"!==e&&"test_run"!==e){if("mcp__playwright-test__test_debug"===e||"test_debug"===e){const e=r.test;return"string"==typeof e?.title?e.title:void 0}return"mcp__playwright-test__generator_setup_page"===e||"generator_setup_page"===e?"string"==typeof r.seedFile?r.seedFile:"tests/seed.spec.ts":"mcp__playwright-test__generator_write_test"===e||"generator_write_test"===e?"string"==typeof r.fileName?r.fileName:void 0:"Bash"===e?"string"==typeof r.command?r.command.length>50?`${r.command.slice(0,50)}...`:r.command:void 0:e.includes("browser_navigate")&&!e.includes("back")?"string"==typeof r.url?r.url:n:e.includes("browser_type")?("string"==typeof r.text?`"${r.text}"`:void 0)??n:e.includes("browser_click")?"string"==typeof r.element?r.element:n:e.includes("browser_wait_for")?"string"==typeof r.text?`text: "${r.text}"`:"number"==typeof r.time?`${r.time}ms`:n:e.includes("verify_text")?"string"==typeof r.text?`"${r.text}"`:n:e.includes("verify_element")?"string"==typeof r.accessibleName?r.accessibleName:n:e.includes("screenshot")&&"string"==typeof r.filename?r.filename:n}if(Array.isArray(r.locations)){const e=r.locations.filter(e=>"string"==typeof e);return e.length>0?e.join(", "):void 0}}else if("string"==typeof r.file_path)return r.file_path.split("/").at(-1)??void 0},Mo=(e,t)=>{if(!t||"object"!=typeof t)return null;const r=t;if("Skill"===e){const e="string"==typeof r.skill?r.skill:void 0;if(e){const t=e.includes(":")?e.split(":").pop():e;return Do[t]?Do[t]:`Loading ${t.replace(/-/g," ")}`}return"Preparing for task"}if("Bash"===e&&"string"==typeof r.command){const e=r.command.match(/(?:^|\s)(?:[\w/.-]*\/)?stably-browser\s+(?:--\S+\s+)*(\S+)(.*)/);if(!e)return null;const[,t,n]=e,s=n.trim().replace(/--\S+=?\S*\s*/g,"").trim();if("string"==typeof r.description&&r.description.trim())return r.description.trim();const o=Lo[t];return o?o(s):`${No(t)}${s?` ${s.split(/\s+/)[0]}`:""}`.trim()}return"Read"===e&&"string"==typeof r.file_path&&(r.file_path.includes(".stably-browser/")||r.file_path.includes(".playwright-cli/"))&&r.file_path.endsWith(".yml")?"Page snapshot":null}}}),_a=Fe({"src/agent/ui/format-tool-name.ts"(){Ia(),Fo=e=>"mcp__auto-heal-report__capture-trace-proof"===e?"Verify Test Run":"mcp__auto-heal-report__generate-report"===e?"Generate Report":Bo(e)}}),Ta=Fe({"src/agent/ui/permission-prompt.tsx"(){Ia(),_a(),Ho=({Box:e,Text:t,useInput:r},n,s)=>function({onChoice:o,prompt:i}){const[a,c]=fe(0),[l,u]=fe(!1),[d,p]=fe(""),f=[{label:"Yes, allow this once",value:"allow"},{label:"Yes, always allow for this session",value:"always"},{label:"No, tell AI what to do differently",value:"deny_with_message"}];r((e,t)=>{if(l)return t.return?void o("deny_with_message",d||"User denied this action"):t.escape?(u(!1),void p("")):t.backspace||t.delete?void p(e=>e.slice(0,-1)):void(t.ctrl||t.meta||p(t=>`${t}${e}`));if(t.upArrow)return void c(e=>e>0?e-1:f.length-1);if(t.downArrow)return void c(e=>e<f.length-1?e+1:0);if(t.return){const e=f[a];return"deny_with_message"===e.value?void u(!0):void o(e.value)}const r=parseInt(e,10);if(r>=1&&r<=f.length){const e=f[r-1];if("deny_with_message"===e.value)return void u(!0);o(e.value)}},{isActive:s});const h=Fo(i.toolName),g=jo(i.toolName,i.input);return we(e,{borderColor:"#FFA500",borderStyle:"round",flexDirection:"column",marginTop:1,paddingX:1,paddingY:0,children:[be(t,{bold:!0,color:"#FFA500",children:"Permission Required"}),we(e,{flexDirection:"column",marginTop:1,children:[be(t,{color:"gray",dimColor:!0,children:h}),null!=g&&we(t,{color:"gray",children:[" ",g]})]}),null!=i.decisionReason&&be(e,{marginTop:1,children:we(t,{color:"gray",children:["Reason: ",i.decisionReason]})}),we(e,l?{flexDirection:"column",marginTop:1,children:[be(t,{color:"gray",children:"Enter message for AI (press Enter to submit, Esc to cancel):"}),we(t,{children:[be(t,{color:"#FFA500",children:">"})," ",d,be(n,{})]})]}:{flexDirection:"column",marginTop:1,children:[be(t,{color:"gray",children:"Use ↑↓ arrows or number keys to select:"}),f.map((e,r)=>be(t,{children:we(t,{color:r===a?"cyan":void 0,children:[r===a?"❯":" "," ",r+1,". ",e.label]})},e.value))]})]})}}}),Ea=Fe({"src/agent/ui/chat.tsx"(){Vn(),Go=({termProgram:e})=>"vscode"===e,Yo=({Cursor:e,inkComponents:{Box:t,Static:r,Text:n,useInput:s},isRawModeSupported:o,PermissionPrompt:i,Spinner:a})=>{const c="vscode"!==process.env.TERM_PROGRAM,l=e=>"tool"===e.kind?we(n,{color:"gray",dimColor:!0,children:["• ",e.content]},e.id):"tool_result"===e.kind||"text"===e.kind?be(n,{color:"gray",children:e.content},e.id):null,u=({progress:e})=>{const[r,s]=fe(Date.now());he(()=>{if(!c)return;const e=setInterval(()=>s(Date.now()),1e3);return()=>clearInterval(e)},[]);const o=r-e.startedAt,i=Math.floor(o/1e3),a=Math.floor(i/60),l=i%60,u=a>0?`${a}m ${l.toString().padStart(2,"0")}s`:`${l}s`,{label:d,color:p}={initializing:{label:"Fetching test results",color:"gray"},triage:{label:"Triaging failures",color:"#FFA500"},fixing:{label:"Fixing tests",color:"cyan"},debugging:{label:"Debugging tests",color:"magenta"},validation:{label:"Validating fixes",color:"blue"},complete:{label:"Complete",color:"green"}}[e.phase],f=e.fixedTests+e.failedTests,h=("fixing"===e.phase||"debugging"===e.phase)&&f>0?null!==e.totalTests?` (fixed ${e.fixedTests}/${e.totalTests}${e.failedTests>0?`, failed ${e.failedTests}`:""})`:` (fixed ${e.fixedTests}${e.failedTests>0?`, failed ${e.failedTests}`:""})`:"";return be(t,{flexDirection:"column",children:we(n,{children:[be(n,{color:p,bold:!0,children:d}),be(n,{color:"gray",children:h}),we(n,{color:"gray",children:[" [",u,"]"]})]})})},d=({progress:e})=>{const r=e.endedAt??Date.now(),s=Math.floor((r-e.startedAt)/1e3),o=Math.floor(s/60),i=s%60,a=o>0?`${o}m ${i.toString().padStart(2,"0")}s`:`${i}s`,c=e.isError?"#FFA500":"green",l=e.isError?"Fix stopped":"Fix complete";return we(t,{flexDirection:"column",children:[we(n,{color:c,bold:!0,children:[l," in ",a]}),null!==e.totalTests&&we(n,{color:"gray",children:[e.fixedTests,"/",e.totalTests," tests fixed",e.failedTests>0?`, ${e.failedTests} failed`:""]})]})},p=(e,r=!1)=>{if("subagent"===e.kind&&e.subagent){const{subagent:s}=e,o="complete"===s.status?"green":"error"===s.status?"red":"#FFA500";return we(t,{flexDirection:"column",marginTop:1,children:[we(n,{children:[be(n,{color:o,bold:!0,children:"Agent"}),s.description?we(n,{color:"gray",children:[" (",s.description,")"]}):null]}),s.activities.length>0&&be(t,{flexDirection:"column",marginLeft:2,children:(()=>{if(!r)return s.activities.map(e=>l(e));let e=0;const t=[];for(let r=s.activities.length-1;r>=0;r--){const n=s.activities[r];"tool"!==n.kind&&"tool_result"!==n.kind||("tool"===n.kind&&e++,e<=y&&t.unshift(n))}return t.map(e=>l(e))})()})]},e.id)}return"tool"===e.kind?we(n,{color:"gray",dimColor:!0,children:["• ",e.content]},e.id):"tool_result"===e.kind?be(n,{color:"gray",children:e.content},e.id):"user"===e.kind?we(n,{color:"cyan",children:["You: ",e.content]},e.id):be(n,{children:e.content},e.id)},f=(e,t)=>{if(t<=0)return 0;let r=t-1;for(;r>0&&/\s/.test(e[r]);)r--;for(;r>0&&!/\s/.test(e[r-1]);)r--;return r},h=(e,t)=>{if(t>=e.length)return e.length;let r=t;for(;r<e.length&&!/\s/.test(e[r]);)r++;for(;r<e.length&&/\s/.test(e[r]);)r++;return r},g=(e,t)=>{if(t<=0)return 0;const r=e.lastIndexOf("\n",t-1);return-1===r?0:r+1},m=(e,t)=>{const r=e.indexOf("\n",t);return-1===r?e.length:r},y=3;return function({onExit:c,onPermissionChoice:l,onSend:b,showSpinnerImmediately:w,state:v}){const[I,_]=fe({value:"",cursor:0}),T=I.value,E=I.cursor,S=ge(!1),x=ge(void 0),[A,C]=fe(!1),[R,P]=fe(!1),k=ge(0),U=ge(!1),L=!!v.permissionPrompt,D=Go({hasPermissionPrompt:L,inputValue:T,showExitMessage:A,termProgram:process.env.TERM_PROGRAM}),$=v.log.at(-1),O="text"===$?.kind&&"running"===v.status,N=v.log.findIndex(e=>"subagent"===e.kind&&"running"===e.subagent?.status),B=o&&!R,j=D?0:-1!==N?N:O?v.log.length-1:v.log.length,M=B&&"running"===v.status?Math.min(j,k.current):j;he(()=>{v.log.length<k.current&&(k.current=0),M>k.current&&(k.current=M)},[v.log.length,M]);const F=v.log.slice(0,k.current),H=v.log.slice(k.current),G=B?F.filter(e=>"tool"!==e.kind&&"tool_result"!==e.kind):F,Y=(()=>{if(!B)return H;let e=0;const t=[];for(let r=H.length-1;r>=0;r--){const n=H[r];"tool"===n.kind||"tool_result"===n.kind?("tool"===n.kind&&e++,e<=y&&t.unshift(n)):t.unshift(n)}return t})(),W=me(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]);s((e,t)=>{t.ctrl&&"c"===e&&W().catch(()=>process.exit(1)),t.ctrl&&"o"===e&&P(e=>!e)},{isActive:o}),he(()=>{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&&_(e=>({value:e.value.slice(0,e.cursor)+t+e.value.slice(e.cursor),cursor:e.cursor+t.length}))},t=t=>{const r=t.toString();if(r.includes("[200~")){U.current=!0;const t=r.slice(r.indexOf("[200~")+6),n=t.includes("[201~"),s=n?t.slice(0,t.indexOf("[201~")):t;return n&&(U.current=!1),void e(s)}if(r.includes("[201~")){const t=r.slice(0,r.indexOf("[201~"));return e(t),void(U.current=!1)}U.current?e(r):"[1;5H"!==r&&"[1;5~"!==r?"[1;5F"!==r&&"[4;5~"!==r?"[H"!==r&&"[1~"!==r&&"OH"!==r&&"[7~"!==r?"[F"!==r&&"[4~"!==r&&"OF"!==r&&"[8~"!==r||_(e=>({...e,cursor:m(e.value,e.cursor)})):_(e=>({...e,cursor:g(e.value,e.cursor)})):_(e=>({...e,cursor:e.value.length})):_(e=>({...e,cursor:0}))};return process.stdin.on("data",t),()=>{process.stdin.off("data",t),process.stdout.isTTY&&process.stdout.write("[?2004l")}},[L,b]),s((e,t)=>{if(!t.ctrl||"c"!==e){if(t.return){if(U.current)return;const e=T.trim();return e&&b?.(e),void _({value:"",cursor:0})}t.ctrl&&"w"===e||t.ctrl&&t.backspace?_(e=>{const t=f(e.value,e.cursor);return{value:e.value.slice(0,t)+e.value.slice(e.cursor),cursor:t}}):!t.backspace&&!t.delete||t.ctrl?t.ctrl&&t.leftArrow||t.meta&&"b"===e?_(e=>({...e,cursor:f(e.value,e.cursor)})):t.ctrl&&t.rightArrow||t.meta&&"f"===e?_(e=>({...e,cursor:h(e.value,e.cursor)})):t.leftArrow?_(e=>({...e,cursor:Math.max(0,e.cursor-1)})):t.rightArrow?_(e=>({...e,cursor:Math.min(e.value.length,e.cursor+1)})):t.ctrl&&"a"===e?_(e=>({...e,cursor:0})):t.ctrl&&"e"===e?_(e=>({...e,cursor:e.value.length})):!e||t.ctrl||t.meta||t.escape||e.includes("")||/^\[./.test(e)||/^O[A-D]$/.test(e)||_(t=>({value:t.value.slice(0,t.cursor)+e+t.value.slice(t.cursor),cursor:t.cursor+e.length})):_(e=>e.cursor>0?{value:e.value.slice(0,e.cursor-1)+e.value.slice(e.cursor),cursor:e.cursor-1}:e)}},{isActive:o&&!!b&&!L});const V=ye(()=>"running"===v.status?be(a,{label:v.runningLabel??"Working"}):"success"!==v.status?be(n,{color:"red",children:"✖ Failed"}):void 0,[v.runningLabel,v.status]),z=!(w||!b||"running"!==v.status||0!==v.log.length||v.resultText||v.errorText),K="running"===v.status&&!z||v.log.length>0||v.resultText||v.errorText||"running"!==v.status;return we(t,{flexDirection:"column",children:[D?we(t,{flexDirection:"column",flexShrink:0,children:[be(n,{color:"cyan",bold:!0,children:"Stably Agent"}),be(t,{flexDirection:"column",marginTop:1,children:be(n,{color:"gray",children:v.promptDisplay})})]}):be(r,{items:["header"],children:()=>we(t,{flexDirection:"column",flexShrink:0,children:[be(n,{color:"cyan",bold:!0,children:"Stably Agent"}),be(t,{flexDirection:"column",marginTop:1,children:be(n,{color:"gray",children:v.promptDisplay})})]},"header")}),G.length>0&&be(r,{items:G,children:e=>p(e,B)}),Y.length>0&&be(t,{flexDirection:"column",children:Y.map(e=>p(e,B))}),B&&H.length>Y.length&&we(n,{color:"gray",dimColor:!0,children:["↕ ",H.length-Y.length," tool calls hidden (Ctrl+O to expand)"]}),R&&o&&"running"===v.status&&be(n,{color:"gray",dimColor:!0,children:"↕ Showing all tool calls (Ctrl+O to collapse)"}),"error"===v.status&&v.errorText&&be(t,{marginTop:1,children:be(n,{color:"red",children:v.errorText})}),"success"===v.status&&v.resultText&&be(t,{marginTop:1,children:be(n,{children:v.resultText})}),K&&be(t,{flexDirection:"column",flexShrink:0,marginTop:1,children:"running"===v.status&&v.fixProgress?we(t,{flexDirection:"column",children:[we(t,{children:[be(a,{}),be(n,{children:" "}),be(u,{progress:v.fixProgress})]}),("fixing"===v.fixProgress.phase||"debugging"===v.fixProgress.phase)&&v.log.flatMap(e=>{const{subagent:r}=e;if("subagent"!==e.kind||"code-worker"!==r?.subagentType&&"browser-worker"!==r?.subagentType||"running"!==r.status)return[];const{activities:s}=r,o=s.filter(e=>"tool"===e.kind).length,i=s.at(-1),c=s.filter(e=>"tool"===e.kind).at(-1),l=(()=>{if(!i)return null;if("tool"===i.kind)return null;if("text"===i.kind){const e=i.content.trim().split("\n").at(-1)?.trim();return e?e.length>80?`${e.slice(0,80)}…`:e:null}if("tool_result"===i.kind){const e=i.content.trim().split("\n")[0]?.trim();return e?e.length>80?`${e.slice(0,80)}…`:e:null}return null})();return we(t,{flexDirection:"column",children:[we(n,{children:[" ",be(a,{}),we(n,{color:"gray",children:[r.description||r.subagentType||"worker",o>0?` (${o} ${1===o?"cycle":"cycles"})`:""]})]}),c&&we(n,{color:"gray",dimColor:!0,children:[" • ",c.content]}),l&&we(n,{color:"gray",dimColor:!0,children:[" ",l]})]},e.id)})]}):"success"!==v.status&&"error"!==v.status||!v.fixProgress?V:be(d,{progress:v.fixProgress})}),null!=v.permissionPrompt&&null!=l&&be(i,{onChoice:l,prompt:v.permissionPrompt}),null!=b&&null==v.permissionPrompt&&!v.isExiting&&we(t,{borderColor:"gray",borderStyle:"round",flexDirection:"column",flexShrink:0,marginTop:1,paddingX:1,paddingY:0,children:[be(n,{color:"gray",children:"Type a message and press Enter. Press Ctrl+C to exit."}),we(n,{children:[be(n,{color:"#FFA500",children:">"})," ",T.slice(0,E),be(e,{}),T.slice(E)]})]}),A&&we(t,{marginTop:1,flexDirection:"column",children:[be(n,{color:"#FFA500",children:"Press Ctrl+C again to exit"}),qr&&we(n,{color:"gray",children:["Debug log: ",en]})]})]})}}}}),Sa=Fe({"src/agent/ui.tsx"(){Ia(),_a(),Ta(),Ea(),Wo=async(e,t)=>{const{Box:r,Static:n,Text:s,render:o,useInput:i}=await import("ink"),a=!!process.stdin.isTTY,c="vscode"!==process.env.TERM_PROGRAM,l=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],u=()=>be(s,{inverse:!0,children:" "}),d=Ho({Box:r,Text:s,useInput:i},u,a),p=Yo({Cursor:u,inkComponents:{Box:r,Static:n,Text:s,useInput:i},isInitMode:t?.isInitMode,isRawModeSupported:a,PermissionPrompt:d,Spinner:({label:e})=>{const[t,r]=fe(0);return he(()=>{if(!c)return;const e=setInterval(()=>r(e=>(e+1)%l.length),80);return()=>clearInterval(e)},[]),we(s,{color:"#FFA500",children:[l[t]," ",e]})}});let f=e;t?.isFixMode&&(f.fixProgress={phase:"initializing",totalTests:null,fixedTests:0,failedTests:0,currentTestDescription:null,lastTestDescription:null,startedAt:Date.now(),endedAt:null,isError:!1});const h={current:(e,t)=>{}},g=o(be(p,{onExit:t?.onExit,onPermissionChoice:(e,t)=>h.current(e,t),onSend:t?.onSend,showSpinnerImmediately:t?.showSpinnerImmediately,state:f}),{exitOnCtrlC:!1}),m=()=>{f={...f},g.rerender(be(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"}],m())},b=new Map;return{addSubagentActivity:({toolUseId:e,kind:t,content:r})=>{const n=b.get(e);if(void 0===n)return void console.error("[addSubagentActivity] No entry index for toolUseId:",e);const s=f.log[n];if("subagent"===s?.kind&&s.subagent){if("text"===t){const e=s.subagent.activities.at(-1);"text"===e?.kind?e.content+=r:s.subagent.activities.push({id:s.subagent.activities.length,kind:"text",content:r.replace(/^\s*\n+/,"")})}else s.subagent.activities.push({id:s.subagent.activities.length,kind:t,content:r});f.log=[...f.log],m()}else console.error("[addSubagentActivity] Entry not found or not subagent:",{entryIndex:n,entryKind:s?.kind})},addSubagentStart:({toolUseId:e,subagentType:t,description:r})=>{const n=f.log.length;if(b.set(e,n),f.log=[...f.log,{content:"",id:n,kind:"subagent",subagent:{toolUseId:e,subagentType:t,description:r,status:"running",activities:[]}}],f.fixProgress)if("triage"===t&&"initializing"===f.fixProgress.phase)f.fixProgress={...f.fixProgress,phase:"triage"};else if("code-worker"===t){const e=(f.fixProgress.totalTests??0)+1,t=r||null;f.fixProgress={...f.fixProgress,phase:"fixing",totalTests:e,currentTestDescription:t,lastTestDescription:t??f.fixProgress.lastTestDescription}}else if("browser-worker"===t){const e=(f.fixProgress.totalTests??0)+1,t=r||null;f.fixProgress={...f.fixProgress,phase:"debugging",totalTests:e,currentTestDescription:t,lastTestDescription:t??f.fixProgress.lastTestDescription}}else"validation"===t?f.fixProgress={...f.fixProgress,phase:"validation",currentTestDescription:null}:"context"===t&&(f.fixProgress={...f.fixProgress,currentTestDescription:r||f.fixProgress.currentTestDescription});m()},addTool:({rawName:e,toolInput:t})=>{const r=Mo(e,t),n=r??Fo(e),s=r?void 0:jo(e,t),o=s?`${n} (${s})`:n;f.log=[...f.log,{content:o,id:f.log.length,kind:"tool"}],m()},addToolResult:({message:e})=>{f.log=[...f.log,{content:e,id:f.log.length,kind:"tool_result"}],m()},appendText:({text:e})=>{if(!e)return;const t=f.log.at(-1),r="text"!==t?.kind?e.replace(/^\s*\n+/,""):e;f.log="text"===t?.kind?[...f.log.slice(0,-1),{...t,content:`${t.content}${r}`}]:[...f.log,{content:r,id:f.log.length,kind:"text"}],m()},appendUserMessage:y,cleanup:async()=>{const e=g.waitUntilExit();g.unmount(),await e},setExiting:()=>{f.isExiting=!0,m()},setRunningLabel:({label:e})=>{f.runningLabel=e,m()},setStatus:({error:e,result:t,status:r})=>{f.errorText=e,f.resultText=t,f.status=r,m()},setSubagentStatus:({toolUseId:e,status:t})=>{const r=b.get(e);if(void 0===r)return;const n=f.log[r];"subagent"===n?.kind&&n.subagent&&(n.subagent.status=t,!f.fixProgress||"code-worker"!==n.subagent.subagentType&&"browser-worker"!==n.subagent.subagentType||("complete"===t?f.fixProgress={...f.fixProgress,fixedTests:f.fixProgress.fixedTests+1,currentTestDescription:null}:"error"===t&&(f.fixProgress={...f.fixProgress,failedTests:f.fixProgress.failedTests+1,currentTestDescription:null})),f.log=[...f.log],m(),"complete"!==t&&"error"!==t||b.delete(e))},showPermissionPrompt:e=>new Promise(t=>{h.current=(r,n)=>{if(f.permissionPrompt=void 0,m(),"allow"===r)t({behavior:"allow",updatedInput:e.input});else if("always"===r)t({behavior:"allow",updatedInput:e.input,updatedPermissions:e.suggestions});else{const e=n??"User denied this action";y({text:e}),t({behavior:"deny",message:e,interrupt:!1})}},f.permissionPrompt={...e,resolve:t},m()}),updateFixProgress:t?.isFixMode?e=>{f.fixProgress&&(f.fixProgress={...f.fixProgress,...e},m())}:void 0}}}}),xa=Fe({"../agent-schemas/src/stably-yaml.ts"(){}}),Aa=Fe({"../agent-schemas/src/index.ts"(){xa(),Vo=["test","bug","flake","ui_change","other"],zo={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."},Ko=e=>zo[e],qo=/[^a-zA-Z0-9-_]/g,Jo=e=>{const t=e.trim().replace(qo,"_");return t.length>0?t.slice(0,80):void 0},Xo=e=>Jo(e)??"issue",Qo=e=>"string"==typeof e?Jo(e):void 0,Zo=({proofId:e,testCaseId:t})=>Qo(t)??Qo(e),ei=()=>["Classification of the root cause:","",`- test: ${Ko("test")}`,`- bug: ${Ko("bug")}`,`- flake: ${Ko("flake")}`,`- ui_change: ${Ko("ui_change")}`,`- other: ${Ko("other")}`].join("\n")}});function Ca(e,t){return Ki(e,t||{},0,0)}function Ra(e,t){return Di(e,{i:2},t&&t.out,t&&t.dictionary)}function Pa(e,t){if(ua)return ua.encode(e);for(var r=e.length,n=new si(e.length+(e.length>>1)),s=0,o=function(e){n[s++]=e},i=0;i<r;++i){if(s+5>n.length){var a=new si(s+8+(r-i<<1));a.set(n),n=a}var c=e.charCodeAt(i);c<128||t?o(c):c<2048?(o(192|c>>6),o(128|63&c)):c>55295&&c<57344?(o(240|(c=65536+(1047552&c)|1023&e.charCodeAt(++i))>>18),o(128|c>>12&63),o(128|c>>6&63),o(128|63&c)):(o(224|c>>12),o(128|c>>6&63),o(128|63&c))}return ki(n,0,s)}function ka(e,t,r){r||(r=t,t={}),"function"!=typeof r&&Li(7);var n={};la(e,"",n,t);var s=Object.keys(n),o=s.length,i=0,a=0,c=o,l=new Array(o),u=[],d=function(){for(var e=0;e<u.length;++e)u[e]()},p=function(e,t){wa(function(){r(e,t)})};wa(function(){p=r});var f=function(){var e=new si(a+22),t=i,r=a-i;a=0;for(var n=0;n<c;++n){var s=l[n];try{var o=s.c.length;ya(e,a,s,s.f,s.u,o);var u=30+s.f.length+ma(s.extra),d=a+u;e.set(s.c,d),ya(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)}}ba(e,i,l.length,r,t),p(null,e)};o||f();for(var h=function(e){var t=s[e],r=n[t],c=r[0],h=r[1],g=zi(),m=c.length;g.p(c);var y=Pa(t),b=y.length,w=h.comment,v=w&&Pa(w),I=v&&v.length,_=ma(h.extra),T=0==h.level?0:8,E=function(r,n){if(r)d(),p(r,null);else{var s=n.length;l[e]=qi(h,{size:m,crc:g.d(),c:n,f:y,m:v,u:b!=t.length||v&&w.length!=I,compression:T}),i+=30+b+_+s,a+=76+2*(b+_)+(I||0)+s,--o||f()}};if(b>65535&&E(Li(11,0,1),null),T)if(m<16e4)try{E(null,Ca(c,h))}catch(e){E(e,null)}else u.push(function(e,t,r){return r||(r=t,t={}),"function"!=typeof r&&Li(7),sa(e,t,[ta],function(e){return ra(Ca(e.data[0],e.data[1]))},0,r)}(c,h,E));else E(null,c)},g=0;g<c;++g)h(g);return d}function Ua(e,t,r){r||(r=t,t={}),"function"!=typeof r&&Li(7);var n=[],s=function(){for(var e=0;e<n.length;++e)n[e]()},o={},i=function(e,t){wa(function(){r(e,t)})};wa(function(){i=r});for(var a=e.length-22;101010256!=ia(e,a);--a)if(!a||e.length-a>65558)return i(Li(13,0,1),null),s;var c=oa(e,a+8);if(c){var l=c,u=ia(e,a+16),d=4294967295==u||65535==l;if(d){var p=ia(e,a-12);(d=101075792==ia(e,p))&&(l=c=ia(e,p+32),u=ia(e,p+48))}for(var f=t&&t.filter,h=function(t){var r=ha(e,u,d),a=r[0],l=r[1],p=r[2],h=r[3],g=r[4],m=r[5],y=fa(e,m);u=g;var b=function(e,t){e?(s(),i(e,null)):(t&&(o[h]=t),--c||i(null,o))};if(!f||f({name:h,size:l,originalSize:p,compression:a}))if(a)if(8==a){var w=e.subarray(y,y+l);if(p<524288||l>.8*p)try{b(null,Ra(w,{out:new si(p)}))}catch(e){b(e,null)}else n.push(function(e,t,r){return r||(r=t,t={}),"function"!=typeof r&&Li(7),sa(e,t,[ea],function(e){return ra(Ra(e.data[0],na(e.data[1])))},1,r)}(w,{size:p},b))}else b(Li(14,"unknown compression type "+a,1),null);else b(null,ki(e,y,y+l));else b(null,null)},g=0;g<l;++g)h()}else i(null,{});return s}var La,Da=Fe({"../../app/node_modules/.pnpm/fflate@0.8.2/node_modules/fflate/esm/index.mjs"(){ti=ve("/");try{ri=ti("worker_threads").Worker}catch(e){}for(ni=ri?function(e,t,r,n,s){var o=!1,i=new ri(e+";var __w=require('worker_threads');__w.parentPort.on('message',function(m){onmessage({data:m})}),postMessage=function(m,t){__w.parentPort.postMessage(m,t)},close=process.exit;self=global",{eval:!0}).on("error",function(e){return s(e,null)}).on("message",function(e){return s(null,e)}).on("exit",function(e){e&&!o&&s(new Error("exited with code "+e),null)});return i.postMessage(r,n),i.terminate=function(){return o=!0,ri.prototype.terminate.call(i)},i}:function(e,t,r,n,s){setImmediate(function(){return s(new Error("async operations unsupported - update to Node 12+ (or Node 10-11 with the --experimental-worker CLI flag)"),null)});var o=function(){};return{terminate:o,postMessage:o}},si=Uint8Array,oi=Uint16Array,ii=Int32Array,ai=new si([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]),ci=new si([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]),li=new si([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),ui=function(e,t){for(var r=new oi(31),n=0;n<31;++n)r[n]=t+=1<<e[n-1];var s=new ii(r[30]);for(n=1;n<30;++n)for(var o=r[n];o<r[n+1];++o)s[o]=o-r[n]<<5|n;return{b:r,r:s}},di=ui(ai,2),pi=di.b,fi=di.r,pi[28]=258,fi[258]=28,hi=ui(ci,0),gi=hi.b,mi=hi.r,yi=new oi(32768),_i=0;_i<32768;++_i)bi=(61680&(bi=(52428&(bi=(43690&_i)>>1|(21845&_i)<<1))>>2|(13107&bi)<<2))>>4|(3855&bi)<<4,yi[_i]=((65280&bi)>>8|(255&bi)<<8)>>1;for(wi=function(e,t,r){for(var n=e.length,s=0,o=new oi(t);s<n;++s)e[s]&&++o[e[s]-1];var i,a=new oi(t);for(s=1;s<t;++s)a[s]=a[s-1]+o[s-1]<<1;if(r){i=new oi(1<<t);var c=15-t;for(s=0;s<n;++s)if(e[s])for(var l=s<<4|e[s],u=t-e[s],d=a[e[s]-1]++<<u,p=d|(1<<u)-1;d<=p;++d)i[yi[d]>>c]=l}else for(i=new oi(n),s=0;s<n;++s)e[s]&&(i[s]=yi[a[e[s]-1]++]>>15-e[s]);return i},vi=new si(288),_i=0;_i<144;++_i)vi[_i]=8;for(_i=144;_i<256;++_i)vi[_i]=9;for(_i=256;_i<280;++_i)vi[_i]=7;for(_i=280;_i<288;++_i)vi[_i]=8;for(Ii=new si(32),_i=0;_i<32;++_i)Ii[_i]=5;Ti=wi(vi,9,0),Ei=wi(vi,9,1),Si=wi(Ii,5,0),xi=wi(Ii,5,1),Ai=function(e){for(var t=e[0],r=1;r<e.length;++r)e[r]>t&&(t=e[r]);return t},Ci=function(e,t,r){var n=t/8|0;return(e[n]|e[n+1]<<8)>>(7&t)&r},Ri=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(7&t)},Pi=function(e){return(e+7)/8|0},ki=function(e,t,r){return(null==t||t<0)&&(t=0),(null==r||r>e.length)&&(r=e.length),new si(e.subarray(t,r))},Ui=["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"],Li=function(e,t,r){var n=new Error(t||Ui[e]);if(n.code=e,Error.captureStackTrace&&Error.captureStackTrace(n,Li),!r)throw n;return n},Di=function(e,t,r,n){var s=e.length,o=n?n.length:0;if(!s||t.f&&!t.l)return r||new si(0);var i=!r,a=i||2!=t.i,c=t.i;i&&(r=new si(3*s));var l=function(e){var t=r.length;if(e>t){var n=new si(Math.max(2*t,e));n.set(r),r=n}},u=t.f||0,d=t.p||0,p=t.b||0,f=t.l,h=t.d,g=t.m,m=t.n,y=8*s;do{if(!f){u=Ci(e,d,1);var b=Ci(e,d+1,3);if(d+=3,!b){var w=e[(P=Pi(d)+4)-4]|e[P-3]<<8,v=P+w;if(v>s){c&&Li(0);break}a&&l(p+w),r.set(e.subarray(P,v),p),t.b=p+=w,t.p=d=8*v,t.f=u;continue}if(1==b)f=Ei,h=xi,g=9,m=5;else if(2==b){var I=Ci(e,d,31)+257,_=Ci(e,d+10,15)+4,T=I+Ci(e,d+5,31)+1;d+=14;for(var E=new si(T),S=new si(19),x=0;x<_;++x)S[li[x]]=Ci(e,d+3*x,7);d+=3*_;var A=Ai(S),C=(1<<A)-1,R=wi(S,A,1);for(x=0;x<T;){var P,k=R[Ci(e,d,C)];if(d+=15&k,(P=k>>4)<16)E[x++]=P;else{var U=0,L=0;for(16==P?(L=3+Ci(e,d,3),d+=2,U=E[x-1]):17==P?(L=3+Ci(e,d,7),d+=3):18==P&&(L=11+Ci(e,d,127),d+=7);L--;)E[x++]=U}}var D=E.subarray(0,I),$=E.subarray(I);g=Ai(D),m=Ai($),f=wi(D,g,1),h=wi($,m,1)}else Li(1);if(d>y){c&&Li(0);break}}a&&l(p+131072);for(var O=(1<<g)-1,N=(1<<m)-1,B=d;;B=d){var j=(U=f[Ri(e,d)&O])>>4;if((d+=15&U)>y){c&&Li(0);break}if(U||Li(2),j<256)r[p++]=j;else{if(256==j){B=d,f=null;break}var M=j-254;if(j>264){var F=ai[x=j-257];M=Ci(e,d,(1<<F)-1)+pi[x],d+=F}var H=h[Ri(e,d)&N],G=H>>4;if(H||Li(3),d+=15&H,$=gi[G],G>3&&(F=ci[G],$+=Ri(e,d)&(1<<F)-1,d+=F),d>y){c&&Li(0);break}a&&l(p+131072);var Y=p+M;if(p<$){var W=o-$,V=Math.min($,Y);for(W+p<0&&Li(3);p<V;++p)r[p]=n[W+p]}for(;p<Y;++p)r[p]=r[p-$]}}t.l=f,t.p=B,t.b=p,t.f=u,f&&(u=1,t.m=g,t.d=h,t.n=m)}while(!u);return p!=r.length&&i?ki(r,0,p):r.subarray(0,p)},$i=function(e,t,r){r<<=7&t;var n=t/8|0;e[n]|=r,e[n+1]|=r>>8},Oi=function(e,t,r){r<<=7&t;var n=t/8|0;e[n]|=r,e[n+1]|=r>>8,e[n+2]|=r>>16},Ni=function(e,t){for(var r=[],n=0;n<e.length;++n)e[n]&&r.push({s:n,f:e[n]});var s=r.length,o=r.slice();if(!s)return{t:Yi,l:0};if(1==s){var i=new si(r[0].s+1);return i[r[0].s]=1,{t:i,l:1}}r.sort(function(e,t){return e.f-t.f}),r.push({s:-1,f:25001});var a=r[0],c=r[1],l=0,u=1,d=2;for(r[0]={s:-1,f:a.f+c.f,l:a,r:c};u!=s-1;)a=r[r[l].f<r[d].f?l++:d++],c=r[l!=u&&r[l].f<r[d].f?l++:d++],r[u++]={s:-1,f:a.f+c.f,l:a,r:c};var p=o[0].s;for(n=1;n<s;++n)o[n].s>p&&(p=o[n].s);var f=new oi(p+1),h=Bi(r[u-1],f,0);if(h>t){n=0;var g=0,m=h-t,y=1<<m;for(o.sort(function(e,t){return f[t.s]-f[e.s]||e.f-t.f});n<s;++n){var b=o[n].s;if(!(f[b]>t))break;g+=y-(1<<h-f[b]),f[b]=t}for(g>>=m;g>0;){var w=o[n].s;f[w]<t?g-=1<<t-f[w]++-1:++n}for(;n>=0&&g;--n){var v=o[n].s;f[v]==t&&(--f[v],++g)}h=t}return{t:new si(f),l:h}},Bi=function(e,t,r){return-1==e.s?Math.max(Bi(e.l,t,r+1),Bi(e.r,t,r+1)):t[e.s]=r},ji=function(e){for(var t=e.length;t&&!e[--t];);for(var r=new oi(++t),n=0,s=e[0],o=1,i=function(e){r[n++]=e},a=1;a<=t;++a)if(e[a]==s&&a!=t)++o;else{if(!s&&o>2){for(;o>138;o-=138)i(32754);o>2&&(i(o>10?o-11<<5|28690:o-3<<5|12305),o=0)}else if(o>3){for(i(s),--o;o>6;o-=6)i(8304);o>2&&(i(o-3<<5|8208),o=0)}for(;o--;)i(s);o=1,s=e[a]}return{c:r.subarray(0,n),n:t}},Mi=function(e,t){for(var r=0,n=0;n<t.length;++n)r+=e[n]*t[n];return r},Fi=function(e,t,r){var n=r.length,s=Pi(t+2);e[s]=255&n,e[s+1]=n>>8,e[s+2]=255^e[s],e[s+3]=255^e[s+1];for(var o=0;o<n;++o)e[s+o+4]=r[o];return 8*(s+4+n)},Hi=function(e,t,r,n,s,o,i,a,c,l,u){$i(t,u++,r),++s[256];for(var d=Ni(s,15),p=d.t,f=d.l,h=Ni(o,15),g=h.t,m=h.l,y=ji(p),b=y.c,w=y.n,v=ji(g),I=v.c,_=v.n,T=new oi(19),E=0;E<b.length;++E)++T[31&b[E]];for(E=0;E<I.length;++E)++T[31&I[E]];for(var S=Ni(T,7),x=S.t,A=S.l,C=19;C>4&&!x[li[C-1]];--C);var R,P,k,U,L=l+5<<3,D=Mi(s,vi)+Mi(o,Ii)+i,$=Mi(s,p)+Mi(o,g)+i+14+3*C+Mi(T,x)+2*T[16]+3*T[17]+7*T[18];if(c>=0&&L<=D&&L<=$)return Fi(t,u,e.subarray(c,c+l));if($i(t,u,1+($<D)),u+=2,$<D){R=wi(p,f,0),P=p,k=wi(g,m,0),U=g;var O=wi(x,A,0);for($i(t,u,w-257),$i(t,u+5,_-1),$i(t,u+10,C-4),u+=14,E=0;E<C;++E)$i(t,u+3*E,x[li[E]]);u+=3*C;for(var N=[b,I],B=0;B<2;++B){var j=N[B];for(E=0;E<j.length;++E){var M=31&j[E];$i(t,u,O[M]),u+=x[M],M>15&&($i(t,u,j[E]>>5&127),u+=j[E]>>12)}}}else R=Ti,P=vi,k=Si,U=Ii;for(E=0;E<a;++E){var F=n[E];if(F>255){Oi(t,u,R[257+(M=F>>18&31)]),u+=P[M+257],M>7&&($i(t,u,F>>23&31),u+=ai[M]);var H=31&F;Oi(t,u,k[H]),u+=U[H],H>3&&(Oi(t,u,F>>5&8191),u+=ci[H])}else Oi(t,u,R[F]),u+=P[F]}return Oi(t,u,R[256]),u+P[256]},Gi=new ii([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Yi=new si(0),Wi=function(e,t,r,n,s,o){var i=o.z||e.length,a=new si(n+i+5*(1+Math.ceil(i/7e3))+s),c=a.subarray(n,a.length-s),l=o.l,u=7&(o.r||0);if(t){u&&(c[0]=o.r>>3);for(var d=Gi[t-1],p=d>>13,f=8191&d,h=(1<<r)-1,g=o.p||new oi(32768),m=o.h||new oi(h+1),y=Math.ceil(r/3),b=2*y,w=function(t){return(e[t]^e[t+1]<<y^e[t+2]<<b)&h},v=new ii(25e3),I=new oi(288),_=new oi(32),T=0,E=0,S=o.i||0,x=0,A=o.w||0,C=0;S+2<i;++S){var R=w(S),P=32767&S,k=m[R];if(g[P]=k,m[R]=P,A<=S){var U=i-S;if((T>7e3||x>24576)&&(U>423||!l)){u=Hi(e,c,0,v,I,_,E,x,C,S-C,u),x=T=E=0,C=S;for(var L=0;L<286;++L)I[L]=0;for(L=0;L<30;++L)_[L]=0}var D=2,$=0,O=f,N=P-k&32767;if(U>2&&R==w(S-N))for(var B=Math.min(p,U)-1,j=Math.min(32767,S),M=Math.min(258,U);N<=j&&--O&&P!=k;){if(e[S+D]==e[S+D-N]){for(var F=0;F<M&&e[S+F]==e[S+F-N];++F);if(F>D){if(D=F,$=N,F>B)break;var H=Math.min(N,F-2),G=0;for(L=0;L<H;++L){var Y=S-N+L&32767,W=Y-g[Y]&32767;W>G&&(G=W,k=Y)}}}N+=(P=k)-(k=g[P])&32767}if($){v[x++]=268435456|fi[D]<<18|mi[$];var V=31&fi[D],z=31&mi[$];E+=ai[V]+ci[z],++I[257+V],++_[z],A=S+D,++T}else v[x++]=e[S],++I[e[S]]}}for(S=Math.max(S,A);S<i;++S)v[x++]=e[S],++I[e[S]];u=Hi(e,c,l,v,I,_,E,x,C,S-C,u),l||(o.r=7&u|c[u/8|0]<<3,u-=7,o.h=m,o.p=g,o.i=S,o.w=A)}else{for(S=o.w||0;S<i+l;S+=65535){var K=S+65535;K>=i&&(c[u/8|0]=l,K=i),u=Fi(c,u+1,e.subarray(S,K))}o.i=i}return ki(a,0,n+Pi(u)+s)},Vi=function(){for(var e=new Int32Array(256),t=0;t<256;++t){for(var r=t,n=9;--n;)r=(1&r&&-306674912)^r>>>1;e[t]=r}return e}(),zi=function(){var e=-1;return{p:function(t){for(var r=e,n=0;n<t.length;++n)r=Vi[255&r^t[n]]^r>>>8;e=r},d:function(){return~e}}},Ki=function(e,t,r,n,s){if(!s&&(s={l:1},t.dictionary)){var o=t.dictionary.subarray(-32768),i=new si(o.length+e.length);i.set(o),i.set(e,o.length),e=i,s.w=o.length}return Wi(e,null==t.level?6:t.level,null==t.mem?s.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(e.length)))):20:12+t.mem,r,n,s)},qi=function(e,t){var r={};for(var n in e)r[n]=e[n];for(var n in t)r[n]=t[n];return r},Ji=function(e,t,r){for(var n=e(),s=e.toString(),o=s.slice(s.indexOf("[")+1,s.lastIndexOf("]")).replace(/\s+/g,"").split(","),i=0;i<n.length;++i){var a=n[i],c=o[i];if("function"==typeof a){t+=";"+c+"=";var l=a.toString();if(a.prototype)if(-1!=l.indexOf("[native code]")){var u=l.indexOf(" ",8)+1;t+=l.slice(u,l.indexOf("(",u))}else for(var d in t+=l,a.prototype)t+=";"+c+".prototype."+d+"="+a.prototype[d].toString();else t+=l}else r[c]=a}return t},Xi=[],Qi=function(e){var t=[];for(var r in e)e[r].buffer&&t.push((e[r]=new e[r].constructor(e[r])).buffer);return t},Zi=function(e,t,r,n){if(!Xi[r]){for(var s="",o={},i=e.length-1,a=0;a<i;++a)s=Ji(e[a],s,o);Xi[r]={c:Ji(e[i],s,o),e:o}}var c=qi({},Xi[r].e);return ni(Xi[r].c+";onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage="+t.toString()+"}",r,c,Qi(c),n)},ea=function(){return[si,oi,ii,ai,ci,li,pi,gi,Ei,xi,yi,Ui,wi,Ai,Ci,Ri,Pi,ki,Li,Di,Ra,ra,na]},ta=function(){return[si,oi,ii,ai,ci,li,fi,mi,Ti,vi,Si,Ii,yi,Gi,Yi,wi,$i,Oi,Ni,Bi,ji,Mi,Fi,Hi,Pi,ki,Wi,Ki,Ca,ra]},ra=function(e){return postMessage(e,[e.buffer])},na=function(e){return e&&{out:e.size&&new si(e.size),dictionary:e.dictionary}},sa=function(e,t,r,n,s,o){var i=Zi(r,n,s,function(e,t){i.terminate(),o(e,t)});return i.postMessage([e,t],t.consume?[e.buffer]:[]),function(){i.terminate()}},oa=function(e,t){return e[t]|e[t+1]<<8},ia=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},aa=function(e,t){return ia(e,t)+4294967296*ia(e,t+4)},ca=function(e,t,r){for(;r;++t)e[t]=r,r>>>=8},la=function(e,t,r,n){for(var s in e){var o=e[s],i=t+s,a=n;Array.isArray(o)&&(a=qi(n,o[1]),o=o[0]),o instanceof si?r[i]=[o,a]:(r[i+="/"]=[new si(0),a],la(o,i,r,n))}},ua="undefined"!=typeof TextEncoder&&new TextEncoder,da="undefined"!=typeof TextDecoder&&new TextDecoder;try{da.decode(Yi,{stream:!0})}catch(e){}pa=function(e){for(var t="",r=0;;){var n=e[r++],s=(n>127)+(n>223)+(n>239);if(r+s>e.length)return{s:t,r:ki(e,r-1)};s?3==s?(n=((15&n)<<18|(63&e[r++])<<12|(63&e[r++])<<6|63&e[r++])-65536,t+=String.fromCharCode(55296|n>>10,56320|1023&n)):t+=1&s?String.fromCharCode((31&n)<<6|63&e[r++]):String.fromCharCode((15&n)<<12|(63&e[r++])<<6|63&e[r++]):t+=String.fromCharCode(n)}},fa=function(e,t){return t+30+oa(e,t+26)+oa(e,t+28)},ha=function(e,t,r){var n=oa(e,t+28),s=function(e,t){if(t){for(var r="",n=0;n<e.length;n+=16384)r+=String.fromCharCode.apply(null,e.subarray(n,n+16384));return r}if(da)return da.decode(e);var s=pa(e),o=s.s;return(r=s.r).length&&Li(8),o}(e.subarray(t+46,t+46+n),!(2048&oa(e,t+8))),o=t+46+n,i=ia(e,t+20),a=r&&4294967295==i?ga(e,o):[i,ia(e,t+24),ia(e,t+42)],c=a[0],l=a[1],u=a[2];return[oa(e,t+10),c,l,s,o+oa(e,t+30)+oa(e,t+32),u]},ga=function(e,t){for(;1!=oa(e,t);t+=4+oa(e,t+2));return[aa(e,t+12),aa(e,t+4),aa(e,t+20)]},ma=function(e){var t=0;if(e)for(var r in e){var n=e[r].length;n>65535&&Li(9),t+=n+4}return t},ya=function(e,t,r,n,s,o,i,a){var c=n.length,l=r.extra,u=a&&a.length,d=ma(l);ca(e,t,null!=i?33639248:67324752),t+=4,null!=i&&(e[t++]=20,e[t++]=r.os),e[t]=20,t+=2,e[t++]=r.flag<<1|(o<0&&8),e[t++]=s&&8,e[t++]=255&r.compression,e[t++]=r.compression>>8;var p=new Date(null==r.mtime?Date.now():r.mtime),f=p.getFullYear()-1980;if((f<0||f>119)&&Li(10),ca(e,t,f<<25|p.getMonth()+1<<21|p.getDate()<<16|p.getHours()<<11|p.getMinutes()<<5|p.getSeconds()>>1),t+=4,-1!=o&&(ca(e,t,r.crc),ca(e,t+4,o<0?-o-2:o),ca(e,t+8,r.size)),ca(e,t+12,c),ca(e,t+14,d),t+=16,null!=i&&(ca(e,t,u),ca(e,t+6,r.attrs),ca(e,t+10,i),t+=14),e.set(n,t),t+=c,d)for(var h in l){var g=l[h],m=g.length;ca(e,t,+h),ca(e,t+2,m),e.set(g,t+4),t+=4+m}return u&&(e.set(a,t),t+=u),t},ba=function(e,t,r,n,s){ca(e,t,101010256),ca(e,t+8,r),ca(e,t+10,r),ca(e,t+12,n),ca(e,t+16,s)},wa="function"==typeof queueMicrotask?queueMicrotask:"function"==typeof setTimeout?setTimeout:function(e){e()}}});function $a(e,t,r){const n=Math.min(t,La);if("utf-16"===r||"utf-16le"===r||"utf-16be"===r){for(let t=0;t<n;t+=2){const s=e[t],o=t+1<n?e[t+1]:0;if(("utf-16le"===r||"utf-16"===r)&&0===o&&s<32&&9!==s&&10!==s&&13!==s&&0!==s)return!1;if(("utf-16be"===r||"utf-16"===r)&&0===s&&o<32&&9!==o&&10!==o&&13!==o&&0!==o)return!1}return!0}if("latin1"===r||"iso-8859-1"===r){for(let t=0;t<n;t++){const r=e[t];if(0===r)return!1;if(r<32&&9!==r&&10!==r&&13!==r)return!1}return!0}if("cjk"===r||"big5"===r||"gb2312"===r||"gbk"===r||"euc-kr"===r||"shift-jis"===r){for(let t=0;t<n;t++){const r=e[t];if(0===r)return!1;if(r<32&&9!==r&&10!==r&&13!==r)return!1}return!0}return!1}var Oa,Na,Ba,ja=Fe({"../../app/node_modules/.pnpm/isbinaryfile@6.0.0/node_modules/isbinaryfile/lib/encoding.js"(){La=512}});function Ma(e){let t=0,r=0;for(;!e.hasError();){const n=e.nextByte();if(r|=(127&n)<<7*t,!(128&n))break;if(t>=10){e.error=!0;break}t++}return r}function Fa(e){switch(7&Ma(e)){case 0:return Ma(e),!0;case 1:return e.next(8),!0;case 2:const t=Ma(e);return e.next(t),!0;case 5:return e.next(4),!0}return!1}function Ha(e,t,r){if(0===t)return!1;let n=0;const s=Math.min(t,Oa+Na),o=Math.min(s,Oa);if(t>=3&&239===e[0]&&187===e[1]&&191===e[2])return!1;if(t>=4&&0===e[0]&&0===e[1]&&254===e[2]&&255===e[3])return!1;if(t>=4&&255===e[0]&&254===e[1]&&0===e[2]&&0===e[3])return!1;if(t>=4&&132===e[0]&&49===e[1]&&149===e[2]&&51===e[3])return!1;if(s>=5&&"%PDF-"===e.slice(0,5).toString())return!0;if(t>=2&&254===e[0]&&255===e[1])return!1;if(t>=2&&255===e[0]&&254===e[1])return!1;if(r?.encoding)return!$a(e,t,r.encoding);const i=function(e,t){if(t<4)return null;const r=Math.min(t,La);let n=0,s=0;for(let t=0;t<r;t++)0===e[t]&&(t%2==0?n++:s++);const o=n+s;if(o>.3*r&&o<.7*r){if(s>3*n)return"utf-16le";if(n>3*s)return"utf-16be"}return null}(e,t);if(i)return!$a(e,t,i);for(let t=0;t<o;t++){if(0===e[t])return!0;if((e[t]<7||e[t]>14)&&(e[t]<32||e[t]>127)){if(e[t]>=192&&e[t]<=223&&t+1<s){if(t++,e[t]>=128&&e[t]<=191)continue}else if(e[t]>=224&&e[t]<=239&&t+2<s){if(t++,e[t]>=128&&e[t]<=191&&e[t+1]>=128&&e[t+1]<=191){t++;continue}}else if(e[t]>=240&&e[t]<=247&&t+3<s&&(t++,e[t]>=128&&e[t]<=191&&e[t+1]>=128&&e[t+1]<=191&&e[t+2]>=128&&e[t+2]<=191)){t+=2;continue}if(n++,t>=32&&100*n/o>10)return!0}}return 100*n/o>10||!!(n>1&&function(e,t){const r=new Ba(e,t);let n=0;for(;;){if(!Fa(r)&&!r.hasError())return!1;if(r.hasError())break;n++}return n>0}(e,o))}var Ga,Ya,Wa,Va,za,Ka=Fe({"../../app/node_modules/.pnpm/isbinaryfile@6.0.0/node_modules/isbinaryfile/lib/index.js"(){ja(),Oa=512,Na=3,Ba=class{fileBuffer;size;offset;error;constructor(e,t){this.fileBuffer=e,this.size=t,this.offset=0,this.error=!1}hasError(){return this.error}nextByte(){return this.offset===this.size||this.hasError()?(this.error=!0,255):this.fileBuffer[this.offset++]}next(e){if(e<0||e>this.size-this.offset)return this.error=!0,[];const t=new Array;for(let r=0;r<e;r++){if(this.error)return t;t[r]=this.nextByte()}return t}}}}),qa=Fe({"../playwright-trace-scrubber/src/filter-sensitive-values.ts"(){Ga=[/^\/$/,/^\*+$/,/^[0-9]+$/],Ya=["/artifact/","https://","http://","*********"],Wa=3}});function Ja({sensitiveValues:e,str:t}){return e.reduce((e,t)=>e.replaceAll(t,Va),t)}function Xa({sensitiveValues:e,value:t}){return"string"==typeof t?Ja({sensitiveValues:e,str:t}):Array.isArray(t)?t.map(t=>Xa({sensitiveValues:e,value:t})):function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(t)?Za({obj:t,sensitiveValues:e}):t}function Qa(e){return!!za.has(e)||e.toLowerCase().endsWith("sha1")}function Za({obj:e,sensitiveValues:t}){return Object.fromEntries(Object.entries(e).map(([e,r])=>[e,Qa(e)?r:Xa({sensitiveValues:t,value:r})]))}var ec=Fe({"../playwright-trace-scrubber/src/scrubbers/primitives.ts"(){Va="[REDACTED]",za=new Set(["sha1","_sha1","pageref","downloadsPath","tracesDir","pageId"])}});function tc({error:e,sensitiveValues:t}){return e?{...e,message:Ja({sensitiveValues:t,str:e.message})}:void 0}var rc=Fe({"../playwright-trace-scrubber/src/scrubbers/events.ts"(){ec()}});function nc({content:e,sensitiveValues:t}){const r=new de,n=new pe,s=Ja({sensitiveValues:t,str:r.decode(e)});return n.encode(s)}var sc,oc,ic=Fe({"../playwright-trace-scrubber/src/scrubbers/files.ts"(){rc(),ec()}});async function ac({content:e,filename:t,sensitiveValues:r}){const n=t.toLowerCase();return n.endsWith(".trace")||n.endsWith(".network")?function({content:e,sensitiveValues:t}){const r=new de,n=new pe,s=r.decode(e).split("\n").map(e=>{if(!e.trim())return e;try{const r=function({event:e,sensitiveValues:t}){return Ie(e).with({type:"console"},e=>({...e,args:e.args?.map(e=>({...e,preview:Ja({sensitiveValues:t,str:e.preview}),value:Xa({sensitiveValues:t,value:e.value})})),text:Ja({sensitiveValues:t,str:e.text})})).with({type:"before"},e=>({...e,params:Za({obj:e.params,sensitiveValues:t}),title:e.title?Ja({sensitiveValues:t,str:e.title}):void 0})).with({type:"after"},e=>({...e,error:tc({error:e.error,sensitiveValues:t}),result:void 0!==e.result?Xa({sensitiveValues:t,value:e.result}):void 0})).with({type:"action"},e=>({...e,error:tc({error:e.error,sensitiveValues:t}),params:Za({obj:e.params,sensitiveValues:t}),result:void 0!==e.result?Xa({sensitiveValues:t,value:e.result}):void 0,title:e.title?Ja({sensitiveValues:t,str:e.title}):void 0})).with({type:"event"},e=>({...e,params:Za({obj:e.params,sensitiveValues:t})})).with({type:"stdout"},{type:"stderr"},e=>({...e,text:void 0!==e.text?Ja({sensitiveValues:t,str:e.text}):void 0})).with({type:"error"},e=>({...e,message:Ja({sensitiveValues:t,str:e.message})})).with({type:"log"},e=>({...e,message:Ja({sensitiveValues:t,str:e.message})})).with({type:"context-options"},e=>({...e,options:Za({obj:e.options,sensitiveValues:t}),title:e.title?Ja({sensitiveValues:t,str:e.title}):void 0})).with({type:"frame-snapshot"},e=>({...e,snapshot:Za({obj:e.snapshot,sensitiveValues:t})})).with({type:"resource-snapshot"},e=>({...e,snapshot:Za({obj:e.snapshot,sensitiveValues:t})})).with({type:"screencast-frame"},{type:"input"},e=>e).exhaustive()}({event:JSON.parse(e),sensitiveValues:t});return JSON.stringify(r)}catch{return Ja({sensitiveValues:t,str:e})}});return n.encode(s.join("\n"))}({content:e,sensitiveValues:r}):n.endsWith(".html")||n.endsWith(".dat")||n.endsWith(".json")?nc({content:e,sensitiveValues:r}):n.startsWith("resources/")?async function({content:e,sensitiveValues:t}){return function(e){return function(e,t){if(function(e){return"string"==typeof e}(e)){!function(e){if(!e.isFile())throw new Error("Path provided was not a file!")}(K(e));const r=X(e,"r"),n=Buffer.alloc(Oa+Na),s=Q(r,n,0,Oa+Na,0);return Z(r),Ha(n,s,t)}return Ha(e,void 0!==t?.size?t.size:e.length,t)}(Buffer.from(e),{size:e.length})}(e)?e:nc({content:e,sensitiveValues:t})}({content:e,sensitiveValues:r}):e}var cc=Fe({"../playwright-trace-scrubber/src/scrub-trace.ts"(){Da(),Ka(),qa(),ic(),sc=ue(Ua),oc=ue(ka)}}),lc=Fe({"../playwright-trace-scrubber/src/index.ts"(){cc(),ec(),qa()}});function uc(e=process.cwd()){let t=s(e);for(;;){const e=dc(t);if(e){const r={...e.dependencies,...e.devDependencies},n="@playwright/test"in r?"@playwright/test":"playwright"in r?"playwright":void 0;if(n){const e=pc(t);let r=!1,s=t;for(;;){const e=i(s,"node_modules"),t=i(e,n);if(H(t)){r=!0;break}const a=o(s);if(a===s)break;s=a}return{inNodeModules:r,installed:!0,packageManager:e,packageName:n}}}const r=o(t);if(r===t)return{inNodeModules:!1,installed:!1,packageManager:void 0};t=r}}function dc(e){const t=i(e,"package.json");let r;try{r=G(t,"utf-8")}catch{return}try{return JSON.parse(r)}catch{return}}function pc(e){const t=[["npm","package-lock.json"],["pnpm","pnpm-lock.yaml"],["yarn","yarn.lock"]];let r=e;for(;;){for(const[e,n]of t)if(H(i(r,n)))return e;const e=o(r);if(e===r)return;r=e}}function fc(e){if("npm"===e||"pnpm"===e)return["npx","playwright"];if("yarn"===e)return["yarn","playwright"];throw new Error("Package manager not supported")}var hc,gc,mc,yc,bc,wc,vc,Ic,_c,Tc,Ec,Sc,xc,Ac,Cc,Rc,Pc,kc,Uc,Lc,Dc,$c,Oc,Nc,Bc=Fe({"src/playwright/playwright-installation.ts"(){}}),jc=Fe({"src/agent/auto-heal-report/trace-proof.ts"(){Aa(),lc(),gs(),hs(),Bc(),hc=e=>e.includes("Executable doesn't exist")&&e.includes("ms-playwright")?'Playwright browsers are not installed. Run "npx playwright install" to install them.':e.includes("browserType.launch")&&e.includes("Executable doesn't exist")?"Browser executable not found. Playwright browsers may not be installed.":e.includes("npx playwright install")?"Playwright browsers need to be installed. The trace cannot verify the fix.":void 0,gc=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),mc=e=>(e instanceof Error?e.message:String(e)).slice(0,400),yc=e=>null!=e.filePath||null!=e.testTitle||null!=e.testIdentifier,bc=({outputDir:e,representativeTest:t})=>{const r=["test","--trace=on","--workers=1","--retries=0","--reporter=list","--output",e];return t.filePath&&r.push(t.filePath),t.testTitle?r.push("--grep",gc(t.testTitle)):t.testIdentifier&&r.push("--grep",`^${gc(t.testIdentifier)}$`),r},wc=async({args:e,command:t,cwd:r,env:n,timeoutMs:s})=>await new Promise((o,i)=>{const a=oe(t,e,{cwd:r,env:n??process.env,stdio:["ignore","ignore","pipe"],shell:"win32"===process.platform});let c="",l=!1;a.stderr.on("data",e=>{c+=e.toString()});const u=setTimeout(()=>{l=!0,a.kill("SIGTERM")},s);a.on("error",e=>{clearTimeout(u),i(e)}),a.on("close",e=>{clearTimeout(u),o({code:e,stderr:c,timedOut:l})})}),vc=async e=>{const t=await _(e,{withFileTypes:!0}),r=[];for(const s of t){const t=n.join(e,s.name);if(s.isDirectory())r.push(...await vc(t));else if(s.isFile()&&"trace.zip"===s.name){const e=await I(t);r.push({path:t,mtimeMs:e.mtimeMs})}}return r},Ic=async e=>{const t=await vc(e);if(0!==t.length)return t.sort((e,t)=>t.mtimeMs-e.mtimeMs),t[0]?.path},_c=async e=>{try{const t=await _(e,{withFileTypes:!0});for(const r of t){const t=n.join(e,r.name);r.isDirectory()?await _c(t):r.isFile()&&".last-run.json"===r.name&&await b(t,{force:!0})}}catch{}},Tc=async({representativeTest:e,workingDir:t,outputDir:r})=>{if(!yc(e))return{status:"capture_failed",error:"Representative test info is missing (need filePath, testTitle, or testIdentifier)."};const n=uc(t);if(!n.installed||!n.inNodeModules||!n.packageManager)return{status:"capture_failed",error:"Playwright is not installed in the current workspace."};const[s,...o]=fc(n.packageManager),i=[...o,...bc({outputDir:r,representativeTest:e})];try{await b(r,{force:!0,recursive:!0}),await v(r,{recursive:!0});const{code:e,stderr:n,timedOut:o}=await wc({args:i,command:s,cwd:t,env:{...process.env,STABLY_INTERNAL_DISABLE_REPORTING:"1"},timeoutMs:3e5});if(o)return{status:"capture_failed",error:"Trace proof run timed out while executing Playwright verification."};const a=hc(n);if(a)return{status:"capture_failed",error:a};const c=await Ic(r);return c?(await _c(r),{status:"captured",tracePath:c}):{status:"capture_failed",error:`No trace.zip was produced${0!==e?` (test exit code ${e??"unknown"})`:""}: ${n.trim().slice(0,280)}`.trim()}}catch(e){return{status:"capture_failed",error:mc(e)}}},Ec=async({representativeTest:e,workingDir:t,outputDir:r,requestUploadUrl:n})=>{const s=await Tc({representativeTest:e,workingDir:t,outputDir:r});if("capture_failed"===s.status)return s;try{const{traceBucketPath:e,uploadUrl:t,sensitiveValues:r}=await n(),o=await async function({tracePath:e,sensitiveValues:t}){const r=[],n=J(e);for await(const e of n)r.push(e);return async function({sensitiveValues:e,traceBuffer:t}){const r=e.filter(e=>!(e.length<Wa||Ga.some(t=>t.test(e))||Ya.some(t=>e.includes(t))));if(0===r.length)return new Uint8Array(t);const n=[...r].sort((e,t)=>t.length-e.length),s=await sc(new Uint8Array(t)),o=Object.entries(s),i=await Promise.all(o.map(async([e,t])=>[e,await ac({content:t,filename:e,sensitiveValues:n})])),a=Object.fromEntries(i);return oc(a)}({traceBuffer:new Uint8Array(Buffer.concat(r)),sensitiveValues:t})}({tracePath:s.tracePath,sensitiveValues:r});try{await Pn({body:o,contentType:"application/zip",uploadUrl:t,errorContext:"trace"})}catch(e){return{status:"upload_failed",error:mc(e)}}return{status:"captured",storage:e}}catch(e){return{status:"capture_failed",error:mc(e)}}},Sc=async({authHeader:e,issueId:t,orgId:r,proofId:s,representativeTest:o,runId:i,testCaseId:a,workingDir:c})=>{const l=Xo(t),u=Zo({testCaseId:a,proofId:s}),d=n.join(c,".stably","autoheal-proof",l,u??"issue");return{...await Ec({representativeTest:o,workingDir:c,outputDir:d,requestUploadUrl:()=>os({authHeader:e,issueId:t,proofId:s,orgId:r,runId:i,testCaseId:a})}),representativeTest:o}}}}),Mc=Fe({"src/agent/auto-heal-report/schema.ts"(){Aa(),({zIssueCategory:xc,zAutoHealReport:Ac,zMarkdownAutoHealReport:Cc,zMarkdownAutoHealReportIssue:Rc,zSuiteAutoHealReport:Pc,zStoredAutoHealReport:kc,zTraceProof:Uc,zTraceProofByTest:Lc,zRepresentativeTest:Dc}=function(e){const t=e.enum(Vo),r=ei(),n=e.object({filePath:e.string().optional(),testIdentifier:e.string().optional(),testTitle:e.string().optional()}),s=e.object({status:e.enum(["captured","capture_failed","upload_failed"]),representativeTest:n,storage:e.object({bucket:e.string(),key:e.string()}).optional(),signedUrl:e.string().optional(),error:e.string().optional()}),o=s.extend({testCaseId:e.string().min(1).describe("Test case ID this trace proof corresponds to.")}),i=e.object({erroredUrl:e.string().optional(),issueType:t.describe(r),relatedTestCaseIds:e.array(e.string()).min(1).describe("List of ALL test case IDs impacted by this root cause (must be existing IDs only)."),rootCause:e.string().describe("Brief explanation of what happened (1-2 sentences). Include file:line references (e.g., `src/tests/login.spec.ts:42`) to back up your claim."),traceProofs:e.array(o).min(1).optional().describe("Per-test trace proofs for each testCaseId in this issue.")}),a=e.discriminatedUnion("result",[i.extend({fixApplied:e.string().describe("What fix was applied (brief, specific). Include file:line references (e.g., `src/tests/login.spec.ts:42`) showing where changes were made."),result:e.literal("fixed"),traceProof:s.optional()}),i.extend({followUpActions:e.string().optional().describe("Optional list of follow-up actions for any unfixed issues or missing data."),reasonNotFixed:e.string().describe("Why it could not be auto-fixed (brief). Include file:line references (e.g., `src/tests/login.spec.ts:42`) pointing to the problematic code."),result:e.literal("unfixed")})]),c=e.object({issues:e.array(a).min(1).describe("List of all auto-heal issues/outcomes for this suite."),summary:e.string().min(3).describe("High-level summary (2-3 sentences) of the suite auto-heal results.")}),l=e.discriminatedUnion("result",[e.object({result:e.literal("fixed"),issueType:t,issueId:e.string().optional().describe("Issue ID from triage, used for deterministic fingerprinting across re-uploads."),rootCause:e.string().min(1),fixApplied:e.string().min(1).describe("What fix was applied (brief, specific). Include file:line references."),relatedTestCaseIds:e.array(e.string()).min(1)}),e.object({result:e.literal("unfixed"),issueType:t,issueId:e.string().optional().describe("Issue ID from triage, used for deterministic fingerprinting across re-uploads."),rootCause:e.string().min(1),reasonNotFixed:e.string().min(1).describe("Why it could not be auto-fixed (brief). Include file:line references."),relatedTestCaseIds:e.array(e.string()).min(1)})]),u=e.object({format:e.literal("markdown"),markdown:e.string().min(1).describe("Flexible markdown report content for the auto-heal run. Use headings, bullets, and code fences as needed."),summary:e.string().optional().describe('One-liner summary of the auto-heal run (e.g., "Fixed 2 of 3 issues: stale locators and timing"). Used in notifications, API responses, and triage agent context.'),issues:e.array(l).optional().describe("Structured issue metadata for database tracking. Each issue links a root cause to affected test case IDs.")});return{zAutoHealReport:a,zIssueCategory:t,zMarkdownAutoHealReport:u,zMarkdownAutoHealReportIssue:l,zRepresentativeTest:n,zSuiteAutoHealReport:c,zStoredAutoHealReport:e.union([u,c]),zTraceProof:s,zTraceProofByTest:o}}(te))}}),Fc=Fe({"src/agent/auto-heal-report/mcp-server.ts"(){gs(),hs(),jc(),Mc(),$c=({authHeader:e,diffTracker:t,orgId:r,runId:n,workingDir:s,partialReportId:o})=>Te({name:"auto-heal-report",tools:[Ee("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:te.string().min(1).describe("Issue identifier for deterministic output paths and storage key naming."),proofId:te.string().min(1).optional().describe("Optional id for deterministic proof naming and deduplication."),representativeTest:Dc.optional().default({}),testCaseId:te.string().min(1).optional().describe("Optional test case ID when capturing per-test trace proofs.")},async({issueId:t,proofId:o,representativeTest:i,testCaseId:a})=>{const c=te.string().min(1).parse(t),l=null==o?void 0:te.string().min(1).parse(o),u=null==a?void 0:te.string().min(1).parse(a),d=Dc.parse(i??{}),p=await Sc({authHeader:e,issueId:c,orgId:r,proofId:l,representativeTest:d,runId:n,testCaseId:u,workingDir:s}),f=d.testTitle||d.filePath,h="captured"===p.status&&p.storage?`@[trace:${Buffer.from(JSON.stringify({...p.storage,...f?{label:f}:{}})).toString("base64url")}]`:void 0,g="string"==typeof u?{testCaseId:u,...p,tracePlaceholder:h}:{...p,tracePlaceholder:h};return{content:[{text:JSON.stringify(g),type:"text"}]}}),Ee("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.","","ENTITY REFERENCES: When referencing entities by ID, use placeholder syntax so the UI can render clickable links:","- Test cases: @[test-case:<id>] (e.g., @[test-case:fp8f0yzdqqut6bg7cy5euzer])","- Suite runs: @[suite-run:<id>] (e.g., @[suite-run:cm6i7o6ti0000l40350wys0u1])","- Tests: @[test:<id>] (e.g., @[test:wty0g1v58cwrrd8jj6et8nmx])","- Traces: use the tracePlaceholder value returned by capture-trace-proof (e.g., @[trace:eyJi...])","These placeholders will be automatically resolved to clickable links with human-readable labels in the UI.","NEVER show raw entity IDs without wrapping them in @[type:id] syntax."].join("\n"),{markdown:Cc.shape.markdown,summary:Cc.shape.summary,issues:Cc.shape.issues},async({markdown:i,summary:a,issues:c})=>{const l=await t.computeDiff(),u=Cc.parse({format:"markdown",markdown:i,summary:a,issues:c});if(o){try{const{mkdir:e,writeFile:t}=await import("fs/promises"),{join:r}=await import("path"),n=r(s,".stably","partial-reports");await e(n,{recursive:!0});const c={partialReportId:o,markdown:i,summary:a,issues:u.issues};await t(r(n,`${o}.json`),JSON.stringify(c,null,2),"utf-8"),await t(r(n,`${o}.diff`),l,"utf-8")}catch(e){return console.error("[auto-heal-report] Failed to write partial report:",e),{content:[{text:`Error: Failed to write partial report. ${e instanceof Error?e.message:String(e)}`,type:"text"}]}}return{content:[{text:`Partial report "${o}" written. You may terminate this session now.`,type:"text"}]}}try{await rs({authHeader:e,orgId:r,report:u,runId:n});const{diffBucketPath:t,uploadUrl:s}=await ns({authHeader:e,contentType:"text/plain",orgId:r,runId:n});await Pn({body:l,contentType:"text/plain",uploadUrl:s,errorContext:"diff"}),await ss({authHeader:e,diffBucketPath:t,orgId:r,runId:n})}catch(e){return console.error("[auto-heal-report] Failed to upload report or diff:",e),{content:[{text:`Error: Failed to upload auto-heal report or diff. ${e instanceof Error?e.message:String(e)} Please surface this to the user, and terminate the session.`,type:"text"}]}}return{content:[{text:"Auto-heal report generated. You may terminate this session now.",type:"text"}]}})],version:"0.0.1"})}}),Hc=Fe({"src/agent/session-control-mcp.ts"(){Oc=({onComplete:e,onRestartRequested:t})=>Te(e?{name:"session-control",tools:[Ee("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:te.string().describe("A brief summary of what was accomplished")},({summary:t})=>{const r="string"==typeof t?t:String(t);return e(),Promise.resolve(`Session complete: ${r}`)})]}:{name:"stably-agent-control",version:"1.0.0",tools:[Ee("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.'}]})))]})}});function Gc({workingDir:e,packageManager:t,packageSpec:r,targetSection:n}){const{command:s,args:o}=function(e,t,r){const n="npm"===e?"npm":e;return{command:n,args:["npm"===e?"install":"add",..."devDependencies"===r?["bun"===e?"-d":"-D"]:[],..."npm"===n?["--no-fund"]:[],t]}}(t,r,n);ce(s,o,{cwd:e,stdio:"pipe",timeout:6e4})}function Yc(e){const t=r.join(e,"package.json");return M.existsSync(t)?{path:t,contents:JSON.parse(M.readFileSync(t,"utf-8"))}:null}function Wc(e){return Nc.some(t=>M.existsSync(r.join(e,t)))}function Vc(e,t){const n=M.readdirSync(e,{withFileTypes:!0}),s=[];for(const o of n){if("node_modules"===o.name||".git"===o.name)continue;const n=r.join(e,o.name);o.isDirectory()?s.push(...Vc(n,t)):t.test(o.name)&&s.push(n)}return s}function zc(e){let t=r.resolve(e);for(;;){if(Wc(t))return t;const n=r.dirname(t);if(n===t)return e;t=n}}function Kc(e){const t=Array.from(new Set(e.map(e=>r.resolve(e)))).sort((e,t)=>e.length-t.length),n=[];for(const e of t)n.some(t=>e===t||e.startsWith(`${t}${r.sep}`))||n.push(e);return n}function qc(e){return/\b(test|testing|playwright|e2e|stably)\b/i.test(e)}function Jc(e,t){for(const n of Xc(e,t))if(M.existsSync(r.join(n,"package.json")))return n}function Xc(e,t){const n=[];let s=r.resolve(e);const o=r.resolve(t);for(;n.push(s),s!==o;){const e=r.dirname(s);if(e===s)break;s=e}return n}function Qc(e){return e?.replace(/^[~^>=<]+/,"")}function Zc(e){let t=e;for(let e=0;e<5;e++){if(M.existsSync(r.join(t,"pnpm-lock.yaml")))return"pnpm";if(M.existsSync(r.join(t,"yarn.lock")))return"yarn";if(M.existsSync(r.join(t,"bun.lockb"))||M.existsSync(r.join(t,"bun.lock")))return"bun";if(M.existsSync(r.join(t,"package-lock.json"))||M.existsSync(r.join(t,"npm-shrinkwrap.json")))return"npm";const e=r.dirname(t);if(e===t)break;t=e}return"npm"}var el,tl,rl,nl,sl,ol,il,al,cl,ll,ul,dl,pl,fl,hl,gl,ml,yl=Fe({"src/agent/post-init-verify.ts"(){Us(),Vn(),Nc=["playwright.config.ts","playwright.config.js","playwright.config.mts","playwright.config.mjs","playwright.config.cjs"]}}),bl=Fe({"src/api/stably/create-report.ts"(){Ln(),Vn(),el=te.object({commentUrl:te.string()})}}),wl=Fe({"src/agent/create-report-mcp.ts"(){bl(),Vn(),tl=({prContext:e,authHeader:t,orgId:r,onReportPosted:n})=>Te({name:"create-report",tools:[Ee("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:te.string().describe("A summary of the tests created. Include what features/flows are tested and any important notes."),filesCreated:te.array(te.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:[];fn.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:r,owner:n,repo:s,report:o}){const i=new URL("/internal/v1/cli/create-report",Gt).toString(),a={Authorization:e,"Content-Type":"application/json"};t&&(a["x-stably-org-id"]=t),fn.debug("Posting create report to GitHub",{prNumber:r,owner:n,repo:s,filesCount:o.filesCreated.length});const c=await fetch(i,{method:"POST",headers:a,body:JSON.stringify({prNumber:r,owner:n,repo:s,report:o}),signal:AbortSignal.timeout(3e4)});if(!c.ok){const e=await c.text().catch(()=>"");throw fn.error("Failed to post create report",{status:c.status,error:e.slice(0,500)}),new Error(`Failed to post create report: ${c.status} ${e.slice(0,200)}`)}const l=el.parse(await c.json());return fn.info("Create report posted successfully",{commentUrl:l.commentUrl}),l}({authHeader:t,orgId:r,prNumber:e.prNumber,owner:e.owner,repo:e.repo,report:o});return n?.(a),fn.info("[create-report] Report posted successfully",{commentUrl:a.commentUrl}),{content:[{type:"text",text:`✅ Test creation report posted to PR #${e.prNumber}\n\nView the comment: ${a.commentUrl}`}]}}catch(e){const t=e instanceof Error?e.message:String(e);return fn.error("[create-report] Failed to post report",{error:t}),{content:[{type:"text",text:`❌ Failed to post report to GitHub: ${t}\n\nThe tests were still created successfully, but the PR comment could not be posted.`}],isError:!0}}})]})}}),vl=Fe({"src/api/stably/session-trace-upload.ts"(){kn(),Dn(),Xn(),hs(),rl=te.object({traceBucketPath:Rn,expiresInSeconds:te.number(),key:te.string(),uploadUrl:te.string(),sensitiveValues:te.array(te.string())}),nl=async({authHeader:e,sessionId:t,testFilePath:r,orgId:n,contentType:s="application/zip"})=>{const o=await kt({auth:e,body:{testFilePath:r,contentType:s},client:Zt(),headers:xn(n),path:{sessionId:t}});if(o.error)throw new Error(`Failed to presign session trace upload (${o.response.status})`);const i=rl.parse(o.data);return{traceBucketPath:i.traceBucketPath,expiresInSeconds:i.expiresInSeconds,key:i.key,uploadUrl:i.uploadUrl,sensitiveValues:i.sensitiveValues}}}}),Il=Fe({"src/agent/create-trace-proof-mcp.ts"(){Aa(),vl(),Vn(),jc(),Mc(),sl=({authHeader:e,sessionId:t,orgId:r,workingDir:s,onTraceProofCaptured:o})=>Te({name:"create-trace-proof",tools:[Ee("capture-create-trace-proof",["Capture and upload a Playwright trace proof for a created test file.","","Call this after verifying that a created test file passes.","The trace proves the test works and is viewable in the Stably web UI.","","Pass the testFilePath of the created test file.","Optionally pass representativeTest to narrow which test to run (useful for files with multiple tests)."].join("\n"),{testFilePath:te.string().min(1).describe("Path to the created test file (relative to workspace root)."),representativeTest:Dc.optional().default({})},async({testFilePath:i,representativeTest:a})=>{const c=te.string().min(1).parse(i),l=Dc.parse(a??{}),u={...l,filePath:l.filePath??c},d=Xo(c),p=n.join(s,".stably","create-proof",d);fn.info("[create-trace-proof] Capturing trace",{testFilePath:c});const f=await Ec({representativeTest:u,workingDir:s,outputDir:p,requestUploadUrl:()=>nl({authHeader:e,sessionId:t,testFilePath:c,orgId:r})});"captured"===f.status?(await b(p,{recursive:!0,force:!0}).catch(()=>{}),fn.info("[create-trace-proof] Upload succeeded",{testFilePath:c,traceBucketPath:f.storage})):fn.error("[create-trace-proof] Failed",{testFilePath:c,error:f.error});const h={testFilePath:c,status:f.status,storage:"captured"===f.status?f.storage:null,..."error"in f?{error:f.error}:{}};return o?.(h),{content:[{type:"text",text:JSON.stringify(h)}]}})]})}}),_l=Fe({"src/agent/run-history-mcp.ts"(){kn(),Dn(),Xn(),Vn(),ol=["QUEUED","RUNNING","PASSED","FAILED","TIMEDOUT","CANCELLED","INTERRUPTED"],il=["LOCAL","CI","WEB"],al=["MANUAL","SCHEDULED","UI","API","GITHUB_ACTION","SUITE_RUN"],cl=({authHeader:e,orgId:t,projectId:r})=>Te({name:"run-history",tools:[Ee("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:te.string().optional().describe("Filter by branch name"),status:te.enum(ol).optional().describe("Filter by status: QUEUED|RUNNING|PASSED|FAILED|TIMEDOUT|CANCELLED|INTERRUPTED"),limit:te.number().min(1).max(100).optional().describe("Max results (1-100, default 20)"),source:te.enum(il).optional().describe("Filter by source: LOCAL|CI|WEB"),trigger:te.enum(al).optional().describe("Filter by trigger: MANUAL|SCHEDULED|UI|API|GITHUB_ACTION|SUITE_RUN"),suite:te.string().optional().describe("Filter by suite name"),after:te.string().optional().describe("Pagination: return runs after this runId"),before:te.string().optional().describe("Pagination: return runs before this runId")},async({branch:n,status:s,limit:o,source:i,trigger:a,suite:c,after:l,before:u})=>{const d="string"==typeof n?n:void 0,p="string"==typeof s?s:void 0,f="number"==typeof o?o:void 0,h="string"==typeof i?i:void 0,g="string"==typeof a?a:void 0,m="string"==typeof c?c:void 0,y="string"==typeof l?l:void 0,b="string"==typeof u?u:void 0;fn.info("[run-history] list_runs called",{branch:d,status:p,limit:f});try{const n=await Nt({auth:e,client:Zt(),headers:xn(t),query:{projectId:r,branchName:d,status:p,limit:f,source:h,trigger:g,suiteName:m,afterRunId:y,beforeRunId:b}});if(n.error||!n.data){const e=n.response?`API error: ${n.response.status}`:`API error: ${String(n.error)}`;return fn.error("[run-history] list_runs failed",{error:e}),{content:[{type:"text",text:`Error: ${e}`}],isError:!0}}return fn.info("[run-history] list_runs success",{runCount:n.data.runs?.length??0,hasMore:n.data.hasMore}),{content:[{type:"text",text:JSON.stringify(n.data)}]}}catch(e){const t=e instanceof Error?e.message:String(e);return fn.error("[run-history] list_runs exception",{error:t}),{content:[{type:"text",text:`Error: ${t}`}],isError:!0}}}),Ee("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:te.string().min(1).describe("The run ID to view (required)")},async({runId:r})=>{const n="string"==typeof r?r:String(r);fn.info("[run-history] view_run called",{runId:n});try{const r=await Bt({auth:e,client:Zt(),headers:xn(t),path:{runId:n},query:{detail:"full"}});if(r.error||!r.data){const e=r.response?404===r.response.status?`Run "${n}" not found`:`API error: ${r.response.status}`:`API error: ${String(r.error)}`;return fn.error("[run-history] view_run failed",{error:e,runId:n}),{content:[{type:"text",text:`Error: ${e}`}],isError:!0}}return fn.info("[run-history] view_run success",{runId:n}),{content:[{type:"text",text:JSON.stringify(r.data)}]}}catch(e){const t=e instanceof Error?e.message:String(e);return fn.error("[run-history] view_run exception",{error:t,runId:n}),{content:[{type:"text",text:`Error: ${t}`}],isError:!0}}})]})}}),Tl=Fe({"../proxy/src/index.ts"(){kn(),ll=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]"),ul=(e,t)=>({message:ll(e),status:t?.status,statusText:t?.statusText})}}),El=Fe({"src/agent/constants.ts"(){dl=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"])}}),Sl=Fe({"src/agent/prompt-utils.ts"(){pl="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."}}),xl=Fe({"src/agent/subagents.ts"(){kn(),Dn(),Bn(),Vn(),fl=async({authHeader:e,mode:t,maxTurnsOverride:r})=>{const n=Zt();fn.debug("Requesting subagent definitions from API",{mode:t,maxTurnsOverride:r});const s=await Et({client:n,auth:e,body:{mode:t,maxTurnsOverride:r}});if(401===s.response.status)throw fn.warn("Subagent definitions fetch failed: unauthorized (401)"),await gr(),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 fn.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 fn.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:o}=s.data;return fn.debug("Subagent definitions received",{count:Object.keys(o).length}),o}}});function Al(e){return H(n.join(e,gl))}var Cl,Rl,Pl,kl,Ul,Ll,Dl,$l,Ol,Nl,Bl=Fe({"src/agent/stably-plugin.ts"(){hl=n.dirname(C(import.meta.url)),gl=n.join(".claude-plugin","plugin.json"),ml=[n.join("packages","agent-plugin","stably-plugin-cli"),n.join("agent-plugin","stably-plugin-cli")]}}),jl=Fe({"src/config/stably-yaml.ts"(){Aa(),Vn(),Nn(),({zStablyYaml:Cl}=function(e){const t=e.object({cron:e.string(),stablyTestArgs:e.string().optional(),timezone:e.string().optional(),command:e.string().optional(),autofix:e.boolean().optional()}),r=e.object({maxTurnsPerIssue:e.number().int().positive().optional(),maxParallelWorkers:e.number().int().positive().optional(),rules:e.string().optional(),skipAfterConsecutiveUnfixed:e.number().int().positive().optional(),maxBudgetUsd:e.number().positive().optional()}),n=e.object({fix:r.optional()}),s=e.object({setupScript:e.string().optional()});return{zStablyYaml:e.object({schedules:e.record(e.string(),t).optional(),agent:n.optional(),cloud:s.optional()}),zAgentConfig:n,zAgentFixConfig:r,zScheduleEntry:t,zCloudConfig:s}}(x)),Rl=async e=>{try{const t=await ir(e,"stably.yaml");if(!t)return void fn.debug("No stably.yaml found");const r=await m(t,"utf-8");if(!r.trim())return;const n=Se(r),s=Cl.parse(n.toJS()),o=s.agent?.fix?.maxTurnsPerIssue,i=s.agent?.fix?.maxParallelWorkers,a=!!s.agent?.fix?.rules;return fn.debug(`Loaded stably.yaml: maxTurnsPerIssue=${o??"default"}, maxParallelWorkers=${i??"default"}, hasRules=${a}`,{path:t,config:s.agent}),s}catch(e){return void fn.warn("Failed to parse stably.yaml",{error:e})}}}}),Ml=Fe({"src/config/read-markdown-rules.ts"(){Vn(),Nn(),Pl=async(e,t)=>{try{const r=await ir(e,t);if(!r)return void fn.debug(`No ${t} found`);const n=await m(r,"utf-8");if(!n.trim())return;return n.length>1e4?(fn.warn(`${t} exceeds max length (${n.length} > 10000), truncating`,{path:r}),{content:n.slice(0,1e4),path:r}):(fn.debug(`Loaded ${t} rules`,{path:r,contentLength:n.length}),{content:n,path:r})}catch(e){return void fn.warn(`Failed to read ${t}`,{error:e})}}}}),Fl=Fe({"src/config/stably-create-rules.ts"(){Ml(),kl=async e=>{const t=await Pl(e,"STABLY-CREATE.md");return t?.content}}}),Hl=Fe({"src/config/stably-md-rules.ts"(){Ml(),Ul=e=>Pl(e,"STABLY.md")}}),Gl=Fe({"src/agent/hooks/security-hooks.ts"(){zs()}});function Yl(e,t){return t?`${e}-${t}`:e}function Wl(e){if(e&&"object"==typeof e&&"agent_id"in e){const t=e.agent_id;return"string"==typeof t?t:void 0}}var Vl,zl,Kl,ql,Jl=Fe({"src/agent/hooks/playwright-cli-hook.ts"(){Vn(),Ll=/\bstably-browser\b/,Dl=/\bstably-browser\s+run-test\b/,$l=/\$\{process\.env\.([a-zA-Z_][a-zA-Z0-9_]*)\}/g,Ol=e=>/^[A-Za-z0-9_./:@=-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`,Nl=".stably-browser"}});function Xl(e){return e.replace(zl,"browser_tool").replace(Kl,"verification-artifact").replace(ql,"browser automation")}function Ql(e){return{...e,steps:e.steps.map(e=>Xl(e)),reason:e.reason?Xl(e.reason):null,evidence:e.evidence.map(e=>Xl(e))}}function Zl(e){const t=e.matchAll(/```verdict\s*\r?\n([\s\S]*?)\r?\n```/g);let r=null;for(const e of t)try{const t=JSON.parse(e[1]??"");r=Vl.parse(t)}catch{}return r}var eu,tu,ru,nu,su,ou,iu,au,cu,lu,uu,du,pu,fu,hu,gu,mu,yu=Fe({"src/agent/verify-verdict.ts"(){Vl=x.object({verdict:x.enum(["PASS","FAIL","INCONCLUSIVE"]),steps:x.array(x.string()).min(1),reason:x.string().nullable(),evidence:x.array(x.string())}).superRefine((e,t)=>{"PASS"===e.verdict||e.reason&&0!==e.reason.trim().length||t.addIssue({code:x.ZodIssueCode.custom,path:["reason"],message:"reason is required for FAIL and INCONCLUSIVE verdicts"})}),zl=/\bmcp__playwright-mcp__[a-z0-9_]+\b/gi,Kl=/\.playwright-mcp(?:\/[^\s"'`)\]]*)?/gi,ql=/\bplaywright[\s_-]?mcp\b/gi}});async function bu(e,t){return!!e&&(!!e.hasQueuedMessages()||new Promise(r=>{const n=setTimeout(()=>{clearInterval(s),r(!1)},t),s=setInterval(()=>{e.hasQueuedMessages()&&(clearTimeout(n),clearInterval(s),r(!0))},200)}))}async function wu(e){return new Promise(t=>{const r=new xe.Socket;let n=!1;const s=e=>{n||(n=!0,r.destroy(),t(e))};r.setTimeout(700),r.once("connect",()=>s(!0)),r.once("timeout",()=>s(!1)),r.once("error",()=>s(!1)),r.connect(e,"127.0.0.1")})}var vu,Iu=Fe({"src/agent/agent.tsx"(){jt(),Kn(),qn(),Qn(),gs(),hs(),ms(),ys(),bs(),Ps(),Vn(),ao(),co(),Eo(),So(),vo(),Un(),va(),Ia(),_a(),Sa(),Fc(),Hc(),yl(),wl(),Il(),_l(),Tl(),Ln(),El(),Dn(),Sl(),xl(),Bl(),jl(),Fl(),Hl(),Gl(),Jl(),yu(),eu=e=>`[38;5;208m${e}[39m`,tu=["Bash","Read","Write","Edit","Glob","Grep","Task","Skill"],ru=["Task","Skill"],nu=["Bash","Read","Write","Edit","Glob","Grep","mcp__session-control"],su=e=>{if("EPIPE"!==e.code)throw e},ou="__main__",iu=[3e3,5173,4173,8080,4200,8e3],au=/\b(TEST_EMAIL|TEST_PASSWORD|auth|authentication|credentials|login|log in|sign in)\b/i,cu=/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/i,lu=/playwright[\s_-]?mcp/i,uu=e=>"mcp__auto-heal-report__generate-report"===e,du=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),pu=e=>/^[A-Za-z0-9_./:@-]+$/.test(e)?e:`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`,fu=e=>!!e&&au.test(e),hu=({envEmail:e,envPassword:t,promptIncludesEmail:r,stablyMdContent:n})=>!Boolean(e?.trim()&&t?.trim())&&!r&&!fu(n),gu=async(e,t,r)=>{const n=r?"[Y/n]":"[y/N]",s=(await e.question(`${N.cyan("?")} ${t} ${N.gray(n)} `)).trim().toLowerCase();return s?"y"===s||"yes"===s:r},mu=async e=>{if("single"===e.mode){const t=Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt;fn.initSession(t||"create-from-diff")}else if("verify"===e.mode){const t=Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt;fn.initSession(t||"verify")}else"fix"===e.mode&&fn.initSession(`fix-${e.runId}`);fn.info("Agent session starting",{mode:e.mode}),process.stdout.on("error",su),process.stderr.on("error",su);const a=e=>{if("EPIPE"!==e.code)throw e};process.on("uncaughtException",a),fn.debug("Checking authentication");const c=await In({autoLogin:"chat"===e.mode||"init"===e.mode}),l=En(c);fn.debug("Authentication resolved",{authType:c.type});const u="oauth"===c.type?c.auth.context.orgId:void 0,d=n.resolve(process.cwd()),p="fix"!==e.mode,f=n.join(d,".env"),g=p&&F.existsSync(f)&&F.statSync(f).isFile(),y=g?t(F.readFileSync(f,"utf8")):{};fn.debug("Environment file",{path:f,exists:g,variableCount:Object.keys(y).length});const b="chat"!==e.mode&&"init"!==e.mode,w="chat"===e.mode,v="chat"===e.mode||"init"===e.mode,I="single"===e.mode,_="verify"===e.mode,T=I||_;let E,S=new oo;"init"===e.mode&&(E=e.initPreferences??await async function(){if(!process.stdin.isTTY||!process.stdout.isTTY)return{googleAuth:!0,emailPackage:!1};const e=ee({input:process.stdin,output:process.stdout});try{return{googleAuth:await gu(e,"Include Google Auth test helper guidance? (recommended)",!0),emailPackage:await gu(e,"Install @stablyai/email for inbox testing?",!1)}}finally{e.close()}}());const x="chat"===e.mode?e.getHelpText:void 0,A="verify"===e.mode?(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt).trim():"";let R="verify"===e.mode?e.url?.trim()||function(e){const t=Array.isArray(e)?e.join(" "):e,r=e=>e.replace(/[),.;!?]+$/,""),n=e=>{const t=r(e);try{return new URL(t).toString()}catch{return}},s=t.match(/https?:\/\/[^\s"'`<>]+/i);if(s)return n(s[0]);const o=t.match(/(?<!@)\b(?:localhost|(?:\d{1,3}\.){3}\d{1,3}|(?:[a-z0-9-]+\.)+[a-z]{2,63})(?::\d{2,5})?(?:\/[^\s"'`<>]*)?/i);if(!o)return;const i=r(o[0]),a=i.split("/")[0]??i,c=a.split(":")[0]?.toLowerCase()??"",l=c.includes(".")?c.split(".").at(-1)??"":"";return new Set(["ts","tsx","js","jsx","md","json","yaml","yml","txt","css"]).has(l)?void 0:n(`${"localhost"===c||"127.0.0.1"===c?"http":"https"}://${i}`)}(e.prompt):void 0;if("verify"===e.mode&&!e.url&&R&&fn.info("[verify] Using URL extracted from prompt",{url:R}),"verify"!==e.mode||R||(R=await async function(){for(const e of iu)if(await wu(e))return`http://localhost:${e}`}(),R?fn.info("[verify] Detected local application URL",{url:R}):fn.info("[verify] No common localhost dev server detected")),"verify"===e.mode&&!1!==e.interactive){const e=await async function({envFilePath:e,envFromFile:t,initialUrl:r,verifyPromptText:s,workingDir:o}){if(!process.stdin.isTTY||!process.stdout.isTTY)return{resolvedUrl:r};const i=n.join(o,"STABLY.md"),a=F.existsSync(i),c=a?await F.promises.readFile(i,"utf8").catch(()=>{}):void 0;let l=r?.trim()||void 0;const u=process.env.TEST_EMAIL??t.TEST_EMAIL,d=process.env.TEST_PASSWORD??t.TEST_PASSWORD,p=cu.test(s),f=!l,h=hu({envEmail:u,envPassword:d,promptIncludesEmail:p,stablyMdContent:c}),g=!a;if(!f&&!h&&!g)return{resolvedUrl:l};const m=ee({input:process.stdin,output:process.stdout}),y=async(r,n)=>{const s=F.existsSync(e)?await F.promises.readFile(e,"utf8"):"",o=new RegExp(`^${du(r)}=.*$`,"m"),i=`${r}=${pu(n)}`,a=o.test(s)?s.replace(o,i):`${s}${s&&!s.endsWith("\n")?"\n":""}${i}\n`;await F.promises.writeFile(e,a,"utf8"),t[r]=n};try{if(f){const e=(await m.question("Starting URL (optional, Enter to auto-infer): ")).trim();e&&(l=e)}if(h&&await gu(m,"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 m.question("TEST_EMAIL: ")).trim(),t=(await m.question("TEST_PASSWORD: ")).trim();e&&t&&(await y("TEST_EMAIL",e),await y("TEST_PASSWORD",t),process.env.TEST_EMAIL||(process.env.TEST_EMAIL=e),process.env.TEST_PASSWORD||(process.env.TEST_PASSWORD=t))}if(g&&await gu(m,"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 F.promises.writeFile(i,e,"utf8");const t=(await m.question("Special verify instruction to append to STABLY.md (optional): ")).trim();if(t){const e=await F.promises.readFile(i,"utf8"),r=/(^|\n)## Special Instructions\s*$/m.test(e)?`${e}${e.endsWith("\n")?"":"\n"}- ${t}\n`:`${e}${e.endsWith("\n")?"":"\n"}\n## Special Instructions\n- ${t}\n`;await F.promises.writeFile(i,r,"utf8")}}return{resolvedUrl:l}}finally{m.close()}}({envFilePath:f,envFromFile:y,initialUrl:R,verifyPromptText:A,workingDir:d});R=e.resolvedUrl?.trim()||R}"verify"!==e.mode||R||fn.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 P={log:[],promptDisplay:Ie(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 k,U,L,D,$=b,O=!1,B=!1,j=0,Y=0,W=!1;const z=[];let K,q,J=[],X=!1,Q=!1,Z=0;const te=new Map,re=[],ne=e=>{re.push(e)},se=new Map;let oe=null,ie=!1,ce=!1;const le=Date.now();let ue,de="fix"===e.mode?{suiteId:e.runId,phase:"initializing",totalTests:null,fixedTests:0,failedTests:0,currentTestDescription:null,lastTestDescription:null,startedAt:le,endedAt:null,isError:!1,updatedAt:le,recentActivity:[],workers:[{id:ou,testDescription:"Orchestrator",workerType:"main",status:"running",summary:null,startedAt:le,endedAt:null,activity:[]}]}:null;const pe=new Set,fe=(e,t)=>{if(!de)return;const r=de.workers.map(r=>{if(r.id!==e)return r;const n=[...r.activity,{...t,timestamp:Date.now()}].slice(-15);return{...r,activity:n}});me({workers:r})},he=e=>{if(!de)return;const t=[...de.recentActivity,{...e,timestamp:Date.now()}].slice(-10);me({recentActivity:t})},ge=e=>(de?.workers??[]).map(t=>t.id===ou?{...t,status:e?"failed":"succeeded",endedAt:t.endedAt??Date.now()}:"running"===t.status?{...t,status:"failed",endedAt:Date.now()}:t),me=e=>{de&&!ue?.isClosed&&(de={...de,...e,updatedAt:Date.now()},ue?.sendProgress(de))},ye=async t=>{if("fix"===e.mode){if("STARTED"===t){if(ie)return;ie=!0}else{if(ce)return;ce=!0}try{await is({authHeader:l,orgId:u,runId:e.runId,status:t})}catch{}}},be=Date.now();let we,ve=null;const Te=e=>{ve&&!we?.isClosed&&(ve={...ve,...e,updatedAt:Date.now()},we?.sendProgress(ve))},Ee=e=>{if(!ve)return;const t=[...ve.recentActivity,{...e,timestamp:Date.now()}].slice(-10);Te({recentActivity:t})};let Se;const xe=(e.mode,!0);fn.info("[session] Checking session creation",{mode:e.mode,shouldCreateSession:xe});try{fn.info("[session] Creating progress session",{mode:e.mode,projectId:Tn(c)});const t=await async function({agentMode:e,authHeader:t,orgId:r,projectId:n,runId:s,fetchImpl:o=fetch,apiUrl:i=Gt}){const a=yo[e],c=new URL("/internal/v1/cli/progress",i).toString(),l={Authorization:t,"Content-Type":"application/json"};r&&(l["x-stably-org-id"]=r);const u=await o(c,{method:"POST",headers:l,body:JSON.stringify({mode:a,projectId:n,agentId:h.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:Tn(c),..."fix"===e.mode?{runId:e.runId}:{}}),{sessionId:r,sessionMode:n}=t;if(Se=r,T){const t="single"===e.mode||"verify"===e.mode?Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt:null,n=lo(d);ve={sessionId:r,phase:"initializing",startedAt:be,endedAt:null,isError:!1,updatedAt:be,currentActivity:null,filesCreated:[],traceProofs:[],recentActivity:[],prompt:t||null,environment:{gitBranch:n?.branch??null,workingDirectory:d,nodeVersion:process.version,cliVersion:Ht}},we=new cs({authHeader:l,orgId:u,sessionId:r,onUserMessage:e=>{S&&(fn.info("[ws] Injecting web UI message into agent",{contentLength:e.length}),Ee({type:"user_message",summary:e}),De({text:`[Web] ${e}`}),S.pushText(`[Message from web UI user]: ${e}`),$||($=!0,Ye({status:"running"})))}}),we.start(),Te({phase:"initializing"})}fn.info(`[${n}] Progress session created`,{sessionId:r})}catch(e){const t=e instanceof Error?e.message:String(e);fn.warn(`[progress] Session creation failed (non-fatal): ${t}`)}const Ae={current:e=>{}},Ce={current:async()=>{}};let Re;const{addSubagentActivity:Pe,addSubagentStart:ke,addTool:Ue,appendText:Le,appendUserMessage:De,cleanup:$e,setExiting:Oe,setRunningLabel:Be,setStatus:je,setSubagentStatus:Fe,updateFixProgress:He}=await Wo(P,"init"===e.mode?{onExit:()=>Ce.current(),onSend:e=>Ae.current(e),showSpinnerImmediately:!0,isInitMode:!0}:"chat"===e.mode?{onExit:()=>Ce.current(),onSend:e=>Ae.current(e)}:"fix"===e.mode?{onExit:()=>Ce.current(),isFixMode:!0}:{onExit:()=>Ce.current()});let Ge=P.status;const Ye=({error:e,result:t,status:r})=>{Ge=r,je({error:e,result:t,status:r})};let We;_&&(Le({text:"Starting verification...\n"}),Le(R?{text:`Target URL: ${R}\n`}:{text:"Target URL: auto-detect (agent may infer from project config)\n"}),Be({label:"Calibrating verification flow..."})),Ae.current=e=>{const t=e.trim();if(w&&!fn.getLogFilePath()&&fn.initSession(t||"chat"),fn.debug("User message",{text:t}),"/help"===t){$&&S&&(O=!0,k?.interrupt?.(),S.allowNextTurn(),$=!1),"running"===Ge&&Ye({status:"success"}),De({text:e});const t=x?.();return void Le({text:t??"Help is not available in this session."})}const r=L||B&&$;if(w&&(j+=1,D=void 0,r||(W=!1,Be({label:void 0}))),S){if(r)return Ye({status:"running"}),De({text:e}),void z.push(e);if(!B||$||L||(B=!1),$)return Ye({status:"running"}),De({text:e}),S.pushText(e),void(Y+=1);Ye({status:"running"}),De({text:e}),ne({role:"user",content:e,timestamp:(new Date).toISOString()}),S.pushText(e),$=!0}};let Ve="",ze="";const Ke=[],qe=[],Je=[];let Xe;const Qe=await Rl(d),Ze=Qe?.agent?.fix?.skipAfterConsecutiveUnfixed,et=await(async()=>{if("single"===e.mode){const r=await async function(e,t){const r=s(e);if(t){const e=s(r,t);return Po(e,"output-flag"),{path:e,source:"output-flag"}}const n=xo(r);if(n){const e=await async function(e){try{const t=(await m(e,"utf-8")).match(/testDir:\s*['"]([^'"]+)['"]/);return t?.[1]}catch{return}}(n);if(e){const t=s(o(n),e);if(Ro(t))return Po(t,"playwright.config.ts"),{path:t,source:"playwright.config.ts"}}}for(const e of Ao){const t=i(r,e);if(Ro(t))return Po(t,"auto-detected"),{path:t,source:"auto-detected"}}return Po(r,"cwd-fallback"),{path:r,source:"cwd-fallback"}}(d,e.outputDir);return Xe=r.path,t=e.prompt,`${(Array.isArray(t)?t.join(" "):t).trim()||pl}\n\n[Output directory: ${Xe}]`}var t;if("verify"===e.mode)return function(e,t){const r=(Array.isArray(e)?e.join(" "):e).trim()||"Verify the application behavior.",n=t?.trim();return n?`Starting URL: ${n}\nURL policy: treat this as the source of truth and do not switch domains unless the user explicitly asks.\n\nVerification prompt: ${r}`:r}(e.prompt,R);if("fix"===e.mode)try{fn.info("[fix] Fetching autoheal context",{runId:e.runId,skipAfterConsecutiveUnfixed:Ze});const t=Date.now(),{context:r,autohealReportUrl:n,skippedTests:s}=await Cn({authHeader:l,orgId:u,runId:e.runId,skipAfterConsecutiveUnfixed:Ze});if(fn.info("[fix] Autoheal context fetched",{runId:e.runId,durationMs:Date.now()-t,contextLength:r.length,skippedTestCount:s.length}),We=n,s.length>0){fn.info(`[fix] Skipping ${s.length} test(s) that failed to be fixed ${Ze}+ consecutive times`);for(const e of s)fn.info(`[fix] Skipped: ${e.testIdentifier} — ${e.testTitle} (unfixed ${e.consecutiveUnfixedCount}x)`)}r.includes("No failing tests to fix (all were skipped).")&&(fn.info("[fix] All failing tests were skipped — nothing to fix"),Ye({status:"success",result:`All failing tests skipped (unfixed ${Ze}+ consecutive times). Nothing to fix.`}),await $e(),process.exit(0)),ue||(fn.info("[fix] Creating WebSocket progress reporter"),ue=new as({authHeader:l,orgId:u,runId:e.runId,onUserMessage:e=>{if(fn.info("[ws] Injecting web UI message into fix agent",{contentLength:e.length}),fe(ou,{type:"user_message",summary:e}),he({type:"user_message",summary:e}),De({text:`[Web] ${e}`}),!$)return S.pushText(`[Message from web UI user]: ${e}`),$=!0,void S.allowNextTurn();X||Date.now()-Z<2e3?S.pushText(`[Message from web UI user]: ${e}`):(J.push(e),K&&clearTimeout(K),K=setTimeout(()=>{K=void 0;const e=[...J];J=[],Z=Date.now(),ir(e)},500))}}),ue.start(),me({phase:"initializing"})),ye("STARTED");let o=r;return e.triageOnly&&(o+=`\n\n## TRIAGE-ONLY MODE\n\nYou are running in TRIAGE-ONLY mode. Your workflow:\n1. Run the triage subagent with the failure context above\n2. Write the triage output as JSON to .stably/triage-output.json (create the .stably directory if needed)\n3. The JSON must conform to this schema: { schemaVersion: 1, testSuiteRunId: "${e.runId}", issues: [...], testsToSkipFixing: [...] }\n4. Do NOT launch any fix-workers. Do NOT generate a report. Exit after writing triage output.\n`),e.issues&&(o+=`\n\n## PRE-ASSIGNED ISSUES\n\nYou are running as a parallel fix agent in the SFN workflow.\nPre-assigned issue IDs: ${e.issues.join(", ")}\nThese issue IDs correspond to groups of test failures already triaged. Parse the failure context above to find the test details for your assigned issues.\n`),e.partialReportId&&(o+=`\n\n## PARTIAL REPORT MODE\n\nYou are running as parallel fix agent "${e.partialReportId}". When generating the report, it will be saved as a partial report for later merging.\n`),o}catch(e){const t=e instanceof Error?e.message:"Failed to fetch autoheal context.";fn.error("[fix] Failed to fetch autoheal context",{error:t}),Ye({error:t,status:"error"}),await $e(),process.exit(1)}if("init"===e.mode){const e=E??{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""})(),tt=await async function(e){const t=n.resolve(e),r=n.join(t,"tests"),s=n.join(r,"helpers"),o=n.join(r,"assets"),i=function(e){const t=n.resolve(e);if(H(t))for(const e of uo){const r=n.join(t,`playwright.config${e}`);if(H(r))return r}}(t)??n.join(t,"playwright.config.ts"),a=n.basename(i),c=n.join(r,"seed.spec.ts"),[l,u,d,p,f,h]=await Promise.all([go({defaultContent:"Unable to read directory",dirName:"working directory",dirPath:t}),go({defaultContent:"Unable to read directory",dirName:"tests directory",dirPath:r}),go({defaultContent:"Directory does not exist yet",dirName:"helpers directory",dirPath:s}),go({defaultContent:"Directory does not exist yet",dirName:"assets directory",dirPath:o}),ho({defaultContent:"File does not exist or could not be read",fileName:a,filePath:i}),ho({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),rt="fix"===e.mode?Qe?.agent?.fix?.maxTurnsPerIssue:void 0,nt=Qe?.agent?.fix?.maxParallelWorkers??3,st="fix"===e.mode?Qe?.agent?.fix?.rules:void 0,ot=Qe?.agent?.fix?.maxBudgetUsd??50,it="verify"===e.mode?e.maxBudgetUsd??5:void 0,at="fix"===e.mode?ot:_?it:void 0,ct="init"!==e.mode,lt="single"===e.mode?await kl(d):void 0,ut=await Ul(d),dt=ut?.content;_&&(Be({label:"Assembling verification context..."}),Le({text:"Assembling workspace context...\n"})),fn.info("[fix] Fetching system prompt and subagent definitions",{mode:e.mode,maxTurnsOverride:rt,maxBudgetUsd:at,hasCustomRules:!!st,hasCreateRules:!!lt,hasStablyMd:!!dt,stablyMdPath:ut?.path}),ut&&fn.info(`STABLY.md loaded (${ut.content.length} chars)`,{path:ut.path});const pt=await Sn(),ft=pt?Object.keys(pt.variables):[],ht=[...new Set([...Object.keys(y),...ft])],gt=Date.now(),[{systemPrompt:mt,prContext:yt},bt]=await Promise.all([mo({allowedEnvVars:ht,mode:e.mode,workspaceInfo:tt,authHeader:l,customHeader:"single"===e.mode?e.customHeader:void 0,maxParallelWorkers:nt,preAssignedIssues:!("fix"!==e.mode||!("issues"in e)||!e.issues)||void 0}),ct?fl({authHeader:l,mode:e.mode,maxTurnsOverride:rt}):Promise.resolve({})]);fn.info("[fix] System prompt and subagents fetched",{durationMs:Date.now()-gt,systemPromptSize:mt.length,subagentCount:Object.keys(bt).length,maxTurnsOverride:rt??"default",hasPrContext:!!yt});const vt={...y,...process.env},It={};for(const[e,t]of Object.entries(vt))dl.has(e)||void 0===t||(It[e]=t);const _t=!0;fn.debug("AI proxy configuration",{useStablyAiProxy:_t,wantsBypassProxy:!1,wantsUseOllama:!1}),fn.info("[fix] Acquiring AI proxy key",{useStablyAiProxy:_t});const Tt=Date.now(),Et=await async function({auth:e,client:t,source:r,metadata:n,duration:s}){try{const o=await wt({auth:e,client:t,body:{source:r,metadata:n??{},duration:s}}),i=o.response;if(o.error){const e="object"==typeof o.error&&"error"in o.error?o.error.error:"Unknown error";return{error:ul(e,i)}}return o.data?{key:o.data.key}:{error:ul("No data in response",i)}}catch(e){const t=e instanceof Error?e.message:"Unknown error";return{error:ul(t)}}}({auth:l,client:Zt(),source:"cli"}),St=Et?.key;if(fn.info("[fix] AI proxy key acquired",{durationMs:Date.now()-Tt,success:!!St,hasError:!!Et?.error}),!St){const e=Et?.error?.message?`Unable to make AI calls: ${Et.error.message}`:"Unable to make AI calls. Check if you are authenticated.";fn.warn("Failed to get proxy API key",{error:Et?.error?.message}),Ye({error:e,status:"error"}),await $e(),fn.flush(),fn.printLogFileInfo(),process.exit(1)}fn.debug("Proxy API key acquired",{success:!!St});const xt="init"===e.mode,At="fix"===e.mode,Ct=xt?void 0:function(e){let t;!function(e){const t=i(e,".gitignore");try{if(H(t)){const e=G(t,"utf-8"),r=e.split("\n").map(e=>e.trim());if(r.includes(Nl)||r.includes(`/${Nl}`))return;const n=e.length>0&&!e.endsWith("\n");V(t,`${n?"\n":""}${Nl}\n`)}}catch{}}(process.cwd());const r=new Set;let n;const s=()=>{var t;return n||(n="auto"!==(t=e.sessionName)?t:`stably-${process.pid}`),n};return{hook:async n=>{const a=n&&"object"==typeof n&&"tool_input"in n&&n.tool_input&&"object"==typeof n.tool_input&&"command"in n.tool_input&&"string"==typeof n.tool_input.command?n.tool_input.command:"";if(!Ll.test(a))return{decision:"approve"};const c=/\bstably-browser\s+close\b/.test(a),l=/\bstably-browser\s+(?!close\b)\w/.test(a);if(c){if(!l&&0===r.size)return{decision:"approve"};const e=Wl(n),t=Yl(s(),e);r.delete(t)}if(!t)try{t=await async function(){const e=i(o(C(import.meta.url)),"stably-browser.js");if(H(e))return e;try{return Me.resolve("@stablyai-internal/playwright-cli/playwright-cli.js")}catch{}return new Promise((e,t)=>{ae("which",["stably-browser"],(r,n)=>{!r&&n.trim()?e(n.trim()):t(new Error("stably-browser not found. Ensure @stablyai-internal/playwright-cli is installed or stably-browser is on PATH."))})})}(),fn.info("[stably-browser-hook] Resolved binary",{path:t})}catch(e){const t=e instanceof Error?e.message:String(e);return{decision:"block",reason:t,systemMessage:`stably-browser binary not found: ${t}`}}const u=Wl(n),d=Yl(s(),u),p=/\bstably-browser\s+open\b/.test(a);if((!c||l)&&!r.has(d))if(p)r.add(d);else{r.add(d),fn.info("[stably-browser-hook] First browser command, starting daemon...",{sessionName:d,agentId:u});const n=await async function(e,t,r){const n=["open",`-s=${t}`];return r&&n.push("--headed"),n.push("--browser=chrome"),fn.info("[stably-browser-hook] Starting daemon",{bin:e,args:n}),new Promise(t=>{ae(process.execPath,[e,...n],{timeout:3e4},(e,r,n)=>{if(e)return fn.error("[stably-browser-hook] Failed to start daemon",{error:e.message,stderr:n}),void t(!1);fn.info("[stably-browser-hook] Daemon started",{stdout:r.trim()}),t(!0)})})}(t,d,e.headed);if(!n)return r.delete(d),{decision:"block",reason:"Failed to start stably-browser daemon. Check logs for details.",systemMessage:"stably-browser daemon failed to start"}}const f=`${process.execPath} ${t}`;let h=a.replace(/\b(?:npx\s+)?stably-browser\b/g,f);const g=[];h.includes("-s=")||h.includes("--session=")||g.push(`-s=${d}`),e.headed&&!h.includes("--headed")&&g.push("--headed"),g.length>0&&(h=h.replaceAll(f,`${f} ${g.join(" ")}`)),e.envVars&&(h=h.replace($l,(t,r)=>{const n=e.envVars[r];return null!=n?n:t}));const m=[];if(Dl.test(a)&&e.envVars)for(const[t,r]of Object.entries(e.envVars))m.push(`${t}=${Ol(r)}`);return m.length>0&&(h=`${m.join(" ")} ${h}`),fn.debug("[stably-browser-hook] Rewritten command",{original:a.slice(0,100),sessionName:d,agentId:u,envVarCount:m.length}),{decision:"approve",hookSpecificOutput:{hookEventName:"PreToolUse",updatedInput:{command:h}}}},cleanup:async()=>{t&&r.size>0&&(await Promise.all(Array.from(r).map(e=>{return r=t,n=e,new Promise(e=>{ae(process.execPath,[r,"close",`-s=${n}`],{timeout:1e4},t=>{t&&fn.warn("[stably-browser-hook] Failed to stop daemon",{error:t.message,sessionName:n}),e()})});var r,n})),r.clear())}}}({sessionName:process.env.STABLY_PLAYWRIGHT_SESSION??(At?"auto":"default"),headed:!At&&!process.env.CI,envVars:{...y,...pt?.variables}}),Rt=At?Ne.createLocal({workingDir:d}):void 0;Rt&&await Rt.captureSnapshot();const Pt=()=>{xt&&function({workingDir:e,options:t={}}){const n=function(e){const t=function(e){let t=r.resolve(e);for(;;){if(M.existsSync(r.join(t,".git")))return t;const n=r.dirname(t);if(n===t)return r.resolve(e);t=n}}(e),n=function(e,t){for(const r of Xc(e,t))if(Wc(r))return r}(e,t),s=Kc(Vc(e,/playwright\.config\.(ts|js|mts|mjs|cjs)$/).map(e=>r.dirname(e))),o=function(e){const t=new Set;for(const n of e)t.add(zc(r.dirname(n)));return Kc(Array.from(t))}(Vc(e,/\.(spec|test)\.(ts|js)$/)),i=s.length>0?s:o,a=n??(1===i.length?i[0]:void 0)??e,c=Jc(a,t);if(!c)return{repoRoot:t,projectRoot:a,targetDir:void 0};if(!n&&c===r.resolve(e)&&function(e,t,r){const n=new Set;for(const s of e){const e=Jc(s,r);e&&e!==t&&n.add(e)}return n.size>1}(i,c,t))return{repoRoot:t,projectRoot:a,targetDir:void 0};const l=Yc(c);if(!l||!("workspaces"in l.contents))return{repoRoot:t,projectRoot:a,targetDir:c};const u=function(e,t){let n=r.resolve(e);const s=r.resolve(t);for(;n!==s;){if(M.existsSync(r.join(n,"package.json")))return n;const e=r.dirname(n);if(e===n)break;n=e}}(a,c);return{repoRoot:t,projectRoot:a,targetDir:u??c}}(e);if(n.targetDir){try{!function(e){const t=r.join(e,"package.json");if(!M.existsSync(t))return;const n=JSON.parse(M.readFileSync(t,"utf-8"));if({...n.dependencies,...n.devDependencies}.stably)fn.debug("stably package already present in dependencies");else{fn.info("stably package missing from devDependencies, installing...");try{Gc({workingDir:e,packageManager:Zc(e),packageSpec:"stably",targetSection:"devDependencies"}),fn.info("stably package installed successfully")}catch(e){fn.warn("Failed to install stably package",{error:String(e)})}}}(n.targetDir)}catch(e){fn.warn("Post-init: ensureStablyDependency failed",{error:String(e)})}try{!function(e){const t=Yc(e);if(!t)return;const r=t.contents.devDependencies?.playwright??t.contents.dependencies?.playwright;if(r)if(Qc(r)!==Is)try{Gc({workingDir:e,packageManager:Zc(e),packageSpec:`playwright@${Is}`,targetSection:t.contents.devDependencies?.playwright?"devDependencies":"dependencies"}),fn.info("standalone playwright version aligned successfully",{version:Is})}catch(e){fn.warn("Failed to align standalone playwright version",{error:String(e)})}else fn.debug("standalone playwright already at supported version",{version:Is});else fn.debug("standalone playwright package not present")}(n.targetDir)}catch(e){fn.warn("Post-init: alignStandalonePlaywrightVersion failed",{error:String(e)})}try{!function(e){const t=Yc(e);if(t)if(Qc(t.contents.devDependencies?.["@playwright/test"]??t.contents.dependencies?.["@playwright/test"])!==Is)try{fn.info(`Updating @playwright/test to supported version ${Is}...`),Gc({workingDir:e,packageManager:Zc(e),packageSpec:`@playwright/test@${Is}`,targetSection:t.contents.dependencies?.["@playwright/test"]?"dependencies":"devDependencies"}),fn.info("@playwright/test updated successfully")}catch(e){fn.warn("Failed to update @playwright/test",{error:String(e)})}else fn.debug("@playwright/test already at supported version",{version:Is});else fn.debug("No package.json found, skipping @playwright/test update")}(n.targetDir)}catch(e){fn.warn("Post-init: updatePlaywrightTest failed",{error:String(e)})}try{!function(e,t,n){const s=[];n.googleAuth&&s.push("Google Auth methods"),n.emailPackage&&s.push("@stablyai/email Inbox methods for email verification flows");const o=`Use Stably CLI for Playwright test runs (better reporting, auto-fix); import from @stablyai/playwright-test for agent.act(), aiAssert, page.extract(), page.getLocatorsByAI()${s.length>0?`; also use ${s.join(" and ")}`:""}.`,i=function(e,t){const n=["CLAUDE.md","AGENTS.md","AGENT.md","agent.md"];for(const s of Xc(e,t)){let t;for(const o of n){const n=r.join(s,o);if(!M.existsSync(n))continue;t??=n;const i=M.readFileSync(n,"utf-8");if(/Stably CLI/i.test(i)&&i.includes("@stablyai/playwright-test"))return void fn.debug("Agent guidance already present",{file:r.relative(e,n)||o});if(qc(i))return n}if(t)return t}return r.join(e,"AGENTS.md")}(e,t);if(i){fn.info("Appending Stably guidance",{file:r.basename(i)});try{const e=M.existsSync(i)?M.readFileSync(i,"utf-8"):"",t=e.length>0&&!e.endsWith("\n")?"\n\n":e.length>0?"\n":"";M.writeFileSync(i,`${e}${t}${o}\n`,"utf-8"),fn.info("Agent guidance appended successfully")}catch(e){fn.warn("Failed to update agent guidance file",{error:String(e)})}}}(n.targetDir,n.repoRoot,t)}catch(e){fn.warn("Post-init: ensureAgentGuidance failed",{error:String(e)})}}else fn.warn("Post-init: could not resolve target package directory; skipping verification",{workingDir:e})}({workingDir:d,options:{googleAuth:E?.googleAuth,emailPackage:E?.emailPackage}})},kt=xt?Oc({onComplete:()=>{Pt(),Ye({status:"success"}),Oe(),S?.finish(),process.exit(0)}}):w?Oc({onRestartRequested:()=>{w&&(B=!0,Ye({status:"running"}),Be({label:"Restarting browser tools..."}),D={createdAtUserMessageSeq:j,attempts:0})}}):void 0,Ut=kt?w?{"stably-agent-control":kt}:{"session-control":kt}:{},Lt=I&&yt?["mcp__create-report"]:[],Dt=I&&Se?["mcp__create-trace-proof"]:[],$t=xt?nu:_?tu:[...tu,...At?["mcp__auto-heal-report"]:[],...Lt,...Dt],Ot=xt?nu:w?[...ru,"mcp__stably-agent-control"]:_?ru:[...ru,...Lt,...Dt],Nt=I&&yt?{"create-report":tl({prContext:yt,authHeader:l,orgId:u,onReportPosted:e=>{Te({githubComment:{url:e.commentUrl,prNumber:yt.prNumber}})}})}:{},Bt=I&&Se?{"create-trace-proof":sl({authHeader:l,sessionId:Se,orgId:u,workingDir:d,onTraceProofCaptured:e=>{Te({traceProofs:[...ve?.traceProofs??[],e]})}})}:{},jt=xt?Ut:At&&Rt?{"auto-heal-report":$c({authHeader:l,diffTracker:Rt,orgId:u,runId:e.runId,workingDir:d,partialReportId:e.partialReportId}),"run-history":cl({authHeader:l,orgId:u,projectId:Tn(c)}),...Ut}:{...Ut,...Nt,...Bt},Mt="single"===e.mode,Ft=xt?[]:Mt?[{matcher:"Write",hooks:[Xs({onFileCreated:e=>{if(Ke.includes(e)||Ke.push(e),ve){if(ve.filesCreated.some(t=>"string"==typeof t?t===e:t.path===e))return;const t=n.isAbsolute(e)?e:n.join(d,e),r=n.basename(e),{sessionId:s}=ve,o=(async()=>{try{const n=await F.promises.readFile(t,"utf8"),o=await ps({authHeader:l,content:n,contentType:"text/plain",filename:r,filePath:e,orgId:u,sessionId:s}),i={path:e,filename:r,bucketPath:o};qe.push(i),Te({filesCreated:[...qe]})}catch(t){fn.warn("Failed to upload created file",{filePath:e,error:t instanceof Error?t.message:String(t)});const n={path:e,filename:r,bucketPath:null};qe.push(n),Te({filesCreated:[...qe]})}})();Je.push(o)}}})]}]:[],Yt=xt?[]:[...At?[{matcher:"Read",hooks:[Bs({action:"reading",pathKey:"file_path"})]},{matcher:"Write",hooks:[Bs({action:"writing",pathKey:"file_path"})]},{matcher:"Edit",hooks:[Bs({action:"editing",pathKey:"file_path"})]},{matcher:"Grep",hooks:[Bs({action:"searching",pathKey:"path"})]},{matcher:"Glob",hooks:[Bs({action:"searching",pathKey:"path"})]},{matcher:"Bash",hooks:[Ys({workspaceBoundary:d})]}]:[],...Ct?[{matcher:"Bash",hooks:[Ct.hook]}]:[]],Wt=Object.keys(bt).length>0?bt:void 0,Vt={...It};Vt.MCP_TOOL_TIMEOUT=String(6e5),St&&(Vt.ANTHROPIC_API_KEY=St,Vt.ANTHROPIC_BASE_URL=zt,Vt.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS="1",Vt.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC="1");const Kt=process.env.STABLY_AGENT_MODEL??"claude-opus-4-6",qt=At?"env"===c.type?c.auth.apiKey:c.auth.accessToken:void 0,Jt=At?Tn(c):void 0;At&&qt&&Jt&&(Vt.STABLY_API_KEY=qt,Vt.STABLY_PROJECT_ID=Jt);const Xt=st?`\n\n## Custom Rules\n${st}`:"",Qt=lt?`\n\n## Custom Test Generation Rules\n${lt}`:"",er=dt?`\n\n## Project Rules (STABLY.md)\n${dt}`:"",tr=mt+Xt+Qt+er;fn.debug("[fix] Final system prompt assembled",{baseSize:mt.length,fixRulesSize:Xt.length,createRulesSize:Qt.length,stablyMdSize:er.length,finalSize:tr.length});const rr=function(){const e=function(){const e=function(){const e=process.env.STABLY_PLUGIN_PATH?.trim();if(!e)return;const t=n.isAbsolute(e)?e:n.resolve(process.cwd(),e);return Al(t)?t:void 0}();if(e)return e;const t=n.join(hl,"stably-plugin-cli");if(Al(t))return t;for(const e of function*(e){let t=n.resolve(e);for(;;){yield t;const e=n.dirname(t);if(e===t)return;t=e}}(hl))for(const t of ml){const r=n.join(e,t);if(Al(r))return r}}();if(e)return{type:"local",path:e}}(),nr=()=>(fn.info("[fix] Starting SDK query",{model:Kt,tools:$t,mcpServers:Object.keys(jt),resumeSessionId:U??null,subagentsEnabled:!!Wt,subagentCount:Object.keys(bt).length,useStablyAiProxy:_t,aiProxyUrl:zt,anthropicBaseUrl:void 0,stablyPluginPath:rr?.path,stablyPluginExists:!!rr}),_e({options:{executableArgs:["--max-old-space-size=4096"],tools:$t,allowedTools:Ot,...null!=at?{maxBudgetUsd:at}:{},betas:[],canUseTool:(e,t)=>(fn.debug("[fix] canUseTool called",{toolName:e}),Promise.resolve({behavior:"allow",updatedInput:t})),cwd:d,env:Vt,hooks:{PostToolUse:Ft,PreToolUse:Yt},includePartialMessages:!0,agents:Wt,mcpServers:jt,model:Kt,permissionMode:"default",plugins:rr?[rr]:void 0,systemPrompt:tr,...U?{resume:U}:{}},prompt:S??et})),sr=()=>{if(S&&0!==z.length){for(const e of z)S.pushText(e);z.length=0,$=!0,Ye({status:"running"})}},or=async()=>{w&&(L||(L=(async()=>{fn.info("Restarting MCP servers for chat mode"),Ye({status:"running"}),Be({label:"Restarting browser tools..."});try{await(k?.interrupt?.())}catch(e){fn.warn("Failed to interrupt response during MCP restart",{error:e instanceof Error?e.message:String(e)})}so(),await eo(),S?.finish(),S=new oo,Y=0,$=!1,O=!1,te.clear(),k=nr(),W=!0,Be({label:"Restarting browser tools..."}),w&&S&&D&&(D.createdAtUserMessageSeq===j?D.attempts>=1||z.length>0?D=void 0:(D.attempts+=1,S.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")),D=void 0,$=!0,Ye({status:"running"})):D=void 0),sr()})().finally(()=>{L=void 0,sr()})),await L)},ir=async e=>{if(b&&$&&!X&&!q)q=(async()=>{fn.info("[fix] Interrupting for user message",{messageCount:e.length,phase:de?.phase});try{await(k?.interrupt?.())}catch(e){fn.warn("[fix] Failed to interrupt response for user message",{error:e instanceof Error?e.message:String(e)})}await eo(),so(),S?.finish(),S=new oo,te.clear(),k=nr();const t=e.map(e=>`[Message from web UI user]: ${e}`).join("\n\n");S.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}`),Q=!0,$=!0})().finally(()=>{q=void 0}),await q;else for(const t of e)S?.pushText(`[Message from web UI user]: ${t}`)};if(St){_&&Be({label:"Checking AI connectivity..."});const e=zt,t=`${e.replace(/\/$/,"")}/v1/messages`;fn.debug(`[fix] Pre-flight: POST ${t}`);const r=Date.now();let n;try{const e=await fetch(t,{method:"POST",signal:AbortSignal.timeout(1e4),headers:{"x-api-key":St,"anthropic-version":"2023-06-01","content-type":"application/json"},body:"{}"}),s=await e.text().catch(()=>""),o=Date.now()-r;fn.debug(`[fix] Pre-flight: ${e.status} in ${o}ms — ${s.slice(0,300)}`),401===e.status||403===e.status?(fn.error(`[fix] Pre-flight: AI proxy key rejected (${e.status}) at ${t}`),n="Unable to start verification: AI proxy credentials were rejected. Please run `stably login` and try again."):fn.info("[fix] Pre-flight: AI proxy key valid",{status:e.status,durationMs:o})}catch(t){fn.error("[fix] Pre-flight: AI proxy unreachable",{error:t instanceof Error?t.message:String(t),durationMs:Date.now()-r,url:e}),n="Unable to start verification: cannot reach the AI proxy. Please check your network/VPN and try again."}finally{_&&"running"===Ge&&Be({label:void 0})}n&&(Le({text:`[stably] ${n}\n`}),Ye({error:n,status:"error"}),await $e(),fn.flush(),fn.printLogFileInfo(),process.exit(1))}fn.info("[fix] Creating initial agent query"),_&&(Be({label:"Initializing verification session..."}),Le({text:"Initializing verification session...\n"})),fn.flush(),k=nr(),fn.info("[fix] Agent query created, entering message loop"),"chat"!==e.mode&&(S.pushText(et),re.push({role:"user",content:et,timestamp:(new Date).toISOString()}));const ar=async t=>{Re||(Re=(async()=>{fn.info("[session] Interrupt requested",{source:t,mode:e.mode}),oe="CANCELED",await ye("CANCELED"),me({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:ge(!0)}),await(ue?.closeAndWait()),await Promise.allSettled(Je),Te({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0}),await(we?.closeAndWait()),K&&(clearTimeout(K),K=void 0),Oe(),so(),await eo(),await(Ct?.cleanup());try{await(k?.interrupt?.())}catch{}S?.finish(),re.length>0&&Se&&await ws({authHeader:l,orgId:u,sessionId:Se,projectId:Tn(c),history:re}).catch(e=>{fn.warn("[exit] Failed to upload session history",{error:e instanceof Error?e.message:String(e)})}),$e(),fn.flush()})()),await Re};Ce.current=async()=>{await ar("ctrl-c")};let cr=()=>{};cr=function({enabled:e,onSignal:t}){const r=()=>{t("SIGINT")},n=()=>{t("SIGTERM")};return process.prependOnceListener("SIGINT",r),process.prependOnceListener("SIGTERM",n),()=>{process.removeListener("SIGINT",r),process.removeListener("SIGTERM",n)}}({enabled:!0,onSignal:e=>{(async()=>{await ar("signal"),process.exit(function(e){return"SIGINT"===e?130:143}(e))})()}});let lr=0,ur=null,dr=!1;const pr=_?setTimeout(()=>{if(ur||"running"!==Ge)return;const e="This is taking longer than expected. Please try again.";Le({text:`[stably] ${e}\n`}),Ye({error:e,status:"error"});try{k?.interrupt?.()}catch{}S?.finish(),$e(),fn.flush(),fn.printLogFileInfo(),process.exit(1)},9e4):void 0;pr?.unref();const fr=setInterval(()=>{const e=Date.now()-le;ur?fn.info("[fix] Watchdog: message loop active",{messageCount:lr,elapsed:e}):(fn.info("[fix] Watchdog: waiting for first SDK message",{elapsed:e}),_&&!dr&&e>=15e3&&(Le({text:"Still preparing verification. This can take a bit...\n"}),dr=!0)),fn.flush()},15e3);fr.unref();try{let t=!1;for(;;){if(!k){fn.info("[fix] No response object, exiting message loop");break}t=!1,fn.info("[fix] Entering for-await on SDK response");for await(const r of k){lr++,ur||(ur=Date.now(),pr&&clearTimeout(pr),_&&Be({label:void 0}),fn.info("[fix] First SDK message received",{waitDurationMs:ur-le,messageType:r.type,messageSubtype:"subtype"in r?r.subtype:void 0}));const n="session_id"in r&&"string"==typeof r.session_id?r.session_id:void 0;if(n&&n!==U&&(U=n,fn.debug("Captured Claude session id",{sessionId:U})),"stream_event"===r.type){const{event:e}=r;(lr<=5||lr%200==0)&&fn.debug("[fix] Stream event",{msgNum:lr,eventType:e?.type});const t=e&&"object"==typeof e&&"parent_tool_use_id"in e&&"string"==typeof e.parent_tool_use_id?e.parent_tool_use_id:void 0;if("content_block_delta"===e?.type){const{delta:r}=e;if("text_delta"===r?.type&&r.text){if(w&&B&&!t)continue;W&&(W=!1,Be({label:void 0}));const e=t&&te.has(t)?t:1===te.size?Array.from(te.keys())[0]:void 0;e?Pe({toolUseId:e,kind:"text",content:r.text}):_||Le({text:r.text})}}"message_stop"===e?.type&&S&&(X=!1,S.allowNextTurn());continue}if("assistant"===r.type){const t="parent_tool_use_id"in r&&"string"==typeof r.parent_tool_use_id?r.parent_tool_use_id:void 0,{content:n}=r.message??{};if(Array.isArray(n)&&!t){const t=n.filter(e=>e&&"object"==typeof e&&"type"in e&&"text"===e.type).map(e=>e&&"object"==typeof e&&"text"in e&&"string"==typeof e.text?e.text:void 0).filter(Boolean).join("\n");t&&(Ve=t,_&&(ze=ze?`${ze}\n\n${t}`:t),fn.debug("Assistant message",{text:_?Xl(t):t}),"fix"===e.mode&&(fe(ou,{type:"ai_message",summary:t.slice(0,200)}),he({type:"ai_message",summary:t.slice(0,200)})),T&&Ee({type:"ai_message",summary:t.slice(0,200)}),ne({role:"assistant",content:t,timestamp:(new Date).toISOString()}))}if(te.size>0){const e=Array.isArray(n)?n.filter(e=>e&&"object"==typeof e&&"type"in e&&"tool_use"===e.type).map(e=>e&&"object"==typeof e&&"name"in e&&"string"==typeof e.name?e.name:void 0):[];fn.debug("Assistant message with active subagents",{hasParentToolUseId:!!t,parentToolUseId:t,activeSubagentIds:Array.from(te.keys()),toolNames:e,fullMessageKeys:Object.keys(r),rawMessage:JSON.stringify(r).slice(0,500)})}if(Array.isArray(n))for(const r of n){if("tool_use"===r?.type){if("mcp__auto-heal-report__generate-report"===r.name&&(X=!0),"mcp__session-control__restart_mcp_servers"===r.name||"mcp__stably-agent-control__restart_mcp_servers"===r.name){Ue({rawName:r.name,toolInput:r.input});continue}if(r.name.startsWith("mcp__session-control__")||r.name.startsWith("mcp__stably-agent-control__"))continue;if(uu(r.name))continue;if(_&&lu.test(r.name))continue;if(te.size>0&&fn.debug("Tool use detected with active subagents",{toolName:r.name,hasParentToolUseId:!!t,parentToolUseId:t,wouldRouteToSubagent:!!t&&te.has(t),activeSubagentIds:Array.from(te.keys())}),"Task"===r.name){const t=r.input,n=t&&"object"==typeof t?t:void 0,s=n&&"subagent_type"in n&&"string"==typeof n.subagent_type?n.subagent_type:"subagent",o=n&&"description"in n&&"string"==typeof n.description?n.description.trim():"";if(fn.info("[fix] Subagent started",{subagentType:s,description:o,toolUseId:r.id,activeSubagentCount:te.size+1}),te.set(r.id,{subagentType:s,description:o}),ke({toolUseId:r.id,subagentType:s,description:o}),"fix"===e.mode){if("triage"===s){He?.({phase:"triage"});const e={id:r.id,testDescription:"Triage",workerType:"triage",status:"running",summary:null,startedAt:Date.now(),endedAt:null,activity:[]};me({phase:"triage",workers:[...de?.workers??[],e]})}else if("code-worker"===s){pe.add(o||r.id);const e={id:r.id,testDescription:o||r.id,workerType:"code-worker",status:"running",summary:null,startedAt:Date.now(),endedAt:null,activity:[]};He?.({phase:"fixing",totalTests:pe.size,currentTestDescription:o||null}),me({phase:"fixing",totalTests:pe.size,currentTestDescription:o||null,lastTestDescription:o||de?.lastTestDescription||null,workers:[...de?.workers??[],e]})}else if("browser-worker"===s){pe.add(o||r.id);const e={id:r.id,testDescription:o||r.id,workerType:"browser-worker",status:"running",summary:null,startedAt:Date.now(),endedAt:null,activity:[]};He?.({phase:"debugging",totalTests:pe.size,currentTestDescription:o||null}),me({phase:"debugging",totalTests:pe.size,currentTestDescription:o||null,lastTestDescription:o||de?.lastTestDescription||null,workers:[...de?.workers??[],e]})}else"validation"===s?(He?.({phase:"validation",currentTestDescription:null}),me({phase:"validation",currentTestDescription:null})):"context"===s&&me({currentTestDescription:o||null});he({type:"tool_call",summary:`[${s}] ${o}`.trim()})}continue}if(t&&te.has(t)){const n=Mo(r.name,r.input),s=n??Fo(r.name),o=n?void 0:jo(r.name,r.input),i=o?`${s} (${o})`:s;if(fn.debug("Subagent tool called",{tool:r.name,parentToolUseId:t}),Pe({toolUseId:t,kind:"tool",content:i}),"fix"===e.mode){he({type:"tool_call",summary:i});const e=te.get(t);"code-worker"!==e?.subagentType&&"browser-worker"!==e?.subagentType&&"triage"!==e?.subagentType||fe(t,{type:"tool_call",summary:i})}continue}if(t&&fn.debug("Tool with parent_tool_use_id but no matching subagent",{tool:r.name,parentToolUseId:t,activeSubagentIds:Array.from(te.keys())}),fn.debug("Tool called",{tool:r.name,input:r.input}),Ue({rawName:r.name,toolInput:r.input}),r.id&&se.set(r.id,r.name),ne({role:"tool",content:"",timestamp:(new Date).toISOString(),toolName:r.name,toolInput:r.input}),"fix"===e.mode){const e=Mo(r.name,r.input),t=e??Fo(r.name),n=e?void 0:jo(r.name,r.input),s=n?`${t} (${n})`:t;fe(ou,{type:"tool_call",summary:s}),he({type:"tool_call",summary:s})}if(I){const e=Mo(r.name,r.input),t=e??Fo(r.name),n=e?void 0:jo(r.name,r.input),s=n?`${t} (${n})`:t;"initializing"===ve?.phase?Te({phase:"generating",currentActivity:s}):"mcp__playwright-test__test_run"===r.name&&"generating"===ve?.phase?Te({phase:"testing",currentActivity:s}):Te({currentActivity:s}),Ee({type:"tool_call",summary:s})}if(_){const e=Mo(r.name,r.input),t=e??Fo(r.name),n=e?void 0:jo(r.name,r.input),s=Xl(n?`${t} (${n})`:t);Te("initializing"===ve?.phase?{phase:"verifying",currentActivity:s}:{currentActivity:s}),Ee({type:"tool_call",summary:s})}}if("text"===r?.type){const n="string"==typeof r.text?r.text:"",s=t&&te.has(t)?t:1===te.size?Array.from(te.keys())[0]:void 0;if(s&&n&&(Pe({toolUseId:s,kind:"text",content:n}),"fix"===e.mode)){const e=te.get(s);"code-worker"!==e?.subagentType&&"browser-worker"!==e?.subagentType&&"triage"!==e?.subagentType||fe(s,{type:"ai_message",summary:n.slice(0,200)})}}}continue}if("user"===r.type){const t="message"in r&&r.message&&"object"==typeof r.message&&"content"in r.message?r.message.content:void 0,n="tool_use_result"in r&&r.tool_use_result&&"object"==typeof r.tool_use_result?r.tool_use_result:void 0;if(Array.isArray(t))for(const r of t)if(r&&"object"==typeof r&&"type"in r&&"tool_result"===r.type&&"tool_use_id"in r){const t="string"==typeof r.tool_use_id?r.tool_use_id:void 0,s="is_error"in r&&!0===r.is_error||"error"===n?.status;let o;const i=n?.content??("content"in r?r.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("")),fn.debug("Tool result",{toolUseId:t,isError:s,output:o?.slice(0,500)});const a=5e4,c=t?se.get(t):void 0;if(ne({role:"tool_result",content:"",timestamp:(new Date).toISOString(),toolName:c,toolOutput:o?.slice(0,a),isError:s}),t&&te.has(t)){const r=te.get(t);if(fn.info("[fix] Subagent completed",{toolUseId:t,isError:s,subagentType:r?.subagentType,description:r?.description,activeSubagentCount:te.size-1}),o&&Pe({toolUseId:t,kind:"text",content:o}),Fe({toolUseId:t,status:s?"error":"complete"}),"fix"===e.mode&&"triage"===r?.subagentType){const e=s?"failed":"succeeded",r=o?o.slice(0,500):null,n=(de?.workers??[]).map(n=>n.id===t?{...n,status:e,summary:r,endedAt:Date.now()}:n);me({workers:n})}if("fix"===e.mode&&("code-worker"===r?.subagentType||"browser-worker"===r?.subagentType)){const e=s?"failed":"succeeded",r=o?o.slice(0,500):null,n=(de?.workers??[]).map(n=>n.id===t?{...n,status:e,summary:r,endedAt:Date.now()}:n);s?(He?.({failedTests:(de?.failedTests??0)+1,currentTestDescription:null}),me({failedTests:(de?.failedTests??0)+1,currentTestDescription:null,workers:n})):(He?.({fixedTests:(de?.fixedTests??0)+1,currentTestDescription:null}),me({fixedTests:(de?.fixedTests??0)+1,currentTestDescription:null,workers:n}))}te.delete(t)}}continue}if("result"===r.type){if(fn.info("[fix] Agent result received",{subtype:r.subtype,messageCount:lr,elapsed:Date.now()-le,activeSubagents:te.size,fixedTests:de?.fixedTests,failedTests:de?.failedTests,phase:de?.phase}),b){if("success"===r.subtype){K&&(clearTimeout(K),K=void 0);for(const e of J)S?.pushText(`[Message from web UI user]: ${e}`);if(J=[],(T||"fix"===e.mode)&&S){if(S.hasQueuedMessages()){fn.info("[ws] Queued web UI messages found, continuing agent"),$=!0,S.allowNextTurn();continue}if(await bu(S,3e3)){fn.info("[ws] Web UI message received during grace period, continuing agent"),$=!0,S.allowNextTurn();continue}S.finish()}if(He?.({phase:"complete",currentTestDescription:null,endedAt:Date.now()}),me({phase:"complete",currentTestDescription:null,endedAt:Date.now(),isError:!1,workers:ge(!1)}),await Promise.allSettled(Je),"verify"===e.mode){(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt).trim();const t=ze||Ve,r=/```verdict\s*\r?\n/.test(t),n=Zl(t)??{verdict:"INCONCLUSIVE",steps:["Agent finished without a parseable verdict block."],reason:r?"Failed to parse verdict.":"The agent completed without reporting a verdict.",evidence:[]},s=Ql(n);"PASS"===n.verdict?N.green("VERIFICATION PASSED"):"FAIL"===n.verdict?N.red("VERIFICATION FAILED"):eu("VERIFICATION INCONCLUSIVE"),s.steps.length>0&&s.steps.forEach((e,t)=>{}),s.reason&&(n.verdict,s.reason),s.evidence.length>0&&s.evidence.forEach(e=>{}),Te({phase:"complete",endedAt:Date.now(),isError:"PASS"!==n.verdict,currentActivity:null}),process.exitCode="PASS"===n.verdict?0:"FAIL"===n.verdict?1:2,Ye({status:"success"})}else{if(Te({phase:"complete",endedAt:Date.now(),isError:!1,currentActivity:null}),Mt&&Ke.length>0){N.green("Created files:");for(const e of Ke)N.green(`- ${e}`)}const e=(e,t)=>`]8;;${e}${t}]8;;`,t=We?N.cyan(`📊 View Autoheal Report:\n ${e(We,N.cyan(N.bold(N.underline(We))))}`):void 0;Ye({status:"success",result:t}),oe="COMPLETED"}}else if(q||Q)fn.info("[fix] Suppressing error status: user-message interrupt in progress");else if(O)oe="CANCELED",me({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:ge(!0)}),await Promise.allSettled(Je),Te({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0});else if(_){let e="Execution error before verification completed.";"error_max_budget_usd"===r.subtype?e="Budget limit exceeded before verification completed.":"error_max_turns"===r.subtype&&(e="Maximum turns exceeded before verification completed."),eu("VERIFICATION INCONCLUSIVE"),await Promise.allSettled(Je),Te({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),Ye({status:"success"}),process.exitCode=2}else{let e,t="unknown",n="Run failed.";"error_max_budget_usd"===r.subtype?(t="budget_exceeded",e="total_cost_usd"in r?r.total_cost_usd:void 0,n=`Budget limit exceeded (${void 0!==e?`$${e.toFixed(2)}`:"unknown"} spent). The fix session was stopped to prevent runaway costs.`,fn.warn("[fix] Budget limit exceeded",{subtype:r.subtype,totalCostUsd:e})):"error_max_turns"===r.subtype?(t="max_turns",n="Maximum turns exceeded. The fix session was stopped."):"error_during_execution"===r.subtype&&(t="execution_error"),He?.({endedAt:Date.now(),isError:!0}),me({phase:"complete",endedAt:Date.now(),isError:!0,errorReason:t,errorMessage:n,totalCostUsd:e,currentTestDescription:null,workers:ge(!0)}),await Promise.allSettled(Je),Te({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),Ye({error:n,status:"error"}),process.exitCode=1,oe="FAILED"}O=!1;break}const n=w&&B;if("success"!==r.subtype){if(!O){let e="Run failed.";"error_max_budget_usd"===r.subtype?(e=`Budget limit exceeded (${"total_cost_usd"in r?`$${r.total_cost_usd.toFixed(2)}`:"unknown"} spent). The fix session was stopped to prevent runaway costs.`,fn.warn("[fix] Budget limit exceeded",{subtype:r.subtype,totalCostUsd:"total_cost_usd"in r?r.total_cost_usd:void 0})):"error_max_turns"===r.subtype&&(e="Maximum turns exceeded. The fix session was stopped."),Ye({error:e,status:"error"}),process.exitCode=1}}else Ye(n?{status:"running"}:{status:"success"});if($=!1,O=!1,n){B=!1,fn.info("Processing deferred MCP restart request in chat mode"),await or(),t=!0;break}W=!1,Be({label:void 0}),S?.allowNextTurn(),v&&Y>0&&(Y-=1,$=!0,Ye({status:"running"}));continue}}if(q&&await q,Q&&(Q=!1,t=!0,Ye({status:"running"}),fn.info("[fix] Resuming after user-message interrupt")),!t)break}}catch(e){O?(oe="CANCELED",me({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:ge(!0)}),await Promise.allSettled(Je),Te({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0})):(fn.error("[fix] Agent encountered an error",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0,elapsed:Date.now()-le}),Ye({error:`Agent encountered an error: ${e}`,status:"error"}),process.exitCode=1,oe="FAILED",me({phase:"complete",endedAt:Date.now(),isError:!0,currentTestDescription:null,workers:ge(!0)}),await Promise.allSettled(Je),Te({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),fn.flush(),fn.printLogFileInfo())}finally{if(pr&&clearTimeout(pr),clearInterval(fr),K&&(clearTimeout(K),K=void 0),fn.info("[fix] Agent session ending",{finalStatus:oe,elapsed:Date.now()-le,totalMessages:lr}),Pt(),$=!1,O=!1,cr(),process.off("uncaughtException",a),S?.finish(),oe){fn.info("[fix] Reporting final autoheal status",{status:oe});const e=Date.now();await ye(oe),fn.info("[fix] Final autoheal status reported",{durationMs:Date.now()-e})}if(fn.info("[fix] Closing WebSocket progress reporter"),await(ue?.closeAndWait()),await Promise.allSettled(Je),await(we?.closeAndWait()),!At&&re.length>0&&Se&&(fn.info("[session] Uploading session history",{messageCount:re.length}),await ws({authHeader:l,orgId:u,sessionId:Se,projectId:Tn(c),history:re}).catch(e=>{fn.warn("[session] Failed to upload session history",{error:e instanceof Error?e.message:String(e)})})),At&&Rt){const t=Date.now();try{fn.info("[fix] Computing diff...");const r=await Rt.computeDiff();if(r&&r.trim().length>0){fn.info("[fix] Uploading diff...",{diffLength:r.length});const{diffBucketPath:n,uploadUrl:s}=await ns({authHeader:l,contentType:"text/plain",orgId:u,runId:e.runId});await Pn({body:r,contentType:"text/plain",uploadUrl:s,errorContext:"diff"}),await ss({authHeader:l,diffBucketPath:n,orgId:u,runId:e.runId}),fn.info("[fix] Diff uploaded",{durationMs:Date.now()-t})}else fn.info("[fix] No diff to upload (empty or no changes)")}catch(e){fn.warn("[fix] Failed to upload diff",{error:e instanceof Error?e.message:String(e),durationMs:Date.now()-t})}}fn.info("[fix] Cleaning up diff tracker"),await(Rt?.cleanup()),At&&re.length>0&&Se&&(fn.info("[fix] Uploading session history",{messageCount:re.length}),await ws({authHeader:l,orgId:u,sessionId:Se,projectId:Tn(c),history:re}).catch(e=>{fn.warn("[fix] Failed to upload session history",{error:e instanceof Error?e.message:String(e)})})),fn.info("[fix] Running final cleanup"),await(Ct?.cleanup()),await $e(),fn.info("[fix] Cleanup complete")}}}}),_u=Fe({"src/fix/triage-output-schema.ts"(){vu=x.object({schemaVersion:x.literal(1),testSuiteRunId:x.string(),issues:x.array(x.object({issueId:x.string(),title:x.string(),rootCause:x.string(),testCaseIds:x.array(x.string()).min(1),priority:x.number().int().min(1).max(10)})),testsToSkipFixing:x.array(x.object({testCaseId:x.string(),reason:x.string()}))})}}),Tu={};async function Eu({runId:e}){const t=process.env.STABLY_TRIAGE_S3_PRESIGNED_URL;if(!t)throw new Error("STABLY_TRIAGE_S3_PRESIGNED_URL is required for triage command");fn.info("[triage] Starting standalone triage",{runId:e}),await mu({mode:"fix",runId:e,triageOnly:!0});const{readFile:r}=await import("fs/promises"),{join:n}=await import("path"),s=n(process.cwd(),".stably","triage-output.json");let o;try{o=await r(s,"utf-8")}catch{throw new Error(`Triage output not found at ${s}. The triage agent may have failed to produce output.`)}const i=vu.safeParse(JSON.parse(o));if(!i.success)throw fn.error("[triage] Triage output failed schema validation",{errors:i.error.issues}),new Error(`Triage output failed schema validation: ${i.error.message}`);fn.info("[triage] Uploading triage output to S3",{runId:e}),await Pn({body:JSON.stringify(i.data),contentType:"application/json",uploadUrl:t,errorContext:"triage output"}),fn.info("[triage] Triage complete",{runId:e,issueCount:i.data.issues.length})}He(Tu,{runTriageCommand:()=>Eu});var Su=Fe({"src/fix/triage-command.ts"(){Vn(),hs(),_u(),Iu()}}),xu=Fe({"src/fix/merge-reports.ts"(){}}),Au={};async function Cu({runId:e}){fn.info("[merge-reports] Starting report merge",{runId:e});const{readdir:t,readFile:r}=await import("fs/promises"),{join:n}=await import("path"),s=n(process.cwd(),".stably","partial-reports");let o;try{o=await t(s)}catch{throw new Error(`No partial reports directory found at ${s}`)}const i=o.filter(e=>e.endsWith(".json"));if(0===i.length)throw new Error(`No partial report JSON files found in ${s}`);const a=[];for(const e of i){const t=await r(n(s,e),"utf-8");a.push(JSON.parse(t))}const c=function(e){if(0===e.length)return{markdown:"# Auto-Heal Report\n\nNo partial reports were produced.",summary:"No partial reports available",issues:[]};if(1===e.length){const t=e[0];return{markdown:t.markdown,summary:t.summary,issues:t.issues}}const t=new Set,r=[];for(const n of e)for(const e of n.issues){const n=e.testCaseIds??[];if(0===n.length||n.some(e=>!t.has(e))){r.push(e);for(const e of n)t.add(e)}}const n=e.map((e,t)=>`## Agent ${t+1} (${e.partialReportId})\n\n${e.markdown}`),s=r.filter(e=>"fixed"===e.result).length,o=r.filter(e=>"fixed"!==e.result).length;return{markdown:["# Auto-Heal Report (Merged)","",`Fixed ${s} of ${r.length} issues across ${e.length} agents.`,"",...n].join("\n"),summary:`Fixed ${s} of ${r.length} issues across ${e.length} agents${o>0?` (${o} unfixed)`:""}`,issues:r}}(a);fn.info("[merge-reports] Reports merged",{runId:e,partialCount:a.length,issueCount:c.issues.length});const{mkdir:l,writeFile:u}=await import("fs/promises"),d=n(process.cwd(),".stably");await l(d,{recursive:!0}),await u(n(d,"merged-report.json"),JSON.stringify(c,null,2),"utf-8"),fn.info("[merge-reports] Merged report written to .stably/merged-report.json")}He(Au,{runMergeReportsCommand:()=>Cu});var Ru=Fe({"src/fix/merge-reports-command.ts"(){Vn(),xu()}});Ge();var Pu={detect:({env:e})=>Boolean(e.APPVEYOR),configuration({env:e}){const t=e.APPVEYOR_PULL_REQUEST_NUMBER,r=Boolean(t);return{name:"Appveyor",service:"appveyor",commit:e.APPVEYOR_REPO_COMMIT,tag:e.APPVEYOR_REPO_TAG_NAME,build:e.APPVEYOR_BUILD_NUMBER,buildUrl:`https://ci.appveyor.com/project/${e.APPVEYOR_PROJECT_SLUG}/build/${e.APPVEYOR_BUILD_VERSION}`,branch:e.APPVEYOR_REPO_BRANCH,job:e.APPVEYOR_JOB_NUMBER,jobUrl:`https://ci.appveyor.com/project/${e.APPVEYOR_PROJECT_SLUG}/build/job/${e.APPVEYOR_JOB_ID}`,pr:t,isPr:r,prBranch:e.APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH,slug:e.APPVEYOR_REPO_NAME,root:e.APPVEYOR_BUILD_FOLDER}}};function ku(e){return(/\d+(?!.*\d+)/.exec(e)||[])[0]}function Uu(e){return e?/^(?:refs\/heads\/)?(?<branch>.+)$/i.exec(e)[1]:void 0}var Lu={detect:({env:e})=>Boolean(e.BUILD_BUILDURI),configuration({env:e}){const t=e.SYSTEM_PULLREQUEST_PULLREQUESTID,r=Boolean(t);return{name:"Azure Pipelines",service:"azurePipelines",commit:e.BUILD_SOURCEVERSION,build:e.BUILD_BUILDNUMBER,branch:Uu(r?e.SYSTEM_PULLREQUEST_TARGETBRANCH:e.BUILD_SOURCEBRANCH),pr:t,isPr:r,prBranch:Uu(r?e.SYSTEM_PULLREQUEST_SOURCEBRANCH:void 0),root:e.BUILD_REPOSITORY_LOCALPATH}}},Du={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})},$u={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})},Ou={detect:({env:e})=>Boolean(e.BITRISE_IO),configuration({env:e}){const t="false"===e.BITRISE_PULL_REQUEST?void 0:e.BITRISE_PULL_REQUEST,r=Boolean(t);return{name:"Bitrise",service:"bitrise",commit:e.BITRISE_GIT_COMMIT,tag:e.BITRISE_GIT_TAG,build:e.BITRISE_BUILD_NUMBER,buildUrl:e.BITRISE_BUILD_URL,branch:r?e.BITRISEIO_GIT_BRANCH_DEST:e.BITRISE_GIT_BRANCH,pr:t,isPr:r,prBranch:r?e.BITRISE_GIT_BRANCH:void 0,slug:e.BITRISE_APP_SLUG}}},Nu={detect:({env:e})=>Boolean(e.BUDDY_WORKSPACE_ID),configuration({env:e}){const t=ku(e.BUDDY_EXECUTION_PULL_REQUEST_ID),r=Boolean(t);return{name:"Buddy",service:"buddy",commit:e.BUDDY_EXECUTION_REVISION,tag:e.BUDDY_EXECUTION_TAG,build:e.BUDDY_EXECUTION_ID,buildUrl:e.BUDDY_EXECUTION_URL,branch:r?e.BUDDY_EXECUTION_PULL_REQUEST_HEAD_BRANCH:e.BUDDY_EXECUTION_BRANCH,pr:t,isPr:r,slug:e.BUDDY_REPO_SLUG}}},Bu="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function ju(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Mu,Fu,Hu,Gu,Yu,Wu,Vu,zu,Ku={exports:{}};var qu,Ju,Xu,Qu,Zu,ed,td,rd,nd,sd,od,id,ad,cd,ld,ud={exports:{}},dd={};function pd(){if(id)return od;id=1;const e=n,t=function(){if(Xu)return Ju;Xu=1;const e=n,t=function(){if(zu)return Vu;zu=1;const e="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,t=n,r=e?";":":",s=function(){if(Wu)return Yu;var e;function t(r,n,s){if("function"==typeof n&&(s=n,n={}),!s){if("function"!=typeof Promise)throw new TypeError("callback not provided");return new Promise(function(e,s){t(r,n||{},function(t,r){t?s(t):e(r)})})}e(r,n||{},function(e,t){e&&("EACCES"===e.code||n&&n.ignoreErrors)&&(e=null,t=!1),s(e,t)})}return Wu=1,e="win32"===process.platform||Bu.TESTING_WINDOWS?function(){if(Fu)return Mu;Fu=1,Mu=r,r.sync=function(r,n){return t(e.statSync(r),r,n)};var e=F;function t(e,t,r){return!(!e.isSymbolicLink()&&!e.isFile())&&function(e,t){var r=void 0!==t.pathExt?t.pathExt:process.env.PATHEXT;if(!r)return!0;if(-1!==(r=r.split(";")).indexOf(""))return!0;for(var n=0;n<r.length;n++){var s=r[n].toLowerCase();if(s&&e.substr(-s.length).toLowerCase()===s)return!0}return!1}(t,r)}function r(r,n,s){e.stat(r,function(e,o){s(e,!e&&t(o,r,n))})}return Mu}():function(){if(Gu)return Hu;Gu=1,Hu=t,t.sync=function(t,n){return r(e.statSync(t),n)};var e=F;function t(t,n,s){e.stat(t,function(e,t){s(e,!e&&r(t,n))})}function r(e,t){return e.isFile()&&function(e,t){var r=e.mode,n=e.uid,s=e.gid,o=void 0!==t.uid?t.uid:process.getuid&&process.getuid(),i=void 0!==t.gid?t.gid:process.getgid&&process.getgid(),a=parseInt("100",8),c=parseInt("010",8);return r&parseInt("001",8)||r&c&&s===i||r&a&&n===o||r&(a|c)&&0===o}(e,t)}return Hu}(),Yu=t,t.sync=function(t,r){try{return e.sync(t,r||{})}catch(e){if(r&&r.ignoreErrors||"EACCES"===e.code)return!1;throw e}},Yu}(),o=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),i=(t,n)=>{const s=n.colon||r,o=t.match(/\//)||e&&t.match(/\\/)?[""]:[...e?[process.cwd()]:[],...(n.path||process.env.PATH||"").split(s)],i=e?n.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",a=e?i.split(s):[""];return e&&-1!==t.indexOf(".")&&""!==a[0]&&a.unshift(""),{pathEnv:o,pathExt:a,pathExtExe:i}},a=(e,r,n)=>{"function"==typeof r&&(n=r,r={}),r||(r={});const{pathEnv:a,pathExt:c,pathExtExe:l}=i(e,r),u=[],d=n=>new Promise((s,i)=>{if(n===a.length)return r.all&&u.length?s(u):i(o(e));const c=a[n],l=/^".*"$/.test(c)?c.slice(1,-1):c,d=t.join(l,e),f=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d;s(p(f,n,0))}),p=(e,t,n)=>new Promise((o,i)=>{if(n===c.length)return o(d(t+1));const a=c[n];s(e+a,{pathExt:l},(s,i)=>{if(!s&&i){if(!r.all)return o(e+a);u.push(e+a)}return o(p(e,t,n+1))})});return n?d(0).then(e=>n(null,e),n):d(0)};return Vu=a,a.sync=(e,r)=>{r=r||{};const{pathEnv:n,pathExt:a,pathExtExe:c}=i(e,r),l=[];for(let o=0;o<n.length;o++){const i=n[o],u=/^".*"$/.test(i)?i.slice(1,-1):i,d=t.join(u,e),p=!u&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d;for(let e=0;e<a.length;e++){const t=p+a[e];try{if(s.sync(t,{pathExt:c})){if(!r.all)return t;l.push(t)}}catch(e){}}}if(r.all&&l.length)return l;if(r.nothrow)return null;throw o(e)},Vu}(),r=function(){if(qu)return ud.exports;qu=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 ud.exports=e,ud.exports.default=e,ud.exports}();function s(n,s){const o=n.options.env||process.env,i=process.cwd(),a=null!=n.options.cwd,c=a&&void 0!==process.chdir&&!process.chdir.disabled;if(c)try{process.chdir(n.options.cwd)}catch(e){}let l;try{l=t.sync(n.command,{path:o[r({env:o})],pathExt:s?e.delimiter:void 0})}catch(e){}finally{c&&process.chdir(i)}return l&&(l=e.resolve(a?n.options.cwd:"",l)),l}return Ju=function(e){return s(e)||s(e,!0)}}(),r=function(){if(Qu)return dd;Qu=1;const e=/([()\][%!^"`<>&|;, *?])/g;return dd.command=function(t){return t.replace(e,"^$1")},dd.argument=function(t,r){return t=(t=`"${t=(t=(t=`${t}`).replace(/(?=(\\+?)?)\1"/g,'$1$1\\"')).replace(/(?=(\\+?)?)\1$/,"$1$1")}"`).replace(e,"^$1"),r&&(t=t.replace(e,"^$1")),t},dd}(),s=function(){if(sd)return nd;sd=1;const e=F,t=function(){if(rd)return td;rd=1;const e=ed?Zu:(ed=1,Zu=/^#!(.*)/);return td=(t="")=>{const r=t.match(e);if(!r)return null;const[n,s]=r[0].replace(/#! ?/,"").split(" "),o=n.split("/").pop();return"env"===o?s:s?`${o} ${s}`:o}}();return nd=function(r){const n=Buffer.alloc(150);let s;try{s=e.openSync(r,"r"),e.readSync(s,n,0,150,0),e.closeSync(s)}catch(e){}return t(n.toString())}}(),o="win32"===process.platform,i=/\.(?:com|exe)$/i,a=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;return od=function(n,c,l){c&&!Array.isArray(c)&&(l=c,c=null);const u={command:n,args:c=c?c.slice(0):[],options:l=Object.assign({},l),file:void 0,original:{command:n,args:c}};return l.shell?u:function(n){if(!o)return n;const c=function(e){e.file=t(e);const r=e.file&&s(e.file);return r?(e.args.unshift(e.file),e.command=r,t(e)):e.file}(n),l=!i.test(c);if(n.options.forceShell||l){const t=a.test(c);n.command=e.normalize(n.command),n.command=r.command(n.command),n.args=n.args.map(e=>r.argument(e,t));const s=[n.command].concat(n.args).join(" ");n.args=["/d","/s","/c",`"${s}"`],n.command=process.env.comspec||"cmd.exe",n.options.windowsVerbatimArguments=!0}return n}(u)}}var fd=ju(function(){if(ld)return Ku.exports;ld=1;const e=ne,t=pd(),r=function(){if(cd)return ad;cd=1;const e="win32"===process.platform;function t(e,t){return Object.assign(new Error(`${t} ${e.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}function r(r,n){return e&&1===r&&!n.file?t(n.original,"spawn"):null}return ad={hookChildProcess:function(t,n){if(!e)return;const s=t.emit;t.emit=function(e,o){if("exit"===e){const e=r(o,n);if(e)return s.call(t,"error",e)}return s.apply(t,arguments)}},verifyENOENT:r,verifyENOENTSync:function(r,n){return e&&1===r&&!n.file?t(n.original,"spawnSync"):null},notFoundError:t},ad}();function n(n,s,o){const i=t(n,s,o),a=e.spawn(i.command,i.args,i.options);return r.hookChildProcess(a,i),a}return Ku.exports=n,Ku.exports.spawn=n,Ku.exports.sync=function(n,s,o){const i=t(n,s,o),a=e.spawnSync(i.command,i.args,i.options);return a.error=a.error||r.verifyENOENTSync(a.status,i),a},Ku.exports._parse=t,Ku.exports._enoent=r,Ku.exports}());function hd(e={}){const{env:t=process.env,platform:r=process.platform}=e;return"win32"!==r?"PATH":Object.keys(t).reverse().find(e=>"PATH"===e.toUpperCase())||"Path"}var gd=(e,t)=>({name:`SIGRT${t+1}`,number:md+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),md=34,yd=[{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"}],bd=()=>{const e=(()=>{const e=64-md+1;return Array.from({length:e},gd)})();return[...yd,...e].map(wd)},wd=({name:e,number:t,description:r,action:n,forced:s=!1,standard:o})=>{const{signals:{[e]:i}}=p,a=void 0!==i;return{name:e,number:a?i:t,description:r,supported:a,action:n,forced:s,standard:o}},vd=({name:e,number:t,description:r,supported:n,action:s,forced:o,standard:i})=>[e,{name:e,number:t,description:r,supported:n,action:s,forced:o,standard:i}],Id=(()=>{const e=bd();return Object.fromEntries(e.map(vd))})();(()=>{const e=bd(),t=Array.from({length:65},(t,r)=>((e,t)=>{const r=((e,t)=>{const r=t.find(({name:t})=>p.signals[t]===e);return void 0!==r?r:t.find(t=>t.number===e)})(e,t);if(void 0===r)return{};const{name:n,description:s,supported:o,action:i,forced:a,standard:c}=r;return{[e]:{name:n,number:e,description:s,supported:o,action:i,forced:a,standard:c}}})(r,e));Object.assign({},...t)})();var _d=({stdout:e,stderr:t,all:r,error:n,signal:s,exitCode:o,command:i,escapedCommand:a,timedOut:c,isCanceled:l,killed:u,parsed:{options:{timeout:d,cwd:p=Re.cwd()}}})=>{o=null===o?void 0:o;const f=void 0===(s=null===s?void 0:s)?void 0:Id[s].description,h=(({timedOut:e,timeout:t,errorCode:r,signal:n,signalDescription:s,exitCode:o,isCanceled:i})=>e?`timed out after ${t} milliseconds`:void 0!==r?`failed with ${r}`:void 0!==n?`was killed with ${n} (${s})`:void 0!==o?`failed with exit code ${o}`:"failed")({timedOut:c,timeout:d,errorCode:n&&n.code,signal:s,signalDescription:f,exitCode:o,isCanceled:l}),g=`Command ${h}: ${i}`,m="[object Error]"===Object.prototype.toString.call(n),y=m?`${g}\n${n.message}`:g,b=[y,t,e].filter(Boolean).join("\n");return m?(n.originalMessage=n.message,n.message=b):n=new Error(b),n.shortMessage=y,n.command=i,n.escapedCommand=a,n.exitCode=o,n.signal=s,n.signalDescription=f,n.stdout=e,n.stderr=t,n.cwd=p,void 0!==r&&(n.all=r),"bufferedData"in n&&delete n.bufferedData,n.failed=!0,n.timedOut=Boolean(c),n.isCanceled=l,n.killed=u&&!c,n},Td=["stdin","stdout","stderr"],Ed=[];Ed.push("SIGHUP","SIGINT","SIGTERM"),"win32"!==process.platform&&Ed.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),"linux"===process.platform&&Ed.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var Sd,xd,Ad=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,Cd=Symbol.for("signal-exit emitter"),Rd=globalThis,Pd=Object.defineProperty.bind(Object),kd=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(Rd[Cd])return Rd[Cd];Pd(Rd,Cd,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,t){this.listeners[e].push(t)}removeListener(e,t){const r=this.listeners[e],n=r.indexOf(t);-1!==n&&(0===n&&1===r.length?r.length=0:r.splice(n,1))}emit(e,t,r){if(this.emitted[e])return!1;this.emitted[e]=!0;let n=!1;for(const s of this.listeners[e])n=!0===s(t,r)||n;return"exit"===e&&(n=this.emit("afterExit",t,r)||n),n}},Ud=class{},Ld=globalThis.process;Ad(Ld)?new class extends Ud{#e="win32"===Ld.platform?"SIGINT":"SIGHUP";#t=new kd;#r;#n;#s;#o={};#i=!1;constructor(e){super(),this.#r=e,this.#o={};for(const t of Ed)this.#o[t]=()=>{const r=this.#r.listeners(t);let{count:n}=this.#t;const s=e;if("object"==typeof s.__signal_exit_emitter__&&"number"==typeof s.__signal_exit_emitter__.count&&(n+=s.__signal_exit_emitter__.count),r.length===n){this.unload();const r=this.#t.emit("exit",null,t),n="SIGHUP"===t?this.#e:t;r||e.kill(e.pid,n)}};this.#s=e.reallyExit,this.#n=e.emit}onExit(e,t){if(!Ad(this.#r))return()=>{};!1===this.#i&&this.load();const r=t?.alwaysLast?"afterExit":"exit";return this.#t.on(r,e),()=>{this.#t.removeListener(r,e),0===this.#t.listeners.exit.length&&0===this.#t.listeners.afterExit.length&&this.unload()}}load(){if(!this.#i){this.#i=!0,this.#t.count+=1;for(const e of Ed)try{const t=this.#o[e];t&&this.#r.on(e,t)}catch(e){}this.#r.emit=(e,...t)=>this.#a(e,...t),this.#r.reallyExit=e=>this.#c(e)}}unload(){this.#i&&(this.#i=!1,Ed.forEach(e=>{const t=this.#o[e];if(!t)throw new Error("Listener not defined for signal: "+e);try{this.#r.removeListener(e,t)}catch(e){}}),this.#r.emit=this.#n,this.#r.reallyExit=this.#s,this.#t.count-=1)}#c(e){return Ad(this.#r)?(this.#r.exitCode=e||0,this.#t.emit("exit",this.#r.exitCode,null),this.#s.call(this.#r,this.#r.exitCode)):0}#a(e,...t){const r=this.#n;if("exit"===e&&Ad(this.#r)){"number"==typeof t[0]&&(this.#r.exitCode=t[0]);const n=r.call(this.#r,e,...t);return this.#t.emit("exit",this.#r.exitCode,null),n}return r.call(this.#r,e,...t)}}(Ld):new class extends Ud{onExit(){return()=>{}}load(){}unload(){}},new TextEncoder,function(){if(xd)return Sd;xd=1;const{PassThrough:e}=Pe;Sd=function(){var t=[],r=new e({objectMode:!0});return r.setMaxListeners(0),r.add=n,r.isEmpty=function(){return 0==t.length},r.on("unpipe",s),Array.prototype.slice.call(arguments).forEach(n),r;function n(e){return Array.isArray(e)?(e.forEach(n),this):(t.push(e),e.once("end",s.bind(null,e)),e.once("error",r.emit.bind(r,"error")),e.pipe(r,{end:!1}),this)}function s(e){!(t=t.filter(function(t){return t!==e})).length&&r.readable&&r.end()}}}();var Dd=(async()=>{})().constructor.prototype;["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(Dd,e)]);var $d=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],Od=/^[\w.-]+$/,Nd=le("execa").enabled,Bd=(e,t)=>String(e).padStart(t,"0"),jd=(e,t,r={})=>{const s=fd._parse(e,t,r);return e=s.command,t=s.args,(r={maxBuffer:1e8,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:(r=s.options).cwd||Re.cwd(),execPath:Re.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:Nd,...r}).env=(({env:e,extendEnv:t,preferLocal:r,localDir:s,execPath:o})=>{const i=t?{...Re.env,...e}:e;return r?(({env:e=Re.env,...t}={})=>{const r=hd({env:e={...e}});return t.path=e[r],e[r]=(({cwd:e=Re.cwd(),path:t=Re.env[hd()],preferLocal:r=!0,execPath:s=Re.execPath,addExecPath:o=!0}={})=>{const i=e instanceof URL?C(e):e,a=n.resolve(i),c=[];return r&&((e,t)=>{let r;for(;r!==t;)e.push(n.join(t,"node_modules/.bin")),r=t,t=n.resolve(t,"..")})(c,a),o&&((e,t,r)=>{const s=t instanceof URL?C(t):t;e.push(n.resolve(r,s,".."))})(c,s,a),[...c,t].join(n.delimiter)})(t),e})({env:i,cwd:s,execPath:o}):i})(r),r.stdio=(e=>{if(!e)return;const{stdio:t}=e;if(void 0===t)return Td.map(t=>e[t]);if((e=>Td.some(t=>void 0!==e[t]))(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${Td.map(e=>`\`${e}\``).join(", ")}`);if("string"==typeof t)return t;if(!Array.isArray(t))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof t}\``);const r=Math.max(t.length,Td.length);return Array.from({length:r},(e,r)=>t[r])})(r),"win32"===Re.platform&&"cmd"===n.basename(e,".exe")&&t.unshift("/q"),{file:e,args:t,options:r,parsed:s}},Md=(e,t,r)=>"string"==typeof t||Ce.isBuffer(t)?e.stripFinalNewline?function(e){const t="string"==typeof e?"\n":"\n".charCodeAt(),r="string"==typeof e?"\r":"\r".charCodeAt();return e[e.length-1]===t&&(e=e.slice(0,-1)),e[e.length-1]===r&&(e=e.slice(0,-1)),e}(t):t:void 0===r?void 0:"";function Fd(e,t,r){const n=jd(e,t,r),s=((e,t)=>$d(e,t).join(" "))(e,t),o=((e,t)=>$d(e,t).map(e=>(e=>"string"!=typeof e||Od.test(e)?e:`"${e.replaceAll('"','\\"')}"`)(e)).join(" "))(e,t);((e,{verbose:t})=>{t&&Re.stderr.write(`[${(()=>{const e=new Date;return`${Bd(e.getHours(),2)}:${Bd(e.getMinutes(),2)}:${Bd(e.getSeconds(),2)}.${Bd(e.getMilliseconds(),3)}`})()}] ${e}\n`)})(o,n.options);const i=(e=>{const t=(({input:e,inputFile:t})=>"string"!=typeof t?e:((e=>{if(void 0!==e)throw new TypeError("The `input` and `inputFile` options cannot be both set.")})(e),G(t)))(e);if(null!==(r=t)&&"object"==typeof r&&"function"==typeof r.pipe)throw new TypeError("The `input` option cannot be a stream in sync mode");var r;return t})(n.options);let a;try{a=ne.spawnSync(n.file,n.args,{...n.options,input:i})}catch(e){throw _d({error:e,stdout:"",stderr:"",all:"",command:s,escapedCommand:o,parsed:n,timedOut:!1,isCanceled:!1,killed:!1})}const c=Md(n.options,a.stdout,a.error),l=Md(n.options,a.stderr,a.error);if(a.error||0!==a.status||null!==a.signal){const e=_d({stdout:c,stderr:l,error:a.error,signal:a.signal,exitCode:a.status,command:s,escapedCommand:o,parsed:n,timedOut:a.error&&"ETIMEDOUT"===a.error.code,isCanceled:!1,killed:null!==a.signal});if(!n.options.reject)return e;throw e}return{command:s,escapedCommand:o,exitCode:0,stdout:c,stderr:l,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}}function Hd(e){try{return Fd("git",["rev-parse","HEAD"],e).stdout}catch{return}}function Gd(e){try{const t=Fd("git",["rev-parse","--abbrev-ref","HEAD"],e).stdout;if("HEAD"===t){const t=Fd("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 Yd=/^(?:.*)@(?:.*):(?:\d+\/)?(.*)\.git$/,Wd=/^\/(.*)\.git$/;function Vd(e){if(e){if(e.match(Yd))return e.replace(Yd,"$1");try{return new URL(e).pathname.replace(Wd,"$1")}catch{return}}}var zd,Kd={detect:({env:e})=>Boolean(e.BUILDKITE),configuration({env:e}){const t="false"===e.BUILDKITE_PULL_REQUEST?void 0:e.BUILDKITE_PULL_REQUEST,r=Boolean(t);return{name:"Buildkite",service:"buildkite",build:e.BUILDKITE_BUILD_NUMBER,buildUrl:e.BUILDKITE_BUILD_URL,commit:e.BUILDKITE_COMMIT,tag:e.BUILDKITE_TAG,branch:r?e.BUILDKITE_PULL_REQUEST_BASE_BRANCH:e.BUILDKITE_BRANCH,slug:Vd(e.BUILDKITE_REPO),pr:t,isPr:r,prBranch:r?e.BUILDKITE_BRANCH:void 0,root:e.BUILDKITE_BUILD_CHECKOUT_PATH}}},qd={detect:({env:e})=>Boolean(e.CIRCLECI),configuration({env:e}){const t=e.CIRCLE_PR_NUMBER||ku(e.CIRCLE_PULL_REQUEST||e.CI_PULL_REQUEST),r=Boolean(t);return{name:"CircleCI",service:"circleci",build:e.CIRCLE_BUILD_NUM,buildUrl:e.CIRCLE_BUILD_URL,job:`${e.CIRCLE_BUILD_NUM}.${e.CIRCLE_NODE_INDEX}`,commit:e.CIRCLE_SHA1,tag:e.CIRCLE_TAG,branch:r?void 0:e.CIRCLE_BRANCH,pr:t,isPr:r,prBranch:r?e.CIRCLE_BRANCH:void 0,slug:`${e.CIRCLE_PROJECT_USERNAME}/${e.CIRCLE_PROJECT_REPONAME}`}}},Jd="https://cirrus-ci.com",Xd={detect:({env:e})=>Boolean(e.CIRRUS_CI),configuration({env:e}){const t=e.CIRRUS_PR,r=Boolean(t);return{name:"Cirrus CI",service:"cirrus",commit:e.CIRRUS_CHANGE_IN_REPO,tag:e.CIRRUS_TAG,build:e.CIRRUS_BUILD_ID,buildUrl:`${Jd}/build/${e.CIRRUS_BUILD_ID}`,job:e.CIRRUS_TASK_ID,jobUrl:`${Jd}/task/${e.CIRRUS_TASK_ID}`,branch:r?e.CIRRUS_BASE_BRANCH:e.CIRRUS_BRANCH,pr:t,isPr:r,prBranch:r?e.CIRRUS_BRANCH:void 0,slug:e.CIRRUS_REPO_FULL_NAME,root:e.CIRRUS_WORKING_DIR}}},Qd={detect:({env:e})=>Boolean(e.CODEBUILD_BUILD_ID),configuration:({env:e,cwd:t})=>({name:"AWS CodeBuild",service:"codebuild",commit:Hd({env:e,cwd:t}),build:e.CODEBUILD_BUILD_ID,branch:Gd({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})},Zd={detect:({env:e})=>Boolean(e.CF_BUILD_ID),configuration({env:e}){const t=e.CF_PULL_REQUEST_NUMBER,r=Boolean(t);return{name:"Codefresh",service:"codefresh",commit:e.CF_REVISION,build:e.CF_BUILD_ID,buildUrl:e.CF_BUILD_URL,branch:r?e.CF_PULL_REQUEST_TARGET:e.CF_BRANCH,pr:t,isPr:r,prBranch:r?e.CF_BRANCH:void 0,slug:`${e.CF_REPO_OWNER}/${e.CF_REPO_NAME}`,root:e.CF_VOLUME_PATH}}},ep={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}}},tp=({env:e})=>{try{const t=e.GITHUB_EVENT_PATH?JSON.parse(G(e.GITHUB_EVENT_PATH,"utf-8")):void 0;if(t&&t.pull_request)return{branch:t.pull_request.base?Uu(t.pull_request.base.ref):void 0,pr:t.pull_request.number}}catch{}return{pr:void 0,branch:void 0}},rp={detect:({env:e})=>Boolean(e.GITHUB_ACTIONS),configuration({env:e,cwd:t}){const r="pull_request"===e.GITHUB_EVENT_NAME||"pull_request_target"===e.GITHUB_EVENT_NAME,n=Uu("pull_request_target"===e.GITHUB_EVENT_NAME?`refs/pull/${(e=>{const t=e.GITHUB_EVENT_PATH?JSON.parse(G(e.GITHUB_EVENT_PATH,"utf-8")):void 0;return t&&t.pull_request?t.pull_request.number:void 0})(e)}/merge`:e.GITHUB_REF);return{name:"GitHub Actions",service:"github",commit:e.GITHUB_SHA,build:e.GITHUB_RUN_ID,buildUrl:`${e.GITHUB_SERVER_URL}/${e.GITHUB_REPOSITORY}/actions/runs/${e.GITHUB_RUN_ID}`,isPr:r,branch:n,prBranch:r?n:void 0,slug:e.GITHUB_REPOSITORY,root:e.GITHUB_WORKSPACE,...r?tp({env:e}):void 0}}},np={detect:({env:e})=>Boolean(e.GITLAB_CI),configuration({env:e}){const t=e.CI_MERGE_REQUEST_ID,r=Boolean(t);return{name:"GitLab CI/CD",service:"gitlab",commit:e.CI_COMMIT_SHA,tag:e.CI_COMMIT_TAG,build:e.CI_PIPELINE_ID,buildUrl:`${e.CI_PROJECT_URL}/pipelines/${e.CI_PIPELINE_ID}`,job:e.CI_JOB_ID,jobUrl:`${e.CI_PROJECT_URL}/-/jobs/${e.CI_JOB_ID}`,branch:r?e.CI_MERGE_REQUEST_TARGET_BRANCH_NAME:e.CI_COMMIT_REF_NAME,pr:t,isPr:r,prBranch:e.CI_MERGE_REQUEST_SOURCE_BRANCH_NAME,slug:e.CI_PROJECT_PATH,root:e.CI_PROJECT_DIR}}},sp={detect:({env:e})=>Boolean(e.JENKINS_URL),configuration({env:e,cwd:t}){const r=e.ghprbPullId||e.gitlabMergeRequestId||e.CHANGE_ID,n=Boolean(r),s=e.GIT_LOCAL_BRANCH||e.GIT_BRANCH||e.gitlabBranch||e.BRANCH_NAME;return{name:"Jenkins",service:"jenkins",commit:e.ghprbActualCommit||e.GIT_COMMIT||Hd({env:e,cwd:t}),branch:n?e.ghprbTargetBranch||e.gitlabTargetBranch:s,build:e.BUILD_NUMBER,buildUrl:e.BUILD_URL,root:e.WORKSPACE,pr:r,isPr:n,prBranch:n?e.ghprbSourceBranch||e.gitlabSourceBranch||s:void 0}}},op={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}}},ip={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})},ap={detect:({env:e})=>Boolean(e.SAILCI),configuration({env:e}){const t=e.SAIL_PULL_REQUEST_NUMBER,r=Boolean(t);return{name:"Sail CI",service:"sail",commit:e.SAIL_COMMIT_SHA,branch:r?void 0:e.SAIL_COMMIT_BRANCH,pr:t,isPr:r,slug:`${e.SAIL_REPO_OWNER}/${e.SAIL_REPO_NAME}`,root:e.SAIL_CLONE_DIR}}},cp={detect:({env:e})=>Boolean(e.SCREWDRIVER),configuration({env:e}){const t=e.SD_PULL_REQUEST,r=Boolean(t);return{name:"Screwdriver.cd",service:"screwdriver",branch:r?e.PR_BASE_BRANCH_NAME:e.GIT_BRANCH,prBranch:r?e.PR_BRANCH_NAME:void 0,commit:e.SD_BUILD_SHA,build:e.SD_BUILD_ID,buildUrl:e.SD_UI_BUILD_URL,job:e.SD_JOB_ID,pr:t,isPr:r,slug:e.SD_PIPELINE_NAME,root:e.SD_ROOT_DIR}}},lp={detect:({env:e})=>Boolean(e.SCRUTINIZER),configuration({env:e}){const t=e.SCRUTINIZER_PR_NUMBER,r=Boolean(t);return{name:"Scrutinizer",service:"scrutinizer",commit:e.SCRUTINIZER_SHA1,build:e.SCRUTINIZER_INSPECTION_UUID,branch:e.SCRUTINIZER_BRANCH,pr:t,isPr:r,prBranch:e.SCRUTINIZER_PR_SOURCE_BRANCH}}},up={detect:({env:e})=>Boolean(e.SEMAPHORE),configuration({env:e,cwd:t}){const r=e.SEMAPHORE_GIT_PR_NUMBER||e.PULL_REQUEST_NUMBER,n=Boolean(r);return{name:"Semaphore",service:"semaphore",commit:e.SEMAPHORE_GIT_SHA||Hd({env:e,cwd:t}),tag:e.SEMAPHORE_GIT_TAG_NAME,build:e.SEMAPHORE_JOB_ID||e.SEMAPHORE_BUILD_NUMBER,branch:e.SEMAPHORE_GIT_BRANCH||(n?void 0:e.BRANCH_NAME),pr:r,isPr:n,prBranch:e.SEMAPHORE_GIT_PR_BRANCH||(n?e.BRANCH_NAME:void 0),slug:e.SEMAPHORE_GIT_REPO_SLUG||e.SEMAPHORE_REPO_SLUG,root:e.SEMAPHORE_GIT_DIR||e.SEMAPHORE_PROJECT_DIR}}},dp={detect:({env:e})=>Boolean(e.SHIPPABLE),configuration({env:e}){const t="true"===e.IS_PULL_REQUEST?e.PULL_REQUEST:void 0,r=Boolean(t);return{name:"Shippable",service:"shippable",commit:e.COMMIT,tag:e.GIT_TAG_NAME,build:e.BUILD_NUMBER,buildUrl:e.BUILD_URL,branch:r?e.BASE_BRANCH:e.BRANCH,job:e.JOB_NUMBER,pr:t,isPr:r,prBranch:r?e.HEAD_BRANCH:void 0,slug:e.SHIPPABLE_REPO_SLUG,root:e.SHIPPABLE_BUILD_DIR}}},pp={};function fp(){if(zd)return pp;zd=1,Object.defineProperty(pp,"__esModule",{value:!0}),pp.of=pp.PropertiesFile=void 0;var e,t=(e=F)&&e.__esModule?e:{default:e};class r{constructor(...e){this.objs={},e.length&&this.of.apply(this,e)}makeKeys(e){if(e&&0!==e.indexOf("#")){let t=["=",":"].map(t=>e.indexOf(t)).filter(e=>e>-1),r=Math.min(...t),n=e.substring(0,r).trim(),s=e.substring(r+1).trim();if(this.objs.hasOwnProperty(n))if(Array.isArray(this.objs[n]))this.objs[n].push(s);else{let e=this.objs[n];this.objs[n]=[e,s]}else{const e=s.replace(/"/g,'\\"').replace(/\\:/g,":").replace(/\\=/g,"=");this.objs[n]=unescape(JSON.parse('"'+e+'"'))}}}addFile(e){let r=t.default.readFileSync(e,"utf-8").split(/\r?\n/),n=this;for(let e=0;e<r.length;e++){let t=r[e];for(;"\\"===t.substring(t.length-1);)t=t.slice(0,-1),t+=r[e+1].trim(),e++;n.makeKeys(t)}}of(...e){for(let t=0;t<e.length;t++)this.addFile(e[t])}get(e,t){if(this.objs.hasOwnProperty(e)){if(Array.isArray(this.objs[e])){let t=[];for(let r=0;r<this.objs[e].length;r++)t[r]=this.interpolate(this.objs[e][r]);return t}return void 0===this.objs[e]?"":this.interpolate(this.objs[e])}return t}getLast(e,t){if(this.objs.hasOwnProperty(e)){if(Array.isArray(this.objs[e])){var r=this.objs[e].length;return this.interpolate(this.objs[e][r-1])}return void 0===this.objs[e]?"":this.interpolate(this.objs[e])}return t}getFirst(e,t){return this.objs.hasOwnProperty(e)?Array.isArray(this.objs[e])?this.interpolate(this.objs[e][0]):void 0===this.objs[e]?"":this.interpolate(this.objs[e]):t}getInt(e,t){let r=this.getLast(e);return r?parseInt(r,10):t}getFloat(e,t){let r=this.getLast(e);return r?parseFloat(r):t}getBoolean(e,t){let r=this.getLast(e);return r?!/^(false|0)$/i.test(n=r)&&!!n:t||!1;var n}set(e,t){this.objs[e]=t}interpolate(e){let t=this;return e.replace(/\\\\/g,"\\").replace(/\$\{([A-Za-z0-9\.\-\_]*)\}/g,function(e){return t.getLast(e.substring(2,e.length-1))})}getKeys(){let e=[];for(let t in this.objs)e.push(t);return e}getMatchingKeys(e){let t=[];for(let r in this.objs)-1!==r.search(e)&&t.push(r);return t}reset(){this.objs={}}}return pp.PropertiesFile=r,pp.of=function(...e){let t=new r;return t.of.apply(t,e),t},pp}var hp=ju(fp()),gp={root:"teamcity.build.workingDir",branch:"teamcity.build.branch"},mp=e=>{try{return hp.of(e)}catch{return}},yp=({env:e,cwd:t})=>{const r=e.TEAMCITY_BUILD_PROPERTIES_FILE?mp(e.TEAMCITY_BUILD_PROPERTIES_FILE):void 0,n=r?r.get("teamcity.configuration.properties.file"):void 0,s=n?mp(n):n;return Object.fromEntries(Object.keys(gp).map(n=>[n,(r?r.get(gp[n]):void 0)||(s?s.get(gp[n]):void 0)||("branch"===n?Gd({env:e,cwd:t}):void 0)]))},bp={appveyor:Pu,azurePipelines:Lu,bamboo:Du,bitbucket:$u,bitrise:Ou,buddy:Nu,buildkite:Kd,circleci:qd,cirrus:Xd,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:Qd,codefresh:Zd,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:ep,github:rp,gitlab:np,jenkins:sp,netlify:op,puppet:ip,sail:ap,screwdriver:cp,scrutinizer:lp,semaphore:up,shippable:dp,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,...yp({env:e,cwd:t})})},travis:{detect:({env:e})=>Boolean(e.TRAVIS),configuration({env:e}){const t="false"===e.TRAVIS_PULL_REQUEST?void 0:e.TRAVIS_PULL_REQUEST,r=Boolean(t);return{name:"Travis CI",service:"travis",commit:e.TRAVIS_COMMIT,tag:e.TRAVIS_TAG,build:e.TRAVIS_BUILD_NUMBER,buildUrl:e.TRAVIS_BUILD_WEB_URL,branch:e.TRAVIS_BRANCH,job:e.TRAVIS_JOB_NUMBER,jobUrl:e.TRAVIS_JOB_WEB_URL,pr:t,isPr:r,prBranch:e.TRAVIS_PULL_REQUEST_BRANCH,slug:e.TRAVIS_REPO_SLUG,root:e.TRAVIS_BUILD_DIR}}},vela:{detect:({env:e})=>Boolean(e.VELA),configuration({env:e}){const t="pull_request"===e.VELA_BUILD_EVENT;return{name:"Vela",service:"vela",branch:t?e.VELA_PULL_REQUEST_TARGET:e.VELA_BUILD_BRANCH,commit:e.VELA_BUILD_COMMIT,tag:e.VELA_BUILD_TAG,build:e.VELA_BUILD_NUMBER,buildUrl:e.VELA_BUILD_LINK,job:void 0,jobUrl:void 0,isPr:t,pr:e.VELA_BUILD_PULL_REQUEST,prBranch:e.VELA_PULL_REQUEST_SOURCE,slug:e.VELA_REPO_FULL_NAME,root:e.VELA_BUILD_WORKSPACE}}},vercel:{detect:({env:e})=>Boolean(e.VERCEL)||Boolean(e.NOW_GITHUB_DEPLOYMENT),configuration({env:e}){const t="Vercel",r="vercel";return e.VERCEL?{name:t,service:r,commit:e.VERCEL_GIT_COMMIT_SHA,branch:e.VERCEL_GIT_COMMIT_REF,slug:`${e.VERCEL_GIT_REPO_OWNER}/${e.VERCEL_GIT_REPO_SLUG}`}:{name:t,service:r,commit:e.NOW_GITHUB_COMMIT_SHA,branch:e.NOW_GITHUB_COMMIT_REF,slug:`${e.NOW_GITHUB_ORG}/${e.NOW_GITHUB_REPO}`}}},wercker:{detect:({env:e})=>Boolean(e.WERCKER_MAIN_PIPELINE_STARTED),configuration:({env:e})=>({name:"Wercker",service:"wercker",commit:e.WERCKER_GIT_COMMIT,build:e.WERCKER_MAIN_PIPELINE_STARTED,buildUrl:e.WERCKER_RUN_URL,branch:e.WERCKER_GIT_BRANCH,slug:`${e.WERCKER_GIT_OWNER}/${e.WERCKER_GIT_REPOSITORY}`,root:e.WERCKER_ROOT})},woodpecker:{detect:({env:e})=>e.CI&&"woodpecker"===e.CI,configuration({env:e}){const t="pull_request"===e.CI_PIPELINE_EVENT;return{name:"Woodpecker CI",service:"woodpecker",commit:e.CI_COMMIT_SHA,tag:e.CI_COMMIT_TAG,build:e.CI_PIPELINE_NUMBER,buildUrl:e.CI_PIPELINE_URL,branch:t?e.CI_COMMIT_TARGET_BRANCH:e.CI_COMMIT_BRANCH,job:e.CI_STEP_NUMBER,jobUrl:e.CI_STEP_URL,pr:e.CI_COMMIT_PULL_REQUEST,isPr:t,prBranch:t?e.CI_COMMIT_SOURCE_BRANCH:void 0,slug:`${e.CI_REPO_OWNER}/${e.CI_REPO_NAME}`,root:e.CI_WORKSPACE}}},jetbrainsSpace:{detect:({env:e})=>Boolean(e.JB_SPACE_EXECUTION_NUMBER),configuration({env:e}){const t=e.JB_SPACE_PROJECT_KEY,r=e.JB_SPACE_GIT_REPOSITORY_NAME;return{name:"JetBrains Space",service:"jetbrainsSpace",commit:e.JB_SPACE_GIT_REVISION,build:e.JB_SPACE_EXECUTION_NUMBER,branch:Uu(e.JB_SPACE_GIT_BRANCH),slug:t&&r?`${t.toLowerCase()}/${r}`:void 0}}}};Iu(),vo(),Wn(),Kn(),Nn();var wp=S.object({runId:S.string(),timestamp:S.number()});On(),Bn(),Un(),Kn(),Mn(),Ln(),Kn(),Vn(),qn(),Co(),Vn(),Vn(),Bc();var vp=[{args:["--trace=on"],description:"Run Playwright tests",name:"test"},{args:[],description:"Install browser dependencies",name:"install"}],Ip=["You have two different versions of @playwright/test"];function _p(e){const[t,...r]=fc(e),n=[t,...r.slice(0,-1)].join(" ");return(t,r)=>{let s=t.toString();for(const e of vp)s=s.replaceAll(`${n} playwright ${e.name}`,`${n} stably ${e.name}`).replaceAll(`npx playwright ${e.name}`,`npx stably ${e.name}`);if("yarn"===e){const e=s.split("\n");return e.length>0&&(e[0].includes("/.bin/playwright")||e[0].includes("\\.bin\\playwright"))&&e.shift(),void r.write(e.join("\n"))}r.write(s)}}async function Tp({overrideArgs:e,subcommand:t}){fn.info("[test] forwardToPlaywright starting",{subcommand:t,overrideArgs:e});const r=process.argv,n=r.findIndex((e,r)=>r>1&&e===t),c=-1===n?[]:r.slice(n+1),l="--"===c[0],u=l?c.slice(1):c;if(!l&&("--help"===u[0]||"-h"===u[0]))return async function({subcommand:e}){const t=vp.find(t=>t.name===e),r=e=>process.stdout.write(`${e}\n`);r(`stably ${e} - ${t?.description??""}`),r(""),"test"===e&&(r('IMPORTANT: Always use "stably" commands instead of "playwright" directly.'),r(""),r("Stably commands:"),r(" stably test [file] Run tests (auto-enables tracing and analytics)"),r(" stably fix [file] Auto-fix failing tests using AI"),r(" stably create <url> Generate new tests from a URL using AI"),r(""),r("Why use Stably?"),r(' - "stably fix" automatically repairs broken tests'),r(' - "stably test" enables --trace=on and test analytics'),r(' - "stably create" generates tests from prompt'),r(""));const n=uc();if(!n.installed||!n.inNodeModules)return void r('No Playwright project found in this directory or its parents.\nMake sure you\'re in a directory within your Playwright project, or run "stably init" to create a new playwright directory.');const{packageManager:s}=n;if(!s)return void r("Could not determine package manager.");r("Playwright options:"),r("");const[o,...i]=fc(s),a=_p(s);return new Promise(t=>{const r=oe(o,[...i,e,"--help"],{stdio:["inherit","pipe","pipe"],shell:"win32"===process.platform,env:{...process.env,...process.env.CI?{}:{FORCE_COLOR:"1"}}});r.stdout?.on("data",e=>{a(e,process.stdout)}),r.stderr?.on("data",e=>{a(e,process.stderr)}),r.on("close",()=>{t()})})}({subcommand:t});const d=e??[],p=new Set(d.map(e=>{const[t]=e.split("=");return t})),f=[];for(let e=0;e<u.length;e++){const t=u[e],[r]=t.split("=");p.has(r)?!t.includes("=")&&e+1<u.length&&!u[e+1].startsWith("-")&&e++:f.push(t)}const h=[t,...d,...f];fn.info("[test] Forwarded args computed",{forwardedArgs:h}),fn.info("[test] Resolving Stably test environment");const g=Date.now(),m="test"===t?await(async()=>{fn.info("[test] Resolving Stably test env");const e=(()=>{if(process.env.STABLY_WS_URL)return;if("https://api.stably.ai"===Gt)return;const e=Gt.startsWith("http://")?"ws://":"wss://";return`${Gt.replace(/^https?:\/\//,e).replace(/\/$/,"")}/reporter`})();fn.debug("[test] WebSocket URL resolved",{wsUrl:e??"(default)"});const t=wn();if(t)return fn.info("[test] Using env var auth (STABLY_API_KEY + STABLY_PROJECT_ID)"),{STABLY_API_KEY:t.apiKey,STABLY_PROJECT_ID:t.projectId,...e&&{STABLY_WS_URL:e}};fn.info("[test] No env var auth, attempting OAuth auth");const r=Date.now(),n=await _n();if(fn.info("[test] OAuth auth resolved",{durationMs:Date.now()-r,hasAuth:!!n,authType:n?.type}),!n||"env"===n.type)return void fn.info("[test] No usable auth found");const s=process.env.STABLY_PROJECT_ID?.trim(),o=s||Tn(n);if(!o)return void fn.warn("[test] No project ID available");fn.info("[test] Fetching JWT API key",{projectId:o});const i=Date.now(),a=await(async(e,t)=>{try{fn.debug("Requesting JWT API key",{projectId:t,apiUrl:Gt});const r=await xr({accessToken:e,projectId:t});return fn.debug("JWT API key obtained",{keyPrefix:r.apiKey.substring(0,10)}),r.apiKey}catch(e){return void fn.warn("Failed to get JWT API key for test reporter",{error:e instanceof Error?e.message:String(e)})}})(n.auth.accessToken,o);fn.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 fn.info("[test] Stably test env resolved",{hasApiKey:!!c?.STABLY_API_KEY,projectId:c?.STABLY_PROJECT_ID,wsUrl:c?.STABLY_WS_URL??process.env.STABLY_WS_URL??"(default)"}),c})():void 0;fn.info("[test] Stably test environment resolved",{durationMs:Date.now()-g,hasCredentials:null!=m,hasWsUrl:!!m?.STABLY_WS_URL}),fn.info("[test] Loading remote environment variables");const y=await Sn();fn.info("[test] Remote environment loaded",{hasRemoteEnv:!!y,variableCount:y?Object.keys(y.variables).length:0});const b={...y?.variables,...y?.sensitiveValues.length?{STABLY_SENSITIVE_VALUES:Buffer.from(JSON.stringify(y.sensitiveValues)).toString("base64")}:{}};fn.info("[test] Setting up Stably reporter injection");const w="test"===t?function({forwardedArgs:e,hasCredentials:t}){if(!t){console.warn("[33m⚠️ Stably credentials not found. Test results will not be reported to Stably.[0m");const e=gn();if("local"!==e){const t=yn(e);console.warn(`[33m To enable reporting, add the following to your ${t}:[0m`),console.warn("[33m • STABLY_API_KEY → https://app.stably.ai/settings?tab=api-key[0m"),console.warn("[33m • STABLY_PROJECT_ID → https://app.stably.ai/settings?tab=project-id[0m\n")}else console.warn("[33m To enable reporting, either:[0m"),console.warn("[33m • Run `npx stably login` to authenticate[0m"),console.warn("[33m • Or set STABLY_API_KEY and STABLY_PROJECT_ID environment variables[0m\n");return}const r=process.cwd(),n=e=>{const t=function(e){let t=s(e);for(;;){if([i(t,"node_modules","@stablyai","playwright-test"),i(t,"node_modules",".pnpm","@stablyai+playwright-test")].some(e=>H(e)))return!0;const e=o(t);if(e===t)return!1;t=e}}(e);return t||(console.warn("[33m⚠️ @stablyai/playwright-test is not installed. Stably reporter will not be injected.[0m"),console.warn("[33m Install it with: npm install @stablyai/playwright-test[0m"),console.warn("[33m Reference: ]8;;https://docs.stably.ai/getting-started/sdk-setup-guidehttps://docs.stably.ai/getting-started/sdk-setup-guide]8;;[0m\n")),t},c=(e,t)=>{try{return function({baseConfigPath:e,projectDir:t}){const r=function(e){try{const t=se("npm pkg get type",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return"module"===JSON.parse(t.trim())}catch{return!1}}(t),n=r?"mts":"ts",c=o(s(e)),l=a(e),u=i(c,`.stably-playwright-wrapper.config.${n}`),d=`\n// Auto-generated wrapper config by Stably CLI\n// This file injects the Stably reporter and ensures trace is enabled\nimport baseConfig from './${l}';\nimport { defineConfig, stablyReporter } from '@stablyai/playwright-test';\n\n// Inline type definitions to avoid import failures when @stablyai/playwright-test is not installed\ntype StablyNotificationConfig = {\n email?: { to: string[]; notifyOnStart?: boolean; notifyOnResult?: 'all' | 'failures-only' | null } | null;\n slack?: { channelName: string; notifyOnStart?: boolean; notifyOnResult?: 'all' | 'failures-only' } | null;\n};\n\ntype ProjectNotificationConfig = {\n projectName: string;\n notifications: StablyNotificationConfig;\n};\n\n// Extract notification configs from projects that have stably.notifications defined\n// This runs at config-load time before Playwright strips custom properties\nconst extractNotificationConfigs = (): ProjectNotificationConfig[] | undefined => {\n const projects = baseConfig.projects;\n if (!projects || !Array.isArray(projects)) return undefined;\n\n const configs = projects\n .map((p: { name?: string; stably?: { notifications?: StablyNotificationConfig } }) => {\n const notifications = p.stably?.notifications;\n return notifications ? { projectName: p.name ?? '', notifications } : undefined;\n })\n .filter((config): config is ProjectNotificationConfig => config != null);\n\n return configs.length > 0 ? configs : undefined;\n};\n\nconst isStablyReporter = (reporter: unknown): boolean => {\n // Only match @stablyai npm scope to avoid false positives on unrelated reporters\n // that might contain "stably" substring (e.g., "unstably-runner")\n if (typeof reporter === 'string') {\n return reporter.includes('@stablyai');\n }\n if (Array.isArray(reporter) && typeof reporter[0] === 'string') {\n return reporter[0].includes('@stablyai');\n }\n return false;\n};\n\nconst getStablyReporterOptions = (reporters: unknown[]): Record<string, unknown> | undefined => {\n for (const reporter of reporters) {\n if (Array.isArray(reporter) && typeof reporter[0] === 'string' && reporter[0].includes('@stablyai')) {\n return (reporter[1] as Record<string, unknown>) ?? {};\n }\n }\n return undefined;\n};\n\nconst filterOutStablyReporter = (reporters: unknown[]): unknown[] => {\n return reporters.filter((reporter) => !isStablyReporter(reporter));\n};\n\n// Decode sensitive values from env var (set by CLI --env flag)\nconst decodeSensitiveValues = (): string[] | undefined => {\n const encoded = process.env.STABLY_SENSITIVE_VALUES;\n if (!encoded) return undefined;\n try {\n const decoded: unknown = JSON.parse(Buffer.from(encoded, 'base64').toString('utf-8'));\n return Array.isArray(decoded) ? decoded.filter((v): v is string => typeof v === 'string') : undefined;\n } catch {\n return undefined;\n }\n};\n\nconst buildReporterList = () => {\n const existingReporters = baseConfig.reporter;\n const sensitiveValues = decodeSensitiveValues();\n\n // Resolve errorSummary: env var STABLY_ERROR_SUMMARY=0 disables it\n const resolveErrorSummary = (existingValue?: unknown): boolean | undefined => {\n if (process.env.STABLY_ERROR_SUMMARY === '0') return false;\n if (typeof existingValue === 'boolean') return existingValue;\n return undefined; // let the reporter default (true)\n };\n\n // No existing reporters - create fresh stably reporter\n if (!existingReporters) {\n return [stablyReporter({\n apiKey: process.env.STABLY_API_KEY,\n cliVersion: '${Ht}',\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: '${Ht}',\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 H(c)||Y(c,{recursive:!0}),W(u,d,"utf-8"),function(e){const t=i(e,".gitignore");try{if(H(t)){const e=G(t,"utf-8");if(e.split("\n").map(e=>e.trim()).includes(bo))return;const r=e.length>0&&!e.endsWith("\n");V(t,`${r?"\n":""}${bo}\n`)}else W(t,`${bo}\n`)}catch{}}(c),u}({baseConfigPath:e,projectDir:t})}catch{return void console.warn("[33m⚠️ Could not create Stably wrapper config. Reporter injection skipped.[0m")}};if(e.some(e=>"--config"===e||"-c"===e||e.startsWith("--config=")||e.startsWith("-c="))){const t=e.findIndex(e=>"--config"===e||"-c"===e);if(-1!==t&&e[t+1]){const i=s(r,e[t+1]),a=o(i);if(!n(a))return;const l=c(i,a);if(!l)return;return e[t+1]=l,l}const i=e.findIndex(e=>e.startsWith("--config=")||e.startsWith("-c="));if(-1!==i){const t=s(r,e[i].split("=")[1]),a=o(t);if(!n(a))return;const l=c(t,a);if(!l)return;const u=e[i].startsWith("--config=")?"--config=":"-c=";return e[i]=`${u}${l}`,l}}const l=xo(r);if(!l)return;const u=o(l);if(!n(u))return;const d=c(l,u);return d?(e.push("--config",d),d):void 0}({forwardedArgs:h,hasCredentials:null!=m}):void 0;fn.info("[test] Reporter injection setup complete",{hasWrapperConfig:!!w}),fn.info("[test] Spawning Playwright process"),await function(e,t={}){fn.info("[test] Detecting Playwright installation");const r=uc();fn.info("[test] Playwright installation check",{installed:r.installed,inNodeModules:r.inNodeModules,packageManager:r.packageManager,packageName:r.packageName}),r.installed||(console.error('Playwright is not installed. Please run "stably init" to install it.'),process.exit(1)),r.inNodeModules||(console.error("Playwright is present in your project, but not in node_modules. Please install your dependencies before proceeding."),process.exit(1));const{packageManager:n}=r;n||(console.error("Playwright installation not found. Could not determine your package manager (tried pnpm, yarn, and npm)."),process.exit(1));const[s,...o]=fc(n),i=(a=t.env)?{...process.env,...a}:process.env;var a;const c=[s,...o,...e];fn.info("[test] Spawning Playwright process",{command:c.join(" "),pid:process.pid});const l=Date.now(),u=oe(s,[...o,...e],{stdio:["inherit","pipe","pipe"],shell:"win32"===process.platform,env:{...i,...process.env.CI?{}:{FORCE_COLOR:"1"}}});fn.info("[test] Playwright process spawned",{childPid:u.pid});const d=_p(n),p=function(){let e=!1,t="";return(r,n)=>{if(!e){t+=r,t.length>1024&&(t=t.slice(-1024));for(const r of Ip)if(t.includes(r))return n.write("\n[stably] Hint: This is a Playwright error, not caused by @stablyai/playwright-test.\n Common causes: running from the wrong directory (especially in monorepos),\n or a dependency pulling in a conflicting @playwright/test version.\n"),void(e=!0)}}}();u.stdout?.on("data",e=>{d(e,process.stdout)}),u.stderr?.on("data",e=>{const t=e.toString();d(e,process.stderr),p(t,process.stderr)});const f=new AbortController,h=()=>!f.signal.aborted&&(f.abort(),t.onClose?.(),process.removeListener("SIGINT",g),process.removeListener("SIGTERM",g),!0),g=e=>{fn.info("[test] Signal received, killing Playwright process",{signal:e,childPid:u.pid}),h(),u.kill(e);const t="SIGINT"===e?130:143;process.exit(t)};return process.on("SIGINT",g),process.on("SIGTERM",g),new Promise((e,t)=>{u.on("error",e=>{h()&&(fn.error("[test] Playwright process error",{error:e.message,childPid:u.pid}),t(e))}),u.on("close",t=>{if(!h())return;fn.info("[test] Playwright process exited",{exitCode:t,durationMs:Date.now()-l});const r=[process.stdout,process.stderr].filter(e=>e.writableNeedDrain).map(e=>new Promise(t=>e.once("drain",t)));Promise.race([Promise.all(r),new Promise(e=>setTimeout(e,5e3))]).then(()=>{process.exitCode=t??0,e(t??0)})})})}(h,{env:{...b,...m},onClose:()=>{var e;fn.info("[test] Playwright process closed, cleaning up wrapper config"),(e=w)&&H(e)&&z(e)}})}function Ep(e){const t=new Date(e),r=new Date,n=r.getTime()-t.getTime(),s=Math.floor(n/1e3),o=Math.floor(s/60),i=Math.floor(o/60),a=Math.floor(i/24);if(s<60)return"just now";if(o<60)return`${o}m ago`;if(i<24)return`${i}h ago`;if(a<=7)return`${a}d ago`;const c=t.toLocaleString("en-US",{month:"short"}),l=t.getDate();return t.getFullYear()===r.getFullYear()?`${c} ${l}`:`${c} ${l}, ${t.getFullYear()}`}kn(),Kn(),Dn(),Vn(),kn(),Kn(),Dn(),Xn(),Vn();var Sp={PASSED:N.green,FAILED:N.red,TIMEDOUT:N.red,CANCELLED:N.yellow,INTERRUPTED:N.yellow,RUNNING:N.cyan,QUEUED:N.dim},xp=(e,t)=>e?e.length>t?`${e.slice(0,t-1)}…`:e:"-",Ap=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")}`},Cp=e=>(Sp[e]??(e=>e))(e),Rp=/\x1b\[[0-9;]*m/g,Pp=(e,t)=>{const r=e.replace(Rp,"").length,n=Math.max(0,t-r);return e+" ".repeat(n)},kp=e=>`${JSON.stringify(e,null,2)}\n`,Up=e=>"oauth"===e.type?e.auth.context.orgId:void 0,Lp=(e,t,r)=>{if(!e)return;const n=e.toUpperCase();if(t.includes(n))return n;k(N.red(`Invalid ${r} value "${e}". Must be one of: ${t.join(", ").toLowerCase()}`)),process.exit(1)},Dp=(e,t,r)=>{if(401!==e.response.status&&403!==e.response.status||(k(N.red("Access denied.")),process.exit(1)),404===e.response.status&&r&&(k(N.red(r)),process.exit(1)),400===e.response.status){const t=e.error&&"object"==typeof e.error&&"error"in e.error?e.error.error:"Bad request";k(N.red(t)),process.exit(1)}e.error&&(k(N.red(`Failed to ${t}: ${e.response.status}`)),process.exit(1))};Kn();var $p="stably",Op=`https://registry.npmjs.org/${$p}/latest`;function Np(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 Bp(e,t){const r=Np(e),n=Np(t);return!(!r||!n)&&(n.major>r.major||!(n.major<r.major)&&(n.minor>r.minor||!(n.minor<r.minor)&&n.patch>r.patch))}Un();var jp=n.join(d.homedir(),".stably"),Mp=n.join(jp,"update-check.json"),Fp="1"===process.env.STABLY_DISABLE_UPDATE_CHECK,Hp=x.object({lastCheck:x.number(),latestVersion:x.string()}),Gp=Symbol.for("stably.updateNotifier.registered");function Yp(e=""){process.stdout.write(`${e}\n`)}function Wp(...e){process.stderr.write(`${e.join(" ")}\n`)}Un();var Vp=x.object({version:x.string()});Un(),Vn(),Un();var zp=!1,Kp=async()=>{if(zp)try{const{shutdown:e}=await import("@hyperdx/node-opentelemetry"),t=process.stderr.write.bind(process.stderr),r=process.stdout.write.bind(process.stdout),n=(e,...t)=>{const r=t[0];return!("string"!=typeof r||!r.includes("OpenTelemetry"))||!(!Buffer.isBuffer(r)||!r.toString().includes("OpenTelemetry"))||e(...t)};process.stderr.write=(...e)=>n(t,...e),process.stdout.write=(...e)=>n(r,...e);try{await e()}finally{process.stderr.write=t,process.stdout.write=r}}catch{}},qp=e=>{const t=e.toLowerCase();return t.startsWith("npm_config_")||"node_options"===t};!function(){if(Fp||function(e=process.argv.slice(2)){return e.includes("upgrade")}())return;const e=function(){try{const e=F.readFileSync(Mp,"utf-8");return Hp.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 = '${Op}';\n const cacheFile = ${JSON.stringify(Mp)};\n const cacheDir = ${JSON.stringify(jp)};\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{oe(process.execPath,["--input-type=module","-e",e],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()}catch{}}(),null!=e&&Bp(Ht,e.latestVersion)){if(!0===process[Gp])return;process[Gp]=!0;let t=!1;const r=()=>{if(t)return;t=!0;const r=`${N.yellow(`update available (${Ht} → ${e.latestVersion})`)} - run \`${$p} upgrade\` to get the latest version\n`;try{F.writeSync(2,r)}catch{}};process.once("beforeExit",r),process.once("exit",r)}}(),Ue.cwdChanged&&fn.debug("Changed working directory",{cwd:Ue.newCwd});for(const e of Ue.envFilesLoaded)fn.debug("Loaded env file",{path:e});for(const e of Ue.envFileErrors)fn.warn(e);var Jp=process.argv.findIndex(e=>"-v"===e||"--verbose"===e);-1!==Jp&&process.argv.splice(Jp,1);var Xp=process.argv.findIndex(e=>"--no-telemetry"===e);-1!==Xp&&process.argv.splice(Xp,1),fn.info("CLI starting",{version:Ht,args:process.argv.slice(2),cwd:process.cwd()}),process.on("unhandledRejection",(e,t)=>{fn.error("Unhandled promise rejection",{reason:e instanceof Error?{message:e.message,stack:e.stack}:e,promise:String(t)}),fn.flush(),fn.printLogFileInfo()}),process.on("uncaughtException",(e,t)=>{"EPIPE"!==e.code&&(fn.error("Uncaught exception",{error:{message:e.message,stack:e.stack,name:e.name},origin:t}),fn.flush(),fn.printLogFileInfo())});var Qp=new Ae;Qp.name("stably").description("AI-assisted Playwright testing CLI").version(Ht),Qp.enablePositionalOptions(),Qp.showHelpAfterError(),Qp.exitOverride(),Qp.configureHelp({subcommandTerm:e=>{const t=e.registeredArguments.map(e=>e.required?`<${e.name()}>`:`[${e.name()}]`).join(" ");return t?`${e.name()} ${t}`:e.name()}});var Zp=[];Qp.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>{Zp.push(e)}});var ef=()=>{const e=Qp.helpInformation().trimEnd();return e?`${e}\n`:""},tf=(e,t)=>{let r=e;for(const e of t){const t=r.commands.find(t=>t.name()===e||t.aliases().includes(e));if(!t)return;r=t}return r},rf=()=>{process.stdout.write(ef())};Qp.command("help [command...]").description("Show help for a command (e.g. stably help create)").action(e=>{if(!e||0===e.length)return void rf();const t=tf(Qp,e);if(!t)return process.stderr.write(`Unknown command: ${e.join(" ")}\n`),rf(),void(process.exitCode=1);var r;r=t,process.stdout.write((e=>{const t=e.helpInformation().trimEnd();return t?`${t}\n`:""})(r))}),Qp.action(()=>mu({mode:"chat",getHelpText:ef})),Qp.command("login").description("Authenticate with Stably in your browser").action(Mr),Qp.command("logout").description("Clear stored Stably credentials").action(Fr),Qp.command("whoami").description("Show auth status and current project").action(async()=>{P.info(`${N.bold("CLI Version:")} ${N.cyan(Ht)}`);const e=wn();if(e){P.info(N.dim("Authentication: Environment variables")),P.info(` ${N.bold("API Key:")} ${N.cyan(e.apiKey.slice(0,8))}...`),P.info(` ${N.bold("Project ID:")} ${N.cyan(e.projectId)}`);const t=await fr();if(t){let e;try{e=sr(t.accessToken).email}catch{e=void 0}P.warn("Stored OAuth login detected but will be ignored (env auth takes precedence)."),e&&P.info(` ${N.bold("OAuth Email:")} ${N.cyan(e)}`),P.info(` ${N.bold("Tip:")} Unset env vars to use OAuth`)}return void k(N.green("Authenticated via environment variables"))}const t=await fr();if(!t)return void k(N.yellow("Not logged in. Run `stably login` to authenticate."));let r;try{r=sr(t.accessToken).email}catch{r=void 0}const s=await yr();if(!s)return P.info(N.dim("Authentication: OAuth (not linked to a project)")),r&&P.info(` ${N.bold("Email:")} ${N.cyan(r)}`),void k(N.yellow("Logged in but this directory is not linked to a project. Run `stably login` to link."));const o=await vr(),i=o?n.dirname(o):process.cwd(),a=n.relative(process.cwd(),i)||".";P.info(N.dim("Authentication: OAuth")),r&&P.info(` ${N.bold("Email:")} ${N.cyan(r)}`),P.info(` ${N.bold("Organization:")} ${N.cyan(s.orgName)}`),P.info(` ${N.bold("Project:")} ${N.cyan(s.projectName)}`),P.info(` ${N.bold("Linked at:")} ${N.dim(a)}`),k(N.green("Authenticated"))}),Qp.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=>{U(`Starting development server for port ${e.port}...`);const t=await In(),r="oauth"===t.type?`${t.auth.context.orgName}-${t.auth.context.projectName}`.toLowerCase().replace(/[^a-z0-9-]/g,""):`project-${t.auth.projectId}`.toLowerCase(),n=L();n.start("Starting development server...");const s=await ke(`http://localhost:${e.port}`,{subdomain:r});n.stop(`Your local environment is available at: ]8;;${s.url}${N.underline(N.cyan(s.url))}]8;;`)}),Qp.command("create [prompt...]").description("Generate a test from prompt (omit prompt to infer from branch diff)").option("-o, --output <dir>","Output directory for generated test files").action(async(e,t)=>{const r=e.length>0&&"test"===e[0]?e.slice(1):e;return mu({mode:"single",prompt:r,outputDir:t.output})}).command("test",{hidden:!0}).description("Generate a Playwright test from a prompt (deprecated: use `stably create <prompt>` directly)").argument("<prompt...>","Prompt describing the test to generate").option("-o, --output <dir>","Output directory for generated test files").action(async(e,t)=>mu({mode:"single",prompt:e,outputDir:t.output})),Qp.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 mu({mode:"verify",prompt:e,url:t.url,maxBudgetUsd:t.maxBudget,interactive:t.interactive})}),Qp.command("internal-fix-run <runId>",{hidden:!0}).description("Internal: run fix session in subprocess").action(async e=>{const t=process.env.STABLY_FIX_ISSUES,r=t?t.split(",").filter(Boolean):void 0,n=process.env.STABLY_PARTIAL_REPORT_ID||void 0;await mu({mode:"fix",runId:e,issues:r,partialReportId:n});const s=process.env.STABLY_PARTIAL_REPORT_S3_PRESIGNED_URL;if(n&&s){const{readFile:e}=await import("fs/promises"),{join:t}=await import("path"),{uploadToPresignedUrl:r}=await Promise.resolve().then(()=>(hs(),Zn)),o=t(process.cwd(),".stably","partial-reports",`${n}.json`),i=await e(o,"utf-8");await r({body:i,contentType:"application/json",uploadUrl:s,errorContext:"partial report"}),fn.info("[fix] Partial report uploaded to S3",{partialReportId:n})}}),Qp.command("internal-triage <runId>",{hidden:!0}).description("Internal: run triage-only session, output structured JSON to S3").action(async e=>{const{runTriageCommand:t}=await Promise.resolve().then(()=>(Su(),Tu));return t({runId:e})}),Qp.command("internal-merge-reports <runId>",{hidden:!0}).description("Internal: merge partial fix reports from S3").action(async e=>{const{runMergeReportsCommand:t}=await Promise.resolve().then(()=>(Ru(),Au));return t({runId:e})}),Qp.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 se("git rev-parse --is-inside-work-tree",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}})(process.cwd())||(fn.error('Not a git repository. The "stably fix" command requires a git repository to track changes made during the fix. Please run this command from inside a git repository.'),process.stderr.write('Error: Not a git repository.\nThe "stably fix" command requires a git repository to track changes made during the fix.\nPlease run this command from inside a git repository.\n'),process.exit(1));const t=await(async e=>{const t=e=>e.replace(/\//g,"_");if(e)return fn.debug("Run ID provided explicitly",{runId:e}),t(e);const r=function(){if(process.env.CI_BUILD_ID)return process.env.CI_BUILD_ID;const e=(({env:e=process.env,cwd:t=process.cwd()}={})=>{for(const r of Object.keys(bp))if(bp[r].detect({env:e,cwd:t}))return{isCi:!0,...bp[r].configuration({env:e,cwd:t})};return{isCi:Boolean(e.CI),...(r={env:e,cwd:t},{commit:Hd(r),branch:Gd(r)})};var r})();if(!e.isCi)return;const t=function(e){switch(e){case"github":return process.env.GITHUB_RUN_ATTEMPT;case"azure-devops":return process.env.SYSTEM_JOBATTEMPT;case"bitbucket":return process.env.BITBUCKET_STEP_RUN_NUMBER;default:return}}(e.service),r=[e.service,"slug"in e?e.slug?.replace(/\//g,"_"):void 0,"build"in e?String(e.build):void 0,"job"in e?String(e.job):void 0,t&&String(t)].filter(Boolean);return r.length>0?r.join("-"):void 0}();if(r)return fn.debug("Run ID detected from CI environment",{runId:r}),t(r);fn.debug("No explicit run ID or CI environment detected, checking last-run.json");const n=await(async()=>{try{const e=await ir(process.cwd(),".stably/last-run.json");if(!e)return;const t=await m(e,"utf-8");return{...wp.parse(JSON.parse(t)),filePath:e}}catch{return}})();if(n){const e=(Date.now()-n.timestamp)/36e5;return fn.debug("Run ID found in last-run.json",{runId:n.runId,timestamp:n.timestamp,filePath:n.filePath,ageHours:Math.round(e)}),e>24&&fn.warn(`Using run ID from ${Math.round(e)} hours ago (${n.filePath}). Provide an explicit run ID if this is not the run you want to fix.`),t(n.runId)}fn.debug("No run ID found in last-run.json")})(e);t||(process.stderr.write('Run ID is required. Either:\n 1. Run "stably test" first (run ID will be auto-detected)\n 2. Provide a run ID: stably fix <runId>\n 3. Run in CI (auto-detected from environment)\n'),process.exit(1));const r=await(async e=>{const t=await In(),r=En(t),n=Tn(t),[,s]=process.argv;if(!s)throw new Error("Unable to determine CLI entrypoint for fix subprocess.");return await(async({runId:e,cliEntry:t,stablyApiKey:r,stablyProjectId:n,baseEnv:s=process.env,cwd:o=process.cwd(),execPath:i=process.execPath,execArgv:a=process.execArgv,stdio:c="inherit",spawnImpl:l=({command:e,args:t,options:r})=>oe(e,t,r)})=>{const u=(({baseEnv:e,stablyApiKey:t,stablyProjectId:r,playwrightSession:n})=>{const s={...e};for(const e of Object.keys(s))qp(e)&&delete s[e];return{...s,STABLY_API_KEY:t,STABLY_PROJECT_ID:r,...n?{STABLY_PLAYWRIGHT_SESSION:n}:{}}})({baseEnv:s,stablyApiKey:r,stablyProjectId:n});return await new Promise((r,n)=>{const s=l({args:[...a,t,"internal-fix-run",e],command:i,options:{cwd:o,stdio:c,env:u}});s.once("error",n),s.once("exit",(e,t)=>{r(t?1:e??1)})})})({cliEntry:s,runId:e,stablyApiKey:r,stablyProjectId:n,cwd:process.cwd(),stdio:"inherit"})})(t);0!==r&&process.exit(r)}),Qp.command("init").description("Initialize Playwright and Stably SDK in your project").action(async()=>mu({mode:"init"})),Qp.command("upgrade").description("Upgrade to latest version (use --check to only check)").option("-c, --check","Only check for updates without upgrading").action(e=>async function(e){const{check:t=!1}=e;let r;Yp(N.cyan("Checking for updates...\n"));try{r=await async function(){const e=await async function(){const e=new AbortController,t=setTimeout(()=>e.abort(),1e4);t.unref();try{const t=await fetch(Op,{signal:e.signal});if(!t.ok)throw new Error(`Failed to fetch latest version: ${t.statusText}`);return Vp.parse(await t.json()).version}finally{clearTimeout(t)}}();return{current:Ht,latest:e,isOutdated:Bp(Ht,e)}}()}catch(e){return Wp(N.red("Failed to check for updates:"),e instanceof Error?e.message:e),void(process.exitCode=1)}if(Yp(`Current version: ${N.yellow(r.current)}`),Yp(`Latest version: ${N.green(r.latest)}`),Yp(),!r.isOutdated)return void Yp(N.green("✓ You are already on the latest version!"));if(Yp(N.yellow(`⚠ A new version is available: ${r.current} → ${r.latest}`)),Yp(),t)return Yp(N.dim("Exiting with code 1 to indicate update available (useful for CI).")),void(process.exitCode=1);const n=function(){const e=process.argv[1]||"";if(e.includes("_npx")||e.includes(".npm/_cacache")||e.includes(".npm\\_cacache"))return"npx";try{const t=se("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=se("pnpm root -g",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-pnpm"}catch{}try{const t=se("yarn global dir",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-yarn-classic"}catch{}try{const t=se("yarn config get globalFolder",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-yarn-berry"}catch{}return"unknown"}(),s=function(e){switch(e){case"global-npm":case"global-yarn-berry":case"unknown":return{command:"npm",args:["install","-g","--no-fund",`${$p}@latest`],description:`npm install -g ${$p}@latest`};case"global-pnpm":return{command:"pnpm",args:["add","-g",`${$p}@latest`],description:`pnpm add -g ${$p}@latest`};case"global-yarn-classic":return{command:"yarn",args:["global","add",`${$p}@latest`],description:`yarn global add ${$p}@latest`};case"npx":return{command:"npx",args:[`${$p}@latest`],description:`npx ${$p}@latest (always uses latest)`}}}(n);if("npx"===n)return Yp(N.dim("You are running via npx, which always fetches the latest version.")),void Yp(N.dim(`Simply run: ${N.white("npx stably")} to use the latest version.`));"unknown"===n?(Yp(N.yellow("Could not detect installation method. Falling back to npm.")),Yp()):"global-yarn-berry"===n&&(Yp(N.yellow("Yarn Berry does not support global packages. Falling back to npm.")),Yp()),Yp(`Upgrade command: ${N.cyan(s.description)}`),Yp(),Yp(N.cyan("Upgrading...")),Yp();try{await(o=s.command,i=s.args,new Promise((e,t)=>{const r=oe(o,i,{stdio:"inherit",shell:"win32"===process.platform});r.on("close",r=>{0===r?e():t(new Error(`Upgrade command exited with code ${r}`))}),r.on("error",e=>{t(e)})})),function(){try{F.unlinkSync(Mp)}catch{}}(),Yp(),Yp(N.green("✓ Upgrade complete!")),Yp(N.dim(`Run ${N.white("stably --version")} to verify.`))}catch(e){Wp(N.red("Upgrade failed:"),e instanceof Error?e.message:e),Yp(),Yp(N.dim("You can try manually running:")),Yp(N.cyan(` ${s.description}`)),process.exitCode=1}var o,i}(e));var nf=Qp.command("env").description("Manage remote environments");nf.command("list").description("List available environments").action(async()=>{const e=await In(),t=Tn(e),r=En(e);fn.debug("Listing environments",{projectId:t});const n=await Ut({auth:r,client:Zt(),path:{projectId:t}});401!==n.response.status&&403!==n.response.status||(k(N.red("Access denied.")),process.exit(1)),n.error&&(k(N.red(`Failed to list environments: ${n.response.status}`)),process.exit(1));const{environments:s}=n.data;if(0!==s.length){process.stdout.write(`${N.bold("Environments")}\n\n`);for(const e of s){const t=e.isDefault?N.green(" (default)"):"",r=N.dim(` ${e.variableCount} variable${1!==e.variableCount?"s":""}`);process.stdout.write(` ${N.cyan(e.name)}${t}${r}\n`),e.description&&process.stdout.write(` ${N.dim(e.description)}\n`)}process.stdout.write("\n")}else process.stdout.write(N.dim("No environments found. Create one on your Stably dashboard.\n"))}),nf.command("inspect <name>").description("Show variable metadata (name, sensitive flag, updated timestamp)").action(e=>(async e=>{const t=await In(),r=Tn(t),n=En(t);fn.debug("Inspecting environment",{name:e,projectId:r});const s=await Dt({auth:n,client:Zt(),path:{projectId:r,environmentName:e}});404===s.response.status&&(k(N.red(`Environment "${e}" not found. Run ${N.bold("stably env list")} to see available environments.`)),process.exit(1)),401!==s.response.status&&403!==s.response.status||(k(N.red("Access denied.")),process.exit(1)),s.error&&(k(N.red(`Failed to inspect environment: ${s.response.status}`)),process.exit(1));const{variables:o}=s.data;if(0!==o.length){process.stdout.write(`${N.bold(e)} ${N.dim(`(${o.length} variable${1!==o.length?"s":""})`)}\n\n`);for(const e of o){const t=N.dim(` [updated ${Ep(e.updatedAt)}]`);e.sensitive?process.stdout.write(` ${N.cyan(e.name)} ${N.yellow("[sensitive]")}${t}\n`):process.stdout.write(` ${N.cyan(e.name)}${t}\n`)}process.stdout.write("\n")}else process.stdout.write(N.dim(`Environment "${e}" has no variables.\n`))})(e));var sf=Qp.command("runs").description("View test run history");sf.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 In(),r=Tn(t),n=En(t),s=Up(t);let o;e.limit&&(o=parseInt(e.limit,10),(Number.isNaN(o)||o<1||o>100)&&(k(N.red("--limit must be an integer between 1 and 100")),process.exit(1)));const i=Lp(e.source,["LOCAL","CI","WEB"],"--source"),a=Lp(e.status,["QUEUED","RUNNING","PASSED","FAILED","TIMEDOUT","CANCELLED","INTERRUPTED"],"--status"),c=Lp(e.trigger,["MANUAL","SCHEDULED","UI","API","GITHUB_ACTION","SUITE_RUN"],"--trigger");fn.debug("Listing runs",{projectId:r,branch:e.branch,limit:o,after:e.after,before:e.before,source:i,status:a,suite:e.suite,trigger:c});const l=await Nt({auth:n,client:Zt(),headers:xn(s),query:{projectId:r,branchName:e.branch,limit:o,afterRunId:e.after,beforeRunId:e.before,source:i,status:a,suiteName:e.suite,trigger:c}});Dp(l,"list runs");const{runs:u,hasMore:d}=l.data;e.json?process.stdout.write(kp(l.data)):process.stdout.write(((e,t)=>{if(0===e.length)return N.dim("No runs found matching the specified filters.\n");const r=Math.min(40,Math.max(10,...e.map(e=>e.runId.length))),n={runId:{w:r+2,t:r},status:{w:14},branch:{w:32,t:30},started:{w:18}},s=[],o=`${Pp("Run ID",n.runId.w)}${Pp("Status",n.status.w)}${Pp("Branch",n.branch.w)}${Pp("Started",n.started.w)}Tests`;s.push(N.bold(o));for(const t of e){const e=xp(t.runId,n.runId.t),r=Cp(t.status),o=xp(t.branchName,n.branch.t),i=Ap(t.startedAt),a=t.totalCount.toString();s.push(`${Pp(e,n.runId.w)}${Pp(r,n.status.w)}${Pp(o,n.branch.w)}${Pp(i,n.started.w)}${a}`)}if(t&&e.length>0){const t=e.at(-1)?.runId;t&&(s.push(""),s.push(N.dim(`Next page: stably runs list --before ${t}`)))}return s.push(""),s.join("\n")})(u,d))}),sf.command("view <runId>").description("Show details for a specific run").option("--json","Output as JSON").action(async(e,t)=>{const r=await In(),n=En(r),s=Up(r);fn.debug("Viewing run",{runId:e});const o=await Bt({auth:n,client:Zt(),headers:xn(s),path:{runId:e},query:{detail:"full"}});if(Dp(o,"get run details",`Run "${e}" not found.`),t.json)process.stdout.write(kp(o.data));else{const e=o.data;process.stdout.write((e=>{const t=[];if(t.push(N.bold(`Run ${e.runId}`)),t.push(` ${N.dim("Status:")} ${Cp(e.status)}`),e.branchName&&t.push(` ${N.dim("Branch:")} ${e.branchName}`),e.commitSha&&t.push(` ${N.dim("Commit:")} ${e.commitSha.slice(0,7)}`),e.startedAt&&t.push(` ${N.dim("Started:")} ${Ap(e.startedAt)}`),null!==e.durationMs&&t.push(` ${N.dim("Duration:")} ${(e=>{if(null===e)return"-";const t=Math.floor(e/1e3);if(t<60)return`${t}s`;const r=Math.floor(t/60);return r<60?`${r}m ${t%60}s`:`${Math.floor(r/60)}h ${r%60}m`})(e.durationMs)}`),e.source&&t.push(` ${N.dim("Source:")} ${e.source.toLowerCase()}`),e.projectId){const r=`https://app.stably.ai/project/${e.projectId}/playwright/history/${e.runId}`;t.push(` ${N.dim("URL:")} ${N.cyan(N.underline(r))}`)}t.push("");const r=[];e.passedCount>0&&r.push(N.green(`${e.passedCount} passed`)),e.failedCount>0&&r.push(N.red(`${e.failedCount} failed`)),e.flakyCount>0&&r.push(N.yellow(`${e.flakyCount} flaky`)),e.timedoutCount>0&&r.push(N.red(`${e.timedoutCount} timedout`)),e.skippedCount>0&&r.push(N.dim(`${e.skippedCount} skipped`)),e.interruptedCount>0&&r.push(N.yellow(`${e.interruptedCount} interrupted`)),t.push(`${N.bold("Test Results:")} ${r.join(", ")}`);const n=e.testCases.filter(e=>"FAILED"===e.status||"TIMEDOUT"===e.status||"INTERRUPTED"===e.status||"FLAKY"===e.status);if(n.length>0){t.push(""),t.push(N.bold("Failed/Flaky Tests:"));for(const e of n){const r=e.status??"UNKNOWN",n=Sp[r]??(e=>e),s=e.location??"",o=e.title??e.testIdentifier,{attempts:i}=e,a=i?.length??0,c=a>1?` (${a} attempts)`:"",l=s?`${s} - `:"";t.push(` ${n(r)} ${l}${o}${N.dim(c)}`);const u=i?.at(-1);if(u?.errorMessage){const e=u.errorMessage.split("\n")[0]?.slice(0,100)??"";t.push(` ${N.dim(e)}`)}}}return t.push(""),t.join("\n")})(e))}}),Qp.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)}),vp.forEach(({args:e,description:t,name:r})=>{Qp.command(r).description(t).helpOption(!1).helpCommand(!1).allowUnknownOption(!0).allowExcessArguments(!0).passThroughOptions().action(()=>Tp({overrideArgs:e,subcommand:r}))});var of=()=>{0!==Zp.length&&(process.stderr.write(Zp.join("")),Zp=[])};(async()=>{await(async()=>{if(!zp&&"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":Ht,"node.version":process.version,"os.platform":process.platform}}),zp=!0}catch{}})();try{await Qp.parseAsync(process.argv),fn.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 fn.error(t,{stack:e instanceof Error?e.stack:void 0}),of(),fn.flush(),fn.printLogFileInfo(),await Kp(),void(process.exitCode=1)}const t="number"==typeof e.exitCode?e.exitCode:1,r=process.argv.slice(2).find(e=>!e.startsWith("-")),n=!!r&&!!tf(Qp,[r]);if(("commander.excessArguments"===e.code||"commander.unknownCommand"===e.code)&&r&&!n)return Zp=[],fn.warn("Unknown command",{command:r}),process.stderr.write(`command '${r}' not found\n`),rf(),void(process.exitCode=t);fn.debug("Commander error",{code:e.code,exitCode:t}),of(),process.exitCode=t}finally{fn.flush(),await Kp()}})();
|