stably 4.6.0 → 4.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +1 -1
  2. package/package.json +5 -4
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var e=require("dotenv"),t=require("path"),r=require("commander"),n=require("buffer"),s=require("child_process"),o=require("process"),i=require("fs"),a=require("url"),c=require("os");require("timers/promises");var l=require("stream"),u=require("util"),d=require("@anthropic-ai/claude-agent-sdk"),p=require("crypto"),f=require("picocolors"),h=require("simple-git"),g=require("fs/promises"),m=require("@clack/prompts"),y=require("readline/promises"),b=require("zod"),w=require("open"),v=require("http"),_=require("pino"),E=require("sonic-boom"),I=require("zod/v3"),T=require("ws"),x=require("react"),S=require("react/jsx-runtime"),A=require("module"),C=require("yaml"),R=require("@stablyhq/runner-sdk"),P="undefined"!=typeof document?document.currentScript:null;function U(e){return e&&e.__esModule?e:{default:e}}var k,L,D=U(t),O=U(s),B=U(o),N=U(i),j=U(c),$=U(l),M=U(p),F=U(f),H=U(g),G=U(b),z=U(w),W=U(v),Y=U(_),V=U(E),q=U(T),K=Object.create,J=Object.defineProperty,X=Object.getOwnPropertyDescriptor,Q=Object.getOwnPropertyNames,Z=Object.getPrototypeOf,ee=Object.prototype.hasOwnProperty,te=(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')}),re=(k={"../playwright-trace-scrubber/node_modules/.pnpm/isbinaryfile@5.0.7/node_modules/isbinaryfile/lib/index.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.isBinaryFileSync=e.isBinaryFile=void 0;var t=te("fs"),r=te("util"),n=(0,r.promisify)(t.stat),s=(0,r.promisify)(t.open),o=(0,r.promisify)(t.close),i=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){const t=new Array;for(let r=0;r<e;r++){if(this.error)return t;t[r]=this.nextByte()}return t}};function a(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 c(e){switch(7&a(e)){case 0:return a(e),!0;case 1:return e.next(8),!0;case 2:const t=a(e);return e.next(t),!0;case 5:return e.next(4),!0}return!1}function l(e,t){if(0===t)return!1;let r=0;const n=Math.min(t,515),s=Math.min(n,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(n>=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;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<n){if(t++,e[t]>=128&&e[t]<=191)continue}else if(e[t]>=224&&e[t]<=239&&t+2<n){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<n&&(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 r=new i(e,t);let n=0;for(;;){if(!c(r)&&!r.hasError())return!1;if(r.hasError())break;n++}return n>0}(e,s))}function u(e){return"string"==typeof e}function d(e){if(!e.isFile())throw new Error("Path provided was not a file!")}e.isBinaryFile=async function(e,r){if(u(e)){d(await n(e));const r=await s(e,"r"),i=Buffer.alloc(515);return new Promise((e,n)=>{t.read(r,i,0,515,0,(t,s,a)=>{if(o(r),t)n(t);else try{e(l(i,s))}catch(e){n(e)}})})}return void 0===r&&(r=e.length),l(e,r)},e.isBinaryFileSync=function(e,r){if(u(e)){d(t.statSync(e));const r=t.openSync(e,"r"),n=Buffer.alloc(515),s=t.readSync(r,n,0,515,0);return t.closeSync(r),l(n,s)}return void 0===r&&(r=e.length),l(e,r)}}},function(){return L||(0,k[Q(k)[0]])((L={exports:{}}).exports,L),L.exports}),ne={cwdChanged:!1,newCwd:void 0,envFilesLoaded:[],envFileErrors:[]},se=process.argv.findIndex(e=>"-C"===e||"--cwd"===e);if(-1!==se&&process.argv[se+1]){const e=process.argv[se+1];process.chdir(e),ne.cwdChanged=!0,ne.newCwd=e,process.argv.splice(se,2)}for(var oe=[],ie=0;ie<process.argv.length;)if("--env-file"===process.argv[ie]){const e=process.argv[ie+1];e&&!e.startsWith("-")?(oe.push(e),process.argv.splice(ie,2)):ie++}else ie++;for(const t of oe){const r=D.default.resolve(process.cwd(),t),n=e.config({path:r,override:!0,quiet:!0});if(n.error){const e=`warning: could not load env file: ${r} (${n.error.message})`;ne.envFileErrors.push(e),process.stderr.write(`${e}\n`)}else ne.envFilesLoaded.push(r)}var ae={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 ce(e){return(/\d+(?!.*\d+)/.exec(e)||[])[0]}function le(e){return e?/^(?:refs\/heads\/)?(?<branch>.+)$/i.exec(e)[1]:void 0}var ue={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:le(r?e.SYSTEM_PULLREQUEST_TARGETBRANCH:e.BUILD_SOURCEBRANCH),pr:t,isPr:r,prBranch:le(r?e.SYSTEM_PULLREQUEST_SOURCEBRANCH:void 0),root:e.BUILD_REPOSITORY_LOCALPATH}}},de={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})},pe={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})},fe={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}}},he={detect:({env:e})=>Boolean(e.BUDDY_WORKSPACE_ID),configuration({env:e}){const t=ce(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}}},ge="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function me(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ye,be,we,ve,_e,Ee,Ie,Te,xe={exports:{}};var Se,Ae,Ce,Re,Pe,Ue,ke,Le,De,Oe,Be,Ne,je,$e,Me,Fe={exports:{}},He={};function Ge(){if(Ne)return Be;Ne=1;const e=D.default,t=function(){if(Ce)return Ae;Ce=1;const e=D.default,t=function(){if(Te)return Ie;Te=1;const e="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,t=D.default,r=e?";":":",n=function(){if(Ee)return _e;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 Ee=1,e="win32"===process.platform||ge.TESTING_WINDOWS?function(){if(be)return ye;be=1,ye=r,r.sync=function(r,n){return t(e.statSync(r),r,n)};var e=N.default;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 ye}():function(){if(ve)return we;ve=1,we=t,t.sync=function(t,n){return r(e.statSync(t),n)};var e=N.default;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 we}(),_e=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}},_e}(),s=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),o=(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}},i=(e,r,i)=>{"function"==typeof r&&(i=r,r={}),r||(r={});const{pathEnv:a,pathExt:c,pathExtExe:l}=o(e,r),u=[],d=n=>new Promise((o,i)=>{if(n===a.length)return r.all&&u.length?o(u):i(s(e));const c=a[n],l=/^".*"$/.test(c)?c.slice(1,-1):c,d=t.join(l,e),f=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d;o(p(f,n,0))}),p=(e,t,s)=>new Promise((o,i)=>{if(s===c.length)return o(d(t+1));const a=c[s];n(e+a,{pathExt:l},(n,i)=>{if(!n&&i){if(!r.all)return o(e+a);u.push(e+a)}return o(p(e,t,s+1))})});return i?d(0).then(e=>i(null,e),i):d(0)};return Ie=i,i.sync=(e,r)=>{r=r||{};const{pathEnv:i,pathExt:a,pathExtExe:c}=o(e,r),l=[];for(let s=0;s<i.length;s++){const o=i[s],u=/^".*"$/.test(o)?o.slice(1,-1):o,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(n.sync(t,{pathExt:c})){if(!r.all)return t;l.push(t)}}catch(e){}}}if(r.all&&l.length)return l;if(r.nothrow)return null;throw s(e)},Ie}(),r=function(){if(Se)return Fe.exports;Se=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 Fe.exports=e,Fe.exports.default=e,Fe.exports}();function n(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 Ae=function(e){return n(e)||n(e,!0)}}(),r=function(){if(Re)return He;Re=1;const e=/([()\][%!^"`<>&|;, *?])/g;return He.command=function(t){return t.replace(e,"^$1")},He.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},He}(),n=function(){if(Oe)return De;Oe=1;const e=N.default,t=function(){if(Le)return ke;Le=1;const e=Ue?Pe:(Ue=1,Pe=/^#!(.*)/);return ke=(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 De=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())},De}(),s="win32"===process.platform,o=/\.(?:com|exe)$/i,i=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;return Be=function(a,c,l){c&&!Array.isArray(c)&&(l=c,c=null);const u={command:a,args:c=c?c.slice(0):[],options:l=Object.assign({},l),file:void 0,original:{command:a,args:c}};return l.shell?u:function(a){if(!s)return a;const c=function(e){e.file=t(e);const r=e.file&&n(e.file);return r?(e.args.unshift(e.file),e.command=r,t(e)):e.file}(a),l=!o.test(c);if(a.options.forceShell||l){const t=i.test(c);a.command=e.normalize(a.command),a.command=r.command(a.command),a.args=a.args.map(e=>r.argument(e,t));const n=[a.command].concat(a.args).join(" ");a.args=["/d","/s","/c",`"${n}"`],a.command=process.env.comspec||"cmd.exe",a.options.windowsVerbatimArguments=!0}return a}(u)}}var ze=me(function(){if(Me)return xe.exports;Me=1;const e=O.default,t=Ge(),r=function(){if($e)return je;$e=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 je={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},je}();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 xe.exports=n,xe.exports.spawn=n,xe.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},xe.exports._parse=t,xe.exports._enoent=r,xe.exports}());function We(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 Ye=(e,t)=>({name:`SIGRT${t+1}`,number:Ve+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),Ve=34,qe=[{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"}],Ke=()=>{const e=(()=>{const e=64-Ve+1;return Array.from({length:e},Ye)})();return[...qe,...e].map(Je)},Je=({name:e,number:t,description:r,action:n,forced:s=!1,standard:o})=>{const{signals:{[e]:i}}=c.constants,a=void 0!==i;return{name:e,number:a?i:t,description:r,supported:a,action:n,forced:s,standard:o}},Xe=({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}],Qe=(()=>{const e=Ke();return Object.fromEntries(e.map(Xe))})();(()=>{const e=Ke(),t=Array.from({length:65},(t,r)=>((e,t)=>{const r=((e,t)=>{const r=t.find(({name:t})=>c.constants.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:l}=r;return{[e]:{name:n,number:e,description:s,supported:o,action:i,forced:a,standard:l}}})(r,e));Object.assign({},...t)})();var Ze=({stdout:e,stderr:t,all:r,error:n,signal:s,exitCode:o,command:i,escapedCommand:a,timedOut:c,isCanceled:l,killed:u,parsed:{options:{timeout:d,cwd:p=B.default.cwd()}}})=>{o=null===o?void 0:o;const f=void 0===(s=null===s?void 0:s)?void 0:Qe[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},et=["stdin","stdout","stderr"],tt=[];tt.push("SIGHUP","SIGINT","SIGTERM"),"win32"!==process.platform&&tt.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),"linux"===process.platform&&tt.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var rt,nt,st=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"),it=globalThis,at=Object.defineProperty.bind(Object),ct=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(it[ot])return it[ot];at(it,ot,{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}},lt=class{},ut=globalThis.process;st(ut)?new class extends lt{#e="win32"===ut.platform?"SIGINT":"SIGHUP";#t=new ct;#r;#n;#s;#o={};#i=!1;constructor(e){super(),this.#r=e,this.#o={};for(const t of tt)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(!st(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 tt)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,tt.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 st(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&&st(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)}}(ut):new class extends lt{onExit(){return()=>{}}load(){}unload(){}},new TextEncoder,function(){if(nt)return rt;nt=1;const{PassThrough:e}=$.default;rt=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 dt=(async()=>{})().constructor.prototype;["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(dt,e)]);var pt=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],ft=/^[\w.-]+$/,ht=u.debuglog("execa").enabled,gt=(e,t)=>String(e).padStart(t,"0"),mt=(e,t,r={})=>{const n=ze._parse(e,t,r);return e=n.command,t=n.args,(r={maxBuffer:1e8,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:(r=n.options).cwd||B.default.cwd(),execPath:B.default.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:ht,...r}).env=(({env:e,extendEnv:t,preferLocal:r,localDir:n,execPath:s})=>{const o=t?{...B.default.env,...e}:e;return r?(({env:e=B.default.env,...t}={})=>{const r=We({env:e={...e}});return t.path=e[r],e[r]=(({cwd:e=B.default.cwd(),path:t=B.default.env[We()],preferLocal:r=!0,execPath:n=B.default.execPath,addExecPath:s=!0}={})=>{const o=e instanceof URL?a.fileURLToPath(e):e,i=D.default.resolve(o),c=[];return r&&((e,t)=>{let r;for(;r!==t;)e.push(D.default.join(t,"node_modules/.bin")),r=t,t=D.default.resolve(t,"..")})(c,i),s&&((e,t,r)=>{const n=t instanceof URL?a.fileURLToPath(t):t;e.push(D.default.resolve(r,n,".."))})(c,n,i),[...c,t].join(D.default.delimiter)})(t),e})({env:o,cwd:n,execPath:s}):o})(r),r.stdio=(e=>{if(!e)return;const{stdio:t}=e;if(void 0===t)return et.map(t=>e[t]);if((e=>et.some(t=>void 0!==e[t]))(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${et.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,et.length);return Array.from({length:r},(e,r)=>t[r])})(r),"win32"===B.default.platform&&"cmd"===D.default.basename(e,".exe")&&t.unshift("/q"),{file:e,args:t,options:r,parsed:n}},yt=(e,t,r)=>"string"==typeof t||n.Buffer.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 bt(e,t,r){const n=mt(e,t,r),s=((e,t)=>pt(e,t).join(" "))(e,t),o=((e,t)=>pt(e,t).map(e=>(e=>"string"!=typeof e||ft.test(e)?e:`"${e.replaceAll('"','\\"')}"`)(e)).join(" "))(e,t);((e,{verbose:t})=>{t&&B.default.stderr.write(`[${(()=>{const e=new Date;return`${gt(e.getHours(),2)}:${gt(e.getMinutes(),2)}:${gt(e.getSeconds(),2)}.${gt(e.getMilliseconds(),3)}`})()}] ${e}\n`)})(o,n.options);const a=(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),i.readFileSync(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 c;try{c=O.default.spawnSync(n.file,n.args,{...n.options,input:a})}catch(e){throw Ze({error:e,stdout:"",stderr:"",all:"",command:s,escapedCommand:o,parsed:n,timedOut:!1,isCanceled:!1,killed:!1})}const l=yt(n.options,c.stdout,c.error),u=yt(n.options,c.stderr,c.error);if(c.error||0!==c.status||null!==c.signal){const e=Ze({stdout:l,stderr:u,error:c.error,signal:c.signal,exitCode:c.status,command:s,escapedCommand:o,parsed:n,timedOut:c.error&&"ETIMEDOUT"===c.error.code,isCanceled:!1,killed:null!==c.signal});if(!n.options.reject)return e;throw e}return{command:s,escapedCommand:o,exitCode:0,stdout:l,stderr:u,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}}function wt(e){try{return bt("git",["rev-parse","HEAD"],e).stdout}catch{return}}function vt(e){try{const t=bt("git",["rev-parse","--abbrev-ref","HEAD"],e).stdout;if("HEAD"===t){const t=bt("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 _t=/^(?:.*)@(?:.*):(?:\d+\/)?(.*)\.git$/,Et=/^\/(.*)\.git$/;function It(e){if(e){if(e.match(_t))return e.replace(_t,"$1");try{return new URL(e).pathname.replace(Et,"$1")}catch{return}}}var Tt,xt={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:It(e.BUILDKITE_REPO),pr:t,isPr:r,prBranch:r?e.BUILDKITE_BRANCH:void 0,root:e.BUILDKITE_BUILD_CHECKOUT_PATH}}},St={detect:({env:e})=>Boolean(e.CIRCLECI),configuration({env:e}){const t=e.CIRCLE_PR_NUMBER||ce(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}`}}},At="https://cirrus-ci.com",Ct={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:`${At}/build/${e.CIRRUS_BUILD_ID}`,job:e.CIRRUS_TASK_ID,jobUrl:`${At}/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}}},Rt={detect:({env:e})=>Boolean(e.CODEBUILD_BUILD_ID),configuration:({env:e,cwd:t})=>({name:"AWS CodeBuild",service:"codebuild",commit:wt({env:e,cwd:t}),build:e.CODEBUILD_BUILD_ID,branch:vt({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})},Pt={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}}},Ut={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}}},kt=({env:e})=>{try{const t=e.GITHUB_EVENT_PATH?JSON.parse(i.readFileSync(e.GITHUB_EVENT_PATH,"utf-8")):void 0;if(t&&t.pull_request)return{branch:t.pull_request.base?le(t.pull_request.base.ref):void 0,pr:t.pull_request.number}}catch{}return{pr:void 0,branch:void 0}},Lt={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=le("pull_request_target"===e.GITHUB_EVENT_NAME?`refs/pull/${(e=>{const t=e.GITHUB_EVENT_PATH?JSON.parse(i.readFileSync(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?kt({env:e}):void 0}}},Dt={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}}},Ot={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||wt({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}}},Bt={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}}},Nt={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})},jt={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}}},$t={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}}},Mt={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}}},Ft={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||wt({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}}},Ht={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}}},Gt={};function zt(){if(Tt)return Gt;Tt=1,Object.defineProperty(Gt,"__esModule",{value:!0}),Gt.of=Gt.PropertiesFile=void 0;var e,t=(e=N.default)&&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 Gt.PropertiesFile=r,Gt.of=function(...e){let t=new r;return t.of.apply(t,e),t},Gt}var Wt=me(zt()),Yt={root:"teamcity.build.workingDir",branch:"teamcity.build.branch"},Vt=e=>{try{return Wt.of(e)}catch{return}},qt=({env:e,cwd:t})=>{const r=e.TEAMCITY_BUILD_PROPERTIES_FILE?Vt(e.TEAMCITY_BUILD_PROPERTIES_FILE):void 0,n=r?r.get("teamcity.configuration.properties.file"):void 0,s=n?Vt(n):n;return Object.fromEntries(Object.keys(Yt).map(n=>[n,(r?r.get(Yt[n]):void 0)||(s?s.get(Yt[n]):void 0)||("branch"===n?vt({env:e,cwd:t}):void 0)]))},Kt={appveyor:ae,azurePipelines:ue,bamboo:de,bitbucket:pe,bitrise:fe,buddy:he,buildkite:xt,circleci:St,cirrus:Ct,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:Rt,codefresh:Pt,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:Ut,github:Lt,gitlab:Dt,jenkins:Ot,netlify:Bt,puppet:Nt,sail:jt,screwdriver:$t,scrutinizer:Mt,semaphore:Ft,shippable:Ht,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,...qt({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:le(e.JB_SPACE_GIT_BRANCH),slug:t&&r?`${t.toLowerCase()}/${r}`:void 0}}}},Jt=class e{git;config;snapshotTreeHash;snapshotIndexPath;constructor(e){this.config=e,this.git=h.simpleGit({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=t.join(c.tmpdir(),`git-diff-tracker-${p.randomUUID()}.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=t.join(c.tmpdir(),`git-diff-tracker-${p.randomUUID()}.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 Xt(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 Xt(this.snapshotIndexPath),this.snapshotIndexPath=void 0),this.snapshotTreeHash=void 0}};async function Xt(e){try{await g.unlink(e)}catch{}}var Qt="x-stably-org-id",Zt={bodySerializer:e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t)},er=({allowReserved:e,explode:t,name:r,style:n,value:s})=>{if(!t){const t=(e?s:s.map(e=>encodeURIComponent(e))).join((e=>{switch(e){case"form":default:return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20"}})(n));switch(n){case"label":return`.${t}`;case"matrix":return`;${r}=${t}`;case"simple":return t;default:return`${r}=${t}`}}const o=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(n),i=s.map(t=>"label"===n||"simple"===n?e?t:encodeURIComponent(t):tr({allowReserved:e,name:r,value:t})).join(o);return"label"===n||"matrix"===n?o+i:i},tr=({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)}`},rr=({allowReserved:e,explode:t,name:r,style:n,value:s,valueOnly:o})=>{if(s instanceof Date)return o?s.toISOString():`${r}=${s.toISOString()}`;if("deepObject"!==n&&!t){let t=[];Object.entries(s).forEach(([r,n])=>{t=[...t,r,e?n:encodeURIComponent(n)]});const o=t.join(",");switch(n){case"form":return`${r}=${o}`;case"label":return`.${o}`;case"matrix":return`;${r}=${o}`;default:return o}}const i=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(n),a=Object.entries(s).map(([t,s])=>tr({allowReserved:e,name:"deepObject"===n?`${r}[${t}]`:t,value:s})).join(i);return"label"===n||"matrix"===n?i+a:a},nr=/\{[^{}]+\}/g;function sr(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 or,ir=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},ar=({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=er({allowReserved:i.allowReserved,explode:!0,name:s,style:"form",value:o,...i.array});e&&n.push(e)}else if("object"==typeof o){const e=rr({allowReserved:i.allowReserved,explode:!0,name:s,style:"deepObject",value:o,...i.object});e&&n.push(e)}else{const e=tr({allowReserved:i.allowReserved,name:s,value:o});e&&n.push(e)}}return n.join("&")},cr=(e,t)=>!!t&&!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`)),lr=e=>(({baseUrl:e,path:t,query:r,querySerializer:n,url:s})=>{let o=(e??"")+(s.startsWith("/")?s:`/${s}`);t&&(o=(({path:e,url:t})=>{let r=t;const n=t.match(nr);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,er({explode:n,name:s,style:o,value:i}));continue}if("object"==typeof i){r=r.replace(t,rr({explode:n,name:s,style:o,value:i,valueOnly:!0}));continue}if("matrix"===o){r=r.replace(t,`;${tr({name:s,value:i})}`);continue}const a=encodeURIComponent("label"===o?`.${i}`:i);r=r.replace(t,a)}return r})({path:t,url:o}));let i=r?n(r):"";return i.startsWith("?")&&(i=i.substring(1)),i&&(o+=`?${i}`),o})({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:"function"==typeof e.querySerializer?e.querySerializer:ar(e.querySerializer),url:e.url}),ur=(e,t)=>{const r={...e,...t};return r.baseUrl?.endsWith("/")&&(r.baseUrl=r.baseUrl.substring(0,r.baseUrl.length-1)),r.headers=pr(e.headers,t.headers),r},dr=e=>{const t=[];return e.forEach((e,r)=>{t.push([r,e])}),t},pr=(...e)=>{const t=new Headers;for(const r of e){if(!r)continue;const e=r instanceof Headers?dr(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},fr=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}},hr=ar({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),gr={"Content-Type":"application/json"},mr=(e={})=>({...Zt,headers:gr,parseAs:"auto",querySerializer:hr,...e}),yr=(e={})=>{let t=ur(mr(),e);const r=()=>({...t}),n={error:new fr,request:new fr,response:new fr},s=async e=>{const r={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:pr(t.headers,e.headers),serializedBody:void 0};return r.security&&await(async({security:e,...t})=>{for(const r of e){if(cr(t,r.name))continue;const e=await ir(r,t.auth);if(!e)continue;const n=r.name??"Authorization";switch(r.in){case"query":t.query||(t.query={}),t.query[n]=e;break;case"cookie":t.headers.append("Cookie",`${n}=${e}`);break;default:t.headers.set(n,e)}}})({...r,security:r.security}),r.requestValidator&&await r.requestValidator(r),void 0!==r.body&&r.bodySerializer&&(r.serializedBody=r.bodySerializer(r.body)),void 0!==r.body&&""!==r.serializedBody||r.headers.delete("Content-Type"),{opts:r,url:lr(r)}},o=async e=>{const{opts:t,url:r}=await s(e),o={redirect:"follow",...t,body:sr(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;try{c=await a(i)}catch(e){let r=e;for(const s of n.error.fns)s&&(r=await s(e,void 0,i,t));if(r=r||{},t.throwOnError)throw r;return"data"===t.responseStyle?void 0:{error:r,request:i,response:void 0}}for(const e of n.response.fns)e&&(c=await e(c,i,t));const l={request:i,response:c};if(c.ok){const e=("auto"===t.parseAs?(e=>{if(!e)return"stream";const t=e.split(";")[0]?.trim();return t?t.startsWith("application/json")||t.endsWith("+json")?"json":"multipart/form-data"===t?"formData":["application/","audio/","image/","video/"].some(e=>t.startsWith(e))?"blob":t.startsWith("text/")?"text":void 0:void 0})(c.headers.get("Content-Type")):t.parseAs)??"json";if(204===c.status||"0"===c.headers.get("Content-Length")){let r;switch(e){case"arrayBuffer":case"blob":case"text":r=await c[e]();break;case"formData":r=new FormData;break;case"stream":r=c.body;break;default:r={}}return"data"===t.responseStyle?r:{data:r,...l}}let r;switch(e){case"arrayBuffer":case"blob":case"formData":case"json":case"text":r=await c[e]();break;case"stream":return"data"===t.responseStyle?c.body:{data:c.body,...l}}return"json"===e&&(t.responseValidator&&await t.responseValidator(r),t.responseTransformer&&(r=await t.responseTransformer(r))),"data"===t.responseStyle?r:{data:r,...l}}const u=await c.text();let d;try{d=JSON.parse(u)}catch{}const p=d??u;let f=p;for(const e of n.error.fns)e&&(f=await e(p,c,i,t));if(f=f||{},t.throwOnError)throw f;return"data"===t.responseStyle?void 0:{error:f,...l}},i=e=>t=>o({...t,method:e}),a=e=>async t=>{const{opts:r,url:o}=await s(t);return(({onRequest:e,onSseError:t,onSseEvent:r,responseTransformer:n,responseValidator:s,sseDefaultRetryDelay:o,sseMaxRetryAttempts:i,sseMaxRetryDelay:a,sseSleepFn:c,url:l,...u})=>{let d;const p=c??(e=>new Promise(t=>setTimeout(t,e))),f=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)}}}();return{stream:f}})({...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:lr,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=ur(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")}},br=yr(mr({baseUrl:"https://api.stably.ai"})),wr="4.6.0",vr=process.env.STABLY_API_URL||"https://api.stably.ai",_r=e=>{const t=new URL(e);return t.protocol="http:"===t.protocol?"ws:":"wss:",t},Er=process.env.AUTH_URL||"https://auth.stably.ai",Ir=process.env.AUTH_CLIENT_ID||"288007877071cce81f269428ea78653a",Tr=process.env.AI_PROXY_URL||"https://ai-proxy.stably.ai",xr=process.env.STABLY_AUTOHEAL_WS_URL||new URL("/autoheal",_r(vr)).toString(),Sr=process.env.STABLY_CREATE_PROGRESS_WS_URL||new URL("/create-progress",_r(vr)).toString(),Ar="http://localhost:9876/auth/callback",Cr=()=>or||(or=yr(mr({baseUrl:vr,headers:{"X-STABLY-CLI-VERSION":wr,"X-STABLY-SOURCE":"cli"}}))),Rr=async(e,t)=>{const r=await(n={body:{accessToken:e,orgId:t},client:Cr()},(n.client??br).post({url:"/internal/v1/cli/exchange-token",...n,headers:{"Content-Type":"application/json",...n.headers}}));var n;if(401===r.response.status)throw new Error("Invalid or expired access token");if(403===r.response.status)throw new Error("You do not have access to this organization");if(r.error)throw new Error(`Failed to exchange token: ${r.response.status}`);return r.data},Pr=b.z.object({org_id:b.z.string(),org_name:b.z.string()}),Ur=b.z.object({email:b.z.string(),org_id_to_org_member_info:b.z.record(b.z.string(),Pr).optional(),org_member_info:Pr.optional(),user_id:b.z.string()});b.z.object({email:b.z.string(),firstName:b.z.string().optional(),lastName:b.z.string().optional(),organizations:b.z.array(b.z.object({id:b.z.string(),name:b.z.string()})),userId:b.z.string()});var kr=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)},Lr=e=>{try{const t=Ur.parse(kr(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"}`)}},Dr=async(e,t)=>{let r=e;const{root:n}=D.default.parse(r);for(;r!==n;){const e=D.default.join(r,t);try{return await g.access(e),e}catch{r=D.default.dirname(r)}}},Or=D.default.join(j.default.homedir(),".stably"),Br=D.default.join(Or,"auth.json"),Nr=".stably",jr="project.json",$r=G.default.object({accessToken:G.default.string(),expiresAt:G.default.number(),idToken:G.default.string().optional(),refreshToken:G.default.string()}),Mr=G.default.object({orgId:G.default.string(),orgName:G.default.string(),projectId:G.default.string(),projectName:G.default.string()}),Fr=async()=>{try{const e=await g.readFile(Br,"utf-8");return $r.parse(JSON.parse(e))}catch{return}},Hr=async e=>{await g.mkdir(Or,{recursive:!0}),await g.writeFile(Br,JSON.stringify(e,null,2),{mode:384})},Gr=async()=>{try{await g.unlink(Br)}catch{}},zr=async()=>{try{const e=await Dr(process.cwd(),Nr);if(!e)return;const t=D.default.join(e,jr),r=await g.readFile(t,"utf-8");return Mr.parse(JSON.parse(r))}catch{return}},Wr=async()=>{try{const e=await Dr(process.cwd(),Nr);e&&await g.unlink(D.default.join(e,jr))}catch{}},Yr=e=>Date.now()>=e.expiresAt-3e5,Vr=async e=>{const t=new URLSearchParams({client_id:Ir,grant_type:"refresh_token",refresh_token:e}),r=await fetch(`${Er}/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}},qr=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`,Kr=(e,t,r)=>{e.writeHead(t,{"Content-Type":"text/html"}),e.end(r)},Jr=(e,t)=>{const r=new URLSearchParams({client_id:Ir,code_challenge:e,code_challenge_method:"S256",redirect_uri:Ar,response_type:"code",state:t});return`${Er}/propelauth/oauth/authorize?${r.toString()}`},Xr=async e=>{const t=m.spinner();let r;t.start("Loading user info...");try{r=Lr(e.accessToken),t.stop(F.default.green(`✓ Logged in as ${F.default.cyan(r.email)}`))}catch(e){t.stop(F.default.red("✗ Failed to load user info"));const r=e instanceof Error?e.message:"Unknown error";return m.log.error(r),{success:!1}}const n=await(async e=>{if(0===e.length)return void m.log.error("You don't belong to any organizations.");if(1===e.length)return m.log.info(`Using organization: ${F.default.cyan(e[0].name)}`),e[0];if(!process.stdin.isTTY)return m.log.info(`Auto-selecting organization: ${F.default.cyan(e[0].name)}`),e[0];const t=await m.select({message:"Select an organization",options:[...e].sort((e,t)=>e.name.localeCompare(t.name)).map(e=>({label:e.name,value:e.id}))});return m.isCancel(t)?void 0:e.find(e=>e.id===t)})(r.organizations);if(!n)return m.log.warn("Organization selection cancelled."),{success:!1};let s;t.start("Getting org credentials...");try{const r=await Rr(e.accessToken,n.id);s={accessToken:r.accessToken,expiresAt:Date.now()+1e3*r.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken},t.stop(F.default.green("✓ Credentials obtained"))}catch(e){t.stop(F.default.red("✗ Failed to get org credentials"));const r=e instanceof Error?e.message:"Unknown error";return m.log.error(r),{success:!1}}const o=await(async(e,t)=>{const r=m.spinner();let n;r.start("Loading projects...");try{n=await(async({accessToken:e,orgId:t})=>{const r=await(n={auth:e,client:Cr(),path:{orgId:t}},(n.client??br).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/orgs/{orgId}/projects",...n}));var n;if(401===r.response.status)throw new Error("Invalid or expired access token");if(403===r.response.status)throw new Error("You do not have access to this organization");if(r.error)throw new Error(`Failed to list projects: ${r.response.status}`);return r.data.projects})({accessToken:e,orgId:t}),r.stop(F.default.green("✓ Projects loaded"))}catch(e){r.stop(F.default.red("✗ Failed to load projects"));const t=e instanceof Error?e.message:"Unknown error";return void m.log.error(t)}if(0===n.length)return m.log.error("No projects found in this organization."),void m.log.info(`Create a project at ${F.default.underline(F.default.cyan("https://app.stably.ai"))}`);if(1===n.length)return m.log.info(`Using project: ${F.default.cyan(n[0].name)}`),n[0];if(!process.stdin.isTTY)return m.log.info(`Auto-selecting project: ${F.default.cyan(n[0].name)}`),n[0];const s=await m.select({message:"Select a project",options:n.map(e=>({label:e.name,value:e.id}))});return m.isCancel(s)?void 0:n.find(e=>e.id===s)})(s.accessToken,n.id);return o?(await(async e=>{const t=D.default.join(process.cwd(),Nr),r=D.default.join(t,jr);await g.mkdir(t,{recursive:!0}),await g.writeFile(r,JSON.stringify(e,null,2)),await(async e=>{const t=D.default.join(e,".gitignore"),r="# Stably CLI (only docs/ are tracked)\n.stably/*\n!.stably/docs/";try{const e=await g.readFile(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 g.writeFile(t,n)}else if(o.test(e)){const n=e.replace(o,`\n${r}\n`);await g.writeFile(t,n)}else await g.appendFile(t,`\n${r}\n`)}catch{await g.writeFile(t,`${r}\n`)}})(process.cwd())})({orgId:n.id,orgName:n.name,projectId:o.id,projectName:o.name}),m.log.info(F.default.dim("Linked this directory to your Stably project.")),{scopedTokens:s,success:!0}):(m.log.warn("Project selection cancelled."),{success:!1})},Qr=async()=>{if(wn())return m.log.warn(`Environment variables ${F.default.cyan("STABLY_API_KEY")} and ${F.default.cyan("STABLY_PROJECT_ID")} are set.`),m.log.warn("These will be used for authentication instead of OAuth login."),m.log.warn("To use OAuth login, unset these environment variables first."),void m.outro(F.default.yellow("Login skipped - using environment variable authentication."));const e=await Fr();if(e){if(!Yr(e)){if(await zr())return void m.outro(F.default.yellow("You are already logged in. Run `stably logout` first to log out."));m.log.info("You are logged in but haven't selected a project yet.");const t=await Xr(e);return void(t.success?(await Hr(t.scopedTokens),m.outro(F.default.green("Setup complete! You can now use Stably CLI."))):m.outro(F.default.yellow("Setup incomplete. Run `stably login` to try again.")))}const t=m.spinner();t.start("Refreshing session...");try{const r=await Vr(e.refreshToken);t.stop(F.default.green("✓ Session refreshed"));const n=await zr();if(n){t.start("Getting org credentials...");try{const e=await Rr(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(F.default.green("✓ Credentials obtained")),m.outro(F.default.green("Login successful"))}catch{await Hr(r),t.stop(F.default.yellow("Using full credentials")),m.outro(F.default.green("Login successful"))}}else{const e=await Xr(r);e.success?(await Hr(e.scopedTokens),m.outro(F.default.green("Setup complete! You can now use Stably CLI."))):m.outro(F.default.yellow("Setup incomplete. Run `stably login` to try again."))}return}catch{t.stop(F.default.yellow("Session expired, proceeding with fresh login...")),await Gr(),await Wr()}}const{authorizeUrl:t,serverReady:r,waitForCallback:n}=(()=>{const{authorizeUrl:e,codeVerifier:t,state:r}=(()=>{const e=M.default.randomBytes(32).toString("base64url"),t=(r=e,M.default.createHash("sha256").update(r).digest("base64url"));var r;const n=M.default.randomBytes(16).toString("base64url");return{authorizeUrl:Jr(t,n),codeVerifier:e,state:n}})(),{ready:n,result:s}=(e=>{let t,r;return{ready:new Promise((e,n)=>{t=e,r=n}),result:new Promise((n,s)=>{const o=setTimeout(()=>{c.close(),n({error:"Login timed out",success:!1})},3e5),i=()=>{clearTimeout(o)},c=W.default.createServer((t,r)=>{const s=new a.URL(t.url||"","http://localhost:9876");if("/auth/callback"!==s.pathname)return r.writeHead(404),void r.end("Not found");const o=s.searchParams.get("code"),l=s.searchParams.get("state"),u=s.searchParams.get("error");return u?(Kr(r,400,qr(u)),i(),c.close(),void n({error:u,success:!1})):o&&l?l!==e?(Kr(r,400,qr("Invalid state parameter (possible CSRF attack)")),i(),c.close(),void n({error:"State mismatch",success:!1})):(Kr(r,200,'\n<!DOCTYPE html>\n<html>\n<head>\n <title>Authenticated Stably CLI</title>\n <style>\n * { box-sizing: border-box; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, sans-serif;\n display: flex;\n justify-content: center;\n align-items: center;\n min-height: 100vh;\n margin: 0;\n background: #000;\n color: #fafafa;\n }\n .container {\n text-align: center;\n padding: 48px;\n max-width: 400px;\n }\n .icon {\n width: 48px;\n height: 48px;\n border-radius: 50%;\n background: #22c55e;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 24px;\n }\n .icon svg { width: 24px; height: 24px; }\n .title {\n font-size: 24px;\n font-weight: 600;\n margin: 0 0 8px;\n letter-spacing: -0.5px;\n }\n .subtitle {\n color: #888;\n font-size: 14px;\n margin: 0 0 32px;\n line-height: 1.5;\n }\n .terminal {\n background: #111;\n border: 1px solid #333;\n border-radius: 8px;\n padding: 16px;\n text-align: left;\n font-family: \'SF Mono\', \'Fira Code\', \'Consolas\', monospace;\n font-size: 13px;\n }\n .terminal-header {\n display: flex;\n gap: 6px;\n margin-bottom: 12px;\n }\n .terminal-dot {\n width: 10px;\n height: 10px;\n border-radius: 50%;\n background: #333;\n }\n .terminal-line {\n color: #888;\n }\n .terminal-line .prompt { color: #888; }\n .terminal-line .cmd { color: #fafafa; }\n .terminal-line.success { color: #22c55e; }\n .brand {\n margin-top: 32px;\n font-size: 12px;\n color: #444;\n letter-spacing: 0.5px;\n }\n </style>\n</head>\n<body>\n <div class="container">\n <div class="icon">\n <svg fill="none" stroke="#000" stroke-width="3" viewBox="0 0 24 24">\n <path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/>\n </svg>\n </div>\n <h1 class="title">Authenticated</h1>\n <p class="subtitle">You can close this tab and return to your terminal.</p>\n <div class="terminal">\n <div class="terminal-header">\n <div class="terminal-dot"></div>\n <div class="terminal-dot"></div>\n <div class="terminal-dot"></div>\n </div>\n <div class="terminal-line"><span class="prompt">$</span> <span class="cmd">stably login</span></div>\n <div class="terminal-line success">Logged in successfully</div>\n </div>\n <div class="brand">STABLY</div>\n </div>\n</body>\n</html>\n'),i(),c.close(),void n({code:o,state:l,success:!0})):(Kr(r,400,qr("Missing code or state parameter")),i(),c.close(),void n({error:"Missing code or state parameter",success:!1}))});c.on("error",e=>{if(i(),"EADDRINUSE"===e.code){const e=new Error("Port 9876 is already in use. Please close the application using it and try again.");return r(e),void s(e)}const t=new Error(`Failed to start callback server: ${e.message}`);r(t),s(t)}),c.listen(9876,()=>{t()})})}})(r);return{authorizeUrl:e,serverReady:n,waitForCallback:async()=>{const e=await s;if(!e.success)throw new Error(e.error);return(async(e,t)=>{const r=new URLSearchParams({client_id:Ir,code:e,code_verifier:t,grant_type:"authorization_code",redirect_uri:Ar}),n=await fetch(`${Er}/propelauth/oauth/token`,{body:r.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},method:"POST"});if(!n.ok){const e=await n.text();throw new Error(`Token exchange failed: ${n.status} ${e}`)}const s=await n.json();return{accessToken:s.access_token,expiresAt:Date.now()+1e3*s.expires_in,idToken:s.id_token,refreshToken:s.refresh_token}})(e.code,t)}}})();await r,m.log.info("Opening browser for authentication..."),m.log.info(F.default.dim("If browser doesn't open, visit:")),m.log.info(`]8;;${t}${F.default.underline(F.default.cyan(t))}]8;;`);try{await z.default(t)}catch{m.log.warn("Could not open browser automatically. Please open the URL above manually.")}const s=m.spinner();let o;s.start("Waiting for authentication...");try{o=await n(),s.stop(F.default.green("✓ Authentication successful"))}catch(e){s.stop(F.default.red("✗ Authentication failed"));const t=e instanceof Error?e.message:"Unknown error";m.outro(F.default.red(`Login failed: ${t}`)),process.exit(1)}const i=await Xr(o);i.success?(await Hr(i.scopedTokens),m.outro(F.default.green("Setup complete! You can now use Stably CLI."))):(m.outro(F.default.yellow("Setup incomplete. Run `stably login` to try again.")),process.exit(1))},Zr={fatal:60,error:50,warn:40,info:30,debug:20,trace:10},en=new Set(["help","login","logout","whoami","tunnel","create","fix","init","upgrade","test","show-report","codegen"]),tn=(new Date).toISOString().split("T")[0],rn=D.default.join(j.default.tmpdir(),"stably-logs",tn);N.default.mkdirSync(rn,{recursive:!0});var nn,sn=process.argv.includes("--verbose")||process.argv.includes("-v"),on=process.env.STABLY_LOG_LEVEL?.toLowerCase(),an=sn?"debug":void 0!==(nn=on)&&nn in Zr?on:"warn",cn=Zr[an],ln=null,un=null,dn=null,pn=[],fn=!1,hn=e=>{if(!fn){ln=(e=>{const t=(()=>{const e=new Date;return[e.getHours().toString().padStart(2,"0"),e.getMinutes().toString().padStart(2,"0"),e.getSeconds().toString().padStart(2,"0")].join("-")})(),r=((e,t=100)=>e.replace(/[/\\:*?"<>|]/g,"-").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9\-_]/g,"").replace(/-+/g,"-").replace(/^-+|-+$/g,"").slice(0,t).toLowerCase()||"session")(e);return D.default.join(rn,`${t}-${r}.log`)})(e),(e=>{const t=["","=".repeat(60),"Stably CLI Debug Log",`Version: ${wr}`,`Generated: ${(new Date).toISOString()}`,`Node: ${process.version}`,`Platform: ${process.platform} ${j.default.release()}`,`CWD: ${process.cwd()}`,`Args: ${process.argv.slice(2).join(" ")}`,`Log Level (console): ${an}`,"=".repeat(60),""].join("\n");e.write(t)})(un=new V.default({dest:ln,minLength:4096,sync:!1,append:!0})),dn=Y.default({level:"debug",timestamp:Y.default.stdTimeFunctions.isoTime,base:{version:wr}},un);for(const{level:e,msg:t,context:r}of pn)r?dn[e](r,t):dn[e](t);pn=[],fn=!0,sn&&process.stderr.write(`${F.default.dim(`Debug log: ${ln}`)}\n\n`)}},gn=(()=>{const e=process.argv.slice(2).find(e=>!e.startsWith("-"));return e&&en.has(e)?e:null})();gn&&hn(gn);var mn=e=>(t,r)=>{if(dn?r?dn[e](r,t):dn[e](t):pn.push({level:e,msg:t,context:r}),(e=>Zr[e]>=cn)(e)){const r=((e,t)=>`${{fatal:F.default.bgRed(F.default.white(" FATAL ")),error:F.default.red("error"),warn:F.default.yellow("warn"),info:F.default.cyan("info"),debug:F.default.dim("debug"),trace:F.default.dim("trace")}[e]} ${t}`)(e,t);process.stderr.write(`${r}\n`)}},yn={fatal:mn("fatal"),error:mn("error"),warn:mn("warn"),info:mn("info"),debug:mn("debug"),trace:mn("trace"),initSession:e=>{fn||hn(e)},getLogFilePath:()=>ln,flush:()=>{if(un)try{un.flushSync()}catch{}},printLogFileInfo:()=>{ln&&(process.stderr.write(`\n${F.default.dim("Debug log written to:")}\n`),process.stderr.write(` ${F.default.cyan(ln)}\n`),process.stderr.write(`${F.default.dim("Share this file with support for assistance.")}\n`))},getPinoLogger:()=>dn};setInterval(()=>{yn.flush()},3e4).unref(),process.on("beforeExit",()=>{yn.flush()});var bn=e=>{const t=()=>{yn.flush(),sn&&yn.printLogFileInfo(),process.removeListener(e,t),process.kill(process.pid,e)};return t};process.on("SIGINT",bn("SIGINT")),process.on("SIGTERM",bn("SIGTERM"));var wn=()=>{const e=process.env.STABLY_API_KEY?.trim(),t=process.env.STABLY_PROJECT_ID?.trim();if(e&&t)return yn.debug("Environment auth detected",{hasApiKey:!0,hasProjectId:!0}),{apiKey:e,projectId:t};yn.debug("Environment auth not set",{hasApiKey:!!e,hasProjectId:!!t})},vn=!1,_n=()=>{vn||(vn=!0,m.log.warn("Both environment variable auth and stored OAuth login were detected."),m.log.warn(`Honoring environment variables (${F.default.cyan("STABLY_API_KEY")} + ${F.default.cyan("STABLY_PROJECT_ID")}).`),m.log.warn("To use OAuth login instead, unset those environment variables."))},En=async()=>{yn.debug("Checking for stored auth tokens");const e=await Fr();if(!e)return void yn.debug("No stored auth tokens found");const t=Yr(e);if(yn.debug("Auth tokens status",{expired:t}),!t){const t=await zr(),r=(e=>{try{const t=Ur.parse(kr(e));if(t.org_id_to_org_member_info)return"full";if(t.org_member_info)return"org"}catch{return"unknown"}return"unknown"})(e.accessToken);if(yn.debug("Token scope check",{scope:r,hasContext:!!t}),t&&"full"===r)try{yn.debug("Exchanging full token for org-scoped token",{orgId:t.orgId});const r=await Rr(e.accessToken,t.orgId),n={accessToken:r.accessToken,expiresAt:Date.now()+1e3*r.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken};return await Hr(n),yn.debug("Token exchange successful"),n}catch(t){return yn.debug("Token exchange failed, using existing token",{error:t instanceof Error?t.message:String(t)}),e}return e}try{yn.debug("Attempting token refresh");const t=await Vr(e.refreshToken);yn.debug("Token refresh successful");const r=await zr();if(r)try{yn.debug("Exchanging refreshed token for org-scoped token");const e=await Rr(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 yn.warn("Token refresh failed",{error:e instanceof Error?e.message:String(e)})}},In=async(e={})=>{yn.debug("Requiring authentication",{autoLogin:e.autoLogin});const t=wn();if(t){yn.info("Using environment variable authentication");try{await Fr()&&_n()}catch{}return{auth:t,type:"env"}}let r=await En(),n=r?await zr():void 0;const s=process.stdin.isTTY&&process.stdout.isTTY;if(yn.debug("OAuth auth check",{hasTokens:!!r,hasContext:!!n,canPrompt:s}),(!r||!n)&&e.autoLogin&&s){yn.info("Prompting user to login"),r?m.log.info("You are logged in but need to select an organization and project."):m.log.info("You are not logged in."),m.log.info("Press Enter to log in."),process.stdout.write(`${F.default.dim("Alternatively, set environment variables for an org API key:")}\n${F.default.dim(" STABLY_API_KEY=... STABLY_PROJECT_ID=... stably")}\n`),process.stdout.write("\n");const e=y.createInterface({input:process.stdin,output:process.stdout});try{await e.question(F.default.dim("Press Enter to continue... "))}finally{e.close()}await Qr(),r=await En(),n=r?await zr():void 0}return r||(yn.warn("Authentication required but no tokens available"),m.outro(F.default.red("You are not logged in. Run `stably login` to authenticate.")),process.exit(1)),n||(yn.warn("Authentication succeeded but no project context selected"),m.outro(F.default.red("You haven't selected an organization and project. Run `stably login` to complete setup.")),process.exit(1)),yn.info("OAuth authentication successful",{orgId:n.orgId,projectId:n.projectId}),{auth:{accessToken:r.accessToken,context:n},type:"oauth"}},Tn=e=>"env"===e.type?e.auth.projectId:e.auth.context.projectId,xn=e=>e?{...process.env,...e}:process.env,Sn=async()=>{yn.info("[test] Resolving Stably test env");const e=(()=>{if(process.env.STABLY_WS_URL)return;if("https://api.stably.ai"===vr)return;const e=vr.startsWith("http://")?"ws://":"wss://";return`${vr.replace(/^https?:\/\//,e).replace(/\/$/,"")}/reporter`})();yn.debug("[test] WebSocket URL resolved",{wsUrl:e??"(default)"});const t=wn();if(t)return yn.info("[test] Using env var auth (STABLY_API_KEY + STABLY_PROJECT_ID)"),{STABLY_API_KEY:t.apiKey,STABLY_PROJECT_ID:t.projectId,...e&&{STABLY_WS_URL:e}};yn.info("[test] No env var auth, attempting OAuth auth");const r=Date.now(),n=await(async()=>{const e=wn();if(e){try{await Fr()&&_n()}catch{}return{auth:e,type:"env"}}const t=await En(),r=t?await zr():void 0;if(t&&r)return{auth:{accessToken:t.accessToken,context:r},type:"oauth"}})();if(yn.info("[test] OAuth auth resolved",{durationMs:Date.now()-r,hasAuth:!!n,authType:n?.type}),!n||"env"===n.type)return void yn.info("[test] No usable auth found");const s=process.env.STABLY_PROJECT_ID?.trim(),o=s||Tn(n);if(!o)return void yn.warn("[test] No project ID available");yn.info("[test] Fetching JWT API key",{projectId:o});const i=Date.now(),a=await(async(e,t)=>{try{yn.debug("Requesting JWT API key",{projectId:t,apiUrl:vr});const r=await(async({accessToken:e,projectId:t})=>{const r=await(n={auth:e,client:Cr(),path:{projectId:t}},(n.client??br).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/api-key",...n}));var n;if(r.error){const e=r.error?.error,{status:t}=r.response;throw new Error(e??`Failed to get API key: ${t}`)}return r.data})({accessToken:e,projectId:t});return yn.debug("JWT API key obtained",{keyPrefix:r.apiKey.substring(0,10)}),r.apiKey}catch(e){return void yn.warn("Failed to get JWT API key for test reporter",{error:e instanceof Error?e.message:String(e)})}})(n.auth.accessToken,o);yn.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 yn.info("[test] Stably test env resolved",{hasApiKey:!!c?.STABLY_API_KEY,projectId:c?.STABLY_PROJECT_ID,wsUrl:c?.STABLY_WS_URL??process.env.STABLY_WS_URL??"(default)"}),c},An=e=>e?{[Qt]:e}:void 0,Cn=b.z.object({context:b.z.string().min(1),autohealReportUrl:b.z.string()}),Rn=I.z.object({bucket:I.z.string(),key:I.z.string()}),Pn=I.z.object({diffBucketPath:Rn,expiresInSeconds:I.z.number(),key:I.z.string(),uploadUrl:I.z.string()}),Un=I.z.object({traceBucketPath:Rn,expiresInSeconds:I.z.number(),key:I.z.string(),uploadUrl:I.z.string(),sensitiveValues:I.z.array(I.z.string())}),kn=async({authHeader:e,contentType:t="text/plain",orgId:r,runId:n})=>{const s=await(o={auth:e,body:{contentType:t},client:Cr(),headers:An(r),path:{runId:n}},(o.client??br).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-diff/upload-url",...o,headers:{"Content-Type":"application/json",...o.headers}}));var o;if(s.error)throw new Error(`Failed to presign diff upload (${s.response.status})`);const i=Pn.parse(s.data);return{diffBucketPath:i.diffBucketPath,expiresInSeconds:i.expiresInSeconds,key:i.key,uploadUrl:i.uploadUrl}},Ln=async({contentType:e="text/plain",diff:t,uploadUrl:r})=>{const n=await fetch(r,{body:t,headers:{"Content-Type":e},method:"PUT"});if(!n.ok)throw new Error(`Failed to upload diff (${n.status})`)},Dn=async({authHeader:e,diffBucketPath:t,orgId:r,runId:n})=>{const s=(Cr().getConfig().baseUrl??"").replace(/\/$/,""),o=await fetch(`${s}/internal/v1/cli/runs/${encodeURIComponent(n)}/autoheal-diff/confirm-upload`,{method:"POST",headers:{"Content-Type":"application/json",...An(r),authorization:e},body:JSON.stringify(t)});if(!o.ok)throw new Error(`Failed to confirm diff upload (${o.status})`)},On=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=xr,onUserMessage:s}){this.authHeader=e,this.orgId=t,this.runId=r,this.url=n,this.onUserMessage=s,yn.info("[ws] Constructing AutohealWebSocketClient",{url:this.url,runId:r})}start(){this.connect()}connect(){if(!this._isClosed)try{const e={Authorization:this.authHeader};this.orgId&&(e["x-stably-org-id"]=this.orgId);const t=`${this.url}?runId=${encodeURIComponent(this.runId)}`;yn.info("[ws] Connecting",{url:t,attempt:this.reconnectAttempts}),this.socket=new q.default(t,{headers:e}),this.socket.on("open",()=>{yn.info("[ws] Connection opened"),this.reconnectAttempts=0}),this.socket.on("message",e=>{try{const t="string"==typeof e?e:e.toString(),r=JSON.parse(t);yn.debug("[ws] Received message",{type:r?.type}),"connected"===r?.type&&(yn.info("[ws] Authenticated successfully"),this.isAuthenticated=!0,this.authenticationFailed=!1,this.flushPending()),"user_message"===r?.type&&"string"==typeof r.content&&(yn.info("[ws] Received user message from web UI"),this.onUserMessage?.(r.content))}catch{}}),this.socket.on("close",(e,t)=>{yn.info("[ws] Connection closed",{code:e,authFailed:1008===e,reconnectAttempts:this.reconnectAttempts,maxReconnect:this.maxReconnectAttempts,isClosed:this._isClosed}),this.isAuthenticated=!1,1008===e&&(this.authenticationFailed=!0),!this._isClosed&&!this.authenticationFailed&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()}),this.socket.on("error",e=>{yn.warn("[ws] Connection error",{error:e.message})})}catch(e){yn.warn("[ws] Failed to create WebSocket",{error:e instanceof Error?e.message:String(e)}),this.scheduleReconnect()}}scheduleReconnect(){this._isClosed||this.reconnectTimer||(this.reconnectAttempts++,yn.info("[ws] Scheduling reconnect",{attempt:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts,delayMs:this.reconnectDelay}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect()},this.reconnectDelay))}isConnected(){return!!this.socket&&this.socket.readyState===q.default.OPEN&&this.isAuthenticated}sendProgress(e){if(this._isClosed)return void yn.debug("[ws] sendProgress called but client is closed",{phase:e.phase});const t={type:"autoheal_progress",payload:e};return this.pendingEvent=t,this.isConnected()?"complete"===e.phase?(yn.info("[ws] sendProgress: flushing terminal state immediately"),void this.flushPending()):void(this.debounceTimer||(this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.flushPending()},this.debounceMs))):(yn.debug("[ws] sendProgress: not connected, queuing event",{phase:e.phase,socketState:this.socket?.readyState,isAuthenticated:this.isAuthenticated,reconnectAttempts:this.reconnectAttempts}),void(this.socket?.readyState===q.default.CLOSED&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()))}flushPending(){if(this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),!this.pendingEvent)return;const e=this.pendingEvent;if(this.pendingEvent=null,!this.isConnected())return yn.debug("[ws] flushPending: not connected, re-queuing event",{phase:e.payload.phase}),void(this.pendingEvent=e);try{yn.debug("[ws] flushPending: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),t=>{t&&(yn.warn("[ws] flushPending: send failed",{error:t.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e))})}catch(t){yn.warn("[ws] flushPending: send threw",{error:t instanceof Error?t.message:String(t)}),this.pendingEvent=e}}close(){if(this._isClosed)return;yn.info("[ws] Closing WebSocket client"),this._isClosed=!0,this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.flushPending();const{socket:e}=this;this.socket=void 0,e&&setTimeout(()=>{e.close()},200)}},Bn=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=Sr,onUserMessage:s}){this.authHeader=e,this.orgId=t,this.sessionId=r,this.url=n,this.onUserMessage=s,yn.info("[ws] Constructing CreateProgressWebSocketClient",{url:this.url,sessionId:r})}start(){this.connect()}connect(){if(!this._isClosed)try{const e={Authorization:this.authHeader};this.orgId&&(e["x-stably-org-id"]=this.orgId);const t=`${this.url}?sessionId=${encodeURIComponent(this.sessionId)}`;yn.info("[ws] Connecting",{url:t,attempt:this.reconnectAttempts}),this.socket=new q.default(t,{headers:e}),this.socket.on("open",()=>{yn.info("[ws] Connection opened"),this.reconnectAttempts=0}),this.socket.on("message",e=>{try{const t="string"==typeof e?e:e.toString(),r=JSON.parse(t);yn.debug("[ws] Received message",{type:r?.type}),"connected"===r?.type&&(yn.info("[ws] Authenticated successfully"),this.isAuthenticated=!0,this.authenticationFailed=!1,this.flushPending()),"user_message"===r?.type&&"string"==typeof r.content&&(yn.info("[ws] Received user message from web UI"),this.onUserMessage?.(r.content))}catch{}}),this.socket.on("close",(e,t)=>{yn.info("[ws] Connection closed",{code:e,authFailed:1008===e,reconnectAttempts:this.reconnectAttempts,maxReconnect:this.maxReconnectAttempts,isClosed:this._isClosed}),this.isAuthenticated=!1,1008===e&&(this.authenticationFailed=!0),!this._isClosed&&!this.authenticationFailed&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()}),this.socket.on("error",e=>{yn.warn("[ws] Connection error",{error:e.message})})}catch(e){yn.warn("[ws] Failed to create WebSocket",{error:e instanceof Error?e.message:String(e)}),this.scheduleReconnect()}}scheduleReconnect(){this._isClosed||this.reconnectTimer||(this.reconnectAttempts++,yn.info("[ws] Scheduling reconnect",{attempt:this.reconnectAttempts,maxAttempts:this.maxReconnectAttempts,delayMs:this.reconnectDelay}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect()},this.reconnectDelay))}isConnected(){return!!this.socket&&this.socket.readyState===q.default.OPEN&&this.isAuthenticated}sendProgress(e){if(this._isClosed)return void yn.debug("[ws] sendProgress called but client is closed",{phase:e.phase});const t={type:"create_progress",payload:e};return this.pendingEvent=t,this.isConnected()?"complete"===e.phase?(yn.info("[ws] sendProgress: flushing terminal state immediately"),void this.flushPending()):void(this.debounceTimer||(this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.flushPending()},this.debounceMs))):(yn.debug("[ws] sendProgress: not connected, queuing event",{phase:e.phase,socketState:this.socket?.readyState,isAuthenticated:this.isAuthenticated,reconnectAttempts:this.reconnectAttempts}),void(this.socket?.readyState===q.default.CLOSED&&this.reconnectAttempts<this.maxReconnectAttempts&&this.scheduleReconnect()))}flushPending(){if(this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),!this.pendingEvent)return;const e=this.pendingEvent;if(this.pendingEvent=null,!this.isConnected())return yn.debug("[ws] flushPending: not connected, re-queuing event",{phase:e.payload.phase}),void(this.pendingEvent=e);try{yn.debug("[ws] flushPending: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),t=>{t&&(yn.warn("[ws] flushPending: send failed",{error:t.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e))})}catch(t){yn.warn("[ws] flushPending: send threw",{error:t instanceof Error?t.message:String(t)}),this.pendingEvent=e}}close(){if(this._isClosed)return;yn.info("[ws] Closing WebSocket client"),this._isClosed=!0,this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.flushPending();const{socket:e}=this;this.socket=void 0,e&&setTimeout(()=>{e.close()},200)}},Nn=/\.(spec|test)\.(c|m)?[jt]sx?$/,jn=e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"text"===t.type&&"string"==typeof t.text},$n=e=>null!=e&&"object"==typeof e&&"tool_response"in e,Mn=e=>{if(!e||"object"!=typeof e)return;const t=e;return Array.isArray(t.tool_response)?t.tool_response:void 0},Fn=e=>{const t=Mn(e);if(t)return t.filter(jn).map(e=>e.text).join("\n")||void 0},Hn=/\u001b\[[0-9;]*m/g,Gn=e=>e.replace(Hn,""),zn=/\$\{process\.env\.([A-Z_][A-Z0-9_]*)\}/g;function Wn({envVars:e}){return async t=>{if(!function(e){return Boolean(e&&"object"==typeof e&&"tool_input"in e&&e.tool_input&&"object"==typeof e.tool_input)}(t))return{decision:"approve"};const r=t.tool_input,n="string"==typeof r.text?r.text:void 0;if(!n)return{decision:"approve"};const s=n.replace(zn,(t,r)=>{const n=e[r];return null!=n?n:t});return s===n?{decision:"approve"}:{decision:"approve",hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",reason:"Evaluated environment variable placeholders in browser text input.",updatedInput:{...r,text:s}}}}}function Yn({onResult:e}){return async t=>{if(!$n(t))return{decision:"approve"};const r=Fn(t);if(!r)return{decision:"approve"};const n=function(e){const t=Gn(e),r=t.split(/Running \d+ tests? using \d+ workers?/).at(-1)??t,n=parseInt(r.match(/(\d+)\s+passed/g)?.at(-1)?.match(/(\d+)/)?.[1]??"0"),s=parseInt(r.match(/(\d+)\s+failed/g)?.at(-1)?.match(/(\d+)/)?.[1]??"0");if(0===n&&0===s)return;const o=[n>0?`${n} test${1===n?"":"s"} passed ✓`:void 0,s>0?`${s} test${1===s?"":"s"} failed ✗`:void 0].filter(e=>void 0!==e).join(", ");if(0===s)return o;const i=r.split(/\n\s+\d+\)\s+\[id=/).slice(1).map(e=>e.match(/\n\s{4}((?:TimeoutError|Error|AssertionError):\s*[^\n]+)/)?.[1]?.trim()).filter(e=>void 0!==e);return 0===i.length?o:`${o}\n${i.map(e=>` - ${e}`).join("\n")}`}(r);return n&&e(n),{decision:"approve"}}}function Vn({onResult:e}){return async t=>{if(!$n(t))return{decision:"approve"};const r=Fn(t);if(!r)return{decision:"approve"};const n=function(e){const t=Gn(e);if(t.match(/### Paused on error:/)){const e=t.match(/### Paused on error:\s*\n((?:TimeoutError|Error|AssertionError):\s*[^\n]+)/);return e?`Test paused on error - ${e[1].trim()}`:"Test paused on error"}const r=t.match(/(\d+)\s+passed/);if(r){const e=parseInt(r[1]);return`${e} test${1===e?"":"s"} passed ✓`}}(r);return n&&e(n),{decision:"approve"}}}var qn=/\.(spec|test)\.(ts|tsx|js|jsx|mts|mjs)$/;function Kn({onFileCreated:e}){return async t=>{const r=(e=>{if(!e||"object"!=typeof e)return;const t=e;return t.tool_input&&"object"==typeof t.tool_input&&!Array.isArray(t.tool_input)?t.tool_input:void 0})(t),n=r?.file_path;return"string"==typeof n&&qn.test(n)&&e(n),{decision:"approve"}}}var Jn=u.promisify(s.exec);async function Xn(){try{const{stdout:e}=await Jn('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 Jn(`pkill -KILL -P ${e} '.*' 2>/dev/null || true`)}))}catch{}}var Qn="sha256",Zn=/^---\r?\n([\s\S]*?)\r?\n---/;function es(e){const t=e.replace(Zn,"").replace(/^(\r?\n)+/,""),r=M.default.createHash(Qn).update(t,"utf8").digest("hex");return`${Qn}:${r}`}function ts(e){const t=e.match(/^\/\*\*[\s\S]*?@prompt-hash\s+(sha256:[a-f0-9]{64})[\s\S]*?\*\//);return t?.[1]}function rs({builtAt:e=new Date,promptFile:t,promptHash:r}){const n=Array.isArray(t)?t:[t],s=n[0]??"unknown",o=e.toISOString();return["/**"," * @generated by stably build",` * @prompt-hash ${r}`,...n.map(e=>` * @prompt-file ${e}`),` * @built-at ${o}`," *",` * DO NOT EDIT MANUALLY - regenerate with: stably build ${s} --force`," */"].join("\n")}function ns({workDir:e}){return async r=>{if(null==(n=r)||"object"!=typeof n||!("file_path"in n)||"string"!=typeof n.file_path)return{};var n;const s=r.file_path;if(!/\.(spec|test)\.[jt]sx?$/.test(s))return{};const o=t.resolve(e,s);if(!o.startsWith(t.resolve(e)+t.sep))return console.error(`[PromptHash Hook] Path traversal attempt blocked: ${s}`),{};let i;try{i=await g.readFile(o,"utf-8")}catch(e){return console.error(`[PromptHash Hook] Error reading ${s}:`,e),{}}const a=function(e){const t=e.match(/\/\/\s*@stably\.spec\s+(\S+)/);return t?.[1]}(i);if(!a)return{};const c=t.resolve(e,a);if(!c.startsWith(t.resolve(e)+t.sep))return console.error(`[PromptHash Hook] Path traversal attempt blocked: ${a}`),{};let l;try{l=await g.readFile(c,"utf-8")}catch{return{}}const u=es(l);if(ts(i)===u)return{};const d=rs({promptHash:u,promptFile:a});let p;const f=i.match(/\/\*\*[\s\S]*?@prompt-hash[\s\S]*?\*\/\n?/);p=f?i.replace(f[0],`${d}\n`):`${d}\n${i}`;try{await g.writeFile(o,p,"utf-8")}catch(e){console.error(`[PromptHash Hook] Error writing ${s}:`,e)}return{}}}var ss=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 os(e){try{const t=s.execSync("git branch --show-current",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(!t)return;return{branch:t}}catch{return}}var is=[".ts",".js",".mts",".mjs",".cts",".cjs"],as=10240,cs=async({defaultContent:e,fileName:t,filePath:r})=>{try{const e=(await g.stat(r)).size,n=await g.readFile(r,"utf-8"),s=Buffer.byteLength(n,"utf-8");if(s<=as)return n;const o=(e=>{const t=e.split("\n"),r=[];let n=!1,s=!1,o=0,i=!1;for(let e=0;e<t.length;e++){const a=t[e],c=a.trim();c.startsWith("/*")&&(n=!0),c.includes("*/")?n=!1:n||c.startsWith("//")&&!c.startsWith("///")||(c.startsWith("import ")||c.startsWith("export ")?(r.push(a),i=!0):i&&""===c?(r.push(a),i=!1):(i=!1,c.startsWith("type ")||c.startsWith("interface ")?r.push(a):c.startsWith("function ")||c.startsWith("const ")||c.startsWith("async function ")||c.startsWith("export function ")||c.startsWith("export const ")||c.startsWith("test.describe(")||c.startsWith("test(")?(r.push(a),s=!0,o=(a.match(/{/g)||[]).length-(a.match(/}/g)||[]).length,0===o&&(c.endsWith(";")||c.endsWith(","))&&(s=!1)):s?(o+=(a.match(/{/g)||[]).length,o-=(a.match(/}/g)||[]).length,0===o&&c.includes("}")?(r.push(a),s=!1):o>0&&" // ... implementation omitted ..."!==r.at(-1)&&r.push(" // ... implementation omitted ...")):c.match(/^[a-zA-Z_]+:/)&&r.push(a)))}return r.join("\n")})(n),i=Buffer.byteLength(o,"utf-8");return i<=as?o:o.slice(0,as)+`\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}},ls=async({defaultContent:e,dirName:t,dirPath:r})=>{try{const e=await g.readdir(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}},us=async({allowedEnvVars:e,mode:t,workspaceInfo:r,authHeader:n,customHeader:s,maxParallelWorkers:o})=>{const i=Cr(),a=os(r.absolutePath);yn.debug("Requesting system prompt from API",{mode:t,hasGitContext:!!a,envVarCount:e.length});const c=await(l={client:i,auth:n,body:{mode:t,workspaceInfo:r,allowedEnvVars:e,gitContext:a,maxParallelWorkers:o}},(l.client??br).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/prompts/system",...l,headers:{"Content-Type":"application/json",...l.headers}}));var l;if(401===c.response.status)throw yn.warn("System prompt fetch failed: unauthorized (401)"),await Gr(),new Error("Your session has expired or been revoked. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(403===c.response.status)throw yn.warn("System prompt fetch failed: forbidden (403)"),await Gr(),new Error("You no longer have access to this organization. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(c.error)throw yn.warn("System prompt fetch failed",{error:c.error}),new Error(`Failed to fetch system prompt: ${JSON.stringify(c.error)}`);const u=function({customHeader:e,systemPrompt:t}){return e?`${t}\n\nWhen writing or updating the generated test file, prepend this exact header at the top of the file without modification:\n\`\`\`ts\n${e}\n\`\`\``:t}({systemPrompt:c.data.systemPrompt,customHeader:s});return yn.debug("System prompt received",{size:u.length,appendedCustomHeader:!!s,hasPrContext:!!c.data.prContext}),{systemPrompt:u,prContext:c.data.prContext}},ds=".stably-playwright-wrapper.config.*",ps=[".ts",".js",".mts",".mjs",".cts",".cjs"];function fs(e){const r=t.resolve(e);if(i.existsSync(r))for(const e of ps){const n=t.join(r,`playwright.config${e}`);if(i.existsSync(n))return n}}var hs=["tests","e2e","__tests__","test"];function gs(e){try{return i.existsSync(e)&&i.statSync(e).isDirectory()}catch{return!1}}function ms(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(F.default.dim(`Using output directory: ${e} (from ${r})`))}var ys,bs=["mcp__playwright-test__","mcp__auto-heal-report__","mcp__test-doc-sync__","mcp__stably-agent-control__"],ws=["planner_","generator_"],vs={"mcp__stably-agent-control__restart_mcp_servers":"Restarting Browser Tools","mcp__session-control__restart_mcp_servers":"Restarting Browser Tools"},_s=(e,t)=>{const r=t.find(t=>e.startsWith(t));return r?e.slice(r.length):e},Es=e=>{const t=vs[e];if(t)return t;const r=_s(e,bs);return _s(r,ws).split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")},Is=(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},Ts=["test","bug","other"],xs={bug:"Application code defect; behavior diverges from expected requirements.",other:"External dependencies, environment, or infra issues outside test/app code.",test:"Test code is incorrect, out-of-date, or missing necessary setup."},Ss=e=>xs[e],As=/[^a-zA-Z0-9-_]/g,Cs=e=>{const t=e.trim().replace(As,"_");return t.length>0?t.slice(0,80):void 0},Rs=e=>"string"==typeof e?Cs(e):void 0,Ps=((e,t,r)=>(r=null!=e?K(Z(e)):{},((e,t,r,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let r of Q(t))ee.call(e,r)||void 0===r||J(e,r,{get:()=>t[r],enumerable:!(n=X(t,r))||n.enumerable});return e})(J(r,"default",{value:e,enumerable:!0}),e)))(re()),Us=A.createRequire("/");try{ys=Us("worker_threads").Worker}catch(e){}var ks=ys?function(e,t,r,n,s){var o=!1,i=new ys(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,ys.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}},Ls=Uint8Array,Ds=Uint16Array,Os=Int32Array,Bs=new Ls([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]),Ns=new Ls([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]),js=new Ls([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),$s=function(e,t){for(var r=new Ds(31),n=0;n<31;++n)r[n]=t+=1<<e[n-1];var s=new Os(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}},Ms=$s(Bs,2),Fs=Ms.b,Hs=Ms.r;Fs[28]=258,Hs[258]=28;var Gs,zs=$s(Ns,0),Ws=zs.b,Ys=zs.r,Vs=new Ds(32768);for(Js=0;Js<32768;++Js)Gs=(61680&(Gs=(52428&(Gs=(43690&Js)>>1|(21845&Js)<<1))>>2|(13107&Gs)<<2))>>4|(3855&Gs)<<4,Vs[Js]=((65280&Gs)>>8|(255&Gs)<<8)>>1;var qs=function(e,t,r){for(var n=e.length,s=0,o=new Ds(t);s<n;++s)e[s]&&++o[e[s]-1];var i,a=new Ds(t);for(s=1;s<t;++s)a[s]=a[s-1]+o[s-1]<<1;if(r){i=new Ds(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[Vs[d]>>c]=l}else for(i=new Ds(n),s=0;s<n;++s)e[s]&&(i[s]=Vs[a[e[s]-1]++]>>15-e[s]);return i},Ks=new Ls(288);for(Js=0;Js<144;++Js)Ks[Js]=8;for(Js=144;Js<256;++Js)Ks[Js]=9;for(Js=256;Js<280;++Js)Ks[Js]=7;for(Js=280;Js<288;++Js)Ks[Js]=8;var Js,Xs=new Ls(32);for(Js=0;Js<32;++Js)Xs[Js]=5;var Qs=qs(Ks,9,0),Zs=qs(Ks,9,1),eo=qs(Xs,5,0),to=qs(Xs,5,1),ro=function(e){for(var t=e[0],r=1;r<e.length;++r)e[r]>t&&(t=e[r]);return t},no=function(e,t,r){var n=t/8|0;return(e[n]|e[n+1]<<8)>>(7&t)&r},so=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(7&t)},oo=function(e){return(e+7)/8|0},io=function(e,t,r){return(null==t||t<0)&&(t=0),(null==r||r>e.length)&&(r=e.length),new Ls(e.subarray(t,r))},ao=["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"],co=function(e,t,r){var n=new Error(t||ao[e]);if(n.code=e,Error.captureStackTrace&&Error.captureStackTrace(n,co),!r)throw n;return n},lo=function(e,t,r,n){var s=e.length,o=n?n.length:0;if(!s||t.f&&!t.l)return r||new Ls(0);var i=!r,a=i||2!=t.i,c=t.i;i&&(r=new Ls(3*s));var l=function(e){var t=r.length;if(e>t){var n=new Ls(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=no(e,d,1);var b=no(e,d+1,3);if(d+=3,!b){var w=e[(P=oo(d)+4)-4]|e[P-3]<<8,v=P+w;if(v>s){c&&co(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=Zs,h=to,g=9,m=5;else if(2==b){var _=no(e,d,31)+257,E=no(e,d+10,15)+4,I=_+no(e,d+5,31)+1;d+=14;for(var T=new Ls(I),x=new Ls(19),S=0;S<E;++S)x[js[S]]=no(e,d+3*S,7);d+=3*E;var A=ro(x),C=(1<<A)-1,R=qs(x,A,1);for(S=0;S<I;){var P,U=R[no(e,d,C)];if(d+=15&U,(P=U>>4)<16)T[S++]=P;else{var k=0,L=0;for(16==P?(L=3+no(e,d,3),d+=2,k=T[S-1]):17==P?(L=3+no(e,d,7),d+=3):18==P&&(L=11+no(e,d,127),d+=7);L--;)T[S++]=k}}var D=T.subarray(0,_),O=T.subarray(_);g=ro(D),m=ro(O),f=qs(D,g,1),h=qs(O,m,1)}else co(1);if(d>y){c&&co(0);break}}a&&l(p+131072);for(var B=(1<<g)-1,N=(1<<m)-1,j=d;;j=d){var $=(k=f[so(e,d)&B])>>4;if((d+=15&k)>y){c&&co(0);break}if(k||co(2),$<256)r[p++]=$;else{if(256==$){j=d,f=null;break}var M=$-254;if($>264){var F=Bs[S=$-257];M=no(e,d,(1<<F)-1)+Fs[S],d+=F}var H=h[so(e,d)&N],G=H>>4;if(H||co(3),d+=15&H,O=Ws[G],G>3&&(F=Ns[G],O+=so(e,d)&(1<<F)-1,d+=F),d>y){c&&co(0);break}a&&l(p+131072);var z=p+M;if(p<O){var W=o-O,Y=Math.min(O,z);for(W+p<0&&co(3);p<Y;++p)r[p]=n[W+p]}for(;p<z;++p)r[p]=r[p-O]}}t.l=f,t.p=j,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?io(r,0,p):r.subarray(0,p)},uo=function(e,t,r){r<<=7&t;var n=t/8|0;e[n]|=r,e[n+1]|=r>>8},po=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},fo=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:vo,l:0};if(1==s){var i=new Ls(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 Ds(p+1),h=ho(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 Ls(f),l:h}},ho=function(e,t,r){return-1==e.s?Math.max(ho(e.l,t,r+1),ho(e.r,t,r+1)):t[e.s]=r},go=function(e){for(var t=e.length;t&&!e[--t];);for(var r=new Ds(++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}},mo=function(e,t){for(var r=0,n=0;n<t.length;++n)r+=e[n]*t[n];return r},yo=function(e,t,r){var n=r.length,s=oo(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)},bo=function(e,t,r,n,s,o,i,a,c,l,u){uo(t,u++,r),++s[256];for(var d=fo(s,15),p=d.t,f=d.l,h=fo(o,15),g=h.t,m=h.l,y=go(p),b=y.c,w=y.n,v=go(g),_=v.c,E=v.n,I=new Ds(19),T=0;T<b.length;++T)++I[31&b[T]];for(T=0;T<_.length;++T)++I[31&_[T]];for(var x=fo(I,7),S=x.t,A=x.l,C=19;C>4&&!S[js[C-1]];--C);var R,P,U,k,L=l+5<<3,D=mo(s,Ks)+mo(o,Xs)+i,O=mo(s,p)+mo(o,g)+i+14+3*C+mo(I,S)+2*I[16]+3*I[17]+7*I[18];if(c>=0&&L<=D&&L<=O)return yo(t,u,e.subarray(c,c+l));if(uo(t,u,1+(O<D)),u+=2,O<D){R=qs(p,f,0),P=p,U=qs(g,m,0),k=g;var B=qs(S,A,0);for(uo(t,u,w-257),uo(t,u+5,E-1),uo(t,u+10,C-4),u+=14,T=0;T<C;++T)uo(t,u+3*T,S[js[T]]);u+=3*C;for(var N=[b,_],j=0;j<2;++j){var $=N[j];for(T=0;T<$.length;++T){var M=31&$[T];uo(t,u,B[M]),u+=S[M],M>15&&(uo(t,u,$[T]>>5&127),u+=$[T]>>12)}}}else R=Qs,P=Ks,U=eo,k=Xs;for(T=0;T<a;++T){var F=n[T];if(F>255){po(t,u,R[257+(M=F>>18&31)]),u+=P[M+257],M>7&&(uo(t,u,F>>23&31),u+=Bs[M]);var H=31&F;po(t,u,U[H]),u+=k[H],H>3&&(po(t,u,F>>5&8191),u+=Ns[H])}else po(t,u,R[F]),u+=P[F]}return po(t,u,R[256]),u+P[256]},wo=new Os([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),vo=new Ls(0),_o=function(e,t,r,n,s,o){var i=o.z||e.length,a=new Ls(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=wo[t-1],p=d>>13,f=8191&d,h=(1<<r)-1,g=o.p||new Ds(32768),m=o.h||new Ds(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 Os(25e3),_=new Ds(288),E=new Ds(32),I=0,T=0,x=o.i||0,S=0,A=o.w||0,C=0;x+2<i;++x){var R=w(x),P=32767&x,U=m[R];if(g[P]=U,m[R]=P,A<=x){var k=i-x;if((I>7e3||S>24576)&&(k>423||!l)){u=bo(e,c,0,v,_,E,T,S,C,x-C,u),S=I=T=0,C=x;for(var L=0;L<286;++L)_[L]=0;for(L=0;L<30;++L)E[L]=0}var D=2,O=0,B=f,N=P-U&32767;if(k>2&&R==w(x-N))for(var j=Math.min(p,k)-1,$=Math.min(32767,x),M=Math.min(258,k);N<=$&&--B&&P!=U;){if(e[x+D]==e[x+D-N]){for(var F=0;F<M&&e[x+F]==e[x+F-N];++F);if(F>D){if(D=F,O=N,F>j)break;var H=Math.min(N,F-2),G=0;for(L=0;L<H;++L){var z=x-N+L&32767,W=z-g[z]&32767;W>G&&(G=W,U=z)}}}N+=(P=U)-(U=g[P])&32767}if(O){v[S++]=268435456|Hs[D]<<18|Ys[O];var Y=31&Hs[D],V=31&Ys[O];T+=Bs[Y]+Ns[V],++_[257+Y],++E[V],A=x+D,++I}else v[S++]=e[x],++_[e[x]]}}for(x=Math.max(x,A);x<i;++x)v[S++]=e[x],++_[e[x]];u=bo(e,c,l,v,_,E,T,S,C,x-C,u),l||(o.r=7&u|c[u/8|0]<<3,u-=7,o.h=m,o.p=g,o.i=x,o.w=A)}else{for(x=o.w||0;x<i+l;x+=65535){var q=x+65535;q>=i&&(c[u/8|0]=l,q=i),u=yo(c,u+1,e.subarray(x,q))}o.i=i}return io(a,0,n+oo(u)+s)},Eo=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}(),Io=function(e,t,r,n,s){if(!s&&(s={l:1},t.dictionary)){var o=t.dictionary.subarray(-32768),i=new Ls(o.length+e.length);i.set(o),i.set(e,o.length),e=i,s.w=o.length}return _o(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)},To=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},xo=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},So=[],Ao=function(){return[Ls,Ds,Os,Bs,Ns,js,Fs,Ws,Zs,to,Vs,ao,qs,ro,no,so,oo,io,co,lo,No,Ro,Po]},Co=function(){return[Ls,Ds,Os,Bs,Ns,js,Hs,Ys,Qs,Ks,eo,Xs,Vs,wo,vo,qs,uo,po,fo,ho,go,mo,yo,bo,oo,io,_o,Io,Bo,Ro]},Ro=function(e){return postMessage(e,[e.buffer])},Po=function(e){return e&&{out:e.size&&new Ls(e.size),dictionary:e.dictionary}},Uo=function(e,t,r,n,s,o){var i=function(e,t,r,n){if(!So[r]){for(var s="",o={},i=e.length-1,a=0;a<i;++a)s=xo(e[a],s,o);So[r]={c:xo(e[i],s,o),e:o}}var c=To({},So[r].e);return ks(So[r].c+";onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage="+t.toString()+"}",r,c,function(e){var t=[];for(var r in e)e[r].buffer&&t.push((e[r]=new e[r].constructor(e[r])).buffer);return t}(c),n)}(r,n,s,function(e,t){i.terminate(),o(e,t)});return i.postMessage([e,t],t.consume?[e.buffer]:[]),function(){i.terminate()}},ko=function(e,t){return e[t]|e[t+1]<<8},Lo=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},Do=function(e,t){return Lo(e,t)+4294967296*Lo(e,t+4)},Oo=function(e,t,r){for(;r;++t)e[t]=r,r>>>=8};function Bo(e,t){return Io(e,t||{},0,0)}function No(e,t){return lo(e,{i:2},t&&t.out,t&&t.dictionary)}var jo=function(e,t,r,n){for(var s in e){var o=e[s],i=t+s,a=n;Array.isArray(o)&&(a=To(n,o[1]),o=o[0]),o instanceof Ls?r[i]=[o,a]:(r[i+="/"]=[new Ls(0),a],jo(o,i,r,n))}},$o="undefined"!=typeof TextEncoder&&new TextEncoder,Mo="undefined"!=typeof TextDecoder&&new TextDecoder;try{Mo.decode(vo,{stream:!0})}catch(e){}function Fo(e,t){if($o)return $o.encode(e);for(var r=e.length,n=new Ls(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 Ls(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 io(n,0,s)}var Ho=function(e){var t=0;if(e)for(var r in e){var n=e[r].length;n>65535&&co(9),t+=n+4}return t},Go=function(e,t,r,n,s,o,i,a){var c=n.length,l=r.extra,u=a&&a.length,d=Ho(l);Oo(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)&&co(10),Oo(e,t,f<<25|p.getMonth()+1<<21|p.getDate()<<16|p.getHours()<<11|p.getMinutes()<<5|p.getSeconds()>>1),t+=4,-1!=o&&(Oo(e,t,r.crc),Oo(e,t+4,o<0?-o-2:o),Oo(e,t+8,r.size)),Oo(e,t+12,c),Oo(e,t+14,d),t+=16,null!=i&&(Oo(e,t,u),Oo(e,t+6,r.attrs),Oo(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;Oo(e,t,+h),Oo(e,t+2,m),e.set(g,t+4),t+=4+m}return u&&(e.set(a,t),t+=u),t},zo="function"==typeof queueMicrotask?queueMicrotask:"function"==typeof setTimeout?setTimeout:function(e){e()},Wo=[/^\/$/,/^\*+$/,/^[0-9]+$/],Yo=["/artifact/","https://","http://","*********"],Vo=Symbol.for("@ts-pattern/matcher"),qo=Symbol.for("@ts-pattern/isVariadic"),Ko="@ts-pattern/anonymous-select-key",Jo=e=>Boolean(e&&"object"==typeof e),Xo=e=>e&&!!e[Vo],Qo=(e,t,r)=>{if(Xo(e)){const n=e[Vo](),{matched:s,selections:o}=n.match(t);return s&&o&&Object.keys(o).forEach(e=>r(e,o[e])),s}if(Jo(e)){if(!Jo(t))return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let n=[],s=[],o=[];for(const t of e.keys()){const r=e[t];Xo(r)&&r[qo]?o.push(r):o.length?s.push(r):n.push(r)}if(o.length){if(o.length>1)throw new Error("Pattern error: Using `...P.array(...)` several times in a single pattern is not allowed.");if(t.length<n.length+s.length)return!1;const e=t.slice(0,n.length),i=0===s.length?[]:t.slice(-s.length),a=t.slice(n.length,0===s.length?1/0:-s.length);return n.every((t,n)=>Qo(t,e[n],r))&&s.every((e,t)=>Qo(e,i[t],r))&&(0===o.length||Qo(o[0],a,r))}return e.length===t.length&&e.every((e,n)=>Qo(e,t[n],r))}return Reflect.ownKeys(e).every(n=>{const s=e[n];return(n in t||Xo(o=s)&&"optional"===o[Vo]().matcherType)&&Qo(s,t[n],r);var o})}return Object.is(t,e)},Zo=e=>{var t,r,n;return Jo(e)?Xo(e)?null!=(t=null==(r=(n=e[Vo]()).getSelectionKeys)?void 0:r.call(n))?t:[]:Array.isArray(e)?ei(e,Zo):ei(Object.values(e),Zo):[]},ei=(e,t)=>e.reduce((e,r)=>e.concat(t(r)),[]);function ti(e){return Object.assign(e,{optional:()=>{return t=e,ti({[Vo]:()=>({match:e=>{let r={};const n=(e,t)=>{r[e]=t};return void 0===e?(Zo(t).forEach(e=>n(e,void 0)),{matched:!0,selections:r}):{matched:Qo(t,e,n),selections:r}},getSelectionKeys:()=>Zo(t),matcherType:"optional"})});var t},and:t=>ri(e,t),or:t=>function(...e){return ti({[Vo]:()=>({match:t=>{let r={};const n=(e,t)=>{r[e]=t};return ei(e,Zo).forEach(e=>n(e,void 0)),{matched:e.some(e=>Qo(e,t,n)),selections:r}},getSelectionKeys:()=>ei(e,Zo),matcherType:"or"})})}(e,t),select:t=>void 0===t?si(e):si(t,e)})}function ri(...e){return ti({[Vo]:()=>({match:t=>{let r={};const n=(e,t)=>{r[e]=t};return{matched:e.every(e=>Qo(e,t,n)),selections:r}},getSelectionKeys:()=>ei(e,Zo),matcherType:"and"})})}function ni(e){return{[Vo]:()=>({match:t=>({matched:Boolean(e(t))})})}}function si(...e){const t="string"==typeof e[0]?e[0]:void 0,r=2===e.length?e[1]:"string"==typeof e[0]?void 0:e[0];return ti({[Vo]:()=>({match:e=>{let n={[null!=t?t:Ko]:e};return{matched:void 0===r||Qo(r,e,(e,t)=>{n[e]=t}),selections:n}},getSelectionKeys:()=>[null!=t?t:Ko].concat(void 0===r?[]:Zo(r))})})}function oi(e){return!0}function ii(e){return"number"==typeof e}function ai(e){return"string"==typeof e}function ci(e){return"bigint"==typeof e}ti(ni(oi)),ti(ni(oi));var li=e=>Object.assign(ti(e),{startsWith:t=>{return li(ri(e,(r=t,ni(e=>ai(e)&&e.startsWith(r)))));var r},endsWith:t=>{return li(ri(e,(r=t,ni(e=>ai(e)&&e.endsWith(r)))));var r},minLength:t=>{return li(ri(e,(r=t,ni(e=>ai(e)&&e.length>=r))));var r},length:t=>{return li(ri(e,(r=t,ni(e=>ai(e)&&e.length===r))));var r},maxLength:t=>{return li(ri(e,(r=t,ni(e=>ai(e)&&e.length<=r))));var r},includes:t=>{return li(ri(e,(r=t,ni(e=>ai(e)&&e.includes(r)))));var r},regex:t=>{return li(ri(e,(r=t,ni(e=>ai(e)&&Boolean(e.match(r))))));var r}});li(ni(ai));var ui=e=>Object.assign(ti(e),{between:(t,r)=>{return ui(ri(e,(n=t,s=r,ni(e=>ii(e)&&n<=e&&s>=e))));var n,s},lt:t=>{return ui(ri(e,(r=t,ni(e=>ii(e)&&e<r))));var r},gt:t=>{return ui(ri(e,(r=t,ni(e=>ii(e)&&e>r))));var r},lte:t=>{return ui(ri(e,(r=t,ni(e=>ii(e)&&e<=r))));var r},gte:t=>{return ui(ri(e,(r=t,ni(e=>ii(e)&&e>=r))));var r},int:()=>ui(ri(e,ni(e=>ii(e)&&Number.isInteger(e)))),finite:()=>ui(ri(e,ni(e=>ii(e)&&Number.isFinite(e)))),positive:()=>ui(ri(e,ni(e=>ii(e)&&e>0))),negative:()=>ui(ri(e,ni(e=>ii(e)&&e<0)))});ui(ni(ii));var di=e=>Object.assign(ti(e),{between:(t,r)=>{return di(ri(e,(n=t,s=r,ni(e=>ci(e)&&n<=e&&s>=e))));var n,s},lt:t=>{return di(ri(e,(r=t,ni(e=>ci(e)&&e<r))));var r},gt:t=>{return di(ri(e,(r=t,ni(e=>ci(e)&&e>r))));var r},lte:t=>{return di(ri(e,(r=t,ni(e=>ci(e)&&e<=r))));var r},gte:t=>{return di(ri(e,(r=t,ni(e=>ci(e)&&e>=r))));var r},positive:()=>di(ri(e,ni(e=>ci(e)&&e>0))),negative:()=>di(ri(e,ni(e=>ci(e)&&e<0)))});di(ni(ci)),ti(ni(function(e){return"boolean"==typeof e})),ti(ni(function(e){return"symbol"==typeof e})),ti(ni(function(e){return null==e})),ti(ni(function(e){return null!=e}));var pi=class extends Error{constructor(e){let t;try{t=JSON.stringify(e)}catch(r){t=e}super(`Pattern matching error: no pattern matches value ${t}`),this.input=void 0,this.input=e}},fi={matched:!1,value:void 0},hi=class e{constructor(e,t){this.input=void 0,this.state=void 0,this.input=e,this.state=t}with(...t){if(this.state.matched)return this;const r=t[t.length-1],n=[t[0]];let s;3===t.length&&"function"==typeof t[1]?s=t[1]:t.length>2&&n.push(...t.slice(1,t.length-1));let o=!1,i={};const a=(e,t)=>{o=!0,i[e]=t},c=!n.some(e=>Qo(e,this.input,a))||s&&!Boolean(s(this.input))?fi:{matched:!0,value:r(o?Ko in i?i[Ko]:i:this.input,this.input)};return new e(this.input,c)}when(t,r){if(this.state.matched)return this;const n=Boolean(t(this.input));return new e(this.input,n?{matched:!0,value:r(this.input,this.input)}:fi)}otherwise(e){return this.state.matched?this.state.value:e(this.input)}exhaustive(e=gi){return this.state.matched?this.state.value:e(this.input)}run(){return this.exhaustive()}returnType(){return this}narrow(){return this}};function gi(e){throw new pi(e)}var mi=new Set(["sha1","_sha1","pageref","downloadsPath","tracesDir","pageId"]);function yi({sensitiveValues:e,str:t}){return e.reduce((e,t)=>e.replaceAll(t,"[REDACTED]"),t)}function bi({sensitiveValues:e,value:t}){return"string"==typeof t?yi({sensitiveValues:e,str:t}):Array.isArray(t)?t.map(t=>bi({sensitiveValues:e,value:t})):function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(t)?vi({obj:t,sensitiveValues:e}):t}function wi(e){return!!mi.has(e)||e.toLowerCase().endsWith("sha1")}function vi({obj:e,sensitiveValues:t}){return Object.fromEntries(Object.entries(e).map(([e,r])=>[e,wi(e)?r:bi({sensitiveValues:t,value:r})]))}function _i({error:e,sensitiveValues:t}){return e?{...e,message:yi({sensitiveValues:t,str:e.message})}:void 0}function Ei({content:e,sensitiveValues:t}){const r=new u.TextDecoder,n=new u.TextEncoder,s=yi({sensitiveValues:t,str:r.decode(e)});return n.encode(s)}var Ii=u.promisify(function(e,t,r){r||(r=t,t={}),"function"!=typeof r&&co(7);var n=[],s=function(){for(var e=0;e<n.length;++e)n[e]()},o={},i=function(e,t){zo(function(){r(e,t)})};zo(function(){i=r});for(var a=e.length-22;101010256!=Lo(e,a);--a)if(!a||e.length-a>65558)return i(co(13,0,1),null),s;var c=ko(e,a+8);if(c){var l=c,u=Lo(e,a+16),d=4294967295==u||65535==l;if(d){var p=Lo(e,a-12);(d=101075792==Lo(e,p))&&(l=c=Lo(e,p+32),u=Lo(e,p+48))}for(var f=t&&t.filter,h=function(t){var r=function(e,t,r){var n=ko(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(Mo)return Mo.decode(e);var s=function(e){for(var t="",r=0;;){var n=e[r++],s=(n>127)+(n>223)+(n>239);if(r+s>e.length)return{s:t,r:io(e,r-1)};s?3==s?(n=((15&n)<<18|(63&e[r++])<<12|(63&e[r++])<<6|63&e[r++])-65536,t+=String.fromCharCode(55296|n>>10,56320|1023&n)):t+=1&s?String.fromCharCode((31&n)<<6|63&e[r++]):String.fromCharCode((15&n)<<12|(63&e[r++])<<6|63&e[r++]):t+=String.fromCharCode(n)}}(e),o=s.s;return(r=s.r).length&&co(8),o}(e.subarray(t+46,t+46+n),!(2048&ko(e,t+8))),o=t+46+n,i=Lo(e,t+20),a=r&&4294967295==i?function(e,t){for(;1!=ko(e,t);t+=4+ko(e,t+2));return[Do(e,t+12),Do(e,t+4),Do(e,t+20)]}(e,o):[i,Lo(e,t+24),Lo(e,t+42)],c=a[0],l=a[1],u=a[2];return[ko(e,t+10),c,l,s,o+ko(e,t+30)+ko(e,t+32),u]}(e,u,d),a=r[0],l=r[1],p=r[2],h=r[3],g=r[4],m=r[5],y=function(e,t){return t+30+ko(e,t+26)+ko(e,t+28)}(e,m);u=g;var b=function(e,t){e?(s(),i(e,null)):(t&&(o[h]=t),--c||i(null,o))};if(!f||f({name:h,size:l,originalSize:p,compression:a}))if(a)if(8==a){var w=e.subarray(y,y+l);if(p<524288||l>.8*p)try{b(null,No(w,{out:new Ls(p)}))}catch(e){b(e,null)}else n.push(function(e,t,r){return r||(r=t,t={}),"function"!=typeof r&&co(7),Uo(e,t,[Ao],function(e){return Ro(No(e.data[0],Po(e.data[1])))},1,r)}(w,{size:p},b))}else b(co(14,"unknown compression type "+a,1),null);else b(null,io(e,y,y+l));else b(null,null)},g=0;g<l;++g)h()}else i(null,{});return s}),Ti=u.promisify(function(e,t,r){r||(r=t,t={}),"function"!=typeof r&&co(7);var n={};jo(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){zo(function(){r(e,t)})};zo(function(){p=r});var f=function(){var e=new Ls(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;Go(e,a,s,s.f,s.u,o);var u=30+s.f.length+Ho(s.extra),d=a+u;e.set(s.c,d),Go(e,i,s,s.f,s.u,o,a,s.m),i+=16+u+(s.m?s.m.length:0),a=d+o}catch(e){return p(e,null)}}!function(e,t,r,n,s){Oo(e,t,101010256),Oo(e,t+8,r),Oo(e,t+10,r),Oo(e,t+12,n),Oo(e,t+16,s)}(e,i,l.length,r,t),p(null,e)};o||f();for(var h=function(e){var t=s[e],r=n[t],c=r[0],h=r[1],g=function(){var e=-1;return{p:function(t){for(var r=e,n=0;n<t.length;++n)r=Eo[255&r^t[n]]^r>>>8;e=r},d:function(){return~e}}}(),m=c.length;g.p(c);var y=Fo(t),b=y.length,w=h.comment,v=w&&Fo(w),_=v&&v.length,E=Ho(h.extra),I=0==h.level?0:8,T=function(r,n){if(r)d(),p(r,null);else{var s=n.length;l[e]=To(h,{size:m,crc:g.d(),c:n,f:y,m:v,u:b!=t.length||v&&w.length!=_,compression:I}),i+=30+b+E+s,a+=76+2*(b+E)+(_||0)+s,--o||f()}};if(b>65535&&T(co(11,0,1),null),I)if(m<16e4)try{T(null,Bo(c,h))}catch(e){T(e,null)}else u.push(function(e,t,r){return r||(r=t,t={}),"function"!=typeof r&&co(7),Uo(e,t,[Co],function(e){return Ro(Bo(e.data[0],e.data[1]))},0,r)}(c,h,T));else T(null,c)},g=0;g<c;++g)h(g);return d});async function xi({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 u.TextDecoder,n=new u.TextEncoder,s=r.decode(e).split("\n").map(e=>{if(!e.trim())return e;try{const r=function({event:e,sensitiveValues:t}){return(r=e,new hi(r,fi)).with({type:"console"},e=>({...e,args:e.args?.map(e=>({...e,preview:yi({sensitiveValues:t,str:e.preview}),value:bi({sensitiveValues:t,value:e.value})})),text:yi({sensitiveValues:t,str:e.text})})).with({type:"before"},e=>({...e,params:vi({obj:e.params,sensitiveValues:t}),title:e.title?yi({sensitiveValues:t,str:e.title}):void 0})).with({type:"after"},e=>({...e,error:_i({error:e.error,sensitiveValues:t}),result:void 0!==e.result?bi({sensitiveValues:t,value:e.result}):void 0})).with({type:"action"},e=>({...e,error:_i({error:e.error,sensitiveValues:t}),params:vi({obj:e.params,sensitiveValues:t}),result:void 0!==e.result?bi({sensitiveValues:t,value:e.result}):void 0,title:e.title?yi({sensitiveValues:t,str:e.title}):void 0})).with({type:"event"},e=>({...e,params:vi({obj:e.params,sensitiveValues:t})})).with({type:"stdout"},{type:"stderr"},e=>({...e,text:void 0!==e.text?yi({sensitiveValues:t,str:e.text}):void 0})).with({type:"error"},e=>({...e,message:yi({sensitiveValues:t,str:e.message})})).with({type:"log"},e=>({...e,message:yi({sensitiveValues:t,str:e.message})})).with({type:"context-options"},e=>({...e,options:vi({obj:e.options,sensitiveValues:t}),title:e.title?yi({sensitiveValues:t,str:e.title}):void 0})).with({type:"frame-snapshot"},e=>({...e,snapshot:vi({obj:e.snapshot,sensitiveValues:t})})).with({type:"resource-snapshot"},e=>({...e,snapshot:vi({obj:e.snapshot,sensitiveValues:t})})).with({type:"screencast-frame"},{type:"input"},e=>e).exhaustive();var r}({event:JSON.parse(e),sensitiveValues:t});return JSON.stringify(r)}catch{return yi({sensitiveValues:t,str:e})}});return n.encode(s.join("\n"))}({content:e,sensitiveValues:r}):n.endsWith(".html")||n.endsWith(".dat")||n.endsWith(".json")?Ei({content:e,sensitiveValues:r}):n.startsWith("resources/")?async function({content:e,sensitiveValues:t}){return await(0,Ps.isBinaryFile)(Buffer.from(e))?e:Ei({content:e,sensitiveValues:t})}({content:e,sensitiveValues:r}):e}function Si(e=process.cwd()){let r=t.resolve(e);for(;;){const e=Ai(r);if(e){const n={...e.dependencies,...e.devDependencies},s="@playwright/test"in n?"@playwright/test":"playwright"in n?"playwright":void 0;if(s){const e=Ci(r);let n=!1,o=r;for(;;){const e=t.join(o,"node_modules"),r=t.join(e,s);if(i.existsSync(r)){n=!0;break}const a=t.dirname(o);if(a===o)break;o=a}return{inNodeModules:n,installed:!0,packageManager:e,packageName:s}}}const n=t.dirname(r);if(n===r)return{inNodeModules:!1,installed:!1,packageManager:void 0};r=n}}function Ai(e){const r=t.join(e,"package.json");let n;try{n=i.readFileSync(r,"utf-8")}catch{return}try{return JSON.parse(n)}catch{return}}function Ci(e){const r=[["npm","package-lock.json"],["pnpm","pnpm-lock.yaml"],["yarn","yarn.lock"]];let n=e;for(;;){for(const[e,s]of r)if(i.existsSync(t.join(n,s)))return e;const e=t.dirname(n);if(e===n)return;n=e}}function Ri(e){if("npm"===e)return["npx","playwright"];if("pnpm"===e)return["pnpm","exec","playwright"];if("yarn"===e)return["yarn","playwright"];throw new Error("Package manager not supported")}var Pi=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Ui=e=>(e instanceof Error?e.message:String(e)).slice(0,400),ki=({outputDir:e,representativeTest:t})=>{const r=["test","--trace=on","--workers=1","--retries=0","--output",e];return t.filePath&&r.push(t.filePath),t.testIdentifier?r.push("--grep",`^${Pi(t.testIdentifier)}$`):t.testTitle&&r.push("--grep",Pi(t.testTitle)),r},Li=async e=>{const t=await g.readdir(e,{withFileTypes:!0}),r=[];for(const n of t){const t=D.default.join(e,n.name);if(n.isDirectory())r.push(...await Li(t));else if(n.isFile()&&"trace.zip"===n.name){const e=await g.stat(t);r.push({path:t,mtimeMs:e.mtimeMs})}}return r},{zSuiteAutoHealReport:Di,zRepresentativeTest:Oi}=function(e){const t=e.enum(Ts),r=["Classification of the root cause:","",`- test: ${Ss("test")}`,`- bug: ${Ss("bug")}`,`- other: ${Ss("other")}`].join("\n"),n=e.object({filePath:e.string().optional(),testIdentifier:e.string().optional(),testTitle:e.string().optional()}),s=e.object({status:e.enum(["captured","capture_failed","upload_failed"]),representativeTest:n,storage:e.object({bucket:e.string(),key:e.string()}).optional(),signedUrl:e.string().optional(),error:e.string().optional()}),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 and fix (must be existing IDs only)."),rootCause:e.string().describe("Brief explanation of what happened (1-2 sentences).")}),a=e.discriminatedUnion("result",[i.extend({fixApplied:e.string().describe("What fix was applied (brief, specific)."),result:e.literal("fixed"),traceProof:s.optional().describe("Optional trace proof metadata for fixed issues."),traceProofs:e.array(o).min(1).optional().describe("Optional per-test trace proof metadata for fixed issues.")}),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)."),result:e.literal("unfixed")})]);return{zAutoHealReport:a,zIssueCategory:t,zRepresentativeTest:n,zSuiteAutoHealReport:e.object({issues:e.array(a).min(1).describe("List of all auto-heal issues/outcomes for this suite."),summary:e.string().min(3).describe("High-level summary (2-3 sentences) of the suite auto-heal results.")}),zTraceProof:s,zTraceProofByTest:o}}(I.z),Bi=({authHeader:e,diffTracker:t,orgId:r,runId:n,workingDir:o})=>d.createSdkMcpServer({name:"auto-heal-report",tools:[d.tool("capture-trace-proof",["Capture and upload a Playwright trace proof for a fixed issue or fixed test case.","","Use this only for fixed results. Pass representative test info from the worker.","Pass testCaseId and call once per fixed test case.","testCaseId is for per-test mapping/storage metadata; representativeTest selects the runnable test."].join("\n"),{issueId:I.z.string().min(1).describe("Issue identifier for deterministic output paths and storage key naming."),proofId:I.z.string().min(1).optional().describe("Optional id for deterministic proof naming and deduplication."),representativeTest:Oi.optional().default({}),testCaseId:I.z.string().min(1).optional().describe("Optional test case ID when capturing per-test trace proofs.")},async({issueId:t,proofId:a,representativeTest:c,testCaseId:l})=>{const u=I.z.string().min(1).parse(t),d=null==a?void 0:I.z.string().min(1).parse(a),p=null==l?void 0:I.z.string().min(1).parse(l),f=await(async({authHeader:e,issueId:t,orgId:r,proofId:n,representativeTest:o,runId:a,testCaseId:c,workingDir:l})=>{if(!(e=>null!=e.filePath||null!=e.testTitle||null!=e.testIdentifier)(o))return{status:"capture_failed",representativeTest:o,error:"Representative test info is missing (need filePath, testTitle, or testIdentifier)."};const u=Si(l);if(!u.installed||!u.inNodeModules||!u.packageManager)return{status:"capture_failed",representativeTest:o,error:"Playwright is not installed in the current workspace."};const d=(e=>Cs(e)??"issue")(t),p=(({proofId:e,testCaseId:t})=>Rs(t)??Rs(e))({testCaseId:c,proofId:n}),f=D.default.join(l,".stably","autoheal-proof",d,p??"issue"),[h,...m]=Ri(u.packageManager),y=[...m,...ki({outputDir:f,representativeTest:o})];try{await g.rm(f,{force:!0,recursive:!0}),await g.mkdir(f,{recursive:!0});const{code:u,stderr:d,timedOut:p}=await(async({args:e,command:t,cwd:r,timeoutMs:n})=>await new Promise((o,i)=>{const a=s.spawn(t,e,{cwd:r,env:process.env,stdio:["ignore","ignore","pipe"]});let c="",l=!1;a.stderr.on("data",e=>{c+=e.toString()});const u=setTimeout(()=>{l=!0,a.kill("SIGTERM")},n);a.on("error",e=>{clearTimeout(u),i(e)}),a.on("close",e=>{clearTimeout(u),o({code:e,stderr:c,timedOut:l})})}))({args:y,command:h,cwd:l,timeoutMs:3e5});if(p)return{status:"capture_failed",representativeTest:o,error:"Trace proof run timed out while executing Playwright verification."};if(0!==u)return{status:"capture_failed",representativeTest:o,error:`Trace proof run failed (exit code ${u??"unknown"}): ${d.trim().slice(0,280)}`};const m=await(async e=>{const t=await Li(e);if(0!==t.length)return t.sort((e,t)=>t.mtimeMs-e.mtimeMs),t[0]?.path})(f);if(!m)return{status:"capture_failed",representativeTest:o,error:"Trace proof run completed, but no trace.zip was produced."};const{traceBucketPath:b,uploadUrl:w,sensitiveValues:v}=await(async({authHeader:e,issueId:t,proofId:r,testCaseId:n,contentType:s="application/zip",orgId:o,runId:i})=>{const a=await(c={auth:e,body:{contentType:s,issueId:t,proofId:r,testCaseId:n},client:Cr(),headers:An(o),path:{runId:i}},(c.client??br).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=Un.parse(a.data);return{traceBucketPath:l.traceBucketPath,expiresInSeconds:l.expiresInSeconds,key:l.key,uploadUrl:l.uploadUrl,sensitiveValues:l.sensitiveValues}})({authHeader:e,issueId:t,proofId:n,orgId:r,runId:a,testCaseId:c}),_=await async function({tracePath:e,sensitiveValues:t}){const r=[],n=i.createReadStream(e);for await(const e of n)r.push(e);return async function({sensitiveValues:e,traceBuffer:t}){const r=e.filter(e=>!(e.length<3||Wo.some(t=>t.test(e))||Yo.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 Ii(new Uint8Array(t)),o=Object.entries(s),i=await Promise.all(o.map(async([e,t])=>[e,await xi({content:t,filename:e,sensitiveValues:n})])),a=Object.fromEntries(i);return Ti(a)}({traceBuffer:new Uint8Array(Buffer.concat(r)),sensitiveValues:t})}({tracePath:m,sensitiveValues:v});try{await(async({contentType:e="application/zip",traceBuffer:t,uploadUrl:r})=>{const n=await fetch(r,{body:Buffer.from(t),headers:{"Content-Type":e},method:"PUT"});if(!n.ok)throw new Error(`Failed to upload trace (${n.status})`)})({traceBuffer:_,uploadUrl:w})}catch(e){return{status:"upload_failed",representativeTest:o,error:Ui(e)}}return{status:"captured",representativeTest:o,storage:b}}catch(e){return{status:"capture_failed",representativeTest:o,error:Ui(e)}}})({authHeader:e,issueId:u,orgId:r,proofId:d,representativeTest:Oi.parse(c??{}),runId:n,testCaseId:p,workingDir:o}),h="string"==typeof p?{testCaseId:p,...f}:f;return{content:[{text:JSON.stringify(h),type:"text"}]}}),d.tool("generate-report",["After attempting to fix all broken tests (skip only those truly infeasible), generate and return a suite auto-heal report in the required schema.","","Ensure the payload matches zSuiteAutoHealReport exactly; include every issue discovered."].join("\n"),{report:Di},async({report:s})=>{const o=await t.computeDiff(),i=(e=>{if(!e||"object"!=typeof e)return e;const t=e;if(!Array.isArray(t.issues))return e;const r=t.issues.map(e=>{if(!e||"object"!=typeof e)return e;const t=e;if("fixed"!==t.result||null!=t.traceProof||!Array.isArray(t.traceProofs))return e;const[r]=t.traceProofs;if(!r||"object"!=typeof r)return e;const n={...r};return delete n.testCaseId,{...t,traceProof:n}});return{...t,issues:r}})(s),a=Di.parse(i);try{await(async({authHeader:e,orgId:t,report:r,runId:n})=>{const s=await(o={auth:e,body:{report:JSON.stringify(r)},client:Cr(),headers:An(t),path:{runId:n}},(o.client??br).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-report",...o,headers:{"Content-Type":"application/json",...o.headers}}));var o;if(s.error)throw new Error(`Failed to upload auto-heal report (${s.response.status})`)})({authHeader:e,orgId:r,report:a,runId:n});const{diffBucketPath:t,uploadUrl:s}=await kn({authHeader:e,contentType:"text/plain",orgId:r,runId:n});await Ln({contentType:"text/plain",diff:o,uploadUrl:s}),await Dn({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"}),Ni=({onComplete:e,onRestartRequested:t})=>e?d.createSdkMcpServer({name:"session-control",tools:[d.tool("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:I.z.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}`)})]}):d.createSdkMcpServer({name:"stably-agent-control",version:"1.0.0",tools:[d.tool("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 servers are being restarted. Browser tools will be reinitialized."}]})))]}),ji=I.z.object({commentUrl:I.z.string()}),$i=({prContext:e,authHeader:t,orgId:r,onReportPosted:n})=>d.createSdkMcpServer({name:"create-report",tools:[d.tool("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:I.z.string().describe("A summary of the tests created. Include what features/flows are tested and any important notes."),filesCreated:I.z.array(I.z.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:[];yn.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",vr).toString(),a={Authorization:e,"Content-Type":"application/json"};t&&(a["x-stably-org-id"]=t),yn.debug("Posting create report to GitHub",{prNumber:r,owner:n,repo: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 yn.error("Failed to post create report",{status:c.status,error:e.slice(0,500)}),new Error(`Failed to post create report: ${c.status} ${e.slice(0,200)}`)}const l=ji.parse(await c.json());return yn.info("Create report posted successfully",{commentUrl:l.commentUrl}),l}({authHeader:t,orgId:r,prNumber:e.prNumber,owner:e.owner,repo:e.repo,report:o});return n?.(a),yn.info("[create-report] Report posted successfully",{commentUrl:a.commentUrl}),{content:[{type:"text",text:`✅ Test creation report posted to PR #${e.prNumber}\n\nView the comment: ${a.commentUrl}`}]}}catch(e){const t=e instanceof Error?e.message:String(e);return yn.error("[create-report] Failed to post report",{error:t}),{content:[{type:"text",text:`❌ Failed to post report to GitHub: ${t}\n\nThe tests were still created successfully, but the PR comment could not be posted.`}],isError:!0}}})]}),Mi=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]"),Fi=(e,t)=>({message:Mi(e),status:t?.status,statusText:t?.statusText}),Hi=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"]),Gi=async({authHeader:e,mode:t,maxTurnsOverride:r})=>{const n=Cr();yn.debug("Requesting subagent definitions from API",{mode:t,maxTurnsOverride:r});const s=await(o={client:n,auth:e,body:{mode:t,maxTurnsOverride:r}},(o.client??br).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/prompts/subagents",...o,headers:{"Content-Type":"application/json",...o.headers}}));var o;if(401===s.response.status)throw yn.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 yn.warn("Subagent definitions fetch failed: forbidden (403)"),await Gr(),new Error("You no longer have access to this organization. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(s.error)throw yn.warn("Subagent definitions fetch failed",{error:s.error}),new Error(`Failed to fetch subagent definitions: ${JSON.stringify(s.error)}`);const{subagents:i}=s.data;return yn.debug("Subagent definitions received",{count:Object.keys(i).length}),i},{zStablyYaml:zi}=function(e){const t=e.object({cron:e.string(),stablyTestArgs:e.string().optional(),timezone:e.string().optional()}),r=e.object({maxTurnsPerIssue:e.number().int().positive().optional(),maxParallelWorkers:e.number().int().positive().optional(),rules:e.string().optional()}),n=e.object({fix:r.optional()});return{zStablyYaml:e.object({schedules:e.record(e.string(),t).optional(),agent:n.optional()}),zAgentConfig:n,zAgentFixConfig:r,zScheduleEntry:t}}(b.z),Wi=["Bash","Read","Write","Edit","Glob","Grep","Task","Skill"],Yi=["Task","mcp__playwright-test","Skill"],Vi=["Bash","Read","Write","Edit","Glob","Grep","mcp__session-control"],qi=e=>{if("EPIPE"!==e.code)throw e},Ki="__main__",Ji=e=>"mcp__auto-heal-report__generate-report"===e,Xi=e=>"mcp__auto-heal-report__capture-trace-proof"===e?"Verify Test Run":"mcp__auto-heal-report__generate-report"===e?"Generate Report":Es(e);async function Qi(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)}))}var Zi=async r=>{if("single"===r.mode||"build"===r.mode){const e=Array.isArray(r.prompt)?r.prompt.join(" "):r.prompt;yn.initSession(e||"create-from-diff")}else"fix"===r.mode&&yn.initSession(`fix-${r.runId}`);yn.info("Agent session starting",{mode:r.mode}),process.stdout.on("error",qi),process.stderr.on("error",qi);const n=e=>{if("EPIPE"!==e.code)throw e};process.on("uncaughtException",n),yn.debug("Checking authentication");const s=await In({autoLogin:"chat"===r.mode||"init"===r.mode}),o=(e=>"env"===e.type?e.auth.apiKey:e.auth.accessToken)(s);yn.debug("Authentication resolved",{authType:s.type});const c="oauth"===s.type?s.auth.context.orgId:void 0,l=D.default.resolve(process.cwd()),u=D.default.join(l,".env"),p=N.default.existsSync(u)&&N.default.statSync(u).isFile(),f=p?e.parse(N.default.readFileSync(u,"utf8")):{};yn.debug("Environment file",{path:u,exists:p,variableCount:Object.keys(f).length});const h="chat"!==r.mode&&"init"!==r.mode,m="chat"===r.mode;let y=new ss;const b="chat"===r.mode?r.getHelpText:void 0,w={log:[],promptDisplay:"chat"===r.mode?"Ask Stably to build tests for you":"init"===r.mode?"Setting up Playwright and Stably SDK":"fix"===r.mode?"Fixing broken tests":(Array.isArray(r.prompt)?r.prompt.join(" "):r.prompt)?.trim()||"Creating tests from PR/branch changes",status:"running"};let v,_,E,I,T=h,A=!1,R=!1,U=0,k=0,L=!1;const O=[];let B,j,$=[],H=!1,G=!1,z=0;const W=new Map;let Y=null,V=!1,q=!1;const K=Date.now();let J,X="fix"===r.mode?{suiteId:r.runId,phase:"initializing",totalTests:null,fixedTests:0,failedTests:0,currentTestDescription:null,lastTestDescription:null,startedAt:K,endedAt:null,isError:!1,updatedAt:K,recentActivity:[],workers:[{id:Ki,testDescription:"Orchestrator",workerType:"main",status:"running",summary:null,startedAt:K,endedAt:null,activity:[]}]}:null;const Q=new Set,Z=(e,t)=>{if(!X)return;const r=X.workers.map(r=>{if(r.id!==e)return r;const n=[...r.activity,{...t,timestamp:Date.now()}].slice(-15);return{...r,activity:n}});re({workers:r})},ee=e=>{if(!X)return;const t=[...X.recentActivity,{...e,timestamp:Date.now()}].slice(-10);re({recentActivity:t})},te=e=>(X?.workers??[]).map(t=>t.id===Ki?{...t,status:e?"failed":"succeeded",endedAt:t.endedAt??Date.now()}:"running"===t.status?{...t,status:"failed",endedAt:Date.now()}:t),re=e=>{X&&!J?.isClosed&&(X={...X,...e,updatedAt:Date.now()},J?.sendProgress(X))},ne=async e=>{if("fix"===r.mode){if("STARTED"===e){if(V)return;V=!0}else{if(q)return;q=!0}try{await(async({authHeader:e,orgId:t,runId:r,status:n})=>{const s=await(o={auth:e,body:{status:n},client:Cr(),headers:An(t),path:{runId:r}},(o.client??br).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-status",...o,headers:{"Content-Type":"application/json",...o.headers}}));var o;if(s.error)throw new Error(`Failed to update autoheal status (${s.response.status})`)})({authHeader:o,orgId:c,runId:r.runId,status:e})}catch{}}},se="single"===r.mode||"build"===r.mode,oe=Date.now();let ie,ae=null;const ce=e=>{ae&&!ie?.isClosed&&(ae={...ae,...e,updatedAt:Date.now()},ie?.sendProgress(ae))},le=e=>{if(!ae)return;const t=[...ae.recentActivity,{...e,timestamp:Date.now()}].slice(-10);ce({recentActivity:t})};if(se||"fix"===r.mode)try{const e=new URL("/internal/v1/cli/progress",vr).toString(),t={Authorization:o,"Content-Type":"application/json"};c&&(t["x-stably-org-id"]=c);const n="single"===r.mode?"create":"build"===r.mode?"build":"fix",i=await fetch(e,{method:"POST",headers:t,body:JSON.stringify({mode:n,projectId:Tn(s),agentId:M.default.randomUUID(),..."fix"===r.mode?{playwrightSuiteRunId:r.runId}:{}}),signal:AbortSignal.timeout(1e4)});if(i.ok){const{sessionId:e}=await i.json();if(se){const t="single"===r.mode||"build"===r.mode?Array.isArray(r.prompt)?r.prompt.join(" "):r.prompt:null,n=os(l);ae={sessionId:e,phase:"initializing",startedAt:oe,endedAt:null,isError:!1,updatedAt:oe,currentActivity:null,filesCreated:[],recentActivity:[],prompt:t||null,environment:{gitBranch:n?.branch??null,workingDirectory:l,nodeVersion:process.version,cliVersion:wr}},ie=new Bn({authHeader:o,orgId:c,sessionId:e,onUserMessage:e=>{y&&(yn.info("[ws] Injecting web UI message into agent",{contentLength:e.length}),le({type:"user_message",summary:e}),ye({text:`[Web] ${e}`}),y.pushText(`[Message from web UI user]: ${e}`),T||(T=!0,xe({status:"running"})))}}),ie.start(),ce({phase:"initializing"})}yn.info(`[${n}] Progress session created`,{sessionId:e})}else{const t=await i.text().catch(()=>"");yn.warn(`[${n}] Failed to create progress session: ${i.status} ${e} — ${t.slice(0,300)}`)}}catch(e){const t=e instanceof Error?e.message:String(e);yn.warn(`[progress] Session creation failed (non-fatal): ${t}`)}const ue={current:e=>{}},de={current:async()=>{}},{addSubagentActivity:pe,addSubagentStart:fe,addTool:he,addToolResult:ge,appendText:me,appendUserMessage:ye,cleanup:be,setExiting:we,setRunningLabel:ve,setStatus:_e,setSubagentStatus:Ee,updateFixProgress:Ie}=await(async(e,t)=>{const{Box:r,Static:n,Text:s,render:o,useInput:i}=await import("ink"),a=!!process.stdin.isTTY,c=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],l=()=>S.jsx(s,{inverse:!0,children:" "}),u=(({Box:e,Text:t,useInput:r},n,s)=>function({onChoice:o,prompt:i}){const[a,c]=x.useState(0),[l,u]=x.useState(!1),[d,p]=x.useState(""),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=Es(i.toolName),g=Is(i.toolName,i.input);return S.jsxs(e,{borderColor:"yellow",borderStyle:"round",flexDirection:"column",marginTop:1,paddingX:1,paddingY:0,children:[S.jsx(t,{bold:!0,color:"yellow",children:"Permission Required"}),S.jsxs(e,{flexDirection:"column",marginTop:1,children:[S.jsx(t,{color:"magenta",children:h}),null!=g&&S.jsxs(t,{color:"gray",children:[" ",g]})]}),null!=i.decisionReason&&S.jsx(e,{marginTop:1,children:S.jsxs(t,{color:"gray",children:["Reason: ",i.decisionReason]})}),l?S.jsxs(e,{flexDirection:"column",marginTop:1,children:[S.jsx(t,{color:"gray",children:"Enter message for AI (press Enter to submit, Esc to cancel):"}),S.jsxs(t,{children:[S.jsx(t,{color:"yellow",children:">"})," ",d,S.jsx(n,{})]})]}):S.jsxs(e,{flexDirection:"column",marginTop:1,children:[S.jsx(t,{color:"gray",children:"Use ↑↓ arrows or number keys to select:"}),f.map((e,r)=>S.jsx(t,{children:S.jsxs(t,{color:r===a?"cyan":void 0,children:[r===a?"❯":" "," ",r+1,". ",e.label]})},e.value))]})]})})({Box:r,Text:s,useInput:i},l,a),d=(({Cursor:e,inkComponents:{Box:t,Static:r,Text:n,useInput:s},isRawModeSupported:o,PermissionPrompt:i,Spinner:a})=>{const c=({progress:e})=>{const[r,s]=x.useState(Date.now());x.useEffect(()=>{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),c=i%60,l=a>0?`${a}m ${c.toString().padStart(2,"0")}s`:`${c}s`,{label:u,color:d}={initializing:{label:"Fetching test results",color:"gray"},triage:{label:"Triaging failures",color:"yellow"},fixing:{label:"Fixing tests",color:"cyan"},validation:{label:"Validating fixes",color:"blue"},complete:{label:"Complete",color:"green"}}[e.phase],p=e.fixedTests+e.failedTests,f="fixing"===e.phase&&p>0?null!==e.totalTests?` (fixed ${e.fixedTests}/${e.totalTests}${e.failedTests>0?`, failed ${e.failedTests}`:""})`:` (fixed ${e.fixedTests}${e.failedTests>0?`, failed ${e.failedTests}`:""})`:"";return S.jsx(t,{flexDirection:"column",children:S.jsxs(n,{children:[S.jsx(n,{color:d,bold:!0,children:u}),S.jsx(n,{color:"gray",children:f}),S.jsxs(n,{color:"gray",children:[" [",l,"]"]})]})})},l=({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?"yellow":"green",l=e.isError?"Fix stopped":"Fix complete";return S.jsxs(t,{flexDirection:"column",children:[S.jsxs(n,{color:c,bold:!0,children:[l," in ",a]}),null!==e.totalTests&&S.jsxs(n,{color:"gray",children:[e.fixedTests,"/",e.totalTests," tests fixed",e.failedTests>0?`, ${e.failedTests} failed`:""]})]})},u=e=>{if("subagent"===e.kind&&e.subagent){const{subagent:r}=e,s="complete"===r.status?"green":"error"===r.status?"red":"yellow";return S.jsxs(t,{flexDirection:"column",marginTop:1,children:[S.jsxs(n,{children:[S.jsx(n,{color:s,bold:!0,children:"Agent"}),r.description?S.jsxs(n,{color:"gray",children:[" (",r.description,")"]}):null]}),r.activities.length>0&&S.jsx(t,{flexDirection:"column",marginLeft:2,children:r.activities.map(e=>(e=>"tool"===e.kind?S.jsxs(n,{color:"magenta",children:["• ",e.content]},e.id):"tool_result"===e.kind?S.jsx(n,{color:"gray",children:e.content},e.id):null)(e))})]},e.id)}return"tool"===e.kind?S.jsxs(n,{color:"magenta",children:["• ",e.content]},e.id):"tool_result"===e.kind?S.jsx(n,{color:"gray",children:e.content},e.id):"user"===e.kind?S.jsxs(n,{color:"cyan",children:["You: ",e.content]},e.id):S.jsx(n,{children:e.content},e.id)},d="vscode"===process.env.TERM_PROGRAM,p=(e,t)=>{if(t<=0)return 0;let r=t-1;for(;r>0&&/\s/.test(e[r]);)r--;for(;r>0&&!/\s/.test(e[r-1]);)r--;return r},f=(e,t)=>{if(t>=e.length)return e.length;let r=t;for(;r<e.length&&!/\s/.test(e[r]);)r++;for(;r<e.length&&/\s/.test(e[r]);)r++;return r},h=(e,t)=>{if(t<=0)return 0;const r=e.lastIndexOf("\n",t-1);return-1===r?0:r+1},g=(e,t)=>{const r=e.indexOf("\n",t);return-1===r?e.length:r};return function({onExit:m,onPermissionChoice:y,onSend:b,showSpinnerImmediately:w,state:v}){const[_,E]=x.useState({value:"",cursor:0}),I=_.value,T=_.cursor,A=x.useRef(!1),C=x.useRef(void 0),[R,P]=x.useState(!1),U=x.useRef(0),k=v.log.at(-1),L="text"===k?.kind&&"running"===v.status,D=v.log.findIndex(e=>"subagent"===e.kind&&"running"===e.subagent?.status),O=d?0:-1!==D?D:L?v.log.length-1:v.log.length;x.useEffect(()=>{v.log.length<U.current&&(U.current=0),O>U.current&&(U.current=O)},[v.log.length,O]);const B=v.log.slice(0,U.current),N=v.log.slice(U.current),j=!!v.permissionPrompt,$=x.useCallback(async()=>{A.current?(C.current&&clearTimeout(C.current),await(m?.()),process.exit(0)):(A.current=!0,P(!0),C.current=setTimeout(()=>{A.current=!1,P(!1)},2e3))},[m]);s((e,t)=>{t.ctrl&&"c"===e&&$().catch(()=>process.exit(1))},{isActive:o}),x.useEffect(()=>{if(j||!b)return;const e=e=>{const t=e.toString();""!==t&&"[1;5~"!==t?""!==t&&"[4;5~"!==t?""!==t&&"[1~"!==t&&"OH"!==t&&"[7~"!==t?""!==t&&"[4~"!==t&&"OF"!==t&&"[8~"!==t||E(e=>({...e,cursor:g(e.value,e.cursor)})):E(e=>({...e,cursor:h(e.value,e.cursor)})):E(e=>({...e,cursor:e.value.length})):E(e=>({...e,cursor:0}))};return process.stdin.on("data",e),()=>{process.stdin.off("data",e)}},[j,b,I]),s((e,t)=>{if(!t.ctrl||"c"!==e){if(t.return){const e=I.trim();return e&&b?.(e),void E({value:"",cursor:0})}t.ctrl&&"w"===e||t.ctrl&&t.backspace?E(e=>{const t=p(e.value,e.cursor);return{value:e.value.slice(0,t)+e.value.slice(e.cursor),cursor:t}}):!t.backspace&&!t.delete||t.ctrl?t.ctrl&&t.leftArrow||t.meta&&"b"===e?E(e=>({...e,cursor:p(e.value,e.cursor)})):t.ctrl&&t.rightArrow||t.meta&&"f"===e?E(e=>({...e,cursor:f(e.value,e.cursor)})):t.leftArrow?E(e=>({...e,cursor:Math.max(0,e.cursor-1)})):t.rightArrow?E(e=>({...e,cursor:Math.min(e.value.length,e.cursor+1)})):t.ctrl&&"a"===e?E(e=>({...e,cursor:0})):t.ctrl&&"e"===e?E(e=>({...e,cursor:e.value.length})):!e||t.ctrl||t.meta||t.escape||e.includes("")||/^\[./.test(e)||/^O[A-D]$/.test(e)||E(t=>({value:t.value.slice(0,t.cursor)+e+t.value.slice(t.cursor),cursor:t.cursor+e.length})):E(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&&!j});const M=x.useMemo(()=>"running"===v.status?S.jsx(a,{label:v.runningLabel??"Working"}):"success"!==v.status?S.jsx(n,{color:"red",children:"✖ Failed"}):void 0,[v.runningLabel,v.status]),F=!(w||!b||"running"!==v.status||0!==v.log.length||v.resultText||v.errorText),H="running"===v.status&&!F||v.log.length>0||v.resultText||v.errorText||"running"!==v.status;return S.jsxs(t,{flexDirection:"column",children:[S.jsx(r,{items:["header"],children:()=>S.jsxs(t,{flexDirection:"column",flexShrink:0,children:[S.jsx(n,{color:"cyan",bold:!0,children:"Stably Agent"}),S.jsx(t,{flexDirection:"column",marginTop:1,children:S.jsx(n,{color:"gray",children:v.promptDisplay})})]},"header")}),B.length>0&&S.jsx(r,{items:B,children:e=>u(e)}),N.length>0&&S.jsx(t,{flexDirection:"column",children:N.map(e=>u(e))}),"error"===v.status&&v.errorText&&S.jsx(t,{marginTop:1,children:S.jsx(n,{color:"red",children:v.errorText})}),"success"===v.status&&v.resultText&&S.jsx(t,{marginTop:1,children:S.jsx(n,{children:v.resultText})}),H&&S.jsx(t,{flexDirection:"column",flexShrink:0,marginTop:1,children:"running"===v.status&&v.fixProgress?S.jsxs(t,{flexDirection:"column",children:[S.jsxs(t,{children:[S.jsx(a,{}),S.jsx(n,{children:" "}),S.jsx(c,{progress:v.fixProgress})]}),"fixing"===v.fixProgress.phase&&v.log.flatMap(e=>{const{subagent:r}=e;if("subagent"!==e.kind||"fix-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 S.jsxs(t,{flexDirection:"column",children:[S.jsxs(n,{children:[" ",S.jsx(a,{}),S.jsxs(n,{color:"gray",children:[r.description||"fix-worker",o>0?` (${o} ${1===o?"cycle":"cycles"})`:""]})]}),c&&S.jsxs(n,{color:"gray",dimColor:!0,children:[" • ",c.content]}),l&&S.jsxs(n,{color:"gray",dimColor:!0,children:[" ",l]})]},e.id)})]}):"success"!==v.status&&"error"!==v.status||!v.fixProgress?M:S.jsx(l,{progress:v.fixProgress})}),null!=v.permissionPrompt&&null!=y&&S.jsx(i,{onChoice:y,prompt:v.permissionPrompt}),null!=b&&null==v.permissionPrompt&&!v.isExiting&&S.jsxs(t,{borderColor:"gray",borderStyle:"round",flexDirection:"column",flexShrink:0,marginTop:1,paddingX:1,paddingY:0,children:[S.jsx(n,{color:"gray",children:"Type a message and press Enter. Press Ctrl+C to exit."}),S.jsxs(n,{children:[S.jsx(n,{color:"yellow",children:">"})," ",I.slice(0,T),S.jsx(e,{}),I.slice(T)]})]}),R&&S.jsxs(t,{marginTop:1,flexDirection:"column",children:[S.jsx(n,{color:"yellow",children:"Press Ctrl+C again to exit"}),sn&&S.jsxs(n,{color:"gray",children:["Debug log: ",ln]})]})]})}})({Cursor:l,inkComponents:{Box:r,Static:n,Text:s,useInput:i},isRawModeSupported:a,PermissionPrompt:u,Spinner:({label:e})=>{const[t,r]=x.useState(0);return x.useEffect(()=>{const e=setInterval(()=>r(e=>(e+1)%c.length),80);return()=>clearInterval(e)},[]),S.jsxs(s,{color:"yellow",children:[c[t]," ",e]})}});let p=e;t?.isFixMode&&(p.fixProgress={phase:"initializing",totalTests:null,fixedTests:0,failedTests:0,currentTestDescription:null,lastTestDescription:null,startedAt:Date.now(),endedAt:null,isError:!1});const f={current:(e,t)=>{}},h=o(S.jsx(d,{onExit:t?.onExit,onPermissionChoice:(e,t)=>f.current(e,t),onSend:t?.onSend,showSpinnerImmediately:t?.showSpinnerImmediately,state:p}),{exitOnCtrlC:!1}),g=()=>{p={...p},h.rerender(S.jsx(d,{onExit:t?.onExit,onPermissionChoice:(e,t)=>f.current(e,t),onSend:t?.onSend,showSpinnerImmediately:t?.showSpinnerImmediately,state:p}))},m=({text:e})=>{e&&(p.log=[...p.log,{content:e,id:p.log.length,kind:"user"}],g())},y=new Map;return{addSubagentActivity:({toolUseId:e,kind:t,content:r})=>{const n=y.get(e);if(void 0===n)return void console.error("[addSubagentActivity] No entry index for toolUseId:",e);const s=p.log[n];if(s&&"subagent"===s.kind&&s.subagent){if("text"===t){const e=s.subagent.activities.at(-1);e&&"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});p.log=[...p.log],g()}else console.error("[addSubagentActivity] Entry not found or not subagent:",{entryIndex:n,entryKind:s?.kind})},addSubagentStart:({toolUseId:e,subagentType:t,description:r})=>{const n=p.log.length;if(y.set(e,n),p.log=[...p.log,{content:"",id:n,kind:"subagent",subagent:{toolUseId:e,subagentType:t,description:r,status:"running",activities:[]}}],p.fixProgress)if("triage"===t&&"initializing"===p.fixProgress.phase)p.fixProgress={...p.fixProgress,phase:"triage"};else if("fix-worker"===t){const e=(p.fixProgress.totalTests??0)+1,t=r||null;p.fixProgress={...p.fixProgress,phase:"fixing",totalTests:e,currentTestDescription:t,lastTestDescription:t??p.fixProgress.lastTestDescription}}else"validation"===t?p.fixProgress={...p.fixProgress,phase:"validation",currentTestDescription:null}:"context"===t&&(p.fixProgress={...p.fixProgress,currentTestDescription:r||p.fixProgress.currentTestDescription});g()},addTool:({rawName:e,toolInput:t})=>{const r=Es(e),n=Is(e,t),s=n?`${r} (${n})`:r;p.log=[...p.log,{content:s,id:p.log.length,kind:"tool"}],g()},addToolResult:({message:e})=>{p.log=[...p.log,{content:e,id:p.log.length,kind:"tool_result"}],g()},appendText:({text:e})=>{if(!e)return;const t=p.log.at(-1),r=t&&"text"===t.kind?e:e.replace(/^\s*\n+/,"");t&&"text"===t.kind?p.log=[...p.log.slice(0,-1),{...t,content:`${t.content}${r}`}]:p.log=[...p.log,{content:r,id:p.log.length,kind:"text"}],g()},appendUserMessage:m,cleanup:async()=>{const e=h.waitUntilExit();h.unmount(),await e},setExiting:()=>{p.isExiting=!0,g()},setRunningLabel:({label:e})=>{p.runningLabel=e,g()},setStatus:({error:e,result:t,status:r})=>{p.errorText=e,p.resultText=t,p.status=r,g()},setSubagentStatus:({toolUseId:e,status:t})=>{const r=y.get(e);if(void 0===r)return;const n=p.log[r];n&&"subagent"===n.kind&&n.subagent&&(n.subagent.status=t,p.fixProgress&&"fix-worker"===n.subagent.subagentType&&("complete"===t?p.fixProgress={...p.fixProgress,fixedTests:p.fixProgress.fixedTests+1,currentTestDescription:null}:"error"===t&&(p.fixProgress={...p.fixProgress,failedTests:p.fixProgress.failedTests+1,currentTestDescription:null})),p.log=[...p.log],g(),"complete"!==t&&"error"!==t||y.delete(e))},showPermissionPrompt:e=>new Promise(t=>{f.current=(r,n)=>{if(p.permissionPrompt=void 0,g(),"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";m({text:e}),t({behavior:"deny",message:e,interrupt:!1})}},p.permissionPrompt={...e,resolve:t},g()}),updateFixProgress:t?.isFixMode?e=>{p.fixProgress&&(p.fixProgress={...p.fixProgress,...e},g())}:void 0}})(w,"chat"===r.mode||"init"===r.mode?{onExit:()=>de.current(),onSend:e=>ue.current(e),showSpinnerImmediately:"init"===r.mode}:"fix"===r.mode?{onExit:()=>de.current(),isFixMode:!0}:void 0);let Te=w.status;const xe=({error:e,result:t,status:r})=>{Te=r,_e({error:e,result:t,status:r})};let Se;ue.current=e=>{const t=e.trim();if(m&&!yn.getLogFilePath()&&yn.initSession(t||"chat"),yn.debug("User message",{text:t}),"/help"===t){T&&y&&(A=!0,v?.interrupt?.(),y.allowNextTurn(),T=!1),"running"===Te&&xe({status:"success"}),ye({text:e});const t=b?.();return void me({text:t??"Help is not available in this session."})}const r=E||R&&T;if(m&&(U+=1,I=void 0,r||(L=!1,ve({label:void 0}))),y){if(r)return xe({status:"running"}),ye({text:e}),void O.push(e);if(!R||T||E||(R=!1),T)return xe({status:"running"}),ye({text:e}),y.pushText(e),void(k+=1);xe({status:"running"}),ye({text:e}),y.pushText(e),T=!0}};const Ae=[];let Ce;const Re=await(async()=>{if("single"===r.mode||"build"===r.mode){const n=await async function(e,r){const n=t.resolve(e);if(r){const e=t.resolve(n,r);return ms(e,"output-flag"),{path:e,source:"output-flag"}}const s=fs(n);if(s){const e=await async function(e){try{const t=(await g.readFile(e,"utf-8")).match(/testDir:\s*['"]([^'"]+)['"]/);return t?.[1]}catch{return}}(s);if(e){const r=t.resolve(t.dirname(s),e);if(gs(r))return ms(r,"playwright.config.ts"),{path:r,source:"playwright.config.ts"}}}for(const e of hs){const r=t.join(n,e);if(gs(r))return ms(r,"auto-detected"),{path:r,source:"auto-detected"}}return ms(n,"cwd-fallback"),{path:n,source:"cwd-fallback"}}(l,r.outputDir);return Ce=n.path,e=r.prompt,`${(Array.isArray(e)?e.join(" "):e).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: ${Ce}]`}var e;if("fix"===r.mode)try{yn.info("[fix] Fetching autoheal context",{runId:r.runId});const e=Date.now(),{context:t,autohealReportUrl:n}=await(async({authHeader:e,orgId:t,runId:r})=>{yn.debug("Fetching autoheal context",{runId:r});const n=await(s={auth:e,client:Cr(),headers:An(t),path:{runId:r}},(s.client??br).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-context",...s}));var s;if(404===n.response.status)throw yn.warn("Autoheal context not found",{runId:r,status:404}),new Error(`Run ID "${r}" was not found.`);if(401===n.response.status)throw yn.warn("Autoheal context fetch unauthorized",{runId:r,status:401}),new Error("Unauthorized: failed to fetch autoheal context (401).");if(422===n.response.status)throw yn.warn("Autoheal context fetch invalid request",{runId:r,status:422,error:n.error?.error}),new Error(n.error?.error??"Failed to fetch autoheal context (422).");if(!n.error){const e=Cn.safeParse(n.data);if(e.success)return yn.debug("Autoheal context fetched successfully",{runId:r,contextSize:e.data.context.length}),{context:e.data.context,autohealReportUrl:e.data.autohealReportUrl};throw yn.warn("Autoheal context response invalid",{runId:r}),new Error("Autoheal context response missing or invalid context.")}throw yn.warn("Autoheal context fetch failed",{runId:r,error:n.error}),new Error("Failed to fetch autoheal context")})({authHeader:o,orgId:c,runId:r.runId});return yn.info("[fix] Autoheal context fetched",{runId:r.runId,durationMs:Date.now()-e,contextLength:t.length}),Se=n,J||(yn.info("[fix] Creating WebSocket progress reporter"),J=new On({authHeader:o,orgId:c,runId:r.runId,onUserMessage:e=>{if(yn.info("[ws] Injecting web UI message into fix agent",{contentLength:e.length}),Z(Ki,{type:"user_message",summary:e}),ee({type:"user_message",summary:e}),ye({text:`[Web] ${e}`}),!T)return y.pushText(`[Message from web UI user]: ${e}`),T=!0,void y.allowNextTurn();H||Date.now()-z<2e3?y.pushText(`[Message from web UI user]: ${e}`):($.push(e),B&&clearTimeout(B),B=setTimeout(()=>{B=void 0;const e=[...$];$=[],z=Date.now(),wt(e)},500))}}),J.start(),re({phase:"initializing"})),ne("STARTED"),t}catch(e){const t=e instanceof Error?e.message:"Failed to fetch autoheal context.";yn.error("[fix] Failed to fetch autoheal context",{error:t}),xe({error:t,status:"error"}),await be(),process.exit(1)}return"init"===r.mode?"Please analyze this project and set up Playwright with the Stably SDK. Check for existing configurations and install the necessary dependencies.":""})(),Pe=await async function(e){const t=D.default.resolve(e),r=D.default.join(t,"tests"),n=D.default.join(r,"helpers"),s=D.default.join(r,"assets"),o=function(e){const t=D.default.resolve(e);if(i.existsSync(t))for(const e of is){const r=D.default.join(t,`playwright.config${e}`);if(i.existsSync(r))return r}}(t)??D.default.join(t,"playwright.config.ts"),a=D.default.basename(o),c=D.default.join(r,"seed.spec.ts"),[l,u,d,p,f,h]=await Promise.all([ls({defaultContent:"Unable to read directory",dirName:"working directory",dirPath:t}),ls({defaultContent:"Unable to read directory",dirName:"tests directory",dirPath:r}),ls({defaultContent:"Directory does not exist yet",dirName:"helpers directory",dirPath:n}),ls({defaultContent:"Directory does not exist yet",dirName:"assets directory",dirPath:s}),cs({defaultContent:"File does not exist or could not be read",fileName:a,filePath:o}),cs({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}}}(l),Ue=await(async e=>{try{const t=await Dr(e,"stably.yaml");if(!t)return void yn.debug("No stably.yaml found");const r=await g.readFile(t,"utf-8");if(!r.trim())return;const n=C.parseDocument(r),s=zi.parse(n.toJS()),o=s.agent?.fix?.maxTurnsPerIssue,i=s.agent?.fix?.maxParallelWorkers,a=!!s.agent?.fix?.rules;return yn.debug(`Loaded stably.yaml: maxTurnsPerIssue=${o??"default"}, maxParallelWorkers=${i??"default"}, hasRules=${a}`,{path:t,config:s.agent}),s}catch(e){return void yn.warn("Failed to parse stably.yaml",{error:e})}})(l),ke=Ue?.agent?.fix?.maxTurnsPerIssue,Le=Ue?.agent?.fix?.maxParallelWorkers,De=Ue?.agent?.fix?.rules,Oe="fix"===r.mode||"single"===r.mode||"build"===r.mode,Be="single"===r.mode||"build"===r.mode?await(async e=>{try{const t=await Dr(e,"STABLY-CREATE.md");if(!t)return void yn.debug("No STABLY-CREATE.md found");const r=await g.readFile(t,"utf-8");if(!r.trim())return;return r.length>1e4?(yn.warn(`STABLY-CREATE.md exceeds max length (${r.length} > 10000), truncating`,{path:t}),r.slice(0,1e4)):(yn.debug("Loaded STABLY-CREATE.md rules",{path:t,contentLength:r.length}),r)}catch(e){return void yn.warn("Failed to read STABLY-CREATE.md",{error:e})}})(l):void 0;yn.info("[fix] Fetching system prompt and subagent definitions",{mode:r.mode,maxTurnsOverride:ke,hasCustomRules:!!De,hasCreateRules:!!Be});const Ne=Date.now(),[{systemPrompt:je,prContext:$e},Me]=await Promise.all([us({allowedEnvVars:Object.keys(f),mode:r.mode,workspaceInfo:Pe,authHeader:o,customHeader:"single"===r.mode||"build"===r.mode?r.customHeader:void 0,maxParallelWorkers:"fix"===r.mode?Le:void 0}),Oe?Gi({authHeader:o,mode:r.mode,maxTurnsOverride:ke}):Promise.resolve({})]);yn.info("[fix] System prompt and subagents fetched",{durationMs:Date.now()-Ne,systemPromptSize:je.length,subagentCount:Object.keys(Me).length,maxTurnsOverride:ke??"default",hasPrContext:!!$e});const Fe={...f,...process.env},He={};for(const[e,t]of Object.entries(Fe))Hi.has(e)||void 0===t||(He[e]=t);const Ge=!0;yn.debug("AI proxy configuration",{useStablyAiProxy:Ge,wantsBypassProxy:!1,wantsUseOllama:!1}),yn.info("[fix] Acquiring AI proxy key",{useStablyAiProxy:Ge});const ze=Date.now(),We=await async function({auth:e,client:t,source:r,metadata:n,duration:s}){try{const i=await(o={auth:e,client:t,body:{source:r,metadata:n??{},duration:s}},(o.client??br).post({security:[{scheme:"bearer",type:"http"}],url:"/v1/proxy/api-key",...o,headers:{"Content-Type":"application/json",...o.headers}})),a=i.response;if(i.error){const e="object"==typeof i.error&&"error"in i.error?i.error.error:"Unknown error";return{error:Fi(e,a)}}return i.data?{key:i.data.key}:{error:Fi("No data in response",a)}}catch(e){const t=e instanceof Error?e.message:"Unknown error";return{error:Fi(t)}}var o}({auth:o,client:Cr(),source:"cli"}),Ye=We?.key;if(yn.info("[fix] AI proxy key acquired",{durationMs:Date.now()-ze,success:!!Ye,hasError:!!We?.error}),!Ye){const e=We?.error?.message?`Unable to make AI calls: ${We.error.message}`:"Unable to make AI calls. Check if you are authenticated.";yn.warn("Failed to get proxy API key",{error:We?.error?.message}),xe({error:e,status:"error"}),await be(),yn.flush(),yn.printLogFileInfo(),process.exit(1)}yn.debug("Proxy API key acquired",{success:!!Ye});const Ve=await Sn(),qe=Ve?Object.fromEntries(Object.entries(xn(Ve)).filter(e=>null!=e[1])):void 0,Ke="init"===r.mode,Je="fix"===r.mode,Xe=Je?Jt.createLocal({workingDir:l}):void 0;Xe&&await Xe.captureSnapshot();const Qe=Ke?Ni({onComplete:()=>{xe({status:"success"}),we(),y?.finish(),process.exit(0)}}):m?Ni({onRestartRequested:()=>{m&&(R=!0,xe({status:"running"}),ve({label:"Restarting browser tools..."}),I={createdAtUserMessageSeq:U,attempts:0})}}):void 0,Ze=Qe?m?{"stably-agent-control":Qe}:{"session-control":Qe}:{},et=se&&$e?["mcp__create-report"]:[],tt=Ke?Vi:[...Wi,...Je?["mcp__auto-heal-report"]:[],...et],rt=Ke?Vi:m?[...Yi,"mcp__stably-agent-control"]:[...Yi,...et],nt=se&&$e?{"create-report":$i({prContext:$e,authHeader:o,orgId:c,onReportPosted:e=>{ce({githubComment:{url:e.commentUrl,prNumber:$e.prNumber}})}})}:{},st=Ke?Ze:Je&&Xe?{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:qe},"auto-heal-report":Bi({authHeader:o,diffTracker:Xe,orgId:c,runId:r.runId,workingDir:l}),...Ze}:{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:qe},...Ze,...nt},ot="single"===r.mode||"build"===r.mode,it=Ke?[]:[{hooks:[async e=>{const t=Mn(e);if(!t)return{decision:"approve"};let r=!1;const n=t.map(e=>jn(e)?e.text.length<=4e4?e:(r=!0,{...e,text:`${e.text.slice(0,4e4)}...[truncated to 40000 characters]`}):e);return r?{decision:"approve",hookSpecificOutput:{hookEventName:"PostToolUse",updatedMCPToolOutput:n}}:{decision:"approve"}}],matcher:"mcp__playwright-test__.*"},{matcher:"mcp__playwright-test__test_run",hooks:[Yn({onResult:e=>ge({message:e})})]},{matcher:"mcp__playwright-test__test_debug",hooks:[Vn({onResult:e=>ge({message:e})})]},...ot?[{matcher:"Write",hooks:[Kn({onFileCreated:e=>{Ae.push(e),ae&&ce({filesCreated:[...ae.filesCreated,e]})}})]}]:[],{matcher:"Write",hooks:[ns({workDir:l})]},{matcher:"Edit",hooks:[ns({workDir:l})]}],at=Ke?[]:[{matcher:"mcp__playwright-test__browser_type",hooks:[Wn({envVars:f})]}],ct=Object.keys(Me).length>0?Me:void 0,lt={...He};lt.MCP_TOOL_TIMEOUT=String(6e5),Ye&&(lt.ANTHROPIC_API_KEY=Ye,lt.ANTHROPIC_BASE_URL=Tr,lt.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS="1");const ut=process.env.STABLY_AGENT_MODEL??"claude-opus-4-6",dt=De?`\n\n## Custom Rules\n${De}`:"",pt=Be?`\n\n## Custom Test Generation Rules\n${Be}`:"",ft=je+dt+pt;yn.debug("[fix] Final system prompt assembled",{baseSize:je.length,fixRulesSize:dt.length,createRulesSize:pt.length,finalSize:ft.length});const ht=D.default.join(__dirname,"stably-plugin"),gt=N.default.existsSync(ht)?{type:"local",path:ht}:function(){const e=function(){try{if(!("undefined"==typeof document?require("url").pathToFileURL(e).href:P&&"SCRIPT"===P.tagName.toUpperCase()&&P.src||new URL("index.js",document.baseURI).href))return;const e=a.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(e).href:P&&"SCRIPT"===P.tagName.toUpperCase()&&P.src||new URL("index.js",document.baseURI).href),r=t.dirname(e);return t.join(r,"..","stably-plugin")}catch{return}}();if(e&&i.existsSync(e))return{type:"local",path:e}}(),mt=()=>(yn.info("[fix] Starting SDK query",{model:ut,tools:tt,mcpServers:Object.keys(st),resumeSessionId:_??null,subagentsEnabled:!!ct,subagentCount:Object.keys(Me).length,useStablyAiProxy:Ge,aiProxyUrl:Tr,anthropicBaseUrl:void 0,stablyPluginPath:gt?.path,stablyPluginExists:!!gt}),d.query({options:{executableArgs:["--max-old-space-size=4096"],tools:tt,allowedTools:rt,betas:[],canUseTool:(e,t)=>(yn.debug("[fix] canUseTool called",{toolName:e}),Promise.resolve({behavior:"allow",updatedInput:t})),cwd:l,env:lt,hooks:{PostToolUse:it,PreToolUse:at},includePartialMessages:!0,agents:ct,mcpServers:st,model:ut,permissionMode:"default",plugins:gt?[gt]:void 0,systemPrompt:ft,..._?{resume:_}:{}},prompt:y??Re})),yt=()=>{if(y&&0!==O.length){for(const e of O)y.pushText(e);O.length=0,T=!0,xe({status:"running"})}},bt=async()=>{m&&(E||(E=(async()=>{yn.info("Restarting MCP servers for chat mode"),xe({status:"running"}),ve({label:"Restarting browser tools..."});try{await(v?.interrupt?.())}catch(e){yn.warn("Failed to interrupt response during MCP restart",{error:e instanceof Error?e.message:String(e)})}await Xn(),y?.finish(),y=new ss,k=0,T=!1,A=!1,W.clear(),v=mt(),L=!0,ve({label:"Restarting browser tools..."}),m&&y&&I&&(I.createdAtUserMessageSeq===U?I.attempts>=1||O.length>0?I=void 0:(I.attempts+=1,y.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")),I=void 0,T=!0,xe({status:"running"})):I=void 0),yt()})().finally(()=>{E=void 0,yt()})),await E)},wt=async e=>{if(h&&T&&!H&&!j)j=(async()=>{yn.info("[fix] Interrupting for user message",{messageCount:e.length,phase:X?.phase});try{await(v?.interrupt?.())}catch(e){yn.warn("[fix] Failed to interrupt response for user message",{error:e instanceof Error?e.message:String(e)})}await Xn(),y?.finish(),y=new ss,W.clear(),v=mt();const t=e.map(e=>`[Message from web UI user]: ${e}`).join("\n\n");y.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}`),G=!0,T=!0})().finally(()=>{j=void 0}),await j;else for(const t of e)y?.pushText(`[Message from web UI user]: ${t}`)};if(Ye){const e=Tr,t=`${e.replace(/\/$/,"")}/v1/messages`;yn.debug(`[fix] Pre-flight: POST ${t}`);const r=Date.now();try{const e=await fetch(t,{method:"POST",signal:AbortSignal.timeout(1e4),headers:{"x-api-key":Ye,"anthropic-version":"2023-06-01","content-type":"application/json"},body:"{}"}),n=await e.text().catch(()=>""),s=Date.now()-r;yn.debug(`[fix] Pre-flight: ${e.status} in ${s}ms — ${n.slice(0,300)}`),401===e.status||403===e.status?yn.error(`[fix] Pre-flight: AI proxy key rejected (${e.status}) at ${t}`):yn.info("[fix] Pre-flight: AI proxy key valid",{status:e.status,durationMs:s})}catch(t){yn.error("[fix] Pre-flight: AI proxy unreachable",{error:t instanceof Error?t.message:String(t),durationMs:Date.now()-r,url:e})}}yn.info("[fix] Creating initial agent query"),yn.flush(),v=mt(),yn.info("[fix] Agent query created, entering message loop"),"chat"!==r.mode&&y.pushText(Re),de.current=async()=>{Y="CANCELED",await ne("CANCELED"),re({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:te(!0)}),J?.close(),ce({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0}),ie?.close(),B&&(clearTimeout(B),B=void 0),yn.flush(),we();try{await(v?.interrupt?.())}catch{}y?.finish(),be()};let vt=0,_t=null;const Et=setInterval(()=>{const e=Date.now()-K;_t?yn.info("[fix] Watchdog: message loop active",{messageCount:vt,elapsed:e}):yn.info("[fix] Watchdog: waiting for first SDK message",{elapsed:e}),yn.flush()},15e3);Et.unref();try{let e=!1;for(;;){if(!v){yn.info("[fix] No response object, exiting message loop");break}e=!1,yn.info("[fix] Entering for-await on SDK response");for await(const t of v){vt++,_t||(_t=Date.now(),yn.info("[fix] First SDK message received",{waitDurationMs:_t-K,messageType:t.type,messageSubtype:"subtype"in t?t.subtype:void 0}));const n="session_id"in t&&"string"==typeof t.session_id?t.session_id:void 0;if(n&&n!==_&&(_=n,yn.debug("Captured Claude session id",{sessionId:_})),"stream_event"===t.type){const{event:e}=t;(vt<=5||vt%200==0)&&yn.debug("[fix] Stream event",{msgNum:vt,eventType:e?.type});const r=e&&"object"==typeof e&&"parent_tool_use_id"in e&&"string"==typeof e.parent_tool_use_id?e.parent_tool_use_id:void 0;if("content_block_delta"===e?.type){const{delta:t}=e;if("text_delta"===t?.type&&t.text){if(m&&R&&!r)continue;L&&(L=!1,ve({label:void 0})),r&&W.has(r)?pe({toolUseId:r,kind:"text",content:t.text}):me({text:t.text})}}"message_stop"===e?.type&&y&&(H=!1,y.allowNextTurn());continue}if("assistant"===t.type){const e="parent_tool_use_id"in t&&"string"==typeof t.parent_tool_use_id?t.parent_tool_use_id:void 0,{content:n}=t.message??{};if(Array.isArray(n)&&!e){const e=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("");e&&(yn.debug("Assistant message",{text:e}),"fix"===r.mode&&(Z(Ki,{type:"ai_message",summary:e.slice(0,200)}),ee({type:"ai_message",summary:e.slice(0,200)})),se&&le({type:"ai_message",summary:e.slice(0,200)}))}if(W.size>0){const r=Array.isArray(n)?n.filter(e=>e&&"object"==typeof e&&"type"in e&&"tool_use"===e.type).map(e=>e&&"object"==typeof e&&"name"in e&&"string"==typeof e.name?e.name:void 0):[];yn.debug("Assistant message with active subagents",{hasParentToolUseId:!!e,parentToolUseId:e,activeSubagentIds:Array.from(W.keys()),toolNames:r,fullMessageKeys:Object.keys(t),rawMessage:JSON.stringify(t).slice(0,500)})}if(Array.isArray(n))for(const t of n){if("tool_use"===t?.type){if("mcp__auto-heal-report__generate-report"===t.name&&(H=!0),"mcp__session-control__restart_mcp_servers"===t.name||"mcp__stably-agent-control__restart_mcp_servers"===t.name){he({rawName:t.name,toolInput:t.input});continue}if(t.name.startsWith("mcp__session-control__")||t.name.startsWith("mcp__stably-agent-control__"))continue;if(Ji(t.name))continue;if(W.size>0&&yn.debug("Tool use detected with active subagents",{toolName:t.name,hasParentToolUseId:!!e,parentToolUseId:e,wouldRouteToSubagent:!!e&&W.has(e),activeSubagentIds:Array.from(W.keys())}),"Task"===t.name){const e=t.input,n=e&&"object"==typeof e?e: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(yn.info("[fix] Subagent started",{subagentType:s,description:o,toolUseId:t.id,activeSubagentCount:W.size+1}),W.set(t.id,{subagentType:s,description:o}),fe({toolUseId:t.id,subagentType:s,description:o}),"fix"===r.mode){if("triage"===s){Ie?.({phase:"triage"});const e={id:t.id,testDescription:"Triage",workerType:"triage",status:"running",summary:null,startedAt:Date.now(),endedAt:null,activity:[]};re({phase:"triage",workers:[...X?.workers??[],e]})}else if("fix-worker"===s){Q.add(o||t.id);const e={id:t.id,testDescription:o||t.id,workerType:"fix-worker",status:"running",summary:null,startedAt:Date.now(),endedAt:null,activity:[]};Ie?.({phase:"fixing",totalTests:Q.size,currentTestDescription:o||null}),re({phase:"fixing",totalTests:Q.size,currentTestDescription:o||null,lastTestDescription:o||X?.lastTestDescription||null,workers:[...X?.workers??[],e]})}else"validation"===s?(Ie?.({phase:"validation",currentTestDescription:null}),re({phase:"validation",currentTestDescription:null})):"context"===s&&re({currentTestDescription:o||null});ee({type:"tool_call",summary:`[${s}] ${o}`.trim()})}continue}if(e&&W.has(e)){const n=Xi(t.name),s=Is(t.name,t.input),o=s?`${n} (${s})`:n;if(yn.debug("Subagent tool called",{tool:t.name,parentToolUseId:e}),pe({toolUseId:e,kind:"tool",content:o}),"fix"===r.mode){ee({type:"tool_call",summary:o});const t=W.get(e);"fix-worker"!==t?.subagentType&&"triage"!==t?.subagentType||Z(e,{type:"tool_call",summary:o})}continue}if(e&&yn.debug("Tool with parent_tool_use_id but no matching subagent",{tool:t.name,parentToolUseId:e,activeSubagentIds:Array.from(W.keys())}),yn.debug("Tool called",{tool:t.name,input:t.input}),he({rawName:t.name,toolInput:t.input}),"fix"===r.mode){const e=Xi(t.name),r=Is(t.name,t.input),n=r?`${e} (${r})`:e;Z(Ki,{type:"tool_call",summary:n}),ee({type:"tool_call",summary:n})}if(se){const e=Xi(t.name),r=Is(t.name,t.input),n=r?`${e} (${r})`:e;"initializing"===ae?.phase?ce({phase:"generating",currentActivity:n}):"mcp__playwright-test__test_run"===t.name&&"generating"===ae?.phase?ce({phase:"testing",currentActivity:n}):ce({currentActivity:n}),le({type:"tool_call",summary:n})}}if("text"===t?.type&&e&&W.has(e)){const n="string"==typeof t.text?t.text:"";if(n&&(pe({toolUseId:e,kind:"text",content:n}),"fix"===r.mode)){const t=W.get(e);"fix-worker"!==t?.subagentType&&"triage"!==t?.subagentType||Z(e,{type:"ai_message",summary:n.slice(0,200)})}}}continue}if("user"===t.type){const e="message"in t&&t.message&&"object"==typeof t.message&&"content"in t.message?t.message.content:void 0;if(Array.isArray(e))for(const t of e)if(t&&"object"==typeof t&&"type"in t&&"tool_result"===t.type&&"tool_use_id"in t){const e="string"==typeof t.tool_use_id?t.tool_use_id:void 0,n="is_error"in t&&!0===t.is_error,s="content"in t&&"string"==typeof t.content?t.content:void 0;if(yn.debug("Tool result",{toolUseId:e,isError:n,output:s?.slice(0,500)}),e&&W.has(e)){const t=W.get(e);if(yn.info("[fix] Subagent completed",{toolUseId:e,isError:n,subagentType:t?.subagentType,description:t?.description,activeSubagentCount:W.size-1}),Ee({toolUseId:e,status:n?"error":"complete"}),"fix"===r.mode&&"triage"===t?.subagentType){const t=n?"failed":"succeeded",r=s?s.slice(0,500):null,o=(X?.workers??[]).map(n=>n.id===e?{...n,status:t,summary:r,endedAt:Date.now()}:n);re({workers:o})}if("fix"===r.mode&&"fix-worker"===t?.subagentType){const t=n?"failed":"succeeded",r=s?s.slice(0,500):null,o=(X?.workers??[]).map(n=>n.id===e?{...n,status:t,summary:r,endedAt:Date.now()}:n);n?(Ie?.({failedTests:(X?.failedTests??0)+1,currentTestDescription:null}),re({failedTests:(X?.failedTests??0)+1,currentTestDescription:null,workers:o})):(Ie?.({fixedTests:(X?.fixedTests??0)+1,currentTestDescription:null}),re({fixedTests:(X?.fixedTests??0)+1,currentTestDescription:null,workers:o}))}W.delete(e)}}continue}if("result"===t.type){if(yn.info("[fix] Agent result received",{subtype:t.subtype,messageCount:vt,elapsed:Date.now()-K,activeSubagents:W.size,fixedTests:X?.fixedTests,failedTests:X?.failedTests,phase:X?.phase}),h){if("success"===t.subtype){B&&(clearTimeout(B),B=void 0);for(const e of $)y?.pushText(`[Message from web UI user]: ${e}`);if($=[],(se||"fix"===r.mode)&&y){if(y.hasQueuedMessages()){yn.info("[ws] Queued web UI messages found, continuing agent"),T=!0,y.allowNextTurn();continue}if(await Qi(y,3e3)){yn.info("[ws] Web UI message received during grace period, continuing agent"),T=!0,y.allowNextTurn();continue}y.finish()}if(Ie?.({phase:"complete",currentTestDescription:null,endedAt:Date.now()}),re({phase:"complete",currentTestDescription:null,endedAt:Date.now(),isError:!1,workers:te(!1)}),ce({phase:"complete",endedAt:Date.now(),isError:!1,currentActivity:null}),ot&&Ae.length>0){F.default.green("Created files:");for(const e of Ae)F.default.green(`- ${e}`)}const e=(e,t)=>`]8;;${e}${t}]8;;`,t=Se?F.default.cyan(`📊 View Autoheal Report:\n ${e(Se,F.default.cyan(F.default.bold(F.default.underline(Se))))}`):void 0;xe({status:"success",result:t}),Y="COMPLETED"}else j||G?yn.info("[fix] Suppressing error status: user-message interrupt in progress"):A?(Y="CANCELED",re({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:te(!0)}),ce({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0})):(Ie?.({endedAt:Date.now(),isError:!0}),re({phase:"complete",endedAt:Date.now(),isError:!0,currentTestDescription:null,workers:te(!0)}),ce({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),xe({error:"Run failed.",status:"error"}),process.exitCode=1,Y="FAILED");A=!1;break}const n=m&&R;if("success"!==t.subtype?A||(xe({error:"Run failed.",status:"error"}),process.exitCode=1):xe(n?{status:"running"}:{status:"success"}),T=!1,A=!1,n){R=!1,yn.info("Processing deferred MCP restart request in chat mode"),await bt(),e=!0;break}L=!1,ve({label:void 0}),y?.allowNextTurn(),m&&k>0&&(k-=1,T=!0,xe({status:"running"}));continue}}if(j&&await j,G&&(G=!1,e=!0,xe({status:"running"}),yn.info("[fix] Resuming after user-message interrupt")),!e)break}}catch(e){A?(Y="CANCELED",re({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:te(!0)}),ce({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0})):(yn.error("[fix] Agent encountered an error",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0,elapsed:Date.now()-K}),xe({error:`Agent encountered an error: ${e}`,status:"error"}),process.exitCode=1,Y="FAILED",re({phase:"complete",endedAt:Date.now(),isError:!0,currentTestDescription:null,workers:te(!0)}),ce({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),yn.flush(),yn.printLogFileInfo())}finally{if(clearInterval(Et),B&&(clearTimeout(B),B=void 0),yn.info("[fix] Agent session ending",{finalStatus:Y,elapsed:Date.now()-K,totalMessages:vt}),T=!1,A=!1,process.off("uncaughtException",n),y?.finish(),Y){yn.info("[fix] Reporting final autoheal status",{status:Y});const e=Date.now();await ne(Y),yn.info("[fix] Final autoheal status reported",{durationMs:Date.now()-e})}if(yn.info("[fix] Closing WebSocket progress reporter"),J?.close(),ie?.close(),Je&&Xe){const e=Date.now();try{yn.info("[fix] Computing diff...");const t=await Xe.computeDiff();if(t&&t.trim().length>0){yn.info("[fix] Uploading diff...",{diffLength:t.length});const{diffBucketPath:n,uploadUrl:s}=await kn({authHeader:o,contentType:"text/plain",orgId:c,runId:r.runId});await Ln({contentType:"text/plain",diff:t,uploadUrl:s}),await Dn({authHeader:o,diffBucketPath:n,orgId:c,runId:r.runId}),yn.info("[fix] Diff uploaded",{durationMs:Date.now()-e})}else yn.info("[fix] No diff to upload (empty or no changes)")}catch(t){yn.warn("[fix] Failed to upload diff",{error:t instanceof Error?t.message:String(t),durationMs:Date.now()-e})}}yn.info("[fix] Cleaning up diff tracker"),await(Xe?.cleanup()),yn.info("[fix] Running final cleanup"),await be(),yn.info("[fix] Cleanup complete")}},ea=G.default.object({runId:G.default.string(),timestamp:G.default.number()}),ta=class{entries=[];warnings=[];runId;command;executionMode;constructor(e){this.runId=e.runId,this.command=e.command,this.executionMode=e.executionMode}phaseStart(e,t){this.addEntry({phase:e,level:"info",message:t}),function(e){F.default.bold(F.default.cyan(`[${e}]`))}(e)}phaseEnd(e,t){this.addEntry({phase:e,level:"info",message:t})}info(e){this.addEntry({phase:e.phase,level:"info",message:e.message,fields:e.fields})}warn(e){this.addEntry({phase:e.phase,level:"warn",message:e.message,fields:e.fields}),F.default.yellow(` warn: ${e.message}`)}error(e){this.addEntry({phase:e.phase,level:"error",message:e.message,fields:e.fields}),console.error(F.default.red(` error: ${e.message}`))}emitWarning(e){this.warnings.push(e),this.addEntry({phase:"summary",level:"warn",message:e.message,fields:{warningCode:e.code,...e.details}}),function(e){F.default.yellow(` warning: ${e.code} - ${e.message}`)}(e)}getEntries(){return[...this.entries]}getWarnings(){return[...this.warnings]}getRunId(){return this.runId}getCommand(){return this.command}getExecutionMode(){return this.executionMode}addEntry(e){this.entries.push({runId:this.runId,command:this.command,executionMode:this.executionMode,phase:e.phase,timestamp:(new Date).toISOString(),level:e.level,message:e.message,...e.fields?{fields:e.fields}:{}})}};function ra(e){return 0===e.length?[]:[F.default.yellow(F.default.bold("Warnings:")),...e.map(e=>F.default.yellow(` ${e.code}: ${e.message}`)),""]}function na(e){return e?[F.default.dim(`Next action: ${e}`),""]:[]}function sa(e){const t=[],r="fix"===e.command?"Fix":"Build";if(t.push(""),"success"===e.status){const n=e.changedPaths.length;t.push(F.default.green(F.default.bold(`${r} succeeded`))+(n>0?F.default.green(` (${n} path${1!==n?"s":""} changed)`):"")),t.push(""),t.push(...ra(e.warnings))}else if("failure"===e.status)t.push(F.default.red(F.default.bold(`${r} failed`))),e.errorCode&&t.push(F.default.red(` Error: ${e.errorCode}`)),t.push(""),t.push(...ra(e.warnings)),t.push(...na(e.nextAction));else{const n=e.changedPaths.length,s=e.failedPaths.length,o=e.partialPaths.length;t.push(F.default.yellow(F.default.bold(`${r} partially succeeded`))+F.default.yellow(` (${n} changed, ${s} failed, ${o} partial)`)),t.push(""),t.push(...ra(e.warnings)),t.push(...na(e.nextAction))}return t.push(F.default.dim(`Run ID: ${e.runId}`)),t.join("\n")}var oa=/^\/\*\*\r?\n \* @generated by stably build[\s\S]*?\*\/(?:\r?\n)*/;function ia(e){return!!e&&"object"==typeof e&&"code"in e}async function aa({errorMessage:e,filePath:t}){try{return await H.default.readFile(t,"utf8")}catch(t){if(ia(t)&&"ENOENT"===t.code)throw new Error(e);throw t}}function ca(e){return e.split(D.default.sep).join("/")}async function la(e){const t=[];return await async function e(r){let n;try{n=await H.default.readdir(r,{withFileTypes:!0})}catch{return}for(const s of n){const n=D.default.join(r,s.name);s.isDirectory()&&!s.isSymbolicLink()?await e(n):s.isFile()&&s.name.endsWith(".stably.md")&&t.push(n)}}(e),t.sort()}var ua=/^---\r?\n([\s\S]*?)\r?\n---/;function da(e,t){const r=[],n=ua.exec(e);let s,o={};if(n){try{const e=C.parse(n[1]??"");o=e&&"object"==typeof e&&!Array.isArray(e)?e:{}}catch{console.warn(`Warning: Failed to parse YAML frontmatter in ${t}, treating as empty`),o={}}s=e.slice(n[0].length).replace(/^(\r?\n)+/,"")}else s=e;if(!s.trim())return{updated:e,addedFields:r};if(!o.name){const e=s.slice(0,1e4).replace(/```[\s\S]*?```/g,""),n=/^#\s+(.+)$/m.exec(e),i=D.default.basename(t).replace(/\.stably\.md$/,"").replace(/\.md$/,"");o.name=n?.[1]?.trim()??i,r.push("name")}return o.priority||(o.priority="medium",r.push("priority")),0===r.length?{updated:e,addedFields:r}:{updated:`---\n${C.stringify(o).trimEnd()}\n---\n\n${s}`,addedFields:r}}async function pa(e){try{return(await H.default.readdir(e)).filter(e=>Nn.test(e)).map(t=>D.default.join(e,t))}catch(e){if(ia(e)&&"ENOENT"===e.code)return[];throw e}}function fa({runId:e,warnings:t,changedPaths:r=[],failedPaths:n=[],...s}){return{runId:e,command:"build",executionMode:"cli",warnings:t,changedPaths:r,failedPaths:n,partialPaths:[],...s}}async function ha({force:e,inputFilePath:t}){const r=`build-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,n=new ta({runId:r,command:"build",executionMode:"cli"});n.phaseStart("preflight","Validating workspace and arguments");const s=process.cwd();n.info({phase:"preflight",message:"Input resolved",fields:{input:t}}),n.phaseEnd("preflight","Preflight complete"),n.phaseStart("scope","Resolving scope");const o=await aa({filePath:t,errorMessage:`Prompt file not found: ${t}`});if(!o.trim())throw new Error(`Prompt file is empty: ${t}`);const i=es(o),a=ca(D.default.relative(s,t)),c=D.default.dirname(t),l=(u=t,D.default.basename(u).replace(/\.stably\.md$/,"").replace(/\.md$/,"").replace(/\.txt$/,""));var u;const d=await async function(e,t){return(await pa(e)).find(e=>{const r=D.default.basename(e);return r.startsWith(`${t}.spec`)||r.startsWith(`${t}.test`)})}(c,l);if(!e&&d&&await async function({outputFilePath:e,promptHash:t}){try{return ts(await H.default.readFile(e,"utf8"))===t}catch(e){if(ia(e)&&"ENOENT"===e.code)return!1;throw e}}({outputFilePath:d,promptHash:i})){n.info({phase:"scope",message:"Hash unchanged, skipping build"});const e={code:"STABLY_WARNING_NO_CHANGES",message:"Test code is up to date (hash unchanged)"};n.emitWarning(e);const t=fa({runId:r,status:"success",warnings:[e]});return n.phaseStart("summary","Build summary"),sa(t),n.phaseEnd("summary","Done"),F.default.green(`Skipped build: ${a} (hash unchanged)`),"skipped"}n.info({phase:"scope",message:"Scope resolved",fields:{promptFile:a,promptHash:i,resolvedScopeCount:1,unmappedPaths:[],baseSource:"prompt-file",baseRef:a}}),n.phaseEnd("scope","Scope complete"),n.phaseStart("plan","Preparing prompt");const p=new Set(await pa(c));await H.default.mkdir(c,{recursive:!0});const f=rs({promptFile:a,promptHash:i}),h=ca(D.default.relative(s,c)||c),g=function({outputDir:e,promptContent:t,sourceSpecFile:r}){return["Compile this test specification into a Playwright test file.","",`Output directory: ${e}`,"","Choose output filename:",`- Look at existing test files in ${e} to determine the naming convention.`,"- Use the same extension pattern as existing tests (e.g., .test.ts or .spec.ts).","- If no existing tests, default to .spec.ts.","- Base the filename on the prompt content (e.g., login.spec.ts for login tests).","","File creation rules:","- Create your test file in the output directory with your chosen filename.","- You MAY create shared helper files (e.g., lib/auth.ts) if the prompt explicitly requests reusable components.","- Prefer single-file output unless shared helpers would significantly improve maintainability.","- Never modify unrelated existing files.","","Sync workflow for existing files:","1. Examine existing test files in the workspace and preserve hand edits where possible.","2. If a matching test file already exists, read it first and compare against the prompt specification.","3. Apply sync rules:"," - If file does not exist: CREATE from scratch."," - If file exists and already satisfies the prompt: KEEP behavior and make minimal edits only when needed."," - If file exists but only partially matches: UPDATE only changed scenarios so code aligns with prompt."," - If file structure conflicts heavily with prompt: REGENERATE the file content completely.","4. Prompt specification is the source of truth for final test behavior.","","Test verification:","After generating the test file, run the tests locally to verify they work correctly.","Use the appropriate test command (e.g., `pnpm stably test` or the repository's test command).","If tests fail, analyze the errors and iterate on the test code until all tests pass.","","Spec file linking:",`- Add \`// @stably.spec ${r}\` after the import statements.`,"- This links the test back to its source .md specification.","- If different test.describe()/test() blocks come from different .md files, add per-block @stably.spec instead.","","Prompt specification:",t].join("\n")}({outputDir:h,promptContent:o,sourceSpecFile:a});n.info({phase:"plan",message:"Agent prompt assembled",fields:{outputTarget:h,plannedPathCount:1,plannedPaths:[h],mode:"directory"}}),n.phaseEnd("plan","Plan complete"),n.phaseStart("execute","Running agent session"),process.exitCode=void 0;const m=Date.now();await Zi({mode:"build",prompt:g,outputDir:c,customHeader:f});const y=Date.now()-m,b=process.exitCode;if("number"==typeof b&&0!==b){n.error({phase:"execute",message:`Build generation failed for: ${a}`,fields:{toolName:"runAgentSession",durationMs:y}});const e=fa({runId:r,status:"failure",warnings:n.getWarnings(),failedPaths:[a],nextAction:"open_agent_session",errorCode:"STABLY_WRITE_FAILED"});throw n.phaseStart("summary","Build summary"),n.info({phase:"summary",message:"Run failed",fields:{errorCode:e.errorCode,nextAction:e.nextAction}}),sa(e),n.phaseEnd("summary","Done"),new Error(`Build generation failed for: ${a}`)}n.info({phase:"execute",message:"Agent session completed",fields:{toolName:"runAgentSession",durationMs:y}}),n.phaseEnd("execute","Agent session complete"),n.phaseStart("finalize","Applying results");const w=[];let v=d;if(!v&&(v=(await pa(c)).find(e=>!p.has(e)),!v)){const e={path:a,status:"failed",error:"No new test file created"};w.push(e),n.info({phase:"finalize",message:"Write failed",fields:{path:e.path,writeStatus:e.status,error:e.error}});const t=fa({runId:r,status:"failure",warnings:n.getWarnings(),failedPaths:[a],nextAction:"open_agent_session",errorCode:"STABLY_WRITE_FAILED"});throw n.phaseStart("summary","Build summary"),n.info({phase:"summary",message:"Run failed",fields:{errorCode:t.errorCode,nextAction:t.nextAction}}),sa(t),n.phaseEnd("summary","Done"),new Error(`Build finished but no new test file was created for: ${a}`)}const _=await aa({filePath:v,errorMessage:`Build finished but output file was not created for: ${a}`}),E=function(e){return e.replace(oa,"")}(_),I=_.startsWith(f)?_:`${f}\n\n${E}`;I!==_&&await H.default.writeFile(v,I,"utf8");const T=ca(D.default.relative(s,v)),x={path:T,status:"success"};w.push(x),n.info({phase:"finalize",message:"Write succeeded",fields:{path:x.path,writeStatus:x.status}}),n.phaseEnd("finalize","Finalize complete"),n.phaseStart("summary","Build summary");const S=w.filter(e=>"success"===e.status).map(e=>e.path),A=w.filter(e=>"failed"===e.status).map(e=>e.path);let C;C=A.length>0?S.length>0?"partial":"failure":"success";const R=A.length>0,P=fa({runId:r,status:C,warnings:n.getWarnings(),changedPaths:S,failedPaths:A,nextAction:R?"inspect_failed_paths":void 0,errorCode:R?"STABLY_WRITE_FAILED":void 0});return n.info({phase:"summary",message:"Run completed",fields:{status:P.status,changedPathCount:S.length,failedPathCount:A.length,...P.errorCode?{errorCode:P.errorCode}:{},...P.nextAction?{nextAction:P.nextAction}:{}}}),sa(P),n.phaseEnd("summary","Done"),F.default.green(`Built: ${T}`),"built"}var ga=[{args:["--trace=on"],description:"Run Playwright tests",name:"test"},{args:[],description:"Install browser dependencies",name:"install"}],ma=["You have two different versions of @playwright/test"];function ya(e){const[t,...r]=Ri(e),n=[t,...r.slice(0,-1)].join(" ");return(t,r)=>{let s=t.toString();for(const e of ga)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.shift(),void r.write(e.join("\n"))}r.write(s)}}async function ba({overrideArgs:e,subcommand:r}){yn.info("[test] forwardToPlaywright starting",{subcommand:r,overrideArgs:e});const n=process.argv,o=n.findIndex((e,t)=>t>1&&e===r),a=-1===o?[]:n.slice(o+1),c="--"===a[0],l=c?a.slice(1):a;if(!c&&("--help"===l[0]||"-h"===l[0]))return async function({subcommand:e}){const t=ga.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=Si();if(!n.installed||!n.inNodeModules)return void r('No Playwright project found in this directory or its parents.\nMake sure you\'re in a directory within your Playwright project, or run "stably init" to create a new playwright directory.');const{packageManager:o}=n;if(!o)return void r("Could not determine package manager.");r("Playwright options:"),r("");const[i,...a]=Ri(o),c=ya(o);return new Promise(t=>{const r=s.spawn(i,[...a,e,"--help"],{stdio:["inherit","pipe","pipe"],env:{...process.env,...process.env.CI?{}:{FORCE_COLOR:"1"}}});r.stdout?.on("data",e=>{c(e,process.stdout)}),r.stderr?.on("data",e=>{c(e,process.stderr)}),r.on("close",()=>{t()})})}({subcommand:r});const u=e??[],d=new Set(u.map(e=>{const[t]=e.split("=");return t})),p=[];for(let e=0;e<l.length;e++){const t=l[e],[r]=t.split("=");d.has(r)?!t.includes("=")&&e+1<l.length&&!l[e+1].startsWith("-")&&e++:p.push(t)}const f=[r,...u,...p];yn.info("[test] Forwarded args computed",{forwardedArgs:f}),yn.info("[test] Resolving Stably test environment");const h=Date.now(),g="test"===r?await Sn():void 0;yn.info("[test] Stably test environment resolved",{durationMs:Date.now()-h,hasCredentials:null!=g,hasWsUrl:!!g?.STABLY_WS_URL}),yn.info("[test] Setting up Stably reporter injection");const m="test"===r?function({forwardedArgs:e,hasCredentials:r}){if(!r)return console.warn("⚠️ Stably credentials not found. Test results will not be reported to Stably."),console.warn(" To enable reporting, either:"),console.warn(" • Run `npx stably login` to authenticate"),void console.warn(" • Or set STABLY_API_KEY and STABLY_PROJECT_ID environment variables\n");const n=process.cwd(),o=e=>{const r=function(e){let r=t.resolve(e);for(;;){if([t.join(r,"node_modules","@stablyai","playwright-test"),t.join(r,"node_modules",".pnpm","@stablyai+playwright-test")].some(e=>i.existsSync(e)))return!0;const e=t.dirname(r);if(e===r)return!1;r=e}}(e);return r||(console.warn("⚠️ @stablyai/playwright-test is not installed. Stably reporter will not be injected."),console.warn(" Install it with: npm install @stablyai/playwright-test"),console.warn(" Reference: ]8;;https://docs.stably.ai/getting-started/sdk-setup-guidehttps://docs.stably.ai/getting-started/sdk-setup-guide]8;;\n")),r},a=(e,r)=>{try{return function({baseConfigPath:e,projectDir:r}){const n=function(e){try{const t=s.execSync("npm pkg get type",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return"module"===JSON.parse(t.trim())}catch{return!1}}(r),o=n?"mts":"ts",a=t.dirname(t.resolve(e)),c=t.basename(e),l=t.join(a,`.stably-playwright-wrapper.config.${o}`),u=`\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\nconst buildReporterList = () => {\n const existingReporters = baseConfig.reporter;\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 projectId: process.env.STABLY_PROJECT_ID,\n notificationConfigs: extractNotificationConfigs(),\n errorSummary: resolveErrorSummary(),\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 projectId: process.env.STABLY_PROJECT_ID,\n notificationConfigs: extractNotificationConfigs(),\n errorSummary: resolveErrorSummary(existingOptions?.errorSummary),\n });\n\n // Keep all non-stably reporters, add our (merged or fresh) stably reporter\n const otherReporters = filterOutStablyReporter(reportersArray);\n return [...otherReporters, stablyReporterEntry];\n};\n\nexport default defineConfig({\n ...baseConfig,\n use: {\n ...baseConfig.use,\n trace: 'on',\n },\n reporter: buildReporterList(),\n});\n`.trim();return i.existsSync(a)||i.mkdirSync(a,{recursive:!0}),i.writeFileSync(l,u,"utf-8"),function(e){const r=t.join(e,".gitignore");try{if(i.existsSync(r)){const e=i.readFileSync(r,"utf-8");if(e.split("\n").map(e=>e.trim()).includes(ds))return;const t=e.length>0&&!e.endsWith("\n");i.appendFileSync(r,`${t?"\n":""}${ds}\n`)}else i.writeFileSync(r,`${ds}\n`)}catch{}}(a),l}({baseConfigPath:e,projectDir:r})}catch{return void console.warn("⚠️ Could not create Stably wrapper config. Reporter injection skipped.")}};if(e.some(e=>"--config"===e||"-c"===e||e.startsWith("--config=")||e.startsWith("-c="))){const r=e.findIndex(e=>"--config"===e||"-c"===e);if(-1!==r&&e[r+1]){const s=t.resolve(n,e[r+1]),i=t.dirname(s);if(!o(i))return;const c=a(s,i);if(!c)return;return e[r+1]=c,c}const s=e.findIndex(e=>e.startsWith("--config=")||e.startsWith("-c="));if(-1!==s){const r=t.resolve(n,e[s].split("=")[1]),i=t.dirname(r);if(!o(i))return;const c=a(r,i);if(!c)return;const l=e[s].startsWith("--config=")?"--config=":"-c=";return e[s]=`${l}${c}`,c}}const c=fs(n);if(!c)return;const l=t.dirname(c);if(!o(l))return;const u=a(c,l);return u?(e.push("--config",u),u):void 0}({forwardedArgs:f,hasCredentials:null!=g}):void 0;yn.info("[test] Reporter injection setup complete",{hasWrapperConfig:!!m}),yn.info("[test] Spawning Playwright process"),await function(e,t={}){yn.info("[test] Detecting Playwright installation");const r=Si();yn.info("[test] Playwright installation check",{installed:r.installed,inNodeModules:r.inNodeModules,packageManager:r.packageManager,packageName:r.packageName}),r.installed||(console.error('Playwright is not installed. Please run "stably init" to install it.'),process.exit(1)),r.inNodeModules||(console.error("Playwright is present in your project, but not in node_modules. Please install your dependencies before proceeding."),process.exit(1));const{packageManager:n}=r;n||(console.error("Playwright installation not found. Could not determine your package manager (tried pnpm, yarn, and npm)."),process.exit(1));const[o,...i]=Ri(n),a=xn(t.env),c=[o,...i,...e];yn.info("[test] Spawning Playwright process",{command:c.join(" "),pid:process.pid});const l=Date.now(),u=s.spawn(o,[...i,...e],{stdio:["inherit","pipe","pipe"],env:{...a,...process.env.CI?{}:{FORCE_COLOR:"1"}}});yn.info("[test] Playwright process spawned",{childPid:u.pid});const d=ya(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 ma)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=>{yn.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()&&(yn.error("[test] Playwright process error",{error:e.message,childPid:u.pid}),t(e))}),u.on("close",t=>{if(!h())return;yn.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)})})})}(f,{env:g,onClose:()=>{var e;yn.info("[test] Playwright process closed, cleaning up wrapper config"),(e=m)&&i.existsSync(e)&&i.rmSync(e)}})}function wa(e=""){process.stdout.write(`${e}\n`)}function va(...e){process.stderr.write(`${e.join(" ")}\n`)}var _a="stably",Ea=`https://registry.npmjs.org/${_a}/latest`,Ia=b.z.object({version:b.z.string()});function Ta(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 xa(e,t){const r=Ta(e),n=Ta(t);return!(!r||!n)&&(n.major>r.major||!(n.major<r.major)&&(n.minor>r.minor||!(n.minor<r.minor)&&n.patch>r.patch))}var Sa=D.default.join(j.default.homedir(),".stably"),Aa=D.default.join(Sa,"update-check.json"),Ca=`https://registry.npmjs.org/${_a}/latest`,Ra=b.z.object({lastCheck:b.z.number(),latestVersion:b.z.string()}),Pa=!1,Ua=!1,ka=async()=>{if(Ua)try{const{shutdown:e}=await import("@hyperdx/node-opentelemetry"),t=process.stderr.write.bind(process.stderr),r=process.stdout.write.bind(process.stdout),n=(e,...t)=>{const r=t[0];return!("string"!=typeof r||!r.includes("OpenTelemetry"))||!(!Buffer.isBuffer(r)||!r.toString().includes("OpenTelemetry"))||e(...t)};process.stderr.write=(...e)=>n(t,...e),process.stdout.write=(...e)=>n(r,...e);try{await e()}finally{process.stderr.write=t,process.stdout.write=r}}catch{}};!function(){const e=function(){try{const e=N.default.readFileSync(Aa,"utf-8");return Ra.parse(JSON.parse(e))}catch{return null}}(),t=Date.now();if((null==e||t-e.lastCheck>=18e5)&&function(){const e=`\n const https = require('https');\n const fs = require('fs');\n const url = '${Ca}';\n const cacheFile = ${JSON.stringify(Aa)};\n const cacheDir = ${JSON.stringify(Sa)};\n\n const req = https.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{s.spawn(process.execPath,["-e",e],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()}catch{}}(),null!=e&&xa(wr,e.latestVersion)){if(Pa)return;Pa=!0;let t=!1;const r=()=>{if(t)return;t=!0;const r=`${F.default.yellow(`update available (${wr} → ${e.latestVersion})`)} - run \`${_a} upgrade\` to get the latest version\n`;try{N.default.writeSync(2,r)}catch{}};process.once("beforeExit",r),process.once("exit",r)}}(),ne.cwdChanged&&yn.debug("Changed working directory",{cwd:ne.newCwd});for(const e of ne.envFilesLoaded)yn.debug("Loaded env file",{path:e});for(const e of ne.envFileErrors)yn.warn(e);var La=process.argv.findIndex(e=>"-v"===e||"--verbose"===e);-1!==La&&process.argv.splice(La,1);var Da=process.argv.findIndex(e=>"--no-telemetry"===e);-1!==Da&&process.argv.splice(Da,1),yn.info("CLI starting",{version:wr,args:process.argv.slice(2),cwd:process.cwd()}),process.on("unhandledRejection",(e,t)=>{yn.error("Unhandled promise rejection",{reason:e instanceof Error?{message:e.message,stack:e.stack}:e,promise:String(t)}),yn.flush(),yn.printLogFileInfo()}),process.on("uncaughtException",(e,t)=>{"EPIPE"!==e.code&&(yn.error("Uncaught exception",{error:{message:e.message,stack:e.stack,name:e.name},origin:t}),yn.flush(),yn.printLogFileInfo())});var Oa=new r.Command;Oa.name("stably").description("AI-assisted Playwright testing CLI").version(wr),Oa.enablePositionalOptions(),Oa.showHelpAfterError(),Oa.exitOverride(),Oa.configureHelp({subcommandTerm:e=>{const t=e.registeredArguments.map(e=>e.required?`<${e.name()}>`:`[${e.name()}]`).join(" ");return t?`${e.name()} ${t}`:e.name()}});var Ba=[];Oa.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>{Ba.push(e)}});var Na=()=>{const e=Oa.helpInformation().trimEnd();return e?`${e}\n`:""},ja=(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},$a=()=>{process.stdout.write(Na())};Oa.command("help [command...]").description("Show help for a command (e.g. stably help create)").action(e=>{if(!e||0===e.length)return void $a();const t=ja(Oa,e);if(!t)return process.stderr.write(`Unknown command: ${e.join(" ")}\n`),$a(),void(process.exitCode=1);var r;r=t,process.stdout.write((e=>{const t=e.helpInformation().trimEnd();return t?`${t}\n`:""})(r))}),Oa.action(()=>Zi({mode:"chat",getHelpText:Na})),Oa.command("login").description("Authenticate with Stably in your browser").action(Qr),Oa.command("logout").description("Clear stored Stably credentials").action(async()=>{const e=wn();e&&(m.log.warn(`Environment variables ${F.default.cyan("STABLY_API_KEY")} and ${F.default.cyan("STABLY_PROJECT_ID")} are set.`),m.log.warn("They will continue to be used for authentication even after logout."),m.log.warn("Unset them if you want to fully de-authenticate this shell/session."));const t=await Fr();if(!t)return void m.outro(e?F.default.yellow("No stored OAuth login found to clear."):F.default.yellow("You are not logged in."));const r=m.spinner();r.start("Logging out..."),await(async e=>{try{await fetch(`${Er}/api/backend/v1/logout`,{body:JSON.stringify({refresh_token:e}),headers:{"Content-Type":"application/json"},method:"POST"})}catch{}})(t.refreshToken),await Gr(),await Wr(),r.stop(F.default.green("✓ Logged out")),m.outro(F.default.green("You have been logged out successfully."))}),Oa.command("whoami").description("Show auth status and current project").action(async()=>{m.log.info(`${F.default.bold("CLI Version:")} ${F.default.cyan(wr)}`);const e=wn();if(e){m.log.info(F.default.dim("Authentication: Environment variables")),m.log.info(` ${F.default.bold("API Key:")} ${F.default.cyan(e.apiKey.slice(0,8))}...`),m.log.info(` ${F.default.bold("Project ID:")} ${F.default.cyan(e.projectId)}`);const t=await Fr();if(t){let e;try{e=Lr(t.accessToken).email}catch{e=void 0}m.log.warn("Stored OAuth login detected but will be ignored (env auth takes precedence)."),e&&m.log.info(` ${F.default.bold("OAuth Email:")} ${F.default.cyan(e)}`),m.log.info(` ${F.default.bold("Tip:")} Unset env vars to use OAuth`)}return void m.outro(F.default.green("Authenticated via environment variables"))}const t=await Fr();if(!t)return void m.outro(F.default.yellow("Not logged in. Run `stably login` to authenticate."));let r;try{r=Lr(t.accessToken).email}catch{r=void 0}const n=await zr();if(!n)return m.log.info(F.default.dim("Authentication: OAuth (not linked to a project)")),r&&m.log.info(` ${F.default.bold("Email:")} ${F.default.cyan(r)}`),void m.outro(F.default.yellow("Logged in but this directory is not linked to a project. Run `stably login` to link."));const s=await(async()=>Dr(process.cwd(),Nr))(),o=s?D.default.dirname(s):process.cwd(),i=D.default.relative(process.cwd(),o)||".";m.log.info(F.default.dim("Authentication: OAuth")),r&&m.log.info(` ${F.default.bold("Email:")} ${F.default.cyan(r)}`),m.log.info(` ${F.default.bold("Organization:")} ${F.default.cyan(n.orgName)}`),m.log.info(` ${F.default.bold("Project:")} ${F.default.cyan(n.projectName)}`),m.log.info(` ${F.default.bold("Linked at:")} ${F.default.dim(i)}`),m.outro(F.default.green("Authenticated"))}),Oa.command("build [input...]").description("Compile test specification files (.stably.md) into Playwright tests").option("--force","Force regeneration even if prompt is unchanged").action(async(e,t)=>{try{await async function(e){const{inputs:t,force:r}=e,n=process.cwd();let o;if(0===t.length){const e=function(e){try{return s.execSync('git ls-files --cached --others --exclude-standard "*.stably.md"',{cwd:e,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).split("\n").map(e=>e.trim()).filter(Boolean)}catch{return[]}}(n);o=e.map(e=>D.default.resolve(n,e))}else o=await async function(e,t){const r=[];for(const n of e){const e=D.default.resolve(t,n);let s;try{s=await H.default.stat(e)}catch{r.push(e);continue}if(s.isDirectory()){const t=await la(e);r.push(...t)}else r.push(e)}const n=new Set,s=[];for(const e of r){const t=D.default.resolve(e);n.has(t)||(n.add(t),s.push(t))}return s}(t,n);if(0===o.length)throw new Error("No .stably.md files found. Create a test specification file (e.g., login.stably.md) and try again.");const{fixedFiles:i}=await async function(e,t){const r=[],n=[];for(const s of e){let e=s;try{await H.default.stat(e)}catch{n.push(e);continue}if(e.endsWith(".md")&&!e.endsWith(".stably.md")){const n=e.replace(/\.md$/,".stably.md");try{await H.default.rename(e,n);const s=ca(D.default.relative(t,e)),o=ca(D.default.relative(t,n)),i={code:"STABLY_WARNING_FILE_RENAMED",message:`Renamed ${s} → ${o} (test specs must use .stably.md extension)`,details:{oldPath:s,newPath:o}};r.push(i),F.default.yellow(` ⚠ ${i.message}`),e=n}catch(t){if(!(t instanceof Error&&"code"in t)||"EEXIST"!==t.code&&"ENOTEMPTY"!==t.code)throw t;console.warn(F.default.yellow(` ⚠ Skipping rename: ${n} already exists`)),e=n}}if(!e.endsWith(".stably.md")){n.push(e);continue}const o=await H.default.readFile(e,"utf8"),{updated:i,addedFields:a}=da(o,e);if(a.length>0){await H.default.writeFile(e,i,"utf8");const n=ca(D.default.relative(t,e)),s={code:"STABLY_WARNING_FRONTMATTER_ADDED",message:`Added missing frontmatter fields to ${n}: ${a.join(", ")}`,details:{path:n,addedFields:a}};r.push(s),F.default.yellow(` ⚠ ${s.message}`)}n.push(e)}return{fixedFiles:n,warnings:r}}(o,n);o=i,F.default.bold(`Found ${o.length} test specification${1!==o.length?"s":""}`);for(const e of o){const t=ca(D.default.relative(n,e));F.default.dim(` ${t}`)}const a={built:[],skipped:[],failed:[]};for(const e of o){const t=ca(D.default.relative(n,e));try{"built"===await ha({force:r,inputFilePath:e})?a.built.push(t):a.skipped.push(t)}catch(e){const r=e instanceof Error?e.message:String(e);console.error(F.default.red(`Failed to build ${t}: ${r}`)),a.failed.push(t)}}return function(e){if(F.default.bold("Build Summary"),F.default.green(`${e.built.length} built`),F.default.dim(`${e.skipped.length} skipped (unchanged)`),e.failed.length>0?F.default.red(`${e.failed.length} failed`):F.default.dim("0 failed"),e.failed.length>0){F.default.red("Failed files:");for(const t of e.failed)F.default.red(` - ${t}`)}}(a),a.failed.length>0&&(process.exitCode=1),a}({inputs:e,force:t.force??!1})}catch(e){const t=e instanceof Error?e.message:String(e);process.stderr.write(`${t}\n`),process.exitCode=1}}),Oa.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=>{m.intro(`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=m.spinner();n.start("Starting development server...");const s=await R.startTunnel(`http://localhost:${e.port}`,{subdomain:r});n.stop(`Your local environment is available at: ]8;;${s.url}${F.default.underline(F.default.cyan(s.url))}]8;;`)}),Oa.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 Zi({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)=>Zi({mode:"single",prompt:e,outputDir:t.output})),Oa.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 s.execSync("git rev-parse --is-inside-work-tree",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}})(process.cwd())||(yn.error('Not a git repository. The "stably fix" command requires a git repository to track changes made during the fix. Please run this command from inside a git repository.'),process.stderr.write('Error: Not a git repository.\nThe "stably fix" command requires a git repository to track changes made during the fix.\nPlease run this command from inside a git repository.\n'),process.exit(1));const t=await(async e=>{const t=e=>e.replace(/\//g,"_");if(e)return yn.debug("Run ID provided explicitly",{runId:e}),t(e);const r=function(){if(process.env.CI_BUILD_ID)return process.env.CI_BUILD_ID;const e=(({env:e=process.env,cwd:t=process.cwd()}={})=>{for(const r of Object.keys(Kt))if(Kt[r].detect({env:e,cwd:t}))return{isCi:!0,...Kt[r].configuration({env:e,cwd:t})};return{isCi:Boolean(e.CI),...(r={env:e,cwd:t},{commit:wt(r),branch:vt(r)})};var r})();if(!e.isCi)return;const t=function(e){switch(e){case"github":return process.env.GITHUB_RUN_ATTEMPT;case"azure-devops":return process.env.SYSTEM_JOBATTEMPT;case"bitbucket":return process.env.BITBUCKET_STEP_RUN_NUMBER;default:return}}(e.service),r=[e.service,"slug"in e?e.slug?.replace(/\//g,"_"):void 0,"build"in e?String(e.build):void 0,"job"in e?String(e.job):void 0,t&&String(t)].filter(Boolean);return r.length>0?r.join("-"):void 0}();if(r)return yn.debug("Run ID detected from CI environment",{runId:r}),t(r);yn.debug("No explicit run ID or CI environment detected, checking last-run.json");const n=await(async()=>{try{const e=await Dr(process.cwd(),".stably/last-run.json");if(!e)return;const t=await g.readFile(e,"utf-8");return{...ea.parse(JSON.parse(t)),filePath:e}}catch{return}})();if(n){const e=(Date.now()-n.timestamp)/36e5;return yn.debug("Run ID found in last-run.json",{runId:n.runId,timestamp:n.timestamp,filePath:n.filePath,ageHours:Math.round(e)}),e>24&&yn.warn(`Using run ID from ${Math.round(e)} hours ago (${n.filePath}). Provide an explicit run ID if this is not the run you want to fix.`),t(n.runId)}yn.debug("No run ID found in last-run.json")})(e);return t||(process.stderr.write('Run ID is required. Either:\n 1. Run "stably test" first (run ID will be auto-detected)\n 2. Provide a run ID: stably fix <runId>\n 3. Run in CI (auto-detected from environment)\n'),process.exit(1)),Zi({mode:"fix",runId:t})}),Oa.command("init").description("Initialize Playwright and Stably SDK in your project").action(async()=>Zi({mode:"init"})),Oa.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;wa(F.default.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(Ea,{signal:e.signal});if(!t.ok)throw new Error(`Failed to fetch latest version: ${t.statusText}`);return Ia.parse(await t.json()).version}finally{clearTimeout(t)}}();return{current:wr,latest:e,isOutdated:xa(wr,e)}}()}catch(e){return va(F.default.red("Failed to check for updates:"),e instanceof Error?e.message:e),void(process.exitCode=1)}if(wa(`Current version: ${F.default.yellow(r.current)}`),wa(`Latest version: ${F.default.green(r.latest)}`),wa(),!r.isOutdated)return void wa(F.default.green("✓ You are already on the latest version!"));if(wa(F.default.yellow(`⚠ A new version is available: ${r.current} → ${r.latest}`)),wa(),t)return wa(F.default.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"))return"npx";try{const t=s.execSync("npm root -g",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-npm"}catch{}if(e.includes("node_modules/stably"))return"global-npm";try{const t=s.execSync("pnpm root -g",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-pnpm"}catch{}try{const t=s.execSync("yarn global dir",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-yarn-classic"}catch{}try{const t=s.execSync("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",`${_a}@latest`],description:`npm install -g ${_a}@latest`};case"global-pnpm":return{command:"pnpm",args:["add","-g",`${_a}@latest`],description:`pnpm add -g ${_a}@latest`};case"global-yarn-classic":return{command:"yarn",args:["global","add",`${_a}@latest`],description:`yarn global add ${_a}@latest`};case"npx":return{command:"npx",args:[`${_a}@latest`],description:`npx ${_a}@latest (always uses latest)`}}}(n);if("npx"===n)return wa(F.default.dim("You are running via npx, which always fetches the latest version.")),void wa(F.default.dim(`Simply run: ${F.default.white("npx stably")} to use the latest version.`));"unknown"===n?(wa(F.default.yellow("Could not detect installation method. Falling back to npm.")),wa()):"global-yarn-berry"===n&&(wa(F.default.yellow("Yarn Berry does not support global packages. Falling back to npm.")),wa()),wa(`Upgrade command: ${F.default.cyan(o.description)}`),wa(),wa(F.default.cyan("Upgrading...")),wa();try{await(i=o.command,a=o.args,new Promise((e,t)=>{const r=s.spawn(i,a,{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)})})),wa(),wa(F.default.green("✓ Upgrade complete!")),wa(F.default.dim(`Run ${F.default.white("stably --version")} to verify.`))}catch(e){va(F.default.red("Upgrade failed:"),e instanceof Error?e.message:e),wa(),wa(F.default.dim("You can try manually running:")),wa(F.default.cyan(` ${o.description}`)),process.exitCode=1}var i,a}(e)),ga.forEach(({args:e,description:t,name:r})=>{Oa.command(r).description(t).helpOption(!1).helpCommand(!1).allowUnknownOption(!0).allowExcessArguments(!0).passThroughOptions().action(()=>ba({overrideArgs:e,subcommand:r}))});var Ma=()=>{0!==Ba.length&&(process.stderr.write(Ba.join("")),Ba=[])};(async()=>{await(async()=>{if(!Ua&&"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":wr,"node.version":process.version,"os.platform":process.platform}}),Ua=!0}catch{}})();try{await Oa.parseAsync(process.argv),yn.info("CLI completed successfully")}catch(e){if(!(e=>!!e&&"object"==typeof e&&"code"in e)(e))throw yn.error("Unexpected CLI error",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),Ma(),yn.flush(),yn.printLogFileInfo(),await ka(),e;const t="number"==typeof e.exitCode?e.exitCode:1,r=process.argv.slice(2).find(e=>!e.startsWith("-")),n=!!r&&!!ja(Oa,[r]);if(("commander.excessArguments"===e.code||"commander.unknownCommand"===e.code)&&r&&!n)return Ba=[],yn.warn("Unknown command",{command:r}),process.stderr.write(`command '${r}' not found\n`),$a(),void(process.exitCode=t);yn.debug("Commander error",{code:e.code,exitCode:t}),Ma(),process.exitCode=t}finally{yn.flush(),await ka()}})();
2
+ "use strict";var e=require("dotenv"),t=require("path"),r=require("commander"),n=require("buffer"),s=require("child_process"),o=require("process"),i=require("fs"),a=require("url"),c=require("os");require("timers/promises");var l=require("stream"),u=require("util"),d=require("@anthropic-ai/claude-agent-sdk"),p=require("ts-pattern"),f=require("crypto"),h=require("picocolors"),g=require("simple-git"),m=require("fs/promises"),y=require("@clack/prompts"),b=require("readline/promises"),w=require("zod"),v=require("open"),_=require("http"),E=require("pino"),I=require("sonic-boom"),T=require("zod/v3"),x=require("ws"),S=require("react"),A=require("react/jsx-runtime"),C=require("module"),R=require("yaml"),P=require("@stablyhq/runner-sdk"),U="undefined"!=typeof document?document.currentScript:null;function k(e){return e&&e.__esModule?e:{default:e}}var L,D,O=k(t),B=k(s),N=k(o),$=k(i),j=k(c),M=k(l),F=k(f),H=k(h),G=k(m),z=k(w),Y=k(v),W=k(_),V=k(E),q=k(I),K=k(x),J=Object.create,X=Object.defineProperty,Q=Object.getOwnPropertyDescriptor,Z=Object.getOwnPropertyNames,ee=Object.getPrototypeOf,te=Object.prototype.hasOwnProperty,re=(e=>"undefined"!=typeof require?require:"undefined"!=typeof Proxy?new Proxy(e,{get:(e,t)=>("undefined"!=typeof require?require:e)[t]}):e)(function(e){if("undefined"!=typeof require)return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),ne=(L={"../playwright-trace-scrubber/node_modules/.pnpm/isbinaryfile@5.0.7/node_modules/isbinaryfile/lib/index.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.isBinaryFileSync=e.isBinaryFile=void 0;var t=re("fs"),r=re("util"),n=(0,r.promisify)(t.stat),s=(0,r.promisify)(t.open),o=(0,r.promisify)(t.close),i=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){const t=new Array;for(let r=0;r<e;r++){if(this.error)return t;t[r]=this.nextByte()}return t}};function a(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 c(e){switch(7&a(e)){case 0:return a(e),!0;case 1:return e.next(8),!0;case 2:const t=a(e);return e.next(t),!0;case 5:return e.next(4),!0}return!1}function l(e,t){if(0===t)return!1;let r=0;const n=Math.min(t,515),s=Math.min(n,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(n>=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;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<n){if(t++,e[t]>=128&&e[t]<=191)continue}else if(e[t]>=224&&e[t]<=239&&t+2<n){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<n&&(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 r=new i(e,t);let n=0;for(;;){if(!c(r)&&!r.hasError())return!1;if(r.hasError())break;n++}return n>0}(e,s))}function u(e){return"string"==typeof e}function d(e){if(!e.isFile())throw new Error("Path provided was not a file!")}e.isBinaryFile=async function(e,r){if(u(e)){d(await n(e));const r=await s(e,"r"),i=Buffer.alloc(515);return new Promise((e,n)=>{t.read(r,i,0,515,0,(t,s,a)=>{if(o(r),t)n(t);else try{e(l(i,s))}catch(e){n(e)}})})}return void 0===r&&(r=e.length),l(e,r)},e.isBinaryFileSync=function(e,r){if(u(e)){d(t.statSync(e));const r=t.openSync(e,"r"),n=Buffer.alloc(515),s=t.readSync(r,n,0,515,0);return t.closeSync(r),l(n,s)}return void 0===r&&(r=e.length),l(e,r)}}},function(){return D||(0,L[Z(L)[0]])((D={exports:{}}).exports,D),D.exports}),se={cwdChanged:!1,newCwd:void 0,envFilesLoaded:[],envFileErrors:[]},oe=process.argv.findIndex(e=>"-C"===e||"--cwd"===e);if(-1!==oe&&process.argv[oe+1]){const e=process.argv[oe+1];process.chdir(e),se.cwdChanged=!0,se.newCwd=e,process.argv.splice(oe,2)}for(var ie=[],ae=0;ae<process.argv.length;)if("--env-file"===process.argv[ae]){const e=process.argv[ae+1];e&&!e.startsWith("-")?(ie.push(e),process.argv.splice(ae,2)):ae++}else ae++;for(const t of ie){const r=O.default.resolve(process.cwd(),t),n=e.config({path:r,override:!0,quiet:!0});if(n.error){const e=`warning: could not load env file: ${r} (${n.error.message})`;se.envFileErrors.push(e),process.stderr.write(`${e}\n`)}else se.envFilesLoaded.push(r)}var ce={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 le(e){return(/\d+(?!.*\d+)/.exec(e)||[])[0]}function ue(e){return e?/^(?:refs\/heads\/)?(?<branch>.+)$/i.exec(e)[1]:void 0}var de={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:ue(r?e.SYSTEM_PULLREQUEST_TARGETBRANCH:e.BUILD_SOURCEBRANCH),pr:t,isPr:r,prBranch:ue(r?e.SYSTEM_PULLREQUEST_SOURCEBRANCH:void 0),root:e.BUILD_REPOSITORY_LOCALPATH}}},pe={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})},fe={detect:({env:e})=>Boolean(e.BITBUCKET_BUILD_NUMBER),configuration:({env:e})=>({name:"Bitbucket Pipelines",service:"bitbucket",commit:e.BITBUCKET_COMMIT,tag:e.BITBUCKET_TAG,build:e.BITBUCKET_BUILD_NUMBER,buildUrl:`https://bitbucket.org/${e.BITBUCKET_REPO_FULL_NAME}/addon/pipelines/home#!/results/${e.BITBUCKET_BUILD_NUMBER}`,branch:e.BITBUCKET_BRANCH,slug:e.BITBUCKET_REPO_FULL_NAME,root:e.BITBUCKET_CLONE_DIR})},he={detect:({env:e})=>Boolean(e.BITRISE_IO),configuration({env:e}){const t="false"===e.BITRISE_PULL_REQUEST?void 0:e.BITRISE_PULL_REQUEST,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}}},ge={detect:({env:e})=>Boolean(e.BUDDY_WORKSPACE_ID),configuration({env:e}){const t=le(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}}},me="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function ye(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var be,we,ve,_e,Ee,Ie,Te,xe,Se={exports:{}};var Ae,Ce,Re,Pe,Ue,ke,Le,De,Oe,Be,Ne,$e,je,Me,Fe,He={exports:{}},Ge={};function ze(){if($e)return Ne;$e=1;const e=O.default,t=function(){if(Re)return Ce;Re=1;const e=O.default,t=function(){if(xe)return Te;xe=1;const e="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,t=O.default,r=e?";":":",n=function(){if(Ie)return Ee;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 Ie=1,e="win32"===process.platform||me.TESTING_WINDOWS?function(){if(we)return be;we=1,be=r,r.sync=function(r,n){return t(e.statSync(r),r,n)};var e=$.default;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 be}():function(){if(_e)return ve;_e=1,ve=t,t.sync=function(t,n){return r(e.statSync(t),n)};var e=$.default;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 ve}(),Ee=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}},Ee}(),s=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),o=(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}},i=(e,r,i)=>{"function"==typeof r&&(i=r,r={}),r||(r={});const{pathEnv:a,pathExt:c,pathExtExe:l}=o(e,r),u=[],d=n=>new Promise((o,i)=>{if(n===a.length)return r.all&&u.length?o(u):i(s(e));const c=a[n],l=/^".*"$/.test(c)?c.slice(1,-1):c,d=t.join(l,e),f=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d;o(p(f,n,0))}),p=(e,t,s)=>new Promise((o,i)=>{if(s===c.length)return o(d(t+1));const a=c[s];n(e+a,{pathExt:l},(n,i)=>{if(!n&&i){if(!r.all)return o(e+a);u.push(e+a)}return o(p(e,t,s+1))})});return i?d(0).then(e=>i(null,e),i):d(0)};return Te=i,i.sync=(e,r)=>{r=r||{};const{pathEnv:i,pathExt:a,pathExtExe:c}=o(e,r),l=[];for(let s=0;s<i.length;s++){const o=i[s],u=/^".*"$/.test(o)?o.slice(1,-1):o,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(n.sync(t,{pathExt:c})){if(!r.all)return t;l.push(t)}}catch(e){}}}if(r.all&&l.length)return l;if(r.nothrow)return null;throw s(e)},Te}(),r=function(){if(Ae)return He.exports;Ae=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 He.exports=e,He.exports.default=e,He.exports}();function n(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 Ce=function(e){return n(e)||n(e,!0)}}(),r=function(){if(Pe)return Ge;Pe=1;const e=/([()\][%!^"`<>&|;, *?])/g;return Ge.command=function(t){return t.replace(e,"^$1")},Ge.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},Ge}(),n=function(){if(Be)return Oe;Be=1;const e=$.default,t=function(){if(De)return Le;De=1;const e=ke?Ue:(ke=1,Ue=/^#!(.*)/);return Le=(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 Oe=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())},Oe}(),s="win32"===process.platform,o=/\.(?:com|exe)$/i,i=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;return Ne=function(a,c,l){c&&!Array.isArray(c)&&(l=c,c=null);const u={command:a,args:c=c?c.slice(0):[],options:l=Object.assign({},l),file:void 0,original:{command:a,args:c}};return l.shell?u:function(a){if(!s)return a;const c=function(e){e.file=t(e);const r=e.file&&n(e.file);return r?(e.args.unshift(e.file),e.command=r,t(e)):e.file}(a),l=!o.test(c);if(a.options.forceShell||l){const t=i.test(c);a.command=e.normalize(a.command),a.command=r.command(a.command),a.args=a.args.map(e=>r.argument(e,t));const n=[a.command].concat(a.args).join(" ");a.args=["/d","/s","/c",`"${n}"`],a.command=process.env.comspec||"cmd.exe",a.options.windowsVerbatimArguments=!0}return a}(u)}}var Ye=ye(function(){if(Fe)return Se.exports;Fe=1;const e=B.default,t=ze(),r=function(){if(Me)return je;Me=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 je={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},je}();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 Se.exports=n,Se.exports.spawn=n,Se.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},Se.exports._parse=t,Se.exports._enoent=r,Se.exports}());function We(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 Ve=(e,t)=>({name:`SIGRT${t+1}`,number:qe+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),qe=34,Ke=[{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"}],Je=()=>{const e=(()=>{const e=64-qe+1;return Array.from({length:e},Ve)})();return[...Ke,...e].map(Xe)},Xe=({name:e,number:t,description:r,action:n,forced:s=!1,standard:o})=>{const{signals:{[e]:i}}=c.constants,a=void 0!==i;return{name:e,number:a?i:t,description:r,supported:a,action:n,forced:s,standard:o}},Qe=({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}],Ze=(()=>{const e=Je();return Object.fromEntries(e.map(Qe))})();(()=>{const e=Je(),t=Array.from({length:65},(t,r)=>((e,t)=>{const r=((e,t)=>{const r=t.find(({name:t})=>c.constants.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:l}=r;return{[e]:{name:n,number:e,description:s,supported:o,action:i,forced:a,standard:l}}})(r,e));Object.assign({},...t)})();var et=({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=N.default.cwd()}}})=>{o=null===o?void 0:o;const f=void 0===(s=null===s?void 0:s)?void 0:Ze[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},tt=["stdin","stdout","stderr"],rt=[];rt.push("SIGHUP","SIGINT","SIGTERM"),"win32"!==process.platform&&rt.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),"linux"===process.platform&&rt.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var nt,st,ot=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,it=Symbol.for("signal-exit emitter"),at=globalThis,ct=Object.defineProperty.bind(Object),lt=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(at[it])return at[it];ct(at,it,{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}},ut=class{},dt=globalThis.process;ot(dt)?new class extends ut{#e="win32"===dt.platform?"SIGINT":"SIGHUP";#t=new lt;#r;#n;#s;#o={};#i=!1;constructor(e){super(),this.#r=e,this.#o={};for(const t of rt)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(!ot(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 rt)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,rt.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 ot(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&&ot(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)}}(dt):new class extends ut{onExit(){return()=>{}}load(){}unload(){}},new TextEncoder,function(){if(st)return nt;st=1;const{PassThrough:e}=M.default;nt=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 pt=(async()=>{})().constructor.prototype;["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(pt,e)]);var ft=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],ht=/^[\w.-]+$/,gt=u.debuglog("execa").enabled,mt=(e,t)=>String(e).padStart(t,"0"),yt=(e,t,r={})=>{const n=Ye._parse(e,t,r);return e=n.command,t=n.args,(r={maxBuffer:1e8,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:(r=n.options).cwd||N.default.cwd(),execPath:N.default.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:gt,...r}).env=(({env:e,extendEnv:t,preferLocal:r,localDir:n,execPath:s})=>{const o=t?{...N.default.env,...e}:e;return r?(({env:e=N.default.env,...t}={})=>{const r=We({env:e={...e}});return t.path=e[r],e[r]=(({cwd:e=N.default.cwd(),path:t=N.default.env[We()],preferLocal:r=!0,execPath:n=N.default.execPath,addExecPath:s=!0}={})=>{const o=e instanceof URL?a.fileURLToPath(e):e,i=O.default.resolve(o),c=[];return r&&((e,t)=>{let r;for(;r!==t;)e.push(O.default.join(t,"node_modules/.bin")),r=t,t=O.default.resolve(t,"..")})(c,i),s&&((e,t,r)=>{const n=t instanceof URL?a.fileURLToPath(t):t;e.push(O.default.resolve(r,n,".."))})(c,n,i),[...c,t].join(O.default.delimiter)})(t),e})({env:o,cwd:n,execPath:s}):o})(r),r.stdio=(e=>{if(!e)return;const{stdio:t}=e;if(void 0===t)return tt.map(t=>e[t]);if((e=>tt.some(t=>void 0!==e[t]))(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${tt.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,tt.length);return Array.from({length:r},(e,r)=>t[r])})(r),"win32"===N.default.platform&&"cmd"===O.default.basename(e,".exe")&&t.unshift("/q"),{file:e,args:t,options:r,parsed:n}},bt=(e,t,r)=>"string"==typeof t||n.Buffer.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 wt(e,t,r){const n=yt(e,t,r),s=((e,t)=>ft(e,t).join(" "))(e,t),o=((e,t)=>ft(e,t).map(e=>(e=>"string"!=typeof e||ht.test(e)?e:`"${e.replaceAll('"','\\"')}"`)(e)).join(" "))(e,t);((e,{verbose:t})=>{t&&N.default.stderr.write(`[${(()=>{const e=new Date;return`${mt(e.getHours(),2)}:${mt(e.getMinutes(),2)}:${mt(e.getSeconds(),2)}.${mt(e.getMilliseconds(),3)}`})()}] ${e}\n`)})(o,n.options);const a=(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),i.readFileSync(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 c;try{c=B.default.spawnSync(n.file,n.args,{...n.options,input:a})}catch(e){throw et({error:e,stdout:"",stderr:"",all:"",command:s,escapedCommand:o,parsed:n,timedOut:!1,isCanceled:!1,killed:!1})}const l=bt(n.options,c.stdout,c.error),u=bt(n.options,c.stderr,c.error);if(c.error||0!==c.status||null!==c.signal){const e=et({stdout:l,stderr:u,error:c.error,signal:c.signal,exitCode:c.status,command:s,escapedCommand:o,parsed:n,timedOut:c.error&&"ETIMEDOUT"===c.error.code,isCanceled:!1,killed:null!==c.signal});if(!n.options.reject)return e;throw e}return{command:s,escapedCommand:o,exitCode:0,stdout:l,stderr:u,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}}function vt(e){try{return wt("git",["rev-parse","HEAD"],e).stdout}catch{return}}function _t(e){try{const t=wt("git",["rev-parse","--abbrev-ref","HEAD"],e).stdout;if("HEAD"===t){const t=wt("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 Et=/^(?:.*)@(?:.*):(?:\d+\/)?(.*)\.git$/,It=/^\/(.*)\.git$/;function Tt(e){if(e){if(e.match(Et))return e.replace(Et,"$1");try{return new URL(e).pathname.replace(It,"$1")}catch{return}}}var xt,St={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:Tt(e.BUILDKITE_REPO),pr:t,isPr:r,prBranch:r?e.BUILDKITE_BRANCH:void 0,root:e.BUILDKITE_BUILD_CHECKOUT_PATH}}},At={detect:({env:e})=>Boolean(e.CIRCLECI),configuration({env:e}){const t=e.CIRCLE_PR_NUMBER||le(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}`}}},Ct="https://cirrus-ci.com",Rt={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:`${Ct}/build/${e.CIRRUS_BUILD_ID}`,job:e.CIRRUS_TASK_ID,jobUrl:`${Ct}/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}}},Pt={detect:({env:e})=>Boolean(e.CODEBUILD_BUILD_ID),configuration:({env:e,cwd:t})=>({name:"AWS CodeBuild",service:"codebuild",commit:vt({env:e,cwd:t}),build:e.CODEBUILD_BUILD_ID,branch:_t({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})},Ut={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}}},kt={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}}},Lt=({env:e})=>{try{const t=e.GITHUB_EVENT_PATH?JSON.parse(i.readFileSync(e.GITHUB_EVENT_PATH,"utf-8")):void 0;if(t&&t.pull_request)return{branch:t.pull_request.base?ue(t.pull_request.base.ref):void 0,pr:t.pull_request.number}}catch{}return{pr:void 0,branch:void 0}},Dt={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=ue("pull_request_target"===e.GITHUB_EVENT_NAME?`refs/pull/${(e=>{const t=e.GITHUB_EVENT_PATH?JSON.parse(i.readFileSync(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?Lt({env:e}):void 0}}},Ot={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}}},Bt={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||vt({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}}},Nt={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}}},$t={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})},jt={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}}},Mt={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}}},Ft={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}}},Ht={detect:({env:e})=>Boolean(e.SEMAPHORE),configuration({env:e,cwd:t}){const r=e.SEMAPHORE_GIT_PR_NUMBER||e.PULL_REQUEST_NUMBER,n=Boolean(r);return{name:"Semaphore",service:"semaphore",commit:e.SEMAPHORE_GIT_SHA||vt({env:e,cwd:t}),tag:e.SEMAPHORE_GIT_TAG_NAME,build:e.SEMAPHORE_JOB_ID||e.SEMAPHORE_BUILD_NUMBER,branch:e.SEMAPHORE_GIT_BRANCH||(n?void 0:e.BRANCH_NAME),pr:r,isPr:n,prBranch:e.SEMAPHORE_GIT_PR_BRANCH||(n?e.BRANCH_NAME:void 0),slug:e.SEMAPHORE_GIT_REPO_SLUG||e.SEMAPHORE_REPO_SLUG,root:e.SEMAPHORE_GIT_DIR||e.SEMAPHORE_PROJECT_DIR}}},Gt={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}}},zt={};function Yt(){if(xt)return zt;xt=1,Object.defineProperty(zt,"__esModule",{value:!0}),zt.of=zt.PropertiesFile=void 0;var e,t=(e=$.default)&&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 zt.PropertiesFile=r,zt.of=function(...e){let t=new r;return t.of.apply(t,e),t},zt}var Wt=ye(Yt()),Vt={root:"teamcity.build.workingDir",branch:"teamcity.build.branch"},qt=e=>{try{return Wt.of(e)}catch{return}},Kt=({env:e,cwd:t})=>{const r=e.TEAMCITY_BUILD_PROPERTIES_FILE?qt(e.TEAMCITY_BUILD_PROPERTIES_FILE):void 0,n=r?r.get("teamcity.configuration.properties.file"):void 0,s=n?qt(n):n;return Object.fromEntries(Object.keys(Vt).map(n=>[n,(r?r.get(Vt[n]):void 0)||(s?s.get(Vt[n]):void 0)||("branch"===n?_t({env:e,cwd:t}):void 0)]))},Jt={appveyor:ce,azurePipelines:de,bamboo:pe,bitbucket:fe,bitrise:he,buddy:ge,buildkite:St,circleci:At,cirrus:Rt,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:Pt,codefresh:Ut,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:kt,github:Dt,gitlab:Ot,jenkins:Bt,netlify:Nt,puppet:$t,sail:jt,screwdriver:Mt,scrutinizer:Ft,semaphore:Ht,shippable:Gt,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,...Kt({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:ue(e.JB_SPACE_GIT_BRANCH),slug:t&&r?`${t.toLowerCase()}/${r}`:void 0}}}},Xt=class e{git;config;snapshotTreeHash;snapshotIndexPath;constructor(e){this.config=e,this.git=g.simpleGit({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=t.join(c.tmpdir(),`git-diff-tracker-${f.randomUUID()}.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=t.join(c.tmpdir(),`git-diff-tracker-${f.randomUUID()}.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 Qt(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 Qt(this.snapshotIndexPath),this.snapshotIndexPath=void 0),this.snapshotTreeHash=void 0}};async function Qt(e){try{await m.unlink(e)}catch{}}var Zt="x-stably-org-id",er={bodySerializer:e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t)},tr=({allowReserved:e,explode:t,name:r,style:n,value:s})=>{if(!t){const t=(e?s:s.map(e=>encodeURIComponent(e))).join((e=>{switch(e){case"form":default:return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20"}})(n));switch(n){case"label":return`.${t}`;case"matrix":return`;${r}=${t}`;case"simple":return t;default:return`${r}=${t}`}}const o=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(n),i=s.map(t=>"label"===n||"simple"===n?e?t:encodeURIComponent(t):rr({allowReserved:e,name:r,value:t})).join(o);return"label"===n||"matrix"===n?o+i:i},rr=({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)}`},nr=({allowReserved:e,explode:t,name:r,style:n,value:s,valueOnly:o})=>{if(s instanceof Date)return o?s.toISOString():`${r}=${s.toISOString()}`;if("deepObject"!==n&&!t){let t=[];Object.entries(s).forEach(([r,n])=>{t=[...t,r,e?n:encodeURIComponent(n)]});const o=t.join(",");switch(n){case"form":return`${r}=${o}`;case"label":return`.${o}`;case"matrix":return`;${r}=${o}`;default:return o}}const i=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(n),a=Object.entries(s).map(([t,s])=>rr({allowReserved:e,name:"deepObject"===n?`${r}[${t}]`:t,value:s})).join(i);return"label"===n||"matrix"===n?i+a:a},sr=/\{[^{}]+\}/g;function or(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 ir,ar=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},cr=({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=tr({allowReserved:i.allowReserved,explode:!0,name:s,style:"form",value:o,...i.array});e&&n.push(e)}else if("object"==typeof o){const e=nr({allowReserved:i.allowReserved,explode:!0,name:s,style:"deepObject",value:o,...i.object});e&&n.push(e)}else{const e=rr({allowReserved:i.allowReserved,name:s,value:o});e&&n.push(e)}}return n.join("&")},lr=(e,t)=>!!t&&!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`)),ur=e=>(({baseUrl:e,path:t,query:r,querySerializer:n,url:s})=>{let o=(e??"")+(s.startsWith("/")?s:`/${s}`);t&&(o=(({path:e,url:t})=>{let r=t;const n=t.match(sr);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,tr({explode:n,name:s,style:o,value:i}));continue}if("object"==typeof i){r=r.replace(t,nr({explode:n,name:s,style:o,value:i,valueOnly:!0}));continue}if("matrix"===o){r=r.replace(t,`;${rr({name:s,value:i})}`);continue}const a=encodeURIComponent("label"===o?`.${i}`:i);r=r.replace(t,a)}return r})({path:t,url:o}));let i=r?n(r):"";return i.startsWith("?")&&(i=i.substring(1)),i&&(o+=`?${i}`),o})({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:"function"==typeof e.querySerializer?e.querySerializer:cr(e.querySerializer),url:e.url}),dr=(e,t)=>{const r={...e,...t};return r.baseUrl?.endsWith("/")&&(r.baseUrl=r.baseUrl.substring(0,r.baseUrl.length-1)),r.headers=fr(e.headers,t.headers),r},pr=e=>{const t=[];return e.forEach((e,r)=>{t.push([r,e])}),t},fr=(...e)=>{const t=new Headers;for(const r of e){if(!r)continue;const e=r instanceof Headers?pr(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},hr=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}},gr=cr({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),mr={"Content-Type":"application/json"},yr=(e={})=>({...er,headers:mr,parseAs:"auto",querySerializer:gr,...e}),br=(e={})=>{let t=dr(yr(),e);const r=()=>({...t}),n={error:new hr,request:new hr,response:new hr},s=async e=>{const r={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:fr(t.headers,e.headers),serializedBody:void 0};return r.security&&await(async({security:e,...t})=>{for(const r of e){if(lr(t,r.name))continue;const e=await ar(r,t.auth);if(!e)continue;const n=r.name??"Authorization";switch(r.in){case"query":t.query||(t.query={}),t.query[n]=e;break;case"cookie":t.headers.append("Cookie",`${n}=${e}`);break;default:t.headers.set(n,e)}}})({...r,security:r.security}),r.requestValidator&&await r.requestValidator(r),void 0!==r.body&&r.bodySerializer&&(r.serializedBody=r.bodySerializer(r.body)),void 0!==r.body&&""!==r.serializedBody||r.headers.delete("Content-Type"),{opts:r,url:ur(r)}},o=async e=>{const{opts:t,url:r}=await s(e),o={redirect:"follow",...t,body:or(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;try{c=await a(i)}catch(e){let r=e;for(const s of n.error.fns)s&&(r=await s(e,void 0,i,t));if(r=r||{},t.throwOnError)throw r;return"data"===t.responseStyle?void 0:{error:r,request:i,response:void 0}}for(const e of n.response.fns)e&&(c=await e(c,i,t));const l={request:i,response:c};if(c.ok){const e=("auto"===t.parseAs?(e=>{if(!e)return"stream";const t=e.split(";")[0]?.trim();return t?t.startsWith("application/json")||t.endsWith("+json")?"json":"multipart/form-data"===t?"formData":["application/","audio/","image/","video/"].some(e=>t.startsWith(e))?"blob":t.startsWith("text/")?"text":void 0:void 0})(c.headers.get("Content-Type")):t.parseAs)??"json";if(204===c.status||"0"===c.headers.get("Content-Length")){let r;switch(e){case"arrayBuffer":case"blob":case"text":r=await c[e]();break;case"formData":r=new FormData;break;case"stream":r=c.body;break;default:r={}}return"data"===t.responseStyle?r:{data:r,...l}}let r;switch(e){case"arrayBuffer":case"blob":case"formData":case"json":case"text":r=await c[e]();break;case"stream":return"data"===t.responseStyle?c.body:{data:c.body,...l}}return"json"===e&&(t.responseValidator&&await t.responseValidator(r),t.responseTransformer&&(r=await t.responseTransformer(r))),"data"===t.responseStyle?r:{data:r,...l}}const u=await c.text();let d;try{d=JSON.parse(u)}catch{}const p=d??u;let f=p;for(const e of n.error.fns)e&&(f=await e(p,c,i,t));if(f=f||{},t.throwOnError)throw f;return"data"===t.responseStyle?void 0:{error:f,...l}},i=e=>t=>o({...t,method:e}),a=e=>async t=>{const{opts:r,url:o}=await s(t);return(({onRequest:e,onSseError:t,onSseEvent:r,responseTransformer:n,responseValidator:s,sseDefaultRetryDelay:o,sseMaxRetryAttempts:i,sseMaxRetryDelay:a,sseSleepFn:c,url:l,...u})=>{let d;const p=c??(e=>new Promise(t=>setTimeout(t,e))),f=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)}}}();return{stream:f}})({...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:ur,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=dr(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")}},wr=br(yr({baseUrl:"https://api.stably.ai"})),vr="4.6.2",_r=process.env.STABLY_API_URL||"https://api.stably.ai",Er=e=>{const t=new URL(e);return t.protocol="http:"===t.protocol?"ws:":"wss:",t},Ir=process.env.AUTH_URL||"https://auth.stably.ai",Tr=process.env.AUTH_CLIENT_ID||"288007877071cce81f269428ea78653a",xr=process.env.AI_PROXY_URL||"https://ai-proxy.stably.ai",Sr=process.env.STABLY_AUTOHEAL_WS_URL||new URL("/autoheal",Er(_r)).toString(),Ar=process.env.STABLY_CREATE_PROGRESS_WS_URL||new URL("/create-progress",Er(_r)).toString(),Cr="http://localhost:9876/auth/callback",Rr=()=>ir||(ir=br(yr({baseUrl:_r,headers:{"X-STABLY-CLI-VERSION":vr,"X-STABLY-SOURCE":"cli"}}))),Pr=async(e,t)=>{const r=await(n={body:{accessToken:e,orgId:t},client:Rr()},(n.client??wr).post({url:"/internal/v1/cli/exchange-token",...n,headers:{"Content-Type":"application/json",...n.headers}}));var n;if(401===r.response.status)throw new Error("Invalid or expired access token");if(403===r.response.status)throw new Error("You do not have access to this organization");if(r.error)throw new Error(`Failed to exchange token: ${r.response.status}`);return r.data},Ur=w.z.object({org_id:w.z.string(),org_name:w.z.string()}),kr=w.z.object({email:w.z.string(),org_id_to_org_member_info:w.z.record(w.z.string(),Ur).optional(),org_member_info:Ur.optional(),user_id:w.z.string()});w.z.object({email:w.z.string(),firstName:w.z.string().optional(),lastName:w.z.string().optional(),organizations:w.z.array(w.z.object({id:w.z.string(),name:w.z.string()})),userId:w.z.string()});var Lr=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)},Dr=e=>{try{const t=kr.parse(Lr(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=async(e,t)=>{let r=e;const{root:n}=O.default.parse(r);for(;r!==n;){const e=O.default.join(r,t);try{return await m.access(e),e}catch{r=O.default.dirname(r)}}},Br=O.default.join(j.default.homedir(),".stably"),Nr=O.default.join(Br,"auth.json"),$r=".stably",jr="project.json",Mr=z.default.object({accessToken:z.default.string(),expiresAt:z.default.number(),idToken:z.default.string().optional(),refreshToken:z.default.string()}),Fr=z.default.object({orgId:z.default.string(),orgName:z.default.string(),projectId:z.default.string(),projectName:z.default.string()}),Hr=async()=>{try{const e=await m.readFile(Nr,"utf-8");return Mr.parse(JSON.parse(e))}catch{return}},Gr=async e=>{await m.mkdir(Br,{recursive:!0}),await m.writeFile(Nr,JSON.stringify(e,null,2),{mode:384})},zr=async()=>{try{await m.unlink(Nr)}catch{}},Yr=async()=>{try{const e=await Or(process.cwd(),$r);if(!e)return;const t=O.default.join(e,jr),r=await m.readFile(t,"utf-8");return Fr.parse(JSON.parse(r))}catch{return}},Wr=async()=>{try{const e=await Or(process.cwd(),$r);e&&await m.unlink(O.default.join(e,jr))}catch{}},Vr=e=>Date.now()>=e.expiresAt-3e5,qr=async e=>{const t=new URLSearchParams({client_id:Tr,grant_type:"refresh_token",refresh_token:e}),r=await fetch(`${Ir}/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}},Kr=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`,Jr=(e,t,r)=>{e.writeHead(t,{"Content-Type":"text/html"}),e.end(r)},Xr=(e,t)=>{const r=new URLSearchParams({client_id:Tr,code_challenge:e,code_challenge_method:"S256",redirect_uri:Cr,response_type:"code",state:t});return`${Ir}/propelauth/oauth/authorize?${r.toString()}`},Qr=async e=>{const t=y.spinner();let r;t.start("Loading user info...");try{r=Dr(e.accessToken),t.stop(H.default.green(`✓ Logged in as ${H.default.cyan(r.email)}`))}catch(e){t.stop(H.default.red("✗ Failed to load user info"));const r=e instanceof Error?e.message:"Unknown error";return y.log.error(r),{success:!1}}const n=await(async e=>{if(0===e.length)return void y.log.error("You don't belong to any organizations.");if(1===e.length)return y.log.info(`Using organization: ${H.default.cyan(e[0].name)}`),e[0];if(!process.stdin.isTTY)return y.log.info(`Auto-selecting organization: ${H.default.cyan(e[0].name)}`),e[0];const t=await y.select({message:"Select an organization",options:[...e].sort((e,t)=>e.name.localeCompare(t.name)).map(e=>({label:e.name,value:e.id}))});return y.isCancel(t)?void 0:e.find(e=>e.id===t)})(r.organizations);if(!n)return y.log.warn("Organization selection cancelled."),{success:!1};let s;t.start("Getting org credentials...");try{const r=await Pr(e.accessToken,n.id);s={accessToken:r.accessToken,expiresAt:Date.now()+1e3*r.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken},t.stop(H.default.green("✓ Credentials obtained"))}catch(e){t.stop(H.default.red("✗ Failed to get org credentials"));const r=e instanceof Error?e.message:"Unknown error";return y.log.error(r),{success:!1}}const o=await(async(e,t)=>{const r=y.spinner();let n;r.start("Loading projects...");try{n=await(async({accessToken:e,orgId:t})=>{const r=await(n={auth:e,client:Rr(),path:{orgId:t}},(n.client??wr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/orgs/{orgId}/projects",...n}));var n;if(401===r.response.status)throw new Error("Invalid or expired access token");if(403===r.response.status)throw new Error("You do not have access to this organization");if(r.error)throw new Error(`Failed to list projects: ${r.response.status}`);return r.data.projects})({accessToken:e,orgId:t}),r.stop(H.default.green("✓ Projects loaded"))}catch(e){r.stop(H.default.red("✗ Failed to load projects"));const t=e instanceof Error?e.message:"Unknown error";return void y.log.error(t)}if(0===n.length)return y.log.error("No projects found in this organization."),void y.log.info(`Create a project at ${H.default.underline(H.default.cyan("https://app.stably.ai"))}`);if(1===n.length)return y.log.info(`Using project: ${H.default.cyan(n[0].name)}`),n[0];if(!process.stdin.isTTY)return y.log.info(`Auto-selecting project: ${H.default.cyan(n[0].name)}`),n[0];const s=await y.select({message:"Select a project",options:n.map(e=>({label:e.name,value:e.id}))});return y.isCancel(s)?void 0:n.find(e=>e.id===s)})(s.accessToken,n.id);return o?(await(async e=>{const t=O.default.join(process.cwd(),$r),r=O.default.join(t,jr);await m.mkdir(t,{recursive:!0}),await m.writeFile(r,JSON.stringify(e,null,2)),await(async e=>{const t=O.default.join(e,".gitignore"),r="# Stably CLI (only docs/ are tracked)\n.stably/*\n!.stably/docs/";try{const e=await m.readFile(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 m.writeFile(t,n)}else if(o.test(e)){const n=e.replace(o,`\n${r}\n`);await m.writeFile(t,n)}else await m.appendFile(t,`\n${r}\n`)}catch{await m.writeFile(t,`${r}\n`)}})(process.cwd())})({orgId:n.id,orgName:n.name,projectId:o.id,projectName:o.name}),y.log.info(H.default.dim("Linked this directory to your Stably project.")),{scopedTokens:s,success:!0}):(y.log.warn("Project selection cancelled."),{success:!1})},Zr=async()=>{if(vn())return y.log.warn(`Environment variables ${H.default.cyan("STABLY_API_KEY")} and ${H.default.cyan("STABLY_PROJECT_ID")} are set.`),y.log.warn("These will be used for authentication instead of OAuth login."),y.log.warn("To use OAuth login, unset these environment variables first."),void y.outro(H.default.yellow("Login skipped - using environment variable authentication."));const e=await Hr();if(e){if(!Vr(e)){if(await Yr())return void y.outro(H.default.yellow("You are already logged in. Run `stably logout` first to log out."));y.log.info("You are logged in but haven't selected a project yet.");const t=await Qr(e);return void(t.success?(await Gr(t.scopedTokens),y.outro(H.default.green("Setup complete! You can now use Stably CLI."))):y.outro(H.default.yellow("Setup incomplete. Run `stably login` to try again.")))}const t=y.spinner();t.start("Refreshing session...");try{const r=await qr(e.refreshToken);t.stop(H.default.green("✓ Session refreshed"));const n=await Yr();if(n){t.start("Getting org credentials...");try{const e=await Pr(r.accessToken,n.orgId),s={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:r.idToken,refreshToken:r.refreshToken};await Gr(s),t.stop(H.default.green("✓ Credentials obtained")),y.outro(H.default.green("Login successful"))}catch{await Gr(r),t.stop(H.default.yellow("Using full credentials")),y.outro(H.default.green("Login successful"))}}else{const e=await Qr(r);e.success?(await Gr(e.scopedTokens),y.outro(H.default.green("Setup complete! You can now use Stably CLI."))):y.outro(H.default.yellow("Setup incomplete. Run `stably login` to try again."))}return}catch{t.stop(H.default.yellow("Session expired, proceeding with fresh login...")),await zr(),await Wr()}}const{authorizeUrl:t,serverReady:r,waitForCallback:n}=(()=>{const{authorizeUrl:e,codeVerifier:t,state:r}=(()=>{const e=F.default.randomBytes(32).toString("base64url"),t=(r=e,F.default.createHash("sha256").update(r).digest("base64url"));var r;const n=F.default.randomBytes(16).toString("base64url");return{authorizeUrl:Xr(t,n),codeVerifier:e,state:n}})(),{ready:n,result:s}=(e=>{let t,r;return{ready:new Promise((e,n)=>{t=e,r=n}),result:new Promise((n,s)=>{const o=setTimeout(()=>{c.close(),n({error:"Login timed out",success:!1})},3e5),i=()=>{clearTimeout(o)},c=W.default.createServer((t,r)=>{const s=new a.URL(t.url||"","http://localhost:9876");if("/auth/callback"!==s.pathname)return r.writeHead(404),void r.end("Not found");const o=s.searchParams.get("code"),l=s.searchParams.get("state"),u=s.searchParams.get("error");return u?(Jr(r,400,Kr(u)),i(),c.close(),void n({error:u,success:!1})):o&&l?l!==e?(Jr(r,400,Kr("Invalid state parameter (possible CSRF attack)")),i(),c.close(),void n({error:"State mismatch",success:!1})):(Jr(r,200,'\n<!DOCTYPE html>\n<html>\n<head>\n <title>Authenticated Stably CLI</title>\n <style>\n * { box-sizing: border-box; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, sans-serif;\n display: flex;\n justify-content: center;\n align-items: center;\n min-height: 100vh;\n margin: 0;\n background: #000;\n color: #fafafa;\n }\n .container {\n text-align: center;\n padding: 48px;\n max-width: 400px;\n }\n .icon {\n width: 48px;\n height: 48px;\n border-radius: 50%;\n background: #22c55e;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 24px;\n }\n .icon svg { width: 24px; height: 24px; }\n .title {\n font-size: 24px;\n font-weight: 600;\n margin: 0 0 8px;\n letter-spacing: -0.5px;\n }\n .subtitle {\n color: #888;\n font-size: 14px;\n margin: 0 0 32px;\n line-height: 1.5;\n }\n .terminal {\n background: #111;\n border: 1px solid #333;\n border-radius: 8px;\n padding: 16px;\n text-align: left;\n font-family: \'SF Mono\', \'Fira Code\', \'Consolas\', monospace;\n font-size: 13px;\n }\n .terminal-header {\n display: flex;\n gap: 6px;\n margin-bottom: 12px;\n }\n .terminal-dot {\n width: 10px;\n height: 10px;\n border-radius: 50%;\n background: #333;\n }\n .terminal-line {\n color: #888;\n }\n .terminal-line .prompt { color: #888; }\n .terminal-line .cmd { color: #fafafa; }\n .terminal-line.success { color: #22c55e; }\n .brand {\n margin-top: 32px;\n font-size: 12px;\n color: #444;\n letter-spacing: 0.5px;\n }\n </style>\n</head>\n<body>\n <div class="container">\n <div class="icon">\n <svg fill="none" stroke="#000" stroke-width="3" viewBox="0 0 24 24">\n <path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/>\n </svg>\n </div>\n <h1 class="title">Authenticated</h1>\n <p class="subtitle">You can close this tab and return to your terminal.</p>\n <div class="terminal">\n <div class="terminal-header">\n <div class="terminal-dot"></div>\n <div class="terminal-dot"></div>\n <div class="terminal-dot"></div>\n </div>\n <div class="terminal-line"><span class="prompt">$</span> <span class="cmd">stably login</span></div>\n <div class="terminal-line success">Logged in successfully</div>\n </div>\n <div class="brand">STABLY</div>\n </div>\n</body>\n</html>\n'),i(),c.close(),void n({code:o,state:l,success:!0})):(Jr(r,400,Kr("Missing code or state parameter")),i(),c.close(),void n({error:"Missing code or state parameter",success:!1}))});c.on("error",e=>{if(i(),"EADDRINUSE"===e.code){const e=new Error("Port 9876 is already in use. Please close the application using it and try again.");return r(e),void s(e)}const t=new Error(`Failed to start callback server: ${e.message}`);r(t),s(t)}),c.listen(9876,()=>{t()})})}})(r);return{authorizeUrl:e,serverReady:n,waitForCallback:async()=>{const e=await s;if(!e.success)throw new Error(e.error);return(async(e,t)=>{const r=new URLSearchParams({client_id:Tr,code:e,code_verifier:t,grant_type:"authorization_code",redirect_uri:Cr}),n=await fetch(`${Ir}/propelauth/oauth/token`,{body:r.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"},method:"POST"});if(!n.ok){const e=await n.text();throw new Error(`Token exchange failed: ${n.status} ${e}`)}const s=await n.json();return{accessToken:s.access_token,expiresAt:Date.now()+1e3*s.expires_in,idToken:s.id_token,refreshToken:s.refresh_token}})(e.code,t)}}})();await r,y.log.info("Opening browser for authentication..."),y.log.info(H.default.dim("If browser doesn't open, visit:")),y.log.info(`]8;;${t}${H.default.underline(H.default.cyan(t))}]8;;`);try{await Y.default(t)}catch{y.log.warn("Could not open browser automatically. Please open the URL above manually.")}const s=y.spinner();let o;s.start("Waiting for authentication...");try{o=await n(),s.stop(H.default.green("✓ Authentication successful"))}catch(e){s.stop(H.default.red("✗ Authentication failed"));const t=e instanceof Error?e.message:"Unknown error";y.outro(H.default.red(`Login failed: ${t}`)),process.exit(1)}const i=await Qr(o);i.success?(await Gr(i.scopedTokens),y.outro(H.default.green("Setup complete! You can now use Stably CLI."))):(y.outro(H.default.yellow("Setup incomplete. Run `stably login` to try again.")),process.exit(1))},en={fatal:60,error:50,warn:40,info:30,debug:20,trace:10},tn=new Set(["help","login","logout","whoami","tunnel","create","fix","init","upgrade","test","show-report","codegen"]),rn=(new Date).toISOString().split("T")[0],nn=O.default.join(j.default.tmpdir(),"stably-logs",rn);$.default.mkdirSync(nn,{recursive:!0});var sn,on=process.argv.includes("--verbose")||process.argv.includes("-v"),an=process.env.STABLY_LOG_LEVEL?.toLowerCase(),cn=on?"debug":void 0!==(sn=an)&&sn in en?an:"warn",ln=en[cn],un=null,dn=null,pn=null,fn=[],hn=!1,gn=e=>{if(!hn){un=(e=>{const t=(()=>{const e=new Date;return[e.getHours().toString().padStart(2,"0"),e.getMinutes().toString().padStart(2,"0"),e.getSeconds().toString().padStart(2,"0")].join("-")})(),r=((e,t=100)=>e.replace(/[/\\:*?"<>|]/g,"-").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9\-_]/g,"").replace(/-+/g,"-").replace(/^-+|-+$/g,"").slice(0,t).toLowerCase()||"session")(e);return O.default.join(nn,`${t}-${r}.log`)})(e),(e=>{const t=["","=".repeat(60),"Stably CLI Debug Log",`Version: ${vr}`,`Generated: ${(new Date).toISOString()}`,`Node: ${process.version}`,`Platform: ${process.platform} ${j.default.release()}`,`CWD: ${process.cwd()}`,`Args: ${process.argv.slice(2).join(" ")}`,`Log Level (console): ${cn}`,"=".repeat(60),""].join("\n");e.write(t)})(dn=new q.default({dest:un,minLength:4096,sync:!1,append:!0})),pn=V.default({level:"debug",timestamp:V.default.stdTimeFunctions.isoTime,base:{version:vr}},dn);for(const{level:e,msg:t,context:r}of fn)r?pn[e](r,t):pn[e](t);fn=[],hn=!0,on&&process.stderr.write(`${H.default.dim(`Debug log: ${un}`)}\n\n`)}},mn=(()=>{const e=process.argv.slice(2).find(e=>!e.startsWith("-"));return e&&tn.has(e)?e:null})();mn&&gn(mn);var yn=e=>(t,r)=>{if(pn?r?pn[e](r,t):pn[e](t):fn.push({level:e,msg:t,context:r}),(e=>en[e]>=ln)(e)){const r=((e,t)=>`${{fatal:H.default.bgRed(H.default.white(" FATAL ")),error:H.default.red("error"),warn:H.default.yellow("warn"),info:H.default.cyan("info"),debug:H.default.dim("debug"),trace:H.default.dim("trace")}[e]} ${t}`)(e,t);process.stderr.write(`${r}\n`)}},bn={fatal:yn("fatal"),error:yn("error"),warn:yn("warn"),info:yn("info"),debug:yn("debug"),trace:yn("trace"),initSession:e=>{hn||gn(e)},getLogFilePath:()=>un,flush:()=>{if(dn)try{dn.flushSync()}catch{}},printLogFileInfo:()=>{un&&(process.stderr.write(`\n${H.default.dim("Debug log written to:")}\n`),process.stderr.write(` ${H.default.cyan(un)}\n`),process.stderr.write(`${H.default.dim("Share this file with support for assistance.")}\n`))},getPinoLogger:()=>pn};setInterval(()=>{bn.flush()},3e4).unref(),process.on("beforeExit",()=>{bn.flush()});var wn=e=>{const t=()=>{bn.flush(),on&&bn.printLogFileInfo(),process.removeListener(e,t),process.kill(process.pid,e)};return t};process.on("SIGINT",wn("SIGINT")),process.on("SIGTERM",wn("SIGTERM"));var vn=()=>{const e=process.env.STABLY_API_KEY?.trim(),t=process.env.STABLY_PROJECT_ID?.trim();if(e&&t)return bn.debug("Environment auth detected",{hasApiKey:!0,hasProjectId:!0}),{apiKey:e,projectId:t};bn.debug("Environment auth not set",{hasApiKey:!!e,hasProjectId:!!t})},_n=!1,En=()=>{_n||(_n=!0,y.log.warn("Both environment variable auth and stored OAuth login were detected."),y.log.warn(`Honoring environment variables (${H.default.cyan("STABLY_API_KEY")} + ${H.default.cyan("STABLY_PROJECT_ID")}).`),y.log.warn("To use OAuth login instead, unset those environment variables."))},In=async()=>{bn.debug("Checking for stored auth tokens");const e=await Hr();if(!e)return void bn.debug("No stored auth tokens found");const t=Vr(e);if(bn.debug("Auth tokens status",{expired:t}),!t){const t=await Yr(),r=(e=>{try{const t=kr.parse(Lr(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(bn.debug("Token scope check",{scope:r,hasContext:!!t}),t&&"full"===r)try{bn.debug("Exchanging full token for org-scoped token",{orgId:t.orgId});const r=await Pr(e.accessToken,t.orgId),n={accessToken:r.accessToken,expiresAt:Date.now()+1e3*r.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken};return await Gr(n),bn.debug("Token exchange successful"),n}catch(t){return bn.debug("Token exchange failed, using existing token",{error:t instanceof Error?t.message:String(t)}),e}return e}try{bn.debug("Attempting token refresh");const t=await qr(e.refreshToken);bn.debug("Token refresh successful");const r=await Yr();if(r)try{bn.debug("Exchanging refreshed token for org-scoped token");const e=await Pr(t.accessToken,r.orgId),n={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:t.idToken,refreshToken:t.refreshToken};return await Gr(n),n}catch{return await Gr(t),t}return await Gr(t),t}catch(e){return void bn.warn("Token refresh failed",{error:e instanceof Error?e.message:String(e)})}},Tn=async(e={})=>{bn.debug("Requiring authentication",{autoLogin:e.autoLogin});const t=vn();if(t){bn.info("Using environment variable authentication");try{await Hr()&&En()}catch{}return{auth:t,type:"env"}}let r=await In(),n=r?await Yr():void 0;const s=process.stdin.isTTY&&process.stdout.isTTY;if(bn.debug("OAuth auth check",{hasTokens:!!r,hasContext:!!n,canPrompt:s}),(!r||!n)&&e.autoLogin&&s){bn.info("Prompting user to login"),r?y.log.info("You are logged in but need to select an organization and project."):y.log.info("You are not logged in."),y.log.info("Press Enter to log in."),process.stdout.write(`${H.default.dim("Alternatively, set environment variables for an org API key:")}\n${H.default.dim(" STABLY_API_KEY=... STABLY_PROJECT_ID=... stably")}\n`),process.stdout.write("\n");const e=b.createInterface({input:process.stdin,output:process.stdout});try{await e.question(H.default.dim("Press Enter to continue... "))}finally{e.close()}await Zr(),r=await In(),n=r?await Yr():void 0}return r||(bn.warn("Authentication required but no tokens available"),y.outro(H.default.red("You are not logged in. Run `stably login` to authenticate.")),process.exit(1)),n||(bn.warn("Authentication succeeded but no project context selected"),y.outro(H.default.red("You haven't selected an organization and project. Run `stably login` to complete setup.")),process.exit(1)),bn.info("OAuth authentication successful",{orgId:n.orgId,projectId:n.projectId}),{auth:{accessToken:r.accessToken,context:n},type:"oauth"}},xn=e=>"env"===e.type?e.auth.projectId:e.auth.context.projectId,Sn=e=>e?{...process.env,...e}:process.env,An=async()=>{bn.info("[test] Resolving Stably test env");const e=(()=>{if(process.env.STABLY_WS_URL)return;if("https://api.stably.ai"===_r)return;const e=_r.startsWith("http://")?"ws://":"wss://";return`${_r.replace(/^https?:\/\//,e).replace(/\/$/,"")}/reporter`})();bn.debug("[test] WebSocket URL resolved",{wsUrl:e??"(default)"});const t=vn();if(t)return bn.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}};bn.info("[test] No env var auth, attempting OAuth auth");const r=Date.now(),n=await(async()=>{const e=vn();if(e){try{await Hr()&&En()}catch{}return{auth:e,type:"env"}}const t=await In(),r=t?await Yr():void 0;if(t&&r)return{auth:{accessToken:t.accessToken,context:r},type:"oauth"}})();if(bn.info("[test] OAuth auth resolved",{durationMs:Date.now()-r,hasAuth:!!n,authType:n?.type}),!n||"env"===n.type)return void bn.info("[test] No usable auth found");const s=process.env.STABLY_PROJECT_ID?.trim(),o=s||xn(n);if(!o)return void bn.warn("[test] No project ID available");bn.info("[test] Fetching JWT API key",{projectId:o});const i=Date.now(),a=await(async(e,t)=>{try{bn.debug("Requesting JWT API key",{projectId:t,apiUrl:_r});const r=await(async({accessToken:e,projectId:t})=>{const r=await(n={auth:e,client:Rr(),path:{projectId:t}},(n.client??wr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/api-key",...n}));var n;if(r.error){const e=r.error?.error,{status:t}=r.response;throw new Error(e??`Failed to get API key: ${t}`)}return r.data})({accessToken:e,projectId:t});return bn.debug("JWT API key obtained",{keyPrefix:r.apiKey.substring(0,10)}),r.apiKey}catch(e){return void bn.warn("Failed to get JWT API key for test reporter",{error:e instanceof Error?e.message:String(e)})}})(n.auth.accessToken,o);bn.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 bn.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},Cn=e=>e?{[Zt]:e}:void 0,Rn=w.z.object({context:w.z.string().min(1),autohealReportUrl:w.z.string()}),Pn=T.z.object({bucket:T.z.string(),key:T.z.string()}),Un=T.z.object({diffBucketPath:Pn,expiresInSeconds:T.z.number(),key:T.z.string(),uploadUrl:T.z.string()}),kn=T.z.object({traceBucketPath:Pn,expiresInSeconds:T.z.number(),key:T.z.string(),uploadUrl:T.z.string(),sensitiveValues:T.z.array(T.z.string())}),Ln=async({authHeader:e,contentType:t="text/plain",orgId:r,runId:n})=>{const s=await(o={auth:e,body:{contentType:t},client:Rr(),headers:Cn(r),path:{runId:n}},(o.client??wr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-diff/upload-url",...o,headers:{"Content-Type":"application/json",...o.headers}}));var o;if(s.error)throw new Error(`Failed to presign diff upload (${s.response.status})`);const i=Un.parse(s.data);return{diffBucketPath:i.diffBucketPath,expiresInSeconds:i.expiresInSeconds,key:i.key,uploadUrl:i.uploadUrl}},Dn=async({contentType:e="text/plain",diff:t,uploadUrl:r})=>{const n=await fetch(r,{body:t,headers:{"Content-Type":e},method:"PUT"});if(!n.ok)throw new Error(`Failed to upload diff (${n.status})`)},On=async({authHeader:e,diffBucketPath:t,orgId:r,runId:n})=>{const s=(Rr().getConfig().baseUrl??"").replace(/\/$/,""),o=await fetch(`${s}/internal/v1/cli/runs/${encodeURIComponent(n)}/autoheal-diff/confirm-upload`,{method:"POST",headers:{"Content-Type":"application/json",...Cn(r),authorization:e},body:JSON.stringify(t)});if(!o.ok)throw new Error(`Failed to confirm diff upload (${o.status})`)},Bn=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=Sr,onUserMessage:s}){this.authHeader=e,this.orgId=t,this.runId=r,this.url=n,this.onUserMessage=s,bn.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)}`;bn.info("[ws] Connecting",{url:t,attempt:this.reconnectAttempts}),this.socket=new K.default(t,{headers:e}),this.socket.on("open",()=>{bn.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);bn.debug("[ws] Received message",{type:r?.type}),"connected"===r?.type&&(bn.info("[ws] Authenticated successfully"),this.isAuthenticated=!0,this.authenticationFailed=!1,this.flushPending()),"user_message"===r?.type&&"string"==typeof r.content&&(bn.info("[ws] Received user message from web UI"),this.onUserMessage?.(r.content))}catch{}}),this.socket.on("close",(e,t)=>{bn.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=>{bn.warn("[ws] Connection error",{error:e.message})})}catch(e){bn.warn("[ws] Failed to create WebSocket",{error:e instanceof Error?e.message:String(e)}),this.scheduleReconnect()}}scheduleReconnect(){this._isClosed||this.reconnectTimer||(this.reconnectAttempts++,bn.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===K.default.OPEN&&this.isAuthenticated}sendProgress(e){if(this._isClosed)return void bn.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?(bn.info("[ws] sendProgress: flushing terminal state immediately"),void this.flushPending()):void(this.debounceTimer||(this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.flushPending()},this.debounceMs))):(bn.debug("[ws] sendProgress: not connected, queuing event",{phase:e.phase,socketState:this.socket?.readyState,isAuthenticated:this.isAuthenticated,reconnectAttempts:this.reconnectAttempts}),void(this.socket?.readyState===K.default.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 bn.debug("[ws] flushPending: not connected, re-queuing event",{phase:e.payload.phase}),void(this.pendingEvent=e);try{bn.debug("[ws] flushPending: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),t=>{t&&(bn.warn("[ws] flushPending: send failed",{error:t.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e))})}catch(t){bn.warn("[ws] flushPending: send threw",{error:t instanceof Error?t.message:String(t)}),this.pendingEvent=e}}close(){if(this._isClosed)return;bn.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)}},Nn=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=Ar,onUserMessage:s}){this.authHeader=e,this.orgId=t,this.sessionId=r,this.url=n,this.onUserMessage=s,bn.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)}`;bn.info("[ws] Connecting",{url:t,attempt:this.reconnectAttempts}),this.socket=new K.default(t,{headers:e}),this.socket.on("open",()=>{bn.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);bn.debug("[ws] Received message",{type:r?.type}),"connected"===r?.type&&(bn.info("[ws] Authenticated successfully"),this.isAuthenticated=!0,this.authenticationFailed=!1,this.flushPending()),"user_message"===r?.type&&"string"==typeof r.content&&(bn.info("[ws] Received user message from web UI"),this.onUserMessage?.(r.content))}catch{}}),this.socket.on("close",(e,t)=>{bn.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=>{bn.warn("[ws] Connection error",{error:e.message})})}catch(e){bn.warn("[ws] Failed to create WebSocket",{error:e instanceof Error?e.message:String(e)}),this.scheduleReconnect()}}scheduleReconnect(){this._isClosed||this.reconnectTimer||(this.reconnectAttempts++,bn.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===K.default.OPEN&&this.isAuthenticated}sendProgress(e){if(this._isClosed)return void bn.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?(bn.info("[ws] sendProgress: flushing terminal state immediately"),void this.flushPending()):void(this.debounceTimer||(this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.flushPending()},this.debounceMs))):(bn.debug("[ws] sendProgress: not connected, queuing event",{phase:e.phase,socketState:this.socket?.readyState,isAuthenticated:this.isAuthenticated,reconnectAttempts:this.reconnectAttempts}),void(this.socket?.readyState===K.default.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 bn.debug("[ws] flushPending: not connected, re-queuing event",{phase:e.payload.phase}),void(this.pendingEvent=e);try{bn.debug("[ws] flushPending: sending event",{phase:e.payload.phase}),this.socket?.send(JSON.stringify(e),t=>{t&&(bn.warn("[ws] flushPending: send failed",{error:t.message,phase:e.payload.phase}),this.pendingEvent||(this.pendingEvent=e))})}catch(t){bn.warn("[ws] flushPending: send threw",{error:t instanceof Error?t.message:String(t)}),this.pendingEvent=e}}close(){if(this._isClosed)return;bn.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)}},$n=/\.(spec|test)\.(c|m)?[jt]sx?$/,jn=e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"text"===t.type&&"string"==typeof t.text},Mn=e=>null!=e&&"object"==typeof e&&"tool_response"in e,Fn=e=>{if(!e||"object"!=typeof e)return;const t=e;return Array.isArray(t.tool_response)?t.tool_response:void 0},Hn=e=>{const t=Fn(e);if(t)return t.filter(jn).map(e=>e.text).join("\n")||void 0},Gn=/\u001b\[[0-9;]*m/g,zn=e=>e.replace(Gn,""),Yn=/\$\{process\.env\.([A-Z_][A-Z0-9_]*)\}/g;function Wn({envVars:e}){return async t=>{if(!function(e){return Boolean(e&&"object"==typeof e&&"tool_input"in e&&e.tool_input&&"object"==typeof e.tool_input)}(t))return{decision:"approve"};const r=t.tool_input,n="string"==typeof r.text?r.text:void 0;if(!n)return{decision:"approve"};const s=n.replace(Yn,(t,r)=>{const n=e[r];return null!=n?n:t});return s===n?{decision:"approve"}:{decision:"approve",hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",reason:"Evaluated environment variable placeholders in browser text input.",updatedInput:{...r,text:s}}}}}function Vn({onResult:e}){return async t=>{if(!Mn(t))return{decision:"approve"};const r=Hn(t);if(!r)return{decision:"approve"};const n=function(e){const t=zn(e),r=t.split(/Running \d+ tests? using \d+ workers?/).at(-1)??t,n=parseInt(r.match(/(\d+)\s+passed/g)?.at(-1)?.match(/(\d+)/)?.[1]??"0"),s=parseInt(r.match(/(\d+)\s+failed/g)?.at(-1)?.match(/(\d+)/)?.[1]??"0");if(0===n&&0===s)return;const o=[n>0?`${n} test${1===n?"":"s"} passed ✓`:void 0,s>0?`${s} test${1===s?"":"s"} failed ✗`:void 0].filter(e=>void 0!==e).join(", ");if(0===s)return o;const i=r.split(/\n\s+\d+\)\s+\[id=/).slice(1).map(e=>e.match(/\n\s{4}((?:TimeoutError|Error|AssertionError):\s*[^\n]+)/)?.[1]?.trim()).filter(e=>void 0!==e);return 0===i.length?o:`${o}\n${i.map(e=>` - ${e}`).join("\n")}`}(r);return n&&e(n),{decision:"approve"}}}function qn({onResult:e}){return async t=>{if(!Mn(t))return{decision:"approve"};const r=Hn(t);if(!r)return{decision:"approve"};const n=function(e){const t=zn(e);if(t.match(/### Paused on error:/)){const e=t.match(/### Paused on error:\s*\n((?:TimeoutError|Error|AssertionError):\s*[^\n]+)/);return e?`Test paused on error - ${e[1].trim()}`:"Test paused on error"}const r=t.match(/(\d+)\s+passed/);if(r){const e=parseInt(r[1]);return`${e} test${1===e?"":"s"} passed ✓`}}(r);return n&&e(n),{decision:"approve"}}}var Kn=/\.(spec|test)\.(ts|tsx|js|jsx|mts|mjs)$/;function Jn({onFileCreated:e}){return async t=>{const r=(e=>{if(!e||"object"!=typeof e)return;const t=e;return t.tool_input&&"object"==typeof t.tool_input&&!Array.isArray(t.tool_input)?t.tool_input:void 0})(t),n=r?.file_path;return"string"==typeof n&&Kn.test(n)&&e(n),{decision:"approve"}}}var Xn=u.promisify(s.exec);async function Qn(){try{const{stdout:e}=await Xn('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 Xn(`pkill -KILL -P ${e} '.*' 2>/dev/null || true`)}))}catch{}}var Zn="sha256",es=/^---\r?\n([\s\S]*?)\r?\n---/;function ts(e){const t=e.replace(es,"").replace(/^(\r?\n)+/,""),r=F.default.createHash(Zn).update(t,"utf8").digest("hex");return`${Zn}:${r}`}function rs(e){const t=e.match(/^\/\*\*[\s\S]*?@prompt-hash\s+(sha256:[a-f0-9]{64})[\s\S]*?\*\//);return t?.[1]}function ns({builtAt:e=new Date,promptFile:t,promptHash:r}){const n=Array.isArray(t)?t:[t],s=n[0]??"unknown",o=e.toISOString();return["/**"," * @generated by stably build",` * @prompt-hash ${r}`,...n.map(e=>` * @prompt-file ${e}`),` * @built-at ${o}`," *",` * DO NOT EDIT MANUALLY - regenerate with: stably build ${s} --force`," */"].join("\n")}function ss({workDir:e}){return async r=>{if(null==(n=r)||"object"!=typeof n||!("file_path"in n)||"string"!=typeof n.file_path)return{};var n;const s=r.file_path;if(!/\.(spec|test)\.[jt]sx?$/.test(s))return{};const o=t.resolve(e,s);if(!o.startsWith(t.resolve(e)+t.sep))return console.error(`[PromptHash Hook] Path traversal attempt blocked: ${s}`),{};let i;try{i=await m.readFile(o,"utf-8")}catch(e){return console.error(`[PromptHash Hook] Error reading ${s}:`,e),{}}const a=function(e){const t=e.match(/\/\/\s*@stably\.spec\s+(\S+)/);return t?.[1]}(i);if(!a)return{};const c=t.resolve(e,a);if(!c.startsWith(t.resolve(e)+t.sep))return console.error(`[PromptHash Hook] Path traversal attempt blocked: ${a}`),{};let l;try{l=await m.readFile(c,"utf-8")}catch{return{}}const u=ts(l);if(rs(i)===u)return{};const d=ns({promptHash:u,promptFile:a});let p;const f=i.match(/\/\*\*[\s\S]*?@prompt-hash[\s\S]*?\*\/\n?/);p=f?i.replace(f[0],`${d}\n`):`${d}\n${i}`;try{await m.writeFile(o,p,"utf-8")}catch(e){console.error(`[PromptHash Hook] Error writing ${s}:`,e)}return{}}}var os=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 is(e){try{const t=s.execSync("git branch --show-current",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(!t)return;return{branch:t}}catch{return}}var as=[".ts",".js",".mts",".mjs",".cts",".cjs"],cs=10240,ls=async({defaultContent:e,fileName:t,filePath:r})=>{try{const e=(await m.stat(r)).size,n=await m.readFile(r,"utf-8"),s=Buffer.byteLength(n,"utf-8");if(s<=cs)return n;const o=(e=>{const t=e.split("\n"),r=[];let n=!1,s=!1,o=0,i=!1;for(let e=0;e<t.length;e++){const a=t[e],c=a.trim();c.startsWith("/*")&&(n=!0),c.includes("*/")?n=!1:n||c.startsWith("//")&&!c.startsWith("///")||(c.startsWith("import ")||c.startsWith("export ")?(r.push(a),i=!0):i&&""===c?(r.push(a),i=!1):(i=!1,c.startsWith("type ")||c.startsWith("interface ")?r.push(a):c.startsWith("function ")||c.startsWith("const ")||c.startsWith("async function ")||c.startsWith("export function ")||c.startsWith("export const ")||c.startsWith("test.describe(")||c.startsWith("test(")?(r.push(a),s=!0,o=(a.match(/{/g)||[]).length-(a.match(/}/g)||[]).length,0===o&&(c.endsWith(";")||c.endsWith(","))&&(s=!1)):s?(o+=(a.match(/{/g)||[]).length,o-=(a.match(/}/g)||[]).length,0===o&&c.includes("}")?(r.push(a),s=!1):o>0&&" // ... implementation omitted ..."!==r.at(-1)&&r.push(" // ... implementation omitted ...")):c.match(/^[a-zA-Z_]+:/)&&r.push(a)))}return r.join("\n")})(n),i=Buffer.byteLength(o,"utf-8");return i<=cs?o:o.slice(0,cs)+`\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}},us=async({defaultContent:e,dirName:t,dirPath:r})=>{try{const e=await m.readdir(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}},ds=async({allowedEnvVars:e,mode:t,workspaceInfo:r,authHeader:n,customHeader:s,maxParallelWorkers:o})=>{const i=Rr(),a=is(r.absolutePath);bn.debug("Requesting system prompt from API",{mode:t,hasGitContext:!!a,envVarCount:e.length});const c=await(l={client:i,auth:n,body:{mode:t,workspaceInfo:r,allowedEnvVars:e,gitContext:a,maxParallelWorkers:o}},(l.client??wr).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 bn.warn("System prompt fetch failed: unauthorized (401)"),await zr(),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 bn.warn("System prompt fetch failed: forbidden (403)"),await zr(),new Error("You no longer have access to this organization. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(c.error)throw bn.warn("System prompt fetch failed",{error:c.error}),new Error(`Failed to fetch system prompt: ${JSON.stringify(c.error)}`);const u=function({customHeader:e,systemPrompt:t}){return e?`${t}\n\nWhen writing or updating the generated test file, prepend this exact header at the top of the file without modification:\n\`\`\`ts\n${e}\n\`\`\``:t}({systemPrompt:c.data.systemPrompt,customHeader:s});return bn.debug("System prompt received",{size:u.length,appendedCustomHeader:!!s,hasPrContext:!!c.data.prContext}),{systemPrompt:u,prContext:c.data.prContext}},ps=".stably-playwright-wrapper.config.*",fs=[".ts",".js",".mts",".mjs",".cts",".cjs"];function hs(e){const r=t.resolve(e);if(i.existsSync(r))for(const e of fs){const n=t.join(r,`playwright.config${e}`);if(i.existsSync(n))return n}}var gs=["tests","e2e","__tests__","test"];function ms(e){try{return i.existsSync(e)&&i.statSync(e).isDirectory()}catch{return!1}}function ys(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(H.default.dim(`Using output directory: ${e} (from ${r})`))}var bs,ws=["mcp__playwright-test__","mcp__auto-heal-report__","mcp__test-doc-sync__","mcp__stably-agent-control__"],vs=["planner_","generator_"],_s={"mcp__stably-agent-control__restart_mcp_servers":"Restarting Browser Tools","mcp__session-control__restart_mcp_servers":"Restarting Browser Tools"},Es=(e,t)=>{const r=t.find(t=>e.startsWith(t));return r?e.slice(r.length):e},Is=e=>{const t=_s[e];if(t)return t;const r=Es(e,ws);return Es(r,vs).split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")},Ts=(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},xs=["test","bug","other"],Ss={bug:"Application code defect; behavior diverges from expected requirements.",other:"External dependencies, environment, or infra issues outside test/app code.",test:"Test code is incorrect, out-of-date, or missing necessary setup."},As=e=>Ss[e],Cs=/[^a-zA-Z0-9-_]/g,Rs=e=>{const t=e.trim().replace(Cs,"_");return t.length>0?t.slice(0,80):void 0},Ps=e=>"string"==typeof e?Rs(e):void 0,Us=((e,t,r)=>(r=null!=e?J(ee(e)):{},((e,t,r,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let r of Z(t))te.call(e,r)||void 0===r||X(e,r,{get:()=>t[r],enumerable:!(n=Q(t,r))||n.enumerable});return e})(X(r,"default",{value:e,enumerable:!0}),e)))(ne()),ks=C.createRequire("/");try{bs=ks("worker_threads").Worker}catch(e){}var Ls=bs?function(e,t,r,n,s){var o=!1,i=new bs(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,bs.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}},Ds=Uint8Array,Os=Uint16Array,Bs=Int32Array,Ns=new Ds([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 Ds([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]),js=new Ds([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ms=function(e,t){for(var r=new Os(31),n=0;n<31;++n)r[n]=t+=1<<e[n-1];var s=new Bs(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}},Fs=Ms(Ns,2),Hs=Fs.b,Gs=Fs.r;Hs[28]=258,Gs[258]=28;var zs,Ys=Ms($s,0),Ws=Ys.b,Vs=Ys.r,qs=new Os(32768);for(Xs=0;Xs<32768;++Xs)zs=(61680&(zs=(52428&(zs=(43690&Xs)>>1|(21845&Xs)<<1))>>2|(13107&zs)<<2))>>4|(3855&zs)<<4,qs[Xs]=((65280&zs)>>8|(255&zs)<<8)>>1;var Ks=function(e,t,r){for(var n=e.length,s=0,o=new Os(t);s<n;++s)e[s]&&++o[e[s]-1];var i,a=new Os(t);for(s=1;s<t;++s)a[s]=a[s-1]+o[s-1]<<1;if(r){i=new Os(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[qs[d]>>c]=l}else for(i=new Os(n),s=0;s<n;++s)e[s]&&(i[s]=qs[a[e[s]-1]++]>>15-e[s]);return i},Js=new Ds(288);for(Xs=0;Xs<144;++Xs)Js[Xs]=8;for(Xs=144;Xs<256;++Xs)Js[Xs]=9;for(Xs=256;Xs<280;++Xs)Js[Xs]=7;for(Xs=280;Xs<288;++Xs)Js[Xs]=8;var Xs,Qs=new Ds(32);for(Xs=0;Xs<32;++Xs)Qs[Xs]=5;var Zs=Ks(Js,9,0),eo=Ks(Js,9,1),to=Ks(Qs,5,0),ro=Ks(Qs,5,1),no=function(e){for(var t=e[0],r=1;r<e.length;++r)e[r]>t&&(t=e[r]);return t},so=function(e,t,r){var n=t/8|0;return(e[n]|e[n+1]<<8)>>(7&t)&r},oo=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(7&t)},io=function(e){return(e+7)/8|0},ao=function(e,t,r){return(null==t||t<0)&&(t=0),(null==r||r>e.length)&&(r=e.length),new Ds(e.subarray(t,r))},co=["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"],lo=function(e,t,r){var n=new Error(t||co[e]);if(n.code=e,Error.captureStackTrace&&Error.captureStackTrace(n,lo),!r)throw n;return n},uo=function(e,t,r,n){var s=e.length,o=n?n.length:0;if(!s||t.f&&!t.l)return r||new Ds(0);var i=!r,a=i||2!=t.i,c=t.i;i&&(r=new Ds(3*s));var l=function(e){var t=r.length;if(e>t){var n=new Ds(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=so(e,d,1);var b=so(e,d+1,3);if(d+=3,!b){var w=e[(P=io(d)+4)-4]|e[P-3]<<8,v=P+w;if(v>s){c&&lo(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=eo,h=ro,g=9,m=5;else if(2==b){var _=so(e,d,31)+257,E=so(e,d+10,15)+4,I=_+so(e,d+5,31)+1;d+=14;for(var T=new Ds(I),x=new Ds(19),S=0;S<E;++S)x[js[S]]=so(e,d+3*S,7);d+=3*E;var A=no(x),C=(1<<A)-1,R=Ks(x,A,1);for(S=0;S<I;){var P,U=R[so(e,d,C)];if(d+=15&U,(P=U>>4)<16)T[S++]=P;else{var k=0,L=0;for(16==P?(L=3+so(e,d,3),d+=2,k=T[S-1]):17==P?(L=3+so(e,d,7),d+=3):18==P&&(L=11+so(e,d,127),d+=7);L--;)T[S++]=k}}var D=T.subarray(0,_),O=T.subarray(_);g=no(D),m=no(O),f=Ks(D,g,1),h=Ks(O,m,1)}else lo(1);if(d>y){c&&lo(0);break}}a&&l(p+131072);for(var B=(1<<g)-1,N=(1<<m)-1,$=d;;$=d){var j=(k=f[oo(e,d)&B])>>4;if((d+=15&k)>y){c&&lo(0);break}if(k||lo(2),j<256)r[p++]=j;else{if(256==j){$=d,f=null;break}var M=j-254;if(j>264){var F=Ns[S=j-257];M=so(e,d,(1<<F)-1)+Hs[S],d+=F}var H=h[oo(e,d)&N],G=H>>4;if(H||lo(3),d+=15&H,O=Ws[G],G>3&&(F=$s[G],O+=oo(e,d)&(1<<F)-1,d+=F),d>y){c&&lo(0);break}a&&l(p+131072);var z=p+M;if(p<O){var Y=o-O,W=Math.min(O,z);for(Y+p<0&&lo(3);p<W;++p)r[p]=n[Y+p]}for(;p<z;++p)r[p]=r[p-O]}}t.l=f,t.p=$,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?ao(r,0,p):r.subarray(0,p)},po=function(e,t,r){r<<=7&t;var n=t/8|0;e[n]|=r,e[n+1]|=r>>8},fo=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},ho=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:_o,l:0};if(1==s){var i=new Ds(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 Os(p+1),h=go(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 Ds(f),l:h}},go=function(e,t,r){return-1==e.s?Math.max(go(e.l,t,r+1),go(e.r,t,r+1)):t[e.s]=r},mo=function(e){for(var t=e.length;t&&!e[--t];);for(var r=new Os(++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}},yo=function(e,t){for(var r=0,n=0;n<t.length;++n)r+=e[n]*t[n];return r},bo=function(e,t,r){var n=r.length,s=io(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)},wo=function(e,t,r,n,s,o,i,a,c,l,u){po(t,u++,r),++s[256];for(var d=ho(s,15),p=d.t,f=d.l,h=ho(o,15),g=h.t,m=h.l,y=mo(p),b=y.c,w=y.n,v=mo(g),_=v.c,E=v.n,I=new Os(19),T=0;T<b.length;++T)++I[31&b[T]];for(T=0;T<_.length;++T)++I[31&_[T]];for(var x=ho(I,7),S=x.t,A=x.l,C=19;C>4&&!S[js[C-1]];--C);var R,P,U,k,L=l+5<<3,D=yo(s,Js)+yo(o,Qs)+i,O=yo(s,p)+yo(o,g)+i+14+3*C+yo(I,S)+2*I[16]+3*I[17]+7*I[18];if(c>=0&&L<=D&&L<=O)return bo(t,u,e.subarray(c,c+l));if(po(t,u,1+(O<D)),u+=2,O<D){R=Ks(p,f,0),P=p,U=Ks(g,m,0),k=g;var B=Ks(S,A,0);for(po(t,u,w-257),po(t,u+5,E-1),po(t,u+10,C-4),u+=14,T=0;T<C;++T)po(t,u+3*T,S[js[T]]);u+=3*C;for(var N=[b,_],$=0;$<2;++$){var j=N[$];for(T=0;T<j.length;++T){var M=31&j[T];po(t,u,B[M]),u+=S[M],M>15&&(po(t,u,j[T]>>5&127),u+=j[T]>>12)}}}else R=Zs,P=Js,U=to,k=Qs;for(T=0;T<a;++T){var F=n[T];if(F>255){fo(t,u,R[257+(M=F>>18&31)]),u+=P[M+257],M>7&&(po(t,u,F>>23&31),u+=Ns[M]);var H=31&F;fo(t,u,U[H]),u+=k[H],H>3&&(fo(t,u,F>>5&8191),u+=$s[H])}else fo(t,u,R[F]),u+=P[F]}return fo(t,u,R[256]),u+P[256]},vo=new Bs([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),_o=new Ds(0),Eo=function(e,t,r,n,s,o){var i=o.z||e.length,a=new Ds(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=vo[t-1],p=d>>13,f=8191&d,h=(1<<r)-1,g=o.p||new Os(32768),m=o.h||new Os(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 Bs(25e3),_=new Os(288),E=new Os(32),I=0,T=0,x=o.i||0,S=0,A=o.w||0,C=0;x+2<i;++x){var R=w(x),P=32767&x,U=m[R];if(g[P]=U,m[R]=P,A<=x){var k=i-x;if((I>7e3||S>24576)&&(k>423||!l)){u=wo(e,c,0,v,_,E,T,S,C,x-C,u),S=I=T=0,C=x;for(var L=0;L<286;++L)_[L]=0;for(L=0;L<30;++L)E[L]=0}var D=2,O=0,B=f,N=P-U&32767;if(k>2&&R==w(x-N))for(var $=Math.min(p,k)-1,j=Math.min(32767,x),M=Math.min(258,k);N<=j&&--B&&P!=U;){if(e[x+D]==e[x+D-N]){for(var F=0;F<M&&e[x+F]==e[x+F-N];++F);if(F>D){if(D=F,O=N,F>$)break;var H=Math.min(N,F-2),G=0;for(L=0;L<H;++L){var z=x-N+L&32767,Y=z-g[z]&32767;Y>G&&(G=Y,U=z)}}}N+=(P=U)-(U=g[P])&32767}if(O){v[S++]=268435456|Gs[D]<<18|Vs[O];var W=31&Gs[D],V=31&Vs[O];T+=Ns[W]+$s[V],++_[257+W],++E[V],A=x+D,++I}else v[S++]=e[x],++_[e[x]]}}for(x=Math.max(x,A);x<i;++x)v[S++]=e[x],++_[e[x]];u=wo(e,c,l,v,_,E,T,S,C,x-C,u),l||(o.r=7&u|c[u/8|0]<<3,u-=7,o.h=m,o.p=g,o.i=x,o.w=A)}else{for(x=o.w||0;x<i+l;x+=65535){var q=x+65535;q>=i&&(c[u/8|0]=l,q=i),u=bo(c,u+1,e.subarray(x,q))}o.i=i}return ao(a,0,n+io(u)+s)},Io=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}(),To=function(e,t,r,n,s){if(!s&&(s={l:1},t.dictionary)){var o=t.dictionary.subarray(-32768),i=new Ds(o.length+e.length);i.set(o),i.set(e,o.length),e=i,s.w=o.length}return Eo(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)},xo=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},So=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},Ao=[],Co=function(){return[Ds,Os,Bs,Ns,$s,js,Hs,Ws,eo,ro,qs,co,Ks,no,so,oo,io,ao,lo,uo,$o,Po,Uo]},Ro=function(){return[Ds,Os,Bs,Ns,$s,js,Gs,Vs,Zs,Js,to,Qs,qs,vo,_o,Ks,po,fo,ho,go,mo,yo,bo,wo,io,ao,Eo,To,No,Po]},Po=function(e){return postMessage(e,[e.buffer])},Uo=function(e){return e&&{out:e.size&&new Ds(e.size),dictionary:e.dictionary}},ko=function(e,t,r,n,s,o){var i=function(e,t,r,n){if(!Ao[r]){for(var s="",o={},i=e.length-1,a=0;a<i;++a)s=So(e[a],s,o);Ao[r]={c:So(e[i],s,o),e:o}}var c=xo({},Ao[r].e);return Ls(Ao[r].c+";onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage="+t.toString()+"}",r,c,function(e){var t=[];for(var r in e)e[r].buffer&&t.push((e[r]=new e[r].constructor(e[r])).buffer);return t}(c),n)}(r,n,s,function(e,t){i.terminate(),o(e,t)});return i.postMessage([e,t],t.consume?[e.buffer]:[]),function(){i.terminate()}},Lo=function(e,t){return e[t]|e[t+1]<<8},Do=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},Oo=function(e,t){return Do(e,t)+4294967296*Do(e,t+4)},Bo=function(e,t,r){for(;r;++t)e[t]=r,r>>>=8};function No(e,t){return To(e,t||{},0,0)}function $o(e,t){return uo(e,{i:2},t&&t.out,t&&t.dictionary)}var jo=function(e,t,r,n){for(var s in e){var o=e[s],i=t+s,a=n;Array.isArray(o)&&(a=xo(n,o[1]),o=o[0]),o instanceof Ds?r[i]=[o,a]:(r[i+="/"]=[new Ds(0),a],jo(o,i,r,n))}},Mo="undefined"!=typeof TextEncoder&&new TextEncoder,Fo="undefined"!=typeof TextDecoder&&new TextDecoder;try{Fo.decode(_o,{stream:!0})}catch(e){}function Ho(e,t){if(Mo)return Mo.encode(e);for(var r=e.length,n=new Ds(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 Ds(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 ao(n,0,s)}var Go=function(e){var t=0;if(e)for(var r in e){var n=e[r].length;n>65535&&lo(9),t+=n+4}return t},zo=function(e,t,r,n,s,o,i,a){var c=n.length,l=r.extra,u=a&&a.length,d=Go(l);Bo(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)&&lo(10),Bo(e,t,f<<25|p.getMonth()+1<<21|p.getDate()<<16|p.getHours()<<11|p.getMinutes()<<5|p.getSeconds()>>1),t+=4,-1!=o&&(Bo(e,t,r.crc),Bo(e,t+4,o<0?-o-2:o),Bo(e,t+8,r.size)),Bo(e,t+12,c),Bo(e,t+14,d),t+=16,null!=i&&(Bo(e,t,u),Bo(e,t+6,r.attrs),Bo(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;Bo(e,t,+h),Bo(e,t+2,m),e.set(g,t+4),t+=4+m}return u&&(e.set(a,t),t+=u),t},Yo="function"==typeof queueMicrotask?queueMicrotask:"function"==typeof setTimeout?setTimeout:function(e){e()},Wo=[/^\/$/,/^\*+$/,/^[0-9]+$/],Vo=["/artifact/","https://","http://","*********"],qo=new Set(["sha1","_sha1","pageref","downloadsPath","tracesDir","pageId"]);function Ko({sensitiveValues:e,str:t}){return e.reduce((e,t)=>e.replaceAll(t,"[REDACTED]"),t)}function Jo({sensitiveValues:e,value:t}){return"string"==typeof t?Ko({sensitiveValues:e,str:t}):Array.isArray(t)?t.map(t=>Jo({sensitiveValues:e,value:t})):function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(t)?Qo({obj:t,sensitiveValues:e}):t}function Xo(e){return!!qo.has(e)||e.toLowerCase().endsWith("sha1")}function Qo({obj:e,sensitiveValues:t}){return Object.fromEntries(Object.entries(e).map(([e,r])=>[e,Xo(e)?r:Jo({sensitiveValues:t,value:r})]))}function Zo({error:e,sensitiveValues:t}){return e?{...e,message:Ko({sensitiveValues:t,str:e.message})}:void 0}function ei({content:e,sensitiveValues:t}){const r=new u.TextDecoder,n=new u.TextEncoder,s=Ko({sensitiveValues:t,str:r.decode(e)});return n.encode(s)}var ti=u.promisify(function(e,t,r){r||(r=t,t={}),"function"!=typeof r&&lo(7);var n=[],s=function(){for(var e=0;e<n.length;++e)n[e]()},o={},i=function(e,t){Yo(function(){r(e,t)})};Yo(function(){i=r});for(var a=e.length-22;101010256!=Do(e,a);--a)if(!a||e.length-a>65558)return i(lo(13,0,1),null),s;var c=Lo(e,a+8);if(c){var l=c,u=Do(e,a+16),d=4294967295==u||65535==l;if(d){var p=Do(e,a-12);(d=101075792==Do(e,p))&&(l=c=Do(e,p+32),u=Do(e,p+48))}for(var f=t&&t.filter,h=function(t){var r=function(e,t,r){var n=Lo(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(Fo)return Fo.decode(e);var s=function(e){for(var t="",r=0;;){var n=e[r++],s=(n>127)+(n>223)+(n>239);if(r+s>e.length)return{s:t,r:ao(e,r-1)};s?3==s?(n=((15&n)<<18|(63&e[r++])<<12|(63&e[r++])<<6|63&e[r++])-65536,t+=String.fromCharCode(55296|n>>10,56320|1023&n)):t+=1&s?String.fromCharCode((31&n)<<6|63&e[r++]):String.fromCharCode((15&n)<<12|(63&e[r++])<<6|63&e[r++]):t+=String.fromCharCode(n)}}(e),o=s.s;return(r=s.r).length&&lo(8),o}(e.subarray(t+46,t+46+n),!(2048&Lo(e,t+8))),o=t+46+n,i=Do(e,t+20),a=r&&4294967295==i?function(e,t){for(;1!=Lo(e,t);t+=4+Lo(e,t+2));return[Oo(e,t+12),Oo(e,t+4),Oo(e,t+20)]}(e,o):[i,Do(e,t+24),Do(e,t+42)],c=a[0],l=a[1],u=a[2];return[Lo(e,t+10),c,l,s,o+Lo(e,t+30)+Lo(e,t+32),u]}(e,u,d),a=r[0],l=r[1],p=r[2],h=r[3],g=r[4],m=r[5],y=function(e,t){return t+30+Lo(e,t+26)+Lo(e,t+28)}(e,m);u=g;var b=function(e,t){e?(s(),i(e,null)):(t&&(o[h]=t),--c||i(null,o))};if(!f||f({name:h,size:l,originalSize:p,compression:a}))if(a)if(8==a){var w=e.subarray(y,y+l);if(p<524288||l>.8*p)try{b(null,$o(w,{out:new Ds(p)}))}catch(e){b(e,null)}else n.push(function(e,t,r){return r||(r=t,t={}),"function"!=typeof r&&lo(7),ko(e,t,[Co],function(e){return Po($o(e.data[0],Uo(e.data[1])))},1,r)}(w,{size:p},b))}else b(lo(14,"unknown compression type "+a,1),null);else b(null,ao(e,y,y+l));else b(null,null)},g=0;g<l;++g)h()}else i(null,{});return s}),ri=u.promisify(function(e,t,r){r||(r=t,t={}),"function"!=typeof r&&lo(7);var n={};jo(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){Yo(function(){r(e,t)})};Yo(function(){p=r});var f=function(){var e=new Ds(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;zo(e,a,s,s.f,s.u,o);var u=30+s.f.length+Go(s.extra),d=a+u;e.set(s.c,d),zo(e,i,s,s.f,s.u,o,a,s.m),i+=16+u+(s.m?s.m.length:0),a=d+o}catch(e){return p(e,null)}}!function(e,t,r,n,s){Bo(e,t,101010256),Bo(e,t+8,r),Bo(e,t+10,r),Bo(e,t+12,n),Bo(e,t+16,s)}(e,i,l.length,r,t),p(null,e)};o||f();for(var h=function(e){var t=s[e],r=n[t],c=r[0],h=r[1],g=function(){var e=-1;return{p:function(t){for(var r=e,n=0;n<t.length;++n)r=Io[255&r^t[n]]^r>>>8;e=r},d:function(){return~e}}}(),m=c.length;g.p(c);var y=Ho(t),b=y.length,w=h.comment,v=w&&Ho(w),_=v&&v.length,E=Go(h.extra),I=0==h.level?0:8,T=function(r,n){if(r)d(),p(r,null);else{var s=n.length;l[e]=xo(h,{size:m,crc:g.d(),c:n,f:y,m:v,u:b!=t.length||v&&w.length!=_,compression:I}),i+=30+b+E+s,a+=76+2*(b+E)+(_||0)+s,--o||f()}};if(b>65535&&T(lo(11,0,1),null),I)if(m<16e4)try{T(null,No(c,h))}catch(e){T(e,null)}else u.push(function(e,t,r){return r||(r=t,t={}),"function"!=typeof r&&lo(7),ko(e,t,[Ro],function(e){return Po(No(e.data[0],e.data[1]))},0,r)}(c,h,T));else T(null,c)},g=0;g<c;++g)h(g);return d});async function ni({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 u.TextDecoder,n=new u.TextEncoder,s=r.decode(e).split("\n").map(e=>{if(!e.trim())return e;try{const r=function({event:e,sensitiveValues:t}){return p.match(e).with({type:"console"},e=>({...e,args:e.args?.map(e=>({...e,preview:Ko({sensitiveValues:t,str:e.preview}),value:Jo({sensitiveValues:t,value:e.value})})),text:Ko({sensitiveValues:t,str:e.text})})).with({type:"before"},e=>({...e,params:Qo({obj:e.params,sensitiveValues:t}),title:e.title?Ko({sensitiveValues:t,str:e.title}):void 0})).with({type:"after"},e=>({...e,error:Zo({error:e.error,sensitiveValues:t}),result:void 0!==e.result?Jo({sensitiveValues:t,value:e.result}):void 0})).with({type:"action"},e=>({...e,error:Zo({error:e.error,sensitiveValues:t}),params:Qo({obj:e.params,sensitiveValues:t}),result:void 0!==e.result?Jo({sensitiveValues:t,value:e.result}):void 0,title:e.title?Ko({sensitiveValues:t,str:e.title}):void 0})).with({type:"event"},e=>({...e,params:Qo({obj:e.params,sensitiveValues:t})})).with({type:"stdout"},{type:"stderr"},e=>({...e,text:void 0!==e.text?Ko({sensitiveValues:t,str:e.text}):void 0})).with({type:"error"},e=>({...e,message:Ko({sensitiveValues:t,str:e.message})})).with({type:"log"},e=>({...e,message:Ko({sensitiveValues:t,str:e.message})})).with({type:"context-options"},e=>({...e,options:Qo({obj:e.options,sensitiveValues:t}),title:e.title?Ko({sensitiveValues:t,str:e.title}):void 0})).with({type:"frame-snapshot"},e=>({...e,snapshot:Qo({obj:e.snapshot,sensitiveValues:t})})).with({type:"resource-snapshot"},e=>({...e,snapshot:Qo({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 Ko({sensitiveValues:t,str:e})}});return n.encode(s.join("\n"))}({content:e,sensitiveValues:r}):n.endsWith(".html")||n.endsWith(".dat")||n.endsWith(".json")?ei({content:e,sensitiveValues:r}):n.startsWith("resources/")?async function({content:e,sensitiveValues:t}){return await(0,Us.isBinaryFile)(Buffer.from(e))?e:ei({content:e,sensitiveValues:t})}({content:e,sensitiveValues:r}):e}function si(e=process.cwd()){let r=t.resolve(e);for(;;){const e=oi(r);if(e){const n={...e.dependencies,...e.devDependencies},s="@playwright/test"in n?"@playwright/test":"playwright"in n?"playwright":void 0;if(s){const e=ii(r);let n=!1,o=r;for(;;){const e=t.join(o,"node_modules"),r=t.join(e,s);if(i.existsSync(r)){n=!0;break}const a=t.dirname(o);if(a===o)break;o=a}return{inNodeModules:n,installed:!0,packageManager:e,packageName:s}}}const n=t.dirname(r);if(n===r)return{inNodeModules:!1,installed:!1,packageManager:void 0};r=n}}function oi(e){const r=t.join(e,"package.json");let n;try{n=i.readFileSync(r,"utf-8")}catch{return}try{return JSON.parse(n)}catch{return}}function ii(e){const r=[["npm","package-lock.json"],["pnpm","pnpm-lock.yaml"],["yarn","yarn.lock"]];let n=e;for(;;){for(const[e,s]of r)if(i.existsSync(t.join(n,s)))return e;const e=t.dirname(n);if(e===n)return;n=e}}function ai(e){if("npm"===e)return["npx","playwright"];if("pnpm"===e)return["pnpm","exec","playwright"];if("yarn"===e)return["yarn","playwright"];throw new Error("Package manager not supported")}var ci=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),li=e=>(e instanceof Error?e.message:String(e)).slice(0,400),ui=({outputDir:e,representativeTest:t})=>{const r=["test","--trace=on","--workers=1","--retries=0","--output",e];return t.filePath&&r.push(t.filePath),t.testIdentifier?r.push("--grep",`^${ci(t.testIdentifier)}$`):t.testTitle&&r.push("--grep",ci(t.testTitle)),r},di=async e=>{const t=await m.readdir(e,{withFileTypes:!0}),r=[];for(const n of t){const t=O.default.join(e,n.name);if(n.isDirectory())r.push(...await di(t));else if(n.isFile()&&"trace.zip"===n.name){const e=await m.stat(t);r.push({path:t,mtimeMs:e.mtimeMs})}}return r},{zSuiteAutoHealReport:pi,zRepresentativeTest:fi}=function(e){const t=e.enum(xs),r=["Classification of the root cause:","",`- test: ${As("test")}`,`- bug: ${As("bug")}`,`- other: ${As("other")}`].join("\n"),n=e.object({filePath:e.string().optional(),testIdentifier:e.string().optional(),testTitle:e.string().optional()}),s=e.object({status:e.enum(["captured","capture_failed","upload_failed"]),representativeTest:n,storage:e.object({bucket:e.string(),key:e.string()}).optional(),signedUrl:e.string().optional(),error:e.string().optional()}),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 and fix (must be existing IDs only)."),rootCause:e.string().describe("Brief explanation of what happened (1-2 sentences).")}),a=e.discriminatedUnion("result",[i.extend({fixApplied:e.string().describe("What fix was applied (brief, specific)."),result:e.literal("fixed"),traceProof:s.optional().describe("Optional trace proof metadata for fixed issues."),traceProofs:e.array(o).min(1).optional().describe("Optional per-test trace proof metadata for fixed issues.")}),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)."),result:e.literal("unfixed")})]);return{zAutoHealReport:a,zIssueCategory:t,zRepresentativeTest:n,zSuiteAutoHealReport:e.object({issues:e.array(a).min(1).describe("List of all auto-heal issues/outcomes for this suite."),summary:e.string().min(3).describe("High-level summary (2-3 sentences) of the suite auto-heal results.")}),zTraceProof:s,zTraceProofByTest:o}}(T.z),hi=({authHeader:e,diffTracker:t,orgId:r,runId:n,workingDir:o})=>d.createSdkMcpServer({name:"auto-heal-report",tools:[d.tool("capture-trace-proof",["Capture and upload a Playwright trace proof for a fixed issue or fixed test case.","","Use this only for fixed results. Pass representative test info from the worker.","Pass testCaseId and call once per fixed test case.","testCaseId is for per-test mapping/storage metadata; representativeTest selects the runnable test."].join("\n"),{issueId:T.z.string().min(1).describe("Issue identifier for deterministic output paths and storage key naming."),proofId:T.z.string().min(1).optional().describe("Optional id for deterministic proof naming and deduplication."),representativeTest:fi.optional().default({}),testCaseId:T.z.string().min(1).optional().describe("Optional test case ID when capturing per-test trace proofs.")},async({issueId:t,proofId:a,representativeTest:c,testCaseId:l})=>{const u=T.z.string().min(1).parse(t),d=null==a?void 0:T.z.string().min(1).parse(a),p=null==l?void 0:T.z.string().min(1).parse(l),f=await(async({authHeader:e,issueId:t,orgId:r,proofId:n,representativeTest:o,runId:a,testCaseId:c,workingDir:l})=>{if(!(e=>null!=e.filePath||null!=e.testTitle||null!=e.testIdentifier)(o))return{status:"capture_failed",representativeTest:o,error:"Representative test info is missing (need filePath, testTitle, or testIdentifier)."};const u=si(l);if(!u.installed||!u.inNodeModules||!u.packageManager)return{status:"capture_failed",representativeTest:o,error:"Playwright is not installed in the current workspace."};const d=(e=>Rs(e)??"issue")(t),p=(({proofId:e,testCaseId:t})=>Ps(t)??Ps(e))({testCaseId:c,proofId:n}),f=O.default.join(l,".stably","autoheal-proof",d,p??"issue"),[h,...g]=ai(u.packageManager),y=[...g,...ui({outputDir:f,representativeTest:o})];try{await m.rm(f,{force:!0,recursive:!0}),await m.mkdir(f,{recursive:!0});const{code:u,stderr:d,timedOut:p}=await(async({args:e,command:t,cwd:r,env:n,timeoutMs:o})=>await new Promise((i,a)=>{const c=s.spawn(t,e,{cwd:r,env:n??process.env,stdio:["ignore","ignore","pipe"]});let l="",u=!1;c.stderr.on("data",e=>{l+=e.toString()});const d=setTimeout(()=>{u=!0,c.kill("SIGTERM")},o);c.on("error",e=>{clearTimeout(d),a(e)}),c.on("close",e=>{clearTimeout(d),i({code:e,stderr:l,timedOut:u})})}))({args:y,command:h,cwd:l,env:{...process.env,STABLY_INTERNAL_DISABLE_REPORTING:"1"},timeoutMs:3e5});if(p)return{status:"capture_failed",representativeTest:o,error:"Trace proof run timed out while executing Playwright verification."};if(0!==u)return{status:"capture_failed",representativeTest:o,error:`Trace proof run failed (exit code ${u??"unknown"}): ${d.trim().slice(0,280)}`};const g=await(async e=>{const t=await di(e);if(0!==t.length)return t.sort((e,t)=>t.mtimeMs-e.mtimeMs),t[0]?.path})(f);if(!g)return{status:"capture_failed",representativeTest:o,error:"Trace proof run completed, but no trace.zip was produced."};const{traceBucketPath:b,uploadUrl:w,sensitiveValues:v}=await(async({authHeader:e,issueId:t,proofId:r,testCaseId:n,contentType:s="application/zip",orgId:o,runId:i})=>{const a=await(c={auth:e,body:{contentType:s,issueId:t,proofId:r,testCaseId:n},client:Rr(),headers:Cn(o),path:{runId:i}},(c.client??wr).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=kn.parse(a.data);return{traceBucketPath:l.traceBucketPath,expiresInSeconds:l.expiresInSeconds,key:l.key,uploadUrl:l.uploadUrl,sensitiveValues:l.sensitiveValues}})({authHeader:e,issueId:t,proofId:n,orgId:r,runId:a,testCaseId:c}),_=await async function({tracePath:e,sensitiveValues:t}){const r=[],n=i.createReadStream(e);for await(const e of n)r.push(e);return async function({sensitiveValues:e,traceBuffer:t}){const r=e.filter(e=>!(e.length<3||Wo.some(t=>t.test(e))||Vo.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 ti(new Uint8Array(t)),o=Object.entries(s),i=await Promise.all(o.map(async([e,t])=>[e,await ni({content:t,filename:e,sensitiveValues:n})])),a=Object.fromEntries(i);return ri(a)}({traceBuffer:new Uint8Array(Buffer.concat(r)),sensitiveValues:t})}({tracePath:g,sensitiveValues:v});try{await(async({contentType:e="application/zip",traceBuffer:t,uploadUrl:r})=>{const n=await fetch(r,{body:Buffer.from(t),headers:{"Content-Type":e},method:"PUT"});if(!n.ok)throw new Error(`Failed to upload trace (${n.status})`)})({traceBuffer:_,uploadUrl:w})}catch(e){return{status:"upload_failed",representativeTest:o,error:li(e)}}return{status:"captured",representativeTest:o,storage:b}}catch(e){return{status:"capture_failed",representativeTest:o,error:li(e)}}})({authHeader:e,issueId:u,orgId:r,proofId:d,representativeTest:fi.parse(c??{}),runId:n,testCaseId:p,workingDir:o}),h="string"==typeof p?{testCaseId:p,...f}:f;return{content:[{text:JSON.stringify(h),type:"text"}]}}),d.tool("generate-report",["After attempting to fix all broken tests (skip only those truly infeasible), generate and return a suite auto-heal report in the required schema.","","Ensure the payload matches zSuiteAutoHealReport exactly; include every issue discovered."].join("\n"),{report:pi},async({report:s})=>{const o=await t.computeDiff(),i=(e=>{if(!e||"object"!=typeof e)return e;const t=e;if(!Array.isArray(t.issues))return e;const r=t.issues.map(e=>{if(!e||"object"!=typeof e)return e;const t=e;if("fixed"!==t.result||null!=t.traceProof||!Array.isArray(t.traceProofs))return e;const[r]=t.traceProofs;if(!r||"object"!=typeof r)return e;const n={...r};return delete n.testCaseId,{...t,traceProof:n}});return{...t,issues:r}})(s),a=pi.parse(i);try{await(async({authHeader:e,orgId:t,report:r,runId:n})=>{const s=await(o={auth:e,body:{report:JSON.stringify(r)},client:Rr(),headers:Cn(t),path:{runId:n}},(o.client??wr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-report",...o,headers:{"Content-Type":"application/json",...o.headers}}));var o;if(s.error)throw new Error(`Failed to upload auto-heal report (${s.response.status})`)})({authHeader:e,orgId:r,report:a,runId:n});const{diffBucketPath:t,uploadUrl:s}=await Ln({authHeader:e,contentType:"text/plain",orgId:r,runId:n});await Dn({contentType:"text/plain",diff:o,uploadUrl:s}),await On({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"}),gi=({onComplete:e,onRestartRequested:t})=>e?d.createSdkMcpServer({name:"session-control",tools:[d.tool("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:T.z.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}`)})]}):d.createSdkMcpServer({name:"stably-agent-control",version:"1.0.0",tools:[d.tool("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 servers are being restarted. Browser tools will be reinitialized."}]})))]}),mi=T.z.object({commentUrl:T.z.string()}),yi=({prContext:e,authHeader:t,orgId:r,onReportPosted:n})=>d.createSdkMcpServer({name:"create-report",tools:[d.tool("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:T.z.string().describe("A summary of the tests created. Include what features/flows are tested and any important notes."),filesCreated:T.z.array(T.z.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:[];bn.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",_r).toString(),a={Authorization:e,"Content-Type":"application/json"};t&&(a["x-stably-org-id"]=t),bn.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 bn.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=mi.parse(await c.json());return bn.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),bn.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 bn.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}}})]}),bi=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]"),wi=(e,t)=>({message:bi(e),status:t?.status,statusText:t?.statusText}),vi=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"]),_i=async({authHeader:e,mode:t,maxTurnsOverride:r})=>{const n=Rr();bn.debug("Requesting subagent definitions from API",{mode:t,maxTurnsOverride:r});const s=await(o={client:n,auth:e,body:{mode:t,maxTurnsOverride:r}},(o.client??wr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/prompts/subagents",...o,headers:{"Content-Type":"application/json",...o.headers}}));var o;if(401===s.response.status)throw bn.warn("Subagent definitions fetch failed: unauthorized (401)"),await zr(),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 bn.warn("Subagent definitions fetch failed: forbidden (403)"),await zr(),new Error("You no longer have access to this organization. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(s.error)throw bn.warn("Subagent definitions fetch failed",{error:s.error}),new Error(`Failed to fetch subagent definitions: ${JSON.stringify(s.error)}`);const{subagents:i}=s.data;return bn.debug("Subagent definitions received",{count:Object.keys(i).length}),i},{zStablyYaml:Ei}=function(e){const t=e.object({cron:e.string(),stablyTestArgs:e.string().optional(),timezone:e.string().optional()}),r=e.object({maxTurnsPerIssue:e.number().int().positive().optional(),maxParallelWorkers:e.number().int().positive().optional(),rules:e.string().optional()}),n=e.object({fix:r.optional()});return{zStablyYaml:e.object({schedules:e.record(e.string(),t).optional(),agent:n.optional()}),zAgentConfig:n,zAgentFixConfig:r,zScheduleEntry:t}}(w.z),Ii=async(e,t)=>{try{const r=await Or(e,t);if(!r)return void bn.debug(`No ${t} found`);const n=await m.readFile(r,"utf-8");if(!n.trim())return;return n.length>1e4?(bn.warn(`${t} exceeds max length (${n.length} > 10000), truncating`,{path:r}),{content:n.slice(0,1e4),path:r}):(bn.debug(`Loaded ${t} rules`,{path:r,contentLength:n.length}),{content:n,path:r})}catch(e){return void bn.warn(`Failed to read ${t}`,{error:e})}},Ti=["Bash","Read","Write","Edit","Glob","Grep","Task","Skill"],xi=["Task","mcp__playwright-test","Skill"],Si=["Bash","Read","Write","Edit","Glob","Grep","mcp__session-control"],Ai=e=>{if("EPIPE"!==e.code)throw e},Ci="__main__",Ri=e=>"mcp__auto-heal-report__generate-report"===e,Pi=e=>"mcp__auto-heal-report__capture-trace-proof"===e?"Verify Test Run":"mcp__auto-heal-report__generate-report"===e?"Generate Report":Is(e);async function Ui(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)}))}var ki=async r=>{if("single"===r.mode||"build"===r.mode){const e=Array.isArray(r.prompt)?r.prompt.join(" "):r.prompt;bn.initSession(e||"create-from-diff")}else"fix"===r.mode&&bn.initSession(`fix-${r.runId}`);bn.info("Agent session starting",{mode:r.mode}),process.stdout.on("error",Ai),process.stderr.on("error",Ai);const n=e=>{if("EPIPE"!==e.code)throw e};process.on("uncaughtException",n),bn.debug("Checking authentication");const s=await Tn({autoLogin:"chat"===r.mode||"init"===r.mode}),o=(e=>"env"===e.type?e.auth.apiKey:e.auth.accessToken)(s);bn.debug("Authentication resolved",{authType:s.type});const c="oauth"===s.type?s.auth.context.orgId:void 0,l=O.default.resolve(process.cwd()),u=O.default.join(l,".env"),f=$.default.existsSync(u)&&$.default.statSync(u).isFile(),h=f?e.parse($.default.readFileSync(u,"utf8")):{};bn.debug("Environment file",{path:u,exists:f,variableCount:Object.keys(h).length});const g="chat"!==r.mode&&"init"!==r.mode,y="chat"===r.mode;let b=new os;const w="chat"===r.mode?r.getHelpText:void 0,v={log:[],promptDisplay:p.match(r).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:"build"},()=>"Building tests from specifications").with({mode:"single"},e=>{const t=(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt)?.trim();return t||"Creating tests from PR/branch changes"}).exhaustive(),status:"running"};let _,E,I,T,x=g,C=!1,P=!1,k=0,L=0,D=!1;const B=[];let N,j,M=[],G=!1,z=!1,Y=0;const W=new Map;let V=null,q=!1,K=!1;const J=Date.now();let X,Q="fix"===r.mode?{suiteId:r.runId,phase:"initializing",totalTests:null,fixedTests:0,failedTests:0,currentTestDescription:null,lastTestDescription:null,startedAt:J,endedAt:null,isError:!1,updatedAt:J,recentActivity:[],workers:[{id:Ci,testDescription:"Orchestrator",workerType:"main",status:"running",summary:null,startedAt:J,endedAt:null,activity:[]}]}:null;const Z=new Set,ee=(e,t)=>{if(!Q)return;const r=Q.workers.map(r=>{if(r.id!==e)return r;const n=[...r.activity,{...t,timestamp:Date.now()}].slice(-15);return{...r,activity:n}});ne({workers:r})},te=e=>{if(!Q)return;const t=[...Q.recentActivity,{...e,timestamp:Date.now()}].slice(-10);ne({recentActivity:t})},re=e=>(Q?.workers??[]).map(t=>t.id===Ci?{...t,status:e?"failed":"succeeded",endedAt:t.endedAt??Date.now()}:"running"===t.status?{...t,status:"failed",endedAt:Date.now()}:t),ne=e=>{Q&&!X?.isClosed&&(Q={...Q,...e,updatedAt:Date.now()},X?.sendProgress(Q))},se=async e=>{if("fix"===r.mode){if("STARTED"===e){if(q)return;q=!0}else{if(K)return;K=!0}try{await(async({authHeader:e,orgId:t,runId:r,status:n})=>{const s=await(o={auth:e,body:{status:n},client:Rr(),headers:Cn(t),path:{runId:r}},(o.client??wr).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-status",...o,headers:{"Content-Type":"application/json",...o.headers}}));var o;if(s.error)throw new Error(`Failed to update autoheal status (${s.response.status})`)})({authHeader:o,orgId:c,runId:r.runId,status:e})}catch{}}},oe="single"===r.mode||"build"===r.mode,ie=Date.now();let ae,ce=null;const le=e=>{ce&&!ae?.isClosed&&(ce={...ce,...e,updatedAt:Date.now()},ae?.sendProgress(ce))},ue=e=>{if(!ce)return;const t=[...ce.recentActivity,{...e,timestamp:Date.now()}].slice(-10);le({recentActivity:t})};if(oe||"fix"===r.mode)try{const e=new URL("/internal/v1/cli/progress",_r).toString(),t={Authorization:o,"Content-Type":"application/json"};c&&(t["x-stably-org-id"]=c);const n="single"===r.mode?"create":"build"===r.mode?"build":"fix",i=await fetch(e,{method:"POST",headers:t,body:JSON.stringify({mode:n,projectId:xn(s),agentId:F.default.randomUUID(),..."fix"===r.mode?{playwrightSuiteRunId:r.runId}:{}}),signal:AbortSignal.timeout(1e4)});if(i.ok){const{sessionId:e}=await i.json();if(oe){const t="single"===r.mode||"build"===r.mode?Array.isArray(r.prompt)?r.prompt.join(" "):r.prompt:null,n=is(l);ce={sessionId:e,phase:"initializing",startedAt:ie,endedAt:null,isError:!1,updatedAt:ie,currentActivity:null,filesCreated:[],recentActivity:[],prompt:t||null,environment:{gitBranch:n?.branch??null,workingDirectory:l,nodeVersion:process.version,cliVersion:vr}},ae=new Nn({authHeader:o,orgId:c,sessionId:e,onUserMessage:e=>{b&&(bn.info("[ws] Injecting web UI message into agent",{contentLength:e.length}),ue({type:"user_message",summary:e}),be({text:`[Web] ${e}`}),b.pushText(`[Message from web UI user]: ${e}`),x||(x=!0,Se({status:"running"})))}}),ae.start(),le({phase:"initializing"})}bn.info(`[${n}] Progress session created`,{sessionId:e})}else{const t=await i.text().catch(()=>"");bn.warn(`[${n}] Failed to create progress session: ${i.status} ${e} — ${t.slice(0,300)}`)}}catch(e){const t=e instanceof Error?e.message:String(e);bn.warn(`[progress] Session creation failed (non-fatal): ${t}`)}const de={current:e=>{}},pe={current:async()=>{}},{addSubagentActivity:fe,addSubagentStart:he,addTool:ge,addToolResult:me,appendText:ye,appendUserMessage:be,cleanup:we,setExiting:ve,setRunningLabel:_e,setStatus:Ee,setSubagentStatus:Ie,updateFixProgress:Te}=await(async(e,t)=>{const{Box:r,Static:n,Text:s,render:o,useInput:i}=await import("ink"),a=!!process.stdin.isTTY,c=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],l=()=>A.jsx(s,{inverse:!0,children:" "}),u=(({Box:e,Text:t,useInput:r},n,s)=>function({onChoice:o,prompt:i}){const[a,c]=S.useState(0),[l,u]=S.useState(!1),[d,p]=S.useState(""),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=Is(i.toolName),g=Ts(i.toolName,i.input);return A.jsxs(e,{borderColor:"yellow",borderStyle:"round",flexDirection:"column",marginTop:1,paddingX:1,paddingY:0,children:[A.jsx(t,{bold:!0,color:"yellow",children:"Permission Required"}),A.jsxs(e,{flexDirection:"column",marginTop:1,children:[A.jsx(t,{color:"magenta",children:h}),null!=g&&A.jsxs(t,{color:"gray",children:[" ",g]})]}),null!=i.decisionReason&&A.jsx(e,{marginTop:1,children:A.jsxs(t,{color:"gray",children:["Reason: ",i.decisionReason]})}),l?A.jsxs(e,{flexDirection:"column",marginTop:1,children:[A.jsx(t,{color:"gray",children:"Enter message for AI (press Enter to submit, Esc to cancel):"}),A.jsxs(t,{children:[A.jsx(t,{color:"yellow",children:">"})," ",d,A.jsx(n,{})]})]}):A.jsxs(e,{flexDirection:"column",marginTop:1,children:[A.jsx(t,{color:"gray",children:"Use ↑↓ arrows or number keys to select:"}),f.map((e,r)=>A.jsx(t,{children:A.jsxs(t,{color:r===a?"cyan":void 0,children:[r===a?"❯":" "," ",r+1,". ",e.label]})},e.value))]})]})})({Box:r,Text:s,useInput:i},l,a),d=(({Cursor:e,inkComponents:{Box:t,Static:r,Text:n,useInput:s},isRawModeSupported:o,PermissionPrompt:i,Spinner:a})=>{const c=({progress:e})=>{const[r,s]=S.useState(Date.now());S.useEffect(()=>{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),c=i%60,l=a>0?`${a}m ${c.toString().padStart(2,"0")}s`:`${c}s`,{label:u,color:d}={initializing:{label:"Fetching test results",color:"gray"},triage:{label:"Triaging failures",color:"yellow"},fixing:{label:"Fixing tests",color:"cyan"},validation:{label:"Validating fixes",color:"blue"},complete:{label:"Complete",color:"green"}}[e.phase],p=e.fixedTests+e.failedTests,f="fixing"===e.phase&&p>0?null!==e.totalTests?` (fixed ${e.fixedTests}/${e.totalTests}${e.failedTests>0?`, failed ${e.failedTests}`:""})`:` (fixed ${e.fixedTests}${e.failedTests>0?`, failed ${e.failedTests}`:""})`:"";return A.jsx(t,{flexDirection:"column",children:A.jsxs(n,{children:[A.jsx(n,{color:d,bold:!0,children:u}),A.jsx(n,{color:"gray",children:f}),A.jsxs(n,{color:"gray",children:[" [",l,"]"]})]})})},l=({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?"yellow":"green",l=e.isError?"Fix stopped":"Fix complete";return A.jsxs(t,{flexDirection:"column",children:[A.jsxs(n,{color:c,bold:!0,children:[l," in ",a]}),null!==e.totalTests&&A.jsxs(n,{color:"gray",children:[e.fixedTests,"/",e.totalTests," tests fixed",e.failedTests>0?`, ${e.failedTests} failed`:""]})]})},u=e=>{if("subagent"===e.kind&&e.subagent){const{subagent:r}=e,s="complete"===r.status?"green":"error"===r.status?"red":"yellow";return A.jsxs(t,{flexDirection:"column",marginTop:1,children:[A.jsxs(n,{children:[A.jsx(n,{color:s,bold:!0,children:"Agent"}),r.description?A.jsxs(n,{color:"gray",children:[" (",r.description,")"]}):null]}),r.activities.length>0&&A.jsx(t,{flexDirection:"column",marginLeft:2,children:r.activities.map(e=>(e=>"tool"===e.kind?A.jsxs(n,{color:"magenta",children:["• ",e.content]},e.id):"tool_result"===e.kind?A.jsx(n,{color:"gray",children:e.content},e.id):null)(e))})]},e.id)}return"tool"===e.kind?A.jsxs(n,{color:"magenta",children:["• ",e.content]},e.id):"tool_result"===e.kind?A.jsx(n,{color:"gray",children:e.content},e.id):"user"===e.kind?A.jsxs(n,{color:"cyan",children:["You: ",e.content]},e.id):A.jsx(n,{children:e.content},e.id)},d="vscode"===process.env.TERM_PROGRAM,p=(e,t)=>{if(t<=0)return 0;let r=t-1;for(;r>0&&/\s/.test(e[r]);)r--;for(;r>0&&!/\s/.test(e[r-1]);)r--;return r},f=(e,t)=>{if(t>=e.length)return e.length;let r=t;for(;r<e.length&&!/\s/.test(e[r]);)r++;for(;r<e.length&&/\s/.test(e[r]);)r++;return r},h=(e,t)=>{if(t<=0)return 0;const r=e.lastIndexOf("\n",t-1);return-1===r?0:r+1},g=(e,t)=>{const r=e.indexOf("\n",t);return-1===r?e.length:r};return function({onExit:m,onPermissionChoice:y,onSend:b,showSpinnerImmediately:w,state:v}){const[_,E]=S.useState({value:"",cursor:0}),I=_.value,T=_.cursor,x=S.useRef(!1),C=S.useRef(void 0),[R,P]=S.useState(!1),U=S.useRef(0),k=v.log.at(-1),L="text"===k?.kind&&"running"===v.status,D=v.log.findIndex(e=>"subagent"===e.kind&&"running"===e.subagent?.status),O=d?0:-1!==D?D:L?v.log.length-1:v.log.length;S.useEffect(()=>{v.log.length<U.current&&(U.current=0),O>U.current&&(U.current=O)},[v.log.length,O]);const B=v.log.slice(0,U.current),N=v.log.slice(U.current),$=!!v.permissionPrompt,j=S.useCallback(async()=>{x.current?(C.current&&clearTimeout(C.current),await(m?.()),process.exit(0)):(x.current=!0,P(!0),C.current=setTimeout(()=>{x.current=!1,P(!1)},2e3))},[m]);s((e,t)=>{t.ctrl&&"c"===e&&j().catch(()=>process.exit(1))},{isActive:o}),S.useEffect(()=>{if($||!b)return;const e=e=>{const t=e.toString();""!==t&&"[1;5~"!==t?""!==t&&"[4;5~"!==t?""!==t&&"[1~"!==t&&"OH"!==t&&"[7~"!==t?""!==t&&"[4~"!==t&&"OF"!==t&&"[8~"!==t||E(e=>({...e,cursor:g(e.value,e.cursor)})):E(e=>({...e,cursor:h(e.value,e.cursor)})):E(e=>({...e,cursor:e.value.length})):E(e=>({...e,cursor:0}))};return process.stdin.on("data",e),()=>{process.stdin.off("data",e)}},[$,b,I]),s((e,t)=>{if(!t.ctrl||"c"!==e){if(t.return){const e=I.trim();return e&&b?.(e),void E({value:"",cursor:0})}t.ctrl&&"w"===e||t.ctrl&&t.backspace?E(e=>{const t=p(e.value,e.cursor);return{value:e.value.slice(0,t)+e.value.slice(e.cursor),cursor:t}}):!t.backspace&&!t.delete||t.ctrl?t.ctrl&&t.leftArrow||t.meta&&"b"===e?E(e=>({...e,cursor:p(e.value,e.cursor)})):t.ctrl&&t.rightArrow||t.meta&&"f"===e?E(e=>({...e,cursor:f(e.value,e.cursor)})):t.leftArrow?E(e=>({...e,cursor:Math.max(0,e.cursor-1)})):t.rightArrow?E(e=>({...e,cursor:Math.min(e.value.length,e.cursor+1)})):t.ctrl&&"a"===e?E(e=>({...e,cursor:0})):t.ctrl&&"e"===e?E(e=>({...e,cursor:e.value.length})):!e||t.ctrl||t.meta||t.escape||e.includes("")||/^\[./.test(e)||/^O[A-D]$/.test(e)||E(t=>({value:t.value.slice(0,t.cursor)+e+t.value.slice(t.cursor),cursor:t.cursor+e.length})):E(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&&!$});const M=S.useMemo(()=>"running"===v.status?A.jsx(a,{label:v.runningLabel??"Working"}):"success"!==v.status?A.jsx(n,{color:"red",children:"✖ Failed"}):void 0,[v.runningLabel,v.status]),F=!(w||!b||"running"!==v.status||0!==v.log.length||v.resultText||v.errorText),H="running"===v.status&&!F||v.log.length>0||v.resultText||v.errorText||"running"!==v.status;return A.jsxs(t,{flexDirection:"column",children:[A.jsx(r,{items:["header"],children:()=>A.jsxs(t,{flexDirection:"column",flexShrink:0,children:[A.jsx(n,{color:"cyan",bold:!0,children:"Stably Agent"}),A.jsx(t,{flexDirection:"column",marginTop:1,children:A.jsx(n,{color:"gray",children:v.promptDisplay})})]},"header")}),B.length>0&&A.jsx(r,{items:B,children:e=>u(e)}),N.length>0&&A.jsx(t,{flexDirection:"column",children:N.map(e=>u(e))}),"error"===v.status&&v.errorText&&A.jsx(t,{marginTop:1,children:A.jsx(n,{color:"red",children:v.errorText})}),"success"===v.status&&v.resultText&&A.jsx(t,{marginTop:1,children:A.jsx(n,{children:v.resultText})}),H&&A.jsx(t,{flexDirection:"column",flexShrink:0,marginTop:1,children:"running"===v.status&&v.fixProgress?A.jsxs(t,{flexDirection:"column",children:[A.jsxs(t,{children:[A.jsx(a,{}),A.jsx(n,{children:" "}),A.jsx(c,{progress:v.fixProgress})]}),"fixing"===v.fixProgress.phase&&v.log.flatMap(e=>{const{subagent:r}=e;if("subagent"!==e.kind||"fix-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 A.jsxs(t,{flexDirection:"column",children:[A.jsxs(n,{children:[" ",A.jsx(a,{}),A.jsxs(n,{color:"gray",children:[r.description||"fix-worker",o>0?` (${o} ${1===o?"cycle":"cycles"})`:""]})]}),c&&A.jsxs(n,{color:"gray",dimColor:!0,children:[" • ",c.content]}),l&&A.jsxs(n,{color:"gray",dimColor:!0,children:[" ",l]})]},e.id)})]}):"success"!==v.status&&"error"!==v.status||!v.fixProgress?M:A.jsx(l,{progress:v.fixProgress})}),null!=v.permissionPrompt&&null!=y&&A.jsx(i,{onChoice:y,prompt:v.permissionPrompt}),null!=b&&null==v.permissionPrompt&&!v.isExiting&&A.jsxs(t,{borderColor:"gray",borderStyle:"round",flexDirection:"column",flexShrink:0,marginTop:1,paddingX:1,paddingY:0,children:[A.jsx(n,{color:"gray",children:"Type a message and press Enter. Press Ctrl+C to exit."}),A.jsxs(n,{children:[A.jsx(n,{color:"yellow",children:">"})," ",I.slice(0,T),A.jsx(e,{}),I.slice(T)]})]}),R&&A.jsxs(t,{marginTop:1,flexDirection:"column",children:[A.jsx(n,{color:"yellow",children:"Press Ctrl+C again to exit"}),on&&A.jsxs(n,{color:"gray",children:["Debug log: ",un]})]})]})}})({Cursor:l,inkComponents:{Box:r,Static:n,Text:s,useInput:i},isRawModeSupported:a,PermissionPrompt:u,Spinner:({label:e})=>{const[t,r]=S.useState(0);return S.useEffect(()=>{const e=setInterval(()=>r(e=>(e+1)%c.length),80);return()=>clearInterval(e)},[]),A.jsxs(s,{color:"yellow",children:[c[t]," ",e]})}});let p=e;t?.isFixMode&&(p.fixProgress={phase:"initializing",totalTests:null,fixedTests:0,failedTests:0,currentTestDescription:null,lastTestDescription:null,startedAt:Date.now(),endedAt:null,isError:!1});const f={current:(e,t)=>{}},h=o(A.jsx(d,{onExit:t?.onExit,onPermissionChoice:(e,t)=>f.current(e,t),onSend:t?.onSend,showSpinnerImmediately:t?.showSpinnerImmediately,state:p}),{exitOnCtrlC:!1}),g=()=>{p={...p},h.rerender(A.jsx(d,{onExit:t?.onExit,onPermissionChoice:(e,t)=>f.current(e,t),onSend:t?.onSend,showSpinnerImmediately:t?.showSpinnerImmediately,state:p}))},m=({text:e})=>{e&&(p.log=[...p.log,{content:e,id:p.log.length,kind:"user"}],g())},y=new Map;return{addSubagentActivity:({toolUseId:e,kind:t,content:r})=>{const n=y.get(e);if(void 0===n)return void console.error("[addSubagentActivity] No entry index for toolUseId:",e);const s=p.log[n];if(s&&"subagent"===s.kind&&s.subagent){if("text"===t){const e=s.subagent.activities.at(-1);e&&"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});p.log=[...p.log],g()}else console.error("[addSubagentActivity] Entry not found or not subagent:",{entryIndex:n,entryKind:s?.kind})},addSubagentStart:({toolUseId:e,subagentType:t,description:r})=>{const n=p.log.length;if(y.set(e,n),p.log=[...p.log,{content:"",id:n,kind:"subagent",subagent:{toolUseId:e,subagentType:t,description:r,status:"running",activities:[]}}],p.fixProgress)if("triage"===t&&"initializing"===p.fixProgress.phase)p.fixProgress={...p.fixProgress,phase:"triage"};else if("fix-worker"===t){const e=(p.fixProgress.totalTests??0)+1,t=r||null;p.fixProgress={...p.fixProgress,phase:"fixing",totalTests:e,currentTestDescription:t,lastTestDescription:t??p.fixProgress.lastTestDescription}}else"validation"===t?p.fixProgress={...p.fixProgress,phase:"validation",currentTestDescription:null}:"context"===t&&(p.fixProgress={...p.fixProgress,currentTestDescription:r||p.fixProgress.currentTestDescription});g()},addTool:({rawName:e,toolInput:t})=>{const r=Is(e),n=Ts(e,t),s=n?`${r} (${n})`:r;p.log=[...p.log,{content:s,id:p.log.length,kind:"tool"}],g()},addToolResult:({message:e})=>{p.log=[...p.log,{content:e,id:p.log.length,kind:"tool_result"}],g()},appendText:({text:e})=>{if(!e)return;const t=p.log.at(-1),r=t&&"text"===t.kind?e:e.replace(/^\s*\n+/,"");t&&"text"===t.kind?p.log=[...p.log.slice(0,-1),{...t,content:`${t.content}${r}`}]:p.log=[...p.log,{content:r,id:p.log.length,kind:"text"}],g()},appendUserMessage:m,cleanup:async()=>{const e=h.waitUntilExit();h.unmount(),await e},setExiting:()=>{p.isExiting=!0,g()},setRunningLabel:({label:e})=>{p.runningLabel=e,g()},setStatus:({error:e,result:t,status:r})=>{p.errorText=e,p.resultText=t,p.status=r,g()},setSubagentStatus:({toolUseId:e,status:t})=>{const r=y.get(e);if(void 0===r)return;const n=p.log[r];n&&"subagent"===n.kind&&n.subagent&&(n.subagent.status=t,p.fixProgress&&"fix-worker"===n.subagent.subagentType&&("complete"===t?p.fixProgress={...p.fixProgress,fixedTests:p.fixProgress.fixedTests+1,currentTestDescription:null}:"error"===t&&(p.fixProgress={...p.fixProgress,failedTests:p.fixProgress.failedTests+1,currentTestDescription:null})),p.log=[...p.log],g(),"complete"!==t&&"error"!==t||y.delete(e))},showPermissionPrompt:e=>new Promise(t=>{f.current=(r,n)=>{if(p.permissionPrompt=void 0,g(),"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";m({text:e}),t({behavior:"deny",message:e,interrupt:!1})}},p.permissionPrompt={...e,resolve:t},g()}),updateFixProgress:t?.isFixMode?e=>{p.fixProgress&&(p.fixProgress={...p.fixProgress,...e},g())}:void 0}})(v,"chat"===r.mode||"init"===r.mode?{onExit:()=>pe.current(),onSend:e=>de.current(e),showSpinnerImmediately:"init"===r.mode}:"fix"===r.mode?{onExit:()=>pe.current(),isFixMode:!0}:void 0);let xe=v.status;const Se=({error:e,result:t,status:r})=>{xe=r,Ee({error:e,result:t,status:r})};let Ae;de.current=e=>{const t=e.trim();if(y&&!bn.getLogFilePath()&&bn.initSession(t||"chat"),bn.debug("User message",{text:t}),"/help"===t){x&&b&&(C=!0,_?.interrupt?.(),b.allowNextTurn(),x=!1),"running"===xe&&Se({status:"success"}),be({text:e});const t=w?.();return void ye({text:t??"Help is not available in this session."})}const r=I||P&&x;if(y&&(k+=1,T=void 0,r||(D=!1,_e({label:void 0}))),b){if(r)return Se({status:"running"}),be({text:e}),void B.push(e);if(!P||x||I||(P=!1),x)return Se({status:"running"}),be({text:e}),b.pushText(e),void(L+=1);Se({status:"running"}),be({text:e}),b.pushText(e),x=!0}};const Ce=[];let Re;const Pe=await(async()=>{if("single"===r.mode||"build"===r.mode){const n=await async function(e,r){const n=t.resolve(e);if(r){const e=t.resolve(n,r);return ys(e,"output-flag"),{path:e,source:"output-flag"}}const s=hs(n);if(s){const e=await async function(e){try{const t=(await m.readFile(e,"utf-8")).match(/testDir:\s*['"]([^'"]+)['"]/);return t?.[1]}catch{return}}(s);if(e){const r=t.resolve(t.dirname(s),e);if(ms(r))return ys(r,"playwright.config.ts"),{path:r,source:"playwright.config.ts"}}}for(const e of gs){const r=t.join(n,e);if(ms(r))return ys(r,"auto-detected"),{path:r,source:"auto-detected"}}return ys(n,"cwd-fallback"),{path:n,source:"cwd-fallback"}}(l,r.outputDir);return Re=n.path,e=r.prompt,`${(Array.isArray(e)?e.join(" "):e).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: ${Re}]`}var e;if("fix"===r.mode)try{bn.info("[fix] Fetching autoheal context",{runId:r.runId});const e=Date.now(),{context:t,autohealReportUrl:n}=await(async({authHeader:e,orgId:t,runId:r})=>{bn.debug("Fetching autoheal context",{runId:r});const n=await(s={auth:e,client:Rr(),headers:Cn(t),path:{runId:r}},(s.client??wr).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-context",...s}));var s;if(404===n.response.status)throw bn.warn("Autoheal context not found",{runId:r,status:404}),new Error(`Run ID "${r}" was not found.`);if(401===n.response.status)throw bn.warn("Autoheal context fetch unauthorized",{runId:r,status:401}),new Error("Unauthorized: failed to fetch autoheal context (401).");if(422===n.response.status)throw bn.warn("Autoheal context fetch invalid request",{runId:r,status:422,error:n.error?.error}),new Error(n.error?.error??"Failed to fetch autoheal context (422).");if(!n.error){const e=Rn.safeParse(n.data);if(e.success)return bn.debug("Autoheal context fetched successfully",{runId:r,contextSize:e.data.context.length}),{context:e.data.context,autohealReportUrl:e.data.autohealReportUrl};throw bn.warn("Autoheal context response invalid",{runId:r}),new Error("Autoheal context response missing or invalid context.")}throw bn.warn("Autoheal context fetch failed",{runId:r,error:n.error}),new Error("Failed to fetch autoheal context")})({authHeader:o,orgId:c,runId:r.runId});return bn.info("[fix] Autoheal context fetched",{runId:r.runId,durationMs:Date.now()-e,contextLength:t.length}),Ae=n,X||(bn.info("[fix] Creating WebSocket progress reporter"),X=new Bn({authHeader:o,orgId:c,runId:r.runId,onUserMessage:e=>{if(bn.info("[ws] Injecting web UI message into fix agent",{contentLength:e.length}),ee(Ci,{type:"user_message",summary:e}),te({type:"user_message",summary:e}),be({text:`[Web] ${e}`}),!x)return b.pushText(`[Message from web UI user]: ${e}`),x=!0,void b.allowNextTurn();G||Date.now()-Y<2e3?b.pushText(`[Message from web UI user]: ${e}`):(M.push(e),N&&clearTimeout(N),N=setTimeout(()=>{N=void 0;const e=[...M];M=[],Y=Date.now(),It(e)},500))}}),X.start(),ne({phase:"initializing"})),se("STARTED"),t}catch(e){const t=e instanceof Error?e.message:"Failed to fetch autoheal context.";bn.error("[fix] Failed to fetch autoheal context",{error:t}),Se({error:t,status:"error"}),await we(),process.exit(1)}return"init"===r.mode?"Please analyze this project and set up Playwright with the Stably SDK. Check for existing configurations and install the necessary dependencies.":""})(),Ue=await async function(e){const t=O.default.resolve(e),r=O.default.join(t,"tests"),n=O.default.join(r,"helpers"),s=O.default.join(r,"assets"),o=function(e){const t=O.default.resolve(e);if(i.existsSync(t))for(const e of as){const r=O.default.join(t,`playwright.config${e}`);if(i.existsSync(r))return r}}(t)??O.default.join(t,"playwright.config.ts"),a=O.default.basename(o),c=O.default.join(r,"seed.spec.ts"),[l,u,d,p,f,h]=await Promise.all([us({defaultContent:"Unable to read directory",dirName:"working directory",dirPath:t}),us({defaultContent:"Unable to read directory",dirName:"tests directory",dirPath:r}),us({defaultContent:"Directory does not exist yet",dirName:"helpers directory",dirPath:n}),us({defaultContent:"Directory does not exist yet",dirName:"assets directory",dirPath:s}),ls({defaultContent:"File does not exist or could not be read",fileName:a,filePath:o}),ls({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}}}(l),ke=await(async e=>{try{const t=await Or(e,"stably.yaml");if(!t)return void bn.debug("No stably.yaml found");const r=await m.readFile(t,"utf-8");if(!r.trim())return;const n=R.parseDocument(r),s=Ei.parse(n.toJS()),o=s.agent?.fix?.maxTurnsPerIssue,i=s.agent?.fix?.maxParallelWorkers,a=!!s.agent?.fix?.rules;return bn.debug(`Loaded stably.yaml: maxTurnsPerIssue=${o??"default"}, maxParallelWorkers=${i??"default"}, hasRules=${a}`,{path:t,config:s.agent}),s}catch(e){return void bn.warn("Failed to parse stably.yaml",{error:e})}})(l),Le=ke?.agent?.fix?.maxTurnsPerIssue,De=ke?.agent?.fix?.maxParallelWorkers,Oe=ke?.agent?.fix?.rules,Be="fix"===r.mode||"single"===r.mode||"build"===r.mode,Ne="single"===r.mode||"build"===r.mode?await(async e=>{const t=await Ii(e,"STABLY-CREATE.md");return t?.content})(l):void 0,$e=await(e=>Ii(e,"STABLY.md"))(l),je=$e?.content;bn.info("[fix] Fetching system prompt and subagent definitions",{mode:r.mode,maxTurnsOverride:Le,hasCustomRules:!!Oe,hasCreateRules:!!Ne,hasStablyMd:!!je,stablyMdPath:$e?.path}),$e&&bn.info(`STABLY.md loaded (${$e.content.length} chars)`,{path:$e.path});const Me=Date.now(),[{systemPrompt:Fe,prContext:He},Ge]=await Promise.all([ds({allowedEnvVars:Object.keys(h),mode:r.mode,workspaceInfo:Ue,authHeader:o,customHeader:"single"===r.mode||"build"===r.mode?r.customHeader:void 0,maxParallelWorkers:"fix"===r.mode?De:void 0}),Be?_i({authHeader:o,mode:r.mode,maxTurnsOverride:Le}):Promise.resolve({})]);bn.info("[fix] System prompt and subagents fetched",{durationMs:Date.now()-Me,systemPromptSize:Fe.length,subagentCount:Object.keys(Ge).length,maxTurnsOverride:Le??"default",hasPrContext:!!He});const ze={...h,...process.env},Ye={};for(const[e,t]of Object.entries(ze))vi.has(e)||void 0===t||(Ye[e]=t);const We=!0;bn.debug("AI proxy configuration",{useStablyAiProxy:We,wantsBypassProxy:!1,wantsUseOllama:!1}),bn.info("[fix] Acquiring AI proxy key",{useStablyAiProxy:We});const Ve=Date.now(),qe=await async function({auth:e,client:t,source:r,metadata:n,duration:s}){try{const i=await(o={auth:e,client:t,body:{source:r,metadata:n??{},duration:s}},(o.client??wr).post({security:[{scheme:"bearer",type:"http"}],url:"/v1/proxy/api-key",...o,headers:{"Content-Type":"application/json",...o.headers}})),a=i.response;if(i.error){const e="object"==typeof i.error&&"error"in i.error?i.error.error:"Unknown error";return{error:wi(e,a)}}return i.data?{key:i.data.key}:{error:wi("No data in response",a)}}catch(e){const t=e instanceof Error?e.message:"Unknown error";return{error:wi(t)}}var o}({auth:o,client:Rr(),source:"cli"}),Ke=qe?.key;if(bn.info("[fix] AI proxy key acquired",{durationMs:Date.now()-Ve,success:!!Ke,hasError:!!qe?.error}),!Ke){const e=qe?.error?.message?`Unable to make AI calls: ${qe.error.message}`:"Unable to make AI calls. Check if you are authenticated.";bn.warn("Failed to get proxy API key",{error:qe?.error?.message}),Se({error:e,status:"error"}),await we(),bn.flush(),bn.printLogFileInfo(),process.exit(1)}bn.debug("Proxy API key acquired",{success:!!Ke});const Je=await An(),Xe=Je?Object.fromEntries(Object.entries(Sn(Je)).filter(e=>null!=e[1])):void 0,Qe="init"===r.mode,Ze="fix"===r.mode,et=Ze?Xt.createLocal({workingDir:l}):void 0;et&&await et.captureSnapshot();const tt=Qe?gi({onComplete:()=>{Se({status:"success"}),ve(),b?.finish(),process.exit(0)}}):y?gi({onRestartRequested:()=>{y&&(P=!0,Se({status:"running"}),_e({label:"Restarting browser tools..."}),T={createdAtUserMessageSeq:k,attempts:0})}}):void 0,rt=tt?y?{"stably-agent-control":tt}:{"session-control":tt}:{},nt=oe&&He?["mcp__create-report"]:[],st=Qe?Si:[...Ti,...Ze?["mcp__auto-heal-report"]:[],...nt],ot=Qe?Si:y?[...xi,"mcp__stably-agent-control"]:[...xi,...nt],it=oe&&He?{"create-report":yi({prContext:He,authHeader:o,orgId:c,onReportPosted:e=>{le({githubComment:{url:e.commentUrl,prNumber:He.prNumber}})}})}:{},at=Qe?rt:Ze&&et?{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:Xe},"auto-heal-report":hi({authHeader:o,diffTracker:et,orgId:c,runId:r.runId,workingDir:l}),...rt}:{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:Xe},...rt,...it},ct="single"===r.mode||"build"===r.mode,lt=Qe?[]:[{hooks:[async e=>{const t=Fn(e);if(!t)return{decision:"approve"};let r=!1;const n=t.map(e=>jn(e)?e.text.length<=4e4?e:(r=!0,{...e,text:`${e.text.slice(0,4e4)}...[truncated to 40000 characters]`}):e);return r?{decision:"approve",hookSpecificOutput:{hookEventName:"PostToolUse",updatedMCPToolOutput:n}}:{decision:"approve"}}],matcher:"mcp__playwright-test__.*"},{matcher:"mcp__playwright-test__test_run",hooks:[Vn({onResult:e=>me({message:e})})]},{matcher:"mcp__playwright-test__test_debug",hooks:[qn({onResult:e=>me({message:e})})]},...ct?[{matcher:"Write",hooks:[Jn({onFileCreated:e=>{Ce.push(e),ce&&le({filesCreated:[...ce.filesCreated,e]})}})]}]:[],{matcher:"Write",hooks:[ss({workDir:l})]},{matcher:"Edit",hooks:[ss({workDir:l})]}],ut=Qe?[]:[{matcher:"mcp__playwright-test__browser_type",hooks:[Wn({envVars:h})]}],dt=Object.keys(Ge).length>0?Ge:void 0,pt={...Ye};pt.MCP_TOOL_TIMEOUT=String(6e5),Ke&&(pt.ANTHROPIC_API_KEY=Ke,pt.ANTHROPIC_BASE_URL=xr,pt.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS="1");const ft=process.env.STABLY_AGENT_MODEL??"claude-opus-4-6",ht=Oe?`\n\n## Custom Rules\n${Oe}`:"",gt=Ne?`\n\n## Custom Test Generation Rules\n${Ne}`:"",mt=je?`\n\n## Project Rules (STABLY.md)\n${je}`:"",yt=Fe+ht+gt+mt;bn.debug("[fix] Final system prompt assembled",{baseSize:Fe.length,fixRulesSize:ht.length,createRulesSize:gt.length,stablyMdSize:mt.length,finalSize:yt.length});const bt=O.default.join(__dirname,"stably-plugin"),wt=$.default.existsSync(bt)?{type:"local",path:bt}:function(){const e=function(){try{if(!("undefined"==typeof document?require("url").pathToFileURL(e).href:U&&"SCRIPT"===U.tagName.toUpperCase()&&U.src||new URL("index.js",document.baseURI).href))return;const e=a.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(e).href:U&&"SCRIPT"===U.tagName.toUpperCase()&&U.src||new URL("index.js",document.baseURI).href),r=t.dirname(e);return t.join(r,"..","stably-plugin")}catch{return}}();if(e&&i.existsSync(e))return{type:"local",path:e}}(),vt=()=>(bn.info("[fix] Starting SDK query",{model:ft,tools:st,mcpServers:Object.keys(at),resumeSessionId:E??null,subagentsEnabled:!!dt,subagentCount:Object.keys(Ge).length,useStablyAiProxy:We,aiProxyUrl:xr,anthropicBaseUrl:void 0,stablyPluginPath:wt?.path,stablyPluginExists:!!wt}),d.query({options:{executableArgs:["--max-old-space-size=4096"],tools:st,allowedTools:ot,betas:[],canUseTool:(e,t)=>(bn.debug("[fix] canUseTool called",{toolName:e}),Promise.resolve({behavior:"allow",updatedInput:t})),cwd:l,env:pt,hooks:{PostToolUse:lt,PreToolUse:ut},includePartialMessages:!0,agents:dt,mcpServers:at,model:ft,permissionMode:"default",plugins:wt?[wt]:void 0,systemPrompt:yt,...E?{resume:E}:{}},prompt:b??Pe})),_t=()=>{if(b&&0!==B.length){for(const e of B)b.pushText(e);B.length=0,x=!0,Se({status:"running"})}},Et=async()=>{y&&(I||(I=(async()=>{bn.info("Restarting MCP servers for chat mode"),Se({status:"running"}),_e({label:"Restarting browser tools..."});try{await(_?.interrupt?.())}catch(e){bn.warn("Failed to interrupt response during MCP restart",{error:e instanceof Error?e.message:String(e)})}await Qn(),b?.finish(),b=new os,L=0,x=!1,C=!1,W.clear(),_=vt(),D=!0,_e({label:"Restarting browser tools..."}),y&&b&&T&&(T.createdAtUserMessageSeq===k?T.attempts>=1||B.length>0?T=void 0:(T.attempts+=1,b.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")),T=void 0,x=!0,Se({status:"running"})):T=void 0),_t()})().finally(()=>{I=void 0,_t()})),await I)},It=async e=>{if(g&&x&&!G&&!j)j=(async()=>{bn.info("[fix] Interrupting for user message",{messageCount:e.length,phase:Q?.phase});try{await(_?.interrupt?.())}catch(e){bn.warn("[fix] Failed to interrupt response for user message",{error:e instanceof Error?e.message:String(e)})}await Qn(),b?.finish(),b=new os,W.clear(),_=vt();const t=e.map(e=>`[Message from web UI user]: ${e}`).join("\n\n");b.pushText(`[SYSTEM] The user sent a message while you were working. Read their message below, incorporate their feedback, and continue your task. Do not restart from scratch unless the user explicitly asks.\n\n${t}`),z=!0,x=!0})().finally(()=>{j=void 0}),await j;else for(const t of e)b?.pushText(`[Message from web UI user]: ${t}`)};if(Ke){const e=xr,t=`${e.replace(/\/$/,"")}/v1/messages`;bn.debug(`[fix] Pre-flight: POST ${t}`);const r=Date.now();try{const e=await fetch(t,{method:"POST",signal:AbortSignal.timeout(1e4),headers:{"x-api-key":Ke,"anthropic-version":"2023-06-01","content-type":"application/json"},body:"{}"}),n=await e.text().catch(()=>""),s=Date.now()-r;bn.debug(`[fix] Pre-flight: ${e.status} in ${s}ms — ${n.slice(0,300)}`),401===e.status||403===e.status?bn.error(`[fix] Pre-flight: AI proxy key rejected (${e.status}) at ${t}`):bn.info("[fix] Pre-flight: AI proxy key valid",{status:e.status,durationMs:s})}catch(t){bn.error("[fix] Pre-flight: AI proxy unreachable",{error:t instanceof Error?t.message:String(t),durationMs:Date.now()-r,url:e})}}bn.info("[fix] Creating initial agent query"),bn.flush(),_=vt(),bn.info("[fix] Agent query created, entering message loop"),"chat"!==r.mode&&b.pushText(Pe),pe.current=async()=>{V="CANCELED",await se("CANCELED"),ne({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:re(!0)}),X?.close(),le({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0}),ae?.close(),N&&(clearTimeout(N),N=void 0),bn.flush(),ve();try{await(_?.interrupt?.())}catch{}b?.finish(),we()};let Tt=0,xt=null;const St=setInterval(()=>{const e=Date.now()-J;xt?bn.info("[fix] Watchdog: message loop active",{messageCount:Tt,elapsed:e}):bn.info("[fix] Watchdog: waiting for first SDK message",{elapsed:e}),bn.flush()},15e3);St.unref();try{let e=!1;for(;;){if(!_){bn.info("[fix] No response object, exiting message loop");break}e=!1,bn.info("[fix] Entering for-await on SDK response");for await(const t of _){Tt++,xt||(xt=Date.now(),bn.info("[fix] First SDK message received",{waitDurationMs:xt-J,messageType:t.type,messageSubtype:"subtype"in t?t.subtype:void 0}));const n="session_id"in t&&"string"==typeof t.session_id?t.session_id:void 0;if(n&&n!==E&&(E=n,bn.debug("Captured Claude session id",{sessionId:E})),"stream_event"===t.type){const{event:e}=t;(Tt<=5||Tt%200==0)&&bn.debug("[fix] Stream event",{msgNum:Tt,eventType:e?.type});const r=e&&"object"==typeof e&&"parent_tool_use_id"in e&&"string"==typeof e.parent_tool_use_id?e.parent_tool_use_id:void 0;if("content_block_delta"===e?.type){const{delta:t}=e;if("text_delta"===t?.type&&t.text){if(y&&P&&!r)continue;D&&(D=!1,_e({label:void 0})),r&&W.has(r)?fe({toolUseId:r,kind:"text",content:t.text}):ye({text:t.text})}}"message_stop"===e?.type&&b&&(G=!1,b.allowNextTurn());continue}if("assistant"===t.type){const e="parent_tool_use_id"in t&&"string"==typeof t.parent_tool_use_id?t.parent_tool_use_id:void 0,{content:n}=t.message??{};if(Array.isArray(n)&&!e){const e=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("");e&&(bn.debug("Assistant message",{text:e}),"fix"===r.mode&&(ee(Ci,{type:"ai_message",summary:e.slice(0,200)}),te({type:"ai_message",summary:e.slice(0,200)})),oe&&ue({type:"ai_message",summary:e.slice(0,200)}))}if(W.size>0){const r=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):[];bn.debug("Assistant message with active subagents",{hasParentToolUseId:!!e,parentToolUseId:e,activeSubagentIds:Array.from(W.keys()),toolNames:r,fullMessageKeys:Object.keys(t),rawMessage:JSON.stringify(t).slice(0,500)})}if(Array.isArray(n))for(const t of n){if("tool_use"===t?.type){if("mcp__auto-heal-report__generate-report"===t.name&&(G=!0),"mcp__session-control__restart_mcp_servers"===t.name||"mcp__stably-agent-control__restart_mcp_servers"===t.name){ge({rawName:t.name,toolInput:t.input});continue}if(t.name.startsWith("mcp__session-control__")||t.name.startsWith("mcp__stably-agent-control__"))continue;if(Ri(t.name))continue;if(W.size>0&&bn.debug("Tool use detected with active subagents",{toolName:t.name,hasParentToolUseId:!!e,parentToolUseId:e,wouldRouteToSubagent:!!e&&W.has(e),activeSubagentIds:Array.from(W.keys())}),"Task"===t.name){const e=t.input,n=e&&"object"==typeof e?e: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(bn.info("[fix] Subagent started",{subagentType:s,description:o,toolUseId:t.id,activeSubagentCount:W.size+1}),W.set(t.id,{subagentType:s,description:o}),he({toolUseId:t.id,subagentType:s,description:o}),"fix"===r.mode){if("triage"===s){Te?.({phase:"triage"});const e={id:t.id,testDescription:"Triage",workerType:"triage",status:"running",summary:null,startedAt:Date.now(),endedAt:null,activity:[]};ne({phase:"triage",workers:[...Q?.workers??[],e]})}else if("fix-worker"===s){Z.add(o||t.id);const e={id:t.id,testDescription:o||t.id,workerType:"fix-worker",status:"running",summary:null,startedAt:Date.now(),endedAt:null,activity:[]};Te?.({phase:"fixing",totalTests:Z.size,currentTestDescription:o||null}),ne({phase:"fixing",totalTests:Z.size,currentTestDescription:o||null,lastTestDescription:o||Q?.lastTestDescription||null,workers:[...Q?.workers??[],e]})}else"validation"===s?(Te?.({phase:"validation",currentTestDescription:null}),ne({phase:"validation",currentTestDescription:null})):"context"===s&&ne({currentTestDescription:o||null});te({type:"tool_call",summary:`[${s}] ${o}`.trim()})}continue}if(e&&W.has(e)){const n=Pi(t.name),s=Ts(t.name,t.input),o=s?`${n} (${s})`:n;if(bn.debug("Subagent tool called",{tool:t.name,parentToolUseId:e}),fe({toolUseId:e,kind:"tool",content:o}),"fix"===r.mode){te({type:"tool_call",summary:o});const t=W.get(e);"fix-worker"!==t?.subagentType&&"triage"!==t?.subagentType||ee(e,{type:"tool_call",summary:o})}continue}if(e&&bn.debug("Tool with parent_tool_use_id but no matching subagent",{tool:t.name,parentToolUseId:e,activeSubagentIds:Array.from(W.keys())}),bn.debug("Tool called",{tool:t.name,input:t.input}),ge({rawName:t.name,toolInput:t.input}),"fix"===r.mode){const e=Pi(t.name),r=Ts(t.name,t.input),n=r?`${e} (${r})`:e;ee(Ci,{type:"tool_call",summary:n}),te({type:"tool_call",summary:n})}if(oe){const e=Pi(t.name),r=Ts(t.name,t.input),n=r?`${e} (${r})`:e;"initializing"===ce?.phase?le({phase:"generating",currentActivity:n}):"mcp__playwright-test__test_run"===t.name&&"generating"===ce?.phase?le({phase:"testing",currentActivity:n}):le({currentActivity:n}),ue({type:"tool_call",summary:n})}}if("text"===t?.type&&e&&W.has(e)){const n="string"==typeof t.text?t.text:"";if(n&&(fe({toolUseId:e,kind:"text",content:n}),"fix"===r.mode)){const t=W.get(e);"fix-worker"!==t?.subagentType&&"triage"!==t?.subagentType||ee(e,{type:"ai_message",summary:n.slice(0,200)})}}}continue}if("user"===t.type){const e="message"in t&&t.message&&"object"==typeof t.message&&"content"in t.message?t.message.content:void 0;if(Array.isArray(e))for(const t of e)if(t&&"object"==typeof t&&"type"in t&&"tool_result"===t.type&&"tool_use_id"in t){const e="string"==typeof t.tool_use_id?t.tool_use_id:void 0,n="is_error"in t&&!0===t.is_error,s="content"in t&&"string"==typeof t.content?t.content:void 0;if(bn.debug("Tool result",{toolUseId:e,isError:n,output:s?.slice(0,500)}),e&&W.has(e)){const t=W.get(e);if(bn.info("[fix] Subagent completed",{toolUseId:e,isError:n,subagentType:t?.subagentType,description:t?.description,activeSubagentCount:W.size-1}),Ie({toolUseId:e,status:n?"error":"complete"}),"fix"===r.mode&&"triage"===t?.subagentType){const t=n?"failed":"succeeded",r=s?s.slice(0,500):null,o=(Q?.workers??[]).map(n=>n.id===e?{...n,status:t,summary:r,endedAt:Date.now()}:n);ne({workers:o})}if("fix"===r.mode&&"fix-worker"===t?.subagentType){const t=n?"failed":"succeeded",r=s?s.slice(0,500):null,o=(Q?.workers??[]).map(n=>n.id===e?{...n,status:t,summary:r,endedAt:Date.now()}:n);n?(Te?.({failedTests:(Q?.failedTests??0)+1,currentTestDescription:null}),ne({failedTests:(Q?.failedTests??0)+1,currentTestDescription:null,workers:o})):(Te?.({fixedTests:(Q?.fixedTests??0)+1,currentTestDescription:null}),ne({fixedTests:(Q?.fixedTests??0)+1,currentTestDescription:null,workers:o}))}W.delete(e)}}continue}if("result"===t.type){if(bn.info("[fix] Agent result received",{subtype:t.subtype,messageCount:Tt,elapsed:Date.now()-J,activeSubagents:W.size,fixedTests:Q?.fixedTests,failedTests:Q?.failedTests,phase:Q?.phase}),g){if("success"===t.subtype){N&&(clearTimeout(N),N=void 0);for(const e of M)b?.pushText(`[Message from web UI user]: ${e}`);if(M=[],(oe||"fix"===r.mode)&&b){if(b.hasQueuedMessages()){bn.info("[ws] Queued web UI messages found, continuing agent"),x=!0,b.allowNextTurn();continue}if(await Ui(b,3e3)){bn.info("[ws] Web UI message received during grace period, continuing agent"),x=!0,b.allowNextTurn();continue}b.finish()}if(Te?.({phase:"complete",currentTestDescription:null,endedAt:Date.now()}),ne({phase:"complete",currentTestDescription:null,endedAt:Date.now(),isError:!1,workers:re(!1)}),le({phase:"complete",endedAt:Date.now(),isError:!1,currentActivity:null}),ct&&Ce.length>0){H.default.green("Created files:");for(const e of Ce)H.default.green(`- ${e}`)}const e=(e,t)=>`]8;;${e}${t}]8;;`,t=Ae?H.default.cyan(`📊 View Autoheal Report:\n ${e(Ae,H.default.cyan(H.default.bold(H.default.underline(Ae))))}`):void 0;Se({status:"success",result:t}),V="COMPLETED"}else j||z?bn.info("[fix] Suppressing error status: user-message interrupt in progress"):C?(V="CANCELED",ne({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:re(!0)}),le({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0})):(Te?.({endedAt:Date.now(),isError:!0}),ne({phase:"complete",endedAt:Date.now(),isError:!0,currentTestDescription:null,workers:re(!0)}),le({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),Se({error:"Run failed.",status:"error"}),process.exitCode=1,V="FAILED");C=!1;break}const n=y&&P;if("success"!==t.subtype?C||(Se({error:"Run failed.",status:"error"}),process.exitCode=1):Se(n?{status:"running"}:{status:"success"}),x=!1,C=!1,n){P=!1,bn.info("Processing deferred MCP restart request in chat mode"),await Et(),e=!0;break}D=!1,_e({label:void 0}),b?.allowNextTurn(),y&&L>0&&(L-=1,x=!0,Se({status:"running"}));continue}}if(j&&await j,z&&(z=!1,e=!0,Se({status:"running"}),bn.info("[fix] Resuming after user-message interrupt")),!e)break}}catch(e){C?(V="CANCELED",ne({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0,currentTestDescription:null,workers:re(!0)}),le({phase:"complete",endedAt:Date.now(),isError:!1,isInterrupted:!0})):(bn.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()-J}),Se({error:`Agent encountered an error: ${e}`,status:"error"}),process.exitCode=1,V="FAILED",ne({phase:"complete",endedAt:Date.now(),isError:!0,currentTestDescription:null,workers:re(!0)}),le({phase:"complete",endedAt:Date.now(),isError:!0,currentActivity:null}),bn.flush(),bn.printLogFileInfo())}finally{if(clearInterval(St),N&&(clearTimeout(N),N=void 0),bn.info("[fix] Agent session ending",{finalStatus:V,elapsed:Date.now()-J,totalMessages:Tt}),x=!1,C=!1,process.off("uncaughtException",n),b?.finish(),V){bn.info("[fix] Reporting final autoheal status",{status:V});const e=Date.now();await se(V),bn.info("[fix] Final autoheal status reported",{durationMs:Date.now()-e})}if(bn.info("[fix] Closing WebSocket progress reporter"),X?.close(),ae?.close(),Ze&&et){const e=Date.now();try{bn.info("[fix] Computing diff...");const t=await et.computeDiff();if(t&&t.trim().length>0){bn.info("[fix] Uploading diff...",{diffLength:t.length});const{diffBucketPath:n,uploadUrl:s}=await Ln({authHeader:o,contentType:"text/plain",orgId:c,runId:r.runId});await Dn({contentType:"text/plain",diff:t,uploadUrl:s}),await On({authHeader:o,diffBucketPath:n,orgId:c,runId:r.runId}),bn.info("[fix] Diff uploaded",{durationMs:Date.now()-e})}else bn.info("[fix] No diff to upload (empty or no changes)")}catch(t){bn.warn("[fix] Failed to upload diff",{error:t instanceof Error?t.message:String(t),durationMs:Date.now()-e})}}bn.info("[fix] Cleaning up diff tracker"),await(et?.cleanup()),bn.info("[fix] Running final cleanup"),await we(),bn.info("[fix] Cleanup complete")}},Li=z.default.object({runId:z.default.string(),timestamp:z.default.number()}),Di=class{entries=[];warnings=[];runId;command;executionMode;constructor(e){this.runId=e.runId,this.command=e.command,this.executionMode=e.executionMode}phaseStart(e,t){this.addEntry({phase:e,level:"info",message:t}),y.log.info(function(e,t){return`${H.default.bold(H.default.cyan(`[${e}]`))} ${t}`}(e,t))}phaseEnd(e,t){this.addEntry({phase:e,level:"info",message:t})}info(e){this.addEntry({phase:e.phase,level:"info",message:e.message,fields:e.fields})}warn(e){this.addEntry({phase:e.phase,level:"warn",message:e.message,fields:e.fields}),y.log.warn(H.default.yellow(` warn: ${e.message}`))}error(e){this.addEntry({phase:e.phase,level:"error",message:e.message,fields:e.fields}),y.log.error(H.default.red(` error: ${e.message}`))}emitWarning(e){this.warnings.push(e),this.addEntry({phase:"summary",level:"warn",message:e.message,fields:{warningCode:e.code,...e.details}}),y.log.warn(function(e){return H.default.yellow(` warning: ${e.code} - ${e.message}`)}(e))}getEntries(){return[...this.entries]}getWarnings(){return[...this.warnings]}getRunId(){return this.runId}getCommand(){return this.command}getExecutionMode(){return this.executionMode}addEntry(e){this.entries.push({runId:this.runId,command:this.command,executionMode:this.executionMode,phase:e.phase,timestamp:(new Date).toISOString(),level:e.level,message:e.message,...e.fields?{fields:e.fields}:{}})}};function Oi(e){return 0===e.length?[]:[H.default.yellow(H.default.bold("Warnings:")),...e.map(e=>H.default.yellow(` ${e.code}: ${e.message}`)),""]}function Bi(e){return e?[H.default.dim(`Next action: ${e}`),""]:[]}function Ni(e){const t=[],r="fix"===e.command?"Fix":"Build";if(t.push(""),"success"===e.status){const n=e.changedPaths.length;t.push(H.default.green(H.default.bold(`${r} succeeded`))+(n>0?H.default.green(` (${n} path${1!==n?"s":""} changed)`):"")),t.push(""),t.push(...Oi(e.warnings))}else if("failure"===e.status)t.push(H.default.red(H.default.bold(`${r} failed`))),e.errorCode&&t.push(H.default.red(` Error: ${e.errorCode}`)),t.push(""),t.push(...Oi(e.warnings)),t.push(...Bi(e.nextAction));else{const n=e.changedPaths.length,s=e.failedPaths.length,o=e.partialPaths.length;t.push(H.default.yellow(H.default.bold(`${r} partially succeeded`))+H.default.yellow(` (${n} changed, ${s} failed, ${o} partial)`)),t.push(""),t.push(...Oi(e.warnings)),t.push(...Bi(e.nextAction))}return t.push(H.default.dim(`Run ID: ${e.runId}`)),t.join("\n")}var $i=/^\/\*\*\r?\n \* @generated by stably build[\s\S]*?\*\/(?:\r?\n)*/;function ji(e){return!!e&&"object"==typeof e&&"code"in e}async function Mi({errorMessage:e,filePath:t}){try{return await G.default.readFile(t,"utf8")}catch(t){if(ji(t)&&"ENOENT"===t.code)throw new Error(e);throw t}}function Fi(e){return e.split(O.default.sep).join("/")}async function Hi(e){const t=[];return await async function e(r){let n;try{n=await G.default.readdir(r,{withFileTypes:!0})}catch{return}for(const s of n){const n=O.default.join(r,s.name);s.isDirectory()&&!s.isSymbolicLink()?await e(n):s.isFile()&&s.name.endsWith(".stably.md")&&t.push(n)}}(e),t.sort()}var Gi=/^---\r?\n([\s\S]*?)\r?\n---/;function zi(e,t){const r=[],n=Gi.exec(e);let s,o={};if(n){try{const e=R.parse(n[1]??"");o=e&&"object"==typeof e&&!Array.isArray(e)?e:{}}catch{y.log.warn(`Warning: Failed to parse YAML frontmatter in ${t}, treating as empty`),o={}}s=e.slice(n[0].length).replace(/^(\r?\n)+/,"")}else s=e;if(!s.trim())return{updated:e,addedFields:r};if(!o.name){const e=s.slice(0,1e4).replace(/```[\s\S]*?```/g,""),n=/^#\s+(.+)$/m.exec(e),i=O.default.basename(t).replace(/\.stably\.md$/,"").replace(/\.md$/,"");o.name=n?.[1]?.trim()??i,r.push("name")}return o.priority||(o.priority="medium",r.push("priority")),0===r.length?{updated:e,addedFields:r}:{updated:`---\n${R.stringify(o).trimEnd()}\n---\n\n${s}`,addedFields:r}}async function Yi(e){try{return(await G.default.readdir(e)).filter(e=>$n.test(e)).map(t=>O.default.join(e,t))}catch(e){if(ji(e)&&"ENOENT"===e.code)return[];throw e}}function Wi({runId:e,warnings:t,changedPaths:r=[],failedPaths:n=[],...s}){return{runId:e,command:"build",executionMode:"cli",warnings:t,changedPaths:r,failedPaths:n,partialPaths:[],...s}}async function Vi({force:e,inputFilePath:t}){const r=`build-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,n=new Di({runId:r,command:"build",executionMode:"cli"});n.phaseStart("preflight","Validating workspace and arguments");const s=process.cwd();n.info({phase:"preflight",message:"Input resolved",fields:{input:t}}),n.phaseEnd("preflight","Preflight complete"),n.phaseStart("scope","Resolving scope");const o=await Mi({filePath:t,errorMessage:`Prompt file not found: ${t}`});if(!o.trim())throw new Error(`Prompt file is empty: ${t}`);const i=ts(o),a=Fi(O.default.relative(s,t)),c=O.default.dirname(t),l=(u=t,O.default.basename(u).replace(/\.stably\.md$/,"").replace(/\.md$/,"").replace(/\.txt$/,""));var u;const d=await async function(e,t){return(await Yi(e)).find(e=>{const r=O.default.basename(e);return r.startsWith(`${t}.spec`)||r.startsWith(`${t}.test`)})}(c,l);if(!e&&d&&await async function({outputFilePath:e,promptHash:t}){try{return rs(await G.default.readFile(e,"utf8"))===t}catch(e){if(ji(e)&&"ENOENT"===e.code)return!1;throw e}}({outputFilePath:d,promptHash:i})){n.info({phase:"scope",message:"Hash unchanged, skipping build"});const e={code:"STABLY_WARNING_NO_CHANGES",message:"Test code is up to date (hash unchanged)"};n.emitWarning(e);const t=Wi({runId:r,status:"success",warnings:[e]});return n.phaseStart("summary","Build summary"),y.log.info(Ni(t)),n.phaseEnd("summary","Done"),y.log.success(H.default.green(`Skipped build: ${a} (hash unchanged)`)),"skipped"}n.info({phase:"scope",message:"Scope resolved",fields:{promptFile:a,promptHash:i,resolvedScopeCount:1,unmappedPaths:[],baseSource:"prompt-file",baseRef:a}}),n.phaseEnd("scope","Scope complete"),n.phaseStart("plan","Preparing prompt");const p=new Set(await Yi(c));await G.default.mkdir(c,{recursive:!0});const f=ns({promptFile:a,promptHash:i}),h=Fi(O.default.relative(s,c)||c),g=function({outputDir:e,promptContent:t,sourceSpecFile:r}){return["Compile this test specification into a Playwright test file.","",`Output directory: ${e}`,"","Choose output filename:",`- Look at existing test files in ${e} to determine the naming convention.`,"- Use the same extension pattern as existing tests (e.g., .test.ts or .spec.ts).","- If no existing tests, default to .spec.ts.","- Base the filename on the prompt content (e.g., login.spec.ts for login tests).","","File creation rules:","- Create your test file in the output directory with your chosen filename.","- You MAY create shared helper files (e.g., lib/auth.ts) if the prompt explicitly requests reusable components.","- Prefer single-file output unless shared helpers would significantly improve maintainability.","- Never modify unrelated existing files.","","Sync workflow for existing files:","1. Examine existing test files in the workspace and preserve hand edits where possible.","2. If a matching test file already exists, read it first and compare against the prompt specification.","3. Apply sync rules:"," - If file does not exist: CREATE from scratch."," - If file exists and already satisfies the prompt: KEEP behavior and make minimal edits only when needed."," - If file exists but only partially matches: UPDATE only changed scenarios so code aligns with prompt."," - If file structure conflicts heavily with prompt: REGENERATE the file content completely.","4. Prompt specification is the source of truth for final test behavior.","","Test verification:","After generating the test file, run the tests locally to verify they work correctly.","Use the appropriate test command (e.g., `pnpm stably test` or the repository's test command).","If tests fail, analyze the errors and iterate on the test code until all tests pass.","","Spec file linking:",`- Add \`// @stably.spec ${r}\` after the import statements.`,"- This links the test back to its source .md specification.","- If different test.describe()/test() blocks come from different .md files, add per-block @stably.spec instead.","","Prompt specification:",t].join("\n")}({outputDir:h,promptContent:o,sourceSpecFile:a});n.info({phase:"plan",message:"Agent prompt assembled",fields:{outputTarget:h,plannedPathCount:1,plannedPaths:[h],mode:"directory"}}),n.phaseEnd("plan","Plan complete"),n.phaseStart("execute","Running agent session"),process.exitCode=void 0;const m=Date.now();await ki({mode:"build",prompt:g,outputDir:c,customHeader:f});const b=Date.now()-m,w=process.exitCode;if("number"==typeof w&&0!==w){n.error({phase:"execute",message:`Build generation failed for: ${a}`,fields:{toolName:"runAgentSession",durationMs:b}});const e=Wi({runId:r,status:"failure",warnings:n.getWarnings(),failedPaths:[a],nextAction:"open_agent_session",errorCode:"STABLY_WRITE_FAILED"});throw n.phaseStart("summary","Build summary"),n.info({phase:"summary",message:"Run failed",fields:{errorCode:e.errorCode,nextAction:e.nextAction}}),y.log.info(Ni(e)),n.phaseEnd("summary","Done"),new Error(`Build generation failed for: ${a}`)}n.info({phase:"execute",message:"Agent session completed",fields:{toolName:"runAgentSession",durationMs:b}}),n.phaseEnd("execute","Agent session complete"),n.phaseStart("finalize","Applying results");const v=[];let _=d;if(!_&&(_=(await Yi(c)).find(e=>!p.has(e)),!_)){const e={path:a,status:"failed",error:"No new test file created"};v.push(e),n.info({phase:"finalize",message:"Write failed",fields:{path:e.path,writeStatus:e.status,error:e.error}});const t=Wi({runId:r,status:"failure",warnings:n.getWarnings(),failedPaths:[a],nextAction:"open_agent_session",errorCode:"STABLY_WRITE_FAILED"});throw n.phaseStart("summary","Build summary"),n.info({phase:"summary",message:"Run failed",fields:{errorCode:t.errorCode,nextAction:t.nextAction}}),y.log.info(Ni(t)),n.phaseEnd("summary","Done"),new Error(`Build finished but no new test file was created for: ${a}`)}const E=await Mi({filePath:_,errorMessage:`Build finished but output file was not created for: ${a}`}),I=function(e){return e.replace($i,"")}(E),T=E.startsWith(f)?E:`${f}\n\n${I}`;T!==E&&await G.default.writeFile(_,T,"utf8");const x=Fi(O.default.relative(s,_)),S={path:x,status:"success"};v.push(S),n.info({phase:"finalize",message:"Write succeeded",fields:{path:S.path,writeStatus:S.status}}),n.phaseEnd("finalize","Finalize complete"),n.phaseStart("summary","Build summary");const A=v.filter(e=>"success"===e.status).map(e=>e.path),C=v.filter(e=>"failed"===e.status).map(e=>e.path);let R;R=C.length>0?A.length>0?"partial":"failure":"success";const P=C.length>0,U=Wi({runId:r,status:R,warnings:n.getWarnings(),changedPaths:A,failedPaths:C,nextAction:P?"inspect_failed_paths":void 0,errorCode:P?"STABLY_WRITE_FAILED":void 0});return n.info({phase:"summary",message:"Run completed",fields:{status:U.status,changedPathCount:A.length,failedPathCount:C.length,...U.errorCode?{errorCode:U.errorCode}:{},...U.nextAction?{nextAction:U.nextAction}:{}}}),y.log.info(Ni(U)),n.phaseEnd("summary","Done"),y.log.success(H.default.green(`Built: ${x}`)),"built"}var qi=[{args:["--trace=on"],description:"Run Playwright tests",name:"test"},{args:[],description:"Install browser dependencies",name:"install"}],Ki=["You have two different versions of @playwright/test"];function Ji(e){const[t,...r]=ai(e),n=[t,...r.slice(0,-1)].join(" ");return(t,r)=>{let s=t.toString();for(const e of qi)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.shift(),void r.write(e.join("\n"))}r.write(s)}}async function Xi({overrideArgs:e,subcommand:r}){bn.info("[test] forwardToPlaywright starting",{subcommand:r,overrideArgs:e});const n=process.argv,o=n.findIndex((e,t)=>t>1&&e===r),a=-1===o?[]:n.slice(o+1),c="--"===a[0],l=c?a.slice(1):a;if(!c&&("--help"===l[0]||"-h"===l[0]))return async function({subcommand:e}){const t=qi.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=si();if(!n.installed||!n.inNodeModules)return void r('No Playwright project found in this directory or its parents.\nMake sure you\'re in a directory within your Playwright project, or run "stably init" to create a new playwright directory.');const{packageManager:o}=n;if(!o)return void r("Could not determine package manager.");r("Playwright options:"),r("");const[i,...a]=ai(o),c=Ji(o);return new Promise(t=>{const r=s.spawn(i,[...a,e,"--help"],{stdio:["inherit","pipe","pipe"],env:{...process.env,...process.env.CI?{}:{FORCE_COLOR:"1"}}});r.stdout?.on("data",e=>{c(e,process.stdout)}),r.stderr?.on("data",e=>{c(e,process.stderr)}),r.on("close",()=>{t()})})}({subcommand:r});const u=e??[],d=new Set(u.map(e=>{const[t]=e.split("=");return t})),p=[];for(let e=0;e<l.length;e++){const t=l[e],[r]=t.split("=");d.has(r)?!t.includes("=")&&e+1<l.length&&!l[e+1].startsWith("-")&&e++:p.push(t)}const f=[r,...u,...p];bn.info("[test] Forwarded args computed",{forwardedArgs:f}),bn.info("[test] Resolving Stably test environment");const h=Date.now(),g="test"===r?await An():void 0;bn.info("[test] Stably test environment resolved",{durationMs:Date.now()-h,hasCredentials:null!=g,hasWsUrl:!!g?.STABLY_WS_URL}),bn.info("[test] Setting up Stably reporter injection");const m="test"===r?function({forwardedArgs:e,hasCredentials:r}){if(!r)return console.warn("⚠️ Stably credentials not found. Test results will not be reported to Stably."),console.warn(" To enable reporting, either:"),console.warn(" • Run `npx stably login` to authenticate"),void console.warn(" • Or set STABLY_API_KEY and STABLY_PROJECT_ID environment variables\n");const n=process.cwd(),o=e=>{const r=function(e){let r=t.resolve(e);for(;;){if([t.join(r,"node_modules","@stablyai","playwright-test"),t.join(r,"node_modules",".pnpm","@stablyai+playwright-test")].some(e=>i.existsSync(e)))return!0;const e=t.dirname(r);if(e===r)return!1;r=e}}(e);return r||(console.warn("⚠️ @stablyai/playwright-test is not installed. Stably reporter will not be injected."),console.warn(" Install it with: npm install @stablyai/playwright-test"),console.warn(" Reference: ]8;;https://docs.stably.ai/getting-started/sdk-setup-guidehttps://docs.stably.ai/getting-started/sdk-setup-guide]8;;\n")),r},a=(e,r)=>{try{return function({baseConfigPath:e,projectDir:r}){const n=function(e){try{const t=s.execSync("npm pkg get type",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return"module"===JSON.parse(t.trim())}catch{return!1}}(r),o=n?"mts":"ts",a=t.dirname(t.resolve(e)),c=t.basename(e),l=t.join(a,`.stably-playwright-wrapper.config.${o}`),u=`\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\nconst buildReporterList = () => {\n const existingReporters = baseConfig.reporter;\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 projectId: process.env.STABLY_PROJECT_ID,\n notificationConfigs: extractNotificationConfigs(),\n errorSummary: resolveErrorSummary(),\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 projectId: process.env.STABLY_PROJECT_ID,\n notificationConfigs: extractNotificationConfigs(),\n errorSummary: resolveErrorSummary(existingOptions?.errorSummary),\n });\n\n // Keep all non-stably reporters, add our (merged or fresh) stably reporter\n const otherReporters = filterOutStablyReporter(reportersArray);\n return [...otherReporters, stablyReporterEntry];\n};\n\nexport default defineConfig({\n ...baseConfig,\n use: {\n ...baseConfig.use,\n trace: 'on',\n },\n reporter: buildReporterList(),\n});\n`.trim();return i.existsSync(a)||i.mkdirSync(a,{recursive:!0}),i.writeFileSync(l,u,"utf-8"),function(e){const r=t.join(e,".gitignore");try{if(i.existsSync(r)){const e=i.readFileSync(r,"utf-8");if(e.split("\n").map(e=>e.trim()).includes(ps))return;const t=e.length>0&&!e.endsWith("\n");i.appendFileSync(r,`${t?"\n":""}${ps}\n`)}else i.writeFileSync(r,`${ps}\n`)}catch{}}(a),l}({baseConfigPath:e,projectDir:r})}catch{return void console.warn("⚠️ Could not create Stably wrapper config. Reporter injection skipped.")}};if(e.some(e=>"--config"===e||"-c"===e||e.startsWith("--config=")||e.startsWith("-c="))){const r=e.findIndex(e=>"--config"===e||"-c"===e);if(-1!==r&&e[r+1]){const s=t.resolve(n,e[r+1]),i=t.dirname(s);if(!o(i))return;const c=a(s,i);if(!c)return;return e[r+1]=c,c}const s=e.findIndex(e=>e.startsWith("--config=")||e.startsWith("-c="));if(-1!==s){const r=t.resolve(n,e[s].split("=")[1]),i=t.dirname(r);if(!o(i))return;const c=a(r,i);if(!c)return;const l=e[s].startsWith("--config=")?"--config=":"-c=";return e[s]=`${l}${c}`,c}}const c=hs(n);if(!c)return;const l=t.dirname(c);if(!o(l))return;const u=a(c,l);return u?(e.push("--config",u),u):void 0}({forwardedArgs:f,hasCredentials:null!=g}):void 0;bn.info("[test] Reporter injection setup complete",{hasWrapperConfig:!!m}),bn.info("[test] Spawning Playwright process"),await function(e,t={}){bn.info("[test] Detecting Playwright installation");const r=si();bn.info("[test] Playwright installation check",{installed:r.installed,inNodeModules:r.inNodeModules,packageManager:r.packageManager,packageName:r.packageName}),r.installed||(console.error('Playwright is not installed. Please run "stably init" to install it.'),process.exit(1)),r.inNodeModules||(console.error("Playwright is present in your project, but not in node_modules. Please install your dependencies before proceeding."),process.exit(1));const{packageManager:n}=r;n||(console.error("Playwright installation not found. Could not determine your package manager (tried pnpm, yarn, and npm)."),process.exit(1));const[o,...i]=ai(n),a=Sn(t.env),c=[o,...i,...e];bn.info("[test] Spawning Playwright process",{command:c.join(" "),pid:process.pid});const l=Date.now(),u=s.spawn(o,[...i,...e],{stdio:["inherit","pipe","pipe"],env:{...a,...process.env.CI?{}:{FORCE_COLOR:"1"}}});bn.info("[test] Playwright process spawned",{childPid:u.pid});const d=Ji(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 Ki)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=>{bn.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()&&(bn.error("[test] Playwright process error",{error:e.message,childPid:u.pid}),t(e))}),u.on("close",t=>{if(!h())return;bn.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)})})})}(f,{env:g,onClose:()=>{var e;bn.info("[test] Playwright process closed, cleaning up wrapper config"),(e=m)&&i.existsSync(e)&&i.rmSync(e)}})}function Qi(e=""){process.stdout.write(`${e}\n`)}function Zi(...e){process.stderr.write(`${e.join(" ")}\n`)}var ea="stably",ta=`https://registry.npmjs.org/${ea}/latest`,ra=w.z.object({version:w.z.string()});function na(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 sa(e,t){const r=na(e),n=na(t);return!(!r||!n)&&(n.major>r.major||!(n.major<r.major)&&(n.minor>r.minor||!(n.minor<r.minor)&&n.patch>r.patch))}var oa=O.default.join(j.default.homedir(),".stably"),ia=O.default.join(oa,"update-check.json"),aa=`https://registry.npmjs.org/${ea}/latest`,ca=w.z.object({lastCheck:w.z.number(),latestVersion:w.z.string()}),la=!1,ua=!1,da=async()=>{if(ua)try{const{shutdown:e}=await import("@hyperdx/node-opentelemetry"),t=process.stderr.write.bind(process.stderr),r=process.stdout.write.bind(process.stdout),n=(e,...t)=>{const r=t[0];return!("string"!=typeof r||!r.includes("OpenTelemetry"))||!(!Buffer.isBuffer(r)||!r.toString().includes("OpenTelemetry"))||e(...t)};process.stderr.write=(...e)=>n(t,...e),process.stdout.write=(...e)=>n(r,...e);try{await e()}finally{process.stderr.write=t,process.stdout.write=r}}catch{}};!function(){const e=function(){try{const e=$.default.readFileSync(ia,"utf-8");return ca.parse(JSON.parse(e))}catch{return null}}(),t=Date.now();if((null==e||t-e.lastCheck>=18e5)&&function(){const e=`\n const https = require('https');\n const fs = require('fs');\n const url = '${aa}';\n const cacheFile = ${JSON.stringify(ia)};\n const cacheDir = ${JSON.stringify(oa)};\n\n const req = https.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{s.spawn(process.execPath,["-e",e],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()}catch{}}(),null!=e&&sa(vr,e.latestVersion)){if(la)return;la=!0;let t=!1;const r=()=>{if(t)return;t=!0;const r=`${H.default.yellow(`update available (${vr} → ${e.latestVersion})`)} - run \`${ea} upgrade\` to get the latest version\n`;try{$.default.writeSync(2,r)}catch{}};process.once("beforeExit",r),process.once("exit",r)}}(),se.cwdChanged&&bn.debug("Changed working directory",{cwd:se.newCwd});for(const e of se.envFilesLoaded)bn.debug("Loaded env file",{path:e});for(const e of se.envFileErrors)bn.warn(e);var pa=process.argv.findIndex(e=>"-v"===e||"--verbose"===e);-1!==pa&&process.argv.splice(pa,1);var fa=process.argv.findIndex(e=>"--no-telemetry"===e);-1!==fa&&process.argv.splice(fa,1),bn.info("CLI starting",{version:vr,args:process.argv.slice(2),cwd:process.cwd()}),process.on("unhandledRejection",(e,t)=>{bn.error("Unhandled promise rejection",{reason:e instanceof Error?{message:e.message,stack:e.stack}:e,promise:String(t)}),bn.flush(),bn.printLogFileInfo()}),process.on("uncaughtException",(e,t)=>{"EPIPE"!==e.code&&(bn.error("Uncaught exception",{error:{message:e.message,stack:e.stack,name:e.name},origin:t}),bn.flush(),bn.printLogFileInfo())});var ha=new r.Command;ha.name("stably").description("AI-assisted Playwright testing CLI").version(vr),ha.enablePositionalOptions(),ha.showHelpAfterError(),ha.exitOverride(),ha.configureHelp({subcommandTerm:e=>{const t=e.registeredArguments.map(e=>e.required?`<${e.name()}>`:`[${e.name()}]`).join(" ");return t?`${e.name()} ${t}`:e.name()}});var ga=[];ha.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>{ga.push(e)}});var ma=()=>{const e=ha.helpInformation().trimEnd();return e?`${e}\n`:""},ya=(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},ba=()=>{process.stdout.write(ma())};ha.command("help [command...]").description("Show help for a command (e.g. stably help create)").action(e=>{if(!e||0===e.length)return void ba();const t=ya(ha,e);if(!t)return process.stderr.write(`Unknown command: ${e.join(" ")}\n`),ba(),void(process.exitCode=1);var r;r=t,process.stdout.write((e=>{const t=e.helpInformation().trimEnd();return t?`${t}\n`:""})(r))}),ha.action(()=>ki({mode:"chat",getHelpText:ma})),ha.command("login").description("Authenticate with Stably in your browser").action(Zr),ha.command("logout").description("Clear stored Stably credentials").action(async()=>{const e=vn();e&&(y.log.warn(`Environment variables ${H.default.cyan("STABLY_API_KEY")} and ${H.default.cyan("STABLY_PROJECT_ID")} are set.`),y.log.warn("They will continue to be used for authentication even after logout."),y.log.warn("Unset them if you want to fully de-authenticate this shell/session."));const t=await Hr();if(!t)return void y.outro(e?H.default.yellow("No stored OAuth login found to clear."):H.default.yellow("You are not logged in."));const r=y.spinner();r.start("Logging out..."),await(async e=>{try{await fetch(`${Ir}/api/backend/v1/logout`,{body:JSON.stringify({refresh_token:e}),headers:{"Content-Type":"application/json"},method:"POST"})}catch{}})(t.refreshToken),await zr(),await Wr(),r.stop(H.default.green("✓ Logged out")),y.outro(H.default.green("You have been logged out successfully."))}),ha.command("whoami").description("Show auth status and current project").action(async()=>{y.log.info(`${H.default.bold("CLI Version:")} ${H.default.cyan(vr)}`);const e=vn();if(e){y.log.info(H.default.dim("Authentication: Environment variables")),y.log.info(` ${H.default.bold("API Key:")} ${H.default.cyan(e.apiKey.slice(0,8))}...`),y.log.info(` ${H.default.bold("Project ID:")} ${H.default.cyan(e.projectId)}`);const t=await Hr();if(t){let e;try{e=Dr(t.accessToken).email}catch{e=void 0}y.log.warn("Stored OAuth login detected but will be ignored (env auth takes precedence)."),e&&y.log.info(` ${H.default.bold("OAuth Email:")} ${H.default.cyan(e)}`),y.log.info(` ${H.default.bold("Tip:")} Unset env vars to use OAuth`)}return void y.outro(H.default.green("Authenticated via environment variables"))}const t=await Hr();if(!t)return void y.outro(H.default.yellow("Not logged in. Run `stably login` to authenticate."));let r;try{r=Dr(t.accessToken).email}catch{r=void 0}const n=await Yr();if(!n)return y.log.info(H.default.dim("Authentication: OAuth (not linked to a project)")),r&&y.log.info(` ${H.default.bold("Email:")} ${H.default.cyan(r)}`),void y.outro(H.default.yellow("Logged in but this directory is not linked to a project. Run `stably login` to link."));const s=await(async()=>Or(process.cwd(),$r))(),o=s?O.default.dirname(s):process.cwd(),i=O.default.relative(process.cwd(),o)||".";y.log.info(H.default.dim("Authentication: OAuth")),r&&y.log.info(` ${H.default.bold("Email:")} ${H.default.cyan(r)}`),y.log.info(` ${H.default.bold("Organization:")} ${H.default.cyan(n.orgName)}`),y.log.info(` ${H.default.bold("Project:")} ${H.default.cyan(n.projectName)}`),y.log.info(` ${H.default.bold("Linked at:")} ${H.default.dim(i)}`),y.outro(H.default.green("Authenticated"))}),ha.command("build [input...]").description("Compile test specification files (.stably.md) into Playwright tests").option("--force","Force regeneration even if prompt is unchanged").action(async(e,t)=>{try{await async function(e){const{inputs:t,force:r}=e,n=process.cwd();let o;if(0===t.length){const e=function(e){try{return s.execSync('git ls-files --cached --others --exclude-standard "*.stably.md"',{cwd:e,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).split("\n").map(e=>e.trim()).filter(Boolean)}catch{return[]}}(n);o=e.map(e=>O.default.resolve(n,e))}else o=await async function(e,t){const r=[];for(const n of e){const e=O.default.resolve(t,n);let s;try{s=await G.default.stat(e)}catch{r.push(e);continue}if(s.isDirectory()){const t=await Hi(e);r.push(...t)}else r.push(e)}const n=new Set,s=[];for(const e of r){const t=O.default.resolve(e);n.has(t)||(n.add(t),s.push(t))}return s}(t,n);if(0===o.length)throw new Error("No .stably.md files found. Create a test specification file (e.g., login.stably.md) and try again.");const{fixedFiles:i}=await async function(e,t){const r=[],n=[];for(const s of e){let e=s;try{await G.default.stat(e)}catch{n.push(e);continue}if(e.endsWith(".md")&&!e.endsWith(".stably.md")){const n=e.replace(/\.md$/,".stably.md");try{await G.default.rename(e,n);const s=Fi(O.default.relative(t,e)),o=Fi(O.default.relative(t,n)),i={code:"STABLY_WARNING_FILE_RENAMED",message:`Renamed ${s} → ${o} (test specs must use .stably.md extension)`,details:{oldPath:s,newPath:o}};r.push(i),y.log.warn(H.default.yellow(` ⚠ ${i.message}`)),e=n}catch(t){if(!(t instanceof Error&&"code"in t)||"EEXIST"!==t.code&&"ENOTEMPTY"!==t.code)throw t;y.log.warn(H.default.yellow(` ⚠ Skipping rename: ${n} already exists`)),e=n}}if(!e.endsWith(".stably.md")){n.push(e);continue}const o=await G.default.readFile(e,"utf8"),{updated:i,addedFields:a}=zi(o,e);if(a.length>0){await G.default.writeFile(e,i,"utf8");const n=Fi(O.default.relative(t,e)),s={code:"STABLY_WARNING_FRONTMATTER_ADDED",message:`Added missing frontmatter fields to ${n}: ${a.join(", ")}`,details:{path:n,addedFields:a}};r.push(s),y.log.warn(H.default.yellow(` ⚠ ${s.message}`))}n.push(e)}return{fixedFiles:n,warnings:r}}(o,n);o=i,y.log.info(H.default.bold(`Found ${o.length} test specification${1!==o.length?"s":""}`));for(const e of o){const t=Fi(O.default.relative(n,e));y.log.info(H.default.dim(` ${t}`))}y.log.info("");const a={built:[],skipped:[],failed:[]};for(const e of o){const t=Fi(O.default.relative(n,e));try{"built"===await Vi({force:r,inputFilePath:e})?a.built.push(t):a.skipped.push(t)}catch(e){const r=e instanceof Error?e.message:String(e);y.log.error(H.default.red(`Failed to build ${t}: ${r}`)),a.failed.push(t)}}return function(e){if(y.log.info(""),y.log.info(H.default.bold("Build Summary")),y.log.info(` ${H.default.green(`${e.built.length} built`)} ${H.default.dim(`${e.skipped.length} skipped (unchanged)`)} ${e.failed.length>0?H.default.red(`${e.failed.length} failed`):H.default.dim("0 failed")}`),e.failed.length>0){y.log.info(""),y.log.error(H.default.red("Failed files:"));for(const t of e.failed)y.log.error(H.default.red(` - ${t}`))}}(a),a.failed.length>0&&(process.exitCode=1),a}({inputs:e,force:t.force??!1})}catch(e){const t=e instanceof Error?e.message:String(e);process.stderr.write(`${t}\n`),process.exitCode=1}}),ha.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=>{y.intro(`Starting development server for port ${e.port}...`);const t=await Tn(),r="oauth"===t.type?`${t.auth.context.orgName}-${t.auth.context.projectName}`.toLowerCase().replace(/[^a-z0-9-]/g,""):`project-${t.auth.projectId}`.toLowerCase(),n=y.spinner();n.start("Starting development server...");const s=await P.startTunnel(`http://localhost:${e.port}`,{subdomain:r});n.stop(`Your local environment is available at: ]8;;${s.url}${H.default.underline(H.default.cyan(s.url))}]8;;`)}),ha.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 ki({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)=>ki({mode:"single",prompt:e,outputDir:t.output})),ha.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 s.execSync("git rev-parse --is-inside-work-tree",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),!0}catch{return!1}})(process.cwd())||(bn.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 bn.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(Jt))if(Jt[r].detect({env:e,cwd:t}))return{isCi:!0,...Jt[r].configuration({env:e,cwd:t})};return{isCi:Boolean(e.CI),...(r={env:e,cwd:t},{commit:vt(r),branch:_t(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 bn.debug("Run ID detected from CI environment",{runId:r}),t(r);bn.debug("No explicit run ID or CI environment detected, checking last-run.json");const n=await(async()=>{try{const e=await Or(process.cwd(),".stably/last-run.json");if(!e)return;const t=await m.readFile(e,"utf-8");return{...Li.parse(JSON.parse(t)),filePath:e}}catch{return}})();if(n){const e=(Date.now()-n.timestamp)/36e5;return bn.debug("Run ID found in last-run.json",{runId:n.runId,timestamp:n.timestamp,filePath:n.filePath,ageHours:Math.round(e)}),e>24&&bn.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)}bn.debug("No run ID found in last-run.json")})(e);return t||(process.stderr.write('Run ID is required. Either:\n 1. Run "stably test" first (run ID will be auto-detected)\n 2. Provide a run ID: stably fix <runId>\n 3. Run in CI (auto-detected from environment)\n'),process.exit(1)),ki({mode:"fix",runId:t})}),ha.command("init").description("Initialize Playwright and Stably SDK in your project").action(async()=>ki({mode:"init"})),ha.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;Qi(H.default.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(ta,{signal:e.signal});if(!t.ok)throw new Error(`Failed to fetch latest version: ${t.statusText}`);return ra.parse(await t.json()).version}finally{clearTimeout(t)}}();return{current:vr,latest:e,isOutdated:sa(vr,e)}}()}catch(e){return Zi(H.default.red("Failed to check for updates:"),e instanceof Error?e.message:e),void(process.exitCode=1)}if(Qi(`Current version: ${H.default.yellow(r.current)}`),Qi(`Latest version: ${H.default.green(r.latest)}`),Qi(),!r.isOutdated)return void Qi(H.default.green("✓ You are already on the latest version!"));if(Qi(H.default.yellow(`⚠ A new version is available: ${r.current} → ${r.latest}`)),Qi(),t)return Qi(H.default.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"))return"npx";try{const t=s.execSync("npm root -g",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-npm"}catch{}if(e.includes("node_modules/stably"))return"global-npm";try{const t=s.execSync("pnpm root -g",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-pnpm"}catch{}try{const t=s.execSync("yarn global dir",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-yarn-classic"}catch{}try{const t=s.execSync("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",`${ea}@latest`],description:`npm install -g ${ea}@latest`};case"global-pnpm":return{command:"pnpm",args:["add","-g",`${ea}@latest`],description:`pnpm add -g ${ea}@latest`};case"global-yarn-classic":return{command:"yarn",args:["global","add",`${ea}@latest`],description:`yarn global add ${ea}@latest`};case"npx":return{command:"npx",args:[`${ea}@latest`],description:`npx ${ea}@latest (always uses latest)`}}}(n);if("npx"===n)return Qi(H.default.dim("You are running via npx, which always fetches the latest version.")),void Qi(H.default.dim(`Simply run: ${H.default.white("npx stably")} to use the latest version.`));"unknown"===n?(Qi(H.default.yellow("Could not detect installation method. Falling back to npm.")),Qi()):"global-yarn-berry"===n&&(Qi(H.default.yellow("Yarn Berry does not support global packages. Falling back to npm.")),Qi()),Qi(`Upgrade command: ${H.default.cyan(o.description)}`),Qi(),Qi(H.default.cyan("Upgrading...")),Qi();try{await(i=o.command,a=o.args,new Promise((e,t)=>{const r=s.spawn(i,a,{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)})})),Qi(),Qi(H.default.green("✓ Upgrade complete!")),Qi(H.default.dim(`Run ${H.default.white("stably --version")} to verify.`))}catch(e){Zi(H.default.red("Upgrade failed:"),e instanceof Error?e.message:e),Qi(),Qi(H.default.dim("You can try manually running:")),Qi(H.default.cyan(` ${o.description}`)),process.exitCode=1}var i,a}(e)),qi.forEach(({args:e,description:t,name:r})=>{ha.command(r).description(t).helpOption(!1).helpCommand(!1).allowUnknownOption(!0).allowExcessArguments(!0).passThroughOptions().action(()=>Xi({overrideArgs:e,subcommand:r}))});var wa=()=>{0!==ga.length&&(process.stderr.write(ga.join("")),ga=[])};(async()=>{await(async()=>{if(!ua&&"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":vr,"node.version":process.version,"os.platform":process.platform}}),ua=!0}catch{}})();try{await ha.parseAsync(process.argv),bn.info("CLI completed successfully")}catch(e){if(!(e=>!!e&&"object"==typeof e&&"code"in e)(e))throw bn.error("Unexpected CLI error",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),wa(),bn.flush(),bn.printLogFileInfo(),await da(),e;const t="number"==typeof e.exitCode?e.exitCode:1,r=process.argv.slice(2).find(e=>!e.startsWith("-")),n=!!r&&!!ya(ha,[r]);if(("commander.excessArguments"===e.code||"commander.unknownCommand"===e.code)&&r&&!n)return ga=[],bn.warn("Unknown command",{command:r}),process.stderr.write(`command '${r}' not found\n`),ba(),void(process.exitCode=t);bn.debug("Commander error",{code:e.code,exitCode:t}),wa(),process.exitCode=t}finally{bn.flush(),await da()}})();