allwright 1.22.0 → 1.22.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/bin/allwright.js +159 -142
  2. package/package.json +1 -1
package/bin/allwright.js CHANGED
@@ -1,26 +1,26 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Mh=Object.create;var no=Object.defineProperty;var zh=Object.getOwnPropertyDescriptor;var Dh=Object.getOwnPropertyNames;var Lh=Object.getPrototypeOf,Uh=Object.prototype.hasOwnProperty;var zs=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(r){throw t=[r],r}};var ne=(n,e)=>()=>{try{return e||n((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},Ds=(n,e)=>{for(var t in e)no(n,t,{get:e[t],enumerable:!0})},qh=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Dh(e))!Uh.call(n,s)&&s!==t&&no(n,s,{get:()=>e[s],enumerable:!(r=zh(e,s))||r.enumerable});return n};var R=(n,e,t)=>(t=n!=null?Mh(Lh(n)):{},qh(e||!n||!n.__esModule?no(t,"default",{value:n,enumerable:!0}):t,n));var os=ne(so=>{var Ls=class extends Error{constructor(e,t,r){super(r),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},ro=class extends Ls{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};so.CommanderError=Ls;so.InvalidArgumentError=ro});var Us=ne(oo=>{var{InvalidArgumentError:Fh}=os(),io=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,r)=>{if(!this.argChoices.includes(t))throw new Fh(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,r):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Bh(n){let e=n.name()+(n.variadic===!0?"...":"");return n.required?"<"+e+">":"["+e+"]"}oo.Argument=io;oo.humanReadableArgName=Bh});var lo=ne(ul=>{var{humanReadableArgName:Kh}=Us(),ao=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let t=e.commands.filter(s=>!s._hidden),r=e._getHelpCommand();return r&&!r._hidden&&t.push(r),this.sortSubcommands&&t.sort((s,i)=>s.name().localeCompare(i.name())),t}compareOptions(e,t){let r=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return r(e).localeCompare(r(t))}visibleOptions(e){let t=e.options.filter(s=>!s.hidden),r=e._getHelpOption();if(r&&!r.hidden){let s=r.short&&e._findOption(r.short),i=r.long&&e._findOption(r.long);!s&&!i?t.push(r):r.long&&!i?t.push(e.createOption(r.long,r.description)):r.short&&!s&&t.push(e.createOption(r.short,r.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let r=e.parent;r;r=r.parent){let s=r.options.filter(i=>!i.hidden);t.push(...s)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(r=>Kh(r)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((r,s)=>Math.max(r,t.subcommandTerm(s).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((r,s)=>Math.max(r,t.optionTerm(s).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((r,s)=>Math.max(r,t.optionTerm(s).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((r,s)=>Math.max(r,t.argumentTerm(s).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let r="";for(let s=e.parent;s;s=s.parent)r=s.name()+" "+r;return r+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let r=`(${t.join(", ")})`;return e.description?`${e.description} ${r}`:r}return e.description}formatHelp(e,t){let r=t.padWidth(e,t),s=t.helpWidth||80,i=2,o=2;function l(T,x){if(x){let A=`${T.padEnd(r+o)}${x}`;return t.wrap(A,s-i,r+o)}return T}function u(T){return T.join(`
3
- `).replace(/^/gm," ".repeat(i))}let c=[`Usage: ${t.commandUsage(e)}`,""],f=t.commandDescription(e);f.length>0&&(c=c.concat([t.wrap(f,s,0),""]));let p=t.visibleArguments(e).map(T=>l(t.argumentTerm(T),t.argumentDescription(T)));p.length>0&&(c=c.concat(["Arguments:",u(p),""]));let b=t.visibleOptions(e).map(T=>l(t.optionTerm(T),t.optionDescription(T)));if(b.length>0&&(c=c.concat(["Options:",u(b),""])),this.showGlobalOptions){let T=t.visibleGlobalOptions(e).map(x=>l(t.optionTerm(x),t.optionDescription(x)));T.length>0&&(c=c.concat(["Global Options:",u(T),""]))}let w=t.visibleCommands(e).map(T=>l(t.subcommandTerm(T),t.subcommandDescription(T)));return w.length>0&&(c=c.concat(["Commands:",u(w),""])),c.join(`
2
+ "use strict";var Gh=Object.create;var ao=Object.defineProperty;var Hh=Object.getOwnPropertyDescriptor;var Vh=Object.getOwnPropertyNames;var Wh=Object.getPrototypeOf,Jh=Object.prototype.hasOwnProperty;var qs=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(r){throw t=[r],r}};var re=(n,e)=>()=>{try{return e||n((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},Fs=(n,e)=>{for(var t in e)ao(n,t,{get:e[t],enumerable:!0})},Yh=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Vh(e))!Jh.call(n,s)&&s!==t&&ao(n,s,{get:()=>e[s],enumerable:!(r=Hh(e,s))||r.enumerable});return n};var R=(n,e,t)=>(t=n!=null?Gh(Wh(n)):{},Yh(e||!n||!n.__esModule?ao(t,"default",{value:n,enumerable:!0}):t,n));var ds=re(uo=>{var Bs=class extends Error{constructor(e,t,r){super(r),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},lo=class extends Bs{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};uo.CommanderError=Bs;uo.InvalidArgumentError=lo});var Ks=re(ho=>{var{InvalidArgumentError:Xh}=ds(),co=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,r)=>{if(!this.argChoices.includes(t))throw new Xh(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,r):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Qh(n){let e=n.name()+(n.variadic===!0?"...":"");return n.required?"<"+e+">":"["+e+"]"}ho.Argument=co;ho.humanReadableArgName=Qh});var po=re(gl=>{var{humanReadableArgName:ef}=Ks(),fo=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let t=e.commands.filter(s=>!s._hidden),r=e._getHelpCommand();return r&&!r._hidden&&t.push(r),this.sortSubcommands&&t.sort((s,i)=>s.name().localeCompare(i.name())),t}compareOptions(e,t){let r=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return r(e).localeCompare(r(t))}visibleOptions(e){let t=e.options.filter(s=>!s.hidden),r=e._getHelpOption();if(r&&!r.hidden){let s=r.short&&e._findOption(r.short),i=r.long&&e._findOption(r.long);!s&&!i?t.push(r):r.long&&!i?t.push(e.createOption(r.long,r.description)):r.short&&!s&&t.push(e.createOption(r.short,r.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let r=e.parent;r;r=r.parent){let s=r.options.filter(i=>!i.hidden);t.push(...s)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(r=>ef(r)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((r,s)=>Math.max(r,t.subcommandTerm(s).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((r,s)=>Math.max(r,t.optionTerm(s).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((r,s)=>Math.max(r,t.optionTerm(s).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((r,s)=>Math.max(r,t.argumentTerm(s).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let r="";for(let s=e.parent;s;s=s.parent)r=s.name()+" "+r;return r+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let r=`(${t.join(", ")})`;return e.description?`${e.description} ${r}`:r}return e.description}formatHelp(e,t){let r=t.padWidth(e,t),s=t.helpWidth||80,i=2,o=2;function l(T,C){if(C){let A=`${T.padEnd(r+o)}${C}`;return t.wrap(A,s-i,r+o)}return T}function u(T){return T.join(`
3
+ `).replace(/^/gm," ".repeat(i))}let c=[`Usage: ${t.commandUsage(e)}`,""],f=t.commandDescription(e);f.length>0&&(c=c.concat([t.wrap(f,s,0),""]));let p=t.visibleArguments(e).map(T=>l(t.argumentTerm(T),t.argumentDescription(T)));p.length>0&&(c=c.concat(["Arguments:",u(p),""]));let b=t.visibleOptions(e).map(T=>l(t.optionTerm(T),t.optionDescription(T)));if(b.length>0&&(c=c.concat(["Options:",u(b),""])),this.showGlobalOptions){let T=t.visibleGlobalOptions(e).map(C=>l(t.optionTerm(C),t.optionDescription(C)));T.length>0&&(c=c.concat(["Global Options:",u(T),""]))}let w=t.visibleCommands(e).map(T=>l(t.subcommandTerm(T),t.subcommandDescription(T)));return w.length>0&&(c=c.concat(["Commands:",u(w),""])),c.join(`
4
4
  `)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,r,s=40){let i=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",o=new RegExp(`[\\n][${i}]+`);if(e.match(o))return e;let l=t-r;if(l<s)return e;let u=e.slice(0,r),c=e.slice(r).replace(`\r
5
5
  `,`
6
6
  `),f=" ".repeat(r),b="\\s\u200B",w=new RegExp(`
7
- |.{1,${l-1}}([${b}]|$)|[^${b}]+?([${b}]|$)`,"g"),T=c.match(w)||[];return u+T.map((x,A)=>x===`
8
- `?"":(A>0?f:"")+x.trimEnd()).join(`
9
- `)}};ul.Help=ao});var fo=ne(ho=>{var{InvalidArgumentError:Zh}=os(),uo=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let r=Hh(e);this.short=r.shortFlag,this.long=r.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,r)=>{if(!this.argChoices.includes(t))throw new Zh(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,r):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return Gh(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},co=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,r)=>{this.positiveOptions.has(r)&&this.dualOptions.add(r)})}valueFromOption(e,t){let r=t.attributeName();if(!this.dualOptions.has(r))return!0;let s=this.negativeOptions.get(r).presetArg,i=s!==void 0?s:!1;return t.negate===(i===e)}};function Gh(n){return n.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Hh(n){let e,t,r=n.split(/[ |,]+/);return r.length>1&&!/^[[<]/.test(r[1])&&(e=r.shift()),t=r.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}ho.Option=uo;ho.DualOptions=co});var dl=ne(cl=>{function Vh(n,e){if(Math.abs(n.length-e.length)>3)return Math.max(n.length,e.length);let t=[];for(let r=0;r<=n.length;r++)t[r]=[r];for(let r=0;r<=e.length;r++)t[0][r]=r;for(let r=1;r<=e.length;r++)for(let s=1;s<=n.length;s++){let i=1;n[s-1]===e[r-1]?i=0:i=1,t[s][r]=Math.min(t[s-1][r]+1,t[s][r-1]+1,t[s-1][r-1]+i),s>1&&r>1&&n[s-1]===e[r-2]&&n[s-2]===e[r-1]&&(t[s][r]=Math.min(t[s][r],t[s-2][r-2]+1))}return t[n.length][e.length]}function Wh(n,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=n.startsWith("--");t&&(n=n.slice(2),e=e.map(o=>o.slice(2)));let r=[],s=3,i=.4;return e.forEach(o=>{if(o.length<=1)return;let l=Vh(n,o),u=Math.max(n.length,o.length);(u-l)/u>i&&(l<s?(s=l,r=[o]):l===s&&r.push(o))}),r.sort((o,l)=>o.localeCompare(l)),t&&(r=r.map(o=>`--${o}`)),r.length>1?`
7
+ |.{1,${l-1}}([${b}]|$)|[^${b}]+?([${b}]|$)`,"g"),T=c.match(w)||[];return u+T.map((C,A)=>C===`
8
+ `?"":(A>0?f:"")+C.trimEnd()).join(`
9
+ `)}};gl.Help=fo});var vo=re(yo=>{var{InvalidArgumentError:tf}=ds(),mo=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let r=rf(e);this.short=r.shortFlag,this.long=r.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,r)=>{if(!this.argChoices.includes(t))throw new tf(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,r):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return nf(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},go=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,r)=>{this.positiveOptions.has(r)&&this.dualOptions.add(r)})}valueFromOption(e,t){let r=t.attributeName();if(!this.dualOptions.has(r))return!0;let s=this.negativeOptions.get(r).presetArg,i=s!==void 0?s:!1;return t.negate===(i===e)}};function nf(n){return n.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function rf(n){let e,t,r=n.split(/[ |,]+/);return r.length>1&&!/^[[<]/.test(r[1])&&(e=r.shift()),t=r.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}yo.Option=mo;yo.DualOptions=go});var vl=re(yl=>{function sf(n,e){if(Math.abs(n.length-e.length)>3)return Math.max(n.length,e.length);let t=[];for(let r=0;r<=n.length;r++)t[r]=[r];for(let r=0;r<=e.length;r++)t[0][r]=r;for(let r=1;r<=e.length;r++)for(let s=1;s<=n.length;s++){let i=1;n[s-1]===e[r-1]?i=0:i=1,t[s][r]=Math.min(t[s-1][r]+1,t[s][r-1]+1,t[s-1][r-1]+i),s>1&&r>1&&n[s-1]===e[r-2]&&n[s-2]===e[r-1]&&(t[s][r]=Math.min(t[s][r],t[s-2][r-2]+1))}return t[n.length][e.length]}function of(n,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=n.startsWith("--");t&&(n=n.slice(2),e=e.map(o=>o.slice(2)));let r=[],s=3,i=.4;return e.forEach(o=>{if(o.length<=1)return;let l=sf(n,o),u=Math.max(n.length,o.length);(u-l)/u>i&&(l<s?(s=l,r=[o]):l===s&&r.push(o))}),r.sort((o,l)=>o.localeCompare(l)),t&&(r=r.map(o=>`--${o}`)),r.length>1?`
10
10
  (Did you mean one of ${r.join(", ")}?)`:r.length===1?`
11
- (Did you mean ${r[0]}?)`:""}cl.suggestSimilar=Wh});var gl=ne(ml=>{var Jh=require("node:events").EventEmitter,po=require("node:child_process"),kt=require("node:path"),mo=require("node:fs"),he=require("node:process"),{Argument:Yh,humanReadableArgName:Xh}=Us(),{CommanderError:go}=os(),{Help:Qh}=lo(),{Option:hl,DualOptions:ef}=fo(),{suggestSimilar:fl}=dl(),yo=class n extends Jh{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:t=>he.stdout.write(t),writeErr:t=>he.stderr.write(t),getOutHelpWidth:()=>he.stdout.isTTY?he.stdout.columns:void 0,getErrHelpWidth:()=>he.stderr.isTTY?he.stderr.columns:void 0,outputError:(t,r)=>r(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,r){let s=t,i=r;typeof s=="object"&&s!==null&&(i=s,s=null),i=i||{};let[,o,l]=e.match(/([^ ]+) *(.*)/),u=this.createCommand(o);return s&&(u.description(s),u._executableHandler=!0),i.isDefault&&(this._defaultCommandName=u._name),u._hidden=!!(i.noHelp||i.hidden),u._executableFile=i.executableFile||null,l&&u.arguments(l),this._registerCommand(u),u.parent=this,u.copyInheritedSettings(this),s?this:u}createCommand(e){return new n(e)}createHelp(){return Object.assign(new Qh,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
12
- - specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new Yh(e,t)}argument(e,t,r,s){let i=this.createArgument(e,t);return typeof r=="function"?i.default(s).argParser(r):i.default(r),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,r,s]=e.match(/([^ ]+) *(.*)/),i=t??"display help for command",o=this.createCommand(r);return o.helpOption(!1),s&&o.arguments(s),i&&o.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let r=["preSubcommand","preAction","postAction"];if(!r.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
13
- Expecting one of '${r.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,r){this._exitCallback&&this._exitCallback(new go(e,t,r)),he.exit(e)}action(e){let t=r=>{let s=this.registeredArguments.length,i=r.slice(0,s);return this._storeOptionsAsProperties?i[s]=this:i[s]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=t,this}createOption(e,t){return new hl(e,t)}_callParseArg(e,t,r,s){try{return e.parseArg(t,r)}catch(i){if(i.code==="commander.invalidArgument"){let o=`${s} ${i.message}`;this.error(o,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let r=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${r}'
14
- - already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=s=>[s.name()].concat(s.aliases()),r=t(e).find(s=>this._findCommand(s));if(r){let s=t(this._findCommand(r)).join("|"),i=t(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),r=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(r,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(r,e.defaultValue,"default");let s=(i,o,l)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let u=this.getOptionValue(r);i!==null&&e.parseArg?i=this._callParseArg(e,i,u,o):i!==null&&e.variadic&&(i=e._concatValue(i,u)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(r,i,l)};return this.on("option:"+t,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;s(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+t,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;s(i,o,"env")}),this}_optionEx(e,t,r,s,i){if(typeof t=="object"&&t instanceof hl)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(t,r);if(o.makeOptionMandatory(!!e.mandatory),typeof s=="function")o.default(i).argParser(s);else if(s instanceof RegExp){let l=s;s=(u,c)=>{let f=l.exec(u);return f?f[0]:c},o.default(i).argParser(s)}else o.default(s);return this.addOption(o)}option(e,t,r,s){return this._optionEx({},e,t,r,s)}requiredOption(e,t,r,s){return this._optionEx({mandatory:!0},e,t,r,s)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,r){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=r,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(r=>{r.getOptionValueSource(e)!==void 0&&(t=r.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){he.versions?.electron&&(t.from="electron");let s=he.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(t.from="eval")}e===void 0&&(e=he.argv),this.rawArgs=e.slice();let r;switch(t.from){case void 0:case"node":this._scriptPath=e[1],r=e.slice(2);break;case"electron":he.defaultApp?(this._scriptPath=e[1],r=e.slice(2)):r=e.slice(1);break;case"user":r=e.slice(0);break;case"eval":r=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",r}parse(e,t){let r=this._prepareUserArgs(e,t);return this._parseCommand([],r),this}async parseAsync(e,t){let r=this._prepareUserArgs(e,t);return await this._parseCommand([],r),this}_executeSubCommand(e,t){t=t.slice();let r=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function i(f,p){let b=kt.resolve(f,p);if(mo.existsSync(b))return b;if(s.includes(kt.extname(p)))return;let w=s.find(T=>mo.existsSync(`${b}${T}`));if(w)return`${b}${w}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,l=this._executableDir||"";if(this._scriptPath){let f;try{f=mo.realpathSync(this._scriptPath)}catch{f=this._scriptPath}l=kt.resolve(kt.dirname(f),l)}if(l){let f=i(l,o);if(!f&&!e._executableFile&&this._scriptPath){let p=kt.basename(this._scriptPath,kt.extname(this._scriptPath));p!==this._name&&(f=i(l,`${p}-${e._name}`))}o=f||o}r=s.includes(kt.extname(o));let u;he.platform!=="win32"?r?(t.unshift(o),t=pl(he.execArgv).concat(t),u=po.spawn(he.argv[0],t,{stdio:"inherit"})):u=po.spawn(o,t,{stdio:"inherit"}):(t.unshift(o),t=pl(he.execArgv).concat(t),u=po.spawn(he.execPath,t,{stdio:"inherit"})),u.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(p=>{he.on(p,()=>{u.killed===!1&&u.exitCode===null&&u.kill(p)})});let c=this._exitCallback;u.on("close",f=>{f=f??1,c?c(new go(f,"commander.executeSubCommandAsync","(close)")):he.exit(f)}),u.on("error",f=>{if(f.code==="ENOENT"){let p=l?`searched for local subcommand relative to directory '${l}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",b=`'${o}' does not exist
11
+ (Did you mean ${r[0]}?)`:""}yl.suggestSimilar=of});var Sl=re(kl=>{var af=require("node:events").EventEmitter,bo=require("node:child_process"),Tt=require("node:path"),wo=require("node:fs"),he=require("node:process"),{Argument:lf,humanReadableArgName:uf}=Ks(),{CommanderError:_o}=ds(),{Help:cf}=po(),{Option:bl,DualOptions:df}=vo(),{suggestSimilar:wl}=vl(),ko=class n extends af{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:t=>he.stdout.write(t),writeErr:t=>he.stderr.write(t),getOutHelpWidth:()=>he.stdout.isTTY?he.stdout.columns:void 0,getErrHelpWidth:()=>he.stderr.isTTY?he.stderr.columns:void 0,outputError:(t,r)=>r(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,r){let s=t,i=r;typeof s=="object"&&s!==null&&(i=s,s=null),i=i||{};let[,o,l]=e.match(/([^ ]+) *(.*)/),u=this.createCommand(o);return s&&(u.description(s),u._executableHandler=!0),i.isDefault&&(this._defaultCommandName=u._name),u._hidden=!!(i.noHelp||i.hidden),u._executableFile=i.executableFile||null,l&&u.arguments(l),this._registerCommand(u),u.parent=this,u.copyInheritedSettings(this),s?this:u}createCommand(e){return new n(e)}createHelp(){return Object.assign(new cf,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
12
+ - specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new lf(e,t)}argument(e,t,r,s){let i=this.createArgument(e,t);return typeof r=="function"?i.default(s).argParser(r):i.default(r),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,r,s]=e.match(/([^ ]+) *(.*)/),i=t??"display help for command",o=this.createCommand(r);return o.helpOption(!1),s&&o.arguments(s),i&&o.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let r=["preSubcommand","preAction","postAction"];if(!r.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
13
+ Expecting one of '${r.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,r){this._exitCallback&&this._exitCallback(new _o(e,t,r)),he.exit(e)}action(e){let t=r=>{let s=this.registeredArguments.length,i=r.slice(0,s);return this._storeOptionsAsProperties?i[s]=this:i[s]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=t,this}createOption(e,t){return new bl(e,t)}_callParseArg(e,t,r,s){try{return e.parseArg(t,r)}catch(i){if(i.code==="commander.invalidArgument"){let o=`${s} ${i.message}`;this.error(o,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let r=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${r}'
14
+ - already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=s=>[s.name()].concat(s.aliases()),r=t(e).find(s=>this._findCommand(s));if(r){let s=t(this._findCommand(r)).join("|"),i=t(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),r=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(r,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(r,e.defaultValue,"default");let s=(i,o,l)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let u=this.getOptionValue(r);i!==null&&e.parseArg?i=this._callParseArg(e,i,u,o):i!==null&&e.variadic&&(i=e._concatValue(i,u)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(r,i,l)};return this.on("option:"+t,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;s(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+t,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;s(i,o,"env")}),this}_optionEx(e,t,r,s,i){if(typeof t=="object"&&t instanceof bl)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(t,r);if(o.makeOptionMandatory(!!e.mandatory),typeof s=="function")o.default(i).argParser(s);else if(s instanceof RegExp){let l=s;s=(u,c)=>{let f=l.exec(u);return f?f[0]:c},o.default(i).argParser(s)}else o.default(s);return this.addOption(o)}option(e,t,r,s){return this._optionEx({},e,t,r,s)}requiredOption(e,t,r,s){return this._optionEx({mandatory:!0},e,t,r,s)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,r){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=r,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(r=>{r.getOptionValueSource(e)!==void 0&&(t=r.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){he.versions?.electron&&(t.from="electron");let s=he.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(t.from="eval")}e===void 0&&(e=he.argv),this.rawArgs=e.slice();let r;switch(t.from){case void 0:case"node":this._scriptPath=e[1],r=e.slice(2);break;case"electron":he.defaultApp?(this._scriptPath=e[1],r=e.slice(2)):r=e.slice(1);break;case"user":r=e.slice(0);break;case"eval":r=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",r}parse(e,t){let r=this._prepareUserArgs(e,t);return this._parseCommand([],r),this}async parseAsync(e,t){let r=this._prepareUserArgs(e,t);return await this._parseCommand([],r),this}_executeSubCommand(e,t){t=t.slice();let r=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function i(f,p){let b=Tt.resolve(f,p);if(wo.existsSync(b))return b;if(s.includes(Tt.extname(p)))return;let w=s.find(T=>wo.existsSync(`${b}${T}`));if(w)return`${b}${w}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,l=this._executableDir||"";if(this._scriptPath){let f;try{f=wo.realpathSync(this._scriptPath)}catch{f=this._scriptPath}l=Tt.resolve(Tt.dirname(f),l)}if(l){let f=i(l,o);if(!f&&!e._executableFile&&this._scriptPath){let p=Tt.basename(this._scriptPath,Tt.extname(this._scriptPath));p!==this._name&&(f=i(l,`${p}-${e._name}`))}o=f||o}r=s.includes(Tt.extname(o));let u;he.platform!=="win32"?r?(t.unshift(o),t=_l(he.execArgv).concat(t),u=bo.spawn(he.argv[0],t,{stdio:"inherit"})):u=bo.spawn(o,t,{stdio:"inherit"}):(t.unshift(o),t=_l(he.execArgv).concat(t),u=bo.spawn(he.execPath,t,{stdio:"inherit"})),u.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(p=>{he.on(p,()=>{u.killed===!1&&u.exitCode===null&&u.kill(p)})});let c=this._exitCallback;u.on("close",f=>{f=f??1,c?c(new _o(f,"commander.executeSubCommandAsync","(close)")):he.exit(f)}),u.on("error",f=>{if(f.code==="ENOENT"){let p=l?`searched for local subcommand relative to directory '${l}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",b=`'${o}' does not exist
15
15
  - if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
16
16
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
17
- - ${p}`;throw new Error(b)}else if(f.code==="EACCES")throw new Error(`'${o}' not executable`);if(!c)he.exit(1);else{let p=new go(1,"commander.executeSubCommandAsync","(error)");p.nestedError=f,c(p)}}),this.runningCommand=u}_dispatchSubcommand(e,t,r){let s=this._findCommand(e);s||this.help({error:!0});let i;return i=this._chainOrCallSubCommandHook(i,s,"preSubcommand"),i=this._chainOrCall(i,()=>{if(s._executableHandler)this._executeSubCommand(s,t.concat(r));else return s._parseCommand(t,r)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(r,s,i)=>{let o=s;if(s!==null&&r.parseArg){let l=`error: command-argument value '${s}' is invalid for argument '${r.name()}'.`;o=this._callParseArg(r,s,i,l)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((r,s)=>{let i=r.defaultValue;r.variadic?s<this.args.length?(i=this.args.slice(s),r.parseArg&&(i=i.reduce((o,l)=>e(r,l,o),r.defaultValue))):i===void 0&&(i=[]):s<this.args.length&&(i=this.args[s],r.parseArg&&(i=e(r,i,r.defaultValue))),t[s]=i}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let r=e,s=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[t]!==void 0).forEach(i=>{i._lifeCycleHooks[t].forEach(o=>{s.push({hookedCommand:i,callback:o})})}),t==="postAction"&&s.reverse(),s.forEach(i=>{r=this._chainOrCall(r,()=>i.callback(i.hookedCommand,this))}),r}_chainOrCallSubCommandHook(e,t,r){let s=e;return this._lifeCycleHooks[r]!==void 0&&this._lifeCycleHooks[r].forEach(i=>{s=this._chainOrCall(s,()=>i(this,t))}),s}_parseCommand(e,t){let r=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(r.operands),t=r.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(r.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{r.unknown.length>0&&this.unknownOption(r.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){s(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(i,e,t)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(i))s(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(r=>{let s=r.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});e.filter(r=>r.conflictsWith.length>0).forEach(r=>{let s=e.find(i=>r.conflictsWith.includes(i.attributeName()));s&&this._conflictingOption(r,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],r=[],s=t,i=e.slice();function o(u){return u.length>1&&u[0]==="-"}let l=null;for(;i.length;){let u=i.shift();if(u==="--"){s===r&&s.push(u),s.push(...i);break}if(l&&!o(u)){this.emit(`option:${l.name()}`,u);continue}if(l=null,o(u)){let c=this._findOption(u);if(c){if(c.required){let f=i.shift();f===void 0&&this.optionMissingArgument(c),this.emit(`option:${c.name()}`,f)}else if(c.optional){let f=null;i.length>0&&!o(i[0])&&(f=i.shift()),this.emit(`option:${c.name()}`,f)}else this.emit(`option:${c.name()}`);l=c.variadic?c:null;continue}}if(u.length>2&&u[0]==="-"&&u[1]!=="-"){let c=this._findOption(`-${u[1]}`);if(c){c.required||c.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${c.name()}`,u.slice(2)):(this.emit(`option:${c.name()}`),i.unshift(`-${u.slice(2)}`));continue}}if(/^--[^=]+=/.test(u)){let c=u.indexOf("="),f=this._findOption(u.slice(0,c));if(f&&(f.required||f.optional)){this.emit(`option:${f.name()}`,u.slice(c+1));continue}}if(o(u)&&(s=r),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&r.length===0){if(this._findCommand(u)){t.push(u),i.length>0&&r.push(...i);break}else if(this._getHelpCommand()&&u===this._getHelpCommand().name()){t.push(u),i.length>0&&t.push(...i);break}else if(this._defaultCommandName){r.push(u),i.length>0&&r.push(...i);break}}if(this._passThroughOptions){s.push(u),i.length>0&&s.push(...i);break}s.push(u)}return{operands:t,unknown:r}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let r=0;r<t;r++){let s=this.options[r].attributeName();e[s]=s===this._versionOptionName?this._version:this[s]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
17
+ - ${p}`;throw new Error(b)}else if(f.code==="EACCES")throw new Error(`'${o}' not executable`);if(!c)he.exit(1);else{let p=new _o(1,"commander.executeSubCommandAsync","(error)");p.nestedError=f,c(p)}}),this.runningCommand=u}_dispatchSubcommand(e,t,r){let s=this._findCommand(e);s||this.help({error:!0});let i;return i=this._chainOrCallSubCommandHook(i,s,"preSubcommand"),i=this._chainOrCall(i,()=>{if(s._executableHandler)this._executeSubCommand(s,t.concat(r));else return s._parseCommand(t,r)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(r,s,i)=>{let o=s;if(s!==null&&r.parseArg){let l=`error: command-argument value '${s}' is invalid for argument '${r.name()}'.`;o=this._callParseArg(r,s,i,l)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((r,s)=>{let i=r.defaultValue;r.variadic?s<this.args.length?(i=this.args.slice(s),r.parseArg&&(i=i.reduce((o,l)=>e(r,l,o),r.defaultValue))):i===void 0&&(i=[]):s<this.args.length&&(i=this.args[s],r.parseArg&&(i=e(r,i,r.defaultValue))),t[s]=i}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let r=e,s=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[t]!==void 0).forEach(i=>{i._lifeCycleHooks[t].forEach(o=>{s.push({hookedCommand:i,callback:o})})}),t==="postAction"&&s.reverse(),s.forEach(i=>{r=this._chainOrCall(r,()=>i.callback(i.hookedCommand,this))}),r}_chainOrCallSubCommandHook(e,t,r){let s=e;return this._lifeCycleHooks[r]!==void 0&&this._lifeCycleHooks[r].forEach(i=>{s=this._chainOrCall(s,()=>i(this,t))}),s}_parseCommand(e,t){let r=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(r.operands),t=r.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(r.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{r.unknown.length>0&&this.unknownOption(r.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){s(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(i,e,t)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(i))s(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(r=>{let s=r.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});e.filter(r=>r.conflictsWith.length>0).forEach(r=>{let s=e.find(i=>r.conflictsWith.includes(i.attributeName()));s&&this._conflictingOption(r,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],r=[],s=t,i=e.slice();function o(u){return u.length>1&&u[0]==="-"}let l=null;for(;i.length;){let u=i.shift();if(u==="--"){s===r&&s.push(u),s.push(...i);break}if(l&&!o(u)){this.emit(`option:${l.name()}`,u);continue}if(l=null,o(u)){let c=this._findOption(u);if(c){if(c.required){let f=i.shift();f===void 0&&this.optionMissingArgument(c),this.emit(`option:${c.name()}`,f)}else if(c.optional){let f=null;i.length>0&&!o(i[0])&&(f=i.shift()),this.emit(`option:${c.name()}`,f)}else this.emit(`option:${c.name()}`);l=c.variadic?c:null;continue}}if(u.length>2&&u[0]==="-"&&u[1]!=="-"){let c=this._findOption(`-${u[1]}`);if(c){c.required||c.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${c.name()}`,u.slice(2)):(this.emit(`option:${c.name()}`),i.unshift(`-${u.slice(2)}`));continue}}if(/^--[^=]+=/.test(u)){let c=u.indexOf("="),f=this._findOption(u.slice(0,c));if(f&&(f.required||f.optional)){this.emit(`option:${f.name()}`,u.slice(c+1));continue}}if(o(u)&&(s=r),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&r.length===0){if(this._findCommand(u)){t.push(u),i.length>0&&r.push(...i);break}else if(this._getHelpCommand()&&u===this._getHelpCommand().name()){t.push(u),i.length>0&&t.push(...i);break}else if(this._defaultCommandName){r.push(u),i.length>0&&r.push(...i);break}}if(this._passThroughOptions){s.push(u),i.length>0&&s.push(...i);break}s.push(u)}return{operands:t,unknown:r}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let r=0;r<t;r++){let s=this.options[r].attributeName();e[s]=s===this._versionOptionName?this._version:this[s]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
18
18
  `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
19
19
  `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
20
- `),this.outputHelp({error:!0}));let r=t||{},s=r.exitCode||1,i=r.code||"commander.error";this._exit(s,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in he.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,he.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new ef(this.options),t=r=>this.getOptionValue(r)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(r));this.options.filter(r=>r.implied!==void 0&&t(r.attributeName())&&e.valueFromOption(this.getOptionValue(r.attributeName()),r)).forEach(r=>{Object.keys(r.implied).filter(s=>!t(s)).forEach(s=>{this.setOptionValueWithSource(s,r.implied[s],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let r=o=>{let l=o.attributeName(),u=this.getOptionValue(l),c=this.options.find(p=>p.negate&&l===p.attributeName()),f=this.options.find(p=>!p.negate&&l===p.attributeName());return c&&(c.presetArg===void 0&&u===!1||c.presetArg!==void 0&&u===c.presetArg)?c:f||o},s=o=>{let l=r(o),u=l.attributeName();return this.getOptionValueSource(u)==="env"?`environment variable '${l.envVar}'`:`option '${l.flags}'`},i=`error: ${s(e)} cannot be used with ${s(t)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],i=this;do{let o=i.createHelp().visibleOptions(i).filter(l=>l.long).map(l=>l.long);s=s.concat(o),i=i.parent}while(i&&!i._enablePositionalOptions);t=fl(e,s)}let r=`error: unknown option '${e}'${t}`;this.error(r,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,r=t===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${r} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(i=>{s.push(i.name()),i.alias()&&s.push(i.alias())}),t=fl(e,s)}let r=`error: unknown command '${e}'${t}`;this.error(r,{code:"commander.unknownCommand"})}version(e,t,r){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",r=r||"output the version number";let s=this.createOption(t,r);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.name(),()=>{this._outputConfiguration.writeOut(`${e}
21
- `),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let r=this.parent?._findCommand(e);if(r){let s=[r.name()].concat(r.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(r=>Xh(r));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=kt.basename(e,kt.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};let t={error:!!e.error},r;return t.error?r=s=>this._outputConfiguration.writeErr(s):r=s=>this._outputConfiguration.writeOut(s),t.write=e.write||r,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let r=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",r)),this.emit("beforeHelp",r);let s=this.helpInformation(r);if(t&&(s=t(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");r.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",r),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",r))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=he.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let r=["beforeAll","before","after","afterAll"];if(!r.includes(e))throw new Error(`Unexpected value for position to addHelpText.
20
+ `),this.outputHelp({error:!0}));let r=t||{},s=r.exitCode||1,i=r.code||"commander.error";this._exit(s,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in he.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,he.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new df(this.options),t=r=>this.getOptionValue(r)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(r));this.options.filter(r=>r.implied!==void 0&&t(r.attributeName())&&e.valueFromOption(this.getOptionValue(r.attributeName()),r)).forEach(r=>{Object.keys(r.implied).filter(s=>!t(s)).forEach(s=>{this.setOptionValueWithSource(s,r.implied[s],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let r=o=>{let l=o.attributeName(),u=this.getOptionValue(l),c=this.options.find(p=>p.negate&&l===p.attributeName()),f=this.options.find(p=>!p.negate&&l===p.attributeName());return c&&(c.presetArg===void 0&&u===!1||c.presetArg!==void 0&&u===c.presetArg)?c:f||o},s=o=>{let l=r(o),u=l.attributeName();return this.getOptionValueSource(u)==="env"?`environment variable '${l.envVar}'`:`option '${l.flags}'`},i=`error: ${s(e)} cannot be used with ${s(t)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],i=this;do{let o=i.createHelp().visibleOptions(i).filter(l=>l.long).map(l=>l.long);s=s.concat(o),i=i.parent}while(i&&!i._enablePositionalOptions);t=wl(e,s)}let r=`error: unknown option '${e}'${t}`;this.error(r,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,r=t===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${r} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(i=>{s.push(i.name()),i.alias()&&s.push(i.alias())}),t=wl(e,s)}let r=`error: unknown command '${e}'${t}`;this.error(r,{code:"commander.unknownCommand"})}version(e,t,r){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",r=r||"output the version number";let s=this.createOption(t,r);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.name(),()=>{this._outputConfiguration.writeOut(`${e}
21
+ `),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let r=this.parent?._findCommand(e);if(r){let s=[r.name()].concat(r.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(r=>uf(r));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=Tt.basename(e,Tt.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};let t={error:!!e.error},r;return t.error?r=s=>this._outputConfiguration.writeErr(s):r=s=>this._outputConfiguration.writeOut(s),t.write=e.write||r,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let r=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",r)),this.emit("beforeHelp",r);let s=this.helpInformation(r);if(t&&(s=t(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");r.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",r),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",r))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=he.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let r=["beforeAll","before","after","afterAll"];if(!r.includes(e))throw new Error(`Unexpected value for position to addHelpText.
22
22
  Expecting one of '${r.join("', '")}'`);let s=`${e}Help`;return this.on(s,i=>{let o;typeof t=="function"?o=t({error:i.error,command:i.command}):o=t,o&&i.write(`${o}
23
- `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(s=>t.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function pl(n){return n.map(e=>{if(!e.startsWith("--inspect"))return e;let t,r="127.0.0.1",s="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?t=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=i[1],/^\d+$/.test(i[3])?s=i[3]:r=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],r=i[3],s=i[4]),t&&s!=="0"?`${t}=${r}:${parseInt(s)+1}`:e})}ml.Command=yo});var wl=ne(Ue=>{var{Argument:yl}=Us(),{Command:vo}=gl(),{CommanderError:tf,InvalidArgumentError:vl}=os(),{Help:nf}=lo(),{Option:bl}=fo();Ue.program=new vo;Ue.createCommand=n=>new vo(n);Ue.createOption=(n,e)=>new bl(n,e);Ue.createArgument=(n,e)=>new yl(n,e);Ue.Command=vo;Ue.Option=bl;Ue.Argument=yl;Ue.Help=nf;Ue.CommanderError=tf;Ue.InvalidArgumentError=vl;Ue.InvalidOptionArgumentError=vl});var ds=ne(ae=>{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});ae.getParsedType=ae.ZodParsedType=ae.objectUtil=ae.util=void 0;var Co;(function(n){n.assertEqual=s=>{};function e(s){}n.assertIs=e;function t(s){throw new Error}n.assertNever=t,n.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},n.getValidEnumValues=s=>{let i=n.objectKeys(s).filter(l=>typeof s[s[l]]!="number"),o={};for(let l of i)o[l]=s[l];return n.objectValues(o)},n.objectValues=s=>n.objectKeys(s).map(function(i){return s[i]}),n.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},n.find=(s,i)=>{for(let o of s)if(i(o))return o},n.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}n.joinValues=r,n.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(Co||(ae.util=Co={}));var Kl;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(Kl||(ae.objectUtil=Kl={}));ae.ZodParsedType=Co.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var _p=n=>{switch(typeof n){case"undefined":return ae.ZodParsedType.undefined;case"string":return ae.ZodParsedType.string;case"number":return Number.isNaN(n)?ae.ZodParsedType.nan:ae.ZodParsedType.number;case"boolean":return ae.ZodParsedType.boolean;case"function":return ae.ZodParsedType.function;case"bigint":return ae.ZodParsedType.bigint;case"symbol":return ae.ZodParsedType.symbol;case"object":return Array.isArray(n)?ae.ZodParsedType.array:n===null?ae.ZodParsedType.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?ae.ZodParsedType.promise:typeof Map<"u"&&n instanceof Map?ae.ZodParsedType.map:typeof Set<"u"&&n instanceof Set?ae.ZodParsedType.set:typeof Date<"u"&&n instanceof Date?ae.ZodParsedType.date:ae.ZodParsedType.object;default:return ae.ZodParsedType.unknown}};ae.getParsedType=_p});var ei=ne(Wt=>{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.ZodError=Wt.quotelessJson=Wt.ZodIssueCode=void 0;var Zl=ds();Wt.ZodIssueCode=Zl.util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);var kp=n=>JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:");Wt.quotelessJson=kp;var hs=class n extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},r={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)r._errors.push(t(o));else{let l=r,u=0;for(;u<o.path.length;){let c=o.path[u];u===o.path.length-1?(l[c]=l[c]||{_errors:[]},l[c]._errors.push(t(o))):l[c]=l[c]||{_errors:[]},l=l[c],u++}}};return s(this),r}static assert(e){if(!(e instanceof n))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Zl.util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},r=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];t[i]=t[i]||[],t[i].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}};Wt.ZodError=hs;hs.create=n=>new hs(n)});var Ro=ne(Io=>{"use strict";Object.defineProperty(Io,"__esModule",{value:!0});var Se=ei(),En=ds(),Sp=(n,e)=>{let t;switch(n.code){case Se.ZodIssueCode.invalid_type:n.received===En.ZodParsedType.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case Se.ZodIssueCode.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,En.util.jsonStringifyReplacer)}`;break;case Se.ZodIssueCode.unrecognized_keys:t=`Unrecognized key(s) in object: ${En.util.joinValues(n.keys,", ")}`;break;case Se.ZodIssueCode.invalid_union:t="Invalid input";break;case Se.ZodIssueCode.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${En.util.joinValues(n.options)}`;break;case Se.ZodIssueCode.invalid_enum_value:t=`Invalid enum value. Expected ${En.util.joinValues(n.options)}, received '${n.received}'`;break;case Se.ZodIssueCode.invalid_arguments:t="Invalid function arguments";break;case Se.ZodIssueCode.invalid_return_type:t="Invalid function return type";break;case Se.ZodIssueCode.invalid_date:t="Invalid date";break;case Se.ZodIssueCode.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:En.util.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case Se.ZodIssueCode.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case Se.ZodIssueCode.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case Se.ZodIssueCode.custom:t="Invalid input";break;case Se.ZodIssueCode.invalid_intersection_types:t="Intersection results could not be merged";break;case Se.ZodIssueCode.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case Se.ZodIssueCode.not_finite:t="Number must be finite";break;default:t=e.defaultError,En.util.assertNever(n)}return{message:t}};Io.default=Sp});var ti=ne(Jt=>{"use strict";var Tp=Jt&&Jt.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(Jt,"__esModule",{value:!0});Jt.defaultErrorMap=void 0;Jt.setErrorMap=xp;Jt.getErrorMap=Cp;var Gl=Tp(Ro());Jt.defaultErrorMap=Gl.default;var Hl=Gl.default;function xp(n){Hl=n}function Cp(){return Hl}});var Ao=ne(oe=>{"use strict";var Ip=oe&&oe.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(oe,"__esModule",{value:!0});oe.isAsync=oe.isValid=oe.isDirty=oe.isAborted=oe.OK=oe.DIRTY=oe.INVALID=oe.ParseStatus=oe.EMPTY_PATH=oe.makeIssue=void 0;oe.addIssueToContext=Ap;var Rp=ti(),Vl=Ip(Ro()),Ep=n=>{let{data:e,path:t,errorMaps:r,issueData:s}=n,i=[...t,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let l="",u=r.filter(c=>!!c).slice().reverse();for(let c of u)l=c(o,{data:e,defaultError:l}).message;return{...s,path:i,message:l}};oe.makeIssue=Ep;oe.EMPTY_PATH=[];function Ap(n,e){let t=(0,Rp.getErrorMap)(),r=(0,oe.makeIssue)({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===Vl.default?void 0:Vl.default].filter(s=>!!s)});n.common.issues.push(r)}var Eo=class n{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let r=[];for(let s of t){if(s.status==="aborted")return oe.INVALID;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let s of t){let i=await s.key,o=await s.value;r.push({key:i,value:o})}return n.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let s of t){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return oe.INVALID;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(r[i.value]=o.value)}return{status:e.value,value:r}}};oe.ParseStatus=Eo;oe.INVALID=Object.freeze({status:"aborted"});var $p=n=>({status:"dirty",value:n});oe.DIRTY=$p;var Pp=n=>({status:"valid",value:n});oe.OK=Pp;var jp=n=>n.status==="aborted";oe.isAborted=jp;var Op=n=>n.status==="dirty";oe.isDirty=Op;var Np=n=>n.status==="valid";oe.isValid=Np;var Mp=n=>typeof Promise<"u"&&n instanceof Promise;oe.isAsync=Mp});var Jl=ne(Wl=>{"use strict";Object.defineProperty(Wl,"__esModule",{value:!0})});var Xl=ne(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.errorUtil=void 0;var Yl;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e?.message})(Yl||(ni.errorUtil=Yl={}))});var cu=ne(_=>{"use strict";Object.defineProperty(_,"__esModule",{value:!0});_.discriminatedUnion=_.date=_.boolean=_.bigint=_.array=_.any=_.coerce=_.ZodFirstPartyTypeKind=_.late=_.ZodSchema=_.Schema=_.ZodReadonly=_.ZodPipeline=_.ZodBranded=_.BRAND=_.ZodNaN=_.ZodCatch=_.ZodDefault=_.ZodNullable=_.ZodOptional=_.ZodTransformer=_.ZodEffects=_.ZodPromise=_.ZodNativeEnum=_.ZodEnum=_.ZodLiteral=_.ZodLazy=_.ZodFunction=_.ZodSet=_.ZodMap=_.ZodRecord=_.ZodTuple=_.ZodIntersection=_.ZodDiscriminatedUnion=_.ZodUnion=_.ZodObject=_.ZodArray=_.ZodVoid=_.ZodNever=_.ZodUnknown=_.ZodAny=_.ZodNull=_.ZodUndefined=_.ZodSymbol=_.ZodDate=_.ZodBoolean=_.ZodBigInt=_.ZodNumber=_.ZodString=_.ZodType=void 0;_.NEVER=_.void=_.unknown=_.union=_.undefined=_.tuple=_.transformer=_.symbol=_.string=_.strictObject=_.set=_.record=_.promise=_.preprocess=_.pipeline=_.ostring=_.optional=_.onumber=_.oboolean=_.object=_.number=_.nullable=_.null=_.never=_.nativeEnum=_.nan=_.map=_.literal=_.lazy=_.intersection=_.instanceof=_.function=_.enum=_.effect=void 0;_.datetimeRegex=ru;_.custom=iu;var E=ei(),ri=ti(),U=Xl(),S=Ao(),$=ds(),Ze=class{constructor(e,t,r,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Ql=(n,e)=>{if((0,S.isValid)(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new E.ZodError(n.common.issues);return this._error=t,this._error}}};function W(n){if(!n)return{};let{errorMap:e,invalid_type_error:t,required_error:r,description:s}=n;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,l)=>{let{message:u}=n;return o.code==="invalid_enum_value"?{message:u??l.defaultError}:typeof l.data>"u"?{message:u??r??l.defaultError}:o.code!=="invalid_type"?{message:l.defaultError}:{message:u??t??l.defaultError}},description:s}}var J=class{get description(){return this._def.description}_getType(e){return(0,$.getParsedType)(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:(0,$.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new S.ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:(0,$.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if((0,S.isAsync)(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,$.getParsedType)(e)},s=this._parseSync({data:e,path:r.path,parent:r});return Ql(r,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,$.getParsedType)(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return(0,S.isValid)(r)?{value:r.value}:{issues:t.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(r=>(0,S.isValid)(r)?{value:r.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,$.getParsedType)(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await((0,S.isAsync)(s)?s:Promise.resolve(s));return Ql(r,i)}refine(e,t){let r=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,i)=>{let o=e(s),l=()=>i.addIssue({code:E.ZodIssueCode.custom,...r(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(u=>u?!0:(l(),!1)):o?!0:(l(),!1)})}refinement(e,t){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof t=="function"?t(r,s):t),!1))}_refinement(e){return new Ne({schema:this,typeName:G.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return Ke.create(this,this._def)}nullable(){return ht.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return At.create(this)}promise(){return Qt.create(this,this._def)}or(e){return Mn.create([this,e],this._def)}and(e){return zn.create(this,e,this._def)}transform(e){return new Ne({...W(this._def),schema:this,typeName:G.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Fn({...W(this._def),innerType:this,defaultValue:t,typeName:G.ZodDefault})}brand(){return new fs({typeName:G.ZodBranded,type:this,...W(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Bn({...W(this._def),innerType:this,catchValue:t,typeName:G.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ps.create(this,e)}readonly(){return Kn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};_.ZodType=J;_.Schema=J;_.ZodSchema=J;var zp=/^c[^\s-]{8,}$/i,Dp=/^[0-9a-z]+$/,Lp=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Up=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,qp=/^[a-z0-9_-]{21}$/i,Fp=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Bp=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Kp=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Zp="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",$o,Gp=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Hp=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Vp=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Wp=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Jp=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Yp=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,tu="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Xp=new RegExp(`^${tu}$`);function nu(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);let t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Qp(n){return new RegExp(`^${nu(n)}$`)}function ru(n){let e=`${tu}T${nu(n)}`,t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function em(n,e){return!!((e==="v4"||!e)&&Gp.test(n)||(e==="v6"||!e)&&Vp.test(n))}function tm(n,e){if(!Fp.test(n))return!1;try{let[t]=n.split(".");if(!t)return!1;let r=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function nm(n,e){return!!((e==="v4"||!e)&&Hp.test(n)||(e==="v6"||!e)&&Wp.test(n))}var Yt=class n extends J{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==$.ZodParsedType.string){let i=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(i,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.string,received:i.parsedType}),S.INVALID}let r=new S.ParseStatus,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:E.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:E.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,l=e.data.length<i.value;(o||l)&&(s=this._getOrReturnCtx(e,s),o?(0,S.addIssueToContext)(s,{code:E.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):l&&(0,S.addIssueToContext)(s,{code:E.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")Kp.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"email",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")$o||($o=new RegExp(Zp,"u")),$o.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"emoji",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")Up.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"uuid",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")qp.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"nanoid",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")zp.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"cuid",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")Dp.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"cuid2",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")Lp.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"ulid",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"url",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"regex",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:E.ZodIssueCode.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:E.ZodIssueCode.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:E.ZodIssueCode.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?ru(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:E.ZodIssueCode.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?Xp.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:E.ZodIssueCode.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Qp(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:E.ZodIssueCode.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?Bp.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"duration",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?em(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"ip",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?tm(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"jwt",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?nm(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"cidr",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?Jp.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"base64",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?Yp.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"base64url",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):$.util.assertNever(i);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(s=>e.test(s),{validation:t,code:E.ZodIssueCode.invalid_string,...U.errorUtil.errToObj(r)})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...U.errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...U.errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...U.errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...U.errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...U.errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...U.errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...U.errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...U.errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...U.errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...U.errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...U.errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...U.errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...U.errorUtil.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...U.errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...U.errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...U.errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...U.errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...U.errorUtil.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...U.errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...U.errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...U.errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...U.errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...U.errorUtil.errToObj(t)})}nonempty(e){return this.min(1,U.errorUtil.errToObj(e))}trim(){return new n({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};_.ZodString=Yt;Yt.create=n=>new Yt({checks:[],typeName:G.ZodString,coerce:n?.coerce??!1,...W(n)});function rm(n,e){let t=(n.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=t>r?t:r,i=Number.parseInt(n.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var An=class n extends J{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==$.ZodParsedType.number){let i=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(i,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.number,received:i.parsedType}),S.INVALID}let r,s=new S.ParseStatus;for(let i of this._def.checks)i.kind==="int"?$.util.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?rm(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.not_finite,message:i.message}),s.dirty()):$.util.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,U.errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,U.errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,U.errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,U.errorUtil.toString(t))}setLimit(e,t,r,s){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:U.errorUtil.toString(s)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:U.errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:U.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:U.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:U.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:U.errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:U.errorUtil.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:U.errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:U.errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:U.errorUtil.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&$.util.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(t===null||r.value>t)&&(t=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}};_.ZodNumber=An;An.create=n=>new An({checks:[],typeName:G.ZodNumber,coerce:n?.coerce||!1,...W(n)});var $n=class n extends J{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==$.ZodParsedType.bigint)return this._getInvalidInput(e);let r,s=new S.ParseStatus;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):$.util.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(t,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.bigint,received:t.parsedType}),S.INVALID}gte(e,t){return this.setLimit("min",e,!0,U.errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,U.errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,U.errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,U.errorUtil.toString(t))}setLimit(e,t,r,s){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:U.errorUtil.toString(s)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:U.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:U.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:U.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:U.errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:U.errorUtil.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};_.ZodBigInt=$n;$n.create=n=>new $n({checks:[],typeName:G.ZodBigInt,coerce:n?.coerce??!1,...W(n)});var Pn=class extends J{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==$.ZodParsedType.boolean){let r=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.boolean,received:r.parsedType}),S.INVALID}return(0,S.OK)(e.data)}};_.ZodBoolean=Pn;Pn.create=n=>new Pn({typeName:G.ZodBoolean,coerce:n?.coerce||!1,...W(n)});var jn=class n extends J{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==$.ZodParsedType.date){let i=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(i,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.date,received:i.parsedType}),S.INVALID}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(i,{code:E.ZodIssueCode.invalid_date}),S.INVALID}let r=new S.ParseStatus,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:E.ZodIssueCode.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:E.ZodIssueCode.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):$.util.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:U.errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:U.errorUtil.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};_.ZodDate=jn;jn.create=n=>new jn({checks:[],coerce:n?.coerce||!1,typeName:G.ZodDate,...W(n)});var Ar=class extends J{_parse(e){if(this._getType(e)!==$.ZodParsedType.symbol){let r=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.symbol,received:r.parsedType}),S.INVALID}return(0,S.OK)(e.data)}};_.ZodSymbol=Ar;Ar.create=n=>new Ar({typeName:G.ZodSymbol,...W(n)});var On=class extends J{_parse(e){if(this._getType(e)!==$.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.undefined,received:r.parsedType}),S.INVALID}return(0,S.OK)(e.data)}};_.ZodUndefined=On;On.create=n=>new On({typeName:G.ZodUndefined,...W(n)});var Nn=class extends J{_parse(e){if(this._getType(e)!==$.ZodParsedType.null){let r=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.null,received:r.parsedType}),S.INVALID}return(0,S.OK)(e.data)}};_.ZodNull=Nn;Nn.create=n=>new Nn({typeName:G.ZodNull,...W(n)});var Xt=class extends J{constructor(){super(...arguments),this._any=!0}_parse(e){return(0,S.OK)(e.data)}};_.ZodAny=Xt;Xt.create=n=>new Xt({typeName:G.ZodAny,...W(n)});var Et=class extends J{constructor(){super(...arguments),this._unknown=!0}_parse(e){return(0,S.OK)(e.data)}};_.ZodUnknown=Et;Et.create=n=>new Et({typeName:G.ZodUnknown,...W(n)});var Qe=class extends J{_parse(e){let t=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(t,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.never,received:t.parsedType}),S.INVALID}};_.ZodNever=Qe;Qe.create=n=>new Qe({typeName:G.ZodNever,...W(n)});var $r=class extends J{_parse(e){if(this._getType(e)!==$.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.void,received:r.parsedType}),S.INVALID}return(0,S.OK)(e.data)}};_.ZodVoid=$r;$r.create=n=>new $r({typeName:G.ZodVoid,...W(n)});var At=class n extends J{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==$.ZodParsedType.array)return(0,S.addIssueToContext)(t,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.array,received:t.parsedType}),S.INVALID;if(s.exactLength!==null){let o=t.data.length>s.exactLength.value,l=t.data.length<s.exactLength.value;(o||l)&&((0,S.addIssueToContext)(t,{code:o?E.ZodIssueCode.too_big:E.ZodIssueCode.too_small,minimum:l?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&((0,S.addIssueToContext)(t,{code:E.ZodIssueCode.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&((0,S.addIssueToContext)(t,{code:E.ZodIssueCode.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((o,l)=>s.type._parseAsync(new Ze(t,o,t.path,l)))).then(o=>S.ParseStatus.mergeArray(r,o));let i=[...t.data].map((o,l)=>s.type._parseSync(new Ze(t,o,t.path,l)));return S.ParseStatus.mergeArray(r,i)}get element(){return this._def.type}min(e,t){return new n({...this._def,minLength:{value:e,message:U.errorUtil.toString(t)}})}max(e,t){return new n({...this._def,maxLength:{value:e,message:U.errorUtil.toString(t)}})}length(e,t){return new n({...this._def,exactLength:{value:e,message:U.errorUtil.toString(t)}})}nonempty(e){return this.min(1,e)}};_.ZodArray=At;At.create=(n,e)=>new At({type:n,minLength:null,maxLength:null,exactLength:null,typeName:G.ZodArray,...W(e)});function Er(n){if(n instanceof Ae){let e={};for(let t in n.shape){let r=n.shape[t];e[t]=Ke.create(Er(r))}return new Ae({...n._def,shape:()=>e})}else return n instanceof At?new At({...n._def,type:Er(n.element)}):n instanceof Ke?Ke.create(Er(n.unwrap())):n instanceof ht?ht.create(Er(n.unwrap())):n instanceof dt?dt.create(n.items.map(e=>Er(e))):n}var Ae=class n extends J{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=$.util.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==$.ZodParsedType.object){let c=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(c,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.object,received:c.parsedType}),S.INVALID}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),l=[];if(!(this._def.catchall instanceof Qe&&this._def.unknownKeys==="strip"))for(let c in s.data)o.includes(c)||l.push(c);let u=[];for(let c of o){let f=i[c],p=s.data[c];u.push({key:{status:"valid",value:c},value:f._parse(new Ze(s,p,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof Qe){let c=this._def.unknownKeys;if(c==="passthrough")for(let f of l)u.push({key:{status:"valid",value:f},value:{status:"valid",value:s.data[f]}});else if(c==="strict")l.length>0&&((0,S.addIssueToContext)(s,{code:E.ZodIssueCode.unrecognized_keys,keys:l}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let f of l){let p=s.data[f];u.push({key:{status:"valid",value:f},value:c._parse(new Ze(s,p,s.path,f)),alwaysSet:f in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let c=[];for(let f of u){let p=await f.key,b=await f.value;c.push({key:p,value:b,alwaysSet:f.alwaysSet})}return c}).then(c=>S.ParseStatus.mergeObjectSync(r,c)):S.ParseStatus.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(e){return U.errorUtil.errToObj,new n({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{let s=this._def.errorMap?.(t,r).message??r.defaultError;return t.code==="unrecognized_keys"?{message:U.errorUtil.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new n({...this._def,unknownKeys:"strip"})}passthrough(){return new n({...this._def,unknownKeys:"passthrough"})}extend(e){return new n({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new n({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:G.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new n({...this._def,catchall:e})}pick(e){let t={};for(let r of $.util.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new n({...this._def,shape:()=>t})}omit(e){let t={};for(let r of $.util.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new n({...this._def,shape:()=>t})}deepPartial(){return Er(this)}partial(e){let t={};for(let r of $.util.objectKeys(this.shape)){let s=this.shape[r];e&&!e[r]?t[r]=s:t[r]=s.optional()}return new n({...this._def,shape:()=>t})}required(e){let t={};for(let r of $.util.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Ke;)i=i._def.innerType;t[r]=i}return new n({...this._def,shape:()=>t})}keyof(){return su($.util.objectKeys(this.shape))}};_.ZodObject=Ae;Ae.create=(n,e)=>new Ae({shape:()=>n,unknownKeys:"strip",catchall:Qe.create(),typeName:G.ZodObject,...W(e)});Ae.strictCreate=(n,e)=>new Ae({shape:()=>n,unknownKeys:"strict",catchall:Qe.create(),typeName:G.ZodObject,...W(e)});Ae.lazycreate=(n,e)=>new Ae({shape:n,unknownKeys:"strip",catchall:Qe.create(),typeName:G.ZodObject,...W(e)});var Mn=class extends J{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;function s(i){for(let l of i)if(l.result.status==="valid")return l.result;for(let l of i)if(l.result.status==="dirty")return t.common.issues.push(...l.ctx.common.issues),l.result;let o=i.map(l=>new E.ZodError(l.ctx.common.issues));return(0,S.addIssueToContext)(t,{code:E.ZodIssueCode.invalid_union,unionErrors:o}),S.INVALID}if(t.common.async)return Promise.all(r.map(async i=>{let o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let u of r){let c={...t,common:{...t.common,issues:[]},parent:null},f=u._parseSync({data:t.data,path:t.path,parent:c});if(f.status==="valid")return f;f.status==="dirty"&&!i&&(i={result:f,ctx:c}),c.common.issues.length&&o.push(c.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let l=o.map(u=>new E.ZodError(u));return(0,S.addIssueToContext)(t,{code:E.ZodIssueCode.invalid_union,unionErrors:l}),S.INVALID}}get options(){return this._def.options}};_.ZodUnion=Mn;Mn.create=(n,e)=>new Mn({options:n,typeName:G.ZodUnion,...W(e)});var Rt=n=>n instanceof Dn?Rt(n.schema):n instanceof Ne?Rt(n.innerType()):n instanceof Ln?[n.value]:n instanceof Un?n.options:n instanceof qn?$.util.objectValues(n.enum):n instanceof Fn?Rt(n._def.innerType):n instanceof On?[void 0]:n instanceof Nn?[null]:n instanceof Ke?[void 0,...Rt(n.unwrap())]:n instanceof ht?[null,...Rt(n.unwrap())]:n instanceof fs||n instanceof Kn?Rt(n.unwrap()):n instanceof Bn?Rt(n._def.innerType):[],si=class n extends J{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==$.ZodParsedType.object)return(0,S.addIssueToContext)(t,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.object,received:t.parsedType}),S.INVALID;let r=this.discriminator,s=t.data[r],i=this.optionsMap.get(s);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):((0,S.addIssueToContext)(t,{code:E.ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),S.INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let s=new Map;for(let i of t){let o=Rt(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let l of o){if(s.has(l))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(l)}`);s.set(l,i)}}return new n({typeName:G.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...W(r)})}};_.ZodDiscriminatedUnion=si;function Po(n,e){let t=(0,$.getParsedType)(n),r=(0,$.getParsedType)(e);if(n===e)return{valid:!0,data:n};if(t===$.ZodParsedType.object&&r===$.ZodParsedType.object){let s=$.util.objectKeys(e),i=$.util.objectKeys(n).filter(l=>s.indexOf(l)!==-1),o={...n,...e};for(let l of i){let u=Po(n[l],e[l]);if(!u.valid)return{valid:!1};o[l]=u.data}return{valid:!0,data:o}}else if(t===$.ZodParsedType.array&&r===$.ZodParsedType.array){if(n.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<n.length;i++){let o=n[i],l=e[i],u=Po(o,l);if(!u.valid)return{valid:!1};s.push(u.data)}return{valid:!0,data:s}}else return t===$.ZodParsedType.date&&r===$.ZodParsedType.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}var zn=class extends J{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),s=(i,o)=>{if((0,S.isAborted)(i)||(0,S.isAborted)(o))return S.INVALID;let l=Po(i.value,o.value);return l.valid?(((0,S.isDirty)(i)||(0,S.isDirty)(o))&&t.dirty(),{status:t.value,value:l.data}):((0,S.addIssueToContext)(r,{code:E.ZodIssueCode.invalid_intersection_types}),S.INVALID)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};_.ZodIntersection=zn;zn.create=(n,e,t)=>new zn({left:n,right:e,typeName:G.ZodIntersection,...W(t)});var dt=class n extends J{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==$.ZodParsedType.array)return(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.array,received:r.parsedType}),S.INVALID;if(r.data.length<this._def.items.length)return(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),S.INVALID;!this._def.rest&&r.data.length>this._def.items.length&&((0,S.addIssueToContext)(r,{code:E.ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...r.data].map((o,l)=>{let u=this._def.items[l]||this._def.rest;return u?u._parse(new Ze(r,o,r.path,l)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>S.ParseStatus.mergeArray(t,o)):S.ParseStatus.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new n({...this._def,rest:e})}};_.ZodTuple=dt;dt.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new dt({items:n,typeName:G.ZodTuple,rest:null,...W(e)})};var ii=class n extends J{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==$.ZodParsedType.object)return(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.object,received:r.parsedType}),S.INVALID;let s=[],i=this._def.keyType,o=this._def.valueType;for(let l in r.data)s.push({key:i._parse(new Ze(r,l,r.path,l)),value:o._parse(new Ze(r,r.data[l],r.path,l)),alwaysSet:l in r.data});return r.common.async?S.ParseStatus.mergeObjectAsync(t,s):S.ParseStatus.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,r){return t instanceof J?new n({keyType:e,valueType:t,typeName:G.ZodRecord,...W(r)}):new n({keyType:Yt.create(),valueType:e,typeName:G.ZodRecord,...W(t)})}};_.ZodRecord=ii;var Pr=class extends J{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==$.ZodParsedType.map)return(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.map,received:r.parsedType}),S.INVALID;let s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([l,u],c)=>({key:s._parse(new Ze(r,l,r.path,[c,"key"])),value:i._parse(new Ze(r,u,r.path,[c,"value"]))}));if(r.common.async){let l=new Map;return Promise.resolve().then(async()=>{for(let u of o){let c=await u.key,f=await u.value;if(c.status==="aborted"||f.status==="aborted")return S.INVALID;(c.status==="dirty"||f.status==="dirty")&&t.dirty(),l.set(c.value,f.value)}return{status:t.value,value:l}})}else{let l=new Map;for(let u of o){let c=u.key,f=u.value;if(c.status==="aborted"||f.status==="aborted")return S.INVALID;(c.status==="dirty"||f.status==="dirty")&&t.dirty(),l.set(c.value,f.value)}return{status:t.value,value:l}}}};_.ZodMap=Pr;Pr.create=(n,e,t)=>new Pr({valueType:e,keyType:n,typeName:G.ZodMap,...W(t)});var jr=class n extends J{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==$.ZodParsedType.set)return(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.set,received:r.parsedType}),S.INVALID;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&((0,S.addIssueToContext)(r,{code:E.ZodIssueCode.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&((0,S.addIssueToContext)(r,{code:E.ZodIssueCode.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let i=this._def.valueType;function o(u){let c=new Set;for(let f of u){if(f.status==="aborted")return S.INVALID;f.status==="dirty"&&t.dirty(),c.add(f.value)}return{status:t.value,value:c}}let l=[...r.data.values()].map((u,c)=>i._parse(new Ze(r,u,r.path,c)));return r.common.async?Promise.all(l).then(u=>o(u)):o(l)}min(e,t){return new n({...this._def,minSize:{value:e,message:U.errorUtil.toString(t)}})}max(e,t){return new n({...this._def,maxSize:{value:e,message:U.errorUtil.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};_.ZodSet=jr;jr.create=(n,e)=>new jr({valueType:n,minSize:null,maxSize:null,typeName:G.ZodSet,...W(e)});var oi=class n extends J{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==$.ZodParsedType.function)return(0,S.addIssueToContext)(t,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.function,received:t.parsedType}),S.INVALID;function r(l,u){return(0,S.makeIssue)({data:l,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,(0,ri.getErrorMap)(),ri.defaultErrorMap].filter(c=>!!c),issueData:{code:E.ZodIssueCode.invalid_arguments,argumentsError:u}})}function s(l,u){return(0,S.makeIssue)({data:l,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,(0,ri.getErrorMap)(),ri.defaultErrorMap].filter(c=>!!c),issueData:{code:E.ZodIssueCode.invalid_return_type,returnTypeError:u}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof Qt){let l=this;return(0,S.OK)(async function(...u){let c=new E.ZodError([]),f=await l._def.args.parseAsync(u,i).catch(w=>{throw c.addIssue(r(u,w)),c}),p=await Reflect.apply(o,this,f);return await l._def.returns._def.type.parseAsync(p,i).catch(w=>{throw c.addIssue(s(p,w)),c})})}else{let l=this;return(0,S.OK)(function(...u){let c=l._def.args.safeParse(u,i);if(!c.success)throw new E.ZodError([r(u,c.error)]);let f=Reflect.apply(o,this,c.data),p=l._def.returns.safeParse(f,i);if(!p.success)throw new E.ZodError([s(f,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new n({...this._def,args:dt.create(e).rest(Et.create())})}returns(e){return new n({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new n({args:e||dt.create([]).rest(Et.create()),returns:t||Et.create(),typeName:G.ZodFunction,...W(r)})}};_.ZodFunction=oi;var Dn=class extends J{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};_.ZodLazy=Dn;Dn.create=(n,e)=>new Dn({getter:n,typeName:G.ZodLazy,...W(e)});var Ln=class extends J{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(t,{received:t.data,code:E.ZodIssueCode.invalid_literal,expected:this._def.value}),S.INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}};_.ZodLiteral=Ln;Ln.create=(n,e)=>new Ln({value:n,typeName:G.ZodLiteral,...W(e)});function su(n,e){return new Un({values:n,typeName:G.ZodEnum,...W(e)})}var Un=class n extends J{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),r=this._def.values;return(0,S.addIssueToContext)(t,{expected:$.util.joinValues(r),received:t.parsedType,code:E.ZodIssueCode.invalid_type}),S.INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return(0,S.addIssueToContext)(t,{received:t.data,code:E.ZodIssueCode.invalid_enum_value,options:r}),S.INVALID}return(0,S.OK)(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return n.create(e,{...this._def,...t})}exclude(e,t=this._def){return n.create(this.options.filter(r=>!e.includes(r)),{...this._def,...t})}};_.ZodEnum=Un;Un.create=su;var qn=class extends J{_parse(e){let t=$.util.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==$.ZodParsedType.string&&r.parsedType!==$.ZodParsedType.number){let s=$.util.objectValues(t);return(0,S.addIssueToContext)(r,{expected:$.util.joinValues(s),received:r.parsedType,code:E.ZodIssueCode.invalid_type}),S.INVALID}if(this._cache||(this._cache=new Set($.util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=$.util.objectValues(t);return(0,S.addIssueToContext)(r,{received:r.data,code:E.ZodIssueCode.invalid_enum_value,options:s}),S.INVALID}return(0,S.OK)(e.data)}get enum(){return this._def.values}};_.ZodNativeEnum=qn;qn.create=(n,e)=>new qn({values:n,typeName:G.ZodNativeEnum,...W(e)});var Qt=class extends J{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==$.ZodParsedType.promise&&t.common.async===!1)return(0,S.addIssueToContext)(t,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.promise,received:t.parsedType}),S.INVALID;let r=t.parsedType===$.ZodParsedType.promise?t.data:Promise.resolve(t.data);return(0,S.OK)(r.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};_.ZodPromise=Qt;Qt.create=(n,e)=>new Qt({type:n,typeName:G.ZodPromise,...W(e)});var Ne=class extends J{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===G.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{(0,S.addIssueToContext)(r,o),o.fatal?t.abort():t.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(r.data,i);if(r.common.async)return Promise.resolve(o).then(async l=>{if(t.value==="aborted")return S.INVALID;let u=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return u.status==="aborted"?S.INVALID:u.status==="dirty"||t.value==="dirty"?(0,S.DIRTY)(u.value):u});{if(t.value==="aborted")return S.INVALID;let l=this._def.schema._parseSync({data:o,path:r.path,parent:r});return l.status==="aborted"?S.INVALID:l.status==="dirty"||t.value==="dirty"?(0,S.DIRTY)(l.value):l}}if(s.type==="refinement"){let o=l=>{let u=s.refinement(l,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){let l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?S.INVALID:(l.status==="dirty"&&t.dirty(),o(l.value),{status:t.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?S.INVALID:(l.status==="dirty"&&t.dirty(),o(l.value).then(()=>({status:t.value,value:l.value}))))}if(s.type==="transform")if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!(0,S.isValid)(o))return S.INVALID;let l=s.transform(o.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>(0,S.isValid)(o)?Promise.resolve(s.transform(o.value,i)).then(l=>({status:t.value,value:l})):S.INVALID);$.util.assertNever(s)}};_.ZodEffects=Ne;_.ZodTransformer=Ne;Ne.create=(n,e,t)=>new Ne({schema:n,typeName:G.ZodEffects,effect:e,...W(t)});Ne.createWithPreprocess=(n,e,t)=>new Ne({schema:e,effect:{type:"preprocess",transform:n},typeName:G.ZodEffects,...W(t)});var Ke=class extends J{_parse(e){return this._getType(e)===$.ZodParsedType.undefined?(0,S.OK)(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};_.ZodOptional=Ke;Ke.create=(n,e)=>new Ke({innerType:n,typeName:G.ZodOptional,...W(e)});var ht=class extends J{_parse(e){return this._getType(e)===$.ZodParsedType.null?(0,S.OK)(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};_.ZodNullable=ht;ht.create=(n,e)=>new ht({innerType:n,typeName:G.ZodNullable,...W(e)});var Fn=class extends J{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return t.parsedType===$.ZodParsedType.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};_.ZodDefault=Fn;Fn.create=(n,e)=>new Fn({innerType:n,typeName:G.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...W(e)});var Bn=class extends J{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return(0,S.isAsync)(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new E.ZodError(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new E.ZodError(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};_.ZodCatch=Bn;Bn.create=(n,e)=>new Bn({innerType:n,typeName:G.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...W(e)});var Or=class extends J{_parse(e){if(this._getType(e)!==$.ZodParsedType.nan){let r=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.invalid_type,expected:$.ZodParsedType.nan,received:r.parsedType}),S.INVALID}return{status:"valid",value:e.data}}};_.ZodNaN=Or;Or.create=n=>new Or({typeName:G.ZodNaN,...W(n)});_.BRAND=Symbol("zod_brand");var fs=class extends J{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}};_.ZodBranded=fs;var ps=class n extends J{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?S.INVALID:i.status==="dirty"?(t.dirty(),(0,S.DIRTY)(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?S.INVALID:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,t){return new n({in:e,out:t,typeName:G.ZodPipeline})}};_.ZodPipeline=ps;var Kn=class extends J{_parse(e){let t=this._def.innerType._parse(e),r=s=>((0,S.isValid)(s)&&(s.value=Object.freeze(s.value)),s);return(0,S.isAsync)(t)?t.then(s=>r(s)):r(t)}unwrap(){return this._def.innerType}};_.ZodReadonly=Kn;Kn.create=(n,e)=>new Kn({innerType:n,typeName:G.ZodReadonly,...W(e)});function eu(n,e){let t=typeof n=="function"?n(e):typeof n=="string"?{message:n}:n;return typeof t=="string"?{message:t}:t}function iu(n,e={},t){return n?Xt.create().superRefine((r,s)=>{let i=n(r);if(i instanceof Promise)return i.then(o=>{if(!o){let l=eu(e,r),u=l.fatal??t??!0;s.addIssue({code:"custom",...l,fatal:u})}});if(!i){let o=eu(e,r),l=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:l})}}):Xt.create()}_.late={object:Ae.lazycreate};var G;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(G||(_.ZodFirstPartyTypeKind=G={}));var sm=(n,e={message:`Input not instance of ${n.name}`})=>iu(t=>t instanceof n,e);_.instanceof=sm;var ou=Yt.create;_.string=ou;var au=An.create;_.number=au;var im=Or.create;_.nan=im;var om=$n.create;_.bigint=om;var lu=Pn.create;_.boolean=lu;var am=jn.create;_.date=am;var lm=Ar.create;_.symbol=lm;var um=On.create;_.undefined=um;var cm=Nn.create;_.null=cm;var dm=Xt.create;_.any=dm;var hm=Et.create;_.unknown=hm;var fm=Qe.create;_.never=fm;var pm=$r.create;_.void=pm;var mm=At.create;_.array=mm;var gm=Ae.create;_.object=gm;var ym=Ae.strictCreate;_.strictObject=ym;var vm=Mn.create;_.union=vm;var bm=si.create;_.discriminatedUnion=bm;var wm=zn.create;_.intersection=wm;var _m=dt.create;_.tuple=_m;var km=ii.create;_.record=km;var Sm=Pr.create;_.map=Sm;var Tm=jr.create;_.set=Tm;var xm=oi.create;_.function=xm;var Cm=Dn.create;_.lazy=Cm;var Im=Ln.create;_.literal=Im;var Rm=Un.create;_.enum=Rm;var Em=qn.create;_.nativeEnum=Em;var Am=Qt.create;_.promise=Am;var uu=Ne.create;_.effect=uu;_.transformer=uu;var $m=Ke.create;_.optional=$m;var Pm=ht.create;_.nullable=Pm;var jm=Ne.createWithPreprocess;_.preprocess=jm;var Om=ps.create;_.pipeline=Om;var Nm=()=>ou().optional();_.ostring=Nm;var Mm=()=>au().optional();_.onumber=Mm;var zm=()=>lu().optional();_.oboolean=zm;_.coerce={string:(n=>Yt.create({...n,coerce:!0})),number:(n=>An.create({...n,coerce:!0})),boolean:(n=>Pn.create({...n,coerce:!0})),bigint:(n=>$n.create({...n,coerce:!0})),date:(n=>jn.create({...n,coerce:!0}))};_.NEVER=S.INVALID});var jo=ne(Ge=>{"use strict";var Dm=Ge&&Ge.__createBinding||(Object.create?(function(n,e,t,r){r===void 0&&(r=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(n,r,s)}):(function(n,e,t,r){r===void 0&&(r=t),n[r]=e[t]})),Nr=Ge&&Ge.__exportStar||function(n,e){for(var t in n)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Dm(e,n,t)};Object.defineProperty(Ge,"__esModule",{value:!0});Nr(ti(),Ge);Nr(Ao(),Ge);Nr(Jl(),Ge);Nr(ds(),Ge);Nr(cu(),Ge);Nr(ei(),Ge)});var fu=ne($e=>{"use strict";var du=$e&&$e.__createBinding||(Object.create?(function(n,e,t,r){r===void 0&&(r=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(n,r,s)}):(function(n,e,t,r){r===void 0&&(r=t),n[r]=e[t]})),Lm=$e&&$e.__setModuleDefault||(Object.create?(function(n,e){Object.defineProperty(n,"default",{enumerable:!0,value:e})}):function(n,e){n.default=e}),Um=$e&&$e.__importStar||function(n){if(n&&n.__esModule)return n;var e={};if(n!=null)for(var t in n)t!=="default"&&Object.prototype.hasOwnProperty.call(n,t)&&du(e,n,t);return Lm(e,n),e},qm=$e&&$e.__exportStar||function(n,e){for(var t in n)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&du(e,n,t)};Object.defineProperty($e,"__esModule",{value:!0});$e.z=void 0;var hu=Um(jo());$e.z=hu;qm(jo(),$e);$e.default=hu});var we=ne(d=>{"use strict";Object.defineProperty(d,"__esModule",{value:!0});d.RepoDocReadMsg=d.RepoDocsResultMsg=d.RepoDocsMsg=d.ChatLoadResultMsg=d.ChatLoadMsg=d.ChatListResultMsg=d.ChatListMsg=d.ChatUsageMsg=d.ChatStreamMsg=d.JiraUsersResultMsg=d.DeployClaimResultMsg=d.DeployClaimMsg=d.RuleDiagnoseResultMsg=d.ProjectTestResultMsg=d.RunStatusMsg=d.FailedTest=d.RunUsageMsg=d.RunLogMsg=d.RunClaimMsg=d.HeartbeatMsg=d.HelloMsg=d.RuleConfig=d.ProjectConfig=d.ActionConfig=d.DeployAction=d.EnvironmentConfig=d.PromotionMode=d.DeployStep=d.RespondAction=d.ImplementAction=d.PlanOnlyAction=d.TriggerConfig=d.StatusChangedTrigger=d.CommentKeywordTrigger=d.LabelAddedTrigger=d.ActionType=d.TriggerType=d.ACTIVE_RUN_STATUSES=d.RunStatus=d.needsInputMarkerIn=d.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=d.NEEDS_INPUT_COMMENT_MARKER=d.NEEDS_INPUT_LABEL=d.NEEDS_INPUT_MARKER=d.BRANCH_DEPLOY_ISSUE_KEY=d.REQUIRED_AGENT_CAPABILITIES=d.DEFAULT_AGENT_ID=d.REGISTERED_AGENTS=d.PROTOCOL_VERSION=d.GITHUB_TOKEN_PERMISSIONS=void 0;d.RunnerUpdateMsg=d.RepoDocSaveResultMsg=d.RepoDocSaveMsg=d.SetupClaudeMdSaveResultMsg=d.SetupClaudeMdSaveMsg=d.SetupClaudeMdGenerateResultMsg=d.SetupClaudeMdGenerateMsg=d.SetupStatusResultMsg=d.SetupStatusMsg=d.DeploySuggestResultMsg=d.EnvPreflightResultMsg=d.EnvPreflightMsg=d.ChatCreateTicketResultMsg=d.ChatCreateTicketMsg=d.ChatTurnResultMsg=d.ChatTurnMsg=d.ChatFile=d.TeamCredsResultMsg=d.TeamCredsMsg=d.KnowledgeSaveResultMsg=d.KnowledgeSaveMsg=d.KnowledgeListResultMsg=d.KnowledgeFile=d.KnowledgeListMsg=d.AuditReviewResultMsg=d.AuditReviewMsg=d.AuditGetResultMsg=d.AuditGetMsg=d.AuditListResultMsg=d.AuditStatsResultMsg=d.AuditStatsMsg=d.AuditListMsg=d.AuditStartResultMsg=d.AuditStartMsg=d.AuditRecord=d.AuditFinding=d.AuditScope=d.AuditSeverity=d.KnowledgeRole=d.AuditRole=d.EpicSuggestResultMsg=d.EpicSuggestMsg=d.EpicListResultMsg=d.EpicChild=d.EpicListMsg=d.BoardTriggerResultMsg=d.BoardTriggerMsg=d.BoardFetchResultMsg=d.BoardFetchMsg=d.RepoDocReadResultMsg=void 0;d.DEFAULT_DEPLOY_SUGGEST_PROMPT_TEMPLATE=d.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE=d.DEPLOY_FIX_PROMPT_TEMPLATE=d.PROMPT_PRESETS=d.DEFAULT_RESPOND_PROMPT_TEMPLATE=d.BUGFIX_IMPLEMENT_PROMPT_TEMPLATE=d.BUG_INVESTIGATION_PROMPT_TEMPLATE=d.TECHNICAL_PLAN_PROMPT_TEMPLATE=d.MEMORY_UPDATE_PROMPT=d.DEFAULT_IMPLEMENT_PROMPT_TEMPLATE=d.WRITE_TESTS_PROMPT=d.DEFAULT_PLAN_PROMPT_TEMPLATE=d.EnrollResponse=d.EnrollRequest=d.ServerToRunnerMsg=d.JiraUsersMsg=d.DeploySuggestMsg=d.DeployFixMsg=d.DeployStartMsg=d.RunRetryPushMsg=d.RunRejectedMsg=d.RunApprovedMsg=d.RunCancelMsg=d.RuleDiagnoseMsg=d.ProjectTestMsg=d.RunClaimResultMsg=d.ConfigMsg=d.HelloAckMsg=d.RunnerToServerMsg=d.AutopilotReportMsg=d.AutopilotNextResultMsg=d.AutopilotNextMsg=d.RunnerUpdateResultMsg=d.AgentProfilesResultMsg=d.AgentProfilesMsg=d.RunPrConflictMsg=d.RunResolveConflictResultMsg=d.RunTestFixResultMsg=d.RunTestFixMsg=d.RunResolveConflictMsg=void 0;d.missingAgentCapabilities=Fm;d.parseRunnerMsg=Km;d.parseServerMsg=Zm;var a=fu();d.GITHUB_TOKEN_PERMISSIONS={where:"github.com/settings/personal-access-tokens/new (fine-grained token)",steps:["Resource owner: the org or user that OWNS the repo - not your personal account, unless the repo is under it","Repository access: Only select repositories -> pick this repo","Contents: Read and write - pushing the agent's branch","Pull requests: Read and write - opening the PR, and merging it when you approve","Metadata: Read-only - GitHub adds this itself and will not let you remove it","Workflows: Read and write - ONLY if changes may touch .github/workflows; without it GitHub rejects those pushes"],note:"A fine-grained token covers exactly ONE resource owner, so a repo in a different org always needs its own token. A classic token with the `repo` scope also works and is simpler, but it reaches every repository you can see - prefer fine-grained."};d.PROTOCOL_VERSION="1.42";d.REGISTERED_AGENTS=[{id:"claude-code",displayName:"Claude Code",capabilities:{readOnlyJail:!0,editNoShellJail:!0,sessionResume:!0,costReporting:!0,modelSelection:!0,loginProfiles:!0},suggestedModels:["claude-fable-5","claude-opus-5","claude-sonnet-5","claude-haiku-4-5-20251001"],experimental:!1},{id:"codex",displayName:"OpenAI Codex CLI (experimental)",capabilities:{readOnlyJail:!0,editNoShellJail:!1,sessionResume:!1,costReporting:!1,modelSelection:!0,loginProfiles:!1},suggestedModels:[],experimental:!0}];d.DEFAULT_AGENT_ID="claude-code";d.REQUIRED_AGENT_CAPABILITIES={plan_only:["readOnlyJail","sessionResume"],respond:["readOnlyJail"],implement:["editNoShellJail","sessionResume"],deploy:[],chat:["readOnlyJail","sessionResume"],assist:["readOnlyJail"]};function Fm(n,e){let t=d.REGISTERED_AGENTS.find(r=>r.id===n);return t?(d.REQUIRED_AGENT_CAPABILITIES[e]??[]).filter(r=>!t.capabilities[r]):null}d.BRANCH_DEPLOY_ISSUE_KEY="(branch deploy)";d.NEEDS_INPUT_MARKER="NEEDS-INPUT";d.NEEDS_INPUT_LABEL="agent-needs-input";d.NEEDS_INPUT_COMMENT_MARKER="Allwright needs your input";d.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=["TicketPilot needs your input"];var Bm=n=>n.includes(d.NEEDS_INPUT_COMMENT_MARKER)||d.LEGACY_NEEDS_INPUT_COMMENT_MARKERS.some(e=>n.includes(e));d.needsInputMarkerIn=Bm;d.RunStatus=a.z.enum(["queued","running","posting","awaiting_approval","needs_input","succeeded","failed","timed_out"]);d.ACTIVE_RUN_STATUSES=["queued","running","posting","awaiting_approval"];d.TriggerType=a.z.enum(["label_added","comment_keyword","status_changed"]);d.ActionType=a.z.enum(["plan_only","implement","respond","deploy"]);d.LabelAddedTrigger=a.z.object({type:a.z.literal("label_added"),label:a.z.string().min(1),doneLabel:a.z.string().min(1).default("agent-planned"),failedLabel:a.z.string().min(1).default("agent-failed")});d.CommentKeywordTrigger=a.z.object({type:a.z.literal("comment_keyword"),keyword:a.z.string().min(1),doneLabel:a.z.string().min(1).default("agent-implemented"),failedLabel:a.z.string().min(1).default("agent-failed")});d.StatusChangedTrigger=a.z.object({type:a.z.literal("status_changed"),status:a.z.string().min(1),doneLabel:a.z.string().min(1).default("agent-deployed"),failedLabel:a.z.string().min(1).default("agent-failed")});d.TriggerConfig=a.z.discriminatedUnion("type",[d.LabelAddedTrigger,d.CommentKeywordTrigger,d.StatusChangedTrigger]);d.PlanOnlyAction=a.z.object({type:a.z.literal("plan_only"),promptTemplate:a.z.string().min(1),timeoutSeconds:a.z.number().int().positive().max(3600).default(900),agent:a.z.string().default(d.DEFAULT_AGENT_ID),model:a.z.string().default("")});d.ImplementAction=a.z.object({type:a.z.literal("implement"),promptTemplate:a.z.string().min(1),timeoutSeconds:a.z.number().int().positive().max(7200).default(1800),maxTurns:a.z.number().int().positive().max(500).default(120),requireApproval:a.z.boolean().default(!0),branchTemplate:a.z.string().min(1).default("agent/{{issueKey}}").refine(n=>n.includes("{{issueKey}}"),{message:"branchTemplate must contain {{issueKey}}"}),baseBranch:a.z.string().min(1).default("main"),jiraTransition:a.z.string().optional(),jiraTransitionOnStart:a.z.string().optional(),jiraTransitionOnMerge:a.z.string().optional(),agent:a.z.string().default(d.DEFAULT_AGENT_ID),model:a.z.string().default(""),updateMemory:a.z.boolean().default(!1),writeTests:a.z.boolean().default(!0),runTests:a.z.boolean().default(!0),mergeOnApprove:a.z.boolean().default(!0),mergeMethod:a.z.enum(["squash","merge","rebase"]).default("squash"),autoMerge:a.z.boolean().default(!0)});d.RespondAction=a.z.object({type:a.z.literal("respond"),promptTemplate:a.z.string().min(1),timeoutSeconds:a.z.number().int().positive().max(3600).default(600),agent:a.z.string().default(d.DEFAULT_AGENT_ID),model:a.z.string().default("")});d.DeployStep=a.z.object({name:a.z.string().min(1).max(120),run:a.z.string().min(1).max(4e3),continueOnError:a.z.boolean().default(!1)});d.PromotionMode=a.z.enum(["deploy_only","merge_and_deploy"]);d.EnvironmentConfig=a.z.object({id:a.z.string(),projectId:a.z.string(),name:a.z.string(),rank:a.z.number().int().nonnegative(),auditBeforeDeploy:a.z.enum(["","security","testing"]).default(""),branch:a.z.string().default(""),publicUrl:a.z.string().default(""),useDedicatedCheckout:a.z.boolean().default(!1),promotionMode:d.PromotionMode.default("deploy_only"),ticketBranchTemplate:a.z.string().default("agent/{{issueKey}}"),steps:a.z.array(d.DeployStep).default([]),workdir:a.z.string().default(""),timeoutSeconds:a.z.number().int().positive().max(21600).default(1800),requiredSecrets:a.z.array(a.z.string()).default([]),requireApproval:a.z.boolean().default(!1),requireSyncCheck:a.z.boolean().default(!1),previousEnvBranch:a.z.string().optional(),deployFromColumn:a.z.string().default(""),deployToColumn:a.z.string().default("")});d.DeployAction=a.z.object({type:a.z.literal("deploy"),envSelection:a.z.enum(["fixed","from_comment"]).default("from_comment"),environmentId:a.z.string().optional(),requireStatus:a.z.string().optional()});d.ActionConfig=a.z.discriminatedUnion("type",[d.PlanOnlyAction,d.ImplementAction,d.RespondAction,d.DeployAction]);d.ProjectConfig=a.z.object({id:a.z.string(),name:a.z.string(),jiraProjectKey:a.z.string(),repoName:a.z.string(),jiraSiteUrl:a.z.string().default(""),defaultAgent:a.z.string().default("claude-code"),componentRoutes:a.z.array(a.z.object({component:a.z.string().min(1),repoName:a.z.string().min(1)})).default([])});d.RuleConfig=a.z.object({id:a.z.string(),projectId:a.z.string(),name:a.z.string(),enabled:a.z.boolean(),trigger:d.TriggerConfig,action:d.ActionConfig});d.HelloMsg=a.z.object({type:a.z.literal("hello"),protocolVersion:a.z.string(),runnerVersion:a.z.string(),platform:a.z.string(),justBooted:a.z.boolean().optional()});d.HeartbeatMsg=a.z.object({type:a.z.literal("heartbeat"),ts:a.z.string()});d.RunClaimMsg=a.z.object({type:a.z.literal("run.claim"),requestId:a.z.string(),ruleId:a.z.string(),issueKey:a.z.string(),issueSummary:a.z.string().default(""),triggerFingerprint:a.z.string(),dedupKey:a.z.string().optional(),triggeredByAccountId:a.z.string().optional()});d.RunLogMsg=a.z.object({type:a.z.literal("run.log"),runId:a.z.string(),seq:a.z.number().int().nonnegative(),ts:a.z.string(),level:a.z.enum(["info","warn","error","agent"]),message:a.z.string().max(16384)});d.RunUsageMsg=a.z.object({type:a.z.literal("run.usage"),runId:a.z.string(),inputTokens:a.z.number().int().nonnegative(),outputTokens:a.z.number().int().nonnegative(),cacheReadTokens:a.z.number().int().nonnegative().optional(),costUsd:a.z.number().nonnegative().optional(),turns:a.z.number().int().nonnegative().optional()});d.FailedTest=a.z.object({command:a.z.string().max(500),exitCode:a.z.number().int(),tail:a.z.string().max(4e3)});d.RunStatusMsg=a.z.object({type:a.z.literal("run.status"),runId:a.z.string(),status:d.RunStatus,error:a.z.string().optional(),errorKind:a.z.enum(["guard"]).optional(),costUsd:a.z.number().nonnegative().optional(),inputTokens:a.z.number().int().nonnegative().optional(),outputTokens:a.z.number().int().nonnegative().optional(),resultSummary:a.z.string().max(2e3).optional(),billingMode:a.z.enum(["subscription","api","unknown"]).optional(),model:a.z.string().max(200).optional(),prUrl:a.z.string().optional(),headSha:a.z.string().optional(),deployedRef:a.z.string().optional(),retryAvailable:a.z.boolean().optional(),failedTests:a.z.array(d.FailedTest).max(20).optional()});d.ProjectTestResultMsg=a.z.object({type:a.z.literal("project.test.result"),requestId:a.z.string(),ok:a.z.boolean(),checks:a.z.array(a.z.object({name:a.z.string(),ok:a.z.boolean(),detail:a.z.string(),kind:a.z.enum(["connection","content"]).default("connection"),fix:a.z.array(a.z.string()).default([]),fixNote:a.z.string().default("")}))});d.RuleDiagnoseResultMsg=a.z.object({type:a.z.literal("rule.diagnose.result"),requestId:a.z.string(),checks:a.z.array(a.z.object({name:a.z.string(),ok:a.z.boolean(),detail:a.z.string(),kind:a.z.enum(["connection","content"]).default("connection"),fix:a.z.array(a.z.string()).default([]),fixNote:a.z.string().default("")})),matchedCount:a.z.number().int().nonnegative(),excludedCount:a.z.number().int().nonnegative(),excludedSample:a.z.array(a.z.string()).max(5)});d.DeployClaimMsg=a.z.object({type:a.z.literal("deploy.claim"),requestId:a.z.string(),projectId:a.z.string(),ruleId:a.z.string(),issueKey:a.z.string(),issueSummary:a.z.string().default(""),environmentName:a.z.string(),requestedByAccountId:a.z.string().optional(),requestedByDisplayName:a.z.string().default(""),dedupKey:a.z.string(),triggerFingerprint:a.z.string()});d.DeployClaimResultMsg=a.z.object({type:a.z.literal("deploy.claim.result"),requestId:a.z.string(),accepted:a.z.boolean(),runId:a.z.string().optional(),environment:d.EnvironmentConfig.optional(),reason:a.z.string().optional(),code:a.z.enum(["ok","duplicate","unknown_environment","not_permitted","unlinked_jira_account","promotion_order","jira_disabled","rule_disabled","cap"]).optional()});d.JiraUsersResultMsg=a.z.object({type:a.z.literal("jira.users.result"),requestId:a.z.string(),ok:a.z.boolean(),users:a.z.array(a.z.object({accountId:a.z.string(),displayName:a.z.string(),email:a.z.string().default(""),active:a.z.boolean().default(!0)})).default([]),error:a.z.string().optional()});d.ChatStreamMsg=a.z.object({type:a.z.literal("chat.stream"),requestId:a.z.string(),seq:a.z.number().int().nonnegative(),text:a.z.string().max(8e3)});d.ChatUsageMsg=a.z.object({type:a.z.literal("chat.usage"),requestId:a.z.string(),inputTokens:a.z.number().int().nonnegative(),outputTokens:a.z.number().int().nonnegative(),cacheReadTokens:a.z.number().int().nonnegative().optional(),turns:a.z.number().int().nonnegative().optional()});d.ChatListMsg=a.z.object({type:a.z.literal("chat.list"),requestId:a.z.string(),projectId:a.z.string()});d.ChatListResultMsg=a.z.object({type:a.z.literal("chat.list.result"),requestId:a.z.string(),sessions:a.z.array(a.z.object({sessionId:a.z.string(),title:a.z.string().default(""),updatedAt:a.z.string().default(""),messageCount:a.z.number().int().nonnegative().default(0)})).default([])});d.ChatLoadMsg=a.z.object({type:a.z.literal("chat.load"),requestId:a.z.string(),sessionId:a.z.string()});d.ChatLoadResultMsg=a.z.object({type:a.z.literal("chat.load.result"),requestId:a.z.string(),ok:a.z.boolean(),projectId:a.z.string().default(""),messages:a.z.array(a.z.object({role:a.z.enum(["user","agent"]),text:a.z.string()})).default([]),error:a.z.string().optional()});d.RepoDocsMsg=a.z.object({type:a.z.literal("repo.docs"),requestId:a.z.string(),projectId:a.z.string()});d.RepoDocsResultMsg=a.z.object({type:a.z.literal("repo.docs.result"),requestId:a.z.string(),ok:a.z.boolean(),docs:a.z.array(a.z.object({path:a.z.string(),sizeBytes:a.z.number().int().nonnegative().default(0),updatedAt:a.z.string().default("")})).default([]),error:a.z.string().optional()});d.RepoDocReadMsg=a.z.object({type:a.z.literal("repo.doc.read"),requestId:a.z.string(),projectId:a.z.string(),path:a.z.string().max(400)});d.RepoDocReadResultMsg=a.z.object({type:a.z.literal("repo.doc.read.result"),requestId:a.z.string(),ok:a.z.boolean(),path:a.z.string().default(""),content:a.z.string().default(""),truncated:a.z.boolean().default(!1),error:a.z.string().optional()});d.BoardFetchMsg=a.z.object({type:a.z.literal("board.fetch"),requestId:a.z.string(),projectId:a.z.string()});d.BoardFetchResultMsg=a.z.object({type:a.z.literal("board.fetch.result"),requestId:a.z.string(),ok:a.z.boolean(),browseBaseUrl:a.z.string().default(""),columns:a.z.array(a.z.object({name:a.z.string(),issues:a.z.array(a.z.object({key:a.z.string(),summary:a.z.string(),labels:a.z.array(a.z.string()).default([])})).default([])})).default([]),error:a.z.string().optional()});d.BoardTriggerMsg=a.z.object({type:a.z.literal("board.trigger"),requestId:a.z.string(),projectId:a.z.string(),issueKey:a.z.string(),comment:a.z.string().max(2e3).default(""),removeLabel:a.z.string().default(""),requestedBy:a.z.string().default(""),requestedByEmail:a.z.string().default(""),reimplement:a.z.boolean().default(!1)});d.BoardTriggerResultMsg=a.z.object({type:a.z.literal("board.trigger.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional()});d.EpicListMsg=a.z.object({type:a.z.literal("epic.list"),requestId:a.z.string(),projectId:a.z.string(),epicKey:a.z.string().default("")});d.EpicChild=a.z.object({key:a.z.string(),summary:a.z.string(),status:a.z.string(),statusCategory:a.z.string(),labels:a.z.array(a.z.string()).default([])});d.EpicListResultMsg=a.z.object({type:a.z.literal("epic.list.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),epics:a.z.array(a.z.object({key:a.z.string(),summary:a.z.string(),status:a.z.string()})).default([]),children:a.z.array(d.EpicChild).default([])});d.EpicSuggestMsg=a.z.object({type:a.z.literal("epic.suggest"),requestId:a.z.string(),projectId:a.z.string(),epicKey:a.z.string().min(1),model:a.z.string().default("")});d.EpicSuggestResultMsg=a.z.object({type:a.z.literal("epic.suggest.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),issueKey:a.z.string().default(""),reason:a.z.string().default(""),considered:a.z.number().int().default(0)});d.AuditRole=a.z.enum(["security","testing","architecture"]);d.KnowledgeRole=a.z.enum(["security","testing","architecture","implement"]);d.AuditSeverity=a.z.enum(["critical","high","medium","low","info"]);d.AuditScope=a.z.object({kind:a.z.enum(["repo","ticket","branch"]).default("repo"),ref:a.z.string().default("")});d.AuditFinding=a.z.object({id:a.z.string().min(1),title:a.z.string().min(1),ruleId:a.z.string().max(20).default(""),severity:d.AuditSeverity,area:a.z.string().default(""),evidence:a.z.array(a.z.object({file:a.z.string().min(1),line:a.z.number().int().positive().optional(),note:a.z.string().default("")})).min(1),fix:a.z.string().default("")});d.AuditRecord=a.z.object({id:a.z.string(),role:d.AuditRole,createdAt:a.z.string(),model:a.z.string().default(""),summary:a.z.string().default(""),packNames:a.z.array(a.z.string()).default([]),findings:a.z.array(d.AuditFinding).default([]),costUsd:a.z.number().default(0),review:a.z.object({selected:a.z.array(a.z.string()),updatedAt:a.z.string()}).optional(),verdicts:a.z.record(a.z.object({verdict:a.z.enum(["valid","false-positive","wont-fix"]),note:a.z.string().default(""),by:a.z.string().default(""),at:a.z.string().default("")})).default({}),lessonsWritten:a.z.array(a.z.string()).default([]),ticketed:a.z.record(a.z.string()).default({}),scope:d.AuditScope.default({kind:"repo",ref:""}),testRun:a.z.array(a.z.object({command:a.z.string(),exitCode:a.z.number().int(),durationMs:a.z.number().int().default(0),tail:a.z.string().default("")})).optional()});d.AuditStartMsg=a.z.object({type:a.z.literal("audit.start"),requestId:a.z.string(),projectId:a.z.string(),role:d.AuditRole,model:a.z.string().default(""),scope:d.AuditScope.default({kind:"repo",ref:""})});d.AuditStartResultMsg=a.z.object({type:a.z.literal("audit.start.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),audit:d.AuditRecord.optional()});d.AuditListMsg=a.z.object({type:a.z.literal("audit.list"),requestId:a.z.string(),projectId:a.z.string()});d.AuditStatsMsg=a.z.object({type:a.z.literal("audit.stats"),requestId:a.z.string(),projectIds:a.z.array(a.z.string()).max(200).default([]),since:a.z.string().default("")});d.AuditStatsResultMsg=a.z.object({type:a.z.literal("audit.stats.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),byProject:a.z.record(a.z.object({audits:a.z.number().int().default(0),findings:a.z.number().int().default(0),valid:a.z.number().int().default(0),falsePositive:a.z.number().int().default(0),wontFix:a.z.number().int().default(0),unreviewed:a.z.number().int().default(0)})).default({})});d.AuditListResultMsg=a.z.object({type:a.z.literal("audit.list.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),audits:a.z.array(a.z.object({id:a.z.string(),role:d.AuditRole,createdAt:a.z.string(),findingCount:a.z.number().int(),bySeverity:a.z.record(a.z.number().int()).default({})})).default([])});d.AuditGetMsg=a.z.object({type:a.z.literal("audit.get"),requestId:a.z.string(),projectId:a.z.string(),auditId:a.z.string()});d.AuditGetResultMsg=a.z.object({type:a.z.literal("audit.get.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),audit:d.AuditRecord.optional()});d.AuditReviewMsg=a.z.object({type:a.z.literal("audit.review"),requestId:a.z.string(),projectId:a.z.string(),auditId:a.z.string(),selected:a.z.array(a.z.string()).optional(),ticketed:a.z.array(a.z.object({findingId:a.z.string(),issueKey:a.z.string()})).default([]),verdicts:a.z.array(a.z.object({findingId:a.z.string(),verdict:a.z.enum(["valid","false-positive","wont-fix"]),note:a.z.string().max(2e3).default("")})).default([]),verdictBy:a.z.string().default("")});d.AuditReviewResultMsg=a.z.object({type:a.z.literal("audit.review.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),audit:d.AuditRecord.optional()});d.KnowledgeListMsg=a.z.object({type:a.z.literal("knowledge.list"),requestId:a.z.string(),projectId:a.z.string()});d.KnowledgeFile=a.z.object({role:d.KnowledgeRole,level:a.z.enum(["global","org","project"]),source:a.z.enum(["pack","lessons"]),name:a.z.string(),content:a.z.string(),editable:a.z.boolean().default(!1)});d.KnowledgeListResultMsg=a.z.object({type:a.z.literal("knowledge.list.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),files:a.z.array(d.KnowledgeFile).default([])});d.KnowledgeSaveMsg=a.z.object({type:a.z.literal("knowledge.save"),requestId:a.z.string(),projectId:a.z.string(),role:d.KnowledgeRole,level:a.z.enum(["org","project"]),source:a.z.enum(["pack","lessons"]),name:a.z.string().min(1).max(100),content:a.z.string().max(6e4),append:a.z.boolean().default(!1),by:a.z.string().default("")});d.KnowledgeSaveResultMsg=a.z.object({type:a.z.literal("knowledge.save.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional()});d.TeamCredsMsg=a.z.object({type:a.z.literal("team.creds"),requestId:a.z.string(),emails:a.z.array(a.z.string()).max(200)});d.TeamCredsResultMsg=a.z.object({type:a.z.literal("team.creds.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),githubShared:a.z.boolean().default(!1),sharedGithubLogin:a.z.string().default(""),entries:a.z.array(a.z.object({email:a.z.string(),jira:a.z.enum(["own","runner-account","missing"]),jiraAs:a.z.string().default(""),github:a.z.enum(["own","shared","missing"]),githubAs:a.z.string().default("")})).default([])});d.ChatFile=a.z.object({name:a.z.string().min(1).max(255),contentBase64:a.z.string().min(1).max(6e6)});d.ChatTurnMsg=a.z.object({type:a.z.literal("chat.turn"),requestId:a.z.string(),projectId:a.z.string(),sessionId:a.z.string().optional(),message:a.z.string().min(1).max(2e4),userName:a.z.string().default(""),model:a.z.string().default(""),files:a.z.array(d.ChatFile).max(8).default([])});d.ChatTurnResultMsg=a.z.object({type:a.z.literal("chat.turn.result"),requestId:a.z.string(),ok:a.z.boolean(),sessionId:a.z.string().default(""),reply:a.z.string().default(""),error:a.z.string().optional(),inputTokens:a.z.number().int().nonnegative().default(0),outputTokens:a.z.number().int().nonnegative().default(0),cacheReadTokens:a.z.number().int().nonnegative().default(0),costUsd:a.z.number().nonnegative().default(0),model:a.z.string().max(200).default("")});d.ChatCreateTicketMsg=a.z.object({type:a.z.literal("chat.create.ticket"),requestId:a.z.string(),projectId:a.z.string(),summary:a.z.string().min(1).max(250),description:a.z.string().default(""),triggerComment:a.z.string().default(""),requestedBy:a.z.string().default(""),requestedByEmail:a.z.string().default(""),asEpic:a.z.boolean().default(!1),children:a.z.array(a.z.object({summary:a.z.string().min(1),description:a.z.string().default("")})).max(20).default([]),files:a.z.array(d.ChatFile).max(8).default([])});d.ChatCreateTicketResultMsg=a.z.object({type:a.z.literal("chat.create.ticket.result"),requestId:a.z.string(),ok:a.z.boolean(),issueKey:a.z.string().default(""),error:a.z.string().optional(),childKeys:a.z.array(a.z.string()).default([])});d.EnvPreflightMsg=a.z.object({type:a.z.literal("env.preflight"),requestId:a.z.string(),projectId:a.z.string(),environmentName:a.z.string().default(""),steps:a.z.array(d.DeployStep).default([]),requiredSecrets:a.z.array(a.z.string()).default([]),workdir:a.z.string().default(""),branch:a.z.string().default(""),publicUrl:a.z.string().default("")});d.EnvPreflightResultMsg=a.z.object({type:a.z.literal("env.preflight.result"),requestId:a.z.string(),ok:a.z.boolean(),checks:a.z.array(a.z.object({name:a.z.string(),ok:a.z.boolean(),detail:a.z.string().default(""),kind:a.z.enum(["connection","content"]).default("connection"),fix:a.z.array(a.z.string()).default([]),fixNote:a.z.string().default("")})).default([])});d.DeploySuggestResultMsg=a.z.object({type:a.z.literal("deploy.suggest.result"),requestId:a.z.string(),ok:a.z.boolean(),steps:a.z.array(d.DeployStep).default([]),requiredSecrets:a.z.array(a.z.string()).default([]),notes:a.z.string().default(""),error:a.z.string().optional(),docPath:a.z.string().default(""),docContent:a.z.string().max(1e5).default("")});d.SetupStatusMsg=a.z.object({type:a.z.literal("setup.status"),requestId:a.z.string(),repoNames:a.z.array(a.z.string()).max(100).default([])});d.SetupStatusResultMsg=a.z.object({type:a.z.literal("setup.status.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),jiraConfigured:a.z.boolean().default(!1),jiraEmail:a.z.string().default(""),claude:a.z.object({installed:a.z.boolean(),version:a.z.string().default(""),loggedIn:a.z.boolean()}).optional(),githubTokenSet:a.z.boolean().default(!1),githubLogin:a.z.string().default(""),deploysEnabled:a.z.boolean().default(!1),jiraUserCount:a.z.number().int().default(0),repos:a.z.array(a.z.object({repoName:a.z.string(),mapped:a.z.boolean(),pathExists:a.z.boolean().default(!1),isGit:a.z.boolean().default(!1),claudeMd:a.z.boolean().default(!1),deployMd:a.z.boolean().default(!1),testMd:a.z.boolean().default(!1),defaultBranch:a.z.string().default(""),githubToken:a.z.boolean().default(!1),githubTokenOwn:a.z.boolean().default(!1)})).default([])});d.SetupClaudeMdGenerateMsg=a.z.object({type:a.z.literal("setup.claudemd.generate"),requestId:a.z.string(),projectId:a.z.string(),kind:a.z.enum(["claude","deploy","design"]).default("claude"),streamId:a.z.string().default("")});d.SetupClaudeMdGenerateResultMsg=a.z.object({type:a.z.literal("setup.claudemd.generate.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),content:a.z.string().default("")});d.SetupClaudeMdSaveMsg=a.z.object({type:a.z.literal("setup.claudemd.save"),requestId:a.z.string(),projectId:a.z.string(),kind:a.z.enum(["claude","deploy","design"]).default("claude"),overwrite:a.z.boolean().default(!1),content:a.z.string().max(1e5)});d.SetupClaudeMdSaveResultMsg=a.z.object({type:a.z.literal("setup.claudemd.save.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),note:a.z.string().default("")});d.RepoDocSaveMsg=a.z.object({type:a.z.literal("repo.doc.save"),requestId:a.z.string(),projectId:a.z.string(),relPath:a.z.string().min(1).max(200),overwrite:a.z.boolean().default(!1),content:a.z.string().max(2e5)});d.RepoDocSaveResultMsg=a.z.object({type:a.z.literal("repo.doc.save.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),note:a.z.string().default("")});d.RunnerUpdateMsg=a.z.object({type:a.z.literal("runner.update"),requestId:a.z.string()});d.RunResolveConflictMsg=a.z.object({type:a.z.literal("run.resolve.conflict"),requestId:a.z.string(),runId:a.z.string()});d.RunTestFixMsg=a.z.object({type:a.z.literal("run.testfix"),requestId:a.z.string(),runId:a.z.string(),failedTests:a.z.array(d.FailedTest).min(1).max(20)});d.RunTestFixResultMsg=a.z.object({type:a.z.literal("run.testfix.result"),requestId:a.z.string(),ok:a.z.boolean(),note:a.z.string().default(""),headSha:a.z.string().default(""),remaining:a.z.array(d.FailedTest).default([]),costUsd:a.z.number().nonnegative().optional(),inputTokens:a.z.number().int().nonnegative().optional(),outputTokens:a.z.number().int().nonnegative().optional()});d.RunResolveConflictResultMsg=a.z.object({type:a.z.literal("run.resolve.conflict.result"),requestId:a.z.string(),ok:a.z.boolean(),note:a.z.string().default(""),freeOfCharge:a.z.boolean().default(!1),headSha:a.z.string().default(""),costUsd:a.z.number().nonnegative().optional(),inputTokens:a.z.number().int().nonnegative().optional(),outputTokens:a.z.number().int().nonnegative().optional()});d.RunPrConflictMsg=a.z.object({type:a.z.literal("run.pr.conflict"),runId:a.z.string(),conflicted:a.z.boolean()});d.AgentProfilesMsg=a.z.object({type:a.z.literal("agent.profiles"),requestId:a.z.string()});d.AgentProfilesResultMsg=a.z.object({type:a.z.literal("agent.profiles.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),profiles:a.z.array(a.z.object({agent:a.z.string(),name:a.z.string(),loggedIn:a.z.boolean()})).max(200).default([]),defaultLoggedIn:a.z.boolean().default(!1),agentsWithoutProfiles:a.z.array(a.z.string()).max(20).default([])});d.RunnerUpdateResultMsg=a.z.object({type:a.z.literal("runner.update.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),note:a.z.string().default(""),scheduled:a.z.boolean().default(!1)});d.AutopilotNextMsg=a.z.object({type:a.z.literal("autopilot.next"),requestId:a.z.string()});d.AutopilotNextResultMsg=a.z.object({type:a.z.literal("autopilot.next.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),item:a.z.object({id:a.z.string(),projectId:a.z.string(),issueKey:a.z.string(),ruleId:a.z.string(),baseOverride:a.z.string().default(""),branchOverride:a.z.string().default(""),continueBranch:a.z.boolean().default(!1),autoMerge:a.z.boolean().default(!1)}).nullable().default(null),pausedUntil:a.z.string().default("")});d.AutopilotReportMsg=a.z.object({type:a.z.literal("autopilot.report"),requestId:a.z.string(),itemId:a.z.string(),outcome:a.z.enum(["claimed","failed","paused"]),runId:a.z.string().default(""),error:a.z.string().default("")});d.RunnerToServerMsg=a.z.discriminatedUnion("type",[d.HelloMsg,d.HeartbeatMsg,d.RunClaimMsg,d.RunLogMsg,d.RunUsageMsg,d.RunStatusMsg,d.ProjectTestResultMsg,d.RuleDiagnoseResultMsg,d.DeployClaimMsg,d.DeploySuggestResultMsg,d.EnvPreflightResultMsg,d.ChatTurnResultMsg,d.ChatStreamMsg,d.ChatUsageMsg,d.ChatCreateTicketResultMsg,d.ChatListResultMsg,d.RepoDocsResultMsg,d.RepoDocReadResultMsg,d.ChatLoadResultMsg,d.BoardFetchResultMsg,d.BoardTriggerResultMsg,d.TeamCredsResultMsg,d.AuditStartResultMsg,d.AuditListResultMsg,d.AuditGetResultMsg,d.AuditReviewResultMsg,d.KnowledgeListResultMsg,d.KnowledgeSaveResultMsg,d.EpicListResultMsg,d.EpicSuggestResultMsg,d.JiraUsersResultMsg,d.SetupStatusResultMsg,d.SetupClaudeMdGenerateResultMsg,d.SetupClaudeMdSaveResultMsg,d.RepoDocSaveResultMsg,d.RunnerUpdateResultMsg,d.AgentProfilesResultMsg,d.RunPrConflictMsg,d.RunResolveConflictResultMsg,d.RunTestFixResultMsg,d.AuditStatsResultMsg,d.AutopilotNextMsg,d.AutopilotReportMsg]);d.HelloAckMsg=a.z.object({type:a.z.literal("hello.ack"),runnerId:a.z.string(),runnerName:a.z.string(),serverTime:a.z.string()});d.ConfigMsg=a.z.object({type:a.z.literal("config"),projects:a.z.array(d.ProjectConfig),rules:a.z.array(d.RuleConfig),environments:a.z.array(d.EnvironmentConfig).default([]),pollingPaused:a.z.boolean().default(!1)});d.RunClaimResultMsg=a.z.object({type:a.z.literal("run.claim.result"),requestId:a.z.string(),accepted:a.z.boolean(),runId:a.z.string().optional(),reason:a.z.string().optional(),claudeProfile:a.z.string().optional(),actorEmail:a.z.string().optional()});d.ProjectTestMsg=a.z.object({type:a.z.literal("project.test"),requestId:a.z.string(),projectId:a.z.string()});d.RuleDiagnoseMsg=a.z.object({type:a.z.literal("rule.diagnose"),requestId:a.z.string(),ruleId:a.z.string()});d.RunCancelMsg=a.z.object({type:a.z.literal("run.cancel"),runId:a.z.string()});d.RunApprovedMsg=a.z.object({type:a.z.literal("run.approved"),runId:a.z.string(),headSha:a.z.string().optional()});d.RunRejectedMsg=a.z.object({type:a.z.literal("run.rejected"),runId:a.z.string()});d.RunRetryPushMsg=a.z.object({type:a.z.literal("run.retryPush"),runId:a.z.string()});d.DeployStartMsg=a.z.object({type:a.z.literal("deploy.start"),runId:a.z.string(),projectId:a.z.string(),issueKey:a.z.string(),issueSummary:a.z.string().default(""),environment:d.EnvironmentConfig,requestedBy:a.z.string().default(""),attempt:a.z.number().int().positive().default(1)});d.DeployFixMsg=a.z.object({type:a.z.literal("deploy.fix"),requestId:a.z.string(),projectId:a.z.string(),environmentName:a.z.string(),steps:a.z.array(a.z.object({name:a.z.string(),run:a.z.string(),continueOnError:a.z.boolean().default(!1)})),failedStep:a.z.string().default(""),errorText:a.z.string().max(8e3).default("")});d.DeploySuggestMsg=a.z.object({type:a.z.literal("deploy.suggest"),requestId:a.z.string(),projectId:a.z.string(),environmentName:a.z.string(),notes:a.z.string().default(""),timeoutSeconds:a.z.number().int().positive().max(1800).default(300)});d.JiraUsersMsg=a.z.object({type:a.z.literal("jira.users"),requestId:a.z.string(),query:a.z.string().default("")});d.ServerToRunnerMsg=a.z.discriminatedUnion("type",[d.HelloAckMsg,d.ConfigMsg,d.RunClaimResultMsg,d.ProjectTestMsg,d.RuleDiagnoseMsg,d.RunCancelMsg,d.RunApprovedMsg,d.RunRejectedMsg,d.RunRetryPushMsg,d.DeployClaimResultMsg,d.DeployStartMsg,d.DeploySuggestMsg,d.DeployFixMsg,d.EnvPreflightMsg,d.ChatTurnMsg,d.ChatCreateTicketMsg,d.ChatListMsg,d.RepoDocsMsg,d.RepoDocReadMsg,d.ChatLoadMsg,d.BoardFetchMsg,d.BoardTriggerMsg,d.TeamCredsMsg,d.AuditStartMsg,d.AuditListMsg,d.AuditGetMsg,d.AuditReviewMsg,d.KnowledgeListMsg,d.KnowledgeSaveMsg,d.EpicListMsg,d.EpicSuggestMsg,d.JiraUsersMsg,d.SetupStatusMsg,d.SetupClaudeMdGenerateMsg,d.SetupClaudeMdSaveMsg,d.RepoDocSaveMsg,d.RunnerUpdateMsg,d.AgentProfilesMsg,d.RunResolveConflictMsg,d.RunTestFixMsg,d.AuditStatsMsg,d.AutopilotNextResultMsg]);d.EnrollRequest=a.z.object({enrollToken:a.z.string().min(10),name:a.z.string().min(1).max(100),platform:a.z.string(),runnerVersion:a.z.string()});d.EnrollResponse=a.z.object({runnerId:a.z.string(),runnerToken:a.z.string(),controlPlaneWsUrl:a.z.string()});function Km(n){return d.RunnerToServerMsg.parse(n)}function Zm(n){return d.ServerToRunnerMsg.parse(n)}d.DEFAULT_PLAN_PROMPT_TEMPLATE=`You are a senior engineer asked to assess a Jira ticket. You have read-only access to the repository - do not attempt to modify anything.
23
+ `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(s=>t.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function _l(n){return n.map(e=>{if(!e.startsWith("--inspect"))return e;let t,r="127.0.0.1",s="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?t=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=i[1],/^\d+$/.test(i[3])?s=i[3]:r=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],r=i[3],s=i[4]),t&&s!=="0"?`${t}=${r}:${parseInt(s)+1}`:e})}kl.Command=ko});var Il=re(Be=>{var{Argument:Tl}=Ks(),{Command:So}=Sl(),{CommanderError:hf,InvalidArgumentError:xl}=ds(),{Help:ff}=po(),{Option:Cl}=vo();Be.program=new So;Be.createCommand=n=>new So(n);Be.createOption=(n,e)=>new Cl(n,e);Be.createArgument=(n,e)=>new Tl(n,e);Be.Command=So;Be.Option=Cl;Be.Argument=Tl;Be.Help=ff;Be.CommanderError=hf;Be.InvalidArgumentError=xl;Be.InvalidOptionArgumentError=xl});var gs=re(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.getParsedType=le.ZodParsedType=le.objectUtil=le.util=void 0;var $o;(function(n){n.assertEqual=s=>{};function e(s){}n.assertIs=e;function t(s){throw new Error}n.assertNever=t,n.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},n.getValidEnumValues=s=>{let i=n.objectKeys(s).filter(l=>typeof s[s[l]]!="number"),o={};for(let l of i)o[l]=s[l];return n.objectValues(o)},n.objectValues=s=>n.objectKeys(s).map(function(i){return s[i]}),n.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},n.find=(s,i)=>{for(let o of s)if(i(o))return o},n.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}n.joinValues=r,n.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})($o||(le.util=$o={}));var Yl;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(Yl||(le.objectUtil=Yl={}));le.ZodParsedType=$o.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var $p=n=>{switch(typeof n){case"undefined":return le.ZodParsedType.undefined;case"string":return le.ZodParsedType.string;case"number":return Number.isNaN(n)?le.ZodParsedType.nan:le.ZodParsedType.number;case"boolean":return le.ZodParsedType.boolean;case"function":return le.ZodParsedType.function;case"bigint":return le.ZodParsedType.bigint;case"symbol":return le.ZodParsedType.symbol;case"object":return Array.isArray(n)?le.ZodParsedType.array:n===null?le.ZodParsedType.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?le.ZodParsedType.promise:typeof Map<"u"&&n instanceof Map?le.ZodParsedType.map:typeof Set<"u"&&n instanceof Set?le.ZodParsedType.set:typeof Date<"u"&&n instanceof Date?le.ZodParsedType.date:le.ZodParsedType.object;default:return le.ZodParsedType.unknown}};le.getParsedType=$p});var si=re(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.ZodError=Yt.quotelessJson=Yt.ZodIssueCode=void 0;var Xl=gs();Yt.ZodIssueCode=Xl.util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);var Pp=n=>JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:");Yt.quotelessJson=Pp;var ys=class n extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},r={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)r._errors.push(t(o));else{let l=r,u=0;for(;u<o.path.length;){let c=o.path[u];u===o.path.length-1?(l[c]=l[c]||{_errors:[]},l[c]._errors.push(t(o))):l[c]=l[c]||{_errors:[]},l=l[c],u++}}};return s(this),r}static assert(e){if(!(e instanceof n))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Xl.util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},r=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];t[i]=t[i]||[],t[i].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}};Yt.ZodError=ys;ys.create=n=>new ys(n)});var jo=re(Po=>{"use strict";Object.defineProperty(Po,"__esModule",{value:!0});var Se=si(),Pn=gs(),jp=(n,e)=>{let t;switch(n.code){case Se.ZodIssueCode.invalid_type:n.received===Pn.ZodParsedType.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case Se.ZodIssueCode.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,Pn.util.jsonStringifyReplacer)}`;break;case Se.ZodIssueCode.unrecognized_keys:t=`Unrecognized key(s) in object: ${Pn.util.joinValues(n.keys,", ")}`;break;case Se.ZodIssueCode.invalid_union:t="Invalid input";break;case Se.ZodIssueCode.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${Pn.util.joinValues(n.options)}`;break;case Se.ZodIssueCode.invalid_enum_value:t=`Invalid enum value. Expected ${Pn.util.joinValues(n.options)}, received '${n.received}'`;break;case Se.ZodIssueCode.invalid_arguments:t="Invalid function arguments";break;case Se.ZodIssueCode.invalid_return_type:t="Invalid function return type";break;case Se.ZodIssueCode.invalid_date:t="Invalid date";break;case Se.ZodIssueCode.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:Pn.util.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case Se.ZodIssueCode.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case Se.ZodIssueCode.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case Se.ZodIssueCode.custom:t="Invalid input";break;case Se.ZodIssueCode.invalid_intersection_types:t="Intersection results could not be merged";break;case Se.ZodIssueCode.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case Se.ZodIssueCode.not_finite:t="Number must be finite";break;default:t=e.defaultError,Pn.util.assertNever(n)}return{message:t}};Po.default=jp});var ii=re(Xt=>{"use strict";var Op=Xt&&Xt.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(Xt,"__esModule",{value:!0});Xt.defaultErrorMap=void 0;Xt.setErrorMap=Np;Xt.getErrorMap=Mp;var Ql=Op(jo());Xt.defaultErrorMap=Ql.default;var eu=Ql.default;function Np(n){eu=n}function Mp(){return eu}});var No=re(oe=>{"use strict";var zp=oe&&oe.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(oe,"__esModule",{value:!0});oe.isAsync=oe.isValid=oe.isDirty=oe.isAborted=oe.OK=oe.DIRTY=oe.INVALID=oe.ParseStatus=oe.EMPTY_PATH=oe.makeIssue=void 0;oe.addIssueToContext=Up;var Dp=ii(),tu=zp(jo()),Lp=n=>{let{data:e,path:t,errorMaps:r,issueData:s}=n,i=[...t,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let l="",u=r.filter(c=>!!c).slice().reverse();for(let c of u)l=c(o,{data:e,defaultError:l}).message;return{...s,path:i,message:l}};oe.makeIssue=Lp;oe.EMPTY_PATH=[];function Up(n,e){let t=(0,Dp.getErrorMap)(),r=(0,oe.makeIssue)({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===tu.default?void 0:tu.default].filter(s=>!!s)});n.common.issues.push(r)}var Oo=class n{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let r=[];for(let s of t){if(s.status==="aborted")return oe.INVALID;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let s of t){let i=await s.key,o=await s.value;r.push({key:i,value:o})}return n.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let s of t){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return oe.INVALID;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(r[i.value]=o.value)}return{status:e.value,value:r}}};oe.ParseStatus=Oo;oe.INVALID=Object.freeze({status:"aborted"});var qp=n=>({status:"dirty",value:n});oe.DIRTY=qp;var Fp=n=>({status:"valid",value:n});oe.OK=Fp;var Bp=n=>n.status==="aborted";oe.isAborted=Bp;var Kp=n=>n.status==="dirty";oe.isDirty=Kp;var Zp=n=>n.status==="valid";oe.isValid=Zp;var Gp=n=>typeof Promise<"u"&&n instanceof Promise;oe.isAsync=Gp});var ru=re(nu=>{"use strict";Object.defineProperty(nu,"__esModule",{value:!0})});var iu=re(oi=>{"use strict";Object.defineProperty(oi,"__esModule",{value:!0});oi.errorUtil=void 0;var su;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e?.message})(su||(oi.errorUtil=su={}))});var yu=re(_=>{"use strict";Object.defineProperty(_,"__esModule",{value:!0});_.discriminatedUnion=_.date=_.boolean=_.bigint=_.array=_.any=_.coerce=_.ZodFirstPartyTypeKind=_.late=_.ZodSchema=_.Schema=_.ZodReadonly=_.ZodPipeline=_.ZodBranded=_.BRAND=_.ZodNaN=_.ZodCatch=_.ZodDefault=_.ZodNullable=_.ZodOptional=_.ZodTransformer=_.ZodEffects=_.ZodPromise=_.ZodNativeEnum=_.ZodEnum=_.ZodLiteral=_.ZodLazy=_.ZodFunction=_.ZodSet=_.ZodMap=_.ZodRecord=_.ZodTuple=_.ZodIntersection=_.ZodDiscriminatedUnion=_.ZodUnion=_.ZodObject=_.ZodArray=_.ZodVoid=_.ZodNever=_.ZodUnknown=_.ZodAny=_.ZodNull=_.ZodUndefined=_.ZodSymbol=_.ZodDate=_.ZodBoolean=_.ZodBigInt=_.ZodNumber=_.ZodString=_.ZodType=void 0;_.NEVER=_.void=_.unknown=_.union=_.undefined=_.tuple=_.transformer=_.symbol=_.string=_.strictObject=_.set=_.record=_.promise=_.preprocess=_.pipeline=_.ostring=_.optional=_.onumber=_.oboolean=_.object=_.number=_.nullable=_.null=_.never=_.nativeEnum=_.nan=_.map=_.literal=_.lazy=_.intersection=_.instanceof=_.function=_.enum=_.effect=void 0;_.datetimeRegex=cu;_.custom=hu;var E=si(),ai=ii(),L=iu(),S=No(),P=gs(),Ve=class{constructor(e,t,r,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},ou=(n,e)=>{if((0,S.isValid)(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new E.ZodError(n.common.issues);return this._error=t,this._error}}};function W(n){if(!n)return{};let{errorMap:e,invalid_type_error:t,required_error:r,description:s}=n;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,l)=>{let{message:u}=n;return o.code==="invalid_enum_value"?{message:u??l.defaultError}:typeof l.data>"u"?{message:u??r??l.defaultError}:o.code!=="invalid_type"?{message:l.defaultError}:{message:u??t??l.defaultError}},description:s}}var J=class{get description(){return this._def.description}_getType(e){return(0,P.getParsedType)(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:(0,P.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new S.ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:(0,P.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if((0,S.isAsync)(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,P.getParsedType)(e)},s=this._parseSync({data:e,path:r.path,parent:r});return ou(r,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,P.getParsedType)(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return(0,S.isValid)(r)?{value:r.value}:{issues:t.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(r=>(0,S.isValid)(r)?{value:r.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,P.getParsedType)(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await((0,S.isAsync)(s)?s:Promise.resolve(s));return ou(r,i)}refine(e,t){let r=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,i)=>{let o=e(s),l=()=>i.addIssue({code:E.ZodIssueCode.custom,...r(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(u=>u?!0:(l(),!1)):o?!0:(l(),!1)})}refinement(e,t){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof t=="function"?t(r,s):t),!1))}_refinement(e){return new ze({schema:this,typeName:G.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return He.create(this,this._def)}nullable(){return pt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return jt.create(this)}promise(){return tn.create(this,this._def)}or(e){return Ln.create([this,e],this._def)}and(e){return Un.create(this,e,this._def)}transform(e){return new ze({...W(this._def),schema:this,typeName:G.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Zn({...W(this._def),innerType:this,defaultValue:t,typeName:G.ZodDefault})}brand(){return new vs({typeName:G.ZodBranded,type:this,...W(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Gn({...W(this._def),innerType:this,catchValue:t,typeName:G.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return bs.create(this,e)}readonly(){return Hn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};_.ZodType=J;_.Schema=J;_.ZodSchema=J;var Hp=/^c[^\s-]{8,}$/i,Vp=/^[0-9a-z]+$/,Wp=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Jp=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Yp=/^[a-z0-9_-]{21}$/i,Xp=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Qp=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,em=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,tm="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Mo,nm=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,rm=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,sm=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,im=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,om=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,am=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,lu="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",lm=new RegExp(`^${lu}$`);function uu(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);let t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function um(n){return new RegExp(`^${uu(n)}$`)}function cu(n){let e=`${lu}T${uu(n)}`,t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function cm(n,e){return!!((e==="v4"||!e)&&nm.test(n)||(e==="v6"||!e)&&sm.test(n))}function dm(n,e){if(!Xp.test(n))return!1;try{let[t]=n.split(".");if(!t)return!1;let r=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function hm(n,e){return!!((e==="v4"||!e)&&rm.test(n)||(e==="v6"||!e)&&im.test(n))}var Qt=class n extends J{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==P.ZodParsedType.string){let i=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(i,{code:E.ZodIssueCode.invalid_type,expected:P.ZodParsedType.string,received:i.parsedType}),S.INVALID}let r=new S.ParseStatus,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:E.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:E.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,l=e.data.length<i.value;(o||l)&&(s=this._getOrReturnCtx(e,s),o?(0,S.addIssueToContext)(s,{code:E.ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):l&&(0,S.addIssueToContext)(s,{code:E.ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")em.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"email",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Mo||(Mo=new RegExp(tm,"u")),Mo.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"emoji",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")Jp.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"uuid",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")Yp.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"nanoid",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")Hp.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"cuid",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")Vp.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"cuid2",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")Wp.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"ulid",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"url",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"regex",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:E.ZodIssueCode.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:E.ZodIssueCode.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:E.ZodIssueCode.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?cu(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:E.ZodIssueCode.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?lm.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:E.ZodIssueCode.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?um(i).test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:E.ZodIssueCode.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?Qp.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"duration",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?cm(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"ip",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?dm(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"jwt",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?hm(e.data,i.version)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"cidr",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?om.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"base64",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?am.test(e.data)||(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{validation:"base64url",code:E.ZodIssueCode.invalid_string,message:i.message}),r.dirty()):P.util.assertNever(i);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(s=>e.test(s),{validation:t,code:E.ZodIssueCode.invalid_string,...L.errorUtil.errToObj(r)})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...L.errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...L.errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...L.errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...L.errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...L.errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...L.errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...L.errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...L.errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...L.errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...L.errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...L.errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...L.errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...L.errorUtil.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...L.errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...L.errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...L.errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...L.errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...L.errorUtil.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...L.errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...L.errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...L.errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...L.errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...L.errorUtil.errToObj(t)})}nonempty(e){return this.min(1,L.errorUtil.errToObj(e))}trim(){return new n({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};_.ZodString=Qt;Qt.create=n=>new Qt({checks:[],typeName:G.ZodString,coerce:n?.coerce??!1,...W(n)});function fm(n,e){let t=(n.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=t>r?t:r,i=Number.parseInt(n.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var jn=class n extends J{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==P.ZodParsedType.number){let i=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(i,{code:E.ZodIssueCode.invalid_type,expected:P.ZodParsedType.number,received:i.parsedType}),S.INVALID}let r,s=new S.ParseStatus;for(let i of this._def.checks)i.kind==="int"?P.util.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?fm(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.not_finite,message:i.message}),s.dirty()):P.util.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,L.errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,L.errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,L.errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,L.errorUtil.toString(t))}setLimit(e,t,r,s){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:L.errorUtil.toString(s)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:L.errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:L.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:L.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:L.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:L.errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:L.errorUtil.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:L.errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:L.errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:L.errorUtil.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&P.util.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(t===null||r.value>t)&&(t=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}};_.ZodNumber=jn;jn.create=n=>new jn({checks:[],typeName:G.ZodNumber,coerce:n?.coerce||!1,...W(n)});var On=class n extends J{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==P.ZodParsedType.bigint)return this._getInvalidInput(e);let r,s=new S.ParseStatus;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):P.util.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(t,{code:E.ZodIssueCode.invalid_type,expected:P.ZodParsedType.bigint,received:t.parsedType}),S.INVALID}gte(e,t){return this.setLimit("min",e,!0,L.errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,L.errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,L.errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,L.errorUtil.toString(t))}setLimit(e,t,r,s){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:L.errorUtil.toString(s)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:L.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:L.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:L.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:L.errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:L.errorUtil.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};_.ZodBigInt=On;On.create=n=>new On({checks:[],typeName:G.ZodBigInt,coerce:n?.coerce??!1,...W(n)});var Nn=class extends J{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==P.ZodParsedType.boolean){let r=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.invalid_type,expected:P.ZodParsedType.boolean,received:r.parsedType}),S.INVALID}return(0,S.OK)(e.data)}};_.ZodBoolean=Nn;Nn.create=n=>new Nn({typeName:G.ZodBoolean,coerce:n?.coerce||!1,...W(n)});var Mn=class n extends J{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==P.ZodParsedType.date){let i=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(i,{code:E.ZodIssueCode.invalid_type,expected:P.ZodParsedType.date,received:i.parsedType}),S.INVALID}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(i,{code:E.ZodIssueCode.invalid_date}),S.INVALID}let r=new S.ParseStatus,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:E.ZodIssueCode.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),(0,S.addIssueToContext)(s,{code:E.ZodIssueCode.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):P.util.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:L.errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:L.errorUtil.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};_.ZodDate=Mn;Mn.create=n=>new Mn({checks:[],coerce:n?.coerce||!1,typeName:G.ZodDate,...W(n)});var Or=class extends J{_parse(e){if(this._getType(e)!==P.ZodParsedType.symbol){let r=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.invalid_type,expected:P.ZodParsedType.symbol,received:r.parsedType}),S.INVALID}return(0,S.OK)(e.data)}};_.ZodSymbol=Or;Or.create=n=>new Or({typeName:G.ZodSymbol,...W(n)});var zn=class extends J{_parse(e){if(this._getType(e)!==P.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.invalid_type,expected:P.ZodParsedType.undefined,received:r.parsedType}),S.INVALID}return(0,S.OK)(e.data)}};_.ZodUndefined=zn;zn.create=n=>new zn({typeName:G.ZodUndefined,...W(n)});var Dn=class extends J{_parse(e){if(this._getType(e)!==P.ZodParsedType.null){let r=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.invalid_type,expected:P.ZodParsedType.null,received:r.parsedType}),S.INVALID}return(0,S.OK)(e.data)}};_.ZodNull=Dn;Dn.create=n=>new Dn({typeName:G.ZodNull,...W(n)});var en=class extends J{constructor(){super(...arguments),this._any=!0}_parse(e){return(0,S.OK)(e.data)}};_.ZodAny=en;en.create=n=>new en({typeName:G.ZodAny,...W(n)});var Pt=class extends J{constructor(){super(...arguments),this._unknown=!0}_parse(e){return(0,S.OK)(e.data)}};_.ZodUnknown=Pt;Pt.create=n=>new Pt({typeName:G.ZodUnknown,...W(n)});var tt=class extends J{_parse(e){let t=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(t,{code:E.ZodIssueCode.invalid_type,expected:P.ZodParsedType.never,received:t.parsedType}),S.INVALID}};_.ZodNever=tt;tt.create=n=>new tt({typeName:G.ZodNever,...W(n)});var Nr=class extends J{_parse(e){if(this._getType(e)!==P.ZodParsedType.undefined){let r=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.invalid_type,expected:P.ZodParsedType.void,received:r.parsedType}),S.INVALID}return(0,S.OK)(e.data)}};_.ZodVoid=Nr;Nr.create=n=>new Nr({typeName:G.ZodVoid,...W(n)});var jt=class n extends J{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==P.ZodParsedType.array)return(0,S.addIssueToContext)(t,{code:E.ZodIssueCode.invalid_type,expected:P.ZodParsedType.array,received:t.parsedType}),S.INVALID;if(s.exactLength!==null){let o=t.data.length>s.exactLength.value,l=t.data.length<s.exactLength.value;(o||l)&&((0,S.addIssueToContext)(t,{code:o?E.ZodIssueCode.too_big:E.ZodIssueCode.too_small,minimum:l?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&((0,S.addIssueToContext)(t,{code:E.ZodIssueCode.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&((0,S.addIssueToContext)(t,{code:E.ZodIssueCode.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((o,l)=>s.type._parseAsync(new Ve(t,o,t.path,l)))).then(o=>S.ParseStatus.mergeArray(r,o));let i=[...t.data].map((o,l)=>s.type._parseSync(new Ve(t,o,t.path,l)));return S.ParseStatus.mergeArray(r,i)}get element(){return this._def.type}min(e,t){return new n({...this._def,minLength:{value:e,message:L.errorUtil.toString(t)}})}max(e,t){return new n({...this._def,maxLength:{value:e,message:L.errorUtil.toString(t)}})}length(e,t){return new n({...this._def,exactLength:{value:e,message:L.errorUtil.toString(t)}})}nonempty(e){return this.min(1,e)}};_.ZodArray=jt;jt.create=(n,e)=>new jt({type:n,minLength:null,maxLength:null,exactLength:null,typeName:G.ZodArray,...W(e)});function jr(n){if(n instanceof Pe){let e={};for(let t in n.shape){let r=n.shape[t];e[t]=He.create(jr(r))}return new Pe({...n._def,shape:()=>e})}else return n instanceof jt?new jt({...n._def,type:jr(n.element)}):n instanceof He?He.create(jr(n.unwrap())):n instanceof pt?pt.create(jr(n.unwrap())):n instanceof ft?ft.create(n.items.map(e=>jr(e))):n}var Pe=class n extends J{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=P.util.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==P.ZodParsedType.object){let c=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(c,{code:E.ZodIssueCode.invalid_type,expected:P.ZodParsedType.object,received:c.parsedType}),S.INVALID}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),l=[];if(!(this._def.catchall instanceof tt&&this._def.unknownKeys==="strip"))for(let c in s.data)o.includes(c)||l.push(c);let u=[];for(let c of o){let f=i[c],p=s.data[c];u.push({key:{status:"valid",value:c},value:f._parse(new Ve(s,p,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof tt){let c=this._def.unknownKeys;if(c==="passthrough")for(let f of l)u.push({key:{status:"valid",value:f},value:{status:"valid",value:s.data[f]}});else if(c==="strict")l.length>0&&((0,S.addIssueToContext)(s,{code:E.ZodIssueCode.unrecognized_keys,keys:l}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let f of l){let p=s.data[f];u.push({key:{status:"valid",value:f},value:c._parse(new Ve(s,p,s.path,f)),alwaysSet:f in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let c=[];for(let f of u){let p=await f.key,b=await f.value;c.push({key:p,value:b,alwaysSet:f.alwaysSet})}return c}).then(c=>S.ParseStatus.mergeObjectSync(r,c)):S.ParseStatus.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(e){return L.errorUtil.errToObj,new n({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{let s=this._def.errorMap?.(t,r).message??r.defaultError;return t.code==="unrecognized_keys"?{message:L.errorUtil.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new n({...this._def,unknownKeys:"strip"})}passthrough(){return new n({...this._def,unknownKeys:"passthrough"})}extend(e){return new n({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new n({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:G.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new n({...this._def,catchall:e})}pick(e){let t={};for(let r of P.util.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new n({...this._def,shape:()=>t})}omit(e){let t={};for(let r of P.util.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new n({...this._def,shape:()=>t})}deepPartial(){return jr(this)}partial(e){let t={};for(let r of P.util.objectKeys(this.shape)){let s=this.shape[r];e&&!e[r]?t[r]=s:t[r]=s.optional()}return new n({...this._def,shape:()=>t})}required(e){let t={};for(let r of P.util.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof He;)i=i._def.innerType;t[r]=i}return new n({...this._def,shape:()=>t})}keyof(){return du(P.util.objectKeys(this.shape))}};_.ZodObject=Pe;Pe.create=(n,e)=>new Pe({shape:()=>n,unknownKeys:"strip",catchall:tt.create(),typeName:G.ZodObject,...W(e)});Pe.strictCreate=(n,e)=>new Pe({shape:()=>n,unknownKeys:"strict",catchall:tt.create(),typeName:G.ZodObject,...W(e)});Pe.lazycreate=(n,e)=>new Pe({shape:n,unknownKeys:"strip",catchall:tt.create(),typeName:G.ZodObject,...W(e)});var Ln=class extends J{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;function s(i){for(let l of i)if(l.result.status==="valid")return l.result;for(let l of i)if(l.result.status==="dirty")return t.common.issues.push(...l.ctx.common.issues),l.result;let o=i.map(l=>new E.ZodError(l.ctx.common.issues));return(0,S.addIssueToContext)(t,{code:E.ZodIssueCode.invalid_union,unionErrors:o}),S.INVALID}if(t.common.async)return Promise.all(r.map(async i=>{let o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let u of r){let c={...t,common:{...t.common,issues:[]},parent:null},f=u._parseSync({data:t.data,path:t.path,parent:c});if(f.status==="valid")return f;f.status==="dirty"&&!i&&(i={result:f,ctx:c}),c.common.issues.length&&o.push(c.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let l=o.map(u=>new E.ZodError(u));return(0,S.addIssueToContext)(t,{code:E.ZodIssueCode.invalid_union,unionErrors:l}),S.INVALID}}get options(){return this._def.options}};_.ZodUnion=Ln;Ln.create=(n,e)=>new Ln({options:n,typeName:G.ZodUnion,...W(e)});var $t=n=>n instanceof qn?$t(n.schema):n instanceof ze?$t(n.innerType()):n instanceof Fn?[n.value]:n instanceof Bn?n.options:n instanceof Kn?P.util.objectValues(n.enum):n instanceof Zn?$t(n._def.innerType):n instanceof zn?[void 0]:n instanceof Dn?[null]:n instanceof He?[void 0,...$t(n.unwrap())]:n instanceof pt?[null,...$t(n.unwrap())]:n instanceof vs||n instanceof Hn?$t(n.unwrap()):n instanceof Gn?$t(n._def.innerType):[],li=class n extends J{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==P.ZodParsedType.object)return(0,S.addIssueToContext)(t,{code:E.ZodIssueCode.invalid_type,expected:P.ZodParsedType.object,received:t.parsedType}),S.INVALID;let r=this.discriminator,s=t.data[r],i=this.optionsMap.get(s);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):((0,S.addIssueToContext)(t,{code:E.ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),S.INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let s=new Map;for(let i of t){let o=$t(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let l of o){if(s.has(l))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(l)}`);s.set(l,i)}}return new n({typeName:G.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...W(r)})}};_.ZodDiscriminatedUnion=li;function zo(n,e){let t=(0,P.getParsedType)(n),r=(0,P.getParsedType)(e);if(n===e)return{valid:!0,data:n};if(t===P.ZodParsedType.object&&r===P.ZodParsedType.object){let s=P.util.objectKeys(e),i=P.util.objectKeys(n).filter(l=>s.indexOf(l)!==-1),o={...n,...e};for(let l of i){let u=zo(n[l],e[l]);if(!u.valid)return{valid:!1};o[l]=u.data}return{valid:!0,data:o}}else if(t===P.ZodParsedType.array&&r===P.ZodParsedType.array){if(n.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<n.length;i++){let o=n[i],l=e[i],u=zo(o,l);if(!u.valid)return{valid:!1};s.push(u.data)}return{valid:!0,data:s}}else return t===P.ZodParsedType.date&&r===P.ZodParsedType.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}var Un=class extends J{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),s=(i,o)=>{if((0,S.isAborted)(i)||(0,S.isAborted)(o))return S.INVALID;let l=zo(i.value,o.value);return l.valid?(((0,S.isDirty)(i)||(0,S.isDirty)(o))&&t.dirty(),{status:t.value,value:l.data}):((0,S.addIssueToContext)(r,{code:E.ZodIssueCode.invalid_intersection_types}),S.INVALID)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};_.ZodIntersection=Un;Un.create=(n,e,t)=>new Un({left:n,right:e,typeName:G.ZodIntersection,...W(t)});var ft=class n extends J{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==P.ZodParsedType.array)return(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.invalid_type,expected:P.ZodParsedType.array,received:r.parsedType}),S.INVALID;if(r.data.length<this._def.items.length)return(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),S.INVALID;!this._def.rest&&r.data.length>this._def.items.length&&((0,S.addIssueToContext)(r,{code:E.ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...r.data].map((o,l)=>{let u=this._def.items[l]||this._def.rest;return u?u._parse(new Ve(r,o,r.path,l)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>S.ParseStatus.mergeArray(t,o)):S.ParseStatus.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new n({...this._def,rest:e})}};_.ZodTuple=ft;ft.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ft({items:n,typeName:G.ZodTuple,rest:null,...W(e)})};var ui=class n extends J{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==P.ZodParsedType.object)return(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.invalid_type,expected:P.ZodParsedType.object,received:r.parsedType}),S.INVALID;let s=[],i=this._def.keyType,o=this._def.valueType;for(let l in r.data)s.push({key:i._parse(new Ve(r,l,r.path,l)),value:o._parse(new Ve(r,r.data[l],r.path,l)),alwaysSet:l in r.data});return r.common.async?S.ParseStatus.mergeObjectAsync(t,s):S.ParseStatus.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,r){return t instanceof J?new n({keyType:e,valueType:t,typeName:G.ZodRecord,...W(r)}):new n({keyType:Qt.create(),valueType:e,typeName:G.ZodRecord,...W(t)})}};_.ZodRecord=ui;var Mr=class extends J{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==P.ZodParsedType.map)return(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.invalid_type,expected:P.ZodParsedType.map,received:r.parsedType}),S.INVALID;let s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([l,u],c)=>({key:s._parse(new Ve(r,l,r.path,[c,"key"])),value:i._parse(new Ve(r,u,r.path,[c,"value"]))}));if(r.common.async){let l=new Map;return Promise.resolve().then(async()=>{for(let u of o){let c=await u.key,f=await u.value;if(c.status==="aborted"||f.status==="aborted")return S.INVALID;(c.status==="dirty"||f.status==="dirty")&&t.dirty(),l.set(c.value,f.value)}return{status:t.value,value:l}})}else{let l=new Map;for(let u of o){let c=u.key,f=u.value;if(c.status==="aborted"||f.status==="aborted")return S.INVALID;(c.status==="dirty"||f.status==="dirty")&&t.dirty(),l.set(c.value,f.value)}return{status:t.value,value:l}}}};_.ZodMap=Mr;Mr.create=(n,e,t)=>new Mr({valueType:e,keyType:n,typeName:G.ZodMap,...W(t)});var zr=class n extends J{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==P.ZodParsedType.set)return(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.invalid_type,expected:P.ZodParsedType.set,received:r.parsedType}),S.INVALID;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&((0,S.addIssueToContext)(r,{code:E.ZodIssueCode.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&((0,S.addIssueToContext)(r,{code:E.ZodIssueCode.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let i=this._def.valueType;function o(u){let c=new Set;for(let f of u){if(f.status==="aborted")return S.INVALID;f.status==="dirty"&&t.dirty(),c.add(f.value)}return{status:t.value,value:c}}let l=[...r.data.values()].map((u,c)=>i._parse(new Ve(r,u,r.path,c)));return r.common.async?Promise.all(l).then(u=>o(u)):o(l)}min(e,t){return new n({...this._def,minSize:{value:e,message:L.errorUtil.toString(t)}})}max(e,t){return new n({...this._def,maxSize:{value:e,message:L.errorUtil.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};_.ZodSet=zr;zr.create=(n,e)=>new zr({valueType:n,minSize:null,maxSize:null,typeName:G.ZodSet,...W(e)});var ci=class n extends J{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==P.ZodParsedType.function)return(0,S.addIssueToContext)(t,{code:E.ZodIssueCode.invalid_type,expected:P.ZodParsedType.function,received:t.parsedType}),S.INVALID;function r(l,u){return(0,S.makeIssue)({data:l,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,(0,ai.getErrorMap)(),ai.defaultErrorMap].filter(c=>!!c),issueData:{code:E.ZodIssueCode.invalid_arguments,argumentsError:u}})}function s(l,u){return(0,S.makeIssue)({data:l,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,(0,ai.getErrorMap)(),ai.defaultErrorMap].filter(c=>!!c),issueData:{code:E.ZodIssueCode.invalid_return_type,returnTypeError:u}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof tn){let l=this;return(0,S.OK)(async function(...u){let c=new E.ZodError([]),f=await l._def.args.parseAsync(u,i).catch(w=>{throw c.addIssue(r(u,w)),c}),p=await Reflect.apply(o,this,f);return await l._def.returns._def.type.parseAsync(p,i).catch(w=>{throw c.addIssue(s(p,w)),c})})}else{let l=this;return(0,S.OK)(function(...u){let c=l._def.args.safeParse(u,i);if(!c.success)throw new E.ZodError([r(u,c.error)]);let f=Reflect.apply(o,this,c.data),p=l._def.returns.safeParse(f,i);if(!p.success)throw new E.ZodError([s(f,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new n({...this._def,args:ft.create(e).rest(Pt.create())})}returns(e){return new n({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new n({args:e||ft.create([]).rest(Pt.create()),returns:t||Pt.create(),typeName:G.ZodFunction,...W(r)})}};_.ZodFunction=ci;var qn=class extends J{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};_.ZodLazy=qn;qn.create=(n,e)=>new qn({getter:n,typeName:G.ZodLazy,...W(e)});var Fn=class extends J{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(t,{received:t.data,code:E.ZodIssueCode.invalid_literal,expected:this._def.value}),S.INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}};_.ZodLiteral=Fn;Fn.create=(n,e)=>new Fn({value:n,typeName:G.ZodLiteral,...W(e)});function du(n,e){return new Bn({values:n,typeName:G.ZodEnum,...W(e)})}var Bn=class n extends J{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),r=this._def.values;return(0,S.addIssueToContext)(t,{expected:P.util.joinValues(r),received:t.parsedType,code:E.ZodIssueCode.invalid_type}),S.INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return(0,S.addIssueToContext)(t,{received:t.data,code:E.ZodIssueCode.invalid_enum_value,options:r}),S.INVALID}return(0,S.OK)(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return n.create(e,{...this._def,...t})}exclude(e,t=this._def){return n.create(this.options.filter(r=>!e.includes(r)),{...this._def,...t})}};_.ZodEnum=Bn;Bn.create=du;var Kn=class extends J{_parse(e){let t=P.util.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==P.ZodParsedType.string&&r.parsedType!==P.ZodParsedType.number){let s=P.util.objectValues(t);return(0,S.addIssueToContext)(r,{expected:P.util.joinValues(s),received:r.parsedType,code:E.ZodIssueCode.invalid_type}),S.INVALID}if(this._cache||(this._cache=new Set(P.util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=P.util.objectValues(t);return(0,S.addIssueToContext)(r,{received:r.data,code:E.ZodIssueCode.invalid_enum_value,options:s}),S.INVALID}return(0,S.OK)(e.data)}get enum(){return this._def.values}};_.ZodNativeEnum=Kn;Kn.create=(n,e)=>new Kn({values:n,typeName:G.ZodNativeEnum,...W(e)});var tn=class extends J{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==P.ZodParsedType.promise&&t.common.async===!1)return(0,S.addIssueToContext)(t,{code:E.ZodIssueCode.invalid_type,expected:P.ZodParsedType.promise,received:t.parsedType}),S.INVALID;let r=t.parsedType===P.ZodParsedType.promise?t.data:Promise.resolve(t.data);return(0,S.OK)(r.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};_.ZodPromise=tn;tn.create=(n,e)=>new tn({type:n,typeName:G.ZodPromise,...W(e)});var ze=class extends J{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===G.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{(0,S.addIssueToContext)(r,o),o.fatal?t.abort():t.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(r.data,i);if(r.common.async)return Promise.resolve(o).then(async l=>{if(t.value==="aborted")return S.INVALID;let u=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return u.status==="aborted"?S.INVALID:u.status==="dirty"||t.value==="dirty"?(0,S.DIRTY)(u.value):u});{if(t.value==="aborted")return S.INVALID;let l=this._def.schema._parseSync({data:o,path:r.path,parent:r});return l.status==="aborted"?S.INVALID:l.status==="dirty"||t.value==="dirty"?(0,S.DIRTY)(l.value):l}}if(s.type==="refinement"){let o=l=>{let u=s.refinement(l,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){let l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?S.INVALID:(l.status==="dirty"&&t.dirty(),o(l.value),{status:t.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?S.INVALID:(l.status==="dirty"&&t.dirty(),o(l.value).then(()=>({status:t.value,value:l.value}))))}if(s.type==="transform")if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!(0,S.isValid)(o))return S.INVALID;let l=s.transform(o.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>(0,S.isValid)(o)?Promise.resolve(s.transform(o.value,i)).then(l=>({status:t.value,value:l})):S.INVALID);P.util.assertNever(s)}};_.ZodEffects=ze;_.ZodTransformer=ze;ze.create=(n,e,t)=>new ze({schema:n,typeName:G.ZodEffects,effect:e,...W(t)});ze.createWithPreprocess=(n,e,t)=>new ze({schema:e,effect:{type:"preprocess",transform:n},typeName:G.ZodEffects,...W(t)});var He=class extends J{_parse(e){return this._getType(e)===P.ZodParsedType.undefined?(0,S.OK)(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};_.ZodOptional=He;He.create=(n,e)=>new He({innerType:n,typeName:G.ZodOptional,...W(e)});var pt=class extends J{_parse(e){return this._getType(e)===P.ZodParsedType.null?(0,S.OK)(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};_.ZodNullable=pt;pt.create=(n,e)=>new pt({innerType:n,typeName:G.ZodNullable,...W(e)});var Zn=class extends J{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return t.parsedType===P.ZodParsedType.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};_.ZodDefault=Zn;Zn.create=(n,e)=>new Zn({innerType:n,typeName:G.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...W(e)});var Gn=class extends J{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return(0,S.isAsync)(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new E.ZodError(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new E.ZodError(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};_.ZodCatch=Gn;Gn.create=(n,e)=>new Gn({innerType:n,typeName:G.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...W(e)});var Dr=class extends J{_parse(e){if(this._getType(e)!==P.ZodParsedType.nan){let r=this._getOrReturnCtx(e);return(0,S.addIssueToContext)(r,{code:E.ZodIssueCode.invalid_type,expected:P.ZodParsedType.nan,received:r.parsedType}),S.INVALID}return{status:"valid",value:e.data}}};_.ZodNaN=Dr;Dr.create=n=>new Dr({typeName:G.ZodNaN,...W(n)});_.BRAND=Symbol("zod_brand");var vs=class extends J{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}};_.ZodBranded=vs;var bs=class n extends J{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?S.INVALID:i.status==="dirty"?(t.dirty(),(0,S.DIRTY)(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?S.INVALID:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,t){return new n({in:e,out:t,typeName:G.ZodPipeline})}};_.ZodPipeline=bs;var Hn=class extends J{_parse(e){let t=this._def.innerType._parse(e),r=s=>((0,S.isValid)(s)&&(s.value=Object.freeze(s.value)),s);return(0,S.isAsync)(t)?t.then(s=>r(s)):r(t)}unwrap(){return this._def.innerType}};_.ZodReadonly=Hn;Hn.create=(n,e)=>new Hn({innerType:n,typeName:G.ZodReadonly,...W(e)});function au(n,e){let t=typeof n=="function"?n(e):typeof n=="string"?{message:n}:n;return typeof t=="string"?{message:t}:t}function hu(n,e={},t){return n?en.create().superRefine((r,s)=>{let i=n(r);if(i instanceof Promise)return i.then(o=>{if(!o){let l=au(e,r),u=l.fatal??t??!0;s.addIssue({code:"custom",...l,fatal:u})}});if(!i){let o=au(e,r),l=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:l})}}):en.create()}_.late={object:Pe.lazycreate};var G;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(G||(_.ZodFirstPartyTypeKind=G={}));var pm=(n,e={message:`Input not instance of ${n.name}`})=>hu(t=>t instanceof n,e);_.instanceof=pm;var fu=Qt.create;_.string=fu;var pu=jn.create;_.number=pu;var mm=Dr.create;_.nan=mm;var gm=On.create;_.bigint=gm;var mu=Nn.create;_.boolean=mu;var ym=Mn.create;_.date=ym;var vm=Or.create;_.symbol=vm;var bm=zn.create;_.undefined=bm;var wm=Dn.create;_.null=wm;var _m=en.create;_.any=_m;var km=Pt.create;_.unknown=km;var Sm=tt.create;_.never=Sm;var Tm=Nr.create;_.void=Tm;var xm=jt.create;_.array=xm;var Cm=Pe.create;_.object=Cm;var Im=Pe.strictCreate;_.strictObject=Im;var Rm=Ln.create;_.union=Rm;var Em=li.create;_.discriminatedUnion=Em;var Am=Un.create;_.intersection=Am;var $m=ft.create;_.tuple=$m;var Pm=ui.create;_.record=Pm;var jm=Mr.create;_.map=jm;var Om=zr.create;_.set=Om;var Nm=ci.create;_.function=Nm;var Mm=qn.create;_.lazy=Mm;var zm=Fn.create;_.literal=zm;var Dm=Bn.create;_.enum=Dm;var Lm=Kn.create;_.nativeEnum=Lm;var Um=tn.create;_.promise=Um;var gu=ze.create;_.effect=gu;_.transformer=gu;var qm=He.create;_.optional=qm;var Fm=pt.create;_.nullable=Fm;var Bm=ze.createWithPreprocess;_.preprocess=Bm;var Km=bs.create;_.pipeline=Km;var Zm=()=>fu().optional();_.ostring=Zm;var Gm=()=>pu().optional();_.onumber=Gm;var Hm=()=>mu().optional();_.oboolean=Hm;_.coerce={string:(n=>Qt.create({...n,coerce:!0})),number:(n=>jn.create({...n,coerce:!0})),boolean:(n=>Nn.create({...n,coerce:!0})),bigint:(n=>On.create({...n,coerce:!0})),date:(n=>Mn.create({...n,coerce:!0}))};_.NEVER=S.INVALID});var Do=re(We=>{"use strict";var Vm=We&&We.__createBinding||(Object.create?(function(n,e,t,r){r===void 0&&(r=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(n,r,s)}):(function(n,e,t,r){r===void 0&&(r=t),n[r]=e[t]})),Lr=We&&We.__exportStar||function(n,e){for(var t in n)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Vm(e,n,t)};Object.defineProperty(We,"__esModule",{value:!0});Lr(ii(),We);Lr(No(),We);Lr(ru(),We);Lr(gs(),We);Lr(yu(),We);Lr(si(),We)});var wu=re(je=>{"use strict";var vu=je&&je.__createBinding||(Object.create?(function(n,e,t,r){r===void 0&&(r=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(n,r,s)}):(function(n,e,t,r){r===void 0&&(r=t),n[r]=e[t]})),Wm=je&&je.__setModuleDefault||(Object.create?(function(n,e){Object.defineProperty(n,"default",{enumerable:!0,value:e})}):function(n,e){n.default=e}),Jm=je&&je.__importStar||function(n){if(n&&n.__esModule)return n;var e={};if(n!=null)for(var t in n)t!=="default"&&Object.prototype.hasOwnProperty.call(n,t)&&vu(e,n,t);return Wm(e,n),e},Ym=je&&je.__exportStar||function(n,e){for(var t in n)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&vu(e,n,t)};Object.defineProperty(je,"__esModule",{value:!0});je.z=void 0;var bu=Jm(Do());je.z=bu;Ym(Do(),je);je.default=bu});var we=re(d=>{"use strict";Object.defineProperty(d,"__esModule",{value:!0});d.RepoDocReadMsg=d.RepoDocsResultMsg=d.RepoDocsMsg=d.ChatLoadResultMsg=d.ChatLoadMsg=d.ChatListResultMsg=d.ChatListMsg=d.ChatUsageMsg=d.ChatStreamMsg=d.JiraUsersResultMsg=d.DeployClaimResultMsg=d.DeployClaimMsg=d.RuleDiagnoseResultMsg=d.ProjectTestResultMsg=d.RunStatusMsg=d.FailedTest=d.RunUsageMsg=d.RunLogMsg=d.RunClaimMsg=d.HeartbeatMsg=d.HelloMsg=d.RuleConfig=d.ProjectConfig=d.ActionConfig=d.DeployAction=d.EnvironmentConfig=d.PromotionMode=d.DeployStep=d.RespondAction=d.ImplementAction=d.PlanOnlyAction=d.TriggerConfig=d.StatusChangedTrigger=d.CommentKeywordTrigger=d.LabelAddedTrigger=d.ActionType=d.TriggerType=d.ACTIVE_RUN_STATUSES=d.RunStatus=d.needsInputMarkerIn=d.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=d.NEEDS_INPUT_COMMENT_MARKER=d.NEEDS_INPUT_LABEL=d.NEEDS_INPUT_MARKER=d.BRANCH_DEPLOY_ISSUE_KEY=d.REQUIRED_AGENT_CAPABILITIES=d.DEFAULT_AGENT_ID=d.REGISTERED_AGENTS=d.PROTOCOL_VERSION=d.GITHUB_TOKEN_PERMISSIONS=void 0;d.RunnerUpdateMsg=d.RepoDocSaveResultMsg=d.RepoDocSaveMsg=d.SetupClaudeMdSaveResultMsg=d.SetupClaudeMdSaveMsg=d.SetupClaudeMdGenerateResultMsg=d.SetupClaudeMdGenerateMsg=d.SetupStatusResultMsg=d.SetupStatusMsg=d.DeploySuggestResultMsg=d.EnvPreflightResultMsg=d.EnvPreflightMsg=d.ChatCreateTicketResultMsg=d.ChatCreateTicketMsg=d.ChatTurnResultMsg=d.ChatTurnMsg=d.ChatFile=d.TeamCredsResultMsg=d.TeamCredsMsg=d.KnowledgeSaveResultMsg=d.KnowledgeSaveMsg=d.KnowledgeListResultMsg=d.KnowledgeFile=d.KnowledgeListMsg=d.AuditReviewResultMsg=d.AuditReviewMsg=d.AuditGetResultMsg=d.AuditGetMsg=d.AuditListResultMsg=d.AuditStatsResultMsg=d.AuditStatsMsg=d.AuditListMsg=d.AuditStartResultMsg=d.AuditStartMsg=d.AuditRecord=d.AuditFinding=d.AuditScope=d.AuditSeverity=d.KnowledgeRole=d.AuditRole=d.EpicSuggestResultMsg=d.EpicSuggestMsg=d.EpicListResultMsg=d.EpicChild=d.EpicListMsg=d.BoardTriggerResultMsg=d.BoardTriggerMsg=d.BoardFetchResultMsg=d.BoardFetchMsg=d.RepoDocReadResultMsg=void 0;d.DEFAULT_DEPLOY_SUGGEST_PROMPT_TEMPLATE=d.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE=d.DEPLOY_FIX_PROMPT_TEMPLATE=d.PROMPT_PRESETS=d.DEFAULT_RESPOND_PROMPT_TEMPLATE=d.BUGFIX_IMPLEMENT_PROMPT_TEMPLATE=d.BUG_INVESTIGATION_PROMPT_TEMPLATE=d.TECHNICAL_PLAN_PROMPT_TEMPLATE=d.MEMORY_UPDATE_PROMPT=d.DEFAULT_IMPLEMENT_PROMPT_TEMPLATE=d.WRITE_TESTS_PROMPT=d.DEFAULT_PLAN_PROMPT_TEMPLATE=d.EnrollResponse=d.EnrollRequest=d.ServerToRunnerMsg=d.JiraUsersMsg=d.DeploySuggestMsg=d.DeployFixMsg=d.DeployStartMsg=d.RunRetryPushMsg=d.RunRejectedMsg=d.RunApprovedMsg=d.RunCancelMsg=d.RuleDiagnoseMsg=d.ProjectTestMsg=d.RunClaimResultMsg=d.ConfigMsg=d.HelloAckMsg=d.RunnerToServerMsg=d.AutopilotReportMsg=d.AutopilotNextResultMsg=d.AutopilotNextMsg=d.RunnerUpdateResultMsg=d.AgentProfilesResultMsg=d.AgentProfilesMsg=d.RunPrConflictMsg=d.RunResolveConflictResultMsg=d.RunTestFixResultMsg=d.RunTestFixMsg=d.RunResolveConflictMsg=void 0;d.missingAgentCapabilities=Xm;d.parseRunnerMsg=eg;d.parseServerMsg=tg;var a=wu();d.GITHUB_TOKEN_PERMISSIONS={where:"github.com/settings/personal-access-tokens/new (fine-grained token)",steps:["Resource owner: the org or user that OWNS the repo - not your personal account, unless the repo is under it","Repository access: Only select repositories -> pick this repo","Contents: Read and write - pushing the agent's branch","Pull requests: Read and write - opening the PR, and merging it when you approve","Metadata: Read-only - GitHub adds this itself and will not let you remove it","Workflows: Read and write - ONLY if changes may touch .github/workflows; without it GitHub rejects those pushes"],note:"A fine-grained token covers exactly ONE resource owner, so a repo in a different org always needs its own token. A classic token with the `repo` scope also works and is simpler, but it reaches every repository you can see - prefer fine-grained."};d.PROTOCOL_VERSION="1.44";d.REGISTERED_AGENTS=[{id:"claude-code",displayName:"Claude Code",capabilities:{readOnlyJail:!0,editNoShellJail:!0,sessionResume:!0,costReporting:!0,modelSelection:!0,loginProfiles:!0},suggestedModels:["claude-fable-5","claude-opus-5","claude-sonnet-5","claude-haiku-4-5-20251001"],experimental:!1},{id:"codex",displayName:"OpenAI Codex CLI (experimental)",capabilities:{readOnlyJail:!0,editNoShellJail:!1,sessionResume:!1,costReporting:!1,modelSelection:!0,loginProfiles:!1},suggestedModels:[],experimental:!0}];d.DEFAULT_AGENT_ID="claude-code";d.REQUIRED_AGENT_CAPABILITIES={plan_only:["readOnlyJail","sessionResume"],respond:["readOnlyJail"],implement:["editNoShellJail","sessionResume"],deploy:[],chat:["readOnlyJail","sessionResume"],assist:["readOnlyJail"]};function Xm(n,e){let t=d.REGISTERED_AGENTS.find(r=>r.id===n);return t?(d.REQUIRED_AGENT_CAPABILITIES[e]??[]).filter(r=>!t.capabilities[r]):null}d.BRANCH_DEPLOY_ISSUE_KEY="(branch deploy)";d.NEEDS_INPUT_MARKER="NEEDS-INPUT";d.NEEDS_INPUT_LABEL="agent-needs-input";d.NEEDS_INPUT_COMMENT_MARKER="Allwright needs your input";d.LEGACY_NEEDS_INPUT_COMMENT_MARKERS=["TicketPilot needs your input"];var Qm=n=>n.includes(d.NEEDS_INPUT_COMMENT_MARKER)||d.LEGACY_NEEDS_INPUT_COMMENT_MARKERS.some(e=>n.includes(e));d.needsInputMarkerIn=Qm;d.RunStatus=a.z.enum(["queued","running","posting","awaiting_approval","needs_input","succeeded","failed","timed_out"]);d.ACTIVE_RUN_STATUSES=["queued","running","posting","awaiting_approval"];d.TriggerType=a.z.enum(["label_added","comment_keyword","status_changed"]);d.ActionType=a.z.enum(["plan_only","implement","respond","deploy"]);d.LabelAddedTrigger=a.z.object({type:a.z.literal("label_added"),label:a.z.string().min(1),doneLabel:a.z.string().min(1).default("agent-planned"),failedLabel:a.z.string().min(1).default("agent-failed")});d.CommentKeywordTrigger=a.z.object({type:a.z.literal("comment_keyword"),keyword:a.z.string().min(1),doneLabel:a.z.string().min(1).default("agent-implemented"),failedLabel:a.z.string().min(1).default("agent-failed")});d.StatusChangedTrigger=a.z.object({type:a.z.literal("status_changed"),status:a.z.string().min(1),doneLabel:a.z.string().min(1).default("agent-deployed"),failedLabel:a.z.string().min(1).default("agent-failed")});d.TriggerConfig=a.z.discriminatedUnion("type",[d.LabelAddedTrigger,d.CommentKeywordTrigger,d.StatusChangedTrigger]);d.PlanOnlyAction=a.z.object({type:a.z.literal("plan_only"),promptTemplate:a.z.string().min(1),timeoutSeconds:a.z.number().int().positive().max(3600).default(900),agent:a.z.string().default(d.DEFAULT_AGENT_ID),model:a.z.string().default("")});d.ImplementAction=a.z.object({type:a.z.literal("implement"),promptTemplate:a.z.string().min(1),timeoutSeconds:a.z.number().int().positive().max(7200).default(1800),maxTurns:a.z.number().int().positive().max(500).default(120),requireApproval:a.z.boolean().default(!0),branchTemplate:a.z.string().min(1).default("agent/{{issueKey}}").refine(n=>n.includes("{{issueKey}}"),{message:"branchTemplate must contain {{issueKey}}"}),baseBranch:a.z.string().min(1).default("main"),jiraTransition:a.z.string().optional(),jiraTransitionOnStart:a.z.string().optional(),jiraTransitionOnMerge:a.z.string().optional(),agent:a.z.string().default(d.DEFAULT_AGENT_ID),model:a.z.string().default(""),updateMemory:a.z.boolean().default(!1),writeTests:a.z.boolean().default(!0),runTests:a.z.boolean().default(!0),mergeOnApprove:a.z.boolean().default(!0),mergeMethod:a.z.enum(["squash","merge","rebase"]).default("squash"),autoMerge:a.z.boolean().default(!0)});d.RespondAction=a.z.object({type:a.z.literal("respond"),promptTemplate:a.z.string().min(1),timeoutSeconds:a.z.number().int().positive().max(3600).default(600),agent:a.z.string().default(d.DEFAULT_AGENT_ID),model:a.z.string().default("")});d.DeployStep=a.z.object({name:a.z.string().min(1).max(120),run:a.z.string().min(1).max(4e3),continueOnError:a.z.boolean().default(!1)});d.PromotionMode=a.z.enum(["deploy_only","merge_and_deploy"]);d.EnvironmentConfig=a.z.object({id:a.z.string(),projectId:a.z.string(),name:a.z.string(),rank:a.z.number().int().nonnegative(),auditBeforeDeploy:a.z.enum(["","security","testing"]).default(""),branch:a.z.string().default(""),publicUrl:a.z.string().default(""),useDedicatedCheckout:a.z.boolean().default(!1),promotionMode:d.PromotionMode.default("deploy_only"),ticketBranchTemplate:a.z.string().default("agent/{{issueKey}}"),steps:a.z.array(d.DeployStep).default([]),workdir:a.z.string().default(""),timeoutSeconds:a.z.number().int().positive().max(21600).default(1800),requiredSecrets:a.z.array(a.z.string()).default([]),requireApproval:a.z.boolean().default(!1),requireSyncCheck:a.z.boolean().default(!1),previousEnvBranch:a.z.string().optional(),deployFromColumn:a.z.string().default(""),deployToColumn:a.z.string().default("")});d.DeployAction=a.z.object({type:a.z.literal("deploy"),envSelection:a.z.enum(["fixed","from_comment"]).default("from_comment"),environmentId:a.z.string().optional(),requireStatus:a.z.string().optional()});d.ActionConfig=a.z.discriminatedUnion("type",[d.PlanOnlyAction,d.ImplementAction,d.RespondAction,d.DeployAction]);d.ProjectConfig=a.z.object({id:a.z.string(),name:a.z.string(),jiraProjectKey:a.z.string(),goLiveIssueKey:a.z.string().default(""),repoName:a.z.string(),jiraSiteUrl:a.z.string().default(""),defaultAgent:a.z.string().default("claude-code"),componentRoutes:a.z.array(a.z.object({component:a.z.string().min(1),repoName:a.z.string().min(1)})).default([])});d.RuleConfig=a.z.object({id:a.z.string(),projectId:a.z.string(),name:a.z.string(),enabled:a.z.boolean(),trigger:d.TriggerConfig,action:d.ActionConfig});d.HelloMsg=a.z.object({type:a.z.literal("hello"),protocolVersion:a.z.string(),runnerVersion:a.z.string(),platform:a.z.string(),justBooted:a.z.boolean().optional()});d.HeartbeatMsg=a.z.object({type:a.z.literal("heartbeat"),ts:a.z.string()});d.RunClaimMsg=a.z.object({type:a.z.literal("run.claim"),requestId:a.z.string(),ruleId:a.z.string(),issueKey:a.z.string(),issueSummary:a.z.string().default(""),triggerFingerprint:a.z.string(),dedupKey:a.z.string().optional(),triggeredByAccountId:a.z.string().optional()});d.RunLogMsg=a.z.object({type:a.z.literal("run.log"),runId:a.z.string(),seq:a.z.number().int().nonnegative(),ts:a.z.string(),level:a.z.enum(["info","warn","error","agent"]),message:a.z.string().max(16384)});d.RunUsageMsg=a.z.object({type:a.z.literal("run.usage"),runId:a.z.string(),inputTokens:a.z.number().int().nonnegative(),outputTokens:a.z.number().int().nonnegative(),cacheReadTokens:a.z.number().int().nonnegative().optional(),costUsd:a.z.number().nonnegative().optional(),turns:a.z.number().int().nonnegative().optional()});d.FailedTest=a.z.object({command:a.z.string().max(500),exitCode:a.z.number().int(),tail:a.z.string().max(4e3)});d.RunStatusMsg=a.z.object({type:a.z.literal("run.status"),runId:a.z.string(),status:d.RunStatus,error:a.z.string().optional(),errorKind:a.z.enum(["guard"]).optional(),costUsd:a.z.number().nonnegative().optional(),inputTokens:a.z.number().int().nonnegative().optional(),outputTokens:a.z.number().int().nonnegative().optional(),resultSummary:a.z.string().max(2e3).optional(),billingMode:a.z.enum(["subscription","api","unknown"]).optional(),model:a.z.string().max(200).optional(),prUrl:a.z.string().optional(),headSha:a.z.string().optional(),deployedRef:a.z.string().optional(),retryAvailable:a.z.boolean().optional(),failedTests:a.z.array(d.FailedTest).max(20).optional(),testsPassed:a.z.number().int().nonnegative().optional(),testsTotal:a.z.number().int().nonnegative().optional(),goLiveDraft:a.z.string().max(4e3).optional()});d.ProjectTestResultMsg=a.z.object({type:a.z.literal("project.test.result"),requestId:a.z.string(),ok:a.z.boolean(),checks:a.z.array(a.z.object({name:a.z.string(),ok:a.z.boolean(),detail:a.z.string(),kind:a.z.enum(["connection","content"]).default("connection"),fix:a.z.array(a.z.string()).default([]),fixNote:a.z.string().default("")}))});d.RuleDiagnoseResultMsg=a.z.object({type:a.z.literal("rule.diagnose.result"),requestId:a.z.string(),checks:a.z.array(a.z.object({name:a.z.string(),ok:a.z.boolean(),detail:a.z.string(),kind:a.z.enum(["connection","content"]).default("connection"),fix:a.z.array(a.z.string()).default([]),fixNote:a.z.string().default("")})),matchedCount:a.z.number().int().nonnegative(),excludedCount:a.z.number().int().nonnegative(),excludedSample:a.z.array(a.z.string()).max(5)});d.DeployClaimMsg=a.z.object({type:a.z.literal("deploy.claim"),requestId:a.z.string(),projectId:a.z.string(),ruleId:a.z.string(),issueKey:a.z.string(),issueSummary:a.z.string().default(""),environmentName:a.z.string(),requestedByAccountId:a.z.string().optional(),requestedByDisplayName:a.z.string().default(""),dedupKey:a.z.string(),triggerFingerprint:a.z.string()});d.DeployClaimResultMsg=a.z.object({type:a.z.literal("deploy.claim.result"),requestId:a.z.string(),accepted:a.z.boolean(),runId:a.z.string().optional(),environment:d.EnvironmentConfig.optional(),reason:a.z.string().optional(),code:a.z.enum(["ok","duplicate","unknown_environment","not_permitted","unlinked_jira_account","promotion_order","jira_disabled","rule_disabled","cap"]).optional()});d.JiraUsersResultMsg=a.z.object({type:a.z.literal("jira.users.result"),requestId:a.z.string(),ok:a.z.boolean(),users:a.z.array(a.z.object({accountId:a.z.string(),displayName:a.z.string(),email:a.z.string().default(""),active:a.z.boolean().default(!0)})).default([]),error:a.z.string().optional()});d.ChatStreamMsg=a.z.object({type:a.z.literal("chat.stream"),requestId:a.z.string(),seq:a.z.number().int().nonnegative(),text:a.z.string().max(8e3)});d.ChatUsageMsg=a.z.object({type:a.z.literal("chat.usage"),requestId:a.z.string(),inputTokens:a.z.number().int().nonnegative(),outputTokens:a.z.number().int().nonnegative(),cacheReadTokens:a.z.number().int().nonnegative().optional(),turns:a.z.number().int().nonnegative().optional()});d.ChatListMsg=a.z.object({type:a.z.literal("chat.list"),requestId:a.z.string(),projectId:a.z.string()});d.ChatListResultMsg=a.z.object({type:a.z.literal("chat.list.result"),requestId:a.z.string(),sessions:a.z.array(a.z.object({sessionId:a.z.string(),title:a.z.string().default(""),updatedAt:a.z.string().default(""),messageCount:a.z.number().int().nonnegative().default(0)})).default([])});d.ChatLoadMsg=a.z.object({type:a.z.literal("chat.load"),requestId:a.z.string(),sessionId:a.z.string()});d.ChatLoadResultMsg=a.z.object({type:a.z.literal("chat.load.result"),requestId:a.z.string(),ok:a.z.boolean(),projectId:a.z.string().default(""),messages:a.z.array(a.z.object({role:a.z.enum(["user","agent"]),text:a.z.string()})).default([]),error:a.z.string().optional()});d.RepoDocsMsg=a.z.object({type:a.z.literal("repo.docs"),requestId:a.z.string(),projectId:a.z.string()});d.RepoDocsResultMsg=a.z.object({type:a.z.literal("repo.docs.result"),requestId:a.z.string(),ok:a.z.boolean(),docs:a.z.array(a.z.object({path:a.z.string(),sizeBytes:a.z.number().int().nonnegative().default(0),updatedAt:a.z.string().default("")})).default([]),error:a.z.string().optional()});d.RepoDocReadMsg=a.z.object({type:a.z.literal("repo.doc.read"),requestId:a.z.string(),projectId:a.z.string(),path:a.z.string().max(400)});d.RepoDocReadResultMsg=a.z.object({type:a.z.literal("repo.doc.read.result"),requestId:a.z.string(),ok:a.z.boolean(),path:a.z.string().default(""),content:a.z.string().default(""),truncated:a.z.boolean().default(!1),error:a.z.string().optional()});d.BoardFetchMsg=a.z.object({type:a.z.literal("board.fetch"),requestId:a.z.string(),projectId:a.z.string()});d.BoardFetchResultMsg=a.z.object({type:a.z.literal("board.fetch.result"),requestId:a.z.string(),ok:a.z.boolean(),browseBaseUrl:a.z.string().default(""),columns:a.z.array(a.z.object({name:a.z.string(),issues:a.z.array(a.z.object({key:a.z.string(),summary:a.z.string(),labels:a.z.array(a.z.string()).default([])})).default([])})).default([]),error:a.z.string().optional()});d.BoardTriggerMsg=a.z.object({type:a.z.literal("board.trigger"),requestId:a.z.string(),projectId:a.z.string(),issueKey:a.z.string(),comment:a.z.string().max(2e3).default(""),removeLabel:a.z.string().default(""),requestedBy:a.z.string().default(""),requestedByEmail:a.z.string().default(""),reimplement:a.z.boolean().default(!1)});d.BoardTriggerResultMsg=a.z.object({type:a.z.literal("board.trigger.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional()});d.EpicListMsg=a.z.object({type:a.z.literal("epic.list"),requestId:a.z.string(),projectId:a.z.string(),epicKey:a.z.string().default("")});d.EpicChild=a.z.object({key:a.z.string(),summary:a.z.string(),status:a.z.string(),statusCategory:a.z.string(),labels:a.z.array(a.z.string()).default([])});d.EpicListResultMsg=a.z.object({type:a.z.literal("epic.list.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),epics:a.z.array(a.z.object({key:a.z.string(),summary:a.z.string(),status:a.z.string()})).default([]),children:a.z.array(d.EpicChild).default([])});d.EpicSuggestMsg=a.z.object({type:a.z.literal("epic.suggest"),requestId:a.z.string(),projectId:a.z.string(),epicKey:a.z.string().min(1),model:a.z.string().default("")});d.EpicSuggestResultMsg=a.z.object({type:a.z.literal("epic.suggest.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),issueKey:a.z.string().default(""),reason:a.z.string().default(""),considered:a.z.number().int().default(0)});d.AuditRole=a.z.enum(["security","testing","architecture"]);d.KnowledgeRole=a.z.enum(["security","testing","architecture","implement"]);d.AuditSeverity=a.z.enum(["critical","high","medium","low","info"]);d.AuditScope=a.z.object({kind:a.z.enum(["repo","ticket","branch"]).default("repo"),ref:a.z.string().default("")});d.AuditFinding=a.z.object({id:a.z.string().min(1),title:a.z.string().min(1),ruleId:a.z.string().max(20).default(""),severity:d.AuditSeverity,area:a.z.string().default(""),evidence:a.z.array(a.z.object({file:a.z.string().min(1),line:a.z.number().int().positive().optional(),note:a.z.string().default("")})).min(1),fix:a.z.string().default("")});d.AuditRecord=a.z.object({id:a.z.string(),role:d.AuditRole,createdAt:a.z.string(),model:a.z.string().default(""),summary:a.z.string().default(""),packNames:a.z.array(a.z.string()).default([]),findings:a.z.array(d.AuditFinding).default([]),costUsd:a.z.number().default(0),review:a.z.object({selected:a.z.array(a.z.string()),updatedAt:a.z.string()}).optional(),verdicts:a.z.record(a.z.object({verdict:a.z.enum(["valid","false-positive","wont-fix"]),note:a.z.string().default(""),by:a.z.string().default(""),at:a.z.string().default("")})).default({}),lessonsWritten:a.z.array(a.z.string()).default([]),ticketed:a.z.record(a.z.string()).default({}),scope:d.AuditScope.default({kind:"repo",ref:""}),testRun:a.z.array(a.z.object({command:a.z.string(),exitCode:a.z.number().int(),durationMs:a.z.number().int().default(0),tail:a.z.string().default("")})).optional()});d.AuditStartMsg=a.z.object({type:a.z.literal("audit.start"),requestId:a.z.string(),projectId:a.z.string(),role:d.AuditRole,model:a.z.string().default(""),scope:d.AuditScope.default({kind:"repo",ref:""})});d.AuditStartResultMsg=a.z.object({type:a.z.literal("audit.start.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),audit:d.AuditRecord.optional()});d.AuditListMsg=a.z.object({type:a.z.literal("audit.list"),requestId:a.z.string(),projectId:a.z.string()});d.AuditStatsMsg=a.z.object({type:a.z.literal("audit.stats"),requestId:a.z.string(),projectIds:a.z.array(a.z.string()).max(200).default([]),since:a.z.string().default("")});d.AuditStatsResultMsg=a.z.object({type:a.z.literal("audit.stats.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),byProject:a.z.record(a.z.object({audits:a.z.number().int().default(0),findings:a.z.number().int().default(0),valid:a.z.number().int().default(0),falsePositive:a.z.number().int().default(0),wontFix:a.z.number().int().default(0),unreviewed:a.z.number().int().default(0)})).default({})});d.AuditListResultMsg=a.z.object({type:a.z.literal("audit.list.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),audits:a.z.array(a.z.object({id:a.z.string(),role:d.AuditRole,createdAt:a.z.string(),findingCount:a.z.number().int(),bySeverity:a.z.record(a.z.number().int()).default({})})).default([])});d.AuditGetMsg=a.z.object({type:a.z.literal("audit.get"),requestId:a.z.string(),projectId:a.z.string(),auditId:a.z.string()});d.AuditGetResultMsg=a.z.object({type:a.z.literal("audit.get.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),audit:d.AuditRecord.optional()});d.AuditReviewMsg=a.z.object({type:a.z.literal("audit.review"),requestId:a.z.string(),projectId:a.z.string(),auditId:a.z.string(),selected:a.z.array(a.z.string()).optional(),ticketed:a.z.array(a.z.object({findingId:a.z.string(),issueKey:a.z.string()})).default([]),verdicts:a.z.array(a.z.object({findingId:a.z.string(),verdict:a.z.enum(["valid","false-positive","wont-fix"]),note:a.z.string().max(2e3).default("")})).default([]),verdictBy:a.z.string().default("")});d.AuditReviewResultMsg=a.z.object({type:a.z.literal("audit.review.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),audit:d.AuditRecord.optional()});d.KnowledgeListMsg=a.z.object({type:a.z.literal("knowledge.list"),requestId:a.z.string(),projectId:a.z.string()});d.KnowledgeFile=a.z.object({role:d.KnowledgeRole,level:a.z.enum(["global","org","project"]),source:a.z.enum(["pack","lessons","memory"]),name:a.z.string(),content:a.z.string(),editable:a.z.boolean().default(!1)});d.KnowledgeListResultMsg=a.z.object({type:a.z.literal("knowledge.list.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),files:a.z.array(d.KnowledgeFile).default([])});d.KnowledgeSaveMsg=a.z.object({type:a.z.literal("knowledge.save"),requestId:a.z.string(),projectId:a.z.string(),role:d.KnowledgeRole,level:a.z.enum(["org","project"]),source:a.z.enum(["pack","lessons"]),name:a.z.string().min(1).max(100),content:a.z.string().max(6e4),append:a.z.boolean().default(!1),by:a.z.string().default("")});d.KnowledgeSaveResultMsg=a.z.object({type:a.z.literal("knowledge.save.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional()});d.TeamCredsMsg=a.z.object({type:a.z.literal("team.creds"),requestId:a.z.string(),emails:a.z.array(a.z.string()).max(200)});d.TeamCredsResultMsg=a.z.object({type:a.z.literal("team.creds.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),githubShared:a.z.boolean().default(!1),sharedGithubLogin:a.z.string().default(""),entries:a.z.array(a.z.object({email:a.z.string(),jira:a.z.enum(["own","runner-account","missing"]),jiraAs:a.z.string().default(""),github:a.z.enum(["own","shared","missing"]),githubAs:a.z.string().default("")})).default([])});d.ChatFile=a.z.object({name:a.z.string().min(1).max(255),contentBase64:a.z.string().min(1).max(6e6)});d.ChatTurnMsg=a.z.object({type:a.z.literal("chat.turn"),requestId:a.z.string(),projectId:a.z.string(),sessionId:a.z.string().optional(),message:a.z.string().min(1).max(2e4),userName:a.z.string().default(""),model:a.z.string().default(""),files:a.z.array(d.ChatFile).max(8).default([])});d.ChatTurnResultMsg=a.z.object({type:a.z.literal("chat.turn.result"),requestId:a.z.string(),ok:a.z.boolean(),sessionId:a.z.string().default(""),reply:a.z.string().default(""),error:a.z.string().optional(),inputTokens:a.z.number().int().nonnegative().default(0),outputTokens:a.z.number().int().nonnegative().default(0),cacheReadTokens:a.z.number().int().nonnegative().default(0),costUsd:a.z.number().nonnegative().default(0),model:a.z.string().max(200).default("")});d.ChatCreateTicketMsg=a.z.object({type:a.z.literal("chat.create.ticket"),requestId:a.z.string(),projectId:a.z.string(),summary:a.z.string().min(1).max(250),description:a.z.string().default(""),triggerComment:a.z.string().default(""),requestedBy:a.z.string().default(""),requestedByEmail:a.z.string().default(""),asEpic:a.z.boolean().default(!1),children:a.z.array(a.z.object({summary:a.z.string().min(1),description:a.z.string().default("")})).max(20).default([]),files:a.z.array(d.ChatFile).max(8).default([])});d.ChatCreateTicketResultMsg=a.z.object({type:a.z.literal("chat.create.ticket.result"),requestId:a.z.string(),ok:a.z.boolean(),issueKey:a.z.string().default(""),error:a.z.string().optional(),childKeys:a.z.array(a.z.string()).default([])});d.EnvPreflightMsg=a.z.object({type:a.z.literal("env.preflight"),requestId:a.z.string(),projectId:a.z.string(),environmentName:a.z.string().default(""),steps:a.z.array(d.DeployStep).default([]),requiredSecrets:a.z.array(a.z.string()).default([]),workdir:a.z.string().default(""),branch:a.z.string().default(""),publicUrl:a.z.string().default("")});d.EnvPreflightResultMsg=a.z.object({type:a.z.literal("env.preflight.result"),requestId:a.z.string(),ok:a.z.boolean(),checks:a.z.array(a.z.object({name:a.z.string(),ok:a.z.boolean(),detail:a.z.string().default(""),kind:a.z.enum(["connection","content"]).default("connection"),fix:a.z.array(a.z.string()).default([]),fixNote:a.z.string().default("")})).default([])});d.DeploySuggestResultMsg=a.z.object({type:a.z.literal("deploy.suggest.result"),requestId:a.z.string(),ok:a.z.boolean(),steps:a.z.array(d.DeployStep).default([]),requiredSecrets:a.z.array(a.z.string()).default([]),notes:a.z.string().default(""),error:a.z.string().optional(),docPath:a.z.string().default(""),docContent:a.z.string().max(1e5).default("")});d.SetupStatusMsg=a.z.object({type:a.z.literal("setup.status"),requestId:a.z.string(),repoNames:a.z.array(a.z.string()).max(100).default([])});d.SetupStatusResultMsg=a.z.object({type:a.z.literal("setup.status.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),jiraConfigured:a.z.boolean().default(!1),jiraEmail:a.z.string().default(""),claude:a.z.object({installed:a.z.boolean(),version:a.z.string().default(""),loggedIn:a.z.boolean()}).optional(),githubTokenSet:a.z.boolean().default(!1),githubLogin:a.z.string().default(""),deploysEnabled:a.z.boolean().default(!1),jiraUserCount:a.z.number().int().default(0),repos:a.z.array(a.z.object({repoName:a.z.string(),mapped:a.z.boolean(),pathExists:a.z.boolean().default(!1),isGit:a.z.boolean().default(!1),claudeMd:a.z.boolean().default(!1),deployMd:a.z.boolean().default(!1),testMd:a.z.boolean().default(!1),defaultBranch:a.z.string().default(""),githubToken:a.z.boolean().default(!1),githubTokenOwn:a.z.boolean().default(!1)})).default([])});d.SetupClaudeMdGenerateMsg=a.z.object({type:a.z.literal("setup.claudemd.generate"),requestId:a.z.string(),projectId:a.z.string(),kind:a.z.enum(["claude","deploy","design"]).default("claude"),streamId:a.z.string().default("")});d.SetupClaudeMdGenerateResultMsg=a.z.object({type:a.z.literal("setup.claudemd.generate.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),content:a.z.string().default("")});d.SetupClaudeMdSaveMsg=a.z.object({type:a.z.literal("setup.claudemd.save"),requestId:a.z.string(),projectId:a.z.string(),kind:a.z.enum(["claude","deploy","design"]).default("claude"),overwrite:a.z.boolean().default(!1),content:a.z.string().max(1e5)});d.SetupClaudeMdSaveResultMsg=a.z.object({type:a.z.literal("setup.claudemd.save.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),note:a.z.string().default("")});d.RepoDocSaveMsg=a.z.object({type:a.z.literal("repo.doc.save"),requestId:a.z.string(),projectId:a.z.string(),relPath:a.z.string().min(1).max(200),overwrite:a.z.boolean().default(!1),content:a.z.string().max(2e5)});d.RepoDocSaveResultMsg=a.z.object({type:a.z.literal("repo.doc.save.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),note:a.z.string().default("")});d.RunnerUpdateMsg=a.z.object({type:a.z.literal("runner.update"),requestId:a.z.string()});d.RunResolveConflictMsg=a.z.object({type:a.z.literal("run.resolve.conflict"),requestId:a.z.string(),runId:a.z.string()});d.RunTestFixMsg=a.z.object({type:a.z.literal("run.testfix"),requestId:a.z.string(),runId:a.z.string(),failedTests:a.z.array(d.FailedTest).min(1).max(20)});d.RunTestFixResultMsg=a.z.object({type:a.z.literal("run.testfix.result"),requestId:a.z.string(),ok:a.z.boolean(),note:a.z.string().default(""),headSha:a.z.string().default(""),remaining:a.z.array(d.FailedTest).default([]),costUsd:a.z.number().nonnegative().optional(),inputTokens:a.z.number().int().nonnegative().optional(),outputTokens:a.z.number().int().nonnegative().optional()});d.RunResolveConflictResultMsg=a.z.object({type:a.z.literal("run.resolve.conflict.result"),requestId:a.z.string(),ok:a.z.boolean(),note:a.z.string().default(""),freeOfCharge:a.z.boolean().default(!1),headSha:a.z.string().default(""),costUsd:a.z.number().nonnegative().optional(),inputTokens:a.z.number().int().nonnegative().optional(),outputTokens:a.z.number().int().nonnegative().optional()});d.RunPrConflictMsg=a.z.object({type:a.z.literal("run.pr.conflict"),runId:a.z.string(),conflicted:a.z.boolean()});d.AgentProfilesMsg=a.z.object({type:a.z.literal("agent.profiles"),requestId:a.z.string()});d.AgentProfilesResultMsg=a.z.object({type:a.z.literal("agent.profiles.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),profiles:a.z.array(a.z.object({agent:a.z.string(),name:a.z.string(),loggedIn:a.z.boolean()})).max(200).default([]),defaultLoggedIn:a.z.boolean().default(!1),agentsWithoutProfiles:a.z.array(a.z.string()).max(20).default([])});d.RunnerUpdateResultMsg=a.z.object({type:a.z.literal("runner.update.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),note:a.z.string().default(""),scheduled:a.z.boolean().default(!1)});d.AutopilotNextMsg=a.z.object({type:a.z.literal("autopilot.next"),requestId:a.z.string()});d.AutopilotNextResultMsg=a.z.object({type:a.z.literal("autopilot.next.result"),requestId:a.z.string(),ok:a.z.boolean(),error:a.z.string().optional(),item:a.z.object({id:a.z.string(),projectId:a.z.string(),issueKey:a.z.string(),ruleId:a.z.string(),baseOverride:a.z.string().default(""),branchOverride:a.z.string().default(""),continueBranch:a.z.boolean().default(!1),autoMerge:a.z.boolean().default(!1)}).nullable().default(null),pausedUntil:a.z.string().default("")});d.AutopilotReportMsg=a.z.object({type:a.z.literal("autopilot.report"),requestId:a.z.string(),itemId:a.z.string(),outcome:a.z.enum(["claimed","failed","paused"]),runId:a.z.string().default(""),error:a.z.string().default("")});d.RunnerToServerMsg=a.z.discriminatedUnion("type",[d.HelloMsg,d.HeartbeatMsg,d.RunClaimMsg,d.RunLogMsg,d.RunUsageMsg,d.RunStatusMsg,d.ProjectTestResultMsg,d.RuleDiagnoseResultMsg,d.DeployClaimMsg,d.DeploySuggestResultMsg,d.EnvPreflightResultMsg,d.ChatTurnResultMsg,d.ChatStreamMsg,d.ChatUsageMsg,d.ChatCreateTicketResultMsg,d.ChatListResultMsg,d.RepoDocsResultMsg,d.RepoDocReadResultMsg,d.ChatLoadResultMsg,d.BoardFetchResultMsg,d.BoardTriggerResultMsg,d.TeamCredsResultMsg,d.AuditStartResultMsg,d.AuditListResultMsg,d.AuditGetResultMsg,d.AuditReviewResultMsg,d.KnowledgeListResultMsg,d.KnowledgeSaveResultMsg,d.EpicListResultMsg,d.EpicSuggestResultMsg,d.JiraUsersResultMsg,d.SetupStatusResultMsg,d.SetupClaudeMdGenerateResultMsg,d.SetupClaudeMdSaveResultMsg,d.RepoDocSaveResultMsg,d.RunnerUpdateResultMsg,d.AgentProfilesResultMsg,d.RunPrConflictMsg,d.RunResolveConflictResultMsg,d.RunTestFixResultMsg,d.AuditStatsResultMsg,d.AutopilotNextMsg,d.AutopilotReportMsg]);d.HelloAckMsg=a.z.object({type:a.z.literal("hello.ack"),runnerId:a.z.string(),runnerName:a.z.string(),serverTime:a.z.string()});d.ConfigMsg=a.z.object({type:a.z.literal("config"),projects:a.z.array(d.ProjectConfig),rules:a.z.array(d.RuleConfig),environments:a.z.array(d.EnvironmentConfig).default([]),pollingPaused:a.z.boolean().default(!1)});d.RunClaimResultMsg=a.z.object({type:a.z.literal("run.claim.result"),requestId:a.z.string(),accepted:a.z.boolean(),runId:a.z.string().optional(),reason:a.z.string().optional(),claudeProfile:a.z.string().optional(),actorEmail:a.z.string().optional()});d.ProjectTestMsg=a.z.object({type:a.z.literal("project.test"),requestId:a.z.string(),projectId:a.z.string()});d.RuleDiagnoseMsg=a.z.object({type:a.z.literal("rule.diagnose"),requestId:a.z.string(),ruleId:a.z.string()});d.RunCancelMsg=a.z.object({type:a.z.literal("run.cancel"),runId:a.z.string()});d.RunApprovedMsg=a.z.object({type:a.z.literal("run.approved"),runId:a.z.string(),headSha:a.z.string().optional()});d.RunRejectedMsg=a.z.object({type:a.z.literal("run.rejected"),runId:a.z.string()});d.RunRetryPushMsg=a.z.object({type:a.z.literal("run.retryPush"),runId:a.z.string()});d.DeployStartMsg=a.z.object({type:a.z.literal("deploy.start"),runId:a.z.string(),projectId:a.z.string(),issueKey:a.z.string(),issueSummary:a.z.string().default(""),environment:d.EnvironmentConfig,requestedBy:a.z.string().default(""),attempt:a.z.number().int().positive().default(1)});d.DeployFixMsg=a.z.object({type:a.z.literal("deploy.fix"),requestId:a.z.string(),projectId:a.z.string(),environmentName:a.z.string(),steps:a.z.array(a.z.object({name:a.z.string(),run:a.z.string(),continueOnError:a.z.boolean().default(!1)})),failedStep:a.z.string().default(""),errorText:a.z.string().max(8e3).default("")});d.DeploySuggestMsg=a.z.object({type:a.z.literal("deploy.suggest"),requestId:a.z.string(),projectId:a.z.string(),environmentName:a.z.string(),notes:a.z.string().default(""),timeoutSeconds:a.z.number().int().positive().max(1800).default(300)});d.JiraUsersMsg=a.z.object({type:a.z.literal("jira.users"),requestId:a.z.string(),query:a.z.string().default("")});d.ServerToRunnerMsg=a.z.discriminatedUnion("type",[d.HelloAckMsg,d.ConfigMsg,d.RunClaimResultMsg,d.ProjectTestMsg,d.RuleDiagnoseMsg,d.RunCancelMsg,d.RunApprovedMsg,d.RunRejectedMsg,d.RunRetryPushMsg,d.DeployClaimResultMsg,d.DeployStartMsg,d.DeploySuggestMsg,d.DeployFixMsg,d.EnvPreflightMsg,d.ChatTurnMsg,d.ChatCreateTicketMsg,d.ChatListMsg,d.RepoDocsMsg,d.RepoDocReadMsg,d.ChatLoadMsg,d.BoardFetchMsg,d.BoardTriggerMsg,d.TeamCredsMsg,d.AuditStartMsg,d.AuditListMsg,d.AuditGetMsg,d.AuditReviewMsg,d.KnowledgeListMsg,d.KnowledgeSaveMsg,d.EpicListMsg,d.EpicSuggestMsg,d.JiraUsersMsg,d.SetupStatusMsg,d.SetupClaudeMdGenerateMsg,d.SetupClaudeMdSaveMsg,d.RepoDocSaveMsg,d.RunnerUpdateMsg,d.AgentProfilesMsg,d.RunResolveConflictMsg,d.RunTestFixMsg,d.AuditStatsMsg,d.AutopilotNextResultMsg]);d.EnrollRequest=a.z.object({enrollToken:a.z.string().min(10),name:a.z.string().min(1).max(100),platform:a.z.string(),runnerVersion:a.z.string()});d.EnrollResponse=a.z.object({runnerId:a.z.string(),runnerToken:a.z.string(),controlPlaneWsUrl:a.z.string()});function eg(n){return d.RunnerToServerMsg.parse(n)}function tg(n){return d.ServerToRunnerMsg.parse(n)}d.DEFAULT_PLAN_PROMPT_TEMPLATE=`You are a senior engineer asked to assess a Jira ticket. You have read-only access to the repository - do not attempt to modify anything.
24
24
 
25
25
  Ticket {{issueKey}}: {{summary}}
26
26
 
@@ -234,57 +234,57 @@ Rules for the steps:
234
234
  - Reference secrets as environment variables ($DEPLOY_HOST), never literal values, and list every variable you use in "requiredSecrets".
235
235
  - Prefer commands that are safe to re-run; a deploy may be retried.
236
236
  - Order matters: install, build, test (if cheap), then release.
237
- - If you genuinely cannot tell how this repo is deployed, return an empty "steps" array and explain what is missing in "notes".`});var Su={};Ds(Su,{DELETE_MANIFEST_FILE:()=>$t,MAX_CHANGED_FILES:()=>en,MAX_CHANGED_LINES:()=>tn,abortMerge:()=>sn,applyDeleteManifest:()=>Mr,branchForIssue:()=>Lo,branchSha:()=>hi,branchesDiffer:()=>Go,checkDiffSafety:()=>rn,commitAll:()=>Gn,commitMergeResolution:()=>Bo,deleteStaleBranch:()=>Mo,diffAgainstDefault:()=>fi,envCheckoutPath:()=>ku,envCheckoutsRoot:()=>_u,fetchBase:()=>nn,findConflictMarkers:()=>pi,headSha:()=>He,mergeBaseIntoWorktree:()=>Fo,mergeTicketBranch:()=>qo,originUrl:()=>Vn,parseOwnerRepo:()=>et,prepareEnvCheckout:()=>Uo,pruneWorktrees:()=>Do,pushBranch:()=>Hn,pushEnvBranch:()=>Zo,pushWipBranch:()=>Oo,removeWorktree:()=>ft,resetHard:()=>zr,statusSnapshot:()=>No,unresolvedAmong:()=>Ko,worktreeAdd:()=>zo,worktreeAddExisting:()=>gs,worktreeFingerprint:()=>di,worktreesRoot:()=>Pt});async function q(n,e,t={}){try{let{stdout:r}=await bu("git",["-C",n,...e],{timeout:t.timeoutMs??12e4,maxBuffer:16777216,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});return r}catch(r){let s=r;throw new Error(`git ${e[0]} failed: ${(s.stderr||s.message||"").trim().slice(0,500)}`)}}async function Mr(n){let e={deleted:[],refused:[]},t=ce.default.join(n,$t);if(!ge.default.existsSync(t))return e;let r=ce.default.resolve(n),s=ge.default.readFileSync(t,"utf8").split(`
238
- `).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#"));for(let i of s.slice(0,200)){if(ce.default.isAbsolute(i)){e.refused.push(`${i} - absolute paths are not allowed`);continue}let o=ce.default.resolve(r,i);if(o!==r&&!o.startsWith(r+ce.default.sep)){e.refused.push(`${i} - escapes the worktree`);continue}let l=ce.default.relative(r,o).split(ce.default.sep).join("/");if(l===$t)continue;if(wu.some(c=>c.test(l))){e.refused.push(`${i} - protected path (CI/hook files are never touched)`);continue}let u;try{u=ge.default.lstatSync(o)}catch{e.refused.push(`${i} - no such file`);continue}if(u.isDirectory()){e.refused.push(`${i} - is a directory (list the files inside it instead)`);continue}try{ge.default.rmSync(o),e.deleted.push(l)}catch(c){e.refused.push(`${i} - ${c instanceof Error?c.message:"delete failed"}`)}}return ge.default.rmSync(t,{force:!0}),e}async function Oo(n,e){await q(n,["push","--force","origin",`HEAD:refs/heads/${e}`],{timeoutMs:3e5})}async function di(n){let e=await q(n,["status","--porcelain"]),t=await q(n,["diff","--numstat"]),r=e.split(`
239
- `).filter(s=>s.startsWith("??")).map(s=>s.slice(3).trim()).slice(0,500).map(s=>{try{let i=ge.default.statSync(ce.default.join(n,s));return`${s}:${i.size}:${i.mtimeMs}`}catch{return s}}).join(`
237
+ - If you genuinely cannot tell how this repo is deployed, return an empty "steps" array and explain what is missing in "notes".`});var Au={};Fs(Au,{DELETE_MANIFEST_FILE:()=>Ot,MAX_CHANGED_FILES:()=>nn,MAX_CHANGED_LINES:()=>rn,abortMerge:()=>an,applyDeleteManifest:()=>Ur,branchForIssue:()=>Ko,branchSha:()=>gi,branchesDiffer:()=>Yo,checkDiffSafety:()=>on,commitAll:()=>Wn,commitMergeResolution:()=>Vo,deleteStaleBranch:()=>qo,diffAgainstDefault:()=>yi,envCheckoutPath:()=>Eu,envCheckoutsRoot:()=>Ru,fetchBase:()=>sn,findConflictMarkers:()=>vi,headSha:()=>Je,mergeBaseIntoWorktree:()=>Ho,mergeTicketBranch:()=>Go,originUrl:()=>Yn,parseOwnerRepo:()=>nt,prepareEnvCheckout:()=>Zo,pruneWorktrees:()=>Bo,pushBranch:()=>Jn,pushEnvBranch:()=>Jo,pushWipBranch:()=>Lo,removeWorktree:()=>mt,resetHard:()=>qr,statusSnapshot:()=>Uo,unresolvedAmong:()=>Wo,worktreeAdd:()=>Fo,worktreeAddExisting:()=>_s,worktreeFingerprint:()=>mi,worktreesRoot:()=>Nt});async function U(n,e,t={}){try{let{stdout:r}=await Cu("git",["-C",n,...e],{timeout:t.timeoutMs??12e4,maxBuffer:16777216,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});return r}catch(r){let s=r;throw new Error(`git ${e[0]} failed: ${(s.stderr||s.message||"").trim().slice(0,500)}`)}}async function Ur(n){let e={deleted:[],refused:[]},t=ue.default.join(n,Ot);if(!me.default.existsSync(t))return e;let r=ue.default.resolve(n),s=me.default.readFileSync(t,"utf8").split(`
238
+ `).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#"));for(let i of s.slice(0,200)){if(ue.default.isAbsolute(i)){e.refused.push(`${i} - absolute paths are not allowed`);continue}let o=ue.default.resolve(r,i);if(o!==r&&!o.startsWith(r+ue.default.sep)){e.refused.push(`${i} - escapes the worktree`);continue}let l=ue.default.relative(r,o).split(ue.default.sep).join("/");if(l===Ot)continue;if(Iu.some(c=>c.test(l))){e.refused.push(`${i} - protected path (CI/hook files are never touched)`);continue}let u;try{u=me.default.lstatSync(o)}catch{e.refused.push(`${i} - no such file`);continue}if(u.isDirectory()){e.refused.push(`${i} - is a directory (list the files inside it instead)`);continue}try{me.default.rmSync(o),e.deleted.push(l)}catch(c){e.refused.push(`${i} - ${c instanceof Error?c.message:"delete failed"}`)}}return me.default.rmSync(t,{force:!0}),e}async function Lo(n,e){await U(n,["push","--force","origin",`HEAD:refs/heads/${e}`],{timeoutMs:3e5})}async function mi(n){let e=await U(n,["status","--porcelain"]),t=await U(n,["diff","--numstat"]),r=e.split(`
239
+ `).filter(s=>s.startsWith("??")).map(s=>s.slice(3).trim()).slice(0,500).map(s=>{try{let i=me.default.statSync(ue.default.join(n,s));return`${s}:${i.size}:${i.mtimeMs}`}catch{return s}}).join(`
240
240
  `);return`${e}
241
241
  --
242
242
  ${t}
243
243
  --
244
- ${r}`}async function No(n){let e=(await q(n,["rev-parse","--abbrev-ref","HEAD"])).trim(),t=(await q(n,["log","--oneline","-1"])).trim(),r=(await q(n,["status","--porcelain"])).trim(),s=r?r.split(`
244
+ ${r}`}async function Uo(n){let e=(await U(n,["rev-parse","--abbrev-ref","HEAD"])).trim(),t=(await U(n,["log","--oneline","-1"])).trim(),r=(await U(n,["status","--porcelain"])).trim(),s=r?r.split(`
245
245
  `):[],i=s.slice(0,15).join(`
246
246
  `),o=s.length>15?`
247
247
  (\u2026 ${s.length-15} more)`:"";return`branch ${e} @ ${t}
248
248
  working tree: ${s.length?`
249
- ${i}${o}`:"clean"}`}function Pt(){let n=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(ge.default.existsSync(ce.default.join(Zn.default.homedir(),".cache","ticketpilot"))?ce.default.join(Zn.default.homedir(),".cache","ticketpilot"):ce.default.join(Zn.default.homedir(),".cache","allwright"));return ce.default.join(n,"worktrees")}async function nn(n,e){try{await q(n,["fetch","origin",e])}catch(t){throw new Error(`could not fetch base branch "${e}" from origin - check the rule's base branch and that this machine can reach the remote (${t instanceof Error?t.message:t})`)}}async function Mo(n,e){try{let t=await q(n,["worktree","list","--porcelain"]),r=Pt(),s=null;for(let i of t.split(`
250
- `))i.startsWith("worktree ")&&(s=i.slice(9).trim()),i===`branch refs/heads/${e}`&&s&&s.startsWith(r)&&await q(n,["worktree","remove","--force",s]);await q(n,["worktree","prune"])}catch{}try{await q(n,["branch","-D",e])}catch{}}async function zo(n,e,t,r){ge.default.mkdirSync(ce.default.dirname(e),{recursive:!0,mode:448}),await q(n,["worktree","add","-b",t,e,`origin/${r}`])}async function Gn(n,e){if(await q(n,["add","-A"]),!(await q(n,["status","--porcelain"])).trim())throw new Error("Claude wrote no changes - nothing to commit");await q(n,["-c",`user.name=${ui}`,"-c",`user.email=${ci}`,"commit","-m",e])}async function rn(n,e){let r=(await q(n,["diff","--name-only",`origin/${e}...HEAD`])).split(`
251
- `).filter(Boolean),s=r.filter(c=>wu.some(f=>f.test(c))),i=await q(n,["diff","--shortstat",`origin/${e}...HEAD`]),o=Number(/(\d+) insertion/.exec(i)?.[1]??0),l=Number(/(\d+) deletion/.exec(i)?.[1]??0);return{ok:s.length===0&&r.length<=en&&o+l<=tn,files:r.length,insertions:o,deletions:l,forbidden:s}}async function Hn(n,e){await q(n,["fetch","--prune","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],{timeoutMs:12e4}).catch(()=>q(n,["update-ref","-d",`refs/remotes/origin/${e}`]).catch(()=>{})),await q(n,["push","--force-with-lease","-u","origin",e],{timeoutMs:3e5})}async function He(n){return(await q(n,["rev-parse","HEAD"])).trim()}async function hi(n,e){try{return(await q(n,["rev-parse","--verify",`refs/heads/${e}`])).trim()}catch{return null}}async function zr(n,e){await q(n,["reset","--hard",e])}async function ft(n,e){try{await q(n,["worktree","remove","--force",e])}catch{ge.default.rmSync(e,{recursive:!0,force:!0})}}async function Do(n,e=[]){let t=new Set(e.map(s=>ce.default.basename(ce.default.resolve(s))).filter(s=>s.length>0)),r=Pt();if(ge.default.existsSync(r))for(let s of ge.default.readdirSync(r))t.has(s)||ge.default.rmSync(ce.default.join(r,s),{recursive:!0,force:!0});for(let s of n)try{await q(s,["worktree","prune"])}catch{}}async function Lo(n,e){return await q(n,["fetch","origin","--prune"]).catch(()=>{}),(await q(n,["branch","-r","--list",`*${e}*`])).split(`
252
- `).map(s=>s.trim()).filter(s=>s&&!s.includes("->"))[0]??null}async function fi(n,e,t=6e4){let s=(await q(n,["symbolic-ref","refs/remotes/origin/HEAD"]).catch(()=>"")).trim().replace("refs/remotes/","")||"origin/main",i=await q(n,["diff","--stat",`${s}...${e}`]),o=await q(n,["diff",`${s}...${e}`]);return{base:s,stat:i.slice(0,4e3),diff:o.slice(0,t)}}function _u(){let n=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(ge.default.existsSync(ce.default.join(Zn.default.homedir(),".cache","ticketpilot"))?ce.default.join(Zn.default.homedir(),".cache","ticketpilot"):ce.default.join(Zn.default.homedir(),".cache","allwright"));return ce.default.join(n,"env-checkouts")}function gu(n){return n.replace(/[^\w.-]+/g,"_")}function ku(n,e){return ce.default.join(_u(),gu(n),gu(e))}async function Uo(n){let e=ku(n.repoName,n.envName);return await q(n.repoPath,["fetch","origin",n.branch],{timeoutMs:3e5}),ge.default.existsSync(ce.default.join(e,".git"))?await q(e,["fetch","origin",n.branch],{timeoutMs:3e5}):(ge.default.rmSync(e,{recursive:!0,force:!0}),ge.default.mkdirSync(ce.default.dirname(e),{recursive:!0,mode:448}),await q(n.repoPath,["worktree","prune"]).catch(()=>{}),await q(n.repoPath,["worktree","add","--detach",e,`origin/${n.branch}`])),n.attached?await q(e,["checkout","-B",n.branch,`origin/${n.branch}`]):await q(e,["checkout","--force","--detach",`origin/${n.branch}`]),e}async function qo(n,e,t){try{await q(n,["fetch","origin",e],{timeoutMs:3e5})}catch{return{ok:!1,reason:`branch "${e}" does not exist on origin - nothing to promote. Check the environment's ticket branch template against the branch your implement rule creates.`}}try{return await q(n,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyMerged:!0}}catch{}try{return await q(n,["-c",`user.name=${ui}`,"-c",`user.email=${ci}`,"merge","--no-ff","-m",t,`origin/${e}`]),{ok:!0}}catch(r){return await q(n,["merge","--abort"]).catch(()=>{}),{ok:!1,reason:`could not merge "${e}" into the environment branch - ${r instanceof Error?r.message:r}. Resolve it manually and deploy again.`}}}async function Fo(n,e){await q(n,["fetch","origin",e],{timeoutMs:3e5});try{return await q(n,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyUpToDate:!0}}catch{}try{return await q(n,["-c",`user.name=${ui}`,"-c",`user.email=${ci}`,"merge","--no-edit",`origin/${e}`]),{ok:!0,alreadyUpToDate:!1}}catch(t){let s=(await q(n,["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
253
- `).filter(Boolean);return s.length?{ok:!1,conflicts:s}:(await q(n,["merge","--abort"]).catch(()=>{}),{ok:!1,conflicts:null,reason:t instanceof Error?t.message.slice(0,300):String(t)})}}async function sn(n){await q(n,["merge","--abort"]).catch(()=>{})}async function Bo(n,e){await q(n,["add","-A"]),await q(n,["-c",`user.name=${ui}`,"-c",`user.email=${ci}`,"commit","--no-edit","-m",e])}async function Ko(n,e){let t=new Set(await pi(n));return e.filter(r=>t.has(r))}async function pi(n){let e=new Set;try{let r=await q(n,["grep","-l","-I","-E","^(<{7}|>{7})( |$)"]);for(let s of r.split(`
254
- `).filter(Boolean))e.add(s)}catch{}let t=[];try{t=(await q(n,["grep","-l","-I","-E","^={7}$"])).split(`
255
- `).filter(Boolean).filter(s=>!e.has(s))}catch{}for(let r of t)try{let s=await q(n,["show",`HEAD:${r}`]);/^={7}$/m.test(s)||e.add(r)}catch{e.add(r)}return[...e]}async function gs(n,e,t){ge.default.mkdirSync(ce.default.dirname(e),{recursive:!0,mode:448}),await q(n,["fetch","origin",t],{timeoutMs:3e5}),await q(n,["worktree","add","--detach",e,`origin/${t}`]),await q(e,["checkout","-B",t,`origin/${t}`])}async function Zo(n,e){try{await q(n,["push","origin",e],{timeoutMs:3e5})}catch(t){throw new Error(`could not push "${e}" - ${t instanceof Error?t.message:t}. Someone may have pushed to it since this deploy started; retry.`)}}async function Go(n,e,t){try{return await bu("git",["-C",n,"diff","--quiet",e,t,"--"],{timeout:12e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),!1}catch(r){let s=r;if(s.code===1)return!0;throw new Error(`git diff failed comparing ${e}..${t}: ${(s.stderr||s.message||"").trim().slice(0,500)}`)}}async function Vn(n){return(await q(n,["config","--get","remote.origin.url"])).trim()}function et(n){let e=/^git@github\.com(?:-[\w.-]+)?:([^/]+)\/(.+?)(\.git)?$/.exec(n)??/^https:\/\/github\.com\/([^/]+)\/(.+?)(\.git)?\/?$/.exec(n)??/^ssh:\/\/git@github\.com(?:-[\w.-]+)?\/([^/]+)\/(.+?)(\.git)?$/.exec(n);return e?{owner:e[1],repo:e[2]}:null}var ge,Zn,ce,yu,vu,bu,ui,ci,en,tn,wu,$t,pt=zs(()=>{"use strict";ge=R(require("node:fs"),1),Zn=R(require("node:os"),1),ce=R(require("node:path"),1),yu=require("node:child_process"),vu=require("node:util"),bu=(0,vu.promisify)(yu.execFile),ui="Allwright Agent",ci="agent@ticketpilot.local",en=200,tn=2e4,wu=[/^\.github\/workflows\//,/^\.git\b/,/(^|\/)\.githooks\//];$t=".ticketpilot-delete"});function mi(n,e,t){let r=(t??"").trim().toLowerCase(),s=r?n.githubUsers[r]?.token:void 0;if(s)return{token:s,source:"user"};let i=n.repos[e]?.github?.token;return i?{token:i,source:"repo"}:n.github?.token?{token:n.github.token,source:"global"}:null}function Te(n,e){return n.repos[e]?.github?.token??n.github?.token??null}function Iu(n,e){let t=[n.jira,...Object.values(n.repos).map(l=>l.jira)].filter(l=>!!l),r=new Set(t.map(l=>l.email.toLowerCase())),s=!!n.github?.token||Object.values(n.repos).some(l=>l.github?.token),i=n.github?.login??Object.values(n.repos).find(l=>l.github?.login)?.github?.login??"",o=e.map(l=>{let u=l.trim().toLowerCase(),c=n.jiraUsers[u]?"own":r.has(u)?"runner-account":"missing",f=c==="own"?n.jiraUsers[u].email:c==="runner-account"?u:"",p=n.githubUsers[u]?"own":s?"shared":"missing",b=p==="own"?n.githubUsers[u].login??"":p==="shared"?i:"";return{email:u,jira:c,jiraAs:f,github:p,githubAs:b}});return{githubShared:s,sharedGithubLogin:i,entries:o}}var Wn=zs(()=>{"use strict"});var Qn={};Ds(Qn,{GitHubClient:()=>xe});var cg,xe,nt=zs(()=>{"use strict";cg=process.env.TICKETPILOT_GITHUB_API??"https://api.github.com",xe=class{constructor(e){this.token=e}token;async request(e,t,r){let s=await fetch(`${cg}${t}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"allwright",...r!==void 0?{"Content-Type":"application/json"}:{}},body:r===void 0?void 0:JSON.stringify(r)}),i=await s.text(),o=null;try{o=i?JSON.parse(i):null}catch{}if(s.status===401)throw new Error("GitHub rejected the token (401) - expired or revoked? Run `allwright github set-token`");if(!s.ok&&s.status!==422){let l=o?.message??i.slice(0,300);throw new Error(`GitHub ${e} ${t} -> ${s.status}: ${l}`)}return{status:s.status,data:o}}async whoami(){let{data:e}=await this.request("GET","/user");return e.login}async createPullRequest(e,t,r){let{status:s,data:i}=await this.request("POST",`/repos/${e}/${t}/pulls`,r);if(s===422){let{data:o}=await this.request("GET",`/repos/${e}/${t}/pulls?head=${encodeURIComponent(`${e}:${r.head}`)}&state=open`);if(o?.length){let l=o[0];return{number:l.number,url:l.html_url,state:l.state,merged:l.merged??!1,headSha:l.head.sha,mergeableState:null,baseRef:l.base?.ref??""}}throw new Error(`GitHub refused the PR (422): ${i?.message??"validation failed"}`)}return{number:i.number,url:i.html_url,state:i.state,merged:i.merged??!1,headSha:i.head.sha,mergeableState:null,baseRef:r.base}}async getReviews(e,t,r){let{data:s}=await this.request("GET",`/repos/${e}/${t}/pulls/${r}/reviews?per_page=100`);return(s??[]).map(i=>({state:i.state??"",commitId:i.commit_id??"",user:i.user?.login??"",submittedAt:i.submitted_at??""}))}async getPullRequest(e,t,r){try{let{data:s}=await this.request("GET",`/repos/${e}/${t}/pulls/${r}`);return{number:s.number,url:s.html_url,state:s.state,merged:s.merged,headSha:s.head.sha,mergeableState:s.mergeable_state??null,baseRef:s.base?.ref??""}}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return null;throw s}}async mergePullRequest(e,t,r,s,i={}){try{return await this.request("PUT",`/repos/${e}/${t}/pulls/${r}/merge`,{merge_method:s,...i.sha?{sha:i.sha}:{},...i.title?{commit_title:i.title}:{}}),{merged:!0}}catch(o){let l=o instanceof Error?o.message:String(o);return l.includes("-> 405")?{merged:!1,reason:`GitHub refused the merge: the branch is not in a mergeable state, or this repository does not allow "${s}" merges. Check the PR for conflicts or required checks, then merge it there.`}:l.includes("-> 409")?{merged:!1,reason:"the branch moved since it was reviewed, so GitHub refused to merge the commit that was approved. Re-review the PR and approve again."}:l.includes("-> 403")?{merged:!1,reason:`this runner's GitHub token is not allowed to merge in ${e}/${t}. It needs write access to the repository - or merge the PR yourself.`}:{merged:!1,reason:l}}}async repoAccess(e,t){try{let{data:r}=await this.request("GET",`/repos/${e}/${t}`);return{ok:!0,canPush:!!(r.permissions?.push||r.permissions?.admin)}}catch(r){let s=r instanceof Error?r.message:String(r);return{ok:!1,canPush:!1,error:s.includes("-> 404")?"not found (private repo this token cannot see, or the name is wrong)":s.slice(0,200)}}}async closePullRequest(e,t,r){await this.request("PATCH",`/repos/${e}/${t}/pulls/${r}`,{state:"closed"})}async deleteBranch(e,t,r){try{await this.request("DELETE",`/repos/${e}/${t}/git/refs/heads/${encodeURIComponent(r)}`)}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return;throw s}}}});var Nt=ne((L_,_d)=>{"use strict";var bd=["nodebuffer","arraybuffer","fragments"],wd=typeof Blob<"u";wd&&bd.push("blob");_d.exports={BINARY_TYPES:bd,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:wd,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var xs=ne((U_,Mi)=>{"use strict";var{EMPTY_BUFFER:ly}=Nt(),$a=Buffer[Symbol.species];function uy(n,e){if(n.length===0)return ly;if(n.length===1)return n[0];let t=Buffer.allocUnsafe(e),r=0;for(let s=0;s<n.length;s++){let i=n[s];t.set(i,r),r+=i.length}return r<e?new $a(t.buffer,t.byteOffset,r):t}function kd(n,e,t,r,s){for(let i=0;i<s;i++)t[r+i]=n[i]^e[i&3]}function Sd(n,e){for(let t=0;t<n.length;t++)n[t]^=e[t&3]}function cy(n){return n.length===n.buffer.byteLength?n.buffer:n.buffer.slice(n.byteOffset,n.byteOffset+n.length)}function Pa(n){if(Pa.readOnly=!0,Buffer.isBuffer(n))return n;let e;return n instanceof ArrayBuffer?e=new $a(n):ArrayBuffer.isView(n)?e=new $a(n.buffer,n.byteOffset,n.byteLength):(e=Buffer.from(n),Pa.readOnly=!1),e}Mi.exports={concat:uy,mask:kd,toArrayBuffer:cy,toBuffer:Pa,unmask:Sd};if(!process.env.WS_NO_BUFFER_UTIL)try{let n=require("bufferutil");Mi.exports.mask=function(e,t,r,s,i){i<48?kd(e,t,r,s,i):n.mask(e,t,r,s,i)},Mi.exports.unmask=function(e,t){e.length<32?Sd(e,t):n.unmask(e,t)}}catch{}});var Cd=ne((q_,xd)=>{"use strict";var Td=Symbol("kDone"),ja=Symbol("kRun"),Oa=class{constructor(e){this[Td]=()=>{this.pending--,this[ja]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[ja]()}[ja](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Td])}}};xd.exports=Oa});var Jr=ne((F_,Ad)=>{"use strict";var Cs=require("zlib"),Id=xs(),dy=Cd(),{kStatusCode:Rd}=Nt(),hy=Buffer[Symbol.species],fy=Buffer.from([0,0,255,255]),Di=Symbol("permessage-deflate"),Mt=Symbol("total-length"),Vr=Symbol("callback"),an=Symbol("buffers"),Wr=Symbol("error"),zi,Na=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!zi){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;zi=new dy(t)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Vr];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,r=e.find(s=>!(t.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>s.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(r.server_no_context_takeover=!0),t.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(r.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?r.client_max_window_bits=t.clientMaxWindowBits:(r.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(r=>{let s=t[r];if(s.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(s=s[0],r==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else if(r==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else throw new Error(`Unknown parameter "${r}"`);t[r]=s})}),e}decompress(e,t,r){zi.add(s=>{this._decompress(e,t,(i,o)=>{s(),r(i,o)})})}compress(e,t,r){zi.add(s=>{this._compress(e,t,(i,o)=>{s(),r(i,o)})})}_decompress(e,t,r){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Cs.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Cs.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Di]=this,this._inflate[Mt]=0,this._inflate[an]=[],this._inflate.on("error",my),this._inflate.on("data",Ed)}this._inflate[Vr]=r,this._inflate.write(e),t&&this._inflate.write(fy),this._inflate.flush(()=>{let i=this._inflate[Wr];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=Id.concat(this._inflate[an],this._inflate[Mt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Mt]=0,this._inflate[an]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,t,r){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Cs.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Cs.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[Mt]=0,this._deflate[an]=[],this._deflate.on("data",py)}this._deflate[Vr]=r,this._deflate.write(e),this._deflate.flush(Cs.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Id.concat(this._deflate[an],this._deflate[Mt]);t&&(i=new hy(i.buffer,i.byteOffset,i.length-4)),this._deflate[Vr]=null,this._deflate[Mt]=0,this._deflate[an]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};Ad.exports=Na;function py(n){this[an].push(n),this[Mt]+=n.length}function Ed(n){if(this[Mt]+=n.length,this[Di]._maxPayload<1||this[Mt]<=this[Di]._maxPayload){this[an].push(n);return}this[Wr]=new RangeError("Max payload size exceeded"),this[Wr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Wr][Rd]=1009,this.removeListener("data",Ed),this.reset()}function my(n){if(this[Di]._inflate=null,this[Wr]){this[Vr](this[Wr]);return}n[Rd]=1007,this[Vr](n)}});var Yr=ne((B_,Li)=>{"use strict";var{isUtf8:$d}=require("buffer"),{hasBlob:gy}=Nt(),yy=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function vy(n){return n>=1e3&&n<=1014&&n!==1004&&n!==1005&&n!==1006||n>=3e3&&n<=4999}function Ma(n){let e=n.length,t=0;for(;t<e;)if((n[t]&128)===0)t++;else if((n[t]&224)===192){if(t+1===e||(n[t+1]&192)!==128||(n[t]&254)===192)return!1;t+=2}else if((n[t]&240)===224){if(t+2>=e||(n[t+1]&192)!==128||(n[t+2]&192)!==128||n[t]===224&&(n[t+1]&224)===128||n[t]===237&&(n[t+1]&224)===160)return!1;t+=3}else if((n[t]&248)===240){if(t+3>=e||(n[t+1]&192)!==128||(n[t+2]&192)!==128||(n[t+3]&192)!==128||n[t]===240&&(n[t+1]&240)===128||n[t]===244&&n[t+1]>143||n[t]>244)return!1;t+=4}else return!1;return!0}function by(n){return gy&&typeof n=="object"&&typeof n.arrayBuffer=="function"&&typeof n.type=="string"&&typeof n.stream=="function"&&(n[Symbol.toStringTag]==="Blob"||n[Symbol.toStringTag]==="File")}Li.exports={isBlob:by,isValidStatusCode:vy,isValidUTF8:Ma,tokenChars:yy};if($d)Li.exports.isValidUTF8=function(n){return n.length<24?Ma(n):$d(n)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let n=require("utf-8-validate");Li.exports.isValidUTF8=function(e){return e.length<32?Ma(e):n(e)}}catch{}});var qa=ne((K_,Dd)=>{"use strict";var{Writable:wy}=require("stream"),Pd=Jr(),{BINARY_TYPES:_y,EMPTY_BUFFER:jd,kStatusCode:ky,kWebSocket:Sy}=Nt(),{concat:za,toArrayBuffer:Ty,unmask:xy}=xs(),{isValidStatusCode:Cy,isValidUTF8:Od}=Yr(),Ui=Buffer[Symbol.species],We=0,Nd=1,Md=2,zd=3,Da=4,La=5,qi=6,Ua=class extends wy{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||_y[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Sy]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=We}_write(e,t,r){if(this._opcode===8&&this._state==We)return r();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){r(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new Ui(r.buffer,r.byteOffset+e,r.length-e),new Ui(r.buffer,r.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let r=this._buffers[0],s=t.length-e;e>=r.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new Ui(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case We:this.getInfo(e);break;case Nd:this.getPayloadLength16(e);break;case Md:this.getPayloadLength64(e);break;case zd:this.getMask();break;case Da:this.getData(e);break;case La:case qi:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((t[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let r=(t[0]&64)===64;if(r&&!this._extensions[Pd.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=Nd:this._payloadLength===127?this._state=Md:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),r=t.readUInt32BE(0);if(r>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=r*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=zd:this._state=Da}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Da}getData(e){let t=jd;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&xy(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let r=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(r);return}if(this._compressed){this._state=La,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Pd.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return t(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(o);return}this._fragments.push(i)}this.dataMessage(t),this._state===We&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=We;return}let t=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=za(r,t):this._binaryType==="arraybuffer"?s=Ty(za(r,t)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=We):(this._state=qi,setImmediate(()=>{this.emit("message",s,!0),this._state=We,this.startLoop(e)}))}else{let s=za(r,t);if(!this._skipUTF8Validation&&!Od(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===La||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=We):(this._state=qi,setImmediate(()=>{this.emit("message",s,!1),this._state=We,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,jd),this.end();else{let r=e.readUInt16BE(0);if(!Cy(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new Ui(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Od(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(i);return}this._loop=!1,this.emit("conclude",r,s),this.end()}this._state=We;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=We):(this._state=qi,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=We,this.startLoop(t)}))}createError(e,t,r,s,i){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[ky]=s,o}};Dd.exports=Ua});var Ka=ne((G_,qd)=>{"use strict";var{Duplex:Z_}=require("stream"),{randomFillSync:Iy}=require("crypto"),{types:{isUint8Array:Ry}}=require("util"),Ld=Jr(),{EMPTY_BUFFER:Ey,kWebSocket:Ay,NOOP:$y}=Nt(),{isBlob:Xr,isValidStatusCode:Py}=Yr(),{mask:Ud,toBuffer:cr}=xs(),Je=Symbol("kByteLength"),jy=Buffer.alloc(4),Fi=8*1024,dr,Qr=Fi,it=0,Oy=1,Ny=2,Fa=class n{constructor(e,t,r){this._extensions=t||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=it,this.onerror=$y,this[Ay]=void 0}static frame(e,t){let r,s=!1,i=2,o=!1;t.mask&&(r=t.maskBuffer||jy,t.generateMask?t.generateMask(r):(Qr===Fi&&(dr===void 0&&(dr=Buffer.alloc(Fi)),Iy(dr,0,Fi),Qr=0),r[0]=dr[Qr++],r[1]=dr[Qr++],r[2]=dr[Qr++],r[3]=dr[Qr++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let l;typeof e=="string"?(!t.mask||o)&&t[Je]!==void 0?l=t[Je]:(e=Buffer.from(e),l=e.length):(l=e.length,s=t.mask&&t.readOnly&&!o);let u=l;l>=65536?(i+=8,u=127):l>125&&(i+=2,u=126);let c=Buffer.allocUnsafe(s?l+i:i);return c[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(c[0]|=64),c[1]=u,u===126?c.writeUInt16BE(l,2):u===127&&(c[2]=c[3]=0,c.writeUIntBE(l,4,6)),t.mask?(c[1]|=128,c[i-4]=r[0],c[i-3]=r[1],c[i-2]=r[2],c[i-1]=r[3],o?[c,e]:s?(Ud(e,r,c,i,l),[c]):(Ud(e,r,e,0,l),[c,e])):[c,e]}close(e,t,r,s){let i;if(e===void 0)i=Ey;else{if(typeof e!="number"||!Py(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let l=Buffer.byteLength(t);if(l>123)throw new RangeError("The message must not be greater than 123 bytes");if(i=Buffer.allocUnsafe(2+l),i.writeUInt16BE(e,0),typeof t=="string")i.write(t,2);else if(Ry(t))i.set(t,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[Je]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==it?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(n.frame(i,o),s)}ping(e,t,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):Xr(e)?(s=e.size,i=!1):(e=cr(e),s=e.length,i=cr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Je]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Xr(e)?this._state!==it?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==it?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(n.frame(e,o),r)}pong(e,t,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):Xr(e)?(s=e.size,i=!1):(e=cr(e),s=e.length,i=cr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Je]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Xr(e)?this._state!==it?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==it?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(n.frame(e,o),r)}send(e,t,r){let s=this._extensions[Ld.extensionName],i=t.binary?2:1,o=t.compress,l,u;typeof e=="string"?(l=Buffer.byteLength(e),u=!1):Xr(e)?(l=e.size,u=!1):(e=cr(e),l=e.length,u=cr.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=l>=s._threshold),this._compress=o):(o=!1,i=0),t.fin&&(this._firstFragment=!0);let c={[Je]:l,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:u,rsv1:o};Xr(e)?this._state!==it?this.enqueue([this.getBlobData,e,this._compress,c,r]):this.getBlobData(e,this._compress,c,r):this._state!==it?this.enqueue([this.dispatch,e,this._compress,c,r]):this.dispatch(e,this._compress,c,r)}getBlobData(e,t,r,s){this._bufferedBytes+=r[Je],this._state=Ny,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let l=new Error("The socket was closed while the blob was being read");process.nextTick(Ba,this,l,s);return}this._bufferedBytes-=r[Je];let o=cr(i);t?this.dispatch(o,t,r,s):(this._state=it,this.sendFrame(n.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(My,this,i,s)})}dispatch(e,t,r,s){if(!t){this.sendFrame(n.frame(e,r),s);return}let i=this._extensions[Ld.extensionName];this._bufferedBytes+=r[Je],this._state=Oy,i.compress(e,r.fin,(o,l)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");Ba(this,u,s);return}this._bufferedBytes-=r[Je],this._state=it,r.readOnly=!1,this.sendFrame(n.frame(l,r),s),this.dequeue()})}dequeue(){for(;this._state===it&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Je],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Je],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};qd.exports=Fa;function Ba(n,e,t){typeof t=="function"&&t(e);for(let r=0;r<n._queue.length;r++){let s=n._queue[r],i=s[s.length-1];typeof i=="function"&&i(e)}}function My(n,e,t){Ba(n,e,t),n.onerror(e)}});var Jd=ne((H_,Wd)=>{"use strict";var{kForOnEventAttribute:Is,kListener:Za}=Nt(),Fd=Symbol("kCode"),Bd=Symbol("kData"),Kd=Symbol("kError"),Zd=Symbol("kMessage"),Gd=Symbol("kReason"),es=Symbol("kTarget"),Hd=Symbol("kType"),Vd=Symbol("kWasClean"),zt=class{constructor(e){this[es]=null,this[Hd]=e}get target(){return this[es]}get type(){return this[Hd]}};Object.defineProperty(zt.prototype,"target",{enumerable:!0});Object.defineProperty(zt.prototype,"type",{enumerable:!0});var hr=class extends zt{constructor(e,t={}){super(e),this[Fd]=t.code===void 0?0:t.code,this[Gd]=t.reason===void 0?"":t.reason,this[Vd]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Fd]}get reason(){return this[Gd]}get wasClean(){return this[Vd]}};Object.defineProperty(hr.prototype,"code",{enumerable:!0});Object.defineProperty(hr.prototype,"reason",{enumerable:!0});Object.defineProperty(hr.prototype,"wasClean",{enumerable:!0});var ts=class extends zt{constructor(e,t={}){super(e),this[Kd]=t.error===void 0?null:t.error,this[Zd]=t.message===void 0?"":t.message}get error(){return this[Kd]}get message(){return this[Zd]}};Object.defineProperty(ts.prototype,"error",{enumerable:!0});Object.defineProperty(ts.prototype,"message",{enumerable:!0});var Rs=class extends zt{constructor(e,t={}){super(e),this[Bd]=t.data===void 0?null:t.data}get data(){return this[Bd]}};Object.defineProperty(Rs.prototype,"data",{enumerable:!0});var zy={addEventListener(n,e,t={}){for(let s of this.listeners(n))if(!t[Is]&&s[Za]===e&&!s[Is])return;let r;if(n==="message")r=function(i,o){let l=new Rs("message",{data:o?i:i.toString()});l[es]=this,Bi(e,this,l)};else if(n==="close")r=function(i,o){let l=new hr("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});l[es]=this,Bi(e,this,l)};else if(n==="error")r=function(i){let o=new ts("error",{error:i,message:i.message});o[es]=this,Bi(e,this,o)};else if(n==="open")r=function(){let i=new zt("open");i[es]=this,Bi(e,this,i)};else return;r[Is]=!!t[Is],r[Za]=e,t.once?this.once(n,r):this.on(n,r)},removeEventListener(n,e){for(let t of this.listeners(n))if(t[Za]===e&&!t[Is]){this.removeListener(n,t);break}}};Wd.exports={CloseEvent:hr,ErrorEvent:ts,Event:zt,EventTarget:zy,MessageEvent:Rs};function Bi(n,e,t){typeof n=="object"&&n.handleEvent?n.handleEvent.call(n,t):n.call(e,t)}});var Ki=ne((V_,Yd)=>{"use strict";var{tokenChars:Es}=Yr();function bt(n,e,t){n[e]===void 0?n[e]=[t]:n[e].push(t)}function Dy(n){let e=Object.create(null),t=Object.create(null),r=!1,s=!1,i=!1,o,l,u=-1,c=-1,f=-1,p=0;for(;p<n.length;p++)if(c=n.charCodeAt(p),o===void 0)if(f===-1&&Es[c]===1)u===-1&&(u=p);else if(p!==0&&(c===32||c===9))f===-1&&u!==-1&&(f=p);else if(c===59||c===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let w=n.slice(u,f);c===44?(bt(e,w,t),t=Object.create(null)):o=w,u=f=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(l===void 0)if(f===-1&&Es[c]===1)u===-1&&(u=p);else if(c===32||c===9)f===-1&&u!==-1&&(f=p);else if(c===59||c===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),bt(t,n.slice(u,f),!0),c===44&&(bt(e,o,t),t=Object.create(null),o=void 0),u=f=-1}else if(c===61&&u!==-1&&f===-1)l=n.slice(u,p),u=f=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(s){if(Es[c]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:r||(r=!0),s=!1}else if(i)if(Es[c]===1)u===-1&&(u=p);else if(c===34&&u!==-1)i=!1,f=p;else if(c===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(c===34&&n.charCodeAt(p-1)===61)i=!0;else if(f===-1&&Es[c]===1)u===-1&&(u=p);else if(u!==-1&&(c===32||c===9))f===-1&&(f=p);else if(c===59||c===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let w=n.slice(u,f);r&&(w=w.replace(/\\/g,""),r=!1),bt(t,l,w),c===44&&(bt(e,o,t),t=Object.create(null),o=void 0),l=void 0,u=f=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(u===-1||i||c===32||c===9)throw new SyntaxError("Unexpected end of input");f===-1&&(f=p);let b=n.slice(u,f);return o===void 0?bt(e,b,t):(l===void 0?bt(t,b,!0):r?bt(t,l,b.replace(/\\/g,"")):bt(t,l,b),bt(e,o,t)),e}function Ly(n){return Object.keys(n).map(e=>{let t=n[e];return Array.isArray(t)||(t=[t]),t.map(r=>[e].concat(Object.keys(r).map(s=>{let i=r[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Yd.exports={format:Ly,parse:Dy}});var Vi=ne((Y_,uh)=>{"use strict";var Uy=require("events"),qy=require("https"),Fy=require("http"),eh=require("net"),By=require("tls"),{randomBytes:Ky,createHash:Zy}=require("crypto"),{Duplex:W_,Readable:J_}=require("stream"),{URL:Ga}=require("url"),ln=Jr(),Gy=qa(),Hy=Ka(),{isBlob:Vy}=Yr(),{BINARY_TYPES:Xd,CLOSE_TIMEOUT:Wy,EMPTY_BUFFER:Zi,GUID:Jy,kForOnEventAttribute:Ha,kListener:Yy,kStatusCode:Xy,kWebSocket:ye,NOOP:th}=Nt(),{EventTarget:{addEventListener:Qy,removeEventListener:ev}}=Jd(),{format:tv,parse:nv}=Ki(),{toBuffer:rv}=xs(),nh=Symbol("kAborted"),Va=[8,13],Dt=["CONNECTING","OPEN","CLOSING","CLOSED"],sv=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,de=class n extends Uy{constructor(e,t,r){super(),this._binaryType=Xd[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Zi,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=n.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(r=t,t=[]):t=[t]),rh(this,e,t,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Xd.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,r){let s=new Gy({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new Hy(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[ye]=this,i[ye]=this,e[ye]=this,s.on("conclude",av),s.on("drain",lv),s.on("error",uv),s.on("message",cv),s.on("ping",dv),s.on("pong",hv),i.onerror=fv,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",oh),e.on("data",Hi),e.on("end",ah),e.on("error",lh),this._readyState=n.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[ln.extensionName]&&this._extensions[ln.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){De(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===n.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=n.CLOSING,this._sender.close(e,t,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),ih(this)}}pause(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,r){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=t=void 0):typeof t=="function"&&(r=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){Wa(this,e,r);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Zi,t,r)}pong(e,t,r){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=t=void 0):typeof t=="function"&&(r=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){Wa(this,e,r);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Zi,t,r)}resume(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,r){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(r=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){Wa(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[ln.extensionName]||(s.compress=!1),this._sender.send(e||Zi,s,r)}terminate(){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){De(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=n.CLOSING,this._socket.destroy())}}};Object.defineProperty(de,"CONNECTING",{enumerable:!0,value:Dt.indexOf("CONNECTING")});Object.defineProperty(de.prototype,"CONNECTING",{enumerable:!0,value:Dt.indexOf("CONNECTING")});Object.defineProperty(de,"OPEN",{enumerable:!0,value:Dt.indexOf("OPEN")});Object.defineProperty(de.prototype,"OPEN",{enumerable:!0,value:Dt.indexOf("OPEN")});Object.defineProperty(de,"CLOSING",{enumerable:!0,value:Dt.indexOf("CLOSING")});Object.defineProperty(de.prototype,"CLOSING",{enumerable:!0,value:Dt.indexOf("CLOSING")});Object.defineProperty(de,"CLOSED",{enumerable:!0,value:Dt.indexOf("CLOSED")});Object.defineProperty(de.prototype,"CLOSED",{enumerable:!0,value:Dt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(n=>{Object.defineProperty(de.prototype,n,{enumerable:!0})});["open","error","close","message"].forEach(n=>{Object.defineProperty(de.prototype,`on${n}`,{enumerable:!0,get(){for(let e of this.listeners(n))if(e[Ha])return e[Yy];return null},set(e){for(let t of this.listeners(n))if(t[Ha]){this.removeListener(n,t);break}typeof e=="function"&&this.addEventListener(n,e,{[Ha]:!0})}})});de.prototype.addEventListener=Qy;de.prototype.removeEventListener=ev;uh.exports=de;function rh(n,e,t,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Wy,protocolVersion:Va[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(n._autoPong=s.autoPong,n._closeTimeout=s.closeTimeout,!Va.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Va.join(", ")})`);let i;if(e instanceof Ga)i=e;else try{i=new Ga(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),n._url=i.href;let o=i.protocol==="wss:",l=i.protocol==="ws+unix:",u;if(i.protocol!=="ws:"&&!o&&!l?u=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:l&&!i.pathname?u="The URL's pathname is empty":i.hash&&(u="The URL contains a fragment identifier"),u){let x=new SyntaxError(u);if(n._redirects===0)throw x;Gi(n,x);return}let c=o?443:80,f=Ky(16).toString("base64"),p=o?qy.request:Fy.request,b=new Set,w;if(s.createConnection=s.createConnection||(o?ov:iv),s.defaultPort=s.defaultPort||c,s.port=i.port||c,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":f,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(w=new ln({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=tv({[ln.extensionName]:w.offer()})),t.length){for(let x of t){if(typeof x!="string"||!sv.test(x)||b.has(x))throw new SyntaxError("An invalid or duplicated subprotocol was specified");b.add(x)}s.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),l){let x=s.path.split(":");s.socketPath=x[0],s.path=x[1]}let T;if(s.followRedirects){if(n._redirects===0){n._originalIpc=l,n._originalSecure=o,n._originalHostOrSocketPath=l?s.socketPath:i.host;let x=r&&r.headers;if(r={...r,headers:{}},x)for(let[A,v]of Object.entries(x))r.headers[A.toLowerCase()]=v}else if(n.listenerCount("redirect")===0){let x=l?n._originalIpc?s.socketPath===n._originalHostOrSocketPath:!1:n._originalIpc?!1:i.host===n._originalHostOrSocketPath;(!x||n._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,x||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),T=n._req=p(s),n._redirects&&n.emit("redirect",n.url,T)}else T=n._req=p(s);s.timeout&&T.on("timeout",()=>{De(n,T,"Opening handshake has timed out")}),T.on("error",x=>{T===null||T[nh]||(T=n._req=null,Gi(n,x))}),T.on("response",x=>{let A=x.headers.location,v=x.statusCode;if(A&&s.followRedirects&&v>=300&&v<400){if(++n._redirects>s.maxRedirects){De(n,T,"Maximum redirects exceeded");return}T.abort();let Z;try{Z=new Ga(A,e)}catch{let L=new SyntaxError(`Invalid URL: ${A}`);Gi(n,L);return}rh(n,Z,t,r)}else n.emit("unexpected-response",T,x)||De(n,T,`Unexpected server response: ${x.statusCode}`)}),T.on("upgrade",(x,A,v)=>{if(n.emit("upgrade",x),n.readyState!==de.CONNECTING)return;T=n._req=null;let Z=x.headers.upgrade;if(Z===void 0||Z.toLowerCase()!=="websocket"){De(n,A,"Invalid Upgrade header");return}let M=Zy("sha1").update(f+Jy).digest("base64");if(x.headers["sec-websocket-accept"]!==M){De(n,A,"Invalid Sec-WebSocket-Accept header");return}let L=x.headers["sec-websocket-protocol"],z;if(L!==void 0?b.size?b.has(L)||(z="Server sent an invalid subprotocol"):z="Server sent a subprotocol but none was requested":b.size&&(z="Server sent no subprotocol"),z){De(n,A,z);return}L&&(n._protocol=L);let h=x.headers["sec-websocket-extensions"];if(h!==void 0){if(!w){De(n,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let m;try{m=nv(h)}catch{De(n,A,"Invalid Sec-WebSocket-Extensions header");return}let g=Object.keys(m);if(g.length!==1||g[0]!==ln.extensionName){De(n,A,"Server indicated an extension that was not requested");return}try{w.accept(m[ln.extensionName])}catch{De(n,A,"Invalid Sec-WebSocket-Extensions header");return}n._extensions[ln.extensionName]=w}n.setSocket(A,v,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(T,n):T.end()}function Gi(n,e){n._readyState=de.CLOSING,n._errorEmitted=!0,n.emit("error",e),n.emitClose()}function iv(n){return n.path=n.socketPath,eh.connect(n)}function ov(n){return n.path=void 0,!n.servername&&n.servername!==""&&(n.servername=eh.isIP(n.host)?"":n.host),By.connect(n)}function De(n,e,t){n._readyState=de.CLOSING;let r=new Error(t);Error.captureStackTrace(r,De),e.setHeader?(e[nh]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Gi,n,r)):(e.destroy(r),e.once("error",n.emit.bind(n,"error")),e.once("close",n.emitClose.bind(n)))}function Wa(n,e,t){if(e){let r=Vy(e)?e.size:rv(e).length;n._socket?n._sender._bufferedBytes+=r:n._bufferedAmount+=r}if(t){let r=new Error(`WebSocket is not open: readyState ${n.readyState} (${Dt[n.readyState]})`);process.nextTick(t,r)}}function av(n,e){let t=this[ye];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=n,t._socket[ye]!==void 0&&(t._socket.removeListener("data",Hi),process.nextTick(sh,t._socket),n===1005?t.close():t.close(n,e))}function lv(){let n=this[ye];n.isPaused||n._socket.resume()}function uv(n){let e=this[ye];e._socket[ye]!==void 0&&(e._socket.removeListener("data",Hi),process.nextTick(sh,e._socket),e.close(n[Xy])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n))}function Qd(){this[ye].emitClose()}function cv(n,e){this[ye].emit("message",n,e)}function dv(n){let e=this[ye];e._autoPong&&e.pong(n,!this._isServer,th),e.emit("ping",n)}function hv(n){this[ye].emit("pong",n)}function sh(n){n.resume()}function fv(n){let e=this[ye];e.readyState!==de.CLOSED&&(e.readyState===de.OPEN&&(e._readyState=de.CLOSING,ih(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n)))}function ih(n){n._closeTimer=setTimeout(n._socket.destroy.bind(n._socket),n._closeTimeout)}function oh(){let n=this[ye];if(this.removeListener("close",oh),this.removeListener("data",Hi),this.removeListener("end",ah),n._readyState=de.CLOSING,!this._readableState.endEmitted&&!n._closeFrameReceived&&!n._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);n._receiver.write(e)}n._receiver.end(),this[ye]=void 0,clearTimeout(n._closeTimer),n._receiver._writableState.finished||n._receiver._writableState.errorEmitted?n.emitClose():(n._receiver.on("error",Qd),n._receiver.on("finish",Qd))}function Hi(n){this[ye]._receiver.write(n)||this.pause()}function ah(){let n=this[ye];n._readyState=de.CLOSING,n._receiver.end(),this.end()}function lh(){let n=this[ye];this.removeListener("error",lh),this.on("error",th),n&&(n._readyState=de.CLOSING,this.destroy())}});var fh=ne((Q_,hh)=>{"use strict";var X_=Vi(),{Duplex:pv}=require("stream");function ch(n){n.emit("close")}function mv(){!this.destroyed&&this._writableState.finished&&this.destroy()}function dh(n){this.removeListener("error",dh),this.destroy(),this.listenerCount("error")===0&&this.emit("error",n)}function gv(n,e){let t=!0,r=new pv({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return n.on("message",function(i,o){let l=!o&&r._readableState.objectMode?i.toString():i;r.push(l)||n.pause()}),n.once("error",function(i){r.destroyed||(t=!1,r.destroy(i))}),n.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(s,i){if(n.readyState===n.CLOSED){i(s),process.nextTick(ch,r);return}let o=!1;n.once("error",function(u){o=!0,i(u)}),n.once("close",function(){o||i(s),process.nextTick(ch,r)}),t&&n.terminate()},r._final=function(s){if(n.readyState===n.CONNECTING){n.once("open",function(){r._final(s)});return}n._socket!==null&&(n._socket._writableState.finished?(s(),r._readableState.endEmitted&&r.destroy()):(n._socket.once("finish",function(){s()}),n.close()))},r._read=function(){n.isPaused&&n.resume()},r._write=function(s,i,o){if(n.readyState===n.CONNECTING){n.once("open",function(){r._write(s,i,o)});return}n.send(s,o)},r.on("end",mv),r.on("error",dh),r}hh.exports=gv});var Ja=ne((ek,ph)=>{"use strict";var{tokenChars:yv}=Yr();function vv(n){let e=new Set,t=-1,r=-1,s=0;for(s;s<n.length;s++){let o=n.charCodeAt(s);if(r===-1&&yv[o]===1)t===-1&&(t=s);else if(s!==0&&(o===32||o===9))r===-1&&t!==-1&&(r=s);else if(o===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${s}`);r===-1&&(r=s);let l=n.slice(t,r);if(e.has(l))throw new SyntaxError(`The "${l}" subprotocol is duplicated`);e.add(l),t=r=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(t===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let i=n.slice(t,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}ph.exports={parse:vv}});var _h=ne((nk,wh)=>{"use strict";var bv=require("events"),Wi=require("http"),{Duplex:tk}=require("stream"),{createHash:wv}=require("crypto"),mh=Ki(),fr=Jr(),_v=Ja(),kv=Vi(),{CLOSE_TIMEOUT:Sv,GUID:Tv,kWebSocket:xv}=Nt(),Cv=/^[+/0-9A-Za-z]{22}==$/,gh=0,yh=1,bh=2,Ya=class extends bv{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Sv,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:kv,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Wi.createServer((r,s)=>{let i=Wi.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=Iv(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=gh}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===bh){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(As,this);return}if(e&&this.once("close",e),this._state!==yh)if(this._state=yh,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(As,this):process.nextTick(As,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{As(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,r,s){t.on("error",vh);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,l=+e.headers["sec-websocket-version"];if(e.method!=="GET"){pr(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){pr(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!Cv.test(i)){pr(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(l!==13&&l!==8){pr(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){$s(t,400);return}let u=e.headers["sec-websocket-protocol"],c=new Set;if(u!==void 0)try{c=_v.parse(u)}catch{pr(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let f=e.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&f!==void 0){let b=new fr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let w=mh.parse(f);w[fr.extensionName]&&(b.accept(w[fr.extensionName]),p[fr.extensionName]=b)}catch{pr(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let b={origin:e.headers[`${l===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(b,(w,T,x,A)=>{if(!w)return $s(t,T||401,x,A);this.completeUpgrade(p,i,c,e,t,r,s)});return}if(!this.options.verifyClient(b))return $s(t,401)}this.completeUpgrade(p,i,c,e,t,r,s)}completeUpgrade(e,t,r,s,i,o,l){if(!i.readable||!i.writable)return i.destroy();if(i[xv])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>gh)return $s(i,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${wv("sha1").update(t+Tv).digest("base64")}`],f=new this.options.WebSocket(null,void 0,this.options);if(r.size){let p=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;p&&(c.push(`Sec-WebSocket-Protocol: ${p}`),f._protocol=p)}if(e[fr.extensionName]){let p=e[fr.extensionName].params,b=mh.format({[fr.extensionName]:[p]});c.push(`Sec-WebSocket-Extensions: ${b}`),f._extensions=e}this.emit("headers",c,s),i.write(c.concat(`\r
249
+ ${i}${o}`:"clean"}`}function Nt(){let n=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(me.default.existsSync(ue.default.join(Vn.default.homedir(),".cache","ticketpilot"))?ue.default.join(Vn.default.homedir(),".cache","ticketpilot"):ue.default.join(Vn.default.homedir(),".cache","allwright"));return ue.default.join(n,"worktrees")}async function sn(n,e){try{await U(n,["fetch","origin",e])}catch(t){throw new Error(`could not fetch base branch "${e}" from origin - check the rule's base branch and that this machine can reach the remote (${t instanceof Error?t.message:t})`)}}async function qo(n,e){try{let t=await U(n,["worktree","list","--porcelain"]),r=Nt(),s=null;for(let i of t.split(`
250
+ `))i.startsWith("worktree ")&&(s=i.slice(9).trim()),i===`branch refs/heads/${e}`&&s&&s.startsWith(r)&&await U(n,["worktree","remove","--force",s]);await U(n,["worktree","prune"])}catch{}try{await U(n,["branch","-D",e])}catch{}}async function Fo(n,e,t,r){me.default.mkdirSync(ue.default.dirname(e),{recursive:!0,mode:448}),await U(n,["worktree","add","-b",t,e,`origin/${r}`])}async function Wn(n,e){if(await U(n,["add","-A"]),!(await U(n,["status","--porcelain"])).trim())throw new Error("Claude wrote no changes - nothing to commit");await U(n,["-c",`user.name=${fi}`,"-c",`user.email=${pi}`,"commit","-m",e])}async function on(n,e){let r=(await U(n,["diff","--name-only",`origin/${e}...HEAD`])).split(`
251
+ `).filter(Boolean),s=r.filter(c=>Iu.some(f=>f.test(c))),i=await U(n,["diff","--shortstat",`origin/${e}...HEAD`]),o=Number(/(\d+) insertion/.exec(i)?.[1]??0),l=Number(/(\d+) deletion/.exec(i)?.[1]??0);return{ok:s.length===0&&r.length<=nn&&o+l<=rn,files:r.length,insertions:o,deletions:l,forbidden:s}}async function Jn(n,e){await U(n,["fetch","--prune","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],{timeoutMs:12e4}).catch(()=>U(n,["update-ref","-d",`refs/remotes/origin/${e}`]).catch(()=>{})),await U(n,["push","--force-with-lease","-u","origin",e],{timeoutMs:3e5})}async function Je(n){return(await U(n,["rev-parse","HEAD"])).trim()}async function gi(n,e){try{return(await U(n,["rev-parse","--verify",`refs/heads/${e}`])).trim()}catch{return null}}async function qr(n,e){await U(n,["reset","--hard",e])}async function mt(n,e){try{await U(n,["worktree","remove","--force",e])}catch{me.default.rmSync(e,{recursive:!0,force:!0})}}async function Bo(n,e=[]){let t=new Set(e.map(s=>ue.default.basename(ue.default.resolve(s))).filter(s=>s.length>0)),r=Nt();if(me.default.existsSync(r))for(let s of me.default.readdirSync(r))t.has(s)||me.default.rmSync(ue.default.join(r,s),{recursive:!0,force:!0});for(let s of n)try{await U(s,["worktree","prune"])}catch{}}async function Ko(n,e){return await U(n,["fetch","origin","--prune"]).catch(()=>{}),(await U(n,["branch","-r","--list",`*${e}*`])).split(`
252
+ `).map(s=>s.trim()).filter(s=>s&&!s.includes("->"))[0]??null}async function yi(n,e,t=6e4){let s=(await U(n,["symbolic-ref","refs/remotes/origin/HEAD"]).catch(()=>"")).trim().replace("refs/remotes/","")||"origin/main",i=await U(n,["diff","--stat",`${s}...${e}`]),o=await U(n,["diff",`${s}...${e}`]);return{base:s,stat:i.slice(0,4e3),diff:o.slice(0,t)}}function Ru(){let n=process.env.ALLWRIGHT_CACHE_DIR??process.env.TICKETPILOT_CACHE_DIR??(me.default.existsSync(ue.default.join(Vn.default.homedir(),".cache","ticketpilot"))?ue.default.join(Vn.default.homedir(),".cache","ticketpilot"):ue.default.join(Vn.default.homedir(),".cache","allwright"));return ue.default.join(n,"env-checkouts")}function Su(n){return n.replace(/[^\w.-]+/g,"_")}function Eu(n,e){return ue.default.join(Ru(),Su(n),Su(e))}async function Zo(n){let e=Eu(n.repoName,n.envName);return await U(n.repoPath,["fetch","origin",n.branch],{timeoutMs:3e5}),me.default.existsSync(ue.default.join(e,".git"))?await U(e,["fetch","origin",n.branch],{timeoutMs:3e5}):(me.default.rmSync(e,{recursive:!0,force:!0}),me.default.mkdirSync(ue.default.dirname(e),{recursive:!0,mode:448}),await U(n.repoPath,["worktree","prune"]).catch(()=>{}),await U(n.repoPath,["worktree","add","--detach",e,`origin/${n.branch}`])),n.attached?await U(e,["checkout","-B",n.branch,`origin/${n.branch}`]):await U(e,["checkout","--force","--detach",`origin/${n.branch}`]),e}async function Go(n,e,t){try{await U(n,["fetch","origin",e],{timeoutMs:3e5})}catch{return{ok:!1,reason:`branch "${e}" does not exist on origin - nothing to promote. Check the environment's ticket branch template against the branch your implement rule creates.`}}try{return await U(n,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyMerged:!0}}catch{}try{return await U(n,["-c",`user.name=${fi}`,"-c",`user.email=${pi}`,"merge","--no-ff","-m",t,`origin/${e}`]),{ok:!0}}catch(r){return await U(n,["merge","--abort"]).catch(()=>{}),{ok:!1,reason:`could not merge "${e}" into the environment branch - ${r instanceof Error?r.message:r}. Resolve it manually and deploy again.`}}}async function Ho(n,e){await U(n,["fetch","origin",e],{timeoutMs:3e5});try{return await U(n,["merge-base","--is-ancestor",`origin/${e}`,"HEAD"]),{ok:!0,alreadyUpToDate:!0}}catch{}try{return await U(n,["-c",`user.name=${fi}`,"-c",`user.email=${pi}`,"merge","--no-edit",`origin/${e}`]),{ok:!0,alreadyUpToDate:!1}}catch(t){let s=(await U(n,["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
253
+ `).filter(Boolean);return s.length?{ok:!1,conflicts:s}:(await U(n,["merge","--abort"]).catch(()=>{}),{ok:!1,conflicts:null,reason:t instanceof Error?t.message.slice(0,300):String(t)})}}async function an(n){await U(n,["merge","--abort"]).catch(()=>{})}async function Vo(n,e){await U(n,["add","-A"]),await U(n,["-c",`user.name=${fi}`,"-c",`user.email=${pi}`,"commit","--no-edit","-m",e])}async function Wo(n,e){let t=new Set(await vi(n));return e.filter(r=>t.has(r))}async function vi(n){let e=new Set;try{let r=await U(n,["grep","-l","-I","-E","^(<{7}|>{7})( |$)"]);for(let s of r.split(`
254
+ `).filter(Boolean))e.add(s)}catch{}let t=[];try{t=(await U(n,["grep","-l","-I","-E","^={7}$"])).split(`
255
+ `).filter(Boolean).filter(s=>!e.has(s))}catch{}for(let r of t)try{let s=await U(n,["show",`HEAD:${r}`]);/^={7}$/m.test(s)||e.add(r)}catch{e.add(r)}return[...e]}async function _s(n,e,t){me.default.mkdirSync(ue.default.dirname(e),{recursive:!0,mode:448}),await U(n,["fetch","origin",t],{timeoutMs:3e5}),await U(n,["worktree","add","--detach",e,`origin/${t}`]),await U(e,["checkout","-B",t,`origin/${t}`])}async function Jo(n,e){try{await U(n,["push","origin",e],{timeoutMs:3e5})}catch(t){throw new Error(`could not push "${e}" - ${t instanceof Error?t.message:t}. Someone may have pushed to it since this deploy started; retry.`)}}async function Yo(n,e,t){try{return await Cu("git",["-C",n,"diff","--quiet",e,t,"--"],{timeout:12e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),!1}catch(r){let s=r;if(s.code===1)return!0;throw new Error(`git diff failed comparing ${e}..${t}: ${(s.stderr||s.message||"").trim().slice(0,500)}`)}}async function Yn(n){return(await U(n,["config","--get","remote.origin.url"])).trim()}function nt(n){let e=/^git@github\.com(?:-[\w.-]+)?:([^/]+)\/(.+?)(\.git)?$/.exec(n)??/^https:\/\/github\.com\/([^/]+)\/(.+?)(\.git)?\/?$/.exec(n)??/^ssh:\/\/git@github\.com(?:-[\w.-]+)?\/([^/]+)\/(.+?)(\.git)?$/.exec(n);return e?{owner:e[1],repo:e[2]}:null}var me,Vn,ue,Tu,xu,Cu,fi,pi,nn,rn,Iu,Ot,gt=qs(()=>{"use strict";me=R(require("node:fs"),1),Vn=R(require("node:os"),1),ue=R(require("node:path"),1),Tu=require("node:child_process"),xu=require("node:util"),Cu=(0,xu.promisify)(Tu.execFile),fi="Allwright Agent",pi="agent@ticketpilot.local",nn=200,rn=2e4,Iu=[/^\.github\/workflows\//,/^\.git\b/,/(^|\/)\.githooks\//];Ot=".ticketpilot-delete"});function bi(n,e,t){let r=(t??"").trim().toLowerCase(),s=r?n.githubUsers[r]?.token:void 0;if(s)return{token:s,source:"user"};let i=n.repos[e]?.github?.token;return i?{token:i,source:"repo"}:n.github?.token?{token:n.github.token,source:"global"}:null}function Te(n,e){return n.repos[e]?.github?.token??n.github?.token??null}function Ou(n,e){let t=[n.jira,...Object.values(n.repos).map(l=>l.jira)].filter(l=>!!l),r=new Set(t.map(l=>l.email.toLowerCase())),s=!!n.github?.token||Object.values(n.repos).some(l=>l.github?.token),i=n.github?.login??Object.values(n.repos).find(l=>l.github?.login)?.github?.login??"",o=e.map(l=>{let u=l.trim().toLowerCase(),c=n.jiraUsers[u]?"own":r.has(u)?"runner-account":"missing",f=c==="own"?n.jiraUsers[u].email:c==="runner-account"?u:"",p=n.githubUsers[u]?"own":s?"shared":"missing",b=p==="own"?n.githubUsers[u].login??"":p==="shared"?i:"";return{email:u,jira:c,jiraAs:f,github:p,githubAs:b}});return{githubShared:s,sharedGithubLogin:i,entries:o}}var Xn=qs(()=>{"use strict"});var nr={};Fs(nr,{GitHubClient:()=>xe});var Sg,xe,it=qs(()=>{"use strict";Sg=process.env.TICKETPILOT_GITHUB_API??"https://api.github.com",xe=class{constructor(e){this.token=e}token;async request(e,t,r){let s=await fetch(`${Sg}${t}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"allwright",...r!==void 0?{"Content-Type":"application/json"}:{}},body:r===void 0?void 0:JSON.stringify(r)}),i=await s.text(),o=null;try{o=i?JSON.parse(i):null}catch{}if(s.status===401)throw new Error("GitHub rejected the token (401) - expired or revoked? Run `allwright github set-token`");if(!s.ok&&s.status!==422){let l=o?.message??i.slice(0,300);throw new Error(`GitHub ${e} ${t} -> ${s.status}: ${l}`)}return{status:s.status,data:o}}async whoami(){let{data:e}=await this.request("GET","/user");return e.login}async createPullRequest(e,t,r){let{status:s,data:i}=await this.request("POST",`/repos/${e}/${t}/pulls`,r);if(s===422){let{data:o}=await this.request("GET",`/repos/${e}/${t}/pulls?head=${encodeURIComponent(`${e}:${r.head}`)}&state=open`);if(o?.length){let l=o[0];return{number:l.number,url:l.html_url,state:l.state,merged:l.merged??!1,headSha:l.head.sha,mergeableState:null,baseRef:l.base?.ref??""}}throw new Error(`GitHub refused the PR (422): ${i?.message??"validation failed"}`)}return{number:i.number,url:i.html_url,state:i.state,merged:i.merged??!1,headSha:i.head.sha,mergeableState:null,baseRef:r.base}}async getReviews(e,t,r){let{data:s}=await this.request("GET",`/repos/${e}/${t}/pulls/${r}/reviews?per_page=100`);return(s??[]).map(i=>({state:i.state??"",commitId:i.commit_id??"",user:i.user?.login??"",submittedAt:i.submitted_at??""}))}async getPullRequest(e,t,r){try{let{data:s}=await this.request("GET",`/repos/${e}/${t}/pulls/${r}`);return{number:s.number,url:s.html_url,state:s.state,merged:s.merged,headSha:s.head.sha,mergeableState:s.mergeable_state??null,baseRef:s.base?.ref??""}}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return null;throw s}}async mergePullRequest(e,t,r,s,i={}){try{return await this.request("PUT",`/repos/${e}/${t}/pulls/${r}/merge`,{merge_method:s,...i.sha?{sha:i.sha}:{},...i.title?{commit_title:i.title}:{}}),{merged:!0}}catch(o){let l=o instanceof Error?o.message:String(o);return l.includes("-> 405")?{merged:!1,reason:`GitHub refused the merge: the branch is not in a mergeable state, or this repository does not allow "${s}" merges. Check the PR for conflicts or required checks, then merge it there.`}:l.includes("-> 409")?{merged:!1,reason:"the branch moved since it was reviewed, so GitHub refused to merge the commit that was approved. Re-review the PR and approve again."}:l.includes("-> 403")?{merged:!1,reason:`this runner's GitHub token is not allowed to merge in ${e}/${t}. It needs write access to the repository - or merge the PR yourself.`}:{merged:!1,reason:l}}}async repoAccess(e,t){try{let{data:r}=await this.request("GET",`/repos/${e}/${t}`);return{ok:!0,canPush:!!(r.permissions?.push||r.permissions?.admin)}}catch(r){let s=r instanceof Error?r.message:String(r);return{ok:!1,canPush:!1,error:s.includes("-> 404")?"not found (private repo this token cannot see, or the name is wrong)":s.slice(0,200)}}}async closePullRequest(e,t,r){await this.request("PATCH",`/repos/${e}/${t}/pulls/${r}`,{state:"closed"})}async deleteBranch(e,t,r){try{await this.request("DELETE",`/repos/${e}/${t}/git/refs/heads/${encodeURIComponent(r)}`)}catch(s){if(s instanceof Error&&s.message.includes("-> 404"))return;throw s}}}});var Lt=re((rk,$d)=>{"use strict";var Ed=["nodebuffer","arraybuffer","fragments"],Ad=typeof Blob<"u";Ad&&Ed.push("blob");$d.exports={BINARY_TYPES:Ed,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Ad,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var $s=re((sk,Ui)=>{"use strict";var{EMPTY_BUFFER:ky}=Lt(),Da=Buffer[Symbol.species];function Sy(n,e){if(n.length===0)return ky;if(n.length===1)return n[0];let t=Buffer.allocUnsafe(e),r=0;for(let s=0;s<n.length;s++){let i=n[s];t.set(i,r),r+=i.length}return r<e?new Da(t.buffer,t.byteOffset,r):t}function Pd(n,e,t,r,s){for(let i=0;i<s;i++)t[r+i]=n[i]^e[i&3]}function jd(n,e){for(let t=0;t<n.length;t++)n[t]^=e[t&3]}function Ty(n){return n.length===n.buffer.byteLength?n.buffer:n.buffer.slice(n.byteOffset,n.byteOffset+n.length)}function La(n){if(La.readOnly=!0,Buffer.isBuffer(n))return n;let e;return n instanceof ArrayBuffer?e=new Da(n):ArrayBuffer.isView(n)?e=new Da(n.buffer,n.byteOffset,n.byteLength):(e=Buffer.from(n),La.readOnly=!1),e}Ui.exports={concat:Sy,mask:Pd,toArrayBuffer:Ty,toBuffer:La,unmask:jd};if(!process.env.WS_NO_BUFFER_UTIL)try{let n=require("bufferutil");Ui.exports.mask=function(e,t,r,s,i){i<48?Pd(e,t,r,s,i):n.mask(e,t,r,s,i)},Ui.exports.unmask=function(e,t){e.length<32?jd(e,t):n.unmask(e,t)}}catch{}});var Md=re((ik,Nd)=>{"use strict";var Od=Symbol("kDone"),Ua=Symbol("kRun"),qa=class{constructor(e){this[Od]=()=>{this.pending--,this[Ua]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ua]()}[Ua](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Od])}}};Nd.exports=qa});var es=re((ok,Ud)=>{"use strict";var Ps=require("zlib"),zd=$s(),xy=Md(),{kStatusCode:Dd}=Lt(),Cy=Buffer[Symbol.species],Iy=Buffer.from([0,0,255,255]),Fi=Symbol("permessage-deflate"),Ut=Symbol("total-length"),Xr=Symbol("callback"),un=Symbol("buffers"),Qr=Symbol("error"),qi,Fa=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!qi){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;qi=new xy(t)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Xr];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,r=e.find(s=>!(t.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>s.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(r.server_no_context_takeover=!0),t.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(r.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?r.client_max_window_bits=t.clientMaxWindowBits:(r.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(r=>{let s=t[r];if(s.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(s=s[0],r==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else if(r==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else throw new Error(`Unknown parameter "${r}"`);t[r]=s})}),e}decompress(e,t,r){qi.add(s=>{this._decompress(e,t,(i,o)=>{s(),r(i,o)})})}compress(e,t,r){qi.add(s=>{this._compress(e,t,(i,o)=>{s(),r(i,o)})})}_decompress(e,t,r){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Ps.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Ps.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Fi]=this,this._inflate[Ut]=0,this._inflate[un]=[],this._inflate.on("error",Ey),this._inflate.on("data",Ld)}this._inflate[Xr]=r,this._inflate.write(e),t&&this._inflate.write(Iy),this._inflate.flush(()=>{let i=this._inflate[Qr];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=zd.concat(this._inflate[un],this._inflate[Ut]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Ut]=0,this._inflate[un]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,t,r){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Ps.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Ps.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[Ut]=0,this._deflate[un]=[],this._deflate.on("data",Ry)}this._deflate[Xr]=r,this._deflate.write(e),this._deflate.flush(Ps.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=zd.concat(this._deflate[un],this._deflate[Ut]);t&&(i=new Cy(i.buffer,i.byteOffset,i.length-4)),this._deflate[Xr]=null,this._deflate[Ut]=0,this._deflate[un]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};Ud.exports=Fa;function Ry(n){this[un].push(n),this[Ut]+=n.length}function Ld(n){if(this[Ut]+=n.length,this[Fi]._maxPayload<1||this[Ut]<=this[Fi]._maxPayload){this[un].push(n);return}this[Qr]=new RangeError("Max payload size exceeded"),this[Qr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Qr][Dd]=1009,this.removeListener("data",Ld),this.reset()}function Ey(n){if(this[Fi]._inflate=null,this[Qr]){this[Xr](this[Qr]);return}n[Dd]=1007,this[Xr](n)}});var ts=re((ak,Bi)=>{"use strict";var{isUtf8:qd}=require("buffer"),{hasBlob:Ay}=Lt(),$y=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function Py(n){return n>=1e3&&n<=1014&&n!==1004&&n!==1005&&n!==1006||n>=3e3&&n<=4999}function Ba(n){let e=n.length,t=0;for(;t<e;)if((n[t]&128)===0)t++;else if((n[t]&224)===192){if(t+1===e||(n[t+1]&192)!==128||(n[t]&254)===192)return!1;t+=2}else if((n[t]&240)===224){if(t+2>=e||(n[t+1]&192)!==128||(n[t+2]&192)!==128||n[t]===224&&(n[t+1]&224)===128||n[t]===237&&(n[t+1]&224)===160)return!1;t+=3}else if((n[t]&248)===240){if(t+3>=e||(n[t+1]&192)!==128||(n[t+2]&192)!==128||(n[t+3]&192)!==128||n[t]===240&&(n[t+1]&240)===128||n[t]===244&&n[t+1]>143||n[t]>244)return!1;t+=4}else return!1;return!0}function jy(n){return Ay&&typeof n=="object"&&typeof n.arrayBuffer=="function"&&typeof n.type=="string"&&typeof n.stream=="function"&&(n[Symbol.toStringTag]==="Blob"||n[Symbol.toStringTag]==="File")}Bi.exports={isBlob:jy,isValidStatusCode:Py,isValidUTF8:Ba,tokenChars:$y};if(qd)Bi.exports.isValidUTF8=function(n){return n.length<24?Ba(n):qd(n)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let n=require("utf-8-validate");Bi.exports.isValidUTF8=function(e){return e.length<32?Ba(e):n(e)}}catch{}});var Va=re((lk,Vd)=>{"use strict";var{Writable:Oy}=require("stream"),Fd=es(),{BINARY_TYPES:Ny,EMPTY_BUFFER:Bd,kStatusCode:My,kWebSocket:zy}=Lt(),{concat:Ka,toArrayBuffer:Dy,unmask:Ly}=$s(),{isValidStatusCode:Uy,isValidUTF8:Kd}=ts(),Ki=Buffer[Symbol.species],Xe=0,Zd=1,Gd=2,Hd=3,Za=4,Ga=5,Zi=6,Ha=class extends Oy{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Ny[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[zy]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=Xe}_write(e,t,r){if(this._opcode===8&&this._state==Xe)return r();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){r(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new Ki(r.buffer,r.byteOffset+e,r.length-e),new Ki(r.buffer,r.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let r=this._buffers[0],s=t.length-e;e>=r.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new Ki(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case Xe:this.getInfo(e);break;case Zd:this.getPayloadLength16(e);break;case Gd:this.getPayloadLength64(e);break;case Hd:this.getMask();break;case Za:this.getData(e);break;case Ga:case Zi:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((t[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let r=(t[0]&64)===64;if(r&&!this._extensions[Fd.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=Zd:this._payloadLength===127?this._state=Gd:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),r=t.readUInt32BE(0);if(r>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=r*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=Hd:this._state=Za}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Za}getData(e){let t=Bd;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Ly(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let r=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(r);return}if(this._compressed){this._state=Ga,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Fd.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return t(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(o);return}this._fragments.push(i)}this.dataMessage(t),this._state===Xe&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=Xe;return}let t=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=Ka(r,t):this._binaryType==="arraybuffer"?s=Dy(Ka(r,t)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=Xe):(this._state=Zi,setImmediate(()=>{this.emit("message",s,!0),this._state=Xe,this.startLoop(e)}))}else{let s=Ka(r,t);if(!this._skipUTF8Validation&&!Kd(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Ga||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=Xe):(this._state=Zi,setImmediate(()=>{this.emit("message",s,!1),this._state=Xe,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Bd),this.end();else{let r=e.readUInt16BE(0);if(!Uy(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new Ki(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Kd(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(i);return}this._loop=!1,this.emit("conclude",r,s),this.end()}this._state=Xe;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Xe):(this._state=Zi,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Xe,this.startLoop(t)}))}createError(e,t,r,s,i){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[My]=s,o}};Vd.exports=Ha});var Ya=re((ck,Yd)=>{"use strict";var{Duplex:uk}=require("stream"),{randomFillSync:qy}=require("crypto"),{types:{isUint8Array:Fy}}=require("util"),Wd=es(),{EMPTY_BUFFER:By,kWebSocket:Ky,NOOP:Zy}=Lt(),{isBlob:ns,isValidStatusCode:Gy}=ts(),{mask:Jd,toBuffer:fr}=$s(),Qe=Symbol("kByteLength"),Hy=Buffer.alloc(4),Gi=8*1024,pr,rs=Gi,lt=0,Vy=1,Wy=2,Wa=class n{constructor(e,t,r){this._extensions=t||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=lt,this.onerror=Zy,this[Ky]=void 0}static frame(e,t){let r,s=!1,i=2,o=!1;t.mask&&(r=t.maskBuffer||Hy,t.generateMask?t.generateMask(r):(rs===Gi&&(pr===void 0&&(pr=Buffer.alloc(Gi)),qy(pr,0,Gi),rs=0),r[0]=pr[rs++],r[1]=pr[rs++],r[2]=pr[rs++],r[3]=pr[rs++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let l;typeof e=="string"?(!t.mask||o)&&t[Qe]!==void 0?l=t[Qe]:(e=Buffer.from(e),l=e.length):(l=e.length,s=t.mask&&t.readOnly&&!o);let u=l;l>=65536?(i+=8,u=127):l>125&&(i+=2,u=126);let c=Buffer.allocUnsafe(s?l+i:i);return c[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(c[0]|=64),c[1]=u,u===126?c.writeUInt16BE(l,2):u===127&&(c[2]=c[3]=0,c.writeUIntBE(l,4,6)),t.mask?(c[1]|=128,c[i-4]=r[0],c[i-3]=r[1],c[i-2]=r[2],c[i-1]=r[3],o?[c,e]:s?(Jd(e,r,c,i,l),[c]):(Jd(e,r,e,0,l),[c,e])):[c,e]}close(e,t,r,s){let i;if(e===void 0)i=By;else{if(typeof e!="number"||!Gy(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let l=Buffer.byteLength(t);if(l>123)throw new RangeError("The message must not be greater than 123 bytes");if(i=Buffer.allocUnsafe(2+l),i.writeUInt16BE(e,0),typeof t=="string")i.write(t,2);else if(Fy(t))i.set(t,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[Qe]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==lt?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(n.frame(i,o),s)}ping(e,t,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):ns(e)?(s=e.size,i=!1):(e=fr(e),s=e.length,i=fr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Qe]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};ns(e)?this._state!==lt?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==lt?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(n.frame(e,o),r)}pong(e,t,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):ns(e)?(s=e.size,i=!1):(e=fr(e),s=e.length,i=fr.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Qe]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};ns(e)?this._state!==lt?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==lt?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(n.frame(e,o),r)}send(e,t,r){let s=this._extensions[Wd.extensionName],i=t.binary?2:1,o=t.compress,l,u;typeof e=="string"?(l=Buffer.byteLength(e),u=!1):ns(e)?(l=e.size,u=!1):(e=fr(e),l=e.length,u=fr.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=l>=s._threshold),this._compress=o):(o=!1,i=0),t.fin&&(this._firstFragment=!0);let c={[Qe]:l,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:u,rsv1:o};ns(e)?this._state!==lt?this.enqueue([this.getBlobData,e,this._compress,c,r]):this.getBlobData(e,this._compress,c,r):this._state!==lt?this.enqueue([this.dispatch,e,this._compress,c,r]):this.dispatch(e,this._compress,c,r)}getBlobData(e,t,r,s){this._bufferedBytes+=r[Qe],this._state=Wy,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let l=new Error("The socket was closed while the blob was being read");process.nextTick(Ja,this,l,s);return}this._bufferedBytes-=r[Qe];let o=fr(i);t?this.dispatch(o,t,r,s):(this._state=lt,this.sendFrame(n.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(Jy,this,i,s)})}dispatch(e,t,r,s){if(!t){this.sendFrame(n.frame(e,r),s);return}let i=this._extensions[Wd.extensionName];this._bufferedBytes+=r[Qe],this._state=Vy,i.compress(e,r.fin,(o,l)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");Ja(this,u,s);return}this._bufferedBytes-=r[Qe],this._state=lt,r.readOnly=!1,this.sendFrame(n.frame(l,r),s),this.dequeue()})}dequeue(){for(;this._state===lt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Qe],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Qe],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};Yd.exports=Wa;function Ja(n,e,t){typeof t=="function"&&t(e);for(let r=0;r<n._queue.length;r++){let s=n._queue[r],i=s[s.length-1];typeof i=="function"&&i(e)}}function Jy(n,e,t){Ja(n,e,t),n.onerror(e)}});var oh=re((dk,ih)=>{"use strict";var{kForOnEventAttribute:js,kListener:Xa}=Lt(),Xd=Symbol("kCode"),Qd=Symbol("kData"),eh=Symbol("kError"),th=Symbol("kMessage"),nh=Symbol("kReason"),ss=Symbol("kTarget"),rh=Symbol("kType"),sh=Symbol("kWasClean"),qt=class{constructor(e){this[ss]=null,this[rh]=e}get target(){return this[ss]}get type(){return this[rh]}};Object.defineProperty(qt.prototype,"target",{enumerable:!0});Object.defineProperty(qt.prototype,"type",{enumerable:!0});var mr=class extends qt{constructor(e,t={}){super(e),this[Xd]=t.code===void 0?0:t.code,this[nh]=t.reason===void 0?"":t.reason,this[sh]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Xd]}get reason(){return this[nh]}get wasClean(){return this[sh]}};Object.defineProperty(mr.prototype,"code",{enumerable:!0});Object.defineProperty(mr.prototype,"reason",{enumerable:!0});Object.defineProperty(mr.prototype,"wasClean",{enumerable:!0});var is=class extends qt{constructor(e,t={}){super(e),this[eh]=t.error===void 0?null:t.error,this[th]=t.message===void 0?"":t.message}get error(){return this[eh]}get message(){return this[th]}};Object.defineProperty(is.prototype,"error",{enumerable:!0});Object.defineProperty(is.prototype,"message",{enumerable:!0});var Os=class extends qt{constructor(e,t={}){super(e),this[Qd]=t.data===void 0?null:t.data}get data(){return this[Qd]}};Object.defineProperty(Os.prototype,"data",{enumerable:!0});var Yy={addEventListener(n,e,t={}){for(let s of this.listeners(n))if(!t[js]&&s[Xa]===e&&!s[js])return;let r;if(n==="message")r=function(i,o){let l=new Os("message",{data:o?i:i.toString()});l[ss]=this,Hi(e,this,l)};else if(n==="close")r=function(i,o){let l=new mr("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});l[ss]=this,Hi(e,this,l)};else if(n==="error")r=function(i){let o=new is("error",{error:i,message:i.message});o[ss]=this,Hi(e,this,o)};else if(n==="open")r=function(){let i=new qt("open");i[ss]=this,Hi(e,this,i)};else return;r[js]=!!t[js],r[Xa]=e,t.once?this.once(n,r):this.on(n,r)},removeEventListener(n,e){for(let t of this.listeners(n))if(t[Xa]===e&&!t[js]){this.removeListener(n,t);break}}};ih.exports={CloseEvent:mr,ErrorEvent:is,Event:qt,EventTarget:Yy,MessageEvent:Os};function Hi(n,e,t){typeof n=="object"&&n.handleEvent?n.handleEvent.call(n,t):n.call(e,t)}});var Vi=re((hk,ah)=>{"use strict";var{tokenChars:Ns}=ts();function _t(n,e,t){n[e]===void 0?n[e]=[t]:n[e].push(t)}function Xy(n){let e=Object.create(null),t=Object.create(null),r=!1,s=!1,i=!1,o,l,u=-1,c=-1,f=-1,p=0;for(;p<n.length;p++)if(c=n.charCodeAt(p),o===void 0)if(f===-1&&Ns[c]===1)u===-1&&(u=p);else if(p!==0&&(c===32||c===9))f===-1&&u!==-1&&(f=p);else if(c===59||c===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let w=n.slice(u,f);c===44?(_t(e,w,t),t=Object.create(null)):o=w,u=f=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(l===void 0)if(f===-1&&Ns[c]===1)u===-1&&(u=p);else if(c===32||c===9)f===-1&&u!==-1&&(f=p);else if(c===59||c===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),_t(t,n.slice(u,f),!0),c===44&&(_t(e,o,t),t=Object.create(null),o=void 0),u=f=-1}else if(c===61&&u!==-1&&f===-1)l=n.slice(u,p),u=f=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(s){if(Ns[c]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:r||(r=!0),s=!1}else if(i)if(Ns[c]===1)u===-1&&(u=p);else if(c===34&&u!==-1)i=!1,f=p;else if(c===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(c===34&&n.charCodeAt(p-1)===61)i=!0;else if(f===-1&&Ns[c]===1)u===-1&&(u=p);else if(u!==-1&&(c===32||c===9))f===-1&&(f=p);else if(c===59||c===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let w=n.slice(u,f);r&&(w=w.replace(/\\/g,""),r=!1),_t(t,l,w),c===44&&(_t(e,o,t),t=Object.create(null),o=void 0),l=void 0,u=f=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(u===-1||i||c===32||c===9)throw new SyntaxError("Unexpected end of input");f===-1&&(f=p);let b=n.slice(u,f);return o===void 0?_t(e,b,t):(l===void 0?_t(t,b,!0):r?_t(t,l,b.replace(/\\/g,"")):_t(t,l,b),_t(e,o,t)),e}function Qy(n){return Object.keys(n).map(e=>{let t=n[e];return Array.isArray(t)||(t=[t]),t.map(r=>[e].concat(Object.keys(r).map(s=>{let i=r[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}ah.exports={format:Qy,parse:Xy}});var Xi=re((mk,bh)=>{"use strict";var ev=require("events"),tv=require("https"),nv=require("http"),ch=require("net"),rv=require("tls"),{randomBytes:sv,createHash:iv}=require("crypto"),{Duplex:fk,Readable:pk}=require("stream"),{URL:Qa}=require("url"),cn=es(),ov=Va(),av=Ya(),{isBlob:lv}=ts(),{BINARY_TYPES:lh,CLOSE_TIMEOUT:uv,EMPTY_BUFFER:Wi,GUID:cv,kForOnEventAttribute:el,kListener:dv,kStatusCode:hv,kWebSocket:ge,NOOP:dh}=Lt(),{EventTarget:{addEventListener:fv,removeEventListener:pv}}=oh(),{format:mv,parse:gv}=Vi(),{toBuffer:yv}=$s(),hh=Symbol("kAborted"),tl=[8,13],Ft=["CONNECTING","OPEN","CLOSING","CLOSED"],vv=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,de=class n extends ev{constructor(e,t,r){super(),this._binaryType=lh[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Wi,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=n.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(r=t,t=[]):t=[t]),fh(this,e,t,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){lh.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,r){let s=new ov({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new av(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[ge]=this,i[ge]=this,e[ge]=this,s.on("conclude",_v),s.on("drain",kv),s.on("error",Sv),s.on("message",Tv),s.on("ping",xv),s.on("pong",Cv),i.onerror=Iv,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",gh),e.on("data",Yi),e.on("end",yh),e.on("error",vh),this._readyState=n.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[cn.extensionName]&&this._extensions[cn.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){Ue(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===n.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=n.CLOSING,this._sender.close(e,t,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),mh(this)}}pause(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,r){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=t=void 0):typeof t=="function"&&(r=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){nl(this,e,r);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Wi,t,r)}pong(e,t,r){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=t=void 0):typeof t=="function"&&(r=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){nl(this,e,r);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Wi,t,r)}resume(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,r){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(r=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){nl(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[cn.extensionName]||(s.compress=!1),this._sender.send(e||Wi,s,r)}terminate(){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){Ue(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=n.CLOSING,this._socket.destroy())}}};Object.defineProperty(de,"CONNECTING",{enumerable:!0,value:Ft.indexOf("CONNECTING")});Object.defineProperty(de.prototype,"CONNECTING",{enumerable:!0,value:Ft.indexOf("CONNECTING")});Object.defineProperty(de,"OPEN",{enumerable:!0,value:Ft.indexOf("OPEN")});Object.defineProperty(de.prototype,"OPEN",{enumerable:!0,value:Ft.indexOf("OPEN")});Object.defineProperty(de,"CLOSING",{enumerable:!0,value:Ft.indexOf("CLOSING")});Object.defineProperty(de.prototype,"CLOSING",{enumerable:!0,value:Ft.indexOf("CLOSING")});Object.defineProperty(de,"CLOSED",{enumerable:!0,value:Ft.indexOf("CLOSED")});Object.defineProperty(de.prototype,"CLOSED",{enumerable:!0,value:Ft.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(n=>{Object.defineProperty(de.prototype,n,{enumerable:!0})});["open","error","close","message"].forEach(n=>{Object.defineProperty(de.prototype,`on${n}`,{enumerable:!0,get(){for(let e of this.listeners(n))if(e[el])return e[dv];return null},set(e){for(let t of this.listeners(n))if(t[el]){this.removeListener(n,t);break}typeof e=="function"&&this.addEventListener(n,e,{[el]:!0})}})});de.prototype.addEventListener=fv;de.prototype.removeEventListener=pv;bh.exports=de;function fh(n,e,t,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:uv,protocolVersion:tl[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(n._autoPong=s.autoPong,n._closeTimeout=s.closeTimeout,!tl.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${tl.join(", ")})`);let i;if(e instanceof Qa)i=e;else try{i=new Qa(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),n._url=i.href;let o=i.protocol==="wss:",l=i.protocol==="ws+unix:",u;if(i.protocol!=="ws:"&&!o&&!l?u=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:l&&!i.pathname?u="The URL's pathname is empty":i.hash&&(u="The URL contains a fragment identifier"),u){let C=new SyntaxError(u);if(n._redirects===0)throw C;Ji(n,C);return}let c=o?443:80,f=sv(16).toString("base64"),p=o?tv.request:nv.request,b=new Set,w;if(s.createConnection=s.createConnection||(o?wv:bv),s.defaultPort=s.defaultPort||c,s.port=i.port||c,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":f,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(w=new cn({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=mv({[cn.extensionName]:w.offer()})),t.length){for(let C of t){if(typeof C!="string"||!vv.test(C)||b.has(C))throw new SyntaxError("An invalid or duplicated subprotocol was specified");b.add(C)}s.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),l){let C=s.path.split(":");s.socketPath=C[0],s.path=C[1]}let T;if(s.followRedirects){if(n._redirects===0){n._originalIpc=l,n._originalSecure=o,n._originalHostOrSocketPath=l?s.socketPath:i.host;let C=r&&r.headers;if(r={...r,headers:{}},C)for(let[A,v]of Object.entries(C))r.headers[A.toLowerCase()]=v}else if(n.listenerCount("redirect")===0){let C=l?n._originalIpc?s.socketPath===n._originalHostOrSocketPath:!1:n._originalIpc?!1:i.host===n._originalHostOrSocketPath;(!C||n._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,C||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),T=n._req=p(s),n._redirects&&n.emit("redirect",n.url,T)}else T=n._req=p(s);s.timeout&&T.on("timeout",()=>{Ue(n,T,"Opening handshake has timed out")}),T.on("error",C=>{T===null||T[hh]||(T=n._req=null,Ji(n,C))}),T.on("response",C=>{let A=C.headers.location,v=C.statusCode;if(A&&s.followRedirects&&v>=300&&v<400){if(++n._redirects>s.maxRedirects){Ue(n,T,"Maximum redirects exceeded");return}T.abort();let B;try{B=new Qa(A,e)}catch{let D=new SyntaxError(`Invalid URL: ${A}`);Ji(n,D);return}fh(n,B,t,r)}else n.emit("unexpected-response",T,C)||Ue(n,T,`Unexpected server response: ${C.statusCode}`)}),T.on("upgrade",(C,A,v)=>{if(n.emit("upgrade",C),n.readyState!==de.CONNECTING)return;T=n._req=null;let B=C.headers.upgrade;if(B===void 0||B.toLowerCase()!=="websocket"){Ue(n,A,"Invalid Upgrade header");return}let N=iv("sha1").update(f+cv).digest("base64");if(C.headers["sec-websocket-accept"]!==N){Ue(n,A,"Invalid Sec-WebSocket-Accept header");return}let D=C.headers["sec-websocket-protocol"],K;if(D!==void 0?b.size?b.has(D)||(K="Server sent an invalid subprotocol"):K="Server sent a subprotocol but none was requested":b.size&&(K="Server sent no subprotocol"),K){Ue(n,A,K);return}D&&(n._protocol=D);let h=C.headers["sec-websocket-extensions"];if(h!==void 0){if(!w){Ue(n,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let m;try{m=gv(h)}catch{Ue(n,A,"Invalid Sec-WebSocket-Extensions header");return}let g=Object.keys(m);if(g.length!==1||g[0]!==cn.extensionName){Ue(n,A,"Server indicated an extension that was not requested");return}try{w.accept(m[cn.extensionName])}catch{Ue(n,A,"Invalid Sec-WebSocket-Extensions header");return}n._extensions[cn.extensionName]=w}n.setSocket(A,v,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(T,n):T.end()}function Ji(n,e){n._readyState=de.CLOSING,n._errorEmitted=!0,n.emit("error",e),n.emitClose()}function bv(n){return n.path=n.socketPath,ch.connect(n)}function wv(n){return n.path=void 0,!n.servername&&n.servername!==""&&(n.servername=ch.isIP(n.host)?"":n.host),rv.connect(n)}function Ue(n,e,t){n._readyState=de.CLOSING;let r=new Error(t);Error.captureStackTrace(r,Ue),e.setHeader?(e[hh]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Ji,n,r)):(e.destroy(r),e.once("error",n.emit.bind(n,"error")),e.once("close",n.emitClose.bind(n)))}function nl(n,e,t){if(e){let r=lv(e)?e.size:yv(e).length;n._socket?n._sender._bufferedBytes+=r:n._bufferedAmount+=r}if(t){let r=new Error(`WebSocket is not open: readyState ${n.readyState} (${Ft[n.readyState]})`);process.nextTick(t,r)}}function _v(n,e){let t=this[ge];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=n,t._socket[ge]!==void 0&&(t._socket.removeListener("data",Yi),process.nextTick(ph,t._socket),n===1005?t.close():t.close(n,e))}function kv(){let n=this[ge];n.isPaused||n._socket.resume()}function Sv(n){let e=this[ge];e._socket[ge]!==void 0&&(e._socket.removeListener("data",Yi),process.nextTick(ph,e._socket),e.close(n[hv])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n))}function uh(){this[ge].emitClose()}function Tv(n,e){this[ge].emit("message",n,e)}function xv(n){let e=this[ge];e._autoPong&&e.pong(n,!this._isServer,dh),e.emit("ping",n)}function Cv(n){this[ge].emit("pong",n)}function ph(n){n.resume()}function Iv(n){let e=this[ge];e.readyState!==de.CLOSED&&(e.readyState===de.OPEN&&(e._readyState=de.CLOSING,mh(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n)))}function mh(n){n._closeTimer=setTimeout(n._socket.destroy.bind(n._socket),n._closeTimeout)}function gh(){let n=this[ge];if(this.removeListener("close",gh),this.removeListener("data",Yi),this.removeListener("end",yh),n._readyState=de.CLOSING,!this._readableState.endEmitted&&!n._closeFrameReceived&&!n._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);n._receiver.write(e)}n._receiver.end(),this[ge]=void 0,clearTimeout(n._closeTimer),n._receiver._writableState.finished||n._receiver._writableState.errorEmitted?n.emitClose():(n._receiver.on("error",uh),n._receiver.on("finish",uh))}function Yi(n){this[ge]._receiver.write(n)||this.pause()}function yh(){let n=this[ge];n._readyState=de.CLOSING,n._receiver.end(),this.end()}function vh(){let n=this[ge];this.removeListener("error",vh),this.on("error",dh),n&&(n._readyState=de.CLOSING,this.destroy())}});var Sh=re((yk,kh)=>{"use strict";var gk=Xi(),{Duplex:Rv}=require("stream");function wh(n){n.emit("close")}function Ev(){!this.destroyed&&this._writableState.finished&&this.destroy()}function _h(n){this.removeListener("error",_h),this.destroy(),this.listenerCount("error")===0&&this.emit("error",n)}function Av(n,e){let t=!0,r=new Rv({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return n.on("message",function(i,o){let l=!o&&r._readableState.objectMode?i.toString():i;r.push(l)||n.pause()}),n.once("error",function(i){r.destroyed||(t=!1,r.destroy(i))}),n.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(s,i){if(n.readyState===n.CLOSED){i(s),process.nextTick(wh,r);return}let o=!1;n.once("error",function(u){o=!0,i(u)}),n.once("close",function(){o||i(s),process.nextTick(wh,r)}),t&&n.terminate()},r._final=function(s){if(n.readyState===n.CONNECTING){n.once("open",function(){r._final(s)});return}n._socket!==null&&(n._socket._writableState.finished?(s(),r._readableState.endEmitted&&r.destroy()):(n._socket.once("finish",function(){s()}),n.close()))},r._read=function(){n.isPaused&&n.resume()},r._write=function(s,i,o){if(n.readyState===n.CONNECTING){n.once("open",function(){r._write(s,i,o)});return}n.send(s,o)},r.on("end",Ev),r.on("error",_h),r}kh.exports=Av});var rl=re((vk,Th)=>{"use strict";var{tokenChars:$v}=ts();function Pv(n){let e=new Set,t=-1,r=-1,s=0;for(s;s<n.length;s++){let o=n.charCodeAt(s);if(r===-1&&$v[o]===1)t===-1&&(t=s);else if(s!==0&&(o===32||o===9))r===-1&&t!==-1&&(r=s);else if(o===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${s}`);r===-1&&(r=s);let l=n.slice(t,r);if(e.has(l))throw new SyntaxError(`The "${l}" subprotocol is duplicated`);e.add(l),t=r=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(t===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let i=n.slice(t,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}Th.exports={parse:Pv}});var $h=re((wk,Ah)=>{"use strict";var jv=require("events"),Qi=require("http"),{Duplex:bk}=require("stream"),{createHash:Ov}=require("crypto"),xh=Vi(),gr=es(),Nv=rl(),Mv=Xi(),{CLOSE_TIMEOUT:zv,GUID:Dv,kWebSocket:Lv}=Lt(),Uv=/^[+/0-9A-Za-z]{22}==$/,Ch=0,Ih=1,Eh=2,sl=class extends jv{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:zv,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Mv,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Qi.createServer((r,s)=>{let i=Qi.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=qv(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Ch}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Eh){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Ms,this);return}if(e&&this.once("close",e),this._state!==Ih)if(this._state=Ih,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Ms,this):process.nextTick(Ms,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{Ms(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,r,s){t.on("error",Rh);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,l=+e.headers["sec-websocket-version"];if(e.method!=="GET"){yr(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){yr(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!Uv.test(i)){yr(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(l!==13&&l!==8){yr(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){zs(t,400);return}let u=e.headers["sec-websocket-protocol"],c=new Set;if(u!==void 0)try{c=Nv.parse(u)}catch{yr(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let f=e.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&f!==void 0){let b=new gr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let w=xh.parse(f);w[gr.extensionName]&&(b.accept(w[gr.extensionName]),p[gr.extensionName]=b)}catch{yr(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let b={origin:e.headers[`${l===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(b,(w,T,C,A)=>{if(!w)return zs(t,T||401,C,A);this.completeUpgrade(p,i,c,e,t,r,s)});return}if(!this.options.verifyClient(b))return zs(t,401)}this.completeUpgrade(p,i,c,e,t,r,s)}completeUpgrade(e,t,r,s,i,o,l){if(!i.readable||!i.writable)return i.destroy();if(i[Lv])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Ch)return zs(i,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Ov("sha1").update(t+Dv).digest("base64")}`],f=new this.options.WebSocket(null,void 0,this.options);if(r.size){let p=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;p&&(c.push(`Sec-WebSocket-Protocol: ${p}`),f._protocol=p)}if(e[gr.extensionName]){let p=e[gr.extensionName].params,b=xh.format({[gr.extensionName]:[p]});c.push(`Sec-WebSocket-Extensions: ${b}`),f._extensions=e}this.emit("headers",c,s),i.write(c.concat(`\r
256
256
  `).join(`\r
257
- `)),i.removeListener("error",vh),f.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(f),f.on("close",()=>{this.clients.delete(f),this._shouldEmitClose&&!this.clients.size&&process.nextTick(As,this)})),l(f,s)}};wh.exports=Ya;function Iv(n,e){for(let t of Object.keys(e))n.on(t,e[t]);return function(){for(let r of Object.keys(e))n.removeListener(r,e[r])}}function As(n){n._state=bh,n.emit("close")}function vh(){this.destroy()}function $s(n,e,t,r){t=t||Wi.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...r},n.once("finish",n.destroy),n.end(`HTTP/1.1 ${e} ${Wi.STATUS_CODES[e]}\r
257
+ `)),i.removeListener("error",Rh),f.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(f),f.on("close",()=>{this.clients.delete(f),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Ms,this)})),l(f,s)}};Ah.exports=sl;function qv(n,e){for(let t of Object.keys(e))n.on(t,e[t]);return function(){for(let r of Object.keys(e))n.removeListener(r,e[r])}}function Ms(n){n._state=Eh,n.emit("close")}function Rh(){this.destroy()}function zs(n,e,t,r){t=t||Qi.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...r},n.once("finish",n.destroy),n.end(`HTTP/1.1 ${e} ${Qi.STATUS_CODES[e]}\r
258
258
  `+Object.keys(r).map(s=>`${s}: ${r[s]}`).join(`\r
259
259
  `)+`\r
260
260
  \r
261
- `+t)}function pr(n,e,t,r,s,i){if(n.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,pr),n.emit("wsClientError",o,t,e)}else $s(t,r,s,i)}});var Ph={};Ds(Ph,{buildSetupReport:()=>Gv,claudeLoggedIn:()=>$h,repoDefaultBranch:()=>Ah});function Ah(n){let e=(...s)=>{try{return(0,eo.execFileSync)("git",["-C",n,...s],{encoding:"utf8",timeout:1e4}).trim()}catch{return null}},t=e("symbolic-ref","--short","refs/remotes/origin/HEAD");if(t?.startsWith("origin/"))return t.slice(7);let r=e("rev-parse","--abbrev-ref","HEAD");return r&&r!=="HEAD"?r:""}function $h(n=Rh.default.homedir()){if(un.default.existsSync(gr.default.join(n,".claude",".credentials.json")))return!0;try{return!!JSON.parse(un.default.readFileSync(gr.default.join(n,".claude.json"),"utf8")).oauthAccount}catch{return!1}}async function Gv(n,e){let t=!1,r="";if(Os&&Date.now()-Os.at<6e4)t=Os.installed,r=Os.version;else{try{let{stdout:o}=await Zv(n.claudeBin,["--version"],{timeout:1e4});t=!0,r=o.trim().slice(0,60)}catch{t=!1}Os={at:Date.now(),installed:t,version:r}}let s=e.map(o=>{let l=n.repos[o];if(!l)return{repoName:o,mapped:!1,pathExists:!1,isGit:!1,claudeMd:!1,deployMd:!1,testMd:!1,githubToken:!1,githubTokenOwn:!1,defaultBranch:""};let u=un.default.existsSync(l.path);return{repoName:o,mapped:!0,pathExists:u,isGit:u&&un.default.existsSync(gr.default.join(l.path,".git")),claudeMd:u&&un.default.existsSync(gr.default.join(l.path,"CLAUDE.md")),deployMd:u&&un.default.existsSync(gr.default.join(l.path,"DEPLOY.md")),testMd:u&&un.default.existsSync(gr.default.join(l.path,"TEST.md")),githubToken:!!Te(n,o),githubTokenOwn:!!l.github?.token,defaultBranch:u?Ah(l.path):""}}),i=Object.values(n.repos).find(o=>o.github?.token);return{jiraConfigured:!!n.jira,jiraEmail:n.jira?.email??"",claude:{installed:t,version:r,loggedIn:$h()},githubTokenSet:!!(n.github?.token||i),githubLogin:n.github?.login??i?.github?.login??"",deploysEnabled:n.deploy.enabled,jiraUserCount:Object.keys(n.jiraUsers).length,repos:s}}var eo,un,Rh,gr,Eh,Zv,Os,jh=zs(()=>{"use strict";eo=require("node:child_process"),un=R(require("node:fs"),1),Rh=R(require("node:os"),1),gr=R(require("node:path"),1),Eh=require("node:util");Wn();Zv=(0,Eh.promisify)(eo.execFile);Os=null});var ot=R(require("node:fs"),1),nl=R(require("node:os"),1),rs=R(require("node:path"),1),Ut=require("node:child_process"),to=require("node:crypto"),yr=R(require("node:readline/promises"),1);var _l=R(wl(),1),{program:nb,createCommand:rb,createArgument:sb,createOption:ib,CommanderError:ob,InvalidArgumentError:ab,InvalidOptionArgumentError:lb,Command:kl,Argument:ub,Option:cb,Help:db}=_l.default;var It=R(require("node:fs"),1),Gs=R(require("node:os"),1),Hs=R(require("node:path"),1);var k={};Ds(k,{BRAND:()=>Ef,DIRTY:()=>cn,EMPTY_PATH:()=>af,INVALID:()=>B,NEVER:()=>fp,OK:()=>_e,ParseStatus:()=>be,Schema:()=>Y,ZodAny:()=>Kt,ZodArray:()=>Ct,ZodBigInt:()=>hn,ZodBoolean:()=>fn,ZodBranded:()=>ls,ZodCatch:()=>Tn,ZodDate:()=>pn,ZodDefault:()=>Sn,ZodDiscriminatedUnion:()=>Bs,ZodEffects:()=>Be,ZodEnum:()=>_n,ZodError:()=>Re,ZodFirstPartyTypeKind:()=>K,ZodFunction:()=>Zs,ZodIntersection:()=>vn,ZodIssueCode:()=>I,ZodLazy:()=>bn,ZodLiteral:()=>wn,ZodMap:()=>Sr,ZodNaN:()=>xr,ZodNativeEnum:()=>kn,ZodNever:()=>Xe,ZodNull:()=>gn,ZodNullable:()=>ct,ZodNumber:()=>dn,ZodObject:()=>Ee,ZodOptional:()=>qe,ZodParsedType:()=>O,ZodPipeline:()=>us,ZodPromise:()=>Zt,ZodReadonly:()=>xn,ZodRecord:()=>Ks,ZodSchema:()=>Y,ZodSet:()=>Tr,ZodString:()=>Bt,ZodSymbol:()=>_r,ZodTransformer:()=>Be,ZodTuple:()=>ut,ZodType:()=>Y,ZodUndefined:()=>mn,ZodUnion:()=>yn,ZodUnknown:()=>xt,ZodVoid:()=>kr,addIssueToContext:()=>P,any:()=>Df,array:()=>Ff,bigint:()=>jf,boolean:()=>jl,coerce:()=>hp,custom:()=>Al,date:()=>Of,datetimeRegex:()=>Rl,defaultErrorMap:()=>St,discriminatedUnion:()=>Gf,effect:()=>sp,enum:()=>tp,function:()=>Xf,getErrorMap:()=>vr,getParsedType:()=>lt,instanceof:()=>$f,intersection:()=>Hf,isAborted:()=>qs,isAsync:()=>br,isDirty:()=>Fs,isValid:()=>Ft,late:()=>Af,lazy:()=>Qf,literal:()=>ep,makeIssue:()=>as,map:()=>Jf,nan:()=>Pf,nativeEnum:()=>np,never:()=>Uf,null:()=>zf,nullable:()=>op,number:()=>Pl,object:()=>Bf,objectUtil:()=>bo,oboolean:()=>dp,onumber:()=>cp,optional:()=>ip,ostring:()=>up,pipeline:()=>lp,preprocess:()=>ap,promise:()=>rp,quotelessJson:()=>rf,record:()=>Wf,set:()=>Yf,setErrorMap:()=>of,strictObject:()=>Kf,string:()=>$l,symbol:()=>Nf,transformer:()=>sp,tuple:()=>Vf,undefined:()=>Mf,union:()=>Zf,unknown:()=>Lf,util:()=>Q,void:()=>qf});var Q;(function(n){n.assertEqual=s=>{};function e(s){}n.assertIs=e;function t(s){throw new Error}n.assertNever=t,n.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},n.getValidEnumValues=s=>{let i=n.objectKeys(s).filter(l=>typeof s[s[l]]!="number"),o={};for(let l of i)o[l]=s[l];return n.objectValues(o)},n.objectValues=s=>n.objectKeys(s).map(function(i){return s[i]}),n.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},n.find=(s,i)=>{for(let o of s)if(i(o))return o},n.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}n.joinValues=r,n.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(Q||(Q={}));var bo;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(bo||(bo={}));var O=Q.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),lt=n=>{switch(typeof n){case"undefined":return O.undefined;case"string":return O.string;case"number":return Number.isNaN(n)?O.nan:O.number;case"boolean":return O.boolean;case"function":return O.function;case"bigint":return O.bigint;case"symbol":return O.symbol;case"object":return Array.isArray(n)?O.array:n===null?O.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?O.promise:typeof Map<"u"&&n instanceof Map?O.map:typeof Set<"u"&&n instanceof Set?O.set:typeof Date<"u"&&n instanceof Date?O.date:O.object;default:return O.unknown}};var I=Q.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),rf=n=>JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:"),Re=class n extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},r={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)r._errors.push(t(o));else{let l=r,u=0;for(;u<o.path.length;){let c=o.path[u];u===o.path.length-1?(l[c]=l[c]||{_errors:[]},l[c]._errors.push(t(o))):l[c]=l[c]||{_errors:[]},l=l[c],u++}}};return s(this),r}static assert(e){if(!(e instanceof n))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Q.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},r=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];t[i]=t[i]||[],t[i].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}};Re.create=n=>new Re(n);var sf=(n,e)=>{let t;switch(n.code){case I.invalid_type:n.received===O.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case I.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,Q.jsonStringifyReplacer)}`;break;case I.unrecognized_keys:t=`Unrecognized key(s) in object: ${Q.joinValues(n.keys,", ")}`;break;case I.invalid_union:t="Invalid input";break;case I.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${Q.joinValues(n.options)}`;break;case I.invalid_enum_value:t=`Invalid enum value. Expected ${Q.joinValues(n.options)}, received '${n.received}'`;break;case I.invalid_arguments:t="Invalid function arguments";break;case I.invalid_return_type:t="Invalid function return type";break;case I.invalid_date:t="Invalid date";break;case I.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:Q.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case I.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case I.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case I.custom:t="Invalid input";break;case I.invalid_intersection_types:t="Intersection results could not be merged";break;case I.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case I.not_finite:t="Number must be finite";break;default:t=e.defaultError,Q.assertNever(n)}return{message:t}},St=sf;var Sl=St;function of(n){Sl=n}function vr(){return Sl}var as=n=>{let{data:e,path:t,errorMaps:r,issueData:s}=n,i=[...t,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let l="",u=r.filter(c=>!!c).slice().reverse();for(let c of u)l=c(o,{data:e,defaultError:l}).message;return{...s,path:i,message:l}},af=[];function P(n,e){let t=vr(),r=as({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===St?void 0:St].filter(s=>!!s)});n.common.issues.push(r)}var be=class n{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let r=[];for(let s of t){if(s.status==="aborted")return B;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let s of t){let i=await s.key,o=await s.value;r.push({key:i,value:o})}return n.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let s of t){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return B;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(r[i.value]=o.value)}return{status:e.value,value:r}}},B=Object.freeze({status:"aborted"}),cn=n=>({status:"dirty",value:n}),_e=n=>({status:"valid",value:n}),qs=n=>n.status==="aborted",Fs=n=>n.status==="dirty",Ft=n=>n.status==="valid",br=n=>typeof Promise<"u"&&n instanceof Promise;var D;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e?.message})(D||(D={}));var Fe=class{constructor(e,t,r,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Tl=(n,e)=>{if(Ft(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new Re(n.common.issues);return this._error=t,this._error}}};function V(n){if(!n)return{};let{errorMap:e,invalid_type_error:t,required_error:r,description:s}=n;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,l)=>{let{message:u}=n;return o.code==="invalid_enum_value"?{message:u??l.defaultError}:typeof l.data>"u"?{message:u??r??l.defaultError}:o.code!=="invalid_type"?{message:l.defaultError}:{message:u??t??l.defaultError}},description:s}}var Y=class{get description(){return this._def.description}_getType(e){return lt(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:lt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new be,ctx:{common:e.parent.common,data:e.data,parsedType:lt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(br(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:lt(e)},s=this._parseSync({data:e,path:r.path,parent:r});return Tl(r,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:lt(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return Ft(r)?{value:r.value}:{issues:t.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(r=>Ft(r)?{value:r.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:lt(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(br(s)?s:Promise.resolve(s));return Tl(r,i)}refine(e,t){let r=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,i)=>{let o=e(s),l=()=>i.addIssue({code:I.custom,...r(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(u=>u?!0:(l(),!1)):o?!0:(l(),!1)})}refinement(e,t){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof t=="function"?t(r,s):t),!1))}_refinement(e){return new Be({schema:this,typeName:K.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return qe.create(this,this._def)}nullable(){return ct.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ct.create(this)}promise(){return Zt.create(this,this._def)}or(e){return yn.create([this,e],this._def)}and(e){return vn.create(this,e,this._def)}transform(e){return new Be({...V(this._def),schema:this,typeName:K.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Sn({...V(this._def),innerType:this,defaultValue:t,typeName:K.ZodDefault})}brand(){return new ls({typeName:K.ZodBranded,type:this,...V(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Tn({...V(this._def),innerType:this,catchValue:t,typeName:K.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return us.create(this,e)}readonly(){return xn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},lf=/^c[^\s-]{8,}$/i,uf=/^[0-9a-z]+$/,cf=/^[0-9A-HJKMNP-TV-Z]{26}$/i,df=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,hf=/^[a-z0-9_-]{21}$/i,ff=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,pf=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,mf=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,gf="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",wo,yf=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,vf=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,bf=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,wf=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,_f=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,kf=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Cl="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Sf=new RegExp(`^${Cl}$`);function Il(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);let t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Tf(n){return new RegExp(`^${Il(n)}$`)}function Rl(n){let e=`${Cl}T${Il(n)}`,t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function xf(n,e){return!!((e==="v4"||!e)&&yf.test(n)||(e==="v6"||!e)&&bf.test(n))}function Cf(n,e){if(!ff.test(n))return!1;try{let[t]=n.split(".");if(!t)return!1;let r=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function If(n,e){return!!((e==="v4"||!e)&&vf.test(n)||(e==="v6"||!e)&&wf.test(n))}var Bt=class n extends Y{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==O.string){let i=this._getOrReturnCtx(e);return P(i,{code:I.invalid_type,expected:O.string,received:i.parsedType}),B}let r=new be,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),P(s,{code:I.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),P(s,{code:I.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,l=e.data.length<i.value;(o||l)&&(s=this._getOrReturnCtx(e,s),o?P(s,{code:I.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):l&&P(s,{code:I.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")mf.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"email",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")wo||(wo=new RegExp(gf,"u")),wo.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"emoji",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")df.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"uuid",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")hf.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"nanoid",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")lf.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"cuid",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")uf.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"cuid2",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")cf.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"ulid",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),P(s,{validation:"url",code:I.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"regex",code:I.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),P(s,{code:I.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),P(s,{code:I.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),P(s,{code:I.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Rl(i).test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{code:I.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?Sf.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{code:I.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Tf(i).test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{code:I.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?pf.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"duration",code:I.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?xf(e.data,i.version)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"ip",code:I.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?Cf(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"jwt",code:I.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?If(e.data,i.version)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"cidr",code:I.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?_f.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"base64",code:I.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?kf.test(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{validation:"base64url",code:I.invalid_string,message:i.message}),r.dirty()):Q.assertNever(i);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(s=>e.test(s),{validation:t,code:I.invalid_string,...D.errToObj(r)})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...D.errToObj(e)})}url(e){return this._addCheck({kind:"url",...D.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...D.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...D.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...D.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...D.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...D.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...D.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...D.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...D.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...D.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...D.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...D.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...D.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...D.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...D.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...D.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...D.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...D.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...D.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...D.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...D.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...D.errToObj(t)})}nonempty(e){return this.min(1,D.errToObj(e))}trim(){return new n({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Bt.create=n=>new Bt({checks:[],typeName:K.ZodString,coerce:n?.coerce??!1,...V(n)});function Rf(n,e){let t=(n.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=t>r?t:r,i=Number.parseInt(n.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var dn=class n extends Y{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==O.number){let i=this._getOrReturnCtx(e);return P(i,{code:I.invalid_type,expected:O.number,received:i.parsedType}),B}let r,s=new be;for(let i of this._def.checks)i.kind==="int"?Q.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{code:I.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),P(r,{code:I.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),P(r,{code:I.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Rf(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),P(r,{code:I.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{code:I.not_finite,message:i.message}),s.dirty()):Q.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,D.toString(t))}gt(e,t){return this.setLimit("min",e,!1,D.toString(t))}lte(e,t){return this.setLimit("max",e,!0,D.toString(t))}lt(e,t){return this.setLimit("max",e,!1,D.toString(t))}setLimit(e,t,r,s){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:D.toString(s)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:D.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:D.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:D.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:D.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:D.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:D.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:D.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:D.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:D.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Q.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(t===null||r.value>t)&&(t=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}};dn.create=n=>new dn({checks:[],typeName:K.ZodNumber,coerce:n?.coerce||!1,...V(n)});var hn=class n extends Y{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==O.bigint)return this._getInvalidInput(e);let r,s=new be;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),P(r,{code:I.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),P(r,{code:I.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),P(r,{code:I.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):Q.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return P(t,{code:I.invalid_type,expected:O.bigint,received:t.parsedType}),B}gte(e,t){return this.setLimit("min",e,!0,D.toString(t))}gt(e,t){return this.setLimit("min",e,!1,D.toString(t))}lte(e,t){return this.setLimit("max",e,!0,D.toString(t))}lt(e,t){return this.setLimit("max",e,!1,D.toString(t))}setLimit(e,t,r,s){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:D.toString(s)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:D.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:D.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:D.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:D.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:D.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};hn.create=n=>new hn({checks:[],typeName:K.ZodBigInt,coerce:n?.coerce??!1,...V(n)});var fn=class extends Y{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==O.boolean){let r=this._getOrReturnCtx(e);return P(r,{code:I.invalid_type,expected:O.boolean,received:r.parsedType}),B}return _e(e.data)}};fn.create=n=>new fn({typeName:K.ZodBoolean,coerce:n?.coerce||!1,...V(n)});var pn=class n extends Y{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==O.date){let i=this._getOrReturnCtx(e);return P(i,{code:I.invalid_type,expected:O.date,received:i.parsedType}),B}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return P(i,{code:I.invalid_date}),B}let r=new be,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),P(s,{code:I.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),P(s,{code:I.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):Q.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:D.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:D.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};pn.create=n=>new pn({checks:[],coerce:n?.coerce||!1,typeName:K.ZodDate,...V(n)});var _r=class extends Y{_parse(e){if(this._getType(e)!==O.symbol){let r=this._getOrReturnCtx(e);return P(r,{code:I.invalid_type,expected:O.symbol,received:r.parsedType}),B}return _e(e.data)}};_r.create=n=>new _r({typeName:K.ZodSymbol,...V(n)});var mn=class extends Y{_parse(e){if(this._getType(e)!==O.undefined){let r=this._getOrReturnCtx(e);return P(r,{code:I.invalid_type,expected:O.undefined,received:r.parsedType}),B}return _e(e.data)}};mn.create=n=>new mn({typeName:K.ZodUndefined,...V(n)});var gn=class extends Y{_parse(e){if(this._getType(e)!==O.null){let r=this._getOrReturnCtx(e);return P(r,{code:I.invalid_type,expected:O.null,received:r.parsedType}),B}return _e(e.data)}};gn.create=n=>new gn({typeName:K.ZodNull,...V(n)});var Kt=class extends Y{constructor(){super(...arguments),this._any=!0}_parse(e){return _e(e.data)}};Kt.create=n=>new Kt({typeName:K.ZodAny,...V(n)});var xt=class extends Y{constructor(){super(...arguments),this._unknown=!0}_parse(e){return _e(e.data)}};xt.create=n=>new xt({typeName:K.ZodUnknown,...V(n)});var Xe=class extends Y{_parse(e){let t=this._getOrReturnCtx(e);return P(t,{code:I.invalid_type,expected:O.never,received:t.parsedType}),B}};Xe.create=n=>new Xe({typeName:K.ZodNever,...V(n)});var kr=class extends Y{_parse(e){if(this._getType(e)!==O.undefined){let r=this._getOrReturnCtx(e);return P(r,{code:I.invalid_type,expected:O.void,received:r.parsedType}),B}return _e(e.data)}};kr.create=n=>new kr({typeName:K.ZodVoid,...V(n)});var Ct=class n extends Y{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==O.array)return P(t,{code:I.invalid_type,expected:O.array,received:t.parsedType}),B;if(s.exactLength!==null){let o=t.data.length>s.exactLength.value,l=t.data.length<s.exactLength.value;(o||l)&&(P(t,{code:o?I.too_big:I.too_small,minimum:l?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(P(t,{code:I.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(P(t,{code:I.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((o,l)=>s.type._parseAsync(new Fe(t,o,t.path,l)))).then(o=>be.mergeArray(r,o));let i=[...t.data].map((o,l)=>s.type._parseSync(new Fe(t,o,t.path,l)));return be.mergeArray(r,i)}get element(){return this._def.type}min(e,t){return new n({...this._def,minLength:{value:e,message:D.toString(t)}})}max(e,t){return new n({...this._def,maxLength:{value:e,message:D.toString(t)}})}length(e,t){return new n({...this._def,exactLength:{value:e,message:D.toString(t)}})}nonempty(e){return this.min(1,e)}};Ct.create=(n,e)=>new Ct({type:n,minLength:null,maxLength:null,exactLength:null,typeName:K.ZodArray,...V(e)});function wr(n){if(n instanceof Ee){let e={};for(let t in n.shape){let r=n.shape[t];e[t]=qe.create(wr(r))}return new Ee({...n._def,shape:()=>e})}else return n instanceof Ct?new Ct({...n._def,type:wr(n.element)}):n instanceof qe?qe.create(wr(n.unwrap())):n instanceof ct?ct.create(wr(n.unwrap())):n instanceof ut?ut.create(n.items.map(e=>wr(e))):n}var Ee=class n extends Y{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=Q.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==O.object){let c=this._getOrReturnCtx(e);return P(c,{code:I.invalid_type,expected:O.object,received:c.parsedType}),B}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),l=[];if(!(this._def.catchall instanceof Xe&&this._def.unknownKeys==="strip"))for(let c in s.data)o.includes(c)||l.push(c);let u=[];for(let c of o){let f=i[c],p=s.data[c];u.push({key:{status:"valid",value:c},value:f._parse(new Fe(s,p,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof Xe){let c=this._def.unknownKeys;if(c==="passthrough")for(let f of l)u.push({key:{status:"valid",value:f},value:{status:"valid",value:s.data[f]}});else if(c==="strict")l.length>0&&(P(s,{code:I.unrecognized_keys,keys:l}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let f of l){let p=s.data[f];u.push({key:{status:"valid",value:f},value:c._parse(new Fe(s,p,s.path,f)),alwaysSet:f in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let c=[];for(let f of u){let p=await f.key,b=await f.value;c.push({key:p,value:b,alwaysSet:f.alwaysSet})}return c}).then(c=>be.mergeObjectSync(r,c)):be.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(e){return D.errToObj,new n({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{let s=this._def.errorMap?.(t,r).message??r.defaultError;return t.code==="unrecognized_keys"?{message:D.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new n({...this._def,unknownKeys:"strip"})}passthrough(){return new n({...this._def,unknownKeys:"passthrough"})}extend(e){return new n({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new n({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:K.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new n({...this._def,catchall:e})}pick(e){let t={};for(let r of Q.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new n({...this._def,shape:()=>t})}omit(e){let t={};for(let r of Q.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new n({...this._def,shape:()=>t})}deepPartial(){return wr(this)}partial(e){let t={};for(let r of Q.objectKeys(this.shape)){let s=this.shape[r];e&&!e[r]?t[r]=s:t[r]=s.optional()}return new n({...this._def,shape:()=>t})}required(e){let t={};for(let r of Q.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof qe;)i=i._def.innerType;t[r]=i}return new n({...this._def,shape:()=>t})}keyof(){return El(Q.objectKeys(this.shape))}};Ee.create=(n,e)=>new Ee({shape:()=>n,unknownKeys:"strip",catchall:Xe.create(),typeName:K.ZodObject,...V(e)});Ee.strictCreate=(n,e)=>new Ee({shape:()=>n,unknownKeys:"strict",catchall:Xe.create(),typeName:K.ZodObject,...V(e)});Ee.lazycreate=(n,e)=>new Ee({shape:n,unknownKeys:"strip",catchall:Xe.create(),typeName:K.ZodObject,...V(e)});var yn=class extends Y{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;function s(i){for(let l of i)if(l.result.status==="valid")return l.result;for(let l of i)if(l.result.status==="dirty")return t.common.issues.push(...l.ctx.common.issues),l.result;let o=i.map(l=>new Re(l.ctx.common.issues));return P(t,{code:I.invalid_union,unionErrors:o}),B}if(t.common.async)return Promise.all(r.map(async i=>{let o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let u of r){let c={...t,common:{...t.common,issues:[]},parent:null},f=u._parseSync({data:t.data,path:t.path,parent:c});if(f.status==="valid")return f;f.status==="dirty"&&!i&&(i={result:f,ctx:c}),c.common.issues.length&&o.push(c.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let l=o.map(u=>new Re(u));return P(t,{code:I.invalid_union,unionErrors:l}),B}}get options(){return this._def.options}};yn.create=(n,e)=>new yn({options:n,typeName:K.ZodUnion,...V(e)});var Tt=n=>n instanceof bn?Tt(n.schema):n instanceof Be?Tt(n.innerType()):n instanceof wn?[n.value]:n instanceof _n?n.options:n instanceof kn?Q.objectValues(n.enum):n instanceof Sn?Tt(n._def.innerType):n instanceof mn?[void 0]:n instanceof gn?[null]:n instanceof qe?[void 0,...Tt(n.unwrap())]:n instanceof ct?[null,...Tt(n.unwrap())]:n instanceof ls||n instanceof xn?Tt(n.unwrap()):n instanceof Tn?Tt(n._def.innerType):[],Bs=class n extends Y{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==O.object)return P(t,{code:I.invalid_type,expected:O.object,received:t.parsedType}),B;let r=this.discriminator,s=t.data[r],i=this.optionsMap.get(s);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(P(t,{code:I.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),B)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let s=new Map;for(let i of t){let o=Tt(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let l of o){if(s.has(l))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(l)}`);s.set(l,i)}}return new n({typeName:K.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...V(r)})}};function _o(n,e){let t=lt(n),r=lt(e);if(n===e)return{valid:!0,data:n};if(t===O.object&&r===O.object){let s=Q.objectKeys(e),i=Q.objectKeys(n).filter(l=>s.indexOf(l)!==-1),o={...n,...e};for(let l of i){let u=_o(n[l],e[l]);if(!u.valid)return{valid:!1};o[l]=u.data}return{valid:!0,data:o}}else if(t===O.array&&r===O.array){if(n.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<n.length;i++){let o=n[i],l=e[i],u=_o(o,l);if(!u.valid)return{valid:!1};s.push(u.data)}return{valid:!0,data:s}}else return t===O.date&&r===O.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}var vn=class extends Y{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),s=(i,o)=>{if(qs(i)||qs(o))return B;let l=_o(i.value,o.value);return l.valid?((Fs(i)||Fs(o))&&t.dirty(),{status:t.value,value:l.data}):(P(r,{code:I.invalid_intersection_types}),B)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};vn.create=(n,e,t)=>new vn({left:n,right:e,typeName:K.ZodIntersection,...V(t)});var ut=class n extends Y{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==O.array)return P(r,{code:I.invalid_type,expected:O.array,received:r.parsedType}),B;if(r.data.length<this._def.items.length)return P(r,{code:I.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),B;!this._def.rest&&r.data.length>this._def.items.length&&(P(r,{code:I.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...r.data].map((o,l)=>{let u=this._def.items[l]||this._def.rest;return u?u._parse(new Fe(r,o,r.path,l)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>be.mergeArray(t,o)):be.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new n({...this._def,rest:e})}};ut.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ut({items:n,typeName:K.ZodTuple,rest:null,...V(e)})};var Ks=class n extends Y{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==O.object)return P(r,{code:I.invalid_type,expected:O.object,received:r.parsedType}),B;let s=[],i=this._def.keyType,o=this._def.valueType;for(let l in r.data)s.push({key:i._parse(new Fe(r,l,r.path,l)),value:o._parse(new Fe(r,r.data[l],r.path,l)),alwaysSet:l in r.data});return r.common.async?be.mergeObjectAsync(t,s):be.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,r){return t instanceof Y?new n({keyType:e,valueType:t,typeName:K.ZodRecord,...V(r)}):new n({keyType:Bt.create(),valueType:e,typeName:K.ZodRecord,...V(t)})}},Sr=class extends Y{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==O.map)return P(r,{code:I.invalid_type,expected:O.map,received:r.parsedType}),B;let s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([l,u],c)=>({key:s._parse(new Fe(r,l,r.path,[c,"key"])),value:i._parse(new Fe(r,u,r.path,[c,"value"]))}));if(r.common.async){let l=new Map;return Promise.resolve().then(async()=>{for(let u of o){let c=await u.key,f=await u.value;if(c.status==="aborted"||f.status==="aborted")return B;(c.status==="dirty"||f.status==="dirty")&&t.dirty(),l.set(c.value,f.value)}return{status:t.value,value:l}})}else{let l=new Map;for(let u of o){let c=u.key,f=u.value;if(c.status==="aborted"||f.status==="aborted")return B;(c.status==="dirty"||f.status==="dirty")&&t.dirty(),l.set(c.value,f.value)}return{status:t.value,value:l}}}};Sr.create=(n,e,t)=>new Sr({valueType:e,keyType:n,typeName:K.ZodMap,...V(t)});var Tr=class n extends Y{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==O.set)return P(r,{code:I.invalid_type,expected:O.set,received:r.parsedType}),B;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(P(r,{code:I.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(P(r,{code:I.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let i=this._def.valueType;function o(u){let c=new Set;for(let f of u){if(f.status==="aborted")return B;f.status==="dirty"&&t.dirty(),c.add(f.value)}return{status:t.value,value:c}}let l=[...r.data.values()].map((u,c)=>i._parse(new Fe(r,u,r.path,c)));return r.common.async?Promise.all(l).then(u=>o(u)):o(l)}min(e,t){return new n({...this._def,minSize:{value:e,message:D.toString(t)}})}max(e,t){return new n({...this._def,maxSize:{value:e,message:D.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Tr.create=(n,e)=>new Tr({valueType:n,minSize:null,maxSize:null,typeName:K.ZodSet,...V(e)});var Zs=class n extends Y{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==O.function)return P(t,{code:I.invalid_type,expected:O.function,received:t.parsedType}),B;function r(l,u){return as({data:l,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,vr(),St].filter(c=>!!c),issueData:{code:I.invalid_arguments,argumentsError:u}})}function s(l,u){return as({data:l,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,vr(),St].filter(c=>!!c),issueData:{code:I.invalid_return_type,returnTypeError:u}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof Zt){let l=this;return _e(async function(...u){let c=new Re([]),f=await l._def.args.parseAsync(u,i).catch(w=>{throw c.addIssue(r(u,w)),c}),p=await Reflect.apply(o,this,f);return await l._def.returns._def.type.parseAsync(p,i).catch(w=>{throw c.addIssue(s(p,w)),c})})}else{let l=this;return _e(function(...u){let c=l._def.args.safeParse(u,i);if(!c.success)throw new Re([r(u,c.error)]);let f=Reflect.apply(o,this,c.data),p=l._def.returns.safeParse(f,i);if(!p.success)throw new Re([s(f,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new n({...this._def,args:ut.create(e).rest(xt.create())})}returns(e){return new n({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new n({args:e||ut.create([]).rest(xt.create()),returns:t||xt.create(),typeName:K.ZodFunction,...V(r)})}},bn=class extends Y{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};bn.create=(n,e)=>new bn({getter:n,typeName:K.ZodLazy,...V(e)});var wn=class extends Y{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return P(t,{received:t.data,code:I.invalid_literal,expected:this._def.value}),B}return{status:"valid",value:e.data}}get value(){return this._def.value}};wn.create=(n,e)=>new wn({value:n,typeName:K.ZodLiteral,...V(e)});function El(n,e){return new _n({values:n,typeName:K.ZodEnum,...V(e)})}var _n=class n extends Y{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),r=this._def.values;return P(t,{expected:Q.joinValues(r),received:t.parsedType,code:I.invalid_type}),B}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return P(t,{received:t.data,code:I.invalid_enum_value,options:r}),B}return _e(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return n.create(e,{...this._def,...t})}exclude(e,t=this._def){return n.create(this.options.filter(r=>!e.includes(r)),{...this._def,...t})}};_n.create=El;var kn=class extends Y{_parse(e){let t=Q.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==O.string&&r.parsedType!==O.number){let s=Q.objectValues(t);return P(r,{expected:Q.joinValues(s),received:r.parsedType,code:I.invalid_type}),B}if(this._cache||(this._cache=new Set(Q.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=Q.objectValues(t);return P(r,{received:r.data,code:I.invalid_enum_value,options:s}),B}return _e(e.data)}get enum(){return this._def.values}};kn.create=(n,e)=>new kn({values:n,typeName:K.ZodNativeEnum,...V(e)});var Zt=class extends Y{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==O.promise&&t.common.async===!1)return P(t,{code:I.invalid_type,expected:O.promise,received:t.parsedType}),B;let r=t.parsedType===O.promise?t.data:Promise.resolve(t.data);return _e(r.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};Zt.create=(n,e)=>new Zt({type:n,typeName:K.ZodPromise,...V(e)});var Be=class extends Y{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===K.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{P(r,o),o.fatal?t.abort():t.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(r.data,i);if(r.common.async)return Promise.resolve(o).then(async l=>{if(t.value==="aborted")return B;let u=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return u.status==="aborted"?B:u.status==="dirty"?cn(u.value):t.value==="dirty"?cn(u.value):u});{if(t.value==="aborted")return B;let l=this._def.schema._parseSync({data:o,path:r.path,parent:r});return l.status==="aborted"?B:l.status==="dirty"?cn(l.value):t.value==="dirty"?cn(l.value):l}}if(s.type==="refinement"){let o=l=>{let u=s.refinement(l,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){let l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?B:(l.status==="dirty"&&t.dirty(),o(l.value),{status:t.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?B:(l.status==="dirty"&&t.dirty(),o(l.value).then(()=>({status:t.value,value:l.value}))))}if(s.type==="transform")if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Ft(o))return B;let l=s.transform(o.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>Ft(o)?Promise.resolve(s.transform(o.value,i)).then(l=>({status:t.value,value:l})):B);Q.assertNever(s)}};Be.create=(n,e,t)=>new Be({schema:n,typeName:K.ZodEffects,effect:e,...V(t)});Be.createWithPreprocess=(n,e,t)=>new Be({schema:e,effect:{type:"preprocess",transform:n},typeName:K.ZodEffects,...V(t)});var qe=class extends Y{_parse(e){return this._getType(e)===O.undefined?_e(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};qe.create=(n,e)=>new qe({innerType:n,typeName:K.ZodOptional,...V(e)});var ct=class extends Y{_parse(e){return this._getType(e)===O.null?_e(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ct.create=(n,e)=>new ct({innerType:n,typeName:K.ZodNullable,...V(e)});var Sn=class extends Y{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return t.parsedType===O.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Sn.create=(n,e)=>new Sn({innerType:n,typeName:K.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...V(e)});var Tn=class extends Y{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return br(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Re(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Re(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Tn.create=(n,e)=>new Tn({innerType:n,typeName:K.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...V(e)});var xr=class extends Y{_parse(e){if(this._getType(e)!==O.nan){let r=this._getOrReturnCtx(e);return P(r,{code:I.invalid_type,expected:O.nan,received:r.parsedType}),B}return{status:"valid",value:e.data}}};xr.create=n=>new xr({typeName:K.ZodNaN,...V(n)});var Ef=Symbol("zod_brand"),ls=class extends Y{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}},us=class n extends Y{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?B:i.status==="dirty"?(t.dirty(),cn(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?B:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,t){return new n({in:e,out:t,typeName:K.ZodPipeline})}},xn=class extends Y{_parse(e){let t=this._def.innerType._parse(e),r=s=>(Ft(s)&&(s.value=Object.freeze(s.value)),s);return br(t)?t.then(s=>r(s)):r(t)}unwrap(){return this._def.innerType}};xn.create=(n,e)=>new xn({innerType:n,typeName:K.ZodReadonly,...V(e)});function xl(n,e){let t=typeof n=="function"?n(e):typeof n=="string"?{message:n}:n;return typeof t=="string"?{message:t}:t}function Al(n,e={},t){return n?Kt.create().superRefine((r,s)=>{let i=n(r);if(i instanceof Promise)return i.then(o=>{if(!o){let l=xl(e,r),u=l.fatal??t??!0;s.addIssue({code:"custom",...l,fatal:u})}});if(!i){let o=xl(e,r),l=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:l})}}):Kt.create()}var Af={object:Ee.lazycreate},K;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(K||(K={}));var $f=(n,e={message:`Input not instance of ${n.name}`})=>Al(t=>t instanceof n,e),$l=Bt.create,Pl=dn.create,Pf=xr.create,jf=hn.create,jl=fn.create,Of=pn.create,Nf=_r.create,Mf=mn.create,zf=gn.create,Df=Kt.create,Lf=xt.create,Uf=Xe.create,qf=kr.create,Ff=Ct.create,Bf=Ee.create,Kf=Ee.strictCreate,Zf=yn.create,Gf=Bs.create,Hf=vn.create,Vf=ut.create,Wf=Ks.create,Jf=Sr.create,Yf=Tr.create,Xf=Zs.create,Qf=bn.create,ep=wn.create,tp=_n.create,np=kn.create,rp=Zt.create,sp=Be.create,ip=qe.create,op=ct.create,ap=Be.createWithPreprocess,lp=us.create,up=()=>$l().optional(),cp=()=>Pl().optional(),dp=()=>jl().optional(),hp={string:(n=>Bt.create({...n,coerce:!0})),number:(n=>dn.create({...n,coerce:!0})),boolean:(n=>fn.create({...n,coerce:!0})),bigint:(n=>hn.create({...n,coerce:!0})),date:(n=>pn.create({...n,coerce:!0}))};var fp=B;var Ol=k.object({baseUrl:k.string().url(),email:k.string().email(),apiToken:k.string().min(1)}),ko=k.object({controlPlaneUrl:k.string().url(),runnerId:k.string().optional(),runnerToken:k.string().optional(),runnerName:k.string().default(Gs.default.hostname()),jira:Ol.optional(),repos:k.record(k.object({path:k.string(),jira:Ol.optional(),github:k.object({token:k.string().min(1),login:k.string().optional()}).optional()})).default({}),github:k.object({token:k.string().min(1),login:k.string().optional()}).optional(),githubUsers:k.record(k.object({token:k.string().min(1),login:k.string().optional()})).default({}),deploy:k.object({enabled:k.boolean().default(!1)}).default({enabled:!1}),environments:k.record(k.object({secrets:k.record(k.string()).default({})})).default({}),claudeProfiles:k.record(k.object({configDir:k.string()})).default({}),claudeBin:k.string().default("claude"),agents:k.record(k.object({bin:k.string()})).default({}),jiraUsers:k.record(k.object({email:k.string().email(),apiToken:k.string().min(1)})).default({}),auditSchedules:k.array(k.object({repoName:k.string(),role:k.enum(["security","testing"]),intervalHours:k.number().int().min(6).max(720)})).default([]),pollIntervalSeconds:k.number().int().min(10).max(600).default(30)});function re(){let n=process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR;if(n)return n;let e=Hs.default.join(Gs.default.homedir(),".config","allwright"),t=Hs.default.join(Gs.default.homedir(),".config","ticketpilot");return!It.default.existsSync(e)&&It.default.existsSync(t)?t:e}function Gt(){return Hs.default.join(re(),"runner.json")}function me(){let n=Gt();if(!It.default.existsSync(n))return null;let e=JSON.parse(It.default.readFileSync(n,"utf8"));return ko.parse(e)}function fe(n){let e=re();It.default.mkdirSync(e,{recursive:!0,mode:448});let t=Gt(),r=t+".tmp";It.default.writeFileSync(r,JSON.stringify(n,null,2)+`
262
- `,{mode:384}),It.default.renameSync(r,t),It.default.chmodSync(t,384)}function Vs(n,e){return`${n}:${e}`}function Cn(n,e,t){return n.environments[Vs(e,t)]?.secrets??{}}function ie(){let n=me();if(!n)throw new Error(`No runner config found at ${Gt()}. Run \`allwright init\` first.`);return n}var Ws=require("node:child_process"),Oe=R(require("node:fs"),1),Js=R(require("node:path"),1);var pp=new Set(["runner.log","runner.pid"]);function mp(n){return Oe.default.readdirSync(n).filter(e=>!pp.has(e)&&!/\.bak-\d+$/.test(e)).sort()}function Nl(n){let e=re();if(!Oe.default.existsSync(e))throw new Error(`nothing to export - ${e} does not exist`);let t=mp(e);if(!t.length)throw new Error(`nothing to export - ${e} is empty`);let r=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),s=Js.default.resolve(n||`ticketpilot-backup-${r}.tgz`);return Oe.default.writeFileSync(s,"",{mode:384}),(0,Ws.execFileSync)("tar",["-czf",s,"-C",e,...t]),Oe.default.chmodSync(s,384),{file:s,entries:t}}function Ml(n){let e=Js.default.resolve(n);if(!Oe.default.existsSync(e))throw new Error(`backup file not found: ${e}`);let t=(0,Ws.execFileSync)("tar",["-tzf",e],{encoding:"utf8"}).split(`
263
- `).filter(Boolean);for(let i of t)if(i.startsWith("/")||i.split("/").includes(".."))throw new Error(`refusing to import - unsafe path in archive: ${i}`);let r=re(),s;Oe.default.existsSync(r)&&Oe.default.readdirSync(r).length&&(s=`${r}.bak-${Date.now()}`,Oe.default.renameSync(r,s)),Oe.default.mkdirSync(r,{recursive:!0,mode:448}),(0,Ws.execFileSync)("tar",["-xzf",e,"-C",r]);for(let i of Oe.default.readdirSync(r)){let o=Js.default.join(r,i);Oe.default.statSync(o).isFile()&&Oe.default.chmodSync(o,384)}return{restored:t.map(i=>i.replace(/\/$/,"")).sort(),previousDir:s}}var Cr=R(require("node:fs"),1),Ht=R(require("node:path"),1),Ys=".ticketpilot-attachments",gp=15*1024*1024,yp=50*1024*1024,zl=20;function Dl(n,e){let t=Ht.default.basename(n).replace(/[^\w.\- ()]/g,"_").replace(/^\.+/,"").slice(-100)||"file",r=t,s=1;for(;e.has(r);)r=`${s++}-${t}`;return e.add(r),r}async function Ir(n,e,t,r){if(!e.length)return"";let s=Ht.default.join(t,Ys);Cr.default.mkdirSync(s,{recursive:!0});let i=new Set,o=[],l=0;for(let u of e){if(o.length>=zl){r("warn",`attachment cap reached (${zl} files) - skipping the rest`);break}if(u.size>gp){r("warn",`skipping attachment "${u.filename}" - ${wp(u.size)} MB exceeds the 15 MB limit`);continue}if(l+u.size>yp){r("warn",`attachment size budget reached - skipping "${u.filename}" and the rest`);break}try{let c=await n.downloadAttachment(u.contentUrl),f=Dl(u.filename,i);Cr.default.writeFileSync(Ht.default.join(s,f),c),l+=c.length,o.push(`- ${Ys}/${f} (${u.mimeType||"unknown type"}, ${So(c.length)} KB)`),r("info",`Downloaded attachment "${u.filename}" (${So(c.length)} KB)`)}catch(c){r("warn",`could not download attachment "${u.filename}": ${c instanceof Error?c.message:c}`)}}return o.length?`
261
+ `+t)}function yr(n,e,t,r,s,i){if(n.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,yr),n.emit("wsClientError",o,t,e)}else zs(t,r,s,i)}});var Fh={};Fs(Fh,{buildSetupReport:()=>ob,claudeLoggedIn:()=>qh,repoDefaultBranch:()=>Uh});function Uh(n){let e=(...s)=>{try{return(0,so.execFileSync)("git",["-C",n,...s],{encoding:"utf8",timeout:1e4}).trim()}catch{return null}},t=e("symbolic-ref","--short","refs/remotes/origin/HEAD");if(t?.startsWith("origin/"))return t.slice(7);let r=e("rev-parse","--abbrev-ref","HEAD");return r&&r!=="HEAD"?r:""}function qh(n=Dh.default.homedir()){if(dn.default.existsSync(br.default.join(n,".claude",".credentials.json")))return!0;try{return!!JSON.parse(dn.default.readFileSync(br.default.join(n,".claude.json"),"utf8")).oauthAccount}catch{return!1}}async function ob(n,e){let t=!1,r="";if(Us&&Date.now()-Us.at<6e4)t=Us.installed,r=Us.version;else{try{let{stdout:o}=await ib(n.claudeBin,["--version"],{timeout:1e4});t=!0,r=o.trim().slice(0,60)}catch{t=!1}Us={at:Date.now(),installed:t,version:r}}let s=e.map(o=>{let l=n.repos[o];if(!l)return{repoName:o,mapped:!1,pathExists:!1,isGit:!1,claudeMd:!1,deployMd:!1,testMd:!1,githubToken:!1,githubTokenOwn:!1,defaultBranch:""};let u=dn.default.existsSync(l.path);return{repoName:o,mapped:!0,pathExists:u,isGit:u&&dn.default.existsSync(br.default.join(l.path,".git")),claudeMd:u&&dn.default.existsSync(br.default.join(l.path,"CLAUDE.md")),deployMd:u&&dn.default.existsSync(br.default.join(l.path,"DEPLOY.md")),testMd:u&&dn.default.existsSync(br.default.join(l.path,"TEST.md")),githubToken:!!Te(n,o),githubTokenOwn:!!l.github?.token,defaultBranch:u?Uh(l.path):""}}),i=Object.values(n.repos).find(o=>o.github?.token);return{jiraConfigured:!!n.jira,jiraEmail:n.jira?.email??"",claude:{installed:t,version:r,loggedIn:qh()},githubTokenSet:!!(n.github?.token||i),githubLogin:n.github?.login??i?.github?.login??"",deploysEnabled:n.deploy.enabled,jiraUserCount:Object.keys(n.jiraUsers).length,repos:s}}var so,dn,Dh,br,Lh,ib,Us,Bh=qs(()=>{"use strict";so=require("node:child_process"),dn=R(require("node:fs"),1),Dh=R(require("node:os"),1),br=R(require("node:path"),1),Lh=require("node:util");Xn();ib=(0,Lh.promisify)(so.execFile);Us=null});var ut=R(require("node:fs"),1),ul=R(require("node:os"),1),as=R(require("node:path"),1),Kt=require("node:child_process"),io=require("node:crypto"),hn=R(require("node:readline/promises"),1);var Rl=R(Il(),1),{program:gb,createCommand:yb,createArgument:vb,createOption:bb,CommanderError:wb,InvalidArgumentError:_b,InvalidOptionArgumentError:kb,Command:El,Argument:Sb,Option:Tb,Help:xb}=Rl.default;var Et=R(require("node:fs"),1),Js=R(require("node:os"),1),Ys=R(require("node:path"),1);var k={};Fs(k,{BRAND:()=>Lf,DIRTY:()=>fn,EMPTY_PATH:()=>yf,INVALID:()=>F,NEVER:()=>Sp,OK:()=>_e,ParseStatus:()=>be,Schema:()=>Y,ZodAny:()=>Ht,ZodArray:()=>Rt,ZodBigInt:()=>mn,ZodBoolean:()=>gn,ZodBranded:()=>fs,ZodCatch:()=>In,ZodDate:()=>yn,ZodDefault:()=>Cn,ZodDiscriminatedUnion:()=>Hs,ZodEffects:()=>Ge,ZodEnum:()=>Tn,ZodError:()=>Ae,ZodFirstPartyTypeKind:()=>Z,ZodFunction:()=>Ws,ZodIntersection:()=>_n,ZodIssueCode:()=>I,ZodLazy:()=>kn,ZodLiteral:()=>Sn,ZodMap:()=>Ir,ZodNaN:()=>Er,ZodNativeEnum:()=>xn,ZodNever:()=>et,ZodNull:()=>bn,ZodNullable:()=>ht,ZodNumber:()=>pn,ZodObject:()=>$e,ZodOptional:()=>Ke,ZodParsedType:()=>O,ZodPipeline:()=>ps,ZodPromise:()=>Vt,ZodReadonly:()=>Rn,ZodRecord:()=>Vs,ZodSchema:()=>Y,ZodSet:()=>Rr,ZodString:()=>Gt,ZodSymbol:()=>xr,ZodTransformer:()=>Ge,ZodTuple:()=>dt,ZodType:()=>Y,ZodUndefined:()=>vn,ZodUnion:()=>wn,ZodUnknown:()=>It,ZodVoid:()=>Cr,addIssueToContext:()=>j,any:()=>Vf,array:()=>Xf,bigint:()=>Bf,boolean:()=>Ul,coerce:()=>kp,custom:()=>zl,date:()=>Kf,datetimeRegex:()=>Nl,defaultErrorMap:()=>xt,discriminatedUnion:()=>np,effect:()=>pp,enum:()=>dp,function:()=>lp,getErrorMap:()=>kr,getParsedType:()=>ct,instanceof:()=>qf,intersection:()=>rp,isAborted:()=>Zs,isAsync:()=>Sr,isDirty:()=>Gs,isValid:()=>Zt,late:()=>Uf,lazy:()=>up,literal:()=>cp,makeIssue:()=>hs,map:()=>op,nan:()=>Ff,nativeEnum:()=>hp,never:()=>Jf,null:()=>Hf,nullable:()=>gp,number:()=>Ll,object:()=>Qf,objectUtil:()=>To,oboolean:()=>_p,onumber:()=>wp,optional:()=>mp,ostring:()=>bp,pipeline:()=>vp,preprocess:()=>yp,promise:()=>fp,quotelessJson:()=>pf,record:()=>ip,set:()=>ap,setErrorMap:()=>gf,strictObject:()=>ep,string:()=>Dl,symbol:()=>Zf,transformer:()=>pp,tuple:()=>sp,undefined:()=>Gf,union:()=>tp,unknown:()=>Wf,util:()=>Q,void:()=>Yf});var Q;(function(n){n.assertEqual=s=>{};function e(s){}n.assertIs=e;function t(s){throw new Error}n.assertNever=t,n.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},n.getValidEnumValues=s=>{let i=n.objectKeys(s).filter(l=>typeof s[s[l]]!="number"),o={};for(let l of i)o[l]=s[l];return n.objectValues(o)},n.objectValues=s=>n.objectKeys(s).map(function(i){return s[i]}),n.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},n.find=(s,i)=>{for(let o of s)if(i(o))return o},n.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}n.joinValues=r,n.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(Q||(Q={}));var To;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(To||(To={}));var O=Q.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ct=n=>{switch(typeof n){case"undefined":return O.undefined;case"string":return O.string;case"number":return Number.isNaN(n)?O.nan:O.number;case"boolean":return O.boolean;case"function":return O.function;case"bigint":return O.bigint;case"symbol":return O.symbol;case"object":return Array.isArray(n)?O.array:n===null?O.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?O.promise:typeof Map<"u"&&n instanceof Map?O.map:typeof Set<"u"&&n instanceof Set?O.set:typeof Date<"u"&&n instanceof Date?O.date:O.object;default:return O.unknown}};var I=Q.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),pf=n=>JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:"),Ae=class n extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},r={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)r._errors.push(t(o));else{let l=r,u=0;for(;u<o.path.length;){let c=o.path[u];u===o.path.length-1?(l[c]=l[c]||{_errors:[]},l[c]._errors.push(t(o))):l[c]=l[c]||{_errors:[]},l=l[c],u++}}};return s(this),r}static assert(e){if(!(e instanceof n))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Q.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},r=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];t[i]=t[i]||[],t[i].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}};Ae.create=n=>new Ae(n);var mf=(n,e)=>{let t;switch(n.code){case I.invalid_type:n.received===O.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case I.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,Q.jsonStringifyReplacer)}`;break;case I.unrecognized_keys:t=`Unrecognized key(s) in object: ${Q.joinValues(n.keys,", ")}`;break;case I.invalid_union:t="Invalid input";break;case I.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${Q.joinValues(n.options)}`;break;case I.invalid_enum_value:t=`Invalid enum value. Expected ${Q.joinValues(n.options)}, received '${n.received}'`;break;case I.invalid_arguments:t="Invalid function arguments";break;case I.invalid_return_type:t="Invalid function return type";break;case I.invalid_date:t="Invalid date";break;case I.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:Q.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case I.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case I.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case I.custom:t="Invalid input";break;case I.invalid_intersection_types:t="Intersection results could not be merged";break;case I.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case I.not_finite:t="Number must be finite";break;default:t=e.defaultError,Q.assertNever(n)}return{message:t}},xt=mf;var Al=xt;function gf(n){Al=n}function kr(){return Al}var hs=n=>{let{data:e,path:t,errorMaps:r,issueData:s}=n,i=[...t,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let l="",u=r.filter(c=>!!c).slice().reverse();for(let c of u)l=c(o,{data:e,defaultError:l}).message;return{...s,path:i,message:l}},yf=[];function j(n,e){let t=kr(),r=hs({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===xt?void 0:xt].filter(s=>!!s)});n.common.issues.push(r)}var be=class n{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let r=[];for(let s of t){if(s.status==="aborted")return F;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let s of t){let i=await s.key,o=await s.value;r.push({key:i,value:o})}return n.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let s of t){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return F;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(r[i.value]=o.value)}return{status:e.value,value:r}}},F=Object.freeze({status:"aborted"}),fn=n=>({status:"dirty",value:n}),_e=n=>({status:"valid",value:n}),Zs=n=>n.status==="aborted",Gs=n=>n.status==="dirty",Zt=n=>n.status==="valid",Sr=n=>typeof Promise<"u"&&n instanceof Promise;var z;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e?.message})(z||(z={}));var Ze=class{constructor(e,t,r,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},$l=(n,e)=>{if(Zt(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new Ae(n.common.issues);return this._error=t,this._error}}};function V(n){if(!n)return{};let{errorMap:e,invalid_type_error:t,required_error:r,description:s}=n;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,l)=>{let{message:u}=n;return o.code==="invalid_enum_value"?{message:u??l.defaultError}:typeof l.data>"u"?{message:u??r??l.defaultError}:o.code!=="invalid_type"?{message:l.defaultError}:{message:u??t??l.defaultError}},description:s}}var Y=class{get description(){return this._def.description}_getType(e){return ct(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ct(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new be,ctx:{common:e.parent.common,data:e.data,parsedType:ct(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Sr(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ct(e)},s=this._parseSync({data:e,path:r.path,parent:r});return $l(r,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ct(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return Zt(r)?{value:r.value}:{issues:t.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(r=>Zt(r)?{value:r.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ct(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(Sr(s)?s:Promise.resolve(s));return $l(r,i)}refine(e,t){let r=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,i)=>{let o=e(s),l=()=>i.addIssue({code:I.custom,...r(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(u=>u?!0:(l(),!1)):o?!0:(l(),!1)})}refinement(e,t){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof t=="function"?t(r,s):t),!1))}_refinement(e){return new Ge({schema:this,typeName:Z.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return Ke.create(this,this._def)}nullable(){return ht.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Rt.create(this)}promise(){return Vt.create(this,this._def)}or(e){return wn.create([this,e],this._def)}and(e){return _n.create(this,e,this._def)}transform(e){return new Ge({...V(this._def),schema:this,typeName:Z.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Cn({...V(this._def),innerType:this,defaultValue:t,typeName:Z.ZodDefault})}brand(){return new fs({typeName:Z.ZodBranded,type:this,...V(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new In({...V(this._def),innerType:this,catchValue:t,typeName:Z.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ps.create(this,e)}readonly(){return Rn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},vf=/^c[^\s-]{8,}$/i,bf=/^[0-9a-z]+$/,wf=/^[0-9A-HJKMNP-TV-Z]{26}$/i,_f=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,kf=/^[a-z0-9_-]{21}$/i,Sf=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Tf=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,xf=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Cf="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",xo,If=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Rf=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Ef=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Af=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,$f=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Pf=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,jl="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",jf=new RegExp(`^${jl}$`);function Ol(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);let t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Of(n){return new RegExp(`^${Ol(n)}$`)}function Nl(n){let e=`${jl}T${Ol(n)}`,t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Nf(n,e){return!!((e==="v4"||!e)&&If.test(n)||(e==="v6"||!e)&&Ef.test(n))}function Mf(n,e){if(!Sf.test(n))return!1;try{let[t]=n.split(".");if(!t)return!1;let r=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function zf(n,e){return!!((e==="v4"||!e)&&Rf.test(n)||(e==="v6"||!e)&&Af.test(n))}var Gt=class n extends Y{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==O.string){let i=this._getOrReturnCtx(e);return j(i,{code:I.invalid_type,expected:O.string,received:i.parsedType}),F}let r=new be,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),j(s,{code:I.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),j(s,{code:I.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,l=e.data.length<i.value;(o||l)&&(s=this._getOrReturnCtx(e,s),o?j(s,{code:I.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):l&&j(s,{code:I.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")xf.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"email",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")xo||(xo=new RegExp(Cf,"u")),xo.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"emoji",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")_f.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"uuid",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")kf.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"nanoid",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")vf.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"cuid",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")bf.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"cuid2",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")wf.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"ulid",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),j(s,{validation:"url",code:I.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"regex",code:I.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),j(s,{code:I.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),j(s,{code:I.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),j(s,{code:I.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Nl(i).test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{code:I.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?jf.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{code:I.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Of(i).test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{code:I.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?Tf.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"duration",code:I.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?Nf(e.data,i.version)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"ip",code:I.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?Mf(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"jwt",code:I.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?zf(e.data,i.version)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"cidr",code:I.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?$f.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"base64",code:I.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?Pf.test(e.data)||(s=this._getOrReturnCtx(e,s),j(s,{validation:"base64url",code:I.invalid_string,message:i.message}),r.dirty()):Q.assertNever(i);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(s=>e.test(s),{validation:t,code:I.invalid_string,...z.errToObj(r)})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...z.errToObj(e)})}url(e){return this._addCheck({kind:"url",...z.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...z.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...z.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...z.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...z.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...z.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...z.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...z.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...z.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...z.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...z.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...z.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...z.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...z.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...z.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...z.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...z.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...z.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...z.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...z.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...z.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...z.errToObj(t)})}nonempty(e){return this.min(1,z.errToObj(e))}trim(){return new n({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Gt.create=n=>new Gt({checks:[],typeName:Z.ZodString,coerce:n?.coerce??!1,...V(n)});function Df(n,e){let t=(n.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=t>r?t:r,i=Number.parseInt(n.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var pn=class n extends Y{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==O.number){let i=this._getOrReturnCtx(e);return j(i,{code:I.invalid_type,expected:O.number,received:i.parsedType}),F}let r,s=new be;for(let i of this._def.checks)i.kind==="int"?Q.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),j(r,{code:I.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),j(r,{code:I.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),j(r,{code:I.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Df(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),j(r,{code:I.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),j(r,{code:I.not_finite,message:i.message}),s.dirty()):Q.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,z.toString(t))}gt(e,t){return this.setLimit("min",e,!1,z.toString(t))}lte(e,t){return this.setLimit("max",e,!0,z.toString(t))}lt(e,t){return this.setLimit("max",e,!1,z.toString(t))}setLimit(e,t,r,s){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:z.toString(s)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:z.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:z.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:z.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:z.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:z.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:z.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Q.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(t===null||r.value>t)&&(t=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}};pn.create=n=>new pn({checks:[],typeName:Z.ZodNumber,coerce:n?.coerce||!1,...V(n)});var mn=class n extends Y{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==O.bigint)return this._getInvalidInput(e);let r,s=new be;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),j(r,{code:I.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),j(r,{code:I.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),j(r,{code:I.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):Q.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return j(t,{code:I.invalid_type,expected:O.bigint,received:t.parsedType}),F}gte(e,t){return this.setLimit("min",e,!0,z.toString(t))}gt(e,t){return this.setLimit("min",e,!1,z.toString(t))}lte(e,t){return this.setLimit("max",e,!0,z.toString(t))}lt(e,t){return this.setLimit("max",e,!1,z.toString(t))}setLimit(e,t,r,s){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:z.toString(s)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:z.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:z.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};mn.create=n=>new mn({checks:[],typeName:Z.ZodBigInt,coerce:n?.coerce??!1,...V(n)});var gn=class extends Y{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==O.boolean){let r=this._getOrReturnCtx(e);return j(r,{code:I.invalid_type,expected:O.boolean,received:r.parsedType}),F}return _e(e.data)}};gn.create=n=>new gn({typeName:Z.ZodBoolean,coerce:n?.coerce||!1,...V(n)});var yn=class n extends Y{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==O.date){let i=this._getOrReturnCtx(e);return j(i,{code:I.invalid_type,expected:O.date,received:i.parsedType}),F}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return j(i,{code:I.invalid_date}),F}let r=new be,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),j(s,{code:I.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),j(s,{code:I.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):Q.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:z.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:z.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};yn.create=n=>new yn({checks:[],coerce:n?.coerce||!1,typeName:Z.ZodDate,...V(n)});var xr=class extends Y{_parse(e){if(this._getType(e)!==O.symbol){let r=this._getOrReturnCtx(e);return j(r,{code:I.invalid_type,expected:O.symbol,received:r.parsedType}),F}return _e(e.data)}};xr.create=n=>new xr({typeName:Z.ZodSymbol,...V(n)});var vn=class extends Y{_parse(e){if(this._getType(e)!==O.undefined){let r=this._getOrReturnCtx(e);return j(r,{code:I.invalid_type,expected:O.undefined,received:r.parsedType}),F}return _e(e.data)}};vn.create=n=>new vn({typeName:Z.ZodUndefined,...V(n)});var bn=class extends Y{_parse(e){if(this._getType(e)!==O.null){let r=this._getOrReturnCtx(e);return j(r,{code:I.invalid_type,expected:O.null,received:r.parsedType}),F}return _e(e.data)}};bn.create=n=>new bn({typeName:Z.ZodNull,...V(n)});var Ht=class extends Y{constructor(){super(...arguments),this._any=!0}_parse(e){return _e(e.data)}};Ht.create=n=>new Ht({typeName:Z.ZodAny,...V(n)});var It=class extends Y{constructor(){super(...arguments),this._unknown=!0}_parse(e){return _e(e.data)}};It.create=n=>new It({typeName:Z.ZodUnknown,...V(n)});var et=class extends Y{_parse(e){let t=this._getOrReturnCtx(e);return j(t,{code:I.invalid_type,expected:O.never,received:t.parsedType}),F}};et.create=n=>new et({typeName:Z.ZodNever,...V(n)});var Cr=class extends Y{_parse(e){if(this._getType(e)!==O.undefined){let r=this._getOrReturnCtx(e);return j(r,{code:I.invalid_type,expected:O.void,received:r.parsedType}),F}return _e(e.data)}};Cr.create=n=>new Cr({typeName:Z.ZodVoid,...V(n)});var Rt=class n extends Y{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==O.array)return j(t,{code:I.invalid_type,expected:O.array,received:t.parsedType}),F;if(s.exactLength!==null){let o=t.data.length>s.exactLength.value,l=t.data.length<s.exactLength.value;(o||l)&&(j(t,{code:o?I.too_big:I.too_small,minimum:l?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(j(t,{code:I.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(j(t,{code:I.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((o,l)=>s.type._parseAsync(new Ze(t,o,t.path,l)))).then(o=>be.mergeArray(r,o));let i=[...t.data].map((o,l)=>s.type._parseSync(new Ze(t,o,t.path,l)));return be.mergeArray(r,i)}get element(){return this._def.type}min(e,t){return new n({...this._def,minLength:{value:e,message:z.toString(t)}})}max(e,t){return new n({...this._def,maxLength:{value:e,message:z.toString(t)}})}length(e,t){return new n({...this._def,exactLength:{value:e,message:z.toString(t)}})}nonempty(e){return this.min(1,e)}};Rt.create=(n,e)=>new Rt({type:n,minLength:null,maxLength:null,exactLength:null,typeName:Z.ZodArray,...V(e)});function Tr(n){if(n instanceof $e){let e={};for(let t in n.shape){let r=n.shape[t];e[t]=Ke.create(Tr(r))}return new $e({...n._def,shape:()=>e})}else return n instanceof Rt?new Rt({...n._def,type:Tr(n.element)}):n instanceof Ke?Ke.create(Tr(n.unwrap())):n instanceof ht?ht.create(Tr(n.unwrap())):n instanceof dt?dt.create(n.items.map(e=>Tr(e))):n}var $e=class n extends Y{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=Q.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==O.object){let c=this._getOrReturnCtx(e);return j(c,{code:I.invalid_type,expected:O.object,received:c.parsedType}),F}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),l=[];if(!(this._def.catchall instanceof et&&this._def.unknownKeys==="strip"))for(let c in s.data)o.includes(c)||l.push(c);let u=[];for(let c of o){let f=i[c],p=s.data[c];u.push({key:{status:"valid",value:c},value:f._parse(new Ze(s,p,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof et){let c=this._def.unknownKeys;if(c==="passthrough")for(let f of l)u.push({key:{status:"valid",value:f},value:{status:"valid",value:s.data[f]}});else if(c==="strict")l.length>0&&(j(s,{code:I.unrecognized_keys,keys:l}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let f of l){let p=s.data[f];u.push({key:{status:"valid",value:f},value:c._parse(new Ze(s,p,s.path,f)),alwaysSet:f in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let c=[];for(let f of u){let p=await f.key,b=await f.value;c.push({key:p,value:b,alwaysSet:f.alwaysSet})}return c}).then(c=>be.mergeObjectSync(r,c)):be.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(e){return z.errToObj,new n({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{let s=this._def.errorMap?.(t,r).message??r.defaultError;return t.code==="unrecognized_keys"?{message:z.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new n({...this._def,unknownKeys:"strip"})}passthrough(){return new n({...this._def,unknownKeys:"passthrough"})}extend(e){return new n({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new n({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Z.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new n({...this._def,catchall:e})}pick(e){let t={};for(let r of Q.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new n({...this._def,shape:()=>t})}omit(e){let t={};for(let r of Q.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new n({...this._def,shape:()=>t})}deepPartial(){return Tr(this)}partial(e){let t={};for(let r of Q.objectKeys(this.shape)){let s=this.shape[r];e&&!e[r]?t[r]=s:t[r]=s.optional()}return new n({...this._def,shape:()=>t})}required(e){let t={};for(let r of Q.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Ke;)i=i._def.innerType;t[r]=i}return new n({...this._def,shape:()=>t})}keyof(){return Ml(Q.objectKeys(this.shape))}};$e.create=(n,e)=>new $e({shape:()=>n,unknownKeys:"strip",catchall:et.create(),typeName:Z.ZodObject,...V(e)});$e.strictCreate=(n,e)=>new $e({shape:()=>n,unknownKeys:"strict",catchall:et.create(),typeName:Z.ZodObject,...V(e)});$e.lazycreate=(n,e)=>new $e({shape:n,unknownKeys:"strip",catchall:et.create(),typeName:Z.ZodObject,...V(e)});var wn=class extends Y{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;function s(i){for(let l of i)if(l.result.status==="valid")return l.result;for(let l of i)if(l.result.status==="dirty")return t.common.issues.push(...l.ctx.common.issues),l.result;let o=i.map(l=>new Ae(l.ctx.common.issues));return j(t,{code:I.invalid_union,unionErrors:o}),F}if(t.common.async)return Promise.all(r.map(async i=>{let o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let u of r){let c={...t,common:{...t.common,issues:[]},parent:null},f=u._parseSync({data:t.data,path:t.path,parent:c});if(f.status==="valid")return f;f.status==="dirty"&&!i&&(i={result:f,ctx:c}),c.common.issues.length&&o.push(c.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let l=o.map(u=>new Ae(u));return j(t,{code:I.invalid_union,unionErrors:l}),F}}get options(){return this._def.options}};wn.create=(n,e)=>new wn({options:n,typeName:Z.ZodUnion,...V(e)});var Ct=n=>n instanceof kn?Ct(n.schema):n instanceof Ge?Ct(n.innerType()):n instanceof Sn?[n.value]:n instanceof Tn?n.options:n instanceof xn?Q.objectValues(n.enum):n instanceof Cn?Ct(n._def.innerType):n instanceof vn?[void 0]:n instanceof bn?[null]:n instanceof Ke?[void 0,...Ct(n.unwrap())]:n instanceof ht?[null,...Ct(n.unwrap())]:n instanceof fs||n instanceof Rn?Ct(n.unwrap()):n instanceof In?Ct(n._def.innerType):[],Hs=class n extends Y{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==O.object)return j(t,{code:I.invalid_type,expected:O.object,received:t.parsedType}),F;let r=this.discriminator,s=t.data[r],i=this.optionsMap.get(s);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(j(t,{code:I.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),F)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let s=new Map;for(let i of t){let o=Ct(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let l of o){if(s.has(l))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(l)}`);s.set(l,i)}}return new n({typeName:Z.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...V(r)})}};function Co(n,e){let t=ct(n),r=ct(e);if(n===e)return{valid:!0,data:n};if(t===O.object&&r===O.object){let s=Q.objectKeys(e),i=Q.objectKeys(n).filter(l=>s.indexOf(l)!==-1),o={...n,...e};for(let l of i){let u=Co(n[l],e[l]);if(!u.valid)return{valid:!1};o[l]=u.data}return{valid:!0,data:o}}else if(t===O.array&&r===O.array){if(n.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<n.length;i++){let o=n[i],l=e[i],u=Co(o,l);if(!u.valid)return{valid:!1};s.push(u.data)}return{valid:!0,data:s}}else return t===O.date&&r===O.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}var _n=class extends Y{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),s=(i,o)=>{if(Zs(i)||Zs(o))return F;let l=Co(i.value,o.value);return l.valid?((Gs(i)||Gs(o))&&t.dirty(),{status:t.value,value:l.data}):(j(r,{code:I.invalid_intersection_types}),F)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};_n.create=(n,e,t)=>new _n({left:n,right:e,typeName:Z.ZodIntersection,...V(t)});var dt=class n extends Y{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==O.array)return j(r,{code:I.invalid_type,expected:O.array,received:r.parsedType}),F;if(r.data.length<this._def.items.length)return j(r,{code:I.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),F;!this._def.rest&&r.data.length>this._def.items.length&&(j(r,{code:I.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...r.data].map((o,l)=>{let u=this._def.items[l]||this._def.rest;return u?u._parse(new Ze(r,o,r.path,l)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>be.mergeArray(t,o)):be.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new n({...this._def,rest:e})}};dt.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new dt({items:n,typeName:Z.ZodTuple,rest:null,...V(e)})};var Vs=class n extends Y{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==O.object)return j(r,{code:I.invalid_type,expected:O.object,received:r.parsedType}),F;let s=[],i=this._def.keyType,o=this._def.valueType;for(let l in r.data)s.push({key:i._parse(new Ze(r,l,r.path,l)),value:o._parse(new Ze(r,r.data[l],r.path,l)),alwaysSet:l in r.data});return r.common.async?be.mergeObjectAsync(t,s):be.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,r){return t instanceof Y?new n({keyType:e,valueType:t,typeName:Z.ZodRecord,...V(r)}):new n({keyType:Gt.create(),valueType:e,typeName:Z.ZodRecord,...V(t)})}},Ir=class extends Y{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==O.map)return j(r,{code:I.invalid_type,expected:O.map,received:r.parsedType}),F;let s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([l,u],c)=>({key:s._parse(new Ze(r,l,r.path,[c,"key"])),value:i._parse(new Ze(r,u,r.path,[c,"value"]))}));if(r.common.async){let l=new Map;return Promise.resolve().then(async()=>{for(let u of o){let c=await u.key,f=await u.value;if(c.status==="aborted"||f.status==="aborted")return F;(c.status==="dirty"||f.status==="dirty")&&t.dirty(),l.set(c.value,f.value)}return{status:t.value,value:l}})}else{let l=new Map;for(let u of o){let c=u.key,f=u.value;if(c.status==="aborted"||f.status==="aborted")return F;(c.status==="dirty"||f.status==="dirty")&&t.dirty(),l.set(c.value,f.value)}return{status:t.value,value:l}}}};Ir.create=(n,e,t)=>new Ir({valueType:e,keyType:n,typeName:Z.ZodMap,...V(t)});var Rr=class n extends Y{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==O.set)return j(r,{code:I.invalid_type,expected:O.set,received:r.parsedType}),F;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(j(r,{code:I.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(j(r,{code:I.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let i=this._def.valueType;function o(u){let c=new Set;for(let f of u){if(f.status==="aborted")return F;f.status==="dirty"&&t.dirty(),c.add(f.value)}return{status:t.value,value:c}}let l=[...r.data.values()].map((u,c)=>i._parse(new Ze(r,u,r.path,c)));return r.common.async?Promise.all(l).then(u=>o(u)):o(l)}min(e,t){return new n({...this._def,minSize:{value:e,message:z.toString(t)}})}max(e,t){return new n({...this._def,maxSize:{value:e,message:z.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Rr.create=(n,e)=>new Rr({valueType:n,minSize:null,maxSize:null,typeName:Z.ZodSet,...V(e)});var Ws=class n extends Y{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==O.function)return j(t,{code:I.invalid_type,expected:O.function,received:t.parsedType}),F;function r(l,u){return hs({data:l,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,kr(),xt].filter(c=>!!c),issueData:{code:I.invalid_arguments,argumentsError:u}})}function s(l,u){return hs({data:l,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,kr(),xt].filter(c=>!!c),issueData:{code:I.invalid_return_type,returnTypeError:u}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof Vt){let l=this;return _e(async function(...u){let c=new Ae([]),f=await l._def.args.parseAsync(u,i).catch(w=>{throw c.addIssue(r(u,w)),c}),p=await Reflect.apply(o,this,f);return await l._def.returns._def.type.parseAsync(p,i).catch(w=>{throw c.addIssue(s(p,w)),c})})}else{let l=this;return _e(function(...u){let c=l._def.args.safeParse(u,i);if(!c.success)throw new Ae([r(u,c.error)]);let f=Reflect.apply(o,this,c.data),p=l._def.returns.safeParse(f,i);if(!p.success)throw new Ae([s(f,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new n({...this._def,args:dt.create(e).rest(It.create())})}returns(e){return new n({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new n({args:e||dt.create([]).rest(It.create()),returns:t||It.create(),typeName:Z.ZodFunction,...V(r)})}},kn=class extends Y{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};kn.create=(n,e)=>new kn({getter:n,typeName:Z.ZodLazy,...V(e)});var Sn=class extends Y{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return j(t,{received:t.data,code:I.invalid_literal,expected:this._def.value}),F}return{status:"valid",value:e.data}}get value(){return this._def.value}};Sn.create=(n,e)=>new Sn({value:n,typeName:Z.ZodLiteral,...V(e)});function Ml(n,e){return new Tn({values:n,typeName:Z.ZodEnum,...V(e)})}var Tn=class n extends Y{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),r=this._def.values;return j(t,{expected:Q.joinValues(r),received:t.parsedType,code:I.invalid_type}),F}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return j(t,{received:t.data,code:I.invalid_enum_value,options:r}),F}return _e(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return n.create(e,{...this._def,...t})}exclude(e,t=this._def){return n.create(this.options.filter(r=>!e.includes(r)),{...this._def,...t})}};Tn.create=Ml;var xn=class extends Y{_parse(e){let t=Q.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==O.string&&r.parsedType!==O.number){let s=Q.objectValues(t);return j(r,{expected:Q.joinValues(s),received:r.parsedType,code:I.invalid_type}),F}if(this._cache||(this._cache=new Set(Q.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=Q.objectValues(t);return j(r,{received:r.data,code:I.invalid_enum_value,options:s}),F}return _e(e.data)}get enum(){return this._def.values}};xn.create=(n,e)=>new xn({values:n,typeName:Z.ZodNativeEnum,...V(e)});var Vt=class extends Y{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==O.promise&&t.common.async===!1)return j(t,{code:I.invalid_type,expected:O.promise,received:t.parsedType}),F;let r=t.parsedType===O.promise?t.data:Promise.resolve(t.data);return _e(r.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};Vt.create=(n,e)=>new Vt({type:n,typeName:Z.ZodPromise,...V(e)});var Ge=class extends Y{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Z.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{j(r,o),o.fatal?t.abort():t.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(r.data,i);if(r.common.async)return Promise.resolve(o).then(async l=>{if(t.value==="aborted")return F;let u=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return u.status==="aborted"?F:u.status==="dirty"?fn(u.value):t.value==="dirty"?fn(u.value):u});{if(t.value==="aborted")return F;let l=this._def.schema._parseSync({data:o,path:r.path,parent:r});return l.status==="aborted"?F:l.status==="dirty"?fn(l.value):t.value==="dirty"?fn(l.value):l}}if(s.type==="refinement"){let o=l=>{let u=s.refinement(l,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){let l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?F:(l.status==="dirty"&&t.dirty(),o(l.value),{status:t.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?F:(l.status==="dirty"&&t.dirty(),o(l.value).then(()=>({status:t.value,value:l.value}))))}if(s.type==="transform")if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Zt(o))return F;let l=s.transform(o.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>Zt(o)?Promise.resolve(s.transform(o.value,i)).then(l=>({status:t.value,value:l})):F);Q.assertNever(s)}};Ge.create=(n,e,t)=>new Ge({schema:n,typeName:Z.ZodEffects,effect:e,...V(t)});Ge.createWithPreprocess=(n,e,t)=>new Ge({schema:e,effect:{type:"preprocess",transform:n},typeName:Z.ZodEffects,...V(t)});var Ke=class extends Y{_parse(e){return this._getType(e)===O.undefined?_e(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ke.create=(n,e)=>new Ke({innerType:n,typeName:Z.ZodOptional,...V(e)});var ht=class extends Y{_parse(e){return this._getType(e)===O.null?_e(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ht.create=(n,e)=>new ht({innerType:n,typeName:Z.ZodNullable,...V(e)});var Cn=class extends Y{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return t.parsedType===O.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Cn.create=(n,e)=>new Cn({innerType:n,typeName:Z.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...V(e)});var In=class extends Y{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Sr(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Ae(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ae(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};In.create=(n,e)=>new In({innerType:n,typeName:Z.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...V(e)});var Er=class extends Y{_parse(e){if(this._getType(e)!==O.nan){let r=this._getOrReturnCtx(e);return j(r,{code:I.invalid_type,expected:O.nan,received:r.parsedType}),F}return{status:"valid",value:e.data}}};Er.create=n=>new Er({typeName:Z.ZodNaN,...V(n)});var Lf=Symbol("zod_brand"),fs=class extends Y{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}},ps=class n extends Y{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?F:i.status==="dirty"?(t.dirty(),fn(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?F:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,t){return new n({in:e,out:t,typeName:Z.ZodPipeline})}},Rn=class extends Y{_parse(e){let t=this._def.innerType._parse(e),r=s=>(Zt(s)&&(s.value=Object.freeze(s.value)),s);return Sr(t)?t.then(s=>r(s)):r(t)}unwrap(){return this._def.innerType}};Rn.create=(n,e)=>new Rn({innerType:n,typeName:Z.ZodReadonly,...V(e)});function Pl(n,e){let t=typeof n=="function"?n(e):typeof n=="string"?{message:n}:n;return typeof t=="string"?{message:t}:t}function zl(n,e={},t){return n?Ht.create().superRefine((r,s)=>{let i=n(r);if(i instanceof Promise)return i.then(o=>{if(!o){let l=Pl(e,r),u=l.fatal??t??!0;s.addIssue({code:"custom",...l,fatal:u})}});if(!i){let o=Pl(e,r),l=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:l})}}):Ht.create()}var Uf={object:$e.lazycreate},Z;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(Z||(Z={}));var qf=(n,e={message:`Input not instance of ${n.name}`})=>zl(t=>t instanceof n,e),Dl=Gt.create,Ll=pn.create,Ff=Er.create,Bf=mn.create,Ul=gn.create,Kf=yn.create,Zf=xr.create,Gf=vn.create,Hf=bn.create,Vf=Ht.create,Wf=It.create,Jf=et.create,Yf=Cr.create,Xf=Rt.create,Qf=$e.create,ep=$e.strictCreate,tp=wn.create,np=Hs.create,rp=_n.create,sp=dt.create,ip=Vs.create,op=Ir.create,ap=Rr.create,lp=Ws.create,up=kn.create,cp=Sn.create,dp=Tn.create,hp=xn.create,fp=Vt.create,pp=Ge.create,mp=Ke.create,gp=ht.create,yp=Ge.createWithPreprocess,vp=ps.create,bp=()=>Dl().optional(),wp=()=>Ll().optional(),_p=()=>Ul().optional(),kp={string:(n=>Gt.create({...n,coerce:!0})),number:(n=>pn.create({...n,coerce:!0})),boolean:(n=>gn.create({...n,coerce:!0})),bigint:(n=>mn.create({...n,coerce:!0})),date:(n=>yn.create({...n,coerce:!0}))};var Sp=F;var ql=k.object({baseUrl:k.string().url(),email:k.string().email(),apiToken:k.string().min(1)}),Io=k.object({controlPlaneUrl:k.string().url(),runnerId:k.string().optional(),runnerToken:k.string().optional(),runnerName:k.string().default(Js.default.hostname()),jira:ql.optional(),repos:k.record(k.object({path:k.string(),jira:ql.optional(),github:k.object({token:k.string().min(1),login:k.string().optional()}).optional()})).default({}),github:k.object({token:k.string().min(1),login:k.string().optional()}).optional(),githubUsers:k.record(k.object({token:k.string().min(1),login:k.string().optional()})).default({}),deploy:k.object({enabled:k.boolean().default(!1)}).default({enabled:!1}),environments:k.record(k.object({secrets:k.record(k.string()).default({})})).default({}),claudeProfiles:k.record(k.object({configDir:k.string()})).default({}),claudeBin:k.string().default("claude"),agents:k.record(k.object({bin:k.string()})).default({}),jiraUsers:k.record(k.object({email:k.string().email(),apiToken:k.string().min(1)})).default({}),auditSchedules:k.array(k.object({repoName:k.string(),role:k.enum(["security","testing"]),intervalHours:k.number().int().min(6).max(720)})).default([]),pollIntervalSeconds:k.number().int().min(10).max(600).default(30)});function se(){let n=process.env.ALLWRIGHT_CONFIG_DIR??process.env.TICKETPILOT_CONFIG_DIR;if(n)return n;let e=Ys.default.join(Js.default.homedir(),".config","allwright"),t=Ys.default.join(Js.default.homedir(),".config","ticketpilot");return!Et.default.existsSync(e)&&Et.default.existsSync(t)?t:e}function At(){return Ys.default.join(se(),"runner.json")}function pe(){let n=At();if(!Et.default.existsSync(n))return null;let e=JSON.parse(Et.default.readFileSync(n,"utf8"));return Io.parse(e)}function fe(n){let e=se();Et.default.mkdirSync(e,{recursive:!0,mode:448});let t=At(),r=t+".tmp";Et.default.writeFileSync(r,JSON.stringify(n,null,2)+`
262
+ `,{mode:384}),Et.default.renameSync(r,t),Et.default.chmodSync(t,384)}function Xs(n,e){return`${n}:${e}`}function En(n,e,t){return n.environments[Xs(e,t)]?.secrets??{}}function ie(){let n=pe();if(!n)throw new Error(`No runner config found at ${At()}. Run \`allwright init\` first.`);return n}var Qs=require("node:child_process"),Me=R(require("node:fs"),1),ei=R(require("node:path"),1);var Tp=new Set(["runner.log","runner.pid"]);function xp(n){return Me.default.readdirSync(n).filter(e=>!Tp.has(e)&&!/\.bak-\d+$/.test(e)).sort()}function Fl(n){let e=se();if(!Me.default.existsSync(e))throw new Error(`nothing to export - ${e} does not exist`);let t=xp(e);if(!t.length)throw new Error(`nothing to export - ${e} is empty`);let r=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-"),s=ei.default.resolve(n||`ticketpilot-backup-${r}.tgz`);return Me.default.writeFileSync(s,"",{mode:384}),(0,Qs.execFileSync)("tar",["-czf",s,"-C",e,...t]),Me.default.chmodSync(s,384),{file:s,entries:t}}function Bl(n){let e=ei.default.resolve(n);if(!Me.default.existsSync(e))throw new Error(`backup file not found: ${e}`);let t=(0,Qs.execFileSync)("tar",["-tzf",e],{encoding:"utf8"}).split(`
263
+ `).filter(Boolean);for(let i of t)if(i.startsWith("/")||i.split("/").includes(".."))throw new Error(`refusing to import - unsafe path in archive: ${i}`);let r=se(),s;Me.default.existsSync(r)&&Me.default.readdirSync(r).length&&(s=`${r}.bak-${Date.now()}`,Me.default.renameSync(r,s)),Me.default.mkdirSync(r,{recursive:!0,mode:448}),(0,Qs.execFileSync)("tar",["-xzf",e,"-C",r]);for(let i of Me.default.readdirSync(r)){let o=ei.default.join(r,i);Me.default.statSync(o).isFile()&&Me.default.chmodSync(o,384)}return{restored:t.map(i=>i.replace(/\/$/,"")).sort(),previousDir:s}}var Ar=R(require("node:fs"),1),Wt=R(require("node:path"),1),ti=".ticketpilot-attachments",Cp=15*1024*1024,Ip=50*1024*1024,Kl=20;function Zl(n,e){let t=Wt.default.basename(n).replace(/[^\w.\- ()]/g,"_").replace(/^\.+/,"").slice(-100)||"file",r=t,s=1;for(;e.has(r);)r=`${s++}-${t}`;return e.add(r),r}async function $r(n,e,t,r){if(!e.length)return"";let s=Wt.default.join(t,ti);Ar.default.mkdirSync(s,{recursive:!0});let i=new Set,o=[],l=0;for(let u of e){if(o.length>=Kl){r("warn",`attachment cap reached (${Kl} files) - skipping the rest`);break}if(u.size>Cp){r("warn",`skipping attachment "${u.filename}" - ${Ap(u.size)} MB exceeds the 15 MB limit`);continue}if(l+u.size>Ip){r("warn",`attachment size budget reached - skipping "${u.filename}" and the rest`);break}try{let c=await n.downloadAttachment(u.contentUrl),f=Zl(u.filename,i);Ar.default.writeFileSync(Wt.default.join(s,f),c),l+=c.length,o.push(`- ${ti}/${f} (${u.mimeType||"unknown type"}, ${Ro(c.length)} KB)`),r("info",`Downloaded attachment "${u.filename}" (${Ro(c.length)} KB)`)}catch(c){r("warn",`could not download attachment "${u.filename}": ${c instanceof Error?c.message:c}`)}}return o.length?`
264
264
 
265
265
  Files attached to the Jira ticket, downloaded locally for this run. They are reference material and NOT part of the repository - never commit, copy, or edit them:
266
266
  ${o.join(`
267
267
  `)}
268
- Read them with the Read tool when relevant; images (screenshots) can be viewed directly.`:(Vt(t),"")}function Vt(n){Cr.default.rmSync(Ht.default.join(n,Ys),{recursive:!0,force:!0})}var vp=4*1024*1024,bp=16*1024*1024;function Ll(n,e,t){let r=Ht.default.join(n,Ys,`chat-${e.replace(/[^\w-]/g,"")}`);if(!t.length)return{section:"",dir:r};Cr.default.mkdirSync(r,{recursive:!0});let s=new Set,i=[],o=0,l=Ht.default.relative(n,r);for(let c of t){let f=Buffer.from(c.contentBase64,"base64");if(f.length>vp||o+f.length>bp){i.push(`- (skipped "${c.name}" - over the upload size budget)`);continue}let p=Dl(c.name,s);Cr.default.writeFileSync(Ht.default.join(r,p),f),o+=f.length,i.push(`- ${l}/${p} (${So(f.length)} KB)`)}return{section:`
268
+ Read them with the Read tool when relevant; images (screenshots) can be viewed directly.`:(Jt(t),"")}function Jt(n){Ar.default.rmSync(Wt.default.join(n,ti),{recursive:!0,force:!0})}var Rp=4*1024*1024,Ep=16*1024*1024;function Gl(n,e,t){let r=Wt.default.join(n,ti,`chat-${e.replace(/[^\w-]/g,"")}`);if(!t.length)return{section:"",dir:r};Ar.default.mkdirSync(r,{recursive:!0});let s=new Set,i=[],o=0,l=Wt.default.relative(n,r);for(let c of t){let f=Buffer.from(c.contentBase64,"base64");if(f.length>Rp||o+f.length>Ep){i.push(`- (skipped "${c.name}" - over the upload size budget)`);continue}let p=Zl(c.name,s);Ar.default.writeFileSync(Wt.default.join(r,p),f),o+=f.length,i.push(`- ${l}/${p} (${Ro(f.length)} KB)`)}return{section:`
269
269
 
270
270
  The user attached file(s) with this message, staged locally for you. They are reference material and NOT part of the repository - never commit, copy, or edit them. If a ticket is created from this chat, these files are attached to it automatically, so reference them by filename instead of pasting their content:
271
271
  ${i.join(`
272
272
  `)}
273
- Read them with the Read tool; images can be viewed directly.`,dir:r}}var So=n=>Math.max(1,Math.round(n/1024)),wp=n=>Math.round(n/(1024*1024)*10)/10;var ke=R(require("node:fs"),1),Qs=R(require("node:path"),1);function Rr(){return Qs.default.join(re(),"runner.pid")}function Xs(){return Qs.default.join(re(),"runner.log")}function Ul(){ke.default.mkdirSync(re(),{recursive:!0,mode:448});let n=ke.default.openSync(Xs(),"a",384);try{ke.default.chmodSync(Xs(),384)}catch{}return n}function In(){let n=Rr();if(!ke.default.existsSync(n))return null;let e=Number(ke.default.readFileSync(n,"utf8").trim());return Number.isFinite(e)&&e>0?e:null}function Rn(n){try{return process.kill(n,0),!0}catch{return!1}}function ql(n){ke.default.mkdirSync(re(),{recursive:!0,mode:448}),ke.default.writeFileSync(Rr(),String(n),{mode:384})}function Fl(n){In()===n&&ke.default.rmSync(Rr(),{force:!0})}function To(){return Qs.default.join(re(),"runner.lock")}function cs(){let n=To();if(!ke.default.existsSync(n))return null;let e=Number(ke.default.readFileSync(n,"utf8").trim());return!Number.isFinite(e)||e<=0||e===process.pid?null:Rn(e)?e:null}function Bl(){let n=cs();return n?{ok:!1,pid:n}:(ke.default.mkdirSync(re(),{recursive:!0,mode:448}),ke.default.writeFileSync(To(),String(process.pid),{mode:384}),{ok:!0})}function xo(){try{let n=To();ke.default.existsSync(n)&&Number(ke.default.readFileSync(n,"utf8").trim())===process.pid&&ke.default.rmSync(n,{force:!0})}catch{}}var ai=R(require("node:fs"),1),ms=R(require("node:path"),1),pu=R(we(),1);async function mu(n,e){let t=await fetch(new URL("/api/runners/enroll",n.controlPlaneUrl),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enrollToken:e,name:n.runnerName,platform:`${process.platform}/${process.arch}`,runnerVersion:li})});if(!t.ok){let i=await t.text().catch(()=>"");throw new Error(`enrollment failed (${t.status}): ${i.slice(0,300)}`)}let r=pu.EnrollResponse.parse(await t.json()),s={...n,runnerId:r.runnerId,runnerToken:r.runnerToken};return fe(s),s}function Gm(){try{let n=process.argv[1]?ai.default.realpathSync(process.argv[1]):"";for(let e of[ms.default.dirname(n),ms.default.dirname(ms.default.dirname(n))]){let t=ms.default.join(e,"package.json");if(!ai.default.existsSync(t))continue;let r=JSON.parse(ai.default.readFileSync(t,"utf8")).version;if(typeof r=="string"&&r)return r}}catch{}return"0.0.0"}var li=Gm();pt();var xu="Posted automatically by Allwright",Hm=["Posted automatically by TicketPilot"],mt=n=>n.includes(xu)||Hm.some(e=>n.includes(e));var Pe=class{constructor(e){this.auth=e}auth;headers(){return{Authorization:`Basic ${Buffer.from(`${this.auth.email}:${this.auth.apiToken}`).toString("base64")}`,Accept:"application/json","Content-Type":"application/json"}}async request(e,t,r){let s=new URL(t,this.auth.baseUrl).toString(),i=await fetch(s,{method:e,headers:this.headers(),body:r===void 0?void 0:JSON.stringify(r)});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`Jira ${e} ${t} -> ${i.status}: ${o.slice(0,500)}`)}if(i.status!==204)return await i.json()}async myself(){return this.request("GET","/rest/api/3/myself")}async searchUsers(e,t=20){let r=await this.userSearch(e,t);return r.length||!e.includes("@")?r:this.userSearch(e.slice(0,e.indexOf("@")),t)}async userSearch(e,t){return e.trim()?(await this.request("GET",`/rest/api/3/user/search?query=${encodeURIComponent(e)}&maxResults=${t}`)??[]).filter(s=>s.accountId&&(s.accountType??"atlassian")==="atlassian").map(s=>({accountId:s.accountId,displayName:s.displayName??"(no name)",email:s.emailAddress??"",active:s.active??!0})):[]}async search(e,t=20){return((await this.request("POST","/rest/api/3/search/jql",{jql:e,maxResults:t,fields:["summary","components"]})).issues??[]).map(s=>({key:s.key,summary:s.fields?.summary??"",components:(s.fields?.components??[]).map(i=>i.name??"").filter(Boolean)}))}async projectStatuses(e){let t=await this.request("GET",`/rest/api/3/project/${encodeURIComponent(e)}/statuses`),r=new Map;for(let i of t??[])for(let o of i.statuses??[])o.name&&!r.has(o.name)&&r.set(o.name,o.statusCategory?.key??"indeterminate");let s=i=>i==="new"?0:i==="done"?2:1;return[...r.entries()].sort((i,o)=>s(i[1])-s(o[1])).map(([i])=>i)}async searchEpics(e,t=20){return((await this.request("POST","/rest/api/3/search/jql",{jql:`project = "${e}" AND issuetype = Epic AND statusCategory != Done ORDER BY created DESC`,maxResults:t,fields:["summary","status"]})).issues??[]).map(s=>({key:s.key,summary:s.fields?.summary??"",status:s.fields?.status?.name??""}))}async epicChildren(e,t=50){return((await this.request("POST","/rest/api/3/search/jql",{jql:`parent = "${e}" ORDER BY created ASC`,maxResults:t,fields:["summary","status","labels"]})).issues??[]).map(s=>({key:s.key,summary:s.fields?.summary??"",status:s.fields?.status?.name??"",statusCategory:s.fields?.status?.statusCategory?.key??"indeterminate",labels:s.fields?.labels??[]}))}async searchBoard(e,t=100){return((await this.request("POST","/rest/api/3/search/jql",{jql:e,maxResults:t,fields:["summary","status","labels"]})).issues??[]).map(s=>({key:s.key,summary:s.fields?.summary??"",status:s.fields?.status?.name??"(no status)",statusId:s.fields?.status?.id??"",labels:s.fields?.labels??[]}))}async boardColumns(e){try{let r=(await this.request("GET",`/rest/agile/1.0/board?projectKeyOrId=${encodeURIComponent(e)}`)).values?.[0]?.id;if(!r)return null;let i=((await this.request("GET",`/rest/agile/1.0/board/${r}/configuration`)).columnConfig?.columns??[]).filter(o=>(o.statuses??[]).length>0&&o.name).map(o=>({name:o.name,statusIds:(o.statuses??[]).map(l=>l.id??"").filter(Boolean)}));return i.length?i:null}catch{return null}}async getIssue(e){let t=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}?fields=summary,description,labels,comment,status,attachment`),r;try{r=await this.listAllComments(e)}catch{r=t.fields.comment?.comments??[]}let s=r.map(o=>({id:o.id??"",author:o.author?.displayName??"unknown",authorAccountId:o.author?.accountId??null,created:o.created,body:Tu(o.body)})),i=(t.fields.attachment??[]).filter(o=>o.id&&o.filename&&o.content).map(o=>({id:o.id,filename:o.filename,mimeType:o.mimeType??"",size:o.size??0,contentUrl:o.content}));return{key:t.key,summary:t.fields.summary??"",description:Tu(t.fields.description),labels:t.fields.labels??[],status:t.fields.status?.name??"",comments:s,attachments:i}}async listAllComments(e){let t=await this.fetchCommentPage(e,0),r=t.total??t.comments.length;if(r<=t.comments.length)return t.comments;let s=Math.max(0,r-200),i=s===0?[...t.comments]:[];for(;i.length<Math.min(r,200);){let o=await this.fetchCommentPage(e,s+i.length);if(!o.comments.length)break;i.push(...o.comments)}return i.slice(-200)}async fetchCommentPage(e,t){let r=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}/comment?startAt=${t}&maxResults=100`);return{comments:r.comments??[],total:r.total}}async downloadAttachment(e){let t=await fetch(e,{headers:this.headers()});if(!t.ok)throw new Error(`attachment download failed: ${t.status}`);return Buffer.from(await t.arrayBuffer())}async lastEnteredStatus(e,t){let r=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}?expand=changelog&fields=status`),s=t.toLowerCase(),i=null;for(let o of r.changelog?.histories??[])(o.items??[]).some(u=>(u.field==="status"||u.fieldId==="status")&&(u.toString??"").toLowerCase()===s)&&(!i||new Date(o.created)>new Date(i.at))&&(i={at:o.created,author:o.author?.displayName??"unknown",authorAccountId:o.author?.accountId??null});return i}async createIssue(e,t,r,s="Task",i){return{key:(await this.request("POST","/rest/api/3/issue",{fields:{project:{key:e},issuetype:{name:s},summary:t.slice(0,250),description:Ho(r),...i?{parent:{key:i}}:{}}})).key}}async addAttachments(e,t){if(!t.length)return;let r=new FormData;for(let l of t)r.append("file",new Blob([new Uint8Array(l.content)]),l.name.slice(0,255));let s=new URL(`/rest/api/3/issue/${encodeURIComponent(e)}/attachments`,this.auth.baseUrl).toString(),i=Buffer.from(`${this.auth.email}:${this.auth.apiToken}`).toString("base64"),o=await fetch(s,{method:"POST",headers:{Authorization:`Basic ${i}`,Accept:"application/json","X-Atlassian-Token":"no-check"},body:r});if(!o.ok)throw new Error(`Jira attachment upload failed: HTTP ${o.status}`)}async addTriggerComment(e,t){await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/comment`,{body:Ho(t)})}async addComment(e,t){let r=`${t}
273
+ Read them with the Read tool; images can be viewed directly.`,dir:r}}var Ro=n=>Math.max(1,Math.round(n/1024)),Ap=n=>Math.round(n/(1024*1024)*10)/10;var ke=R(require("node:fs"),1),ri=R(require("node:path"),1);function Pr(){return ri.default.join(se(),"runner.pid")}function ni(){return ri.default.join(se(),"runner.log")}function Hl(){ke.default.mkdirSync(se(),{recursive:!0,mode:448});let n=ke.default.openSync(ni(),"a",384);try{ke.default.chmodSync(ni(),384)}catch{}return n}function An(){let n=Pr();if(!ke.default.existsSync(n))return null;let e=Number(ke.default.readFileSync(n,"utf8").trim());return Number.isFinite(e)&&e>0?e:null}function $n(n){try{return process.kill(n,0),!0}catch{return!1}}function Vl(n){ke.default.mkdirSync(se(),{recursive:!0,mode:448}),ke.default.writeFileSync(Pr(),String(n),{mode:384})}function Wl(n){An()===n&&ke.default.rmSync(Pr(),{force:!0})}function Eo(){return ri.default.join(se(),"runner.lock")}function ms(){let n=Eo();if(!ke.default.existsSync(n))return null;let e=Number(ke.default.readFileSync(n,"utf8").trim());return!Number.isFinite(e)||e<=0||e===process.pid?null:$n(e)?e:null}function Jl(){let n=ms();return n?{ok:!1,pid:n}:(ke.default.mkdirSync(se(),{recursive:!0,mode:448}),ke.default.writeFileSync(Eo(),String(process.pid),{mode:384}),{ok:!0})}function Ao(){try{let n=Eo();ke.default.existsSync(n)&&Number(ke.default.readFileSync(n,"utf8").trim())===process.pid&&ke.default.rmSync(n,{force:!0})}catch{}}var di=R(require("node:fs"),1),ws=R(require("node:path"),1),_u=R(we(),1);async function ku(n,e){let t=await fetch(new URL("/api/runners/enroll",n.controlPlaneUrl),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enrollToken:e,name:n.runnerName,platform:`${process.platform}/${process.arch}`,runnerVersion:hi})});if(!t.ok){let i=await t.text().catch(()=>"");throw new Error(`enrollment failed (${t.status}): ${i.slice(0,300)}`)}let r=_u.EnrollResponse.parse(await t.json()),s={...n,runnerId:r.runnerId,runnerToken:r.runnerToken};return fe(s),s}function ng(){try{let n=process.argv[1]?di.default.realpathSync(process.argv[1]):"";for(let e of[ws.default.dirname(n),ws.default.dirname(ws.default.dirname(n))]){let t=ws.default.join(e,"package.json");if(!di.default.existsSync(t))continue;let r=JSON.parse(di.default.readFileSync(t,"utf8")).version;if(typeof r=="string"&&r)return r}}catch{}return"0.0.0"}var hi=ng();gt();var Pu="Posted automatically by Allwright",rg=["Posted automatically by TicketPilot"],yt=n=>n.includes(Pu)||rg.some(e=>n.includes(e));var Ce=class{constructor(e){this.auth=e}auth;headers(){return{Authorization:`Basic ${Buffer.from(`${this.auth.email}:${this.auth.apiToken}`).toString("base64")}`,Accept:"application/json","Content-Type":"application/json"}}async request(e,t,r){let s=new URL(t,this.auth.baseUrl).toString(),i=await fetch(s,{method:e,headers:this.headers(),body:r===void 0?void 0:JSON.stringify(r)});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`Jira ${e} ${t} -> ${i.status}: ${o.slice(0,500)}`)}if(i.status!==204)return await i.json()}async myself(){return this.request("GET","/rest/api/3/myself")}async searchUsers(e,t=20){let r=await this.userSearch(e,t);return r.length||!e.includes("@")?r:this.userSearch(e.slice(0,e.indexOf("@")),t)}async userSearch(e,t){return e.trim()?(await this.request("GET",`/rest/api/3/user/search?query=${encodeURIComponent(e)}&maxResults=${t}`)??[]).filter(s=>s.accountId&&(s.accountType??"atlassian")==="atlassian").map(s=>({accountId:s.accountId,displayName:s.displayName??"(no name)",email:s.emailAddress??"",active:s.active??!0})):[]}async search(e,t=20){return((await this.request("POST","/rest/api/3/search/jql",{jql:e,maxResults:t,fields:["summary","components"]})).issues??[]).map(s=>({key:s.key,summary:s.fields?.summary??"",components:(s.fields?.components??[]).map(i=>i.name??"").filter(Boolean)}))}async projectStatuses(e){let t=await this.request("GET",`/rest/api/3/project/${encodeURIComponent(e)}/statuses`),r=new Map;for(let i of t??[])for(let o of i.statuses??[])o.name&&!r.has(o.name)&&r.set(o.name,o.statusCategory?.key??"indeterminate");let s=i=>i==="new"?0:i==="done"?2:1;return[...r.entries()].sort((i,o)=>s(i[1])-s(o[1])).map(([i])=>i)}async searchEpics(e,t=20){return((await this.request("POST","/rest/api/3/search/jql",{jql:`project = "${e}" AND issuetype = Epic AND statusCategory != Done ORDER BY created DESC`,maxResults:t,fields:["summary","status"]})).issues??[]).map(s=>({key:s.key,summary:s.fields?.summary??"",status:s.fields?.status?.name??""}))}async epicChildren(e,t=50){return((await this.request("POST","/rest/api/3/search/jql",{jql:`parent = "${e}" ORDER BY created ASC`,maxResults:t,fields:["summary","status","labels"]})).issues??[]).map(s=>({key:s.key,summary:s.fields?.summary??"",status:s.fields?.status?.name??"",statusCategory:s.fields?.status?.statusCategory?.key??"indeterminate",labels:s.fields?.labels??[]}))}async searchBoard(e,t=100){return((await this.request("POST","/rest/api/3/search/jql",{jql:e,maxResults:t,fields:["summary","status","labels"]})).issues??[]).map(s=>({key:s.key,summary:s.fields?.summary??"",status:s.fields?.status?.name??"(no status)",statusId:s.fields?.status?.id??"",labels:s.fields?.labels??[]}))}async boardColumns(e){try{let r=(await this.request("GET",`/rest/agile/1.0/board?projectKeyOrId=${encodeURIComponent(e)}`)).values?.[0]?.id;if(!r)return null;let i=((await this.request("GET",`/rest/agile/1.0/board/${r}/configuration`)).columnConfig?.columns??[]).filter(o=>(o.statuses??[]).length>0&&o.name).map(o=>({name:o.name,statusIds:(o.statuses??[]).map(l=>l.id??"").filter(Boolean)}));return i.length?i:null}catch{return null}}async getIssue(e){let t=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}?fields=summary,description,labels,comment,status,attachment`),r;try{r=await this.listAllComments(e)}catch{r=t.fields.comment?.comments??[]}let s=r.map(o=>({id:o.id??"",author:o.author?.displayName??"unknown",authorAccountId:o.author?.accountId??null,created:o.created,body:$u(o.body)})),i=(t.fields.attachment??[]).filter(o=>o.id&&o.filename&&o.content).map(o=>({id:o.id,filename:o.filename,mimeType:o.mimeType??"",size:o.size??0,contentUrl:o.content}));return{key:t.key,summary:t.fields.summary??"",description:$u(t.fields.description),labels:t.fields.labels??[],status:t.fields.status?.name??"",comments:s,attachments:i}}async listAllComments(e){let t=await this.fetchCommentPage(e,0),r=t.total??t.comments.length;if(r<=t.comments.length)return t.comments;let s=Math.max(0,r-200),i=s===0?[...t.comments]:[];for(;i.length<Math.min(r,200);){let o=await this.fetchCommentPage(e,s+i.length);if(!o.comments.length)break;i.push(...o.comments)}return i.slice(-200)}async fetchCommentPage(e,t){let r=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}/comment?startAt=${t}&maxResults=100`);return{comments:r.comments??[],total:r.total}}async downloadAttachment(e){let t=await fetch(e,{headers:this.headers()});if(!t.ok)throw new Error(`attachment download failed: ${t.status}`);return Buffer.from(await t.arrayBuffer())}async lastEnteredStatus(e,t){let r=await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}?expand=changelog&fields=status`),s=t.toLowerCase(),i=null;for(let o of r.changelog?.histories??[])(o.items??[]).some(u=>(u.field==="status"||u.fieldId==="status")&&(u.toString??"").toLowerCase()===s)&&(!i||new Date(o.created)>new Date(i.at))&&(i={at:o.created,author:o.author?.displayName??"unknown",authorAccountId:o.author?.accountId??null});return i}async createIssue(e,t,r,s="Task",i){return{key:(await this.request("POST","/rest/api/3/issue",{fields:{project:{key:e},issuetype:{name:s},summary:t.slice(0,250),description:Xo(r),...i?{parent:{key:i}}:{}}})).key}}async addAttachments(e,t){if(!t.length)return;let r=new FormData;for(let l of t)r.append("file",new Blob([new Uint8Array(l.content)]),l.name.slice(0,255));let s=new URL(`/rest/api/3/issue/${encodeURIComponent(e)}/attachments`,this.auth.baseUrl).toString(),i=Buffer.from(`${this.auth.email}:${this.auth.apiToken}`).toString("base64"),o=await fetch(s,{method:"POST",headers:{Authorization:`Basic ${i}`,Accept:"application/json","X-Atlassian-Token":"no-check"},body:r});if(!o.ok)throw new Error(`Jira attachment upload failed: HTTP ${o.status}`)}async addTriggerComment(e,t){await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/comment`,{body:Xo(t)})}async addComment(e,t){let r=`${t}
274
274
 
275
275
  ---
276
- _${xu} - never treated as a trigger._`;await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/comment`,{body:Ho(r)})}async editLabels(e,t){let r=[...(t.add??[]).map(s=>({add:s})),...(t.remove??[]).map(s=>({remove:s}))];await this.request("PUT",`/rest/api/3/issue/${encodeURIComponent(e)}`,{update:{labels:r}})}async getTransitions(e){return((await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}/transitions`)).transitions??[]).map(r=>({id:r.id,name:r.name}))}async transition(e,t){await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/transitions`,{transition:{id:t}})}async transitionByName(e,t){let s=(await this.getTransitions(e)).find(i=>i.name.toLowerCase()===t.toLowerCase());return s?(await this.transition(e,s.id),!0):!1}};function Tu(n){if(!n)return"";let e=[],t=r=>{r.text&&e.push(r.text),r.type==="hardBreak"&&e.push(`
276
+ _${Pu} - never treated as a trigger._`;await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/comment`,{body:Xo(r)})}async editLabels(e,t){let r=[...(t.add??[]).map(s=>({add:s})),...(t.remove??[]).map(s=>({remove:s}))];await this.request("PUT",`/rest/api/3/issue/${encodeURIComponent(e)}`,{update:{labels:r}})}async getTransitions(e){return((await this.request("GET",`/rest/api/3/issue/${encodeURIComponent(e)}/transitions`)).transitions??[]).map(r=>({id:r.id,name:r.name}))}async transition(e,t){await this.request("POST",`/rest/api/3/issue/${encodeURIComponent(e)}/transitions`,{transition:{id:t}})}async transitionByName(e,t){let s=(await this.getTransitions(e)).find(i=>i.name.toLowerCase()===t.toLowerCase());return s?(await this.transition(e,s.id),!0):!1}};function $u(n){if(!n)return"";let e=[],t=r=>{r.text&&e.push(r.text),r.type==="hardBreak"&&e.push(`
277
277
  `);for(let s of r.content??[])t(s);r.type&&["paragraph","heading","listItem","codeBlock","blockquote"].includes(r.type)&&e.push(`
278
278
  `)};return t(n),e.join("").replace(/\n{3,}/g,`
279
279
 
280
- `).trim()}function Ho(n){let e=n.replace(/\r\n/g,`
280
+ `).trim()}function Xo(n){let e=n.replace(/\r\n/g,`
281
281
  `).split(`
282
282
  `),t=[],r=0,s=i=>{let o=[],l=/(\*\*[^*]+\*\*|`[^`]+`)/g,u=0,c;for(;(c=l.exec(i))!==null;){c.index>u&&o.push({type:"text",text:i.slice(u,c.index)});let f=c[0];f.startsWith("**")?o.push({type:"text",text:f.slice(2,-2),marks:[{type:"strong"}]}):o.push({type:"text",text:f.slice(1,-1),marks:[{type:"code"}]}),u=c.index+f.length}return u<i.length&&o.push({type:"text",text:i.slice(u)}),o.length?o:[{type:"text",text:" "}]};for(;r<e.length;){let i=e[r];if(i.trim()===""){r++;continue}let o=i.match(/^```(\w*)\s*$/);if(o){let p=[];for(r++;r<e.length&&!/^```\s*$/.test(e[r]);)p.push(e[r]),r++;r++,t.push({type:"codeBlock",attrs:o[1]?{language:o[1]}:{},content:[{type:"text",text:p.join(`
283
- `)||" "}]});continue}let l=i.match(/^(#{1,6})\s+(.*)$/);if(l){t.push({type:"heading",attrs:{level:l[1].length},content:s(l[2])}),r++;continue}if(i.match(/^\s*[-*]\s+(.*)$/)){let p=[];for(;r<e.length;){let b=e[r].match(/^\s*[-*]\s+(.*)$/);if(!b)break;p.push({type:"listItem",content:[{type:"paragraph",content:s(b[1])}]}),r++}t.push({type:"bulletList",content:p});continue}if(i.match(/^\s*\d+[.)]\s+(.*)$/)){let p=[];for(;r<e.length;){let b=e[r].match(/^\s*\d+[.)]\s+(.*)$/);if(!b)break;p.push({type:"listItem",content:[{type:"paragraph",content:s(b[1])}]}),r++}t.push({type:"orderedList",content:p});continue}let f=[i];for(r++;r<e.length&&e[r].trim()!==""&&!/^(#{1,6}\s|```|\s*[-*]\s|\s*\d+[.)]\s)/.test(e[r]);)f.push(e[r]),r++;t.push({type:"paragraph",content:s(f.join(" "))})}return{type:"doc",version:1,content:t}}function Cu(n,e,t){let r=n.repos[e]?.jira??n.jira;if(!r)return{kind:"legacy"};let s=t.trim().toLowerCase();if(!s)return{kind:"legacy"};if(s===r.email.toLowerCase())return{kind:"self"};let i=n.jiraUsers[s];return i?{kind:"user",creds:{baseUrl:r.baseUrl,email:i.email,apiToken:i.apiToken}}:{kind:"missing",error:`Jira actions from Allwright post under YOUR OWN Atlassian identity, and no Jira credential is set up for ${s} on the runner yet. Ask your admin to run this on the runner machine:
283
+ `)||" "}]});continue}let l=i.match(/^(#{1,6})\s+(.*)$/);if(l){t.push({type:"heading",attrs:{level:l[1].length},content:s(l[2])}),r++;continue}if(i.match(/^\s*[-*]\s+(.*)$/)){let p=[];for(;r<e.length;){let b=e[r].match(/^\s*[-*]\s+(.*)$/);if(!b)break;p.push({type:"listItem",content:[{type:"paragraph",content:s(b[1])}]}),r++}t.push({type:"bulletList",content:p});continue}if(i.match(/^\s*\d+[.)]\s+(.*)$/)){let p=[];for(;r<e.length;){let b=e[r].match(/^\s*\d+[.)]\s+(.*)$/);if(!b)break;p.push({type:"listItem",content:[{type:"paragraph",content:s(b[1])}]}),r++}t.push({type:"orderedList",content:p});continue}let f=[i];for(r++;r<e.length&&e[r].trim()!==""&&!/^(#{1,6}\s|```|\s*[-*]\s|\s*\d+[.)]\s)/.test(e[r]);)f.push(e[r]),r++;t.push({type:"paragraph",content:s(f.join(" "))})}return{type:"doc",version:1,content:t}}function ju(n,e,t){let r=n.repos[e]?.jira??n.jira;if(!r)return{kind:"legacy"};let s=t.trim().toLowerCase();if(!s)return{kind:"legacy"};if(s===r.email.toLowerCase())return{kind:"self"};let i=n.jiraUsers[s];return i?{kind:"user",creds:{baseUrl:r.baseUrl,email:i.email,apiToken:i.apiToken}}:{kind:"missing",error:`Jira actions from Allwright post under YOUR OWN Atlassian identity, and no Jira credential is set up for ${s} on the runner yet. Ask your admin to run this on the runner machine:
284
284
 
285
285
  allwright jira user-add ${s}
286
286
 
287
- It prompts for your Atlassian email and an API token (create one at id.atlassian.com -> Security -> API tokens). Takes effect immediately - then just retry this action.`}}Wn();var Jn=require("node:child_process"),Dr=R(require("node:fs"),1),Vo=R(require("node:os"),1),Jo=R(require("node:path"),1);var ys="allwright",Ru=`/etc/systemd/system/${ys}.service`,Wo="ticketpilot-runner";function Yo(){let n=process.env.SUDO_USER&&process.env.SUDO_USER!=="root"?process.env.SUDO_USER:"",e=n||Vo.default.userInfo().username,t=n?Jo.default.join("/home",n):Vo.default.homedir();return{nodePath:process.execPath,scriptPath:Dr.default.realpathSync(process.argv[1]),user:e,home:t}}function Xo(n){let e=Jo.default.dirname(n.nodePath);return`[Unit]
287
+ It prompts for your Atlassian email and an API token (create one at id.atlassian.com -> Security -> API tokens). Takes effect immediately - then just retry this action.`}}Xn();var Qn=require("node:child_process"),Fr=R(require("node:fs"),1),Qo=R(require("node:os"),1),ta=R(require("node:path"),1);var ks="allwright",Nu=`/etc/systemd/system/${ks}.service`,ea="ticketpilot-runner";function na(){let n=process.env.SUDO_USER&&process.env.SUDO_USER!=="root"?process.env.SUDO_USER:"",e=n||Qo.default.userInfo().username,t=n?ta.default.join("/home",n):Qo.default.homedir();return{nodePath:process.execPath,scriptPath:Fr.default.realpathSync(process.argv[1]),user:e,home:t}}function ra(n){let e=ta.default.dirname(n.nodePath);return`[Unit]
288
288
  Description=Allwright runner
289
289
  After=network-online.target
290
290
 
@@ -302,8 +302,8 @@ TimeoutStopSec=2h
302
302
 
303
303
  [Install]
304
304
  WantedBy=multi-user.target
305
- `}function Eu(){return process.platform==="linux"&&Dr.default.existsSync("/run/systemd/system")}function Au(n){if(!Eu())throw new Error(process.platform==="win32"?"Windows service install isn't built in yet - use NSSM: nssm install allwright <node> <this script> start --foreground":"no systemd on this machine - run `allwright start` (background mode) instead");let e=Yo(),t=Xo(e);if(typeof process.getuid=="function"&&process.getuid()!==0){n.info("Root is needed to write the unit. Re-run as:"),n.info(' sudo env "PATH=$PATH" allwright service install'),n.info("(the env PATH part matters when node is installed via nvm - plain sudo can't find it)"),n.info(""),n.info(`This is exactly what it will write to ${Ru}:`),n.info(`
306
- `+t);return}try{(0,Jn.execFileSync)("systemctl",["disable","--now",Wo]),n.info(`stopped the old ${Wo} service - this one replaces it`)}catch{}let r=cs();if(r)try{process.kill(r,"SIGTERM"),n.info(`stopped the running runner (pid ${r}) - the service takes over`)}catch{}Dr.default.writeFileSync(Ru,t),(0,Jn.execFileSync)("systemctl",["daemon-reload"]),(0,Jn.execFileSync)("systemctl",["enable","--now",ys]),(0,Jn.execFileSync)("systemctl",["restart",ys]),n.info(`Installed and started (runs as ${e.user}, survives reboots).`),n.info(`Watch it: journalctl -u ${ys} -f`),n.info("Status: allwright service status")}function $u(n){if(!Eu())throw new Error("no systemd on this machine");if(typeof process.getuid=="function"&&process.getuid()!==0)throw new Error("root is needed - run: sudo allwright service uninstall");for(let e of[ys,Wo]){try{(0,Jn.execFileSync)("systemctl",["disable","--now",e])}catch{}let t=`/etc/systemd/system/${e}.service`;Dr.default.existsSync(t)&&Dr.default.rmSync(t)}(0,Jn.execFileSync)("systemctl",["daemon-reload"]),n.info("Service removed. The runner config and credentials were not touched.")}var Pu=R(we(),1);function ju(n){return n.filter(e=>e.statusCategory!=="done"&&!e.labels.includes("agent-implemented")&&!e.labels.includes(Pu.NEEDS_INPUT_LABEL))}function Ou(n,e,t){let r=t.map(s=>{let i=(s.description??"").trim().slice(0,600);return`- ${s.key} [${s.status}] ${s.summary}${i?`
305
+ `}function Mu(){return process.platform==="linux"&&Fr.default.existsSync("/run/systemd/system")}function zu(n){if(!Mu())throw new Error(process.platform==="win32"?"Windows service install isn't built in yet - use NSSM: nssm install allwright <node> <this script> start --foreground":"no systemd on this machine - run `allwright start` (background mode) instead");let e=na(),t=ra(e);if(typeof process.getuid=="function"&&process.getuid()!==0){n.info("Root is needed to write the unit. Re-run as:"),n.info(' sudo env "PATH=$PATH" allwright service install'),n.info("(the env PATH part matters when node is installed via nvm - plain sudo can't find it)"),n.info(""),n.info(`This is exactly what it will write to ${Nu}:`),n.info(`
306
+ `+t);return}try{(0,Qn.execFileSync)("systemctl",["disable","--now",ea]),n.info(`stopped the old ${ea} service - this one replaces it`)}catch{}let r=ms();if(r)try{process.kill(r,"SIGTERM"),n.info(`stopped the running runner (pid ${r}) - the service takes over`)}catch{}Fr.default.writeFileSync(Nu,t),(0,Qn.execFileSync)("systemctl",["daemon-reload"]),(0,Qn.execFileSync)("systemctl",["enable","--now",ks]),(0,Qn.execFileSync)("systemctl",["restart",ks]),n.info(`Installed and started (runs as ${e.user}, survives reboots).`),n.info(`Watch it: journalctl -u ${ks} -f`),n.info("Status: allwright service status")}function Du(n){if(!Mu())throw new Error("no systemd on this machine");if(typeof process.getuid=="function"&&process.getuid()!==0)throw new Error("root is needed - run: sudo allwright service uninstall");for(let e of[ks,ea]){try{(0,Qn.execFileSync)("systemctl",["disable","--now",e])}catch{}let t=`/etc/systemd/system/${e}.service`;Fr.default.existsSync(t)&&Fr.default.rmSync(t)}(0,Qn.execFileSync)("systemctl",["daemon-reload"]),n.info("Service removed. The runner config and credentials were not touched.")}var Lu=R(we(),1);function Uu(n){return n.filter(e=>e.statusCategory!=="done"&&!e.labels.includes("agent-implemented")&&!e.labels.includes(Lu.NEEDS_INPUT_LABEL))}function qu(n,e,t){let r=t.map(s=>{let i=(s.description??"").trim().slice(0,600);return`- ${s.key} [${s.status}] ${s.summary}${i?`
307
307
  ${i.replace(/\n+/g," ")}`:""}`}).join(`
308
308
  `);return`You are looking at this repository to help sequence work on the Jira epic ${n} ("${e}"). These child tickets are still pending:
309
309
 
@@ -314,7 +314,7 @@ Pick the ONE ticket that should be implemented FIRST. Weigh, in this order: (1)
314
314
  Answer with ONLY a fenced json block, nothing after it:
315
315
  \`\`\`json
316
316
  {"issueKey": "<one of the keys above>", "reason": "<2-3 sentences: why this one first, and what it unblocks>"}
317
- \`\`\``}function Nu(n,e){let r=n.match(/```(?:json)?\s*(\{[\s\S]*?\})\s*```/)?.[1]??n.match(/\{[\s\S]*"issueKey"[\s\S]*?\}/)?.[0];if(!r)return{error:"the agent's answer contained no JSON recommendation"};try{let s=JSON.parse(r),i=typeof s.issueKey=="string"?s.issueKey.trim():"",o=typeof s.reason=="string"?s.reason.trim():"";return e.includes(i)?{issueKey:i,reason:o||"(no reasoning given)"}:{error:`the agent recommended "${i}", which is not a pending child of this epic`}}catch{return{error:"the agent's JSON recommendation did not parse"}}}var oa=require("node:crypto"),ic=R(require("node:fs"),1);var Qo=R(require("node:fs"),1),gi=R(require("node:path"),1),yi=R(we(),1),Vm={security:"You are a security auditor. You can READ this repository; you can never run or change anything. Audit it against the knowledge packs below and report real, exploitable-here problems - not checklist theatre.",testing:"You are a test-coverage auditor. You can READ this repository (code and tests); you can never run anything. Find what is untested and fragile against the knowledge packs below - gaps that would actually bite this product, not generic coverage philosophy.",architecture:"You are a software architecture auditor. You can READ this repository; you can never run or change anything. Judge whether it is structurally HEALTHY for what it is trying to be, against the knowledge packs below - real structural pain for this team, not textbook purity."};function zu(n,e,t,r={}){let s=e.map(u=>`### Pack: ${u.name}
317
+ \`\`\``}function Fu(n,e){let r=n.match(/```(?:json)?\s*(\{[\s\S]*?\})\s*```/)?.[1]??n.match(/\{[\s\S]*"issueKey"[\s\S]*?\}/)?.[0];if(!r)return{error:"the agent's answer contained no JSON recommendation"};try{let s=JSON.parse(r),i=typeof s.issueKey=="string"?s.issueKey.trim():"",o=typeof s.reason=="string"?s.reason.trim():"";return e.includes(i)?{issueKey:i,reason:o||"(no reasoning given)"}:{error:`the agent recommended "${i}", which is not a pending child of this epic`}}catch{return{error:"the agent's JSON recommendation did not parse"}}}var fa=require("node:crypto"),pc=R(require("node:fs"),1);var sa=R(require("node:fs"),1),wi=R(require("node:path"),1),_i=R(we(),1),sg={security:"You are a security auditor. You can READ this repository; you can never run or change anything. Audit it against the knowledge packs below and report real, exploitable-here problems - not checklist theatre.",testing:"You are a test-coverage auditor. You can READ this repository (code and tests); you can never run anything. Find what is untested and fragile against the knowledge packs below - gaps that would actually bite this product, not generic coverage philosophy.",architecture:"You are a software architecture auditor. You can READ this repository; you can never run or change anything. Judge whether it is structurally HEALTHY for what it is trying to be, against the knowledge packs below - real structural pain for this team, not textbook purity."};function Ku(n,e,t,r={}){let s=e.map(u=>`### Pack: ${u.name}
318
318
 
319
319
  ${u.content}`).join(`
320
320
 
@@ -334,7 +334,7 @@ Read whatever surrounding code you need for context, but every finding must be a
334
334
 
335
335
  ${r.testResults}
336
336
 
337
- Fold what these results show - failures, flaky exits, suspiciously green suites - into your findings with the rest of the audit.`:"";return`${Vm[n]}
337
+ Fold what these results show - failures, flaky exits, suspiciously green suites - into your findings with the rest of the audit.`:"";return`${sg[n]}
338
338
 
339
339
  Knowledge below is LAYERED: global (product) -> org (this company) -> project (this repo). More specific levels OVERRIDE general ones; entries referencing a rule id (SEC-001 style) modify or disable that rule.
340
340
 
@@ -348,8 +348,20 @@ Explore the repository first - entry points, routes, storage, tests - then audit
348
348
  "evidence": [{"file": "<repo-relative path>", "line": <number, omit if n/a>, "note": "<what is there>"}],
349
349
  "fix": "<2-4 sentences: concrete fix, specific to this code>"}]}
350
350
  \`\`\`
351
- Rules: every finding needs at least one evidence file you actually read - findings without real evidence will be DELETED from your report. Max 25 findings, worst first. An empty findings list with an honest summary is a valid, good answer.`}function Du(n){let t=n.match(/```(?:json)?\s*(\{[\s\S]*\})\s*```(?![\s\S]*```)/)?.[1]??n.match(/\{[\s\S]*"findings"[\s\S]*\}/)?.[0];if(!t)return{error:"the agent's report contained no JSON block"};let r;try{r=JSON.parse(t)}catch{return{error:"the agent's JSON report did not parse"}}if(!Array.isArray(r.findings))return{error:"the report has no findings array"};let s=[],i=0,o=new Set;for(let l of r.findings.slice(0,25)){let u=Wm(l),c=u?yi.AuditFinding.safeParse(u):null;if(!c?.success){i++;continue}let f=c.data.id;for(;o.has(f);)f=`${f}-2`;o.add(f),s.push({...c.data,id:f})}return{summary:typeof r.summary=="string"?r.summary.trim().slice(0,2e3):"",findings:s,dropped:i}}function Wm(n){if(typeof n!="object"||n===null)return null;let e=n,t=typeof e.severity=="string"?e.severity.toLowerCase():"",r=Array.isArray(e.evidence)?e.evidence.filter(i=>typeof i=="object"&&i!==null).map(i=>({file:typeof i.file=="string"?i.file:"",...Mu(i.line)?{line:Mu(i.line)}:{},note:typeof i.note=="string"?i.note:""})).filter(i=>i.file):[],s=typeof e.ruleId=="string"?e.ruleId.trim().toUpperCase():"";return{id:Jm(typeof e.id=="string"&&e.id?e.id:String(e.title??"")),ruleId:/^[A-Z]{2,8}-\d{1,4}$/.test(s)?s:"",title:typeof e.title=="string"?e.title.slice(0,200):"",severity:yi.AuditSeverity.options.includes(t)?t:void 0,area:typeof e.area=="string"?e.area.slice(0,60):"",evidence:r,fix:typeof e.fix=="string"?e.fix.slice(0,2e3):""}}function Mu(n){let e=typeof n=="number"?n:typeof n=="string"?parseInt(n,10):NaN;return Number.isInteger(e)&&e>0?e:void 0}function Jm(n){return n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"finding"}function Ym(n){try{let e=Qo.default.readFileSync(n,"utf8");return e?e.split(`
352
- `).length:0}catch{return null}}function Lu(n,e){let t=gi.default.resolve(n),r=[],s=[],i=0;for(let o of e){let l=[];for(let u of o.evidence){let c=u.file.trim().replace(/^\.\//,""),f=gi.default.resolve(t,c);if(f!==t&&!f.startsWith(t+gi.default.sep))continue;let p;try{p=Qo.default.statSync(f)}catch{continue}if(p.isFile()){if(u.line!==void 0){let b=Ym(f);if(b!==null&&u.line>b){l.push({...u,line:void 0}),i++;continue}}l.push(u)}}if(!l.length){s.push({title:o.title,files:o.evidence.map(u=>u.file)});continue}r.push({...o,evidence:l})}return{findings:r,droppedFindings:s,correctedLines:i}}var vs=R(require("node:fs"),1),ea=R(require("node:path"),1),Uu=R(we(),1);var Xm=20;function qu(){return ea.default.join(re(),"audits.json")}function Lr(){try{return{byProject:JSON.parse(vs.default.readFileSync(qu(),"utf8")).byProject??{}}}catch{return{byProject:{}}}}function Fu(n){let e=qu();vs.default.mkdirSync(ea.default.dirname(e),{recursive:!0,mode:448});let t=e+".tmp";vs.default.writeFileSync(t,JSON.stringify(n,null,2),{mode:384}),vs.default.renameSync(t,e)}function Bu(n,e){let t=Lr(),r=t.byProject[n]??[];r.unshift(Uu.AuditRecord.parse(e)),t.byProject[n]=r.slice(0,Xm),Fu(t)}function Ku(n){return(Lr().byProject[n]??[]).map(e=>{let t={};for(let r of e.findings)t[r.severity]=(t[r.severity]??0)+1;return{id:e.id,role:e.role,createdAt:e.createdAt,findingCount:e.findings.length,bySeverity:t}})}function Zu(n,e){let t=Lr(),r=e?Date.parse(e):NaN,s={};for(let i of n){let o=(t.byProject[i]??[]).filter(u=>!Number.isFinite(r)||Date.parse(u.createdAt)>=r);if(!o.length)continue;let l={audits:o.length,findings:0,valid:0,falsePositive:0,wontFix:0,unreviewed:0};for(let u of o){l.findings+=u.findings.length;for(let c of u.findings){let f=u.verdicts[c.id]?.verdict;f==="valid"?l.valid++:f==="false-positive"?l.falsePositive++:f==="wont-fix"?l.wontFix++:l.unreviewed++}}s[i]=l}return s}function ta(n,e,t){let r=Lr(),i=(r.byProject[n]??[]).find(l=>l.id===e);if(!i)return null;i.ticketed??={},i.verdicts??={},i.lessonsWritten??=[];let o=new Set(i.findings.map(l=>l.id));t.selected&&(i.review={selected:t.selected.filter(l=>o.has(l)),updatedAt:new Date().toISOString()});for(let l of t.ticketed??[])o.has(l.findingId)&&(i.ticketed={...i.ticketed,[l.findingId]:l.issueKey});for(let l of t.verdicts??[])o.has(l.findingId)&&(i.verdicts={...i.verdicts,[l.findingId]:{verdict:l.verdict,note:l.note,by:t.verdictBy??"",at:new Date().toISOString()}});for(let l of t.markLessonsWritten??[])o.has(l)&&!i.lessonsWritten.includes(l)&&i.lessonsWritten.push(l);return Fu(r),i}function Gu(n,e){return(Lr().byProject[n]??[]).find(s=>s.role===e&&(s.scope?.kind??"repo")==="repo")?.createdAt??null}function Hu(n,e){return(Lr().byProject[n]??[]).find(t=>t.id===e)??null}pt();var Ce=R(require("node:fs"),1),gt=R(require("node:path"),1),Wu=R(we(),1);var Qm=`# Security baseline - what to check in any repo
351
+ Rules: every finding needs at least one evidence file you actually read - findings without real evidence will be DELETED from your report. Max 25 findings, worst first. An empty findings list with an honest summary is a valid, good answer.`}function Zu(n){let t=n.match(/```(?:json)?\s*(\{[\s\S]*\})\s*```(?![\s\S]*```)/)?.[1]??n.match(/\{[\s\S]*"findings"[\s\S]*\}/)?.[0];if(!t)return{error:"the agent's report contained no JSON block"};let r;try{r=JSON.parse(t)}catch{return{error:"the agent's JSON report did not parse"}}if(!Array.isArray(r.findings))return{error:"the report has no findings array"};let s=[],i=0,o=new Set;for(let l of r.findings.slice(0,25)){let u=ig(l),c=u?_i.AuditFinding.safeParse(u):null;if(!c?.success){i++;continue}let f=c.data.id;for(;o.has(f);)f=`${f}-2`;o.add(f),s.push({...c.data,id:f})}return{summary:typeof r.summary=="string"?r.summary.trim().slice(0,2e3):"",findings:s,dropped:i}}function ig(n){if(typeof n!="object"||n===null)return null;let e=n,t=typeof e.severity=="string"?e.severity.toLowerCase():"",r=Array.isArray(e.evidence)?e.evidence.filter(i=>typeof i=="object"&&i!==null).map(i=>({file:typeof i.file=="string"?i.file:"",...Bu(i.line)?{line:Bu(i.line)}:{},note:typeof i.note=="string"?i.note:""})).filter(i=>i.file):[],s=typeof e.ruleId=="string"?e.ruleId.trim().toUpperCase():"";return{id:og(typeof e.id=="string"&&e.id?e.id:String(e.title??"")),ruleId:/^[A-Z]{2,8}-\d{1,4}$/.test(s)?s:"",title:typeof e.title=="string"?e.title.slice(0,200):"",severity:_i.AuditSeverity.options.includes(t)?t:void 0,area:typeof e.area=="string"?e.area.slice(0,60):"",evidence:r,fix:typeof e.fix=="string"?e.fix.slice(0,2e3):""}}function Bu(n){let e=typeof n=="number"?n:typeof n=="string"?parseInt(n,10):NaN;return Number.isInteger(e)&&e>0?e:void 0}function og(n){return n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"finding"}function ag(n){try{let e=sa.default.readFileSync(n,"utf8");return e?e.split(`
352
+ `).length:0}catch{return null}}function Gu(n,e){let t=wi.default.resolve(n),r=[],s=[],i=0;for(let o of e){let l=[];for(let u of o.evidence){let c=u.file.trim().replace(/^\.\//,""),f=wi.default.resolve(t,c);if(f!==t&&!f.startsWith(t+wi.default.sep))continue;let p;try{p=sa.default.statSync(f)}catch{continue}if(p.isFile()){if(u.line!==void 0){let b=ag(f);if(b!==null&&u.line>b){l.push({...u,line:void 0}),i++;continue}}l.push(u)}}if(!l.length){s.push({title:o.title,files:o.evidence.map(u=>u.file)});continue}r.push({...o,evidence:l})}return{findings:r,droppedFindings:s,correctedLines:i}}var Ss=R(require("node:fs"),1),ia=R(require("node:path"),1),Hu=R(we(),1);var lg=20;function Vu(){return ia.default.join(se(),"audits.json")}function Br(){try{return{byProject:JSON.parse(Ss.default.readFileSync(Vu(),"utf8")).byProject??{}}}catch{return{byProject:{}}}}function Wu(n){let e=Vu();Ss.default.mkdirSync(ia.default.dirname(e),{recursive:!0,mode:448});let t=e+".tmp";Ss.default.writeFileSync(t,JSON.stringify(n,null,2),{mode:384}),Ss.default.renameSync(t,e)}function Ju(n,e){let t=Br(),r=t.byProject[n]??[];r.unshift(Hu.AuditRecord.parse(e)),t.byProject[n]=r.slice(0,lg),Wu(t)}function Yu(n){return(Br().byProject[n]??[]).map(e=>{let t={};for(let r of e.findings)t[r.severity]=(t[r.severity]??0)+1;return{id:e.id,role:e.role,createdAt:e.createdAt,findingCount:e.findings.length,bySeverity:t}})}function Xu(n,e){let t=Br(),r=e?Date.parse(e):NaN,s={};for(let i of n){let o=(t.byProject[i]??[]).filter(u=>!Number.isFinite(r)||Date.parse(u.createdAt)>=r);if(!o.length)continue;let l={audits:o.length,findings:0,valid:0,falsePositive:0,wontFix:0,unreviewed:0};for(let u of o){l.findings+=u.findings.length;for(let c of u.findings){let f=u.verdicts[c.id]?.verdict;f==="valid"?l.valid++:f==="false-positive"?l.falsePositive++:f==="wont-fix"?l.wontFix++:l.unreviewed++}}s[i]=l}return s}function oa(n,e,t){let r=Br(),i=(r.byProject[n]??[]).find(l=>l.id===e);if(!i)return null;i.ticketed??={},i.verdicts??={},i.lessonsWritten??=[];let o=new Set(i.findings.map(l=>l.id));t.selected&&(i.review={selected:t.selected.filter(l=>o.has(l)),updatedAt:new Date().toISOString()});for(let l of t.ticketed??[])o.has(l.findingId)&&(i.ticketed={...i.ticketed,[l.findingId]:l.issueKey});for(let l of t.verdicts??[])o.has(l.findingId)&&(i.verdicts={...i.verdicts,[l.findingId]:{verdict:l.verdict,note:l.note,by:t.verdictBy??"",at:new Date().toISOString()}});for(let l of t.markLessonsWritten??[])o.has(l)&&!i.lessonsWritten.includes(l)&&i.lessonsWritten.push(l);return Wu(r),i}function Qu(n,e){return(Br().byProject[n]??[]).find(s=>s.role===e&&(s.scope?.kind??"repo")==="repo")?.createdAt??null}function ec(n,e){return(Br().byProject[n]??[]).find(t=>t.id===e)??null}gt();var Ie=R(require("node:fs"),1),vt=R(require("node:path"),1),sc=R(we(),1);var Mt=R(require("node:fs"),1),aa=R(require("node:path"),1),ug=25e4,cg=2e5,tc=`# Incident ledger
353
+
354
+ Machine-written facts about this repository's runs: what failed, what
355
+ resolved it. Appended by the Allwright runner; humans may edit freely.
356
+ Newest entries are at the bottom.
357
+
358
+ `;function la(n){return aa.default.join(n,".ticketpilot","memory","incidents.md")}function rt(n,e){try{let t=la(n);Mt.default.mkdirSync(aa.default.dirname(t),{recursive:!0});let r=Mt.default.existsSync(t)?"":tc,s=new Date().toISOString().slice(0,10),i=e.detail?.trim();Mt.default.appendFileSync(t,r+`## ${s} \xB7 ${e.issueKey} \xB7 ${e.title} (run ${e.runId})
359
+ `+(i?`${i.slice(0,1500)}
360
+ `:"")+`
361
+ `),dg(t)}catch{}}function Ts(n,e){try{return Mt.default.readFileSync(la(n),"utf8").includes(`\xB7 ${e} \xB7`)}catch{return!1}}function dg(n){if(Mt.default.statSync(n).size<=ug)return;let r=Mt.default.readFileSync(n,"utf8").slice(-cg),s=r.indexOf(`
362
+ ## `),i=s===-1?r:r.slice(s+1);Mt.default.writeFileSync(n,tc+`*(older entries were rotated out)*
363
+
364
+ `+i)}function nc(n){try{return Mt.default.readFileSync(la(n),"utf8")}catch{return null}}var hg=`# Security baseline - what to check in any repo
353
365
 
354
366
  Every rule has a stable id. Findings must cite the id they violate.
355
367
 
@@ -392,7 +404,7 @@ Every rule has a stable id. Findings must cite the id they violate.
392
404
  - **SEC-042** TLS/redirect handling that downgrades to http.
393
405
 
394
406
  Prioritize by real exploitability in THIS codebase, not by rule order.
395
- `,eg=`# Test gaps - what to check in any repo
407
+ `,fg=`# Test gaps - what to check in any repo
396
408
 
397
409
  Every rule has a stable id. Findings must cite the id they violate.
398
410
 
@@ -422,7 +434,7 @@ Every rule has a stable id. Findings must cite the id they violate.
422
434
  flaky suspects.
423
435
 
424
436
  Report the GAP and why it is risky here, not generic coverage philosophy.
425
- `,tg=`# GDPR readiness - data-protection audit for repos with EU exposure
437
+ `,pg=`# GDPR readiness - data-protection audit for repos with EU exposure
426
438
 
427
439
  FIRST decide exposure: if this product clearly has no EU users, no personal
428
440
  data, or is a purely static/internal tool, say so in ONE summary sentence and
@@ -466,7 +478,7 @@ rules below. Cite the rule id AND map the area to the closest GDPR article
466
478
 
467
479
  Severity: many users' data exposed or a missing legal-basis mechanism is
468
480
  high/critical; hygiene and documentation gaps are medium/low.
469
- `,ng=`# Architecture health - is this repository structurally sound?
481
+ `,mg=`# Architecture health - is this repository structurally sound?
470
482
 
471
483
  Every rule has a stable id. Findings must cite the id they violate. Judge
472
484
  against what THIS codebase is trying to be (a static site does not need
@@ -505,47 +517,49 @@ deviations.
505
517
 
506
518
  Summarize with an overall verdict: is this repository HEALTHY for its
507
519
  purpose, and what are the 2-3 structural moves with the best payoff?
508
- `,Vu={security:[{name:"baseline.md",content:Qm},{name:"gdpr.md",content:tg}],testing:[{name:"test-gaps.md",content:eg}],architecture:[{name:"architecture-health.md",content:ng}],implement:[]},rg=["You are auditing code you can READ but never run or change.","You are auditing test coverage by READING code and tests","\\`area\\`"];function na(n){return gt.default.join(re(),"knowledge",n)}function Ju(n,e){return gt.default.join(n,".ticketpilot","knowledge",`${e}.md`)}function ra(n,e){return gt.default.join(n,".ticketpilot","lessons",`${e}.md`)}function Yu(n,e){let t=[],r=na(n),s=[];if(Ce.default.existsSync(r)){for(let u of Ce.default.readdirSync(r)){if(!u.endsWith(".md"))continue;let c=gt.default.join(r,u),f=Ce.default.readFileSync(c,"utf8");if(rg.some(p=>f.includes(p))&&Vu[n].map(b=>b.name).includes(u)&&!f.includes("SEC-0")&&!f.includes("TEST-0")&&!f.includes("GDPR-0")){Ce.default.rmSync(c);continue}s.push(u)}s.sort()}let i=new Set(s);for(let u of Vu[n])i.has(u.name)||t.push({level:"global",source:"pack",name:u.name,content:u.content,editable:!1});for(let u of s)t.push({level:"org",source:"pack",name:u,content:Ce.default.readFileSync(gt.default.join(r,u),"utf8").slice(0,3e4),editable:!0});let o=Ju(e,n);Ce.default.existsSync(o)&&t.push({level:"project",source:"pack",name:`${n}.md`,content:Ce.default.readFileSync(o,"utf8").slice(0,3e4),editable:!0});let l=ra(e,n);return Ce.default.existsSync(l)&&t.push({level:"project",source:"lessons",name:`${n}.md`,content:Ce.default.readFileSync(l,"utf8").slice(0,2e4),editable:!0}),t}function vi(n,e){let t=Yu(n,e);return{packs:t.filter(r=>r.source==="pack").map(r=>({name:`${r.level}/${r.name}`,content:r.content})),lessons:t.find(r=>r.source==="lessons")?.content??"",layers:t}}function sa(n,e,t,r="project"){let s=r==="org"?gt.default.join(na(e),"org-lessons.md"):ra(n,e);Ce.default.mkdirSync(gt.default.dirname(s),{recursive:!0});let i=Ce.default.existsSync(s)?"":`# ${e} lessons (${r} level)
520
+ `,rc={security:[{name:"baseline.md",content:hg},{name:"gdpr.md",content:pg}],testing:[{name:"test-gaps.md",content:fg}],architecture:[{name:"architecture-health.md",content:mg}],implement:[]},gg=["You are auditing code you can READ but never run or change.","You are auditing test coverage by READING code and tests","\\`area\\`"];function ua(n){return vt.default.join(se(),"knowledge",n)}function ic(n,e){return vt.default.join(n,".ticketpilot","knowledge",`${e}.md`)}function ca(n,e){return vt.default.join(n,".ticketpilot","lessons",`${e}.md`)}function oc(n,e){let t=[],r=ua(n),s=[];if(Ie.default.existsSync(r)){for(let u of Ie.default.readdirSync(r)){if(!u.endsWith(".md"))continue;let c=vt.default.join(r,u),f=Ie.default.readFileSync(c,"utf8");if(gg.some(p=>f.includes(p))&&rc[n].map(b=>b.name).includes(u)&&!f.includes("SEC-0")&&!f.includes("TEST-0")&&!f.includes("GDPR-0")){Ie.default.rmSync(c);continue}s.push(u)}s.sort()}let i=new Set(s);for(let u of rc[n])i.has(u.name)||t.push({level:"global",source:"pack",name:u.name,content:u.content,editable:!1});for(let u of s)t.push({level:"org",source:"pack",name:u,content:Ie.default.readFileSync(vt.default.join(r,u),"utf8").slice(0,3e4),editable:!0});let o=ic(e,n);Ie.default.existsSync(o)&&t.push({level:"project",source:"pack",name:`${n}.md`,content:Ie.default.readFileSync(o,"utf8").slice(0,3e4),editable:!0});let l=ca(e,n);return Ie.default.existsSync(l)&&t.push({level:"project",source:"lessons",name:`${n}.md`,content:Ie.default.readFileSync(l,"utf8").slice(0,2e4),editable:!0}),t}function ki(n,e){let t=oc(n,e);return{packs:t.filter(r=>r.source==="pack").map(r=>({name:`${r.level}/${r.name}`,content:r.content})),lessons:t.find(r=>r.source==="lessons")?.content??"",layers:t}}function da(n,e,t,r="project"){let s=r==="org"?vt.default.join(ua(e),"org-lessons.md"):ca(n,e);Ie.default.mkdirSync(vt.default.dirname(s),{recursive:!0});let i=Ie.default.existsSync(s)?"":`# ${e} lessons (${r} level)
509
521
 
510
522
  Human-confirmed corrections and rules. `+(e==="implement"?`Every implement run on this repo reads this BEFORE starting work.
511
523
 
512
524
  `:`Every ${e} audit reads this FIRST. Reference rule ids (SEC-001 style) when overriding a rule.
513
525
 
514
- `);Ce.default.appendFileSync(s,i+t.trimEnd()+`
526
+ `);Ie.default.appendFileSync(s,i+t.trimEnd()+`
515
527
 
516
- `)}function Xu(n,e,t,r){let s=new Date().toISOString().slice(0,10),i=n.evidence[0]?` (${n.evidence[0].file}${n.evidence[0].line?`:${n.evidence[0].line}`:""})`:"",o=n.ruleId?` \xB7 rule ${n.ruleId}`:"";return`## ${s} \xB7 ${e}${o} \xB7 ${n.title}${i}
528
+ `)}function ac(n,e,t,r){let s=new Date().toISOString().slice(0,10),i=n.evidence[0]?` (${n.evidence[0].file}${n.evidence[0].line?`:${n.evidence[0].line}`:""})`:"",o=n.ruleId?` \xB7 rule ${n.ruleId}`:"";return`## ${s} \xB7 ${e}${o} \xB7 ${n.title}${i}
517
529
  Finding \`${n.id}\` [${n.severity}] was marked **${e}**`+(r?` by ${r}`:"")+`.${t?` Reason: ${t}`:""}
518
- `+(e==="false-positive"?"Do not raise this class of finding here again unless the code meaningfully changes.":"Known and accepted - do not re-raise; mention only if its risk materially grows.")}function Qu(n,e){return`## ${new Date().toISOString().slice(0,10)} \xB7 taught${e?` by ${e}`:""}
519
- ${n.trim()}`}function ec(n){let e=[];for(let t of Wu.KnowledgeRole.options)for(let r of Yu(t,n))e.push({role:t,...r});return e}function tc(n,e,t,r,s,i){if(!/^[a-zA-Z0-9._-]+\.md$/.test(s))throw new Error("file name must be a simple .md name");let o=t==="org"?gt.default.join(na(e),s):r==="lessons"?ra(n,e):Ju(n,e);Ce.default.mkdirSync(gt.default.dirname(o),{recursive:!0}),Ce.default.writeFileSync(o,i,{mode:t==="org"?384:420})}var ia=()=>new Date().toISOString(),y={info:n=>console.log(`${ia()} [info] ${n}`),warn:n=>console.warn(`${ia()} [warn] ${n}`),error:n=>console.error(`${ia()} [error] ${n}`)};var nc=require("node:child_process"),rc=R(require("node:fs"),1),sc=R(require("node:path"),1);function Ur(n){for(let e of["TEST.md","TESTING.md","docs/TEST.md"]){let t=sc.default.join(n,e);if(rc.default.existsSync(t))return t}return null}function qr(n){let e=[];for(let t of n.matchAll(/```(?:bash|sh|shell)?\s*\n([\s\S]*?)```/g))for(let r of t[1].split(`
520
- `)){let s=r.trim();!s||s.startsWith("#")||e.push(s)}return e.slice(0,10)}async function Yn(n,e,t={}){let r=[],s=t.perCommandTimeoutMs??6e5;for(let i of e){t.onProgress?.(`running: ${i}`);let o=Date.now(),l=await new Promise(u=>{let c=(0,nc.spawn)("bash",["-lc",i],{cwd:n,env:{...process.env,CI:"1",FORCE_COLOR:"0"}}),f="",p=w=>{f+=w.toString(),f.length>2e5&&(f=f.slice(-1e5))};c.stdout.on("data",p),c.stderr.on("data",p);let b=setTimeout(()=>{c.kill("SIGKILL"),f+=`
521
- [killed: timed out]`},s);c.on("close",w=>{clearTimeout(b),u({command:i,exitCode:w??-1,durationMs:Date.now()-o,tail:f.slice(-4e3)})}),c.on("error",w=>{clearTimeout(b),u({command:i,exitCode:-1,durationMs:Date.now()-o,tail:String(w)})})});t.onProgress?.(`exit ${l.exitCode} in ${Math.round(l.durationMs/1e3)}s: ${i}`),r.push(l)}return r}async function Fr(n){let{packs:e,lessons:t}=vi(n.role,n.repoPath);if(!e.length)return{ok:!1,error:`no knowledge packs found for the ${n.role} role - add markdown files under ~/.config/ticketpilot/knowledge/${n.role}/ on the runner`};let r="";if(n.scope.kind==="ticket"&&n.scope.ref){let p=n.scope.ref,b="";try{let T=await n.jira.getIssue(p);b=`Ticket ${p}: ${T.summary}
530
+ `+(e==="false-positive"?"Do not raise this class of finding here again unless the code meaningfully changes.":"Known and accepted - do not re-raise; mention only if its risk materially grows.")}function lc(n,e){return`## ${new Date().toISOString().slice(0,10)} \xB7 taught${e?` by ${e}`:""}
531
+ ${n.trim()}`}function uc(n){let e=[];for(let r of sc.KnowledgeRole.options)for(let s of oc(r,n))e.push({role:r,...s});let t=nc(n);return t&&e.push({role:"implement",level:"project",source:"memory",name:"incidents.md",content:t.slice(-3e4),editable:!1}),e}function cc(n,e,t,r,s,i){if(!/^[a-zA-Z0-9._-]+\.md$/.test(s))throw new Error("file name must be a simple .md name");let o=t==="org"?vt.default.join(ua(e),s):r==="lessons"?ca(n,e):ic(n,e);Ie.default.mkdirSync(vt.default.dirname(o),{recursive:!0}),Ie.default.writeFileSync(o,i,{mode:t==="org"?384:420})}var ha=()=>new Date().toISOString(),y={info:n=>console.log(`${ha()} [info] ${n}`),warn:n=>console.warn(`${ha()} [warn] ${n}`),error:n=>console.error(`${ha()} [error] ${n}`)};var dc=require("node:child_process"),hc=R(require("node:fs"),1),fc=R(require("node:path"),1);function Kr(n){for(let e of["TEST.md","TESTING.md","docs/TEST.md"]){let t=fc.default.join(n,e);if(hc.default.existsSync(t))return t}return null}function Zr(n){let e=[];for(let t of n.matchAll(/```(?:bash|sh|shell)?\s*\n([\s\S]*?)```/g))for(let r of t[1].split(`
532
+ `)){let s=r.trim();!s||s.startsWith("#")||e.push(s)}return e.slice(0,10)}async function er(n,e,t={}){let r=[],s=t.perCommandTimeoutMs??6e5;for(let i of e){t.onProgress?.(`running: ${i}`);let o=Date.now(),l=await new Promise(u=>{let c=(0,dc.spawn)("bash",["-lc",i],{cwd:n,env:{...process.env,CI:"1",FORCE_COLOR:"0"}}),f="",p=w=>{f+=w.toString(),f.length>2e5&&(f=f.slice(-1e5))};c.stdout.on("data",p),c.stderr.on("data",p);let b=setTimeout(()=>{c.kill("SIGKILL"),f+=`
533
+ [killed: timed out]`},s);c.on("close",w=>{clearTimeout(b),u({command:i,exitCode:w??-1,durationMs:Date.now()-o,tail:f.slice(-4e3)})}),c.on("error",w=>{clearTimeout(b),u({command:i,exitCode:-1,durationMs:Date.now()-o,tail:String(w)})})});t.onProgress?.(`exit ${l.exitCode} in ${Math.round(l.durationMs/1e3)}s: ${i}`),r.push(l)}return r}async function Gr(n){let{packs:e,lessons:t}=ki(n.role,n.repoPath);if(!e.length)return{ok:!1,error:`no knowledge packs found for the ${n.role} role - add markdown files under ~/.config/ticketpilot/knowledge/${n.role}/ on the runner`};let r="";if(n.scope.kind==="ticket"&&n.scope.ref){let p=n.scope.ref,b="";try{let T=await n.jira.getIssue(p);b=`Ticket ${p}: ${T.summary}
522
534
 
523
- ${T.description}`.slice(0,4e3)}catch{b=`Ticket ${p} (could not fetch its text from Jira).`}let w=await Lo(n.repoPath,p).catch(()=>null);if(w){let{base:T,stat:x,diff:A}=await fi(n.repoPath,w).catch(()=>({base:"",stat:"",diff:""}));r=`${b}
535
+ ${T.description}`.slice(0,4e3)}catch{b=`Ticket ${p} (could not fetch its text from Jira).`}let w=await Ko(n.repoPath,p).catch(()=>null);if(w){let{base:T,stat:C,diff:A}=await yi(n.repoPath,w).catch(()=>({base:"",stat:"",diff:""}));r=`${b}
524
536
 
525
537
  Its implementation branch \`${w}\` vs \`${T}\`:
526
538
  \`\`\`
527
- ${x}\`\`\`
539
+ ${C}\`\`\`
528
540
  \`\`\`diff
529
541
  ${A}
530
542
  \`\`\``}else r=`${b}
531
543
 
532
- No implementation branch found for ${p} - audit the parts of the codebase this ticket touches or would touch.`}else if(n.scope.kind==="branch"&&n.scope.ref){let{base:p,stat:b,diff:w}=await fi(n.repoPath,n.scope.ref);r=`The diff of \`${n.scope.ref}\` vs \`${p}\`:
544
+ No implementation branch found for ${p} - audit the parts of the codebase this ticket touches or would touch.`}else if(n.scope.kind==="branch"&&n.scope.ref){let{base:p,stat:b,diff:w}=await yi(n.repoPath,n.scope.ref);r=`The diff of \`${n.scope.ref}\` vs \`${p}\`:
533
545
  \`\`\`
534
546
  ${b}\`\`\`
535
547
  \`\`\`diff
536
548
  ${w}
537
- \`\`\``}let s,i;if(n.role==="testing"){let p=Ur(n.repoPath),b=p?qr(ic.default.readFileSync(p,"utf8")):[];b.length&&(y.info(`Audit (testing): executing ${b.length} TEST.md command(s)`),i=await Yn(n.repoPath,b,{onProgress:w=>y.info(`[test-run] ${w}`)}),s=i.map(w=>`$ ${w.command}
549
+ \`\`\``}let s,i;if(n.role==="testing"){let p=Kr(n.repoPath),b=p?Zr(pc.default.readFileSync(p,"utf8")):[];b.length&&(y.info(`Audit (testing): executing ${b.length} TEST.md command(s)`),i=await er(n.repoPath,b,{onProgress:w=>y.info(`[test-run] ${w}`)}),s=i.map(w=>`$ ${w.command}
538
550
  (exit ${w.exitCode}, ${Math.round(w.durationMs/1e3)}s)
539
551
  ${w.tail.slice(-2e3)}`).join(`
540
552
 
541
553
  ---
542
554
 
543
- `))}let o=n.model||n.agent.adapter.deepModel,l=await n.agent.adapter.run({repoPath:n.repoPath,prompt:zu(n.role,e,t,{scopeNote:r,testResults:s}),timeoutSeconds:480,bin:n.agent.bin,mode:"read_only",maxTurns:120,sessionId:(0,oa.randomUUID)(),model:o,onLog:(p,b)=>{p==="agent"&&y.info(`[audit:${n.role}] ${b.slice(0,160)}`)}}),u=Du(l.resultText);if("error"in u)return{ok:!1,error:u.error};let c=Lu(n.repoPath,u.findings);for(let p of c.droppedFindings)y.warn(`[audit:${n.role}] dropped "${p.title}" - cited files do not exist: `+p.files.join(", "));let f={id:(0,oa.randomUUID)(),role:n.role,createdAt:new Date().toISOString(),model:l.model||o,summary:u.summary,packNames:e.map(p=>p.name),findings:c.findings,costUsd:l.costUsd??0,ticketed:{},verdicts:{},lessonsWritten:[],scope:n.scope,...i?{testRun:i}:{}};return Bu(n.projectId,f),y.info(`Audit (${n.role}${n.scope.kind!=="repo"?` \xB7 ${n.scope.kind}:${n.scope.ref}`:""}) done: ${c.findings.length} finding(s)`+(u.dropped?`, ${u.dropped} malformed`:"")+(c.droppedFindings.length?`, ${c.droppedFindings.length} dropped for citing files that do not exist`:"")+(c.correctedLines?`, ${c.correctedLines} bad line number(s) stripped`:"")),{ok:!0,audit:f}}var ar=R(we(),1);var va=R(require("node:fs"),1),Ci=R(require("node:path"),1),Ii=require("node:crypto"),ze=R(we(),1);var Xn=R(we(),1);var aa=R(require("node:fs"),1),oc=R(require("node:os"),1),bi=R(require("node:path"),1),ac=require("node:child_process"),lc=R(require("node:readline"),1),uc=R(we(),1),sg=4e3,ig={read_only:["Read(./**)","Glob(./**)","Grep(./**)"],edit_no_shell:["Read(./**)","Glob(./**)","Grep(./**)","Edit(./**)","Write(./**)"]};function og(n){if(process.env.ANTHROPIC_API_KEY)return"API key";let e=n??bi.default.join(oc.default.homedir(),".claude");try{if(aa.default.existsSync(bi.default.join(e,".credentials.json"))||aa.default.existsSync(bi.default.join(e,"credentials.json")))return"subscription"}catch{}return"unknown"}async function ag(n){let e=["-p","--output-format","stream-json","--verbose","--allowedTools",ig[n.mode].join(","),"--max-turns",String(n.maxTurns??60),...n.model?["--model",n.model]:[],...n.resume?["--resume",n.sessionId]:["--session-id",n.sessionId]],t=og(n.configDir);return t!=="unknown"&&n.onLog("info",t==="subscription"?"Billing: Claude subscription - costs shown are notional list prices, not money charged":"Billing: Anthropic API key - costs shown are actual metered spend"),new Promise(r=>{let s=(0,ac.spawn)(n.bin,e,{cwd:n.repoPath,env:n.configDir?{...process.env,CLAUDE_CONFIG_DIR:n.configDir}:process.env,stdio:["pipe","pipe","pipe"]}),i={ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,billingMode:t==="subscription"?"subscription":t==="API key"?"api":"unknown"},o=0,l=0,u=0,c=0,f=0,p=()=>{if(!n.onUsage)return;let Z=Date.now();Z-f<sg||(f=Z,n.onUsage({inputTokens:l,outputTokens:u,cacheReadTokens:c,turns:o}))},b=!1,w=()=>{b||(b=!0,clearTimeout(x),n.signal?.removeEventListener("abort",T),r(i))},T=()=>{i.cancelled=!0,i.error="stopped from the dashboard",n.onLog("error",i.error),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),3e3).unref()};n.signal?.addEventListener("abort",T,{once:!0});let x=setTimeout(()=>{i.timedOut=!0,i.error=`run exceeded ${n.timeoutSeconds}s wall-clock limit`,n.onLog("error",i.error),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),5e3).unref()},n.timeoutSeconds*1e3);s.stdin.write(n.prompt),s.stdin.end(),lc.default.createInterface({input:s.stdout}).on("line",Z=>{if(!Z.trim())return;let M;try{M=JSON.parse(Z)}catch{n.onLog("agent",Z.slice(0,1e3));return}if(M.type==="system"&&M.subtype==="init")i.model=typeof M.model=="string"?M.model:void 0,n.onLog("info",`Claude Code session started (model: ${M.model??"default"})`);else if(M.type==="assistant"){o+=1;let L=M.message?.usage;L&&(l+=Number(L.input_tokens??0)+Number(L.cache_creation_input_tokens??0),u+=Number(L.output_tokens??0),c+=Number(L.cache_read_input_tokens??0),p());for(let z of M.message?.content??[])if(z.type==="text"&&z.text?.trim())n.onLog("agent",z.text.trim().slice(0,4e3));else if(z.type==="tool_use"){let h=z.input??{},m=["file_path","path","pattern","command","description","url"].map(C=>typeof h[C]=="string"?`${C}=${h[C]}`:null).filter(Boolean).join(" "),g=JSON.stringify(h).slice(0,400);n.onLog("info",`tool ${z.name} ${m?`${m} `:""}${g}`)}}else M.type==="result"&&(i.costUsd=Number(M.total_cost_usd??0),i.inputTokens=Number(M.usage?.input_tokens??0)+Number(M.usage?.cache_creation_input_tokens??0),i.outputTokens=Number(M.usage?.output_tokens??0),l=Math.max(i.inputTokens,l),u=Math.max(i.outputTokens,u),i.inputTokens=l,i.outputTokens=u,c=Number(M.usage?.cache_read_input_tokens??c),i.cacheReadTokens=c,n.onUsage&&(n.onUsage({inputTokens:l,outputTokens:u,cacheReadTokens:c,costUsd:i.costUsd,turns:o}),f=Date.now()),M.subtype==="success"&&!M.is_error?(i.ok=!0,i.resultText=String(M.result??"")):M.subtype==="error_max_turns"?(i.turnLimitHit=!0,i.error=`hit the ${n.maxTurns??60}-turn limit before finishing`):(i.error=String(M.result??M.subtype??"unknown Claude Code error"),/rate.?limit|usage limit|limit (reached|exceeded)|overloaded/i.test(i.error)&&(i.error=`Claude usage limit hit for this account - the run will work again once the limit window resets. Original error: ${i.error.slice(0,400)}`)))});let v="";s.stderr.on("data",Z=>{v=(v+Z.toString()).slice(-2e3)}),s.on("error",Z=>{i.error=`failed to start ${n.bin}: ${Z.message}`,n.onLog("error",i.error),w()}),s.on("close",Z=>{!i.ok&&!i.error&&(i.error=i.timedOut?i.error:`claude exited with code ${Z}${v?`: ${v.slice(-500)}`:""}`),w()})})}var wi={id:"claude-code",displayName:"Claude Code",fastModel:"claude-sonnet-5",deepModel:"claude-fable-5",capabilities:uc.REGISTERED_AGENTS.find(n=>n.id==="claude-code").capabilities,run:ag};var cc=require("node:child_process"),dc=R(require("node:readline"),1),hc=R(we(),1);async function lg(n){if(n.mode!=="read_only")return{ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,error:"the codex adapter only supports read-only runs - its write sandbox cannot exclude shell, and Allwright never weakens a guarantee silently"};if(n.resume)return{ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,error:"the codex adapter cannot resume sessions"};let e=["exec","--json","--sandbox","read-only","--skip-git-repo-check","--cd",n.repoPath,...n.model?["--model",n.model]:[],"-"];return new Promise(t=>{let r=(0,cc.spawn)(n.bin,e,{cwd:n.repoPath,env:process.env,stdio:["pipe","pipe","pipe"]}),s={ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,cacheReadTokens:0},i="",o=!1,l=()=>{o||(o=!0,clearTimeout(u),t(s))},u=setTimeout(()=>{s.timedOut=!0,s.error=`run exceeded ${n.timeoutSeconds}s wall-clock limit`,n.onLog("error",s.error),r.kill("SIGTERM"),setTimeout(()=>r.kill("SIGKILL"),5e3).unref()},n.timeoutSeconds*1e3);r.stdin.write(n.prompt),r.stdin.end(),dc.default.createInterface({input:r.stdout}).on("line",p=>{if(!p.trim())return;let b;try{b=JSON.parse(p)}catch{n.onLog("agent",p.slice(0,1e3));return}let w=b.item??b.msg??b,T=w?.type??b.type,x=w?.text??w?.message??"";T==="agent_message"&&typeof x=="string"&&x.trim()?(i=x,n.onLog("agent",x.trim().slice(0,4e3))):T==="command_execution"||T==="exec_command_begin"?n.onLog("info",`tool ${String(w?.command??"").slice(0,300)}`):T==="error"&&typeof x=="string"&&x&&n.onLog("error",x.slice(0,1e3))});let f="";r.stderr.on("data",p=>{f=(f+p.toString()).slice(-2e3)}),r.on("error",p=>{s.error=`failed to start ${n.bin}: ${p.message} - is the Codex CLI installed and logged in?`,n.onLog("error",s.error),l()}),r.on("close",p=>{p===0&&i.trim()?(s.ok=!0,s.resultText=i):s.error||(s.error=`codex exited with code ${p}`+(i?"":" and produced no answer")+(f?`: ${f.slice(-500)}`:"")),l()})})}var la={id:"codex",fastModel:"",deepModel:"",displayName:"OpenAI Codex CLI (experimental)",capabilities:hc.REGISTERED_AGENTS.find(n=>n.id==="codex").capabilities,run:lg};var ug={[wi.id]:wi,[la.id]:la};function Me(n){return ug[n||Xn.DEFAULT_AGENT_ID]??null}function je(n,e){return!e||e===wi.id?n.claudeBin:n.agents[e]?.bin??e}function on(n,e){let t=Me(n);if(!t)return`no agent adapter named "${n}" on this runner - update the runner, or set the rule's agent to "${Xn.DEFAULT_AGENT_ID}"`;let r=(0,Xn.missingAgentCapabilities)(t.id,e);return r&&r.length?`agent "${t.displayName}" cannot run ${e} rules: it cannot guarantee ${r.join(", ")}. Allwright refuses rather than weakening the isolation silently.`:null}function tt(n,e,t){let r=e.defaultAgent||Xn.DEFAULT_AGENT_ID,s=Me(r);if(!s)return{error:`this project's default agent "${r}" is not on this runner - update the runner, or change the project's agent`};let i=(0,Xn.missingAgentCapabilities)(s.id,t);return i&&i.length?{error:`this project's default agent "${s.displayName}" cannot power this - it lacks ${i.join(", ")}. Change the project's agent, or use one that can.`}:{adapter:s,bin:je(n,s.id)}}function jt(n,e){return n.replace(/\{\{(\w+)\}\}/g,(t,r)=>r in e?e[r]:t)}var _c=R(we(),1);nt();Wn();pt();var Ie=R(require("node:fs"),1),Br=R(require("node:path"),1);var dg=k.object({runId:k.string(),issueKey:k.string(),repoName:k.string(),owner:k.string(),repo:k.string(),prNumber:k.number().int(),prUrl:k.string(),branch:k.string(),headSha:k.string(),doneLabel:k.string(),failedLabel:k.string(),jiraTransition:k.string().optional(),mergeOnApprove:k.boolean().default(!1),mergeMethod:k.enum(["squash","merge","rebase"]).default("squash"),autoMerge:k.boolean().default(!1),nextDecisionSeq:k.number().int().default(1e5),changesRequestedNotified:k.boolean().optional(),conflictNotified:k.boolean().optional(),agentConfigDir:k.string().optional()}),hg=k.record(dg),fg=k.object({runId:k.string(),issueKey:k.string(),issueSummary:k.string().default(""),projectId:k.string(),repoName:k.string(),environmentName:k.string(),requestedBy:k.string().default(""),createdAt:k.string()}),pg=k.record(fg),mg=k.object({runId:k.string(),issueKey:k.string(),kind:k.enum(["plan","implement"]),repoPath:k.string(),sessionId:k.string(),doneLabel:k.string(),failedLabel:k.string(),timeoutSeconds:k.number(),createdAt:k.string(),questionsPostedAt:k.string(),rounds:k.number().int().default(1),nextLogSeq:k.number().int().nonnegative().default(0),baseRepoPath:k.string().optional(),repoName:k.string().optional(),branch:k.string().optional(),baseBranch:k.string().optional(),jiraTransition:k.string().optional(),jiraTransitionOnMerge:k.string().optional(),requireApproval:k.boolean().optional(),maxTurns:k.number().int().optional(),runTests:k.boolean().default(!0),mergeOnApprove:k.boolean().default(!1),mergeMethod:k.enum(["squash","merge","rebase"]).default("squash"),autoMerge:k.boolean().default(!1),issueSummary:k.string().default(""),claudeConfigDir:k.string().optional(),agent:k.string().optional(),model:k.string().optional(),actorEmail:k.string().optional()}),gg=k.object({runId:k.string(),issueKey:k.string(),issueSummary:k.string().default(""),repoName:k.string(),baseRepoPath:k.string(),branch:k.string(),baseBranch:k.string(),headSha:k.string(),requireApproval:k.boolean(),mergeOnApprove:k.boolean().default(!1),mergeMethod:k.enum(["squash","merge","rebase"]).default("squash"),autoMerge:k.boolean().default(!1),doneLabel:k.string(),failedLabel:k.string(),jiraTransition:k.string().optional(),jiraTransitionOnMerge:k.string().optional(),actorEmail:k.string().optional(),resultSummary:k.string().default(""),prSummary:k.string().default(""),costUsd:k.number().default(0),nextLogSeq:k.number().int().default(1e5),createdAt:k.string()}),yg=k.record(gg),vg=k.object({runId:k.string(),issueKey:k.string(),repoName:k.string(),owner:k.string(),repo:k.string(),prNumber:k.number().int(),prUrl:k.string(),jiraTransitionOnMerge:k.string().default(""),createdAt:k.string()}),bg=k.record(vg),wg=k.record(mg);function fc(){return Br.default.join(re(),"pending-runs.json")}function ua(){return Br.default.join(re(),"pending-deploys.json")}function ca(){return Br.default.join(re(),"pending-inputs.json")}function da(){return Br.default.join(re(),"merge-watch.json")}function ha(){return Br.default.join(re(),"pending-pushes.json")}function fa(){let n=ha();if(!Ie.default.existsSync(n))return{};try{return yg.parse(JSON.parse(Ie.default.readFileSync(n,"utf8")))}catch{return{}}}function _i(n){let e=fa();e[n.runId]=n,Ot(ha(),e)}function ki(n){return fa()[n]??null}function pa(n){let e=fa();n in e&&(delete e[n],Ot(ha(),e))}function Si(){let n=da();if(!Ie.default.existsSync(n))return{};try{return bg.parse(JSON.parse(Ie.default.readFileSync(n,"utf8")))}catch{return{}}}function pc(n){let e=Si();e[n.runId]=n,Ot(da(),e)}function bs(n){let e=Si();n in e&&(delete e[n],Ot(da(),e))}function ws(){let n=fc();if(!Ie.default.existsSync(n))return{};try{return hg.parse(JSON.parse(Ie.default.readFileSync(n,"utf8")))}catch{return{}}}function Ot(n,e){Ie.default.mkdirSync(re(),{recursive:!0,mode:448});let t=n+".tmp";Ie.default.writeFileSync(t,JSON.stringify(e,null,2)+`
544
- `,{mode:384}),Ie.default.renameSync(t,n),Ie.default.chmodSync(n,384)}function mc(n){Ot(fc(),n)}function rt(n){let e=ws();e[n.runId]=n,mc(e)}function Kr(n){return ws()[n]??null}function er(n){let e=ws();n in e&&(delete e[n],mc(e))}function ma(){let n=ua();if(!Ie.default.existsSync(n))return{};try{return pg.parse(JSON.parse(Ie.default.readFileSync(n,"utf8")))}catch{return{}}}function gc(n){let e=ma();e[n.runId]=n,Ot(ua(),e)}function Ti(n){return ma()[n]??null}function xi(n){let e=ma();n in e&&(delete e[n],Ot(ua(),e))}function Zr(){let n=ca();if(!Ie.default.existsSync(n))return{};try{return wg.parse(JSON.parse(Ie.default.readFileSync(n,"utf8")))}catch{return{}}}function yc(n){let e=Zr();e[n.runId]=n,Ot(ca(),e)}function yt(n){let e=Zr();n in e&&(delete e[n],Ot(ca(),e))}var _g=`
555
+ `))}let o=n.model||n.agent.adapter.deepModel,l=await n.agent.adapter.run({repoPath:n.repoPath,prompt:Ku(n.role,e,t,{scopeNote:r,testResults:s}),timeoutSeconds:480,bin:n.agent.bin,mode:"read_only",maxTurns:120,sessionId:(0,fa.randomUUID)(),model:o,onLog:(p,b)=>{p==="agent"&&y.info(`[audit:${n.role}] ${b.slice(0,160)}`)}}),u=Zu(l.resultText);if("error"in u)return{ok:!1,error:u.error};let c=Gu(n.repoPath,u.findings);for(let p of c.droppedFindings)y.warn(`[audit:${n.role}] dropped "${p.title}" - cited files do not exist: `+p.files.join(", "));let f={id:(0,fa.randomUUID)(),role:n.role,createdAt:new Date().toISOString(),model:l.model||o,summary:u.summary,packNames:e.map(p=>p.name),findings:c.findings,costUsd:l.costUsd??0,ticketed:{},verdicts:{},lessonsWritten:[],scope:n.scope,...i?{testRun:i}:{}};return Ju(n.projectId,f),y.info(`Audit (${n.role}${n.scope.kind!=="repo"?` \xB7 ${n.scope.kind}:${n.scope.ref}`:""}) done: ${c.findings.length} finding(s)`+(u.dropped?`, ${u.dropped} malformed`:"")+(c.droppedFindings.length?`, ${c.droppedFindings.length} dropped for citing files that do not exist`:"")+(c.correctedLines?`, ${c.correctedLines} bad line number(s) stripped`:"")),{ok:!0,audit:f}}var cr=R(we(),1);var xa=R(require("node:fs"),1),Ai=R(require("node:path"),1),$i=require("node:crypto"),Le=R(we(),1);var tr=R(we(),1);var pa=R(require("node:fs"),1),mc=R(require("node:os"),1),Si=R(require("node:path"),1),gc=require("node:child_process"),yc=R(require("node:readline"),1),vc=R(we(),1),yg=4e3,vg={read_only:["Read(./**)","Glob(./**)","Grep(./**)"],edit_no_shell:["Read(./**)","Glob(./**)","Grep(./**)","Edit(./**)","Write(./**)"]};function bg(n){if(process.env.ANTHROPIC_API_KEY)return"API key";let e=n??Si.default.join(mc.default.homedir(),".claude");try{if(pa.default.existsSync(Si.default.join(e,".credentials.json"))||pa.default.existsSync(Si.default.join(e,"credentials.json")))return"subscription"}catch{}return"unknown"}async function wg(n){let e=["-p","--output-format","stream-json","--verbose","--allowedTools",vg[n.mode].join(","),"--max-turns",String(n.maxTurns??60),...n.model?["--model",n.model]:[],...n.resume?["--resume",n.sessionId]:["--session-id",n.sessionId]],t=bg(n.configDir);return t!=="unknown"&&n.onLog("info",t==="subscription"?"Billing: Claude subscription - costs shown are notional list prices, not money charged":"Billing: Anthropic API key - costs shown are actual metered spend"),new Promise(r=>{let s=(0,gc.spawn)(n.bin,e,{cwd:n.repoPath,env:n.configDir?{...process.env,CLAUDE_CONFIG_DIR:n.configDir}:process.env,stdio:["pipe","pipe","pipe"]}),i={ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,billingMode:t==="subscription"?"subscription":t==="API key"?"api":"unknown"},o=0,l=0,u=0,c=0,f=0,p=()=>{if(!n.onUsage)return;let B=Date.now();B-f<yg||(f=B,n.onUsage({inputTokens:l,outputTokens:u,cacheReadTokens:c,turns:o}))},b=!1,w=()=>{b||(b=!0,clearTimeout(C),n.signal?.removeEventListener("abort",T),r(i))},T=()=>{i.cancelled=!0,i.error="stopped from the dashboard",n.onLog("error",i.error),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),3e3).unref()};n.signal?.addEventListener("abort",T,{once:!0});let C=setTimeout(()=>{i.timedOut=!0,i.error=`run exceeded ${n.timeoutSeconds}s wall-clock limit`,n.onLog("error",i.error),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),5e3).unref()},n.timeoutSeconds*1e3);s.stdin.write(n.prompt),s.stdin.end(),yc.default.createInterface({input:s.stdout}).on("line",B=>{if(!B.trim())return;let N;try{N=JSON.parse(B)}catch{n.onLog("agent",B.slice(0,1e3));return}if(N.type==="system"&&N.subtype==="init")i.model=typeof N.model=="string"?N.model:void 0,n.onLog("info",`Claude Code session started (model: ${N.model??"default"})`);else if(N.type==="assistant"){o+=1;let D=N.message?.usage;D&&(l+=Number(D.input_tokens??0)+Number(D.cache_creation_input_tokens??0),u+=Number(D.output_tokens??0),c+=Number(D.cache_read_input_tokens??0),p());for(let K of N.message?.content??[])if(K.type==="text"&&K.text?.trim())n.onLog("agent",K.text.trim().slice(0,4e3));else if(K.type==="tool_use"){let h=K.input??{},m=["file_path","path","pattern","command","description","url"].map(x=>typeof h[x]=="string"?`${x}=${h[x]}`:null).filter(Boolean).join(" "),g=JSON.stringify(h).slice(0,400);n.onLog("info",`tool ${K.name} ${m?`${m} `:""}${g}`)}}else N.type==="result"&&(i.costUsd=Number(N.total_cost_usd??0),i.inputTokens=Number(N.usage?.input_tokens??0)+Number(N.usage?.cache_creation_input_tokens??0),i.outputTokens=Number(N.usage?.output_tokens??0),l=Math.max(i.inputTokens,l),u=Math.max(i.outputTokens,u),i.inputTokens=l,i.outputTokens=u,c=Number(N.usage?.cache_read_input_tokens??c),i.cacheReadTokens=c,n.onUsage&&(n.onUsage({inputTokens:l,outputTokens:u,cacheReadTokens:c,costUsd:i.costUsd,turns:o}),f=Date.now()),N.subtype==="success"&&!N.is_error?(i.ok=!0,i.resultText=String(N.result??"")):N.subtype==="error_max_turns"?(i.turnLimitHit=!0,i.error=`hit the ${n.maxTurns??60}-turn limit before finishing`):(i.error=String(N.result??N.subtype??"unknown Claude Code error"),/rate.?limit|usage limit|limit (reached|exceeded)|overloaded/i.test(i.error)&&(i.error=`Claude usage limit hit for this account - the run will work again once the limit window resets. Original error: ${i.error.slice(0,400)}`)))});let v="";s.stderr.on("data",B=>{v=(v+B.toString()).slice(-2e3)}),s.on("error",B=>{i.error=`failed to start ${n.bin}: ${B.message}`,n.onLog("error",i.error),w()}),s.on("close",B=>{!i.ok&&!i.error&&(i.error=i.timedOut?i.error:`claude exited with code ${B}${v?`: ${v.slice(-500)}`:""}`),w()})})}var Ti={id:"claude-code",displayName:"Claude Code",fastModel:"claude-sonnet-5",deepModel:"claude-fable-5",capabilities:vc.REGISTERED_AGENTS.find(n=>n.id==="claude-code").capabilities,run:wg};var bc=require("node:child_process"),wc=R(require("node:readline"),1),_c=R(we(),1);async function _g(n){if(n.mode!=="read_only")return{ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,error:"the codex adapter only supports read-only runs - its write sandbox cannot exclude shell, and Allwright never weakens a guarantee silently"};if(n.resume)return{ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,error:"the codex adapter cannot resume sessions"};let e=["exec","--json","--sandbox","read-only","--skip-git-repo-check","--cd",n.repoPath,...n.model?["--model",n.model]:[],"-"];return new Promise(t=>{let r=(0,bc.spawn)(n.bin,e,{cwd:n.repoPath,env:process.env,stdio:["pipe","pipe","pipe"]}),s={ok:!1,timedOut:!1,resultText:"",costUsd:0,inputTokens:0,outputTokens:0,cacheReadTokens:0},i="",o=!1,l=()=>{o||(o=!0,clearTimeout(u),t(s))},u=setTimeout(()=>{s.timedOut=!0,s.error=`run exceeded ${n.timeoutSeconds}s wall-clock limit`,n.onLog("error",s.error),r.kill("SIGTERM"),setTimeout(()=>r.kill("SIGKILL"),5e3).unref()},n.timeoutSeconds*1e3);r.stdin.write(n.prompt),r.stdin.end(),wc.default.createInterface({input:r.stdout}).on("line",p=>{if(!p.trim())return;let b;try{b=JSON.parse(p)}catch{n.onLog("agent",p.slice(0,1e3));return}let w=b.item??b.msg??b,T=w?.type??b.type,C=w?.text??w?.message??"";T==="agent_message"&&typeof C=="string"&&C.trim()?(i=C,n.onLog("agent",C.trim().slice(0,4e3))):T==="command_execution"||T==="exec_command_begin"?n.onLog("info",`tool ${String(w?.command??"").slice(0,300)}`):T==="error"&&typeof C=="string"&&C&&n.onLog("error",C.slice(0,1e3))});let f="";r.stderr.on("data",p=>{f=(f+p.toString()).slice(-2e3)}),r.on("error",p=>{s.error=`failed to start ${n.bin}: ${p.message} - is the Codex CLI installed and logged in?`,n.onLog("error",s.error),l()}),r.on("close",p=>{p===0&&i.trim()?(s.ok=!0,s.resultText=i):s.error||(s.error=`codex exited with code ${p}`+(i?"":" and produced no answer")+(f?`: ${f.slice(-500)}`:"")),l()})})}var ma={id:"codex",fastModel:"",deepModel:"",displayName:"OpenAI Codex CLI (experimental)",capabilities:_c.REGISTERED_AGENTS.find(n=>n.id==="codex").capabilities,run:_g};var kg={[Ti.id]:Ti,[ma.id]:ma};function De(n){return kg[n||tr.DEFAULT_AGENT_ID]??null}function Oe(n,e){return!e||e===Ti.id?n.claudeBin:n.agents[e]?.bin??e}function ln(n,e){let t=De(n);if(!t)return`no agent adapter named "${n}" on this runner - update the runner, or set the rule's agent to "${tr.DEFAULT_AGENT_ID}"`;let r=(0,tr.missingAgentCapabilities)(t.id,e);return r&&r.length?`agent "${t.displayName}" cannot run ${e} rules: it cannot guarantee ${r.join(", ")}. Allwright refuses rather than weakening the isolation silently.`:null}function st(n,e,t){let r=e.defaultAgent||tr.DEFAULT_AGENT_ID,s=De(r);if(!s)return{error:`this project's default agent "${r}" is not on this runner - update the runner, or change the project's agent`};let i=(0,tr.missingAgentCapabilities)(s.id,t);return i&&i.length?{error:`this project's default agent "${s.displayName}" cannot power this - it lacks ${i.join(", ")}. Change the project's agent, or use one that can.`}:{adapter:s,bin:Oe(n,s.id)}}function zt(n,e){return n.replace(/\{\{(\w+)\}\}/g,(t,r)=>r in e?e[r]:t)}var $c=R(we(),1);it();Xn();gt();var Re=R(require("node:fs"),1),Hr=R(require("node:path"),1);var Tg=k.object({runId:k.string(),issueKey:k.string(),repoName:k.string(),owner:k.string(),repo:k.string(),prNumber:k.number().int(),prUrl:k.string(),branch:k.string(),headSha:k.string(),doneLabel:k.string(),failedLabel:k.string(),jiraTransition:k.string().optional(),mergeOnApprove:k.boolean().default(!1),mergeMethod:k.enum(["squash","merge","rebase"]).default("squash"),autoMerge:k.boolean().default(!1),nextDecisionSeq:k.number().int().default(1e5),changesRequestedNotified:k.boolean().optional(),conflictNotified:k.boolean().optional(),agentConfigDir:k.string().optional()}),xg=k.record(Tg),Cg=k.object({runId:k.string(),issueKey:k.string(),issueSummary:k.string().default(""),projectId:k.string(),repoName:k.string(),environmentName:k.string(),requestedBy:k.string().default(""),createdAt:k.string()}),Ig=k.record(Cg),Rg=k.object({runId:k.string(),issueKey:k.string(),kind:k.enum(["plan","implement"]),repoPath:k.string(),sessionId:k.string(),doneLabel:k.string(),failedLabel:k.string(),timeoutSeconds:k.number(),createdAt:k.string(),questionsPostedAt:k.string(),rounds:k.number().int().default(1),nextLogSeq:k.number().int().nonnegative().default(0),baseRepoPath:k.string().optional(),repoName:k.string().optional(),branch:k.string().optional(),baseBranch:k.string().optional(),jiraTransition:k.string().optional(),jiraTransitionOnMerge:k.string().optional(),requireApproval:k.boolean().optional(),maxTurns:k.number().int().optional(),runTests:k.boolean().default(!0),mergeOnApprove:k.boolean().default(!1),mergeMethod:k.enum(["squash","merge","rebase"]).default("squash"),autoMerge:k.boolean().default(!1),issueSummary:k.string().default(""),claudeConfigDir:k.string().optional(),agent:k.string().optional(),model:k.string().optional(),actorEmail:k.string().optional()}),Eg=k.object({runId:k.string(),issueKey:k.string(),issueSummary:k.string().default(""),repoName:k.string(),baseRepoPath:k.string(),branch:k.string(),baseBranch:k.string(),headSha:k.string(),requireApproval:k.boolean(),mergeOnApprove:k.boolean().default(!1),mergeMethod:k.enum(["squash","merge","rebase"]).default("squash"),autoMerge:k.boolean().default(!1),doneLabel:k.string(),failedLabel:k.string(),jiraTransition:k.string().optional(),jiraTransitionOnMerge:k.string().optional(),actorEmail:k.string().optional(),resultSummary:k.string().default(""),prSummary:k.string().default(""),costUsd:k.number().default(0),nextLogSeq:k.number().int().default(1e5),createdAt:k.string()}),Ag=k.record(Eg),$g=k.object({runId:k.string(),issueKey:k.string(),repoName:k.string(),owner:k.string(),repo:k.string(),prNumber:k.number().int(),prUrl:k.string(),jiraTransitionOnMerge:k.string().default(""),createdAt:k.string()}),Pg=k.record($g),jg=k.record(Rg);function kc(){return Hr.default.join(se(),"pending-runs.json")}function ga(){return Hr.default.join(se(),"pending-deploys.json")}function ya(){return Hr.default.join(se(),"pending-inputs.json")}function va(){return Hr.default.join(se(),"merge-watch.json")}function ba(){return Hr.default.join(se(),"pending-pushes.json")}function wa(){let n=ba();if(!Re.default.existsSync(n))return{};try{return Ag.parse(JSON.parse(Re.default.readFileSync(n,"utf8")))}catch{return{}}}function xi(n){let e=wa();e[n.runId]=n,Dt(ba(),e)}function Ci(n){return wa()[n]??null}function _a(n){let e=wa();n in e&&(delete e[n],Dt(ba(),e))}function Ii(){let n=va();if(!Re.default.existsSync(n))return{};try{return Pg.parse(JSON.parse(Re.default.readFileSync(n,"utf8")))}catch{return{}}}function Sc(n){let e=Ii();e[n.runId]=n,Dt(va(),e)}function xs(n){let e=Ii();n in e&&(delete e[n],Dt(va(),e))}function Cs(){let n=kc();if(!Re.default.existsSync(n))return{};try{return xg.parse(JSON.parse(Re.default.readFileSync(n,"utf8")))}catch{return{}}}function Dt(n,e){Re.default.mkdirSync(se(),{recursive:!0,mode:448});let t=n+".tmp";Re.default.writeFileSync(t,JSON.stringify(e,null,2)+`
556
+ `,{mode:384}),Re.default.renameSync(t,n),Re.default.chmodSync(n,384)}function Tc(n){Dt(kc(),n)}function ot(n){let e=Cs();e[n.runId]=n,Tc(e)}function Vr(n){return Cs()[n]??null}function rr(n){let e=Cs();n in e&&(delete e[n],Tc(e))}function ka(){let n=ga();if(!Re.default.existsSync(n))return{};try{return Ig.parse(JSON.parse(Re.default.readFileSync(n,"utf8")))}catch{return{}}}function xc(n){let e=ka();e[n.runId]=n,Dt(ga(),e)}function Ri(n){return ka()[n]??null}function Ei(n){let e=ka();n in e&&(delete e[n],Dt(ga(),e))}function Wr(){let n=ya();if(!Re.default.existsSync(n))return{};try{return jg.parse(JSON.parse(Re.default.readFileSync(n,"utf8")))}catch{return{}}}function Cc(n){let e=Wr();e[n.runId]=n,Dt(ya(),e)}function bt(n){let e=Wr();n in e&&(delete e[n],Dt(ya(),e))}var Og=`
557
+
558
+ NEVER create or modify CI/workflow files (.github/workflows/, .githooks/ or similar CI config) - the runner refuses to push them, and the refusal costs the whole run. When the ticket needs something enforced on every change, use a path that is yours to edit instead: add the check as a command in TEST.md (this runner executes TEST.md commands after every implement run and posts the results into the PR), wire it into a script CI already runs (package.json test/build scripts, the test suite itself), or - only if it truly must be a workflow file - put the exact proposed YAML in your summary for a human to apply by hand.`,Ng=`
545
559
 
546
- NEVER create or modify CI/workflow files (.github/workflows/, .githooks/ or similar CI config) - the runner refuses to push them, and the refusal costs the whole run. When the ticket needs something enforced on every change, use a path that is yours to edit instead: add the check as a command in TEST.md (this runner executes TEST.md commands after every implement run and posts the results into the PR), wire it into a script CI already runs (package.json test/build scripts, the test suite itself), or - only if it truly must be a workflow file - put the exact proposed YAML in your summary for a human to apply by hand.`,kg=`
560
+ After your "## Summary of changes" section, end with one more section headed exactly "## PR summary": 4-8 short sentences in plain language for the person reviewing the pull request. Say what was built and what a user can now do, name anything you did NOT do or assumed, and anything that genuinely needs a human decision. No file paths, no function names, no jargon unless the point cannot be made without it. Complete but short.`,Mg=`
547
561
 
548
- After your "## Summary of changes" section, end with one more section headed exactly "## PR summary": 4-8 short sentences in plain language for the person reviewing the pull request. Say what was built and what a user can now do, name anything you did NOT do or assumed, and anything that genuinely needs a human decision. No file paths, no function names, no jargon unless the point cannot be made without it. Complete but short.`;function Sg(n){let e=n.map(t=>`$ ${t.command} (exit ${t.exitCode})
562
+ This project keeps a living go-live checklist and manual test cases on a Jira issue. If (and only if) this ticket changes what must be checked before going live, or adds user-visible behavior a human should test by hand, end with one more section headed exactly "## Go-live draft": checklist additions/changes as short imperative bullets, then manual test cases as numbered steps a non-developer can follow. Under 1500 characters total. If nothing about going live changes, OMIT the section entirely - an empty ritual entry is noise.`;function Ic(n){let e=/##\s*Go-live draft\s*\n([\s\S]*?)(?=\n##\s|$)/i.exec(n),t=e?e[1].trim():"";return t?t.slice(0,3500):null}function zg(n){let e=n.map(t=>`$ ${t.command} (exit ${t.exitCode})
549
563
  ${t.tail.slice(-2e3)}`).join(`
550
564
 
551
565
  `);return`After you finished, the runner executed this repository's documented TEST.md commands (you cannot run them yourself - you have no shell). ${n.length} failed:
@@ -557,7 +571,7 @@ Fix what these failures point at, with the smallest change that makes them pass.
557
571
  - If a failure is clearly pre-existing on the base branch and unrelated to your change, leave the code alone and say so in one sentence.
558
572
  - Do not ask questions; if you cannot fix something safely, say what you found and stop.
559
573
  - The runner re-runs every documented command after you finish, so a fix that breaks a previously passing command will be caught.
560
- End with one short paragraph stating exactly what you changed, or why you changed nothing. Then repeat your "## PR summary" section, updated if your fix changed what a reviewer sees.`}function Tg(n){try{let{packs:e,lessons:t}=vi("implement",n),r="",s=e.map(o=>`### ${o.name}
574
+ End with one short paragraph stating exactly what you changed, or why you changed nothing. Then repeat your "## PR summary" section, updated if your fix changed what a reviewer sees.`}function Dg(n){try{let{packs:e,lessons:t}=ki("implement",n),r="",s=e.map(o=>`### ${o.name}
561
575
  ${o.content}`).join(`
562
576
 
563
577
  `).trim();s&&(r+=`
@@ -567,170 +581,173 @@ This repository has working rules taught to Allwright - follow them:
567
581
  \u2026${i.slice(-6e3)}`:i;r+=`
568
582
 
569
583
  Lessons from earlier runs on this repository (human-confirmed - follow them BEFORE writing code, they exist because a run got this wrong once):
570
- `+o}return r}catch{return""}}function ba(n){return va.default.existsSync(Ci.default.join(n,"DESIGN.md"))?`
584
+ `+o}return r}catch{return""}}function Ca(n){return xa.default.existsSync(Ai.default.join(n,"DESIGN.md"))?`
571
585
 
572
- This repository has a DESIGN.md at its root: read it before doing any user-facing work (UI, copy, styling) and follow it. Where the ticket and DESIGN.md conflict, say so instead of silently picking one.`:""}var kc=5,vc=2,xg=8,bc=2,Cg="You stopped because the session hit its turn limit - nothing failed. Continue exactly where you left off. Do not re-read files you already know or redo completed work; be economical with tool calls and finish the remaining work. Then end with your final summary exactly as the original instructions asked.";async function _s(n,e,t,r){let s=Date.now(),i="";r&&(i=await r().catch(()=>""));let o=await n.run(e),l=0,u="",c=r?xg:vc;for(;!o.ok&&o.turnLimitHit&&!o.cancelled&&n.capabilities.sessionResume;){if(l>=c){u=`resume cap (${c}) reached`;break}if(r&&l>=vc){let p=await r().catch(()=>""),b=p!==""&&p!==i;if(i=p,!b){u="the last resume produced no new work";break}if(Date.now()-s>e.timeoutSeconds*bc*1e3){u=`wall-clock budget (${bc}x the rule's timeout) exhausted`;break}}l++,t("info",`Turn limit hit mid-work - auto-resuming the same session (resume ${l}, cap ${c})`);let f=await n.run({...e,prompt:Cg,resume:!0});f.costUsd+=o.costUsd,f.inputTokens+=o.inputTokens,f.outputTokens+=o.outputTokens,o=f}return!o.ok&&o.turnLimitHit&&n.capabilities.sessionResume&&(o.error=`${o.error??"hit the turn limit"} - even after ${l} automatic same-session resume(s)${u?` (stopped: ${u})`:""}. The ticket is probably too large for one run: raise the rule's max turns, or split the ticket.`),o}var ya=new Map;function Sc(n){let e=ya.get(n);return e?(e.abort(),!0):!1}async function Hr(n,e,t,r,s){let i=new AbortController;ya.set(n,i);try{return await _s(e,{...t,signal:i.signal},r,s)}finally{ya.delete(n)}}function tr(n,e,t=0){let r=t;return{emit:(l,u)=>{e.send({type:"run.log",runId:n,seq:r++,ts:new Date().toISOString(),level:l,message:u}),l!=="agent"&&y.info(`[run ${n}] ${u}`)},setStatus:(l,u={})=>{e.send({type:"run.status",runId:n,status:l,...u})},sendUsage:l=>{e.send({type:"run.usage",runId:n,inputTokens:Math.round(l.inputTokens),outputTokens:Math.round(l.outputTokens),cacheReadTokens:l.cacheReadTokens===void 0?void 0:Math.round(l.cacheReadTokens),costUsd:l.costUsd,turns:l.turns})},nextSeq:()=>r}}async function Ri(n){return n.rule.action.type==="implement"?Eg(n):n.rule.action.type==="respond"?Rg(n):Ig(n)}async function Ig(n){let{emit:e,setStatus:t,sendUsage:r,nextSeq:s}=tr(n.runId,n.transport),{trigger:i}=n.rule,o=n.rule.action;if(o.type!=="plan_only")return;let l=on(o.agent,o.type);if(l){e("error",l),await Gr(n,l),t("failed",{error:l});return}let u=(0,Ii.randomUUID)();try{t("running"),e("info",`Run started for ${n.issueKey} (rule "${n.rule.name}", plan-only)`),e("info",`Fetching ${n.issueKey} from Jira`);let c=await n.jira.getIssue(n.issueKey),f=jt(o.promptTemplate,{issueKey:c.key,summary:c.summary,description:c.description||"(no description)",comments:Ss(c.comments)})+await Ir(n.jira,c.attachments,n.repoPath,e)+ba(n.repoPath);e("info",`Starting Claude Code in ${n.repoPath} - read-only tools, path-jailed to the repo, timeout ${o.timeoutSeconds}s`);let p=await Hr(n.runId,Me(o.agent),{repoPath:n.repoPath,prompt:f,timeoutSeconds:o.timeoutSeconds,bin:je(n.cfg,o.agent),configDir:n.claudeConfigDir,mode:"read_only",model:o.model||void 0,sessionId:u,onLog:(T,x)=>e(T,x),onUsage:r},e),b={costUsd:p.costUsd,inputTokens:p.inputTokens,outputTokens:p.outputTokens,billingMode:p.billingMode,model:p.model};if(!p.ok||!p.resultText.trim()){let T=p.error??"Claude Code produced no output";e("error",`Run failed: ${T}`),await Gr(n,T),t(p.timedOut?"timed_out":"failed",{error:T,...p.cancelled?{errorKind:"guard"}:{},...b});return}let w=Ts(p.resultText);if(w){await Ei({kind:"plan",runId:n.runId,issueKey:n.issueKey,repoPath:n.repoPath,sessionId:u,doneLabel:i.doneLabel,failedLabel:i.failedLabel,timeoutSeconds:o.timeoutSeconds,jira:n.jira,nextLogSeq:s(),rounds:1,claudeConfigDir:n.claudeConfigDir,agent:o.agent,model:o.model},w,e,t,b);return}await xc({runId:n.runId,issueKey:n.issueKey,doneLabel:i.doneLabel,jira:n.jira,resultText:p.resultText,costFields:b,emit:e,setStatus:t})}catch(c){let f=c instanceof Error?c.message:String(c);e("error",`Run failed: ${f}`),await Gr(n,f),t("failed",{error:f})}finally{Vt(n.repoPath)}}async function Tc(n,e,t,r){let{emit:s,setStatus:i,sendUsage:o,nextSeq:l}=tr(n.runId,r.transport,n.nextLogSeq);try{i("running"),s("info",`Reply received on ${n.issueKey} - continuing run \`${n.runId}\``);let u=Mc(e)+await Ir(r.jiraFor(n.repoName??""),t,n.repoPath,s),c=await Hr(n.runId,Me(n.agent),{repoPath:n.repoPath,prompt:u,timeoutSeconds:n.timeoutSeconds,bin:je(r.cfg,n.agent??""),configDir:n.claudeConfigDir,mode:"read_only",model:n.model||void 0,sessionId:n.sessionId,resume:!0,onLog:(b,w)=>s(b,w),onUsage:o},s),f={costUsd:c.costUsd,inputTokens:c.inputTokens,outputTokens:c.outputTokens,billingMode:c.billingMode,model:c.model};if(!c.ok||!c.resultText.trim()){let b=c.error??"Claude Code produced no output";s("error",`Run failed: ${b}`),await vt(r.jiraFor(n.repoName??""),n.issueKey,n.runId,n.failedLabel,b),yt(n.runId),i(c.timedOut?"timed_out":"failed",{error:b,...c.cancelled?{errorKind:"guard"}:{},...f});return}let p=Ts(c.resultText);if(p){if(n.rounds>=kc){await zc(r.jiraFor(n.repoName??""),n,s,i,f);return}await Ei({kind:"plan",runId:n.runId,issueKey:n.issueKey,repoPath:n.repoPath,sessionId:n.sessionId,doneLabel:n.doneLabel,failedLabel:n.failedLabel,timeoutSeconds:n.timeoutSeconds,jira:r.jiraFor(n.repoName??""),nextLogSeq:l(),rounds:n.rounds+1,createdAt:n.createdAt,claudeConfigDir:n.claudeConfigDir,actorEmail:n.actorEmail,agent:n.agent,model:n.model},p,s,i,f);return}await xc({runId:n.runId,issueKey:n.issueKey,doneLabel:n.doneLabel,jira:r.jiraFor(n.repoName??""),resultText:c.resultText,costFields:f,emit:s,setStatus:i}),yt(n.runId)}catch(u){let c=u instanceof Error?u.message:String(u);s("error",`Run failed: ${c}`),await vt(r.jiraFor(n.repoName??""),n.issueKey,n.runId,n.failedLabel,c),yt(n.runId),i("failed",{error:c})}finally{Vt(n.repoPath)}}async function xc(n){let{runId:e,issueKey:t,doneLabel:r,jira:s,resultText:i,costFields:o,emit:l,setStatus:u}=n;u("posting",o),l("info",`Posting plan to ${t} (${i.length} chars)`);let c=`
586
+ This repository has a DESIGN.md at its root: read it before doing any user-facing work (UI, copy, styling) and follow it. Where the ticket and DESIGN.md conflict, say so instead of silently picking one.`:""}var Pc=5,Rc=2,Lg=8,Ec=2,Ug="You stopped because the session hit its turn limit - nothing failed. Continue exactly where you left off. Do not re-read files you already know or redo completed work; be economical with tool calls and finish the remaining work. Then end with your final summary exactly as the original instructions asked.";async function Is(n,e,t,r){let s=Date.now(),i="";r&&(i=await r().catch(()=>""));let o=await n.run(e),l=0,u="",c=r?Lg:Rc;for(;!o.ok&&o.turnLimitHit&&!o.cancelled&&n.capabilities.sessionResume;){if(l>=c){u=`resume cap (${c}) reached`;break}if(r&&l>=Rc){let p=await r().catch(()=>""),b=p!==""&&p!==i;if(i=p,!b){u="the last resume produced no new work";break}if(Date.now()-s>e.timeoutSeconds*Ec*1e3){u=`wall-clock budget (${Ec}x the rule's timeout) exhausted`;break}}l++,t("info",`Turn limit hit mid-work - auto-resuming the same session (resume ${l}, cap ${c})`);let f=await n.run({...e,prompt:Ug,resume:!0});f.costUsd+=o.costUsd,f.inputTokens+=o.inputTokens,f.outputTokens+=o.outputTokens,o=f}return!o.ok&&o.turnLimitHit&&n.capabilities.sessionResume&&(o.error=`${o.error??"hit the turn limit"} - even after ${l} automatic same-session resume(s)${u?` (stopped: ${u})`:""}. The ticket is probably too large for one run: raise the rule's max turns, or split the ticket.`),o}var Ta=new Map;function jc(n){let e=Ta.get(n);return e?(e.abort(),!0):!1}async function Yr(n,e,t,r,s){let i=new AbortController;Ta.set(n,i);try{return await Is(e,{...t,signal:i.signal},r,s)}finally{Ta.delete(n)}}function sr(n,e,t=0){let r=t;return{emit:(l,u)=>{e.send({type:"run.log",runId:n,seq:r++,ts:new Date().toISOString(),level:l,message:u}),l!=="agent"&&y.info(`[run ${n}] ${u}`)},setStatus:(l,u={})=>{e.send({type:"run.status",runId:n,status:l,...u})},sendUsage:l=>{e.send({type:"run.usage",runId:n,inputTokens:Math.round(l.inputTokens),outputTokens:Math.round(l.outputTokens),cacheReadTokens:l.cacheReadTokens===void 0?void 0:Math.round(l.cacheReadTokens),costUsd:l.costUsd,turns:l.turns})},nextSeq:()=>r}}async function Pi(n){return n.rule.action.type==="implement"?Bg(n):n.rule.action.type==="respond"?Fg(n):qg(n)}async function qg(n){let{emit:e,setStatus:t,sendUsage:r,nextSeq:s}=sr(n.runId,n.transport),{trigger:i}=n.rule,o=n.rule.action;if(o.type!=="plan_only")return;let l=ln(o.agent,o.type);if(l){e("error",l),await Jr(n,l),t("failed",{error:l});return}let u=(0,$i.randomUUID)();try{t("running"),e("info",`Run started for ${n.issueKey} (rule "${n.rule.name}", plan-only)`),e("info",`Fetching ${n.issueKey} from Jira`);let c=await n.jira.getIssue(n.issueKey),f=zt(o.promptTemplate,{issueKey:c.key,summary:c.summary,description:c.description||"(no description)",comments:Es(c.comments)})+await $r(n.jira,c.attachments,n.repoPath,e)+Ca(n.repoPath);e("info",`Starting Claude Code in ${n.repoPath} - read-only tools, path-jailed to the repo, timeout ${o.timeoutSeconds}s`);let p=await Yr(n.runId,De(o.agent),{repoPath:n.repoPath,prompt:f,timeoutSeconds:o.timeoutSeconds,bin:Oe(n.cfg,o.agent),configDir:n.claudeConfigDir,mode:"read_only",model:o.model||void 0,sessionId:u,onLog:(T,C)=>e(T,C),onUsage:r},e),b={costUsd:p.costUsd,inputTokens:p.inputTokens,outputTokens:p.outputTokens,billingMode:p.billingMode,model:p.model};if(!p.ok||!p.resultText.trim()){let T=p.error??"Claude Code produced no output";e("error",`Run failed: ${T}`),await Jr(n,T),t(p.timedOut?"timed_out":"failed",{error:T,...p.cancelled?{errorKind:"guard"}:{},...b});return}let w=As(p.resultText);if(w){await ji({kind:"plan",runId:n.runId,issueKey:n.issueKey,repoPath:n.repoPath,sessionId:u,doneLabel:i.doneLabel,failedLabel:i.failedLabel,timeoutSeconds:o.timeoutSeconds,jira:n.jira,nextLogSeq:s(),rounds:1,claudeConfigDir:n.claudeConfigDir,agent:o.agent,model:o.model},w,e,t,b);return}await Nc({runId:n.runId,issueKey:n.issueKey,doneLabel:i.doneLabel,jira:n.jira,resultText:p.resultText,costFields:b,emit:e,setStatus:t})}catch(c){let f=c instanceof Error?c.message:String(c);e("error",`Run failed: ${f}`),await Jr(n,f),t("failed",{error:f})}finally{Jt(n.repoPath)}}async function Oc(n,e,t,r){let{emit:s,setStatus:i,sendUsage:o,nextSeq:l}=sr(n.runId,r.transport,n.nextLogSeq);try{i("running"),s("info",`Reply received on ${n.issueKey} - continuing run \`${n.runId}\``);let u=Gc(e)+await $r(r.jiraFor(n.repoName??""),t,n.repoPath,s),c=await Yr(n.runId,De(n.agent),{repoPath:n.repoPath,prompt:u,timeoutSeconds:n.timeoutSeconds,bin:Oe(r.cfg,n.agent??""),configDir:n.claudeConfigDir,mode:"read_only",model:n.model||void 0,sessionId:n.sessionId,resume:!0,onLog:(b,w)=>s(b,w),onUsage:o},s),f={costUsd:c.costUsd,inputTokens:c.inputTokens,outputTokens:c.outputTokens,billingMode:c.billingMode,model:c.model};if(!c.ok||!c.resultText.trim()){let b=c.error??"Claude Code produced no output";s("error",`Run failed: ${b}`),await wt(r.jiraFor(n.repoName??""),n.issueKey,n.runId,n.failedLabel,b),bt(n.runId),i(c.timedOut?"timed_out":"failed",{error:b,...c.cancelled?{errorKind:"guard"}:{},...f});return}let p=As(c.resultText);if(p){if(n.rounds>=Pc){await Hc(r.jiraFor(n.repoName??""),n,s,i,f);return}await ji({kind:"plan",runId:n.runId,issueKey:n.issueKey,repoPath:n.repoPath,sessionId:n.sessionId,doneLabel:n.doneLabel,failedLabel:n.failedLabel,timeoutSeconds:n.timeoutSeconds,jira:r.jiraFor(n.repoName??""),nextLogSeq:l(),rounds:n.rounds+1,createdAt:n.createdAt,claudeConfigDir:n.claudeConfigDir,actorEmail:n.actorEmail,agent:n.agent,model:n.model},p,s,i,f);return}await Nc({runId:n.runId,issueKey:n.issueKey,doneLabel:n.doneLabel,jira:r.jiraFor(n.repoName??""),resultText:c.resultText,costFields:f,emit:s,setStatus:i}),bt(n.runId)}catch(u){let c=u instanceof Error?u.message:String(u);s("error",`Run failed: ${c}`),await wt(r.jiraFor(n.repoName??""),n.issueKey,n.runId,n.failedLabel,c),bt(n.runId),i("failed",{error:c})}finally{Jt(n.repoPath)}}async function Nc(n){let{runId:e,issueKey:t,doneLabel:r,jira:s,resultText:i,costFields:o,emit:l,setStatus:u}=n;u("posting",o),l("info",`Posting plan to ${t} (${i.length} chars)`);let c=`
573
587
 
574
588
  ---
575
- _Allwright plan-only run \`${e}\` \xB7 cost $${o.costUsd.toFixed(4)} \xB7 no code was written._`;await s.addComment(t,i+c),await s.editLabels(t,{add:[r],remove:[ze.NEEDS_INPUT_LABEL]}),l("info",`Labeled ${t} with "${r}"`),u("succeeded",{...o,resultSummary:nr(i)}),l("info",`Run succeeded \xB7 $${o.costUsd.toFixed(4)}`)}async function Rg(n){let{emit:e,setStatus:t,sendUsage:r}=tr(n.runId,n.transport),s=n.rule.action;if(s.type!=="respond")return;let i=on(s.agent,s.type);if(i){e("error",i),await n.jira.addComment(n.issueKey,`**Allwright could not answer this question.**
589
+ _Allwright plan-only run \`${e}\` \xB7 cost $${o.costUsd.toFixed(4)} \xB7 no code was written._`;await s.addComment(t,i+c),await s.editLabels(t,{add:[r],remove:[Le.NEEDS_INPUT_LABEL]}),l("info",`Labeled ${t} with "${r}"`),u("succeeded",{...o,resultSummary:ir(i)}),l("info",`Run succeeded \xB7 $${o.costUsd.toFixed(4)}`)}async function Fg(n){let{emit:e,setStatus:t,sendUsage:r}=sr(n.runId,n.transport),s=n.rule.action;if(s.type!=="respond")return;let i=ln(s.agent,s.type);if(i){e("error",i),await n.jira.addComment(n.issueKey,`**Allwright could not answer this question.**
576
590
 
577
- ${i}`).catch(()=>{}),t("failed",{error:i});return}try{t("running"),e("info",`Run started for ${n.issueKey} (rule "${n.rule.name}", respond`+(n.question?`, question from ${n.question.author}`:"")+")"),e("info",`Fetching ${n.issueKey} from Jira`);let o=await n.jira.getIssue(n.issueKey),l=jt(s.promptTemplate,{issueKey:o.key,summary:o.summary,description:o.description||"(no description)",comments:Ss(o.comments),question:n.question?.body??"(see the latest comment on the ticket)",questionAuthor:n.question?.author??"the commenter"})+await Ir(n.jira,o.attachments,n.repoPath,e)+ba(n.repoPath);e("info",`Starting Claude Code in ${n.repoPath} - read-only tools, path-jailed, timeout ${s.timeoutSeconds}s`);let u=await Hr(n.runId,Me(s.agent),{repoPath:n.repoPath,prompt:l,timeoutSeconds:s.timeoutSeconds,bin:je(n.cfg,s.agent),configDir:n.claudeConfigDir,mode:"read_only",model:s.model||void 0,sessionId:(0,Ii.randomUUID)(),onLog:(f,p)=>e(f,p),onUsage:r},e),c={costUsd:u.costUsd,inputTokens:u.inputTokens,outputTokens:u.outputTokens,billingMode:u.billingMode,model:u.model};if(!u.ok||!u.resultText.trim()){let f=u.error??"Claude Code produced no answer";e("error",`Run failed: ${f}`),await n.jira.addComment(n.issueKey,`**Allwright could not answer this question.**
591
+ ${i}`).catch(()=>{}),t("failed",{error:i});return}try{t("running"),e("info",`Run started for ${n.issueKey} (rule "${n.rule.name}", respond`+(n.question?`, question from ${n.question.author}`:"")+")"),e("info",`Fetching ${n.issueKey} from Jira`);let o=await n.jira.getIssue(n.issueKey),l=zt(s.promptTemplate,{issueKey:o.key,summary:o.summary,description:o.description||"(no description)",comments:Es(o.comments),question:n.question?.body??"(see the latest comment on the ticket)",questionAuthor:n.question?.author??"the commenter"})+await $r(n.jira,o.attachments,n.repoPath,e)+Ca(n.repoPath);e("info",`Starting Claude Code in ${n.repoPath} - read-only tools, path-jailed, timeout ${s.timeoutSeconds}s`);let u=await Yr(n.runId,De(s.agent),{repoPath:n.repoPath,prompt:l,timeoutSeconds:s.timeoutSeconds,bin:Oe(n.cfg,s.agent),configDir:n.claudeConfigDir,mode:"read_only",model:s.model||void 0,sessionId:(0,$i.randomUUID)(),onLog:(f,p)=>e(f,p),onUsage:r},e),c={costUsd:u.costUsd,inputTokens:u.inputTokens,outputTokens:u.outputTokens,billingMode:u.billingMode,model:u.model};if(!u.ok||!u.resultText.trim()){let f=u.error??"Claude Code produced no answer";e("error",`Run failed: ${f}`),await n.jira.addComment(n.issueKey,`**Allwright could not answer this question.**
578
592
 
579
593
  Error: ${f.slice(0,800)}
580
594
 
581
- Ask again in a new comment to retry. (run \`${n.runId}\`)`).catch(p=>y.error(`could not post answer failure to ${n.issueKey}: ${p}`)),t(u.timedOut?"timed_out":"failed",{error:f,...u.cancelled?{errorKind:"guard"}:{},...c});return}t("posting",c),e("info",`Posting answer to ${n.issueKey} (${u.resultText.length} chars)`),await n.jira.addComment(n.issueKey,u.resultText),t("succeeded",{...c,resultSummary:nr(u.resultText)}),e("info",`Run succeeded \xB7 $${u.costUsd.toFixed(4)}`)}catch(o){let l=o instanceof Error?o.message:String(o);e("error",`Run failed: ${l}`),t("failed",{error:l})}finally{Vt(n.repoPath)}}async function Cc(n,e,t,r){let s=`${e}-wip`;try{return Vt(n),await Gn(n,`WIP: turn limit exhausted (Allwright run ${t})`),await Oo(n,s),r("info",`Partial work preserved on branch "${s}"`),s}catch(i){return r("warn",`could not preserve partial work: ${i instanceof Error?i.message:i}`),null}}function Ic(n){return`
595
+ Ask again in a new comment to retry. (run \`${n.runId}\`)`).catch(p=>y.error(`could not post answer failure to ${n.issueKey}: ${p}`)),t(u.timedOut?"timed_out":"failed",{error:f,...u.cancelled?{errorKind:"guard"}:{},...c});return}t("posting",c),e("info",`Posting answer to ${n.issueKey} (${u.resultText.length} chars)`),await n.jira.addComment(n.issueKey,u.resultText),t("succeeded",{...c,resultSummary:ir(u.resultText)}),e("info",`Run succeeded \xB7 $${u.costUsd.toFixed(4)}`)}catch(o){let l=o instanceof Error?o.message:String(o);e("error",`Run failed: ${l}`),t("failed",{error:l})}finally{Jt(n.repoPath)}}async function Mc(n,e,t,r){let s=`${e}-wip`;try{return Jt(n),await Wn(n,`WIP: turn limit exhausted (Allwright run ${t})`),await Lo(n,s),r("info",`Partial work preserved on branch "${s}"`),s}catch(i){return r("warn",`could not preserve partial work: ${i instanceof Error?i.message:i}`),null}}function zc(n){return`
582
596
 
583
- Partial work from this run is saved on branch \`${n}\` - it was NOT safety-checked or reviewed and never merges on its own; a future run or a developer can pick it up.`}async function Eg(n){let{emit:e,setStatus:t,sendUsage:r,nextSeq:s}=tr(n.runId,n.transport),{trigger:i}=n.rule,o=n.rule.action;if(o.type!=="implement")return;let l=on(o.agent,o.type);if(l){e("error",l),await Gr(n,l),t("failed",{error:l});return}let u=Ci.default.join(Pt(),n.runId),c=jt(o.branchTemplate,{issueKey:n.issueKey}),f=(0,Ii.randomUUID)(),p=!1,b=!1;try{if(!mi(me()??n.cfg,n.project.repoName,n.actorEmail))throw new Error("no GitHub token applies to this repo - run `allwright github set-token` (runner-wide) or `github set <repoName>` (this repo only)");if(c===o.baseBranch&&!n.continueBranch)throw new Error(`rendered branch "${c}" equals the base branch - refusing (check the rule's branch template)`);if(t("running"),e("info",`Run started for ${n.issueKey} (rule "${n.rule.name}", implement)`),o.jiraTransitionOnStart)try{await n.jira.transitionByName(n.issueKey,o.jiraTransitionOnStart)?e("info",`Jira transition "${o.jiraTransitionOnStart}" applied at run start`):e("warn",`no transition named "${o.jiraTransitionOnStart}" is available from this ticket's current status - continuing anyway`)}catch(L){e("warn",`Jira start transition failed: ${L instanceof Error?L.message:L} - continuing anyway`)}let w=await Vn(n.repoPath);if(e("info",`Repo origin: ${w}`),!et(w))throw new Error(`origin "${w}" is not a GitHub remote - implement mode supports GitHub only`);e("info",`Fetching ${n.issueKey} from Jira`);let T=await n.jira.getIssue(n.issueKey),x=n.continueBranch?c:o.baseBranch;e("info",n.continueBranch?`Continuing branch "${c}" from origin/${c} (autopilot batch)`:`Preparing worktree on branch "${c}" from origin/${o.baseBranch}`),await nn(n.repoPath,x),await Mo(n.repoPath,c),await zo(n.repoPath,u,c,x),p=!0;let A=jt(o.promptTemplate,{issueKey:T.key,summary:T.summary,description:T.description||"(no description)",comments:Ss(T.comments)})+await Ir(n.jira,T.attachments,u,e)+ba(u)+Tg(n.repoPath)+_g+kg+(o.writeTests?_c.WRITE_TESTS_PROMPT:"")+(o.updateMemory?ze.MEMORY_UPDATE_PROMPT:"");e("info",`Starting Claude Code in the worktree - edit tools enabled, path-jailed, no shell, timeout ${o.timeoutSeconds}s`);let v=await Hr(n.runId,Me(o.agent),{repoPath:u,prompt:A,timeoutSeconds:o.timeoutSeconds,bin:je(n.cfg,o.agent),configDir:n.claudeConfigDir,mode:"edit_no_shell",model:o.model||void 0,maxTurns:o.maxTurns,sessionId:f,onLog:(L,z)=>e(L,z),onUsage:r},e,()=>di(u)),Z={costUsd:v.costUsd,inputTokens:v.inputTokens,outputTokens:v.outputTokens,billingMode:v.billingMode,model:v.model};if(!v.ok){let L=v.error??"Claude Code failed";e("error",`Run failed: ${L}`);let z=L;if(v.turnLimitHit){let h=await Cc(u,c,n.runId,e);h&&(z+=Ic(h))}await Gr(n,z),t(v.timedOut?"timed_out":"failed",{error:L,...v.cancelled?{errorKind:"guard"}:{},...Z});return}let M=Ts(v.resultText);if(M){b=!0,await Ei({kind:"implement",runId:n.runId,issueKey:n.issueKey,repoPath:u,sessionId:f,doneLabel:i.doneLabel,failedLabel:i.failedLabel,timeoutSeconds:o.timeoutSeconds,jira:n.jira,nextLogSeq:s(),rounds:1,claudeConfigDir:n.claudeConfigDir,agent:o.agent,model:o.model,actorEmail:n.actorEmail,baseRepoPath:n.repoPath,repoName:n.project.repoName,branch:c,baseBranch:o.baseBranch,jiraTransition:o.jiraTransition,jiraTransitionOnMerge:o.jiraTransitionOnMerge,requireApproval:o.requireApproval,maxTurns:o.maxTurns,issueSummary:T.summary},M,e,t,Z);return}Vt(u),await Ec({runId:n.runId,issueKey:n.issueKey,issueSummary:T.summary,worktreePath:u,agentConfigDir:n.claudeConfigDir,baseRepoPath:n.repoPath,branch:c,baseBranch:o.baseBranch,jiraTransition:o.jiraTransition,jiraTransitionOnMerge:o.jiraTransitionOnMerge,requireApproval:o.requireApproval,doneLabel:i.doneLabel,failedLabel:i.failedLabel,repoName:n.project.repoName,jira:n.jira,cfg:n.cfg,actorEmail:n.actorEmail,resultText:v.resultText,costFields:Z,runTests:o.runTests,fixSession:{sessionId:f,agent:o.agent,model:o.model,timeoutSeconds:o.timeoutSeconds,maxTurns:o.maxTurns},sendUsage:r,mergeOnApprove:o.mergeOnApprove,mergeMethod:o.mergeMethod,autoMerge:o.autoMerge,emit:e,setStatus:t})}catch(w){let T=w instanceof Error?w.message:String(w);e("error",`Run failed: ${T}`),await Gr(n,T),t("failed",{error:T})}finally{p&&!b&&await ft(n.repoPath,u).catch(()=>{})}}async function Rc(n,e,t,r){let{emit:s,setStatus:i,sendUsage:o,nextSeq:l}=tr(n.runId,r.transport,n.nextLogSeq),u=n.repoPath,c=!1;try{if(!mi(me()??r.cfg,n.repoName??"",n.actorEmail))throw new Error("no GitHub token applies to this repo - run `allwright github set-token` (runner-wide) or `github set <repoName>` (this repo only)");i("running"),s("info",`Reply received on ${n.issueKey} - continuing run \`${n.runId}\``);let f=Mc(e)+await Ir(r.jiraFor(n.repoName??""),t,u,s),p=await Hr(n.runId,Me(n.agent),{repoPath:u,prompt:f,timeoutSeconds:n.timeoutSeconds,bin:je(r.cfg,n.agent??""),configDir:n.claudeConfigDir,mode:"edit_no_shell",model:n.model||void 0,maxTurns:n.maxTurns??120,sessionId:n.sessionId,resume:!0,onLog:(T,x)=>s(T,x),onUsage:o},s,()=>di(u)),b={costUsd:p.costUsd,inputTokens:p.inputTokens,outputTokens:p.outputTokens,billingMode:p.billingMode,model:p.model};if(!p.ok){let T=p.error??"Claude Code failed";s("error",`Run failed: ${T}`);let x=T;if(p.turnLimitHit&&n.branch){let A=await Cc(u,n.branch,n.runId,s);A&&(x+=Ic(A))}await vt(r.jiraFor(n.repoName??""),n.issueKey,n.runId,n.failedLabel,x),yt(n.runId),i(p.timedOut?"timed_out":"failed",{error:T,...p.cancelled?{errorKind:"guard"}:{},...b});return}let w=Ts(p.resultText);if(w){if(n.rounds>=kc){await zc(r.jiraFor(n.repoName??""),n,s,i,b);return}c=!0,await Ei({kind:"implement",runId:n.runId,issueKey:n.issueKey,repoPath:u,sessionId:n.sessionId,doneLabel:n.doneLabel,failedLabel:n.failedLabel,timeoutSeconds:n.timeoutSeconds,jira:r.jiraFor(n.repoName??""),nextLogSeq:l(),rounds:n.rounds+1,createdAt:n.createdAt,claudeConfigDir:n.claudeConfigDir,actorEmail:n.actorEmail,agent:n.agent,model:n.model,baseRepoPath:n.baseRepoPath,repoName:n.repoName,branch:n.branch,baseBranch:n.baseBranch,jiraTransition:n.jiraTransition,jiraTransitionOnMerge:n.jiraTransitionOnMerge,requireApproval:n.requireApproval,maxTurns:n.maxTurns,issueSummary:n.issueSummary},w,s,i,b);return}Vt(u),await Ec({runId:n.runId,issueKey:n.issueKey,issueSummary:n.issueSummary,worktreePath:u,agentConfigDir:n.claudeConfigDir,baseRepoPath:n.baseRepoPath??u,branch:n.branch,baseBranch:n.baseBranch,jiraTransition:n.jiraTransition,requireApproval:n.requireApproval??!0,doneLabel:n.doneLabel,failedLabel:n.failedLabel,repoName:n.repoName,jira:r.jiraFor(n.repoName??""),cfg:r.cfg,actorEmail:n.actorEmail,resultText:p.resultText,costFields:b,runTests:n.runTests,fixSession:{sessionId:n.sessionId,agent:n.agent??"",model:n.model,timeoutSeconds:n.timeoutSeconds,maxTurns:n.maxTurns},sendUsage:o,mergeOnApprove:n.mergeOnApprove,mergeMethod:n.mergeMethod,autoMerge:n.autoMerge??!1,emit:s,setStatus:i}),yt(n.runId)}catch(f){let p=f instanceof Error?f.message:String(f);s("error",`Run failed: ${p}`),await vt(r.jiraFor(n.repoName??""),n.issueKey,n.runId,n.failedLabel,p),yt(n.runId),i("failed",{error:p})}finally{c||await ft(n.baseRepoPath??u,u).catch(()=>{})}}async function Ec(n){let{runId:e,issueKey:t,issueSummary:r,worktreePath:s,baseRepoPath:i,branch:o,baseBranch:l,jiraTransition:u,jiraTransitionOnMerge:c,requireApproval:f,doneLabel:p,failedLabel:b,repoName:w,jira:T,cfg:x,actorEmail:A,runTests:v,mergeOnApprove:Z,mergeMethod:M,autoMerge:L,resultText:z,costFields:h,emit:m,setStatus:g}=n,C=await Mr(s);C.deleted.length&&m("info",`Deleted ${C.deleted.length} file(s) listed in ${$t}: `+C.deleted.slice(0,10).join(", ")+(C.deleted.length>10?", \u2026":""));for(let pe of C.refused)m("warn",`${$t} entry refused: ${pe}`);m("info","Committing changes"),await Gn(s,`${t}: ${r}
597
+ Partial work from this run is saved on branch \`${n}\` - it was NOT safety-checked or reviewed and never merges on its own; a future run or a developer can pick it up.`}async function Bg(n){let{emit:e,setStatus:t,sendUsage:r,nextSeq:s}=sr(n.runId,n.transport),{trigger:i}=n.rule,o=n.rule.action;if(o.type!=="implement")return;let l=ln(o.agent,o.type);if(l){e("error",l),await Jr(n,l),t("failed",{error:l});return}let u=Ai.default.join(Nt(),n.runId),c=zt(o.branchTemplate,{issueKey:n.issueKey}),f=(0,$i.randomUUID)(),p=!1,b=!1;try{if(!bi(pe()??n.cfg,n.project.repoName,n.actorEmail))throw new Error("no GitHub token applies to this repo - run `allwright github set-token` (runner-wide) or `github set <repoName>` (this repo only)");if(c===o.baseBranch&&!n.continueBranch)throw new Error(`rendered branch "${c}" equals the base branch - refusing (check the rule's branch template)`);if(t("running"),e("info",`Run started for ${n.issueKey} (rule "${n.rule.name}", implement)`),o.jiraTransitionOnStart)try{await n.jira.transitionByName(n.issueKey,o.jiraTransitionOnStart)?e("info",`Jira transition "${o.jiraTransitionOnStart}" applied at run start`):e("warn",`no transition named "${o.jiraTransitionOnStart}" is available from this ticket's current status - continuing anyway`)}catch(D){e("warn",`Jira start transition failed: ${D instanceof Error?D.message:D} - continuing anyway`)}let w=await Yn(n.repoPath);if(e("info",`Repo origin: ${w}`),!nt(w))throw new Error(`origin "${w}" is not a GitHub remote - implement mode supports GitHub only`);e("info",`Fetching ${n.issueKey} from Jira`);let T=await n.jira.getIssue(n.issueKey),C=n.continueBranch?c:o.baseBranch;e("info",n.continueBranch?`Continuing branch "${c}" from origin/${c} (autopilot batch)`:`Preparing worktree on branch "${c}" from origin/${o.baseBranch}`),await sn(n.repoPath,C),await qo(n.repoPath,c),await Fo(n.repoPath,u,c,C),p=!0;let A=zt(o.promptTemplate,{issueKey:T.key,summary:T.summary,description:T.description||"(no description)",comments:Es(T.comments)})+await $r(n.jira,T.attachments,u,e)+Ca(u)+Dg(n.repoPath)+Og+Ng+(n.project.goLiveIssueKey?Mg:"")+(o.writeTests?$c.WRITE_TESTS_PROMPT:"")+(o.updateMemory?Le.MEMORY_UPDATE_PROMPT:"");e("info",`Starting Claude Code in the worktree - edit tools enabled, path-jailed, no shell, timeout ${o.timeoutSeconds}s`);let v=await Yr(n.runId,De(o.agent),{repoPath:u,prompt:A,timeoutSeconds:o.timeoutSeconds,bin:Oe(n.cfg,o.agent),configDir:n.claudeConfigDir,mode:"edit_no_shell",model:o.model||void 0,maxTurns:o.maxTurns,sessionId:f,onLog:(D,K)=>e(D,K),onUsage:r},e,()=>mi(u)),B={costUsd:v.costUsd,inputTokens:v.inputTokens,outputTokens:v.outputTokens,billingMode:v.billingMode,model:v.model};if(!v.ok){let D=v.error??"Claude Code failed";e("error",`Run failed: ${D}`);let K=D;if(v.turnLimitHit){let h=await Mc(u,c,n.runId,e);h&&(K+=zc(h))}rt(n.repoPath,{issueKey:n.issueKey,runId:n.runId,title:"implement failed",detail:D.slice(0,500)}),await Jr(n,K),t(v.timedOut?"timed_out":"failed",{error:D,...v.cancelled?{errorKind:"guard"}:{},...B});return}let N=As(v.resultText);if(N){b=!0,await ji({kind:"implement",runId:n.runId,issueKey:n.issueKey,repoPath:u,sessionId:f,doneLabel:i.doneLabel,failedLabel:i.failedLabel,timeoutSeconds:o.timeoutSeconds,jira:n.jira,nextLogSeq:s(),rounds:1,claudeConfigDir:n.claudeConfigDir,agent:o.agent,model:o.model,actorEmail:n.actorEmail,baseRepoPath:n.repoPath,repoName:n.project.repoName,branch:c,baseBranch:o.baseBranch,jiraTransition:o.jiraTransition,jiraTransitionOnMerge:o.jiraTransitionOnMerge,requireApproval:o.requireApproval,maxTurns:o.maxTurns,issueSummary:T.summary},N,e,t,B);return}Jt(u),await Lc({runId:n.runId,issueKey:n.issueKey,issueSummary:T.summary,worktreePath:u,agentConfigDir:n.claudeConfigDir,baseRepoPath:n.repoPath,branch:c,baseBranch:o.baseBranch,jiraTransition:o.jiraTransition,jiraTransitionOnMerge:o.jiraTransitionOnMerge,requireApproval:o.requireApproval,doneLabel:i.doneLabel,failedLabel:i.failedLabel,repoName:n.project.repoName,jira:n.jira,cfg:n.cfg,actorEmail:n.actorEmail,resultText:v.resultText,costFields:B,runTests:o.runTests,fixSession:{sessionId:f,agent:o.agent,model:o.model,timeoutSeconds:o.timeoutSeconds,maxTurns:o.maxTurns},sendUsage:r,mergeOnApprove:o.mergeOnApprove,mergeMethod:o.mergeMethod,autoMerge:o.autoMerge,emit:e,setStatus:t})}catch(w){let T=w instanceof Error?w.message:String(w);e("error",`Run failed: ${T}`),rt(n.repoPath,{issueKey:n.issueKey,runId:n.runId,title:"implement failed",detail:T.slice(0,500)}),await Jr(n,T),t("failed",{error:T})}finally{p&&!b&&await mt(n.repoPath,u).catch(()=>{})}}async function Dc(n,e,t,r){let{emit:s,setStatus:i,sendUsage:o,nextSeq:l}=sr(n.runId,r.transport,n.nextLogSeq),u=n.repoPath,c=!1;try{if(!bi(pe()??r.cfg,n.repoName??"",n.actorEmail))throw new Error("no GitHub token applies to this repo - run `allwright github set-token` (runner-wide) or `github set <repoName>` (this repo only)");i("running"),s("info",`Reply received on ${n.issueKey} - continuing run \`${n.runId}\``);let f=Gc(e)+await $r(r.jiraFor(n.repoName??""),t,u,s),p=await Yr(n.runId,De(n.agent),{repoPath:u,prompt:f,timeoutSeconds:n.timeoutSeconds,bin:Oe(r.cfg,n.agent??""),configDir:n.claudeConfigDir,mode:"edit_no_shell",model:n.model||void 0,maxTurns:n.maxTurns??120,sessionId:n.sessionId,resume:!0,onLog:(T,C)=>s(T,C),onUsage:o},s,()=>mi(u)),b={costUsd:p.costUsd,inputTokens:p.inputTokens,outputTokens:p.outputTokens,billingMode:p.billingMode,model:p.model};if(!p.ok){let T=p.error??"Claude Code failed";s("error",`Run failed: ${T}`);let C=T;if(p.turnLimitHit&&n.branch){let A=await Mc(u,n.branch,n.runId,s);A&&(C+=zc(A))}await wt(r.jiraFor(n.repoName??""),n.issueKey,n.runId,n.failedLabel,C),bt(n.runId),i(p.timedOut?"timed_out":"failed",{error:T,...p.cancelled?{errorKind:"guard"}:{},...b});return}let w=As(p.resultText);if(w){if(n.rounds>=Pc){await Hc(r.jiraFor(n.repoName??""),n,s,i,b);return}c=!0,await ji({kind:"implement",runId:n.runId,issueKey:n.issueKey,repoPath:u,sessionId:n.sessionId,doneLabel:n.doneLabel,failedLabel:n.failedLabel,timeoutSeconds:n.timeoutSeconds,jira:r.jiraFor(n.repoName??""),nextLogSeq:l(),rounds:n.rounds+1,createdAt:n.createdAt,claudeConfigDir:n.claudeConfigDir,actorEmail:n.actorEmail,agent:n.agent,model:n.model,baseRepoPath:n.baseRepoPath,repoName:n.repoName,branch:n.branch,baseBranch:n.baseBranch,jiraTransition:n.jiraTransition,jiraTransitionOnMerge:n.jiraTransitionOnMerge,requireApproval:n.requireApproval,maxTurns:n.maxTurns,issueSummary:n.issueSummary},w,s,i,b);return}Jt(u),await Lc({runId:n.runId,issueKey:n.issueKey,issueSummary:n.issueSummary,worktreePath:u,agentConfigDir:n.claudeConfigDir,baseRepoPath:n.baseRepoPath??u,branch:n.branch,baseBranch:n.baseBranch,jiraTransition:n.jiraTransition,requireApproval:n.requireApproval??!0,doneLabel:n.doneLabel,failedLabel:n.failedLabel,repoName:n.repoName,jira:r.jiraFor(n.repoName??""),cfg:r.cfg,actorEmail:n.actorEmail,resultText:p.resultText,costFields:b,runTests:n.runTests,fixSession:{sessionId:n.sessionId,agent:n.agent??"",model:n.model,timeoutSeconds:n.timeoutSeconds,maxTurns:n.maxTurns},sendUsage:o,mergeOnApprove:n.mergeOnApprove,mergeMethod:n.mergeMethod,autoMerge:n.autoMerge??!1,emit:s,setStatus:i}),bt(n.runId)}catch(f){let p=f instanceof Error?f.message:String(f);s("error",`Run failed: ${p}`),await wt(r.jiraFor(n.repoName??""),n.issueKey,n.runId,n.failedLabel,p),bt(n.runId),i("failed",{error:p})}finally{c||await mt(n.baseRepoPath??u,u).catch(()=>{})}}async function Lc(n){let{runId:e,issueKey:t,issueSummary:r,worktreePath:s,baseRepoPath:i,branch:o,baseBranch:l,jiraTransition:u,jiraTransitionOnMerge:c,requireApproval:f,doneLabel:p,failedLabel:b,repoName:w,jira:T,cfg:C,actorEmail:A,runTests:v,mergeOnApprove:B,mergeMethod:N,autoMerge:D,resultText:K,costFields:h,emit:m,setStatus:g}=n,x=await Ur(s);x.deleted.length&&m("info",`Deleted ${x.deleted.length} file(s) listed in ${Ot}: `+x.deleted.slice(0,10).join(", ")+(x.deleted.length>10?", \u2026":""));for(let ve of x.refused)m("warn",`${Ot} entry refused: ${ve}`);m("info","Committing changes"),await Wn(s,`${t}: ${r}
584
598
 
585
- Allwright run ${e}`);let N=await rn(s,l);if(!N.ok){let pe=N.forbidden.length?`refusing to push: changes touch protected paths (${N.forbidden.slice(0,5).join(", ")}) - CI/workflow files can exfiltrate repo secrets and are never pushed by the agent. Apply those files' changes yourself, or re-run the ticket with them out of scope.`:`refusing to push: change is too large (${N.files} files, ${N.insertions+N.deletions} lines; limits ${en}/${tn})`;m("error",pe),await vt(T,t,e,b,pe),g("failed",{error:pe,errorKind:"guard",...h});return}m("info",`Diff: ${N.files} file(s), +${N.insertions}/-${N.deletions}`);let F={...h},X="",ee="",H;if(v){let pe=Ur(s);if(!pe)m("info","No TEST.md in this repo - skipping the test run (nothing documented to run)");else{let _t=qr(va.default.readFileSync(pe,"utf8"));if(!_t.length)m("info",`${Ci.default.basename(pe)} lists no commands - nothing to run`);else{m("info",`Running ${_t.length} documented test command(s) - no tokens, plain shell`);let qt=await Yn(s,_t,{perCommandTimeoutMs:15*6e4}),at=qt.filter(ue=>ue.exitCode!==0),ll=at.length;for(let ue of qt)m(ue.exitCode===0?"info":"warn",`${ue.exitCode===0?"PASS":"FAIL"} ${ue.command} (exit ${ue.exitCode})`+(ue.exitCode===0?"":`
586
- ${ue.tail.slice(-1500)}`));let Ms="";if(at.length&&n.fixSession){let ue=await $g({runId:e,issueKey:t,worktreePath:s,baseBranch:l,fixSession:n.fixSession,agentConfigDir:n.agentConfigDir,cfg:x,failed:at,emit:m,sendUsage:n.sendUsage,baseCost:F});if(F.costUsd+=ue.cost.costUsd,F.inputTokens+=ue.cost.inputTokens,F.outputTokens+=ue.cost.outputTokens,ue.outcome==="cancelled"){let Le="stopped by a person during the automatic test-fix attempt - nothing was pushed";m("warn",Le),_i({runId:e,issueKey:t,issueSummary:r,mergeOnApprove:Z,mergeMethod:M,autoMerge:L,repoName:w,baseRepoPath:i,branch:o,baseBranch:l,headSha:await He(s),requireApproval:f,doneLabel:p,failedLabel:b,jiraTransition:u,jiraTransitionOnMerge:c,actorEmail:A,resultSummary:wc(z),prSummary:ga(z)??"",costUsd:F.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),await vt(T,t,e,b,`${Le}. The commit survived on the runner - "Retry push" on the run's dashboard page ships it without a new agent run.`),g("failed",{error:Le,errorKind:"guard",retryAvailable:!0,...F});return}if(ue.outcome==="committed"){ee=ue.resultText,m("info",`Re-running ${_t.length} documented test command(s) after the fix`),qt=await Yn(s,_t,{perCommandTimeoutMs:15*6e4}),at=qt.filter(Le=>Le.exitCode!==0);for(let Le of qt)m(Le.exitCode===0?"info":"warn",`${Le.exitCode===0?"PASS":"FAIL"} ${Le.command} (exit ${Le.exitCode})`+(Le.exitCode===0?"":`
587
- ${Le.tail.slice(-1500)}`));Ms=at.length?`One automatic same-session fix attempt ran; the results above are AFTER it. First pass: ${ll} failure(s). ${ue.note}`:`The first pass had ${ll} failure(s); one automatic same-session fix attempt resolved them. ${ue.note}`}else Ms=ue.note}H=at.slice(0,20).map(ue=>({command:ue.command.slice(0,500),exitCode:ue.exitCode,tail:ue.tail.slice(-4e3)})),X=`
599
+ Allwright run ${e}`);let M=await on(s,l);if(!M.ok){let ve=M.forbidden.length?`refusing to push: changes touch protected paths (${M.forbidden.slice(0,5).join(", ")}) - CI/workflow files can exfiltrate repo secrets and are never pushed by the agent. Apply those files' changes yourself, or re-run the ticket with them out of scope.`:`refusing to push: change is too large (${M.files} files, ${M.insertions+M.deletions} lines; limits ${nn}/${rn})`;m("error",ve),await wt(T,t,e,b,ve),g("failed",{error:ve,errorKind:"guard",...h});return}m("info",`Diff: ${M.files} file(s), +${M.insertions}/-${M.deletions}`);let q={...h},X="",ee="",H,$,te;if(v){let ve=Kr(s);if(!ve)m("info","No TEST.md in this repo - skipping the test run (nothing documented to run)");else{let St=Zr(xa.default.readFileSync(ve,"utf8"));if(!St.length)m("info",`${Ai.default.basename(ve)} lists no commands - nothing to run`);else{m("info",`Running ${St.length} documented test command(s) - no tokens, plain shell`);let qe=await er(s,St,{perCommandTimeoutMs:15*6e4}),Ne=qe.filter(ae=>ae.exitCode!==0),oo=Ne.length;for(let ae of qe)m(ae.exitCode===0?"info":"warn",`${ae.exitCode===0?"PASS":"FAIL"} ${ae.command} (exit ${ae.exitCode})`+(ae.exitCode===0?"":`
600
+ ${ae.tail.slice(-1500)}`));let _r="";if(Ne.length&&n.fixSession){let ae=await Zg({runId:e,issueKey:t,worktreePath:s,baseBranch:l,fixSession:n.fixSession,agentConfigDir:n.agentConfigDir,cfg:C,failed:Ne,emit:m,sendUsage:n.sendUsage,baseCost:q});if(q.costUsd+=ae.cost.costUsd,q.inputTokens+=ae.cost.inputTokens,q.outputTokens+=ae.cost.outputTokens,ae.outcome==="cancelled"){let Fe="stopped by a person during the automatic test-fix attempt - nothing was pushed";m("warn",Fe),xi({runId:e,issueKey:t,issueSummary:r,mergeOnApprove:B,mergeMethod:N,autoMerge:D,repoName:w,baseRepoPath:i,branch:o,baseBranch:l,headSha:await Je(s),requireApproval:f,doneLabel:p,failedLabel:b,jiraTransition:u,jiraTransitionOnMerge:c,actorEmail:A,resultSummary:Ac(K),prSummary:Sa(K)??"",costUsd:q.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),await wt(T,t,e,b,`${Fe}. The commit survived on the runner - "Retry push" on the run's dashboard page ships it without a new agent run.`),g("failed",{error:Fe,errorKind:"guard",retryAvailable:!0,...q});return}if(ae.outcome==="committed"){ee=ae.resultText,m("info",`Re-running ${St.length} documented test command(s) after the fix`),qe=await er(s,St,{perCommandTimeoutMs:15*6e4}),Ne=qe.filter(Fe=>Fe.exitCode!==0);for(let Fe of qe)m(Fe.exitCode===0?"info":"warn",`${Fe.exitCode===0?"PASS":"FAIL"} ${Fe.command} (exit ${Fe.exitCode})`+(Fe.exitCode===0?"":`
601
+ ${Fe.tail.slice(-1500)}`));_r=Ne.length?`One automatic same-session fix attempt ran; the results above are AFTER it. First pass: ${oo} failure(s). ${ae.note}`:`The first pass had ${oo} failure(s); one automatic same-session fix attempt resolved them. ${ae.note}`}else _r=ae.note}H=Ne.slice(0,20).map(ae=>({command:ae.command.slice(0,500),exitCode:ae.exitCode,tail:ae.tail.slice(-4e3)})),$=qe.length-Ne.length,te=qe.length,X=`
588
602
 
589
603
  ### Tests
590
- `+qt.map(ue=>`- ${ue.exitCode===0?"PASS":"FAIL"} \`${ue.command}\``).join(`
591
- `)+(at.length?`
604
+ `+qe.map(ae=>`- ${ae.exitCode===0?"PASS":"FAIL"} \`${ae.command}\``).join(`
605
+ `)+(Ne.length?`
592
606
 
593
- **${at.length} of ${qt.length} failed.** Output is in the run log.`:`
607
+ **${Ne.length} of ${qe.length} failed.** Output is in the run log.`:`
594
608
 
595
- All ${qt.length} passed.`)+(Ms?`
609
+ All ${qe.length} passed.`)+(_r?`
596
610
 
597
- ${Ms}`:""),at.length&&m("warn",`${at.length} test command(s) failed - the PR will say so; review before merging`)}}}let j=await Vn(s),te=et(j);if(!te){let pe=`origin "${j}" is not a GitHub remote - implement mode supports GitHub only`;m("error",pe),await vt(T,t,e,b,pe),g("failed",{error:pe,...h});return}let se=await He(s),le=wc(z),Ye=(ee?ga(ee):null)??ga(z);try{await Ac({gitDir:s,ownerRepo:te,runId:e,issueKey:t,issueSummary:r,agentConfigDir:n.agentConfigDir,branch:o,baseBranch:l,jiraTransition:u,jiraTransitionOnMerge:c,requireApproval:f,doneLabel:p,failedLabel:b,repoName:w,jira:T,cfg:x,actorEmail:A,mergeOnApprove:Z,mergeMethod:M,autoMerge:L,summary:le,prSummary:Ye??void 0,cost:F,testReport:X,failedTests:H,emit:m,setStatus:g})}catch(pe){let _t=pe instanceof Error?pe.message:String(pe);_i({runId:e,issueKey:t,issueSummary:r,mergeOnApprove:Z,mergeMethod:M,autoMerge:L,repoName:w,baseRepoPath:i,branch:o,baseBranch:l,headSha:se,requireApproval:f,doneLabel:p,failedLabel:b,jiraTransition:u,jiraTransitionOnMerge:c,actorEmail:A,resultSummary:le,prSummary:Ye??"",costUsd:F.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),m("error",`Run failed: ${_t}`),m("info",`The commit itself survived on the runner (branch ${o}) - fix the cause, then use "Retry push" on this run's dashboard page.`),await vt(T,t,e,b,`${_t}
611
+ ${_r}`:""),Ne.length&&m("warn",`${Ne.length} test command(s) failed - the PR will say so; review before merging`),oo>0&&rt(i,{issueKey:t,runId:e,title:Ne.length?`TEST.md commands failing at PR (${Ne.length} of ${qe.length})`:"TEST.md failures fixed by same-session retry",detail:qe.map(ae=>`${ae.exitCode===0?"PASS":"FAIL"} ${ae.command}`).join(`
612
+ `)+(_r?`
613
+ ${_r}`:"")})}}}let ne=await Yn(s),ce=nt(ne);if(!ce){let ve=`origin "${ne}" is not a GitHub remote - implement mode supports GitHub only`;m("error",ve),await wt(T,t,e,b,ve),g("failed",{error:ve,...h});return}let Ee=await Je(s),cs=Ac(K),ml=(ee?Sa(ee):null)??Sa(K);try{await Uc({gitDir:s,ownerRepo:ce,runId:e,issueKey:t,issueSummary:r,agentConfigDir:n.agentConfigDir,branch:o,baseBranch:l,jiraTransition:u,jiraTransitionOnMerge:c,requireApproval:f,doneLabel:p,failedLabel:b,repoName:w,jira:T,cfg:C,actorEmail:A,mergeOnApprove:B,mergeMethod:N,autoMerge:D,summary:cs,prSummary:ml??void 0,cost:q,testReport:X,failedTests:H,testsPassed:$,testsTotal:te,goLiveDraft:(ee?Ic(ee):null)??Ic(K)??void 0,emit:m,setStatus:g})}catch(ve){let St=ve instanceof Error?ve.message:String(ve);xi({runId:e,issueKey:t,issueSummary:r,mergeOnApprove:B,mergeMethod:N,autoMerge:D,repoName:w,baseRepoPath:i,branch:o,baseBranch:l,headSha:Ee,requireApproval:f,doneLabel:p,failedLabel:b,jiraTransition:u,jiraTransitionOnMerge:c,actorEmail:A,resultSummary:cs,prSummary:ml??"",costUsd:q.costUsd,nextLogSeq:1e5,createdAt:new Date().toISOString()}),m("error",`Run failed: ${St}`),m("info",`The commit itself survived on the runner (branch ${o}) - fix the cause, then use "Retry push" on this run's dashboard page.`),await wt(T,t,e,b,`${St}
598
614
 
599
- The agent's commit survived on the runner - "Retry push" on the dashboard's run page re-pushes it without a new agent run.`),g("failed",{error:_t,retryAvailable:!0,...F})}}var Ag={costUsd:0,inputTokens:0,outputTokens:0};async function $g(n){let{runId:e,issueKey:t,worktreePath:r,baseBranch:s,fixSession:i,cfg:o,failed:l,emit:u,sendUsage:c,baseCost:f}=n,p=Me(i.agent);if(!p?.capabilities.sessionResume){let v=`No automatic fix attempt: the ${i.agent||"configured"} adapter cannot resume sessions.`;return u("info",v),{outcome:"skipped",note:v,cost:Ag}}u("info",`${l.length} test command(s) failed - resuming the same agent session for one fix attempt (same session = cached context, not a re-explore)`);let b=await He(r),w=await Hr(e,p,{repoPath:r,prompt:Sg(l),timeoutSeconds:i.timeoutSeconds,bin:je(o,i.agent),configDir:n.agentConfigDir,mode:"edit_no_shell",model:i.model||void 0,maxTurns:Math.min(i.maxTurns??120,60),sessionId:i.sessionId,resume:!0,onLog:(v,Z)=>u(v,Z),onUsage:c?v=>c({...v,inputTokens:f.inputTokens+v.inputTokens,outputTokens:f.outputTokens+v.outputTokens,costUsd:v.costUsd===void 0?void 0:f.costUsd+v.costUsd}):void 0},u),T={costUsd:w.costUsd,inputTokens:w.inputTokens,outputTokens:w.outputTokens};if(w.cancelled)return{outcome:"cancelled",cost:T};if(!w.ok){let v=`One automatic fix attempt did not complete (${w.error??"agent error"}) - the results above are from the original work.`;return u("warn",v),{outcome:"agent_failed",note:v,cost:T}}if(Ts(w.resultText)){let v="One automatic fix attempt asked for human input instead of fixing - the original commit ships unchanged; answer on the PR instead.";return u("warn",v),{outcome:"agent_failed",note:v,cost:T}}let x=await Mr(r);for(let v of x.refused)u("warn",`${$t} entry refused: ${v}`);try{await Gn(r,`${t}: fix failing TEST.md commands
615
+ The agent's commit survived on the runner - "Retry push" on the dashboard's run page re-pushes it without a new agent run.`),g("failed",{error:St,retryAvailable:!0,...q})}}var Kg={costUsd:0,inputTokens:0,outputTokens:0};async function Zg(n){let{runId:e,issueKey:t,worktreePath:r,baseBranch:s,fixSession:i,cfg:o,failed:l,emit:u,sendUsage:c,baseCost:f}=n,p=De(i.agent);if(!p?.capabilities.sessionResume){let v=`No automatic fix attempt: the ${i.agent||"configured"} adapter cannot resume sessions.`;return u("info",v),{outcome:"skipped",note:v,cost:Kg}}u("info",`${l.length} test command(s) failed - resuming the same agent session for one fix attempt (same session = cached context, not a re-explore)`);let b=await Je(r),w=await Yr(e,p,{repoPath:r,prompt:zg(l),timeoutSeconds:i.timeoutSeconds,bin:Oe(o,i.agent),configDir:n.agentConfigDir,mode:"edit_no_shell",model:i.model||void 0,maxTurns:Math.min(i.maxTurns??120,60),sessionId:i.sessionId,resume:!0,onLog:(v,B)=>u(v,B),onUsage:c?v=>c({...v,inputTokens:f.inputTokens+v.inputTokens,outputTokens:f.outputTokens+v.outputTokens,costUsd:v.costUsd===void 0?void 0:f.costUsd+v.costUsd}):void 0},u),T={costUsd:w.costUsd,inputTokens:w.inputTokens,outputTokens:w.outputTokens};if(w.cancelled)return{outcome:"cancelled",cost:T};if(!w.ok){let v=`One automatic fix attempt did not complete (${w.error??"agent error"}) - the results above are from the original work.`;return u("warn",v),{outcome:"agent_failed",note:v,cost:T}}if(As(w.resultText)){let v="One automatic fix attempt asked for human input instead of fixing - the original commit ships unchanged; answer on the PR instead.";return u("warn",v),{outcome:"agent_failed",note:v,cost:T}}let C=await Ur(r);for(let v of C.refused)u("warn",`${Ot} entry refused: ${v}`);try{await Wn(r,`${t}: fix failing TEST.md commands
600
616
 
601
- Allwright run ${e} (automatic test-fix attempt)`)}catch{let v=`An automatic fix attempt concluded no code change was warranted: ${nr(w.resultText)}`;return u("info",v),{outcome:"no_changes",note:v,cost:T}}let A=await rn(r,s);if(!A.ok){await zr(r,b);let v=A.forbidden.length?`An automatic fix attempt touched protected paths (${A.forbidden.slice(0,3).join(", ")}) and was discarded - the results above are from the original work.`:"An automatic fix attempt pushed the diff past the safety limits and was discarded - the results above are from the original work.";return u("warn",v),{outcome:"reverted",note:v,cost:T}}return{outcome:"committed",note:`Fix attempt: ${nr(w.resultText)}`,resultText:w.resultText,cost:T}}async function Ac(n){let{gitDir:e,ownerRepo:t,runId:r,issueKey:s,issueSummary:i,mergeOnApprove:o,mergeMethod:l,autoMerge:u,branch:c,baseBranch:f,jiraTransition:p,jiraTransitionOnMerge:b,requireApproval:w,doneLabel:T,failedLabel:x,repoName:A,jira:v,cfg:Z,actorEmail:M,summary:L,prSummary:z,cost:h,testReport:m,emit:g,setStatus:C}=n;g("info",`Pushing ${c} to origin`),await Hn(e,c);let N=await hi(e,c),X=`${z?.trim()?`${z.trim()}
617
+ Allwright run ${e} (automatic test-fix attempt)`)}catch{let v=`An automatic fix attempt concluded no code change was warranted: ${ir(w.resultText)}`;return u("info",v),{outcome:"no_changes",note:v,cost:T}}let A=await on(r,s);if(!A.ok){await qr(r,b);let v=A.forbidden.length?`An automatic fix attempt touched protected paths (${A.forbidden.slice(0,3).join(", ")}) and was discarded - the results above are from the original work.`:"An automatic fix attempt pushed the diff past the safety limits and was discarded - the results above are from the original work.";return u("warn",v),{outcome:"reverted",note:v,cost:T}}return{outcome:"committed",note:`Fix attempt: ${ir(w.resultText)}`,resultText:w.resultText,cost:T}}async function Uc(n){let{gitDir:e,ownerRepo:t,runId:r,issueKey:s,issueSummary:i,mergeOnApprove:o,mergeMethod:l,autoMerge:u,branch:c,baseBranch:f,jiraTransition:p,jiraTransitionOnMerge:b,requireApproval:w,doneLabel:T,failedLabel:C,repoName:A,jira:v,cfg:B,actorEmail:N,summary:D,prSummary:K,cost:h,testReport:m,emit:g,setStatus:x}=n;g("info",`Pushing ${c} to origin`),await Jn(e,c);let M=await gi(e,c),X=`${K?.trim()?`${K.trim()}
602
618
 
603
619
  <details>
604
620
  <summary>Technical details</summary>
605
621
 
606
- ${L}
622
+ ${D}
607
623
 
608
- </details>`:L}${m??""}
624
+ </details>`:D}${m??""}
609
625
 
610
626
  ---
611
- Jira: ${new URL(`/browse/${s}`,Z.jira?.baseUrl??"").toString()}
612
- _Allwright implement run \`${r}\` \xB7 cost $${h.costUsd.toFixed(4)}. `+(m?"Tests were run by the runner, not the agent._":"The agent has no shell and no tests were run here - review accordingly._");g("info","Opening pull request");let ee=mi(me()??Z,A,M);ee.source==="user"&&g("info",`PR will be authored with ${M}'s own GitHub token`);let j=await new xe(ee.token).createPullRequest(t.owner,t.repo,{title:`${s}: ${i}`.slice(0,250),head:c,base:f,body:X});g("info",`PR ready: ${j.url}`),pc({runId:r,issueKey:s,repoName:A,owner:t.owner,repo:t.repo,prNumber:j.number,prUrl:j.url,jiraTransitionOnMerge:b??"",createdAt:new Date().toISOString()}),C("posting",h);let te={nextDecisionSeq:1e5,runId:r,issueKey:s,repoName:A,owner:t.owner,repo:t.repo,prNumber:j.number,prUrl:j.url,branch:c,headSha:N,doneLabel:T,failedLabel:x,jiraTransition:p,mergeOnApprove:o,mergeMethod:l,autoMerge:u,agentConfigDir:n.agentConfigDir};if(w)rt(te),await v.addComment(s,`**Allwright opened a pull request for review.**
627
+ Jira: ${new URL(`/browse/${s}`,B.jira?.baseUrl??"").toString()}
628
+ _Allwright implement run \`${r}\` \xB7 cost $${h.costUsd.toFixed(4)}. `+(m?"Tests were run by the runner, not the agent._":"The agent has no shell and no tests were run here - review accordingly._");g("info","Opening pull request");let ee=bi(pe()??B,A,N);ee.source==="user"&&g("info",`PR will be authored with ${N}'s own GitHub token`);let $=await new xe(ee.token).createPullRequest(t.owner,t.repo,{title:`${s}: ${i}`.slice(0,250),head:c,base:f,body:X});g("info",`PR ready: ${$.url}`),Sc({runId:r,issueKey:s,repoName:A,owner:t.owner,repo:t.repo,prNumber:$.number,prUrl:$.url,jiraTransitionOnMerge:b??"",createdAt:new Date().toISOString()}),x("posting",h);let te={nextDecisionSeq:1e5,runId:r,issueKey:s,repoName:A,owner:t.owner,repo:t.repo,prNumber:$.number,prUrl:$.url,branch:c,headSha:M,doneLabel:T,failedLabel:C,jiraTransition:p,mergeOnApprove:o,mergeMethod:l,autoMerge:u,agentConfigDir:n.agentConfigDir};if(w)ot(te),await v.addComment(s,`**Allwright opened a pull request for review.**
613
629
 
614
- PR: ${j.url}
630
+ PR: ${$.url}
615
631
 
616
- Approve the PR on GitHub OR on the Allwright dashboard - either completes the run. Rejecting on the dashboard closes the PR and deletes the branch. (run \`${r}\`)`),C("awaiting_approval",{...h,prUrl:j.url,headSha:N,resultSummary:nr(z?.trim()||L),retryAvailable:!1,...n.failedTests!==void 0?{failedTests:n.failedTests}:{}}),g("info",`Awaiting approval on the dashboard \xB7 $${h.costUsd.toFixed(4)}`);else{if(u){g("info",`Auto-merging PR #${j.number} (${l})`);let se=Te(Z,A),le=se?await new xe(se).mergePullRequest(t.owner,t.repo,j.number,l,{sha:N,title:`${s} (#${j.number})`}):{merged:!1,reason:"no GitHub token applies to this repo"};le.merged?g("info",`PR #${j.number} merged`):(g("warn",`Auto-merge did not go through - ${le.reason}. The PR stays open.`),await v.addComment(s,`**Allwright:** the work is done and the PR is open, but auto-merge did not go through - ${le.reason}
632
+ Approve the PR on GitHub OR on the Allwright dashboard - either completes the run. Rejecting on the dashboard closes the PR and deletes the branch. (run \`${r}\`)`),x("awaiting_approval",{...h,prUrl:$.url,headSha:M,resultSummary:ir(K?.trim()||D),retryAvailable:!1,...n.failedTests!==void 0?{failedTests:n.failedTests}:{},...n.testsPassed!==void 0?{testsPassed:n.testsPassed}:{},...n.testsTotal!==void 0?{testsTotal:n.testsTotal}:{},...n.goLiveDraft!==void 0?{goLiveDraft:n.goLiveDraft}:{}}),g("info",`Awaiting approval on the dashboard \xB7 $${h.costUsd.toFixed(4)}`);else{if(u){g("info",`Auto-merging PR #${$.number} (${l})`);let ce=Te(B,A),Ee=ce?await new xe(ce).mergePullRequest(t.owner,t.repo,$.number,l,{sha:M,title:`${s} (#${$.number})`}):{merged:!1,reason:"no GitHub token applies to this repo"};Ee.merged?g("info",`PR #${$.number} merged`):(g("warn",`Auto-merge did not go through - ${Ee.reason}. The PR stays open.`),await v.addComment(s,`**Allwright:** the work is done and the PR is open, but auto-merge did not go through - ${Ee.reason}
617
633
 
618
- PR: ${j.url}`))}await $c({jira:v,issueKey:s},te,g),C("succeeded",{...h,prUrl:j.url,headSha:N,resultSummary:nr(z?.trim()||L),retryAvailable:!1,...n.failedTests!==void 0?{failedTests:n.failedTests}:{}}),g("info",`Run succeeded \xB7 ${j.url} \xB7 $${h.costUsd.toFixed(4)}`)}}async function $c(n,e,t){let r=null;if(e.jiraTransition)try{await n.jira.transitionByName(e.issueKey,e.jiraTransition)?t("info",`Jira transition "${e.jiraTransition}" applied`):(r=`no transition named "${e.jiraTransition}" is available from this ticket's current status - the PR is fine, but move the ticket manually`,t("warn",r))}catch(s){r=`Jira transition failed: ${s instanceof Error?s.message:s}`,t("warn",r)}return await n.jira.addComment(e.issueKey,`**Allwright: implementation complete.**
634
+ PR: ${$.url}`))}let ne=(pe()??B).repos[A]?.path;ne&&Ts(ne,s)&&rt(ne,{issueKey:s,runId:r,title:"shipped after earlier failure",detail:`PR ${$.url} merged/opened straight-through.`}),await qc({jira:v,issueKey:s},te,g),x("succeeded",{...h,prUrl:$.url,headSha:M,resultSummary:ir(K?.trim()||D),retryAvailable:!1,...n.failedTests!==void 0?{failedTests:n.failedTests}:{},...n.testsPassed!==void 0?{testsPassed:n.testsPassed}:{},...n.testsTotal!==void 0?{testsTotal:n.testsTotal}:{},...n.goLiveDraft!==void 0?{goLiveDraft:n.goLiveDraft}:{}}),g("info",`Run succeeded \xB7 ${$.url} \xB7 $${h.costUsd.toFixed(4)}`)}}async function qc(n,e,t){let r=null;if(e.jiraTransition)try{await n.jira.transitionByName(e.issueKey,e.jiraTransition)?t("info",`Jira transition "${e.jiraTransition}" applied`):(r=`no transition named "${e.jiraTransition}" is available from this ticket's current status - the PR is fine, but move the ticket manually`,t("warn",r))}catch(s){r=`Jira transition failed: ${s instanceof Error?s.message:s}`,t("warn",r)}return await n.jira.addComment(e.issueKey,`**Allwright: implementation complete.**
619
635
 
620
636
  PR: ${e.prUrl}`+(r?`
621
637
 
622
638
  Note: ${r}`:"")+`
623
639
 
624
- (run \`${e.runId}\`)`),await n.jira.editLabels(e.issueKey,{add:[e.doneLabel],remove:[ze.NEEDS_INPUT_LABEL]}),r}async function ks(n,e,t){let r=Kr(e);if(!r){y.warn(`run.approved for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:s,setStatus:i}=Oc(n,e);try{let o=Te(me()??n.cfg,r.repoName);if(!o)throw new Error("GitHub token missing on this runner");let l=new xe(o);s("info",`Approval received for ${r.issueKey} - verifying PR state`);let u=await l.getPullRequest(r.owner,r.repo,r.prNumber);if(!u)throw new Error(`PR #${r.prNumber} no longer exists on GitHub`);if(u.state==="closed"&&!u.merged)throw new Error(`PR #${r.prNumber} was closed on GitHub without merging`);let c=t??r.headSha;if(u.state==="open"&&u.headSha!==c){let f=`PR #${r.prNumber} changed since review started (${c.slice(0,7)} \u2192 ${u.headSha.slice(0,7)}) - approval not applied. Re-review the PR and approve again.`;s("warn",f),await n.jiraFor(r.repoName??"").addComment(r.issueKey,`**Allwright:** ${f}`),i("awaiting_approval",{prUrl:r.prUrl,headSha:u.headSha,resultSummary:f});return}if(r.mergeOnApprove&&u.state==="open"&&!u.merged){s("info",`Merging PR #${r.prNumber} (${r.mergeMethod})`);let f=await l.mergePullRequest(r.owner,r.repo,r.prNumber,r.mergeMethod,{sha:c,title:`${r.issueKey} (#${r.prNumber})`});if(!f.merged){let p=`Approved, but the merge did not go through - ${f.reason}`;s("warn",p),await n.jiraFor(r.repoName??"").addComment(r.issueKey,`**Allwright:** ${p}
640
+ (run \`${e.runId}\`)`),await n.jira.editLabels(e.issueKey,{add:[e.doneLabel],remove:[Le.NEEDS_INPUT_LABEL]}),r}async function Rs(n,e,t){let r=Vr(e);if(!r){y.warn(`run.approved for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:s,setStatus:i}=Kc(n,e);try{let o=Te(pe()??n.cfg,r.repoName);if(!o)throw new Error("GitHub token missing on this runner");let l=new xe(o);s("info",`Approval received for ${r.issueKey} - verifying PR state`);let u=await l.getPullRequest(r.owner,r.repo,r.prNumber);if(!u)throw new Error(`PR #${r.prNumber} no longer exists on GitHub`);if(u.state==="closed"&&!u.merged)throw new Error(`PR #${r.prNumber} was closed on GitHub without merging`);let c=t??r.headSha;if(u.state==="open"&&u.headSha!==c){let f=`PR #${r.prNumber} changed since review started (${c.slice(0,7)} \u2192 ${u.headSha.slice(0,7)}) - approval not applied. Re-review the PR and approve again.`;s("warn",f),await n.jiraFor(r.repoName??"").addComment(r.issueKey,`**Allwright:** ${f}`),i("awaiting_approval",{prUrl:r.prUrl,headSha:u.headSha,resultSummary:f});return}if(r.mergeOnApprove&&u.state==="open"&&!u.merged){s("info",`Merging PR #${r.prNumber} (${r.mergeMethod})`);let f=await l.mergePullRequest(r.owner,r.repo,r.prNumber,r.mergeMethod,{sha:c,title:`${r.issueKey} (#${r.prNumber})`});if(!f.merged){let p=`Approved, but the merge did not go through - ${f.reason}`;s("warn",p),await n.jiraFor(r.repoName??"").addComment(r.issueKey,`**Allwright:** ${p}
625
641
 
626
- PR: ${r.prUrl}`),i("awaiting_approval",{prUrl:r.prUrl,headSha:u.headSha,resultSummary:p});return}s("info",`PR #${r.prNumber} merged`)}await $c({jira:n.jiraFor(r.repoName??""),issueKey:r.issueKey},r,s),i("succeeded",{prUrl:r.prUrl}),s("info","Run completed after approval"),er(e)}catch(o){let l=o instanceof Error?o.message:String(o);s("error",`Approval handling failed: ${l}`),await Nc(n,r,l),i("failed",{error:l}),er(e)}}async function Pc(n,e){let t=Kr(e);if(!t){y.warn(`run.rejected for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:r,setStatus:s}=Oc(n,e);try{let i=Te(me()??n.cfg,t.repoName);if(!i)throw new Error("GitHub token missing on this runner");let o=new xe(i);r("info",`Rejection received for ${t.issueKey} - closing PR #${t.prNumber}`);let l=await o.getPullRequest(t.owner,t.repo,t.prNumber);l&&l.state==="open"&&await o.closePullRequest(t.owner,t.repo,t.prNumber),l?.merged||await o.deleteBranch(t.owner,t.repo,t.branch),await n.jiraFor(t.repoName??"").addComment(t.issueKey,`**Allwright: changes rejected.**
642
+ PR: ${r.prUrl}`),i("awaiting_approval",{prUrl:r.prUrl,headSha:u.headSha,resultSummary:p});return}s("info",`PR #${r.prNumber} merged`)}{let f=(pe()??n.cfg).repos[r.repoName??""]?.path;f&&Ts(f,r.issueKey)&&rt(f,{issueKey:r.issueKey,runId:e,title:"shipped after earlier failure",detail:`PR ${r.prUrl} approved and completed.`})}await qc({jira:n.jiraFor(r.repoName??""),issueKey:r.issueKey},r,s),i("succeeded",{prUrl:r.prUrl}),s("info","Run completed after approval"),rr(e)}catch(o){let l=o instanceof Error?o.message:String(o);s("error",`Approval handling failed: ${l}`),await Zc(n,r,l),i("failed",{error:l}),rr(e)}}async function Fc(n,e){let t=Vr(e);if(!t){y.warn(`run.rejected for ${e}: no pending entry (already processed?) - ignoring`);return}let{emit:r,setStatus:s}=Kc(n,e);try{let i=Te(pe()??n.cfg,t.repoName);if(!i)throw new Error("GitHub token missing on this runner");let o=new xe(i);r("info",`Rejection received for ${t.issueKey} - closing PR #${t.prNumber}`);let l=await o.getPullRequest(t.owner,t.repo,t.prNumber);l&&l.state==="open"&&await o.closePullRequest(t.owner,t.repo,t.prNumber),l?.merged||await o.deleteBranch(t.owner,t.repo,t.branch),await n.jiraFor(t.repoName??"").addComment(t.issueKey,`**Allwright: changes rejected.**
627
643
 
628
- The pull request was closed and the branch deleted. This ticket is labeled \`${t.failedLabel}\`; remove the label to try again. (run \`${t.runId}\`)`),await n.jiraFor(t.repoName??"").editLabels(t.issueKey,{add:[t.failedLabel]}),s("failed",{error:"rejected by user"}),r("info","PR closed, branch deleted, ticket labeled"),er(e)}catch(i){let o=i instanceof Error?i.message:String(i);r("error",`Rejection handling failed: ${o}`),await Nc(n,t,o),s("failed",{error:o}),er(e)}}async function jc(n,e){let t=ki(e);if(!t){y.warn(`run.retryPush for ${e}: no retry record (already pushed, or invalidated?)`);let{emit:l,setStatus:u,sendUsage:c}=tr(e,n.transport,1e5);l("error","Retry push requested, but this runner holds no retry record for the run - it was already used or never saved. Re-run the ticket instead."),u("failed",{retryAvailable:!1});return}let{emit:r,setStatus:s,sendUsage:i,nextSeq:o}=tr(e,n.transport,t.nextLogSeq);try{let l=await hi(t.baseRepoPath,t.branch);if(l!==t.headSha){r("error",`Retry push aborted: branch ${t.branch} no longer holds the commit this run produced (expected ${t.headSha.slice(0,7)}, ${l?`found ${l.slice(0,7)}`:"the branch is gone"}) - a newer run has likely reused the branch. Re-run the ticket instead.`),pa(e),s("failed",{retryAvailable:!1});return}let u=await Vn(t.baseRepoPath),c=et(u);if(!c)throw new Error(`origin "${u}" is not a GitHub remote`);r("info",`Retry push for ${t.issueKey}: branch ${t.branch} at ${t.headSha.slice(0,7)}`);let f=n.jiraFor(t.repoName);await Ac({gitDir:t.baseRepoPath,ownerRepo:c,runId:t.runId,issueKey:t.issueKey,issueSummary:t.issueSummary,branch:t.branch,baseBranch:t.baseBranch,jiraTransition:t.jiraTransition,jiraTransitionOnMerge:t.jiraTransitionOnMerge,requireApproval:t.requireApproval,mergeOnApprove:t.mergeOnApprove??!1,mergeMethod:t.mergeMethod??"squash",autoMerge:t.autoMerge??!1,doneLabel:t.doneLabel,failedLabel:t.failedLabel,repoName:t.repoName,jira:f,cfg:me()??n.cfg,actorEmail:t.actorEmail,summary:t.resultSummary,prSummary:t.prSummary||void 0,cost:{costUsd:t.costUsd},emit:r,setStatus:s}),pa(e),await f.editLabels(t.issueKey,{remove:[t.failedLabel]}).catch(()=>{})}catch(l){let u=l instanceof Error?l.message:String(l);r("error",`Retry push failed: ${u}`),_i({...t,nextLogSeq:o()}),s("failed",{error:u,retryAvailable:!0})}}function Oc(n,e){let t=1e5;return{emit:(i,o)=>{n.transport.send({type:"run.log",runId:e,seq:t++,ts:new Date().toISOString(),level:i,message:o}),i!=="agent"&&y.info(`[run ${e}] ${o}`)},setStatus:(i,o={})=>{n.transport.send({type:"run.status",runId:e,status:i,...o})}}}async function Nc(n,e,t){try{await n.jiraFor(e.repoName??"").addComment(e.issueKey,`**Allwright could not complete the approval decision.**
644
+ The pull request was closed and the branch deleted. This ticket is labeled \`${t.failedLabel}\`; remove the label to try again. (run \`${t.runId}\`)`),await n.jiraFor(t.repoName??"").editLabels(t.issueKey,{add:[t.failedLabel]}),s("failed",{error:"rejected by user"}),r("info","PR closed, branch deleted, ticket labeled"),rr(e)}catch(i){let o=i instanceof Error?i.message:String(i);r("error",`Rejection handling failed: ${o}`),await Zc(n,t,o),s("failed",{error:o}),rr(e)}}async function Bc(n,e){let t=Ci(e);if(!t){y.warn(`run.retryPush for ${e}: no retry record (already pushed, or invalidated?)`);let{emit:l,setStatus:u,sendUsage:c}=sr(e,n.transport,1e5);l("error","Retry push requested, but this runner holds no retry record for the run - it was already used or never saved. Re-run the ticket instead."),u("failed",{retryAvailable:!1});return}let{emit:r,setStatus:s,sendUsage:i,nextSeq:o}=sr(e,n.transport,t.nextLogSeq);try{let l=await gi(t.baseRepoPath,t.branch);if(l!==t.headSha){r("error",`Retry push aborted: branch ${t.branch} no longer holds the commit this run produced (expected ${t.headSha.slice(0,7)}, ${l?`found ${l.slice(0,7)}`:"the branch is gone"}) - a newer run has likely reused the branch. Re-run the ticket instead.`),_a(e),s("failed",{retryAvailable:!1});return}let u=await Yn(t.baseRepoPath),c=nt(u);if(!c)throw new Error(`origin "${u}" is not a GitHub remote`);r("info",`Retry push for ${t.issueKey}: branch ${t.branch} at ${t.headSha.slice(0,7)}`);let f=n.jiraFor(t.repoName);await Uc({gitDir:t.baseRepoPath,ownerRepo:c,runId:t.runId,issueKey:t.issueKey,issueSummary:t.issueSummary,branch:t.branch,baseBranch:t.baseBranch,jiraTransition:t.jiraTransition,jiraTransitionOnMerge:t.jiraTransitionOnMerge,requireApproval:t.requireApproval,mergeOnApprove:t.mergeOnApprove??!1,mergeMethod:t.mergeMethod??"squash",autoMerge:t.autoMerge??!1,doneLabel:t.doneLabel,failedLabel:t.failedLabel,repoName:t.repoName,jira:f,cfg:pe()??n.cfg,actorEmail:t.actorEmail,summary:t.resultSummary,prSummary:t.prSummary||void 0,cost:{costUsd:t.costUsd},emit:r,setStatus:s}),_a(e),await f.editLabels(t.issueKey,{remove:[t.failedLabel]}).catch(()=>{})}catch(l){let u=l instanceof Error?l.message:String(l);r("error",`Retry push failed: ${u}`),xi({...t,nextLogSeq:o()}),s("failed",{error:u,retryAvailable:!0})}}function Kc(n,e){let t=1e5;return{emit:(i,o)=>{n.transport.send({type:"run.log",runId:e,seq:t++,ts:new Date().toISOString(),level:i,message:o}),i!=="agent"&&y.info(`[run ${e}] ${o}`)},setStatus:(i,o={})=>{n.transport.send({type:"run.status",runId:e,status:i,...o})}}}async function Zc(n,e,t){try{await n.jiraFor(e.repoName??"").addComment(e.issueKey,`**Allwright could not complete the approval decision.**
629
645
 
630
646
  Error: ${t.slice(0,800)}
631
647
 
632
648
  PR: ${e.prUrl}
633
- (run \`${e.runId}\`)`),await n.jiraFor(e.repoName??"").editLabels(e.issueKey,{add:[e.failedLabel]})}catch(r){y.error(`could not post decision failure to ${e.issueKey}: ${r}`)}}function Ss(n){if(!n.length)return"(no comments)";let e=6e4,t=n.map(i=>`${i.author} (${i.created}):
649
+ (run \`${e.runId}\`)`),await n.jiraFor(e.repoName??"").editLabels(e.issueKey,{add:[e.failedLabel]})}catch(r){y.error(`could not post decision failure to ${e.issueKey}: ${r}`)}}function Es(n){if(!n.length)return"(no comments)";let e=6e4,t=n.map(i=>`${i.author} (${i.created}):
634
650
  ${i.body}`),r=[],s=0;for(let i=t.length-1;i>=0;i--){if(s+=t[i].length+6,s>e){r.unshift(`(\u2026 ${i+1} earlier comment(s) omitted for length \u2026)`);break}r.unshift(t[i])}return r.join(`
635
651
  ---
636
- `)}function Mc(n){return`The ticket author replied:
652
+ `)}function Gc(n){return`The ticket author replied:
637
653
 
638
654
  ${n}
639
655
 
640
- Continue from where you left off now that you have this information. If you are still missing what you need, ask again the same way as before (the ${ze.NEEDS_INPUT_MARKER} marker).`}function Ts(n){let e=n.trim(),t=e.split(`
641
- `,1)[0].trim(),r=o=>o.replace(/[^a-z]/gi,"").toUpperCase();if(r(t)!==r(ze.NEEDS_INPUT_MARKER))return null;let s=e.indexOf(`
642
- `);return s<0?null:e.slice(s+1).trim()||null}async function Ei(n,e,t,r,s){t("info",`Claude needs more information - posting questions to ${n.issueKey}`),await n.jira.addComment(n.issueKey,`**${ze.NEEDS_INPUT_COMMENT_MARKER} before it can continue.**
656
+ Continue from where you left off now that you have this information. If you are still missing what you need, ask again the same way as before (the ${Le.NEEDS_INPUT_MARKER} marker).`}function As(n){let e=n.trim(),t=e.split(`
657
+ `,1)[0].trim(),r=o=>o.replace(/[^a-z]/gi,"").toUpperCase();if(r(t)!==r(Le.NEEDS_INPUT_MARKER))return null;let s=e.indexOf(`
658
+ `);return s<0?null:e.slice(s+1).trim()||null}async function ji(n,e,t,r,s){t("info",`Claude needs more information - posting questions to ${n.issueKey}`),await n.jira.addComment(n.issueKey,`**${Le.NEEDS_INPUT_COMMENT_MARKER} before it can continue.**
643
659
 
644
660
  ${e}
645
661
 
646
- Reply with your answers in a comment on this ticket - this run will pick up right where it left off, automatically, once you do. (run \`${n.runId}\`)`);let i=new Date().toISOString();await n.jira.editLabels(n.issueKey,{add:[ze.NEEDS_INPUT_LABEL]}),yc({runId:n.runId,issueKey:n.issueKey,kind:n.kind,mergeOnApprove:n.mergeOnApprove??!1,mergeMethod:n.mergeMethod??"squash",autoMerge:n.autoMerge??!1,repoPath:n.repoPath,sessionId:n.sessionId,doneLabel:n.doneLabel,failedLabel:n.failedLabel,timeoutSeconds:n.timeoutSeconds,createdAt:n.createdAt??i,questionsPostedAt:i,rounds:n.rounds,nextLogSeq:n.nextLogSeq,baseRepoPath:n.baseRepoPath,repoName:n.repoName,branch:n.branch,baseBranch:n.baseBranch,jiraTransition:n.jiraTransition,jiraTransitionOnMerge:n.jiraTransitionOnMerge,requireApproval:n.requireApproval,maxTurns:n.maxTurns,runTests:n.runTests??!0,issueSummary:n.issueSummary??"",claudeConfigDir:n.claudeConfigDir,agent:n.agent,model:n.model,actorEmail:n.actorEmail}),r("needs_input",{...s,resultSummary:nr(e)}),t("info",`Waiting for a reply on ${n.issueKey} (label "${ze.NEEDS_INPUT_LABEL}")`)}async function zc(n,e,t,r,s){let i=`Claude asked for clarification ${e.rounds} times without reaching a result - giving up. Answer more completely and re-trigger manually if you want another attempt.`;t("error",i),await vt(n,e.issueKey,e.runId,e.failedLabel,i),yt(e.runId),r("failed",{error:i,...s})}async function Gr(n,e){await vt(n.jira,n.issueKey,n.runId,n.rule.trigger.failedLabel,e)}async function vt(n,e,t,r,s){try{await n.addComment(e,`**Allwright run failed.**
662
+ Reply with your answers in a comment on this ticket - this run will pick up right where it left off, automatically, once you do. (run \`${n.runId}\`)`);let i=new Date().toISOString();await n.jira.editLabels(n.issueKey,{add:[Le.NEEDS_INPUT_LABEL]}),Cc({runId:n.runId,issueKey:n.issueKey,kind:n.kind,mergeOnApprove:n.mergeOnApprove??!1,mergeMethod:n.mergeMethod??"squash",autoMerge:n.autoMerge??!1,repoPath:n.repoPath,sessionId:n.sessionId,doneLabel:n.doneLabel,failedLabel:n.failedLabel,timeoutSeconds:n.timeoutSeconds,createdAt:n.createdAt??i,questionsPostedAt:i,rounds:n.rounds,nextLogSeq:n.nextLogSeq,baseRepoPath:n.baseRepoPath,repoName:n.repoName,branch:n.branch,baseBranch:n.baseBranch,jiraTransition:n.jiraTransition,jiraTransitionOnMerge:n.jiraTransitionOnMerge,requireApproval:n.requireApproval,maxTurns:n.maxTurns,runTests:n.runTests??!0,issueSummary:n.issueSummary??"",claudeConfigDir:n.claudeConfigDir,agent:n.agent,model:n.model,actorEmail:n.actorEmail}),r("needs_input",{...s,resultSummary:ir(e)}),t("info",`Waiting for a reply on ${n.issueKey} (label "${Le.NEEDS_INPUT_LABEL}")`)}async function Hc(n,e,t,r,s){let i=`Claude asked for clarification ${e.rounds} times without reaching a result - giving up. Answer more completely and re-trigger manually if you want another attempt.`;t("error",i),await wt(n,e.issueKey,e.runId,e.failedLabel,i),bt(e.runId),r("failed",{error:i,...s})}async function Jr(n,e){await wt(n.jira,n.issueKey,n.runId,n.rule.trigger.failedLabel,e)}async function wt(n,e,t,r,s){try{await n.addComment(e,`**Allwright run failed.**
647
663
 
648
664
  Error: ${s.slice(0,800)}
649
665
 
650
- This ticket has been labeled \`${r}\` and will not be retried automatically. To retry, fix the cause and remove the \`${r}\` label. (run \`${t}\`)`),await n.editLabels(e,{add:[r],remove:[ze.NEEDS_INPUT_LABEL]})}catch(i){y.error(`could not post failure comment to ${e}: ${i}`)}}function wc(n){let e=n.split(/\n##\s*PR summary\s*\n/i)[0],t=/##\s*Summary of changes\s*\n([\s\S]*)$/i.exec(e);return(t?t[1]:e).trim().slice(0,8e3)||"(no summary provided)"}function ga(n){let e=/##\s*PR summary\s*\n([\s\S]*?)(?=\n##\s|$)/i.exec(n),t=e?e[1].trim():"";return t?t.slice(0,2e3):null}function nr(n){for(let e of n.split(`
651
- `)){let t=e.replace(/^#+\s*/,"").trim();if(t.length>10)return t.slice(0,200)}return n.slice(0,200)}var sr=R(require("node:fs"),1),rr=R(require("node:path"),1),ir=require("node:child_process"),_a=R(require("node:readline"),1),ka=require("node:crypto"),or=R(we(),1);var Bc=R(we(),1);pt();nt();Wn();var Dc=4e3,Pg=4e3;function Sa(n){let e=0;return{emit:(s,i)=>{n.transport.send({type:"run.log",runId:n.runId,seq:e++,ts:new Date().toISOString(),level:s,message:i.slice(0,Pg)}),s!=="agent"&&y.info(`[deploy ${n.runId}] ${i}`)},setStatus:(s,i={})=>{n.transport.send({type:"run.status",runId:n.runId,status:s,...i})}}}async function Ai(n){let{emit:e,setStatus:t}=Sa(n),r=n.environment;try{let s=jg(n);if(s){e("error",s),await st(n,`**Allwright could not deploy to \`${r.name}\`.**
666
+ This ticket has been labeled \`${r}\` and will not be retried automatically. To retry, fix the cause and remove the \`${r}\` label. (run \`${t}\`)`),await n.editLabels(e,{add:[r],remove:[Le.NEEDS_INPUT_LABEL]})}catch(i){y.error(`could not post failure comment to ${e}: ${i}`)}}function Ac(n){let e=n.split(/\n##\s*(?:PR summary|Go-live draft)\s*\n/i)[0],t=/##\s*Summary of changes\s*\n([\s\S]*)$/i.exec(e);return(t?t[1]:e).trim().slice(0,8e3)||"(no summary provided)"}function Sa(n){let e=/##\s*PR summary\s*\n([\s\S]*?)(?=\n##\s|$)/i.exec(n),t=e?e[1].trim():"";return t?t.slice(0,2e3):null}function ir(n){for(let e of n.split(`
667
+ `)){let t=e.replace(/^#+\s*/,"").trim();if(t.length>10)return t.slice(0,200)}return n.slice(0,200)}var ar=R(require("node:fs"),1);var or=R(require("node:path"),1),lr=require("node:child_process"),Ra=R(require("node:readline"),1),Ea=require("node:crypto"),ur=R(we(),1);var Qc=R(we(),1);gt();it();Xn();var Vc=4e3,Gg=4e3;function Aa(n){let e=0;return{emit:(s,i)=>{n.transport.send({type:"run.log",runId:n.runId,seq:e++,ts:new Date().toISOString(),level:s,message:i.slice(0,Gg)}),s!=="agent"&&y.info(`[deploy ${n.runId}] ${i}`)},setStatus:(s,i={})=>{n.transport.send({type:"run.status",runId:n.runId,status:s,...i})}}}async function Oi(n){let{emit:e,setStatus:t}=Aa(n),r=n.environment;try{let s=Hg(n);if(s){e("error",s),await at(n,`**Allwright could not deploy to \`${r.name}\`.**
652
668
 
653
- ${s}`),t("failed",{error:s});return}if(r.requireApproval){gc({runId:n.runId,issueKey:n.issueKey,issueSummary:n.issueSummary,projectId:n.project.id,repoName:n.project.repoName,environmentName:r.name,requestedBy:n.requestedBy,createdAt:new Date().toISOString()}),e("info",`Deploy to "${r.name}" is waiting for approval on the dashboard - no step has run yet`),await st(n,`**Allwright: deploy to \`${r.name}\` needs approval.**
669
+ ${s}`),t("failed",{error:s});return}if(r.requireApproval){xc({runId:n.runId,issueKey:n.issueKey,issueSummary:n.issueSummary,projectId:n.project.id,repoName:n.project.repoName,environmentName:r.name,requestedBy:n.requestedBy,createdAt:new Date().toISOString()}),e("info",`Deploy to "${r.name}" is waiting for approval on the dashboard - no step has run yet`),await at(n,`**Allwright: deploy to \`${r.name}\` needs approval.**
654
670
 
655
- ${n.requestedBy?`Requested by ${n.requestedBy}. `:""}Nothing has been executed yet. Approve it on the Allwright dashboard to run the ${r.steps.length} deploy step(s), or reject to cancel. (run \`${n.runId}\`)`),t("awaiting_approval",{resultSummary:`Awaiting approval to deploy ${n.issueKey} to ${r.name}`});return}await Kc(n,e,t)}catch(s){let i=s instanceof Error?s.message:String(s);e("error",`Deploy failed: ${i}`),await st(n,`**Allwright deploy to \`${r.name}\` failed.**
671
+ ${n.requestedBy?`Requested by ${n.requestedBy}. `:""}Nothing has been executed yet. Approve it on the Allwright dashboard to run the ${r.steps.length} deploy step(s), or reject to cancel. (run \`${n.runId}\`)`),t("awaiting_approval",{resultSummary:`Awaiting approval to deploy ${n.issueKey} to ${r.name}`});return}await ed(n,e,t)}catch(s){let i=s instanceof Error?s.message:String(s);e("error",`Deploy failed: ${i}`),await at(n,`**Allwright deploy to \`${r.name}\` failed.**
656
672
 
657
673
  ${i.slice(0,800)}
658
674
 
659
- (run \`${n.runId}\`)`),t("failed",{error:i})}}function jg(n){let e=n.environment;if(!n.cfg.deploy.enabled)return"deployments are turned off on this runner. Deploy steps are shell commands, so they stay disabled until someone with access to this machine runs `allwright deploy enable`.";if(!e.steps.length)return`environment "${e.name}" has no deploy steps configured - add them in the dashboard first`;if(e.promotionMode==="merge_and_deploy"&&!e.branch)return`environment "${e.name}" is set to merge-and-deploy but has no branch configured`;if(e.useDedicatedCheckout&&!e.branch)return`environment "${e.name}" wants a dedicated checkout but has no branch configured`;let t=Cn(n.cfg,n.project.repoName,e.name),r=e.requiredSecrets.filter(s=>!t[s]&&!process.env[s]);return r.length?`missing deploy secret(s) on this runner: ${r.join(", ")}. Set them with: allwright env set "${n.project.repoName}" "${e.name}" ${r[0]}=...`:null}async function Kc(n,e,t){let r=n.environment,s=Cn(n.cfg,n.project.repoName,r.name),i=Dg(Object.values(s)),o=Date.now();if(t("running"),e("info",`Deploying ${n.issueKey} to "${r.name}"`+(n.requestedBy?` (requested by ${n.requestedBy})`:"")+` - ${r.steps.length} step(s), ${r.timeoutSeconds}s budget`),r.auditBeforeDeploy){e("info",`Pre-deploy ${r.auditBeforeDeploy} audit starting (advisory - will not block)`);try{let A=tt(n.cfg,n.project,"assist"),v="error"in A?{ok:!1,error:A.error}:await Fr({projectId:n.project.id,repoPath:n.repoPath,role:r.auditBeforeDeploy,scope:{kind:"repo",ref:""},model:"",agent:A,jira:n.jira});if(!v.ok)e("warn",`Pre-deploy audit could not run: ${v.error} - deploying anyway (advisory)`);else if(!v.audit.findings.length)e("info","Pre-deploy audit: no findings \u2713");else{let Z={};for(let M of v.audit.findings)Z[M.severity]=(Z[M.severity]??0)+1;e("warn",`Pre-deploy audit: ${v.audit.findings.length} finding(s) (`+Object.entries(Z).map(([M,L])=>`${L} ${M}`).join(", ")+") - full report on the Audits page. Deploying anyway (advisory).");for(let M of v.audit.findings.slice(0,5))e("warn",` [${M.severity}] ${M.title} - ${M.evidence[0]?.file??""}`)}}catch(A){e("warn",`Pre-deploy audit crashed: ${A instanceof Error?A.message:String(A)} - deploying anyway`)}}if(r.requireSyncCheck){if(!r.previousEnvBranch||!r.branch){let v=r.branch?`"${r.name}" requires a branch sync check, but no earlier stage in the pipeline has a branch to compare against. Check the pipeline order on the Environments page (was "${r.name}" moved to the top?), or turn the check off.`:`"${r.name}" requires a branch sync check but has no branch set - set it, or turn the check off`;e("error",v),await st(n,`**Allwright refused to deploy to \`${r.name}\`.**
675
+ (run \`${n.runId}\`)`),t("failed",{error:i})}}function Hg(n){let e=n.environment;if(!n.cfg.deploy.enabled)return"deployments are turned off on this runner. Deploy steps are shell commands, so they stay disabled until someone with access to this machine runs `allwright deploy enable`.";if(!e.steps.length)return`environment "${e.name}" has no deploy steps configured - add them in the dashboard first`;if(e.promotionMode==="merge_and_deploy"&&!e.branch)return`environment "${e.name}" is set to merge-and-deploy but has no branch configured`;if(e.useDedicatedCheckout&&!e.branch)return`environment "${e.name}" wants a dedicated checkout but has no branch configured`;let t=En(n.cfg,n.project.repoName,e.name),r=e.requiredSecrets.filter(s=>!t[s]&&!process.env[s]);return r.length?`missing deploy secret(s) on this runner: ${r.join(", ")}. Set them with: allwright env set "${n.project.repoName}" "${e.name}" ${r[0]}=...`:null}async function ed(n,e,t){let r=n.environment,s=En(n.cfg,n.project.repoName,r.name),i=Xg(Object.values(s)),o=Date.now();if(t("running"),e("info",`Deploying ${n.issueKey} to "${r.name}"`+(n.requestedBy?` (requested by ${n.requestedBy})`:"")+` - ${r.steps.length} step(s), ${r.timeoutSeconds}s budget`),r.auditBeforeDeploy){e("info",`Pre-deploy ${r.auditBeforeDeploy} audit starting (advisory - will not block)`);try{let A=st(n.cfg,n.project,"assist"),v="error"in A?{ok:!1,error:A.error}:await Gr({projectId:n.project.id,repoPath:n.repoPath,role:r.auditBeforeDeploy,scope:{kind:"repo",ref:""},model:"",agent:A,jira:n.jira});if(!v.ok)e("warn",`Pre-deploy audit could not run: ${v.error} - deploying anyway (advisory)`);else if(!v.audit.findings.length)e("info","Pre-deploy audit: no findings \u2713");else{let B={};for(let N of v.audit.findings)B[N.severity]=(B[N.severity]??0)+1;e("warn",`Pre-deploy audit: ${v.audit.findings.length} finding(s) (`+Object.entries(B).map(([N,D])=>`${D} ${N}`).join(", ")+") - full report on the Audits page. Deploying anyway (advisory).");for(let N of v.audit.findings.slice(0,5))e("warn",` [${N.severity}] ${N.title} - ${N.evidence[0]?.file??""}`)}}catch(A){e("warn",`Pre-deploy audit crashed: ${A instanceof Error?A.message:String(A)} - deploying anyway`)}}if(r.requireSyncCheck){if(!r.previousEnvBranch||!r.branch){let v=r.branch?`"${r.name}" requires a branch sync check, but no earlier stage in the pipeline has a branch to compare against. Check the pipeline order on the Environments page (was "${r.name}" moved to the top?), or turn the check off.`:`"${r.name}" requires a branch sync check but has no branch set - set it, or turn the check off`;e("error",v),await at(n,`**Allwright refused to deploy to \`${r.name}\`.**
660
676
 
661
677
  ${v}
662
678
 
663
- (run \`${n.runId}\`)`),t("failed",{error:v,errorKind:"guard"});return}let A=await Ng(n,e);if(A){await st(n,A.comment),t("failed",{error:A.error,...A.guard?{errorKind:"guard"}:{}});return}}let l=n.repoPath;if(r.useDedicatedCheckout||r.promotionMode==="merge_and_deploy"?(e("info",`Preparing ${r.name} checkout at origin/${r.branch}`),l=await Uo({repoPath:n.repoPath,repoName:n.project.repoName,envName:r.name,branch:r.branch,attached:r.promotionMode==="merge_and_deploy"})):e("info",`No dedicated checkout for "${r.name}" - running the steps in the mapped checkout as it is`),r.promotionMode==="merge_and_deploy"){let A=jt(r.ticketBranchTemplate,{issueKey:n.issueKey});e("info",`Merging "${A}" into "${r.branch}"`);let v=await qo(l,A,`Deploy ${n.issueKey} to ${r.name}
679
+ (run \`${n.runId}\`)`),t("failed",{error:v,errorKind:"guard"});return}let A=await Wg(n,e);if(A){await at(n,A.comment),t("failed",{error:A.error,...A.guard?{errorKind:"guard"}:{}});return}}let l=n.repoPath;if(r.useDedicatedCheckout||r.promotionMode==="merge_and_deploy"?(e("info",`Preparing ${r.name} checkout at origin/${r.branch}`),l=await Zo({repoPath:n.repoPath,repoName:n.project.repoName,envName:r.name,branch:r.branch,attached:r.promotionMode==="merge_and_deploy"})):e("info",`No dedicated checkout for "${r.name}" - running the steps in the mapped checkout as it is`),r.promotionMode==="merge_and_deploy"){let A=zt(r.ticketBranchTemplate,{issueKey:n.issueKey});e("info",`Merging "${A}" into "${r.branch}"`);let v=await Go(l,A,`Deploy ${n.issueKey} to ${r.name}
664
680
 
665
- Allwright run ${n.runId}`);if(!v.ok){e("error",v.reason??"merge failed"),await st(n,`**Allwright deploy to \`${r.name}\` failed before running anything.**
681
+ Allwright run ${n.runId}`);if(!v.ok){e("error",v.reason??"merge failed"),await at(n,`**Allwright deploy to \`${r.name}\` failed before running anything.**
666
682
 
667
- ${v.reason}`),t("failed",{error:v.reason});return}v.alreadyMerged?e("info",`"${A}" is already in "${r.branch}" - nothing to merge`):(e("info",`Pushing "${r.branch}" to origin`),await Zo(l,r.branch))}let c=await He(l).catch(()=>"");c&&e("info",`Deploying commit ${c.slice(0,10)}`);let f=Mg(l,r.workdir),p={...process.env,...s,ALLWRIGHT_ENVIRONMENT:r.name,ALLWRIGHT_ISSUE_KEY:n.issueKey,ALLWRIGHT_RUN_ID:n.runId,ALLWRIGHT_DEPLOY_REF:c,ALLWRIGHT_BRANCH:r.branch,TICKETPILOT_ENVIRONMENT:r.name,TICKETPILOT_ISSUE_KEY:n.issueKey,TICKETPILOT_RUN_ID:n.runId,TICKETPILOT_DEPLOY_REF:c,TICKETPILOT_BRANCH:r.branch},b=0,w=r.timeoutSeconds*1e3;for(let[A,v]of r.steps.entries()){let Z=w-(Date.now()-o);if(Z<=0){let L=`deploy exceeded its ${r.timeoutSeconds}s budget before step ${A+1}`;e("error",L),await st(n,`**Allwright deploy to \`${r.name}\` timed out.**
683
+ ${v.reason}`),t("failed",{error:v.reason});return}v.alreadyMerged?e("info",`"${A}" is already in "${r.branch}" - nothing to merge`):(e("info",`Pushing "${r.branch}" to origin`),await Jo(l,r.branch))}let c=await Je(l).catch(()=>"");c&&e("info",`Deploying commit ${c.slice(0,10)}`);let f=Jg(l,r.workdir),p={...process.env,...s,ALLWRIGHT_ENVIRONMENT:r.name,ALLWRIGHT_ISSUE_KEY:n.issueKey,ALLWRIGHT_RUN_ID:n.runId,ALLWRIGHT_DEPLOY_REF:c,ALLWRIGHT_BRANCH:r.branch,TICKETPILOT_ENVIRONMENT:r.name,TICKETPILOT_ISSUE_KEY:n.issueKey,TICKETPILOT_RUN_ID:n.runId,TICKETPILOT_DEPLOY_REF:c,TICKETPILOT_BRANCH:r.branch},b=0,w=r.timeoutSeconds*1e3;for(let[A,v]of r.steps.entries()){let B=w-(Date.now()-o);if(B<=0){let D=`deploy exceeded its ${r.timeoutSeconds}s budget before step ${A+1}`;e("error",D),await at(n,`**Allwright deploy to \`${r.name}\` timed out.**
668
684
 
669
- ${L}`),t("timed_out",{error:L,deployedRef:c});return}e("info",`\u25B6 step ${A+1}/${r.steps.length}: ${v.name}`);let M=await zg({command:v.run,cwd:f,env:p,timeoutMs:Z,onLine:(L,z)=>{b++,b===Dc&&e("warn","(output truncated - deploy log limit reached)"),!(b>=Dc)&&e(L,i(z))}});if(M.timedOut){let L=`step "${v.name}" hit the ${r.timeoutSeconds}s deploy budget and was killed`;e("error",L),await st(n,`**Allwright deploy to \`${r.name}\` timed out.**
685
+ ${D}`),t("timed_out",{error:D,deployedRef:c});return}e("info",`\u25B6 step ${A+1}/${r.steps.length}: ${v.name}`);let N=await Yg({command:v.run,cwd:f,env:p,timeoutMs:B,onLine:(D,K)=>{b++,b===Vc&&e("warn","(output truncated - deploy log limit reached)"),!(b>=Vc)&&e(D,i(K))}});if(N.timedOut){let D=`step "${v.name}" hit the ${r.timeoutSeconds}s deploy budget and was killed`;e("error",D),await at(n,`**Allwright deploy to \`${r.name}\` timed out.**
670
686
 
671
- ${L}`),t("timed_out",{error:L,deployedRef:c});return}if(M.code!==0){if(v.continueOnError){e("warn",`step "${v.name}" exited ${M.code} - continuing (marked continue-on-error)`);continue}let L="";try{L=i(await No(l))}catch{}let z=`step ${A+1} "${v.name}" failed with exit code ${M.code}`+(M.tail?`: ${i(M.tail)}`:"")+(L?`
687
+ ${D}`),t("timed_out",{error:D,deployedRef:c});return}if(N.code!==0){if(v.continueOnError){e("warn",`step "${v.name}" exited ${N.code} - continuing (marked continue-on-error)`);continue}let D="";try{D=i(await Uo(l))}catch{}let K=`step ${A+1} "${v.name}" failed with exit code ${N.code}`+(N.tail?`: ${i(N.tail)}`:"")+(D?`
672
688
 
673
689
  Checkout at failure:
674
- ${L}`:"");e("error",z),await st(n,`**Allwright deploy to \`${r.name}\` failed.**
690
+ ${D}`:"");e("error",K),await at(n,`**Allwright deploy to \`${r.name}\` failed.**
675
691
 
676
- Step ${A+1} \`${v.name}\` exited ${M.code}.
692
+ Step ${A+1} \`${v.name}\` exited ${N.code}.
677
693
 
678
- `+(M.tail?`\`\`\`
679
- ${i(M.tail).slice(0,1200)}
694
+ `+(N.tail?`\`\`\`
695
+ ${i(N.tail).slice(0,1200)}
680
696
  \`\`\`
681
697
 
682
- `:"")+(L?`Checkout at failure:
698
+ `:"")+(D?`Checkout at failure:
683
699
  \`\`\`
684
- ${L.slice(0,800)}
700
+ ${D.slice(0,800)}
685
701
  \`\`\`
686
702
 
687
- `:"")+`Nothing after it ran. Full log is on the Allwright dashboard. (run \`${n.runId}\`)`),t("failed",{error:z.slice(0,1600),deployedRef:c});return}e("info",`\u2713 step ${A+1}/${r.steps.length}: ${v.name}`)}t("posting");let T=Math.round((Date.now()-o)/1e3);n.issueKey!==or.BRANCH_DEPLOY_ISSUE_KEY&&await st(n,`**Allwright deployed \`${n.issueKey}\` to \`${r.name}\`.**
703
+ `:"")+`Nothing after it ran. Full log is on the Allwright dashboard. (run \`${n.runId}\`)`),rt(n.repoPath,{issueKey:n.issueKey,runId:n.runId,title:`deploy to ${r.name} failed`,detail:`step ${A+1} "${v.name}" exit ${N.code}`+(N.tail?`
704
+ ${i(N.tail).slice(0,500)}`:"")}),t("failed",{error:K.slice(0,1600),deployedRef:c});return}e("info",`\u2713 step ${A+1}/${r.steps.length}: ${v.name}`)}t("posting");let T=Math.round((Date.now()-o)/1e3);n.issueKey!==ur.BRANCH_DEPLOY_ISSUE_KEY&&await at(n,`**Allwright deployed \`${n.issueKey}\` to \`${r.name}\`.**
688
705
 
689
706
  `+(c?`Commit: \`${c.slice(0,10)}\`${r.branch?` on \`${r.branch}\``:""}
690
707
  `:"")+`${r.steps.length} step(s) in ${T}s.`+(n.requestedBy?` Requested by ${n.requestedBy}.`:"")+`
691
708
 
692
- (run \`${n.runId}\`)`);let x=await Og(n,e,c);t("succeeded",{resultSummary:`Deployed to ${r.name}${c?` at ${c.slice(0,10)}`:""} in ${T}s`+(x!==null?` \xB7 ${x} ticket(s) moved to "${r.deployToColumn}"`:""),deployedRef:c}),e("info",`Deploy to "${r.name}" succeeded in ${T}s`)}async function Og(n,e,t){let r=n.environment;if(!r.deployFromColumn||!r.deployToColumn)return null;let s=new Date().toISOString().slice(0,10),i;try{i=await n.jira.search(`project = "${n.project.jiraProjectKey}" AND status = "${r.deployFromColumn}" ORDER BY updated ASC`,50)}catch(l){return e("warn",`deploy succeeded, but listing tickets in "${r.deployFromColumn}" failed: ${l instanceof Error?l.message:l} - move them by hand`),null}if(!i.length)return e("info",`No tickets in "${r.deployFromColumn}" to move`),0;e("info",`Moving ${i.length} ticket(s) from "${r.deployFromColumn}" to "${r.deployToColumn}"`);let o=0;for(let l of i)try{if(await n.jira.addComment(l.key,`**Allwright: deployed to \`${r.name}\` on ${s}.**
709
+ (run \`${n.runId}\`)`);let C=await Vg(n,e,c);n.project.goLiveIssueKey&&e("info",`Go-live checklist: this project keeps one on ${n.project.goLiveIssueKey} - review it before shipping to production`),Ts(n.repoPath,n.issueKey)&&rt(n.repoPath,{issueKey:n.issueKey,runId:n.runId,title:`deploy to ${r.name} succeeded after earlier failure`,detail:c?`commit ${c.slice(0,10)}`:void 0}),t("succeeded",{resultSummary:`Deployed to ${r.name}${c?` at ${c.slice(0,10)}`:""} in ${T}s`+(C!==null?` \xB7 ${C} ticket(s) moved to "${r.deployToColumn}"`:""),deployedRef:c}),e("info",`Deploy to "${r.name}" succeeded in ${T}s`)}async function Vg(n,e,t){let r=n.environment;if(!r.deployFromColumn||!r.deployToColumn)return null;let s=new Date().toISOString().slice(0,10),i;try{i=await n.jira.search(`project = "${n.project.jiraProjectKey}" AND status = "${r.deployFromColumn}" ORDER BY updated ASC`,50)}catch(l){return e("warn",`deploy succeeded, but listing tickets in "${r.deployFromColumn}" failed: ${l instanceof Error?l.message:l} - move them by hand`),null}if(!i.length)return e("info",`No tickets in "${r.deployFromColumn}" to move`),0;e("info",`Moving ${i.length} ticket(s) from "${r.deployFromColumn}" to "${r.deployToColumn}"`);let o=0;for(let l of i)try{if(await n.jira.addComment(l.key,`**Allwright: deployed to \`${r.name}\` on ${s}.**
693
710
 
694
711
  `+(t?`Commit: \`${t.slice(0,10)}\`${r.branch?` on \`${r.branch}\``:""}
695
- `:"")+(n.requestedBy?`Requested by ${n.requestedBy}. `:"")+`(run \`${n.runId}\`)`),!await n.jira.transitionByName(l.key,r.deployToColumn)){e("warn",`${l.key}: no workflow transition to "${r.deployToColumn}" from its current status - left in place`),await n.jira.addComment(l.key,`**Allwright could not move this ticket to \`${r.deployToColumn}\`** - no such transition from its current status. The deploy itself succeeded; move it by hand. (run \`${n.runId}\`)`).catch(()=>{});continue}o++,e("info",`\u2713 ${l.key} \u2192 "${r.deployToColumn}"`)}catch(u){e("warn",`${l.key}: sweep failed (${u instanceof Error?u.message:u}) - left in "${r.deployFromColumn}"`)}return e("info",`Moved ${o}/${i.length} ticket(s) to "${r.deployToColumn}"`),o}async function Ng(n,e){let t=n.environment,r=t.previousEnvBranch,s=(l,u=!1)=>({error:l,guard:u,comment:`**Allwright could not deploy \`${n.issueKey}\` to \`${t.name}\`.**
712
+ `:"")+(n.requestedBy?`Requested by ${n.requestedBy}. `:"")+`(run \`${n.runId}\`)`),!await n.jira.transitionByName(l.key,r.deployToColumn)){e("warn",`${l.key}: no workflow transition to "${r.deployToColumn}" from its current status - left in place`),await n.jira.addComment(l.key,`**Allwright could not move this ticket to \`${r.deployToColumn}\`** - no such transition from its current status. The deploy itself succeeded; move it by hand. (run \`${n.runId}\`)`).catch(()=>{});continue}o++,e("info",`\u2713 ${l.key} \u2192 "${r.deployToColumn}"`)}catch(u){e("warn",`${l.key}: sweep failed (${u instanceof Error?u.message:u}) - left in "${r.deployFromColumn}"`)}return e("info",`Moved ${o}/${i.length} ticket(s) to "${r.deployToColumn}"`),o}async function Wg(n,e){let t=n.environment,r=t.previousEnvBranch,s=(l,u=!1)=>({error:l,guard:u,comment:`**Allwright could not deploy \`${n.issueKey}\` to \`${t.name}\`.**
696
713
 
697
714
  ${l}
698
715
 
699
- (run \`${n.runId}\`)`});e("info",`Checking "${t.branch}" is in sync with "${r}" before deploying`);try{await nn(n.repoPath,r),await nn(n.repoPath,t.branch)}catch(l){return s(`sync check could not fetch branches: ${l instanceof Error?l.message:String(l)}`)}let i;try{i=await Go(n.repoPath,`origin/${r}`,`origin/${t.branch}`)}catch(l){return s(`sync check failed: ${l instanceof Error?l.message:String(l)}`)}if(!i)return e("info",`"${t.branch}" already matches "${r}" - continuing`),null;e("warn",`"${t.branch}" and "${r}" have diverged - opening a PR instead of deploying`);let o=Te(me()??n.cfg,n.project.repoName);if(!o)return s(`"${t.branch}" and "${r}" have diverged, and no GitHub token applies to this repo to open a PR. Run \`allwright github set-token\`, or merge them manually, then retry the deploy.`,!0);try{let l=await Vn(n.repoPath),u=et(l);if(!u)throw new Error(`could not parse a GitHub owner/repo from origin "${l}"`);let f=await new xe(o).createPullRequest(u.owner,u.repo,{title:`Sync ${t.name} (${t.branch}) with ${r}`,head:r,base:t.branch,body:`Allwright opened this automatically while trying to deploy \`${n.issueKey}\` to \`${t.name}\`: \`${t.branch}\` doesn't have everything that's on \`${r}\` yet, so deploying now would ship different code than what was validated there. Merge this PR, then retry the deploy.
716
+ (run \`${n.runId}\`)`});e("info",`Checking "${t.branch}" is in sync with "${r}" before deploying`);try{await sn(n.repoPath,r),await sn(n.repoPath,t.branch)}catch(l){return s(`sync check could not fetch branches: ${l instanceof Error?l.message:String(l)}`)}let i;try{i=await Yo(n.repoPath,`origin/${r}`,`origin/${t.branch}`)}catch(l){return s(`sync check failed: ${l instanceof Error?l.message:String(l)}`)}if(!i)return e("info",`"${t.branch}" already matches "${r}" - continuing`),null;e("warn",`"${t.branch}" and "${r}" have diverged - opening a PR instead of deploying`);let o=Te(pe()??n.cfg,n.project.repoName);if(!o)return s(`"${t.branch}" and "${r}" have diverged, and no GitHub token applies to this repo to open a PR. Run \`allwright github set-token\`, or merge them manually, then retry the deploy.`,!0);try{let l=await Yn(n.repoPath),u=nt(l);if(!u)throw new Error(`could not parse a GitHub owner/repo from origin "${l}"`);let f=await new xe(o).createPullRequest(u.owner,u.repo,{title:`Sync ${t.name} (${t.branch}) with ${r}`,head:r,base:t.branch,body:`Allwright opened this automatically while trying to deploy \`${n.issueKey}\` to \`${t.name}\`: \`${t.branch}\` doesn't have everything that's on \`${r}\` yet, so deploying now would ship different code than what was validated there. Merge this PR, then retry the deploy.
700
717
 
701
- (run \`${n.runId}\`)`});return s(`"${t.branch}" is not in sync with "${r}" - opened ${f.url} to catch it up. Merge that, then retry the deploy.`,!0)}catch(l){return s(`could not open a sync PR: ${l instanceof Error?l.message:String(l)}`)}}function Mg(n,e){if(!e.trim())return n;let t=rr.default.resolve(n,e),r=rr.default.relative(n,t);if(r.startsWith("..")||rr.default.isAbsolute(r))throw new Error(`working directory "${e}" is outside the repository checkout`);return t}function zg(n){return new Promise(e=>{let t=(0,ir.spawn)("bash",["-lc",n.command],{cwd:n.cwd,env:n.env,detached:!0,stdio:["ignore","pipe","pipe"]}),r=[],s=c=>{r.push(c),r.length>20&&r.shift()},i=!1,o=!1,l=c=>{i||(i=!0,clearTimeout(u),e({code:c,timedOut:o,tail:r.join(`
702
- `)}))},u=setTimeout(()=>{o=!0,Lc(t.pid,"SIGTERM"),setTimeout(()=>Lc(t.pid,"SIGKILL"),1e4).unref()},n.timeoutMs);_a.default.createInterface({input:t.stdout}).on("line",c=>{s(c),n.onLine("info",c)}),_a.default.createInterface({input:t.stderr}).on("line",c=>{s(c),n.onLine("warn",c)}),t.on("error",c=>{s(`failed to start: ${c.message}`),l(127)}),t.on("close",c=>l(c??1))})}function Lc(n,e){if(n)try{process.kill(-n,e)}catch{try{process.kill(n,e)}catch{}}}function Dg(n){let e=n.filter(t=>t&&t.length>=6).sort((t,r)=>r.length-t.length);return e.length?t=>{let r=t;for(let s of e)r=r.split(s).join("***");return r}:t=>t}async function st(n,e){if(n.issueKey!==or.BRANCH_DEPLOY_ISSUE_KEY)try{await n.jira.addComment(n.issueKey,e)}catch(t){y.error(`could not post deploy comment to ${n.issueKey}: ${t}`)}}function Ta(n){return Ti(n)!==null}async function Zc(n,e){let t=Ti(e);if(!t)return;let{emit:r,setStatus:s}=Sa({runId:e,transport:n.transport}),i=n.lookup(t.projectId,t.environmentName);if(!i){let l=`approved, but environment "${t.environmentName}" is no longer in this runner's config (deleted or renamed?) - nothing was deployed`;r("error",l),s("failed",{error:l}),xi(e);return}xi(e);let o={runId:e,project:i.project,environment:i.environment,issueKey:t.issueKey,issueSummary:t.issueSummary,repoPath:i.repoPath,cfg:n.cfg,jira:n.jiraFor(i.project.repoName),transport:n.transport,requestedBy:t.requestedBy};r("info",`Approved - running the ${i.environment.steps.length} deploy step(s) now`);try{await Kc(o,r,s)}catch(l){let u=l instanceof Error?l.message:String(l);r("error",`Deploy failed: ${u}`),await st(o,`**Allwright deploy failed.**
718
+ (run \`${n.runId}\`)`});return s(`"${t.branch}" is not in sync with "${r}" - opened ${f.url} to catch it up. Merge that, then retry the deploy.`,!0)}catch(l){return s(`could not open a sync PR: ${l instanceof Error?l.message:String(l)}`)}}function Jg(n,e){if(!e.trim())return n;let t=or.default.resolve(n,e),r=or.default.relative(n,t);if(r.startsWith("..")||or.default.isAbsolute(r))throw new Error(`working directory "${e}" is outside the repository checkout`);return t}function Yg(n){return new Promise(e=>{let t=(0,lr.spawn)("bash",["-lc",n.command],{cwd:n.cwd,env:n.env,detached:!0,stdio:["ignore","pipe","pipe"]}),r=[],s=c=>{r.push(c),r.length>20&&r.shift()},i=!1,o=!1,l=c=>{i||(i=!0,clearTimeout(u),e({code:c,timedOut:o,tail:r.join(`
719
+ `)}))},u=setTimeout(()=>{o=!0,Wc(t.pid,"SIGTERM"),setTimeout(()=>Wc(t.pid,"SIGKILL"),1e4).unref()},n.timeoutMs);Ra.default.createInterface({input:t.stdout}).on("line",c=>{s(c),n.onLine("info",c)}),Ra.default.createInterface({input:t.stderr}).on("line",c=>{s(c),n.onLine("warn",c)}),t.on("error",c=>{s(`failed to start: ${c.message}`),l(127)}),t.on("close",c=>l(c??1))})}function Wc(n,e){if(n)try{process.kill(-n,e)}catch{try{process.kill(n,e)}catch{}}}function Xg(n){let e=n.filter(t=>t&&t.length>=6).sort((t,r)=>r.length-t.length);return e.length?t=>{let r=t;for(let s of e)r=r.split(s).join("***");return r}:t=>t}async function at(n,e){if(n.issueKey!==ur.BRANCH_DEPLOY_ISSUE_KEY)try{await n.jira.addComment(n.issueKey,e)}catch(t){y.error(`could not post deploy comment to ${n.issueKey}: ${t}`)}}function $a(n){return Ri(n)!==null}async function td(n,e){let t=Ri(e);if(!t)return;let{emit:r,setStatus:s}=Aa({runId:e,transport:n.transport}),i=n.lookup(t.projectId,t.environmentName);if(!i){let l=`approved, but environment "${t.environmentName}" is no longer in this runner's config (deleted or renamed?) - nothing was deployed`;r("error",l),s("failed",{error:l}),Ei(e);return}Ei(e);let o={runId:e,project:i.project,environment:i.environment,issueKey:t.issueKey,issueSummary:t.issueSummary,repoPath:i.repoPath,cfg:n.cfg,jira:n.jiraFor(i.project.repoName),transport:n.transport,requestedBy:t.requestedBy};r("info",`Approved - running the ${i.environment.steps.length} deploy step(s) now`);try{await ed(o,r,s)}catch(l){let u=l instanceof Error?l.message:String(l);r("error",`Deploy failed: ${u}`),await at(o,`**Allwright deploy failed.**
703
720
 
704
- ${u.slice(0,800)}`),s("failed",{error:u})}}async function Gc(n,e){let t=Ti(e);if(!t)return;let{emit:r,setStatus:s}=Sa({runId:e,transport:n.transport});xi(e),r("info",`Deploy to "${t.environmentName}" was rejected - nothing ran`);let i=n.lookup(t.projectId,t.environmentName);try{await n.jiraFor(i?.project.repoName??"").addComment(t.issueKey,`**Allwright: deploy to \`${t.environmentName}\` was rejected.**
721
+ ${u.slice(0,800)}`),s("failed",{error:u})}}async function nd(n,e){let t=Ri(e);if(!t)return;let{emit:r,setStatus:s}=Aa({runId:e,transport:n.transport});Ei(e),r("info",`Deploy to "${t.environmentName}" was rejected - nothing ran`);let i=n.lookup(t.projectId,t.environmentName);try{await n.jiraFor(i?.project.repoName??"").addComment(t.issueKey,`**Allwright: deploy to \`${t.environmentName}\` was rejected.**
705
722
 
706
- No deploy step was executed. (run \`${e}\`)`)}catch(o){y.error(`could not post rejection comment to ${t.issueKey}: ${o}`)}s("failed",{error:"deploy rejected by a reviewer"})}var Lg=k.object({steps:k.array(or.DeployStep).max(50).default([]),requiredSecrets:k.array(k.string()).max(50).default([]),notes:k.string().default("")}),Ug=[".ticketpilot/deploy.md","DEPLOY.md","DEPLOYMENT.md","docs/DEPLOY.md","docs/deploy.md","docs/deployment.md"],Uc=24e3;function $i(n){for(let e of Ug){let t=rr.default.join(n,e);try{if(!sr.default.existsSync(t))continue;let r=sr.default.readFileSync(t,"utf8");if(!r.trim())continue;return{path:e,content:r.length>Uc?r.slice(0,Uc)+`
723
+ No deploy step was executed. (run \`${e}\`)`)}catch(o){y.error(`could not post rejection comment to ${t.issueKey}: ${o}`)}s("failed",{error:"deploy rejected by a reviewer"})}var Qg=k.object({steps:k.array(ur.DeployStep).max(50).default([]),requiredSecrets:k.array(k.string()).max(50).default([]),notes:k.string().default("")}),ey=[".ticketpilot/deploy.md","DEPLOY.md","DEPLOYMENT.md","docs/DEPLOY.md","docs/deploy.md","docs/deployment.md"],Jc=24e3;function Ni(n){for(let e of ey){let t=or.default.join(n,e);try{if(!ar.default.existsSync(t))continue;let r=ar.default.readFileSync(t,"utf8");if(!r.trim())continue;return{path:e,content:r.length>Jc?r.slice(0,Jc)+`
707
724
 
708
- [\u2026document truncated\u2026]`:r}}catch{continue}}return null}var qc=["docker","docker-compose","pm2","systemctl","node","pnpm","npm","yarn","make","python3","pip","rsync","ssh","caddy","nginx"];function Hc(n){return Vc("bash",["-lc",`command -v ${JSON.stringify(n)}`]).trim().length>0}function Vc(n,e){try{let t=(0,ir.spawnSync)(n,e,{encoding:"utf8",timeout:5e3});return t.status===0?t.stdout??"":""}catch{return""}}async function qg(n,e){let t;try{t=new URL(n)}catch{e.push({name:"public-url",ok:!1,detail:`not a valid URL: ${n}`});return}try{let{lookup:r}=await import("node:dns/promises"),s=await r(t.hostname);e.push({name:"public-url-dns",ok:!0,detail:`${t.hostname} \u2192 ${s.address}`})}catch{e.push({name:"public-url-dns",ok:!1,detail:`${t.hostname} does not resolve - add an A/CNAME record for it at your DNS provider (changes can take a few minutes to propagate)`});return}if(t.protocol==="https:"){let r=await import("node:tls");await new Promise(s=>{let i=r.connect({host:t.hostname,port:Number(t.port||443),servername:t.hostname,timeout:8e3},()=>{let o=i.getPeerCertificate(),l=o?.valid_to?Math.round((new Date(o.valid_to).getTime()-Date.now())/864e5):NaN;e.push(Number.isFinite(l)&&l>0?{name:"public-url-tls",ok:l>14,detail:`certificate valid, expires in ${l} day(s)${l<=14?" - renew soon":""}`}:{name:"public-url-tls",ok:!1,detail:"certificate expired or unreadable"}),i.end(),s()});i.on("error",o=>{e.push({name:"public-url-tls",ok:!1,detail:`TLS handshake failed: ${o.message} - is a certificate installed for this hostname?`}),s()}),i.on("timeout",()=>{e.push({name:"public-url-tls",ok:!1,detail:"TLS handshake timed out"}),i.destroy(),s()})})}try{let r=await fetch(t.toString(),{method:"GET",redirect:"manual",signal:AbortSignal.timeout(1e4)});e.push({name:"public-url-reachable",ok:r.status<500,detail:`HTTP ${r.status}${r.status>=300&&r.status<400?` \u2192 ${r.headers.get("location")??""}`:""}`})}catch(r){e.push({name:"public-url-reachable",ok:!1,detail:`not reachable from the runner: ${r instanceof Error?r.message:String(r)}`})}}function Fg(n){let e=n.match(/\/(?:var|home|opt|srv)\/[\w./-]+/g)??[],t=[...new Set(e.map(s=>s.replace(/[.,;:)\]'"`]+$/,"")))].slice(0,12);return t.length?`
725
+ [\u2026document truncated\u2026]`:r}}catch{continue}}return null}var Yc=["docker","docker-compose","pm2","systemctl","node","pnpm","npm","yarn","make","python3","pip","rsync","ssh","caddy","nginx"];function rd(n){return sd("bash",["-lc",`command -v ${JSON.stringify(n)}`]).trim().length>0}function sd(n,e){try{let t=(0,lr.spawnSync)(n,e,{encoding:"utf8",timeout:5e3});return t.status===0?t.stdout??"":""}catch{return""}}async function ty(n,e){let t;try{t=new URL(n)}catch{e.push({name:"public-url",ok:!1,detail:`not a valid URL: ${n}`});return}try{let{lookup:r}=await import("node:dns/promises"),s=await r(t.hostname);e.push({name:"public-url-dns",ok:!0,detail:`${t.hostname} \u2192 ${s.address}`})}catch{e.push({name:"public-url-dns",ok:!1,detail:`${t.hostname} does not resolve - add an A/CNAME record for it at your DNS provider (changes can take a few minutes to propagate)`});return}if(t.protocol==="https:"){let r=await import("node:tls");await new Promise(s=>{let i=r.connect({host:t.hostname,port:Number(t.port||443),servername:t.hostname,timeout:8e3},()=>{let o=i.getPeerCertificate(),l=o?.valid_to?Math.round((new Date(o.valid_to).getTime()-Date.now())/864e5):NaN;e.push(Number.isFinite(l)&&l>0?{name:"public-url-tls",ok:l>14,detail:`certificate valid, expires in ${l} day(s)${l<=14?" - renew soon":""}`}:{name:"public-url-tls",ok:!1,detail:"certificate expired or unreadable"}),i.end(),s()});i.on("error",o=>{e.push({name:"public-url-tls",ok:!1,detail:`TLS handshake failed: ${o.message} - is a certificate installed for this hostname?`}),s()}),i.on("timeout",()=>{e.push({name:"public-url-tls",ok:!1,detail:"TLS handshake timed out"}),i.destroy(),s()})})}try{let r=await fetch(t.toString(),{method:"GET",redirect:"manual",signal:AbortSignal.timeout(1e4)});e.push({name:"public-url-reachable",ok:r.status<500,detail:`HTTP ${r.status}${r.status>=300&&r.status<400?` \u2192 ${r.headers.get("location")??""}`:""}`})}catch(r){e.push({name:"public-url-reachable",ok:!1,detail:`not reachable from the runner: ${r instanceof Error?r.message:String(r)}`})}}function ny(n){let e=n.match(/\/(?:var|home|opt|srv)\/[\w./-]+/g)??[],t=[...new Set(e.map(s=>s.replace(/[.,;:)\]'"`]+$/,"")))].slice(0,12);return t.length?`
709
726
  - absolute paths the document mentions, checked on THIS machine:
710
- ${t.map(s=>` - ${s}: ${sr.default.existsSync(s)?"EXISTS on this machine":"not found on this machine"}`).join(`
711
- `)}`:""}function Bg(){let n=[],e=(t,r)=>{try{let s=(0,ir.execFileSync)(r,["--version"],{encoding:"utf8",timeout:5e3}).trim();n.push(`- ${t}: ${s}`)}catch{}};for(let t of["node","npm","python3"]){let r="";try{r=(0,ir.execFileSync)("which",[t],{encoding:"utf8",timeout:5e3}).trim()}catch{continue}e(`${t} in the RUNNER's PATH (${r}) - deploy steps run with THIS`,r);for(let s of[`/usr/bin/${t}`,`/usr/local/bin/${t}`])s!==r&&sr.default.existsSync(s)&&e(`${t} at ${s}`,s)}return n.length?`
727
+ ${t.map(s=>` - ${s}: ${ar.default.existsSync(s)?"EXISTS on this machine":"not found on this machine"}`).join(`
728
+ `)}`:""}function ry(){let n=[],e=(t,r)=>{try{let s=(0,lr.execFileSync)(r,["--version"],{encoding:"utf8",timeout:5e3}).trim();n.push(`- ${t}: ${s}`)}catch{}};for(let t of["node","npm","python3"]){let r="";try{r=(0,lr.execFileSync)("which",[t],{encoding:"utf8",timeout:5e3}).trim()}catch{continue}e(`${t} in the RUNNER's PATH (${r}) - deploy steps run with THIS`,r);for(let s of[`/usr/bin/${t}`,`/usr/local/bin/${t}`])s!==r&&ar.default.existsSync(s)&&e(`${t} at ${s}`,s)}return n.length?`
712
729
  - runtime versions (a MISMATCH between the runner's PATH and the system install is a common root cause):
713
730
  ${n.map(t=>` ${t}`).join(`
714
- `)}`:""}function Wc(n,e,t,r=""){let s=qc.filter(l=>Hc(l)),i=qc.filter(l=>!s.includes(l)),o=Object.keys(Cn(n,e,t));return`About the machine these steps will run on (gathered by the runner, trust it):
731
+ `)}`:""}function id(n,e,t,r=""){let s=Yc.filter(l=>rd(l)),i=Yc.filter(l=>!s.includes(l)),o=Object.keys(En(n,e,t));return`About the machine these steps will run on (gathered by the runner, trust it):
715
732
  - available tools: ${s.join(", ")||"(none of the common ones)"}
716
733
  - NOT installed: ${i.join(", ")||"(none missing)"}
717
- - secrets already stored for this environment (names only): ${o.join(", ")||"(none yet)"}`+Bg()+Fg(r)}async function Jc(n){let e=[];if(n.publicUrl?.trim()&&await qg(n.publicUrl.trim(),e),e.push(sr.default.existsSync(n.repoPath)?{name:"repo-path",ok:!0,detail:n.repoPath}:{name:"repo-path",ok:!1,detail:`checkout missing: ${n.repoPath}`}),e.push({name:"deploys-enabled",ok:n.cfg.deploy.enabled,detail:n.cfg.deploy.enabled?"enabled on this runner":"disabled - run: allwright deploy enable (then restart the runner)"}),n.workdir){let l=rr.default.isAbsolute(n.workdir)?n.workdir:rr.default.join(n.repoPath,n.workdir);e.push(sr.default.existsSync(l)?{name:"workdir",ok:!0,detail:l}:{name:"workdir",ok:!1,detail:`does not exist: ${l}`})}if(n.branch){let l=Vc("git",["-C",n.repoPath,"ls-remote","--heads","origin",n.branch]);e.push(l.trim()?{name:"branch",ok:!0,detail:`origin/${n.branch} exists`}:{name:"branch",ok:!1,detail:`origin has no branch "${n.branch}" (or the remote is unreachable)`})}let t=Cn(n.cfg,n.repoName,n.environmentName),r=new Set(n.requiredSecrets);for(let l of n.steps)for(let u of l.run.matchAll(/\$\{?([A-Z][A-Z0-9_]{2,})\}?/g))r.add(u[1]);let s=[...r].filter(l=>!t[l]&&!process.env[l]);e.push({name:"secrets",ok:s.length===0,detail:s.length?`missing: ${s.join(", ")} - set with: allwright env set "${n.repoName}" "${n.environmentName}" ${s[0]}=...`:`${r.size} present`});let i=new Set;for(let l of n.steps)for(let u of l.run.split(/&&|\|\||;|\|/)){let c=u.trim().split(/\s+/),f=c.shift();for(;f&&(/^[A-Za-z_][A-Za-z0-9_]*=/.test(f)||f==="sudo"||f==="env"||f==="nohup");)f=c.shift();!f||f.startsWith("$")||f.startsWith("#")||f.startsWith("(")||i.add(f)}let o=[...i].filter(l=>!Hc(l));return e.push({name:"binaries",ok:o.length===0,detail:o.length?`not found on this machine: ${o.join(", ")}`:`${i.size} found: ${[...i].slice(0,12).join(", ")}`}),{ok:e.every(l=>l.ok),checks:e}}async function Yc(n){let e=Wc(n.cfg,n.repoName,n.environmentName),t=jt(Bc.DEPLOY_FIX_PROMPT_TEMPLATE,{envName:n.environmentName,steps:n.steps.map((c,f)=>`${f+1}. [${c.name}]${c.continueOnError?" (continues on error)":""}
734
+ - secrets already stored for this environment (names only): ${o.join(", ")||"(none yet)"}`+ry()+ny(r)}async function od(n){let e=[];if(n.publicUrl?.trim()&&await ty(n.publicUrl.trim(),e),e.push(ar.default.existsSync(n.repoPath)?{name:"repo-path",ok:!0,detail:n.repoPath}:{name:"repo-path",ok:!1,detail:`checkout missing: ${n.repoPath}`}),e.push({name:"deploys-enabled",ok:n.cfg.deploy.enabled,detail:n.cfg.deploy.enabled?"enabled on this runner":"disabled - run: allwright deploy enable (then restart the runner)"}),n.workdir){let l=or.default.isAbsolute(n.workdir)?n.workdir:or.default.join(n.repoPath,n.workdir);e.push(ar.default.existsSync(l)?{name:"workdir",ok:!0,detail:l}:{name:"workdir",ok:!1,detail:`does not exist: ${l}`})}if(n.branch){let l=sd("git",["-C",n.repoPath,"ls-remote","--heads","origin",n.branch]);e.push(l.trim()?{name:"branch",ok:!0,detail:`origin/${n.branch} exists`}:{name:"branch",ok:!1,detail:`origin has no branch "${n.branch}" (or the remote is unreachable)`})}let t=En(n.cfg,n.repoName,n.environmentName),r=new Set(n.requiredSecrets);for(let l of n.steps)for(let u of l.run.matchAll(/\$\{?([A-Z][A-Z0-9_]{2,})\}?/g))r.add(u[1]);let s=[...r].filter(l=>!t[l]&&!process.env[l]);e.push({name:"secrets",ok:s.length===0,detail:s.length?`missing: ${s.join(", ")} - set with: allwright env set "${n.repoName}" "${n.environmentName}" ${s[0]}=...`:`${r.size} present`});let i=new Set;for(let l of n.steps)for(let u of l.run.split(/&&|\|\||;|\|/)){let c=u.trim().split(/\s+/),f=c.shift();for(;f&&(/^[A-Za-z_][A-Za-z0-9_]*=/.test(f)||f==="sudo"||f==="env"||f==="nohup");)f=c.shift();!f||f.startsWith("$")||f.startsWith("#")||f.startsWith("(")||i.add(f)}let o=[...i].filter(l=>!rd(l));return e.push({name:"binaries",ok:o.length===0,detail:o.length?`not found on this machine: ${o.join(", ")}`:`${i.size} found: ${[...i].slice(0,12).join(", ")}`}),{ok:e.every(l=>l.ok),checks:e}}async function ad(n){let e=id(n.cfg,n.repoName,n.environmentName),t=zt(Qc.DEPLOY_FIX_PROMPT_TEMPLATE,{envName:n.environmentName,steps:n.steps.map((c,f)=>`${f+1}. [${c.name}]${c.continueOnError?" (continues on error)":""}
718
735
  ${c.run}`).join(`
719
- `),failedStep:n.failedStep||"(unknown)",errorText:n.errorText||"(no error text recorded)",machineContext:e}),r=await n.agent.adapter.run({repoPath:n.repoPath,prompt:t,timeoutSeconds:240,bin:n.agent.bin,mode:"read_only",maxTurns:40,sessionId:(0,ka.randomUUID)(),onLog:()=>{}});if(!r.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:r.error??"the agent produced no output"};let s=Qc(r.resultText),i=r.resultText.split(/```/)[0]?.trim()??"",l=/```(?:markdown|md)\s*\n([\s\S]*?)```/i.exec(r.resultText)?.[1]?.trim()??"",u=l?$i(n.repoPath):null;return s?{ok:!0,...s,notes:i||s.notes,docPath:u?.path??(l?"DEPLOY.md":""),docContent:l}:{ok:!1,steps:[],requiredSecrets:[],notes:i,error:i?"the agent diagnosed the failure (see its notes) but did not produce an applicable step list - the cause may live outside the steps":`the agent's answer was not in the expected shape. It started: "${r.resultText.trim().slice(0,200).replace(/\s+/g," ")}\u2026"`}}async function Xc(n){let e=$i(n.repoPath);if(!e)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:'this repo has no deploy document. Create DEPLOY.md at the repo root (or .ticketpilot/deploy.md) describing how this project actually deploys - the same commands you run by hand. "Ask Claude for steps" translates that document; it does not guess.'};let t=Wc(n.cfg,n.repoName,n.environmentName,e.content),r=jt(or.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE,{envName:n.environmentName,docPath:e.path,docContent:e.content,notes:n.notes.trim()||"(nothing specified)",machineContext:t}),s=await n.agent.adapter.run({repoPath:n.repoPath,prompt:r,timeoutSeconds:n.timeoutSeconds,bin:n.agent.bin,mode:"read_only",maxTurns:30,sessionId:(0,ka.randomUUID)(),onLog:()=>{}});if(!s.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:s.error??"Claude Code produced no output"};let i=Qc(s.resultText);return i?{ok:!0,...i}:(y.warn(`deploy step suggestion could not be parsed. Claude's raw answer follows:
720
- `+s.resultText.slice(0,4e3)),{ok:!1,steps:[],requiredSecrets:[],notes:"",error:`Claude answered, but not in the JSON shape we expected, so there is nothing safe to fill in. Try again, or write the steps by hand. Its answer started: "${s.resultText.trim().slice(0,200).replace(/\s+/g," ")}\u2026"`})}function Qc(n){for(let e of Kg(n)){let t;try{t=JSON.parse(e)}catch{continue}let r=Lg.safeParse(Zg(t));if(r.success&&r.data.steps.length||r.success&&r.data.notes.trim())return r.data}return null}function Kg(n){let e=[];for(let s of n.matchAll(/```[a-zA-Z0-9_-]*[ \t]*\r?\n([\s\S]*?)```/g))s[1].trim()&&e.push(s[1]);let t=n.indexOf("{"),r=n.lastIndexOf("}");return t>=0&&r>t&&e.push(n.slice(t,r+1)),e}function Zg(n){if(!n||typeof n!="object")return n;let e=n,r=(Array.isArray(n)?n:Array.isArray(e.steps)?e.steps:Array.isArray(e.deploy_steps)?e.deploy_steps:Array.isArray(e.deploySteps)?e.deploySteps:[]).map((o,l)=>{if(typeof o=="string")return o.trim()?{name:Fc(o,l),run:o.trim()}:null;if(!o||typeof o!="object")return null;let u=o,c=wa(u.run,u.command,u.cmd,u.script,u.shell);return c?{name:(wa(u.name,u.title,u.description)??Fc(c,l)).slice(0,120),run:c,continueOnError:u.continueOnError===!0||u.continue_on_error===!0}:null}).filter(Boolean),s=e.requiredSecrets??e.required_secrets??e.secrets,i=Array.isArray(s)?s.filter(o=>typeof o=="string"):s&&typeof s=="object"?Object.keys(s):[];return{steps:r.slice(0,50),requiredSecrets:i.slice(0,50),notes:wa(e.notes,e.note,e.explanation)??""}}function wa(...n){for(let e of n)if(typeof e=="string"&&e.trim())return e.trim()}function Fc(n,e){return(n.split(`
721
- `)[0].trim()||`Step ${e+1}`).slice(0,120)}pt();nt();Wn();function Pi(n,e){if(!n.componentRoutes.length)return{project:n};let t=e.filter(Boolean);if(!t.length)return{error:`no Jira component set - project "${n.name}" routes by component (${n.componentRoutes.map(i=>i.component).join(", ")}); set one on the ticket`};let r=n.componentRoutes.filter(i=>t.includes(i.component));if(!r.length)return{error:`component(s) [${t.join(", ")}] not mapped - known: `+n.componentRoutes.map(i=>`${i.component}\u2192${i.repoName}`).join(", ")};let s=new Set(r.map(i=>i.repoName));return s.size>1?{error:`components map to DIFFERENT repos (${[...s].join(", ")}) - ambiguous, refusing`}:{project:{...n,repoName:r[0].repoName}}}var ed=24*3600*1e3,ji=14,Gg=ji*24*3600*1e3,Hg=new Set(["to","on","this","the","a","an","env","environment","please","now","it"]),Oi=class{constructor(e,t,r){this.cfg=e;this.jiraFor=t;this.transport=r}cfg;jiraFor;transport;projects=[];rules=[];environments=[];inFlight=new Set;autopilotPausedUntil=0;get busyCount(){return Math.max(this.inFlight.size,this.activeWork)}activeWork=0;get idle(){return!this.ticking&&this.inFlight.size===0&&this.activeWork===0}repoQueues=new Map;envQueues=new Map;timer=null;ticking=!1;paused=!1;jiraOf(e){return this.jiraFor(e.repoName)}routingWarned=new Set;warnRoutingOnce(e,t){this.routingWarned.has(e)||(this.routingWarned.add(e),y.warn(`Component routing refused - ${t}`))}resolveClaudeProfile(e,t){if(!t)return;let r=this.cfg.claudeProfiles[t]?.configDir;return!r&&e&&(this.transport.send({type:"run.log",runId:e,seq:99e3,ts:new Date().toISOString(),level:"warn",message:`Claude profile "${t}" is not set up on this runner (allwright claude login "${t}") - using the runner's own login instead.`}),y.warn(`run ${e}: claude profile "${t}" missing locally - using default login`)),r}setConfig(e,t,r=!1,s=[]){this.projects=e,this.rules=t,this.environments=s;let i=t.filter(o=>o.enabled).length;y.info(`config synced: ${e.length} project(s), ${t.length} rule(s) (${i} enabled), ${s.length} environment(s)`),r!==this.paused&&(y.info(r?"polling paused from the dashboard":"polling resumed from the dashboard"),this.paused=r)}start(){let e=this.cfg.pollIntervalSeconds*1e3;this.timer=setInterval(()=>{this.tick()},e),this.tick(),y.info(`polling Jira every ${this.cfg.pollIntervalSeconds}s`)}stop(){this.timer&&clearInterval(this.timer)}lastScheduleCheck=0;auditInFlight=!1;async runScheduledAudits(){if(!(!this.cfg.auditSchedules.length||this.auditInFlight)&&!(Date.now()-this.lastScheduleCheck<15*6e4)){this.lastScheduleCheck=Date.now();for(let e of this.cfg.auditSchedules){let t=this.projects.find(s=>s.repoName===e.repoName);if(!t)continue;let r=Gu(t.id,e.role);if(!(r&&Date.now()-new Date(r).getTime()<e.intervalHours*36e5)){this.auditInFlight=!0;try{y.info(`Scheduled ${e.role} audit of ${e.repoName} starting (every ${e.intervalHours}h)`);let s=tt(this.cfg,t,"assist");if("error"in s){y.warn(`Scheduled audit skipped: ${s.error}`);continue}let i=await Fr({projectId:t.id,repoPath:this.cfg.repos[e.repoName]?.path??"",role:e.role,scope:{kind:"repo",ref:""},model:"",agent:s,jira:this.jiraFor(e.repoName)});if(i.ok){let o=i.audit.findings.length;y.info(`Scheduled audit done: ${o} finding(s) - drift visible on the Audits page`)}else y.warn(`Scheduled audit failed: ${i.error}`)}catch(s){y.warn(`Scheduled audit crashed: ${s instanceof Error?s.message:String(s)}`)}finally{this.auditInFlight=!1}break}}}}async tick(){if(!(this.ticking||this.paused||!this.transport.connected)){this.ticking=!0;try{await this.runScheduledAudits(),await this.sweepMergedPRs(),await this.sweepGitHubApprovals();let e=new Set;for(let t of this.rules){if(!t.enabled)continue;let r=this.projects.find(i=>i.id===t.projectId);if(!r)continue;let s=this.cfg.repos[r.repoName];if(!s){y.warn(`rule "${t.name}": no local path for repo "${r.repoName}" - run: allwright repo add "${r.repoName}" /path/to/checkout`);continue}t.action.type==="deploy"?await this.pollDeployRule(t,r,s.path):t.action.type==="respond"?await this.pollRespondRule(t,r,s.path):(e.has(r.id)||(e.add(r.id),await this.sweepNeedsInput(r)),t.trigger.type==="comment_keyword"&&await this.sweepRevisions(t,r),await this.pollRule(t,r,s.path))}await this.pullAutopilotWork()}catch(e){y.warn(`poll tick failed: ${e instanceof Error?e.message:e}`)}finally{this.ticking=!1}}}async pullAutopilotWork(){if(this.inFlight.size>0||this.autopilotPausedUntil>Date.now())return;let e=await this.transport.requestAutopilotNext();if(!e?.ok)return;if(e.pausedUntil){let T=Date.parse(e.pausedUntil);Number.isFinite(T)&&(this.autopilotPausedUntil=T);return}let t=e.item;if(!t)return;let r=this.rules.find(T=>T.id===t.ruleId&&T.enabled),s=this.projects.find(T=>T.id===t.projectId);if(!r||!s){this.transport.sendAutopilotReport({itemId:t.id,outcome:"failed",error:"the rule or project this item was queued against no longer exists"});return}let i=Pi(s,[]),o="project"in i?i.project:s,l=this.cfg.repos[o.repoName];if(!l){this.transport.sendAutopilotReport({itemId:t.id,outcome:"failed",error:`no local checkout mapped for "${o.repoName}" on this machine`});return}let u=t.baseOverride||t.branchOverride||t.autoMerge?{...r,action:r.action.type==="implement"?{...r.action,...t.baseOverride?{baseBranch:t.baseOverride}:{},...t.branchOverride?{branchTemplate:t.branchOverride}:{},...t.autoMerge?{requireApproval:!1,autoMerge:!0}:{}}:r.action}:r;y.info(`autopilot: taking ${t.issueKey} (${r.name})`+(t.branchOverride?` -> shared branch ${t.branchOverride}`:"")+(t.baseOverride?` -> stacked on ${t.baseOverride}`:""));let c=this.jiraOf(o),f="";try{f=(await c.getIssue(t.issueKey))?.summary??""}catch(T){this.transport.sendAutopilotReport({itemId:t.id,outcome:"failed",error:`could not read ${t.issueKey} from Jira: ${T instanceof Error?T.message:String(T)}`});return}let p=await this.transport.claimRun({ruleId:r.id,issueKey:t.issueKey,issueSummary:f,triggerFingerprint:`autopilot:${t.id}`,dedupKey:`autopilot:${t.id}`});if(!p.accepted||!p.runId){this.transport.sendAutopilotReport({itemId:t.id,outcome:"failed",error:p.reason??"the control plane refused the run"});return}this.transport.sendAutopilotReport({itemId:t.id,outcome:"claimed",runId:p.runId});let b=`${r.id}:${t.issueKey}`;this.inFlight.add(b);let w=this.resolveClaudeProfile(p.runId,p.claudeProfile);this.enqueueForRepo(l.path,async()=>{try{await Ri({runId:p.runId,rule:u,project:o,issueKey:t.issueKey,repoPath:l.path,cfg:this.cfg,jira:c,transport:this.transport,claudeConfigDir:w,actorEmail:p.actorEmail,continueBranch:t.continueBranch})}finally{this.inFlight.delete(b)}})}async sweepGitHubApprovals(){let e=Object.values(ws());if(!e.length)return;let t=me()??this.cfg,r=new Map,s=i=>{let o=Te(t,i);if(!o)return null;let l=r.get(o);return l||r.set(o,l=new xe(o)),l};for(let i of e.slice(0,10)){let o=s(i.repoName);if(!o)continue;let l=`gh-approve:${i.runId}`;if(this.inFlight.has(l))continue;let u,c;try{[u,c]=await Promise.all([o.getReviews(i.owner,i.repo,i.prNumber),o.getPullRequest(i.owner,i.repo,i.prNumber)])}catch(w){y.warn(`review check failed for ${i.owner}/${i.repo}#${i.prNumber}: ${w instanceof Error?w.message:w}`);continue}if(!c)continue;let f={cfg:this.cfg,jiraFor:this.jiraFor,transport:this.transport};if(c.merged){y.info(`PR #${i.prNumber} for ${i.issueKey} was merged on GitHub - completing the run`),this.inFlight.add(l);try{await ks(f,i.runId,c.headSha)}finally{this.inFlight.delete(l)}continue}if(c.state==="closed"){y.info(`PR #${i.prNumber} for ${i.issueKey} was closed unmerged on GitHub - failing the run`);let w=this.jiraFor(i.repoName),T=`PR #${i.prNumber} was closed on GitHub without merging`;await w.addComment(i.issueKey,`**Allwright: the pull request for this ticket was closed on GitHub without merging.**
736
+ `),failedStep:n.failedStep||"(unknown)",errorText:n.errorText||"(no error text recorded)",machineContext:e}),r=await n.agent.adapter.run({repoPath:n.repoPath,prompt:t,timeoutSeconds:240,bin:n.agent.bin,mode:"read_only",maxTurns:40,sessionId:(0,Ea.randomUUID)(),onLog:()=>{}});if(!r.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:r.error??"the agent produced no output"};let s=ud(r.resultText),i=r.resultText.split(/```/)[0]?.trim()??"",l=/```(?:markdown|md)\s*\n([\s\S]*?)```/i.exec(r.resultText)?.[1]?.trim()??"",u=l?Ni(n.repoPath):null;return s?{ok:!0,...s,notes:i||s.notes,docPath:u?.path??(l?"DEPLOY.md":""),docContent:l}:{ok:!1,steps:[],requiredSecrets:[],notes:i,error:i?"the agent diagnosed the failure (see its notes) but did not produce an applicable step list - the cause may live outside the steps":`the agent's answer was not in the expected shape. It started: "${r.resultText.trim().slice(0,200).replace(/\s+/g," ")}\u2026"`}}async function ld(n){let e=Ni(n.repoPath);if(!e)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:'this repo has no deploy document. Create DEPLOY.md at the repo root (or .ticketpilot/deploy.md) describing how this project actually deploys - the same commands you run by hand. "Ask Claude for steps" translates that document; it does not guess.'};let t=id(n.cfg,n.repoName,n.environmentName,e.content),r=zt(ur.DEPLOY_DOC_SUGGEST_PROMPT_TEMPLATE,{envName:n.environmentName,docPath:e.path,docContent:e.content,notes:n.notes.trim()||"(nothing specified)",machineContext:t}),s=await n.agent.adapter.run({repoPath:n.repoPath,prompt:r,timeoutSeconds:n.timeoutSeconds,bin:n.agent.bin,mode:"read_only",maxTurns:30,sessionId:(0,Ea.randomUUID)(),onLog:()=>{}});if(!s.ok)return{ok:!1,steps:[],requiredSecrets:[],notes:"",error:s.error??"Claude Code produced no output"};let i=ud(s.resultText);return i?{ok:!0,...i}:(y.warn(`deploy step suggestion could not be parsed. Claude's raw answer follows:
737
+ `+s.resultText.slice(0,4e3)),{ok:!1,steps:[],requiredSecrets:[],notes:"",error:`Claude answered, but not in the JSON shape we expected, so there is nothing safe to fill in. Try again, or write the steps by hand. Its answer started: "${s.resultText.trim().slice(0,200).replace(/\s+/g," ")}\u2026"`})}function ud(n){for(let e of sy(n)){let t;try{t=JSON.parse(e)}catch{continue}let r=Qg.safeParse(iy(t));if(r.success&&r.data.steps.length||r.success&&r.data.notes.trim())return r.data}return null}function sy(n){let e=[];for(let s of n.matchAll(/```[a-zA-Z0-9_-]*[ \t]*\r?\n([\s\S]*?)```/g))s[1].trim()&&e.push(s[1]);let t=n.indexOf("{"),r=n.lastIndexOf("}");return t>=0&&r>t&&e.push(n.slice(t,r+1)),e}function iy(n){if(!n||typeof n!="object")return n;let e=n,r=(Array.isArray(n)?n:Array.isArray(e.steps)?e.steps:Array.isArray(e.deploy_steps)?e.deploy_steps:Array.isArray(e.deploySteps)?e.deploySteps:[]).map((o,l)=>{if(typeof o=="string")return o.trim()?{name:Xc(o,l),run:o.trim()}:null;if(!o||typeof o!="object")return null;let u=o,c=Ia(u.run,u.command,u.cmd,u.script,u.shell);return c?{name:(Ia(u.name,u.title,u.description)??Xc(c,l)).slice(0,120),run:c,continueOnError:u.continueOnError===!0||u.continue_on_error===!0}:null}).filter(Boolean),s=e.requiredSecrets??e.required_secrets??e.secrets,i=Array.isArray(s)?s.filter(o=>typeof o=="string"):s&&typeof s=="object"?Object.keys(s):[];return{steps:r.slice(0,50),requiredSecrets:i.slice(0,50),notes:Ia(e.notes,e.note,e.explanation)??""}}function Ia(...n){for(let e of n)if(typeof e=="string"&&e.trim())return e.trim()}function Xc(n,e){return(n.split(`
738
+ `)[0].trim()||`Step ${e+1}`).slice(0,120)}gt();it();Xn();function Mi(n,e){if(!n.componentRoutes.length)return{project:n};let t=e.filter(Boolean);if(!t.length)return{error:`no Jira component set - project "${n.name}" routes by component (${n.componentRoutes.map(i=>i.component).join(", ")}); set one on the ticket`};let r=n.componentRoutes.filter(i=>t.includes(i.component));if(!r.length)return{error:`component(s) [${t.join(", ")}] not mapped - known: `+n.componentRoutes.map(i=>`${i.component}\u2192${i.repoName}`).join(", ")};let s=new Set(r.map(i=>i.repoName));return s.size>1?{error:`components map to DIFFERENT repos (${[...s].join(", ")}) - ambiguous, refusing`}:{project:{...n,repoName:r[0].repoName}}}var cd=24*3600*1e3,zi=14,oy=zi*24*3600*1e3,ay=new Set(["to","on","this","the","a","an","env","environment","please","now","it"]),Di=class{constructor(e,t,r){this.cfg=e;this.jiraFor=t;this.transport=r}cfg;jiraFor;transport;projects=[];rules=[];environments=[];inFlight=new Set;autopilotPausedUntil=0;get busyCount(){return Math.max(this.inFlight.size,this.activeWork)}activeWork=0;get idle(){return!this.ticking&&this.inFlight.size===0&&this.activeWork===0}repoQueues=new Map;envQueues=new Map;timer=null;ticking=!1;paused=!1;jiraOf(e){return this.jiraFor(e.repoName)}routingWarned=new Set;warnRoutingOnce(e,t){this.routingWarned.has(e)||(this.routingWarned.add(e),y.warn(`Component routing refused - ${t}`))}resolveClaudeProfile(e,t){if(!t)return;let r=this.cfg.claudeProfiles[t]?.configDir;return!r&&e&&(this.transport.send({type:"run.log",runId:e,seq:99e3,ts:new Date().toISOString(),level:"warn",message:`Claude profile "${t}" is not set up on this runner (allwright claude login "${t}") - using the runner's own login instead.`}),y.warn(`run ${e}: claude profile "${t}" missing locally - using default login`)),r}setConfig(e,t,r=!1,s=[]){this.projects=e,this.rules=t,this.environments=s;let i=t.filter(o=>o.enabled).length;y.info(`config synced: ${e.length} project(s), ${t.length} rule(s) (${i} enabled), ${s.length} environment(s)`),r!==this.paused&&(y.info(r?"polling paused from the dashboard":"polling resumed from the dashboard"),this.paused=r)}start(){let e=this.cfg.pollIntervalSeconds*1e3;this.timer=setInterval(()=>{this.tick()},e),this.tick(),y.info(`polling Jira every ${this.cfg.pollIntervalSeconds}s`)}stop(){this.timer&&clearInterval(this.timer)}lastScheduleCheck=0;auditInFlight=!1;async runScheduledAudits(){if(!(!this.cfg.auditSchedules.length||this.auditInFlight)&&!(Date.now()-this.lastScheduleCheck<15*6e4)){this.lastScheduleCheck=Date.now();for(let e of this.cfg.auditSchedules){let t=this.projects.find(s=>s.repoName===e.repoName);if(!t)continue;let r=Qu(t.id,e.role);if(!(r&&Date.now()-new Date(r).getTime()<e.intervalHours*36e5)){this.auditInFlight=!0;try{y.info(`Scheduled ${e.role} audit of ${e.repoName} starting (every ${e.intervalHours}h)`);let s=st(this.cfg,t,"assist");if("error"in s){y.warn(`Scheduled audit skipped: ${s.error}`);continue}let i=await Gr({projectId:t.id,repoPath:this.cfg.repos[e.repoName]?.path??"",role:e.role,scope:{kind:"repo",ref:""},model:"",agent:s,jira:this.jiraFor(e.repoName)});if(i.ok){let o=i.audit.findings.length;y.info(`Scheduled audit done: ${o} finding(s) - drift visible on the Audits page`)}else y.warn(`Scheduled audit failed: ${i.error}`)}catch(s){y.warn(`Scheduled audit crashed: ${s instanceof Error?s.message:String(s)}`)}finally{this.auditInFlight=!1}break}}}}async tick(){if(!(this.ticking||this.paused||!this.transport.connected)){this.ticking=!0;try{await this.runScheduledAudits(),await this.sweepMergedPRs(),await this.sweepGitHubApprovals();let e=new Set;for(let t of this.rules){if(!t.enabled)continue;let r=this.projects.find(i=>i.id===t.projectId);if(!r)continue;let s=this.cfg.repos[r.repoName];if(!s){y.warn(`rule "${t.name}": no local path for repo "${r.repoName}" - run: allwright repo add "${r.repoName}" /path/to/checkout`);continue}t.action.type==="deploy"?await this.pollDeployRule(t,r,s.path):t.action.type==="respond"?await this.pollRespondRule(t,r,s.path):(e.has(r.id)||(e.add(r.id),await this.sweepNeedsInput(r)),t.trigger.type==="comment_keyword"&&await this.sweepRevisions(t,r),await this.pollRule(t,r,s.path))}await this.pullAutopilotWork()}catch(e){y.warn(`poll tick failed: ${e instanceof Error?e.message:e}`)}finally{this.ticking=!1}}}async pullAutopilotWork(){if(this.inFlight.size>0||this.autopilotPausedUntil>Date.now())return;let e=await this.transport.requestAutopilotNext();if(!e?.ok)return;if(e.pausedUntil){let T=Date.parse(e.pausedUntil);Number.isFinite(T)&&(this.autopilotPausedUntil=T);return}let t=e.item;if(!t)return;let r=this.rules.find(T=>T.id===t.ruleId&&T.enabled),s=this.projects.find(T=>T.id===t.projectId);if(!r||!s){this.transport.sendAutopilotReport({itemId:t.id,outcome:"failed",error:"the rule or project this item was queued against no longer exists"});return}let i=Mi(s,[]),o="project"in i?i.project:s,l=this.cfg.repos[o.repoName];if(!l){this.transport.sendAutopilotReport({itemId:t.id,outcome:"failed",error:`no local checkout mapped for "${o.repoName}" on this machine`});return}let u=t.baseOverride||t.branchOverride||t.autoMerge?{...r,action:r.action.type==="implement"?{...r.action,...t.baseOverride?{baseBranch:t.baseOverride}:{},...t.branchOverride?{branchTemplate:t.branchOverride}:{},...t.autoMerge?{requireApproval:!1,autoMerge:!0}:{}}:r.action}:r;y.info(`autopilot: taking ${t.issueKey} (${r.name})`+(t.branchOverride?` -> shared branch ${t.branchOverride}`:"")+(t.baseOverride?` -> stacked on ${t.baseOverride}`:""));let c=this.jiraOf(o),f="";try{f=(await c.getIssue(t.issueKey))?.summary??""}catch(T){this.transport.sendAutopilotReport({itemId:t.id,outcome:"failed",error:`could not read ${t.issueKey} from Jira: ${T instanceof Error?T.message:String(T)}`});return}let p=await this.transport.claimRun({ruleId:r.id,issueKey:t.issueKey,issueSummary:f,triggerFingerprint:`autopilot:${t.id}`,dedupKey:`autopilot:${t.id}`});if(!p.accepted||!p.runId){this.transport.sendAutopilotReport({itemId:t.id,outcome:"failed",error:p.reason??"the control plane refused the run"});return}this.transport.sendAutopilotReport({itemId:t.id,outcome:"claimed",runId:p.runId});let b=`${r.id}:${t.issueKey}`;this.inFlight.add(b);let w=this.resolveClaudeProfile(p.runId,p.claudeProfile);this.enqueueForRepo(l.path,async()=>{try{await Pi({runId:p.runId,rule:u,project:o,issueKey:t.issueKey,repoPath:l.path,cfg:this.cfg,jira:c,transport:this.transport,claudeConfigDir:w,actorEmail:p.actorEmail,continueBranch:t.continueBranch})}finally{this.inFlight.delete(b)}})}async sweepGitHubApprovals(){let e=Object.values(Cs());if(!e.length)return;let t=pe()??this.cfg,r=new Map,s=i=>{let o=Te(t,i);if(!o)return null;let l=r.get(o);return l||r.set(o,l=new xe(o)),l};for(let i of e.slice(0,10)){let o=s(i.repoName);if(!o)continue;let l=`gh-approve:${i.runId}`;if(this.inFlight.has(l))continue;let u,c;try{[u,c]=await Promise.all([o.getReviews(i.owner,i.repo,i.prNumber),o.getPullRequest(i.owner,i.repo,i.prNumber)])}catch(w){y.warn(`review check failed for ${i.owner}/${i.repo}#${i.prNumber}: ${w instanceof Error?w.message:w}`);continue}if(!c)continue;let f={cfg:this.cfg,jiraFor:this.jiraFor,transport:this.transport};if(c.merged){y.info(`PR #${i.prNumber} for ${i.issueKey} was merged on GitHub - completing the run`),this.inFlight.add(l);try{await Rs(f,i.runId,c.headSha)}finally{this.inFlight.delete(l)}continue}if(c.state==="closed"){y.info(`PR #${i.prNumber} for ${i.issueKey} was closed unmerged on GitHub - failing the run`);let w=this.jiraFor(i.repoName),T=`PR #${i.prNumber} was closed on GitHub without merging`;await w.addComment(i.issueKey,`**Allwright: the pull request for this ticket was closed on GitHub without merging.**
722
739
 
723
740
  PR: ${i.prUrl}
724
741
 
725
- The run is marked failed. Remove the \`${i.failedLabel}\` label (or hit Retry on the Allwright board) to implement again. (run \`${i.runId}\`)`).catch(()=>{}),await w.editLabels(i.issueKey,{add:[i.failedLabel]}).catch(()=>{}),this.transport.send({type:"run.status",runId:i.runId,status:"failed",error:T}),er(i.runId);continue}c.mergeableState==="dirty"?(this.transport.send({type:"run.pr.conflict",runId:i.runId,conflicted:!0}),i.conflictNotified||(await this.jiraFor(i.repoName).addComment(i.issueKey,`**Allwright: the pull request for this ticket has merge conflicts.** The base branch moved after this change was built, so GitHub cannot merge it as-is.
742
+ The run is marked failed. Remove the \`${i.failedLabel}\` label (or hit Retry on the Allwright board) to implement again. (run \`${i.runId}\`)`).catch(()=>{}),await w.editLabels(i.issueKey,{add:[i.failedLabel]}).catch(()=>{}),this.transport.send({type:"run.status",runId:i.runId,status:"failed",error:T}),rr(i.runId);continue}c.mergeableState==="dirty"?(this.transport.send({type:"run.pr.conflict",runId:i.runId,conflicted:!0}),i.conflictNotified||(await this.jiraFor(i.repoName).addComment(i.issueKey,`**Allwright: the pull request for this ticket has merge conflicts.** The base branch moved after this change was built, so GitHub cannot merge it as-is.
726
743
 
727
744
  PR: ${i.prUrl}
728
745
 
729
- To fix: Reject this run on the Allwright dashboard (that closes the conflicted PR), then post the implement trigger comment again - a fresh run rebuilds the change on the current base. Or resolve the conflicts manually on branch \`${i.branch}\`; approval works normally once the PR is conflict-free. (run \`${i.runId}\`)`).catch(()=>{}),i.conflictNotified=!0,rt(i),y.info(`merge conflicts on PR #${i.prNumber} for ${i.issueKey} - ticket notified`))):c.mergeableState!==null&&c.mergeableState!=="unknown"&&(this.transport.send({type:"run.pr.conflict",runId:i.runId,conflicted:!1}),i.conflictNotified&&(i.conflictNotified=!1,rt(i)));let p=u.filter(w=>w.state==="APPROVED"||w.state==="CHANGES_REQUESTED").sort((w,T)=>w.submittedAt.localeCompare(T.submittedAt)),b=p[p.length-1];if(b){if(b.state==="CHANGES_REQUESTED"){i.changesRequestedNotified||(await this.jiraFor(i.repoName).addComment(i.issueKey,`**Allwright: changes were requested on the pull request** (by ${b.user}).
746
+ To fix: Reject this run on the Allwright dashboard (that closes the conflicted PR), then post the implement trigger comment again - a fresh run rebuilds the change on the current base. Or resolve the conflicts manually on branch \`${i.branch}\`; approval works normally once the PR is conflict-free. (run \`${i.runId}\`)`).catch(()=>{}),i.conflictNotified=!0,ot(i),y.info(`merge conflicts on PR #${i.prNumber} for ${i.issueKey} - ticket notified`))):c.mergeableState!==null&&c.mergeableState!=="unknown"&&(this.transport.send({type:"run.pr.conflict",runId:i.runId,conflicted:!1}),i.conflictNotified&&(i.conflictNotified=!1,ot(i)));let p=u.filter(w=>w.state==="APPROVED"||w.state==="CHANGES_REQUESTED").sort((w,T)=>w.submittedAt.localeCompare(T.submittedAt)),b=p[p.length-1];if(b){if(b.state==="CHANGES_REQUESTED"){i.changesRequestedNotified||(await this.jiraFor(i.repoName).addComment(i.issueKey,`**Allwright: changes were requested on the pull request** (by ${b.user}).
730
747
 
731
748
  PR: ${i.prUrl}
732
749
 
733
- Reply to the review on GitHub, or reject the run on the Allwright dashboard and re-trigger with new instructions. (run \`${i.runId}\`)`).catch(()=>{}),rt({...i,changesRequestedNotified:!0}),y.info(`changes requested on PR #${i.prNumber} for ${i.issueKey} - ticket notified`));continue}if(b.commitId===c.headSha){y.info(`PR #${i.prNumber} for ${i.issueKey} approved on GitHub by ${b.user} - completing the run`),this.inFlight.add(l);try{await ks(f,i.runId,b.commitId)}catch(w){y.warn(`github-approval completion failed for ${i.runId}: ${w instanceof Error?w.message:w}`)}finally{this.inFlight.delete(l)}}}}}async sweepMergedPRs(){let e=Object.values(Si());if(!e.length)return;let t=me()??this.cfg,r=new Map,s=l=>{let u=Te(t,l);if(!u)return null;let c=r.get(u);return c||r.set(u,c=new xe(u)),c},i=20,o=720*3600*1e3;for(let l of e.slice(0,i)){let u=s(l.repoName);if(!u)continue;if(Date.now()-new Date(l.createdAt).getTime()>o){y.warn(`merge watch for ${l.issueKey} PR #${l.prNumber} is over 30 days old - dropping`),bs(l.runId);continue}let c;try{c=await u.getPullRequest(l.owner,l.repo,l.prNumber)}catch(b){y.warn(`merge check failed for ${l.owner}/${l.repo}#${l.prNumber}: ${b instanceof Error?b.message:b}`);continue}if(!c){bs(l.runId);continue}if(c.state==="open")continue;if(!c.merged){bs(l.runId);continue}let f=this.jiraFor(l.repoName),p="";if(l.jiraTransitionOnMerge)try{p=await f.transitionByName(l.issueKey,l.jiraTransitionOnMerge)?`
750
+ Reply to the review on GitHub, or reject the run on the Allwright dashboard and re-trigger with new instructions. (run \`${i.runId}\`)`).catch(()=>{}),ot({...i,changesRequestedNotified:!0}),y.info(`changes requested on PR #${i.prNumber} for ${i.issueKey} - ticket notified`));continue}if(b.commitId===c.headSha){y.info(`PR #${i.prNumber} for ${i.issueKey} approved on GitHub by ${b.user} - completing the run`),this.inFlight.add(l);try{await Rs(f,i.runId,b.commitId)}catch(w){y.warn(`github-approval completion failed for ${i.runId}: ${w instanceof Error?w.message:w}`)}finally{this.inFlight.delete(l)}}}}}async sweepMergedPRs(){let e=Object.values(Ii());if(!e.length)return;let t=pe()??this.cfg,r=new Map,s=l=>{let u=Te(t,l);if(!u)return null;let c=r.get(u);return c||r.set(u,c=new xe(u)),c},i=20,o=720*3600*1e3;for(let l of e.slice(0,i)){let u=s(l.repoName);if(!u)continue;if(Date.now()-new Date(l.createdAt).getTime()>o){y.warn(`merge watch for ${l.issueKey} PR #${l.prNumber} is over 30 days old - dropping`),xs(l.runId);continue}let c;try{c=await u.getPullRequest(l.owner,l.repo,l.prNumber)}catch(b){y.warn(`merge check failed for ${l.owner}/${l.repo}#${l.prNumber}: ${b instanceof Error?b.message:b}`);continue}if(!c){xs(l.runId);continue}if(c.state==="open")continue;if(!c.merged){xs(l.runId);continue}let f=this.jiraFor(l.repoName),p="";if(l.jiraTransitionOnMerge)try{p=await f.transitionByName(l.issueKey,l.jiraTransitionOnMerge)?`
734
751
 
735
752
  Ticket moved to **${l.jiraTransitionOnMerge}**.`:`
736
753
 
@@ -740,15 +757,15 @@ Note: the "${l.jiraTransitionOnMerge}" transition failed: ${b instanceof Error?b
740
757
 
741
758
  PR: ${l.prUrl} (merged at \`${c.headSha.slice(0,10)}\`)${p}
742
759
 
743
- (run \`${l.runId}\`)`)}catch(b){y.warn(`could not post merge comment to ${l.issueKey}: ${b instanceof Error?b.message:b}`);continue}y.info(`PR #${l.prNumber} for ${l.issueKey} merged - ticket updated`),bs(l.runId)}}async sweepNeedsInput(e){let t;try{t=await this.jiraOf(e).search(`project = "${e.jiraProjectKey}" AND labels = "${ar.NEEDS_INPUT_LABEL}"`,10)}catch(s){y.warn(`needs-input sweep failed for ${e.jiraProjectKey}: ${s instanceof Error?s.message:s}`);return}if(!t.length)return;let r=Zr();for(let s of t){let i=Object.values(r).filter(l=>l.issueKey===s.key);if(!i.length){await this.jiraOf(e).editLabels(s.key,{remove:[ar.NEEDS_INPUT_LABEL]}).catch(()=>{}),y.warn(`${s.key}: needs-input label with no local pending record - removed`);continue}let o=null;for(let l of i){let u=`resume:${l.runId}`;if(this.inFlight.has(u))continue;if(Date.now()-new Date(l.createdAt).getTime()>Gg){this.inFlight.add(u),this.abandonStaleInput(l,e).finally(()=>this.inFlight.delete(u));continue}try{o=o??await this.jiraOf(e).getIssue(s.key)}catch(T){y.warn(`needs-input check failed for ${s.key}: ${T instanceof Error?T.message:T}`);continue}let c=new Date(l.questionsPostedAt).getTime(),f=o.comments.filter(T=>!mt(T.body)&&new Date(T.created).getTime()>c);if(!f.length)continue;let p=Ss(f),b=o.attachments;this.inFlight.add(u),y.info(`reply received on ${s.key} - resuming run ${l.runId}`),await this.jiraOf(e).editLabels(s.key,{remove:[ar.NEEDS_INPUT_LABEL]}).catch(T=>{y.warn(`could not remove needs-input label on ${s.key}: ${T}`)});let w={jiraFor:this.jiraFor,transport:this.transport,cfg:this.cfg};l.kind==="implement"?this.enqueueForRepo(l.baseRepoPath??l.repoPath,async()=>{try{await Rc(l,p,b,w)}finally{this.inFlight.delete(u)}}):this.enqueueForRepo(l.repoPath,async()=>{try{await Tc(l,p,b,w)}finally{this.inFlight.delete(u)}})}}}async abandonStaleInput(e,t){y.warn(`${e.issueKey}: needs-input unanswered for over ${ji}d - abandoning run ${e.runId}`);try{await this.jiraOf(t).addComment(e.issueKey,`**Allwright gave up waiting for an answer.**
760
+ (run \`${l.runId}\`)`)}catch(b){y.warn(`could not post merge comment to ${l.issueKey}: ${b instanceof Error?b.message:b}`);continue}y.info(`PR #${l.prNumber} for ${l.issueKey} merged - ticket updated`),xs(l.runId)}}async sweepNeedsInput(e){let t;try{t=await this.jiraOf(e).search(`project = "${e.jiraProjectKey}" AND labels = "${cr.NEEDS_INPUT_LABEL}"`,10)}catch(s){y.warn(`needs-input sweep failed for ${e.jiraProjectKey}: ${s instanceof Error?s.message:s}`);return}if(!t.length)return;let r=Wr();for(let s of t){let i=Object.values(r).filter(l=>l.issueKey===s.key);if(!i.length){await this.jiraOf(e).editLabels(s.key,{remove:[cr.NEEDS_INPUT_LABEL]}).catch(()=>{}),y.warn(`${s.key}: needs-input label with no local pending record - removed`);continue}let o=null;for(let l of i){let u=`resume:${l.runId}`;if(this.inFlight.has(u))continue;if(Date.now()-new Date(l.createdAt).getTime()>oy){this.inFlight.add(u),this.abandonStaleInput(l,e).finally(()=>this.inFlight.delete(u));continue}try{o=o??await this.jiraOf(e).getIssue(s.key)}catch(T){y.warn(`needs-input check failed for ${s.key}: ${T instanceof Error?T.message:T}`);continue}let c=new Date(l.questionsPostedAt).getTime(),f=o.comments.filter(T=>!yt(T.body)&&new Date(T.created).getTime()>c);if(!f.length)continue;let p=Es(f),b=o.attachments;this.inFlight.add(u),y.info(`reply received on ${s.key} - resuming run ${l.runId}`),await this.jiraOf(e).editLabels(s.key,{remove:[cr.NEEDS_INPUT_LABEL]}).catch(T=>{y.warn(`could not remove needs-input label on ${s.key}: ${T}`)});let w={jiraFor:this.jiraFor,transport:this.transport,cfg:this.cfg};l.kind==="implement"?this.enqueueForRepo(l.baseRepoPath??l.repoPath,async()=>{try{await Dc(l,p,b,w)}finally{this.inFlight.delete(u)}}):this.enqueueForRepo(l.repoPath,async()=>{try{await Oc(l,p,b,w)}finally{this.inFlight.delete(u)}})}}}async abandonStaleInput(e,t){y.warn(`${e.issueKey}: needs-input unanswered for over ${zi}d - abandoning run ${e.runId}`);try{await this.jiraOf(t).addComment(e.issueKey,`**Allwright gave up waiting for an answer.**
744
761
 
745
- No reply arrived within ${ji} days of the question above. This ticket has been labeled \`${e.failedLabel}\`; remove it and re-trigger to try again. (run \`${e.runId}\`)`),await this.jiraOf(t).editLabels(e.issueKey,{add:[e.failedLabel],remove:[ar.NEEDS_INPUT_LABEL]})}catch(r){y.warn(`could not post staleness notice for ${e.issueKey}: ${r}`)}e.kind==="implement"&&await ft(e.baseRepoPath??e.repoPath,e.repoPath).catch(()=>{}),yt(e.runId),this.transport.send({type:"run.status",runId:e.runId,status:"failed",error:`no reply within ${ji} days`})}async pollRule(e,t,r){let s=e.trigger.type==="label_added"?await this.matchLabelTrigger(e,t):await this.matchCommentTrigger(e,t);for(let i of s){let o=`${e.id}:${i.issueKey}`;if(this.inFlight.has(o))continue;let l=Pi(t,i.components??[]);if("error"in l){this.warnRoutingOnce(`${e.id}:${i.issueKey}`,`${i.issueKey}: ${l.error}`);continue}let u=l.project,c=u.repoName===t.repoName?r:this.cfg.repos[u.repoName]?.path;if(!c){this.warnRoutingOnce(`${e.id}:${i.issueKey}:path`,`${i.issueKey}: routed to repo "${u.repoName}" but it has no local checkout - run: allwright repo add "${u.repoName}" /path/to/checkout`);continue}let f=await this.transport.claimRun({ruleId:e.id,issueKey:i.issueKey,issueSummary:i.summary,triggerFingerprint:i.fingerprint,triggeredByAccountId:i.triggeredByAccountId});if(!f.accepted||!f.runId){f.reason!=="duplicate"&&y.warn(`claim rejected for ${i.issueKey}: ${f.reason??"unknown"}`);continue}this.inFlight.add(o),y.info(`claimed run ${f.runId} for ${i.issueKey}`+(u.repoName!==t.repoName?` (routed \u2192 ${u.repoName})`:"")+(f.claudeProfile?` (claude profile "${f.claudeProfile}")`:""));let p=this.resolveClaudeProfile(f.runId,f.claudeProfile);this.enqueueForRepo(c,async()=>{try{await Ri({runId:f.runId,rule:e,project:u,issueKey:i.issueKey,repoPath:c,cfg:this.cfg,jira:this.jiraOf(u),transport:this.transport,claudeConfigDir:p,actorEmail:f.actorEmail})}finally{this.inFlight.delete(o)}})}}async pollRespondRule(e,t,r){let s=e.trigger;if(s.type!=="comment_keyword"||e.action.type!=="respond")return;let i=await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=s.keyword.toLowerCase(),l=Date.now()-ed;for(let u of i){let c=await this.jiraOf(t).getIssue(u.key);for(let f of c.comments){if(!f.body.toLowerCase().includes(o)||mt(f.body)||new Date(f.created).getTime()<l||!f.id)continue;let p=`respond:${f.id}`;if(this.inFlight.has(p))continue;let b=Pi(t,u.components??[]);if("error"in b){this.warnRoutingOnce(`${e.id}:${u.key}`,`${u.key}: ${b.error}`);continue}let w=b.project,T=w.repoName===t.repoName?r:this.cfg.repos[w.repoName]?.path;if(!T){this.warnRoutingOnce(`${e.id}:${u.key}:path`,`${u.key}: routed to repo "${w.repoName}" but it has no local checkout - run: allwright repo add "${w.repoName}" /path/to/checkout`);continue}let x=await this.transport.claimRun({ruleId:e.id,issueKey:u.key,issueSummary:u.summary,triggerFingerprint:`question by ${f.author} at ${f.created}`,dedupKey:`respond:comment:${f.id}`,triggeredByAccountId:f.authorAccountId??void 0});if(!x.accepted||!x.runId){x.reason!=="duplicate"&&y.warn(`respond claim rejected for ${u.key}: ${x.reason??"unknown"}`);continue}this.inFlight.add(p),y.info(`claimed respond run ${x.runId}: ${u.key} (comment ${f.id})`+(w.repoName!==t.repoName?` (routed \u2192 ${w.repoName})`:"")+(x.claudeProfile?` (claude profile "${x.claudeProfile}")`:""));let A={author:f.author,body:f.body},v=this.resolveClaudeProfile(x.runId,x.claudeProfile);this.enqueueForRepo(T,async()=>{try{await Ri({runId:x.runId,rule:e,project:w,issueKey:u.key,repoPath:T,cfg:this.cfg,jira:this.jiraOf(w),transport:this.transport,question:A,claudeConfigDir:v,actorEmail:x.actorEmail})}finally{this.inFlight.delete(p)}})}}}async sweepRevisions(e,t){let r=e.trigger;if(r.type!=="comment_keyword")return;let s;try{s=await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND labels = "${r.doneLabel}" AND updated >= "-2d"`,10)}catch(o){y.warn(`revision sweep failed for ${t.jiraProjectKey}: ${o instanceof Error?o.message:o}`);return}let i=r.keyword.toLowerCase();for(let o of s)try{let l=await this.jiraOf(t).getIssue(o.key),u=null;for(let f of l.comments)mt(f.body)&&(u=Math.max(u??0,new Date(f.created).getTime()));if(u===null||!l.comments.some(f=>!mt(f.body)&&f.body.toLowerCase().includes(i)&&new Date(f.created).getTime()>u))continue;await this.jiraOf(t).editLabels(o.key,{remove:[r.doneLabel]}),y.info(`revision requested on ${o.key} (new "${r.keyword}" after completion) - done label removed, rule will re-fire`)}catch(l){y.warn(`revision check failed for ${o.key}: ${l instanceof Error?l.message:l}`)}}async pollDeployRule(e,t,r){if(e.action.type!=="deploy")return;let s=e.trigger.type==="status_changed"?await this.matchStatusDeploys(e,t):await this.matchCommentDeploys(e,t);for(let i of s){let o=`deploy:${i.dedupKey}`;if(this.inFlight.has(o))continue;let l=await this.transport.claimDeploy({projectId:t.id,ruleId:e.id,issueKey:i.issueKey,issueSummary:i.summary,environmentName:i.environmentName,requestedByAccountId:i.requestedByAccountId,requestedByDisplayName:i.requestedByDisplayName,dedupKey:i.dedupKey,triggerFingerprint:i.fingerprint});if(!l.accepted||!l.runId||!l.environment){if(l.code==="duplicate")continue;l.reason&&l.runId?(await this.jiraOf(t).addComment(i.issueKey,`**Allwright did not deploy this ticket.**
762
+ No reply arrived within ${zi} days of the question above. This ticket has been labeled \`${e.failedLabel}\`; remove it and re-trigger to try again. (run \`${e.runId}\`)`),await this.jiraOf(t).editLabels(e.issueKey,{add:[e.failedLabel],remove:[cr.NEEDS_INPUT_LABEL]})}catch(r){y.warn(`could not post staleness notice for ${e.issueKey}: ${r}`)}e.kind==="implement"&&await mt(e.baseRepoPath??e.repoPath,e.repoPath).catch(()=>{}),bt(e.runId),this.transport.send({type:"run.status",runId:e.runId,status:"failed",error:`no reply within ${zi} days`})}async pollRule(e,t,r){let s=e.trigger.type==="label_added"?await this.matchLabelTrigger(e,t):await this.matchCommentTrigger(e,t);for(let i of s){let o=`${e.id}:${i.issueKey}`;if(this.inFlight.has(o))continue;let l=Mi(t,i.components??[]);if("error"in l){this.warnRoutingOnce(`${e.id}:${i.issueKey}`,`${i.issueKey}: ${l.error}`);continue}let u=l.project,c=u.repoName===t.repoName?r:this.cfg.repos[u.repoName]?.path;if(!c){this.warnRoutingOnce(`${e.id}:${i.issueKey}:path`,`${i.issueKey}: routed to repo "${u.repoName}" but it has no local checkout - run: allwright repo add "${u.repoName}" /path/to/checkout`);continue}let f=await this.transport.claimRun({ruleId:e.id,issueKey:i.issueKey,issueSummary:i.summary,triggerFingerprint:i.fingerprint,triggeredByAccountId:i.triggeredByAccountId});if(!f.accepted||!f.runId){f.reason!=="duplicate"&&y.warn(`claim rejected for ${i.issueKey}: ${f.reason??"unknown"}`);continue}this.inFlight.add(o),y.info(`claimed run ${f.runId} for ${i.issueKey}`+(u.repoName!==t.repoName?` (routed \u2192 ${u.repoName})`:"")+(f.claudeProfile?` (claude profile "${f.claudeProfile}")`:""));let p=this.resolveClaudeProfile(f.runId,f.claudeProfile);this.enqueueForRepo(c,async()=>{try{await Pi({runId:f.runId,rule:e,project:u,issueKey:i.issueKey,repoPath:c,cfg:this.cfg,jira:this.jiraOf(u),transport:this.transport,claudeConfigDir:p,actorEmail:f.actorEmail})}finally{this.inFlight.delete(o)}})}}async pollRespondRule(e,t,r){let s=e.trigger;if(s.type!=="comment_keyword"||e.action.type!=="respond")return;let i=await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=s.keyword.toLowerCase(),l=Date.now()-cd;for(let u of i){let c=await this.jiraOf(t).getIssue(u.key);for(let f of c.comments){if(!f.body.toLowerCase().includes(o)||yt(f.body)||new Date(f.created).getTime()<l||!f.id)continue;let p=`respond:${f.id}`;if(this.inFlight.has(p))continue;let b=Mi(t,u.components??[]);if("error"in b){this.warnRoutingOnce(`${e.id}:${u.key}`,`${u.key}: ${b.error}`);continue}let w=b.project,T=w.repoName===t.repoName?r:this.cfg.repos[w.repoName]?.path;if(!T){this.warnRoutingOnce(`${e.id}:${u.key}:path`,`${u.key}: routed to repo "${w.repoName}" but it has no local checkout - run: allwright repo add "${w.repoName}" /path/to/checkout`);continue}let C=await this.transport.claimRun({ruleId:e.id,issueKey:u.key,issueSummary:u.summary,triggerFingerprint:`question by ${f.author} at ${f.created}`,dedupKey:`respond:comment:${f.id}`,triggeredByAccountId:f.authorAccountId??void 0});if(!C.accepted||!C.runId){C.reason!=="duplicate"&&y.warn(`respond claim rejected for ${u.key}: ${C.reason??"unknown"}`);continue}this.inFlight.add(p),y.info(`claimed respond run ${C.runId}: ${u.key} (comment ${f.id})`+(w.repoName!==t.repoName?` (routed \u2192 ${w.repoName})`:"")+(C.claudeProfile?` (claude profile "${C.claudeProfile}")`:""));let A={author:f.author,body:f.body},v=this.resolveClaudeProfile(C.runId,C.claudeProfile);this.enqueueForRepo(T,async()=>{try{await Pi({runId:C.runId,rule:e,project:w,issueKey:u.key,repoPath:T,cfg:this.cfg,jira:this.jiraOf(w),transport:this.transport,question:A,claudeConfigDir:v,actorEmail:C.actorEmail})}finally{this.inFlight.delete(p)}})}}}async sweepRevisions(e,t){let r=e.trigger;if(r.type!=="comment_keyword")return;let s;try{s=await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND labels = "${r.doneLabel}" AND updated >= "-2d"`,10)}catch(o){y.warn(`revision sweep failed for ${t.jiraProjectKey}: ${o instanceof Error?o.message:o}`);return}let i=r.keyword.toLowerCase();for(let o of s)try{let l=await this.jiraOf(t).getIssue(o.key),u=null;for(let f of l.comments)yt(f.body)&&(u=Math.max(u??0,new Date(f.created).getTime()));if(u===null||!l.comments.some(f=>!yt(f.body)&&f.body.toLowerCase().includes(i)&&new Date(f.created).getTime()>u))continue;await this.jiraOf(t).editLabels(o.key,{remove:[r.doneLabel]}),y.info(`revision requested on ${o.key} (new "${r.keyword}" after completion) - done label removed, rule will re-fire`)}catch(l){y.warn(`revision check failed for ${o.key}: ${l instanceof Error?l.message:l}`)}}async pollDeployRule(e,t,r){if(e.action.type!=="deploy")return;let s=e.trigger.type==="status_changed"?await this.matchStatusDeploys(e,t):await this.matchCommentDeploys(e,t);for(let i of s){let o=`deploy:${i.dedupKey}`;if(this.inFlight.has(o))continue;let l=await this.transport.claimDeploy({projectId:t.id,ruleId:e.id,issueKey:i.issueKey,issueSummary:i.summary,environmentName:i.environmentName,requestedByAccountId:i.requestedByAccountId,requestedByDisplayName:i.requestedByDisplayName,dedupKey:i.dedupKey,triggerFingerprint:i.fingerprint});if(!l.accepted||!l.runId||!l.environment){if(l.code==="duplicate")continue;l.reason&&l.runId?(await this.jiraOf(t).addComment(i.issueKey,`**Allwright did not deploy this ticket.**
746
763
 
747
764
  ${l.reason}`+(i.requestedByAccountId?`
748
765
 
749
766
  Jira account id: \`${i.requestedByAccountId}\``:"")+`
750
767
 
751
- (run \`${l.runId}\`)`).catch(c=>y.warn(`could not post refusal to ${i.issueKey}: ${c}`)),y.warn(`deploy refused for ${i.issueKey}: ${l.reason}`)):l.reason&&y.warn(`deploy claim rejected for ${i.issueKey}: ${l.reason}`);continue}let u=l.environment;this.inFlight.add(o),y.info(`claimed deploy ${l.runId}: ${i.issueKey} \u2192 ${u.name}`),this.enqueue(this.envQueues,u.id,async()=>{try{await Ai({runId:l.runId,project:t,environment:u,issueKey:i.issueKey,issueSummary:i.summary,repoPath:r,cfg:this.cfg,jira:this.jiraOf(t),transport:this.transport,requestedBy:i.requestedByDisplayName})}finally{this.inFlight.delete(o)}})}}async matchCommentDeploys(e,t){let r=e.trigger,s=e.action;if(r.type!=="comment_keyword"||s.type!=="deploy")return[];let i=await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=r.keyword.toLowerCase(),l=Date.now()-ed,u=this.environments.filter(p=>p.projectId===t.id).map(p=>p.name),c=this.fixedEnvironmentName(s.environmentId),f=[];for(let p of i){let b=await this.jiraOf(t).getIssue(p.key);if(!(s.requireStatus&&b.status.toLowerCase()!==s.requireStatus.toLowerCase()))for(let w of b.comments){if(!w.body.toLowerCase().includes(o)||mt(w.body)||new Date(w.created).getTime()<l||!w.id)continue;let T=s.envSelection==="fixed"?c:Vg(w.body,r.keyword,u);f.push({issueKey:p.key,summary:p.summary,environmentName:T,requestedByAccountId:w.authorAccountId??void 0,requestedByDisplayName:w.author,dedupKey:`deploy:comment:${w.id}`,fingerprint:`comment "${r.keyword}" by ${w.author} at ${w.created}`+(T?` \u2192 ${T}`:"")})}}return f}async matchStatusDeploys(e,t){let r=e.trigger,s=e.action;if(r.type!=="status_changed"||s.type!=="deploy")return[];let i=await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND status = "${r.status}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=this.fixedEnvironmentName(s.environmentId),l=[];for(let u of i){let c=await this.jiraOf(t).lastEnteredStatus(u.key,r.status);c&&l.push({issueKey:u.key,summary:u.summary,environmentName:o,requestedByAccountId:c.authorAccountId??void 0,requestedByDisplayName:c.author,dedupKey:`deploy:status:${e.id}:${u.key}:${c.at}`,fingerprint:`moved to "${r.status}" by ${c.author} at ${c.at}`})}return l}fixedEnvironmentName(e){return e?this.environments.find(t=>t.id===e)?.name??"":""}async matchLabelTrigger(e,t){let r=e.trigger;if(r.type!=="label_added")return[];let s=`project = "${t.jiraProjectKey}" AND labels = "${r.label}" AND labels not in ("${r.doneLabel}", "${r.failedLabel}", "${ar.NEEDS_INPUT_LABEL}") ORDER BY updated ASC`;return(await this.jiraOf(t).search(s,10)).map(o=>({issueKey:o.key,summary:o.summary,components:o.components,fingerprint:`label "${r.label}" matched at ${new Date().toISOString()}`}))}async matchCommentTrigger(e,t){let r=e.trigger;if(r.type!=="comment_keyword")return[];let s=`project = "${t.jiraProjectKey}" AND updated >= "-2d" AND (labels IS EMPTY OR labels not in ("${r.doneLabel}", "${r.failedLabel}", "${ar.NEEDS_INPUT_LABEL}")) ORDER BY updated DESC`,i=await this.jiraOf(t).search(s,10),o=r.keyword.toLowerCase(),l=[];for(let u of i){let f=[...(await this.jiraOf(t).getIssue(u.key)).comments].reverse().find(p=>p.body.toLowerCase().includes(o)&&!mt(p.body));f&&l.push({issueKey:u.key,components:u.components,summary:u.summary,fingerprint:`comment keyword "${r.keyword}" by ${f.author} at ${f.created}`,triggeredByAccountId:f.authorAccountId??void 0})}return l}async diagnoseRule(e,t){let r=e.trigger;if(e.action.type==="deploy"){let u=r.type==="status_changed"?await this.matchStatusDeploys(e,t):await this.matchCommentDeploys(e,t),c=u.filter(f=>f.environmentName);return{matchedCount:c.length,excludedCount:u.length-c.length,excludedSample:u.filter(f=>!f.environmentName).slice(0,5).map(f=>f.issueKey)}}if(r.type==="status_changed")return{matchedCount:(await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND status = "${r.status}"`,50)).length,excludedCount:0,excludedSample:[]};if(r.type==="label_added"){let[u,c]=await Promise.all([this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND labels = "${r.label}" AND labels not in ("${r.doneLabel}", "${r.failedLabel}")`,50),this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND labels = "${r.label}" AND labels in ("${r.doneLabel}", "${r.failedLabel}")`,50)]);return{matchedCount:u.length,excludedCount:c.length,excludedSample:c.slice(0,5).map(f=>f.key)}}let s=r.keyword.toLowerCase(),[i,o]=await Promise.all([this.matchCommentTrigger(e,t),this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND updated >= "-2d" AND labels in ("${r.doneLabel}", "${r.failedLabel}")`,50)]),l=[];for(let u of o)(await this.jiraOf(t).getIssue(u.key)).comments.some(f=>f.body.toLowerCase().includes(s))&&l.push(u.key);return{matchedCount:i.length,excludedCount:l.length,excludedSample:l.slice(0,5)}}enqueueForRepo(e,t){this.enqueue(this.repoQueues,e,t)}runOnRepoQueue(e,t){this.enqueue(this.repoQueues,e,t)}runOnEnvironmentQueue(e,t){this.enqueue(this.envQueues,e,t)}enqueue(e,t,r){let i=(e.get(t)??Promise.resolve()).then(async()=>{this.activeWork++;try{await r()}finally{this.activeWork--}}).catch(o=>{y.error(`run crashed: ${o instanceof Error?o.stack:o}`)});e.set(t,i)}};function Vg(n,e,t){let r=n.toLowerCase().indexOf(e.toLowerCase());if(r<0)return"";let i=n.slice(r+e.length).split(/[^\w.-]+/).filter(Boolean);for(let o of i){let l=t.find(u=>u.toLowerCase()===o.toLowerCase());if(l)return l}for(let o of i)if(!Hg.has(o.toLowerCase()))return o;return""}var td=R(require("node:fs"),1),nd=R(require("node:path"),1),xa=require("node:crypto");pt();var Wg=`This repository is in the middle of a git merge: the base branch moved and some files conflict with the change on this branch. Your ONLY job is to resolve those conflicts.
768
+ (run \`${l.runId}\`)`).catch(c=>y.warn(`could not post refusal to ${i.issueKey}: ${c}`)),y.warn(`deploy refused for ${i.issueKey}: ${l.reason}`)):l.reason&&y.warn(`deploy claim rejected for ${i.issueKey}: ${l.reason}`);continue}let u=l.environment;this.inFlight.add(o),y.info(`claimed deploy ${l.runId}: ${i.issueKey} \u2192 ${u.name}`),this.enqueue(this.envQueues,u.id,async()=>{try{await Oi({runId:l.runId,project:t,environment:u,issueKey:i.issueKey,issueSummary:i.summary,repoPath:r,cfg:this.cfg,jira:this.jiraOf(t),transport:this.transport,requestedBy:i.requestedByDisplayName})}finally{this.inFlight.delete(o)}})}}async matchCommentDeploys(e,t){let r=e.trigger,s=e.action;if(r.type!=="comment_keyword"||s.type!=="deploy")return[];let i=await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=r.keyword.toLowerCase(),l=Date.now()-cd,u=this.environments.filter(p=>p.projectId===t.id).map(p=>p.name),c=this.fixedEnvironmentName(s.environmentId),f=[];for(let p of i){let b=await this.jiraOf(t).getIssue(p.key);if(!(s.requireStatus&&b.status.toLowerCase()!==s.requireStatus.toLowerCase()))for(let w of b.comments){if(!w.body.toLowerCase().includes(o)||yt(w.body)||new Date(w.created).getTime()<l||!w.id)continue;let T=s.envSelection==="fixed"?c:ly(w.body,r.keyword,u);f.push({issueKey:p.key,summary:p.summary,environmentName:T,requestedByAccountId:w.authorAccountId??void 0,requestedByDisplayName:w.author,dedupKey:`deploy:comment:${w.id}`,fingerprint:`comment "${r.keyword}" by ${w.author} at ${w.created}`+(T?` \u2192 ${T}`:"")})}}return f}async matchStatusDeploys(e,t){let r=e.trigger,s=e.action;if(r.type!=="status_changed"||s.type!=="deploy")return[];let i=await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND status = "${r.status}" AND updated >= "-2d" ORDER BY updated DESC`,15),o=this.fixedEnvironmentName(s.environmentId),l=[];for(let u of i){let c=await this.jiraOf(t).lastEnteredStatus(u.key,r.status);c&&l.push({issueKey:u.key,summary:u.summary,environmentName:o,requestedByAccountId:c.authorAccountId??void 0,requestedByDisplayName:c.author,dedupKey:`deploy:status:${e.id}:${u.key}:${c.at}`,fingerprint:`moved to "${r.status}" by ${c.author} at ${c.at}`})}return l}fixedEnvironmentName(e){return e?this.environments.find(t=>t.id===e)?.name??"":""}async matchLabelTrigger(e,t){let r=e.trigger;if(r.type!=="label_added")return[];let s=`project = "${t.jiraProjectKey}" AND labels = "${r.label}" AND labels not in ("${r.doneLabel}", "${r.failedLabel}", "${cr.NEEDS_INPUT_LABEL}") ORDER BY updated ASC`;return(await this.jiraOf(t).search(s,10)).map(o=>({issueKey:o.key,summary:o.summary,components:o.components,fingerprint:`label "${r.label}" matched at ${new Date().toISOString()}`}))}async matchCommentTrigger(e,t){let r=e.trigger;if(r.type!=="comment_keyword")return[];let s=`project = "${t.jiraProjectKey}" AND updated >= "-2d" AND (labels IS EMPTY OR labels not in ("${r.doneLabel}", "${r.failedLabel}", "${cr.NEEDS_INPUT_LABEL}")) ORDER BY updated DESC`,i=await this.jiraOf(t).search(s,10),o=r.keyword.toLowerCase(),l=[];for(let u of i){let f=[...(await this.jiraOf(t).getIssue(u.key)).comments].reverse().find(p=>p.body.toLowerCase().includes(o)&&!yt(p.body));f&&l.push({issueKey:u.key,components:u.components,summary:u.summary,fingerprint:`comment keyword "${r.keyword}" by ${f.author} at ${f.created}`,triggeredByAccountId:f.authorAccountId??void 0})}return l}async diagnoseRule(e,t){let r=e.trigger;if(e.action.type==="deploy"){let u=r.type==="status_changed"?await this.matchStatusDeploys(e,t):await this.matchCommentDeploys(e,t),c=u.filter(f=>f.environmentName);return{matchedCount:c.length,excludedCount:u.length-c.length,excludedSample:u.filter(f=>!f.environmentName).slice(0,5).map(f=>f.issueKey)}}if(r.type==="status_changed")return{matchedCount:(await this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND status = "${r.status}"`,50)).length,excludedCount:0,excludedSample:[]};if(r.type==="label_added"){let[u,c]=await Promise.all([this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND labels = "${r.label}" AND labels not in ("${r.doneLabel}", "${r.failedLabel}")`,50),this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND labels = "${r.label}" AND labels in ("${r.doneLabel}", "${r.failedLabel}")`,50)]);return{matchedCount:u.length,excludedCount:c.length,excludedSample:c.slice(0,5).map(f=>f.key)}}let s=r.keyword.toLowerCase(),[i,o]=await Promise.all([this.matchCommentTrigger(e,t),this.jiraOf(t).search(`project = "${t.jiraProjectKey}" AND updated >= "-2d" AND labels in ("${r.doneLabel}", "${r.failedLabel}")`,50)]),l=[];for(let u of o)(await this.jiraOf(t).getIssue(u.key)).comments.some(f=>f.body.toLowerCase().includes(s))&&l.push(u.key);return{matchedCount:i.length,excludedCount:l.length,excludedSample:l.slice(0,5)}}enqueueForRepo(e,t){this.enqueue(this.repoQueues,e,t)}runOnRepoQueue(e,t){this.enqueue(this.repoQueues,e,t)}runOnEnvironmentQueue(e,t){this.enqueue(this.envQueues,e,t)}enqueue(e,t,r){let i=(e.get(t)??Promise.resolve()).then(async()=>{this.activeWork++;try{await r()}finally{this.activeWork--}}).catch(o=>{y.error(`run crashed: ${o instanceof Error?o.stack:o}`)});e.set(t,i)}};function ly(n,e,t){let r=n.toLowerCase().indexOf(e.toLowerCase());if(r<0)return"";let i=n.slice(r+e.length).split(/[^\w.-]+/).filter(Boolean);for(let o of i){let l=t.find(u=>u.toLowerCase()===o.toLowerCase());if(l)return l}for(let o of i)if(!ay.has(o.toLowerCase()))return o;return""}var dd=R(require("node:fs"),1),hd=R(require("node:path"),1),Pa=require("node:crypto");gt();var uy=`This repository is in the middle of a git merge: the base branch moved and some files conflict with the change on this branch. Your ONLY job is to resolve those conflicts.
752
769
 
753
770
  Rules:
754
771
  - Edit ONLY the conflicted files listed below. Do not touch anything else, do not refactor, do not "improve" surrounding code.
@@ -757,10 +774,10 @@ Rules:
757
774
  - When you are done, every listed file must contain no conflict markers and must be syntactically valid.
758
775
 
759
776
  Conflicted files:
760
- `;async function rd(n){let{cfg:e,repoPath:t,branch:r,baseBranch:s,issueKey:i,onLog:o}=n,l=nd.default.join(Pt(),`conflict-${(0,xa.randomUUID)().slice(0,8)}`),u=!1;try{o("info",`Preparing a worktree for ${r} to merge ${s} into it`),await gs(t,l,r),u=!0;let c=await Fo(l,s);if(c.ok&&c.alreadyUpToDate)return o("info",`${r} already contains ${s} - nothing to merge`),{ok:!0,freeOfCharge:!0,note:`This branch already contains ${s}, so there was nothing to merge - GitHub's conflict flag was out of date. Refresh the PR.`};if(!c.ok&&c.conflicts===null)return{ok:!1,note:`The merge could not even be started: ${c.reason}`};let f={},p=!1;if(!c.ok){let T=c.conflicts;o("info",`git merged everything except ${T.length} file(s): ${T.slice(0,20).join(", ")}`+(T.length>20?", \u2026":""));let x=Me(n.agentId);if(!x)return await sn(l),{ok:!1,note:`no adapter for agent "${n.agentId}" on this runner`};let A=on(n.agentId,"edit_no_shell");if(A)return await sn(l),{ok:!1,note:`${A} Resolve the conflicts yourself on branch ${r}, or use Rebuild on current base.`};o("info",`Asking ${x.displayName} to resolve only those files`);let v=-1,Z=setInterval(()=>{Ko(l,T).then(z=>{let h=T.filter(m=>!z.includes(m));h.length!==v&&(v=h.length,o("info",`Conflict progress: ${h.length}/${T.length} resolved`+(h.length?` \xB7 clean: ${h.join(", ")}`:"")+(z.length?` \xB7 still conflicted: ${z.join(", ")}`:"")))}).catch(()=>{})},12e3),M=await _s(x,{repoPath:l,prompt:Wg+T.map(z=>`- ${z}`).join(`
761
- `),timeoutSeconds:n.timeoutSeconds,bin:je(e,n.agentId),configDir:n.configDir,mode:"edit_no_shell",sessionId:(0,xa.randomUUID)(),onLog:(z,h)=>o(z,h)},(z,h)=>o(z==="warn"?"warn":z,h));if(clearInterval(Z),f={costUsd:M.costUsd,inputTokens:M.inputTokens,outputTokens:M.outputTokens},!M.ok)return await sn(l),{ok:!1,...f,note:`The agent could not do the resolution: ${M.error??"it produced no output"}. Nothing was changed - the merge was rolled back. Fix that first, then Resolve again.`};p=!0;let L=await pi(l);if(L.length)return await sn(l),{ok:!1,...f,note:`The agent left conflict markers in ${L.slice(0,5).join(", ")}, so nothing was pushed and the merge was rolled back. Resolve it by hand on ${r}, or use Rebuild on current base to redo the ticket against today's base.`};await Bo(l,`${i}: merge ${s}, conflicts resolved by the agent
777
+ `;async function fd(n){let{cfg:e,repoPath:t,branch:r,baseBranch:s,issueKey:i,onLog:o}=n,l=hd.default.join(Nt(),`conflict-${(0,Pa.randomUUID)().slice(0,8)}`),u=!1;try{o("info",`Preparing a worktree for ${r} to merge ${s} into it`),await _s(t,l,r),u=!0;let c=await Ho(l,s);if(c.ok&&c.alreadyUpToDate)return o("info",`${r} already contains ${s} - nothing to merge`),{ok:!0,freeOfCharge:!0,note:`This branch already contains ${s}, so there was nothing to merge - GitHub's conflict flag was out of date. Refresh the PR.`};if(!c.ok&&c.conflicts===null)return{ok:!1,note:`The merge could not even be started: ${c.reason}`};let f={},p=!1;if(!c.ok){let T=c.conflicts;o("info",`git merged everything except ${T.length} file(s): ${T.slice(0,20).join(", ")}`+(T.length>20?", \u2026":""));let C=De(n.agentId);if(!C)return await an(l),{ok:!1,note:`no adapter for agent "${n.agentId}" on this runner`};let A=ln(n.agentId,"edit_no_shell");if(A)return await an(l),{ok:!1,note:`${A} Resolve the conflicts yourself on branch ${r}, or use Rebuild on current base.`};o("info",`Asking ${C.displayName} to resolve only those files`);let v=-1,B=setInterval(()=>{Wo(l,T).then(K=>{let h=T.filter(m=>!K.includes(m));h.length!==v&&(v=h.length,o("info",`Conflict progress: ${h.length}/${T.length} resolved`+(h.length?` \xB7 clean: ${h.join(", ")}`:"")+(K.length?` \xB7 still conflicted: ${K.join(", ")}`:"")))}).catch(()=>{})},12e3),N=await Is(C,{repoPath:l,prompt:uy+T.map(K=>`- ${K}`).join(`
778
+ `),timeoutSeconds:n.timeoutSeconds,bin:Oe(e,n.agentId),configDir:n.configDir,mode:"edit_no_shell",sessionId:(0,Pa.randomUUID)(),onLog:(K,h)=>o(K,h)},(K,h)=>o(K==="warn"?"warn":K,h));if(clearInterval(B),f={costUsd:N.costUsd,inputTokens:N.inputTokens,outputTokens:N.outputTokens},!N.ok)return await an(l),{ok:!1,...f,note:`The agent could not do the resolution: ${N.error??"it produced no output"}. Nothing was changed - the merge was rolled back. Fix that first, then Resolve again.`};p=!0;let D=await vi(l);if(D.length)return await an(l),{ok:!1,...f,note:`The agent left conflict markers in ${D.slice(0,5).join(", ")}, so nothing was pushed and the merge was rolled back. Resolve it by hand on ${r}, or use Rebuild on current base to redo the ticket against today's base.`};await Vo(l,`${i}: merge ${s}, conflicts resolved by the agent
762
779
 
763
- Resolved via Allwright`)}let b=await rn(l,s);if(!b.ok){let T=b.forbidden.length?`the merged result touches protected paths (${b.forbidden.slice(0,5).join(", ")})`:`the merged result is too large (${b.files} files, ${b.insertions+b.deletions} lines; limits ${en}/${tn})`;return await sn(l),{ok:!1,...f,note:`Nothing was pushed: ${T}. The merge was rolled back.`}}await Hn(l,r);let w=await He(l);return o("info",`Pushed the merge to ${r} (${w.slice(0,7)})`),{ok:!0,...f,freeOfCharge:!p,headSha:w,note:p?`Merged ${s} into ${r}; the agent resolved the overlapping files. The PR is the same one - review the merge commit, then approve.`:`Merged ${s} into ${r} cleanly - no agent was needed, so this cost nothing. The PR is the same one; review and approve.`}}catch(c){return await sn(l).catch(()=>{}),{ok:!1,note:`Could not resolve the conflict: ${c instanceof Error?c.message.slice(0,300):String(c)}`}}finally{u&&(await ft(t,l).catch(()=>{}),td.default.rmSync(l,{recursive:!0,force:!0}))}}var Ca=R(require("node:fs"),1),sd=R(require("node:path"),1),Ia=require("node:crypto");pt();function Jg(n,e){let t=e.map(r=>`$ ${r.command} (exit ${r.exitCode})
780
+ Resolved via Allwright`)}let b=await on(l,s);if(!b.ok){let T=b.forbidden.length?`the merged result touches protected paths (${b.forbidden.slice(0,5).join(", ")})`:`the merged result is too large (${b.files} files, ${b.insertions+b.deletions} lines; limits ${nn}/${rn})`;return await an(l),{ok:!1,...f,note:`Nothing was pushed: ${T}. The merge was rolled back.`}}await Jn(l,r);let w=await Je(l);return o("info",`Pushed the merge to ${r} (${w.slice(0,7)})`),{ok:!0,...f,freeOfCharge:!p,headSha:w,note:p?`Merged ${s} into ${r}; the agent resolved the overlapping files. The PR is the same one - review the merge commit, then approve.`:`Merged ${s} into ${r} cleanly - no agent was needed, so this cost nothing. The PR is the same one; review and approve.`}}catch(c){return await an(l).catch(()=>{}),{ok:!1,note:`Could not resolve the conflict: ${c instanceof Error?c.message.slice(0,300):String(c)}`}}finally{u&&(await mt(t,l).catch(()=>{}),dd.default.rmSync(l,{recursive:!0,force:!0}))}}var ja=R(require("node:fs"),1),pd=R(require("node:path"),1),Oa=require("node:crypto");gt();function cy(n,e){let t=e.map(r=>`$ ${r.command} (exit ${r.exitCode})
764
781
  ${r.tail.slice(-2e3)}`).join(`
765
782
 
766
783
  `);return`You are on the pull-request branch for ticket ${n}. The work itself is done and under review - do NOT redo or extend it. The repository's documented TEST.md commands were executed by the runner and ${e.length} failed:
@@ -773,14 +790,14 @@ Your ONLY job is to make these commands pass, with the smallest change possible.
773
790
  - If a failure is clearly pre-existing on the base branch and unrelated to this PR's change, leave the code alone and say so in one sentence.
774
791
  - Do not ask questions; if you cannot fix something safely, say what you found and stop.
775
792
  - You have no shell; the runner re-runs every documented command after you finish.
776
- End with one short paragraph stating exactly what you changed, or why you changed nothing.`}async function id(n){let{cfg:e,repoPath:t,branch:r,baseBranch:s,issueKey:i,failedTests:o,onLog:l}=n,u=sd.default.join(Pt(),`testfix-${(0,Ia.randomUUID)().slice(0,8)}`),c=!1;try{let f=Me(n.agentId);if(!f)return{ok:!1,note:`no adapter for agent "${n.agentId}" on this runner`};let p=on(n.agentId,"edit_no_shell");if(p)return{ok:!1,note:p};l("info",`Preparing a worktree on ${r} for the test fix`),await nn(t,r),await gs(t,u,r),c=!0,await zr(u,`origin/${r}`);let b=await He(u);l("info",`Asking ${f.displayName} to fix ${o.length} failing test command(s) - narrow prompt, failure output included, no re-exploration`);let w=await _s(f,{repoPath:u,prompt:Jg(i,o),timeoutSeconds:n.timeoutSeconds,bin:je(e,n.agentId),configDir:n.configDir,mode:"edit_no_shell",maxTurns:60,sessionId:(0,Ia.randomUUID)(),onLog:(z,h)=>l(z,h)},(z,h)=>l(z==="warn"?"warn":z,h)),T={costUsd:w.costUsd,inputTokens:w.inputTokens,outputTokens:w.outputTokens};if(!w.ok)return{ok:!1,...T,note:`The fix agent could not run: ${w.error??"it produced no output"}. Nothing was changed or pushed.`};let x=await Mr(u);for(let z of x.refused)l("warn",`${$t} entry refused: ${z}`);let A=!0;try{await Gn(u,`${i}: fix failing TEST.md commands
793
+ End with one short paragraph stating exactly what you changed, or why you changed nothing.`}async function md(n){let{cfg:e,repoPath:t,branch:r,baseBranch:s,issueKey:i,failedTests:o,onLog:l}=n,u=pd.default.join(Nt(),`testfix-${(0,Oa.randomUUID)().slice(0,8)}`),c=!1;try{let f=De(n.agentId);if(!f)return{ok:!1,note:`no adapter for agent "${n.agentId}" on this runner`};let p=ln(n.agentId,"edit_no_shell");if(p)return{ok:!1,note:p};l("info",`Preparing a worktree on ${r} for the test fix`),await sn(t,r),await _s(t,u,r),c=!0,await qr(u,`origin/${r}`);let b=await Je(u);l("info",`Asking ${f.displayName} to fix ${o.length} failing test command(s) - narrow prompt, failure output included, no re-exploration`);let w=await Is(f,{repoPath:u,prompt:cy(i,o),timeoutSeconds:n.timeoutSeconds,bin:Oe(e,n.agentId),configDir:n.configDir,mode:"edit_no_shell",maxTurns:60,sessionId:(0,Oa.randomUUID)(),onLog:(m,g)=>l(m,g)},(m,g)=>l(m==="warn"?"warn":m,g)),T={costUsd:w.costUsd,inputTokens:w.inputTokens,outputTokens:w.outputTokens};if(!w.ok)return{ok:!1,...T,note:`The fix agent could not run: ${w.error??"it produced no output"}. Nothing was changed or pushed.`};let C=await Ur(u);for(let m of C.refused)l("warn",`${Ot} entry refused: ${m}`);let A=!0;try{await Wn(u,`${i}: fix failing TEST.md commands
777
794
 
778
- Allwright test-fix run`)}catch{A=!1}if(!A){let z=`The agent changed nothing - its own conclusion: ${w.resultText.trim().slice(0,400)||"(no explanation given)"}`;return l("info",z),{ok:!0,...T,remaining:o,note:z}}let v=await rn(u,s);if(!v.ok){await zr(u,b);let z=v.forbidden.length?`the fixed result touches protected paths (${v.forbidden.slice(0,5).join(", ")})`:`the fixed result is too large (${v.files} files, ${v.insertions+v.deletions} lines; limits ${en}/${tn})`;return{ok:!1,...T,note:`Nothing was pushed: ${z}. The fix commit was discarded; the PR is unchanged.`}}let Z=o,M=Ur(u);if(M){let z=qr(Ca.default.readFileSync(M,"utf8"));if(z.length){l("info",`Re-running ${z.length} documented test command(s)`);let h=await Yn(u,z,{perCommandTimeoutMs:15*6e4});for(let m of h)l(m.exitCode===0?"info":"warn",`${m.exitCode===0?"PASS":"FAIL"} ${m.command} (exit ${m.exitCode})`+(m.exitCode===0?"":`
779
- ${m.tail.slice(-1500)}`));Z=h.filter(m=>m.exitCode!==0).slice(0,20).map(m=>({command:m.command.slice(0,500),exitCode:m.exitCode,tail:m.tail.slice(-4e3)}))}}await Hn(u,r);let L=await He(u);return l("info",`Pushed the fix to ${r} (${L.slice(0,7)})`),{ok:!0,...T,headSha:L,remaining:Z,note:Z.length?`The fix was pushed, but ${Z.length} command(s) still fail - output is in the run log. The PR is the same one; review the new commit.`:"All documented test commands pass now. The PR is the same one - review the fix commit, then approve."}}catch(f){return{ok:!1,note:`Could not fix the tests: ${f instanceof Error?f.message.slice(0,300):String(f)}`}}finally{c&&(await ft(t,u).catch(()=>{}),Ca.default.rmSync(u,{recursive:!0,force:!0}))}}nt();var lr=R(require("node:fs"),1),ad=R(require("node:path"),1);var Yg=k.object({role:k.enum(["user","agent"]),text:k.string()}),Xg=k.object({sessionId:k.string(),projectId:k.string(),title:k.string().default(""),updatedAt:k.string(),messages:k.array(Yg).default([])}),Qg=k.record(Xg),ey=10,ty=200,od=2e4;function ld(){return ad.default.join(re(),"chat-sessions.json")}function Ra(){let n=ld();if(!lr.default.existsSync(n))return{};try{return Qg.parse(JSON.parse(lr.default.readFileSync(n,"utf8")))}catch{return{}}}function ny(n){lr.default.mkdirSync(re(),{recursive:!0,mode:448});let e=ld(),t=e+".tmp";lr.default.writeFileSync(t,JSON.stringify(n,null,2)+`
780
- `,{mode:384}),lr.default.renameSync(t,e),lr.default.chmodSync(e,384)}function ud(n,e,t,r){let s=Ra(),o=s[e]??{sessionId:e,projectId:n,title:t.slice(0,80),updatedAt:new Date().toISOString(),messages:[]};o.messages.push({role:"user",text:t.slice(0,od)},{role:"agent",text:r.slice(0,od)}),o.messages=o.messages.slice(-ty),o.updatedAt=new Date().toISOString(),s[e]=o;let l=Object.values(s).filter(u=>u.projectId===o.projectId).sort((u,c)=>c.updatedAt.localeCompare(u.updatedAt));for(let u of l.slice(ey))delete s[u.sessionId];ny(s)}function cd(n){return Object.values(Ra()).filter(e=>e.projectId===n).sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt)).map(e=>({sessionId:e.sessionId,title:e.title,updatedAt:e.updatedAt,messageCount:e.messages.length}))}function Ea(n){return Ra()[n]??null}var ur=R(require("node:fs"),1),Ve=R(require("node:path"),1),Aa=300,ry=4,dd=512*1024,sy=new Set([".git","node_modules","dist","build","out",".next","vendor","coverage",".venv","venv","__pycache__",".turbo",".cache"]),hd=/\.mdx?$/i;function fd(n){let e=Ve.default.resolve(n),t=[],r=(s,i)=>{if(i>ry||t.length>=Aa)return;let o;try{o=ur.default.readdirSync(s,{withFileTypes:!0})}catch{return}for(let l of o){if(t.length>=Aa)return;if(!l.isFile()||!hd.test(l.name))continue;let u=Ve.default.join(s,l.name);try{let c=ur.default.statSync(u);t.push({path:Ve.default.relative(e,u).split(Ve.default.sep).join("/"),sizeBytes:c.size,updatedAt:c.mtime.toISOString()})}catch{}}for(let l of o){if(t.length>=Aa)return;!l.isDirectory()||l.isSymbolicLink()||sy.has(l.name)||l.name.startsWith(".")||r(Ve.default.join(s,l.name),i+1)}};return r(e,0),t}function pd(n,e){let t=Ve.default.resolve(n);if(!hd.test(e))return{ok:!1,error:"only markdown files can be opened here"};let r=Ve.default.resolve(t,e);if(r!==t&&!r.startsWith(t+Ve.default.sep))return{ok:!1,error:"that path is outside the project checkout"};let s;try{s=ur.default.realpathSync(r)}catch{return{ok:!1,error:"file not found in this checkout"}}let i=(()=>{try{return ur.default.realpathSync(t)}catch{return t}})();if(s!==i&&!s.startsWith(i+Ve.default.sep))return{ok:!1,error:"that path links outside the project checkout"};let o;try{o=ur.default.statSync(s)}catch{return{ok:!1,error:"file not found in this checkout"}}if(!o.isFile())return{ok:!1,error:"that path is not a file"};try{let l=ur.default.readFileSync(s,"utf8"),u=Buffer.byteLength(l,"utf8")>dd;return{ok:!0,path:Ve.default.relative(i,s).split(Ve.default.sep).join("/"),content:u?l.slice(0,dd):l,truncated:u}}catch(l){return{ok:!1,error:l instanceof Error?l.message:"could not read the file"}}}var Lt=R(we(),1);var Ni=R(require("node:fs"),1),md=R(require("node:path"),1);var iy=k.object({id:k.string(),name:k.string().default(""),jiraProjectKey:k.string().default(""),repoName:k.string().default(""),jiraSiteUrl:k.string().default("")}),oy=k.array(iy);function gd(){return md.default.join(re(),"synced-projects.json")}function yd(n){try{let e=n.map(t=>({id:t.id,name:t.name,jiraProjectKey:t.jiraProjectKey,repoName:t.repoName,jiraSiteUrl:t.jiraSiteUrl??""}));Ni.default.mkdirSync(re(),{recursive:!0}),Ni.default.writeFileSync(gd(),JSON.stringify(e,null,2),{mode:384})}catch{}}function ay(){try{let n=oy.safeParse(JSON.parse(Ni.default.readFileSync(gd(),"utf8")));return n.success?n.data:[]}catch{return[]}}function vd(n){return ay().find(e=>e.repoName===n)??null}var Rv=R(fh(),1),Ev=R(Ki(),1),Av=R(Jr(),1),$v=R(qa(),1),Pv=R(Ka(),1),jv=R(Ja(),1),kh=R(Vi(),1),Ov=R(_h(),1);var Xa=kh.default;var Ps=R(require("node:crypto"),1),wt=R(we(),1);function Nv(n){let e=n&&typeof n=="object"&&"name"in n?String(n.name):null;return e?`"${e}"`:"(unnamed)"}function Qa(n,e,t,r){n.push(`dropped ${e} ${t} - this runner is out of date and does not understand it yet (${r}). Update the runner (npm install -g @ticketpilot/runner) to pick it up.`)}function Mv(n){if(!n||typeof n!="object"||n.type!=="config")return null;let e=n,t=[],r=[];for(let l of Array.isArray(e.projects)?e.projects:[]){let u=wt.ProjectConfig.safeParse(l);u.success?r.push(u.data):Qa(t,"project","",u.error.issues[0]?.message??"invalid shape")}let s=[];for(let l of Array.isArray(e.rules)?e.rules:[]){let u=wt.RuleConfig.safeParse(l);u.success?s.push(u.data):Qa(t,"rule",Nv(l),u.error.issues[0]?.message??"invalid shape")}let i=[];for(let l of Array.isArray(e.environments)?e.environments:[]){let u=wt.EnvironmentConfig.safeParse(l);u.success?i.push(u.data):Qa(t,"environment","",u.error.issues[0]?.message??"invalid shape")}return{msg:{type:"config",projects:r,rules:s,environments:i,pollingPaused:typeof e.pollingPaused=="boolean"?e.pollingPaused:!1},warnings:t}}var zv=2e4,Dv=6e4,Lv=5e3,Ji=class{constructor(e,t,r,s){this.wsUrl=e;this.runnerToken=t;this.meta=r;this.events=s}wsUrl;runnerToken;meta;events;ws=null;queue=[];pending=new Map;backoffMs=1e3;heartbeat=null;closed=!1;bootAnnounced=!1;start(){this.closed=!1,this.connect()}stop(){this.closed=!0,this.heartbeat&&clearInterval(this.heartbeat),this.ws?.close()}get connected(){return this.ws?.readyState===Xa.OPEN}connect(){if(this.closed)return;y.info(`connecting to control plane at ${this.wsUrl}`);let e=new Xa(this.wsUrl,{headers:{authorization:`Bearer ${this.runnerToken}`}});this.ws=e,e.on("open",()=>{this.backoffMs=1e3,this.sendNow({type:"hello",protocolVersion:wt.PROTOCOL_VERSION,runnerVersion:this.meta.runnerVersion,platform:`${process.platform}/${process.arch} node${process.versions.node}`,justBooted:!this.bootAnnounced});let t=this.queue.splice(0,this.queue.length);for(let r of t)this.sendNow(r);this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=setInterval(()=>{this.send({type:"heartbeat",ts:new Date().toISOString()})},zv)}),e.on("message",t=>{let r;try{r=JSON.parse(t.toString())}catch(i){y.warn(`ignoring malformed server message (bad JSON): ${i}`);return}let s;try{s=(0,wt.parseServerMsg)(r)}catch(i){let o=Mv(r);if(!o){y.warn(`ignoring malformed server message: ${i}`);return}for(let l of o.warnings)y.warn(l);y.warn(`config push had ${o.warnings.length} ${o.warnings.length===1?"entry":"entries"} this runner doesn't understand - applied everything else instead of dropping the whole config`),s=o.msg}this.handle(s)}),e.on("close",t=>{if(this.heartbeat&&clearInterval(this.heartbeat),t===4001)y.error("control plane rejected this runner version (protocol mismatch). Update with: npm install -g @ticketpilot/runner");else if(t===4003){y.error("this runner has been revoked from the control plane UI. Re-enroll with a fresh token if this was not intended."),this.closed=!0;return}if(this.closed)return;let r=Math.random()*.3+.85,s=Math.round(this.backoffMs*r);y.warn(`disconnected (code ${t}); reconnecting in ${Math.round(s/1e3)}s`),setTimeout(()=>this.connect(),s),this.backoffMs=Math.min(this.backoffMs*2,Dv)}),e.on("error",t=>{y.warn(`websocket error: ${t.message}`)})}handle(e){if(e.type==="hello.ack"){this.bootAnnounced=!0,y.info(`connected as runner "${e.runnerName}" (${e.runnerId})`);return}if(e.type==="run.claim.result"||e.type==="deploy.claim.result"||e.type==="autopilot.next.result"){let t=this.pending.get(e.requestId);t&&(clearTimeout(t.timer),this.pending.delete(e.requestId),t.resolve(e));return}if(e.type==="config")return this.events.onConfig(e);if(e.type==="project.test")return this.events.onProjectTest(e);if(e.type==="rule.diagnose")return this.events.onRuleDiagnose(e);if(e.type==="run.cancel")return this.events.onCancel(e.runId);if(e.type==="run.approved")return this.events.onApproved(e.runId,e.headSha);if(e.type==="run.rejected")return this.events.onRejected(e.runId);if(e.type==="run.retryPush")return this.events.onRetryPush(e.runId);if(e.type==="deploy.start")return this.events.onDeployStart(e);if(e.type==="deploy.suggest")return this.events.onDeploySuggest(e);if(e.type==="deploy.fix")return this.events.onDeployFix(e);if(e.type==="env.preflight")return this.events.onEnvPreflight(e);if(e.type==="chat.turn")return this.events.onChatTurn(e);if(e.type==="chat.create.ticket")return this.events.onChatCreateTicket(e);if(e.type==="chat.list")return this.events.onChatList(e);if(e.type==="repo.docs")return this.events.onRepoDocs(e);if(e.type==="repo.doc.read")return this.events.onRepoDocRead(e);if(e.type==="chat.load")return this.events.onChatLoad(e);if(e.type==="board.fetch")return this.events.onBoardFetch(e);if(e.type==="board.trigger")return this.events.onBoardTrigger(e);if(e.type==="audit.start")return this.events.onAuditStart(e);if(e.type==="audit.list")return this.events.onAuditList(e);if(e.type==="audit.get")return this.events.onAuditGet(e);if(e.type==="audit.review")return this.events.onAuditReview(e);if(e.type==="knowledge.list")return this.events.onKnowledgeList(e);if(e.type==="knowledge.save")return this.events.onKnowledgeSave(e);if(e.type==="epic.list")return this.events.onEpicList(e);if(e.type==="epic.suggest")return this.events.onEpicSuggest(e);if(e.type==="team.creds")return this.events.onTeamCreds(e);if(e.type==="jira.users")return this.events.onJiraUsers(e);if(e.type==="setup.status")return this.events.onSetupStatus(e);if(e.type==="setup.claudemd.generate")return this.events.onSetupClaudeMdGenerate(e);if(e.type==="setup.claudemd.save")return this.events.onSetupClaudeMdSave(e);if(e.type==="repo.doc.save")return this.events.onRepoDocSave(e);if(e.type==="runner.update")return this.events.onRunnerUpdate(e);if(e.type==="agent.profiles")return this.events.onAgentProfiles(e);if(e.type==="run.resolve.conflict")return this.events.onResolveConflict(e);if(e.type==="run.testfix")return this.events.onTestFix(e);if(e.type==="audit.stats")return this.events.onAuditStats(e)}sendNow(e){this.ws?.send(JSON.stringify(e))}send(e){if(this.connected){this.sendNow(e);return}if(this.queue.length>=Lv){let t=this.queue.findIndex(r=>r.type==="run.log");t>=0?this.queue.splice(t,1):this.queue.shift()}this.queue.push(e)}async claimRun(e){if(!this.connected)return{accepted:!1,reason:"control plane offline"};let t=Ps.default.randomUUID(),r=await new Promise(s=>{let i=setTimeout(()=>{this.pending.delete(t),s(null)},15e3);this.pending.set(t,{resolve:s,timer:i}),this.sendNow({type:"run.claim",requestId:t,...e})});return!r||r.type!=="run.claim.result"?{accepted:!1,reason:"claim timed out"}:{accepted:r.accepted,runId:r.runId,reason:r.reason,claudeProfile:r.claudeProfile,actorEmail:r.actorEmail}}async requestAutopilotNext(){if(!this.connected)return null;let e=Ps.default.randomUUID(),t=await new Promise(r=>{let s=setTimeout(()=>{this.pending.delete(e),r(null)},15e3);this.pending.set(e,{resolve:r,timer:s}),this.sendNow({type:"autopilot.next",requestId:e})});return!t||t.type!=="autopilot.next.result"?null:{ok:t.ok,item:t.item,pausedUntil:t.pausedUntil}}sendAutopilotReport(e){this.send({type:"autopilot.report",requestId:Ps.default.randomUUID(),itemId:e.itemId,outcome:e.outcome,runId:e.runId??"",error:e.error??""})}async claimDeploy(e){if(!this.connected)return{accepted:!1,reason:"control plane offline"};let t=Ps.default.randomUUID(),r=await new Promise(s=>{let i=setTimeout(()=>{this.pending.delete(t),s(null)},15e3);this.pending.set(t,{resolve:s,timer:i}),this.sendNow({type:"deploy.claim",requestId:t,...e})});return!r||r.type!=="deploy.claim.result"?{accepted:!1,reason:"deploy authorization timed out"}:{accepted:r.accepted,runId:r.runId,environment:r.environment,reason:r.reason,code:r.code}}sendDeploySuggestResult(e,t){this.send({type:"deploy.suggest.result",requestId:e,...t,docPath:t.docPath??"",docContent:t.docContent??""})}sendChatTurnResult(e,t){this.send({type:"chat.turn.result",requestId:e,...t,inputTokens:t.inputTokens??0,outputTokens:t.outputTokens??0,cacheReadTokens:t.cacheReadTokens??0,costUsd:t.costUsd??0,model:t.model??""})}sendChatCreateTicketResult(e,t){this.send({type:"chat.create.ticket.result",requestId:e,...t,childKeys:t.childKeys??[]})}sendChatListResult(e,t){this.send({type:"chat.list.result",requestId:e,sessions:t})}sendRepoDocsResult(e,t){this.send({type:"repo.docs.result",requestId:e,...t})}sendRepoDocReadResult(e,t){this.send({type:"repo.doc.read.result",requestId:e,...t})}sendChatLoadResult(e,t){this.send({type:"chat.load.result",requestId:e,...t})}sendBoardFetchResult(e,t){this.send({type:"board.fetch.result",requestId:e,...t,browseBaseUrl:t.browseBaseUrl??""})}sendAuditStartResult(e,t){this.send({type:"audit.start.result",requestId:e,...t})}sendAuditListResult(e,t){this.send({type:"audit.list.result",requestId:e,ok:t.ok,error:t.error,audits:t.audits??[]})}sendAuditGetResult(e,t){this.send({type:"audit.get.result",requestId:e,...t})}sendAuditReviewResult(e,t){this.send({type:"audit.review.result",requestId:e,...t})}sendKnowledgeListResult(e,t){this.send({type:"knowledge.list.result",requestId:e,ok:t.ok,error:t.error,files:t.files??[]})}sendKnowledgeSaveResult(e,t){this.send({type:"knowledge.save.result",requestId:e,...t})}sendEpicListResult(e,t){this.send({type:"epic.list.result",requestId:e,ok:t.ok,error:t.error,epics:t.epics??[],children:t.children??[]})}sendEpicSuggestResult(e,t){this.send({type:"epic.suggest.result",requestId:e,ok:t.ok,error:t.error,issueKey:t.issueKey??"",reason:t.reason??"",considered:t.considered??0})}sendTeamCredsResult(e,t){this.send({type:"team.creds.result",requestId:e,ok:t.ok,error:t.error,githubShared:t.githubShared??!1,sharedGithubLogin:t.sharedGithubLogin??"",entries:t.entries??[]})}sendBoardTriggerResult(e,t){this.send({type:"board.trigger.result",requestId:e,...t})}sendAuditStatsResult(e,t){this.send({type:"audit.stats.result",requestId:e,ok:t.ok,error:t.error,byProject:t.byProject??{}})}sendRunnerUpdateResult(e,t){this.send({type:"runner.update.result",requestId:e,ok:t.ok,error:t.error,note:t.note??"",scheduled:t.scheduled??!1})}sendSetupClaudeMdGenerateResult(e,t){this.send({type:"setup.claudemd.generate.result",requestId:e,ok:t.ok,error:t.error,content:t.content??""})}sendSetupClaudeMdSaveResult(e,t){this.send({type:"setup.claudemd.save.result",requestId:e,ok:t.ok,error:t.error,note:t.note??""})}sendResolveConflictResult(e,t){this.send({type:"run.resolve.conflict.result",requestId:e,ok:t.ok,note:t.note??"",freeOfCharge:t.freeOfCharge??!1,headSha:t.headSha??"",costUsd:t.costUsd,inputTokens:t.inputTokens,outputTokens:t.outputTokens})}sendTestFixResult(e,t){this.send({type:"run.testfix.result",requestId:e,ok:t.ok,note:t.note??"",headSha:t.headSha??"",remaining:t.remaining??[],costUsd:t.costUsd,inputTokens:t.inputTokens,outputTokens:t.outputTokens})}sendAgentProfilesResult(e,t){this.send({type:"agent.profiles.result",requestId:e,ok:t.ok,error:t.error,profiles:t.profiles??[],defaultLoggedIn:t.defaultLoggedIn??!1,agentsWithoutProfiles:t.agentsWithoutProfiles??[]})}sendRepoDocSaveResult(e,t){this.send({type:"repo.doc.save.result",requestId:e,ok:t.ok,error:t.error,note:t.note??""})}sendSetupStatusResult(e,t){this.send({type:"setup.status.result",requestId:e,ok:t.ok,error:t.error,jiraConfigured:t.jiraConfigured??!1,jiraEmail:t.jiraEmail??"",claude:t.claude,githubTokenSet:t.githubTokenSet??!1,githubLogin:t.githubLogin??"",deploysEnabled:t.deploysEnabled??!1,jiraUserCount:t.jiraUserCount??0,repos:t.repos??[]})}sendEnvPreflightResult(e,t){this.send({type:"env.preflight.result",requestId:e,...t,checks:this.withFixDefaults(t.checks)})}sendJiraUsersResult(e,t){this.send({type:"jira.users.result",requestId:e,...t})}withFixDefaults(e){return e.map(t=>({...t,kind:t.kind??"connection",fix:t.fix??[],fixNote:t.fixNote??""}))}sendProjectTestResult(e,t,r){this.send({type:"project.test.result",requestId:e,ok:t,checks:this.withFixDefaults(r)})}sendRuleDiagnoseResult(e,t){this.send({type:"rule.diagnose.result",requestId:e,...t,checks:this.withFixDefaults(t.checks)})}};var Yi=R(require("node:fs"),1),ns=R(require("node:path"),1),Th=require("node:child_process"),Uv=/\.mdx?$/i,Sh=6,qv=/^[\w.\- ()]+$/;function Fv(n,e){let t=e.trim().replace(/\\/g,"/").replace(/^\.\//,"");if(!t)return{ok:!1,error:"empty path"};if(ns.default.isAbsolute(t))return{ok:!1,error:"path must be repo-relative"};if(!Uv.test(t))return{ok:!1,error:"only markdown files (.md) can be saved"};let r=t.split("/");if(r.length>Sh)return{ok:!1,error:`path deeper than ${Sh} levels`};for(let o of r)if(o==="."||o===".."||!qv.test(o))return{ok:!1,error:`invalid path segment "${o}"`};if(r[0]===".git")return{ok:!1,error:"cannot write under .git"};let s=ns.default.resolve(n),i=ns.default.resolve(s,t);return i!==s&&!i.startsWith(s+ns.default.sep)?{ok:!1,error:"path escapes the checkout"}:{ok:!0,abs:i,rel:t}}async function el(n){let e=Fv(n.repoPath,n.relPath);if(!e.ok)return{ok:!1,error:e.error};if(Yi.default.existsSync(e.abs)&&!n.overwrite)return{ok:!1,error:`${e.rel} already exists in this checkout`};Yi.default.mkdirSync(ns.default.dirname(e.abs),{recursive:!0}),Yi.default.writeFileSync(e.abs,n.content.endsWith(`
795
+ Allwright test-fix run`)}catch{A=!1}if(!A){let m=`The agent changed nothing - its own conclusion: ${w.resultText.trim().slice(0,400)||"(no explanation given)"}`;return l("info",m),{ok:!0,...T,remaining:o,note:m}}let v=await on(u,s);if(!v.ok){await qr(u,b);let m=v.forbidden.length?`the fixed result touches protected paths (${v.forbidden.slice(0,5).join(", ")})`:`the fixed result is too large (${v.files} files, ${v.insertions+v.deletions} lines; limits ${nn}/${rn})`;return{ok:!1,...T,note:`Nothing was pushed: ${m}. The fix commit was discarded; the PR is unchanged.`}}let B=o,N,D,K=Kr(u);if(K){let m=Zr(ja.default.readFileSync(K,"utf8"));if(m.length){l("info",`Re-running ${m.length} documented test command(s)`);let g=await er(u,m,{perCommandTimeoutMs:15*6e4});for(let x of g)l(x.exitCode===0?"info":"warn",`${x.exitCode===0?"PASS":"FAIL"} ${x.command} (exit ${x.exitCode})`+(x.exitCode===0?"":`
796
+ ${x.tail.slice(-1500)}`));B=g.filter(x=>x.exitCode!==0).slice(0,20).map(x=>({command:x.command.slice(0,500),exitCode:x.exitCode,tail:x.tail.slice(-4e3)})),D=g.length,N=g.length-B.length}}await Jn(u,r);let h=await Je(u);return l("info",`Pushed the fix to ${r} (${h.slice(0,7)})`),{ok:!0,...T,headSha:h,remaining:B,testsPassed:N,testsTotal:D,note:B.length?`The fix was pushed, but ${B.length} command(s) still fail - output is in the run log. The PR is the same one; review the new commit.`:"All documented test commands pass now. The PR is the same one - review the fix commit, then approve."}}catch(f){return{ok:!1,note:`Could not fix the tests: ${f instanceof Error?f.message.slice(0,300):String(f)}`}}finally{c&&(await mt(t,u).catch(()=>{}),ja.default.rmSync(u,{recursive:!0,force:!0}))}}it();var dr=R(require("node:fs"),1),yd=R(require("node:path"),1);var dy=k.object({role:k.enum(["user","agent"]),text:k.string()}),hy=k.object({sessionId:k.string(),projectId:k.string(),title:k.string().default(""),updatedAt:k.string(),messages:k.array(dy).default([])}),fy=k.record(hy),py=10,my=200,gd=2e4;function vd(){return yd.default.join(se(),"chat-sessions.json")}function Na(){let n=vd();if(!dr.default.existsSync(n))return{};try{return fy.parse(JSON.parse(dr.default.readFileSync(n,"utf8")))}catch{return{}}}function gy(n){dr.default.mkdirSync(se(),{recursive:!0,mode:448});let e=vd(),t=e+".tmp";dr.default.writeFileSync(t,JSON.stringify(n,null,2)+`
797
+ `,{mode:384}),dr.default.renameSync(t,e),dr.default.chmodSync(e,384)}function bd(n,e,t,r){let s=Na(),o=s[e]??{sessionId:e,projectId:n,title:t.slice(0,80),updatedAt:new Date().toISOString(),messages:[]};o.messages.push({role:"user",text:t.slice(0,gd)},{role:"agent",text:r.slice(0,gd)}),o.messages=o.messages.slice(-my),o.updatedAt=new Date().toISOString(),s[e]=o;let l=Object.values(s).filter(u=>u.projectId===o.projectId).sort((u,c)=>c.updatedAt.localeCompare(u.updatedAt));for(let u of l.slice(py))delete s[u.sessionId];gy(s)}function wd(n){return Object.values(Na()).filter(e=>e.projectId===n).sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt)).map(e=>({sessionId:e.sessionId,title:e.title,updatedAt:e.updatedAt,messageCount:e.messages.length}))}function Ma(n){return Na()[n]??null}var hr=R(require("node:fs"),1),Ye=R(require("node:path"),1),za=300,yy=4,_d=512*1024,vy=new Set([".git","node_modules","dist","build","out",".next","vendor","coverage",".venv","venv","__pycache__",".turbo",".cache"]),kd=/\.mdx?$/i;function Sd(n){let e=Ye.default.resolve(n),t=[],r=(s,i)=>{if(i>yy||t.length>=za)return;let o;try{o=hr.default.readdirSync(s,{withFileTypes:!0})}catch{return}for(let l of o){if(t.length>=za)return;if(!l.isFile()||!kd.test(l.name))continue;let u=Ye.default.join(s,l.name);try{let c=hr.default.statSync(u);t.push({path:Ye.default.relative(e,u).split(Ye.default.sep).join("/"),sizeBytes:c.size,updatedAt:c.mtime.toISOString()})}catch{}}for(let l of o){if(t.length>=za)return;!l.isDirectory()||l.isSymbolicLink()||vy.has(l.name)||l.name.startsWith(".")||r(Ye.default.join(s,l.name),i+1)}};return r(e,0),t}function Td(n,e){let t=Ye.default.resolve(n);if(!kd.test(e))return{ok:!1,error:"only markdown files can be opened here"};let r=Ye.default.resolve(t,e);if(r!==t&&!r.startsWith(t+Ye.default.sep))return{ok:!1,error:"that path is outside the project checkout"};let s;try{s=hr.default.realpathSync(r)}catch{return{ok:!1,error:"file not found in this checkout"}}let i=(()=>{try{return hr.default.realpathSync(t)}catch{return t}})();if(s!==i&&!s.startsWith(i+Ye.default.sep))return{ok:!1,error:"that path links outside the project checkout"};let o;try{o=hr.default.statSync(s)}catch{return{ok:!1,error:"file not found in this checkout"}}if(!o.isFile())return{ok:!1,error:"that path is not a file"};try{let l=hr.default.readFileSync(s,"utf8"),u=Buffer.byteLength(l,"utf8")>_d;return{ok:!0,path:Ye.default.relative(i,s).split(Ye.default.sep).join("/"),content:u?l.slice(0,_d):l,truncated:u}}catch(l){return{ok:!1,error:l instanceof Error?l.message:"could not read the file"}}}var Bt=R(we(),1);var Li=R(require("node:fs"),1),xd=R(require("node:path"),1);var by=k.object({id:k.string(),name:k.string().default(""),jiraProjectKey:k.string().default(""),repoName:k.string().default(""),jiraSiteUrl:k.string().default("")}),wy=k.array(by);function Cd(){return xd.default.join(se(),"synced-projects.json")}function Id(n){try{let e=n.map(t=>({id:t.id,name:t.name,jiraProjectKey:t.jiraProjectKey,repoName:t.repoName,jiraSiteUrl:t.jiraSiteUrl??""}));Li.default.mkdirSync(se(),{recursive:!0}),Li.default.writeFileSync(Cd(),JSON.stringify(e,null,2),{mode:384})}catch{}}function _y(){try{let n=wy.safeParse(JSON.parse(Li.default.readFileSync(Cd(),"utf8")));return n.success?n.data:[]}catch{return[]}}function Rd(n){return _y().find(e=>e.repoName===n)??null}var Fv=R(Sh(),1),Bv=R(Vi(),1),Kv=R(es(),1),Zv=R(Va(),1),Gv=R(Ya(),1),Hv=R(rl(),1),Ph=R(Xi(),1),Vv=R($h(),1);var il=Ph.default;var Ds=R(require("node:crypto"),1),kt=R(we(),1);function Wv(n){let e=n&&typeof n=="object"&&"name"in n?String(n.name):null;return e?`"${e}"`:"(unnamed)"}function ol(n,e,t,r){n.push(`dropped ${e} ${t} - this runner is out of date and does not understand it yet (${r}). Update the runner (npm install -g @ticketpilot/runner) to pick it up.`)}function Jv(n){if(!n||typeof n!="object"||n.type!=="config")return null;let e=n,t=[],r=[];for(let l of Array.isArray(e.projects)?e.projects:[]){let u=kt.ProjectConfig.safeParse(l);u.success?r.push(u.data):ol(t,"project","",u.error.issues[0]?.message??"invalid shape")}let s=[];for(let l of Array.isArray(e.rules)?e.rules:[]){let u=kt.RuleConfig.safeParse(l);u.success?s.push(u.data):ol(t,"rule",Wv(l),u.error.issues[0]?.message??"invalid shape")}let i=[];for(let l of Array.isArray(e.environments)?e.environments:[]){let u=kt.EnvironmentConfig.safeParse(l);u.success?i.push(u.data):ol(t,"environment","",u.error.issues[0]?.message??"invalid shape")}return{msg:{type:"config",projects:r,rules:s,environments:i,pollingPaused:typeof e.pollingPaused=="boolean"?e.pollingPaused:!1},warnings:t}}var Yv=2e4,Xv=6e4,Qv=5e3,eo=class{constructor(e,t,r,s){this.wsUrl=e;this.runnerToken=t;this.meta=r;this.events=s}wsUrl;runnerToken;meta;events;ws=null;queue=[];pending=new Map;backoffMs=1e3;heartbeat=null;closed=!1;bootAnnounced=!1;start(){this.closed=!1,this.connect()}stop(){this.closed=!0,this.heartbeat&&clearInterval(this.heartbeat),this.ws?.close()}get connected(){return this.ws?.readyState===il.OPEN}connect(){if(this.closed)return;y.info(`connecting to control plane at ${this.wsUrl}`);let e=new il(this.wsUrl,{headers:{authorization:`Bearer ${this.runnerToken}`}});this.ws=e,e.on("open",()=>{this.backoffMs=1e3,this.sendNow({type:"hello",protocolVersion:kt.PROTOCOL_VERSION,runnerVersion:this.meta.runnerVersion,platform:`${process.platform}/${process.arch} node${process.versions.node}`,justBooted:!this.bootAnnounced});let t=this.queue.splice(0,this.queue.length);for(let r of t)this.sendNow(r);this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=setInterval(()=>{this.send({type:"heartbeat",ts:new Date().toISOString()})},Yv)}),e.on("message",t=>{let r;try{r=JSON.parse(t.toString())}catch(i){y.warn(`ignoring malformed server message (bad JSON): ${i}`);return}let s;try{s=(0,kt.parseServerMsg)(r)}catch(i){let o=Jv(r);if(!o){y.warn(`ignoring malformed server message: ${i}`);return}for(let l of o.warnings)y.warn(l);y.warn(`config push had ${o.warnings.length} ${o.warnings.length===1?"entry":"entries"} this runner doesn't understand - applied everything else instead of dropping the whole config`),s=o.msg}this.handle(s)}),e.on("close",t=>{if(this.heartbeat&&clearInterval(this.heartbeat),t===4001)y.error("control plane rejected this runner version (protocol mismatch). Update with: npm install -g @ticketpilot/runner");else if(t===4003){y.error("this runner has been revoked from the control plane UI. Re-enroll with a fresh token if this was not intended."),this.closed=!0;return}if(this.closed)return;let r=Math.random()*.3+.85,s=Math.round(this.backoffMs*r);y.warn(`disconnected (code ${t}); reconnecting in ${Math.round(s/1e3)}s`),setTimeout(()=>this.connect(),s),this.backoffMs=Math.min(this.backoffMs*2,Xv)}),e.on("error",t=>{y.warn(`websocket error: ${t.message}`)})}handle(e){if(e.type==="hello.ack"){this.bootAnnounced=!0,y.info(`connected as runner "${e.runnerName}" (${e.runnerId})`);return}if(e.type==="run.claim.result"||e.type==="deploy.claim.result"||e.type==="autopilot.next.result"){let t=this.pending.get(e.requestId);t&&(clearTimeout(t.timer),this.pending.delete(e.requestId),t.resolve(e));return}if(e.type==="config")return this.events.onConfig(e);if(e.type==="project.test")return this.events.onProjectTest(e);if(e.type==="rule.diagnose")return this.events.onRuleDiagnose(e);if(e.type==="run.cancel")return this.events.onCancel(e.runId);if(e.type==="run.approved")return this.events.onApproved(e.runId,e.headSha);if(e.type==="run.rejected")return this.events.onRejected(e.runId);if(e.type==="run.retryPush")return this.events.onRetryPush(e.runId);if(e.type==="deploy.start")return this.events.onDeployStart(e);if(e.type==="deploy.suggest")return this.events.onDeploySuggest(e);if(e.type==="deploy.fix")return this.events.onDeployFix(e);if(e.type==="env.preflight")return this.events.onEnvPreflight(e);if(e.type==="chat.turn")return this.events.onChatTurn(e);if(e.type==="chat.create.ticket")return this.events.onChatCreateTicket(e);if(e.type==="chat.list")return this.events.onChatList(e);if(e.type==="repo.docs")return this.events.onRepoDocs(e);if(e.type==="repo.doc.read")return this.events.onRepoDocRead(e);if(e.type==="chat.load")return this.events.onChatLoad(e);if(e.type==="board.fetch")return this.events.onBoardFetch(e);if(e.type==="board.trigger")return this.events.onBoardTrigger(e);if(e.type==="audit.start")return this.events.onAuditStart(e);if(e.type==="audit.list")return this.events.onAuditList(e);if(e.type==="audit.get")return this.events.onAuditGet(e);if(e.type==="audit.review")return this.events.onAuditReview(e);if(e.type==="knowledge.list")return this.events.onKnowledgeList(e);if(e.type==="knowledge.save")return this.events.onKnowledgeSave(e);if(e.type==="epic.list")return this.events.onEpicList(e);if(e.type==="epic.suggest")return this.events.onEpicSuggest(e);if(e.type==="team.creds")return this.events.onTeamCreds(e);if(e.type==="jira.users")return this.events.onJiraUsers(e);if(e.type==="setup.status")return this.events.onSetupStatus(e);if(e.type==="setup.claudemd.generate")return this.events.onSetupClaudeMdGenerate(e);if(e.type==="setup.claudemd.save")return this.events.onSetupClaudeMdSave(e);if(e.type==="repo.doc.save")return this.events.onRepoDocSave(e);if(e.type==="runner.update")return this.events.onRunnerUpdate(e);if(e.type==="agent.profiles")return this.events.onAgentProfiles(e);if(e.type==="run.resolve.conflict")return this.events.onResolveConflict(e);if(e.type==="run.testfix")return this.events.onTestFix(e);if(e.type==="audit.stats")return this.events.onAuditStats(e)}sendNow(e){this.ws?.send(JSON.stringify(e))}send(e){if(this.connected){this.sendNow(e);return}if(this.queue.length>=Qv){let t=this.queue.findIndex(r=>r.type==="run.log");t>=0?this.queue.splice(t,1):this.queue.shift()}this.queue.push(e)}async claimRun(e){if(!this.connected)return{accepted:!1,reason:"control plane offline"};let t=Ds.default.randomUUID(),r=await new Promise(s=>{let i=setTimeout(()=>{this.pending.delete(t),s(null)},15e3);this.pending.set(t,{resolve:s,timer:i}),this.sendNow({type:"run.claim",requestId:t,...e})});return!r||r.type!=="run.claim.result"?{accepted:!1,reason:"claim timed out"}:{accepted:r.accepted,runId:r.runId,reason:r.reason,claudeProfile:r.claudeProfile,actorEmail:r.actorEmail}}async requestAutopilotNext(){if(!this.connected)return null;let e=Ds.default.randomUUID(),t=await new Promise(r=>{let s=setTimeout(()=>{this.pending.delete(e),r(null)},15e3);this.pending.set(e,{resolve:r,timer:s}),this.sendNow({type:"autopilot.next",requestId:e})});return!t||t.type!=="autopilot.next.result"?null:{ok:t.ok,item:t.item,pausedUntil:t.pausedUntil}}sendAutopilotReport(e){this.send({type:"autopilot.report",requestId:Ds.default.randomUUID(),itemId:e.itemId,outcome:e.outcome,runId:e.runId??"",error:e.error??""})}async claimDeploy(e){if(!this.connected)return{accepted:!1,reason:"control plane offline"};let t=Ds.default.randomUUID(),r=await new Promise(s=>{let i=setTimeout(()=>{this.pending.delete(t),s(null)},15e3);this.pending.set(t,{resolve:s,timer:i}),this.sendNow({type:"deploy.claim",requestId:t,...e})});return!r||r.type!=="deploy.claim.result"?{accepted:!1,reason:"deploy authorization timed out"}:{accepted:r.accepted,runId:r.runId,environment:r.environment,reason:r.reason,code:r.code}}sendDeploySuggestResult(e,t){this.send({type:"deploy.suggest.result",requestId:e,...t,docPath:t.docPath??"",docContent:t.docContent??""})}sendChatTurnResult(e,t){this.send({type:"chat.turn.result",requestId:e,...t,inputTokens:t.inputTokens??0,outputTokens:t.outputTokens??0,cacheReadTokens:t.cacheReadTokens??0,costUsd:t.costUsd??0,model:t.model??""})}sendChatCreateTicketResult(e,t){this.send({type:"chat.create.ticket.result",requestId:e,...t,childKeys:t.childKeys??[]})}sendChatListResult(e,t){this.send({type:"chat.list.result",requestId:e,sessions:t})}sendRepoDocsResult(e,t){this.send({type:"repo.docs.result",requestId:e,...t})}sendRepoDocReadResult(e,t){this.send({type:"repo.doc.read.result",requestId:e,...t})}sendChatLoadResult(e,t){this.send({type:"chat.load.result",requestId:e,...t})}sendBoardFetchResult(e,t){this.send({type:"board.fetch.result",requestId:e,...t,browseBaseUrl:t.browseBaseUrl??""})}sendAuditStartResult(e,t){this.send({type:"audit.start.result",requestId:e,...t})}sendAuditListResult(e,t){this.send({type:"audit.list.result",requestId:e,ok:t.ok,error:t.error,audits:t.audits??[]})}sendAuditGetResult(e,t){this.send({type:"audit.get.result",requestId:e,...t})}sendAuditReviewResult(e,t){this.send({type:"audit.review.result",requestId:e,...t})}sendKnowledgeListResult(e,t){this.send({type:"knowledge.list.result",requestId:e,ok:t.ok,error:t.error,files:t.files??[]})}sendKnowledgeSaveResult(e,t){this.send({type:"knowledge.save.result",requestId:e,...t})}sendEpicListResult(e,t){this.send({type:"epic.list.result",requestId:e,ok:t.ok,error:t.error,epics:t.epics??[],children:t.children??[]})}sendEpicSuggestResult(e,t){this.send({type:"epic.suggest.result",requestId:e,ok:t.ok,error:t.error,issueKey:t.issueKey??"",reason:t.reason??"",considered:t.considered??0})}sendTeamCredsResult(e,t){this.send({type:"team.creds.result",requestId:e,ok:t.ok,error:t.error,githubShared:t.githubShared??!1,sharedGithubLogin:t.sharedGithubLogin??"",entries:t.entries??[]})}sendBoardTriggerResult(e,t){this.send({type:"board.trigger.result",requestId:e,...t})}sendAuditStatsResult(e,t){this.send({type:"audit.stats.result",requestId:e,ok:t.ok,error:t.error,byProject:t.byProject??{}})}sendRunnerUpdateResult(e,t){this.send({type:"runner.update.result",requestId:e,ok:t.ok,error:t.error,note:t.note??"",scheduled:t.scheduled??!1})}sendSetupClaudeMdGenerateResult(e,t){this.send({type:"setup.claudemd.generate.result",requestId:e,ok:t.ok,error:t.error,content:t.content??""})}sendSetupClaudeMdSaveResult(e,t){this.send({type:"setup.claudemd.save.result",requestId:e,ok:t.ok,error:t.error,note:t.note??""})}sendResolveConflictResult(e,t){this.send({type:"run.resolve.conflict.result",requestId:e,ok:t.ok,note:t.note??"",freeOfCharge:t.freeOfCharge??!1,headSha:t.headSha??"",costUsd:t.costUsd,inputTokens:t.inputTokens,outputTokens:t.outputTokens})}sendTestFixResult(e,t){this.send({type:"run.testfix.result",requestId:e,ok:t.ok,note:t.note??"",headSha:t.headSha??"",remaining:t.remaining??[],costUsd:t.costUsd,inputTokens:t.inputTokens,outputTokens:t.outputTokens})}sendAgentProfilesResult(e,t){this.send({type:"agent.profiles.result",requestId:e,ok:t.ok,error:t.error,profiles:t.profiles??[],defaultLoggedIn:t.defaultLoggedIn??!1,agentsWithoutProfiles:t.agentsWithoutProfiles??[]})}sendRepoDocSaveResult(e,t){this.send({type:"repo.doc.save.result",requestId:e,ok:t.ok,error:t.error,note:t.note??""})}sendSetupStatusResult(e,t){this.send({type:"setup.status.result",requestId:e,ok:t.ok,error:t.error,jiraConfigured:t.jiraConfigured??!1,jiraEmail:t.jiraEmail??"",claude:t.claude,githubTokenSet:t.githubTokenSet??!1,githubLogin:t.githubLogin??"",deploysEnabled:t.deploysEnabled??!1,jiraUserCount:t.jiraUserCount??0,repos:t.repos??[]})}sendEnvPreflightResult(e,t){this.send({type:"env.preflight.result",requestId:e,...t,checks:this.withFixDefaults(t.checks)})}sendJiraUsersResult(e,t){this.send({type:"jira.users.result",requestId:e,...t})}withFixDefaults(e){return e.map(t=>({...t,kind:t.kind??"connection",fix:t.fix??[],fixNote:t.fixNote??""}))}sendProjectTestResult(e,t,r){this.send({type:"project.test.result",requestId:e,ok:t,checks:this.withFixDefaults(r)})}sendRuleDiagnoseResult(e,t){this.send({type:"rule.diagnose.result",requestId:e,...t,checks:this.withFixDefaults(t.checks)})}};var to=R(require("node:fs"),1),os=R(require("node:path"),1),Oh=require("node:child_process"),eb=/\.mdx?$/i,jh=6,tb=/^[\w.\- ()]+$/;function nb(n,e){let t=e.trim().replace(/\\/g,"/").replace(/^\.\//,"");if(!t)return{ok:!1,error:"empty path"};if(os.default.isAbsolute(t))return{ok:!1,error:"path must be repo-relative"};if(!eb.test(t))return{ok:!1,error:"only markdown files (.md) can be saved"};let r=t.split("/");if(r.length>jh)return{ok:!1,error:`path deeper than ${jh} levels`};for(let o of r)if(o==="."||o===".."||!tb.test(o))return{ok:!1,error:`invalid path segment "${o}"`};if(r[0]===".git")return{ok:!1,error:"cannot write under .git"};let s=os.default.resolve(n),i=os.default.resolve(s,t);return i!==s&&!i.startsWith(s+os.default.sep)?{ok:!1,error:"path escapes the checkout"}:{ok:!0,abs:i,rel:t}}async function al(n){let e=nb(n.repoPath,n.relPath);if(!e.ok)return{ok:!1,error:e.error};if(to.default.existsSync(e.abs)&&!n.overwrite)return{ok:!1,error:`${e.rel} already exists in this checkout`};to.default.mkdirSync(os.default.dirname(e.abs),{recursive:!0}),to.default.writeFileSync(e.abs,n.content.endsWith(`
781
798
  `)?n.content:n.content+`
782
- `);let t=s=>new Promise((i,o)=>{(0,Th.execFile)("git",["-C",n.repoPath,...s],{timeout:12e4},(l,u,c)=>l?o(new Error(c||l.message)):i())}),r="";try{await t(["add",e.rel]),await t(["-c","user.name=Allwright","-c","user.email=runner@allwright.local","commit","-m",n.commitMessage]);try{await t(["push"]),r="committed and pushed to the repo"}catch(s){r="committed locally, but push failed: "+(s instanceof Error?s.message.slice(0,200):"unknown")+" - push it from the server when convenient"}}catch(s){r="file written, but commit failed: "+(s instanceof Error?s.message.slice(0,200):"unknown")+" - commit it from the server when convenient"}return{ok:!0,note:r}}var mr=R(require("node:fs"),1),tl=R(require("node:path"),1),Xi=require("node:child_process"),Ch=require("node:util");Wn();pt();var Ih=R(we(),1),xh=(0,Ch.promisify)(Xi.execFile);function Bv(n){try{return new URL(n).host}catch{return n}}function Kv(n){try{return(0,Xi.execFileSync)("git",["-C",n,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim()}catch{return null}}async function Qi(n,e,t=[],r){let s=[],i=n.repos[e.repoName]?.jira,o=i??n.jira,l=(e.jiraSiteUrl??"").trim().toLowerCase();if(!o)s.push({name:"jira-credentials",ok:!1,detail:"no Jira credentials configured on this runner"});else if(!l)s.push({name:"jira-site",ok:!1,detail:"this project has not said which Atlassian site it is on, so nothing here can be verified - a credential that authenticates somewhere else would look like a pass.",fixNote:"This one is fixed in the dashboard, not on the server: open the project and fill in its Atlassian site (for example yourcompany.atlassian.net), then run this test again."});else{let p=Bv(o.baseUrl),b=i?"this repo's own Jira credential":"the runner-wide Jira credential";if(p!==l)s.push({name:"jira-site",ok:!1,detail:`this project is on ${l}, but ${b} is for ${p}.`,fix:[`allwright jira set "${e.repoName}"`],fixNote:`"${e.repoName}" in that command is this project's REPO NAME - the label that ties the project here to a checkout on the server (the same one used with allwright repo add). Not the Jira key, not a folder path. The command asks for three things for ${l}: the base URL (https://${l}), your Jira account email, and an API token from id.atlassian.com/manage-profile/security/api-tokens. They are stored on this server only. Restart afterwards: allwright stop && allwright start`});else{let w=new Pe(o);try{let T=await w.myself();s.push({name:"jira-auth",ok:!0,detail:`authenticated as ${T.displayName} on ${p} (${b})`});try{await w.search(`project = "${e.jiraProjectKey}" ORDER BY created DESC`,1),s.push({name:"jira-project",ok:!0,detail:`project ${e.jiraProjectKey} is readable on ${p}`})}catch(x){s.push({name:"jira-project",ok:!1,detail:`cannot read project ${e.jiraProjectKey} on ${p}: ${js(x)}`})}}catch(T){s.push({name:"jira-auth",ok:!1,detail:`Jira auth failed on ${p}: ${js(T)}`})}}}let u=n.repos[e.repoName];if(u&&mr.default.existsSync(u.path)){let p=tl.default.join(u.path,"CLAUDE.md"),b=mr.default.existsSync(p)&&mr.default.readFileSync(p,"utf8").trim().length>0;s.push({name:"memory-file",kind:"content",ok:b,detail:b?"CLAUDE.md present - the agent has project memory":"MISSING: CLAUDE.md at the repo root. Rules can't be enabled until the project has a memory file - it is what makes every run smarter than the last.",...b?{}:{fixNote:"No command needed: the setup step below this one drafts CLAUDE.md by reading the repo, shows it to you, and commits it when you approve. Writing it by hand works too - any honest description of what the project is and how it is built beats an empty file."}});let w=$i(u.path);s.push({name:"deploy-doc",kind:"content",ok:w!==null,detail:w?`${w.path} present - deploy suggestions will follow it`:"MISSING: DEPLOY.md (or .ticketpilot/deploy.md). Environments can't be created until the repo documents how it deploys.",...w?{}:{fixNote:"Only needed if this project will deploy from Allwright. The setup wizard can draft DEPLOY.md the same way it drafts CLAUDE.md - describe how you deploy today (the commands you actually run), and the agent proposes steps a human saves. Skip it if you only want tickets to become pull requests."}})}if(!u)s.push({name:"repo-path",ok:!1,detail:`no local path mapped for repo "${e.repoName}" - run: allwright repo add "${e.repoName}" /path/to/checkout`});else if(!mr.default.existsSync(u.path))s.push({name:"repo-path",ok:!1,detail:`path does not exist: ${u.path}`});else{let p=mr.default.existsSync(tl.default.join(u.path,".git"));s.push({name:"repo-path",ok:!0,detail:`${u.path}${p?" (git checkout)":" (warning: not a git checkout)"}`})}let c=[...new Set([e.defaultAgent||"claude-code",...r??[]])];for(let p of c){let b=je(n,p),w=p==="claude-code"?"claude-code":`agent:${p}`;try{let{stdout:T}=await xh(b,["--version"],{timeout:15e3});s.push({name:w,ok:!0,detail:T.trim().slice(0,100)})}catch(T){s.push({name:w,ok:!1,detail:`cannot run "${b}" for agent "${p}": ${js(T)}`,fixNote:p==="claude-code"?"Install Claude Code on this server (npm install -g @anthropic-ai/claude-code) and log it in.":`Install the "${p}" CLI on this server, or point the runner at its binary in the config's agents section.`})}}try{let{stdout:p}=await xh("git",["--version"],{timeout:15e3});s.push({name:"git",ok:!0,detail:p.trim().slice(0,100)})}catch(p){s.push({name:"git",ok:!1,detail:`cannot run git: ${js(p)}`})}let f=Te(n,e.repoName);if(!f)s.push({name:"github-token",ok:!1,detail:`no GitHub token applies to "${e.repoName}" - implement rules cannot push.`,fix:[`allwright github set "${e.repoName}"`,"allwright github set-token"],fixNote:`"${e.repoName}" is this project's REPO NAME - the same label used with allwright repo add, not a folder path. The first command stores a token for this repo alone (separately revocable); the second stores one shared by every repo on this server. Both print the exact permission checklist before asking. In short: create it at ${Ih.GITHUB_TOKEN_PERMISSIONS.where}, with the RESOURCE OWNER set to the org that owns the repo (the usual mistake), Contents and Pull requests both Read and write.`});else try{let{GitHubClient:p}=await Promise.resolve().then(()=>(nt(),Qn)),b=new p(f),w=await b.whoami(),T=u&&mr.default.existsSync(u.path)?Kv(u.path):null,x=T?et(T):null;if(!x)s.push({name:"github-token",ok:!0,detail:`authenticated as ${w} - repo access not checked (no local checkout yet)`});else{let A=await b.repoAccess(x.owner,x.repo);s.push({name:"github-token",ok:A.ok&&A.canPush,detail:A.ok?A.canPush?`${w} has push access to ${x.owner}/${x.repo}`:`${w} can read ${x.owner}/${x.repo} but NOT push to it - implement rules will fail at the push`:`${w} cannot see ${x.owner}/${x.repo}: ${A.error}`,...A.ok&&A.canPush?{}:{fix:[`allwright github set "${e.repoName}"`],fixNote:`Two ways: edit the existing PAT on GitHub and add ${x.owner}/${x.repo} to it with contents:write and pull_requests:write - or give this repo its own token with the command above. A fine-grained PAT only ever covers ONE organisation, so a repo in a different org than your other projects always needs its own.`}})}}catch(p){s.push({name:"github-token",ok:!1,detail:js(p)})}if(t.length){n.deploy.enabled?s.push({name:"deploy",ok:!0,detail:"deployments enabled on this runner"}):s.push({name:"deploy",ok:!1,detail:"deployments are disabled on this runner - run `allwright deploy enable` to allow it to execute your saved deploy steps"});for(let p of t){let b=Cn(n,e.repoName,p.name),w=p.requiredSecrets.filter(T=>!b[T]&&!process.env[T]);s.push({name:`env:${p.name}`,ok:w.length===0,detail:w.length?`missing secret(s): ${w.join(", ")} - allwright env set "${e.repoName}" "${p.name}" ${w[0]}=...`:`${p.steps.length} step(s), ${p.requiredSecrets.length} secret(s) present`+(p.branch?`, deploys origin/${p.branch}`:"")})}}return s}function js(n){return(n instanceof Error?n.message:String(n)).slice(0,300)}var ve=new kl;ve.name("allwright").description("Allwright runner - runs on YOUR machine, holds YOUR credentials locally, connects outbound-only to the control plane. Your Jira token, Anthropic key and source code never leave this host.").version(li);function Oh(n){y.info(`Create the token at ${Lt.GITHUB_TOKEN_PERMISSIONS.where}`);for(let e of Lt.GITHUB_TOKEN_PERMISSIONS.steps)y.info(` - ${e}`);y.info(Lt.GITHUB_TOKEN_PERMISSIONS.note),y.info(`Then paste it below for ${n}.`)}ve.command("init").description("Interactive setup: enroll this runner and store credentials locally").option("--cp-url <url>","control plane URL").option("--enroll-token <token>","enrolment token from the Allwright UI").option("--name <name>","runner name",nl.default.hostname()).option("--jira-url <url>","Jira base URL, e.g. https://yourorg.atlassian.net").option("--jira-email <email>","Jira account email").option("--jira-token <token>","Jira API token (stored locally only)").action(async n=>{let e=yr.default.createInterface({input:process.stdin,output:process.stdout}),t=async(r,s,i=!1)=>{if(s)return s;let o=await e.question(`${r}: `);if(!o.trim())throw new Error(`${r} is required`);return o.trim()};try{let r=await t("Control plane URL",n.cpUrl),s=await t("Enrolment token (from the web UI)",n.enrollToken),i=await t("Jira base URL (https://yourorg.atlassian.net)",n.jiraUrl),o=await t("Jira account email",n.jiraEmail),l=await t("Jira API token (create at id.atlassian.com/manage-profile/security/api-tokens)",n.jiraToken,!0),u=ko.parse({controlPlaneUrl:r,runnerName:n.name,jira:{baseUrl:i,email:o,apiToken:l}}),c=await new Pe(u.jira).myself();y.info(`Jira credential OK - authenticated as ${c.displayName}`),u=await mu(u,s),y.info(`Enrolled as runner "${u.runnerName}" (${u.runnerId})`),y.info(`Credentials saved to ${Gt()} (mode 600, this machine only)`),y.info("Next: map your repo with `allwright repo add <repoName> <localPath>`, then `allwright start`")}finally{e.close()}});var rl=ve.command("repo").description("Map control-plane repo names to local checkouts");rl.command("add <repoName> <localPath>").description("Map a repo name (as configured in the web UI) to a local checkout path").action(async(n,e)=>{let t=ie();t.repos[n]={path:e},fe(t),y.info(`mapped repo "${n}" -> ${e}`);try{let{originUrl:r}=await Promise.resolve().then(()=>(pt(),Su));y.info(` origin remote: ${await r(e)} - make sure this is the repo you meant`)}catch{y.warn(` could not read an origin remote at ${e} - is it a git checkout?`)}});rl.command("list").description("Show configured repo mappings").action(()=>{let n=ie(),e=Object.entries(n.repos);if(!e.length)return y.info("no repos mapped yet");for(let[t,r]of e)y.info(`${t} -> ${r.path}`)});var Nh=ve.command("claude").description("Per-user Claude login profiles - each teammate's runs bill their OWN Claude account");Nh.command("login <profileName>").description("Create (or re-login) a named Claude profile. Opens Claude Code interactively with its own config directory - have the PERSON WHOSE ACCOUNT IT IS complete the /login flow with their credentials, then exit. Assign the profile to their user on the dashboard's Team page.").action(async n=>{if(!/^[a-zA-Z0-9._-]+$/.test(n))throw new Error("profile name: letters, digits, dots, dashes and underscores only");let e=ie(),t=e.claudeProfiles[n]?.configDir??`${Gt().replace(/runner\.json$/,"")}claude-profiles/${n}`;ot.default.mkdirSync(t,{recursive:!0,mode:448}),e.claudeProfiles[n]={configDir:t},fe(e),y.info(`profile "${n}" -> ${t}`),y.info("Opening Claude Code with this profile. In it: run /login, complete the browser flow"),y.info("with the account this profile belongs to, then exit Claude (ctrl+c twice or /exit).");let r=(0,Ut.spawn)(e.claudeBin,[],{env:{...process.env,CLAUDE_CONFIG_DIR:t},stdio:"inherit"});await new Promise(s=>r.on("exit",()=>s())),y.info(`Done. Assign it on the dashboard: Team -> the user -> Claude profile = "${n}".`),ss()});Nh.command("list").description("Show configured Claude profiles and whether each looks logged in").action(()=>{let n=ie(),e=Object.entries(n.claudeProfiles);if(y.info("default: this OS user's own Claude login (no profile)"),!e.length)return y.info("no named profiles yet - allwright claude login <name>");for(let[t,r]of e){let s=ot.default.existsSync(r.configDir)&&ot.default.readdirSync(r.configDir).length>0;y.info(`${t} -> ${r.configDir} ${s?"(logged in)":"(NOT logged in yet)"}`)}});rl.command("remove <repoName>").description("Unmap a repo from this runner: removes the mapping plus its per-repo Jira/GitHub overrides and env secrets from the config. Does NOT touch the checkout on disk or anything in the control plane - delete the project on the dashboard separately.").action(n=>{let e=ie();if(!e.repos[n]){let i=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${n}" - mapped repos: ${i}`)}let t=e.repos[n].path;delete e.repos[n];let r=Object.keys(e.environments).filter(i=>i.startsWith(`${n}:`));for(let i of r)delete e.environments[i];let s=e.auditSchedules.length;e.auditSchedules=e.auditSchedules.filter(i=>i.repoName!==n),fe(e),y.info(`Removed "${n}" (was ${t})`),r.length&&y.info(`Also removed ${r.length} environment secret set(s): ${r.join(", ")}`),e.auditSchedules.length!==s&&y.info("Also removed its audit schedule(s)"),y.info("The checkout on disk was NOT touched - remove it yourself if you want it gone."),y.info("Restart the runner to apply. Dashboard project (if any) is deleted separately there.")});var sl=ve.command("service").description("Run the runner as a system service (starts on boot, restarts on crash)");sl.command("install").description("Install + start the systemd service - detects node, this script, your user and home; no hand-written unit files. Run with sudo. (--print shows the unit without installing.)").option("--print","print the generated unit file and exit").action(n=>{if(n.print){y.info(`
783
- `+Xo(Yo()));return}Au(y)});sl.command("uninstall").description("Stop and remove the systemd service (config/credentials untouched)").action(()=>$u(y));sl.command("status").description("systemctl status for the runner service").action(()=>{(0,Ut.spawn)("systemctl",["status","allwright","--no-pager"],{stdio:"inherit"}).on("exit",e=>process.exit(e??0))});ve.command("update").description("Update the runner to the latest published version (npm install -g allwright@latest). Restart the runner afterwards - and only when no runs are active.").action(async()=>{y.info("Updating: npm install -g allwright@latest");let n=(0,Ut.spawn)("npm",["install","-g","allwright@latest"],{stdio:"inherit"});await new Promise((e,t)=>{n.on("exit",r=>r===0?e():t(new Error(`npm exited with code ${r}`))),n.on("error",t)}),y.info("Updated. Restart the runner service to load the new version (check active runs first).")});var Ns=ve.command("jira").description("Per-repo Jira site overrides - for projects living on a different Atlassian site");Ns.command("set <repoName>").description("Store Jira credentials for ONE repo's project (e.g. a project on a different *.atlassian.net site than the runner's main credential). Prompts on stdin; stored locally only, like every other credential.").action(async n=>{let e=ie();if(!e.repos[n]){let l=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${n}" - mapped repos: ${l}. Run \`allwright repo add\` first.`)}let t=vd(n),r=(t?.jiraSiteUrl??"").trim(),s=r?`https://${r}`:"",i=e.jira?.email??"";if(s&&i&&e.jira?.apiToken){let l={baseUrl:s,email:i,apiToken:e.jira.apiToken};try{let u=await new Pe(l).myself();if(e.repos[n].jira=l,fe(e),y.info(`The token already on this server works on ${r} - authenticated as ${u.displayName}. Saved it for "${n}"; nothing to type.`),t?.jiraProjectKey)try{await new Pe(l).search(`project = "${t.jiraProjectKey}"`,1),y.info(`Project ${t.jiraProjectKey} is readable with it.`)}catch{y.warn(`Authenticated, but project ${t.jiraProjectKey} is not readable with this account. Ask a Jira admin for access, or re-run this command to enter a different account's token.`)}ss();return}catch{y.info(`The token already on this server does not work on ${r} - asking for one that does.`)}}let o=yr.default.createInterface({input:process.stdin,output:process.stdout});try{let u=(await o.question(s?`Jira base URL [${s}]: `:"Jira base URL for this repo (https://yourorg.atlassian.net): ")).trim()||s,f=(await o.question(i?`Jira account email [${i}]: `:"Jira account email: ")).trim()||i,p=(await o.question("Jira API token (id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!u||!f||!p)throw new Error("all three values are required");let b={baseUrl:u,email:f,apiToken:p},w=await new Pe(b).myself();y.info(`Jira credential OK - authenticated as ${w.displayName} on ${u}`),e.repos[n].jira=b,fe(e),y.info(`Saved: repo "${n}" now polls ${u} (other repos keep the runner-wide credential)`),ss()}finally{o.close()}});Ns.command("show").description("Show which Jira site each repo uses (never prints tokens)").action(()=>{let n=ie();y.info(`runner-wide: ${n.jira?`${n.jira.baseUrl} (${n.jira.email})`:"(not configured)"}`);for(let[e,t]of Object.entries(n.repos))y.info(`${e} -> ${t.jira?`${t.jira.baseUrl} (${t.jira.email})`:"(runner-wide credential)"}`)});Ns.command("user-add <ticketpilotEmail>").description("Store a PERSON's own Jira credential, so board buttons and Compose tickets they click post to Jira under THEIR Atlassian identity instead of the runner's account. Keyed by their Allwright login email. Prompts on stdin; stored locally only. Picked up on the next click - no restart needed.").action(async n=>{let e=ie(),t=n.trim().toLowerCase();if(!t.includes("@"))throw new Error(`"${n}" doesn't look like an email`);let r=yr.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await r.question(`Their ATLASSIAN account email [${t}]: `)).trim()||t,i=(await r.question("Their Jira API token (they create it at id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!i)throw new Error("API token is required");let o=[e.jira,...Object.values(e.repos).map(c=>c.jira)].filter(c=>!!c),l=new Set,u=!1;for(let c of o)if(!l.has(c.baseUrl)){l.add(c.baseUrl);try{let f=await new Pe({baseUrl:c.baseUrl,email:s,apiToken:i}).myself();y.info(`${c.baseUrl}: OK - authenticated as ${f.displayName}`),u=!0}catch{y.warn(`${c.baseUrl}: this credential does NOT work there (fine if they don't use that site)`)}}if(!u)throw new Error("credential failed on every configured Jira site - nothing saved");e.jiraUsers[t]={email:s,apiToken:i},fe(e),y.info(`Saved. Dashboard actions by ${t} now post to Jira as ${s}. No restart needed.`)}finally{r.close()}});Ns.command("user-list").description("Show which Allwright users have their own Jira credential here (never prints tokens)").action(()=>{let n=ie(),e=Object.entries(n.jiraUsers);if(!e.length)return y.info("none yet - everyone's dashboard clicks require one: allwright jira user-add <their-ticketpilot-email>");for(let[t,r]of e)y.info(`${t} -> posts to Jira as ${r.email}`)});Ns.command("user-remove <ticketpilotEmail>").description("Delete a person's stored Jira credential").action(n=>{let e=ie(),t=n.trim().toLowerCase();if(!e.jiraUsers[t])throw new Error(`no credential stored for ${t}`);delete e.jiraUsers[t],fe(e),y.info(`Removed. Dashboard actions by ${t} will now be refused until a new credential is added.`)});var is=ve.command("github").description("GitHub credential for implement-mode rules");is.command("set-token").description("Store a GitHub token for opening pull requests (implement rules). Stored locally only, like your Jira token. Recommended: a fine-grained PAT scoped to the repo with contents:write + pull_requests:write.").option("--token <token>","GitHub token (omit to be prompted)").action(async n=>{let e=yr.default.createInterface({input:process.stdin,output:process.stdout});try{let t=n.token??void Oh("every repo on this server")??(await e.question("GitHub token: ")).trim();if(!t)throw new Error("token is required");let{GitHubClient:r}=await Promise.resolve().then(()=>(nt(),Qn)),s=await new r(t).whoami(),i=ie();i.github={token:t,login:s},fe(i),y.info(`GitHub token OK - authenticated as ${s}`),y.info(`Saved to ${Gt()} (mode 600, this machine only)`)}finally{e.close()}});is.command("set <repoName>").description("Store a GitHub token for ONE repo only - overrides the runner-wide token for that repo's PRs and PR-watching. Useful when projects need separately revocable access. Prompts on stdin; stored locally only.").action(async n=>{let e=ie();if(!e.repos[n]){let i=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${n}" - mapped repos: ${i}. Run \`allwright repo add\` first.`)}let t=e.github?.token,r=e.repos[n]?.path;if(t&&r&&ot.default.existsSync(r))try{let i=(0,Ut.execFileSync)("git",["-C",r,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim(),o=et(i);if(o){let{GitHubClient:l}=await Promise.resolve().then(()=>(nt(),Qn)),u=new l(t),c=await u.repoAccess(o.owner,o.repo);if(c.ok&&c.canPush){let f=await u.whoami();y.info(`The shared token on this server already has push access to ${o.owner}/${o.repo} as ${f} - "${n}" needs nothing of its own. Storing a second token here would only give you two to rotate.`),y.info("Want a separately revocable one anyway? Paste it at the prompt below; press Enter to leave things as they are.")}}}catch{}let s=yr.default.createInterface({input:process.stdin,output:process.stdout});try{Oh(`"${n}"`);let i=(await s.question(`GitHub token for "${n}": `)).trim();if(!i&&t){y.info(`Nothing changed - "${n}" keeps using the shared token.`);return}if(!i)throw new Error("token is required");let{GitHubClient:o}=await Promise.resolve().then(()=>(nt(),Qn)),l=await new o(i).whoami();e.repos[n].github={token:i,login:l},fe(e),y.info(`GitHub token OK - authenticated as ${l}`),y.info(`Saved: repo "${n}" now uses its own token (other repos keep the runner-wide one)`)}finally{s.close()}});is.command("user-add <ticketpilotEmail>").description("Store a PERSON's own GitHub token, so PRs from implement runs THEY trigger are authored by their GitHub account. Keyed by their Allwright login email. Optional - without it their runs fall back to the repo/runner-wide token. Needs contents:write + pull_requests:write on the repos they'll touch.").action(async n=>{let e=ie(),t=n.trim().toLowerCase();if(!t.includes("@"))throw new Error(`"${n}" doesn't look like an email`);let r=yr.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await r.question(`GitHub token for ${t}: `)).trim();if(!s)throw new Error("token is required");let{GitHubClient:i}=await Promise.resolve().then(()=>(nt(),Qn)),o=await new i(s).whoami();e.githubUsers[t]={token:s,login:o},fe(e),y.info(`GitHub token OK - authenticated as ${o}`),y.info(`Saved. Implement runs triggered by ${t} now open PRs as ${o}. No restart needed.`)}finally{r.close()}});is.command("user-list").description("Show which Allwright users have their own GitHub token here (never prints tokens)").action(()=>{let n=ie(),e=Object.entries(n.githubUsers);if(!e.length)return y.info("no per-user GitHub tokens - everyone's PRs use the repo/runner-wide token");for(let[t]of e)y.info(`${t} -> own GitHub token stored`)});is.command("user-remove <ticketpilotEmail>").description("Delete a person's stored GitHub token (their runs fall back to the shared token)").action(n=>{let e=ie(),t=n.trim().toLowerCase();if(!e.githubUsers[t])throw new Error(`no GitHub token stored for ${t}`);delete e.githubUsers[t],fe(e),y.info(`Removed. ${t}'s runs use the repo/runner-wide token again.`)});is.command("show").description("Show which GitHub token each repo and person would use (never prints tokens)").action(()=>{let n=ie();y.info(`runner-wide: ${n.github?.token?"token set":"(not configured)"}`);for(let[t,r]of Object.entries(n.repos))y.info(`${t} -> ${r.github?.token?"own repo token":"runner-wide token"}`);let e=Object.keys(n.githubUsers);y.info(e.length?`per-user tokens: ${e.join(", ")}`:"per-user tokens: (none)")});var il=ve.command("audit").description("Recurring specialist audits on this runner");il.command("schedule <repoName> <role> <intervalHours>").description("Audit this repo's project on a cadence (role: security|testing; interval in hours, min 6). Runs on the runner's own clock; reports land in the Audits page history, where the diff-vs-previous view shows drift. Advisory only - nothing blocks.").action((n,e,t)=>{let r=ie();if(!r.repos[n]){let i=Object.keys(r.repos).join(", ")||"(none)";throw new Error(`unknown repo "${n}" - mapped repos: ${i}`)}if(e!=="security"&&e!=="testing")throw new Error('role must be "security" or "testing"');let s=parseInt(t,10);if(!Number.isInteger(s)||s<6||s>720)throw new Error("intervalHours must be 6-720");r.auditSchedules=[...r.auditSchedules.filter(i=>!(i.repoName===n&&i.role===e)),{repoName:n,role:e,intervalHours:s}],fe(r),y.info(`Scheduled: ${e} audit of "${n}" every ${s}h. Restart the runner to apply.`)});il.command("schedules").description("List scheduled audits").action(()=>{let n=ie();if(!n.auditSchedules.length)return y.info("no scheduled audits - allwright audit schedule <repo> <role> <hours>");for(let e of n.auditSchedules)y.info(`${e.repoName} \xB7 ${e.role} \xB7 every ${e.intervalHours}h`)});il.command("unschedule <repoName> <role>").description("Remove a scheduled audit").action((n,e)=>{let t=ie(),r=t.auditSchedules.length;if(t.auditSchedules=t.auditSchedules.filter(s=>!(s.repoName===n&&s.role===e)),t.auditSchedules.length===r)throw new Error("no such schedule");fe(t),y.info("Removed. Restart the runner to apply.")});var ol=ve.command("deploy").description("Deployment settings for this machine");ol.command("enable").description("Allow this runner to execute the deploy steps saved in the dashboard. Those steps are shell commands that run here, as this user - so this switch lives on the machine, not in the web UI, and only someone with shell access can flip it.").action(()=>{let n=ie();n.deploy={enabled:!0},fe(n),y.info("deployments ENABLED on this runner"),y.info("This runner will now execute the deploy steps configured for your environments. Review them in the dashboard before shipping to production."),ss()});ol.command("disable").description("Stop this runner from executing any deploy steps").action(()=>{let n=ie();n.deploy={enabled:!1},fe(n),y.info("deployments DISABLED on this runner"),ss()});ol.command("status").description("Show whether deployments are enabled here, and which env secrets are stored").action(()=>{let n=ie();y.info(`deployments: ${n.deploy.enabled?"enabled":"disabled"}`);let e=Object.entries(n.environments);if(!e.length)return y.info("no environment secrets stored");for(let[t,r]of e){let s=Object.keys(r.secrets);y.info(`${t}: ${s.length?s.join(", "):"(no secrets)"}`)}});var al=ve.command("env").description("Per-environment deploy secrets. Values stay on this machine, like your Jira token.");al.command("set <repoName> <envName> <assignments...>").description('Store secrets for one environment, e.g. env set acme/api production "SSH_HOST=1.2.3.4" "SSH_USER=deploy". Your deploy steps reference these as $SSH_HOST. The control plane only ever learns the NAMES.').action((n,e,t)=>{let r=ie(),s=Vs(n,e),i=r.environments[s]??{secrets:{}},o=[];for(let l of t){let u=l.indexOf("=");if(u<=0)throw new Error(`expected KEY=VALUE, got "${l}"`);let c=l.slice(0,u).trim();i.secrets[c]=l.slice(u+1),o.push(c)}r.environments[s]=i,fe(r),y.info(`stored ${o.length} secret(s) for ${s}: ${o.join(", ")}`),y.info(`Saved to ${Gt()} (mode 600, this machine only)`),ss()});al.command("unset <repoName> <envName> <names...>").description("Remove stored secrets for an environment").action((n,e,t)=>{let r=ie(),s=Vs(n,e),i=r.environments[s];if(!i)return y.info(`nothing stored for ${s}`);for(let o of t)delete i.secrets[o];r.environments[s]=i,fe(r),y.info(`removed ${t.join(", ")} from ${s}`)});al.command("list").description("Show which environments have secrets stored here (names only, never values)").action(()=>{let n=ie(),e=Object.entries(n.environments);if(!e.length)return y.info("no environment secrets stored");for(let[t,r]of e)y.info(`${t}: ${Object.keys(r.secrets).join(", ")||"(none)"}`)});ve.command("export [file]").description("Back up ALL runner state (config+secrets, knowledge, audits, chats) to one tarball").action(n=>{try{let e=Nl(n);y.info(`Backup written: ${e.file} (${e.entries.length} entries, mode 600)`),y.warn("This file CONTAINS YOUR SECRETS (Jira/GitHub tokens). Keep it private - anyone holding it can act as this runner."),y.info(`Restore on any machine with: allwright import ${rs.default.basename(e.file)}`)}catch(e){y.error(e instanceof Error?e.message:String(e)),process.exitCode=1}});ve.command("import <file>").description("Restore runner state from an `export` tarball (existing config is kept as a .bak dir)").action(n=>{let e=In();if(e&&Rn(e)){y.error("the runner is running - stop it first (systemctl stop allwright, or `allwright stop` for a pid-file daemon), then import."),process.exitCode=1;return}try{let t=Ml(n);y.info(`Restored ${t.restored.length} entries into ${re()}`),t.previousDir&&y.info(`Previous config kept at ${t.previousDir}`),y.info("Start the runner and it will reconnect with the restored identity.")}catch(t){y.error(t instanceof Error?t.message:String(t)),process.exitCode=1}});ve.command("test").description("Check local setup: Jira auth, repo mappings, Claude Code binary").action(async()=>{let n=ie(),e=Object.keys(n.repos);if(!n.jira){y.error("no Jira credentials configured - run `allwright init`"),process.exitCode=1;return}let t=e.length?e.map(s=>({jiraProjectKey:"*",repoName:s})):[{jiraProjectKey:"*",repoName:"(none mapped)"}],r=!0;for(let s of t){let i=await Qi(n,s);for(let o of i){if(s.jiraProjectKey==="*"&&o.name==="jira-project")continue;let l=o.ok?"PASS":"FAIL";(o.ok?y.info:y.error)(`[${l}] ${o.name}: ${o.detail}`),r&&=o.ok}}r||(process.exitCode=1)});function ss(){let n=In();if(n&&Rn(n)&&process.platform!=="win32")try{process.kill(n,"SIGHUP"),y.info("running runner reloaded its config live - no restart needed");return}catch{}y.info("No background runner found to reload. Under systemd: sudo systemctl kill -s HUP allwright - otherwise it applies on the next allwright start.")}function Hv(n){if(!n.runnerToken)throw new Error("runner not enrolled - run `allwright init`");if(!n.jira)throw new Error("no Jira credentials - run `allwright init`");let e=Bl();e.ok||(y.warn(`another runner is already running on this machine (pid ${e.pid}). Two runner processes with one identity kick each other off the control plane every second. Stop the other one first: \`allwright stop\` (background runner) or \`sudo systemctl stop allwright\` (service).`),process.exit(1)),process.on("exit",xo);let t=new Pe(n.jira),r=new Map,s=h=>{let m=n.repos[h]?.jira;if(!m)return t;let g=r.get(h);return g||(g=new Pe(m),r.set(h,g)),g},i=new Map,o=(h,m)=>{let g=Cu(me()??n,h,m);switch(g.kind){case"legacy":return{jira:s(h),authored:!1};case"self":return{jira:s(h),authored:!0};case"missing":return{error:g.error};case"user":{let C=`${g.creds.baseUrl}:${g.creds.email}:${g.creds.apiToken.slice(-6)}`,N=i.get(C);return N||(N=new Pe(g.creds),i.set(C,N)),{jira:N,authored:!0}}}},l=new URL("/api/runner/ws",n.controlPlaneUrl);l.protocol=l.protocol==="https:"?"wss:":"ws:";let u=[],c=[],f=[],p,b=null,w={cfg:n,jiraFor:s,transport:null},T=new Set,x=h=>{let m=u.find(C=>C.id===h),g=m&&n.repos[m.repoName];return m&&g?{project:m,repoPath:g.path}:null},A={cfg:n,jiraFor:s,get transport(){return w.transport},lookup:(h,m)=>{let g=x(h),C=f.find(N=>N.projectId===h&&N.name===m);return g&&C?{...g,environment:C}:null}},v=new Ji(l.toString(),n.runnerToken,{runnerVersion:li},{onConfig:h=>{u=h.projects,yd(h.projects),c=h.rules,f=h.environments,p.setConfig(h.projects,h.rules,h.pollingPaused,h.environments)},onDeployFix:async h=>{let m=x(h.projectId);if(!m){v.sendDeploySuggestResult(h.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:"this runner has no local checkout mapped for that project"});return}let g=tt(n,m.project,"assist");if("error"in g){v.sendDeploySuggestResult(h.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:g.error});return}y.info(`investigating failed deploy of "${h.environmentName}" (step: ${h.failedStep||"?"})`);let C=await Yc({agent:g,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:h.environmentName,steps:h.steps,failedStep:h.failedStep,errorText:h.errorText,cfg:n});v.sendDeploySuggestResult(h.requestId,C)},onProjectTest:async h=>{let m=u.find(C=>C.id===h.projectId);if(!m){v.sendProjectTestResult(h.requestId,!1,[{name:"config",ok:!1,detail:"project not in this runner's synced config yet"}]);return}y.info(`running connection test for project "${m.name}"`);let g=await Qi(me()??n,m,f.filter(C=>C.projectId===m.id),c.filter(C=>C.projectId===m.id).map(C=>"agent"in C.action?C.action.agent:"").filter(Boolean));v.sendProjectTestResult(h.requestId,g.every(C=>C.ok),g)},onRuleDiagnose:async h=>{let m=c.find(H=>H.id===h.ruleId),g=m&&u.find(H=>H.id===m.projectId);if(!m||!g){v.sendRuleDiagnoseResult(h.requestId,{checks:[{name:"config",ok:!1,detail:"rule not in this runner's synced config yet"}],matchedCount:0,excludedCount:0,excludedSample:[]});return}y.info(`diagnosing rule "${m.name}"`);let C=await Qi(me()??n,g,m.action.type==="deploy"?f.filter(H=>H.projectId===g.id):[]),N=m.action.type==="implement"?C:C.filter(H=>H.name!=="github-token"),{matchedCount:F,excludedCount:X,excludedSample:ee}=await p.diagnoseRule(m,g);v.sendRuleDiagnoseResult(h.requestId,{checks:N,matchedCount:F,excludedCount:X,excludedSample:ee})},onCancel:h=>{Sc(h)?y.info(`run ${h} stopped from the dashboard`):y.warn(`cancel requested for run ${h}, but nothing is running under that id here - it likely finished already`)},onApproved:(h,m)=>{if(Ta(h)){Zc(A,h).catch(g=>y.error(`deploy approval crashed for ${h}: ${g instanceof Error?g.stack:g}`));return}ks(w,h,m).catch(g=>y.error(`approval handling crashed for ${h}: ${g instanceof Error?g.stack:g}`))},onRetryPush:h=>{let m=ki(h),g=()=>jc(w,h).catch(C=>y.error(`retry push crashed for ${h}: ${C instanceof Error?C.stack:C}`));m?p.runOnRepoQueue(m.baseRepoPath,g):g()},onRejected:h=>{if(Ta(h)){Gc(A,h).catch(m=>y.error(`deploy rejection crashed for ${h}: ${m instanceof Error?m.stack:m}`));return}Pc(w,h).catch(m=>y.error(`rejection handling crashed for ${h}: ${m instanceof Error?m.stack:m}`))},onDeployStart:h=>{let m=`${h.runId}#${h.attempt}`;if(T.has(m))return;T.add(m);let g=x(h.projectId);if(!g){let C="this runner has no local checkout mapped for that project - run: allwright repo add <repoName> /path/to/checkout";y.error(`deploy ${h.runId}: ${C}`),v.send({type:"run.status",runId:h.runId,status:"failed",error:C});return}y.info(`deploy ${h.runId} requested from the dashboard: ${h.issueKey} \u2192 ${h.environment.name}`),p.runOnEnvironmentQueue(h.environment.id,()=>Ai({runId:h.runId,project:g.project,environment:h.environment,issueKey:h.issueKey,issueSummary:h.issueSummary,repoPath:g.repoPath,cfg:n,jira:s(g.project.repoName),transport:v,requestedBy:h.requestedBy}).catch(C=>y.error(`deploy crashed for ${h.runId}: ${C instanceof Error?C.stack:C}`)))},onDeploySuggest:async h=>{let m=x(h.projectId);if(!m){v.sendDeploySuggestResult(h.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:"this runner has no local checkout mapped for that project"});return}let g=tt(n,m.project,"assist");if("error"in g){v.sendDeploySuggestResult(h.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:g.error});return}y.info(`asking ${g.adapter.displayName} for "${h.environmentName}" deploy steps in ${m.repoPath}`);let C=await Xc({agent:g,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:h.environmentName,notes:h.notes,timeoutSeconds:h.timeoutSeconds,cfg:n});v.sendDeploySuggestResult(h.requestId,C)},onEnvPreflight:async h=>{let m=x(h.projectId);if(!m){v.sendEnvPreflightResult(h.requestId,{ok:!1,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project"}]});return}let g=await Jc({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:h.environmentName,steps:h.steps,requiredSecrets:h.requiredSecrets,workdir:h.workdir,branch:h.branch,publicUrl:h.publicUrl,cfg:n});v.sendEnvPreflightResult(h.requestId,g)},onChatTurn:async h=>{let m=x(h.projectId);if(!m){v.sendChatTurnResult(h.requestId,{ok:!1,sessionId:h.sessionId??"",reply:"",error:"this runner has no local checkout mapped for that project"});return}let g=h.sessionId||(0,to.randomUUID)(),C=!h.sessionId;if((C?0:Ea(g)?.messages.length??0)>=44){v.sendChatTurnResult(h.requestId,{ok:!1,sessionId:g,reply:"",error:"this chat has hit its length limit - every turn re-reads the whole conversation, so long chats get slow and expensive. Start a new chat (it keeps the repo knowledge; only the conversation resets)."});return}let F=h.files.length?Ll(m.repoPath,h.requestId,h.files):null,X="```",ee=C?`You are the project assistant for "${m.project.name}" - this working directory is its repository, and you have read-only access.
799
+ `);let t=s=>new Promise((i,o)=>{(0,Oh.execFile)("git",["-C",n.repoPath,...s],{timeout:12e4},(l,u,c)=>l?o(new Error(c||l.message)):i())}),r="";try{await t(["add",e.rel]),await t(["-c","user.name=Allwright","-c","user.email=runner@allwright.local","commit","-m",n.commitMessage]);try{await t(["push"]),r="committed and pushed to the repo"}catch(s){r="committed locally, but push failed: "+(s instanceof Error?s.message.slice(0,200):"unknown")+" - push it from the server when convenient"}}catch(s){r="file written, but commit failed: "+(s instanceof Error?s.message.slice(0,200):"unknown")+" - commit it from the server when convenient"}return{ok:!0,note:r}}var vr=R(require("node:fs"),1),ll=R(require("node:path"),1),no=require("node:child_process"),Mh=require("node:util");Xn();gt();var zh=R(we(),1),Nh=(0,Mh.promisify)(no.execFile);function rb(n){try{return new URL(n).host}catch{return n}}function sb(n){try{return(0,no.execFileSync)("git",["-C",n,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim()}catch{return null}}async function ro(n,e,t=[],r){let s=[],i=n.repos[e.repoName]?.jira,o=i??n.jira,l=(e.jiraSiteUrl??"").trim().toLowerCase();if(!o)s.push({name:"jira-credentials",ok:!1,detail:"no Jira credentials configured on this runner"});else if(!l)s.push({name:"jira-site",ok:!1,detail:"this project has not said which Atlassian site it is on, so nothing here can be verified - a credential that authenticates somewhere else would look like a pass.",fixNote:"This one is fixed in the dashboard, not on the server: open the project and fill in its Atlassian site (for example yourcompany.atlassian.net), then run this test again."});else{let p=rb(o.baseUrl),b=i?"this repo's own Jira credential":"the runner-wide Jira credential";if(p!==l)s.push({name:"jira-site",ok:!1,detail:`this project is on ${l}, but ${b} is for ${p}.`,fix:[`allwright jira set "${e.repoName}"`],fixNote:`"${e.repoName}" in that command is this project's REPO NAME - the label that ties the project here to a checkout on the server (the same one used with allwright repo add). Not the Jira key, not a folder path. The command asks for three things for ${l}: the base URL (https://${l}), your Jira account email, and an API token from id.atlassian.com/manage-profile/security/api-tokens. They are stored on this server only. Restart afterwards: allwright stop && allwright start`});else{let w=new Ce(o);try{let T=await w.myself();s.push({name:"jira-auth",ok:!0,detail:`authenticated as ${T.displayName} on ${p} (${b})`});try{await w.search(`project = "${e.jiraProjectKey}" ORDER BY created DESC`,1),s.push({name:"jira-project",ok:!0,detail:`project ${e.jiraProjectKey} is readable on ${p}`})}catch(C){s.push({name:"jira-project",ok:!1,detail:`cannot read project ${e.jiraProjectKey} on ${p}: ${Ls(C)}`})}}catch(T){s.push({name:"jira-auth",ok:!1,detail:`Jira auth failed on ${p}: ${Ls(T)}`})}}}let u=n.repos[e.repoName];if(u&&vr.default.existsSync(u.path)){let p=ll.default.join(u.path,"CLAUDE.md"),b=vr.default.existsSync(p)&&vr.default.readFileSync(p,"utf8").trim().length>0;s.push({name:"memory-file",kind:"content",ok:b,detail:b?"CLAUDE.md present - the agent has project memory":"MISSING: CLAUDE.md at the repo root. Rules can't be enabled until the project has a memory file - it is what makes every run smarter than the last.",...b?{}:{fixNote:"No command needed: the setup step below this one drafts CLAUDE.md by reading the repo, shows it to you, and commits it when you approve. Writing it by hand works too - any honest description of what the project is and how it is built beats an empty file."}});let w=Ni(u.path);s.push({name:"deploy-doc",kind:"content",ok:w!==null,detail:w?`${w.path} present - deploy suggestions will follow it`:"MISSING: DEPLOY.md (or .ticketpilot/deploy.md). Environments can't be created until the repo documents how it deploys.",...w?{}:{fixNote:"Only needed if this project will deploy from Allwright. The setup wizard can draft DEPLOY.md the same way it drafts CLAUDE.md - describe how you deploy today (the commands you actually run), and the agent proposes steps a human saves. Skip it if you only want tickets to become pull requests."}})}if(!u)s.push({name:"repo-path",ok:!1,detail:`no local path mapped for repo "${e.repoName}" - run: allwright repo add "${e.repoName}" /path/to/checkout`});else if(!vr.default.existsSync(u.path))s.push({name:"repo-path",ok:!1,detail:`path does not exist: ${u.path}`});else{let p=vr.default.existsSync(ll.default.join(u.path,".git"));s.push({name:"repo-path",ok:!0,detail:`${u.path}${p?" (git checkout)":" (warning: not a git checkout)"}`})}let c=[...new Set([e.defaultAgent||"claude-code",...r??[]])];for(let p of c){let b=Oe(n,p),w=p==="claude-code"?"claude-code":`agent:${p}`;try{let{stdout:T}=await Nh(b,["--version"],{timeout:15e3});s.push({name:w,ok:!0,detail:T.trim().slice(0,100)})}catch(T){s.push({name:w,ok:!1,detail:`cannot run "${b}" for agent "${p}": ${Ls(T)}`,fixNote:p==="claude-code"?"Install Claude Code on this server (npm install -g @anthropic-ai/claude-code) and log it in.":`Install the "${p}" CLI on this server, or point the runner at its binary in the config's agents section.`})}}try{let{stdout:p}=await Nh("git",["--version"],{timeout:15e3});s.push({name:"git",ok:!0,detail:p.trim().slice(0,100)})}catch(p){s.push({name:"git",ok:!1,detail:`cannot run git: ${Ls(p)}`})}let f=Te(n,e.repoName);if(!f)s.push({name:"github-token",ok:!1,detail:`no GitHub token applies to "${e.repoName}" - implement rules cannot push.`,fix:[`allwright github set "${e.repoName}"`,"allwright github set-token"],fixNote:`"${e.repoName}" is this project's REPO NAME - the same label used with allwright repo add, not a folder path. The first command stores a token for this repo alone (separately revocable); the second stores one shared by every repo on this server. Both print the exact permission checklist before asking. In short: create it at ${zh.GITHUB_TOKEN_PERMISSIONS.where}, with the RESOURCE OWNER set to the org that owns the repo (the usual mistake), Contents and Pull requests both Read and write.`});else try{let{GitHubClient:p}=await Promise.resolve().then(()=>(it(),nr)),b=new p(f),w=await b.whoami(),T=u&&vr.default.existsSync(u.path)?sb(u.path):null,C=T?nt(T):null;if(!C)s.push({name:"github-token",ok:!0,detail:`authenticated as ${w} - repo access not checked (no local checkout yet)`});else{let A=await b.repoAccess(C.owner,C.repo);s.push({name:"github-token",ok:A.ok&&A.canPush,detail:A.ok?A.canPush?`${w} has push access to ${C.owner}/${C.repo}`:`${w} can read ${C.owner}/${C.repo} but NOT push to it - implement rules will fail at the push`:`${w} cannot see ${C.owner}/${C.repo}: ${A.error}`,...A.ok&&A.canPush?{}:{fix:[`allwright github set "${e.repoName}"`],fixNote:`Two ways: edit the existing PAT on GitHub and add ${C.owner}/${C.repo} to it with contents:write and pull_requests:write - or give this repo its own token with the command above. A fine-grained PAT only ever covers ONE organisation, so a repo in a different org than your other projects always needs its own.`}})}}catch(p){s.push({name:"github-token",ok:!1,detail:Ls(p)})}if(t.length){n.deploy.enabled?s.push({name:"deploy",ok:!0,detail:"deployments enabled on this runner"}):s.push({name:"deploy",ok:!1,detail:"deployments are disabled on this runner - run `allwright deploy enable` to allow it to execute your saved deploy steps"});for(let p of t){let b=En(n,e.repoName,p.name),w=p.requiredSecrets.filter(T=>!b[T]&&!process.env[T]);s.push({name:`env:${p.name}`,ok:w.length===0,detail:w.length?`missing secret(s): ${w.join(", ")} - allwright env set "${e.repoName}" "${p.name}" ${w[0]}=...`:`${p.steps.length} step(s), ${p.requiredSecrets.length} secret(s) present`+(p.branch?`, deploys origin/${p.branch}`:"")})}}return s}function Ls(n){return(n instanceof Error?n.message:String(n)).slice(0,300)}var ye=new El;ye.name("allwright").description("Allwright runner - runs on YOUR machine, holds YOUR credentials locally, connects outbound-only to the control plane. Your Jira token, Anthropic key and source code never leave this host.").version(hi);function Kh(n){y.info(`Create the token at ${Bt.GITHUB_TOKEN_PERMISSIONS.where}`);for(let e of Bt.GITHUB_TOKEN_PERMISSIONS.steps)y.info(` - ${e}`);y.info(Bt.GITHUB_TOKEN_PERMISSIONS.note),y.info(`Then paste it below for ${n}.`)}ye.command("init").description("Interactive setup: enroll this runner and store credentials locally").option("--cp-url <url>","control plane URL").option("--enroll-token <token>","enrolment token from the Allwright UI").option("--name <name>","runner name",ul.default.hostname()).option("--jira-url <url>","Jira base URL, e.g. https://yourorg.atlassian.net").option("--jira-email <email>","Jira account email").option("--jira-token <token>","Jira API token (stored locally only)").action(async n=>{let e=hn.default.createInterface({input:process.stdin,output:process.stdout}),t=async(r,s,i=!1)=>{if(s)return s;let o=await e.question(`${r}: `);if(!o.trim())throw new Error(`${r} is required`);return o.trim()};try{let r=await t("Control plane URL",n.cpUrl),s=await t("Enrolment token (from the web UI)",n.enrollToken),i=await t("Jira base URL (https://yourorg.atlassian.net)",n.jiraUrl),o=await t("Jira account email",n.jiraEmail),l=await t("Jira API token (create at id.atlassian.com/manage-profile/security/api-tokens)",n.jiraToken,!0),u=Io.parse({controlPlaneUrl:r,runnerName:n.name,jira:{baseUrl:i,email:o,apiToken:l}}),c=await new Ce(u.jira).myself();y.info(`Jira credential OK - authenticated as ${c.displayName}`),u=await ku(u,s),y.info(`Enrolled as runner "${u.runnerName}" (${u.runnerId})`),y.info(`Credentials saved to ${At()} (mode 600, this machine only)`),y.info("Next: map your repo with `allwright repo add <repoName> <localPath>`, then `allwright start`")}finally{e.close()}});var cl=ye.command("repo").description("Map control-plane repo names to local checkouts");cl.command("add <repoName> <localPath>").description("Map a repo name (as configured in the web UI) to a local checkout path").action(async(n,e)=>{let t=ie();t.repos[n]={path:e},fe(t),y.info(`mapped repo "${n}" -> ${e}`);try{let{originUrl:r}=await Promise.resolve().then(()=>(gt(),Au));y.info(` origin remote: ${await r(e)} - make sure this is the repo you meant`)}catch{y.warn(` could not read an origin remote at ${e} - is it a git checkout?`)}});cl.command("list").description("Show configured repo mappings").action(()=>{let n=ie(),e=Object.entries(n.repos);if(!e.length)return y.info("no repos mapped yet");for(let[t,r]of e)y.info(`${t} -> ${r.path}`)});var Zh=ye.command("claude").description("Per-user Claude login profiles - each teammate's runs bill their OWN Claude account");Zh.command("login <profileName>").description("Create (or re-login) a named Claude profile. Opens Claude Code interactively with its own config directory - have the PERSON WHOSE ACCOUNT IT IS complete the /login flow with their credentials, then exit. Assign the profile to their user on the dashboard's Team page.").action(async n=>{if(!/^[a-zA-Z0-9._-]+$/.test(n))throw new Error("profile name: letters, digits, dots, dashes and underscores only");let e=ie(),t=e.claudeProfiles[n]?.configDir??`${At().replace(/runner\.json$/,"")}claude-profiles/${n}`;ut.default.mkdirSync(t,{recursive:!0,mode:448}),e.claudeProfiles[n]={configDir:t},fe(e),y.info(`profile "${n}" -> ${t}`),y.info("Opening Claude Code with this profile. In it: run /login, complete the browser flow"),y.info("with the account this profile belongs to, then exit Claude (ctrl+c twice or /exit).");let r=(0,Kt.spawn)(e.claudeBin,[],{env:{...process.env,CLAUDE_CONFIG_DIR:t},stdio:"inherit"});await new Promise(s=>r.on("exit",()=>s())),y.info(`Done. Assign it on the dashboard: Team -> the user -> Claude profile = "${n}".`),wr()});Zh.command("list").description("Show configured Claude profiles and whether each looks logged in").action(()=>{let n=ie(),e=Object.entries(n.claudeProfiles);if(y.info("default: this OS user's own Claude login (no profile)"),!e.length)return y.info("no named profiles yet - allwright claude login <name>");for(let[t,r]of e){let s=ut.default.existsSync(r.configDir)&&ut.default.readdirSync(r.configDir).length>0;y.info(`${t} -> ${r.configDir} ${s?"(logged in)":"(NOT logged in yet)"}`)}});cl.command("remove <repoName>").description("Unmap a repo from this runner: removes the mapping plus its per-repo Jira/GitHub overrides and env secrets from the config. Does NOT touch the checkout on disk or anything in the control plane - delete the project on the dashboard separately.").action(n=>{let e=ie();if(!e.repos[n]){let i=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${n}" - mapped repos: ${i}`)}let t=e.repos[n].path;delete e.repos[n];let r=Object.keys(e.environments).filter(i=>i.startsWith(`${n}:`));for(let i of r)delete e.environments[i];let s=e.auditSchedules.length;e.auditSchedules=e.auditSchedules.filter(i=>i.repoName!==n),fe(e),y.info(`Removed "${n}" (was ${t})`),r.length&&y.info(`Also removed ${r.length} environment secret set(s): ${r.join(", ")}`),e.auditSchedules.length!==s&&y.info("Also removed its audit schedule(s)"),y.info("The checkout on disk was NOT touched - remove it yourself if you want it gone."),y.info("Restart the runner to apply. Dashboard project (if any) is deleted separately there.")});var dl=ye.command("service").description("Run the runner as a system service (starts on boot, restarts on crash)");dl.command("install").description("Install + start the systemd service - detects node, this script, your user and home; no hand-written unit files. Run with sudo. (--print shows the unit without installing.)").option("--print","print the generated unit file and exit").action(n=>{if(n.print){y.info(`
800
+ `+ra(na()));return}zu(y)});dl.command("uninstall").description("Stop and remove the systemd service (config/credentials untouched)").action(()=>Du(y));dl.command("status").description("systemctl status for the runner service").action(()=>{(0,Kt.spawn)("systemctl",["status","allwright","--no-pager"],{stdio:"inherit"}).on("exit",e=>process.exit(e??0))});ye.command("update").description("Update the runner to the latest published version (npm install -g allwright@latest). Restart the runner afterwards - and only when no runs are active.").action(async()=>{y.info("Updating: npm install -g allwright@latest");let n=(0,Kt.spawn)("npm",["install","-g","allwright@latest"],{stdio:"inherit"});await new Promise((e,t)=>{n.on("exit",r=>r===0?e():t(new Error(`npm exited with code ${r}`))),n.on("error",t)}),y.info("Updated. Restart the runner service to load the new version (check active runs first).")});var ls=ye.command("jira").description("Per-repo Jira site overrides - for projects living on a different Atlassian site");ls.command("set <repoName>").description("Store Jira credentials for ONE repo's project (e.g. a project on a different *.atlassian.net site than the runner's main credential). Prompts on stdin; stored locally only, like every other credential.").action(async n=>{let e=ie();if(!e.repos[n]){let l=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${n}" - mapped repos: ${l}. Run \`allwright repo add\` first.`)}let t=Rd(n),r=(t?.jiraSiteUrl??"").trim(),s=r?`https://${r}`:"",i=e.jira?.email??"";if(s&&i&&e.jira?.apiToken){let l={baseUrl:s,email:i,apiToken:e.jira.apiToken};try{let u=await new Ce(l).myself();if(e.repos[n].jira=l,fe(e),y.info(`The token already on this server works on ${r} - authenticated as ${u.displayName}. Saved it for "${n}"; nothing to type.`),t?.jiraProjectKey)try{await new Ce(l).search(`project = "${t.jiraProjectKey}"`,1),y.info(`Project ${t.jiraProjectKey} is readable with it.`)}catch{y.warn(`Authenticated, but project ${t.jiraProjectKey} is not readable with this account. Ask a Jira admin for access, or re-run this command to enter a different account's token.`)}wr();return}catch{y.info(`The token already on this server does not work on ${r} - asking for one that does.`)}}let o=hn.default.createInterface({input:process.stdin,output:process.stdout});try{let u=(await o.question(s?`Jira base URL [${s}]: `:"Jira base URL for this repo (https://yourorg.atlassian.net): ")).trim()||s,f=(await o.question(i?`Jira account email [${i}]: `:"Jira account email: ")).trim()||i,p=(await o.question("Jira API token (id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!u||!f||!p)throw new Error("all three values are required");let b={baseUrl:u,email:f,apiToken:p},w=await new Ce(b).myself();y.info(`Jira credential OK - authenticated as ${w.displayName} on ${u}`),e.repos[n].jira=b,fe(e),y.info(`Saved: repo "${n}" now polls ${u} (other repos keep the runner-wide credential)`),wr()}finally{o.close()}});ls.command("set-token").description("Replace the RUNNER-WIDE Jira credential (the one every repo without an override uses). Until now this was only set at init - and Atlassian API tokens expire, which surfaces as boards quietly going empty. Prompts on stdin; validated before saving; applies live, no restart.").action(async()=>{let n=ie(),e=hn.default.createInterface({input:process.stdin,output:process.stdout});try{let t=n.jira?.baseUrl??"",r=n.jira?.email??"",s=(await e.question(t?`Jira base URL [${t}]: `:"Jira base URL (https://yourorg.atlassian.net): ")).trim()||t,i=(await e.question(r?`Jira account email [${r}]: `:"Jira account email: ")).trim()||r,o=(await e.question("Jira API token (id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!s||!i||!o)throw new Error("all three values are required");let l={baseUrl:s,email:i,apiToken:o},u=await new Ce(l).myself();n.jira=l,fe(n),y.info(`Jira credential OK - authenticated as ${u.displayName} on ${s}`),y.info(`Saved to ${At()} (mode 600, this machine only). Repo overrides are untouched.`),wr()}finally{e.close()}});ls.command("show").description("Show which Jira site each repo uses (never prints tokens)").action(()=>{let n=ie();y.info(`runner-wide: ${n.jira?`${n.jira.baseUrl} (${n.jira.email})`:"(not configured)"}`);for(let[e,t]of Object.entries(n.repos))y.info(`${e} -> ${t.jira?`${t.jira.baseUrl} (${t.jira.email})`:"(runner-wide credential)"}`)});ls.command("user-add <ticketpilotEmail>").description("Store a PERSON's own Jira credential, so board buttons and Compose tickets they click post to Jira under THEIR Atlassian identity instead of the runner's account. Keyed by their Allwright login email. Prompts on stdin; stored locally only. Picked up on the next click - no restart needed.").action(async n=>{let e=ie(),t=n.trim().toLowerCase();if(!t.includes("@"))throw new Error(`"${n}" doesn't look like an email`);let r=hn.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await r.question(`Their ATLASSIAN account email [${t}]: `)).trim()||t,i=(await r.question("Their Jira API token (they create it at id.atlassian.com/manage-profile/security/api-tokens): ")).trim();if(!i)throw new Error("API token is required");let o=[e.jira,...Object.values(e.repos).map(c=>c.jira)].filter(c=>!!c),l=new Set,u=!1;for(let c of o)if(!l.has(c.baseUrl)){l.add(c.baseUrl);try{let f=await new Ce({baseUrl:c.baseUrl,email:s,apiToken:i}).myself();y.info(`${c.baseUrl}: OK - authenticated as ${f.displayName}`),u=!0}catch{y.warn(`${c.baseUrl}: this credential does NOT work there (fine if they don't use that site)`)}}if(!u)throw new Error("credential failed on every configured Jira site - nothing saved");e.jiraUsers[t]={email:s,apiToken:i},fe(e),y.info(`Saved. Dashboard actions by ${t} now post to Jira as ${s}. No restart needed.`)}finally{r.close()}});ls.command("user-list").description("Show which Allwright users have their own Jira credential here (never prints tokens)").action(()=>{let n=ie(),e=Object.entries(n.jiraUsers);if(!e.length)return y.info("none yet - everyone's dashboard clicks require one: allwright jira user-add <their-ticketpilot-email>");for(let[t,r]of e)y.info(`${t} -> posts to Jira as ${r.email}`)});ls.command("user-remove <ticketpilotEmail>").description("Delete a person's stored Jira credential").action(n=>{let e=ie(),t=n.trim().toLowerCase();if(!e.jiraUsers[t])throw new Error(`no credential stored for ${t}`);delete e.jiraUsers[t],fe(e),y.info(`Removed. Dashboard actions by ${t} will now be refused until a new credential is added.`)});var us=ye.command("github").description("GitHub credential for implement-mode rules");us.command("set-token").description("Store a GitHub token for opening pull requests (implement rules). Stored locally only, like your Jira token. Recommended: a fine-grained PAT scoped to the repo with contents:write + pull_requests:write.").option("--token <token>","GitHub token (omit to be prompted)").action(async n=>{let e=hn.default.createInterface({input:process.stdin,output:process.stdout});try{let t=n.token??void Kh("every repo on this server")??(await e.question("GitHub token: ")).trim();if(!t)throw new Error("token is required");let{GitHubClient:r}=await Promise.resolve().then(()=>(it(),nr)),s=await new r(t).whoami(),i=ie();i.github={token:t,login:s},fe(i),y.info(`GitHub token OK - authenticated as ${s}`),y.info(`Saved to ${At()} (mode 600, this machine only)`)}finally{e.close()}});us.command("set <repoName>").description("Store a GitHub token for ONE repo only - overrides the runner-wide token for that repo's PRs and PR-watching. Useful when projects need separately revocable access. Prompts on stdin; stored locally only.").action(async n=>{let e=ie();if(!e.repos[n]){let i=Object.keys(e.repos).join(", ")||"(none)";throw new Error(`unknown repo "${n}" - mapped repos: ${i}. Run \`allwright repo add\` first.`)}let t=e.github?.token,r=e.repos[n]?.path;if(t&&r&&ut.default.existsSync(r))try{let i=(0,Kt.execFileSync)("git",["-C",r,"remote","get-url","origin"],{encoding:"utf8",timeout:1e4}).trim(),o=nt(i);if(o){let{GitHubClient:l}=await Promise.resolve().then(()=>(it(),nr)),u=new l(t),c=await u.repoAccess(o.owner,o.repo);if(c.ok&&c.canPush){let f=await u.whoami();y.info(`The shared token on this server already has push access to ${o.owner}/${o.repo} as ${f} - "${n}" needs nothing of its own. Storing a second token here would only give you two to rotate.`),y.info("Want a separately revocable one anyway? Paste it at the prompt below; press Enter to leave things as they are.")}}}catch{}let s=hn.default.createInterface({input:process.stdin,output:process.stdout});try{Kh(`"${n}"`);let i=(await s.question(`GitHub token for "${n}": `)).trim();if(!i&&t){y.info(`Nothing changed - "${n}" keeps using the shared token.`);return}if(!i)throw new Error("token is required");let{GitHubClient:o}=await Promise.resolve().then(()=>(it(),nr)),l=await new o(i).whoami();e.repos[n].github={token:i,login:l},fe(e),y.info(`GitHub token OK - authenticated as ${l}`),y.info(`Saved: repo "${n}" now uses its own token (other repos keep the runner-wide one)`)}finally{s.close()}});us.command("user-add <ticketpilotEmail>").description("Store a PERSON's own GitHub token, so PRs from implement runs THEY trigger are authored by their GitHub account. Keyed by their Allwright login email. Optional - without it their runs fall back to the repo/runner-wide token. Needs contents:write + pull_requests:write on the repos they'll touch.").action(async n=>{let e=ie(),t=n.trim().toLowerCase();if(!t.includes("@"))throw new Error(`"${n}" doesn't look like an email`);let r=hn.default.createInterface({input:process.stdin,output:process.stdout});try{let s=(await r.question(`GitHub token for ${t}: `)).trim();if(!s)throw new Error("token is required");let{GitHubClient:i}=await Promise.resolve().then(()=>(it(),nr)),o=await new i(s).whoami();e.githubUsers[t]={token:s,login:o},fe(e),y.info(`GitHub token OK - authenticated as ${o}`),y.info(`Saved. Implement runs triggered by ${t} now open PRs as ${o}. No restart needed.`)}finally{r.close()}});us.command("user-list").description("Show which Allwright users have their own GitHub token here (never prints tokens)").action(()=>{let n=ie(),e=Object.entries(n.githubUsers);if(!e.length)return y.info("no per-user GitHub tokens - everyone's PRs use the repo/runner-wide token");for(let[t]of e)y.info(`${t} -> own GitHub token stored`)});us.command("user-remove <ticketpilotEmail>").description("Delete a person's stored GitHub token (their runs fall back to the shared token)").action(n=>{let e=ie(),t=n.trim().toLowerCase();if(!e.githubUsers[t])throw new Error(`no GitHub token stored for ${t}`);delete e.githubUsers[t],fe(e),y.info(`Removed. ${t}'s runs use the repo/runner-wide token again.`)});us.command("show").description("Show which GitHub token each repo and person would use (never prints tokens)").action(()=>{let n=ie();y.info(`runner-wide: ${n.github?.token?"token set":"(not configured)"}`);for(let[t,r]of Object.entries(n.repos))y.info(`${t} -> ${r.github?.token?"own repo token":"runner-wide token"}`);let e=Object.keys(n.githubUsers);y.info(e.length?`per-user tokens: ${e.join(", ")}`:"per-user tokens: (none)")});var hl=ye.command("audit").description("Recurring specialist audits on this runner");hl.command("schedule <repoName> <role> <intervalHours>").description("Audit this repo's project on a cadence (role: security|testing; interval in hours, min 6). Runs on the runner's own clock; reports land in the Audits page history, where the diff-vs-previous view shows drift. Advisory only - nothing blocks.").action((n,e,t)=>{let r=ie();if(!r.repos[n]){let i=Object.keys(r.repos).join(", ")||"(none)";throw new Error(`unknown repo "${n}" - mapped repos: ${i}`)}if(e!=="security"&&e!=="testing")throw new Error('role must be "security" or "testing"');let s=parseInt(t,10);if(!Number.isInteger(s)||s<6||s>720)throw new Error("intervalHours must be 6-720");r.auditSchedules=[...r.auditSchedules.filter(i=>!(i.repoName===n&&i.role===e)),{repoName:n,role:e,intervalHours:s}],fe(r),y.info(`Scheduled: ${e} audit of "${n}" every ${s}h. Restart the runner to apply.`)});hl.command("schedules").description("List scheduled audits").action(()=>{let n=ie();if(!n.auditSchedules.length)return y.info("no scheduled audits - allwright audit schedule <repo> <role> <hours>");for(let e of n.auditSchedules)y.info(`${e.repoName} \xB7 ${e.role} \xB7 every ${e.intervalHours}h`)});hl.command("unschedule <repoName> <role>").description("Remove a scheduled audit").action((n,e)=>{let t=ie(),r=t.auditSchedules.length;if(t.auditSchedules=t.auditSchedules.filter(s=>!(s.repoName===n&&s.role===e)),t.auditSchedules.length===r)throw new Error("no such schedule");fe(t),y.info("Removed. Restart the runner to apply.")});var fl=ye.command("deploy").description("Deployment settings for this machine");fl.command("enable").description("Allow this runner to execute the deploy steps saved in the dashboard. Those steps are shell commands that run here, as this user - so this switch lives on the machine, not in the web UI, and only someone with shell access can flip it.").action(()=>{let n=ie();n.deploy={enabled:!0},fe(n),y.info("deployments ENABLED on this runner"),y.info("This runner will now execute the deploy steps configured for your environments. Review them in the dashboard before shipping to production."),wr()});fl.command("disable").description("Stop this runner from executing any deploy steps").action(()=>{let n=ie();n.deploy={enabled:!1},fe(n),y.info("deployments DISABLED on this runner"),wr()});fl.command("status").description("Show whether deployments are enabled here, and which env secrets are stored").action(()=>{let n=ie();y.info(`deployments: ${n.deploy.enabled?"enabled":"disabled"}`);let e=Object.entries(n.environments);if(!e.length)return y.info("no environment secrets stored");for(let[t,r]of e){let s=Object.keys(r.secrets);y.info(`${t}: ${s.length?s.join(", "):"(no secrets)"}`)}});var pl=ye.command("env").description("Per-environment deploy secrets. Values stay on this machine, like your Jira token.");pl.command("set <repoName> <envName> <assignments...>").description('Store secrets for one environment, e.g. env set acme/api production "SSH_HOST=1.2.3.4" "SSH_USER=deploy". Your deploy steps reference these as $SSH_HOST. The control plane only ever learns the NAMES.').action((n,e,t)=>{let r=ie(),s=Xs(n,e),i=r.environments[s]??{secrets:{}},o=[];for(let l of t){let u=l.indexOf("=");if(u<=0)throw new Error(`expected KEY=VALUE, got "${l}"`);let c=l.slice(0,u).trim();i.secrets[c]=l.slice(u+1),o.push(c)}r.environments[s]=i,fe(r),y.info(`stored ${o.length} secret(s) for ${s}: ${o.join(", ")}`),y.info(`Saved to ${At()} (mode 600, this machine only)`),wr()});pl.command("unset <repoName> <envName> <names...>").description("Remove stored secrets for an environment").action((n,e,t)=>{let r=ie(),s=Xs(n,e),i=r.environments[s];if(!i)return y.info(`nothing stored for ${s}`);for(let o of t)delete i.secrets[o];r.environments[s]=i,fe(r),y.info(`removed ${t.join(", ")} from ${s}`)});pl.command("list").description("Show which environments have secrets stored here (names only, never values)").action(()=>{let n=ie(),e=Object.entries(n.environments);if(!e.length)return y.info("no environment secrets stored");for(let[t,r]of e)y.info(`${t}: ${Object.keys(r.secrets).join(", ")||"(none)"}`)});ye.command("export [file]").description("Back up ALL runner state (config+secrets, knowledge, audits, chats) to one tarball").action(n=>{try{let e=Fl(n);y.info(`Backup written: ${e.file} (${e.entries.length} entries, mode 600)`),y.warn("This file CONTAINS YOUR SECRETS (Jira/GitHub tokens). Keep it private - anyone holding it can act as this runner."),y.info(`Restore on any machine with: allwright import ${as.default.basename(e.file)}`)}catch(e){y.error(e instanceof Error?e.message:String(e)),process.exitCode=1}});ye.command("import <file>").description("Restore runner state from an `export` tarball (existing config is kept as a .bak dir)").action(n=>{let e=An();if(e&&$n(e)){y.error("the runner is running - stop it first (systemctl stop allwright, or `allwright stop` for a pid-file daemon), then import."),process.exitCode=1;return}try{let t=Bl(n);y.info(`Restored ${t.restored.length} entries into ${se()}`),t.previousDir&&y.info(`Previous config kept at ${t.previousDir}`),y.info("Start the runner and it will reconnect with the restored identity.")}catch(t){y.error(t instanceof Error?t.message:String(t)),process.exitCode=1}});ye.command("test").description("Check local setup: Jira auth, repo mappings, Claude Code binary").action(async()=>{let n=ie(),e=Object.keys(n.repos);if(!n.jira){y.error("no Jira credentials configured - run `allwright init`"),process.exitCode=1;return}let t=e.length?e.map(s=>({jiraProjectKey:"*",repoName:s})):[{jiraProjectKey:"*",repoName:"(none mapped)"}],r=!0;for(let s of t){let i=await ro(n,s);for(let o of i){if(s.jiraProjectKey==="*"&&o.name==="jira-project")continue;let l=o.ok?"PASS":"FAIL";(o.ok?y.info:y.error)(`[${l}] ${o.name}: ${o.detail}`),r&&=o.ok}}r||(process.exitCode=1)});function wr(){let n=An();if(n&&$n(n)&&process.platform!=="win32")try{process.kill(n,"SIGHUP"),y.info("running runner reloaded its config live - no restart needed");return}catch{}y.info("No background runner found to reload. Under systemd: sudo systemctl kill -s HUP allwright - otherwise it applies on the next allwright start.")}function ab(n){if(!n.runnerToken)throw new Error("runner not enrolled - run `allwright init`");if(!n.jira)throw new Error("no Jira credentials - run `allwright init`");let e=Jl();e.ok||(y.warn(`another runner is already running on this machine (pid ${e.pid}). Two runner processes with one identity kick each other off the control plane every second. Stop the other one first: \`allwright stop\` (background runner) or \`sudo systemctl stop allwright\` (service).`),process.exit(1)),process.on("exit",Ao);let t=new Ce(n.jira),r=new Map,s=h=>{let m=n.repos[h]?.jira;if(!m)return t;let g=r.get(h);return g||(g=new Ce(m),r.set(h,g)),g},i=new Map,o=(h,m)=>{let g=ju(pe()??n,h,m);switch(g.kind){case"legacy":return{jira:s(h),authored:!1};case"self":return{jira:s(h),authored:!0};case"missing":return{error:g.error};case"user":{let x=`${g.creds.baseUrl}:${g.creds.email}:${g.creds.apiToken.slice(-6)}`,M=i.get(x);return M||(M=new Ce(g.creds),i.set(x,M)),{jira:M,authored:!0}}}},l=new URL("/api/runner/ws",n.controlPlaneUrl);l.protocol=l.protocol==="https:"?"wss:":"ws:";let u=[],c=[],f=[],p,b=null,w={cfg:n,jiraFor:s,transport:null},T=new Set,C=h=>{let m=u.find(x=>x.id===h),g=m&&n.repos[m.repoName];return m&&g?{project:m,repoPath:g.path}:null},A={cfg:n,jiraFor:s,get transport(){return w.transport},lookup:(h,m)=>{let g=C(h),x=f.find(M=>M.projectId===h&&M.name===m);return g&&x?{...g,environment:x}:null}},v=new eo(l.toString(),n.runnerToken,{runnerVersion:hi},{onConfig:h=>{u=h.projects,Id(h.projects),c=h.rules,f=h.environments,p.setConfig(h.projects,h.rules,h.pollingPaused,h.environments)},onDeployFix:async h=>{let m=C(h.projectId);if(!m){v.sendDeploySuggestResult(h.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:"this runner has no local checkout mapped for that project"});return}let g=st(n,m.project,"assist");if("error"in g){v.sendDeploySuggestResult(h.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:g.error});return}y.info(`investigating failed deploy of "${h.environmentName}" (step: ${h.failedStep||"?"})`);let x=await ad({agent:g,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:h.environmentName,steps:h.steps,failedStep:h.failedStep,errorText:h.errorText,cfg:n});v.sendDeploySuggestResult(h.requestId,x)},onProjectTest:async h=>{let m=u.find(x=>x.id===h.projectId);if(!m){v.sendProjectTestResult(h.requestId,!1,[{name:"config",ok:!1,detail:"project not in this runner's synced config yet"}]);return}y.info(`running connection test for project "${m.name}"`);let g=await ro(pe()??n,m,f.filter(x=>x.projectId===m.id),c.filter(x=>x.projectId===m.id).map(x=>"agent"in x.action?x.action.agent:"").filter(Boolean));v.sendProjectTestResult(h.requestId,g.every(x=>x.ok),g)},onRuleDiagnose:async h=>{let m=c.find(H=>H.id===h.ruleId),g=m&&u.find(H=>H.id===m.projectId);if(!m||!g){v.sendRuleDiagnoseResult(h.requestId,{checks:[{name:"config",ok:!1,detail:"rule not in this runner's synced config yet"}],matchedCount:0,excludedCount:0,excludedSample:[]});return}y.info(`diagnosing rule "${m.name}"`);let x=await ro(pe()??n,g,m.action.type==="deploy"?f.filter(H=>H.projectId===g.id):[]),M=m.action.type==="implement"?x:x.filter(H=>H.name!=="github-token"),{matchedCount:q,excludedCount:X,excludedSample:ee}=await p.diagnoseRule(m,g);v.sendRuleDiagnoseResult(h.requestId,{checks:M,matchedCount:q,excludedCount:X,excludedSample:ee})},onCancel:h=>{jc(h)?y.info(`run ${h} stopped from the dashboard`):y.warn(`cancel requested for run ${h}, but nothing is running under that id here - it likely finished already`)},onApproved:(h,m)=>{if($a(h)){td(A,h).catch(g=>y.error(`deploy approval crashed for ${h}: ${g instanceof Error?g.stack:g}`));return}Rs(w,h,m).catch(g=>y.error(`approval handling crashed for ${h}: ${g instanceof Error?g.stack:g}`))},onRetryPush:h=>{let m=Ci(h),g=()=>Bc(w,h).catch(x=>y.error(`retry push crashed for ${h}: ${x instanceof Error?x.stack:x}`));m?p.runOnRepoQueue(m.baseRepoPath,g):g()},onRejected:h=>{if($a(h)){nd(A,h).catch(m=>y.error(`deploy rejection crashed for ${h}: ${m instanceof Error?m.stack:m}`));return}Fc(w,h).catch(m=>y.error(`rejection handling crashed for ${h}: ${m instanceof Error?m.stack:m}`))},onDeployStart:h=>{let m=`${h.runId}#${h.attempt}`;if(T.has(m))return;T.add(m);let g=C(h.projectId);if(!g){let x="this runner has no local checkout mapped for that project - run: allwright repo add <repoName> /path/to/checkout";y.error(`deploy ${h.runId}: ${x}`),v.send({type:"run.status",runId:h.runId,status:"failed",error:x});return}y.info(`deploy ${h.runId} requested from the dashboard: ${h.issueKey} \u2192 ${h.environment.name}`),p.runOnEnvironmentQueue(h.environment.id,()=>Oi({runId:h.runId,project:g.project,environment:h.environment,issueKey:h.issueKey,issueSummary:h.issueSummary,repoPath:g.repoPath,cfg:n,jira:s(g.project.repoName),transport:v,requestedBy:h.requestedBy}).catch(x=>y.error(`deploy crashed for ${h.runId}: ${x instanceof Error?x.stack:x}`)))},onDeploySuggest:async h=>{let m=C(h.projectId);if(!m){v.sendDeploySuggestResult(h.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:"this runner has no local checkout mapped for that project"});return}let g=st(n,m.project,"assist");if("error"in g){v.sendDeploySuggestResult(h.requestId,{ok:!1,steps:[],requiredSecrets:[],notes:"",error:g.error});return}y.info(`asking ${g.adapter.displayName} for "${h.environmentName}" deploy steps in ${m.repoPath}`);let x=await ld({agent:g,repoPath:m.repoPath,repoName:m.project.repoName,environmentName:h.environmentName,notes:h.notes,timeoutSeconds:h.timeoutSeconds,cfg:n});v.sendDeploySuggestResult(h.requestId,x)},onEnvPreflight:async h=>{let m=C(h.projectId);if(!m){v.sendEnvPreflightResult(h.requestId,{ok:!1,checks:[{name:"repo",ok:!1,detail:"no local checkout mapped for that project"}]});return}let g=await od({repoPath:m.repoPath,repoName:m.project.repoName,environmentName:h.environmentName,steps:h.steps,requiredSecrets:h.requiredSecrets,workdir:h.workdir,branch:h.branch,publicUrl:h.publicUrl,cfg:n});v.sendEnvPreflightResult(h.requestId,g)},onChatTurn:async h=>{let m=C(h.projectId);if(!m){v.sendChatTurnResult(h.requestId,{ok:!1,sessionId:h.sessionId??"",reply:"",error:"this runner has no local checkout mapped for that project"});return}let g=h.sessionId||(0,io.randomUUID)(),x=!h.sessionId;if((x?0:Ma(g)?.messages.length??0)>=44){v.sendChatTurnResult(h.requestId,{ok:!1,sessionId:g,reply:"",error:"this chat has hit its length limit - every turn re-reads the whole conversation, so long chats get slow and expensive. Start a new chat (it keeps the repo knowledge; only the conversation resets)."});return}let q=h.files.length?Gl(m.repoPath,h.requestId,h.files):null,X="```",ee=x?`You are the project assistant for "${m.project.name}" - this working directory is its repository, and you have read-only access.
784
801
 
785
802
  DEFAULT MODE IS DISCUSSION. Answer questions, explain code, weigh approaches, review ideas - like a teammate who knows this repo. Most conversations never produce a ticket, and that is fine. Do NOT propose a Jira ticket unless the user explicitly asks for one in this conversation ("create a ticket", "make this a ticket", "draft the ticket" or similar). Never end a normal answer with a ticket proposal.
786
803
  Be fast: answer from CLAUDE.md and what you already know first; open files only when the question genuinely needs code-level detail. Keep replies short.
@@ -802,11 +819,11 @@ EXCEPTION - big requirements: when the user asks for an epic with sub-tickets, o
802
819
  {"epic": {"summary": "\u2026", "description": "\u2026"}, "tickets": [{"summary": "\u2026", "description": "\u2026"}, \u2026]}
803
820
  3-8 tickets, each independently implementable and structured with the same section headings as above, ordered so foundations come first; the epic description is the overall goal in under 100 words.
804
821
 
805
- ${h.userName||"The user"} says: ${h.message}`+(F?.section??""):`${h.userName||"The user"} says: ${h.message}`+(F?.section??""),H=0,j;try{let te=tt(n,m.project,"chat");if("error"in te){v.sendChatTurnResult(h.requestId,{ok:!1,sessionId:g,reply:"",error:te.error});return}j=await te.adapter.run({repoPath:m.repoPath,prompt:ee,timeoutSeconds:180,bin:te.bin,mode:"read_only",maxTurns:25,model:h.model||te.adapter.fastModel,sessionId:g,resume:!C,onLog:(se,le)=>{se==="agent"&&v.send({type:"chat.stream",requestId:h.requestId,seq:H++,text:le.slice(0,8e3)})},onUsage:se=>{v.send({type:"chat.usage",requestId:h.requestId,inputTokens:Math.round(se.inputTokens),outputTokens:Math.round(se.outputTokens),cacheReadTokens:se.cacheReadTokens===void 0?void 0:Math.round(se.cacheReadTokens),turns:se.turns})}})}finally{F&&ot.default.rmSync(F.dir,{recursive:!0,force:!0})}j.ok&&ud(h.projectId,g,h.message,j.resultText),v.sendChatTurnResult(h.requestId,{ok:j.ok,sessionId:g,reply:j.resultText,error:j.ok?void 0:j.error??"the agent produced no reply",inputTokens:j.inputTokens,outputTokens:j.outputTokens,cacheReadTokens:j.cacheReadTokens,costUsd:j.costUsd,model:j.model??""})},onChatList:h=>{v.sendChatListResult(h.requestId,cd(h.projectId))},onRepoDocs:h=>{let m=x(h.projectId);if(!m){v.sendRepoDocsResult(h.requestId,{ok:!1,docs:[],error:"this runner has no local checkout mapped for that project"});return}v.sendRepoDocsResult(h.requestId,{ok:!0,docs:fd(m.repoPath)})},onRepoDocRead:h=>{let m=x(h.projectId);if(!m){v.sendRepoDocReadResult(h.requestId,{ok:!1,path:h.path,content:"",truncated:!1,error:"this runner has no local checkout mapped for that project"});return}let g=pd(m.repoPath,h.path);v.sendRepoDocReadResult(h.requestId,{ok:g.ok,path:g.ok?g.path:h.path,content:g.ok?g.content:"",truncated:g.ok?g.truncated:!1,error:g.ok?void 0:g.error})},onChatLoad:h=>{let m=Ea(h.sessionId);v.sendChatLoadResult(h.requestId,{ok:m!==null,projectId:m?.projectId??"",messages:m?.messages??[],error:m?void 0:"chat not found on this runner (pruned or never existed)"})},onBoardFetch:async h=>{let m=x(h.projectId);if(!m){v.sendBoardFetchResult(h.requestId,{ok:!1,columns:[],error:"this runner has no local checkout mapped for that project"});return}try{let g=s(m.project.repoName),C;try{C=await g.searchBoard(`project = "${m.project.jiraProjectKey}" ORDER BY Rank ASC`,100)}catch{C=await g.searchBoard(`project = "${m.project.jiraProjectKey}" ORDER BY updated DESC`,100)}let N=await g.boardColumns(m.project.jiraProjectKey),F;if(N){F=N.map(H=>({name:H.name,issues:[]}));let ee=new Map;for(let H of C){let j=N.findIndex(se=>se.statusIds.includes(H.statusId)),te={key:H.key,summary:H.summary,labels:H.labels};if(j>=0)F[j].issues.push(te);else{let se=ee.get(H.status)??[];se.push(te),ee.set(H.status,se)}}for(let[H,j]of ee)F.push({name:H,issues:j})}else{let ee=le=>le.trim().toLowerCase(),H=new Map,j=new Map;for(let le of C){let Ye=ee(le.status);H.has(Ye)||H.set(Ye,le.status.trim());let pe=j.get(Ye)??[];pe.push({key:le.key,summary:le.summary,labels:le.labels}),j.set(Ye,pe)}let te=[];try{te=await g.projectStatuses(m.project.jiraProjectKey)}catch{}let se=[];for(let le of te){let Ye=ee(le);!se.includes(Ye)&&j.has(Ye)&&se.push(Ye)}for(let le of j.keys())se.includes(le)||se.push(le);F=se.map(le=>({name:H.get(le)??le,issues:j.get(le)??[]}))}let X=n.repos[m.project.repoName]?.jira??n.jira;v.sendBoardFetchResult(h.requestId,{ok:!0,browseBaseUrl:(X?.baseUrl??"").replace(/\/+$/,""),columns:F})}catch(g){v.sendBoardFetchResult(h.requestId,{ok:!1,columns:[],error:g instanceof Error?g.message:String(g)})}},onBoardTrigger:async h=>{let m=x(h.projectId);if(!m){v.sendBoardTriggerResult(h.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{let g=s(m.project.repoName),C=h.comment.trim()?o(m.project.repoName,h.requestedByEmail):{jira:g,authored:!1};if(C.error!==void 0){v.sendBoardTriggerResult(h.requestId,{ok:!1,error:C.error});return}if(h.reimplement){let N=await g.getIssue(h.issueKey),F=N.comments.filter(H=>mt(H.body)),X=F.length?Math.max(...F.map(H=>new Date(H.created).getTime())):0;if(!N.comments.some(H=>!mt(H.body)&&new Date(H.created).getTime()>X)){v.sendBoardTriggerResult(h.requestId,{ok:!1,error:`${h.issueKey} has nothing new since the last implementation - add a comment describing what should change, then hit Implement again. Re-running with the same ticket would just rebuild the same thing.`});return}await g.editLabels(h.issueKey,{remove:["agent-implemented"]})}h.removeLabel.trim()&&await g.editLabels(h.issueKey,{remove:[h.removeLabel.trim()]}),h.comment.trim()&&await C.jira.addTriggerComment(h.issueKey,`${h.comment.trim()}`+(!C.authored&&h.requestedBy?`
822
+ ${h.userName||"The user"} says: ${h.message}`+(q?.section??""):`${h.userName||"The user"} says: ${h.message}`+(q?.section??""),H=0,$;try{let te=st(n,m.project,"chat");if("error"in te){v.sendChatTurnResult(h.requestId,{ok:!1,sessionId:g,reply:"",error:te.error});return}$=await te.adapter.run({repoPath:m.repoPath,prompt:ee,timeoutSeconds:180,bin:te.bin,mode:"read_only",maxTurns:25,model:h.model||te.adapter.fastModel,sessionId:g,resume:!x,onLog:(ne,ce)=>{ne==="agent"&&v.send({type:"chat.stream",requestId:h.requestId,seq:H++,text:ce.slice(0,8e3)})},onUsage:ne=>{v.send({type:"chat.usage",requestId:h.requestId,inputTokens:Math.round(ne.inputTokens),outputTokens:Math.round(ne.outputTokens),cacheReadTokens:ne.cacheReadTokens===void 0?void 0:Math.round(ne.cacheReadTokens),turns:ne.turns})}})}finally{q&&ut.default.rmSync(q.dir,{recursive:!0,force:!0})}$.ok&&bd(h.projectId,g,h.message,$.resultText),v.sendChatTurnResult(h.requestId,{ok:$.ok,sessionId:g,reply:$.resultText,error:$.ok?void 0:$.error??"the agent produced no reply",inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,costUsd:$.costUsd,model:$.model??""})},onChatList:h=>{v.sendChatListResult(h.requestId,wd(h.projectId))},onRepoDocs:h=>{let m=C(h.projectId);if(!m){v.sendRepoDocsResult(h.requestId,{ok:!1,docs:[],error:"this runner has no local checkout mapped for that project"});return}v.sendRepoDocsResult(h.requestId,{ok:!0,docs:Sd(m.repoPath)})},onRepoDocRead:h=>{let m=C(h.projectId);if(!m){v.sendRepoDocReadResult(h.requestId,{ok:!1,path:h.path,content:"",truncated:!1,error:"this runner has no local checkout mapped for that project"});return}let g=Td(m.repoPath,h.path);v.sendRepoDocReadResult(h.requestId,{ok:g.ok,path:g.ok?g.path:h.path,content:g.ok?g.content:"",truncated:g.ok?g.truncated:!1,error:g.ok?void 0:g.error})},onChatLoad:h=>{let m=Ma(h.sessionId);v.sendChatLoadResult(h.requestId,{ok:m!==null,projectId:m?.projectId??"",messages:m?.messages??[],error:m?void 0:"chat not found on this runner (pruned or never existed)"})},onBoardFetch:async h=>{let m=C(h.projectId);if(!m){v.sendBoardFetchResult(h.requestId,{ok:!1,columns:[],error:"this runner has no local checkout mapped for that project"});return}try{let g=s(m.project.repoName),x;try{x=await g.searchBoard(`project = "${m.project.jiraProjectKey}" ORDER BY Rank ASC`,100)}catch{x=await g.searchBoard(`project = "${m.project.jiraProjectKey}" ORDER BY updated DESC`,100)}let M=await g.boardColumns(m.project.jiraProjectKey),q;if(M){q=M.map(H=>({name:H.name,issues:[]}));let ee=new Map;for(let H of x){let $=M.findIndex(ne=>ne.statusIds.includes(H.statusId)),te={key:H.key,summary:H.summary,labels:H.labels};if($>=0)q[$].issues.push(te);else{let ne=ee.get(H.status)??[];ne.push(te),ee.set(H.status,ne)}}for(let[H,$]of ee)q.push({name:H,issues:$})}else{let ee=ce=>ce.trim().toLowerCase(),H=new Map,$=new Map;for(let ce of x){let Ee=ee(ce.status);H.has(Ee)||H.set(Ee,ce.status.trim());let cs=$.get(Ee)??[];cs.push({key:ce.key,summary:ce.summary,labels:ce.labels}),$.set(Ee,cs)}let te=[];try{te=await g.projectStatuses(m.project.jiraProjectKey)}catch{}let ne=[];for(let ce of te){let Ee=ee(ce);!ne.includes(Ee)&&$.has(Ee)&&ne.push(Ee)}for(let ce of $.keys())ne.includes(ce)||ne.push(ce);q=ne.map(ce=>({name:H.get(ce)??ce,issues:$.get(ce)??[]}))}let X=n.repos[m.project.repoName]?.jira??n.jira;v.sendBoardFetchResult(h.requestId,{ok:!0,browseBaseUrl:(X?.baseUrl??"").replace(/\/+$/,""),columns:q})}catch(g){v.sendBoardFetchResult(h.requestId,{ok:!1,columns:[],error:g instanceof Error?g.message:String(g)})}},onBoardTrigger:async h=>{let m=C(h.projectId);if(!m){v.sendBoardTriggerResult(h.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{let g=s(m.project.repoName),x=h.comment.trim()?o(m.project.repoName,h.requestedByEmail):{jira:g,authored:!1};if(x.error!==void 0){v.sendBoardTriggerResult(h.requestId,{ok:!1,error:x.error});return}if(h.reimplement){let M=await g.getIssue(h.issueKey),q=M.comments.filter(H=>yt(H.body)),X=q.length?Math.max(...q.map(H=>new Date(H.created).getTime())):0;if(!M.comments.some(H=>!yt(H.body)&&new Date(H.created).getTime()>X)){v.sendBoardTriggerResult(h.requestId,{ok:!1,error:`${h.issueKey} has nothing new since the last implementation - add a comment describing what should change, then hit Implement again. Re-running with the same ticket would just rebuild the same thing.`});return}await g.editLabels(h.issueKey,{remove:["agent-implemented"]})}h.removeLabel.trim()&&await g.editLabels(h.issueKey,{remove:[h.removeLabel.trim()]}),h.comment.trim()&&await x.jira.addTriggerComment(h.issueKey,`${h.comment.trim()}`+(!x.authored&&h.requestedBy?`
806
823
 
807
- _(requested by ${h.requestedBy} via Allwright)_`:"")),y.info(`Board action on ${h.issueKey}`+(h.comment?` comment "${h.comment.trim()}"`:"")+(h.removeLabel?` -label ${h.removeLabel}`:"")+(h.requestedBy?` by ${h.requestedBy}`:"")),v.sendBoardTriggerResult(h.requestId,{ok:!0})}catch(g){v.sendBoardTriggerResult(h.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onChatCreateTicket:async h=>{let m=x(h.projectId);if(!m){v.sendChatCreateTicketResult(h.requestId,{ok:!1,issueKey:"",error:"this runner has no local checkout mapped for that project"});return}try{let g=o(m.project.repoName,h.requestedByEmail);if(g.error!==void 0){v.sendChatCreateTicketResult(h.requestId,{ok:!1,issueKey:"",error:g.error});return}let C=`
824
+ _(requested by ${h.requestedBy} via Allwright)_`:"")),y.info(`Board action on ${h.issueKey}`+(h.comment?` comment "${h.comment.trim()}"`:"")+(h.removeLabel?` -label ${h.removeLabel}`:"")+(h.requestedBy?` by ${h.requestedBy}`:"")),v.sendBoardTriggerResult(h.requestId,{ok:!0})}catch(g){v.sendBoardTriggerResult(h.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onChatCreateTicket:async h=>{let m=C(h.projectId);if(!m){v.sendChatCreateTicketResult(h.requestId,{ok:!1,issueKey:"",error:"this runner has no local checkout mapped for that project"});return}try{let g=o(m.project.repoName,h.requestedByEmail);if(g.error!==void 0){v.sendChatCreateTicketResult(h.requestId,{ok:!1,issueKey:"",error:g.error});return}let x=`
808
825
 
809
826
  ---
810
- _Created via Allwright Compose`+(!g.authored&&h.requestedBy?` by ${h.requestedBy}`:"")+", drafted with the project agent._",{key:N}=await g.jira.createIssue(m.project.jiraProjectKey,h.summary,(h.description||"(no description)")+C,h.asEpic?"Epic":"Task");h.files.length&&await g.jira.addAttachments(N,h.files.map(X=>({name:X.name,content:Buffer.from(X.contentBase64,"base64")}))).then(()=>y.info(`Compose attached ${h.files.length} file(s) to ${N}`)).catch(X=>y.warn(`Compose could not attach files to ${N}: ${X instanceof Error?X.message:X}`));let F=[];if(h.asEpic){for(let X of h.children){let ee=await g.jira.createIssue(m.project.jiraProjectKey,X.summary,X.description||"(no description)","Task",N);F.push(ee.key)}y.info(`Compose created epic ${N} with ${F.length} child ticket(s)`),v.sendChatCreateTicketResult(h.requestId,{ok:!0,issueKey:N,childKeys:F});return}h.triggerComment.trim()&&await g.jira.addTriggerComment(N,`${h.triggerComment.trim()}`+(!g.authored&&h.requestedBy?`
827
+ _Created via Allwright Compose`+(!g.authored&&h.requestedBy?` by ${h.requestedBy}`:"")+", drafted with the project agent._",{key:M}=await g.jira.createIssue(m.project.jiraProjectKey,h.summary,(h.description||"(no description)")+x,h.asEpic?"Epic":"Task");h.files.length&&await g.jira.addAttachments(M,h.files.map(X=>({name:X.name,content:Buffer.from(X.contentBase64,"base64")}))).then(()=>y.info(`Compose attached ${h.files.length} file(s) to ${M}`)).catch(X=>y.warn(`Compose could not attach files to ${M}: ${X instanceof Error?X.message:X}`));let q=[];if(h.asEpic){for(let X of h.children){let ee=await g.jira.createIssue(m.project.jiraProjectKey,X.summary,X.description||"(no description)","Task",M);q.push(ee.key)}y.info(`Compose created epic ${M} with ${q.length} child ticket(s)`),v.sendChatCreateTicketResult(h.requestId,{ok:!0,issueKey:M,childKeys:q});return}h.triggerComment.trim()&&await g.jira.addTriggerComment(M,`${h.triggerComment.trim()}`+(!g.authored&&h.requestedBy?`
811
828
 
812
- _(requested by ${h.requestedBy} via Allwright)_`:"")),y.info(`Compose created ${N}`+(h.requestedBy?` for ${h.requestedBy}`:"")+(h.triggerComment?` with trigger "${h.triggerComment.trim()}"`:"")),v.sendChatCreateTicketResult(h.requestId,{ok:!0,issueKey:N})}catch(g){v.sendChatCreateTicketResult(h.requestId,{ok:!1,issueKey:"",error:g instanceof Error?g.message:String(g)})}},onAuditStart:async h=>{let m=x(h.projectId);if(!m){v.sendAuditStartResult(h.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{y.info(`Audit (${h.role}) starting on ${m.project.repoName}`+(h.scope.kind!=="repo"?` scoped to ${h.scope.kind}:${h.scope.ref}`:""));let g=tt(n,m.project,"assist");if("error"in g){v.sendAuditStartResult(h.requestId,{ok:!1,error:g.error});return}let C=await Fr({projectId:h.projectId,repoPath:m.repoPath,role:h.role,scope:h.scope,model:h.model,agent:g,jira:s(m.project.repoName)});if(!C.ok){v.sendAuditStartResult(h.requestId,{ok:!1,error:C.error});return}v.sendAuditStartResult(h.requestId,{ok:!0,audit:C.audit})}catch(g){v.sendAuditStartResult(h.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onAuditList:async h=>{try{v.sendAuditListResult(h.requestId,{ok:!0,audits:Ku(h.projectId)})}catch(m){v.sendAuditListResult(h.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditGet:async h=>{try{let m=Hu(h.projectId,h.auditId);if(!m){v.sendAuditGetResult(h.requestId,{ok:!1,error:"audit not found on this runner"});return}v.sendAuditGetResult(h.requestId,{ok:!0,audit:m})}catch(m){v.sendAuditGetResult(h.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditReview:async h=>{try{let m=ta(h.projectId,h.auditId,{selected:h.selected,ticketed:h.ticketed,verdicts:h.verdicts,verdictBy:h.verdictBy});if(!m){v.sendAuditReviewResult(h.requestId,{ok:!1,error:"audit not found on this runner"});return}let g=x(h.projectId);if(g&&h.verdicts.length){let C=[];for(let N of h.verdicts){if(N.verdict==="valid"||m.lessonsWritten.includes(N.findingId))continue;let F=m.findings.find(X=>X.id===N.findingId);F&&(sa(g.repoPath,m.role,Xu(F,N.verdict,N.note,h.verdictBy)),C.push(N.findingId),y.info(`Lesson written (${m.role}): ${N.verdict} - ${F.title.slice(0,60)}`))}C.length&&(m=ta(h.projectId,h.auditId,{markLessonsWritten:C})??m)}v.sendAuditReviewResult(h.requestId,{ok:!0,audit:m})}catch(m){v.sendAuditReviewResult(h.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onKnowledgeList:async h=>{let m=x(h.projectId);if(!m){v.sendKnowledgeListResult(h.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{v.sendKnowledgeListResult(h.requestId,{ok:!0,files:ec(m.repoPath)})}catch(g){v.sendKnowledgeListResult(h.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onKnowledgeSave:async h=>{let m=x(h.projectId);if(!m){v.sendKnowledgeSaveResult(h.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{h.append?sa(m.repoPath,h.role,Qu(h.content,h.by),h.level):tc(m.repoPath,h.role,h.level,h.source,h.name,h.content),y.info(`Knowledge ${h.append?"taught":"saved"}: ${h.role}/${h.level}/${h.name}`),v.sendKnowledgeSaveResult(h.requestId,{ok:!0})}catch(g){v.sendKnowledgeSaveResult(h.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onEpicList:async h=>{let m=x(h.projectId);if(!m){v.sendEpicListResult(h.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{let g=s(m.project.repoName);if(h.epicKey){let C=await g.epicChildren(h.epicKey);v.sendEpicListResult(h.requestId,{ok:!0,children:C})}else{let C=await g.searchEpics(m.project.jiraProjectKey);v.sendEpicListResult(h.requestId,{ok:!0,epics:C})}}catch(g){v.sendEpicListResult(h.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onEpicSuggest:async h=>{let m=x(h.projectId);if(!m){v.sendEpicSuggestResult(h.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{let g=s(m.project.repoName),C=await g.epicChildren(h.epicKey),N=ju(C);if(!N.length){v.sendEpicSuggestResult(h.requestId,{ok:!1,error:`every child of ${h.epicKey} is already done or in an agent's hands - nothing to sequence`});return}if(N.length===1){v.sendEpicSuggestResult(h.requestId,{ok:!0,issueKey:N[0].key,reason:"It's the only pending ticket left in this epic.",considered:1});return}let F=await Promise.all(N.slice(0,12).map(async te=>{try{let se=await g.getIssue(te.key);return{...te,description:se.description}}catch{return{...te,description:""}}})),X=(await g.getIssue(h.epicKey).catch(()=>null))?.summary??"";y.info(`Epic suggest: weighing ${F.length} pending children of ${h.epicKey}`);let ee=tt(n,m.project,"assist");if("error"in ee){v.sendEpicSuggestResult(h.requestId,{ok:!1,error:ee.error});return}let H=await ee.adapter.run({repoPath:m.repoPath,prompt:Ou(h.epicKey,X,F),timeoutSeconds:150,bin:ee.bin,mode:"read_only",maxTurns:20,sessionId:(0,to.randomUUID)(),model:h.model||"claude-sonnet-5",onLog:()=>{}}),j=Nu(H.resultText,F.map(te=>te.key));if("error"in j){v.sendEpicSuggestResult(h.requestId,{ok:!1,error:j.error});return}y.info(`Epic suggest: ${h.epicKey} -> do ${j.issueKey} first`),v.sendEpicSuggestResult(h.requestId,{ok:!0,issueKey:j.issueKey,reason:j.reason,considered:F.length})}catch(g){v.sendEpicSuggestResult(h.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onTeamCreds:async h=>{try{let m=me()??n;if(m.github?.token&&!m.github.login)try{let{GitHubClient:C}=await Promise.resolve().then(()=>(nt(),Qn));m.github.login=await new C(m.github.token).whoami(),fe(m)}catch{}let g=Iu(m,h.emails);v.sendTeamCredsResult(h.requestId,{ok:!0,...g})}catch(m){v.sendTeamCredsResult(h.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupStatus:async h=>{try{let m=me()??n,{buildSetupReport:g}=await Promise.resolve().then(()=>(jh(),Ph)),C=await g(m,h.repoNames);v.sendSetupStatusResult(h.requestId,{ok:!0,...C})}catch(m){v.sendSetupStatusResult(h.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdGenerate:async h=>{try{let m=x(h.projectId);if(!m){v.sendSetupClaudeMdGenerateResult(h.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=h.kind==="deploy"?"DEPLOY.md":h.kind==="design"?"DESIGN.md":"CLAUDE.md";y.info(`Setup: drafting ${g} for ${m.project.repoName}`);let C="Explore this repository and draft the content of a CLAUDE.md file for its repo root - the memory file AI agents read before working on tickets here. Cover: what the product does (one paragraph), the tech stack, how the code is organized (key directories and what lives in them), exact commands to install dependencies / build / run tests, code conventions worth following, and gotchas a newcomer would trip over. Under 150 lines, factual, no marketing language, nothing you cannot verify from the code. Reply with ONLY the file content - no preamble, no fences around the whole thing.",N='Inspect this repository (deploy scripts, CI files, server configs, package scripts) and draft the content of a DEPLOY.md deploy contract for its repo root. An automation tool will follow it LITERALLY, so only write what you can verify from the repo. IMPORTANT: you are running ON the machine where deploys will execute - commands are plain local commands, no ssh wrapper, unless the repo clearly documents a different target machine. For each environment that VERIFIABLY exists: name, branch, exact deploy commands, secrets as $NAMES only (never values), pre/post checks (post-restart checks must wait and retry - services report active before their port binds). Where you cannot verify something (hosts, service names, ports), write it with a clear "VERIFY:" marker so the human fills it in during review, instead of guessing. State explicitly which environments do NOT exist. Reply with ONLY the file content - no preamble, no fences around the whole thing.',F=`Explore this repository's UI code and draft the content of a DESIGN.md file for its repo root - the design guidelines AI agents will follow for anything user-facing here. This is a SEED DRAFT: extract only what the code proves, and leave taste to the humans. Cover, from real evidence (tailwind/theme configs, design tokens, CSS, component libraries, existing screens): the color palette actually in use (names + hex), typography (families, the size scale), spacing and layout conventions, the component idiom (which library, how buttons/forms/cards are built, naming), dark mode, responsive breakpoints, and accessibility patterns already present. For everything code cannot prove - brand intent, tone of voice, look-and-feel references, what to never do - write a line starting with "VERIFY:" phrased as a question for the human to answer during review, instead of guessing. If the project has no UI at all, say exactly that in one line and stop. Under 120 lines, factual, no marketing language. Reply with ONLY the file content - no preamble, no fences around the whole thing.`,X=tt(n,m.project,"assist");if("error"in X){v.sendSetupClaudeMdGenerateResult(h.requestId,{ok:!1,content:"",error:X.error});return}let H=(await X.adapter.run({repoPath:m.repoPath,prompt:h.kind==="deploy"?N:h.kind==="design"?F:C,timeoutSeconds:240,bin:X.bin,mode:"read_only",maxTurns:40,sessionId:(0,to.randomUUID)(),onLog:()=>{}})).resultText.trim();if(!H){v.sendSetupClaudeMdGenerateResult(h.requestId,{ok:!1,error:"the agent returned no content - try again"});return}v.sendSetupClaudeMdGenerateResult(h.requestId,{ok:!0,content:H})}catch(m){v.sendSetupClaudeMdGenerateResult(h.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdSave:async h=>{try{let m=x(h.projectId);if(!m){v.sendSetupClaudeMdSaveResult(h.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=h.kind==="deploy"?"DEPLOY.md":h.kind==="design"?"DESIGN.md":"CLAUDE.md",C=await el({repoPath:m.repoPath,relPath:g,content:h.content,overwrite:h.overwrite,commitMessage:`Add ${g} (agent-drafted, human-approved via Allwright)`});C.ok&&y.info(`Setup: wrote human-approved ${g} to ${m.repoPath}`),v.sendSetupClaudeMdSaveResult(h.requestId,C)}catch(m){v.sendSetupClaudeMdSaveResult(h.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRepoDocSave:async h=>{try{let m=x(h.projectId);if(!m){v.sendRepoDocSaveResult(h.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=await el({repoPath:m.repoPath,relPath:h.relPath,content:h.content,overwrite:h.overwrite,commitMessage:`Add ${h.relPath.trim()} (written in Allwright Compose, human-approved)`});g.ok&&y.info(`Saved approved doc ${h.relPath} into ${m.repoPath}`),v.sendRepoDocSaveResult(h.requestId,g)}catch(m){v.sendRepoDocSaveResult(h.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditStats:h=>{try{v.sendAuditStatsResult(h.requestId,{ok:!0,byProject:Zu(h.projectIds,h.since)})}catch(m){v.sendAuditStatsResult(h.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRunnerUpdate:async h=>{if(!process.env.INVOCATION_ID){v.sendRunnerUpdateResult(h.requestId,{ok:!1,error:"this runner is not running as a systemd service, so it cannot restart itself after updating. On the machine run: allwright update && allwright stop && allwright start"});return}let m=()=>{y.info("Installing allwright@latest");let C=rs.default.dirname(process.execPath),N=ot.default.existsSync(rs.default.join(C,"npm"))?rs.default.join(C,"npm"):"npm";(0,Ut.execFile)(N,["install","-g","allwright@latest"],{timeout:18e4,env:{...process.env,PATH:`${C}:${process.env.PATH??""}`}},(F,X,ee)=>{if(F){v.sendRunnerUpdateResult(h.requestId,{ok:!1,error:`npm install failed: ${(ee||F.message).slice(0,300)} - on the machine run: allwright update && sudo systemctl restart allwright`});return}v.sendRunnerUpdateResult(h.requestId,{ok:!0,note:"updated - restarting now, back in a few seconds"}),y.info("Update installed; exiting so systemd restarts on the new version"),setTimeout(()=>process.exit(0),1500)})};if(p.idle){m();return}if(b){v.sendRunnerUpdateResult(h.requestId,{ok:!0,scheduled:!0,note:"an update is already scheduled and will install once the current work finishes"});return}let g=p.busyCount;v.sendRunnerUpdateResult(h.requestId,{ok:!0,scheduled:!0,note:`scheduled - ${g} run(s)/deploy(s) active right now. Nothing is refused meanwhile; the install runs automatically as soon as this machine goes idle.`}),y.info(`Update scheduled: waiting for ${g} active run(s)/deploy(s) to finish`),b=setInterval(()=>{p.idle&&(clearInterval(b),b=null,m())},5e3)},onTestFix:async h=>{let m=g=>v.sendTestFixResult(h.requestId,{ok:!1,note:g});try{let g=Kr(h.runId);if(!g){m("this runner no longer has that PR on file - it may have been decided already");return}let C=n.repos[g.repoName];if(!C){m(`no local checkout mapped for "${g.repoName}" on this machine`);return}let N=Te(n,g.repoName);if(!N){m("no GitHub token on this runner for that repo");return}let F=await new xe(N).getPullRequest(g.owner,g.repo,g.prNumber);if(!F){m("that pull request no longer exists on GitHub");return}if(F.merged||F.state==="closed"){m("that pull request is already merged or closed - there is nothing left to fix");return}let X=u.find(te=>te.repoName===g.repoName),ee=g.nextDecisionSeq??1e5,H=(te,se)=>{v.send({type:"run.log",runId:h.runId,seq:ee++,ts:new Date().toISOString(),level:te,message:se}),g.nextDecisionSeq=ee,rt(g)},j=await id({cfg:n,repoPath:C.path,branch:g.branch,baseBranch:F.baseRef||"main",issueKey:g.issueKey,agentId:X?.defaultAgent||Lt.DEFAULT_AGENT_ID,configDir:g.agentConfigDir,failedTests:h.failedTests,timeoutSeconds:900,onLog:H});j.ok&&j.headSha&&(g.headSha=j.headSha,rt(g),v.send({type:"run.status",runId:h.runId,status:"awaiting_approval",headSha:j.headSha,failedTests:j.remaining??[],...j.costUsd!==void 0?{costUsd:j.costUsd}:{},...j.inputTokens!==void 0?{inputTokens:j.inputTokens}:{},...j.outputTokens!==void 0?{outputTokens:j.outputTokens}:{}})),v.sendTestFixResult(h.requestId,j)}catch(g){m(g instanceof Error?g.message.slice(0,300):String(g))}},onResolveConflict:async h=>{let m=g=>v.sendResolveConflictResult(h.requestId,{ok:!1,note:g});try{let g=Kr(h.runId);if(!g){m("this runner no longer has that PR on file - it may have been decided already");return}let C=n.repos[g.repoName];if(!C){m(`no local checkout mapped for "${g.repoName}" on this machine`);return}let N=Te(n,g.repoName);if(!N){m("no GitHub token on this runner for that repo");return}let F=await new xe(N).getPullRequest(g.owner,g.repo,g.prNumber);if(!F){m("that pull request no longer exists on GitHub");return}if(!F.baseRef){m("GitHub did not report the PR's base branch, so there is nothing to merge in");return}let X=u.find(te=>te.repoName===g.repoName),ee=g.nextDecisionSeq??1e5,H=(te,se)=>{v.send({type:"run.log",runId:h.runId,seq:ee++,ts:new Date().toISOString(),level:te,message:se}),g.nextDecisionSeq=ee,rt(g)},j=await rd({cfg:n,repoPath:C.path,branch:g.branch,baseBranch:F.baseRef,issueKey:g.issueKey,agentId:X?.defaultAgent||Lt.DEFAULT_AGENT_ID,configDir:g.agentConfigDir,timeoutSeconds:900,onLog:H});j.ok&&j.headSha&&(g.headSha=j.headSha,g.conflictNotified=!1,rt(g),v.send({type:"run.pr.conflict",runId:h.runId,conflicted:!1}),v.send({type:"run.status",runId:h.runId,status:"awaiting_approval",headSha:j.headSha,...j.costUsd!==void 0?{costUsd:j.costUsd}:{},...j.inputTokens!==void 0?{inputTokens:j.inputTokens}:{},...j.outputTokens!==void 0?{outputTokens:j.outputTokens}:{}})),v.sendResolveConflictResult(h.requestId,j)}catch(g){m(g instanceof Error?g.message.slice(0,300):String(g))}},onAgentProfiles:h=>{try{let m=C=>{try{return ot.default.existsSync(C)&&ot.default.readdirSync(C).length>0}catch{return!1}},g=Object.entries(n.claudeProfiles).map(([C,N])=>({agent:"claude-code",name:C,loggedIn:m(N.configDir)}));v.sendAgentProfilesResult(h.requestId,{ok:!0,profiles:g,defaultLoggedIn:m(rs.default.join(nl.default.homedir(),".claude")),agentsWithoutProfiles:Lt.REGISTERED_AGENTS.filter(C=>!C.capabilities.loginProfiles).map(C=>C.id)})}catch(m){v.sendAgentProfilesResult(h.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onJiraUsers:async h=>{try{let m=await t.searchUsers(h.query);v.sendJiraUsersResult(h.requestId,{ok:!0,users:m})}catch(m){v.sendJiraUsersResult(h.requestId,{ok:!1,users:[],error:m instanceof Error?m.message:String(m)})}}});w.transport=v,p=new Oi(n,s,v);let Z=Object.values(Zr()).filter(h=>h.kind==="implement").map(h=>h.repoPath);Do(Object.values(n.repos).map(h=>h.path),Z).catch(()=>{}),v.start(),p.start();let M=()=>{y.info("shutting down"),b&&clearInterval(b),v.stop(),Fl(process.pid),xo(),process.exit(0)},L=!1,z=()=>{if(L){y.warn("second stop signal - exiting NOW; the interrupted run will be marked failed"),M();return}if(L=!0,p.stop(),p.idle){M();return}y.info(`stop requested - no new work will start; waiting for ${p.busyCount} active run(s)/deploy(s) to finish. Send the signal again to kill them immediately.`);let h=setInterval(()=>{p.idle&&(clearInterval(h),M())},3e3)};process.on("SIGINT",z),process.on("SIGTERM",z),process.on("SIGHUP",()=>{try{let h=ie();if(!h.jira)throw new Error("no Jira credentials in the reloaded config");for(let m of Object.keys(n))delete n[m];Object.assign(n,h),t=new Pe(h.jira),r.clear(),y.info("config reloaded live - new Jira tokens/repos/rules apply from the next poll. (Poll interval and control-plane URL still need a restart.)")}catch(h){y.error(`config reload failed - keeping the running config: ${h instanceof Error?h.message:String(h)}`)}})}ve.command("start").description("Start watching Jira. Runs in the background by default - close this terminal and it keeps going until you run `allwright stop`. Use --foreground to keep it attached (e.g. under systemd).").option("--foreground","run in this terminal instead of detaching to the background").action(async n=>{let e=ie();if(n.foreground){Hv(e);return}let t=In();if(t&&Rn(t)){y.info(`already running in the background (pid ${t}). Use \`allwright status\` or \`stop\`.`);return}let r=cs();if(r){y.info(`a runner is already running on this machine (pid ${r}) - most likely the systemd service. One machine runs ONE runner; nothing to do. (Service controls: sudo systemctl status|stop|restart allwright)`);return}let s=Ul(),i=(0,Ut.spawn)(process.execPath,[process.argv[1],"start","--foreground"],{detached:!0,stdio:["ignore",s,s]});i.unref(),ql(i.pid),y.info(`Runner started in the background (pid ${i.pid}).`),y.info(`Logs: ${Xs()}`),y.info("It will keep polling Jira until you run `allwright stop` - closing this terminal is fine.")});ve.command("stop").description("Stop the background runner started by `start`. Graceful by default: it stops taking new work and exits once active runs and deploys finish - safe to use while customers' tickets are running.").option("--force","kill immediately - anything executing is interrupted and marked failed").action(n=>{let e=In();if(!e||!Rn(e)){y.info("no background runner is running"),e&&ot.default.rmSync(Rr(),{force:!0});return}if(n.force){process.kill(e,"SIGKILL"),ot.default.rmSync(Rr(),{force:!0}),y.info(`killed (pid ${e}) - any interrupted run will show as failed on the dashboard`);return}process.kill(e,"SIGTERM"),y.info(`stop signal sent (pid ${e}) - it stops polling now and exits once active work finishes (watch \`allwright status\`). Use --force to kill immediately.`)});ve.command("status").description("Check whether the background runner is running").action(()=>{let n=In();n&&Rn(n)?y.info(`running in the background (pid ${n})`):y.info("not running")});ve.parseAsync().catch(n=>{y.error(n instanceof Error?n.message:String(n)),process.exit(1)});
829
+ _(requested by ${h.requestedBy} via Allwright)_`:"")),y.info(`Compose created ${M}`+(h.requestedBy?` for ${h.requestedBy}`:"")+(h.triggerComment?` with trigger "${h.triggerComment.trim()}"`:"")),v.sendChatCreateTicketResult(h.requestId,{ok:!0,issueKey:M})}catch(g){v.sendChatCreateTicketResult(h.requestId,{ok:!1,issueKey:"",error:g instanceof Error?g.message:String(g)})}},onAuditStart:async h=>{let m=C(h.projectId);if(!m){v.sendAuditStartResult(h.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{y.info(`Audit (${h.role}) starting on ${m.project.repoName}`+(h.scope.kind!=="repo"?` scoped to ${h.scope.kind}:${h.scope.ref}`:""));let g=st(n,m.project,"assist");if("error"in g){v.sendAuditStartResult(h.requestId,{ok:!1,error:g.error});return}let x=await Gr({projectId:h.projectId,repoPath:m.repoPath,role:h.role,scope:h.scope,model:h.model,agent:g,jira:s(m.project.repoName)});if(!x.ok){v.sendAuditStartResult(h.requestId,{ok:!1,error:x.error});return}v.sendAuditStartResult(h.requestId,{ok:!0,audit:x.audit})}catch(g){v.sendAuditStartResult(h.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onAuditList:async h=>{try{v.sendAuditListResult(h.requestId,{ok:!0,audits:Yu(h.projectId)})}catch(m){v.sendAuditListResult(h.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditGet:async h=>{try{let m=ec(h.projectId,h.auditId);if(!m){v.sendAuditGetResult(h.requestId,{ok:!1,error:"audit not found on this runner"});return}v.sendAuditGetResult(h.requestId,{ok:!0,audit:m})}catch(m){v.sendAuditGetResult(h.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditReview:async h=>{try{let m=oa(h.projectId,h.auditId,{selected:h.selected,ticketed:h.ticketed,verdicts:h.verdicts,verdictBy:h.verdictBy});if(!m){v.sendAuditReviewResult(h.requestId,{ok:!1,error:"audit not found on this runner"});return}let g=C(h.projectId);if(g&&h.verdicts.length){let x=[];for(let M of h.verdicts){if(M.verdict==="valid"||m.lessonsWritten.includes(M.findingId))continue;let q=m.findings.find(X=>X.id===M.findingId);q&&(da(g.repoPath,m.role,ac(q,M.verdict,M.note,h.verdictBy)),x.push(M.findingId),y.info(`Lesson written (${m.role}): ${M.verdict} - ${q.title.slice(0,60)}`))}x.length&&(m=oa(h.projectId,h.auditId,{markLessonsWritten:x})??m)}v.sendAuditReviewResult(h.requestId,{ok:!0,audit:m})}catch(m){v.sendAuditReviewResult(h.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onKnowledgeList:async h=>{let m=C(h.projectId);if(!m){v.sendKnowledgeListResult(h.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{v.sendKnowledgeListResult(h.requestId,{ok:!0,files:uc(m.repoPath)})}catch(g){v.sendKnowledgeListResult(h.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onKnowledgeSave:async h=>{let m=C(h.projectId);if(!m){v.sendKnowledgeSaveResult(h.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{h.append?da(m.repoPath,h.role,lc(h.content,h.by),h.level):cc(m.repoPath,h.role,h.level,h.source,h.name,h.content),y.info(`Knowledge ${h.append?"taught":"saved"}: ${h.role}/${h.level}/${h.name}`),v.sendKnowledgeSaveResult(h.requestId,{ok:!0})}catch(g){v.sendKnowledgeSaveResult(h.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onEpicList:async h=>{let m=C(h.projectId);if(!m){v.sendEpicListResult(h.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{let g=s(m.project.repoName);if(h.epicKey){let x=await g.epicChildren(h.epicKey);v.sendEpicListResult(h.requestId,{ok:!0,children:x})}else{let x=await g.searchEpics(m.project.jiraProjectKey);v.sendEpicListResult(h.requestId,{ok:!0,epics:x})}}catch(g){v.sendEpicListResult(h.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onEpicSuggest:async h=>{let m=C(h.projectId);if(!m){v.sendEpicSuggestResult(h.requestId,{ok:!1,error:"this runner has no local checkout mapped for that project"});return}try{let g=s(m.project.repoName),x=await g.epicChildren(h.epicKey),M=Uu(x);if(!M.length){v.sendEpicSuggestResult(h.requestId,{ok:!1,error:`every child of ${h.epicKey} is already done or in an agent's hands - nothing to sequence`});return}if(M.length===1){v.sendEpicSuggestResult(h.requestId,{ok:!0,issueKey:M[0].key,reason:"It's the only pending ticket left in this epic.",considered:1});return}let q=await Promise.all(M.slice(0,12).map(async te=>{try{let ne=await g.getIssue(te.key);return{...te,description:ne.description}}catch{return{...te,description:""}}})),X=(await g.getIssue(h.epicKey).catch(()=>null))?.summary??"";y.info(`Epic suggest: weighing ${q.length} pending children of ${h.epicKey}`);let ee=st(n,m.project,"assist");if("error"in ee){v.sendEpicSuggestResult(h.requestId,{ok:!1,error:ee.error});return}let H=await ee.adapter.run({repoPath:m.repoPath,prompt:qu(h.epicKey,X,q),timeoutSeconds:150,bin:ee.bin,mode:"read_only",maxTurns:20,sessionId:(0,io.randomUUID)(),model:h.model||"claude-sonnet-5",onLog:()=>{}}),$=Fu(H.resultText,q.map(te=>te.key));if("error"in $){v.sendEpicSuggestResult(h.requestId,{ok:!1,error:$.error});return}y.info(`Epic suggest: ${h.epicKey} -> do ${$.issueKey} first`),v.sendEpicSuggestResult(h.requestId,{ok:!0,issueKey:$.issueKey,reason:$.reason,considered:q.length})}catch(g){v.sendEpicSuggestResult(h.requestId,{ok:!1,error:g instanceof Error?g.message:String(g)})}},onTeamCreds:async h=>{try{let m=pe()??n;if(m.github?.token&&!m.github.login)try{let{GitHubClient:x}=await Promise.resolve().then(()=>(it(),nr));m.github.login=await new x(m.github.token).whoami(),fe(m)}catch{}let g=Ou(m,h.emails);v.sendTeamCredsResult(h.requestId,{ok:!0,...g})}catch(m){v.sendTeamCredsResult(h.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupStatus:async h=>{try{let m=pe()??n,{buildSetupReport:g}=await Promise.resolve().then(()=>(Bh(),Fh)),x=await g(m,h.repoNames);v.sendSetupStatusResult(h.requestId,{ok:!0,...x})}catch(m){v.sendSetupStatusResult(h.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdGenerate:async h=>{try{let m=C(h.projectId);if(!m){v.sendSetupClaudeMdGenerateResult(h.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=h.kind==="deploy"?"DEPLOY.md":h.kind==="design"?"DESIGN.md":"CLAUDE.md";y.info(`Setup: drafting ${g} for ${m.project.repoName}`);let x="Explore this repository and draft the content of a CLAUDE.md file for its repo root - the memory file AI agents read before working on tickets here. Cover: what the product does (one paragraph), the tech stack, how the code is organized (key directories and what lives in them), exact commands to install dependencies / build / run tests, code conventions worth following, and gotchas a newcomer would trip over. Under 150 lines, factual, no marketing language, nothing you cannot verify from the code. Reply with ONLY the file content - no preamble, no fences around the whole thing.",M='Inspect this repository (deploy scripts, CI files, server configs, package scripts) and draft the content of a DEPLOY.md deploy contract for its repo root. An automation tool will follow it LITERALLY, so only write what you can verify from the repo. IMPORTANT: you are running ON the machine where deploys will execute - commands are plain local commands, no ssh wrapper, unless the repo clearly documents a different target machine. For each environment that VERIFIABLY exists: name, branch, exact deploy commands, secrets as $NAMES only (never values), pre/post checks (post-restart checks must wait and retry - services report active before their port binds). Where you cannot verify something (hosts, service names, ports), write it with a clear "VERIFY:" marker so the human fills it in during review, instead of guessing. State explicitly which environments do NOT exist. Reply with ONLY the file content - no preamble, no fences around the whole thing.',q=`Explore this repository's UI code and draft the content of a DESIGN.md file for its repo root - the design guidelines AI agents will follow for anything user-facing here. This is a SEED DRAFT: extract only what the code proves, and leave taste to the humans. Cover, from real evidence (tailwind/theme configs, design tokens, CSS, component libraries, existing screens): the color palette actually in use (names + hex), typography (families, the size scale), spacing and layout conventions, the component idiom (which library, how buttons/forms/cards are built, naming), dark mode, responsive breakpoints, and accessibility patterns already present. For everything code cannot prove - brand intent, tone of voice, look-and-feel references, what to never do - write a line starting with "VERIFY:" phrased as a question for the human to answer during review, instead of guessing. If the project has no UI at all, say exactly that in one line and stop. Under 120 lines, factual, no marketing language. Reply with ONLY the file content - no preamble, no fences around the whole thing.`,X=st(n,m.project,"assist");if("error"in X){v.sendSetupClaudeMdGenerateResult(h.requestId,{ok:!1,content:"",error:X.error});return}let H=(await X.adapter.run({repoPath:m.repoPath,prompt:h.kind==="deploy"?M:h.kind==="design"?q:x,timeoutSeconds:240,bin:X.bin,mode:"read_only",maxTurns:40,sessionId:(0,io.randomUUID)(),onLog:()=>{}})).resultText.trim();if(!H){v.sendSetupClaudeMdGenerateResult(h.requestId,{ok:!1,error:"the agent returned no content - try again"});return}v.sendSetupClaudeMdGenerateResult(h.requestId,{ok:!0,content:H})}catch(m){v.sendSetupClaudeMdGenerateResult(h.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onSetupClaudeMdSave:async h=>{try{let m=C(h.projectId);if(!m){v.sendSetupClaudeMdSaveResult(h.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=h.kind==="deploy"?"DEPLOY.md":h.kind==="design"?"DESIGN.md":"CLAUDE.md",x=await al({repoPath:m.repoPath,relPath:g,content:h.content,overwrite:h.overwrite,commitMessage:`Add ${g} (agent-drafted, human-approved via Allwright)`});x.ok&&y.info(`Setup: wrote human-approved ${g} to ${m.repoPath}`),v.sendSetupClaudeMdSaveResult(h.requestId,x)}catch(m){v.sendSetupClaudeMdSaveResult(h.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRepoDocSave:async h=>{try{let m=C(h.projectId);if(!m){v.sendRepoDocSaveResult(h.requestId,{ok:!1,error:"no local checkout mapped for that project"});return}let g=await al({repoPath:m.repoPath,relPath:h.relPath,content:h.content,overwrite:h.overwrite,commitMessage:`Add ${h.relPath.trim()} (written in Allwright Compose, human-approved)`});g.ok&&y.info(`Saved approved doc ${h.relPath} into ${m.repoPath}`),v.sendRepoDocSaveResult(h.requestId,g)}catch(m){v.sendRepoDocSaveResult(h.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onAuditStats:h=>{try{v.sendAuditStatsResult(h.requestId,{ok:!0,byProject:Xu(h.projectIds,h.since)})}catch(m){v.sendAuditStatsResult(h.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onRunnerUpdate:async h=>{if(!process.env.INVOCATION_ID){v.sendRunnerUpdateResult(h.requestId,{ok:!1,error:"this runner is not running as a systemd service, so it cannot restart itself after updating. On the machine run: allwright update && allwright stop && allwright start"});return}let m=()=>{y.info("Installing allwright@latest");let x=as.default.dirname(process.execPath),M=ut.default.existsSync(as.default.join(x,"npm"))?as.default.join(x,"npm"):"npm";(0,Kt.execFile)(M,["install","-g","allwright@latest"],{timeout:18e4,env:{...process.env,PATH:`${x}:${process.env.PATH??""}`}},(q,X,ee)=>{if(q){v.sendRunnerUpdateResult(h.requestId,{ok:!1,error:`npm install failed: ${(ee||q.message).slice(0,300)} - on the machine run: allwright update && sudo systemctl restart allwright`});return}v.sendRunnerUpdateResult(h.requestId,{ok:!0,note:"updated - restarting now, back in a few seconds"}),y.info("Update installed; exiting so systemd restarts on the new version"),setTimeout(()=>process.exit(0),1500)})};if(p.idle){m();return}if(b){v.sendRunnerUpdateResult(h.requestId,{ok:!0,scheduled:!0,note:"an update is already scheduled and will install once the current work finishes"});return}let g=p.busyCount;v.sendRunnerUpdateResult(h.requestId,{ok:!0,scheduled:!0,note:`scheduled - ${g} run(s)/deploy(s) active right now. Nothing is refused meanwhile; the install runs automatically as soon as this machine goes idle.`}),y.info(`Update scheduled: waiting for ${g} active run(s)/deploy(s) to finish`),b=setInterval(()=>{p.idle&&(clearInterval(b),b=null,m())},5e3)},onTestFix:async h=>{let m=g=>v.sendTestFixResult(h.requestId,{ok:!1,note:g});try{let g=Vr(h.runId);if(!g){m("this runner no longer has that PR on file - it may have been decided already");return}let x=n.repos[g.repoName];if(!x){m(`no local checkout mapped for "${g.repoName}" on this machine`);return}let M=Te(n,g.repoName);if(!M){m("no GitHub token on this runner for that repo");return}let q=await new xe(M).getPullRequest(g.owner,g.repo,g.prNumber);if(!q){m("that pull request no longer exists on GitHub");return}if(q.merged||q.state==="closed"){m("that pull request is already merged or closed - there is nothing left to fix");return}let X=u.find(te=>te.repoName===g.repoName),ee=g.nextDecisionSeq??1e5,H=(te,ne)=>{v.send({type:"run.log",runId:h.runId,seq:ee++,ts:new Date().toISOString(),level:te,message:ne}),g.nextDecisionSeq=ee,ot(g)},$=await md({cfg:n,repoPath:x.path,branch:g.branch,baseBranch:q.baseRef||"main",issueKey:g.issueKey,agentId:X?.defaultAgent||Bt.DEFAULT_AGENT_ID,configDir:g.agentConfigDir,failedTests:h.failedTests,timeoutSeconds:900,onLog:H});$.ok&&$.headSha&&(g.headSha=$.headSha,ot(g),v.send({type:"run.status",runId:h.runId,status:"awaiting_approval",headSha:$.headSha,failedTests:$.remaining??[],...$.testsPassed!==void 0?{testsPassed:$.testsPassed}:{},...$.testsTotal!==void 0?{testsTotal:$.testsTotal}:{},...$.costUsd!==void 0?{costUsd:$.costUsd}:{},...$.inputTokens!==void 0?{inputTokens:$.inputTokens}:{},...$.outputTokens!==void 0?{outputTokens:$.outputTokens}:{}})),rt(x.path,{issueKey:g.issueKey,runId:h.runId,title:$.ok?$.headSha?($.remaining??[]).length?"dashboard test fix pushed, some commands still failing":"tests fixed from the dashboard":"dashboard test fix: agent changed nothing":"dashboard test fix failed",detail:$.note.slice(0,500)}),v.sendTestFixResult(h.requestId,$)}catch(g){m(g instanceof Error?g.message.slice(0,300):String(g))}},onResolveConflict:async h=>{let m=g=>v.sendResolveConflictResult(h.requestId,{ok:!1,note:g});try{let g=Vr(h.runId);if(!g){m("this runner no longer has that PR on file - it may have been decided already");return}let x=n.repos[g.repoName];if(!x){m(`no local checkout mapped for "${g.repoName}" on this machine`);return}let M=Te(n,g.repoName);if(!M){m("no GitHub token on this runner for that repo");return}let q=await new xe(M).getPullRequest(g.owner,g.repo,g.prNumber);if(!q){m("that pull request no longer exists on GitHub");return}if(!q.baseRef){m("GitHub did not report the PR's base branch, so there is nothing to merge in");return}let X=u.find(te=>te.repoName===g.repoName),ee=g.nextDecisionSeq??1e5,H=(te,ne)=>{v.send({type:"run.log",runId:h.runId,seq:ee++,ts:new Date().toISOString(),level:te,message:ne}),g.nextDecisionSeq=ee,ot(g)},$=await fd({cfg:n,repoPath:x.path,branch:g.branch,baseBranch:q.baseRef,issueKey:g.issueKey,agentId:X?.defaultAgent||Bt.DEFAULT_AGENT_ID,configDir:g.agentConfigDir,timeoutSeconds:900,onLog:H});$.ok&&$.headSha&&(g.headSha=$.headSha,g.conflictNotified=!1,ot(g),v.send({type:"run.pr.conflict",runId:h.runId,conflicted:!1}),v.send({type:"run.status",runId:h.runId,status:"awaiting_approval",headSha:$.headSha,...$.costUsd!==void 0?{costUsd:$.costUsd}:{},...$.inputTokens!==void 0?{inputTokens:$.inputTokens}:{},...$.outputTokens!==void 0?{outputTokens:$.outputTokens}:{}})),v.sendResolveConflictResult(h.requestId,$)}catch(g){m(g instanceof Error?g.message.slice(0,300):String(g))}},onAgentProfiles:h=>{try{let m=x=>{try{return ut.default.existsSync(x)&&ut.default.readdirSync(x).length>0}catch{return!1}},g=Object.entries(n.claudeProfiles).map(([x,M])=>({agent:"claude-code",name:x,loggedIn:m(M.configDir)}));v.sendAgentProfilesResult(h.requestId,{ok:!0,profiles:g,defaultLoggedIn:m(as.default.join(ul.default.homedir(),".claude")),agentsWithoutProfiles:Bt.REGISTERED_AGENTS.filter(x=>!x.capabilities.loginProfiles).map(x=>x.id)})}catch(m){v.sendAgentProfilesResult(h.requestId,{ok:!1,error:m instanceof Error?m.message:String(m)})}},onJiraUsers:async h=>{try{let m=await t.searchUsers(h.query);v.sendJiraUsersResult(h.requestId,{ok:!0,users:m})}catch(m){v.sendJiraUsersResult(h.requestId,{ok:!1,users:[],error:m instanceof Error?m.message:String(m)})}}});w.transport=v,p=new Di(n,s,v);let B=Object.values(Wr()).filter(h=>h.kind==="implement").map(h=>h.repoPath);Bo(Object.values(n.repos).map(h=>h.path),B).catch(()=>{}),v.start(),p.start();let N=()=>{y.info("shutting down"),b&&clearInterval(b),v.stop(),Wl(process.pid),Ao(),process.exit(0)},D=!1,K=()=>{if(D){y.warn("second stop signal - exiting NOW; the interrupted run will be marked failed"),N();return}if(D=!0,p.stop(),p.idle){N();return}y.info(`stop requested - no new work will start; waiting for ${p.busyCount} active run(s)/deploy(s) to finish. Send the signal again to kill them immediately.`);let h=setInterval(()=>{p.idle&&(clearInterval(h),N())},3e3)};process.on("SIGINT",K),process.on("SIGTERM",K),process.on("SIGHUP",()=>{try{let h=ie();if(!h.jira)throw new Error("no Jira credentials in the reloaded config");for(let m of Object.keys(n))delete n[m];Object.assign(n,h),t=new Ce(h.jira),r.clear(),y.info("config reloaded live - new Jira tokens/repos/rules apply from the next poll. (Poll interval and control-plane URL still need a restart.)")}catch(h){y.error(`config reload failed - keeping the running config: ${h instanceof Error?h.message:String(h)}`)}})}ye.command("start").description("Start watching Jira. Runs in the background by default - close this terminal and it keeps going until you run `allwright stop`. Use --foreground to keep it attached (e.g. under systemd).").option("--foreground","run in this terminal instead of detaching to the background").action(async n=>{let e=ie();if(n.foreground){ab(e);return}let t=An();if(t&&$n(t)){y.info(`already running in the background (pid ${t}). Use \`allwright status\` or \`stop\`.`);return}let r=ms();if(r){y.info(`a runner is already running on this machine (pid ${r}) - most likely the systemd service. One machine runs ONE runner; nothing to do. (Service controls: sudo systemctl status|stop|restart allwright)`);return}let s=Hl(),i=(0,Kt.spawn)(process.execPath,[process.argv[1],"start","--foreground"],{detached:!0,stdio:["ignore",s,s]});i.unref(),Vl(i.pid),y.info(`Runner started in the background (pid ${i.pid}).`),y.info(`Logs: ${ni()}`),y.info("It will keep polling Jira until you run `allwright stop` - closing this terminal is fine.")});ye.command("stop").description("Stop the background runner started by `start`. Graceful by default: it stops taking new work and exits once active runs and deploys finish - safe to use while customers' tickets are running.").option("--force","kill immediately - anything executing is interrupted and marked failed").action(n=>{let e=An();if(!e||!$n(e)){y.info("no background runner is running"),e&&ut.default.rmSync(Pr(),{force:!0});return}if(n.force){process.kill(e,"SIGKILL"),ut.default.rmSync(Pr(),{force:!0}),y.info(`killed (pid ${e}) - any interrupted run will show as failed on the dashboard`);return}process.kill(e,"SIGTERM"),y.info(`stop signal sent (pid ${e}) - it stops polling now and exits once active work finishes (watch \`allwright status\`). Use --force to kill immediately.`)});ye.command("status").description("Check whether the background runner is running").action(()=>{let n=An();n&&$n(n)?y.info(`running in the background (pid ${n})`):y.info("not running")});ye.parseAsync().catch(n=>{y.error(n instanceof Error?n.message:String(n)),process.exit(1)});