stably 4.0.5 → 4.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var e=require("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("@clack/prompts"),p=require("picocolors"),h=require("readline/promises"),f=require("zod"),m=require("fs/promises"),_=require("open"),g=require("http"),E=require("crypto"),y=require("react"),I=require("react/jsx-runtime"),b=require("simple-git"),T=require("zod/v3"),v=require("@stablyhq/runner-sdk");function R(e){return e&&e.__esModule?e:{default:e}}var S=R(r),w=R(n),C=R(o),A=R(i),U=R(a),x=R(p),L=R(f),O=R(_),P=R(g),B=R(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)),K=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)}}}),Y=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?K():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}}}}),V=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=Y(),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),h=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;s(p(h,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}}),q=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js"(e,t){var r=H("path"),n=V(),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=q(),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}}},he=F(re());function fe(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:_e+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),_e=34,ge=[{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"}],Ee=()=>{const e=(()=>{const e=64-_e+1;return Array.from({length:e},me)})();return[...ge,...e].map(ye)},ye=({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}},Ie=({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}],be=(()=>{const e=Ee();return Object.fromEntries(e.map(Ie))})();(()=>{const e=Ee(),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 Te=({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 h=void 0===(o=null===o?void 0:o)?void 0:be[o].description,f=(({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:h,exitCode:s,isCanceled:l}),m=`Command ${f}: ${i}`,_="[object Error]"===Object.prototype.toString.call(n),g=_?`${m}\n${n.message}`:m,E=[g,t,e].filter(Boolean).join("\n");return _?(n.originalMessage=n.message,n.message=E):n=new Error(E),n.shortMessage=g,n.command=i,n.escapedCommand=a,n.exitCode=s,n.signal=o,n.signalDescription=h,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"],Re=[];Re.push("SIGHUP","SIGINT","SIGTERM"),"win32"!==process.platform&&Re.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),"linux"===process.platform&&Re.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var Se=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,we=Symbol.for("signal-exit emitter"),Ce=globalThis,Ae=Object.defineProperty.bind(Object),Ue=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(Ce[we])return Ce[we];Ae(Ce,we,{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}},xe=class{},Le=globalThis.process;Se(Le)?new class extends xe{#e="win32"===Le.platform?"SIGINT":"SIGHUP";#t=new Ue;#r;#n;#o;#s={};#i=!1;constructor(e){super(),this.#r=e,this.#s={};for(const t of Re)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(!Se(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 Re)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,Re.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 Se(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&&Se(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)}}(Le):new class extends xe{onExit(){return()=>{}}load(){}unload(){}},new TextEncoder,F(ne());var Oe=(async()=>{})().constructor.prototype;["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(Oe,e)]);var Pe=(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=he.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=fe({env:e={...e}});return t.path=e[r],e[r]=(({cwd:e=C.default.cwd(),path:t=C.default.env[fe()],preferLocal:r=!0,execPath:n=C.default.execPath,addExecPath:o=!0}={})=>{const i=e instanceof URL?s.fileURLToPath(e):e,a=S.default.resolve(i),c=[];return r&&((e,t)=>{let r;for(;r!==t;)e.push(S.default.join(t,"node_modules/.bin")),r=t,t=S.default.resolve(t,"..")})(c,a),o&&((e,t,r)=>{const n=t instanceof URL?s.fileURLToPath(t):t;e.push(S.default.resolve(r,n,".."))})(c,n,a),[...c,t].join(S.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"===S.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)=>Pe(e,t).join(" "))(e,t),s=((e,t)=>Pe(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=w.default.spawnSync(n.file,n.args,{...n.options,input:i})}catch(e){throw Te({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=Te({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 Ke(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:Ke(e.BUILDKITE_REPO),pr:t,isPr:r,prBranch:r?e.BUILDKITE_BRANCH:void 0,root:e.BUILDKITE_BUILD_CHECKOUT_PATH}}},Ye={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}`}}},Ve="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:`${Ve}/build/${e.CIRRUS_BUILD_ID}`,job:e.CIRRUS_TASK_ID,jobUrl:`${Ve}/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}}},qe={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)]))},ht={appveyor:se,azurePipelines:ce,bamboo:le,bitbucket:de,bitrise:ue,buddy:pe,buildkite:ze,circleci:Ye,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:qe,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}}}},ft={bodySerializer:e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t)},mt=({allowReserved:e,explode:t,name:r,style:n,value:o})=>{if(!t){const t=(e?o:o.map(e=>encodeURIComponent(e))).join((e=>{switch(e){case"form":default:return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20"}})(n));switch(n){case"label":return`.${t}`;case"matrix":return`;${r}=${t}`;case"simple":return t;default:return`${r}=${t}`}}const s=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(n),i=o.map(t=>"label"===n||"simple"===n?e?t:encodeURIComponent(t):_t({allowReserved:e,name:r,value:t})).join(s);return"label"===n||"matrix"===n?s+i:i},_t=({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)}`},gt=({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])=>_t({allowReserved:e,name:"deepObject"===n?`${r}[${t}]`:t,value:o})).join(i);return"label"===n||"matrix"===n?i+a:a},Et=/\{[^{}]+\}/g;function yt(e){const t=void 0!==e.body;return t&&e.bodySerializer?"serializedBody"in e?void 0!==e.serializedBody&&""!==e.serializedBody?e.serializedBody:null:""!==e.body?e.body:null:t?e.body:void 0}var It,bt=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=mt({allowReserved:i.allowReserved,explode:!0,name:o,style:"form",value:s,...i.array});e&&n.push(e)}else if("object"==typeof s){const e=gt({allowReserved:i.allowReserved,explode:!0,name:o,style:"deepObject",value:s,...i.object});e&&n.push(e)}else{const e=_t({allowReserved:i.allowReserved,name:o,value:s});e&&n.push(e)}}return n.join("&")},vt=(e,t)=>!!t&&!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`)),Rt=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(Et);if(n)for(const t of n){let n=!1,o=t.substring(1,t.length-1),s="simple";o.endsWith("*")&&(n=!0,o=o.substring(0,o.length-1)),o.startsWith(".")?(o=o.substring(1),s="label"):o.startsWith(";")&&(o=o.substring(1),s="matrix");const i=e[o];if(null==i)continue;if(Array.isArray(i)){r=r.replace(t,mt({explode:n,name:o,style:s,value:i}));continue}if("object"==typeof i){r=r.replace(t,gt({explode:n,name:o,style:s,value:i,valueOnly:!0}));continue}if("matrix"===s){r=r.replace(t,`;${_t({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}),St=(e,t)=>{const r={...e,...t};return r.baseUrl?.endsWith("/")&&(r.baseUrl=r.baseUrl.substring(0,r.baseUrl.length-1)),r.headers=Ct(e.headers,t.headers),r},wt=e=>{const t=[];return e.forEach((e,r)=>{t.push([r,e])}),t},Ct=(...e)=>{const t=new Headers;for(const r of e){if(!r)continue;const e=r instanceof Headers?wt(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},At=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}},Ut=Tt({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),xt={"Content-Type":"application/json"},Lt=(e={})=>({...ft,headers:xt,parseAs:"auto",querySerializer:Ut,...e}),Ot=(e={})=>{let t=St(Lt(),e);const r=()=>({...t}),n={error:new At,request:new At,response:new At},o=async e=>{const r={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:Ct(t.headers,e.headers),serializedBody:void 0};return r.security&&await(async({security:e,...t})=>{for(const r of e){if(vt(t,r.name))continue;const e=await bt(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:Rt(r)}},s=async e=>{const{opts:t,url:r}=await o(e),s={redirect:"follow",...t,body:yt(t)};let i=new Request(r,s);for(const e of n.request.fns)e&&(i=await e(i,t));const a=t.fetch;let c;try{c=await a(i)}catch(e){let r=e;for(const o of n.error.fns)o&&(r=await o(e,void 0,i,t));if(r=r||{},t.throwOnError)throw r;return"data"===t.responseStyle?void 0:{error:r,request:i,response:void 0}}for(const e of n.response.fns)e&&(c=await e(c,i,t));const l={request:i,response:c};if(c.ok){const e=("auto"===t.parseAs?(e=>{if(!e)return"stream";const t=e.split(";")[0]?.trim();return t?t.startsWith("application/json")||t.endsWith("+json")?"json":"multipart/form-data"===t?"formData":["application/","audio/","image/","video/"].some(e=>t.startsWith(e))?"blob":t.startsWith("text/")?"text":void 0:void 0})(c.headers.get("Content-Type")):t.parseAs)??"json";if(204===c.status||"0"===c.headers.get("Content-Length")){let r;switch(e){case"arrayBuffer":case"blob":case"text":r=await c[e]();break;case"formData":r=new FormData;break;case"stream":r=c.body;break;default:r={}}return"data"===t.responseStyle?r:{data:r,...l}}let r;switch(e){case"arrayBuffer":case"blob":case"formData":case"json":case"text":r=await c[e]();break;case"stream":return"data"===t.responseStyle?c.body:{data:c.body,...l}}return"json"===e&&(t.responseValidator&&await t.responseValidator(r),t.responseTransformer&&(r=await t.responseTransformer(r))),"data"===t.responseStyle?r:{data:r,...l}}const d=await c.text();let u;try{u=JSON.parse(d)}catch{}const p=u??d;let h=p;for(const e of n.error.fns)e&&(h=await e(p,c,i,t));if(h=h||{},t.throwOnError)throw h;return"data"===t.responseStyle?void 0:{error:h,...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))),h=async function*(){let c=s??3e3,h=0;const f=d.signal??(new AbortController).signal;for(;!f.aborted;){h++;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:f};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 h=p.body.pipeThrough(new TextDecoderStream).getReader();let m="";const _=()=>{try{h.cancel()}catch{}};f.addEventListener("abort",_);try{for(;;){const{done:e,value:t}=await h.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{f.removeEventListener("abort",_),h.releaseLock()}break}catch(e){if(t?.(e),void 0!==i&&h>=i)break;const r=Math.min(c*2**(h-1),a??3e4);await p(r)}}}();return{stream:h}})({...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:Rt,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=St(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")}},Pt=Ot(Lt({baseUrl:"https://api.stably.ai"})),Bt="x-stably-org-id",Nt="4.0.2",Dt=process.env.STABLY_API_URL||"https://api.stably.ai",jt=process.env.AUTH_URL||"https://auth.stably.ai",kt=process.env.AUTH_CLIENT_ID||"288007877071cce81f269428ea78653a",Mt=process.env.AI_PROXY_URL||"https://ai-proxy.stably.ai",$t="http://localhost:9876/auth/callback",Ht=()=>It||(It=Ot(Lt({baseUrl:Dt,headers:{"X-STABLY-CLI-VERSION":Nt,"X-STABLY-SOURCE":"cli"}}))),Gt=f.z.object({org_id:f.z.string(),org_name:f.z.string()}),Ft=f.z.object({email:f.z.string(),org_id_to_org_member_info:f.z.record(f.z.string(),Gt).optional(),org_member_info:Gt.optional(),user_id:f.z.string()});f.z.object({email:f.z.string(),firstName:f.z.string().optional(),lastName:f.z.string().optional(),organizations:f.z.array(f.z.object({id:f.z.string(),name:f.z.string()})),userId:f.z.string()});var Kt=f.z.object({projects:f.z.array(f.z.object({id:f.z.string(),name:f.z.string()}))}),zt=f.z.object({accessToken:f.z.string(),expiresInSeconds:f.z.number()}),Yt=async(e,t)=>{const r=await(n={body:{accessToken:e,orgId:t},client:Ht()},(n.client??Pt).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 zt.parse(r.data)},Vt=S.default.join(A.default.homedir(),".stably"),Wt=S.default.join(Vt,"auth.json"),qt=".stably",Jt="project.json",Xt=L.default.object({accessToken:L.default.string(),expiresAt:L.default.number(),idToken:L.default.string().optional(),refreshToken:L.default.string()}),Qt=L.default.object({orgId:L.default.string(),orgName:L.default.string(),projectId:L.default.string(),projectName:L.default.string()}),Zt=async()=>{try{const e=await m.readFile(Wt,"utf-8");return Xt.parse(JSON.parse(e))}catch{return}},er=async e=>{await m.mkdir(Vt,{recursive:!0}),await m.writeFile(Wt,JSON.stringify(e,null,2),{mode:384})},tr=async()=>{try{await m.unlink(Wt)}catch{}},rr=async e=>{let t=e;const{root:r}=S.default.parse(t);for(;t!==r;){const e=S.default.join(t,qt);try{return await m.access(e),e}catch{t=S.default.dirname(t)}}},nr=async()=>{try{const e=await rr(process.cwd());if(!e)return;const t=S.default.join(e,Jt),r=await m.readFile(t,"utf-8");return Qt.parse(JSON.parse(r))}catch{return}},or=async()=>{try{const e=await rr(process.cwd());e&&await m.unlink(S.default.join(e,Jt))}catch{}},sr=e=>Date.now()>=e.expiresAt-3e5,ir=async e=>{const t=new URLSearchParams({client_id:kt,grant_type:"refresh_token",refresh_token:e}),r=await fetch(`${jt}/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}},ar=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`,cr=(e,t,r)=>{e.writeHead(t,{"Content-Type":"text/html"}),e.end(r)},lr=(e,t)=>{const r=new URLSearchParams({client_id:kt,code_challenge:e,code_challenge_method:"S256",redirect_uri:$t,response_type:"code",state:t});return`${jt}/propelauth/oauth/authorize?${r.toString()}`},dr=async e=>{const t=u.spinner();let r;t.start("Loading user info...");try{r=(e=>{try{const t=Ft.parse((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)})(e));let r;return 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}]:[],{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"}`)}})(e.accessToken),t.stop(x.default.green(`✓ Logged in as ${x.default.cyan(r.email)}`))}catch(e){t.stop(x.default.red("✗ Failed to load user info"));const r=e instanceof Error?e.message:"Unknown error";return u.log.error(r),{success:!1}}const n=await(async e=>{if(0===e.length)return void u.log.error("You don't belong to any organizations.");if(1===e.length)return u.log.info(`Using organization: ${x.default.cyan(e[0].name)}`),e[0];if(!process.stdin.isTTY)return u.log.info(`Auto-selecting organization: ${x.default.cyan(e[0].name)}`),e[0];const t=await u.select({message:"Select an organization",options:e.map(e=>({label:e.name,value:e.id}))});return u.isCancel(t)?void 0:e.find(e=>e.id===t)})(r.organizations);if(!n)return u.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(x.default.green("✓ Credentials obtained"))}catch(e){t.stop(x.default.red("✗ Failed to get org credentials"));const r=e instanceof Error?e.message:"Unknown error";return u.log.error(r),{success:!1}}const s=await(async(e,t)=>{const r=u.spinner();let n;r.start("Loading projects...");try{n=await(async(e,t)=>{const r=await(n={auth:`Bearer ${e}`,client:Ht(),path:{orgId:t}},(n.client??Pt).get({security:[{name:"authorization",type:"apiKey"}],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 Kt.parse(r.data).projects})(e,t),r.stop(x.default.green("✓ Projects loaded"))}catch(e){r.stop(x.default.red("✗ Failed to load projects"));const t=e instanceof Error?e.message:"Unknown error";return void u.log.error(t)}if(0===n.length)return u.log.error("No projects found in this organization."),void u.log.info(`Create a project at ${x.default.underline(x.default.cyan("https://app.stably.ai"))}`);if(1===n.length)return u.log.info(`Using project: ${x.default.cyan(n[0].name)}`),n[0];if(!process.stdin.isTTY)return u.log.info(`Auto-selecting project: ${x.default.cyan(n[0].name)}`),n[0];const o=await u.select({message:"Select a project",options:n.map(e=>({label:e.name,value:e.id}))});return u.isCancel(o)?void 0:n.find(e=>e.id===o)})(o.accessToken,n.id);return s?(await(async e=>{const t=S.default.join(process.cwd(),qt),r=S.default.join(t,Jt);await m.mkdir(t,{recursive:!0}),await m.writeFile(r,JSON.stringify(e,null,2)),await(async e=>{const t=S.default.join(e,".gitignore");try{if((await m.readFile(t,"utf-8")).split("\n").some(e=>".stably"===e.trim()))return;await m.appendFile(t,"\n# Stably CLI\n.stably\n")}catch{await m.writeFile(t,"# Stably CLI\n.stably\n")}})(process.cwd())})({orgId:n.id,orgName:n.name,projectId:s.id,projectName:s.name}),u.log.info(x.default.dim("Linked this directory to your Stably project.")),{scopedTokens:o,success:!0}):(u.log.warn("Project selection cancelled."),{success:!1})},ur=async()=>{const e=await Zt();if(e){if(!sr(e)){if(await nr())return void u.outro(x.default.yellow("You are already logged in. Run `stably logout` first to log out."));u.log.info("You are logged in but haven't selected a project yet.");const t=await dr(e);return void(t.success?(await er(t.scopedTokens),u.outro(x.default.green("Setup complete! You can now use Stably CLI."))):u.outro(x.default.yellow("Setup incomplete. Run `stably login` to try again.")))}const t=u.spinner();t.start("Refreshing session...");try{const r=await ir(e.refreshToken);t.stop(x.default.green("✓ Session refreshed"));const n=await nr();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 er(o),t.stop(x.default.green("✓ Credentials obtained")),u.outro(x.default.green("Login successful"))}catch{await er(r),t.stop(x.default.yellow("Using full credentials")),u.outro(x.default.green("Login successful"))}}else{const e=await dr(r);e.success?(await er(e.scopedTokens),u.outro(x.default.green("Setup complete! You can now use Stably CLI."))):u.outro(x.default.yellow("Setup incomplete. Run `stably login` to try again."))}return}catch{t.stop(x.default.yellow("Session expired, proceeding with fresh login...")),await tr(),await or()}}const{authorizeUrl:t,waitForCallback:r}=(()=>{const{authorizeUrl:e,codeVerifier:t,state:r}=(()=>{const e=B.default.randomBytes(32).toString("base64url"),t=(r=e,B.default.createHash("sha256").update(r).digest("base64url"));var r;const n=B.default.randomBytes(16).toString("base64url");return{authorizeUrl:lr(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=P.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?(cr(r,400,ar(d)),o(),i.close(),void e({error:d,success:!1})):c&&l?l!==n?(cr(r,400,ar("Invalid state parameter (possible CSRF attack)")),o(),i.close(),void e({error:"State mismatch",success:!1})):(cr(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})):(cr(r,400,ar("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:kt,code:e,code_verifier:t,grant_type:"authorization_code",redirect_uri:$t}),n=await fetch(`${jt}/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)}})();u.log.info("Opening browser for authentication..."),u.log.info(x.default.dim("If browser doesn't open, visit:")),u.log.info(x.default.underline(x.default.cyan(t)));try{await O.default(t)}catch{u.log.warn("Could not open browser automatically. Please open the URL above manually.")}const n=u.spinner();let o;n.start("Waiting for authentication...");try{o=await r(),n.stop(x.default.green("✓ Authentication successful"))}catch(e){n.stop(x.default.red("✗ Authentication failed"));const t=e instanceof Error?e.message:"Unknown error";u.outro(x.default.red(`Login failed: ${t}`)),process.exit(1)}const i=await dr(o);i.success?(await er(i.scopedTokens),u.outro(x.default.green("Setup complete! You can now use Stably CLI."))):(u.outro(x.default.yellow("Setup incomplete. Run `stably login` to try again.")),process.exit(1))},pr=()=>{const e=process.env.STABLY_API_KEY,t=process.env.STABLY_PROJECT_ID;if(e&&t)return{apiKey:e,projectId:t}},hr=async()=>{const e=await Zt();if(e){if(!sr(e))return e;try{const t=await ir(e.refreshToken),r=await nr();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 er(n),n}catch{return await er(t),t}return await er(t),t}catch{return}}},fr=async(e={})=>{const t=pr();if(t)return{auth:t,type:"env"};let r=await hr(),n=r?await nr():void 0;const o=process.stdin.isTTY&&process.stdout.isTTY;if((!r||!n)&&e.autoLogin&&o){r?u.log.info("You are logged in but need to select an organization and project."):u.log.info("You are not logged in."),u.log.info("Press Enter to log in."),process.stdout.write(`${x.default.dim("Alternatively, set environment variables for an org API key:")}\n${x.default.dim(" STABLY_API_KEY=... STABLY_PROJECT_ID=... stably")}\n`),process.stdout.write("\n");const e=h.createInterface({input:process.stdin,output:process.stdout});try{await e.question(x.default.dim("Press Enter to continue... "))}finally{e.close()}await ur(),r=await hr(),n=r?await nr():void 0}return r||(u.outro(x.default.red("You are not logged in. Run `stably login` to authenticate.")),process.exit(1)),n||(u.outro(x.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"}},mr=e=>e?{[Bt]:e}:void 0,_r=f.z.object({context:f.z.string().min(1)});function gr(e){return/^\.env(\..*)?$/.test(e)}function Er(e){return Boolean(e&&"object"==typeof e&&"tool_input"in e&&e.tool_input&&"object"==typeof e.tool_input)}function yr({input:e,pathKey:t}){if(!Er(e))return{decision:"block",reason:`Invalid tool call format: Expected an object with 'tool_input' property. Please ensure the tool call follows the correct structure: { tool_input: { ${t}: "path/to/file" } }`,success:!1,systemMessage:"Tool call blocked due to invalid input format"};const r=e.tool_input;return t in r?"string"==typeof r[t]?{path:r[t],success:!0}:{decision:"block",reason:`Invalid tool call format: The '${t}' parameter must be a string containing the file path, but received ${typeof r[t]}. Please provide a valid file path as a string. Example: { tool_input: { ${t}: "src/example.ts" } }`,success:!1,systemMessage:"Tool call blocked due to invalid parameter type"}:{decision:"block",reason:`Invalid tool call format: Missing required parameter '${t}'. Please provide the file path using the '${t}' parameter. Example: { tool_input: { ${t}: "path/to/file" } }`,success:!1,systemMessage:"Tool call blocked due to missing required parameters"}}function Ir({action:e,fileCheck:t,getBlockMessage:r,pathKey:n}){return async o=>{const s=yr({input:o,pathKey:n});if(!s.success)return s;const i=s.path.replace(/\\/g,"/"),a=i.split("/").pop()||i;return t(a)?{decision:"block",reason:r("reading"===e?"Access to":"writing"===e?"Writing to":"editing"===e?"Editing":"Searching in"),systemMessage:"AI blocked due to accessing sensitive content"}:{decision:"approve"}}}function br({action:e,pathKey:t}){return Ir({action:e,fileCheck:gr,getBlockMessage:e=>`${e} .env files is not allowed. Environment variables and secrets should be managed in Stably's Test Data section instead. You can access these values using process.env in your test code.`,pathKey:t})}function Tr({action:e,pathKey:t}){return Ir({action:e,fileCheck:e=>".gitignore"===e,getBlockMessage:()=>"Modifying .gitignore is not allowed. The .gitignore file is managed by the system and cannot be changed.",pathKey:t})}function vr({action:e,pathKey:t}){return Ir({action:e,fileCheck:e=>".gitattributes"===e,getBlockMessage:()=>"Modifying .gitattributes is not allowed. The .gitattributes file is managed by the system and cannot be changed.",pathKey:t})}function Rr({action:e,pathKey:t}){return Ir({action:e,fileCheck:e=>".lfsconfig"===e,getBlockMessage:()=>"Modifying .lfsconfig is not allowed. The .lfsconfig file is managed by the system and cannot be changed.",pathKey:t})}var Sr=/\.(spec|test)\.(c|m)?(ts|tsx|js|jsx)$/;function wr({pathKey:e}){return async t=>{const r=yr({input:t,pathKey:e});if(!r.success)return r;const n=r.path.replace(/\\/g,"/").split("/").pop()||r.path;return Sr.test(n)?n.endsWith(".spec.ts")?{decision:"approve"}:{decision:"block",reason:`Test files must use the .spec.ts extension. The file "${n}" is not supported by Stably. Please use ".spec.ts" as the extension instead.`,systemMessage:"Tool call blocked due to unsupported test file extension"}:{decision:"approve"}}}function Cr({action:e,pathKey:t,workDir:n}){return async o=>{const s=yr({input:o,pathKey:t});if(!s.success)return s;const i=s.path;try{return function({targetPath:e,workDir:t}){const n=function(e){if(a.existsSync(e))return a.realpathSync.native(e);let t=e;const n=[];for(;!a.existsSync(t);){const o=r.dirname(t);if(o===t)return r.resolve(e);n.unshift(t.slice(o.length+1)),t=o}const o=a.realpathSync.native(t);return n.length>0?r.resolve(o,...n):o}(e),o=a.realpathSync.native(t),s=n.endsWith(r.sep)?n:n+r.sep,i=o.endsWith(r.sep)?o:o+r.sep;return s.startsWith(i)||n===o}({targetPath:r.resolve(n,i),workDir:n})?{decision:"approve"}:{decision:"block",reason:`${"reading"===e?"Accessing":"writing"===e?"Writing to":"editing"===e?"Editing":"Searching in"} files outside the workspace is not allowed. The path "${i}" resolves to a location outside your workspace directory. Please only access files within your workspace.`,systemMessage:"Tool call blocked due to path traversal attempt"}}catch(e){return{decision:"block",reason:`Unable to validate file path "${i}". Please ensure the path is valid and try again. Error: ${e instanceof Error?e.message:"Unknown error"}`,systemMessage:"Tool call blocked due to path validation error"}}}}var Ar=e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"text"===t.type&&"string"==typeof t.text},Ur=e=>null!=e&&"object"==typeof e&&"tool_response"in e,xr=e=>{if(!e||"object"!=typeof e)return;const t=e;return Array.isArray(t.tool_response)?t.tool_response:void 0},Lr=e=>{const t=xr(e);if(t)return t.filter(Ar).map(e=>e.text).join("\n")||void 0},Or=/\u001b\[[0-9;]*m/g,Pr=e=>e.replace(Or,""),Br=/\$\{process\.env\.([A-Z_][A-Z0-9_]*)\}/g;function Nr({envVars:e}){return async t=>{if(!Er(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(Br,(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 Dr({onResult:e}){return async t=>{if(!Ur(t))return{decision:"approve"};const r=Lr(t);if(!r)return{decision:"approve"};const n=function(e){const t=Pr(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 jr({onResult:e}){return async t=>{if(!Ur(t))return{decision:"approve"};const r=Lr(t);if(!r)return{decision:"approve"};const n=function(e){const t=Pr(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 kr=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()})}},Mr=10240,$r=async({defaultContent:e,fileName:t,filePath:r})=>{try{const e=(await m.stat(r)).size,n=await m.readFile(r,"utf-8"),o=Buffer.byteLength(n,"utf-8");if(o<=Mr)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<=Mr?s:s.slice(0,Mr)+`\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(t){let r;if(t&&"object"==typeof t&&"code"in t){const e=t.code;"string"==typeof e&&(r=e)}return e}},Hr=async({defaultContent:e,dirName:t,dirPath:r})=>{try{const e=await m.readdir(r);return e.length>0?e.join("\n"):"(empty)"}catch(t){let r;if(t&&"object"==typeof t&&"code"in t){const e=t.code;"string"==typeof e&&(r=e)}return e}},Gr=e=>{const t=["mcp__playwright-test__","mcp__auto-heal-report__"];for(const r of t)if(e.startsWith(r))return e.slice(r.length).replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase());return e},Fr=T.z.object({bucket:T.z.string(),key:T.z.string()}),Kr=T.z.object({diffBucketPath:Fr,expiresInSeconds:T.z.number(),key:T.z.string(),uploadUrl:T.z.string()}),zr=["test","bug","other"],Yr={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."},Vr=e=>Yr[e],{zSuiteAutoHealReport:Wr}=function(e){const t=e.enum(zr),r=["Classification of the root cause:","",`- test: ${Vr("test")}`,`- bug: ${Vr("bug")}`,`- other: ${Vr("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.")})}}(T.z),qr=({authHeader:e,orgId:t,runId:r})=>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:Wr},async({report:n})=>{const o=b.simpleGit({baseDir:process.cwd(),maxConcurrentProcesses:1}),s=await o.diff(),i=Wr.parse(n);try{await(async({authHeader:e,orgId:t,report:r,runId:n})=>{const o=await(s={auth:e,body:{report:JSON.stringify(r)},client:Ht(),headers:mr(t),path:{runId:n}},(s.client??Pt).post({security:[{name:"authorization",type:"apiKey"}],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:t,report:i,runId:r});const{uploadUrl:n}=await(async({authHeader:e,contentType:t="text/plain",orgId:r,runId:n})=>{const o=await(s={auth:e,body:{contentType:t},client:Ht(),headers:mr(r),path:{runId:n}},(s.client??Pt).post({security:[{name:"authorization",type:"apiKey"}],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=Kr.parse(o.data);return{diffBucketPath:i.diffBucketPath,expiresInSeconds:i.expiresInSeconds,key:i.key,uploadUrl:i.uploadUrl}})({authHeader:e,contentType:"text/plain",orgId:t,runId:r});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:n})}catch(e){return{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"}),Jr=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]"),Xr=(e,t)=>({message:Jr(e),status:t?.status,statusText:t?.statusText}),Qr=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"]),Zr=["mcp__playwright-test","Read","Write","Edit","Glob","Grep"],en=async e=>{const t=await fr({autoLogin:"chat"===e.mode}),r=(e=>"env"===e.type?e.auth.apiKey:`Bearer ${e.auth.accessToken}`)(t),n="oauth"===t.type?t.auth.context.orgId:void 0,o=S.default.resolve(process.cwd()),s=S.default.join(o,".env"),i=U.default.existsSync(s)&&U.default.statSync(s).isFile()?d.parse(U.default.readFileSync(s,"utf8")):{},a="chat"!==e.mode,c="chat"===e.mode?new kr:void 0,u="chat"===e.mode?e.getHelpText:void 0,p={log:[],promptDisplay:"chat"===e.mode?"Ask Stably to build tests for you":"fix"===e.mode?"Fixing broken tests":(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt)||"<empty prompt>",status:"running"};let h,f=a,m=!1;const _={current:e=>{}},{addTool:g,addToolResult:E,appendText:b,appendUserMessage:T,cleanup:v,setStatus:R}=await(async(e,t)=>{const{Box:r,Text:n,render:o,useInput:s}=await import("ink"),i=({label:e})=>{const[t,r]=y.useState(0);return y.useEffect(()=>{const e=setInterval(()=>r(e=>(e+1)%c.length),80);return()=>clearInterval(e)},[]),I.jsxs(n,{color:"yellow",children:[c[t]," ",e]})},a=()=>{const[e,t]=y.useState(!0);return y.useEffect(()=>{const e=setInterval(()=>t(e=>!e),500);return()=>clearInterval(e)},[]),e?I.jsx(n,{inverse:!0,children:" "}):I.jsx(n,{children:" "})},c=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],l=({onSend:e,state:t})=>{const[o,c]=y.useState("");s((t,r)=>{if(e&&(!r.ctrl||"c"!==t)){if(r.return){const t=o.trim();return t&&e(t),void c("")}r.backspace||r.delete?c(e=>e.slice(0,-1)):c(e=>`${e}${t}`)}});const l=y.useMemo(()=>"running"===t.status?I.jsx(i,{label:"Working"}):"success"!==t.status?I.jsx(n,{color:"red",children:"✖ Failed"}):void 0,[t.status]),d=!!e&&"running"===t.status&&0===t.log.length&&!t.resultText&&!t.errorText,u="running"===t.status&&!d||t.log.length>0||t.resultText||t.errorText||"running"!==t.status;return I.jsxs(r,{flexDirection:"column",children:[I.jsxs(r,{flexDirection:"column",flexShrink:0,children:[I.jsx(n,{color:"cyan",bold:!0,children:"Stably Agent"}),t.promptDisplay&&I.jsx(r,{flexDirection:"column",marginTop:1,children:I.jsx(n,{color:"gray",children:t.promptDisplay})})]}),I.jsxs(r,{flexDirection:"column",flexGrow:1,justifyContent:t.log.length>0?"flex-end":"flex-start",minHeight:0,children:[t.log.length>0&&I.jsx(r,{flexDirection:"column",marginTop:1,children:t.log.map(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))}),"error"===t.status&&t.errorText&&I.jsx(r,{marginTop:1,children:I.jsx(n,{color:"red",children:t.errorText})})]}),u&&I.jsx(r,{flexDirection:"column",flexShrink:0,marginTop:1,children:l}),e&&I.jsxs(r,{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:">"})," ",o,I.jsx(a,{})]})]})]})};let d=e;const u=o(I.jsx(l,{onSend:t?.onSend,state:d})),p=()=>{d={...d},u.rerender(I.jsx(l,{onSend:t?.onSend,state:d}))};return{addTool:({rawName:e})=>{d.log=[...d.log,{content:Gr(e),id:d.log.length,kind:"tool"}],p()},addToolResult:({message:e})=>{d.log=[...d.log,{content:e,id:d.log.length,kind:"tool_result"}],p()},appendText:({text:e})=>{if(!e)return;const t=d.log.at(-1),r=t&&"text"===t.kind?e:e.replace(/^\s*\n+/,"");t&&"text"===t.kind?d.log=[...d.log.slice(0,-1),{...t,content:`${t.content}${r}`}]:d.log=[...d.log,{content:r,id:d.log.length,kind:"text"}],p()},appendUserMessage:({text:e})=>{e&&(d.log=[...d.log,{content:e,id:d.log.length,kind:"user"}],p())},cleanup:async()=>{u.unmount(),await u.waitUntilExit()},setStatus:({error:e,result:t,status:r})=>{d.errorText=e,d.resultText=t,d.status=r,p()}}})(p,"chat"===e.mode?{onSend:e=>_.current(e)}:void 0);let w=p.status;const C=({error:e,result:t,status:r})=>{w=r,R({error:e,result:t,status:r})};_.current=e=>{if("/help"===e.trim()){f&&c&&(m=!0,h?.interrupt?.(),c.allowNextTurn(),f=!1),"running"===w&&C({status:"success"}),T({text:e});const t=u?.();return void b({text:t??"Help is not available in this session."})}c&&(f&&(m=!0,h?.interrupt?.(),c.allowNextTurn(),f=!1),C({status:"running"}),T({text:e}),c.pushText(e),f=!0)};const A=await(async()=>{if("single"===e.mode)return Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt;if("fix"===e.mode)try{return await(async({authHeader:e,orgId:t,runId:r})=>{const n=await(o={auth:e,client:Ht(),headers:mr(t),path:{runId:r}},(o.client??Pt).get({security:[{name:"authorization",type:"apiKey"}],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=_r.safeParse(n.data);if(e.success)return e.data.context;throw new Error("Autoheal context response missing or invalid context.")}throw new Error("Failed to fetch autoheal context")})({authHeader:r,orgId:n,runId:e.runId})}catch(e){const t=e instanceof Error?e.message:"Failed to fetch autoheal context.";C({error:t,status:"error"}),await v(),process.exit(1)}return""})(),x=await async function(e){const t=S.default.resolve(e),r=S.default.join(t,"tests"),n=S.default.join(r,"helpers"),o=S.default.join(r,"assets"),s=S.default.join(t,"playwright.config.ts"),i=S.default.join(r,"seed.spec.ts"),[a,c,l,d,u,p]=await Promise.all([Hr({defaultContent:"Unable to read directory",dirName:"working directory",dirPath:t}),Hr({defaultContent:"Unable to read directory",dirName:"tests directory",dirPath:r}),Hr({defaultContent:"Directory does not exist yet",dirName:"helpers directory",dirPath:n}),Hr({defaultContent:"Directory does not exist yet",dirName:"assets directory",dirPath:o}),$r({defaultContent:"File does not exist or could not be read",fileName:"playwright.config.ts",filePath:s}),$r({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}}}(o),L=await(async({allowedEnvVars:e,mode:t,workspaceInfo:r,authHeader:n})=>{const o=Ht(),s=await(i={client:o,body:{mode:t,workspaceInfo:r,allowedEnvVars:e},headers:{authorization:n}},(i.client??Pt).post({security:[{name:"authorization",type:"apiKey"}],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(i),mode:e.mode,workspaceInfo:x,authHeader:r}),O=await async function({auth:e,client:t,source:r,metadata:n}){try{const s=await(o={auth:e,client:t,body:{source:r,metadata:n??{}}},(o.client??Pt).post({security:[{name:"authorization",type:"apiKey"}],url:"/v1/proxy/api-key",...o,headers:{"Content-Type":"application/json",...o.headers}})),i=s.response;if(s.error){const e="object"==typeof s.error&&"error"in s.error?s.error.error:"Unknown error";return{error:Xr(e,i)}}return s.data?{key:s.data.key}:{error:Xr("No data in response",i)}}catch(e){const t=e instanceof Error?e.message:"Unknown error";return{error:Xr(t)}}var o}({auth:r,client:Ht(),source:"cli"}),P=O.key;if(!P){const e=O.error?.message;C({error:e?`Unable to make AI calls: ${e}`:"Unable to make AI calls. Check if you are authenticated.",status:"error"}),await v(),process.exit(1)}const B=Object.fromEntries(Object.entries(process.env).filter(([e])=>!Qr.has(e)));h=l.query({options:{allowedTools:[...Zr,..."fix"===e.mode?["mcp__auto-heal-report"]:[]],cwd:o,env:{...B,ANTHROPIC_API_KEY:P,ANTHROPIC_BASE_URL:Mt},hooks:{PostToolUse:[{hooks:[async e=>{const t=xr(e);if(!t)return{decision:"approve"};let r=!1;const n=t.map(e=>Ar(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:[Dr({onResult:e=>E({message:e})})]},{matcher:"mcp__playwright-test__test_debug",hooks:[jr({onResult:e=>E({message:e})})]}],PreToolUse:[{hooks:[Cr({action:"writing",pathKey:"file_path",workDir:o}),Tr({action:"writing",pathKey:"file_path"}),vr({action:"writing",pathKey:"file_path"}),Rr({action:"writing",pathKey:"file_path"}),br({action:"writing",pathKey:"file_path"}),wr({pathKey:"file_path"})],matcher:"Write"},{hooks:[Cr({action:"editing",pathKey:"file_path",workDir:o}),Tr({action:"editing",pathKey:"file_path"}),vr({action:"editing",pathKey:"file_path"}),Rr({action:"editing",pathKey:"file_path"}),br({action:"editing",pathKey:"file_path"}),wr({pathKey:"file_path"})],matcher:"Edit"},{hooks:[wr({pathKey:"fileName"})],matcher:"mcp__playwright-test__generator_write_test"},{hooks:[Cr({action:"reading",pathKey:"file_path",workDir:o}),br({action:"reading",pathKey:"file_path"})],matcher:"Read"},{hooks:[Cr({action:"searching",pathKey:"path",workDir:o}),br({action:"searching",pathKey:"path"})],matcher:"Grep"},{matcher:"mcp__playwright-test__browser_type",hooks:[Nr({envVars:i})]}]},includePartialMessages:!0,mcpServers:{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx"},..."fix"===e.mode?{"auto-heal-report":qr({authHeader:r,orgId:n,runId:e.runId})}:{}},model:"claude-sonnet-4-5",systemPrompt:L},prompt:c??A});const N=async()=>{try{await(h?.interrupt?.())}catch{}c?.finish(),await v(),process.exit(1)};process.on("SIGINT",N);try{for await(const e of h){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&&b({text:e.text})}"message_stop"===t?.type&&c&&c.allowNextTurn();continue}if("assistant"===e.type){const{content:t}=e.message??{};if(Array.isArray(t))for(const e of t)"tool_use"===e?.type&&g({rawName:e.name});continue}if("result"!==e.type);else{if(a){"success"===e.subtype?C({status:"success"}):m||(C({error:"Run failed.",status:"error"}),process.exitCode=1),m=!1;break}"success"!==e.subtype?m||(C({error:"Run failed.",status:"error"}),process.exitCode=1):C({status:"success"}),f=!1,m=!1,c?.allowNextTurn()}}}catch(e){m||(C({error:`Agent encountered an error: ${e}`,status:"error"}),process.exitCode=1)}finally{f=!1,m=!1,process.off("SIGINT",N),c?.finish(),await v()}},tn=[{args:["--trace=on"],description:"Run Playwright tests",name:"test"},{args:[],description:"Install browser dependencies",name:"install"}],rn=new e.Command;rn.name("stably").description("Stably CLI").version(Nt),rn.enablePositionalOptions(),rn.showHelpAfterError(),rn.exitOverride();var nn=[];rn.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>{nn.push(e)}});var on=()=>{const e=rn.helpInformation().trimEnd();return e?`${e}\n`:""},sn=(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},an=()=>{process.stdout.write(on())};rn.command("help").description("Show help for a command").argument("[command...]","Command to show help for").action(e=>{if(!e||0===e.length)return void an();const t=sn(rn,e);if(!t)return process.stderr.write(`Unknown command: ${e.join(" ")}\n`),an(),void(process.exitCode=1);var r;r=t,process.stdout.write((e=>{const t=e.helpInformation().trimEnd();return t?`${t}\n`:""})(r))}),rn.action(()=>en({mode:"chat",getHelpText:on})),rn.command("login").description("Login to Stably via browser authentication").action(ur),rn.command("logout").description("Logout from Stably and clear stored credentials").action(async()=>{const e=await Zt();if(!e)return void u.outro(x.default.yellow("You are not logged in."));const t=u.spinner();t.start("Logging out..."),await(async e=>{try{await fetch(`${jt}/api/backend/v1/logout`,{body:JSON.stringify({refresh_token:e}),headers:{"Content-Type":"application/json"},method:"POST"})}catch{}})(e.refreshToken),await tr(),await or(),t.stop(x.default.green("✓ Logged out")),u.outro(x.default.green("You have been logged out successfully."))}),rn.command("whoami").description("Show current authentication status").action(async()=>{const e=pr();if(e)return u.log.info(x.default.dim("Authentication: Environment variables")),u.log.info(` ${x.default.bold("API Key:")} ${x.default.cyan(e.apiKey.slice(0,8))}...`),u.log.info(` ${x.default.bold("Project ID:")} ${x.default.cyan(e.projectId)}`),void u.outro(x.default.green("Authenticated via environment variables"));if(!await Zt())return void u.outro(x.default.yellow("Not logged in. Run `stably login` to authenticate."));const t=await nr();if(!t)return u.log.info(x.default.dim("Authentication: OAuth (not linked to a project)")),void u.outro(x.default.yellow("Logged in but this directory is not linked to a project. Run `stably login` to link."));const r=await(async()=>rr(process.cwd()))(),n=r?S.default.dirname(r):process.cwd(),o=S.default.relative(process.cwd(),n)||".";u.log.info(x.default.dim("Authentication: OAuth")),u.log.info(` ${x.default.bold("Organization:")} ${x.default.cyan(t.orgName)}`),u.log.info(` ${x.default.bold("Project:")} ${x.default.cyan(t.projectName)}`),u.log.info(` ${x.default.bold("Linked at:")} ${x.default.dim(o)}`),u.outro(x.default.green("Authenticated"))}),rn.command("tunnel").description("Start a tunnel to expose your local server").option("-p, --port <number>","Port number for the tunnel","3000").action(async e=>{u.intro(`Starting development server for port ${e.port}...`);const t=await fr(),r="oauth"===t.type?`${t.auth.context.orgName}-${t.auth.context.projectName}`.toLowerCase().replace(/[^a-z0-9-]/g,""):`project-${t.auth.projectId}`.toLowerCase(),n=u.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: ${x.default.underline(x.default.cyan(o.url))}`)}),rn.command("create").description("Create resources").command("test").description("Create a test from a prompt").argument("<prompt...>","Prompt describing the test to create").action(e=>en({mode:"single",prompt:e})),rn.command("fix").description("Fix failing Playwright tests with 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(ht))if(ht[r].detect({env:e,cwd:t}))return{isCi:!0,...ht[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)),en({mode:"fix",runId:t})}),tn.forEach(({args:e,description:t,name:o})=>{rn.command(o).description(t).helpOption(!1).helpCommand(!1).allowUnknownOption(!0).allowExcessArguments(!0).passThroughOptions().action(()=>function({overrideArgs:e,subcommand:t}){const o=process.argv,s=o.findIndex((e,r)=>r>1&&e===t),i=-1===s?[]:o.slice(s+1),c="--"===i[0]?i.slice(1):i,l=e??[],d=new Set(l.map(e=>{const[t]=e.split("=");return t})),u=c.filter(e=>{const[t]=e.split("=");return!d.has(t)});!function(e){const t=function(e=process.cwd()){const t=r.resolve(e),n=function(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}}(t);if(!n)return{inNodeModules:!1,installed:!1,packageManager:void 0};const o={...n.dependencies,...n.devDependencies},s="@playwright/test"in o?"@playwright/test":"playwright"in o?"playwright":void 0,i=function(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}(t),c=r.join(t,"node_modules"),l=s?r.join(c,s):void 0;return{inNodeModules:!!l&&a.existsSync(l),installed:!!s,packageManager:i,packageName:s}}();t.installed||process.exit(1),t.inNodeModules||process.exit(1);const{packageManager:o}=t;o||process.exit(1);const[s,...i]=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")}(o),c=[s,...i.slice(0,-1)].join(" "),l=n.spawn(s,[...i,...e],{stdio:["inherit","pipe","pipe"]}),d=(e,t)=>{let r=e.toString();for(const e of tn)r=r.replaceAll(`${c} playwright ${e.name}`,`${c} stably ${e.name}`).replaceAll(`npx playwright ${e.name}`,`npx stably ${e.name}`);if("yarn"===o){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)};l.stdout?.on("data",e=>{d(e,process.stdout)}),l.stderr?.on("data",e=>{d(e,process.stderr)}),l.on("close",e=>{process.exit(e??0)})}([t,...l,...u])}({overrideArgs:e,subcommand:o}))});var cn=()=>{0!==nn.length&&(process.stderr.write(nn.join("")),nn=[])};(async()=>{try{await rn.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&&!!sn(rn,[r]);if(("commander.excessArguments"===e.code||"commander.unknownCommand"===e.code)&&r&&!n)return nn=[],process.stderr.write(`command '${r}' not found\n`),an(),void(process.exitCode=t);cn(),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("@clack/prompts"),p=require("picocolors"),h=require("readline/promises"),f=require("fs/promises"),m=require("zod"),_=require("open"),g=require("http"),E=require("crypto"),y=require("react"),I=require("react/jsx-runtime"),b=require("simple-git"),T=require("zod/v3"),v=require("@stablyhq/runner-sdk");function R(e){return e&&e.__esModule?e:{default:e}}var w=R(r),S=R(n),C=R(o),A=R(i),U=R(a),x=R(p),L=R(m),P=R(_),O=R(g),B=R(E),N=Object.create,D=Object.defineProperty,k=Object.getOwnPropertyDescriptor,j=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[j(e)[0]])((t={exports:{}}).exports,t),t.exports},K=(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 j(t))$.call(e,r)||void 0===r||D(e,r,{get:()=>t[r],enumerable:!(n=k(t,r))||n.enumerable});return e})(D(r,"default",{value:e,enumerable:!0}),e)),F=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)}}}),Y=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?F():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}}}}),V=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=Y(),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),h=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+u:u;s(p(h,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}}),q=G({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js"(e,t){var r=H("path"),n=V(),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=q(),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}}},he=K(re());function fe(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:_e+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),_e=34,ge=[{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"}],Ee=()=>{const e=(()=>{const e=64-_e+1;return Array.from({length:e},me)})();return[...ge,...e].map(ye)},ye=({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}},Ie=({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}],be=(()=>{const e=Ee();return Object.fromEntries(e.map(Ie))})();(()=>{const e=Ee(),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 Te=({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 h=void 0===(o=null===o?void 0:o)?void 0:be[o].description,f=(({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:h,exitCode:s,isCanceled:l}),m=`Command ${f}: ${i}`,_="[object Error]"===Object.prototype.toString.call(n),g=_?`${m}\n${n.message}`:m,E=[g,t,e].filter(Boolean).join("\n");return _?(n.originalMessage=n.message,n.message=E):n=new Error(E),n.shortMessage=g,n.command=i,n.escapedCommand=a,n.exitCode=s,n.signal=o,n.signalDescription=h,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"],Re=[];Re.push("SIGHUP","SIGINT","SIGTERM"),"win32"!==process.platform&&Re.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),"linux"===process.platform&&Re.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var we=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),Ue=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}},xe=class{},Le=globalThis.process;we(Le)?new class extends xe{#e="win32"===Le.platform?"SIGINT":"SIGHUP";#t=new Ue;#r;#n;#o;#s={};#i=!1;constructor(e){super(),this.#r=e,this.#s={};for(const t of Re)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(!we(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 Re)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,Re.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 we(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&&we(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)}}(Le):new class extends xe{onExit(){return()=>{}}load(){}unload(){}},new TextEncoder,K(ne());var Pe=(async()=>{})().constructor.prototype;["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(Pe,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"),ke=(e,t,r={})=>{const n=he.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=fe({env:e={...e}});return t.path=e[r],e[r]=(({cwd:e=C.default.cwd(),path:t=C.default.env[fe()],preferLocal:r=!0,execPath:n=C.default.execPath,addExecPath:o=!0}={})=>{const i=e instanceof URL?s.fileURLToPath(e):e,a=w.default.resolve(i),c=[];return r&&((e,t)=>{let r;for(;r!==t;)e.push(w.default.join(t,"node_modules/.bin")),r=t,t=w.default.resolve(t,"..")})(c,a),o&&((e,t,r)=>{const n=t instanceof URL?s.fileURLToPath(t):t;e.push(w.default.resolve(r,n,".."))})(c,n,a),[...c,t].join(w.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"===w.default.basename(e,".exe")&&t.unshift("/q"),{file:e,args:t,options:r,parsed:n}},je=(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=ke(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 Te({error:e,stdout:"",stderr:"",all:"",command:o,escapedCommand:s,parsed:n,timedOut:!1,isCanceled:!1,killed:!1})}const l=je(n.options,c.stdout,c.error),d=je(n.options,c.stderr,c.error);if(c.error||0!==c.status||null!==c.signal){const e=Te({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$/,Ke=/^\/(.*)\.git$/;function Fe(e){if(e){if(e.match(Ge))return e.replace(Ge,"$1");try{return new URL(e).pathname.replace(Ke,"$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:Fe(e.BUILDKITE_REPO),pr:t,isPr:r,prBranch:r?e.BUILDKITE_BRANCH:void 0,root:e.BUILDKITE_BUILD_CHECKOUT_PATH}}},Ye={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}`}}},Ve="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:`${Ve}/build/${e.CIRRUS_BUILD_ID}`,job:e.CIRRUS_TASK_ID,jobUrl:`${Ve}/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}}},qe={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=K(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)]))},ht={appveyor:se,azurePipelines:ce,bamboo:le,bitbucket:de,bitrise:ue,buddy:pe,buildkite:ze,circleci:Ye,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:qe,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}}}},ft={bodySerializer:e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t)},mt=({allowReserved:e,explode:t,name:r,style:n,value:o})=>{if(!t){const t=(e?o:o.map(e=>encodeURIComponent(e))).join((e=>{switch(e){case"form":default:return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20"}})(n));switch(n){case"label":return`.${t}`;case"matrix":return`;${r}=${t}`;case"simple":return t;default:return`${r}=${t}`}}const s=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(n),i=o.map(t=>"label"===n||"simple"===n?e?t:encodeURIComponent(t):_t({allowReserved:e,name:r,value:t})).join(s);return"label"===n||"matrix"===n?s+i:i},_t=({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)}`},gt=({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])=>_t({allowReserved:e,name:"deepObject"===n?`${r}[${t}]`:t,value:o})).join(i);return"label"===n||"matrix"===n?i+a:a},Et=/\{[^{}]+\}/g;function yt(e){const t=void 0!==e.body;return t&&e.bodySerializer?"serializedBody"in e?void 0!==e.serializedBody&&""!==e.serializedBody?e.serializedBody:null:""!==e.body?e.body:null:t?e.body:void 0}var It,bt=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=mt({allowReserved:i.allowReserved,explode:!0,name:o,style:"form",value:s,...i.array});e&&n.push(e)}else if("object"==typeof s){const e=gt({allowReserved:i.allowReserved,explode:!0,name:o,style:"deepObject",value:s,...i.object});e&&n.push(e)}else{const e=_t({allowReserved:i.allowReserved,name:o,value:s});e&&n.push(e)}}return n.join("&")},vt=(e,t)=>!!t&&!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`)),Rt=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(Et);if(n)for(const t of n){let n=!1,o=t.substring(1,t.length-1),s="simple";o.endsWith("*")&&(n=!0,o=o.substring(0,o.length-1)),o.startsWith(".")?(o=o.substring(1),s="label"):o.startsWith(";")&&(o=o.substring(1),s="matrix");const i=e[o];if(null==i)continue;if(Array.isArray(i)){r=r.replace(t,mt({explode:n,name:o,style:s,value:i}));continue}if("object"==typeof i){r=r.replace(t,gt({explode:n,name:o,style:s,value:i,valueOnly:!0}));continue}if("matrix"===s){r=r.replace(t,`;${_t({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}),wt=(e,t)=>{const r={...e,...t};return r.baseUrl?.endsWith("/")&&(r.baseUrl=r.baseUrl.substring(0,r.baseUrl.length-1)),r.headers=Ct(e.headers,t.headers),r},St=e=>{const t=[];return e.forEach((e,r)=>{t.push([r,e])}),t},Ct=(...e)=>{const t=new Headers;for(const r of e){if(!r)continue;const e=r instanceof Headers?St(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},At=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}},Ut=Tt({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),xt={"Content-Type":"application/json"},Lt=(e={})=>({...ft,headers:xt,parseAs:"auto",querySerializer:Ut,...e}),Pt=(e={})=>{let t=wt(Lt(),e);const r=()=>({...t}),n={error:new At,request:new At,response:new At},o=async e=>{const r={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:Ct(t.headers,e.headers),serializedBody:void 0};return r.security&&await(async({security:e,...t})=>{for(const r of e){if(vt(t,r.name))continue;const e=await bt(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:Rt(r)}},s=async e=>{const{opts:t,url:r}=await o(e),s={redirect:"follow",...t,body:yt(t)};let i=new Request(r,s);for(const e of n.request.fns)e&&(i=await e(i,t));const a=t.fetch;let c;try{c=await a(i)}catch(e){let r=e;for(const o of n.error.fns)o&&(r=await o(e,void 0,i,t));if(r=r||{},t.throwOnError)throw r;return"data"===t.responseStyle?void 0:{error:r,request:i,response:void 0}}for(const e of n.response.fns)e&&(c=await e(c,i,t));const l={request:i,response:c};if(c.ok){const e=("auto"===t.parseAs?(e=>{if(!e)return"stream";const t=e.split(";")[0]?.trim();return t?t.startsWith("application/json")||t.endsWith("+json")?"json":"multipart/form-data"===t?"formData":["application/","audio/","image/","video/"].some(e=>t.startsWith(e))?"blob":t.startsWith("text/")?"text":void 0:void 0})(c.headers.get("Content-Type")):t.parseAs)??"json";if(204===c.status||"0"===c.headers.get("Content-Length")){let r;switch(e){case"arrayBuffer":case"blob":case"text":r=await c[e]();break;case"formData":r=new FormData;break;case"stream":r=c.body;break;default:r={}}return"data"===t.responseStyle?r:{data:r,...l}}let r;switch(e){case"arrayBuffer":case"blob":case"formData":case"json":case"text":r=await c[e]();break;case"stream":return"data"===t.responseStyle?c.body:{data:c.body,...l}}return"json"===e&&(t.responseValidator&&await t.responseValidator(r),t.responseTransformer&&(r=await t.responseTransformer(r))),"data"===t.responseStyle?r:{data:r,...l}}const d=await c.text();let u;try{u=JSON.parse(d)}catch{}const p=u??d;let h=p;for(const e of n.error.fns)e&&(h=await e(p,c,i,t));if(h=h||{},t.throwOnError)throw h;return"data"===t.responseStyle?void 0:{error:h,...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))),h=async function*(){let c=s??3e3,h=0;const f=d.signal??(new AbortController).signal;for(;!f.aborted;){h++;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:f};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 h=p.body.pipeThrough(new TextDecoderStream).getReader();let m="";const _=()=>{try{h.cancel()}catch{}};f.addEventListener("abort",_);try{for(;;){const{done:e,value:t}=await h.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{f.removeEventListener("abort",_),h.releaseLock()}break}catch(e){if(t?.(e),void 0!==i&&h>=i)break;const r=Math.min(c*2**(h-1),a??3e4);await p(r)}}}();return{stream:h}})({...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:Rt,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=wt(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")}},Ot=Pt(Lt({baseUrl:"https://api.stably.ai"})),Bt="x-stably-org-id",Nt="4.1.0",Dt=process.env.STABLY_API_URL||"https://api.stably.ai",kt=process.env.AUTH_URL||"https://auth.stably.ai",jt=process.env.AUTH_CLIENT_ID||"288007877071cce81f269428ea78653a",Mt=process.env.AI_PROXY_URL||"https://ai-proxy.stably.ai",$t="http://localhost:9876/auth/callback",Ht=()=>It||(It=Pt(Lt({baseUrl:Dt,headers:{"X-STABLY-CLI-VERSION":Nt,"X-STABLY-SOURCE":"cli"}}))),Gt=async(e,t)=>{const r=await(n={body:{accessToken:e,orgId:t},client:Ht()},(n.client??Ot).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},Kt=w.default.join(A.default.homedir(),".stably"),Ft=w.default.join(Kt,"auth.json"),zt=".stably",Yt="project.json",Vt=L.default.object({accessToken:L.default.string(),expiresAt:L.default.number(),idToken:L.default.string().optional(),refreshToken:L.default.string()}),Wt=L.default.object({orgId:L.default.string(),orgName:L.default.string(),projectId:L.default.string(),projectName:L.default.string()}),qt=async()=>{try{const e=await f.readFile(Ft,"utf-8");return Vt.parse(JSON.parse(e))}catch{return}},Jt=async e=>{await f.mkdir(Kt,{recursive:!0}),await f.writeFile(Ft,JSON.stringify(e,null,2),{mode:384})},Xt=async()=>{try{await f.unlink(Ft)}catch{}},Qt=async e=>{let t=e;const{root:r}=w.default.parse(t);for(;t!==r;){const e=w.default.join(t,zt);try{return await f.access(e),e}catch{t=w.default.dirname(t)}}},Zt=async()=>{try{const e=await Qt(process.cwd());if(!e)return;const t=w.default.join(e,Yt),r=await f.readFile(t,"utf-8");return Wt.parse(JSON.parse(r))}catch{return}},er=async()=>{try{const e=await Qt(process.cwd());e&&await f.unlink(w.default.join(e,Yt))}catch{}},tr=e=>Date.now()>=e.expiresAt-3e5,rr=async e=>{const t=new URLSearchParams({client_id:jt,grant_type:"refresh_token",refresh_token:e}),r=await fetch(`${kt}/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}},nr=m.z.object({org_id:m.z.string(),org_name:m.z.string()}),or=m.z.object({email:m.z.string(),org_id_to_org_member_info:m.z.record(m.z.string(),nr).optional(),org_member_info:nr.optional(),user_id:m.z.string()});m.z.object({email:m.z.string(),firstName:m.z.string().optional(),lastName:m.z.string().optional(),organizations:m.z.array(m.z.object({id:m.z.string(),name:m.z.string()})),userId:m.z.string()});var sr=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`,ir=(e,t,r)=>{e.writeHead(t,{"Content-Type":"text/html"}),e.end(r)},ar=(e,t)=>{const r=new URLSearchParams({client_id:jt,code_challenge:e,code_challenge_method:"S256",redirect_uri:$t,response_type:"code",state:t});return`${kt}/propelauth/oauth/authorize?${r.toString()}`},cr=async e=>{const t=u.spinner();let r;t.start("Loading user info...");try{r=(e=>{try{const t=or.parse((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)})(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"}`)}})(e.accessToken),t.stop(x.default.green(`✓ Logged in as ${x.default.cyan(r.email)}`))}catch(e){t.stop(x.default.red("✗ Failed to load user info"));const r=e instanceof Error?e.message:"Unknown error";return u.log.error(r),{success:!1}}const n=await(async e=>{if(0===e.length)return void u.log.error("You don't belong to any organizations.");if(1===e.length)return u.log.info(`Using organization: ${x.default.cyan(e[0].name)}`),e[0];if(!process.stdin.isTTY)return u.log.info(`Auto-selecting organization: ${x.default.cyan(e[0].name)}`),e[0];const t=await u.select({message:"Select an organization",options:e.map(e=>({label:e.name,value:e.id}))});return u.isCancel(t)?void 0:e.find(e=>e.id===t)})(r.organizations);if(!n)return u.log.warn("Organization selection cancelled."),{success:!1};let o;t.start("Getting org credentials...");try{const r=await Gt(e.accessToken,n.id);o={accessToken:r.accessToken,expiresAt:Date.now()+1e3*r.expiresInSeconds,idToken:e.idToken,refreshToken:e.refreshToken},t.stop(x.default.green("✓ Credentials obtained"))}catch(e){t.stop(x.default.red("✗ Failed to get org credentials"));const r=e instanceof Error?e.message:"Unknown error";return u.log.error(r),{success:!1}}const s=await(async(e,t)=>{const r=u.spinner();let n;r.start("Loading projects...");try{n=await(async({accessToken:e,orgId:t})=>{const r=await(n={auth:`Bearer ${e}`,client:Ht(),path:{orgId:t}},(n.client??Ot).get({security:[{name:"authorization",type:"apiKey"}],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(x.default.green("✓ Projects loaded"))}catch(e){r.stop(x.default.red("✗ Failed to load projects"));const t=e instanceof Error?e.message:"Unknown error";return void u.log.error(t)}if(0===n.length)return u.log.error("No projects found in this organization."),void u.log.info(`Create a project at ${x.default.underline(x.default.cyan("https://app.stably.ai"))}`);if(1===n.length)return u.log.info(`Using project: ${x.default.cyan(n[0].name)}`),n[0];if(!process.stdin.isTTY)return u.log.info(`Auto-selecting project: ${x.default.cyan(n[0].name)}`),n[0];const o=await u.select({message:"Select a project",options:n.map(e=>({label:e.name,value:e.id}))});return u.isCancel(o)?void 0:n.find(e=>e.id===o)})(o.accessToken,n.id);return s?(await(async e=>{const t=w.default.join(process.cwd(),zt),r=w.default.join(t,Yt);await f.mkdir(t,{recursive:!0}),await f.writeFile(r,JSON.stringify(e,null,2)),await(async e=>{const t=w.default.join(e,".gitignore");try{if((await f.readFile(t,"utf-8")).split("\n").some(e=>".stably"===e.trim()))return;await f.appendFile(t,"\n# Stably CLI\n.stably\n")}catch{await f.writeFile(t,"# Stably CLI\n.stably\n")}})(process.cwd())})({orgId:n.id,orgName:n.name,projectId:s.id,projectName:s.name}),u.log.info(x.default.dim("Linked this directory to your Stably project.")),{scopedTokens:o,success:!0}):(u.log.warn("Project selection cancelled."),{success:!1})},lr=async()=>{const e=await qt();if(e){if(!tr(e)){if(await Zt())return void u.outro(x.default.yellow("You are already logged in. Run `stably logout` first to log out."));u.log.info("You are logged in but haven't selected a project yet.");const t=await cr(e);return void(t.success?(await Jt(t.scopedTokens),u.outro(x.default.green("Setup complete! You can now use Stably CLI."))):u.outro(x.default.yellow("Setup incomplete. Run `stably login` to try again.")))}const t=u.spinner();t.start("Refreshing session...");try{const r=await rr(e.refreshToken);t.stop(x.default.green("✓ Session refreshed"));const n=await Zt();if(n){t.start("Getting org credentials...");try{const e=await Gt(r.accessToken,n.orgId),o={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:r.idToken,refreshToken:r.refreshToken};await Jt(o),t.stop(x.default.green("✓ Credentials obtained")),u.outro(x.default.green("Login successful"))}catch{await Jt(r),t.stop(x.default.yellow("Using full credentials")),u.outro(x.default.green("Login successful"))}}else{const e=await cr(r);e.success?(await Jt(e.scopedTokens),u.outro(x.default.green("Setup complete! You can now use Stably CLI."))):u.outro(x.default.yellow("Setup incomplete. Run `stably login` to try again."))}return}catch{t.stop(x.default.yellow("Session expired, proceeding with fresh login...")),await Xt(),await er()}}const{authorizeUrl:t,waitForCallback:r}=(()=>{const{authorizeUrl:e,codeVerifier:t,state:r}=(()=>{const e=B.default.randomBytes(32).toString("base64url"),t=(r=e,B.default.createHash("sha256").update(r).digest("base64url"));var r;const n=B.default.randomBytes(16).toString("base64url");return{authorizeUrl:ar(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=O.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?(ir(r,400,sr(d)),o(),i.close(),void e({error:d,success:!1})):c&&l?l!==n?(ir(r,400,sr("Invalid state parameter (possible CSRF attack)")),o(),i.close(),void e({error:"State mismatch",success:!1})):(ir(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})):(ir(r,400,sr("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:jt,code:e,code_verifier:t,grant_type:"authorization_code",redirect_uri:$t}),n=await fetch(`${kt}/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)}})();u.log.info("Opening browser for authentication..."),u.log.info(x.default.dim("If browser doesn't open, visit:")),u.log.info(x.default.underline(x.default.cyan(t)));try{await P.default(t)}catch{u.log.warn("Could not open browser automatically. Please open the URL above manually.")}const n=u.spinner();let o;n.start("Waiting for authentication...");try{o=await r(),n.stop(x.default.green("✓ Authentication successful"))}catch(e){n.stop(x.default.red("✗ Authentication failed"));const t=e instanceof Error?e.message:"Unknown error";u.outro(x.default.red(`Login failed: ${t}`)),process.exit(1)}const i=await cr(o);i.success?(await Jt(i.scopedTokens),u.outro(x.default.green("Setup complete! You can now use Stably CLI."))):(u.outro(x.default.yellow("Setup incomplete. Run `stably login` to try again.")),process.exit(1))},dr=()=>{const e=process.env.STABLY_API_KEY,t=process.env.STABLY_PROJECT_ID;if(e&&t)return{apiKey:e,projectId:t}},ur=async()=>{const e=await qt();if(e){if(!tr(e))return e;try{const t=await rr(e.refreshToken),r=await Zt();if(r)try{const e=await Gt(t.accessToken,r.orgId),n={accessToken:e.accessToken,expiresAt:Date.now()+1e3*e.expiresInSeconds,idToken:t.idToken,refreshToken:t.refreshToken};return await Jt(n),n}catch{return await Jt(t),t}return await Jt(t),t}catch{return}}},pr=async(e={})=>{const t=dr();if(t)return{auth:t,type:"env"};let r=await ur(),n=r?await Zt():void 0;const o=process.stdin.isTTY&&process.stdout.isTTY;if((!r||!n)&&e.autoLogin&&o){r?u.log.info("You are logged in but need to select an organization and project."):u.log.info("You are not logged in."),u.log.info("Press Enter to log in."),process.stdout.write(`${x.default.dim("Alternatively, set environment variables for an org API key:")}\n${x.default.dim(" STABLY_API_KEY=... STABLY_PROJECT_ID=... stably")}\n`),process.stdout.write("\n");const e=h.createInterface({input:process.stdin,output:process.stdout});try{await e.question(x.default.dim("Press Enter to continue... "))}finally{e.close()}await lr(),r=await ur(),n=r?await Zt():void 0}return r||(u.outro(x.default.red("You are not logged in. Run `stably login` to authenticate.")),process.exit(1)),n||(u.outro(x.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"}},hr=e=>e?{[Bt]:e}:void 0,fr=m.z.object({context:m.z.string().min(1)});function mr(e){return/^\.env(\..*)?$/.test(e)}function _r(e){return Boolean(e&&"object"==typeof e&&"tool_input"in e&&e.tool_input&&"object"==typeof e.tool_input)}function gr({input:e,pathKey:t}){if(!_r(e))return{decision:"block",reason:`Invalid tool call format: Expected an object with 'tool_input' property. Please ensure the tool call follows the correct structure: { tool_input: { ${t}: "path/to/file" } }`,success:!1,systemMessage:"Tool call blocked due to invalid input format"};const r=e.tool_input;return t in r?"string"==typeof r[t]?{path:r[t],success:!0}:{decision:"block",reason:`Invalid tool call format: The '${t}' parameter must be a string containing the file path, but received ${typeof r[t]}. Please provide a valid file path as a string. Example: { tool_input: { ${t}: "src/example.ts" } }`,success:!1,systemMessage:"Tool call blocked due to invalid parameter type"}:{decision:"block",reason:`Invalid tool call format: Missing required parameter '${t}'. Please provide the file path using the '${t}' parameter. Example: { tool_input: { ${t}: "path/to/file" } }`,success:!1,systemMessage:"Tool call blocked due to missing required parameters"}}function Er({action:e,fileCheck:t,getBlockMessage:r,pathKey:n}){return async o=>{const s=gr({input:o,pathKey:n});if(!s.success)return s;const i=s.path.replace(/\\/g,"/"),a=i.split("/").pop()||i;return t(a)?{decision:"block",reason:r("reading"===e?"Access to":"writing"===e?"Writing to":"editing"===e?"Editing":"Searching in"),systemMessage:"AI blocked due to accessing sensitive content"}:{decision:"approve"}}}function yr({action:e,pathKey:t}){return Er({action:e,fileCheck:mr,getBlockMessage:e=>`${e} .env files is not allowed. Environment variables and secrets should be managed in Stably's Test Data section instead. You can access these values using process.env in your test code.`,pathKey:t})}function Ir({action:e,pathKey:t}){return Er({action:e,fileCheck:e=>".gitignore"===e,getBlockMessage:()=>"Modifying .gitignore is not allowed. The .gitignore file is managed by the system and cannot be changed.",pathKey:t})}function br({action:e,pathKey:t}){return Er({action:e,fileCheck:e=>".gitattributes"===e,getBlockMessage:()=>"Modifying .gitattributes is not allowed. The .gitattributes file is managed by the system and cannot be changed.",pathKey:t})}function Tr({action:e,pathKey:t}){return Er({action:e,fileCheck:e=>".lfsconfig"===e,getBlockMessage:()=>"Modifying .lfsconfig is not allowed. The .lfsconfig file is managed by the system and cannot be changed.",pathKey:t})}var vr=/\.(spec|test)\.(c|m)?(ts|tsx|js|jsx)$/;function Rr({pathKey:e}){return async t=>{const r=gr({input:t,pathKey:e});if(!r.success)return r;const n=r.path.replace(/\\/g,"/").split("/").pop()||r.path;return vr.test(n)?n.endsWith(".spec.ts")?{decision:"approve"}:{decision:"block",reason:`Test files must use the .spec.ts extension. The file "${n}" is not supported by Stably. Please use ".spec.ts" as the extension instead.`,systemMessage:"Tool call blocked due to unsupported test file extension"}:{decision:"approve"}}}function wr({action:e,pathKey:t,workDir:n}){return async o=>{const s=gr({input:o,pathKey:t});if(!s.success)return s;const i=s.path;try{return function({targetPath:e,workDir:t}){const n=function(e){if(a.existsSync(e))return a.realpathSync.native(e);let t=e;const n=[];for(;!a.existsSync(t);){const o=r.dirname(t);if(o===t)return r.resolve(e);n.unshift(t.slice(o.length+1)),t=o}const o=a.realpathSync.native(t);return n.length>0?r.resolve(o,...n):o}(e),o=a.realpathSync.native(t),s=n.endsWith(r.sep)?n:n+r.sep,i=o.endsWith(r.sep)?o:o+r.sep;return s.startsWith(i)||n===o}({targetPath:r.resolve(n,i),workDir:n})?{decision:"approve"}:{decision:"block",reason:`${"reading"===e?"Accessing":"writing"===e?"Writing to":"editing"===e?"Editing":"Searching in"} files outside the workspace is not allowed. The path "${i}" resolves to a location outside your workspace directory. Please only access files within your workspace.`,systemMessage:"Tool call blocked due to path traversal attempt"}}catch(e){return{decision:"block",reason:`Unable to validate file path "${i}". Please ensure the path is valid and try again. Error: ${e instanceof Error?e.message:"Unknown error"}`,systemMessage:"Tool call blocked due to path validation error"}}}}var Sr=e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"text"===t.type&&"string"==typeof t.text},Cr=e=>null!=e&&"object"==typeof e&&"tool_response"in e,Ar=e=>{if(!e||"object"!=typeof e)return;const t=e;return Array.isArray(t.tool_response)?t.tool_response:void 0},Ur=e=>{const t=Ar(e);if(t)return t.filter(Sr).map(e=>e.text).join("\n")||void 0},xr=/\u001b\[[0-9;]*m/g,Lr=e=>e.replace(xr,""),Pr=/\$\{process\.env\.([A-Z_][A-Z0-9_]*)\}/g;function Or({envVars:e}){return async t=>{if(!_r(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(Pr,(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 Br({onResult:e}){return async t=>{if(!Cr(t))return{decision:"approve"};const r=Ur(t);if(!r)return{decision:"approve"};const n=function(e){const t=Lr(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 Nr({onResult:e}){return async t=>{if(!Cr(t))return{decision:"approve"};const r=Ur(t);if(!r)return{decision:"approve"};const n=function(e){const t=Lr(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 Dr=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()})}},kr=10240,jr=async({defaultContent:e,fileName:t,filePath:r})=>{try{const e=(await f.stat(r)).size,n=await f.readFile(r,"utf-8"),o=Buffer.byteLength(n,"utf-8");if(o<=kr)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<=kr?s:s.slice(0,kr)+`\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(t){let r;if(t&&"object"==typeof t&&"code"in t){const e=t.code;"string"==typeof e&&(r=e)}return e}},Mr=async({defaultContent:e,dirName:t,dirPath:r})=>{try{const e=await f.readdir(r);return e.length>0?e.join("\n"):"(empty)"}catch(t){let r;if(t&&"object"==typeof t&&"code"in t){const e=t.code;"string"==typeof e&&(r=e)}return e}},$r=e=>{const t=["mcp__playwright-test__","mcp__auto-heal-report__"];for(const r of t)if(e.startsWith(r))return e.slice(r.length).replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase());return e},Hr=T.z.object({bucket:T.z.string(),key:T.z.string()}),Gr=T.z.object({diffBucketPath:Hr,expiresInSeconds:T.z.number(),key:T.z.string(),uploadUrl:T.z.string()}),Kr=["test","bug","other"],Fr={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."},zr=e=>Fr[e],{zSuiteAutoHealReport:Yr}=function(e){const t=e.enum(Kr),r=["Classification of the root cause:","",`- test: ${zr("test")}`,`- bug: ${zr("bug")}`,`- other: ${zr("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.")})}}(T.z),Vr=({authHeader:e,orgId:t,runId:r})=>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:Yr},async({report:n})=>{const o=b.simpleGit({baseDir:process.cwd(),maxConcurrentProcesses:1}),s=await o.diff(),i=Yr.parse(n);try{await(async({authHeader:e,orgId:t,report:r,runId:n})=>{const o=await(s={auth:e,body:{report:JSON.stringify(r)},client:Ht(),headers:hr(t),path:{runId:n}},(s.client??Ot).post({security:[{name:"authorization",type:"apiKey"}],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:t,report:i,runId:r});const{uploadUrl:n}=await(async({authHeader:e,contentType:t="text/plain",orgId:r,runId:n})=>{const o=await(s={auth:e,body:{contentType:t},client:Ht(),headers:hr(r),path:{runId:n}},(s.client??Ot).post({security:[{name:"authorization",type:"apiKey"}],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=Gr.parse(o.data);return{diffBucketPath:i.diffBucketPath,expiresInSeconds:i.expiresInSeconds,key:i.key,uploadUrl:i.uploadUrl}})({authHeader:e,contentType:"text/plain",orgId:t,runId:r});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:n})}catch(e){return{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"}),Wr=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]"),qr=(e,t)=>({message:Wr(e),status:t?.status,statusText:t?.statusText}),Jr=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"]),Xr=["mcp__playwright-test","Read","Write","Edit","Glob","Grep"],Qr=async e=>{const t=await pr({autoLogin:"chat"===e.mode}),r=(e=>"env"===e.type?e.auth.apiKey:`Bearer ${e.auth.accessToken}`)(t),n="oauth"===t.type?t.auth.context.orgId:void 0,o=w.default.resolve(process.cwd()),s=w.default.join(o,".env"),i=U.default.existsSync(s)&&U.default.statSync(s).isFile()?d.parse(U.default.readFileSync(s,"utf8")):{},a="chat"!==e.mode,c="chat"===e.mode?new Dr:void 0,u="chat"===e.mode?e.getHelpText:void 0,p={log:[],promptDisplay:"chat"===e.mode?"Ask Stably to build tests for you":"fix"===e.mode?"Fixing broken tests":(Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt)||"<empty prompt>",status:"running"};let h,f=a,m=!1;const _={current:e=>{}},{addTool:g,addToolResult:E,appendText:b,appendUserMessage:T,cleanup:v,setStatus:R}=await(async(e,t)=>{const{Box:r,Text:n,render:o,useInput:s}=await import("ink"),i=({label:e})=>{const[t,r]=y.useState(0);return y.useEffect(()=>{const e=setInterval(()=>r(e=>(e+1)%c.length),80);return()=>clearInterval(e)},[]),I.jsxs(n,{color:"yellow",children:[c[t]," ",e]})},a=()=>{const[e,t]=y.useState(!0);return y.useEffect(()=>{const e=setInterval(()=>t(e=>!e),500);return()=>clearInterval(e)},[]),e?I.jsx(n,{inverse:!0,children:" "}):I.jsx(n,{children:" "})},c=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],l=({onSend:e,state:t})=>{const[o,c]=y.useState("");s((t,r)=>{if(e&&(!r.ctrl||"c"!==t)){if(r.return){const t=o.trim();return t&&e(t),void c("")}r.backspace||r.delete?c(e=>e.slice(0,-1)):c(e=>`${e}${t}`)}});const l=y.useMemo(()=>"running"===t.status?I.jsx(i,{label:"Working"}):"success"!==t.status?I.jsx(n,{color:"red",children:"✖ Failed"}):void 0,[t.status]),d=!!e&&"running"===t.status&&0===t.log.length&&!t.resultText&&!t.errorText,u="running"===t.status&&!d||t.log.length>0||t.resultText||t.errorText||"running"!==t.status;return I.jsxs(r,{flexDirection:"column",children:[I.jsxs(r,{flexDirection:"column",flexShrink:0,children:[I.jsx(n,{color:"cyan",bold:!0,children:"Stably Agent"}),t.promptDisplay&&I.jsx(r,{flexDirection:"column",marginTop:1,children:I.jsx(n,{color:"gray",children:t.promptDisplay})})]}),I.jsxs(r,{flexDirection:"column",flexGrow:1,justifyContent:t.log.length>0?"flex-end":"flex-start",minHeight:0,children:[t.log.length>0&&I.jsx(r,{flexDirection:"column",marginTop:1,children:t.log.map(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))}),"error"===t.status&&t.errorText&&I.jsx(r,{marginTop:1,children:I.jsx(n,{color:"red",children:t.errorText})})]}),u&&I.jsx(r,{flexDirection:"column",flexShrink:0,marginTop:1,children:l}),e&&I.jsxs(r,{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:">"})," ",o,I.jsx(a,{})]})]})]})};let d=e;const u=o(I.jsx(l,{onSend:t?.onSend,state:d})),p=()=>{d={...d},u.rerender(I.jsx(l,{onSend:t?.onSend,state:d}))};return{addTool:({rawName:e})=>{d.log=[...d.log,{content:$r(e),id:d.log.length,kind:"tool"}],p()},addToolResult:({message:e})=>{d.log=[...d.log,{content:e,id:d.log.length,kind:"tool_result"}],p()},appendText:({text:e})=>{if(!e)return;const t=d.log.at(-1),r=t&&"text"===t.kind?e:e.replace(/^\s*\n+/,"");t&&"text"===t.kind?d.log=[...d.log.slice(0,-1),{...t,content:`${t.content}${r}`}]:d.log=[...d.log,{content:r,id:d.log.length,kind:"text"}],p()},appendUserMessage:({text:e})=>{e&&(d.log=[...d.log,{content:e,id:d.log.length,kind:"user"}],p())},cleanup:async()=>{u.unmount(),await u.waitUntilExit()},setStatus:({error:e,result:t,status:r})=>{d.errorText=e,d.resultText=t,d.status=r,p()}}})(p,"chat"===e.mode?{onSend:e=>_.current(e)}:void 0);let S=p.status;const C=({error:e,result:t,status:r})=>{S=r,R({error:e,result:t,status:r})};_.current=e=>{if("/help"===e.trim()){f&&c&&(m=!0,h?.interrupt?.(),c.allowNextTurn(),f=!1),"running"===S&&C({status:"success"}),T({text:e});const t=u?.();return void b({text:t??"Help is not available in this session."})}c&&(f&&(m=!0,h?.interrupt?.(),c.allowNextTurn(),f=!1),C({status:"running"}),T({text:e}),c.pushText(e),f=!0)};const A=await(async()=>{if("single"===e.mode)return Array.isArray(e.prompt)?e.prompt.join(" "):e.prompt;if("fix"===e.mode)try{return await(async({authHeader:e,orgId:t,runId:r})=>{const n=await(o={auth:e,client:Ht(),headers:hr(t),path:{runId:r}},(o.client??Ot).get({security:[{name:"authorization",type:"apiKey"}],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=fr.safeParse(n.data);if(e.success)return e.data.context;throw new Error("Autoheal context response missing or invalid context.")}throw new Error("Failed to fetch autoheal context")})({authHeader:r,orgId:n,runId:e.runId})}catch(e){const t=e instanceof Error?e.message:"Failed to fetch autoheal context.";C({error:t,status:"error"}),await v(),process.exit(1)}return""})(),x=await async function(e){const t=w.default.resolve(e),r=w.default.join(t,"tests"),n=w.default.join(r,"helpers"),o=w.default.join(r,"assets"),s=w.default.join(t,"playwright.config.ts"),i=w.default.join(r,"seed.spec.ts"),[a,c,l,d,u,p]=await Promise.all([Mr({defaultContent:"Unable to read directory",dirName:"working directory",dirPath:t}),Mr({defaultContent:"Unable to read directory",dirName:"tests directory",dirPath:r}),Mr({defaultContent:"Directory does not exist yet",dirName:"helpers directory",dirPath:n}),Mr({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}}}(o),L=await(async({allowedEnvVars:e,mode:t,workspaceInfo:r,authHeader:n})=>{const o=Ht(),s=await(i={client:o,body:{mode:t,workspaceInfo:r,allowedEnvVars:e},headers:{authorization:n}},(i.client??Ot).post({security:[{name:"authorization",type:"apiKey"}],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(i),mode:e.mode,workspaceInfo:x,authHeader:r}),P=await async function({auth:e,client:t,source:r,metadata:n}){try{const s=await(o={auth:e,client:t,body:{source:r,metadata:n??{}}},(o.client??Ot).post({security:[{name:"authorization",type:"apiKey"}],url:"/v1/proxy/api-key",...o,headers:{"Content-Type":"application/json",...o.headers}})),i=s.response;if(s.error){const e="object"==typeof s.error&&"error"in s.error?s.error.error:"Unknown error";return{error:qr(e,i)}}return s.data?{key:s.data.key}:{error:qr("No data in response",i)}}catch(e){const t=e instanceof Error?e.message:"Unknown error";return{error:qr(t)}}var o}({auth:r,client:Ht(),source:"cli"}),O=P.key;if(!O){const e=P.error?.message;C({error:e?`Unable to make AI calls: ${e}`:"Unable to make AI calls. Check if you are authenticated.",status:"error"}),await v(),process.exit(1)}const B=Object.fromEntries(Object.entries(process.env).filter(([e])=>!Jr.has(e)));h=l.query({options:{allowedTools:[...Xr,..."fix"===e.mode?["mcp__auto-heal-report"]:[]],cwd:o,env:{...B,ANTHROPIC_API_KEY:O,ANTHROPIC_BASE_URL:Mt},hooks:{PostToolUse:[{hooks:[async e=>{const t=Ar(e);if(!t)return{decision:"approve"};let r=!1;const n=t.map(e=>Sr(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:[Br({onResult:e=>E({message:e})})]},{matcher:"mcp__playwright-test__test_debug",hooks:[Nr({onResult:e=>E({message:e})})]}],PreToolUse:[{hooks:[wr({action:"writing",pathKey:"file_path",workDir:o}),Ir({action:"writing",pathKey:"file_path"}),br({action:"writing",pathKey:"file_path"}),Tr({action:"writing",pathKey:"file_path"}),yr({action:"writing",pathKey:"file_path"}),Rr({pathKey:"file_path"})],matcher:"Write"},{hooks:[wr({action:"editing",pathKey:"file_path",workDir:o}),Ir({action:"editing",pathKey:"file_path"}),br({action:"editing",pathKey:"file_path"}),Tr({action:"editing",pathKey:"file_path"}),yr({action:"editing",pathKey:"file_path"}),Rr({pathKey:"file_path"})],matcher:"Edit"},{hooks:[Rr({pathKey:"fileName"})],matcher:"mcp__playwright-test__generator_write_test"},{hooks:[wr({action:"reading",pathKey:"file_path",workDir:o}),yr({action:"reading",pathKey:"file_path"})],matcher:"Read"},{hooks:[wr({action:"searching",pathKey:"path",workDir:o}),yr({action:"searching",pathKey:"path"})],matcher:"Grep"},{matcher:"mcp__playwright-test__browser_type",hooks:[Or({envVars:i})]}]},includePartialMessages:!0,mcpServers:{"playwright-test":{args:["playwright","run-test-mcp-server"],command:"npx"},..."fix"===e.mode?{"auto-heal-report":Vr({authHeader:r,orgId:n,runId:e.runId})}:{}},model:"claude-sonnet-4-5",systemPrompt:L},prompt:c??A});const N=async()=>{try{await(h?.interrupt?.())}catch{}c?.finish(),await v(),process.exit(1)};process.on("SIGINT",N);try{for await(const e of h){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&&b({text:e.text})}"message_stop"===t?.type&&c&&c.allowNextTurn();continue}if("assistant"===e.type){const{content:t}=e.message??{};if(Array.isArray(t))for(const e of t)"tool_use"===e?.type&&g({rawName:e.name});continue}if("result"!==e.type);else{if(a){"success"===e.subtype?C({status:"success"}):m||(C({error:"Run failed.",status:"error"}),process.exitCode=1),m=!1;break}"success"!==e.subtype?m||(C({error:"Run failed.",status:"error"}),process.exitCode=1):C({status:"success"}),f=!1,m=!1,c?.allowNextTurn()}}}catch(e){m||(C({error:`Agent encountered an error: ${e}`,status:"error"}),process.exitCode=1)}finally{f=!1,m=!1,process.off("SIGINT",N),c?.finish(),await v()}},Zr=[{args:["--trace=on"],description:"Run Playwright tests",name:"test"},{args:[],description:"Install browser dependencies",name:"install"}],en=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=dr();if(e)return{auth:e,type:"env"};const t=await ur(),r=t?await Zt():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:`Bearer ${e}`,client:Ht(),path:{projectId:t}},(n.client??Ot).post({security:[{name:"authorization",type:"apiKey"}],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},tn=process.argv.findIndex(e=>"-C"===e||"--cwd"===e);-1!==tn&&process.argv[tn+1]&&(process.chdir(process.argv[tn+1]),process.argv.splice(tn,2));var rn=new e.Command;rn.name("stably").description("Stably CLI").version(Nt),rn.enablePositionalOptions(),rn.showHelpAfterError(),rn.exitOverride();var nn=[];rn.configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>{nn.push(e)}});var on=()=>{const e=rn.helpInformation().trimEnd();return e?`${e}\n`:""},sn=(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},an=()=>{process.stdout.write(on())};rn.command("help").description("Show help for a command").argument("[command...]","Command to show help for").action(e=>{if(!e||0===e.length)return void an();const t=sn(rn,e);if(!t)return process.stderr.write(`Unknown command: ${e.join(" ")}\n`),an(),void(process.exitCode=1);var r;r=t,process.stdout.write((e=>{const t=e.helpInformation().trimEnd();return t?`${t}\n`:""})(r))}),rn.action(()=>Qr({mode:"chat",getHelpText:on})),rn.command("login").description("Login to Stably via browser authentication").action(lr),rn.command("logout").description("Logout from Stably and clear stored credentials").action(async()=>{const e=await qt();if(!e)return void u.outro(x.default.yellow("You are not logged in."));const t=u.spinner();t.start("Logging out..."),await(async e=>{try{await fetch(`${kt}/api/backend/v1/logout`,{body:JSON.stringify({refresh_token:e}),headers:{"Content-Type":"application/json"},method:"POST"})}catch{}})(e.refreshToken),await Xt(),await er(),t.stop(x.default.green("✓ Logged out")),u.outro(x.default.green("You have been logged out successfully."))}),rn.command("whoami").description("Show current authentication status").action(async()=>{const e=dr();if(e)return u.log.info(x.default.dim("Authentication: Environment variables")),u.log.info(` ${x.default.bold("API Key:")} ${x.default.cyan(e.apiKey.slice(0,8))}...`),u.log.info(` ${x.default.bold("Project ID:")} ${x.default.cyan(e.projectId)}`),void u.outro(x.default.green("Authenticated via environment variables"));if(!await qt())return void u.outro(x.default.yellow("Not logged in. Run `stably login` to authenticate."));const t=await Zt();if(!t)return u.log.info(x.default.dim("Authentication: OAuth (not linked to a project)")),void u.outro(x.default.yellow("Logged in but this directory is not linked to a project. Run `stably login` to link."));const r=await(async()=>Qt(process.cwd()))(),n=r?w.default.dirname(r):process.cwd(),o=w.default.relative(process.cwd(),n)||".";u.log.info(x.default.dim("Authentication: OAuth")),u.log.info(` ${x.default.bold("Organization:")} ${x.default.cyan(t.orgName)}`),u.log.info(` ${x.default.bold("Project:")} ${x.default.cyan(t.projectName)}`),u.log.info(` ${x.default.bold("Linked at:")} ${x.default.dim(o)}`),u.outro(x.default.green("Authenticated"))}),rn.command("tunnel").description("Start a tunnel to expose your local server").option("-p, --port <number>","Port number for the tunnel","3000").action(async e=>{u.intro(`Starting development server for port ${e.port}...`);const t=await pr(),r="oauth"===t.type?`${t.auth.context.orgName}-${t.auth.context.projectName}`.toLowerCase().replace(/[^a-z0-9-]/g,""):`project-${t.auth.projectId}`.toLowerCase(),n=u.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: ${x.default.underline(x.default.cyan(o.url))}`)}),rn.command("create").description("Create resources").command("test").description("Create a test from a prompt").argument("<prompt...>","Prompt describing the test to create").action(e=>Qr({mode:"single",prompt:e})),rn.command("fix").description("Fix failing Playwright tests with 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(ht))if(ht[r].detect({env:e,cwd:t}))return{isCi:!0,...ht[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)),Qr({mode:"fix",runId:t})}),Zr.forEach(({args:e,description:t,name:o})=>{rn.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),i=-1===s?[]:o.slice(s+1),c="--"===i[0]?i.slice(1):i,l=e??[],d=new Set(l.map(e=>{const[t]=e.split("=");return t})),u=c.filter(e=>{const[t]=e.split("=");return!d.has(t)});!function(e,t={}){const o=function(e=process.cwd()){const t=r.resolve(e),n=function(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}}(t);if(!n)return{inNodeModules:!1,installed:!1,packageManager:void 0};const o={...n.dependencies,...n.devDependencies},s="@playwright/test"in o?"@playwright/test":"playwright"in o?"playwright":void 0,i=function(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}(t),c=r.join(t,"node_modules"),l=s?r.join(c,s):void 0;return{inNodeModules:!!l&&a.existsSync(l),installed:!!s,packageManager:i,packageName:s}}();o.installed||process.exit(1),o.inNodeModules||process.exit(1);const{packageManager:s}=o;s||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=t.env?{...process.env,...t.env}:process.env,u=n.spawn(i,[...c,...e],{stdio:["inherit","pipe","pipe"],env:d}),p=(e,t)=>{let r=e.toString();for(const e of Zr)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=>{process.exit(e??0)})}([t,...l,...u],{env:"test"===t?await en():void 0})}({overrideArgs:e,subcommand:o}))});var cn=()=>{0!==nn.length&&(process.stderr.write(nn.join("")),nn=[])};(async()=>{try{await rn.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&&!!sn(rn,[r]);if(("commander.excessArguments"===e.code||"commander.unknownCommand"===e.code)&&r&&!n)return nn=[],process.stderr.write(`command '${r}' not found\n`),an(),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.0
|
|
3
|
+
"version": "4.1.0",
|
|
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",
|