stably 4.3.0 → 4.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -0
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -35,3 +35,11 @@ Below is a short list of common commands. For a complete list, please use `stabl
|
|
|
35
35
|
* `npx stably`: This starts our REPL which will help with test creation or modifications
|
|
36
36
|
* `npx stably test`: Use this to run tests locally or in the CI
|
|
37
37
|
* `npx stably --help`: Will print full list of commands
|
|
38
|
+
|
|
39
|
+
## Authentication
|
|
40
|
+
Stably CLI supports two auth modes:
|
|
41
|
+
|
|
42
|
+
- **API key via env vars (highest priority)**: set `STABLY_API_KEY` and `STABLY_PROJECT_ID`
|
|
43
|
+
- **Browser login (OAuth)**: run `npx stably login` (credentials are stored locally)
|
|
44
|
+
|
|
45
|
+
If both are present, the CLI will honor the environment variables and warn that stored OAuth credentials are being ignored. To switch back to browser login, unset the env vars.
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var e=require("commander"),t=require("buffer"),r=require("path"),n=require("child_process"),o=require("process"),s=require("url"),i=require("os"),a=require("fs");require("timers/promises");var c=require("util"),l=require("@anthropic-ai/claude-agent-sdk"),d=require("dotenv"),u=require("picocolors"),p=require("simple-git"),f=require("crypto"),h=require("fs/promises"),m=require("@clack/prompts"),g=require("readline/promises"),_=require("zod"),y=require("open"),E=require("http"),b=require("react"),I=require("react/jsx-runtime"),v=require("zod/v3"),T=require("@stablyhq/runner-sdk");function w(e){return e&&e.__esModule?e:{default:e}}var R=w(r),S=w(n),C=w(o),x=w(i),A=w(a),U=w(u),P=w(f),L=w(_),O=w(y),B=w(E),N=Object.create,D=Object.defineProperty,j=Object.getOwnPropertyDescriptor,k=Object.getOwnPropertyNames,M=Object.getPrototypeOf,$=Object.prototype.hasOwnProperty,H=(e=>"undefined"!=typeof require?require:"undefined"!=typeof Proxy?new Proxy(e,{get:(e,t)=>("undefined"!=typeof require?require:e)[t]}):e)(function(e){if("undefined"!=typeof require)return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),G=(e,t)=>function(){return t||(0,e[k(e)[0]])((t={exports:{}}).exports,t),t.exports},F=(e,t,r)=>(r=null!=e?N(M(e)):{},((e,t,r,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let r of k(t))$.call(e,r)||void 0===r||D(e,r,{get:()=>t[r],enumerable:!(n=j(t,r))||n.enumerable});return e})(D(r,"default",{value:e,enumerable:!0}),e)),Y=G({"node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js"(e,t){t.exports=o,o.sync=function(e,t){return n(r.statSync(e),e,t)};var r=H("fs");function n(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 o(e,t,o){r.stat(e,function(r,s){o(r,!r&&n(s,e,t))})}}}),z=G({"node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/mode.js"(e,t){t.exports=n,n.sync=function(e,t){return o(r.statSync(e),t)};var r=H("fs");function n(e,t,n){r.stat(e,function(e,r){n(e,!e&&o(r,t))})}function o(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)}}}),q=G({"node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js"(e,t){var r;function n(e,t,o){if("function"==typeof t&&(o=t,t={}),!o){if("function"!=typeof Promise)throw new TypeError("callback not provided");return new Promise(function(r,o){n(e,t||{},function(e,t){e?o(e):r(t)})})}r(e,t||{},function(e,r){e&&("EACCES"===e.code||t&&t.ignoreErrors)&&(e=null,r=!1),o(e,r)})}H("fs"),r="win32"===process.platform||global.TESTING_WINDOWS?Y():z(),t.exports=n,n.sync=function(e,t){try{return r.sync(e,t||{})}catch(e){if(t&&t.ignoreErrors||"EACCES"===e.code)return!1;throw e}}}}),K=G({"node_modules/.pnpm/which@2.0.2/node_modules/which/which.js"(e,t){var r="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,n=H("path"),o=r?";":":",s=q(),i=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),a=(e,t)=>{const n=t.colon||o,s=e.match(/\//)||r&&e.match(/\\/)?[""]:[...r?[process.cwd()]:[],...(t.path||process.env.PATH||"").split(n)],i=r?t.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",a=r?i.split(n):[""];return r&&-1!==e.indexOf(".")&&""!==a[0]&&a.unshift(""),{pathEnv:s,pathExt:a,pathExtExe:i}},c=(e,t,r)=>{"function"==typeof t&&(r=t,t={}),t||(t={});const{pathEnv:o,pathExt:c,pathExtExe:l}=a(e,t),d=[],u=r=>new Promise((s,a)=>{if(r===o.length)return t.all&&d.length?s(d):a(i(e));const c=o[r],l=/^".*"$/.test(c)?c.slice(1,-1):c,u=n.join(l,e),f=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;s(p(f,r,0))}),p=(e,r,n)=>new Promise((o,i)=>{if(n===c.length)return o(u(r+1));const a=c[n];s(e+a,{pathExt:l},(s,i)=>{if(!s&&i){if(!t.all)return o(e+a);d.push(e+a)}return o(p(e,r,n+1))})});return r?u(0).then(e=>r(null,e),r):u(0)};t.exports=c,c.sync=(e,t)=>{t=t||{};const{pathEnv:r,pathExt:o,pathExtExe:c}=a(e,t),l=[];for(let i=0;i<r.length;i++){const a=r[i],d=/^".*"$/.test(a)?a.slice(1,-1):a,u=n.join(d,e),p=!d&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;for(let e=0;e<o.length;e++){const r=p+o[e];try{if(s.sync(r,{pathExt:c})){if(!t.all)return r;l.push(r)}}catch(e){}}}if(t.all&&l.length)return l;if(t.nothrow)return null;throw i(e)}}}),V=G({"node_modules/.pnpm/path-key@3.1.1/node_modules/path-key/index.js"(e,t){var r=(e={})=>{const t=e.env||process.env;return"win32"!==(e.platform||process.platform)?"PATH":Object.keys(t).reverse().find(e=>"PATH"===e.toUpperCase())||"Path"};t.exports=r,t.exports.default=r}}),W=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js"(e,t){var r=H("path"),n=K(),o=V();function s(e,t){const s=e.options.env||process.env,i=process.cwd(),a=null!=e.options.cwd,c=a&&void 0!==process.chdir&&!process.chdir.disabled;if(c)try{process.chdir(e.options.cwd)}catch(e){}let l;try{l=n.sync(e.command,{path:s[o({env:s})],pathExt:t?r.delimiter:void 0})}catch(e){}finally{c&&process.chdir(i)}return l&&(l=r.resolve(a?e.options.cwd:"",l)),l}t.exports=function(e){return s(e)||s(e,!0)}}}),J=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/escape.js"(e,t){var r=/([()\][%!^"`<>&|;, *?])/g;t.exports.command=function(e){return e.replace(r,"^$1")},t.exports.argument=function(e,t){return e=(e=`"${e=(e=(e=`${e}`).replace(/(?=(\\+?)?)\1"/g,'$1$1\\"')).replace(/(?=(\\+?)?)\1$/,"$1$1")}"`).replace(r,"^$1"),t&&(e=e.replace(r,"^$1")),e}}}),X=G({"node_modules/.pnpm/shebang-regex@3.0.0/node_modules/shebang-regex/index.js"(e,t){t.exports=/^#!(.*)/}}),Q=G({"node_modules/.pnpm/shebang-command@2.0.0/node_modules/shebang-command/index.js"(e,t){var r=X();t.exports=(e="")=>{const t=e.match(r);if(!t)return null;const[n,o]=t[0].replace(/#! ?/,"").split(" "),s=n.split("/").pop();return"env"===s?o:o?`${s} ${o}`:s}}}),Z=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js"(e,t){var r=H("fs"),n=Q();t.exports=function(e){const t=Buffer.alloc(150);let o;try{o=r.openSync(e,"r"),r.readSync(o,t,0,150,0),r.closeSync(o)}catch(e){}return n(t.toString())}}}),ee=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js"(e,t){var r=H("path"),n=W(),o=J(),s=Z(),i="win32"===process.platform,a=/\.(?:com|exe)$/i,c=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;t.exports=function(e,t,l){t&&!Array.isArray(t)&&(l=t,t=null);const d={command:e,args:t=t?t.slice(0):[],options:l=Object.assign({},l),file:void 0,original:{command:e,args:t}};return l.shell?d:function(e){if(!i)return e;const t=function(e){e.file=n(e);const t=e.file&&s(e.file);return t?(e.args.unshift(e.file),e.command=t,n(e)):e.file}(e),l=!a.test(t);if(e.options.forceShell||l){const n=c.test(t);e.command=r.normalize(e.command),e.command=o.command(e.command),e.args=e.args.map(e=>o.argument(e,n));const s=[e.command].concat(e.args).join(" ");e.args=["/d","/s","/c",`"${s}"`],e.command=process.env.comspec||"cmd.exe",e.options.windowsVerbatimArguments=!0}return e}(d)}}}),te=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/enoent.js"(e,t){var r="win32"===process.platform;function n(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 o(e,t){return r&&1===e&&!t.file?n(t.original,"spawn"):null}t.exports={hookChildProcess:function(e,t){if(!r)return;const n=e.emit;e.emit=function(r,s){if("exit"===r){const r=o(s,t);if(r)return n.call(e,"error",r)}return n.apply(e,arguments)}},verifyENOENT:o,verifyENOENTSync:function(e,t){return r&&1===e&&!t.file?n(t.original,"spawnSync"):null},notFoundError:n}}}),re=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/index.js"(e,t){var r=H("child_process"),n=ee(),o=te();function s(e,t,s){const i=n(e,t,s),a=r.spawn(i.command,i.args,i.options);return o.hookChildProcess(a,i),a}t.exports=s,t.exports.spawn=s,t.exports.sync=function(e,t,s){const i=n(e,t,s),a=r.spawnSync(i.command,i.args,i.options);return a.error=a.error||o.verifyENOENTSync(a.status,i),a},t.exports._parse=n,t.exports._enoent=o}}),ne=G({"node_modules/.pnpm/merge-stream@2.0.0/node_modules/merge-stream/index.js"(e,t){var{PassThrough:r}=H("stream");t.exports=function(){var e=[],t=new r({objectMode:!0});return t.setMaxListeners(0),t.add=n,t.isEmpty=function(){return 0==e.length},t.on("unpipe",o),Array.prototype.slice.call(arguments).forEach(n),t;function n(r){return Array.isArray(r)?(r.forEach(n),this):(e.push(r),r.once("end",o.bind(null,r)),r.once("error",t.emit.bind(t,"error")),r.pipe(t,{end:!1}),this)}function o(r){!(e=e.filter(function(e){return e!==r})).length&&t.readable&&t.end()}}}}),oe=G({"node_modules/.pnpm/java-properties@1.0.2/node_modules/java-properties/dist-node/index.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.of=e.PropertiesFile=void 0;var t,r=(t=H("fs"))&&t.__esModule?t:{default:t},n=class{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 t=r.default.readFileSync(e,"utf-8").split(/\r?\n/),n=this;for(let e=0;e<t.length;e++){let r=t[e];for(;"\\"===r.substring(r.length-1);)r=r.slice(0,-1),r+=t[e+1].trim(),e++;n.makeKeys(r)}}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={}}};e.PropertiesFile=n,e.of=function(...e){let t=new n;return t.of.apply(t,e),t}}}),se={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 ie(e){return(/\d+(?!.*\d+)/.exec(e)||[])[0]}function ae(e){return e?/^(?:refs\/heads\/)?(?<branch>.+)$/i.exec(e)[1]:void 0}var ce={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:ae(r?e.SYSTEM_PULLREQUEST_TARGETBRANCH:e.BUILD_SOURCEBRANCH),pr:t,isPr:r,prBranch:ae(r?e.SYSTEM_PULLREQUEST_SOURCEBRANCH:void 0),root:e.BUILD_REPOSITORY_LOCALPATH}}},le={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})},de={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})},ue={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}}},pe={detect:({env:e})=>Boolean(e.BUDDY_WORKSPACE_ID),configuration({env:e}){const t=ie(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}}},fe=F(re());function he(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 me=(e,t)=>({name:`SIGRT${t+1}`,number:ge+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),ge=34,_e=[{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"}],ye=()=>{const e=(()=>{const e=64-ge+1;return Array.from({length:e},me)})();return[..._e,...e].map(Ee)},Ee=({name:e,number:t,description:r,action:n,forced:o=!1,standard:s})=>{const{signals:{[e]:a}}=i.constants,c=void 0!==a;return{name:e,number:c?a:t,description:r,supported:c,action:n,forced:o,standard:s}},be=({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}],Ie=(()=>{const e=ye();return Object.fromEntries(e.map(be))})();(()=>{const e=ye(),t=Array.from({length:65},(t,r)=>((e,t)=>{const r=((e,t)=>{const r=t.find(({name:t})=>i.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:a,forced:c,standard:l}=r;return{[e]:{name:n,number:e,description:o,supported:s,action:a,forced:c,standard:l}}})(r,e));Object.assign({},...t)})();var ve=({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=C.default.cwd()}}})=>{s=null===s?void 0:s;const f=void 0===(o=null===o?void 0:o)?void 0:Ie[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}),m=`Command ${h}: ${i}`,g="[object Error]"===Object.prototype.toString.call(n),_=g?`${m}\n${n.message}`:m,y=[_,t,e].filter(Boolean).join("\n");return g?(n.originalMessage=n.message,n.message=y):n=new Error(y),n.shortMessage=_,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},Te=["stdin","stdout","stderr"],we=[];we.push("SIGHUP","SIGINT","SIGTERM"),"win32"!==process.platform&&we.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),"linux"===process.platform&&we.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var Re=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,Se=Symbol.for("signal-exit emitter"),Ce=globalThis,xe=Object.defineProperty.bind(Object),Ae=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(Ce[Se])return Ce[Se];xe(Ce,Se,{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}},Ue=class{},Pe=globalThis.process;Re(Pe)?new class extends Ue{#e="win32"===Pe.platform?"SIGINT":"SIGHUP";#t=new Ae;#r;#n;#o;#s={};#i=!1;constructor(e){super(),this.#r=e,this.#s={};for(const t of we)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(!Re(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 we)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,we.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 Re(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&&Re(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)}}(Pe):new class extends Ue{onExit(){return()=>{}}load(){}unload(){}},new TextEncoder,F(ne());var Le=(async()=>{})().constructor.prototype;["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(Le,e)]);var Oe=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],Be=/^[\w.-]+$/,Ne=c.debuglog("execa").enabled,De=(e,t)=>String(e).padStart(t,"0"),je=(e,t,r={})=>{const n=fe.default._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||C.default.cwd(),execPath:C.default.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:Ne,...r}).env=(({env:e,extendEnv:t,preferLocal:r,localDir:n,execPath:o})=>{const i=t?{...C.default.env,...e}:e;return r?(({env:e=C.default.env,...t}={})=>{const r=he({env:e={...e}});return t.path=e[r],e[r]=(({cwd:e=C.default.cwd(),path:t=C.default.env[he()],preferLocal:r=!0,execPath:n=C.default.execPath,addExecPath:o=!0}={})=>{const i=e instanceof URL?s.fileURLToPath(e):e,a=R.default.resolve(i),c=[];return r&&((e,t)=>{let r;for(;r!==t;)e.push(R.default.join(t,"node_modules/.bin")),r=t,t=R.default.resolve(t,"..")})(c,a),o&&((e,t,r)=>{const n=t instanceof URL?s.fileURLToPath(t):t;e.push(R.default.resolve(r,n,".."))})(c,n,a),[...c,t].join(R.default.delimiter)})(t),e})({env:i,cwd:n,execPath:o}):i})(r),r.stdio=(e=>{if(!e)return;const{stdio:t}=e;if(void 0===t)return Te.map(t=>e[t]);if((e=>Te.some(t=>void 0!==e[t]))(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${Te.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,Te.length);return Array.from({length:r},(e,r)=>t[r])})(r),"win32"===C.default.platform&&"cmd"===R.default.basename(e,".exe")&&t.unshift("/q"),{file:e,args:t,options:r,parsed:n}},ke=(e,r,n)=>"string"==typeof r||t.Buffer.isBuffer(r)?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}(r):r:void 0===n?void 0:"";function Me(e,t,r){const n=je(e,t,r),o=((e,t)=>Oe(e,t).join(" "))(e,t),s=((e,t)=>Oe(e,t).map(e=>(e=>"string"!=typeof e||Be.test(e)?e:`"${e.replaceAll('"','\\"')}"`)(e)).join(" "))(e,t);((e,{verbose:t})=>{t&&C.default.stderr.write(`[${(()=>{const e=new Date;return`${De(e.getHours(),2)}:${De(e.getMinutes(),2)}:${De(e.getSeconds(),2)}.${De(e.getMilliseconds(),3)}`})()}] ${e}\n`)})(s,n.options);const i=(e=>{const t=(({input:e,inputFile:t})=>"string"!=typeof t?e:((e=>{if(void 0!==e)throw new TypeError("The `input` and `inputFile` options cannot be both set.")})(e),a.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=S.default.spawnSync(n.file,n.args,{...n.options,input:i})}catch(e){throw ve({error:e,stdout:"",stderr:"",all:"",command:o,escapedCommand:s,parsed:n,timedOut:!1,isCanceled:!1,killed:!1})}const l=ke(n.options,c.stdout,c.error),d=ke(n.options,c.stderr,c.error);if(c.error||0!==c.status||null!==c.signal){const e=ve({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 $e(e){try{return Me("git",["rev-parse","HEAD"],e).stdout}catch{return}}function He(e){try{const t=Me("git",["rev-parse","--abbrev-ref","HEAD"],e).stdout;if("HEAD"===t){const t=Me("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 Ge=/^(?:.*)@(?:.*):(?:\d+\/)?(.*)\.git$/,Fe=/^\/(.*)\.git$/;function Ye(e){if(e){if(e.match(Ge))return e.replace(Ge,"$1");try{return new URL(e).pathname.replace(Fe,"$1")}catch{return}}}var ze={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:Ye(e.BUILDKITE_REPO),pr:t,isPr:r,prBranch:r?e.BUILDKITE_BRANCH:void 0,root:e.BUILDKITE_BUILD_CHECKOUT_PATH}}},qe={detect:({env:e})=>Boolean(e.CIRCLECI),configuration({env:e}){const t=e.CIRCLE_PR_NUMBER||ie(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}`}}},Ke="https://cirrus-ci.com",Ve={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:`${Ke}/build/${e.CIRRUS_BUILD_ID}`,job:e.CIRRUS_TASK_ID,jobUrl:`${Ke}/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}}},We={detect:({env:e})=>Boolean(e.CODEBUILD_BUILD_ID),configuration:({env:e,cwd:t})=>({name:"AWS CodeBuild",service:"codebuild",commit:$e({env:e,cwd:t}),build:e.CODEBUILD_BUILD_ID,branch:He({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})},Je={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}}},Xe={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}}},Qe=({env:e})=>{try{const t=e.GITHUB_EVENT_PATH?JSON.parse(a.readFileSync(e.GITHUB_EVENT_PATH,"utf-8")):void 0;if(t&&t.pull_request)return{branch:t.pull_request.base?ae(t.pull_request.base.ref):void 0,pr:t.pull_request.number}}catch{}return{pr:void 0,branch:void 0}},Ze={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=ae("pull_request_target"===e.GITHUB_EVENT_NAME?`refs/pull/${(e=>{const t=e.GITHUB_EVENT_PATH?JSON.parse(a.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?Qe({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}}},tt={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||$e({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}}},rt={detect:({env:e})=>"true"===e.NETLIFY,configuration({env:e}){const t="true"===e.PULL_REQUEST;return{name:"Netlify",service:"netlify",commit:e.COMMIT_REF,build:e.DEPLOY_ID,buildUrl:`https://app.netlify.com/sites/${e.SITE_NAME}/deploys/${e.DEPLOY_ID}`,branch:t?void 0:e.HEAD,pr:e.REVIEW_ID,isPr:t,prBranch:t?e.HEAD:void 0,slug:e.REPOSITORY_URL.match(/[^/:]+\/[^/]+?$/)[0],root:e.PWD}}},nt={detect:({env:e})=>Boolean(e.DISTELLI_APPNAME),configuration:({env:e})=>({name:"Puppet",service:"puppet",build:e.DISTELLI_BUILDNUM,buildUrl:e.DISTELLI_RELEASE,commit:e.DISTELLI_RELREVISION,branch:e.DISTELLI_RELBRANCH,root:e.DISTELLI_INSTALLHOME})},ot={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}}},st={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}}},it={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}}},at={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||$e({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}}},lt=F(oe()),dt={root:"teamcity.build.workingDir",branch:"teamcity.build.branch"},ut=e=>{try{return lt.default.of(e)}catch{return}},pt=({env:e,cwd:t})=>{const r=e.TEAMCITY_BUILD_PROPERTIES_FILE?ut(e.TEAMCITY_BUILD_PROPERTIES_FILE):void 0,n=r?r.get("teamcity.configuration.properties.file"):void 0,o=n?ut(n):n;return Object.fromEntries(Object.keys(dt).map(n=>[n,(r?r.get(dt[n]):void 0)||(o?o.get(dt[n]):void 0)||("branch"===n?He({env:e,cwd:t}):void 0)]))},ft={appveyor:se,azurePipelines:ce,bamboo:le,bitbucket:de,bitrise:ue,buddy:pe,buildkite:ze,circleci:qe,cirrus:Ve,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:We,codefresh:Je,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:Xe,github:Ze,gitlab:et,jenkins:tt,netlify:rt,puppet:nt,sail:ot,screwdriver:st,scrutinizer:it,semaphore:at,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,...pt({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:ae(e.JB_SPACE_GIT_BRANCH),slug:t&&r?`${t.toLowerCase()}/${r}`:void 0}}}},ht=class e{git;config;snapshotTreeHash;snapshotIndexPath;constructor(e){this.config=e,this.git=p.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=r.join(i.tmpdir(),`git-diff-tracker-${f.randomUUID()}.index`),await this.git.env("GIT_INDEX_FILE",this.snapshotIndexPath).add(["-A"]);const e=await this.git.env("GIT_INDEX_FILE",this.snapshotIndexPath).raw(["write-tree"]);this.snapshotTreeHash=e.trim()}async computeDiff(){return"local"===this.config.mode?this.computeLocalDiff():this.computeCloudDiff()}async computeLocalDiff(){if(!this.snapshotTreeHash)throw new Error("No snapshot captured. Call captureSnapshot() first.");const e=r.join(i.tmpdir(),`git-diff-tracker-${f.randomUUID()}.index`);try{await this.git.env("GIT_INDEX_FILE",e).add(["-A"]);const t=(await this.git.env("GIT_INDEX_FILE",e).raw(["write-tree"])).trim();return await this.git.raw(["diff-tree","-p","--no-color",this.snapshotTreeHash,t])}finally{await mt(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 mt(this.snapshotIndexPath),this.snapshotIndexPath=void 0),this.snapshotTreeHash=void 0}};async function mt(e){try{await h.unlink(e)}catch{}}var gt={bodySerializer:e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t)},_t=({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):yt({allowReserved:e,name:r,value:t})).join(s);return"label"===n||"matrix"===n?s+i:i},yt=({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)}`},Et=({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])=>yt({allowReserved:e,name:"deepObject"===n?`${r}[${t}]`:t,value:o})).join(i);return"label"===n||"matrix"===n?i+a:a},bt=/\{[^{}]+\}/g;function It(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 vt,Tt=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},wt=({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=_t({allowReserved:i.allowReserved,explode:!0,name:o,style:"form",value:s,...i.array});e&&n.push(e)}else if("object"==typeof s){const e=Et({allowReserved:i.allowReserved,explode:!0,name:o,style:"deepObject",value:s,...i.object});e&&n.push(e)}else{const e=yt({allowReserved:i.allowReserved,name:o,value:s});e&&n.push(e)}}return n.join("&")},Rt=(e,t)=>!!t&&!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`)),St=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(bt);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,_t({explode:n,name:o,style:s,value:i}));continue}if("object"==typeof i){r=r.replace(t,Et({explode:n,name:o,style:s,value:i,valueOnly:!0}));continue}if("matrix"===s){r=r.replace(t,`;${yt({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:wt(e.querySerializer),url:e.url}),Ct=(e,t)=>{const r={...e,...t};return r.baseUrl?.endsWith("/")&&(r.baseUrl=r.baseUrl.substring(0,r.baseUrl.length-1)),r.headers=At(e.headers,t.headers),r},xt=e=>{const t=[];return e.forEach((e,r)=>{t.push([r,e])}),t},At=(...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},Ut=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}},Pt=wt({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Lt={"Content-Type":"application/json"},Ot=(e={})=>({...gt,headers:Lt,parseAs:"auto",querySerializer:Pt,...e}),Bt=(e={})=>{let t=Ct(Ot(),e);const r=()=>({...t}),n={error:new Ut,request:new Ut,response:new Ut},o=async e=>{const r={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:At(t.headers,e.headers),serializedBody:void 0};return r.security&&await(async({security:e,...t})=>{for(const r of e){if(Rt(t,r.name))continue;const e=await Tt(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:St(r)}},s=async e=>{const{opts:t,url:r}=await o(e),s={redirect:"follow",...t,body:It(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 m="";const g=()=>{try{f.cancel()}catch{}};h.addEventListener("abort",g);try{for(;;){const{done:e,value:t}=await f.read();if(e)break;m+=t;const s=m.split("\n\n");m=s.pop()??"";for(const e of s){const t=e.split("\n"),s=[];let i,a;for(const e of t)if(e.startsWith("data:"))s.push(e.replace(/^data:\s*/,""));else if(e.startsWith("event:"))i=e.replace(/^event:\s*/,"");else if(e.startsWith("id:"))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",g),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:St,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=Ct(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")}},Nt=Bt(Ot({baseUrl:"https://api.stably.ai"})),Dt="x-stably-org-id",jt="4.3.0",kt=process.env.STABLY_API_URL||"https://api.stably.ai",Mt=process.env.AUTH_URL||"https://auth.stably.ai",$t=process.env.AUTH_CLIENT_ID||"288007877071cce81f269428ea78653a",Ht=process.env.AI_PROXY_URL||"https://ai-proxy.stably.ai",Gt="http://localhost:9876/auth/callback",Ft=()=>vt||(vt=Bt(Ot({baseUrl:kt,headers:{"X-STABLY-CLI-VERSION":jt,"X-STABLY-SOURCE":"cli"}}))),Yt=async(e,t)=>{const r=await(n={body:{accessToken:e,orgId:t},client:Ft()},(n.client??Nt).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},zt=_.z.object({org_id:_.z.string(),org_name:_.z.string()}),qt=_.z.object({email:_.z.string(),org_id_to_org_member_info:_.z.record(_.z.string(),zt).optional(),org_member_info:zt.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 Kt=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)},Vt=e=>{try{const t=qt.parse(Kt(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"}`)}},Wt=R.default.join(x.default.homedir(),".stably"),Jt=R.default.join(Wt,"auth.json"),Xt=".stably",Qt="project.json",Zt=L.default.object({accessToken:L.default.string(),expiresAt:L.default.number(),idToken:L.default.string().optional(),refreshToken:L.default.string()}),er=L.default.object({orgId:L.default.string(),orgName:L.default.string(),projectId:L.default.string(),projectName:L.default.string()}),tr=async()=>{try{const e=await h.readFile(Jt,"utf-8");return Zt.parse(JSON.parse(e))}catch{return}},rr=async e=>{await h.mkdir(Wt,{recursive:!0}),await h.writeFile(Jt,JSON.stringify(e,null,2),{mode:384})},nr=async()=>{try{await h.unlink(Jt)}catch{}},or=async e=>{let t=e;const{root:r}=R.default.parse(t);for(;t!==r;){const e=R.default.join(t,Xt);try{return await h.access(e),e}catch{t=R.default.dirname(t)}}},sr=async()=>{try{const e=await or(process.cwd());if(!e)return;const t=R.default.join(e,Qt),r=await h.readFile(t,"utf-8");return er.parse(JSON.parse(r))}catch{return}},ir=async()=>{try{const e=await or(process.cwd());e&&await h.unlink(R.default.join(e,Qt))}catch{}},ar=e=>Date.now()>=e.expiresAt-3e5,cr=async e=>{const t=new URLSearchParams({client_id:$t,grant_type:"refresh_token",refresh_token:e}),r=await fetch(`${Mt}/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}},lr=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`,dr=(e,t,r)=>{e.writeHead(t,{"Content-Type":"text/html"}),e.end(r)},ur=(e,t)=>{const r=new URLSearchParams({client_id:$t,code_challenge:e,code_challenge_method:"S256",redirect_uri:Gt,response_type:"code",state:t});return`${Mt}/propelauth/oauth/authorize?${r.toString()}`},pr=async e=>{const t=m.spinner();let r;t.start("Loading user info...");try{r=Vt(e.accessToken),t.stop(U.default.green(`✓ Logged in as ${U.default.cyan(r.email)}`))}catch(e){t.stop(U.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: ${U.default.cyan(e[0].name)}`),e[0];if(!process.stdin.isTTY)return m.log.info(`Auto-selecting organization: ${U.default.cyan(e[0].name)}`),e[0];const t=await m.select({message:"Select an organization",options:e.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 Yt(e.accessToken,n.id);o={accessToken:r.accessToken,expiresAt:Date.now()+1e3*r.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken},t.stop(U.default.green("✓ Credentials obtained"))}catch(e){t.stop(U.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:Ft(),path:{orgId:t}},(n.client??Nt).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(U.default.green("✓ Projects loaded"))}catch(e){r.stop(U.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 ${U.default.underline(U.default.cyan("https://app.stably.ai"))}`);if(1===n.length)return m.log.info(`Using project: ${U.default.cyan(n[0].name)}`),n[0];if(!process.stdin.isTTY)return m.log.info(`Auto-selecting project: ${U.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=R.default.join(process.cwd(),Xt),r=R.default.join(t,Qt);await h.mkdir(t,{recursive:!0}),await h.writeFile(r,JSON.stringify(e,null,2)),await(async e=>{const t=R.default.join(e,".gitignore"),r="# Stably CLI (only docs/ are tracked)\n.stably/*\n!.stably/docs/";try{const e=await h.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 h.writeFile(t,n)}else if(s.test(e)){const n=e.replace(s,`\n${r}\n`);await h.writeFile(t,n)}else await h.appendFile(t,`\n${r}\n`)}catch{await h.writeFile(t,`${r}\n`)}})(process.cwd())})({orgId:n.id,orgName:n.name,projectId:s.id,projectName:s.name}),m.log.info(U.default.dim("Linked this directory to your Stably project.")),{scopedTokens:o,success:!0}):(m.log.warn("Project selection cancelled."),{success:!1})},fr=async()=>{const e=await tr();if(e){if(!ar(e)){if(await sr())return void m.outro(U.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 pr(e);return void(t.success?(await rr(t.scopedTokens),m.outro(U.default.green("Setup complete! You can now use Stably CLI."))):m.outro(U.default.yellow("Setup incomplete. Run `stably login` to try again.")))}const t=m.spinner();t.start("Refreshing session...");try{const r=await cr(e.refreshToken);t.stop(U.default.green("✓ Session refreshed"));const n=await sr();if(n){t.start("Getting org credentials...");try{const e=await Yt(r.accessToken,n.orgId),o={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:r.idToken,refreshToken:r.refreshToken};await rr(o),t.stop(U.default.green("✓ Credentials obtained")),m.outro(U.default.green("Login successful"))}catch{await rr(r),t.stop(U.default.yellow("Using full credentials")),m.outro(U.default.green("Login successful"))}}else{const e=await pr(r);e.success?(await rr(e.scopedTokens),m.outro(U.default.green("Setup complete! You can now use Stably CLI."))):m.outro(U.default.yellow("Setup incomplete. Run `stably login` to try again."))}return}catch{t.stop(U.default.yellow("Session expired, proceeding with fresh login...")),await nr(),await ir()}}const{authorizeUrl:t,waitForCallback:r}=(()=>{const{authorizeUrl:e,codeVerifier:t,state:r}=(()=>{const e=P.default.randomBytes(32).toString("base64url"),t=(r=e,P.default.createHash("sha256").update(r).digest("base64url"));var r;const n=P.default.randomBytes(16).toString("base64url");return{authorizeUrl:ur(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(()=>{i.close(),e({error:"Login timed out",success:!1})},3e5),o=()=>{clearTimeout(r)},i=B.default.createServer((t,r)=>{const a=new s.URL(t.url||"","http://localhost:9876");if("/auth/callback"!==a.pathname)return r.writeHead(404),void r.end("Not found");const c=a.searchParams.get("code"),l=a.searchParams.get("state"),d=a.searchParams.get("error");return d?(dr(r,400,lr(d)),o(),i.close(),void e({error:d,success:!1})):c&&l?l!==n?(dr(r,400,lr("Invalid state parameter (possible CSRF attack)")),o(),i.close(),void e({error:"State mismatch",success:!1})):(dr(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(),i.close(),void e({code:c,state:l,success:!0})):(dr(r,400,lr("Missing code or state parameter")),o(),i.close(),void e({error:"Missing code or state parameter",success:!1}))});i.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."))}),i.listen(9876)}));var n;if(!r.success)throw new Error(r.error);return(async(e,t)=>{const r=new URLSearchParams({client_id:$t,code:e,code_verifier:t,grant_type:"authorization_code",redirect_uri:Gt}),n=await fetch(`${Mt}/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(U.default.dim("If browser doesn't open, visit:")),m.log.info(U.default.underline(U.default.cyan(t)));try{await O.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(U.default.green("✓ Authentication successful"))}catch(e){n.stop(U.default.red("✗ Authentication failed"));const t=e instanceof Error?e.message:"Unknown error";m.outro(U.default.red(`Login failed: ${t}`)),process.exit(1)}const i=await pr(o);i.success?(await rr(i.scopedTokens),m.outro(U.default.green("Setup complete! You can now use Stably CLI."))):(m.outro(U.default.yellow("Setup incomplete. Run `stably login` to try again.")),process.exit(1))},hr=()=>{const e=process.env.STABLY_API_KEY,t=process.env.STABLY_PROJECT_ID;if(e&&t)return{apiKey:e,projectId:t}},mr=async()=>{const e=await tr();if(e){if(!ar(e)){const t=await sr();if(t&&"full"===(e=>{try{const t=qt.parse(Kt(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))try{const r=await Yt(e.accessToken,t.orgId),n={accessToken:r.accessToken,expiresAt:Date.now()+1e3*r.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken};return await rr(n),n}catch{return e}return e}try{const t=await cr(e.refreshToken),r=await sr();if(r)try{const e=await Yt(t.accessToken,r.orgId),n={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:t.idToken,refreshToken:t.refreshToken};return await rr(n),n}catch{return await rr(t),t}return await rr(t),t}catch{return}}},gr=async(e={})=>{const t=hr();if(t)return{auth:t,type:"env"};let r=await mr(),n=r?await sr():void 0;const o=process.stdin.isTTY&&process.stdout.isTTY;if((!r||!n)&&e.autoLogin&&o){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(`${U.default.dim("Alternatively, set environment variables for an org API key:")}\n${U.default.dim(" STABLY_API_KEY=... STABLY_PROJECT_ID=... stably")}\n`),process.stdout.write("\n");const e=g.createInterface({input:process.stdin,output:process.stdout});try{await e.question(U.default.dim("Press Enter to continue... "))}finally{e.close()}await fr(),r=await mr(),n=r?await sr():void 0}return r||(m.outro(U.default.red("You are not logged in. Run `stably login` to authenticate.")),process.exit(1)),n||(m.outro(U.default.red("You haven't selected an organization and project. Run `stably login` to complete setup.")),process.exit(1)),{auth:{accessToken:r.accessToken,context:n},type:"oauth"}},_r=e=>e?{...process.env,...e}:process.env,yr=async()=>{const e=process.env.STABLY_API_KEY,t=process.env.STABLY_PROJECT_ID;if(e&&t)return{STABLY_API_KEY:e,STABLY_PROJECT_ID:t};const r=await(async()=>{const e=hr();if(e)return{auth:e,type:"env"};const t=await mr(),r=t?await sr():void 0;return t&&r?{auth:{accessToken:t.accessToken,context:r},type:"oauth"}:void 0})();if(!r)return;const n=t??(e=>"env"===e.type?e.auth.projectId:e.auth.context.projectId)(r);if(!n)return;const o=e??("env"===r.type?r.auth.apiKey:await(async(e,t)=>{try{return(await(async({accessToken:e,projectId:t})=>{const r=await(n={auth:e,client:Ft(),path:{projectId:t}},(n.client??Nt).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/api-key",...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 project");if(r.error)throw new Error(`Failed to get API key: ${r.response.status}`);return r.data})({accessToken:e,projectId:t})).apiKey}catch{return e}})(r.auth.accessToken,n));return o?{STABLY_API_KEY:o,STABLY_PROJECT_ID:n}:void 0},Er=e=>e?{[Dt]:e}:void 0,br=_.z.object({context:_.z.string().min(1),autohealReportUrl:_.z.string()}),Ir=e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"text"===t.type&&"string"==typeof t.text},vr=e=>null!=e&&"object"==typeof e&&"tool_response"in e,Tr=e=>{if(!e||"object"!=typeof e)return;const t=e;return Array.isArray(t.tool_response)?t.tool_response:void 0},wr=e=>{const t=Tr(e);if(t)return t.filter(Ir).map(e=>e.text).join("\n")||void 0},Rr=/\u001b\[[0-9;]*m/g,Sr=e=>e.replace(Rr,""),Cr=/\$\{process\.env\.([A-Z_][A-Z0-9_]*)\}/g;function xr({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(Cr,(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 Ar({onResult:e}){return async t=>{if(!vr(t))return{decision:"approve"};const r=wr(t);if(!r)return{decision:"approve"};const n=function(e){const t=Sr(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 Ur({onResult:e}){return async t=>{if(!vr(t))return{decision:"approve"};const r=wr(t);if(!r)return{decision:"approve"};const n=function(e){const t=Sr(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 Pr=/\.(spec|test)\.(ts|tsx|js|jsx|mts|mjs)$/;function Lr({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&&Pr.test(n)&&e(n),{decision:"approve"}}}var Or=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()})}},Br=10240,Nr=async({defaultContent:e,fileName:t,filePath:r})=>{try{const e=(await h.stat(r)).size,n=await h.readFile(r,"utf-8"),o=Buffer.byteLength(n,"utf-8");if(o<=Br)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<=Br?s:s.slice(0,Br)+`\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}},Dr=async({defaultContent:e,dirName:t,dirPath:r})=>{try{const e=await h.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}},jr=[".ts",".js",".mts",".mjs",".cts",".cjs"];function kr(e){const t=r.resolve(e);if(a.existsSync(t))for(const e of jr){const n=r.join(t,`playwright.config${e}`);if(a.existsSync(n))return n}}var Mr=["tests","e2e","__tests__","test"];function $r(e){try{return a.existsSync(e)&&a.statSync(e).isDirectory()}catch{return!1}}function Hr(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(U.default.dim(`Using output directory: ${e} (from ${r})`))}var Gr=["mcp__playwright-test__","mcp__auto-heal-report__","mcp__test-doc-sync__","mcp__stably-agent-control__"],Fr=["planner_","generator_"],Yr={"mcp__stably-agent-control__restart_mcp_servers":"Restarting Browser Tools"},zr=(e,t)=>{const r=t.find(t=>e.startsWith(t));return r?e.slice(r.length):e},qr=e=>{const t=Yr[e];if(t)return t;const r=zr(e,Gr);return zr(r,Fr).split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")},Kr=(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},Vr=v.z.object({bucket:v.z.string(),key:v.z.string()}),Wr=v.z.object({diffBucketPath:Vr,expiresInSeconds:v.z.number(),key:v.z.string(),uploadUrl:v.z.string()}),Jr=["test","bug","other"],Xr={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."},Qr=e=>Xr[e],{zSuiteAutoHealReport:Zr}=function(e){const t=e.enum(Jr),r=["Classification of the root cause:","",`- test: ${Qr("test")}`,`- bug: ${Qr("bug")}`,`- other: ${Qr("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),en=({authHeader:e,diffTracker:t,orgId:r,runId:n})=>l.createSdkMcpServer({name:"auto-heal-report",tools:[l.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:Zr},async({report:o})=>{const s=await t.computeDiff(),i=Zr.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:Ft(),headers:Er(t),path:{runId:n}},(s.client??Nt).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:Ft(),headers:Er(r),path:{runId:n}},(s.client??Nt).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=Wr.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"}),tn=({onComplete:e})=>l.createSdkMcpServer({name:"session-control",tools:[l.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}`})]}),rn=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]"),nn=(e,t)=>({message:rn(e),status:t?.status,statusText:t?.statusText}),on=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"]),sn=["Bash","Read","Write","Edit","Glob","Grep"],an=["mcp__playwright-test"],cn=["Bash","Read","Write","Edit","Glob","Grep","mcp__session-control"],ln=e=>{if("EPIPE"!==e.code)throw e},dn=async e=>{process.stdout.on("error",ln),process.stderr.on("error",ln);const t=e=>{if("EPIPE"!==e.code)throw e};process.on("uncaughtException",t);const n=await gr({autoLogin:"chat"===e.mode||"init"===e.mode}),o=(e=>"env"===e.type?e.auth.apiKey:e.auth.accessToken)(n),s="oauth"===n.type?n.auth.context.orgId:void 0,i=R.default.resolve(process.cwd()),a=R.default.join(i,".env"),c=A.default.existsSync(a)&&A.default.statSync(a).isFile()?d.parse(A.default.readFileSync(a,"utf8")):{},u="chat"!==e.mode&&"init"!==e.mode,p="chat"===e.mode||"init"===e.mode?new Or:void 0,f="chat"===e.mode?e.getHelpText:void 0,m={log:[],promptDisplay:"chat"===e.mode?"Ask Stably to build tests for you":"init"===e.mode?"Setting up Playwright and Stably SDK":"fix"===e.mode?"Fixing broken tests":(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt)||"<empty prompt>",status:"running"};let g,_=u,y=!1;const E={current:e=>{}},v={current:async()=>{}},{addTool:T,addToolResult:w,appendText:S,appendUserMessage:C,cleanup:x,setExiting:P,setStatus:L,showPermissionPrompt:O}=await(async(e,t)=>{const{Box:r,Static:n,Text:o,render:s,useInput:i}=await import("ink"),a=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],c=()=>I.jsx(o,{inverse:!0,children:" "}),l=(({Box:e,Text:t,useInput:r},n)=>function({onChoice:o,prompt:s}){const[i,a]=b.useState(0),[c,l]=b.useState(!1),[d,u]=b.useState(""),p=[{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(c)return t.return?void o("deny_with_message",d||"User denied this action"):t.escape?(l(!1),void u("")):t.backspace||t.delete?void u(e=>e.slice(0,-1)):void(t.ctrl||t.meta||u(t=>`${t}${e}`));if(t.upArrow)return void a(e=>e>0?e-1:p.length-1);if(t.downArrow)return void a(e=>e<p.length-1?e+1:0);if(t.return){const e=p[i];return"deny_with_message"===e.value?void l(!0):void o(e.value)}const r=parseInt(e,10);if(r>=1&&r<=p.length){const e=p[r-1];if("deny_with_message"===e.value)return void l(!0);o(e.value)}});const f=qr(s.toolName),h=Kr(s.toolName,s.input);return I.jsxs(e,{borderColor:"yellow",borderStyle:"round",flexDirection:"column",marginTop:1,paddingX:1,paddingY:0,children:[I.jsx(t,{bold:!0,color:"yellow",children:"Permission Required"}),I.jsxs(e,{flexDirection:"column",marginTop:1,children:[I.jsx(t,{color:"magenta",children:f}),null!=h&&I.jsxs(t,{color:"gray",children:[" ",h]})]}),null!=s.decisionReason&&I.jsx(e,{marginTop:1,children:I.jsxs(t,{color:"gray",children:["Reason: ",s.decisionReason]})}),c?I.jsxs(e,{flexDirection:"column",marginTop:1,children:[I.jsx(t,{color:"gray",children:"Enter message for AI (press Enter to submit, Esc to cancel):"}),I.jsxs(t,{children:[I.jsx(t,{color:"yellow",children:">"})," ",d,I.jsx(n,{})]})]}):I.jsxs(e,{flexDirection:"column",marginTop:1,children:[I.jsx(t,{color:"gray",children:"Use ↑↓ arrows or number keys to select:"}),p.map((e,r)=>I.jsx(t,{children:I.jsxs(t,{color:r===i?"cyan":void 0,children:[r===i?"❯":" "," ",r+1,". ",e.label]})},e.value))]})]})})({Box:r,Text:o,useInput:i},c),d=(({Cursor:e,inkComponents:{Box:t,Static:r,Text:n,useInput:o},PermissionPrompt:s,Spinner:i})=>{const a=e=>"tool"===e.kind?I.jsxs(n,{color:"magenta",children:["• ",e.content]},e.id):"tool_result"===e.kind?I.jsx(n,{color:"gray",children:e.content},e.id):"user"===e.kind?I.jsxs(n,{color:"cyan",children:["You: ",e.content]},e.id):I.jsx(n,{children:e.content},e.id),c="vscode"===process.env.TERM_PROGRAM;return function({onExit:l,onPermissionChoice:d,onSend:u,showSpinnerImmediately:p,state:f}){const[h,m]=b.useState(""),g=b.useRef(!1),_=b.useRef(void 0),[y,E]=b.useState(!1),v=b.useRef(0),T=f.log.at(-1),w="text"===T?.kind&&"running"===f.status,R=c?0:w?f.log.length-1:f.log.length;b.useEffect(()=>{f.log.length<v.current&&(v.current=0),R>v.current&&(v.current=R)},[f.log.length,R]);const S=f.log.slice(0,v.current),C=f.log.slice(v.current),x=!!f.permissionPrompt,A=b.useCallback(()=>{g.current?(_.current&&clearTimeout(_.current),l?.(),process.exit(0)):(g.current=!0,E(!0),_.current=setTimeout(()=>{g.current=!1,E(!1)},2e3))},[l]);o((e,t)=>{t.ctrl&&"c"===e&&A()},{isActive:!0}),o((e,t)=>{if(!t.ctrl||"c"!==e){if(t.return){const e=h.trim();return e&&u?.(e),void m("")}t.backspace||t.delete?m(e=>e.slice(0,-1)):m(t=>`${t}${e}`)}},{isActive:!!u&&!x});const U=b.useMemo(()=>"running"===f.status?I.jsx(i,{label:"Working"}):"success"!==f.status?I.jsx(n,{color:"red",children:"✖ Failed"}):void 0,[f.status]),P=!(p||!u||"running"!==f.status||0!==f.log.length||f.resultText||f.errorText),L="running"===f.status&&!P||f.log.length>0||f.resultText||f.errorText||"running"!==f.status;return I.jsxs(t,{flexDirection:"column",children:[I.jsx(r,{items:["header"],children:()=>I.jsxs(t,{flexDirection:"column",flexShrink:0,children:[I.jsx(n,{color:"cyan",bold:!0,children:"Stably Agent"}),I.jsx(t,{flexDirection:"column",marginTop:1,children:I.jsx(n,{color:"gray",children:f.promptDisplay})})]},"header")}),S.length>0&&I.jsx(r,{items:S,children:e=>a(e)}),C.length>0&&I.jsx(t,{flexDirection:"column",children:C.map(e=>a(e))}),"error"===f.status&&f.errorText&&I.jsx(t,{marginTop:1,children:I.jsx(n,{color:"red",children:f.errorText})}),"success"===f.status&&f.resultText&&I.jsx(t,{marginTop:1,children:I.jsx(n,{children:f.resultText})}),L&&I.jsx(t,{flexDirection:"column",flexShrink:0,marginTop:1,children:U}),null!=f.permissionPrompt&&null!=d&&I.jsx(s,{onChoice:d,prompt:f.permissionPrompt}),null!=u&&null==f.permissionPrompt&&!f.isExiting&&I.jsxs(t,{borderColor:"gray",borderStyle:"round",flexDirection:"column",flexShrink:0,marginTop:1,paddingX:1,paddingY:0,children:[I.jsx(n,{color:"gray",children:"Type a message and press Enter. Press Ctrl+C to exit."}),I.jsxs(n,{children:[I.jsx(n,{color:"yellow",children:">"})," ",h,I.jsx(e,{})]})]}),y&&I.jsx(t,{marginTop:1,children:I.jsx(n,{color:"yellow",children:"Press Ctrl+C again to exit"})})]})}})({Cursor:c,inkComponents:{Box:r,Static:n,Text:o,useInput:i},PermissionPrompt:l,Spinner:({label:e})=>{const[t,r]=b.useState(0);return b.useEffect(()=>{const e=setInterval(()=>r(e=>(e+1)%a.length),80);return()=>clearInterval(e)},[]),I.jsxs(o,{color:"yellow",children:[a[t]," ",e]})}});let u=e;const p={current:(e,t)=>{}},f=s(I.jsx(d,{onExit:t?.onExit,onPermissionChoice:(e,t)=>p.current(e,t),onSend:t?.onSend,showSpinnerImmediately:t?.showSpinnerImmediately,state:u}),{exitOnCtrlC:!1}),h=()=>{u={...u},f.rerender(I.jsx(d,{onExit:t?.onExit,onPermissionChoice:(e,t)=>p.current(e,t),onSend:t?.onSend,showSpinnerImmediately:t?.showSpinnerImmediately,state:u}))},m=({text:e})=>{e&&(u.log=[...u.log,{content:e,id:u.log.length,kind:"user"}],h())};return{addTool:({rawName:e,toolInput:t})=>{const r=qr(e),n=Kr(e,t),o=n?`${r} (${n})`:r;u.log=[...u.log,{content:o,id:u.log.length,kind:"tool"}],h()},addToolResult:({message:e})=>{u.log=[...u.log,{content:e,id:u.log.length,kind:"tool_result"}],h()},appendText:({text:e})=>{if(!e)return;const t=u.log.at(-1),r=t&&"text"===t.kind?e:e.replace(/^\s*\n+/,"");t&&"text"===t.kind?u.log=[...u.log.slice(0,-1),{...t,content:`${t.content}${r}`}]:u.log=[...u.log,{content:r,id:u.log.length,kind:"text"}],h()},appendUserMessage:m,cleanup:async()=>{f.unmount(),await f.waitUntilExit()},setExiting:()=>{u.isExiting=!0,h()},setStatus:({error:e,result:t,status:r})=>{u.errorText=e,u.resultText=t,u.status=r,h()},showPermissionPrompt:e=>new Promise(t=>{p.current=(r,n)=>{if(u.permissionPrompt=void 0,h(),"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})}},u.permissionPrompt={...e,resolve:t},h()})}})(m,"chat"===e.mode||"init"===e.mode?{onExit:()=>{v.current()},onSend:e=>E.current(e),showSpinnerImmediately:"init"===e.mode}:void 0);let B=m.status;const N=({error:e,result:t,status:r})=>{B=r,L({error:e,result:t,status:r})};let D;E.current=e=>{if("/help"===e.trim()){_&&p&&(y=!0,g?.interrupt?.(),p.allowNextTurn(),_=!1),"running"===B&&N({status:"success"}),C({text:e});const t=f?.();return void S({text:t??"Help is not available in this session."})}p&&(_&&(y=!0,g?.interrupt?.(),p.allowNextTurn(),_=!1),N({status:"running"}),C({text:e}),p.pushText(e),_=!0)};const j=[];let k;const M=await(async()=>{if("single"===e.mode){const t=Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt,n=await async function(e,t){const n=r.resolve(e);if(t){const e=r.resolve(n,t);return Hr(e,"output-flag"),{path:e,source:"output-flag"}}const o=kr(n);if(o){const e=await async function(e){try{const t=(await h.readFile(e,"utf-8")).match(/testDir:\s*['"]([^'"]+)['"]/);return t?.[1]}catch{return}}(o);if(e){const t=r.resolve(r.dirname(o),e);if($r(t))return Hr(t,"playwright.config.ts"),{path:t,source:"playwright.config.ts"}}}for(const e of Mr){const t=r.join(n,e);if($r(t))return Hr(t,"auto-detected"),{path:t,source:"auto-detected"}}return Hr(n,"cwd-fallback"),{path:n,source:"cwd-fallback"}}(i,e.outputDir);return k=n.path,`${t}\n\n[Output directory: ${k}]`}if("fix"===e.mode)try{const{context:t,autohealReportUrl:r}=await(async({authHeader:e,orgId:t,runId:r})=>{const n=await(o={auth:e,client:Ft(),headers:Er(t),path:{runId:r}},(o.client??Nt).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-context",...o}));var o;if(404===n.response.status)throw new Error(`Run ID "${r}" was not found.`);if(401===n.response.status)throw new Error("Unauthorized: failed to fetch autoheal context (401).");if(422===n.response.status)throw new Error(n.error?.error??"Failed to fetch autoheal context (422).");if(!n.error){const e=br.safeParse(n.data);if(e.success)return{context:e.data.context,autohealReportUrl:e.data.autohealReportUrl};throw new Error("Autoheal context response missing or invalid context.")}throw new Error("Failed to fetch autoheal context")})({authHeader:o,orgId:s,runId:e.runId});return D=r,t}catch(e){const t=e instanceof Error?e.message:"Failed to fetch autoheal context.";N({error:t,status:"error"}),await x(),process.exit(1)}return"init"===e.mode?"Please analyze this project and set up Playwright with the Stably SDK. Check for existing configurations and install the necessary dependencies.":""})(),$=await async function(e){const t=R.default.resolve(e),r=R.default.join(t,"tests"),n=R.default.join(r,"helpers"),o=R.default.join(r,"assets"),s=R.default.join(t,"playwright.config.ts"),i=R.default.join(r,"seed.spec.ts"),[a,c,l,d,u,p]=await Promise.all([Dr({defaultContent:"Unable to read directory",dirName:"working directory",dirPath:t}),Dr({defaultContent:"Unable to read directory",dirName:"tests directory",dirPath:r}),Dr({defaultContent:"Directory does not exist yet",dirName:"helpers directory",dirPath:n}),Dr({defaultContent:"Directory does not exist yet",dirName:"assets directory",dirPath:o}),Nr({defaultContent:"File does not exist or could not be read",fileName:"playwright.config.ts",filePath:s}),Nr({defaultContent:"File does not exist or could not be read",fileName:"seed.spec.ts",filePath:i})]);return{absolutePath:t,directories:{assets:d,helpers:l,root:a,tests:c},files:{playwrightConfig:u,seedSpec:p}}}(i),H=await(async({allowedEnvVars:e,mode:t,workspaceInfo:r,authHeader:n})=>{const o=Ft(),s=await(i={client:o,auth:n,body:{mode:t,workspaceInfo:r,allowedEnvVars:e}},(i.client??Nt).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/prompts/system",...i,headers:{"Content-Type":"application/json",...i.headers}}));var i;if(s.error)throw new Error(`Failed to fetch system prompt: ${JSON.stringify(s.error)}`);return s.data.systemPrompt})({allowedEnvVars:Object.keys(c),mode:e.mode,workspaceInfo:$,authHeader:o}),G=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??Nt).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:nn(e,a)}}return i.data?{key:i.data.key}:{error:nn("No data in response",a)}}catch(e){const t=e instanceof Error?e.message:"Unknown error";return{error:nn(t)}}var s}({auth:o,client:Ft(),source:"cli"}),F=G.key;if(!F){const e=G.error?.message;N({error:e?`Unable to make AI calls: ${e}`:"Unable to make AI calls. Check if you are authenticated.",status:"error"}),await x(),process.exit(1)}const Y=Object.fromEntries(Object.entries(process.env).filter(([e])=>!on.has(e))),z=await yr(),q=z?Object.fromEntries(Object.entries(_r(z)).filter(e=>null!=e[1])):void 0,K="init"===e.mode,V="fix"===e.mode,W="chat"===e.mode,J=V?ht.createLocal({workingDir:i}):void 0;J&&await J.captureSnapshot();const X=K?cn:[...sn,...V?["mcp__auto-heal-report"]:[]],Q=K?cn:an,Z=K?{"session-control":tn({onComplete:()=>{N({status:"success"}),P(),p?.finish(),process.exit(0)}})}:V&&J?{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:q},"auto-heal-report":en({authHeader:o,diffTracker:J,orgId:s,runId:e.runId})}:{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:q}},ee="single"===e.mode,te=K?[]:[{hooks:[async e=>{const t=Tr(e);if(!t)return{decision:"approve"};let r=!1;const n=t.map(e=>Ir(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:[Ar({onResult:e=>w({message:e})})]},{matcher:"mcp__playwright-test__test_debug",hooks:[Ur({onResult:e=>w({message:e})})]},...ee?[{matcher:"Write",hooks:[Lr({onFileCreated:e=>j.push(e)})]}]:[]],re=K?[]:[{matcher:"mcp__playwright-test__browser_type",hooks:[xr({envVars:c})]}];g=l.query({options:{tools:X,allowedTools:Q,canUseTool:async(e,t,{suggestions:r,decisionReason:n})=>W||K?O({decisionReason:n,input:t,suggestions:r,toolName:e}):{behavior:"allow",updatedInput:t},cwd:i,env:{...Y,ANTHROPIC_API_KEY:F,ANTHROPIC_BASE_URL:Ht},hooks:{PostToolUse:te,PreToolUse:re},includePartialMessages:!0,mcpServers:Z,model:"claude-opus-4-5-20251101",permissionMode:"default",systemPrompt:H},prompt:p??M}),"init"===e.mode&&p&&p.pushText(M),v.current=async()=>{P();try{await(g?.interrupt?.())}catch{}p?.finish(),x()};try{for await(const e of g){if("stream_event"===e.type){const{event:t}=e;if("content_block_delta"===t?.type){const{delta:e}=t;"text_delta"===e?.type&&e.text&&S({text:e.text})}"message_stop"===t?.type&&p&&p.allowNextTurn();continue}if("assistant"===e.type){const{content:t}=e.message??{};if(Array.isArray(t))for(const e of t)if("tool_use"===e?.type){if(e.name.startsWith("mcp__session-control__"))continue;T({rawName:e.name,toolInput:e.input})}continue}if("result"!==e.type);else{if(u){if("success"===e.subtype){if(ee&&j.length>0){U.default.green("Created files:");for(const e of j)U.default.green(`- ${e}`)}const e=D?U.default.cyan(`📊 View Autoheal Report:\n ${U.default.cyan(U.default.bold(U.default.underline(D)))}`):void 0;N({status:"success",result:e})}else y||(N({error:"Run failed.",status:"error"}),process.exitCode=1);y=!1;break}"success"!==e.subtype?y||(N({error:"Run failed.",status:"error"}),process.exitCode=1):N({status:"success"}),_=!1,y=!1,p?.allowNextTurn()}}}catch(e){y||(N({error:`Agent encountered an error: ${e}`,status:"error"}),process.exitCode=1)}finally{_=!1,y=!1,process.off("uncaughtException",t),p?.finish(),await(J?.cleanup()),await x()}},un=[{args:["--trace=on"],description:"Run Playwright tests",name:"test"},{args:[],description:"Install browser dependencies",name:"install"}];function pn(e){const t=r.join(e,"package.json");let n;try{n=a.readFileSync(t,"utf-8")}catch{return}try{return JSON.parse(n)}catch{return}}function fn(e){const t=[["npm","package-lock.json"],["pnpm","pnpm-lock.yaml"],["yarn","yarn.lock"]];for(const[n,o]of t)if(a.existsSync(r.join(e,o)))return n}var hn=process.argv.findIndex(e=>"-C"===e||"--cwd"===e);-1!==hn&&process.argv[hn+1]&&(process.chdir(process.argv[hn+1]),process.argv.splice(hn,2));var mn=new e.Command;mn.name("stably").description("AI-assisted Playwright testing CLI").version(jt),mn.enablePositionalOptions(),mn.showHelpAfterError(),mn.exitOverride();var gn=[];mn.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>{gn.push(e)}});var _n=()=>{const e=mn.helpInformation().trimEnd();return e?`${e}\n`:""},yn=(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},En=()=>{process.stdout.write(_n())},bn=e=>{process.stdout.write((e=>{const t=e.helpInformation().trimEnd();return t?`${t}\n`:""})(e))};mn.command("help").description("Show help for a command or subcommand").argument("[command...]","Command path to show help for (e.g. create test)").action(e=>{if(!e||0===e.length)return void En();const t=yn(mn,e);if(!t)return process.stderr.write(`Unknown command: ${e.join(" ")}\n`),En(),void(process.exitCode=1);bn(t)}),mn.action(()=>dn({mode:"chat",getHelpText:_n})),mn.command("login").description("Authenticate with Stably in your browser").action(fr),mn.command("logout").description("Clear stored Stably credentials").action(async()=>{const e=await tr();if(!e)return void m.outro(U.default.yellow("You are not logged in."));const t=m.spinner();t.start("Logging out..."),await(async e=>{try{await fetch(`${Mt}/api/backend/v1/logout`,{body:JSON.stringify({refresh_token:e}),headers:{"Content-Type":"application/json"},method:"POST"})}catch{}})(e.refreshToken),await nr(),await ir(),t.stop(U.default.green("✓ Logged out")),m.outro(U.default.green("You have been logged out successfully."))}),mn.command("whoami").description("Show auth status and current project").action(async()=>{m.log.info(`${U.default.bold("CLI Version:")} ${U.default.cyan(jt)}`);const e=hr();if(e)return m.log.info(U.default.dim("Authentication: Environment variables")),m.log.info(` ${U.default.bold("API Key:")} ${U.default.cyan(e.apiKey.slice(0,8))}...`),m.log.info(` ${U.default.bold("Project ID:")} ${U.default.cyan(e.projectId)}`),void m.outro(U.default.green("Authenticated via environment variables"));const t=await tr();if(!t)return void m.outro(U.default.yellow("Not logged in. Run `stably login` to authenticate."));let r;try{r=Vt(t.accessToken).email}catch{r=void 0}const n=await sr();if(!n)return m.log.info(U.default.dim("Authentication: OAuth (not linked to a project)")),r&&m.log.info(` ${U.default.bold("Email:")} ${U.default.cyan(r)}`),void m.outro(U.default.yellow("Logged in but this directory is not linked to a project. Run `stably login` to link."));const o=await(async()=>or(process.cwd()))(),s=o?R.default.dirname(o):process.cwd(),i=R.default.relative(process.cwd(),s)||".";m.log.info(U.default.dim("Authentication: OAuth")),r&&m.log.info(` ${U.default.bold("Email:")} ${U.default.cyan(r)}`),m.log.info(` ${U.default.bold("Organization:")} ${U.default.cyan(n.orgName)}`),m.log.info(` ${U.default.bold("Project:")} ${U.default.cyan(n.projectName)}`),m.log.info(` ${U.default.bold("Linked at:")} ${U.default.dim(i)}`),m.outro(U.default.green("Authenticated"))}),mn.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 gr(),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 T.startTunnel(`http://localhost:${e.port}`,{subdomain:r});n.stop(`Your local environment is available at: ${U.default.underline(U.default.cyan(o.url))}`)});var In=mn.command("create").description("Generate a Playwright test from a prompt").argument("[prompt...]","Prompt describing the test to generate").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 0===r.length?(process.stderr.write("Error: missing required argument: prompt\n"),bn(In),void(process.exitCode=1)):dn({mode:"single",prompt:r,outputDir:t.output})});In.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)=>dn({mode:"single",prompt:e,outputDir:t.output})),mn.command("fix").description("Fix failing Playwright tests using debug context").argument("[runId]","Run ID for the failing test suite (defaults to CI's unique runId if available)").action(e=>{const t=e??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(ft))if(ft[r].detect({env:e,cwd:t}))return{isCi:!0,...ft[r].configuration({env:e,cwd:t})};return{isCi:Boolean(e.CI),...(r={env:e,cwd:t},{commit:$e(r),branch:He(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: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}();return t||(process.stderr.write("Run ID is required. Provide <runId>.\n"),process.exit(1)),dn({mode:"fix",runId:t})}),mn.command("init").description("Initialize Playwright and Stably SDK in your project").action(()=>dn({mode:"init"})),un.forEach(({args:e,description:t,name:o})=>{mn.command(o).description(t).helpOption(!1).helpCommand(!1).allowUnknownOption(!0).allowExcessArguments(!0).passThroughOptions().action(()=>async function({overrideArgs:e,subcommand:t}){const o=process.argv,s=o.findIndex((e,r)=>r>1&&e===t),c=-1===s?[]:o.slice(s+1),l="--"===c[0]?c.slice(1):c,d=e??[],u=new Set(d.map(e=>{const[t]=e.split("=");return t})),p=l.filter(e=>{const[t]=e.split("=");return!u.has(t)}),h=[t,...d,...p],m="test"===t?await yr():void 0,g="test"===t?function({forwardedArgs:e,hasCredentials:t}){if(!t)return console.warn("[33m⚠️ Stably credentials not found. Test results will not be reported to Stably.[0m"),console.warn("[33m To enable reporting, either:[0m"),console.warn("[33m • Run `npx stably login` to authenticate[0m"),void console.warn("[33m • Set STABLY_API_KEY and STABLY_PROJECT_ID environment variables[0m\n");const n=process.cwd(),o=e=>{const t=function(e){let t=r.resolve(e);for(;;){if([r.join(t,"node_modules","@stablyai","playwright-test"),r.join(t,"node_modules",".pnpm","@stablyai+playwright-test")].some(e=>a.existsSync(e)))return!0;const e=r.dirname(t);if(e===t)return!1;t=e}}(e);return t||(console.warn("[33m⚠️ @stablyai/playwright-test is not installed. Stably reporter will not be injected.[0m"),console.warn("[33m Install it with: npm install @stablyai/playwright-test[0m"),console.warn("[33m Reference: https://docs.stably.ai/getting-started/sdk-setup-guide[0m\n")),t},s=e=>{try{return function({baseConfigPath:e}){const t=r.join(i.tmpdir(),".stably-playwright-wrapper.<id>.config.mts".replaceAll("<id>",f.randomUUID())),n=a.realpathSync(r.dirname(t)),o=r.resolve(e),s=r.relative(n,o).replace(/\\/g,"/"),c=r.dirname(o).replace(/\\/g,"/"),l=`\n// Auto-generated wrapper config by Stably CLI\n// This file injects the Stably reporter and ensures trace is enabled\nimport { resolve, isAbsolute } from 'path';\nimport { createRequire } from 'module';\nimport baseConfig from '${s}';\n\n// Create a require function that resolves modules from the base config directory\n// This is needed because the wrapper is in /tmp but node_modules is in the project\nconst projectRequire = createRequire('${c}/package.json');\n\n// Import defineConfig from @stablyai/playwright-test using projectRequire\n// This ensures the module is resolved from the project's node_modules, not /tmp\nconst { defineConfig } = projectRequire('@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// Dynamically import stablyReporter to handle cases where it's not installed\n// Use projectRequire to resolve from the project's node_modules, not /tmp\nlet stablyReporter: ((options?: { apiKey?: string; projectId?: string; notificationConfigs?: ProjectNotificationConfig[] }) => [string, unknown]) | undefined;\ntry {\n stablyReporter = projectRequire('@stablyai/playwright-test').stablyReporter;\n} catch {\n // @stablyai/playwright-test not installed - reporter injection will be skipped\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 hasStablyReporter = (reporters: unknown): boolean => {\n if (!Array.isArray(reporters)) return false;\n return reporters.some((reporter) => {\n if (typeof reporter === 'string') {\n return reporter.includes('stablyai') || reporter.includes('stably');\n }\n if (Array.isArray(reporter) && typeof reporter[0] === 'string') {\n return reporter[0].includes('stablyai') || reporter[0].includes('stably');\n }\n return false;\n });\n};\n\nconst buildReporterList = () => {\n const existingReporters = baseConfig.reporter;\n\n // If stablyReporter is not available, just use existing reporters\n if (!stablyReporter) {\n return existingReporters;\n }\n\n // If already has stably reporter, don't add another\n if (hasStablyReporter(existingReporters)) {\n return existingReporters;\n }\n\n // Create the stably reporter entry with notification configs\n const [reporterModule, reporterOptions] = stablyReporter({\n apiKey: process.env.STABLY_API_KEY,\n projectId: process.env.STABLY_PROJECT_ID,\n notificationConfigs: extractNotificationConfigs(),\n });\n // Resolve to absolute path so Playwright can find it (pnpm strict mode)\n const reporterAbsolutePath = projectRequire.resolve(reporterModule);\n const stablyReporterEntry = [reporterAbsolutePath, reporterOptions];\n\n // Merge with existing reporters\n if (!existingReporters) {\n return [stablyReporterEntry];\n }\n\n if (Array.isArray(existingReporters)) {\n return [...existingReporters, stablyReporterEntry];\n }\n\n // Single reporter as string - convert to tuple format [name, {}]\n return [[existingReporters, {}], stablyReporterEntry];\n};\n\n// Resolve testDir relative to the base config directory, not the wrapper location\n// This ensures test paths are resolved correctly even though the wrapper is in /tmp\nconst baseConfigDir = '${c}';\nconst resolveTestDir = (testDir?: string): string => {\n if (!testDir) {\n // If no testDir in base config, default to the base config directory\n return baseConfigDir;\n }\n // If testDir is already absolute, use it as-is\n if (isAbsolute(testDir)) {\n return testDir;\n }\n // Otherwise, resolve it relative to the base config directory\n return resolve(baseConfigDir, testDir);\n};\n\nexport default defineConfig({\n ...baseConfig,\n testDir: resolveTestDir(baseConfig.testDir),\n use: {\n ...baseConfig.use,\n trace: 'on',\n },\n reporter: buildReporterList(),\n});\n`.trim();return a.existsSync(n)||a.mkdirSync(n,{recursive:!0}),a.writeFileSync(t,l,"utf-8"),t}({baseConfigPath:e})}catch{return void console.warn("[33m⚠️ Could not create Stably wrapper config. Reporter injection skipped.[0m")}};if(e.some(e=>"--config"===e||"-c"===e||e.startsWith("--config=")||e.startsWith("-c="))){const t=e.findIndex(e=>"--config"===e||"-c"===e);if(-1!==t&&e[t+1]){const i=r.resolve(n,e[t+1]);if(!o(r.dirname(i)))return;const a=s(i);if(!a)return;return e[t+1]=a,a}const i=e.findIndex(e=>e.startsWith("--config=")||e.startsWith("-c="));if(-1!==i){const t=r.resolve(n,e[i].split("=")[1]);if(!o(r.dirname(t)))return;const a=s(t);if(!a)return;const c=e[i].startsWith("--config=")?"--config=":"-c=";return e[i]=`${c}${a}`,a}}const c=kr(n);if(!c)return;if(!o(r.dirname(c)))return;const l=s(c);return l?(e.push("--config",l),l):void 0}({forwardedArgs:h,hasCredentials:null!=m}):void 0;!function(e,t={}){const o=function(e=process.cwd()){let t=r.resolve(e);for(;;){const e=pn(t);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=fn(t),n=r.join(t,"node_modules"),s=r.join(n,o);return{inNodeModules:a.existsSync(s),installed:!0,packageManager:e,packageName:o}}}const n=r.dirname(t);if(n===t)return{inNodeModules:!1,installed:!1,packageManager:void 0};t=n}}();o.installed||(console.error('Playwright is not installed. Please run "stably init" to install it.'),process.exit(1)),o.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:s}=o;s||(console.error("Playwright installation not found. Could not determine your package manager (tried pnpm, yarn, and npm)."),process.exit(1));const[i,...c]=function(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")}(s),l=[i,...c.slice(0,-1)].join(" "),d=_r(t.env),u=n.spawn(i,[...c,...e],{stdio:["inherit","pipe","pipe"],env:{...d,...process.env.CI?{}:{FORCE_COLOR:"1"}}}),p=(e,t)=>{let r=e.toString();for(const e of un)r=r.replaceAll(`${l} playwright ${e.name}`,`${l} stably ${e.name}`).replaceAll(`npx playwright ${e.name}`,`npx stably ${e.name}`);if("yarn"===s){const e=r.split("\n");e.length>0&&e[0].includes("/.bin/playwright")&&e.shift();const n=e.join("\n");return void t.write(n)}t.write(r)};u.stdout?.on("data",e=>{p(e,process.stdout)}),u.stderr?.on("data",e=>{p(e,process.stderr)}),u.on("close",e=>{t.onClose?.(),process.exit(e??0)});const f=e=>{t.onClose?.(),u.kill(e);const r="SIGINT"===e?130:143;process.exit(r)};process.on("SIGINT",f),process.on("SIGTERM",f)}(h,{env:m,onClose:()=>{var e;(e=g)&&a.existsSync(e)&&a.rmSync(e)}})}({overrideArgs:e,subcommand:o}))});var vn=()=>{0!==gn.length&&(process.stderr.write(gn.join("")),gn=[])};(async()=>{try{await mn.parseAsync(process.argv)}catch(e){if(!(e=>!!e&&"object"==typeof e&&"code"in e)(e))throw vn(),e;const t="number"==typeof e.exitCode?e.exitCode:1,r=process.argv.slice(2).find(e=>!e.startsWith("-")),n=!!r&&!!yn(mn,[r]);if(("commander.excessArguments"===e.code||"commander.unknownCommand"===e.code)&&r&&!n)return gn=[],process.stderr.write(`command '${r}' not found\n`),En(),void(process.exitCode=t);vn(),process.exitCode=t}})();
|
|
2
|
+
"use strict";var e=require("commander"),t=require("buffer"),r=require("path"),n=require("child_process"),o=require("process"),s=require("url"),i=require("os"),a=require("fs");require("timers/promises");var c=require("util"),l=require("@anthropic-ai/claude-agent-sdk"),d=require("dotenv"),u=require("picocolors"),p=require("simple-git"),f=require("crypto"),h=require("fs/promises"),m=require("@clack/prompts"),g=require("readline/promises"),_=require("zod"),y=require("open"),E=require("http"),b=require("react"),I=require("react/jsx-runtime"),w=require("zod/v3"),v=require("@stablyhq/runner-sdk");function T(e){return e&&e.__esModule?e:{default:e}}var R=T(r),S=T(n),C=T(o),A=T(i),x=T(a),U=T(u),P=T(f),L=T(_),O=T(y),B=T(E),N=Object.create,D=Object.defineProperty,j=Object.getOwnPropertyDescriptor,k=Object.getOwnPropertyNames,$=Object.getPrototypeOf,M=Object.prototype.hasOwnProperty,H=(e=>"undefined"!=typeof require?require:"undefined"!=typeof Proxy?new Proxy(e,{get:(e,t)=>("undefined"!=typeof require?require:e)[t]}):e)(function(e){if("undefined"!=typeof require)return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),G=(e,t)=>function(){return t||(0,e[k(e)[0]])((t={exports:{}}).exports,t),t.exports},F=(e,t,r)=>(r=null!=e?N($(e)):{},((e,t,r,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let r of k(t))M.call(e,r)||void 0===r||D(e,r,{get:()=>t[r],enumerable:!(n=j(t,r))||n.enumerable});return e})(D(r,"default",{value:e,enumerable:!0}),e)),Y=G({"node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js"(e,t){t.exports=o,o.sync=function(e,t){return n(r.statSync(e),e,t)};var r=H("fs");function n(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 o(e,t,o){r.stat(e,function(r,s){o(r,!r&&n(s,e,t))})}}}),z=G({"node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/mode.js"(e,t){t.exports=n,n.sync=function(e,t){return o(r.statSync(e),t)};var r=H("fs");function n(e,t,n){r.stat(e,function(e,r){n(e,!e&&o(r,t))})}function o(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)}}}),K=G({"node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js"(e,t){var r;function n(e,t,o){if("function"==typeof t&&(o=t,t={}),!o){if("function"!=typeof Promise)throw new TypeError("callback not provided");return new Promise(function(r,o){n(e,t||{},function(e,t){e?o(e):r(t)})})}r(e,t||{},function(e,r){e&&("EACCES"===e.code||t&&t.ignoreErrors)&&(e=null,r=!1),o(e,r)})}H("fs"),r="win32"===process.platform||global.TESTING_WINDOWS?Y():z(),t.exports=n,n.sync=function(e,t){try{return r.sync(e,t||{})}catch(e){if(t&&t.ignoreErrors||"EACCES"===e.code)return!1;throw e}}}}),q=G({"node_modules/.pnpm/which@2.0.2/node_modules/which/which.js"(e,t){var r="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,n=H("path"),o=r?";":":",s=K(),i=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),a=(e,t)=>{const n=t.colon||o,s=e.match(/\//)||r&&e.match(/\\/)?[""]:[...r?[process.cwd()]:[],...(t.path||process.env.PATH||"").split(n)],i=r?t.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",a=r?i.split(n):[""];return r&&-1!==e.indexOf(".")&&""!==a[0]&&a.unshift(""),{pathEnv:s,pathExt:a,pathExtExe:i}},c=(e,t,r)=>{"function"==typeof t&&(r=t,t={}),t||(t={});const{pathEnv:o,pathExt:c,pathExtExe:l}=a(e,t),d=[],u=r=>new Promise((s,a)=>{if(r===o.length)return t.all&&d.length?s(d):a(i(e));const c=o[r],l=/^".*"$/.test(c)?c.slice(1,-1):c,u=n.join(l,e),f=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;s(p(f,r,0))}),p=(e,r,n)=>new Promise((o,i)=>{if(n===c.length)return o(u(r+1));const a=c[n];s(e+a,{pathExt:l},(s,i)=>{if(!s&&i){if(!t.all)return o(e+a);d.push(e+a)}return o(p(e,r,n+1))})});return r?u(0).then(e=>r(null,e),r):u(0)};t.exports=c,c.sync=(e,t)=>{t=t||{};const{pathEnv:r,pathExt:o,pathExtExe:c}=a(e,t),l=[];for(let i=0;i<r.length;i++){const a=r[i],d=/^".*"$/.test(a)?a.slice(1,-1):a,u=n.join(d,e),p=!d&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;for(let e=0;e<o.length;e++){const r=p+o[e];try{if(s.sync(r,{pathExt:c})){if(!t.all)return r;l.push(r)}}catch(e){}}}if(t.all&&l.length)return l;if(t.nothrow)return null;throw i(e)}}}),W=G({"node_modules/.pnpm/path-key@3.1.1/node_modules/path-key/index.js"(e,t){var r=(e={})=>{const t=e.env||process.env;return"win32"!==(e.platform||process.platform)?"PATH":Object.keys(t).reverse().find(e=>"PATH"===e.toUpperCase())||"Path"};t.exports=r,t.exports.default=r}}),V=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js"(e,t){var r=H("path"),n=q(),o=W();function s(e,t){const s=e.options.env||process.env,i=process.cwd(),a=null!=e.options.cwd,c=a&&void 0!==process.chdir&&!process.chdir.disabled;if(c)try{process.chdir(e.options.cwd)}catch(e){}let l;try{l=n.sync(e.command,{path:s[o({env:s})],pathExt:t?r.delimiter:void 0})}catch(e){}finally{c&&process.chdir(i)}return l&&(l=r.resolve(a?e.options.cwd:"",l)),l}t.exports=function(e){return s(e)||s(e,!0)}}}),J=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/escape.js"(e,t){var r=/([()\][%!^"`<>&|;, *?])/g;t.exports.command=function(e){return e.replace(r,"^$1")},t.exports.argument=function(e,t){return e=(e=`"${e=(e=(e=`${e}`).replace(/(?=(\\+?)?)\1"/g,'$1$1\\"')).replace(/(?=(\\+?)?)\1$/,"$1$1")}"`).replace(r,"^$1"),t&&(e=e.replace(r,"^$1")),e}}}),X=G({"node_modules/.pnpm/shebang-regex@3.0.0/node_modules/shebang-regex/index.js"(e,t){t.exports=/^#!(.*)/}}),Q=G({"node_modules/.pnpm/shebang-command@2.0.0/node_modules/shebang-command/index.js"(e,t){var r=X();t.exports=(e="")=>{const t=e.match(r);if(!t)return null;const[n,o]=t[0].replace(/#! ?/,"").split(" "),s=n.split("/").pop();return"env"===s?o:o?`${s} ${o}`:s}}}),Z=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js"(e,t){var r=H("fs"),n=Q();t.exports=function(e){const t=Buffer.alloc(150);let o;try{o=r.openSync(e,"r"),r.readSync(o,t,0,150,0),r.closeSync(o)}catch(e){}return n(t.toString())}}}),ee=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js"(e,t){var r=H("path"),n=V(),o=J(),s=Z(),i="win32"===process.platform,a=/\.(?:com|exe)$/i,c=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;t.exports=function(e,t,l){t&&!Array.isArray(t)&&(l=t,t=null);const d={command:e,args:t=t?t.slice(0):[],options:l=Object.assign({},l),file:void 0,original:{command:e,args:t}};return l.shell?d:function(e){if(!i)return e;const t=function(e){e.file=n(e);const t=e.file&&s(e.file);return t?(e.args.unshift(e.file),e.command=t,n(e)):e.file}(e),l=!a.test(t);if(e.options.forceShell||l){const n=c.test(t);e.command=r.normalize(e.command),e.command=o.command(e.command),e.args=e.args.map(e=>o.argument(e,n));const s=[e.command].concat(e.args).join(" ");e.args=["/d","/s","/c",`"${s}"`],e.command=process.env.comspec||"cmd.exe",e.options.windowsVerbatimArguments=!0}return e}(d)}}}),te=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/enoent.js"(e,t){var r="win32"===process.platform;function n(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 o(e,t){return r&&1===e&&!t.file?n(t.original,"spawn"):null}t.exports={hookChildProcess:function(e,t){if(!r)return;const n=e.emit;e.emit=function(r,s){if("exit"===r){const r=o(s,t);if(r)return n.call(e,"error",r)}return n.apply(e,arguments)}},verifyENOENT:o,verifyENOENTSync:function(e,t){return r&&1===e&&!t.file?n(t.original,"spawnSync"):null},notFoundError:n}}}),re=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/index.js"(e,t){var r=H("child_process"),n=ee(),o=te();function s(e,t,s){const i=n(e,t,s),a=r.spawn(i.command,i.args,i.options);return o.hookChildProcess(a,i),a}t.exports=s,t.exports.spawn=s,t.exports.sync=function(e,t,s){const i=n(e,t,s),a=r.spawnSync(i.command,i.args,i.options);return a.error=a.error||o.verifyENOENTSync(a.status,i),a},t.exports._parse=n,t.exports._enoent=o}}),ne=G({"node_modules/.pnpm/merge-stream@2.0.0/node_modules/merge-stream/index.js"(e,t){var{PassThrough:r}=H("stream");t.exports=function(){var e=[],t=new r({objectMode:!0});return t.setMaxListeners(0),t.add=n,t.isEmpty=function(){return 0==e.length},t.on("unpipe",o),Array.prototype.slice.call(arguments).forEach(n),t;function n(r){return Array.isArray(r)?(r.forEach(n),this):(e.push(r),r.once("end",o.bind(null,r)),r.once("error",t.emit.bind(t,"error")),r.pipe(t,{end:!1}),this)}function o(r){!(e=e.filter(function(e){return e!==r})).length&&t.readable&&t.end()}}}}),oe=G({"node_modules/.pnpm/java-properties@1.0.2/node_modules/java-properties/dist-node/index.js"(e){Object.defineProperty(e,"__esModule",{value:!0}),e.of=e.PropertiesFile=void 0;var t,r=(t=H("fs"))&&t.__esModule?t:{default:t},n=class{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 t=r.default.readFileSync(e,"utf-8").split(/\r?\n/),n=this;for(let e=0;e<t.length;e++){let r=t[e];for(;"\\"===r.substring(r.length-1);)r=r.slice(0,-1),r+=t[e+1].trim(),e++;n.makeKeys(r)}}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={}}};e.PropertiesFile=n,e.of=function(...e){let t=new n;return t.of.apply(t,e),t}}}),se={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 ie(e){return(/\d+(?!.*\d+)/.exec(e)||[])[0]}function ae(e){return e?/^(?:refs\/heads\/)?(?<branch>.+)$/i.exec(e)[1]:void 0}var ce={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:ae(r?e.SYSTEM_PULLREQUEST_TARGETBRANCH:e.BUILD_SOURCEBRANCH),pr:t,isPr:r,prBranch:ae(r?e.SYSTEM_PULLREQUEST_SOURCEBRANCH:void 0),root:e.BUILD_REPOSITORY_LOCALPATH}}},le={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})},de={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})},ue={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}}},pe={detect:({env:e})=>Boolean(e.BUDDY_WORKSPACE_ID),configuration({env:e}){const t=ie(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}}},fe=F(re());function he(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 me=(e,t)=>({name:`SIGRT${t+1}`,number:ge+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),ge=34,_e=[{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"}],ye=()=>{const e=(()=>{const e=64-ge+1;return Array.from({length:e},me)})();return[..._e,...e].map(Ee)},Ee=({name:e,number:t,description:r,action:n,forced:o=!1,standard:s})=>{const{signals:{[e]:a}}=i.constants,c=void 0!==a;return{name:e,number:c?a:t,description:r,supported:c,action:n,forced:o,standard:s}},be=({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}],Ie=(()=>{const e=ye();return Object.fromEntries(e.map(be))})();(()=>{const e=ye(),t=Array.from({length:65},(t,r)=>((e,t)=>{const r=((e,t)=>{const r=t.find(({name:t})=>i.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:a,forced:c,standard:l}=r;return{[e]:{name:n,number:e,description:o,supported:s,action:a,forced:c,standard:l}}})(r,e));Object.assign({},...t)})();var we=({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=C.default.cwd()}}})=>{s=null===s?void 0:s;const f=void 0===(o=null===o?void 0:o)?void 0:Ie[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}),m=`Command ${h}: ${i}`,g="[object Error]"===Object.prototype.toString.call(n),_=g?`${m}\n${n.message}`:m,y=[_,t,e].filter(Boolean).join("\n");return g?(n.originalMessage=n.message,n.message=y):n=new Error(y),n.shortMessage=_,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},ve=["stdin","stdout","stderr"],Te=[];Te.push("SIGHUP","SIGINT","SIGTERM"),"win32"!==process.platform&&Te.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),"linux"===process.platform&&Te.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var Re=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,Se=Symbol.for("signal-exit emitter"),Ce=globalThis,Ae=Object.defineProperty.bind(Object),xe=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(Ce[Se])return Ce[Se];Ae(Ce,Se,{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}},Ue=class{},Pe=globalThis.process;Re(Pe)?new class extends Ue{#e="win32"===Pe.platform?"SIGINT":"SIGHUP";#t=new xe;#r;#n;#o;#s={};#i=!1;constructor(e){super(),this.#r=e,this.#s={};for(const t of Te)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(!Re(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 Te)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,Te.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 Re(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&&Re(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)}}(Pe):new class extends Ue{onExit(){return()=>{}}load(){}unload(){}},new TextEncoder,F(ne());var Le=(async()=>{})().constructor.prototype;["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(Le,e)]);var Oe=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],Be=/^[\w.-]+$/,Ne=c.debuglog("execa").enabled,De=(e,t)=>String(e).padStart(t,"0"),je=(e,t,r={})=>{const n=fe.default._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||C.default.cwd(),execPath:C.default.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:Ne,...r}).env=(({env:e,extendEnv:t,preferLocal:r,localDir:n,execPath:o})=>{const i=t?{...C.default.env,...e}:e;return r?(({env:e=C.default.env,...t}={})=>{const r=he({env:e={...e}});return t.path=e[r],e[r]=(({cwd:e=C.default.cwd(),path:t=C.default.env[he()],preferLocal:r=!0,execPath:n=C.default.execPath,addExecPath:o=!0}={})=>{const i=e instanceof URL?s.fileURLToPath(e):e,a=R.default.resolve(i),c=[];return r&&((e,t)=>{let r;for(;r!==t;)e.push(R.default.join(t,"node_modules/.bin")),r=t,t=R.default.resolve(t,"..")})(c,a),o&&((e,t,r)=>{const n=t instanceof URL?s.fileURLToPath(t):t;e.push(R.default.resolve(r,n,".."))})(c,n,a),[...c,t].join(R.default.delimiter)})(t),e})({env:i,cwd:n,execPath:o}):i})(r),r.stdio=(e=>{if(!e)return;const{stdio:t}=e;if(void 0===t)return ve.map(t=>e[t]);if((e=>ve.some(t=>void 0!==e[t]))(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${ve.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,ve.length);return Array.from({length:r},(e,r)=>t[r])})(r),"win32"===C.default.platform&&"cmd"===R.default.basename(e,".exe")&&t.unshift("/q"),{file:e,args:t,options:r,parsed:n}},ke=(e,r,n)=>"string"==typeof r||t.Buffer.isBuffer(r)?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}(r):r:void 0===n?void 0:"";function $e(e,t,r){const n=je(e,t,r),o=((e,t)=>Oe(e,t).join(" "))(e,t),s=((e,t)=>Oe(e,t).map(e=>(e=>"string"!=typeof e||Be.test(e)?e:`"${e.replaceAll('"','\\"')}"`)(e)).join(" "))(e,t);((e,{verbose:t})=>{t&&C.default.stderr.write(`[${(()=>{const e=new Date;return`${De(e.getHours(),2)}:${De(e.getMinutes(),2)}:${De(e.getSeconds(),2)}.${De(e.getMilliseconds(),3)}`})()}] ${e}\n`)})(s,n.options);const i=(e=>{const t=(({input:e,inputFile:t})=>"string"!=typeof t?e:((e=>{if(void 0!==e)throw new TypeError("The `input` and `inputFile` options cannot be both set.")})(e),a.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=S.default.spawnSync(n.file,n.args,{...n.options,input:i})}catch(e){throw we({error:e,stdout:"",stderr:"",all:"",command:o,escapedCommand:s,parsed:n,timedOut:!1,isCanceled:!1,killed:!1})}const l=ke(n.options,c.stdout,c.error),d=ke(n.options,c.stderr,c.error);if(c.error||0!==c.status||null!==c.signal){const e=we({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 Me(e){try{return $e("git",["rev-parse","HEAD"],e).stdout}catch{return}}function He(e){try{const t=$e("git",["rev-parse","--abbrev-ref","HEAD"],e).stdout;if("HEAD"===t){const t=$e("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 Ge=/^(?:.*)@(?:.*):(?:\d+\/)?(.*)\.git$/,Fe=/^\/(.*)\.git$/;function Ye(e){if(e){if(e.match(Ge))return e.replace(Ge,"$1");try{return new URL(e).pathname.replace(Fe,"$1")}catch{return}}}var ze={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:Ye(e.BUILDKITE_REPO),pr:t,isPr:r,prBranch:r?e.BUILDKITE_BRANCH:void 0,root:e.BUILDKITE_BUILD_CHECKOUT_PATH}}},Ke={detect:({env:e})=>Boolean(e.CIRCLECI),configuration({env:e}){const t=e.CIRCLE_PR_NUMBER||ie(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}`}}},qe="https://cirrus-ci.com",We={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:`${qe}/build/${e.CIRRUS_BUILD_ID}`,job:e.CIRRUS_TASK_ID,jobUrl:`${qe}/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}}},Ve={detect:({env:e})=>Boolean(e.CODEBUILD_BUILD_ID),configuration:({env:e,cwd:t})=>({name:"AWS CodeBuild",service:"codebuild",commit:Me({env:e,cwd:t}),build:e.CODEBUILD_BUILD_ID,branch:He({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})},Je={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}}},Xe={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}}},Qe=({env:e})=>{try{const t=e.GITHUB_EVENT_PATH?JSON.parse(a.readFileSync(e.GITHUB_EVENT_PATH,"utf-8")):void 0;if(t&&t.pull_request)return{branch:t.pull_request.base?ae(t.pull_request.base.ref):void 0,pr:t.pull_request.number}}catch{}return{pr:void 0,branch:void 0}},Ze={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=ae("pull_request_target"===e.GITHUB_EVENT_NAME?`refs/pull/${(e=>{const t=e.GITHUB_EVENT_PATH?JSON.parse(a.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?Qe({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}}},tt={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||Me({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}}},rt={detect:({env:e})=>"true"===e.NETLIFY,configuration({env:e}){const t="true"===e.PULL_REQUEST;return{name:"Netlify",service:"netlify",commit:e.COMMIT_REF,build:e.DEPLOY_ID,buildUrl:`https://app.netlify.com/sites/${e.SITE_NAME}/deploys/${e.DEPLOY_ID}`,branch:t?void 0:e.HEAD,pr:e.REVIEW_ID,isPr:t,prBranch:t?e.HEAD:void 0,slug:e.REPOSITORY_URL.match(/[^/:]+\/[^/]+?$/)[0],root:e.PWD}}},nt={detect:({env:e})=>Boolean(e.DISTELLI_APPNAME),configuration:({env:e})=>({name:"Puppet",service:"puppet",build:e.DISTELLI_BUILDNUM,buildUrl:e.DISTELLI_RELEASE,commit:e.DISTELLI_RELREVISION,branch:e.DISTELLI_RELBRANCH,root:e.DISTELLI_INSTALLHOME})},ot={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}}},st={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}}},it={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}}},at={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||Me({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}}},lt=F(oe()),dt={root:"teamcity.build.workingDir",branch:"teamcity.build.branch"},ut=e=>{try{return lt.default.of(e)}catch{return}},pt=({env:e,cwd:t})=>{const r=e.TEAMCITY_BUILD_PROPERTIES_FILE?ut(e.TEAMCITY_BUILD_PROPERTIES_FILE):void 0,n=r?r.get("teamcity.configuration.properties.file"):void 0,o=n?ut(n):n;return Object.fromEntries(Object.keys(dt).map(n=>[n,(r?r.get(dt[n]):void 0)||(o?o.get(dt[n]):void 0)||("branch"===n?He({env:e,cwd:t}):void 0)]))},ft={appveyor:se,azurePipelines:ce,bamboo:le,bitbucket:de,bitrise:ue,buddy:pe,buildkite:ze,circleci:Ke,cirrus:We,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:Ve,codefresh:Je,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:Xe,github:Ze,gitlab:et,jenkins:tt,netlify:rt,puppet:nt,sail:ot,screwdriver:st,scrutinizer:it,semaphore:at,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,...pt({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:ae(e.JB_SPACE_GIT_BRANCH),slug:t&&r?`${t.toLowerCase()}/${r}`:void 0}}}},ht=class e{git;config;snapshotTreeHash;snapshotIndexPath;constructor(e){this.config=e,this.git=p.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=r.join(i.tmpdir(),`git-diff-tracker-${f.randomUUID()}.index`),await this.git.env("GIT_INDEX_FILE",this.snapshotIndexPath).add(["-A"]);const e=await this.git.env("GIT_INDEX_FILE",this.snapshotIndexPath).raw(["write-tree"]);this.snapshotTreeHash=e.trim()}async computeDiff(){return"local"===this.config.mode?this.computeLocalDiff():this.computeCloudDiff()}async computeLocalDiff(){if(!this.snapshotTreeHash)throw new Error("No snapshot captured. Call captureSnapshot() first.");const e=r.join(i.tmpdir(),`git-diff-tracker-${f.randomUUID()}.index`);try{await this.git.env("GIT_INDEX_FILE",e).add(["-A"]);const t=(await this.git.env("GIT_INDEX_FILE",e).raw(["write-tree"])).trim();return await this.git.raw(["diff-tree","-p","--no-color",this.snapshotTreeHash,t])}finally{await mt(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 mt(this.snapshotIndexPath),this.snapshotIndexPath=void 0),this.snapshotTreeHash=void 0}};async function mt(e){try{await h.unlink(e)}catch{}}var gt={bodySerializer:e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t)},_t=({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):yt({allowReserved:e,name:r,value:t})).join(s);return"label"===n||"matrix"===n?s+i:i},yt=({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)}`},Et=({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])=>yt({allowReserved:e,name:"deepObject"===n?`${r}[${t}]`:t,value:o})).join(i);return"label"===n||"matrix"===n?i+a:a},bt=/\{[^{}]+\}/g;function It(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 wt,vt=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},Tt=({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=_t({allowReserved:i.allowReserved,explode:!0,name:o,style:"form",value:s,...i.array});e&&n.push(e)}else if("object"==typeof s){const e=Et({allowReserved:i.allowReserved,explode:!0,name:o,style:"deepObject",value:s,...i.object});e&&n.push(e)}else{const e=yt({allowReserved:i.allowReserved,name:o,value:s});e&&n.push(e)}}return n.join("&")},Rt=(e,t)=>!!t&&!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`)),St=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(bt);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,_t({explode:n,name:o,style:s,value:i}));continue}if("object"==typeof i){r=r.replace(t,Et({explode:n,name:o,style:s,value:i,valueOnly:!0}));continue}if("matrix"===s){r=r.replace(t,`;${yt({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:Tt(e.querySerializer),url:e.url}),Ct=(e,t)=>{const r={...e,...t};return r.baseUrl?.endsWith("/")&&(r.baseUrl=r.baseUrl.substring(0,r.baseUrl.length-1)),r.headers=xt(e.headers,t.headers),r},At=e=>{const t=[];return e.forEach((e,r)=>{t.push([r,e])}),t},xt=(...e)=>{const t=new Headers;for(const r of e){if(!r)continue;const e=r instanceof Headers?At(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},Ut=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}},Pt=Tt({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Lt={"Content-Type":"application/json"},Ot=(e={})=>({...gt,headers:Lt,parseAs:"auto",querySerializer:Pt,...e}),Bt=(e={})=>{let t=Ct(Ot(),e);const r=()=>({...t}),n={error:new Ut,request:new Ut,response:new Ut},o=async e=>{const r={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:xt(t.headers,e.headers),serializedBody:void 0};return r.security&&await(async({security:e,...t})=>{for(const r of e){if(Rt(t,r.name))continue;const e=await vt(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:St(r)}},s=async e=>{const{opts:t,url:r}=await o(e),s={redirect:"follow",...t,body:It(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 m="";const g=()=>{try{f.cancel()}catch{}};h.addEventListener("abort",g);try{for(;;){const{done:e,value:t}=await f.read();if(e)break;m+=t;const s=m.split("\n\n");m=s.pop()??"";for(const e of s){const t=e.split("\n"),s=[];let i,a;for(const e of t)if(e.startsWith("data:"))s.push(e.replace(/^data:\s*/,""));else if(e.startsWith("event:"))i=e.replace(/^event:\s*/,"");else if(e.startsWith("id:"))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",g),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:St,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=Ct(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")}},Nt=Bt(Ot({baseUrl:"https://api.stably.ai"})),Dt="x-stably-org-id",jt="4.3.2",kt=process.env.STABLY_API_URL||"https://api.stably.ai",$t=process.env.AUTH_URL||"https://auth.stably.ai",Mt=process.env.AUTH_CLIENT_ID||"288007877071cce81f269428ea78653a",Ht=process.env.AI_PROXY_URL||"https://ai-proxy.stably.ai",Gt="http://localhost:9876/auth/callback",Ft=()=>wt||(wt=Bt(Ot({baseUrl:kt,headers:{"X-STABLY-CLI-VERSION":jt,"X-STABLY-SOURCE":"cli"}}))),Yt=async(e,t)=>{const r=await(n={body:{accessToken:e,orgId:t},client:Ft()},(n.client??Nt).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},zt=_.z.object({org_id:_.z.string(),org_name:_.z.string()}),Kt=_.z.object({email:_.z.string(),org_id_to_org_member_info:_.z.record(_.z.string(),zt).optional(),org_member_info:zt.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 qt=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)},Wt=e=>{try{const t=Kt.parse(qt(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"}`)}},Vt=R.default.join(A.default.homedir(),".stably"),Jt=R.default.join(Vt,"auth.json"),Xt=".stably",Qt="project.json",Zt=L.default.object({accessToken:L.default.string(),expiresAt:L.default.number(),idToken:L.default.string().optional(),refreshToken:L.default.string()}),er=L.default.object({orgId:L.default.string(),orgName:L.default.string(),projectId:L.default.string(),projectName:L.default.string()}),tr=async()=>{try{const e=await h.readFile(Jt,"utf-8");return Zt.parse(JSON.parse(e))}catch{return}},rr=async e=>{await h.mkdir(Vt,{recursive:!0}),await h.writeFile(Jt,JSON.stringify(e,null,2),{mode:384})},nr=async()=>{try{await h.unlink(Jt)}catch{}},or=async e=>{let t=e;const{root:r}=R.default.parse(t);for(;t!==r;){const e=R.default.join(t,Xt);try{return await h.access(e),e}catch{t=R.default.dirname(t)}}},sr=async()=>{try{const e=await or(process.cwd());if(!e)return;const t=R.default.join(e,Qt),r=await h.readFile(t,"utf-8");return er.parse(JSON.parse(r))}catch{return}},ir=async()=>{try{const e=await or(process.cwd());e&&await h.unlink(R.default.join(e,Qt))}catch{}},ar=e=>Date.now()>=e.expiresAt-3e5,cr=async e=>{const t=new URLSearchParams({client_id:Mt,grant_type:"refresh_token",refresh_token:e}),r=await fetch(`${$t}/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}},lr=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`,dr=(e,t,r)=>{e.writeHead(t,{"Content-Type":"text/html"}),e.end(r)},ur=(e,t)=>{const r=new URLSearchParams({client_id:Mt,code_challenge:e,code_challenge_method:"S256",redirect_uri:Gt,response_type:"code",state:t});return`${$t}/propelauth/oauth/authorize?${r.toString()}`},pr=async e=>{const t=m.spinner();let r;t.start("Loading user info...");try{r=Wt(e.accessToken),t.stop(U.default.green(`✓ Logged in as ${U.default.cyan(r.email)}`))}catch(e){t.stop(U.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: ${U.default.cyan(e[0].name)}`),e[0];if(!process.stdin.isTTY)return m.log.info(`Auto-selecting organization: ${U.default.cyan(e[0].name)}`),e[0];const t=await m.select({message:"Select an organization",options:e.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 Yt(e.accessToken,n.id);o={accessToken:r.accessToken,expiresAt:Date.now()+1e3*r.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken},t.stop(U.default.green("✓ Credentials obtained"))}catch(e){t.stop(U.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:Ft(),path:{orgId:t}},(n.client??Nt).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(U.default.green("✓ Projects loaded"))}catch(e){r.stop(U.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 ${U.default.underline(U.default.cyan("https://app.stably.ai"))}`);if(1===n.length)return m.log.info(`Using project: ${U.default.cyan(n[0].name)}`),n[0];if(!process.stdin.isTTY)return m.log.info(`Auto-selecting project: ${U.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=R.default.join(process.cwd(),Xt),r=R.default.join(t,Qt);await h.mkdir(t,{recursive:!0}),await h.writeFile(r,JSON.stringify(e,null,2)),await(async e=>{const t=R.default.join(e,".gitignore"),r="# Stably CLI (only docs/ are tracked)\n.stably/*\n!.stably/docs/";try{const e=await h.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 h.writeFile(t,n)}else if(s.test(e)){const n=e.replace(s,`\n${r}\n`);await h.writeFile(t,n)}else await h.appendFile(t,`\n${r}\n`)}catch{await h.writeFile(t,`${r}\n`)}})(process.cwd())})({orgId:n.id,orgName:n.name,projectId:s.id,projectName:s.name}),m.log.info(U.default.dim("Linked this directory to your Stably project.")),{scopedTokens:o,success:!0}):(m.log.warn("Project selection cancelled."),{success:!1})},fr=async()=>{if(hr())return m.log.warn(`Environment variables ${U.default.cyan("STABLY_API_KEY")} and ${U.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(U.default.yellow("Login skipped - using environment variable authentication."));const e=await tr();if(e){if(!ar(e)){if(await sr())return void m.outro(U.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 pr(e);return void(t.success?(await rr(t.scopedTokens),m.outro(U.default.green("Setup complete! You can now use Stably CLI."))):m.outro(U.default.yellow("Setup incomplete. Run `stably login` to try again.")))}const t=m.spinner();t.start("Refreshing session...");try{const r=await cr(e.refreshToken);t.stop(U.default.green("✓ Session refreshed"));const n=await sr();if(n){t.start("Getting org credentials...");try{const e=await Yt(r.accessToken,n.orgId),o={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:r.idToken,refreshToken:r.refreshToken};await rr(o),t.stop(U.default.green("✓ Credentials obtained")),m.outro(U.default.green("Login successful"))}catch{await rr(r),t.stop(U.default.yellow("Using full credentials")),m.outro(U.default.green("Login successful"))}}else{const e=await pr(r);e.success?(await rr(e.scopedTokens),m.outro(U.default.green("Setup complete! You can now use Stably CLI."))):m.outro(U.default.yellow("Setup incomplete. Run `stably login` to try again."))}return}catch{t.stop(U.default.yellow("Session expired, proceeding with fresh login...")),await nr(),await ir()}}const{authorizeUrl:t,waitForCallback:r}=(()=>{const{authorizeUrl:e,codeVerifier:t,state:r}=(()=>{const e=P.default.randomBytes(32).toString("base64url"),t=(r=e,P.default.createHash("sha256").update(r).digest("base64url"));var r;const n=P.default.randomBytes(16).toString("base64url");return{authorizeUrl:ur(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(()=>{i.close(),e({error:"Login timed out",success:!1})},3e5),o=()=>{clearTimeout(r)},i=B.default.createServer((t,r)=>{const a=new s.URL(t.url||"","http://localhost:9876");if("/auth/callback"!==a.pathname)return r.writeHead(404),void r.end("Not found");const c=a.searchParams.get("code"),l=a.searchParams.get("state"),d=a.searchParams.get("error");return d?(dr(r,400,lr(d)),o(),i.close(),void e({error:d,success:!1})):c&&l?l!==n?(dr(r,400,lr("Invalid state parameter (possible CSRF attack)")),o(),i.close(),void e({error:"State mismatch",success:!1})):(dr(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(),i.close(),void e({code:c,state:l,success:!0})):(dr(r,400,lr("Missing code or state parameter")),o(),i.close(),void e({error:"Missing code or state parameter",success:!1}))});i.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."))}),i.listen(9876)}));var n;if(!r.success)throw new Error(r.error);return(async(e,t)=>{const r=new URLSearchParams({client_id:Mt,code:e,code_verifier:t,grant_type:"authorization_code",redirect_uri:Gt}),n=await fetch(`${$t}/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(U.default.dim("If browser doesn't open, visit:")),m.log.info(U.default.underline(U.default.cyan(t)));try{await O.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(U.default.green("✓ Authentication successful"))}catch(e){n.stop(U.default.red("✗ Authentication failed"));const t=e instanceof Error?e.message:"Unknown error";m.outro(U.default.red(`Login failed: ${t}`)),process.exit(1)}const i=await pr(o);i.success?(await rr(i.scopedTokens),m.outro(U.default.green("Setup complete! You can now use Stably CLI."))):(m.outro(U.default.yellow("Setup incomplete. Run `stably login` to try again.")),process.exit(1))},hr=()=>{const e=process.env.STABLY_API_KEY?.trim(),t=process.env.STABLY_PROJECT_ID?.trim();if(e&&t)return{apiKey:e,projectId:t}},mr=!1,gr=()=>{mr||(mr=!0,m.log.warn("Both environment variable auth and stored OAuth login were detected."),m.log.warn(`Honoring environment variables (${U.default.cyan("STABLY_API_KEY")} + ${U.default.cyan("STABLY_PROJECT_ID")}).`),m.log.warn("To use OAuth login instead, unset those environment variables."))},_r=async()=>{const e=await tr();if(e){if(!ar(e)){const t=await sr();if(t&&"full"===(e=>{try{const t=Kt.parse(qt(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))try{const r=await Yt(e.accessToken,t.orgId),n={accessToken:r.accessToken,expiresAt:Date.now()+1e3*r.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken};return await rr(n),n}catch{return e}return e}try{const t=await cr(e.refreshToken),r=await sr();if(r)try{const e=await Yt(t.accessToken,r.orgId),n={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:t.idToken,refreshToken:t.refreshToken};return await rr(n),n}catch{return await rr(t),t}return await rr(t),t}catch{return}}},yr=async(e={})=>{const t=hr();if(t){try{await tr()&&gr()}catch{}return{auth:t,type:"env"}}let r=await _r(),n=r?await sr():void 0;const o=process.stdin.isTTY&&process.stdout.isTTY;if((!r||!n)&&e.autoLogin&&o){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(`${U.default.dim("Alternatively, set environment variables for an org API key:")}\n${U.default.dim(" STABLY_API_KEY=... STABLY_PROJECT_ID=... stably")}\n`),process.stdout.write("\n");const e=g.createInterface({input:process.stdin,output:process.stdout});try{await e.question(U.default.dim("Press Enter to continue... "))}finally{e.close()}await fr(),r=await _r(),n=r?await sr():void 0}return r||(m.outro(U.default.red("You are not logged in. Run `stably login` to authenticate.")),process.exit(1)),n||(m.outro(U.default.red("You haven't selected an organization and project. Run `stably login` to complete setup.")),process.exit(1)),{auth:{accessToken:r.accessToken,context:n},type:"oauth"}},Er=e=>e?{...process.env,...e}:process.env,br=async()=>{const e=hr();if(e)return{STABLY_API_KEY:e.apiKey,STABLY_PROJECT_ID:e.projectId};const t=await(async()=>{const e=hr();if(e){try{await tr()&&gr()}catch{}return{auth:e,type:"env"}}const t=await _r(),r=t?await sr():void 0;if(t&&r)return{auth:{accessToken:t.accessToken,context:r},type:"oauth"}})();if(!t||"env"===t.type)return;const r=process.env.STABLY_PROJECT_ID?.trim(),n=r||(e=>"env"===e.type?e.auth.projectId:e.auth.context.projectId)(t);if(!n)return;const o=await(async(e,t)=>{try{return(await(async({accessToken:e,projectId:t})=>{const r=await(n={auth:e,client:Ft(),path:{projectId:t}},(n.client??Nt).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/projects/{projectId}/api-key",...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 project");if(r.error)throw new Error(`Failed to get API key: ${r.response.status}`);return r.data})({accessToken:e,projectId:t})).apiKey}catch{return e}})(t.auth.accessToken,n);return o?{STABLY_API_KEY:o,STABLY_PROJECT_ID:n}:void 0},Ir=e=>e?{[Dt]:e}:void 0,wr=_.z.object({context:_.z.string().min(1),autohealReportUrl:_.z.string()}),vr=e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"text"===t.type&&"string"==typeof t.text},Tr=e=>null!=e&&"object"==typeof e&&"tool_response"in e,Rr=e=>{if(!e||"object"!=typeof e)return;const t=e;return Array.isArray(t.tool_response)?t.tool_response:void 0},Sr=e=>{const t=Rr(e);if(t)return t.filter(vr).map(e=>e.text).join("\n")||void 0},Cr=/\u001b\[[0-9;]*m/g,Ar=e=>e.replace(Cr,""),xr=/\$\{process\.env\.([A-Z_][A-Z0-9_]*)\}/g;function Ur({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(xr,(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 Pr({onResult:e}){return async t=>{if(!Tr(t))return{decision:"approve"};const r=Sr(t);if(!r)return{decision:"approve"};const n=function(e){const t=Ar(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 Lr({onResult:e}){return async t=>{if(!Tr(t))return{decision:"approve"};const r=Sr(t);if(!r)return{decision:"approve"};const n=function(e){const t=Ar(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 Or=/\.(spec|test)\.(ts|tsx|js|jsx|mts|mjs)$/;function Br({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&&Or.test(n)&&e(n),{decision:"approve"}}}var Nr=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()})}},Dr=10240,jr=async({defaultContent:e,fileName:t,filePath:r})=>{try{const e=(await h.stat(r)).size,n=await h.readFile(r,"utf-8"),o=Buffer.byteLength(n,"utf-8");if(o<=Dr)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<=Dr?s:s.slice(0,Dr)+`\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}},kr=async({defaultContent:e,dirName:t,dirPath:r})=>{try{const e=await h.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}},$r=[".ts",".js",".mts",".mjs",".cts",".cjs"];function Mr(e){const t=r.resolve(e);if(a.existsSync(t))for(const e of $r){const n=r.join(t,`playwright.config${e}`);if(a.existsSync(n))return n}}var Hr=["tests","e2e","__tests__","test"];function Gr(e){try{return a.existsSync(e)&&a.statSync(e).isDirectory()}catch{return!1}}function Fr(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(U.default.dim(`Using output directory: ${e} (from ${r})`))}var Yr=["mcp__playwright-test__","mcp__auto-heal-report__","mcp__test-doc-sync__","mcp__stably-agent-control__"],zr=["planner_","generator_"],Kr={"mcp__stably-agent-control__restart_mcp_servers":"Restarting Browser Tools"},qr=(e,t)=>{const r=t.find(t=>e.startsWith(t));return r?e.slice(r.length):e},Wr=e=>{const t=Kr[e];if(t)return t;const r=qr(e,Yr);return qr(r,zr).split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")},Vr=(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},Jr=w.z.object({bucket:w.z.string(),key:w.z.string()}),Xr=w.z.object({diffBucketPath:Jr,expiresInSeconds:w.z.number(),key:w.z.string(),uploadUrl:w.z.string()}),Qr=["test","bug","other"],Zr={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."},en=e=>Zr[e],{zSuiteAutoHealReport:tn}=function(e){const t=e.enum(Qr),r=["Classification of the root cause:","",`- test: ${en("test")}`,`- bug: ${en("bug")}`,`- other: ${en("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.")})}}(w.z),rn=({authHeader:e,diffTracker:t,orgId:r,runId:n})=>l.createSdkMcpServer({name:"auto-heal-report",tools:[l.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:tn},async({report:o})=>{const s=await t.computeDiff(),i=tn.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:Ft(),headers:Ir(t),path:{runId:n}},(s.client??Nt).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:Ft(),headers:Ir(r),path:{runId:n}},(s.client??Nt).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=Xr.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"}),nn=({onComplete:e})=>l.createSdkMcpServer({name:"session-control",tools:[l.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:w.z.string().describe("A brief summary of what was accomplished")},async({summary:t})=>{const r=t;return e(),`Session complete: ${r}`})]}),on=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]"),sn=(e,t)=>({message:on(e),status:t?.status,statusText:t?.statusText}),an=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"]),cn=["Bash","Read","Write","Edit","Glob","Grep"],ln=["mcp__playwright-test"],dn=["Bash","Read","Write","Edit","Glob","Grep","mcp__session-control"],un=e=>{if("EPIPE"!==e.code)throw e},pn=async e=>{process.stdout.on("error",un),process.stderr.on("error",un);const t=e=>{if("EPIPE"!==e.code)throw e};process.on("uncaughtException",t);const n=await yr({autoLogin:"chat"===e.mode||"init"===e.mode}),o=(e=>"env"===e.type?e.auth.apiKey:e.auth.accessToken)(n),s="oauth"===n.type?n.auth.context.orgId:void 0,i=R.default.resolve(process.cwd()),a=R.default.join(i,".env"),c=x.default.existsSync(a)&&x.default.statSync(a).isFile()?d.parse(x.default.readFileSync(a,"utf8")):{},u="chat"!==e.mode&&"init"!==e.mode,p="chat"===e.mode||"init"===e.mode?new Nr:void 0,f="chat"===e.mode?e.getHelpText:void 0,m={log:[],promptDisplay:"chat"===e.mode?"Ask Stably to build tests for you":"init"===e.mode?"Setting up Playwright and Stably SDK":"fix"===e.mode?"Fixing broken tests":(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt)||"<empty prompt>",status:"running"};let g,_=u,y=!1;const E={current:e=>{}},w={current:async()=>{}},{addTool:v,addToolResult:T,appendText:S,appendUserMessage:C,cleanup:A,setExiting:P,setStatus:L,showPermissionPrompt:O}=await(async(e,t)=>{const{Box:r,Static:n,Text:o,render:s,useInput:i}=await import("ink"),a=!!process.stdin.isTTY,c=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],l=()=>I.jsx(o,{inverse:!0,children:" "}),d=(({Box:e,Text:t,useInput:r},n,o)=>function({onChoice:s,prompt:i}){const[a,c]=b.useState(0),[l,d]=b.useState(!1),[u,p]=b.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=Wr(i.toolName),m=Vr(i.toolName,i.input);return I.jsxs(e,{borderColor:"yellow",borderStyle:"round",flexDirection:"column",marginTop:1,paddingX:1,paddingY:0,children:[I.jsx(t,{bold:!0,color:"yellow",children:"Permission Required"}),I.jsxs(e,{flexDirection:"column",marginTop:1,children:[I.jsx(t,{color:"magenta",children:h}),null!=m&&I.jsxs(t,{color:"gray",children:[" ",m]})]}),null!=i.decisionReason&&I.jsx(e,{marginTop:1,children:I.jsxs(t,{color:"gray",children:["Reason: ",i.decisionReason]})}),l?I.jsxs(e,{flexDirection:"column",marginTop:1,children:[I.jsx(t,{color:"gray",children:"Enter message for AI (press Enter to submit, Esc to cancel):"}),I.jsxs(t,{children:[I.jsx(t,{color:"yellow",children:">"})," ",u,I.jsx(n,{})]})]}):I.jsxs(e,{flexDirection:"column",marginTop:1,children:[I.jsx(t,{color:"gray",children:"Use ↑↓ arrows or number keys to select:"}),f.map((e,r)=>I.jsx(t,{children:I.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=e=>"tool"===e.kind?I.jsxs(n,{color:"magenta",children:["• ",e.content]},e.id):"tool_result"===e.kind?I.jsx(n,{color:"gray",children:e.content},e.id):"user"===e.kind?I.jsxs(n,{color:"cyan",children:["You: ",e.content]},e.id):I.jsx(n,{children:e.content},e.id),l="vscode"===process.env.TERM_PROGRAM,d=(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};return function({onExit:u,onPermissionChoice:p,onSend:f,showSpinnerImmediately:h,state:m}){const[g,_]=b.useState(""),[y,E]=b.useState(0),w=b.useRef(!1),v=b.useRef(void 0),[T,R]=b.useState(!1),S=b.useRef(0),C=m.log.at(-1),A="text"===C?.kind&&"running"===m.status,x=l?0:A?m.log.length-1:m.log.length;b.useEffect(()=>{m.log.length<S.current&&(S.current=0),x>S.current&&(S.current=x)},[m.log.length,x]);const U=m.log.slice(0,S.current),P=m.log.slice(S.current),L=!!m.permissionPrompt,O=b.useCallback(()=>{w.current?(v.current&&clearTimeout(v.current),u?.(),process.exit(0)):(w.current=!0,R(!0),v.current=setTimeout(()=>{w.current=!1,R(!1)},2e3))},[u]);o((e,t)=>{t.ctrl&&"c"===e&&O()},{isActive:s}),b.useEffect(()=>{if(L||!f)return;const e=e=>{const t=e.toString();"[1;5H"!==t&&"[1;5~"!==t?"[1;5F"!==t&&"[4;5~"!==t?"[H"!==t&&"[1~"!==t&&"OH"!==t&&"[7~"!==t?"[F"!==t&&"[4~"!==t&&"OF"!==t&&"[8~"!==t||E(e=>((e,t)=>{const r=e.indexOf("\n",t);return-1===r?e.length:r})(g,e)):E(e=>((e,t)=>{if(t<=0)return 0;const r=e.lastIndexOf("\n",t-1);return-1===r?0:r+1})(g,e)):E(g.length):E(0)};return process.stdin.on("data",e),()=>{process.stdin.off("data",e)}},[L,f,g]),o((e,t)=>{if(!t.ctrl||"c"!==e){if(t.return){const e=g.trim();return e&&f?.(e),_(""),void E(0)}if(t.ctrl&&"w"===e||t.ctrl&&t.backspace){const e=d(g,y);return _(t=>t.slice(0,e)+t.slice(y)),void E(e)}!t.backspace&&!t.delete||t.ctrl?t.ctrl&&t.leftArrow||t.meta&&"b"===e?E(d(g,y)):t.ctrl&&t.rightArrow||t.meta&&"f"===e?E(((e,t)=>{if(t>=e.length)return e.length;let r=t;for(;r<e.length&&!/\s/.test(e[r]);)r++;for(;r<e.length&&/\s/.test(e[r]);)r++;return r})(g,y)):t.leftArrow?E(e=>Math.max(0,e-1)):t.rightArrow?E(e=>Math.min(g.length,e+1)):t.ctrl&&"a"===e?E(0):t.ctrl&&"e"===e?E(g.length):!e||t.ctrl||t.meta||t.escape||e.includes("")||/^\[./.test(e)||/^O[A-D]$/.test(e)||(_(t=>t.slice(0,y)+e+t.slice(y)),E(t=>t+e.length)):y>0&&(_(e=>e.slice(0,y-1)+e.slice(y)),E(e=>e-1))}},{isActive:s&&!!f&&!L});const B=b.useMemo(()=>"running"===m.status?I.jsx(a,{label:"Working"}):"success"!==m.status?I.jsx(n,{color:"red",children:"✖ Failed"}):void 0,[m.status]),N=!(h||!f||"running"!==m.status||0!==m.log.length||m.resultText||m.errorText),D="running"===m.status&&!N||m.log.length>0||m.resultText||m.errorText||"running"!==m.status;return I.jsxs(t,{flexDirection:"column",children:[I.jsx(r,{items:["header"],children:()=>I.jsxs(t,{flexDirection:"column",flexShrink:0,children:[I.jsx(n,{color:"cyan",bold:!0,children:"Stably Agent"}),I.jsx(t,{flexDirection:"column",marginTop:1,children:I.jsx(n,{color:"gray",children:m.promptDisplay})})]},"header")}),U.length>0&&I.jsx(r,{items:U,children:e=>c(e)}),P.length>0&&I.jsx(t,{flexDirection:"column",children:P.map(e=>c(e))}),"error"===m.status&&m.errorText&&I.jsx(t,{marginTop:1,children:I.jsx(n,{color:"red",children:m.errorText})}),"success"===m.status&&m.resultText&&I.jsx(t,{marginTop:1,children:I.jsx(n,{children:m.resultText})}),D&&I.jsx(t,{flexDirection:"column",flexShrink:0,marginTop:1,children:B}),null!=m.permissionPrompt&&null!=p&&I.jsx(i,{onChoice:p,prompt:m.permissionPrompt}),null!=f&&null==m.permissionPrompt&&!m.isExiting&&I.jsxs(t,{borderColor:"gray",borderStyle:"round",flexDirection:"column",flexShrink:0,marginTop:1,paddingX:1,paddingY:0,children:[I.jsx(n,{color:"gray",children:"Type a message and press Enter. Press Ctrl+C to exit."}),I.jsxs(n,{children:[I.jsx(n,{color:"yellow",children:">"})," ",g.slice(0,y),I.jsx(e,{}),g.slice(y)]})]}),T&&I.jsx(t,{marginTop:1,children:I.jsx(n,{color:"yellow",children:"Press Ctrl+C again to exit"})})]})}})({Cursor:l,inkComponents:{Box:r,Static:n,Text:o,useInput:i},isRawModeSupported:a,PermissionPrompt:d,Spinner:({label:e})=>{const[t,r]=b.useState(0);return b.useEffect(()=>{const e=setInterval(()=>r(e=>(e+1)%c.length),80);return()=>clearInterval(e)},[]),I.jsxs(o,{color:"yellow",children:[c[t]," ",e]})}});let p=e;const f={current:(e,t)=>{}},h=s(I.jsx(u,{onExit:t?.onExit,onPermissionChoice:(e,t)=>f.current(e,t),onSend:t?.onSend,showSpinnerImmediately:t?.showSpinnerImmediately,state:p}),{exitOnCtrlC:!1}),m=()=>{p={...p},h.rerender(I.jsx(u,{onExit:t?.onExit,onPermissionChoice:(e,t)=>f.current(e,t),onSend:t?.onSend,showSpinnerImmediately:t?.showSpinnerImmediately,state:p}))},g=({text:e})=>{e&&(p.log=[...p.log,{content:e,id:p.log.length,kind:"user"}],m())};return{addTool:({rawName:e,toolInput:t})=>{const r=Wr(e),n=Vr(e,t),o=n?`${r} (${n})`:r;p.log=[...p.log,{content:o,id:p.log.length,kind:"tool"}],m()},addToolResult:({message:e})=>{p.log=[...p.log,{content:e,id:p.log.length,kind:"tool_result"}],m()},appendText:({text:e})=>{if(!e)return;const t=p.log.at(-1),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"}],m()},appendUserMessage:g,cleanup:async()=>{const e=h.waitUntilExit();h.unmount(),await e},setExiting:()=>{p.isExiting=!0,m()},setStatus:({error:e,result:t,status:r})=>{p.errorText=e,p.resultText=t,p.status=r,m()},showPermissionPrompt:e=>new Promise(t=>{f.current=(r,n)=>{if(p.permissionPrompt=void 0,m(),"allow"===r)t({behavior:"allow",updatedInput:e.input});else if("always"===r)t({behavior:"allow",updatedInput:e.input,updatedPermissions:e.suggestions});else{const e=n??"User denied this action";g({text:e}),t({behavior:"deny",message:e,interrupt:!1})}},p.permissionPrompt={...e,resolve:t},m()})}})(m,"chat"===e.mode||"init"===e.mode?{onExit:()=>{w.current()},onSend:e=>E.current(e),showSpinnerImmediately:"init"===e.mode}:void 0);let B=m.status;const N=({error:e,result:t,status:r})=>{B=r,L({error:e,result:t,status:r})};let D;E.current=e=>{if("/help"===e.trim()){_&&p&&(y=!0,g?.interrupt?.(),p.allowNextTurn(),_=!1),"running"===B&&N({status:"success"}),C({text:e});const t=f?.();return void S({text:t??"Help is not available in this session."})}p&&(_&&(y=!0,g?.interrupt?.(),p.allowNextTurn(),_=!1),N({status:"running"}),C({text:e}),p.pushText(e),_=!0)};const j=[];let k;const $=await(async()=>{if("single"===e.mode){const t=Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt,n=await async function(e,t){const n=r.resolve(e);if(t){const e=r.resolve(n,t);return Fr(e,"output-flag"),{path:e,source:"output-flag"}}const o=Mr(n);if(o){const e=await async function(e){try{const t=(await h.readFile(e,"utf-8")).match(/testDir:\s*['"]([^'"]+)['"]/);return t?.[1]}catch{return}}(o);if(e){const t=r.resolve(r.dirname(o),e);if(Gr(t))return Fr(t,"playwright.config.ts"),{path:t,source:"playwright.config.ts"}}}for(const e of Hr){const t=r.join(n,e);if(Gr(t))return Fr(t,"auto-detected"),{path:t,source:"auto-detected"}}return Fr(n,"cwd-fallback"),{path:n,source:"cwd-fallback"}}(i,e.outputDir);return k=n.path,`${t}\n\n[Output directory: ${k}]`}if("fix"===e.mode)try{const{context:t,autohealReportUrl:r}=await(async({authHeader:e,orgId:t,runId:r})=>{const n=await(o={auth:e,client:Ft(),headers:Ir(t),path:{runId:r}},(o.client??Nt).get({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/runs/{runId}/autoheal-context",...o}));var o;if(404===n.response.status)throw new Error(`Run ID "${r}" was not found.`);if(401===n.response.status)throw new Error("Unauthorized: failed to fetch autoheal context (401).");if(422===n.response.status)throw new Error(n.error?.error??"Failed to fetch autoheal context (422).");if(!n.error){const e=wr.safeParse(n.data);if(e.success)return{context:e.data.context,autohealReportUrl:e.data.autohealReportUrl};throw new Error("Autoheal context response missing or invalid context.")}throw new Error("Failed to fetch autoheal context")})({authHeader:o,orgId:s,runId:e.runId});return D=r,t}catch(e){const t=e instanceof Error?e.message:"Failed to fetch autoheal context.";N({error:t,status:"error"}),await A(),process.exit(1)}return"init"===e.mode?"Please analyze this project and set up Playwright with the Stably SDK. Check for existing configurations and install the necessary dependencies.":""})(),M=await async function(e){const t=R.default.resolve(e),r=R.default.join(t,"tests"),n=R.default.join(r,"helpers"),o=R.default.join(r,"assets"),s=R.default.join(t,"playwright.config.ts"),i=R.default.join(r,"seed.spec.ts"),[a,c,l,d,u,p]=await Promise.all([kr({defaultContent:"Unable to read directory",dirName:"working directory",dirPath:t}),kr({defaultContent:"Unable to read directory",dirName:"tests directory",dirPath:r}),kr({defaultContent:"Directory does not exist yet",dirName:"helpers directory",dirPath:n}),kr({defaultContent:"Directory does not exist yet",dirName:"assets directory",dirPath:o}),jr({defaultContent:"File does not exist or could not be read",fileName:"playwright.config.ts",filePath:s}),jr({defaultContent:"File does not exist or could not be read",fileName:"seed.spec.ts",filePath:i})]);return{absolutePath:t,directories:{assets:d,helpers:l,root:a,tests:c},files:{playwrightConfig:u,seedSpec:p}}}(i),H=await(async({allowedEnvVars:e,mode:t,workspaceInfo:r,authHeader:n})=>{const o=Ft(),s=await(i={client:o,auth:n,body:{mode:t,workspaceInfo:r,allowedEnvVars:e}},(i.client??Nt).post({security:[{scheme:"bearer",type:"http"}],url:"/internal/v1/cli/prompts/system",...i,headers:{"Content-Type":"application/json",...i.headers}}));var i;if(s.error)throw new Error(`Failed to fetch system prompt: ${JSON.stringify(s.error)}`);return s.data.systemPrompt})({allowedEnvVars:Object.keys(c),mode:e.mode,workspaceInfo:M,authHeader:o}),G=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??Nt).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:sn(e,a)}}return i.data?{key:i.data.key}:{error:sn("No data in response",a)}}catch(e){const t=e instanceof Error?e.message:"Unknown error";return{error:sn(t)}}var s}({auth:o,client:Ft(),source:"cli"}),F=G.key;if(!F){const e=G.error?.message;N({error:e?`Unable to make AI calls: ${e}`:"Unable to make AI calls. Check if you are authenticated.",status:"error"}),await A(),process.exit(1)}const Y=Object.fromEntries(Object.entries(process.env).filter(([e])=>!an.has(e))),z=await br(),K=z?Object.fromEntries(Object.entries(Er(z)).filter(e=>null!=e[1])):void 0,q="init"===e.mode,W="fix"===e.mode,V="chat"===e.mode,J=W?ht.createLocal({workingDir:i}):void 0;J&&await J.captureSnapshot();const X=q?dn:[...cn,...W?["mcp__auto-heal-report"]:[]],Q=q?dn:ln,Z=q?{"session-control":nn({onComplete:()=>{N({status:"success"}),P(),p?.finish(),process.exit(0)}})}:W&&J?{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:K},"auto-heal-report":rn({authHeader:o,diffTracker:J,orgId:s,runId:e.runId})}:{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx",env:K}},ee="single"===e.mode,te=q?[]:[{hooks:[async e=>{const t=Rr(e);if(!t)return{decision:"approve"};let r=!1;const n=t.map(e=>vr(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:[Pr({onResult:e=>T({message:e})})]},{matcher:"mcp__playwright-test__test_debug",hooks:[Lr({onResult:e=>T({message:e})})]},...ee?[{matcher:"Write",hooks:[Br({onFileCreated:e=>j.push(e)})]}]:[]],re=q?[]:[{matcher:"mcp__playwright-test__browser_type",hooks:[Ur({envVars:c})]}];g=l.query({options:{tools:X,allowedTools:Q,canUseTool:async(e,t,{suggestions:r,decisionReason:n})=>V||q?O({decisionReason:n,input:t,suggestions:r,toolName:e}):{behavior:"allow",updatedInput:t},cwd:i,env:{...Y,ANTHROPIC_API_KEY:F,ANTHROPIC_BASE_URL:Ht},hooks:{PostToolUse:te,PreToolUse:re},includePartialMessages:!0,mcpServers:Z,model:"claude-opus-4-5-20251101",permissionMode:"default",systemPrompt:H},prompt:p??$}),"init"===e.mode&&p&&p.pushText($),w.current=async()=>{P();try{await(g?.interrupt?.())}catch{}p?.finish(),A()};try{for await(const e of g){if("stream_event"===e.type){const{event:t}=e;if("content_block_delta"===t?.type){const{delta:e}=t;"text_delta"===e?.type&&e.text&&S({text:e.text})}"message_stop"===t?.type&&p&&p.allowNextTurn();continue}if("assistant"===e.type){const{content:t}=e.message??{};if(Array.isArray(t))for(const e of t)if("tool_use"===e?.type){if(e.name.startsWith("mcp__session-control__"))continue;v({rawName:e.name,toolInput:e.input})}continue}if("result"!==e.type);else{if(u){if("success"===e.subtype){if(ee&&j.length>0){U.default.green("Created files:");for(const e of j)U.default.green(`- ${e}`)}const e=D?U.default.cyan(`📊 View Autoheal Report:\n ${U.default.cyan(U.default.bold(U.default.underline(D)))}`):void 0;N({status:"success",result:e})}else y||(N({error:"Run failed.",status:"error"}),process.exitCode=1);y=!1;break}"success"!==e.subtype?y||(N({error:"Run failed.",status:"error"}),process.exitCode=1):N({status:"success"}),_=!1,y=!1,p?.allowNextTurn()}}}catch(e){y||(N({error:`Agent encountered an error: ${e}`,status:"error"}),process.exitCode=1)}finally{_=!1,y=!1,process.off("uncaughtException",t),p?.finish(),await(J?.cleanup()),await A()}};function fn(e=process.cwd()){let t=r.resolve(e);for(;;){const e=hn(t);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=mn(t);let n=!1,s=t;for(;;){const e=r.join(s,"node_modules"),t=r.join(e,o);if(a.existsSync(t)){n=!0;break}const i=r.dirname(s);if(i===s)break;s=i}return{inNodeModules:n,installed:!0,packageManager:e,packageName:o}}}const n=r.dirname(t);if(n===t)return{inNodeModules:!1,installed:!1,packageManager:void 0};t=n}}function hn(e){const t=r.join(e,"package.json");let n;try{n=a.readFileSync(t,"utf-8")}catch{return}try{return JSON.parse(n)}catch{return}}function mn(e){const t=[["npm","package-lock.json"],["pnpm","pnpm-lock.yaml"],["yarn","yarn.lock"]];let n=e;for(;;){for(const[e,o]of t)if(a.existsSync(r.join(n,o)))return e;const e=r.dirname(n);if(e===n)return;n=e}}function gn(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 _n=[{args:["--trace=on"],description:"Run Playwright tests",name:"test"},{args:[],description:"Install browser dependencies",name:"install"}];function yn(e){const[t,...r]=gn(e),n=[t,...r.slice(0,-1)].join(" ");return(t,r)=>{let o=t.toString();for(const e of _n)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)}}var En=process.argv.findIndex(e=>"-C"===e||"--cwd"===e);-1!==En&&process.argv[En+1]&&(process.chdir(process.argv[En+1]),process.argv.splice(En,2));var bn=new e.Command;bn.name("stably").description("AI-assisted Playwright testing CLI").version(jt),bn.enablePositionalOptions(),bn.showHelpAfterError(),bn.exitOverride();var In=[];bn.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>{In.push(e)}});var wn=()=>{const e=bn.helpInformation().trimEnd();return e?`${e}\n`:""},vn=(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},Tn=()=>{process.stdout.write(wn())},Rn=e=>{process.stdout.write((e=>{const t=e.helpInformation().trimEnd();return t?`${t}\n`:""})(e))};bn.command("help").description("Show help for a command or subcommand").argument("[command...]","Command path to show help for (e.g. create test)").action(e=>{if(!e||0===e.length)return void Tn();const t=vn(bn,e);if(!t)return process.stderr.write(`Unknown command: ${e.join(" ")}\n`),Tn(),void(process.exitCode=1);Rn(t)}),bn.action(()=>pn({mode:"chat",getHelpText:wn})),bn.command("login").description("Authenticate with Stably in your browser").action(fr),bn.command("logout").description("Clear stored Stably credentials").action(async()=>{const e=hr();e&&(m.log.warn(`Environment variables ${U.default.cyan("STABLY_API_KEY")} and ${U.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 tr();if(!t)return void m.outro(e?U.default.yellow("No stored OAuth login found to clear."):U.default.yellow("You are not logged in."));const r=m.spinner();r.start("Logging out..."),await(async e=>{try{await fetch(`${$t}/api/backend/v1/logout`,{body:JSON.stringify({refresh_token:e}),headers:{"Content-Type":"application/json"},method:"POST"})}catch{}})(t.refreshToken),await nr(),await ir(),r.stop(U.default.green("✓ Logged out")),m.outro(U.default.green("You have been logged out successfully."))}),bn.command("whoami").description("Show auth status and current project").action(async()=>{m.log.info(`${U.default.bold("CLI Version:")} ${U.default.cyan(jt)}`);const e=hr();if(e){m.log.info(U.default.dim("Authentication: Environment variables")),m.log.info(` ${U.default.bold("API Key:")} ${U.default.cyan(e.apiKey.slice(0,8))}...`),m.log.info(` ${U.default.bold("Project ID:")} ${U.default.cyan(e.projectId)}`);const t=await tr();if(t){let e;try{e=Wt(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(` ${U.default.bold("OAuth Email:")} ${U.default.cyan(e)}`),m.log.info(` ${U.default.bold("Tip:")} Unset env vars to use OAuth`)}return void m.outro(U.default.green("Authenticated via environment variables"))}const t=await tr();if(!t)return void m.outro(U.default.yellow("Not logged in. Run `stably login` to authenticate."));let r;try{r=Wt(t.accessToken).email}catch{r=void 0}const n=await sr();if(!n)return m.log.info(U.default.dim("Authentication: OAuth (not linked to a project)")),r&&m.log.info(` ${U.default.bold("Email:")} ${U.default.cyan(r)}`),void m.outro(U.default.yellow("Logged in but this directory is not linked to a project. Run `stably login` to link."));const o=await(async()=>or(process.cwd()))(),s=o?R.default.dirname(o):process.cwd(),i=R.default.relative(process.cwd(),s)||".";m.log.info(U.default.dim("Authentication: OAuth")),r&&m.log.info(` ${U.default.bold("Email:")} ${U.default.cyan(r)}`),m.log.info(` ${U.default.bold("Organization:")} ${U.default.cyan(n.orgName)}`),m.log.info(` ${U.default.bold("Project:")} ${U.default.cyan(n.projectName)}`),m.log.info(` ${U.default.bold("Linked at:")} ${U.default.dim(i)}`),m.outro(U.default.green("Authenticated"))}),bn.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 yr(),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 v.startTunnel(`http://localhost:${e.port}`,{subdomain:r});n.stop(`Your local environment is available at: ${U.default.underline(U.default.cyan(o.url))}`)});var Sn=bn.command("create").description("Generate a Playwright test from a prompt").argument("[prompt...]","Prompt describing the test to generate").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 0===r.length?(process.stderr.write("Error: missing required argument: prompt\n"),Rn(Sn),void(process.exitCode=1)):pn({mode:"single",prompt:r,outputDir:t.output})});Sn.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)=>pn({mode:"single",prompt:e,outputDir:t.output})),bn.command("fix").description("Fix failing Playwright tests using debug context").argument("[runId]","Run ID for the failing test suite (defaults to CI's unique runId if available)").action(e=>{const t=e??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(ft))if(ft[r].detect({env:e,cwd:t}))return{isCi:!0,...ft[r].configuration({env:e,cwd:t})};return{isCi:Boolean(e.CI),...(r={env:e,cwd:t},{commit:Me(r),branch:He(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: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}();return t||(process.stderr.write("Run ID is required. Provide <runId>.\n"),process.exit(1)),pn({mode:"fix",runId:t})}),bn.command("init").description("Initialize Playwright and Stably SDK in your project").action(()=>pn({mode:"init"})),_n.forEach(({args:e,description:t,name:o})=>{bn.command(o).description(t).helpOption(!1).helpCommand(!1).allowUnknownOption(!0).allowExcessArguments(!0).passThroughOptions().action(()=>async function({overrideArgs:e,subcommand:t}){const o=process.argv,s=o.findIndex((e,r)=>r>1&&e===t),c=-1===s?[]:o.slice(s+1),l="--"===c[0],d=l?c.slice(1):c;if(!l&&("--help"===d[0]||"-h"===d[0]))return async function({subcommand:e}){const t=_n.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 o=fn();if(!o.installed||!o.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}=o;if(!s)return void r("Could not determine package manager.");r("Playwright options:"),r("");const[i,...a]=gn(s),c=yn(s);return new Promise(t=>{const r=n.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:t});const u=e??[],p=new Set(u.map(e=>{const[t]=e.split("=");return t})),h=[];for(let e=0;e<d.length;e++){const t=d[e],[r]=t.split("=");p.has(r)?!t.includes("=")&&e+1<d.length&&!d[e+1].startsWith("-")&&e++:h.push(t)}const m=[t,...u,...h],g="test"===t?await br():void 0,_="test"===t?function({forwardedArgs:e,hasCredentials:t}){if(!t)return console.warn("[33m⚠️ Stably credentials not found. Test results will not be reported to Stably.[0m"),console.warn("[33m To enable reporting, either:[0m"),console.warn("[33m • Run `npx stably login` to authenticate[0m"),void console.warn("[33m • Set STABLY_API_KEY and STABLY_PROJECT_ID environment variables[0m\n");const o=process.cwd(),s=e=>{const t=function(e){let t=r.resolve(e);for(;;){if([r.join(t,"node_modules","@stablyai","playwright-test"),r.join(t,"node_modules",".pnpm","@stablyai+playwright-test")].some(e=>a.existsSync(e)))return!0;const e=r.dirname(t);if(e===t)return!1;t=e}}(e);return t||(console.warn("[33m⚠️ @stablyai/playwright-test is not installed. Stably reporter will not be injected.[0m"),console.warn("[33m Install it with: npm install @stablyai/playwright-test[0m"),console.warn("[33m Reference: https://docs.stably.ai/getting-started/sdk-setup-guide[0m\n")),t},c=(e,t)=>{try{return function({baseConfigPath:e,projectDir:t}){const o=function(e){try{const t=n.execSync("npm pkg get type",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return"module"===JSON.parse(t.trim())}catch{return!1}}(t),s=o?"mts":"ts",c=r.join(i.tmpdir(),`.stably-playwright-wrapper.${f.randomUUID()}.config.${s}`),l=a.realpathSync(r.dirname(c)),d=r.resolve(e),u=r.relative(l,d).replace(/\\/g,"/"),p=r.dirname(d).replace(/\\/g,"/"),h=`\n// Auto-generated wrapper config by Stably CLI\n// This file injects the Stably reporter and ensures trace is enabled\nimport { resolve, isAbsolute } from 'path';\nimport { createRequire } from 'module';\nimport baseConfig from '${u}';\n\n// Create a require function that resolves modules from the base config directory\n// This is needed because the wrapper is in /tmp but node_modules is in the project\nconst projectRequire = createRequire('${p}/package.json');\n\n// Import defineConfig from @stablyai/playwright-test using projectRequire\n// This ensures the module is resolved from the project's node_modules, not /tmp\nconst { defineConfig } = projectRequire('@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// Dynamically import stablyReporter to handle cases where it's not installed\n// Use projectRequire to resolve from the project's node_modules, not /tmp\nlet stablyReporter: ((options?: { apiKey?: string; projectId?: string; notificationConfigs?: ProjectNotificationConfig[] }) => [string, unknown]) | undefined;\ntry {\n stablyReporter = projectRequire('@stablyai/playwright-test').stablyReporter;\n} catch {\n // @stablyai/playwright-test not installed - reporter injection will be skipped\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 hasStablyReporter = (reporters: unknown): boolean => {\n if (!Array.isArray(reporters)) return false;\n return reporters.some((reporter) => {\n if (typeof reporter === 'string') {\n return reporter.includes('stablyai') || reporter.includes('stably');\n }\n if (Array.isArray(reporter) && typeof reporter[0] === 'string') {\n return reporter[0].includes('stablyai') || reporter[0].includes('stably');\n }\n return false;\n });\n};\n\nconst buildReporterList = () => {\n const existingReporters = baseConfig.reporter;\n\n // If stablyReporter is not available, just use existing reporters\n if (!stablyReporter) {\n return existingReporters;\n }\n\n // If already has stably reporter, don't add another\n if (hasStablyReporter(existingReporters)) {\n return existingReporters;\n }\n\n // Create the stably reporter entry with notification configs\n const [reporterModule, reporterOptions] = stablyReporter({\n apiKey: process.env.STABLY_API_KEY,\n projectId: process.env.STABLY_PROJECT_ID,\n notificationConfigs: extractNotificationConfigs(),\n });\n // Resolve to absolute path so Playwright can find it (pnpm strict mode)\n const reporterAbsolutePath = projectRequire.resolve(reporterModule);\n const stablyReporterEntry = [reporterAbsolutePath, reporterOptions];\n\n // Merge with existing reporters\n if (!existingReporters) {\n return [stablyReporterEntry];\n }\n\n if (Array.isArray(existingReporters)) {\n return [...existingReporters, stablyReporterEntry];\n }\n\n // Single reporter as string - convert to tuple format [name, {}]\n return [[existingReporters, {}], stablyReporterEntry];\n};\n\n// Resolve testDir relative to the base config directory, not the wrapper location\n// This ensures test paths are resolved correctly even though the wrapper is in /tmp\nconst baseConfigDir = '${p}';\nconst resolveTestDir = (testDir?: string): string => {\n if (!testDir) {\n // If no testDir in base config, default to the base config directory\n return baseConfigDir;\n }\n // If testDir is already absolute, use it as-is\n if (isAbsolute(testDir)) {\n return testDir;\n }\n // Otherwise, resolve it relative to the base config directory\n return resolve(baseConfigDir, testDir);\n};\n\nexport default defineConfig({\n ...baseConfig,\n testDir: resolveTestDir(baseConfig.testDir),\n use: {\n ...baseConfig.use,\n trace: 'on',\n },\n reporter: buildReporterList(),\n});\n`.trim();return a.existsSync(l)||a.mkdirSync(l,{recursive:!0}),a.writeFileSync(c,h,"utf-8"),c}({baseConfigPath:e,projectDir:t})}catch{return void console.warn("[33m⚠️ Could not create Stably wrapper config. Reporter injection skipped.[0m")}};if(e.some(e=>"--config"===e||"-c"===e||e.startsWith("--config=")||e.startsWith("-c="))){const t=e.findIndex(e=>"--config"===e||"-c"===e);if(-1!==t&&e[t+1]){const n=r.resolve(o,e[t+1]),i=r.dirname(n);if(!s(i))return;const a=c(n,i);if(!a)return;return e[t+1]=a,a}const n=e.findIndex(e=>e.startsWith("--config=")||e.startsWith("-c="));if(-1!==n){const t=r.resolve(o,e[n].split("=")[1]),i=r.dirname(t);if(!s(i))return;const a=c(t,i);if(!a)return;const l=e[n].startsWith("--config=")?"--config=":"-c=";return e[n]=`${l}${a}`,a}}const l=Mr(o);if(!l)return;const d=r.dirname(l);if(!s(d))return;const u=c(l,d);return u?(e.push("--config",u),u):void 0}({forwardedArgs:m,hasCredentials:null!=g}):void 0;!function(e,t={}){const r=fn();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:o}=r;o||(console.error("Playwright installation not found. Could not determine your package manager (tried pnpm, yarn, and npm)."),process.exit(1));const[s,...i]=gn(o),a=Er(t.env),c=n.spawn(s,[...i,...e],{stdio:["inherit","pipe","pipe"],env:{...a,...process.env.CI?{}:{FORCE_COLOR:"1"}}}),l=yn(o);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?.())};c.on("close",e=>{u(),process.exit(e??0)});const p=e=>{u(),c.kill(e);const t="SIGINT"===e?130:143;process.exit(t)};process.on("SIGINT",p),process.on("SIGTERM",p)}(m,{env:g,onClose:()=>{var e;(e=_)&&a.existsSync(e)&&a.rmSync(e)}})}({overrideArgs:e,subcommand:o}))});var Cn=()=>{0!==In.length&&(process.stderr.write(In.join("")),In=[])};(async()=>{try{await bn.parseAsync(process.argv)}catch(e){if(!(e=>!!e&&"object"==typeof e&&"code"in e)(e))throw Cn(),e;const t="number"==typeof e.exitCode?e.exitCode:1,r=process.argv.slice(2).find(e=>!e.startsWith("-")),n=!!r&&!!vn(bn,[r]);if(("commander.excessArguments"===e.code||"commander.unknownCommand"===e.code)&&r&&!n)return In=[],process.stderr.write(`command '${r}' not found\n`),Tn(),void(process.exitCode=t);Cn(),process.exitCode=t}})();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "stably",
|
|
3
|
-
"version": "4.3.
|
|
3
|
+
"version": "4.3.2",
|
|
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",
|