stably 4.4.4 → 4.4.5

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 +1 -1
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"),o=require("child_process"),s=require("process"),i=require("fs"),a=require("url"),c=require("os");require("timers/promises");var l=require("stream"),d=require("util"),u=require("@anthropic-ai/claude-agent-sdk"),p=require("picocolors"),f=require("simple-git"),h=require("crypto"),g=require("fs/promises"),m=require("@clack/prompts"),y=require("readline/promises"),_=require("zod"),b=require("open"),E=require("http"),w=require("pino"),I=require("sonic-boom"),v=require("zod/v3"),T=require("react"),x=require("react/jsx-runtime"),S=require("yaml"),R=require("@stablyhq/runner-sdk");function C(e){return e&&e.__esModule?e:{default:e}}var A=C(t),P=C(o),U=C(s),L=C(i),O=C(c),B=C(l),D=C(p),N=C(h),k=C(g),j=C(_),$=C(b),M=C(E),H=C(w),F=C(I),G={cwdChanged:!1,newCwd:void 0,envFilesLoaded:[],envFileErrors:[]},Y=process.argv.findIndex(e=>"-C"===e||"--cwd"===e);if(-1!==Y&&process.argv[Y+1]){const e=process.argv[Y+1];process.chdir(e),G.cwdChanged=!0,G.newCwd=e,process.argv.splice(Y,2)}for(var z=[],W=0;W<process.argv.length;)if("--env-file"===process.argv[W]){const e=process.argv[W+1];e&&!e.startsWith("-")?(z.push(e),process.argv.splice(W,2)):W++}else W++;for(const t of z){const r=A.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})`;G.envFileErrors.push(e),process.stderr.write(`${e}\n`)}else G.envFilesLoaded.push(r)}var K={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 q(e){return(/\d+(?!.*\d+)/.exec(e)||[])[0]}function V(e){return e?/^(?:refs\/heads\/)?(?<branch>.+)$/i.exec(e)[1]:void 0}var J={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:V(r?e.SYSTEM_PULLREQUEST_TARGETBRANCH:e.BUILD_SOURCEBRANCH),pr:t,isPr:r,prBranch:V(r?e.SYSTEM_PULLREQUEST_SOURCEBRANCH:void 0),root:e.BUILD_REPOSITORY_LOCALPATH}}},X={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})},Q={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})},Z={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}}},ee={detect:({env:e})=>Boolean(e.BUDDY_WORKSPACE_ID),configuration({env:e}){const t=q(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}}},te="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function re(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ne,oe,se,ie,ae,ce,le,de,ue={exports:{}};var pe,fe,he,ge,me,ye,_e,be,Ee,we,Ie,ve,Te,xe,Se,Re={exports:{}},Ce={};function Ae(){if(ve)return Ie;ve=1;const e=A.default,t=function(){if(he)return fe;he=1;const e=A.default,t=function(){if(de)return le;de=1;const e="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,t=A.default,r=e?";":":",n=function(){if(ce)return ae;var e;function t(r,n,o){if("function"==typeof n&&(o=n,n={}),!o){if("function"!=typeof Promise)throw new TypeError("callback not provided");return new Promise(function(e,o){t(r,n||{},function(t,r){t?o(t):e(r)})})}e(r,n||{},function(e,t){e&&("EACCES"===e.code||n&&n.ignoreErrors)&&(e=null,t=!1),o(e,t)})}return ce=1,e="win32"===process.platform||te.TESTING_WINDOWS?function(){if(oe)return ne;oe=1,ne=r,r.sync=function(r,n){return t(e.statSync(r),r,n)};var e=L.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 o=r[n].toLowerCase();if(o&&e.substr(-o.length).toLowerCase()===o)return!0}return!1}(t,r)}function r(r,n,o){e.stat(r,function(e,s){o(e,!e&&t(s,r,n))})}return ne}():function(){if(ie)return se;ie=1,se=t,t.sync=function(t,n){return r(e.statSync(t),n)};var e=L.default;function t(t,n,o){e.stat(t,function(e,t){o(e,!e&&r(t,n))})}function r(e,t){return e.isFile()&&function(e,t){var r=e.mode,n=e.uid,o=e.gid,s=void 0!==t.uid?t.uid:process.getuid&&process.getuid(),i=void 0!==t.gid?t.gid:process.getgid&&process.getgid(),a=parseInt("100",8),c=parseInt("010",8);return r&parseInt("001",8)||r&c&&o===i||r&a&&n===s||r&(a|c)&&0===s}(e,t)}return se}(),ae=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}},ae}(),o=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),s=(t,n)=>{const o=n.colon||r,s=t.match(/\//)||e&&t.match(/\\/)?[""]:[...e?[process.cwd()]:[],...(n.path||process.env.PATH||"").split(o)],i=e?n.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",a=e?i.split(o):[""];return e&&-1!==t.indexOf(".")&&""!==a[0]&&a.unshift(""),{pathEnv:s,pathExt:a,pathExtExe:i}},i=(e,r,i)=>{"function"==typeof r&&(i=r,r={}),r||(r={});const{pathEnv:a,pathExt:c,pathExtExe:l}=s(e,r),d=[],u=n=>new Promise((s,i)=>{if(n===a.length)return r.all&&d.length?s(d):i(o(e));const c=a[n],l=/^".*"$/.test(c)?c.slice(1,-1):c,u=t.join(l,e),f=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;s(p(f,n,0))}),p=(e,t,o)=>new Promise((s,i)=>{if(o===c.length)return s(u(t+1));const a=c[o];n(e+a,{pathExt:l},(n,i)=>{if(!n&&i){if(!r.all)return s(e+a);d.push(e+a)}return s(p(e,t,o+1))})});return i?u(0).then(e=>i(null,e),i):u(0)};return le=i,i.sync=(e,r)=>{r=r||{};const{pathEnv:i,pathExt:a,pathExtExe:c}=s(e,r),l=[];for(let o=0;o<i.length;o++){const s=i[o],d=/^".*"$/.test(s)?s.slice(1,-1):s,u=t.join(d,e),p=!d&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;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 o(e)},le}(),r=function(){if(pe)return Re.exports;pe=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 Re.exports=e,Re.exports.default=e,Re.exports}();function n(n,o){const s=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:s[r({env:s})],pathExt:o?e.delimiter:void 0})}catch(e){}finally{c&&process.chdir(i)}return l&&(l=e.resolve(a?n.options.cwd:"",l)),l}return fe=function(e){return n(e)||n(e,!0)}}(),r=function(){if(ge)return Ce;ge=1;const e=/([()\][%!^"`<>&|;, *?])/g;return Ce.command=function(t){return t.replace(e,"^$1")},Ce.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},Ce}(),n=function(){if(we)return Ee;we=1;const e=L.default,t=function(){if(be)return _e;be=1;const e=ye?me:(ye=1,me=/^#!(.*)/);return _e=(t="")=>{const r=t.match(e);if(!r)return null;const[n,o]=r[0].replace(/#! ?/,"").split(" "),s=n.split("/").pop();return"env"===s?o:o?`${s} ${o}`:s}}();return Ee=function(r){const n=Buffer.alloc(150);let o;try{o=e.openSync(r,"r"),e.readSync(o,n,0,150,0),e.closeSync(o)}catch(e){}return t(n.toString())},Ee}(),o="win32"===process.platform,s=/\.(?:com|exe)$/i,i=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;return Ie=function(a,c,l){c&&!Array.isArray(c)&&(l=c,c=null);const d={command:a,args:c=c?c.slice(0):[],options:l=Object.assign({},l),file:void 0,original:{command:a,args:c}};return l.shell?d:function(a){if(!o)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=!s.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}(d)}}var Pe=re(function(){if(Se)return ue.exports;Se=1;const e=P.default,t=Ae(),r=function(){if(xe)return Te;xe=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 Te={hookChildProcess:function(t,n){if(!e)return;const o=t.emit;t.emit=function(e,s){if("exit"===e){const e=r(s,n);if(e)return o.call(t,"error",e)}return o.apply(t,arguments)}},verifyENOENT:r,verifyENOENTSync:function(r,n){return e&&1===r&&!n.file?t(n.original,"spawnSync"):null},notFoundError:t},Te}();function n(n,o,s){const i=t(n,o,s),a=e.spawn(i.command,i.args,i.options);return r.hookChildProcess(a,i),a}return ue.exports=n,ue.exports.spawn=n,ue.exports.sync=function(n,o,s){const i=t(n,o,s),a=e.spawnSync(i.command,i.args,i.options);return a.error=a.error||r.verifyENOENTSync(a.status,i),a},ue.exports._parse=t,ue.exports._enoent=r,ue.exports}());function Ue(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 Le=(e,t)=>({name:`SIGRT${t+1}`,number:Oe+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),Oe=34,Be=[{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"}],De=()=>{const e=(()=>{const e=64-Oe+1;return Array.from({length:e},Le)})();return[...Be,...e].map(Ne)},Ne=({name:e,number:t,description:r,action:n,forced:o=!1,standard:s})=>{const{signals:{[e]:i}}=c.constants,a=void 0!==i;return{name:e,number:a?i:t,description:r,supported:a,action:n,forced:o,standard:s}},ke=({name:e,number:t,description:r,supported:n,action:o,forced:s,standard:i})=>[e,{name:e,number:t,description:r,supported:n,action:o,forced:s,standard:i}],je=(()=>{const e=De();return Object.fromEntries(e.map(ke))})();(()=>{const e=De(),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:o,supported:s,action:i,forced:a,standard:l}=r;return{[e]:{name:n,number:e,description:o,supported:s,action:i,forced:a,standard:l}}})(r,e));Object.assign({},...t)})();var $e=({stdout:e,stderr:t,all:r,error:n,signal:o,exitCode:s,command:i,escapedCommand:a,timedOut:c,isCanceled:l,killed:d,parsed:{options:{timeout:u,cwd:p=U.default.cwd()}}})=>{s=null===s?void 0:s;const f=void 0===(o=null===o?void 0:o)?void 0:je[o].description,h=(({timedOut:e,timeout:t,errorCode:r,signal:n,signalDescription:o,exitCode:s,isCanceled:i})=>e?`timed out after ${t} milliseconds`:void 0!==r?`failed with ${r}`:void 0!==n?`was killed with ${n} (${o})`:void 0!==s?`failed with exit code ${s}`:"failed")({timedOut:c,timeout:u,errorCode:n&&n.code,signal:o,signalDescription:f,exitCode:s,isCanceled:l}),g=`Command ${h}: ${i}`,m="[object Error]"===Object.prototype.toString.call(n),y=m?`${g}\n${n.message}`:g,_=[y,t,e].filter(Boolean).join("\n");return m?(n.originalMessage=n.message,n.message=_):n=new Error(_),n.shortMessage=y,n.command=i,n.escapedCommand=a,n.exitCode=s,n.signal=o,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=d&&!c,n},Me=["stdin","stdout","stderr"],He=[];He.push("SIGHUP","SIGINT","SIGTERM"),"win32"!==process.platform&&He.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),"linux"===process.platform&&He.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var Fe,Ge,Ye=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,ze=Symbol.for("signal-exit emitter"),We=globalThis,Ke=Object.defineProperty.bind(Object),qe=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(We[ze])return We[ze];Ke(We,ze,{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 o of this.listeners[e])n=!0===o(t,r)||n;return"exit"===e&&(n=this.emit("afterExit",t,r)||n),n}},Ve=class{},Je=globalThis.process;Ye(Je)?new class extends Ve{#e="win32"===Je.platform?"SIGINT":"SIGHUP";#t=new qe;#r;#n;#o;#s={};#i=!1;constructor(e){super(),this.#r=e,this.#s={};for(const t of He)this.#s[t]=()=>{const r=this.#r.listeners(t);let{count:n}=this.#t;const o=e;if("object"==typeof o.__signal_exit_emitter__&&"number"==typeof o.__signal_exit_emitter__.count&&(n+=o.__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.#o=e.reallyExit,this.#n=e.emit}onExit(e,t){if(!Ye(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 He)try{const t=this.#s[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,He.forEach(e=>{const t=this.#s[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.#o,this.#t.count-=1)}#c(e){return Ye(this.#r)?(this.#r.exitCode=e||0,this.#t.emit("exit",this.#r.exitCode,null),this.#o.call(this.#r,this.#r.exitCode)):0}#a(e,...t){const r=this.#n;if("exit"===e&&Ye(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)}}(Je):new class extends Ve{onExit(){return()=>{}}load(){}unload(){}},new TextEncoder,function(){if(Ge)return Fe;Ge=1;const{PassThrough:e}=B.default;Fe=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",o),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",o.bind(null,e)),e.once("error",r.emit.bind(r,"error")),e.pipe(r,{end:!1}),this)}function o(e){!(t=t.filter(function(t){return t!==e})).length&&r.readable&&r.end()}}}();var Xe=(async()=>{})().constructor.prototype;["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(Xe,e)]);var Qe=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],Ze=/^[\w.-]+$/,et=d.debuglog("execa").enabled,tt=(e,t)=>String(e).padStart(t,"0"),rt=(e,t,r={})=>{const n=Pe._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||U.default.cwd(),execPath:U.default.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:et,...r}).env=(({env:e,extendEnv:t,preferLocal:r,localDir:n,execPath:o})=>{const s=t?{...U.default.env,...e}:e;return r?(({env:e=U.default.env,...t}={})=>{const r=Ue({env:e={...e}});return t.path=e[r],e[r]=(({cwd:e=U.default.cwd(),path:t=U.default.env[Ue()],preferLocal:r=!0,execPath:n=U.default.execPath,addExecPath:o=!0}={})=>{const s=e instanceof URL?a.fileURLToPath(e):e,i=A.default.resolve(s),c=[];return r&&((e,t)=>{let r;for(;r!==t;)e.push(A.default.join(t,"node_modules/.bin")),r=t,t=A.default.resolve(t,"..")})(c,i),o&&((e,t,r)=>{const n=t instanceof URL?a.fileURLToPath(t):t;e.push(A.default.resolve(r,n,".."))})(c,n,i),[...c,t].join(A.default.delimiter)})(t),e})({env:s,cwd:n,execPath:o}):s})(r),r.stdio=(e=>{if(!e)return;const{stdio:t}=e;if(void 0===t)return Me.map(t=>e[t]);if((e=>Me.some(t=>void 0!==e[t]))(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${Me.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,Me.length);return Array.from({length:r},(e,r)=>t[r])})(r),"win32"===U.default.platform&&"cmd"===A.default.basename(e,".exe")&&t.unshift("/q"),{file:e,args:t,options:r,parsed:n}},nt=(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 ot(e,t,r){const n=rt(e,t,r),o=((e,t)=>Qe(e,t).join(" "))(e,t),s=((e,t)=>Qe(e,t).map(e=>(e=>"string"!=typeof e||Ze.test(e)?e:`"${e.replaceAll('"','\\"')}"`)(e)).join(" "))(e,t);((e,{verbose:t})=>{t&&U.default.stderr.write(`[${(()=>{const e=new Date;return`${tt(e.getHours(),2)}:${tt(e.getMinutes(),2)}:${tt(e.getSeconds(),2)}.${tt(e.getMilliseconds(),3)}`})()}] ${e}\n`)})(s,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=P.default.spawnSync(n.file,n.args,{...n.options,input:a})}catch(e){throw $e({error:e,stdout:"",stderr:"",all:"",command:o,escapedCommand:s,parsed:n,timedOut:!1,isCanceled:!1,killed:!1})}const l=nt(n.options,c.stdout,c.error),d=nt(n.options,c.stderr,c.error);if(c.error||0!==c.status||null!==c.signal){const e=$e({stdout:l,stderr:d,error:c.error,signal:c.signal,exitCode:c.status,command:o,escapedCommand:s,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:o,escapedCommand:s,exitCode:0,stdout:l,stderr:d,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}}function st(e){try{return ot("git",["rev-parse","HEAD"],e).stdout}catch{return}}function it(e){try{const t=ot("git",["rev-parse","--abbrev-ref","HEAD"],e).stdout;if("HEAD"===t){const t=ot("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 at=/^(?:.*)@(?:.*):(?:\d+\/)?(.*)\.git$/,ct=/^\/(.*)\.git$/;function lt(e){if(e){if(e.match(at))return e.replace(at,"$1");try{return new URL(e).pathname.replace(ct,"$1")}catch{return}}}var dt,ut={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:lt(e.BUILDKITE_REPO),pr:t,isPr:r,prBranch:r?e.BUILDKITE_BRANCH:void 0,root:e.BUILDKITE_BUILD_CHECKOUT_PATH}}},pt={detect:({env:e})=>Boolean(e.CIRCLECI),configuration({env:e}){const t=e.CIRCLE_PR_NUMBER||q(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}`}}},ft="https://cirrus-ci.com",ht={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:`${ft}/build/${e.CIRRUS_BUILD_ID}`,job:e.CIRRUS_TASK_ID,jobUrl:`${ft}/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}}},gt={detect:({env:e})=>Boolean(e.CODEBUILD_BUILD_ID),configuration:({env:e,cwd:t})=>({name:"AWS CodeBuild",service:"codebuild",commit:st({env:e,cwd:t}),build:e.CODEBUILD_BUILD_ID,branch:it({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})},mt={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}}},yt={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}}},_t=({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?V(t.pull_request.base.ref):void 0,pr:t.pull_request.number}}catch{}return{pr:void 0,branch:void 0}},bt={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=V("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?_t({env:e}):void 0}}},Et={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}}},wt={detect:({env:e})=>Boolean(e.JENKINS_URL),configuration({env:e,cwd:t}){const r=e.ghprbPullId||e.gitlabMergeRequestId||e.CHANGE_ID,n=Boolean(r),o=e.GIT_LOCAL_BRANCH||e.GIT_BRANCH||e.gitlabBranch||e.BRANCH_NAME;return{name:"Jenkins",service:"jenkins",commit:e.ghprbActualCommit||e.GIT_COMMIT||st({env:e,cwd:t}),branch:n?e.ghprbTargetBranch||e.gitlabTargetBranch:o,build:e.BUILD_NUMBER,buildUrl:e.BUILD_URL,root:e.WORKSPACE,pr:r,isPr:n,prBranch:n?e.ghprbSourceBranch||e.gitlabSourceBranch||o:void 0}}},It={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}}},vt={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})},Tt={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}}},xt={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}}},St={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}}},Rt={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||st({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}}},Ct={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}}},At={};function Pt(){if(dt)return At;dt=1,Object.defineProperty(At,"__esModule",{value:!0}),At.of=At.PropertiesFile=void 0;var e,t=(e=L.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(),o=e.substring(r+1).trim();if(this.objs.hasOwnProperty(n))if(Array.isArray(this.objs[n]))this.objs[n].push(o);else{let e=this.objs[n];this.objs[n]=[e,o]}else{const e=o.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 At.PropertiesFile=r,At.of=function(...e){let t=new r;return t.of.apply(t,e),t},At}var Ut=re(Pt()),Lt={root:"teamcity.build.workingDir",branch:"teamcity.build.branch"},Ot=e=>{try{return Ut.of(e)}catch{return}},Bt=({env:e,cwd:t})=>{const r=e.TEAMCITY_BUILD_PROPERTIES_FILE?Ot(e.TEAMCITY_BUILD_PROPERTIES_FILE):void 0,n=r?r.get("teamcity.configuration.properties.file"):void 0,o=n?Ot(n):n;return Object.fromEntries(Object.keys(Lt).map(n=>[n,(r?r.get(Lt[n]):void 0)||(o?o.get(Lt[n]):void 0)||("branch"===n?it({env:e,cwd:t}):void 0)]))},Dt={appveyor:K,azurePipelines:J,bamboo:X,bitbucket:Q,bitrise:Z,buddy:ee,buildkite:ut,circleci:pt,cirrus:ht,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:gt,codefresh:mt,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:yt,github:bt,gitlab:Et,jenkins:wt,netlify:It,puppet:vt,sail:Tt,screwdriver:xt,scrutinizer:St,semaphore:Rt,shippable:Ct,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,...Bt({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:V(e.JB_SPACE_GIT_BRANCH),slug:t&&r?`${t.toLowerCase()}/${r}`:void 0}}}},Nt=class e{git;config;snapshotTreeHash;snapshotIndexPath;constructor(e){this.config=e,this.git=f.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-${h.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-${h.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 kt(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 kt(this.snapshotIndexPath),this.snapshotIndexPath=void 0),this.snapshotTreeHash=void 0}};async function kt(e){try{await g.unlink(e)}catch{}}var jt="x-stably-org-id",$t={bodySerializer:e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t)},Mt=({allowReserved:e,explode:t,name:r,style:n,value:o})=>{if(!t){const t=(e?o:o.map(e=>encodeURIComponent(e))).join((e=>{switch(e){case"form":default:return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20"}})(n));switch(n){case"label":return`.${t}`;case"matrix":return`;${r}=${t}`;case"simple":return t;default:return`${r}=${t}`}}const s=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(n),i=o.map(t=>"label"===n||"simple"===n?e?t:encodeURIComponent(t):Ht({allowReserved:e,name:r,value:t})).join(s);return"label"===n||"matrix"===n?s+i:i},Ht=({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)}`},Ft=({allowReserved:e,explode:t,name:r,style:n,value:o,valueOnly:s})=>{if(o instanceof Date)return s?o.toISOString():`${r}=${o.toISOString()}`;if("deepObject"!==n&&!t){let t=[];Object.entries(o).forEach(([r,n])=>{t=[...t,r,e?n:encodeURIComponent(n)]});const s=t.join(",");switch(n){case"form":return`${r}=${s}`;case"label":return`.${s}`;case"matrix":return`;${r}=${s}`;default:return s}}const i=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(n),a=Object.entries(o).map(([t,o])=>Ht({allowReserved:e,name:"deepObject"===n?`${r}[${t}]`:t,value:o})).join(i);return"label"===n||"matrix"===n?i+a:a},Gt=/\{[^{}]+\}/g;function Yt(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 zt,Wt=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},Kt=({parameters:e={},...t}={})=>r=>{const n=[];if(r&&"object"==typeof r)for(const o in r){const s=r[o];if(null==s)continue;const i=e[o]||t;if(Array.isArray(s)){const e=Mt({allowReserved:i.allowReserved,explode:!0,name:o,style:"form",value:s,...i.array});e&&n.push(e)}else if("object"==typeof s){const e=Ft({allowReserved:i.allowReserved,explode:!0,name:o,style:"deepObject",value:s,...i.object});e&&n.push(e)}else{const e=Ht({allowReserved:i.allowReserved,name:o,value:s});e&&n.push(e)}}return n.join("&")},qt=(e,t)=>!!t&&!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`)),Vt=e=>(({baseUrl:e,path:t,query:r,querySerializer:n,url:o})=>{let s=(e??"")+(o.startsWith("/")?o:`/${o}`);t&&(s=(({path:e,url:t})=>{let r=t;const n=t.match(Gt);if(n)for(const t of n){let n=!1,o=t.substring(1,t.length-1),s="simple";o.endsWith("*")&&(n=!0,o=o.substring(0,o.length-1)),o.startsWith(".")?(o=o.substring(1),s="label"):o.startsWith(";")&&(o=o.substring(1),s="matrix");const i=e[o];if(null==i)continue;if(Array.isArray(i)){r=r.replace(t,Mt({explode:n,name:o,style:s,value:i}));continue}if("object"==typeof i){r=r.replace(t,Ft({explode:n,name:o,style:s,value:i,valueOnly:!0}));continue}if("matrix"===s){r=r.replace(t,`;${Ht({name:o,value:i})}`);continue}const a=encodeURIComponent("label"===s?`.${i}`:i);r=r.replace(t,a)}return r})({path:t,url:s}));let i=r?n(r):"";return i.startsWith("?")&&(i=i.substring(1)),i&&(s+=`?${i}`),s})({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:"function"==typeof e.querySerializer?e.querySerializer:Kt(e.querySerializer),url:e.url}),Jt=(e,t)=>{const r={...e,...t};return r.baseUrl?.endsWith("/")&&(r.baseUrl=r.baseUrl.substring(0,r.baseUrl.length-1)),r.headers=Qt(e.headers,t.headers),r},Xt=e=>{const t=[];return e.forEach((e,r)=>{t.push([r,e])}),t},Qt=(...e)=>{const t=new Headers;for(const r of e){if(!r)continue;const e=r instanceof Headers?Xt(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},Zt=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}},er=Kt({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),tr={"Content-Type":"application/json"},rr=(e={})=>({...$t,headers:tr,parseAs:"auto",querySerializer:er,...e}),nr=(e={})=>{let t=Jt(rr(),e);const r=()=>({...t}),n={error:new Zt,request:new Zt,response:new Zt},o=async e=>{const r={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:Qt(t.headers,e.headers),serializedBody:void 0};return r.security&&await(async({security:e,...t})=>{for(const r of e){if(qt(t,r.name))continue;const e=await Wt(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:Vt(r)}},s=async e=>{const{opts:t,url:r}=await o(e),s={redirect:"follow",...t,body:Yt(t)};let i=new Request(r,s);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 o of n.error.fns)o&&(r=await o(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 d=await c.text();let u;try{u=JSON.parse(d)}catch{}const p=u??d;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=>s({...t,method:e}),a=e=>async t=>{const{opts:r,url:s}=await o(t);return(({onRequest:e,onSseError:t,onSseEvent:r,responseTransformer:n,responseValidator:o,sseDefaultRetryDelay:s,sseMaxRetryAttempts:i,sseMaxRetryDelay:a,sseSleepFn:c,url:l,...d})=>{let u;const p=c??(e=>new Promise(t=>setTimeout(t,e))),f=async function*(){let c=s??3e3,f=0;const h=d.signal??(new AbortController).signal;for(;!h.aborted;){f++;const s=d.headers instanceof Headers?d.headers:new Headers(d.headers);void 0!==u&&s.set("Last-Event-ID",u);try{const t={redirect:"follow",...d,body:d.serializedBody,headers:s,signal:h};let i=new Request(l,t);e&&(i=await e(l,t));const a=d.fetch??globalThis.fetch,p=await a(i);if(!p.ok)throw new Error(`SSE failed: ${p.status} ${p.statusText}`);if(!p.body)throw new Error("No body in SSE response");const f=p.body.pipeThrough(new TextDecoderStream).getReader();let g="";const m=()=>{try{f.cancel()}catch{}};h.addEventListener("abort",m);try{for(;;){const{done:e,value:t}=await f.read();if(e)break;g+=t;const s=g.split("\n\n");g=s.pop()??"";for(const e of s){const t=e.split("\n"),s=[];let i,a;for(const e of t)if(e.startsWith("data:"))s.push(e.replace(/^data:\s*/,""));else if(e.startsWith("event:"))i=e.replace(/^event:\s*/,"");else if(e.startsWith("id:"))u=e.replace(/^id:\s*/,"");else if(e.startsWith("retry:")){const t=Number.parseInt(e.replace(/^retry:\s*/,""),10);Number.isNaN(t)||(c=t)}let l=!1;if(s.length){const e=s.join("\n");try{a=JSON.parse(e),l=!0}catch{a=e}}l&&(o&&await o(a),n&&(a=await n(a))),r?.({data:a,event:i,id:u,retry:c}),s.length&&(yield a)}}}finally{h.removeEventListener("abort",m),f.releaseLock()}break}catch(e){if(t?.(e),void 0!==i&&f>=i)break;const 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 o=new Request(e,t);for(const e of n.request.fns)e&&(o=await e(o,r));return o},url:s})};return{buildUrl:Vt,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:s,setConfig:e=>(t=Jt(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")}},or=nr(rr({baseUrl:"https://api.stably.ai"})),sr="4.4.4",ir=process.env.STABLY_API_URL||"https://api.stably.ai",ar=process.env.AUTH_URL||"https://auth.stably.ai",cr=process.env.AUTH_CLIENT_ID||"288007877071cce81f269428ea78653a",lr=process.env.AI_PROXY_URL||"https://ai-proxy.stably.ai",dr="http://localhost:9876/auth/callback",ur=()=>zt||(zt=nr(rr({baseUrl:ir,headers:{"X-STABLY-CLI-VERSION":sr,"X-STABLY-SOURCE":"cli"}}))),pr=async(e,t)=>{const r=await(n={body:{accessToken:e,orgId:t},client:ur()},(n.client??or).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},fr=_.z.object({org_id:_.z.string(),org_name:_.z.string()}),hr=_.z.object({email:_.z.string(),org_id_to_org_member_info:_.z.record(_.z.string(),fr).optional(),org_member_info:fr.optional(),user_id:_.z.string()});_.z.object({email:_.z.string(),firstName:_.z.string().optional(),lastName:_.z.string().optional(),organizations:_.z.array(_.z.object({id:_.z.string(),name:_.z.string()})),userId:_.z.string()});var gr=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)},mr=e=>{try{const t=hr.parse(gr(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"}`)}},yr=A.default.join(O.default.homedir(),".stably"),_r=A.default.join(yr,"auth.json"),br=".stably",Er="project.json",wr=j.default.object({accessToken:j.default.string(),expiresAt:j.default.number(),idToken:j.default.string().optional(),refreshToken:j.default.string()}),Ir=j.default.object({orgId:j.default.string(),orgName:j.default.string(),projectId:j.default.string(),projectName:j.default.string()}),vr=async()=>{try{const e=await g.readFile(_r,"utf-8");return wr.parse(JSON.parse(e))}catch{return}},Tr=async e=>{await g.mkdir(yr,{recursive:!0}),await g.writeFile(_r,JSON.stringify(e,null,2),{mode:384})},xr=async()=>{try{await g.unlink(_r)}catch{}},Sr=async e=>{let t=e;const{root:r}=A.default.parse(t);for(;t!==r;){const e=A.default.join(t,br);try{return await g.access(e),e}catch{t=A.default.dirname(t)}}},Rr=async()=>{try{const e=await Sr(process.cwd());if(!e)return;const t=A.default.join(e,Er),r=await g.readFile(t,"utf-8");return Ir.parse(JSON.parse(r))}catch{return}},Cr=async()=>{try{const e=await Sr(process.cwd());e&&await g.unlink(A.default.join(e,Er))}catch{}},Ar=e=>Date.now()>=e.expiresAt-3e5,Pr=async e=>{const t=new URLSearchParams({client_id:cr,grant_type:"refresh_token",refresh_token:e}),r=await fetch(`${ar}/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}},Ur=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`,Lr=(e,t,r)=>{e.writeHead(t,{"Content-Type":"text/html"}),e.end(r)},Or=(e,t)=>{const r=new URLSearchParams({client_id:cr,code_challenge:e,code_challenge_method:"S256",redirect_uri:dr,response_type:"code",state:t});return`${ar}/propelauth/oauth/authorize?${r.toString()}`},Br=async e=>{const t=m.spinner();let r;t.start("Loading user info...");try{r=mr(e.accessToken),t.stop(D.default.green(`✓ Logged in as ${D.default.cyan(r.email)}`))}catch(e){t.stop(D.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: ${D.default.cyan(e[0].name)}`),e[0];if(!process.stdin.isTTY)return m.log.info(`Auto-selecting organization: ${D.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 o;t.start("Getting org credentials...");try{const r=await pr(e.accessToken,n.id);o={accessToken:r.accessToken,expiresAt:Date.now()+1e3*r.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken},t.stop(D.default.green("✓ Credentials obtained"))}catch(e){t.stop(D.default.red("✗ Failed to get org credentials"));const r=e instanceof Error?e.message:"Unknown error";return m.log.error(r),{success:!1}}const s=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:ur(),path:{orgId:t}},(n.client??or).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(D.default.green("✓ Projects loaded"))}catch(e){r.stop(D.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 ${D.default.underline(D.default.cyan("https://app.stably.ai"))}`);if(1===n.length)return m.log.info(`Using project: ${D.default.cyan(n[0].name)}`),n[0];if(!process.stdin.isTTY)return m.log.info(`Auto-selecting project: ${D.default.cyan(n[0].name)}`),n[0];const o=await m.select({message:"Select a project",options:n.map(e=>({label:e.name,value:e.id}))});return m.isCancel(o)?void 0:n.find(e=>e.id===o)})(o.accessToken,n.id);return s?(await(async e=>{const t=A.default.join(process.cwd(),br),r=A.default.join(t,Er);await g.mkdir(t,{recursive:!0}),await g.writeFile(r,JSON.stringify(e,null,2)),await(async e=>{const t=A.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 o=/^# Stably CLI\n\.stably\/?$/m,s=/^\.stably\/?$/m;if(o.test(e)){const n=e.replace(o,`\n${r}\n`);await g.writeFile(t,n)}else if(s.test(e)){const n=e.replace(s,`\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:s.id,projectName:s.name}),m.log.info(D.default.dim("Linked this directory to your Stably project.")),{scopedTokens:o,success:!0}):(m.log.warn("Project selection cancelled."),{success:!1})},Dr=async()=>{if(tn())return m.log.warn(`Environment variables ${D.default.cyan("STABLY_API_KEY")} and ${D.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(D.default.yellow("Login skipped - using environment variable authentication."));const e=await vr();if(e){if(!Ar(e)){if(await Rr())return void m.outro(D.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 Br(e);return void(t.success?(await Tr(t.scopedTokens),m.outro(D.default.green("Setup complete! You can now use Stably CLI."))):m.outro(D.default.yellow("Setup incomplete. Run `stably login` to try again.")))}const t=m.spinner();t.start("Refreshing session...");try{const r=await Pr(e.refreshToken);t.stop(D.default.green("✓ Session refreshed"));const n=await Rr();if(n){t.start("Getting org credentials...");try{const e=await pr(r.accessToken,n.orgId),o={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:r.idToken,refreshToken:r.refreshToken};await Tr(o),t.stop(D.default.green("✓ Credentials obtained")),m.outro(D.default.green("Login successful"))}catch{await Tr(r),t.stop(D.default.yellow("Using full credentials")),m.outro(D.default.green("Login successful"))}}else{const e=await Br(r);e.success?(await Tr(e.scopedTokens),m.outro(D.default.green("Setup complete! You can now use Stably CLI."))):m.outro(D.default.yellow("Setup incomplete. Run `stably login` to try again."))}return}catch{t.stop(D.default.yellow("Session expired, proceeding with fresh login...")),await xr(),await Cr()}}const{authorizeUrl:t,waitForCallback:r}=(()=>{const{authorizeUrl:e,codeVerifier:t,state:r}=(()=>{const e=N.default.randomBytes(32).toString("base64url"),t=(r=e,N.default.createHash("sha256").update(r).digest("base64url"));var r;const n=N.default.randomBytes(16).toString("base64url");return{authorizeUrl:Or(t,n),codeVerifier:e,state:n}})();return{authorizeUrl:e,waitForCallback:async()=>(async(e,t)=>{const r=await(n=e,new Promise((e,t)=>{const r=setTimeout(()=>{s.close(),e({error:"Login timed out",success:!1})},3e5),o=()=>{clearTimeout(r)},s=M.default.createServer((t,r)=>{const i=new a.URL(t.url||"","http://localhost:9876");if("/auth/callback"!==i.pathname)return r.writeHead(404),void r.end("Not found");const c=i.searchParams.get("code"),l=i.searchParams.get("state"),d=i.searchParams.get("error");return d?(Lr(r,400,Ur(d)),o(),s.close(),void e({error:d,success:!1})):c&&l?l!==n?(Lr(r,400,Ur("Invalid state parameter (possible CSRF attack)")),o(),s.close(),void e({error:"State mismatch",success:!1})):(Lr(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'),o(),s.close(),void e({code:c,state:l,success:!0})):(Lr(r,400,Ur("Missing code or state parameter")),o(),s.close(),void e({error:"Missing code or state parameter",success:!1}))});s.on("error",e=>{o(),"EADDRINUSE"!==e.code?t(new Error(`Failed to start callback server: ${e.message}`)):t(new Error("Port 9876 is already in use. Please close the application using it and try again."))}),s.listen(9876)}));var n;if(!r.success)throw new Error(r.error);return(async(e,t)=>{const r=new URLSearchParams({client_id:cr,code:e,code_verifier:t,grant_type:"authorization_code",redirect_uri:dr}),n=await fetch(`${ar}/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 o=await n.json();return{accessToken:o.access_token,expiresAt:Date.now()+1e3*o.expires_in,idToken:o.id_token,refreshToken:o.refresh_token}})(r.code,t)})(r,t)}})();m.log.info("Opening browser for authentication..."),m.log.info(D.default.dim("If browser doesn't open, visit:")),m.log.info(D.default.underline(D.default.cyan(t)));try{await $.default(t)}catch{m.log.warn("Could not open browser automatically. Please open the URL above manually.")}const n=m.spinner();let o;n.start("Waiting for authentication...");try{o=await r(),n.stop(D.default.green("✓ Authentication successful"))}catch(e){n.stop(D.default.red("✗ Authentication failed"));const t=e instanceof Error?e.message:"Unknown error";m.outro(D.default.red(`Login failed: ${t}`)),process.exit(1)}const s=await Br(o);s.success?(await Tr(s.scopedTokens),m.outro(D.default.green("Setup complete! You can now use Stably CLI."))):(m.outro(D.default.yellow("Setup incomplete. Run `stably login` to try again.")),process.exit(1))},Nr={fatal:60,error:50,warn:40,info:30,debug:20,trace:10},kr=new Set(["help","login","logout","whoami","tunnel","create","fix","init","upgrade","test","show-report","codegen"]),jr=(new Date).toISOString().split("T")[0],$r=A.default.join(O.default.tmpdir(),"stably-logs",jr);L.default.mkdirSync($r,{recursive:!0});var Mr,Hr=process.argv.includes("--verbose")||process.argv.includes("-v"),Fr=process.env.STABLY_LOG_LEVEL?.toLowerCase(),Gr=Hr?"debug":void 0!==(Mr=Fr)&&Mr in Nr?Fr:"warn",Yr=Nr[Gr],zr=null,Wr=null,Kr=null,qr=[],Vr=!1,Jr=e=>{if(!Vr){zr=(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 A.default.join($r,`${t}-${r}.log`)})(e),(e=>{const t=["","=".repeat(60),"Stably CLI Debug Log",`Version: ${sr}`,`Generated: ${(new Date).toISOString()}`,`Node: ${process.version}`,`Platform: ${process.platform} ${O.default.release()}`,`CWD: ${process.cwd()}`,`Args: ${process.argv.slice(2).join(" ")}`,`Log Level (console): ${Gr}`,"=".repeat(60),""].join("\n");e.write(t)})(Wr=new F.default({dest:zr,minLength:4096,sync:!1,append:!0})),Kr=H.default({level:"debug",timestamp:H.default.stdTimeFunctions.isoTime,base:{version:sr}},Wr);for(const{level:e,msg:t,context:r}of qr)r?Kr[e](r,t):Kr[e](t);qr=[],Vr=!0,Hr&&process.stderr.write(`${D.default.dim(`Debug log: ${zr}`)}\n\n`)}},Xr=(()=>{const e=process.argv.slice(2).find(e=>!e.startsWith("-"));return e&&kr.has(e)?e:null})();Xr&&Jr(Xr);var Qr=e=>(t,r)=>{if(Kr?r?Kr[e](r,t):Kr[e](t):qr.push({level:e,msg:t,context:r}),(e=>Nr[e]>=Yr)(e)){const r=((e,t)=>`${{fatal:D.default.bgRed(D.default.white(" FATAL ")),error:D.default.red("error"),warn:D.default.yellow("warn"),info:D.default.cyan("info"),debug:D.default.dim("debug"),trace:D.default.dim("trace")}[e]} ${t}`)(e,t);process.stderr.write(`${r}\n`)}},Zr={fatal:Qr("fatal"),error:Qr("error"),warn:Qr("warn"),info:Qr("info"),debug:Qr("debug"),trace:Qr("trace"),initSession:e=>{Vr||Jr(e)},getLogFilePath:()=>zr,flush:()=>{if(Wr)try{Wr.flushSync()}catch{}},printLogFileInfo:()=>{zr&&(process.stderr.write(`\n${D.default.dim("Debug log written to:")}\n`),process.stderr.write(` ${D.default.cyan(zr)}\n`),process.stderr.write(`${D.default.dim("Share this file with support for assistance.")}\n`))},getPinoLogger:()=>Kr};setInterval(()=>{Zr.flush()},3e4).unref(),process.on("beforeExit",()=>{Zr.flush()});var en=e=>{const t=()=>{Zr.flush(),Hr&&Zr.printLogFileInfo(),process.removeListener(e,t),process.kill(process.pid,e)};return t};process.on("SIGINT",en("SIGINT")),process.on("SIGTERM",en("SIGTERM"));var tn=()=>{const e=process.env.STABLY_API_KEY?.trim(),t=process.env.STABLY_PROJECT_ID?.trim();if(e&&t)return Zr.debug("Environment auth detected",{hasApiKey:!0,hasProjectId:!0}),{apiKey:e,projectId:t};Zr.debug("Environment auth not set",{hasApiKey:!!e,hasProjectId:!!t})},rn=!1,nn=()=>{rn||(rn=!0,m.log.warn("Both environment variable auth and stored OAuth login were detected."),m.log.warn(`Honoring environment variables (${D.default.cyan("STABLY_API_KEY")} + ${D.default.cyan("STABLY_PROJECT_ID")}).`),m.log.warn("To use OAuth login instead, unset those environment variables."))},on=async()=>{Zr.debug("Checking for stored auth tokens");const e=await vr();if(!e)return void Zr.debug("No stored auth tokens found");const t=Ar(e);if(Zr.debug("Auth tokens status",{expired:t}),!t){const t=await Rr(),r=(e=>{try{const t=hr.parse(gr(e));if(t.org_id_to_org_member_info)return"full";if(t.org_member_info)return"org"}catch{return"unknown"}return"unknown"})(e.accessToken);if(Zr.debug("Token scope check",{scope:r,hasContext:!!t}),t&&"full"===r)try{Zr.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 Tr(n),Zr.debug("Token exchange successful"),n}catch(t){return Zr.debug("Token exchange failed, using existing token",{error:t instanceof Error?t.message:String(t)}),e}return e}try{Zr.debug("Attempting token refresh");const t=await Pr(e.refreshToken);Zr.debug("Token refresh successful");const r=await Rr();if(r)try{Zr.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 Tr(n),n}catch{return await Tr(t),t}return await Tr(t),t}catch(e){return void Zr.warn("Token refresh failed",{error:e instanceof Error?e.message:String(e)})}},sn=async(e={})=>{Zr.debug("Requiring authentication",{autoLogin:e.autoLogin});const t=tn();if(t){Zr.info("Using environment variable authentication");try{await vr()&&nn()}catch{}return{auth:t,type:"env"}}let r=await on(),n=r?await Rr():void 0;const o=process.stdin.isTTY&&process.stdout.isTTY;if(Zr.debug("OAuth auth check",{hasTokens:!!r,hasContext:!!n,canPrompt:o}),(!r||!n)&&e.autoLogin&&o){Zr.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(`${D.default.dim("Alternatively, set environment variables for an org API key:")}\n${D.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(D.default.dim("Press Enter to continue... "))}finally{e.close()}await Dr(),r=await on(),n=r?await Rr():void 0}return r||(Zr.warn("Authentication required but no tokens available"),m.outro(D.default.red("You are not logged in. Run `stably login` to authenticate.")),process.exit(1)),n||(Zr.warn("Authentication succeeded but no project context selected"),m.outro(D.default.red("You haven't selected an organization and project. Run `stably login` to complete setup.")),process.exit(1)),Zr.info("OAuth authentication successful",{orgId:n.orgId,projectId:n.projectId}),{auth:{accessToken:r.accessToken,context:n},type:"oauth"}},an=e=>e?{...process.env,...e}:process.env,cn=async()=>{const e=(()=>{if(!process.env.STABLY_WS_URL&&"https://api.stably.ai"!==ir)return`${ir.replace(/^https?:\/\//,"wss://").replace(/\/$/,"")}/reporter`})(),t=tn();if(t)return{STABLY_API_KEY:t.apiKey,STABLY_PROJECT_ID:t.projectId,...e&&{STABLY_WS_URL:e}};const r=await(async()=>{const e=tn();if(e){try{await vr()&&nn()}catch{}return{auth:e,type:"env"}}const t=await on(),r=t?await Rr():void 0;if(t&&r)return{auth:{accessToken:t.accessToken,context:r},type:"oauth"}})();if(!r||"env"===r.type)return;const n=process.env.STABLY_PROJECT_ID?.trim(),o=n||(e=>"env"===e.type?e.auth.projectId:e.auth.context.projectId)(r);if(!o)return;const s=await(async(e,t)=>{try{Zr.debug("Requesting JWT API key",{projectId:t,apiUrl:ir});const r=await(async({accessToken:e,projectId:t})=>{const r=await(n={auth:e,client:ur(),path:{projectId:t}},(n.client??or).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 Zr.debug("JWT API key obtained",{keyPrefix:r.apiKey.substring(0,10)}),r.apiKey}catch(e){return void Zr.warn("Failed to get JWT API key for test reporter",{error:e instanceof Error?e.message:String(e)})}})(r.auth.accessToken,o),i=s?{STABLY_API_KEY:s,STABLY_PROJECT_ID:o,...e&&{STABLY_WS_URL:e}}:void 0;return Zr.debug("Resolved Stably test env",{hasApiKey:!!i?.STABLY_API_KEY,projectId:i?.STABLY_PROJECT_ID,wsUrl:i?.STABLY_WS_URL??process.env.STABLY_WS_URL??"(default)"}),i},ln=e=>e?{[jt]:e}:void 0,dn=_.z.object({context:_.z.string().min(1),autohealReportUrl:_.z.string()}),un=v.z.object({bucket:v.z.string(),key:v.z.string()}),pn=v.z.object({diffBucketPath:un,expiresInSeconds:v.z.number(),key:v.z.string(),uploadUrl:v.z.string()}),fn=/\.(spec|test)\.(c|m)?[jt]sx?$/,hn=e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"text"===t.type&&"string"==typeof t.text},gn=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},yn=e=>{const t=mn(e);if(t)return t.filter(hn).map(e=>e.text).join("\n")||void 0},_n=/\u001b\[[0-9;]*m/g,bn=e=>e.replace(_n,""),En=/\$\{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 o=n.replace(En,(t,r)=>{const n=e[r];return null!=n?n:t});return o===n?{decision:"approve"}:{decision:"approve",hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",reason:"Evaluated environment variable placeholders in browser text input.",updatedInput:{...r,text:o}}}}}function In({onResult:e}){return async t=>{if(!gn(t))return{decision:"approve"};const r=yn(t);if(!r)return{decision:"approve"};const n=function(e){const t=bn(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"),o=parseInt(r.match(/(\d+)\s+failed/g)?.at(-1)?.match(/(\d+)/)?.[1]??"0");if(0===n&&0===o)return;const s=[n>0?`${n} test${1===n?"":"s"} passed ✓`:void 0,o>0?`${o} test${1===o?"":"s"} failed ✗`:void 0].filter(e=>void 0!==e).join(", ");if(0===o)return s;const i=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?s:`${s}\n${i.map(e=>` - ${e}`).join("\n")}`}(r);return n&&e(n),{decision:"approve"}}}function vn({onResult:e}){return async t=>{if(!gn(t))return{decision:"approve"};const r=yn(t);if(!r)return{decision:"approve"};const n=function(e){const t=bn(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 Tn=/\.(spec|test)\.(ts|tsx|js|jsx|mts|mjs)$/;function xn({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&&Tn.test(n)&&e(n),{decision:"approve"}}}d.promisify(o.exec);var Sn=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())}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()})}},Rn=[".ts",".js",".mts",".mjs",".cts",".cjs"],Cn=10240,An=async({defaultContent:e,fileName:t,filePath:r})=>{try{const e=(await g.stat(r)).size,n=await g.readFile(r,"utf-8"),o=Buffer.byteLength(n,"utf-8");if(o<=Cn)return n;const s=(e=>{const t=e.split("\n"),r=[];let n=!1,o=!1,s=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),o=!0,s=(a.match(/{/g)||[]).length-(a.match(/}/g)||[]).length,0===s&&(c.endsWith(";")||c.endsWith(","))&&(o=!1)):o?(s+=(a.match(/{/g)||[]).length,s-=(a.match(/}/g)||[]).length,0===s&&c.includes("}")?(r.push(a),o=!1):s>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(s,"utf-8");return i<=Cn?s:s.slice(0,Cn)+`\n\n... [TRUNCATED: File "${t}" at ${r} was ${e} bytes (${o} 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}},Pn=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}},Un=async({allowedEnvVars:e,mode:t,workspaceInfo:r,authHeader:n,customHeader:s,maxParallelWorkers:i})=>{const a=ur(),c=function(e){try{const t=o.execSync("git branch --show-current",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(!t)return;return{branch:t}}catch{return}}(r.absolutePath);Zr.debug("Requesting system prompt from API",{mode:t,hasGitContext:!!c,envVarCount:e.length});const l=await(d={client:a,auth:n,body:{mode:t,workspaceInfo:r,allowedEnvVars:e,gitContext:c,maxParallelWorkers:i}},(d.client??or).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/prompts/system",...d,headers:{"Content-Type":"application/json",...d.headers}}));var d;if(401===l.response.status)throw Zr.warn("System prompt fetch failed: unauthorized (401)"),await xr(),new Error("Your session has expired or been revoked. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(403===l.response.status)throw Zr.warn("System prompt fetch failed: forbidden (403)"),await xr(),new Error("You no longer have access to this organization. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(l.error)throw Zr.warn("System prompt fetch failed",{error:l.error}),new Error(`Failed to fetch system prompt: ${JSON.stringify(l.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:l.data.systemPrompt,customHeader:s});return Zr.debug("System prompt received",{size:u.length,appendedCustomHeader:!!s}),u},Ln=".stably-playwright-wrapper.config.*",On=[".ts",".js",".mts",".mjs",".cts",".cjs"];function Bn(e){const r=t.resolve(e);if(i.existsSync(r))for(const e of On){const n=t.join(r,`playwright.config${e}`);if(i.existsSync(n))return n}}var Dn=["tests","e2e","__tests__","test"];function Nn(e){try{return i.existsSync(e)&&i.statSync(e).isDirectory()}catch{return!1}}function kn(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(D.default.dim(`Using output directory: ${e} (from ${r})`))}var jn=["mcp__playwright-test__","mcp__auto-heal-report__","mcp__test-doc-sync__","mcp__stably-agent-control__"],$n=["planner_","generator_"],Mn={"mcp__stably-agent-control__restart_mcp_servers":"Restarting Browser Tools"},Hn=(e,t)=>{const r=t.find(t=>e.startsWith(t));return r?e.slice(r.length):e},Fn=e=>{const t=Mn[e];if(t)return t;const r=Hn(e,jn);return Hn(r,$n).split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")},Gn=(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},Yn=["test","bug","other"],zn={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."},Wn=e=>zn[e],{zSuiteAutoHealReport:Kn}=function(e){const t=e.enum(Yn),r=["Classification of the root cause:","",`- test: ${Wn("test")}`,`- bug: ${Wn("bug")}`,`- other: ${Wn("other")}`].join("\n"),n=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).")}),o=e.discriminatedUnion("result",[n.extend({fixApplied:e.string().describe("What fix was applied (brief, specific)."),result:e.literal("fixed")}),n.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:o,zIssueCategory:t,zSuiteAutoHealReport:e.object({issues:e.array(o).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.")})}}(v.z),qn=({authHeader:e,diffTracker:t,orgId:r,runId:n})=>u.createSdkMcpServer({name:"auto-heal-report",tools:[u.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:Kn},async({report:o})=>{const s=await t.computeDiff(),i=Kn.parse(o);try{await(async({authHeader:e,orgId:t,report:r,runId:n})=>{const o=await(s={auth:e,body:{report:JSON.stringify(r)},client:ur(),headers:ln(t),path:{runId:n}},(s.client??or).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-report",...s,headers:{"Content-Type":"application/json",...s.headers}}));var s;if(o.error)throw new Error(`Failed to upload auto-heal report (${o.response.status})`)})({authHeader:e,orgId:r,report:i,runId:n});const{uploadUrl:t}=await(async({authHeader:e,contentType:t="text/plain",orgId:r,runId:n})=>{const o=await(s={auth:e,body:{contentType:t},client:ur(),headers:ln(r),path:{runId:n}},(s.client??or).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-diff/upload-url",...s,headers:{"Content-Type":"application/json",...s.headers}}));var s;if(o.error)throw new Error(`Failed to presign diff upload (${o.response.status})`);const i=pn.parse(o.data);return{diffBucketPath:i.diffBucketPath,expiresInSeconds:i.expiresInSeconds,key:i.key,uploadUrl:i.uploadUrl}})({authHeader:e,contentType:"text/plain",orgId:r,runId:n});await(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})`)})({contentType:"text/plain",diff:s,uploadUrl:t})}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. 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"}),Vn=({onComplete:e})=>u.createSdkMcpServer({name:"session-control",tools:[u.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:v.z.string().describe("A brief summary of what was accomplished")},async({summary:t})=>{const r=t;return e(),`Session complete: ${r}`})]}),Jn=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]"),Xn=(e,t)=>({message:Jn(e),status:t?.status,statusText:t?.statusText}),Qn=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"]),Zn=async({authHeader:e,mode:t,maxTurnsOverride:r})=>{const n=ur();Zr.debug("Requesting subagent definitions from API",{mode:t,maxTurnsOverride:r});const o=await(s={client:n,auth:e,body:{mode:t,maxTurnsOverride:r}},(s.client??or).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/prompts/subagents",...s,headers:{"Content-Type":"application/json",...s.headers}}));var s;if(401===o.response.status)throw Zr.warn("Subagent definitions fetch failed: unauthorized (401)"),await xr(),new Error("Your session has expired or been revoked. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(403===o.response.status)throw Zr.warn("Subagent definitions fetch failed: forbidden (403)"),await xr(),new Error("You no longer have access to this organization. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(o.error)throw Zr.warn("Subagent definitions fetch failed",{error:o.error}),new Error(`Failed to fetch subagent definitions: ${JSON.stringify(o.error)}`);const{subagents:i}=o.data;return Zr.debug("Subagent definitions received",{count:Object.keys(i).length}),i},{zStablyYaml:eo}=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}}(_.z),to=["Bash","Read","Write","Edit","Glob","Grep","Task"],ro=["Task","mcp__playwright-test"],no=["Bash","Read","Write","Edit","Glob","Grep","mcp__session-control"],oo=e=>{if("EPIPE"!==e.code)throw e},so=async r=>{if("single"===r.mode||"build"===r.mode){const e=Array.isArray(r.prompt)?r.prompt.join(" "):r.prompt;Zr.initSession(e||"create-from-diff")}else"fix"===r.mode&&Zr.initSession(`fix-${r.runId}`);Zr.info("Agent session starting",{mode:r.mode}),process.stdout.on("error",oo),process.stderr.on("error",oo);const n=e=>{if("EPIPE"!==e.code)throw e};process.on("uncaughtException",n),Zr.debug("Checking authentication");const o=await sn({autoLogin:"chat"===r.mode||"init"===r.mode}),s=(e=>"env"===e.type?e.auth.apiKey:e.auth.accessToken)(o);Zr.debug("Authentication resolved",{authType:o.type});const a="oauth"===o.type?o.auth.context.orgId:void 0,c=A.default.resolve(process.cwd()),l=A.default.join(c,".env"),d=L.default.existsSync(l)&&L.default.statSync(l).isFile(),p=d?e.parse(L.default.readFileSync(l,"utf8")):{};Zr.debug("Environment file",{path:l,exists:d,variableCount:Object.keys(p).length});const f="chat"!==r.mode&&"init"!==r.mode,h="chat"===r.mode||"init"===r.mode?new Sn:void 0,m="chat"===r.mode?r.getHelpText:void 0,y={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 _,b=f,E=!1;const w=new Map;let I=null,v=!1,R=!1;const C=async e=>{if("fix"===r.mode){if("STARTED"===e){if(v)return;v=!0}else{if(R)return;R=!0}try{await(async({authHeader:e,orgId:t,runId:r,status:n})=>{const o=await(s={auth:e,body:{status:n},client:ur(),headers:ln(t),path:{runId:r}},(s.client??or).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-status",...s,headers:{"Content-Type":"application/json",...s.headers}}));var s;if(o.error)throw new Error(`Failed to update autoheal status (${o.response.status})`)})({authHeader:s,orgId:a,runId:r.runId,status:e})}catch{}}},P={current:e=>{}},U={current:async()=>{}},{addSubagentActivity:O,addSubagentStart:B,addTool:N,addToolResult:k,appendText:j,appendUserMessage:$,cleanup:M,setExiting:H,setStatus:F,setSubagentStatus:G,updateFixProgress:Y}=await(async(e,t)=>{const{Box:r,Static:n,Text:o,render:s,useInput:i}=await import("ink"),a=!!process.stdin.isTTY,c=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],l=()=>x.jsx(o,{inverse:!0,children:" "}),d=(({Box:e,Text:t,useInput:r},n,o)=>function({onChoice:s,prompt:i}){const[a,c]=T.useState(0),[l,d]=T.useState(!1),[u,p]=T.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 s("deny_with_message",u||"User denied this action"):t.escape?(d(!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 d(!0):void s(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 d(!0);s(e.value)}},{isActive:o});const h=Fn(i.toolName),g=Gn(i.toolName,i.input);return x.jsxs(e,{borderColor:"yellow",borderStyle:"round",flexDirection:"column",marginTop:1,paddingX:1,paddingY:0,children:[x.jsx(t,{bold:!0,color:"yellow",children:"Permission Required"}),x.jsxs(e,{flexDirection:"column",marginTop:1,children:[x.jsx(t,{color:"magenta",children:h}),null!=g&&x.jsxs(t,{color:"gray",children:[" ",g]})]}),null!=i.decisionReason&&x.jsx(e,{marginTop:1,children:x.jsxs(t,{color:"gray",children:["Reason: ",i.decisionReason]})}),l?x.jsxs(e,{flexDirection:"column",marginTop:1,children:[x.jsx(t,{color:"gray",children:"Enter message for AI (press Enter to submit, Esc to cancel):"}),x.jsxs(t,{children:[x.jsx(t,{color:"yellow",children:">"})," ",u,x.jsx(n,{})]})]}):x.jsxs(e,{flexDirection:"column",marginTop:1,children:[x.jsx(t,{color:"gray",children:"Use ↑↓ arrows or number keys to select:"}),f.map((e,r)=>x.jsx(t,{children:x.jsxs(t,{color:r===a?"cyan":void 0,children:[r===a?"❯":" "," ",r+1,". ",e.label]})},e.value))]})]})})({Box:r,Text:o,useInput:i},l,a),u=(({Cursor:e,inkComponents:{Box:t,Static:r,Text:n,useInput:o},isRawModeSupported:s,PermissionPrompt:i,Spinner:a})=>{const c=({progress:e})=>{const[r,o]=T.useState(Date.now());T.useEffect(()=>{const e=setInterval(()=>o(Date.now()),1e3);return()=>clearInterval(e)},[]);const s=r-e.startedAt,i=Math.floor(s/1e3),a=Math.floor(i/60),c=i%60,l=a>0?`${a}m ${c.toString().padStart(2,"0")}s`:`${c}s`,{label:d,color:u}={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 x.jsx(t,{flexDirection:"column",children:x.jsxs(n,{children:[x.jsx(n,{color:u,bold:!0,children:d}),x.jsx(n,{color:"gray",children:f}),x.jsxs(n,{color:"gray",children:[" [",l,"]"]})]})})},l=({progress:e})=>{const r=e.endedAt??Date.now(),o=Math.floor((r-e.startedAt)/1e3),s=Math.floor(o/60),i=o%60,a=s>0?`${s}m ${i.toString().padStart(2,"0")}s`:`${i}s`,c=e.isError?"yellow":"green",l=e.isError?"Fix stopped":"Fix complete";return x.jsxs(t,{flexDirection:"column",children:[x.jsxs(n,{color:c,bold:!0,children:[l," in ",a]}),null!==e.totalTests&&x.jsxs(n,{color:"gray",children:[e.fixedTests,"/",e.totalTests," tests fixed",e.failedTests>0?`, ${e.failedTests} failed`:""]})]})},d=e=>{if("subagent"===e.kind&&e.subagent){const{subagent:r}=e,o="complete"===r.status?"green":"error"===r.status?"red":"yellow";return x.jsxs(t,{flexDirection:"column",marginTop:1,children:[x.jsxs(n,{children:[x.jsx(n,{color:o,bold:!0,children:"Agent"}),r.description?x.jsxs(n,{color:"gray",children:[" (",r.description,")"]}):null]}),r.activities.length>0&&x.jsx(t,{flexDirection:"column",marginLeft:2,children:r.activities.map(e=>(e=>"tool"===e.kind?x.jsxs(n,{color:"magenta",children:["• ",e.content]},e.id):"tool_result"===e.kind?x.jsx(n,{color:"gray",children:e.content},e.id):null)(e))})]},e.id)}return"tool"===e.kind?x.jsxs(n,{color:"magenta",children:["• ",e.content]},e.id):"tool_result"===e.kind?x.jsx(n,{color:"gray",children:e.content},e.id):"user"===e.kind?x.jsxs(n,{color:"cyan",children:["You: ",e.content]},e.id):x.jsx(n,{children:e.content},e.id)},u="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:_,showSpinnerImmediately:b,state:E}){const[w,I]=T.useState({value:"",cursor:0}),v=w.value,S=w.cursor,R=T.useRef(!1),C=T.useRef(void 0),[A,P]=T.useState(!1),U=T.useRef(0),L=E.log.at(-1),O="text"===L?.kind&&"running"===E.status,B=E.log.findIndex(e=>"subagent"===e.kind&&"running"===e.subagent?.status),D=u?0:-1!==B?B:O?E.log.length-1:E.log.length;T.useEffect(()=>{E.log.length<U.current&&(U.current=0),D>U.current&&(U.current=D)},[E.log.length,D]);const N=E.log.slice(0,U.current),k=E.log.slice(U.current),j=!!E.permissionPrompt,$=T.useCallback(async()=>{R.current?(C.current&&clearTimeout(C.current),await(m?.()),process.exit(0)):(R.current=!0,P(!0),C.current=setTimeout(()=>{R.current=!1,P(!1)},2e3))},[m]);o((e,t)=>{t.ctrl&&"c"===e&&$().catch(()=>process.exit(1))},{isActive:s}),T.useEffect(()=>{if(j||!_)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||I(e=>({...e,cursor:g(e.value,e.cursor)})):I(e=>({...e,cursor:h(e.value,e.cursor)})):I(e=>({...e,cursor:e.value.length})):I(e=>({...e,cursor:0}))};return process.stdin.on("data",e),()=>{process.stdin.off("data",e)}},[j,_,v]),o((e,t)=>{if(!t.ctrl||"c"!==e){if(t.return){const e=v.trim();return e&&_?.(e),void I({value:"",cursor:0})}t.ctrl&&"w"===e||t.ctrl&&t.backspace?I(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?I(e=>({...e,cursor:p(e.value,e.cursor)})):t.ctrl&&t.rightArrow||t.meta&&"f"===e?I(e=>({...e,cursor:f(e.value,e.cursor)})):t.leftArrow?I(e=>({...e,cursor:Math.max(0,e.cursor-1)})):t.rightArrow?I(e=>({...e,cursor:Math.min(e.value.length,e.cursor+1)})):t.ctrl&&"a"===e?I(e=>({...e,cursor:0})):t.ctrl&&"e"===e?I(e=>({...e,cursor:e.value.length})):!e||t.ctrl||t.meta||t.escape||e.includes("")||/^\[./.test(e)||/^O[A-D]$/.test(e)||I(t=>({value:t.value.slice(0,t.cursor)+e+t.value.slice(t.cursor),cursor:t.cursor+e.length})):I(e=>e.cursor>0?{value:e.value.slice(0,e.cursor-1)+e.value.slice(e.cursor),cursor:e.cursor-1}:e)}},{isActive:s&&!!_&&!j});const M=T.useMemo(()=>"running"===E.status?x.jsx(a,{label:"Working"}):"success"!==E.status?x.jsx(n,{color:"red",children:"✖ Failed"}):void 0,[E.status]),H=!(b||!_||"running"!==E.status||0!==E.log.length||E.resultText||E.errorText),F="running"===E.status&&!H||E.log.length>0||E.resultText||E.errorText||"running"!==E.status;return x.jsxs(t,{flexDirection:"column",children:[x.jsx(r,{items:["header"],children:()=>x.jsxs(t,{flexDirection:"column",flexShrink:0,children:[x.jsx(n,{color:"cyan",bold:!0,children:"Stably Agent"}),x.jsx(t,{flexDirection:"column",marginTop:1,children:x.jsx(n,{color:"gray",children:E.promptDisplay})})]},"header")}),N.length>0&&x.jsx(r,{items:N,children:e=>d(e)}),k.length>0&&x.jsx(t,{flexDirection:"column",children:k.map(e=>d(e))}),"error"===E.status&&E.errorText&&x.jsx(t,{marginTop:1,children:x.jsx(n,{color:"red",children:E.errorText})}),"success"===E.status&&E.resultText&&x.jsx(t,{marginTop:1,children:x.jsx(n,{children:E.resultText})}),F&&x.jsx(t,{flexDirection:"column",flexShrink:0,marginTop:1,children:"running"===E.status&&E.fixProgress?x.jsxs(t,{flexDirection:"column",children:[x.jsxs(t,{children:[x.jsx(a,{}),x.jsx(n,{children:" "}),x.jsx(c,{progress:E.fixProgress})]}),"fixing"===E.fixProgress.phase&&E.log.flatMap(e=>{const{subagent:r}=e;if("subagent"!==e.kind||"fix-worker"!==r?.subagentType||"running"!==r.status)return[];const{activities:o}=r,s=o.filter(e=>"tool"===e.kind).length,i=o.at(-1),c=o.filter(e=>"tool"===e.kind).at(-1),l=(()=>{if(!i)return null;if("tool"===i.kind)return null;if("text"===i.kind){const e=i.content.trim().split("\n").at(-1)?.trim();return e?e.length>80?`${e.slice(0,80)}…`:e:null}if("tool_result"===i.kind){const e=i.content.trim().split("\n")[0]?.trim();return e?e.length>80?`${e.slice(0,80)}…`:e:null}return null})();return x.jsxs(t,{flexDirection:"column",children:[x.jsxs(n,{children:[" ",x.jsx(a,{}),x.jsxs(n,{color:"gray",children:[r.description||"fix-worker",s>0?` (${s} ${1===s?"cycle":"cycles"})`:""]})]}),c&&x.jsxs(n,{color:"gray",dimColor:!0,children:[" • ",c.content]}),l&&x.jsxs(n,{color:"gray",dimColor:!0,children:[" ",l]})]},e.id)})]}):"success"!==E.status&&"error"!==E.status||!E.fixProgress?M:x.jsx(l,{progress:E.fixProgress})}),null!=E.permissionPrompt&&null!=y&&x.jsx(i,{onChoice:y,prompt:E.permissionPrompt}),null!=_&&null==E.permissionPrompt&&!E.isExiting&&x.jsxs(t,{borderColor:"gray",borderStyle:"round",flexDirection:"column",flexShrink:0,marginTop:1,paddingX:1,paddingY:0,children:[x.jsx(n,{color:"gray",children:"Type a message and press Enter. Press Ctrl+C to exit."}),x.jsxs(n,{children:[x.jsx(n,{color:"yellow",children:">"})," ",v.slice(0,S),x.jsx(e,{}),v.slice(S)]})]}),A&&x.jsxs(t,{marginTop:1,flexDirection:"column",children:[x.jsx(n,{color:"yellow",children:"Press Ctrl+C again to exit"}),Hr&&x.jsxs(n,{color:"gray",children:["Debug log: ",zr]})]})]})}})({Cursor:l,inkComponents:{Box:r,Static:n,Text:o,useInput:i},isRawModeSupported:a,PermissionPrompt:d,Spinner:({label:e})=>{const[t,r]=T.useState(0);return T.useEffect(()=>{const e=setInterval(()=>r(e=>(e+1)%c.length),80);return()=>clearInterval(e)},[]),x.jsxs(o,{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=s(x.jsx(u,{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(x.jsx(u,{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 o=p.log[n];if(o&&"subagent"===o.kind&&o.subagent){if("text"===t){const e=o.subagent.activities.at(-1);e&&"text"===e.kind?e.content+=r:o.subagent.activities.push({id:o.subagent.activities.length,kind:"text",content:r.replace(/^\s*\n+/,"")})}else o.subagent.activities.push({id:o.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:o?.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=Fn(e),n=Gn(e,t),o=n?`${r} (${n})`:r;p.log=[...p.log,{content:o,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()},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}})(y,"chat"===r.mode||"init"===r.mode?{onExit:()=>U.current(),onSend:e=>P.current(e),showSpinnerImmediately:"init"===r.mode}:"fix"===r.mode?{onExit:()=>U.current(),isFixMode:!0}:void 0);let z=y.status;const W=({error:e,result:t,status:r})=>{z=r,F({error:e,result:t,status:r})};let K;P.current=e=>{const t=e.trim();if("chat"!==r.mode||Zr.getLogFilePath()||Zr.initSession(t||"chat"),Zr.debug("User message",{text:t}),"/help"===t){b&&h&&(E=!0,_?.interrupt?.(),h.allowNextTurn(),b=!1),"running"===z&&W({status:"success"}),$({text:e});const t=m?.();return void j({text:t??"Help is not available in this session."})}h&&(b&&(E=!0,_?.interrupt?.(),h.allowNextTurn(),b=!1),W({status:"running"}),$({text:e}),h.pushText(e),b=!0)};const q=[];let V;const J=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 kn(e,"output-flag"),{path:e,source:"output-flag"}}const o=Bn(n);if(o){const e=await async function(e){try{const t=(await g.readFile(e,"utf-8")).match(/testDir:\s*['"]([^'"]+)['"]/);return t?.[1]}catch{return}}(o);if(e){const r=t.resolve(t.dirname(o),e);if(Nn(r))return kn(r,"playwright.config.ts"),{path:r,source:"playwright.config.ts"}}}for(const e of Dn){const r=t.join(n,e);if(Nn(r))return kn(r,"auto-detected"),{path:r,source:"auto-detected"}}return kn(n,"cwd-fallback"),{path:n,source:"cwd-fallback"}}(c,r.outputDir);return V=n.path,e=r.prompt,`${(Array.isArray(e)?e.join(" "):e).trim()||"Create tests based on the changes in the current PR or 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 playwright test` or the repo's Playwright test command) and iterate until the new tests pass."}\n\n[Output directory: ${V}]`}var e;if("fix"===r.mode)try{const{context:e,autohealReportUrl:t}=await(async({authHeader:e,orgId:t,runId:r})=>{Zr.debug("Fetching autoheal context",{runId:r});const n=await(o={auth:e,client:ur(),headers:ln(t),path:{runId:r}},(o.client??or).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-context",...o}));var o;if(404===n.response.status)throw Zr.warn("Autoheal context not found",{runId:r,status:404}),new Error(`Run ID "${r}" was not found.`);if(401===n.response.status)throw Zr.warn("Autoheal context fetch unauthorized",{runId:r,status:401}),new Error("Unauthorized: failed to fetch autoheal context (401).");if(422===n.response.status)throw Zr.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=dn.safeParse(n.data);if(e.success)return Zr.debug("Autoheal context fetched successfully",{runId:r,contextSize:e.data.context.length}),{context:e.data.context,autohealReportUrl:e.data.autohealReportUrl};throw Zr.warn("Autoheal context response invalid",{runId:r}),new Error("Autoheal context response missing or invalid context.")}throw Zr.warn("Autoheal context fetch failed",{runId:r,error:n.error}),new Error("Failed to fetch autoheal context")})({authHeader:s,orgId:a,runId:r.runId});return K=t,C("STARTED"),e}catch(e){const t=e instanceof Error?e.message:"Failed to fetch autoheal context.";W({error:t,status:"error"}),await M(),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.":""})(),X=await async function(e){const t=A.default.resolve(e),r=A.default.join(t,"tests"),n=A.default.join(r,"helpers"),o=A.default.join(r,"assets"),s=function(e){const t=A.default.resolve(e);if(i.existsSync(t))for(const e of Rn){const r=A.default.join(t,`playwright.config${e}`);if(i.existsSync(r))return r}}(t)??A.default.join(t,"playwright.config.ts"),a=A.default.basename(s),c=A.default.join(r,"seed.spec.ts"),[l,d,u,p,f,h]=await Promise.all([Pn({defaultContent:"Unable to read directory",dirName:"working directory",dirPath:t}),Pn({defaultContent:"Unable to read directory",dirName:"tests directory",dirPath:r}),Pn({defaultContent:"Directory does not exist yet",dirName:"helpers directory",dirPath:n}),Pn({defaultContent:"Directory does not exist yet",dirName:"assets directory",dirPath:o}),An({defaultContent:"File does not exist or could not be read",fileName:a,filePath:s}),An({defaultContent:"File does not exist or could not be read",fileName:"seed.spec.ts",filePath:c})]);return{absolutePath:t,directories:{assets:p,helpers:u,root:l,tests:d},files:{playwrightConfig:f,playwrightConfigFilename:a,seedSpec:h}}}(c),Q=await(async e=>{try{const t=await(async e=>{let t=e;const{root:r}=A.default.parse(t);for(;t!==r;){const e=A.default.join(t,"stably.yaml");try{return await g.readFile(e),e}catch{t=A.default.dirname(t)}}})(e);if(!t)return void Zr.debug("No stably.yaml found");const r=await g.readFile(t,"utf-8");if(!r.trim())return;const n=S.parseDocument(r),o=eo.parse(n.toJS()),s=o.agent?.fix?.maxTurnsPerIssue,i=o.agent?.fix?.maxParallelWorkers,a=!!o.agent?.fix?.rules;return Zr.debug(`Loaded stably.yaml: maxTurnsPerIssue=${s??"default"}, maxParallelWorkers=${i??"default"}, hasRules=${a}`,{path:t,config:o.agent}),o}catch(e){return void Zr.warn("Failed to parse stably.yaml",{error:e})}})(c),Z=Q?.agent?.fix?.maxTurnsPerIssue,ee=Q?.agent?.fix?.maxParallelWorkers,te=Q?.agent?.fix?.rules;Zr.debug("Fetching system prompt and subagents",{mode:r.mode,maxTurnsOverride:Z,hasCustomRules:!!te});const[re,ne]=await Promise.all([Un({allowedEnvVars:Object.keys(p),mode:r.mode,workspaceInfo:X,authHeader:s,customHeader:"single"===r.mode||"build"===r.mode?r.customHeader:void 0,maxParallelWorkers:"fix"===r.mode?ee:void 0}),"fix"===r.mode?Zn({authHeader:s,mode:r.mode,maxTurnsOverride:Z}):Promise.resolve({})]);Zr.debug("System prompt and subagents fetched",{systemPromptSize:re.length,subagentCount:Object.keys(ne).length,maxTurnsOverride:Z??"default"});const oe={...p,...process.env},se={};for(const[e,t]of Object.entries(oe))Qn.has(e)||void 0===t||(se[e]=t);Zr.debug("AI proxy configuration",{useStablyAiProxy:!0,wantsBypassProxy:!1,wantsUseOllama:!1});const ie=await async function({auth:e,client:t,source:r,metadata:n,duration:o}){try{const i=await(s={auth:e,client:t,body:{source:r,metadata:n??{},duration:o}},(s.client??or).post({security:[{scheme:"bearer",type:"http"}],url:"/v1/proxy/api-key",...s,headers:{"Content-Type":"application/json",...s.headers}})),a=i.response;if(i.error){const e="object"==typeof i.error&&"error"in i.error?i.error.error:"Unknown error";return{error:Xn(e,a)}}return i.data?{key:i.data.key}:{error:Xn("No data in response",a)}}catch(e){const t=e instanceof Error?e.message:"Unknown error";return{error:Xn(t)}}var s}({auth:s,client:ur(),source:"cli"}),ae=ie?.key;if(!ae){const e=ie?.error?.message?`Unable to make AI calls: ${ie.error.message}`:"Unable to make AI calls. Check if you are authenticated.";Zr.warn("Failed to get proxy API key",{error:ie?.error?.message}),W({error:e,status:"error"}),await M(),Zr.flush(),Zr.printLogFileInfo(),process.exit(1)}Zr.debug("Proxy API key acquired",{success:!!ae});const ce=await cn(),le=ce?Object.fromEntries(Object.entries(an(ce)).filter(e=>null!=e[1])):void 0,de="init"===r.mode,ue="fix"===r.mode,pe=ue?Nt.createLocal({workingDir:c}):void 0;pe&&await pe.captureSnapshot();const fe=de?no:[...to,...ue?["mcp__auto-heal-report"]:[]],he=de?no:ro,ge=de?{"session-control":Vn({onComplete:()=>{W({status:"success"}),H(),h?.finish(),process.exit(0)}})}:ue&&pe?{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:le},"auto-heal-report":qn({authHeader:s,diffTracker:pe,orgId:a,runId:r.runId})}:{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:le}},me="single"===r.mode||"build"===r.mode,ye=de?[]:[{hooks:[async e=>{const t=mn(e);if(!t)return{decision:"approve"};let r=!1;const n=t.map(e=>hn(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:[In({onResult:e=>k({message:e})})]},{matcher:"mcp__playwright-test__test_debug",hooks:[vn({onResult:e=>k({message:e})})]},...me?[{matcher:"Write",hooks:[xn({onFileCreated:e=>q.push(e)})]}]:[]],_e=de?[]:[{matcher:"mcp__playwright-test__browser_type",hooks:[wn({envVars:p})]}],be=Object.keys(ne).length>0?ne:void 0,Ee={...se};Ee.MCP_TOOL_TIMEOUT=String(6e5),ae&&(Ee.ANTHROPIC_API_KEY=ae,Ee.ANTHROPIC_BASE_URL=lr,Ee.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS="1");const we=process.env.STABLY_AGENT_MODEL??"claude-opus-4-5-20251101",Ie=te?`${re}\n\n## Custom Rules\n${te}`:re;Zr.info("Starting agent query",{model:we,tools:fe,mcpServers:Object.keys(ge),subagentsEnabled:!!be,subagentCount:Object.keys(ne).length}),_=u.query({options:{tools:fe,allowedTools:he,betas:[],canUseTool:(e,t)=>Promise.resolve({behavior:"allow",updatedInput:t}),cwd:c,env:Ee,hooks:{PostToolUse:ye,PreToolUse:_e},includePartialMessages:!0,agents:be,mcpServers:ge,model:we,permissionMode:"default",systemPrompt:Ie},prompt:h??J}),"init"===r.mode&&h&&h.pushText(J),U.current=async()=>{I="CANCELED",await C("CANCELED"),Zr.flush(),H();try{await(_?.interrupt?.())}catch{}h?.finish(),M()};try{for await(const e of _){if("stream_event"===e.type){const{event:t}=e,r=t&&"object"==typeof t&&"parent_tool_use_id"in t&&"string"==typeof t.parent_tool_use_id?t.parent_tool_use_id:void 0;if("content_block_delta"===t?.type){const{delta:e}=t;"text_delta"===e?.type&&e.text&&(r&&w.has(r)?O({toolUseId:r,kind:"text",content:e.text}):j({text:e.text}))}"message_stop"===t?.type&&h&&h.allowNextTurn();continue}if("assistant"===e.type){const t="parent_tool_use_id"in e&&"string"==typeof e.parent_tool_use_id?e.parent_tool_use_id:void 0,{content:r}=e.message??{};if(Array.isArray(r)&&!t){const e=r.filter(e=>e&&"object"==typeof e&&"type"in e&&"text"===e.type).map(e=>e&&"object"==typeof e&&"text"in e&&"string"==typeof e.text?e.text:void 0).filter(Boolean).join("");e&&Zr.debug("Assistant message",{text:e})}if(w.size>0){const n=Array.isArray(r)?r.filter(e=>e&&"object"==typeof e&&"type"in e&&"tool_use"===e.type).map(e=>e&&"object"==typeof e&&"name"in e&&"string"==typeof e.name?e.name:void 0):[];Zr.debug("Assistant message with active subagents",{hasParentToolUseId:!!t,parentToolUseId:t,activeSubagentIds:Array.from(w.keys()),toolNames:n,fullMessageKeys:Object.keys(e),rawMessage:JSON.stringify(e).slice(0,500)})}if(Array.isArray(r))for(const e of r){if("tool_use"===e?.type){if(e.name.startsWith("mcp__session-control__"))continue;if(w.size>0&&Zr.debug("Tool use detected with active subagents",{toolName:e.name,hasParentToolUseId:!!t,parentToolUseId:t,wouldRouteToSubagent:!!t&&w.has(t),activeSubagentIds:Array.from(w.keys())}),"Task"===e.name){const t=e.input,r=t&&"object"==typeof t?t:void 0,n=r&&"subagent_type"in r&&"string"==typeof r.subagent_type?r.subagent_type:"subagent",o=r&&"description"in r&&"string"==typeof r.description?r.description.trim():"";Zr.debug("Subagent started",{subagentType:n,description:o,toolUseId:e.id}),w.set(e.id,{subagentType:n,description:o}),B({toolUseId:e.id,subagentType:n,description:o});continue}if(t&&w.has(t)){const r=Fn(e.name),n=Gn(e.name,e.input),o=n?`${r} (${n})`:r;Zr.debug("Subagent tool called",{tool:e.name,parentToolUseId:t}),O({toolUseId:t,kind:"tool",content:o});continue}t&&Zr.debug("Tool with parent_tool_use_id but no matching subagent",{tool:e.name,parentToolUseId:t,activeSubagentIds:Array.from(w.keys())}),Zr.debug("Tool called",{tool:e.name,input:e.input}),N({rawName:e.name,toolInput:e.input})}if("text"===e?.type&&t&&w.has(t)){const r="string"==typeof e.text?e.text:"";r&&O({toolUseId:t,kind:"text",content:r})}}continue}if("user"===e.type){const t="message"in e&&e.message&&"object"==typeof e.message&&"content"in e.message?e.message.content:void 0;if(Array.isArray(t))for(const e of t)if(e&&"object"==typeof e&&"type"in e&&"tool_result"===e.type&&"tool_use_id"in e){const t="string"==typeof e.tool_use_id?e.tool_use_id:void 0,r="is_error"in e&&!0===e.is_error,n="content"in e&&"string"==typeof e.content?e.content:void 0;Zr.debug("Tool result",{toolUseId:t,isError:r,output:n?.slice(0,500)}),t&&w.has(t)&&(Zr.debug("Subagent completed",{toolUseId:t,isError:r}),G({toolUseId:t,status:r?"error":"complete"}),w.delete(t))}continue}if("result"!==e.type);else{if(Zr.debug("Agent result",{subtype:e.subtype}),f){if("success"===e.subtype){if(Y?.({phase:"complete",currentTestDescription:null,endedAt:Date.now()}),me&&q.length>0){D.default.green("Created files:");for(const e of q)D.default.green(`- ${e}`)}const e=K?D.default.cyan(`📊 View Autoheal Report:\n ${D.default.cyan(D.default.bold(D.default.underline(K)))}`):void 0;W({status:"success",result:e}),I="COMPLETED"}else E?I="CANCELED":(Y?.({endedAt:Date.now(),isError:!0}),W({error:"Run failed.",status:"error"}),process.exitCode=1,I="FAILED");E=!1;break}"success"!==e.subtype?E||(W({error:"Run failed.",status:"error"}),process.exitCode=1):W({status:"success"}),b=!1,E=!1,h?.allowNextTurn()}}}catch(e){E?I="CANCELED":(Zr.error("Agent encountered an error",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),W({error:`Agent encountered an error: ${e}`,status:"error"}),process.exitCode=1,I="FAILED",Zr.flush(),Zr.printLogFileInfo())}finally{Zr.info("Agent session ending"),b=!1,E=!1,process.off("uncaughtException",n),h?.finish(),I&&await C(I),await(pe?.cleanup()),await M()}},io=j.default.object({runId:j.default.string(),timestamp:j.default.number()}),ao="sha256",co=/^\/\*\*\r?\n \* @generated by stably build[\s\S]*?\*\/(?:\r?\n)*/;function lo(e){return!!e&&"object"==typeof e&&"code"in e}async function uo({errorMessage:e,filePath:t}){try{return await k.default.readFile(t,"utf8")}catch(t){if(lo(t)&&"ENOENT"===t.code)throw new Error(e);throw t}}function po(e){return e.split(A.default.sep).join("/")}async function fo(e){try{return(await k.default.readdir(e)).filter(e=>fn.test(e)).map(t=>A.default.join(e,t))}catch(e){if(lo(e)&&"ENOENT"===e.code)return[];throw e}}function ho(e=process.cwd()){let r=t.resolve(e);for(;;){const e=go(r);if(e){const n={...e.dependencies,...e.devDependencies},o="@playwright/test"in n?"@playwright/test":"playwright"in n?"playwright":void 0;if(o){const e=mo(r);let n=!1,s=r;for(;;){const e=t.join(s,"node_modules"),r=t.join(e,o);if(i.existsSync(r)){n=!0;break}const a=t.dirname(s);if(a===s)break;s=a}return{inNodeModules:n,installed:!0,packageManager:e,packageName:o}}}const n=t.dirname(r);if(n===r)return{inNodeModules:!1,installed:!1,packageManager:void 0};r=n}}function go(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 mo(e){const r=[["npm","package-lock.json"],["pnpm","pnpm-lock.yaml"],["yarn","yarn.lock"]];let n=e;for(;;){for(const[e,o]of r)if(i.existsSync(t.join(n,o)))return e;const e=t.dirname(n);if(e===n)return;n=e}}function yo(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 _o=[{args:["--trace=on"],description:"Run Playwright tests",name:"test"},{args:[],description:"Install browser dependencies",name:"install"}];function bo(e){const[t,...r]=yo(e),n=[t,...r.slice(0,-1)].join(" ");return(t,r)=>{let o=t.toString();for(const e of _o)o=o.replaceAll(`${n} playwright ${e.name}`,`${n} stably ${e.name}`).replaceAll(`npx playwright ${e.name}`,`npx stably ${e.name}`);if("yarn"===e){const e=o.split("\n");return e.length>0&&e[0].includes("/.bin/playwright")&&e.shift(),void r.write(e.join("\n"))}r.write(o)}}function Eo(e=""){process.stdout.write(`${e}\n`)}function wo(...e){process.stderr.write(`${e.join(" ")}\n`)}var Io="stably",vo=`https://registry.npmjs.org/${Io}/latest`,To=_.z.object({version:_.z.string()});function xo(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 So(e,t){const r=xo(e),n=xo(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 Ro=A.default.join(O.default.homedir(),".stably"),Co=A.default.join(Ro,"update-check.json"),Ao=`https://registry.npmjs.org/${Io}/latest`,Po=_.z.object({lastCheck:_.z.number(),latestVersion:_.z.string()}),Uo=!1,Lo=!1,Oo=async()=>{if(Lo)try{const{shutdown:e}=await import("@hyperdx/node-opentelemetry"),t=console.log;console.log=(...e)=>{e[0]?.toString().includes("OpenTelemetry")||t(...e)};try{await e()}finally{console.log=t}}catch{}};!function(){const e=function(){try{const e=L.default.readFileSync(Co,"utf-8");return Po.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 = '${Ao}';\n const cacheFile = ${JSON.stringify(Co)};\n const cacheDir = ${JSON.stringify(Ro)};\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{o.spawn(process.execPath,["-e",e],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()}catch{}}(),null!=e&&So(sr,e.latestVersion)){if(Uo)return;Uo=!0;let t=!1;const r=()=>{if(t)return;t=!0;const r=`${D.default.yellow(`update available (${sr} → ${e.latestVersion})`)} - run \`${Io} upgrade\` to get the latest version\n`;try{L.default.writeSync(2,r)}catch{}};process.once("beforeExit",r),process.once("exit",r)}}(),G.cwdChanged&&Zr.debug("Changed working directory",{cwd:G.newCwd});for(const e of G.envFilesLoaded)Zr.debug("Loaded env file",{path:e});for(const e of G.envFileErrors)Zr.warn(e);var Bo=process.argv.findIndex(e=>"-v"===e||"--verbose"===e);-1!==Bo&&process.argv.splice(Bo,1);var Do=process.argv.findIndex(e=>"--no-telemetry"===e);-1!==Do&&process.argv.splice(Do,1),Zr.info("CLI starting",{version:sr,args:process.argv.slice(2),cwd:process.cwd()}),process.on("unhandledRejection",(e,t)=>{Zr.error("Unhandled promise rejection",{reason:e instanceof Error?{message:e.message,stack:e.stack}:e,promise:String(t)}),Zr.flush(),Zr.printLogFileInfo()}),process.on("uncaughtException",(e,t)=>{"EPIPE"!==e.code&&(Zr.error("Uncaught exception",{error:{message:e.message,stack:e.stack,name:e.name},origin:t}),Zr.flush(),Zr.printLogFileInfo())});var No=new r.Command;No.name("stably").description("AI-assisted Playwright testing CLI").version(sr),No.enablePositionalOptions(),No.showHelpAfterError(),No.exitOverride(),No.configureHelp({subcommandTerm:e=>{const t=e.registeredArguments.map(e=>e.required?`<${e.name()}>`:`[${e.name()}]`).join(" ");return t?`${e.name()} ${t}`:e.name()}});var ko=[];No.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>{ko.push(e)}});var jo=()=>{const e=No.helpInformation().trimEnd();return e?`${e}\n`:""},$o=(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},Mo=()=>{process.stdout.write(jo())};No.command("help [command...]").description("Show help for a command (e.g. stably help create)").action(e=>{if(!e||0===e.length)return void Mo();const t=$o(No,e);if(!t)return process.stderr.write(`Unknown command: ${e.join(" ")}\n`),Mo(),void(process.exitCode=1);var r;r=t,process.stdout.write((e=>{const t=e.helpInformation().trimEnd();return t?`${t}\n`:""})(r))}),No.action(()=>so({mode:"chat",getHelpText:jo})),No.command("login").description("Authenticate with Stably in your browser").action(Dr),No.command("logout").description("Clear stored Stably credentials").action(async()=>{const e=tn();e&&(m.log.warn(`Environment variables ${D.default.cyan("STABLY_API_KEY")} and ${D.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 vr();if(!t)return void m.outro(e?D.default.yellow("No stored OAuth login found to clear."):D.default.yellow("You are not logged in."));const r=m.spinner();r.start("Logging out..."),await(async e=>{try{await fetch(`${ar}/api/backend/v1/logout`,{body:JSON.stringify({refresh_token:e}),headers:{"Content-Type":"application/json"},method:"POST"})}catch{}})(t.refreshToken),await xr(),await Cr(),r.stop(D.default.green("✓ Logged out")),m.outro(D.default.green("You have been logged out successfully."))}),No.command("whoami").description("Show auth status and current project").action(async()=>{m.log.info(`${D.default.bold("CLI Version:")} ${D.default.cyan(sr)}`);const e=tn();if(e){m.log.info(D.default.dim("Authentication: Environment variables")),m.log.info(` ${D.default.bold("API Key:")} ${D.default.cyan(e.apiKey.slice(0,8))}...`),m.log.info(` ${D.default.bold("Project ID:")} ${D.default.cyan(e.projectId)}`);const t=await vr();if(t){let e;try{e=mr(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(` ${D.default.bold("OAuth Email:")} ${D.default.cyan(e)}`),m.log.info(` ${D.default.bold("Tip:")} Unset env vars to use OAuth`)}return void m.outro(D.default.green("Authenticated via environment variables"))}const t=await vr();if(!t)return void m.outro(D.default.yellow("Not logged in. Run `stably login` to authenticate."));let r;try{r=mr(t.accessToken).email}catch{r=void 0}const n=await Rr();if(!n)return m.log.info(D.default.dim("Authentication: OAuth (not linked to a project)")),r&&m.log.info(` ${D.default.bold("Email:")} ${D.default.cyan(r)}`),void m.outro(D.default.yellow("Logged in but this directory is not linked to a project. Run `stably login` to link."));const o=await(async()=>Sr(process.cwd()))(),s=o?A.default.dirname(o):process.cwd(),i=A.default.relative(process.cwd(),s)||".";m.log.info(D.default.dim("Authentication: OAuth")),r&&m.log.info(` ${D.default.bold("Email:")} ${D.default.cyan(r)}`),m.log.info(` ${D.default.bold("Organization:")} ${D.default.cyan(n.orgName)}`),m.log.info(` ${D.default.bold("Project:")} ${D.default.cyan(n.projectName)}`),m.log.info(` ${D.default.bold("Linked at:")} ${D.default.dim(i)}`),m.outro(D.default.green("Authenticated"))}),No.command("build <input>").description("Compile a prompt file into a Playwright test").requiredOption("-o, --output <file>","Output file (required)").option("--force","Force regeneration even if prompt is unchanged").action(async(e,t)=>{try{await async function({force:e,input:t,output:r}){const n=process.cwd(),o=A.default.resolve(n,t),s=await async function({output:e}){const t=e.trim();if(!t)throw new Error("Output file is required. Example: -o tests/example.spec.ts");const r=A.default.resolve(process.cwd(),t);if([A.default.sep,"/"].some(e=>t.endsWith(e)))return{mode:"directory",dirPath:r};try{if((await k.default.stat(r)).isDirectory())return{mode:"directory",dirPath:r}}catch(e){if(!lo(e)||"ENOENT"!==e.code)throw e}if(!fn.test(r))throw new Error(`Output file must be a valid Playwright test file (e.g., .spec.ts, .test.ts): ${e}`);return{mode:"file",filePath:r}}({output:r}),i=await uo({filePath:o,errorMessage:`Prompt file not found: ${t}`});if(!i.trim())throw new Error(`Prompt file is empty: ${t}`);const a=function(e){const t=N.default.createHash(ao).update(e,"utf8").digest("hex");return`${ao}:${t}`}(i),c=po(A.default.relative(n,o)),l="directory"===s.mode,d=l?s.dirPath:A.default.dirname(s.filePath),u=(p=o,A.default.basename(p).replace(/\.prompt\.md$/,"").replace(/\.md$/,"").replace(/\.txt$/,""));var p;let f=l?await async function(e,t){return(await fo(e)).find(e=>{const r=A.default.basename(e);return r.startsWith(`${t}.spec`)||r.startsWith(`${t}.test`)})}(s.dirPath,u):s.filePath;if(!e&&f&&await async function({outputFilePath:e,promptHash:t}){try{const r=function(e){const t=e.match(/^\/\*\*[\s\S]*?@prompt-hash\s+(sha256:[a-f0-9]{64})[\s\S]*?\*\//);return t?.[1]}(await k.default.readFile(e,"utf8"));return r===t}catch(e){if(lo(e)&&"ENOENT"===e.code)return!1;throw e}}({outputFilePath:f,promptHash:a}))return D.default.green("Skipped build: test code is up to date (hash unchanged)"),"skipped";const h=l?new Set(await fo(s.dirPath)):void 0;await k.default.mkdir(d,{recursive:!0});const g=function({builtAt:e=new Date,promptFile:t,promptHash:r}){return["/**"," * @generated by stably build",` * @prompt-hash ${r}`,` * @prompt-file ${t}`,` * @built-at ${e.toISOString()}`," *",` * DO NOT EDIT MANUALLY - regenerate with: stably build ${t} --force`," */"].join("\n")}({promptFile:c,promptHash:a}),m=po(l?A.default.relative(n,s.dirPath)||s.dirPath:A.default.relative(n,s.filePath)),y=function(e){const{promptContent:t}=e;return["Compile this test specification into a Playwright test file.",..."file"===e.mode?[`Primary output file: ${e.outputFile}`,"","File creation rules:","- Always create/update the primary output file specified above."]:[`Output directory: ${e.outputDir}`,"","Choose output filename:",`- Look at existing test files in ${e.outputDir} 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. Check whether ${"file"===e.mode?e.outputFile:`the test file in ${e.outputDir} (based on prompt filename or matching test file)`} already exists.`,"2. If it exists, read it first and compare it 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 Playwright test command (e.g., `pnpm playwright test` or the repository's test command).","If tests fail, analyze the errors and iterate on the test code until all tests pass.","","Prompt specification:",t].join("\n")}(l?{mode:"directory",outputDir:m,promptContent:i}:{mode:"file",outputFile:m,promptContent:i});await so({mode:"build",prompt:y,outputDir:d,customHeader:g});const _=process.exitCode;if("number"==typeof _&&0!==_)throw new Error(`Build generation failed for: ${m}`);if(l&&!f&&h&&(f=(await fo(s.dirPath)).find(e=>!h.has(e)),!f))throw new Error(`Build finished but no new test file was created in: ${m}`);if(!f)throw new Error(`Build finished but output file was not created: ${m}`);const b=await uo({filePath:f,errorMessage:`Build finished but output file was not created: ${m}`}),E=function(e){return e.replace(co,"")}(b),w=b.startsWith(g)?b:`${g}\n\n${E}`;w!==b&&await k.default.writeFile(f,w,"utf8");const I=po(A.default.relative(n,f));return D.default.green(`Built: ${I}`),"built"}({force:t.force??!1,input:e,output:t.output})}catch(e){const t=e instanceof Error?e.message:String(e);process.stderr.write(`${t}\n`),process.exitCode=1}}),No.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 sn(),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 o=await R.startTunnel(`http://localhost:${e.port}`,{subdomain:r});n.stop(`Your local environment is available at: ${D.default.underline(D.default.cyan(o.url))}`)}),No.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((e,t)=>{const r=e.length>0&&"test"===e[0]?e.slice(1):e;return so({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((e,t)=>so({mode:"single",prompt:e,outputDir:t.output})),No.command("fix [runId]").description("Fix failing tests from a run (auto-detects from last test run or CI)").action(async e=>{const t=await(async e=>{const t=e=>e.replace(/\//g,"_");if(e)return Zr.debug("Run ID provided explicitly",{runId:e}),t(e);const 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(Dt))if(Dt[r].detect({env:e,cwd:t}))return{isCi:!0,...Dt[r].configuration({env:e,cwd:t})};return{isCi:Boolean(e.CI),...(r={env:e,cwd:t},{commit:st(r),branch:it(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 Zr.debug("Run ID detected from CI environment",{runId:r}),t(r);Zr.debug("No explicit run ID or CI environment detected, checking last-run.json");const n=await(async()=>{try{const e=await(async()=>{let e=process.cwd();const{root:t}=A.default.parse(e);for(;e!==t;){const t=A.default.join(e,".stably/last-run.json");try{return await g.access(t),t}catch{e=A.default.dirname(e)}}})();if(!e)return;const t=await g.readFile(e,"utf-8");return{...io.parse(JSON.parse(t)),filePath:e}}catch{return}})();if(n){const e=(Date.now()-n.timestamp)/36e5;return Zr.debug("Run ID found in last-run.json",{runId:n.runId,timestamp:n.timestamp,filePath:n.filePath,ageHours:Math.round(e)}),e>24&&Zr.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)}Zr.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)),so({mode:"fix",runId:t})}),No.command("init").description("Initialize Playwright and Stably SDK in your project").action(()=>so({mode:"init"})),No.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;Eo(D.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(vo,{signal:e.signal});if(!t.ok)throw new Error(`Failed to fetch latest version: ${t.statusText}`);return To.parse(await t.json()).version}finally{clearTimeout(t)}}();return{current:sr,latest:e,isOutdated:So(sr,e)}}()}catch(e){return wo(D.default.red("Failed to check for updates:"),e instanceof Error?e.message:e),void(process.exitCode=1)}if(Eo(`Current version: ${D.default.yellow(r.current)}`),Eo(`Latest version: ${D.default.green(r.latest)}`),Eo(),!r.isOutdated)return void Eo(D.default.green("✓ You are already on the latest version!"));if(Eo(D.default.yellow(`⚠ A new version is available: ${r.current} → ${r.latest}`)),Eo(),t)return Eo(D.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=o.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=o.execSync("pnpm root -g",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-pnpm"}catch{}try{const t=o.execSync("yarn global dir",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-yarn-classic"}catch{}try{const t=o.execSync("yarn config get globalFolder",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-yarn-berry"}catch{}return"unknown"}(),s=function(e){switch(e){case"global-npm":case"global-yarn-berry":case"unknown":return{command:"npm",args:["install","-g",`${Io}@latest`],description:`npm install -g ${Io}@latest`};case"global-pnpm":return{command:"pnpm",args:["add","-g",`${Io}@latest`],description:`pnpm add -g ${Io}@latest`};case"global-yarn-classic":return{command:"yarn",args:["global","add",`${Io}@latest`],description:`yarn global add ${Io}@latest`};case"npx":return{command:"npx",args:[`${Io}@latest`],description:`npx ${Io}@latest (always uses latest)`}}}(n);if("npx"===n)return Eo(D.default.dim("You are running via npx, which always fetches the latest version.")),void Eo(D.default.dim(`Simply run: ${D.default.white("npx stably")} to use the latest version.`));"unknown"===n?(Eo(D.default.yellow("Could not detect installation method. Falling back to npm.")),Eo()):"global-yarn-berry"===n&&(Eo(D.default.yellow("Yarn Berry does not support global packages. Falling back to npm.")),Eo()),Eo(`Upgrade command: ${D.default.cyan(s.description)}`),Eo(),Eo(D.default.cyan("Upgrading...")),Eo();try{await(i=s.command,a=s.args,new Promise((e,t)=>{const r=o.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)})})),Eo(),Eo(D.default.green("✓ Upgrade complete!")),Eo(D.default.dim(`Run ${D.default.white("stably --version")} to verify.`))}catch(e){wo(D.default.red("Upgrade failed:"),e instanceof Error?e.message:e),Eo(),Eo(D.default.dim("You can try manually running:")),Eo(D.default.cyan(` ${s.description}`)),process.exitCode=1}var i,a}(e)),_o.forEach(({args:e,description:r,name:n})=>{No.command(n).description(r).helpOption(!1).helpCommand(!1).allowUnknownOption(!0).allowExcessArguments(!0).passThroughOptions().action(()=>async function({overrideArgs:e,subcommand:r}){const n=process.argv,s=n.findIndex((e,t)=>t>1&&e===r),a=-1===s?[]:n.slice(s+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=_o.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=ho();if(!n.installed||!n.inNodeModules)return void r('No Playwright project found in this directory or its parents.\nMake sure you\'re in a directory within your Playwright project, or run "stably init" to create a new playwright directory.');const{packageManager:s}=n;if(!s)return void r("Could not determine package manager.");r("Playwright options:"),r("");const[i,...a]=yo(s),c=bo(s);return new Promise(t=>{const r=o.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 d=e??[],u=new Set(d.map(e=>{const[t]=e.split("=");return t})),p=[];for(let e=0;e<l.length;e++){const t=l[e],[r]=t.split("=");u.has(r)?!t.includes("=")&&e+1<l.length&&!l[e+1].startsWith("-")&&e++:p.push(t)}const f=[r,...d,...p],h="test"===r?await cn():void 0,g="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(),s=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: https://docs.stably.ai/getting-started/sdk-setup-guide\n")),r},a=(e,r)=>{try{return function({baseConfigPath:e,projectDir:r}){const n=function(e){try{const t=o.execSync("npm pkg get type",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return"module"===JSON.parse(t.trim())}catch{return!1}}(r),s=n?"mts":"ts",a=t.dirname(t.resolve(e)),c=t.basename(e),l=t.join(a,`.stably-playwright-wrapper.config.${s}`),d=`\n// Auto-generated wrapper config by Stably CLI\n// This file injects the Stably reporter and ensures trace is enabled\nimport baseConfig from './${c}';\nimport { defineConfig, stablyReporter } from '@stablyai/playwright-test';\n\n// Inline type definitions to avoid import failures when @stablyai/playwright-test is not installed\ntype StablyNotificationConfig = {\n email?: { to: string[]; notifyOnStart?: boolean; notifyOnResult?: 'all' | 'failures-only' | null } | null;\n slack?: { channelName: string; notifyOnStart?: boolean; notifyOnResult?: 'all' | 'failures-only' } | null;\n};\n\ntype ProjectNotificationConfig = {\n projectName: string;\n notifications: StablyNotificationConfig;\n};\n\n// Extract notification configs from projects that have stably.notifications defined\n// This runs at config-load time before Playwright strips custom properties\nconst extractNotificationConfigs = (): ProjectNotificationConfig[] | undefined => {\n const projects = baseConfig.projects;\n if (!projects || !Array.isArray(projects)) return undefined;\n\n const configs = projects\n .map((p: { name?: string; stably?: { notifications?: StablyNotificationConfig } }) => {\n const notifications = p.stably?.notifications;\n return notifications ? { projectName: p.name ?? '', notifications } : undefined;\n })\n .filter((config): config is ProjectNotificationConfig => config != null);\n\n return configs.length > 0 ? configs : undefined;\n};\n\nconst isStablyReporter = (reporter: unknown): boolean => {\n // Only match @stablyai npm scope to avoid false positives on unrelated reporters\n // that might contain "stably" substring (e.g., "unstably-runner")\n if (typeof reporter === 'string') {\n return reporter.includes('@stablyai');\n }\n if (Array.isArray(reporter) && typeof reporter[0] === 'string') {\n return reporter[0].includes('@stablyai');\n }\n return false;\n};\n\nconst filterOutStablyReporter = (reporters: unknown[]): unknown[] => {\n return reporters.filter((reporter) => !isStablyReporter(reporter));\n};\n\nconst buildReporterList = () => {\n const existingReporters = baseConfig.reporter;\n\n // Create the stably reporter entry with notification configs\n // This replaces any existing stably reporter to ensure notificationConfigs are included\n const stablyReporterEntry = stablyReporter({\n apiKey: process.env.STABLY_API_KEY,\n projectId: process.env.STABLY_PROJECT_ID,\n notificationConfigs: extractNotificationConfigs(),\n });\n\n // No existing reporters - just return our reporter\n if (!existingReporters) {\n return [stablyReporterEntry];\n }\n\n // Array of reporters - filter out any existing stably reporter and add ours\n if (Array.isArray(existingReporters)) {\n const filtered = filterOutStablyReporter(existingReporters);\n return [...filtered, stablyReporterEntry];\n }\n\n // Single reporter as string - check if it's a stably reporter\n if (typeof existingReporters === 'string') {\n if (isStablyReporter(existingReporters)) {\n return [stablyReporterEntry];\n }\n return [[existingReporters, {}], stablyReporterEntry];\n }\n\n // For any other type (class, object, etc.), wrap it and add our reporter\n return [[existingReporters, {}], 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,d,"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(Ln))return;const t=e.length>0&&!e.endsWith("\n");i.appendFileSync(r,`${t?"\n":""}${Ln}\n`)}else i.writeFileSync(r,`${Ln}\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 o=t.resolve(n,e[r+1]),i=t.dirname(o);if(!s(i))return;const c=a(o,i);if(!c)return;return e[r+1]=c,c}const o=e.findIndex(e=>e.startsWith("--config=")||e.startsWith("-c="));if(-1!==o){const r=t.resolve(n,e[o].split("=")[1]),i=t.dirname(r);if(!s(i))return;const c=a(r,i);if(!c)return;const l=e[o].startsWith("--config=")?"--config=":"-c=";return e[o]=`${l}${c}`,c}}const c=Bn(n);if(!c)return;const l=t.dirname(c);if(!s(l))return;const d=a(c,l);return d?(e.push("--config",d),d):void 0}({forwardedArgs:f,hasCredentials:null!=h}):void 0;!function(e,t={}){const r=ho();r.installed||(console.error('Playwright is not installed. Please run "stably init" to install it.'),process.exit(1)),r.inNodeModules||(console.error("Playwright is present in your project, but not in node_modules. Please install your dependencies before proceeding."),process.exit(1));const{packageManager:n}=r;n||(console.error("Playwright installation not found. Could not determine your package manager (tried pnpm, yarn, and npm)."),process.exit(1));const[s,...i]=yo(n),a=an(t.env),c=o.spawn(s,[...i,...e],{stdio:["inherit","pipe","pipe"],env:{...a,...process.env.CI?{}:{FORCE_COLOR:"1"}}}),l=bo(n);c.stdout?.on("data",e=>{l(e,process.stdout)}),c.stderr?.on("data",e=>{l(e,process.stderr)});let d=!1;const u=()=>{d||(d=!0,t.onClose?.())},p=e=>{u(),c.kill(e);const t="SIGINT"===e?130:143;process.exit(t)};process.on("SIGINT",p),process.on("SIGTERM",p),c.on("close",e=>{u(),process.exitCode=e??0,process.removeListener("SIGINT",p),process.removeListener("SIGTERM",p)})}(f,{env:h,onClose:()=>{var e;(e=g)&&i.existsSync(e)&&i.rmSync(e)}})}({overrideArgs:e,subcommand:n}))});var Ho=()=>{0!==ko.length&&(process.stderr.write(ko.join("")),ko=[])};(async()=>{await(async()=>{if(!Lo&&"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":sr,"node.version":process.version,"os.platform":process.platform}}),Lo=!0}catch{}})();try{await No.parseAsync(process.argv),Zr.info("CLI completed successfully")}catch(e){if(!(e=>!!e&&"object"==typeof e&&"code"in e)(e))throw Zr.error("Unexpected CLI error",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),Ho(),Zr.flush(),Zr.printLogFileInfo(),await Oo(),e;const t="number"==typeof e.exitCode?e.exitCode:1,r=process.argv.slice(2).find(e=>!e.startsWith("-")),n=!!r&&!!$o(No,[r]);if(("commander.excessArguments"===e.code||"commander.unknownCommand"===e.code)&&r&&!n)return ko=[],Zr.warn("Unknown command",{command:r}),process.stderr.write(`command '${r}' not found\n`),Mo(),void(process.exitCode=t);Zr.debug("Commander error",{code:e.code,exitCode:t}),Ho(),process.exitCode=t}finally{Zr.flush(),await Oo()}})();
2
+ "use strict";var e=require("dotenv"),t=require("path"),r=require("commander"),n=require("buffer"),o=require("child_process"),s=require("process"),i=require("fs"),a=require("url"),c=require("os");require("timers/promises");var l=require("stream"),d=require("util"),u=require("@anthropic-ai/claude-agent-sdk"),p=require("picocolors"),f=require("simple-git"),h=require("crypto"),g=require("fs/promises"),m=require("@clack/prompts"),y=require("readline/promises"),_=require("zod"),b=require("open"),E=require("http"),w=require("pino"),I=require("sonic-boom"),v=require("zod/v3"),T=require("react"),x=require("react/jsx-runtime"),S=require("yaml"),R=require("@stablyhq/runner-sdk");function A(e){return e&&e.__esModule?e:{default:e}}var C=A(t),P=A(o),U=A(s),L=A(i),O=A(c),B=A(l),D=A(p),N=A(h),k=A(g),j=A(_),$=A(b),M=A(E),H=A(w),F=A(I),G={cwdChanged:!1,newCwd:void 0,envFilesLoaded:[],envFileErrors:[]},Y=process.argv.findIndex(e=>"-C"===e||"--cwd"===e);if(-1!==Y&&process.argv[Y+1]){const e=process.argv[Y+1];process.chdir(e),G.cwdChanged=!0,G.newCwd=e,process.argv.splice(Y,2)}for(var z=[],W=0;W<process.argv.length;)if("--env-file"===process.argv[W]){const e=process.argv[W+1];e&&!e.startsWith("-")?(z.push(e),process.argv.splice(W,2)):W++}else W++;for(const t of z){const r=C.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})`;G.envFileErrors.push(e),process.stderr.write(`${e}\n`)}else G.envFilesLoaded.push(r)}var K={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 q(e){return(/\d+(?!.*\d+)/.exec(e)||[])[0]}function V(e){return e?/^(?:refs\/heads\/)?(?<branch>.+)$/i.exec(e)[1]:void 0}var J={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:V(r?e.SYSTEM_PULLREQUEST_TARGETBRANCH:e.BUILD_SOURCEBRANCH),pr:t,isPr:r,prBranch:V(r?e.SYSTEM_PULLREQUEST_SOURCEBRANCH:void 0),root:e.BUILD_REPOSITORY_LOCALPATH}}},X={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})},Q={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})},Z={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}}},ee={detect:({env:e})=>Boolean(e.BUDDY_WORKSPACE_ID),configuration({env:e}){const t=q(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}}},te="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function re(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ne,oe,se,ie,ae,ce,le,de,ue={exports:{}};var pe,fe,he,ge,me,ye,_e,be,Ee,we,Ie,ve,Te,xe,Se,Re={exports:{}},Ae={};function Ce(){if(ve)return Ie;ve=1;const e=C.default,t=function(){if(he)return fe;he=1;const e=C.default,t=function(){if(de)return le;de=1;const e="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,t=C.default,r=e?";":":",n=function(){if(ce)return ae;var e;function t(r,n,o){if("function"==typeof n&&(o=n,n={}),!o){if("function"!=typeof Promise)throw new TypeError("callback not provided");return new Promise(function(e,o){t(r,n||{},function(t,r){t?o(t):e(r)})})}e(r,n||{},function(e,t){e&&("EACCES"===e.code||n&&n.ignoreErrors)&&(e=null,t=!1),o(e,t)})}return ce=1,e="win32"===process.platform||te.TESTING_WINDOWS?function(){if(oe)return ne;oe=1,ne=r,r.sync=function(r,n){return t(e.statSync(r),r,n)};var e=L.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 o=r[n].toLowerCase();if(o&&e.substr(-o.length).toLowerCase()===o)return!0}return!1}(t,r)}function r(r,n,o){e.stat(r,function(e,s){o(e,!e&&t(s,r,n))})}return ne}():function(){if(ie)return se;ie=1,se=t,t.sync=function(t,n){return r(e.statSync(t),n)};var e=L.default;function t(t,n,o){e.stat(t,function(e,t){o(e,!e&&r(t,n))})}function r(e,t){return e.isFile()&&function(e,t){var r=e.mode,n=e.uid,o=e.gid,s=void 0!==t.uid?t.uid:process.getuid&&process.getuid(),i=void 0!==t.gid?t.gid:process.getgid&&process.getgid(),a=parseInt("100",8),c=parseInt("010",8);return r&parseInt("001",8)||r&c&&o===i||r&a&&n===s||r&(a|c)&&0===s}(e,t)}return se}(),ae=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}},ae}(),o=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),s=(t,n)=>{const o=n.colon||r,s=t.match(/\//)||e&&t.match(/\\/)?[""]:[...e?[process.cwd()]:[],...(n.path||process.env.PATH||"").split(o)],i=e?n.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",a=e?i.split(o):[""];return e&&-1!==t.indexOf(".")&&""!==a[0]&&a.unshift(""),{pathEnv:s,pathExt:a,pathExtExe:i}},i=(e,r,i)=>{"function"==typeof r&&(i=r,r={}),r||(r={});const{pathEnv:a,pathExt:c,pathExtExe:l}=s(e,r),d=[],u=n=>new Promise((s,i)=>{if(n===a.length)return r.all&&d.length?s(d):i(o(e));const c=a[n],l=/^".*"$/.test(c)?c.slice(1,-1):c,u=t.join(l,e),f=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;s(p(f,n,0))}),p=(e,t,o)=>new Promise((s,i)=>{if(o===c.length)return s(u(t+1));const a=c[o];n(e+a,{pathExt:l},(n,i)=>{if(!n&&i){if(!r.all)return s(e+a);d.push(e+a)}return s(p(e,t,o+1))})});return i?u(0).then(e=>i(null,e),i):u(0)};return le=i,i.sync=(e,r)=>{r=r||{};const{pathEnv:i,pathExt:a,pathExtExe:c}=s(e,r),l=[];for(let o=0;o<i.length;o++){const s=i[o],d=/^".*"$/.test(s)?s.slice(1,-1):s,u=t.join(d,e),p=!d&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;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 o(e)},le}(),r=function(){if(pe)return Re.exports;pe=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 Re.exports=e,Re.exports.default=e,Re.exports}();function n(n,o){const s=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:s[r({env:s})],pathExt:o?e.delimiter:void 0})}catch(e){}finally{c&&process.chdir(i)}return l&&(l=e.resolve(a?n.options.cwd:"",l)),l}return fe=function(e){return n(e)||n(e,!0)}}(),r=function(){if(ge)return Ae;ge=1;const e=/([()\][%!^"`<>&|;, *?])/g;return Ae.command=function(t){return t.replace(e,"^$1")},Ae.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},Ae}(),n=function(){if(we)return Ee;we=1;const e=L.default,t=function(){if(be)return _e;be=1;const e=ye?me:(ye=1,me=/^#!(.*)/);return _e=(t="")=>{const r=t.match(e);if(!r)return null;const[n,o]=r[0].replace(/#! ?/,"").split(" "),s=n.split("/").pop();return"env"===s?o:o?`${s} ${o}`:s}}();return Ee=function(r){const n=Buffer.alloc(150);let o;try{o=e.openSync(r,"r"),e.readSync(o,n,0,150,0),e.closeSync(o)}catch(e){}return t(n.toString())},Ee}(),o="win32"===process.platform,s=/\.(?:com|exe)$/i,i=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;return Ie=function(a,c,l){c&&!Array.isArray(c)&&(l=c,c=null);const d={command:a,args:c=c?c.slice(0):[],options:l=Object.assign({},l),file:void 0,original:{command:a,args:c}};return l.shell?d:function(a){if(!o)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=!s.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}(d)}}var Pe=re(function(){if(Se)return ue.exports;Se=1;const e=P.default,t=Ce(),r=function(){if(xe)return Te;xe=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 Te={hookChildProcess:function(t,n){if(!e)return;const o=t.emit;t.emit=function(e,s){if("exit"===e){const e=r(s,n);if(e)return o.call(t,"error",e)}return o.apply(t,arguments)}},verifyENOENT:r,verifyENOENTSync:function(r,n){return e&&1===r&&!n.file?t(n.original,"spawnSync"):null},notFoundError:t},Te}();function n(n,o,s){const i=t(n,o,s),a=e.spawn(i.command,i.args,i.options);return r.hookChildProcess(a,i),a}return ue.exports=n,ue.exports.spawn=n,ue.exports.sync=function(n,o,s){const i=t(n,o,s),a=e.spawnSync(i.command,i.args,i.options);return a.error=a.error||r.verifyENOENTSync(a.status,i),a},ue.exports._parse=t,ue.exports._enoent=r,ue.exports}());function Ue(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 Le=(e,t)=>({name:`SIGRT${t+1}`,number:Oe+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),Oe=34,Be=[{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"}],De=()=>{const e=(()=>{const e=64-Oe+1;return Array.from({length:e},Le)})();return[...Be,...e].map(Ne)},Ne=({name:e,number:t,description:r,action:n,forced:o=!1,standard:s})=>{const{signals:{[e]:i}}=c.constants,a=void 0!==i;return{name:e,number:a?i:t,description:r,supported:a,action:n,forced:o,standard:s}},ke=({name:e,number:t,description:r,supported:n,action:o,forced:s,standard:i})=>[e,{name:e,number:t,description:r,supported:n,action:o,forced:s,standard:i}],je=(()=>{const e=De();return Object.fromEntries(e.map(ke))})();(()=>{const e=De(),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:o,supported:s,action:i,forced:a,standard:l}=r;return{[e]:{name:n,number:e,description:o,supported:s,action:i,forced:a,standard:l}}})(r,e));Object.assign({},...t)})();var $e=({stdout:e,stderr:t,all:r,error:n,signal:o,exitCode:s,command:i,escapedCommand:a,timedOut:c,isCanceled:l,killed:d,parsed:{options:{timeout:u,cwd:p=U.default.cwd()}}})=>{s=null===s?void 0:s;const f=void 0===(o=null===o?void 0:o)?void 0:je[o].description,h=(({timedOut:e,timeout:t,errorCode:r,signal:n,signalDescription:o,exitCode:s,isCanceled:i})=>e?`timed out after ${t} milliseconds`:void 0!==r?`failed with ${r}`:void 0!==n?`was killed with ${n} (${o})`:void 0!==s?`failed with exit code ${s}`:"failed")({timedOut:c,timeout:u,errorCode:n&&n.code,signal:o,signalDescription:f,exitCode:s,isCanceled:l}),g=`Command ${h}: ${i}`,m="[object Error]"===Object.prototype.toString.call(n),y=m?`${g}\n${n.message}`:g,_=[y,t,e].filter(Boolean).join("\n");return m?(n.originalMessage=n.message,n.message=_):n=new Error(_),n.shortMessage=y,n.command=i,n.escapedCommand=a,n.exitCode=s,n.signal=o,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=d&&!c,n},Me=["stdin","stdout","stderr"],He=[];He.push("SIGHUP","SIGINT","SIGTERM"),"win32"!==process.platform&&He.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),"linux"===process.platform&&He.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var Fe,Ge,Ye=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,ze=Symbol.for("signal-exit emitter"),We=globalThis,Ke=Object.defineProperty.bind(Object),qe=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(We[ze])return We[ze];Ke(We,ze,{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 o of this.listeners[e])n=!0===o(t,r)||n;return"exit"===e&&(n=this.emit("afterExit",t,r)||n),n}},Ve=class{},Je=globalThis.process;Ye(Je)?new class extends Ve{#e="win32"===Je.platform?"SIGINT":"SIGHUP";#t=new qe;#r;#n;#o;#s={};#i=!1;constructor(e){super(),this.#r=e,this.#s={};for(const t of He)this.#s[t]=()=>{const r=this.#r.listeners(t);let{count:n}=this.#t;const o=e;if("object"==typeof o.__signal_exit_emitter__&&"number"==typeof o.__signal_exit_emitter__.count&&(n+=o.__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.#o=e.reallyExit,this.#n=e.emit}onExit(e,t){if(!Ye(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 He)try{const t=this.#s[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,He.forEach(e=>{const t=this.#s[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.#o,this.#t.count-=1)}#c(e){return Ye(this.#r)?(this.#r.exitCode=e||0,this.#t.emit("exit",this.#r.exitCode,null),this.#o.call(this.#r,this.#r.exitCode)):0}#a(e,...t){const r=this.#n;if("exit"===e&&Ye(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)}}(Je):new class extends Ve{onExit(){return()=>{}}load(){}unload(){}},new TextEncoder,function(){if(Ge)return Fe;Ge=1;const{PassThrough:e}=B.default;Fe=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",o),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",o.bind(null,e)),e.once("error",r.emit.bind(r,"error")),e.pipe(r,{end:!1}),this)}function o(e){!(t=t.filter(function(t){return t!==e})).length&&r.readable&&r.end()}}}();var Xe=(async()=>{})().constructor.prototype;["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(Xe,e)]);var Qe=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],Ze=/^[\w.-]+$/,et=d.debuglog("execa").enabled,tt=(e,t)=>String(e).padStart(t,"0"),rt=(e,t,r={})=>{const n=Pe._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||U.default.cwd(),execPath:U.default.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:et,...r}).env=(({env:e,extendEnv:t,preferLocal:r,localDir:n,execPath:o})=>{const s=t?{...U.default.env,...e}:e;return r?(({env:e=U.default.env,...t}={})=>{const r=Ue({env:e={...e}});return t.path=e[r],e[r]=(({cwd:e=U.default.cwd(),path:t=U.default.env[Ue()],preferLocal:r=!0,execPath:n=U.default.execPath,addExecPath:o=!0}={})=>{const s=e instanceof URL?a.fileURLToPath(e):e,i=C.default.resolve(s),c=[];return r&&((e,t)=>{let r;for(;r!==t;)e.push(C.default.join(t,"node_modules/.bin")),r=t,t=C.default.resolve(t,"..")})(c,i),o&&((e,t,r)=>{const n=t instanceof URL?a.fileURLToPath(t):t;e.push(C.default.resolve(r,n,".."))})(c,n,i),[...c,t].join(C.default.delimiter)})(t),e})({env:s,cwd:n,execPath:o}):s})(r),r.stdio=(e=>{if(!e)return;const{stdio:t}=e;if(void 0===t)return Me.map(t=>e[t]);if((e=>Me.some(t=>void 0!==e[t]))(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${Me.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,Me.length);return Array.from({length:r},(e,r)=>t[r])})(r),"win32"===U.default.platform&&"cmd"===C.default.basename(e,".exe")&&t.unshift("/q"),{file:e,args:t,options:r,parsed:n}},nt=(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 ot(e,t,r){const n=rt(e,t,r),o=((e,t)=>Qe(e,t).join(" "))(e,t),s=((e,t)=>Qe(e,t).map(e=>(e=>"string"!=typeof e||Ze.test(e)?e:`"${e.replaceAll('"','\\"')}"`)(e)).join(" "))(e,t);((e,{verbose:t})=>{t&&U.default.stderr.write(`[${(()=>{const e=new Date;return`${tt(e.getHours(),2)}:${tt(e.getMinutes(),2)}:${tt(e.getSeconds(),2)}.${tt(e.getMilliseconds(),3)}`})()}] ${e}\n`)})(s,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=P.default.spawnSync(n.file,n.args,{...n.options,input:a})}catch(e){throw $e({error:e,stdout:"",stderr:"",all:"",command:o,escapedCommand:s,parsed:n,timedOut:!1,isCanceled:!1,killed:!1})}const l=nt(n.options,c.stdout,c.error),d=nt(n.options,c.stderr,c.error);if(c.error||0!==c.status||null!==c.signal){const e=$e({stdout:l,stderr:d,error:c.error,signal:c.signal,exitCode:c.status,command:o,escapedCommand:s,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:o,escapedCommand:s,exitCode:0,stdout:l,stderr:d,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}}function st(e){try{return ot("git",["rev-parse","HEAD"],e).stdout}catch{return}}function it(e){try{const t=ot("git",["rev-parse","--abbrev-ref","HEAD"],e).stdout;if("HEAD"===t){const t=ot("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 at=/^(?:.*)@(?:.*):(?:\d+\/)?(.*)\.git$/,ct=/^\/(.*)\.git$/;function lt(e){if(e){if(e.match(at))return e.replace(at,"$1");try{return new URL(e).pathname.replace(ct,"$1")}catch{return}}}var dt,ut={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:lt(e.BUILDKITE_REPO),pr:t,isPr:r,prBranch:r?e.BUILDKITE_BRANCH:void 0,root:e.BUILDKITE_BUILD_CHECKOUT_PATH}}},pt={detect:({env:e})=>Boolean(e.CIRCLECI),configuration({env:e}){const t=e.CIRCLE_PR_NUMBER||q(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}`}}},ft="https://cirrus-ci.com",ht={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:`${ft}/build/${e.CIRRUS_BUILD_ID}`,job:e.CIRRUS_TASK_ID,jobUrl:`${ft}/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}}},gt={detect:({env:e})=>Boolean(e.CODEBUILD_BUILD_ID),configuration:({env:e,cwd:t})=>({name:"AWS CodeBuild",service:"codebuild",commit:st({env:e,cwd:t}),build:e.CODEBUILD_BUILD_ID,branch:it({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})},mt={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}}},yt={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}}},_t=({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?V(t.pull_request.base.ref):void 0,pr:t.pull_request.number}}catch{}return{pr:void 0,branch:void 0}},bt={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=V("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?_t({env:e}):void 0}}},Et={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}}},wt={detect:({env:e})=>Boolean(e.JENKINS_URL),configuration({env:e,cwd:t}){const r=e.ghprbPullId||e.gitlabMergeRequestId||e.CHANGE_ID,n=Boolean(r),o=e.GIT_LOCAL_BRANCH||e.GIT_BRANCH||e.gitlabBranch||e.BRANCH_NAME;return{name:"Jenkins",service:"jenkins",commit:e.ghprbActualCommit||e.GIT_COMMIT||st({env:e,cwd:t}),branch:n?e.ghprbTargetBranch||e.gitlabTargetBranch:o,build:e.BUILD_NUMBER,buildUrl:e.BUILD_URL,root:e.WORKSPACE,pr:r,isPr:n,prBranch:n?e.ghprbSourceBranch||e.gitlabSourceBranch||o:void 0}}},It={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}}},vt={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})},Tt={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}}},xt={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}}},St={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}}},Rt={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||st({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}}},At={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}}},Ct={};function Pt(){if(dt)return Ct;dt=1,Object.defineProperty(Ct,"__esModule",{value:!0}),Ct.of=Ct.PropertiesFile=void 0;var e,t=(e=L.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(),o=e.substring(r+1).trim();if(this.objs.hasOwnProperty(n))if(Array.isArray(this.objs[n]))this.objs[n].push(o);else{let e=this.objs[n];this.objs[n]=[e,o]}else{const e=o.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 Ct.PropertiesFile=r,Ct.of=function(...e){let t=new r;return t.of.apply(t,e),t},Ct}var Ut=re(Pt()),Lt={root:"teamcity.build.workingDir",branch:"teamcity.build.branch"},Ot=e=>{try{return Ut.of(e)}catch{return}},Bt=({env:e,cwd:t})=>{const r=e.TEAMCITY_BUILD_PROPERTIES_FILE?Ot(e.TEAMCITY_BUILD_PROPERTIES_FILE):void 0,n=r?r.get("teamcity.configuration.properties.file"):void 0,o=n?Ot(n):n;return Object.fromEntries(Object.keys(Lt).map(n=>[n,(r?r.get(Lt[n]):void 0)||(o?o.get(Lt[n]):void 0)||("branch"===n?it({env:e,cwd:t}):void 0)]))},Dt={appveyor:K,azurePipelines:J,bamboo:X,bitbucket:Q,bitrise:Z,buddy:ee,buildkite:ut,circleci:pt,cirrus:ht,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:gt,codefresh:mt,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:yt,github:bt,gitlab:Et,jenkins:wt,netlify:It,puppet:vt,sail:Tt,screwdriver:xt,scrutinizer:St,semaphore:Rt,shippable:At,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,...Bt({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:V(e.JB_SPACE_GIT_BRANCH),slug:t&&r?`${t.toLowerCase()}/${r}`:void 0}}}},Nt=class e{git;config;snapshotTreeHash;snapshotIndexPath;constructor(e){this.config=e,this.git=f.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-${h.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-${h.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 kt(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 kt(this.snapshotIndexPath),this.snapshotIndexPath=void 0),this.snapshotTreeHash=void 0}};async function kt(e){try{await g.unlink(e)}catch{}}var jt="x-stably-org-id",$t={bodySerializer:e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t)},Mt=({allowReserved:e,explode:t,name:r,style:n,value:o})=>{if(!t){const t=(e?o:o.map(e=>encodeURIComponent(e))).join((e=>{switch(e){case"form":default:return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20"}})(n));switch(n){case"label":return`.${t}`;case"matrix":return`;${r}=${t}`;case"simple":return t;default:return`${r}=${t}`}}const s=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(n),i=o.map(t=>"label"===n||"simple"===n?e?t:encodeURIComponent(t):Ht({allowReserved:e,name:r,value:t})).join(s);return"label"===n||"matrix"===n?s+i:i},Ht=({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)}`},Ft=({allowReserved:e,explode:t,name:r,style:n,value:o,valueOnly:s})=>{if(o instanceof Date)return s?o.toISOString():`${r}=${o.toISOString()}`;if("deepObject"!==n&&!t){let t=[];Object.entries(o).forEach(([r,n])=>{t=[...t,r,e?n:encodeURIComponent(n)]});const s=t.join(",");switch(n){case"form":return`${r}=${s}`;case"label":return`.${s}`;case"matrix":return`;${r}=${s}`;default:return s}}const i=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(n),a=Object.entries(o).map(([t,o])=>Ht({allowReserved:e,name:"deepObject"===n?`${r}[${t}]`:t,value:o})).join(i);return"label"===n||"matrix"===n?i+a:a},Gt=/\{[^{}]+\}/g;function Yt(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 zt,Wt=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},Kt=({parameters:e={},...t}={})=>r=>{const n=[];if(r&&"object"==typeof r)for(const o in r){const s=r[o];if(null==s)continue;const i=e[o]||t;if(Array.isArray(s)){const e=Mt({allowReserved:i.allowReserved,explode:!0,name:o,style:"form",value:s,...i.array});e&&n.push(e)}else if("object"==typeof s){const e=Ft({allowReserved:i.allowReserved,explode:!0,name:o,style:"deepObject",value:s,...i.object});e&&n.push(e)}else{const e=Ht({allowReserved:i.allowReserved,name:o,value:s});e&&n.push(e)}}return n.join("&")},qt=(e,t)=>!!t&&!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`)),Vt=e=>(({baseUrl:e,path:t,query:r,querySerializer:n,url:o})=>{let s=(e??"")+(o.startsWith("/")?o:`/${o}`);t&&(s=(({path:e,url:t})=>{let r=t;const n=t.match(Gt);if(n)for(const t of n){let n=!1,o=t.substring(1,t.length-1),s="simple";o.endsWith("*")&&(n=!0,o=o.substring(0,o.length-1)),o.startsWith(".")?(o=o.substring(1),s="label"):o.startsWith(";")&&(o=o.substring(1),s="matrix");const i=e[o];if(null==i)continue;if(Array.isArray(i)){r=r.replace(t,Mt({explode:n,name:o,style:s,value:i}));continue}if("object"==typeof i){r=r.replace(t,Ft({explode:n,name:o,style:s,value:i,valueOnly:!0}));continue}if("matrix"===s){r=r.replace(t,`;${Ht({name:o,value:i})}`);continue}const a=encodeURIComponent("label"===s?`.${i}`:i);r=r.replace(t,a)}return r})({path:t,url:s}));let i=r?n(r):"";return i.startsWith("?")&&(i=i.substring(1)),i&&(s+=`?${i}`),s})({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:"function"==typeof e.querySerializer?e.querySerializer:Kt(e.querySerializer),url:e.url}),Jt=(e,t)=>{const r={...e,...t};return r.baseUrl?.endsWith("/")&&(r.baseUrl=r.baseUrl.substring(0,r.baseUrl.length-1)),r.headers=Qt(e.headers,t.headers),r},Xt=e=>{const t=[];return e.forEach((e,r)=>{t.push([r,e])}),t},Qt=(...e)=>{const t=new Headers;for(const r of e){if(!r)continue;const e=r instanceof Headers?Xt(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},Zt=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}},er=Kt({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),tr={"Content-Type":"application/json"},rr=(e={})=>({...$t,headers:tr,parseAs:"auto",querySerializer:er,...e}),nr=(e={})=>{let t=Jt(rr(),e);const r=()=>({...t}),n={error:new Zt,request:new Zt,response:new Zt},o=async e=>{const r={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:Qt(t.headers,e.headers),serializedBody:void 0};return r.security&&await(async({security:e,...t})=>{for(const r of e){if(qt(t,r.name))continue;const e=await Wt(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:Vt(r)}},s=async e=>{const{opts:t,url:r}=await o(e),s={redirect:"follow",...t,body:Yt(t)};let i=new Request(r,s);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 o of n.error.fns)o&&(r=await o(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 d=await c.text();let u;try{u=JSON.parse(d)}catch{}const p=u??d;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=>s({...t,method:e}),a=e=>async t=>{const{opts:r,url:s}=await o(t);return(({onRequest:e,onSseError:t,onSseEvent:r,responseTransformer:n,responseValidator:o,sseDefaultRetryDelay:s,sseMaxRetryAttempts:i,sseMaxRetryDelay:a,sseSleepFn:c,url:l,...d})=>{let u;const p=c??(e=>new Promise(t=>setTimeout(t,e))),f=async function*(){let c=s??3e3,f=0;const h=d.signal??(new AbortController).signal;for(;!h.aborted;){f++;const s=d.headers instanceof Headers?d.headers:new Headers(d.headers);void 0!==u&&s.set("Last-Event-ID",u);try{const t={redirect:"follow",...d,body:d.serializedBody,headers:s,signal:h};let i=new Request(l,t);e&&(i=await e(l,t));const a=d.fetch??globalThis.fetch,p=await a(i);if(!p.ok)throw new Error(`SSE failed: ${p.status} ${p.statusText}`);if(!p.body)throw new Error("No body in SSE response");const f=p.body.pipeThrough(new TextDecoderStream).getReader();let g="";const m=()=>{try{f.cancel()}catch{}};h.addEventListener("abort",m);try{for(;;){const{done:e,value:t}=await f.read();if(e)break;g+=t;const s=g.split("\n\n");g=s.pop()??"";for(const e of s){const t=e.split("\n"),s=[];let i,a;for(const e of t)if(e.startsWith("data:"))s.push(e.replace(/^data:\s*/,""));else if(e.startsWith("event:"))i=e.replace(/^event:\s*/,"");else if(e.startsWith("id:"))u=e.replace(/^id:\s*/,"");else if(e.startsWith("retry:")){const t=Number.parseInt(e.replace(/^retry:\s*/,""),10);Number.isNaN(t)||(c=t)}let l=!1;if(s.length){const e=s.join("\n");try{a=JSON.parse(e),l=!0}catch{a=e}}l&&(o&&await o(a),n&&(a=await n(a))),r?.({data:a,event:i,id:u,retry:c}),s.length&&(yield a)}}}finally{h.removeEventListener("abort",m),f.releaseLock()}break}catch(e){if(t?.(e),void 0!==i&&f>=i)break;const 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 o=new Request(e,t);for(const e of n.request.fns)e&&(o=await e(o,r));return o},url:s})};return{buildUrl:Vt,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:s,setConfig:e=>(t=Jt(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")}},or=nr(rr({baseUrl:"https://api.stably.ai"})),sr="4.4.5",ir=process.env.STABLY_API_URL||"https://api.stably.ai",ar=process.env.AUTH_URL||"https://auth.stably.ai",cr=process.env.AUTH_CLIENT_ID||"288007877071cce81f269428ea78653a",lr=process.env.AI_PROXY_URL||"https://ai-proxy.stably.ai",dr="http://localhost:9876/auth/callback",ur=()=>zt||(zt=nr(rr({baseUrl:ir,headers:{"X-STABLY-CLI-VERSION":sr,"X-STABLY-SOURCE":"cli"}}))),pr=async(e,t)=>{const r=await(n={body:{accessToken:e,orgId:t},client:ur()},(n.client??or).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},fr=_.z.object({org_id:_.z.string(),org_name:_.z.string()}),hr=_.z.object({email:_.z.string(),org_id_to_org_member_info:_.z.record(_.z.string(),fr).optional(),org_member_info:fr.optional(),user_id:_.z.string()});_.z.object({email:_.z.string(),firstName:_.z.string().optional(),lastName:_.z.string().optional(),organizations:_.z.array(_.z.object({id:_.z.string(),name:_.z.string()})),userId:_.z.string()});var gr=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)},mr=e=>{try{const t=hr.parse(gr(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"}`)}},yr=C.default.join(O.default.homedir(),".stably"),_r=C.default.join(yr,"auth.json"),br=".stably",Er="project.json",wr=j.default.object({accessToken:j.default.string(),expiresAt:j.default.number(),idToken:j.default.string().optional(),refreshToken:j.default.string()}),Ir=j.default.object({orgId:j.default.string(),orgName:j.default.string(),projectId:j.default.string(),projectName:j.default.string()}),vr=async()=>{try{const e=await g.readFile(_r,"utf-8");return wr.parse(JSON.parse(e))}catch{return}},Tr=async e=>{await g.mkdir(yr,{recursive:!0}),await g.writeFile(_r,JSON.stringify(e,null,2),{mode:384})},xr=async()=>{try{await g.unlink(_r)}catch{}},Sr=async e=>{let t=e;const{root:r}=C.default.parse(t);for(;t!==r;){const e=C.default.join(t,br);try{return await g.access(e),e}catch{t=C.default.dirname(t)}}},Rr=async()=>{try{const e=await Sr(process.cwd());if(!e)return;const t=C.default.join(e,Er),r=await g.readFile(t,"utf-8");return Ir.parse(JSON.parse(r))}catch{return}},Ar=async()=>{try{const e=await Sr(process.cwd());e&&await g.unlink(C.default.join(e,Er))}catch{}},Cr=e=>Date.now()>=e.expiresAt-3e5,Pr=async e=>{const t=new URLSearchParams({client_id:cr,grant_type:"refresh_token",refresh_token:e}),r=await fetch(`${ar}/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}},Ur=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`,Lr=(e,t,r)=>{e.writeHead(t,{"Content-Type":"text/html"}),e.end(r)},Or=(e,t)=>{const r=new URLSearchParams({client_id:cr,code_challenge:e,code_challenge_method:"S256",redirect_uri:dr,response_type:"code",state:t});return`${ar}/propelauth/oauth/authorize?${r.toString()}`},Br=async e=>{const t=m.spinner();let r;t.start("Loading user info...");try{r=mr(e.accessToken),t.stop(D.default.green(`✓ Logged in as ${D.default.cyan(r.email)}`))}catch(e){t.stop(D.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: ${D.default.cyan(e[0].name)}`),e[0];if(!process.stdin.isTTY)return m.log.info(`Auto-selecting organization: ${D.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 o;t.start("Getting org credentials...");try{const r=await pr(e.accessToken,n.id);o={accessToken:r.accessToken,expiresAt:Date.now()+1e3*r.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken},t.stop(D.default.green("✓ Credentials obtained"))}catch(e){t.stop(D.default.red("✗ Failed to get org credentials"));const r=e instanceof Error?e.message:"Unknown error";return m.log.error(r),{success:!1}}const s=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:ur(),path:{orgId:t}},(n.client??or).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(D.default.green("✓ Projects loaded"))}catch(e){r.stop(D.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 ${D.default.underline(D.default.cyan("https://app.stably.ai"))}`);if(1===n.length)return m.log.info(`Using project: ${D.default.cyan(n[0].name)}`),n[0];if(!process.stdin.isTTY)return m.log.info(`Auto-selecting project: ${D.default.cyan(n[0].name)}`),n[0];const o=await m.select({message:"Select a project",options:n.map(e=>({label:e.name,value:e.id}))});return m.isCancel(o)?void 0:n.find(e=>e.id===o)})(o.accessToken,n.id);return s?(await(async e=>{const t=C.default.join(process.cwd(),br),r=C.default.join(t,Er);await g.mkdir(t,{recursive:!0}),await g.writeFile(r,JSON.stringify(e,null,2)),await(async e=>{const t=C.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 o=/^# Stably CLI\n\.stably\/?$/m,s=/^\.stably\/?$/m;if(o.test(e)){const n=e.replace(o,`\n${r}\n`);await g.writeFile(t,n)}else if(s.test(e)){const n=e.replace(s,`\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:s.id,projectName:s.name}),m.log.info(D.default.dim("Linked this directory to your Stably project.")),{scopedTokens:o,success:!0}):(m.log.warn("Project selection cancelled."),{success:!1})},Dr=async()=>{if(tn())return m.log.warn(`Environment variables ${D.default.cyan("STABLY_API_KEY")} and ${D.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(D.default.yellow("Login skipped - using environment variable authentication."));const e=await vr();if(e){if(!Cr(e)){if(await Rr())return void m.outro(D.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 Br(e);return void(t.success?(await Tr(t.scopedTokens),m.outro(D.default.green("Setup complete! You can now use Stably CLI."))):m.outro(D.default.yellow("Setup incomplete. Run `stably login` to try again.")))}const t=m.spinner();t.start("Refreshing session...");try{const r=await Pr(e.refreshToken);t.stop(D.default.green("✓ Session refreshed"));const n=await Rr();if(n){t.start("Getting org credentials...");try{const e=await pr(r.accessToken,n.orgId),o={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:r.idToken,refreshToken:r.refreshToken};await Tr(o),t.stop(D.default.green("✓ Credentials obtained")),m.outro(D.default.green("Login successful"))}catch{await Tr(r),t.stop(D.default.yellow("Using full credentials")),m.outro(D.default.green("Login successful"))}}else{const e=await Br(r);e.success?(await Tr(e.scopedTokens),m.outro(D.default.green("Setup complete! You can now use Stably CLI."))):m.outro(D.default.yellow("Setup incomplete. Run `stably login` to try again."))}return}catch{t.stop(D.default.yellow("Session expired, proceeding with fresh login...")),await xr(),await Ar()}}const{authorizeUrl:t,waitForCallback:r}=(()=>{const{authorizeUrl:e,codeVerifier:t,state:r}=(()=>{const e=N.default.randomBytes(32).toString("base64url"),t=(r=e,N.default.createHash("sha256").update(r).digest("base64url"));var r;const n=N.default.randomBytes(16).toString("base64url");return{authorizeUrl:Or(t,n),codeVerifier:e,state:n}})();return{authorizeUrl:e,waitForCallback:async()=>(async(e,t)=>{const r=await(n=e,new Promise((e,t)=>{const r=setTimeout(()=>{s.close(),e({error:"Login timed out",success:!1})},3e5),o=()=>{clearTimeout(r)},s=M.default.createServer((t,r)=>{const i=new a.URL(t.url||"","http://localhost:9876");if("/auth/callback"!==i.pathname)return r.writeHead(404),void r.end("Not found");const c=i.searchParams.get("code"),l=i.searchParams.get("state"),d=i.searchParams.get("error");return d?(Lr(r,400,Ur(d)),o(),s.close(),void e({error:d,success:!1})):c&&l?l!==n?(Lr(r,400,Ur("Invalid state parameter (possible CSRF attack)")),o(),s.close(),void e({error:"State mismatch",success:!1})):(Lr(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'),o(),s.close(),void e({code:c,state:l,success:!0})):(Lr(r,400,Ur("Missing code or state parameter")),o(),s.close(),void e({error:"Missing code or state parameter",success:!1}))});s.on("error",e=>{o(),"EADDRINUSE"!==e.code?t(new Error(`Failed to start callback server: ${e.message}`)):t(new Error("Port 9876 is already in use. Please close the application using it and try again."))}),s.listen(9876)}));var n;if(!r.success)throw new Error(r.error);return(async(e,t)=>{const r=new URLSearchParams({client_id:cr,code:e,code_verifier:t,grant_type:"authorization_code",redirect_uri:dr}),n=await fetch(`${ar}/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 o=await n.json();return{accessToken:o.access_token,expiresAt:Date.now()+1e3*o.expires_in,idToken:o.id_token,refreshToken:o.refresh_token}})(r.code,t)})(r,t)}})();m.log.info("Opening browser for authentication..."),m.log.info(D.default.dim("If browser doesn't open, visit:")),m.log.info(D.default.underline(D.default.cyan(t)));try{await $.default(t)}catch{m.log.warn("Could not open browser automatically. Please open the URL above manually.")}const n=m.spinner();let o;n.start("Waiting for authentication...");try{o=await r(),n.stop(D.default.green("✓ Authentication successful"))}catch(e){n.stop(D.default.red("✗ Authentication failed"));const t=e instanceof Error?e.message:"Unknown error";m.outro(D.default.red(`Login failed: ${t}`)),process.exit(1)}const s=await Br(o);s.success?(await Tr(s.scopedTokens),m.outro(D.default.green("Setup complete! You can now use Stably CLI."))):(m.outro(D.default.yellow("Setup incomplete. Run `stably login` to try again.")),process.exit(1))},Nr={fatal:60,error:50,warn:40,info:30,debug:20,trace:10},kr=new Set(["help","login","logout","whoami","tunnel","create","fix","init","upgrade","test","show-report","codegen"]),jr=(new Date).toISOString().split("T")[0],$r=C.default.join(O.default.tmpdir(),"stably-logs",jr);L.default.mkdirSync($r,{recursive:!0});var Mr,Hr=process.argv.includes("--verbose")||process.argv.includes("-v"),Fr=process.env.STABLY_LOG_LEVEL?.toLowerCase(),Gr=Hr?"debug":void 0!==(Mr=Fr)&&Mr in Nr?Fr:"warn",Yr=Nr[Gr],zr=null,Wr=null,Kr=null,qr=[],Vr=!1,Jr=e=>{if(!Vr){zr=(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 C.default.join($r,`${t}-${r}.log`)})(e),(e=>{const t=["","=".repeat(60),"Stably CLI Debug Log",`Version: ${sr}`,`Generated: ${(new Date).toISOString()}`,`Node: ${process.version}`,`Platform: ${process.platform} ${O.default.release()}`,`CWD: ${process.cwd()}`,`Args: ${process.argv.slice(2).join(" ")}`,`Log Level (console): ${Gr}`,"=".repeat(60),""].join("\n");e.write(t)})(Wr=new F.default({dest:zr,minLength:4096,sync:!1,append:!0})),Kr=H.default({level:"debug",timestamp:H.default.stdTimeFunctions.isoTime,base:{version:sr}},Wr);for(const{level:e,msg:t,context:r}of qr)r?Kr[e](r,t):Kr[e](t);qr=[],Vr=!0,Hr&&process.stderr.write(`${D.default.dim(`Debug log: ${zr}`)}\n\n`)}},Xr=(()=>{const e=process.argv.slice(2).find(e=>!e.startsWith("-"));return e&&kr.has(e)?e:null})();Xr&&Jr(Xr);var Qr=e=>(t,r)=>{if(Kr?r?Kr[e](r,t):Kr[e](t):qr.push({level:e,msg:t,context:r}),(e=>Nr[e]>=Yr)(e)){const r=((e,t)=>`${{fatal:D.default.bgRed(D.default.white(" FATAL ")),error:D.default.red("error"),warn:D.default.yellow("warn"),info:D.default.cyan("info"),debug:D.default.dim("debug"),trace:D.default.dim("trace")}[e]} ${t}`)(e,t);process.stderr.write(`${r}\n`)}},Zr={fatal:Qr("fatal"),error:Qr("error"),warn:Qr("warn"),info:Qr("info"),debug:Qr("debug"),trace:Qr("trace"),initSession:e=>{Vr||Jr(e)},getLogFilePath:()=>zr,flush:()=>{if(Wr)try{Wr.flushSync()}catch{}},printLogFileInfo:()=>{zr&&(process.stderr.write(`\n${D.default.dim("Debug log written to:")}\n`),process.stderr.write(` ${D.default.cyan(zr)}\n`),process.stderr.write(`${D.default.dim("Share this file with support for assistance.")}\n`))},getPinoLogger:()=>Kr};setInterval(()=>{Zr.flush()},3e4).unref(),process.on("beforeExit",()=>{Zr.flush()});var en=e=>{const t=()=>{Zr.flush(),Hr&&Zr.printLogFileInfo(),process.removeListener(e,t),process.kill(process.pid,e)};return t};process.on("SIGINT",en("SIGINT")),process.on("SIGTERM",en("SIGTERM"));var tn=()=>{const e=process.env.STABLY_API_KEY?.trim(),t=process.env.STABLY_PROJECT_ID?.trim();if(e&&t)return Zr.debug("Environment auth detected",{hasApiKey:!0,hasProjectId:!0}),{apiKey:e,projectId:t};Zr.debug("Environment auth not set",{hasApiKey:!!e,hasProjectId:!!t})},rn=!1,nn=()=>{rn||(rn=!0,m.log.warn("Both environment variable auth and stored OAuth login were detected."),m.log.warn(`Honoring environment variables (${D.default.cyan("STABLY_API_KEY")} + ${D.default.cyan("STABLY_PROJECT_ID")}).`),m.log.warn("To use OAuth login instead, unset those environment variables."))},on=async()=>{Zr.debug("Checking for stored auth tokens");const e=await vr();if(!e)return void Zr.debug("No stored auth tokens found");const t=Cr(e);if(Zr.debug("Auth tokens status",{expired:t}),!t){const t=await Rr(),r=(e=>{try{const t=hr.parse(gr(e));if(t.org_id_to_org_member_info)return"full";if(t.org_member_info)return"org"}catch{return"unknown"}return"unknown"})(e.accessToken);if(Zr.debug("Token scope check",{scope:r,hasContext:!!t}),t&&"full"===r)try{Zr.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 Tr(n),Zr.debug("Token exchange successful"),n}catch(t){return Zr.debug("Token exchange failed, using existing token",{error:t instanceof Error?t.message:String(t)}),e}return e}try{Zr.debug("Attempting token refresh");const t=await Pr(e.refreshToken);Zr.debug("Token refresh successful");const r=await Rr();if(r)try{Zr.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 Tr(n),n}catch{return await Tr(t),t}return await Tr(t),t}catch(e){return void Zr.warn("Token refresh failed",{error:e instanceof Error?e.message:String(e)})}},sn=async(e={})=>{Zr.debug("Requiring authentication",{autoLogin:e.autoLogin});const t=tn();if(t){Zr.info("Using environment variable authentication");try{await vr()&&nn()}catch{}return{auth:t,type:"env"}}let r=await on(),n=r?await Rr():void 0;const o=process.stdin.isTTY&&process.stdout.isTTY;if(Zr.debug("OAuth auth check",{hasTokens:!!r,hasContext:!!n,canPrompt:o}),(!r||!n)&&e.autoLogin&&o){Zr.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(`${D.default.dim("Alternatively, set environment variables for an org API key:")}\n${D.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(D.default.dim("Press Enter to continue... "))}finally{e.close()}await Dr(),r=await on(),n=r?await Rr():void 0}return r||(Zr.warn("Authentication required but no tokens available"),m.outro(D.default.red("You are not logged in. Run `stably login` to authenticate.")),process.exit(1)),n||(Zr.warn("Authentication succeeded but no project context selected"),m.outro(D.default.red("You haven't selected an organization and project. Run `stably login` to complete setup.")),process.exit(1)),Zr.info("OAuth authentication successful",{orgId:n.orgId,projectId:n.projectId}),{auth:{accessToken:r.accessToken,context:n},type:"oauth"}},an=e=>e?{...process.env,...e}:process.env,cn=async()=>{const e=(()=>{if(!process.env.STABLY_WS_URL&&"https://api.stably.ai"!==ir)return`${ir.replace(/^https?:\/\//,"wss://").replace(/\/$/,"")}/reporter`})(),t=tn();if(t)return{STABLY_API_KEY:t.apiKey,STABLY_PROJECT_ID:t.projectId,...e&&{STABLY_WS_URL:e}};const r=await(async()=>{const e=tn();if(e){try{await vr()&&nn()}catch{}return{auth:e,type:"env"}}const t=await on(),r=t?await Rr():void 0;if(t&&r)return{auth:{accessToken:t.accessToken,context:r},type:"oauth"}})();if(!r||"env"===r.type)return;const n=process.env.STABLY_PROJECT_ID?.trim(),o=n||(e=>"env"===e.type?e.auth.projectId:e.auth.context.projectId)(r);if(!o)return;const s=await(async(e,t)=>{try{Zr.debug("Requesting JWT API key",{projectId:t,apiUrl:ir});const r=await(async({accessToken:e,projectId:t})=>{const r=await(n={auth:e,client:ur(),path:{projectId:t}},(n.client??or).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 Zr.debug("JWT API key obtained",{keyPrefix:r.apiKey.substring(0,10)}),r.apiKey}catch(e){return void Zr.warn("Failed to get JWT API key for test reporter",{error:e instanceof Error?e.message:String(e)})}})(r.auth.accessToken,o),i=s?{STABLY_API_KEY:s,STABLY_PROJECT_ID:o,...e&&{STABLY_WS_URL:e}}:void 0;return Zr.debug("Resolved Stably test env",{hasApiKey:!!i?.STABLY_API_KEY,projectId:i?.STABLY_PROJECT_ID,wsUrl:i?.STABLY_WS_URL??process.env.STABLY_WS_URL??"(default)"}),i},ln=e=>e?{[jt]:e}:void 0,dn=_.z.object({context:_.z.string().min(1),autohealReportUrl:_.z.string()}),un=v.z.object({bucket:v.z.string(),key:v.z.string()}),pn=v.z.object({diffBucketPath:un,expiresInSeconds:v.z.number(),key:v.z.string(),uploadUrl:v.z.string()}),fn=/\.(spec|test)\.(c|m)?[jt]sx?$/,hn=e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"text"===t.type&&"string"==typeof t.text},gn=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},yn=e=>{const t=mn(e);if(t)return t.filter(hn).map(e=>e.text).join("\n")||void 0},_n=/\u001b\[[0-9;]*m/g,bn=e=>e.replace(_n,""),En=/\$\{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 o=n.replace(En,(t,r)=>{const n=e[r];return null!=n?n:t});return o===n?{decision:"approve"}:{decision:"approve",hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",reason:"Evaluated environment variable placeholders in browser text input.",updatedInput:{...r,text:o}}}}}function In({onResult:e}){return async t=>{if(!gn(t))return{decision:"approve"};const r=yn(t);if(!r)return{decision:"approve"};const n=function(e){const t=bn(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"),o=parseInt(r.match(/(\d+)\s+failed/g)?.at(-1)?.match(/(\d+)/)?.[1]??"0");if(0===n&&0===o)return;const s=[n>0?`${n} test${1===n?"":"s"} passed ✓`:void 0,o>0?`${o} test${1===o?"":"s"} failed ✗`:void 0].filter(e=>void 0!==e).join(", ");if(0===o)return s;const i=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?s:`${s}\n${i.map(e=>` - ${e}`).join("\n")}`}(r);return n&&e(n),{decision:"approve"}}}function vn({onResult:e}){return async t=>{if(!gn(t))return{decision:"approve"};const r=yn(t);if(!r)return{decision:"approve"};const n=function(e){const t=bn(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 Tn=/\.(spec|test)\.(ts|tsx|js|jsx|mts|mjs)$/;function xn({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&&Tn.test(n)&&e(n),{decision:"approve"}}}d.promisify(o.exec);var Sn=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())}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()})}},Rn=[".ts",".js",".mts",".mjs",".cts",".cjs"],An=10240,Cn=async({defaultContent:e,fileName:t,filePath:r})=>{try{const e=(await g.stat(r)).size,n=await g.readFile(r,"utf-8"),o=Buffer.byteLength(n,"utf-8");if(o<=An)return n;const s=(e=>{const t=e.split("\n"),r=[];let n=!1,o=!1,s=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),o=!0,s=(a.match(/{/g)||[]).length-(a.match(/}/g)||[]).length,0===s&&(c.endsWith(";")||c.endsWith(","))&&(o=!1)):o?(s+=(a.match(/{/g)||[]).length,s-=(a.match(/}/g)||[]).length,0===s&&c.includes("}")?(r.push(a),o=!1):s>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(s,"utf-8");return i<=An?s:s.slice(0,An)+`\n\n... [TRUNCATED: File "${t}" at ${r} was ${e} bytes (${o} 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}},Pn=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}},Un=async({allowedEnvVars:e,mode:t,workspaceInfo:r,authHeader:n,customHeader:s,maxParallelWorkers:i})=>{const a=ur(),c=function(e){try{const t=o.execSync("git branch --show-current",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(!t)return;return{branch:t}}catch{return}}(r.absolutePath);Zr.debug("Requesting system prompt from API",{mode:t,hasGitContext:!!c,envVarCount:e.length});const l=await(d={client:a,auth:n,body:{mode:t,workspaceInfo:r,allowedEnvVars:e,gitContext:c,maxParallelWorkers:i}},(d.client??or).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/prompts/system",...d,headers:{"Content-Type":"application/json",...d.headers}}));var d;if(401===l.response.status)throw Zr.warn("System prompt fetch failed: unauthorized (401)"),await xr(),new Error("Your session has expired or been revoked. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(403===l.response.status)throw Zr.warn("System prompt fetch failed: forbidden (403)"),await xr(),new Error("You no longer have access to this organization. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(l.error)throw Zr.warn("System prompt fetch failed",{error:l.error}),new Error(`Failed to fetch system prompt: ${JSON.stringify(l.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:l.data.systemPrompt,customHeader:s});return Zr.debug("System prompt received",{size:u.length,appendedCustomHeader:!!s}),u},Ln=".stably-playwright-wrapper.config.*",On=[".ts",".js",".mts",".mjs",".cts",".cjs"];function Bn(e){const r=t.resolve(e);if(i.existsSync(r))for(const e of On){const n=t.join(r,`playwright.config${e}`);if(i.existsSync(n))return n}}var Dn=["tests","e2e","__tests__","test"];function Nn(e){try{return i.existsSync(e)&&i.statSync(e).isDirectory()}catch{return!1}}function kn(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(D.default.dim(`Using output directory: ${e} (from ${r})`))}var jn=["mcp__playwright-test__","mcp__auto-heal-report__","mcp__test-doc-sync__","mcp__stably-agent-control__"],$n=["planner_","generator_"],Mn={"mcp__stably-agent-control__restart_mcp_servers":"Restarting Browser Tools"},Hn=(e,t)=>{const r=t.find(t=>e.startsWith(t));return r?e.slice(r.length):e},Fn=e=>{const t=Mn[e];if(t)return t;const r=Hn(e,jn);return Hn(r,$n).split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")},Gn=(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},Yn=["test","bug","other"],zn={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."},Wn=e=>zn[e],{zSuiteAutoHealReport:Kn}=function(e){const t=e.enum(Yn),r=["Classification of the root cause:","",`- test: ${Wn("test")}`,`- bug: ${Wn("bug")}`,`- other: ${Wn("other")}`].join("\n"),n=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).")}),o=e.discriminatedUnion("result",[n.extend({fixApplied:e.string().describe("What fix was applied (brief, specific)."),result:e.literal("fixed")}),n.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:o,zIssueCategory:t,zSuiteAutoHealReport:e.object({issues:e.array(o).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.")})}}(v.z),qn=({authHeader:e,diffTracker:t,orgId:r,runId:n})=>u.createSdkMcpServer({name:"auto-heal-report",tools:[u.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:Kn},async({report:o})=>{const s=await t.computeDiff(),i=Kn.parse(o);try{await(async({authHeader:e,orgId:t,report:r,runId:n})=>{const o=await(s={auth:e,body:{report:JSON.stringify(r)},client:ur(),headers:ln(t),path:{runId:n}},(s.client??or).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-report",...s,headers:{"Content-Type":"application/json",...s.headers}}));var s;if(o.error)throw new Error(`Failed to upload auto-heal report (${o.response.status})`)})({authHeader:e,orgId:r,report:i,runId:n});const{uploadUrl:t}=await(async({authHeader:e,contentType:t="text/plain",orgId:r,runId:n})=>{const o=await(s={auth:e,body:{contentType:t},client:ur(),headers:ln(r),path:{runId:n}},(s.client??or).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-diff/upload-url",...s,headers:{"Content-Type":"application/json",...s.headers}}));var s;if(o.error)throw new Error(`Failed to presign diff upload (${o.response.status})`);const i=pn.parse(o.data);return{diffBucketPath:i.diffBucketPath,expiresInSeconds:i.expiresInSeconds,key:i.key,uploadUrl:i.uploadUrl}})({authHeader:e,contentType:"text/plain",orgId:r,runId:n});await(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})`)})({contentType:"text/plain",diff:s,uploadUrl:t})}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. 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"}),Vn=({onComplete:e})=>u.createSdkMcpServer({name:"session-control",tools:[u.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:v.z.string().describe("A brief summary of what was accomplished")},async({summary:t})=>{const r=t;return e(),`Session complete: ${r}`})]}),Jn=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]"),Xn=(e,t)=>({message:Jn(e),status:t?.status,statusText:t?.statusText}),Qn=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"]),Zn=async({authHeader:e,mode:t,maxTurnsOverride:r})=>{const n=ur();Zr.debug("Requesting subagent definitions from API",{mode:t,maxTurnsOverride:r});const o=await(s={client:n,auth:e,body:{mode:t,maxTurnsOverride:r}},(s.client??or).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/prompts/subagents",...s,headers:{"Content-Type":"application/json",...s.headers}}));var s;if(401===o.response.status)throw Zr.warn("Subagent definitions fetch failed: unauthorized (401)"),await xr(),new Error("Your session has expired or been revoked. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(403===o.response.status)throw Zr.warn("Subagent definitions fetch failed: forbidden (403)"),await xr(),new Error("You no longer have access to this organization. Credentials have been cleared. Please run `stably login` to re-authenticate.");if(o.error)throw Zr.warn("Subagent definitions fetch failed",{error:o.error}),new Error(`Failed to fetch subagent definitions: ${JSON.stringify(o.error)}`);const{subagents:i}=o.data;return Zr.debug("Subagent definitions received",{count:Object.keys(i).length}),i},{zStablyYaml:eo}=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}}(_.z),to=["Bash","Read","Write","Edit","Glob","Grep","Task"],ro=["Task","mcp__playwright-test"],no=["Bash","Read","Write","Edit","Glob","Grep","mcp__session-control"],oo=e=>{if("EPIPE"!==e.code)throw e},so=async r=>{if("single"===r.mode||"build"===r.mode){const e=Array.isArray(r.prompt)?r.prompt.join(" "):r.prompt;Zr.initSession(e||"create-from-diff")}else"fix"===r.mode&&Zr.initSession(`fix-${r.runId}`);Zr.info("Agent session starting",{mode:r.mode}),process.stdout.on("error",oo),process.stderr.on("error",oo);const n=e=>{if("EPIPE"!==e.code)throw e};process.on("uncaughtException",n),Zr.debug("Checking authentication");const o=await sn({autoLogin:"chat"===r.mode||"init"===r.mode}),s=(e=>"env"===e.type?e.auth.apiKey:e.auth.accessToken)(o);Zr.debug("Authentication resolved",{authType:o.type});const a="oauth"===o.type?o.auth.context.orgId:void 0,c=C.default.resolve(process.cwd()),l=C.default.join(c,".env"),d=L.default.existsSync(l)&&L.default.statSync(l).isFile(),p=d?e.parse(L.default.readFileSync(l,"utf8")):{};Zr.debug("Environment file",{path:l,exists:d,variableCount:Object.keys(p).length});const f="chat"!==r.mode&&"init"!==r.mode,h="chat"===r.mode||"init"===r.mode?new Sn:void 0,m="chat"===r.mode?r.getHelpText:void 0,y={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 _,b=f,E=!1;const w=new Map;let I=null,v=!1,R=!1;const A=async e=>{if("fix"===r.mode){if("STARTED"===e){if(v)return;v=!0}else{if(R)return;R=!0}try{await(async({authHeader:e,orgId:t,runId:r,status:n})=>{const o=await(s={auth:e,body:{status:n},client:ur(),headers:ln(t),path:{runId:r}},(s.client??or).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-status",...s,headers:{"Content-Type":"application/json",...s.headers}}));var s;if(o.error)throw new Error(`Failed to update autoheal status (${o.response.status})`)})({authHeader:s,orgId:a,runId:r.runId,status:e})}catch{}}},P={current:e=>{}},U={current:async()=>{}},{addSubagentActivity:O,addSubagentStart:B,addTool:N,addToolResult:k,appendText:j,appendUserMessage:$,cleanup:M,setExiting:H,setStatus:F,setSubagentStatus:G,updateFixProgress:Y}=await(async(e,t)=>{const{Box:r,Static:n,Text:o,render:s,useInput:i}=await import("ink"),a=!!process.stdin.isTTY,c=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],l=()=>x.jsx(o,{inverse:!0,children:" "}),d=(({Box:e,Text:t,useInput:r},n,o)=>function({onChoice:s,prompt:i}){const[a,c]=T.useState(0),[l,d]=T.useState(!1),[u,p]=T.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 s("deny_with_message",u||"User denied this action"):t.escape?(d(!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 d(!0):void s(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 d(!0);s(e.value)}},{isActive:o});const h=Fn(i.toolName),g=Gn(i.toolName,i.input);return x.jsxs(e,{borderColor:"yellow",borderStyle:"round",flexDirection:"column",marginTop:1,paddingX:1,paddingY:0,children:[x.jsx(t,{bold:!0,color:"yellow",children:"Permission Required"}),x.jsxs(e,{flexDirection:"column",marginTop:1,children:[x.jsx(t,{color:"magenta",children:h}),null!=g&&x.jsxs(t,{color:"gray",children:[" ",g]})]}),null!=i.decisionReason&&x.jsx(e,{marginTop:1,children:x.jsxs(t,{color:"gray",children:["Reason: ",i.decisionReason]})}),l?x.jsxs(e,{flexDirection:"column",marginTop:1,children:[x.jsx(t,{color:"gray",children:"Enter message for AI (press Enter to submit, Esc to cancel):"}),x.jsxs(t,{children:[x.jsx(t,{color:"yellow",children:">"})," ",u,x.jsx(n,{})]})]}):x.jsxs(e,{flexDirection:"column",marginTop:1,children:[x.jsx(t,{color:"gray",children:"Use ↑↓ arrows or number keys to select:"}),f.map((e,r)=>x.jsx(t,{children:x.jsxs(t,{color:r===a?"cyan":void 0,children:[r===a?"❯":" "," ",r+1,". ",e.label]})},e.value))]})]})})({Box:r,Text:o,useInput:i},l,a),u=(({Cursor:e,inkComponents:{Box:t,Static:r,Text:n,useInput:o},isRawModeSupported:s,PermissionPrompt:i,Spinner:a})=>{const c=({progress:e})=>{const[r,o]=T.useState(Date.now());T.useEffect(()=>{const e=setInterval(()=>o(Date.now()),1e3);return()=>clearInterval(e)},[]);const s=r-e.startedAt,i=Math.floor(s/1e3),a=Math.floor(i/60),c=i%60,l=a>0?`${a}m ${c.toString().padStart(2,"0")}s`:`${c}s`,{label:d,color:u}={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 x.jsx(t,{flexDirection:"column",children:x.jsxs(n,{children:[x.jsx(n,{color:u,bold:!0,children:d}),x.jsx(n,{color:"gray",children:f}),x.jsxs(n,{color:"gray",children:[" [",l,"]"]})]})})},l=({progress:e})=>{const r=e.endedAt??Date.now(),o=Math.floor((r-e.startedAt)/1e3),s=Math.floor(o/60),i=o%60,a=s>0?`${s}m ${i.toString().padStart(2,"0")}s`:`${i}s`,c=e.isError?"yellow":"green",l=e.isError?"Fix stopped":"Fix complete";return x.jsxs(t,{flexDirection:"column",children:[x.jsxs(n,{color:c,bold:!0,children:[l," in ",a]}),null!==e.totalTests&&x.jsxs(n,{color:"gray",children:[e.fixedTests,"/",e.totalTests," tests fixed",e.failedTests>0?`, ${e.failedTests} failed`:""]})]})},d=e=>{if("subagent"===e.kind&&e.subagent){const{subagent:r}=e,o="complete"===r.status?"green":"error"===r.status?"red":"yellow";return x.jsxs(t,{flexDirection:"column",marginTop:1,children:[x.jsxs(n,{children:[x.jsx(n,{color:o,bold:!0,children:"Agent"}),r.description?x.jsxs(n,{color:"gray",children:[" (",r.description,")"]}):null]}),r.activities.length>0&&x.jsx(t,{flexDirection:"column",marginLeft:2,children:r.activities.map(e=>(e=>"tool"===e.kind?x.jsxs(n,{color:"magenta",children:["• ",e.content]},e.id):"tool_result"===e.kind?x.jsx(n,{color:"gray",children:e.content},e.id):null)(e))})]},e.id)}return"tool"===e.kind?x.jsxs(n,{color:"magenta",children:["• ",e.content]},e.id):"tool_result"===e.kind?x.jsx(n,{color:"gray",children:e.content},e.id):"user"===e.kind?x.jsxs(n,{color:"cyan",children:["You: ",e.content]},e.id):x.jsx(n,{children:e.content},e.id)},u="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:_,showSpinnerImmediately:b,state:E}){const[w,I]=T.useState({value:"",cursor:0}),v=w.value,S=w.cursor,R=T.useRef(!1),A=T.useRef(void 0),[C,P]=T.useState(!1),U=T.useRef(0),L=E.log.at(-1),O="text"===L?.kind&&"running"===E.status,B=E.log.findIndex(e=>"subagent"===e.kind&&"running"===e.subagent?.status),D=u?0:-1!==B?B:O?E.log.length-1:E.log.length;T.useEffect(()=>{E.log.length<U.current&&(U.current=0),D>U.current&&(U.current=D)},[E.log.length,D]);const N=E.log.slice(0,U.current),k=E.log.slice(U.current),j=!!E.permissionPrompt,$=T.useCallback(async()=>{R.current?(A.current&&clearTimeout(A.current),await(m?.()),process.exit(0)):(R.current=!0,P(!0),A.current=setTimeout(()=>{R.current=!1,P(!1)},2e3))},[m]);o((e,t)=>{t.ctrl&&"c"===e&&$().catch(()=>process.exit(1))},{isActive:s}),T.useEffect(()=>{if(j||!_)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||I(e=>({...e,cursor:g(e.value,e.cursor)})):I(e=>({...e,cursor:h(e.value,e.cursor)})):I(e=>({...e,cursor:e.value.length})):I(e=>({...e,cursor:0}))};return process.stdin.on("data",e),()=>{process.stdin.off("data",e)}},[j,_,v]),o((e,t)=>{if(!t.ctrl||"c"!==e){if(t.return){const e=v.trim();return e&&_?.(e),void I({value:"",cursor:0})}t.ctrl&&"w"===e||t.ctrl&&t.backspace?I(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?I(e=>({...e,cursor:p(e.value,e.cursor)})):t.ctrl&&t.rightArrow||t.meta&&"f"===e?I(e=>({...e,cursor:f(e.value,e.cursor)})):t.leftArrow?I(e=>({...e,cursor:Math.max(0,e.cursor-1)})):t.rightArrow?I(e=>({...e,cursor:Math.min(e.value.length,e.cursor+1)})):t.ctrl&&"a"===e?I(e=>({...e,cursor:0})):t.ctrl&&"e"===e?I(e=>({...e,cursor:e.value.length})):!e||t.ctrl||t.meta||t.escape||e.includes("")||/^\[./.test(e)||/^O[A-D]$/.test(e)||I(t=>({value:t.value.slice(0,t.cursor)+e+t.value.slice(t.cursor),cursor:t.cursor+e.length})):I(e=>e.cursor>0?{value:e.value.slice(0,e.cursor-1)+e.value.slice(e.cursor),cursor:e.cursor-1}:e)}},{isActive:s&&!!_&&!j});const M=T.useMemo(()=>"running"===E.status?x.jsx(a,{label:"Working"}):"success"!==E.status?x.jsx(n,{color:"red",children:"✖ Failed"}):void 0,[E.status]),H=!(b||!_||"running"!==E.status||0!==E.log.length||E.resultText||E.errorText),F="running"===E.status&&!H||E.log.length>0||E.resultText||E.errorText||"running"!==E.status;return x.jsxs(t,{flexDirection:"column",children:[x.jsx(r,{items:["header"],children:()=>x.jsxs(t,{flexDirection:"column",flexShrink:0,children:[x.jsx(n,{color:"cyan",bold:!0,children:"Stably Agent"}),x.jsx(t,{flexDirection:"column",marginTop:1,children:x.jsx(n,{color:"gray",children:E.promptDisplay})})]},"header")}),N.length>0&&x.jsx(r,{items:N,children:e=>d(e)}),k.length>0&&x.jsx(t,{flexDirection:"column",children:k.map(e=>d(e))}),"error"===E.status&&E.errorText&&x.jsx(t,{marginTop:1,children:x.jsx(n,{color:"red",children:E.errorText})}),"success"===E.status&&E.resultText&&x.jsx(t,{marginTop:1,children:x.jsx(n,{children:E.resultText})}),F&&x.jsx(t,{flexDirection:"column",flexShrink:0,marginTop:1,children:"running"===E.status&&E.fixProgress?x.jsxs(t,{flexDirection:"column",children:[x.jsxs(t,{children:[x.jsx(a,{}),x.jsx(n,{children:" "}),x.jsx(c,{progress:E.fixProgress})]}),"fixing"===E.fixProgress.phase&&E.log.flatMap(e=>{const{subagent:r}=e;if("subagent"!==e.kind||"fix-worker"!==r?.subagentType||"running"!==r.status)return[];const{activities:o}=r,s=o.filter(e=>"tool"===e.kind).length,i=o.at(-1),c=o.filter(e=>"tool"===e.kind).at(-1),l=(()=>{if(!i)return null;if("tool"===i.kind)return null;if("text"===i.kind){const e=i.content.trim().split("\n").at(-1)?.trim();return e?e.length>80?`${e.slice(0,80)}…`:e:null}if("tool_result"===i.kind){const e=i.content.trim().split("\n")[0]?.trim();return e?e.length>80?`${e.slice(0,80)}…`:e:null}return null})();return x.jsxs(t,{flexDirection:"column",children:[x.jsxs(n,{children:[" ",x.jsx(a,{}),x.jsxs(n,{color:"gray",children:[r.description||"fix-worker",s>0?` (${s} ${1===s?"cycle":"cycles"})`:""]})]}),c&&x.jsxs(n,{color:"gray",dimColor:!0,children:[" • ",c.content]}),l&&x.jsxs(n,{color:"gray",dimColor:!0,children:[" ",l]})]},e.id)})]}):"success"!==E.status&&"error"!==E.status||!E.fixProgress?M:x.jsx(l,{progress:E.fixProgress})}),null!=E.permissionPrompt&&null!=y&&x.jsx(i,{onChoice:y,prompt:E.permissionPrompt}),null!=_&&null==E.permissionPrompt&&!E.isExiting&&x.jsxs(t,{borderColor:"gray",borderStyle:"round",flexDirection:"column",flexShrink:0,marginTop:1,paddingX:1,paddingY:0,children:[x.jsx(n,{color:"gray",children:"Type a message and press Enter. Press Ctrl+C to exit."}),x.jsxs(n,{children:[x.jsx(n,{color:"yellow",children:">"})," ",v.slice(0,S),x.jsx(e,{}),v.slice(S)]})]}),C&&x.jsxs(t,{marginTop:1,flexDirection:"column",children:[x.jsx(n,{color:"yellow",children:"Press Ctrl+C again to exit"}),Hr&&x.jsxs(n,{color:"gray",children:["Debug log: ",zr]})]})]})}})({Cursor:l,inkComponents:{Box:r,Static:n,Text:o,useInput:i},isRawModeSupported:a,PermissionPrompt:d,Spinner:({label:e})=>{const[t,r]=T.useState(0);return T.useEffect(()=>{const e=setInterval(()=>r(e=>(e+1)%c.length),80);return()=>clearInterval(e)},[]),x.jsxs(o,{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=s(x.jsx(u,{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(x.jsx(u,{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 o=p.log[n];if(o&&"subagent"===o.kind&&o.subagent){if("text"===t){const e=o.subagent.activities.at(-1);e&&"text"===e.kind?e.content+=r:o.subagent.activities.push({id:o.subagent.activities.length,kind:"text",content:r.replace(/^\s*\n+/,"")})}else o.subagent.activities.push({id:o.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:o?.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=Fn(e),n=Gn(e,t),o=n?`${r} (${n})`:r;p.log=[...p.log,{content:o,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()},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}})(y,"chat"===r.mode||"init"===r.mode?{onExit:()=>U.current(),onSend:e=>P.current(e),showSpinnerImmediately:"init"===r.mode}:"fix"===r.mode?{onExit:()=>U.current(),isFixMode:!0}:void 0);let z=y.status;const W=({error:e,result:t,status:r})=>{z=r,F({error:e,result:t,status:r})};let K;P.current=e=>{const t=e.trim();if("chat"!==r.mode||Zr.getLogFilePath()||Zr.initSession(t||"chat"),Zr.debug("User message",{text:t}),"/help"===t){b&&h&&(E=!0,_?.interrupt?.(),h.allowNextTurn(),b=!1),"running"===z&&W({status:"success"}),$({text:e});const t=m?.();return void j({text:t??"Help is not available in this session."})}h&&(b&&(E=!0,_?.interrupt?.(),h.allowNextTurn(),b=!1),W({status:"running"}),$({text:e}),h.pushText(e),b=!0)};const q=[];let V;const J=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 kn(e,"output-flag"),{path:e,source:"output-flag"}}const o=Bn(n);if(o){const e=await async function(e){try{const t=(await g.readFile(e,"utf-8")).match(/testDir:\s*['"]([^'"]+)['"]/);return t?.[1]}catch{return}}(o);if(e){const r=t.resolve(t.dirname(o),e);if(Nn(r))return kn(r,"playwright.config.ts"),{path:r,source:"playwright.config.ts"}}}for(const e of Dn){const r=t.join(n,e);if(Nn(r))return kn(r,"auto-detected"),{path:r,source:"auto-detected"}}return kn(n,"cwd-fallback"),{path:n,source:"cwd-fallback"}}(c,r.outputDir);return V=n.path,e=r.prompt,`${(Array.isArray(e)?e.join(" "):e).trim()||"Create tests based on the changes in the current PR or 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 playwright test` or the repo's Playwright test command) and iterate until the new tests pass."}\n\n[Output directory: ${V}]`}var e;if("fix"===r.mode)try{const{context:e,autohealReportUrl:t}=await(async({authHeader:e,orgId:t,runId:r})=>{Zr.debug("Fetching autoheal context",{runId:r});const n=await(o={auth:e,client:ur(),headers:ln(t),path:{runId:r}},(o.client??or).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-context",...o}));var o;if(404===n.response.status)throw Zr.warn("Autoheal context not found",{runId:r,status:404}),new Error(`Run ID "${r}" was not found.`);if(401===n.response.status)throw Zr.warn("Autoheal context fetch unauthorized",{runId:r,status:401}),new Error("Unauthorized: failed to fetch autoheal context (401).");if(422===n.response.status)throw Zr.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=dn.safeParse(n.data);if(e.success)return Zr.debug("Autoheal context fetched successfully",{runId:r,contextSize:e.data.context.length}),{context:e.data.context,autohealReportUrl:e.data.autohealReportUrl};throw Zr.warn("Autoheal context response invalid",{runId:r}),new Error("Autoheal context response missing or invalid context.")}throw Zr.warn("Autoheal context fetch failed",{runId:r,error:n.error}),new Error("Failed to fetch autoheal context")})({authHeader:s,orgId:a,runId:r.runId});return K=t,A("STARTED"),e}catch(e){const t=e instanceof Error?e.message:"Failed to fetch autoheal context.";W({error:t,status:"error"}),await M(),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.":""})(),X=await async function(e){const t=C.default.resolve(e),r=C.default.join(t,"tests"),n=C.default.join(r,"helpers"),o=C.default.join(r,"assets"),s=function(e){const t=C.default.resolve(e);if(i.existsSync(t))for(const e of Rn){const r=C.default.join(t,`playwright.config${e}`);if(i.existsSync(r))return r}}(t)??C.default.join(t,"playwright.config.ts"),a=C.default.basename(s),c=C.default.join(r,"seed.spec.ts"),[l,d,u,p,f,h]=await Promise.all([Pn({defaultContent:"Unable to read directory",dirName:"working directory",dirPath:t}),Pn({defaultContent:"Unable to read directory",dirName:"tests directory",dirPath:r}),Pn({defaultContent:"Directory does not exist yet",dirName:"helpers directory",dirPath:n}),Pn({defaultContent:"Directory does not exist yet",dirName:"assets directory",dirPath:o}),Cn({defaultContent:"File does not exist or could not be read",fileName:a,filePath:s}),Cn({defaultContent:"File does not exist or could not be read",fileName:"seed.spec.ts",filePath:c})]);return{absolutePath:t,directories:{assets:p,helpers:u,root:l,tests:d},files:{playwrightConfig:f,playwrightConfigFilename:a,seedSpec:h}}}(c),Q=await(async e=>{try{const t=await(async e=>{let t=e;const{root:r}=C.default.parse(t);for(;t!==r;){const e=C.default.join(t,"stably.yaml");try{return await g.readFile(e),e}catch{t=C.default.dirname(t)}}})(e);if(!t)return void Zr.debug("No stably.yaml found");const r=await g.readFile(t,"utf-8");if(!r.trim())return;const n=S.parseDocument(r),o=eo.parse(n.toJS()),s=o.agent?.fix?.maxTurnsPerIssue,i=o.agent?.fix?.maxParallelWorkers,a=!!o.agent?.fix?.rules;return Zr.debug(`Loaded stably.yaml: maxTurnsPerIssue=${s??"default"}, maxParallelWorkers=${i??"default"}, hasRules=${a}`,{path:t,config:o.agent}),o}catch(e){return void Zr.warn("Failed to parse stably.yaml",{error:e})}})(c),Z=Q?.agent?.fix?.maxTurnsPerIssue,ee=Q?.agent?.fix?.maxParallelWorkers,te=Q?.agent?.fix?.rules;Zr.debug("Fetching system prompt and subagents",{mode:r.mode,maxTurnsOverride:Z,hasCustomRules:!!te});const[re,ne]=await Promise.all([Un({allowedEnvVars:Object.keys(p),mode:r.mode,workspaceInfo:X,authHeader:s,customHeader:"single"===r.mode||"build"===r.mode?r.customHeader:void 0,maxParallelWorkers:"fix"===r.mode?ee:void 0}),"fix"===r.mode?Zn({authHeader:s,mode:r.mode,maxTurnsOverride:Z}):Promise.resolve({})]);Zr.debug("System prompt and subagents fetched",{systemPromptSize:re.length,subagentCount:Object.keys(ne).length,maxTurnsOverride:Z??"default"});const oe={...p,...process.env},se={};for(const[e,t]of Object.entries(oe))Qn.has(e)||void 0===t||(se[e]=t);Zr.debug("AI proxy configuration",{useStablyAiProxy:!0,wantsBypassProxy:!1,wantsUseOllama:!1});const ie=await async function({auth:e,client:t,source:r,metadata:n,duration:o}){try{const i=await(s={auth:e,client:t,body:{source:r,metadata:n??{},duration:o}},(s.client??or).post({security:[{scheme:"bearer",type:"http"}],url:"/v1/proxy/api-key",...s,headers:{"Content-Type":"application/json",...s.headers}})),a=i.response;if(i.error){const e="object"==typeof i.error&&"error"in i.error?i.error.error:"Unknown error";return{error:Xn(e,a)}}return i.data?{key:i.data.key}:{error:Xn("No data in response",a)}}catch(e){const t=e instanceof Error?e.message:"Unknown error";return{error:Xn(t)}}var s}({auth:s,client:ur(),source:"cli"}),ae=ie?.key;if(!ae){const e=ie?.error?.message?`Unable to make AI calls: ${ie.error.message}`:"Unable to make AI calls. Check if you are authenticated.";Zr.warn("Failed to get proxy API key",{error:ie?.error?.message}),W({error:e,status:"error"}),await M(),Zr.flush(),Zr.printLogFileInfo(),process.exit(1)}Zr.debug("Proxy API key acquired",{success:!!ae});const ce=await cn(),le=ce?Object.fromEntries(Object.entries(an(ce)).filter(e=>null!=e[1])):void 0,de="init"===r.mode,ue="fix"===r.mode,pe=ue?Nt.createLocal({workingDir:c}):void 0;pe&&await pe.captureSnapshot();const fe=de?no:[...to,...ue?["mcp__auto-heal-report"]:[]],he=de?no:ro,ge=de?{"session-control":Vn({onComplete:()=>{W({status:"success"}),H(),h?.finish(),process.exit(0)}})}:ue&&pe?{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:le},"auto-heal-report":qn({authHeader:s,diffTracker:pe,orgId:a,runId:r.runId})}:{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:le}},me="single"===r.mode||"build"===r.mode,ye=de?[]:[{hooks:[async e=>{const t=mn(e);if(!t)return{decision:"approve"};let r=!1;const n=t.map(e=>hn(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:[In({onResult:e=>k({message:e})})]},{matcher:"mcp__playwright-test__test_debug",hooks:[vn({onResult:e=>k({message:e})})]},...me?[{matcher:"Write",hooks:[xn({onFileCreated:e=>q.push(e)})]}]:[]],_e=de?[]:[{matcher:"mcp__playwright-test__browser_type",hooks:[wn({envVars:p})]}],be=Object.keys(ne).length>0?ne:void 0,Ee={...se};Ee.MCP_TOOL_TIMEOUT=String(6e5),ae&&(Ee.ANTHROPIC_API_KEY=ae,Ee.ANTHROPIC_BASE_URL=lr,Ee.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS="1");const we=process.env.STABLY_AGENT_MODEL??"claude-opus-4-5-20251101",Ie=te?`${re}\n\n## Custom Rules\n${te}`:re;Zr.info("Starting agent query",{model:we,tools:fe,mcpServers:Object.keys(ge),subagentsEnabled:!!be,subagentCount:Object.keys(ne).length}),_=u.query({options:{tools:fe,allowedTools:he,betas:[],canUseTool:(e,t)=>Promise.resolve({behavior:"allow",updatedInput:t}),cwd:c,env:Ee,hooks:{PostToolUse:ye,PreToolUse:_e},includePartialMessages:!0,agents:be,mcpServers:ge,model:we,permissionMode:"default",systemPrompt:Ie},prompt:h??J}),"init"===r.mode&&h&&h.pushText(J),U.current=async()=>{I="CANCELED",await A("CANCELED"),Zr.flush(),H();try{await(_?.interrupt?.())}catch{}h?.finish(),M()};try{for await(const e of _){if("stream_event"===e.type){const{event:t}=e,r=t&&"object"==typeof t&&"parent_tool_use_id"in t&&"string"==typeof t.parent_tool_use_id?t.parent_tool_use_id:void 0;if("content_block_delta"===t?.type){const{delta:e}=t;"text_delta"===e?.type&&e.text&&(r&&w.has(r)?O({toolUseId:r,kind:"text",content:e.text}):j({text:e.text}))}"message_stop"===t?.type&&h&&h.allowNextTurn();continue}if("assistant"===e.type){const t="parent_tool_use_id"in e&&"string"==typeof e.parent_tool_use_id?e.parent_tool_use_id:void 0,{content:r}=e.message??{};if(Array.isArray(r)&&!t){const e=r.filter(e=>e&&"object"==typeof e&&"type"in e&&"text"===e.type).map(e=>e&&"object"==typeof e&&"text"in e&&"string"==typeof e.text?e.text:void 0).filter(Boolean).join("");e&&Zr.debug("Assistant message",{text:e})}if(w.size>0){const n=Array.isArray(r)?r.filter(e=>e&&"object"==typeof e&&"type"in e&&"tool_use"===e.type).map(e=>e&&"object"==typeof e&&"name"in e&&"string"==typeof e.name?e.name:void 0):[];Zr.debug("Assistant message with active subagents",{hasParentToolUseId:!!t,parentToolUseId:t,activeSubagentIds:Array.from(w.keys()),toolNames:n,fullMessageKeys:Object.keys(e),rawMessage:JSON.stringify(e).slice(0,500)})}if(Array.isArray(r))for(const e of r){if("tool_use"===e?.type){if(e.name.startsWith("mcp__session-control__"))continue;if(w.size>0&&Zr.debug("Tool use detected with active subagents",{toolName:e.name,hasParentToolUseId:!!t,parentToolUseId:t,wouldRouteToSubagent:!!t&&w.has(t),activeSubagentIds:Array.from(w.keys())}),"Task"===e.name){const t=e.input,r=t&&"object"==typeof t?t:void 0,n=r&&"subagent_type"in r&&"string"==typeof r.subagent_type?r.subagent_type:"subagent",o=r&&"description"in r&&"string"==typeof r.description?r.description.trim():"";Zr.debug("Subagent started",{subagentType:n,description:o,toolUseId:e.id}),w.set(e.id,{subagentType:n,description:o}),B({toolUseId:e.id,subagentType:n,description:o});continue}if(t&&w.has(t)){const r=Fn(e.name),n=Gn(e.name,e.input),o=n?`${r} (${n})`:r;Zr.debug("Subagent tool called",{tool:e.name,parentToolUseId:t}),O({toolUseId:t,kind:"tool",content:o});continue}t&&Zr.debug("Tool with parent_tool_use_id but no matching subagent",{tool:e.name,parentToolUseId:t,activeSubagentIds:Array.from(w.keys())}),Zr.debug("Tool called",{tool:e.name,input:e.input}),N({rawName:e.name,toolInput:e.input})}if("text"===e?.type&&t&&w.has(t)){const r="string"==typeof e.text?e.text:"";r&&O({toolUseId:t,kind:"text",content:r})}}continue}if("user"===e.type){const t="message"in e&&e.message&&"object"==typeof e.message&&"content"in e.message?e.message.content:void 0;if(Array.isArray(t))for(const e of t)if(e&&"object"==typeof e&&"type"in e&&"tool_result"===e.type&&"tool_use_id"in e){const t="string"==typeof e.tool_use_id?e.tool_use_id:void 0,r="is_error"in e&&!0===e.is_error,n="content"in e&&"string"==typeof e.content?e.content:void 0;Zr.debug("Tool result",{toolUseId:t,isError:r,output:n?.slice(0,500)}),t&&w.has(t)&&(Zr.debug("Subagent completed",{toolUseId:t,isError:r}),G({toolUseId:t,status:r?"error":"complete"}),w.delete(t))}continue}if("result"!==e.type);else{if(Zr.debug("Agent result",{subtype:e.subtype}),f){if("success"===e.subtype){if(Y?.({phase:"complete",currentTestDescription:null,endedAt:Date.now()}),me&&q.length>0){D.default.green("Created files:");for(const e of q)D.default.green(`- ${e}`)}const e=K?D.default.cyan(`📊 View Autoheal Report:\n ${D.default.cyan(D.default.bold(D.default.underline(K)))}`):void 0;W({status:"success",result:e}),I="COMPLETED"}else E?I="CANCELED":(Y?.({endedAt:Date.now(),isError:!0}),W({error:"Run failed.",status:"error"}),process.exitCode=1,I="FAILED");E=!1;break}"success"!==e.subtype?E||(W({error:"Run failed.",status:"error"}),process.exitCode=1):W({status:"success"}),b=!1,E=!1,h?.allowNextTurn()}}}catch(e){E?I="CANCELED":(Zr.error("Agent encountered an error",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),W({error:`Agent encountered an error: ${e}`,status:"error"}),process.exitCode=1,I="FAILED",Zr.flush(),Zr.printLogFileInfo())}finally{Zr.info("Agent session ending"),b=!1,E=!1,process.off("uncaughtException",n),h?.finish(),I&&await A(I),await(pe?.cleanup()),await M()}},io=j.default.object({runId:j.default.string(),timestamp:j.default.number()}),ao="sha256",co=/^\/\*\*\r?\n \* @generated by stably build[\s\S]*?\*\/(?:\r?\n)*/;function lo(e){return!!e&&"object"==typeof e&&"code"in e}async function uo({errorMessage:e,filePath:t}){try{return await k.default.readFile(t,"utf8")}catch(t){if(lo(t)&&"ENOENT"===t.code)throw new Error(e);throw t}}function po(e){return e.split(C.default.sep).join("/")}async function fo(e){try{return(await k.default.readdir(e)).filter(e=>fn.test(e)).map(t=>C.default.join(e,t))}catch(e){if(lo(e)&&"ENOENT"===e.code)return[];throw e}}function ho(e=process.cwd()){let r=t.resolve(e);for(;;){const e=go(r);if(e){const n={...e.dependencies,...e.devDependencies},o="@playwright/test"in n?"@playwright/test":"playwright"in n?"playwright":void 0;if(o){const e=mo(r);let n=!1,s=r;for(;;){const e=t.join(s,"node_modules"),r=t.join(e,o);if(i.existsSync(r)){n=!0;break}const a=t.dirname(s);if(a===s)break;s=a}return{inNodeModules:n,installed:!0,packageManager:e,packageName:o}}}const n=t.dirname(r);if(n===r)return{inNodeModules:!1,installed:!1,packageManager:void 0};r=n}}function go(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 mo(e){const r=[["npm","package-lock.json"],["pnpm","pnpm-lock.yaml"],["yarn","yarn.lock"]];let n=e;for(;;){for(const[e,o]of r)if(i.existsSync(t.join(n,o)))return e;const e=t.dirname(n);if(e===n)return;n=e}}function yo(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 _o=[{args:["--trace=on"],description:"Run Playwright tests",name:"test"},{args:[],description:"Install browser dependencies",name:"install"}];function bo(e){const[t,...r]=yo(e),n=[t,...r.slice(0,-1)].join(" ");return(t,r)=>{let o=t.toString();for(const e of _o)o=o.replaceAll(`${n} playwright ${e.name}`,`${n} stably ${e.name}`).replaceAll(`npx playwright ${e.name}`,`npx stably ${e.name}`);if("yarn"===e){const e=o.split("\n");return e.length>0&&e[0].includes("/.bin/playwright")&&e.shift(),void r.write(e.join("\n"))}r.write(o)}}function Eo(e=""){process.stdout.write(`${e}\n`)}function wo(...e){process.stderr.write(`${e.join(" ")}\n`)}var Io="stably",vo=`https://registry.npmjs.org/${Io}/latest`,To=_.z.object({version:_.z.string()});function xo(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 So(e,t){const r=xo(e),n=xo(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 Ro=C.default.join(O.default.homedir(),".stably"),Ao=C.default.join(Ro,"update-check.json"),Co=`https://registry.npmjs.org/${Io}/latest`,Po=_.z.object({lastCheck:_.z.number(),latestVersion:_.z.string()}),Uo=!1,Lo=!1,Oo=async()=>{if(Lo)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=L.default.readFileSync(Ao,"utf-8");return Po.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 = '${Co}';\n const cacheFile = ${JSON.stringify(Ao)};\n const cacheDir = ${JSON.stringify(Ro)};\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{o.spawn(process.execPath,["-e",e],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()}catch{}}(),null!=e&&So(sr,e.latestVersion)){if(Uo)return;Uo=!0;let t=!1;const r=()=>{if(t)return;t=!0;const r=`${D.default.yellow(`update available (${sr} → ${e.latestVersion})`)} - run \`${Io} upgrade\` to get the latest version\n`;try{L.default.writeSync(2,r)}catch{}};process.once("beforeExit",r),process.once("exit",r)}}(),G.cwdChanged&&Zr.debug("Changed working directory",{cwd:G.newCwd});for(const e of G.envFilesLoaded)Zr.debug("Loaded env file",{path:e});for(const e of G.envFileErrors)Zr.warn(e);var Bo=process.argv.findIndex(e=>"-v"===e||"--verbose"===e);-1!==Bo&&process.argv.splice(Bo,1);var Do=process.argv.findIndex(e=>"--no-telemetry"===e);-1!==Do&&process.argv.splice(Do,1),Zr.info("CLI starting",{version:sr,args:process.argv.slice(2),cwd:process.cwd()}),process.on("unhandledRejection",(e,t)=>{Zr.error("Unhandled promise rejection",{reason:e instanceof Error?{message:e.message,stack:e.stack}:e,promise:String(t)}),Zr.flush(),Zr.printLogFileInfo()}),process.on("uncaughtException",(e,t)=>{"EPIPE"!==e.code&&(Zr.error("Uncaught exception",{error:{message:e.message,stack:e.stack,name:e.name},origin:t}),Zr.flush(),Zr.printLogFileInfo())});var No=new r.Command;No.name("stably").description("AI-assisted Playwright testing CLI").version(sr),No.enablePositionalOptions(),No.showHelpAfterError(),No.exitOverride(),No.configureHelp({subcommandTerm:e=>{const t=e.registeredArguments.map(e=>e.required?`<${e.name()}>`:`[${e.name()}]`).join(" ");return t?`${e.name()} ${t}`:e.name()}});var ko=[];No.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>{ko.push(e)}});var jo=()=>{const e=No.helpInformation().trimEnd();return e?`${e}\n`:""},$o=(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},Mo=()=>{process.stdout.write(jo())};No.command("help [command...]").description("Show help for a command (e.g. stably help create)").action(e=>{if(!e||0===e.length)return void Mo();const t=$o(No,e);if(!t)return process.stderr.write(`Unknown command: ${e.join(" ")}\n`),Mo(),void(process.exitCode=1);var r;r=t,process.stdout.write((e=>{const t=e.helpInformation().trimEnd();return t?`${t}\n`:""})(r))}),No.action(()=>so({mode:"chat",getHelpText:jo})),No.command("login").description("Authenticate with Stably in your browser").action(Dr),No.command("logout").description("Clear stored Stably credentials").action(async()=>{const e=tn();e&&(m.log.warn(`Environment variables ${D.default.cyan("STABLY_API_KEY")} and ${D.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 vr();if(!t)return void m.outro(e?D.default.yellow("No stored OAuth login found to clear."):D.default.yellow("You are not logged in."));const r=m.spinner();r.start("Logging out..."),await(async e=>{try{await fetch(`${ar}/api/backend/v1/logout`,{body:JSON.stringify({refresh_token:e}),headers:{"Content-Type":"application/json"},method:"POST"})}catch{}})(t.refreshToken),await xr(),await Ar(),r.stop(D.default.green("✓ Logged out")),m.outro(D.default.green("You have been logged out successfully."))}),No.command("whoami").description("Show auth status and current project").action(async()=>{m.log.info(`${D.default.bold("CLI Version:")} ${D.default.cyan(sr)}`);const e=tn();if(e){m.log.info(D.default.dim("Authentication: Environment variables")),m.log.info(` ${D.default.bold("API Key:")} ${D.default.cyan(e.apiKey.slice(0,8))}...`),m.log.info(` ${D.default.bold("Project ID:")} ${D.default.cyan(e.projectId)}`);const t=await vr();if(t){let e;try{e=mr(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(` ${D.default.bold("OAuth Email:")} ${D.default.cyan(e)}`),m.log.info(` ${D.default.bold("Tip:")} Unset env vars to use OAuth`)}return void m.outro(D.default.green("Authenticated via environment variables"))}const t=await vr();if(!t)return void m.outro(D.default.yellow("Not logged in. Run `stably login` to authenticate."));let r;try{r=mr(t.accessToken).email}catch{r=void 0}const n=await Rr();if(!n)return m.log.info(D.default.dim("Authentication: OAuth (not linked to a project)")),r&&m.log.info(` ${D.default.bold("Email:")} ${D.default.cyan(r)}`),void m.outro(D.default.yellow("Logged in but this directory is not linked to a project. Run `stably login` to link."));const o=await(async()=>Sr(process.cwd()))(),s=o?C.default.dirname(o):process.cwd(),i=C.default.relative(process.cwd(),s)||".";m.log.info(D.default.dim("Authentication: OAuth")),r&&m.log.info(` ${D.default.bold("Email:")} ${D.default.cyan(r)}`),m.log.info(` ${D.default.bold("Organization:")} ${D.default.cyan(n.orgName)}`),m.log.info(` ${D.default.bold("Project:")} ${D.default.cyan(n.projectName)}`),m.log.info(` ${D.default.bold("Linked at:")} ${D.default.dim(i)}`),m.outro(D.default.green("Authenticated"))}),No.command("build <input>").description("Compile a prompt file into a Playwright test").requiredOption("-o, --output <file>","Output file (required)").option("--force","Force regeneration even if prompt is unchanged").action(async(e,t)=>{try{await async function({force:e,input:t,output:r}){const n=process.cwd(),o=C.default.resolve(n,t),s=await async function({output:e}){const t=e.trim();if(!t)throw new Error("Output file is required. Example: -o tests/example.spec.ts");const r=C.default.resolve(process.cwd(),t);if([C.default.sep,"/"].some(e=>t.endsWith(e)))return{mode:"directory",dirPath:r};try{if((await k.default.stat(r)).isDirectory())return{mode:"directory",dirPath:r}}catch(e){if(!lo(e)||"ENOENT"!==e.code)throw e}if(!fn.test(r))throw new Error(`Output file must be a valid Playwright test file (e.g., .spec.ts, .test.ts): ${e}`);return{mode:"file",filePath:r}}({output:r}),i=await uo({filePath:o,errorMessage:`Prompt file not found: ${t}`});if(!i.trim())throw new Error(`Prompt file is empty: ${t}`);const a=function(e){const t=N.default.createHash(ao).update(e,"utf8").digest("hex");return`${ao}:${t}`}(i),c=po(C.default.relative(n,o)),l="directory"===s.mode,d=l?s.dirPath:C.default.dirname(s.filePath),u=(p=o,C.default.basename(p).replace(/\.prompt\.md$/,"").replace(/\.md$/,"").replace(/\.txt$/,""));var p;let f=l?await async function(e,t){return(await fo(e)).find(e=>{const r=C.default.basename(e);return r.startsWith(`${t}.spec`)||r.startsWith(`${t}.test`)})}(s.dirPath,u):s.filePath;if(!e&&f&&await async function({outputFilePath:e,promptHash:t}){try{const r=function(e){const t=e.match(/^\/\*\*[\s\S]*?@prompt-hash\s+(sha256:[a-f0-9]{64})[\s\S]*?\*\//);return t?.[1]}(await k.default.readFile(e,"utf8"));return r===t}catch(e){if(lo(e)&&"ENOENT"===e.code)return!1;throw e}}({outputFilePath:f,promptHash:a}))return D.default.green("Skipped build: test code is up to date (hash unchanged)"),"skipped";const h=l?new Set(await fo(s.dirPath)):void 0;await k.default.mkdir(d,{recursive:!0});const g=function({builtAt:e=new Date,promptFile:t,promptHash:r}){return["/**"," * @generated by stably build",` * @prompt-hash ${r}`,` * @prompt-file ${t}`,` * @built-at ${e.toISOString()}`," *",` * DO NOT EDIT MANUALLY - regenerate with: stably build ${t} --force`," */"].join("\n")}({promptFile:c,promptHash:a}),m=po(l?C.default.relative(n,s.dirPath)||s.dirPath:C.default.relative(n,s.filePath)),y=function(e){const{promptContent:t}=e;return["Compile this test specification into a Playwright test file.",..."file"===e.mode?[`Primary output file: ${e.outputFile}`,"","File creation rules:","- Always create/update the primary output file specified above."]:[`Output directory: ${e.outputDir}`,"","Choose output filename:",`- Look at existing test files in ${e.outputDir} 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. Check whether ${"file"===e.mode?e.outputFile:`the test file in ${e.outputDir} (based on prompt filename or matching test file)`} already exists.`,"2. If it exists, read it first and compare it 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 Playwright test command (e.g., `pnpm playwright test` or the repository's test command).","If tests fail, analyze the errors and iterate on the test code until all tests pass.","","Prompt specification:",t].join("\n")}(l?{mode:"directory",outputDir:m,promptContent:i}:{mode:"file",outputFile:m,promptContent:i});await so({mode:"build",prompt:y,outputDir:d,customHeader:g});const _=process.exitCode;if("number"==typeof _&&0!==_)throw new Error(`Build generation failed for: ${m}`);if(l&&!f&&h&&(f=(await fo(s.dirPath)).find(e=>!h.has(e)),!f))throw new Error(`Build finished but no new test file was created in: ${m}`);if(!f)throw new Error(`Build finished but output file was not created: ${m}`);const b=await uo({filePath:f,errorMessage:`Build finished but output file was not created: ${m}`}),E=function(e){return e.replace(co,"")}(b),w=b.startsWith(g)?b:`${g}\n\n${E}`;w!==b&&await k.default.writeFile(f,w,"utf8");const I=po(C.default.relative(n,f));return D.default.green(`Built: ${I}`),"built"}({force:t.force??!1,input:e,output:t.output})}catch(e){const t=e instanceof Error?e.message:String(e);process.stderr.write(`${t}\n`),process.exitCode=1}}),No.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 sn(),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 o=await R.startTunnel(`http://localhost:${e.port}`,{subdomain:r});n.stop(`Your local environment is available at: ${D.default.underline(D.default.cyan(o.url))}`)}),No.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((e,t)=>{const r=e.length>0&&"test"===e[0]?e.slice(1):e;return so({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((e,t)=>so({mode:"single",prompt:e,outputDir:t.output})),No.command("fix [runId]").description("Fix failing tests from a run (auto-detects from last test run or CI)").action(async e=>{const t=await(async e=>{const t=e=>e.replace(/\//g,"_");if(e)return Zr.debug("Run ID provided explicitly",{runId:e}),t(e);const 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(Dt))if(Dt[r].detect({env:e,cwd:t}))return{isCi:!0,...Dt[r].configuration({env:e,cwd:t})};return{isCi:Boolean(e.CI),...(r={env:e,cwd:t},{commit:st(r),branch:it(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 Zr.debug("Run ID detected from CI environment",{runId:r}),t(r);Zr.debug("No explicit run ID or CI environment detected, checking last-run.json");const n=await(async()=>{try{const e=await(async()=>{let e=process.cwd();const{root:t}=C.default.parse(e);for(;e!==t;){const t=C.default.join(e,".stably/last-run.json");try{return await g.access(t),t}catch{e=C.default.dirname(e)}}})();if(!e)return;const t=await g.readFile(e,"utf-8");return{...io.parse(JSON.parse(t)),filePath:e}}catch{return}})();if(n){const e=(Date.now()-n.timestamp)/36e5;return Zr.debug("Run ID found in last-run.json",{runId:n.runId,timestamp:n.timestamp,filePath:n.filePath,ageHours:Math.round(e)}),e>24&&Zr.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)}Zr.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)),so({mode:"fix",runId:t})}),No.command("init").description("Initialize Playwright and Stably SDK in your project").action(()=>so({mode:"init"})),No.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;Eo(D.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(vo,{signal:e.signal});if(!t.ok)throw new Error(`Failed to fetch latest version: ${t.statusText}`);return To.parse(await t.json()).version}finally{clearTimeout(t)}}();return{current:sr,latest:e,isOutdated:So(sr,e)}}()}catch(e){return wo(D.default.red("Failed to check for updates:"),e instanceof Error?e.message:e),void(process.exitCode=1)}if(Eo(`Current version: ${D.default.yellow(r.current)}`),Eo(`Latest version: ${D.default.green(r.latest)}`),Eo(),!r.isOutdated)return void Eo(D.default.green("✓ You are already on the latest version!"));if(Eo(D.default.yellow(`⚠ A new version is available: ${r.current} → ${r.latest}`)),Eo(),t)return Eo(D.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=o.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=o.execSync("pnpm root -g",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-pnpm"}catch{}try{const t=o.execSync("yarn global dir",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-yarn-classic"}catch{}try{const t=o.execSync("yarn config get globalFolder",{encoding:"utf-8"}).trim();if(e.includes(t))return"global-yarn-berry"}catch{}return"unknown"}(),s=function(e){switch(e){case"global-npm":case"global-yarn-berry":case"unknown":return{command:"npm",args:["install","-g",`${Io}@latest`],description:`npm install -g ${Io}@latest`};case"global-pnpm":return{command:"pnpm",args:["add","-g",`${Io}@latest`],description:`pnpm add -g ${Io}@latest`};case"global-yarn-classic":return{command:"yarn",args:["global","add",`${Io}@latest`],description:`yarn global add ${Io}@latest`};case"npx":return{command:"npx",args:[`${Io}@latest`],description:`npx ${Io}@latest (always uses latest)`}}}(n);if("npx"===n)return Eo(D.default.dim("You are running via npx, which always fetches the latest version.")),void Eo(D.default.dim(`Simply run: ${D.default.white("npx stably")} to use the latest version.`));"unknown"===n?(Eo(D.default.yellow("Could not detect installation method. Falling back to npm.")),Eo()):"global-yarn-berry"===n&&(Eo(D.default.yellow("Yarn Berry does not support global packages. Falling back to npm.")),Eo()),Eo(`Upgrade command: ${D.default.cyan(s.description)}`),Eo(),Eo(D.default.cyan("Upgrading...")),Eo();try{await(i=s.command,a=s.args,new Promise((e,t)=>{const r=o.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)})})),Eo(),Eo(D.default.green("✓ Upgrade complete!")),Eo(D.default.dim(`Run ${D.default.white("stably --version")} to verify.`))}catch(e){wo(D.default.red("Upgrade failed:"),e instanceof Error?e.message:e),Eo(),Eo(D.default.dim("You can try manually running:")),Eo(D.default.cyan(` ${s.description}`)),process.exitCode=1}var i,a}(e)),_o.forEach(({args:e,description:r,name:n})=>{No.command(n).description(r).helpOption(!1).helpCommand(!1).allowUnknownOption(!0).allowExcessArguments(!0).passThroughOptions().action(()=>async function({overrideArgs:e,subcommand:r}){const n=process.argv,s=n.findIndex((e,t)=>t>1&&e===r),a=-1===s?[]:n.slice(s+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=_o.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=ho();if(!n.installed||!n.inNodeModules)return void r('No Playwright project found in this directory or its parents.\nMake sure you\'re in a directory within your Playwright project, or run "stably init" to create a new playwright directory.');const{packageManager:s}=n;if(!s)return void r("Could not determine package manager.");r("Playwright options:"),r("");const[i,...a]=yo(s),c=bo(s);return new Promise(t=>{const r=o.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 d=e??[],u=new Set(d.map(e=>{const[t]=e.split("=");return t})),p=[];for(let e=0;e<l.length;e++){const t=l[e],[r]=t.split("=");u.has(r)?!t.includes("=")&&e+1<l.length&&!l[e+1].startsWith("-")&&e++:p.push(t)}const f=[r,...d,...p],h="test"===r?await cn():void 0,g="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(),s=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: https://docs.stably.ai/getting-started/sdk-setup-guide\n")),r},a=(e,r)=>{try{return function({baseConfigPath:e,projectDir:r}){const n=function(e){try{const t=o.execSync("npm pkg get type",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return"module"===JSON.parse(t.trim())}catch{return!1}}(r),s=n?"mts":"ts",a=t.dirname(t.resolve(e)),c=t.basename(e),l=t.join(a,`.stably-playwright-wrapper.config.${s}`),d=`\n// Auto-generated wrapper config by Stably CLI\n// This file injects the Stably reporter and ensures trace is enabled\nimport baseConfig from './${c}';\nimport { defineConfig, stablyReporter } from '@stablyai/playwright-test';\n\n// Inline type definitions to avoid import failures when @stablyai/playwright-test is not installed\ntype StablyNotificationConfig = {\n email?: { to: string[]; notifyOnStart?: boolean; notifyOnResult?: 'all' | 'failures-only' | null } | null;\n slack?: { channelName: string; notifyOnStart?: boolean; notifyOnResult?: 'all' | 'failures-only' } | null;\n};\n\ntype ProjectNotificationConfig = {\n projectName: string;\n notifications: StablyNotificationConfig;\n};\n\n// Extract notification configs from projects that have stably.notifications defined\n// This runs at config-load time before Playwright strips custom properties\nconst extractNotificationConfigs = (): ProjectNotificationConfig[] | undefined => {\n const projects = baseConfig.projects;\n if (!projects || !Array.isArray(projects)) return undefined;\n\n const configs = projects\n .map((p: { name?: string; stably?: { notifications?: StablyNotificationConfig } }) => {\n const notifications = p.stably?.notifications;\n return notifications ? { projectName: p.name ?? '', notifications } : undefined;\n })\n .filter((config): config is ProjectNotificationConfig => config != null);\n\n return configs.length > 0 ? configs : undefined;\n};\n\nconst isStablyReporter = (reporter: unknown): boolean => {\n // Only match @stablyai npm scope to avoid false positives on unrelated reporters\n // that might contain "stably" substring (e.g., "unstably-runner")\n if (typeof reporter === 'string') {\n return reporter.includes('@stablyai');\n }\n if (Array.isArray(reporter) && typeof reporter[0] === 'string') {\n return reporter[0].includes('@stablyai');\n }\n return false;\n};\n\nconst getStablyReporterOptions = (reporters: unknown[]): Record<string, unknown> | undefined => {\n for (const reporter of reporters) {\n if (Array.isArray(reporter) && typeof reporter[0] === 'string' && reporter[0].includes('@stablyai')) {\n return (reporter[1] as Record<string, unknown>) ?? {};\n }\n }\n return undefined;\n};\n\nconst filterOutStablyReporter = (reporters: unknown[]): unknown[] => {\n return reporters.filter((reporter) => !isStablyReporter(reporter));\n};\n\nconst buildReporterList = () => {\n const existingReporters = baseConfig.reporter;\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 })];\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 });\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,d,"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(Ln))return;const t=e.length>0&&!e.endsWith("\n");i.appendFileSync(r,`${t?"\n":""}${Ln}\n`)}else i.writeFileSync(r,`${Ln}\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 o=t.resolve(n,e[r+1]),i=t.dirname(o);if(!s(i))return;const c=a(o,i);if(!c)return;return e[r+1]=c,c}const o=e.findIndex(e=>e.startsWith("--config=")||e.startsWith("-c="));if(-1!==o){const r=t.resolve(n,e[o].split("=")[1]),i=t.dirname(r);if(!s(i))return;const c=a(r,i);if(!c)return;const l=e[o].startsWith("--config=")?"--config=":"-c=";return e[o]=`${l}${c}`,c}}const c=Bn(n);if(!c)return;const l=t.dirname(c);if(!s(l))return;const d=a(c,l);return d?(e.push("--config",d),d):void 0}({forwardedArgs:f,hasCredentials:null!=h}):void 0;!function(e,t={}){const r=ho();r.installed||(console.error('Playwright is not installed. Please run "stably init" to install it.'),process.exit(1)),r.inNodeModules||(console.error("Playwright is present in your project, but not in node_modules. Please install your dependencies before proceeding."),process.exit(1));const{packageManager:n}=r;n||(console.error("Playwright installation not found. Could not determine your package manager (tried pnpm, yarn, and npm)."),process.exit(1));const[s,...i]=yo(n),a=an(t.env),c=o.spawn(s,[...i,...e],{stdio:["inherit","pipe","pipe"],env:{...a,...process.env.CI?{}:{FORCE_COLOR:"1"}}}),l=bo(n);c.stdout?.on("data",e=>{l(e,process.stdout)}),c.stderr?.on("data",e=>{l(e,process.stderr)});let d=!1;const u=()=>{d||(d=!0,t.onClose?.())},p=e=>{u(),c.kill(e);const t="SIGINT"===e?130:143;process.exit(t)};process.on("SIGINT",p),process.on("SIGTERM",p),c.on("close",e=>{u(),process.exitCode=e??0,process.removeListener("SIGINT",p),process.removeListener("SIGTERM",p)})}(f,{env:h,onClose:()=>{var e;(e=g)&&i.existsSync(e)&&i.rmSync(e)}})}({overrideArgs:e,subcommand:n}))});var Ho=()=>{0!==ko.length&&(process.stderr.write(ko.join("")),ko=[])};(async()=>{await(async()=>{if(!Lo&&"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":sr,"node.version":process.version,"os.platform":process.platform}}),Lo=!0}catch{}})();try{await No.parseAsync(process.argv),Zr.info("CLI completed successfully")}catch(e){if(!(e=>!!e&&"object"==typeof e&&"code"in e)(e))throw Zr.error("Unexpected CLI error",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),Ho(),Zr.flush(),Zr.printLogFileInfo(),await Oo(),e;const t="number"==typeof e.exitCode?e.exitCode:1,r=process.argv.slice(2).find(e=>!e.startsWith("-")),n=!!r&&!!$o(No,[r]);if(("commander.excessArguments"===e.code||"commander.unknownCommand"===e.code)&&r&&!n)return ko=[],Zr.warn("Unknown command",{command:r}),process.stderr.write(`command '${r}' not found\n`),Mo(),void(process.exitCode=t);Zr.debug("Commander error",{code:e.code,exitCode:t}),Ho(),process.exitCode=t}finally{Zr.flush(),await Oo()}})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "stably",
3
- "version": "4.4.4",
3
+ "version": "4.4.5",
4
4
  "packageManager": "pnpm@10.24.0",
5
5
  "description": "AI-powered E2E Playwright testing CLI. Stably can understand your codebase, edit/run tests, and handle complex test scenarios for you.",
6
6
  "main": "dist/index.js",